Files
archy/packages/app/vite-dev-chats.ts
T
DorianandClaude Opus 4.6 cc7d9fc19e fix(app): add dev server auth token to all API endpoints
Generate random VITE_DEV_API_TOKEN in dev.sh, validate Bearer token
in shared server/dev-auth.ts middleware. Applied to all Vite plugins
(fs, dev-chats, rss, web-search, tmdb, music-search) and claude-proxy.
Client-side uses apiFetch() wrapper to attach the token automatically.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 01:23:17 +00:00

71 lines
2.0 KiB
TypeScript

import type { Plugin, Connect } from 'vite'
import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'fs'
import { resolve, dirname } from 'path'
import { validateDevAuth } from './server/dev-auth'
const CHATS_DIR = '.dev'
const CHATS_FILE = 'chats.json'
function getChatsPath(root: string): string {
const dir = resolve(root, CHATS_DIR)
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
return resolve(dir, CHATS_FILE)
}
function readChats(filePath: string): string {
if (!existsSync(filePath)) return '{}'
try {
return readFileSync(filePath, 'utf-8')
} catch {
return '{}'
}
}
function writeChats(filePath: string, data: string): void {
const dir = dirname(filePath)
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
writeFileSync(filePath, data, 'utf-8')
}
export function devChatsPlugin(): Plugin {
let chatsPath = ''
return {
name: 'aiui-dev-chats',
apply: 'serve',
configResolved(config) {
chatsPath = getChatsPath(config.root)
},
configureServer(server) {
server.middlewares.use('/api/dev-chats', (req: Connect.IncomingMessage, res: any, next: () => void) => {
if (!validateDevAuth(req, res)) return
if (req.method === 'GET') {
const data = readChats(chatsPath)
res.setHeader('Content-Type', 'application/json')
res.end(data)
return
}
if (req.method === 'PUT') {
let body = ''
req.on('data', (chunk: Buffer) => { body += chunk.toString() })
req.on('end', () => {
try {
JSON.parse(body)
writeChats(chatsPath, body)
res.setHeader('Content-Type', 'application/json')
res.end(JSON.stringify({ ok: true }))
} catch (e) {
res.writeHead(400, { 'Content-Type': 'application/json' })
res.end(JSON.stringify({ error: 'Invalid JSON' }))
}
})
return
}
next()
})
},
}
}