Files
picoclaw/web/frontend/src/features/chat/websocket.ts
T
zeed zhao 6ea364e67d feat(web): protect launcher dashboard with token and SPA login (#1953)
Add token-based authentication for the Launcher's embedded Web Dashboard.

- Ephemeral token generated in-memory each run (or via PICOCLAW_LAUNCHER_TOKEN env var)
- HMAC-SHA256 session cookie (HttpOnly, SameSite=Lax, Secure when HTTPS)
- Bearer token support for API/script access
- Rate limiting on login (10 attempts/IP/min)
- Referrer-Policy: no-referrer on all responses
- POST-only logout with JSON content-type (CSRF-safe)
- System tray "Copy dashboard token" action
- Login page shows contextual help (console/tray/log file path)
- Path traversal protection via path.Clean
- X-Forwarded-Host/Port/Proto support for reverse proxy deployments
- Full i18n support (English, Chinese)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-29 13:11:43 +08:00

70 lines
1.7 KiB
TypeScript

export function normalizeWsUrlForBrowser(wsUrl: string): string {
let finalWsUrl = wsUrl
try {
const parsedUrl = new URL(wsUrl)
const isLocalHost =
parsedUrl.hostname === "localhost" ||
parsedUrl.hostname === "127.0.0.1" ||
parsedUrl.hostname === "0.0.0.0"
const isBrowserLocal =
window.location.hostname === "localhost" ||
window.location.hostname === "127.0.0.1"
if (isLocalHost && !isBrowserLocal) {
parsedUrl.hostname = window.location.hostname
finalWsUrl = parsedUrl.toString()
} else if (
isLocalHost &&
isBrowserLocal &&
parsedUrl.hostname !== window.location.hostname &&
(parsedUrl.hostname === "127.0.0.1" ||
parsedUrl.hostname === "localhost") &&
(window.location.hostname === "127.0.0.1" ||
window.location.hostname === "localhost")
) {
// Same machine, but cookies are host-specific; match the page origin.
parsedUrl.hostname = window.location.hostname
finalWsUrl = parsedUrl.toString()
}
} catch (error) {
console.warn("Could not parse ws_url:", error)
}
return finalWsUrl
}
export function invalidateSocket(socket: WebSocket | null) {
if (!socket) {
return
}
socket.onopen = null
socket.onmessage = null
socket.onclose = null
socket.onerror = null
socket.close()
}
export function isCurrentSocket({
socket,
currentSocket,
generation,
currentGeneration,
sessionId,
currentSessionId,
}: {
socket: WebSocket
currentSocket: WebSocket | null
generation: number
currentGeneration: number
sessionId: string
currentSessionId: string
}): boolean {
return (
currentSocket === socket &&
generation === currentGeneration &&
sessionId === currentSessionId
)
}