Skip to content

A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.

JavaScript

fix(supervisor): enforce admin auth on control-center, merchant-admin proxies, and observer status (#3)

Harshbb7dc037e6d8
diff --git a/apps/control-center/src/server.js b/apps/control-center/src/server.js
index b7f1c52..cafe13a 100644
--- a/apps/control-center/src/server.js
+++ b/apps/control-center/src/server.js
@@ -19,11 +19,19 @@ const BASE_SECURITY_HEADERS = Object.freeze({
/** Routes reachable without a credential (liveness probe and the dashboard shell). */
const PUBLIC_PATHS = new Set(['/health', '/', '/dashboard', '/fonts/dm-sans.woff2', '/fonts/sora.woff2']);
-/** True when the caller presented the admin bearer token in constant time. */
-function hasAdminToken(req) {
+/** True when the caller presented the admin bearer token in constant time (or ?token= on GET SSE). */
+function hasAdminToken(req, url = null, pathname = '') {
const match = /^Bearer\s+(.+)$/i.exec(req.headers?.['authorization'] || '');
- if (!match) return false;
- return safeEqual(match[1].trim(), getAdminToken());
+ if (match) {
+ return safeEqual(match[1].trim(), getAdminToken());
+ }
+ if (req.method?.toUpperCase() === 'GET' && pathname === '/api/logs/stream' && url) {
+ const queryToken = (url.searchParams.get('token') || '').trim();
+ if (queryToken) {
+ return safeEqual(queryToken, getAdminToken());
+ }
+ }
+ return false;
}
export class ControlCenterServer {
@@ -84,7 +92,7 @@ export class ControlCenterServer {
// Every remaining route controls processes, streams service logs or exposes internal
// state. Without a token these are a remote denial-of-service and a log-exfiltration
// primitive, so the admin bearer is required.
- if (!PUBLIC_PATHS.has(pathname) && !hasAdminToken(req)) {
+ if (!PUBLIC_PATHS.has(pathname) && !hasAdminToken(req, url, pathname)) {
res.writeHead(401, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Unauthorized', code: 'AUTH_REQUIRED' }));
return;
diff --git a/apps/control-center/src/views/dashboard.html b/apps/control-center/src/views/dashboard.html
index 6bc6658..19be007 100644
--- a/apps/control-center/src/views/dashboard.html
+++ b/apps/control-center/src/views/dashboard.html
@@ -256,6 +256,82 @@
<script>
let sse = null;
+ window.__youpiAdminAuth = (function () {
+ const KEY = 'youpi_admin_token';
+ const nativeFetch = window.fetch.bind(window);
+ let pending = null;
+
+ const read = () => { try { return sessionStorage.getItem(KEY) || ''; } catch (e) { return ''; } };
+ const write = (t) => { try { sessionStorage.setItem(KEY, t); } catch (e) {} };
+ const clear = () => { try { sessionStorage.removeItem(KEY); } catch (e) {} };
+
+ function isProtected(url) {
+ return /\/api\/services/.test(url);
+ }
+
+ function prompt(message) {
+ if (pending) return pending;
+ pending = new Promise((resolve) => {
+ const overlay = document.createElement('div');
+ overlay.style.cssText = 'position:fixed;inset:0;z-index:2147483647;background:rgba(15,23,42,.85);display:flex;align-items:center;justify-content:center;padding:16px;font-family:system-ui,sans-serif';
+ const box = document.createElement('form');
+ box.style.cssText = 'background:#fff;color:#0f172a;border-radius:12px;padding:24px;max-width:420px;width:100%;box-shadow:0 20px 50px rgba(0,0,0,.4)';
+ const title = document.createElement('h3');
+ title.textContent = 'Admin token required';
+ title.style.margin = '0 0 8px';
+ const hint = document.createElement('p');
+ hint.textContent = message || 'Enter the admin API token (ADMIN_API_TOKEN, or the contents of data/.secrets/admin_api_token on the server).';
+ hint.style.cssText = 'margin:0 0 12px;font-size:14px;color:#475569';
+ const input = document.createElement('input');
+ input.type = 'password';
+ input.autocomplete = 'off';
+ input.required = true;
+ input.style.cssText = 'width:100%;box-sizing:border-box;padding:10px;border:1px solid #cbd5e1;border-radius:8px;margin-bottom:12px';
+ const btn = document.createElement('button');
+ btn.type = 'submit';
+ btn.textContent = 'Unlock';
+ btn.style.cssText = 'width:100%;padding:10px;border:0;border-radius:8px;background:#0f766e;color:#fff;font-weight:600;cursor:pointer';
+ box.append(title, hint, input, btn);
+ overlay.appendChild(box);
+ document.body.appendChild(overlay);
+ input.focus();
+ box.addEventListener('submit', (ev) => {
+ ev.preventDefault();
+ write(input.value.trim());
+ overlay.remove();
+ pending = null;
+ resolve();
+ });
+ });
+ return pending;
+ }
+
+ async function authedFetch(input, init) {
+ const url = typeof input === 'string' ? input : (input && input.url) || '';
+ if (!isProtected(url)) return nativeFetch(input, init);
+ if (!read()) {
+ await prompt();
+ if (typeof connectLogsSse === 'function') connectLogsSse();
+ }
+ const attempt = () => {
+ const headers = new Headers((init && init.headers) || (input && input.headers) || {});
+ headers.set('Authorization', 'Bearer ' + read());
+ return nativeFetch(input, Object.assign({}, init, { headers }));
+ };
+ let res = await attempt();
+ if (res.status === 401) {
+ clear();
+ await prompt('That token was rejected. Enter the admin API token again.');
+ res = await attempt();
+ if (res.ok && typeof connectLogsSse === 'function') connectLogsSse();
+ }
+ return res;
+ }
+
+ window.fetch = authedFetch;
+ return { token: read, ensure: () => (read() ? Promise.resolve() : prompt()) };
+ })();
+
const THEME_KEY = 'youpi-theme';
const themeMQ = window.matchMedia('(prefers-color-scheme: dark)');
@@ -365,7 +441,9 @@
function connectLogsSse() {
if (sse) sse.close();
- sse = new EventSource('/api/logs/stream');
+ const token = window.__youpiAdminAuth ? window.__youpiAdminAuth.token() : '';
+ if (!token) return;
+ sse = new EventSource(`/api/logs/stream?token=${encodeURIComponent(token)}`);
sse.addEventListener('log', (e) => {
try {
diff --git a/apps/gmail-observer/src/server.js b/apps/gmail-observer/src/server.js
index 9d941d7..65777b9 100644
--- a/apps/gmail-observer/src/server.js
+++ b/apps/gmail-observer/src/server.js
@@ -375,8 +375,8 @@ export class GmailObserverServer {
// GET /api/browser/status
if (pathname === '/api/browser/status') {
- // Auto-ensure connection if currently idle/standby
- if (this.automator.mode === 'STANDBY' && !this.automator.isEnsuring) {
+ // Only trigger a background connection attempt when an authenticated observer/admin asks
+ if (hasBearer(req, getObserverToken(), getAdminToken()) && this.automator.mode === 'STANDBY' && !this.automator.isEnsuring) {
this.automator.autoEnsureConnection().catch(() => {});
}
res.writeHead(200, {
diff --git a/apps/merchant-admin/src/__tests__/merchant-admin.test.js b/apps/merchant-admin/src/__tests__/merchant-admin.test.js
index e02bd15..a8efb3b 100644
--- a/apps/merchant-admin/src/__tests__/merchant-admin.test.js
+++ b/apps/merchant-admin/src/__tests__/merchant-admin.test.js
@@ -64,4 +64,18 @@ describe('Merchant Admin Integration Tests', () => {
const json = JSON.parse(res.text);
assert.ok(Array.isArray(json));
});
+
+ test('Control Center supervisor proxy routes (/api/services* and /api/logs/stream) require the admin token', async () => {
+ const anonServices = await get('/api/services');
+ assert.equal(anonServices.status, 401);
+
+ const wrongToken = await get('/api/services', { Authorization: 'Bearer wrong-token' });
+ assert.equal(wrongToken.status, 401);
+
+ const anonLogs = await get('/api/logs/stream');
+ assert.equal(anonLogs.status, 401);
+
+ const wrongQueryLogs = await get('/api/logs/stream?token=wrong-token');
+ assert.equal(wrongQueryLogs.status, 401);
+ });
});
diff --git a/apps/merchant-admin/src/server.js b/apps/merchant-admin/src/server.js
index 8672cea..4f2a75d 100644
--- a/apps/merchant-admin/src/server.js
+++ b/apps/merchant-admin/src/server.js
@@ -16,11 +16,19 @@ const BASE_SECURITY_HEADERS = Object.freeze({
'Content-Security-Policy': "default-src 'self'; img-src 'self' data: https:; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; frame-ancestors 'self'; base-uri 'none'; form-action 'self'; object-src 'none'"
});
-/** True when the caller presented the admin bearer token in constant time. */
-function hasAdminToken(req) {
+/** True when the caller presented the admin bearer token in constant time (or ?token= on GET SSE). */
+function hasAdminToken(req, url = null, pathname = '') {
const match = /^Bearer\s+(.+)$/i.exec(req.headers?.['authorization'] || '');
- if (!match) return false;
- return safeEqual(match[1].trim(), getAdminToken());
+ if (match) {
+ return safeEqual(match[1].trim(), getAdminToken());
+ }
+ if (req.method?.toUpperCase() === 'GET' && pathname === '/api/logs/stream' && url) {
+ const queryToken = (url.searchParams.get('token') || '').trim();
+ if (queryToken) {
+ return safeEqual(queryToken, getAdminToken());
+ }
+ }
+ return false;
}
/**
@@ -122,18 +130,22 @@ export class AdminServer {
// Relaying this unauthenticated would republish process control and every service's
// stdout/stderr on the internet-facing admin host, so the admin token is required.
if (pathname.startsWith('/api/services') || pathname === '/api/logs/stream') {
- if (!hasAdminToken(req)) {
+ if (!hasAdminToken(req, url, pathname)) {
res.writeHead(401, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Unauthorized', code: 'AUTH_REQUIRED' }));
return;
}
const ccPort = Number(process.env.CONTROL_CENTER_PORT || 8090);
+ const forwardHeaders = sanitizedForwardHeaders(req, `localhost:${ccPort}`);
+ if (!forwardHeaders.authorization && !forwardHeaders.Authorization) {
+ forwardHeaders.Authorization = `Bearer ${getAdminToken()}`;
+ }
const proxyReq = http.request({
hostname: '127.0.0.1',
port: ccPort,
path: req.url,
method: req.method,
- headers: sanitizedForwardHeaders(req, `localhost:${ccPort}`)
+ headers: forwardHeaders
}, (proxyRes) => {
res.writeHead(proxyRes.statusCode, proxyRes.headers);
proxyRes.pipe(res);
diff --git a/apps/merchant-admin/src/views/admin.html b/apps/merchant-admin/src/views/admin.html
index 81e25f9..4443878 100644
--- a/apps/merchant-admin/src/views/admin.html
+++ b/apps/merchant-admin/src/views/admin.html
@@ -3683,7 +3683,7 @@
const clear = () => { try { sessionStorage.removeItem(KEY); } catch (e) {} };
function isProtected(url) {
- return /\/api\/v1\/admin\//.test(url) && !/\/admin\/sms-gateway\/download-apk/.test(url);
+ return (/\/api\/v1\/admin\//.test(url) || /\/api\/services/.test(url) || /\/api\/admin\/tickets/.test(url)) && !/\/admin\/sms-gateway\/download-apk/.test(url);
}
function prompt(message) {
@@ -3729,6 +3729,7 @@
if (!read()) {
await prompt();
if (typeof connectAdminEventsSse === 'function') connectAdminEventsSse();
+ if (typeof connectServicesLogsSse === 'function') connectServicesLogsSse();
}
const attempt = () => {
const headers = new Headers((init && init.headers) || (input && input.headers) || {});
@@ -3741,6 +3742,7 @@
await prompt('That token was rejected. Enter the admin API token again.');
res = await attempt();
if (res.ok && typeof connectAdminEventsSse === 'function') connectAdminEventsSse();
+ if (res.ok && typeof connectServicesLogsSse === 'function') connectServicesLogsSse();
}
return res;
}
@@ -4147,8 +4149,10 @@
let rawLogsBuffer = [];
function connectServicesLogsSse() {
if (servicesLogsSse) return;
+ const token = window.__youpiAdminAuth ? window.__youpiAdminAuth.token() : '';
+ if (!token) return;
try {
- servicesLogsSse = new EventSource('/api/logs/stream');
+ servicesLogsSse = new EventSource(`/api/logs/stream?token=${encodeURIComponent(token)}`);
servicesLogsSse.addEventListener('log', (e) => {
try {
const entry = JSON.parse(e.data);
diff --git a/apps/sms-observer/src/server.js b/apps/sms-observer/src/server.js
index be5f178..aff6cbd 100644
--- a/apps/sms-observer/src/server.js
+++ b/apps/sms-observer/src/server.js
@@ -47,8 +47,8 @@ export class SmsObserverServer {
// GET /api/browser/status
if (pathname === '/api/browser/status') {
- // Auto-ensure connection if currently idle/standby
- if (this.automator.mode === 'STANDBY' && !this.automator.isEnsuring) {
+ // Only trigger a background connection attempt when an authenticated observer/admin asks
+ if (hasBearer(req, getObserverToken(), getAdminToken()) && this.automator.mode === 'STANDBY' && !this.automator.isEnsuring) {
this.automator.autoEnsureConnection().catch(() => {});
}
res.writeHead(200, {