From 67c1a33e479701b3c1c127d87d3891ddfd9275d5 Mon Sep 17 00:00:00 2001 From: paula-alves Date: Sun, 8 Nov 2026 12:08:57 +0000 Subject: [PATCH] fix(shop,invoicing): wrap Stripe/InvoiceXpress fetch failures instead of leaking a bare TypeError (BIT-31961) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The error hub fingerprints a bare \"TypeError: fetch failed\" with no frame (native undici errors don't point into our code) by component and message shape alone — every unwrapped fetch call site in the same component collapses into one indistinguishable ERRSIG. Fixing the desktop download route (PR #133) didn't stop this ticket from reopening, because shop/stripe.ts's createCheckout()/call() (Stripe Checkout + Connect) and invoicing/invoicexpress.ts's call() also threw the native fetch error straight through to callers/routes with no wrapping, unlike every other network client in apps/api (zerozero, Nextcloud, VIES, calendar ICS). Wraps both call sites in try/catch and rethrows a StripeError/ InvoicingError (status 0, descriptive message) on network failure — same pattern Nextcloud's CloudClient and calendar's download() already use. Gives future occurrences their own frame and fingerprint instead of colliding into this one. Paperclip-Agent: José Alves (urlKey jos-alves; id 11179220-3cec-4f0f-880d-2771ff64fce8) Paperclip-Issue: BIT-31961 Paperclip-Run: 36170d99-50b2-4583-ae8e-ce8cfc898189 --- apps/api/src/invoicing/invoicexpress.ts | 16 +++++++++++----- apps/api/src/shop/stripe.ts | 13 +++++++++++-- apps/api/test/invoicing.test.ts | 11 +++++++++++ apps/api/test/shop.test.ts | 11 ++++++++++- 4 files changed, 43 insertions(+), 8 deletions(-) diff --git a/apps/api/src/invoicing/invoicexpress.ts b/apps/api/src/invoicing/invoicexpress.ts index f694f62..ed8ea8b 100644 --- a/apps/api/src/invoicing/invoicexpress.ts +++ b/apps/api/src/invoicing/invoicexpress.ts @@ -70,11 +70,17 @@ export class InvoiceXpress { ) {} private async call(method: "GET" | "POST" | "PUT", path: string, body?: unknown): Promise { - const res = await this.fetchImpl(`${this.base}${path}${path.includes("?") ? "&" : "?"}api_key=${encodeURIComponent(this.apiKey)}`, { - method, - headers: { accept: "application/json", ...(body !== undefined && { "content-type": "application/json" }) }, - ...(body !== undefined && { body: JSON.stringify(body) }), - }); + let res: Response; + try { + res = await this.fetchImpl(`${this.base}${path}${path.includes("?") ? "&" : "?"}api_key=${encodeURIComponent(this.apiKey)}`, { + method, + headers: { accept: "application/json", ...(body !== undefined && { "content-type": "application/json" }) }, + ...(body !== undefined && { body: JSON.stringify(body) }), + }); + } catch (err) { + // A network-level failure (DNS, connection) has no Response: reported as an InvoicingError of its own, not a bare, unlocatable fetch error. + throw new InvoicingError(`invoicexpress: ${err instanceof Error ? err.message : "fetch failed"}`, 0); + } const text = await res.text(); if (!res.ok) { let message = `invoicexpress ${res.status}`; diff --git a/apps/api/src/shop/stripe.ts b/apps/api/src/shop/stripe.ts index c276779..aa3f77e 100644 --- a/apps/api/src/shop/stripe.ts +++ b/apps/api/src/shop/stripe.ts @@ -28,6 +28,15 @@ export class StripeError extends Error { } } +/** A network-level failure (DNS, connection) has no `Response` and no HTTP status: reported as a StripeError of its own, not a bare, unlocatable fetch error. */ +async function fetchOrThrow(fetchImpl: typeof fetch, url: string, init: RequestInit): Promise { + try { + return await fetchImpl(url, init); + } catch (err) { + throw new StripeError(`stripe: ${err instanceof Error ? err.message : "fetch failed"}`, 0); + } +} + /** Flattens nested params the way Stripe's form API expects (`line_items[0][price_data][currency]`). */ export function formEncode(params: Record, prefix = ""): string[] { const out: string[] = []; @@ -56,7 +65,7 @@ export async function createCheckout(secretKey: string, req: CheckoutRequest, fe payment_intent_data: { metadata: req.metadata }, line_items: req.lines.map((l) => ({ quantity: l.quantity, price_data: { currency: req.currency.toLowerCase(), unit_amount: l.unitCents, product_data: { name: l.name } } })), }).join("&"); - const res = await fetchImpl(`${base}/v1/checkout/sessions`, { + const res = await fetchOrThrow(fetchImpl, `${base}/v1/checkout/sessions`, { method: "POST", headers: { authorization: `Bearer ${secretKey}`, "content-type": "application/x-www-form-urlencoded", "idempotency-key": `checkout-${req.reference}` }, body, @@ -91,7 +100,7 @@ export function signWebhook(rawBody: string, secret: string, t = Math.floor(Date // ---- Connect (payouts to photographers and affiliates) ------------------------------------------------ async function call(secretKey: string, method: "GET" | "POST", path: string, params: Record | null, opts: { fetchImpl?: typeof fetch | undefined; base?: string | undefined; idempotencyKey?: string }): Promise { - const res = await (opts.fetchImpl ?? fetch)(`${opts.base ?? "https://api.stripe.com"}${path}`, { + const res = await fetchOrThrow(opts.fetchImpl ?? fetch, `${opts.base ?? "https://api.stripe.com"}${path}`, { method, headers: { authorization: `Bearer ${secretKey}`, diff --git a/apps/api/test/invoicing.test.ts b/apps/api/test/invoicing.test.ts index a35a1e4..345439f 100644 --- a/apps/api/test/invoicing.test.ts +++ b/apps/api/test/invoicing.test.ts @@ -1,5 +1,6 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest"; import { SecretBox } from "../src/delivery/secrets.js"; +import { InvoiceXpress, InvoicingError } from "../src/invoicing/invoicexpress.js"; import { InvoicingService } from "../src/invoicing/service.js"; import { Notifications } from "../src/notifications/service.js"; import { MemoryBroadcaster } from "../src/realtime.js"; @@ -8,6 +9,16 @@ import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } fro const KEY = Buffer.alloc(32, 9).toString("base64"); const quiet = { info: () => {}, warn: () => {} }; +describe("InvoiceXpress client", () => { + it("wraps a network-level failure into an InvoicingError instead of a bare, unlocatable fetch error (BIT-31961)", async () => { + const rejecting: typeof fetch = async () => { + throw new TypeError("fetch failed"); + }; + const client = new InvoiceXpress("bitreport", "ix-secret", rejecting); + await expect(client.check()).rejects.toThrow(InvoicingError); + }); +}); + describe("invoicing (InvoiceXpress)", () => { let ctx: TestContext; const calls: { method: string; url: string; body: unknown }[] = []; diff --git a/apps/api/test/shop.test.ts b/apps/api/test/shop.test.ts index 9a8e849..c4dbee6 100644 --- a/apps/api/test/shop.test.ts +++ b/apps/api/test/shop.test.ts @@ -12,7 +12,7 @@ import { Notifications } from "../src/notifications/service.js"; import { PressService } from "../src/shop/press.js"; import { EarningsService } from "../src/shop/earnings.js"; import { ShopService } from "../src/shop/service.js"; -import { formEncode, signWebhook, verifyWebhook } from "../src/shop/stripe.js"; +import { createCheckout, formEncode, signWebhook, StripeError, verifyWebhook } from "../src/shop/stripe.js"; import { LocalStorage, UrlSigner } from "../src/storage/storage.js"; import { bearer, createTestApp, login, resetDb, seedUser, type TestContext } from "./helpers.js"; @@ -43,6 +43,15 @@ describe("pricing", () => { expect(verifyWebhook(Buffer.from(body), signWebhook(body, WHSEC, Math.floor(Date.now() / 1000) - 3600), WHSEC)).toBe(false); expect(formEncode({ a: { b: [{ c: 1 }] } })).toEqual(["a%5Bb%5D%5B0%5D%5Bc%5D=1"]); }); + + it("wraps a network-level Stripe failure into a StripeError instead of a bare, unlocatable fetch error (BIT-31961)", async () => { + const rejecting: typeof fetch = async () => { + throw new TypeError("fetch failed"); + }; + await expect( + createCheckout("sk_test", { reference: "o1", metadata: {}, currency: "eur", lines: [{ name: "x", unitCents: 100, quantity: 1 }], successUrl: "https://x/ok", cancelUrl: "https://x/cancel" }, rejecting), + ).rejects.toThrow(StripeError); + }); }); describe("shop", () => { -- 2.47.3