Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 104 additions & 4 deletions packages/cli/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,18 @@ import {
type ServeMode,
} from "./serve.js";
import { executeCiReport } from "./ci-report-command.js";
import { note, report } from "./output.js";
import { exitCodeFor, note, report, verdictNotes } from "./output.js";
import { LiveReport } from "./live.js";
import { colorDepth, colorEnabled, lineWidth, liveEnabled, styler } from "./style.js";
import { executeRun } from "./run.js";
import {
CHECK_CATALOGUE,
PROTOCOL_IDS,
X402_PAYMENT_CHECK_IDS,
catalogueEntry,
deniedEnvValues,
endpointOutcome,
networkClass,
paymentChainFor,
runMppChannelSuite,
runMppChargeSuite,
Expand Down Expand Up @@ -226,7 +232,11 @@ is not set: X402-06 settles a payment; X402-07..10 send payments the target
must refuse (a corrupted signature, a replay, an underpayment, an expired
authorization). X402-11 needs a request the service must refuse, the reject case
of a wasit.config.json endpoint: it runs in wasit run and is skipped here. See
docs/CHECKS.md for what each check ID verifies.`,
docs/CHECKS.md for what each check ID verifies.

At a terminal the output is coloured and live: each check shows while it runs,
with its duration, and the run's duration comes at the end. A pipe, CI, --json
or NO_COLOR gives the plain text; FORCE_COLOR=1 colours a pipe.`,
)
.action(async (opts) => {
const jsonMode = opts.json === true;
Expand All @@ -236,6 +246,12 @@ docs/CHECKS.md for what each check ID verifies.`,
...(opts.header ? { headers: opts.header as Record<string, string> } : {}),
};

// A person at a terminal gets the coloured, live output; a pipe, CI, NO_COLOR
// and --json get the plain text below, unchanged.
if (!jsonMode && colorEnabled(process.stdout, process.env)) {
process.exit(await liveX402Test(opts, shape));
}

const results = await runX402ReadChecks({ target: opts.target, ...shape });
// Each chain reads its own payer key: a Stellar secret is no use on EVM.
const keyEnv = paymentChainFor(opts.network as string)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY";
Expand Down Expand Up @@ -569,8 +585,92 @@ that channel.`,
},
});

process.exit(report(results, jsonMode));
process.exit(report(results, jsonMode, terminalStyle(jsonMode)));
});


/** Colours for the MPP commands' text output, when a person is at the terminal. */
function terminalStyle(jsonMode: boolean): { style: ReturnType<typeof styler>; width: number } {
return {
style: styler(!jsonMode && colorEnabled(process.stdout, process.env), colorDepth(process.env)),
width: lineWidth(process.stdout),
};
}

/**
* `wasit test` for a person at a terminal: the same checks, notes and exit code
* as the plain output, drawn live (a RUNNING line with a timer while a check is
* in flight, each result as it arrives, the counts and the duration at the end).
*/
async function liveX402Test(
opts: Record<string, unknown>,
shape: { method?: string; body?: string; headers?: Record<string, string> },
): Promise<number> {
const secrets = deniedEnvValues(process.env);
const live = new LiveReport({
stream: process.stdout,
live: liveEnabled(process.stdout, process.env),
depth: colorDepth(process.env),
clean: (text) => sanitizeText(text, { redact: secrets }),
});
const target = opts["target"] as string;
const network = opts["network"] as string;
live.header(CLI_VERSION, "x402 conformance", [
["target", `${target}${shape.method !== undefined ? ` ${shape.method.toUpperCase()}` : ""}`],
["network", network],
]);

live.phase("challenge", [["no payment"]]);
live.running("X402-01..05", "Challenge checks");
const results = await runX402ReadChecks({ target, ...shape, onResult: (result) => live.result(result) });
live.gap();

const keyEnv = paymentChainFor(network)?.payerKeyEnv ?? "STELLAR_PRIVATE_KEY";
const payerKey = (opts["payerKey"] as string | undefined) ?? process.env[keyEnv];
if (opts["readOnly"] === true) {
live.phase("payment", [["not run"]]);
live.note("--read-only set: the payment checks were not run.");
} else if (!payerKey) {
live.phase("payment", [["not run"]]);
live.note(`No payer key: set ${keyEnv} in .env or pass --payer-key. The payment checks were not run.`);
} else if (networkClass(network) !== "test") {
// Not a test network: the guard refuses the payment checks before anything
// is signed (the PREFLIGHT line says why), so no money moves.
live.phase("payment", [[network], ["not a test network: refused", "danger"]]);
} else {
live.phase("payment", [[network], ["testnet funds move", "warning"]]);
live.note(
`When the target offers a ${network} option, X402-06 settles a real payment and X402-07..10 send ` +
"payments it must refuse.",
);
}
if (opts["readOnly"] !== true && payerKey) {
const order = X402_PAYMENT_CHECK_IDS;
const startAt = (index: number): void => {
const id = order[index];
if (id !== undefined) live.running(id, catalogueEntry(id)?.name ?? id);
};
startAt(0);
results.push(
...(await runX402PaymentChecks({
target,
network,
payerSecretKey: payerKey,
...(opts["rpcUrl"] ? { rpcUrl: opts["rpcUrl"] as string } : {}),
...shape,
onResult: (result) => {
live.result(result);
const index = order.indexOf(result.id);
if (index >= 0) startAt(index + 1);
},
onProgress: (line) => live.progress(line),
})),
);
}

live.finish(results, endpointOutcome(results, "x402"), verdictNotes(results, "x402"));
return exitCodeFor(results, "x402");
}

program
.command("mpp-charge")
Expand Down Expand Up @@ -614,7 +714,7 @@ a real payment and moves testnet funds, because charge mode has no dry run.`,
...(opts.rpcUrl ? { rpcUrl: opts.rpcUrl } : {}),
});

process.exit(report(results, jsonMode));
process.exit(report(results, jsonMode, terminalStyle(jsonMode)));
});

registerWalletCommand(program);
Expand Down
Loading