2026-05-15 23:40:10 -04:00
|
|
|
/**
|
|
|
|
|
* Authentication middleware.
|
|
|
|
|
*
|
|
|
|
|
* When AUTH_ENABLED=true in the environment, every protected route requires
|
2026-05-18 12:45:15 -04:00
|
|
|
* either:
|
|
|
|
|
* - An active session (set by POST /api/v1/auth/login), or
|
|
|
|
|
* - A valid Bearer token in Authorization header (set by POST /api/v1/tokens)
|
2026-05-15 23:40:10 -04:00
|
|
|
*
|
2026-05-18 12:45:15 -04:00
|
|
|
* When AUTH_ENABLED is unset or any other value, all middleware is a no-op so
|
|
|
|
|
* the stack can be run without user accounts during development.
|
2026-05-15 23:40:10 -04:00
|
|
|
*/
|
2026-05-18 12:45:15 -04:00
|
|
|
import crypto from 'crypto';
|
|
|
|
|
import pool from '../db/pool.js';
|
|
|
|
|
|
|
|
|
|
export const requireAuth = async (req, res, next) => {
|
2026-05-15 23:40:10 -04:00
|
|
|
if (process.env.AUTH_ENABLED !== 'true') return next();
|
2026-05-18 12:45:15 -04:00
|
|
|
|
|
|
|
|
// ── Session-based auth ────────────────────────────────────────
|
|
|
|
|
if (req.session?.userId) {
|
|
|
|
|
req.user = {
|
|
|
|
|
id: req.session.userId,
|
|
|
|
|
username: req.session.username,
|
|
|
|
|
role: req.session.role,
|
|
|
|
|
};
|
|
|
|
|
return next();
|
2026-04-07 21:58:26 -04:00
|
|
|
}
|
2026-05-18 12:45:15 -04:00
|
|
|
|
|
|
|
|
// ── Bearer token auth ─────────────────────────────────────────
|
|
|
|
|
const authHeader = req.headers.authorization;
|
|
|
|
|
if (authHeader?.startsWith('Bearer ')) {
|
|
|
|
|
const raw = authHeader.slice(7).trim();
|
|
|
|
|
const hash = crypto.createHash('sha256').update(raw).digest('hex');
|
|
|
|
|
try {
|
|
|
|
|
const { rows } = await pool.query(
|
chore: 1.2 ship-prep sweep — close 38 issues
Frontend / UX / a11y
- Sidebar collapse/expand toggle with localStorage persistence (#142)
- Settings sections wrap inputs in <form> with Enter-to-submit + native
validation; password autocomplete=new-password (#141, #138)
- Asset thumbnails get descriptive alt text (#140)
- Production deploy now precompiles JSX via esbuild and loads the
production React UMD instead of dev builds + in-browser Babel (#139,
#122)
- Search wrapper gets role=search; global search input gets aria-label,
role=combobox, aria-controls/aria-expanded/aria-activedescendant
wiring (#137, #135)
- Dashboard and Library no longer share the same nav icon (#136)
- Sidebar collapses off-canvas with a topbar menu button below 768 px;
mobile default is collapsed (#134)
- --text-3 bumped to #8B92A0 for WCAG AA contrast on --bg-0 (#133)
- Schedule and Library routes were rendering empty inside the .main
flex container — switched to flex:1 + min-height:0 (#131, #132,
editor + asset detail get the same fix)
- Jobs nav badge now polls /jobs?status=active every 10 s and reflects
the live count (#130, #113)
- aria-label sweep on every icon-only button (#126)
- Premiere panel release list moved to window.PREMIERE_RELEASES in
data.jsx; Editor + Settings read from the same source (#125)
- Typo setPgMclips → setPgmClips (#124)
- Stray console.error / console.warn calls gated behind
window.DF_LOG.{warn,error} (#123)
- Hardcoded /api/v1 paths route through window.ZAMPP_API_PREFIX (#115)
- Schedule rows no longer crash on null recorder_id (#117)
- EditorKeyboard guards against document.activeElement === null (#116)
- Unmount-safe timers for PasswordResetModal, Containers, Editor (#111)
- Player seek clamps below totalMs, server-side range clamping +
uncached 416 on EOF, client-side EOF-stall watchdog (#143)
- Duration badge overlap fix on narrow asset cards (#52)
Backend / security / reliability
- GET /recorders fixed N+1: single LATERAL JOIN for live_asset_id;
Docker inspects bounded to actually-recording rows (#121)
- Upload disk-storage (multer.diskStorage) streams parts to S3 instead
of buffering 500 MB in RAM (#120)
- /assets list clamps limit to MAX_LIMIT=500 to prevent OOM (#119)
- SDK upload archive listing + post-extract sanitize block zip-slip /
tar-slip and symlink escapes (#118)
- Migrations track applied state in schema_migrations, run in a
transaction, and exit non-zero on failure (#107)
- node-agent BMD_COUNT override uses BMD_DEVICE_PREFIX; filesystem
detection wins (#109, #127)
- GPU_COUNT override now merges with nvidia-smi enrichment (#108)
- /cluster/heartbeat requires a node-bound token or admin user;
tokens carry bound_hostname (#106)
- /recorders/:id/start error responses no longer echo the Docker
create payload — env vars stay out of client responses (#105)
- /recorders/probe restricts schemes (srt/rtmp/rtsp/udp/rtp), blocks
private + loopback hosts for non-admins, denies common service
ports (#104)
- Scheduler tick guarded by a Postgres advisory lock; pending/running
rows claimed via UPDATE...RETURNING + FOR UPDATE SKIP LOCKED to
survive multi-node deploys (#103)
- UUID validateUuid('id') param middleware on every /:id route (#102)
- Error handler scrubs Postgres error messages and 5xx detail (#101)
- Graceful SIGTERM/SIGINT shutdown — stops scheduler, drains the HTTP
server, ends the pool, 25 s force-exit watchdog (#100)
- AMPP sync moved from fire-and-forget to a persisted retry queue
(ampp_sync_status / attempts / next_attempt_at + scheduler retry
loop with exponential backoff) (#77)
Migrations
- 019: api_tokens.bound_hostname (#106)
- 020: assets.ampp_sync_status + retry bookkeeping (#77)
Other
- Defer #92 Growing-files per-upload toggle, #80 Audio tab, #57
Dashboard redesign, #56 Editor SPA polish phase 3, #114 S3
migration tool to v1.3
2026-05-26 22:06:14 -04:00
|
|
|
`SELECT t.user_id AS id, u.username, u.role, t.bound_hostname
|
2026-05-18 12:45:15 -04:00
|
|
|
FROM api_tokens t
|
|
|
|
|
JOIN users u ON u.id = t.user_id
|
|
|
|
|
WHERE t.token_hash = $1
|
|
|
|
|
AND (t.expires_at IS NULL OR t.expires_at > NOW())`,
|
|
|
|
|
[hash]
|
|
|
|
|
);
|
|
|
|
|
if (rows.length > 0) {
|
|
|
|
|
req.user = rows[0];
|
chore: 1.2 ship-prep sweep — close 38 issues
Frontend / UX / a11y
- Sidebar collapse/expand toggle with localStorage persistence (#142)
- Settings sections wrap inputs in <form> with Enter-to-submit + native
validation; password autocomplete=new-password (#141, #138)
- Asset thumbnails get descriptive alt text (#140)
- Production deploy now precompiles JSX via esbuild and loads the
production React UMD instead of dev builds + in-browser Babel (#139,
#122)
- Search wrapper gets role=search; global search input gets aria-label,
role=combobox, aria-controls/aria-expanded/aria-activedescendant
wiring (#137, #135)
- Dashboard and Library no longer share the same nav icon (#136)
- Sidebar collapses off-canvas with a topbar menu button below 768 px;
mobile default is collapsed (#134)
- --text-3 bumped to #8B92A0 for WCAG AA contrast on --bg-0 (#133)
- Schedule and Library routes were rendering empty inside the .main
flex container — switched to flex:1 + min-height:0 (#131, #132,
editor + asset detail get the same fix)
- Jobs nav badge now polls /jobs?status=active every 10 s and reflects
the live count (#130, #113)
- aria-label sweep on every icon-only button (#126)
- Premiere panel release list moved to window.PREMIERE_RELEASES in
data.jsx; Editor + Settings read from the same source (#125)
- Typo setPgMclips → setPgmClips (#124)
- Stray console.error / console.warn calls gated behind
window.DF_LOG.{warn,error} (#123)
- Hardcoded /api/v1 paths route through window.ZAMPP_API_PREFIX (#115)
- Schedule rows no longer crash on null recorder_id (#117)
- EditorKeyboard guards against document.activeElement === null (#116)
- Unmount-safe timers for PasswordResetModal, Containers, Editor (#111)
- Player seek clamps below totalMs, server-side range clamping +
uncached 416 on EOF, client-side EOF-stall watchdog (#143)
- Duration badge overlap fix on narrow asset cards (#52)
Backend / security / reliability
- GET /recorders fixed N+1: single LATERAL JOIN for live_asset_id;
Docker inspects bounded to actually-recording rows (#121)
- Upload disk-storage (multer.diskStorage) streams parts to S3 instead
of buffering 500 MB in RAM (#120)
- /assets list clamps limit to MAX_LIMIT=500 to prevent OOM (#119)
- SDK upload archive listing + post-extract sanitize block zip-slip /
tar-slip and symlink escapes (#118)
- Migrations track applied state in schema_migrations, run in a
transaction, and exit non-zero on failure (#107)
- node-agent BMD_COUNT override uses BMD_DEVICE_PREFIX; filesystem
detection wins (#109, #127)
- GPU_COUNT override now merges with nvidia-smi enrichment (#108)
- /cluster/heartbeat requires a node-bound token or admin user;
tokens carry bound_hostname (#106)
- /recorders/:id/start error responses no longer echo the Docker
create payload — env vars stay out of client responses (#105)
- /recorders/probe restricts schemes (srt/rtmp/rtsp/udp/rtp), blocks
private + loopback hosts for non-admins, denies common service
ports (#104)
- Scheduler tick guarded by a Postgres advisory lock; pending/running
rows claimed via UPDATE...RETURNING + FOR UPDATE SKIP LOCKED to
survive multi-node deploys (#103)
- UUID validateUuid('id') param middleware on every /:id route (#102)
- Error handler scrubs Postgres error messages and 5xx detail (#101)
- Graceful SIGTERM/SIGINT shutdown — stops scheduler, drains the HTTP
server, ends the pool, 25 s force-exit watchdog (#100)
- AMPP sync moved from fire-and-forget to a persisted retry queue
(ampp_sync_status / attempts / next_attempt_at + scheduler retry
loop with exponential backoff) (#77)
Migrations
- 019: api_tokens.bound_hostname (#106)
- 020: assets.ampp_sync_status + retry bookkeeping (#77)
Other
- Defer #92 Growing-files per-upload toggle, #80 Audio tab, #57
Dashboard redesign, #56 Editor SPA polish phase 3, #114 S3
migration tool to v1.3
2026-05-26 22:06:14 -04:00
|
|
|
req.tokenBoundHostname = rows[0].bound_hostname || null;
|
2026-05-18 12:45:15 -04:00
|
|
|
// Fire-and-forget last_used_at update
|
|
|
|
|
pool.query(
|
|
|
|
|
'UPDATE api_tokens SET last_used_at = NOW() WHERE token_hash = $1',
|
|
|
|
|
[hash]
|
|
|
|
|
).catch(() => {});
|
|
|
|
|
return next();
|
|
|
|
|
}
|
|
|
|
|
} catch (err) {
|
|
|
|
|
return next(err);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return res.status(401).json({ error: 'Unauthorized' });
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
export const requireAdmin = (req, res, next) => {
|
|
|
|
|
if (process.env.AUTH_ENABLED !== 'true') return next();
|
|
|
|
|
if (req.user?.role === 'admin') return next();
|
|
|
|
|
return res.status(403).json({ error: 'Admin access required' });
|
2026-04-07 21:58:26 -04:00
|
|
|
};
|