OpenAI's Codex Security CLI and TypeScript SDK for finding, validating, and fixing security vulnerabilities. npm: https://www.npmjs.com/package/@openai/codex-security
TypeScript ai-securityapplication-securityclicode-scanningcodexcodex-securitycybersecuritydevsecopsnodejsnpmopenaisdksecuritytypescriptvulnerability-scanning
feat(examples): add Invoice Desk fixture and OpenAI PR scans (#1144)
mldangelo-oai619d389c7ffe
diff --git a/.github/actionlint.yaml b/.github/actionlint.yamlindex 87bd73c14..eee1bdd57 100644--- a/.github/actionlint.yaml+++ b/.github/actionlint.yaml@@ -4,3 +4,8 @@ paths:# actionlint 1.7.12 predates GitHub's queue: max support. Keep release queuing.# https://docs.github.com/en/actions/how-tos/write-workflows/choose-when-workflows-run/control-workflow-concurrency- '^unexpected key "queue" for "concurrency" section\.'+ .github/workflows/invoice-desk-scan.yml:+ ignore:+ # actionlint 1.7.12 predates GitHub's job-level cache permissions.+ # https://docs.github.com/en/actions/reference/workflows-and-actions/workflow-syntax#jobsjob_idcache-mode+ - '^unexpected key "cache-mode" for "job" section\.'diff --git a/.github/scripts/invoice-desk-source.mjs b/.github/scripts/invoice-desk-source.mjsnew file mode 100644index 000000000..787d6b405--- /dev/null+++ b/.github/scripts/invoice-desk-source.mjs@@ -0,0 +1,56 @@+import { execFileSync } from "node:child_process";+import { closeSync, mkdirSync, openSync } from "node:fs";+import { dirname, resolve, sep } from "node:path";+import { pathToFileURL } from "node:url";++export function extractApplication(repository, sha, destination) {+ const git = (args) =>+ execFileSync("git", args, { cwd: repository, maxBuffer: Infinity });+ // Read committed blobs directly: export-ignore and export-subst must not alter scan input.+ const entries = new TextDecoder("utf-8", { fatal: true })+ .decode(git(["ls-tree", "-rz", `${sha}:examples/invoice-desk/app`]))+ .split("\0")+ .filter(Boolean)+ .map((entry) => {+ const tab = entry.indexOf("\t");+ const [mode, type, oid] = entry.slice(0, tab).split(" ");+ const path = entry.slice(tab + 1);+ const output = resolve(destination, path);+ if (!["100644", "100755"].includes(mode) || type !== "blob") {+ throw new Error(+ "The application source must contain only regular files.",+ );+ }+ if (!output.startsWith(resolve(destination) + sep)) {+ throw new Error("The application source contains an unsafe path.");+ }+ return { oid, output };+ });+ if (entries.length === 0) throw new Error("The application source is empty.");+ mkdirSync(destination);+ for (const { oid, output } of entries) {+ mkdirSync(dirname(output), { recursive: true });+ const descriptor = openSync(output, "w");+ try {+ execFileSync("git", ["cat-file", "blob", oid], {+ cwd: repository,+ stdio: ["ignore", descriptor, "pipe"],+ });+ } finally {+ closeSync(descriptor);+ }+ }+ return entries.length;+}++if (+ process.argv[1] &&+ import.meta.url === pathToFileURL(process.argv[1]).href+) {+ const count = extractApplication(+ process.env.SOURCE_REPOSITORY,+ process.env.SOURCE_SHA,+ process.env.SCAN_SOURCE,+ );+ console.log(`Extracted ${count} committed application files.`);+}diff --git a/.github/scripts/invoice-desk-source.test.mjs b/.github/scripts/invoice-desk-source.test.mjsnew file mode 100644index 000000000..cbfbf0012--- /dev/null+++ b/.github/scripts/invoice-desk-source.test.mjs@@ -0,0 +1,110 @@+import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";+import {+ mkdtempSync,+ mkdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+ existsSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { extractApplication } from "./invoice-desk-source.mjs";++function fixture(t) {+ const root = mkdtempSync(join(tmpdir(), "invoice-desk-source-"));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ const repository = join(root, "repository");+ const app = join(repository, "examples/invoice-desk/app");+ mkdirSync(app, { recursive: true });+ const git = (...args) =>+ execFileSync("git", args, { cwd: repository, encoding: "utf8" }).trim();+ git("init", "--quiet");+ writeFileSync(+ join(app, "server.mjs"),+ 'export const version = "$Format:%H$";\n',+ );+ writeFileSync(+ join(app, ".gitattributes"),+ "server.mjs export-ignore export-subst\n",+ );+ writeFileSync(+ join(repository, "examples/invoice-desk/README.md"),+ "Sample metadata\n",+ );+ git("add", ".");+ return { root, repository, app, git, destination: join(root, "source") };+}++test("extracts exact blobs despite archive attributes and dirty checkout files", (t) => {+ const { repository, app, git, destination } = fixture(t);+ const tree = git("write-tree");+ writeFileSync(join(app, "server.mjs"), "changed working tree\n");+ assert.equal(extractApplication(repository, tree, destination), 2);+ assert.equal(+ readFileSync(join(destination, "server.mjs"), "utf8"),+ 'export const version = "$Format:%H$";\n',+ );+ assert.equal(existsSync(join(destination, "README.md")), false);+});++test("rejects links instead of following or silently omitting them", (t) => {+ const { repository, app, git, destination } = fixture(t);+ writeFileSync(join(app, "link"), "../../outside\n");+ const oid = git("hash-object", "-w", "examples/invoice-desk/app/link");+ git(+ "update-index",+ "--add",+ "--cacheinfo",+ `120000,${oid},examples/invoice-desk/app/link`,+ );+ assert.throws(+ () => extractApplication(repository, git("write-tree"), destination),+ /regular files/,+ );+ assert.equal(existsSync(destination), false);+});++test("missing application source is an error, not an empty clean scan", (t) => {+ const { repository, git, destination } = fixture(t);+ git("rm", "--cached", "-r", "examples/invoice-desk/app");+ assert.throws(() =>+ extractApplication(repository, git("write-tree"), destination),+ );+ assert.equal(existsSync(destination), false);+});++test("streams application assets larger than the child-process buffer", (t) => {+ const { repository, app, git, destination } = fixture(t);+ const bytes = Buffer.alloc(2 * 1024 * 1024, 0xa5);+ writeFileSync(join(app, "asset.bin"), bytes);+ git("add", ".");+ assert.equal(+ extractApplication(repository, git("write-tree"), destination),+ 3,+ );+ assert.deepEqual(readFileSync(join(destination, "asset.bin")), bytes);+});++test("rejects lossy filename decoding before any source files can collide", (t) => {+ const { repository, git, destination } = fixture(t);+ const oid = git("rev-parse", ":examples/invoice-desk/app/server.mjs");+ const prefix = `100644 ${oid}\texamples/invoice-desk/app/`;+ const index = Buffer.concat([+ Buffer.from(`${prefix}�.mjs\0`),+ Buffer.from(prefix),+ Buffer.from([0xff]),+ Buffer.from(".mjs\0"),+ ]);+ execFileSync("git", ["update-index", "-z", "--index-info"], {+ cwd: repository,+ input: index,+ });+ assert.throws(+ () => extractApplication(repository, git("write-tree"), destination),+ /encoded data/,+ );+ assert.equal(existsSync(destination), false);+});diff --git a/.github/scripts/invoice-desk-target.mjs b/.github/scripts/invoice-desk-target.mjsnew file mode 100644index 000000000..03d5e7683--- /dev/null+++ b/.github/scripts/invoice-desk-target.mjs@@ -0,0 +1,154 @@+import { execFileSync } from "node:child_process";+import { appendFileSync, readFileSync } from "node:fs";+import { pathToFileURL } from "node:url";++function eligible(pr, repository, sha) {+ return (+ pr.state === "open" &&+ pr.base.repo.full_name === repository &&+ pr.base.ref === "main" &&+ pr.head.sha === sha+ );+}++export async function resolveScanTargets(+ context,+ getPullRequest,+ pullRequestsForCommit,+ dispatchedScanTitles,+) {+ const { eventName, event, repository, sha, target } = context;+ // After approval, recheck this matrix entry rather than other PRs on the same commit.+ if (target) {+ if (target.pr === 0) return [{ pr: 0, sha }];+ const pr = await getPullRequest(String(target.pr));+ return eligible(pr, repository, target.sha)+ ? [{ pr: pr.number, sha: target.sha }]+ : [];+ }+ if (eventName === "workflow_run") {+ const run = event.workflow_run;+ if (run.event !== "pull_request" || run.conclusion === "cancelled")+ return [];+ // GitHub can suppress target events for automated PRs and some branch names.+ const requests = await pullRequestsForCommit(run.head_sha);+ const numbers = new Set(run.pull_requests.map((pr) => pr.number));+ const candidates = requests.filter(+ (pr) =>+ eligible(pr, repository, run.head_sha) &&+ (numbers.size === 0 || numbers.has(pr.number)),+ );+ if (candidates.length === 0) return [];+ const dispatched = new Set(await dispatchedScanTitles(sha));+ return candidates+ .filter(+ (pr) =>+ !dispatched.has(+ `Invoice Desk scan — PR #${pr.number} @ ${pr.head.sha}`,+ ),+ )+ .map((pr) => ({ pr: pr.number, sha: pr.head.sha }));+ }+ if (eventName !== "workflow_dispatch") return [];+ const { pr_number: number = "", source_sha: sourceSha = "" } =+ event.inputs ?? {};+ if (!number && !sourceSha) return [{ pr: 0, sha }];+ if (!/^[1-9][0-9]*$/.test(number) || !/^[a-f0-9]{40}$/.test(sourceSha)) {+ throw new Error(+ "PR scans require both a positive pr_number and a full source_sha.",+ );+ }++ const pr = await getPullRequest(number);+ if (!eligible(pr, repository, sourceSha)) return [];+ return [{ pr: pr.number, sha: sourceSha }];+}++if (+ process.argv[1] &&+ import.meta.url === pathToFileURL(process.argv[1]).href+) {+ const repository = process.env.GITHUB_REPOSITORY;+ const targets = await resolveScanTargets(+ {+ eventName: process.env.GITHUB_EVENT_NAME,+ event: JSON.parse(readFileSync(process.env.GITHUB_EVENT_PATH, "utf8")),+ repository,+ sha: process.env.GITHUB_SHA,+ target:+ process.env.PR_NUMBER === undefined+ ? undefined+ : {+ pr: Number(process.env.PR_NUMBER),+ sha: process.env.SOURCE_SHA,+ },+ },+ (number) =>+ JSON.parse(+ execFileSync("gh", ["api", `repos/${repository}/pulls/${number}`], {+ encoding: "utf8",+ }),+ ),+ (sha) =>+ JSON.parse(+ execFileSync(+ "gh",+ [+ "api",+ "--paginate",+ "--slurp",+ `repos/${repository}/commits/${sha}/pulls?per_page=100`,+ ],+ { encoding: "utf8" },+ ),+ ).flat(),+ (sha) =>+ JSON.parse(+ execFileSync(+ "gh",+ [+ "api",+ "--paginate",+ "--slurp",+ `repos/${repository}/actions/workflows/invoice-desk-scan.yml/runs?event=workflow_dispatch&branch=main&head_sha=${sha}&per_page=100`,+ ],+ { encoding: "utf8", maxBuffer: Infinity },+ ),+ ).flatMap((page) => page.workflow_runs.map((run) => run.display_title)),+ );+ const fallback = process.env.GITHUB_EVENT_NAME === "workflow_run";+ if (fallback) {+ for (const { pr, sha } of targets) {+ execFileSync("gh", [+ "workflow",+ "run",+ "invoice-desk-scan.yml",+ "--repo",+ repository,+ "--ref",+ "main",+ "-f",+ `pr_number=${pr}`,+ "-f",+ `source_sha=${sha}`,+ ]);+ }+ }+ appendFileSync(+ process.env.GITHUB_OUTPUT,+ `targets=${JSON.stringify(fallback ? [] : targets)}\n`,+ );+ const message =+ targets.length === 0+ ? "Skipped: no eligible PR revision needs a scan."+ : targets+ .map(+ ({ pr, sha }) =>+ `${fallback ? "Queued " : ""}${pr ? `PR #${pr}` : "Main baseline"} at ${sha}`,+ )+ .join("\n");+ console.log(message);+ if (process.env.GITHUB_STEP_SUMMARY) {+ appendFileSync(process.env.GITHUB_STEP_SUMMARY, message + "\n");+ }+}diff --git a/.github/scripts/invoice-desk-target.test.mjs b/.github/scripts/invoice-desk-target.test.mjsnew file mode 100644index 000000000..ad9fcf5f8--- /dev/null+++ b/.github/scripts/invoice-desk-target.test.mjs@@ -0,0 +1,296 @@+import assert from "node:assert/strict";+import { execFileSync } from "node:child_process";+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import test from "node:test";+import { fileURLToPath } from "node:url";+import { resolveScanTargets } from "./invoice-desk-target.mjs";++const repository = "example/invoices";+const sourceSha = "1".repeat(40);+const mainSha = "2".repeat(40);+const context = {+ eventName: "workflow_dispatch",+ repository,+ sha: mainSha,+ event: { inputs: { pr_number: "7", source_sha: sourceSha } },+};+function pullRequest(overrides = {}) {+ return {+ number: 7,+ state: "open",+ draft: false,+ base: { ref: "main", repo: { full_name: repository } },+ head: { sha: sourceSha, repo: { full_name: repository } },+ ...overrides,+ };+}++test("selects the requested PR head rather than the trusted workflow commit", async () => {+ assert.deepEqual(+ await resolveScanTargets(context, async (number) => {+ assert.equal(number, "7");+ return pullRequest();+ }),+ [{ pr: 7, sha: sourceSha }],+ );+});++test("includes fork and draft PRs without depending on a PR workflow run", async () => {+ assert.deepEqual(+ await resolveScanTargets(context, async () =>+ pullRequest({+ draft: true,+ head: { sha: sourceSha, repo: { full_name: "contributor/invoices" } },+ }),+ ),+ [{ pr: 7, sha: sourceSha }],+ );+});++test("rechecking after approval excludes closed, retargeted, and superseded PRs", async () => {+ assert.deepEqual(+ await resolveScanTargets(context, async () => pullRequest()),+ [{ pr: 7, sha: sourceSha }],+ );+ for (const changed of [+ { state: "closed" },+ { base: { ref: "release", repo: { full_name: repository } } },+ { base: { ref: "main", repo: { full_name: "other/invoices" } } },+ { head: { sha: "3".repeat(40) } },+ ]) {+ assert.deepEqual(+ await resolveScanTargets(context, async () => pullRequest(changed)),+ [],+ );+ }+});++test("manual baseline scans use the trusted workflow commit", async () => {+ assert.deepEqual(+ await resolveScanTargets({ ...context, event: { inputs: {} } }, () =>+ assert.fail("unexpected API call"),+ ),+ [{ pr: 0, sha: mainSha }],+ );+});++test("incomplete or invalid PR inputs fail instead of falling back to a baseline", async () => {+ for (const inputs of [+ { pr_number: "7" },+ { source_sha: sourceSha },+ { pr_number: "-1", source_sha: sourceSha },+ { pr_number: "7", source_sha: "main" },+ ]) {+ await assert.rejects(+ resolveScanTargets({ ...context, event: { inputs } }, () =>+ assert.fail("unexpected API call"),+ ),+ /require both/,+ );+ }+});++test("ignores unexpected events without querying GitHub", async () => {+ assert.deepEqual(+ await resolveScanTargets({ ...context, eventName: "pull_request" }, () =>+ assert.fail("unexpected API call"),+ ),+ [],+ );+});++const automationContext = {+ ...context,+ eventName: "workflow_run",+ event: {+ workflow_run: {+ event: "pull_request",+ actor: { login: "github-actions[bot]" },+ conclusion: "success",+ head_sha: sourceSha,+ pull_requests: [{ number: 7 }],+ },+ },+};++test("falls back to completed behavior runs for GITHUB_TOKEN-created PRs", async () => {+ for (const conclusion of ["success", "failure"]) {+ const run = structuredClone(automationContext);+ run.event.workflow_run.conclusion = conclusion;+ assert.deepEqual(+ await resolveScanTargets(+ run,+ () => assert.fail("unexpected direct lookup"),+ async (sha) => {+ assert.equal(sha, sourceSha);+ return [+ pullRequest(),+ pullRequest({ number: 8 }),+ pullRequest({ state: "closed" }),+ ];+ },+ async (sha) => {+ assert.equal(sha, mainSha);+ return [];+ },+ ),+ [{ pr: 7, sha: sourceSha }],+ );+ }+});++test("fallback rechecks current heads and handles empty association metadata", async () => {+ const run = structuredClone(automationContext);+ run.event.workflow_run.pull_requests = [];+ const lookup = async () => [+ pullRequest(),+ pullRequest({ head: { sha: mainSha } }),+ ];+ assert.deepEqual(+ await resolveScanTargets(run, null, lookup, async () => []),+ [{ pr: 7, sha: sourceSha }],+ );+ assert.deepEqual(+ await resolveScanTargets(run, null, async () => [+ pullRequest({ state: "closed" }),+ ]),+ [],+ );+});++test("target events and cancelled runs do not queue fallback scans", async () => {+ for (const changed of [+ { event: "pull_request_target" },+ { conclusion: "cancelled" },+ ]) {+ const run = structuredClone(automationContext);+ Object.assign(run.event.workflow_run, changed);+ assert.deepEqual(+ await resolveScanTargets(run, null, () =>+ assert.fail("unexpected association lookup"),+ ),+ [],+ );+ }+});++test("approval recheck stays bound to its matrix PR even when another PR shares the commit", async () => {+ const run = { ...automationContext, target: { pr: 7, sha: sourceSha } };+ assert.deepEqual(+ await resolveScanTargets(+ run,+ async (number) => {+ assert.equal(number, "7");+ return pullRequest({ state: "closed" });+ },+ () => assert.fail("must not select another associated PR"),+ ),+ [],+ );+ assert.deepEqual(await resolveScanTargets(run, async () => pullRequest()), [+ { pr: 7, sha: sourceSha },+ ]);+});++test("fallback covers human PRs when GitHub suppresses a target event", async () => {+ const run = structuredClone(automationContext);+ run.event.workflow_run.actor.login = "contributor";+ run.event.workflow_run.head_branch = sourceSha;+ assert.deepEqual(+ await resolveScanTargets(+ run,+ null,+ async () => [pullRequest()],+ async () => [],+ ),+ [{ pr: 7, sha: sourceSha }],+ );+});++test("fallback skips only the PR and head already dispatched from the same workflow revision", async () => {+ const run = structuredClone(automationContext);+ run.event.workflow_run.pull_requests = [];+ assert.deepEqual(+ await resolveScanTargets(+ run,+ null,+ async () => [pullRequest(), pullRequest({ number: 8 })],+ async (sha) => {+ assert.equal(sha, mainSha);+ return [+ `Invoice Desk scan — PR #7 @ ${sourceSha}`,+ `Invoice Desk scan — PR #8 @ ${mainSha}`,+ ];+ },+ ),+ [{ pr: 8, sha: sourceSha }],+ );+});++test("fallback CLI dispatches a keyed run once and leaves inference to that run", (t) => {+ const root = mkdtempSync(join(tmpdir(), "invoice-desk-dispatch-"));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ const statePath = join(root, "dispatches.json");+ const eventPath = join(root, "event.json");+ const outputPath = join(root, "output.txt");+ writeFileSync(statePath, "[]");+ writeFileSync(eventPath, JSON.stringify(automationContext.event));+ const scriptUrl = new URL("./invoice-desk-target.mjs", import.meta.url);+ const script = `+ import assert from "node:assert/strict";+ import childProcess from "node:child_process";+ import { readFileSync, writeFileSync } from "node:fs";+ import { syncBuiltinESMExports } from "node:module";+ const statePath = ${JSON.stringify(statePath)};+ const dispatches = JSON.parse(readFileSync(statePath, "utf8"));+ childProcess.execFileSync = (command, args) => {+ assert.equal(command, "gh");+ if (args[0] === "workflow") {+ assert.deepEqual(args, [+ "workflow", "run", "invoice-desk-scan.yml", "--repo", ${JSON.stringify(repository)},+ "--ref", "main", "-f", "pr_number=7", "-f", ${JSON.stringify(`source_sha=${sourceSha}`)}+ ]);+ dispatches.push(${JSON.stringify(`Invoice Desk scan — PR #7 @ ${sourceSha}`)});+ writeFileSync(statePath, JSON.stringify(dispatches));+ return "";+ }+ assert.equal(args[0], "api");+ const endpoint = args.at(-1);+ if (endpoint === ${JSON.stringify(`repos/${repository}/pulls/7`)})+ return JSON.stringify(${JSON.stringify(pullRequest())});+ if (endpoint === ${JSON.stringify(`repos/${repository}/commits/${sourceSha}/pulls?per_page=100`)})+ return JSON.stringify([[${JSON.stringify(pullRequest())}]]);+ assert.equal(endpoint, ${JSON.stringify(`repos/${repository}/actions/workflows/invoice-desk-scan.yml/runs?event=workflow_dispatch&branch=main&head_sha=${mainSha}&per_page=100`)});+ return JSON.stringify([{ workflow_runs: dispatches.map(display_title => ({ display_title })) }]);+ };+ syncBuiltinESMExports();+ process.argv[1] = ${JSON.stringify(fileURLToPath(scriptUrl))};+ await import(${JSON.stringify(scriptUrl.href)});+ `;+ const run = (eventName) =>+ execFileSync(process.execPath, ["--input-type=module", "--eval", script], {+ encoding: "utf8",+ env: {+ GITHUB_REPOSITORY: repository,+ GITHUB_SHA: mainSha,+ GITHUB_EVENT_NAME: eventName,+ GITHUB_EVENT_PATH: eventPath,+ GITHUB_OUTPUT: outputPath,+ },+ });+ assert.match(run("workflow_run"), /Queued PR #7/);+ assert.match(run("workflow_run"), /Skipped/);+ assert.deepEqual(JSON.parse(readFileSync(statePath, "utf8")), [+ `Invoice Desk scan — PR #7 @ ${sourceSha}`,+ ]);+ assert.equal(readFileSync(outputPath, "utf8"), "targets=[]\ntargets=[]\n");++ writeFileSync(eventPath, JSON.stringify(context.event));+ run("workflow_dispatch");+ assert.equal(+ readFileSync(outputPath, "utf8").trim().split("\n").at(-1),+ `targets=${JSON.stringify([{ pr: 7, sha: sourceSha }])}`,+ );+});diff --git a/.github/workflows/invoice-desk-scan.yml b/.github/workflows/invoice-desk-scan.ymlnew file mode 100644index 000000000..3196bf34a--- /dev/null+++ b/.github/workflows/invoice-desk-scan.yml@@ -0,0 +1,282 @@+name: Invoice Desk OpenAI scan+run-name: "Invoice Desk scan — ${{ inputs.pr_number && format('PR #{0} @ {1}', inputs.pr_number, inputs.source_sha) || (github.event_name == 'workflow_run' && 'PR fallback' || 'main baseline') }}"++on:+ workflow_run:+ workflows: ["Invoice Desk sample"]+ types: [completed]+ workflow_dispatch:+ inputs:+ pr_number:+ description: "PR number (leave both inputs empty for a main baseline)"+ type: string+ default: ""+ source_sha:+ description: "Exact PR head SHA, required with pr_number"+ type: string+ default: ""++permissions:+ contents: read++concurrency:+ group: invoice-desk-scan-${{ github.event_name == 'workflow_dispatch' && (inputs.pr_number && format('pr-{0}-{1}', inputs.pr_number, inputs.source_sha) || 'main') || format('fallback-{0}', github.run_id) }}+ cancel-in-progress: true++env:+ CODEX_SECURITY_VERSION: "0.1.30"++jobs:+ target:+ # Only a workflow on protected main can request the inference environment.+ if: >-+ github.ref == 'refs/heads/main' && github.ref_protected &&+ (github.event_name == 'workflow_dispatch' ||+ github.event.workflow_run.event == 'pull_request')+ runs-on: ubuntu-24.04+ # This job reads only trusted helpers and event metadata before caching public packages.+ cache-mode: write+ permissions:+ actions: write+ contents: read+ pull-requests: read+ outputs:+ targets: ${{ steps.target.outputs.targets }}+ cache-hit: ${{ steps.cache.outputs.cache-hit }}+ steps:+ - name: Check out trusted workflow helpers+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: ${{ github.sha }}+ persist-credentials: false+ - name: Set up Node.js+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: "24"+ package-manager-cache: false+ - name: Resolve the current pull request targeting main+ id: target+ env:+ GH_TOKEN: ${{ github.token }}+ run: node .github/scripts/invoice-desk-target.mjs++ # Populate only public package downloads, before any PR source or inference.+ - name: Restore CLI package download cache+ if: steps.target.outputs.targets != '[]'+ id: cache+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0+ with:+ path: ${{ runner.temp }}/invoice-desk-npm-cache/_cacache+ key: invoice-desk-npm-v1-${{ runner.os }}-${{ runner.arch }}-node24-cli${{ env.CODEX_SECURITY_VERSION }}+ - name: Populate CLI package download cache+ if: steps.target.outputs.targets != '[]' && steps.cache.outputs.cache-hit != 'true'+ working-directory: ${{ runner.temp }}+ run: |+ npm install --prefix "$RUNNER_TEMP/codex-security-cli" \+ --cache "$RUNNER_TEMP/invoice-desk-npm-cache" --prefer-offline \+ --ignore-scripts --no-audit --no-fund \+ --registry=https://registry.npmjs.org/ \+ "@openai/codex-security@$CODEX_SECURITY_VERSION"+ - name: Save CLI package download cache+ if: steps.target.outputs.targets != '[]' && steps.cache.outputs.cache-hit != 'true'+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0+ with:+ path: ${{ runner.temp }}/invoice-desk-npm-cache/_cacache+ key: invoice-desk-npm-v1-${{ runner.os }}-${{ runner.arch }}-node24-cli${{ env.CODEX_SECURITY_VERSION }}++ scan:+ name: "OpenAI source scan (${{ matrix.target.pr && format('PR #{0}', matrix.target.pr) || 'main' }})"+ needs: target+ if: needs.target.outputs.targets != '[]'+ strategy:+ fail-fast: false+ matrix:+ target: ${{ fromJSON(needs.target.outputs.targets) }}+ environment: invoice-desk-inference+ runs-on: ubuntu-24.04+ timeout-minutes: 60+ cache-mode: read+ permissions:+ contents: read+ pull-requests: read+ env:+ SOURCE_SHA: ${{ matrix.target.sha }}+ PR_NUMBER: ${{ matrix.target.pr }}++ steps:+ - name: Check out trusted workflow helpers+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: ${{ github.sha }}+ path: trusted-workflow+ persist-credentials: false+ - name: Set up Node.js+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: "24"+ package-manager-cache: false+ - name: Set up Python+ uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0+ with:+ python-version: "3.12"+ - name: Restore CLI package download cache+ id: cache+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0+ with:+ path: ${{ runner.temp }}/invoice-desk-npm-cache/_cacache+ key: invoice-desk-npm-v1-${{ runner.os }}-${{ runner.arch }}-node24-cli${{ env.CODEX_SECURITY_VERSION }}+ - name: Install Codex Security outside the checkout+ working-directory: ${{ runner.temp }}+ shell: bash+ run: |+ npm install --prefix "$RUNNER_TEMP/codex-security-cli" \+ --cache "$RUNNER_TEMP/invoice-desk-npm-cache" --prefer-offline \+ --ignore-scripts --no-audit --no-fund \+ --registry=https://registry.npmjs.org/ \+ "@openai/codex-security@$CODEX_SECURITY_VERSION"+ - name: Check out the exact source commit+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ ref: ${{ matrix.target.sha }}+ path: source+ persist-credentials: false+ - name: Extract committed application files without running PR code+ env:+ SOURCE_REPOSITORY: ${{ github.workspace }}/source+ SCAN_SOURCE: ${{ runner.temp }}/invoice-desk+ run: node trusted-workflow/.github/scripts/invoice-desk-source.mjs++ - name: Recheck PR eligibility after environment approval+ id: recheck+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ node trusted-workflow/.github/scripts/invoice-desk-target.mjs+ # The scanner can read outside its target; remove the guide and answer key.+ rm -rf -- "$GITHUB_WORKSPACE/source" "$GITHUB_WORKSPACE/trusted-workflow"+ - name: Scan with OpenAI inference+ id: scan+ if: steps.recheck.outputs.targets != '[]'+ working-directory: ${{ runner.temp }}/invoice-desk+ shell: bash+ env:+ OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}+ CODEX_SECURITY_STATE_DIR: ${{ runner.temp }}/invoice-desk-state+ run: |+ if [[ -z "$OPENAI_API_KEY" ]]; then+ echo "::error::Configure OPENAI_API_KEY in the protected invoice-desk-inference environment."+ echo "exit-code=2" >> "$GITHUB_OUTPUT"+ echo "elapsed-seconds=0" >> "$GITHUB_OUTPUT"+ exit 2+ fi+ started_at=$SECONDS+ scan_status=0+ "$RUNNER_TEMP/codex-security-cli/node_modules/.bin/codex-security" scan . \+ --provider openai --auth api-key \+ --model gpt-5.6-sol --effort high --mode standard \+ --headless --format json \+ --output-dir "$RUNNER_TEMP/invoice-desk-scan" \+ > "$RUNNER_TEMP/invoice-desk-result.json" || scan_status=$?+ echo "exit-code=$scan_status" >> "$GITHUB_OUTPUT"+ echo "elapsed-seconds=$((SECONDS - started_at))" >> "$GITHUB_OUTPUT"+ exit "$scan_status"++ - name: Export completed findings as SARIF+ if: ${{ !cancelled() && steps.scan.outputs.exit-code == '0' }}+ shell: bash+ env:+ CODEX_SECURITY_STATE_DIR: ${{ runner.temp }}/invoice-desk-state+ run: |+ "$RUNNER_TEMP/codex-security-cli/node_modules/.bin/codex-security" export "$RUNNER_TEMP/invoice-desk-scan" \+ --export-format sarif \+ --source-root "$RUNNER_TEMP/invoice-desk" \+ --output "$RUNNER_TEMP/invoice-desk.sarif"++ - name: Summarize and measure the scan+ if: ${{ !cancelled() && steps.scan.outputs.exit-code != '' }}+ shell: bash+ env:+ SCAN_EXIT_CODE: ${{ steps.scan.outputs.exit-code }}+ SCAN_ELAPSED_SECONDS: ${{ steps.scan.outputs.elapsed-seconds }}+ PREVIOUS_CACHE_HIT: ${{ needs.target.outputs.cache-hit }}+ SCAN_CACHE_HIT: ${{ steps.cache.outputs.cache-hit }}+ run: |+ python3 - <<'PYTHON'+ from collections import Counter+ import json+ import os+ from pathlib import Path++ root = Path(os.environ["RUNNER_TEMP"])+ completed = os.environ["SCAN_EXIT_CODE"] == "0"+ counts, coverage, total, usage, cost_range = {}, None, None, None, None+ result = {}+ result_path = root / "invoice-desk-result.json"+ if result_path.is_file() and result_path.stat().st_size:+ try:+ result = json.loads(result_path.read_text())+ except json.JSONDecodeError:+ if completed:+ raise+ raw_usage = (result.get("turn") or {}).get("usage")+ if raw_usage is not None:+ usage = {key: raw_usage.get(key) for key in (+ "input_tokens", "cached_input_tokens", "cache_write_input_tokens",+ "cache_write_input_tokens_reported", "output_tokens"+ )}+ cost_range = (result.get("cost") or {}).get("estimatedUsdRange")+ coverage = (result.get("coverage") or {}).get("completeness")+ if completed:+ findings = json.loads((root / "invoice-desk-scan/findings.json").read_text())["findings"]+ coverage = json.loads((root / "invoice-desk-scan/coverage.json").read_text())["completeness"]+ counts = Counter(finding["severity"]["level"] for finding in findings)+ total = len(findings)+ metrics = {+ "schemaVersion": 1,+ "sourceSha": os.environ["SOURCE_SHA"],+ "workflowSha": os.environ["GITHUB_SHA"],+ "pullRequest": int(os.environ["PR_NUMBER"]) or None,+ "cliVersion": os.environ["CODEX_SECURITY_VERSION"],+ "model": "gpt-5.6-sol", "mode": "standard", "effort": "high",+ "exitCode": int(os.environ["SCAN_EXIT_CODE"]),+ "completed": completed,+ "elapsedSeconds": int(os.environ["SCAN_ELAPSED_SECONDS"]),+ "packageCacheReusedFromPreviousRun": os.environ["PREVIOUS_CACHE_HIT"] == "true",+ "packageCacheRestoredForScan": os.environ["SCAN_CACHE_HIT"] == "true",+ "findings": total, "findingsBySeverity": dict(counts),+ "coverage": coverage, "tokenUsage": usage, "estimatedUsdRange": cost_range,+ "seedRecall": None,+ }+ (root / "invoice-desk-metrics.json").write_text(json.dumps(metrics, indent=2) + "\n")+ with Path(os.environ["GITHUB_STEP_SUMMARY"]).open("a") as summary:+ summary.write("## Invoice Desk security scan\n\n")+ summary.write("Source commit: `" + metrics["sourceSha"] + "`.\n\n")+ if metrics["pullRequest"]:+ summary.write(f"Pull request: #{metrics['pullRequest']}.\n\n")+ summary.write(f"Scan elapsed: **{metrics['elapsedSeconds']} seconds**. Package cache reused from an earlier run: **{metrics['packageCacheReusedFromPreviousRun']}**.\n\n")+ if not completed:+ summary.write("The scan did not complete. Check the scan step and any saved reports; this is not a clean security result.\n")+ else:+ summary.write(f"Reported findings: **{total}**. Coverage: **{coverage}**.\n\n")+ summary.write("| Severity | Count |\n| --- | --- |\n")+ for severity in ("critical", "high", "medium", "low", "informational"):+ summary.write(f"| {severity} | {counts[severity]} |\n")+ summary.write("\nDownload the report and metrics artifacts to compare distinct root causes with the ten seeded cases. Extra reports and duplicates need review; raw counts do not measure recall.\n")+ summary.write("\nScanner: @openai/codex-security@" + metrics["cliVersion"] + "; OpenAI gpt-5.6-sol; standard mode; high effort.\n")+ PYTHON++ - name: Save reports and metrics+ if: ${{ !cancelled() && steps.scan.outputs.exit-code != '' }}+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1+ with:+ name: invoice-desk-scan-${{ matrix.target.pr || 'main' }}-${{ github.run_id }}-${{ github.run_attempt }}+ retention-days: 7+ if-no-files-found: warn+ path: |+ ${{ runner.temp }}/invoice-desk-result.json+ ${{ runner.temp }}/invoice-desk-metrics.json+ ${{ runner.temp }}/invoice-desk.sarif+ ${{ runner.temp }}/invoice-desk-scan/report.md+ ${{ runner.temp }}/invoice-desk-scan/scan-manifest.json+ ${{ runner.temp }}/invoice-desk-scan/coverage.json+ ${{ runner.temp }}/invoice-desk-scan/findings.jsondiff --git a/.github/workflows/invoice-desk.yml b/.github/workflows/invoice-desk.ymlnew file mode 100644index 000000000..4e8b9863c--- /dev/null+++ b/.github/workflows/invoice-desk.yml@@ -0,0 +1,54 @@+name: Invoice Desk sample++on:+ pull_request:+ branches: [main]+ types: [opened, reopened, synchronize, edited]+ pull_request_target:+ branches: [main]+ types: [opened, reopened, synchronize, edited]++permissions:+ contents: read++jobs:+ request-scan:+ # The default-branch dispatcher handles only event metadata, never PR code.+ if: >-+ github.event_name == 'pull_request_target' &&+ github.ref == 'refs/heads/main' && github.ref_protected &&+ (github.event.action != 'edited' || github.event.changes.base != null)+ runs-on: ubuntu-24.04+ concurrency:+ group: invoice-desk-request-${{ github.event.pull_request.number }}+ cancel-in-progress: true+ permissions:+ actions: write+ steps:+ - name: Queue the protected scan workflow on main+ env:+ GH_TOKEN: ${{ github.token }}+ PR_NUMBER: ${{ github.event.pull_request.number }}+ SOURCE_SHA: ${{ github.event.pull_request.head.sha }}+ run: |+ gh workflow run invoice-desk-scan.yml --repo "$GITHUB_REPOSITORY" \+ --ref main -f "pr_number=$PR_NUMBER" -f "source_sha=$SOURCE_SHA"++ behavior:+ if: github.event_name == 'pull_request'+ runs-on: ubuntu-latest+ concurrency:+ group: invoice-desk-behavior-${{ github.event.pull_request.number }}-${{ matrix.node }}+ cancel-in-progress: true+ strategy:+ matrix:+ node: ["22.13.0", "24"]+ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1+ with:+ persist-credentials: false+ - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: ${{ matrix.node }}+ - name: Check application behavior and scan orchestration+ run: node --test examples/invoice-desk/qa/app.test.mjs .github/scripts/invoice-desk-*.test.mjsdiff --git a/.github/zizmor.yml b/.github/zizmor.ymlindex 2787b577c..37c764767 100644--- a/.github/zizmor.yml+++ b/.github/zizmor.yml@@ -5,3 +5,8 @@ rules:- node-release-labels.yml:3# Requires successful push CI on main and verifies commit ancestry before tagging.- node-release-cut.yml:3+ # The protected-main dispatcher reads event metadata and never checks out PR code.+ - invoice-desk.yml:3+ # The fallback runs trusted helpers on protected main and only dispatches a scan.+ # Inference requires environment approval and treats extracted PR source as data.+ - invoice-desk-scan.yml:4diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 92b6b92f0..6738af3d3 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -71,9 +71,9 @@ SHELLCHECK_OPTS=--severity=warning actionlintzizmor --offline --strict-collection --min-severity medium --config .github/zizmor.yml .github```-The actionlint configuration preserves GitHub's supported release queue syntax-until the linter supports it. The zizmor configuration records the two existing-privileged triggers and why they do not execute pull request code. Review these+The actionlint configuration preserves GitHub's supported release queue and+job-level cache syntax until the linter supports them. The zizmor configuration+records reviewed privileged triggers and their trust boundaries. Review theseexceptions when changing the affected workflows.CI package builds and npm release validation require the production dependencydiff --git a/examples/README.md b/examples/README.mdindex afd700875..0709ef772 100644--- a/examples/README.md+++ b/examples/README.md@@ -22,6 +22,13 @@ Examples and templates for using Codex Security:validation script against a deliberately vulnerable API using synthetic data.Follow the demo's setup instructions, and do not deploy the example app.+- [Invoice Desk sample](invoice-desk/README.md): a Node.js invoice app with ten+ seeded finding scenarios, synthetic data, and no dependencies or external+ services. Its [CI workflow](invoice-desk/README.md#ci-and-openai-scans) runs+ behavior tests on PRs to `main` and queues OpenAI scans with environment+ approval. Sample guides and expected findings stay outside the scan input.+ Results include finding metrics and downloadable reports.+- [Azure Pipelines with Amazon Bedrock](azure-pipelines/README.md): centrally runmanual full or committed-diff scans against Azure Repos, with OIDC credentials,report artifacts, and optional native SARIF publishing.diff --git a/examples/github-actions/README.md b/examples/github-actions/README.mdindex ff19f0ce7..9a7528650 100644--- a/examples/github-actions/README.md+++ b/examples/github-actions/README.md@@ -92,3 +92,21 @@ is installed outside the checkout before checkout; AWS credentials are scopedto the scan step, and no `GH_TOKEN` or `GITHUB_TOKEN` is passed to the scanner.Keep any additional scanner configuration maintainer-controlled. Only scan codeyou are authorized to submit to the configured inference provider.++## OpenAI inference on a sample application++The repository's [Invoice Desk workflow](../../.github/workflows/invoice-desk.yml)+adapts this example to `--provider openai --auth api-key` using an+`OPENAI_API_KEY` secret in a protected GitHub environment. Pull requests to+`main` run behavior tests without inference credentials. A trusted dispatcher+handles only PR metadata and starts a separate+[scan workflow](../../.github/workflows/invoice-desk-scan.yml) on protected `main`.+It scans each PR's application source, including forks and drafts, after+environment approval. The Actions summary shows the PR number, source commit,+finding counts, coverage, elapsed time, and package-cache reuse. Reports, metrics+JSON, and SARIF are saved as artifacts.+Only public CLI package downloads are cached; analysis and authentication state+are fresh for each scan. Manual baseline scans remain available. The scan does+not create a PR status check, upload the sample's intentional vulnerabilities to+Code Scanning, or post PR comments.+See the [setup and reporting guide](../invoice-desk/README.md#ci-and-openai-scans).diff --git a/examples/invoice-desk/README.md b/examples/invoice-desk/README.mdnew file mode 100644index 000000000..9af97a852--- /dev/null+++ b/examples/invoice-desk/README.md@@ -0,0 +1,210 @@+# Invoice Desk security sample++This is a deliberately insecure, self-contained application for Codex Security+QA. All people, workspaces, invoices, and credentials are synthetic. Run it only+locally; do not deploy it or supply real data or credentials.++The application has **ten seeded finding scenarios**. It looks and behaves like+an ordinary invoice application, with no vulnerability labels, answer keys,+sample banners, or test-mode branches in its application code. This README and+the nested [QA guide](qa/README.md) explain the sample and its expected findings.+The [threat model](SECURITY.md) describes the app's assets, trust boundaries, and+intended security properties. It also stays outside the standalone scanner input.++## Start++From the repository root:++```bash+node examples/invoice-desk/app/server.mjs+```++Open `http://127.0.0.1:4310`. There is no install, build, Docker, database service,+external API, or model credential requirement. Node.js 22.13 or later is enough.+The app uses in-memory storage, binds to loopback, and makes no outbound network+requests. `PORT=4311` selects another local port. Stop and restart to reset it.++| Account | Password | Workspace | Role |+| -------------------------- | ------------------ | -------------- | ------------- |+| `[email protected]` | `river-orchard-24` | North Studio | Member |+| `[email protected]` | `meadow-paper-56` | North Studio | Administrator |+| `[email protected]` | `cedar-window-81` | Cedar Workshop | Administrator |++These fixed login accounts are setup data. The connector secrets are generated+anew on each start, and are valid only for the same process's Ledger adapter.+They are never copied from environment variables, credentials, or the host.++## Verify++```bash+node --test examples/invoice-desk/qa/app.test.mjs+```++The tests start their own loopback servers on available ports and clean them up.+They exercise all ten seeded behaviors, ordinary application workflows, and+secure controls. **Passing scenario tests mean the intended weaknesses remain+present.** They do not mean the application is secure or that a scanner found+ten issues. The repository's Invoice Desk workflow runs this suite in CI without+installing dependencies.++## CI and OpenAI scans++The [Invoice Desk workflow](../../.github/workflows/invoice-desk.yml) runs behavior+tests on PRs targeting `main`, including drafts and forks, regardless of which+files changed. A separate [OpenAI scan workflow](../../.github/workflows/invoice-desk-scan.yml)+scans the entire application at the PR's exact head, subject to protected+environment approval. Failed behavior tests do not suppress a scan.++### Setup++Both workflows must be on `main` before automatic scans can run. Configure the+`invoice-desk-inference` environment with required reviewers and a deployment+branch rule allowing only protected `main`. Store a dedicated service-account+key in its `OPENAI_API_KEY` environment secret, with access to `gpt-5.6-sol` and+permission to use the API from the selected runner's network. Creating a service+account alone does not grant that network access. Do not use a repository or+organization Actions secret for this workflow. A missing key fails the scan+with a setup error.++Review the source commit before approving inference. Behavior tests receive no+inference credentials; GitHub may separately require approval to run them for a+first-time contributor.++For a manual baseline, select **Actions → Invoice Desk OpenAI scan → Run+workflow** on `main` and leave both inputs empty. To scan an open PR, provide its+number and exact current head SHA.++The scan adapts the existing [GitHub Actions example](../github-actions/README.md)+to OpenAI inference. It uses CLI 0.1.30, standard mode, high effort, Node.js 24,+and Python 3.12. Each run scans the full application so unchanged cases remain+in scope. Inference consumes API usage.++### Triggers and source selection++A [default-branch dispatcher](https://docs.github.com/en/actions/reference/workflows-and-actions/events-that-trigger-workflows#pull_request_target)+queues scans when a PR is opened, reopened, updated, or retargeted to `main`.+It handles only the PR number and head SHA, with no checkout or inference secret,+and starts the scan on protected `main`. PR edits cannot disable that dispatcher.+Title and description edits do not request another scan.++GitHub can suppress `pull_request_target` for PRs created using `GITHUB_TOKEN`+and for certain branch names. A `workflow_run` fallback handles completed+behavior workflows, including failed tests. It looks up the current PR and skips+PR/head pairs already dispatched from the same `main` workflow revision. It+queues eligible revisions through the same dispatch path, whose run title includes+the PR number and full source SHA. Later fallback events can find those runs and+avoid rescanning an unchanged revision.++If GitHub suppresses the target event and no behavior workflow completes,+automatic scanning cannot start. Use the manual PR dispatch above with the current+head SHA; the same protected workflow and approval checks apply.++The scan checks the PR's base and exact head through GitHub's API before queuing+and again after environment approval, immediately before inference. Closed,+retargeted, and superseded PR revisions are skipped. Repeated scans of the same PR+revision cancel older runs of that revision. A scan that has already started+inference may finish after the PR head changes; its reports identify the source SHA.++The workflow installs the CLI outside the checkout and copies committed `app/`+blobs into a fresh directory. Archive attributes cannot omit or substitute files;+unsafe paths, links, and submodules fail extraction. The inference job does not+install PR dependencies, run the application or its tests, or download artifacts+produced by the PR.++After rechecking eligibility, it removes both full checkouts so the scanner+cannot read their sample guide, threat model, tests, or answer key. Previous+reports are also outside the scan input. The API key is available only in the+scan step, and no GitHub token is passed to the scanner.++### Results++Results appear under **Actions → Invoice Desk OpenAI scan**. This separate+workflow does not create a PR status check or merge gate. Its summary identifies+the PR and source commit, completion, finding and severity counts, coverage,+elapsed time, and package-cache reuse. Passing behavior tests alone does not+mean a source scan completed.++Reports are retained for seven days. The artifact includes Markdown, findings+and coverage JSON, the scan manifest, CLI result JSON, SARIF, and+`invoice-desk-metrics.json`. Metrics record source and workflow revisions,+scanner settings, exit code, elapsed time, cache hits, and any token usage or+cost estimates reported by the CLI. Incomplete scans retain the measurements+that were emitted; missing measurements and recall remain unknown. Failed scans+do not count as zero findings. Authentication state and agent transcripts are+not uploaded. SARIF is downloadable; the workflow does not create Code Scanning+alerts or post PR comments.++Findings are report-only. Scan errors and incomplete scans fail the job, with+available reports retained. A successful job means the scan completed; it does+not establish that the application is secure or that all ten scenarios were+found. Compare distinct root causes with the QA manifest and review extra+findings and duplicates separately. There is no exact-count or recall gate yet.++### Cache persistence++The trusted preparation job restores and saves the npm content-addressed download+cache for the pinned CLI and its bundled runtime dependencies. Its key includes a+cache schema version, OS, architecture, Node major, and CLI version. The scan job+restores that same cache and installs with `--prefer-offline`; a cache miss still+allows a normal registry install. Cache population happens before PR source is+checked out or an inference credential is available. The scan job has read-only+cache access and never saves files produced during inference.++Only `invoice-desk-npm-cache/_cacache` is cached. The private+`CODEX_SECURITY_STATE_DIR`, `codex-home`, authentication files, session logs,+workbench database, threat models, and previous findings stay out of the cache.+Each scan starts with fresh analysis state so previous answers do not influence+fixture evaluation. API prompt-cache token usage is reported separately by the+CLI; saving the package cache does not preserve model responses. GitHub can+[evict caches](https://docs.github.com/en/actions/using-workflows/caching-dependencies-to-speed-up-workflows),+so cache availability is a performance signal, not a pass/fail condition.++### Establishing the first baseline++After merging this setup, run a main baseline, approve the protected environment,+and inspect the completed reports. Run the same revision again to verify a cache+hit and compare elapsed time and token use. Then use an ordinary PR to verify the+automatic dispatcher and the reported source SHA.++Review actual findings against the ten root causes in the QA manifest. Record+matched cases, misses, uncertain cases, duplicates, and additional findings;+confirm secret exposure is matched by the crossed credential boundary. Start+with report-only recall and cost measurements. Consider a regression gate only+after repeated completed scans establish normal variation. The initial CI gate+is operational completion, not zero vulnerabilities or exactly ten reports.++## Scan without including the answer key++The standalone application is `app/`. The harness, scenario labels, and findings+manifest are siblings outside that directory:++```text+invoice-desk/+ README.md Sample instructions+ SECURITY.md Threat model and security assumptions+ app/ Standalone scanner input+ README.md Ordinary product and runtime documentation+ server.mjs+ ...+ qa/+ README.md Scenario and scoring guide+ expected-findings.json Expected root causes and source symbols+ app.test.mjs Behavior checks and secure controls+```++For an independent discovery run, copy only `app/` into a fresh directory outside+this checkout and select that directory as the scan target. Keep this README,+SECURITY.md, the QA directory, and prior reports outside the scanner's input. This+also avoids inheriting the parent repository's instructions or exposing the answer+key by walking to a neighboring directory inside the checkout.++The app has no dependency on its surrounding example directory, and runs from+the copied directory. Its own README describes the product and intended roles,+without identifying the seeded defects. Source scanning does not require keeping+a separate server running; the HTTP suite independently verifies runtime behavior.++Review returned findings against the [manifest](qa/expected-findings.json).+Count distinct matched root causes, missed cases, unexpected findings, and+duplicates. Ten scenarios are a ground-truth design target, not a guaranteed raw+finding count from every model run. The fixed seed accounts, loopback HTTP, and+in-memory data are declared harness assumptions, not additional target findings.diff --git a/examples/invoice-desk/SECURITY.md b/examples/invoice-desk/SECURITY.mdnew file mode 100644index 000000000..201ec52d9--- /dev/null+++ b/examples/invoice-desk/SECURITY.md@@ -0,0 +1,160 @@+# Invoice Desk threat model++Generated with Codex Security CLI 0.1.30 (`policy`, OpenAI `gpt-5.6-sol`, high+effort), then reviewed against the source and condensed. The CLI inspected a+standalone copy of `app/`. The local QA scope and intended properties below also+use the surrounding [sample guide](README.md) and [QA guide](qa/README.md).++Invoice Desk is deliberately insecure. This document describes its architecture+and intended security boundaries; it does not claim that those boundaries hold.+Threat modeling is separate from finding discovery and runtime verification.+Keep this file outside the standalone application given to blind scans.++## 1. Overview++Invoice Desk manages workspace invoices, imports, approvals, notes, and accounting+connections through server-rendered pages and a JSON API. Members work with their+workspace's invoices and edit their display name. Administrators additionally+approve invoices and manage import policy. An approval represents the invoice+version reviewed. See the [application contract](app/README.md#workspaces).++The documented startup runs a dependency-free Node.js process on+`127.0.0.1:4310`, with `PORT` selecting another local port. Each application+instance creates fresh in-memory users, sessions, invoices, policies, previews,+connector credentials, and deliveries. Restarting discards that state.+[Startup](app/server.mjs#L269), [store](app/store.mjs#L8).++```mermaid+flowchart LR+ Browser[Member or administrator browser] -->|Session cookie and JSON| HTTP[HTTP routes]+ Caller[Connector credential holder] -->|Bearer credential| Ledger[Ledger account route]+ HTTP --> Accounts[Accounts and sessions]+ HTTP --> Workflows[Invoices, approvals and imports]+ HTTP --> Connections[Support reports and deliveries]+ Accounts --> State[(In-memory state)]+ Workflows --> State+ Connections --> State+ Ledger --> State+ Connections -->|Stored delivery| Inbox[Destination-owner inbox]+```++All server components and connector adapters run in the same process. Deliveries+record invoice summaries in memory; the app makes no outbound network requests,+transfers no money, and writes no application state to disk. Ledger exposes a+synthetic settlement balance to a caller with the matching connector credential.+[Integration implementation](app/integrations.mjs#L26).++## 2. Actors, assets, and trust boundaries++| Actor | Intended authority |+| ----------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------ |+| Unauthenticated caller | Reach login, health, and static assets. Application operations require a session or the separate Ledger bearer credential. |+| Workspace member | Work with invoices in their own workspace, submit imports and notes, and edit their display name. |+| Workspace administrator | Member actions plus approval and import-policy changes, scoped to their own workspace. |+| Destination owner | Inspect invoice copies delivered to their destination; this does not grant authority over the source workspace's Ledger account. |+| Connector caller | Read the Ledger account associated with its bearer credential. This does not grant a browser session or administrator role. |+| Local operator | Start and stop the process and control its host. Host access is trusted; application authorization does not isolate data from the process owner. |++The assets are:++- Password records, session tokens, workspace membership, and administrator roles.+- Invoice contents, versions, approvals, notes, and workflow state.+- Workspace import policies and the integrity of import review.+- Connector credentials, settlement balances, diagnostic exports, and destination+ inbox contents.+- Availability and integrity of the single process and its volatile state.++HTTP clients can send arbitrary JSON to reachable routes, independently of what+the interface offers. Each workspace is a separate authorization domain even+though all records share one process. Shared caches and nested policy objects+must preserve that separation. A workspace administrator has no authority over+another workspace. User-supplied notes also cross a boundary when another user's+browser interprets the resulting page.++Connector credentials carry authority beyond the ordinary invoice view. A+diagnostic download or an invoice copy must not transfer that authority to its+recipient. The Ledger bearer route has a separate authentication path from the+session-protected application. [Route boundaries](app/server.mjs#L92),+[Ledger authentication](app/integrations.mjs#L53).++### Controls already present++Passwords use salted scrypt records and timing-safe comparison. Sessions use+random tokens, expire after eight hours, and are removed on logout or when an+expired session is checked. Cookies use `HttpOnly` and `SameSite=Strict`.+[Password records](app/store.mjs#L3), [sessions](app/accounts.mjs#L12),+[cookie settings](app/server.mjs#L100).++The router applies a common session gate after its public and bearer-authenticated+routes. Invoice lists and most invoice operations check workspace ownership;+approval and import-policy updates check the administrator role. These checks+are useful controls, but their coverage and the integrity of the values they+trust require separate review. [Ownership and roles](app/invoices.mjs#L10),+[import policy](app/imports.mjs#L12).++JSON writes require a JSON object, amounts receive positive-integer validation,+and responses use `Cache-Control: no-store` and `X-Content-Type-Options: nosniff`.+The rendering code has an HTML-escaping helper, and browser notices and previews+use `textContent`. An escaping helper protects only values passed through it.+[Request parsing](app/server.mjs#L54), [rendering](app/views.mjs#L1),+[browser updates](app/public/client.js#L43).++## 3. Threat scenarios and intended protections++These are review scenarios and repair directions for a secure implementation.+The sample deliberately retains the seeded weaknesses for QA. The+[expected-findings manifest](qa/expected-findings.json) identifies the ten root+causes; the [HTTP harness](qa/app.test.mjs) records the behaviors it checks.+Neither this model nor the number of rows establishes a scanner's detection score.++| Boundary and potential failure | Intended protection | Source to review |+| --------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- |+| Member to connector authority: a diagnostic export discloses a reusable credential. | Export only diagnostic fields that the recipient is allowed to see; keep connector secrets server-side. | [Support report](app/integrations.mjs#L16) |+| Workspace to workspace: an invoice read returns a record without checking its owner. | Apply workspace authorization to every object read as well as writes. | [Individual invoice route](app/server.mjs#L227), [ownership helper](app/invoices.mjs#L21) |+| Workspace to shared cache: a valid preview request receives another workspace's cached content. | Cache identity must include the workspace and invoice identity, with versioning for invalidation. | [Preview cache](app/invoices.mjs#L71) |+| Reviewed version to sent version: editing leaves an old approval effective. | Sending requires approval of the current invoice version; edits invalidate or supersede earlier approval. | [Edit, approve, and send](app/invoices.mjs#L34) |+| Import input to review decision: unsupported or failed review permits an over-limit import. | Required review fails closed; unsupported schemas and reviewer errors cannot imply approval. | [Import review](app/imports.mjs#L35) |+| Source workspace to destination owner: an invoice copy carries the source connector's authority. | Keep authentication credentials separate from recipient-visible delivery data and bind any connector authorization to its intended destination. | [Delivery and inbox](app/integrations.mjs#L26) |+| Workspace to shared policy state: one administrator changes another workspace's import limit. | Each workspace owns independent mutable policy state, including nested objects. | [Policy construction](app/store.mjs#L8), [policy update](app/imports.mjs#L12) |+| Validated document to persisted record: authorization and storage use different workspace metadata. | Derive stored ownership from the authenticated workspace and reject conflicting ownership fields. | [Import authorization](app/imports.mjs#L21), [stored ownership](app/imports.mjs#L50) |+| Member to administrator: a self-service profile edit changes authorization attributes. | Allow only intended profile fields to change and keep role assignment outside self-service profile updates. | [Profile update](app/accounts.mjs#L49), [role check](app/invoices.mjs#L10) |+| Stored note to another user's browser: note content becomes active HTML. | Encode note content for its rendering context; if formatting is supported, use an explicit safe formatting policy. | [Comments](app/invoices.mjs#L84), [invoice rendering](app/views.mjs#L71) |++Availability also needs review beyond those ten cases. The parser buffers a+complete request body, login performs synchronous password derivation, and the+store has no application-defined collection limits. Assess the caller's reach+and the resource consumed before assigning impact; this model sets no arbitrary+request or rate thresholds. [Body buffering](app/server.mjs#L54),+[password verification](app/accounts.mjs#L12), [collections](app/store.mjs#L99).++## 4. Assumptions, impact, and verification++The supported sample use is local QA with synthetic data and credentials. Fixed+login accounts are fixture setup; connector credentials are fresh per process+and valid only for that process's adapter. The intended role, workspace, approval,+and credential boundaries still matter when evaluating a scenario.++Severity depends on the starting principal, the boundary crossed, the additional+authority obtained, affected data, and repeatability. Distinguish a disclosure+within one workspace from a cross-workspace disclosure, and a metadata leak from+a usable credential. Browser impact depends on what executes and whose authority+it gains. The harness checks inert HTML interpretation; it does not by itself+establish script execution or administrator compromise.++Do not infer real financial loss, external-account compromise, or host execution+from an in-process simulation. The generated model does not assign final+severities or validate findings. Review unexpected scanner findings and duplicate+root causes separately, using the [QA scoring guidance](qa/README.md#scanner-evaluation).++The direct executable binds to loopback, but the exported `createApp()` returns+an unbound server. Remote exposure, reverse proxies, TLS, persistent storage, and+multiple processes would change this model; none is a supported deployment for+this sample. The current cookie and in-memory design are not a production+deployment contract. [Server construction](app/server.mjs#L86),+[listener](app/server.mjs#L269).++Revisit this model when routes, ownership rules, approval transitions, credential+recipients, rendering, or storage change. Run the harness to preserve the QA+contract, and keep this document and the answer key outside discovery inputs.+For actual Codex Security product vulnerabilities, follow the repository's+[security reporting policy](../../SECURITY.md).diff --git a/examples/invoice-desk/app/README.md b/examples/invoice-desk/app/README.mdnew file mode 100644index 000000000..5fb8e3c93--- /dev/null+++ b/examples/invoice-desk/app/README.md@@ -0,0 +1,57 @@+# Invoice Desk++Invoice Desk organizes workspace invoices, approvals, imports, and accounting+connections. It includes a server-rendered interface and a JSON API.++## Run++Requires Node.js 22.13 or later. There are no package dependencies or build steps.++```bash+node server.mjs+```++Open `http://127.0.0.1:4310`. Set `PORT` to use a different local port. The server+listens on loopback. Data lives in memory and resets when the process restarts.+Each process creates its own workspace state and connector credentials.++## Workspaces++Members work with invoices in their workspace. Administrators approve invoices+and manage the workspace's import policy. An approval represents the invoice+version an administrator reviewed. Members can edit their display name.++Invoice references are local to a workspace. Amounts are positive integer cents+in USD. Imports use this document format:++```json+{+ "schemaVersion": "1",+ "workspaceId": "north",+ "invoice": {+ "reference": "INV-1003",+ "customer": "Field Studio",+ "amountCents": 25000+ }+}+```++Ledger provides the accounting connection. Cedar Archive is a destination owned+by Cedar Workshop. Deliveries use in-process adapters and stay in this process;+the application makes no outbound network requests. The Ledger credential grants+server-side access to settlement balances, which are not part of member-facing+invoice data. Destination owners can inspect received requests.++## Application layout++- `server.mjs`: HTTP routes, session cookies, and static assets.+- `accounts.mjs`: authentication and profiles.+- `invoices.mjs`: invoice workflows and previews.+- `imports.mjs`: document review and import policies.+- `integrations.mjs`: connector deliveries and support reports.+- `store.mjs`: initial workspaces and process-local storage.+- `views.mjs` and `public/`: interface templates, styles, and form handling.++`GET /health` reports process readiness. JSON writes require+`Content-Type: application/json`. Stopping the process releases all application+state; no application files or databases are written to disk.diff --git a/examples/invoice-desk/app/accounts.mjs b/examples/invoice-desk/app/accounts.mjsnew file mode 100644index 000000000..254d73b8d--- /dev/null+++ b/examples/invoice-desk/app/accounts.mjs@@ -0,0 +1,52 @@+import { randomBytes, scryptSync, timingSafeEqual } from "node:crypto";++export function publicUser(user) {+ return {+ id: user.id,+ email: user.email,+ workspaceId: user.workspaceId,+ profile: { ...user.profile },+ };+}++export function signIn(store, email, password) {+ const user = [...store.users.values()].find((entry) => entry.email === email);+ if (!user || typeof password !== "string") return null;+ const actual = scryptSync(password, user.password.salt, 32);+ if (!timingSafeEqual(actual, Buffer.from(user.password.hash, "hex")))+ return null;+ const token = randomBytes(32).toString("hex");+ store.sessions.set(token, {+ userId: user.id,+ expiresAt: Date.now() + 8 * 60 * 60 * 1000,+ });+ return token;+}++export function sessionUser(store, cookie = "") {+ const token = cookie+ .split(";")+ .map((part) => part.trim())+ .find((part) => part.startsWith("session="))+ ?.slice(8);+ const session = store.sessions.get(token);+ if (!session || session.expiresAt <= Date.now()) {+ store.sessions.delete(token);+ return null;+ }+ return store.users.get(session.userId) ?? null;+}++export function signOut(store, cookie = "") {+ const token = cookie+ .split(";")+ .map((part) => part.trim())+ .find((part) => part.startsWith("session="))+ ?.slice(8);+ store.sessions.delete(token);+}++export function updateProfile(user, fields) {+ Object.assign(user.profile, fields);+ return publicUser(user);+}diff --git a/examples/invoice-desk/app/imports.mjs b/examples/invoice-desk/app/imports.mjsnew file mode 100644index 000000000..557b5f577--- /dev/null+++ b/examples/invoice-desk/app/imports.mjs@@ -0,0 +1,70 @@+import { randomUUID } from "node:crypto";+import { HttpError, requireAdmin } from "./invoices.mjs";++function checkAmount(document, policy) {+ return {+ approved: document.invoice.amountCents <= policy.limits.maxAmountCents,+ };+}++const reviewers = new Map([["1", checkAmount]]);++export function updateImportPolicy(store, user, maxAmountCents) {+ requireAdmin(user);+ if (!Number.isSafeInteger(maxAmountCents) || maxAmountCents <= 0)+ throw new HttpError(400, "Enter a positive import limit.");+ const policy = store.workspaces.get(user.workspaceId).importPolicy;+ policy.limits.maxAmountCents = maxAmountCents;+ return policy;+}++export function importInvoice(store, user, document) {+ if (document.workspaceId !== user.workspaceId)+ throw new HttpError(403, "The import belongs to another workspace.");+ const item = document.invoice;+ if (+ !item ||+ !Number.isSafeInteger(item.amountCents) ||+ item.amountCents <= 0 ||+ typeof item.customer !== "string"+ )+ throw new HttpError(+ 400,+ "An invoice needs a customer and a positive amount in cents.",+ );+ const policy = store.workspaces.get(user.workspaceId).importPolicy;+ let review;+ try {+ review = reviewers.get(String(document.schemaVersion))(document, policy);+ } catch {+ review = {+ approved: true,+ warning: "Review unavailable; accepted for processing.",+ };+ }+ if (!review.approved)+ throw new HttpError(+ 422,+ "This invoice exceeds the workspace import limit.",+ );+ const workspaceId = item.workspaceId ?? document.workspaceId;+ if (!store.workspaces.has(workspaceId))+ throw new HttpError(400, "Workspace not found.");+ const id = randomUUID();+ const invoice = {+ id,+ workspaceId,+ reference:+ typeof item.reference === "string"+ ? item.reference+ : `INV-${store.invoices.size + 1001}`,+ customer: item.customer,+ amountCents: item.amountCents,+ version: 1,+ approval: null,+ status: "draft",+ comments: [],+ };+ store.invoices.set(id, invoice);+ return { invoice, review };+}diff --git a/examples/invoice-desk/app/integrations.mjs b/examples/invoice-desk/app/integrations.mjsnew file mode 100644index 000000000..fd2e5602f--- /dev/null+++ b/examples/invoice-desk/app/integrations.mjs@@ -0,0 +1,64 @@+import { randomUUID } from "node:crypto";+import { HttpError, ownedInvoice } from "./invoices.mjs";++export function connectionSettings(store, user) {+ const workspace = store.workspaces.get(user.workspaceId);+ return {+ destination: workspace.connector.destination,+ connected: Boolean(workspace.connector.accessToken),+ destinations: [...store.destinations.values()].map(({ id, name }) => ({+ id,+ name,+ })),+ };+}++export function supportReport(store, user) {+ const workspace = store.workspaces.get(user.workspaceId);+ return {+ generatedAt: new Date().toISOString(),+ workspace: { id: workspace.id, name: workspace.name },+ connector: { ...workspace.connector },+ importPolicy: workspace.importPolicy,+ };+}++export function deliverInvoice(store, user, invoiceId, destinationId) {+ const invoice = ownedInvoice(store, user, invoiceId);+ const connector = store.workspaces.get(user.workspaceId).connector;+ const destination = store.destinations.get(+ destinationId ?? connector.destination,+ );+ if (!destination)+ throw new HttpError(400, "Select an available destination.");+ const request = {+ id: randomUUID(),+ destinationId: destination.id,+ workspaceId: user.workspaceId,+ credential: connector.accessToken,+ invoice: { reference: invoice.reference, amountCents: invoice.amountCents },+ };+ store.deliveries.push(request);+ return { id: request.id, destination: destination.name, status: "delivered" };+}++export function receivedDeliveries(store, user) {+ return store.deliveries.filter(+ (delivery) =>+ store.destinations.get(delivery.destinationId).ownerWorkspaceId ===+ user.workspaceId,+ );+}++export function ledgerAccount(store, credential) {+ const workspace = [...store.workspaces.values()].find(+ (entry) => entry.connector.accessToken === credential,+ );+ if (!workspace)+ throw new HttpError(401, "A valid connector credential is required.");+ return {+ workspaceId: workspace.id,+ accountName: workspace.name,+ settlementBalanceCents: workspace.ledger.settlementBalanceCents,+ };+}diff --git a/examples/invoice-desk/app/invoices.mjs b/examples/invoice-desk/app/invoices.mjsnew file mode 100644index 000000000..855eebce3--- /dev/null+++ b/examples/invoice-desk/app/invoices.mjs@@ -0,0 +1,90 @@+import { randomUUID } from "node:crypto";++export class HttpError extends Error {+ constructor(status, message) {+ super(message);+ this.status = status;+ }+}++export function requireAdmin(user) {+ if (user.profile.role !== "admin")+ throw new HttpError(403, "An administrator must perform this action.");+}++export function getInvoice(store, id) {+ const invoice = store.invoices.get(id);+ if (!invoice) throw new HttpError(404, "Invoice not found.");+ return invoice;+}++export function ownedInvoice(store, user, id) {+ const invoice = getInvoice(store, id);+ if (invoice.workspaceId !== user.workspaceId)+ throw new HttpError(404, "Invoice not found.");+ return invoice;+}++export function listInvoices(store, user) {+ return [...store.invoices.values()].filter(+ (invoice) => invoice.workspaceId === user.workspaceId,+ );+}++export function updateInvoice(store, user, id, fields) {+ const invoice = ownedInvoice(store, user, id);+ if (fields.amountCents !== undefined) {+ if (!Number.isSafeInteger(fields.amountCents) || fields.amountCents <= 0)+ throw new HttpError(400, "Enter a positive amount in cents.");+ invoice.amountCents = fields.amountCents;+ }+ if (typeof fields.customer === "string") invoice.customer = fields.customer;+ invoice.version += 1;+ return invoice;+}++export function approveInvoice(store, user, id) {+ requireAdmin(user);+ const invoice = ownedInvoice(store, user, id);+ invoice.approval = {+ version: invoice.version,+ userId: user.id,+ approvedAt: new Date().toISOString(),+ };+ invoice.status = "approved";+ return invoice;+}++export function sendInvoice(store, user, id) {+ const invoice = ownedInvoice(store, user, id);+ if (!invoice.approval)+ throw new HttpError(409, "Approve the invoice before sending it.");+ invoice.status = "sent";+ return {+ id: invoice.id,+ version: invoice.version,+ amountCents: invoice.amountCents,+ status: invoice.status,+ };+}++export function previewInvoice(store, user, id) {+ const invoice = ownedInvoice(store, user, id);+ const cacheKey = `${invoice.reference}:${invoice.version}`;+ if (!store.previews.has(cacheKey)) {+ store.previews.set(cacheKey, {+ reference: invoice.reference,+ customer: invoice.customer,+ amountCents: invoice.amountCents,+ });+ }+ return store.previews.get(cacheKey);+}++export function addComment(store, user, id, body) {+ if (typeof body !== "string" || !body.trim())+ throw new HttpError(400, "Write a note first.");+ const comment = { id: randomUUID(), author: user.profile.name, body };+ ownedInvoice(store, user, id).comments.push(comment);+ return comment;+}diff --git a/examples/invoice-desk/app/package.json b/examples/invoice-desk/app/package.jsonnew file mode 100644index 000000000..30885a9cf--- /dev/null+++ b/examples/invoice-desk/app/package.json@@ -0,0 +1,12 @@+{+ "name": "invoice-desk",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "engines": {+ "node": ">=22.13.0"+ },+ "scripts": {+ "start": "node server.mjs"+ }+}diff --git a/examples/invoice-desk/app/public/client.js b/examples/invoice-desk/app/public/client.jsnew file mode 100644index 000000000..a2866f5f5--- /dev/null+++ b/examples/invoice-desk/app/public/client.js@@ -0,0 +1,63 @@+const notice = document.querySelector("#notice");++function tell(message, error = false) {+ notice.textContent = message;+ notice.className = error ? "error" : "";+ notice.hidden = false;+}++for (const form of document.querySelectorAll("form[data-action]")) {+ form.addEventListener("submit", async (event) => {+ event.preventDefault();+ const button = form.querySelector("button");+ button.disabled = true;+ try {+ let body = Object.fromEntries(new FormData(form));+ for (const input of form.querySelectorAll('input[type="number"]'))+ body[input.name] = Number(input.value);+ if (form.hasAttribute("data-document")) body = JSON.parse(body.document);+ const response = await fetch(form.dataset.action, {+ method: form.dataset.method ?? "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });+ const result = await response.json();+ if (!response.ok)+ throw new Error(result.error ?? "Something went wrong.");+ if (form.hasAttribute("data-stay"))+ tell(`Delivered to ${result.destination}.`);+ else if (form.hasAttribute("data-document")) {+ tell(+ `Imported ${result.invoice.reference}.${result.review.warning ? ` ${result.review.warning}` : ""}`,+ );+ } else+ window.location.assign(result.redirect ?? window.location.pathname);+ } catch (error) {+ tell(error.message, true);+ } finally {+ button.disabled = false;+ }+ });+}++for (const button of document.querySelectorAll("[data-preview]")) {+ button.addEventListener("click", async () => {+ try {+ const response = await fetch(button.dataset.preview);+ const preview = await response.json();+ if (!response.ok) throw new Error(preview.error);+ const dialog = document.querySelector("#preview-dialog");+ dialog.querySelector(".preview-body").textContent =+ `${preview.reference}\n${preview.customer}\n${new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(preview.amountCents / 100)}`;+ dialog.showModal();+ } catch (error) {+ tell(error.message, true);+ }+ });+}++document+ .querySelector("[data-close]")+ ?.addEventListener("click", () =>+ document.querySelector("#preview-dialog").close(),+ );diff --git a/examples/invoice-desk/app/public/styles.css b/examples/invoice-desk/app/public/styles.cssnew file mode 100644index 000000000..c4354a9d5--- /dev/null+++ b/examples/invoice-desk/app/public/styles.css@@ -0,0 +1,793 @@+:root {+ --muted: #5d6653;+ color-scheme: light;+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;+ color: #262924;+ background: #f6f7f3;+ font-synthesis: none;+}+* {+ box-sizing: border-box;+}+body {+ margin: 0;+}+a {+ color: inherit;+ text-decoration: none;+}+button,+input,+textarea,+select {+ font: inherit;+}+button,+a,+input,+textarea,+select {+ -webkit-tap-highlight-color: transparent;+}+:focus-visible {+ outline: 3px solid #748969;+ outline-offset: 3px;+}+button {+ cursor: pointer;+}+button:disabled {+ opacity: 0.55;+ cursor: wait;+}+.shell {+ display: flex;+ min-height: 100vh;+}+.sidebar {+ position: sticky;+ top: 0;+ height: 100vh;+ width: 244px;+ flex-shrink: 0;+ display: flex;+ flex-direction: column;+ padding: 30px 22px 24px;+ background: #fff;+ border-right: 1px solid #e4e7df;+}+.brand {+ display: flex;+ align-items: center;+ gap: 10px;+ font-weight: 700;+ font-size: 18px;+ letter-spacing: -0.5px;+}+.brand-mark {+ display: grid;+ place-items: center;+ width: 33px;+ height: 33px;+ background: #263e2e;+ color: #fff;+ border-radius: 9px;+ font-size: 19px;+}+.workspace {+ display: flex;+ gap: 11px;+ align-items: center;+ padding: 19px 0;+ margin: 25px 0 19px;+ border-top: 1px solid #eef0eb;+ border-bottom: 1px solid #eef0eb;+ font-size: 13px;+}+.workspace-mark {+ display: grid;+ place-items: center;+ border: 1px solid #e4e7df;+ width: 33px;+ height: 33px;+ border-radius: 8px;+ background: #f7f6ef;+ font-weight: 700;+}+small {+ display: block;+ color: var(--muted);+ line-height: 1.7;+ font-size: 12px;+}+.nav-label,+.eyebrow {+ color: var(--muted);+ font-size: 10px;+ letter-spacing: 1.8px;+ font-weight: 700;+}+.nav-label {+ padding: 0 12px;+ margin-bottom: 13px;+}+nav {+ display: grid;+ gap: 7px;+}+nav a {+ display: flex;+ align-items: center;+ gap: 13px;+ padding: 12px;+ border-radius: 7px;+ color: var(--muted);+ font-size: 13px;+ font-weight: 500;+}+nav a:hover {+ background: #f5f7f0;+}+nav a[aria-current] {+ background: #eaf0e4;+ color: #354b2f;+}+nav svg {+ width: 19px;+ height: 19px;+}+.sidebar-bottom {+ margin-top: auto;+ padding-top: 22px;+ border-top: 1px solid #edf0e7;+ display: flex;+ align-items: center;+ gap: 10px;+ font-size: 13px;+}+.sidebar-bottom form {+ margin: 0 0 0 auto;+}+.avatar {+ display: grid;+ place-items: center;+ width: 35px;+ height: 35px;+ border-radius: 50%;+ background: #eee7da;+ color: #776342;+}+.logout {+ background: none;+ border: 0;+ color: #6a7363;+ font-size: 20px;+ padding: 8px;+}+main {+ flex: 1;+ min-width: 0;+}+.topbar {+ height: 78px;+ display: flex;+ align-items: center;+ justify-content: space-between;+ border-bottom: 1px solid #e4e7df;+ padding: 0 44px;+ color: var(--muted);+ font-size: 12px;+}+.slash {+ margin: 0 12px;+ color: #b2b7aa;+}+.connection-dot {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 11px;+}+.connection-dot::before {+ content: "";+ width: 6px;+ height: 6px;+ background: #668450;+ border-radius: 50%;+}+.content {+ max-width: 1270px;+ margin: 0 auto;+ padding: 46px 44px;+}+.page-heading {+ display: flex;+ justify-content: space-between;+ align-items: center;+ gap: 24px;+ margin-bottom: 35px;+}+h1 {+ font-size: clamp(26px, 3vw, 34px);+ letter-spacing: -1.2px;+ line-height: 1.2;+ margin: 10px 0 12px;+ font-weight: 600;+}+h2 {+ margin: 0;+ font-size: 16px;+ letter-spacing: -0.3px;+ font-weight: 600;+}+h3 {+ font-size: 14px;+ margin-top: 0;+}+p {+ line-height: 1.6;+}+.muted {+ color: var(--muted);+ font-size: 13px;+ margin: 8px 0;+}+.small {+ font-size: 12px;+}+.button {+ display: inline-flex;+ justify-content: center;+ align-items: center;+ gap: 8px;+ border: 1px solid #dce2d5;+ border-radius: 7px;+ background: #fff;+ color: #3f4b36;+ padding: 11px 16px;+ font-size: 12px;+ font-weight: 600;+ white-space: nowrap;+ min-height: 40px;+}+.button:hover {+ background: #f0f4ea;+}+.button.primary {+ background: #344b2c;+ border-color: #344b2c;+ color: #fff;+}+.button.primary:hover {+ background: #273d20;+}+.stats {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 18px;+ margin-bottom: 30px;+}+.stat {+ border: 1px solid #e0e4da;+ border-radius: 10px;+ padding: 24px;+ background: #fff;+}+.stat > span {+ display: block;+ font-size: 12px;+ color: var(--muted);+}+.stat > strong {+ display: block;+ font-size: 30px;+ font-weight: 500;+ letter-spacing: -1px;+ margin: 15px 0 7px;+ font-variant-numeric: tabular-nums;+}+.stat small {+ font-size: 11px;+}+.panel {+ background: #fff;+ border: 1px solid #e0e4da;+ border-radius: 10px;+ overflow: hidden;+}+.panel-heading {+ display: flex;+ align-items: center;+ justify-content: space-between;+ padding: 24px;+}+.count {+ display: inline-block;+ background: #f1f4eb;+ color: var(--muted);+ font-size: 11px;+ padding: 3px 7px;+ margin-left: 6px;+ border-radius: 5px;+ vertical-align: middle;+}+.table-wrap {+ overflow-x: auto;+}+table {+ border-collapse: collapse;+ width: 100%;+ white-space: nowrap;+}+th {+ text-align: left;+ font-size: 10px;+ letter-spacing: 0.5px;+ color: var(--muted);+ background: #fafbf8;+ font-weight: 500;+ padding: 12px 24px;+ border-block: 1px solid #edf0e7;+}+td {+ padding: 23px 24px;+ font-size: 12px;+ border-bottom: 1px solid #edf0e7;+}+tbody tr:last-child td {+ border-bottom: 0;+}+tbody tr:hover {+ background: #fdfefa;+}+td small {+ font-size: 10px;+ margin-top: 5px;+}+.numeric {+ text-align: right;+}+.amount {+ font-weight: 600;+ font-variant-numeric: tabular-nums;+}+.invoice-link {+ font-weight: 600;+}+.invoice-link:hover {+ text-decoration: underline;+}+.row-arrow {+ font-size: 17px;+ color: #819070;+}+.badge {+ display: inline-block;+ padding: 5px 8px;+ background: #f3efdf;+ color: #79622f;+ border-radius: 5px;+ font-size: 10px;+ font-weight: 500;+ text-transform: capitalize;+ letter-spacing: 0;+ vertical-align: middle;+}+.badge.approved {+ background: #eaf1e4;+ color: #4b6a33;+}+.badge.sent {+ background: #eaf0f6;+ color: #456585;+}+.bottom-note {+ display: flex;+ align-items: center;+ gap: 17px;+ margin-top: 28px;+ padding: 20px 5px;+}+.bottom-note p {+ font-size: 11px;+ color: var(--muted);+ margin: 0;+}+.bottom-note strong {+ color: #69745c;+ font-weight: 500;+}+.bottom-note a {+ margin-left: auto;+ font-size: 11px;+ color: #69745c;+}+.note-icon {+ font-size: 30px;+ color: #99a78a;+}+.columns {+ display: grid;+ grid-template-columns: 1.2fr 1fr;+ gap: 22px;+}+.padded {+ padding: 28px;+}+.align-start {+ align-self: start;+}+form {+ margin-top: 22px;+}+label {+ display: grid;+ gap: 8px;+ margin-bottom: 20px;+ font-size: 12px;+ color: #5d6653;+}+input,+textarea,+select {+ border: 1px solid #dce2d5;+ border-radius: 7px;+ padding: 12px;+ background: #fff;+ color: #384030;+ width: 100%;+ min-width: 0;+ font-size: 13px;+}+textarea {+ resize: vertical;+ line-height: 1.6;+}+input:focus,+textarea:focus,+select:focus {+ border-color: #7e9868;+}+.code-input,+pre {+ font:+ 12px/1.7 ui-monospace,+ "SFMono-Regular",+ Consolas,+ monospace;+}+pre {+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ background: #f7f8f3;+ padding: 16px;+ border-radius: 7px;+}+.actions {+ display: flex;+ flex-wrap: wrap;+ gap: 10px;+}+.actions form {+ margin: 14px 0 0;+}+hr {+ border: 0;+ border-top: 1px solid #edf0e7;+ margin: 28px 0;+}+.notes {+ margin-top: 24px;+}+.comment {+ padding: 18px 0;+ border-bottom: 1px solid #edf0e7;+ font-size: 13px;+}+.comment-body {+ margin-top: 8px;+ line-height: 1.6;+ overflow-wrap: anywhere;+}+.back-link {+ display: inline-block;+ margin-bottom: 20px;+ font-size: 12px;+ color: var(--muted);+}+.policy-value {+ font-size: 32px;+ margin: 28px 0;+}+.policy-value small {+ font-size: 11px;+}+.connection-card {+ display: flex;+ align-items: center;+ gap: 14px;+ margin-bottom: 22px;+}+.connection-card .badge {+ margin-left: auto;+}+.connection-card p {+ margin: 5px 0 0;+ font-size: 11px;+}+.service-icon {+ display: grid;+ place-items: center;+ background: #e8ede0;+ color: #62794e;+ font-size: 21px;+ font-weight: 600;+ border-radius: 10px;+ width: 48px;+ height: 48px;+}+.padded > .eyebrow {+ display: block;+ margin-bottom: 12px;+}+.padded > .button {+ margin-top: 15px;+}+.empty-state {+ text-align: center;+ padding: 34px 0 18px;+ font-size: 12px;+ color: var(--muted);+}+details {+ margin-top: 18px;+ font-size: 13px;+}+summary {+ cursor: pointer;+}+.profile-panel {+ max-width: 560px;+}+dialog {+ border: 1px solid #e0e4da;+ border-radius: 12px;+ padding: 0;+ width: min(480px, 90vw);+ color: #384030;+}+dialog::backdrop {+ background: #15201166;+}+.preview-body {+ padding: 20px 24px 35px;+ white-space: pre-line;+ line-height: 2;+}+#notice {+ position: fixed;+ bottom: 24px;+ right: 24px;+ z-index: 10;+ max-width: min(480px, calc(100vw - 48px));+ padding: 17px 23px;+ background: #344b2c;+ color: #fff;+ border-radius: 9px;+ box-shadow: 0 7px 25px #24391b22;+ font-size: 13px;+ line-height: 1.6;+}+#notice.error {+ background: #934932;+}+.sr-only {+ position: absolute;+ width: 1px;+ height: 1px;+ padding: 0;+ margin: -1px;+ overflow: hidden;+ clip: rect(0, 0, 0, 0);+ border: 0;+}+.login-shell {+ min-height: 100vh;+ display: grid;+ grid-template-columns: 1fr 1fr;+}+.login-intro {+ background: #e9eddf;+ padding: 45px 60px;+ display: flex;+ flex-direction: column;+ justify-content: space-between;+ gap: 40px;+}+.login-intro h1 {+ font-size: clamp(42px, 5vw, 68px);+ letter-spacing: -3px;+ margin: 22px 0;+ line-height: 1.07;+ color: #344b2c;+}+.login-intro p {+ max-width: 310px;+ color: var(--muted);+ font-size: 14px;+}+.login-decoration {+ max-width: 350px;+ margin-top: 40px;+ border: 1px solid #ced7bf;+ background: #f3f5eb;+ border-radius: 12px;+ padding: 24px;+ transform: rotate(-2deg);+}+.login-decoration > span {+ font-size: 10px;+ letter-spacing: 1px;+ color: #849372;+}+.login-decoration strong {+ display: flex;+ justify-content: space-between;+ font-size: 17px;+ font-weight: 500;+ margin: 16px 0 20px;+}+.decoration-line {+ border-top: 1px solid #dce3d0;+ margin-bottom: 13px;+}+.login-decoration small {+ font-size: 10px;+}+.login-form {+ display: grid;+ place-items: center;+ padding: 50px 35px;+ background: #fff;+}+.login-form > div {+ width: 100%;+ max-width: 340px;+}+.login-form h2 {+ font-size: 32px;+ margin: 14px 0;+ letter-spacing: -1px;+}+.login-form form {+ margin-top: 34px;+}+.wide {+ width: 100%;+ justify-content: space-between;+}+.fine-print {+ text-align: center;+ font-size: 10px;+ color: var(--muted);+ margin-top: 25px;+}+@media (max-width: 1000px) {+ .sidebar {+ width: 210px;+ padding-inline: 16px;+ }+ .content {+ padding: 32px 25px;+ }+ .topbar {+ padding: 0 25px;+ }+ .stats {+ gap: 10px;+ }+ .stat {+ padding: 20px;+ }+ .stat > strong {+ font-size: 26px;+ }+ .columns {+ grid-template-columns: 1fr;+ }+}+@media (max-width: 700px) {+ .shell {+ display: block;+ }+ .sidebar {+ position: static;+ height: auto;+ width: 100%;+ padding: 17px;+ border-right: 0;+ border-bottom: 1px solid #e4e7df;+ }+ .workspace,+ .nav-label {+ display: none;+ }+ .sidebar-bottom {+ border-top: 0;+ padding-top: 15px;+ margin-top: 0;+ }+ nav {+ display: flex;+ margin-top: 18px;+ justify-content: space-between;+ gap: 3px;+ }+ nav a {+ padding: 9px 6px;+ font-size: 11px;+ gap: 5px;+ }+ nav svg {+ width: 15px;+ }+ .topbar {+ height: 50px;+ padding: 0 20px;+ }+ .connection-dot {+ display: none;+ }+ .content {+ padding: 28px 18px;+ }+ .page-heading {+ align-items: flex-start;+ flex-direction: column;+ gap: 12px;+ margin-bottom: 25px;+ }+ .stats {+ grid-template-columns: 1fr;+ }+ .stat {+ padding: 18px;+ display: grid;+ grid-template-columns: 1fr auto;+ align-items: center;+ }+ .stat > strong {+ margin: 0;+ grid-column: 2;+ grid-row: 1 / 3;+ }+ .stat small {+ margin-top: 6px;+ }+ th,+ td {+ padding: 17px;+ }+ .bottom-note {+ align-items: flex-start;+ }+ .bottom-note a {+ display: none;+ }+ .padded {+ padding: 22px;+ }+ .login-shell {+ grid-template-columns: 1fr;+ }+ .login-intro {+ padding: 25px;+ }+ .login-intro > div,+ .login-intro > small {+ display: none;+ }+ .login-form {+ padding: 50px 30px;+ }+}diff --git a/examples/invoice-desk/app/server.mjs b/examples/invoice-desk/app/server.mjsnew file mode 100644index 000000000..967431755--- /dev/null+++ b/examples/invoice-desk/app/server.mjs@@ -0,0 +1,281 @@+import { createServer } from "node:http";+import { readFileSync, realpathSync } from "node:fs";+import { fileURLToPath } from "node:url";+import { createStore } from "./store.mjs";+import {+ publicUser,+ sessionUser,+ signIn,+ signOut,+ updateProfile,+} from "./accounts.mjs";+import {+ HttpError,+ addComment,+ approveInvoice,+ getInvoice,+ listInvoices,+ ownedInvoice,+ previewInvoice,+ sendInvoice,+ updateInvoice,+} from "./invoices.mjs";+import { importInvoice, updateImportPolicy } from "./imports.mjs";+import {+ connectionSettings,+ deliverInvoice,+ ledgerAccount,+ receivedDeliveries,+ supportReport,+} from "./integrations.mjs";+import {+ dashboardPage,+ importPage,+ integrationsPage,+ invoicePage,+ loginPage,+ profilePage,+} from "./views.mjs";++const assets = new Map([+ [+ "/styles.css",+ ["text/css", readFileSync(new URL("./public/styles.css", import.meta.url))],+ ],+ [+ "/client.js",+ [+ "text/javascript",+ readFileSync(new URL("./public/client.js", import.meta.url)),+ ],+ ],+]);++async function readBody(request) {+ if (!request.headers["content-type"]?.startsWith("application/json"))+ throw new HttpError(415, "Send a JSON document.");+ const chunks = [];+ for await (const chunk of request) chunks.push(chunk);+ let value;+ try {+ value = JSON.parse(Buffer.concat(chunks).toString("utf8"));+ } catch {+ throw new HttpError(400, "Invalid JSON document.");+ }+ if (!value || typeof value !== "object" || Array.isArray(value))+ throw new HttpError(400, "Send a JSON object.");+ return value;+}++function respond(+ response,+ status,+ value,+ type = "application/json",+ headers = {},+) {+ response.writeHead(status, {+ "Content-Type": `${type}; charset=utf-8`,+ "Cache-Control": "no-store",+ "X-Content-Type-Options": "nosniff",+ ...headers,+ });+ response.end(type === "application/json" ? JSON.stringify(value) : value);+}++export function createApp() {+ const store = createStore();+ const server = createServer(async (request, response) => {+ try {+ const path = new URL(request.url, "http://127.0.0.1").pathname;+ const method = request.method;+ if (method === "GET" && assets.has(path)) {+ const [type, content] = assets.get(path);+ return respond(response, 200, content, type);+ }+ if (method === "GET" && path === "/health")+ return respond(response, 200, { status: "ok" });+ if (method === "GET" && path === "/login")+ return respond(response, 200, loginPage(), "text/html");+ if (method === "POST" && path === "/api/login") {+ const body = await readBody(request);+ const token = signIn(store, body.email, body.password);+ if (!token) throw new HttpError(401, "Email or password is incorrect.");+ return respond(response, 200, { redirect: "/" }, "application/json", {+ "Set-Cookie": `session=${token}; HttpOnly; SameSite=Strict; Path=/; Max-Age=28800`,+ });+ }+ if (method === "GET" && path === "/api/ledger/account") {+ return respond(+ response,+ 200,+ ledgerAccount(+ store,+ request.headers.authorization?.replace(/^Bearer /, ""),+ ),+ );+ }+ const user = sessionUser(store, request.headers.cookie);+ if (!user) {+ if (method === "GET" && !path.startsWith("/api/"))+ return respond(response, 302, "", "text/plain", {+ Location: "/login",+ });+ throw new HttpError(401, "Sign in to continue.");+ }+ const workspace = store.workspaces.get(user.workspaceId);+ if (method === "POST" && path === "/api/logout") {+ await readBody(request);+ signOut(store, request.headers.cookie);+ return respond(+ response,+ 200,+ { redirect: "/login" },+ "application/json",+ {+ "Set-Cookie":+ "session=; HttpOnly; SameSite=Strict; Path=/; Max-Age=0",+ },+ );+ }+ if (method === "GET" && path === "/")+ return respond(+ response,+ 200,+ dashboardPage(user, workspace, listInvoices(store, user)),+ "text/html",+ );+ if (method === "GET" && path === "/imports")+ return respond(response, 200, importPage(user, workspace), "text/html");+ if (method === "GET" && path === "/integrations")+ return respond(+ response,+ 200,+ integrationsPage(+ user,+ workspace,+ connectionSettings(store, user),+ receivedDeliveries(store, user),+ ),+ "text/html",+ );+ if (method === "GET" && path === "/profile")+ return respond(+ response,+ 200,+ profilePage(user, workspace),+ "text/html",+ );+ const page = path.match(/^\/invoices\/([^/]+)$/);+ if (method === "GET" && page)+ return respond(+ response,+ 200,+ invoicePage(user, workspace, ownedInvoice(store, user, page[1])),+ "text/html",+ );+ if (method === "GET" && path === "/api/me")+ return respond(response, 200, publicUser(user));+ if (method === "PATCH" && path === "/api/profile")+ return respond(+ response,+ 200,+ updateProfile(user, await readBody(request)),+ );+ if (method === "GET" && path === "/api/invoices")+ return respond(response, 200, listInvoices(store, user));+ if (method === "GET" && path === "/api/import-policy")+ return respond(response, 200, workspace.importPolicy);+ if (method === "PATCH" && path === "/api/import-policy")+ return respond(+ response,+ 200,+ updateImportPolicy(+ store,+ user,+ (await readBody(request)).maxAmountCents,+ ),+ );+ if (method === "POST" && path === "/api/imports")+ return respond(+ response,+ 201,+ importInvoice(store, user, await readBody(request)),+ );+ if (method === "GET" && path === "/api/integrations")+ return respond(response, 200, connectionSettings(store, user));+ if (method === "GET" && path === "/api/integrations/inbox")+ return respond(response, 200, receivedDeliveries(store, user));+ if (method === "POST" && path === "/api/integrations/deliver") {+ const body = await readBody(request);+ return respond(+ response,+ 201,+ deliverInvoice(store, user, body.invoiceId, body.destination),+ );+ }+ if (method === "GET" && path === "/api/support-report")+ return respond(+ response,+ 200,+ supportReport(store, user),+ "application/json",+ {+ "Content-Disposition": 'attachment; filename="support-report.json"',+ },+ );+ const invoice = path.match(+ /^\/api\/invoices\/([^/]+)(?:\/(preview|approve|send|comments))?$/,+ );+ if (invoice) {+ const [, id, action] = invoice;+ if (method === "GET" && !action)+ return respond(response, 200, getInvoice(store, id));+ if (method === "PATCH" && !action)+ return respond(+ response,+ 200,+ updateInvoice(store, user, id, await readBody(request)),+ );+ if (method === "GET" && action === "preview")+ return respond(response, 200, previewInvoice(store, user, id));+ if (method === "POST") {+ const body = await readBody(request);+ if (action === "approve")+ return respond(response, 200, approveInvoice(store, user, id));+ if (action === "send")+ return respond(response, 200, sendInvoice(store, user, id));+ if (action === "comments")+ return respond(+ response,+ 201,+ addComment(store, user, id, body.body),+ );+ }+ }+ throw new HttpError(404, "Page not found.");+ } catch (error) {+ respond(response, error instanceof HttpError ? error.status : 500, {+ error:+ error instanceof HttpError+ ? error.message+ : "The request could not be completed.",+ });+ }+ });+ return server;+}++if (+ process.argv[1] &&+ realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)+) {+ const server = createApp();+ server.listen(Number(process.env.PORT ?? 4310), "127.0.0.1", () => {+ console.log(+ `Invoice Desk is running at http://127.0.0.1:${server.address().port}`,+ );+ });+ for (const signal of ["SIGINT", "SIGTERM"])+ process.once(signal, () => server.close());+}diff --git a/examples/invoice-desk/app/store.mjs b/examples/invoice-desk/app/store.mjsnew file mode 100644index 000000000..d1cededbc--- /dev/null+++ b/examples/invoice-desk/app/store.mjs@@ -0,0 +1,103 @@+import { randomBytes, scryptSync } from "node:crypto";++export function passwordRecord(password) {+ const salt = randomBytes(16).toString("hex");+ return { salt, hash: scryptSync(password, salt, 32).toString("hex") };+}++export function createStore() {+ const importDefaults = { limits: { maxAmountCents: 100_000 } };+ const workspace = (id, name, settlementBalanceCents) => ({+ id,+ name,+ importPolicy: { ...importDefaults },+ connector: {+ destination: "ledger",+ accessToken: randomBytes(24).toString("hex"),+ },+ ledger: { settlementBalanceCents },+ });+ const user = (id, email, password, workspaceId, name, role) => ({+ id,+ email,+ workspaceId,+ password: passwordRecord(password),+ profile: { name, role },+ });+ const invoice = (id, workspaceId, reference, customer, amountCents) => ({+ id,+ workspaceId,+ reference,+ customer,+ amountCents,+ version: 1,+ approval: null,+ status: "draft",+ comments: [],+ });+ return {+ workspaces: new Map([+ ["north", workspace("north", "North Studio", 314_200)],+ ["cedar", workspace("cedar", "Cedar Workshop", 89_200)],+ ]),+ users: new Map([+ [+ "alex",+ user(+ "alex",+ "[email protected]",+ "river-orchard-24",+ "north",+ "Alex",+ "member",+ ),+ ],+ [+ "jules",+ user(+ "jules",+ "[email protected]",+ "meadow-paper-56",+ "north",+ "Jules",+ "admin",+ ),+ ],+ [+ "sam",+ user(+ "sam",+ "[email protected]",+ "cedar-window-81",+ "cedar",+ "Sam",+ "admin",+ ),+ ],+ ]),+ invoices: new Map([+ [+ "inv-north-1",+ invoice("inv-north-1", "north", "INV-1001", "Aster Design", 48_500),+ ],+ [+ "inv-north-2",+ invoice("inv-north-2", "north", "INV-1002", "Paper Finch", 72_000),+ ],+ [+ "inv-cedar-1",+ invoice("inv-cedar-1", "cedar", "INV-1001", "Willow Office", 93_000),+ ],+ ]),+ destinations: new Map([+ ["ledger", { id: "ledger", name: "Ledger", ownerWorkspaceId: null }],+ [+ "archive",+ { id: "archive", name: "Cedar Archive", ownerWorkspaceId: "cedar" },+ ],+ ]),+ sessions: new Map(),+ previews: new Map(),+ deliveries: [],+ };+}diff --git a/examples/invoice-desk/app/views.mjs b/examples/invoice-desk/app/views.mjsnew file mode 100644index 000000000..78d1840ef--- /dev/null+++ b/examples/invoice-desk/app/views.mjs@@ -0,0 +1,119 @@+function h(value) {+ return String(value).replace(+ /[&<>"']/g,+ (character) =>+ ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[+ character+ ],+ );+}++const money = (amount) =>+ new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" }).format(+ amount / 100,+ );+const badge = (status) =>+ `<span class="badge ${h(status)}">${h(status)}</span>`;+const icon = (name) => {+ const paths = {+ invoices:+ '<rect x="5" y="3" width="14" height="18" rx="2"/><path d="M9 8h6M9 12h6M9 16h3"/>',+ imports: '<path d="M12 3v12m-4-4 4 4 4-4M4 16v4h16v-4"/>',+ integrations:+ '<rect x="3" y="3" width="7" height="7" rx="2"/><rect x="14" y="14" width="7" height="7" rx="2"/><path d="M14 6h4v8M10 18H6v-8"/>',+ profile:+ '<circle cx="12" cy="8" r="4"/><path d="M4 21v-2a8 8 0 0 1 16 0v2"/>',+ };+ return `<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6">${paths[name]}</svg>`;+};++function document(title, body) {+ return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${h(title)} · Invoice Desk</title><link rel="stylesheet" href="/styles.css"><script src="/client.js" defer></script></head><body>${body}<div id="notice" role="status" aria-live="polite" hidden></div></body></html>`;+}++function layout(title, active, user, workspace, content) {+ const links = [+ ["invoices", "/", "Invoices"],+ ["imports", "/imports", "Imports"],+ ["integrations", "/integrations", "Connections"],+ ["profile", "/profile", "My account"],+ ];+ return document(+ title,+ `<div class="shell"><aside class="sidebar"><a class="brand" href="/"><span class="brand-mark">id.</span> Invoice Desk</a><div class="workspace"><span class="workspace-mark">${h(workspace.name[0])}</span><div><strong>${h(workspace.name)}</strong><small>Workspace</small></div></div><div class="nav-label">WORKSPACE</div><nav aria-label="Main navigation">${links.map(([name, href, label]) => `<a href="${href}" ${active === name ? 'aria-current="page"' : ""}>${icon(name)}${label}</a>`).join("")}</nav><div class="sidebar-bottom"><span class="avatar">${h(String(user.profile.name)[0])}</span><div><strong>${h(user.profile.name)}</strong><small>${h(user.profile.role)}</small></div><form data-action="/api/logout"><button class="logout" aria-label="Sign out" title="Sign out">↗</button></form></div></aside><main><header class="topbar"><span>${h(workspace.name)} <span class="slash">/</span> ${h(title)}</span><span class="connection-dot">Workspace connected</span></header><div class="content">${content}</div></main></div>`,+ );+}++export function loginPage() {+ return document(+ "Sign in",+ `<div class="login-shell"><section class="login-intro"><a class="brand" href="/"><span class="brand-mark">id.</span> Invoice Desk</a><div><span class="eyebrow">LESS ADMIN. MORE CLARITY.</span><h1>Good work.<br>Clear invoices.</h1><p>Keep your invoices, approvals, and connections in one place.</p><div class="login-decoration" aria-hidden="true"><span>INV-1001</span><strong>Ready for review <span>↗</span></strong><div class="decoration-line"></div><small>One workspace. Everything in order.</small></div></div><small>Built for teams that make things.</small></section><section class="login-form"><div><span class="eyebrow">YOUR WORKSPACE AWAITS</span><h2>Welcome back</h2><p class="muted">Sign in to pick up where you left off.</p><form data-action="/api/login"><label>Email address<input name="email" type="email" autocomplete="username" placeholder="[email protected]" required></label><label>Password<input name="password" type="password" autocomplete="current-password" required></label><button class="button primary wide">Sign in <span>→</span></button></form><p class="fine-print">Your team’s invoices, thoughtfully organized.</p></div></section></div>`,+ );+}++export function dashboardPage(user, workspace, invoices) {+ const drafts = invoices.filter((invoice) => invoice.status === "draft");+ return layout(+ "Invoices",+ "invoices",+ user,+ workspace,+ `<div class="page-heading"><div><span class="eyebrow">THE BIG PICTURE</span><h1>Your invoices, in order.</h1><p class="muted">A little less paperwork. A little more headspace.</p></div><a class="button primary" href="/imports">+ Import invoice</a></div><div class="stats"><section class="stat"><span>Total invoiced</span><strong>${money(invoices.reduce((sum, invoice) => sum + invoice.amountCents, 0))}</strong><small>Across ${invoices.length} invoices</small></section><section class="stat"><span>Awaiting approval</span><strong>${drafts.length.toString().padStart(2, "0")}</strong><small>Ready for a closer look</small></section><section class="stat"><span>Sent to clients</span><strong>${invoices+ .filter((invoice) => invoice.status === "sent")+ .length.toString()+ .padStart(+ 2,+ "0",+ )}</strong><small>Moving things forward</small></section></div><section class="panel"><div class="panel-heading"><h2>All invoices <span class="count">${invoices.length}</span></h2><span class="muted small">Amounts in USD</span></div><div class="table-wrap"><table><thead><tr><th>Invoice</th><th>Client</th><th>Status</th><th class="numeric">Amount</th><th><span class="sr-only">Open</span></th></tr></thead><tbody>${invoices.map((invoice) => `<tr><td><a class="invoice-link" href="/invoices/${encodeURIComponent(invoice.id)}">${h(invoice.reference)}</a><small>Version ${invoice.version}</small></td><td>${h(invoice.customer)}</td><td>${badge(invoice.status)}</td><td class="numeric amount">${money(invoice.amountCents)}</td><td><a class="row-arrow" aria-label="Open ${h(invoice.reference)}" href="/invoices/${encodeURIComponent(invoice.id)}">↗</a></td></tr>`).join("")}</tbody></table></div></section><div class="bottom-note"><span class="note-icon">↳</span><p><strong>Everything starts with a clear handoff.</strong><br>Import an invoice, get it approved, and send it on its way.</p><a href="/integrations">Manage connections →</a></div>`,+ );+}++export function invoicePage(user, workspace, invoice) {+ const api = `/api/invoices/${encodeURIComponent(invoice.id)}`;+ return layout(+ invoice.reference,+ "invoices",+ user,+ workspace,+ `<a class="back-link" href="/">← All invoices</a><div class="page-heading"><div><span class="eyebrow">INVOICE DETAILS</span><h1>${h(invoice.reference)} ${badge(invoice.status)}</h1><p class="muted">${h(invoice.customer)} · Version ${invoice.version}</p></div><button class="button" data-preview="${api}/preview">Preview</button></div><div class="columns"><section class="panel padded"><h2>Invoice information</h2><form data-action="${api}" data-method="PATCH"><label>Client<input name="customer" value="${h(invoice.customer)}" required></label><label>Amount in cents<input name="amountCents" type="number" min="1" step="1" value="${invoice.amountCents}" required><small>${money(invoice.amountCents)} USD</small></label><button class="button primary">Save changes</button></form></section><section class="panel padded"><h2>Approval & delivery</h2><p class="muted">${invoice.approval ? `Approved by ${h(invoice.approval.userId)} on version ${invoice.approval.version}.` : "An administrator can approve this invoice when it is ready."}</p><div class="actions">${user.profile.role === "admin" ? `<form data-action="${api}/approve"><button class="button">Approve invoice</button></form>` : ""}<form data-action="${api}/send"><button class="button primary">Send invoice</button></form></div><hr><h3>Send a copy to a connection</h3><form data-action="/api/integrations/deliver" data-stay><input name="invoiceId" type="hidden" value="${h(invoice.id)}"><label>Destination<select name="destination"><option value="ledger">Ledger</option><option value="archive">Cedar Archive</option></select></label><button class="button">Deliver copy</button></form></section></div><section class="panel padded notes"><h2>Notes <span class="count">${invoice.comments.length}</span></h2>${invoice.comments.length ? invoice.comments.map((comment) => `<article class="comment"><strong>${h(comment.author)}</strong><div class="comment-body">${comment.body}</div></article>`).join("") : '<p class="muted">Keep the conversation close to the work.</p>'}<form data-action="${api}/comments"><label>Add a note<textarea name="body" rows="3" placeholder="Leave an update for your team…" required></textarea></label><button class="button primary">Post note</button></form></section><dialog id="preview-dialog" aria-labelledby="preview-title"><div class="panel-heading"><h2 id="preview-title">Invoice preview</h2><button class="button" data-close>Close</button></div><div class="preview-body"></div></dialog>`,+ );+}++export function importPage(user, workspace) {+ const document = {+ schemaVersion: "1",+ workspaceId: workspace.id,+ invoice: {+ reference: "INV-1003",+ customer: "Field Studio",+ amountCents: 25_000,+ },+ };+ return layout(+ "Imports",+ "imports",+ user,+ workspace,+ `<div class="page-heading"><div><span class="eyebrow">A FRESH START</span><h1>Bring your work together.</h1><p class="muted">Import an invoice from a connected billing workflow.</p></div></div><div class="columns"><section class="panel padded"><h2>Import invoice</h2><p class="muted">Paste a version 1 invoice document. Amounts are in cents.</p><form data-action="/api/imports" data-document><label>Invoice document<textarea class="code-input" name="document" rows="14" spellcheck="false" required>${h(JSON.stringify(document, null, 2))}</textarea></label><button class="button primary">Review & import</button></form></section><section class="panel padded align-start"><h2>Workspace policy</h2><p class="muted">Invoices above the import limit require a separate review.</p><div class="policy-value">${money(workspace.importPolicy.limits.maxAmountCents)}<small>Current import limit</small></div>${user.profile.role === "admin" ? `<form data-action="/api/import-policy" data-method="PATCH"><label>Import limit in cents<input name="maxAmountCents" type="number" min="1" step="1" value="${workspace.importPolicy.limits.maxAmountCents}" required></label><button class="button">Update policy</button></form>` : '<p class="muted small">Ask a workspace administrator to update this policy.</p>'}</section></div>`,+ );+}++export function integrationsPage(user, workspace, settings, deliveries) {+ return layout(+ "Connections",+ "integrations",+ user,+ workspace,+ `<div class="page-heading"><div><span class="eyebrow">BETTER TOGETHER</span><h1>Keep everything connected.</h1><p class="muted">Move invoice details between the tools your team uses.</p></div></div><div class="columns"><section class="panel padded"><div class="connection-card"><span class="service-icon">L</span><div><h2>Ledger</h2><p class="muted">Accounting connection</p></div><span class="badge approved">Connected</span></div><p class="muted">Your workspace account is connected. Send a copy from any invoice to record a delivery.</p><p class="small">Default destination: <strong>${h(settings.destination)}</strong></p></section><section class="panel padded"><span class="eyebrow">NEED A HAND?</span><h2>Connection diagnostics</h2><p class="muted">Download your workspace’s connection details and current policy to help troubleshoot a delivery.</p><a class="button" href="/api/support-report" download>Download support report ↗</a></section></div><section class="panel padded notes"><h2>Received deliveries <span class="count">${deliveries.length}</span></h2><p class="muted">Requests received by connections owned by your workspace.</p>${deliveries.length ? deliveries.map((delivery) => `<details><summary>${h(delivery.invoice.reference)} · ${h(delivery.workspaceId)}</summary><pre>${h(JSON.stringify(delivery, null, 2))}</pre></details>`).join("") : '<div class="empty-state">No deliveries yet. They will appear here when a connection receives an invoice.</div>'}</section>`,+ );+}++export function profilePage(user, workspace) {+ return layout(+ "My account",+ "profile",+ user,+ workspace,+ `<div class="page-heading"><div><span class="eyebrow">THE PERSON BEHIND THE WORK</span><h1>Make yourself at home.</h1><p class="muted">Manage how you appear to your team.</p></div></div><section class="panel padded profile-panel"><h2>Profile details</h2><p class="muted">${h(user.email)} · ${h(user.profile.role)}</p><form data-action="/api/profile" data-method="PATCH"><label>Display name<input name="name" value="${h(user.profile.name)}" required></label><button class="button primary">Save profile</button></form></section>`,+ );+}diff --git a/examples/invoice-desk/qa/README.md b/examples/invoice-desk/qa/README.mdnew file mode 100644index 000000000..37b3d9470--- /dev/null+++ b/examples/invoice-desk/qa/README.md@@ -0,0 +1,75 @@+# Invoice Desk QA++Invoice Desk is an intentionally vulnerable sample. This directory is the answer+key and HTTP harness; it must stay outside the application source given to the+scanner. The application contains no QA-specific branches or vulnerability labels.++## Expected scenarios++| ID | Category | Application feature |+| ------ | ----------------------------------- | ------------------------------------------------------------------- |+| ID-001 | Secret exposure | Support report discloses a usable, process-local connector token. |+| ID-002 | Broken object authorization | Invoice API reads cross a workspace boundary. |+| ID-003 | Cross-tenant cache leakage | Authorized preview requests share cached content across workspaces. |+| ID-004 | Stale approval | Editing an invoice leaves an earlier version's approval usable. |+| ID-005 | Fail-open validation | An unavailable import reviewer permits an over-limit invoice. |+| ID-006 | Credential destination confusion | A different connection owner receives the Ledger credential. |+| ID-007 | Shared mutable security policy | Changing one workspace's nested policy changes another's. |+| ID-008 | Validation and consumption mismatch | Import checks and persistence select different ownership metadata. |+| ID-009 | Mass assignment | Profile updates reach the administrative role. |+| ID-010 | Stored HTML injection | Notes become unescaped HTML in another user's invoice view. |++These are ten distinct root causes, not ten disjoint OWASP Top Ten groups. Some+share broader authorization or disclosure classifications. The manifest gives+suggested CWE tags and source symbols; equivalent, more precise classifications+are acceptable. Multiple reports of the same root cause count once.++The approval case is a deterministic version-binding error, not a timing race.+The import mismatch uses outer document metadata and nested invoice metadata;+it needs no custom parser, proxy, or request-smuggling infrastructure. Connector+destinations are in-process adapters with distinct owners, not arbitrary URLs.+The HTML test uses inert formatting markup, with no executable payloads.++## Running the harness++From the repository root:++```bash+node --test examples/invoice-desk/qa/app.test.mjs+```++Each test creates its own application, port, users, policies, and fresh connector+credentials. Tests do not connect to an existing server or accept external+targets. All state is discarded when the server closes.++The suite also checks ordinary pages, authentication, logout, scoped writes,+administrator checks, normal imports and approvals, safe settings output,+escaped customer names, and clean state on restart. These checks catch unrelated+regressions that could distort the finding count.++## Scanner evaluation++Keep the scanner input restricted to a standalone copy of `../app`. Record the+application revision or content digest, scanner version, model, mode, and effort+alongside each result. Application behavior is deterministic apart from IDs,+session tokens, and timestamps; model discovery remains variable.++Evaluate each scenario as **found**, **missed**, or **uncertain**, based on the+actual root cause and affected feature. Track unexpected findings and duplicate+reports separately. Treat unexpected findings as needing review rather than+automatically declaring them false positives.++For secret exposure, a report should identify the server credential crossing a+boundary. Merely flagging the fixed QA login accounts is not a match for ID-001.+The support report and wrong-destination delivery are distinct root causes with+independent remedies, even though they expose the same class of token. Both tests+confirm that the disclosed token grants access to a synthetic settlement balance+that is absent from the ordinary invoice and connection views.++Some controls and finding scenarios share application features. Read a report's+claimed boundary carefully: an ownership check on preview requests does not+remove the separate cache-isolation defect. Run the harness after changes to+confirm that all ten intended scenarios are still reachable.++No model scan runs as part of this HTTP suite, and no detection score is asserted+until actual scanner output has been reviewed.diff --git a/examples/invoice-desk/qa/app.test.mjs b/examples/invoice-desk/qa/app.test.mjsnew file mode 100644index 000000000..492d3f2f6--- /dev/null+++ b/examples/invoice-desk/qa/app.test.mjs@@ -0,0 +1,582 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import { test } from "node:test";+import { cp, mkdtemp, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { spawn } from "node:child_process";+import { once } from "node:events";+import { createApp } from "../app/server.mjs";++const accounts = {+ alex: ["[email protected]", "river-orchard-24"],+ jules: ["[email protected]", "meadow-paper-56"],+ sam: ["[email protected]", "cedar-window-81"],+};+const manifest = JSON.parse(+ readFileSync(new URL("./expected-findings.json", import.meta.url), "utf8"),+);+const registered = new Set();++async function app(t) {+ const server = createApp();+ await new Promise((resolve, reject) => {+ server.once("error", reject);+ server.listen(0, "127.0.0.1", resolve);+ });+ t.after(+ () =>+ new Promise((resolve, reject) => {+ server.closeAllConnections();+ server.close((error) => (error ? reject(error) : resolve()));+ }),+ );+ const origin = `http://127.0.0.1:${server.address().port}`;+ const request = async (+ path,+ { method = "GET", body, cookie, headers = {} } = {},+ ) => {+ const response = await fetch(`${origin}${path}`, {+ method,+ redirect: "manual",+ headers: {+ ...(body === undefined ? {} : { "Content-Type": "application/json" }),+ ...(cookie ? { Cookie: cookie } : {}),+ ...headers,+ },+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),+ });+ const text = await response.text();+ return {+ status: response.status,+ headers: response.headers,+ body: response.headers.get("content-type")?.startsWith("application/json")+ ? JSON.parse(text)+ : text,+ };+ };+ const login = async (name) => {+ const [email, password] = accounts[name];+ const response = await request("/api/login", {+ method: "POST",+ body: { email, password },+ });+ assert.equal(response.status, 200);+ const cookie = response.headers.get("set-cookie").split(";")[0];+ return (path, options = {}) => request(path, { ...options, cookie });+ };+ return { request, login };+}++function scenario(id, run) {+ const expected = manifest.findings.find((finding) => finding.id === id);+ assert.ok(expected, `Missing manifest entry: ${id}`);+ assert.ok(!registered.has(id), `Duplicate scenario: ${id}`);+ registered.add(id);+ test(`${id}: ${expected.category}`, run);+}++function invoiceDocument(workspaceId, amountCents = 25_000) {+ return {+ schemaVersion: "1",+ workspaceId,+ invoice: { customer: "Garden Office", amountCents },+ };+}++scenario("ID-001", async (t) => {+ const { login, request } = await app(t);+ const alex = await login("alex");+ const settings = await alex("/api/integrations");+ assert.equal(settings.body.accessToken, undefined);+ const report = await alex("/api/support-report");+ assert.equal(report.status, 200);+ const token = report.body.connector.accessToken;+ assert.ok(token);+ const account = await request("/api/ledger/account", {+ headers: { Authorization: `Bearer ${token}` },+ });+ assert.equal(account.status, 200);+ assert.equal(account.body.workspaceId, "north");+ assert.equal(account.body.settlementBalanceCents, 314_200);+ assert.equal((await request("/api/ledger/account")).status, 401);+});++scenario("ID-002", async (t) => {+ const { login } = await app(t);+ const alex = await login("alex");+ assert.ok(+ (await alex("/api/invoices")).body.every(+ (invoice) => invoice.workspaceId === "north",+ ),+ );+ const other = await alex("/api/invoices/inv-cedar-1");+ assert.equal(other.status, 200);+ assert.equal(other.body.workspaceId, "cedar");+});++scenario("ID-003", async (t) => {+ const { login } = await app(t);+ const alex = await login("alex");+ const sam = await login("sam");+ const first = await alex("/api/invoices/inv-north-1/preview");+ const second = await sam("/api/invoices/inv-cedar-1/preview");+ const own = await sam("/api/invoices/inv-cedar-1");+ assert.equal(second.status, 200);+ assert.deepEqual(second.body, first.body);+ assert.notEqual(second.body.customer, own.body.customer);+ assert.notEqual(second.body.amountCents, own.body.amountCents);+});++scenario("ID-004", async (t) => {+ const { login } = await app(t);+ const alex = await login("alex");+ const jules = await login("jules");+ const approved = await jules("/api/invoices/inv-north-1/approve", {+ method: "POST",+ body: {},+ });+ assert.equal(approved.status, 200);+ const changed = await alex("/api/invoices/inv-north-1", {+ method: "PATCH",+ body: { amountCents: 98_000 },+ });+ assert.equal(changed.status, 200);+ assert.notEqual(changed.body.version, changed.body.approval.version);+ const sent = await alex("/api/invoices/inv-north-1/send", {+ method: "POST",+ body: {},+ });+ assert.equal(sent.status, 200);+ assert.equal(sent.body.amountCents, 98_000);+ assert.equal(sent.body.status, "sent");+});++scenario("ID-005", async (t) => {+ const { login } = await app(t);+ const alex = await login("alex");+ const document = invoiceDocument("north", 150_000);+ assert.equal(+ (await alex("/api/imports", { method: "POST", body: document })).status,+ 422,+ );+ document.schemaVersion = "2";+ const imported = await alex("/api/imports", {+ method: "POST",+ body: document,+ });+ assert.equal(imported.status, 201);+ assert.equal(imported.body.invoice.amountCents, 150_000);+ assert.equal(imported.body.review.approved, true);+ assert.ok(imported.body.review.warning);+});++scenario("ID-006", async (t) => {+ const { login, request } = await app(t);+ const alex = await login("alex");+ const sam = await login("sam");+ assert.equal(+ (+ await alex("/api/integrations/deliver", {+ method: "POST",+ body: { invoiceId: "inv-north-1", destination: "ledger" },+ })+ ).status,+ 201,+ );+ assert.deepEqual((await sam("/api/integrations/inbox")).body, []);+ assert.equal(+ (+ await alex("/api/integrations/deliver", {+ method: "POST",+ body: { invoiceId: "inv-north-1", destination: "archive" },+ })+ ).status,+ 201,+ );+ const inbox = await sam("/api/integrations/inbox");+ assert.equal(inbox.body.length, 1);+ const account = await request("/api/ledger/account", {+ headers: { Authorization: `Bearer ${inbox.body[0].credential}` },+ });+ assert.equal(account.status, 200);+ assert.equal(account.body.workspaceId, "north");+ assert.equal(account.body.settlementBalanceCents, 314_200);+ assert.deepEqual((await alex("/api/integrations/inbox")).body, []);+});++scenario("ID-007", async (t) => {+ const { login } = await app(t);+ const jules = await login("jules");+ const sam = await login("sam");+ const document = invoiceDocument("cedar", 150_000);+ assert.equal(+ (await sam("/api/imports", { method: "POST", body: document })).status,+ 422,+ );+ assert.equal(+ (+ await jules("/api/import-policy", {+ method: "PATCH",+ body: { maxAmountCents: 200_000 },+ })+ ).status,+ 200,+ );+ assert.equal(+ (await sam("/api/import-policy")).body.limits.maxAmountCents,+ 200_000,+ );+ assert.equal(+ (await sam("/api/imports", { method: "POST", body: document })).status,+ 201,+ );+});++scenario("ID-008", async (t) => {+ const { login } = await app(t);+ const alex = await login("alex");+ const sam = await login("sam");+ assert.equal(+ (+ await alex("/api/imports", {+ method: "POST",+ body: invoiceDocument("cedar"),+ })+ ).status,+ 403,+ );+ const document = invoiceDocument("north");+ document.invoice.workspaceId = "cedar";+ const imported = await alex("/api/imports", {+ method: "POST",+ body: document,+ });+ assert.equal(imported.status, 201);+ assert.equal(imported.body.invoice.workspaceId, "cedar");+ assert.ok(+ (await sam("/api/invoices")).body.some(+ (invoice) => invoice.id === imported.body.invoice.id,+ ),+ );+ assert.ok(+ !(await alex("/api/invoices")).body.some(+ (invoice) => invoice.id === imported.body.invoice.id,+ ),+ );+});++scenario("ID-009", async (t) => {+ const { login } = await app(t);+ const alex = await login("alex");+ assert.equal(+ (+ await alex("/api/invoices/inv-north-1/approve", {+ method: "POST",+ body: {},+ })+ ).status,+ 403,+ );+ const profile = await alex("/api/profile", {+ method: "PATCH",+ body: { name: "Alex", role: "admin" },+ });+ assert.equal(profile.status, 200);+ assert.equal((await alex("/api/me")).body.profile.role, "admin");+ assert.equal(+ (+ await alex("/api/invoices/inv-north-1/approve", {+ method: "POST",+ body: {},+ })+ ).status,+ 200,+ );+});++scenario("ID-010", async (t) => {+ const { login } = await app(t);+ const alex = await login("alex");+ const jules = await login("jules");+ const markup = '<strong data-note="formatting">Account update</strong>';+ assert.equal(+ (+ await alex("/api/invoices/inv-north-1/comments", {+ method: "POST",+ body: { body: markup },+ })+ ).status,+ 201,+ );+ const page = await jules("/invoices/inv-north-1");+ assert.equal(page.status, 200);+ assert.ok(page.body.includes(`<div class="comment-body">${markup}</div>`));+ await alex("/api/invoices/inv-north-1", {+ method: "PATCH",+ body: { customer: '<em data-client="name">Client</em>' },+ });+ assert.ok(+ (await jules("/invoices/inv-north-1")).body.includes(+ "<em data-client="name">Client</em>",+ ),+ );+});++test("manifest accounts for all ten separately exercised scenarios", () => {+ assert.equal(manifest.findings.length, 10);+ assert.deepEqual(+ new Set(manifest.findings.map((finding) => finding.id)),+ registered,+ );+ assert.equal(+ new Set(manifest.findings.map((finding) => finding.category)).size,+ 10,+ );+});++test(+ "a standalone app copy starts without its parent or QA directory",+ { timeout: 10_000 },+ async (t) => {+ const directory = await mkdtemp(join(tmpdir(), "invoice-desk-"));+ let child;+ t.after(async () => {+ if (child && child.exitCode === null && child.signalCode === null) {+ const exited = once(child, "exit");+ child.kill("SIGTERM");+ await exited;+ }+ await rm(directory, { recursive: true, force: true });+ });+ await cp(new URL("../app/", import.meta.url), directory, {+ recursive: true,+ });+ child = spawn(process.execPath, [join(directory, "server.mjs")], {+ cwd: directory,+ env: { PORT: "0" },+ stdio: ["ignore", "pipe", "pipe"],+ });+ const origin = await new Promise((resolve, reject) => {+ let output = "";+ let errors = "";+ child.stderr.on("data", (chunk) => {+ errors += chunk;+ });+ child.stdout.on("data", (chunk) => {+ output += chunk;+ const match = output.match(/http:\/\/127\.0\.0\.1:\d+/);+ if (match) resolve(match[0]);+ });+ child.once("error", reject);+ child.once("exit", (code) =>+ reject(new Error(`App exited ${code}: ${errors}`)),+ );+ });+ const health = await fetch(`${origin}/health`);+ assert.deepEqual(await health.json(), { status: "ok" });+ const login = await fetch(`${origin}/login`);+ assert.equal(login.status, 200);+ assert.ok((await login.text()).includes("Invoice Desk"));+ },+);++test("invoice previews refresh when the invoice version changes", async (t) => {+ const { login } = await app(t);+ const alex = await login("alex");+ assert.equal(+ (await alex("/api/invoices/inv-north-1/preview")).body.amountCents,+ 48_500,+ );+ await alex("/api/invoices/inv-north-1", {+ method: "PATCH",+ body: { amountCents: 49_000 },+ });+ assert.equal(+ (await alex("/api/invoices/inv-north-1/preview")).body.amountCents,+ 49_000,+ );+});++test("health, static assets, and every ordinary page are served", async (t) => {+ const { request, login } = await app(t);+ assert.deepEqual((await request("/health")).body, { status: "ok" });+ assert.equal((await request("/")).status, 302);+ for (const path of ["/login", "/styles.css", "/client.js"])+ assert.equal((await request(path)).status, 200);+ const alex = await login("alex");+ for (const path of [+ "/",+ "/invoices/inv-north-1",+ "/imports",+ "/integrations",+ "/profile",+ ]) {+ const response = await alex(path);+ assert.equal(response.status, 200);+ assert.ok(response.body.includes("Invoice Desk"));+ }+});++test("anonymous callers and incorrect passwords do not authenticate", async (t) => {+ const { request } = await app(t);+ assert.equal((await request("/api/invoices")).status, 401);+ assert.equal(+ (+ await request("/api/login", {+ method: "POST",+ body: { email: accounts.alex[0], password: "incorrect" },+ })+ ).status,+ 401,+ );+ const login = await request("/api/login", {+ method: "POST",+ body: { email: accounts.alex[0], password: accounts.alex[1] },+ });+ assert.match(login.headers.get("set-cookie"), /HttpOnly; SameSite=Strict/);+});++test("scoped writes, previews, HTML pages, and connector deliveries reject another workspace", async (t) => {+ const { login } = await app(t);+ const alex = await login("alex");+ assert.equal(+ (+ await alex("/api/invoices/inv-cedar-1", {+ method: "PATCH",+ body: { amountCents: 1 },+ })+ ).status,+ 404,+ );+ assert.equal(+ (+ await alex("/api/invoices/inv-cedar-1/comments", {+ method: "POST",+ body: { body: "Hello" },+ })+ ).status,+ 404,+ );+ assert.equal((await alex("/api/invoices/inv-cedar-1/preview")).status, 404);+ assert.equal((await alex("/invoices/inv-cedar-1")).status, 404);+ assert.equal(+ (+ await alex("/api/integrations/deliver", {+ method: "POST",+ body: { invoiceId: "inv-cedar-1", destination: "ledger" },+ })+ ).status,+ 404,+ );+});++test("normal approval and delivery work, and unapproved invoices cannot be sent", async (t) => {+ const { login } = await app(t);+ const alex = await login("alex");+ const jules = await login("jules");+ assert.equal(+ (await alex("/api/invoices/inv-north-1/send", { method: "POST", body: {} }))+ .status,+ 409,+ );+ assert.equal(+ (+ await alex("/api/import-policy", {+ method: "PATCH",+ body: { maxAmountCents: 200_000 },+ })+ ).status,+ 403,+ );+ assert.equal(+ (+ await jules("/api/invoices/inv-north-1/approve", {+ method: "POST",+ body: {},+ })+ ).status,+ 200,+ );+ const sent = await alex("/api/invoices/inv-north-1/send", {+ method: "POST",+ body: {},+ });+ assert.equal(sent.status, 200);+ assert.equal(sent.body.version, 1);+});++test("normal imports remain in their workspace and settings omit server credentials", async (t) => {+ const { login } = await app(t);+ const alex = await login("alex");+ const imported = await alex("/api/imports", {+ method: "POST",+ body: invoiceDocument("north"),+ });+ assert.equal(imported.status, 201);+ assert.equal(imported.body.invoice.workspaceId, "north");+ assert.equal(imported.body.review.approved, true);+ assert.deepEqual(Object.keys((await alex("/api/integrations")).body).sort(), [+ "connected",+ "destination",+ "destinations",+ ]);+ assert.equal(+ (+ await alex("/api/integrations/deliver", {+ method: "POST",+ body: { invoiceId: "inv-north-1", destination: "unknown" },+ })+ ).status,+ 400,+ );+});++test("logout revokes the current session", async (t) => {+ const { login } = await app(t);+ const alex = await login("alex");+ assert.equal(+ (await alex("/api/logout", { method: "POST", body: {} })).status,+ 200,+ );+ assert.equal((await alex("/api/me")).status, 401);+});++test("new app instances reset invoices, credentials, profiles, and import policies", async (t) => {+ const first = await app(t);+ const alex = await first.login("alex");+ const jules = await first.login("jules");+ const token = (await alex("/api/support-report")).body.connector.accessToken;+ await alex("/api/profile", { method: "PATCH", body: { role: "admin" } });+ await alex("/api/invoices/inv-north-1", {+ method: "PATCH",+ body: { amountCents: 1 },+ });+ await jules("/api/import-policy", {+ method: "PATCH",+ body: { maxAmountCents: 200_000 },+ });+ const second = await app(t);+ const fresh = await second.login("alex");+ assert.equal((await fresh("/api/me")).body.profile.role, "member");+ assert.equal(+ (await fresh("/api/invoices/inv-north-1")).body.amountCents,+ 48_500,+ );+ assert.equal(+ (await fresh("/api/import-policy")).body.limits.maxAmountCents,+ 100_000,+ );+ assert.notEqual(+ (await fresh("/api/support-report")).body.connector.accessToken,+ token,+ );+ assert.equal(+ (+ await second.request("/api/ledger/account", {+ headers: { Authorization: `Bearer ${token}` },+ })+ ).status,+ 401,+ );+});diff --git a/examples/invoice-desk/qa/expected-findings.json b/examples/invoice-desk/qa/expected-findings.jsonnew file mode 100644index 000000000..c08e49a2e--- /dev/null+++ b/examples/invoice-desk/qa/expected-findings.json@@ -0,0 +1,95 @@+{+ "schemaVersion": 1,+ "application": "../app",+ "findings": [+ {+ "id": "ID-001",+ "category": "Secret exposure",+ "cwe": ["CWE-200"],+ "title": "Support reports disclose a server-side connector credential",+ "locations": [{ "path": "integrations.mjs", "symbol": "supportReport" }],+ "boundary": "A workspace member receives a server-only Ledger credential."+ },+ {+ "id": "ID-002",+ "category": "Broken object authorization",+ "cwe": ["CWE-639"],+ "title": "Invoice API lookup omits workspace ownership",+ "locations": [+ { "path": "server.mjs", "symbol": "createApp" },+ { "path": "invoices.mjs", "symbol": "getInvoice" }+ ],+ "boundary": "An authenticated member reads another workspace's invoice."+ },+ {+ "id": "ID-003",+ "category": "Cross-tenant cache leakage",+ "cwe": ["CWE-524"],+ "title": "Invoice previews share a cache key across workspaces",+ "locations": [{ "path": "invoices.mjs", "symbol": "previewInvoice" }],+ "boundary": "A correctly authorized preview returns another workspace's cached content."+ },+ {+ "id": "ID-004",+ "category": "Stale approval",+ "cwe": ["CWE-841"],+ "title": "Invoice edits retain approvals for an earlier version",+ "locations": [+ { "path": "invoices.mjs", "symbol": "updateInvoice" },+ { "path": "invoices.mjs", "symbol": "sendInvoice" }+ ],+ "boundary": "An edited invoice is sent without approval of its current amount."+ },+ {+ "id": "ID-005",+ "category": "Fail-open validation",+ "cwe": ["CWE-636"],+ "title": "Import-review errors turn into successful approvals",+ "locations": [{ "path": "imports.mjs", "symbol": "importInvoice" }],+ "boundary": "An unsupported document version bypasses the import amount policy."+ },+ {+ "id": "ID-006",+ "category": "Credential destination confusion",+ "cwe": ["CWE-201"],+ "title": "Connector deliveries reuse a credential at a different destination",+ "locations": [{ "path": "integrations.mjs", "symbol": "deliverInvoice" }],+ "boundary": "A destination owned by another workspace receives a reusable Ledger credential."+ },+ {+ "id": "ID-007",+ "category": "Shared mutable security policy",+ "cwe": ["CWE-668"],+ "title": "Workspace import limits share the same nested policy object",+ "locations": [+ { "path": "store.mjs", "symbol": "createStore" },+ { "path": "imports.mjs", "symbol": "updateImportPolicy" }+ ],+ "boundary": "An administrator changes a different workspace's effective import policy."+ },+ {+ "id": "ID-008",+ "category": "Validation and consumption mismatch",+ "cwe": ["CWE-436"],+ "title": "Import authorization and persistence choose different workspace fields",+ "locations": [{ "path": "imports.mjs", "symbol": "importInvoice" }],+ "boundary": "A document authorized for one workspace creates an invoice in another."+ },+ {+ "id": "ID-009",+ "category": "Mass assignment",+ "cwe": ["CWE-915"],+ "title": "Profile updates can change the caller's administrative role",+ "locations": [{ "path": "accounts.mjs", "symbol": "updateProfile" }],+ "boundary": "A member acquires administrator-only approval privileges."+ },+ {+ "id": "ID-010",+ "category": "Stored HTML injection",+ "cwe": ["CWE-79"],+ "title": "Invoice notes render stored user input as HTML",+ "locations": [{ "path": "views.mjs", "symbol": "invoicePage" }],+ "boundary": "A member's note becomes active markup in another user's invoice page."+ }+ ]+}diff --git a/sdk/typescript/tests-ts/invoice-desk-workflow.test.ts b/sdk/typescript/tests-ts/invoice-desk-workflow.test.tsnew file mode 100644index 000000000..038e0c945--- /dev/null+++ b/sdk/typescript/tests-ts/invoice-desk-workflow.test.ts@@ -0,0 +1,268 @@+import { spawnSync } from "node:child_process";+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, expect, test } from "bun:test";+import { parse } from "yaml";+import { resolvePluginPython } from "../src/runtime.js";++interface Step {+ name: string;+ id?: string;+ if?: string;+ run?: string;+ with?: Record<string, string>;+}++const workflow = parse(+ readFileSync(+ new URL(+ "../../../.github/workflows/invoice-desk-scan.yml",+ import.meta.url,+ ),+ "utf8",+ ),+) as { env: Record<string, string>; jobs: { scan: { steps: Step[] } } };+const steps = workflow.jobs.scan.steps;+const scan = steps.find((step) => step.id === "scan")!;+const sarif = steps.find(+ (step) => step.name === "Export completed findings as SARIF",+)!;+const metrics = steps.find(+ (step) => step.name === "Summarize and measure the scan",+)!;+const sourceSha = "a".repeat(40);+const temporaryDirectories: string[] = [];++afterEach(() => {+ for (const directory of temporaryDirectories.splice(0)) {+ rmSync(directory, { recursive: true, force: true });+ }+});++function fixture() {+ const directory = mkdtempSync(join(tmpdir(), "invoice workflow "));+ temporaryDirectories.push(directory);+ const bin = join(directory, "codex-security-cli/node_modules/.bin");+ mkdirSync(bin, { recursive: true });+ mkdirSync(join(directory, "invoice-desk"));+ writeFileSync(+ join(bin, "codex-security"),+ `#!/usr/bin/env bash+printf '%s\\0' "$@" > "$RUNNER_TEMP/arguments"+printf '%s\\n' "$MOCK_RESULT"+exit "$MOCK_EXIT_CODE"+`,+ { mode: 0o755 },+ );+ return directory;+}++function runStep(+ step: Step,+ directory: string,+ overrides: Record<string, string> = {},+ python?: string,+) {+ const root = directory.replaceAll("\\", "/");+ const bash =+ process.platform === "win32"+ ? join(+ process.env["ProgramFiles"] ?? "C:/Program Files",+ "Git/bin/bash.exe",+ )+ : "bash";+ const result = spawnSync(+ bash,+ [+ "--noprofile",+ "--norc",+ "-e",+ "-o",+ "pipefail",+ "-c",+ `${python ? 'python3() { "$WORKFLOW_TEST_PYTHON" "$@"; }\n' : ""}${step.run}`,+ ],+ {+ cwd: join(directory, "invoice-desk"),+ encoding: "utf8",+ env: {+ PATH: process.env["PATH"],+ SYSTEMROOT: process.env["SYSTEMROOT"],+ RUNNER_TEMP: root,+ GITHUB_OUTPUT: `${root}/outputs`,+ GITHUB_STEP_SUMMARY: `${root}/summary.md`,+ GITHUB_SHA: "b".repeat(40),+ SOURCE_SHA: sourceSha,+ PR_NUMBER: "7",+ CODEX_SECURITY_VERSION: workflow.env["CODEX_SECURITY_VERSION"],+ OPENAI_API_KEY: "synthetic-workflow-key",+ MOCK_EXIT_CODE: "0",+ MOCK_RESULT: '{"mock":true}',+ SCAN_EXIT_CODE: "0",+ SCAN_ELAPSED_SECONDS: "12",+ PREVIOUS_CACHE_HIT: "true",+ SCAN_CACHE_HIT: "true",+ WORKFLOW_TEST_PYTHON: python?.replaceAll("\\", "/"),+ ...overrides,+ },+ },+ );+ if (result.error) throw result.error;+ return { ...result, root };+}++function argumentsFor(directory: string) {+ return readFileSync(join(directory, "arguments"), "utf8")+ .split("\0")+ .slice(0, -1);+}++for (const status of [0, 1, 2]) {+ test(`Invoice Desk preserves scan exit ${status}, JSON, and literal arguments`, () => {+ const directory = fixture();+ const result = runStep(scan, directory, { MOCK_EXIT_CODE: String(status) });+ expect(result.status).toBe(status);+ expect(argumentsFor(directory)).toEqual([+ "scan",+ ".",+ "--provider",+ "openai",+ "--auth",+ "api-key",+ "--model",+ "gpt-5.6-sol",+ "--effort",+ "high",+ "--mode",+ "standard",+ "--headless",+ "--format",+ "json",+ "--output-dir",+ `${result.root}/invoice-desk-scan`,+ ]);+ expect(+ JSON.parse(+ readFileSync(join(directory, "invoice-desk-result.json"), "utf8"),+ ),+ ).toEqual({ mock: true });+ expect(readFileSync(join(directory, "outputs"), "utf8")).toMatch(+ new RegExp(`^exit-code=${status}\\nelapsed-seconds=\\d+\\n$`),+ );+ });+}++test("Invoice Desk reports a missing key without invoking the scanner", () => {+ const directory = fixture();+ const result = runStep(scan, directory, { OPENAI_API_KEY: "" });+ expect(result.status).toBe(2);+ expect(existsSync(join(directory, "arguments"))).toBe(false);+ expect(existsSync(join(directory, "invoice-desk-result.json"))).toBe(false);+ expect(readFileSync(join(directory, "outputs"), "utf8")).toBe(+ "exit-code=2\nelapsed-seconds=0\n",+ );+});++test("Invoice Desk exports SARIF only for a completed report-only scan", () => {+ const directory = fixture();+ const result = runStep(sarif, directory);+ expect(result.status).toBe(0);+ expect(argumentsFor(directory)).toEqual([+ "export",+ `${result.root}/invoice-desk-scan`,+ "--export-format",+ "sarif",+ "--source-root",+ `${result.root}/invoice-desk`,+ "--output",+ `${result.root}/invoice-desk.sarif`,+ ]);+ expect(sarif.if).toBe(+ "${{ !cancelled() && steps.scan.outputs.exit-code == '0' }}",+ );+});++for (const completed of [true, false]) {+ test(`Invoice Desk records metrics for ${completed ? "completed" : "failed"} scans`, async () => {+ const directory = fixture();+ if (completed) {+ mkdirSync(join(directory, "invoice-desk-scan"));+ writeFileSync(+ join(directory, "invoice-desk-result.json"),+ JSON.stringify({+ turn: { usage: { input_tokens: 23, output_tokens: 5 } },+ cost: { estimatedUsdRange: { min: 0.01, max: 0.02 } },+ }),+ );+ writeFileSync(+ join(directory, "invoice-desk-scan/findings.json"),+ JSON.stringify({+ findings: [+ { severity: { level: "high" } },+ { severity: { level: "low" } },+ ],+ }),+ );+ writeFileSync(+ join(directory, "invoice-desk-scan/coverage.json"),+ JSON.stringify({ completeness: "partial" }),+ );+ }+ const result = runStep(+ metrics,+ directory,+ { SCAN_EXIT_CODE: completed ? "0" : "2" },+ await resolvePluginPython(),+ );+ expect(result.status).toBe(0);+ const saved = JSON.parse(+ readFileSync(join(directory, "invoice-desk-metrics.json"), "utf8"),+ );+ expect(saved).toMatchObject({+ sourceSha,+ workflowSha: "b".repeat(40),+ pullRequest: 7,+ completed,+ exitCode: completed ? 0 : 2,+ elapsedSeconds: 12,+ packageCacheReusedFromPreviousRun: true,+ packageCacheRestoredForScan: true,+ findings: completed ? 2 : null,+ findingsBySeverity: completed ? { high: 1, low: 1 } : {},+ coverage: completed ? "partial" : null,+ tokenUsage: completed ? { input_tokens: 23, output_tokens: 5 } : null,+ estimatedUsdRange: completed ? { min: 0.01, max: 0.02 } : null,+ seedRecall: null,+ });+ const summary = readFileSync(join(directory, "summary.md"), "utf8");+ expect(summary).toContain(sourceSha);+ if (!completed) expect(summary).toContain("did not complete");+ const upload = steps.find(+ (step) => step.name === "Save reports and metrics",+ )!;+ expect(metrics.if).toBe(+ "${{ !cancelled() && steps.scan.outputs.exit-code != '' }}",+ );+ expect(upload.if).toBe(metrics.if);+ expect(upload.with?.["path"]).toContain(+ "${{ runner.temp }}/invoice-desk-metrics.json",+ );+ });+}++test("Invoice Desk rejects a completed scan with missing required artifacts", async () => {+ const directory = fixture();+ writeFileSync(join(directory, "invoice-desk-result.json"), "{}");+ const result = runStep(metrics, directory, {}, await resolvePluginPython());+ expect(result.status).not.toBe(0);+ expect(existsSync(join(directory, "invoice-desk-metrics.json"))).toBe(false);+ expect(existsSync(join(directory, "summary.md"))).toBe(false);+});