Remote: paste the phone clipboard, including images, on the desktop
CI / test (push) Failing after 1m2s

- Web UI: Ctrl+V, Ctrl+Shift+V, Shift+Insert (Cmd+V on Mac) and a Paste button send the phone clipboard (text or PNG, up to 16 MB) to the desktop over POST /api/clipboard
- chandra-remote passes clipboard data to the compositor in a sealed memfd (clipboard-set-fd), replacing the 4 KB hex clipboard-set line
- Compositor: new clipboard-status and input-paste commands; text is typed into the launcher, password dialog and shell popups, otherwise the paste chord is sent (Ctrl+Shift+V in terminals)
- Paste data is captured when a paste starts, so a clipboard change mid-transfer can't corrupt it
- VNC clipboard text limit raised from 4 KB to 1 MB
- Upload endpoints are authorized with the same token check as /ws; the no-header cross-site case is refused with 403
This commit is contained in:
nandi committed 2026-11-29 15:42:46 -08:00
1 parent 8a6d19d16f
commit d2e00b4658
11 files changed
+853 -68

No files matched your search

+292 -8
View File
@@ -87,6 +87,20 @@
position: fixed; left: -9999px; top: 0; width: 1px; height: 1px;
opacity: 0; border: 0; padding: 0; font-size: 16px;
}
#pasteSink {
position: fixed; left: -9999px; top: 0; width: 1px; height: 1px;
overflow: hidden; opacity: 0; outline: 0;
user-select: text; -webkit-user-select: text;
}
#toast {
position: fixed; left: 50%; bottom: calc(64px + env(safe-area-inset-bottom));
transform: translateX(-50%); z-index: 40; display: none;
max-width: calc(100vw - 32px); padding: 8px 14px; border-radius: 999px;
background: var(--panel); border: 1px solid var(--border);
font-size: 13px; pointer-events: none;
}
#toast.open { display: block; }
#toast.err { border-color: var(--err); }
#loginMask {
position: fixed; inset: 0; z-index: 50; display: none;
align-items: center; justify-content: center; padding: 20px;
@@ -142,6 +156,7 @@
</div>
<div class="row">
<button id="clipBtn" class="btn">Send Clipboard</button>
<button id="imgBtn" class="btn">Paste Image…</button>
<button id="fsBtn" class="btn">Fullscreen</button>
<button class="btn" data-ctl="refresh">Redraw</button>
</div>
@@ -169,6 +184,9 @@
<button id="kbHideBtn" class="btn">Done</button>
</div>
<input id="kbdInput" type="text" value=" " autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">
<div id="pasteSink" contenteditable="true" inputmode="none" tabindex="-1" aria-hidden="true"></div>
<input id="imgInput" type="file" accept="image/*" hidden>
<div id="toast" role="status"></div>
<div id="loginMask">
<form id="loginForm" class="card">
@@ -202,6 +220,9 @@
const loginForm = document.getElementById('loginForm');
const passInput = document.getElementById('passInput');
const loginErr = document.getElementById('loginErr');
const pasteSink = document.getElementById('pasteSink');
const imgInput = document.getElementById('imgInput');
const toastEl = document.getElementById('toast');
let ws = null;
let token = localStorage.getItem('chandra_remote_token') || '';
@@ -214,7 +235,20 @@
let keyHandled = false;
let lastPtrSent = 0;
/* While a paste is uploading, typing waits for it, so "Ctrl+V, Enter" arrives in that order. */
const HELD_WHILE_PASTING = new Set(['key', 'ktap', 'text', 'release']);
let pastesInFlight = 0;
let heldMessages = [];
function sendJson(obj) {
if (pastesInFlight > 0 && HELD_WHILE_PASTING.has(obj.t)) {
heldMessages.push(obj);
return;
}
sendNow(obj);
}
function sendNow(obj) {
if (ws && ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(obj));
}
@@ -308,6 +342,7 @@
sock.onopen = () => {
setStatusDot('ok', 'Connected');
noteClipboardBase();
loginMask.classList.remove('open');
};
sock.onmessage = (ev) => {
@@ -572,6 +607,7 @@
if (loginMask.classList.contains('open')) return;
if (e.target === passInput || e.target === briSlider || e.target === kbdInput) return;
if (e.isComposing || e.key === 'Unidentified' || e.key === 'Process' || e.key === 'Dead') return;
if (beginKeyPaste(e)) return;
const sym = eventToKeysym(e);
if (sym !== null) {
e.preventDefault();
@@ -599,10 +635,241 @@
});
window.addEventListener('blur', releaseAllKeys);
window.addEventListener('focus', noteClipboardBase);
document.addEventListener('visibilitychange', () => {
if (document.hidden) releaseAllKeys();
else noteClipboardBase();
});
/* ---- Paste: this device's clipboard (text or image) into the phone ----
The paste keys put the local clipboard on the phone's, then send the same keys there. The
clipboard comes from the browser's paste event, which needs no permission and works over
plain HTTP. Something copied on the phone since this page was focused is newer than the
local clipboard, and is pasted as it is. */
const PASTE_MAX = 16 * 1024 * 1024;
const IS_MAC = /Mac|iPhone|iPad/.test(navigator.platform || '');
let clipBase = null; /* phone clipboard serial when this page was last focused */
let clipLastSig = null; /* the local clipboard last sent, or passed over for the phone's */
let pasteChain = Promise.resolve();
let keyPaste = null; /* paste keys pressed, paste event not seen yet */
let keyPasteMissed = 0; /* when the last one was given up on */
let toastTimer = null;
function toast(msg, isErr) {
clearTimeout(toastTimer);
toastEl.textContent = msg;
toastEl.classList.toggle('err', !!isErr);
toastEl.classList.add('open');
toastTimer = setTimeout(() => toastEl.classList.remove('open'), isErr ? 5000 : 1800);
}
async function clipboardApi(method, type, body) {
const headers = { 'X-Chandra-Remote': '1' };
if (token) headers['Authorization'] = 'Bearer ' + token;
if (type) headers['Content-Type'] = type;
const ctl = new AbortController();
const timer = setTimeout(() => ctl.abort(), method === 'GET' ? 4000 : 45000);
try {
const r = await fetch('/api/clipboard', { method, headers, body, cache: 'no-store', signal: ctl.signal });
const d = await r.json();
if (!r.ok || !d.ok) throw new Error(d.error || ('HTTP ' + r.status));
return d.serial;
} finally {
clearTimeout(timer);
}
}
function noteClipboardBase() {
if (!ws || ws.readyState !== WebSocket.OPEN) return;
pasteChain = pasteChain.then(async () => {
try {
const s = await clipboardApi('GET');
if (clipBase !== null && s < clipBase) clipLastSig = null; /* the desktop restarted */
clipBase = s;
} catch (_) {}
});
}
/* {type, blob, text, sig} of some text or an image file; images become PNG. */
async function makePayload(text, image) {
let blob, type;
if (image) {
type = 'image/png';
blob = image;
if (image.type !== 'image/png') {
let bmp;
try {
bmp = await createImageBitmap(image);
} catch (_) {
throw new Error('This image format can\'t be read');
}
const cv = document.createElement('canvas');
cv.width = bmp.width;
cv.height = bmp.height;
cv.getContext('2d').drawImage(bmp, 0, 0);
bmp.close();
blob = await new Promise(res => cv.toBlob(res, 'image/png'));
if (!blob) throw new Error('This image is too big');
}
} else {
type = 'text/plain';
blob = new Blob([text.replace(/\r\n?/g, '\n')], { type });
}
if (blob.size > PASTE_MAX) throw new Error('Too large to paste (16 MB at most)');
const bytes = new Uint8Array(await blob.arrayBuffer());
let h = 0x811c9dc5;
for (let i = 0; i < bytes.length; i++) h = Math.imul(h ^ bytes[i], 0x01000193);
return { type, blob, text, sig: type + ':' + bytes.length + ':' + (h >>> 0) };
}
/* Send it to the phone's clipboard, unless (not `force`) the phone's own is the one to paste. */
async function syncClipboard(p, force) {
if (!force) {
if (p.sig === clipLastSig) return false;
if (clipBase !== null && await clipboardApi('GET') !== clipBase) {
clipLastSig = p.sig;
return false;
}
}
clipBase = await clipboardApi('POST', p.type, p.blob);
clipLastSig = p.sig;
if (p.type === 'image/png') {
const kb = p.blob.size / 1024;
toast('Image sent (' + (kb < 1024 ? Math.ceil(kb) + ' KB' : (kb / 1024).toFixed(1) + ' MB') + ')');
}
return true;
}
function holdTyping() { pastesInFlight++; }
function releaseTyping() {
if (--pastesInFlight > 0) return;
const queue = heldMessages;
heldMessages = [];
queue.forEach(sendNow);
}
/* Paste text or an image. `chord` is {c, m} (evdev code, modifiers), or null for whatever the
focused app uses. Typing must be held by the caller; it is released here. */
function runPaste(text, image, chord, force) {
pasteChain = pasteChain.then(async () => {
let p = null;
try {
if (text || image) {
p = await makePayload(text, image);
await syncClipboard(p, force);
}
sendNow(chord ? { t: 'paste', c: chord.c, m: chord.m } : { t: 'paste' });
} catch (err) {
/* Never paste what was on the phone's clipboard before in its place. */
toast('Paste failed: ' + (err.name === 'AbortError' ? 'timed out' : err.message), true);
} finally {
releaseTyping();
}
});
}
function pasteChord(e) {
if (e.altKey) return null;
const isV = e.key.toLowerCase() === 'v' || (e.code === 'KeyV' && e.key.charCodeAt(0) > 0x7F);
if (isV && (IS_MAC ? e.metaKey && !e.ctrlKey : e.ctrlKey && !e.metaKey)) {
return { c: 47, m: e.shiftKey ? 5 : 4 };
}
if (!IS_MAC && e.key === 'Insert' && e.shiftKey && !e.ctrlKey && !e.metaKey) return { c: 110, m: 1 };
return null;
}
/* A paste key press: let the browser do its paste, into the sink, and pick up the event. */
function beginKeyPaste(e) {
const chord = pasteChord(e);
if (!chord) return false;
if (e.repeat || keyPaste) {
e.preventDefault();
return true;
}
if (IS_MAC) {
/* Command is held on the phone as Super: let go of it, without it counting as a Super tap. */
for (const [id, sym] of [...pressedKeys]) {
if (sym === 0xFFEB || sym === 0xFFEC) {
pressedKeys.delete(id);
sendJson({ t: 'ktap', c: 29, m: 0 });
sendJson({ t: 'key', k: sym, d: 0 });
}
}
}
const back = document.activeElement === kbdInput ? kbdInput : null;
holdTyping();
pasteSink.textContent = '';
pasteSink.focus({ preventScroll: true });
keyPaste = {
chord, back,
timer: setTimeout(() => {
/* No paste event (nothing the browser can paste): the phone's own clipboard then. */
const k = endKeyPaste();
keyPasteMissed = performance.now();
runPaste('', null, k.chord, false);
}, 600)
};
return true;
}
function endKeyPaste() {
const k = keyPaste;
keyPaste = null;
clearTimeout(k.timer);
pasteSink.textContent = '';
if (k.back) k.back.focus();
else pasteSink.blur();
return k;
}
function pickFromTransfer(dt) {
let image = null;
for (const it of dt ? dt.items : []) {
if (it.kind === 'file' && it.type.startsWith('image/')) { image = it.getAsFile(); break; }
}
let text = dt ? dt.getData('text/plain') : '';
/* A copied image file also comes with its name or path as text. */
if (image && text && image.name && text.trim().endsWith(image.name) && !text.trim().includes('\n')) text = '';
return text ? [text, null] : ['', image];
}
document.addEventListener('paste', (e) => {
if (loginMask.classList.contains('open') || e.target === passInput) return;
e.preventDefault();
const [text, image] = pickFromTransfer(e.clipboardData);
if (keyPaste) {
const k = endKeyPaste();
runPaste(text, image, k.chord, false);
} else if (performance.now() - keyPasteMissed > 2000 && (text || image)) {
holdTyping();
runPaste(text, image, null, true); /* the browser's own Paste menu item */
}
});
/* For the buttons: [text, image] from the async clipboard API, or text asked for. */
async function readLocalClipboard(question) {
if (navigator.clipboard && navigator.clipboard.read) {
try {
const items = await navigator.clipboard.read();
for (const it of items) {
if (it.types.includes('text/plain')) {
const t = await (await it.getType('text/plain')).text();
if (t) return [t, null];
}
}
for (const it of items) {
const ty = it.types.find(x => x.startsWith('image/'));
if (ty) return ['', await it.getType(ty)];
}
} catch (_) {}
}
try {
const t = await navigator.clipboard.readText();
if (t) return [t, null];
} catch (_) {}
return [prompt(question) || '', null];
}
/* ---- Android Gboard sentinel-space keyboard bridge ---- */
function setKbOpen(open) {
kbOpen = open;
@@ -660,6 +927,7 @@
kbdInput.addEventListener('keydown', (e) => {
keyHandled = false;
if (beginKeyPaste(e)) return;
const map = {
Enter: 28, Backspace: 14, Tab: 15, Escape: 1, Delete: 111,
ArrowLeft: 105, ArrowUp: 103, ArrowRight: 106, ArrowDown: 108,
@@ -751,17 +1019,33 @@
});
document.getElementById('clipBtn').addEventListener('click', async () => {
let txt = '';
try { txt = await navigator.clipboard.readText(); } catch (_) {}
if (!txt) txt = prompt('Text to copy to phone clipboard:') || '';
if (txt) sendJson({ t: 'clip', s: txt });
const [text, image] = await readLocalClipboard('Text to copy to phone clipboard:');
if (!text && !image) return;
try {
const p = await makePayload(text, image);
await syncClipboard(p, true);
if (!image) toast('Clipboard sent');
} catch (err) {
toast('Send failed: ' + err.message, true);
}
});
document.getElementById('imgBtn').addEventListener('click', () => imgInput.click());
imgInput.addEventListener('change', () => {
const f = imgInput.files[0];
imgInput.value = '';
if (!f) return;
drawer.classList.remove('open');
holdTyping();
runPaste('', f, null, true);
});
document.getElementById('pasteBtn').addEventListener('click', async () => {
let txt = '';
try { txt = await navigator.clipboard.readText(); } catch (_) {}
if (!txt) txt = prompt('Text to type on phone:') || '';
if (txt) sendJson({ t: 'text', s: txt });
const [text, image] = await readLocalClipboard('Text to paste on phone:');
if (text || image) {
holdTyping();
runPaste(text, image, null, true);
}
kbdInput.focus();
});