feat(client): upgrade SFTP manager & Tunnels/Proxy panel for v1.1

This commit is contained in:
tyuXX 2026-11-28 05:19:15 +00:00
parent 5b09c8ada1
commit f7d2abe3de
2 changed files with 414 additions and 54 deletions

View file

@ -1,7 +1,15 @@
import { computeLineDiff } from '../../../shared/diff.js'; import { collapseDiffHunks, computeLineDiff } from '../../../shared/diff.js';
import { apiFetch, apiUploadBinary } from '../api.js'; import { apiFetch, apiUploadBinary } from '../api.js';
import { confirmDialog } from '../dialogs.js'; import { confirmDialog } from '../dialogs.js';
import { el, extractErrorMessage, fmtTime, type ClientState, type ServerEntry } from '../state.js'; import {
el,
extractErrorMessage,
fmtTime,
registerViewCleanup,
type ClientState,
type ServerEntry,
} from '../state.js';
import { showToast } from '../toast.js';
import { renderTunnelsPanel } from './tunnels-panel.js'; import { renderTunnelsPanel } from './tunnels-panel.js';
interface SftpEntry { interface SftpEntry {
@ -12,6 +20,9 @@ interface SftpEntry {
mode: number; mode: number;
permissionsOctal: string; permissionsOctal: string;
mtimeMs: number; mtimeMs: number;
uid?: number;
gid?: number;
symlinkTarget?: string;
} }
interface SftpTextPayload { interface SftpTextPayload {
@ -27,6 +38,8 @@ let currentServerId = '';
let currentPath = ''; let currentPath = '';
let activeEdit: SftpTextPayload | null = null; let activeEdit: SftpTextPayload | null = null;
let activeEditSudo = false; let activeEditSudo = false;
let searchMatches: string[] | null = null;
let lastSearchQuery = '';
function fmtFileSize(bytes: number): string { function fmtFileSize(bytes: number): string {
if (!Number.isFinite(bytes) || bytes < 1024) return `${bytes} B`; if (!Number.isFinite(bytes) || bytes < 1024) return `${bytes} B`;
@ -42,16 +55,35 @@ function showSftpDiffDialog(
onConfirm: (force: boolean) => Promise<void>, onConfirm: (force: boolean) => Promise<void>,
): void { ): void {
const diff = computeLineDiff(originalText, nextText, 'remote', 'edited'); const diff = computeLineDiff(originalText, nextText, 'remote', 'edited');
const collapsed = diff.collapsedLines ?? collapseDiffHunks(diff.lines);
const hasHunk = collapsed.some((e) => e.type === 'hunk');
let expanded = !hasHunk;
const dialog = document.createElement('dialog'); const dialog = document.createElement('dialog');
dialog.className = 'dialog-wide'; dialog.className = 'dialog-wide';
dialog.setAttribute('aria-labelledby', 'sftp-diff-title'); dialog.setAttribute('aria-labelledby', 'sftp-diff-title');
const pre = el('pre', { class: 'diff-body mono' }); const pre = el('pre', { class: 'diff-body mono' });
for (const line of diff.lines) { const toggleDiffBtn = el('button', { type: 'button', class: 'btn btn-sm', hidden: !hasHunk }, 'Expand Full Diff');
const cls = line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : ''; const renderDiffBody = () => {
const prefix = line.type === 'add' ? '+' : line.type === 'del' ? '-' : ' '; pre.replaceChildren();
pre.append(el('div', { class: cls }, `${prefix}${line.text}`)); const src = expanded ? diff.lines : collapsed;
for (const entry of src) {
if (entry.type === 'hunk') {
pre.append(el('div', { class: 'diff-hunk-sep' }, entry.text));
} else {
const cls = entry.type === 'add' ? 'diff-add' : entry.type === 'del' ? 'diff-del' : '';
const prefix = entry.type === 'add' ? '+' : entry.type === 'del' ? '-' : ' ';
pre.append(el('div', { class: cls }, `${prefix}${entry.text}`));
} }
}
toggleDiffBtn.textContent = expanded ? 'Collapse Context' : 'Expand Full Diff';
};
toggleDiffBtn.addEventListener('click', () => {
expanded = !expanded;
renderDiffBody();
});
renderDiffBody();
const errEl = el('p', { class: 'form-msg err-text', 'aria-live': 'polite' }); const errEl = el('p', { class: 'form-msg err-text', 'aria-live': 'polite' });
const forceWrap = el('div', { hidden: true }); const forceWrap = el('div', { hidden: true });
@ -83,7 +115,7 @@ function showSftpDiffDialog(
dialog.append( dialog.append(
el('div', { class: 'row-between' }, el('h1', { id: 'sftp-diff-title' }, `Pre-Save Diff: ${filePath}${sudo ? ' [SUDO]' : ''}`), cancelBtn), el('div', { class: 'row-between' }, el('h1', { id: 'sftp-diff-title' }, `Pre-Save Diff: ${filePath}${sudo ? ' [SUDO]' : ''}`), cancelBtn),
el('p', { class: 'mono muted' }, `+${diff.additions} additions, -${diff.deletions} deletions`), el('div', { class: 'row-between' }, el('p', { class: 'mono muted' }, `+${diff.additions} additions, -${diff.deletions} deletions`), toggleDiffBtn),
pre, pre,
errEl, errEl,
el('div', { class: 'dialog-actions' }, forceWrap, writeBtn), el('div', { class: 'dialog-actions' }, forceWrap, writeBtn),
@ -138,9 +170,13 @@ export async function renderSftpView(
return; return;
} }
if (q.server && servers.some((s) => s.config.id === q.server)) { const targetServer = q.server ?? q.serverId;
if (currentServerId !== q.server) currentPath = ''; if (targetServer && servers.some((s) => s.config.id === targetServer)) {
currentServerId = q.server; if (currentServerId !== targetServer) {
currentPath = '';
searchMatches = null;
}
currentServerId = targetServer;
} else if (!currentServerId || !servers.some((s) => s.config.id === currentServerId)) { } else if (!currentServerId || !servers.some((s) => s.config.id === currentServerId)) {
currentServerId = servers[0]!.config.id; currentServerId = servers[0]!.config.id;
} }
@ -185,6 +221,7 @@ export async function renderSftpView(
const goPath = (nextPath: string) => { const goPath = (nextPath: string) => {
currentPath = nextPath; currentPath = nextPath;
activeEdit = null; activeEdit = null;
searchMatches = null;
void renderSftpView(root, state); void renderSftpView(root, state);
}; };
goBtn.addEventListener('click', () => goPath(pathInput.value.trim() || '~')); goBtn.addEventListener('click', () => goPath(pathInput.value.trim() || '~'));
@ -199,6 +236,7 @@ export async function renderSftpView(
refreshBtn.addEventListener('click', () => void renderSftpView(root, state)); refreshBtn.addEventListener('click', () => void renderSftpView(root, state));
const mkdirBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ Folder'); const mkdirBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ Folder');
const touchBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, '+ File');
const uploadInput = el('input', { type: 'file', multiple: true, style: 'display:none' }); const uploadInput = el('input', { type: 'file', multiple: true, style: 'display:none' });
const uploadBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Upload Files'); const uploadBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Upload Files');
uploadBtn.addEventListener('click', () => uploadInput.click()); uploadBtn.addEventListener('click', () => uploadInput.click());
@ -257,6 +295,63 @@ export async function renderSftpView(
} }
}); });
touchBtn.addEventListener('click', async () => {
const name = window.prompt('New empty file name:');
if (!name || !name.trim()) return;
const target = currentPath === '/' ? `/${name.trim()}` : `${currentPath}/${name.trim()}`;
try {
await apiFetch(`/api/servers/${encodeURIComponent(currentServerId)}/sftp/touch`, {
method: 'POST',
body: { path: target },
});
showToast(`Created ${target}`, 'ok');
await renderSftpView(root, state);
} catch (err) {
statusMsg.className = 'form-msg err-text';
statusMsg.textContent = extractErrorMessage(err);
}
});
const searchInput = el('input', {
type: 'search',
class: 'input-sm',
value: lastSearchQuery,
placeholder: 'Search files recursively (e.g. *.conf)...',
'aria-label': 'Search remote files',
}) as HTMLInputElement;
const searchBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Search');
const clearSearchBtn = el('button', { type: 'button', class: 'btn btn-sm', hidden: searchMatches === null }, 'Clear Search');
const runSearch = async () => {
const qStr = searchInput.value.trim();
if (!qStr) return;
lastSearchQuery = qStr;
statusMsg.className = 'form-msg muted';
statusMsg.textContent = `Searching ${currentPath || '/'} for "${qStr}"...`;
try {
const sRes = await apiFetch<{ basePath: string; matches: string[] }>(
`/api/servers/${encodeURIComponent(currentServerId)}/sftp/search?path=${encodeURIComponent(currentPath || '/')}&q=${encodeURIComponent(qStr)}&max=100`,
);
searchMatches = sRes.matches;
await renderSftpView(root, state);
} catch (err) {
statusMsg.className = 'form-msg err-text';
statusMsg.textContent = extractErrorMessage(err);
}
};
searchBtn.addEventListener('click', () => void runSearch());
searchInput.addEventListener('keydown', (ev) => {
if (ev.key === 'Enter') {
ev.preventDefault();
void runSearch();
}
});
clearSearchBtn.addEventListener('click', () => {
searchMatches = null;
lastSearchQuery = '';
void renderSftpView(root, state);
});
const termHref = `#terminal?server=${encodeURIComponent(currentServerId)}&cwd=${encodeURIComponent(currentPath || '~')}`; const termHref = `#terminal?server=${encodeURIComponent(currentServerId)}&cwd=${encodeURIComponent(currentPath || '~')}`;
const archiveAutoHref = `/api/servers/${encodeURIComponent(currentServerId)}/sftp/archive?path=${encodeURIComponent(currentPath || '/')}&format=auto`; const archiveAutoHref = `/api/servers/${encodeURIComponent(currentServerId)}/sftp/archive?path=${encodeURIComponent(currentPath || '/')}&format=auto`;
const archiveGzHref = `/api/servers/${encodeURIComponent(currentServerId)}/sftp/archive?path=${encodeURIComponent(currentPath || '/')}&format=tar.gz`; const archiveGzHref = `/api/servers/${encodeURIComponent(currentServerId)}/sftp/archive?path=${encodeURIComponent(currentPath || '/')}&format=tar.gz`;
@ -292,13 +387,46 @@ export async function renderSftpView(
el('a', { href: archiveAutoHref, class: 'btn btn-sm', download: '' }, 'Archive Folder (.tar.zst/.gz)'), el('a', { href: archiveAutoHref, class: 'btn btn-sm', download: '' }, 'Archive Folder (.tar.zst/.gz)'),
el('a', { href: archiveGzHref, class: 'btn btn-sm', download: '' }, '.tar.gz'), el('a', { href: archiveGzHref, class: 'btn btn-sm', download: '' }, '.tar.gz'),
mkdirBtn, mkdirBtn,
touchBtn,
uploadBtn, uploadBtn,
uploadInput, uploadInput,
), ),
el('div', { class: 'row', style: 'margin-top:8px' }, searchInput, searchBtn, clearSearchBtn),
statusMsg, statusMsg,
); );
root.append(topPanel); root.append(topPanel);
if (searchMatches !== null) {
const sBox = el('section', { class: 'panel stack' });
sBox.append(el('strong', {}, `Search Results for "${lastSearchQuery}" (${searchMatches.length})`));
if (searchMatches.length === 0) {
sBox.append(el('p', { class: 'muted' }, 'No matching files or directories found (max depth 5).'));
} else {
for (const m of searchMatches) {
const openEd = el('button', { type: 'button', class: 'btn btn-sm' }, 'Edit');
openEd.addEventListener('click', async () => {
try {
const loaded = await apiFetch<{ file: SftpTextPayload }>(
`/api/servers/${encodeURIComponent(currentServerId)}/sftp/text?path=${encodeURIComponent(m)}&sudo=0`,
);
activeEditSudo = false;
activeEdit = loaded.file;
await renderSftpView(root, state);
} catch (err) {
showToast(extractErrorMessage(err), 'err');
}
});
const jumpDir = el('button', { type: 'button', class: 'btn btn-sm' }, 'Open Dir');
jumpDir.addEventListener('click', () => {
const idx = m.lastIndexOf('/');
goPath(idx > 0 ? m.slice(0, idx) : '/');
});
sBox.append(el('div', { class: 'row-between' }, el('span', { class: 'mono' }, m), el('div', { class: 'row' }, openEd, jumpDir)));
}
}
root.append(sBox);
}
// Inline Editor with Pre-Save Diff // Inline Editor with Pre-Save Diff
if (activeEdit) { if (activeEdit) {
const editBox = el('section', { class: 'panel' }); const editBox = el('section', { class: 'panel' });
@ -320,8 +448,7 @@ export async function renderSftpView(
} }
}); });
const saveBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Review Diff & Save'); const triggerSaveDiff = () => {
saveBtn.addEventListener('click', () => {
if (!activeEdit) return; if (!activeEdit) return;
showSftpDiffDialog(activeEdit.path, activeEdit.content, textarea.value, activeEditSudo, async (force) => { showSftpDiffDialog(activeEdit.path, activeEdit.content, textarea.value, activeEditSudo, async (force) => {
const res = await apiFetch<{ path: string; sha256: string; size: number }>( const res = await apiFetch<{ path: string; sha256: string; size: number }>(
@ -340,8 +467,18 @@ export async function renderSftpView(
activeEdit = { ...activeEdit!, content: textarea.value, sha256: res.sha256, size: res.size }; activeEdit = { ...activeEdit!, content: textarea.value, sha256: res.sha256, size: res.size };
statusMsg.className = 'form-msg ok-text'; statusMsg.className = 'form-msg ok-text';
statusMsg.textContent = `Saved ${res.path} (${res.size} B)`; statusMsg.textContent = `Saved ${res.path} (${res.size} B)`;
showToast(`Saved ${res.path}`, 'ok');
}); });
}); };
const saveBtn = el('button', { type: 'button', class: 'btn btn-primary btn-sm mutating-action' }, 'Review Diff & Save');
saveBtn.addEventListener('click', triggerSaveDiff);
const onCtrlS = () => {
if (textarea.isConnected && !state.safeMode) triggerSaveDiff();
};
window.addEventListener('gcoord:save', onCtrlS);
registerViewCleanup(() => window.removeEventListener('gcoord:save', onCtrlS));
const closeEdBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close Editor'); const closeEdBtn = el('button', { type: 'button', class: 'btn btn-sm' }, 'Close Editor');
closeEdBtn.addEventListener('click', () => { closeEdBtn.addEventListener('click', () => {
@ -379,6 +516,42 @@ export async function renderSftpView(
} }
}); });
const selectedPaths = new Set<string>();
const bulkDelBtn = el(
'button',
{ type: 'button', class: 'btn btn-sm btn-danger mutating-action', disabled: true },
'Delete Selected (0)',
);
const updateBulkBtn = () => {
bulkDelBtn.textContent = `Delete Selected (${selectedPaths.size})`;
bulkDelBtn.disabled = selectedPaths.size === 0;
};
bulkDelBtn.addEventListener('click', async () => {
if (selectedPaths.size === 0) return;
const ok = await confirmDialog(
'dialog-confirm',
`Bulk delete ${selectedPaths.size} selected item(s)? Directories will be deleted recursively.`,
);
if (!ok) return;
try {
const bRes = await apiFetch<{ deleted: string[]; failed: Array<{ path: string; error: string }> }>(
`/api/servers/${encodeURIComponent(currentServerId)}/sftp/bulk-delete`,
{
method: 'POST',
body: { paths: [...selectedPaths], recursive: true },
},
);
showToast(
`Bulk delete: ${bRes.deleted.length} removed${bRes.failed.length ? `, ${bRes.failed.length} failed` : ''}.`,
bRes.failed.length ? 'warn' : 'ok',
);
await renderSftpView(root, state);
} catch (err) {
statusMsg.className = 'form-msg err-text';
statusMsg.textContent = extractErrorMessage(err);
}
});
const tbl = el('table'); const tbl = el('table');
tbl.append( tbl.append(
el( el(
@ -387,10 +560,11 @@ export async function renderSftpView(
el( el(
'tr', 'tr',
{}, {},
el('th', {}, 'Sel'),
el('th', {}, 'Name'), el('th', {}, 'Name'),
el('th', {}, 'Type'), el('th', {}, 'Type'),
el('th', {}, 'Size'), el('th', {}, 'Size'),
el('th', {}, 'Mode'), el('th', {}, 'Mode / Owner'),
el('th', {}, 'Modified'), el('th', {}, 'Modified'),
el('th', {}, 'Actions'), el('th', {}, 'Actions'),
), ),
@ -401,15 +575,30 @@ export async function renderSftpView(
if (listing.parentPath) { if (listing.parentPath) {
const upBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '.. (Parent Dir)'); const upBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '.. (Parent Dir)');
upBtn.addEventListener('click', () => goPath(listing!.parentPath!)); upBtn.addEventListener('click', () => goPath(listing!.parentPath!));
tbody.append(el('tr', {}, el('td', { colspan: 6 }, upBtn))); tbody.append(el('tr', {}, el('td', { colspan: 7 }, upBtn)));
} }
for (const entry of listing.entries) { for (const entry of listing.entries) {
const selChk = el('input', { type: 'checkbox', 'aria-label': `Select ${entry.name}` }) as HTMLInputElement;
selChk.addEventListener('change', () => {
if (selChk.checked) selectedPaths.add(entry.path);
else selectedPaths.delete(entry.path);
updateBulkBtn();
});
const nameCell = el('td', {}); const nameCell = el('td', {});
if (entry.type === 'dir') { if (entry.type === 'dir') {
const openBtn = el('button', { type: 'button', class: 'btn btn-sm' }, `[DIR] ${entry.name}/`); const openBtn = el('button', { type: 'button', class: 'btn btn-sm' }, `[DIR] ${entry.name}/`);
openBtn.addEventListener('click', () => goPath(entry.path)); openBtn.addEventListener('click', () => goPath(entry.path));
nameCell.append(openBtn); nameCell.append(openBtn);
} else if (entry.type === 'symlink') {
nameCell.append(
el('span', { class: 'badge' }, 'LNK'),
el('span', { class: 'mono', style: 'margin-left:6px' }, entry.name),
entry.symlinkTarget
? el('div', { class: 'mono muted' }, `-> ${entry.symlinkTarget}`)
: '',
);
} else { } else {
nameCell.append(el('span', { class: 'mono' }, entry.name)); nameCell.append(el('span', { class: 'mono' }, entry.name));
} }
@ -466,6 +655,32 @@ export async function renderSftpView(
await renderSftpView(root, state); await renderSftpView(root, state);
}); });
const chownBtn = el('button', { type: 'button', class: 'btn btn-sm mutating-action' }, 'Chown');
chownBtn.addEventListener('click', async () => {
const curOwner = `${entry.uid ?? 0}:${entry.gid ?? 0}`;
const rawOwner = window.prompt('Owner UID:GID (numeric, e.g. 1000:1000):', curOwner);
if (!rawOwner) return;
const parts = rawOwner.trim().split(':');
const uid = Number(parts[0]);
const gid = Number(parts[1] ?? parts[0]);
if (!Number.isInteger(uid) || uid < 0 || !Number.isInteger(gid) || gid < 0) {
showToast('Invalid UID:GID numbers.', 'err');
return;
}
const useSudo = window.confirm('Use sudo chown (requires step-up)? Cancel = normal chown.');
try {
await apiFetch(`/api/servers/${encodeURIComponent(currentServerId)}/sftp/chown`, {
method: 'POST',
body: { path: entry.path, uid, gid, sudo: useSudo },
});
showToast(`Changed owner of ${entry.name} to ${uid}:${gid}`, 'ok');
await renderSftpView(root, state);
} catch (err) {
statusMsg.className = 'form-msg err-text';
statusMsg.textContent = extractErrorMessage(err);
}
});
const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete'); const delBtn = el('button', { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, 'Delete');
delBtn.addEventListener('click', async () => { delBtn.addEventListener('click', async () => {
const ok = await confirmDialog( const ok = await confirmDialog(
@ -482,16 +697,20 @@ export async function renderSftpView(
await renderSftpView(root, state); await renderSftpView(root, state);
}); });
actionsRow.append(renBtn, chmodBtn, delBtn); actionsRow.append(renBtn, chmodBtn, chownBtn, delBtn);
const ownerText =
entry.uid !== undefined && entry.gid !== undefined ? ` (${entry.uid}:${entry.gid})` : '';
tbody.append( tbody.append(
el( el(
'tr', 'tr',
{}, {},
el('td', {}, selChk),
nameCell, nameCell,
el('td', { class: 'mono' }, entry.type), el('td', { class: 'mono' }, entry.type),
el('td', { class: 'mono' }, entry.type === 'dir' ? '—' : fmtFileSize(entry.size)), el('td', { class: 'mono' }, entry.type === 'dir' ? '—' : fmtFileSize(entry.size)),
el('td', { class: 'mono' }, entry.permissionsOctal), el('td', { class: 'mono' }, `${entry.permissionsOctal}${ownerText}`),
el('td', { class: 'mono' }, fmtTime(entry.mtimeMs)), el('td', { class: 'mono' }, fmtTime(entry.mtimeMs)),
el('td', {}, actionsRow), el('td', {}, actionsRow),
), ),
@ -500,7 +719,7 @@ export async function renderSftpView(
tbl.append(tbody); tbl.append(tbody);
dropPanel.append( dropPanel.append(
el('div', { class: 'muted', style: 'margin-bottom:6px' }, 'Tip: Drag files anywhere onto this table to stream upload via SFTP.'), el('div', { class: 'row-between', style: 'margin-bottom:6px' }, el('span', { class: 'muted' }, 'Tip: Drag files anywhere onto this table to stream upload via SFTP.'), bulkDelBtn),
el('div', { class: 'table-wrap' }, tbl), el('div', { class: 'table-wrap' }, tbl),
); );
root.append(dropPanel); root.append(dropPanel);

View file

@ -1,6 +1,13 @@
import { apiFetch } from '../api.js'; import { apiFetch } from '../api.js';
import { confirmDialog } from '../dialogs.js'; import { confirmDialog } from '../dialogs.js';
import { el, extractErrorMessage, fmtTime, type ServerEntry } from '../state.js'; import {
el,
extractErrorMessage,
fmtTime,
registerViewCleanup,
type ServerEntry,
} from '../state.js';
import { showToast } from '../toast.js';
export interface TunnelViewEntry { export interface TunnelViewEntry {
key: string; key: string;
@ -8,11 +15,15 @@ export interface TunnelViewEntry {
tunnel: { tunnel: {
id: string; id: string;
name: string; name: string;
mode: 'http-proxy' | 'local-tcp' | 'remote-tcp'; mode: 'http-proxy' | 'local-tcp' | 'remote-tcp' | 'socks5';
bindHost?: string; bindHost?: string;
bindPort?: number; bindPort?: number;
targetHost: string; targetHost: string;
targetPort: number; targetPort: number;
targetProtocol?: 'http' | 'https';
tlsRejectUnauthorized?: boolean;
tlsServerName?: string;
ttlSec?: number;
autoStart: boolean; autoStart: boolean;
}; };
active: boolean; active: boolean;
@ -20,6 +31,7 @@ export interface TunnelViewEntry {
localBoundPort?: number; localBoundPort?: number;
remoteBoundPort?: number; remoteBoundPort?: number;
proxyPath?: string; proxyPath?: string;
expiresAt?: number;
activeConnections: number; activeConnections: number;
totalConnections: number; totalConnections: number;
bytesIn: number; bytesIn: number;
@ -28,6 +40,13 @@ export interface TunnelViewEntry {
lastError?: string; lastError?: string;
} }
function fmtRemainingSec(sec: number): string {
const s = Math.max(0, Math.floor(sec));
const m = Math.floor(s / 60);
const rem = s % 60;
return m > 0 ? `${m}m ${rem}s` : `${rem}s`;
}
function fmtBytes(bytes: number): string { function fmtBytes(bytes: number): string {
if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'; if (!Number.isFinite(bytes) || bytes <= 0) return '0 B';
if (bytes < 1024) return `${bytes} B`; if (bytes < 1024) return `${bytes} B`;
@ -90,24 +109,71 @@ export async function renderTunnelsPanel(
), ),
); );
const tbody = el('tbody'); const tbody = el('tbody');
const countdownEls: Array<{ el: HTMLElement; expiresAt: number }> = [];
for (const item of tunnels) { for (const item of tunnels) {
const bindInfo = item.proxyPath let bindInfo: HTMLElement;
? el('a', { href: item.proxyPath, target: '_blank', rel: 'noopener', class: 'mono' }, item.proxyPath) if (item.tunnel.mode === 'http-proxy' && item.active) {
: item.tunnel.mode === 'remote-tcp' const launchBtn = el(
? el( 'button',
{ type: 'button', class: 'btn btn-sm btn-primary' },
'Open Isolated Proxy',
);
launchBtn.addEventListener('click', async () => {
launchBtn.disabled = true;
try {
const ticketRes = await apiFetch<{
launchUrl: string;
mode: 'subdomain' | 'port' | 'same-origin';
expiresInSec: number;
}>(
`/api/tunnels/${encodeURIComponent(item.serverId)}/${encodeURIComponent(item.tunnel.id)}/proxy-ticket`,
{ method: 'POST', body: {} },
);
if (ticketRes.mode === 'same-origin') {
showToast(
'Launched via same-origin fallback proxy (isolated subdomain/port offers stronger cookie isolation).',
'warn',
);
}
window.open(ticketRes.launchUrl, '_blank', 'noopener,noreferrer');
} catch (err) {
const msg = extractErrorMessage(err);
statusMsg.className = 'form-msg err-text';
statusMsg.textContent = msg;
showToast(msg, 'err');
} finally {
launchBtn.disabled = false;
}
});
bindInfo = el(
'div',
{ class: 'stack' },
launchBtn,
el(
'span',
{ class: 'mono muted' },
`${item.tunnel.targetProtocol ?? 'http'}:// via ticket`,
),
);
} else if (item.tunnel.mode === 'http-proxy') {
bindInfo = el('span', { class: 'muted mono' }, 'proxy (inactive)');
} else if (item.tunnel.mode === 'remote-tcp') {
bindInfo = el(
'span', 'span',
{ class: 'mono' }, { class: 'mono' },
item.active && item.remoteBoundPort item.active && item.remoteBoundPort
? `${item.localBoundHost ?? '127.0.0.1'}:${item.remoteBoundPort}` ? `${item.localBoundHost ?? '127.0.0.1'}:${item.remoteBoundPort}`
: `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`,
) );
: el( } else {
bindInfo = el(
'span', 'span',
{ class: 'mono' }, { class: 'mono' },
item.active && item.localBoundPort item.active && item.localBoundPort
? `${item.localBoundHost ?? '127.0.0.1'}:${item.localBoundPort}` ? `${item.localBoundHost ?? '127.0.0.1'}:${item.localBoundPort}`
: `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`,
); );
}
const toggleBtn = el( const toggleBtn = el(
'button', 'button',
@ -154,6 +220,15 @@ export async function renderTunnelsPanel(
} }
}); });
let ttlBadge: HTMLElement | string = '';
if (item.active && item.expiresAt) {
const b = el('div', { class: 'badge badge-warn' }, `TTL: ${fmtRemainingSec((item.expiresAt - Date.now()) / 1000)}`);
countdownEls.push({ el: b, expiresAt: item.expiresAt });
ttlBadge = b;
} else if (item.tunnel.ttlSec) {
ttlBadge = el('div', { class: 'muted' }, `TTL: ${item.tunnel.ttlSec}s`);
}
tbody.append( tbody.append(
el( el(
'tr', 'tr',
@ -169,9 +244,16 @@ export async function renderTunnelsPanel(
{}, {},
el('span', { class: `badge ${item.active ? 'badge-ok' : ''}` }, item.tunnel.mode.toUpperCase()), el('span', { class: `badge ${item.active ? 'badge-ok' : ''}` }, item.tunnel.mode.toUpperCase()),
item.tunnel.autoStart ? el('div', { class: 'muted' }, 'auto-start') : '', item.tunnel.autoStart ? el('div', { class: 'muted' }, 'auto-start') : '',
ttlBadge,
), ),
el('td', {}, bindInfo), el('td', {}, bindInfo),
el('td', { class: 'mono' }, `${item.tunnel.targetHost}:${item.tunnel.targetPort}`), el(
'td',
{ class: 'mono' },
item.tunnel.mode === 'socks5'
? 'Dynamic SOCKS5'
: `${item.tunnel.targetProtocol ? `${item.tunnel.targetProtocol}://` : ''}${item.tunnel.targetHost}:${item.tunnel.targetPort}`,
),
el( el(
'td', 'td',
{ class: 'mono' }, { class: 'mono' },
@ -185,6 +267,17 @@ export async function renderTunnelsPanel(
} }
tbl.append(tbody); tbl.append(tbody);
listPanel.append(el('div', { class: 'table-wrap' }, tbl)); listPanel.append(el('div', { class: 'table-wrap' }, tbl));
if (countdownEls.length > 0) {
const ttlTimer = window.setInterval(() => {
const now = Date.now();
for (const row of countdownEls) {
const remSec = Math.max(0, Math.floor((row.expiresAt - now) / 1000));
row.el.textContent = `TTL: ${fmtRemainingSec(remSec)}`;
}
}, 1000);
registerViewCleanup(() => window.clearInterval(ttlTimer));
}
} }
// Add Tunnel Form // Add Tunnel Form
@ -194,7 +287,7 @@ export async function renderTunnelsPanel(
el( el(
'p', 'p',
{ class: 'muted' }, { class: 'muted' },
'http-proxy binds strictly inside 127.0.0.1 and serves behind GCoordinator auth/CSRF/Safe-Mode at /proxy/<id>/.', 'http-proxy serves via short-lived proxy tickets in isolated origin mode (subdomain/port) or same-origin fallback when enabled. socks5 provides dynamic local forwarding without targetPort.',
), ),
); );
@ -213,31 +306,67 @@ export async function renderTunnelsPanel(
const modeSel = el( const modeSel = el(
'select', 'select',
{ name: 'mode' }, { name: 'mode' },
el('option', { value: 'http-proxy' }, 'http-proxy (Zero-Port Web Proxy /proxy/<id>/)'), el('option', { value: 'http-proxy' }, 'http-proxy (Authenticated Web Proxy)'),
el('option', { value: 'local-tcp' }, 'local-tcp (Local Bind -> Target)'), el('option', { value: 'local-tcp' }, 'local-tcp (Local Bind -> Target)'),
el('option', { value: 'remote-tcp' }, 'remote-tcp (Remote Bind -R -> Hub/LAN)'), el('option', { value: 'remote-tcp' }, 'remote-tcp (Remote Bind -R -> Hub/LAN)'),
); el('option', { value: 'socks5' }, 'socks5 (Dynamic Local SOCKS5 Proxy)'),
const targetHostInput = el('input', { name: 'targetHost', value: '127.0.0.1', required: true }); ) as HTMLSelectElement;
const targetHostInput = el('input', { name: 'targetHost', value: '127.0.0.1', required: true }) as HTMLInputElement;
const targetPortInput = el('input', { const targetPortInput = el('input', {
name: 'targetPort', name: 'targetPort',
type: 'number', type: 'number',
min: 1, min: 0,
max: 65535, max: 65535,
value: '3000', value: '3000',
required: true, required: true,
}); }) as HTMLInputElement;
const bindHostInput = el('input', { name: 'bindHost', placeholder: '127.0.0.1 (tcp modes)' }); const protoSel = el(
'select',
{ name: 'targetProtocol' },
el('option', { value: 'http' }, 'http'),
el('option', { value: 'https' }, 'https'),
) as HTMLSelectElement;
const tlsVerifyChk = el('input', { type: 'checkbox', name: 'tlsRejectUnauthorized', checked: true }) as HTMLInputElement;
const tlsSniInput = el('input', { name: 'tlsServerName', placeholder: 'optional TLS SNI host' }) as HTMLInputElement;
const ttlSecInput = el('input', {
name: 'ttlSec',
type: 'number',
min: 60,
max: 86400,
placeholder: 'optional auto-expire (60-86400s)',
}) as HTMLInputElement;
const bindHostInput = el('input', { name: 'bindHost', placeholder: '127.0.0.1 (tcp/socks5)' }) as HTMLInputElement;
const bindPortInput = el('input', { const bindPortInput = el('input', {
name: 'bindPort', name: 'bindPort',
type: 'number', type: 'number',
min: 1, min: 1,
max: 65535, max: 65535,
placeholder: 'auto (tcp modes)', placeholder: 'auto (tcp/socks5)',
}); }) as HTMLInputElement;
const autoStartChk = el('input', { type: 'checkbox', name: 'autoStart' }); const autoStartChk = el('input', { type: 'checkbox', name: 'autoStart' }) as HTMLInputElement;
const startNowChk = el('input', { type: 'checkbox', name: 'startNow', checked: true }); const startNowChk = el('input', { type: 'checkbox', name: 'startNow', checked: true }) as HTMLInputElement;
const formMsg = el('p', { class: 'form-msg' }); const formMsg = el('p', { class: 'form-msg' });
const targetPortWrap = el('div', {}, el('label', {}, 'Target Port'), targetPortInput);
const httpTlsWrap = el(
'div',
{ class: 'grid-3' },
el('div', {}, el('label', {}, 'Upstream Protocol'), protoSel),
el('div', {}, el('label', {}, 'TLS SNI ServerName (HTTPS)'), tlsSniInput),
el('div', { style: 'padding-top:22px' }, el('label', { class: 'chk-row' }, tlsVerifyChk, 'Verify upstream TLS cert')),
);
const syncModeFields = () => {
const m = modeSel.value;
targetPortWrap.hidden = m === 'socks5';
targetPortInput.required = m !== 'socks5';
if (m === 'socks5') targetPortInput.value = '0';
else if (targetPortInput.value === '0') targetPortInput.value = '3000';
httpTlsWrap.hidden = m !== 'http-proxy';
};
modeSel.addEventListener('change', syncModeFields);
syncModeFields();
form.append( form.append(
el( el(
'div', 'div',
@ -247,10 +376,12 @@ export async function renderTunnelsPanel(
el('div', {}, el('label', {}, 'Display Name'), nameInput), el('div', {}, el('label', {}, 'Display Name'), nameInput),
el('div', {}, el('label', {}, 'Mode'), modeSel), el('div', {}, el('label', {}, 'Mode'), modeSel),
el('div', {}, el('label', {}, 'Target Host'), targetHostInput), el('div', {}, el('label', {}, 'Target Host'), targetHostInput),
el('div', {}, el('label', {}, 'Target Port'), targetPortInput), targetPortWrap,
el('div', {}, el('label', {}, 'Bind Host (TCP only)'), bindHostInput), el('div', {}, el('label', {}, 'Bind Host (TCP/SOCKS5)'), bindHostInput),
el('div', {}, el('label', {}, 'Bind Port (TCP only)'), bindPortInput), el('div', {}, el('label', {}, 'Bind Port (TCP/SOCKS5)'), bindPortInput),
el('div', {}, el('label', {}, 'TTL Seconds (Optional)'), ttlSecInput),
), ),
httpTlsWrap,
el( el(
'div', 'div',
{ class: 'row' }, { class: 'row' },
@ -271,10 +402,12 @@ export async function renderTunnelsPanel(
return; return;
} }
const mode = modeSel.value as 'http-proxy' | 'local-tcp' | 'remote-tcp'; const mode = modeSel.value as 'http-proxy' | 'local-tcp' | 'remote-tcp' | 'socks5';
const bindHost = bindHostInput.value.trim() || undefined; const bindHost = bindHostInput.value.trim() || undefined;
const bindPortVal = bindPortInput.value.trim(); const bindPortVal = bindPortInput.value.trim();
const bindPort = bindPortVal ? Number(bindPortVal) : undefined; const bindPort = bindPortVal ? Number(bindPortVal) : undefined;
const ttlVal = ttlSecInput.value.trim();
const ttlSec = ttlVal ? Number(ttlVal) : undefined;
try { try {
const res = await apiFetch<{ startError?: string }>('/api/tunnels', { const res = await apiFetch<{ startError?: string }>('/api/tunnels', {
@ -286,7 +419,13 @@ export async function renderTunnelsPanel(
name: nameInput.value.trim(), name: nameInput.value.trim(),
mode, mode,
targetHost: targetHostInput.value.trim() || '127.0.0.1', targetHost: targetHostInput.value.trim() || '127.0.0.1',
targetPort: Number(targetPortInput.value), targetPort: mode === 'socks5' ? 0 : Number(targetPortInput.value),
targetProtocol: mode === 'http-proxy' ? protoSel.value : 'http',
tlsRejectUnauthorized: mode === 'http-proxy' ? tlsVerifyChk.checked : true,
...(mode === 'http-proxy' && tlsSniInput.value.trim()
? { tlsServerName: tlsSniInput.value.trim() }
: {}),
...(ttlSec !== undefined ? { ttlSec } : {}),
bindHost: mode === 'http-proxy' ? undefined : bindHost, bindHost: mode === 'http-proxy' ? undefined : bindHost,
bindPort: mode === 'http-proxy' ? undefined : bindPort, bindPort: mode === 'http-proxy' ? undefined : bindPort,
autoStart: autoStartChk.checked, autoStart: autoStartChk.checked,
@ -297,6 +436,8 @@ export async function renderTunnelsPanel(
if (res.startError) { if (res.startError) {
statusMsg.className = 'form-msg warn-text'; statusMsg.className = 'form-msg warn-text';
statusMsg.textContent = `Saved, but start failed: ${res.startError}`; statusMsg.textContent = `Saved, but start failed: ${res.startError}`;
} else {
showToast('Tunnel saved.', 'ok');
} }
await renderTunnelsPanel(root, fixedServerId); await renderTunnelsPanel(root, fixedServerId);
} catch (err) { } catch (err) {