cli-setu 0.3.2 → 0.3.3
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/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/pair.js +162 -131
- package/src/providerProtocol.js +155 -0
- package/src/reconnect.js +94 -0
- package/src/supervisor.js +2228 -1369
|
@@ -1,27 +1,28 @@
|
|
|
1
|
-
// One place supervisor.js asks "which adapter for this CLI name" -
|
|
2
|
-
// unrecognized names fall through to the generic PTY-only adapter
|
|
3
|
-
// (see generic.js) rather than erroring out, since "not yet integrated"
|
|
4
|
-
// should never mean "can't run this CLI through the bridge at all."
|
|
5
|
-
const claude = require('./claude');
|
|
6
|
-
const codex = require('./codex');
|
|
7
|
-
const shell = require('./shell');
|
|
8
|
-
const makeGeneric = require('./generic');
|
|
9
|
-
|
|
10
|
-
const KNOWN_ADAPTERS = {
|
|
11
|
-
claude,
|
|
12
|
-
codex,
|
|
13
|
-
shell,
|
|
14
|
-
};
|
|
15
|
-
|
|
16
|
-
// Real product decision (confirmed directly by the PM):
|
|
17
|
-
// no --cli flag bridges the user's own plain terminal, not Claude
|
|
18
|
-
// specifically - the user decides what to run once it's open.
|
|
19
|
-
// to 'claude' here silently assumed every user wanted an AI
|
|
20
|
-
// the instant they typed `cli-setu`, which isn't
|
|
21
|
-
// intent (a genuine remote terminal, not an
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
1
|
+
// One place supervisor.js asks "which adapter for this CLI name" -
|
|
2
|
+
// unrecognized names fall through to the generic PTY-only adapter
|
|
3
|
+
// (see generic.js) rather than erroring out, since "not yet integrated"
|
|
4
|
+
// should never mean "can't run this CLI through the bridge at all."
|
|
5
|
+
const claude = require('./claude');
|
|
6
|
+
const codex = require('./codex');
|
|
7
|
+
const shell = require('./shell');
|
|
8
|
+
const makeGeneric = require('./generic');
|
|
9
|
+
|
|
10
|
+
const KNOWN_ADAPTERS = {
|
|
11
|
+
claude,
|
|
12
|
+
codex,
|
|
13
|
+
shell,
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
// Real product decision (confirmed directly by the PM): `cli-setu session`
|
|
17
|
+
// with no --cli flag bridges the user's own plain terminal, not Claude
|
|
18
|
+
// Code specifically - the user decides what to run once it's open.
|
|
19
|
+
// Defaulting to 'claude' here silently assumed every user wanted an AI
|
|
20
|
+
// CLI running the instant they typed `cli-setu session`, which isn't
|
|
21
|
+
// actually the product's real intent (a genuine remote terminal, not an
|
|
22
|
+
// AI-agent-only bridge).
|
|
23
|
+
function getAdapter(cliName) {
|
|
24
|
+
const normalized = (cliName || 'shell').toLowerCase();
|
|
25
|
+
return KNOWN_ADAPTERS[normalized] || makeGeneric(cliName);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
module.exports = { getAdapter, KNOWN_ADAPTERS };
|
|
@@ -1,88 +1,96 @@
|
|
|
1
|
-
// The default adapter when a user runs plain `cli-setu` with no --cli flag at
|
|
2
|
-
// all - a real gap in the earlier design: `cli-setu` (bare) always launched
|
|
3
|
-
// Claude Code specifically, silently assuming that's what every user
|
|
4
|
-
// wants. The actual product intent (confirmed directly by the PM) is
|
|
5
|
-
// simpler and more honest: `cli-setu` bridges the user's OWN real terminal to
|
|
6
|
-
// their phone - a genuine remote shell, nothing AI-specific - and the
|
|
7
|
-
// user decides what to run inside it once it's open (`claude`, `codex`,
|
|
8
|
-
// `npm install`, `git status`, anything). Running an AI CLI inside this
|
|
9
|
-
// bridged shell still gets real approval detection IF that CLI has its
|
|
10
|
-
// own adapter (this adapter itself has none - see approvals: null below)
|
|
11
|
-
// - detection is about what's actually running inside the PTY moment to
|
|
12
|
-
// moment, not about which adapter spawned the shell around it.
|
|
13
|
-
const os = require('os');
|
|
14
|
-
const fs = require('fs');
|
|
15
|
-
|
|
16
|
-
// Real bug found by testing (PM report, multiple real macOS users hit
|
|
17
|
-
// this): node-pty's spawn() throws synchronously with an opaque native
|
|
18
|
-
// "posix_spawnp failed" error - and nothing ever caught it - whenever
|
|
19
|
-
// $SHELL points at a path that doesn't actually exist or isn't
|
|
20
|
-
// executable anymore (a shell installed via Homebrew/nvm/asdf that was
|
|
21
|
-
// later upgraded, moved, or uninstalled; a stale value left over from a
|
|
22
|
-
// deleted user profile; a corporate-managed Mac with $SHELL pointing at
|
|
23
|
-
// something sandboxed). This crashed the ENTIRE supervisor process on
|
|
24
|
-
// startup with no actionable message - "not able to start any session"
|
|
25
|
-
// was the only thing the user could see. Validating the path exists AND
|
|
26
|
-
// is actually a regular file before trusting it, falling back through a
|
|
27
|
-
// short list of real, almost-always-present POSIX shells, means a
|
|
28
|
-
// broken $SHELL no longer takes down the whole bridge - it just quietly
|
|
29
|
-
// uses a working shell instead, same as if $SHELL had never been set at
|
|
30
|
-
// all.
|
|
31
|
-
function isExecutableFile(path) {
|
|
32
|
-
try {
|
|
33
|
-
return fs.statSync(path).isFile();
|
|
34
|
-
} catch {
|
|
35
|
-
return false;
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
function resolveShellCommand() {
|
|
40
|
-
if (process.platform === 'win32') {
|
|
41
|
-
// Real users' machines vary here - PowerShell is the modern Windows
|
|
42
|
-
// default (present on every Windows 10/11 install), but COMSPEC
|
|
43
|
-
// (usually cmd.exe) is what Windows itself considers "the" shell for
|
|
44
|
-
// a process that doesn't ask for anything more specific. Preferring
|
|
45
|
-
// PowerShell when it's genuinely on PATH, falling back to COMSPEC
|
|
46
|
-
// (or a bare cmd.exe) otherwise, covers both cases without assuming
|
|
47
|
-
// one specific install layout the way a hardcoded path would.
|
|
48
|
-
return 'powershell.exe';
|
|
49
|
-
}
|
|
50
|
-
// SHELL is the real, standard POSIX convention for "the user's own
|
|
51
|
-
// configured shell" (bash, zsh, fish, ...) - respecting it here means
|
|
52
|
-
// this bridges whatever shell the user already actually uses day to
|
|
53
|
-
// day, not a hardcoded assumption that might not even be installed.
|
|
54
|
-
// Only trusted if it actually resolves to a real file on disk right
|
|
55
|
-
// now - see isExecutableFile's own comment for why this check exists.
|
|
56
|
-
if (process.env.SHELL && isExecutableFile(process.env.SHELL)) {
|
|
57
|
-
return process.env.SHELL;
|
|
58
|
-
}
|
|
59
|
-
for (const candidate of ['/bin/zsh', '/bin/bash', '/bin/sh']) {
|
|
60
|
-
if (isExecutableFile(candidate)) return candidate;
|
|
61
|
-
}
|
|
62
|
-
// Every one of those is a standard part of macOS/Linux and should
|
|
63
|
-
// never actually be missing - this is a last-resort value, not an
|
|
64
|
-
// expected path, kept only so spawn() still gets SOME string instead
|
|
65
|
-
// of undefined.
|
|
66
|
-
return '/bin/sh';
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
module.exports = {
|
|
70
|
-
id: 'shell',
|
|
71
|
-
displayName: os.platform() === 'win32' ? 'PowerShell' : 'Shell',
|
|
72
|
-
icon: { name: 'terminal-outline', color: '#7C8B99' },
|
|
73
|
-
spawn: {
|
|
74
|
-
command: resolveShellCommand(),
|
|
75
|
-
args: () => [],
|
|
76
|
-
},
|
|
77
|
-
// No structured Confirmations card - a plain shell has no permission-
|
|
78
|
-
// prompt concept of its own to detect. If the user launches an AI CLI
|
|
79
|
-
// INSIDE this shell, that CLI's own real adapter (claude.js/codex.js)
|
|
80
|
-
// still isn't active here, since supervisor.js picks exactly one
|
|
81
|
-
// adapter per process/session at startup - a real user wanting
|
|
82
|
-
// structured approvals for a specific CLI should run `cli-setu
|
|
83
|
-
// claude` (or codex) directly, same as always. This adapter is
|
|
84
|
-
// specifically for "just give me my terminal, I'll decide what to run."
|
|
85
|
-
approvals: null,
|
|
86
|
-
usage: null,
|
|
87
|
-
|
|
88
|
-
|
|
1
|
+
// The default adapter when a user runs plain `cli-setu` with no --cli flag at
|
|
2
|
+
// all - a real gap in the earlier design: `cli-setu` (bare) always launched
|
|
3
|
+
// Claude Code specifically, silently assuming that's what every user
|
|
4
|
+
// wants. The actual product intent (confirmed directly by the PM) is
|
|
5
|
+
// simpler and more honest: `cli-setu` bridges the user's OWN real terminal to
|
|
6
|
+
// their phone - a genuine remote shell, nothing AI-specific - and the
|
|
7
|
+
// user decides what to run inside it once it's open (`claude`, `codex`,
|
|
8
|
+
// `npm install`, `git status`, anything). Running an AI CLI inside this
|
|
9
|
+
// bridged shell still gets real approval detection IF that CLI has its
|
|
10
|
+
// own adapter (this adapter itself has none - see approvals: null below)
|
|
11
|
+
// - detection is about what's actually running inside the PTY moment to
|
|
12
|
+
// moment, not about which adapter spawned the shell around it.
|
|
13
|
+
const os = require('os');
|
|
14
|
+
const fs = require('fs');
|
|
15
|
+
|
|
16
|
+
// Real bug found by testing (PM report, multiple real macOS users hit
|
|
17
|
+
// this): node-pty's spawn() throws synchronously with an opaque native
|
|
18
|
+
// "posix_spawnp failed" error - and nothing ever caught it - whenever
|
|
19
|
+
// $SHELL points at a path that doesn't actually exist or isn't
|
|
20
|
+
// executable anymore (a shell installed via Homebrew/nvm/asdf that was
|
|
21
|
+
// later upgraded, moved, or uninstalled; a stale value left over from a
|
|
22
|
+
// deleted user profile; a corporate-managed Mac with $SHELL pointing at
|
|
23
|
+
// something sandboxed). This crashed the ENTIRE supervisor process on
|
|
24
|
+
// startup with no actionable message - "not able to start any session"
|
|
25
|
+
// was the only thing the user could see. Validating the path exists AND
|
|
26
|
+
// is actually a regular file before trusting it, falling back through a
|
|
27
|
+
// short list of real, almost-always-present POSIX shells, means a
|
|
28
|
+
// broken $SHELL no longer takes down the whole bridge - it just quietly
|
|
29
|
+
// uses a working shell instead, same as if $SHELL had never been set at
|
|
30
|
+
// all.
|
|
31
|
+
function isExecutableFile(path) {
|
|
32
|
+
try {
|
|
33
|
+
return fs.statSync(path).isFile();
|
|
34
|
+
} catch {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function resolveShellCommand() {
|
|
40
|
+
if (process.platform === 'win32') {
|
|
41
|
+
// Real users' machines vary here - PowerShell is the modern Windows
|
|
42
|
+
// default (present on every Windows 10/11 install), but COMSPEC
|
|
43
|
+
// (usually cmd.exe) is what Windows itself considers "the" shell for
|
|
44
|
+
// a process that doesn't ask for anything more specific. Preferring
|
|
45
|
+
// PowerShell when it's genuinely on PATH, falling back to COMSPEC
|
|
46
|
+
// (or a bare cmd.exe) otherwise, covers both cases without assuming
|
|
47
|
+
// one specific install layout the way a hardcoded path would.
|
|
48
|
+
return 'powershell.exe';
|
|
49
|
+
}
|
|
50
|
+
// SHELL is the real, standard POSIX convention for "the user's own
|
|
51
|
+
// configured shell" (bash, zsh, fish, ...) - respecting it here means
|
|
52
|
+
// this bridges whatever shell the user already actually uses day to
|
|
53
|
+
// day, not a hardcoded assumption that might not even be installed.
|
|
54
|
+
// Only trusted if it actually resolves to a real file on disk right
|
|
55
|
+
// now - see isExecutableFile's own comment for why this check exists.
|
|
56
|
+
if (process.env.SHELL && isExecutableFile(process.env.SHELL)) {
|
|
57
|
+
return process.env.SHELL;
|
|
58
|
+
}
|
|
59
|
+
for (const candidate of ['/bin/zsh', '/bin/bash', '/bin/sh']) {
|
|
60
|
+
if (isExecutableFile(candidate)) return candidate;
|
|
61
|
+
}
|
|
62
|
+
// Every one of those is a standard part of macOS/Linux and should
|
|
63
|
+
// never actually be missing - this is a last-resort value, not an
|
|
64
|
+
// expected path, kept only so spawn() still gets SOME string instead
|
|
65
|
+
// of undefined.
|
|
66
|
+
return '/bin/sh';
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
module.exports = {
|
|
70
|
+
id: 'shell',
|
|
71
|
+
displayName: os.platform() === 'win32' ? 'PowerShell' : 'Shell',
|
|
72
|
+
icon: { name: 'terminal-outline', color: '#7C8B99' },
|
|
73
|
+
spawn: {
|
|
74
|
+
command: resolveShellCommand(),
|
|
75
|
+
args: () => [],
|
|
76
|
+
},
|
|
77
|
+
// No structured Confirmations card - a plain shell has no permission-
|
|
78
|
+
// prompt concept of its own to detect. If the user launches an AI CLI
|
|
79
|
+
// INSIDE this shell, that CLI's own real adapter (claude.js/codex.js)
|
|
80
|
+
// still isn't active here, since supervisor.js picks exactly one
|
|
81
|
+
// adapter per process/session at startup - a real user wanting
|
|
82
|
+
// structured approvals for a specific CLI should run `cli-setu session
|
|
83
|
+
// --cli claude` (or codex) directly, same as always. This adapter is
|
|
84
|
+
// specifically for "just give me my terminal, I'll decide what to run."
|
|
85
|
+
approvals: null,
|
|
86
|
+
usage: null,
|
|
87
|
+
// SETU-012: a one-tap way to launch Claude Code from a plain bridged
|
|
88
|
+
// shell - ties directly into supervisor.js's own detectRunningAdapter
|
|
89
|
+
// (SETU-006): tapping this sends the literal `claude` command into the
|
|
90
|
+
// real PTY, the live process-tree detector picks up the new child
|
|
91
|
+
// process within its own poll interval, and the phone's Usage button
|
|
92
|
+
// appears automatically, same as if the user had typed it by hand.
|
|
93
|
+
// Keystroke format matches claude.js/codex.js's own commands (`\r`, the
|
|
94
|
+
// same Enter sequence this adapter's own PTY already expects).
|
|
95
|
+
commands: [{ id: 'launch-claude', label: 'Open Claude', keystrokes: 'claude\r' }],
|
|
96
|
+
};
|
package/src/dedup.js
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Bounded FIFO dedup cache for inbound relay messages - used by
|
|
2
|
+
// supervisor.js to make sure a terminal.input message delivered twice
|
|
3
|
+
// (e.g. the phone retries because it didn't see an ack in time, or a
|
|
4
|
+
// provider redelivers during a reconnect) is never executed twice.
|
|
5
|
+
//
|
|
6
|
+
// Extracted out of supervisor.js into its own module (same pattern as
|
|
7
|
+
// reconnect.js) specifically so this logic can be unit-tested in
|
|
8
|
+
// isolation - it was previously a module-level Set + function inline in
|
|
9
|
+
// supervisor.js, which works fine at runtime but can't be imported by a
|
|
10
|
+
// test script on its own.
|
|
11
|
+
//
|
|
12
|
+
// Bounded by COUNT, not just a TTL - a pure time-based cache risks
|
|
13
|
+
// unbounded growth under a burst of distinct messages within one
|
|
14
|
+
// window; capping the actual entry count is the harder guarantee. FIFO
|
|
15
|
+
// eviction (insertion order, which a plain Set already preserves) is
|
|
16
|
+
// the right policy here: a message genuinely re-delivered after the
|
|
17
|
+
// window has passed is already long gone from any receiver's retry
|
|
18
|
+
// buffer anyway, so losing the OLDEST entries first costs nothing real.
|
|
19
|
+
function createDedupCache({ maxSize = 200 } = {}) {
|
|
20
|
+
const seen = new Set();
|
|
21
|
+
|
|
22
|
+
function isDuplicate(messageId) {
|
|
23
|
+
if (!messageId) return false; // no ID at all (older server build) - can't dedup, don't block it
|
|
24
|
+
if (seen.has(messageId)) return true;
|
|
25
|
+
seen.add(messageId);
|
|
26
|
+
if (seen.size > maxSize) {
|
|
27
|
+
seen.delete(seen.values().next().value); // oldest (first-inserted)
|
|
28
|
+
}
|
|
29
|
+
return false;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return { isDuplicate, size: () => seen.size };
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
module.exports = { createDedupCache };
|
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 };
|