@anupha/claude-bridge 0.0.0-stage → 1.0.0
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/LICENSE +21 -0
- package/README.md +56 -2
- package/SETUP.md +157 -0
- package/hooks/hook-handler.sh +27 -0
- package/package.json +41 -4
- package/scripts/claude-tmux.sh +52 -0
- package/scripts/install.mjs +282 -0
- package/scripts/kitty-passthrough.py +125 -0
- package/src/apns.mjs +102 -0
- package/src/cli.mjs +248 -0
- package/src/daemon.mjs +1204 -0
- package/src/pairing.mjs +35 -0
- package/src/qr.mjs +296 -0
- package/src/sysmon.mjs +98 -0
- package/src/terminal.mjs +659 -0
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Run a command on a pty and wrap its kitty-graphics escapes for tmux.
|
|
3
|
+
|
|
4
|
+
Claude Code writes pasted-image data as a bare APC (ESC _ G ... ESC \\). tmux
|
|
5
|
+
swallows a bare APC, so the picture never reaches the outer terminal and only
|
|
6
|
+
the empty placeholder cells are drawn. This relays the command's output
|
|
7
|
+
unchanged except that each such APC is rewrapped as a tmux passthrough
|
|
8
|
+
(ESC P tmux; ... ESC \\), which tmux forwards when `allow-passthrough` is on.
|
|
9
|
+
|
|
10
|
+
Usage: kitty-passthrough.py <command> [args...]
|
|
11
|
+
"""
|
|
12
|
+
import fcntl
|
|
13
|
+
import os
|
|
14
|
+
import pty
|
|
15
|
+
import select
|
|
16
|
+
import signal
|
|
17
|
+
import sys
|
|
18
|
+
import termios
|
|
19
|
+
import tty
|
|
20
|
+
|
|
21
|
+
APC_START = b"\x1b_G"
|
|
22
|
+
ST = b"\x1b\\"
|
|
23
|
+
# An image sent as a file path is tiny; inline base64 arrives in 4 KiB chunks.
|
|
24
|
+
# Anything unterminated past this is not a graphics command — stop holding it.
|
|
25
|
+
MAX_HELD = 1 << 20
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def wrap(apc: bytes) -> bytes:
|
|
29
|
+
return b"\x1bPtmux;" + apc.replace(b"\x1b", b"\x1b\x1b") + ST
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def rewrite(buf: bytes) -> tuple[bytes, bytes]:
|
|
33
|
+
"""Return (bytes ready to write, tail to hold until more output arrives)."""
|
|
34
|
+
out = bytearray()
|
|
35
|
+
pos = 0
|
|
36
|
+
while True:
|
|
37
|
+
start = buf.find(APC_START, pos)
|
|
38
|
+
if start < 0:
|
|
39
|
+
break
|
|
40
|
+
end = buf.find(ST, start + len(APC_START))
|
|
41
|
+
if end < 0:
|
|
42
|
+
out += buf[pos:start]
|
|
43
|
+
held = buf[start:]
|
|
44
|
+
return (bytes(out) + held, b"") if len(held) > MAX_HELD else (bytes(out), held)
|
|
45
|
+
out += buf[pos:start]
|
|
46
|
+
out += wrap(buf[start:end + len(ST)])
|
|
47
|
+
pos = end + len(ST)
|
|
48
|
+
rest = buf[pos:]
|
|
49
|
+
# A chunk can end partway through the 3-byte APC opener.
|
|
50
|
+
for n in (2, 1):
|
|
51
|
+
if rest.endswith(APC_START[:n]):
|
|
52
|
+
return bytes(out) + rest[:-n], rest[-n:]
|
|
53
|
+
return bytes(out) + rest, b""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def write_all(fd: int, data: bytes) -> None:
|
|
57
|
+
while data:
|
|
58
|
+
data = data[os.write(fd, data):]
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def copy_winsize(src: int, dst: int) -> None:
|
|
62
|
+
try:
|
|
63
|
+
fcntl.ioctl(dst, termios.TIOCSWINSZ, fcntl.ioctl(src, termios.TIOCGWINSZ, b"\0" * 8))
|
|
64
|
+
except OSError:
|
|
65
|
+
pass
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def main() -> int:
|
|
69
|
+
argv = sys.argv[1:]
|
|
70
|
+
if not argv:
|
|
71
|
+
print(__doc__, file=sys.stderr)
|
|
72
|
+
return 2
|
|
73
|
+
stdin, stdout = sys.stdin.fileno(), sys.stdout.fileno()
|
|
74
|
+
|
|
75
|
+
pid, master = pty.fork()
|
|
76
|
+
if pid == 0:
|
|
77
|
+
try:
|
|
78
|
+
os.execvp(argv[0], argv)
|
|
79
|
+
except OSError as e:
|
|
80
|
+
os.write(2, f"{argv[0]}: {e}\n".encode())
|
|
81
|
+
os._exit(127)
|
|
82
|
+
|
|
83
|
+
is_tty = os.isatty(stdin)
|
|
84
|
+
saved = termios.tcgetattr(stdin) if is_tty else None
|
|
85
|
+
if is_tty:
|
|
86
|
+
copy_winsize(stdin, master)
|
|
87
|
+
tty.setraw(stdin)
|
|
88
|
+
signal.signal(signal.SIGWINCH, lambda *_: copy_winsize(stdin, master))
|
|
89
|
+
for sig in (signal.SIGTERM, signal.SIGHUP):
|
|
90
|
+
signal.signal(sig, lambda s, _: os.kill(pid, s))
|
|
91
|
+
|
|
92
|
+
held = b""
|
|
93
|
+
fds = [master, stdin]
|
|
94
|
+
try:
|
|
95
|
+
while True:
|
|
96
|
+
try:
|
|
97
|
+
ready, _, _ = select.select(fds, [], [])
|
|
98
|
+
except InterruptedError:
|
|
99
|
+
continue
|
|
100
|
+
if master in ready:
|
|
101
|
+
try:
|
|
102
|
+
data = os.read(master, 65536)
|
|
103
|
+
except OSError: # EIO once the child closes its side
|
|
104
|
+
data = b""
|
|
105
|
+
if not data:
|
|
106
|
+
break
|
|
107
|
+
out, held = rewrite(held + data)
|
|
108
|
+
write_all(stdout, out)
|
|
109
|
+
if stdin in ready:
|
|
110
|
+
data = os.read(stdin, 65536)
|
|
111
|
+
if data:
|
|
112
|
+
write_all(master, data)
|
|
113
|
+
else:
|
|
114
|
+
fds.remove(stdin)
|
|
115
|
+
write_all(stdout, held)
|
|
116
|
+
finally:
|
|
117
|
+
if saved is not None:
|
|
118
|
+
termios.tcsetattr(stdin, termios.TCSADRAIN, saved)
|
|
119
|
+
|
|
120
|
+
_, status = os.waitpid(pid, 0)
|
|
121
|
+
return os.waitstatus_to_exitcode(status) if not os.WIFSIGNALED(status) else 128 + os.WTERMSIG(status)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
if __name__ == "__main__":
|
|
125
|
+
sys.exit(main())
|
package/src/apns.mjs
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
// APNs client for Live Activity pushes — HTTP/2 + ES256 JWT, zero dependencies.
|
|
2
|
+
// Lets the Lock Screen approval card appear even when the app is closed:
|
|
3
|
+
// queue 0->1 : push-to-start a Live Activity (iOS 17.2+)
|
|
4
|
+
// changes : update its content-state
|
|
5
|
+
// queue ->0 : end it
|
|
6
|
+
|
|
7
|
+
import http2 from 'node:http2';
|
|
8
|
+
import crypto from 'node:crypto';
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
|
|
11
|
+
const b64url = (buf) => Buffer.from(buf).toString('base64url');
|
|
12
|
+
|
|
13
|
+
export class ApnsClient {
|
|
14
|
+
/** @param getConfig () => {teamId, keyId, bundleId, keyPath, production} */
|
|
15
|
+
constructor(getConfig, log) {
|
|
16
|
+
this.getConfig = getConfig;
|
|
17
|
+
this.log = log;
|
|
18
|
+
this._jwt = null;
|
|
19
|
+
this._jwtAt = 0;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
config() { return this.getConfig() || {}; }
|
|
23
|
+
|
|
24
|
+
configured() {
|
|
25
|
+
const c = this.config();
|
|
26
|
+
return Boolean(c.teamId && c.keyId && c.bundleId && c.keyPath && fs.existsSync(c.keyPath));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
host() {
|
|
30
|
+
// Xcode-installed builds talk to the sandbox; TestFlight/App Store to production.
|
|
31
|
+
return this.config().production ? 'https://api.push.apple.com' : 'https://api.sandbox.push.apple.com';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
jwt() {
|
|
35
|
+
const now = Date.now();
|
|
36
|
+
if (this._jwt && now - this._jwtAt < 45 * 60_000) return this._jwt; // Apple allows 20-60 min
|
|
37
|
+
const c = this.config();
|
|
38
|
+
const key = crypto.createPrivateKey(fs.readFileSync(c.keyPath));
|
|
39
|
+
const header = b64url(JSON.stringify({ alg: 'ES256', kid: c.keyId }));
|
|
40
|
+
const payload = b64url(JSON.stringify({ iss: c.teamId, iat: Math.floor(now / 1000) }));
|
|
41
|
+
const sig = crypto.sign('sha256', Buffer.from(`${header}.${payload}`), { key, dsaEncoding: 'ieee-p1363' });
|
|
42
|
+
this._jwt = `${header}.${payload}.${b64url(sig)}`;
|
|
43
|
+
this._jwtAt = now;
|
|
44
|
+
return this._jwt;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
send(deviceToken, payload, headers = {}) {
|
|
48
|
+
return new Promise((resolve) => {
|
|
49
|
+
const client = http2.connect(this.host());
|
|
50
|
+
client.on('error', (e) => resolve({ status: 0, body: String(e) }));
|
|
51
|
+
const req = client.request({
|
|
52
|
+
':method': 'POST',
|
|
53
|
+
':path': `/3/device/${deviceToken}`,
|
|
54
|
+
authorization: `bearer ${this.jwt()}`,
|
|
55
|
+
'apns-priority': '10',
|
|
56
|
+
...headers,
|
|
57
|
+
});
|
|
58
|
+
let status = 0;
|
|
59
|
+
let body = '';
|
|
60
|
+
req.setTimeout(10_000, () => req.close());
|
|
61
|
+
req.on('response', (h) => { status = h[':status']; });
|
|
62
|
+
req.on('data', (c) => { body += c; });
|
|
63
|
+
req.on('end', () => { client.close(); resolve({ status, body }); });
|
|
64
|
+
req.on('error', (e) => { client.close(); resolve({ status: 0, body: String(e) }); });
|
|
65
|
+
req.end(JSON.stringify(payload));
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
laHeaders() {
|
|
70
|
+
return {
|
|
71
|
+
'apns-topic': `${this.config().bundleId}.push-type.liveactivity`,
|
|
72
|
+
'apns-push-type': 'liveactivity',
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
now() { return Math.floor(Date.now() / 1000); }
|
|
77
|
+
|
|
78
|
+
startActivity(token, contentState, alertBody) {
|
|
79
|
+
return this.send(token, {
|
|
80
|
+
aps: {
|
|
81
|
+
timestamp: this.now(),
|
|
82
|
+
event: 'start',
|
|
83
|
+
'content-state': contentState,
|
|
84
|
+
'attributes-type': 'PendingActivityAttributes',
|
|
85
|
+
attributes: {},
|
|
86
|
+
alert: { title: 'Claude needs your approval', body: alertBody, sound: 'default' },
|
|
87
|
+
},
|
|
88
|
+
}, this.laHeaders());
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
updateActivity(token, contentState) {
|
|
92
|
+
return this.send(token, {
|
|
93
|
+
aps: { timestamp: this.now(), event: 'update', 'content-state': contentState },
|
|
94
|
+
}, this.laHeaders());
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
endActivity(token) {
|
|
98
|
+
return this.send(token, {
|
|
99
|
+
aps: { timestamp: this.now(), event: 'end', 'dismissal-date': this.now() },
|
|
100
|
+
}, this.laHeaders());
|
|
101
|
+
}
|
|
102
|
+
}
|
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// bridge — CLI client for the claude-bridge daemon.
|
|
3
|
+
// Stands in for the iOS app until phase 2: inspect sessions, answer approvals.
|
|
4
|
+
//
|
|
5
|
+
// bridge status show sessions + pending approvals
|
|
6
|
+
// bridge approve <id|latest> [--always]
|
|
7
|
+
// bridge deny <id|latest>
|
|
8
|
+
// bridge remote on|off enable/disable remote approval mode
|
|
9
|
+
// bridge rules [clear]
|
|
10
|
+
// bridge watch live event stream (SSE)
|
|
11
|
+
// bridge pair expose daemon to the phone + show pairing info
|
|
12
|
+
// bridge apns [set k=v ...] Live Activity push setup status / config
|
|
13
|
+
// bridge install [--local] install Claude Code hooks + launchd daemon
|
|
14
|
+
// bridge uninstall [--local] remove hooks + launchd daemon
|
|
15
|
+
// bridge daemon run the daemon in the foreground
|
|
16
|
+
|
|
17
|
+
import fs from 'node:fs';
|
|
18
|
+
import os from 'node:os';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
|
|
21
|
+
const BASE = `http://127.0.0.1:${process.env.BRIDGE_PORT || 8787}`;
|
|
22
|
+
const DATA_DIR = process.env.BRIDGE_DATA_DIR || path.join(os.homedir(), '.claude-bridge');
|
|
23
|
+
const CONFIG_FILE = path.join(DATA_DIR, 'config.json');
|
|
24
|
+
|
|
25
|
+
function readConfig() {
|
|
26
|
+
return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf8'));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// config.json is mode 0600 and owned by the user running the daemon — being able
|
|
30
|
+
// to read it is what makes this CLI privileged. The daemon requires the token on
|
|
31
|
+
// every /api/* call, loopback included, so send it on all of them.
|
|
32
|
+
function authHeader() {
|
|
33
|
+
try {
|
|
34
|
+
const { authToken } = readConfig();
|
|
35
|
+
if (authToken) return { Authorization: `Bearer ${authToken}` };
|
|
36
|
+
} catch { /* daemon has never started, or the file isn't ours to read */ }
|
|
37
|
+
return {};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function api(method, route, body) {
|
|
41
|
+
const res = await fetch(`${BASE}${route}`, {
|
|
42
|
+
method,
|
|
43
|
+
headers: { 'Content-Type': 'application/json', ...authHeader() },
|
|
44
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
45
|
+
}).catch(() => null);
|
|
46
|
+
if (!res) {
|
|
47
|
+
console.error('daemon not running (start with: bridge daemon, or bridge install for the launch agent)');
|
|
48
|
+
process.exit(1);
|
|
49
|
+
}
|
|
50
|
+
if (res.status === 401) {
|
|
51
|
+
console.error(`unauthorized — could not read the daemon token from ${CONFIG_FILE}`);
|
|
52
|
+
console.error('(is the daemon running as a different user?)');
|
|
53
|
+
process.exit(1);
|
|
54
|
+
}
|
|
55
|
+
const text = await res.text();
|
|
56
|
+
return text ? JSON.parse(text) : null;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// The token lives here too, so keep every CLI-side write owner-only.
|
|
60
|
+
function saveConfig(cfg) {
|
|
61
|
+
fs.writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2), { mode: 0o600 });
|
|
62
|
+
try { fs.chmodSync(CONFIG_FILE, 0o600); } catch { /* best-effort */ }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const STATUS_ICON = {
|
|
66
|
+
'needs-approval': '🟠', 'needs-input': '🟡', working: '🟢', idle: '⚪️',
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
function printState(state) {
|
|
70
|
+
console.log(`remote approval: ${state.config.remoteApproval ? 'ON' : 'OFF'}\n`);
|
|
71
|
+
if (!state.sessions.length) console.log('no sessions');
|
|
72
|
+
for (const s of state.sessions) {
|
|
73
|
+
const age = Math.round((Date.now() - s.lastEvent) / 1000);
|
|
74
|
+
console.log(`${STATUS_ICON[s.status] || '·'} ${s.project.padEnd(28)} ${s.status.padEnd(15)} ${age}s ago (${s.id.slice(0, 8)})`);
|
|
75
|
+
}
|
|
76
|
+
if (state.pending.length) {
|
|
77
|
+
console.log('\npending approvals:');
|
|
78
|
+
for (const p of state.pending) {
|
|
79
|
+
console.log(` [${p.id}] ${p.project}: Claude requests to ${p.summary}`);
|
|
80
|
+
}
|
|
81
|
+
console.log(`\nanswer with: bridge approve ${state.pending[0].id} [--always] | bridge deny ${state.pending[0].id}`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function latestPendingId() {
|
|
86
|
+
const state = await api('GET', '/api/state');
|
|
87
|
+
if (!state.pending.length) {
|
|
88
|
+
console.error('no pending approvals');
|
|
89
|
+
process.exit(1);
|
|
90
|
+
}
|
|
91
|
+
return state.pending[0].id;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const [cmd, arg] = process.argv.slice(2);
|
|
95
|
+
const always = process.argv.includes('--always');
|
|
96
|
+
|
|
97
|
+
switch (cmd) {
|
|
98
|
+
case 'install':
|
|
99
|
+
case 'uninstall': {
|
|
100
|
+
// Delegate to scripts/install.mjs (hooks + launchd). Global by default —
|
|
101
|
+
// pass --local to only touch the current project's .claude/settings.json.
|
|
102
|
+
const { execFileSync } = await import('node:child_process');
|
|
103
|
+
const { fileURLToPath } = await import('node:url');
|
|
104
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
105
|
+
const extra = process.argv.slice(3);
|
|
106
|
+
const scope = extra.includes('--local') ? '--local' : '--global';
|
|
107
|
+
const flags = [scope, ...(cmd === 'uninstall' ? ['--uninstall'] : [])];
|
|
108
|
+
execFileSync(process.execPath, [path.join(root, 'scripts', 'install.mjs'), ...flags], { stdio: 'inherit' });
|
|
109
|
+
if (cmd === 'install') console.log('\nnext: run `bridge pair` and scan the QR with the Claude Remote app');
|
|
110
|
+
break;
|
|
111
|
+
}
|
|
112
|
+
case 'daemon': {
|
|
113
|
+
const { execFileSync } = await import('node:child_process');
|
|
114
|
+
const { fileURLToPath } = await import('node:url');
|
|
115
|
+
const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
116
|
+
execFileSync(process.execPath, [path.join(root, 'src', 'daemon.mjs')], { stdio: 'inherit' });
|
|
117
|
+
break;
|
|
118
|
+
}
|
|
119
|
+
case 'status':
|
|
120
|
+
case undefined:
|
|
121
|
+
printState(await api('GET', '/api/state'));
|
|
122
|
+
break;
|
|
123
|
+
case 'approve':
|
|
124
|
+
case 'deny': {
|
|
125
|
+
const id = !arg || arg === 'latest' ? await latestPendingId() : arg;
|
|
126
|
+
const out = await api('POST', '/api/decision', {
|
|
127
|
+
id, decision: cmd === 'approve' ? 'allow' : 'deny', always, source: 'cli',
|
|
128
|
+
});
|
|
129
|
+
console.log(out.ok ? `${cmd === 'approve' ? 'allowed' : 'denied'} [${id}]${always ? ' (rule saved)' : ''}` : `request [${id}] not found`);
|
|
130
|
+
break;
|
|
131
|
+
}
|
|
132
|
+
case 'remote': {
|
|
133
|
+
const out = await api('POST', '/api/config', { remoteApproval: arg === 'on' });
|
|
134
|
+
console.log(`remote approval: ${out.remoteApproval ? 'ON' : 'OFF'}`);
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
case 'rules': {
|
|
138
|
+
if (arg === 'clear') {
|
|
139
|
+
await api('POST', '/api/rules/clear');
|
|
140
|
+
console.log('rules cleared');
|
|
141
|
+
} else {
|
|
142
|
+
const state = await api('GET', '/api/state');
|
|
143
|
+
if (!state.rules.length) console.log('no rules');
|
|
144
|
+
for (const r of state.rules) console.log(`${r.project}: ${r.tool}${r.prefix ? ` (${r.prefix} …)` : ''}`);
|
|
145
|
+
}
|
|
146
|
+
break;
|
|
147
|
+
}
|
|
148
|
+
case 'pair': {
|
|
149
|
+
const { execSync } = await import('node:child_process');
|
|
150
|
+
const cfg = readConfig();
|
|
151
|
+
// bindHost is deliberately not settable over the API — opening the daemon to
|
|
152
|
+
// the network is a decision made here, on the Mac, by the person who owns it.
|
|
153
|
+
if (cfg.bindHost !== '0.0.0.0') {
|
|
154
|
+
cfg.bindHost = '0.0.0.0';
|
|
155
|
+
saveConfig(cfg);
|
|
156
|
+
try {
|
|
157
|
+
execSync('launchctl kickstart -k gui/$(id -u)/com.claude-bridge.daemon');
|
|
158
|
+
console.log('daemon restarted, now reachable from your phone\n');
|
|
159
|
+
await new Promise((r) => setTimeout(r, 800));
|
|
160
|
+
} catch {
|
|
161
|
+
console.log('restart the daemon to apply bindHost=0.0.0.0\n');
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
let ip = '';
|
|
165
|
+
try { ip = execSync('tailscale ip -4 2>/dev/null || ipconfig getifaddr en0').toString().trim().split('\n')[0]; } catch {}
|
|
166
|
+
const host = `http://${ip || '<mac-ip>'}:${process.env.BRIDGE_PORT || 8787}`;
|
|
167
|
+
const { pairingCode, pairingLink } = await import('./pairing.mjs');
|
|
168
|
+
const code = pairingCode(host, cfg.authToken);
|
|
169
|
+
console.log('SCAN with the phone Camera app (opens the app already paired):\n');
|
|
170
|
+
try {
|
|
171
|
+
const { qrLines } = await import('./qr.mjs');
|
|
172
|
+
console.log(qrLines(pairingLink(host, cfg.authToken)).map((l) => ' ' + l).join('\n'));
|
|
173
|
+
} catch { console.log(' (QR unavailable)'); }
|
|
174
|
+
console.log('\n…or paste this code in Settings → “Quick pair”:\n');
|
|
175
|
+
console.log(` ${code}\n`);
|
|
176
|
+
console.log('or enter manually:');
|
|
177
|
+
console.log(` host : ${host}`);
|
|
178
|
+
console.log(` token: ${cfg.authToken}`);
|
|
179
|
+
break;
|
|
180
|
+
}
|
|
181
|
+
case 'apns': {
|
|
182
|
+
if (arg === 'set') {
|
|
183
|
+
const { execSync } = await import('node:child_process');
|
|
184
|
+
// APNs credentials are file-only for the same reason as bindHost: the API
|
|
185
|
+
// must never be able to hand itself push credentials.
|
|
186
|
+
const cfg = readConfig();
|
|
187
|
+
cfg.apns = cfg.apns || {};
|
|
188
|
+
for (const kv of process.argv.slice(4)) {
|
|
189
|
+
const [k, v] = kv.split('=');
|
|
190
|
+
if (['teamId', 'keyId', 'bundleId'].includes(k)) cfg.apns[k] = v;
|
|
191
|
+
if (k === 'production') cfg.apns.production = v === 'true';
|
|
192
|
+
}
|
|
193
|
+
cfg.apns.bundleId = cfg.apns.bundleId || 'com.anupha.ClaudeRemote';
|
|
194
|
+
saveConfig(cfg);
|
|
195
|
+
try { execSync('launchctl kickstart -k gui/$(id -u)/com.claude-bridge.daemon'); } catch {}
|
|
196
|
+
console.log('APNs config saved, daemon restarted\n');
|
|
197
|
+
await new Promise((r) => setTimeout(r, 800));
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
const s = await api('GET', '/api/apns/status');
|
|
201
|
+
console.log(`configured : ${s.configured ? 'YES ✓' : 'no'}`);
|
|
202
|
+
console.log(`key file : ${s.hasKeyFile ? '~/.claude-bridge/AuthKey.p8 ✓' : 'missing — download .p8 from Apple, save as ~/.claude-bridge/AuthKey.p8'}`);
|
|
203
|
+
console.log(`teamId/keyId : ${s.teamId ? '✓' : 'missing'} / ${s.keyId ? '✓' : 'missing'}`);
|
|
204
|
+
console.log(`bundleId : ${s.bundleId || '(default com.anupha.ClaudeRemote)'}`);
|
|
205
|
+
console.log(`environment : ${s.production ? 'production' : 'sandbox (Xcode builds)'}`);
|
|
206
|
+
console.log(`phone tokens : push-to-start=${s.devices.pushToStart ? '✓' : '—'} activity=${s.devices.activity ? '✓' : '—'}`);
|
|
207
|
+
if (!s.configured) {
|
|
208
|
+
console.log('\nsetup: 1) developer.apple.com → Keys → “+” → เปิด APNs → download .p8');
|
|
209
|
+
console.log(' 2) save เป็น ~/.claude-bridge/AuthKey.p8');
|
|
210
|
+
console.log(' 3) bridge apns set teamId=<TEAM_ID> keyId=<KEY_ID>');
|
|
211
|
+
}
|
|
212
|
+
break;
|
|
213
|
+
}
|
|
214
|
+
case 'watch': {
|
|
215
|
+
const res = await fetch(`${BASE}/api/events`, { headers: authHeader() });
|
|
216
|
+
if (res.status === 401) {
|
|
217
|
+
console.error(`unauthorized — could not read the daemon token from ${CONFIG_FILE}`);
|
|
218
|
+
process.exit(1);
|
|
219
|
+
}
|
|
220
|
+
for await (const chunk of res.body) {
|
|
221
|
+
const text = Buffer.from(chunk).toString();
|
|
222
|
+
for (const line of text.split('\n')) {
|
|
223
|
+
if (!line.startsWith('data: ')) continue;
|
|
224
|
+
let state;
|
|
225
|
+
try { state = JSON.parse(line.slice(6)); } catch { continue; } // line split across chunks
|
|
226
|
+
if (!state || typeof state !== 'object') continue; // keep-alive ping
|
|
227
|
+
console.log(`\n--- ${new Date().toLocaleTimeString()} ---`);
|
|
228
|
+
printState(state);
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
break;
|
|
232
|
+
}
|
|
233
|
+
default:
|
|
234
|
+
console.log([
|
|
235
|
+
'usage: bridge <command>',
|
|
236
|
+
'',
|
|
237
|
+
' install set up hooks, the claude→tmux alias and the background daemon',
|
|
238
|
+
' pair show the pairing code + QR for the Claude Remote app',
|
|
239
|
+
' uninstall remove everything install added',
|
|
240
|
+
' daemon run the daemon in the foreground',
|
|
241
|
+
' status sessions and pending approvals',
|
|
242
|
+
' approve <id> [--always] | deny <id>',
|
|
243
|
+
' remote on|off phone approvals on/off',
|
|
244
|
+
' rules [clear] always-allow rules',
|
|
245
|
+
' watch live state stream',
|
|
246
|
+
' apns ... Live Activity push setup',
|
|
247
|
+
].join('\n'));
|
|
248
|
+
}
|