fix: v0.5.0 security and robustness fixes from the 2026-10-07 review
- Ask Claude: strip control characters, send as bracketed paste (closes #2) - end: forget before kill, so ending from inside a session leaves no ghost (closes #3) - reconnects use `attach --existing` and never resurrect ended/renamed sessions (closes #4) - repo: git --no-optional-locks, no safe.directory override, refresh on connect/bell/60s (closes #5) - uploads: unique names via mktemp, cleanup trap on hangup (closes #6) - clipboard: write-only OSC 52 provider, tmux allow-passthrough off (closes #7) - uploads: size check up front, streamed slices, idle timeout (closes #9) - --list: path last in TSV rows, tolerant numbers (closes #10) - tokens via curl config on stdin; userinfo stripped from remote URLs (closes #11) - ttyd max clients 32 and at most 2 concurrent side-channel calls (#8; BroadcastChannel polling still open) - tmux: fixed terminal-features index (no duplicates on re-source), no status-right clock Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+47
-12
@@ -94,9 +94,28 @@ export class TtydConnection {
|
||||
}
|
||||
}
|
||||
|
||||
// Side-channel commands each occupy a ttyd client slot and a server process:
|
||||
// run at most two at a time (devdesk#8).
|
||||
let active = 0;
|
||||
const waiting = [];
|
||||
async function limited(task) {
|
||||
if (active >= 2) await new Promise((resolve) => waiting.push(resolve));
|
||||
active += 1;
|
||||
try {
|
||||
return await task();
|
||||
} finally {
|
||||
active -= 1;
|
||||
waiting.shift()?.();
|
||||
}
|
||||
}
|
||||
|
||||
// Run a short-lived `devdesk attach <args…>` and return its output as text.
|
||||
// ttyd is the only server-side endpoint, so session actions travel this way.
|
||||
export async function runCommand(args, timeoutMs = 8000) {
|
||||
export function runCommand(args, timeoutMs = 8000) {
|
||||
return limited(() => runCommandNow(args, timeoutMs));
|
||||
}
|
||||
|
||||
async function runCommandNow(args, timeoutMs) {
|
||||
const token = await fetchToken();
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = new WebSocket(wsUrl(window.location, args), ['tty']);
|
||||
@@ -139,31 +158,47 @@ function toBase64(bytes) {
|
||||
|
||||
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
export const UPLOAD_MAX = 25 * 1024 * 1024;
|
||||
|
||||
// Upload a file into the session's upload folder through ttyd: wait for the
|
||||
// server's ready line, stream the file as base64 input, read back {ok, path}.
|
||||
export async function uploadFile(session, file, onProgress) {
|
||||
// server's ready line, stream the file as base64 input in slices (never the
|
||||
// whole file in memory), read back {ok, path}. Fails on 20 s of inactivity
|
||||
// rather than a fixed total, so slow links still work (devdesk#9).
|
||||
export function uploadFile(session, file, onProgress) {
|
||||
if (!file.size) return Promise.reject(new Error('file is empty'));
|
||||
if (file.size > UPLOAD_MAX) return Promise.reject(new Error('larger than 25 MB'));
|
||||
return limited(() => uploadNow(session, file, onProgress));
|
||||
}
|
||||
|
||||
async function uploadNow(session, file, onProgress) {
|
||||
const token = await fetchToken();
|
||||
const bytes = new Uint8Array(await file.arrayBuffer());
|
||||
const b64 = toBase64(bytes);
|
||||
const name = (file.name || 'pasted-image.png').slice(-100);
|
||||
const slice = 3 * 16 * 1024; // multiple of 3: base64 of slices concatenates cleanly
|
||||
return new Promise((resolve, reject) => {
|
||||
const socket = new WebSocket(wsUrl(window.location, ['--upload', session, name, String(bytes.length)]), ['tty']);
|
||||
const socket = new WebSocket(wsUrl(window.location, ['--upload', session, name, String(file.size)]), ['tty']);
|
||||
socket.binaryType = 'arraybuffer';
|
||||
const decoder = new TextDecoder();
|
||||
let output = '';
|
||||
let sending = false;
|
||||
const timer = setTimeout(() => socket.close(), 30000 + bytes.length / 50);
|
||||
let idle = 0;
|
||||
const touch = () => {
|
||||
clearTimeout(idle);
|
||||
idle = setTimeout(() => socket.close(), 20000);
|
||||
};
|
||||
const send = async () => {
|
||||
const chunk = 48 * 1024;
|
||||
for (let i = 0; i < b64.length; i += chunk) {
|
||||
for (let offset = 0; offset < file.size; offset += slice) {
|
||||
while (socket.bufferedAmount > 1 << 20) await sleep(20);
|
||||
if (socket.readyState !== WebSocket.OPEN) return;
|
||||
socket.send(encodeInput(b64.slice(i, i + chunk)));
|
||||
onProgress?.(Math.min(1, (i + chunk) / b64.length));
|
||||
const bytes = new Uint8Array(await file.slice(offset, offset + slice).arrayBuffer());
|
||||
socket.send(encodeInput(toBase64(bytes)));
|
||||
touch();
|
||||
onProgress?.(Math.min(1, (offset + slice) / file.size));
|
||||
}
|
||||
};
|
||||
touch();
|
||||
socket.onopen = () => socket.send(encodeInit(token, 240, 24));
|
||||
socket.onmessage = (event) => {
|
||||
touch();
|
||||
const { type, payload } = decodeServer(event.data);
|
||||
if (type !== Server.OUTPUT) return;
|
||||
output += decoder.decode(payload, { stream: true });
|
||||
@@ -174,7 +209,7 @@ export async function uploadFile(session, file, onProgress) {
|
||||
};
|
||||
socket.onerror = () => {};
|
||||
socket.onclose = () => {
|
||||
clearTimeout(timer);
|
||||
clearTimeout(idle);
|
||||
const text = stripAnsi(output.replace(/^[\s\S]*DEVDESK-UPLOAD-READY/, ''));
|
||||
try {
|
||||
const result = parseListOutput(text);
|
||||
|
||||
+17
-11
@@ -3,7 +3,7 @@ import { createTerminal, loadFonts } from './term.js';
|
||||
import {
|
||||
TtydConnection, fetchAlerts, fetchRepo, fetchToken, uploadFile, AuthExpiredError, UnauthorizedError,
|
||||
} from './connection.js';
|
||||
import { parseTitle, sessionFromSearch } from './protocol.js';
|
||||
import { parseTitle, pasteSafe, sessionFromSearch } from './protocol.js';
|
||||
import { SessionsPanel, rememberSession, sessionStatus } from './sessions.js';
|
||||
import { renderAlerts } from './alerts.js';
|
||||
import { renderContext } from './context.js';
|
||||
@@ -246,7 +246,9 @@ function updateUrl(session) {
|
||||
|
||||
// ---------------------------------------------------------------- connection
|
||||
|
||||
function connect(session) {
|
||||
// reconnect: automatic re-attach after a drop. It must not re-create a session
|
||||
// that was ended or renamed meanwhile, so it asks for --existing (devdesk#4).
|
||||
function connect(session, { reconnect = false } = {}) {
|
||||
clearTimeout(state.retryTimer);
|
||||
state.conn?.dispose();
|
||||
state.session = session;
|
||||
@@ -260,7 +262,7 @@ function connect(session) {
|
||||
term.reset();
|
||||
|
||||
const conn = new TtydConnection({
|
||||
arg: session,
|
||||
arg: session && reconnect ? ['--existing', session] : session,
|
||||
size: () => ({ cols: term.cols, rows: term.rows }),
|
||||
onOpen: () => {
|
||||
state.openedAt = Date.now();
|
||||
@@ -353,13 +355,13 @@ function scheduleReconnect() {
|
||||
showOverlay({
|
||||
title: 'Reconnecting',
|
||||
text: `Connection lost; Claude keeps running on the server. Retrying in ${seconds}s (attempt ${state.attempts}).`,
|
||||
actions: [{ label: 'Retry now', primary: true, run: () => connect(state.session) }, pickerAction],
|
||||
actions: [{ label: 'Retry now', primary: true, run: () => connect(state.session, { reconnect: true }) }, pickerAction],
|
||||
});
|
||||
state.retryTimer = setTimeout(() => connect(state.session), delay);
|
||||
state.retryTimer = setTimeout(() => connect(state.session, { reconnect: true }), delay);
|
||||
}
|
||||
|
||||
function retrySoon() {
|
||||
if (state.retryTimer && !state.conn?.isOpen) connect(state.session);
|
||||
if (state.retryTimer && !state.conn?.isOpen) connect(state.session, { reconnect: true });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- titles & bell
|
||||
@@ -474,6 +476,10 @@ function wireChrome() {
|
||||
setInterval(() => {
|
||||
if (!document.hidden && ui.body.classList.contains('dd-sidebar-open')) refreshAlerts();
|
||||
}, 30 * 1000);
|
||||
// Repo status: on connect, after Claude's turns, and once a minute (devdesk#5, #8).
|
||||
setInterval(() => {
|
||||
if (!document.hidden && ui.body.classList.contains('dd-sidebar-open')) refreshRepo();
|
||||
}, 60 * 1000);
|
||||
ui.attention.addEventListener('click', () => {
|
||||
if (ui.attention.dataset.target) connect(ui.attention.dataset.target);
|
||||
});
|
||||
@@ -500,6 +506,7 @@ async function boot() {
|
||||
term.onBell(() => {
|
||||
notify.ring(state.session, ui.paneTitle.textContent);
|
||||
refreshSoon(); // Claude finished a turn: context numbers just changed
|
||||
setTimeout(refreshRepo, 2000); // …and maybe committed or pushed
|
||||
});
|
||||
|
||||
let fitFrame = 0;
|
||||
@@ -537,14 +544,13 @@ async function boot() {
|
||||
ui.sessionChip.textContent = to;
|
||||
sessionsPanel.setCurrent(to);
|
||||
},
|
||||
onData: () => {
|
||||
showContext();
|
||||
refreshRepo();
|
||||
},
|
||||
onData: () => showContext(),
|
||||
},
|
||||
});
|
||||
bindAskClaude($('sidebar'), (text) => {
|
||||
state.conn?.sendInput(text);
|
||||
// Alert text is untrusted: no control characters (a newline would run it in a
|
||||
// shell window, CR would submit), and bracketed paste around it (devdesk#2).
|
||||
term.paste(pasteSafe(text));
|
||||
term.focus();
|
||||
});
|
||||
wireChrome();
|
||||
|
||||
@@ -67,6 +67,14 @@ export function slugify(text) {
|
||||
.replace(/^[-_]+/, '').replace(/-+$/, '').slice(0, 64);
|
||||
}
|
||||
|
||||
// Untrusted text (e.g. Grafana alert annotations) typed into a terminal: drop
|
||||
// every control character so it can't run a command (newline in a shell),
|
||||
// submit early (CR) or inject escape sequences (devdesk#2).
|
||||
export function pasteSafe(text) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
return String(text ?? '').replace(/[\x00-\x1f\x7f]+/g, ' ');
|
||||
}
|
||||
|
||||
export function stripAnsi(text) {
|
||||
// eslint-disable-next-line no-control-regex
|
||||
return text.replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, '').replace(/\x1b\][^\x07\x1b]*(\x07|\x1b\\)/g, '');
|
||||
|
||||
+14
-2
@@ -3,7 +3,17 @@ import { FitAddon } from '@xterm/addon-fit';
|
||||
import { WebglAddon } from '@xterm/addon-webgl';
|
||||
import { WebLinksAddon } from '@xterm/addon-web-links';
|
||||
import { Unicode11Addon } from '@xterm/addon-unicode11';
|
||||
import { ClipboardAddon } from '@xterm/addon-clipboard';
|
||||
import { Base64, ClipboardAddon } from '@xterm/addon-clipboard';
|
||||
|
||||
// Terminal output (tmux copy-mode, Claude) may *write* the browser clipboard
|
||||
// via OSC 52, but must never read it: anything printed could exfiltrate it (devdesk#7).
|
||||
const writeOnlyClipboard = {
|
||||
readText: () => '',
|
||||
writeText: (selection, text) => {
|
||||
if (selection === 'c') return navigator.clipboard?.writeText(text).catch(() => {});
|
||||
return undefined;
|
||||
},
|
||||
};
|
||||
|
||||
// LotusGuild TDS tokens (web_template base.css :root) mapped onto the ANSI palette.
|
||||
export const THEME = Object.freeze({
|
||||
@@ -62,7 +72,7 @@ export function createTerminal(container, { fontSize, onShiftEnter }) {
|
||||
term.loadAddon(fit);
|
||||
term.loadAddon(new Unicode11Addon());
|
||||
term.unicode.activeVersion = '11';
|
||||
term.loadAddon(new ClipboardAddon()); // OSC 52 from tmux copy-mode / Claude
|
||||
term.loadAddon(new ClipboardAddon(new Base64(), writeOnlyClipboard));
|
||||
term.loadAddon(new WebLinksAddon((event, uri) => {
|
||||
event.preventDefault();
|
||||
window.open(uri, '_blank', 'noopener');
|
||||
@@ -90,6 +100,8 @@ export function createTerminal(container, { fontSize, onShiftEnter }) {
|
||||
|
||||
term.open(container);
|
||||
|
||||
// Touch devices: the DOM renderer is more reliable at high DPR than WebGL.
|
||||
if (window.matchMedia?.('(pointer: coarse)').matches) return { term, fit };
|
||||
try {
|
||||
const webgl = new WebglAddon();
|
||||
webgl.onContextLoss(() => webgl.dispose());
|
||||
|
||||
Reference in New Issue
Block a user