Skip to content

Security audits: AI scans for deploys and a scan-before-public gate - #886

Merged
Brooooooklyn merged 93 commits into
mainfrom
feat/security-audits
Nov 25, 2026
Merged

Brooooooklyn merged 93 commits into
mainfrom
feat/security-audits

Conversation

@Brooooooklyn

@Brooooooklyn Brooooooklyn commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

What this adds

Security audits for the self-hosted platform: each go-live deploy gets an AI security scan, and an admin can require a clean scan before a project goes public (Zero Trust turned off). Off by default (securityAudits capability). Design doc: platform/meta/design-docs/0095-security-audits.md.

void deploy ──► go-live ──► scan row (pending_input) ──► SecurityScanScheduler DO
                                                              │  caps, round-robin
                                                              ▼
              scan input (T1 GitHub diff / T2 built diff / T3 full)
                                                              │
                                                              ▼
       scanner container (no internet) ── model calls ──► model proxy ──► @cf / AI Gateway
         Engine B (Void loop, default @cf deepseek-v4.1-flash-1017)        budget meter
         Engine A (Claude Code) · Engine C (Codex)
                                                              │
                                                              ▼
              ingest (one transaction, attempt fence) ──► findings ──► email / webhook / GitHub check
                                                              │
                                                              ▼
                      public gate: Zero Trust stays on until no open urgent findings

Phases

Phase Milestones What users get
1 M1–M24 capability, policy, tables (migration 0065), scheduler, input builder, Engine B, ingest, project + operator APIs, emails, public gate + bypass, admin pages, read-only page, void project security … CLI, deploy notice, docs
2 M13b, M25–M31 Engines A/C wiring, rescan/backfill/sweeps, @cf fallback, digest + webhooks, per-plan caps, GitHub check, page/dashboard forms, runtime checks on a throwaway copy, secret findings, SARIF
3 M32–M36 void project security check (local tree), BYOK keys, per-project rule, severity edits, docs

Public gate rules

  • Only urgent (critical/high) findings block.
  • fixed needs a rescan of a new deploy; false_positive / accepted_risk unlock at once.
  • An admin can bypass the scan with a reason. The bypass is recorded and the platform admin gets an email. A bypass never skips open urgent findings (409).
  • The policy can't be turned on while platform Zero Trust is off.

Spikes (live on Cloudflare, cleaned up)

The one-off spike scripts are not in this PR. Their conclusions are in platform/meta/design-docs/0095-security-audits.md ("Phase 0 spike conclusions").

Spike Result
S1 network lock, S1b image copy S1 not recorded (S2/S3/S11 re-check egress); S1b worked with a ~2 MB image only
S4 Engine B quality deepseek 10/10 bugs, 8/8 valid, $0.18 median → default; glm-5.3 4/10, fails
S5 static confirm 20/20 planted bugs confirmed with a trace
S7 inputs 100% server files readable (React/Vue/Svelte/Solid)
S8 cost/time under $3 median, p95 under 20 min
S9 refusal mapping 24/24 (after fixes)
S10 gateway no stored bodies, no cache
S11 red team 160/160 (after fixes, incl. a Glob/Grep path escape)
S13 throwaway copy ready in ~9 s, outbound blocked, not reachable from the internet
S2/S3/S6 Engines A/C quality blocked: no AI Gateway credits on the test account

Open before release

  • Engine A/C image digests are null until the images are published to ghcr at release, so Engines A/C can't be picked yet.
  • S2/S3/S6 need AI Gateway credits for real quality/cost numbers.
  • S12 legal questions (Anthropic/OpenAI terms, shipping the Claude Code binary in an image, naming) are listed in the design doc.

Checks

  • vp check: clean
  • vp test run: see CI

🤖 Generated with Claude Code

Brooooooklyn and others added 30 commits November 18, 2026 13:02
…ler stub

Adds the securityAudits capability (deployment schema 7, missing reads as off)
and the SecurityScanScheduler Durable Object stub with its migration tag.
Binds the scheduler only for runtimes that ship it, and blocks a CLI rollback
to a runtime from before this release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ge source

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds the hard-coded security model list with prices, badges, engines and
reserves, plus the installation policy type, defaults, limit ranges and
error codes. Writes use a strict parser; the stored row is read with a
lenient reader so a retired or newly added model does not turn audits off.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds the 11 security audit tables (settings, scans, findings, events,
public requests, bypasses, spend, rejections, notifications) in 0065.
Mode, engine and max-cap lists are checked against the M2 policy; the
month check ignores the session time zone; bypasses only from D50 states.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds /operator/v1/security/{policy,status} with revision checks under a lock,
a plan preview, a fresh-probe check to turn on, and Off canceling queued scans.
The preview says where projects go when a model is blocked under a third-party
default. Operator audit records known ids only. Design doc lists the M6/M8/M9 follow-ups.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Runner reads task.json and the input tar on stdin, runs hunt and verify
sessions through the model proxy, and writes findings.json then status.json.
Pax xattrs are skipped as bytes, SIGTERM during the tar read writes timed_out,
paths with control characters are refused, and any non-stop failure retries once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tainer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…tlement probe

Controller Worker with one Durable Object per scan attempt or probe, egress lock,
and result files read as the scanner user without following symlinks.
Per-installation provisioning (controller, container app, owned gate) and probe
checks 1-6; turning the policy on checks the request first, then re-runs the probe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The scan model proxy checks the fence, model, call and token caps, holds the
worst case on both spend rows, and settles to tokens x list price.
It refuses provider-run tools, filters anthropic-beta, stops on tokens below
the provider minimum, and keeps the worst case for unreadable answers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Each live deploy writes its scan row in the go-live transaction, then copies
inline Worker modules, queues the row and pokes the scheduler after `done`.
Compensation finishes the row with the modules when a deploy is still live.
Staged input stays while a waiting scan points at it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The scheduler claims queued scans round-robin by owner, reserves budget,
starts them through the controller and retries a failed start once.
Hourly jobs reap, re-poke, skip backlog, sweep, keep retention and probe.
Ends, requeues and cancels give the reserve back in the same transaction.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
T2/T3 input builder: source maps, filters, third-party, redaction, phrase check,
memory and backlog, streamed to the runner as a tar.
Changed files the input cannot hold go to the backlog, never counted as seen.
Modules are read one at a time and the tar is encoded as it is read.
Builder and runner share one set of input limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
T1 reads the head tarball (equal 8 MiB R2 parts, one key per call) after
the same GitHub authority check a managed build runs. Only changed unread
files cap a scan; unchanged ones are dropped, so big repos stay complete.
The bundle is parsed once, and skipped tar entries count toward the limits.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
S2/S3 gain --local-gateway: the engines run in local Docker behind a model-proxy
stand-in that holds the token and calls the gateway REST route. S10 checks what the
gateway keeps (no bodies, no cache). Third-party calls hit the credits 402.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Take the runner result in one transaction: findings, events, reopen and
stale-scan rules, not-seen hint, fix check, ledger and the no-changes path.
The cap limits new keys only, server leads have their own key space, and a
diff scan keeps the base ledger.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…an caps; fix controller PATH

A bad verify session now leaves the candidate a lead and the scan
incomplete instead of dropping every finding. Engine B repairs harmless
report slips and takes JSON sent as text. The controller PATH gains
/usr/sbin:/sbin so useradd works. Default token caps go to 1.2M in and
120k out after spikes S4/S8.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
… scanner images

Engine A runs the Claude Agent SDK with three read tools; Engine C runs the
Codex SDK with only the void-scan MCP server. Both ask the model proxy why a
session ended without a report. The SDKs live in two images with exact pins,
lockfiles and a drift test. The proxy takes the gateway model name and never
passes an upstream 401 to an engine. Spike lessons: is_error with a 402 is
credits, Codex retry caps are 0.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
After the runner and cap changes deepseek-v4.1-flash-1017 meets every S4
bar (10/10 bugs, 8/8 valid runs, no false crit/high) and glm-5.3 does not
(4/10 bugs, 4/8 valid runs). The default model is unchanged.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
S4 rerun on VoidZero: deepseek 10/10 bugs, 8/8 valid, median $0.18, p95 15.7 min
(pass); glm-5.3 4/10, 4/8 valid (fail). glm-5.3 stays selectable.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Add the per-project security status, findings, comment, resolve, reopen,
scans, model and page-link routes, with reader and CI views that hide detail.
Scans and model writes answer 501 while the capability is off; the page link
uses `?t=` for M19 to redeem.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ate and bypass

Adds the outbox, recipients, copy and senders, queued with the change and sent by the
scheduler alarm. Types email finding severity, pins the raise-to-critical rule with a test,
and covers the hourly poke. Tests that expected the old default model now name the new one.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…e catch-up)

Public requests are judged at ask, ingest, resolve, cutover, rollback, bypass and hourly.
Review fixes: one exposure scan per deployment, the hourly backstop rotates and shares the
run's routing budget, gate-off cancel writes its event and email, and held copy names the cause.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Adds operator routes for the security budget, findings, scans, public requests and bypass.
The budget write needs the capability, the bypass preview shares the real refusal rules,
and the month totals use a UTC month start and stay installation-wide.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Adds the Security pages, banner and nav badge, plus project Security and bypass controls.
Mark all as seen posts the newest bypass time the page showed, clamped to the real newest row.
The admin bypass route stays open with the capability off, like the operator route.
Adds a test per write route, each asserting its audit row.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Bypass races (#72, #89, #93, #94) and gate vs Zero Trust (#64, #90).
Strict policy reader answers 503 on disable.
Deploy and rollback keep working while a request is open.
Operator 202 and dry-run shapes, project 202 reply.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
A signed CLI link opens a path-scoped cookie page at /security/projects/:slug.
Urgent findings load apart from the capped open list, headings use real totals,
and a cut list points to the CLI. The route uses the same gate as the project
API (member, owner not suspended). Tests cover suspended and deleted accounts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Adds status, list, show, comment, resolve, reopen, scans, model, budget and open.
The status route now returns the open public request.
Tests cover every command path, the public request view by role, and the capability-off read.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…tatus

Add 'void project zero-trust bypass' with a reason and a confirm prompt.
Show the held public request and its urgent finding ids in status.
Help, the no-args hint and docs/reference/cli.md are updated.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Managed deploys print the scan state and open urgent findings after the deploy is live.
One read with a 5 s limit; any error, 404 or timeout prints nothing and keeps the exit code.
A deploy with unpublished routing still gets the notice. Rows sort critical first, then oldest.
The caller-role "Fixed?" line is a documented gap in the plan.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Brooooooklyn and others added 3 commits November 24, 2026 12:21
The lint pass sorted the probe's inputFiles with localeCompare, while
judgeContainer sorts the expected list with a plain .sort() and compares
the two as JSON. Sort the probe side in code-unit order too, so both
sides match for any seeded name and any ICU build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
# Conflicts:
#	packages/void/src/cli/project-args.ts
#	platform/packages/proxy/test/unit/email.test.ts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Brooooooklyn added a commit that referenced this pull request Nov 24, 2026
## How this was found

We tested the security-audits work (PR #886) end to end on a live
self-hosted Void platform. One test app was a Vite app that uses
`voidPlugin()` and has no backend. Deploying it broke the site and made
server files public. The bug is not part of the security-audits feature,
and the same code is on `main`, so it gets its own PR.

## Repro

1. Make an app whose `package.json` has `vite-plus` and `void`.
2. `vite.config.ts` uses `plugins: [voidPlugin()]`.
3. Add only `index.html` and `main.js`. No `routes/`, `pages/`, or other
backend folders.
4. Run `void deploy` to a Void platform. The CLI prints "Static SPA
deploy".
5. Make the project public and fetch it.

| Request | Expected | Actual (main) |
| --- | --- | --- |
| `/` | 200, `index.html` | **404** |
| `/client/index.html` | not a path | 200 |
| `/ssr/index.js.map` | not uploaded | **200**, the full server source
map (about 324 KB, with `sourcesContent`) |
| `/ssr/wrangler.json` | not uploaded | **200** |

Uploaded files on main: `client/index.html`, `client/assets/*`,
`client/.vite/manifest.json`, `ssr/index.js`, `ssr/index.js.map`,
`ssr/wrangler.json`, `ssr/.vite/manifest.json`.

Side effect: the server bundle has a new random build key on every build
(`packages/void/src/router/compile.ts:881-883`), so a redeploy of
unchanged code uploaded a changed `ssr/index.js.map` and made a new
deployment (and, with security audits on, a new scan) each time.

## Root cause

```
void deploy
  └─ detectPreset(root)                 packages/void/src/cli/preset.ts
       1. --dir?            no
       2. SSG dep?          no
       3. backend files?    no
       4. vite in deps?     yes  ->  outputDir = dist   <-- wrong for voidPlugin
```

`packages/void/src/cli/preset.ts:277-285` (step 4) always used `dist`.
That is right for plain Vite, which writes `dist/index.html`. But
`voidPlugin()` splits the build:

```
dist/
├─ client/   browser files, index.html   <- should be uploaded
└─ ssr/      server bundle, .map, wrangler.json   <- must not be uploaded
```

So the whole `dist/` went up, and `/` had no `index.html`.

The same step is used by the managed platform path (`cli/deploy.ts`),
the native Cloudflare static path (`resolveCloudflareStaticPreset` in
`cli/deploy-cloudflare-static.ts`), and by configured
`inference.appType: "spa" | "static"` without `outputDir`
(`resolveStaticDeployPreset` in `cli/deploy-helpers.ts`). All three get
the fix.

## Fix

In step 4, when the package depends on `void`, use `dist/client`. Plain
Vite apps keep `dist`. `void init` adds `voidPlugin()` to Vite apps, so
a `void` dependency means the build has the split layout. App type stays
`spa`, same as before; only the folder changes.

The docs for `inference.outputDir` now say the default is `dist/client`
for projects that depend on `void`.

## Tests

- `packages/void/test/unit/preset.test.ts`
- `uploads only dist/client for a Vite app built with void and no
backend`: vite-plus + void, only `index.html` + `main.js` ->
`dist/client`, `spa`.
- `uses dist/client for a configured static app built with void`:
`inference.appType: "spa"` with no `outputDir` -> `dist/client`.
- Both fail on main (they get `dist`) and pass with the fix. The plain
Vite and Vite+ tests still expect `dist`.
- `vp run test`: all groups pass except one timeout in
`platform/packages/api/test/integration/admin-dashboard.test.ts` ("keeps
runtime-log client fields when navigating away and back", 5 s, dashboard
UI, not touched here). It passes when run alone.
- `vp fmt --check`, `vp lint`, and the `void` package typecheck pass. In
a fresh worktree, `vp check` also reports missing
`playground/*/.void/tsconfig.json` files, which are generated by a
playground build and are unrelated.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Brooooooklyn added a commit that referenced this pull request Nov 24, 2026
…908)

## Summary

When a queued deploy is refused at the last check, the deploy stream now
shows the real reason (for example "Zero Trust protection for this
project is not ready … then retry") instead of always saying "Admitted
deployment is no longer authorized or valid".

## How it was found

Found during a live end-to-end run of a self-hosted platform while
testing the security-audits work (PR #886). The bug is not part of that
feature: it is in the existing durable deploy path, so it gets its own
PR.

In the test, a project was flipped to public with `void project
zero-trust public` while a `void deploy` was still waiting for
admission. The flip won the race, as expected. The deploy then failed,
which is also expected, but the stream said:

```
■ Admitted deployment is no longer authorized or valid
```

The user cannot tell from this that a plain retry is the fix. A retry
right after did succeed.

## Repro

1. On a platform with Zero Trust enabled, protect a project.
2. Start `void deploy` for that project.
3. While it waits for admission, run `void project zero-trust public`
for the same project.
4. Watch the deploy stream.

| | Message on step `authorization` |
| -------- |
-------------------------------------------------------------------------------------------------------------------
|
| Expected | `Zero Trust protection for this project is not ready: The
project public exception is still reconciling. … then retry.` |
| Actual | `Admitted deployment is no longer authorized or valid` |

The same happens for any other refusal at run time, such as a build that
was canceled while its deploy sat in the queue ("This build is no longer
active. Start a new build to deploy the current version.").

## Root cause

```
void deploy ──► admit (200, receipt) ──► queue ──► executeQueuedDeployment
                                                     │
                                                     ▼
                                     handleManifestOnlyDeploy (in-process)
                                                     │
                                        409 {error, message}   ◄── real reason here
                                                     │
                                                     ▼
                         status != 204 ──► body never read
                                       ──► "Admitted deployment is no longer authorized or valid"
```

`platform/packages/api/src/routes/deploy.ts:585-607` (on main) runs the
deploy handler again for the queued work. When the handler answers
anything other than 204, the code marks the deployment failed and
appends an `error` event with a fixed text. It never reads the response
body, so the handler's own `message` (or `error`) is dropped.

## Fix

- `platform/packages/api/src/routes/deploy.ts`: new
`rejectedAdmissionReason()` reads the handler's response when it is
JSON, up to 8 KiB, and takes `message`, or `error` when there is no
`message`. The result (cut to 4096 characters) is used both for the
deployment's `error_message` and for the `error` event. If the body is
missing, not JSON, too large, or has neither field, the old generic text
is still used.
- The step stays `authorization` and the status stays `failed`, so
nothing else in the flow changes.
- Non-JSON bodies (such as an NDJSON receipt stream) are not read; their
stream is canceled.

These messages are the same ones a direct (non-queued) deploy already
returns to the CLI, so no new information is exposed.

## Tests

`platform/packages/api/test/integration/deployment-execution.test.ts`:

- New: "reports the Zero Trust reason when protection changes while a
deploy waits". Admits a deploy, then makes the Zero Trust routing check
report "public exception is still reconciling" before the queued run.
Checks that `error_message` and the last `error` event carry the Zero
Trust reason with the retry hint.
- Extended: "rejects a queued deployment whose bound build was revoked
before execution" now checks that the message is the handler's "This
build is no longer active…" text and that the step is `authorization`.

Both fail on main (they get the generic text) and pass with this change.
Ran:

- `vp test run --project 'platform-api-integration*'
platform/packages/api/test/integration/deployment-execution.test.ts`: 55
passed
- `vp run --filter ./platform/packages/api typecheck`
- `vp check`: format and lint pass; the only errors are missing
generated `tsconfig` files in playgrounds that this worktree did not
build
- `vp run test`: still running when this PR was opened; CI covers the
full suite

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Brooooooklyn added a commit that referenced this pull request Nov 24, 2026
…rade (#909)

## How it was found

During a live end-to-end run of the self-hosted platform while testing
the security audits work (PR #886), `void platform upgrade` crashed
halfway through and left the platform paused. The crash is not related
to security audits. It is in the upgrade command's PostgreSQL lifecycle
lock, which every install, upgrade, repair, enable and disable uses.

## Repro

1. Have a self-hosted platform whose database closes idle connections
(seen with PlanetScale Postgres).
2. Run `void platform upgrade --runtime <path> --yes`.
3. While the CLI is in "Deploying the dispatch service" (minutes with no
database traffic), the server resets the idle lock connection.

## Expected vs actual

| | |
| --- | --- |
| Expected | The upgrade fails with a clear message, the normal failure
handler runs and records the failed operation, and the operator reruns
the command. |
| Actual | The process dies with `▲ Something went wrong` / `node:events
Unhandled 'error' event` / `Error: read ECONNRESET ... Emitted 'error'
event on Client instance`. No failure handling runs. Operator API calls
return 503 "the platform is paused for an upgrade or repair" and
`platform status` shows "Saved operation: upgrade — deploying" until the
upgrade is rerun. |

## Root cause

`packages/void/src/cli/platform-installer-database.ts:207-237`
(`acquirePlatformDatabaseLifecycleLock`) checks out one `pg` client with
`pool.connect()` and holds it for the whole lifecycle command, because
the lock is a session advisory lock. It never adds an `'error'` listener
to the client or the pool.

`pg` removes the pool's own error listener from a client while it is
checked out. When the socket is reset, `pg` emits `'error'` on the
client. With no listener, Node throws it as an unhandled `'error'` event
and the process exits.

```
pool.connect() ──► client held for whole upgrade
                     │
   deploy Workers (idle minutes)
                     │
   server resets socket ──► client.emit('error')  ──► no listener ──► process exits
```

## Fix

In `acquirePlatformDatabaseLifecycleLock`:

- Add `pool.on('error')` and `client.on('error')`. The client listener
keeps the first error.
- Run lock queries through a small `QueryConnection` wrapper. After a
lost connection, each lock call (checkpoint, verify, migrate, reads)
fails with `platform: The PostgreSQL connection that holds the lifecycle
lock was closed (read ECONNRESET). Rerun the command to continue.` That
error goes through the normal upgrade failure path.
- On release after a lost connection, skip `pg_advisory_unlock`, because
the server already ended the session lock with the connection. Release
the client with the error so `pg` destroys it instead of pooling it.
Then end the pool. Release no longer throws a second error that would
hide the first.

Keeping traffic paused after a failed cutover is intended: the failure
handler keeps the routing gate closed and the next run continues from
there. This PR does not change that. It only replaces the crash with the
normal failure path and a clear rerun message.

Not changed: `platform-auth-recovery.ts` opens its own short-lived lock
connection. It is a separate command and is left for a follow-up if
needed.

## Tests

- New test in `packages/void/test/unit/platform-database-lock.test.ts`:
a lock client and pool that are `EventEmitter`s. Emitting `'error'`
(ECONNRESET) no longer throws. Later `verifyDatabase` and
`readAdministratorSetup` reject with the clear `platform:` message.
Release resolves, sends no SQL, and destroys the client. The test fails
on `main` with the unhandled `'error'` event.
- Updated the `pg` mocks in `platform-database-lock.test.ts` and
`platform-database-ssl.test.ts` to accept `on()`.
- Ran the exact test file, `vp check` (no errors outside playground
`.void/tsconfig.json` files that only exist after a playground build),
and `vp run test`. All `packages/*` groups pass. The platform groups
passed or timed out only while the test machine was put to sleep (about
980 s gaps in the power log); the platform integration tests that use
this lock (`zero-trust-uninstall`, `platform-bootstrap`) pass when run
alone. CI runs the full suite.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Brooooooklyn added a commit that referenced this pull request Nov 24, 2026
…base (#910)

## How it was found

A live end-to-end run of the self-hosted platform, done while testing
security audits (PR #886), ran about 15 queued scans on one install. The
scans themselves were fine. The database was not. This bug is outside
the security-audits feature, so it gets its own PR.

The install's PostgreSQL server had `max_connections = 25`. The
Hyperdrive config the installer created had `origin_connection_limit =
60` (the Cloudflare default for that account). `pg_stat_activity` showed
18+ Hyperdrive connections whenever we could get in.

## Repro

1. Use a PostgreSQL server with a small `max_connections` (25 here; many
hosted starter plans are this size).
2. `void platform install` with "Void creates the Hyperdrive".
3. Put load on the platform: about 15 queued scans plus normal API use.
4. From your machine, connect with `VOID_PLATFORM_DATABASE_URL` (`psql`,
or `void platform upgrade`).

| | |
|---|---|
| Expected | Hyperdrive stays below what the server accepts, so a direct
connection still gets a slot. |
| Actual | `53300 remaining connection slots are reserved for roles with
the SUPERUSER attribute` for 15+ minutes at a time. The API also
returned an intermittent 500 ("Failed to read project security", on a
`deployment_operations` query). |

## Root cause

On `main`, the installer creates the Hyperdrive with no
`origin_connection_limit` and never changes it later:

- `packages/void/src/cli/platform-installer-resources.ts:287` calls
`client.createHyperdrive(...)`.
- `packages/void/src/cli/platform-cloudflare.ts:1009`
(`createHyperdrive`) posts only `name`, `caching` and `origin`.
- `git grep origin_connection_limit` finds nothing in `packages/*/src`
or `platform/packages/*/src`.

So Cloudflare's default limit applies. When that is above the server's
non-superuser slots, the pool can take every slot.

## Fix

```
install / repair / upgrade
  └─ verify uncached Hyperdrive (existing)
  └─ fit Hyperdrive to database (new)
       slots = max_connections - superuser_reserved_connections - reserved_connections
       limit = max(5, slots - 5)
       live limit > limit ?
         created by Void → PATCH origin_connection_limit = limit
         adopted         → print a warning only
```

- `readConnectionSlots` runs on the lifecycle-lock connection the
installer already holds, so it opens no extra connection
(`platform-installer-database.ts`). `reserved_connections` exists only
on PostgreSQL 16+; older servers count it as 0.
- `getHyperdriveConfig` now reads `origin_connection_limit`, and a new
`setHyperdriveOriginConnectionLimit` sends the PATCH
(`platform-cloudflare.ts`).
- `platform-hyperdrive-connections.ts` holds the rule. It only ever
**lowers** the limit, so it never sends a value above the account plan's
maximum (Free is about 20). If Cloudflare reports no limit, it leaves
the config alone.
- Called from `platform-install-provisioning.ts` right after the
existing Hyperdrive check, so existing installs are fixed by their next
`void platform repair` or `upgrade`.
- With the e2e numbers (25 max, 3 superuser slots) the limit becomes 17,
which leaves 5 slots for direct connections.
- Docs: the database sizing paragraph in
`docs/guide/platform/installation/prerequisites.md` now says what Void
does and what is left to the user.

## Tests

- `packages/void/test/unit/platform-hyperdrive-connections.test.ts`
(new): 60 → 17 for a 22-slot database; no change when the limit already
fits or is not reported; minimum of 5; adopted Hyperdrive only gets a
warning; no calls when the lock cannot read slots.
- `platform-cloudflare.test.ts`: parses `origin_connection_limit` and
sends the PATCH body.
- `platform-database-lock.test.ts`: `readConnectionSlots` runs against
real PostgreSQL (PGlite) through the lock wrapper.
- Test fakes for the installer client gained the new method.
- Ran: the focused files, `vp check` (only errors are missing generated
`playground/*/.void/tsconfig.json` in a fresh worktree; none in changed
code), and `vp run test`. The 8 failures in that run were timeouts in
`platform/packages/api` integration tests while another worktree ran the
same suite; those 6 files pass when rerun alone.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Brooooooklyn added a commit that referenced this pull request Nov 24, 2026
…tails (#911)

## How this was found

During a live end-to-end run of a self-hosted platform, done to test the
security audits work (PR #886), two operator CLI text outputs looked
wrong. Neither bug is part of that feature, and both exist on `main`
today, so this PR fixes them on their own.

## Bug 1: hyphens in data keys turn into spaces

### Repro on `main`

On any platform, preview a full worker rollback in text mode:

```
void platform worker rollback-all --plan
```

The preview's `versions` object is keyed by worker name (`proxy`,
`email-gateway`, `api`, ...).

- **Expected:** `email-gateway: <version id>`
- **Actual:** `Email gateway: <version id>`

With the security audits branch, `void platform security models --block
@cf/zai-org/glm-5.3 --plan` printed `@cf/zai org/glm 5.3: 1`, which is a
model ID nobody can copy back into a command.

### Root cause

`fieldLabel` in `packages/void/src/cli/operator-cmd.ts:113` (on `main`)
turns every object key into a readable label: it splits on spaces, `_`
and `-`, lowercases, and capitalizes the first word. That is right for
field names like `createdAt` or `project_id`, but wrong for keys that
are data.

### Fix

API field names are camelCase or snake_case. A small character check
(`isFieldName`, no regex) now treats any key with another character
(`-`, `/`, `@`, `.`, `:`, space) as data and prints it unchanged. Field
names are still labelled as before (`createdAt` -> `Created at`,
`project_id` -> `Project ID`).

## Bug 2: plain refusals print "Partial result:"

### Repro on `main`

On a self-hosted platform, run any hosted-only worker command in text
mode:

```
void platform worker list
```

The API replies `501 capability_unavailable` with `details: {
capability: "hosted-platform-operations" }`
(`platform/packages/api/src/operator/worker-operations.ts:20`).

- **Expected:** the message, then `Details:` and the details.
- **Actual:**
  ```
platform: Manage this self-hosted Void platform with `void platform
upgrade`.
  Partial result:
  { "capability": "hosted-platform-operations" }
  ```

"Partial result" tells the operator that some work was done, but nothing
ran. Other refusals with details hit the same path, for example
`revision_conflict`, `plan_has_accounts` and
`ownership_transfer_blocked`.

### Root cause

`packages/void/src/cli/cli-main.ts:103` (on `main`) prints `Partial
result:` for every `OperatorClientError` that has `details`, whatever
the error code.

### Fix

`isPartialResult` prints `Partial result:` only when the error code is
`partial_failure` or the details say `partial: true`. Any other error
prints `Details:`. The details are still printed in full, and `--json`
output does not change.

## Tests

- `packages/void/test/unit/operator-cli.test.ts`: `humanLines` keeps
`@cf/zai-org/glm-5.3`, `email-gateway` and `api.example.com` unchanged
and still labels `createdAt` and `project_id`.
- `packages/void/test/integration/operator-cli.test.ts` (real CLI
subprocess against a stub HTTP server):
- `worker rollback-all --plan` prints `email-gateway: version-gateway`.
- A `501 capability_unavailable` refusal prints `Details:` and not
`Partial result`.
- The existing rollback partial-failure test still expects `Partial
result:`.
- Without the fix, all three new tests fail. With the fix, both test
files pass.
- `vp run --filter ./packages/void typecheck`, `vp lint` and `vp fmt
--check` pass on the changed files.
- `vp run test`: everything this PR touches passed. Some platform API
integration tests timed out because the machine was heavily loaded (load
average above 100). None of them use the changed code except
`operator-cli-e2e`, which passed on rerun. The rest passed on rerun or
with a longer timeout.
- In this fresh worktree, `vp check` reported only "Invalid tsconfig"
errors for playgrounds whose `.void/tsconfig.json` had not been
generated yet.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Brooooooklyn and others added 20 commits November 24, 2026 14:02
Named types in place of anonymous object and open dictionary types
(no-known-value-widening), and a reasoned exception where a function
returns raw input for its caller to validate (no-unknown-returns).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ot its timing

The timing bound from a85a179 still failed under the full suite: the
slice-first path took 7-8x the plain id there, inside the 8.5-13.5x of
the old order. Spy on String replace/replaceAll instead: no part of the
id longer than the 128 cap may reach one. Swapping sanitizeForLog back to
replace-then-slice fails it (5242880 > 128).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A deploy scan a public request took over keeps holding its staged
  input after it ends before the copy (budget skip, cancel), so asking
  again can scan it instead of falling to needs_deploy.
- A scan that ends while the platform is disabled or staged leaves the
  public request open and changes no Access; the hourly re-check judges
  it after enable. One shared check with the scheduler stop.
- The coverage label says "static only (runtime copy not made)", so
  status, the page and the panel show a failed runtime copy.
- The page's public request row for a budget-held request names the
  cap and the way on (raise, or ask again after a raise), as the CLI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A protected project whose first deploy is still in cutover no longer
  goes public at once: the request waits and follows that deploy live.
  If the deploy never goes live, the request passes (nothing exposed).
- A changed Worker module whose mapped sources did not change is read
  as built code ("built-only-change N"), so it is never "no changes".
- A scan that left first-party files unread (binary, over 16 MB, bad
  path) holds the gate as held_no_result / unread_files. A bypass can
  skip it; asking again queues no rescan. Registry, unverified
  third-party and client-asset drops do not hold. CLI, page, API,
  emails and dashboard say so.
- A model call lost with no status or error code keeps its worst-case
  charge; a known HTTP error or coded Workers AI error still costs 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- A first-party file a scan could never send (over 16 MB, not text,
  bad path) is noted again on later diff scans while its bytes stay
  the same, so an unrelated redeploy does not clear the unread_files
  hold. The record lives in never-sent.json next to sources.json;
  scans without it read as none. Renamed modules with the same bytes
  keep the note; third-party code is never carried.
- An Anthropic stream that ends before its final usage, or carries an
  error event, keeps the worst-case charge.
- A call that waited for a rate slot reads the caps and the scan fence
  again, so a cap lowered meanwhile applies to it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Narrow non-null assertions, type unknown returns, name widened
dictionary types, posix path imports in the scanner runner, and
compare functions on sorts, following main's own fixes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Some lib versions type TextEncoder.encode() with a shared buffer, which
fails the dispatch test typecheck in CI.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Shared fixtures for the security tests: policy, scan and finding
  rows, roles, Zero Trust seed, bindings, staged scan input, the gate
  fakes, Durable Object storage, engine helpers and CLI status/project
  helpers, in place of copies across ~25 files.
- Integration tests that only repeated a unit-tested rule keep one case
  per wiring path; pure-function blocks move to unit files.
- it.each tables, fake timers for real waits, bulk inserts, a sparse
  file for the 33 MB limit, and a budgetSkipCopy table test.

Tests only; no source change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The spike scripts, images and seeded apps were one-off checks. Their
results now live in design doc 0095 ("Phase 0 spike conclusions").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Merge scenarios that share a setup and drop wording, email text, display
and repeated validation cases. Each design doc invariant (I1-I13), the
scanner lockdown and refusal tests, and the native Workers Free checks
keep one strong test. Files we only extended go back to main where the
current source still passes them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Share repeated queries, copy and parsing; inline one-caller layers; drop
dead exports, unused options and API uninstall code nobody called (the
CLI does the uninstall); merge the SDK session plumbing of Engines A
and C; shorten comments. The design doc now describes the design as
built (677 lines, was 2,487). Each area was checked hunk by hunk
against the previous head for behaviour changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Brooooooklyn
Brooooooklyn merged commit 1f8c75b into main Nov 25, 2026
22 checks passed
@Brooooooklyn
Brooooooklyn deleted the feat/security-audits branch November 25, 2026 14:48
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant