feat(security): add logout button to Control UI and /logout command to TUI

- Control UI: Added logout button in topbar that clears stored credentials (token/password) from localStorage
- TUI: Added /logout command that disconnects from gateway and exits securely
- Added clearCredentials() function in storage.ts for credential cleanup
- Security improvement: Users can now explicitly revoke stored authentication

[AI-assisted]
This commit is contained in:
Nattapong Tapachoom 2026-01-28 09:34:57 +07:00
parent 8a2878f67f
commit 0c17409fb1
7 changed files with 594 additions and 489 deletions

View File

@ -115,6 +115,7 @@ export function getSlashCommands(options: SlashCommandOptions = {}): SlashComman
{ name: "new", description: "Reset the session" }, { name: "new", description: "Reset the session" },
{ name: "reset", description: "Reset the session" }, { name: "reset", description: "Reset the session" },
{ name: "settings", description: "Open settings" }, { name: "settings", description: "Open settings" },
{ name: "logout", description: "Disconnect and exit securely" },
{ name: "exit", description: "Exit the TUI" }, { name: "exit", description: "Exit the TUI" },
{ name: "quit", description: "Exit the TUI" }, { name: "quit", description: "Exit the TUI" },
]; ];
@ -154,6 +155,7 @@ export function helpText(options: SlashCommandOptions = {}): string {
"/new or /reset", "/new or /reset",
"/abort", "/abort",
"/settings", "/settings",
"/logout",
"/exit", "/exit",
].join("\n"); ].join("\n");
} }

View File

@ -427,6 +427,14 @@ export function createCommandHandlers(context: CommandHandlerContext) {
case "settings": case "settings":
openSettings(); openSettings();
break; break;
case "logout":
chatLog.addSystem("Logging out... Disconnecting from gateway.");
tui.requestRender();
client.stop();
tui.stop();
console.log("\nLogged out successfully.");
process.exit(0);
break;
case "exit": case "exit":
case "quit": case "quit":
client.stop(); client.stop();

View File

@ -32,7 +32,9 @@ export function renderTab(state: AppViewState, tab: Tab) {
}} }}
title=${titleForTab(tab)} title=${titleForTab(tab)}
> >
<span class="nav-item__icon" aria-hidden="true">${icons[iconForTab(tab)]}</span> <span class="nav-item__icon" aria-hidden="true"
>${icons[iconForTab(tab)]}</span
>
<span class="nav-item__text">${titleForTab(tab)}</span> <span class="nav-item__text">${titleForTab(tab)}</span>
</a> </a>
`; `;
@ -45,8 +47,39 @@ export function renderChatControls(state: AppViewState) {
const showThinking = state.onboarding ? false : state.settings.chatShowThinking; const showThinking = state.onboarding ? false : state.settings.chatShowThinking;
const focusActive = state.onboarding ? true : state.settings.chatFocusMode; const focusActive = state.onboarding ? true : state.settings.chatFocusMode;
// Refresh icon // Refresh icon
const refreshIcon = html`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"></path><path d="M21 3v5h-5"></path></svg>`; const refreshIcon = html`
const focusIcon = html`<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7V4h3"></path><path d="M20 7V4h-3"></path><path d="M4 17v3h3"></path><path d="M20 17v3h-3"></path><circle cx="12" cy="12" r="3"></circle></svg>`; <svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"></path>
<path d="M21 3v5h-5"></path>
</svg>
`;
const focusIcon = html`
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M4 7V4h3"></path>
<path d="M20 7V4h-3"></path>
<path d="M4 17v3h3"></path>
<path d="M20 17v3h-3"></path>
<circle cx="12" cy="12" r="3"></circle>
</svg>
`;
return html` return html`
<div class="chat-controls"> <div class="chat-controls">
<label class="field chat-controls__session"> <label class="field chat-controls__session">
@ -105,9 +138,11 @@ export function renderChatControls(state: AppViewState) {
}); });
}} }}
aria-pressed=${showThinking} aria-pressed=${showThinking}
title=${disableThinkingToggle title=${
disableThinkingToggle
? "Disabled during onboarding" ? "Disabled during onboarding"
: "Toggle assistant thinking/working output"} : "Toggle assistant thinking/working output"
}
> >
${icons.brain} ${icons.brain}
</button> </button>
@ -122,9 +157,11 @@ export function renderChatControls(state: AppViewState) {
}); });
}} }}
aria-pressed=${focusActive} aria-pressed=${focusActive}
title=${disableFocusToggle title=${
disableFocusToggle
? "Disabled during onboarding" ? "Disabled during onboarding"
: "Toggle focus mode (hide sidebar + page header)"} : "Toggle focus mode (hide sidebar + page header)"
}
> >
${focusIcon} ${focusIcon}
</button> </button>
@ -240,3 +277,41 @@ function renderMonitorIcon() {
</svg> </svg>
`; `;
} }
/**
* Renders the logout button for security logout.
* Clears stored credentials and disconnects from gateway.
*/
export function renderLogoutButton(state: AppViewState) {
const logoutIcon = html`
<svg
width="18"
height="18"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
<polyline points="16 17 21 12 16 7"></polyline>
<line x1="21" y1="12" x2="9" y2="12"></line>
</svg>
`;
return html`
<button
class="btn btn--sm btn--icon btn--logout"
@click=${() => {
if (confirm("Are you sure you want to logout? This will clear your stored credentials.")) {
state.handleLogout();
}
}}
title="Logout (clear stored credentials)"
aria-label="Logout"
>
${logoutIcon}
</button>
`;
}

View File

@ -50,7 +50,12 @@ import {
rotateDeviceToken, rotateDeviceToken,
} from "./controllers/devices"; } from "./controllers/devices";
import { renderSkills } from "./views/skills"; import { renderSkills } from "./views/skills";
import { renderChatControls, renderTab, renderThemeToggle } from "./app-render.helpers"; import {
renderChatControls,
renderLogoutButton,
renderTab,
renderThemeToggle,
} from "./app-render.helpers";
import { loadChannels } from "./controllers/channels"; import { loadChannels } from "./controllers/channels";
import { loadPresence } from "./controllers/presence"; import { loadPresence } from "./controllers/presence";
import { deleteSession, loadSessions, patchSession } from "./controllers/sessions"; import { deleteSession, loadSessions, patchSession } from "./controllers/sessions";
@ -78,7 +83,13 @@ import {
saveExecApprovals, saveExecApprovals,
updateExecApprovalsFormValue, updateExecApprovalsFormValue,
} from "./controllers/exec-approvals"; } from "./controllers/exec-approvals";
import { loadCronRuns, toggleCronJob, runCronJob, removeCronJob, addCronJob } from "./controllers/cron"; import {
loadCronRuns,
toggleCronJob,
runCronJob,
removeCronJob,
addCronJob,
} from "./controllers/cron";
import { loadDebug, callDebugMethod } from "./controllers/debug"; import { loadDebug, callDebugMethod } from "./controllers/debug";
import { loadLogs } from "./controllers/logs"; import { loadLogs } from "./controllers/logs";
@ -88,10 +99,7 @@ const AVATAR_HTTP_RE = /^https?:\/\//i;
function resolveAssistantAvatarUrl(state: AppViewState): string | undefined { function resolveAssistantAvatarUrl(state: AppViewState): string | undefined {
const list = state.agentsList?.agents ?? []; const list = state.agentsList?.agents ?? [];
const parsed = parseAgentSessionKey(state.sessionKey); const parsed = parseAgentSessionKey(state.sessionKey);
const agentId = const agentId = parsed?.agentId ?? state.agentsList?.defaultId ?? "main";
parsed?.agentId ??
state.agentsList?.defaultId ??
"main";
const agent = list.find((entry) => entry.id === agentId); const agent = list.find((entry) => entry.id === agentId);
const identity = agent?.identity; const identity = agent?.identity;
const candidate = identity?.avatarUrl ?? identity?.avatar; const candidate = identity?.avatarUrl ?? identity?.avatar;
@ -112,7 +120,11 @@ export function renderApp(state: AppViewState) {
const chatAvatarUrl = state.chatAvatarUrl ?? assistantAvatarUrl ?? null; const chatAvatarUrl = state.chatAvatarUrl ?? assistantAvatarUrl ?? null;
return html` return html`
<div class="shell ${isChat ? "shell--chat" : ""} ${chatFocus ? "shell--chat-focus" : ""} ${state.settings.navCollapsed ? "shell--nav-collapsed" : ""} ${state.onboarding ? "shell--onboarding" : ""}"> <div
class="shell ${isChat ? "shell--chat" : ""} ${chatFocus ? "shell--chat-focus" : ""} ${
state.settings.navCollapsed ? "shell--nav-collapsed" : ""
} ${state.onboarding ? "shell--onboarding" : ""}"
>
<header class="topbar"> <header class="topbar">
<div class="topbar-left"> <div class="topbar-left">
<button <button
@ -129,7 +141,10 @@ export function renderApp(state: AppViewState) {
</button> </button>
<div class="brand"> <div class="brand">
<div class="brand-logo"> <div class="brand-logo">
<img src="https://mintcdn.com/clawdhub/4rYvG-uuZrMK_URE/assets/pixel-lobster.svg?fit=max&auto=format&n=4rYvG-uuZrMK_URE&q=85&s=da2032e9eac3b5d9bfe7eb96ca6a8a26" alt="Moltbot" /> <img
src="https://mintcdn.com/clawdhub/4rYvG-uuZrMK_URE/assets/pixel-lobster.svg?fit=max&auto=format&n=4rYvG-uuZrMK_URE&q=85&s=da2032e9eac3b5d9bfe7eb96ca6a8a26"
alt="Moltbot"
/>
</div> </div>
<div class="brand-text"> <div class="brand-text">
<div class="brand-title">MOLTBOT</div> <div class="brand-title">MOLTBOT</div>
@ -143,7 +158,7 @@ export function renderApp(state: AppViewState) {
<span>Health</span> <span>Health</span>
<span class="mono">${state.connected ? "OK" : "Offline"}</span> <span class="mono">${state.connected ? "OK" : "Offline"}</span>
</div> </div>
${renderThemeToggle(state)} ${renderThemeToggle(state)} ${renderLogoutButton(state)}
</div> </div>
</header> </header>
<aside class="nav ${state.settings.navCollapsed ? "nav--collapsed" : ""}"> <aside class="nav ${state.settings.navCollapsed ? "nav--collapsed" : ""}">
@ -151,7 +166,9 @@ export function renderApp(state: AppViewState) {
const isGroupCollapsed = state.settings.navGroupsCollapsed[group.label] ?? false; const isGroupCollapsed = state.settings.navGroupsCollapsed[group.label] ?? false;
const hasActiveTab = group.tabs.some((tab) => tab === state.tab); const hasActiveTab = group.tabs.some((tab) => tab === state.tab);
return html` return html`
<div class="nav-group ${isGroupCollapsed && !hasActiveTab ? "nav-group--collapsed" : ""}"> <div
class="nav-group ${isGroupCollapsed && !hasActiveTab ? "nav-group--collapsed" : ""}"
>
<button <button
class="nav-label" class="nav-label"
@click=${() => { @click=${() => {
@ -165,7 +182,9 @@ export function renderApp(state: AppViewState) {
aria-expanded=${!isGroupCollapsed} aria-expanded=${!isGroupCollapsed}
> >
<span class="nav-label__text">${group.label}</span> <span class="nav-label__text">${group.label}</span>
<span class="nav-label__chevron">${isGroupCollapsed ? "+" : ""}</span> <span class="nav-label__chevron"
>${isGroupCollapsed ? "+" : ""}</span
>
</button> </button>
<div class="nav-group__items"> <div class="nav-group__items">
${group.tabs.map((tab) => renderTab(state, tab))} ${group.tabs.map((tab) => renderTab(state, tab))}
@ -185,7 +204,9 @@ export function renderApp(state: AppViewState) {
rel="noreferrer" rel="noreferrer"
title="Docs (opens in new tab)" title="Docs (opens in new tab)"
> >
<span class="nav-item__icon" aria-hidden="true">${icons.book}</span> <span class="nav-item__icon" aria-hidden="true"
>${icons.book}</span
>
<span class="nav-item__text">Docs</span> <span class="nav-item__text">Docs</span>
</a> </a>
</div> </div>
@ -198,14 +219,13 @@ export function renderApp(state: AppViewState) {
<div class="page-sub">${subtitleForTab(state.tab)}</div> <div class="page-sub">${subtitleForTab(state.tab)}</div>
</div> </div>
<div class="page-meta"> <div class="page-meta">
${state.lastError ${state.lastError ? html`<div class="pill danger">${state.lastError}</div>` : nothing}
? html`<div class="pill danger">${state.lastError}</div>`
: nothing}
${isChat ? renderChatControls(state) : nothing} ${isChat ? renderChatControls(state) : nothing}
</div> </div>
</section> </section>
${state.tab === "overview" ${
state.tab === "overview"
? renderOverview({ ? renderOverview({
connected: state.connected, connected: state.connected,
hello: state.hello, hello: state.hello,
@ -233,9 +253,10 @@ export function renderApp(state: AppViewState) {
onConnect: () => state.connect(), onConnect: () => state.connect(),
onRefresh: () => state.loadOverview(), onRefresh: () => state.loadOverview(),
}) })
: nothing} : nothing
}
${state.tab === "channels" ${
state.tab === "channels"
? renderChannels({ ? renderChannels({
connected: state.connected, connected: state.connected,
loading: state.channelsLoading, loading: state.channelsLoading,
@ -270,9 +291,10 @@ export function renderApp(state: AppViewState) {
onNostrProfileImport: () => state.handleNostrProfileImport(), onNostrProfileImport: () => state.handleNostrProfileImport(),
onNostrProfileToggleAdvanced: () => state.handleNostrProfileToggleAdvanced(), onNostrProfileToggleAdvanced: () => state.handleNostrProfileToggleAdvanced(),
}) })
: nothing} : nothing
}
${state.tab === "instances" ${
state.tab === "instances"
? renderInstances({ ? renderInstances({
loading: state.presenceLoading, loading: state.presenceLoading,
entries: state.presenceEntries, entries: state.presenceEntries,
@ -280,9 +302,10 @@ export function renderApp(state: AppViewState) {
statusMessage: state.presenceStatus, statusMessage: state.presenceStatus,
onRefresh: () => loadPresence(state), onRefresh: () => loadPresence(state),
}) })
: nothing} : nothing
}
${state.tab === "sessions" ${
state.tab === "sessions"
? renderSessions({ ? renderSessions({
loading: state.sessionsLoading, loading: state.sessionsLoading,
result: state.sessionsResult, result: state.sessionsResult,
@ -302,9 +325,10 @@ export function renderApp(state: AppViewState) {
onPatch: (key, patch) => patchSession(state, key, patch), onPatch: (key, patch) => patchSession(state, key, patch),
onDelete: (key) => deleteSession(state, key), onDelete: (key) => deleteSession(state, key),
}) })
: nothing} : nothing
}
${state.tab === "cron" ${
state.tab === "cron"
? renderCron({ ? renderCron({
loading: state.cronLoading, loading: state.cronLoading,
status: state.cronStatus, status: state.cronStatus,
@ -314,7 +338,7 @@ export function renderApp(state: AppViewState) {
form: state.cronForm, form: state.cronForm,
channels: state.channelsSnapshot?.channelMeta?.length channels: state.channelsSnapshot?.channelMeta?.length
? state.channelsSnapshot.channelMeta.map((entry) => entry.id) ? state.channelsSnapshot.channelMeta.map((entry) => entry.id)
: state.channelsSnapshot?.channelOrder ?? [], : (state.channelsSnapshot?.channelOrder ?? []),
channelLabels: state.channelsSnapshot?.channelLabels ?? {}, channelLabels: state.channelsSnapshot?.channelLabels ?? {},
channelMeta: state.channelsSnapshot?.channelMeta ?? [], channelMeta: state.channelsSnapshot?.channelMeta ?? [],
runsJobId: state.cronRunsJobId, runsJobId: state.cronRunsJobId,
@ -327,9 +351,10 @@ export function renderApp(state: AppViewState) {
onRemove: (job) => removeCronJob(state, job), onRemove: (job) => removeCronJob(state, job),
onLoadRuns: (jobId) => loadCronRuns(state, jobId), onLoadRuns: (jobId) => loadCronRuns(state, jobId),
}) })
: nothing} : nothing
}
${state.tab === "skills" ${
state.tab === "skills"
? renderSkills({ ? renderSkills({
loading: state.skillsLoading, loading: state.skillsLoading,
report: state.skillsReport, report: state.skillsReport,
@ -346,16 +371,19 @@ export function renderApp(state: AppViewState) {
onInstall: (skillKey, name, installId) => onInstall: (skillKey, name, installId) =>
installSkill(state, skillKey, name, installId), installSkill(state, skillKey, name, installId),
}) })
: nothing} : nothing
}
${state.tab === "nodes" ${
state.tab === "nodes"
? renderNodes({ ? renderNodes({
loading: state.nodesLoading, loading: state.nodesLoading,
nodes: state.nodes, nodes: state.nodes,
devicesLoading: state.devicesLoading, devicesLoading: state.devicesLoading,
devicesError: state.devicesError, devicesError: state.devicesError,
devicesList: state.devicesList, devicesList: state.devicesList,
configForm: state.configForm ?? (state.configSnapshot?.config as Record<string, unknown> | null), configForm:
state.configForm ??
(state.configSnapshot?.config as Record<string, unknown> | null),
configLoading: state.configLoading, configLoading: state.configLoading,
configSaving: state.configSaving, configSaving: state.configSaving,
configDirty: state.configFormDirty, configDirty: state.configFormDirty,
@ -374,13 +402,15 @@ export function renderApp(state: AppViewState) {
onDeviceReject: (requestId) => rejectDevicePairing(state, requestId), onDeviceReject: (requestId) => rejectDevicePairing(state, requestId),
onDeviceRotate: (deviceId, role, scopes) => onDeviceRotate: (deviceId, role, scopes) =>
rotateDeviceToken(state, { deviceId, role, scopes }), rotateDeviceToken(state, { deviceId, role, scopes }),
onDeviceRevoke: (deviceId, role) => onDeviceRevoke: (deviceId, role) => revokeDeviceToken(state, { deviceId, role }),
revokeDeviceToken(state, { deviceId, role }),
onLoadConfig: () => loadConfig(state), onLoadConfig: () => loadConfig(state),
onLoadExecApprovals: () => { onLoadExecApprovals: () => {
const target = const target =
state.execApprovalsTarget === "node" && state.execApprovalsTargetNodeId state.execApprovalsTarget === "node" && state.execApprovalsTargetNodeId
? { kind: "node" as const, nodeId: state.execApprovalsTargetNodeId } ? {
kind: "node" as const,
nodeId: state.execApprovalsTargetNodeId,
}
: { kind: "gateway" as const }; : { kind: "gateway" as const };
return loadExecApprovals(state, target); return loadExecApprovals(state, target);
}, },
@ -413,19 +443,22 @@ export function renderApp(state: AppViewState) {
}, },
onExecApprovalsPatch: (path, value) => onExecApprovalsPatch: (path, value) =>
updateExecApprovalsFormValue(state, path, value), updateExecApprovalsFormValue(state, path, value),
onExecApprovalsRemove: (path) => onExecApprovalsRemove: (path) => removeExecApprovalsFormValue(state, path),
removeExecApprovalsFormValue(state, path),
onSaveExecApprovals: () => { onSaveExecApprovals: () => {
const target = const target =
state.execApprovalsTarget === "node" && state.execApprovalsTargetNodeId state.execApprovalsTarget === "node" && state.execApprovalsTargetNodeId
? { kind: "node" as const, nodeId: state.execApprovalsTargetNodeId } ? {
kind: "node" as const,
nodeId: state.execApprovalsTargetNodeId,
}
: { kind: "gateway" as const }; : { kind: "gateway" as const };
return saveExecApprovals(state, target); return saveExecApprovals(state, target);
}, },
}) })
: nothing} : nothing
}
${state.tab === "chat" ${
state.tab === "chat"
? renderChat({ ? renderChat({
sessionKey: state.sessionKey, sessionKey: state.sessionKey,
onSessionKeyChange: (next) => { onSessionKeyChange: (next) => {
@ -484,8 +517,7 @@ export function renderApp(state: AppViewState) {
canAbort: Boolean(state.chatRunId), canAbort: Boolean(state.chatRunId),
onAbort: () => void state.handleAbortChat(), onAbort: () => void state.handleAbortChat(),
onQueueRemove: (id) => state.removeQueuedMessage(id), onQueueRemove: (id) => state.removeQueuedMessage(id),
onNewSession: () => onNewSession: () => state.handleSendChat("/new", { restoreDraft: true }),
state.handleSendChat("/new", { restoreDraft: true }),
// Sidebar props for tool output viewing // Sidebar props for tool output viewing
sidebarOpen: state.sidebarOpen, sidebarOpen: state.sidebarOpen,
sidebarContent: state.sidebarContent, sidebarContent: state.sidebarContent,
@ -497,9 +529,10 @@ export function renderApp(state: AppViewState) {
assistantName: state.assistantName, assistantName: state.assistantName,
assistantAvatar: state.assistantAvatar, assistantAvatar: state.assistantAvatar,
}) })
: nothing} : nothing
}
${state.tab === "config" ${
state.tab === "config"
? renderConfig({ ? renderConfig({
raw: state.configRaw, raw: state.configRaw,
originalRaw: state.configRawOriginal, originalRaw: state.configRawOriginal,
@ -535,9 +568,10 @@ export function renderApp(state: AppViewState) {
onApply: () => applyConfig(state), onApply: () => applyConfig(state),
onUpdate: () => runUpdate(state), onUpdate: () => runUpdate(state),
}) })
: nothing} : nothing
}
${state.tab === "debug" ${
state.tab === "debug"
? renderDebug({ ? renderDebug({
loading: state.debugLoading, loading: state.debugLoading,
status: state.debugStatus, status: state.debugStatus,
@ -554,9 +588,10 @@ export function renderApp(state: AppViewState) {
onRefresh: () => loadDebug(state), onRefresh: () => loadDebug(state),
onCall: () => callDebugMethod(state), onCall: () => callDebugMethod(state),
}) })
: nothing} : nothing
}
${state.tab === "logs" ${
state.tab === "logs"
? renderLogs({ ? renderLogs({
loading: state.logsLoading, loading: state.logsLoading,
error: state.logsError, error: state.logsError,
@ -568,14 +603,18 @@ export function renderApp(state: AppViewState) {
truncated: state.logsTruncated, truncated: state.logsTruncated,
onFilterTextChange: (next) => (state.logsFilterText = next), onFilterTextChange: (next) => (state.logsFilterText = next),
onLevelToggle: (level, enabled) => { onLevelToggle: (level, enabled) => {
state.logsLevelFilters = { ...state.logsLevelFilters, [level]: enabled }; state.logsLevelFilters = {
...state.logsLevelFilters,
[level]: enabled,
};
}, },
onToggleAutoFollow: (next) => (state.logsAutoFollow = next), onToggleAutoFollow: (next) => (state.logsAutoFollow = next),
onRefresh: () => loadLogs(state, { reset: true }), onRefresh: () => loadLogs(state, { reset: true }),
onExport: (lines, label) => state.exportLogs(lines, label), onExport: (lines, label) => state.exportLogs(lines, label),
onScroll: (event) => state.handleLogsScroll(event), onScroll: (event) => state.handleLogsScroll(event),
}) })
: nothing} : nothing
}
</main> </main>
${renderExecApprovalPrompt(state)} ${renderExecApprovalPrompt(state)}
</div> </div>

View File

@ -22,10 +22,7 @@ import type {
import type { ChatAttachment, ChatQueueItem, CronFormState } from "./ui-types"; import type { ChatAttachment, ChatQueueItem, CronFormState } from "./ui-types";
import type { EventLogEntry } from "./app-events"; import type { EventLogEntry } from "./app-events";
import type { SkillMessage } from "./controllers/skills"; import type { SkillMessage } from "./controllers/skills";
import type { import type { ExecApprovalsFile, ExecApprovalsSnapshot } from "./controllers/exec-approvals";
ExecApprovalsFile,
ExecApprovalsSnapshot,
} from "./controllers/exec-approvals";
import type { DevicePairingList } from "./controllers/devices"; import type { DevicePairingList } from "./controllers/devices";
import type { ExecApprovalRequest } from "./controllers/exec-approval"; import type { ExecApprovalRequest } from "./controllers/exec-approval";
import type { NostrProfileFormState } from "./views/channels.nostr-profile-form"; import type { NostrProfileFormState } from "./views/channels.nostr-profile-form";
@ -203,4 +200,5 @@ export type AppViewState = {
handleLogsLevelFilterToggle: (level: LogLevel) => void; handleLogsLevelFilterToggle: (level: LogLevel) => void;
handleLogsAutoFollowToggle: (next: boolean) => void; handleLogsAutoFollowToggle: (next: boolean) => void;
handleCallDebugMethod: (method: string, params: string) => Promise<void>; handleCallDebugMethod: (method: string, params: string) => Promise<void>;
handleLogout: () => void;
}; };

View File

@ -3,7 +3,7 @@ import { customElement, state } from "lit/decorators.js";
import type { GatewayBrowserClient, GatewayHelloOk } from "./gateway"; import type { GatewayBrowserClient, GatewayHelloOk } from "./gateway";
import { resolveInjectedAssistantIdentity } from "./assistant-identity"; import { resolveInjectedAssistantIdentity } from "./assistant-identity";
import { loadSettings, type UiSettings } from "./storage"; import { clearCredentials, loadSettings, type UiSettings } from "./storage";
import { renderApp } from "./app-render"; import { renderApp } from "./app-render";
import type { Tab } from "./navigation"; import type { Tab } from "./navigation";
import type { ResolvedTheme, ThemeMode } from "./theme"; import type { ResolvedTheme, ThemeMode } from "./theme";
@ -24,17 +24,10 @@ import type {
StatusSummary, StatusSummary,
NostrProfile, NostrProfile,
} from "./types"; } from "./types";
import { import { type ChatAttachment, type ChatQueueItem, type CronFormState } from "./ui-types";
type ChatAttachment,
type ChatQueueItem,
type CronFormState,
} from "./ui-types";
import type { EventLogEntry } from "./app-events"; import type { EventLogEntry } from "./app-events";
import { DEFAULT_CRON_FORM, DEFAULT_LOG_LEVEL_FILTERS } from "./app-defaults"; import { DEFAULT_CRON_FORM, DEFAULT_LOG_LEVEL_FILTERS } from "./app-defaults";
import type { import type { ExecApprovalsFile, ExecApprovalsSnapshot } from "./controllers/exec-approvals";
ExecApprovalsFile,
ExecApprovalsSnapshot,
} from "./controllers/exec-approvals";
import type { DevicePairingList } from "./controllers/devices"; import type { DevicePairingList } from "./controllers/devices";
import type { ExecApprovalRequest } from "./controllers/exec-approval"; import type { ExecApprovalRequest } from "./controllers/exec-approval";
import { import {
@ -97,12 +90,7 @@ function resolveOnboardingMode(): boolean {
const raw = params.get("onboarding"); const raw = params.get("onboarding");
if (!raw) return false; if (!raw) return false;
const normalized = raw.trim().toLowerCase(); const normalized = raw.trim().toLowerCase();
return ( return normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
normalized === "1" ||
normalized === "true" ||
normalized === "yes" ||
normalized === "on"
);
} }
@customElement("moltbot-app") @customElement("moltbot-app")
@ -134,9 +122,7 @@ export class MoltbotApp extends LitElement {
@state() chatStream: string | null = null; @state() chatStream: string | null = null;
@state() chatStreamStartedAt: number | null = null; @state() chatStreamStartedAt: number | null = null;
@state() chatRunId: string | null = null; @state() chatRunId: string | null = null;
@state() compactionStatus: @state() compactionStatus: import("./app-tool-stream").CompactionStatus | null = null;
| import("./app-tool-stream").CompactionStatus
| null = null;
@state() chatAvatarUrl: string | null = null; @state() chatAvatarUrl: string | null = null;
@state() chatThinkingLevel: string | null = null; @state() chatThinkingLevel: string | null = null;
@state() chatQueue: ChatQueueItem[] = []; @state() chatQueue: ChatQueueItem[] = [];
@ -270,12 +256,9 @@ export class MoltbotApp extends LitElement {
private toolStreamOrder: string[] = []; private toolStreamOrder: string[] = [];
basePath = ""; basePath = "";
private popStateHandler = () => private popStateHandler = () =>
onPopStateInternal( onPopStateInternal(this as unknown as Parameters<typeof onPopStateInternal>[0]);
this as unknown as Parameters<typeof onPopStateInternal>[0],
);
private themeMedia: MediaQueryList | null = null; private themeMedia: MediaQueryList | null = null;
private themeMediaHandler: ((event: MediaQueryListEvent) => void) | null = private themeMediaHandler: ((event: MediaQueryListEvent) => void) | null = null;
null;
private topbarObserver: ResizeObserver | null = null; private topbarObserver: ResizeObserver | null = null;
createRenderRoot() { createRenderRoot() {
@ -288,29 +271,20 @@ export class MoltbotApp extends LitElement {
} }
protected firstUpdated() { protected firstUpdated() {
handleFirstUpdated( handleFirstUpdated(this as unknown as Parameters<typeof handleFirstUpdated>[0]);
this as unknown as Parameters<typeof handleFirstUpdated>[0],
);
} }
disconnectedCallback() { disconnectedCallback() {
handleDisconnected( handleDisconnected(this as unknown as Parameters<typeof handleDisconnected>[0]);
this as unknown as Parameters<typeof handleDisconnected>[0],
);
super.disconnectedCallback(); super.disconnectedCallback();
} }
protected updated(changed: Map<PropertyKey, unknown>) { protected updated(changed: Map<PropertyKey, unknown>) {
handleUpdated( handleUpdated(this as unknown as Parameters<typeof handleUpdated>[0], changed);
this as unknown as Parameters<typeof handleUpdated>[0],
changed,
);
} }
connect() { connect() {
connectGatewayInternal( connectGatewayInternal(this as unknown as Parameters<typeof connectGatewayInternal>[0]);
this as unknown as Parameters<typeof connectGatewayInternal>[0],
);
} }
handleChatScroll(event: Event) { handleChatScroll(event: Event) {
@ -332,15 +306,11 @@ export class MoltbotApp extends LitElement {
} }
resetToolStream() { resetToolStream() {
resetToolStreamInternal( resetToolStreamInternal(this as unknown as Parameters<typeof resetToolStreamInternal>[0]);
this as unknown as Parameters<typeof resetToolStreamInternal>[0],
);
} }
resetChatScroll() { resetChatScroll() {
resetChatScrollInternal( resetChatScrollInternal(this as unknown as Parameters<typeof resetChatScrollInternal>[0]);
this as unknown as Parameters<typeof resetChatScrollInternal>[0],
);
} }
async loadAssistantIdentity() { async loadAssistantIdentity() {
@ -348,43 +318,27 @@ export class MoltbotApp extends LitElement {
} }
applySettings(next: UiSettings) { applySettings(next: UiSettings) {
applySettingsInternal( applySettingsInternal(this as unknown as Parameters<typeof applySettingsInternal>[0], next);
this as unknown as Parameters<typeof applySettingsInternal>[0],
next,
);
} }
setTab(next: Tab) { setTab(next: Tab) {
setTabInternal( setTabInternal(this as unknown as Parameters<typeof setTabInternal>[0], next);
this as unknown as Parameters<typeof setTabInternal>[0],
next,
);
} }
setTheme(next: ThemeMode, context?: Parameters<typeof setThemeInternal>[2]) { setTheme(next: ThemeMode, context?: Parameters<typeof setThemeInternal>[2]) {
setThemeInternal( setThemeInternal(this as unknown as Parameters<typeof setThemeInternal>[0], next, context);
this as unknown as Parameters<typeof setThemeInternal>[0],
next,
context,
);
} }
async loadOverview() { async loadOverview() {
await loadOverviewInternal( await loadOverviewInternal(this as unknown as Parameters<typeof loadOverviewInternal>[0]);
this as unknown as Parameters<typeof loadOverviewInternal>[0],
);
} }
async loadCron() { async loadCron() {
await loadCronInternal( await loadCronInternal(this as unknown as Parameters<typeof loadCronInternal>[0]);
this as unknown as Parameters<typeof loadCronInternal>[0],
);
} }
async handleAbortChat() { async handleAbortChat() {
await handleAbortChatInternal( await handleAbortChatInternal(this as unknown as Parameters<typeof handleAbortChatInternal>[0]);
this as unknown as Parameters<typeof handleAbortChatInternal>[0],
);
} }
removeQueuedMessage(id: string) { removeQueuedMessage(id: string) {
@ -449,9 +403,7 @@ export class MoltbotApp extends LitElement {
handleNostrProfileToggleAdvancedInternal(this); handleNostrProfileToggleAdvancedInternal(this);
} }
async handleExecApprovalDecision( async handleExecApprovalDecision(decision: "allow-once" | "allow-always" | "deny") {
decision: "allow-once" | "allow-always" | "deny",
) {
const active = this.execApprovalQueue[0]; const active = this.execApprovalQueue[0];
if (!active || !this.client || this.execApprovalBusy) return; if (!active || !this.client || this.execApprovalBusy) return;
this.execApprovalBusy = true; this.execApprovalBusy = true;
@ -461,9 +413,7 @@ export class MoltbotApp extends LitElement {
id: active.id, id: active.id,
decision, decision,
}); });
this.execApprovalQueue = this.execApprovalQueue.filter( this.execApprovalQueue = this.execApprovalQueue.filter((entry) => entry.id !== active.id);
(entry) => entry.id !== active.id,
);
} catch (err) { } catch (err) {
this.execApprovalError = `Exec approval failed: ${String(err)}`; this.execApprovalError = `Exec approval failed: ${String(err)}`;
} finally { } finally {
@ -496,6 +446,35 @@ export class MoltbotApp extends LitElement {
}, 200); }, 200);
} }
/**
* Security logout - clears stored credentials (token/password) from localStorage.
* Disconnects from gateway and resets connection state.
* User will need to re-authenticate to access the Control UI.
*/
handleLogout() {
// Clear credentials from localStorage
const clearedSettings = clearCredentials();
this.settings = clearedSettings;
this.password = "";
// Disconnect from gateway
if (this.client) {
this.client.stop();
this.client = null;
}
this.connected = false;
this.hello = null;
// Clear URL parameters
const url = new URL(window.location.href);
url.searchParams.delete("token");
url.searchParams.delete("password");
window.history.replaceState({}, "", url.toString());
// Show confirmation
this.lastError = "Logged out successfully. Credentials cleared.";
}
handleSplitRatioChange(ratio: number) { handleSplitRatioChange(ratio: number) {
const newRatio = Math.max(0.4, Math.min(0.7, ratio)); const newRatio = Math.max(0.4, Math.min(0.7, ratio));
this.splitRatio = newRatio; this.splitRatio = newRatio;

View File

@ -46,31 +46,22 @@ export function loadSettings(): UiSettings {
? parsed.gatewayUrl.trim() ? parsed.gatewayUrl.trim()
: defaults.gatewayUrl, : defaults.gatewayUrl,
token: typeof parsed.token === "string" ? parsed.token : defaults.token, token: typeof parsed.token === "string" ? parsed.token : defaults.token,
password: password: typeof parsed.password === "string" ? parsed.password : defaults.password,
typeof parsed.password === "string"
? parsed.password
: defaults.password,
sessionKey: sessionKey:
typeof parsed.sessionKey === "string" && parsed.sessionKey.trim() typeof parsed.sessionKey === "string" && parsed.sessionKey.trim()
? parsed.sessionKey.trim() ? parsed.sessionKey.trim()
: defaults.sessionKey, : defaults.sessionKey,
lastActiveSessionKey: lastActiveSessionKey:
typeof parsed.lastActiveSessionKey === "string" && typeof parsed.lastActiveSessionKey === "string" && parsed.lastActiveSessionKey.trim()
parsed.lastActiveSessionKey.trim()
? parsed.lastActiveSessionKey.trim() ? parsed.lastActiveSessionKey.trim()
: (typeof parsed.sessionKey === "string" && : (typeof parsed.sessionKey === "string" && parsed.sessionKey.trim()) ||
parsed.sessionKey.trim()) ||
defaults.lastActiveSessionKey, defaults.lastActiveSessionKey,
theme: theme:
parsed.theme === "light" || parsed.theme === "light" || parsed.theme === "dark" || parsed.theme === "system"
parsed.theme === "dark" ||
parsed.theme === "system"
? parsed.theme ? parsed.theme
: defaults.theme, : defaults.theme,
chatFocusMode: chatFocusMode:
typeof parsed.chatFocusMode === "boolean" typeof parsed.chatFocusMode === "boolean" ? parsed.chatFocusMode : defaults.chatFocusMode,
? parsed.chatFocusMode
: defaults.chatFocusMode,
chatShowThinking: chatShowThinking:
typeof parsed.chatShowThinking === "boolean" typeof parsed.chatShowThinking === "boolean"
? parsed.chatShowThinking ? parsed.chatShowThinking
@ -82,12 +73,9 @@ export function loadSettings(): UiSettings {
? parsed.splitRatio ? parsed.splitRatio
: defaults.splitRatio, : defaults.splitRatio,
navCollapsed: navCollapsed:
typeof parsed.navCollapsed === "boolean" typeof parsed.navCollapsed === "boolean" ? parsed.navCollapsed : defaults.navCollapsed,
? parsed.navCollapsed
: defaults.navCollapsed,
navGroupsCollapsed: navGroupsCollapsed:
typeof parsed.navGroupsCollapsed === "object" && typeof parsed.navGroupsCollapsed === "object" && parsed.navGroupsCollapsed !== null
parsed.navGroupsCollapsed !== null
? parsed.navGroupsCollapsed ? parsed.navGroupsCollapsed
: defaults.navGroupsCollapsed, : defaults.navGroupsCollapsed,
}; };
@ -99,3 +87,19 @@ export function loadSettings(): UiSettings {
export function saveSettings(next: UiSettings) { export function saveSettings(next: UiSettings) {
localStorage.setItem(KEY, JSON.stringify(next)); localStorage.setItem(KEY, JSON.stringify(next));
} }
/**
* Clears authentication credentials (token and password) from localStorage.
* Used for security logout - allows user to explicitly revoke stored auth.
* Preserves other UI settings like theme, session key, etc.
*/
export function clearCredentials(): UiSettings {
const current = loadSettings();
const cleared: UiSettings = {
...current,
token: "",
password: "",
};
saveSettings(cleared);
return cleared;
}