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
17 changes: 17 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,23 @@ jobs:
- name: Test @wasit-dev/cli
run: npm run test -w packages/cli

# The MCP server's own tests start the built server over stdio, the way
# an MCP client does, and call its tools with a network that is not a
# test network: nothing may be paid. Offline: the target and the RPC
# endpoint are local listeners on 127.0.0.1, and every key is generated
# in the test and holds nothing.
- name: Type-check @wasit-dev/server tests
run: npm run typecheck -w packages/server

- name: Test @wasit-dev/server
run: npm run test -w packages/server

# The Action's scripts and its action.yml, offline: the gh call is
# injected, and four cases run the built CLI against a service on
# 127.0.0.1. It needs the builds above.
- name: Test the Action
run: npm run test:action

# Everything above this line runs against the working tree, where
# npm has deduplicated one dependency graph across all three
# workspaces. That is not the tree an installer gets, so a green
Expand Down
125 changes: 125 additions & 0 deletions action/action.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
name: Wasit
description: >-
Runs Wasit's read-only x402 challenge checks against your service inside the
job, comments the result on the pull request, and compares it with main.
Linux runners. Needs Node 22 or later (add actions/setup-node before this
step). The payment tier is not available in this version.

inputs:
config:
description: Path of the wasit.config.json to run, relative to the working directory.
required: false
default: wasit.config.json
environment:
description: The environment of the config to run. Default is the config's defaultEnvironment, else its only environment.
required: false
default: ""
tier:
description: >-
read-only runs the unpaid challenge checks (X402-01 to X402-05): they send
no payment and sign nothing. payment is not available in this version and
is refused.
required: false
default: read-only
endpoints:
description: Names of the endpoints to run, separated by commas or line breaks. Default is every endpoint of the config.
required: false
default: ""

runs:
using: composite
steps:
# Each step gets only what it needs, as env. No input and no event value is
# written into a run block: they reach the scripts as environment variables.
# The token (GH_TOKEN) is given to the two steps that call gh and to no other,
# and never to the step that starts the service.

- name: Check the runner
shell: bash
run: |
if [ "$RUNNER_OS" != "Linux" ]; then
echo "Wasit: this action runs on Linux runners in this version." >&2
exit 2
fi
if ! command -v node >/dev/null 2>&1; then
echo "Wasit: Node 22 or later is needed and node was not found. Add actions/setup-node with node-version: 22 before this step." >&2
exit 2
fi
major="$(node -p 'process.versions.node.split(".")[0]')"
if [ "$major" -lt 22 ]; then
echo "Wasit: Node 22 or later is needed and this runner has Node $major. Add actions/setup-node with node-version: 22 before this step." >&2
exit 2
fi

- name: Check the inputs
shell: bash
env:
ACTION_PATH: ${{ github.action_path }}
INPUT_CONFIG: ${{ inputs.config }}
INPUT_ENVIRONMENT: ${{ inputs.environment }}
INPUT_TIER: ${{ inputs.tier }}
INPUT_ENDPOINTS: ${{ inputs.endpoints }}
run: node "$ACTION_PATH/scripts/wasit.mjs" check

# Wasit is built from the ref this action was fetched at, with the lockfile
# of that ref: one pin covers the action and the CLI.
- name: Install Wasit
shell: bash
env:
ACTION_PATH: ${{ github.action_path }}
run: |
cd "$ACTION_PATH/.."
npm ci --ignore-scripts --no-audit --no-fund
npm run build -w packages/core
npm run build -w packages/cli
npm run build -w packages/server

- name: Find the baseline
id: baseline
shell: bash
env:
ACTION_PATH: ${{ github.action_path }}
GH_TOKEN: ${{ github.token }}
run: node "$ACTION_PATH/scripts/baseline.mjs"

# The job's result is the exit code of this step. It has no condition and no
# continue-on-error, and it is not given the token.
- name: Run Wasit
id: run
shell: bash
env:
ACTION_PATH: ${{ github.action_path }}
INPUT_CONFIG: ${{ inputs.config }}
INPUT_ENVIRONMENT: ${{ inputs.environment }}
INPUT_TIER: ${{ inputs.tier }}
INPUT_ENDPOINTS: ${{ inputs.endpoints }}
BASELINE_PATH: ${{ steps.baseline.outputs.path }}
WASIT_BUILD_COMMIT: ${{ github.action_ref }}
run: node "$ACTION_PATH/scripts/wasit.mjs" run

- name: Write the report
if: ${{ always() && steps.run.conclusion != 'skipped' }}
shell: bash
env:
ACTION_PATH: ${{ github.action_path }}
BASELINE_PATH: ${{ steps.baseline.outputs.path }}
WASIT_BUILD_COMMIT: ${{ github.action_ref }}
run: node "$ACTION_PATH/scripts/wasit.mjs" report

- name: Comment on the pull request
if: ${{ always() && steps.run.conclusion != 'skipped' && github.event_name == 'pull_request' }}
shell: bash
env:
ACTION_PATH: ${{ github.action_path }}
GH_TOKEN: ${{ github.token }}
WASIT_COMMENT_FILE: ${{ runner.temp }}/wasit/comment.md
run: node "$ACTION_PATH/scripts/comment.mjs"

# Pinned to the commit of v4.6.2 (read from the GitHub API on 2026-11-15).
- name: Upload the baseline
if: ${{ always() && steps.run.conclusion != 'skipped' && github.event_name == 'push' && github.ref == format('refs/heads/{0}', github.event.repository.default_branch) }}
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
with:
name: wasit-baseline
path: ${{ runner.temp }}/wasit/baseline-next.json
if-no-files-found: warn
50 changes: 50 additions & 0 deletions action/examples/wasit.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Wasit on every pull request and every push to main.
#
# What this does: starts your x402 service inside the job (service.start in
# wasit.config.json), runs Wasit's read-only challenge checks against it,
# comments the result on the pull request, and compares it with the last run on
# main. The job named Wasit is the check on the pull request.
#
# Replace <tag-or-commit-sha> below with a release tag or a full commit SHA of
# the Wasit repository. Do not use a branch name.
#
# Wasit needs Node 22 or later and does not install it: keep the setup-node step.
#
# A header your service needs to issue a challenge: set it with WASIT_HEADER_<NAME>
# in the env: of the Wasit step, from a secret, for example
# env:
# WASIT_HEADER_X_API_KEY: ${{ secrets.X_API_KEY }}
# The service Wasit starts is not given that variable, and neither is it given
# the key variables or WASIT_RPC_URL. Never put a key in wasit.config.json.
#
# Do not use pull_request_target. It would give the code of a pull request the
# token and the secrets of your repository.

name: Wasit

on:
pull_request:
push:
branches: [main]

permissions:
contents: read
pull-requests: write
actions: read

jobs:
wasit:
name: Wasit
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0
with:
persist-credentials: false

- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
with:
node-version: 22

- uses: wasit-dev/wasit/action@<tag-or-commit-sha>
with:
config: wasit.config.json
161 changes: 161 additions & 0 deletions action/scripts/baseline.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/**
* Choosing the baseline for a run (spec A5, A8 #4, A-A05).
*
* The RUN is chosen first: the latest successful `push` run of this workflow on
* the default branch, from this repository. Only then is that run's
* `wasit-baseline` artifact downloaded, by run id. Never "the newest artifact
* with that name": a pull request run (a fork's too, which runs the fork's copy
* of the workflow file) can upload an artifact with that name, and a fork can
* have a branch called main.
*
* Whether the file is a report, and whether it may be compared, is the CLI's to
* say (core `readBaseline`); this script only picks and downloads. It never fails
* the job: no baseline is a state the comment already explains.
*/

import { mkdir, readdir } from "node:fs/promises";
import { appendFile, readFileSync } from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";

import { REPOSITORY, api, oneLine, positiveInteger } from "./common.mjs";
import { realGh } from "./gh.mjs";

/** The name the baseline is uploaded under. */
export const BASELINE_ARTIFACT = "wasit-baseline";

/**
* Which finished runs may be a baseline. Only 'success': a run that failed or
* was cancelled is not the state of main to compare with.
*/
export const ACCEPTED_CONCLUSIONS = Object.freeze(["success"]);

const sameName = (a, b) => typeof a === "string" && typeof b === "string" && a.toLowerCase() === b.toLowerCase();

/**
* The run to take the baseline from, out of the runs the API listed.
*
* @param {unknown[] | undefined} runs
* @param {{ repository: string, defaultBranch: string, workflowId: number, currentRunId: number }} context
*/
export function selectBaselineRun(runs, context) {
const eligible = (Array.isArray(runs) ? runs : []).filter(
(run) =>
run !== null &&
typeof run === "object" &&
Number.isSafeInteger(run.id) &&
run.id !== context.currentRunId &&
run.event === "push" &&
run.head_branch === context.defaultBranch &&
run.status === "completed" &&
ACCEPTED_CONCLUSIONS.includes(run.conclusion) &&
run.workflow_id === context.workflowId &&
sameName(run.head_repository?.full_name, context.repository) &&
sameName(run.repository?.full_name, context.repository),
);
const time = (run) => Date.parse(run.created_at) || 0;
return eligible.sort((a, b) => time(b) - time(a) || b.id - a.id)[0];
}

/**
* Finds and downloads the baseline.
*
* @param {{ gh: Function, repository: string, runId: number | string, directory: string, defaultBranch?: string, log?: (line: string) => void }} options
* @returns {Promise<{ path?: string }>} the downloaded file, if there is one
*/
export async function findBaseline({ gh, repository, runId, directory, defaultBranch, log = console.log }) {
const none = (reason) => {
log(`Wasit: no baseline (${reason}). The comment will say there is nothing to compare with.`);
return {};
};

const currentRunId = positiveInteger(runId);
if (typeof repository !== "string" || !REPOSITORY.test(repository) || currentRunId === undefined) {
return none("the repository or the run id is not what a workflow gives");
}

try {
const branch = defaultBranch ?? (await api(gh, `repos/${repository}`)).default_branch;
if (typeof branch !== "string" || !/^[A-Za-z0-9._/-]{1,200}$/.test(branch)) return none("the default branch is unknown");

const workflowId = positiveInteger((await api(gh, `repos/${repository}/actions/runs/${currentRunId}`)).workflow_id);
if (workflowId === undefined) return none("this run does not name its workflow");

// `status=success` keeps the newest successful runs on the first page of a busy repository.
const conclusion = ACCEPTED_CONCLUSIONS.length === 1 ? `&status=${ACCEPTED_CONCLUSIONS[0]}` : "";
const listing = await api(
gh,
`repos/${repository}/actions/workflows/${workflowId}/runs?branch=${encodeURIComponent(branch)}&event=push${conclusion}&per_page=50`,
);
const chosen = selectBaselineRun(listing.workflow_runs, { repository, defaultBranch: branch, workflowId, currentRunId });
if (chosen === undefined) return none(`no successful push run of this workflow on ${oneLine(branch, 60)} yet`);

const artifacts = await api(gh, `repos/${repository}/actions/runs/${chosen.id}/artifacts?per_page=100&name=${BASELINE_ARTIFACT}`);
const found = (Array.isArray(artifacts.artifacts) ? artifacts.artifacts : [])
.filter(
(artifact) =>
artifact?.name === BASELINE_ARTIFACT &&
artifact.expired !== true &&
(artifact.workflow_run?.id === undefined || artifact.workflow_run.id === chosen.id),
)
.sort((a, b) => (Date.parse(b.created_at) || 0) - (Date.parse(a.created_at) || 0))[0];
if (found === undefined) return none(`run ${chosen.id} has no ${BASELINE_ARTIFACT} artifact, or it has expired`);

await mkdir(directory, { recursive: true });
const download = await gh(["run", "download", String(chosen.id), "--repo", repository, "--name", BASELINE_ARTIFACT, "--dir", directory]);
if (download.code !== 0) return none(`the download failed: ${oneLine(download.stderr)}`);

const files = (await readdir(directory)).filter((name) => name.endsWith(".json")).sort();
if (files.length === 0) return none("the artifact held no JSON file");
log(`Wasit: baseline from run ${chosen.id} on ${oneLine(branch, 60)}.`);
return { path: path.join(directory, files[0]) };
} catch (error) {
return none(oneLine(error instanceof Error ? error.message : error));
}
}

/**
* The step: reads the workflow's environment, finds the baseline, writes
* `path=<file>` (empty when there is none) to the step output. Always exits 0.
*
* @param {Record<string, string | undefined>} env
* @param {{ gh?: Function, log?: (line: string) => void }} deps
*/
export async function main(env = process.env, deps = {}) {
const log = deps.log ?? ((line) => console.log(line));
let result = {};
try {
const gh = deps.gh ?? realGh(env);
let defaultBranch;
try {
const event = JSON.parse(readFileSync(env["GITHUB_EVENT_PATH"] ?? "", "utf-8"));
if (typeof event?.repository?.default_branch === "string") defaultBranch = event.repository.default_branch;
} catch {
// The event file may be absent or have no repository (a schedule): findBaseline asks the API.
}
const temp = env["RUNNER_TEMP"];
if (typeof temp !== "string" || !path.isAbsolute(temp)) {
log("Wasit: no baseline (RUNNER_TEMP is not set).");
} else {
result = await findBaseline({
gh,
repository: env["GITHUB_REPOSITORY"],
runId: env["GITHUB_RUN_ID"],
directory: path.join(temp, "wasit", "baseline"),
...(defaultBranch === undefined ? {} : { defaultBranch }),
log,
});
}
} catch (error) {
log(`Wasit: no baseline (${oneLine(error instanceof Error ? error.message : error)}).`);
}
const output = env["GITHUB_OUTPUT"];
if (typeof output === "string" && output !== "") {
await new Promise((resolve) => appendFile(output, `path=${result.path ?? ""}\n`, () => resolve(undefined)));
}
return 0;
}

if (process.argv[1] !== undefined && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
process.exitCode = await main(process.env);
}
Loading
Loading