v0.50.5.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins (#5130)
* v0.50.2.0 fix(security): critical+high advisory wave — DCR scope ceiling, cwd .env quarantine, format-based transcript redaction, consent pins Closes the critical- and high-severity items from six privately reported advisories (GHSA-548g-mhxp-p66h, GHSA-42r8-3jfh-82vr, GHSA-62gp-q5hj-r9mv, GHSA-q374-hhfh-f79x, GHSA-ghfq-gqmq-7fm4, GHSA-q5p9-qr3g-6v38). Squashed to a single commit so no intermediate revision carries a test-fixture credential shape through the gitleaks range gate. Cluster A — OAuth consent gate (GHSA-548g / -42r8 / -62gp). The v0.50.0.0 owner-approval flow is pinned end to end against a real `serve --http --enable-dcr` process and in-process: anonymous /authorize mints no code, a forged code is rejected at /token, revoked clients are refused at grants.begin, and OAuthGrants.begin() now caps awaiting-decision requests per client_id. Cluster B — DCR scope ceiling (GHSA-q374 defect B, GHSA-548g fix #2). registerClient rejects admin/sources_admin/users_admin/agent with HTTP 400 via scope.ts:dcrScopeViolation; client_credentials DCR clients are read-only. Remote sources_remove is source-fenced like sources_status. doctor's oauth_client_scope_health flags privileged self-registered clients. Cluster C — format-based secret detection (GHSA-ghfq). secret-scan.ts gains jwt/aws(AKIA|ASIA)/google/stripe/sendgrid/twilio/supabase/gitlab/npm/hf plus bearer and db_url_credentials catch-alls; the transcripts lane opts into the digit-gated high-entropy rule; getRawData follows the page soft-delete on both engines; delete_page --purge (local-CLI only) hard-removes a leaked page. Cluster D — cwd .env quarantine (GHSA-q5p9). New env-trust.ts + cli-preflight.ts drop a fixed list of code-loading / exec-target / posture-widening GBRAIN_* variables when a working-directory .env assigns them (key-presence, since Bun expands ${VAR}); the guardrails loader refuses cwd-relative and cwd-.env specs. Release artifacts: VERSION/package.json/three plugin manifests bumped to 0.50.2.0; CHANGELOG entry (reporters credited); SECURITY.md, README, DEPLOY.md, CHATGPT.md, guardrails.md, ENGINES.md and KEY_FILES updated; template + plugin trees, skills.lock, flag registry and llms bundle regenerated; module-size ceilings adjusted with per-row reasons; TODOS follow-ups filed. Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> * fix: pre-landing review fixes (v0.50.2.0 security wave) Review cycle 1 of the ship: 6 specialists + red team + coverage audit. Security / red team: - env-trust: parse .env with Bun's line grammar (bare CR terminates a line; BOM/U+2028 cannot hide an assignment); protect the loader / git / node / proxy / AI-CLI variable families a checkout could plant for the programs gbrain spawns; cli-preflight re-execs gbrain once with the sanitized environment so git, the agent CLI and workers inherit the clean view; cwd == ~/.gbrain no longer quarantines the operator's own .env. - guardrails: GBRAIN_GUARDRAILS_MODULE accepts only absolute or ~/ paths (a package name resolves from the cwd's node_modules). - secret-scan: bounded db_url_credentials quantifiers + per-pattern prechecks (linear on long lines), windowed previews that redact every sibling span, single-pass longest-first replacement. - TODOS: follow-up entries reworded to the functional level. API contract / maintainability: - delete_page purge: remote callers get permission_denied; a purged response always carries write_through; get_raw_data description states the soft-delete follow; includeDeleted narrowed to the getRawData signature; client_credentials gate evaluated before the DCR ceiling; doctor privileged set derived from the scope registry; sources_remove / sources_status share assertSourceInCallerScope; shell-job opt-in reaches --job-isolation process children as --allow-shell-jobs; stale help copy. - transcripts ingest: raw-metadata compare uses canonical JSON (JSONB key order made every healthy re-run rewrite unchanged rows). Coverage audit: 5 new test files + 4 extended (25 cases), plus RED-verified pins for every fix above. Docs/KEY_FILES/CHANGELOG/SECURITY updated; llms bundle, flag registry, tool catalog, structural suites regenerated; module-size rows adjusted with reasons. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 2 (v0.50.2.0 security wave) Re-exec redesign (security + red team + adversarial findings): - cli-preflight re-runs gbrain from an empty temporary directory so the sanitized child never reloads the hostile .env: dropped keys are absent, never carried as '' (git and the dynamic loader presence-check GIT_SSL_NO_VERIFY / LD_TRACE_LOADED_OBJECTS; '' broke git ident). - The re-run marker is JSON {cwd, neutral} honoured only when the process provably started in that empty directory — a marker planted via a cwd .env is ignored (the ppid-keyed marker was forgeable under systemd/docker). - SIGINT is delivered by the tty once (wrapper no longer forwards it); SIGTERM/SIGHUP forwarded; execArgv preserved under the dev runtime. - Protected families widened: XDG config roots (git reads $XDG_CONFIG_HOME/git/config as global config), GNUPGHOME, TLS trust stores, EDITOR/VISUAL/PAGER, every provider endpoint variable, the GBRAIN_REMOTE_* / GBRAIN_DIRECT_DATABASE_URL redirects, and the marker. - cwd dotenv parsed once per start; jobs start uses the same '1' literal. secret-scan (cycle-2 findings): - db_url_credentials password class only stops at whitespace, '@' and string delimiters again (unescaped / { } < > | ^ ` \ passwords redact); BEARER uppercase recognized; jwt / high_entropy_assignment / PEM body bounded (adversarial '-eyJ' / '_token' runs and header-only PEM texts were quadratic); incremental PEM line cursor; redactFindings rebuilds the text by span-splice in one pass (was O(unique values x text)). Contract / docs: - delete_page purge responses carry a residuals hint (git history, exports, compiled context, slug-keyed derived rows); CHANGELOG states a single truth for GBRAIN_GUARDRAILS_MODULE (absolute or ~/ only, listed under Changed with a migration note); SECURITY.md / KEY_FILES / docs guides / minion-orchestrator skill describe the new mechanism and the --allow-shell-jobs opt-in; TODOS follow-ups filed; test-reads-source marker on the hook spawn-shape test; new PEM fixtures fragmented. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 3 (v0.50.2.0 security wave) - Compiled binaries: every `bun build --compile` invocation passes `--no-compile-autoload-bunfig`; new `scripts/check-compile-autoload.sh` guard (self-tested, in verify CHECKS) keeps it that way. - cwd `.env` quarantine: `GBRAIN_DATABASE_URL`, `GBRAIN_OAUTH_RELAY_URL`, OpenSSL config/engine/module loaders, temp roots and HOME/USERPROFILE join the protected set; the neutral hop dir is realpath'd; signal handlers are installed before the spawn; non-tty wrappers forward SIGINT once; guardrails fail closed when a dropped GBRAIN_GUARDRAILS_MODULE had a value. - secret-scan: PEM header-line cursor is O(text) on newline-free tails; bounded bearer echo pass redacts bare re-occurrences of claimed tokens. - transcripts ingest: raw-metadata probe reads active rows only. - Tests: afterAll cleanup, execArgv/SIGHUP/chdir-back pins, pty SIGINT, perf pins; docs/CHANGELOG/TODOS/KEY_FILES/SECURITY updated; llms + skills.lock + plugin trees regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 4 (v0.50.2.0 security wave) Cross-model adversarial pass (Codex) + Claude verifier findings: - env-trust: shell-startup / interpreter-home family (BASH_ENV, SHELLOPTS, PS4, BASHOPTS, PROMPT_COMMAND, ZDOTDIR, PYTHONHOME, PERLLIB, GCONV_PATH, BASH_FUNC_* prefix) protected; sh `ENV` deliberately excluded. - cli-preflight: config-dir exemption refused when the cwd .env assigns GBRAIN_HOME/HOME/USERPROFILE; wrapper removes pre-existing signal listeners so its exit is always the child's; SIGINT forwarded only without a controlling terminal (/dev/tty probe); a dropped planted HOME is restored from the passwd home; script-mode runs warn once when the cwd bunfig.toml declares a top-level preload. - secret-scan: overlapping matches redact the UNION of matched spans; echo pass covers bearer + high-entropy values (64 unique, <=512 chars) via per-value sweeps over unclaimed gaps only; planRedaction/ applyRedaction share a session-wide echo dictionary in transcripts render. - sources_remove keys on write authority (assertSourceInCallerWriteScope); federated read grants confer no removal right. - delete_page --purge retries the tombstone's file removal and fails closed (storage_error) while the file remains. - Docs: SECURITY.md quarantine example no longer uses the one key that refuses instead of re-running; KEY_FILES/CHANGELOG/TODOS updated; llms. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * v0.50.3.0 chore: re-bump the security wave to 0.50.3.0 (master claimed 0.50.2.0 in #5122) Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header/date + TODOS follow-up refs + bun.lock, template repo and plugin trees regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix: pre-landing review fixes, cycle 5 — Codex structured-review gate (v0.50.3.0 security wave) - cli-preflight: hop marker carries the wrapper pid; a verified re-run arms an unref'd 1 s watchdog and exits 137 (removing its neutral dir) when the wrapper is force-killed, so supervisor restarts never orphan a worker; relative path-bearing runtime flags (--preload/-r/--require/--import, --config/-c, --env-file, --tsconfig-override) are resolved against the original cwd before the hop. - secret-scan: echo pass is a streaming leftmost-longest merge with O(values) retained state (Codex repro: 64 short claims + 2 MiB repetitive tail went from +233 MiB RSS / 1.4 s to +16 MiB / 140 ms); repetitive tails are now covered wall-to-wall. - Docs: KEY_FILES, SECURITY.md, CHANGELOG; llms regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * docs: update project documentation for v0.50.3.0 Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * fix(ci): green the three failing checks on the v0.50.3.0 wave - semgrep: six `nosemgrep` suppressions with justifications for the path-join/resolve and non-literal-RegExp taint heuristics on operator- controlled cwd/flag paths and compile-time pattern sources (no behaviour change). - test (2): the two pty Ctrl-C pins ran the wrapper through `script -c`'s intermediate /bin/sh; on ubuntu-latest that is dash, which re-raises the pty's SIGINT on itself after the child exits (130) instead of relaying the child's 42. The pty command now `exec`s the wrapper so no shell stays in the foreground group; documented in a `ptyCommand` helper. - Selected E2E: with --enable-dcr, OAuth discovery now advertises exactly the self-registration ceiling (`read write`) via `scopesSupportedForDiscovery`, so a connector that copies `scopes_supported` into /register succeeds (master's #5122 pin); without DCR the full operator list minus `agent` is unchanged. Sibling e2e assertions that expected privileged scopes on the DCR-enabled server updated; unit + PGLite e2e pins added; docs/TODOS/CHANGELOG/KEY_FILES updated; llms regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> * v0.50.5.0 chore: re-bump the security wave to 0.50.5.0 (master claimed 0.50.4.0 in #5131) Five-file lockstep + BOOTSTRAP stamp + CHANGELOG header + TODOS follow-up refs + bun.lock, template repo and plugin trees regenerated. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gbrain",
|
||||
"version": "0.50.4.0",
|
||||
"version": "0.50.5.0",
|
||||
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
|
||||
"author": {
|
||||
"name": "Garry Tan",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gbrain",
|
||||
"version": "0.50.4.0",
|
||||
"version": "0.50.5.0",
|
||||
"description": "Personal knowledge brain for your coding agent — hybrid search, synthesis, graph traversal, and durable cross-session memory over Postgres/PGLite with pgvector, plus a curated brain-first skill set.",
|
||||
"author": {
|
||||
"name": "Garry Tan",
|
||||
|
||||
8
.github/workflows/heavy-tests.yml
vendored
8
.github/workflows/heavy-tests.yml
vendored
@@ -470,7 +470,7 @@ jobs:
|
||||
# keyless and paid runs each pay the 2-4 min compile.
|
||||
- name: Build gbrain (compile once for both door runs)
|
||||
run: |
|
||||
bun build --compile --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.ts
|
||||
bun build --compile --no-compile-autoload-bunfig --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.ts
|
||||
echo "GBRAIN_COMPILED_BIN=$RUNNER_TEMP/gbrain-door-bin" >> "$GITHUB_ENV"
|
||||
|
||||
# SECRETLESS provisioning: the npm registry verifies the per-platform
|
||||
@@ -681,7 +681,7 @@ jobs:
|
||||
|
||||
- name: Build gbrain (compile once for the doors)
|
||||
run: |
|
||||
bun build --compile --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.ts
|
||||
bun build --compile --no-compile-autoload-bunfig --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.ts
|
||||
echo "GBRAIN_COMPILED_BIN=$RUNNER_TEMP/gbrain-door-bin" >> "$GITHUB_ENV"
|
||||
|
||||
- name: Install codex + claude (pinned npm versions, refuse on drift)
|
||||
@@ -784,7 +784,7 @@ jobs:
|
||||
# Compile gbrain ONCE for both bun test invocations below.
|
||||
- name: Build gbrain (compile once for both door runs)
|
||||
run: |
|
||||
bun build --compile --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.ts
|
||||
bun build --compile --no-compile-autoload-bunfig --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.ts
|
||||
echo "GBRAIN_COMPILED_BIN=$RUNNER_TEMP/gbrain-door-bin" >> "$GITHUB_ENV"
|
||||
|
||||
# SECRETLESS provisioning, pack-verify-install: `npm pack` DOWNLOADS
|
||||
@@ -995,7 +995,7 @@ jobs:
|
||||
- run: bun install --frozen-lockfile
|
||||
- name: Build gbrain
|
||||
run: |
|
||||
bun build --compile --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.ts
|
||||
bun build --compile --no-compile-autoload-bunfig --outfile "$RUNNER_TEMP/gbrain-door-bin" src/cli.ts
|
||||
echo "GBRAIN_COMPILED_BIN=$RUNNER_TEMP/gbrain-door-bin" >> "$GITHUB_ENV"
|
||||
- name: Install opencode@latest (unpinned — the whole point)
|
||||
timeout-minutes: 10
|
||||
|
||||
2
.github/workflows/release.yml
vendored
2
.github/workflows/release.yml
vendored
@@ -113,7 +113,7 @@ jobs:
|
||||
# release runner is a flakier duplicate gate — it blocked the first
|
||||
# release on ambient-env tests (run 30698650484). The build job's gate
|
||||
# is the artifact itself: compile, then smoke-test the binary.
|
||||
- run: bun build --compile --target=${{ matrix.target }} --outfile bin/${{ matrix.artifact }} src/cli.ts
|
||||
- run: bun build --compile --no-compile-autoload-bunfig --target=${{ matrix.target }} --outfile bin/${{ matrix.artifact }} src/cli.ts
|
||||
- name: Smoke-test the compiled binary
|
||||
run: |
|
||||
chmod +x bin/${{ matrix.artifact }}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!-- gbrain-runbook-stamp: 0.50.4.0 -->
|
||||
<!-- gbrain-runbook-stamp: 0.50.5.0 -->
|
||||
<!-- This stamp must equal the VERSION file at every release; CI enforces it
|
||||
(scripts/check-bootstrap-tag.sh). `gbrain bootstrap status` compares it to
|
||||
the installed binary and warns on skew. -->
|
||||
|
||||
28
CHANGELOG.md
28
CHANGELOG.md
@@ -2,6 +2,34 @@
|
||||
|
||||
All notable changes to GBrain will be documented in this file.
|
||||
|
||||
## [0.50.5.0] - 2026-09-16
|
||||
|
||||
**Security hardening pass across the remote OAuth surface, transcript ingest, and environment handling.** This wave closes the critical- and high-severity items from privately reported advisories. Fresh installs and existing brains are on the same footing after upgrade; where an operator kept a security-relevant setting in a project directory's `.env`, gbrain now says so and names the fix. Thanks to the reporters credited below.
|
||||
|
||||
### Fixed
|
||||
- **Self-registered OAuth clients are held to `read`/`write`.** With `--enable-dcr`, a self-registered client that requests a privileged scope (`admin`, `sources_admin`, `users_admin`, `agent`) is now rejected at registration with HTTP 400 `invalid_client_metadata` and told to use the operator path instead; machine clients registered under `--enable-dcr-insecure` are read-only. Every self-registered authorization-code connection still stops at the admin dashboard for the owner's approval before a token is issued, and a single client can no longer hold more than a small number of consent requests awaiting a decision. The consent gate is pinned end to end against a real `gbrain serve --http --enable-dcr` process. Widen a client afterward with `gbrain auth rescope-client <client_id> --scopes …`, or pre-register it with `gbrain auth register-client` / the admin API. A `client_credentials` registration without `--enable-dcr-insecure` is told the grant is not available, rather than being quoted a read-only ceiling. While self-registration is enabled, OAuth discovery advertises exactly the scopes a self-registering client may request, so a connector that copies `scopes_supported` into its registration succeeds; operator-registered clients keep their full grant. Reported by @amansk, @rohanprichard, @DanielSiva and @benmiller-SC.
|
||||
- **Remote `sources_remove` is confined to the caller's granted sources**, matching `sources_list` / `sources_status`; an out-of-scope id answers `not_found`. The local CLI is unchanged; the confinement is one shared helper for `sources_remove` and `sources_status`.
|
||||
- **`gbrain doctor` flags privileged self-registered clients.** `oauth_client_scope_health` warns about active OAuth clients that hold a scope beyond the self-registration ceiling without an operator grant record, and prints the exact `rescope-client` / `revoke-client` fix; if the grant audit schema is absent it says so instead of guessing. The privileged set is derived from the scope registry, so a future scope is audited automatically.
|
||||
- **Transcript ingest redacts credentials by wire format, not just vendor prefix.** The shared secret scanner now detects JWTs, cloud and API key shapes, `Bearer` headers, connection strings carrying inline passwords, and high-entropy `KEY=`/`TOKEN=`/`PASSWORD=` assignments, and redacts them from message bodies, speaker labels, titles and session metadata before anything is written by `gbrain transcripts ingest`. Preview with `--dry-run`. The scanner is linear on long lines — a minified or bundled line of hundreds of KB (a JSON blob of credential-less database URLs, thousands of `Bearer` headers) scans in milliseconds instead of seconds, so a pasted bundle cannot stall transcript ingest, `gbrain sources push`, or compiled-context scanning; connection-string detection no longer mistakes a credential-less URL followed by an email address for a password, finding previews redact every secret on the line, and a token that is also a connection-string password is redacted as the full credential span. Connection-string passwords pasted with unescaped `/`, braces, angle brackets, pipes, carets, backticks or backslashes are redacted, an all-caps `BEARER` header is recognized, and every detector does constant work per occurrence: JWT, high-entropy-assignment and PEM-block matching are bounded (a PEM body over 16 KB falls back to the header-only match), and corpus redaction rebuilds the text from the claimed spans in a single pass — a 1 MB transcript with thousands of distinct secrets redacts in about the time it takes to scan, and it redacts exactly the spans the scanner reports so the redacted corpus and the push-gate findings can no longer disagree. Overlapping detector matches redact the union of what every pattern matched, so a credential whose neighbouring text happens to look like a vendor identifier is never partially exposed in the page or the finding preview. A bearer token or pasted assignment value is also redacted where the same value recurs bare or embedded anywhere else in the session — across messages, speaker labels, titles and metadata, in either order — bounded (first 64 distinct values per session, values up to 512 characters, streaming so memory stays flat) so hostile page content cannot make redaction slow or memory-hungry. The private-key scanner stays linear on very large single-line inputs. Re-run `gbrain transcripts ingest` to re-render already-imported sessions. Reported by @Jack82-ai.
|
||||
- **Raw session metadata follows its page's soft delete.** `get_raw_data` no longer returns rows for a soft-deleted page, and the compiled-context sensitivity scan reports a JWT or bearer token once instead of twice. A repeat transcript import no longer rewrites unchanged session metadata on every run.
|
||||
- **Security-relevant environment variables are ignored from a project directory's `.env`.** A fixed set of `GBRAIN_*` variables — the ones that load code, name programs to run, relocate `~/.gbrain`, or widen a security posture — are no longer honored when a `.env` file in the current working directory assigns them; gbrain prints one stderr line naming the variable and where to put it instead. The check runs in compiled binaries and in every gbrain process (hooks, `serve`, `mcp`, workers). `~/.gbrain/.env` is loaded before the guardrails loader so it is a working home for `GBRAIN_GUARDRAILS_MODULE` (see Changed for the accepted spec shapes). The quarantine parses `.env` files with the same line grammar Bun uses (a bare carriage return terminates a line; a BOM or U+2028 cannot hide an assignment), also covers the loader / git / node / proxy / AI-CLI variable families a checkout could plant for the programs gbrain spawns, and re-runs gbrain once with the sanitized environment so git, the agent CLI and workers inherit the clean view. Running gbrain from inside `~/.gbrain` no longer warns about its own `.env`; the shell-job opt-in also reaches `--job-isolation process` children as `--allow-shell-jobs`. The quarantine re-runs gbrain from an empty temporary directory so the dropped variables are absent (not empty) for every program gbrain spawns, ignores a planted re-run marker, protects the XDG config roots, TLS trust stores, OpenSSL configuration loaders, temp-directory and `HOME` roots, editor/pager and every provider-endpoint variable, and lets Ctrl-C reach the running command exactly once. `GBRAIN_DATABASE_URL` and `GBRAIN_OAUTH_RELAY_URL` join the protected set: a project's `.env` can no longer choose which brain gbrain writes to or which relay hands back tokens — export them from your shell or put them in `~/.gbrain/.env`. Guardrails fail closed at this boundary too: when a project `.env` assigns `GBRAIN_GUARDRAILS_MODULE` and a value was dropped, gbrain refuses to start rather than run without the configured firewall. The quarantine also covers the shell-startup and interpreter-home family (`BASH_ENV`, `SHELLOPTS`/`PS4`, `ZDOTDIR`, `PYTHONHOME`, `GCONV_PATH`, `BASH_FUNC_*`, …); running gbrain from inside its own config directory keeps its exemption only when the project `.env` assigns none of `GBRAIN_HOME`, `HOME`, `USERPROFILE`; and the sanitized re-run always exits with the child's status, forwards Ctrl-C only when no controlling terminal exists, hands the child your real `HOME` when a planted one was dropped, exits within a second when its wrapper is force-killed (supervisor restarts no longer leave an orphaned worker), and keeps relative runtime paths (`bun --preload ./x src/cli.ts`, `--env-file .env.ci`, …) working across the hop. Reported by @dberzan.
|
||||
- **A project directory's `bunfig.toml` can no longer preload code into the compiled `gbrain` binary.** Every `bun build --compile` invocation (release workflow, `bun run build`, CI door builds, docs) now passes `--no-compile-autoload-bunfig`, and a CI guard keeps every build invocation flagged. Script-mode installs (`bun install -g`, `bun link`) run gbrain as an ordinary Bun script, which applies the current directory's `bunfig.toml` before gbrain starts; gbrain now prints a one-line warning when it finds a top-level `preload` there (see `SECURITY.md`).
|
||||
- **Source removal over MCP keys on the caller's write authority.** A federated read grant no longer lets a `sources_admin` client hard-remove a sibling source; out-of-authority ids answer `not_found` as before, `sources_status` is unchanged, and the local CLI keeps full operator authority.
|
||||
- **`gbrain delete <slug> --purge` no longer reports success while the page's markdown file is still on disk.** An already-soft-deleted page gets its file removal retried against the recorded path, and a removal failure stops with `storage_error` naming the file so you can fix it and re-run; the row stays soft-deleted until the file is gone.
|
||||
|
||||
### Added
|
||||
- **`gbrain delete <slug> --purge`** removes a page — row, chunks, links, and raw session metadata — immediately with no recovery window. Local CLI only; agents connected over MCP get `permission_denied` for `purge` and keep the recoverable soft delete, and a purge response always reports its file write-through outcome plus the copies a purge cannot reach (brain-repo history, exports, derived rows) so a credential remediation never stops at the row. The soft-delete response points at it.
|
||||
- **`gbrain jobs work --allow-shell-jobs`** — the shell-handler opt-in is now also a flag; the supervisor passes it to workers automatically so the cwd-`.env` quarantine cannot silently disable it.
|
||||
|
||||
### Changed
|
||||
- **`GBRAIN_GUARDRAILS_MODULE` accepts only an absolute path or a `~/` path.** cwd-relative specs (`./x`, `../x`) and bare package names are refused because both resolve against whatever directory gbrain happens to run in (a package name loads the current directory's `node_modules/<name>/`); a refused spec is a fail-closed exit 1 with the fix in the message. This also applies to the published `gbrain/core/guardrails` library export.
|
||||
- Connection strings with inline passwords now count as secrets for `gbrain sources push` / bootstrap verify and are dropped from compiled-context entries; declare a confirmed non-secret value safe with its fingerprint in `.gbrain-scan-allow`. The high-entropy assignment rule now requires a digit in the value, so identifier-shaped assignments in code stop being redacted.
|
||||
- Startup banner and warning text plus `docs/mcp/DEPLOY.md`, `docs/mcp/CHATGPT.md`, `SECURITY.md` and `docs/guardrails.md` describe the registration ceiling, the owner-approval step, the widen path, and the cwd-`.env` trust boundary.
|
||||
|
||||
### To take advantage of v0.50.5.0
|
||||
`gbrain upgrade`, then restart `gbrain serve --http` and run `gbrain doctor`. If it lists self-registered OAuth clients with a privileged scope you did not intend, run `gbrain auth rescope-client <client_id> --scopes read,write` or `gbrain auth revoke-client <client_id>`. Connectors that request `admin` at self-registration will now fail to register — pre-register them with `gbrain auth register-client <name> --scopes …` or let them self-register with `read write` and rescope later. If you kept `GBRAIN_GUARDRAILS_MODULE`, `GBRAIN_HOME`, a `GBRAIN_ALLOW_*` flag or another protected variable in a project's `.env`, move it to `~/.gbrain/.env` (or your service's EnvironmentFile / shell profile) — gbrain names the variable it ignored and where to put it. A hand-started worker that runs shell jobs should use `gbrain jobs work --allow-shell-jobs`. If `GBRAIN_GUARDRAILS_MODULE` is a package name or a relative path, change it to the module's absolute path (or a `~/` path) — gbrain exits 1 until you do. If you set `GBRAIN_DATABASE_URL` in a project's `.env` on purpose, export it from your shell or put it in `~/.gbrain/.env` instead. If you build the binary yourself, rebuild it with `bun run build` (**Say to your agent:** *"rebuild the gbrain binary"*) so it carries the new compile flag.
|
||||
|
||||
**Say to your agent:** *"archive my session transcripts"* / *"import my conversations"* — *"a secret leaked into a brain page — rotate it and purge the page"* (your agent rotates the credential, then runs `gbrain delete <slug> --purge` on the host) — *"run a brain health check"* (your agent runs `gbrain doctor` and follows any `oauth_client_scope_health` advice) — *"start my brain's MCP server with self-service client registration"* (your agent runs `gbrain serve --http --enable-dcr`; you approve each new connection in the admin UI).
|
||||
## [0.50.4.0] - 2026-09-16
|
||||
|
||||
### For contributors
|
||||
|
||||
@@ -522,7 +522,7 @@ ms, max waiters) for `--json`; a one-line summary prints to stderr.
|
||||
|
||||
## Build
|
||||
|
||||
`bun build --compile --outfile bin/gbrain src/cli.ts`
|
||||
`bun build --compile --no-compile-autoload-bunfig --outfile bin/gbrain src/cli.ts`
|
||||
|
||||
## Version locations (single source of truth: `VERSION` file)
|
||||
|
||||
|
||||
@@ -243,7 +243,7 @@ scanning" for details.
|
||||
## Building
|
||||
|
||||
```bash
|
||||
bun build --compile --outfile bin/gbrain src/cli.ts
|
||||
bun build --compile --no-compile-autoload-bunfig --outfile bin/gbrain src/cli.ts
|
||||
```
|
||||
|
||||
## Adding a new operation
|
||||
|
||||
12
README.md
12
README.md
@@ -305,10 +305,14 @@ How the open-loop engine decides who's waiting: [`docs/guides/open-loops.md`](do
|
||||
Your other agents' histories import in one command. `gbrain transcripts ingest`
|
||||
parses agent session logs (Claude Code, Codex, OpenClaw, Hermes, Grok Build) and extracted
|
||||
consumer chat exports (ChatGPT / Claude.ai `conversations.json`) into readable
|
||||
conversation pages with provenance back to the exact session file. Secrets are
|
||||
scrubbed from message bodies, titles, speakers, and session metadata before
|
||||
anything is written, embedding is off by default for bulk backfills, and
|
||||
re-runs are free — unchanged sessions skip on content hash:
|
||||
conversation pages with provenance back to the exact session file. Pattern-based redaction runs over message bodies, titles, speakers, and session
|
||||
metadata before anything is written — vendor key prefixes, JWTs, cloud/API key
|
||||
shapes, `Bearer` headers, connection-string credentials, and high-entropy
|
||||
`KEY=`/`TOKEN=` assignments become `<REDACTED:…>` placeholders (preview with
|
||||
`--dry-run`; no pattern set is complete, so if a secret still lands see
|
||||
["If a secret reached the brain"](SECURITY.md#if-a-secret-reached-the-brain):
|
||||
rotate it, then `gbrain delete <slug> --purge`). Embedding is off by default
|
||||
for bulk backfills, and re-runs are free — unchanged sessions skip on content hash:
|
||||
|
||||
```bash
|
||||
gbrain transcripts ingest # discover importable session logs
|
||||
|
||||
261
SECURITY.md
261
SECURITY.md
@@ -59,6 +59,163 @@ enforced structurally by actionlint on every workflow change.
|
||||
trust-on-first-use on this path. For the strongest guarantee, install the
|
||||
attested release binary and run `gh attestation verify` as above.
|
||||
|
||||
## Environment variables and cwd `.env` files
|
||||
|
||||
gbrain is usually a globally installed CLI (or a compiled binary) that runs
|
||||
with an arbitrary working directory — the repo you happen to be in, the
|
||||
workspace an agent hook fires from. Bun auto-loads `.env`, `.env.local` and
|
||||
the `.env.<NODE_ENV>[.local]` variants from that working directory into the
|
||||
process environment before any gbrain code runs, for `bun run` and for
|
||||
compiled binaries alike, and it expands `${VAR}` references inside those
|
||||
files. A `.env` committed into a cloned repository is therefore **untrusted
|
||||
input** — it was written by whoever authored the repo, not by you.
|
||||
Compiled `gbrain` binaries are built with `--no-compile-autoload-bunfig`, so a
|
||||
`bunfig.toml` in the working directory is inert — it cannot preload code into
|
||||
the binary before gbrain starts (a CI guard keeps every build invocation
|
||||
flagged). The development runtime `bun src/cli.ts` stays bun-native; a
|
||||
contributor's own working directory is trusted. Script-mode installs
|
||||
(`bun install -g github:garrytan/gbrain`, `git clone` + `bun link`) run
|
||||
`src/cli.ts` as an ordinary Bun script, and Bun applies the current
|
||||
directory's `bunfig.toml` before any gbrain code runs — gbrain prints a
|
||||
one-line warning when it finds a top-level `preload` there, but it cannot
|
||||
undo it. Only the compiled binary ignores a cwd `bunfig.toml`; run script-mode
|
||||
gbrain from directories you control, or use the release binary in untrusted
|
||||
checkouts.
|
||||
|
||||
**The trust boundary.** Security-relevant variables are honored from your
|
||||
shell environment, from a service `EnvironmentFile`, and from
|
||||
`~/.gbrain/.env` (the operator-owned secrets file). They are **never** honored
|
||||
from a `.env` file in the current directory. At startup every gbrain process
|
||||
checks the working directory's `.env` family and, for each protected variable
|
||||
that one of those files *assigns* (whatever the value — an expanded
|
||||
`${PWD}/…` looks like an ordinary absolute path by the time it reaches the
|
||||
process), drops the variable and prints one line to stderr:
|
||||
|
||||
```
|
||||
[env] Ignoring GBRAIN_PLUGIN_PATH because a .env file in the current directory assigns it — cwd .env files are untrusted for security settings. Export it from your shell or set it in ~/.gbrain/.env.
|
||||
```
|
||||
|
||||
When a `.env` file in the current directory assigns any protected variable
|
||||
(`GBRAIN_GUARDRAILS_MODULE` is the one exception — it refuses to run instead,
|
||||
see below), gbrain drops it, prints one `[env] Ignoring …` line, and then re-runs itself
|
||||
once from an empty temporary directory with the sanitized environment, switches
|
||||
back to your directory, and exits with that run's status. The re-run's
|
||||
environment simply lacks the dropped variables (they are never carried as empty
|
||||
strings, which git and the dynamic loader would treat as set), so every program
|
||||
gbrain spawns — git, the claude CLI, workers — inherits the clean view. The
|
||||
internal variable `GBRAIN_CWD_ENV_QUARANTINED` marks the re-run — it is not a
|
||||
setting, and gbrain honours it only when it provably started in the empty
|
||||
directory the marker names. A signal-killed re-run maps to exit 128+signal;
|
||||
the wrapper's exit status is always the re-run's (it relays the child and
|
||||
nothing else), and the re-run dies with its wrapper: if the wrapper is
|
||||
force-killed (SIGKILL cannot be forwarded), the re-run notices within about a
|
||||
second, removes its neutral directory and exits, so a supervisor tracking the
|
||||
wrapper's pid never leaves an orphaned worker behind. With a controlling terminal, Ctrl-C reaches the re-run directly
|
||||
from that terminal and the wrapper does not forward it; with no controlling
|
||||
terminal (a supervisor, cron, a detached harness) a SIGINT that reaches the
|
||||
wrapper alone is forwarded once so the re-run is not orphaned; SIGTERM/SIGHUP
|
||||
sent to the wrapper are always forwarded. When the dropped variable was a
|
||||
planted `HOME`, the re-run receives your real home directory (derived from the
|
||||
startup environment, never from the file) so git identity and `~/`-relative
|
||||
paths keep working. gbrain processes that gbrain itself starts from
|
||||
that directory (a supervised worker, a background push) repeat the step once
|
||||
for their own subtree. This costs nothing when the working directory has no
|
||||
`.env`, or when nothing protected is assigned there.
|
||||
|
||||
**Protected variables.** Two groups, one predicate
|
||||
(`isCwdDotenvProtectedKey` in `src/core/env-trust.ts`):
|
||||
|
||||
- The security-relevant `GBRAIN_*` keys (`CWD_DOTENV_PROTECTED_KEYS`):
|
||||
code-loading `GBRAIN_GUARDRAILS_MODULE`, `GBRAIN_PLUGIN_PATH`; exec-target
|
||||
`GBRAIN_CLAUDE_CLI_BIN`, `GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG`,
|
||||
`GBRAIN_JOB_CHILD_CLI`, `GBRAIN_BIN_OVERRIDE`; root/registry redirect
|
||||
`GBRAIN_HOME`, `GBRAIN_MOUNTS_PATH`; the brain connection string
|
||||
`GBRAIN_DATABASE_URL` (a cwd `.env` would retarget every hook, query and
|
||||
write at a database it names — the `DATABASE_URL` value guard covers only
|
||||
the bare name) and the OAuth relay `GBRAIN_OAUTH_RELAY_URL`; posture-widening
|
||||
`GBRAIN_ALLOW_SHELL_JOBS`, `GBRAIN_ALLOW_PRIVATE_REMOTES`,
|
||||
`GBRAIN_ALLOW_UNVERIFIED_REMOTE`, `GBRAIN_GIT_ALLOW_FILE_TRANSPORT`,
|
||||
`GBRAIN_ALLOW_MASS_RECONCILE`, `GBRAIN_ALLOW_DEFAULT_WRITE`,
|
||||
`GBRAIN_NO_SANITY`, `GBRAIN_REMOTE_PRIVATE_PAGES`.
|
||||
- The variable families through which a checkout could hijack the programs
|
||||
gbrain spawns rather than gbrain itself (`CWD_DOTENV_PROTECTED_PREFIXES`,
|
||||
`CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS`): the `LD_*`/`DYLD_*` dynamic-loader
|
||||
family, git configuration/hook/exec injection (`GIT_*`), Bun and npm runtime
|
||||
configuration (`BUN_*`, `NPM_CONFIG_*`/`npm_config_*`), Node preload and
|
||||
TLS knobs (`NODE_OPTIONS`, `NODE_PATH`, `NODE_EXTRA_CA_CERTS`,
|
||||
`NODE_TLS_REJECT_UNAUTHORIZED`), the `XDG_CONFIG_HOME`/`XDG_DATA_HOME`/
|
||||
`XDG_CACHE_HOME` and `GNUPGHOME` roots that git and other tools read as
|
||||
global configuration, the `SSL_CERT_FILE`/`SSL_CERT_DIR`/`CURL_CA_BUNDLE`/
|
||||
`REQUESTS_CA_BUNDLE` trust stores, the OpenSSL provider/engine loaders
|
||||
(`OPENSSL_CONF`, `OPENSSL_ENGINES`, `OPENSSL_MODULES` — a planted
|
||||
configuration loads a shared object into every OpenSSL-linked child such as
|
||||
git over https), the temp roots (`TMPDIR`, `TMP`, `TEMP`) that the sanitized
|
||||
re-run's neutral directory and every temp write resolve through, `HOME` and
|
||||
`USERPROFILE` (inert while exported, but where `HOME` is unset a planted
|
||||
value would relocate `~/.gitconfig`, `~/.ssh` and `~/.gbrain` into the
|
||||
checkout), the shell-startup and interpreter-home family the
|
||||
non-interactive shells gbrain's children start would read (`BASH_ENV`,
|
||||
`SHELLOPTS`/`PS4`, `BASHOPTS`, `PROMPT_COMMAND`, `ZDOTDIR`, `PYTHONHOME`,
|
||||
`PERLLIB`, `GCONV_PATH`, and exported functions under the `BASH_FUNC_*`
|
||||
prefix), `EDITOR`/`VISUAL`/`PAGER`, ssh askpass
|
||||
programs, interpreter preload for Python/Perl/Ruby helpers, HTTP(S)/ALL proxy
|
||||
variables in both spellings, and every AI-provider endpoint or credential
|
||||
variable gbrain's gateway reads from the environment (`CLAUDE_CONFIG_DIR`,
|
||||
`ANTHROPIC_BASE_URL`, `ANTHROPIC_AUTH_TOKEN`, `OPENAI_BASE_URL`,
|
||||
`OPENROUTER_BASE_URL`, `LITELLM_BASE_URL`, `OLLAMA_BASE_URL`,
|
||||
`LMSTUDIO_BASE_URL`, `LLAMA_SERVER_BASE_URL`, `LLAMA_SERVER_RERANKER_BASE_URL`).
|
||||
The endpoint-redirect `GBRAIN_*` keys (`GBRAIN_REMOTE_MCP_URL`,
|
||||
`GBRAIN_REMOTE_ISSUER_URL`, `GBRAIN_DIRECT_DATABASE_URL`) and the re-run
|
||||
marker itself are in the first group. This is a denylist of known hijack
|
||||
families; it grows as new families are identified.
|
||||
|
||||
`GBRAIN_GUARDRAILS_MODULE` additionally accepts only an absolute path or a
|
||||
`~/` path: cwd-relative specs and bare package names are refused (a package
|
||||
name would resolve from the current directory's `node_modules`). It is also
|
||||
the one key that fails closed at the cwd boundary: when a cwd `.env` assigns
|
||||
it and a non-empty value was dropped, gbrain does not re-run without it — it
|
||||
refuses to start (exit 1, `guardrails: GBRAIN_GUARDRAILS_MODULE is assigned by
|
||||
a .env file in the current directory; refusing to run without the operator's
|
||||
firewall …`), because Bun merges the file before gbrain starts and a value you
|
||||
exported cannot be told apart from the file's. A benign repository never
|
||||
assigns this gbrain-specific key; your own setting belongs in your shell or in
|
||||
`~/.gbrain/.env`.
|
||||
|
||||
**Semantics worth knowing.**
|
||||
|
||||
- *Per process, then inherited.* Every gbrain process re-applies the check at
|
||||
startup; the one-time sanitized re-run above is what makes the result reach
|
||||
git, the agent CLI and workers. The supervisor passes the shell-job opt-in to
|
||||
workers — and workers to per-job child processes — as the
|
||||
`--allow-shell-jobs` flag so the quarantine cannot silently disable it.
|
||||
- *Key presence, not value.* If a cwd `.env` assigns a protected key, a value
|
||||
you exported from the shell is dropped too while you stay in that directory —
|
||||
the warning tells you so. Move the setting to `~/.gbrain/.env` or run from
|
||||
another directory. A family member you exported (say `GIT_AUTHOR_NAME`) is
|
||||
untouched unless the cwd `.env` assigns that same name.
|
||||
- *Everything else still loads.* Routing and tuning `GBRAIN_*` variables and
|
||||
every variable not listed above still load from a cwd `.env` as before.
|
||||
`DATABASE_URL` keeps its own, value-matching guard (see `docs/ENGINES.md`).
|
||||
`GBRAIN_DATABASE_URL` exported from your shell is always honored, but a
|
||||
`GBRAIN_DATABASE_URL` *assigned by a cwd `.env`* is dropped like any other
|
||||
protected key — a project directory never gets to choose which brain you
|
||||
write to. Move it to your shell or `~/.gbrain/.env`.
|
||||
- *Your own config directory.* Running gbrain from inside `~/.gbrain` (or
|
||||
`$GBRAIN_HOME/.gbrain`) makes its `.env` the "cwd `.env`". That file is
|
||||
yours, so it is honored without a warning — unless a cwd `.env` assigns
|
||||
any key the config directory is derived from (`GBRAIN_HOME`, `HOME`,
|
||||
`USERPROFILE`); a planted home is never treated as your config directory.
|
||||
- *Server deployments.* `GBRAIN_ADMIN_BOOTSTRAP_TOKEN`, `GBRAIN_HTTP_CORS_ORIGIN`
|
||||
and `GBRAIN_HTTP_TRUST_PROXY` are deliberately not on the list so documented
|
||||
container deployments that co-locate them keep working — launch
|
||||
`gbrain serve --http` from a directory you control.
|
||||
- *Compiled binaries included.* The check and the sanitized re-run behave
|
||||
identically in `bun run src/cli.ts` and in the compiled `gbrain` binary.
|
||||
|
||||
If you kept one of the protected variables in a project's `.env` on purpose,
|
||||
move it to `~/.gbrain/.env` (loaded before anything else, never overriding a
|
||||
shell export) or export it from your shell profile.
|
||||
|
||||
## Remote MCP Security
|
||||
|
||||
### Keep dynamic client registration disabled unless explicitly needed
|
||||
@@ -67,12 +224,25 @@ GBrain disables Dynamic Client Registration (DCR) by default. Keep that
|
||||
default for internet-reachable deployments and pre-register trusted clients
|
||||
with operator-approved scopes and source access. Enabling DCR lets network
|
||||
callers create OAuth client records, so use it only when the deployment's
|
||||
trust model requires self-service registration and browser approval remains
|
||||
part of the authorization flow.
|
||||
trust model requires self-service registration. Self-registered clients still
|
||||
need the owner's approval in the admin dashboard for every authorization-code
|
||||
connection; DCR by itself never yields a token.
|
||||
|
||||
When DCR is on, a self-registered client passes three gates. At registration
|
||||
it may request at most `read write`; a request for any privileged scope is
|
||||
rejected with HTTP 400 `invalid_client_metadata` (never silently narrowed) and
|
||||
the error text points at the operator path (`gbrain auth register-client`, the
|
||||
admin API, or a later `gbrain auth rescope-client <client_id> --scopes ...`).
|
||||
Every authorization-code connection then stops at the admin dashboard for the
|
||||
owner's approval before a code is minted — approval never widens the
|
||||
registered scope. Finally, codes and tokens are re-intersected with the
|
||||
client's current registered scope on every request, so a rescope takes effect
|
||||
immediately.
|
||||
|
||||
Do not enable `--enable-dcr-insecure` on an untrusted network. That option is
|
||||
reserved for deployments that intentionally allow self-registered
|
||||
machine-to-machine clients without browser approval.
|
||||
machine-to-machine (`client_credentials`) clients, which are issued tokens
|
||||
without owner approval; such clients are capped at **read-only** scope.
|
||||
|
||||
### Recommended: `gbrain serve --http`
|
||||
|
||||
@@ -139,17 +309,54 @@ unknown authentication methods are rejected consistently. Browser-based
|
||||
clients can be configured entirely through the supported CLI flags; operators
|
||||
do not need to edit OAuth database rows by hand.
|
||||
|
||||
### DCR consent default (v0.42.55+)
|
||||
### DCR consent default and scope ceiling
|
||||
|
||||
The "disable `client_credentials`, only allow `authorization_code`" guidance
|
||||
above is now the built-in default for the DCR path, not just advice for custom
|
||||
above is the built-in default for the DCR path, not just advice for custom
|
||||
wrappers. With `--enable-dcr` on, a self-registered client defaults to the
|
||||
`authorization_code` (browser-approval) grant, and an explicit
|
||||
`authorization_code` (owner-approval) grant, and an explicit
|
||||
`client_credentials` request is rejected with `invalid_client_metadata`.
|
||||
Operators who genuinely need the machine-to-machine grant on the registration
|
||||
endpoint opt in with `--enable-dcr-insecure` (which implies `--enable-dcr`); a
|
||||
endpoint opt in with `--enable-dcr-insecure` (which implies `--enable-dcr`);
|
||||
those anonymous machine clients are limited to `read`. While DCR is enabled,
|
||||
OAuth discovery advertises only the self-registration ceiling (`read write`)
|
||||
as `scopes_supported`, so a client that registers with the advertised scopes
|
||||
is accepted, and an explicit request above the ceiling is still refused. A
|
||||
startup WARNING prints whenever DCR is enabled, and a second when the insecure
|
||||
grant is allowed. Pre-registering clients via the CLI / admin API is unchanged.
|
||||
grant is allowed. Pre-registering clients via the CLI / admin API is unchanged
|
||||
and accepts every scope; discovery without DCR lists every scope such a client
|
||||
may hold.
|
||||
|
||||
`gbrain doctor` (`oauth_client_scope_health`) warns about active clients that
|
||||
hold a scope beyond the self-registration ceiling but carry no operator grant
|
||||
record, with the exact `rescope-client` / `revoke-client` remedy. Remote
|
||||
`sources_remove` callers may remove only their own write source (a federated
|
||||
read grant naming a source does not make it removable); any other id answers
|
||||
`not_found`, indistinguishable from a nonexistent source. `sources_status`
|
||||
keeps the read-scope confinement it shares with `sources_list`, and the local
|
||||
CLI keeps full operator authority.
|
||||
|
||||
### Owner approval for authorization-code connections
|
||||
|
||||
`/authorize` never issues an authorization code on its own. It records a
|
||||
pending request and sends the browser to the admin dashboard, where the brain
|
||||
owner signs in (bootstrap token or magic link), reviews the client name,
|
||||
redirect URI and requested scopes, and approves or denies. Only an approval
|
||||
mints a code; the code is bound to the client, redirect URI and S256 PKCE
|
||||
challenge of the pending request and is delivered to the client's registered
|
||||
redirect URI. A denial returns `error=access_denied`. This applies equally to
|
||||
clients that self-registered through Dynamic Client Registration — with
|
||||
`--enable-dcr`, self-registration lets a network caller create a client record
|
||||
and a pending request, never a token. Revoked clients are refused at
|
||||
`/authorize` before a pending request is created.
|
||||
|
||||
Pending requests expire after ten minutes and do not survive a server restart.
|
||||
They are bounded twice: a server-wide ceiling on the in-memory store and a
|
||||
per-client ceiling of ten requests awaiting a decision. Beyond either,
|
||||
`/authorize` sends the client back to its registered redirect URI with
|
||||
`error=too_many_requests` and no code until earlier requests are decided or
|
||||
expire; a `429` status on `/authorize` comes only from the MCP SDK's built-in
|
||||
per-IP limits, which remain in force on `/authorize`, `/register` and `/token`.
|
||||
|
||||
### Token Management
|
||||
|
||||
@@ -340,3 +547,41 @@ admin SSE feed at `/admin/events`. Operators on a personal laptop who want
|
||||
raw payloads back can pass `gbrain serve --http --log-full-params` (loud
|
||||
stderr warning at startup). Multi-tenant deployments should leave it
|
||||
on the redacted default.
|
||||
|
||||
## If a secret reached the brain
|
||||
|
||||
Transcript ingest, captures and syncs redact credential-shaped strings before
|
||||
anything is written: vendor key prefixes, JWTs, cloud/API key shapes, `Bearer`
|
||||
headers, connection strings carrying inline passwords, PEM private keys, and
|
||||
high-entropy `KEY=`/`TOKEN=`/`PASSWORD=` assignments. No pattern set is
|
||||
complete. If you find a live credential in a page:
|
||||
|
||||
1. **Rotate the credential first.** Anything readable by a connected agent
|
||||
should be treated as exposed.
|
||||
2. **Remove the page immediately**, from the host machine:
|
||||
|
||||
```bash
|
||||
gbrain delete <slug> --purge
|
||||
```
|
||||
|
||||
`--purge` is honored only by the local CLI; remote/MCP callers keep the
|
||||
72-hour soft delete. It removes the row and its chunks, links and raw session
|
||||
metadata with no recovery window, and it refuses to report success while
|
||||
the page's markdown file remains on disk: it retries the removal and, if the
|
||||
file still cannot be removed, stops with `storage_error` naming the path so
|
||||
you can fix permissions and re-run (the row stays soft-deleted until the
|
||||
file is gone). Verify with `gbrain get <slug>` (expects not found).
|
||||
3. **Check the other copies.** The brain-repo git history, a synced working
|
||||
tree, an export directory or a compiled context file may still hold the
|
||||
value; rewrite/re-push or regenerate those as needed.
|
||||
4. Add a value's fingerprint (printed with every `gbrain sources push` finding)
|
||||
to `<workspace>/.gbrain-scan-allow` ONLY for values you have confirmed are
|
||||
not credentials.
|
||||
|
||||
**Say to your agent:** *"a secret leaked into a brain page — rotate it and
|
||||
purge the page"* (your agent rotates the credential, then runs
|
||||
`gbrain delete <slug> --purge` on the host).
|
||||
|
||||
Behavior note: connection strings with inline passwords now block
|
||||
`gbrain sources push` / bootstrap verify and are dropped from compiled-context
|
||||
entries. The escape hatch is the same `.gbrain-scan-allow` fingerprint line.
|
||||
|
||||
68
TODOS.md
68
TODOS.md
@@ -1,5 +1,73 @@
|
||||
# TODOS
|
||||
|
||||
|
||||
## Security fix wave follow-ups (filed 2026-09-15, follow-up from v0.50.5.0)
|
||||
|
||||
- [ ] **P2 — cwd-`.env` quarantine: decide the remaining `GBRAIN_*` variables.**
|
||||
**What:** `src/core/env-trust.ts` protects a fixed set of `GBRAIN_*` variables plus the loader / git / node / proxy / AI-CLI families. A few `GBRAIN_*` variables with plausible per-project uses (`GBRAIN_SKILLS_DIR`, `GBRAIN_RECIPES_DIR`, `GBRAIN_GITHUB_PAT` — `GBRAIN_DATABASE_URL` graduated to the protected list in v0.50.5.0) and the `serve --http` deployment trio (`GBRAIN_ADMIN_BOOTSTRAP_TOKEN`, `GBRAIN_HTTP_CORS_ORIGIN`, `GBRAIN_HTTP_TRUST_PROXY`) were deliberately left out because documented container/service deployments may co-locate them with the process cwd. **Why:** each is the same trust-boundary class; the cost is a behavior change for operators who rely on project-dir `.env` files. **Fix:** decide per variable, then add to the protected list with a "why" comment (the structural test pins the list; `_DIR` names need `SUSPICIOUS_NAME` in `test/env-trust-protected-keys.test.ts` widened). **Effort:** S. **Priority:** P2.
|
||||
- [ ] **P2 — Align the #427 `DATABASE_URL` guard with the key-presence semantics of the security quarantine.**
|
||||
**What:** `effectiveEnvDatabaseUrl` still decides by comparing the runtime value against the literal right-hand sides parsed from the cwd `.env` files, while v0.50.5.0 moved the security quarantine to key-presence (Bun may transform values before they reach the process). **Why:** two guards with two semantics over one parser is a maintenance hazard, and the documented "an exported, different URL still wins" behavior is what keeps the value-match form alive. **Fix:** either resolve variable references during the re-parse the way Bun does, or move `DATABASE_URL` to key-presence with a doc note. **Effort:** S. **Priority:** P2.
|
||||
- [ ] **P3 — Operator-configurable `redirect_uri` allow-list for dynamic client registration.**
|
||||
**What:** with `--enable-dcr`, a self-registered client may name any `https://` (or loopback / custom-scheme) redirect target; the owner sees it on the consent page but there is no server-side allow-list (e.g. loopback plus the browser-connector callback hosts). **Why:** suggested in a private report as a cheap way to narrow the phishing payoff even with consent in place. **Fix:** `oauth.dcr_redirect_allowlist` config key checked in `registerClient` before the insert; startup summary prints the effective list. **Effort:** S. **Priority:** P3.
|
||||
- [ ] **P3 — RFC 7591 initial access tokens for `/register`.**
|
||||
**What:** registration is anonymous whenever DCR is on; an operator-minted, single-use registration token would let URL-only connectors register without opening `/register` to everyone. **Why:** suggested in a private report; would also let `--enable-dcr` stay off by default for more deployments. **Effort:** M. **Priority:** P3.
|
||||
- [x] **P3 — `scopes_supported` still advertises `admin` / `sources_admin` / `users_admin` to self-registering clients.**
|
||||
**What:** OAuth metadata lists every scope the server knows except the operator-only `agent` scope (omitted from discovery since v0.50.2.0), but DCR clients are capped at `read write` (read-only for `client_credentials`), so a connector that copies `scopes_supported` into its request is rejected at `/register` or gets an empty grant at `/authorize`, and the consent page shows no badge for the dropped scope. **Fix:** either advertise the DCR-registrable subset when DCR is enabled, or have the consent page explain why a requested scope is absent. **Effort:** S. **Priority:** P3. **Completed v0.50.5.0:** discovery advertises the DCR-registrable set while DCR is enabled.
|
||||
- [ ] **P3 — Source fence for operator-registered `sources_admin` clients on the remaining `sources_*` mutating ops.**
|
||||
**What:** v0.50.5.0 confines remote `sources_remove` to the caller's write source (`assertSourceInCallerWriteScope`); `sources_archive` and the other mutating source ops still act on any id a `sources_admin` token names. **Effort:** S. **Priority:** P3.
|
||||
- [ ] **P3 — Entropy-gated assignment redaction: a hex digest after `token:` still redacts.**
|
||||
**What:** the `high_entropy_assignment` rule now requires a digit in the value (so identifiers and paths survive) but a 40-hex git sha or content hash following a `token`/`secret` keyword still redacts in transcript pages. A hex-only exemption would re-open real hex API keys, so this is a documented trade-off pending a better signal. **Effort:** S. **Priority:** P3.
|
||||
- [ ] **P2 — Next security wave: the remaining medium/low privately reported items.**
|
||||
**What:** four open reports remain after the v0.50.5.0 wave, covering admin-API key minting, private-visibility parity across every read surface, the documented untrusted-content controls, and an input-validation regex in skill-name handling; one further report is already closed on master by the v0.50.0.0 data-only frontmatter parser and only needs its advisory published. Specifics live in the maintainer's private plan file, not here, until the fixes ship. **Why:** the v0.50.5.0 wave closed the critical/high set only. **Effort:** M. **Priority:** P2.
|
||||
- [ ] **P3 — Per-client pending-consent cap is per process.**
|
||||
**What:** `OAuthGrants.begin()` bounds awaiting-decision requests server-wide (1000) and per `client_id` (10) in the in-memory store, so a multi-process deployment multiplies both ceilings. **Fix:** persist the per-client count or add a short per-client cooldown shared through the database. **Effort:** M. **Priority:** P3.
|
||||
- [ ] **P3 — `sources_add` over MCP can create a source the caller then cannot see or remove.**
|
||||
**What:** a remote `sources_admin` caller may add a source outside its own grant; with `sources_list` / `sources_status` / `sources_remove` all confined to the grant, the new source stays invisible to its creator until the operator rescopes the client (`gbrain auth rescope-client <id> --federated-read ...`). Consistent with the e2e "stays hidden until rescope" contract but surprising. **Fix:** auto-grant the creator read access, or name the rescope step in the op result hint. **Effort:** S. **Priority:** P3.
|
||||
- [ ] **P3 — Doctor `oauth_client_scope_health` arm (c) signature also matches pre-audit operator clients.**
|
||||
**What:** the "privileged self-registered client" WARN keys on `grant_revision = 0` + no `oauth_grant_audit` 'register' row, which operator clients created before the grant audit log also satisfy; the message is worded as advisory for that reason. **Fix:** a one-time backfill of `register` audit rows for existing operator-created clients would make the DCR signature exact. **Effort:** S. **Priority:** P3.
|
||||
- [ ] **P3 — Confirm the Postgres arm of the `getRawData` soft-delete parity describe on the first CI run.**
|
||||
**What:** `test/e2e/engine-parity.test.ts` gained a standalone describe whose PGLite arm ran in the implementation sandbox; the Postgres arm needs `DATABASE_URL` (no Docker there). **Effort:** XS. **Priority:** P3.
|
||||
- [ ] **P3 — Unify the `bearer` floors between secret-scan (20 chars) and the PII family (10 chars).**
|
||||
**What:** `sensitivity-scan.ts` bridges the gap by fingerprint dedupe so short bearer tokens still surface as `pii:bearer`; making secret-scan the single owner would let the PII family drop `jwt` / `bearer` entirely. **Effort:** S. **Priority:** P3.
|
||||
- [ ] **P3 — Bulk purge for a leaked transcript session.**
|
||||
**What:** a long session lands as `-pN` part pages plus raw metadata; after a leak the operator hand-lists slugs for `gbrain delete <slug> --purge`. A `gbrain transcripts purge --session <file>` would purge every part + raw row of one session. **Effort:** S. **Priority:** P3.
|
||||
- [ ] **P3 — Widen `scripts/check-pg-url-redaction.sh` to every scheme `db_url_credentials` covers.**
|
||||
**What:** the guard greps `src/` for `postgres(ql)://…@` literals only; comments could still spell a mysql/mongodb/redis URL with userinfo. **Effort:** XS. **Priority:** P3.
|
||||
- [ ] **P3 — `gbrain jobs submit shell --follow` (inline execution) reads the shell opt-in from env only.**
|
||||
**What:** `jobs work` gained `--allow-shell-jobs` because the cwd-`.env` quarantine can drop `GBRAIN_ALLOW_SHELL_JOBS`; the inline `--follow` path has no flag equivalent. **Effort:** XS. **Priority:** P3.
|
||||
- [ ] **P3 — CLI-spawning tests fail on the runtime gate instead of skipping when the host Bun is below `MINIMUM_BUN_VERSION`.**
|
||||
**What:** `test/cli-flag-validation.test.ts` subprocess smokes and every `test/helpers/cli-spawn.ts` consumer spawn `bun` from PATH; on a 1.3.10 host they fail with "GBrain requires Bun 1.3.11 or newer". **Fix:** `test.skipIf(!bunSupported)` or spawn `process.execPath`. **Effort:** XS. **Priority:** P3.
|
||||
- [ ] **P3 — `scripts/generate-flag-registry.ts` attributes `jobs work --allow-shell-jobs` to the `doctor` scan surface.**
|
||||
**What:** the `facadeExpansion` heuristic filed the new flag under `doctor`; verify that is the intended registry shape or teach the generator the `jobs work` surface. **Effort:** XS. **Priority:** P3.
|
||||
- [ ] **P3 — Pass `env: process.env` explicitly at the remaining git exec sites.**
|
||||
**What:** the sanitized re-run already cleans the environment those `execFileSync('git', …)` calls in `src/commands/doctor/bootstrap-checks.ts` and `src/core/skill-fix-gates.ts` inherit; the hook path carries the explicit env as belt-and-braces and these two do not. **Effort:** XS. **Priority:** P3.
|
||||
- [ ] **P3 — cwd-`.env` sanitized re-run when gbrain is started via `bun -e` or a wrapper with no re-runnable entry.**
|
||||
**What:** `cli-preflight.ts:selfArgv` returns null there and the process keeps the in-process-only quarantine (descendants may still see planted values). Only dev/wrapper invocations are affected. **Effort:** S. **Priority:** P3.
|
||||
- [ ] **P3 — `DeleteThroughResult.skipped` union: add `already_soft_deleted`.**
|
||||
**What:** `delete_page purge` on a tombstoned row reports `write_through: { removed: false, skipped: 'already_soft_deleted' }` via an inline `as const` (the `subagent_sandbox` precedent); widening the closed union in `write-through.ts` is a one-liner. **Effort:** XS. **Priority:** P3.
|
||||
- [ ] **P3 — Drop the dead `includeDeleted` at the transcript ingest raw probe.**
|
||||
**What:** `importFromContent` re-imports (and revives) a soft-deleted base page, so the all-skipped probe at `src/core/transcripts/ingest.ts` only ever runs against a live page; the flag is harmless but dead (pinned by the "probe never runs" test). **Effort:** XS. **Priority:** P3.
|
||||
- [ ] **P2 — Allowlist-based environment for spawned tools instead of the cwd-`.env` denylist.**
|
||||
**What:** `src/core/env-trust.ts` protects a denylist of known hijack families (loader, git, node, proxies, XDG roots, trust stores, editors, provider endpoints); a denylist is reactive by nature (the XDG config-root vector was found only in review). A per-spawn-site allowlist for git, the claude CLI and workers, built from `env-trust.ts`, would make the boundary positive. **Effort:** M. **Priority:** P2.
|
||||
- [ ] **P3 — gbrain self-spawn sites pass a pre-sanitized env + neutral cwd.**
|
||||
**What:** supervisor → worker, hook → detached push and worker → run-child inherit the hostile cwd, so each subtree pays its own sanitized re-run and warning once; `cli-preflight.ts` could export the hop env builder so descendants start clean. **Effort:** S. **Priority:** P3.
|
||||
- [ ] **P3 — cwd `bunfig.toml` under the dev runtime (`preload`) is a sibling vector to cwd `.env` for `bun src/cli.ts`.**
|
||||
**What:** compiled binaries are unaffected; decide whether preflight should refuse or warn when a cwd bunfig names a preload. **Effort:** S. **Priority:** P3.
|
||||
- [ ] **P2 — Script-mode installs still apply a project directory's `bunfig.toml` `preload` before gbrain starts.**
|
||||
**What:** the documented install (`bun install -g github:garrytan/gbrain`, `bun link`) runs `src/cli.ts` as a Bun script, and Bun applies the cwd `bunfig.toml` top-level `preload` before any gbrain code; only the compiled binary carries `--no-compile-autoload-bunfig`. Measured on Bun 1.3.13: only `bun --config=/dev/null <entry>` suppresses it — no env var, no `-c` spelling, no `--no-bunfig`. Shipped now: a one-line stderr warning from `cli-preflight.ts` when a foreign cwd declares a top-level `preload`. **Fix options:** (1) make the compiled release binary the documented user install; (2) `#!/usr/bin/env -S bun --config=/dev/null` once busybox-`env` platforms are ruled out (coreutils ≥ 8.30, macOS ≥ 10.15); (3) a thin launcher as the `bin` target that execs `bun --config=/dev/null <cli.ts>`; (4) an upstream Bun off switch. Pinned by the script-mode describe in `test/cli-cwd-dotenv-quarantine.test.ts`. **Effort:** S–M. **Priority:** P2.
|
||||
- [ ] **P3 — `removeSource` (`src/core/sources-ops.ts`) lacks the CLI's `clientsReferencingSource` pre-check.**
|
||||
**What:** `gbrain sources remove` refuses with a structured list of referencing OAuth clients; the `sources_remove` op path lets a caller whose write source IS the target pass the authority gate and hit the raw `oauth_clients.source_id` FK RESTRICT (23503) instead. Also: the CLI does not clean the managed clone dir (`_keepStorage` unused) while the op does, and remote `sources_remove` is now effectively operator-only over HTTP (every client is bound and its own source is FK-blocked) — decide whether it should stay exposed. **Fix:** share one removal path between CLI and op (pre-check + clone cleanup). **Effort:** S. **Priority:** P3.
|
||||
- [ ] **P3 — `test/pages-purge-artifact.test.ts` chmod variants skip where the caller has CAP_DAC_OVERRIDE.**
|
||||
**What:** on root / privileged runners `chmod 0555` does not block `unlink(2)`, so the two permission-denied variants skip by name; the directory-in-place variants keep the fail-closed purge path covered unconditionally. **Fix:** none needed unless CI reports the skips as coverage loss. **Effort:** XS. **Priority:** P3.
|
||||
- [ ] **P3 — Provider API keys loaded from a project `.env` are deliberately not quarantined (design decision).**
|
||||
**What:** `OPENAI_API_KEY`, `OPENROUTER_API_KEY` and the other provider credentials a cwd `.env` may assign are the operator's own spend, not a redirection of gbrain's targets, so only the `*_BASE_URL` endpoint variables are on the protected list. Revisit if a concrete path is found where a planted key (rather than a planted endpoint) moves brain content somewhere the operator did not choose. **Effort:** S. **Priority:** P3.
|
||||
- [x] **P3 — `sources_remove` confinement uses the read ladder; consider the write-authority rule for a destructive op.** **Completed: v0.50.5.0 (2026-09-16)** — `sources_remove` now keys on `assertSourceInCallerWriteScope` (`src/core/ops/context.ts`): an untrusted caller may remove only its own write source, a federated read grant confers no removal right, and out-of-authority ids answer `not_found`.
|
||||
**What (as filed):** remote `sources_remove` may name any id inside `sourceIds ?? [sourceId]` (federated read grant), while `delete_page` requires the caller's write source. A `sources_admin` token bound to `a` with `federated_read: [a, b]` can hard-remove `b`. Strict improvement over the pre-wave behavior; tightening to the write source would mirror `delete_page`. **Effort:** S. **Priority:** P3.
|
||||
- [ ] **P2 — Per-client pending-consent cap can be used to lock a known client out of consent.**
|
||||
**What:** anyone holding a `client_id` + registered `redirect_uri` (both appear in `/authorize` URLs) can hold ten pending requests per ten-minute window, so the legitimate connector is redirected with `error=too_many_requests` until the owner decides them; the cap moved the targeted-denial cost from the global capacity to ten unauthenticated requests. **Fix:** separate unauthenticated admission limits from the legitimate client's approval capacity — count per `(client_id, remote address)` with the address threaded into `begin()`, evict the oldest undecided request for that client instead of refusing, add a bulk-deny in the admin UI, or exempt operator-registered clients. Flagged independently by the pre-landing adversarial pass. **Effort:** S. **Priority:** P2.
|
||||
- [ ] **P3 — `delete_page --purge` sweep of slug-keyed derived rows without FKs.**
|
||||
**What:** the purge response names the residuals (git history, exports, compiled context, `take_proposals`/`open_loops`/`files` rows keyed by slug text); sweeping those tables would make the purge more complete. **Effort:** S. **Priority:** P3.
|
||||
|
||||
## Community fix wave follow-ups (filed 2026-09-09)
|
||||
|
||||
- [ ] **P3 — new v0.49/v0.50 tests assume `os.tmpdir()` is already a realpath (macOS `/var` vs `/private/var`).**
|
||||
|
||||
@@ -304,7 +304,10 @@ cwd-.env guard (gbrain never adopts a `DATABASE_URL` that Bun auto-loaded
|
||||
from the working directory's `.env` family: `.env`, `.env.local`, and the
|
||||
`.env.<NODE_ENV>` / `.env.<NODE_ENV>.local` variants for `development`,
|
||||
`production` and `test`; with the precedence note when both `GBRAIN_DATABASE_URL` and
|
||||
`DATABASE_URL` are set), redacted URLs only, and — on Postgres — a
|
||||
`DATABASE_URL` are set — this `DATABASE_URL` guard matches the file's VALUE; the
|
||||
security-relevant `GBRAIN_*` variables get the stricter key-presence quarantine
|
||||
described under "Environment variables and cwd `.env` files" in `SECURITY.md`),
|
||||
redacted URLs only, and — on Postgres — a
|
||||
zero-round-trip pooler block (Supabase pooler detection, prepared-statement
|
||||
resolution, pool sizes, direct/session-pooler derivability). `--brain <id>`
|
||||
resolves a mounted brain and reports the MOUNT's engine and URL source, never
|
||||
|
||||
@@ -162,7 +162,7 @@ Every non-localOnly operation on the MCP surface: 122 tools across 23 areas. **S
|
||||
| `fetch` | Fetch the full text of one search result by its `id` (OpenAI deep-research contract: the search/fetch pair). | read | | |
|
||||
| `get_chunks` | Get content chunks for a page | read | | |
|
||||
| `get_page` | Read a page by slug (supports optional fuzzy matching). | read | yes | |
|
||||
| `get_raw_data` | Retrieve raw data for a page | read | | |
|
||||
| `get_raw_data` | Retrieve raw data for a page. | read | | |
|
||||
| `get_versions` | Page version history | read | | |
|
||||
| `list_pages` | List pages with optional filters. | read | yes | |
|
||||
| `put_page` | Write or replace a page (markdown with frontmatter). | write | yes | |
|
||||
|
||||
@@ -355,8 +355,10 @@ do not opt in are unaffected.
|
||||
|
||||
To adopt, follow `skills/migrations/v0.14.0.md`. The short version:
|
||||
|
||||
1. Set `GBRAIN_ALLOW_SHELL_JOBS=1` on the worker process, then `gbrain jobs work`
|
||||
(Postgres). On PGLite, every crontab invocation uses `--follow` for inline
|
||||
1. Start the worker with `gbrain jobs work --allow-shell-jobs` (equivalently,
|
||||
export `GBRAIN_ALLOW_SHELL_JOBS=1` on the worker process; a `.env` in the
|
||||
worker's directory cannot set it) (Postgres). On PGLite, every crontab
|
||||
invocation uses `--follow` for inline
|
||||
execution; no persistent worker.
|
||||
2. Classify each of your host's cron entries: LLM-requiring (keep on gateway) vs
|
||||
deterministic (candidate for shell). Typical splits:
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -92,11 +92,42 @@ The module may export any of: a default-exported provider, a default-exported
|
||||
provider array, a named `guardrailProviders` array, or a
|
||||
`register(registerGuardrailProvider)` function (sync or async).
|
||||
|
||||
**Where the variable may come from.** The spec must be an **absolute path**
|
||||
or a **`~/` path**. Cwd-relative specs (`./x`, `../x`) are refused: they would
|
||||
resolve against whatever directory gbrain happens to run in. Bare package
|
||||
names (`some-guardrail`, `@scope/pkg`) are refused too: in the compiled binary
|
||||
a package name resolves from the *current directory's* `node_modules`, so a
|
||||
cloned repository could supply the module. The variable is honored from your
|
||||
shell environment, from a service `EnvironmentFile`, or from
|
||||
**`~/.gbrain/.env`** (the operator-owned secrets file, loaded before the
|
||||
guardrails loader runs). It is **never** honored from a `.env` file in the
|
||||
*current directory*: Bun auto-loads those files, and a cloned repository must
|
||||
not be able to choose what your gbrain executes. When a cwd `.env` assigns
|
||||
`GBRAIN_GUARDRAILS_MODULE`, gbrain drops the variable, prints one stderr line
|
||||
(`[env] Ignoring GBRAIN_GUARDRAILS_MODULE because a .env file in the current
|
||||
directory assigns it …`) and then — because it cannot tell a value you exported
|
||||
from the file's — refuses to run rather than re-running without your firewall
|
||||
(the fail-closed rule below). Every other protected variable is dropped the same
|
||||
way and gbrain re-runs itself with the sanitized environment so nothing it
|
||||
spawns sees the value either. Running gbrain from *inside*
|
||||
`~/.gbrain` is the one exception: that `.env` is your own, and it is honored
|
||||
without a warning. The same rule covers the other security-relevant `GBRAIN_*`
|
||||
variables and the loader / git / node / proxy / AI-CLI hijack families — see
|
||||
the "Environment variables and cwd `.env` files" section of `SECURITY.md`.
|
||||
|
||||
**Loading is fail-closed.** If `GBRAIN_GUARDRAILS_MODULE` is set but the module
|
||||
fails to import or registers zero providers, the CLI exits 1 instead of
|
||||
silently running without the firewall you configured. (The *classify* path
|
||||
stays fail-open — a registered provider that throws never breaks an ingest.)
|
||||
Unset, the variable costs nothing and gbrain stays inert.
|
||||
silently running without the firewall you configured. The same holds at the
|
||||
cwd boundary: when a `.env` in the current directory assigns
|
||||
`GBRAIN_GUARDRAILS_MODULE` and a non-empty value was dropped, gbrain does
|
||||
**not** re-run without it — it refuses to run (exit 1,
|
||||
`guardrails: GBRAIN_GUARDRAILS_MODULE is assigned by a .env file in the
|
||||
current directory; refusing to run without the operator's firewall …`),
|
||||
because Bun merges that file before gbrain starts and the value you exported
|
||||
cannot be told apart from the file's. Remove the assignment from the project's
|
||||
`.env` or run from another directory; a benign repository never sets this key.
|
||||
(The *classify* path stays fail-open — a registered provider that throws never
|
||||
breaks an ingest.) Unset, the variable costs nothing and gbrain stays inert.
|
||||
|
||||
### Provider responsibilities
|
||||
|
||||
|
||||
@@ -160,13 +160,17 @@ The agent's host needs a worker that processes shell jobs:
|
||||
gbrain jobs submit shell --params '{...}' --follow
|
||||
|
||||
# Persistent worker (Postgres only — PGLite uses --follow inline):
|
||||
GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs work
|
||||
gbrain jobs work --allow-shell-jobs # or: GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs work
|
||||
```
|
||||
|
||||
`GBRAIN_ALLOW_SHELL_JOBS=1` is the worker-side opt-in. Without it, shell jobs
|
||||
sit in `waiting` indefinitely. Set it on the worker process env (or in your
|
||||
deploy unit / launchd plist), not per-submission — submitter env is a weak
|
||||
proxy for worker env.
|
||||
`--allow-shell-jobs` (equivalently `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the
|
||||
worker; a `.env` in the worker's directory cannot set it) is the worker-side
|
||||
opt-in. The handler is always registered but guarded: an unflagged worker that
|
||||
claims a shell job dead-letters it immediately (`UnrecoverableError`, no
|
||||
retries) — a shell job that stays in `waiting` means no worker is running at
|
||||
all. Put the flag on the worker's command line (or the variable in its deploy
|
||||
unit / launchd plist), not per-submission — submitter env is a weak proxy for
|
||||
worker env.
|
||||
|
||||
## Decision table
|
||||
|
||||
|
||||
@@ -418,11 +418,14 @@ gbrain jobs list --status active --limit 10
|
||||
gbrain jobs list --status dead --limit 10
|
||||
|
||||
# Shell jobs enabled on the worker? There is no supervisor-status JSON field
|
||||
# for this — the gate is the GBRAIN_ALLOW_SHELL_JOBS=1 env var on the worker
|
||||
# process (the handler is always registered but guarded). Inspect the
|
||||
# supervisor's environment directly:
|
||||
ps eww -p "$(gbrain jobs supervisor status --json | jq -r '.supervisor_pid')" \
|
||||
| grep -o 'GBRAIN_ALLOW_SHELL_JOBS=[^ ]*' || echo "flag not set"
|
||||
# for this — the gate is the worker's opt-in (the handler is always registered
|
||||
# but guarded). A supervisor started with --allow-shell-jobs (or with
|
||||
# GBRAIN_ALLOW_SHELL_JOBS=1 exported) passes `--allow-shell-jobs` on the
|
||||
# worker's command line AND sets the env var on it. Inspect the worker
|
||||
# process directly (args + environment):
|
||||
for pid in $(pgrep -f 'gbrain jobs work'); do ps eww -p "$pid"; done \
|
||||
| grep -o -e '--allow-shell-jobs' -e 'GBRAIN_ALLOW_SHELL_JOBS=[^ ]*' | sort -u \
|
||||
|| echo "shell jobs not enabled"
|
||||
# An unflagged worker that claims a shell job dead-letters it instantly:
|
||||
gbrain jobs list --status dead --name shell --limit 3
|
||||
```
|
||||
|
||||
@@ -39,12 +39,15 @@ pass:
|
||||
`ctx.remote === true` (MCP callers). Independent of the env flag. Remote
|
||||
agents can never submit shell jobs. `MinionQueue.add('shell', ...)` has its
|
||||
own guard too, so an in-process handler can't programmatically bypass this.
|
||||
2. **Env flag.** The shell handler is ALWAYS registered on the worker, but it
|
||||
is guarded: unless `GBRAIN_ALLOW_SHELL_JOBS=1` is set on the worker process,
|
||||
a claimed shell job throws `UnrecoverableError` and goes straight to `dead`
|
||||
(no retries). Default: off. Your agent opts in per-host. (Always-registered
|
||||
guarded mode — not "unregistered", so unflagged workers fail shell jobs
|
||||
loudly instead of leaving them `waiting` forever.)
|
||||
2. **Worker opt-in.** The shell handler is ALWAYS registered on the worker, but
|
||||
it is guarded: unless the worker was started with
|
||||
`gbrain jobs work --allow-shell-jobs` (equivalently, `GBRAIN_ALLOW_SHELL_JOBS=1`
|
||||
exported in the worker's environment), a claimed shell job throws
|
||||
`UnrecoverableError` and goes straight to `dead` (no retries). Default: off.
|
||||
Your agent opts in per-host. A `.env` file in the worker's working directory
|
||||
cannot set the variable — gbrain ignores it there. (Always-registered guarded
|
||||
mode — not "unregistered", so unflagged workers fail shell jobs loudly
|
||||
instead of leaving them `waiting` forever.)
|
||||
|
||||
**What the env allowlist does AND does not do.** Shell jobs run with a minimal
|
||||
env: `PATH, HOME, USER, LANG, TZ, NODE_ENV`. Your secrets like `OPENAI_API_KEY`
|
||||
@@ -76,7 +79,7 @@ secrets in `env:` instead.
|
||||
On one terminal, start a persistent worker:
|
||||
|
||||
```bash
|
||||
GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs work
|
||||
gbrain jobs work --allow-shell-jobs # or: GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs work
|
||||
```
|
||||
|
||||
Rewrite crontab to submit shell jobs (no `--follow`):
|
||||
@@ -253,7 +256,7 @@ cat ~/.gbrain/audit/shell-jobs-*.jsonl | jq '.'
|
||||
# The handler is always registered but guarded: an unflagged worker that claims
|
||||
# a shell job dead-letters it immediately (UnrecoverableError, no retries).
|
||||
gbrain jobs list --status dead --name shell
|
||||
# → error_text: "shell handler disabled on this worker (set GBRAIN_ALLOW_SHELL_JOBS=1 ...)"
|
||||
# → error_text: "shell handler disabled on this worker (start it with --allow-shell-jobs or GBRAIN_ALLOW_SHELL_JOBS=1 ...)"
|
||||
# `waiting` pileups mean NO worker is running at all (flagged or not) — check
|
||||
# `gbrain jobs supervisor status` in that case.
|
||||
```
|
||||
|
||||
@@ -216,7 +216,7 @@ If the list is empty AND your submissions keep piling up, no worker is
|
||||
claiming. Start one:
|
||||
|
||||
```bash
|
||||
GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs work --concurrency 4
|
||||
gbrain jobs work --concurrency 4 --allow-shell-jobs # drop --allow-shell-jobs if you never submit shell jobs
|
||||
```
|
||||
|
||||
## Reading the DB-probe verdicts (pool starved vs server unreachable)
|
||||
|
||||
@@ -165,7 +165,7 @@ In the org's qm deployment repo (the directory `qm init` produced):
|
||||
|
||||
1. **Tool:** copy [`qm-harness-snippets/tool.json`](qm-harness-snippets/tool.json)
|
||||
to `sandbox/tools/gbrain/tool.json` and drop the compiled `gbrain` binary
|
||||
beside it (`bun build --compile --outfile gbrain src/cli.ts`, built for
|
||||
beside it (`bun build --compile --no-compile-autoload-bunfig --outfile gbrain src/cli.ts`, built for
|
||||
the sandbox image's OS/arch). `auth.credentialPaths` marks
|
||||
`~/.gbrain/config.json` as the scope's resident credential file;
|
||||
`auth.check` wires `gbrain whoami` into qm's connector status (read-scope;
|
||||
|
||||
@@ -113,6 +113,20 @@ from the `/admin` dashboard or the CLI, then reconnect. Manual
|
||||
registration per step 2 above never hits this — you pick the scopes
|
||||
explicitly.
|
||||
|
||||
**DCR scope ceiling.** The reverse also holds: a self-registering connector
|
||||
may request at most `read write`, and while `--enable-dcr` is on, OAuth
|
||||
discovery (`scopes_supported` in both the authorization-server and the
|
||||
protected-resource metadata) advertises exactly that set — so a connector
|
||||
that copies the advertised scopes into its registration succeeds. If it
|
||||
explicitly asks for `admin` anyway, registration fails with HTTP 400
|
||||
`invalid_client_metadata` rather than being quietly narrowed, and the
|
||||
connector shows a connection error. Either register the client manually
|
||||
(step 2) with the scopes you want, or let it self-register with `read
|
||||
write` and widen it afterwards with
|
||||
`gbrain auth rescope-client <client_id> --scopes ...`. Every self-registered
|
||||
connection also stops at the admin dashboard for your approval before a
|
||||
token is issued.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**"Invalid redirect_uri" during the ChatGPT connector OAuth handshake**
|
||||
|
||||
@@ -20,6 +20,26 @@ Existing sessions are preserved. Before upgrading an installation with queued
|
||||
work, follow the [authorization and worker upgrade guide](../guides/authorization-upgrade.md)
|
||||
for the coordinated cutover, consent recovery, and Bun requirements.
|
||||
|
||||
**The owner-approval step.** `/authorize` never returns an authorization code
|
||||
on its own. It records a pending request and redirects the browser to the admin
|
||||
dashboard (`/admin/?oauth_request=…`), where the brain owner signs in (bootstrap
|
||||
token or magic link), reviews the client name, redirect URI and requested
|
||||
scopes, and approves or denies. Only an approval mints the code, which is then
|
||||
delivered to the client's registered redirect URI; a denial returns
|
||||
`error=access_denied`. This applies to every authorization-code client,
|
||||
including clients that self-registered via DCR — self-registration alone never
|
||||
yields a token. Pending requests expire after ten minutes, do not survive a
|
||||
server restart, and are bounded: at most ten awaiting-decision requests per
|
||||
client and a fixed server-wide ceiling. Beyond either, `/authorize` sends the
|
||||
client back to its registered redirect URI with `error=too_many_requests`
|
||||
(and no code) until earlier requests are decided or expire; a `429` status on
|
||||
`/authorize` comes only from the MCP SDK's per-IP rate limit.
|
||||
|
||||
**Say to your agent:** *"Start the brain server over HTTP with self-service
|
||||
registration, then approve my client in the admin dashboard — your agent runs
|
||||
`gbrain serve --http --enable-dcr` and you finish the connection by approving
|
||||
it at `/admin/`."*
|
||||
|
||||
## Three Paths
|
||||
|
||||
### Local stdio (zero setup)
|
||||
@@ -211,6 +231,40 @@ await oauthProvider.registerClientManual(
|
||||
For self-service client registration (Dynamic Client Registration, RFC 7591),
|
||||
start the server with `--enable-dcr`. DCR is off by default.
|
||||
|
||||
**Say to your agent:** *"Start my brain's MCP server with self-service client
|
||||
registration — your agent runs `gbrain serve --http --enable-dcr`, and you
|
||||
approve each new connection in the admin UI."*
|
||||
|
||||
A self-registered client goes through three gates:
|
||||
|
||||
1. **Scope ceiling at registration.** Dynamic registration may request at most
|
||||
`read write`. A request naming `admin`, `sources_admin`, `users_admin`, or
|
||||
`agent` is rejected with HTTP 400 `invalid_client_metadata` (never silently
|
||||
narrowed), and the error text points at the operator path. Under
|
||||
`--enable-dcr-insecure`, a `client_credentials` registration is capped at
|
||||
`read` — a grant that skips owner approval never carries `write`. While
|
||||
DCR is enabled (either mode), OAuth discovery advertises the `read write`
|
||||
self-registration ceiling as `scopes_supported` (authorization-server and
|
||||
protected-resource metadata alike), so a client that registers with the
|
||||
advertised scopes succeeds;
|
||||
with DCR off, discovery lists every scope an operator-registered client
|
||||
may hold. `agent` is never advertised — it needs delegation bindings no
|
||||
OAuth request can carry.
|
||||
2. **Owner approval on `/authorize`.** Every authorization-code connection
|
||||
redirects to the admin dashboard, where you see the client, its redirect
|
||||
URI, and the requested scopes, and approve or deny. No code is minted
|
||||
until you approve. Consent never widens the registered scope.
|
||||
3. **Per-request clamp.** Issued codes and tokens are re-intersected with the
|
||||
client's current registered scope, so a later `rescope-client` takes effect
|
||||
on the next request.
|
||||
|
||||
To give a self-registered client more than `read write`, widen it yourself
|
||||
after the fact — `gbrain auth rescope-client <client_id> --scopes read,write,sources_admin`
|
||||
(or the admin dashboard's Agents page) — or pre-register it with
|
||||
`gbrain auth register-client` / the admin API, which accept every scope.
|
||||
`gbrain doctor` warns about active clients that hold a privileged scope but
|
||||
look self-registered.
|
||||
|
||||
Native MCP clients register cleanly: `redirect_uris` may use an app custom
|
||||
scheme (RFC 8252, e.g. `myapp://callback`) or `http://` loopback alongside
|
||||
`https://`; scopes the server doesn't know are filtered rather than fatal;
|
||||
|
||||
@@ -1507,7 +1507,7 @@ ms, max waiters) for `--json`; a one-line summary prints to stderr.
|
||||
|
||||
## Build
|
||||
|
||||
`bun build --compile --outfile bin/gbrain src/cli.ts`
|
||||
`bun build --compile --no-compile-autoload-bunfig --outfile bin/gbrain src/cli.ts`
|
||||
|
||||
## Version locations (single source of truth: `VERSION` file)
|
||||
|
||||
@@ -2963,10 +2963,14 @@ How the open-loop engine decides who's waiting: [`docs/guides/open-loops.md`](do
|
||||
Your other agents' histories import in one command. `gbrain transcripts ingest`
|
||||
parses agent session logs (Claude Code, Codex, OpenClaw, Hermes, Grok Build) and extracted
|
||||
consumer chat exports (ChatGPT / Claude.ai `conversations.json`) into readable
|
||||
conversation pages with provenance back to the exact session file. Secrets are
|
||||
scrubbed from message bodies, titles, speakers, and session metadata before
|
||||
anything is written, embedding is off by default for bulk backfills, and
|
||||
re-runs are free — unchanged sessions skip on content hash:
|
||||
conversation pages with provenance back to the exact session file. Pattern-based redaction runs over message bodies, titles, speakers, and session
|
||||
metadata before anything is written — vendor key prefixes, JWTs, cloud/API key
|
||||
shapes, `Bearer` headers, connection-string credentials, and high-entropy
|
||||
`KEY=`/`TOKEN=` assignments become `<REDACTED:…>` placeholders (preview with
|
||||
`--dry-run`; no pattern set is complete, so if a secret still lands see
|
||||
["If a secret reached the brain"](SECURITY.md#if-a-secret-reached-the-brain):
|
||||
rotate it, then `gbrain delete <slug> --purge`). Embedding is off by default
|
||||
for bulk backfills, and re-runs are free — unchanged sessions skip on content hash:
|
||||
|
||||
```bash
|
||||
gbrain transcripts ingest # discover importable session logs
|
||||
@@ -3666,7 +3670,10 @@ cwd-.env guard (gbrain never adopts a `DATABASE_URL` that Bun auto-loaded
|
||||
from the working directory's `.env` family: `.env`, `.env.local`, and the
|
||||
`.env.<NODE_ENV>` / `.env.<NODE_ENV>.local` variants for `development`,
|
||||
`production` and `test`; with the precedence note when both `GBRAIN_DATABASE_URL` and
|
||||
`DATABASE_URL` are set), redacted URLs only, and — on Postgres — a
|
||||
`DATABASE_URL` are set — this `DATABASE_URL` guard matches the file's VALUE; the
|
||||
security-relevant `GBRAIN_*` variables get the stricter key-presence quarantine
|
||||
described under "Environment variables and cwd `.env` files" in `SECURITY.md`),
|
||||
redacted URLs only, and — on Postgres — a
|
||||
zero-round-trip pooler block (Supabase pooler detection, prepared-statement
|
||||
resolution, pool sizes, direct/session-pooler derivability). `--brain <id>`
|
||||
resolves a mounted brain and reports the MOUNT's engine and URL source, never
|
||||
@@ -5780,6 +5787,26 @@ Existing sessions are preserved. Before upgrading an installation with queued
|
||||
work, follow the [authorization and worker upgrade guide](../guides/authorization-upgrade.md)
|
||||
for the coordinated cutover, consent recovery, and Bun requirements.
|
||||
|
||||
**The owner-approval step.** `/authorize` never returns an authorization code
|
||||
on its own. It records a pending request and redirects the browser to the admin
|
||||
dashboard (`/admin/?oauth_request=…`), where the brain owner signs in (bootstrap
|
||||
token or magic link), reviews the client name, redirect URI and requested
|
||||
scopes, and approves or denies. Only an approval mints the code, which is then
|
||||
delivered to the client's registered redirect URI; a denial returns
|
||||
`error=access_denied`. This applies to every authorization-code client,
|
||||
including clients that self-registered via DCR — self-registration alone never
|
||||
yields a token. Pending requests expire after ten minutes, do not survive a
|
||||
server restart, and are bounded: at most ten awaiting-decision requests per
|
||||
client and a fixed server-wide ceiling. Beyond either, `/authorize` sends the
|
||||
client back to its registered redirect URI with `error=too_many_requests`
|
||||
(and no code) until earlier requests are decided or expire; a `429` status on
|
||||
`/authorize` comes only from the MCP SDK's per-IP rate limit.
|
||||
|
||||
**Say to your agent:** *"Start the brain server over HTTP with self-service
|
||||
registration, then approve my client in the admin dashboard — your agent runs
|
||||
`gbrain serve --http --enable-dcr` and you finish the connection by approving
|
||||
it at `/admin/`."*
|
||||
|
||||
## Three Paths
|
||||
|
||||
### Local stdio (zero setup)
|
||||
@@ -5971,6 +5998,40 @@ await oauthProvider.registerClientManual(
|
||||
For self-service client registration (Dynamic Client Registration, RFC 7591),
|
||||
start the server with `--enable-dcr`. DCR is off by default.
|
||||
|
||||
**Say to your agent:** *"Start my brain's MCP server with self-service client
|
||||
registration — your agent runs `gbrain serve --http --enable-dcr`, and you
|
||||
approve each new connection in the admin UI."*
|
||||
|
||||
A self-registered client goes through three gates:
|
||||
|
||||
1. **Scope ceiling at registration.** Dynamic registration may request at most
|
||||
`read write`. A request naming `admin`, `sources_admin`, `users_admin`, or
|
||||
`agent` is rejected with HTTP 400 `invalid_client_metadata` (never silently
|
||||
narrowed), and the error text points at the operator path. Under
|
||||
`--enable-dcr-insecure`, a `client_credentials` registration is capped at
|
||||
`read` — a grant that skips owner approval never carries `write`. While
|
||||
DCR is enabled (either mode), OAuth discovery advertises the `read write`
|
||||
self-registration ceiling as `scopes_supported` (authorization-server and
|
||||
protected-resource metadata alike), so a client that registers with the
|
||||
advertised scopes succeeds;
|
||||
with DCR off, discovery lists every scope an operator-registered client
|
||||
may hold. `agent` is never advertised — it needs delegation bindings no
|
||||
OAuth request can carry.
|
||||
2. **Owner approval on `/authorize`.** Every authorization-code connection
|
||||
redirects to the admin dashboard, where you see the client, its redirect
|
||||
URI, and the requested scopes, and approve or deny. No code is minted
|
||||
until you approve. Consent never widens the registered scope.
|
||||
3. **Per-request clamp.** Issued codes and tokens are re-intersected with the
|
||||
client's current registered scope, so a later `rescope-client` takes effect
|
||||
on the next request.
|
||||
|
||||
To give a self-registered client more than `read write`, widen it yourself
|
||||
after the fact — `gbrain auth rescope-client <client_id> --scopes read,write,sources_admin`
|
||||
(or the admin dashboard's Agents page) — or pre-register it with
|
||||
`gbrain auth register-client` / the admin API, which accept every scope.
|
||||
`gbrain doctor` warns about active clients that hold a privileged scope but
|
||||
look self-registered.
|
||||
|
||||
Native MCP clients register cleanly: `redirect_uris` may use an app custom
|
||||
scheme (RFC 8252, e.g. `myapp://callback`) or `http://` loopback alongside
|
||||
`https://`; scopes the server doesn't know are filtered rather than fatal;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"id": "gbrain-context-engine",
|
||||
"name": "gbrain",
|
||||
"version": "0.50.4.0",
|
||||
"version": "0.50.5.0",
|
||||
"description": "Personal knowledge brain with Postgres + pgvector hybrid search",
|
||||
"family": "bundle-plugin",
|
||||
"configSchema": {
|
||||
|
||||
@@ -34,8 +34,8 @@
|
||||
},
|
||||
"scripts": {
|
||||
"dev": "bun run src/cli.ts",
|
||||
"build": "bun build --compile --outfile bin/gbrain src/cli.ts",
|
||||
"build:all": "bun build --compile --target=bun-darwin-arm64 --outfile bin/gbrain-darwin-arm64 src/cli.ts && bun build --compile --target=bun-linux-x64 --outfile bin/gbrain-linux-x64 src/cli.ts",
|
||||
"build": "bun build --compile --no-compile-autoload-bunfig --outfile bin/gbrain src/cli.ts",
|
||||
"build:all": "bun build --compile --no-compile-autoload-bunfig --target=bun-darwin-arm64 --outfile bin/gbrain-darwin-arm64 src/cli.ts && bun build --compile --no-compile-autoload-bunfig --target=bun-linux-x64 --outfile bin/gbrain-linux-x64 src/cli.ts",
|
||||
"build:admin": "cd admin && bun run build && cd .. && bun run scripts/build-admin-embedded.ts",
|
||||
"build:admin-embedded": "bun run scripts/build-admin-embedded.ts",
|
||||
"build:schema": "bash scripts/build-schema.sh",
|
||||
@@ -115,6 +115,7 @@
|
||||
"check:guard-self-test": "bash scripts/guard-self-test.sh",
|
||||
"check:no-legacy-getconnection": "bash scripts/check-no-legacy-getconnection.sh",
|
||||
"check:module-size": "bash scripts/check-module-size.sh",
|
||||
"check:compile-autoload": "bash scripts/check-compile-autoload.sh",
|
||||
"check:structural-manifest": "bash scripts/check-structural-manifest.sh",
|
||||
"check:orphan-modules": "node scripts/check-orphan-modules.mjs",
|
||||
"build:harness-docs": "bun run scripts/build-harness-docs.ts"
|
||||
@@ -175,7 +176,7 @@
|
||||
"bun": ">=1.3.11"
|
||||
},
|
||||
"license": "MIT",
|
||||
"version": "0.50.4.0",
|
||||
"version": "0.50.5.0",
|
||||
"overrides": {
|
||||
"@ai-sdk/provider-utils": "4.0.33",
|
||||
"@hono/node-server": "^2.0.5",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gbrain-coding",
|
||||
"version": "0.50.4.0",
|
||||
"version": "0.50.5.0",
|
||||
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
|
||||
"author": {
|
||||
"name": "Garry Tan",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gbrain-coding",
|
||||
"version": "0.50.4.0",
|
||||
"version": "0.50.5.0",
|
||||
"description": "Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant. (persona variant of the gbrain plugin — 20 skills)",
|
||||
"author": {
|
||||
"name": "Garry Tan",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!-- gbrain-plugin-tree-stamp: 0.50.4.0 -->
|
||||
<!-- gbrain-plugin-tree-stamp: 0.50.5.0 -->
|
||||
# gbrain-coding (generated persona variant — do not hand-edit)
|
||||
|
||||
Brain-first coding agent working inside a repo: retrieval, routing, ingest discipline, correction hygiene. Default persona for the claude-code harness bridge; also published as the gbrain-coding marketplace variant.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gbrain-daily",
|
||||
"version": "0.50.4.0",
|
||||
"version": "0.50.5.0",
|
||||
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)",
|
||||
"author": {
|
||||
"name": "Garry Tan",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "gbrain-daily",
|
||||
"version": "0.50.4.0",
|
||||
"version": "0.50.5.0",
|
||||
"description": "Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant. (persona variant of the gbrain plugin — 19 skills)",
|
||||
"author": {
|
||||
"name": "Garry Tan",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!-- gbrain-plugin-tree-stamp: 0.50.4.0 -->
|
||||
<!-- gbrain-plugin-tree-stamp: 0.50.5.0 -->
|
||||
# gbrain-daily (generated persona variant — do not hand-edit)
|
||||
|
||||
Personal knowledge-brain daily use: meetings, tasks, briefings, reading, research. Published as the gbrain-daily marketplace variant.
|
||||
|
||||
@@ -193,7 +193,8 @@ a recurring shell job shaped like:
|
||||
gbrain jobs submit shell --params '{"cmd": "cd <brain-repo> && git add projects/<pipeline-name> <output-dirs> && git commit -m \"<pipeline-name> ingest checkpoint\" && git push"}'
|
||||
```
|
||||
|
||||
Shell jobs require `GBRAIN_ALLOW_SHELL_JOBS=1` on the WORKER environment — see
|
||||
Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`
|
||||
(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — see
|
||||
minion-orchestrator Preconditions. Do not set it yourself: it is an RCE-class
|
||||
authorization that belongs to the operator running the daemon, and a submit-side
|
||||
env prefix (`GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs submit ...`) is a no-op in
|
||||
|
||||
@@ -283,7 +283,8 @@ gbrain jobs submit shell --params '{"cmd": "<your pipeline command> --offset 0 -
|
||||
gbrain agent run "Read skills/<pipeline-name>/SKILL.md and process the next 50 pending manifest items"
|
||||
```
|
||||
|
||||
Shell jobs require `GBRAIN_ALLOW_SHELL_JOBS=1` on the WORKER environment — see
|
||||
Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`
|
||||
(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — see
|
||||
minion-orchestrator Preconditions; do not set it yourself (it is an RCE-class
|
||||
operator authorization, and a submit-side env prefix is a no-op in the daemon
|
||||
lane). Small sets (<1000 items) can run inline in chunks; anything that must
|
||||
|
||||
@@ -81,11 +81,18 @@ fingerprint — running with a different cap (or dropping it) starts a fresh
|
||||
watermark scope, so a capped run's skipped tail is never mistaken for
|
||||
already-scanned.
|
||||
|
||||
Native-vs-manual delta to know: the native lane redacts SECRETS (key
|
||||
patterns) plus your `~/.gbrain/harvest-private-patterns.txt` regexes and
|
||||
counts agent-directed imperatives into frontmatter, but broad PII detection
|
||||
(names, phones, addresses) remains YOUR review pass — the manual procedure's
|
||||
human scrub step still applies to sensitive corpora. Two more deltas: the
|
||||
Native-vs-manual delta to know: the native lane redacts SECRETS by FORMAT
|
||||
(vendor key prefixes, JWTs, cloud/API key shapes, `Bearer` headers,
|
||||
connection strings carrying inline passwords, PEM private keys, and
|
||||
high-entropy `KEY=`/`TOKEN=`/`PASSWORD=` assignments) plus your
|
||||
`~/.gbrain/harvest-private-patterns.txt` regexes and counts agent-directed
|
||||
imperatives into frontmatter, but broad PII detection (names, phones,
|
||||
addresses) remains YOUR review pass — the manual procedure's human scrub step
|
||||
still applies to sensitive corpora. Preview what will be scrubbed with
|
||||
`--dry-run` before a bulk `--all`. If a secret still reached a page, rotate
|
||||
it first, then remove the page immediately with
|
||||
`gbrain delete <slug> --purge` (local CLI only — no 72h tombstone); the
|
||||
brain-repo git history or a synced file may still hold it. Two more deltas: the
|
||||
native lane caps each message at ~4K characters in the page body (readable
|
||||
archive, not verbatim — the session file named in `source_uri` stays the
|
||||
verbatim record), and tool/thinking traffic appears only as one-line
|
||||
@@ -141,9 +148,11 @@ Before writing each page, scan the transcript for secret-shaped strings and
|
||||
PII, and redact each match to a labeled placeholder (`[REDACTED_API_KEY]`,
|
||||
`[REDACTED_TOKEN]`, `[REDACTED_EMAIL]`):
|
||||
|
||||
- OpenAI-style keys (`sk-…`), GitHub tokens (`ghp_…`), AWS access-key ids
|
||||
(`AKIA…`), bearer/authorization tokens, and long high-entropy hex or base64
|
||||
blobs.
|
||||
- Vendor-prefixed keys (`sk-…`, `ghp_…`, `AKIA…`/`ASIA…`, `AIza…`,
|
||||
`sk_live_…`, `glpat-…`, `npm_…`, `hf_…`), format-only credentials with NO
|
||||
prefix (JWTs `eyJ….eyJ….…`, account SIDs, connection strings with an inline
|
||||
password), bearer/authorization tokens, PEM private-key blocks, and
|
||||
`KEY=`/`TOKEN=`/`PASSWORD=` assignments whose value is high-entropy.
|
||||
- Personal data the transcript wasn't meant to publish: phone numbers, home
|
||||
addresses, government ids, private emails.
|
||||
|
||||
@@ -400,9 +409,12 @@ This skill guarantees:
|
||||
`conversations/<provider>/YYYY-MM-DD-<slug>.md` with `type: conversation`,
|
||||
a `date:` frontmatter field, and a verbatim transcript in a
|
||||
parser-recognized message format.
|
||||
- Every conversation is scanned for secret-shaped strings and PII before its
|
||||
page is written; matches are redacted to labeled placeholders and counted in
|
||||
the import receipt (untrusted-content convention).
|
||||
- Every conversation is scanned for secret-shaped strings (by wire format,
|
||||
not just vendor prefix — JWTs, cloud/API key shapes, connection-string
|
||||
credentials, high-entropy assignments) and PII before its page is written;
|
||||
matches are redacted to labeled placeholders and counted in the import
|
||||
receipt (untrusted-content convention). A page that still captured a
|
||||
secret is removed immediately with `gbrain delete <slug> --purge`.
|
||||
- Colliding slugs (untitled/same-day threads) are disambiguated with a short
|
||||
stable thread hash and check-before-write, never overwritten.
|
||||
- Every import run validates a sample via `gbrain conversation-parser scan`
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
<!-- gbrain-plugin-tree-stamp: 0.50.4.0 -->
|
||||
<!-- gbrain-plugin-tree-stamp: 0.50.5.0 -->
|
||||
# gbrain plugin skill tree (generated — do not hand-edit)
|
||||
|
||||
This tree is the curated skill set for the gbrain Codex and Claude Code
|
||||
|
||||
@@ -193,7 +193,8 @@ a recurring shell job shaped like:
|
||||
gbrain jobs submit shell --params '{"cmd": "cd <brain-repo> && git add projects/<pipeline-name> <output-dirs> && git commit -m \"<pipeline-name> ingest checkpoint\" && git push"}'
|
||||
```
|
||||
|
||||
Shell jobs require `GBRAIN_ALLOW_SHELL_JOBS=1` on the WORKER environment — see
|
||||
Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`
|
||||
(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — see
|
||||
minion-orchestrator Preconditions. Do not set it yourself: it is an RCE-class
|
||||
authorization that belongs to the operator running the daemon, and a submit-side
|
||||
env prefix (`GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs submit ...`) is a no-op in
|
||||
|
||||
@@ -283,7 +283,8 @@ gbrain jobs submit shell --params '{"cmd": "<your pipeline command> --offset 0 -
|
||||
gbrain agent run "Read skills/<pipeline-name>/SKILL.md and process the next 50 pending manifest items"
|
||||
```
|
||||
|
||||
Shell jobs require `GBRAIN_ALLOW_SHELL_JOBS=1` on the WORKER environment — see
|
||||
Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`
|
||||
(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — see
|
||||
minion-orchestrator Preconditions; do not set it yourself (it is an RCE-class
|
||||
operator authorization, and a submit-side env prefix is a no-op in the daemon
|
||||
lane). Small sets (<1000 items) can run inline in chunks; anything that must
|
||||
|
||||
@@ -81,11 +81,18 @@ fingerprint — running with a different cap (or dropping it) starts a fresh
|
||||
watermark scope, so a capped run's skipped tail is never mistaken for
|
||||
already-scanned.
|
||||
|
||||
Native-vs-manual delta to know: the native lane redacts SECRETS (key
|
||||
patterns) plus your `~/.gbrain/harvest-private-patterns.txt` regexes and
|
||||
counts agent-directed imperatives into frontmatter, but broad PII detection
|
||||
(names, phones, addresses) remains YOUR review pass — the manual procedure's
|
||||
human scrub step still applies to sensitive corpora. Two more deltas: the
|
||||
Native-vs-manual delta to know: the native lane redacts SECRETS by FORMAT
|
||||
(vendor key prefixes, JWTs, cloud/API key shapes, `Bearer` headers,
|
||||
connection strings carrying inline passwords, PEM private keys, and
|
||||
high-entropy `KEY=`/`TOKEN=`/`PASSWORD=` assignments) plus your
|
||||
`~/.gbrain/harvest-private-patterns.txt` regexes and counts agent-directed
|
||||
imperatives into frontmatter, but broad PII detection (names, phones,
|
||||
addresses) remains YOUR review pass — the manual procedure's human scrub step
|
||||
still applies to sensitive corpora. Preview what will be scrubbed with
|
||||
`--dry-run` before a bulk `--all`. If a secret still reached a page, rotate
|
||||
it first, then remove the page immediately with
|
||||
`gbrain delete <slug> --purge` (local CLI only — no 72h tombstone); the
|
||||
brain-repo git history or a synced file may still hold it. Two more deltas: the
|
||||
native lane caps each message at ~4K characters in the page body (readable
|
||||
archive, not verbatim — the session file named in `source_uri` stays the
|
||||
verbatim record), and tool/thinking traffic appears only as one-line
|
||||
@@ -141,9 +148,11 @@ Before writing each page, scan the transcript for secret-shaped strings and
|
||||
PII, and redact each match to a labeled placeholder (`[REDACTED_API_KEY]`,
|
||||
`[REDACTED_TOKEN]`, `[REDACTED_EMAIL]`):
|
||||
|
||||
- OpenAI-style keys (`sk-…`), GitHub tokens (`ghp_…`), AWS access-key ids
|
||||
(`AKIA…`), bearer/authorization tokens, and long high-entropy hex or base64
|
||||
blobs.
|
||||
- Vendor-prefixed keys (`sk-…`, `ghp_…`, `AKIA…`/`ASIA…`, `AIza…`,
|
||||
`sk_live_…`, `glpat-…`, `npm_…`, `hf_…`), format-only credentials with NO
|
||||
prefix (JWTs `eyJ….eyJ….…`, account SIDs, connection strings with an inline
|
||||
password), bearer/authorization tokens, PEM private-key blocks, and
|
||||
`KEY=`/`TOKEN=`/`PASSWORD=` assignments whose value is high-entropy.
|
||||
- Personal data the transcript wasn't meant to publish: phone numbers, home
|
||||
addresses, government ids, private emails.
|
||||
|
||||
@@ -400,9 +409,12 @@ This skill guarantees:
|
||||
`conversations/<provider>/YYYY-MM-DD-<slug>.md` with `type: conversation`,
|
||||
a `date:` frontmatter field, and a verbatim transcript in a
|
||||
parser-recognized message format.
|
||||
- Every conversation is scanned for secret-shaped strings and PII before its
|
||||
page is written; matches are redacted to labeled placeholders and counted in
|
||||
the import receipt (untrusted-content convention).
|
||||
- Every conversation is scanned for secret-shaped strings (by wire format,
|
||||
not just vendor prefix — JWTs, cloud/API key shapes, connection-string
|
||||
credentials, high-entropy assignments) and PII before its page is written;
|
||||
matches are redacted to labeled placeholders and counted in the import
|
||||
receipt (untrusted-content convention). A page that still captured a
|
||||
secret is removed immediately with `gbrain delete <slug> --purge`.
|
||||
- Colliding slugs (untitled/same-day threads) are disambiguated with a short
|
||||
stable thread hash and check-before-write, never overwritten.
|
||||
- Every import run validates a sample via `gbrain conversation-parser scan`
|
||||
|
||||
@@ -117,9 +117,12 @@ tasks where no LLM reasoning loop is needed.
|
||||
|
||||
### Preconditions (read before submitting your first shell job)
|
||||
|
||||
- **`GBRAIN_ALLOW_SHELL_JOBS=1` must be set on the worker environment.**
|
||||
Without it, the shell handler refuses to register and submissions sit in
|
||||
`waiting` silently. Gate lives in `src/core/minions/handlers/shell.ts`.
|
||||
- **The worker must be started with `gbrain jobs work --allow-shell-jobs`** (equivalently `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker; a `.env` in the worker's directory cannot set it).
|
||||
The shell handler is always registered but guarded: an unflagged worker that
|
||||
claims a shell job dead-letters it immediately (`UnrecoverableError`, straight
|
||||
to `dead`, no retries) with the flag named in `error_text`. A job that sits in
|
||||
`waiting` means NO worker is running at all — check
|
||||
`gbrain jobs supervisor status`. Gate lives in `src/core/minions/handlers/shell.ts`.
|
||||
- **Security:** flipping `GBRAIN_ALLOW_SHELL_JOBS=1` authorizes arbitrary
|
||||
command execution on the worker. On a shared queue, this is a remote code
|
||||
execution surface. Treat as privileged infrastructure authorization.
|
||||
@@ -314,7 +317,8 @@ bare background shell except this skill saying don't.
|
||||
### Rung 1 — Minion job + deadman (Postgres + worker)
|
||||
|
||||
Requires: Postgres engine, a running `gbrain jobs work` worker, and — for
|
||||
the shell lane — `GBRAIN_ALLOW_SHELL_JOBS=1` on the worker. All the
|
||||
the shell lane — a worker started with `--allow-shell-jobs` (or
|
||||
`GBRAIN_ALLOW_SHELL_JOBS=1` exported on it). All the
|
||||
Preconditions above still hold: the flag defaults OFF, shell submission is
|
||||
CLI-only across the MCP trust boundary, and PGLite has no worker daemon
|
||||
(see Rung 3). Nothing in this section loosens that contract.
|
||||
|
||||
64
scripts/check-compile-autoload.sh
Executable file
64
scripts/check-compile-autoload.sh
Executable file
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env bash
|
||||
# CI guard: every `bun build --compile` invocation must carry
|
||||
# `--no-compile-autoload-bunfig`.
|
||||
#
|
||||
# Why: a compiled Bun binary auto-loads a `bunfig.toml` from the CURRENT
|
||||
# DIRECTORY at startup and runs its `preload` scripts BEFORE any of the
|
||||
# binary's own code — before cli-preflight.ts, before the cwd-.env quarantine.
|
||||
# gbrain is a globally installed CLI that runs from arbitrary checkouts, so a
|
||||
# hostile repository carrying `bunfig.toml` + `preload = ["./x.ts"]` would get
|
||||
# code execution from a plain `gbrain --version` (verified on Bun 1.3.13). The
|
||||
# flag makes a cwd bunfig.toml inert for the compiled binary. The dev runtime
|
||||
# (`bun src/cli.ts`) stays bun-native: a contributor's cwd is trusted.
|
||||
#
|
||||
# Invocation shapes checked (one line each):
|
||||
# (a) shell / YAML / markdown: `bun build --compile … --outfile …`
|
||||
# (b) TS/JS spawn arrays: ['build', '--compile', …] / ["build", "--compile", …]
|
||||
# Prose that merely names `bun build --compile` (no --outfile) is not an
|
||||
# invocation and is ignored.
|
||||
#
|
||||
# Scan set: package.json, CLAUDE.md, CONTRIBUTING.md, .github/, scripts/, docs/
|
||||
# (relative to the guard root). test/ compile helpers are deliberately out of
|
||||
# scope here — they build throwaway binaries run from temp dirs.
|
||||
#
|
||||
# Self-test seam: GBRAIN_GUARD_ROOT (fixture tree root) — guard-self-test.sh
|
||||
# runs this against test/fixtures/guards/check-compile-autoload.sh/{bad,good}.
|
||||
#
|
||||
# Usage: scripts/check-compile-autoload.sh
|
||||
# Exit: 0 when every invocation carries the flag, 1 otherwise.
|
||||
|
||||
set -uo pipefail
|
||||
|
||||
ROOT="${GBRAIN_GUARD_ROOT:-$(git rev-parse --show-toplevel 2>/dev/null || pwd)}"
|
||||
cd "$ROOT" || exit 1
|
||||
|
||||
FLAG='--no-compile-autoload-bunfig'
|
||||
SELF="scripts/$(basename "$0")"
|
||||
|
||||
TARGETS=()
|
||||
for t in package.json CLAUDE.md CONTRIBUTING.md .github scripts docs; do
|
||||
[ -e "$t" ] && TARGETS+=("$t")
|
||||
done
|
||||
if [ "${#TARGETS[@]}" -eq 0 ]; then
|
||||
echo "FAIL: nothing to scan under $ROOT (expected package.json / .github / scripts / docs)" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# (a) one-line CLI invocation: `bun build --compile` followed later on the line by `--outfile`
|
||||
# (b) spawn-array form: 'build', '--compile' (either quote style, optional whitespace)
|
||||
SHAPE_A='bun build --compile[^`]*--outfile'
|
||||
SHAPE_B="['\"]build['\"],[[:space:]]*['\"]--compile['\"]"
|
||||
|
||||
hits="$(grep -rnE --exclude="$(basename "$SELF")" -e "$SHAPE_A" -e "$SHAPE_B" "${TARGETS[@]}" 2>/dev/null | grep -v -- "$FLAG" || true)"
|
||||
|
||||
if [ -n "$hits" ]; then
|
||||
echo "ERROR: bun build --compile invocation(s) without $FLAG:" >&2
|
||||
echo "$hits" >&2
|
||||
echo >&2
|
||||
echo " A compiled binary auto-loads a cwd bunfig.toml and runs its preload scripts" >&2
|
||||
echo " before any gbrain code. Add $FLAG to every compile invocation" >&2
|
||||
echo " (CLI form: right after --compile; spawn arrays: as the element after '--compile')." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "OK: every bun build --compile invocation carries $FLAG"
|
||||
@@ -20,7 +20,7 @@ cd "$REPO_ROOT"
|
||||
OUT_BIN="$(mktemp /tmp/gbrain-img-decoders-check.XXXXXX)"
|
||||
trap 'rm -f "$OUT_BIN"' EXIT
|
||||
|
||||
bun build --compile --outfile "$OUT_BIN" scripts/image-decoders-smoketest.ts >/dev/null 2>&1
|
||||
bun build --compile --no-compile-autoload-bunfig --outfile "$OUT_BIN" scripts/image-decoders-smoketest.ts >/dev/null 2>&1
|
||||
|
||||
OUTPUT="$("$OUT_BIN" 2>&1 || true)"
|
||||
|
||||
|
||||
@@ -46,7 +46,7 @@ ln -s "$REPO_ROOT/node_modules" "$BUILD_DIR/node_modules"
|
||||
|
||||
# Compile a focused smoketest (imports PGLiteEngine, not the whole CLI) so the
|
||||
# failure mode is laser-focused on PGLite asset embedding, not unrelated wiring.
|
||||
if ! (cd "$BUILD_DIR" && bun build --compile --outfile "$OUT_BIN" scripts/pglite-embedded-smoketest.ts >"$BUILD_DIR/compile.log" 2>&1); then
|
||||
if ! (cd "$BUILD_DIR" && bun build --compile --no-compile-autoload-bunfig --outfile "$OUT_BIN" scripts/pglite-embedded-smoketest.ts >"$BUILD_DIR/compile.log" 2>&1); then
|
||||
# In some sandboxes `bun build --compile` is unavailable (no network for the
|
||||
# baseline download, seccomp, etc). Fail SOFT there — like the compiled-binary
|
||||
# e2e — so local dev without compile support isn't blocked. CI has compile.
|
||||
|
||||
@@ -34,7 +34,7 @@ ln -s "$REPO_ROOT/node_modules" "$BUILD_DIR/node_modules"
|
||||
# Build a minimal smoketest binary that imports the chunker. We compile this
|
||||
# instead of the full gbrain CLI so the failure mode is laser-focused on
|
||||
# chunker + WASM path resolution, not unrelated CLI wiring.
|
||||
if ! (cd "$BUILD_DIR" && bun build --compile --outfile "$OUT_BIN" scripts/chunker-smoketest.ts >/dev/null); then
|
||||
if ! (cd "$BUILD_DIR" && bun build --compile --no-compile-autoload-bunfig --outfile "$OUT_BIN" scripts/chunker-smoketest.ts >/dev/null); then
|
||||
echo "[check-wasm-embedded] FAIL: bun could not compile the smoketest binary." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -187,7 +187,7 @@ function ensureGbrainBinary(explicit: string | undefined, rebuild: boolean): str
|
||||
}
|
||||
fs.mkdirSync(binDir, { recursive: true });
|
||||
log('compiling gbrain (bun build --compile)…');
|
||||
const res = spawnSync('bun', ['build', '--compile', '--outfile', binPath, 'src/cli.ts'], {
|
||||
const res = spawnSync('bun', ['build', '--compile', '--no-compile-autoload-bunfig', '--outfile', binPath, 'src/cli.ts'], {
|
||||
cwd: REPO_ROOT,
|
||||
encoding: 'utf8',
|
||||
timeout: 300_000,
|
||||
|
||||
@@ -46,6 +46,7 @@ check-key-files-current-state.sh scanner todo
|
||||
check-exports-count.sh scanner todo was reachable from neither verify nor CI pre-W0 (check:all only)
|
||||
check-trailing-newline.sh scanner todo was reachable from neither verify nor CI pre-W0 (check:all only)
|
||||
check-test-isolation.sh scanner todo allowlist data file: check-test-isolation.allowlist
|
||||
check-compile-autoload.sh scanner yes every `bun build --compile` invocation (CLI one-liners + TS spawn arrays) in package.json/.github/scripts/docs/CLAUDE.md/CONTRIBUTING.md must carry --no-compile-autoload-bunfig (a cwd bunfig.toml preload runs before cli-preflight in a compiled binary)
|
||||
check-admin-build.sh buildfresh exempt runs the admin build; the build is the test
|
||||
check-admin-embedded.sh buildfresh exempt embed freshness diff; not in verify CHECKS: duplicates check:admin-build's build
|
||||
check-admin-scope-drift.sh buildfresh exempt regenerates + diffs
|
||||
|
||||
|
File diff suppressed because one or more lines are too long
@@ -123,6 +123,8 @@ CHECKS=(
|
||||
# Containment sprint: module-size ratchet + structural-suite freshness.
|
||||
"check:module-size"
|
||||
"check:structural-manifest"
|
||||
# v0.50.5.0 security wave: compiled binaries must not autoload a cwd bunfig.toml.
|
||||
"check:compile-autoload"
|
||||
)
|
||||
|
||||
if [ "${#CHECKS[@]}" -eq 0 ]; then
|
||||
|
||||
@@ -139,6 +139,7 @@ test/e2e/openclaw-reference-compat.test.ts OpenClaw reference workspace compat (
|
||||
test/e2e/skillpack-flow.test.ts skillpack flow (E2E) 17 readFileSync
|
||||
test/e2e/workspace-generic-compat.test.ts generic agent-workspace compat (INSTALL_FOR_AGENTS.md flow) 6 readFileSync
|
||||
test/embedding-dim-check-facts.test.ts doctor checkFactsEmbeddingWidthConsistency wiring (T6) 4 doctor-source-helper
|
||||
test/env-trust-protected-keys.test.ts CWD_DOTENV_PROTECTED_KEYS covers every suspicious GBRAIN_* env read in src/ 3 readFileSync
|
||||
test/eval-brainbench-e2e.slow.test.ts --llm availability gate 1 exec-scan
|
||||
test/eval-brainbench-e2e.slow.test.ts privacy guard violation branches (negative path) 1 exec-scan
|
||||
test/eval-brainbench-e2e.slow.test.ts render-brainbench-delta.ts (the CI step-summary block) 2 exec-scan
|
||||
@@ -177,6 +178,8 @@ test/fix-wave-structural.test.ts v0.42.43.0 #2095 — volunteer-events sink + cy
|
||||
test/frontmatter-install-hook.test.ts frontmatter install-hook (B13) 22 readFileSync
|
||||
test/harness-onboarding.test.ts harness identity and private handoff 5 readFileSync
|
||||
test/hook-command.serial.test.ts user-prompt 14 readFileSync
|
||||
test/hook-push-spawn-env.test.ts spawnDetachedPush env handoff 2 readFileSync
|
||||
test/hook-push-spawn-env.test.ts tryExecAsync env handoff 1 readFileSync
|
||||
test/integrations-install.test.ts installRecipeIntoHostRepo — happy path 6 readFileSync
|
||||
test/integrations.test.ts CLI integration 3 readFileSync
|
||||
test/jobs-embed-background-parity.serial.test.ts embed job background parity (D7) 2 readFileSync
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 44 and column 63.
|
@@ -193,7 +193,8 @@ a recurring shell job shaped like:
|
||||
gbrain jobs submit shell --params '{"cmd": "cd <brain-repo> && git add projects/<pipeline-name> <output-dirs> && git commit -m \"<pipeline-name> ingest checkpoint\" && git push"}'
|
||||
```
|
||||
|
||||
Shell jobs require `GBRAIN_ALLOW_SHELL_JOBS=1` on the WORKER environment — see
|
||||
Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`
|
||||
(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — see
|
||||
minion-orchestrator Preconditions. Do not set it yourself: it is an RCE-class
|
||||
authorization that belongs to the operator running the daemon, and a submit-side
|
||||
env prefix (`GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs submit ...`) is a no-op in
|
||||
|
||||
@@ -283,7 +283,8 @@ gbrain jobs submit shell --params '{"cmd": "<your pipeline command> --offset 0 -
|
||||
gbrain agent run "Read skills/<pipeline-name>/SKILL.md and process the next 50 pending manifest items"
|
||||
```
|
||||
|
||||
Shell jobs require `GBRAIN_ALLOW_SHELL_JOBS=1` on the WORKER environment — see
|
||||
Shell jobs require the WORKER to be started with `gbrain jobs work --allow-shell-jobs`
|
||||
(or `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker) — see
|
||||
minion-orchestrator Preconditions; do not set it yourself (it is an RCE-class
|
||||
operator authorization, and a submit-side env prefix is a no-op in the daemon
|
||||
lane). Small sets (<1000 items) can run inline in chunks; anything that must
|
||||
|
||||
@@ -81,11 +81,18 @@ fingerprint — running with a different cap (or dropping it) starts a fresh
|
||||
watermark scope, so a capped run's skipped tail is never mistaken for
|
||||
already-scanned.
|
||||
|
||||
Native-vs-manual delta to know: the native lane redacts SECRETS (key
|
||||
patterns) plus your `~/.gbrain/harvest-private-patterns.txt` regexes and
|
||||
counts agent-directed imperatives into frontmatter, but broad PII detection
|
||||
(names, phones, addresses) remains YOUR review pass — the manual procedure's
|
||||
human scrub step still applies to sensitive corpora. Two more deltas: the
|
||||
Native-vs-manual delta to know: the native lane redacts SECRETS by FORMAT
|
||||
(vendor key prefixes, JWTs, cloud/API key shapes, `Bearer` headers,
|
||||
connection strings carrying inline passwords, PEM private keys, and
|
||||
high-entropy `KEY=`/`TOKEN=`/`PASSWORD=` assignments) plus your
|
||||
`~/.gbrain/harvest-private-patterns.txt` regexes and counts agent-directed
|
||||
imperatives into frontmatter, but broad PII detection (names, phones,
|
||||
addresses) remains YOUR review pass — the manual procedure's human scrub step
|
||||
still applies to sensitive corpora. Preview what will be scrubbed with
|
||||
`--dry-run` before a bulk `--all`. If a secret still reached a page, rotate
|
||||
it first, then remove the page immediately with
|
||||
`gbrain delete <slug> --purge` (local CLI only — no 72h tombstone); the
|
||||
brain-repo git history or a synced file may still hold it. Two more deltas: the
|
||||
native lane caps each message at ~4K characters in the page body (readable
|
||||
archive, not verbatim — the session file named in `source_uri` stays the
|
||||
verbatim record), and tool/thinking traffic appears only as one-line
|
||||
@@ -141,9 +148,11 @@ Before writing each page, scan the transcript for secret-shaped strings and
|
||||
PII, and redact each match to a labeled placeholder (`[REDACTED_API_KEY]`,
|
||||
`[REDACTED_TOKEN]`, `[REDACTED_EMAIL]`):
|
||||
|
||||
- OpenAI-style keys (`sk-…`), GitHub tokens (`ghp_…`), AWS access-key ids
|
||||
(`AKIA…`), bearer/authorization tokens, and long high-entropy hex or base64
|
||||
blobs.
|
||||
- Vendor-prefixed keys (`sk-…`, `ghp_…`, `AKIA…`/`ASIA…`, `AIza…`,
|
||||
`sk_live_…`, `glpat-…`, `npm_…`, `hf_…`), format-only credentials with NO
|
||||
prefix (JWTs `eyJ….eyJ….…`, account SIDs, connection strings with an inline
|
||||
password), bearer/authorization tokens, PEM private-key blocks, and
|
||||
`KEY=`/`TOKEN=`/`PASSWORD=` assignments whose value is high-entropy.
|
||||
- Personal data the transcript wasn't meant to publish: phone numbers, home
|
||||
addresses, government ids, private emails.
|
||||
|
||||
@@ -400,9 +409,12 @@ This skill guarantees:
|
||||
`conversations/<provider>/YYYY-MM-DD-<slug>.md` with `type: conversation`,
|
||||
a `date:` frontmatter field, and a verbatim transcript in a
|
||||
parser-recognized message format.
|
||||
- Every conversation is scanned for secret-shaped strings and PII before its
|
||||
page is written; matches are redacted to labeled placeholders and counted in
|
||||
the import receipt (untrusted-content convention).
|
||||
- Every conversation is scanned for secret-shaped strings (by wire format,
|
||||
not just vendor prefix — JWTs, cloud/API key shapes, connection-string
|
||||
credentials, high-entropy assignments) and PII before its page is written;
|
||||
matches are redacted to labeled placeholders and counted in the import
|
||||
receipt (untrusted-content convention). A page that still captured a
|
||||
secret is removed immediately with `gbrain delete <slug> --purge`.
|
||||
- Colliding slugs (untitled/same-day threads) are disambiguated with a short
|
||||
stable thread hash and check-before-write, never overwritten.
|
||||
- Every import run validates a sample via `gbrain conversation-parser scan`
|
||||
|
||||
@@ -117,9 +117,12 @@ tasks where no LLM reasoning loop is needed.
|
||||
|
||||
### Preconditions (read before submitting your first shell job)
|
||||
|
||||
- **`GBRAIN_ALLOW_SHELL_JOBS=1` must be set on the worker environment.**
|
||||
Without it, the shell handler refuses to register and submissions sit in
|
||||
`waiting` silently. Gate lives in `src/core/minions/handlers/shell.ts`.
|
||||
- **The worker must be started with `gbrain jobs work --allow-shell-jobs`** (equivalently `GBRAIN_ALLOW_SHELL_JOBS=1` exported on the worker; a `.env` in the worker's directory cannot set it).
|
||||
The shell handler is always registered but guarded: an unflagged worker that
|
||||
claims a shell job dead-letters it immediately (`UnrecoverableError`, straight
|
||||
to `dead`, no retries) with the flag named in `error_text`. A job that sits in
|
||||
`waiting` means NO worker is running at all — check
|
||||
`gbrain jobs supervisor status`. Gate lives in `src/core/minions/handlers/shell.ts`.
|
||||
- **Security:** flipping `GBRAIN_ALLOW_SHELL_JOBS=1` authorizes arbitrary
|
||||
command execution on the worker. On a shared queue, this is a remote code
|
||||
execution surface. Treat as privileged infrastructure authorization.
|
||||
@@ -314,7 +317,8 @@ bare background shell except this skill saying don't.
|
||||
### Rung 1 — Minion job + deadman (Postgres + worker)
|
||||
|
||||
Requires: Postgres engine, a running `gbrain jobs work` worker, and — for
|
||||
the shell lane — `GBRAIN_ALLOW_SHELL_JOBS=1` on the worker. All the
|
||||
the shell lane — a worker started with `--allow-shell-jobs` (or
|
||||
`GBRAIN_ALLOW_SHELL_JOBS=1` exported on it). All the
|
||||
Preconditions above still hold: the flag defaults OFF, shell submission is
|
||||
CLI-only across the MCP trust boundary, and PGLite has no worker daemon
|
||||
(see Rung 3). Nothing in this section loosens that contract.
|
||||
|
||||
@@ -27,8 +27,8 @@
|
||||
"brain-taxonomist/routing-eval.jsonl": "8b485b3d735aace60be703854f0f2e9d97c52d52564efdaf7334a0c39e8d20ae",
|
||||
"briefing/SKILL.md": "f86ad2238104de20433436dcc8f2cc5534e7df8dad4e4845252f85b8290cde53",
|
||||
"briefing/routing-eval.jsonl": "c056fea88f673e324d6a72cb70438cd6fcdbd09ec2cd036d44eb31a9ea6bf33d",
|
||||
"bulk-ingestion/MANIFEST-PATTERN.md": "0df53fdf8b59bf14601761f6c1cce413bb494f0d5ebc3e6fa96feccfda7e5737",
|
||||
"bulk-ingestion/SKILL.md": "bf23978d710d53884252b15f647212c7f59e7ca081b05aa2fb5a93941893f546",
|
||||
"bulk-ingestion/MANIFEST-PATTERN.md": "6180f09d2dc8d9af5749149f2b3c34c40213f5d6b262b69484e864adbb652b47",
|
||||
"bulk-ingestion/SKILL.md": "8149c1ff02b320b80c3850d5f837cbebbdc8e088b24da7da9a78046f919ba9aa",
|
||||
"bulk-ingestion/routing-eval.jsonl": "2bf8ffaf90b8ef761fa3cef54bf3af2eb8cc3ef736d054b5bf8b9361f6448d5a",
|
||||
"capture/SKILL.md": "98568ac96331f57397ea072749641d9748b1ce31e8b09d512b8db25c8fcda65f",
|
||||
"chat-connectors/SKILL.md": "f0218cab53f7e82d1543ba8c6f574b39821ecae780219aa5d408586a00de8062",
|
||||
@@ -60,7 +60,7 @@
|
||||
"conventions/subagent-routing.md": "8b8830b815a9a8581a12b489f966c0b0a39eb9b5f66e905a691a03653eef348d",
|
||||
"conventions/test-before-bulk.md": "6b2c52cda9e2cd5f04c15152b3d92aeb7187ab193a15082be0f8a3991a6a5725",
|
||||
"conventions/untrusted-content.md": "259384d490892cd0e1e8e054decf752d7354f516c83aee57b332c1a96aac6a6e",
|
||||
"conversation-archive/SKILL.md": "de2b44da329c4601da8c77536a627b094e52a93c8f45032335571b29b311d736",
|
||||
"conversation-archive/SKILL.md": "0d27c637f56fc10f8d27c1f0a02aedf70e2bac4355436e9f67f81b0bc120e3ba",
|
||||
"conversation-archive/routing-eval.jsonl": "ae087a84b1fd5b108b7cdab8d035a09b3ccecd8aad53ba5f71e463059108cfca",
|
||||
"correction-pipeline/SKILL.md": "caf1264b7afec46569d30f6d92b07f37ae375e3f4e6aeddd58866aec327053de",
|
||||
"correction-pipeline/routing-eval.jsonl": "7f8d96606a8d7bed3d79fdcee6904764c8abb9fa0b506adb414b5c4805b69d0b",
|
||||
@@ -143,7 +143,7 @@
|
||||
"migrations/v0.8.1.md": "fad7341cfb5e02545fb8a23221d12ab395fc3d8db15d1d8ee8a18844aea6563a",
|
||||
"migrations/v0.9.0.md": "773fab0a8d7f330576265a3f510c1f318f47789b6136c46d43e08121acbc20eb",
|
||||
"migrations/v0.9.1.md": "75761bad6c0ad37b69ec8197c6a678bb6a1484f9a76e4b70f2d1e86dc80102b3",
|
||||
"minion-orchestrator/SKILL.md": "63e7ead284ae03f039e5789e1479d9e49d8897cb2cedf1663746c727d86fd3be",
|
||||
"minion-orchestrator/SKILL.md": "10686e03951d793cbdadfa9111325f05fabf27a4fa0c18894f4857288203dbaa",
|
||||
"minion-orchestrator/routing-eval.jsonl": "501ed2e19cb16847ff8425219d246b7a774de1accd42cb28fd44edbb64204992",
|
||||
"perplexity-research/SKILL.md": "c25f5c471cbe3c6e0f975d8397e8382b00a85f8aa75302231d53c52855369e97",
|
||||
"perplexity-research/routing-eval.jsonl": "f1a40d87e710d5d2acd602a372d83f46c95da022b6e635228fffeaacb3bb2b27",
|
||||
|
||||
18
src/cli.ts
18
src/cli.ts
@@ -36,6 +36,7 @@ import type { Operation, OperationContext } from './core/operations.ts';
|
||||
import { shouldForceExitAfterMain, finishCliTeardown, flushThenExit, currentExitCode, setCliExitVerdict, writeStdoutFinal, installStdoutPipeDelivery } from './core/cli-force-exit.ts';
|
||||
import { serializeMarkdown } from './core/markdown.ts';
|
||||
import { parseGlobalFlags, setCliOptions, getCliOptions } from './core/cli-options.ts';
|
||||
import { runCliPreflight } from './core/cli-preflight.ts';
|
||||
import { conceptNudge } from './core/search/query-intent.ts';
|
||||
import type { CliOptions } from './core/cli-options.ts';
|
||||
import { callRemoteTool, RemoteMcpError, unpackToolResult, extractResponseMeta } from './core/mcp-client.ts';
|
||||
@@ -449,6 +450,9 @@ function maybeEmitUpdateMarker(command: string): void {
|
||||
}
|
||||
|
||||
async function main() {
|
||||
// cwd-.env quarantine → ~/.gbrain/.env → #3688 guardrails loader (fail-closed).
|
||||
await runCliPreflight();
|
||||
|
||||
// Parse global flags (--quiet / --progress-json / --progress-interval)
|
||||
// BEFORE command dispatch, so `gbrain --progress-json doctor` works.
|
||||
// The stripped argv is what the command sees.
|
||||
@@ -456,20 +460,6 @@ async function main() {
|
||||
const { cliOpts, rest: args } = parseGlobalFlags(rawArgs);
|
||||
setCliOptions(cliOpts);
|
||||
|
||||
// #3688: operator-configured guardrail providers load before ANY command
|
||||
// dispatch. Fail-closed by design: when GBRAIN_GUARDRAILS_MODULE is set but
|
||||
// broken, abort rather than silently run without the operator's firewall.
|
||||
// (Unset → zero cost, the OSS distribution stays inert.)
|
||||
if (process.env.GBRAIN_GUARDRAILS_MODULE) {
|
||||
try {
|
||||
const { loadGuardrailProvidersFromEnv } = await import('./core/guardrails.ts');
|
||||
await loadGuardrailProvidersFromEnv();
|
||||
} catch (err) {
|
||||
console.error(`guardrails: ${(err as Error)?.message ?? String(err)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
let command = args[0];
|
||||
|
||||
if (!command || command === '--help' || command === '-h') {
|
||||
|
||||
@@ -44,10 +44,11 @@ export function resolveWhoknowsFixturePath(
|
||||
env: NodeJS.ProcessEnv = process.env,
|
||||
moduleUrl: string = import.meta.url,
|
||||
): string | null {
|
||||
if (env.GBRAIN_WHOKNOWS_FIXTURE_PATH) {
|
||||
return isAbsolute(env.GBRAIN_WHOKNOWS_FIXTURE_PATH)
|
||||
? env.GBRAIN_WHOKNOWS_FIXTURE_PATH
|
||||
: resolvePath(process.cwd(), env.GBRAIN_WHOKNOWS_FIXTURE_PATH);
|
||||
// cwd-dotenv-ok: doctor test-fixture path override; the check only READS that jsonl, never loads or executes it.
|
||||
const override = env.GBRAIN_WHOKNOWS_FIXTURE_PATH;
|
||||
if (override) {
|
||||
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- override is the operator-set GBRAIN_WHOKNOWS_FIXTURE_PATH doctor test-fixture path (the check only READS that jsonl, never loads or executes it); absolutizing the operator's own relative path against the process cwd is the intent, unchanged from the pre-hoist form
|
||||
return isAbsolute(override) ? override : resolvePath(process.cwd(), override);
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
@@ -9,8 +9,18 @@ import type { BrainEngine } from '../../../core/engine.ts';
|
||||
import { gbrainPath } from '../../../core/config.ts';
|
||||
import { embedBackfillWorkerSurface } from '../../../core/minions/embed-backfill-admission.ts';
|
||||
import { isUndefinedTableError, isUndefinedColumnError } from '../../../core/utils.ts';
|
||||
import { ALLOWED_SCOPES_LIST, DCR_REGISTRABLE_SCOPES } from '../../../core/scope.ts';
|
||||
import type { Check } from '../../doctor.ts';
|
||||
|
||||
/**
|
||||
* Scopes beyond the anonymous-DCR ceiling — DERIVED as the complement of
|
||||
* `DCR_REGISTRABLE_SCOPES` over `ALLOWED_SCOPES_LIST` (never hand-copied), so
|
||||
* a scope added to scope.ts is audited by arm (c) below automatically.
|
||||
*/
|
||||
export const DCR_PRIVILEGED_SCOPES: ReadonlyArray<string> = Object.freeze(
|
||||
ALLOWED_SCOPES_LIST.filter((s) => !DCR_REGISTRABLE_SCOPES.has(s)),
|
||||
);
|
||||
|
||||
/**
|
||||
* v0.37.7.0 — Tier 5K source_routing_health (D5 lock: 200-page total cap).
|
||||
*
|
||||
@@ -264,7 +274,52 @@ export async function checkOauthClientScopeHealth(engine: BrainEngine): Promise<
|
||||
if (!(isUndefinedTableError(e) && /facts/i.test(msg))) throw e;
|
||||
orphaned = await engine.executeRaw<{ id: string }>(orphanSql(false), [WORKSPACE_SUFFIX]);
|
||||
}
|
||||
// (c) PRIVILEGED SELF-REGISTERED CLIENTS — an active row whose scope
|
||||
// exceeds the DCR ceiling (read/write) AND carries the anonymous-DCR
|
||||
// signature: grant_revision = 0 with no oauth_grant_audit 'register' row
|
||||
// (every operator path writes one). Nothing sweeps such rows on upgrade,
|
||||
// so this is the operator's visibility into clients that were registered
|
||||
// before the ceiling existed (or that predate the grant audit log — the
|
||||
// same signature, hence ADVISORY). Fail-open to "unknown" when the audit
|
||||
// table / revision column is absent: without them the signature cannot be
|
||||
// evaluated and guessing would either lie green or cry wolf.
|
||||
let privilegedDcr: Array<{ client_id: string; client_name: string | null; scope: string }> = [];
|
||||
let privilegedDcrNote: string | null = null;
|
||||
// Word-bounded match over the DERIVED complement (scope ids are [a-z_]+,
|
||||
// so the alternation needs no escaping); bound as a parameter, never
|
||||
// interpolated into the SQL text.
|
||||
const privilegedScopeRegex = `(^|[[:space:]])(${DCR_PRIVILEGED_SCOPES.join('|')})([[:space:]]|$)`;
|
||||
const dcrCeiling = [...DCR_REGISTRABLE_SCOPES];
|
||||
try {
|
||||
privilegedDcr = await engine.executeRaw<{ client_id: string; client_name: string | null; scope: string }>(
|
||||
`SELECT c.client_id, c.client_name, c.scope
|
||||
FROM oauth_clients c
|
||||
WHERE c.deleted_at IS NULL
|
||||
AND COALESCE(c.grant_revision, 0) = 0
|
||||
AND COALESCE(c.scope, '') ~ $1
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM oauth_grant_audit a
|
||||
WHERE a.client_id = c.client_id AND a.action = 'register'
|
||||
)
|
||||
ORDER BY c.client_id`,
|
||||
[privilegedScopeRegex],
|
||||
);
|
||||
} catch (e) {
|
||||
if (!(isUndefinedTableError(e) || isUndefinedColumnError(e, 'grant_revision'))) throw e;
|
||||
privilegedDcrNote = 'self-registered-client scope audit skipped: grant audit schema not present (run `gbrain apply-migrations --yes`), so privileged self-registered clients are unknown';
|
||||
}
|
||||
const problems: string[] = [];
|
||||
if (privilegedDcr.length > 0) {
|
||||
const shown = privilegedDcr.slice(0, 5)
|
||||
.map(c => `"${c.client_name ?? c.client_id}" (${c.client_id}) scope=${c.scope}`);
|
||||
problems.push(
|
||||
`${privilegedDcr.length} active OAuth client(s) hold a scope beyond the self-registration ceiling (${dcrCeiling.join('/')}) ` +
|
||||
`and look self-registered (no operator grant record): ${shown.join('; ')}` +
|
||||
(privilegedDcr.length > 5 ? ` (+${privilegedDcr.length - 5} more)` : '') +
|
||||
`. If you did not register these yourself, narrow with \`gbrain auth rescope-client <client_id> --scopes ${dcrCeiling.join(',')}\` ` +
|
||||
`or remove with \`gbrain auth revoke-client <client_id>\`.`,
|
||||
);
|
||||
}
|
||||
if (dangling.length > 0) {
|
||||
const byClient = new Map<string, { name: string | null; grants: string[] }>();
|
||||
for (const d of dangling) {
|
||||
@@ -298,7 +353,8 @@ export async function checkOauthClientScopeHealth(engine: BrainEngine): Promise<
|
||||
return {
|
||||
name: 'oauth_client_scope_health',
|
||||
status: 'ok',
|
||||
message: 'Scoped-client grants consistent (no dangling federated reads, no orphaned workspace sources)',
|
||||
message: 'Scoped-client grants consistent (no dangling federated reads, no orphaned workspace sources' +
|
||||
(privilegedDcrNote ? `; ${privilegedDcrNote})` : ', no privileged self-registered clients)'),
|
||||
};
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
|
||||
@@ -144,6 +144,7 @@ export async function runExport(engine: BrainEngine, args: string[]) {
|
||||
// page's own on a key collision.
|
||||
const rawData = await engine.getRawData(page.slug, undefined, {
|
||||
sourceId: page.source_id,
|
||||
includeDeleted: true, // the page list decides which rows export; raw follows its page
|
||||
});
|
||||
if (rawData.length > 0) {
|
||||
const slugParts = page.slug.split('/');
|
||||
|
||||
@@ -719,10 +719,10 @@ async function statusFileNotice(): Promise<string | null> {
|
||||
const HOOK_GIT_TIMEOUT_MS = 1000;
|
||||
|
||||
/**
|
||||
* Async execFile wrapper: the hook push paths must NEVER block the event
|
||||
* loop with execFileSync — a slow repo/network would keep withDeadline's
|
||||
* timer from ever firing and stall the harness for minutes. null on any
|
||||
* failure (missing binary, non-zero exit, timeout).
|
||||
* Async execFile wrapper: hook push paths must NEVER block the event loop with
|
||||
* execFileSync (a slow repo/network would stall withDeadline's timer for minutes).
|
||||
* null on any failure (missing binary, non-zero exit, timeout). Explicit `env`:
|
||||
* git must see the cwd-.env quarantine (env-trust.ts), not Bun's startup snapshot.
|
||||
*/
|
||||
function tryExecAsync(bin: string, args: string[], timeoutMs = HOOK_GIT_TIMEOUT_MS): Promise<string | null> {
|
||||
return new Promise((resolve) => {
|
||||
@@ -730,7 +730,7 @@ function tryExecAsync(bin: string, args: string[], timeoutMs = HOOK_GIT_TIMEOUT_
|
||||
execFile(
|
||||
bin,
|
||||
args,
|
||||
{ timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024 },
|
||||
{ timeout: timeoutMs, maxBuffer: 4 * 1024 * 1024, env: process.env },
|
||||
(err, stdout) => resolve(err ? null : stdout.toString().trim()),
|
||||
);
|
||||
} catch {
|
||||
@@ -813,7 +813,9 @@ function spawnDetachedPush(root: string): void {
|
||||
// Compiled binary: execPath IS gbrain. Dev (bun src/cli.ts): re-exec the
|
||||
// entrypoint — the jobs.ts --detach precedent.
|
||||
const argv = /[/\\]gbrain(\.exe)?$/.test(exec) ? pushArgs : [process.argv[1], ...pushArgs];
|
||||
const child = spawn(exec, argv, { detached: true, stdio: 'ignore' });
|
||||
// Explicit env: a child spawned without one does not see the parent's
|
||||
// cwd-.env quarantine deletions (core/env-trust.ts).
|
||||
const child = spawn(exec, argv, { detached: true, stdio: 'ignore', env: process.env });
|
||||
child.unref();
|
||||
}
|
||||
|
||||
|
||||
@@ -435,9 +435,9 @@ HANDLER TYPES (built in)
|
||||
extract Extract links + timeline entries; '{"mode":"all"}'
|
||||
backlinks Check or fix back-links; '{"action":"fix"}'
|
||||
autopilot-cycle One autopilot pass (sync+extract+embed+backlinks)
|
||||
shell Run a command or argv. Requires GBRAIN_ALLOW_SHELL_JOBS=1
|
||||
on the worker. Params: {cmd?, argv?, cwd, env?}.
|
||||
See: docs/guides/minions-shell-jobs.md
|
||||
shell Run a command or argv. Requires --allow-shell-jobs (or
|
||||
GBRAIN_ALLOW_SHELL_JOBS=1) on the worker. Params: {cmd?,
|
||||
argv?, cwd, env?}. See: docs/guides/minions-shell-jobs.md
|
||||
|
||||
Detailed help: gbrain jobs {work|supervisor|submit|watch|prune} --help
|
||||
Other subcommands are fully described above.
|
||||
@@ -456,10 +456,13 @@ const JOBS_SUBCOMMAND_HELP: Record<string, string> = {
|
||||
USAGE
|
||||
gbrain jobs work [--queue Q] [--concurrency N] [--max-rss MB]
|
||||
[--health-interval MS] [--nice N]
|
||||
[--job-isolation inline|process]
|
||||
[--job-isolation inline|process] [--allow-shell-jobs]
|
||||
|
||||
OPTIONS
|
||||
--queue Q Queue to claim from (default: default)
|
||||
--allow-shell-jobs Enable the shell handler on this worker. Equivalent to
|
||||
exporting GBRAIN_ALLOW_SHELL_JOBS=1 from your shell; a
|
||||
.env in the working directory cannot set it.
|
||||
--job-isolation M inline (default): handlers run in the worker process.
|
||||
process: each claimed job runs in its own child
|
||||
process — a stuck handler is group-SIGKILLed instead
|
||||
@@ -811,18 +814,19 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):
|
||||
} catch { /* audit failures never block submission */ }
|
||||
|
||||
// Starvation warning (DX polish). Fire for every non-`--follow` shell submit
|
||||
// regardless of the submitter's own `GBRAIN_ALLOW_SHELL_JOBS` — the submitter
|
||||
// env is a weak proxy for the worker env (they may run on different machines),
|
||||
// so the warning remains useful any time the job might sit in 'waiting'.
|
||||
// regardless of the submitter's own `GBRAIN_ALLOW_SHELL_JOBS` — submitter env
|
||||
// is a weak proxy for worker env. Two outcomes: no worker → the job waits;
|
||||
// an UNFLAGGED worker → the always-registered guarded handler dead-letters it.
|
||||
if (!follow && name === 'shell') {
|
||||
process.stderr.write(
|
||||
`\n⚠ Shell jobs require GBRAIN_ALLOW_SHELL_JOBS=1 on the worker process.\n` +
|
||||
` Your job was queued (id=${job.id}) but will sit in 'waiting' until a\n` +
|
||||
` worker with the env flag starts. To run now:\n\n` +
|
||||
`\n⚠ Shell jobs require the shell handler enabled on the worker process\n` +
|
||||
` (--allow-shell-jobs, or GBRAIN_ALLOW_SHELL_JOBS=1 exported from your shell).\n` +
|
||||
` Your job was queued (id=${job.id}). It waits until a worker starts; a worker\n` +
|
||||
` WITHOUT shell jobs enabled dead-letters it immediately (no retries). To run now:\n\n` +
|
||||
` GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs submit shell \\\n` +
|
||||
` --params '...' --follow\n\n` +
|
||||
` Or start a persistent worker (Postgres only — PGLite uses --follow):\n\n` +
|
||||
` GBRAIN_ALLOW_SHELL_JOBS=1 gbrain jobs work\n\n`,
|
||||
` gbrain jobs work --allow-shell-jobs\n\n`,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1483,6 +1487,9 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):
|
||||
// exit. Deliberately absent from user-facing help. The CLI layer owns
|
||||
// engine.disconnect() + process.exit() (engine-ownership invariant).
|
||||
{
|
||||
// --allow-shell-jobs (buildChildArgs pass-through): same re-assert as
|
||||
// `work` — this child's preflight re-ran the cwd-.env quarantine.
|
||||
if (hasFlag(args, '--allow-shell-jobs')) process.env.GBRAIN_ALLOW_SHELL_JOBS = '1';
|
||||
const config = loadConfig();
|
||||
if (config?.engine === 'pglite') {
|
||||
console.error('[run-child] process isolation requires the Postgres engine.');
|
||||
@@ -1538,6 +1545,12 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
// --allow-shell-jobs (supervisor pass-through, see buildWorkerArgs): the
|
||||
// startup cwd-.env quarantine drops GBRAIN_ALLOW_SHELL_JOBS when a .env
|
||||
// in this worker's cwd assigns it, so the flag re-asserts the operator's
|
||||
// opt-in AFTER preflight. Read sites keep checking the env var.
|
||||
if (hasFlag(args, '--allow-shell-jobs')) process.env.GBRAIN_ALLOW_SHELL_JOBS = '1';
|
||||
|
||||
const queueName = parseFlag(args, '--queue') ?? 'default';
|
||||
const concurrency = resolveWorkerConcurrency(args);
|
||||
// --max-rss: explicit value wins (including 0 to disable the watchdog).
|
||||
@@ -1987,7 +2000,7 @@ export async function runJobs(engineOrNull: BrainEngine | null, args: string[]):
|
||||
healthInterval = parsed;
|
||||
}
|
||||
const allowShellJobs = hasFlag(args, '--allow-shell-jobs') ||
|
||||
!!process.env.GBRAIN_ALLOW_SHELL_JOBS;
|
||||
process.env.GBRAIN_ALLOW_SHELL_JOBS === '1'; // same literal the shell handler checks
|
||||
const detach = hasFlag(args, '--detach');
|
||||
// Supervisor's --max-rss: explicit wins; absent → cgroup-aware auto-size
|
||||
// (issue #1678). The supervisor is the main production path, so the
|
||||
@@ -2816,17 +2829,17 @@ export async function registerBuiltinHandlers(
|
||||
};
|
||||
});
|
||||
|
||||
// Shell handler is always registered. Runtime env guard lives inside the
|
||||
// handler so claimed jobs emit a clear rejection log on workers missing
|
||||
// GBRAIN_ALLOW_SHELL_JOBS=1.
|
||||
// Shell handler is always registered. Runtime guard lives inside the handler
|
||||
// so claimed jobs emit a clear rejection log on workers started without
|
||||
// --allow-shell-jobs (the flag sets GBRAIN_ALLOW_SHELL_JOBS=1 after preflight).
|
||||
{
|
||||
const { shellHandler } = await import('../core/minions/handlers/shell.ts');
|
||||
worker.register('shell', shellHandler);
|
||||
if (!quiet) {
|
||||
if (process.env.GBRAIN_ALLOW_SHELL_JOBS === '1') {
|
||||
process.stderr.write('[minion worker] shell handler enabled (GBRAIN_ALLOW_SHELL_JOBS=1)\n');
|
||||
process.stderr.write('[minion worker] shell handler enabled (--allow-shell-jobs / GBRAIN_ALLOW_SHELL_JOBS=1)\n');
|
||||
} else {
|
||||
process.stderr.write('[minion worker] shell handler registered in guarded mode (set GBRAIN_ALLOW_SHELL_JOBS=1 to execute shell jobs)\n');
|
||||
process.stderr.write('[minion worker] shell handler registered in guarded mode (start with `gbrain jobs work --allow-shell-jobs`, or export GBRAIN_ALLOW_SHELL_JOBS=1, to execute shell jobs)\n');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -551,8 +551,9 @@ export async function copyPageToTarget(
|
||||
}, sourceOpts);
|
||||
}
|
||||
|
||||
// Copy raw data
|
||||
const rawData = await source.getRawData(page.slug, undefined, sourceOpts);
|
||||
// Copy raw data (includeDeleted: a migration copies whatever the page row
|
||||
// carries — the page list already decided which rows travel).
|
||||
const rawData = await source.getRawData(page.slug, undefined, { ...sourceOpts, includeDeleted: true });
|
||||
for (const rd of rawData) {
|
||||
await target.putRawData(page.slug, rd.source, rd.data, sourceOpts);
|
||||
}
|
||||
|
||||
@@ -49,7 +49,7 @@ import {
|
||||
dcrRegistrationContext,
|
||||
DEFAULT_DCR_TTL_MIN_SECONDS,
|
||||
} from '../core/oauth-provider.ts';
|
||||
import { hasScope, ALLOWED_SCOPES_LIST, normalizeScopesInput } from '../core/scope.ts';
|
||||
import { hasScope, scopesSupportedForDiscovery, normalizeScopesInput } from '../core/scope.ts';
|
||||
import { normalizeTokenScopes } from '../core/legacy-token-scope.ts';
|
||||
import { normalizeSourceInput, normalizeFederatedReadInput } from '../core/source-id.ts';
|
||||
import { summarizeMcpParams, dispatchToolCall, requestLogStatusForResult } from '../mcp/dispatch.ts';
|
||||
@@ -993,15 +993,15 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
// logs, not buried in the neutral "DCR: enabled" banner line.
|
||||
if (enableDcr) {
|
||||
console.error(
|
||||
'SECURITY WARNING: Dynamic Client Registration (--enable-dcr) is ON. ' +
|
||||
'Any network caller can self-register an OAuth client. DCR clients default ' +
|
||||
'to the authorization_code (consent-bearing) grant. See SECURITY.md.',
|
||||
'SECURITY WARNING: Dynamic Client Registration (--enable-dcr) is ON. Any network caller ' +
|
||||
'can self-register an OAuth client, limited to read/write (read-only for client_credentials ' +
|
||||
'under --enable-dcr-insecure); every authorization_code connection needs owner approval in the admin UI. See SECURITY.md.',
|
||||
);
|
||||
if (enableDcrInsecure) {
|
||||
console.error(
|
||||
'SECURITY WARNING: --enable-dcr-insecure is ON — self-registered DCR ' +
|
||||
'clients may request the client_credentials grant, which BYPASSES the ' +
|
||||
'/authorize consent screen. Only use this on a trusted network.',
|
||||
'SECURITY WARNING: --enable-dcr-insecure is ON — self-registered DCR clients may ' +
|
||||
'request the client_credentials grant, which BYPASSES owner approval (they are capped ' +
|
||||
'at read-only scope). Only use this on a trusted network.',
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1216,7 +1216,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
const authRouterOptions: any = {
|
||||
provider: oauthProvider,
|
||||
issuerUrl,
|
||||
scopesSupported: ALLOWED_SCOPES_LIST.filter(scope => scope !== 'agent'),
|
||||
scopesSupported: scopesSupportedForDiscovery({ enableDcr }),
|
||||
resourceName: 'GBrain MCP Server',
|
||||
// Advertise /mcp as the protected resource (see mcpResourceUrl above).
|
||||
resourceServerUrl: mcpResourceUrl,
|
||||
@@ -3319,7 +3319,7 @@ export async function runServeHttp(engine: BrainEngine, options: ServeHttpOption
|
||||
║ Engine: ${(config.engine || 'pglite').padEnd(40)}║
|
||||
║ Issuer: ${issuerUrl.origin.padEnd(40)}║
|
||||
║ Clients: ${String((clientCount[0] as any).count).padEnd(40)}║
|
||||
║ DCR: ${(enableDcr ? (enableDcrInsecure ? 'enabled (INSECURE: client_credentials)' : 'enabled') : 'disabled').padEnd(40)}║
|
||||
║ DCR: ${(enableDcr ? (enableDcrInsecure ? 'enabled (INSECURE: read-only M2M)' : 'enabled (consent; DCR max read write)') : 'disabled').padEnd(40)}║
|
||||
║ Skills: ${skillStatus.bannerValue.padEnd(40)}║
|
||||
║ Token TTL: ${(tokenTtl + 's').padEnd(40)}║
|
||||
╠══════════════════════════════════════════════════════╣
|
||||
|
||||
@@ -23,13 +23,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
|
||||
'backfill': ['--batch-size', '--brain', '--concurrency', '--dry-run', '--fresh', '--help', '--json', '--keep-index', '--list', '--max-errors', '--max-rows', '--resume', '--source'],
|
||||
'backup': ['--background', '--brain', '--dir', '--explain', '--follow', '--help', '--into', '--json', '--output', '--path', '--progress-interval', '--progress-json', '--quiet', '--restore-only', '--source', '--timeout', '--verify'],
|
||||
'bench': ['--baseline', '--brain', '--force', '--from', '--help', '--json', '--label', '--limit', '--source', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-top1', '--to', '--tool'],
|
||||
'book-mirror': ['--access', '--allow-empty', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--file', '--follow', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--mode', '--model', '--multimodal', '--no-confirm', '--no-follow', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--types', '--url', '--yes'],
|
||||
'book-mirror': ['--access', '--allow-empty', '--asof', '--author', '--background', '--bound-slug-prefixes', '--brain', '--chapters-dir', '--context-file', '--date', '--days', '--dry-run', '--entities', '--explain', '--file', '--follow', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-turns', '--mode', '--model', '--multimodal', '--no-confirm', '--no-follow', '--once', '--page', '--path', '--progress-interval', '--progress-json', '--purge', '--quiet', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--timeout', '--timeout-ms', '--title', '--trusted-extraction', '--types', '--url', '--yes'],
|
||||
'bootstrap': ['--abbrev-ref', '--abort', '--accept-visibility-change-consequences', '--active', '--all', '--allow-unverified-remote', '--auto', '--brain', '--branch', '--cached', '--confirm', '--count', '--delete-brain', '--diff-filter', '--dim', '--env', '--error-unmatch', '--exclude-standard', '--file', '--force', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--heads', '--help', '--home', '--hostname', '--http', '--id', '--init', '--install', '--is-inside-work-tree', '--jq', '--json', '--local', '--mcp-even-if-plugin', '--minimal', '--name', '--name-only', '--no-capture', '--no-cron', '--no-hooks', '--no-verify', '--only', '--others', '--pat-file', '--path', '--pglite', '--porcelain', '--port', '--private', '--project', '--pure', '--push-only', '--quiet', '--rebase', '--remove', '--repair', '--scope', '--scopes', '--set', '--short', '--show', '--show-toplevel', '--skip', '--source', '--status', '--surface', '--to', '--token', '--token-name', '--unset-all', '--url', '--verify', '--version', '--visibility', '--workspace', '--yes'],
|
||||
'brainstorm': ['--brain', '--force-rechunk', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--markdown', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--stale', '--strict-budget', '--yes'],
|
||||
'cache': ['--brain', '--help', '--json', '--source', '--yes'],
|
||||
'calibration': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--dry-run', '--entities', '--file', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--phase', '--regenerate', '--scrub-gstack', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--undo-wave', '--url', '--with-calibration', '--yes'],
|
||||
'calibration': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--dry-run', '--entities', '--file', '--full', '--help', '--holder', '--http', '--image', '--json', '--key-prefix', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--phase', '--purge', '--regenerate', '--scrub-gstack', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--undo-wave', '--url', '--with-calibration', '--yes'],
|
||||
'call': ['--brain', '--help', '--json', '--source'],
|
||||
'capture': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--depth', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--quiet', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--trusted-extraction', '--type', '--types', '--url', '--what', '--where', '--who', '--yes'],
|
||||
'capture': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--depth', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--purge', '--quiet', '--scopes', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--stdin', '--surface', '--trusted-extraction', '--type', '--types', '--url', '--what', '--where', '--who', '--yes'],
|
||||
'check-backlinks': ['--background', '--brain', '--dir', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
|
||||
'check-resolvable': ['--brain', '--dry-run', '--fix', '--help', '--json', '--skills-dir', '--source', '--strict', '--verbose'],
|
||||
'check-update': ['--brain', '--ff-only', '--help', '--json', '--markdown', '--migrate-only', '--non-interactive', '--refresh-cache', '--source', '--swap-only', '--version', '--yes'],
|
||||
@@ -45,19 +45,19 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
|
||||
'conversation-parser': ['--brain', '--help', '--json', '--source'],
|
||||
'creds': ['--allow-create-db', '--allow-docker', '--brain', '--chat-model', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--grant-types', '--help', '--http', '--ids', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--out', '--passphrase-env', '--path', '--pglite', '--prefer-postgres', '--provenance', '--provider', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--supabase', '--surface', '--to', '--url', '--version'],
|
||||
'db-repair': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--dry-run', '--filter', '--force', '--force-retry', '--format', '--help', '--json', '--locks', '--name', '--path', '--prefer-postgres', '--remediate', '--restart', '--skip-verify', '--source', '--supabase', '--undo-last-rewrite', '--url', '--version', '--yes'],
|
||||
'doctor': ['--abbrev-ref', '--abort', '--all', '--allow-old-serve', '--allow-unverified-remote', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embedding', '--no-hooks', '--no-migrate', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--restore-only', '--resume', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],
|
||||
'doctor': ['--abbrev-ref', '--abort', '--all', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--check', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--env', '--exclude-standard', '--explain', '--fast', '--federated-read', '--file', '--fix', '--follow', '--force', '--force-retry', '--force-schema', '--force-sunset-target', '--format', '--fresh', '--from-pages', '--full', '--gbrain-bin', '--get', '--git-dir', '--git-path', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-flagged', '--include-gitignored', '--include-pseudo', '--index-audit', '--init', '--install', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--mcp-only', '--migrate-only', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-capture', '--no-cron', '--no-embedding', '--no-hooks', '--no-migrate', '--no-verify', '--older-than', '--once', '--others', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--pure', '--push-only', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--refresh', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--reranker', '--reset', '--restore-only', '--resume', '--review-lower', '--scope', '--scopes', '--session', '--set', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills-dir', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slugs', '--source', '--source-id', '--stale', '--status', '--strict', '--supabase', '--surface', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--type', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--verbose', '--verify', '--version', '--window', '--workers', '--yes'],
|
||||
'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],
|
||||
'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],
|
||||
'embed': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--include-null-signature', '--json', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--pglite', '--priority', '--progress-interval', '--progress-json', '--quiet', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to'],
|
||||
'engine': ['--apply-rewrites', '--brain', '--break-lock', '--db-url', '--help', '--json', '--path', '--prefer-postgres', '--probe', '--source', '--supabase', '--url', '--yes'],
|
||||
'enrich': ['--access', '--allow-empty', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],
|
||||
'enrich': ['--access', '--allow-empty', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--concurrency', '--confirm-destructive', '--date', '--days', '--dry-run', '--embedding-dimensions', '--embedding-model', '--entities', '--explain', '--file', '--follow', '--force', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--max-usd', '--min-context', '--mode', '--model', '--multimodal', '--once', '--order', '--page', '--path', '--progress-interval', '--progress-json', '--purge', '--quiet', '--reenrich-after', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--source-id', '--stats', '--surface', '--thin', '--thin-threshold', '--timeout', '--to', '--trusted-extraction', '--types', '--url', '--workers', '--yes'],
|
||||
'eval': ['--ab-relational', '--against', '--allow-incomplete-judgments', '--allow-mixed-run-config', '--allow-regression', '--asof', '--autocut', '--background', '--baseline', '--batch', '--brain', '--budget-usd', '--budget-usd-answer', '--budget-usd-retrieval', '--by-type', '--by-type-floor', '--by-type-floor-metric', '--capture-pool', '--committed-baseline', '--compare', '--compare-limit', '--concurrent', '--config-a', '--config-b', '--corpus', '--cycles', '--days', '--dedup-cosine', '--dedup-max-per-page', '--dedup-type-ratio', '--dimensions', '--distance-min', '--embed-cache', '--embedder', '--embedding-dimensions', '--embedding-model', '--expand', '--expansion', '--expansion-replay', '--expansion-variant-budget', '--explain', '--fixtures', '--follow', '--force-rechunk', '--format', '--from-capture', '--from-db', '--gold', '--grounding-min', '--harness', '--help', '--include-abstention', '--include-holdout', '--input', '--json', '--judge', '--judge-concurrency', '--judge-model', '--justification', '--k', '--keyword-only', '--limit', '--llm', '--markdown', '--max-pair-chars', '--max-tokens', '--max-usd', '--mcp-only', '--md', '--metric', '--min-recall', '--mode', '--model', '--models', '--modes', '--name-only', '--no-cache', '--no-embed-cache', '--no-expand', '--no-llm', '--no-trajectory', '--older-than', '--out', '--output', '--output-dir', '--parallel', '--parity-baseline', '--pglite', '--progress-interval', '--progress-json', '--qrels', '--queries-file', '--query', '--question-ids', '--questions', '--quiet', '--receipt-dir', '--record', '--refresh-cache', '--reranker', '--resume-from', '--retrieval-only', '--rrf-k', '--rubric-version', '--runs', '--sample', '--sampling', '--save', '--search-pin', '--seed', '--severity', '--short', '--show-toplevel', '--since', '--skip-replay', '--slot-a-model', '--slot-b-model', '--slot-c-model', '--slug', '--slug-prefix', '--source', '--stale', '--strategy', '--suite', '--suites', '--supabase', '--task', '--threshold', '--threshold-expected-top1', '--threshold-first-relevant-hit', '--threshold-jaccard', '--threshold-latency-multiplier', '--threshold-recall-at-k', '--threshold-top1', '--timeout', '--to', '--tool', '--top-k', '--top-regressions', '--until', '--update-baseline', '--usefulness-min', '--verbose', '--verify', '--with-code-intel', '--yes'],
|
||||
'export': ['--background', '--brain', '--dir', '--explain', '--fix', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--repo', '--restore-only', '--slug-prefix', '--source', '--timeout', '--type'],
|
||||
'extract': ['--background', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--dry-run', '--explain', '--follow', '--from-meetings', '--help', '--include-frontmatter', '--infer-dates', '--json', '--kind', '--ner', '--pack', '--path', '--progress-interval', '--progress-json', '--quiet', '--rebuild', '--since', '--source', '--source-id', '--stale', '--timeout', '--type', '--verbose', '--workers', '--yes'],
|
||||
'extract-conversation-facts': ['--background', '--brain', '--concurrency', '--confirm-destructive', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--limit', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embedding', '--override-disabled', '--path', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--segment-limit', '--since', '--sleep', '--slug', '--source', '--source-id', '--stale', '--status', '--supabase', '--timeout', '--to', '--types', '--url', '--workers', '--yes'],
|
||||
'features': ['--all', '--auto', '--auto-fix', '--background', '--batch-size', '--brain', '--by-mention', '--catch-up', '--concurrency', '--dir', '--explain', '--from-meetings', '--help', '--include-frontmatter', '--include-null-signature', '--infer-dates', '--json', '--kind', '--ner', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--path', '--priority', '--rebuild', '--refresh', '--repo', '--since', '--slugs', '--source', '--source-id', '--stale', '--target', '--type', '--verbose', '--workers'],
|
||||
'files': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-pointer', '--page', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--source', '--timeout', '--type', '--yes'],
|
||||
'forget': ['--access', '--allow-empty', '--as-context', '--asof', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--file', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--query', '--reason', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],
|
||||
'forget': ['--access', '--allow-empty', '--as-context', '--asof', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--file', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--purge', '--query', '--reason', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],
|
||||
'founder': ['--brain', '--help', '--json', '--mcp-only', '--since', '--source', '--until'],
|
||||
'friction': ['--agent', '--base', '--brain', '--compare', '--help', '--hint', '--json', '--kind', '--message', '--no-redact', '--phase', '--run-id', '--severity', '--source', '--transcript-path', '--transcripts'],
|
||||
'frontmatter': ['--allow-catch-all', '--brain', '--cached', '--diff-filter', '--dry-run', '--exclude-standard', '--fix', '--force', '--get', '--git-common-dir', '--help', '--include-catch-all', '--json', '--name-only', '--no-verify', '--others', '--source', '--type', '--uninstall'],
|
||||
@@ -68,26 +68,26 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
|
||||
'init': ['--all', '--allow-create-db', '--allow-docker', '--brain', '--break-lock', '--chat-model', '--check', '--dim', '--embedding-dimensions', '--embedding-model', '--entity', '--expansion-model', '--force', '--grant-types', '--help', '--http', '--issuer-url', '--json', '--key', '--local-postgres', '--mcp-only', '--mcp-url', '--migrate-only', '--model', '--no-embedding', '--no-expand', '--non-interactive', '--oauth-client-id', '--oauth-client-secret', '--path', '--pglite', '--prefer-postgres', '--probe', '--provenance', '--schema-pack', '--scopes', '--skip-embed-check', '--source', '--stale', '--status', '--supabase', '--surface', '--to', '--touchpoint', '--url', '--version', '--yes'],
|
||||
'integrations': ['--auto', '--brain', '--dry-run', '--help', '--json', '--overwrite', '--refresh', '--source', '--target'],
|
||||
'integrity': ['--auto', '--backend', '--background', '--brain', '--confidence', '--cost', '--dry-run', '--explain', '--follow', '--fresh', '--help', '--json', '--limit', '--progress-interval', '--progress-json', '--quiet', '--review-lower', '--skip-bare-tweet', '--skip-urls', '--source', '--supabase', '--timeout', '--type', '--url'],
|
||||
'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--queue', '--quiet', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
|
||||
'jobs': ['--abbrev-ref', '--access', '--aliases', '--all', '--allow-empty', '--allow-shell-jobs', '--asof', '--auto', '--background', '--backoff-delay', '--backoff-jitter', '--backoff-type', '--batch-size', '--bound-slug-prefixes', '--brain', '--break-lock', '--by-mention', '--cached', '--catch-up', '--cli-path', '--cluster-errors', '--concurrency', '--confidence', '--confirm-destructive', '--cost-estimate', '--date', '--days', '--delay', '--detach', '--diff-filter', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--entities', '--exclude', '--exclude-standard', '--expect', '--explain', '--file', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-retry', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--hard-deadline', '--health-interval', '--help', '--http', '--idempotency-key', '--ids', '--image', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--infer-dates', '--inject-bootstrap', '--inline', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--job-id', '--job-isolation', '--json', '--kind', '--limit', '--lock-duration-ms', '--log-noop', '--markdown', '--max-age', '--max-attempts', '--max-cost-usd', '--max-crashes', '--max-rss', '--max-runtime-min', '--max-sources', '--max-stalled', '--max-usd', '--max-waiting', '--mcp-only', '--min-context', '--missing-path', '--mode', '--model', '--multimodal', '--name-only', '--ner', '--nice', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-inject', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--no-worker', '--now', '--older-than', '--once', '--order', '--others', '--override-disabled', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--phase', '--pid-file', '--priority', '--purge', '--queue', '--quiet', '--rebuild', '--redact-secrets', '--reenrich-after', '--refresh-ms', '--repo', '--resume', '--retry-failed', '--review-lower', '--segment-limit', '--serial', '--session', '--show-toplevel', '--sigkill-rescue', '--since', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--sleep', '--slug', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--stats', '--status', '--strategy', '--surface', '--swap-only', '--target', '--thin', '--thin-threshold', '--timeout', '--timeout-ms', '--to', '--trusted-extraction', '--type', '--types', '--uninstall', '--url', '--user', '--verbose', '--verify', '--watch', '--wedge-rescue', '--workers', '--working-tree', '--yes'],
|
||||
'lint': ['--abbrev-ref', '--abort', '--background', '--brain', '--branch', '--cached', '--dry-run', '--exclude', '--explain', '--file', '--fix', '--follow', '--get', '--git-dir', '--git-path', '--help', '--is-inside-work-tree', '--json', '--local', '--name-only', '--no-cron', '--no-verify', '--pat-file', '--path', '--progress-interval', '--progress-json', '--push-only', '--quiet', '--rebase', '--short', '--show-toplevel', '--source', '--timeout', '--unset-all'],
|
||||
'loops': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],
|
||||
'lsd': ['--brain', '--force-resume', '--help', '--json', '--judge-model', '--limit', '--list-runs', '--max-cost', '--max-far-set', '--max-ideas-per-judge-call', '--no-save', '--resume', '--save', '--source', '--strict-budget', '--yes'],
|
||||
'maintain': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--reset', '--resume', '--safe', '--scope', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
|
||||
'maintain': ['--all', '--background', '--brain', '--break-lock', '--by-mention', '--catch-up', '--concurrency', '--content-audit', '--count', '--detach', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--fast', '--fix', '--force', '--force-retry', '--force-schema', '--from-meetings', '--full', '--harness', '--help', '--http', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--index-audit', '--infer-dates', '--install', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--migrate-only', '--multimodal', '--ner', '--older-than', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--probe-pglite', '--query', '--queue', '--reauth', '--rebuild', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--reset', '--resume', '--safe', '--scope', '--scopes', '--show-current', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--stale', '--status', '--supabase', '--symbol-kind', '--target', '--target-score', '--to', '--top-k', '--type', '--url', '--verbose', '--version', '--window', '--workers', '--yes'],
|
||||
'mcp': ['--admin-token-file', '--agent', '--arg', '--bound-brain', '--bound-max-concurrent', '--bound-slug-prefixes', '--bound-source', '--bound-tools', '--brain', '--budget-usd-per-day', '--client', '--credentials-file', '--credentials-out', '--delegate', '--delegated-namespace', '--delegated-slug-prefixes', '--dry-run', '--federated-read', '--harness', '--help', '--if-version', '--install', '--json', '--limit', '--profile', '--queue', '--resume', '--root', '--source', '--timeout-ms', '--token-ttl', '--url'],
|
||||
'migrate': ['--all', '--background', '--batch-size', '--brain', '--catch-up', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-retry', '--force-sunset-target', '--help', '--ignore-env-override', '--include-null-signature', '--json', '--locks', '--no-embed', '--non-interactive', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--retarget', '--skip-verify', '--slugs', '--source', '--stale', '--status', '--timeout', '--to', '--url', '--yes'],
|
||||
'models': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--skip', '--source', '--to'],
|
||||
'mounts': ['--alias', '--brain', '--database-path', '--database-url', '--db-path', '--db-url', '--engine', '--help', '--id', '--json', '--mcp-url', '--path', '--skills-dir', '--source'],
|
||||
'notability-eval': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--in', '--json', '--out', '--repo', '--skip-llm', '--source', '--target-high', '--target-low', '--target-medium', '--to'],
|
||||
'onboard': ['--access', '--allow-empty', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--date', '--days', '--entities', '--explain', '--file', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--once', '--page', '--params', '--path', '--remediate', '--remediation-plan', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--yes'],
|
||||
'onboard': ['--access', '--allow-empty', '--asof', '--auto', '--bound-slug-prefixes', '--brain', '--check', '--date', '--days', '--entities', '--explain', '--file', '--from-pages', '--full', '--help', '--history', '--http', '--image', '--json', '--kind', '--limit', '--max-usd', '--mode', '--multimodal', '--once', '--page', '--params', '--path', '--purge', '--remediate', '--remediation-plan', '--resume', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--target-score', '--trusted-extraction', '--types', '--url', '--yes'],
|
||||
'orphans': ['--background', '--brain', '--count', '--explain', '--follow', '--help', '--include-pseudo', '--json', '--mode', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
|
||||
'pages': ['--brain', '--dry-run', '--help', '--json', '--older-than', '--source'],
|
||||
'pglite-repair': ['--brain', '--break-lock', '--dry-run', '--help', '--json', '--path', '--source', '--yes'],
|
||||
'post-upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--concurrency', '--cost-estimate', '--dim', '--embedding-dimensions', '--embedding-model', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--pglite', '--quiet', '--repo', '--require-db', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--swap-only', '--target', '--to', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],
|
||||
'protocol': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--token', '--trusted-extraction', '--types', '--url', '--yes'],
|
||||
'protocol': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mode', '--multimodal', '--once', '--page', '--path', '--purge', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--synthesize', '--target', '--token', '--trusted-extraction', '--types', '--url', '--yes'],
|
||||
'providers': ['--brain', '--dim', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--to', '--touchpoint'],
|
||||
'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],
|
||||
'quarantine': ['--apply', '--brain', '--force', '--force-rechunk', '--help', '--include-flagged', '--json', '--limit', '--markdown', '--no-embed', '--source', '--source-id', '--stale'],
|
||||
'recall': ['--access', '--allow-empty', '--as-context', '--asof', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--file', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--query', '--reason', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],
|
||||
'recall': ['--access', '--allow-empty', '--as-context', '--asof', '--bound-slug-prefixes', '--brain', '--budget-tokens', '--date', '--days', '--entities', '--file', '--full', '--grep', '--help', '--http', '--image', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--pending', '--purge', '--query', '--reason', '--rollup', '--session', '--session-id', '--since', '--since-last-run', '--slug', '--slugs', '--source', '--stats', '--supersessions', '--surface', '--today', '--trusted-extraction', '--types', '--url', '--watch', '--yes'],
|
||||
'reconcile-links': ['--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
|
||||
'reindex': ['--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-embed', '--no-embedding', '--pglite', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--workers', '--yes'],
|
||||
'reindex-code': ['--background', '--brain', '--concurrency', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--markdown', '--max-cost', '--max-cost-usd', '--max-runtime', '--no-embed', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--timeout', '--to', '--workers', '--yes'],
|
||||
@@ -114,13 +114,13 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {
|
||||
'status': ['--abbrev-ref', '--all', '--allow-empty', '--brain', '--break-lock', '--cached', '--concurrency', '--confirm-destructive', '--deadline-ms', '--diff-filter', '--empty', '--exclude', '--exclude-standard', '--fast', '--filters', '--fix', '--force-break-lock', '--format', '--full', '--full-history', '--hard-deadline', '--help', '--include-gitignored', '--include-hidden', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--max-age', '--max-sources', '--mcp-only', '--missing-path', '--name-only', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-renames', '--no-schema-pack', '--no-verify', '--others', '--parallel', '--path', '--priority', '--quiet', '--repo', '--retry-failed', '--section', '--serial', '--show-toplevel', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--strategy', '--timeout', '--url', '--verify', '--watch', '--workers', '--working-tree', '--yes'],
|
||||
'storage': ['--brain', '--fix', '--help', '--json', '--repo', '--restore-only', '--source', '--to'],
|
||||
'sweep': ['--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-delegate', '--once', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout'],
|
||||
'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reset', '--restore-only', '--resume', '--retry-failed', '--scope', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],
|
||||
'sync': ['--abbrev-ref', '--abort', '--account', '--all', '--allow-empty', '--apply-rewrites', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--catch-up', '--concurrency', '--confirm-destructive', '--content-audit', '--count', '--delete-brain', '--depth', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--exclude', '--exclude-standard', '--explain', '--fast', '--ff-only', '--filters', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--hard-deadline', '--harness', '--help', '--home', '--http', '--ids', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lang', '--link-source', '--link-type', '--locks', '--log-noop', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-only', '--missing-path', '--multimodal', '--name-only', '--name-status', '--ner', '--no-auto-embed', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-pull', '--no-recurse-submodules', '--no-renames', '--no-schema-pack', '--no-verify', '--older-than', '--others', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--parallel', '--params', '--path', '--pglite', '--phase', '--pid-file', '--porcelain', '--prefer-postgres', '--priority', '--probe-pglite', '--progress-interval', '--progress-json', '--query', '--queue', '--quiet', '--reauth', '--rebase', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--repo', '--reset', '--restore-only', '--resume', '--retry-failed', '--scope', '--scopes', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip-failed', '--slugs', '--source', '--source-id', '--src-subpath', '--stale', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--target', '--target-score', '--timeout', '--to', '--top-k', '--type', '--url', '--verbose', '--verify', '--version', '--watch', '--window', '--workers', '--working-tree', '--yes'],
|
||||
'takes': ['--accept', '--batch-size', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--pglite', '--quality', '--reject', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],
|
||||
'think': ['--anchor', '--bind', '--brain', '--calibration-holder', '--enable-dcr', '--enable-dcr-insecure', '--help', '--http', '--json', '--log-full-params', '--mcp-only', '--model', '--port', '--print-admin-token', '--public-url', '--rounds', '--save', '--since', '--source', '--source-guard', '--stdio-idle-timeout', '--suppress-bootstrap-token', '--surface', '--take', '--token-ttl', '--until', '--with-calibration', '--yes'],
|
||||
'transcripts': ['--all', '--all-discovery', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--progress-interval', '--progress-json', '--quiet', '--since', '--source', '--source-id', '--timeout'],
|
||||
'upgrade': ['--all', '--apply-clean-hunks', '--brain', '--check', '--concurrency', '--cost-estimate', '--dim', '--embedding-dimensions', '--embedding-model', '--ff-only', '--force', '--force-all', '--force-orchestrator', '--force-retry', '--force-schema', '--format', '--help', '--host-dir', '--inject-bootstrap', '--inline', '--install', '--interval', '--json', '--limit', '--list', '--markdown', '--max-rss', '--migrate-only', '--migration', '--mode', '--multimodal', '--name-only', '--no-autopilot-install', '--no-embed', '--no-embedding', '--no-inject', '--no-worker', '--non-interactive', '--now', '--once', '--pglite', '--quiet', '--repo', '--require-db', '--skills-dir', '--skip-verify', '--source', '--stale', '--status', '--supabase', '--swap-only', '--target', '--to', '--uninstall', '--user', '--verify', '--version', '--workers', '--yes'],
|
||||
'waiting': ['--all', '--brain', '--help', '--json', '--source', '--stale-ok', '--status', '--top', '--type'],
|
||||
'watch': ['--brain', '--help', '--json', '--max-pages', '--min-confidence', '--source', '--window-turns'],
|
||||
'whoknows': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--url', '--yes'],
|
||||
'whoknows': ['--access', '--allow-empty', '--asof', '--bound-slug-prefixes', '--brain', '--date', '--days', '--entities', '--explain', '--file', '--full', '--help', '--http', '--image', '--json', '--kind', '--limit', '--mcp-only', '--mode', '--multimodal', '--once', '--page', '--path', '--purge', '--session', '--since', '--slug', '--slugs', '--source', '--stats', '--surface', '--trusted-extraction', '--types', '--url', '--yes'],
|
||||
'ze-switch': ['--background', '--brain', '--confirm-reembed', '--dim', '--dry-run', '--explain', '--follow', '--force', '--help', '--ignore-env-override', '--ignore-missing-key', '--json', '--markdown', '--non-interactive', '--progress-interval', '--progress-json', '--quiet', '--reranker', '--resume', '--source', '--timeout', '--to', '--undo', '--yes'],
|
||||
};
|
||||
|
||||
595
src/core/cli-preflight.ts
Normal file
595
src/core/cli-preflight.ts
Normal file
@@ -0,0 +1,595 @@
|
||||
/**
|
||||
* CLI startup preflight — the FIRST statement of `cli.ts:main()`, before
|
||||
* global-flag parsing and any command dispatch. Ordered steps:
|
||||
*
|
||||
* 0. Sanitized re-run detection. When this process IS the re-run described
|
||||
* in step 1b (verified, never trusted on the marker's say-so — see
|
||||
* "Loop guard"), switch back to the caller's directory, arm the
|
||||
* die-with-wrapper watchdog (see "Die with the wrapper") and skip step 1:
|
||||
* the parent already quarantined and warned.
|
||||
* 1. `quarantineCwdDotenv()` — drop every protected key (env-trust.ts: the
|
||||
* security-relevant GBRAIN_* keys plus the loader / git / node / XDG /
|
||||
* TLS-trust / proxy / AI-endpoint hijack families) that a `.env` in the
|
||||
* cwd assigns. GBRAIN_HOME is on that list, so it is quarantined BEFORE
|
||||
* step 2 resolves the config dir. The 8 cwd .env files are parsed ONCE
|
||||
* here and the parse is shared with the cwd == config dir check.
|
||||
* 1b. Re-run gbrain with the sanitized environment whenever anything was
|
||||
* dropped (see "Why the re-run" below).
|
||||
* 2. `loadGbrainEnvFile(configDir)` — fill process.env from `~/.gbrain/.env`
|
||||
* (never overriding an exported variable). `loadConfig()` does this too,
|
||||
* but the guardrails loader in step 3 runs before any `loadConfig()`;
|
||||
* without this step `~/.gbrain/.env` could not be the operator's home
|
||||
* for GBRAIN_GUARDRAILS_MODULE.
|
||||
* 3. The #3688 guardrails loader (moved from cli.ts; now passes
|
||||
* `skipCwdCheck`). Fail-closed: set-but-broken aborts rather than
|
||||
* silently running without the operator's firewall; unset costs nothing.
|
||||
*
|
||||
* Fail-closed corollary of step 1 (see "GBRAIN_GUARDRAILS_MODULE" below): when
|
||||
* the quarantine dropped a NON-EMPTY `GBRAIN_GUARDRAILS_MODULE`, preflight
|
||||
* refuses to run at all instead of re-running without it.
|
||||
*
|
||||
* Every runtime entry — commands, `hook *`, `serve` (stdio and --http),
|
||||
* `mcp`, the supervisor-spawned `jobs work`, the per-job `jobs run-child` —
|
||||
* dispatches through `main()`, so this one call covers every gbrain process.
|
||||
* (`src/commands/auth.ts`'s `import.meta.main` seam is a dev-only
|
||||
* direct-script entry.)
|
||||
*
|
||||
* ## Why the re-run (step 1b)
|
||||
*
|
||||
* Deleting a key from process.env changes only THIS process's view. Bun hands
|
||||
* every child spawned without an explicit `env` option the environ snapshot
|
||||
* it took at startup — cwd-.env values included — so git, the claude CLI and
|
||||
* workers would still see the planted keys (verified on Bun 1.3.13: a `.env`
|
||||
* carrying `GIT_CONFIG_COUNT=1 / GIT_CONFIG_KEY_0=core.fsmonitor /
|
||||
* GIT_CONFIG_VALUE_0=./x.sh` runs x.sh from a plain `git status`). When the
|
||||
* quarantine dropped anything, preflight therefore spawns gbrain again with
|
||||
* an explicit, sanitized environment and exits with the re-run's status;
|
||||
* every descendant of the re-run inherits the clean view.
|
||||
*
|
||||
* The re-run starts in a NEUTRAL cwd: a fresh, empty `mkdtemp` directory that
|
||||
* is ours and by construction holds none of the `.env` family. Bun loads
|
||||
* `.env` from the process cwd only (no parent walk — verified on 1.3.13), so
|
||||
* the re-run's Bun never sees the hostile file and its environ simply LACKS
|
||||
* the dropped keys. They are deleted, never carried as empty strings: git and
|
||||
* the dynamic loader PRESENCE-check some of them (`GIT_SSL_NO_VERIFY=`
|
||||
* disables TLS verification, `LD_TRACE_LOADED_OBJECTS=` turns every
|
||||
* dynamically linked child into ldd, `GIT_DIR=` / `GIT_AUTHOR_NAME=` are hard
|
||||
* errors), so `''` would not have been neutral. Preflight in the re-run then
|
||||
* `chdir`s back to the caller's directory before anything else runs, so
|
||||
* relative arguments resolve exactly as typed. Nothing in cli.ts's import
|
||||
* graph captures `process.cwd()` at module-evaluation time (audited); every
|
||||
* read happens after this chdir.
|
||||
*
|
||||
* ## Loop guard
|
||||
*
|
||||
* The re-run carries `GBRAIN_CWD_ENV_QUARANTINED=<JSON {cwd, neutral,
|
||||
* wrapperPid}>`. The marker is NOT trusted by itself — a hostile .env could
|
||||
* plant one (the key is also on the protected list, so a planted copy is
|
||||
* dropped and named in the warning). It is honoured only when ALL of: it
|
||||
* parses to two strings (`wrapperPid` is informational — a positive integer
|
||||
* or ignored), this process's startup cwd IS `neutral` (realpath-compared),
|
||||
* and `neutral` contains none of the `.env` family. A process started from a hostile
|
||||
* directory fails the second check (its startup cwd has a `.env`) and the
|
||||
* third if it names its own directory — so it ignores the marker entirely
|
||||
* and never chdirs on one. Termination is structural: the re-run's startup
|
||||
* cwd has no `.env`, so it never drops anything and never re-runs. gbrain
|
||||
* self-spawns (supervisor → worker, hook → detached push, worker →
|
||||
* run-child) that start in the hostile cwd reload the file and perform the
|
||||
* hop once for their own subtree — accepted; one warning per subtree.
|
||||
*
|
||||
* ## Signals
|
||||
*
|
||||
* Handlers are installed BEFORE the spawn (a signal in the gap would take the
|
||||
* default action, kill the wrapper and orphan the re-run). The wrapper has no
|
||||
* duties of its own, so every listener some earlier module attached for the
|
||||
* forwarded signals is removed first: cli.ts installs its cleanup handlers
|
||||
* (process-cleanup.ts, SIGTERM → exit 143 / SIGHUP → exit 129) in its
|
||||
* `import.meta.main` block before `main()` reaches this preflight, and with
|
||||
* both attached a SIGTERM made the wrapper exit 143 before the re-run had
|
||||
* finished and before the neutral dir was removed. The wrapper's exit is
|
||||
* ALWAYS the child's. SIGTERM and SIGHUP — which a supervisor sends to the
|
||||
* wrapper pid alone — are always forwarded. SIGINT depends on whether the
|
||||
* process has a CONTROLLING TERMINAL (probed by opening `/dev/tty`; the
|
||||
* stdio `isTTY` flags on Windows), not on whether stdin is a tty:
|
||||
* - a controlling terminal exists: the re-run shares the wrapper's
|
||||
* foreground process group, so the terminal delivers Ctrl-C to it
|
||||
* directly — ALSO when stdin/stdout/stderr are redirected
|
||||
* (`serve --http </dev/null >log 2>&1` in a foreground shell). The wrapper
|
||||
* does NOT forward (a second delivery would consume a `once('SIGINT')`
|
||||
* graceful-shutdown handler such as serve-http's and turn Ctrl-C into an
|
||||
* abrupt kill) and ignores the signal itself so it survives to relay the
|
||||
* re-run's exit status.
|
||||
* - no controlling terminal (a supervisor, cron, a detached agent harness):
|
||||
* nothing does process-group delivery, so a SIGINT that reaches the
|
||||
* wrapper pid alone would otherwise orphan the re-run. Each received
|
||||
* SIGINT is forwarded once. (A harness that signals the whole group
|
||||
* instead delivers twice here — accepted: no terminal, no graceful Ctrl-C
|
||||
* expectation. A harness WITH a controlling terminal that signals the
|
||||
* wrapper pid alone with SIGINT is not forwarded — the terminal is the
|
||||
* delivery channel there; SIGTERM is what such harnesses send to stop a
|
||||
* child, and it is always forwarded.)
|
||||
* Exit status: the re-run's code, or 128+signal when a signal killed it
|
||||
* (shell convention).
|
||||
*
|
||||
* ## Die with the wrapper
|
||||
*
|
||||
* SIGKILL cannot be forwarded. A supervisor that tracks the pid it spawned —
|
||||
* the WRAPPER's — and escalates to SIGKILL (minions/supervisor.ts
|
||||
* `restartCurrentChild`, job-isolation children, hook pushes) would leave the
|
||||
* real re-run running as an orphan while a replacement starts. So the marker
|
||||
* carries the wrapper's pid and a VERIFIED re-run arms a watchdog: every
|
||||
* second it compares `process.ppid` with that pid (Bun's `process.ppid` is
|
||||
* live — it flips to the reaper's pid once the parent is gone, whether it
|
||||
* exited or was killed; verified on 1.3.13) and, when they differ, prints one
|
||||
* line, removes the now-orphaned neutral dir (`rmdirSync` — it is empty by
|
||||
* construction, and a non-recursive remove can never take anything else
|
||||
* with it) and exits 137, mirroring the SIGKILL the wrapper took. The timer
|
||||
* is `unref()`ed so it never keeps a finished command alive. A marker without
|
||||
* a usable `wrapperPid` (planted, foreign, older) arms nothing.
|
||||
*
|
||||
* ## Runtime flags across the hop
|
||||
*
|
||||
* `bun <flags> src/cli.ts` re-inserts `process.execArgv` into the re-run (a
|
||||
* compiled binary has none). Bun reports path-bearing flags verbatim in both
|
||||
* spellings (`["--preload", "./x"]` and `["--preload=./x"]`) and resolves a
|
||||
* relative value against the process cwd — which for the re-run is the EMPTY
|
||||
* neutral dir, so `--preload ./probe.ts` died with `preload not found`. For
|
||||
* `--preload`/`-r`/`--require`/`--import`, `--config`/`-c`, `--env-file` and
|
||||
* `--tsconfig-override`, a value that is `./`- or `../`-relative, or a bare
|
||||
* relative name that exists in the original cwd, is resolved against the
|
||||
* ORIGINAL cwd; absolute values, bare package specifiers and every other
|
||||
* flag pass through untouched, in order.
|
||||
*
|
||||
* ## HOME after the drop
|
||||
*
|
||||
* HOME / USERPROFILE are on the protected list (a cron/systemd unit often has
|
||||
* HOME unset, and a planted value then reaches process.env and every child).
|
||||
* Dropping them must not leave the re-run with NO home at all: git fails
|
||||
* (`Author identity unknown`, `$HOME not set`) and every raw
|
||||
* `process.env.HOME || ''` read resolves cwd-relative INTO the checkout. So
|
||||
* when the quarantine dropped HOME (USERPROFILE on Windows), the sanitized env
|
||||
* gets it back from `os.userInfo().homedir` — Bun derives that from the REAL
|
||||
* startup environ (passwd when the variable was unset) BEFORE the .env merge,
|
||||
* so the planted value never reaches it (verified on Bun 1.3.13). Only a
|
||||
* DROPPED key is restored: a home that was simply never set stays unset, so a
|
||||
* hopped run and a plain run see the same environment.
|
||||
*
|
||||
* ## Script mode + cwd bunfig.toml
|
||||
*
|
||||
* The compiled binary is built with `--no-compile-autoload-bunfig`, so a cwd
|
||||
* `bunfig.toml` is inert for it. The documented install (`bun install -g
|
||||
* github:…`, `git clone` + `bun link`) maps the `gbrain` bin to src/cli.ts,
|
||||
* which runs as an ordinary Bun SCRIPT — and for a script Bun applies the cwd
|
||||
* bunfig.toml before any of the script's code: a top-level `preload` has
|
||||
* already run by the time preflight starts. Nothing here can undo that; only
|
||||
* `bun --config=/dev/null <entry>` suppresses it (verified on Bun 1.3.13: no
|
||||
* `-c`/`--no-bunfig` spelling and no `BUN_CONFIG_*` variable does). What
|
||||
* preflight CAN do is say so: when it detects the shape (script runtime + a
|
||||
* top-level `preload` in the startup cwd's bunfig.toml) it prints one stderr
|
||||
* line. The checkout that contains the running entry itself (a contributor's
|
||||
* own repo, whose bunfig is theirs) is exempt; the sanitized re-run started in
|
||||
* the neutral dir never saw a bunfig and does not repeat the warning.
|
||||
*
|
||||
* ## GBRAIN_GUARDRAILS_MODULE: fail closed, not open
|
||||
*
|
||||
* The quarantine is key-presence: when a cwd .env assigns the key, the value
|
||||
* in process.env is dropped whether it came from the file or from the
|
||||
* operator's shell (Bun merges the file before any code runs and never
|
||||
* overrides a live variable, so the two are indistinguishable). For every
|
||||
* other protected key a false drop is a loud downgrade with the fix in the
|
||||
* warning. For THIS key it would be the opposite of the #3688 contract: the
|
||||
* re-run would simply have no module and run without the operator's firewall,
|
||||
* with nothing but a stderr line. So when a non-empty value was dropped,
|
||||
* preflight refuses to run (exit 1). A benign repository never assigns this
|
||||
* gbrain-specific key, and the `~/.gbrain/.env` home is unaffected: it is
|
||||
* read AFTER the quarantine (step 2), never dropped by it.
|
||||
*
|
||||
* Zero cost on the normal path: no .env in the cwd, or nothing protected
|
||||
* assigned there, means no spawn.
|
||||
*
|
||||
* ## cwd == config dir
|
||||
*
|
||||
* Running gbrain from INSIDE `~/.gbrain` (or `$GBRAIN_HOME/.gbrain`) makes Bun
|
||||
* load the operator's own `.env` as a "cwd .env". That file is operator-owned,
|
||||
* so the quarantine and the guardrails loader's cwd check are skipped when
|
||||
* `realpath(cwd) === realpath(configDir())` — but ONLY when no cwd .env file
|
||||
* assigns any key the config dir is DERIVED from: GBRAIN_HOME, HOME or
|
||||
* USERPROFILE (a hostile checkout laid out as `<checkout>/.gbrain` could
|
||||
* otherwise try to point the home at itself to manufacture the collision; a
|
||||
* planted home is never the operator's config dir). Measured on Bun 1.3.13,
|
||||
* `os.homedir()` is captured from the real startup environ before the .env
|
||||
* merge, so a planted HOME does not actually reach `configDir()` — the check
|
||||
* is belt-and-braces against that implementation detail changing.
|
||||
*/
|
||||
import { closeSync, constants as fsConstants, existsSync, mkdtempSync, openSync, readFileSync, realpathSync, rmdirSync, rmSync } from 'fs';
|
||||
import { constants as osConstants, homedir, tmpdir, userInfo } from 'os';
|
||||
import { dirname, isAbsolute, join, resolve } from 'path';
|
||||
import {
|
||||
CWD_DOTENV_FILES,
|
||||
cwdDotenvAssignsKey,
|
||||
parseCwdDotenv,
|
||||
quarantineCwdDotenv,
|
||||
type DotenvAssignment,
|
||||
} from './env-trust.ts';
|
||||
import { loadGbrainEnvFile } from './gbrain-env-file.ts';
|
||||
import { configDir } from './config.ts';
|
||||
|
||||
/**
|
||||
* Set on the sanitized re-run to `JSON {cwd, neutral}` (see "Loop guard").
|
||||
* Internal — not a setting; verified against the startup cwd, never trusted.
|
||||
*/
|
||||
export const CWD_ENV_QUARANTINED_MARKER = 'GBRAIN_CWD_ENV_QUARANTINED';
|
||||
|
||||
interface HopMarker {
|
||||
/** The caller's directory the re-run must switch back to. */
|
||||
cwd: string;
|
||||
/** The fresh empty directory the re-run was started in. */
|
||||
neutral: string;
|
||||
/** The wrapper's pid, for the die-with-wrapper watchdog; absent → no watchdog. Informational, not part of verification. */
|
||||
wrapperPid?: number;
|
||||
}
|
||||
|
||||
function parseHopMarker(raw: string | undefined): HopMarker | null {
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const v: unknown = JSON.parse(raw);
|
||||
if (
|
||||
v !== null && typeof v === 'object' &&
|
||||
typeof (v as HopMarker).cwd === 'string' && (v as HopMarker).cwd !== '' &&
|
||||
typeof (v as HopMarker).neutral === 'string' && (v as HopMarker).neutral !== ''
|
||||
) {
|
||||
const marker: HopMarker = { cwd: (v as HopMarker).cwd, neutral: (v as HopMarker).neutral };
|
||||
const pid = (v as HopMarker).wrapperPid;
|
||||
if (typeof pid === 'number' && Number.isSafeInteger(pid) && pid > 0) marker.wrapperPid = pid;
|
||||
return marker;
|
||||
}
|
||||
} catch {
|
||||
// not JSON — a planted or foreign value; ignored
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
const WRAPPER_WATCHDOG_INTERVAL_MS = 1000;
|
||||
|
||||
/** See "Die with the wrapper". Only ever called for a VERIFIED hop. */
|
||||
function installWrapperWatchdog(hop: HopMarker): void {
|
||||
const wrapperPid = hop.wrapperPid;
|
||||
if (wrapperPid === undefined) return;
|
||||
const t = setInterval(() => {
|
||||
if (process.ppid === wrapperPid) return;
|
||||
console.error('[env] sanitized re-run lost its wrapper (killed); exiting');
|
||||
try { rmdirSync(hop.neutral); } catch { /* already gone, or not empty — never ours to force */ }
|
||||
process.exit(137);
|
||||
}, WRAPPER_WATCHDOG_INTERVAL_MS);
|
||||
t.unref(); // must never keep a finished command alive
|
||||
}
|
||||
|
||||
/**
|
||||
* The marker, but ONLY when this process provably is the re-run: it started
|
||||
* inside the neutral dir the marker names, and that dir holds no .env family
|
||||
* member. Anything else (absent, malformed, planted from a hostile cwd) → null.
|
||||
*/
|
||||
function verifiedHop(startupCwd: string): HopMarker | null {
|
||||
const marker = parseHopMarker(process.env[CWD_ENV_QUARANTINED_MARKER]);
|
||||
if (!marker) return null;
|
||||
try {
|
||||
if (realpathSync(startupCwd) !== realpathSync(marker.neutral)) return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
for (const name of CWD_DOTENV_FILES) {
|
||||
if (existsSync(join(marker.neutral, name))) return null;
|
||||
}
|
||||
return marker;
|
||||
}
|
||||
|
||||
/** The keys `configDir()` is derived from; a cwd .env assigning any of them forfeits the cwd == config dir exemption. */
|
||||
const CONFIG_DIR_SOURCE_KEYS: readonly string[] = ['GBRAIN_HOME', 'HOME', 'USERPROFILE'];
|
||||
|
||||
/**
|
||||
* True when `cwd` IS the operator's config dir (see "cwd == config dir") and
|
||||
* no cwd .env file assigns a key the config dir is derived from. Exported for
|
||||
* tests.
|
||||
*/
|
||||
export function cwdIsOperatorConfigDir(cwd: string, assignments: readonly DotenvAssignment[]): boolean {
|
||||
for (const key of CONFIG_DIR_SOURCE_KEYS) {
|
||||
if (cwdDotenvAssignsKey(key, assignments)) return false;
|
||||
}
|
||||
try {
|
||||
return realpathSync(cwd) === realpathSync(configDir());
|
||||
} catch {
|
||||
return false; // invalid GBRAIN_HOME or a config dir that does not exist yet — no collision
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* argv (after execPath) that runs THIS gbrain again. A compiled Bun binary
|
||||
* reports its virtual entrypoint as argv[1] (`/$bunfs/root/...`; `~BUN` on
|
||||
* Windows) and execPath IS gbrain, so the user args are the whole argv;
|
||||
* `bun src/cli.ts` needs the runtime flags (`--inspect`, `--preload`, … from
|
||||
* process.execArgv, relative paths resolved against `originalCwd` — see
|
||||
* "Runtime flags across the hop") and the entry file re-inserted — Bun
|
||||
* reports the entry as an absolute path, so it survives the neutral-cwd start
|
||||
* (cli.ts computes rawArgs as `process.argv.slice(2)` in both modes). null
|
||||
* when there is no re-runnable entry (`bun -e`).
|
||||
*/
|
||||
function selfArgv(originalCwd: string): string[] | null {
|
||||
const entry = process.argv[1];
|
||||
const userArgs = process.argv.slice(2);
|
||||
if (!isScriptRuntime()) return userArgs;
|
||||
if (!entry || entry.startsWith('-')) return null;
|
||||
return [...resolveRuntimePaths(process.execArgv, originalCwd), entry, ...userArgs];
|
||||
}
|
||||
|
||||
/** Bun runtime flags whose value is a filesystem path (or, for the preload family, a path OR a package specifier). */
|
||||
const PATH_RUNTIME_FLAGS: ReadonlySet<string> = new Set([
|
||||
'--preload', '-r', '--require', '--import',
|
||||
'--config', '-c',
|
||||
'--env-file',
|
||||
'--tsconfig-override',
|
||||
]);
|
||||
|
||||
/** A path-flag value the re-run must see from `cwd`: relative → absolute; everything else verbatim. */
|
||||
function resolveRuntimePath(value: string, cwd: string): string {
|
||||
if (value === '' || isAbsolute(value)) return value;
|
||||
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- value is a --preload/--env-file/... path the operator passed on THIS process's own bun command line (process.execArgv) and cwd is the process's own startup cwd; absolutizing it so the sanitized re-run (which starts in a neutral dir) sees the same file IS the point, and no fs operation happens here
|
||||
if (/^\.\.?(?:[\\/]|$)/.test(value)) return resolve(cwd, value); // ./x ../x . ..
|
||||
try {
|
||||
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- same operator-supplied runtime-flag value against the process's own cwd; existsSync only decides whether a bare name is a file here or a package specifier
|
||||
if (existsSync(resolve(cwd, value))) return resolve(cwd, value); // a bare relative name that IS a file here (`--env-file .env.ci`)
|
||||
} catch {
|
||||
// unreadable — treat as a specifier
|
||||
}
|
||||
return value; // a package specifier (`--preload some-pkg`) or a non-path
|
||||
}
|
||||
|
||||
/** `execArgv` with every path-bearing flag's relative value resolved against `cwd`; order and every other flag preserved. */
|
||||
function resolveRuntimePaths(execArgv: readonly string[], cwd: string): string[] {
|
||||
const out: string[] = [];
|
||||
for (let i = 0; i < execArgv.length; i++) {
|
||||
const arg = execArgv[i]!;
|
||||
const eq = arg.indexOf('=');
|
||||
const flag = eq === -1 ? arg : arg.slice(0, eq);
|
||||
if (!PATH_RUNTIME_FLAGS.has(flag)) {
|
||||
out.push(arg);
|
||||
continue;
|
||||
}
|
||||
if (eq !== -1) {
|
||||
out.push(`${flag}=${resolveRuntimePath(arg.slice(eq + 1), cwd)}`); // --flag=value
|
||||
continue;
|
||||
}
|
||||
out.push(arg); // --flag value
|
||||
if (i + 1 < execArgv.length) out.push(resolveRuntimePath(execArgv[++i]!, cwd));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when this process is `bun <entry>` (the dev runtime or a `bun install
|
||||
* -g` / `bun link` install running src/cli.ts through its shebang), false for
|
||||
* a compiled binary (execPath IS gbrain; the entry is a `/$bunfs/` virtual
|
||||
* path, `~BUN` on Windows).
|
||||
*/
|
||||
function isScriptRuntime(): boolean {
|
||||
const entry = process.argv[1];
|
||||
const bunfsEntry = entry !== undefined && (/^\/\$bunfs\//.test(entry) || /[\\/]~BUN[\\/]/.test(entry));
|
||||
const devRuntime = /[/\\](bun|node)(\.exe)?$/.test(process.execPath);
|
||||
return !bunfsEntry && devRuntime;
|
||||
}
|
||||
|
||||
/**
|
||||
* The one line preflight prints for the shape described in "Script mode + cwd
|
||||
* bunfig.toml". Exported for tests.
|
||||
*/
|
||||
export const SCRIPT_MODE_BUNFIG_WARNING =
|
||||
'[env] gbrain is running as a bun script (not the compiled binary) and the bunfig.toml in the current ' +
|
||||
'directory declares a top-level preload — Bun ran it before gbrain started. A cwd bunfig.toml is untrusted: ' +
|
||||
'run gbrain from a directory you control, or start it as `bun --config=/dev/null <path-to-gbrain/src/cli.ts> …`.';
|
||||
|
||||
/**
|
||||
* Does `bunfig.toml` in `dir` declare a TOP-LEVEL `preload` (the one Bun
|
||||
* applies to `bun <entry>`; a `[test]`-section preload applies to `bun test`
|
||||
* only)? Lines before the first `[section]` header are the top level.
|
||||
* Fail-quiet: unreadable → false (Bun would have failed on it first).
|
||||
*/
|
||||
function bunfigDeclaresTopLevelPreload(dir: string): boolean {
|
||||
let text: string;
|
||||
try {
|
||||
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- dir is the process's own startup cwd (process.cwd() in runCliPreflight) and the tail is the fixed literal 'bunfig.toml'; read-only probe for a top-level preload declaration
|
||||
text = readFileSync(join(dir, 'bunfig.toml'), 'utf-8');
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
if (/^\s*\[/.test(line)) return false; // first section header: top level ends
|
||||
if (/^\s*preload\s*=/.test(line)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** The startup cwd is the checkout that contains the running entry (`<root>/src/cli.ts`). */
|
||||
function cwdIsOwnCheckout(startupCwd: string): boolean {
|
||||
const entry = process.argv[1];
|
||||
if (!entry) return false;
|
||||
try {
|
||||
return realpathSync(startupCwd) === realpathSync(dirname(dirname(entry)));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function warnScriptModeBunfig(startupCwd: string): void {
|
||||
if (!isScriptRuntime()) return;
|
||||
if (!bunfigDeclaresTopLevelPreload(startupCwd)) return;
|
||||
if (cwdIsOwnCheckout(startupCwd)) return;
|
||||
console.error(SCRIPT_MODE_BUNFIG_WARNING);
|
||||
}
|
||||
|
||||
/**
|
||||
* Does this process have a controlling terminal — i.e. will a terminal deliver
|
||||
* Ctrl-C to the whole foreground process group (wrapper AND re-run) itself?
|
||||
* POSIX: `open("/dev/tty")` succeeds exactly then (ENXIO otherwise), whatever
|
||||
* stdin/stdout/stderr are redirected to. Windows has no /dev/tty; the stdio
|
||||
* `isTTY` flags are the closest proxy there.
|
||||
*/
|
||||
function hasControllingTerminal(): boolean {
|
||||
if (process.platform === 'win32') {
|
||||
return Boolean(process.stdin.isTTY || process.stdout.isTTY || process.stderr.isTTY);
|
||||
}
|
||||
try {
|
||||
closeSync(openSync('/dev/tty', fsConstants.O_RDONLY | fsConstants.O_NOCTTY));
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The operator's real home for "HOME after the drop": `os.userInfo().homedir`
|
||||
* (Bun: the startup environ's value, passwd when unset — never the merged
|
||||
* .env value), then `os.homedir()`. undefined when neither is available
|
||||
* (uid-less containers throw from userInfo).
|
||||
*/
|
||||
function realHomeDir(): string | undefined {
|
||||
try {
|
||||
const h = userInfo().homedir;
|
||||
if (h) return h;
|
||||
} catch {
|
||||
// no passwd entry for this uid — fall through
|
||||
}
|
||||
try {
|
||||
return homedir() || undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A fresh, empty directory that is ours, as an ABSOLUTE canonical path.
|
||||
* `tmpdir()` first — it reads TMPDIR/TMP/TEMP at call time, and those are on
|
||||
* the protected list, so a value planted by the cwd .env (a relative `t`, a
|
||||
* path inside the checkout) is already gone when this runs; the home dir when
|
||||
* the temp root is unusable. A mkdtemp dir is new by definition, so neither
|
||||
* can hold a .env. `realpathSync` so the marker's `neutral` and the re-run's
|
||||
* startup cwd compare canonically even if a caller-exported TMPDIR is
|
||||
* relative or a symlink.
|
||||
*/
|
||||
function makeNeutralDir(): string {
|
||||
let dir: string;
|
||||
try {
|
||||
dir = mkdtempSync(join(tmpdir(), 'gbrain-hop-'));
|
||||
} catch {
|
||||
dir = mkdtempSync(join(homedir(), '.gbrain-hop-'));
|
||||
}
|
||||
return realpathSync(dir);
|
||||
}
|
||||
|
||||
/** The home variables restored after a drop (see "HOME after the drop"): HOME everywhere, USERPROFILE on Windows. */
|
||||
const HOME_KEYS: readonly string[] = process.platform === 'win32' ? ['HOME', 'USERPROFILE'] : ['HOME'];
|
||||
|
||||
async function reexecSanitized(originalCwd: string, dropped: readonly string[]): Promise<void> {
|
||||
const argv = selfArgv(originalCwd);
|
||||
if (!argv) return; // in-process view is clean; nothing re-runnable for the descendants' sake
|
||||
const neutral = makeNeutralDir();
|
||||
// The quarantine already deleted the dropped keys from process.env; they are
|
||||
// NOT added back (not even empty — see "Why the re-run") …
|
||||
const env: Record<string, string> = {};
|
||||
for (const [k, v] of Object.entries(process.env)) {
|
||||
if (v !== undefined) env[k] = v;
|
||||
}
|
||||
// … except a dropped HOME, which comes back as the operator's REAL home
|
||||
// (see "HOME after the drop") — the planted value is still discarded.
|
||||
for (const key of HOME_KEYS) {
|
||||
if (!dropped.includes(key) || env[key] !== undefined) continue;
|
||||
const real = realHomeDir();
|
||||
if (real) env[key] = real;
|
||||
}
|
||||
env[CWD_ENV_QUARANTINED_MARKER] = JSON.stringify({ cwd: originalCwd, neutral, wrapperPid: process.pid } satisfies HopMarker);
|
||||
let code: number;
|
||||
let signalCode: string | null;
|
||||
// See "Signals". Installed BEFORE the spawn; the spawn is synchronous in the
|
||||
// same tick, so a handler can only ever run with `child` set.
|
||||
let child: ReturnType<typeof Bun.spawn> | null = null;
|
||||
const forward = (sig: NodeJS.Signals) => () => {
|
||||
try { child?.kill(sig); } catch { /* already exited */ }
|
||||
};
|
||||
// The wrapper's only job is to relay the child. Any listener an earlier
|
||||
// module attached for these signals (cli.ts's cleanup handlers: SIGTERM →
|
||||
// exit 143 / SIGHUP → exit 129, installed before main()) would exit the
|
||||
// wrapper on its own schedule — before the child has finished and before the
|
||||
// neutral dir is removed. Remove them; the forwarders below are the only ones.
|
||||
for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP'] as const) process.removeAllListeners(sig);
|
||||
process.on('SIGTERM', forward('SIGTERM'));
|
||||
process.on('SIGHUP', forward('SIGHUP'));
|
||||
// controlling terminal: it already delivered Ctrl-C to the child; only outlive it.
|
||||
// none: nothing else will deliver it — forward.
|
||||
process.on('SIGINT', hasControllingTerminal() ? () => {} : forward('SIGINT'));
|
||||
try {
|
||||
child = Bun.spawn([process.execPath, ...argv], {
|
||||
cwd: neutral,
|
||||
env,
|
||||
stdio: ['inherit', 'inherit', 'inherit'],
|
||||
});
|
||||
code = await child.exited;
|
||||
signalCode = child.signalCode;
|
||||
} finally {
|
||||
rmSync(neutral, { recursive: true, force: true });
|
||||
}
|
||||
if (signalCode) {
|
||||
const signals = osConstants.signals as Record<string, number | undefined>;
|
||||
process.exit(128 + (signals[signalCode] ?? 1)); // shell convention for a signal death
|
||||
}
|
||||
process.exit(code);
|
||||
}
|
||||
|
||||
/**
|
||||
* The refusal printed when a non-empty GBRAIN_GUARDRAILS_MODULE was dropped
|
||||
* (see "GBRAIN_GUARDRAILS_MODULE: fail closed, not open"). Exported for tests.
|
||||
*/
|
||||
export const GUARDRAILS_ASSIGNED_BY_CWD_DOTENV =
|
||||
'guardrails: GBRAIN_GUARDRAILS_MODULE is assigned by a .env file in the current directory; ' +
|
||||
"refusing to run without the operator's firewall. Bun merges that file before gbrain starts, " +
|
||||
"so a value you exported cannot be told apart from the file's — remove the assignment from the " +
|
||||
"project's .env, or run gbrain from a directory that does not assign it. Your own setting " +
|
||||
'belongs in your shell environment or in ~/.gbrain/.env (never in a project .env).';
|
||||
|
||||
export async function runCliPreflight(): Promise<void> {
|
||||
const startupCwd = process.cwd();
|
||||
const hop = verifiedHop(startupCwd);
|
||||
if (hop) {
|
||||
delete process.env[CWD_ENV_QUARANTINED_MARKER]; // never inherited further: a later self-spawn decides for itself
|
||||
try {
|
||||
process.chdir(hop.cwd);
|
||||
} catch (err) {
|
||||
console.error(`[env] cannot return to ${hop.cwd} after the sanitized re-run: ${(err as Error)?.message ?? String(err)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
installWrapperWatchdog(hop); // after the chdir: the neutral dir may be removed only from outside it
|
||||
} else {
|
||||
// Bun applied the STARTUP cwd's bunfig.toml to this process (script mode
|
||||
// only); the re-run started in the neutral dir, so it has nothing to say.
|
||||
warnScriptModeBunfig(startupCwd);
|
||||
}
|
||||
const cwd = process.cwd();
|
||||
const assignments = parseCwdDotenv(cwd);
|
||||
const collision = cwdIsOperatorConfigDir(cwd, assignments);
|
||||
if (!hop && !collision) {
|
||||
const hadGuardrailsModule = (process.env.GBRAIN_GUARDRAILS_MODULE ?? '').trim() !== '';
|
||||
const dropped = quarantineCwdDotenv(process.env, cwd, { assignments });
|
||||
if (hadGuardrailsModule && dropped.includes('GBRAIN_GUARDRAILS_MODULE')) {
|
||||
console.error(GUARDRAILS_ASSIGNED_BY_CWD_DOTENV);
|
||||
process.exit(1);
|
||||
}
|
||||
if (dropped.length > 0) await reexecSanitized(cwd, dropped);
|
||||
}
|
||||
loadGbrainEnvFile(configDir);
|
||||
if (process.env.GBRAIN_GUARDRAILS_MODULE) {
|
||||
try {
|
||||
const { loadGuardrailProvidersFromEnv } = await import('./guardrails.ts');
|
||||
await loadGuardrailProvidersFromEnv(process.env, { skipCwdCheck: collision });
|
||||
} catch (err) {
|
||||
console.error(`guardrails: ${(err as Error)?.message ?? String(err)}`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import type { EngineConfig, EmbeddingColumnConfig } from './types.ts';
|
||||
import { applyDbPlaneReadSideMerge, type DbPlaneEngineReader } from './config-db-merge.ts';
|
||||
import { loadConfigSnapshot } from './config-snapshot.ts';
|
||||
import { loadGbrainEnvFile } from './gbrain-env-file.ts';
|
||||
import { dotenvValuesForKey } from './env-trust.ts';
|
||||
import { REMOTE_PRIVATE_PAGES_KEY } from './search/private-visibility.ts';
|
||||
|
||||
/**
|
||||
@@ -644,68 +645,18 @@ export function loadConfigFileOnly(): GBrainConfig | null {
|
||||
* #427 guard — DATABASE_URL hijack via Bun's cwd .env auto-load.
|
||||
*
|
||||
* Bun merges `.env` files from the process cwd into process.env before any
|
||||
* user code runs. For a globally-installed tool that is a footgun: running
|
||||
* gbrain inside any checkout whose `.env` defines DATABASE_URL (Next.js,
|
||||
* Hono, Supabase, most web apps) silently retargets the brain at that app's
|
||||
* database. Reads hit the wrong DB; `apply-migrations` can write gbrain's
|
||||
* schema — including its DDL event trigger — into a production app database
|
||||
* (see the v0.42.8 report on #427).
|
||||
*
|
||||
* Bun gives no way to ask which vars came from a .env file (the merge
|
||||
* happens before module load), so we re-parse the .env files Bun auto-loads
|
||||
* from cwd and treat DATABASE_URL as "not operator-provided" when its value
|
||||
* matches one of them. Deliberate overrides still work two ways:
|
||||
* - GBRAIN_DATABASE_URL: namespaced to this tool, never auto-ignored;
|
||||
* - exporting DATABASE_URL in the shell: exported vars win over .env in
|
||||
* Bun, and a deliberate export that happens to EQUAL the cwd .env value
|
||||
* would have selected the same database anyway — ignoring it changes
|
||||
* the outcome only by honoring the brain config, which is the safe
|
||||
* reading of ambiguous intent.
|
||||
*
|
||||
* The file list is a superset of Bun's auto-load set across NODE_ENV values
|
||||
* so the guard doesn't depend on replicating Bun's exact selection logic.
|
||||
* user code runs, so running gbrain inside any checkout whose `.env` defines
|
||||
* DATABASE_URL (Next.js, Hono, Supabase, most web apps) would silently
|
||||
* retarget the brain at that app's database — `apply-migrations` could write
|
||||
* gbrain's schema into a production app database (the v0.42.8 report on #427).
|
||||
* The cwd-.env parser (`CWD_DOTENV_FILES`, `dotenvValuesForKey`) lives in
|
||||
* env-trust.ts beside the key-presence security quarantine; both symbols are
|
||||
* re-exported here so import sites never chase the move. This guard keeps
|
||||
* VALUE-match semantics: a DATABASE_URL equal to a cwd-.env assignment is
|
||||
* file-origin; a deliberate export that happens to EQUAL it would have chosen
|
||||
* the same database anyway, and GBRAIN_DATABASE_URL is never auto-ignored.
|
||||
*/
|
||||
const CWD_DOTENV_FILES = [
|
||||
'.env', '.env.local',
|
||||
'.env.development', '.env.development.local',
|
||||
'.env.production', '.env.production.local',
|
||||
'.env.test', '.env.test.local',
|
||||
];
|
||||
|
||||
/**
|
||||
* All values assigned to `key` across the .env files in `dir`. Collecting
|
||||
* every assignment (rather than emulating override order) keeps the guard
|
||||
* independent of dotenv precedence rules — a match against ANY assignment
|
||||
* means the value is file-origin. Exported for tests.
|
||||
*/
|
||||
export function dotenvValuesForKey(key: string, dir: string = process.cwd()): Set<string> {
|
||||
const values = new Set<string>();
|
||||
const assignment = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;
|
||||
for (const name of CWD_DOTENV_FILES) {
|
||||
let content: string;
|
||||
try {
|
||||
content = readFileSync(join(dir, name), 'utf-8');
|
||||
} catch {
|
||||
continue; // missing/unreadable file — nothing to guard against
|
||||
}
|
||||
for (const rawLine of content.split('\n')) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const m = line.match(assignment);
|
||||
if (!m || m[1] !== key) continue;
|
||||
let v = m[2].trim();
|
||||
if ((v.startsWith('"') && v.endsWith('"') && v.length >= 2) ||
|
||||
(v.startsWith("'") && v.endsWith("'") && v.length >= 2)) {
|
||||
v = v.slice(1, -1);
|
||||
} else {
|
||||
const hash = v.indexOf(' #');
|
||||
if (hash !== -1) v = v.slice(0, hash).trim();
|
||||
}
|
||||
if (v) values.add(v);
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
export { CWD_DOTENV_FILES, dotenvValuesForKey } from './env-trust.ts';
|
||||
|
||||
let warnedCwdEnvDbUrlIgnored = false;
|
||||
|
||||
|
||||
@@ -224,13 +224,28 @@ export function scanSensitive(
|
||||
const out: SensitivityFinding[] = [];
|
||||
|
||||
// (a) Secrets — scanText applies the fingerprint allowlist itself.
|
||||
const secretFingerprints = new Set<string>();
|
||||
for (const f of scanText(text, { allowlist: config.allowlist })) {
|
||||
out.push({ family: `secret:${f.pattern}`, fingerprint: f.fingerprint });
|
||||
secretFingerprints.add(f.fingerprint);
|
||||
}
|
||||
|
||||
// (b) PII — detection over the ordered PII_PATTERNS families.
|
||||
// (b) PII — detection over the ordered PII_PATTERNS families. secret-scan
|
||||
// OWNS the credential-shaped families it also matches (jwt, bearer): a
|
||||
// value the secret pass already reported is not reported a second time
|
||||
// under `pii:*`. Dedupe is by fingerprint, not by family name, so a short
|
||||
// bearer token under the secret-scan floor still reaches `pii:bearer`, and
|
||||
// `Bearer <vendor key>` collapses onto the vendor finding. The PII bearer
|
||||
// match includes the `Bearer ` keyword; the token-only fingerprint is the
|
||||
// one secret-scan emits, so both spellings are checked.
|
||||
for (const f of findPii(text)) {
|
||||
pushUnlessAllowed(out, `pii:${f.family}`, text.slice(f.start, f.end), config.allowlist);
|
||||
const value = text.slice(f.start, f.end);
|
||||
const tokenOnly = value.replace(/^[Bb]earer\s+/, '');
|
||||
if (
|
||||
secretFingerprints.has(fingerprintValue(value).fingerprint) ||
|
||||
secretFingerprints.has(fingerprintValue(tokenOnly).fingerprint)
|
||||
) continue;
|
||||
pushUnlessAllowed(out, `pii:${f.family}`, value, config.allowlist);
|
||||
}
|
||||
|
||||
// (c1) Private path shapes.
|
||||
|
||||
@@ -1768,11 +1768,11 @@ export interface BrainEngine {
|
||||
*/
|
||||
putRawData(slug: string, source: string, data: object, opts?: { sourceId?: string }): Promise<void>;
|
||||
/**
|
||||
* v0.31.8 (D21): `opts.sourceId` source-scopes the page-id lookup. Without
|
||||
* it, multi-source brains return raw_data rows from every same-slug page
|
||||
* (preserved via two-branch query for back-compat).
|
||||
* v0.31.8 (D21): `opts.sourceId` source-scopes the page-id lookup (without
|
||||
* it, multi-source brains return rows from every same-slug page). Rows
|
||||
* follow the page's soft-delete; `includeDeleted` (export/migration) opts in.
|
||||
*/
|
||||
getRawData(slug: string, source?: string, opts?: PageReadScope): Promise<RawData[]>;
|
||||
getRawData(slug: string, source?: string, opts?: PageReadScope & { includeDeleted?: boolean }): Promise<RawData[]>;
|
||||
|
||||
// Files (v0.27.1: binary asset metadata + storage_path. Image bytes never
|
||||
// enter the DB; storage_path references a path inside the brain repo or an
|
||||
|
||||
360
src/core/env-trust.ts
Normal file
360
src/core/env-trust.ts
Normal file
@@ -0,0 +1,360 @@
|
||||
/**
|
||||
* Trust boundary for environment variables that Bun auto-loaded from the
|
||||
* CURRENT DIRECTORY's `.env` files.
|
||||
*
|
||||
* Bun merges `.env`, `.env.local` and the `.env.<NODE_ENV>[.local]` variants
|
||||
* from the process cwd into process.env before any user code runs — for
|
||||
* `bun run` AND for `bun build --compile` binaries alike (verified on Bun
|
||||
* 1.3.10 and 1.3.13). For a globally installed CLI the cwd is arbitrary: any
|
||||
* cloned repository can carry a `.env`, so those files are UNTRUSTED input.
|
||||
* Bun gives no way to ask which variables came from a file (the merge happens
|
||||
* before module load), so this module re-parses the same files and reasons
|
||||
* about them. Two guards sit on top of that parse:
|
||||
*
|
||||
* - The #427 DATABASE_URL guard (`config.ts:effectiveEnvDatabaseUrl`) is a
|
||||
* VALUE match: the URL is ignored when it equals a cwd-.env assignment.
|
||||
* Running gbrain inside a web-app checkout must not retarget the brain at
|
||||
* that app's database. That value guard never touches
|
||||
* `GBRAIN_DATABASE_URL`; the key-presence quarantine below is what drops
|
||||
* it when a cwd .env ASSIGNS it (a planted brain URL is never intent).
|
||||
* - The security quarantine below is a KEY-PRESENCE match: a protected key
|
||||
* that any cwd .env file assigns is dropped, whatever its value. Value
|
||||
* matching is unsound for a security list because Bun expands `${VAR}`
|
||||
* inside .env values — `KEY=${PWD}/x` lands in process.env as an absolute
|
||||
* path that never equals the file text.
|
||||
*
|
||||
* What the quarantine covers: the code-loading, exec-target, root-redirect,
|
||||
* endpoint-redirect and posture-widening GBRAIN_* keys
|
||||
* (`CWD_DOTENV_PROTECTED_KEYS`) AND the loader / git / node / XDG-config /
|
||||
* TLS-trust / pager-editor / proxy / AI-endpoint / shell-startup hijack families
|
||||
* a cwd .env could plant for the programs gbrain spawns (`CWD_DOTENV_PROTECTED_PREFIXES`,
|
||||
* `CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS`) — `isCwdDotenvProtectedKey` is the
|
||||
* single predicate. Routing/tuning GBRAIN_* keys and everything not listed
|
||||
* still load from a cwd .env. Dropping is in-process; making the drop reach
|
||||
* the programs gbrain spawns is `cli-preflight.ts`'s neutral-cwd re-run.
|
||||
*
|
||||
* Grammar: this parser must accept AT LEAST every line shape Bun's loader
|
||||
* accepts, or an assignment Bun honours becomes invisible to the guard. Bun
|
||||
* treats `\n`, `\r\n` AND a bare `\r` as line terminators (`A=x\rB=1` sets
|
||||
* BOTH keys), keeps U+2028/U+2029 as ordinary value bytes, and does not strip
|
||||
* a leading BOM (we strip it anyway — counting one more assignment is the
|
||||
* safe side). The right-hand side is therefore matched as "everything up to
|
||||
* the line terminator", never as `.*$`: `.` skips `\r` and U+2028/2029, and
|
||||
* the `$` anchor then fails, hiding the whole assignment.
|
||||
*
|
||||
* fs/path only — this runs before anything else in the CLI.
|
||||
*/
|
||||
import { readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
|
||||
/**
|
||||
* The .env names Bun auto-loads from cwd — a superset across NODE_ENV values
|
||||
* so the guards don't depend on replicating Bun's exact selection logic.
|
||||
*/
|
||||
export const CWD_DOTENV_FILES: readonly string[] = [
|
||||
'.env', '.env.local',
|
||||
'.env.development', '.env.development.local',
|
||||
'.env.production', '.env.production.local',
|
||||
'.env.test', '.env.test.local',
|
||||
];
|
||||
|
||||
// Bun's terminator set: CRLF first so it is consumed as one break.
|
||||
const LINE_TERMINATOR = /\r\n|\r|\n/;
|
||||
|
||||
/**
|
||||
* Split .env file content into lines the way Bun's loader does (see the
|
||||
* grammar note above) and strip a leading BOM. Shared with the
|
||||
* `~/.gbrain/.env` loader in gbrain-env-file.ts so both files speak the same
|
||||
* grammar.
|
||||
*/
|
||||
export function splitDotenvLines(content: string): string[] {
|
||||
const body = content.charCodeAt(0) === 0xfeff ? content.slice(1) : content;
|
||||
return body.split(LINE_TERMINATOR);
|
||||
}
|
||||
|
||||
// `export KEY=...` is accepted so a shell-styled .env still counts as an
|
||||
// assignment (the guard errs toward "file-origin"). RHS: see the grammar note.
|
||||
const ASSIGNMENT = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*([^\r\n]*)$/;
|
||||
|
||||
/** One `KEY=<raw rhs>` pair as a cwd .env file spells it (rhs untrimmed, unquoted). */
|
||||
export type DotenvAssignment = readonly [key: string, raw: string];
|
||||
|
||||
/** Every `KEY=<raw rhs>` pair across the cwd .env files in `dir`, in file order. */
|
||||
function* dotenvAssignments(dir: string): Generator<DotenvAssignment> {
|
||||
for (const name of CWD_DOTENV_FILES) {
|
||||
let content: string;
|
||||
try {
|
||||
// nosemgrep: javascript.lang.security.audit.path-traversal.path-join-resolve-traversal.path-join-resolve-traversal -- name iterates the fixed CWD_DOTENV_FILES list and dir is the cwd under audit (process.cwd() by default); read-only scan of the .env files Bun auto-loads from there
|
||||
content = readFileSync(join(dir, name), 'utf-8');
|
||||
} catch {
|
||||
continue; // missing/unreadable file — nothing to guard against
|
||||
}
|
||||
for (const rawLine of splitDotenvLines(content)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const m = line.match(ASSIGNMENT);
|
||||
if (m) yield [m[1]!, m[2] ?? ''];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Materialise every assignment across the cwd .env files in `dir` — ONE read
|
||||
* of the 8 files that `cwdDotenvAssignsKey` and `quarantineCwdDotenv` both
|
||||
* accept in place of `dir`, so cli-preflight.ts parses once per process.
|
||||
*/
|
||||
export function parseCwdDotenv(dir: string = process.cwd()): DotenvAssignment[] {
|
||||
return [...dotenvAssignments(dir)];
|
||||
}
|
||||
|
||||
/** `dir` (parse now) or an already-parsed list from `parseCwdDotenv`. */
|
||||
type DirOrAssignments = string | readonly DotenvAssignment[];
|
||||
function assignmentsOf(source: DirOrAssignments): Iterable<DotenvAssignment> {
|
||||
return typeof source === 'string' ? dotenvAssignments(source) : source;
|
||||
}
|
||||
|
||||
/**
|
||||
* All values assigned to `key` across the .env files in `dir`. Collecting
|
||||
* every assignment (rather than emulating override order) keeps the #427
|
||||
* guard independent of dotenv precedence rules — a match against ANY
|
||||
* assignment means the value is file-origin. Exported for tests.
|
||||
*/
|
||||
export function dotenvValuesForKey(key: string, dir: string = process.cwd()): Set<string> {
|
||||
const values = new Set<string>();
|
||||
for (const [k, raw] of dotenvAssignments(dir)) {
|
||||
if (k !== key) continue;
|
||||
let v = raw.trim();
|
||||
if ((v.startsWith('"') && v.endsWith('"') && v.length >= 2) ||
|
||||
(v.startsWith("'") && v.endsWith("'") && v.length >= 2)) {
|
||||
v = v.slice(1, -1);
|
||||
} else {
|
||||
const hash = v.indexOf(' #');
|
||||
if (hash !== -1) v = v.slice(0, hash).trim();
|
||||
}
|
||||
if (v) values.add(v);
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/**
|
||||
* True when ANY cwd .env file in `dir` assigns `key` — the value is ignored
|
||||
* (an empty assignment still shadows the key in Bun's loader). This is the
|
||||
* predicate the security quarantine and the guardrails loader use. The second
|
||||
* argument may be a pre-parsed `parseCwdDotenv(dir)` list.
|
||||
*/
|
||||
export function cwdDotenvAssignsKey(key: string, dir: DirOrAssignments = process.cwd()): boolean {
|
||||
for (const [k] of assignmentsOf(dir)) {
|
||||
if (k === key) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* GBRAIN_* variables a cwd `.env` file must never be allowed to set. Each
|
||||
* one either makes gbrain load or execute something, relocates its
|
||||
* operator-owned roots, or widens a security posture — so a value planted by
|
||||
* a cloned repository is never operator intent.
|
||||
*
|
||||
* Deliberately NOT listed (documented container/service deployments may
|
||||
* legitimately co-locate them with the process cwd, and the attack model is
|
||||
* a hostile cloned repo, not a serve cwd — SECURITY.md says to launch
|
||||
* `serve --http` from a directory you control): GBRAIN_ADMIN_BOOTSTRAP_TOKEN,
|
||||
* GBRAIN_HTTP_CORS_ORIGIN, GBRAIN_HTTP_TRUST_PROXY. Deferred for a later
|
||||
* decision (TODOS): GBRAIN_SKILLS_DIR, GBRAIN_RECIPES_DIR, GBRAIN_GITHUB_PAT.
|
||||
* `test/env-trust-protected-keys.test.ts` fails when a new suspicious-looking
|
||||
* read (`_BIN|_CLI|_MODULE|_PATH|_HOME|_URL` suffix, `GBRAIN_ALLOW_` prefix)
|
||||
* appears in src/ without a decision here or a `cwd-dotenv-ok:` annotation at
|
||||
* the read site.
|
||||
*/
|
||||
export const CWD_DOTENV_PROTECTED_KEYS: readonly string[] = [
|
||||
// --- code-loading: gbrain import()s the named module -------------------
|
||||
'GBRAIN_GUARDRAILS_MODULE', // guardrail provider module loaded before dispatch
|
||||
'GBRAIN_PLUGIN_PATH', // plugin / skillpack module path
|
||||
// --- exec-target: gbrain spawns the named program ------------------------
|
||||
'GBRAIN_CLAUDE_CLI_BIN', // binary run for the claude-cli language model
|
||||
'GBRAIN_CLAUDE_CLI_HERMETIC_CONFIG', // becomes that binary's CLAUDE_CONFIG_DIR → its hooks/settings
|
||||
'GBRAIN_JOB_CHILD_CLI', // CLI the job-isolation worker spawns per job
|
||||
'GBRAIN_BIN_OVERRIDE', // gbrain binary used by claw-test
|
||||
// --- root / registry redirect ------------------------------------------
|
||||
'GBRAIN_HOME', // relocates ~/.gbrain (config, .env, keys, registry)
|
||||
'GBRAIN_MOUNTS_PATH', // brain mounts registry file
|
||||
'GBRAIN_DATABASE_URL', // THE brain connection string: a cwd .env would retarget every hook, query and write at a planted database; the #427 value guard covers only the bare DATABASE_URL, and this key is "stated intent" everywhere it is read
|
||||
'GBRAIN_DIRECT_DATABASE_URL', // direct-pool override (connection-manager.ts): retargets brain writes at a planted host; has no #427 value guard
|
||||
'GBRAIN_REMOTE_MCP_URL', // `init --remote` default: where the thin client sends its MCP traffic and bearer token
|
||||
'GBRAIN_REMOTE_ISSUER_URL', // `init --remote` default: the OAuth issuer the client trusts and hands its credential to
|
||||
'GBRAIN_OAUTH_RELAY_URL', // the OAuth relay that hands back Google tokens (creds/relay-client.ts): a planted relay is token theft
|
||||
// --- re-run marker ------------------------------------------------------
|
||||
'GBRAIN_CWD_ENV_QUARANTINED', // cli-preflight.ts's sanitized re-run marker; only honoured when the startup cwd IS the .env-free dir it names, so a planted one is inert — listed so it is also dropped and named in the warning
|
||||
// --- posture-widening ----------------------------------------------------
|
||||
'GBRAIN_ALLOW_SHELL_JOBS', // enables the shell job handler (arbitrary exec on the worker)
|
||||
'GBRAIN_ALLOW_PRIVATE_REMOTES', // permits git remotes on private networks
|
||||
'GBRAIN_ALLOW_UNVERIFIED_REMOTE', // skips remote verification on workspace push
|
||||
'GBRAIN_GIT_ALLOW_FILE_TRANSPORT', // permits the git file:// transport
|
||||
'GBRAIN_ALLOW_MASS_RECONCILE', // lifts the mass-delete reconcile guard
|
||||
'GBRAIN_ALLOW_DEFAULT_WRITE', // permits writes into the 'default' source
|
||||
'GBRAIN_NO_SANITY', // disables content sanity checks
|
||||
'GBRAIN_REMOTE_PRIVATE_PAGES', // exposes private pages to remote callers
|
||||
];
|
||||
|
||||
/**
|
||||
* Non-GBRAIN hijack families a cwd `.env` could plant for the PROGRAMS gbrain
|
||||
* spawns (git, the claude CLI, bun/node workers, shell jobs). These are
|
||||
* normally absent from an operator's environment, which is exactly why a
|
||||
* file-planted value lands (Bun never overrides a variable that already
|
||||
* exists). Matched by PREFIX because each family is open-ended
|
||||
* (`GIT_CONFIG_KEY_<n>`, `LD_*`, `BUN_CONFIG_*`); a family member the shell
|
||||
* DID export is untouched unless a cwd .env assigns that same name.
|
||||
*/
|
||||
export const CWD_DOTENV_PROTECTED_PREFIXES: readonly string[] = [
|
||||
'LD_', // glibc loader injection (LD_PRELOAD / LD_LIBRARY_PATH / LD_AUDIT) into every dynamically linked child
|
||||
'DYLD_', // the macOS loader's equivalents (DYLD_INSERT_LIBRARIES, DYLD_LIBRARY_PATH)
|
||||
'GIT_', // git config/hook/exec injection: GIT_CONFIG_COUNT/KEY_n/VALUE_n (core.fsmonitor, core.hooksPath), GIT_EXEC_PATH, GIT_SSH*, GIT_ASKPASS
|
||||
'BUN_', // bun runtime hijack for bun-based children: BUN_OPTIONS (--preload), BUN_INSTALL, BUN_CONFIG_*
|
||||
'NPM_CONFIG_', // npm registry / script-shell / node-options redirection for npm-based children
|
||||
'npm_config_', // the lowercase spelling npm actually reads
|
||||
'BASH_FUNC_', // exported-function injection (`BASH_FUNC_name%%=() {…}`): bash imports the body as a function into every child shell
|
||||
];
|
||||
|
||||
/**
|
||||
* Exact non-GBRAIN keys with the same effect as the prefix families above but
|
||||
* no shared prefix. Same rule: dropped only when a cwd .env assigns them.
|
||||
*/
|
||||
export const CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS: readonly string[] = [
|
||||
// --- node preload / resolution / TLS --------------------------------------
|
||||
'NODE_OPTIONS', // --require/--import a module into every node child (the claude CLI among them)
|
||||
'NODE_PATH', // extra module-resolution roots → dependency shadowing
|
||||
'NODE_EXTRA_CA_CERTS', // trusts a planted CA → TLS interception of API traffic
|
||||
'NODE_TLS_REJECT_UNAUTHORIZED', // =0 disables certificate verification outright
|
||||
// --- ssh credential prompts -----------------------------------------------
|
||||
'SSH_ASKPASS', // program ssh/git run to obtain a passphrase
|
||||
'SSH_ASKPASS_REQUIRE', // forces that program even when a tty is present
|
||||
// --- per-user config roots the spawned tools read as GLOBAL config --------
|
||||
'XDG_CONFIG_HOME', // git reads $XDG_CONFIG_HOME/git/config as global config even when ~/.gitconfig exists → core.fsmonitor / core.hooksPath (no GIT_ prefix); the claude CLI and opencode resolve their config dirs from it too
|
||||
'XDG_DATA_HOME', // per-user data root (credential stores, tool state) the children load from
|
||||
'XDG_CACHE_HOME', // per-user cache root — a planted cache is replayed as trusted state
|
||||
'GNUPGHOME', // gpg home for git commit/tag signing → planted keyring and agent config
|
||||
// --- TLS trust roots for the non-node children (git via curl, python, …) --
|
||||
'SSL_CERT_FILE', 'SSL_CERT_DIR', // OpenSSL trust store override → a planted CA intercepts every HTTPS call the children make
|
||||
'CURL_CA_BUNDLE', // curl's (and libcurl-linked git's) CA bundle override
|
||||
'REQUESTS_CA_BUNDLE', // python requests' CA bundle override
|
||||
// --- OpenSSL code loading: every OpenSSL-linked child (git over https, curl, python, ssh) ---
|
||||
'OPENSSL_CONF', // a planted openssl.cnf names a provider/engine .so that OpenSSL dlopen()s at init
|
||||
'OPENSSL_ENGINES', // the directory OpenSSL loads engine .so files from
|
||||
'OPENSSL_MODULES', // the directory OpenSSL 3 loads provider .so files from
|
||||
// --- per-user roots read raw from the environment by gbrain AND its children ---
|
||||
'TMPDIR', 'TMP', 'TEMP', // os.tmpdir() honours these at call time: a planted (even relative) value steers the sanitized re-run's neutral dir and every temp write into the hostile tree
|
||||
'HOME', 'USERPROFILE', // inert while exported (Bun never overrides a live variable) but under systemd/cron HOME is often UNSET, and the planted value then reaches process.env.HOME and every child's $HOME → ~/.gitconfig, ~/.ssh, ~/.gbrain resolve inside the checkout
|
||||
// --- programs the children hand control to -------------------------------
|
||||
'EDITOR', 'VISUAL', // takes.ts spawns $EDITOR || $VISUAL — an arbitrary program
|
||||
'PAGER', // git (and other children) pipe output through it — an arbitrary program
|
||||
// --- interpreter preload for scripted children (git's own helpers included)
|
||||
'PYTHONPATH', // python module shadowing
|
||||
'PYTHONSTARTUP', // python startup script
|
||||
'PERL5LIB', // perl library path
|
||||
'PERL5OPT', // implicit perl -M module load
|
||||
'RUBYOPT', // implicit ruby -r preload
|
||||
'RUBYLIB', // ruby library path
|
||||
// --- shell startup files / interpreter homes: every NON-INTERACTIVE shell gbrain's children start (the git hooks gbrain writes, `sh -c` in workspace-push and shell jobs) reads these before its first command ---
|
||||
'BASH_ENV', // bash sources this file at the start of every non-interactive shell — arbitrary code before the script's first line
|
||||
// `ENV` (sh/ksh startup file) is deliberately NOT listed: every shell gbrain's children run reads it for INTERACTIVE shells only, and `ENV=production` is a routine key in project .env files.
|
||||
'SHELLOPTS', // imported read-only into every bash: an inherited `xtrace` turns PS4 into code that runs on every traced command
|
||||
'PS4', // the xtrace prompt — expanded, `$(…)` command substitution included, before each traced command
|
||||
'BASHOPTS', // imported shopt set for every bash (expand_aliases, sourcepath, …) — changes how the child parses its own script
|
||||
'PROMPT_COMMAND', // executed before every bash prompt — any interactive child shell (an $EDITOR's shell escape, a hook that drops to a shell) runs it
|
||||
'ZDOTDIR', // relocates zsh's startup files: .zshenv is sourced by EVERY zsh, scripts included
|
||||
'PYTHONHOME', // relocates the python stdlib → the interpreter imports planted code on start (PYTHONPATH is listed above)
|
||||
'PERLLIB', // perl's other library-path variable (PERL5LIB is listed above)
|
||||
'GCONV_PATH', // glibc loads iconv gconv modules — shared objects — from this directory on any charset conversion, in every glibc-linked child
|
||||
// --- proxy MITM of every HTTP client gbrain or its children run -----------
|
||||
'HTTP_PROXY', 'HTTPS_PROXY', 'ALL_PROXY',
|
||||
'http_proxy', 'https_proxy', 'all_proxy',
|
||||
// --- AI CLI / API endpoint redirection ------------------------------------
|
||||
'CLAUDE_CONFIG_DIR', // the claude CLI's config dir → its hooks and settings
|
||||
'ANTHROPIC_BASE_URL', // redirects Anthropic API traffic (and the key with it) to a planted host
|
||||
'ANTHROPIC_AUTH_TOKEN', // substitutes the bearer credential the SDK / claude CLI send
|
||||
'OPENAI_BASE_URL', // redirects OpenAI-compatible API traffic
|
||||
// --- the same redirection for every other provider gbrain's gateway / probes / recipes read from env (build-gateway-config.ts, probes.ts, recipes/*) — the API key travels to the planted host
|
||||
'OPENROUTER_BASE_URL',
|
||||
'LITELLM_BASE_URL',
|
||||
'OLLAMA_BASE_URL',
|
||||
'LMSTUDIO_BASE_URL',
|
||||
'LLAMA_SERVER_BASE_URL',
|
||||
'LLAMA_SERVER_RERANKER_BASE_URL',
|
||||
];
|
||||
|
||||
const PROTECTED_EXACT: ReadonlySet<string> = new Set([
|
||||
...CWD_DOTENV_PROTECTED_KEYS,
|
||||
...CWD_DOTENV_PROTECTED_TOOLCHAIN_KEYS,
|
||||
]);
|
||||
|
||||
/** The one predicate: is `key` something a cwd .env must never be allowed to set? */
|
||||
export function isCwdDotenvProtectedKey(key: string): boolean {
|
||||
if (PROTECTED_EXACT.has(key)) return true;
|
||||
for (const prefix of CWD_DOTENV_PROTECTED_PREFIXES) {
|
||||
if (key.startsWith(prefix)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export interface QuarantineOpts {
|
||||
/** Warning sink; default writes one line to stderr. Injectable for tests. */
|
||||
warn?: (line: string) => void;
|
||||
/** Pre-parsed `parseCwdDotenv(dir)` list; when given, `dir` is not re-read. */
|
||||
assignments?: readonly DotenvAssignment[];
|
||||
}
|
||||
|
||||
/** The remediation every cwd-.env refusal ends with (also used by guardrails.ts). */
|
||||
export const CWD_DOTENV_REMEDIATION =
|
||||
'cwd .env files are untrusted for security settings. Export it from your shell or set it ' +
|
||||
'in ~/.gbrain/.env.';
|
||||
|
||||
export function formatQuarantineWarning(keys: readonly string[]): string {
|
||||
return (
|
||||
`[env] Ignoring ${keys.join(', ')} because a .env file in the current directory assigns it — ` +
|
||||
CWD_DOTENV_REMEDIATION
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop every protected key present in `env` that a cwd .env file in `dir`
|
||||
* assigns, and print ONE stderr warning naming them (sorted). Returns the
|
||||
* dropped keys, sorted. Iterates the keys the .env files ASSIGN (not a fixed
|
||||
* list) so the prefix families are covered.
|
||||
*
|
||||
* Semantics worth knowing:
|
||||
* - Per-process, in-process. Deleting a key from process.env is NOT seen by
|
||||
* children spawned without an explicit `env` option (Bun hands them the
|
||||
* environ snapshot it took at startup — verified on Bun 1.3.13). So
|
||||
* whenever this returns a non-empty list, `cli-preflight.ts` re-runs
|
||||
* gbrain once from a fresh EMPTY temporary directory with the sanitized
|
||||
* environment: the re-run's Bun never sees the cwd .env, its environ
|
||||
* simply LACKS the dropped keys (deleted, never carried as `''` — git and
|
||||
* the dynamic loader presence-check `GIT_SSL_NO_VERIFY=` /
|
||||
* `LD_TRACE_LOADED_OBJECTS=`), and every descendant inherits that view.
|
||||
* The re-run switches back to the original cwd in its own preflight.
|
||||
* - Key presence, not value. A value the operator exported from the shell
|
||||
* is ALSO dropped while a cwd .env assigns the same key: Bun's `${VAR}`
|
||||
* expansion makes the two indistinguishable, and for this fixed security
|
||||
* list a false drop (loud, with the fix in the message) is the safe side.
|
||||
* - Fail-soft on I/O: an unreadable .env is treated as absent.
|
||||
*/
|
||||
export function quarantineCwdDotenv(
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
dir: string = process.cwd(),
|
||||
opts: QuarantineOpts = {},
|
||||
): string[] {
|
||||
const dropped: string[] = [];
|
||||
const seen = new Set<string>();
|
||||
for (const [key] of opts.assignments ?? dotenvAssignments(dir)) {
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
if (env[key] === undefined || !isCwdDotenvProtectedKey(key)) continue;
|
||||
delete env[key];
|
||||
dropped.push(key);
|
||||
}
|
||||
dropped.sort();
|
||||
if (dropped.length > 0) {
|
||||
(opts.warn ?? ((line: string) => console.error(line)))(formatQuarantineWarning(dropped));
|
||||
}
|
||||
return dropped;
|
||||
}
|
||||
@@ -12,11 +12,15 @@
|
||||
*/
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
import { splitDotenvLines } from './env-trust.ts';
|
||||
|
||||
// KEY=VALUE with a POSIX-shaped name. `export KEY=...` is deliberately not
|
||||
// accepted: this is an env FILE, not a shell script (same stance as Bun's
|
||||
// own .env loader).
|
||||
const ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/;
|
||||
// own .env loader). Line grammar is shared with the cwd-.env guard
|
||||
// (env-trust.ts): `\n`, `\r\n` AND a bare `\r` terminate a line, a leading
|
||||
// BOM is stripped, and the RHS is "everything up to the terminator" — never
|
||||
// `.*$`, which cannot match past a `\r` or U+2028 and would hide the line.
|
||||
const ASSIGNMENT = /^([A-Za-z_][A-Za-z0-9_]*)\s*=\s*([^\r\n]*)$/;
|
||||
|
||||
/**
|
||||
* Parse `<dir>/.env` and fill process.env with its assignments.
|
||||
@@ -30,7 +34,7 @@ export function loadGbrainEnvFile(resolveDir: () => string): void {
|
||||
const envPath = join(resolveDir(), '.env');
|
||||
if (!existsSync(envPath)) return;
|
||||
const raw = readFileSync(envPath, 'utf-8');
|
||||
for (const rawLine of raw.split('\n')) {
|
||||
for (const rawLine of splitDotenvLines(raw)) {
|
||||
const line = rawLine.trim();
|
||||
if (!line || line.startsWith('#')) continue;
|
||||
const m = line.match(ASSIGNMENT);
|
||||
|
||||
@@ -33,6 +33,10 @@
|
||||
*
|
||||
* @module guardrails
|
||||
*/
|
||||
import { homedir } from 'node:os';
|
||||
import { isAbsolute, resolve } from 'node:path';
|
||||
import { pathToFileURL } from 'node:url';
|
||||
import { CWD_DOTENV_REMEDIATION, cwdDotenvAssignsKey } from './env-trust.ts';
|
||||
|
||||
/**
|
||||
* The boundary at which a guardrail is being consulted. Stable string union so
|
||||
@@ -141,8 +145,8 @@ export interface GuardrailEnvLoadResult {
|
||||
|
||||
/**
|
||||
* #3688 — the operator wiring path. Loads guardrail providers from the module
|
||||
* named by `GBRAIN_GUARDRAILS_MODULE` (an absolute/relative file path or a
|
||||
* bare package specifier). Accepted module shapes, all additive:
|
||||
* named by `GBRAIN_GUARDRAILS_MODULE`: an ABSOLUTE file path or a `~/` path.
|
||||
* Accepted module shapes, all additive:
|
||||
*
|
||||
* - `export default provider` (a single {@link GuardrailProvider})
|
||||
* - `export default [providerA, providerB]`
|
||||
@@ -152,23 +156,55 @@ export interface GuardrailEnvLoadResult {
|
||||
* Unset env var → no-op (the OSS distribution stays inert). Set-but-broken —
|
||||
* import failure, or a module that registers zero providers — throws
|
||||
* {@link GuardrailLoadError} (fail-closed; see class doc).
|
||||
*
|
||||
* Origin checks (all throw {@link GuardrailLoadError} BEFORE any import):
|
||||
* - cwd-relative specs (`./x`, `../x`, bare `.`) are refused — they would
|
||||
* resolve against whatever directory the process happens to run in.
|
||||
* - bare package specifiers (`some-pkg`, `@scope/pkg`, `pkg/sub`) are
|
||||
* refused — in the compiled binary Bun's module walk-up starts at the
|
||||
* CURRENT DIRECTORY, so a hostile checkout's `node_modules/<name>/` is
|
||||
* what would load. Only an absolute or `~/` path names a module the
|
||||
* operator chose.
|
||||
* - when `env` is `process.env` (or `opts.cwd` is given), a spec that a cwd
|
||||
* `.env` file assigns is refused whatever its value: Bun auto-loads those
|
||||
* files and expands `${VAR}` inside them, so a cloned repository could
|
||||
* otherwise pick the module. The CLI already quarantines the variable at
|
||||
* startup (`cli-preflight.ts` → `env-trust.ts`); this is belt-and-braces
|
||||
* for `gbrain/core/guardrails` library callers. `opts.skipCwdCheck` is
|
||||
* for the one legitimate collision — the cwd IS the operator's config
|
||||
* dir, so the "cwd .env" is `~/.gbrain/.env` itself (preflight decides).
|
||||
*/
|
||||
export async function loadGuardrailProvidersFromEnv(
|
||||
env: Record<string, string | undefined> = process.env,
|
||||
opts: { cwd?: string; skipCwdCheck?: boolean } = {},
|
||||
): Promise<GuardrailEnvLoadResult> {
|
||||
const spec = env.GBRAIN_GUARDRAILS_MODULE?.trim();
|
||||
if (!spec) return { loaded: 0, modulePath: null };
|
||||
|
||||
// File paths import via file:// URL so relative specs resolve against the
|
||||
// operator's cwd, not against this module's location.
|
||||
let target = spec;
|
||||
if (spec.startsWith('.') || spec.startsWith('/') || spec.startsWith('~')) {
|
||||
const { resolve } = await import('node:path');
|
||||
const { pathToFileURL } = await import('node:url');
|
||||
const { homedir } = await import('node:os');
|
||||
const expanded = spec.startsWith('~') ? spec.replace(/^~/, homedir()) : spec;
|
||||
target = pathToFileURL(resolve(expanded)).href;
|
||||
if (spec.startsWith('.')) {
|
||||
throw new GuardrailLoadError(
|
||||
`GBRAIN_GUARDRAILS_MODULE=${spec} is a cwd-relative path and is not loaded; ` +
|
||||
`use an absolute path or a ~/ path.`,
|
||||
);
|
||||
}
|
||||
const homePath = spec.startsWith('~/') || spec.startsWith('~\\');
|
||||
if (!homePath && !isAbsolute(spec)) {
|
||||
throw new GuardrailLoadError(
|
||||
`GBRAIN_GUARDRAILS_MODULE=${spec} must be an absolute path or a ~/ path (package names ` +
|
||||
`resolve from the current directory's node_modules and are not loaded).`,
|
||||
);
|
||||
}
|
||||
if (!opts.skipCwdCheck && (env === process.env || opts.cwd !== undefined) &&
|
||||
cwdDotenvAssignsKey('GBRAIN_GUARDRAILS_MODULE', opts.cwd)) {
|
||||
throw new GuardrailLoadError(
|
||||
'GBRAIN_GUARDRAILS_MODULE is assigned by a .env file in the current directory and is ' +
|
||||
`not loaded — ${CWD_DOTENV_REMEDIATION}`,
|
||||
);
|
||||
}
|
||||
|
||||
// Import via file:// URL so the spec is taken literally rather than
|
||||
// resolved against this module's location.
|
||||
const target = pathToFileURL(resolve(homePath ? homedir() + spec.slice(1) : spec)).href;
|
||||
|
||||
// #3688 residual: snapshot BEFORE the import, not after. A module that
|
||||
// registers its providers as a top-level side effect (calling
|
||||
|
||||
@@ -162,7 +162,7 @@ export async function runJobInChild(opts: RunJobInChildOpts): Promise<unknown> {
|
||||
|
||||
const inv = buildSpawnInvocation(opts.tiniPath, opts.invocation.cmd, [
|
||||
...opts.invocation.argsPrefix,
|
||||
...buildChildArgs(opts.jobId),
|
||||
...buildChildArgs(opts.jobId, base),
|
||||
]);
|
||||
|
||||
let child: ChildProcess;
|
||||
|
||||
@@ -30,14 +30,19 @@
|
||||
* scrubbed text; original is not mutated.
|
||||
*
|
||||
* @param text The stdout/stderr/error text to scrub.
|
||||
* @param secrets Map of inherit-name → resolved value. Empty values are skipped.
|
||||
* Order doesn't matter (each value is independently replaced).
|
||||
* @param secrets inherit-name → resolved value pairs: a Map, or any ordered
|
||||
* iterable of `[name, value]` (secret-scan passes an array so
|
||||
* two values can share a pattern name). Empty values are
|
||||
* skipped. Values are replaced in iteration order; that only
|
||||
* matters when one value is a substring of another — put the
|
||||
* longer value first, or its span is corrupted by the shorter
|
||||
* replacement before it is reached.
|
||||
*/
|
||||
export function redactSecretsInText(
|
||||
text: string,
|
||||
secrets: ReadonlyMap<string, string>,
|
||||
secrets: Iterable<readonly [string, string]>,
|
||||
): string {
|
||||
if (text.length === 0 || secrets.size === 0) return text;
|
||||
if (text.length === 0) return text;
|
||||
let result = text;
|
||||
for (const [name, value] of secrets) {
|
||||
if (value.length === 0) continue;
|
||||
|
||||
@@ -206,11 +206,13 @@ class TailBuffer {
|
||||
export async function shellHandler(ctx: MinionJobContext): Promise<ShellJobResult> {
|
||||
if (process.env.GBRAIN_ALLOW_SHELL_JOBS !== '1') {
|
||||
const warning =
|
||||
`[shell] Job #${ctx.id} rejected: GBRAIN_ALLOW_SHELL_JOBS=1 not set on this worker.\n` +
|
||||
' Shell jobs require the env var on the worker process.';
|
||||
`[shell] Job #${ctx.id} rejected: shell jobs are not enabled on this worker.\n` +
|
||||
' Start it with `gbrain jobs work --allow-shell-jobs` (or export GBRAIN_ALLOW_SHELL_JOBS=1\n' +
|
||||
' from your shell; a .env in the working directory cannot set it).';
|
||||
console.warn(warning);
|
||||
throw new UnrecoverableError(
|
||||
'shell handler disabled on this worker (set GBRAIN_ALLOW_SHELL_JOBS=1 to execute shell jobs)',
|
||||
'shell handler disabled on this worker (start it with --allow-shell-jobs or ' +
|
||||
'GBRAIN_ALLOW_SHELL_JOBS=1 to execute shell jobs)',
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -221,9 +221,17 @@ export async function decodeChildOutcomeFileAsync(
|
||||
return parseChildOutcome(await readFile(path, 'utf8'), size, maxBytes);
|
||||
}
|
||||
|
||||
/** argv for the child invocation (appended after the resolved CLI). */
|
||||
export function buildChildArgs(jobId: number): string[] {
|
||||
return ['jobs', 'run-child', '--job-id', String(jobId)];
|
||||
/**
|
||||
* argv for the child invocation (appended after the resolved CLI). The shell
|
||||
* opt-in travels as a FLAG as well as env: the child is a fresh gbrain process
|
||||
* that re-runs the startup cwd-.env quarantine (core/env-trust.ts) in the
|
||||
* worker's cwd and would drop GBRAIN_ALLOW_SHELL_JOBS again whenever a .env
|
||||
* there assigns it; `jobs run-child` re-asserts the env var from the flag.
|
||||
*/
|
||||
export function buildChildArgs(jobId: number, env: Record<string, string | undefined> = process.env): string[] {
|
||||
const args = ['jobs', 'run-child', '--job-id', String(jobId)];
|
||||
if (env.GBRAIN_ALLOW_SHELL_JOBS === '1') args.push('--allow-shell-jobs');
|
||||
return args;
|
||||
}
|
||||
|
||||
export interface ChildCliInvocation {
|
||||
|
||||
@@ -82,7 +82,9 @@ export interface SupervisorOpts {
|
||||
healthInterval: number;
|
||||
/** Path to the gbrain CLI executable (MUST be a compiled binary; .ts sources cannot be spawned). */
|
||||
cliPath: string;
|
||||
/** Allow shell jobs on child worker. Default: false. When true, sets GBRAIN_ALLOW_SHELL_JOBS=1 on child env. */
|
||||
/** Allow shell jobs on child worker. Default: false. When true, sets GBRAIN_ALLOW_SHELL_JOBS=1 on the
|
||||
* child env AND passes `--allow-shell-jobs` (buildWorkerArgs) so the worker's cwd-.env quarantine
|
||||
* cannot silently drop the opt-in. */
|
||||
allowShellJobs: boolean;
|
||||
/** JSON mode: emit JSONL events on stderr, reserve stdout for data payloads. Default: false. */
|
||||
json: boolean;
|
||||
@@ -180,7 +182,8 @@ const DEFAULTS: Omit<SupervisorOpts, 'cliPath'> = {
|
||||
* niceness also inherits to the worker's own children automatically.
|
||||
*/
|
||||
export function buildWorkerArgs(
|
||||
opts: Pick<SupervisorOpts, 'concurrency' | 'queue' | 'maxRssMb' | 'nice_requested' | 'jobIsolation'>,
|
||||
opts: Pick<SupervisorOpts, 'concurrency' | 'queue' | 'maxRssMb' | 'nice_requested' | 'jobIsolation'> &
|
||||
Partial<Pick<SupervisorOpts, 'allowShellJobs'>>,
|
||||
): string[] {
|
||||
const args = [
|
||||
'jobs', 'work',
|
||||
@@ -198,6 +201,14 @@ export function buildWorkerArgs(
|
||||
if (opts.jobIsolation === 'process') {
|
||||
args.push('--job-isolation', 'process');
|
||||
}
|
||||
// Conditional push: the shell opt-in travels as a flag as well as env. The
|
||||
// worker's startup cwd-.env quarantine (core/env-trust.ts) drops
|
||||
// GBRAIN_ALLOW_SHELL_JOBS whenever a .env in the worker's cwd assigns it,
|
||||
// so an env-only handoff could silently disable shell jobs; `jobs work`
|
||||
// re-asserts the env from this flag after its preflight.
|
||||
if (opts.allowShellJobs) {
|
||||
args.push('--allow-shell-jobs');
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
|
||||
@@ -63,6 +63,16 @@ export class OAuthConsentError extends Error {
|
||||
constructor(readonly status: number, readonly code: string, message: string) { super(message); }
|
||||
}
|
||||
|
||||
/** Global ceiling on the in-memory pending store; a full store rejects new requests rather than evicting live ones. */
|
||||
const MAX_PENDING_TOTAL = 1000;
|
||||
/**
|
||||
* Per-client ceiling on requests still awaiting a decision. Without it a handful of callers could fill
|
||||
* the global store on behalf of one self-registered client; with it, no single client_id can consume
|
||||
* more than a sliver of the capacity every other client shares. Decided (approved/denied/failed) entries
|
||||
* stay in the store until expiry but do not count: only the owner can move a request out of `pending`.
|
||||
*/
|
||||
const MAX_PENDING_PER_CLIENT = 10;
|
||||
|
||||
export class OAuthGrants {
|
||||
private readonly pending = new Map<string, PendingAuthorization>();
|
||||
constructor(private readonly options: {
|
||||
@@ -90,9 +100,20 @@ export class OAuthGrants {
|
||||
}
|
||||
}
|
||||
|
||||
async begin(clientId: string, params: AuthorizationParams): Promise<string> {
|
||||
/** Synchronous: prune, then enforce the global and per-client ceilings. Callers must not await between this and the insert. */
|
||||
private assertCapacity(clientId: string): void {
|
||||
this.prune();
|
||||
if (this.pending.size >= 1000) throw new TooManyRequestsError('Too many pending requests. Try again shortly.');
|
||||
if (this.pending.size >= MAX_PENDING_TOTAL) throw new TooManyRequestsError('Too many pending requests. Try again shortly.');
|
||||
let awaiting = 0;
|
||||
for (const pending of this.pending.values()) {
|
||||
if (pending.status === 'pending' && pending.details.clientId === clientId && ++awaiting >= MAX_PENDING_PER_CLIENT) {
|
||||
throw new TooManyRequestsError('Too many pending requests for this client. Complete or wait for an earlier request before starting another.');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async begin(clientId: string, params: AuthorizationParams): Promise<string> {
|
||||
this.assertCapacity(clientId);
|
||||
if (!/^[A-Za-z0-9_-]{43}$/.test(params.codeChallenge)) throw new InvalidRequestError('S256 PKCE challenge required');
|
||||
const [row] = await this.options.sql`SELECT * FROM oauth_clients WHERE client_id = ${clientId}`;
|
||||
assertActive(row);
|
||||
@@ -102,9 +123,8 @@ export class OAuthGrants {
|
||||
if (!Array.isArray(row.redirect_uris) || !row.redirect_uris.some(uri => typeof uri === 'string' && redirectUriMatches(params.redirectUri, uri))) {
|
||||
throw new InvalidRequestError('Redirect URI does not match registered client');
|
||||
}
|
||||
// No await between the capacity check and insert: concurrent DB reads cannot overfill the store.
|
||||
this.prune();
|
||||
if (this.pending.size >= 1000) throw new TooManyRequestsError('Too many pending requests. Try again shortly.');
|
||||
// No await between the capacity check and insert: concurrent DB reads cannot overfill the store or a client's budget.
|
||||
this.assertCapacity(clientId);
|
||||
const id = generateToken('');
|
||||
const details: OAuthConsentDetails = {
|
||||
id, clientId, clientName: typeof row.client_name === 'string' ? row.client_name : clientId,
|
||||
|
||||
@@ -34,6 +34,7 @@ import {
|
||||
parseScopeString,
|
||||
InvalidScopeError,
|
||||
ALLOWED_SCOPES_LIST,
|
||||
dcrScopeViolation,
|
||||
} from './scope.ts';
|
||||
import type { AuthInfo as CoreAuthInfo } from './operations.ts';
|
||||
import { parseLegacyTokenScope, parseTakesHoldersAllowList, coerceLegacyPermissions, normalizeTokenScopes } from './legacy-token-scope.ts';
|
||||
@@ -241,11 +242,11 @@ interface GBrainOAuthProviderOptions {
|
||||
/**
|
||||
* Allow the consent-bypassing `client_credentials` grant on the unauthenticated
|
||||
* Dynamic Client Registration path. Default false (#1353): a self-registered
|
||||
* DCR client defaults to `authorization_code` (which goes through /authorize
|
||||
* consent), and an explicit `client_credentials` request is rejected. Operators
|
||||
* who genuinely need machine-to-machine DCR clients opt in via
|
||||
* `--enable-dcr-insecure`. Manual CLI / admin registration is unaffected
|
||||
* (operator-trusted, registers grants directly).
|
||||
* DCR client defaults to `authorization_code` (owner approval on /authorize),
|
||||
* and an explicit `client_credentials` request is rejected. Operators who opt
|
||||
* in via `--enable-dcr-insecure` get anonymous READ-ONLY machine clients: the
|
||||
* DCR scope ceiling (`dcrScopeViolation` in scope.ts) caps them at `read`.
|
||||
* Manual CLI / admin registration is unaffected (operator-trusted).
|
||||
*/
|
||||
allowClientCredentialsDcr?: boolean;
|
||||
/**
|
||||
@@ -365,17 +366,31 @@ class GBrainClientsStore implements OAuthRegisteredClientsStore {
|
||||
validateRedirectUri(String(uri));
|
||||
}
|
||||
|
||||
// Scope policy for DCR: filter unknowns (RFC 7591 value replacement)
|
||||
// instead of hard-rejecting. Spec-compliant clients and OIDC-flavored
|
||||
// stacks often append `offline_access` / `openid`; rejecting those as
|
||||
// 500 made every such client fail registration. authorize() already
|
||||
// clamps issued tokens to the registered grant, so dropping extras is
|
||||
// safe. Empty-after-filter with a non-empty request is a hard 400.
|
||||
// Operator CLI/admin paths still use assertAllowedScopes (typo-loud).
|
||||
const requestedScopes = parseScopeString(client.scope);
|
||||
if (requestedScopes.includes('agent')) {
|
||||
throw new InvalidClientMetadataError('agent scope requires an operator-approved grant with explicit delegation bindings; dynamic registration cannot grant it');
|
||||
// v0.42 (#1353): the DCR path is the unauthenticated network entry point.
|
||||
// `client_credentials` skips /authorize owner approval entirely, so a
|
||||
// self-registered DCR client must NOT get it unless the operator opted in
|
||||
// via `--enable-dcr-insecure`. Gated BEFORE the scope ceiling: when the
|
||||
// grant is not on offer at all the reply must say so, not "limited to
|
||||
// read" (which implies it is available narrower). CLI/admin paths bypass this.
|
||||
grantTypes = client.grant_types?.length ? client.grant_types : ['authorization_code'];
|
||||
if (!this.allowClientCredentialsDcr && grantTypes.includes('client_credentials')) {
|
||||
throw new InvalidClientMetadataError(
|
||||
'client_credentials grant is not permitted via dynamic client registration; ' +
|
||||
'restart the server with --enable-dcr-insecure to allow it, or register the ' +
|
||||
'client via the gbrain CLI / admin API.',
|
||||
);
|
||||
}
|
||||
|
||||
// Scope policy for DCR: (1) ceiling — anonymous registration may hold
|
||||
// at most `read write` (`read` for an allowed client_credentials
|
||||
// registration); privileged scopes are REJECTED as 400, never silently
|
||||
// dropped (scope.ts). The ceiling depends on the grant default above.
|
||||
// (2) filter unknowns (RFC 7591 value replacement) instead of
|
||||
// hard-rejecting: OIDC-flavored stacks append `offline_access` /
|
||||
// `openid`. Empty-after-filter with a non-empty request is a hard 400.
|
||||
const requestedScopes = parseScopeString(client.scope);
|
||||
const ceilingViolation = dcrScopeViolation(requestedScopes, grantTypes);
|
||||
if (ceilingViolation) throw new InvalidClientMetadataError(ceilingViolation);
|
||||
const { allowed, dropped } = filterAllowedScopes(requestedScopes);
|
||||
if (dropped.length > 0) {
|
||||
console.warn(
|
||||
@@ -397,23 +412,6 @@ class GBrainClientsStore implements OAuthRegisteredClientsStore {
|
||||
// registration entry points share one allow-list.
|
||||
authMethod = validateTokenEndpointAuthMethod(client.token_endpoint_auth_method);
|
||||
|
||||
// v0.42 (#1353): the DCR path is the unauthenticated network entry point.
|
||||
// `client_credentials` skips /authorize consent entirely, so a self-
|
||||
// registered DCR client must NOT get it by default. Default the grant to
|
||||
// `authorization_code` (the consent-bearing flow) when unspecified, and
|
||||
// reject an explicit `client_credentials` request unless the operator opted
|
||||
// in via `--enable-dcr-insecure`. Manual CLI/admin registration bypasses
|
||||
// this store method, so operators can still mint machine clients directly.
|
||||
grantTypes = (client.grant_types && client.grant_types.length > 0)
|
||||
? client.grant_types
|
||||
: ['authorization_code'];
|
||||
if (!this.allowClientCredentialsDcr && grantTypes.includes('client_credentials')) {
|
||||
throw new InvalidClientMetadataError(
|
||||
'client_credentials grant is not permitted via dynamic client registration; ' +
|
||||
'restart the server with --enable-dcr-insecure to allow it, or register the ' +
|
||||
'client via the gbrain CLI / admin API.',
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
asClientMetadataError(err);
|
||||
}
|
||||
|
||||
@@ -473,6 +473,56 @@ export function sourceScopeOpts(ctx: OperationContext): { sourceId?: string; sou
|
||||
return {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Confine an explicitly named source id to the caller's resolved READ scope
|
||||
* (#4433 wave-L posture; used by sources_status — the destructive
|
||||
* sources_remove keys on `assertSourceInCallerWriteScope` below instead):
|
||||
* EVERY untrusted caller (anything not strictly `remote === false`) may only
|
||||
* name a source inside the canonical `sourceScopeOpts` ladder — federated
|
||||
* grant > scalar bound source. An out-of-scope id answers `not_found`, exactly
|
||||
* like a nonexistent source (anti-enumeration). The trusted local CLI passes
|
||||
* unconditionally (full operator view). Returns void; throws otherwise.
|
||||
*/
|
||||
export function assertSourceInCallerScope(ctx: OperationContext, id: string): void {
|
||||
if (ctx.remote === false) return;
|
||||
const scope = sourceScopeOpts(ctx);
|
||||
const allowed = scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : null);
|
||||
if (allowed && !allowed.includes(id)) {
|
||||
throw new OperationError('not_found', `Unknown source: ${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* WRITE-authority twin of `assertSourceInCallerScope`, for the DESTRUCTIVE
|
||||
* source ops (`sources_remove`). Federation (`ctx.auth.allowedSources`) is READ
|
||||
* authority by contract (contract.ts: "source ids this OAuth client may READ
|
||||
* from") and confers no removal right, so this helper deliberately does NOT
|
||||
* consult the `sourceScopeOpts` ladder — a client bound to write `alpha` with
|
||||
* `federated_read: [alpha, beta]` may read `beta` but never cascade-delete it.
|
||||
*
|
||||
* Rules, in order:
|
||||
* - trusted local CLI (`remote === false`) passes unconditionally;
|
||||
* - an untrusted caller that is BOUND — carries a write source
|
||||
* (`ctx.auth.sourceId`, falling back to `ctx.sourceId`; the same notion as
|
||||
* delete_page/restore_page's write gate) and/or a federated grant — may
|
||||
* name ONLY its write source; a bound caller with no write source (or the
|
||||
* `__all__` sentinel as its source) may name nothing;
|
||||
* - an UNBOUND untrusted caller (neither axis set — an operator-registered
|
||||
* client with no source binding) keeps full authority, unchanged.
|
||||
* Out-of-authority ids answer `not_found`, byte-identical to a nonexistent
|
||||
* id (anti-enumeration; the same shape the read helper uses, so a caller
|
||||
* cannot tell "hidden" from "absent"). Returns void; throws otherwise.
|
||||
*/
|
||||
export function assertSourceInCallerWriteScope(ctx: OperationContext, id: string): void {
|
||||
if (ctx.remote === false) return;
|
||||
const writeSource = ctx.auth?.sourceId ?? ctx.sourceId;
|
||||
const bound = writeSource !== undefined || ctx.auth?.allowedSources !== undefined;
|
||||
if (!bound) return;
|
||||
if (writeSource === undefined || writeSource === ALL_SOURCES || id !== writeSource) {
|
||||
throw new OperationError('not_found', `Unknown source: ${id}`);
|
||||
}
|
||||
}
|
||||
|
||||
/** Holder permissions are independent of the operator's page-visibility opt-out. */
|
||||
export function readHolders(ctx: OperationContext): string[] | undefined {
|
||||
return ctx.remote === false ? ctx.takesHoldersAllowList : ctx.takesHoldersAllowList ?? ['world'];
|
||||
|
||||
@@ -12,7 +12,7 @@ import { clampSearchLimit } from '../engine.ts';
|
||||
import type { Page, PageType } from '../types.ts';
|
||||
import { importFromContent, type ImportEmbeddingResult } from '../import-file.ts';
|
||||
import { serializePageToMarkdown } from '../markdown.ts';
|
||||
import { writePageThrough, deletePageThrough, resolvePageWriteTarget, isWriteThroughDisabled, withNoRepoWriteThroughWarning, type WriteThroughResult } from '../write-through.ts';
|
||||
import { writePageThrough, deletePageThrough, resolvePageWriteTarget, isWriteThroughDisabled, withNoRepoWriteThroughWarning, type PageWriteTarget, type WriteThroughResult } from '../write-through.ts';
|
||||
import { hasSourceFilesystemLock, withSourceFilesystemLock, assertSourceFilesystemActive } from '../minions/source-filesystem.ts';
|
||||
import { LockUnavailableError } from '../db-lock.ts';
|
||||
import { extractPageLinks, isAutoLinkEnabled, isAutoTimelineEnabled, isGlobalBasenameEnabled, parseTimelineEntries, makeResolver, type UnresolvedFrontmatterRef } from '../link-extraction.ts';
|
||||
@@ -1094,12 +1094,21 @@ async function runAutoLink(
|
||||
return { ...result, unresolved };
|
||||
}
|
||||
|
||||
/** What a purge cannot reach — surfaced on every purged response so a credential remediation never stops at the row. */
|
||||
const PURGE_RESIDUALS = 'Brain-repo git history, synced working-tree copies, exports, compiled context files and slug-keyed derived rows (takes, open loops, file records) may still hold the content — rotate the credential and rewrite or regenerate those copies.';
|
||||
/** A purge that leaves the markdown file behind is not a purge (the next sync re-imports it): an unlink ERROR fails closed, naming the path, and the row stays soft-deleted so the operator fixes the cause and re-runs. Non-error skips (no repo, disabled, file absent) proceed. */
|
||||
function assertPurgeArtifactGone(slug: string, wt: { removed: boolean; error?: string }, target: PageWriteTarget | undefined): void {
|
||||
if (wt.removed || wt.error === undefined) return;
|
||||
const path = target?.ok ? target.filePath : 'its markdown file';
|
||||
throw new OperationError('storage_error', `purge ${slug}: could not remove ${path}: ${wt.error}`, 'Fix the file permissions (or remove the file by hand) and re-run `gbrain delete <slug> --purge`; the row stays soft-deleted until its file is gone.');
|
||||
}
|
||||
const delete_page: Operation = {
|
||||
name: 'delete_page',
|
||||
description: 'Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the result write_through field reports removed + path, or a skipped reason. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed.',
|
||||
description: 'Soft-delete a page and remove its markdown file from the source working tree (the source local_path, or sync.repo_path when the source has none). File removal is skipped when sync.write_through is off; the result write_through field reports removed + path, or a skipped reason. The row is hidden from search and from get_page/list_pages, but is recoverable via restore_page within 72h, which re-creates the file. The autopilot purge phase hard-deletes after the recovery window. Pass include_deleted: true to get_page to verify the soft-delete landed. purge: true (local CLI only — `gbrain delete <slug> --purge`) removes the row and its chunks/links/raw data immediately with no recovery window; use it when a page must not linger (e.g. it captured a credential); the response names the copies a purge cannot reach (git history, exports, derived rows) — rotate first. A purge never reports success while the page\'s markdown file remains: on an already-soft-deleted page it retries the file removal against the recorded path, and a removal error (permissions) fails with storage_error naming the file — fix it and re-run; the row stays soft-deleted until the file is gone. Remote/MCP callers asking for purge get permission_denied (the soft-delete path stays available to them); status purged always carries write_through.',
|
||||
params: {
|
||||
slug: { type: 'string', required: true, description: "Slug of the page to soft-delete, e.g. 'people/alice-example'." },
|
||||
source_id: { type: 'string', description: "#4329: source holding the row to soft-delete (a multi-source brain can hold the same slug in several sources). Defaults to ctx.sourceId. Remote callers may only target their write source — federated read grants do not confer delete access." },
|
||||
purge: { type: 'boolean', description: 'Hard-delete immediately after the soft-delete (no 72h recovery; status purged). Honored only for the trusted local CLI; remote/MCP callers get permission_denied (a non-boolean value is invalid_params) and keep the soft-delete path.' },
|
||||
},
|
||||
mutating: true,
|
||||
scope: 'write',
|
||||
@@ -1110,7 +1119,18 @@ const delete_page: Operation = {
|
||||
// the delete landed on ctx.sourceId's row — the wrong-source soft-delete).
|
||||
const requestedSource = parseSourceIdParam(p.source_id, 'delete_page');
|
||||
if (requestedSource !== undefined) assertSourceInWriteGrant(ctx, requestedSource);
|
||||
if (ctx.dryRun) return { dry_run: true, action: 'soft_delete_page', slug };
|
||||
// purge: strict boolean, trusted-local only (fail-closed: anything not
|
||||
// strictly remote === false is a remote caller). The hard-delete
|
||||
// primitive is the point of no return, so it never rides an agent-facing
|
||||
// transport — the operator types it.
|
||||
if (p.purge !== undefined && typeof p.purge !== 'boolean') {
|
||||
throw new OperationError('invalid_params', 'purge must be a boolean.', 'Pass purge: true (CLI: gbrain delete <slug> --purge).');
|
||||
}
|
||||
const purge = p.purge === true;
|
||||
if (purge && ctx.remote !== false) {
|
||||
throw new OperationError('permission_denied', 'purge is only available to the local CLI.', 'Remote callers soft-delete only; run `gbrain delete <slug> --purge` on the host to remove a page immediately.');
|
||||
}
|
||||
if (ctx.dryRun) return { dry_run: true, action: purge ? 'purge_page' : 'soft_delete_page', slug };
|
||||
// v0.31.8 (D7): thread ctx.sourceId so multi-source brains soft-delete the
|
||||
// intended row instead of always targeting (default, slug).
|
||||
const sourceOpts = requestedSource
|
||||
@@ -1140,6 +1160,23 @@ const delete_page: Operation = {
|
||||
if (!existing) {
|
||||
throw new OperationError('page_not_found', `Page not found: ${slug}`, 'Check the slug (and source_id on a multi-source brain).');
|
||||
}
|
||||
if (purge) {
|
||||
// Remediation path (O4-2): the earlier soft-delete's unlink may have
|
||||
// FAILED (permissions), leaving the credential-bearing .md for the next
|
||||
// sync to resurrect — so RETRY the removal against the tombstone's OWN
|
||||
// recorded path (the active-row resolution above misses it) and fail
|
||||
// closed on error before the row is dropped. Same response shape as
|
||||
// the live-row purge; the outcome is the real one, never a fabricated skip.
|
||||
const tombstoneTarget = isSandboxSubagent
|
||||
? undefined
|
||||
: await resolvePageWriteTarget(ctx.engine, slug, wtSourceId, { includeDeleted: true });
|
||||
const retried = isSandboxSubagent
|
||||
? { removed: false, skipped: 'subagent_sandbox' as const }
|
||||
: await deletePageThrough(ctx.engine, slug, { sourceId: wtSourceId, logger: ctx.logger, target: tombstoneTarget });
|
||||
assertPurgeArtifactGone(slug, retried, tombstoneTarget);
|
||||
await ctx.engine.deletePage(slug, sourceOpts);
|
||||
return { status: 'purged', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), write_through: retried, residuals: PURGE_RESIDUALS };
|
||||
}
|
||||
return { status: 'already_soft_deleted', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), deleted_at: existing.deleted_at };
|
||||
}
|
||||
// #4022: remove the on-disk artifact too. Pre-fix this was DB-only, so the
|
||||
@@ -1151,9 +1188,18 @@ const delete_page: Operation = {
|
||||
const writeThrough = isSandboxSubagent
|
||||
? { removed: false, skipped: 'subagent_sandbox' as const }
|
||||
: await deletePageThrough(ctx.engine, slug, { sourceId: wtSourceId, logger: ctx.logger, target });
|
||||
if (purge) {
|
||||
// Soft-delete first (artifact removal + the same audit shape), then the
|
||||
// hard primitive: cascades through chunks/links/raw_data via FKs. An
|
||||
// artifact-removal ERROR fails closed here too — the row stays a
|
||||
// tombstone and the re-run resumes on the remediation path above.
|
||||
assertPurgeArtifactGone(slug, writeThrough, target);
|
||||
await ctx.engine.deletePage(slug, sourceOpts);
|
||||
return { status: 'purged', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), write_through: writeThrough, residuals: PURGE_RESIDUALS };
|
||||
}
|
||||
// Echo the targeted source so a multi-source caller can verify WHICH row
|
||||
// the delete landed on (#4329's false-confidence failure mode).
|
||||
return { status: 'soft_deleted', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), recoverable_until: 'now + 72h via restore_page', write_through: writeThrough };
|
||||
return { status: 'soft_deleted', slug, ...(sourceOpts.sourceId ? { source_id: sourceOpts.sourceId } : {}), recoverable_until: 'now + 72h via restore_page (remove immediately instead: gbrain delete <slug> --purge, local CLI only)', write_through: writeThrough };
|
||||
},
|
||||
cliHints: { name: 'delete', positional: ['slug'] },
|
||||
};
|
||||
|
||||
@@ -33,7 +33,7 @@ const put_raw_data: Operation = {
|
||||
|
||||
const get_raw_data: Operation = {
|
||||
name: 'get_raw_data',
|
||||
description: 'Retrieve raw data for a page',
|
||||
description: 'Retrieve raw data for a page. Raw data follows the page\'s soft-delete: a tombstoned (soft-deleted) page returns [] exactly like a missing page; restore_page brings the rows back, and get_page include_deleted: true verifies the tombstone.',
|
||||
params: {
|
||||
slug: { type: 'string', required: true, description: 'Slug of the page whose raw data to fetch.' },
|
||||
source: { type: 'string', description: 'Filter by source' },
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
import type { Operation } from './contract.ts';
|
||||
import { OperationError } from './contract.ts';
|
||||
import { sourceScopeOpts } from './context.ts';
|
||||
import { assertSourceInCallerScope, assertSourceInCallerWriteScope, sourceScopeOpts } from './context.ts';
|
||||
import { resolveAuthCapabilities } from '../harness/capabilities.ts';
|
||||
|
||||
// --- v0.28: whoami + sources management ---
|
||||
@@ -193,7 +193,12 @@ const sources_remove: Operation = {
|
||||
'Hard-remove a source (cascades pages/chunks/embeddings). Refuses to ' +
|
||||
'delete the auto-managed clone dir unless its resolved path is confined ' +
|
||||
'under $GBRAIN_HOME/clones/ (realpath+lstat — symlink-safe). For most ' +
|
||||
'workflows prefer sources_archive for the soft-delete path.',
|
||||
'workflows prefer the soft-delete path (`gbrain sources archive`). ' +
|
||||
"Confined to the caller's WRITE authority, not its read scope: an untrusted " +
|
||||
'caller may remove only its own write source (a federated read grant naming ' +
|
||||
'a source does not make it removable); any other id answers not_found, ' +
|
||||
'indistinguishable from a nonexistent source. Only the trusted local CLI ' +
|
||||
'(`gbrain sources remove`) can remove any source.',
|
||||
params: {
|
||||
id: { type: 'string', required: true, description: "Source id to remove, as listed by sources_list (e.g. 'wiki'). A source id, not a page slug." },
|
||||
confirm_destructive: {
|
||||
@@ -210,6 +215,13 @@ const sources_remove: Operation = {
|
||||
mutating: true,
|
||||
scope: 'sources_admin',
|
||||
handler: async (ctx, p) => {
|
||||
// Source isolation on the DESTRUCTIVE path keys on WRITE authority (O4-1;
|
||||
// supersedes the #4433 wave-L read-ladder check that let a federated read
|
||||
// grant hard-delete a sibling source): a `sources_admin` token may remove
|
||||
// only its own write source; out-of-authority ids answer not_found
|
||||
// (anti-enumeration), an unbound client keeps full authority, trusted
|
||||
// local CLI passes. sources_status keeps the READ helper.
|
||||
assertSourceInCallerWriteScope(ctx, p.id as string);
|
||||
const { removeSource } = await import('../sources-ops.ts');
|
||||
return removeSource(ctx.engine, {
|
||||
id: p.id as string,
|
||||
@@ -235,19 +247,11 @@ const sources_status: Operation = {
|
||||
},
|
||||
scope: 'read',
|
||||
handler: async (ctx, p) => {
|
||||
// Source isolation, mirroring sources_list's #4433 wave-L posture
|
||||
// exactly (the maintainer decision that superseded the wave-g "scalar
|
||||
// callers keep the full listing" carve-out): EVERY untrusted caller
|
||||
// (anything not strictly remote === false) is confined through the
|
||||
// canonical sourceScopeOpts ladder — federated grant > scalar bound
|
||||
// source. Trusted local CLI keeps the full operator view. Out-of-scope
|
||||
// ids answer not_found, indistinguishable from a nonexistent source
|
||||
// (anti-enumeration), matching get_agent_job's shape.
|
||||
const scope = ctx.remote === false ? {} : sourceScopeOpts(ctx);
|
||||
const allowed = scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : null);
|
||||
if (allowed && !allowed.includes(p.id as string)) {
|
||||
throw new OperationError('not_found', `Unknown source: ${p.id}`);
|
||||
}
|
||||
// Source isolation (#4433 wave-L posture, the maintainer decision that
|
||||
// superseded the wave-g "scalar callers keep the full listing"
|
||||
// carve-out), via the helper shared with sources_remove: out-of-scope ids
|
||||
// answer not_found (matching get_agent_job's shape), trusted local passes.
|
||||
assertSourceInCallerScope(ctx, p.id as string);
|
||||
const { getSourceStatus } = await import('../sources-ops.ts');
|
||||
return getSourceStatus(ctx.engine, p.id as string);
|
||||
},
|
||||
|
||||
@@ -4990,12 +4990,13 @@ export class PGLiteEngine implements BrainEngine {
|
||||
async getRawData(
|
||||
slug: string,
|
||||
source?: string,
|
||||
opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },
|
||||
opts?: PageReadScope & { includeDeleted?: boolean },
|
||||
): Promise<RawData[]> {
|
||||
// v0.31.8 (D21): build WHERE clause dynamically. Without opts.sourceId,
|
||||
// no source filter (preserves pre-v0.31.8 cross-source read).
|
||||
const where: string[] = ['p.slug = $1'];
|
||||
if (opts?.excludePrivate) where.push(privatePagesFilterFragment('p'));
|
||||
if (!opts?.includeDeleted) where.push('p.deleted_at IS NULL'); // raw_data follows the page soft-delete
|
||||
const params: unknown[] = [slug];
|
||||
if (source) {
|
||||
params.push(source);
|
||||
|
||||
@@ -4191,36 +4191,37 @@ export class PostgresEngine implements BrainEngine {
|
||||
async getRawData(
|
||||
slug: string,
|
||||
source?: string,
|
||||
opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean },
|
||||
opts?: PageReadScope & { includeDeleted?: boolean },
|
||||
): Promise<RawData[]> {
|
||||
const sql = this.sql;
|
||||
const privacy = opts?.excludePrivate ? sql.unsafe(`AND ${privatePagesFilterFragment('p')}`) : sql``;
|
||||
const alive = opts?.includeDeleted ? sql`` : sql`AND p.deleted_at IS NULL`; // raw_data follows the page soft-delete
|
||||
const sourceIds = opts?.sourceIds && opts.sourceIds.length > 0 ? opts.sourceIds : undefined;
|
||||
const sourceId = sourceIds ? undefined : opts?.sourceId;
|
||||
let rows;
|
||||
if (source && sourceIds) {
|
||||
rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd
|
||||
JOIN pages p ON p.id = rd.page_id ${privacy}
|
||||
JOIN pages p ON p.id = rd.page_id ${privacy} ${alive}
|
||||
WHERE p.slug = ${slug} AND rd.source = ${source} AND p.source_id = ANY(${sourceIds}::text[])`;
|
||||
} else if (sourceIds) {
|
||||
rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd
|
||||
JOIN pages p ON p.id = rd.page_id ${privacy}
|
||||
JOIN pages p ON p.id = rd.page_id ${privacy} ${alive}
|
||||
WHERE p.slug = ${slug} AND p.source_id = ANY(${sourceIds}::text[])`;
|
||||
} else if (source && sourceId) {
|
||||
rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd
|
||||
JOIN pages p ON p.id = rd.page_id ${privacy}
|
||||
JOIN pages p ON p.id = rd.page_id ${privacy} ${alive}
|
||||
WHERE p.slug = ${slug} AND rd.source = ${source} AND p.source_id = ${sourceId}`;
|
||||
} else if (source) {
|
||||
rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd
|
||||
JOIN pages p ON p.id = rd.page_id ${privacy}
|
||||
JOIN pages p ON p.id = rd.page_id ${privacy} ${alive}
|
||||
WHERE p.slug = ${slug} AND rd.source = ${source}`;
|
||||
} else if (sourceId) {
|
||||
rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd
|
||||
JOIN pages p ON p.id = rd.page_id ${privacy}
|
||||
JOIN pages p ON p.id = rd.page_id ${privacy} ${alive}
|
||||
WHERE p.slug = ${slug} AND p.source_id = ${sourceId}`;
|
||||
} else {
|
||||
rows = await sql`SELECT rd.source, rd.data, rd.fetched_at FROM raw_data rd
|
||||
JOIN pages p ON p.id = rd.page_id ${privacy}
|
||||
JOIN pages p ON p.id = rd.page_id ${privacy} ${alive}
|
||||
WHERE p.slug = ${slug}`;
|
||||
}
|
||||
return rows as unknown as RawData[];
|
||||
|
||||
@@ -46,6 +46,77 @@ export const ALLOWED_SCOPES_LIST: ReadonlyArray<Scope> = Object.freeze([
|
||||
'write',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Ceiling for anonymous Dynamic Client Registration (RFC 7591). A network
|
||||
* caller that self-registers may hold at most `read write`; every privileged
|
||||
* scope needs an operator-created grant (`gbrain auth register-client`, the
|
||||
* admin API) or a later `gbrain auth rescope-client`. The owner-approval
|
||||
* step on /authorize shows the requested scopes but never narrows them, so
|
||||
* the ceiling is what keeps "approve" from meaning "grant admin".
|
||||
*/
|
||||
export const DCR_REGISTRABLE_SCOPES: ReadonlySet<Scope> = new Set<Scope>(['read', 'write']);
|
||||
|
||||
/**
|
||||
* A `client_credentials` DCR client (only reachable under
|
||||
* `--enable-dcr-insecure`) mints tokens with NO owner approval at all, so its
|
||||
* ceiling is tighter still: read-only.
|
||||
*/
|
||||
const DCR_MACHINE_SCOPES: ReadonlySet<Scope> = new Set<Scope>(['read']);
|
||||
|
||||
/**
|
||||
* null when the requested DCR scopes fit under the ceiling; otherwise the
|
||||
* `invalid_client_metadata` message naming the offending scopes + remedy.
|
||||
* Unknown scope strings are ignored here (filterAllowedScopes drops them);
|
||||
* `agent` keeps its own wording because it also needs delegation bindings.
|
||||
*/
|
||||
export function dcrScopeViolation(requested: readonly string[], grantTypes: readonly string[]): string | null {
|
||||
if (requested.includes('agent')) {
|
||||
return 'agent scope requires an operator-approved grant with explicit delegation bindings; dynamic registration cannot grant it';
|
||||
}
|
||||
const machine = grantTypes.includes('client_credentials');
|
||||
const ceiling = machine ? DCR_MACHINE_SCOPES : DCR_REGISTRABLE_SCOPES;
|
||||
const over = [...new Set(requested.filter((s) => isScope(s) && !ceiling.has(s)))];
|
||||
if (over.length === 0) return null;
|
||||
const limit = [...ceiling].join(' ');
|
||||
return (
|
||||
`Scope "${over.join(' ')}" cannot be granted through dynamic client registration; ` +
|
||||
(machine
|
||||
? `a client_credentials registration is limited to \`${limit}\` because it is issued without owner approval. `
|
||||
: `self-registered clients are limited to \`${limit}\`. `) +
|
||||
'Register the client with `gbrain auth register-client` / the admin API instead, ' +
|
||||
'or register with a narrower scope and widen it later with `gbrain auth rescope-client <client_id> --scopes ...`.'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* `scopes_supported` for OAuth discovery. The MCP SDK router emits ONE value
|
||||
* into the RFC 8414 authorization-server document and the RFC 9728
|
||||
* protected-resource document(s), so this is the single place that decides
|
||||
* what a client reading discovery is told it may ask for:
|
||||
*
|
||||
* - DCR enabled (either mode): exactly the anonymous-registration ceiling,
|
||||
* `read write`, in canonical order. Clients commonly copy `scopes_supported`
|
||||
* verbatim into their /register request; advertising a privileged scope
|
||||
* would steer every such client straight into `dcrScopeViolation` (HTTP 400)
|
||||
* even though the server is willing to register it at `read write`. The
|
||||
* tighter read-only ceiling for `client_credentials` registrations stays in
|
||||
* `dcrScopeViolation` — authorization_code is the DCR default and may hold
|
||||
* both, so advertising `read` alone would under-describe it.
|
||||
* - DCR disabled: every scope except operator-only `agent`, which also needs
|
||||
* delegation bindings no OAuth request can carry. Operator-registered
|
||||
* clients see the full set they may hold.
|
||||
*
|
||||
* Narrowed discovery never narrows an operator-registered client: one that
|
||||
* omits `scope` at /authorize or /token receives its full registered set
|
||||
* (`grantScopes` in oauth-grants.ts falls back to the row's scope), and an
|
||||
* explicit request is intersected with its registration, not with this list.
|
||||
*/
|
||||
export function scopesSupportedForDiscovery(opts: { enableDcr: boolean }): Scope[] {
|
||||
return opts.enableDcr
|
||||
? ALLOWED_SCOPES_LIST.filter((s) => DCR_REGISTRABLE_SCOPES.has(s))
|
||||
: ALLOWED_SCOPES_LIST.filter((s) => s !== 'agent');
|
||||
}
|
||||
|
||||
/**
|
||||
* Hierarchy table: which required scopes are implied by which granted scope.
|
||||
* `admin` implies all (escape hatch for legacy + super-admin tokens).
|
||||
|
||||
@@ -14,9 +14,13 @@
|
||||
* plus a per-workspace override file (`<ws>/.gbrain-scan-allow`, one
|
||||
* glob-or-fingerprint per line, `#` comments).
|
||||
*
|
||||
* Rendering reuses `redactSecretsInText` [ENG-9] so every surface prints
|
||||
* `<REDACTED:pattern>` — a finding preview or redacted corpus NEVER contains
|
||||
* the secret value, and this module never returns raw matched values.
|
||||
* Every surface prints the one canonical token `<REDACTED:pattern>` [ENG-9]:
|
||||
* finding previews splice the token over every claimed span in the preview
|
||||
* window, the corpus writer (`redactFindings`, or `planRedaction` +
|
||||
* `applyRedaction` for multi-field documents) splices it over each claimed
|
||||
* span and then scrubs bare echoes of the bearer / high-entropy values it
|
||||
* claimed (bounded, see there) — neither ever contains the secret value, and
|
||||
* this module never returns raw matched values.
|
||||
*
|
||||
* The generic high-entropy assignment heuristic is OFF by default (opt-in
|
||||
* via `ScanOpts.highEntropy`) — named-prefix patterns are precise; the
|
||||
@@ -27,7 +31,6 @@
|
||||
import { existsSync, readFileSync, statSync } from 'fs';
|
||||
import { isAbsolute, join, relative, sep } from 'path';
|
||||
import { createHash } from 'crypto';
|
||||
import { redactSecretsInText } from './minions/handlers/shell-redact.ts';
|
||||
|
||||
// ── Types ───────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -69,15 +72,48 @@ export const SCAN_ALLOW_FILENAME = '.gbrain-scan-allow';
|
||||
// "task-…") never fire. Order matters: 'anthropic' precedes 'openai' and the
|
||||
// per-line claimed-span set prevents a `sk-ant-…` key from double-reporting
|
||||
// as a generic `sk-` match.
|
||||
//
|
||||
// FORMAT-BASED, not prefix-only. Credentials without a vendor prefix (a JWT,
|
||||
// an account SID, a connection string carrying its password) are matched on
|
||||
// their WIRE SHAPE. Fixed-length shapes carry a trailing negative lookahead so
|
||||
// a longer alphanumeric run (a digest, an identifier) is not cut into a
|
||||
// false "key". The two CATCH-ALLS (`bearer`, `db_url_credentials`) are
|
||||
// appended LAST on purpose: the per-line claimed-span dedupe is first-wins
|
||||
// for ATTRIBUTION, so `Bearer <vendor key>` keeps its vendor attribution and
|
||||
// a JWT used as a URL password is reported as `jwt` once — while COVERAGE is
|
||||
// the union: whatever part of the later catch-all span the earlier claim did
|
||||
// not cover (the userinfo around that JWT) is still claimed by the catch-all
|
||||
// (see scanInternal).
|
||||
|
||||
interface CompiledPattern {
|
||||
name: string;
|
||||
re: RegExp; // 'g' flags; group 1 = boundary, group 2 = the secret value
|
||||
/** When true, a match must also pass the Shannon-entropy gate. */
|
||||
entropyGated?: boolean;
|
||||
/** See CorePattern.precheck. */
|
||||
precheck?: (line: string) => boolean;
|
||||
}
|
||||
|
||||
const CORE_PATTERNS: ReadonlyArray<{ name: string; source: string }> = [
|
||||
interface CorePattern {
|
||||
name: string;
|
||||
source: string;
|
||||
/**
|
||||
* When true, `source` already carries the two-group layout (group 1 =
|
||||
* boundary/anchor, group 2 = value) and is compiled as-is instead of being
|
||||
* wrapped in the default left-boundary group. Used when the anchor is a
|
||||
* literal keyword (e.g. `Bearer `) that must NOT be part of the value.
|
||||
*/
|
||||
prebuilt?: boolean;
|
||||
/**
|
||||
* Cheap substring gate run BEFORE the regex on every line: when it returns
|
||||
* false the line cannot contain a match and the regex is skipped. Used by
|
||||
* the catch-alls, whose alternation + negated classes are the costliest
|
||||
* shapes here and whose anchor (`earer`, `@`) is a one-call `includes`.
|
||||
*/
|
||||
precheck?: (line: string) => boolean;
|
||||
}
|
||||
|
||||
const CORE_PATTERNS: ReadonlyArray<CorePattern> = [
|
||||
{ name: 'anthropic', source: 'sk-ant-[A-Za-z0-9_-]{16,}' },
|
||||
// Prefixed OpenAI forms (sk-proj-/sk-svcacct-/sk-None-) allow `_`/`-` in the
|
||||
// body, which the bare sk- pattern below deliberately does not. Ordered
|
||||
@@ -88,8 +124,27 @@ const CORE_PATTERNS: ReadonlyArray<{ name: string; source: string }> = [
|
||||
{ name: 'voyage', source: 'pa-[A-Za-z0-9_-]{20,}' },
|
||||
{ name: 'github_pat', source: 'github_pat_[A-Za-z0-9_]{22,}' },
|
||||
{ name: 'github_token', source: 'gh[pousr]_[A-Za-z0-9]{36,}' },
|
||||
{ name: 'gitlab_pat', source: 'glpat-[A-Za-z0-9_-]{20,}' },
|
||||
{ name: 'slack', source: 'xox[baprs]-[A-Za-z0-9-]{10,}' },
|
||||
{ name: 'aws_access_key', source: 'AKIA[0-9A-Z]{16}' },
|
||||
// Long-lived (AKIA) and temporary/STS (ASIA) access-key ids: fixed 16 after
|
||||
// the prefix, hard right edge.
|
||||
{ name: 'aws_access_key', source: '(?:AKIA|ASIA)[0-9A-Z]{16}(?![0-9A-Za-z])' },
|
||||
{ name: 'google_api_key', source: 'AIza[0-9A-Za-z_-]{35}(?![0-9A-Za-z_-])' },
|
||||
// Stripe secret/restricted keys + webhook signing secrets.
|
||||
{ name: 'stripe', source: '[sr]k_(?:live|test)_[0-9a-zA-Z]{20,}' },
|
||||
{ name: 'stripe', source: 'whsec_[A-Za-z0-9]{24,}' },
|
||||
{ name: 'sendgrid', source: 'SG\\.[A-Za-z0-9_-]{16,}\\.[A-Za-z0-9_-]{16,}' },
|
||||
// Twilio account SID (AC) / API signing key SID (SK): 32 hex, hard right
|
||||
// edge so a longer hex digest that happens to start with AC never matches.
|
||||
{ name: 'twilio', source: '(?:AC|SK)[0-9a-fA-F]{32}(?![0-9A-Za-z])' },
|
||||
// Supabase secret (sb_secret_) and management/personal access (sbp_) keys.
|
||||
// Deliberately NOT here: `sb_publishable_` (public by design) and the
|
||||
// project ref (hostname label or `project_ref=` assignment) — identifiers,
|
||||
// not credentials.
|
||||
{ name: 'supabase_key', source: 'sb_secret_[A-Za-z0-9_-]{20,}' },
|
||||
{ name: 'supabase_key', source: 'sbp_[a-f0-9]{40}(?![0-9A-Za-z])' },
|
||||
{ name: 'npm_token', source: 'npm_[A-Za-z0-9]{36}(?![A-Za-z0-9])' },
|
||||
{ name: 'huggingface', source: 'hf_[A-Za-z0-9]{30,}' },
|
||||
// gbrain's own tokens: generateToken (core/utils.ts) mints 'gbrain_' plus an
|
||||
// optional OAuth infix (at_ access / rt_ refresh / cs_ client secret /
|
||||
// code_ auth code) plus 32 random bytes hex. Without this entry the scanner
|
||||
@@ -98,6 +153,77 @@ const CORE_PATTERNS: ReadonlyArray<{ name: string; source: string }> = [
|
||||
// transcript ingest carries it into pages. gbrain_cl_ client ids are public
|
||||
// identifiers, deliberately not listed here.
|
||||
{ name: 'gbrain_token', source: 'gbrain_(?:at_|rt_|cs_|code_)?[0-9a-f]{64}' },
|
||||
// JWT: three base64url segments (header.payload.signature). No vendor
|
||||
// prefix — this is the wire format of many service-role / session
|
||||
// credentials, so it is matched on shape. Same source as the PII family in
|
||||
// eval-capture-scrub.ts; secret-scan is the owner for redaction lanes.
|
||||
//
|
||||
// Prebuilt so the left boundary can exclude `-` as well as `_`: the value
|
||||
// class contains both, so with the default boundary every `-` in a run like
|
||||
// `-eyJ-eyJ-eyJ…` was a fresh start that consumed to end-of-line and
|
||||
// backtracked — quadratic (a 200 KB run took ~25 s). Each segment is also
|
||||
// bounded at 4096 so a start that never finds its `.` does constant work.
|
||||
// A JWT immediately preceded by `-` is not a realistic wire shape (headers,
|
||||
// JSON, URLs and env files put whitespace, a quote, `=`, `:` or `/` in
|
||||
// front of it); a segment over 4096 chars is the accepted miss.
|
||||
{
|
||||
name: 'jwt',
|
||||
source:
|
||||
'(^|[^A-Za-z0-9_-])' +
|
||||
'(eyJ[A-Za-z0-9_-]{8,4096}\\.[A-Za-z0-9_-]{8,4096}\\.[A-Za-z0-9_-]{8,4096})',
|
||||
prebuilt: true,
|
||||
},
|
||||
// ── Catch-alls: LAST, so vendor/JWT attribution above claims the span first.
|
||||
// Bearer: prebuilt two-group layout — the `Bearer ` keyword is the anchor
|
||||
// (group 1), only the token is the value (group 2), so the redacted text
|
||||
// reads `Bearer <REDACTED:bearer>` and the fingerprint is the token's.
|
||||
// RFC 7235 auth-scheme names are case-insensitive; the three spellings
|
||||
// seen on the wire (`Bearer`, `bearer`, `BEARER`) are accepted, and the
|
||||
// precheck tests both suffix spellings so an all-caps header line is not
|
||||
// skipped before the regex runs.
|
||||
{
|
||||
name: 'bearer',
|
||||
source: '((?:^|[^A-Za-z0-9_])[Bb](?:earer|EARER)\\s+)([A-Za-z0-9._~+/=-]{20,})',
|
||||
prebuilt: true,
|
||||
precheck: (line) => line.includes('earer') || line.includes('EARER'),
|
||||
},
|
||||
// Connection strings with inline credentials: the value is exactly the
|
||||
// scheme://user:pass@ span (an empty user is allowed — a redis URL whose
|
||||
// userinfo is just a colon and the password still fires),
|
||||
// so the host/db survive redaction for context. Database schemes only;
|
||||
// `https://user@host` never fires. Literal example spellings are avoided
|
||||
// in this comment on purpose (scripts/check-pg-url-redaction.sh).
|
||||
//
|
||||
// Both userinfo segments are BOUNDED (user 0-128, password 1-256). The
|
||||
// user segment stops at `:` and `/`; the password stops ONLY at whitespace,
|
||||
// `@` and the two string delimiters `"` `'`. Everything else is a legal
|
||||
// password character — every sub-delim (`!$&()*+,;=`), `:`, `%XX` escapes,
|
||||
// and the characters real (copy-pasted, unescaped) passwords carry: `/`
|
||||
// from base64, `{` `}` `<` `>` `|` `^` `\` and backtick. An earlier cut
|
||||
// excluded those on RFC 3986 grounds and let every such password through
|
||||
// unredacted, which is the wrong side of the trade for a redaction lane.
|
||||
// The cost is that `scheme://host:port/path@x` (an `@` inside a path) now
|
||||
// reads as a credential — a rare, harmless over-redaction.
|
||||
//
|
||||
// The old unbounded `[^\s@]+` ran to the end of the line and backtracked
|
||||
// once per scheme occurrence: quadratic on long @-free lines (a 250 KB
|
||||
// minified JSON line of credential-less redis URLs took ~4 s, 160 KB of
|
||||
// repeated `redis://:` ~5.6 s, 1 MB minutes). It ALSO turned a
|
||||
// credential-less URL followed within 256 chars by any `@` (an email in
|
||||
// the same minified JSON object) into a bogus finding, because the string
|
||||
// delimiters between them were legal password characters — excluding `"`
|
||||
// and `'` is what ends that run at the URL's closing quote; the LENGTH
|
||||
// bounds, not the exclusions, are the ReDoS fix. With the bounds the work
|
||||
// per scheme occurrence is a constant; the precheck skips the regex on
|
||||
// lines with no `@` at all. A password over 256 chars is the accepted miss
|
||||
// (a JWT that long is still claimed by `jwt` above).
|
||||
{
|
||||
name: 'db_url_credentials',
|
||||
source:
|
||||
'(?:postgres(?:ql)?|mysql|mongodb(?:\\+srv)?|redis|rediss|amqp|mssql):\\/\\/' +
|
||||
'[^\\s:/@"\']{0,128}:[^\\s@"\']{1,256}@',
|
||||
precheck: (line) => line.includes('@'),
|
||||
},
|
||||
// NOTE: private_key_pem is NOT here — a PEM key spans multiple lines and the
|
||||
// per-line scanner below cannot see the base64 body. It is matched over the
|
||||
// WHOLE text by PEM_BLOCK_RE (see scanPemBlocks) so redaction covers the
|
||||
@@ -111,12 +237,23 @@ const CORE_PATTERNS: ReadonlyArray<{ name: string; source: string }> = [
|
||||
* matching the whole span means the key body is scrubbed. The body+footer are
|
||||
* OPTIONAL so a lone/truncated header (a body-only leak, or a header with no
|
||||
* END) still fires the push-block gate — value is then just the header. The
|
||||
* lazy `[\s\S]*?` stops at the first END marker so two adjacent keys don't
|
||||
* collapse into one span. `-----BEGIN CERTIFICATE-----` never matches (the
|
||||
* literal `PRIVATE KEY` is required).
|
||||
* lazy body stops at the first END marker so two adjacent keys don't collapse
|
||||
* into one span. `-----BEGIN CERTIFICATE-----` never matches (the literal
|
||||
* `PRIVATE KEY` is required).
|
||||
*
|
||||
* The body is BOUNDED at 16384 chars (PEM_BODY_MAX_CHARS). The unbounded lazy
|
||||
* `[\s\S]*?` scanned from every header to the end of the text when no END
|
||||
* followed — quadratic on header-without-END texts (2000 header-only mentions
|
||||
* ahead of a 1 MB tail took ~4 s). With the bound a header does constant
|
||||
* work; a real key is far smaller (an RSA-4096 PEM is ~3.3 KB, RSA-16384
|
||||
* ~12.5 KB). A body longer than the bound degrades to the header-only match —
|
||||
* the gate still fires, the body is the accepted miss.
|
||||
*/
|
||||
export const PEM_BLOCK_RE =
|
||||
/-----BEGIN [A-Z ]*PRIVATE KEY-----(?:[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----)?/g;
|
||||
export const PEM_BODY_MAX_CHARS = 16384;
|
||||
export const PEM_BLOCK_RE = new RegExp(
|
||||
`-----BEGIN [A-Z ]*PRIVATE KEY-----(?:[\\s\\S]{0,${PEM_BODY_MAX_CHARS}}?-----END [A-Z ]*PRIVATE KEY-----)?`,
|
||||
'g',
|
||||
);
|
||||
|
||||
// Opt-in: `secret|token|password|api key`-shaped assignment whose value has
|
||||
// high Shannon entropy. Keyword-anchored (compiled inline below so the group
|
||||
@@ -137,12 +274,35 @@ export const PEM_BLOCK_RE =
|
||||
// matched — the value length was doing gating the entropy check is there to
|
||||
// do. Real passwords are frequently 12-16 characters; secrets that long with
|
||||
// 3.5 bits/char of entropy are not prose.
|
||||
//
|
||||
// The value must ALSO contain at least one digit. Identifier-shaped values
|
||||
// (`DefaultAzureCredential`, `/usr/local/bin/aws-vault`, an env-var NAME
|
||||
// assigned to an `apiKeyEnvVar`) clear the entropy gate on mixed case and
|
||||
// separators alone and were being redacted out of ordinary code. Real
|
||||
// machine-minted secrets essentially always carry digits; a digitless
|
||||
// passphrase is the accepted miss. A 40-hex git sha assigned to a `token:`
|
||||
// key still redacts (digits + entropy) — documented, acceptable.
|
||||
//
|
||||
// Both quantifiers after the keyword are BOUNDED. The trailing identifier
|
||||
// segments used to be `[A-Za-z0-9_-]*`: because the left boundary admits `-`
|
||||
// and `_` and that class contains them too, every `-`/`_` in a run like
|
||||
// `-apikey-apikey…` or `_token_token…` was a fresh keyword start whose
|
||||
// suffix ran to end-of-line and backtracked — quadratic (210 KB of
|
||||
// `-apikey` took ~35 s, 180 KB of `_token` ~15 s). At `{0,64}` a start does
|
||||
// constant work; no real credential key carries 64 identifier characters
|
||||
// after its keyword. The value is capped at 4096 for the same
|
||||
// constant-work-per-occurrence guarantee (the jwt segments share the cap):
|
||||
// a value longer than that is redacted only through its first 4096 chars —
|
||||
// the accepted miss, well above any real token or base64 key blob.
|
||||
const HIGH_ENTROPY_MIN_BITS_PER_CHAR = 3.5;
|
||||
const HIGH_ENTROPY_REQUIRES_DIGIT_RE = /[0-9]/;
|
||||
|
||||
function compilePatterns(opts: ScanOpts): CompiledPattern[] {
|
||||
const out: CompiledPattern[] = CORE_PATTERNS.map((p) => ({
|
||||
name: p.name,
|
||||
re: new RegExp(`(^|[^A-Za-z0-9_])(${p.source})`, 'g'),
|
||||
// nosemgrep: javascript.lang.security.audit.detect-non-literal-regexp.detect-non-literal-regexp -- p.source is a compile-time literal from CORE_PATTERNS (never caller input); every pattern uses bounded quantifiers, pinned by test/secret-scan-perf.test.ts
|
||||
re: new RegExp(p.prebuilt ? p.source : `(^|[^A-Za-z0-9_])(${p.source})`, 'g'),
|
||||
...(p.precheck ? { precheck: p.precheck } : {}),
|
||||
}));
|
||||
if (opts.highEntropy) {
|
||||
// Group layout matches the core shape: group 1 = boundary (empty here,
|
||||
@@ -151,7 +311,7 @@ function compilePatterns(opts: ScanOpts): CompiledPattern[] {
|
||||
out.push({
|
||||
name: 'high_entropy_assignment',
|
||||
re: new RegExp(
|
||||
`((?:^|[^A-Za-z0-9])(?:secret|token|passwd|password|passphrase|credential|api[_-]?key|apikey)[A-Za-z0-9_-]*["']?\\s*[:=]\\s*["']?)([A-Za-z0-9+/_=-]{12,})`,
|
||||
`((?:^|[^A-Za-z0-9])(?:secret|token|passwd|password|passphrase|credential|api[_-]?key|apikey)[A-Za-z0-9_-]{0,64}["']?\\s*[:=]\\s*["']?)([A-Za-z0-9+/_=-]{12,4096})`,
|
||||
'gi',
|
||||
),
|
||||
entropyGated: true,
|
||||
@@ -283,23 +443,59 @@ export function pathAllowlisted(relPath: string, allowlist: string[]): boolean {
|
||||
|
||||
// ── Scanning ────────────────────────────────────────────────────────────────
|
||||
|
||||
interface RawHit {
|
||||
/** One claimed span on a line: where `value` starts within the line text. */
|
||||
interface LineSpan {
|
||||
pattern: string;
|
||||
line: number; // 1-based
|
||||
value: string;
|
||||
start: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The claimed spans of one scanned line, shared BY REFERENCE between that
|
||||
* line's hits (appended to while the line is still being scanned), so
|
||||
* buildPreview can redact a hit's neighbours and snap its window to whole
|
||||
* spans.
|
||||
*/
|
||||
interface LineSpans {
|
||||
/** Discovery order (pattern-major). */
|
||||
all: LineSpan[];
|
||||
/** Lazily built by buildPreview: `all` sorted by `start`. */
|
||||
byStart?: LineSpan[];
|
||||
}
|
||||
|
||||
interface RawHit extends LineSpan {
|
||||
line: number; // 1-based
|
||||
/** Absolute offset of `value` within the scanned text (redactFindings splices on it). */
|
||||
abs: number;
|
||||
lineText: string;
|
||||
spans: LineSpans;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whole-text PEM private-key pass. Runs over the FULL text (not per-line) so
|
||||
* the base64 body between header and footer is part of the matched value and
|
||||
* therefore gets redacted, never left behind. `lineText` is set to the whole
|
||||
* matched block so buildPreview / redactSecretsInText replace the entire span
|
||||
* with `<REDACTED:private_key_pem>`.
|
||||
* matched block so buildPreview renders the entire span as one
|
||||
* `<REDACTED:private_key_pem>` token.
|
||||
*
|
||||
* The 1-based header line is counted INCREMENTALLY: the position of the NEXT
|
||||
* `\n` is carried as state across hits (global exec yields them in ascending
|
||||
* index order). Each `indexOf` resumes where the previous one stopped and a
|
||||
* -1 (no newline left in the text) is sticky, so the newline search touches
|
||||
* every character at most once and the pass is O(text) however the newlines
|
||||
* are distributed. Two earlier forms were O(hits × text): recomputing
|
||||
* `text.slice(0, m.index).split('\n')` per hit, and a cursor that re-ran
|
||||
* `text.indexOf('\n', cursor)` per hit — when no `\n` follows the cursor that
|
||||
* call rescans to the end of the text and returns -1 once PER HIT (20000
|
||||
* header mentions on one line ahead of an 8 MB newline-free tail took ~8 s;
|
||||
* ~30 s with a 23 MB tail, inside SCAN_MAX_FILE_BYTES). Pinned in
|
||||
* test/secret-scan-perf.test.ts.
|
||||
*/
|
||||
function scanPemBlocks(text: string): RawHit[] {
|
||||
const hits: RawHit[] = [];
|
||||
PEM_BLOCK_RE.lastIndex = 0;
|
||||
let line = 1;
|
||||
let nextNl = text.indexOf('\n');
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = PEM_BLOCK_RE.exec(text)) !== null) {
|
||||
const value = m[0];
|
||||
@@ -307,9 +503,12 @@ function scanPemBlocks(text: string): RawHit[] {
|
||||
PEM_BLOCK_RE.lastIndex++; // zero-width safety
|
||||
continue;
|
||||
}
|
||||
// 1-based line of the header start.
|
||||
const line = text.slice(0, m.index).split('\n').length;
|
||||
hits.push({ pattern: 'private_key_pem', line, value, lineText: value });
|
||||
while (nextNl !== -1 && nextNl < m.index) {
|
||||
line++;
|
||||
nextNl = text.indexOf('\n', nextNl + 1);
|
||||
}
|
||||
const span: LineSpan = { pattern: 'private_key_pem', value, start: 0 };
|
||||
hits.push({ ...span, line, abs: m.index, lineText: value, spans: { all: [span] } });
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
@@ -321,11 +520,43 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {
|
||||
// named patterns, so order is a belt-and-suspenders guarantee).
|
||||
const hits: RawHit[] = scanPemBlocks(text);
|
||||
const lines = text.split('\n');
|
||||
// No per-line length cap, deliberately: a secret on a 1 MB minified line
|
||||
// must still be found and redacted, so long lines are scanned in full.
|
||||
// What keeps that bounded is (a) every pattern doing constant work per
|
||||
// candidate occurrence — the shapes whose value class could otherwise run
|
||||
// to end-of-line and backtrack (db_url_credentials, jwt,
|
||||
// high_entropy_assignment, and PEM_BLOCK_RE over the whole text) carry
|
||||
// bounded quantifiers, and jwt's boundary excludes `-` so a `-` run is
|
||||
// never a fresh start — and (b) each catch-all's `precheck`, a substring
|
||||
// test that skips its regex on lines without the anchor. The overlap check
|
||||
// and the union split are O(value) per hit (claimed-char bitmap) and the
|
||||
// preview window is O(log hits) per hit (binary search over the sorted
|
||||
// spans), so a line with tens of thousands of hits costs O(hits × value),
|
||||
// not O(hits²) — and preview rendering is windowed (buildPreview), not
|
||||
// O(hits × line).
|
||||
//
|
||||
// `offset` is the absolute start of the current line (the `+ 1` is the
|
||||
// `\n` split away); each hit records `abs = offset + start` so
|
||||
// redactFindings can splice the text once instead of searching it per
|
||||
// value.
|
||||
let offset = 0;
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
if (!line || line.length < 8) continue;
|
||||
const claimed: Array<[number, number]> = [];
|
||||
const line = lines[i] ?? '';
|
||||
const lineStart = offset;
|
||||
offset += line.length + 1;
|
||||
if (line.length < 8) continue;
|
||||
const spans: LineSpans = { all: [] };
|
||||
// Claimed-character bitmap behind the first-wins dedupe: allocated on the
|
||||
// line's FIRST hit only (most lines have none), then O(value) to test and
|
||||
// to mark. Same answer as scanning every prior span for an intersection.
|
||||
let taken: Uint8Array | null = null;
|
||||
const claim = (pattern: string, value: string, start: number): void => {
|
||||
taken!.fill(1, start, start + value.length);
|
||||
spans.all.push({ pattern, value, start });
|
||||
hits.push({ pattern, value, start, abs: lineStart + start, line: i + 1, lineText: line, spans });
|
||||
};
|
||||
for (const p of patterns) {
|
||||
if (p.precheck && !p.precheck(line)) continue;
|
||||
p.re.lastIndex = 0;
|
||||
let m: RegExpExecArray | null;
|
||||
while ((m = p.re.exec(line)) !== null) {
|
||||
@@ -334,36 +565,129 @@ function scanInternal(text: string, opts: ScanOpts): RawHit[] {
|
||||
const end = start + value.length;
|
||||
// Zero-width safety: never loop forever on a pathological pattern.
|
||||
if (m[0].length === 0) p.re.lastIndex++;
|
||||
if (claimed.some(([s, e]) => start < e && end > s)) continue;
|
||||
// The entropy gate judges the WHOLE matched value (the rule fired on
|
||||
// the assignment's value), before any overlap split.
|
||||
if (p.entropyGated && !HIGH_ENTROPY_REQUIRES_DIGIT_RE.test(value)) continue;
|
||||
if (p.entropyGated && shannonEntropy(value) < HIGH_ENTROPY_MIN_BITS_PER_CHAR) continue;
|
||||
claimed.push([start, end]);
|
||||
hits.push({ pattern: p.name, line: i + 1, value, lineText: line });
|
||||
if (!taken) {
|
||||
taken = new Uint8Array(line.length);
|
||||
} else if (anyTaken(taken, start, end)) {
|
||||
// UNION COVERAGE. An earlier pattern already claimed part of this
|
||||
// span. Attribution stays first-wins — a FULLY covered span is
|
||||
// skipped, so `Bearer <vendor key>` reports the vendor only — but
|
||||
// every still-unclaimed sub-range of the later span is claimed as
|
||||
// a hit of the later pattern (value = that slice), so nothing a
|
||||
// pattern matched is ever left in the output. Discarding the whole
|
||||
// later span shipped the entire PASSWORD of a database URL whose
|
||||
// username happened to be a vendor-shaped id (the id was claimed,
|
||||
// the surrounding `db_url_credentials` span was dropped).
|
||||
for (let a = start, k = start; k <= end; k++) {
|
||||
if (k < end && !taken[k]) continue;
|
||||
if (a < k) claim(p.name, line.slice(a, k), a);
|
||||
a = k + 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
claim(p.name, value, start);
|
||||
}
|
||||
}
|
||||
}
|
||||
return hits;
|
||||
}
|
||||
|
||||
const PREVIEW_MAX_CHARS = 160;
|
||||
|
||||
function buildPreview(lineText: string, value: string, patternName: string): string {
|
||||
// ENG-9: render through redactSecretsInText for the canonical
|
||||
// `<REDACTED:name>` token — the value never survives into the preview.
|
||||
const redacted = redactSecretsInText(lineText, new Map([[patternName, value]])).trim();
|
||||
if (redacted.length <= PREVIEW_MAX_CHARS) return redacted;
|
||||
const at = redacted.indexOf(`<REDACTED:${patternName}>`);
|
||||
const start = Math.max(0, at - 40);
|
||||
return (start > 0 ? '…' : '') + redacted.slice(start, start + PREVIEW_MAX_CHARS) + '…';
|
||||
/** True when any character in [start, end) is already claimed. */
|
||||
function anyTaken(taken: Uint8Array, start: number, end: number): boolean {
|
||||
for (let k = start; k < end; k++) if (taken[k]) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
function toFinding(hit: RawHit, file?: string): SecretFinding {
|
||||
const fullHex = createHash('sha256').update(hit.value).digest('hex');
|
||||
const PREVIEW_MAX_CHARS = 160;
|
||||
/** Raw context kept before / after the hit when the line is longer than the preview. */
|
||||
const PREVIEW_CONTEXT_BEFORE = 40;
|
||||
const PREVIEW_CONTEXT_AFTER = 80;
|
||||
|
||||
/**
|
||||
* Render the finding preview. ENG-9: every claimed span becomes the one
|
||||
* canonical `<REDACTED:name>` token — a value never survives into a preview.
|
||||
*
|
||||
* Only a WINDOW around the hit is rendered, never the whole line: a
|
||||
* minified/bundled line can run to hundreds of KB, and redacting the full
|
||||
* line once per hit was O(hits × line) (5000 tokens on one 190 KB line took
|
||||
* ~2.6 s; 41 ms one-per-line). Lines that fit the preview are rendered whole,
|
||||
* so the short-line output is unchanged.
|
||||
*
|
||||
* Two leak guards on the window: (1) EVERY claimed span on the line that
|
||||
* falls inside it is redacted — by POSITION (spans are disjoint and sorted,
|
||||
* so each is spliced at its own offset; a union-coverage slice or a value
|
||||
* that is a substring of its neighbour needs no replace ordering), so a
|
||||
* preview never carries a sibling secret from the same line; (2) the
|
||||
* window's edges snap OUTWARD to the boundary of any span they would cut
|
||||
* through, so a neighbouring occurrence is redacted whole instead of leaving
|
||||
* a fragment at the edge. Ellipses mark whichever edges were cut.
|
||||
*/
|
||||
function buildPreview(hit: RawHit): string {
|
||||
const { lineText, value, start, pattern } = hit;
|
||||
const end = start + value.length;
|
||||
let winStart = 0;
|
||||
let winEnd = lineText.length;
|
||||
if (lineText.length > PREVIEW_MAX_CHARS) {
|
||||
winStart = Math.max(0, start - PREVIEW_CONTEXT_BEFORE);
|
||||
winEnd = Math.min(lineText.length, end + PREVIEW_CONTEXT_AFTER);
|
||||
}
|
||||
// Spans never overlap each other (claimed-span dedupe), so sorted by start
|
||||
// they are sorted by end too: binary-search the first span ending after
|
||||
// winStart, walk while spans begin before winEnd. Snapping an edge to a
|
||||
// span boundary cannot pull a further span into the window — one pass.
|
||||
const byStart = (hit.spans.byStart ??= [...hit.spans.all].sort((a, b) => a.start - b.start));
|
||||
let lo = 0;
|
||||
let hi = byStart.length;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
const sp = byStart[mid]!;
|
||||
if (sp.start + sp.value.length <= winStart) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
const inWindow: LineSpan[] = [];
|
||||
for (let i = lo; i < byStart.length; i++) {
|
||||
const span = byStart[i]!;
|
||||
if (span.start >= winEnd) break;
|
||||
const e = span.start + span.value.length;
|
||||
if (span.start < winStart) winStart = span.start;
|
||||
if (e > winEnd) winEnd = e;
|
||||
inWindow.push(span);
|
||||
}
|
||||
const pieces: string[] = [];
|
||||
let at = winStart;
|
||||
for (const span of inWindow) {
|
||||
pieces.push(lineText.slice(at, span.start), `<REDACTED:${span.pattern}>`);
|
||||
at = span.start + span.value.length;
|
||||
}
|
||||
pieces.push(lineText.slice(at, winEnd));
|
||||
let redacted = pieces.join('').trim();
|
||||
let cutLeft = winStart > 0;
|
||||
let cutRight = winEnd < lineText.length;
|
||||
if (redacted.length > PREVIEW_MAX_CHARS) {
|
||||
const at = Math.max(0, redacted.indexOf(`<REDACTED:${pattern}>`));
|
||||
const from = Math.max(0, at - PREVIEW_CONTEXT_BEFORE);
|
||||
const to = Math.min(redacted.length, from + PREVIEW_MAX_CHARS);
|
||||
cutLeft ||= from > 0;
|
||||
cutRight ||= to < redacted.length;
|
||||
redacted = redacted.slice(from, to);
|
||||
}
|
||||
return `${cutLeft ? '…' : ''}${redacted}${cutRight ? '…' : ''}`;
|
||||
}
|
||||
|
||||
function sha256Hex(value: string): string {
|
||||
return createHash('sha256').update(value).digest('hex');
|
||||
}
|
||||
|
||||
/** `file` is stamped by scanFiles on the way out, not here. */
|
||||
function toFinding(hit: RawHit, fullHex: string): SecretFinding {
|
||||
return {
|
||||
pattern: hit.pattern,
|
||||
line: hit.line,
|
||||
redactedPreview: buildPreview(hit.lineText, hit.value, hit.pattern),
|
||||
redactedPreview: buildPreview(hit),
|
||||
fingerprint: `sha256:${fullHex.slice(0, 16)}`,
|
||||
...(file !== undefined ? { file } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -376,9 +700,9 @@ export function scanText(text: string, opts: ScanOpts = {}): SecretFinding[] {
|
||||
const allowlist = opts.allowlist ?? [];
|
||||
const out: SecretFinding[] = [];
|
||||
for (const hit of scanInternal(text, opts)) {
|
||||
const fullHex = createHash('sha256').update(hit.value).digest('hex');
|
||||
const fullHex = sha256Hex(hit.value);
|
||||
if (valueAllowlisted(fullHex, allowlist)) continue;
|
||||
out.push(toFinding(hit));
|
||||
out.push(toFinding(hit, fullHex));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
@@ -439,28 +763,264 @@ export function scanFiles(paths: string[], opts: ScanOpts = {}): SecretFinding[]
|
||||
return out;
|
||||
}
|
||||
|
||||
// ── Corpus-write redaction ──────────────────────────────────────────────────
|
||||
//
|
||||
// [S3#2] `redactFindings` replaces every CLAIMED span in place with
|
||||
// `<REDACTED:pattern>` and reports what was redacted. Allowlisted values are
|
||||
// left intact — the user declared them safe. The output is rebuilt by
|
||||
// SPAN-SPLICE, O(text + hits): every hit carries its absolute offset from
|
||||
// scanInternal, the spans are sorted by offset, and the text between
|
||||
// consecutive spans is copied through once. (The previous implementation ran
|
||||
// one full-text `replaceAll` per unique (pattern, value) pair — O(unique
|
||||
// values × text): a 1 MB transcript with ~5k unique high-entropy values took
|
||||
// ~3-5 s to redact after a ~70 ms scan.)
|
||||
//
|
||||
// `redactions` is one finding per CLAIMED span, in scan order (PEM blocks,
|
||||
// then line order). A span the union-coverage rule split around an earlier
|
||||
// claim contributes one record per uncovered slice; an echo (below) adds no
|
||||
// record — it is not a claim.
|
||||
//
|
||||
// SEMANTIC DELTA from the replaceAll form (deliberate): the splice redacts
|
||||
// exactly the claimed spans, so for every pattern OUTSIDE the echo pass
|
||||
// `redactFindings(text).text` agrees byte-for-byte with what `scanText(text)`
|
||||
// reports — a claimed value's bytes at a position the scanner did not claim
|
||||
// (embedded past its left boundary inside a longer identifier) are left
|
||||
// as-is, and the corpus write and the push gate see the same findings.
|
||||
// Vendor-prefixed values lose nothing by staying outside the echo pass: they
|
||||
// re-match on their own wherever they recur.
|
||||
//
|
||||
// THE ECHO PASS. A `bearer` token is claimed only where its `Bearer ` keyword
|
||||
// anchors it and a `high_entropy_assignment` value only where its keyword
|
||||
// does, yet transcripts routinely echo the same value bare (`Authorization:
|
||||
// Bearer <tok>` in a tool call, then `<tok>` alone in the reply; a pasted
|
||||
// `PASSWORD=<v>` line, then `<v>` in prose). So the values those two patterns
|
||||
// claim form an ECHO DICTIONARY (value → pattern) and every remaining
|
||||
// occurrence — bare, or embedded inside a longer identifier — is redacted as
|
||||
// that pattern's token too. Three bounds keep the pass cheap and
|
||||
// collision-safe: a value must clear its pattern's floor
|
||||
// (ECHO_MIN_CHARS_BEARER = 20, ECHO_MIN_CHARS_ENTROPY = 12 — the rules' own
|
||||
// floors, restated so a pattern edit alone can never widen the pass to
|
||||
// short, collision-prone values), must be at most ECHO_MAX_VALUE_CHARS long,
|
||||
// and only the first ECHO_MAX_UNIQUE unique values in claim order — ONE cap
|
||||
// across both patterns — join. A value past either cap is still redacted at
|
||||
// its claimed span; only its echoes are the accepted miss.
|
||||
//
|
||||
// The pass is a streaming merge over the ORIGINAL text: per value, the
|
||||
// position of its next occurrence at or beyond the emit cursor (found by
|
||||
// `indexOf` resuming at the cursor); at each step the leftmost-longest
|
||||
// occurrence that fits inside the current UNCLAIMED GAP is emitted and the
|
||||
// cursor advances. Retained state is O(values) however long the text is —
|
||||
// occurrences are never collected into a list, which on a repetitive tail
|
||||
// (2 MiB of `A` against 64 claimed values of 20–83 `A`s) meant ~3 M candidate
|
||||
// objects and ~230 MB of RSS for 64 findings, ahead of message truncation.
|
||||
// Two earlier forms were also wrong on time: one `replaceAll` per unique
|
||||
// value was O(unique × text) (why the count cap exists), and a single
|
||||
// escaped-alternation RegExp was O(text × Σ|values|) on prefix-sharing
|
||||
// values — 64 claimed bearer values of 4 KB sharing a 4000-char prefix ahead
|
||||
// of a 1 MB tail of the prefix character took ~24 s (the bearer class is
|
||||
// unbounded, so an attacker-influenced page can plant them); the per-value
|
||||
// substring seeks take milliseconds on the same input, and the value-length
|
||||
// cap bounds each compare. Matching only ever runs over the original text,
|
||||
// never over emitted `<REDACTED:…>` tokens: a claimed bearer value that
|
||||
// spells a pattern name (`high_entropy_assignment` is 23 bearer-class
|
||||
// characters) used to turn a sibling token into `<REDACTED:<REDACTED:bearer>>`
|
||||
// when the pass ran over the spliced output.
|
||||
//
|
||||
// SESSION-WIDE DICTIONARY. A multi-field document (a transcript session:
|
||||
// message bodies, speaker labels, title, metadata values) must scrub an echo
|
||||
// in one field of a value claimed in ANOTHER. `planRedaction` scans one
|
||||
// field and adds its eligible values to a caller-supplied shared map under
|
||||
// the same floors and the same single cap; `applyRedaction` splices later and
|
||||
// reads the map as it stands THEN — so a caller plans every field first and
|
||||
// applies afterwards, and a value claimed in the last field is scrubbed from
|
||||
// the first. `redactFindings` is the one-shot composition for a single text.
|
||||
|
||||
/**
|
||||
* Corpus-write mode [S3#2]: replace every matched span in place with
|
||||
* `<REDACTED:pattern>` (via redactSecretsInText) and report what was
|
||||
* redacted. Allowlisted values are left intact — the user declared them
|
||||
* safe. Returns the redacted text plus one finding per original occurrence.
|
||||
* Floor for a `bearer` value to take part in the echo pass. The `bearer`
|
||||
* pattern's own class is `{20,}`, so every claimed value already clears it.
|
||||
*/
|
||||
export const ECHO_MIN_CHARS_BEARER = 20;
|
||||
|
||||
/**
|
||||
* Floor for a `high_entropy_assignment` value to take part in the echo pass —
|
||||
* the rule's own value floor (`{12,4096}`), restated.
|
||||
*/
|
||||
export const ECHO_MIN_CHARS_ENTROPY = 12;
|
||||
|
||||
/**
|
||||
* A claimed value longer than this is redacted at its claimed span but does
|
||||
* not join the echo dictionary. Bounds the per-candidate compare of the
|
||||
* substring sweeps; no real bearer token or assignment value is this long,
|
||||
* and an echo of one is the documented, accepted miss.
|
||||
*/
|
||||
export const ECHO_MAX_VALUE_CHARS = 512;
|
||||
|
||||
/**
|
||||
* Cap on the unique values (bearer + high_entropy_assignment together, claim
|
||||
* order, first N) the echo pass will look for. Keeps the pass a bounded
|
||||
* number of linear sweeps; an echo of a value past the cap is the
|
||||
* documented, accepted miss.
|
||||
*/
|
||||
export const ECHO_MAX_UNIQUE = 64;
|
||||
|
||||
/** Echo dictionary: claimed value → the pattern that claimed it first. */
|
||||
export type EchoDictionary = Map<string, string>;
|
||||
|
||||
export interface RedactOpts extends ScanOpts {
|
||||
/**
|
||||
* Shared echo dictionary. `planRedaction` ADDS the eligible values it
|
||||
* claims (shared floors, one cap, claim order); `applyRedaction` reads the
|
||||
* map at apply time. Pass one map across every field of a document for
|
||||
* session-wide echo coverage. Default: a fresh map per `planRedaction`.
|
||||
*/
|
||||
echoValues?: EchoDictionary;
|
||||
}
|
||||
|
||||
/** The scan half of a redaction: what `applyRedaction` splices. */
|
||||
export interface RedactionPlan {
|
||||
/** One finding per claimed span, scan order — the receipt count. */
|
||||
redactions: SecretFinding[];
|
||||
/** The echo dictionary this plan fed (the caller's map when one was given). */
|
||||
echoValues: EchoDictionary;
|
||||
/** The original text (splice input). */
|
||||
text: string;
|
||||
/** Claimed spans, sorted by absolute offset. */
|
||||
claimed: Array<{ abs: number; end: number; pattern: string }>;
|
||||
}
|
||||
|
||||
function addEchoValue(into: EchoDictionary, pattern: string, value: string): void {
|
||||
const floor =
|
||||
pattern === 'bearer'
|
||||
? ECHO_MIN_CHARS_BEARER
|
||||
: pattern === 'high_entropy_assignment'
|
||||
? ECHO_MIN_CHARS_ENTROPY
|
||||
: Infinity;
|
||||
if (value.length < floor || value.length > ECHO_MAX_VALUE_CHARS) return;
|
||||
if (into.has(value) || into.size >= ECHO_MAX_UNIQUE) return;
|
||||
into.set(value, pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scan `text` for redaction: findings (allowlist applied), the claimed spans
|
||||
* to splice, and the eligible echo values added to `opts.echoValues` (or a
|
||||
* fresh map). Pure with respect to `text`; the only side effect is feeding
|
||||
* the shared dictionary.
|
||||
*/
|
||||
export function planRedaction(text: string, opts: RedactOpts = {}): RedactionPlan {
|
||||
const allowlist = opts.allowlist ?? [];
|
||||
const echoValues = opts.echoValues ?? new Map<string, string>();
|
||||
const redactions: SecretFinding[] = [];
|
||||
const claimed: RedactionPlan['claimed'] = [];
|
||||
for (const hit of scanInternal(text, opts)) {
|
||||
const fullHex = sha256Hex(hit.value);
|
||||
if (valueAllowlisted(fullHex, allowlist)) continue;
|
||||
redactions.push(toFinding(hit, fullHex));
|
||||
claimed.push({ abs: hit.abs, end: hit.abs + hit.value.length, pattern: hit.pattern });
|
||||
addEchoValue(echoValues, hit.pattern, hit.value);
|
||||
}
|
||||
claimed.sort((a, b) => a.abs - b.abs);
|
||||
return { redactions, echoValues, text, claimed };
|
||||
}
|
||||
|
||||
/**
|
||||
* Echo-sweep state for one `applyRedaction` call: the dictionary values
|
||||
* longest-first (a tie at one position resolves to the longest, so a value
|
||||
* that is a prefix of another never cuts the longer echo short) and, per
|
||||
* value, the position of its next occurrence at or beyond the emit cursor
|
||||
* (-1 once exhausted). Occurrences are discovered LAZILY as the cursor
|
||||
* advances and are never materialized as a list: a repetitive tail (2 MiB of
|
||||
* `A` against 64 claimed values of 20–83 `A`s) has O(text × Σ 1/|value|)
|
||||
* non-overlapping occurrences — ~3 M candidate objects, ~230 MB of RSS for
|
||||
* 64 findings when they were collected up front — while this state is
|
||||
* O(values) however long the text is. Each value's `indexOf` resumes at the
|
||||
* cursor and is re-sought only once the cursor has passed its cached
|
||||
* position, so the whole sweep stays O(values × text).
|
||||
*/
|
||||
interface EchoSweep {
|
||||
values: string[];
|
||||
tokens: string[];
|
||||
next: Int32Array;
|
||||
}
|
||||
|
||||
function startEchoSweep(text: string, dict: EchoDictionary): EchoSweep {
|
||||
const entries = [...dict].sort((a, b) => b[0].length - a[0].length);
|
||||
const values = entries.map((e) => e[0]);
|
||||
const tokens = entries.map((e) => `<REDACTED:${e[1]}>`);
|
||||
const next = new Int32Array(values.length);
|
||||
for (let k = 0; k < values.length; k++) next[k] = text.indexOf(values[k]!);
|
||||
return { values, tokens, next };
|
||||
}
|
||||
|
||||
/**
|
||||
* Splice a plan: `<REDACTED:pattern>` over every claimed span, and over every
|
||||
* echo-dictionary occurrence that lies ENTIRELY inside an unclaimed gap,
|
||||
* leftmost-longest. The dictionary is read now, not at plan time — a caller
|
||||
* that planned several fields into one map gets every field's values here.
|
||||
* Output is emitted incrementally as the cursor advances; nothing but the
|
||||
* output parts and the O(values) sweep state is retained.
|
||||
*/
|
||||
export function applyRedaction(plan: RedactionPlan): string {
|
||||
const { text, claimed, echoValues } = plan;
|
||||
if (claimed.length === 0 && echoValues.size === 0) return text;
|
||||
const sweep = echoValues.size > 0 ? startEchoSweep(text, echoValues) : null;
|
||||
const parts: string[] = [];
|
||||
// Copy text[from, to) through, splicing the echo occurrences inside it. At
|
||||
// each step the leftmost (then longest) occurrence at or beyond the cursor
|
||||
// that fits before `to` is emitted; one that runs into the claimed span
|
||||
// ahead is left alone and re-sought past that span — matching never
|
||||
// touches an emitted token.
|
||||
const emitGap = (from: number, to: number): void => {
|
||||
let at = from;
|
||||
if (sweep) {
|
||||
const { values, tokens, next } = sweep;
|
||||
while (at < to) {
|
||||
let best = -1;
|
||||
let bestPos = to;
|
||||
for (let k = 0; k < values.length; k++) {
|
||||
let p = next[k]!;
|
||||
if (p === -1) continue;
|
||||
if (p < at) {
|
||||
p = text.indexOf(values[k]!, at);
|
||||
next[k] = p;
|
||||
if (p === -1) continue;
|
||||
}
|
||||
if (p >= bestPos || p + values[k]!.length > to) continue;
|
||||
best = k;
|
||||
bestPos = p;
|
||||
}
|
||||
if (best === -1) break;
|
||||
if (bestPos > at) parts.push(text.slice(at, bestPos));
|
||||
parts.push(tokens[best]!);
|
||||
at = bestPos + values[best]!.length;
|
||||
}
|
||||
}
|
||||
if (at < to) parts.push(text.slice(at, to));
|
||||
};
|
||||
let cur = 0;
|
||||
for (const c of claimed) {
|
||||
if (c.end <= cur) continue; // fully inside an already-emitted span
|
||||
if (c.abs > cur) emitGap(cur, c.abs);
|
||||
// Per-line spans are disjoint by construction; one can only overlap a
|
||||
// whole-text PEM block (a bearer value whose class admits `-` running
|
||||
// into the block's `-----BEGIN`). The uncovered tail of the later span is
|
||||
// emitted as its own token rather than skipped, so nothing claimed is
|
||||
// ever left in the output.
|
||||
parts.push(`<REDACTED:${c.pattern}>`);
|
||||
cur = c.end;
|
||||
}
|
||||
emitGap(cur, text.length);
|
||||
return parts.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* Corpus-write mode [S3#2] for a single text: plan + apply. Returns the
|
||||
* redacted text, one finding per claimed span, and the echo dictionary the
|
||||
* call collected (see the section comment above for every bound).
|
||||
*/
|
||||
export function redactFindings(
|
||||
text: string,
|
||||
opts: ScanOpts = {},
|
||||
): { text: string; redactions: SecretFinding[] } {
|
||||
const allowlist = opts.allowlist ?? [];
|
||||
const redactions: SecretFinding[] = [];
|
||||
const seen = new Set<string>(); // pattern\0value pairs already replaced
|
||||
let out = text;
|
||||
for (const hit of scanInternal(text, opts)) {
|
||||
const fullHex = createHash('sha256').update(hit.value).digest('hex');
|
||||
if (valueAllowlisted(fullHex, allowlist)) continue;
|
||||
redactions.push(toFinding(hit));
|
||||
const key = `${hit.pattern}\0${hit.value}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
out = redactSecretsInText(out, new Map([[hit.pattern, hit.value]]));
|
||||
}
|
||||
return { text: out, redactions };
|
||||
opts: RedactOpts = {},
|
||||
): { text: string; redactions: SecretFinding[]; echoValues: EchoDictionary } {
|
||||
const plan = planRedaction(text, opts);
|
||||
return { text: applyRedaction(plan), redactions: plan.redactions, echoValues: plan.echoValues };
|
||||
}
|
||||
|
||||
@@ -29,6 +29,7 @@
|
||||
|
||||
import type { BrainEngine } from '../engine.ts';
|
||||
import { importFromContent } from '../import-file.ts';
|
||||
import { canonicalJson } from '../remediation-step.ts';
|
||||
import type { TranscriptAdapter, TranscriptFormat } from './types.ts';
|
||||
import { detectAdapter } from './detect.ts';
|
||||
import {
|
||||
@@ -342,12 +343,24 @@ export async function runTranscriptsIngest(
|
||||
// write so healthy re-runs stay write-free.
|
||||
let needsRaw = true;
|
||||
if (allSkipped) {
|
||||
// Active rows only: `allSkipped` means the import hash check
|
||||
// (which reads ACTIVE rows) just matched every page, so the
|
||||
// base page is alive here by construction — a tombstoned
|
||||
// page never reaches this branch (it reads as missing and is
|
||||
// re-imported, see the "resurrects the page" e2e). No
|
||||
// includeDeleted flag: the probe must never read through a
|
||||
// soft-delete the hash check did not.
|
||||
const existing = await engine.getRawData(resolvedBaseSlug, rawSource, {
|
||||
sourceId: opts.sourceId,
|
||||
});
|
||||
// Key-order-insensitive compare: JSONB hands keys back in
|
||||
// its own canonical order, so a plain JSON.stringify never
|
||||
// matched the freshly built object and every healthy re-run
|
||||
// rewrote the row.
|
||||
needsRaw =
|
||||
existing.length === 0 ||
|
||||
JSON.stringify(existing[0].data) !== JSON.stringify(redacted.session.meta.raw);
|
||||
canonicalJson(existing[0].data) !==
|
||||
canonicalJson(JSON.parse(JSON.stringify(redacted.session.meta.raw)));
|
||||
}
|
||||
if (needsRaw) {
|
||||
await engine.putRawData(resolvedBaseSlug, rawSource, redacted.session.meta.raw, {
|
||||
|
||||
@@ -31,7 +31,7 @@ import { safeDump } from 'js-yaml';
|
||||
import { homedir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { DEFAULT_BYTES_BLOCK } from '../content-sanity.ts';
|
||||
import { redactFindings } from '../secret-scan.ts';
|
||||
import { applyRedaction, planRedaction, type EchoDictionary, type RedactionPlan } from '../secret-scan.ts';
|
||||
import { loadPatterns } from '../skillpack/harvest-lint.ts';
|
||||
import { sanitizeForJsonb } from '../batch-rows.ts';
|
||||
import { ensureWellFormed, truncateUtf8 } from '../text-safe.ts';
|
||||
@@ -113,6 +113,30 @@ export function loadImportRedactionPatterns(userPatternsPath?: string): ImportRe
|
||||
* persisted (message text, SPEAKER labels, title, raw-meta string fields).
|
||||
* Throws on scanner or pattern failure — page writes are FAIL-CLOSED (unlike
|
||||
* the hook corpus lane, these pages are searchable and synced).
|
||||
*
|
||||
* Detector classes (all from `secret-scan.ts`, format-based — not just vendor
|
||||
* prefixes): vendor key shapes (anthropic/openai/voyage/github/gitlab/slack/
|
||||
* aws/google/stripe/sendgrid/twilio/supabase/npm/huggingface/gbrain), JWTs,
|
||||
* whole-block PEM private keys, `Bearer <token>` headers, connection strings
|
||||
* carrying inline credentials, and — opted in for THIS lane — the
|
||||
* high-entropy `KEY=`/`TOKEN=`/`PASSWORD=` assignment heuristic (value must
|
||||
* carry a digit and clear the entropy gate). Transcripts are the corpus where
|
||||
* a pasted `.env` line is most likely, so recall wins over the false-positive
|
||||
* cost here; the push gate and compiled-context scan keep the heuristic off.
|
||||
* Every match becomes `<REDACTED:pattern>`; user patterns become
|
||||
* `<REDACTED:user-pattern>`.
|
||||
*
|
||||
* TWO PHASES, ONE SESSION-WIDE ECHO DICTIONARY. Phase 1 PLANS every persisted
|
||||
* field (scan + claimed spans); the eligible bearer / high-entropy values
|
||||
* every field claims accumulate in one `echoValues` map under the scanner's
|
||||
* shared floors and single cap. Phase 2 APPLIES each plan, and the splice
|
||||
* reads the FULL map — so a token claimed in a tool message's
|
||||
* `Authorization: Bearer …` header is also scrubbed where the assistant
|
||||
* echoed it bare in ANOTHER message (or the title, a speaker label, a
|
||||
* metadata value), whichever order the two appear in. Redacting each field
|
||||
* independently left those cross-field echoes in the page. The per-field
|
||||
* `redactions` that feed `redactionCount` (the receipt) are unchanged by the
|
||||
* echo pass: an echo is not a claim and adds no finding.
|
||||
*/
|
||||
export function redactSession(
|
||||
session: ParsedSession,
|
||||
@@ -121,15 +145,19 @@ export function redactSession(
|
||||
const patterns = opts.patterns ?? loadImportRedactionPatterns(opts.userPatternsPath);
|
||||
let redactionCount = 0;
|
||||
let imperativesFlagged = 0;
|
||||
const echoValues: EchoDictionary = new Map();
|
||||
|
||||
const clean = (text: string): string => {
|
||||
const plan = (text: string): RedactionPlan =>
|
||||
// sanitizeForJsonb (NUL-strip + well-form): transcripts capture raw tool
|
||||
// output that legitimately carries U+0000, which Postgres text/jsonb
|
||||
// reject at the write boundary (#4392).
|
||||
let out = sanitizeForJsonb(text);
|
||||
const r = redactFindings(out);
|
||||
redactionCount += r.redactions.length;
|
||||
out = r.text;
|
||||
// highEntropy: transcripts opt into the assignment heuristic (see doc
|
||||
// comment above) — the shared scanner keeps it off by default.
|
||||
planRedaction(sanitizeForJsonb(text), { highEntropy: true, echoValues });
|
||||
|
||||
const apply = (p: RedactionPlan): string => {
|
||||
redactionCount += p.redactions.length;
|
||||
let out = applyRedaction(p);
|
||||
for (const { regex } of patterns) {
|
||||
out = out.replace(regex, () => {
|
||||
redactionCount++;
|
||||
@@ -139,7 +167,8 @@ export function redactSession(
|
||||
return out;
|
||||
};
|
||||
|
||||
const messages = session.messages.map((m) => {
|
||||
// Phase 1: plan every field.
|
||||
const planned = session.messages.map((m) => {
|
||||
for (const re of IMPERATIVE_RES) {
|
||||
if (re.test(m.text)) {
|
||||
imperativesFlagged++;
|
||||
@@ -149,25 +178,34 @@ export function redactSession(
|
||||
// Speaker labels are persisted into the anchor line, so they get the
|
||||
// same redaction as bodies (a secret or private name in a display name
|
||||
// must not bypass the scan).
|
||||
return {
|
||||
...m,
|
||||
text: clean(m.text),
|
||||
...(m.speaker ? { speaker: clean(m.speaker) } : {}),
|
||||
};
|
||||
return { m, text: plan(m.text), speaker: m.speaker ? plan(m.speaker) : undefined };
|
||||
});
|
||||
|
||||
const meta = { ...session.meta };
|
||||
if (meta.title) meta.title = clean(meta.title);
|
||||
if (meta.raw) {
|
||||
// Flatness is ENFORCED, not assumed: strings are cleaned; primitive
|
||||
// scalars pass; anything nested (arrays/objects an adapter let through
|
||||
// from hostile export data) is DROPPED — it would reach putRawData
|
||||
// unscanned otherwise.
|
||||
const raw: Record<string, unknown> = {};
|
||||
for (const [k, v] of Object.entries(meta.raw)) {
|
||||
if (typeof v === 'string') raw[k] = clean(v);
|
||||
else if (v === null || typeof v === 'number' || typeof v === 'boolean') raw[k] = v;
|
||||
const titlePlan = session.meta.title ? plan(session.meta.title) : undefined;
|
||||
// Flatness is ENFORCED, not assumed: strings are planned; primitive
|
||||
// scalars pass; anything nested (arrays/objects an adapter let through
|
||||
// from hostile export data) is DROPPED — it would reach putRawData
|
||||
// unscanned otherwise.
|
||||
const rawEntries: Array<{ key: string; plan: RedactionPlan | null; scalar: unknown }> = [];
|
||||
if (session.meta.raw) {
|
||||
for (const [key, v] of Object.entries(session.meta.raw)) {
|
||||
if (typeof v === 'string') rawEntries.push({ key, plan: plan(v), scalar: undefined });
|
||||
else if (v === null || typeof v === 'number' || typeof v === 'boolean') {
|
||||
rawEntries.push({ key, plan: null, scalar: v });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Phase 2: apply with the complete dictionary.
|
||||
const messages = planned.map(({ m, text, speaker }) => ({
|
||||
...m,
|
||||
text: apply(text),
|
||||
...(speaker ? { speaker: apply(speaker) } : {}),
|
||||
}));
|
||||
const meta = { ...session.meta };
|
||||
if (titlePlan) meta.title = apply(titlePlan);
|
||||
if (meta.raw) {
|
||||
const raw: Record<string, unknown> = {};
|
||||
for (const e of rawEntries) raw[e.key] = e.plan ? apply(e.plan) : e.scalar;
|
||||
meta.raw = raw;
|
||||
}
|
||||
|
||||
|
||||
@@ -282,6 +282,13 @@ function scannerSourcePath(scanRoot: string, filePath: string): string {
|
||||
* A NULL `source_path` means the page was born via put/capture and has no
|
||||
* file of record yet — the slug-derived path stays correct for those.
|
||||
*
|
||||
* `opts.includeDeleted`: resolve from a soft-deleted row too. The default
|
||||
* reads ACTIVE rows only (a tombstone must not steer a live write), but the
|
||||
* purge remediation path in `delete_page` retries the artifact removal for a
|
||||
* TOMBSTONE — whose recorded `source_path` the active-row read would miss,
|
||||
* falling back to the slug-derived twin and reporting a clean
|
||||
* `file_not_present` while the real file survives for sync to resurrect.
|
||||
*
|
||||
* Shared by `writePageThrough` AND the facts fence writer (#4204): the fence
|
||||
* appends to the page's file, so both writers MUST compute the identical
|
||||
* path or the fence lands in a file sync never reads back and the next
|
||||
@@ -291,6 +298,7 @@ export async function resolvePageWriteTarget(
|
||||
engine: BrainEngine,
|
||||
slug: string,
|
||||
sourceId: string,
|
||||
opts: { includeDeleted?: boolean } = {},
|
||||
): Promise<PageWriteTarget> {
|
||||
let filePath: string;
|
||||
let writeRoot: string;
|
||||
@@ -307,7 +315,7 @@ export async function resolvePageWriteTarget(
|
||||
const sourceLocalPath = rawLocalPath ? msysToNativePath(rawLocalPath) : null;
|
||||
|
||||
const pathRows = await engine.executeRaw<{ source_path: string | null; source_uri: string | null }>(
|
||||
`SELECT source_path, source_uri FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL LIMIT 1`,
|
||||
`SELECT source_path, source_uri FROM pages WHERE source_id = $1 AND slug = $2${opts.includeDeleted ? '' : ' AND deleted_at IS NULL'} LIMIT 1`,
|
||||
[sourceId, slug],
|
||||
);
|
||||
const recordedPath = sanitizeRecordedSourcePath(pathRows[0]?.source_path);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# gbrain agent workspace — template
|
||||
|
||||
<!-- gbrain-template-stamp: 0.50.4.0 -->
|
||||
<!-- gbrain-template-stamp: 0.50.5.0 -->
|
||||
|
||||
This repository is the **"Use this template"** distribution artifact for a
|
||||
[gbrain](https://github.com/garrytan/gbrain) personal-agent workspace — the same
|
||||
|
||||
@@ -111,6 +111,21 @@ describe('runJobInChild (real children)', () => {
|
||||
expect(result.argv).toEqual(['jobs', 'run-child', '--job-id', '77']);
|
||||
}, TEST_TIMEOUT_MS);
|
||||
|
||||
// The shell opt-in travels to the isolated child as a FLAG (buildChildArgs):
|
||||
// the child re-runs the cwd-.env quarantine in the worker's cwd, so an
|
||||
// env-only handoff of GBRAIN_ALLOW_SHELL_JOBS would be dropped again there.
|
||||
test('--allow-shell-jobs pass-through: opts.env GBRAIN_ALLOW_SHELL_JOBS=1 appends the flag; any other value does not', async () => {
|
||||
const harness = makeHarness(
|
||||
'argv-echo',
|
||||
`writeOutcome({ outcome: 'success', result: { argv: process.argv.slice(2) } });\n` +
|
||||
`process.exit(0);\n`,
|
||||
);
|
||||
const on = (await runJobInChild({ ...baseOpts(harness), env: { ...process.env, GBRAIN_ALLOW_SHELL_JOBS: '1' } })) as { argv: string[] };
|
||||
expect(on.argv).toEqual(['jobs', 'run-child', '--job-id', '77', '--allow-shell-jobs']);
|
||||
const off = (await runJobInChild({ ...baseOpts(harness), env: { ...process.env, GBRAIN_ALLOW_SHELL_JOBS: 'true' } })) as { argv: string[] };
|
||||
expect(off.argv).toEqual(['jobs', 'run-child', '--job-id', '77']);
|
||||
}, TEST_TIMEOUT_MS);
|
||||
|
||||
test('error outcome (exit 0) throws the reconstructed class', async () => {
|
||||
const harness = makeHarness(
|
||||
'error-unrecoverable',
|
||||
|
||||
@@ -113,5 +113,13 @@ describe('#4602 — boolean flags consume a literal true/false value token', ()
|
||||
const params = parseOpArgs(operationsByName.add_link, ['page-a', 'page-b', '--json=false']);
|
||||
expect(params).toEqual({ from: 'page-a', to: 'page-b', json: false });
|
||||
});
|
||||
|
||||
test('delete <slug> --purge derives from the contract (boolean param → flag, no cli.ts special case)', () => {
|
||||
expect(findUnknownOpFlag(operationsByName.delete_page, ['people/alice-example', '--purge'])).toBeNull();
|
||||
expect(parseOpArgs(operationsByName.delete_page, ['people/alice-example', '--purge']))
|
||||
.toEqual({ slug: 'people/alice-example', purge: true });
|
||||
expect(parseOpArgs(operationsByName.delete_page, ['people/alice-example', '--purge=false']))
|
||||
.toEqual({ slug: 'people/alice-example', purge: false });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
1091
test/cli-cwd-dotenv-quarantine.test.ts
Normal file
1091
test/cli-cwd-dotenv-quarantine.test.ts
Normal file
File diff suppressed because it is too large
Load Diff
@@ -113,6 +113,19 @@ describe('loadConfig — ~/.gbrain/.env secrets file (#3893)', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('a bare CR terminates a line, as in Bun\'s own loader (grammar shared with env-trust.ts)', async () => {
|
||||
await withEnvFile(
|
||||
'GBRAIN_TEST_ENV_FILE_A=first\rGBRAIN_TEST_ENV_FILE_B=second\r\nGBRAIN_TEST_ENV_FILE_C=third\n',
|
||||
{ GBRAIN_TEST_ENV_FILE_A: undefined, GBRAIN_TEST_ENV_FILE_B: undefined, GBRAIN_TEST_ENV_FILE_C: undefined },
|
||||
() => {
|
||||
loadConfig();
|
||||
expect(process.env.GBRAIN_TEST_ENV_FILE_A).toBe('first');
|
||||
expect(process.env.GBRAIN_TEST_ENV_FILE_B).toBe('second');
|
||||
expect(process.env.GBRAIN_TEST_ENV_FILE_C).toBe('third');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('a missing ~/.gbrain/.env is not an error', async () => {
|
||||
await withEnvFile(null, {}, () => {
|
||||
const cfg = loadConfig();
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
import { describe, test, expect, beforeAll, afterAll, beforeEach } from 'bun:test';
|
||||
import { PGLiteEngine } from '../src/core/pglite-engine.ts';
|
||||
import { checkOauthClientScopeHealth } from '../src/commands/doctor.ts';
|
||||
import { DCR_PRIVILEGED_SCOPES } from '../src/commands/doctor/checks/routing-federation.ts';
|
||||
import { ALLOWED_SCOPES_LIST, DCR_REGISTRABLE_SCOPES } from '../src/core/scope.ts';
|
||||
|
||||
let engine: PGLiteEngine;
|
||||
|
||||
@@ -119,4 +121,228 @@ describe('checkOauthClientScopeHealth', () => {
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
expect(r.status).toBe('ok');
|
||||
});
|
||||
|
||||
// (c) Privileged self-registered clients. A row created through the
|
||||
// anonymous DCR path carries grant_revision = 0 and no oauth_grant_audit
|
||||
// 'register' row (operator paths write one). Rows that hold a scope beyond
|
||||
// the DCR ceiling with that signature predate the ceiling (or predate the
|
||||
// grant audit log) and deserve an operator look — advisory WARN with the
|
||||
// rescope / revoke remedy.
|
||||
describe('privileged self-registered (DCR-signature) clients', () => {
|
||||
async function seedClient(id: string, scope: string, opts: { audited?: boolean; revision?: number; deleted?: boolean } = {}): Promise<void> {
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at)
|
||||
VALUES ($1, $2, $3, 'default', $4, $5, ${opts.deleted ? 'now()' : 'NULL'})`,
|
||||
[id, `${id}-name`, scope, ['default'], opts.revision ?? 0],
|
||||
);
|
||||
if (opts.audited) {
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO oauth_grant_audit (client_id, actor, action, revision, before_grant, after_grant)
|
||||
VALUES ($1, 'operator', 'register', 0, NULL, '{}'::jsonb)`,
|
||||
[id],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await (engine as any).db.exec('DELETE FROM oauth_grant_audit');
|
||||
});
|
||||
|
||||
test('admin-scoped DCR-signature row → warn naming the client + rescope/revoke remedy', async () => {
|
||||
await seedClient('c-dcr-admin', 'read admin');
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
expect(r.status).toBe('warn');
|
||||
expect(r.message).toMatch(/c-dcr-admin/);
|
||||
expect(r.message).toMatch(/admin/);
|
||||
expect(r.message).toMatch(/rescope-client <client_id> --scopes read,write|rescope-client .*--scopes/);
|
||||
expect(r.message).toMatch(/revoke-client/);
|
||||
});
|
||||
|
||||
test('sources_admin and users_admin also trip the arm; the client name is shown', async () => {
|
||||
await seedClient('c-dcr-sources', 'sources_admin');
|
||||
await seedClient('c-dcr-users', 'read users_admin');
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
expect(r.status).toBe('warn');
|
||||
expect(r.message).toMatch(/c-dcr-sources-name/);
|
||||
expect(r.message).toMatch(/c-dcr-users-name/);
|
||||
});
|
||||
|
||||
test('read/write DCR-signature rows are within the ceiling → NOT flagged', async () => {
|
||||
await seedClient('c-dcr-rw', 'read write');
|
||||
await seedClient('c-dcr-empty', '');
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
expect(r.status).toBe('ok');
|
||||
});
|
||||
|
||||
test('operator-registered admin client (audit register row) → NOT flagged', async () => {
|
||||
await seedClient('c-op-admin', 'admin', { audited: true });
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
expect(r.status).toBe('ok');
|
||||
});
|
||||
|
||||
test('rescoped admin client (grant_revision > 0) → NOT flagged', async () => {
|
||||
await seedClient('c-rescoped-admin', 'admin', { revision: 2 });
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
expect(r.status).toBe('ok');
|
||||
});
|
||||
|
||||
test('revoked (deleted_at) DCR-signature admin row → NOT flagged', async () => {
|
||||
await seedClient('c-dcr-revoked', 'admin', { deleted: true });
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
expect(r.status).toBe('ok');
|
||||
});
|
||||
|
||||
test('grant audit table missing → arm skipped with an explicit note, other arms intact', async () => {
|
||||
await seedClient('c-dcr-admin-noaudit', 'admin');
|
||||
await (engine as any).db.exec('DROP TABLE oauth_grant_audit');
|
||||
try {
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
// Fail-open: cannot tell operator rows from self-registered ones
|
||||
// without the audit log, so the arm reports unknown instead of
|
||||
// guessing — and says so.
|
||||
expect(r.status).toBe('ok');
|
||||
expect(r.message).toMatch(/self-registered.*(skipped|unknown)|(skipped|unknown).*self-registered/i);
|
||||
} finally {
|
||||
const { GRANT_AUDIT_SCHEMA_SQL } = await import('../src/core/grants/schema.ts');
|
||||
await (engine as any).db.exec(GRANT_AUDIT_SCHEMA_SQL);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Arm (c) edge shapes not pinned above: the `agent` scope (seeded with the
|
||||
// delegation bindings its check constraint demands), the 5-client display cap
|
||||
// with its "+N more" tail, and the word-bounded scope match (a token that
|
||||
// merely CONTAINS a privileged word is not one).
|
||||
describe('checkOauthClientScopeHealth — arm (c) edge shapes', () => {
|
||||
async function seed(id: string, scope: string): Promise<void> {
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at)
|
||||
VALUES ($1, $2, $3, 'default', $4, 0, NULL)`,
|
||||
[id, `${id}-name`, scope, ['default']],
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await truncate();
|
||||
await (engine as any).db.exec('DELETE FROM oauth_grant_audit');
|
||||
});
|
||||
|
||||
test('agent-scoped DCR-signature row is flagged (agent sits beyond the ceiling too)', async () => {
|
||||
// `oauth_clients_complete_agent_grant` (grants/schema.ts) refuses an agent
|
||||
// scope without complete delegation bindings — seed a complete one.
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at,
|
||||
bound_tools, bound_source_id, delegated_namespace, delegated_slug_prefixes, bound_max_concurrent)
|
||||
VALUES ('c-dcr-agent', 'c-dcr-agent-name', 'read agent', 'default', $1, 0, NULL,
|
||||
$2, 'default', 'job', NULL, 1)`,
|
||||
[['default'], ['get_page']],
|
||||
);
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
expect(r.status).toBe('warn');
|
||||
expect(r.message).toMatch(/c-dcr-agent/);
|
||||
expect(r.message).toContain('scope=read agent');
|
||||
});
|
||||
|
||||
// (client_name is NOT NULL in the schema, so the `?? client_id` display
|
||||
// fallback cannot be reached through the database — not pinned here.)
|
||||
|
||||
test('more than five offenders: five shown (ordered by client_id), the rest counted', async () => {
|
||||
for (let i = 0; i < 7; i++) await seed(`c-dcr-many-${i}`, 'admin');
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
expect(r.status).toBe('warn');
|
||||
expect(r.message).toMatch(/^7 active OAuth client\(s\)/);
|
||||
for (let i = 0; i < 5; i++) expect(r.message).toContain(`(c-dcr-many-${i})`);
|
||||
expect(r.message).not.toContain('(c-dcr-many-5)');
|
||||
expect(r.message).not.toContain('(c-dcr-many-6)');
|
||||
expect(r.message).toContain('(+2 more)');
|
||||
});
|
||||
|
||||
test('a scope token that merely CONTAINS a privileged word is not flagged (word-bounded match)', async () => {
|
||||
await seed('c-dcr-substring', 'readmin write');
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
expect(r.status).toBe('ok');
|
||||
});
|
||||
|
||||
test('grant_revision column missing → arm skipped with the explicit note, other arms intact', async () => {
|
||||
// A brain whose oauth_clients predates the grant schema: the DCR
|
||||
// signature cannot be evaluated, so the arm reports unknown (ok + note)
|
||||
// rather than guessing — even with an admin-scoped row present.
|
||||
await (engine as any).db.exec('ALTER TABLE oauth_clients DROP COLUMN grant_revision');
|
||||
try {
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, deleted_at)
|
||||
VALUES ('c-dcr-norev', 'c-dcr-norev-name', 'admin', 'default', $1, NULL)`,
|
||||
[['default']],
|
||||
);
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
expect(r.status).toBe('ok');
|
||||
expect(r.message).toMatch(/self-registered.*(skipped|unknown)|(skipped|unknown).*self-registered/i);
|
||||
expect(r.message).not.toMatch(/c-dcr-norev/);
|
||||
} finally {
|
||||
await (engine as any).db.exec('ALTER TABLE oauth_clients ADD COLUMN grant_revision integer NOT NULL DEFAULT 0');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// The privileged set arm (c) matches is DERIVED from scope.ts (the complement
|
||||
// of the DCR ceiling), never a hand-copied literal — so a scope added to
|
||||
// ALLOWED_SCOPES_LIST without joining DCR_REGISTRABLE_SCOPES is audited
|
||||
// automatically, and the copy names the ceiling from the same constant.
|
||||
describe('checkOauthClientScopeHealth — arm (c) privileged set is the derived complement of the DCR ceiling', () => {
|
||||
const complement = ALLOWED_SCOPES_LIST.filter((s) => !DCR_REGISTRABLE_SCOPES.has(s));
|
||||
|
||||
test('DCR_PRIVILEGED_SCOPES === ALLOWED_SCOPES_LIST \\ DCR_REGISTRABLE_SCOPES (disjoint, jointly exhaustive)', () => {
|
||||
expect([...DCR_PRIVILEGED_SCOPES]).toEqual(complement);
|
||||
expect(DCR_PRIVILEGED_SCOPES.length).toBeGreaterThan(0);
|
||||
for (const s of DCR_PRIVILEGED_SCOPES) expect(DCR_REGISTRABLE_SCOPES.has(s as any)).toBe(false);
|
||||
expect([...DCR_PRIVILEGED_SCOPES, ...DCR_REGISTRABLE_SCOPES].sort()).toEqual([...ALLOWED_SCOPES_LIST].sort());
|
||||
});
|
||||
|
||||
/** Seed a DCR-signature row; `agent` needs complete delegation bindings (check constraint). */
|
||||
async function seedDcrSignature(id: string, scope: string): Promise<void> {
|
||||
if (scope.split(' ').includes('agent')) {
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at,
|
||||
bound_tools, bound_source_id, delegated_namespace, delegated_slug_prefixes, bound_max_concurrent)
|
||||
VALUES ($1, $2, $3, 'default', $4, 0, NULL, $5, 'default', 'job', NULL, 1)`,
|
||||
[id, `${id}-name`, scope, ['default'], ['get_page']],
|
||||
);
|
||||
return;
|
||||
}
|
||||
await engine.executeRaw(
|
||||
`INSERT INTO oauth_clients (client_id, client_name, scope, source_id, federated_read, grant_revision, deleted_at)
|
||||
VALUES ($1, $2, $3, 'default', $4, 0, NULL)`,
|
||||
[id, `${id}-name`, scope, ['default']],
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await truncate();
|
||||
await (engine as any).db.exec('DELETE FROM oauth_grant_audit');
|
||||
});
|
||||
|
||||
test('every scope in the complement trips the arm on its own; every ceiling scope does not', async () => {
|
||||
for (const scope of complement) {
|
||||
await (engine as any).db.exec('DELETE FROM oauth_clients');
|
||||
await seedDcrSignature(`c-dcr-${scope}`, scope);
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
expect(r.status).toBe('warn');
|
||||
expect(r.message).toContain(`(c-dcr-${scope}) scope=${scope}`);
|
||||
}
|
||||
for (const scope of DCR_REGISTRABLE_SCOPES) {
|
||||
await (engine as any).db.exec('DELETE FROM oauth_clients');
|
||||
await seedDcrSignature(`c-dcr-${scope}`, scope);
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
expect(r.status).toBe('ok');
|
||||
}
|
||||
});
|
||||
|
||||
test('the remedy copy names the ceiling from the constant, not a literal', async () => {
|
||||
await seedDcrSignature('c-dcr-copy', complement[0]);
|
||||
const r = await checkOauthClientScopeHealth(engine);
|
||||
const ceiling = [...DCR_REGISTRABLE_SCOPES];
|
||||
expect(r.message).toContain(`self-registration ceiling (${ceiling.join('/')})`);
|
||||
expect(r.message).toContain(`--scopes ${ceiling.join(',')}`);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2519,3 +2519,57 @@ describeBoth('Engine parity — getCalleesOf bare-name fallback (#4670)', () =>
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// getRawData soft-delete filter. Companion to the #4587 soft-delete blocks
|
||||
// above, but NOT behind describeBoth: the PGLite arm always runs (so the
|
||||
// filter is exercised in every sandbox) and the Postgres arm joins when
|
||||
// DATABASE_URL is configured (CI docker Postgres).
|
||||
describe('getRawData soft-delete filter — parity (PGLite always; Postgres when DATABASE_URL is set)', () => {
|
||||
let pglite: PGLiteEngine;
|
||||
const arms: Array<{ name: string; eng: BrainEngine }> = [];
|
||||
|
||||
beforeAll(async () => {
|
||||
pglite = new PGLiteEngine();
|
||||
await pglite.connect({});
|
||||
await pglite.initSchema();
|
||||
arms.push({ name: 'pglite', eng: pglite });
|
||||
if (!SKIP_PG) arms.push({ name: 'postgres', eng: await setupDB() });
|
||||
}, 90_000);
|
||||
|
||||
afterAll(async () => {
|
||||
await pglite.disconnect();
|
||||
if (!SKIP_PG) await teardownDB();
|
||||
}, 30_000);
|
||||
|
||||
test('putRawData → softDeletePage hides raw_data on every read shape; includeDeleted:true still returns it; restorePage makes it visible again', async () => {
|
||||
expect(arms.length).toBeGreaterThan(0);
|
||||
for (const { name, eng } of arms) {
|
||||
const slug = 'wiki/raw-soft-delete';
|
||||
await eng.putPage(slug, { type: 'note', title: 'raw', compiled_truth: 'body', timeline: '' }, { sourceId: 'default' });
|
||||
await eng.putRawData(slug, 'transcript:test', { k: 'v' }, { sourceId: 'default' });
|
||||
expect((await eng.getRawData(slug, undefined, { sourceId: 'default' })).length).toBe(1);
|
||||
|
||||
expect(await eng.softDeletePage(slug, { sourceId: 'default' })).not.toBeNull();
|
||||
// Every WHERE shape (unscoped, scalar source, federated sourceIds,
|
||||
// with/without a raw source filter) hides the soft-deleted page.
|
||||
const hidden = [
|
||||
await eng.getRawData(slug),
|
||||
await eng.getRawData(slug, 'transcript:test'),
|
||||
await eng.getRawData(slug, undefined, { sourceId: 'default' }),
|
||||
await eng.getRawData(slug, 'transcript:test', { sourceId: 'default' }),
|
||||
await eng.getRawData(slug, undefined, { sourceIds: ['default'] }),
|
||||
await eng.getRawData(slug, 'transcript:test', { sourceIds: ['default'] }),
|
||||
];
|
||||
for (const rows of hidden) expect({ arm: name, rows }).toEqual({ arm: name, rows: [] });
|
||||
|
||||
// Explicit opt-in (export / engine migration / ingest healing) still sees it.
|
||||
expect((await eng.getRawData(slug, undefined, { sourceId: 'default', includeDeleted: true })).length).toBe(1);
|
||||
expect((await eng.getRawData(slug, 'transcript:test', { sourceIds: ['default'], includeDeleted: true })).length).toBe(1);
|
||||
expect((await eng.getRawData(slug, undefined, { includeDeleted: true })).length).toBe(1);
|
||||
|
||||
expect(await eng.restorePage(slug, { sourceId: 'default' })).toBe(true);
|
||||
expect((await eng.getRawData(slug, undefined, { sourceId: 'default' })).length).toBe(1);
|
||||
await eng.deletePage(slug, { sourceId: 'default' });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,11 +5,17 @@ import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { createServer } from 'node:net';
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import { TEST_PKCE_CHALLENGE } from '../helpers/oauth.ts';
|
||||
import { TEST_PKCE_CHALLENGE, TEST_PKCE_VERIFIER } from '../helpers/oauth.ts';
|
||||
|
||||
let child: ChildProcess;
|
||||
let home: string;
|
||||
let base: string;
|
||||
// ONE admin login for the whole file (the shared admin auth limiter is
|
||||
// 10/min/IP and the consent routes draw from the same bucket), taken in
|
||||
// beforeAll so every test is order-independent. `adminSetCookie` keeps the
|
||||
// raw header for the attribute assertions.
|
||||
let adminCookie = '';
|
||||
let adminSetCookie = '';
|
||||
const BOOTSTRAP = 'synthetic-consent-admin-test-token';
|
||||
beforeAll(async () => {
|
||||
home = mkdtempSync(join(tmpdir(), 'gbrain-consent-test-'));
|
||||
@@ -28,12 +34,17 @@ beforeAll(async () => {
|
||||
let output = '';
|
||||
child.stderr?.on('data', chunk => { output += chunk.toString(); });
|
||||
child.stdout?.on('data', chunk => { output += chunk.toString(); });
|
||||
for (let attempt = 0; attempt < 150; attempt++) {
|
||||
let up = false;
|
||||
for (let attempt = 0; attempt < 150 && !up; attempt++) {
|
||||
if (child.exitCode !== null) throw new Error(`Consent server exited: ${output.slice(-2000)}`);
|
||||
try { if ((await fetch(`${base}/health`)).ok) return; } catch { /* starting */ }
|
||||
await Bun.sleep(100);
|
||||
try { up = (await fetch(`${base}/health`)).ok; } catch { /* starting */ }
|
||||
if (!up) await Bun.sleep(100);
|
||||
}
|
||||
throw new Error(`Consent server did not start: ${output.slice(-2000)}`);
|
||||
if (!up) throw new Error(`Consent server did not start: ${output.slice(-2000)}`);
|
||||
const login = await fetch(`${base}/admin/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: BOOTSTRAP }) });
|
||||
if (login.status !== 200) throw new Error(`admin login failed: ${login.status}`);
|
||||
adminSetCookie = login.headers.get('set-cookie') ?? '';
|
||||
adminCookie = adminSetCookie.split(';')[0];
|
||||
}, 30_000);
|
||||
afterAll(async () => {
|
||||
if (child && child.exitCode === null) {
|
||||
@@ -55,13 +66,13 @@ test('login, magic-link recovery, consent authentication and single-use approval
|
||||
const authorization = await fetch(`${base}/authorize?${query}`, { redirect: 'manual' });
|
||||
const pendingUrl = new URL(authorization.headers.get('location')!, base);
|
||||
expect(pendingUrl.pathname).toBe('/admin/');
|
||||
expect(pendingUrl.searchParams.has('code')).toBe(false);
|
||||
const id = pendingUrl.searchParams.get('oauth_request')!;
|
||||
expect((await fetch(pendingUrl)).status).toBe(200); // unauthenticated page shell
|
||||
expect((await fetch(`${base}/admin/api/oauth-requests/${id}`)).status).toBe(401);
|
||||
const login = await fetch(`${base}/admin/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ token: BOOTSTRAP }) });
|
||||
expect(login.status).toBe(200);
|
||||
const oldCookie = login.headers.get('set-cookie')!.split(';')[0];
|
||||
expect(login.headers.get('set-cookie')).toContain('SameSite=Strict');
|
||||
expect(adminCookie).not.toBe('');
|
||||
const oldCookie = adminCookie; // the beforeAll login session
|
||||
expect(adminSetCookie).toContain('SameSite=Strict');
|
||||
const oldDetails = await (await fetch(`${base}/admin/api/oauth-requests/${id}`, { headers: { Cookie: oldCookie } })).json() as any;
|
||||
const magic = await fetch(`${base}/admin/api/issue-magic-link`, { method: 'POST', headers: { Authorization: `Bearer ${BOOTSTRAP}`, 'Content-Type': 'application/json' }, body: JSON.stringify({ oauth_request: id, return_url: 'https://untrusted.example' }) });
|
||||
expect(magic.status).toBe(200);
|
||||
@@ -84,3 +95,74 @@ test('login, magic-link recovery, consent authentication and single-use approval
|
||||
expect(redirect.searchParams.get('code')).toStartWith('gbrain_code_');
|
||||
expect((await fetch(endpoint, { method: 'POST', headers, body: JSON.stringify({ decision: 'approve', csrf: details.csrf }) })).status).toBe(410);
|
||||
}, 15_000);
|
||||
|
||||
/** Anonymous self-registration with a foreign redirect_uri: no code without the owner, forged codes do not redeem, revocation closes /authorize. */
|
||||
test('a self-registered public client cannot obtain or redeem a code without owner approval', async () => {
|
||||
const foreignRedirect = 'https://client-example.invalid/cb';
|
||||
const register = async (body: Record<string, unknown>) => {
|
||||
const response = await fetch(`${base}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({
|
||||
client_name: 'synthetic self-registered client', redirect_uris: [foreignRedirect], token_endpoint_auth_method: 'none', ...body }) });
|
||||
expect(response.status).toBe(201);
|
||||
return response.json() as Promise<any>;
|
||||
};
|
||||
const authorize = async (clientId: string, scope?: string) => {
|
||||
const query = new URLSearchParams({ client_id: clientId, response_type: 'code', redirect_uri: foreignRedirect, code_challenge: TEST_PKCE_CHALLENGE, code_challenge_method: 'S256', state: 'attacker-state' });
|
||||
if (scope !== undefined) query.set('scope', scope);
|
||||
return fetch(`${base}/authorize?${query}`, { redirect: 'manual' });
|
||||
};
|
||||
const expectPending = async (clientId: string, scope?: string) => {
|
||||
const response = await authorize(clientId, scope);
|
||||
expect(response.status).toBe(302);
|
||||
const location = new URL(response.headers.get('location')!, base);
|
||||
expect(location.pathname).toBe('/admin/');
|
||||
expect(location.searchParams.has('code')).toBe(false);
|
||||
return location.searchParams.get('oauth_request')!;
|
||||
};
|
||||
|
||||
// grant_types omitted: the default is the consent-bearing authorization_code flow.
|
||||
const client = await register({ scope: 'read write' });
|
||||
expect(client.client_secret).toBeUndefined();
|
||||
await expectPending(client.client_id, 'read write');
|
||||
const forged = await fetch(`${base}/token`, { method: 'POST', body: new URLSearchParams({
|
||||
grant_type: 'authorization_code', code: 'gbrain_code_' + 'a'.repeat(43), code_verifier: TEST_PKCE_VERIFIER,
|
||||
client_id: client.client_id, redirect_uri: foreignRedirect }) });
|
||||
expect(forged.status).toBe(400);
|
||||
expect((await forged.json() as any).error).toBe('invalid_grant');
|
||||
|
||||
// scope omitted: nothing is registered and the consent request carries no scopes (one consent GET).
|
||||
const unscoped = await register({ grant_types: ['authorization_code'] });
|
||||
expect(unscoped.scope ?? '').toBe('');
|
||||
const id = await expectPending(unscoped.client_id);
|
||||
const details = await fetch(`${base}/admin/api/oauth-requests/${id}`, { headers: { Cookie: adminCookie } });
|
||||
expect(details.status).toBe(200);
|
||||
expect((await details.json() as any).scopes).toEqual([]);
|
||||
|
||||
// Revoked self-registered client: /authorize is refused before any consent request exists.
|
||||
const revoked = await fetch(`${base}/admin/api/revoke-client`, { method: 'POST', headers: { Cookie: adminCookie, 'Content-Type': 'application/json' }, body: JSON.stringify({ clientId: client.client_id }) });
|
||||
expect(revoked.status).toBe(200);
|
||||
const refused = await authorize(client.client_id, 'read write');
|
||||
expect(refused.status).toBe(400);
|
||||
expect((await refused.json() as any).error).toBe('invalid_client');
|
||||
}, 15_000);
|
||||
|
||||
/** With self-registration on, discovery advertises exactly what a self-registering client may request — and a client that copies it registers. */
|
||||
test('OAuth discovery advertises the self-registration ceiling and a client that copies it registers', async () => {
|
||||
const metadata = await (await fetch(`${base}/.well-known/oauth-authorization-server`)).json() as any;
|
||||
expect(metadata.scopes_supported).toEqual(['read', 'write']);
|
||||
expect(new URL(metadata.registration_endpoint).pathname).toBe('/register');
|
||||
const register = (scope: string) => fetch(`${base}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({
|
||||
client_name: 'synthetic discovered-scopes client', redirect_uris: ['https://client-example.invalid/cb'], grant_types: ['authorization_code', 'refresh_token'],
|
||||
response_types: ['code'], token_endpoint_auth_method: 'none', scope }) });
|
||||
const response = await register(metadata.scopes_supported.join(' '));
|
||||
expect(response.status).toBe(201);
|
||||
const client = await response.json() as any;
|
||||
expect(client.scope.split(' ')).toEqual(metadata.scopes_supported);
|
||||
for (const path of ['/.well-known/oauth-protected-resource/mcp', '/.well-known/oauth-protected-resource']) {
|
||||
const resource = await (await fetch(`${base}${path}`)).json() as any;
|
||||
expect(resource.scopes_supported).toEqual(metadata.scopes_supported);
|
||||
}
|
||||
// Narrowed discovery does not loosen the ceiling: an explicit privileged request is still refused.
|
||||
const refused = await register('read write admin');
|
||||
expect(refused.status).toBe(400);
|
||||
expect((await refused.json() as any).error).toBe('invalid_client_metadata');
|
||||
}, 15_000);
|
||||
|
||||
@@ -361,22 +361,24 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {
|
||||
expect(meta.token_endpoint).toContain('/token');
|
||||
expect(meta.scopes_supported).toContain('read');
|
||||
expect(meta.scopes_supported).toContain('write');
|
||||
expect(meta.scopes_supported).toContain('admin');
|
||||
// This server runs with --enable-dcr: discovery advertises the
|
||||
// self-registration ceiling, never a privileged scope
|
||||
// (scopesSupportedForDiscovery in src/core/scope.ts).
|
||||
expect(meta.scopes_supported).not.toContain('admin');
|
||||
});
|
||||
|
||||
// T2 (eng-review): scopes_supported advertises the full ALLOWED_SCOPES_LIST
|
||||
// so MCP clients (Claude Desktop, ChatGPT, Perplexity) can discover the
|
||||
// v0.28 sources_admin and users_admin scopes via standard discovery.
|
||||
// Pre-v0.28 the list was hardcoded to ['read','write','admin'] in
|
||||
// serve-http.ts:195 and this assertion would have failed.
|
||||
test('OAuth metadata advertises all 5 v0.28 scopes (sources_admin + users_admin)', async () => {
|
||||
// With --enable-dcr, scopes_supported is exactly the DCR ceiling (`read write`,
|
||||
// canonical order) so a client that copies discovery into /register is
|
||||
// accepted. The full operator list (admin, read, sources_admin, users_admin,
|
||||
// write) is still advertised WITHOUT DCR — pinned by
|
||||
// test/e2e/sources-remote-mcp.test.ts ('OAuth /.well-known advertises all 5 scopes').
|
||||
test('OAuth metadata under --enable-dcr advertises exactly the self-registration ceiling', async () => {
|
||||
const res = await fetch(`${BASE}/.well-known/oauth-authorization-server`);
|
||||
const meta = await res.json() as any;
|
||||
expect(meta.scopes_supported).toContain('sources_admin');
|
||||
expect(meta.scopes_supported).toContain('users_admin');
|
||||
expect(meta.scopes_supported).toEqual(
|
||||
expect.arrayContaining(['admin', 'read', 'sources_admin', 'users_admin', 'write']),
|
||||
);
|
||||
expect(meta.scopes_supported).toEqual(['read', 'write']);
|
||||
for (const privileged of ['admin', 'sources_admin', 'users_admin', 'agent']) {
|
||||
expect(meta.scopes_supported).not.toContain(privileged);
|
||||
}
|
||||
});
|
||||
|
||||
// =========================================================================
|
||||
@@ -402,9 +404,9 @@ describeE2E('serve-http OAuth 2.1 E2E (v0.26.1 + v0.26.2 + v0.26.3)', () => {
|
||||
expect(meta.resource).toBe(`${BASE}/mcp`);
|
||||
expect(meta.resource).not.toBe(`${BASE}/`);
|
||||
expect(meta.authorization_servers).toContain(`${BASE}/`);
|
||||
expect(meta.scopes_supported).toEqual(
|
||||
expect.arrayContaining(['admin', 'read', 'sources_admin', 'users_admin', 'write']),
|
||||
);
|
||||
// --enable-dcr server: the protected-resource document mirrors the AS
|
||||
// metadata's self-registration ceiling.
|
||||
expect(meta.scopes_supported).toEqual(['read', 'write']);
|
||||
});
|
||||
|
||||
// Setting resourceServerUrl moves the SDK's document to the path-inserted
|
||||
|
||||
@@ -372,45 +372,106 @@ describeE2E('sources-remote-mcp E2E (gstack /setup-gbrain Path 4)', () => {
|
||||
});
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// sources_remove: cascade + clone cleanup
|
||||
// sources_remove: WRITE authority, cascade + clone cleanup
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
test('sources_remove deletes row + cleans up the clone (managed path)', async () => {
|
||||
// Recreate the clone first (the previous test rmd it for the missing
|
||||
// assertion). We do this via sources_add since that path is exercised.
|
||||
// (Could call sources_add again but the row is still there from earlier;
|
||||
// simpler: insert a fresh fixture.)
|
||||
await callMcp(token!, 'sources_add', {
|
||||
id: 'e2e-removable',
|
||||
url: TEST_URL,
|
||||
/**
|
||||
* sources_remove is confined to the caller's WRITE authority (O4-1, review
|
||||
* cycle 4): a sources_admin token may hard-delete only its own write source.
|
||||
* The federated read grant (`--federated-read`) is READ authority by
|
||||
* contract and confers no removal right — widening it makes a source
|
||||
* visible to sources_status / sources_list, yet sources_remove still
|
||||
* answers not_found (indistinguishable from a nonexistent source). Over
|
||||
* HTTP every client carries a write source (registration default
|
||||
* 'default'), and a client's own row FK-RESTRICTs the removal of that very
|
||||
* source, so hard-removing a source is an operator action on the host CLI
|
||||
* (`gbrain sources remove`) — mirrored here.
|
||||
*/
|
||||
async function widenGrantTo(...sourceIds: string[]): Promise<void> {
|
||||
const { execFileSync } = await import('child_process');
|
||||
execFileSync('bun', ['run', 'src/cli.ts', 'auth', 'rescope-client', clientId!,
|
||||
'--federated-read', sourceIds.join(',')], {
|
||||
cwd: process.cwd(), encoding: 'utf8', env: { ...process.env, GBRAIN_HOME },
|
||||
});
|
||||
}
|
||||
|
||||
async function rescopeWriteSource(sourceId: string): Promise<void> {
|
||||
const { execFileSync } = await import('child_process');
|
||||
execFileSync('bun', ['run', 'src/cli.ts', 'auth', 'rescope-client', clientId!,
|
||||
'--source', sourceId], {
|
||||
cwd: process.cwd(), encoding: 'utf8', env: { ...process.env, GBRAIN_HOME },
|
||||
});
|
||||
}
|
||||
|
||||
/** The trusted local path: `gbrain sources remove <id> --confirm-destructive` on the host. */
|
||||
async function operatorRemovesSource(id: string): Promise<string> {
|
||||
const { execFileSync } = await import('child_process');
|
||||
return execFileSync('bun', ['run', 'src/cli.ts', 'sources', 'remove', id, '--confirm-destructive'], {
|
||||
cwd: process.cwd(), encoding: 'utf8', env: { ...process.env, GBRAIN_HOME },
|
||||
});
|
||||
}
|
||||
|
||||
test('sources_remove: a federated READ grant naming the source is not removal authority; the operator removes it on the host CLI', async () => {
|
||||
await callMcp(token!, 'sources_add', { id: 'e2e-removable', url: TEST_URL });
|
||||
const clonePath = join(GBRAIN_HOME, '.gbrain', 'clones', 'e2e-removable');
|
||||
expect(existsSync(clonePath)).toBe(true);
|
||||
const result = await callMcp(token!, 'sources_remove', {
|
||||
// Outside the token's grant entirely → not_found, and nothing is removed.
|
||||
const fenced = await callMcp(token!, 'sources_remove', {
|
||||
id: 'e2e-removable',
|
||||
confirm_destructive: true,
|
||||
});
|
||||
expect(result.clone_removed).toBe(true);
|
||||
expect(existsSync(clonePath)).toBe(false);
|
||||
expect(fenced.__isError).toBe(true);
|
||||
expect(JSON.stringify(fenced.parsed)).toMatch(/not_found/);
|
||||
expect(existsSync(clonePath)).toBe(true);
|
||||
// Operator widens the READ grant; the live token now reads the source...
|
||||
await widenGrantTo('default', 'e2e-yc-artifacts', 'e2e-removable');
|
||||
const status = await callMcp(token!, 'sources_status', { id: 'e2e-removable' });
|
||||
expect(status.clone_state).toBe('healthy');
|
||||
// ...but removal is WRITE authority: still not_found, still on disk.
|
||||
const stillFenced = await callMcp(token!, 'sources_remove', {
|
||||
id: 'e2e-removable',
|
||||
confirm_destructive: true,
|
||||
});
|
||||
expect(stillFenced.__isError).toBe(true);
|
||||
expect(JSON.stringify(stillFenced.parsed)).toMatch(/not_found/);
|
||||
expect(existsSync(clonePath)).toBe(true);
|
||||
// The operator removes it on the host CLI (trusted local path).
|
||||
const out = await operatorRemovesSource('e2e-removable');
|
||||
expect(out).toMatch(/Removed source "e2e-removable"/);
|
||||
const after = await callMcp(token!, 'sources_list', {});
|
||||
expect(after.sources.find((s: any) => s.id === 'e2e-removable')).toBeUndefined();
|
||||
// Drop the dead id from the read grant (hygiene for the tests below).
|
||||
await widenGrantTo('default', 'e2e-yc-artifacts');
|
||||
});
|
||||
|
||||
test('sources_remove without confirm_destructive refuses on populated source', async () => {
|
||||
// Add a fresh source with no pages — should still need confirm_destructive
|
||||
// semantically because remove is hard-delete (vs archive).
|
||||
test('sources_remove: rescoping the WRITE source moves the authority — a federated-readable non-write source stays not_found while sources_status still answers', async () => {
|
||||
await callMcp(token!, 'sources_add', { id: 'e2e-confirm-test', url: TEST_URL });
|
||||
const result = await callMcp(token!, 'sources_remove', {
|
||||
id: 'e2e-confirm-test',
|
||||
// omit confirm_destructive
|
||||
});
|
||||
// A source with 0 pages may pass — the gate is page-count-aware. Our
|
||||
// newly-added source has 0 pages so this should succeed. Tweak:
|
||||
// exercise the throw path by inserting a page first via raw SQL,
|
||||
// but that's heavy. For now assert the result shape exists.
|
||||
if (result.__isError) {
|
||||
expect(JSON.stringify(result.parsed)).toMatch(/confirm/i);
|
||||
} else {
|
||||
// 0-page source: allowed without confirm. Still verify clone cleaned.
|
||||
expect(typeof result.clone_removed).toBe('boolean');
|
||||
await widenGrantTo('default', 'e2e-yc-artifacts', 'e2e-confirm-test');
|
||||
await rescopeWriteSource('e2e-confirm-test');
|
||||
try {
|
||||
const identity = await callMcp(token!, 'whoami', {});
|
||||
expect(identity.source_id).toBe('e2e-confirm-test');
|
||||
// e2e-yc-artifacts is readable (federated) but is not the write source.
|
||||
const fenced = await callMcp(token!, 'sources_remove', {
|
||||
id: 'e2e-yc-artifacts',
|
||||
confirm_destructive: true,
|
||||
});
|
||||
expect(fenced.__isError).toBe(true);
|
||||
expect(JSON.stringify(fenced.parsed)).toMatch(/not_found/);
|
||||
const status = await callMcp(token!, 'sources_status', { id: 'e2e-yc-artifacts' });
|
||||
expect(status.id).toBe('e2e-yc-artifacts');
|
||||
// 'default' is neither readable-only nor the write source now: same
|
||||
// not_found (the fence answers before the op's protected-id guard).
|
||||
const def = await callMcp(token!, 'sources_remove', { id: 'default', confirm_destructive: true });
|
||||
expect(def.__isError).toBe(true);
|
||||
expect(JSON.stringify(def.parsed)).toMatch(/not_found/);
|
||||
} finally {
|
||||
// Restore the write source BEFORE the operator removes the fixture — a
|
||||
// client row referencing it would FK-RESTRICT the removal.
|
||||
await rescopeWriteSource('default');
|
||||
}
|
||||
const out = await operatorRemovesSource('e2e-confirm-test');
|
||||
expect(out).toMatch(/Removed source "e2e-confirm-test"/);
|
||||
await widenGrantTo('default', 'e2e-yc-artifacts');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -646,3 +646,198 @@ describe('putRawData zero-row parity (PGLite)', () => {
|
||||
).rejects.toThrow(/not found/);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Format-based redaction lands in the STORED page ─────────────────────────
|
||||
//
|
||||
// Synthetic, runtime-joined values (>= 2 fragments each) so no committed line
|
||||
// carries a credential-shaped literal. Read back through the engine (never
|
||||
// grep the PGLite data dir — its paged format hides plaintext from grep).
|
||||
const SEEDED_JWT = [
|
||||
'eyJhbGciOiJIUzI1NiJ9',
|
||||
'eyJyb2xlIjoic2VydmljZV9yb2xlIiwiaWF0IjoxNzAwMDAwMDAwfQ',
|
||||
'c2lnbmF0dXJlLXBsYWNlaG9sZGVyLTAwMDA',
|
||||
].join('.');
|
||||
const SEEDED_SID = ['AC', '0123456789abcdef', '0123456789abcdef'].join('');
|
||||
const SEEDED_GOOGLE = ['AIza', 'SyD1-Fake_Example0123456789abcdefGH'].join('');
|
||||
const SEEDED_STRIPE = ['sk_live_', '4eC39HqLyjWDarjtT1zdp7dc'].join('');
|
||||
const SEEDED_DB_URL = ['postgres://', 'dbuser', ':', 'p4ssw0rd', '@db.internal:5432/app'].join('');
|
||||
const SEEDED_ENTROPIC = ['aB3xK9mQ', '2pR7sT1vW4yZ8bC5'].join('');
|
||||
const SEEDED_OPAQUE = ['opaque', 'Token0123456789abcdefXYZ'].join('');
|
||||
|
||||
function claudeCodeLine(type: 'user' | 'assistant', uuid: string, ts: string, content: string): string {
|
||||
return JSON.stringify({
|
||||
type,
|
||||
message: { role: type, content },
|
||||
uuid,
|
||||
timestamp: ts,
|
||||
cwd: '/tmp/poc',
|
||||
sessionId: 'poc-0001',
|
||||
version: '2.1.0',
|
||||
gitBranch: 'main',
|
||||
});
|
||||
}
|
||||
|
||||
describe('format-based redaction before write (unprefixed credential shapes)', () => {
|
||||
test('claude-code session: JWT / account SID / connection string / cloud keys land as placeholders only — and a bare echo in ANOTHER message goes with them', async () => {
|
||||
const p = join(tmp, 'poc-session.jsonl');
|
||||
writeFileSync(
|
||||
p,
|
||||
[
|
||||
claudeCodeLine('user', 'seed-0000', '2026-08-25T23:00:00.000Z', `deploy is failing. service role key ${SEEDED_JWT} and project ref zfakerefzfakeref0000`),
|
||||
// The opaque token appears BARE here, two messages before the header
|
||||
// that claims it; the entropic value appears bare AFTER its claim.
|
||||
claudeCodeLine('assistant', 'seed-0001', '2026-08-25T23:00:01.000Z', `twilio sid ${SEEDED_SID} and maps key ${SEEDED_GOOGLE} need rotating; the token ${SEEDED_OPAQUE} expired too`),
|
||||
claudeCodeLine('user', 'seed-0002', '2026-08-25T23:00:02.000Z', `stripe ${SEEDED_STRIPE} plus DATABASE_URL=${SEEDED_DB_URL} and SMTP_TOKEN=${SEEDED_ENTROPIC}`),
|
||||
claudeCodeLine('assistant', 'seed-0003', '2026-08-25T23:00:03.000Z', `retried with the header Authorization: Bearer ${SEEDED_OPAQUE} and pasted ${SEEDED_ENTROPIC} into the env`),
|
||||
].join('\n') + '\n',
|
||||
);
|
||||
const r = await runTranscriptsIngest(engine, baseOpts([p]));
|
||||
expect(r.sessionsImported).toBe(1);
|
||||
expect(r.pages.imported).toBe(1);
|
||||
// Seven CLAIMS; the two bare echoes add no count.
|
||||
expect(r.redactions).toBeGreaterThanOrEqual(7);
|
||||
|
||||
const slug = r.slugsTouched[0];
|
||||
const page = await engine.getPage(slug, { sourceId: 'default' });
|
||||
expect(page).not.toBeNull();
|
||||
const body = page!.compiled_truth;
|
||||
// Positive control: harmless prose from the same page is present.
|
||||
expect(body).toContain('deploy is failing');
|
||||
for (const v of [SEEDED_JWT, SEEDED_SID, SEEDED_GOOGLE, SEEDED_STRIPE, SEEDED_ENTROPIC, SEEDED_OPAQUE, 'p4ssw0rd']) {
|
||||
expect(body).not.toContain(v);
|
||||
}
|
||||
for (const tag of [
|
||||
'<REDACTED:jwt>', '<REDACTED:twilio>', '<REDACTED:google_api_key>', '<REDACTED:stripe>',
|
||||
'<REDACTED:db_url_credentials>', '<REDACTED:high_entropy_assignment>', '<REDACTED:bearer>',
|
||||
]) {
|
||||
expect(body).toContain(tag);
|
||||
}
|
||||
// The session-wide echo dictionary: the token's bare mention in an
|
||||
// EARLIER message and the entropic value's in a LATER one are scrubbed.
|
||||
expect(body).toContain('the token <REDACTED:bearer> expired too');
|
||||
expect(body).toContain('pasted <REDACTED:high_entropy_assignment> into the env');
|
||||
// A project ref is an identifier, not a credential — deliberately kept.
|
||||
expect(body).toContain('zfakerefzfakeref0000');
|
||||
// Whatever session metadata rode along carries no seeded value either.
|
||||
const raw = await engine.getRawData(slug, undefined, { sourceId: 'default' });
|
||||
const stored = JSON.stringify(raw);
|
||||
for (const v of [SEEDED_JWT, SEEDED_SID, SEEDED_GOOGLE, SEEDED_STRIPE, 'p4ssw0rd']) {
|
||||
expect(stored).not.toContain(v);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/** Count calls to an engine method for one block; restores the original. */
|
||||
async function spyEngine<K extends 'getRawData' | 'putRawData'>(
|
||||
method: K,
|
||||
run: () => Promise<void>,
|
||||
): Promise<unknown[][]> {
|
||||
const calls: unknown[][] = [];
|
||||
const original = (engine as any)[method].bind(engine);
|
||||
(engine as any)[method] = (...args: unknown[]) => { calls.push(args); return original(...args); };
|
||||
try { await run(); } finally { delete (engine as any)[method]; }
|
||||
return calls;
|
||||
}
|
||||
|
||||
function writePlainSession(path: string): void {
|
||||
writeFileSync(
|
||||
path,
|
||||
[
|
||||
JSON.stringify({ type: 'session', version: 3, id: 'plain-02', timestamp: '2026-08-09T11:00:00.000Z', cwd: '/tmp/plain' }),
|
||||
JSON.stringify({
|
||||
type: 'message',
|
||||
id: 'm-1',
|
||||
timestamp: '2026-08-09T11:00:01.000Z',
|
||||
message: { role: 'user', timestamp: '2026-08-09T11:00:01.000Z', content: [{ type: 'text', text: 'plain question two' }] },
|
||||
}),
|
||||
].join('\n') + '\n',
|
||||
);
|
||||
}
|
||||
|
||||
describe('re-ingest over a soft-deleted base page', () => {
|
||||
test('resurrects the page (hash check reads ACTIVE rows only) — the compare probe never runs, raw is rewritten', async () => {
|
||||
const p = join(tmp, 'plain-session-2.jsonl');
|
||||
writePlainSession(p);
|
||||
const r1 = await runTranscriptsIngest(engine, baseOpts([p]));
|
||||
expect(r1.pages.imported).toBe(1);
|
||||
const slug = r1.slugsTouched[0];
|
||||
expect(await engine.softDeletePage(slug, { sourceId: 'default' })).not.toBeNull();
|
||||
expect(await engine.getPage(slug, { sourceId: 'default' })).toBeNull();
|
||||
|
||||
let r2: Awaited<ReturnType<typeof runTranscriptsIngest>> | undefined;
|
||||
let putCalls: unknown[][] = [];
|
||||
const probeCalls = await spyEngine('getRawData', async () => {
|
||||
putCalls = await spyEngine('putRawData', async () => {
|
||||
r2 = await runTranscriptsIngest(engine, baseOpts([p]));
|
||||
});
|
||||
});
|
||||
// No abort; the tombstoned base page reads as missing to the import
|
||||
// hash check, so it is IMPORTED again (not skipped) and comes back alive.
|
||||
expect(r2!.sessionsImported).toBe(1);
|
||||
expect(r2!.sessionsErrored).toBe(0);
|
||||
expect(r2!.cleanScan).toBe(true);
|
||||
expect(r2!.pages.imported).toBe(1);
|
||||
expect(r2!.pages.skipped).toBe(0);
|
||||
const alive = await engine.getPage(slug, { sourceId: 'default' });
|
||||
expect(alive).not.toBeNull();
|
||||
expect(alive!.deleted_at).toBeNull();
|
||||
// Because the session was NOT all-skipped, the compare-before-write
|
||||
// probe is not reached; the raw row is written fresh over the
|
||||
// resurrected page. (The probe reads ACTIVE rows only — it never needs
|
||||
// to see through a tombstone, because a tombstoned base page never
|
||||
// reaches the all-skipped branch: this test is that proof.)
|
||||
expect(probeCalls).toEqual([]);
|
||||
expect(putCalls.length).toBe(1);
|
||||
expect((await engine.getRawData(slug, undefined, { sourceId: 'default' })).length).toBe(1);
|
||||
});
|
||||
|
||||
test('the compare probe fires only on an all-skipped (alive) re-run, and a content-equal row is not rewritten', async () => {
|
||||
const p = join(tmp, 'plain-session-3.jsonl');
|
||||
writePlainSession(p);
|
||||
const r1 = await runTranscriptsIngest(engine, baseOpts([p]));
|
||||
const slug = r1.slugsTouched[0];
|
||||
let putCalls: unknown[][] = [];
|
||||
const probeCalls = await spyEngine('getRawData', async () => {
|
||||
putCalls = await spyEngine('putRawData', async () => {
|
||||
const r2 = await runTranscriptsIngest(engine, baseOpts([p]));
|
||||
expect(r2.pages.skipped).toBe(1);
|
||||
expect(r2.pages.imported).toBe(0);
|
||||
});
|
||||
});
|
||||
expect(probeCalls.length).toBe(1);
|
||||
expect(probeCalls[0][0]).toBe(slug);
|
||||
expect(probeCalls[0][1]).toBe('transcript:openclaw');
|
||||
expect(probeCalls[0][2]).toEqual({ sourceId: 'default' }); // active rows only — no includeDeleted
|
||||
expect(putCalls).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('raw_data follows the page soft-delete', () => {
|
||||
test('after softDeletePage the session metadata is invisible; includeDeleted:true still reads it; restore brings it back', async () => {
|
||||
const p = join(tmp, 'plain-session.jsonl');
|
||||
writeFileSync(
|
||||
p,
|
||||
[
|
||||
JSON.stringify({ type: 'session', version: 3, id: 'plain-01', timestamp: '2026-08-09T10:00:00.000Z', cwd: '/tmp/plain' }),
|
||||
JSON.stringify({
|
||||
type: 'message',
|
||||
id: 'm-1',
|
||||
timestamp: '2026-08-09T10:00:01.000Z',
|
||||
message: { role: 'user', timestamp: '2026-08-09T10:00:01.000Z', content: [{ type: 'text', text: 'plain question' }] },
|
||||
}),
|
||||
].join('\n') + '\n',
|
||||
);
|
||||
const r = await runTranscriptsIngest(engine, baseOpts([p]));
|
||||
expect(r.sessionsImported).toBe(1);
|
||||
const slug = r.slugsTouched[0];
|
||||
expect((await engine.getRawData(slug, undefined, { sourceId: 'default' })).length).toBeGreaterThan(0);
|
||||
|
||||
expect(await engine.softDeletePage(slug, { sourceId: 'default' })).not.toBeNull();
|
||||
expect(await engine.getRawData(slug, undefined, { sourceId: 'default' })).toEqual([]);
|
||||
expect(await engine.getRawData(slug)).toEqual([]);
|
||||
expect((await engine.getRawData(slug, undefined, { sourceId: 'default', includeDeleted: true })).length).toBeGreaterThan(0);
|
||||
|
||||
expect(await engine.restorePage(slug, { sourceId: 'default' })).toBe(true);
|
||||
expect((await engine.getRawData(slug, undefined, { sourceId: 'default' })).length).toBeGreaterThan(0);
|
||||
});
|
||||
});
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user