mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-12-01 09:24:46 +00:00
OpenErrand reference runner: @logicsrc/openerrand and logicsrc errand (#228)
* OpenErrand 0.1: an errand on a website with no API, with the human steps kept human docs/openerrand.md mints OpenErrand: one JSON file per errand (register an account, download a transcript) naming the site, the inputs with a sensitivity class and ordered sources (document, vault, prompt, generate, derive, candidate, literal), field rules matched by id then label, page and wait steps, five human gates a runner never performs (declare, identity-proofing, code, mail, captcha), outcomes, the never-retried shared secret, vault and download outputs, hand-off cards that may name only public inputs, the publisher index at /.well-known/openerrand.json, and thirteen runner rules. The worked example is the MyFTB business registration that cli-tools `ftb` performs (profullstack/cli-tools#125), with no personal data. - @logicsrc/schemas: openerrand + openerrand-index schemas and fixtures - @logicsrc/validators: semantic checks (references, templates, no personal or secret input on a card) and tests that validate the spec's own examples - logicsrc-web: registry entry (process family), /openerrand landing page, the example and the index served as static files, contract tests Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * OpenErrand: hand-off cards stay on the surface that owns the data Anthony's ruling: tax and finance data never touches a social or promotion tool, and nothing is sent to a CPA or preparer. - Hand-off cards are delivered only on the surface that owns the errand's data (for a tax or finance errand, the principal's finance app through its CLI, PWA, MCP server or API, such as CoinPay, or the runner's terminal), never a social, promotion or third-party posting service, and never to anyone but the principal. A card for an errand with personal or secret inputs does not leave that surface. Runner rule 9 says the same. - The run record and the sample run name the card by an opaque id (pin-letter/7f3k2q) instead of a mynaposter.com URL; the myna mention is gone. - `principal: represented` no longer cites a preparer with a power of attorney. - The FTB card's last step no longer suggests sending the PIN to someone else. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * OpenErrand: user-agent rule, captcha solver policy, reference runner note Anthony's answers on #227 ("go with your recommendations"): - Rule 11: a runner may run headless with a normal desktop browser user agent (dropping HeadlessChrome) and nothing more: no fingerprint spoofing beyond the UA string, no stealth plugins, no solving or evading a bot challenge. A challenge the browser completes itself is a wait step; any other is a captcha gate. - Captcha solvers: new site.sector and captcha step `solver` (forbidden by default | allowed). Never allowed on government, tax, financial, healthcare or identity-provider sites, nor on any errand with a declare or identity-proofing step or a secret input; elsewhere only when the file says so, with every use logged. The validator rejects `allowed` in the forbidden set or without a stated sector; six new tests. The FTB example states sector "tax". - Reference runner: @logicsrc/openerrand / `logicsrc errand run`, marked in progress; ftb stays the runner the example was taken from. - Name stays OpenErrand; family stays Agents and process. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * OpenErrand reference runner: @logicsrc/openerrand and logicsrc errand Ship the runner docs/openerrand.md promised. `logicsrc errand run <file>` reads an OpenErrand 0.1 file, validates it with @logicsrc/validators, and drives headless Chrome through it under the spec's thirteen rules; `errand validate` shows what a file will ask of you and `errand status` shows the last run of each errand, its card and any lockout. The engine is generalised from cli-tools `ftb` (PR #125) with no dependency on cli-tools: the CDP client and Chrome finder from wcag.ts, the page reader, native-setter fill and forward-button picker from ftb-run.ts, and the rule matcher, throttle and outcome logic from ftb.ts, all now driven by the file. - Inputs: document (an extractor hook; the one shipped runs a local command that reads JSON requests and prints records), vault (teams or OpenCreds), prompt (no echo for secrets), generate, derive, candidate, literal. `--input name=value` wins. Shared-secret candidates are ranked as the spec says, one is submitted, and a rejection lists the others for --candidate. - Rules: id before label, step rules first, choices before text, an id match final, an unmatched required field stops the run naming it. - Gates: declare only with --declare after the values are shown; identity proofing never touched (URL only) and handed over or stopped on; code from the terminal or a code file, used once, a wrong code waits for the next; mail ends the run waiting with the card; captcha is the person's, and a CaptchaSolver interface is called only where the spec permits (no solver is bundled); wait steps are polled, never solved. - Throttle: 2 runs per errand and account in 30 minutes, 4 a day, 2 minutes between runs on a site, lockouts from metadata.lockout or a default, held per site and account, never lifted by --force. - Outputs: credentials written before success to a teams vault by pull, merge, push (metadata.vault or --vault), else a 0600 file said aloud; downloads type-checked and never overwritten with different bytes; cards only in the local run record. - The user agent is Chrome's own with HeadlessChrome replaced, given at launch: a CDP override did not reach a navigation the page's own script started, which is exactly the proof-of-work interstitial case. Tests: 85 in the package (rule engine, inputs, gates, throttle, outcomes, captcha gating, vaults, outputs, commands) including an integration test that runs the published FTB example unchanged in real headless Chrome against a local HTTPS fake site (Chrome maps webapp.ftb.ca.gov to it and every other host to NOTFOUND; all data fictional), and 2 in the CLI. CLI 0.6.0 -> 0.7.0; @logicsrc/schemas and @logicsrc/validators 0.3.0 -> 0.4.0 (the OpenErrand schemas, and the vocabularies now exported for runners); PRD 0009; the spec's Reference runner section and the landing page say it ships. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
1d69dc3804
commit
dde596b276
46 changed files with 5263 additions and 14 deletions
160
packages/openerrand/src/integration.test.ts
Normal file
160
packages/openerrand/src/integration.test.ts
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
/**
|
||||
* The FTB worked example, run unchanged by `logicsrc errand run` in real
|
||||
* headless Chrome against a local fake site. Chrome resolves
|
||||
* webapp.ftb.ca.gov to the fake server and every other hostname to nothing,
|
||||
* so the real site is unreachable from this test. All data is fictional.
|
||||
*/
|
||||
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { readFileSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { Command } from "commander";
|
||||
import { afterAll, beforeAll, describe, expect, it } from "vitest";
|
||||
import { findChrome } from "./browser.js";
|
||||
import { type Deps, registerErrandCommands } from "./commands.js";
|
||||
import { FAKE, type FakeSite, startFakeSite } from "./fake-site.js";
|
||||
import type { RunRecord } from "./store.js";
|
||||
import { ftbExamplePath, tempDir } from "./testing.js";
|
||||
import { type LogicsrcExec, parseEnv, serializeEnv } from "./vault.js";
|
||||
|
||||
const hasOpenssl = (() => {
|
||||
try {
|
||||
execFileSync("openssl", ["version"], { stdio: "ignore" });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
})();
|
||||
const chrome = findChrome();
|
||||
const enabled = Boolean(chrome && hasOpenssl && !process.env.OPENERRAND_SKIP_BROWSER);
|
||||
|
||||
describe.skipIf(!enabled)("logicsrc errand run, the FTB example, real Chrome, fake site", () => {
|
||||
let site: FakeSite;
|
||||
let home: string;
|
||||
let extractor: string;
|
||||
let remote: Record<string, string>;
|
||||
const out: string[] = [];
|
||||
const say: string[] = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
site = await startFakeSite();
|
||||
if (!Number.isInteger(site.port)) throw new Error("fake site has no port");
|
||||
home = tempDir("openerrand-it-");
|
||||
// The extractor the person would point at their returns: here it prints fictional records.
|
||||
extractor = join(home, "extract.mjs");
|
||||
const records = [
|
||||
{ form: "CA 540", field: "first name", value: FAKE.firstName, year: 2025, file: "2025/540.pdf", page: 1 },
|
||||
{ form: "CA 540", field: "last name", value: FAKE.lastName, year: 2025, file: "2025/540.pdf", page: 1 },
|
||||
{ form: "CA 540", field: "street address", value: "1234 Maple St", year: 2025, file: "2025/540.pdf", page: 1 },
|
||||
{ form: "CA 540", field: "ZIP code", value: "95814-0001", year: 2025, file: "2025/540.pdf", page: 1 },
|
||||
{ form: "CA 100S", field: "California corporation number", value: FAKE.corpId, year: 2025, file: "2025/100S.pdf", page: 1 },
|
||||
{ form: "CA 100S", field: "line 20", label: "Net income for tax purposes", value: "48,210", year: 2025, file: "2025/100S.pdf", page: 3 },
|
||||
{ form: "CA 100S", field: "line 20", label: "Net income for tax purposes", value: "39,875", year: 2024, file: "2024/100S.pdf", page: 3 },
|
||||
];
|
||||
writeFileSync(extractor, `let input = ""; process.stdin.on("data", (c) => (input += c)); process.stdin.on("end", () => { JSON.parse(input); process.stdout.write(${JSON.stringify(JSON.stringify(records))}); });`);
|
||||
remote = { OTHER_TEAM_KEY: "keep me" };
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await site?.close();
|
||||
});
|
||||
|
||||
function program(): Command {
|
||||
const fakeTeams: LogicsrcExec = (args) => {
|
||||
// logicsrc teams pull/push against an in-memory vault: the pull-merge-push is what is under test.
|
||||
const file = args[args.indexOf("--env") + 1]!;
|
||||
if (args[0] === "teams" && args[1] === "pull") writeFileSync(file, serializeEnv(remote));
|
||||
else if (args[0] === "teams" && args[1] === "push") remote = parseEnv(readFileSync(file, "utf8"));
|
||||
else return { status: 1, stdout: "", stderr: "unexpected" };
|
||||
return { status: 0, stdout: "", stderr: "" };
|
||||
};
|
||||
const deps: Partial<Deps> = {
|
||||
env: { ...process.env, LOGICSRC_ERRAND_HOME: home },
|
||||
out: (line) => out.push(line),
|
||||
say: (line) => {
|
||||
say.push(line);
|
||||
// Whoever holds the phone writes the code to the file the runner names.
|
||||
if (/WAITING for the sms code/.test(line)) relayNext();
|
||||
},
|
||||
interactive: false,
|
||||
logicsrc: fakeTeams,
|
||||
chromeArgs: [
|
||||
`--host-resolver-rules=MAP webapp.ftb.ca.gov:443 127.0.0.1:${site.port}, MAP * ~NOTFOUND`,
|
||||
"--ignore-certificate-errors",
|
||||
// CI runners often lack the user namespaces Chrome's sandbox needs.
|
||||
...(process.env.CI ? ["--no-sandbox"] : []),
|
||||
],
|
||||
pollMs: 250,
|
||||
rereadMs: 300,
|
||||
settleMs: 300,
|
||||
};
|
||||
const p = new Command();
|
||||
p.name("logicsrc").enablePositionalOptions().exitOverride();
|
||||
registerErrandCommands(p.command("errand"), deps);
|
||||
return p;
|
||||
}
|
||||
|
||||
const codes = ["000000", FAKE.code];
|
||||
function relayNext(): void {
|
||||
const code = codes.shift();
|
||||
if (code) setTimeout(() => writeFileSync(join(home, "codes", "ftb-register-business.code"), `${code}\n`, { mode: 0o600 }), 300);
|
||||
}
|
||||
|
||||
const lastRecord = (): RunRecord => JSON.parse(out.filter((l) => l.startsWith("{")).at(-1)!) as RunRecord;
|
||||
const args = (...extra: string[]) => ["node", "logicsrc", "errand", "run", ftbExamplePath(), "--extractor", `${process.execPath} ${extractor}`, "--input", "email=jane@example.com", "--input", `phone=${FAKE.phone}`, "--vault", "teams:test/ftb/prod", "--json", ...extra];
|
||||
|
||||
it("a dry run stops before the business page's forward button", async () => {
|
||||
await program().parseAsync(args("--dry-run"));
|
||||
expect(process.exitCode).toBe(0);
|
||||
expect(lastRecord()).toMatchObject({ kind: "dry-run", page: "https://webapp.ftb.ca.gov/MyFTBAccess/Registration/Business" });
|
||||
expect(site.posted["/MyFTBAccess/Registration/Business"]).toBeUndefined();
|
||||
// The challenge interstitial was waited out, not solved.
|
||||
expect(site.requests.some((r) => r.path.endsWith("/Challenge"))).toBe(true);
|
||||
expect(say.join("\n")).toContain("declaration (not ticked)");
|
||||
}, 120_000);
|
||||
|
||||
it("a run with --declare registers, relays the code after a wrong one, pushes the login into the team vault, and keeps the card local", async () => {
|
||||
site.requests.length = 0;
|
||||
await program().parseAsync(args("--declare"));
|
||||
const record = lastRecord();
|
||||
expect(record, say.join("\n")).toMatchObject({ outcome: "registered", kind: "success", vault: "teams test/ftb/prod" });
|
||||
expect(process.exitCode).toBe(0);
|
||||
expect(record.card?.id).toMatch(/^pin-letter\//);
|
||||
expect(record.waiting?.what).toBe("MyFTB PIN letter");
|
||||
|
||||
// What the site received: the shared secret once, the declaration ticked, the code on the second try.
|
||||
expect(site.posted["/MyFTBAccess/Registration/Business"]).toMatchObject({ NetInc: FAKE.netIncome, TaxYear: "2025", Decl: "true", Role: "business", Zip: FAKE.zip, AddrNum: "1234" });
|
||||
expect(site.requests.filter((r) => r.method === "POST" && r.path.endsWith("/Business"))).toHaveLength(1);
|
||||
expect(site.requests.filter((r) => r.method === "POST" && r.path.endsWith("/Code"))).toHaveLength(2);
|
||||
// Rule 11: the user agent says Chrome, not HeadlessChrome.
|
||||
expect(site.requests.filter((r) => r.userAgent.includes("HeadlessChrome")).map((r) => `${r.method} ${r.path}`)).toEqual([]);
|
||||
|
||||
// The team vault: merged, nothing dropped, the generated login in it.
|
||||
const profile = site.posted["/MyFTBAccess/Registration/Profile"]!;
|
||||
expect(remote).toMatchObject({ OTHER_TEAM_KEY: "keep me", FTB_BUSINESS_USERNAME: profile.UserName, FTB_BUSINESS_PASSWORD: profile.Password, FTB_BUSINESS_EMAIL: "jane@example.com" });
|
||||
expect(Object.keys(JSON.parse(remote.FTB_BUSINESS_SECURITY_ANSWERS!))).toHaveLength(3);
|
||||
|
||||
// Rule 8: values never reach the page log or the run record; secrets never reach the terminal.
|
||||
const log = readFileSync(join(home, "pages", "ftb-register-business.jsonl"), "utf8");
|
||||
for (const value of [profile.Password!, FAKE.netIncome, FAKE.code, "jane@example.com", FAKE.phone]) {
|
||||
expect(log).not.toContain(value);
|
||||
expect(JSON.stringify(record)).not.toContain(value);
|
||||
}
|
||||
expect(say.join("\n")).not.toContain(profile.Password!);
|
||||
expect(say.join("\n")).not.toContain(FAKE.netIncome);
|
||||
|
||||
// `errand status` shows the card from the local run record.
|
||||
out.length = 0;
|
||||
await program().parseAsync(["node", "logicsrc", "errand", "status"]);
|
||||
expect(out.join("\n")).toMatch(/ftb-register-business {2}success \(registered\)/);
|
||||
expect(out.join("\n")).toContain("ftb activate business --pin <PIN from the letter>");
|
||||
}, 180_000);
|
||||
|
||||
it("a third run inside the window is refused by the throttle before Chrome starts", async () => {
|
||||
const before = site.requests.length;
|
||||
await program().parseAsync(args("--declare"));
|
||||
expect(process.exitCode).toBe(4);
|
||||
expect(site.requests.length).toBe(before);
|
||||
process.exitCode = 0;
|
||||
}, 30_000);
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue