From f7d2abe3de56a2a4af5f82a59ba45d8040fb58f3 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Sat, 28 Nov 2026 05:19:15 +0000 Subject: [PATCH] feat(client): upgrade SFTP manager & Tunnels/Proxy panel for v1.1 --- src/client/ts/views/sftp-view.ts | 257 +++++++++++++++++++++++++-- src/client/ts/views/tunnels-panel.ts | 211 ++++++++++++++++++---- 2 files changed, 414 insertions(+), 54 deletions(-) diff --git a/src/client/ts/views/sftp-view.ts b/src/client/ts/views/sftp-view.ts index 3359bf3..585203d 100644 --- a/src/client/ts/views/sftp-view.ts +++ b/src/client/ts/views/sftp-view.ts @@ -1,7 +1,15 @@ -import { computeLineDiff } from '../../../shared/diff.js'; +import { collapseDiffHunks, computeLineDiff } from '../../../shared/diff.js'; import { apiFetch, apiUploadBinary } from '../api.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'; interface SftpEntry { @@ -12,6 +20,9 @@ interface SftpEntry { mode: number; permissionsOctal: string; mtimeMs: number; + uid?: number; + gid?: number; + symlinkTarget?: string; } interface SftpTextPayload { @@ -27,6 +38,8 @@ let currentServerId = ''; let currentPath = ''; let activeEdit: SftpTextPayload | null = null; let activeEditSudo = false; +let searchMatches: string[] | null = null; +let lastSearchQuery = ''; function fmtFileSize(bytes: number): string { if (!Number.isFinite(bytes) || bytes < 1024) return `${bytes} B`; @@ -42,16 +55,35 @@ function showSftpDiffDialog( onConfirm: (force: boolean) => Promise, ): void { 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'); dialog.className = 'dialog-wide'; dialog.setAttribute('aria-labelledby', 'sftp-diff-title'); const pre = el('pre', { class: 'diff-body mono' }); - for (const line of diff.lines) { - const cls = line.type === 'add' ? 'diff-add' : line.type === 'del' ? 'diff-del' : ''; - const prefix = line.type === 'add' ? '+' : line.type === 'del' ? '-' : ' '; - pre.append(el('div', { class: cls }, `${prefix}${line.text}`)); - } + const toggleDiffBtn = el('button', { type: 'button', class: 'btn btn-sm', hidden: !hasHunk }, 'Expand Full Diff'); + const renderDiffBody = () => { + pre.replaceChildren(); + 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 forceWrap = el('div', { hidden: true }); @@ -83,7 +115,7 @@ function showSftpDiffDialog( dialog.append( 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, errEl, el('div', { class: 'dialog-actions' }, forceWrap, writeBtn), @@ -138,9 +170,13 @@ export async function renderSftpView( return; } - if (q.server && servers.some((s) => s.config.id === q.server)) { - if (currentServerId !== q.server) currentPath = ''; - currentServerId = q.server; + const targetServer = q.server ?? q.serverId; + if (targetServer && servers.some((s) => s.config.id === targetServer)) { + if (currentServerId !== targetServer) { + currentPath = ''; + searchMatches = null; + } + currentServerId = targetServer; } else if (!currentServerId || !servers.some((s) => s.config.id === currentServerId)) { currentServerId = servers[0]!.config.id; } @@ -185,6 +221,7 @@ export async function renderSftpView( const goPath = (nextPath: string) => { currentPath = nextPath; activeEdit = null; + searchMatches = null; void renderSftpView(root, state); }; goBtn.addEventListener('click', () => goPath(pathInput.value.trim() || '~')); @@ -199,6 +236,7 @@ export async function renderSftpView( refreshBtn.addEventListener('click', () => void renderSftpView(root, state)); 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 uploadBtn = el('button', { type: 'button', class: 'btn btn-sm btn-primary mutating-action' }, 'Upload Files'); 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 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`; @@ -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: archiveGzHref, class: 'btn btn-sm', download: '' }, '.tar.gz'), mkdirBtn, + touchBtn, uploadBtn, uploadInput, ), + el('div', { class: 'row', style: 'margin-top:8px' }, searchInput, searchBtn, clearSearchBtn), statusMsg, ); 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 if (activeEdit) { 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'); - saveBtn.addEventListener('click', () => { + const triggerSaveDiff = () => { if (!activeEdit) return; showSftpDiffDialog(activeEdit.path, activeEdit.content, textarea.value, activeEditSudo, async (force) => { 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 }; statusMsg.className = 'form-msg ok-text'; 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'); closeEdBtn.addEventListener('click', () => { @@ -379,6 +516,42 @@ export async function renderSftpView( } }); + const selectedPaths = new Set(); + 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'); tbl.append( el( @@ -387,10 +560,11 @@ export async function renderSftpView( el( 'tr', {}, + el('th', {}, 'Sel'), el('th', {}, 'Name'), el('th', {}, 'Type'), el('th', {}, 'Size'), - el('th', {}, 'Mode'), + el('th', {}, 'Mode / Owner'), el('th', {}, 'Modified'), el('th', {}, 'Actions'), ), @@ -401,15 +575,30 @@ export async function renderSftpView( if (listing.parentPath) { const upBtn = el('button', { type: 'button', class: 'btn btn-sm' }, '.. (Parent Dir)'); 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) { + 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', {}); if (entry.type === 'dir') { const openBtn = el('button', { type: 'button', class: 'btn btn-sm' }, `[DIR] ${entry.name}/`); openBtn.addEventListener('click', () => goPath(entry.path)); 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 { nameCell.append(el('span', { class: 'mono' }, entry.name)); } @@ -466,6 +655,32 @@ export async function renderSftpView( 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'); delBtn.addEventListener('click', async () => { const ok = await confirmDialog( @@ -482,16 +697,20 @@ export async function renderSftpView( 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( el( 'tr', {}, + el('td', {}, selChk), nameCell, el('td', { class: 'mono' }, entry.type), 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', {}, actionsRow), ), @@ -500,7 +719,7 @@ export async function renderSftpView( tbl.append(tbody); 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), ); root.append(dropPanel); diff --git a/src/client/ts/views/tunnels-panel.ts b/src/client/ts/views/tunnels-panel.ts index c748242..4c4a40a 100644 --- a/src/client/ts/views/tunnels-panel.ts +++ b/src/client/ts/views/tunnels-panel.ts @@ -1,6 +1,13 @@ import { apiFetch } from '../api.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 { key: string; @@ -8,11 +15,15 @@ export interface TunnelViewEntry { tunnel: { id: string; name: string; - mode: 'http-proxy' | 'local-tcp' | 'remote-tcp'; + mode: 'http-proxy' | 'local-tcp' | 'remote-tcp' | 'socks5'; bindHost?: string; bindPort?: number; targetHost: string; targetPort: number; + targetProtocol?: 'http' | 'https'; + tlsRejectUnauthorized?: boolean; + tlsServerName?: string; + ttlSec?: number; autoStart: boolean; }; active: boolean; @@ -20,6 +31,7 @@ export interface TunnelViewEntry { localBoundPort?: number; remoteBoundPort?: number; proxyPath?: string; + expiresAt?: number; activeConnections: number; totalConnections: number; bytesIn: number; @@ -28,6 +40,13 @@ export interface TunnelViewEntry { 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 { if (!Number.isFinite(bytes) || bytes <= 0) return '0 B'; if (bytes < 1024) return `${bytes} B`; @@ -90,24 +109,71 @@ export async function renderTunnelsPanel( ), ); const tbody = el('tbody'); + const countdownEls: Array<{ el: HTMLElement; expiresAt: number }> = []; for (const item of tunnels) { - const bindInfo = item.proxyPath - ? el('a', { href: item.proxyPath, target: '_blank', rel: 'noopener', class: 'mono' }, item.proxyPath) - : item.tunnel.mode === 'remote-tcp' - ? el( - 'span', - { class: 'mono' }, - item.active && item.remoteBoundPort - ? `${item.localBoundHost ?? '127.0.0.1'}:${item.remoteBoundPort}` - : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, - ) - : el( - 'span', - { class: 'mono' }, - item.active && item.localBoundPort - ? `${item.localBoundHost ?? '127.0.0.1'}:${item.localBoundPort}` - : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, + let bindInfo: HTMLElement; + if (item.tunnel.mode === 'http-proxy' && item.active) { + const launchBtn = 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', + { class: 'mono' }, + item.active && item.remoteBoundPort + ? `${item.localBoundHost ?? '127.0.0.1'}:${item.remoteBoundPort}` + : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, + ); + } else { + bindInfo = el( + 'span', + { class: 'mono' }, + item.active && item.localBoundPort + ? `${item.localBoundHost ?? '127.0.0.1'}:${item.localBoundPort}` + : `${item.tunnel.bindHost ?? '127.0.0.1'}:${item.tunnel.bindPort ?? 'auto'} (inactive)`, + ); + } const toggleBtn = el( '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( el( 'tr', @@ -169,9 +244,16 @@ export async function renderTunnelsPanel( {}, el('span', { class: `badge ${item.active ? 'badge-ok' : ''}` }, item.tunnel.mode.toUpperCase()), item.tunnel.autoStart ? el('div', { class: 'muted' }, 'auto-start') : '', + ttlBadge, ), 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( 'td', { class: 'mono' }, @@ -185,6 +267,17 @@ export async function renderTunnelsPanel( } tbl.append(tbody); 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 @@ -194,7 +287,7 @@ export async function renderTunnelsPanel( el( 'p', { class: 'muted' }, - 'http-proxy binds strictly inside 127.0.0.1 and serves behind GCoordinator auth/CSRF/Safe-Mode at /proxy//.', + '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( 'select', { name: 'mode' }, - el('option', { value: 'http-proxy' }, 'http-proxy (Zero-Port Web Proxy /proxy//)'), + el('option', { value: 'http-proxy' }, 'http-proxy (Authenticated Web Proxy)'), el('option', { value: 'local-tcp' }, 'local-tcp (Local Bind -> Target)'), el('option', { value: 'remote-tcp' }, 'remote-tcp (Remote Bind -R -> Hub/LAN)'), - ); - const targetHostInput = el('input', { name: 'targetHost', value: '127.0.0.1', required: true }); + el('option', { value: 'socks5' }, 'socks5 (Dynamic Local SOCKS5 Proxy)'), + ) as HTMLSelectElement; + const targetHostInput = el('input', { name: 'targetHost', value: '127.0.0.1', required: true }) as HTMLInputElement; const targetPortInput = el('input', { name: 'targetPort', type: 'number', - min: 1, + min: 0, max: 65535, value: '3000', required: true, - }); - const bindHostInput = el('input', { name: 'bindHost', placeholder: '127.0.0.1 (tcp modes)' }); + }) as HTMLInputElement; + 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', { name: 'bindPort', type: 'number', min: 1, max: 65535, - placeholder: 'auto (tcp modes)', - }); - const autoStartChk = el('input', { type: 'checkbox', name: 'autoStart' }); - const startNowChk = el('input', { type: 'checkbox', name: 'startNow', checked: true }); + placeholder: 'auto (tcp/socks5)', + }) as HTMLInputElement; + const autoStartChk = el('input', { type: 'checkbox', name: 'autoStart' }) as HTMLInputElement; + const startNowChk = el('input', { type: 'checkbox', name: 'startNow', checked: true }) as HTMLInputElement; 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( el( 'div', @@ -247,10 +376,12 @@ export async function renderTunnelsPanel( el('div', {}, el('label', {}, 'Display Name'), nameInput), el('div', {}, el('label', {}, 'Mode'), modeSel), el('div', {}, el('label', {}, 'Target Host'), targetHostInput), - el('div', {}, el('label', {}, 'Target Port'), targetPortInput), - el('div', {}, el('label', {}, 'Bind Host (TCP only)'), bindHostInput), - el('div', {}, el('label', {}, 'Bind Port (TCP only)'), bindPortInput), + targetPortWrap, + el('div', {}, el('label', {}, 'Bind Host (TCP/SOCKS5)'), bindHostInput), + el('div', {}, el('label', {}, 'Bind Port (TCP/SOCKS5)'), bindPortInput), + el('div', {}, el('label', {}, 'TTL Seconds (Optional)'), ttlSecInput), ), + httpTlsWrap, el( 'div', { class: 'row' }, @@ -271,10 +402,12 @@ export async function renderTunnelsPanel( 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 bindPortVal = bindPortInput.value.trim(); const bindPort = bindPortVal ? Number(bindPortVal) : undefined; + const ttlVal = ttlSecInput.value.trim(); + const ttlSec = ttlVal ? Number(ttlVal) : undefined; try { const res = await apiFetch<{ startError?: string }>('/api/tunnels', { @@ -286,7 +419,13 @@ export async function renderTunnelsPanel( name: nameInput.value.trim(), mode, 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, bindPort: mode === 'http-proxy' ? undefined : bindPort, autoStart: autoStartChk.checked, @@ -297,6 +436,8 @@ export async function renderTunnelsPanel( if (res.startError) { statusMsg.className = 'form-msg warn-text'; statusMsg.textContent = `Saved, but start failed: ${res.startError}`; + } else { + showToast('Tunnel saved.', 'ok'); } await renderTunnelsPanel(root, fixedServerId); } catch (err) {