Initial import of zappier-customer-service from zapier monorepo
This commit is contained in:
commit
420a414381
9 changed files with 453 additions and 0 deletions
25
src/names.js
Normal file
25
src/names.js
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
/** Join ledger ids to zappier-edge customer display names. */
|
||||
export async function withCustomerName(st, idOrName, edge, key) {
|
||||
const out = { ...(st || {}) };
|
||||
if (out.name && out.customerId) return out;
|
||||
try {
|
||||
const r = await fetch(`${edge.replace(/\/$/, '')}/admin/api/customers`, {
|
||||
headers: { 'x-admin-key': key },
|
||||
});
|
||||
const { customers } = await r.json();
|
||||
const want = String(idOrName || out.customerId || '').toLowerCase();
|
||||
const c = (customers || []).find(
|
||||
(x) =>
|
||||
x.id === idOrName ||
|
||||
x.id === out.customerId ||
|
||||
String(x.name || '').toLowerCase() === want,
|
||||
);
|
||||
if (c) {
|
||||
out.name = c.name;
|
||||
out.customerId = c.id;
|
||||
}
|
||||
} catch {
|
||||
/* edge optional */
|
||||
}
|
||||
return out;
|
||||
}
|
||||
44
src/nats-billing.js
Normal file
44
src/nats-billing.js
Normal 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;
|
||||
}
|
||||
}
|
||||
93
src/server.js
Normal file
93
src/server.js
Normal file
|
|
@ -0,0 +1,93 @@
|
|||
#!/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';
|
||||
import { withCustomerName } from './names.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')) {
|
||||
if (process.env.STAFF_AUTH === '1') {
|
||||
const login = (process.env.STAFF_SESSION_URL || 'http://127.0.0.1:3027').replace(/\/$/, '');
|
||||
const chk = await fetch(`${login}/check`, { headers: { cookie: req.headers.cookie || '' } }).catch(() => null);
|
||||
if (!chk || !chk.ok) {
|
||||
const next = `http://${req.headers.host || '127.0.0.1'}/`;
|
||||
res.writeHead(302, { location: `${login}/login?next=${encodeURIComponent(next)}` });
|
||||
res.end();
|
||||
return;
|
||||
}
|
||||
}
|
||||
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 id = decodeURIComponent(review[1]);
|
||||
const out = await statement(id);
|
||||
out.body = await withCustomerName(out.body, id, EDGE, KEY);
|
||||
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`);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue