// Server-side session manager for the legacy PHP backend (backend.acherryontop.com). // // WHY THIS EXISTS // --------------- // The PHP `/apiv2/*` write endpoints (product edit, image_changes, taxonomy // set, setup_new, prod_cat/new, po/new, po/add_products) authenticate via a // PHP session cookie. In the browser the frontend gets that for free with // `credentials: 'include'` because the user is logged into // backend.acherryontop.com in the same browser — that flow is unchanged and // this module does NOT touch it. // // This module backs a separate SIDE-SERVICE (see routes/apiv2-bridge.js) that // lets EXTERNAL apps (the product-import skill, a future product-edit skill) // post to the PHP API without a browser cookie. The inventory-server holds the // PHP session itself: it logs in once with a SERVICE account, caches every // cookie the backend hands back, and replays them on outbound `/apiv2/*` // requests. Callers authenticate to the inventory-server with the normal user // JWT; this PHP-session layer is invisible to them. // // LOGIN FLOW (discovered from the live login page) // ------------------------------------------------ // 1. GET /login -> sets affinity/session cookies + embeds a // hidden `anti_csrf` token in the form HTML. // 2. POST /login/login -> { anti_csrf, userid, pin, after_login:'', // Submit:'Submit' } with the cookies from (1). // On success the backend rotates/sets the // authenticated session cookie. // // EXPIRY DETECTION // ---------------- // Unauthenticated `/apiv2/*` calls return HTTP 200 with an HTML body (the login // page), NOT a 401. So we sniff the response body the same way the frontend // does (isHtmlResponse) and treat an HTML payload as "session dead" -> re-login // once and retry. import axios from 'axios'; import { logger } from '../../shared/logging/logger.js'; const BASE_URL = (process.env.ACOT_BACKEND_URL || 'https://backend.acherryontop.com').replace(/\/$/, ''); const USERID = process.env.ACOT_BACKEND_USERID; const PIN = process.env.ACOT_BACKEND_PIN; const USER_AGENT = 'inventory-server/apiv2-bridge'; // Single host => a simple name->value map is a sufficient cookie jar. We do NOT // hardcode any cookie name: the backend sets a load-balancer affinity cookie // (`S=...`) AND the real session cookie, and both must be replayed for the // session to stick. Capturing every Set-Cookie generically handles both. let cookieJar = new Map(); // Mutex: collapse concurrent login attempts into one in-flight promise so a // burst of bridged requests doesn't trigger N parallel logins. let loginInFlight = null; function cookieHeader() { return Array.from(cookieJar.entries()) .map(([name, value]) => `${name}=${value}`) .join('; '); } function storeSetCookies(setCookieHeaders) { if (!setCookieHeaders) return; const list = Array.isArray(setCookieHeaders) ? setCookieHeaders : [setCookieHeaders]; for (const raw of list) { const first = String(raw).split(';')[0]; const eq = first.indexOf('='); if (eq === -1) continue; const name = first.slice(0, eq).trim(); const value = first.slice(eq + 1).trim(); if (!name) continue; // A `name=deleted`/empty value means the backend is clearing the cookie. if (value === '' || value.toLowerCase() === 'deleted') { cookieJar.delete(name); } else { cookieJar.set(name, value); } } } export function isHtmlResponse(payload) { if (typeof payload !== 'string') return false; const trimmed = payload.trim().toLowerCase(); return trimmed.startsWith(' whose `type=` matches, tolerant of // attribute order and quote style. function inputNameByType(html, type) { const tags = String(html).match(/]*>/gi) || []; const typeRe = new RegExp(`type=['"]${type}['"]`, 'i'); for (const tag of tags) { if (typeRe.test(tag)) { const nm = /name=['"]([^'"]+)['"]/i.exec(tag); if (nm) return nm[1]; } } return null; } function hasPasswordField(html) { return /]*type=['"]password['"]/i.test(String(html)); } async function performLogin() { if (!USERID || !PIN) { throw new Error( 'ACOT backend service credentials are not configured (set ACOT_BACKEND_USERID and ACOT_BACKEND_PIN)' ); } // Fresh jar for a clean login. cookieJar = new Map(); // Step 1: GET the login page for cookies + the anti-CSRF token. The login is // IP-based and serves DIFFERENT forms per network (office: userid/pin; outside: // username/password), so we parse the served form rather than hardcoding field // names — the credential pair maps to whatever identifier/secret fields appear. const getRes = await axios.get(`${BASE_URL}/login`, { maxRedirects: 0, validateStatus: () => true, headers: { 'User-Agent': USER_AGENT }, responseType: 'text', transformResponse: (d) => d, }); storeSetCookies(getRes.headers['set-cookie']); const page = getRes.data || ''; const csrfMatch = /name=['"]anti_csrf['"][^>]*value=['"]([^'"]+)['"]/i.exec(page); if (!csrfMatch) { throw new Error('Could not locate anti_csrf token on the backend login page'); } const antiCsrf = csrfMatch[1]; const actionMatch = /