feat: live SSE stage, phone view and presenter control
- proxy Go /api/stream through Nitro; drive /stage, /live, /plan and /forecast from scenario events - fall back to 5 s polling after SSE failures or heartbeat silence; show Live/Polling/Offline - authenticate /control and POST /api/scenario in Nitro with server-side control credentials - add big-screen stage with local QR and a no-login phone recommendation view - add SSE unit tests and a live smoke test; refresh README/Makefile
This commit is contained in:
1 parent
7181562e0f
commit
233fdbf66c
24 files changed
+2757
-49
No files matched your search
@@ -0,0 +1,35 @@
|
||||
import QRCode from 'qrcode'
|
||||
|
||||
/**
|
||||
* Generate the /stage QR code locally. No third-party QR image service is
|
||||
* called at runtime, so the big screen keeps working without internet access.
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
const query = getQuery(event)
|
||||
const text = typeof query.text === 'string' ? query.text.trim() : ''
|
||||
if (!text) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'text is required' })
|
||||
}
|
||||
if (text.length > 1024) {
|
||||
throw createError({ statusCode: 400, statusMessage: 'text is too long for a QR code' })
|
||||
}
|
||||
|
||||
let svg: string
|
||||
try {
|
||||
svg = await QRCode.toString(text, {
|
||||
type: 'svg',
|
||||
margin: 1,
|
||||
width: 320,
|
||||
errorCorrectionLevel: 'M',
|
||||
color: { dark: '#0f172a', light: '#ffffff' },
|
||||
})
|
||||
} catch {
|
||||
throw createError({ statusCode: 400, statusMessage: 'could not encode text as a QR code' })
|
||||
}
|
||||
|
||||
setResponseHeaders(event, {
|
||||
'content-type': 'image/svg+xml; charset=utf-8',
|
||||
'cache-control': 'public, max-age=300',
|
||||
})
|
||||
return svg
|
||||
})
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { ScenarioState } from '../../shared/types'
|
||||
import { apiRequest, isMockMode } from '../utils/api'
|
||||
import { mockScenario } from '../utils/mock-data'
|
||||
import { getMockScenario } from '../utils/mock-scenario'
|
||||
|
||||
export default defineEventHandler(async () => {
|
||||
if (isMockMode()) return mockScenario
|
||||
if (isMockMode()) return getMockScenario()
|
||||
return apiRequest<ScenarioState>('/api/scenario')
|
||||
})
|
||||
@@ -1,9 +1,7 @@
|
||||
import { SCENARIOS } from '../../shared/types'
|
||||
import type { Scenario, ScenarioDefinition, ScenarioState } from '../../shared/types'
|
||||
import { apiRequest, isMockMode } from '../utils/api'
|
||||
import { mockScenario } from '../utils/mock-data'
|
||||
|
||||
let version = mockScenario.version
|
||||
import { setMockScenario } from '../utils/mock-scenario'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const body = await readBody<ScenarioDefinition>(event)
|
||||
@@ -16,12 +14,7 @@ export default defineEventHandler(async (event) => {
|
||||
}
|
||||
|
||||
if (isMockMode()) {
|
||||
version += 1
|
||||
return {
|
||||
version,
|
||||
scenario: body,
|
||||
at: new Date().toISOString(),
|
||||
}
|
||||
return setMockScenario(body)
|
||||
}
|
||||
|
||||
// Control credentials are attached in the server process, never in the
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { apiBaseUrl, isMockMode } from '../utils/api'
|
||||
|
||||
/**
|
||||
* Same-origin SSE proxy. The browser never talks to Go directly, so the
|
||||
* Cloudflare/K8s CORS surface stays closed and the stream can be cached or
|
||||
* authenticated at one edge only.
|
||||
*
|
||||
* h3's proxyRequest pipes response chunks as they arrive (it does not await
|
||||
* the full body), which preserves the 15 s heartbeat and `retry: 3000`.
|
||||
*/
|
||||
export default defineEventHandler(async (event) => {
|
||||
if (isMockMode() || process.env.NUXT_DISABLE_SSE === '1') {
|
||||
// Failure drill: make the client prove the 5 s polling fallback. Mock mode
|
||||
// has no upstream stream either, so both paths fail fast and visibly.
|
||||
throw createError({
|
||||
statusCode: 503,
|
||||
statusMessage: 'SSE is disabled; the scenario polling fallback is active.',
|
||||
})
|
||||
}
|
||||
|
||||
return proxyRequest(event, `${apiBaseUrl()}/api/stream`, {
|
||||
headers: { accept: 'text/event-stream' },
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,101 @@
|
||||
import { createHash, createHmac, timingSafeEqual } from 'node:crypto'
|
||||
import { isMockMode } from '../utils/api'
|
||||
|
||||
const COOKIE_NAME = 'pulsecast_control'
|
||||
const COOKIE_CONTEXT = 'pulsecast-control-v1'
|
||||
|
||||
function digest(value: string): Buffer {
|
||||
return createHash('sha256').update(value).digest()
|
||||
}
|
||||
|
||||
/** Constant-time compare that works for unequal-length strings. */
|
||||
function safeEqual(a: string, b: string): boolean {
|
||||
return timingSafeEqual(digest(a), digest(b))
|
||||
}
|
||||
|
||||
function expectedCookie(pass: string): string {
|
||||
return createHmac('sha256', pass).update(COOKIE_CONTEXT).digest('base64url')
|
||||
}
|
||||
|
||||
function basicCredentials(event: import('h3').H3Event): { user: string; pass: string } | null {
|
||||
const header = getHeader(event, 'authorization') ?? ''
|
||||
if (!header.startsWith('Basic ')) return null
|
||||
let decoded: string
|
||||
try {
|
||||
decoded = Buffer.from(header.slice('Basic '.length), 'base64').toString('utf8')
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
const separator = decoded.indexOf(':')
|
||||
if (separator < 0) return null
|
||||
return { user: decoded.slice(0, separator), pass: decoded.slice(separator + 1) }
|
||||
}
|
||||
|
||||
function isProtected(event: import('h3').H3Event): boolean {
|
||||
const path = getRequestURL(event).pathname.replace(/\/+$/, '') || '/'
|
||||
if (path === '/control') return true
|
||||
if (path === '/api/scenario' && getMethod(event) === 'POST') return true
|
||||
return false
|
||||
}
|
||||
|
||||
/**
|
||||
* Presenter-only control surface. Basic auth is checked in Nitro; on success
|
||||
* an HMAC cookie (signed with CONTROL_PASS) lets the page POST /api/scenario
|
||||
* without re-prompting. The browser never receives the Go credentials, and
|
||||
* /stage, /live and all public GETs stay open.
|
||||
*/
|
||||
export default defineEventHandler((event) => {
|
||||
if (!isProtected(event)) return
|
||||
if (isMockMode()) return
|
||||
|
||||
const user = process.env.CONTROL_USER ?? process.env.NUXT_CONTROL_USER ?? ''
|
||||
const pass = process.env.CONTROL_PASS ?? process.env.NUXT_CONTROL_PASS ?? ''
|
||||
const isApi = getRequestURL(event).pathname.startsWith('/api/')
|
||||
setResponseHeader(event, 'cache-control', 'no-store')
|
||||
|
||||
if (!user || !pass) {
|
||||
setResponseStatus(event, 503)
|
||||
if (isApi) {
|
||||
setResponseHeader(event, 'content-type', 'application/json; charset=utf-8')
|
||||
return {
|
||||
error: {
|
||||
code: 'control_auth_unconfigured',
|
||||
message: 'CONTROL_USER and CONTROL_PASS are not configured in the web server.',
|
||||
},
|
||||
}
|
||||
}
|
||||
setResponseHeader(event, 'content-type', 'text/plain; charset=utf-8')
|
||||
return 'Control credentials are not configured. Set CONTROL_USER and CONTROL_PASS on the web server.'
|
||||
}
|
||||
|
||||
const expected = expectedCookie(pass)
|
||||
const cookie = getCookie(event, COOKIE_NAME)
|
||||
const cookieValid = Boolean(cookie && safeEqual(cookie, expected))
|
||||
|
||||
let basicValid = false
|
||||
const basic = basicCredentials(event)
|
||||
if (basic && safeEqual(basic.user, user) && safeEqual(basic.pass, pass)) {
|
||||
basicValid = true
|
||||
const forwardedProto = (getHeader(event, 'x-forwarded-proto') ?? '').split(',')[0]?.trim()
|
||||
setCookie(event, COOKIE_NAME, expected, {
|
||||
httpOnly: true,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
maxAge: 60 * 60 * 8,
|
||||
secure: (forwardedProto || getRequestProtocol(event)) === 'https',
|
||||
})
|
||||
}
|
||||
|
||||
if (cookieValid || basicValid) return
|
||||
|
||||
setResponseStatus(event, 401)
|
||||
setResponseHeader(event, 'www-authenticate', 'Basic realm="PulseCast presenter"')
|
||||
if (isApi) {
|
||||
setResponseHeader(event, 'content-type', 'application/json; charset=utf-8')
|
||||
return {
|
||||
error: { code: 'unauthorized', message: 'Presenter credentials are required to change the scenario.' },
|
||||
}
|
||||
}
|
||||
setResponseHeader(event, 'content-type', 'text/plain; charset=utf-8')
|
||||
return 'Authentication required.'
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
import type { ScenarioDefinition, ScenarioState } from '../../shared/types'
|
||||
import { mockScenario } from './mock-data'
|
||||
|
||||
// Mock mode has no Go process, but the presenter controls and the 5 s polling
|
||||
// fallback should still observe a version change. Nitro keeps this per-process
|
||||
// state, exactly like the single Go pod keeps its in-memory scenario.
|
||||
let current: ScenarioState = clone(mockScenario)
|
||||
|
||||
function clone<T>(value: T): T {
|
||||
return JSON.parse(JSON.stringify(value)) as T
|
||||
}
|
||||
|
||||
export function getMockScenario(): ScenarioState {
|
||||
return clone(current)
|
||||
}
|
||||
|
||||
export function setMockScenario(input: ScenarioDefinition): ScenarioState {
|
||||
current = {
|
||||
version: current.version + 1,
|
||||
scenario: clone(input),
|
||||
at: new Date().toISOString(),
|
||||
}
|
||||
return clone(current)
|
||||
}
|
||||
Reference in new issue
Block a user