2026-09-30 23:12:51 +01:00
|
|
|
// YOUreka Tools — Express host for the tools landing page and the
|
|
|
|
|
// /fingerprint enrollment wizard, whose captures run through the local
|
|
|
|
|
// fpagent binary (Socket.IO on 127.0.0.1:9000).
|
|
|
|
|
//
|
|
|
|
|
// Every endpoint and the port are hardcoded in this file by explicit design
|
|
|
|
|
// decision (openspec change fpagent-tools-ui): no env vars, no config files.
|
|
|
|
|
// createApp() accepts overrides so tests can point the app at fake upstreams;
|
|
|
|
|
// production always runs on the constants below.
|
|
|
|
|
import express from 'express';
|
|
|
|
|
import path from 'node:path';
|
2026-10-01 03:28:31 +01:00
|
|
|
import fs from 'node:fs';
|
2026-09-30 23:12:51 +01:00
|
|
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
|
|
|
import { loadYrkaSession, extractPbCookieValue } from './yrka-auth.js';
|
2026-10-01 01:13:30 +01:00
|
|
|
import { permittedDomains, stripPhonePrefix, CACHE_FRESH, DOMAIN_TTL_MS, cropPermission } from './permit.js';
|
|
|
|
|
import { createCropperRouter, buildCropperClients } from './cropper.js';
|
2026-09-30 23:12:51 +01:00
|
|
|
|
|
|
|
|
// ── Hardcoded configuration ──────────────────────────────────────────────────
|
|
|
|
|
export const PORT = 4173;
|
|
|
|
|
export const PORTAL_URL = 'https://portal.yrka.app'; // web-auth + openfga/verify
|
|
|
|
|
export const PB_URL = 'https://pb.itcass.net'; // PocketBase session refresh
|
|
|
|
|
export const A2LOFT_BASE = 'https://apis.a2loft.net'; // staff lookup + fingerprint save
|
|
|
|
|
export const AGENT_URL = 'http://127.0.0.1:9000'; // fpagent Socket.IO
|
|
|
|
|
export const DOMAINS = [
|
|
|
|
|
{ code: 'uc', name: 'UNICAL' },
|
|
|
|
|
{ code: 'mtr', name: 'Metropolitan Hotel' },
|
|
|
|
|
{ code: 'ucth', name: 'UCTH' },
|
|
|
|
|
{ code: 'uri', name: 'UNICAL Radio International' },
|
|
|
|
|
{ code: 'yrka', name: 'YOUreka' },
|
|
|
|
|
];
|
|
|
|
|
|
|
|
|
|
const SESSION_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000; // 30 days
|
|
|
|
|
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
|
|
|
|
|
|
|
|
// ── helpers ──────────────────────────────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
// Express does not parse cookies; this is all we need.
|
|
|
|
|
function cookie(req, name) {
|
|
|
|
|
const header = req.headers.cookie;
|
|
|
|
|
if (!header) return undefined;
|
|
|
|
|
for (const part of header.split(';')) {
|
|
|
|
|
const i = part.indexOf('=');
|
|
|
|
|
if (i < 0) continue;
|
|
|
|
|
if (part.slice(0, i).trim() === name) return decodeURIComponent(part.slice(i + 1).trim());
|
|
|
|
|
}
|
|
|
|
|
return undefined;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
function readProfile(raw) {
|
|
|
|
|
if (!raw) return { firstName: '', lastName: '', phone: '' };
|
|
|
|
|
try {
|
|
|
|
|
const p = JSON.parse(raw);
|
|
|
|
|
return {
|
|
|
|
|
firstName: typeof p.firstName === 'string' ? p.firstName : '',
|
|
|
|
|
lastName: typeof p.lastName === 'string' ? p.lastName : '',
|
|
|
|
|
phone: typeof p.phone === 'string' ? p.phone : '',
|
|
|
|
|
};
|
|
|
|
|
} catch {
|
|
|
|
|
return { firstName: '', lastName: '', phone: '' };
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-10-01 01:35:37 +01:00
|
|
|
function errorPage(res, status, title, message, actions = {}) {
|
|
|
|
|
const primary = actions.primary || { href: '/auth/login', label: 'Try again' };
|
|
|
|
|
const secondary = actions.secondary === null ? null : actions.secondary || { href: '/', label: 'Back to Tools' };
|
|
|
|
|
const icon = actions.icon || 'alert';
|
2026-09-30 23:12:51 +01:00
|
|
|
res
|
2026-10-01 01:13:30 +01:00
|
|
|
.status(status)
|
2026-09-30 23:12:51 +01:00
|
|
|
.type('html')
|
|
|
|
|
.send(`<!doctype html>
|
|
|
|
|
<html lang="en">
|
|
|
|
|
<head>
|
|
|
|
|
<meta charset="utf-8">
|
|
|
|
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
2026-10-01 03:12:02 +01:00
|
|
|
<title>${esc(title)} · YOUreka Tools</title>
|
2026-09-30 23:12:51 +01:00
|
|
|
<link rel="stylesheet" href="/assets/style.css">
|
|
|
|
|
</head>
|
|
|
|
|
<body class="app">
|
2026-10-01 01:35:37 +01:00
|
|
|
<nav class="nav">
|
|
|
|
|
<div class="container">
|
|
|
|
|
<a class="brand" href="/">
|
|
|
|
|
<span class="brand-mark">
|
|
|
|
|
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 2a8 8 0 0 0-8 8c0 3.5 1 5.5 2 7"/><path d="M16 21a10 10 0 0 0 4-13 8 8 0 0 0-15.7-1"/><path d="M8 21a8 8 0 0 1-1-11 5 5 0 0 1 9.7 1.4A6 6 0 0 1 12 17"/><path d="M12 21a4 4 0 0 0 4-4 4 4 0 0 0-1.2-2.9"/></svg>
|
|
|
|
|
</span>
|
|
|
|
|
YOUreka <small>Tools</small>
|
|
|
|
|
</a>
|
|
|
|
|
<div class="nav-right">
|
|
|
|
|
<a class="linklike" href="/auth/logout">Sign out</a>
|
|
|
|
|
</div>
|
|
|
|
|
</div>
|
|
|
|
|
</nav>
|
2026-09-30 23:12:51 +01:00
|
|
|
<main class="container narrow center-v">
|
|
|
|
|
<div class="card message-card">
|
2026-10-01 01:35:37 +01:00
|
|
|
<div class="message-icon error">${ICONS[icon] || ICONS.alert}</div>
|
2026-10-01 03:12:02 +01:00
|
|
|
<h1>${esc(title)}</h1>
|
|
|
|
|
<p class="muted">${esc(message)}</p>
|
|
|
|
|
<a class="btn btn-primary" href="${esc(primary.href)}">${esc(primary.label)}</a>
|
|
|
|
|
${secondary ? `<a class="btn btn-ghost" href="${esc(secondary.href)}">${esc(secondary.label)}</a>` : ''}
|
2026-09-30 23:12:51 +01:00
|
|
|
</div>
|
|
|
|
|
</main>
|
|
|
|
|
</body>
|
|
|
|
|
</html>`);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const ICONS = {
|
|
|
|
|
alert:
|
|
|
|
|
'<svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"/><line x1="12" y1="9" x2="12" y2="13"/><line x1="12" y1="17" x2="12.01" y2="17"/></svg>',
|
2026-10-01 01:35:37 +01:00
|
|
|
lock:
|
|
|
|
|
'<svg viewBox="0 0 24 24" width="28" height="28" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>',
|
2026-09-30 23:12:51 +01:00
|
|
|
};
|
|
|
|
|
|
2026-10-01 03:12:02 +01:00
|
|
|
/** HTML-escape interpolated values — error pages may carry upstream text. */
|
|
|
|
|
function esc(value) {
|
|
|
|
|
return String(value ?? '')
|
|
|
|
|
.replace(/&/g, '&')
|
|
|
|
|
.replace(/</g, '<')
|
|
|
|
|
.replace(/>/g, '>')
|
|
|
|
|
.replace(/"/g, '"')
|
|
|
|
|
.replace(/'/g, ''');
|
|
|
|
|
};
|
|
|
|
|
|
2026-09-30 23:12:51 +01:00
|
|
|
// ── app factory ──────────────────────────────────────────────────────────────
|
|
|
|
|
export function createApp(overrides = {}) {
|
|
|
|
|
const cfg = {
|
|
|
|
|
portalUrl: PORTAL_URL,
|
|
|
|
|
pbUrl: PB_URL,
|
|
|
|
|
a2loftBase: A2LOFT_BASE,
|
|
|
|
|
agentUrl: AGENT_URL,
|
|
|
|
|
domains: DOMAINS,
|
|
|
|
|
ttlMs: DOMAIN_TTL_MS,
|
|
|
|
|
fetch: fetch,
|
|
|
|
|
now: Date.now,
|
|
|
|
|
...overrides,
|
|
|
|
|
};
|
|
|
|
|
const domainCodes = new Set(cfg.domains.map((d) => d.code));
|
|
|
|
|
const domainCache = new Map(); // phone → { codes, checkedAt }
|
2026-10-01 01:13:30 +01:00
|
|
|
const cropCache = cfg.cropCache || new Map(); // phone → { allowed, checkedAt }
|
2026-09-30 23:12:51 +01:00
|
|
|
|
|
|
|
|
const app = express();
|
|
|
|
|
app.disable('x-powered-by');
|
|
|
|
|
app.set('trust proxy', 1); // https termination upstream → correct Secure-cookie flag
|
2026-10-01 03:12:02 +01:00
|
|
|
// cropper pictures travel as data URLs (large); everything else stays small
|
|
|
|
|
app.use('/cropper', express.json({ limit: '50mb' }));
|
|
|
|
|
app.use(express.json({ limit: '1mb' }));
|
2026-09-30 23:12:51 +01:00
|
|
|
|
|
|
|
|
const setSessionCookie = (req, res, value) =>
|
|
|
|
|
res.cookie('session', value, {
|
|
|
|
|
path: '/',
|
|
|
|
|
httpOnly: true,
|
|
|
|
|
secure: req.secure, // https in production; plain http dev on localhost still works
|
|
|
|
|
sameSite: 'lax',
|
|
|
|
|
maxAge: SESSION_MAX_AGE_MS,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const setProfileCookie = (req, res, profile) =>
|
|
|
|
|
res.cookie('user_profile', JSON.stringify(profile), {
|
|
|
|
|
path: '/',
|
|
|
|
|
httpOnly: true,
|
|
|
|
|
secure: req.secure,
|
|
|
|
|
sameSite: 'lax',
|
|
|
|
|
maxAge: SESSION_MAX_AGE_MS,
|
|
|
|
|
});
|
|
|
|
|
|
2026-10-01 03:12:02 +01:00
|
|
|
// ── static assets (no session work per asset) ─────────────────────────────
|
2026-10-01 03:28:31 +01:00
|
|
|
app.use(express.static(path.join(__dirname, 'public'), { index: false })); // assets only; '/' is session-aware
|
2026-10-01 03:12:02 +01:00
|
|
|
|
2026-09-30 23:12:51 +01:00
|
|
|
// ── session middleware: recover / refresh the YOUreka Auth session ────────
|
|
|
|
|
app.use(async (req, res, next) => {
|
|
|
|
|
req.session = null;
|
|
|
|
|
const raw = cookie(req, 'session');
|
|
|
|
|
if (raw) {
|
|
|
|
|
try {
|
|
|
|
|
const yrka = await loadYrkaSession(raw, { pbUrl: cfg.pbUrl });
|
|
|
|
|
if (!yrka) {
|
|
|
|
|
res.clearCookie('session', { path: '/' });
|
|
|
|
|
res.clearCookie('user_profile', { path: '/' });
|
|
|
|
|
} else {
|
|
|
|
|
if (yrka.refreshed && yrka.cookie) setSessionCookie(req, res, yrka.cookie);
|
|
|
|
|
req.session = {
|
|
|
|
|
token: yrka.pb.authStore.token,
|
|
|
|
|
...readProfile(cookie(req, 'user_profile')),
|
|
|
|
|
};
|
|
|
|
|
}
|
|
|
|
|
} catch {
|
|
|
|
|
req.session = null;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
next();
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const requirePage = (req, res, next) => {
|
|
|
|
|
if (!req.session) return res.redirect('/auth/login');
|
|
|
|
|
next();
|
|
|
|
|
};
|
|
|
|
|
const requireApi = (req, res, next) => {
|
|
|
|
|
if (!req.session) return res.status(401).json({ ok: false, message: 'Authentication required.' });
|
|
|
|
|
next();
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
// ── static assets & landing page ──────────────────────────────────────────
|
|
|
|
|
|
|
|
|
|
// ── auth: YOUreka portal web-auth flow ────────────────────────────────────
|
|
|
|
|
app.get('/auth/login', async (req, res) => {
|
|
|
|
|
const returnUrl = `${req.protocol}://${req.get('host')}/auth/callback`;
|
|
|
|
|
try {
|
|
|
|
|
const r = await cfg.fetch(`${cfg.portalUrl.replace(/\/+$/, '')}/api/web/auth`, {
|
|
|
|
|
method: 'POST',
|
|
|
|
|
headers: { 'content-type': 'application/json' },
|
|
|
|
|
body: JSON.stringify({ returnUrl }),
|
|
|
|
|
});
|
|
|
|
|
const data = await r.json().catch(() => null);
|
|
|
|
|
if (!r.ok || !data?.ok || !data.loginUrl) {
|
2026-10-01 01:13:30 +01:00
|
|
|
return errorPage(res, 502, 'Login unavailable', data?.message || 'Could not start the YOUreka login flow. Please try again.');
|
2026-09-30 23:12:51 +01:00
|
|
|
}
|
|
|
|
|
res.redirect(data.loginUrl);
|
|
|
|
|
} catch {
|
2026-10-01 01:13:30 +01:00
|
|
|
errorPage(res, 502, 'Login unavailable', 'Could not reach the YOUreka portal. Please try again.');
|
2026-09-30 23:12:51 +01:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
app.get('/auth/callback', async (req, res) => {
|
|
|
|
|
const { sessionId } = req.query;
|
2026-10-01 01:13:30 +01:00
|
|
|
if (!sessionId) return errorPage(res, 401, 'Login failed', 'Missing login session. Please start again.');
|
2026-09-30 23:12:51 +01:00
|
|
|
try {
|
|
|
|
|
const r = await cfg.fetch(
|
|
|
|
|
`${cfg.portalUrl.replace(/\/+$/, '')}/api/web/auth/${encodeURIComponent(sessionId)}/cookie`
|
|
|
|
|
);
|
|
|
|
|
const data = await r.json().catch(() => null);
|
|
|
|
|
if (!r.ok || !data?.ok) {
|
2026-10-01 01:13:30 +01:00
|
|
|
return errorPage(res, 401, 'Login failed', 'Authentication failed. The link may have expired — please try again.');
|
2026-09-30 23:12:51 +01:00
|
|
|
}
|
|
|
|
|
if (data.status === 'Initialized' || data.status === 'TimedOut') {
|
|
|
|
|
return errorPage(
|
|
|
|
|
res,
|
2026-10-01 01:13:30 +01:00
|
|
|
401,
|
2026-09-30 23:12:51 +01:00
|
|
|
'Login failed',
|
|
|
|
|
data.status === 'TimedOut'
|
|
|
|
|
? 'Your login session timed out. Please start again.'
|
|
|
|
|
: 'Verification incomplete. Please complete the login flow.'
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
const sessionValue = extractPbCookieValue(data.cookie || '');
|
|
|
|
|
if (!sessionValue) {
|
2026-10-01 01:13:30 +01:00
|
|
|
return errorPage(res, 401, 'Login failed', 'The portal did not return a usable session. Please try again.');
|
2026-09-30 23:12:51 +01:00
|
|
|
}
|
|
|
|
|
setSessionCookie(req, res, sessionValue);
|
|
|
|
|
setProfileCookie(req, res, {
|
|
|
|
|
firstName: data.firstName ?? '',
|
|
|
|
|
lastName: data.lastName ?? '',
|
|
|
|
|
phone: data.phone ?? '',
|
|
|
|
|
});
|
|
|
|
|
res.redirect('/fingerprint');
|
|
|
|
|
} catch {
|
2026-10-01 01:13:30 +01:00
|
|
|
errorPage(res, 401, 'Login failed', 'Could not reach the YOUreka portal. Please try again.');
|
2026-09-30 23:12:51 +01:00
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
app.get('/auth/logout', (req, res) => {
|
|
|
|
|
res.clearCookie('session', { path: '/' });
|
|
|
|
|
res.clearCookie('user_profile', { path: '/' });
|
|
|
|
|
res.redirect('/');
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// ── session context + permitted domains ───────────────────────────────────
|
|
|
|
|
const domainContext = async (req, { force = false } = {}) =>
|
|
|
|
|
permittedDomains({
|
|
|
|
|
domains: cfg.domains,
|
|
|
|
|
phone: stripPhonePrefix(req.session.phone),
|
|
|
|
|
portalUrl: cfg.portalUrl,
|
|
|
|
|
fetchImpl: cfg.fetch,
|
|
|
|
|
cache: domainCache,
|
|
|
|
|
ttlMs: cfg.ttlMs,
|
|
|
|
|
now: cfg.now,
|
|
|
|
|
force,
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const domainPayload = (codes, checkedAt) => ({
|
|
|
|
|
domains: cfg.domains.filter((d) => codes.includes(d.code)),
|
|
|
|
|
domainsCheckedAt: checkedAt,
|
|
|
|
|
});
|
|
|
|
|
|
2026-10-01 03:28:31 +01:00
|
|
|
const sessionPayload = async (req, { withDomains = false } = {}) => {
|
|
|
|
|
const base = {
|
|
|
|
|
phone: req.session.phone,
|
|
|
|
|
firstName: req.session.firstName,
|
|
|
|
|
lastName: req.session.lastName,
|
|
|
|
|
};
|
|
|
|
|
if (!withDomains) return base;
|
|
|
|
|
const { codes, checkedAt } = await domainContext(req);
|
|
|
|
|
return {
|
|
|
|
|
...base,
|
|
|
|
|
token: req.session.token,
|
|
|
|
|
agentUrl: cfg.agentUrl,
|
|
|
|
|
domainCacheTtlMs: cfg.ttlMs,
|
|
|
|
|
...domainPayload(codes, checkedAt),
|
|
|
|
|
};
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
* Render a page with the operator's session injected server-side, so the
|
|
|
|
|
* client never has to fetch it (and never flashes a loading state).
|
|
|
|
|
* Per-user content — must not be cached.
|
|
|
|
|
*/
|
|
|
|
|
const renderPage = (res, file, session) => {
|
|
|
|
|
fs.readFile(path.join(__dirname, 'public', 'assets', file), 'utf8', (error, html) => {
|
|
|
|
|
if (error) return errorPage(res, 500, 'Something went wrong', 'The page could not be loaded.');
|
|
|
|
|
const data = session
|
|
|
|
|
? JSON.stringify(session).replace(/</g, '\\u003c') // keep markup out of the script tag
|
|
|
|
|
: 'null';
|
|
|
|
|
res
|
|
|
|
|
.set('Cache-Control', 'no-store')
|
|
|
|
|
.set('Vary', 'Cookie')
|
|
|
|
|
.type('html')
|
|
|
|
|
.send(html.replace('</head>', ` <script>window.__SESSION__ = ${data};</script>\n</head>`));
|
|
|
|
|
});
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
app.get('/', (req, res, next) => {
|
|
|
|
|
fs.readFile(path.join(__dirname, 'public', 'index.html'), 'utf8', (error, html) => {
|
|
|
|
|
if (error) return next(error);
|
|
|
|
|
const nav = req.session
|
|
|
|
|
? `<span class="user-chip"><span class="avatar">${esc((req.session.firstName || req.session.phone || '?').trim().slice(0, 2).toUpperCase())}</span>${esc(req.session.firstName || req.session.phone || '')}</span><a class="linklike" href="/auth/logout">Sign out</a>`
|
|
|
|
|
: '<a class="linklike" href="/auth/login">Sign in</a>';
|
|
|
|
|
res
|
|
|
|
|
.set('Cache-Control', 'no-store')
|
|
|
|
|
.set('Vary', 'Cookie')
|
|
|
|
|
.type('html')
|
|
|
|
|
.send(html.replace('<!--session-nav-->', nav));
|
|
|
|
|
});
|
|
|
|
|
});
|
|
|
|
|
|
2026-09-30 23:12:51 +01:00
|
|
|
app.get('/auth/session', requireApi, async (req, res, next) => {
|
|
|
|
|
try {
|
|
|
|
|
const { codes, checkedAt } = await domainContext(req);
|
|
|
|
|
res.json({
|
|
|
|
|
ok: true,
|
|
|
|
|
token: req.session.token,
|
|
|
|
|
phone: req.session.phone,
|
|
|
|
|
firstName: req.session.firstName,
|
|
|
|
|
lastName: req.session.lastName,
|
|
|
|
|
agentUrl: cfg.agentUrl,
|
|
|
|
|
domainCacheTtlMs: cfg.ttlMs,
|
|
|
|
|
...domainPayload(codes, checkedAt),
|
|
|
|
|
});
|
|
|
|
|
} catch (e) {
|
|
|
|
|
next(e);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
app.post('/auth/domains/refresh', requireApi, async (req, res, next) => {
|
|
|
|
|
try {
|
|
|
|
|
const { codes, checkedAt } = await domainContext(req, { force: true });
|
|
|
|
|
res.json({ ok: true, ...domainPayload(codes, checkedAt) });
|
|
|
|
|
} catch (e) {
|
|
|
|
|
if (e?.code === CACHE_FRESH) {
|
|
|
|
|
return res
|
|
|
|
|
.status(409)
|
|
|
|
|
.json({ ok: false, message: 'Permissions were checked recently. The refresh option unlocks when the cache expires.' });
|
|
|
|
|
}
|
|
|
|
|
next(e);
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
// ── wizard page (session required) ────────────────────────────────────────
|
2026-10-01 03:28:31 +01:00
|
|
|
app.get('/fingerprint', requirePage, async (req, res, next) => {
|
|
|
|
|
try {
|
|
|
|
|
renderPage(res, 'fp/index.html', await sessionPayload(req, { withDomains: true }));
|
|
|
|
|
} catch (e) {
|
|
|
|
|
next(e);
|
|
|
|
|
}
|
2026-09-30 23:12:51 +01:00
|
|
|
});
|
|
|
|
|
|
2026-10-01 01:13:30 +01:00
|
|
|
// ── cropper page + namespaced API (session + crop_image required) ────────
|
|
|
|
|
const cropGateContext = {
|
|
|
|
|
portalUrl: cfg.portalUrl,
|
|
|
|
|
fetchImpl: cfg.fetch,
|
|
|
|
|
cache: cropCache,
|
|
|
|
|
ttlMs: cfg.ttlMs,
|
|
|
|
|
now: cfg.now,
|
|
|
|
|
};
|
|
|
|
|
const pageCropGate = async (req, res, next) => {
|
|
|
|
|
let allowed = false;
|
|
|
|
|
try {
|
|
|
|
|
({ allowed } = await cropPermission({
|
|
|
|
|
phone: stripPhonePrefix(req.session.phone),
|
|
|
|
|
...cropGateContext,
|
|
|
|
|
}));
|
|
|
|
|
} catch {
|
|
|
|
|
allowed = false; // fail closed
|
|
|
|
|
}
|
|
|
|
|
if (!allowed) {
|
|
|
|
|
return errorPage(
|
|
|
|
|
res,
|
|
|
|
|
403,
|
2026-10-01 01:35:37 +01:00
|
|
|
'No access',
|
|
|
|
|
'Your account doesn\u2019t have permission to crop images. Ask a domain administrator to grant you access.',
|
|
|
|
|
{ icon: 'lock', primary: { href: '/', label: 'Back to Tools' }, secondary: null }
|
2026-10-01 01:13:30 +01:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
next();
|
|
|
|
|
};
|
2026-10-01 03:28:31 +01:00
|
|
|
app.get('/cropper', requirePage, pageCropGate, (req, res, next) => {
|
|
|
|
|
renderPage(res, 'cropper/index.html', {
|
|
|
|
|
phone: req.session.phone,
|
|
|
|
|
firstName: req.session.firstName,
|
|
|
|
|
lastName: req.session.lastName,
|
|
|
|
|
});
|
2026-10-01 01:13:30 +01:00
|
|
|
});
|
|
|
|
|
const cropperClients = cfg.cropperClients !== undefined ? cfg.cropperClients : buildCropperClients();
|
|
|
|
|
if (cropperClients) {
|
|
|
|
|
app.use(
|
|
|
|
|
'/cropper',
|
|
|
|
|
createCropperRouter({
|
|
|
|
|
...cropperClients,
|
|
|
|
|
a2loftBase: cfg.a2loftBase,
|
2026-10-01 03:12:02 +01:00
|
|
|
domainCodes,
|
2026-10-01 01:13:30 +01:00
|
|
|
removebgUrl: cfg.removebgUrl,
|
|
|
|
|
noderedBase: cfg.noderedBase,
|
|
|
|
|
...cropGateContext,
|
|
|
|
|
requireApi,
|
|
|
|
|
})
|
|
|
|
|
);
|
|
|
|
|
} else {
|
|
|
|
|
app.use('/cropper', (req, res) =>
|
|
|
|
|
res.status(503).json({ ok: false, message: 'The image cropper is not configured on this deployment.' })
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-30 23:12:51 +01:00
|
|
|
// ── a2loft proxies: same-origin, phone injected from the session ──────────
|
|
|
|
|
const a2loftUrl = (domain, reference, otp, phone) => {
|
|
|
|
|
const q = new URLSearchParams({ phone, otp });
|
|
|
|
|
return `${cfg.a2loftBase.replace(/\/+$/, '')}/identity/${encodeURIComponent(domain)}/${encodeURIComponent(
|
|
|
|
|
reference
|
|
|
|
|
)}?${q.toString()}`;
|
|
|
|
|
};
|
|
|
|
|
const a2loftSaveUrl = (domain, reference, otp, phone) => {
|
|
|
|
|
const q = new URLSearchParams({ phone, otp });
|
|
|
|
|
return `${cfg.a2loftBase.replace(/\/+$/, '')}/identity/${encodeURIComponent(domain)}/fingerprints/${encodeURIComponent(
|
|
|
|
|
reference
|
|
|
|
|
)}?${q.toString()}`;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
const validateProxy = (req, res) => {
|
|
|
|
|
const { domain, reference } = req.params;
|
|
|
|
|
if (!domainCodes.has(domain)) {
|
|
|
|
|
res.status(400).json({ ok: false, message: 'Unknown domain.' });
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
if (!reference) {
|
|
|
|
|
res.status(400).json({ ok: false, message: 'Missing staff reference.' });
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
if (!req.query.otp) {
|
|
|
|
|
res.status(400).json({ ok: false, message: 'OTP is required.' });
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
if (!req.session.phone) {
|
|
|
|
|
res.status(400).json({ ok: false, message: 'The signed-in account has no phone number.' });
|
|
|
|
|
return false;
|
|
|
|
|
}
|
|
|
|
|
return true;
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
app.post('/api/:domain/staff/:reference', requireApi, async (req, res) => {
|
|
|
|
|
if (!validateProxy(req, res)) return;
|
|
|
|
|
try {
|
|
|
|
|
const r = await cfg.fetch(a2loftUrl(req.params.domain, req.params.reference, req.query.otp, req.session.phone));
|
|
|
|
|
res.status(r.status).type('json').send(await r.text());
|
|
|
|
|
} catch {
|
|
|
|
|
res.status(502).json({ ok: false, message: 'Could not reach the identity service.' });
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
app.post('/api/:domain/staff/:reference/fingerprints', requireApi, async (req, res) => {
|
|
|
|
|
if (!validateProxy(req, res)) return;
|
|
|
|
|
if (!Array.isArray(req.body?.fingerprints) || req.body.fingerprints.length === 0) {
|
|
|
|
|
return res.status(400).json({ ok: false, message: 'A fingerprints array is required.' });
|
|
|
|
|
}
|
|
|
|
|
try {
|
|
|
|
|
const r = await cfg.fetch(a2loftSaveUrl(req.params.domain, req.params.reference, req.query.otp, req.session.phone), {
|
|
|
|
|
method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(req.body)
|
|
|
|
|
});
|
|
|
|
|
res.status(r.status).type('json').send(await r.text());
|
|
|
|
|
} catch {
|
|
|
|
|
res.status(502).json({ ok: false, message: 'Could not reach the identity service.' });
|
|
|
|
|
}
|
|
|
|
|
});
|
|
|
|
|
|
2026-10-01 03:12:02 +01:00
|
|
|
// ── error handler (async handlers are wrapped; this catches next(err)) ─────
|
|
|
|
|
// eslint-disable-next-line no-unused-vars
|
|
|
|
|
app.use((err, req, res, next) => {
|
|
|
|
|
const status = err.status || err.statusCode || 500;
|
|
|
|
|
if (status >= 500) console.error('[error]', req.method, req.path, err && err.message);
|
|
|
|
|
if (res.headersSent) return next(err);
|
|
|
|
|
const message =
|
|
|
|
|
status === 413 ? 'The request is too large.'
|
|
|
|
|
: status >= 500 ? 'An unexpected error occurred. Please try again.'
|
|
|
|
|
: err.message || 'The request could not be processed.';
|
|
|
|
|
if (req.path === '/cropper' || req.path.startsWith('/auth/')) {
|
|
|
|
|
return errorPage(res, status, status === 413 ? 'Request too large' : 'Something went wrong', message);
|
|
|
|
|
}
|
|
|
|
|
res.status(status).json({ ok: false, message });
|
|
|
|
|
});
|
|
|
|
|
|
2026-09-30 23:12:51 +01:00
|
|
|
return app;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const isMain = process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href;
|
|
|
|
|
if (isMain) {
|
|
|
|
|
createApp().listen(PORT, () => {
|
|
|
|
|
console.log(`YOUreka Tools listening on http://localhost:${PORT}`);
|
|
|
|
|
});
|
|
|
|
|
}
|