dragonflight/services/web-ui/public/data.jsx
opencode 002e5acb82 auth: top-to-bottom rework — local accounts, RBAC + client tag, audit log, env-bootstrap
Scope (locked in via planning Q&A):
  - Identity: local accounts only (PG users table) + existing bearer
    tokens for headless callers.
  - Transport: httpOnly cookie session for browser, Bearer for API.
  - RBAC: admin / editor / viewer roles, plus an orthogonal
    is_client flag for external (agency, talent, customer) accounts.
  - Bootstrap: ADMIN_BOOTSTRAP_USER + ADMIN_BOOTSTRAP_PASSWORD env
    seed the first admin on a clean install. Set ADMIN_BOOTSTRAP_RESET
    to force-reset the named user (break-glass).
  - Rate limit: in-memory, 10 fails per 15min per (IP, username).
  - Password policy: \u22658 chars, mixed case, digit, symbol; small
    blocklist of common passwords; cannot equal username.
  - Self-service: change own display name + password. Everything
    else (role, is_client, other-user mgmt) is admin only.
  - Audit log: append-only table, indexed by actor + event_type +
    created_at, populated by every auth/admin event.

Files added:
  - services/mam-api/src/db/migrations/022-auth-rework.sql
        users.is_client + last_login_at + failed_attempts; audit_log
        table with FK to users (ON DELETE SET NULL).
  - services/mam-api/src/middleware/audit.js
        Fire-and-forget audit() helper. Caller never awaits, failure
        logs but never throws — auditing cannot break the request
        that triggered it.
  - services/mam-api/src/middleware/passwordPolicy.js
        Shared checkPassword(pw, { username }) used by setup, user
        create/update, and self-service password change.
  - services/mam-api/src/tasks/bootstrapAdmin.js
        Runs after migrations. No-ops unless ADMIN_BOOTSTRAP_USER +
        ADMIN_BOOTSTRAP_PASSWORD are set AND (users table empty OR
        ADMIN_BOOTSTRAP_RESET=true).
  - services/mam-api/src/routes/audit.js
        Admin-only GET /audit (paginated, filter by event_type /
        actor / target / date) and GET /audit/event-types.
  - services/web-ui/public/modal-account-settings.jsx
        Profile + Password tabs. Triggered by sidebar user button.

Files rewritten:
  - services/mam-api/src/routes/auth.js
        - POST /login: regenerate(), no manual save(); audit success/
          fail/lockout; updates last_login_at + failed_attempts.
        - POST /logout: destroys session, audits logout.
        - GET /me: returns is_client + last_login_at. Synthetic admin
          when AUTH_ENABLED=false.
        - GET /setup-status: drives login.html UI state.
        - POST /setup: blocked once any user exists; password policy.
        - POST /password: self-service. Requires current pw, runs
          policy, audits, invalidates other sessions implicitly via
          users.js if changed by admin.
        - PATCH /me: self-service display_name update.
  - services/mam-api/src/routes/users.js
        - is_client field in create/update/list/get.
        - Guardrails: cannot delete or demote last admin, cannot
          delete self, admins cannot be flagged is_client.
        - Password change invalidates all sessions for that user
          (DELETE FROM sessions WHERE sess->>'userId' = id).
        - Audit on every mutation.
        - Password policy enforced.
  - services/mam-api/src/middleware/auth.js
        - requireAuth now exposes req.user.is_client.
        - New requireRole(["admin","editor"], { rejectClients: true })
          helper. Applied to cluster, sdk, capture routes (infra).
        - Synthetic user when AUTH_ENABLED=false has is_client=false.
  - services/mam-api/src/index.js
        - Loads bootstrap admin after migrations.
        - Wires /api/v1/audit.
        - Cleans up an earlier comment block.
  - services/web-ui/public/login.html
        - Password hint added next to setup-mode password field.
  - services/web-ui/public/shell.jsx
        - Sidebar user footer is a button that opens AccountSettings.
        - CLIENT badge next to role when is_client=true.
        - Nav filters: clients lose ingest tree + jobs + editor;
          viewers lose ingest + editor; only admins see the Admin
          section. Power button hidden when synthetic user.
  - services/web-ui/public/screens-admin.jsx
        - Users table: new Client column with inline toggle.
        - InviteUserModal: Client checkbox + password hint, gated
          off when role=admin.
        - Last login column replaces Created in primary view.
        - CSV export includes client + last_login.
  - services/web-ui/public/data.jsx
        - ZAMPP_DATA.ME carries is_client + display_name.
  - services/web-ui/public/index.html
        - Loads dist/modal-account-settings.js.
  - services/web-ui/public/styles-rest.css
        - .user-row grid widened to 6 columns.
  - docker-compose.yml
        - Plumbs SESSION_COOKIE_SECURE + ADMIN_BOOTSTRAP_* env vars.

Deploy:
  cd /opt/wild-dragon
  git pull origin main
  # In .env:
  #   AUTH_ENABLED=true
  #   SESSION_SECRET=<openssl rand -hex 48>
  #   ADMIN_BOOTSTRAP_USER=admin
  #   ADMIN_BOOTSTRAP_PASSWORD=<strong>
  docker compose build mam-api web-ui
  docker compose up -d --force-recreate --no-deps mam-api web-ui
2026-05-27 03:21:16 +00:00

319 lines
11 KiB
JavaScript

// data.jsx — API client; populates window.ZAMPP_DATA from real endpoints
const API = '/api/v1';
window.ZAMPP_API_PREFIX = API; // single source of truth (#115)
// Gated logger (#123). Production deploys ship muted; appending ?debug=1
// to the URL (or localStorage.df_debug = '1') re-enables full console output.
(function setupLogger() {
let enabled = false;
try {
enabled =
/(?:^|[?&])debug=1(?:&|$)/.test(location.search) ||
localStorage.getItem('df_debug') === '1' ||
location.hostname === 'localhost' || location.hostname === '127.0.0.1';
} catch {}
const noop = () => {};
window.DF_LOG = {
debug: enabled ? console.debug.bind(console) : noop,
warn: enabled ? console.warn.bind(console) : noop,
error: console.error.bind(console), // errors always surface
};
})();
// Premiere panel releases embedded in this deployment. Bumping the version
// here is the single source of truth — both the Editor download buttons and
// the Settings → Capture SDKs page read from this list (#125).
window.PREMIERE_RELEASES = [
{
version: '1.0.1',
zxp: '/downloads/dragonflight-premiere-panel-1.0.1.zxp',
installer: '/downloads/dragonflight-premiere-panel-1.0.1-windows-setup.exe',
notes: 'Latest — auto-relinking, growing-file support, batch trim',
latest: true,
},
{
version: '1.0.0',
zxp: '/downloads/dragonflight-premiere-panel-1.0.0.zxp',
installer: '/downloads/dragonflight-premiere-panel-1.0.0-windows-setup.exe',
notes: 'Initial release',
latest: false,
},
];
window.PREMIERE_LATEST = window.PREMIERE_RELEASES.find(r => r.latest) || window.PREMIERE_RELEASES[0];
window.ZAMPP_DATA = {
PROJECTS: [],
ASSETS: [],
RECORDERS: [],
JOBS: [],
NODES: [],
USERS: [],
BINS: [],
COMMENTS: [],
ME: null,
};
async function apiFetch(path, opts = {}) {
const res = await fetch(API + path, {
credentials: 'include',
...opts,
headers: { ...(opts.headers || {}), 'Content-Type': 'application/json' },
});
// 401 from any API call means there's no live session. Bounce to the
// login screen instead of leaving the app in a half-loaded state.
// While AUTH_ENABLED=false the server returns a synthetic /auth/me with
// 200 so this branch never fires; flipping AUTH_ENABLED=true is what
// activates the redirect end-to-end.
if (res.status === 401 && !location.pathname.endsWith('/login.html')) {
location.replace('/login.html');
throw new Error('Unauthenticated — redirecting to login');
}
if (!res.ok) throw new Error(res.status + ' ' + res.statusText);
return res.json();
}
function fmtDuration(ms) {
if (!ms) return '—';
const s = Math.round(ms / 1000);
const h = Math.floor(s / 3600);
const m = Math.floor((s % 3600) / 60);
const sec = s % 60;
if (h > 0) return h + ':' + String(m).padStart(2, '0') + ':' + String(sec).padStart(2, '0');
return m + ':' + String(sec).padStart(2, '0');
}
function fmtSize(bytes) {
if (!bytes) return '—';
if (bytes >= 1e12) return (bytes / 1e12).toFixed(1) + ' TB';
if (bytes >= 1e9) return (bytes / 1e9).toFixed(1) + ' GB';
if (bytes >= 1e6) return Math.round(bytes / 1e6) + ' MB';
return Math.round(bytes / 1e3) + ' KB';
}
function fmtRelative(iso) {
if (!iso) return '—';
const diff = (Date.now() - new Date(iso)) / 1000;
if (diff < 60) return 'just now';
if (diff < 3600) return Math.floor(diff / 60) + 'm ago';
if (diff < 86400) return Math.floor(diff / 3600) + 'h ago';
return Math.floor(diff / 86400) + 'd ago';
}
const PROJECT_COLORS = ['#5B7CFA', '#2DD4A8', '#FF5B5B', '#F5A623', '#B57CFA', '#6B7280'];
window.PROJECT_COLORS = PROJECT_COLORS;
function normalizeAsset(a, projectMap) {
return {
...a,
name: a.display_name || a.filename || 'Untitled',
type: a.media_type || 'video',
duration: fmtDuration(a.duration_ms),
size: fmtSize(a.file_size),
res: a.resolution || '—',
updated: fmtRelative(a.updated_at),
project: (projectMap && projectMap[a.project_id]) || '',
comments: 0,
progress: 0,
tc: a.start_tc || null,
seed: a.id ? Array.from(a.id.replace(/-/g, '')).reduce((acc, c) => acc + c.charCodeAt(0), 0) % 6 : 1,
};
}
function normalizeRecorder(r) {
let elapsed = '—';
if (r.status === 'recording' && r.started_at) {
const s = Math.floor((Date.now() - new Date(r.started_at)) / 1000);
elapsed = String(Math.floor(s / 3600)).padStart(2, '0') + ':' +
String(Math.floor((s % 3600) / 60)).padStart(2, '0') + ':' +
String(s % 60).padStart(2, '0');
}
const cfg = r.source_config || {};
return {
...r,
source: r.source_type || '—',
url: cfg.url || cfg.address || cfg.srt_url || cfg.rtmp_url || r.source_type || '—',
codec: r.recording_codec || '—',
res: r.recording_resolution || '—',
node: r.node_id ? r.node_id.slice(0, 8) : 'primary',
elapsed,
bitrate: '—',
health: 100,
audio: false,
};
}
function normalizeJob(j) {
const statusMap = { waiting: 'queued', active: 'running', completed: 'done', failed: 'failed' };
const kindMap = { proxy: 'Proxy', thumbnail: 'Thumbnail', conform: 'Conform', transcode: 'Transcode' };
const meta = j.metadata || {};
return {
...j,
status: statusMap[j.status] || j.status,
kind: kindMap[j.type] || j.type || 'Job',
asset: j.asset_name || meta.filename || '—',
eta: '—',
node: meta.node || '—',
priority: meta.priority || 'normal',
error: j.error || null,
progress: j.progress || 0,
};
}
async function refreshAssets() {
const raw = await apiFetch('/assets?limit=500');
const list = Array.isArray(raw) ? raw : (raw.assets || []);
const projectMap = {};
(window.ZAMPP_DATA.PROJECTS || []).forEach(function(p) { projectMap[p.id] = p.name; });
const normalized = list.map(function(a) { return normalizeAsset(a, projectMap); });
window.ZAMPP_DATA.ASSETS = normalized;
if (window.ZAMPP_DATA.PROJECTS && window.ZAMPP_DATA.PROJECTS.length) {
const counts = {};
list.forEach(function(a) { if (a.project_id) counts[a.project_id] = (counts[a.project_id] || 0) + 1; });
window.ZAMPP_DATA.PROJECTS = window.ZAMPP_DATA.PROJECTS.map(function(p) {
return { ...p, assets: counts[p.id] || 0 };
});
}
return normalized;
}
async function loadData() {
const [projectsR, assetsR, recordersR, jobsR, clusterR, usersR, binsR, meR] = await Promise.allSettled([
apiFetch('/projects'),
apiFetch('/assets?limit=500'),
apiFetch('/recorders'),
apiFetch('/jobs'),
apiFetch('/cluster'),
apiFetch('/users'),
apiFetch('/bins'),
apiFetch('/auth/me'),
]);
const projectMap = {};
if (projectsR.status === 'fulfilled') {
window.ZAMPP_DATA.PROJECTS = (projectsR.value || []).map((p, i) => ({
...p,
color: PROJECT_COLORS[i % PROJECT_COLORS.length],
assets: 0,
updated: fmtRelative(p.updated_at),
}));
window.ZAMPP_DATA.PROJECTS.forEach(p => { projectMap[p.id] = p.name; });
}
if (assetsR.status === 'fulfilled') {
const raw = assetsR.value;
const list = Array.isArray(raw) ? raw : (raw.assets || []);
window.ZAMPP_DATA.ASSETS = list.map(a => normalizeAsset(a, projectMap));
const counts = {};
list.forEach(a => { if (a.project_id) counts[a.project_id] = (counts[a.project_id] || 0) + 1; });
window.ZAMPP_DATA.PROJECTS = window.ZAMPP_DATA.PROJECTS.map(p => ({ ...p, assets: counts[p.id] || 0 }));
}
if (recordersR.status === 'fulfilled') {
window.ZAMPP_DATA.RECORDERS = (recordersR.value || []).map(normalizeRecorder);
}
if (jobsR.status === 'fulfilled') {
window.ZAMPP_DATA.JOBS = (jobsR.value || []).map(normalizeJob);
}
if (clusterR.status === 'fulfilled') {
window.ZAMPP_DATA.NODES = clusterR.value || [];
}
if (usersR.status === 'fulfilled') {
window.ZAMPP_DATA.USERS = (usersR.value || []).map(u => ({
...u,
name: u.display_name || u.username || u.email || 'Unknown',
initials: (u.display_name || u.username || '?').slice(0, 2).toUpperCase(),
role: u.role || 'viewer',
joined: fmtRelative(u.created_at),
lastSeen: fmtRelative(u.last_seen || u.updated_at),
}));
}
if (binsR.status === 'fulfilled') {
window.ZAMPP_DATA.BINS = (binsR.value || []).map(b => ({
...b,
count: b.asset_count || 0,
icon: b.type || 'grid',
}));
}
if (meR.status === 'fulfilled' && meR.value) {
const me = meR.value;
const label = me.display_name || me.username || 'User';
window.ZAMPP_DATA.ME = {
id: me.id,
username: me.username,
display_name: me.display_name || me.username,
name: label,
initials: label.slice(0, 2).toUpperCase(),
role: me.role || 'viewer',
is_client: !!me.is_client,
// True when the server returned a synthetic user (AUTH_ENABLED=false).
// Surfaced as a small "auth off" hint in the sidebar so the operator
// understands why the corner shows the OS user instead of a login.
synthetic: !!me.synthetic,
};
}
}
// ── Sequence API ────────────────────────────────────────────────
async function getSequences(projectId) {
return apiFetch('/sequences?project_id=' + projectId);
}
async function createSequence(data) {
return apiFetch('/sequences', {
method: 'POST',
body: JSON.stringify(data),
});
}
async function getSequence(sequenceId) {
return apiFetch('/sequences/' + sequenceId);
}
async function updateSequence(sequenceId, data) {
return apiFetch('/sequences/' + sequenceId, {
method: 'PUT',
body: JSON.stringify(data),
});
}
async function deleteSequence(sequenceId) {
return apiFetch('/sequences/' + sequenceId, { method: 'DELETE' });
}
async function syncSequenceClips(sequenceId, clips) {
return apiFetch('/sequences/' + sequenceId + '/clips', {
method: 'PUT',
body: JSON.stringify(clips),
});
}
async function exportSequenceEDL(sequenceId, filename) {
const res = await fetch(API + '/sequences/' + sequenceId + '/export/edl', {
method: 'POST',
credentials: 'include',
});
if (!res.ok) throw new Error('EDL export failed: ' + res.status);
const blob = await res.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename || 'sequence.edl';
a.click();
URL.revokeObjectURL(url);
}
window.ZAMPP_API = {
fetch: apiFetch, loadData, refreshAssets, fmtDuration, fmtSize, fmtRelative,
getSequences, createSequence, getSequence, updateSequence,
deleteSequence, syncSequenceClips, exportSequenceEDL,
};
// Library re-renders after mutations: expose normalizeAsset so the screen
// can re-fetch /assets and produce rows with the same shape as the boot load.
window.normalizeAsset = normalizeAsset;