Files
openbot/scripts/install-git-hooks.ts
NBandClaude Opus 5 799de8791a feat(dev): AI automation bridge over CDP plus ts-log logging package (#220)
* feat(dev): AI automation bridge over CDP plus ts-log logging package

- packages/logging: ts-log Logger with secret redaction, covered by tests
- scripts/dev-automation: snapshot/screenshot/click/type against the running dev app
- migrate console.* in main/backend/scripts to the redacting logger

* fix(dev-automation): drive the main window, not helper popups

CDP lists Dynamic Island surfaces in arbitrary order; prefer the bare
app URL so snapshot/screenshot/act always target the main window.

* docs(agents): point e2e smoke checks at dev:automation

* fix(review): bundle logging, stderr JSON, UA guard, cycle-safe logs, injectable test loggers

- main build bundles @openbot/logging like contracts (packaged startup)
- dev-automation CLI logs to stderr, stdout keeps pure JSON
- CDP refuses non-OpenBot targets; main-window pick covered by tests
- logging handles bigint/circular values without throwing
- team-api-server and dynamic-island accept an optional logger;
  console spies replaced with injected or observed loggers

* fix(review): recipe bump, catalog literals, explicit port for mutations

- bump remoteDesktop.recipeVersion for the touched runtime scripts
- ts-log/playwright-core as literals: single-workspace deps per catalog rule
- click/type refuse a defaulted port; name the instance with --port=

* fix(review): redact serialized payloads, gate log levels, enforce noConsole

- redaction covers a payload that arrives as one string: quoted values are
  consumed whole, `{"apiKey":"…"}` and `set-cookie:` shapes match, and a
  scheme-prefixed `Authorization: Basic …` no longer leaks its base64
- redaction is idempotent, so a value passed through `toLogValue` and then
  formatted no longer grows a stray `]`
- error message and stack are redacted at conversion, not only at format time
- logger honours a level threshold (`info` by default, `OPENBOT_LOG_LEVEL`
  lowers it); dev-automation asks for `debug` to keep renderer console output
- Biome `noConsole` enabled for src, scripts and packages so the migration
  cannot regress
- dev-automation: mutation gate extracted and tested, `ForeignBrowserError`
  sentinel instead of message matching, one role list with the type derived
  from Playwright, unused `waitForRole` dropped, `--text=` can clear a field
- remote-debugging port validated through `readDevelopmentRemoteDebuggingPort`
  so main and automation agree on the range
- docs: restore rule 7 indentation, document the level and the lint rule

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

* fix(dev): tighten automation target selection and screenshot paths

Addresses the review findings on the CDP bridge and unbreaks CI.

- Diagnostics no longer print page titles or full URLs. `describeTarget`
  reduces a target to origin + path for loopback pages and to
  `scheme//host (external)` for anything else, so a visited page's query
  string never reaches the log.
- `pickMainPage` could latch onto an embedded browser page. `isMainAppUrl`
  now requires a loopback http(s) origin, no `surface` query and the bare
  app route, and `findMainPages` refuses to guess when two candidates
  match.
- `screenshot --out` accepted any path with no mutation flag.
  `resolveScreenshotPath` keeps the destination inside the build directory
  and requires a `.png` name.
- Revert the cosmetic logging edits to the three recipe-guarded runtime
  scripts and `recipeVersion` back to 8: the bump guard fired on them,
  and a bumped recipe with a stale `artifactRelease.inputDigest` fails
  `parseNativeRuntimeLock` and 10 tests. Those files are exempted from
  `noConsole` via an enabling override instead.

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

* feat(dev): make automation pick the right dev instance per worktree

Several worktrees run `bun run dev` on one machine, and only the first
gets 9333: `dev-services` walks the port upwards, so the second instance
answered on a port nobody wrote down and `dev:automation` drove the
wrong app.

- Each dev app and test client now publishes its worktree, profile,
  renderer port, debugging port and pid to a registry in the per-user
  temporary directory, and removes the record on shutdown. Reading prunes
  records whose process is gone, so a killed instance never keeps
  offering a port another one has taken.
- `dev:automation instances` lists what is live. Resolution prefers the
  record of the worktree the command runs in, refuses to guess between
  two, and accepts `--instance=<id>`, `--port=` or `--service=`.
- The mutation gate now asks whether the instance was *named* rather than
  whether a port was typed. Another worktree's app stays readable and
  is never clickable.
- Two review findings on target selection: the snapshot document carried
  a raw `page.url()`, which on the app route can hold an OAuth code, so
  it goes through the extracted `describeTarget`; and a visited local
  site in an embedded browser view wore the same loopback origin and
  bare path as the app, so a page is only driven when it carries the
  `window.openbot` preload bridge and, when the registry named one, the
  expected renderer port.

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

* feat(dev): let automation drive any dev window on purpose

The main-window restriction was a safe default that had turned into a
limit. Dev is where every flow has to be testable, embedded browser
views and Dynamic Island surfaces included.

- `dev:automation pages` lists every CDP target with an index and a
  sanitized description.
- `--page=<index|url-substring>` drives any of them, overriding both the
  bare-route filter and the preload-bridge probe. An empty selector is
  refused rather than matching everything.
- Aiming at nothing still resolves the app window, and an ambiguous
  selector prints the target list instead of guessing.

The guards that stay are the ones about hitting the wrong process, not
the wrong page: `--allow-mutations` and an instance that was named
rather than inferred.

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

* fix(logging): bound the redaction patterns and redact snapshot text

Four review findings, and one the third one uncovered.

- `sk-` and friends matched inside ordinary words, so `risk-register`
  logged as `ri[redacted]` and erased the part naming what failed. The
  provider prefixes now need a token boundary.
- A quoted JSON `"key"` is redacted in the text fallback too, for a
  payload too malformed to reparse structurally.
- The 100 KB reparse cap is gone: a long body is exactly where a secret
  hides, and truncation keeps the first characters, which were the
  unredacted ones.
- Removing that cap surfaced why it was there. `SECRET_LABEL` and `EMAIL`
  both had unbounded affix runs, so every position in a long payload
  consumed the rest of it and backtracked: 200 KB took 9.6s. Bounded, the
  same payload takes 150ms and 2 MB takes 1.4s.
- The snapshot document carried the page title and the accessibility tree
  verbatim, so a screen showing an API token exported it on stdout. Both
  go through `redactText` before truncation, so a secret cannot survive
  in the part that is kept.
- The registry record is written to a sibling and renamed into place. A
  plain write truncates first, and a reader hitting that window deleted
  the file as corrupt, leaving a freshly started instance undiscoverable.

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

* fix(logging): stop treating prose as a credential assignment and bound conversion depth

- CREDENTIAL_ASSIGNMENT required an explicit = or : separator; bare whitespace
  turned `SKILLS_ADMIN_TOKEN is missing` into `SKILLS_ADMIN_TOKEN [redacted] missing`.
- convertValue now stops at depth 32, so a deeply nested external payload cannot
  overflow the stack and replace the failure the caller was reporting.
- dev:automation instances redacts profile and projectRoot on its stdout JSON,
  the one registry field that did not pass through the logger.

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

* feat(dev-automation): add --wait-for, warn on cross-worktree ports, tighten redaction

- --wait-for=<role>,<name> settles on an accessible target before a capture and
  after a click or a keystroke, so a flow no longer needs a snapshot loop.
- An explicit --port= stays authoritative, but says whose worktree it resolved
  to when that is not this one; a mistyped digit was silent before.
- Registry directory 0700 and records 0600, created exclusively so a planted
  staging path cannot redirect the write.
- Basic/Digest/Token only redact inside an Authorization context, so
  'Token validation failed' survives; Bearer still matches anywhere.
- Error names, object keys and the String() fallback pass through redactText;
  conversion is exception-safe and emits [unserializable] instead of throwing
  from inside the logger.

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

* fix(dev-automation): contain screenshots against symlinks and fail closed on an unsafe registry

- resolveScreenshotPath refuses a symlink anywhere between the build root and
  the destination; the containment check was lexical and page.screenshot
  follows links, so a read-only command could write outside the directory.
- The screenshot response reports a workspace-relative path, dropping the home
  directory prefix, and refuses a name whose redacted form differs rather than
  returning one the caller cannot reopen.
- Publishing a dev instance verifies the registry directory is owned by this
  user and unreachable by other accounts, instead of swallowing a failed chmod.
  A registry someone else can write lets them choose which CDP port a mutation
  command trusts.

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

* fix(dev-automation): validate the registry directory on read as well as on write

Only the writer failed closed on a directory other accounts can reach, so a
reader that never publishes trusted whatever it found there. A planted record
naming this worktree, a live pid and an attacker's CDP endpoint would have been
classified as the local instance a mutation may drive.

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

* fix(dev-automation): hide non-app loopback paths and aim by CDP target id

A loopback origin does not make a page the app: an embedded view can serve a
callback on 127.0.0.1 whose path carries the code as a plain segment, which no
redaction rule recognizes. `describeTarget` now prints a path only for the
app's own routes and collapses anything else to its origin.

Aiming moves from an array index to CDP's target id. Each command opens its own
connection, so a window closing in between shifted every later position and
`--page=1` could drive a target nobody printed. Verified against a live dev
instance: a stale id now refuses instead of drifting to another window.

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

* fix(dev-automation): redact renderer console before truncating, and verify instance process identity

Two review findings on the dev automation layer.

The renderer console handler sliced the message to 500 characters before
handing it to the logger, which redacts and only then truncates at 2000. A
cut could hand the log a prefix of a token short enough that no redaction
rule recognizes its shape - so the full text now goes to the logger.

`process.kill(pid, 0)` proves only that something holds that pid. A dev
instance killed with SIGKILL leaves its record behind, and a recycled pid
made that record - with its debugging port - look like this worktree's live
app, which is the one match `click` and `type` accept. Liveness now also
compares the process start time from `ps -o lstart=` against the record's
`startedAt`, and two live records claiming one debugging port keep only the
newest, which is what still fails closed where `ps` is unavailable.

Watched both new guards fail: removing the start-time comparison reds
"rejects a pid that was recycled after the record was published", and
returning the records unfiltered reds the port-collision test.

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

* fix(dev-automation): keep a one-time code out of the snapshot document

`ariaSnapshot` prints what a control holds, and `redactText` cannot recognize
a login code: it is a handful of characters with no label and no secret shape.
The snapshot goes to stdout and lands in an agent transcript, so a code typed
by `type` without `--submit` left the machine.

`redactSensitiveSnapshotValues` now blanks what was entered into any node
whose accessible name reads as a one-time code, password, token or
credential - the inline value, and the unnamed text anywhere in its subtree.
Named nodes inside that subtree survive, because a developer still has to see
the control to aim `type` at it.

The subtree half is the part that matters for `OtpInput`: it clears the native
input on every keystroke and rebuilds the code as visible characters, so the
code never is the textbox value - it is loose text under the fieldset. That
fieldset was unnamed, leaving nothing for either consumer to recognize, so it
now carries `aria-label="One-time code entry"`: assistive tech announces the
context those characters belong to, and the redactor knows the subtree.

Watched all three guards fail: neutering the sensitive-name pattern reds both
snapshot tests, dropping the subtree rule reds the loose-character one, and
removing the fieldset name reds the OtpInput contract. Verified against the
live dev app that an ordinary textbox value still prints.

Surfaces touched: desktop renderer (OtpInput), dev automation scripts.

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 18:38:52 +02:00

31 lines
934 B
TypeScript

import { spawnSync } from "node:child_process";
import { createOpenBotLogger } from "@openbot/logging";
const logger = createOpenBotLogger("install-git-hooks");
const repositoryRoot = runGit(["rev-parse", "--show-toplevel"], false);
if (repositoryRoot === undefined) {
logger.info("Skipping Git hook setup because this directory is not a Git repository.");
process.exit(0);
}
const result = spawnSync("git", ["config", "core.hooksPath", ".githooks"], {
cwd: repositoryRoot,
stdio: "inherit",
});
if (result.status !== 0) {
process.exit(result.status ?? 1);
}
logger.info("Git hooks enabled from .githooks.");
function runGit(args: string[], inheritOutput: boolean): string | undefined {
const result = spawnSync("git", args, {
encoding: "utf8",
stdio: inheritOutput ? "inherit" : ["ignore", "pipe", "ignore"],
});
if (result.status !== 0) return undefined;
return result.stdout?.trim() || undefined;
}