File size: 15,552 Bytes
b64654b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 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 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 | /* ββ State βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
let token = sessionStorage.getItem('shellular_token') || null;
let evtSource = null;
let fullOutput = '';
let shellStatus = 'stopped';
let qrRendered = false;
/* ββ DOM helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
const $ = (id) => document.getElementById(id);
const loginPage = $('login-page');
const dashPage = $('dashboard-page');
const loginForm = $('login-form');
const keyInput = $('key-input');
const loginBtn = $('login-btn');
const loginLabel = $('login-label');
const loginSpinner = $('login-spinner');
const loginError = $('login-error');
const toggleVisBtn = $('toggle-vis');
const eyeOpen = $('eye-open');
const eyeClosed = $('eye-closed');
const statusBadge = $('status-badge');
const restartBtn = $('restart-btn');
const logoutBtn = $('logout-btn');
const clearLogBtn = $('clear-log-btn');
const qrLoading = $('qr-loading');
const qrReady = $('qr-ready');
const qrError = $('qr-error');
const qrErrorMsg = $('qr-error-msg');
const qrCanvas = $('qr-canvas');
const logPre = $('log-pre');
/* ββ Routing βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
function showLogin() {
loginPage.classList.remove('hidden');
dashPage.classList.add('hidden');
keyInput.focus();
}
function showDashboard() {
loginPage.classList.add('hidden');
dashPage.classList.remove('hidden');
connectStream();
ensureShellularRunning(); // always start shellular, whether fresh login or returning session
}
/* ββ Password visibility toggle ββββββββββββββββββββββββββββββββββββββββββββ */
toggleVisBtn.addEventListener('click', () => {
const isPassword = keyInput.type === 'password';
keyInput.type = isPassword ? 'text' : 'password';
eyeOpen.classList.toggle('hidden', isPassword);
eyeClosed.classList.toggle('hidden', !isPassword);
});
/* ββ Login βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
loginForm.addEventListener('submit', async (e) => {
e.preventDefault();
const key = keyInput.value.trim();
if (!key) return;
loginBtn.disabled = true;
loginLabel.classList.add('hidden');
loginSpinner.classList.remove('hidden');
loginError.classList.add('hidden');
try {
const res = await fetch('/api/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ key }),
});
const data = await res.json();
if (!res.ok) {
throw new Error(data.error || 'Login failed');
}
token = data.token;
sessionStorage.setItem('shellular_token', token);
keyInput.value = '';
showDashboard();
} catch (err) {
loginError.textContent = err.message;
loginError.classList.remove('hidden');
} finally {
loginBtn.disabled = false;
loginLabel.classList.remove('hidden');
loginSpinner.classList.add('hidden');
}
});
/* ββ Logout ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
logoutBtn.addEventListener('click', async () => {
if (evtSource) { evtSource.close(); evtSource = null; }
await fetch('/api/logout', {
method: 'POST',
headers: { Authorization: `Bearer ${token}` },
}).catch(() => {});
token = null;
sessionStorage.removeItem('shellular_token');
fullOutput = '';
logPre.textContent = '';
qrPre.textContent = '';
showLogin();
});
/* ββ SSE stream ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
function connectStream() {
if (evtSource) { evtSource.close(); }
evtSource = new EventSource(`/api/stream?t=${Date.now()}`, {});
// EventSource doesn't support custom headers, so we pass the token
// as a cookie or query param workaround via a short-lived fetch first.
// Instead, we do: close the native EventSource approach and use fetch-based SSE.
evtSource.close();
evtSource = null;
startFetchSSE();
}
async function startFetchSSE() {
try {
const res = await fetch('/api/stream', {
headers: { Authorization: `Bearer ${token}` },
cache: 'no-store',
});
if (res.status === 401) {
sessionStorage.removeItem('shellular_token');
token = null;
showLogin();
return;
}
if (!res.ok || !res.body) {
setTimeout(startFetchSSE, 3000);
return;
}
const reader = res.body.getReader();
const decoder = new TextDecoder();
let partial = '';
while (true) {
const { value, done } = await reader.read();
if (done) break;
partial += decoder.decode(value, { stream: true });
const parts = partial.split('\n\n');
partial = parts.pop(); // keep incomplete last chunk
for (const part of parts) {
const line = part.trim();
if (!line.startsWith('data:')) continue;
try {
const payload = JSON.parse(line.slice(5).trim());
handleEvent(payload);
} catch { /* ignore parse errors */ }
}
}
} catch {
// Connection dropped β retry after 2s
}
setTimeout(startFetchSSE, 2000);
}
/* ββ Event handler βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
function handleEvent(payload) {
if (payload.type === 'status') {
updateStatus(payload.status);
} else if (payload.type === 'output') {
appendOutput(payload.text);
} else if (payload.type === 'clear') {
fullOutput = '';
logPre.textContent = '';
qrRendered = false;
setQrState('loading');
}
}
/* ββ Status display ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
function updateStatus(status) {
shellStatus = status;
const labels = {
running: 'Running',
starting: 'Starting',
retrying: 'Retryingβ¦',
stopped: 'Stopped',
error: 'Error',
};
statusBadge.textContent = labels[status] || status;
statusBadge.className = `badge badge-${status}`;
if (status === 'retrying') {
if (!qrRendered) setQrState('loading');
return; // keep showing the spinner while we wait
}
if (status === 'stopped' || status === 'error') {
if (!qrRendered) {
setQrState('error');
qrErrorMsg.textContent =
status === 'error'
? 'Shellular failed to start. Check the output log for details.'
: 'Shellular stopped. Click "Try again" to restart.';
}
}
if (status === 'starting') {
if (!qrRendered) setQrState('loading');
}
// Once shellular is running, fetch the QR data and render it
if (status === 'running' && !qrRendered) {
fetchAndRenderQR();
}
}
/* ββ QR state machine ββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
function setQrState(state) {
qrLoading.classList.toggle('hidden', state !== 'loading');
qrReady.classList.toggle('hidden', state !== 'ready');
qrError.classList.toggle('hidden', state !== 'error');
}
/* ββ QR rendering ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
async function fetchAndRenderQR() {
for (let i = 0; i < 8; i++) {
await new Promise(r => setTimeout(r, i === 0 ? 1000 : 2500));
try {
const res = await authFetch('/api/shellular/qr-data');
if (!res || !res.ok) continue;
const json = await res.json();
const qrData = json.qrData;
if (!qrData) continue;
// Show the container FIRST so the div has real dimensions when QRCode renders
setQrState('ready');
// Wipe any previous render
qrCanvas.innerHTML = '';
new QRCode(qrCanvas, {
text: qrData,
width: 220,
height: 220,
colorDark: '#000000',
colorLight: '#ffffff',
correctLevel: QRCode.CorrectLevel.M,
});
qrRendered = true;
return;
} catch (err) {
console.warn('fetchAndRenderQR attempt', i, err);
}
}
if (!qrRendered) {
setQrState('error');
qrErrorMsg.textContent = 'Could not render QR. Try restarting.';
}
}
/* ββ Output processing βββββββββββββββββββββββββββββββββββββββββββββββββββββ */
function appendOutput(text) {
if (!text) return;
fullOutput += text;
logPre.textContent = fullOutput;
logPre.scrollTop = logPre.scrollHeight;
// Show manual registration card as soon as rate-limit message appears
if (text.includes('rate-limited') || text.includes('Registration rate-limited')) {
rateLimitCount++;
if (rateLimitCount >= 1) loadManualCard();
}
}
/* ββ Controls ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
restartBtn.addEventListener('click', restartShellular);
async function restartShellular() {
fullOutput = '';
logPre.textContent = '';
qrRendered = false;
setQrState('loading');
await authFetch('/api/shellular/restart', 'POST');
}
clearLogBtn.addEventListener('click', () => {
logPre.textContent = '';
});
async function authFetch(url, method = 'GET') {
const res = await fetch(url, {
method,
headers: { Authorization: `Bearer ${token}` },
});
if (res.status === 401) {
token = null;
sessionStorage.removeItem('shellular_token');
showLogin();
}
return res;
}
/* ββ Manual registration fallback βββββββββββββββββββββββββββββββββββββββββ */
const manualCard = $('manual-reg-card');
const manualCurlCmd = $('manual-curl-cmd');
const manualHostInput = $('manual-host-id');
const manualSubmitBtn = $('manual-submit-btn');
const manualError = $('manual-error');
let rateLimitCount = 0;
let machineIdLoaded = false;
async function loadManualCard() {
if (machineIdLoaded) { manualCard.classList.remove('hidden'); return; }
try {
const res = await fetch('/api/shellular/machine-id');
const { machineId } = await res.json();
const cmd = `curl -s -X POST "https://api.shellular.dev/register" -H "Content-Type: application/json" -d '{"machineId":"${machineId}","platform":"linux"}'`;
manualCurlCmd.textContent = cmd;
machineIdLoaded = true;
manualCard.classList.remove('hidden');
} catch { /* silent */ }
}
manualSubmitBtn.addEventListener('click', async () => {
const hostId = manualHostInput.value.trim();
if (!hostId) {
manualError.textContent = 'Please enter the hostId from the curl response.';
manualError.classList.remove('hidden');
return;
}
manualError.classList.add('hidden');
manualSubmitBtn.disabled = true;
manualSubmitBtn.textContent = 'Connectingβ¦';
try {
const r = await fetch('/api/shellular/seed-host', {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
body: JSON.stringify({ hostId }),
});
const data = await r.json();
if (!r.ok) throw new Error(data.error || 'Failed');
manualCard.classList.add('hidden');
rateLimitCount = 0;
// shellular is restarting β clear output and show loading
fullOutput = '';
logPre.textContent = '';
qrRendered = false;
setQrState('loading');
} catch (err) {
manualError.textContent = err.message;
manualError.classList.remove('hidden');
} finally {
manualSubmitBtn.disabled = false;
manualSubmitBtn.textContent = 'Connect';
}
});
/* ββ First-time setup panel ββββββββββββββββββββββββββββββββββββββββββββββββ */
const setupCard = $('setup-card');
let setupDone = false; // true once panel is shown OR secrets are already seeded
async function checkSetup() {
if (setupDone || !token) return;
try {
const r1 = await authFetch('/api/setup-status');
if (!r1 || !r1.ok) return;
const { seeded } = await r1.json();
if (seeded) { setupDone = true; return; } // secrets already saved
// Try to read credentials (shellular must have registered first)
const r2 = await authFetch('/api/shellular/credentials');
if (!r2 || !r2.ok) return; // not ready yet β poll will retry
const data = await r2.json();
if (!data.hostId) return;
// Populate and show the panel
$('val-host-id').textContent = data.hostId;
$('val-machine-id').textContent = data.machineId;
$('val-key').textContent = data.keyB64;
setupCard.classList.remove('hidden');
setupDone = true;
} catch { /* retry on next poll */ }
}
// Poll every 4 s so the panel appears as soon as credentials are available,
// regardless of whether the QR has rendered yet.
setInterval(checkSetup, 4000);
// Copy-to-clipboard buttons
document.addEventListener('click', (e) => {
const btn = e.target.closest('.btn-copy');
if (!btn) return;
const val = $( btn.dataset.target )?.textContent || '';
navigator.clipboard.writeText(val).then(() => {
btn.textContent = 'Copied!';
btn.classList.add('copied');
setTimeout(() => { btn.textContent = 'Copy'; btn.classList.remove('copied'); }, 2000);
});
});
/* ββ Kick off shellular automatically after login ββββββββββββββββββββββββββ */
async function ensureShellularRunning() {
const res = await authFetch('/api/status');
if (!res) return;
const { running } = await res.json();
if (!running) {
await authFetch('/api/shellular/start', 'POST');
}
}
/* ββ Init ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ */
// If we have a stored token, try to go straight to the dashboard
if (token) {
fetch('/api/status', { headers: { Authorization: `Bearer ${token}` } })
.then((r) => {
if (r.status === 401) {
token = null;
sessionStorage.removeItem('shellular_token');
showLogin();
} else {
showDashboard();
}
})
.catch(() => showLogin());
} else {
showLogin();
}
// Expose for inline onclick in HTML
window.restartShellular = restartShellular;
|