verae-access-leaf/src/server.js

98 lines
3.4 KiB
JavaScript

#!/usr/bin/env node
/**
* Server-to-server / NATS leaf-node ingress.
* Remote servers publish verae.access.leaf.in; this process authz-checks
* then forwards only allowed internal subjects (archive + jobs, never billing).
*/
import http from 'node:http';
import { leafAllowed } from './allow.js';
const PORT = Number(process.env.PORT || 3023);
const AUTHZ = (process.env.AUTHZ_URL || 'http://127.0.0.1:3020').replace(/\/$/, '');
const TOKEN = process.env.LEAF_TOKEN || 'leaf-dev-token';
const PLANE = 'leaf';
const IN = 'verae.access.leaf.in';
async function check(subject, principal) {
const r = await fetch(`${AUTHZ}/check`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ plane: PLANE, subject, principal }),
});
return r.json();
}
function authorizedToken(got) {
return got && got === TOKEN;
}
async function forward(body) {
if (!authorizedToken(body.token)) {
return { status: 401, body: { allow: false, reason: 'bad leaf token' } };
}
const target = body.target || body.subject;
if (!leafAllowed(target)) {
return { status: 403, body: { allow: false, reason: `leaf policy denies ${target}` } };
}
const gate = await check(target, body.principal || 'leaf');
if (!gate.allow) return { status: 403, body: gate };
const url = process.env.NATS_URL;
if (url) {
const { connect, StringCodec } = await import('nats');
const nc = await connect({ servers: url.split(','), name: 'verae-access-leaf' });
const sc = StringCodec();
nc.publish(gate.subject, sc.encode(JSON.stringify({ ...(body.payload || {}), plane: PLANE })));
await nc.flush();
await nc.close();
}
return { status: 200, body: { forwarded: gate.subject, plane: PLANE, nats: Boolean(url) } };
}
async function startNats() {
const url = process.env.NATS_URL;
if (!url) return;
const { connect, StringCodec } = await import('nats');
const nc = await connect({ servers: url.split(','), name: 'verae-access-leaf' });
const sc = StringCodec();
(async () => {
for await (const m of nc.subscribe(IN, { queue: 'access-leaf' })) {
let payload = {};
try {
payload = JSON.parse(sc.decode(m.data) || '{}');
} catch {
payload = {};
}
const out = await forward(payload);
if (m.reply) m.respond(sc.encode(JSON.stringify(out.body)));
}
})();
process.stdout.write(`access-leaf nats ${IN}\n`);
}
const server = http.createServer(async (req, res) => {
const url = new URL(req.url || '/', `http://127.0.0.1:${PORT}`);
const json = (code, obj) => {
res.writeHead(code, { 'content-type': 'application/json' });
res.end(JSON.stringify(obj));
};
try {
if (req.method === 'GET' && url.pathname === '/health') {
return json(200, { ok: true, role: 'verae-access-leaf', plane: PLANE, ingress: IN });
}
if (req.method === 'POST' && url.pathname === '/forward') {
const chunks = [];
for await (const c of req) chunks.push(c);
const body = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
const out = await forward(body);
return json(out.status, out.body);
}
json(404, { error: 'not found' });
} catch (err) {
json(502, { error: err.message });
}
});
server.listen(PORT, '0.0.0.0', () => {
process.stdout.write(`verae-access-leaf http://0.0.0.0:${PORT}/ plane=${PLANE}\n`);
});
startNats().catch((err) => process.stderr.write(`nats optional: ${err.message}\n`));