feat: add token auth, login page, skill toggle, and route restructure

- Add token-based authentication with auto-generated token stored in server/data/.token
- Add login page with URL token auto-fill support
- Add route guards requiring auth for all pages except login
- Restructure routes: / for login, /chat for conversations
- Add skill enable/disable toggle via config.yaml skills.disabled
- Unify logo to /logo.png across sidebar, login, messages, and empty state
- Hide sidebar on login page, prevent flash with router.isReady()
- Fix session export JSON parse error when CLI returns non-JSON output
- Display token in CLI on server start

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
ekko
2026-04-14 21:48:53 +08:00
parent be4624b8b4
commit 1f45254dd0
19 changed files with 464 additions and 12 deletions
+13
View File
@@ -12,8 +12,17 @@ const VERSION = pkg.version
const PID_DIR = resolve(homedir(), '.hermes-web-ui')
const PID_FILE = join(PID_DIR, 'server.pid')
const LOG_FILE = join(PID_DIR, 'server.log')
const TOKEN_FILE = resolve(__dirname, '..', 'dist', 'server', 'data', '.token')
const DEFAULT_PORT = 8648
function getToken() {
try {
return readFileSync(TOKEN_FILE, 'utf-8').trim()
} catch {
return null
}
}
function getPort() {
if (process.argv[3] && !isNaN(process.argv[3])) return parseInt(process.argv[3])
if (process.argv.includes('--port')) return parseInt(process.argv[process.argv.indexOf('--port') + 1])
@@ -103,6 +112,10 @@ function startDaemon(port) {
console.log(` ✓ hermes-web-ui started (PID: ${child.pid}, port: ${port})`)
console.log(` http://localhost:${port}`)
console.log(` Log: ${LOG_FILE}`)
const token = getToken()
if (token) {
console.log(` Token: ${token}`)
}
// Open browser
const url = `http://localhost:${port}`
const isWin = process.platform === 'win32'
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

+9
View File
@@ -15,6 +15,7 @@ import { fsRoutes } from './routes/filesystem'
import { configRoutes } from './routes/config'
import { weixinRoutes } from './routes/weixin'
import * as hermesCli from './services/hermes-cli'
import { getToken, authMiddleware } from './services/auth'
const app = new Koa()
const { restartGateway, startGateway, startGatewayBackground, getVersion } = hermesCli
@@ -28,6 +29,14 @@ let gatewayPid: number | null = null
export async function bootstrap() {
await mkdir(config.uploadDir, { recursive: true })
await mkdir(config.dataDir, { recursive: true })
// Auth (after mkdir so data dir exists)
const authToken = await getToken()
if (authToken) {
app.use(await authMiddleware(authToken))
console.log(`🔐 Auth enabled — token: ${authToken}`)
}
await ensureApiServerConfig()
await ensureGatewayRunning()
+40
View File
@@ -69,6 +69,7 @@ const hermesDir = resolve(homedir(), '.hermes')
interface SkillInfo {
name: string
description: string
enabled: boolean
}
interface SkillCategory {
@@ -147,6 +148,10 @@ fsRoutes.get('/api/skills', async (ctx) => {
const skillsDir = join(hermesDir, 'skills')
try {
// Read disabled skills list from config.yaml
const config = await readConfigYaml()
const disabledList: string[] = config.skills?.disabled || []
const entries = await readdir(skillsDir, { withFileTypes: true })
const categories: SkillCategory[] = []
@@ -167,6 +172,7 @@ fsRoutes.get('/api/skills', async (ctx) => {
skills.push({
name: se.name,
description: extractDescription(skillMd),
enabled: !disabledList.includes(se.name),
})
}
}
@@ -188,6 +194,40 @@ fsRoutes.get('/api/skills', async (ctx) => {
}
})
// Toggle skill enabled/disabled via config.yaml skills.disabled
fsRoutes.put('/api/skills/toggle', async (ctx) => {
const { name, enabled } = ctx.request.body as { name?: string; enabled?: boolean }
if (!name || typeof enabled !== 'boolean') {
ctx.status = 400
ctx.body = { error: 'Missing name or enabled flag' }
return
}
try {
const config = await readConfigYaml()
if (!config.skills) config.skills = {}
if (!Array.isArray(config.skills.disabled)) config.skills.disabled = []
const disabled = config.skills.disabled as string[]
const idx = disabled.indexOf(name)
if (enabled) {
// Enable: remove from disabled list
if (idx !== -1) disabled.splice(idx, 1)
} else {
// Disable: add to disabled list
if (idx === -1) disabled.push(name)
}
await writeConfigYaml(config)
ctx.body = { success: true }
} catch (err: any) {
ctx.status = 500
ctx.body = { error: err.message }
}
})
// List files in a skill directory
async function listFilesRecursive(dir: string, prefix: string): Promise<{ path: string; name: string }[]> {
const result: { path: string; name: string }[] = []
+72
View File
@@ -0,0 +1,72 @@
import { readFile, writeFile } from 'fs/promises'
import { join } from 'path'
import { randomBytes } from 'crypto'
import { config } from '../config'
// Token stored in project data directory
const TOKEN_FILE = join(config.dataDir, '.token')
function generateToken(): string {
return randomBytes(32).toString('hex')
}
/**
* Get or create the auth token. Returns null if auth is disabled.
*/
export async function getToken(): Promise<string | null> {
// Auth can be disabled via env var
if (process.env.AUTH_DISABLED === '1' || process.env.AUTH_DISABLED === 'true') {
return null
}
// Custom token via env var
if (process.env.AUTH_TOKEN) {
return process.env.AUTH_TOKEN
}
try {
const token = await readFile(TOKEN_FILE, 'utf-8')
return token.trim()
} catch {
// Generate a new token
const token = generateToken()
await writeFile(TOKEN_FILE, token + '\n', { mode: 0o600 })
return token
}
}
/**
* Koa middleware: check Authorization header for API routes.
* Skips /health, /webhook, and static file requests.
*/
export async function authMiddleware(token: string | null) {
return async (ctx: any, next: () => Promise<void>) => {
// If auth is disabled, skip
if (!token) {
await next()
return
}
// Skip non-API paths (static files, health check, SPA)
const path = ctx.path
if (
path === '/health' ||
(!path.startsWith('/api') && !path.startsWith('/v1') && path !== '/upload' && path !== '/webhook')
) {
await next()
return
}
const auth = ctx.headers.authorization || ''
const provided = auth.startsWith('Bearer ') ? auth.slice(7) : ''
if (!provided || provided !== token) {
ctx.status = 401
ctx.set('Content-Type', 'application/json')
ctx.body = { error: 'Unauthorized' }
return
}
await next()
}
}
+2
View File
@@ -137,6 +137,8 @@ export async function getSession(id: string): Promise<HermesSession | null> {
const lines = stdout.trim().split('\n').filter(Boolean)
if (lines.length === 0) return null
if (!lines[0].startsWith('{')) return null
const raw: HermesSessionFull = JSON.parse(lines[0])
return {
id: raw.id,
+26 -5
View File
@@ -1,5 +1,6 @@
<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'
import { onMounted, onUnmounted, computed, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { NConfigProvider, NMessageProvider, NDialogProvider, NNotificationProvider } from 'naive-ui'
import { themeOverrides } from '@/styles/theme'
import AppSidebar from '@/components/layout/AppSidebar.vue'
@@ -7,10 +8,22 @@ import { useKeyboard } from '@/composables/useKeyboard'
import { useAppStore } from '@/stores/app'
const appStore = useAppStore()
const route = useRoute()
const router = useRouter()
const ready = ref(false)
const isLoginPage = computed(() => route.name === 'login')
// Wait for router to resolve before rendering layout
router.isReady().then(() => {
ready.value = true
})
onMounted(() => {
appStore.loadModels()
appStore.startHealthPolling()
if (!isLoginPage.value) {
appStore.loadModels()
appStore.startHealthPolling()
}
})
onUnmounted(() => {
@@ -25,8 +38,8 @@ useKeyboard()
<NMessageProvider>
<NDialogProvider>
<NNotificationProvider>
<div class="app-layout">
<AppSidebar />
<div v-if="ready" class="app-layout" :class="{ 'no-sidebar': isLoginPage }">
<AppSidebar v-if="!isLoginPage" />
<main class="app-main">
<router-view />
</main>
@@ -45,11 +58,19 @@ useKeyboard()
height: 100vh;
width: 100vw;
overflow: hidden;
&.no-sidebar {
display: block;
}
}
.app-main {
flex: 1;
overflow-y: auto;
background-color: $bg-primary;
.no-sidebar & {
height: 100vh;
}
}
</style>
+16
View File
@@ -1,3 +1,5 @@
import router from '@/router'
const DEFAULT_BASE_URL = ''
function getBaseUrl(): string {
@@ -16,6 +18,14 @@ export function setApiKey(key: string) {
localStorage.setItem('hermes_api_key', key)
}
export function clearApiKey() {
localStorage.removeItem('hermes_api_key')
}
export function hasApiKey(): boolean {
return !!getApiKey()
}
export async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
const base = getBaseUrl()
const url = `${base}${path}`
@@ -31,6 +41,12 @@ export async function request<T>(path: string, options: RequestInit = {}): Promi
const res = await fetch(url, { ...options, headers })
// Global 401 handler — redirect to login
if (res.status === 401) {
router.replace({ name: 'login' })
throw new Error('Unauthorized')
}
if (!res.ok) {
const text = await res.text().catch(() => '')
throw new Error(`API Error ${res.status}: ${text || res.statusText}`)
+8
View File
@@ -3,6 +3,7 @@ import { request } from './client'
export interface SkillInfo {
name: string
description: string
enabled?: boolean
}
export interface SkillCategory {
@@ -53,3 +54,10 @@ export async function saveMemory(section: 'memory' | 'user', content: string): P
body: JSON.stringify({ section, content }),
})
}
export async function toggleSkill(name: string, enabled: boolean): Promise<void> {
await request('/api/skills/toggle', {
method: 'PUT',
body: JSON.stringify({ name, enabled }),
})
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.3 MiB

+1 -1
View File
@@ -124,7 +124,7 @@ const formattedToolResult = computed(() => {
<div class="msg-body">
<img
v-if="message.role === 'assistant'"
src="/assets/logo.png"
src="/logo.png"
alt="Hermes"
class="msg-avatar"
/>
+1 -1
View File
@@ -42,7 +42,7 @@ watch(currentToolCalls, scrollToBottom)
<template>
<div ref="listRef" class="message-list">
<div v-if="chatStore.messages.length === 0" class="empty-state">
<img src="/assets/logo.png" alt="Hermes" class="empty-logo" />
<img src="/logo.png" alt="Hermes" class="empty-logo" />
<p>{{ t('chat.emptyState') }}</p>
</div>
<MessageItem
+2 -2
View File
@@ -67,8 +67,8 @@ function handleNav(key: string) {
<template>
<aside class="sidebar">
<div class="sidebar-logo" @click="router.push('/')">
<img src="/assets/logo.png" alt="Hermes" class="logo-img" />
<div class="sidebar-logo" @click="router.push('/chat')">
<img src="/logo.png" alt="Hermes" class="logo-img" />
<span class="logo-text">Hermes</span>
<canvas ref="canvasRef" class="logo-dance" />
</div>
+42 -3
View File
@@ -1,9 +1,12 @@
<script setup lang="ts">
import { ref, computed } from 'vue'
import { NSwitch, useMessage } from 'naive-ui'
import type { SkillCategory } from '@/api/skills'
import { toggleSkill } from '@/api/skills'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const message = useMessage()
const props = defineProps<{
categories: SkillCategory[]
@@ -16,6 +19,7 @@ const emit = defineEmits<{
}>()
const collapsedCategories = ref<Set<string>>(new Set())
const togglingSkills = ref<Set<string>>(new Set())
const filteredCategories = computed(() => {
if (!props.searchQuery) return props.categories
@@ -41,6 +45,23 @@ function toggleCategory(name: string) {
function handleSelect(category: string, skill: string) {
emit('select', category, skill)
}
async function handleToggle(category: string, skillName: string, newEnabled: boolean) {
if (togglingSkills.value.has(skillName)) return
togglingSkills.value.add(skillName)
try {
await toggleSkill(skillName, newEnabled)
// Update local state
const cat = props.categories.find(c => c.name === category)
const skill = cat?.skills.find(s => s.name === skillName)
if (skill) skill.enabled = newEnabled
} catch (err: any) {
message.error(t('skills.toggleFailed') + `: ${err.message}`)
} finally {
togglingSkills.value.delete(skillName)
}
}
</script>
<template>
@@ -75,8 +96,17 @@ function handleSelect(category: string, skill: string) {
}"
@click="handleSelect(cat.name, skill.name)"
>
<span class="skill-name">{{ skill.name }}</span>
<span v-if="skill.description" class="skill-desc">{{ skill.description }}</span>
<div class="skill-info">
<span class="skill-name">{{ skill.name }}</span>
<span v-if="skill.description" class="skill-desc">{{ skill.description }}</span>
</div>
<NSwitch
size="small"
:value="skill.enabled !== false"
:loading="togglingSkills.has(skill.name)"
@update:value="handleToggle(cat.name, skill.name, $event)"
@click.stop
/>
</button>
</div>
</div>
@@ -155,7 +185,8 @@ function handleSelect(category: string, skill: string) {
.skill-item {
display: flex;
flex-direction: column;
flex-direction: row;
align-items: center;
width: 100%;
padding: 6px 10px 6px 28px;
border: none;
@@ -166,6 +197,7 @@ function handleSelect(category: string, skill: string) {
cursor: pointer;
border-radius: $radius-sm;
transition: all $transition-fast;
gap: 8px;
&:hover {
background: rgba($accent-primary, 0.06);
@@ -179,6 +211,13 @@ function handleSelect(category: string, skill: string) {
}
}
.skill-info {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
}
.skill-name {
white-space: nowrap;
overflow: hidden;
+12
View File
@@ -1,4 +1,15 @@
export default {
// Login
login: {
title: 'Login',
description: 'Enter your access token to continue. Find it in the server startup logs.',
placeholder: 'Access token',
submit: 'Login',
tokenRequired: 'Please enter your access token',
invalidToken: 'Invalid token',
connectionFailed: 'Cannot connect to server',
},
// Common
common: {
loading: 'Loading...',
@@ -133,6 +144,7 @@ export default {
attachedFiles: 'Attached Files',
loadFailed: 'Failed to load skill',
fileLoadFailed: 'Failed to load file',
toggleFailed: 'Failed to toggle skill',
},
// Memory
+12
View File
@@ -1,4 +1,15 @@
export default {
// 登录
login: {
title: '登录',
description: '输入访问令牌以继续。令牌在服务端启动日志中查看。',
placeholder: '访问令牌',
submit: '登录',
tokenRequired: '请输入访问令牌',
invalidToken: '令牌无效',
connectionFailed: '无法连接到服务器',
},
// 通用
common: {
loading: '加载中...',
@@ -133,6 +144,7 @@ export default {
attachedFiles: '附件文件',
loadFailed: '加载技能失败',
fileLoadFailed: '加载文件失败',
toggleFailed: '切换技能状态失败',
},
// 记忆
+8
View File
@@ -5,6 +5,14 @@ import { i18n } from './i18n'
import App from './App.vue'
import './styles/global.scss'
// Read token from URL BEFORE router initializes (hash router strips params)
const urlParams = new URLSearchParams(window.location.search)
const hashQuery = window.location.hash.split('?')[1]
const urlToken = urlParams.get('token') || (hashQuery ? new URLSearchParams(hashQuery).get('token') : null)
if (urlToken) {
;(window as any).__LOGIN_TOKEN__ = urlToken
}
const app = createApp(App)
app.use(createPinia())
app.use(i18n)
+28
View File
@@ -1,10 +1,17 @@
import { createRouter, createWebHashHistory } from 'vue-router'
import { hasApiKey } from '@/api/client'
const router = createRouter({
history: createWebHashHistory(),
routes: [
{
path: '/',
name: 'login',
component: () => import('@/views/LoginView.vue'),
meta: { public: true },
},
{
path: '/chat',
name: 'chat',
component: () => import('@/views/ChatView.vue'),
},
@@ -51,4 +58,25 @@ const router = createRouter({
],
})
router.beforeEach((to, _from, next) => {
// Public pages don't need auth
if (to.meta.public) {
// Already has key, skip login
if (to.name === 'login' && hasApiKey()) {
next({ path: '/chat' })
return
}
next()
return
}
// All other pages require token
if (!hasApiKey()) {
next({ name: 'login' })
return
}
next()
})
export default router
+172
View File
@@ -0,0 +1,172 @@
<script setup lang="ts">
import { ref } from "vue";
import { useRouter } from "vue-router";
import { useI18n } from "vue-i18n";
import { setApiKey, hasApiKey } from "@/api/client";
const { t } = useI18n();
const router = useRouter();
// Read token saved by main.ts (before router strips URL params)
const urlToken = (window as any).__LOGIN_TOKEN__ || "";
const token = ref(urlToken);
const loading = ref(false);
const errorMsg = ref("");
// If already has a key, try to go to main page
if (hasApiKey()) {
router.replace("/chat");
}
async function handleLogin() {
const key = token.value.trim();
if (!key) {
errorMsg.value = t("login.tokenRequired");
return;
}
loading.value = true;
errorMsg.value = "";
try {
// Validate token by calling an auth-required endpoint
const res = await fetch("/api/sessions", {
headers: { Authorization: `Bearer ${key}` },
});
if (res.status === 401) {
errorMsg.value = t("login.invalidToken");
loading.value = false;
return;
}
setApiKey(key);
router.replace("/chat");
} catch {
errorMsg.value = t("login.connectionFailed");
} finally {
loading.value = false;
}
}
</script>
<template>
<div class="login-view">
<div class="login-card">
<div class="login-logo">
<img src="/logo.png" alt="Hermes" width="80" height="80" />
</div>
<h1 class="login-title">Hermes Web UI</h1>
<p class="login-desc">{{ t("login.description") }}</p>
<form class="login-form" @submit.prevent="handleLogin">
<input
v-model="token"
type="password"
class="login-input"
:placeholder="t('login.placeholder')"
autofocus
/>
<div v-if="errorMsg" class="login-error">{{ errorMsg }}</div>
<button type="submit" class="login-btn" :disabled="loading">
{{ loading ? "..." : t("login.submit") }}
</button>
</form>
</div>
</div>
</template>
<style scoped lang="scss">
@use "@/styles/variables" as *;
.login-view {
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
background: $bg-primary;
}
.login-card {
width: 480px;
padding: 56px 56px;
border: 1px solid $border-color;
border-radius: $radius-lg;
background: $bg-card;
text-align: center;
}
.login-logo {
margin-bottom: 24px;
}
.login-title {
font-size: 26px;
font-weight: 600;
color: $text-primary;
margin: 0 0 10px;
}
.login-desc {
font-size: 14px;
color: $text-muted;
margin: 0 0 40px;
line-height: 1.6;
}
.login-form {
display: flex;
flex-direction: column;
gap: 14px;
}
.login-input {
width: 100%;
padding: 14px 16px;
border: 1px solid $border-color;
border-radius: $radius-sm;
font-size: 15px;
color: $text-primary;
background: $bg-input;
outline: none;
transition: border-color $transition-fast;
box-sizing: border-box;
font-family: $font-code;
&::placeholder {
color: $text-muted;
}
&:focus {
border-color: $accent-primary;
}
}
.login-error {
font-size: 13px;
color: $error;
text-align: left;
}
.login-btn {
width: 100%;
padding: 14px;
border: none;
border-radius: $radius-sm;
background: $text-primary;
color: #fff;
font-size: 15px;
font-weight: 500;
cursor: pointer;
transition: opacity $transition-fast;
&:hover {
opacity: 0.85;
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
}
</style>