rob-revisited/ide/ui/js/remote-host.js

462 lines
22 KiB
JavaScript

// IDE Remote, the HOST side (contract: docs/ide-remote.md). While sharing is on, a phone or another computer opens the JumPHP IDE Remote
// application and sees / drives the IDE's Claude panel, Terminal (and, for "all", a read-only view of files, git status, run output).
// - end-to-end encrypted (channel.js: the key lives in the pairing link's fragment only); the relay / the direct pipe move ciphertext
// - consent on this computer for every new device (a dialog), expiry (default 8 h), Revoke, Stop sharing
// - DENY BY DEFAULT: only the commands of remote/allow.js run; their payloads are re-built here (never passed through as they come)
// Only data crosses (conversation items, terminal bytes, text); the PHP side is a dumb TCP pipe for the direct mode (ide/src/Remote).
import { backend } from './backend.js';
import { dialog, el, notify, prefs, t } from './ui.js';
import { REMOTE_ALLOW, REMOTE_EVENTS, REMOTE_PANELS, REMOTE_PANELS_OF, SCOPES, isAllowed } from './remote/allow.js';
/** The relay that moves the ciphertext (override: `?relay=ws://localhost:8090/ws` in the IDE page URL, or the pref `remoteRelay`). */
export const RELAY_URL = 'wss://jumphp.net/ide-relay/ws';
export const LOCAL_RELAY_URL = 'ws://localhost:8090/ws';
/** The page the pairing fragment is appended to (JumPHP IDE Remote, published on jumphp.net). */
export const APP_URL = 'https://play.jumphp.net/jumphp-ide-remote/play/'; // the page itself (the jumphp.net page frames it: a fragment would not reach the frame)
export const DEFAULT_HOURS = 8;
const RING_BYTES = 256 * 1024;
const PING_EVERY = 20000;
const IDLE_MAX = 60000;
const MAX_WRITE = 64 * 1024;
const MAX_FILE_RESULT = 2 * 1024 * 1024;
const SNAP_ITEMS = 200;
const SNAP_BYTES = 400 * 1024;
export function relayUrl() {
try {
const q = new URLSearchParams(location.search).get('relay');
if (q && /^wss?:\/\//.test(q)) return q;
} catch { /* no location */ }
const pref = prefs.get('remoteRelay', '');
return /^wss?:\/\//.test(pref) ? pref : RELAY_URL;
}
const b64 = (bytes) => {
let s = '';
for (let i = 0; i < bytes.length; i += 0x8000) s += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
return btoa(s);
};
const unb64 = (text) => Uint8Array.from(atob(text), (c) => c.charCodeAt(0));
const int = (v, lo, hi, dflt) => { const n = Math.trunc(Number(v)); return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : dflt; };
const cleanName = (s) => String(s ?? '').replace(/[\u0000-\u001f\u007f<>]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, 40) || 'Unknown device';
const unsafePath = (p) => !p || typeof p !== 'string' || p.length > 500 || p.startsWith('/') || /^[a-zA-Z]:/.test(p) || p.includes('\\') || p.split('/').includes('..')
|| /(^|\/)(\.env[^/]*|id_[a-z0-9]+|[^/]*\.(pem|key|p12|pfx))$/i.test(p) || /(^|\/)\.git\/(config|credentials)/.test(p);
export const SCOPE_LABELS = { claude: 'the Claude panel', terminal: 'the Terminal', all: 'the whole IDE' };
export class RemoteHost {
constructor(app) {
this.app = app;
this.active = false;
this.scope = 'claude';
this.mode = 'auto';
this.expires = 0;
this.pairing = null;
this.addresses = [];
this.relayState = 'off'; // off | connecting | ready | error
this.error = '';
this.devices = new Map(); // key -> device
this.listeners = new Set();
this.rings = new Map(); // terminal id -> {chunks: [Uint8Array], size}
this.remoteTerms = new Map(); // terminals a device opened: id -> {cols, rows}
this.conns = new Map(); // direct connection id -> {feed, onClose}
this.cleanups = [];
this.relayChannel = null;
this.mod = null;
this.consent = Promise.resolve();
this.timer = 0;
}
/** The state changed: fn(host). Returns the way to stop listening. */
onChange(fn) { this.listeners.add(fn); return () => this.listeners.delete(fn); }
changed() { for (const fn of [...this.listeners]) { try { fn(this); } catch (e) { console.error(e); } } }
/** The pairing link (what the QR code shows). */
link() {
if (!this.active || !this.pairing || !this.mod) return '';
const direct = this.mode === 'server' ? [] : this.addresses;
return this.mod.Channel.pairingUrl(APP_URL, { room: this.pairing.room, key: this.pairing.key, direct });
}
connected() { return [...this.devices.values()].filter((d) => d.ok); }
async start({ scope = 'claude', mode = 'auto', hours = DEFAULT_HOURS } = {}) {
if (this.active) await this.stop();
if (!SCOPES.includes(scope)) scope = 'claude';
if (!['auto', 'server', 'direct'].includes(mode)) mode = 'auto';
this.mod = await import('./remote/channel.js');
this.scope = scope;
this.mode = mode;
this.error = '';
this.expires = Math.floor(Date.now() / 1000 + Math.max(0.1, hours) * 3600);
this.pairing = await this.mod.Channel.newPairing();
this.rings.clear();
this.remoteTerms.clear();
this.active = true;
// the IDE's events: the rings of terminal output (late joiners) and the forwarding
for (const name of REMOTE_EVENTS.all) this.cleanups.push(backend.on(name, (p) => this.onIdeEvent(name, p)));
this.timer = setInterval(() => this.tick(), 5000);
this.lastPing = Date.now();
try {
if (mode !== 'server') await this.startDirect();
if (mode !== 'direct') await this.startRelay();
} catch (e) {
this.error = e.message || String(e);
if (mode === 'direct' || (!this.relayChannel && !this.addresses.length)) { await this.stop(); throw e; }
}
if (mode === 'direct' && !this.addresses.length) { await this.stop(); throw new Error(t('Direct mode found no network address on this computer.')); }
this.changed();
}
async startRelay() {
const { Channel, relayTransport } = this.mod;
this.relayState = 'connecting';
const transport = relayTransport({ url: relayUrl(), room: this.pairing.room, role: 'host' });
const ch = await Channel.open({ role: 'host', key: this.pairing.key, transport });
this.relayChannel = ch;
ch.on('open', () => { this.relayState = 'ready'; this.changed(); });
ch.on('close', () => { if (this.relayChannel === ch && this.active) { this.relayState = 'connecting'; this.changed(); } });
ch.on('error', (e) => { if (e?.code === 'decrypt' || e?.code === 'json') return; this.relayState = 'error'; this.error = e?.message || String(e); this.changed(); });
ch.on('peer', (info) => { if (info?.type === 'leave') this.dropDevice('relay:' + info.peer, false); });
ch.on('message', (msg, from) => this.onMessage('relay:' + from, ch, from, msg));
}
async startDirect() {
if (backend.kind !== 'native') { if (this.mode === 'direct') throw new Error(t('Direct mode needs the desktop IDE.')); return; }
const { Channel, streamTransport } = this.mod;
this.cleanups.push(backend.on('remote.direct.open', ({ conn }) => {
const entry = { feed: null, onClose: null, channel: null };
this.conns.set(conn, entry);
const transport = streamTransport({
send: (bytes) => backend.invoke('remote.direct.write', { conn, data: b64(bytes) }),
onData: (cb) => { entry.feed = cb; },
onClose: (cb) => { entry.onClose = cb; },
close: () => { backend.invoke('remote.direct.close', { conn }).catch(() => {}); },
});
Channel.open({ role: 'host', key: this.pairing.key, transport }).then((ch) => {
entry.channel = ch;
if (!this.conns.has(conn) || !this.active) { ch.close(); return; }
ch.on('message', (msg) => this.onMessage('direct:' + conn, ch, undefined, msg));
ch.on('close', () => this.dropDevice('direct:' + conn, false));
ch.on('error', () => {});
}).catch(() => {});
}));
this.cleanups.push(backend.on('remote.direct.data', ({ conn, data }) => { try { this.conns.get(conn)?.feed?.(unb64(data)); } catch { /* bad chunk */ } }));
this.cleanups.push(backend.on('remote.direct.close', ({ conn }) => {
const e = this.conns.get(conn);
this.conns.delete(conn);
e?.onClose?.('closed');
this.dropDevice('direct:' + conn, false);
}));
const r = await backend.invoke('remote.direct.listen', {});
this.addresses = Array.isArray(r?.addresses) ? r.addresses.map(String) : [];
}
// ---- devices -------------------------------------------------------------------------------------------------------
deviceSend(dev, obj) {
if (!dev.channel) return Promise.resolve();
return dev.channel.send(obj, dev.to === undefined ? {} : { to: dev.to }).catch(() => {});
}
onMessage(key, channel, to, msg) {
if (!this.active || !msg || typeof msg !== 'object') return;
let dev = this.devices.get(key);
if (!dev) {
if (msg.t !== 'hello') return; // nothing is answered before a hello (and its consent)
if (this.devices.size >= 8) return;
dev = { key, channel, to, via: key.startsWith('direct') ? 'direct' : 'server', ok: false, asked: false, name: '', scope: '', subs: new Set(), lastSeen: Date.now(), since: 0 };
this.devices.set(key, dev);
}
dev.lastSeen = Date.now();
switch (msg.t) {
case 'hello': if (!dev.asked) this.hello(dev, msg); break;
case 'ping': if (dev.ok) this.deviceSend(dev, { t: 'pong' }); break;
case 'pong': break;
case 'bye': this.dropDevice(key, false); break;
case 'sub': if (dev.ok) this.subscribe(dev, msg.panels); break;
case 'invoke': if (dev.ok) this.invoke(dev, msg); break;
default: break;
}
}
hello(dev, msg) {
dev.asked = true;
dev.name = cleanName(msg.name);
if (msg.v !== 1) { this.deny(dev, 'version'); return; }
// the scope granted: what this sharing offers, narrowed to what the device wants
const want = SCOPES.includes(msg.want) ? msg.want : this.scope;
dev.scope = this.scope === 'all' ? want : this.scope;
// one dialog at a time
this.consent = this.consent.then(() => this.ask(dev)).catch(() => {});
}
ask(dev) {
if (!this.active || !this.devices.has(dev.key)) return Promise.resolve();
return new Promise((resolve) => {
let answered = false;
const answer = (allow) => {
if (answered) return;
answered = true;
resolve();
if (!this.active || this.devices.get(dev.key) !== dev) return;
if (allow) this.admit(dev); else this.deny(dev, 'refused');
};
dialog({
title: t('A device wants to connect'),
sticky: true,
body: el('div', {},
el('p', {}, t('Allow “{name}” to use {scope}?', { name: dev.name, scope: t(SCOPE_LABELS[dev.scope]) })),
el('p', {}, t('It will see and type into it, from {via}. Only allow a device you just paired yourself.', { via: dev.via === 'direct' ? t('this network') : t('the server') }))),
buttons: [{ label: t('Deny'), action: () => answer(false) }, { label: t('Allow'), primary: true, action: () => answer(true) }],
onClose: () => answer(false),
});
});
}
admit(dev) {
dev.ok = true;
dev.since = Date.now();
dev.subs = new Set(REMOTE_PANELS_OF[dev.scope]);
const app = this.app;
const root = String(app?.project?.root || '');
this.deviceSend(dev, {
t: 'welcome', v: 1, scope: dev.scope,
project: { name: String(app?.project?.name || ''), root_name: root.split(/[\\/]/).filter(Boolean).pop() || String(app?.project?.name || '') },
panels: this.panelsOf(dev.scope),
terminals: this.terminalList(),
expires: this.expires,
});
if (dev.scope !== 'claude') this.sendSnap(dev, 'terminal');
if (dev.scope !== 'terminal') this.sendSnap(dev, 'claude');
notify(t('“{name}” is connected to the IDE.', { name: dev.name }), 'info', { title: t('Remote') });
this.changed();
}
panelsOf(scope) {
const out = [];
if (scope !== 'terminal') out.push({ id: 'claude', title: 'Claude' });
if (scope !== 'claude') out.push({ id: 'terminal', title: 'Terminal' });
if (scope === 'all') out.push({ id: 'files', title: 'Files' }, { id: 'run', title: 'Run' });
return out;
}
terminalList() {
const out = [];
for (const x of this.app?.terminal?.terms || []) {
if (x.id !== null && x.id !== undefined && !x.ended) out.push({ id: x.id, title: String(x.label || 'Terminal'), cols: x.term?.cols || 80, rows: x.term?.rows || 24 });
}
for (const [id, s] of this.remoteTerms) if (!out.some((o) => o.id === id)) out.push({ id, title: t('Remote'), cols: s.cols, rows: s.rows });
return out;
}
deny(dev, reason) {
this.deviceSend(dev, { t: 'denied', reason });
setTimeout(() => this.closeDevice(dev), 300);
this.devices.delete(dev.key);
this.changed();
}
closeDevice(dev) {
if (dev.key.startsWith('direct:')) {
const conn = Number(dev.key.slice(7));
this.conns.delete(conn);
dev.channel?.close();
}
// a relay device just stops being served (it shares the room's channel)
}
dropDevice(key, notifyPeer) {
const dev = this.devices.get(key);
if (!dev) return;
this.devices.delete(key);
if (notifyPeer) this.deviceSend(dev, { t: 'denied', reason: 'revoked' });
setTimeout(() => this.closeDevice(dev), notifyPeer ? 300 : 0);
this.changed();
}
/** The Revoke button: tells the device, forgets it (it must say hello again and be allowed again). */
revoke(key) { this.dropDevice(key, true); }
subscribe(dev, panels) {
const allowed = REMOTE_PANELS_OF[dev.scope];
dev.subs = new Set((Array.isArray(panels) ? panels : []).filter((p) => allowed.includes(p)));
}
// ---- IDE events -> devices ----------------------------------------------------------------------------------------
onIdeEvent(name, payload) {
if (!this.active) return;
if (name === 'terminal.output' && payload && typeof payload.data === 'string') this.record(payload.id, payload.data);
if (name === 'terminal.exit' && payload) this.rings.delete(payload.id);
const panel = Object.keys(REMOTE_PANELS).find((p) => REMOTE_PANELS[p].includes(name));
for (const dev of this.devices.values()) {
if (!dev.ok || !dev.subs.has(panel) || !REMOTE_EVENTS[dev.scope].includes(name)) continue;
this.deviceSend(dev, { t: 'event', name, payload });
}
}
record(id, data) {
let bytes;
try { bytes = unb64(data); } catch { return; }
let ring = this.rings.get(id);
if (!ring) { ring = { chunks: [], size: 0 }; this.rings.set(id, ring); }
ring.chunks.push(bytes);
ring.size += bytes.length;
while (ring.size > RING_BYTES && ring.chunks.length > 1) ring.size -= ring.chunks.shift().length;
if (ring.size > RING_BYTES) { ring.chunks[0] = ring.chunks[0].slice(ring.size - RING_BYTES); ring.size = RING_BYTES; }
}
sendSnap(dev, panel) {
if (!REMOTE_PANELS_OF[dev.scope].includes(panel)) return;
if (panel === 'terminal') {
for (const info of this.terminalList()) {
const ring = this.rings.get(info.id);
const all = new Uint8Array(ring ? ring.size : 0);
let at = 0;
for (const c of ring?.chunks || []) { all.set(c, at); at += c.length; }
this.deviceSend(dev, { t: 'snap', panel: 'terminal', id: info.id, data: b64(all), cols: info.cols, rows: info.rows, title: info.title });
}
} else if (panel === 'claude') {
const conv = this.currentConversation();
if (!conv) { this.deviceSend(dev, { t: 'snap', panel: 'claude', conv: '', items: [] }); return; }
let items = (conv.items || []).slice(-SNAP_ITEMS);
let json = '[]';
try { json = JSON.stringify(items); } catch { items = []; }
while (json.length > SNAP_BYTES && items.length > 1) { items = items.slice(Math.ceil(items.length / 4)); json = JSON.stringify(items); }
this.deviceSend(dev, { t: 'snap', panel: 'claude', conv: String(conv.key), session: conv.session || '', items: JSON.parse(json) });
}
}
currentConversation(key) {
const panel = this.app?.claude;
if (!panel?.convs) return null;
return (key && panel.convs.find((c) => c.key === key)) || panel.current?.() || panel.convs[panel.convs.length - 1] || null;
}
// ---- commands ---------------------------------------------------------------------------------------------------------
async invoke(dev, msg) {
const id = msg.id;
const reply = (ok, v) => this.deviceSend(dev, ok ? { t: 'result', id, ok: true, result: v } : { t: 'result', id, ok: false, error: v });
const name = String(msg.name || '');
try {
if (name === 'snap') {
const panel = String(msg.payload?.panel || '');
if (!REMOTE_PANELS_OF[dev.scope].includes(panel)) return reply(false, 'denied');
this.sendSnap(dev, panel);
return reply(true, true);
}
if (!isAllowed(dev.scope, name)) return reply(false, 'denied');
reply(true, await this.run(dev, name, msg.payload && typeof msg.payload === 'object' ? msg.payload : {}));
} catch (e) {
reply(false, e?.message || String(e));
}
}
/** Runs one allowed command. The payload is RE-BUILT here: only the fields a command needs, checked. */
async run(dev, name, p) {
switch (name) {
case 'claude.send': return this.claudeSend(p);
case 'claude.stop': return backend.invoke(name, { id: String(p.id ?? '') });
case 'claude.stopAll': case 'claude.status': case 'claude.history.list': case 'files.list': case 'git.status':
return backend.invoke(name, {});
case 'claude.history.read': return backend.invoke(name, { id: String(p.id ?? '').slice(0, 200) });
case 'project.info': return { name: String(this.app?.project?.name || ''), kind: String(this.app?.project?.kind || '') };
case 'file.read': {
if (unsafePath(p.path)) throw new Error('denied');
const r = await backend.invoke(name, { path: p.path });
if (JSON.stringify(r).length > MAX_FILE_RESULT) throw new Error('file too large');
return r;
}
case 'terminal.open': {
const cols = int(p.cols, 10, 400, 80), rows = int(p.rows, 2, 200, 24);
const r = await backend.invoke(name, { cols, rows }); // never a `shell` chosen by the device
if (r && r.id !== undefined) this.remoteTerms.set(r.id, { cols, rows });
return r;
}
case 'terminal.write': {
if (typeof p.data !== 'string' || p.data.length > MAX_WRITE) throw new Error('bad data');
return backend.invoke(name, { id: int(p.id, 0, 1e9, -1), data: p.data });
}
case 'terminal.resize': {
const cols = int(p.cols, 10, 400, 80), rows = int(p.rows, 2, 200, 24), id = int(p.id, 0, 1e9, -1);
if (this.remoteTerms.has(id)) this.remoteTerms.set(id, { cols, rows });
return backend.invoke(name, { id, cols, rows });
}
case 'terminal.close': {
const id = int(p.id, 0, 1e9, -1);
this.remoteTerms.delete(id);
return backend.invoke(name, { id });
}
default: throw new Error('denied');
}
}
/**
* Text for Claude. Goes through the panel's conversation exactly as if typed there (the panel shows it, and when the Terminal's Remote Control
* claude holds the session, the panel types it into that terminal tab: one claude per session). The permission mode is the panel's, never the device's.
*/
async claudeSend(p) {
const prompt = String(p.prompt ?? '').trim();
if (!prompt || prompt.length > 64 * 1024) throw new Error('empty or too long');
if (/^\/(rc|remote-control)$/.test(prompt)) throw new Error('denied');
const conv = this.currentConversation(typeof p.conv === 'string' ? p.conv : '');
if (conv?.input && conv.send) {
const draft = conv.input.value;
conv.input.value = prompt;
const done = conv.send();
await done;
if (!conv.input.value && draft) conv.input.value = draft; // what the person was typing is given back
return { ok: true, via: conv.rcTab && !conv.rcTab.ended ? 'terminal' : conv.lease?.state === 'handoff' ? 'queued' : 'claude' }; // the arbiter queues it behind a handoff: a device never owns the session
}
const r = await backend.invoke('claude.send', { prompt, mode: prefs.get('claudeMode', 'acceptEdits'), model: prefs.get('claudeModel', ''), effort: prefs.get('claudeEffort', ''), conv: 'claude:' + (this.app?.projectKey || ''), agent: 'claude' });
return { ok: true, via: r?.queued ? 'queued' : 'claude', id: r?.id };
}
// ---- life ---------------------------------------------------------------------------------------------------------------
tick() {
if (!this.active) return;
const now = Date.now();
if (now / 1000 >= this.expires) { this.stop('expired'); return; }
const ping = now - this.lastPing >= PING_EVERY;
if (ping) this.lastPing = now;
for (const dev of [...this.devices.values()]) {
if (now - dev.lastSeen > IDLE_MAX) { this.dropDevice(dev.key, false); continue; }
if (ping && dev.ok) this.deviceSend(dev, { t: 'ping' });
}
}
/** Stop sharing: every device is told, every channel closed, every listener removed, the direct port closed. */
async stop(reason = 'revoked') {
if (!this.active) return;
this.active = false;
clearInterval(this.timer);
const devices = [...this.devices.values()];
this.devices.clear();
await Promise.all(devices.filter((d) => d.ok).map((d) => Promise.race([this.deviceSend(d, { t: 'denied', reason }), new Promise((r) => setTimeout(r, 400))])));
for (const d of devices) this.closeDevice(d);
for (const off of this.cleanups.splice(0)) { try { off(); } catch { /* gone */ } }
for (const e of this.conns.values()) { try { e.channel?.close(); } catch { /* gone */ } }
this.conns.clear();
try { this.relayChannel?.close(); } catch { /* gone */ }
this.relayChannel = null;
if (backend.kind === 'native' && this.mode !== 'server') backend.invoke('remote.direct.stop', {}).catch(() => {});
this.relayState = 'off';
this.addresses = [];
this.pairing = null;
this.rings.clear();
this.remoteTerms.clear();
this.changed();
}
}
/** The one host of this IDE window. */
export function remoteHost(app) {
return app.remoteHost || (app.remoteHost = new RemoteHost(app));
}
export { REMOTE_ALLOW };