Repository navigation
test(cli): adversarial fast-check verification and bug fixes across browse CLI - #3562
miguelg719 wants to merge 2 commits into
Conversation
…faced bugs Co-authored-by: Cursor <[email protected]>
|
|
Review the following changes in direct dependencies. Learn more about Socket for GitHub.
|
There was a problem hiding this comment.
All reported issues were addressed across 17 files
Architecture diagram
sequenceDiagram
participant CLI as CLI / Secrets API
participant Daemon as Driver Daemon (server.ts)
participant DM as DriverSessionManager
participant Sock as UNIX Socket / Pipe
participant Net as Network / HTTP
participant Remote as Remote Services
participant U as URL Normalizer
participant R as Selector Resolver
participant SS as Snapshot Formatter
participant RL as Log Reducer
participant EC as Error Classifier
participant CS as Command Suggestions
Note over CLI,Remote: CLI utility flows (secrets, daemon, normalize, etc.)
CLI->>CLI: normalizeUrlScheme(input)
alt valid host / idempotent / crash-free
CLI->>CLI: Return cleaned URL (no scheme, whitespace, dot-paths, invalid IPv4)
else invalid input
CLI->>CLI: Return original input
end
CLI->>CLI: resolveSelector(selector, refMaps)
alt ref present and own-property
CLI->>CLI: Resolve to xpath (never prototype leak)
else missing / non-string / empty
CLI->>CLI: Throw DriverError("stale_ref")
end
CLI->>CLI: formatSnapshotTree(tree, opts)
CLI->>CLI: matchLine() (resets regex.lastIndex)
Note over CLI: O(N) ancestor scan with monotonic depth stack
CLI-->>SS: Snapshot string (no O(N^2))
CLI->>CLI: reduceLogs(rawLogs)
alt valid console / exception entries
CLI->>CLI: Format args safely (non-string / non-object guarded)
else malformed / null entries
CLI->>CLI: Skip entry (no crash)
end
CLI->>CLI: classifyDriverError(error)
alt Error instance
CLI->>CLI: Use message
else null-prototype / non-coercible
CLI->>CLI: Return null (no throw)
end
CLI->>CLI: extractCommandTokens / suggestCommand
CLI->>CLI: Split with max token limit + length early-exit (avoid DoS)
CLI->>Daemon: runDriverCommandViaDaemon(session, request)
Daemon->>Sock: Write JSON request
Note over Daemon,Sock: Client guards against post-settle data chunks
Daemon->>DM: initialize(generation)
alt close() during init (closeGeneration mismatch)
DM->>DM: Close stale browser / stagehand
DM->>DM: Throw DriverError("session_closed")
else init success
DM->>DM: Store browser / stagehand / context
end
DM->>Sock: resolve / status / command / stop
Sock-->>Daemon: Response JSON
Daemon->>Daemon: shutdown(triggerSocket)
Daemon->>Sock: Destroy active sockets (except trigger)
Sock-->>Daemon: Socket close
Daemon->>DM: close()
DM->>DM: Await pending init + close stagehand/browser
Daemon->>Daemon: cleanupDaemonFiles(session)
alt half-open / multi-message socket
Daemon->>Sock: resume() + force-close fallback (200ms)
end
Note over CLI,Net: Secrets API path handling
CLI->>CLI: encodePathSegment(id) (reject "", ".", "..", lone surrogates)
alt valid id
CLI->>Net: requestBrowserbase / requestBrowserbaseJson
Net-->>CLI: Response
else malformed id
CLI->>CLI: fail(CommandFailure)
end
Note over CLI,Remote: Forwarded env signature & proto safety
CLI->>CLI: collectForwardedEnv(env, keys)
CLI->>CLI: ForwardedEnvSignature (length-prefixed entries)
Note over CLI: hasOwnProperty guard on keys
Note over CLI,Daemon: Socket path bounds & session sanitization
CLI->>CLI: sanitizeSessionName(session)
CLI->>Daemon: getSocketPath(session) (respect sun_path limit)
Note over CLI,Remote: Property suites (fast-check) drive inputs across all flows
Reply with feedback, questions, or to request a fix.
View guided diff | Turn on auto-fix | Re-trigger cubic
…socket path limits Co-authored-by: Cursor <[email protected]>
Summary
Adds deterministic adversarial
fast-checkproperty suites acrosspackages/cli(HPKE secret sealing, secret API client, daemon IPC/paths/forwarded-env/server, URL normalization, selector resolution, snapshot formatting, log reduction, error classification, command suggestions, and statefulDriverSessionManagerlifecycle) and fixes 11 real bugs surfaced by shrinking counterexamples.Bugs Surfaced & Fixed
sun_pathoverflow (packages/cli/src/lib/driver/daemon/paths.ts): Unbounded session names exceeded POSIXsun_pathlimits (<= 103bytes on macOS,<= 107on Linux), causinglisten EINVAL. BoundedsanitizeSessionNamewith deterministic SHA-256 suffixing and added dynamicsun_pathfallback ingetSocketPath.packages/cli/src/lib/driver/daemon/server.ts,client.ts):handleConnectionclosed the readline interface without resuming the socket to drain trailing bytes/FIN, causingserver.close()during shutdown to hang indefinitely. Resumed sockets on close, tracked active sockets inrunDriverDaemon, added 200ms fallback teardown, guardedformatErroragainst null-prototype throws, and guarded post-settledatachunks inclient.ts.packages/cli/src/lib/secrets/api.ts):encodeURIComponentleft"",".", and".."unencoded (turningdetachFunctionSecret(opts, "..", secretId)intoDELETE /v1/secrets/<secretId>) and threw rawURIErroron lone UTF-16 surrogates. AddedencodePathSegmentvalidation and structuredCommandFailurewrapping.forwardedEnvSignatureNUL-byte collision & prototype inheritance (packages/cli/src/lib/driver/daemon/forwarded-env.ts): Bare\0delimiting collided{ a: "b\0c\0d" }with{ a: "b", c: "d" }, andcollectForwardedEnvread inherited prototype properties. Length-prefixed entries and addedObject.prototype.hasOwnPropertychecks.packages/cli/src/lib/normalize-url.ts): Accepted whitespace (\r\n), dot-paths (".","./index.html"), and out-of-range IPv4 ("999.999.999.999"). Enforced/\s/rejection, IPv4 octet validation, domain label rules, andURL.canParseverification.resolveSelector(packages/cli/src/lib/driver/commands/selectors.ts):resolveSelector("@toString", ...)returnedObject.prototype.toStringinstead of throwingstale_ref. Guarded withObject.prototype.hasOwnPropertyand non-empty string check./g//yregex drop &O(N²)ancestor scan (packages/cli/src/lib/driver/commands/snapshot-format.ts): Reusing/gor/yregexes mutatedlastIndexand skipped alternating matching lines; backward ancestor scanning degraded quadratically. Resetregex.lastIndex = 0per line and replaced with anO(N)monotonic depth stack.packages/cli/src/lib/cloud/reduce-logs.ts): Non-object entries and non-stringexception.descriptionvalues crashed withTypeError. Added entry/params object guards and safe string formatting.packages/cli/src/lib/driver/error-classifier.ts):classifyDriverError(Object.create(null))threwTypeErrorinString(error). Wrapped string coercion safely.packages/cli/src/lib/command-suggestions.ts): Boundedid.split(":", maxCommandTokens + 1)and added length-difference early exit before Myers distance.init/closebrowser leak, zombie resurrection &NaNbackoff (packages/cli/src/lib/driver/session-manager.ts): Closing during an in-flight launch/init leaked the browser and flippedstatus().initializedback totrue;close()left stalerefMaps/selectedTargetId;initFailureBackoffMs(NaN)returnedNaN. AddedcloseGenerationfencing across async boundaries, in-flight teardown, state clearing, and finite clamping.New Property Suites
packages/cli/tests/secrets-and-daemon.prop.test.ts(14 property tests)packages/cli/tests/cli-parsing-and-driver.prop.test.ts(15 property tests)Verification
oxfmt --check&oxlint(0 errors, 0 warnings)pnpm --filter browse run check,build:local-only,buildpackages/clisuite (739/739existing tests) + targeted & property suites (223/223tests,29/29new property tests)Made with Cursor
Summary by cubic
Adds deterministic adversarial property tests with
fast-checkacross the CLI and fixes 11 real bugs the shrinking counterexamples surfaced. The suites cover HPKE secret sealing, the secrets API, daemon IPC and paths, URL normalization, selector resolution, snapshot formatting, log reduction, error classification, command suggestions, and the statefulDriverSessionManagerlifecycle.Bug fixes
sun_pathoverflow and added a hashed fallback for long socket paths..,.., lone surrogates) in secrets and function-secrets API calls with structured errors.forwardedEnvSignaturecollision-free with length-prefixed entries and stopped prototype property leakage in forwarded env and selector resolution.lastIndexon stateful regexes in snapshot filtering and replaced an O(N²) ancestor scan with an O(N) stack.init/closebrowser leaks, zombie session resurrection, andNaNbackoff in the session manager with a close-generation fence.New property suites:
packages/cli/tests/secrets-and-daemon.prop.test.tsandpackages/cli/tests/cli-parsing-and-driver.prop.test.ts(29 tests total).fast-checkadded as a dev dependency.Written for commit bac8795. Summary will update on new commits.