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; }