Stripe optional at startup
Browse filesFiles changed (4)
4 unmodified lines567891011121314151617181920212223242526272829304 unmodified linesimport { parseInvoiceQr, payInvoice, InvoiceSchema } from "./routing.js";import { createFundingCheckout, createFundingPaymentIntent, handleWebhook } from "./stripe.js";export function buildApp(cfg: Config, ledger: Ledger, stripe: Stripe) {const app = express();const userId = cfg.WALLET_USER_ID; // single-user now; replace with auth-derived id for multi-userapp.post("/webhooks/stripe", express.raw({ type: "application/json" }), async (req, res) => {try { const ev = await handleWebhook(stripe, ledger, req.body, req.header("stripe-signature"), cfg.STRIPE_WEBHOOK_SECRET); res.json({ received: true, type: ev.type }); }catch (e) { res.status(400).json({ error: (e as Error).message }); }});app.use(express.json({ limit: "32kb" }));app.get("/healthz", (_req, res) => res.json({ ok: true, mode: "test" }));app.get("/wallet/balance", async (req, res, next) => {try { const currency = String(req.query.currency ?? "usd"); res.json({ currency, balance: await ledger.walletBalance(userId, currency) }); } catch (e) { next(e); }});app.get("/wallet/transactions", async (_req, res, next) => { try { res.json(await ledger.list(userId)); } catch (e) { next(e); } });app.post("/funding/checkout", async (req, res, next) => {try { const s = await createFundingCheckout(stripe, userId, Number(req.body.amount), String(req.body.currency ?? "usd"), cfg.STRIPE_SUCCESS_URL, cfg.STRIPE_CANCEL_URL); res.json({ id: s.id, url: s.url }); } catch (e) { next(e); }});app.post("/funding/payment-intent", async (req, res, next) => {try { const pi = await createFundingPaymentIntent(stripe, 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 {4 unmodified lines567891011121314151617181920212223242526272829303132333435364 unmodified linesimport { parseInvoiceQr, payInvoice, InvoiceSchema } from "./routing.js";import { createFundingCheckout, createFundingPaymentIntent, handleWebhook } from "./stripe.js";export function buildApp(cfg: Config, ledger: Ledger, stripe: Stripe | null) {const app = express();const stripeReady = (needWebhook = false): Stripe | null =>stripe && (!needWebhook || cfg.STRIPE_WEBHOOK_SECRET) ? stripe : null;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-userapp.post("/webhooks/stripe", express.raw({ type: "application/json" }), async (req, res) => {const s = stripeReady(true); if (!s) return notConfigured(res);try { const ev = await handleWebhook(s, ledger, req.body, req.header("stripe-signature"), cfg.STRIPE_WEBHOOK_SECRET!); res.json({ received: true, type: ev.type }); }catch (e) { res.status(400).json({ error: (e as Error).message }); }});app.use(express.json({ limit: "32kb" }));app.get("/healthz", (_req, res) => res.json({ ok: true, mode: "test", stripe: Boolean(stripeReady(true)) }));app.get("/wallet/balance", async (req, res, next) => {try { const currency = String(req.query.currency ?? "usd"); res.json({ currency, balance: await ledger.walletBalance(userId, currency) }); } catch (e) { next(e); }});app.get("/wallet/transactions", async (_req, res, next) => { try { res.json(await ledger.list(userId)); } catch (e) { next(e); } });app.post("/funding/checkout", async (req, res, next) => {const st = stripeReady(); if (!st) return notConfigured(res);try { const s = await createFundingCheckout(st, userId, Number(req.body.amount), String(req.body.currency ?? "usd"), cfg.STRIPE_SUCCESS_URL, cfg.STRIPE_CANCEL_URL); res.json({ id: s.id, url: s.url }); } catch (e) { next(e); }});app.post("/funding/payment-intent", async (req, res, next) => {const st = stripeReady(); 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 {
2 unmodified lines3456789102 unmodified linesconst schema = z.object({PORT: z.coerce.number().default(7860),WALLET_USER_ID: z.string().min(1),STRIPE_SECRET_KEY: z.string().min(1),STRIPE_WEBHOOK_SECRET: z.string().min(1),STRIPE_SUCCESS_URL: z.string().url().default("http://localhost:7860/funding/success"),STRIPE_CANCEL_URL: z.string().url().default("http://localhost:7860/funding/cancel"),SUPABASE_URL: z.string().optional(),2 unmodified lines3456789102 unmodified linesconst schema = z.object({PORT: z.coerce.number().default(7860),WALLET_USER_ID: z.string().min(1),STRIPE_SECRET_KEY: z.string().min(1).optional(),STRIPE_WEBHOOK_SECRET: z.string().min(1).optional(),STRIPE_SUCCESS_URL: z.string().url().default("http://localhost:7860/funding/success"),STRIPE_CANCEL_URL: z.string().url().default("http://localhost:7860/funding/cancel"),SUPABASE_URL: z.string().optional(),
6 unmodified lines78910116 unmodified linesconst cfg = loadConfig(); // throws on sk_live_ / Apple Pay credsconst store = cfg.WALLET_STORE === "memory" ? new MemoryStore() : new SupabaseStore(cfg.SUPABASE_URL!, cfg.SUPABASE_SERVICE_ROLE_KEY!);const app = buildApp(cfg, new Ledger(store), makeStripe(cfg.STRIPE_SECRET_KEY));app.listen(cfg.PORT, "0.0.0.0", () => console.log(`wallet (TEST mode) listening on :${cfg.PORT}`));6 unmodified lines7891011126 unmodified linesconst cfg = loadConfig(); // throws on sk_live_ / Apple Pay credsconst store = cfg.WALLET_STORE === "memory" ? new MemoryStore() : new SupabaseStore(cfg.SUPABASE_URL!, cfg.SUPABASE_SERVICE_ROLE_KEY!);const app = buildApp(cfg, new Ledger(store), cfg.STRIPE_SECRET_KEY ? makeStripe(cfg.STRIPE_SECRET_KEY) : null);if (!cfg.STRIPE_SECRET_KEY || !cfg.STRIPE_WEBHOOK_SECRET) console.warn("Stripe not configured: funding/webhook routes return 503");app.listen(cfg.PORT, "0.0.0.0", () => console.log(`wallet (TEST mode) listening on :${cfg.PORT}`));
12345678910111213141516171819202122232425262728293031import { describe, it, expect } from "vitest";import type { AddressInfo } from "node:net";import { buildApp } from "../src/app.js";import { loadConfig } from "../src/config.js";import { Ledger } from "../src/ledger.js";import { MemoryStore } from "../src/memoryStore.js";
const base = { WALLET_STORE: "memory", WALLET_USER_ID: "u1" };
describe("startup without Stripe", () => { it("config loads without Stripe keys", () => expect(loadConfig(base).STRIPE_SECRET_KEY).toBeUndefined()); it("still refuses live key when set", () => expect(() => loadConfig({ ...base, STRIPE_SECRET_KEY: "sk_live_x" })).toThrow(/live/)); it("503s Stripe routes, ledger + invoice routes work", async () => { const ledger = new Ledger(new MemoryStore()); await ledger.recordFunding("u1", 1000, "usd", "pi_seed"); const srv = buildApp(loadConfig(base), ledger, null).listen(0); const url = `http://127.0.0.1:${(srv.address() as AddressInfo).port}`; try { const post = (p: string, b: unknown) => fetch(url + p, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(b) }); for (const p of ["/funding/checkout", "/funding/payment-intent", "/webhooks/stripe"]) { const r = await post(p, { amount: 500 }); expect(r.status).toBe(503); expect((await r.json()).error).toBe("Stripe not configured"); } expect((await (await fetch(url + "/healthz")).json())).toMatchObject({ ok: true, stripe: false }); const pay = await post("/invoices/pay", { invoice: { v: 1, invoice_id: "I1", merchant_id: "m", amount: 400, currency: "usd" } }); expect(pay.status).toBe(200); expect((await (await fetch(url + "/wallet/balance")).json()).balance).toBe(600); } finally { srv.close(); } });});services/wallet/src/app.ts+11-5
services/wallet/src/config.ts+2-2
services/wallet/src/index.ts+2-1
services/wallet/test/app.test.tsAdded+31