Skip to content

fix(pages): correctly escape special chars for page-data - #181

Merged
cpojer merged 4 commits into
mainfrom
fix/page-data-script-escaping
May 6, 2026
Merged

cpojer merged 4 commits into
mainfrom
fix/page-data-script-escaping

Conversation

@TheAlexLichter

@TheAlexLichter TheAlexLichter commented May 5, 2026 •

Copy link
Copy Markdown
Member

Summary

Right now, serializePageData replaces "<" with "\\u003c" (and equivalent for other characters). Instead of an escaped character, this leads to a "<" in the emitted source (after template literal evaluation), so it is basically a no-op.

As a result, raw <, >, &, U+2028, and U+2029 characters leak unescaped into the inline <script id="__VOID_PAGE_DATA__" type="application/json"> payload.

Doubling the backslashes in the replacement values restores the intended \uXXXX escapes in the emitted source, so the inline JSON survives the script tag and round-trips through JSON.parse.

I also took the chance to refactor and dedupe the used code.

…ncate

`serializePageData` in the Vue / Svelte / Solid renderer modules is defined inside a
template literal that is later emitted as the SSR entry source. The replacement
strings used `"\\u003c"` etc., which the template literal evaluation collapses to
`"<"` in the emitted code; the JS parser then decodes that unicode escape,
leaving `replaceAll("<", "<")` -- a no-op. As a result, raw `<`, `>`, `&`,
U+2028, U+2029 leak into the inline `<script id="__VOID_PAGE_DATA__"
type="application/json">` payload, and any string in the props that contains
`</script>` (e.g. an HTML artifact persisted in user data) closes the tag early
and produces `JSON.parse: unterminated string` on hydration.

Doubling the backslashes in the replacement values restores the intended
`\uXXXX` escapes in the emitted code, so the inline JSON survives the script
tag and round-trips through `JSON.parse`. The React adapter's `serializePageData`
lives in a regular module file (not a template literal) and is unaffected.
@TheAlexLichter TheAlexLichter changed the title fix(pages): escape inline page-data so embedded </script> doesn't truncate fix(pages): proper special character escaping for inline page-data May 5, 2026
@TheAlexLichter TheAlexLichter changed the title fix(pages): proper special character escaping for inline page-data fix(pages): correctly escape special chars for page-data May 5, 2026
Regression test for the previous commit. Exports generateRendererModule
from the vue/svelte/solid pages plugins so a unit test can extract the
emitted serializePageData function, evaluate it, and assert that input
containing </script>, U+2028, U+2029, and `&` never leaks unescaped into
the inline JSON and round-trips through JSON.parse.

Without the fix in 3987931, all six assertions fail because the
single-backslash escapes collapse during template-literal evaluation
and the JS parser then decodes them back to the raw characters,
leaving the .replaceAll calls as no-ops.
The Vue/Svelte/Solid pages plugins each emit their renderer module as a
template literal and inlined an identical copy of serializePageData. That
duplication is what made commit 3987931 a three-line fix in three
different files, and it's also what made the bug possible in the first
place: the function only existed inside string-in-template-in-string
sandwiches, where one stray backslash collapses to a no-op replaceAll.

Move the function to packages/void/src/pages/serialize.ts (using the
single regex form React already had), expose it via the new
"void/pages-server" subpath, and have all four adapters import it
instead. The Vue/Svelte/Solid emitted modules now contain
`import { serializePageData } from "void/pages-server"` instead of an
inline copy, so the escaping logic lives in real source and can never
collapse during template-literal evaluation again.

Per-adapter regression tests added in the previous commit collapse to a
single packages/void/test/unit/serialize-page-data.test.ts that exercises
the real shared function. The temporary `export` on generateRendererModule
in each adapter (only added to make the per-adapter tests reachable)
goes away with them.
@TheAlexLichter
TheAlexLichter marked this pull request as ready for review May 5, 2026 12:01
The unit test in packages/void/test/unit/serialize-page-data.test.ts only
proves the function is correct in isolation; nothing exercised the wiring
(the `void/pages-server` subpath, the dist file, the literal string typed
into each adapter's emitted SSR module). A typo or a future
template-literal-collapse regression could slip past unit tests.

Add a `scriptProbe` to each adapter playground's shared-state middleware
holding the original attack payload (`</script><script>alert(1)</script>`
plus U+2028/U+2029 and `&`). Each adapter's existing "dev: SSR pages…"
integration test now also extracts the `__VOID_PAGE_DATA__` script body
via regex, asserts it contains no literal `</script>`, and JSON-parses it
to confirm the probe round-trips.

If `serializePageData` ever regresses, the embedded `<script>` closes
early, the regex captures truncated content, and JSON.parse throws —
catching the original bug end-to-end on all four adapters.
@cpojer
cpojer merged commit 40b9c33 into main May 6, 2026
9 checks passed
@cpojer
cpojer deleted the fix/page-data-script-escaping branch May 6, 2026 00:09
cpojer pushed a commit that referenced this pull request Sep 11, 2026
* feat(api): routing-after-tx go-live + guarded routing publishers

Rewrite deploy/rollback routing consistency, split out of the
Deploy-on-GitHub branch (PR #179):

- routing KV is written only AFTER the go-live DB commit; a failed
  in-tx check publishes zero routing (no rollback class)
- durable `routing_published` marker on deployments (migration 0026)
  + hourly live-routing reconciler heals degraded publishes
- all routing publishers serialize on the project FOR UPDATE lock and
  re-check active-ness before writing (deploy, rollback, domains,
  suspension, retention, cron sync, queue-token backfill)
- domain activation claims its row conditionally; deletion runs under
  the project lock; stale queue routes are swept uniformly
- rollback derives serving type from the target deployment's manifest,
  not the project's current type

Migration note: 0026_cuddly_lilith keeps its original journal identity
(when=1780982697858) so environments that already applied it (staging)
skip it and fresh environments apply it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): exempt explicitly-unpublished rows from the reconciler recency window

Review finding (P1): rollback to a target older than 24h clears
routing_published without touching deployed_at, so a failed post-commit
publish left the active deployment permanently invisible to the hourly
reconciler — dispatch would serve stale/missing KV forever.

The recency window now bounds only legacy NULL-marker rows (the one-time
backfill mass). Rows explicitly marked false (sole writer:
markRoutingUnpublished in the rollback go-live tx) are always eligible —
the set is bounded by the active-pointer join and self-clears on heal.
deployed_at stays untouched: it is ever-went-live history used by
retention/admin.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): treat a deleting/missing project as superseded in the routing publish chokepoint

A parked deploy/rollback publisher — or the hourly reconciler — resuming during
teardown (after teardownProject set status='deleting' and deleted the routing KV
entries, but before deleteProjectCascade removed the row) re-passed the
pointer-only active check in publishRoutingIfStillActive and re-created the
slug/domain:*/queue:* routes, leaving permanent orphan routes the reconciler
could never heal once the row was gone.

publishRoutingIfStillActive now re-reads projects.status under the project lock
(new lockProjectForPublish sibling, leaving the shared
lockProjectAndGetActiveDeploymentId untouched) and returns 'superseded' when the
row is missing or status='deleting'. getRecentlyLiveActiveDeployments also
excludes deleting projects so the reconciler never selects them.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): lock routing-suspension fan-out + handle rollback publish rejection

setProjectsRoutingSuspension did a lock-free per-key get→modify→put. A
suspender's pre-publish snapshot could overwrite a concurrent publisher's
fresh route after it set routing_published=true, leaving permanently stale
routing the reconciler skips (it heals only unpublished rows). Wrap the
slug + domain fan-out in one project FOR UPDATE lock tx — the same lock
publishers hold — so `suspended` is folded onto the re-read fresh route.
Closes the cursor "Unguarded suspension clobbers routing" finding and the
codex "Wire suspension updates through the guarded RMW" finding (same race).

The rollback handler's post-commit publishRoutingIfStillActive await sat
outside any catch: a transient Hyperdrive/lock error after the go-live
commit returned 500 for an already-committed rollback, prompting users to
retry a completed operation. Treat a thrown helper the same as a 'failed'
publish so the row stays routing-unpublished and the hourly reconciler
heals it; the endpoint returns success/degraded.

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

* fix(api): refuse domain activation while project is deleting

tryActivateDomain took the project FOR UPDATE lock but never re-read
status, so a pending-domain verification interleaving with
teardownProject could re-PUT domain:<host> for a project about to be
cascade-deleted, leaving an orphan route the reconciler can't heal
(teardown deletes slug/domain KV lock-free, then cascade-deletes rows
last). Swap lockProjectAndGetActiveDeploymentId -> lockProjectForPublish
and bail (write nothing, claim nothing) on a missing/deleting project,
mirroring publishRoutingIfStillActive's same-lock guard.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
cpojer pushed a commit that referenced this pull request Sep 11, 2026
…ers (#181)" (#191)

This reverts commit 2c436bf.

#181 was merged prematurely: CI (lint-and-check) was failing and codex
review threads were still unresolved. Reverting from main to re-land the
routing-consistency work after those are addressed.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
cpojer pushed a commit that referenced this pull request Sep 11, 2026
…Hub Actions) (#179)

* feat(api): Deploy on GitHub — GitHub App + remote builds (containers + GitHub Actions)

Rebased on feat/routing-consistency (#181); the routing-consistency
rewrite now lives there. This commit is byte-identical to the fully
reviewed pre-split head (tag backup/pre-split) outside four deliberate
changes:

- drizzle: migrations 0020-0025 squashed into 0027_github_deploy
  (final-shape tables, idempotent IF NOT EXISTS / DO-block FKs) so it
  orders AFTER #181's 0026 for fresh environments and no-ops on staging,
  which already has the tables
- container/Dockerfile: Bun install pinned (BUN_VERSION=1.3.14) and
  verified, instead of curl|bash latest
- ci.yml: temporarily also trigger on PRs to feat/routing-consistency
  so this stacked PR gets CI (drop when retargeted to main)
- framework: bump to 16c1065 (frozen-lockfile installs in the
  scaffolded GitHub Actions workflow)

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): re-check branch head after creating the Actions build row

Review finding (P2): a newer push landing between the OIDC pre-check
returning 'identical' and the build INSERT is invisible to the push
webhook's terminateBuildsForProject cleanup (no row exists yet), so a
stale run kept an ACTIVE build — and a live build-bound deploy token —
for a superseded commit.

After the row is committed, re-prove the sha is still the branch head
before minting. On any non-identical verdict the row is CAS-terminalized
('cancelled'); null is retryable (503) and the cancelled row does not
block the retry (partial-unique index covers only ACTIVE statuses). A
push after this re-check whose webhook is missed remains the documented
TTL-bounded limitation.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): stop the orphaned build container when start() rejects after launch (bump framework)

The base Container.start() launches the container, then runs onStart inside
blockConcurrencyWhile before resolving. Our onStart calls
markBuildBuildingIfStarting (a Hyperdrive write that can throw transiently), so
start() can reject AFTER the container is live. containerStarted flipped only on
the line after start(), so on that path the catch treated it as a pre-launch
failure, skipped teardown, and the container kept running the real `void deploy`
CLI with a live token while Postgres recorded the build failed — pinning a global
fleet slot until the ~75m idle net (enforceTimeout was never armed; the stale
reaper skips already-failed rows).

Flip containerStarted before awaiting start() (capacity errors still re-throw
before the stop block; token-mint throws still precede the marker), set the local
terminal status before teardown (matching enforceTimeout/cancelBuild so the
teardown-triggered onStop won't clobber it), and force-stop (SIGTERM→SIGKILL via
forceStopContainer) so a SIGTERM-ignoring build agent can't outlive the failure.

Also bumps the framework submodule to baa8edd (init/deploy CLI review fixes).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* docs(api): correct deploy-token TTL comments + bump framework

The OIDC GitHub Actions path sizes its deploy token to the plan build timeout
(deployTokenTtlSecondsForBuildMinutes) just like the container executor — it does
NOT fall back to the 15-min default. The old comments claimed the OIDC path used
the 15-min default, which is wrong and misread the actual behavior (Codex P2 on
init.ts:1988 rested on that stale comment). No runtime change.

Bumps framework to 51518c4 (drop the void init --github legacy-workflow migration).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): cancel in-flight builds on branch delete (token revocation)

When a push deletes the connected branch (after === ZERO_SHA), the
handler previously early-returned, leaving any queued/running build for
that branch holding a live deploy token able to publish the deleted SHA
until its <=65min token TTL / the hourly reaper. Now, after a DB-clock
fence and a confirmed-absent branch check, terminalize those builds
under a FOR UPDATE lock on the connection rows (serializing an in-flight
OIDC exchange), then cancel their DOs after commit.

Hardening from adversarial review:
- DB-clock fence (select now()) + ::timestamptz comparison so the Worker
  and Postgres clocks are never compared across a session-TZ offset.
- created_at re-stamp on active-build reuse so a pre-push fence spares a
  same-SHA recreate.
- getBranchExistence: confirmed 404 -> 'absent'; non-404 4xx / exhausted
  retries / transport errors -> 'unknown' (cancellation fails closed).
- Documented bounded limitation: the absence proof keys on the mutable
  repo name while cancellation keys on the immutable id (rename +
  name-reuse window; residual exposure bounded by the token TTL/reaper).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): bound the container build-agent log pipeline

pipeStream now splits child stdout/stderr on CR/LF/CRLF (was \n only) so
carriage-return progress frames flush as log lines instead of being held
in the partial-line tail until process exit, and force-flushes that tail
once it exceeds MAX_PARTIAL_LINE_CHARS (128KiB) so a terminator-free run
can't grow unbounded and OOM the standard-1 container. A trailing lone
\r is carried back to avoid a spurious empty line for a CRLF torn across
a chunk boundary.

Hardening from adversarial review:
- Cap the unflushed PUSH batch (pendingLines); evict the oldest fifth on
  flood so a bare-CR delimiter flood can't grow it without bound.
- Stop mirroring to stderr under backpressure (latch when write() returns
  false, reset on 'drain') instead of buffering a line per call.
- flushLogs is single-flight (concurrent callers join the in-flight POST)
  and the fetch carries AbortSignal.timeout, so a slow/hung DO can't
  accumulate in-flight POST bodies without bound.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): harden Deploy-on-GitHub teardown against token leaks + CF orphans

Addresses the two open PR #179 review threads plus the orphan-on-concurrent-
create class surfaced while verifying them. All changes are in packages/api.

P1 (build-agent.mjs:1025) — reap install-phase processes before deploy:
- After install closes and before the secret-bearing deploy child spawns,
  runBuild SIGKILLs every BUILDER_UID process by scanning /proc (no procps in
  the slim image), removing a postinstall daemon that could read the deploy
  child's /proc/<pid>/environ. Documented honestly as best-effort defense-in-
  depth — a process that re-forks after the one-shot sweep survives; the
  kernel-enforced fix is per-phase UID separation, and the residual is dominated
  by the accepted trust-split (void deploy runs untrusted build in-process).

P2 (db.ts:1749) — stop active builds before deleting their rows:
- Teardown terminalizes in-flight builds at its FIRST step (lockAndMarkDeleting,
  under the project FOR UPDATE) — revoking their deploy tokens — and stops their
  container DOs BEFORE any CF cleanup. deleteProjectCascade re-terminalizes under
  the lock as a gap-catcher. github_actions builds have no DO; the row delete
  revokes their token.

Finding-1 — deploy-token provisioning window:
- POST /:id/database and PUT /:id/database-url return 409 once status='deleting'
  (closes the common already-deleting case for the deploy-token + owner-self
  race).

Orphan-on-concurrent-create class (pre-existing; design-doc 0067):
- deleteProjectCascade now RETURNs the resource rows it deleted; teardown deletes
  the CF object behind any not already cleaned by the pre-cascade snapshot
  (cleanupRaceWindowResourceOrphans). Closes the row-committed orphan subset
  deterministically (cascade FOR UPDATE vs the INSERT's FK FOR KEY SHARE).
- Provisioning create paths (provisionBindings + both hyperdrive routes) now roll
  back a CF object they just created if the resources-row INSERT fails (concurrent
  teardown FK violation), closing the CF-create-before-row subset. Only self-
  created objects are rolled back; adopted already-exists objects are left alone.
  Residual: process death between CF create and compensation (async-reconciler
  territory, 0067).

Tests: +/proc reaper + parseProcStatusUid unit tests; delete terminalizes
in-flight builds + tears down container DO; race-window orphan sweep; cascade
returns deleted resources; create-path rollback (provision + route, incl. the
adopted-object negative). Full api suite: 60 files / 1476 tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* chore(api): strip session-internal review labels from comments

Removes opaque review-session finding/milestone tags (F/N/R/M/A/P/Q/Defect-
prefixed, e.g. F15-1, N4, A9, M3, Q4, Defect-A) from code comments, JSDoc, and
it/describe/test titles across packages/api. These referenced an internal
review's numbering and are meaningless to future readers; the substantive
explanation is preserved verbatim.

Comment- and test-title-only — no executable code, assertions, identifiers, or
string fixtures changed (verified via `git diff -U0`). Left in place: design-doc
numbers (0067), PR refs, SHAs, version strings, R2/SVG-path/URL-encoded string
literals, and tokens used with real meaning in prose.

fmt + lint + typecheck clean; api suite 1476 tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* fix(api): interrupt install on cancel + skip repo enumeration for all-repo installs

- build-agent: track the active build child (install OR deploy) so POST /cancel
  / SIGTERM interrupts an in-flight dependency install instead of letting it run
  to completion and burn the container slot (drops the vestigial trackChild flag)
- github: stop paginating GET /installation/repositories once page 1 reports
  repository_selection='all' and persist an empty array — the cache is never read
  for 'all' installs, so enumerating a large org wasted round trips + JSONB
- test: regression for the all-install early-break

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

* fix(api): refetch installation repos when an all-install narrows to selected

An `all` install caches an empty repositories array (it's never read while
selection='all'), so applying the installation_repositories add/remove delta
against it on an all→selected narrowing dropped the repos the user kept —
silently breaking getGitHubConnectionsByRepo / installationCoversRepo for them
(regression surfaced by f54395de, which made the all cache always empty).
Refetch the authoritative accessible set on that transition instead.

- extract listInstallationRepositories into github/installation-repos.ts, shared
  by the connect callback + the webhook (keeps it out of the route modules'
  test-mock boundary so both callers can import it)
- webhooks: on all->selected, mint an installation token + refetch the live repo
  list outside the FOR UPDATE tx; trust the refetched selection so a stale/
  redelivered event self-corrects
- test: regression for the all->selected refetch

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

* fix(api): skip repo-removal revocation when the install is all-repos

A stale all->selected installation_repositories redelivery can arrive after the
user switched the App back to `all`. The refetch then authoritatively reports
`all` (every repo covered), but the handler still ran the revocation loop on the
stale `repositories_removed` delta — cancelling in-flight builds + revoking valid
deploy tokens for repos that are still covered. Skip the revocation path whenever
the resulting selection is `all` (just sync the cache + selection). Fallout of
a37e4528 (the all->selected refetch).

- test: a stale all->selected redelivery (refetch reports all) leaves a
  still-covered repo's in-flight build untouched

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

* fix(api): serialize Actions build creation with teardown + forward commit metadata

createGithubActionsBuildWithinLimit now locks the projects row FOR UPDATE
first — before the users + github_connections locks — so the OIDC build path
acquires projects-before-connection, matching deleteProjectCascade /
lockAndMarkDeleting and the push path. Previously the builds INSERT took an
implicit projects FK FOR KEY SHARE *after* holding the connection FOR UPDATE,
inverting the lock order against a concurrent teardown (projects FOR UPDATE
then connection) → a 40P01 deadlock. The OIDC path was also the only
build-creation path with no deleting-status guard, so it could mint a deploy
token / orphan a `building` row for a project mid-teardown. The new
`project-deleting` outcome rejects that with a 409.

Forward GITHUB_SHA / GITHUB_REPOSITORY / GITHUB_REF into the container deploy
env. The container has no .git, so without GITHUB_SHA the deployment recorded
a NULL commit. The CLI reads GITHUB_SHA first, and GITHUB_* are not scrubbed,
so the build's own non-secret identity now reaches `void deploy`.

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

* fix(api): keep deleted/suspended installations terminal against stale created webhooks

upsertGitHubInstallation's conflict-update forced status='active' unconditionally,
so a delayed or redelivered installation.created arriving AFTER an
installation.deleted/suspend for the same id flipped the row back to active. The
connection resolvers gate only on status='active', so a removed/suspended App
could resume minting push/OIDC deploy tokens.

A genuine reinstall always gets a NEW installation_id (GitHub never reuses ids),
so it INSERTs — a created that conflicts with an existing row is always a stale
replay. The conflict-update now keeps deleted/suspended terminal via a CASE and
only forces active for non-terminal rows; only installation.unsuspend
(markGitHubInstallationStatus) clears a suspension. The OAuth callback path is
unaffected (fresh install -> new id -> INSERT).

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

* fix(api): interrupt source download on cancel + guard unsuspend against deleted revival

build-agent downloadSource spawned the `tar` extraction child directly and never
registered it as `activeChild`, so a POST /cancel during source download was a
no-op — the fetch + tar pipeline ran the full archive to completion before the
post-download gate bailed (install/deploy already interrupt promptly via
runChild). Track the tar child as activeChild, mirroring runChild: a cancel now
SIGTERMs it, which collapses the pipeline and aborts the in-flight fetch body
pull. Also bail early if a cancel landed during the fetch await.

The installation.unsuspend webhook flipped the row to active unconditionally via
markGitHubInstallationStatus, so a stale/redelivered unsuspend arriving after a
later installation.deleted revived a terminal row — the connection resolvers
gate only on status='active', so a removed App could resume push/OIDC deploys.
This is the same class as the stale-created guard (commit f77913cb) but on the
unsuspend path, which bypasses the upsert CASE. New unsuspendGitHubInstallation
helper performs a guarded suspended->active transition only; deleted stays
terminal. GitHub never reuses installation_ids, so an unsuspend on a deleted row
is always stale.

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

* fix(api): skip container build for deleting project + pin builder corepack toolchain

supersedeAndCreateContainerBuild (the push-path container build creator) locked
the projects row FOR UPDATE but only SELECTed its id and discarded it, never
re-reading status. A push landing after teardownProject flipped the project to
status='deleting' (but before the cascade deletes the connection) still enqueued
a container build — burning a scarce build slot, since neither the scheduler nor
the JIT recheck rejects a deleting project. Re-read status under the same lock
and return skipped='project-deleting', mirroring the GitHub Actions path
(createGithubActionsBuildWithinLimit). Lock order is unchanged (projects-first),
so the 40P01 deadlock class stays closed; the webhook call site already tolerates
a null build (no row enqueued, no scheduler poke).

Pin and activate pnpm@11.8.0 / yarn@1.22.22 into the build container's builder
COREPACK_HOME. A repo can have a lockfile but no packageManager field; with only
`corepack enable` the builder's corepack home is empty, so corepack downloaded
"latest" on every build — nondeterministic across image rebuilds and dependent
on a runtime fetch (the design docs 0010/0011 specified a corepack prepare that
was dropped). A root-level prepare would be a no-op since the builder uses its
own COREPACK_HOME, so the prepare targets that path. corepack still honors an
explicit packageManager pin; this only sets the no-pin default. Validated by a
real docker build + run as the builder uid.

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

* fix(api): keep deleted installations terminal against stale suspend webhooks

Rounds 5/6 guarded the installation.created (upsert CASE) and installation.unsuspend
(status='suspended' guard) paths, but the installation.suspend write was still
unconditional (markGitHubInstallationStatus). A stale/redelivered suspend landing
after a later installation.deleted walked the terminal row deleted->suspended,
which re-satisfied unsuspendGitHubInstallation's status='suspended' guard — so a
following stale unsuspend reactivated a removed App and the connection resolvers
(status='active' only) accepted push/OIDC deploys again.

New guarded suspendGitHubInstallation helper performs the suspend write WHERE
status != 'deleted'; the suspend webhook branch routes to it while the deleted
branch stays unconditional (deleted is the terminalizing write). GitHub never
reuses installation_ids, so a suspend hitting a deleted row is always stale. This
closes the last write in the install-lifecycle reactivation class.

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

* fix(api): serialize installation_repositories writes + fail fast on unresolvable Berry yarn

The installation_repositories handler read the cached repo set (getGitHubInstallation)
OUTSIDE any transaction, computed the added/removed delta, then blind-wrote it.
Two concurrent deliveries both starting from [A] could clobber each other —
persisting only [A,C] and losing B — after which the `@>` membership cache in
getGitHubConnectionsByRepo / installationCoversRepo skips builds for the lost
repo until the next selection refresh. Lock + re-read the install row FOR UPDATE
inside the tx and compute the delta against the lock-held set, so concurrent
deliveries serialize. The fast (no-revocation) path locks only the install row;
the revocation path locks githubConnections THEN the install row — the same
order as the deleted/suspend branch — so no new 40P01 deadlock class. The GitHub
refetch for an all->selected narrowing stays before the tx (no lock held across
a network call).

build-agent resolveInstall chose the yarn immutability flag from the lockfile
format, but corepack's unpinned default is Yarn Classic 1.22 — which ignores
Berry's `--immutable` and cannot parse a Berry `__metadata` lock. Pick the flag
by the yarn that ACTUALLY runs: a `.yarnrc.yml` yarnPath makes Classic re-exec
the bundled Berry release (--immutable, verified), a `yarn@` pin is honored, and
a Berry lock with neither pin nor yarnPath now fails fast with actionable
guidance instead of a confusing mid-install error.

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

* fix(api): detect Yarn PnP after install so generated .pnp.cjs picks the right deploy runner

The build agent snapshotted pnpPresent = existsSync(.pnp.cjs) right after
download, before the install step. A Yarn Berry PnP repo can gitignore .pnp.cjs
and have `yarn install` generate it, so the pre-install snapshot read false and
the deploy took the bare `npx void deploy` path — with no node_modules and no
active PnP runtime, the build children void deploy spawns couldn't resolve the
repo's dependencies.

Move the .pnp.cjs detection to after the install step (before the deploy phase).
pnpPresent's only consumers — the hasLocalVoid closure and the deploy-runner
branch — are both evaluated post-install, so the pre-install snapshot was
needless; the move also corrects hasLocalVoid's PnP branch (same variable) and
covers both committed and install-generated .pnp.cjs.

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

* fix(api): keep install repo membership on stale GitHub webhooks

upsertGitHubInstallation's conflict-update overwrote repositories /
repository_selection with the conflicting payload. GitHub never reuses
installation_ids, so a `created` that conflicts is always a stale redelivery:
a redelivered original `created` ([A]) could roll back a cache the
installation_repositories handler advanced to [A,B], or downgrade
all→selected — silently rejecting pushes/OIDC for the dropped repos until the
next refresh. INSERT seeds membership; installation_repositories is the
authoritative writer thereafter. Drop both columns from the conflict-update
set. Closes the codex "Preserve repo cache on stale install creates" finding.

installation_repositories:removed decided the all→selected refetch from the
pre-tx `existing` snapshot. A stale `selected` delivery that missed a
concurrent widen to `all` (refetched===null) could downgrade the locked `all`
row and revoke builds for still-covered repos. Re-read repository_selection
UNDER the lock; isStaleSelectedDowngrade keeps `all` and skips the build
revocation. Closes the codex "Base repo-selection refetch on the locked
installation" finding.

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

* fix(api): refresh installation membership on OAuth callback upsert

The conflict path of upsertGitHubInstallation deliberately drops
repositories/repository_selection because redelivered installation.created
webhooks carry stale lists. That guard is correct for the webhook caller
but wrongly suppressed the OAuth callback, which just refetched the LIVE
membership via listInstallationRepositories — so on reconnect /
setup_action=update, newly-added repos or a widen-to-all stayed rejected
by the connect/push/OIDC resolvers until the next webhook arrived.

Add an opt-in refreshMembership flag: the callback (authoritative,
just-refetched data) rolls the cache forward on conflict; the webhook
created path leaves it off, so its stale-created guard and generated SQL
are byte-identical to before. Selection write is NULL-safe.

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

* fix(deps): pin hono to 4.12.18 to match framework submodule

The rebase regenerated the lockfile from main's catalog (hono 4.12.26),
but #179's framework submodule (94b0d4e) bundles hono 4.12.18. The
dashboard links to that framework, so the two HonoRequest types diverged
(4.12.26 adds `bytes` + `[GET_MATCH_RESULT]`) and `vp run check` failed on
middleware/01.auth.ts and pages/auth/callback.server.ts. Pin the catalog
back to 4.12.18 so platform and framework share one hono type.

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

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
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.

2 participants