Files
ComfyUiPortalNext/server.js
T
chris.dumas fe0f2b14c0
Deploy ComfyUI Jobs / deploy (push) Failing after 6m25s
Test and build ComfyUI Jobs / test-build (push) Successful in 11m9s
Initial read-only ComfyUI jobs portal
2026-10-02 19:38:51 +00:00

36 lines
5.6 KiB
JavaScript

const express = require('express');
const path = require('path');
const fs = require('fs');
const crypto = require('crypto');
const app = express();
const port = Number(process.env.PORT || 7002);
const dataDir = path.join(__dirname, 'data');
const usersPath = path.join(dataDir, 'users.json');
const browserDir = path.join(__dirname, 'frontend', 'dist', 'browser');
const indexHtml = path.join(browserDir, 'index.html');
const comfyBase = String(process.env.COMFYUI_URL || 'http://127.0.0.1:8188').replace(/\/$/, '');
app.use(express.json({ limit: '1mb' }));
function readJson(file, fallback) { try { return JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return fallback; } }
function writeJson(file, value) { fs.mkdirSync(dataDir, { recursive: true }); fs.writeFileSync(file, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 }); }
function hashPassword(password, salt) { return crypto.pbkdf2Sync(String(password || ''), String(salt || ''), 120000, 32, 'sha256').toString('hex'); }
function users() { const stored = readJson(usersPath, []); if (Array.isArray(stored) && stored.length) return stored; const username = String(process.env.ADMIN_USERNAME || '').trim(); const password = String(process.env.ADMIN_PASSWORD || ''); if (!username || !password) return []; const salt = crypto.randomBytes(16).toString('hex'); const seeded = [{ id: 'user_admin', username, displayName: username, role: 'admin', active: true, passwordSalt: salt, passwordHash: hashPassword(password, salt) }]; writeJson(usersPath, seeded); return seeded; }
function cookies(req) { return Object.fromEntries(String(req.headers.cookie || '').split(';').map((part) => part.trim()).filter(Boolean).map((part) => { const [key, ...rest] = part.split('='); return [key, decodeURIComponent(rest.join('='))]; })); }
function currentUser(req) { const username = cookies(req).cp_auth; const user = users().find((item) => item.username === username && item.active !== false); return user ? { id: user.id, username: user.username, displayName: user.displayName, role: user.role } : null; }
function requireUser(req, res) { const user = currentUser(req); if (!user) { res.status(401).json({ error: 'Unauthorized' }); return null; } return user; }
function comfyUrl(endpoint) { return `${comfyBase}${endpoint.startsWith('/') ? endpoint : `/${endpoint}`}`; }
async function comfyJson(endpoint) { const response = await fetch(comfyUrl(endpoint)); if (!response.ok) throw new Error(`ComfyUI returned HTTP ${response.status}`); return response.json(); }
function statusFromHistory(entry) { const status = entry?.status || {}; const failed = Array.isArray(status.messages) && status.messages.some((message) => String(message?.[0] || '').toLowerCase().includes('error')); return failed ? 'failed' : status.completed ? 'completed' : entry ? 'running' : 'queued'; }
function jobFromHistory(promptId, entry) { const outputs = Object.values(entry?.outputs || {}); const assets = outputs.flatMap((output) => [...(output?.images || []), ...(output?.gifs || []), ...(output?.videos || [])]).filter((asset) => asset?.filename); return { promptId, title: entry?.prompt?.extra_data?.title || `ComfyUI job ${promptId}`, status: statusFromHistory(entry), queuedAt: entry?.status?.messages?.[0]?.[1] || '', outputCount: assets.length, assets }; }
async function listJobs() { const history = await comfyJson('/history'); return Object.entries(history || {}).map(([promptId, entry]) => jobFromHistory(promptId, entry)).sort((a, b) => String(b.promptId).localeCompare(String(a.promptId))); }
app.get('/api/health', (_req, res) => res.json({ ok: true, service: 'comfyui-portal-next' }));
app.post('/api/login', (req, res) => { const user = users().find((item) => item.username === String(req.body?.username || '').trim()); if (!user || !user.active || hashPassword(req.body?.password, user.passwordSalt) !== user.passwordHash) return res.status(401).json({ error: 'Invalid credentials' }); const maxAge = req.body?.remember ? '; Max-Age=2592000' : ''; res.setHeader('Set-Cookie', `cp_auth=${encodeURIComponent(user.username)}; Path=/; HttpOnly; SameSite=Lax${maxAge}`); res.json({ user: { id: user.id, username: user.username, displayName: user.displayName, role: user.role } }); });
app.post('/api/logout', (_req, res) => { res.setHeader('Set-Cookie', 'cp_auth=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0'); res.json({ ok: true }); });
app.get('/api/me', (req, res) => res.json({ user: currentUser(req) }));
app.get('/api/jobs', async (req, res) => { if (!requireUser(req, res)) return; try { res.json({ jobs: await listJobs() }); } catch (error) { res.status(502).json({ error: error.message || 'Unable to read ComfyUI jobs' }); } });
app.get('/api/jobs/:promptId', async (req, res) => { if (!requireUser(req, res)) return; try { const history = await comfyJson(`/history/${encodeURIComponent(req.params.promptId)}`); const entry = history?.[req.params.promptId] || history; if (!entry) return res.status(404).json({ error: 'Job not found' }); res.json({ job: jobFromHistory(req.params.promptId, entry) }); } catch (error) { res.status(502).json({ error: error.message || 'Unable to read ComfyUI job' }); } });
app.use((req, res, next) => { if (req.path.startsWith('/login') || req.path.startsWith('/api/')) return next(); if (!currentUser(req)) return res.redirect('/login'); next(); });
app.use(express.static(browserDir, { index: false }));
app.use((_req, res) => { if (!fs.existsSync(indexHtml)) return res.status(500).send('Build output missing.'); res.type('html').send(fs.readFileSync(indexHtml, 'utf8')); });
if (require.main === module) app.listen(port, () => console.log(`ComfyUiPortal Next listening on ${port}`));
module.exports = { app, jobFromHistory, statusFromHistory };