// © 2026 Evntx FZCO, Dubai, UAE. All rights reserved. /** * Reference app server — sign-in by one-time code (manifest `sso.mode: "code"`). Standard library only, Node 20+. * * AANCER_PLATFORM_ORIGIN=https://platform.example AANCER_APP_SECRET= node server.mjs * * Environment: * AANCER_PLATFORM_ORIGIN the address users open the platform at (required) — the only site allowed to embed us * AANCER_GATEWAY_URL where THIS server reaches the platform (default: AANCER_PLATFORM_ORIGIN) * AANCER_APP_ID the app id of the manifest (default: shift-planner) * AANCER_APP_SECRET shown once under Extensions → the pack → Manage app → Create app secret * HOST / PORT listen address (default 127.0.0.1:8787; put your TLS proxy in front) * A private certificate authority on the platform: start Node with NODE_EXTRA_CA_CERTS=/path/to/ca.pem. * * What stays on this server and never reaches the browser: the app secret, the PKCE verifier, the platform token. * The browser gets a session handle of our own. * * ponytail: handshakes and sessions live in this process's memory — one process only. Behind a load balancer put * the two maps in your shared session store. */ import http from 'node:http'; import { createHash, randomBytes } from 'node:crypto'; import { readFile } from 'node:fs/promises'; import { fileURLToPath } from 'node:url'; const env = process.env; const PLATFORM = (env.AANCER_PLATFORM_ORIGIN ?? '').replace(/\/+$/, ''); if (!/^https?:\/\/[^/]+$/.test(PLATFORM)) { console.error('Set AANCER_PLATFORM_ORIGIN to the address users open the platform at, for example https://platform.example'); process.exit(2); } const GATEWAY = (env.AANCER_GATEWAY_URL ?? PLATFORM).replace(/\/+$/, ''); const APP_ID = env.AANCER_APP_ID ?? 'shift-planner'; const SECRET = env.AANCER_APP_SECRET ?? ''; const BASIC = 'Basic ' + Buffer.from(`${APP_ID}:${SECRET}`).toString('base64'); const HANDSHAKE_TTL_MS = 120_000; const FILES = { '/': ['index.html', 'text/html'], '/index.html': ['index.html', 'text/html'], '/static.html': ['static.html', 'text/html'], '/app.js': ['app.js', 'text/javascript'], '/static.js': ['static.js', 'text/javascript'], '/aancer-app-sdk.js': ['aancer-app-sdk.js', 'text/javascript'] }; const handshakes = new Map(); // handshake id → { verifier, at } const sessions = new Map(); // our session handle → { token } const b64url = (buf) => buf.toString('base64url'); const gateway = (path, init) => fetch(GATEWAY + path, { ...init, headers: { authorization: BASIC, ...init.headers }, signal: AbortSignal.timeout(10_000) }); /** Ask the platform whether the token is still good and who it belongs to. Any error counts as "not signed in". */ async function introspect(token) { try { const r = await gateway('/api/apps/introspect', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ token }) }); const b = r.ok ? await r.json() : { active: false }; return b.active === true ? { sub: b.sub, name: b.name, email: b.email, workspaceId: b.workspaceId, role: b.role } : null; } catch { return null; } } async function readJson(req) { let size = 0; const chunks = []; for await (const c of req) { size += c.length; if (size > 4096) throw new Error('too large'); chunks.push(c); } return chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}; } const handleOf = (req) => /^Bearer (.+)$/.exec(req.headers.authorization ?? '')?.[1] ?? ''; const server = http.createServer(async (req, res) => { // Only the platform may embed this app; nothing but our own files and our own server is loaded or called. res.setHeader('Content-Security-Policy', `frame-ancestors ${PLATFORM}; default-src 'self'`); res.setHeader('Cache-Control', 'no-store'); res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('Referrer-Policy', 'no-referrer'); const send = (status, body) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(body)); }; const path = new URL(req.url ?? '/', 'http://localhost').pathname; try { if (req.method === 'GET' && FILES[path]) { const [name, type] = FILES[path]; let body = await readFile(fileURLToPath(new URL(`./public/${name}`, import.meta.url)), 'utf8'); if (type === 'text/html') body = body.replace('__AANCER_PLATFORM_ORIGIN__', PLATFORM); res.writeHead(200, { 'content-type': `${type}; charset=utf-8` }); return res.end(body); } // Step 1 — a PKCE pair: the verifier stays here, the challenge goes to the frame. if (req.method === 'POST' && path === '/app/handshake/start') { if (!SECRET) return send(503, { message: 'This app server has no app secret yet (AANCER_APP_SECRET).' }); const now = Date.now(); for (const [k, v] of handshakes) if (now - v.at > HANDSHAKE_TTL_MS) handshakes.delete(k); const handshake = b64url(randomBytes(16)), verifier = b64url(randomBytes(32)); handshakes.set(handshake, { verifier, at: now }); return send(200, { handshake, codeChallenge: b64url(createHash('sha256').update(verifier).digest()) }); } // Step 3 — redeem the code (app secret + verifier), learn who the user is, open OUR session. if (req.method === 'POST' && path === '/app/handshake/finish') { const { handshake, code } = await readJson(req); const h = handshakes.get(handshake); handshakes.delete(handshake); if (!h || Date.now() - h.at > HANDSHAKE_TTL_MS || typeof code !== 'string') return send(400, { message: 'The sign-in took too long. Reopen the app.' }); const r = await gateway('/api/apps/oauth/token', { method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ grant_type: 'authorization_code', code, code_verifier: h.verifier }) }); if (!r.ok) { const e = await r.json().catch(() => ({})); console.error(`[app] the platform refused the code: ${r.status} ${e.error ?? ''}`); return send(401, { message: e.error === 'invalid_client' ? 'The app secret on the app server is wrong or was rotated.' : 'The platform did not accept the sign-in code.' }); } const { access_token: token } = await r.json(); const user = await introspect(token); if (!user) return send(401, { message: 'The platform did not confirm the sign-in.' }); const session = b64url(randomBytes(32)); sessions.set(session, { token }); return send(200, { session, user }); } // Every request of the app: the platform decides whether the user is still signed in (you may cache this ≤ 30 s). if (req.method === 'GET' && path === '/app/me') { const s = sessions.get(handleOf(req)); const user = s ? await introspect(s.token) : null; if (!user) { sessions.delete(handleOf(req)); return send(401, { message: 'Not signed in.' }); } return send(200, { user }); } if (req.method === 'POST' && path === '/app/signout') { sessions.delete(handleOf(req)); return send(200, {}); } return send(404, { message: 'Not found.' }); } catch (e) { console.error(`[app] ${req.method} ${path} failed: ${e.message}`); // never log codes, tokens or the secret return send(502, { message: 'The platform could not be reached from the app server.' }); } }); server.listen(Number(env.PORT ?? 8787), env.HOST ?? '127.0.0.1', () => { const a = server.address(); console.log(`reference app listening on http://${a.address}:${a.port}`); });