fix(cli): reject bad billing --timeout and --needed values as usage errors (#7910)

* fix(cli): reject bad billing --timeout and --needed values as usage errors

Closes #7909

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(cli): share one positive-integer flag parser across billing, compare and share

Refs #7909

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Dean
2026-11-18 16:33:18 +00:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 43582dcb72
commit 559499453b
6 changed files with 96 additions and 12 deletions
+32
View File
@@ -212,6 +212,38 @@ describe("billing with no action", () => {
});
});
describe("billing numeric flags", () => {
it.each([
["--timeout", "abc"],
["--timeout", "-5"],
["--timeout", "0"],
["--timeout", "2.5"],
["--needed", "abc"],
["--needed", "-1"],
["--needed", "0"],
])("rejects %s %s as a usage error before opening any page", async (flag, value) => {
await expect(
runCommand(billing, { rawArgs: ["add-credits", flag, value] }),
).rejects.toMatchObject({ result: { exitCode: 2, kind: "usage_error" } });
expect(opened).toEqual([]);
expect(plan.calls).toBe(0);
});
it("still waits for a valid --needed and --timeout", async () => {
vi.spyOn(console, "log").mockImplementation(() => undefined);
vi.spyOn(console, "error").mockImplementation(() => undefined);
vi.useFakeTimers();
const done = runCommand(billing, {
rawArgs: ["add-credits", "--needed", "100", "--timeout", "30"],
});
await vi.advanceTimersByTimeAsync(2000);
await done;
vi.useRealTimers();
expect(opened).toHaveLength(1);
expect(new URL(opened[0] ?? "").searchParams.get("needed_credits")).toBe("100");
});
});
describe("billing without a terminal", () => {
it("prints Stripe's checkout link instead of waiting for Enter, and opens only the pricing page", async () => {
const log = vi.spyOn(console, "log").mockImplementation(() => undefined);
+5 -2
View File
@@ -17,6 +17,7 @@ import { c } from "../ui/colors.js";
import { trackBillingCheckoutFailed, trackBillingWaitTimeout } from "../telemetry/events.js";
import { failCommand, setCommandExitCode } from "../utils/commandResult.js";
import { isUnattended } from "../utils/attendedTerminal.js";
import { parsePositiveIntegerArg } from "../utils/integerArg.js";
import { defineCommand } from "../utils/defineCommand.js";
const describe = (p: Plan | null) =>
@@ -177,9 +178,11 @@ export default defineCommand({
console.error(c.error("Use `billing subscribe` or `billing add-credits`."));
failCommand();
}
const needed = Number(args.needed) || undefined;
const needed = parsePositiveIntegerArg(args.needed, "--needed");
const timeoutSeconds =
parsePositiveIntegerArg(args.timeout, "--timeout", { unit: "seconds" }) ?? 600;
const skill = checkoutSkill(args.skill);
const deadline = Date.now() + (Number(args.timeout) || 600) * 1000;
const deadline = Date.now() + timeoutSeconds * 1000;
const stop = new AbortController();
const atDeadline = setTimeout(() => stop.abort(), deadline - Date.now());
atDeadline.unref?.();
+5 -7
View File
@@ -12,6 +12,7 @@ import {
import { c } from "../ui/colors.js";
import { normalizeErrorMessage } from "../utils/errorMessage.js";
import { displayPathFromInput, readOptionalString, resolveFromBase } from "../utils/pathArgs.js";
import { parsePositiveIntegerArg } from "../utils/integerArg.js";
import { trackCompareSheet } from "../telemetry/events.js";
import { serveStaticProjectHtml } from "../utils/staticProjectServer.js";
import { leftOutNotice, stageReferencedFiles } from "../utils/stageReferencedFiles.js";
@@ -118,13 +119,10 @@ function parseColumns(value: unknown): number | undefined {
}
function parseTimeoutMs(value: unknown): number {
const raw = readOptionalString(value);
if (!raw) return DEFAULT_RENDER_READY_TIMEOUT_MS;
const parsed = Number(raw);
if (!Number.isInteger(parsed) || parsed < 1) {
throw new CliUsageError("--timeout must be a positive integer number of milliseconds");
}
return parsed;
return (
parsePositiveIntegerArg(readOptionalString(value), "--timeout", { unit: "milliseconds" }) ??
DEFAULT_RENDER_READY_TIMEOUT_MS
);
}
function defaultCompareCols(cellCount: number): number {
+3 -3
View File
@@ -11,6 +11,7 @@ import {
} from "../share/service.js";
import { shareError } from "../share/errors.js";
import { jsonFailure } from "../utils/jsonError.js";
import { parsePositiveIntegerArg } from "../utils/integerArg.js";
import type { Example } from "./_examples.js";
export const examples: Example[] = [
@@ -103,9 +104,8 @@ interface ShareArgs {
"include-source"?: boolean;
}
function parseInput(args: ShareArgs): ShareAction {
const waitSeconds = Number(args["wait-seconds"]);
if (!Number.isInteger(waitSeconds) || waitSeconds < 1 || waitSeconds > 1800)
throw new CliUsageError("--wait-seconds must be an integer from 1 to 1800.");
const waitSeconds =
parsePositiveIntegerArg(args["wait-seconds"], "--wait-seconds", { max: 1800 }) ?? 300;
if ([args.update, args.status, args.manage].filter(Boolean).length > 1)
throw new CliUsageError("Choose only one of --update, --status or --manage.");
const audience = requestedAudience(args);
+34
View File
@@ -0,0 +1,34 @@
import { describe, expect, it } from "vitest";
import { parsePositiveIntegerArg } from "./integerArg.js";
describe("parsePositiveIntegerArg", () => {
it("returns undefined for an unset flag so the caller keeps its default", () => {
expect(parsePositiveIntegerArg(undefined, "--timeout")).toBeUndefined();
});
it("accepts a positive whole number", () => {
expect(parsePositiveIntegerArg("30", "--timeout")).toBe(30);
expect(parsePositiveIntegerArg("1800", "--wait-seconds", { max: 1800 })).toBe(1800);
});
it.each(["abc", "-5", "0", "2.5", ""])("rejects %j as a usage error", (value) => {
expect(() => parsePositiveIntegerArg(value, "--needed")).toThrow(
expect.objectContaining({
message: "--needed must be a positive integer",
result: expect.objectContaining({ exitCode: 2, kind: "usage_error" }),
}),
);
});
it("rejects a value above max and names the range", () => {
expect(() => parsePositiveIntegerArg("1801", "--wait-seconds", { max: 1800 })).toThrow(
"--wait-seconds must be an integer from 1 to 1800",
);
});
it("names the unit when one is given", () => {
expect(() => parsePositiveIntegerArg("abc", "--timeout", { unit: "seconds" })).toThrow(
"--timeout must be a positive integer number of seconds",
);
});
});
+17
View File
@@ -0,0 +1,17 @@
import { CliUsageError } from "./commandResult.js";
/** A whole-number flag from 1 to max; unset returns undefined, anything else is a usage error. */
export function parsePositiveIntegerArg(
value: unknown,
flag: string,
options: { max?: number; unit?: string } = {},
): number | undefined {
if (value === undefined) return undefined;
const parsed = Number(value);
const { max, unit } = options;
if (!Number.isInteger(parsed) || parsed < 1 || (max !== undefined && parsed > max)) {
const range = max === undefined ? "a positive integer" : `an integer from 1 to ${max}`;
throw new CliUsageError(`${flag} must be ${range}${unit ? ` number of ${unit}` : ""}`);
}
return parsed;
}