File size: 5,396 Bytes
5bd4e3a 409aa8e 5bd4e3a 1444c0a 5bd4e3a 1444c0a 5bd4e3a 1444c0a 9213d5f 5bd4e3a 1444c0a 5bd4e3a 1444c0a 5bd4e3a 1444c0a 5bd4e3a 1444c0a 5bd4e3a 1444c0a 5bd4e3a 1444c0a 9213d5f 5bd4e3a 1444c0a 5bd4e3a 1444c0a 5bd4e3a 1444c0a 5bd4e3a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | import express from "express";
import { fileURLToPath } from "node:url";
import path from "node:path";
import type Stripe from "stripe";
import type { Config } from "./config.js";
import { Ledger, LedgerError } from "./ledger.js";
import { parseInvoiceQr, payInvoice, InvoiceSchema } from "./routing.js";
import { createFundingCheckout, createFundingPaymentIntent, handleWebhook } from "./stripe.js";
import { Runtime } from "./runtime.js";
import { AdminAuth, adminRouter } from "./admin.js";
import { DeviceError, addDevice } from "./devices.js";
const publicDir = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "public");
export interface AppOptions { runtime?: Runtime; adminPasscode?: string }
export function buildApp(cfg: Config, ledger: Ledger | null, stripe: Stripe | null, opts: AppOptions = {}): express.Application {
const rt = opts.runtime ?? new Runtime(cfg, { stripe, ...(ledger ? { ledger } : {}) });
const L = rt.ledger;
const auth = new AdminAuth(opts.adminPasscode);
const app = express();
app.set("trust proxy", true);
app.disable("x-powered-by");
const notConfigured = (res: express.Response) => res.status(503).json({ error: "Stripe not configured" });
const userId = cfg.WALLET_USER_ID; // single-user now; replace with auth-derived id for multi-user
app.use((_req, res, next) => {
res.setHeader("X-Content-Type-Options", "nosniff");
res.setHeader("Referrer-Policy", "same-origin");
next();
});
app.post("/webhooks/stripe", express.raw({ type: "application/json" }), async (req, res) => {
const s = rt.stripe; const secret = rt.webhookSecret;
if (!s || !secret) return notConfigured(res);
try { const ev = await handleWebhook(s, L, req.body, req.header("stripe-signature"), secret); res.json({ received: true, type: ev.type }); }
catch (e) { res.status(400).json({ error: rt.redact((e as Error).message) }); }
});
app.use(express.json({ limit: "32kb" }));
app.use(express.static(publicDir, { index: "index.html", extensions: ["html"] }));
app.get("/favicon.ico", (_req, res) => res.redirect(301, "/favicon.svg"));
app.get("/healthz", (_req, res) => res.json({ ok: true, mode: "test", stripe: Boolean(rt.stripe && rt.webhookSecret), store: rt.storeMode, admin: auth.configured }));
app.use("/api/admin", adminRouter(rt, auth));
// --- devices / phones (sign-in required: they hold phone numbers) ---
app.get("/api/devices", auth.require, async (_req, res, next) => { try { res.json(await rt.devices.list(userId)); } catch (e) { next(e); } });
app.post("/api/devices", auth.require, async (req, res, next) => { try { res.status(201).json(await addDevice(rt.devices, userId, req.body)); } catch (e) { next(e); } });
app.delete("/api/devices/:id", auth.require, async (req, res, next) => {
try { const ok = await rt.devices.remove(userId, req.params.id); res.status(ok ? 200 : 404).json(ok ? { ok: true } : { error: "device not found" }); } catch (e) { next(e); }
});
// --- wallet ---
app.get("/wallet/balance", async (req, res, next) => {
try { const currency = String(req.query.currency ?? "usd"); res.json({ currency, balance: await L.walletBalance(userId, currency) }); } catch (e) { next(e); }
});
app.get("/wallet/transactions", async (_req, res, next) => { try { res.json(await L.list(userId)); } catch (e) { next(e); } });
app.post("/wallet/test-credit", auth.require, async (req, res, next) => {
try { const amount = Math.round(Number(req.body?.amount)); const tx = await L.recordTestCredit(userId, amount); res.json({ transaction: tx, balance: await L.walletBalance(userId) }); } catch (e) { next(e); }
});
app.post("/funding/checkout", async (req, res, next) => {
const st = rt.stripe; if (!st) return notConfigured(res);
try {
const urls = rt.checkoutUrls(Runtime.origin(req));
const s = await createFundingCheckout(st, userId, Number(req.body.amount), String(req.body.currency ?? "usd"), urls.success, urls.cancel);
res.json({ id: s.id, url: s.url });
} catch (e) { next(e); }
});
app.post("/funding/payment-intent", async (req, res, next) => {
const st = rt.stripe; if (!st) return notConfigured(res);
try { const pi = await createFundingPaymentIntent(st, userId, Number(req.body.amount), String(req.body.currency ?? "usd")); res.json({ id: pi.id, client_secret: pi.client_secret }); } catch (e) { next(e); }
});
app.post("/invoices/pay", async (req, res, next) => {
try {
const invoice = typeof req.body.qr === "string" ? parseInvoiceQr(req.body.qr) : InvoiceSchema.parse(req.body.invoice);
res.json(await payInvoice(L, userId, invoice));
} catch (e) { next(e); }
});
// Unknown API-ish paths get JSON; anything else gets the friendly 404 page.
app.use((req, res) => {
if (req.method === "GET" && !/^\/(api|wallet|funding|invoices|webhooks)\b/.test(req.path)) return void res.status(404).sendFile(path.join(publicDir, "404.html"));
res.status(404).json({ error: "not found" });
});
app.use((err: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
const status = err instanceof LedgerError || err instanceof DeviceError || err.name === "ZodError" ? 422 : (err as { type?: string }).type === "entity.parse.failed" ? 400 : 500;
res.status(status).json({ error: rt.redact(err.message) });
});
return app;
}
|