Initial import of zappier-customer-service from zapier monorepo

This commit is contained in:
George Lambert 2026-09-11 18:03:00 -04:00
commit 8d19233fae
8 changed files with 415 additions and 0 deletions

44
src/nats-billing.js Normal file
View file

@ -0,0 +1,44 @@
export const SUBJECTS = {
STATEMENT_GET: 'verae.billing.statement.get',
BALANCE_ADJUST: 'verae.billing.balance.adjust',
AUTHZ_CHECK: 'verae.access.authz.check',
};
const PLANE = 'staff';
async function authz(subject, payload) {
const http = process.env.AUTHZ_URL;
if (!http && !process.env.NATS_URL) return { allow: true, subject };
if (http) {
const r = await fetch(`${http.replace(/\/$/, '')}/check`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify({ plane: PLANE, subject, kind: payload?.kind, payload, principal: payload?.agent }),
});
return r.json();
}
return { allow: true, subject };
}
export async function billingRequest(subject, payload) {
const decision = await authz(subject, payload);
if (decision && decision.allow === false) {
const err = new Error(decision.reason || 'denied');
err.status = 403;
err.decision = decision;
throw err;
}
const url = process.env.NATS_URL;
if (!url) return null;
try {
const { connect, StringCodec } = await import('nats');
const nc = await connect({ servers: url.split(','), name: 'zappier-customer-service' });
const sc = StringCodec();
const m = await nc.request(subject, sc.encode(JSON.stringify({ ...payload, plane: PLANE })), { timeout: 2000 });
const out = JSON.parse(sc.decode(m.data) || '{}');
await nc.close();
return out;
} catch (err) {
if (err.status === 403) throw err;
return null;
}
}

80
src/server.js Normal file
View file

@ -0,0 +1,80 @@
#!/usr/bin/env node
/**
* CS HTTP front door. Internally prefers NATS account-balance, then HTTP.
*/
import fs from 'node:fs';
import http from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { SUBJECTS, billingRequest } from './nats-billing.js';
const PUBLIC = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'public');
const PORT = Number(process.env.PORT || 3011);
const BOOKS = (process.env.ACCOUNT_BALANCE_URL || 'http://127.0.0.1:3010').replace(/\/$/, '');
const EDGE = (process.env.ZAPPIER_ADMIN_URL || 'http://127.0.0.1:3000').replace(/\/$/, '');
const KEY = process.env.ZAPPIER_ADMIN_KEY || 'admin-dev-key';
async function statement(customerId) {
const nats = await billingRequest(SUBJECTS.STATEMENT_GET, { customerId });
if (nats) return { status: 200, body: { ...nats, source: 'nats' } };
const r = await fetch(`${BOOKS}/statement/${customerId}`);
if (r.ok) return { status: r.status, body: { ...(await r.json()), source: 'account-balance' } };
const e = await fetch(`${EDGE}/admin/api/statement/${customerId}`, { headers: { 'x-admin-key': KEY } });
return { status: e.status, body: { ...(await e.json().catch(() => ({}))), source: 'edge' } };
}
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 === '/' || url.pathname === '/index.html')) {
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8' });
res.end(fs.readFileSync(path.join(PUBLIC, 'index.html')));
return;
}
if (req.method === 'GET' && url.pathname === '/health') {
return json(200, { ok: true, role: 'zappier-customer-service', nats: Boolean(process.env.NATS_URL) });
}
const review = url.pathname.match(/^\/review\/([^/]+)$/);
if (req.method === 'GET' && review) {
const out = await statement(review[1]);
return json(out.status, out.body);
}
if (req.method === 'POST' && url.pathname === '/credits') {
const chunks = [];
for await (const c of req) chunks.push(c);
const payload = JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}');
const nats = await billingRequest(SUBJECTS.BALANCE_ADJUST, { ...payload, kind: 'credit' });
if (nats) return json(200, { ...nats, source: 'nats' });
const r = await fetch(`${BOOKS}/adjust`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
body: JSON.stringify(payload),
});
const body = await r.json().catch(() => ({}));
await fetch(`${EDGE}/admin/api/credits`, {
method: 'POST',
headers: { 'content-type': 'application/json', 'x-admin-key': KEY },
body: JSON.stringify(payload),
}).catch(() => {});
return json(r.status, body);
}
if (req.method === 'GET' && url.pathname === '/credits') {
const id = url.searchParams.get('customerId');
if (!id) return json(400, { error: 'customerId required' });
const out = await statement(id);
return json(out.status, { credits: out.body.credits || [] });
}
json(404, { error: 'not found' });
} catch (err) {
json(err.status === 403 ? 403 : 502, { error: err.message, ...(err.decision || {}) });
}
});
server.listen(PORT, '0.0.0.0', () => {
process.stdout.write(`zappier-customer-service http://0.0.0.0:${PORT}/\n`);
});