fix: auth bypass, SPA serving, and provider improvements (#97)

* feat(chat): polish syntax highlighting and tool payload rendering (#94)

* [verified] feat(chat): polish syntax highlighting and tool payload rendering

* [verified] fix(chat): tighten large tool payload rendering

* docs: update data volume path in Docker docs

Align documentation with docker-compose.yml change:
hermes-web-ui-data -> hermes-web-ui, /app/dist/data -> /root/.hermes-web-ui

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: bundle server build and restructure service modules

- Add build-server.mjs script for standalone server compilation
- Add logger service with structured output
- Restructure auth, gateway-manager, hermes-cli, hermes services
- Update docker-compose volume mount path
- Update tsconfig and entry point for bundled server

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* refactor: separate controllers from routes and centralize route registration

- Extract business logic from route handlers into controllers/
- Add centralized route registry in routes/index.ts with public/auth/protected layers
- Replace global auth whitelist with sequential middleware registration
- Extract shared helpers to services/config-helpers.ts
- Allow custom provider name to be user-editable in ProviderFormModal
- Deduplicate custom providers by poolKey instead of base_url in getAvailable

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

* fix: auth bypass via path case, SPA serving, and provider improvements

- Fix auth bypass: path case-insensitive check for /api, /v1, /upload
- Fix SPA returning 401: skip auth for non-API paths (static files)
- Fix profile switch: use local loading state instead of shared store ref
- Auto-append /v1 to base_url when fetching models (frontend + backend)
- Guard .env writing to built-in providers only
- Add builtin field to provider presets, enable base_url input in form
- Print auth token to console on startup (pino only writes to file)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Zhicheng Han <43314240+hanzckernel@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
ekko
2026-04-21 12:35:48 +08:00
committed by GitHub
parent 21296a416b
commit 477af66232
65 changed files with 2743 additions and 2621 deletions
+80
View File
@@ -0,0 +1,80 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
const highlightJsMock = vi.hoisted(() => ({
getLanguage: vi.fn((lang?: string) => ['shell', 'xml', 'yaml', 'bash', 'json'].includes(lang || '')),
highlight: vi.fn((content: string, { language }: { language: string }) => ({
value: `<span class="mock-${language}">${content}</span>`,
})),
}))
vi.mock('highlight.js', () => ({
default: highlightJsMock,
}))
import { normalizeHighlightLanguage, renderHighlightedCodeBlock } from '@/components/hermes/chat/highlight'
describe('highlight helper', () => {
beforeEach(() => {
vi.clearAllMocks()
highlightJsMock.getLanguage.mockImplementation((lang?: string) => ['shell', 'xml', 'yaml', 'bash', 'json'].includes(lang || ''))
highlightJsMock.highlight.mockImplementation((content: string, { language }: { language: string }) => ({
value: `<span class="mock-${language}">${content}</span>`,
}))
})
it.each([
['vue', 'xml'],
['yml', 'yaml'],
['sh', 'bash'],
['zsh', 'bash'],
['shellscript', 'bash'],
['shell', 'shell'],
])('normalizes %s to %s', (input, expected) => {
expect(normalizeHighlightLanguage(input)).toBe(expected)
})
it('uses a delegated copy attribute instead of inline javascript', () => {
const html = renderHighlightedCodeBlock('x', 'json', 'Copy')
expect(html).toContain('data-copy-code="true"')
expect(html).not.toContain('onclick=')
})
it('preserves shell-session highlighting instead of remapping shell fences to bash', () => {
const html = renderHighlightedCodeBlock('$ ls\nfoo.txt\n', 'shell', 'Copy')
expect(highlightJsMock.highlight).toHaveBeenCalledWith('$ ls\nfoo.txt\n', {
language: 'shell',
ignoreIllegals: true,
})
expect(html).toContain('class="code-lang">shell</span>')
})
it('skips highlighting for large known-language blocks when a render limit is set', () => {
const html = renderHighlightedCodeBlock('x'.repeat(5000), 'vue', 'Copy', {
maxHighlightLength: 2000,
})
expect(highlightJsMock.highlight).not.toHaveBeenCalled()
expect(html).toContain('class="code-lang">vue</span>')
})
it('falls back to escaped plaintext for unsupported fence labels', () => {
const html = renderHighlightedCodeBlock('<tag>', 'unknown', 'Copy')
expect(highlightJsMock.highlight).not.toHaveBeenCalled()
expect(html).toContain('&lt;tag&gt;')
expect(html).toContain('class="code-lang">unknown</span>')
})
it('falls back to escaped plaintext when direct highlighting throws', () => {
highlightJsMock.highlight.mockImplementationOnce(() => {
throw new Error('boom')
})
const html = renderHighlightedCodeBlock('<tag>', 'vue', 'Copy')
expect(html).toContain('&lt;tag&gt;')
expect(html).toContain('class="code-lang">vue</span>')
})
})
+39
View File
@@ -0,0 +1,39 @@
import { describe, expect, it } from 'vitest'
import { renderHighlightedCodeBlock } from '@/components/hermes/chat/highlight'
describe('highlight safety', () => {
it('escapes large unknown code content', () => {
const html = renderHighlightedCodeBlock('<img src=x onerror=alert(1)>'.repeat(100), 'unknown', 'Copy')
expect(html).toContain('&lt;img')
expect(html).not.toContain('<img')
})
it('does not emit executable HTML for known-language code', () => {
const html = renderHighlightedCodeBlock('<script>alert(1)</script>', 'xml', 'Copy')
expect(html).not.toContain('<script>')
expect(html).toContain('&lt;')
})
it('escapes the language label', () => {
const html = renderHighlightedCodeBlock('x'.repeat(5000), '<script>alert(1)</script>', 'Copy')
expect(html).toContain('&lt;script&gt;alert(1)&lt;/script&gt;')
expect(html).not.toContain('<script>')
})
it('sanitizes the language class', () => {
const html = renderHighlightedCodeBlock('x'.repeat(5000), 'foo bar"><img', 'Copy')
expect(html).toContain('language-foo-bar---img')
})
it('escapes the copy label', () => {
const html = renderHighlightedCodeBlock('x', 'json', 'Copy <now>')
expect(html).toContain('Copy &lt;now&gt;')
expect(html).not.toContain('Copy <now>')
})
})
+93
View File
@@ -0,0 +1,93 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mount } from '@vue/test-utils'
vi.mock('vue-i18n', () => ({
useI18n: () => ({
t: (key: string) => key,
}),
}))
import MarkdownRenderer from '@/components/hermes/chat/MarkdownRenderer.vue'
describe('MarkdownRenderer', () => {
beforeEach(() => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: {
writeText: vi.fn().mockResolvedValue(undefined),
},
})
})
it('highlights vue fenced blocks instead of rendering them as plain text', () => {
const wrapper = mount(MarkdownRenderer, {
props: {
content: '```vue\n<template><div>Hello</div></template>\n```',
},
})
expect(wrapper.find('.code-lang').text()).toBe('vue')
expect(wrapper.find('code.hljs').html()).toContain('hljs-tag')
})
it('keeps shell-session fences on the shell grammar', () => {
const wrapper = mount(MarkdownRenderer, {
props: {
content: '```shell\n$ ls\nfoo.txt\n```',
},
})
expect(wrapper.find('.code-lang').text()).toBe('shell')
expect(wrapper.find('code.hljs').html()).toContain('hljs-meta')
})
it('still highlights long supported code fences', () => {
const wrapper = mount(MarkdownRenderer, {
props: {
content: `\`\`\`json\n${JSON.stringify({ content: 'x'.repeat(2500), ok: true })}\n\`\`\``,
},
})
expect(wrapper.find('.code-lang').text()).toBe('json')
expect(wrapper.find('code.hljs').html()).toMatch(/hljs-(attr|string|punctuation)/)
})
it('falls back to plain escaped text when a fence language is unsupported', () => {
const wrapper = mount(MarkdownRenderer, {
props: {
content: '```foobar\n{"answer":42,"ok":true}\n```',
},
})
expect(wrapper.find('.code-lang').text()).toBe('foobar')
expect(wrapper.find('code.hljs').findAll('span')).toHaveLength(0)
expect(wrapper.find('code.hljs').text()).toContain('{"answer":42,"ok":true}')
})
it('keeps unlabeled code fences as plain text instead of guessing a grammar', () => {
const wrapper = mount(MarkdownRenderer, {
props: {
content: '```\nINFO Starting server\nConnected to 127.0.0.1\nDone\n```',
},
})
expect(wrapper.find('.code-lang').text()).toBe('text')
expect(wrapper.find('code.hljs').findAll('span')).toHaveLength(0)
expect(wrapper.find('code.hljs').text()).toContain('INFO Starting server')
})
it('copies code through the delegated click handler', async () => {
const writeText = vi.mocked(navigator.clipboard.writeText)
const wrapper = mount(MarkdownRenderer, {
props: {
content: '```ts\nconst answer = 42\n```',
},
})
const expected = wrapper.find('code.hljs').element.textContent ?? ''
await wrapper.find('[data-copy-code="true"]').trigger('click')
expect(writeText).toHaveBeenCalledWith(expected)
})
})
+160
View File
@@ -0,0 +1,160 @@
// @vitest-environment jsdom
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { mount } from '@vue/test-utils'
vi.mock('vue-i18n', () => ({
useI18n: () => ({
t: (key: string) => key,
}),
}))
import MessageItem from '@/components/hermes/chat/MessageItem.vue'
import type { Message } from '@/stores/hermes/chat'
describe('MessageItem tool details', () => {
beforeEach(() => {
Object.defineProperty(navigator, 'clipboard', {
configurable: true,
value: {
writeText: vi.fn().mockResolvedValue(undefined),
},
})
})
it('renders highlighted code blocks for tool arguments and tool results', async () => {
const wrapper = mount(MessageItem, {
props: {
message: {
id: 'tool-1',
role: 'tool',
content: '',
timestamp: Date.now(),
toolName: 'web_search',
toolArgs: '{"query":"syntax highlighting"}',
toolResult: '{"results":[{"title":"Done"}]}',
toolStatus: 'done',
} satisfies Message,
},
})
await wrapper.find('.tool-line').trigger('click')
const blocks = wrapper.findAll('.tool-details .hljs-code-block')
expect(blocks).toHaveLength(2)
expect(blocks[0].find('.code-lang').text()).toBe('json')
expect(blocks[1].find('.code-lang').text()).toBe('json')
})
it('copies tool detail code through the delegated click handler', async () => {
const writeText = vi.mocked(navigator.clipboard.writeText)
const wrapper = mount(MessageItem, {
props: {
message: {
id: 'tool-copy',
role: 'tool',
content: '',
timestamp: Date.now(),
toolName: 'web_search',
toolArgs: '{"query":"syntax highlighting"}',
toolStatus: 'done',
} satisfies Message,
},
})
await wrapper.find('.tool-line').trigger('click')
const expected = wrapper.find('.tool-details code.hljs').text()
await wrapper.find('.tool-details [data-copy-code="true"]').trigger('click')
expect(writeText).toHaveBeenCalledWith(expected)
})
it('truncates large tool arguments for display but copies the full formatted payload', async () => {
const writeText = vi.mocked(navigator.clipboard.writeText)
const message = {
content: 'x'.repeat(4000),
ok: true,
}
const wrapper = mount(MessageItem, {
props: {
message: {
id: 'tool-args-large',
role: 'tool',
content: '',
timestamp: Date.now(),
toolName: 'write_file',
toolArgs: JSON.stringify(message),
toolStatus: 'done',
} satisfies Message,
},
})
await wrapper.find('.tool-line').trigger('click')
const expected = JSON.stringify(message, null, 2)
const code = wrapper.find('.tool-details code.hljs')
expect(wrapper.find('.tool-details .code-lang').text()).toBe('json')
expect(wrapper.html()).toContain('chat.truncated')
expect(code.findAll('span')).toHaveLength(0)
await wrapper.find('.tool-details [data-copy-code="true"]').trigger('click')
expect(writeText).toHaveBeenCalledWith(expected)
})
it('copies the full large JSON tool result even when the display is truncated', async () => {
const writeText = vi.mocked(navigator.clipboard.writeText)
const fullResult = {
content: 'x'.repeat(4000),
ok: true,
}
const wrapper = mount(MessageItem, {
props: {
message: {
id: 'tool-2',
role: 'tool',
content: '',
timestamp: Date.now(),
toolName: 'read_file',
toolResult: JSON.stringify(fullResult),
toolStatus: 'done',
} satisfies Message,
},
})
await wrapper.find('.tool-line').trigger('click')
expect(wrapper.find('.tool-details .code-lang').text()).toBe('json')
expect(wrapper.html()).toContain('chat.truncated')
expect(wrapper.find('.tool-details code.hljs').findAll('span')).toHaveLength(0)
await wrapper.find('.tool-details [data-copy-code="true"]').trigger('click')
expect(writeText).toHaveBeenCalledWith(JSON.stringify(fullResult, null, 2))
})
it('copies the full large raw tool result even when the display is truncated', async () => {
const writeText = vi.mocked(navigator.clipboard.writeText)
const fullResult = 'line\n'.repeat(1200)
const wrapper = mount(MessageItem, {
props: {
message: {
id: 'tool-raw',
role: 'tool',
content: '',
timestamp: Date.now(),
toolName: 'read_file',
toolResult: fullResult,
toolStatus: 'done',
} satisfies Message,
},
})
await wrapper.find('.tool-line').trigger('click')
expect(wrapper.find('.tool-details .code-lang').text()).toBe('text')
expect(wrapper.html()).toContain('chat.truncated')
expect(wrapper.find('.tool-details code.hljs').findAll('span')).toHaveLength(0)
await wrapper.find('.tool-details [data-copy-code="true"]').trigger('click')
expect(writeText).toHaveBeenCalledWith(fullResult)
})
})