Initial import of verae-access-leaf from zapier monorepo

This commit is contained in:
George Lambert 2026-09-11 17:17:00 -04:00
commit c541fa0860
7 changed files with 271 additions and 0 deletions

9
NATS.md Normal file
View file

@ -0,0 +1,9 @@
# NATS — verae-access-leaf
| Direction | Address | Kind |
|-----------|---------|------|
| IN | `verae.access.leaf.in` | queue `access-leaf` `{ token, target, payload, principal }` |
| OUT | `verae.access.authz.check` | request-reply |
| OUT | allowed `target` only | pub after allow |
Do not export `verae.billing.*` to the leaf account.

13
README.md Normal file
View file

@ -0,0 +1,13 @@
# verae-access-leaf
**Server-to-server leaf node** access plane. Remote machines connect as NATS leaf nodes (or POST `/forward` with a leaf token). They never get the core billing subjects.
**Forgejo:** https://git.georgelambert.org/marchon/verae-access-leaf
```text
remote leaf → verae.access.leaf.in → authz.check → verae.archive.put | jobs.*
```
Denied: `verae.billing.balance.adjust`, `verae.billing.statement.get`. A compromised WORM/leaf cannot credit customers.
`LEAF_TOKEN` required. Port `:3023`. Do not publish NATS `4222` to the internet; leaf nodes use a private leafnode port / tunnel.

46
package-lock.json generated Normal file
View file

@ -0,0 +1,46 @@
{
"name": "verae-access-leaf",
"version": "0.1.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "verae-access-leaf",
"version": "0.1.0",
"dependencies": {
"nats": "^2.28.2"
}
},
"node_modules/nats": {
"version": "2.29.3",
"resolved": "https://registry.npmjs.org/nats/-/nats-2.29.3.tgz",
"integrity": "sha512-tOQCRCwC74DgBTk4pWZ9V45sk4d7peoE2njVprMRCBXrhJ5q5cYM7i6W+Uvw2qUrcfOSnuisrX7bEx3b3Wx4QA==",
"deprecated": "Package moved. Use @nats-io/transport-node from https://github.com/nats-io/nats.js",
"license": "Apache-2.0",
"dependencies": {
"nkeys.js": "1.1.0"
},
"engines": {
"node": ">= 14.0.0"
}
},
"node_modules/nkeys.js": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/nkeys.js/-/nkeys.js-1.1.0.tgz",
"integrity": "sha512-tB/a0shZL5UZWSwsoeyqfTszONTt4k2YS0tuQioMOD180+MbombYVgzDUYHlx+gejYK6rgf08n/2Df99WY0Sxg==",
"license": "Apache-2.0",
"dependencies": {
"tweetnacl": "1.0.3"
},
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/tweetnacl": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz",
"integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==",
"license": "Unlicense"
}
}
}

14
package.json Normal file
View file

@ -0,0 +1,14 @@
{
"name": "verae-access-leaf",
"version": "0.1.0",
"private": true,
"type": "module",
"description": "Server-to-server NATS leaf-node access plane",
"scripts": {
"start": "node src/server.js",
"test": "node --test test/*.test.js"
},
"dependencies": {
"nats": "^2.28.2"
}
}

28
src/allow.js Normal file
View file

@ -0,0 +1,28 @@
import fs from 'node:fs';
const FALLBACK = [
'verae.archive.put',
'verae.archive.query',
'verae.archive.reply.',
'verae.zapier.jobs.watch',
'verae.zapier.jobs.events',
'verae.zapier.webhooks.deliver',
];
export function leafAllowList() {
const p = process.env.NATS_POLICY_PATH;
if (p && fs.existsSync(p)) {
try {
return JSON.parse(fs.readFileSync(p, 'utf8')).leafAllow || FALLBACK;
} catch {
return FALLBACK;
}
}
return FALLBACK;
}
export function leafAllowed(subject) {
return leafAllowList().some((p) =>
p.endsWith('.') ? subject.startsWith(p) : subject === p || subject.startsWith(`${p}.`),
);
}

98
src/server.js Normal file
View file

@ -0,0 +1,98 @@
#!/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`));

63
test/health.test.js Normal file
View file

@ -0,0 +1,63 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const authzRoot = path.join(root, '..', 'verae-access-authz');
test('leaf forwards archive.put and refuses billing adjust', async () => {
const authzPort = 18026;
const leafPort = 18027;
const authz = spawn(process.execPath, ['src/server.js'], {
cwd: authzRoot,
env: { ...process.env, PORT: String(authzPort) },
stdio: ['ignore', 'pipe', 'pipe'],
});
const leaf = spawn(process.execPath, ['src/server.js'], {
cwd: root,
env: {
...process.env,
PORT: String(leafPort),
AUTHZ_URL: `http://127.0.0.1:${authzPort}`,
LEAF_TOKEN: 'leaf-dev-token',
},
stdio: ['ignore', 'pipe', 'pipe'],
});
await new Promise((r) => setTimeout(r, 500));
try {
const h = await (await fetch(`http://127.0.0.1:${leafPort}/health`)).json();
assert.equal(h.plane, 'leaf');
const ok = await fetch(`http://127.0.0.1:${leafPort}/forward`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
token: 'leaf-dev-token',
target: 'verae.archive.put',
principal: 'ns2',
payload: { sha256: 'abc' },
}),
});
assert.equal(ok.status, 200);
const no = await fetch(`http://127.0.0.1:${leafPort}/forward`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({
token: 'leaf-dev-token',
target: 'verae.billing.balance.adjust',
payload: { customerId: 'c1', cents: 9999 },
}),
});
assert.equal(no.status, 403);
const bad = await fetch(`http://127.0.0.1:${leafPort}/forward`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ token: 'wrong', target: 'verae.archive.put' }),
});
assert.equal(bad.status, 401);
} finally {
leaf.kill('SIGTERM');
authz.kill('SIGTERM');
}
});