diff --git a/README.md b/README.md index cfbae45..d1ed155 100644 --- a/README.md +++ b/README.md @@ -193,6 +193,14 @@ chargebee listen --forward-to http://localhost:3000/webhooks --json Press `Ctrl+C` to stop listening. +To send a past event (for example, one your handler failed on) to your local handler again: + +```bash +chargebee event replay event-id --forward-to http://localhost:3000/webhooks +``` + +Replay works on test sites only and sends only to this machine (`localhost`, `127.0.0.1`, `::1`). It sends the event as `chargebee event retrieve` returns it now, so fields such as `webhook_status` show its current state. To deliver an event to a deployed endpoint, use **Resend** on the event page in Chargebee. + ## Use with AI Agents Install Chargebee skills for your coding agent: diff --git a/src/commands/event-replay.ts b/src/commands/event-replay.ts new file mode 100644 index 0000000..71945d8 --- /dev/null +++ b/src/commands/event-replay.ts @@ -0,0 +1,118 @@ +import type { Command } from "commander"; + +import { getClient, isLiveSite, resolveAuth } from "../lib/api/sdk.js"; +import { handleSdkError } from "../lib/api/print.js"; +import { assertResourceId } from "../lib/api/generated-command.js"; +import { EXIT_CODES } from "../lib/exit-codes.js"; +import { diagnostic, exitCommand, humanLog, jsonResult } from "../lib/output.js"; +import { recordTelemetryError } from "../lib/telemetry/error.js"; +import * as display from "../lib/tunnel/display.js"; +import { + checkLoopbackResolution, + describeHandlerStatus, + ReplayErrorCode, + resolveReplayTarget, + sendReplay, + type ReplayResponse, +} from "../lib/tunnel/replay.js"; + +const EXAMPLES = [ + "", + "\u001b[1mEXAMPLES\u001b[0m", + " chargebee event replay ev_16BHbhF4s42tO2lK --forward-to http://localhost:3000/webhooks", + " chargebee event replay ev_16BHbhF4s42tO2lK -f 3000 --json", + "", + "\u001b[1mNOTES\u001b[0m", + " Available on test sites only. Sends only to this machine (localhost, 127.0.0.1, ::1);", + " to deliver to a deployed endpoint, use Resend on the event page.", + " The body is the event as `chargebee event retrieve` returns it now, so fields such as", + " webhook_status reflect its current state rather than the original delivery.", + "", +].join("\n"); + +/** + * `chargebee event replay --forward-to `. + * + * `event` is a generated command group, so this built-in subcommand is attached + * to it after the generated commands are registered (generated files are never + * edited by hand). + */ +export function registerEventReplayCommand(program: Command): void { + // The generated `event` group always exists; codegen drift is checked in CI. + const eventGroup = program.commands.find((cmd) => cmd.name() === "event")!; + + eventGroup + .command("replay") + .argument("", "Unique identifier of the event to replay.") + .description("Send a past event to a local webhook handler (test sites only)") + .requiredOption( + "-f, --forward-to ", + "Local endpoint to send the event to (localhost, 127.0.0.1 or ::1)", + ) + .addHelpText("after", EXAMPLES) + .action(async (eventId: string, opts: { forwardTo: string }, command: Command) => { + assertResourceId(eventId, command); + + const target = resolveReplayTarget(opts.forwardTo); + if ("error" in target) { + recordTelemetryError(target.code); + diagnostic(target.error); + exitCommand(EXIT_CODES.ERROR, target.code); + } + const url = target.url; + const resolutionError = await checkLoopbackResolution(url); + if (resolutionError) { + recordTelemetryError(ReplayErrorCode.TARGET_REFUSED); + diagnostic(resolutionError); + exitCommand(EXIT_CODES.ERROR, ReplayErrorCode.TARGET_REFUSED); + } + + let site: string; + let apiKey: string; + try { + ({ site, apiKey } = await resolveAuth()); + } catch (err) { + handleSdkError(err); + } + if (isLiveSite(site, apiKey)) { + recordTelemetryError(ReplayErrorCode.LIVE_SITE_REFUSED); + diagnostic( + `Refusing to replay on live site "${site}".\n\n` + + ` Event replay is only available on test sites (name ending in "-test", or a test_ API key).`, + ); + exitCommand(EXIT_CODES.ERROR, ReplayErrorCode.LIVE_SITE_REFUSED); + } + + let event: Record; + try { + const client = await getClient(); + ({ event } = await (client as any).event.retrieve(eventId)); + } catch (err) { + handleSdkError(err); + } + + const eventType = typeof event.event_type === "string" ? event.event_type : ""; + const label = display.sanitizeEventType(eventType) || "unknown type"; + const details = { event_id: eventId, event_type: eventType, url }; + humanLog(`Replaying ${eventId} (${label}) to ${url}`); + + let response: ReplayResponse; + try { + response = await sendReplay(url, event); + } catch (err) { + recordTelemetryError(ReplayErrorCode.UNREACHABLE); + diagnostic((err as Error).message); + exitCommand(EXIT_CODES.NETWORK, ReplayErrorCode.UNREACHABLE, details); + } + + const { status, durationMs, location } = response; + const ok = status >= 200 && status < 300; + humanLog(`${eventId} ${label} → ${status} (${durationMs} ms)${ok ? "" : " (non-2xx)"}`); + if (!ok) { + recordTelemetryError(ReplayErrorCode.HANDLER_ERROR); + diagnostic(describeHandlerStatus(url, status, location)); + exitCommand(EXIT_CODES.ERROR, ReplayErrorCode.HANDLER_ERROR, { ...details, status, duration_ms: durationMs }); + } + jsonResult({ ...details, status, duration_ms: durationMs }); + }); +} diff --git a/src/lib/output.ts b/src/lib/output.ts index a387563..75a7560 100644 --- a/src/lib/output.ts +++ b/src/lib/output.ts @@ -79,8 +79,8 @@ export function finishOutput(exitCode = 0, code = "command_failed", details?: un } /** Preserve existing exit codes while flushing the structured outcome first. */ -export function exitCommand(code: number, errorCode?: string): never { - finishOutput(code, errorCode); +export function exitCommand(code: number, errorCode?: string, details?: unknown): never { + finishOutput(code, errorCode, details); // Let the entry point return normally so Node can flush piped JSON in full. if (isJsonMode()) throw new OutputExit(code); process.exit(code); diff --git a/src/lib/skills/content/references/commands.md b/src/lib/skills/content/references/commands.md index 79e61cf..803f73c 100644 --- a/src/lib/skills/content/references/commands.md +++ b/src/lib/skills/content/references/commands.md @@ -262,6 +262,7 @@ chargebee auth status |---|---| | `chargebee docs [resource] [operation]` | Browse API documentation. | | `chargebee listen --forward-to ` | Forward test-site webhooks to a local URL. The URL is required. | +| `chargebee event replay --forward-to ` | Send a past test-site event to a local handler (loopback URLs only). `--json` prints `event_id`, `event_type`, `url`, `status`, `duration_ms`. | | `chargebee resources` | List callable API resources. | | `chargebee skills add\|list\|update\|remove` | Manage installed agent skills. | | `chargebee alias set\|remove\|show` | Manage the shell alias. | diff --git a/src/lib/skills/content/references/workflows.md b/src/lib/skills/content/references/workflows.md index 0a5e8e7..9ec40db 100644 --- a/src/lib/skills/content/references/workflows.md +++ b/src/lib/skills/content/references/workflows.md @@ -201,6 +201,15 @@ chargebee listen \ There is no event-type filter; events for the site are forwarded to the configured URL. +Replay a past event to the local handler, for example after fixing a handler that failed on it: + +```bash +chargebee event list -d 'webhook_status[is]=failed' -d limit=5 +chargebee event replay --forward-to localhost:3000/webhook +``` + +`event replay` is available only for test sites and sends only to `localhost`, `127.0.0.1` or `::1`; there is no override. It exits non-zero when the handler returns a non-2xx status (exit 1) or can't be reached (exit 7). The body is the event's current state, not the exact original delivery. To deliver to a deployed endpoint, the user must use Resend on the event page. + ## 9. AI Agent Setup Install the Chargebee skill: @@ -244,4 +253,5 @@ If a project skill path resolves to a global installation, it is global only: pr | Unknown command/resource | Run `chargebee resources` or `chargebee --help`. | | Code sample unavailable | Use `chargebee docs ` for the API reference and construct the request from the documented parameters. | | Webhook listen blocked | Use a test site. | +| Event replay target refused | Replay only sends to this machine; use a `localhost` URL, or ask the user to use Resend on the event page. | | CLI bug or rough edge | Run `chargebee feedback "what happened"`. | diff --git a/src/lib/test-support/_helpers.ts b/src/lib/test-support/_helpers.ts index 087c0d3..5d2c4d9 100644 --- a/src/lib/test-support/_helpers.ts +++ b/src/lib/test-support/_helpers.ts @@ -82,6 +82,31 @@ export function installFakeClient(opts: FakeClientOptions): void { item: { list: async () => sdkResult({ list: [{ item: { id: `item_${site}` } }] }), }, + event: { + retrieve: async (id: string) => { + if (id === "ev_missing") { + throw { + message: `Sorry, we couldn't find that resource`, + type: "invalid_request", + api_error_code: "resource_not_found", + http_status_code: 404, + headers: { "content-type": "application/json" }, + }; + } + return sdkResult({ + event: { + id, + occurred_at: 1764374400, + source: "admin_console", + object: "event", + api_version: "v2", + event_type: "subscription_created", + webhook_status: "failed", + content: { subscription: { id: `sub_${site}` } }, + }, + }); + }, + }, estimate: { createSubItemEstimate: async () => sdkResult({ estimate: { id: `est_${site}` } }), }, diff --git a/src/lib/tunnel/forwarder.ts b/src/lib/tunnel/forwarder.ts index d968295..7147401 100644 --- a/src/lib/tunnel/forwarder.ts +++ b/src/lib/tunnel/forwarder.ts @@ -18,12 +18,17 @@ export function __setFetchForTest(fn: FetchFn | null): void { let fetchImpl: FetchFn = globalThis.fetch.bind(globalThis) as FetchFn; +/** Send a request to the developer's local handler (replaced by `__setFetchForTest`). */ +export function fetchLocalHandler(url: string, init: RequestInit): Promise { + return fetchImpl(url, init); +} + export type ForwardTargetResult = | { url: string; warning?: string } | { error: string }; /** `localhost`, any 127.0.0.0/8 address, or the IPv6 loopback (brackets already stripped). */ -function isLoopbackHost(hostname: string): boolean { +export function isLoopbackHost(hostname: string): boolean { return ( hostname === "localhost" || hostname === "::1" || @@ -36,6 +41,18 @@ const FORWARD_TO_EXAMPLE = "Example: --forward-to http://localhost:3000/webhook" /** Chargebee event type names are lowercase dotted/underscored slugs; anything else can't be a real one. */ const EVENT_TYPE_HEADER_RE = /^[a-z0-9_.:-]+$/; +/** + * Set `X-Chargebee-Event-Type` so a handler can branch without parsing the body. + * Shared by `listen` and `event replay` so both deliver the same header. A value + * that isn't a valid event-type slug is untrusted and the header is left out + * rather than passed through. + */ +export function setEventTypeHeader(headers: Headers, eventType: unknown): void { + if (typeof eventType === "string" && EVENT_TYPE_HEADER_RE.test(eventType)) { + headers.set("X-Chargebee-Event-Type", eventType); + } +} + /** * Validate and normalize a `--forward-to` value into an absolute http(s) URL. * @@ -117,9 +134,7 @@ export async function forward( headers.set(k, v); } } - if (EVENT_TYPE_HEADER_RE.test(msg.event_type)) { - headers.set("X-Chargebee-Event-Type", msg.event_type); - } + setEventTypeHeader(headers, msg.event_type); const resp = await fetchImpl(targetURL, { method: msg.method, diff --git a/src/lib/tunnel/replay.ts b/src/lib/tunnel/replay.ts new file mode 100644 index 0000000..b60f499 --- /dev/null +++ b/src/lib/tunnel/replay.ts @@ -0,0 +1,194 @@ +import { lookup } from "node:dns/promises"; +import { isIP } from "node:net"; + +import { fetchLocalHandler, isLoopbackHost, resolveForwardTarget, setEventTypeHeader } from "./forwarder.js"; + +/** + * `chargebee event replay`: the CLI POSTs a past event to a handler on this + * machine. Unlike `listen` (which warns on a remote target), replay only ever + * sends to loopback, with no override: a deployed endpoint is a job for Resend, + * where Chargebee's delivery system sends with the endpoint's real credentials. + */ + +/** + * Why `event replay` failed. One code per failure, used as both the `--json` + * `error.code` and the telemetry error category, so tests and consumers import + * these instead of repeating the strings. + */ +export const ReplayErrorCode = { + INVALID_FORWARD_TO: "replay_invalid_forward_to", + TARGET_REFUSED: "replay_target_refused", + LIVE_SITE_REFUSED: "replay_live_site_refused", + HANDLER_ERROR: "replay_handler_error", + UNREACHABLE: "replay_unreachable", +} as const; + +export type ReplayErrorCode = (typeof ReplayErrorCode)[keyof typeof ReplayErrorCode]; + +/** Same per-request budget `listen` gives a local handler. */ +export const REPLAY_TIMEOUT_MS = 8000; + +const LOOPBACK_ONLY = + "replay only sends to this machine (localhost, 127.0.0.1, ::1). To deliver to a deployed endpoint, use Resend on the event page."; + +export type LookupFn = ( + hostname: string, + options: { all: true; verbatim: true }, +) => Promise>; + +let lookupImpl: LookupFn = lookup; + +/** TEST-ONLY: replace the DNS lookup (pass null to restore). */ +export function __setLookupForTest(fn: LookupFn | null): void { + lookupImpl = fn ?? lookup; +} + +function hostnameOf(url: string): string { + return new URL(url).hostname.replace(/^\[|\]$/g, ""); +} + +/** + * Normalise `--forward-to` exactly as `listen` does, but refuse anything that + * isn't a loopback host instead of warning about it. + */ +export function resolveReplayTarget( + raw: string, +): { url: string } | { error: string; code: ReplayErrorCode } { + const target = resolveForwardTarget(raw); + if ("error" in target) return { error: target.error, code: ReplayErrorCode.INVALID_FORWARD_TO }; + const hostname = hostnameOf(target.url); + if (!isLoopbackHost(hostname)) { + return { error: `Refusing to send to ${hostname}: ${LOOPBACK_ONLY}`, code: ReplayErrorCode.TARGET_REFUSED }; + } + return { url: target.url }; +} + +/** Expand an IPv6 address (optionally with a dotted IPv4 tail) into 8 groups. */ +function ipv6Groups(address: string): number[] { + let text = address.toLowerCase(); + const v4Tail = /(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(text); + if (v4Tail) { + const [a, b, c, d] = v4Tail.slice(1).map(Number) as [number, number, number, number]; + text = `${text.slice(0, v4Tail.index)}${((a << 8) | b).toString(16)}:${((c << 8) | d).toString(16)}`; + } + const [head = "", tail] = text.split("::"); + const parse = (part: string) => (part ? part.split(":").map((g) => parseInt(g, 16)) : []); + const front = parse(head); + const back = tail === undefined ? [] : parse(tail); + return [...front, ...Array(8 - front.length - back.length).fill(0), ...back]; +} + +/** 127.0.0.0/8, `::1`, or an IPv4-mapped 127.x address. Hostnames are never loopback here. */ +export function isLoopbackAddress(address: string): boolean { + const version = isIP(address); + if (version === 4) return address.startsWith("127."); + if (version !== 6) return false; + const g = ipv6Groups(address); + const zeroPrefix = (n: number) => g.slice(0, n).every((x) => x === 0); + if (zeroPrefix(7) && g[7] === 1) return true; + return zeroPrefix(5) && g[5] === 0xffff && g[6]! >> 8 === 0x7f; +} + +/** + * Check the address the target will actually connect to. IP literals are + * checked directly; `localhost` must resolve only to loopback addresses, so an + * `/etc/hosts` entry can't redirect the payload off the machine. + * Returns an error message, or undefined when the target is local. + */ +export async function checkLoopbackResolution(url: string): Promise { + const hostname = hostnameOf(url); + if (isIP(hostname)) return undefined; + let addresses: Array<{ address: string }>; + try { + addresses = await lookupImpl(hostname, { all: true, verbatim: true }); + } catch (err) { + return `Could not resolve ${hostname}: ${err instanceof Error ? err.message : String(err)}`; + } + if (addresses.length === 0) return `Could not resolve ${hostname}.`; + const remote = addresses.find((a) => !isLoopbackAddress(a.address)); + if (remote) { + return `Refusing to send to ${hostname}: it resolves to ${remote.address}, not this machine. Use http://127.0.0.1: instead.`; + } + return undefined; +} + +export interface ReplayResponse { + status: number; + durationMs: number; + /** Set for a 3xx: where the handler tried to redirect (never followed). */ + location?: string; +} + +/** + * POST the event object (the webhook body) to the local handler and return its + * status. Like `forward()`, any HTTP status is a response, and a handler that + * can't be reached (or doesn't answer in time) throws. Redirects are not + * followed, so a handler can't bounce the payload elsewhere. The handler's + * response body is discarded. + */ +export async function sendReplay( + url: string, + event: Record, + opts: { timeoutMs?: number } = {}, +): Promise { + const timeoutMs = opts.timeoutMs ?? REPLAY_TIMEOUT_MS; + const headers = new Headers({ "Content-Type": "application/json" }); + setEventTypeHeader(headers, event.event_type); + const started = performance.now(); + let resp: Response; + try { + resp = await fetchLocalHandler(url, { + method: "POST", + headers, + body: JSON.stringify(event), + redirect: "manual", + signal: AbortSignal.timeout(timeoutMs), + }); + } catch (err) { + const timedOut = err instanceof Error && (err.name === "TimeoutError" || err.name === "AbortError"); + throw new Error( + timedOut + ? `${url} did not respond within ${timeoutMs / 1000}s.` + : `Unable to reach ${url}. Ensure your local server is running.`, + { cause: err }, + ); + } + await resp.body?.cancel(); + const durationMs = Math.round(performance.now() - started); + const location = resp.status >= 300 && resp.status < 400 ? resp.headers.get("location") : null; + return { status: resp.status, durationMs, ...(location ? { location } : {}) }; +} + +/** + * Explain a non-2xx reply from the developer's handler: what the status means + * for a webhook route and what to change. The status itself is already on the + * result line, so it isn't repeated here. + */ +export function describeHandlerStatus(url: string, status: number, location?: string): string { + const { host, pathname } = new URL(url); + + if (status >= 300 && status < 400) { + return location + ? `Your handler redirected to ${location}. Replay doesn't follow redirects; put the final URL in --forward-to.` + : `Your handler asked for a redirect but gave no Location. Replay doesn't follow redirects; check the URL in --forward-to.`; + } + if (status === 401 || status === 403) { + return "Your handler rejected the request as unauthenticated. Replay sends no credentials; if your handler checks webhook Basic auth, allow requests from localhost while testing."; + } + if (status === 404) { + return `Your server on ${host} is running, but nothing handles ${pathname}. Check that the path in --forward-to matches your webhook route.`; + } + if (status === 405) { + return `Your handler doesn't accept POST on ${pathname}. Webhooks are delivered as POST; allow POST on this route.`; + } + if (status === 413) { + return "The event is larger than your server's request-body limit. Raise the JSON body size limit on this route."; + } + if (status >= 400 && status < 500) { + return "Your handler rejected the event. Check your server's logs for the reason. The body is the event as it is now, so fields such as webhook_status can differ from the original delivery."; + } + if (status >= 500 && status < 600) { + return "Your handler failed while processing the event. Check your server's logs for the error, fix it, and run this command again."; + } + return `Your handler returned ${status}.`; +} diff --git a/src/program.ts b/src/program.ts index f7c9c42..910e1a9 100644 --- a/src/program.ts +++ b/src/program.ts @@ -5,6 +5,7 @@ import { Command } from "commander"; import { registerAliasCommand } from "./commands/alias.js"; import { registerAuthCommand } from "./commands/auth.js"; import { registerDocsCommand } from "./commands/docs.js"; +import { registerEventReplayCommand } from "./commands/event-replay.js"; import { registerFeedbackCommand } from "./commands/feedback.js"; import { registerListenCommand } from "./commands/listen.js"; import { registerOpenCommand } from "./commands/open.js"; @@ -69,6 +70,8 @@ export function buildProgram(version: string): Command { program.helpInformation = () => `${renderHelp(program, version)}\n`; registerAll(program); + // Built-in subcommands of generated groups attach after the groups exist. + registerEventReplayCommand(program); configureHelpStyle(program); configureJsonOutput(program); diff --git a/src/tests/integration/event-replay.test.ts b/src/tests/integration/event-replay.test.ts new file mode 100644 index 0000000..e41ed49 --- /dev/null +++ b/src/tests/integration/event-replay.test.ts @@ -0,0 +1,273 @@ +/** + * Isolated CLI tests for `chargebee event replay`. The SDK client is a fake, the + * local handler is a fetch stub and DNS lookups are stubbed — no network. + */ +import { afterEach, beforeEach, describe, expect, it } from "bun:test"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { __resetRuntimeState } from "../../lib/api/sdk.js"; +import { __setFetchForTest } from "../../lib/tunnel/forwarder.js"; +import { __setLookupForTest, ReplayErrorCode } from "../../lib/tunnel/replay.js"; +import { takeTelemetryError } from "../../lib/telemetry/error.js"; +import { + createEnvPatcher, + installFakeClient, + runCli, + setStderrIsTTY, + uninstallFakeClient, + type ClientConstruction, +} from "../../lib/test-support/_helpers.js"; + +const env = createEnvPatcher(); + +type Seen = { url: string; headers: Record; body: string }; + +let configDir: string; +let restoreStderrTty: (() => void) | undefined; + +const HANDLER_URL = "http://127.0.0.1:3000/webhooks"; + +/** Stand in for the local handler: record each request and reply with `status`. */ +function stubHandler(status: number, headers: Record = {}) { + const seen: Seen[] = []; + __setFetchForTest(async (input, init = {}) => { + const h: Record = {}; + new Headers(init.headers).forEach((v, k) => { h[k] = v; }); + seen.push({ url: String(input), headers: h, body: String(init.body ?? "") }); + return new Response(status === 204 ? null : "handler body", { status, headers }); + }); + return { url: HANDLER_URL, seen }; +} + +function testSite(): ClientConstruction[] { + env.set("CHARGEBEE_SITE", "acme-test"); + env.set("CHARGEBEE_API_KEY", "test_xxx"); + const constructions: ClientConstruction[] = []; + installFakeClient({ constructions }); + return constructions; +} + +beforeEach(() => { + configDir = mkdtempSync(join(tmpdir(), "cb-replay-")); + env.set("CHARGEBEE_CONFIG_DIR", configDir); + env.set("CHARGEBEE_SITE", undefined); + env.set("CHARGEBEE_API_KEY", undefined); + env.set("CHARGEBEE_HOST", undefined); + restoreStderrTty = setStderrIsTTY(false); + takeTelemetryError(); + __resetRuntimeState(); + __setLookupForTest(async () => [{ address: "127.0.0.1", family: 4 }]); +}); + +afterEach(() => { + env.restore(); + restoreStderrTty?.(); + restoreStderrTty = undefined; + __setFetchForTest(null); + __setLookupForTest(null); + uninstallFakeClient(); + __resetRuntimeState(); + rmSync(configDir, { recursive: true, force: true }); +}); + +describe("chargebee event replay", () => { + it("POSTs the retrieved event to the local handler and reports its status", async () => { + testSite(); + const h = stubHandler(200); + const { stdout, stderr, exitCode } = await runCli(["event", "replay", "ev_123", "--forward-to", h.url]); + expect(exitCode).toBe(0); + expect(h.seen).toHaveLength(1); + const body = JSON.parse(h.seen[0]!.body); + expect(body).toMatchObject({ id: "ev_123", event_type: "subscription_created", content: { subscription: { id: "sub_acme-test" } } }); + expect(body).not.toHaveProperty("headers"); + expect(body).not.toHaveProperty("httpStatusCode"); + expect(h.seen[0]!.headers["content-type"]).toBe("application/json"); + expect(h.seen[0]!.headers["x-chargebee-event-type"]).toBe("subscription_created"); + expect(stderr).toBe(""); + expect(stdout).toMatch( + new RegExp(`^Replaying ev_123 \\(subscription_created\\) to ${h.url}\nev_123 {3}subscription_created → 200 \\(\\d+ ms\\)$`), + ); + expect(stdout).not.toContain("handler body"); + expect(stdout).not.toContain("sub_acme-test"); + }); + + it("accepts a bare port as --forward-to", async () => { + testSite(); + const h = stubHandler(204); + const { exitCode } = await runCli(["event", "replay", "ev_123", "-f", "3000"]); + expect(exitCode).toBe(0); + expect(h.seen).toHaveLength(1); + expect(h.seen[0]!.url).toBe("http://localhost:3000"); + }); + + it("prints a structured result with --json", async () => { + testSite(); + const h = stubHandler(201); + const { stdout, stderr, exitCode } = await runCli(["event", "replay", "ev_123", "--forward-to", h.url, "--json"]); + expect(exitCode).toBe(0); + expect(stderr).toBe(""); + const result = JSON.parse(stdout); + expect(result).toEqual({ + event_id: "ev_123", + event_type: "subscription_created", + url: h.url, + status: 201, + duration_ms: expect.any(Number), + }); + }); + + it("exits 1 when the handler returns an error status", async () => { + testSite(); + const h = stubHandler(500); + const { stdout, stderr, exitCode } = await runCli(["event", "replay", "ev_123", "--forward-to", h.url]); + expect(exitCode).toBe(1); + expect(stdout).toMatch(/subscription_created → 500 \(\d+ ms\) \(non-2xx\)/); + expect(stderr).toContain("Check your server's logs for the error"); + expect(takeTelemetryError()).toBe(ReplayErrorCode.HANDLER_ERROR); + }); + + it("reports an error status as a JSON error with details", async () => { + testSite(); + const h = stubHandler(422); + const { stdout, stderr, exitCode } = await runCli(["event", "replay", "ev_123", "--forward-to", h.url, "--json"]); + expect(exitCode).toBe(1); + expect(stdout).toBe(""); + const { error } = JSON.parse(stderr); + expect(error).toMatchObject({ + code: ReplayErrorCode.HANDLER_ERROR, + exit_code: 1, + details: { event_id: "ev_123", event_type: "subscription_created", url: h.url, status: 422 }, + }); + }); + + it("explains a 404 as a path that has no route", async () => { + testSite(); + const h = stubHandler(404); + const { stderr, exitCode } = await runCli(["event", "replay", "ev_123", "--forward-to", h.url]); + expect(exitCode).toBe(1); + expect(stderr).toBe( + `Your server on 127.0.0.1:3000 is running, but nothing handles /webhooks. Check that the path in --forward-to matches your webhook route.`, + ); + }); + + it("exits 1 on a redirect and does not follow it", async () => { + testSite(); + const elsewhere = "http://127.0.0.1:4000/elsewhere"; + const h = stubHandler(302, { location: elsewhere }); + const { stderr, exitCode } = await runCli(["event", "replay", "ev_123", "--forward-to", h.url]); + expect(exitCode).toBe(1); + expect(h.seen).toHaveLength(1); + expect(stderr).toContain(`Your handler redirected to ${elsewhere}. Replay doesn't follow redirects`); + }); + + it("exits 7 when the handler can't be reached", async () => { + testSite(); + const h = stubHandler(200); + __setFetchForTest(async () => { throw new TypeError("fetch failed"); }); + const { stdout, stderr, exitCode } = await runCli(["event", "replay", "ev_123", "--forward-to", h.url, "--json"]); + expect(exitCode).toBe(7); + expect(stdout).toBe(""); + const { error } = JSON.parse(stderr); + expect(error).toMatchObject({ code: ReplayErrorCode.UNREACHABLE, exit_code: 7, details: { event_id: "ev_123", url: h.url } }); + expect(error.message).toContain(`Unable to reach ${h.url}`); + expect(takeTelemetryError()).toBe(ReplayErrorCode.UNREACHABLE); + }); + + it("refuses a non-loopback target before any API call", async () => { + const constructions = testSite(); + const { stderr, exitCode } = await runCli(["event", "replay", "ev_123", "--forward-to", "https://api.example.com/hook"]); + expect(exitCode).toBe(1); + expect(stderr).toContain( + "Refusing to send to api.example.com: replay only sends to this machine (localhost, 127.0.0.1, ::1). To deliver to a deployed endpoint, use Resend on the event page.", + ); + expect(constructions).toHaveLength(0); + expect(takeTelemetryError()).toBe(ReplayErrorCode.TARGET_REFUSED); + }); + + it("refuses an invalid target", async () => { + testSite(); + const { stderr, exitCode } = await runCli(["event", "replay", "ev_123", "--forward-to", "not a url", "--json"]); + expect(exitCode).toBe(1); + expect(JSON.parse(stderr).error).toMatchObject({ code: ReplayErrorCode.INVALID_FORWARD_TO }); + expect(takeTelemetryError()).toBe(ReplayErrorCode.INVALID_FORWARD_TO); + }); + + it("refuses localhost when it resolves off this machine", async () => { + testSite(); + __setLookupForTest(async () => [{ address: "203.0.113.7", family: 4 }]); + const { stderr, exitCode } = await runCli(["event", "replay", "ev_123", "--forward-to", "http://localhost:3000/x"]); + expect(exitCode).toBe(1); + expect(stderr).toContain("Refusing to send to localhost: it resolves to 203.0.113.7, not this machine."); + expect(takeTelemetryError()).toBe(ReplayErrorCode.TARGET_REFUSED); + }); + + it("refuses a live site without retrieving the event", async () => { + env.set("CHARGEBEE_SITE", "acme"); + env.set("CHARGEBEE_API_KEY", "live_xxx"); + const constructions: ClientConstruction[] = []; + installFakeClient({ constructions }); + const h = stubHandler(200); + const { stderr, exitCode } = await runCli(["event", "replay", "ev_123", "--forward-to", h.url, "--json"]); + expect(exitCode).toBe(1); + const { error } = JSON.parse(stderr); + expect(error.code).toBe(ReplayErrorCode.LIVE_SITE_REFUSED); + expect(error.message).toContain(`Refusing to replay on live site "acme".`); + expect(error.message).toContain(`Event replay is only available on test sites`); + expect(constructions).toHaveLength(0); + expect(h.seen).toHaveLength(0); + expect(takeTelemetryError()).toBe(ReplayErrorCode.LIVE_SITE_REFUSED); + }); + + it("reports an unknown event as an API error", async () => { + testSite(); + const h = stubHandler(200); + const { stderr, exitCode } = await runCli(["event", "replay", "ev_missing", "--forward-to", h.url, "--json"]); + expect(exitCode).toBe(5); + expect(JSON.parse(stderr).error).toMatchObject({ code: "api_error" }); + expect(h.seen).toHaveLength(0); + }); + + it("exits 3 when no site is configured", async () => { + const h = stubHandler(200); + const { exitCode } = await runCli(["event", "replay", "ev_123", "--forward-to", h.url, "--json"]); + expect(exitCode).toBe(3); + expect(h.seen).toHaveLength(0); + }); + + it("rejects an invalid event id", async () => { + testSite(); + const h = stubHandler(200); + const { stderr, exitCode } = await runCli(["event", "replay", "../x", "--forward-to", h.url]); + expect(exitCode).not.toBe(0); + expect(stderr).toContain(`invalid id "../x"`); + expect(h.seen).toHaveLength(0); + }); + + it("requires --forward-to", async () => { + testSite(); + const { stderr, exitCode } = await runCli(["event", "replay", "ev_123"]); + expect(exitCode).not.toBe(0); + expect(stderr).toMatch(/required option .*--forward-to/); + }); + + it("is listed under the event group with examples", async () => { + const group = await runCli(["event", "--help"]); + expect(group.stdout).toMatch(/replay \[options\] +Send a past event to a local webhook/); + const help = await runCli(["event", "replay", "--help"]); + expect(help.exitCode).toBe(0); + expect(help.stdout).toContain("chargebee event replay ev_"); + expect(help.stdout).toContain("--forward-to"); + expect(help.stdout).toContain("test sites only"); + }); + + it("honours --use-profile", async () => { + const constructions: ClientConstruction[] = []; + installFakeClient({ constructions }); + const h = stubHandler(200); + const { exitCode, stderr } = await runCli(["event", "replay", "ev_123", "--forward-to", h.url, "--use-profile", "nope"]); + expect(stderr).not.toContain("--use-profile is only valid"); + expect(exitCode).not.toBe(0); + }); +}); diff --git a/src/tests/integration/generated-operation-names.test.ts b/src/tests/integration/generated-operation-names.test.ts index d683e17..dc246c0 100644 --- a/src/tests/integration/generated-operation-names.test.ts +++ b/src/tests/integration/generated-operation-names.test.ts @@ -1,4 +1,5 @@ import { describe, expect, it } from "bun:test"; +import type { Command } from "commander"; import { buildProgram } from "../../program.js"; import { runCli } from "../../lib/test-support/_helpers.js"; @@ -22,6 +23,9 @@ const previousNames: Record> = { }, }; +/** Built-in subcommands (e.g. `event replay`) attach to generated groups but have no --data and no operation ID. */ +const isGenerated = (operation: Command) => operation.options.some((option) => option.long === "--data"); + describe("generated API operation names", () => { it("maps every generated command and alias to its OpenAPI operation IDs", () => { const program = buildProgram("test"); @@ -31,7 +35,7 @@ describe("generated API operation names", () => { for (const resource of resources) { const mapped = docsOperationIds[resource.name()]; expect(mapped).toBeDefined(); - for (const operation of resource.commands) { + for (const operation of resource.commands.filter(isGenerated)) { expect(mapped[operation.name()]).toBeDefined(); for (const alias of operation.aliases()) { expect(mapped[alias]).toEqual(mapped[operation.name()]); diff --git a/src/tests/unit/lib/tunnel/replay.test.ts b/src/tests/unit/lib/tunnel/replay.test.ts new file mode 100644 index 0000000..6d30212 --- /dev/null +++ b/src/tests/unit/lib/tunnel/replay.test.ts @@ -0,0 +1,195 @@ +import { afterEach, describe, expect, test } from "bun:test"; + +import { __setFetchForTest } from "../../../../lib/tunnel/forwarder.js"; +import { + __setLookupForTest, + checkLoopbackResolution, + describeHandlerStatus, + isLoopbackAddress, + ReplayErrorCode, + resolveReplayTarget, + sendReplay, +} from "../../../../lib/tunnel/replay.js"; + +type Seen = { url: string; init: RequestInit; headers: Record; body: string }; + +const url = "http://127.0.0.1:3000/webhooks"; + +/** Stand in for the local handler: record each request and answer with `respond`. */ +function stubHandler(respond: (init: RequestInit) => Response | Promise) { + const seen: Seen[] = []; + __setFetchForTest(async (input, init = {}) => { + const headers: Record = {}; + new Headers(init.headers).forEach((v, k) => { headers[k] = v; }); + seen.push({ url: String(input), init, headers, body: String(init.body ?? "") }); + return respond(init); + }); + return seen; +} + +afterEach(() => { + __setLookupForTest(null); + __setFetchForTest(null); +}); + +describe("ReplayErrorCode", () => { + // The values are a public contract (`--json` error.code, telemetry). Everything + // else imports the constants; this is the one place the wire strings are pinned, + // so changing one has to be deliberate. + test("keeps its published values", () => { + expect(ReplayErrorCode).toEqual({ + INVALID_FORWARD_TO: "replay_invalid_forward_to", + TARGET_REFUSED: "replay_target_refused", + LIVE_SITE_REFUSED: "replay_live_site_refused", + HANDLER_ERROR: "replay_handler_error", + UNREACHABLE: "replay_unreachable", + }); + }); +}); + +describe("resolveReplayTarget", () => { + test("accepts loopback URLs and shorthands", () => { + expect(resolveReplayTarget("http://localhost:3000/webhooks")).toEqual({ url: "http://localhost:3000/webhooks" }); + expect(resolveReplayTarget("3000")).toEqual({ url: "http://localhost:3000" }); + expect(resolveReplayTarget("127.0.0.2:8080/hook")).toEqual({ url: "http://127.0.0.2:8080/hook" }); + expect(resolveReplayTarget("https://[::1]:8443/x")).toEqual({ url: "https://[::1]:8443/x" }); + }); + + test("passes through malformed-target errors", () => { + const result = resolveReplayTarget("not a url"); + expect(result).toMatchObject({ code: ReplayErrorCode.INVALID_FORWARD_TO }); + expect("error" in result && result.error).toContain("is not a valid URL"); + }); + + test.each([ + ["https://api.example.com/hook", "api.example.com"], + ["http://192.168.1.10:3000/hook", "192.168.1.10"], + ["http://10.0.0.5/hook", "10.0.0.5"], + ["http://host.docker.internal:3000/hook", "host.docker.internal"], + ["http://[::ffff:7f00:1]:3000/hook", "::ffff:7f00:1"], + ])("refuses non-loopback target %s", (raw, host) => { + const result = resolveReplayTarget(raw); + expect("error" in result).toBe(true); + if (!("error" in result)) return; + expect(result.error).toContain(`Refusing to send to ${host}`); + expect(result.code).toBe(ReplayErrorCode.TARGET_REFUSED); + expect(result.error).toContain("replay only sends to this machine (localhost, 127.0.0.1, ::1)"); + expect(result.error).toContain("use Resend on the event page"); + }); +}); + +describe("isLoopbackAddress", () => { + test.each(["127.0.0.1", "127.255.0.9", "::1", "::ffff:127.0.0.1", "0:0:0:0:0:0:0:1"])("%s is loopback", (a) => { + expect(isLoopbackAddress(a)).toBe(true); + }); + test.each(["10.0.0.1", "192.168.0.1", "::", "fe80::1", "::ffff:10.0.0.1", "128.0.0.1", "localhost"])("%s is not", (a) => { + expect(isLoopbackAddress(a)).toBe(false); + }); +}); + +describe("checkLoopbackResolution", () => { + test("IP literals are checked without a lookup", async () => { + let lookups = 0; + __setLookupForTest(async () => { lookups++; return []; }); + expect(await checkLoopbackResolution("http://127.0.0.1:3000/x")).toBeUndefined(); + expect(await checkLoopbackResolution("http://[::1]:3000/x")).toBeUndefined(); + expect(lookups).toBe(0); + }); + + test("localhost must resolve only to loopback addresses", async () => { + __setLookupForTest(async () => [{ address: "127.0.0.1", family: 4 }, { address: "::1", family: 6 }]); + expect(await checkLoopbackResolution("http://localhost:3000/x")).toBeUndefined(); + }); + + test("refuses localhost when any address is not loopback", async () => { + __setLookupForTest(async () => [{ address: "127.0.0.1", family: 4 }, { address: "10.1.2.3", family: 4 }]); + const error = await checkLoopbackResolution("http://localhost:3000/x"); + expect(error).toContain("Refusing to send to localhost: it resolves to 10.1.2.3, not this machine."); + }); + + test("refuses when the lookup returns nothing or fails", async () => { + __setLookupForTest(async () => []); + expect(await checkLoopbackResolution("http://localhost/x")).toContain("Could not resolve localhost"); + __setLookupForTest(async () => { throw new Error("ENOTFOUND"); }); + expect(await checkLoopbackResolution("http://localhost/x")).toContain("Could not resolve localhost: ENOTFOUND"); + }); +}); + +describe("sendReplay", () => { + const event = { id: "ev_1", event_type: "subscription_created", content: { subscription: { id: "sub_1" } } }; + + test("POSTs the event as JSON with the event-type header", async () => { + const seen = stubHandler(() => new Response("ok", { status: 200 })); + const response = await sendReplay(url, event); + expect(response).toEqual({ status: 200, durationMs: expect.any(Number) }); + expect(seen).toHaveLength(1); + expect(seen[0]!.url).toBe(url); + expect(seen[0]!.init.method).toBe("POST"); + expect(seen[0]!.headers["content-type"]).toBe("application/json"); + expect(seen[0]!.headers["x-chargebee-event-type"]).toBe("subscription_created"); + expect(JSON.parse(seen[0]!.body)).toEqual(event); + }); + + test("omits the event-type header when the type is not a valid slug", async () => { + const seen = stubHandler(() => new Response(null, { status: 204 })); + await sendReplay(url, { id: "ev_2", event_type: "Bad\nType" }); + await sendReplay(url, { id: "ev_3" }); + expect(seen.map((s) => "x-chargebee-event-type" in s.headers)).toEqual([false, false]); + }); + + test("reports error statuses as responses", async () => { + stubHandler(() => new Response("boom", { status: 500 })); + expect(await sendReplay(url, event)).toMatchObject({ status: 500 }); + }); + + test("does not follow redirects and reports where the handler pointed", async () => { + const elsewhere = "http://127.0.0.1:4000/stolen"; + const seen = stubHandler(() => new Response(null, { status: 307, headers: { location: elsewhere } })); + expect(await sendReplay(url, event)).toEqual({ status: 307, durationMs: expect.any(Number), location: elsewhere }); + expect(seen[0]!.init.redirect).toBe("manual"); + }); + + test("reports an unreachable handler", async () => { + stubHandler(() => { throw new TypeError("fetch failed"); }); + await expect(sendReplay(url, event)).rejects.toThrow(`Unable to reach ${url}. Ensure your local server is running.`); + }); + + test("reports a handler that does not answer in time", async () => { + stubHandler(({ signal }) => new Promise((_, reject) => { + signal!.addEventListener("abort", () => reject(signal!.reason)); + })); + await expect(sendReplay(url, event, { timeoutMs: 50 })).rejects.toThrow(`${url} did not respond within 0.05s.`); + }); +}); + +describe("describeHandlerStatus", () => { + const url = "http://localhost:6000/event-replay"; + + test.each([ + [404, "Your server on localhost:6000 is running, but nothing handles /event-replay. Check that the path in --forward-to matches your webhook route."], + [401, "Replay sends no credentials"], + [403, "Replay sends no credentials"], + [405, "Your handler doesn't accept POST on /event-replay."], + [413, "larger than your server's request-body limit"], + [422, "Your handler rejected the event. Check your server's logs"], + [500, "Your handler failed while processing the event."], + [503, "Your handler failed while processing the event."], + ])("%d explains the next step without repeating the status line", (status, hint) => { + const message = describeHandlerStatus(url, status); + expect(message).toContain(hint); + expect(message).not.toContain("returned"); + expect(message).not.toContain("\n"); + }); + + test("redirects name the target, or note it is missing", () => { + expect(describeHandlerStatus(url, 307, "http://localhost:6000/new")).toBe( + "Your handler redirected to http://localhost:6000/new. Replay doesn't follow redirects; put the final URL in --forward-to.", + ); + expect(describeHandlerStatus(url, 302)).toContain("gave no Location"); + }); + + test("an unusual status falls back to naming it", () => { + expect(describeHandlerStatus(url, 199)).toBe("Your handler returned 199."); + expect(describeHandlerStatus(url, 600)).toBe("Your handler returned 600."); + }); +});