Files
Hermes-ui/packages/server/src/services/auth.ts
T
ccc 4859c32045 feat: add IP-based login brute-force protection (#531)
* feat: add IP-based login brute-force protection

- Per-IP rate limiting: 3 failed login attempts locks the IP for 1 hour
- Separate counters for password login and token auth
- Global safety net: 20 req/min, hard lock after 50 total failures
- Persistent lock state to ~/.hermes-web-ui/.login-lock.json (survives restarts)
- Manual unlock: edit or delete the lock file
- Frontend handles 429/503 responses with localized error messages
- i18n support for 8 languages

* feat: add locked IP management endpoint and UI

- GET /api/auth/locked-ips: list all currently locked IPs (protected)
- DELETE /api/auth/locked-ips/:ip: unlock a specific IP (protected)
- DELETE /api/auth/locked-ips: unlock all IPs (protected)
- AccountSettings: shows locked IPs with remaining time, unlock buttons
- i18n support for 8 languages
- Clean up stale .js artifacts, add .gitignore rule

* fix: cross-type IP lock and IPv6-compatible unlock route

- Password and token login now share IP lock state: if an IP is locked
  by either method, ALL auth methods are blocked for that IP
- Changed unlock endpoint from path param to query param (?ip=xxx) to
  support IPv6 addresses containing colons
- Merged unlockIp and unlockAll into a single handler

* chore: increase global login rate limit from 20 to 100 requests per minute

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

---------

Co-authored-by: ekko <fqsy1416@gmail.com>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 18:29:43 +08:00

81 lines
2.3 KiB
TypeScript

import { readFile, writeFile, mkdir } from 'fs/promises'
import { join } from 'path'
import { randomBytes } from 'crypto'
import { homedir } from 'os'
import { checkToken, recordTokenFailure, extractIp } from './login-limiter'
const APP_HOME = join(homedir(), '.hermes-web-ui')
const TOKEN_FILE = join(APP_HOME, '.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> {
if (process.env.AUTH_DISABLED === '1' || process.env.AUTH_DISABLED === 'true') {
return null
}
if (process.env.AUTH_TOKEN) {
return process.env.AUTH_TOKEN
}
try {
const token = await readFile(TOKEN_FILE, 'utf-8')
return token.trim()
} catch {
const token = generateToken()
await mkdir(APP_HOME, { recursive: true })
await writeFile(TOKEN_FILE, token + '\n', { mode: 0o600 })
return token
}
}
/**
* Koa middleware: check Authorization header or query token.
* No path whitelisting — applied globally after public routes.
*/
export function requireAuth(token: string | null) {
return async (ctx: any, next: () => Promise<void>) => {
if (!token) {
await next()
return
}
const auth = ctx.headers.authorization || ''
const provided = auth.startsWith('Bearer ')
? auth.slice(7)
: (ctx.query.token as string) || ''
if (!provided || provided !== token) {
// Skip auth for non-API paths (SPA static files)
const lowerPath = ctx.path.toLowerCase()
if (!lowerPath.startsWith('/api') && !lowerPath.startsWith('/v1') && !lowerPath.startsWith('/upload')) {
await next()
return
}
// Check rate limiter for token auth failures (separate IP counters from password login)
const ip = extractIp(ctx)
const result = checkToken(ip)
if (!result.allowed) {
ctx.status = result.status
ctx.set('Content-Type', 'application/json')
ctx.body = { error: 'Too many login attempts, please try again later' }
return
}
recordTokenFailure(ip)
ctx.status = 401
ctx.set('Content-Type', 'application/json')
ctx.body = { error: 'Unauthorized' }
return
}
await next()
}
}