diff --git a/.dockerignore b/.dockerignore
index 4b242c5bd..ebd86a220 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -41,8 +41,6 @@ apps/email/client/build
apps/desktop/resources
apps/cli/.cli-payload
.dev-secrets.json
-# The sample mail environment contains generated credentials, keys and mail.
-apps/email/.dev-mail
data
# VCS + CI
diff --git a/.env.example b/.env.example
index fb8123bc7..e0073b4fb 100644
--- a/.env.example
+++ b/.env.example
@@ -251,8 +251,7 @@ GITHUB_APP_SLUG=openship-io
# Set these in the deployed API environment. Both Compose stacks load this
# root .env; they do NOT load apps/api/.env.saas (used by dev:saas).
# Use the production account's credentials for the production SaaS.
-# Optional complete API mount override. Unset uses the Oblien SDK default.
-# OBLIEN_API_URL=https://your-proxy.example/api/v1
+# OBLIEN_API_URL=https://api.oblien.com
# OBLIEN_CLIENT_ID=
# OBLIEN_CLIENT_SECRET=
# Optional public base-image pack for NEW managed Cloud spaces only.
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index be0ad9138..eaa8f7546 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -28,10 +28,6 @@ concurrency:
# unmergeable forever with no visible reason.
jobs:
- website-image:
- name: Website image
- uses: ./.github/workflows/website-image.yml
-
actions-runner:
name: Actions execution
permissions:
@@ -154,7 +150,6 @@ jobs:
command: >-
RUN_DOCKER_E2E=1 bun run --cwd apps/api test:e2e
test/e2e/platform-import-data.e2e.test.ts
- test/e2e/platform-import-project.e2e.test.ts
# Separate independent daemons keep real-Docker coverage within the job
# budget. Tests remain serial inside each daemon to preserve isolation.
- suite: Compose cutover and rollback
@@ -177,7 +172,6 @@ jobs:
test/e2e/image-volume-persistence.e2e.test.ts
test/e2e/image-gc-concurrent-build.e2e.test.ts
test/e2e/image-refresh.e2e.test.ts
- test/e2e/local-image-refresh.e2e.test.ts
- suite: Security advisories
command: >-
RUN_DOCKER_E2E=1 bun run --cwd apps/api test:e2e
@@ -192,7 +186,6 @@ jobs:
test/e2e/static-fallback.e2e.test.ts
test/e2e/route-protection.e2e.test.ts
test/e2e/edge-not-found-page.e2e.test.ts
- test/e2e/edge-upstream-down-page.e2e.test.ts
- suite: Kubernetes manifests
command: >-
RUN_KUBERNETES_E2E=1 bun run --cwd packages/adapters test
@@ -217,13 +210,6 @@ jobs:
- name: Checkout
uses: actions/checkout@v7
- # Native engine fixtures run Node workers; keep their runtime explicit
- # instead of inheriting whichever Node version the runner image adds.
- - name: Setup native test runtime
- uses: actions/setup-node@v6
- with:
- node-version: '22'
-
- name: Setup Bun
uses: oven-sh/setup-bun@v2
with:
@@ -249,14 +235,6 @@ jobs:
working-directory: apps/email/client
run: bun install --frozen-lockfile --ignore-scripts
- - name: Verify scoped agents against the released Mindwire daemon
- if: matrix.suite == 'Other packages'
- env:
- OPENSHIP_ASSISTANT_E2E: "1"
- run: >-
- bun run --cwd packages/platform test
- test/assistant-agents.e2e.test.ts test/assistant-remote.test.ts
-
# Run every workspace test, with the large API suite split across runners.
# Direct Vitest runs and Turbo's stream mode expose progress immediately.
# The complete API test/e2e/** suite also runs in release-gate.yml.
@@ -278,7 +256,7 @@ jobs:
# matrix must fail this check; no individual shard can make the PR green.
test:
name: Test
- needs: [test_suites, actions-runner, website-image]
+ needs: [test_suites, actions-runner]
if: ${{ always() }}
runs-on: ubuntu-latest
timeout-minutes: 2
@@ -287,10 +265,9 @@ jobs:
env:
TEST_SUITES_RESULT: ${{ needs.test_suites.result }}
ACTIONS_RESULT: ${{ needs.actions-runner.result }}
- WEBSITE_RESULT: ${{ needs.website-image.result }}
run: |
- if [ "$TEST_SUITES_RESULT" != "success" ] || [ "$ACTIONS_RESULT" != "success" ] || [ "$WEBSITE_RESULT" != "success" ]; then
- echo "::error::Test suites: $TEST_SUITES_RESULT; Actions execution: $ACTIONS_RESULT; Website image: $WEBSITE_RESULT"
+ if [ "$TEST_SUITES_RESULT" != "success" ] || [ "$ACTIONS_RESULT" != "success" ]; then
+ echo "::error::Test suites: $TEST_SUITES_RESULT; Actions execution: $ACTIONS_RESULT"
exit 1
fi
@@ -402,35 +379,3 @@ jobs:
- name: Run webmail client tests
working-directory: apps/email/client
run: bun test
-
- # Unit tests do not exercise the Docker dependency layout or the release
- # bundle's dev-origin scan. Build the same artifact that ships to users.
- - name: Set up Docker Buildx
- uses: docker/setup-buildx-action@v3
-
- - name: Build production webmail image
- run: docker buildx build --load --file apps/email/Dockerfile.webmail --tag openship-webmail:ci .
-
- - name: Verify production webmail startup
- run: |
- set -euo pipefail
- container="webmail-readiness-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
- trap 'docker logs "$container"; docker rm -fv "$container" >/dev/null' EXIT
- docker run -d --name "$container" --network none \
- -e SESSION_ENCRYPTION_KEY="$(openssl rand -hex 32)" \
- -e BRANDING_ADMIN_TOKEN="$(openssl rand -hex 32)" \
- openship-webmail:ci
- for attempt in $(seq 1 30); do
- if docker exec "$container" bun -e \
- 'fetch("http://127.0.0.1:4080/health").then(r => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))'; then
- docker exec "$container" bun -e '
- const response = await fetch("http://127.0.0.1:4080/");
- const html = await response.text();
- if (!response.ok || !html.includes("/assets/")) process.exit(1);
- console.log("Production webmail serves its health endpoint and client assets.");
- '
- exit 0
- fi
- sleep 1
- done
- exit 1
diff --git a/.github/workflows/release-gate.yml b/.github/workflows/release-gate.yml
index 7a34602bb..fee238c02 100644
--- a/.github/workflows/release-gate.yml
+++ b/.github/workflows/release-gate.yml
@@ -34,10 +34,6 @@ permissions:
actions: read
jobs:
- website-image:
- name: Website image
- uses: ./.github/workflows/website-image.yml
-
geoip:
name: GeoIP freshness
uses: ./.github/workflows/geoip.yml
@@ -100,12 +96,6 @@ jobs:
# The API network tests spawn Bun directly. Test the runtime shipped by
# the API image and release bundle, including its TLS and WebSocket paths.
- - name: Setup native test runtime
- if: steps.resume.outputs.reused != 'true'
- uses: actions/setup-node@v6
- with:
- node-version: '22'
-
- name: Setup Bun
if: steps.resume.outputs.reused != 'true'
uses: oven-sh/setup-bun@v2
@@ -236,24 +226,18 @@ jobs:
# https://github.com/actions/runner-images/issues/15005
runs-on: ${{ matrix.scope == 'fast' && 'ubuntu-22.04' || 'ubuntu-latest' }}
# Files remain serial within each disposable daemon. Split the growing
- # ordinary suite across four hosts so it fits the gate without relaxing tests.
+ # ordinary suite across two hosts so it fits the gate without relaxing tests.
timeout-minutes: ${{ matrix.scope == 'fast' && 45 || 30 }}
strategy:
fail-fast: false
matrix:
include:
- scope: fast
- label: fast 1/4
- shard: 1/4
+ label: fast 1/2
+ shard: 1/2
- scope: fast
- label: fast 2/4
- shard: 2/4
- - scope: fast
- label: fast 3/4
- shard: 3/4
- - scope: fast
- label: fast 4/4
- shard: 4/4
+ label: fast 2/2
+ shard: 2/2
- scope: heavy
label: heavy
shard: ""
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 78063d002..c6f37c80c 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -411,9 +411,7 @@ jobs:
label: Windows x64
find: "-name *.zip"
asset: Openship-win32-x64.zip
- # Keep the installer toolchain stable. Ubuntu 26.04's RPM 6 changes
- # the build directory layout expected by electron-installer-redhat.
- - os: ubuntu-24.04
+ - os: ubuntu-latest
label: Linux x64
find: "-name *.AppImage -o -name *.deb -o -name *.rpm"
asset: Openship.AppImage
@@ -1078,7 +1076,7 @@ jobs:
fi
else
gh release create "${TAG}" \
- --title "OpenShip ${TAG}" \
+ --title "Openship ${TAG}" \
--notes-file "${NOTES_FILE}" \
${PRERELEASE_FLAG} \
"${CORE_ASSETS[@]}"
diff --git a/.github/workflows/website-image.yml b/.github/workflows/website-image.yml
deleted file mode 100644
index 4be13e784..000000000
--- a/.github/workflows/website-image.yml
+++ /dev/null
@@ -1,42 +0,0 @@
-name: Website image
-
-on:
- workflow_call: {}
- workflow_dispatch: {}
-
-permissions:
- contents: read
-
-jobs:
- build:
- name: Production website build and startup
- runs-on: ubuntu-latest
- timeout-minutes: 30
- steps:
- - uses: actions/checkout@v7
- - uses: docker/setup-buildx-action@v3
- - name: Build the shipped website Dockerfile
- env:
- GITHUB_TOKEN: ${{ github.token }}
- run: >-
- docker buildx build --load --progress=plain
- --secret id=github_token,env=GITHUB_TOKEN
- -f apps/web/Dockerfile -t openship-website:verify .
- - name: Verify public pages from the production image
- run: |
- set -euo pipefail
- container="openship-website-check-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"
- trap 'docker logs "$container" || true; docker rm -f "$container" >/dev/null 2>&1 || true' EXIT
- docker run -d --name "$container" -e HOSTNAME=0.0.0.0 -e PORT=3000 -p 127.0.0.1::3000 openship-website:verify
- binding="$(docker port "$container" 3000/tcp)"
- base="http://${binding}"
- for attempt in $(seq 1 30); do
- if curl -fsS "$base/" -o /tmp/website-home.html; then break; fi
- sleep 1
- done
- test -s /tmp/website-home.html
- for path in / /ar /docs /docs/getting-started/installation /features /compare /mail /download /changelog /llms.txt; do
- curl --fail --silent --show-error --location "$base$path" -o /tmp/website-response
- test -s /tmp/website-response
- echo "Verified $path"
- done
diff --git a/.gitignore b/.gitignore
index e2a2ede04..5c5f64566 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,7 +10,6 @@ dist/
out/
# fumadocs generated content source (apps/web/.source) — compiled from source.config.ts
.source/
-apps/web/.share-feature-art.json
# Self-hosted server release bundle (apps/api/scripts/build-release.ts)
apps/api/release-dist/
# Desktop staged payload (apps/desktop/build/stage.ts)
diff --git a/CHANGELOG.md b/CHANGELOG.md
index af00e1cf6..d8e5ee0e3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,206 +1,10 @@
# Changelog
-All notable changes to OpenShip. Versions follow [semver](https://semver.org);
+All notable changes to Openship. Versions follow [semver](https://semver.org);
the in-app updater surfaces critical advisories from `release-advisories.json`.
Runtime security notices use the signed feed published from `security-advisories.json`.
-## 1.0.1
-
-**Recommended update** for self-hosted startup, application image updates, and
-private GitHub repository access. This patch also fixes postmaster password
-rotation metadata and preserves referral attribution through Cloud deploy links.
-
-### Deployments and connections
-
-- **Application updates** — accept requests with an empty body when the action
- takes no options. Continue validating malformed JSON and required payloads (#1817).
-- **Container image refresh** — pull the current image when refreshing a mutable
- tag, and keep verified local images available for redeploys. Report failed
- refreshes before replacing a running service (#1816, #1819).
-- **Registry credential checks** — record confirmed login rejections and preserve
- the previous credential status when the registry response is inconclusive (#1816, #1819).
-- **Private GitHub repositories** — restore the connected-server token fallback
- for authorized self-hosted repository reads on GitHub.com. A local server
- without credentials no longer prevents selecting an eligible connected server
- (#1821, #1822).
-- **Custom PHP base images** — run build-time dependency and setup steps as root
- when the base image defaults to a non-root user. Keep the app running as
- `www-data` (#1810).
-- **Swarm network setup** — wait for Docker to allocate a new overlay network
- before checking its driver and encryption settings.
-
-### CLI and mail
-
-- **macOS service reinstall** — wait for launchd to unload the previous service
- and verify the replacement is running before reporting success (#1808).
-- **CLI shutdown during startup** — stop the API process when the foreground
- supervisor receives a stop signal, releasing the port and local database lock (#1809).
-- **Postmaster password rotation** — record the password change timestamp together
- with the new hash when rotating through the CLI or API (#1825).
-
-### Cloud and website
-
-- **Cloud deploy referrals** — retain the referral code through the deploy link
- and Cloud plan selection (#1806).
-- **Social previews** — use page-specific share cards across the website and
- documentation (#1824).
-
-### Upgrade notes
-
-- **Component updates** — update the API, dashboard, Desktop and CLI for your
- installation. This patch adds no control-plane database migrations.
-- **Image refreshes** — use Refresh images when you want a new image for a
- mutable tag. A normal redeploy can reuse the local image.
-
-## 1.0.0
-
-OpenShip 1.0 brings a refreshed dashboard, edge maintenance and custom pages,
-deploy links, and scheduled mail workflows. Includes every change since 0.9.12,
-with more reliable builds, imports, billing and recovery.
-
-**Recommended update:** administrators should update all OpenShip components. This
-release closes an authorization flaw that allowed ordinary organization members
-to invoke administrative operations, including host command execution.
-
-### Security and access
-
-- **Administrative authorization** — Require administrative authority across HTTP, SDK,
- native and MCP access. Scoped tokens remain bounded by their owner's current organization
- role, including after demotion. Preserve explicitly delegated, resource-scoped
- administration (#1783, #1784).
-- **Hostname sign-in** — Choose a sign-in page or the browser's native authentication prompt
- for self-hosted hostnames. Customize sign-in HTML and session duration, revoke sessions,
- and see enabled protection directly on domain cards.
-- **Actions tracing** — Update the Actions worker to OpenTelemetry 1.47.0, fixing bypassed
- attribute-length limits in its tracing dependency.
-- **Release build isolation** — Keep generated local mail credentials and runtime caches out
- of image build contexts. Bundle the shared assistant client and its dependency patch so
- release builds do not depend on a sibling checkout or baked development URLs.
-- **Website image verification** — Include the website's client-message generator in its
- Docker build, and verify the production website image and its public pages before release.
-
-### Edge pages and routing
-
-- **Edge maintenance** — Serve maintenance HTML directly from the edge while the application
- keeps running. Restore normal routing when maintenance is disabled.
-- **Custom error pages** — Upload HTML pages and assign error statuses, with server defaults
- and project or hostname overrides. Customize unmatched-host and direct-IP pages.
-- **Authentication header limits** — Accept larger authentication response headers and
- returning cookies at the edge, with bounded defaults and preserved custom buffer settings
- (#1763).
-- **Domains & Routes** — Organize Domains & Routes into routing, access, proxy, and page
- controls, with inline protection settings, HTML previews, and visible loading and retry
- states.
-- **CLI domain targeting** — Target the correct project service and port when adding domains
- from the CLI. Keep primary domains, aliases and www redirects consistent when editing
- routes.
-
-### Deployments, imports and recovery
-
-- **Shareable deploy links** — Add shareable deploy links and `openship launch`, carrying
- the selected repository and deployment intent through sign-in and installation.
-- **Independent service copies** — Copy selected services to the same server or another
- server as independent projects. Validate dependencies and port bindings, preserve separate
- volumes, and improve restoration and rollback if a transfer fails. Keep application
- instance scaling distinct from independent copies.
-- **Compose change review** — Review Compose changes in a shared before/after dialog and
- apply the exact reviewed revision without repeating setup. Preserve deployment options and
- saved overrides, mask credentials, and require a new review if source changes (#1796).
-- **Private registry guidance** — Explain private-image pull failures with the affected
- image and a direct link to registry connections. Preserve public-image recovery and
- distinguish registry credentials from GitHub repository access (#1798).
-- **Compose environment values** — Reveal and hide service environment values through the
- shared Compose editor while retaining the existing permission checks (#1771).
-- **Multi-repository Railway imports** — Import Railway projects with multiple repositories
- as native services and project connections, preserving source ownership and private
- service wiring.
-- **Compose web ports** — Show container ports declared with Compose `expose`, explain how
- to publish a TCP port for a web domain, and handle protocol suffixes and port ranges.
-- **Folder deployments** — Improve folder deployment names, scan errors and streamed
- uploads. Resolve template placeholders consistently in service ports, and explain recovery
- when duplicate containers block deployment.
-- **BuildKit cache retention** — Retain warm BuildKit caches and reduce remote cleanup
- overhead without dropping build ownership, cancellation or capacity checks.
-- **Empty-volume backups** — Back up verified empty Docker volumes and bind directories
- alongside populated sources. Refuse missing sources and preserve errors for unavailable
- storage.
-- **Redis Sentinel readiness** — Verify every Redis Sentinel has discovered the writable
- primary, its replicas and the full voting group before reporting replicated databases
- ready.
-- **Controller relocation** — Fence event-stream admission while relocating the controller,
- restore access when it resumes, and link server preparation to its deployment progress.
-- **Mail engine updates** — Preserve the mail host's configured ignored IP addresses when
- updating its engine.
-
-### Mail and agents
-
-- **Scheduled mail and snoozing** — Schedule messages, cancel queued mail with Undo Send,
- and snooze conversations. Recover interrupted or temporarily failed wake-ups, including
- messages moved or deleted before their wake-up time.
-- **Mailbox agents and MCP** — Connect mailbox-scoped agents and MCP clients with encrypted
- state, isolated runtimes, scoped permissions and explicit approval for sending mail.
-- **Assistant workspace** — Improve the agent workspace, shared conversation rendering,
- connection setup, and empty and error states. Add the OpenShip plugin directory submission
- metadata.
-
-### Cloud, billing and CLI
-
-- **Oblien provider API** — Move the Oblien integration to SDK 3.2.0 and the provider's
- native versioned VM API. Preserve saved VM identities, customer metadata and purchased
- offers; validate scoped credentials against the selected VM.
-- **Cloud checkout recovery** — Recover unfinished Cloud purchases instead of creating
- duplicate unpaid spaces. Open checkout after its payment URL is ready and retain a
- fallback action.
-- **Renewals and pricing** — Keep billing accessible during pending renewals and show
- payment warnings in Plans & billing. Align monthly and yearly pricing across the website
- and dashboard.
-- **Cloud setup recovery** — Recover repeated signup attempts during Cloud linking and
- improve first-admin recovery and Compose managed-edge setup.
-- **CLI install and sign-in** — Keep the installed service's existing ports when `openship
- up` runs again. Support CLI login through public instance URLs and use Node.js for the
- container-to-host connectivity probe.
-- **Cloud update notices** — Limit the managed Cloud update banner to verified
- workload-security notices.
-
-### Dashboard and website
-
-- **Dashboard refresh** — Refresh billing, monitoring, jobs, backups, connections, server
- and agent screens with shared illustrations, compact controls and theme-aware surfaces.
-- **Service controls** — Improve service inspectors and copy/scale flows, put actions before
- runtime details, and replace native disclosure markers with shared icon controls.
-- **Avatar and project icons** — Add avatar and project icon URL settings, with inline
- editing, previews and reset.
-- **Marketing site and docs** — Refresh landing, Cloud, mail, download, migration and
- app-catalog pages; improve Arabic headlines, language navigation and documentation
- navigation.
-- **Comparisons and Cloud information** — Expand product comparisons, feature pages and
- search discovery, and publish Cloud SLA, support and privacy information.
-
-### Upgrade notes
-
-- **Component updates** — Update the API and all its replicas, dashboard, Desktop, CLI and
- mail components together. This release includes database migrations; retain a current
- instance and database backup before updating.
-- **Organization roles** — Ordinary organization members no longer have implicit
- administrative access. Review membership roles and scoped grants for integrations that
- perform admin actions.
-- **Oblien provider rollout** — Cloud operators must coordinate this release with the
- matching Oblien `/v1` API, database, gateway and scoped-credential rollout. Review old
- unversioned `OBLIEN_API_URL` and gateway overrides, and verify existing-VM access before
- directing customers to the upgraded provider.
-- **Edge requirements** — Maintenance, custom edge pages and hostname protection require the
- updated self-hosted edge. These controls do not protect direct application ports or
- hostnames outside their configured scope.
-- **Service copies and database scaling** — Independent service copies are separate
- deployments. Managed database replicas and failover use their existing database scaling
- flows.
-
-## 0.9.12
-
-**Critical update** for build-secret protection, database upgrade repairs and
-backup/restore reliability. Includes all changes since 0.9.11, with reviewed
-source-image update PRs, platform imports, mail improvements and a translated
-website.
+## Unreleased
### Build security
@@ -208,129 +12,23 @@ website.
embedding values in Dockerfiles or image history. Mask configured values in streamed
logs, error summaries and failure notifications, including split and multiline output.
Preserve Cloud worker limits, parallel server builds and cleanup after cancellation.
-- Attribute REST audit events to the personal access token used, and audit token
- reads through the existing authorization path.
-- Preserve private edge-vhost permissions and verify access with unprivileged
- workers. Keep tunnel hostnames out of unsupported password-protection flows.
-### Runtime and source updates
+### Image updates
- Keep image services with missing deployment digests visible as unverified. Inspect the
running image through the existing deployment runtime to detect moved tags, with bounded
reads and no deployment-row writes. Show unavailable update status without an update badge.
-- Propose Dockerfile and Compose image changes through reviewed GitHub pull
- requests. Check repository access first and guide users to reconnect or update
- their GitHub installation when the required permissions are missing.
-- Apply security fixes to managed runtime versions instead of repeatedly refreshing
- an unchanged image. Distinguish a runtime that is absent from a failed probe.
-
-### Deployments and infrastructure
-
-- Allow webhook and CLI deployments to approve reviewed Compose source changes
- through the shared approval flow.
-- Keep branch and Compose-path controls available after an unsuccessful first
- scan, reject blank required build commands, and offer Static Site for folder uploads.
-- Keep token-authenticated repository clones on HTTPS even when a server's global
- Git configuration rewrites GitHub URLs to SSH.
-- Recover orphaned builds through shared worker ownership, preserve application
- runtime/log access when adding services, and scope shared image-export paths.
-- Scale managed build-cache budgets with available disk and expose server cache
- settings. Improve local image exports without sharing another build's output.
-- Let edge upgrades finish safely after an SSH disconnect. Preserve owned mounts
- in imported Cloud workloads and explain host paths that cannot be imported safely.
-- Support hosted Jobs on Manage-connected SSH servers. Match BullMQ repeatable
- jobs by name so changing a cron schedule removes the previous schedule.
-- Accept bounded YAML aliases in imported GitHub workflows, show the latest run
- for every workflow, and avoid duplicate GitHub-owned workflow webhook payloads.
-- Recover failed installed-CLI updates and verify release installation and updates
- on disposable VPS instances before publishing images and packages.
### Domains
-- Configure static HTML, JSON or text responses on a domain through its normal
- route editor, including maintenance and verification responses without an app container.
- Avoid rewriting unchanged edge route files and repeating remote reads during a
registration. Preserve exact file contents and permissions while retaining route
validation, reloads, certificate activation and transactional rollback.
- **DigitalOcean DNS** — connect a DigitalOcean token in Settings → Connections to preview
and apply a custom domain's records and issue DNS-verified HTTPS automatically, as with
- Cloudflare. Each record OpenShip creates is paired with an `_openship-owner` TXT marker,
- so removing a domain deletes only OpenShip's own records.
-
-### Imports, backups and database upgrades
-
-- Improve platform imports, including Railway and Vercel setup, source and
- destination review, progress reporting and cancellation.
-- Keep migration environment fields visible while entering missing secrets, with
- a plain section heading instead of a nested disclosure that collapses during editing.
-- Preserve source project boundaries during platform imports: one project contains
- its native services, private DNS, encrypted service environments and separate volumes.
- Keep service environment values scoped correctly during source builds too.
-- Carry imported custom domains and aliases through the existing migration routing
- flow, pending normal verification. Show DNS cutover guidance and replacement
- notices for Railway and Vercel URLs in review and saved migration progress.
-- Restore portable instance exports with their server credentials and workspace
- ownership. Normalize restored data for the destination schema and keep the
- instance import and server selection views consistent.
-- Repair missing workspace and security-advisory fields on upgrades, including
- databases whose earlier migrations were already marked as applied.
-- Serialize backup execution per destination to prevent connection exhaustion.
- Recover orphaned Cloud backup activities through the existing ownership checks.
-- Complete local mail backups and portable restores through the shared backup
- orchestration, including target-server mail configuration and real mail round trips.
-- Prevent browser autofill of backup destination credentials and keep destination
- menus visible outside their cards.
-
-### Mail
-
-- Preserve mail logs and Fail2ban ban history across engine updates, and remove
- Dovecot's stale PID file before startup.
-- List all signed-in mailboxes and keep account menus usable when they overflow.
-- Correct webmail message colors in light/dark themes and when printing, and
- refresh security dependencies.
-- Protect support intake and add mailbox sender blocking.
-
-### Assistants
-
-- Reuse managed agent setup for custom API connections and report the actual
- runtime setup state.
-- Find agent CLIs installed outside the macOS GUI PATH, restore public BuildKit
- pulls, and correct scoped Claude startup.
-- Allow reviewed repository patches to delete regular files through the existing
- review and validation flow.
-- Add OpenShip plugins for Codex and Claude Code.
-
-### Dashboard, billing and website
-
-- Keep the shared destination dropdown available with one server or Cloud plan,
- with Add server in its menu across deployment and migration flows.
-- Refresh deployment state after navigation and browser resume. Unify project
- settings and shared environment controls with the existing service views.
-- Keep plan overview, usage and payments together under Plans & billing, align
- Cloud plan presentation across the website and dashboard, and retain payment
- recovery for expired renewals.
-- Improve deployment, verification and cancellation emails, and standardize the
- Referral experience.
-- Translate website content into the existing supported languages, with localized
- URLs, navigation and product screenshots. Correct Arabic layout and preserve
- English framework names. Documentation remains in English.
-- Add migration guidance for teams moving an existing app, group website
- navigation, and provide a direct Start on Cloud action.
-- Use the BytesMap SDK for unified Cloud telemetry and remove PostHog.
-
-### Upgrade notes
-
-- Update the API (including all replicas), dashboard and Desktop app together.
- This release includes control-plane database migrations; keep a current
- instance/database backup before upgrading.
-- Build-secret protection applies to new builds. Rebuild older application images
- to use the updated build flow; upgrading does not rewrite existing images.
-- Dockerfile and Compose image pins remain controlled by the repository. Review
- and merge a source-update PR when the fix requires a source change, then deploy
- that revision. Refreshing an unchanged pin does not change its runtime version.
-- Update the mail engine as well to receive mail startup, log persistence and
- restore fixes.
+ Cloudflare. Each record Openship creates is paired with an `_openship-owner` TXT marker,
+ so removing a domain deletes only Openship's own records.
## 0.9.11
diff --git a/SECURITY.md b/SECURITY.md
index 29b19ad67..87c2474ab 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -57,12 +57,6 @@ violation.
## Scope
-Organization owners and administrators can perform host administration. Ordinary
-members retain read/write access but cannot perform operations requiring `admin`,
-including server shell execution. Restricted users require explicit resource grants;
-scoped tokens also respect their user's current built-in role. Host commands execute
-as the server's configured account, so delegate server administration accordingly.
-
In scope — all Openship components:
- Managed Openship Cloud
diff --git a/apps/api/.env.saas.example b/apps/api/.env.saas.example
index 0c1556ce6..a4f391f91 100644
--- a/apps/api/.env.saas.example
+++ b/apps/api/.env.saas.example
@@ -31,8 +31,7 @@ BETTER_AUTH_SECRET=change-me-in-production
INTERNAL_TOKEN=change-me-32-byte-random-hex
# Required for cloud deployments.
-# Leave unset to use the installed SDK's default API version.
-# OBLIEN_API_URL=https://your-proxy.example/api/v1
+OBLIEN_API_URL=https://api.oblien.com
OBLIEN_CLIENT_ID=
OBLIEN_CLIENT_SECRET=
# Optional: enable only after this software preset is published on your provider.
diff --git a/apps/api/Dockerfile b/apps/api/Dockerfile
index 626d17807..b65fca256 100644
--- a/apps/api/Dockerfile
+++ b/apps/api/Dockerfile
@@ -15,12 +15,11 @@ RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache
FROM oven/bun:1.4.4@sha256:1d22548f177f4ff38e0c15baa3c2c46c6c2060ba2d1bc573bb4720b407548f1d AS dependencies
WORKDIR /app
-COPY package.json bun.lock bunfig.toml pnpm-workspace.yaml ./
+COPY package.json bun.lock pnpm-workspace.yaml ./
# Preserve workspace paths without making installation depend on source edits.
# Email's postinstall also installs its two nested packages.
COPY --parents apps/*/package.json packages/*/package.json apps/email/*/package.json apps/email/*/bun.lock ./
COPY patches/ ./patches/
-COPY vendor/ ./vendor/
RUN --mount=type=cache,target=/root/.bun/install/cache \
bun install --frozen-lockfile
diff --git a/apps/api/assets/geoip/GeoLite2-Country.mmdb b/apps/api/assets/geoip/GeoLite2-Country.mmdb
index 261640591..53584f011 100644
Binary files a/apps/api/assets/geoip/GeoLite2-Country.mmdb and b/apps/api/assets/geoip/GeoLite2-Country.mmdb differ
diff --git a/apps/api/package.json b/apps/api/package.json
index 4aa0825c5..6c8dfc4ef 100644
--- a/apps/api/package.json
+++ b/apps/api/package.json
@@ -1,6 +1,6 @@
{
"name": "@repo/api",
- "version": "1.0.1",
+ "version": "0.9.11",
"license": "Apache-2.0",
"private": true,
"type": "module",
@@ -54,7 +54,6 @@
"zod": "^4.6.7"
},
"devDependencies": {
- "@aws-sdk/client-s3": "^3.668.0",
"@repo/sdk": "workspace:*",
"@types/node": "^22.13.0",
"@types/ws": "^8.18.1",
diff --git a/apps/api/scripts/cloud-readiness.ts b/apps/api/scripts/cloud-readiness.ts
index 0a483cae5..1c2330b94 100644
--- a/apps/api/scripts/cloud-readiness.ts
+++ b/apps/api/scripts/cloud-readiness.ts
@@ -1,5 +1,4 @@
/** Read-only release checks. Does not create tokens, checkouts, or resources. */
-import { oblienApiBaseUrl, oblienApiUrl } from "@repo/adapters";
import { runtimeTarget } from "@repo/core";
import { assertOblienEntitlementMatchesSubscription, OblienBillingApi } from "@repo/platform/engine/lib/oblien-billing-api";
import { OBLIEN_WEBHOOK_EVENTS, oblienWebhookUrl } from "@repo/platform/engine/lib/oblien-webhook-config";
@@ -8,13 +7,13 @@ const results: Array<{ check: string; ok: boolean; skipped?: boolean; detail?: s
const record = (check: string, ok: boolean, detail?: string) => results.push({ check, ok, ...(detail ? { detail } : {}) });
const clientId = process.env.OBLIEN_CLIENT_ID;
const clientSecret = process.env.OBLIEN_CLIENT_SECRET;
-const apiBase = oblienApiBaseUrl(process.env.OBLIEN_API_URL);
+const apiBase = process.env.OBLIEN_API_URL ?? "https://api.oblien.com";
record("Cloud mode", process.env.CLOUD_MODE === "true");
record("Oblien credentials configured", Boolean(clientId && clientSecret));
record("Webhook secret configured", Boolean(process.env.OBLIEN_WEBHOOK_SECRET));
record("Subscription purchases enabled", process.env.BILLING_ENABLED === "true");
-const billing = new OblienBillingApi({ clientId, clientSecret, baseUrl: apiBase.toString() });
+const billing = new OblienBillingApi({ clientId, clientSecret, baseUrl: apiBase });
const checks = await Promise.allSettled([
(async () => {
await billing.assertResellerSupport();
@@ -36,13 +35,13 @@ const checks = await Promise.allSettled([
(async () => {
const callback = oblienWebhookUrl(process.env.OBLIEN_WEBHOOK_URL, runtimeTarget.api);
if (!clientId || !clientSecret) throw new Error("Oblien credentials are missing");
- const response = await fetch(oblienApiUrl(apiBase, "/webhooks"), {
+ const response = await fetch(`${apiBase.replace(/\/+$/, "")}/webhooks`, {
headers: { "X-Client-ID": clientId, "X-Client-Secret": clientSecret },
redirect: "error", signal: AbortSignal.timeout(15_000),
});
if (!response.ok) throw new Error(`Webhook registry HTTP ${response.status}`);
const body = await response.json() as { success: boolean; webhooks?: Array<{ url: string; active: boolean; namespace?: string | null; events: string[]; secret?: string | null }> };
- const webhook = body.success ? body.webhooks?.find((item) => item.url === callback && !item.namespace && item.active) : undefined;
+ const webhook = body.success && body.webhooks?.find((item) => item.url === callback && !item.namespace && item.active);
const missing = OBLIEN_WEBHOOK_EVENTS.filter((event) => !webhook || !webhook.events.includes(event));
const maskedSecret = typeof webhook?.secret === "string" && /^[*•*…]+$/u.test(webhook.secret);
const matchingSecret = Boolean(webhook?.secret && webhook.secret === process.env.OBLIEN_WEBHOOK_SECRET);
@@ -57,7 +56,7 @@ const checks = await Promise.allSettled([
})(),
(async () => {
if (!clientId || !clientSecret) throw new Error("Oblien credentials are missing");
- const response = await fetch(oblienApiUrl(apiBase, "/namespaces?limit=1"), {
+ const response = await fetch(`${apiBase.replace(/\/+$/, "")}/namespaces?limit=1`, {
headers: { "X-Client-ID": clientId, "X-Client-Secret": clientSecret },
redirect: "error", signal: AbortSignal.timeout(15_000),
});
diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts
index 0363ab976..264549493 100644
--- a/apps/api/src/app.ts
+++ b/apps/api/src/app.ts
@@ -23,7 +23,6 @@ import {
registerControllerLifecycle,
} from "./modules/system/instance/controller-state";
import { resumeControllerSockets } from "./lib/ws";
-import { resumeControllerStreams } from "./lib/sse";
import { trackBackgroundWork } from "@repo/platform/engine/lib/background-work";
import { instanceAuthorityGuard } from "./modules/system/instance/authority-guard";
import { quiesceController } from "./modules/system/instance/quiescence";
@@ -409,7 +408,6 @@ async function startControllerBackground(): Promise {
backgroundStarted = true;
try {
resumeControllerSockets();
- resumeControllerStreams();
// ─── Backup job runner + boot reconcile ─────────────────────────────
//
// One JobRunner powers all backup work — BullMQ when Redis is
diff --git a/apps/api/src/lib/cloud/resource-router.ts b/apps/api/src/lib/cloud/resource-router.ts
index 359902c29..3b1249f2f 100644
--- a/apps/api/src/lib/cloud/resource-router.ts
+++ b/apps/api/src/lib/cloud/resource-router.ts
@@ -1,9 +1,9 @@
+import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
import type { MiddlewareHandler } from "hono";
import { resolveResourceAuthority, type CloudResourceType } from "@repo/platform/engine/lib/cloud/resource-authority";
import { assertCloudProxyScope } from "@repo/platform/engine/lib/cloud/scope";
import { permission } from "../permission";
import { getRequestContext } from "../request-context";
-import { readOptionalJsonBody } from "../request-body";
import { DEFAULT_ID_PARAMS, parsePermissionTag, type PermissionSpec } from "../route-permission";
import { proxyToSaaS } from "./project-router";
@@ -25,7 +25,7 @@ export function cloudResourceRouter(path: string, spec: PermissionSpec): Middlew
if (!inPath && !inBody && !inQuery) return null;
return async (c, next) => {
const id = inPath ? c.req.param(param) : inQuery ? c.req.query(field)
- : (await readOptionalJsonBody | null>(c))?.[field];
+ : (await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/lib/cloud/resource-router"); return ({}); }) as Record)[field];
if (typeof id !== "string" || !id) return next();
const ctx = getRequestContext(c);
if (await resolveResourceAuthority(type, id, ctx.organizationId) !== "cloud") return next();
diff --git a/apps/api/src/lib/request-body.ts b/apps/api/src/lib/request-body.ts
deleted file mode 100644
index cfbe4e9dd..000000000
--- a/apps/api/src/lib/request-body.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import type { Context } from "hono";
-
-/**
- * Only a zero-byte body means omitted options; malformed JSON must still fail.
- * Operations validate decoded input. Required bodies use c.req.json() instead.
- */
-export async function readOptionalJsonBody(c: Context): Promise {
- const body = await c.req.text();
- return JSON.parse(body.length ? body : "{}");
-}
diff --git a/apps/api/src/lib/route-permission.ts b/apps/api/src/lib/route-permission.ts
index 36deb84ae..39337096d 100644
--- a/apps/api/src/lib/route-permission.ts
+++ b/apps/api/src/lib/route-permission.ts
@@ -276,8 +276,6 @@ export interface McpRouteMeta {
description: string;
/** Override the inferred hint for actions such as destructive migration cutover. */
destructive?: boolean;
- /** Whether this tool may interact with external systems; defaults to true. */
- openWorld?: boolean;
}
export interface PermissionSpec {
@@ -476,10 +474,13 @@ export function isPublicSpec(spec: RouteSpec): spec is PublicSpec {
* Be precise about what that org-wide check buys, because it is easy to misread as
* a defense it is not: it is strict only for a RESTRICTED principal (a scoped
* token), which needs an all-GitHub grant to pass. For a session-authenticated
- * owner/admin it is satisfied by broad membership authority. Ordinary members
- * cannot satisfy an admin action. Per-repo read/write authority still belongs
- * to `github-access.ts` at the token funnel and mutating service helpers; an
- * org-wide tag never substitutes for that repository-specific check.
+ * owner/admin/**member** it is satisfied by bare membership —
+ * `roleAllowsResourceType` (permission.ts) ignores the action level for those
+ * roles, so `github:admin` is no higher a bar than `github:read`. The per-repo,
+ * read-vs-write authority for those principals is enforced ONLY by
+ * `github-access.ts` at the token funnel and at the mutating service helpers.
+ * Reading this comment as "the route layer already gates writes" is what let
+ * GHSA-hp2g-hw7g-f3vm sit behind a `github:admin` tag.
* Paramless GitHub routes (/home, /status, /repos) also stay on the org-wide
* path: `filterToolsForPrincipal` already hides them from a scoped token via
* `perm.wildcard`, and their handlers narrow results through
diff --git a/apps/api/src/lib/sse.ts b/apps/api/src/lib/sse.ts
index 469f5dde6..210f16549 100644
--- a/apps/api/src/lib/sse.ts
+++ b/apps/api/src/lib/sse.ts
@@ -41,12 +41,7 @@ import { SYSTEM } from "@repo/core";
import { trackBackgroundWork } from "@repo/platform/engine/lib/background-work";
const controllerStreams = new Set();
-let accepting = true;
-export function resumeControllerStreams(): void {
- accepting = true;
-}
export function closeControllerStreams(): void {
- accepting = false;
for (const stream of controllerStreams) stream.abort();
}
@@ -187,16 +182,6 @@ export function streamSSE(
c: Context,
cb: (stream: SSEStreamingApi) => Promise,
) {
- // An admitted request can finish its permission/metadata read after the HTTP
- // fence closed existing streams. Do not give the drain a new live subscriber.
- if (!accepting) {
- c.header("Retry-After", "5");
- c.header("Cache-Control", "no-store");
- return c.json({
- code: "INSTANCE_CONTROLLER_INACTIVE",
- error: "Your instance is moving. Reconnect after the handoff.",
- }, 503);
- }
const context = currentErrorContext();
// Disable reverse-proxy response buffering. nginx/OpenResty buffer proxied
// responses by default, which holds SSE events back until the buffer fills —
diff --git a/apps/api/src/modules/apps/app.controller.ts b/apps/api/src/modules/apps/app.controller.ts
index 2c08b8bb2..3b4dd1562 100644
--- a/apps/api/src/modules/apps/app.controller.ts
+++ b/apps/api/src/modules/apps/app.controller.ts
@@ -45,7 +45,7 @@ export async function getSettings(c: Context) {
return c.json({ data: await operationData(c, getPlatformKernel().projects.getAppSettings(operationContext(c), param(c, "id"))) });
}
export async function patchSettings(c: Context) {
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/apps/app.controller"); return ({}); });
return c.json({ data: await operationData(c, getPlatformKernel().projects.updateAppSettings(operationContext(c), param(c, "id"), body)) });
}
export async function getConnection(c: Context) {
diff --git a/apps/api/src/modules/auth/invitation-signup.controller.ts b/apps/api/src/modules/auth/invitation-signup.controller.ts
index 4d61c9db5..f6d47adac 100644
--- a/apps/api/src/modules/auth/invitation-signup.controller.ts
+++ b/apps/api/src/modules/auth/invitation-signup.controller.ts
@@ -1,3 +1,4 @@
+import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
import type { Context } from "hono";
import { bodyLimit } from "hono/body-limit";
import { hashPassword } from "better-auth/crypto";
@@ -37,7 +38,7 @@ export async function inviteSignup(c: Context) {
// router, so a future remount cannot accidentally expose it on SaaS.
if (isSaasDeployment) return c.notFound();
- const body = (await c.req.json()) as {
+ const body = (await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/auth/invitation-signup.controller"); return ({}); })) as {
invitationId?: unknown;
name?: unknown;
password?: unknown;
diff --git a/apps/api/src/modules/backup-destinations/destination.controller.ts b/apps/api/src/modules/backup-destinations/destination.controller.ts
index 1b64bbbc0..7a44c1870 100644
--- a/apps/api/src/modules/backup-destinations/destination.controller.ts
+++ b/apps/api/src/modules/backup-destinations/destination.controller.ts
@@ -28,7 +28,7 @@ export async function create(c: Context) {
return c.json({ data: await operationData(c, getPlatformKernel().backupDestinations.create(operationContext(c), await c.req.json())) });
}
export async function update(c: Context) {
- return c.json({ data: await operationData(c, getPlatformKernel().backupDestinations.update(operationContext(c), param(c, "id"), await c.req.json())) });
+ return c.json({ data: await operationData(c, getPlatformKernel().backupDestinations.update(operationContext(c), param(c, "id"), await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/backup-destinations/destination.controller"); return ({}); }))) });
}
export async function remove(c: Context) {
return c.json({ data: await operationData(c, getPlatformKernel().backupDestinations.remove(operationContext(c), param(c, "id"))) });
diff --git a/apps/api/src/modules/backups/backup.controller.ts b/apps/api/src/modules/backups/backup.controller.ts
index d6e66c2ed..b27fc6228 100644
--- a/apps/api/src/modules/backups/backup.controller.ts
+++ b/apps/api/src/modules/backups/backup.controller.ts
@@ -1,4 +1,5 @@
/** HTTP paths/envelopes over the same authorized operations used by the native SDK. */
+import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
import type { Context } from "hono";
import { ValidationError } from "@repo/contracts";
import { getPlatformKernel } from "@repo/platform/engine/lib/platform";
@@ -6,7 +7,6 @@ import { getRequestContext } from "../../lib/request-context";
import { param } from "../../lib/controller-helpers";
import { operationData } from "../../lib/operation-context";
import { operationEvents } from "../../lib/operation-stream";
-import { readOptionalJsonBody } from "../../lib/request-body";
const backups = () => getPlatformKernel().backups;
export async function listProjectPolicies(c: Context) {
@@ -22,7 +22,7 @@ export async function removePolicy(c: Context) {
return c.json({ data: await operationData(c, backups().removePolicy(getRequestContext(c), param(c, "policyId"))) });
}
export async function triggerManual(c: Context) {
- return c.json({ data: await operationData(c, backups().run(getRequestContext(c), param(c, "policyId"), await readOptionalJsonBody(c))) });
+ return c.json({ data: await operationData(c, backups().run(getRequestContext(c), param(c, "policyId"), await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/backups/backup.controller"); return ({}); }))) });
}
export async function listRuns(c: Context) {
const limit = c.req.query("limit");
@@ -38,10 +38,10 @@ export async function getOneRun(c: Context) {
return c.json({ data: await operationData(c, backups().getRun(getRequestContext(c), param(c, "runId"))) });
}
export async function protectRun(c: Context) {
- return c.json({ data: await operationData(c, backups().protectRun(getRequestContext(c), param(c, "runId"), await readOptionalJsonBody(c))) });
+ return c.json({ data: await operationData(c, backups().protectRun(getRequestContext(c), param(c, "runId"), await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/backups/backup.controller"); return ({}); }))) });
}
export async function prepareRestore(c: Context) {
- return c.json({ data: await operationData(c, backups().prepareRestore(getRequestContext(c), param(c, "runId"), await readOptionalJsonBody(c))) });
+ return c.json({ data: await operationData(c, backups().prepareRestore(getRequestContext(c), param(c, "runId"), await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/backups/backup.controller"); return ({}); }))) });
}
export async function applyRestore(c: Context) {
return c.json({ data: await operationData(c, backups().applyRestore(getRequestContext(c), param(c, "restoreId"), await c.req.json())) });
diff --git a/apps/api/src/modules/backups/backup.routes.ts b/apps/api/src/modules/backups/backup.routes.ts
index 22f3a1b96..5573584d2 100644
--- a/apps/api/src/modules/backups/backup.routes.ts
+++ b/apps/api/src/modules/backups/backup.routes.ts
@@ -32,7 +32,7 @@ r.patch("/backup-policies/:policyId", { tag: "backup_destination:backup_policy:w
r.delete("/backup-policies/:policyId", { tag: "backup_destination:backup_policy:write", auditHandledByOperation: true, mcp: { description: "Disable and remove this backup policy. Existing backup history remains available according to its retention and destination state." } }, ctrl.removePolicy);
// Manual trigger
-r.post("/backup-policies/:policyId/run", { tag: "backup_destination:backup_policy:write", body: RunBackupPolicySchema, bodyValidatedByOperation: true, auditHandledByOperation: true, mcp: { description: "Start an on-demand backup under this policy. Returns runId and possibly runIds for a multi-service batch; poll each run until succeeded or failed. Accepted work is not a completed backup." } }, ctrl.triggerManual);
+r.post("/backup-policies/:policyId/run", { tag: "backup_destination:backup_policy:write", body: RunBackupPolicySchema, auditHandledByOperation: true, mcp: { description: "Start an on-demand backup under this policy. Returns runId and possibly runIds for a multi-service batch; poll each run until succeeded or failed. Accepted work is not a completed backup." } }, ctrl.triggerManual);
// Runs
r.get("/projects/:projectId/backup-runs", { tag: "project:write", ids: { project: "projectId" }, mcp: { description: "List a project's backup runs (history, status)." }, query: ListBackupRunsSchema }, ctrl.listRuns);
@@ -40,10 +40,10 @@ r.get("/backup-runs/:runId", { tag: "backup_destination:backup_run:read", mcp: {
r.get("/backup-runs/:runId/stream", { tag: "backup_destination:backup_run:read", mcpExcluded: "SSE transport for live progress. Use the resource’s JSON status/log tools over MCP, or an authenticated HTTP client for streaming." }, ctrl.streamRun);
// Protect-from-retention
-r.post("/backup-runs/:runId/protect", { tag: "backup_destination:backup_run:write", body: ProtectBackupRunSchema, bodyValidatedByOperation: true, auditHandledByOperation: true, mcp: { description: "Protect or unprotect this backup from retention cleanup, optionally until a specified time. Read the returned retention lock and backup status." } }, ctrl.protectRun);
+r.post("/backup-runs/:runId/protect", { tag: "backup_destination:backup_run:write", body: ProtectBackupRunSchema, auditHandledByOperation: true, mcp: { description: "Protect or unprotect this backup from retention cleanup, optionally until a specified time. Read the returned retention lock and backup status." } }, ctrl.protectRun);
// Restore
-r.post("/backup-runs/:runId/restore/prepare", { tag: "backup_destination:backup_run:admin", body: PrepareBackupRestoreSchema, bodyValidatedByOperation: true, auditHandledByOperation: true, mcp: { description: "Prepare restoration from this backup without applying it. Returns restoreId and confirmationToken. Poll the restore until prepared, review its target and mode, then explicitly apply the returned token." } }, ctrl.prepareRestore);
+r.post("/backup-runs/:runId/restore/prepare", { tag: "backup_destination:backup_run:admin", body: PrepareBackupRestoreSchema, auditHandledByOperation: true, mcp: { description: "Prepare restoration from this backup without applying it. Returns restoreId and confirmationToken. Poll the restore until prepared, review its target and mode, then explicitly apply the returned token." } }, ctrl.prepareRestore);
r.post("/backup-restores/:restoreId/apply", { tag: "backup_destination:backup_restore:admin", body: ApplyBackupRestoreSchema, auditHandledByOperation: true, mcp: { description: "Apply a prepared restore using its returned confirmationToken. In-place restoration overwrites target data and can stop the service. Poll restore status until it finishes before reporting success." } }, ctrl.applyRestore);
r.post("/backup-restores/:restoreId/cancel", { tag: "backup_destination:backup_restore:admin", auditHandledByOperation: true, mcp: { description: "Request cancellation of this backup restore. Poll the restore’s returned status; accepted cancellation does not undo data already written during apply." } }, ctrl.cancelRestore);
r.get("/backup-restores/:restoreId", { tag: "backup_destination:backup_restore:read", mcp: { description: "Get one backup restore's status." } }, ctrl.getOneRestore);
diff --git a/apps/api/src/modules/billing/billing-capacity-catalog.test.ts b/apps/api/src/modules/billing/billing-capacity-catalog.test.ts
index eea7004b3..e49d13054 100644
--- a/apps/api/src/modules/billing/billing-capacity-catalog.test.ts
+++ b/apps/api/src/modules/billing/billing-capacity-catalog.test.ts
@@ -9,7 +9,6 @@ import type { OblienSubscription } from "@repo/platform/engine/lib/oblien-billin
import { savedOffer, savedMetadata, savedMonthlyHobby } from "../../../test/helpers/saved-cloud-offer";
import capacityFixture from "../../../test/fixtures/oblien-capacity-catalog.json";
import { oblienCapacityCatalogSchema } from "@repo/platform/engine/lib/oblien-capacity";
-import { cloudBillingContract } from "@repo/adapters";
const savedPro = (): NonNullable => ({ tierId: "reseller", status: "active", billingInterval: "monthly",
periodStart: "2026-09-01T00:00:00Z", periodEnd: "2026-10-01T00:00:00Z", cancelAtPeriodEnd: false, canceledAt: null,
@@ -18,7 +17,7 @@ const monthlyPro = (): NonNullable => ({ ...savedPro(),
offer: subscriptionOffer("pro", "monthly"), metadata: subscriptionMetadata("pro", "org-a", "ns-a") });
describe("funded Cloud offers and isolated capacity", () => {
- it.each([undefined, oblienCapacityCatalogSchema.parse(cloudBillingContract(capacityFixture))])(
+ it.each([undefined, oblienCapacityCatalogSchema.parse(capacityFixture)])(
"publishes only subscription plans without prepaid compute offers (with or without provider capacity)",
(provider) => {
const catalog = presentCloudPlans("en", provider);
diff --git a/apps/api/src/modules/billing/billing-checkout.test.ts b/apps/api/src/modules/billing/billing-checkout.test.ts
index 58bfb2d97..9bfae4ea9 100644
--- a/apps/api/src/modules/billing/billing-checkout.test.ts
+++ b/apps/api/src/modules/billing/billing-checkout.test.ts
@@ -37,7 +37,7 @@ vi.mock("@repo/platform/engine/lib/cloud-workspace-host", () => ({
readCloudWorkspaceHost: async () => ({ provider: null }),
}));
vi.mock("@repo/platform/engine/lib/oblien-client", () => ({
- getOblienClient: () => ({ vms: { getQuota: h.quota } }),
+ getOblienClient: () => ({ workspaces: { getQuota: h.quota } }),
getOblienBillingApi: () => ({
createCheckout: h.checkout,
createPortal: h.portal,
diff --git a/apps/api/src/modules/billing/billing-reconcile.test.ts b/apps/api/src/modules/billing/billing-reconcile.test.ts
index 3ee761206..5d92b3621 100644
--- a/apps/api/src/modules/billing/billing-reconcile.test.ts
+++ b/apps/api/src/modules/billing/billing-reconcile.test.ts
@@ -116,25 +116,15 @@ describe("Oblien-managed entitlements", () => {
h.balance.mockResolvedValue({ ...state.balance, billingMode: "payg" });
await expect(assertCloudCanSpend("org_1")).rejects.toMatchObject({ code: "CLOUD_BILLING_BLOCKED" });
});
- it.each(["active", "past_due"] as const)("allows billing recovery during a %s unpaid renewal without granting compute or credits", async status => {
+ it("allows billing recovery after an unpaid renewal without granting compute or credits", async () => {
const state = unpaidMonthlyCloudBilling();
- state.subscription.status = status;
h.entitlement.mockResolvedValue(state.entitlement);
h.subscription.mockResolvedValue({ namespace: state.entitlement.namespace, subscription: state.subscription });
h.balance.mockResolvedValue(state.balance);
const result = await syncOblienEntitlement("org_1", { syncResourceLimits: false });
- expect(result).toMatchObject({ tier: "pro", subscription: { status }, entitlement: { status: "canceled", computeCovered: false } });
+ expect(result).toMatchObject({ tier: "pro", subscription: { status: "past_due" }, entitlement: { status: "canceled", computeCovered: false } });
await expect(assertNamespaceHasQuota("org_1")).resolves.toBeUndefined();
await expect(assertCloudCanSpend("org_1")).rejects.toMatchObject({ statusCode: 402, code: "CLOUD_BILLING_BLOCKED" });
- expect(h.mirror).toHaveBeenCalledWith("workspace_1", "org_1", "os-customer", {
- planTierId: "pro", subscriptionStatus: "canceled",
- currentPeriodStart: new Date(state.entitlement.periodStart!),
- currentPeriodEnd: new Date(state.entitlement.periodEnd!),
- });
- // A newer balance response alone must not turn old, uncovered capacity into
- // paid compute. Both authoritative reads must confirm the funded month.
- h.balance.mockResolvedValue({ ...state.balance, blocking: false, computeCovered: true });
- await expect(assertCloudCanSpend("org_1")).rejects.toMatchObject({ statusCode: 402, code: "CLOUD_BILLING_BLOCKED" });
expect(h.limits).not.toHaveBeenCalled();
expect(h.setQuota).not.toHaveBeenCalled();
expect(h.resetQuota).not.toHaveBeenCalled();
diff --git a/apps/api/src/modules/billing/billing.controller.ts b/apps/api/src/modules/billing/billing.controller.ts
index 2d7028560..2527a0bfb 100644
--- a/apps/api/src/modules/billing/billing.controller.ts
+++ b/apps/api/src/modules/billing/billing.controller.ts
@@ -3,9 +3,9 @@ import type { Context } from "hono";
import { getPlatformKernel } from "@repo/platform/engine/lib/platform";
import { publicBillingOperations } from "@repo/platform/engine/modules/billing/billing.operations";
import { operationContext, operationData } from "../../lib/operation-context";
-import { readOptionalJsonBody } from "../../lib/request-body";
const billingScope = (c: Context) => ({ workspaceId: c.req.query("workspaceId") });
+const optionalBody = (c: Context) => c.req.raw.body ? c.req.json() : Promise.resolve({});
export async function listPlans(c: Context) {
const data = await publicBillingOperations.listPlans({ locale: c.req.query("locale") ?? c.req.header("accept-language") });
@@ -66,11 +66,11 @@ export async function cancelSubscriptionChange(c: Context) {
c.header("Cache-Control", "no-store");
return c.json({ data: await operationData(c, getPlatformKernel().billing.cancelSubscriptionChange(operationContext(c), await c.req.json())) });
}
-export async function cancelSubscription(c: Context) { return c.json({ data: await operationData(c, getPlatformKernel().billing.cancelSubscription(operationContext(c), await readOptionalJsonBody(c))) }); }
-export async function resumeSubscription(c: Context) { return c.json({ data: await operationData(c, getPlatformKernel().billing.resumeSubscription(operationContext(c), await readOptionalJsonBody(c))) }); }
+export async function cancelSubscription(c: Context) { return c.json({ data: await operationData(c, getPlatformKernel().billing.cancelSubscription(operationContext(c), await optionalBody(c))) }); }
+export async function resumeSubscription(c: Context) { return c.json({ data: await operationData(c, getPlatformKernel().billing.resumeSubscription(operationContext(c), await optionalBody(c))) }); }
export async function createTopup(c: Context) { return c.json({ data: await operationData(c, getPlatformKernel().billing.createTopup(operationContext(c), await c.req.json())) }, 201); }
export async function listTopupPacks(c: Context) { return c.json({ data: await operationData(c, getPlatformKernel().billing.listTopupPacks(operationContext(c))) }); }
-export async function createPortal(c: Context) { return c.json({ data: await operationData(c, getPlatformKernel().billing.createPortal(operationContext(c), await readOptionalJsonBody(c))) }); }
+export async function createPortal(c: Context) { return c.json({ data: await operationData(c, getPlatformKernel().billing.createPortal(operationContext(c), await optionalBody(c))) }); }
export async function getUsage(c: Context) { return c.json({ data: await operationData(c, getPlatformKernel().billing.getUsage(operationContext(c), { ...billingScope(c), from: c.req.query("from"), to: c.req.query("to"), groupBy: c.req.query("groupBy") as "hour" | "day" | undefined })) }); }
export async function listAllowanceDetail(c: Context) { return c.json({ data: await operationData(c, getPlatformKernel().billing.listAllowanceDetail(operationContext(c), billingScope(c))) }); }
diff --git a/apps/api/src/modules/billing/oblien-billing-api.test.ts b/apps/api/src/modules/billing/oblien-billing-api.test.ts
index 1723cabb3..16fd45c0e 100644
--- a/apps/api/src/modules/billing/oblien-billing-api.test.ts
+++ b/apps/api/src/modules/billing/oblien-billing-api.test.ts
@@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
import { OblienBillingApi, oblienOfferSchema, assertOblienEntitlementMatchesSubscription } from "@repo/platform/engine/lib/oblien-billing-api";
import { BillingOperationSchemas } from "@repo/contracts";
import { Value } from "@sinclair/typebox/value";
-import { providerBillingFixture } from "../../../test/helpers/oblien-vm-billing";
import capacityCatalog from "../../../test/fixtures/oblien-capacity-catalog.json";
import { monthlyCloudBilling, unpaidMonthlyCloudBilling } from "../../../test/helpers/monthly-cloud-offer";
@@ -26,7 +25,7 @@ const subscription = { success: true, namespace: "os-one", subscription: {
cancelAtPeriodEnd: true, canceledAt: "2026-09-15T00:00:00Z",
} };
function setup(body: unknown, status = 200) {
- const fetcher = vi.fn(async (_url: Parameters[0], _init?: RequestInit) => Response.json(providerBillingFixture(body), { status }));
+ const fetcher = vi.fn(async (_url: Parameters[0], _init?: RequestInit) => Response.json(body, { status }));
const api = new OblienBillingApi({ clientId: "test-id", clientSecret: "test-secret", fetch: fetcher as unknown as typeof fetch });
return { api, fetcher };
}
@@ -48,7 +47,7 @@ describe("Oblien billing SDK and transport contract", () => {
await api.createCheckout({ namespace: "os-one", kind: "subscription", billingInterval: "yearly",
offer: { ...monthlyCloudBilling().subscription.offer!, unitAmount: 12000 }, metadata,
affiliateBuyer, affiliateCode: "AF-0123456789", successUrl: "https://app.openship.io", cancelUrl: "https://app.openship.io", idempotencyKey: "referral-transport" });
- expect(fetcher).toHaveBeenCalledExactlyOnceWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({
+ expect(fetcher).toHaveBeenCalledExactlyOnceWith("https://api.oblien.com/billing/checkout", expect.objectContaining({
method: "POST", redirect: "error", signal: expect.any(AbortSignal),
headers: expect.objectContaining({ "X-Client-ID": "test-id", "X-Client-Secret": "test-secret" }),
}));
@@ -60,7 +59,7 @@ describe("Oblien billing SDK and transport contract", () => {
const live = { success: true, credits_per_dollar: 100, rate_card_id: "live", rates: { cpu_per_min: 1.5, memory_per_gb_min: 0.2, disk_per_gb: 0, network_per_gb: 0.15 } };
const { api, fetcher } = setup({ ...live, compute_rate_cards: [{ chargeEnabled: false, cpu_per_min: 0.001 }] });
expect(await api.getMeteredPricing()).toEqual(live);
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/pricing/calculator", expect.objectContaining({ method: "GET", redirect: "error", headers: { Accept: "application/json" } }));
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/pricing/calculator", expect.objectContaining({ method: "GET", redirect: "error", headers: { Accept: "application/json" } }));
});
it.each([
{ credits_per_dollar: 50, rate_card_id: "new", rates: { cpu_per_min: 1, memory_per_gb_min: 1, disk_per_gb: 0, network_per_gb: 0 } },
@@ -75,14 +74,14 @@ describe("Oblien billing SDK and transport contract", () => {
const { api, fetcher } = setup({ success: true, namespace: "os-one", pendingCheckout, wallet: { balance: 12000 } });
expect(await api.getPendingCapacityCheckout("os-one")).toEqual({ success: true, namespace: "os-one",
pendingCheckout: { ...pendingCheckout, quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" } } });
- expect(fetcher.mock.calls[0]![0]).toBe("https://api.oblien.com/v1/billing/capacity?namespace=os-one");
+ expect(fetcher.mock.calls[0]![0]).toBe("https://api.oblien.com/billing/capacity?namespace=os-one");
await expect(api.getPendingCapacityCheckout("os-other")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" });
});
it("cancels a capacity payment with the saved provider quote and retry identity", async () => {
const { api, fetcher } = setup({ success: true, namespace: "os-one", pendingCheckout: null });
const input = { quoteId: "quote_pending", idempotencyKey: "cancel-once" };
await expect(api.cancelCapacityCheckout("os-one", input)).resolves.toMatchObject({ pendingCheckout: null });
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/capacity/change/cancel", expect.objectContaining({
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/capacity/change/cancel", expect.objectContaining({
method: "POST",
}));
expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual({ namespace: "os-one", ...input });
@@ -102,7 +101,7 @@ describe("Oblien billing SDK and transport contract", () => {
(await api.cancelCheckout("os-one", checkout.id, { idempotencyKey: "cancel-once" })).checkout,
).toEqual(checkout);
expect(fetcher).toHaveBeenCalledWith(
- "https://api.oblien.com/v1/billing/checkout/bco_original/cancel",
+ "https://api.oblien.com/billing/checkout/bco_original/cancel",
expect.objectContaining({
method: "POST",
body: JSON.stringify({ namespace: "os-one", idempotencyKey: "cancel-once" }),
@@ -124,7 +123,7 @@ describe("Oblien billing SDK and transport contract", () => {
it.each([
{ quote: { id: "quote_pending", namespace: "os-other", paymentSource: "stripe" }, checkoutId: "cs_requested", url: null },
{ quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" }, checkoutId: "cs_requested", url: "https://evil.example/pay" },
- { quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" }, checkoutId: "cs_requested", url: "https://api.oblien.com/v1/not-a-payment#secret" },
+ { quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" }, checkoutId: "cs_requested", url: "https://api.oblien.com/not-a-payment#secret" },
])("rejects foreign capacity scope and untrusted resume URLs", async pendingCheckout => {
await expect(setup({ success: true, namespace: "os-one", pendingCheckout }).api.getPendingCapacityCheckout("os-one")).rejects.toThrow();
});
@@ -136,16 +135,16 @@ describe("Oblien billing SDK and transport contract", () => {
});
it("scopes complimentary policy writes to the requested namespace and validates the response", async () => {
const policy = { quotaLimit: 3000, overdraft: 60, suspendThreshold: 60, onOverdraftAction: "stop_workspaces" as const };
- const result = { success: true, namespace: "os-one", service: "vm_compute", ...policy };
+ const result = { success: true, namespace: "os-one", service: "workspace_vm", ...policy };
const { api, fetcher } = setup(result);
expect(await api.setPolicy("os-one", policy)).toEqual(result);
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/policy/os-one", expect.objectContaining({ method: "PUT", body: JSON.stringify(providerBillingFixture(policy)) }));
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/policy/os-one", expect.objectContaining({ method: "PUT", body: JSON.stringify(policy) }));
await expect(api.setPolicy("os-two", policy)).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" });
});
it("keeps the same provider reset key on retry and rejects an unscoped reset response", async () => {
const { api, fetcher } = setup({ success: true, namespace: "os-one", applied: false });
expect(await api.resetQuota("os-one", "2026-10-25T14:00:00.000Z")).toMatchObject({ applied: false });
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/policy/os-one/reset", expect.objectContaining({ method: "POST", body: JSON.stringify({ periodEnd: "2026-10-25T14:00:00.000Z" }) }));
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/policy/os-one/reset", expect.objectContaining({ method: "POST", body: JSON.stringify({ periodEnd: "2026-10-25T14:00:00.000Z" }) }));
await expect(setup({ success: true, applied: true }).api.resetQuota("os-one", "2026-10-25T14:00:00.000Z"))
.rejects.toMatchObject({ code: "OBLIEN_BILLING_INVALID_RESPONSE" });
});
@@ -216,7 +215,7 @@ describe("Oblien billing SDK and transport contract", () => {
expect(state.checkout).not.toHaveProperty("walletCredits");
expect(state.checkout).not.toHaveProperty("paymentId");
expect(fetcher.mock.calls[0]![0]).toBe(
- "https://api.oblien.com/v1/billing/checkout/cs_requested?namespace=os-one",
+ "https://api.oblien.com/billing/checkout/cs_requested?namespace=os-one",
);
await expect(api.getCheckout("os-other", "cs_requested")).rejects.toMatchObject({
code: "OBLIEN_BILLING_NAMESPACE_MISMATCH",
@@ -252,7 +251,7 @@ describe("Oblien billing SDK and transport contract", () => {
it("authenticates server requests and validates the returned customer namespace", async () => {
const { api, fetcher } = setup(entitlement);
expect((await api.getEntitlement("os-one")).quota.used).toBe(-50);
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/entitlement?namespace=os-one", expect.objectContaining({
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/entitlement?namespace=os-one", expect.objectContaining({
headers: expect.objectContaining({ "X-Client-ID": "test-id", "X-Client-Secret": "test-secret" }), redirect: "error",
}));
await expect(api.getEntitlement("os-two")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" });
@@ -276,24 +275,22 @@ describe("Oblien billing SDK and transport contract", () => {
idempotencyKey: "checkout-123",
};
await api.createCheckout(input);
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({ method: "POST" }));
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/checkout", expect.objectContaining({ method: "POST" }));
expect(JSON.parse(String(fetcher.mock.calls[0]![1]!.body))).toEqual({ ...input, allowPromotionCodes: true });
});
- it("keeps the hosted payment page unversioned while sending checkout requests to /v1", async () => {
+ it("accepts the exact Oblien promotion checkout and preserves its opaque ID", async () => {
const checkoutId = "bco_24f15202-6a3d-4b27-b7c2-c3abbc401bee";
const url = `https://api.oblien.com/billing/pay#${"a".repeat(43)}`;
- const { api, fetcher } = setup({ success: true, url, checkoutId });
+ const { api } = setup({ success: true, url, checkoutId });
await expect(api.createCheckout({ namespace: "os-one", kind: "topup", offer, metadata,
successUrl: "https://app.openship.io", cancelUrl: "https://app.openship.io", idempotencyKey: "promotion-checkout" }))
.resolves.toMatchObject({ url, checkoutId });
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({ method: "POST" }));
});
it.each([
"http://api.oblien.com/billing/pay", "https://api.oblien.com.evil.example/billing/pay",
- "https://api.oblien.com/billing/pay?return=https://evil.example", "https://api.oblien.com/v1/other",
+ "https://api.oblien.com/billing/pay?return=https://evil.example", "https://api.oblien.com/other",
"https://api.oblien.com/billing/pay", "https://user@api.oblien.com/billing/pay",
"https://api.oblien.com:8443/billing/pay", "https://api.oblien.com/billing/pay/",
- "https://api.oblien.com/v1/billing/pay",
])("rejects an invalid promotion checkout URL: %s", async (value) => {
const url = value + (value === "https://api.oblien.com/billing/pay" ? "#short" : `#${"a".repeat(43)}`);
await expect(setup({ success: true, url, checkoutId: "bco_24f15202-6a3d-4b27-b7c2-c3abbc401bee" }).api.createCheckout({
@@ -556,7 +553,7 @@ describe("Oblien billing SDK and transport contract", () => {
const { api, fetcher } = setup({ success: true, namespace: "os-one", url: "https://billing.stripe.com/p/session/test" });
const input = { namespace: "os-one", returnUrl: "https://app.openship.io/billing/overview" };
expect((await api.createPortal(input)).url).toBe("https://billing.stripe.com/p/session/test");
- expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/portal", expect.objectContaining({ method: "POST", body: JSON.stringify(input), redirect: "error", signal: expect.any(AbortSignal) }));
+ expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/portal", expect.objectContaining({ method: "POST", body: JSON.stringify(input), redirect: "error", signal: expect.any(AbortSignal) }));
await expect(api.createPortal({ ...input, namespace: "os-two" })).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" });
});
it("rejects a legacy owner portal even when its hosted URL is otherwise valid", async () => {
@@ -575,7 +572,7 @@ describe("Oblien billing SDK and transport contract", () => {
] as const)("uses the SDK %s method and checks the response namespace", async (method, verb, path) => {
const { api, fetcher } = setup(subscription);
expect(await api[method]("os-one")).toEqual(subscription);
- expect(fetcher).toHaveBeenCalledWith(`https://api.oblien.com/v1${path}`, expect.objectContaining({
+ expect(fetcher).toHaveBeenCalledWith(`https://api.oblien.com${path}`, expect.objectContaining({
method: verb, ...(verb === "POST" ? { body: JSON.stringify({ namespace: "os-one" }) } : {}),
}));
await expect(api[method]("os-two")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" });
@@ -615,7 +612,7 @@ describe("Oblien monthly capacity contract", () => {
const catalog = await api.assertMonthlyCapacitySupport();
expect(catalog.tariff.usage).toEqual({ activeVcpuHourCents: 3, reservedGiBHourCents: 0.8, retainedGiBMonthCents: 5, monthHours: 720 });
const [url, request] = fetcher.mock.calls[0]!;
- expect(String(url)).toBe("https://api.oblien.com/v1/billing/capacity/catalog");
+ expect(String(url)).toBe("https://api.oblien.com/billing/capacity/catalog");
expect(request?.headers).not.toHaveProperty("X-Client-Secret");
expect(request?.headers).not.toHaveProperty("X-Client-ID");
});
@@ -659,7 +656,7 @@ describe("Oblien monthly capacity contract", () => {
.toThrow(/does not match/);
}
});
- it.each(["active", "past_due", "unpaid", "paused", "canceled"] as const)("keeps billing readable for an expired paid month and a %s renewal", async status => {
+ it.each(["past_due", "unpaid", "paused", "canceled"] as const)("keeps billing readable for an expired paid month and a %s renewal", async status => {
const state = unpaidMonthlyCloudBilling("org-one", "os-one");
state.subscription.status = status;
const entitlement = await setup(state.entitlement).api.getEntitlement("os-one");
@@ -668,8 +665,9 @@ describe("Oblien monthly capacity contract", () => {
expect(entitlement).toMatchObject({ status: "canceled", computeCovered: false, capacity: { status: "expired", computeCovered: false } });
expect(entitlement.periodEnd).not.toBe(subscription!.periodEnd);
});
- it.each(["active", "past_due"] as const)("still rejects funded, overlapping, foreign or inconsistent %s renewal records", status => {
+ it("still rejects funded, overlapping, foreign or inconsistent unpaid renewal records", () => {
for (const mutate of [
+ (state: ReturnType) => { state.subscription.status = "active"; },
(state: ReturnType) => { state.subscription.status = "trialing"; },
(state: ReturnType) => { state.entitlement.status = "active"; },
(state: ReturnType) => { state.entitlement.computeCovered = state.entitlement.capacity!.computeCovered = true; },
@@ -680,12 +678,9 @@ describe("Oblien monthly capacity contract", () => {
(state: ReturnType) => { state.subscription.periodStart = "2026-10-15T00:00:00Z"; },
(state: ReturnType) => { state.subscription.periodStart = null; },
(state: ReturnType) => { state.subscription.periodEnd = state.subscription.periodStart; },
- (state: ReturnType) => { state.entitlement.periodStart = state.entitlement.capacity!.periodStart = state.entitlement.periodEnd!; },
(state: ReturnType) => { state.entitlement.capacity!.periodEnd = "2026-10-31T00:00:00Z"; },
]) {
- const state = unpaidMonthlyCloudBilling();
- state.subscription.status = status;
- mutate(state);
+ const state = unpaidMonthlyCloudBilling(); mutate(state);
expect(() => assertOblienEntitlementMatchesSubscription(state.entitlement, state.subscription)).toThrow(/does not match/);
}
});
@@ -697,9 +692,9 @@ describe("Oblien monthly capacity contract", () => {
offer: subscription.offer!, metadata: subscription.metadata!, idempotencyKey: "saved-monthly-order",
successUrl: "https://app.openship.io/billing/overview", cancelUrl: "https://app.openship.io/billing/plans" });
const [url, request] = fetcher.mock.calls[0]!;
- expect(String(url)).toBe("https://api.oblien.com/v1/billing/checkout");
+ expect(String(url)).toBe("https://api.oblien.com/billing/checkout");
const sent = JSON.parse(String(request?.body));
- expect(sent.offer).toMatchObject({ unitAmount, credits: 0, billingMode: "monthly", capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, vms: 1 } });
+ expect(sent.offer).toMatchObject({ unitAmount, credits: 0, billingMode: "monthly", capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, workspaces: 1 } });
expect(sent.offer).not.toHaveProperty("policy");
expect(sent.idempotencyKey).toBe("saved-monthly-order");
expect(sent.allowPromotionCodes).toBe(unitAmount > 0);
@@ -768,18 +763,18 @@ describe("Oblien subscription changes", () => {
it("delegates all four methods to the official SDK and preserves provider cents and fractional credits", async () => {
const preview = setup({ success: true, namespace: "os-one", quote });
expect((await preview.api.previewPlanChange("os-one", input)).quote).toEqual(quote);
- expect(preview.fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/subscription/changes/preview",
+ expect(preview.fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/subscription/changes/preview",
expect.objectContaining({ method: "POST" }));
expect(JSON.parse(String(preview.fetcher.mock.calls[0]![1]!.body))).toEqual({ namespace: "os-one", ...input });
const accept = setup({ success: true, namespace: "os-one", change }, 202);
expect((await accept.api.changePlan("os-one", { quoteId: quote.id, idempotencyKey: "confirm-request" })).change.status).toBe("payment_pending");
- expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/billing/subscription/changes",
+ expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/billing/subscription/changes",
expect.objectContaining({ method: "POST" }));
expect(JSON.parse(String(accept.fetcher.mock.calls.at(-1)![1]!.body))).toEqual({ namespace: "os-one", quoteId: quote.id, idempotencyKey: "confirm-request" });
await accept.api.getPlanChange("os-one", change.id);
- expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/billing/subscription/changes/change_one?namespace=os-one", expect.objectContaining({ method: "GET" }));
+ expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/billing/subscription/changes/change_one?namespace=os-one", expect.objectContaining({ method: "GET" }));
await accept.api.cancelPlanChange("os-one", change.id, "cancel-request");
- expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/billing/subscription/changes/change_one/cancel",
+ expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/billing/subscription/changes/change_one/cancel",
expect.objectContaining({ method: "POST" }));
expect(JSON.parse(String(accept.fetcher.mock.calls.at(-1)![1]!.body))).toEqual({ namespace: "os-one", idempotencyKey: "cancel-request" });
});
diff --git a/apps/api/src/modules/billing/oblien-managed-transfer.test.ts b/apps/api/src/modules/billing/oblien-managed-transfer.test.ts
index c43a1504f..fb2ed26a8 100644
--- a/apps/api/src/modules/billing/oblien-managed-transfer.test.ts
+++ b/apps/api/src/modules/billing/oblien-managed-transfer.test.ts
@@ -1,12 +1,11 @@
import { describe, expect, it } from "vitest";
import { Value } from "@sinclair/typebox/value";
import { BillingComputeSchema } from "@repo/contracts";
-import { providerBillingFixture } from "../../../test/helpers/oblien-vm-billing";
import { OblienBillingApi, assertOblienEntitlementMatchesSubscription } from "@repo/platform/engine/lib/oblien-billing-api";
import { monthlyCloudBilling } from "../../../test/helpers/monthly-cloud-offer";
import transfer from "../../../test/fixtures/oblien-managed-transfer.json";
-// Native provider transfer counters with synthetic data.
+// SDK 2.10's live response shape, with synthetic counters and no customer data.
const unlimited = { ...transfer, unlimited: true, includedBytes: null,
includedAvailableBytes: null, availableBytes: null };
async function readTransfer(network: unknown, covered = true) {
@@ -15,7 +14,7 @@ async function readTransfer(network: unknown, covered = true) {
...entitlement.capacity, computeCovered: covered, network,
} };
const api = new OblienBillingApi({ clientId: "test-id", clientSecret: "test-secret",
- fetch: (async () => Response.json(providerBillingFixture(payload))) as typeof fetch });
+ fetch: (async () => Response.json(payload)) as typeof fetch });
const result = await api.getEntitlement("os-one");
assertOblienEntitlementMatchesSubscription(result, subscription);
return result.capacity!;
diff --git a/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts b/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts
index 25c707895..d92cc82fe 100644
--- a/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts
+++ b/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts
@@ -64,7 +64,7 @@ describe("deriveOblienEventId", () => {
const base: OblienEventEnvelope = {
event: "credits.usage",
timestamp: "2026-07-21T10:00:00Z",
- data: { namespace: "os-abc", vm_id: "ws_1", period_end: "2026-08-01T00:00:00Z" },
+ data: { namespace: "os-abc", workspace_id: "ws_1", period_end: "2026-08-01T00:00:00Z" },
};
it("is deterministic for the same payload", () => {
diff --git a/apps/api/src/modules/billing/oblien-webhook.controller.test.ts b/apps/api/src/modules/billing/oblien-webhook.controller.test.ts
index 2302b9d73..360375850 100644
--- a/apps/api/src/modules/billing/oblien-webhook.controller.test.ts
+++ b/apps/api/src/modules/billing/oblien-webhook.controller.test.ts
@@ -294,7 +294,7 @@ describe("oblienWebhook — dispatch", () => {
describe("durable quota alert receipt", () => {
it("returns 503 without a checkpoint when notification storage fails, then retries the same event", async () => {
- const body = JSON.stringify({ id: "evt-critical", event: "credits.depleted", data: { namespace: "os-abc", service: "vm_compute" } });
+ const body = JSON.stringify({ id: "evt-critical", event: "credits.depleted", data: { namespace: "os-abc", service: "workspace_vm" } });
h.enqueue.mockRejectedValueOnce(new Error("database unavailable"));
expect(((await oblienWebhook(makeCtx(body, sign(body), "evt-critical"))) as unknown as JsonResult).status).toBe(503);
expect(h.processed.size).toBe(0);
@@ -305,7 +305,7 @@ describe("durable quota alert receipt", () => {
expect(h.processed.size).toBe(1);
});
it("leaves the event retryable when exhaustion activity cannot be recorded", async () => {
- const body = JSON.stringify({ id: "evt-activity", event: "credits.depleted", data: { namespace: "os-abc", service: "vm_compute" } });
+ const body = JSON.stringify({ id: "evt-activity", event: "credits.depleted", data: { namespace: "os-abc", service: "workspace_vm" } });
h.auditRecord.mockRejectedValueOnce(new Error("activity storage unavailable"));
expect(((await oblienWebhook(makeCtx(body, sign(body), "evt-activity"))) as unknown as JsonResult).status).toBe(503);
expect(h.processed.size).toBe(0);
diff --git a/apps/api/src/modules/cloud/cloud-pages.service.ts b/apps/api/src/modules/cloud/cloud-pages.service.ts
index f2b18387a..9530a4f99 100644
--- a/apps/api/src/modules/cloud/cloud-pages.service.ts
+++ b/apps/api/src/modules/cloud/cloud-pages.service.ts
@@ -5,7 +5,7 @@ import { authorizeCloudRelayWorkspace } from "./cloud-relay-access";
export async function createCloudPage(
ctx: RequestContext,
- input: { vm_id: string; path: string; name: string; slug: string; domain?: string },
+ input: { workspace_id: string; path: string; name: string; slug: string; domain?: string },
): Promise {
const workspaceId = await authorizeCloudRelayWorkspace(ctx);
const namespace = await ensureNamespace(ctx.organizationId, workspaceId);
diff --git a/apps/api/src/modules/cloud/cloud-resource.controller.ts b/apps/api/src/modules/cloud/cloud-resource.controller.ts
index 34ac7305e..db9cd5e26 100644
--- a/apps/api/src/modules/cloud/cloud-resource.controller.ts
+++ b/apps/api/src/modules/cloud/cloud-resource.controller.ts
@@ -10,9 +10,9 @@ import { authorizeCloudRelayWorkspace } from "./cloud-relay-access";
const id = z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/);
const path = z.string().min(1).max(2048);
const domain = z.string().min(1).max(253);
-const source = z.object({ vm_id: id, path }).strict();
+const source = z.object({ workspace_id: id, path }).strict();
const action = z.discriminatedUnion("kind", [
- z.object({ kind: z.literal("proxy"), vm: id, port: z.number().int().min(1).max(65535),
+ z.object({ kind: z.literal("proxy"), workspace: id, port: z.number().int().min(1).max(65535),
stripPrefix: z.boolean().optional(), path: path.optional() }).strict(),
z.object({ kind: z.literal("rewrite"), to: path }).strict(),
z.object({ kind: z.literal("redirect"), to: path, status: z.union([z.literal(301), z.literal(302), z.literal(307), z.literal(308)]).optional() }).strict(),
diff --git a/apps/api/src/modules/cloud/cloud-saas.controller.ts b/apps/api/src/modules/cloud/cloud-saas.controller.ts
index 10adfda66..03810ef70 100644
--- a/apps/api/src/modules/cloud/cloud-saas.controller.ts
+++ b/apps/api/src/modules/cloud/cloud-saas.controller.ts
@@ -635,11 +635,11 @@ export async function checkEdgeVerification(c: Context) {
// ─── Pages proxy ────────────────────────────────────────────────────────────
/**
- * POST /api/cloud/pages { vm_id, path, name, slug, domain? }
+ * POST /api/cloud/pages { workspace_id, path, name, slug, domain? }
*
* Forwards to Oblien with the caller's namespace token. Oblien
* enforces:
- * - `vm_id` must belong to the caller's namespace (or 404)
+ * - `workspace_id` must belong to the caller's namespace (or 404)
* - `slug` must be free on the shared zone (or 409 SLUG_TAKEN)
*
* Returns the raw Oblien SDK shape so the caller's infrastructure adapter
@@ -648,18 +648,18 @@ export async function checkEdgeVerification(c: Context) {
export async function pagesProxy(c: Context) {
const ctx = getRequestContext(c);
const body = await c.req.json<{
- vm_id?: string;
+ workspace_id?: string;
path?: string;
name?: string;
slug?: string;
domain?: string;
}>();
- if (!body.vm_id || !body.path || !body.name || !body.slug) {
- return c.json({ error: "vm_id, path, name and slug are required" }, 400);
+ if (!body.workspace_id || !body.path || !body.name || !body.slug) {
+ return c.json({ error: "workspace_id, path, name and slug are required" }, 400);
}
try {
const result = await createCloudPage(ctx, {
- vm_id: body.vm_id,
+ workspace_id: body.workspace_id,
path: body.path,
name: body.name,
slug: body.slug,
diff --git a/apps/api/src/modules/deployments/build-pipeline.prebuilt-image.test.ts b/apps/api/src/modules/deployments/build-pipeline.prebuilt-image.test.ts
index f4df5dde0..4e5d91744 100644
--- a/apps/api/src/modules/deployments/build-pipeline.prebuilt-image.test.ts
+++ b/apps/api/src/modules/deployments/build-pipeline.prebuilt-image.test.ts
@@ -92,7 +92,7 @@ vi.mock("@repo/db", () => ({
listByProject: vi.fn(async () => []),
remove: vi.fn(async () => undefined),
},
- project: { findById: mocks.findProjectById, update: vi.fn(async () => undefined), getEnvMap: vi.fn(async () => ({})) },
+ project: { findById: mocks.findProjectById, update: vi.fn(async () => undefined) },
},
}));
diff --git a/apps/api/src/modules/deployments/cancel-is-final.test.ts b/apps/api/src/modules/deployments/cancel-is-final.test.ts
index 062a62169..841363250 100644
--- a/apps/api/src/modules/deployments/cancel-is-final.test.ts
+++ b/apps/api/src/modules/deployments/cancel-is-final.test.ts
@@ -43,6 +43,7 @@ vi.mock("@repo/platform/engine/modules/projects/cleanup-keep-set", () => ({
// Terminal-event side channels, each of which drags in auth/github/mail wiring.
vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: mocks.notify } }));
vi.mock("../../lib/audit", () => ({ audit: { recordAsync: vi.fn(), record: vi.fn() } }));
+vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn(async () => {}) }));
vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({
onWebmailDeployed: vi.fn(async () => {}),
}));
diff --git a/apps/api/src/modules/deployments/compose/build-cancel.test.ts b/apps/api/src/modules/deployments/compose/build-cancel.test.ts
index fcb82ccb5..86d366a08 100644
--- a/apps/api/src/modules/deployments/compose/build-cancel.test.ts
+++ b/apps/api/src/modules/deployments/compose/build-cancel.test.ts
@@ -4,11 +4,9 @@ import { describe, expect, it, vi } from "vitest";
// Same stubs as build.service.test.ts: the DB row read and the SSE broadcast are
// side effects this contract doesn't depend on (and importing the real @repo/db
// would risk the PGlite single-instance lock).
-const { listByProjectMock, getEnvMapMock } = vi.hoisted(() => ({
- listByProjectMock: vi.fn(), getEnvMapMock: vi.fn(async () => ({})),
-}));
+const { listByProjectMock } = vi.hoisted(() => ({ listByProjectMock: vi.fn() }));
vi.mock("@repo/db", () => ({
- repos: { project: { getEnvMap: getEnvMapMock }, service: { listByProject: listByProjectMock } },
+ repos: { service: { listByProject: listByProjectMock } },
}));
vi.mock("@repo/platform/engine/modules/deployments/session-manager", () => ({
broadcastServiceStatus: vi.fn(),
diff --git a/apps/api/src/modules/deployments/compose/build.service.test.ts b/apps/api/src/modules/deployments/compose/build.service.test.ts
index 9023d7848..f8e2770d9 100644
--- a/apps/api/src/modules/deployments/compose/build.service.test.ts
+++ b/apps/api/src/modules/deployments/compose/build.service.test.ts
@@ -1,5 +1,4 @@
import { existsSync, readdirSync } from "node:fs";
-import { encrypt } from "@repo/platform/engine/lib/encryption";
import { readFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { isAbsolute, join } from "node:path";
@@ -13,11 +12,9 @@ import { describe, expect, it, vi } from "vitest";
// status. Both are side effects the inline-build materialization contract does not
// depend on — stub them so the test exercises ONLY the materialize/COPY path.
// (Importing the real @repo/db would also risk the PGlite single-instance lock.)
-const { listByProjectMock, getEnvMapMock } = vi.hoisted(() => ({
- listByProjectMock: vi.fn(), getEnvMapMock: vi.fn(async () => ({})),
-}));
+const { listByProjectMock } = vi.hoisted(() => ({ listByProjectMock: vi.fn() }));
vi.mock("@repo/db", () => ({
- repos: { project: { getEnvMap: getEnvMapMock }, service: { listByProject: listByProjectMock, startServiceDeploymentTiming: vi.fn(async () => {}) } },
+ repos: { service: { listByProject: listByProjectMock, startServiceDeploymentTiming: vi.fn(async () => {}) } },
}));
vi.mock("@repo/platform/engine/modules/deployments/session-manager", () => ({
broadcastServiceStatus: vi.fn(),
@@ -570,19 +567,6 @@ describe("buildComposeImages — inline catalog build materialization", () => {
* These pin the producer side: which rows get a narrowed context, and which must not.
*/
describe("buildComposeImages — declared build context", () => {
- it("uses each service's encrypted saved environment for its own build", async () => {
- getEnvMapMock.mockResolvedValueOnce({ API_SECRET: encrypt("api-only"), PORT: encrypt("3000") });
- getEnvMapMock.mockResolvedValueOnce({ WORKER_SECRET: encrypt("worker-only"), PORT: encrypt("8000") });
- const { captured } = await run([
- repoService({ id: "api", name: "api", build: "." }),
- repoService({ id: "worker", name: "worker", build: "." }),
- ], undefined, undefined, { SHARED: "shared" });
- expect(captured.map(({ config }) => config.envVars)).toEqual([
- { SHARED: "shared", API_SECRET: "api-only", PORT: "3000" },
- { SHARED: "shared", WORKER_SECRET: "worker-only", PORT: "8000" },
- ]);
- });
-
it("#795 carries project env into the posted root-Dockerfile setup without duplicate service env", async () => {
const projectEnv = {
DATABASE_URI: "postgres://db/app",
diff --git a/apps/api/src/modules/deployments/deployment.controller.ts b/apps/api/src/modules/deployments/deployment.controller.ts
index 45df8370e..7e4bb85c6 100644
--- a/apps/api/src/modules/deployments/deployment.controller.ts
+++ b/apps/api/src/modules/deployments/deployment.controller.ts
@@ -2,7 +2,7 @@
* Deployment controller - Hono request handlers.
*/
-import { readOptionalJsonBody } from "../../lib/request-body";
+import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
import type { Context } from "hono";
import { AppError } from "@repo/core";
import { freezeContext } from "@repo/platform";
@@ -124,7 +124,8 @@ export async function restorePlan(c: Context) {
}
export async function pin(c: Context) {
- const result = await getPlatformKernel().deployments.pin(operationContext(c), param(c, "id"), await readOptionalJsonBody(c));
+ const body = await c.req.json<{ pinned?: boolean }>().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/deployments/deployment.controller"); return ({}); });
+ const result = await getPlatformKernel().deployments.pin(operationContext(c), param(c, "id"), body);
applyOperationContext(c, result.context);
return c.json({ data: result.data });
}
@@ -245,7 +246,8 @@ export async function buildStatus(c: Context) {
* resolves the latest commit on the branch — the auto-redeploy semantic.
*/
export async function buildRedeploy(c: Context) {
- const result = await getPlatformKernel().deployments.redeploy(operationContext(c), param(c, "id"), await readOptionalJsonBody(c));
+ const body = await c.req.json<{ useExistingCommit?: boolean; reuseBuild?: boolean }>().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/deployments/deployment.controller"); return ({}); });
+ const result = await getPlatformKernel().deployments.redeploy(operationContext(c), param(c, "id"), body);
applyOperationContext(c, result.context);
return c.json({ success: true, ...result.data });
}
diff --git a/apps/api/src/modules/deployments/route-issues-warning.test.ts b/apps/api/src/modules/deployments/route-issues-warning.test.ts
index 662d10f40..ef824d981 100644
--- a/apps/api/src/modules/deployments/route-issues-warning.test.ts
+++ b/apps/api/src/modules/deployments/route-issues-warning.test.ts
@@ -1,11 +1,12 @@
import { describe, expect, it, vi } from "vitest";
// The function under test is pure; everything else this module reaches (DB, SSE,
-// notifications) is a side effect the assertion doesn't want.
+// notifications, favicon probing) is a side effect the assertion doesn't want.
// `@repo/adapters` stays REAL — `isEdgeDownMessage` is the branch being pinned.
vi.mock("@repo/db", () => ({ repos: {} }));
vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: {} }));
vi.mock("../../lib/audit", () => ({ audit: {} }));
+vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn() }));
vi.mock("@repo/platform/engine/modules/deployments/session-manager", () => ({}));
vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({
onWebmailDeployed: vi.fn(),
diff --git a/apps/api/src/modules/domains/domain.controller.ts b/apps/api/src/modules/domains/domain.controller.ts
index 7bd1b11b5..c1fd4c0fd 100644
--- a/apps/api/src/modules/domains/domain.controller.ts
+++ b/apps/api/src/modules/domains/domain.controller.ts
@@ -1,5 +1,5 @@
/** HTTP paths, status codes, and envelopes over the shared domain operations. */
-import { readOptionalJsonBody } from "../../lib/request-body";
+import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
import type { Context } from "hono";
import type { TAddDomainBody } from "@repo/contracts";
import { getPlatformKernel } from "@repo/platform/engine/lib/platform";
@@ -102,5 +102,5 @@ export async function renewAllSsl(c: Context) {
return c.json({ data: await operationData(c, operations().renewAllSsl(operationContext(c))) });
}
export async function verifyPending(c: Context) {
- return c.json({ data: await operationData(c, operations().verifyPending(operationContext(c), await readOptionalJsonBody(c))) });
+ return c.json({ data: await operationData(c, operations().verifyPending(operationContext(c), await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/domains/domain.controller"); return ({}); }))) });
}
diff --git a/apps/api/src/modules/domains/routing-apply.service.test.ts b/apps/api/src/modules/domains/routing-apply.service.test.ts
index c63228aff..c3a3b8933 100644
--- a/apps/api/src/modules/domains/routing-apply.service.test.ts
+++ b/apps/api/src/modules/domains/routing-apply.service.test.ts
@@ -132,7 +132,7 @@ describe("Cloud Docker route tables", () => {
} as Record
)[`${container}:${port}`];
if (!published) throw new Error("service port is not published");
- return { vm: "shared-vm", port: published };
+ return { workspace: "shared-vm", port: published };
});
});
it("repairs an existing single static container route without rebuilding", async () => {
@@ -149,7 +149,7 @@ describe("Cloud Docker route tables", () => {
};
domainRepo.listByProject.mockResolvedValue([savedDomain]);
domainRepo.findByHostname.mockResolvedValue(savedDomain);
- target.mockResolvedValue({ vm: "shared-vm", port: 30000 });
+ target.mockResolvedValue({ workspace: "shared-vm", port: 30000 });
await applyCloudRouting({
project: { ...base, workloadType: "static", hasServer: false, port: 3000 } as never,
deployment: {
@@ -186,9 +186,9 @@ describe("Cloud Docker route tables", () => {
["stack-api.opsh.io", 30003, false],
]);
expect(publish.mock.calls.map((call) => call[3].routes[0].action)).toEqual([
- { kind: "proxy", vm: "shared-vm", port: 30001 },
- { kind: "proxy", vm: "shared-vm", port: 30002 },
- { kind: "proxy", vm: "shared-vm", port: 30003 },
+ { kind: "proxy", workspace: "shared-vm", port: 30001 },
+ { kind: "proxy", workspace: "shared-vm", port: 30002 },
+ { kind: "proxy", workspace: "shared-vm", port: 30003 },
]);
});
it("resolves project-level domains to their service's exact published port", async () => {
@@ -209,7 +209,7 @@ describe("Cloud Docker route tables", () => {
expect.objectContaining({
routes: [
expect.objectContaining({
- action: { kind: "proxy", vm: "shared-vm", port: 30002 },
+ action: { kind: "proxy", workspace: "shared-vm", port: 30002 },
}),
],
}),
@@ -235,15 +235,15 @@ describe("Cloud Docker route tables", () => {
expect(writes[0]![3].routes).toEqual([
{
match: { path: "/api/status", type: "exact" },
- action: { kind: "proxy", vm: "shared-vm", port: 30001 },
+ action: { kind: "proxy", workspace: "shared-vm", port: 30001 },
},
{
match: { path: "/api/", type: "prefix" },
- action: { kind: "proxy", vm: "shared-vm", port: 30003 },
+ action: { kind: "proxy", workspace: "shared-vm", port: 30003 },
},
{
match: { path: "/", type: "prefix" },
- action: { kind: "proxy", vm: "shared-vm", port: 30001 },
+ action: { kind: "proxy", workspace: "shared-vm", port: 30001 },
},
]);
});
@@ -259,7 +259,7 @@ describe("Cloud Docker route tables", () => {
}],
});
expect(publish).toHaveBeenCalledWith("api.onvo.me", undefined, true, {
- routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", vm: "shared-vm", port: 30003 } }],
+ routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", workspace: "shared-vm", port: 30003 } }],
});
});
it("keeps the old composite table if any path target is missing, while updating other hosts", async () => {
@@ -296,11 +296,11 @@ describe("Cloud Docker route tables", () => {
expect(rules).toEqual([
{
match: { path: "/api/", type: "prefix" },
- action: { kind: "proxy", vm: "shared-vm", port: 30003 },
+ action: { kind: "proxy", workspace: "shared-vm", port: 30003 },
},
{
match: { path: "/", type: "prefix" },
- action: { kind: "proxy", vm: "shared-vm", port: 30001 },
+ action: { kind: "proxy", workspace: "shared-vm", port: 30001 },
},
]);
});
diff --git a/apps/api/src/modules/github/github.controller.ts b/apps/api/src/modules/github/github.controller.ts
index 0e29a6d76..10e49130c 100644
--- a/apps/api/src/modules/github/github.controller.ts
+++ b/apps/api/src/modules/github/github.controller.ts
@@ -1,7 +1,5 @@
/** HTTP input, status, and cookie adapters for shared GitHub operations. */
-import { readOptionalJsonBody } from "../../lib/request-body";
import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
-import { GitHubDisconnectInput, parseInput } from "@repo/contracts";
import type { Context } from "hono";
import { env, runtimeTarget } from "@repo/platform/engine/config/env";
import { auth } from "@repo/platform/engine/lib/auth";
@@ -38,7 +36,7 @@ export async function getLocalStatus(c: Context) {
}
export async function connect(c: Context) {
- const data = await operationData(c, ops().connect(call(c), await readOptionalJsonBody(c)));
+ const data = await operationData(c, ops().connect(call(c), await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/github/github.controller"); return ({}); })));
return c.json(data, 200);
}
export async function claimInstallation(c: Context) {
@@ -52,12 +50,8 @@ export async function setInstanceToken(c: Context) {
return c.json(data, 200);
}
export async function disconnect(c: Context) {
- const body = await readOptionalJsonBody<{ source?: unknown }>(c);
- // Preserve the legacy query option without hiding an invalid JSON value.
- const input = body && typeof body === "object" && !Array.isArray(body)
- ? { ...body, source: body.source ?? c.req.query("source") }
- : body;
- const data = await operationData(c, ops().disconnect(call(c), parseInput(GitHubDisconnectInput, input)));
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/github/github.controller"); return ({}); });
+ const data = await operationData(c, ops().disconnect(call(c), { source: body.source ?? c.req.query("source") }));
return c.json(data, 200);
}
export async function listRepos(c: Context) {
diff --git a/apps/api/src/modules/images/images.service.ts b/apps/api/src/modules/images/images.service.ts
index 6b24ab6c9..b62749d95 100644
--- a/apps/api/src/modules/images/images.service.ts
+++ b/apps/api/src/modules/images/images.service.ts
@@ -91,7 +91,7 @@ export async function listImages(
if (hit) return hit;
const client = await getClientForOrg(organizationId);
- const response = await client.vms.images.list(params);
+ const response = await client.workspaces.images.list(params);
const images = normalizeImages(response);
await store.set(key, images, CACHE_TTL_S);
return images;
diff --git a/apps/api/src/modules/issues/issues.controller.ts b/apps/api/src/modules/issues/issues.controller.ts
index 8ff7404be..6aeb4db26 100644
--- a/apps/api/src/modules/issues/issues.controller.ts
+++ b/apps/api/src/modules/issues/issues.controller.ts
@@ -1,8 +1,9 @@
/** HTTP codecs over shared issue aggregation and the retained health/job services. */
-import { readOptionalJsonBody } from "../../lib/request-body";
+import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
import type { Context } from "hono";
import { getPlatformKernel } from "@repo/platform/engine/lib/platform";
import { operationContext, operationData } from "../../lib/operation-context";
+import { ValidationError } from "@repo/core";
const issues = () => getPlatformKernel().issues;
export async function listIssues(c: Context) {
const result = await operationData(c, issues().list(operationContext(c), { status: c.req.query("status") === "resolved" ? "resolved" : "open" }));
@@ -25,5 +26,10 @@ export async function rescanStatus(c: Context) {
return c.json({ data: await operationData(c, issues().rescanStatus(operationContext(c))) });
}
export async function rescanIssues(c: Context) {
- return c.json({ data: await operationData(c, issues().rescan(operationContext(c), await readOptionalJsonBody(c))) }, 202);
+ const text = await c.req.text();
+ let input;
+ try { input = text.trim() ? JSON.parse(text) : undefined; }
+ catch (diagnosticFailure) {
+ observeCaughtError(diagnosticFailure, "api/modules/issues/issues.controller"); throw new ValidationError("Invalid JSON body"); }
+ return c.json({ data: await operationData(c, issues().rescan(operationContext(c), input)) }, 202);
}
diff --git a/apps/api/src/modules/mail/admin/admin.controller.ts b/apps/api/src/modules/mail/admin/admin.controller.ts
index 51c9a043b..3298be43c 100644
--- a/apps/api/src/modules/mail/admin/admin.controller.ts
+++ b/apps/api/src/modules/mail/admin/admin.controller.ts
@@ -148,7 +148,7 @@ export async function createDomainHandler(c: Context) {
if (!(await isServerInOrg(ctx, serverId))) {
return c.json({ error: "Server not found" }, 404);
}
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/admin/admin.controller"); return ({}); });
try {
const { row, dnsWarning } = await createDomain(serverId, {
domain: String(body.domain ?? ""),
@@ -178,7 +178,7 @@ export async function updateDomainHandler(c: Context) {
}
const domain = c.req.param("domain");
if (!domain) return c.json({ error: "domain required" }, 400);
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/admin/admin.controller"); return ({}); });
try {
const row = await updateDomain(serverId, domain, {
description: body.description != null ? String(body.description) : undefined,
@@ -390,7 +390,7 @@ export async function putOutboundRelayHandler(c: Context) {
if (!(await isServerInOrg(ctx, serverId))) {
return c.json({ error: "Server not found" }, 404);
}
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/admin/admin.controller"); return ({} as Record); });
// Unknown ids become `custom`, which requires an explicit host — so a bad id
// fails validation loudly instead of quietly relaying somewhere unintended.
const provider = isRelayProviderId(body.provider) ? body.provider : "custom";
@@ -560,7 +560,7 @@ export async function createMailboxHandler(c: Context) {
if (!(await isServerInOrg(ctx, serverId))) {
return c.json({ error: "Server not found" }, 404);
}
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/admin/admin.controller"); return ({}); });
try {
const row = await createMailbox(serverId, {
localPart: String(body.localPart ?? ""),
@@ -590,7 +590,7 @@ export async function updateMailboxHandler(c: Context) {
}
const email = c.req.param("email");
if (!email) return c.json({ error: "email required" }, 400);
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/admin/admin.controller"); return ({}); });
try {
const row = await updateMailbox(serverId, email, {
name: body.name != null ? String(body.name) : undefined,
@@ -708,7 +708,7 @@ export async function createAliasHandler(c: Context) {
if (!(await isServerInOrg(ctx, serverId))) {
return c.json({ error: "Server not found" }, 404);
}
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/admin/admin.controller"); return ({}); });
try {
const row = await createAlias(serverId, {
domain: String(body.domain ?? ""),
@@ -743,7 +743,7 @@ export async function updateAliasHandler(c: Context) {
if (!idParam || !Number.isInteger(id)) {
return c.json({ error: "id must be an integer" }, 400);
}
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/admin/admin.controller"); return ({}); });
if (body.active == null) {
return c.json({ error: "active is required" }, 400);
}
@@ -816,7 +816,7 @@ export async function sendTestEmailHandler(c: Context) {
if (!(await isServerInOrg(ctx, serverId))) {
return c.json({ error: "Server not found" }, 404);
}
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/admin/admin.controller"); return ({}); });
try {
const result = await sendTestEmail(serverId, {
to: String(body.to ?? ""),
diff --git a/apps/api/src/modules/mail/mail-credentials.service.ts b/apps/api/src/modules/mail/mail-credentials.service.ts
index 3a24340ff..fa577de7d 100644
--- a/apps/api/src/modules/mail/mail-credentials.service.ts
+++ b/apps/api/src/modules/mail/mail-credentials.service.ts
@@ -7,7 +7,7 @@
* column), via the shared `admin/password.ts` helper. Hashing on the
* target server avoids sending the cleartext or the hash through any
* intermediate process.
- * 2. Update the mailbox password and its rotation timestamp through `admin/psql-runner`.
+ * 2. UPDATE vmail.mailbox SET password = … through `admin/psql-runner`.
* 3. Scrub any leftover plaintext from the state file. We used to mirror
* it back for the credentials card to display; that was a needless
* attack surface and is gone - the only way to "know" the password
@@ -48,7 +48,7 @@ export async function updatePostmasterPassword(
// sidecar, or `sudo -u postgres` on a legacy install) rather than assuming the latter.
await execute(
exec,
- `UPDATE mailbox SET password = ${q(hash)}, passwordlastchange = NOW() WHERE username = ${q(username)};`,
+ `UPDATE mailbox SET password = ${q(hash)} WHERE username = ${q(username)};`,
);
// Persist the new plaintext into state.secrets so the test-email flow
diff --git a/apps/api/src/modules/mail/mail.controller.ts b/apps/api/src/modules/mail/mail.controller.ts
index 6c8be1e96..8f74d97e7 100644
--- a/apps/api/src/modules/mail/mail.controller.ts
+++ b/apps/api/src/modules/mail/mail.controller.ts
@@ -710,7 +710,7 @@ function validateSetupConfig(config: IRedMailConfig | undefined): string | null
export async function startSetup(c: Context) {
if (env.CLOUD_MODE) return c.json({ error: "Not available" }, 404);
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/mail.controller"); return ({}); });
const serverId = body.serverId as string | undefined;
const domain = body.domain as string | undefined;
const startStep = Math.max(1, Math.min(TOTAL_STEPS, Number(body.startStep) || 1));
@@ -1218,7 +1218,7 @@ export async function cancelSetup(c: Context) {
export async function acknowledgeDns(c: Context) {
if (env.CLOUD_MODE) return c.json({ error: "Not available" }, 404);
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/mail.controller"); return ({}); });
const serverId = body.serverId as string | undefined;
if (!serverId) return c.json({ error: "serverId is required" }, 400);
@@ -1267,7 +1267,7 @@ export async function acknowledgeDns(c: Context) {
export async function acknowledgePtr(c: Context) {
if (env.CLOUD_MODE) return c.json({ error: "Not available" }, 404);
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/mail.controller"); return ({}); });
const serverId = body.serverId as string | undefined;
if (!serverId) return c.json({ error: "serverId is required" }, 400);
@@ -1311,7 +1311,7 @@ export async function acknowledgePtr(c: Context) {
export async function resetSetup(c: Context) {
if (env.CLOUD_MODE) return c.json({ error: "Not available" }, 404);
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/mail.controller"); return ({}); });
const serverId = body.serverId as string | undefined;
if (!serverId) return c.json({ error: "serverId is required" }, 400);
@@ -1437,7 +1437,7 @@ export async function saveMailBackupPolicy(c: Context) {
return c.json({ error: "Mail server is not registered / has no domain" }, 404);
}
- const body = (await c.req.json()) as {
+ const body = (await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/mail.controller"); return ({}); })) as {
destinationId?: string;
messageData?: boolean;
keys?: boolean;
@@ -1573,7 +1573,7 @@ export async function listMailBackupRuns(c: Context) {
export async function setPostmasterPassword(c: Context) {
if (env.CLOUD_MODE) return c.json({ error: "Not available" }, 404);
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/mail.controller"); return ({}); });
const serverId = body.serverId as string | undefined;
const password = body.password as string | undefined;
diff --git a/apps/api/src/modules/mail/webmail/webmail.controller.ts b/apps/api/src/modules/mail/webmail/webmail.controller.ts
index d1b7951bf..85eeb5c92 100644
--- a/apps/api/src/modules/mail/webmail/webmail.controller.ts
+++ b/apps/api/src/modules/mail/webmail/webmail.controller.ts
@@ -89,7 +89,7 @@ export async function startDeployAsProjectHandler(c: Context) {
if (env.CLOUD_MODE) return c.json({ error: "Not available" }, 404);
const ctx = getRequestContext(c);
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/webmail/webmail.controller"); return ({}) as Record; });
const mailServerId = body.mailServerId as string | undefined;
const hostname = (body.hostname as string | undefined)?.trim().toLowerCase();
const targetBody = body.target as { kind?: string; serverId?: string } | undefined;
@@ -148,7 +148,7 @@ export async function startExternalDeployAsProjectHandler(c: Context) {
if (env.CLOUD_MODE) return c.json({ error: "Not available" }, 404);
const ctx = getRequestContext(c);
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/mail/webmail/webmail.controller"); return ({}) as Record; });
const hostname = (body.hostname as string | undefined)?.trim().toLowerCase();
if (!hostname || !HOSTNAME_RE.test(hostname))
diff --git a/apps/api/src/modules/mcp/mcp-tools.ts b/apps/api/src/modules/mcp/mcp-tools.ts
index 12cf298e5..737e8e1fe 100644
--- a/apps/api/src/modules/mcp/mcp-tools.ts
+++ b/apps/api/src/modules/mcp/mcp-tools.ts
@@ -42,7 +42,7 @@ export interface McpToolDef {
name: string;
description: string;
inputSchema: Record;
- annotations: { readOnlyHint: boolean; destructiveHint: boolean; openWorldHint: boolean };
+ annotations: { readOnlyHint: boolean; destructiveHint: boolean };
// Dispatch metadata (not sent to the client):
method: string;
path: string; // full path with :params, e.g. /api/projects/:id
@@ -76,8 +76,6 @@ export interface McpPrincipal {
/** Resolved with the same persisted instance-authority policy as HTTP calls. */
instanceAdmin?: boolean;
role: "owner" | "admin" | "member" | "restricted";
- /** For scoped tokens, the current membership in their bound organization. */
- membershipRole?: "owner" | "admin" | "member" | "restricted";
readOnly: boolean;
/** Resource types the token holds grants on — only consulted when role === "restricted". */
grantedRootTypes: ReadonlySet;
@@ -186,12 +184,9 @@ function inputSchema(
function annotationsFor(route: RegisteredRoute): {
readOnlyHint: boolean;
destructiveHint: boolean;
- openWorldHint: boolean;
} {
const spec = route.spec;
- if (isPublicSpec(spec)) {
- return { readOnlyHint: true, destructiveHint: false, openWorldHint: true };
- }
+ if (isPublicSpec(spec)) return { readOnlyHint: true, destructiveHint: false };
const parsed = parsePermissionTag(spec.tag);
const readOnlyHint = route.method === "GET" || spec.readOnly === true;
const destructiveHint =
@@ -200,7 +195,7 @@ function annotationsFor(route: RegisteredRoute): {
(route.method === "DELETE" ||
parsed.action === "admin" ||
/delete|teardown|destroy|remove|wipe|revoke/i.test(route.path)));
- return { readOnlyHint, destructiveHint, openWorldHint: spec.mcp?.openWorld ?? true };
+ return { readOnlyHint, destructiveHint };
}
let cached: McpToolDef[] | null = null;
@@ -355,10 +350,6 @@ export function filterToolsForPrincipal(
principal: McpPrincipal,
): McpToolDef[] {
return tools.filter((t) => {
- const action = assertedAction(t.perm.action);
- const role = principal.membershipRole ?? principal.role;
- if (role !== "restricted" &&
- !roleAllowsResourceType(role, t.perm.leaf as CheckedResourceType, action)) return false;
// Read-only tokens can only call GET — the runtime gate rejects mutations by
// HTTP method, so mirror that exactly rather than guessing from the tag.
if (principal.readOnly && t.method !== "GET") return false;
@@ -382,7 +373,9 @@ export function filterToolsForPrincipal(
if (principal.role === "restricted" && !caps?.has(needed)) return false;
}
- if (principal.role !== "restricted") return true;
+ if (principal.role !== "restricted") {
+ return roleAllowsResourceType(principal.role, t.perm.leaf as CheckedResourceType);
+ }
// "Own projects" scope: the create-capable project wildcard grant reaches the
// dedicated create routes (POST /projects, POST /apps) and the project list
// (which the caller filters to its self-created projects). Checked before the
@@ -408,11 +401,11 @@ export function filterToolsForPrincipal(
// A per-id grant still fails here, correctly: `wildcardGrants` holds only
// resourceId "*" rows.
const held = principal.wildcardGrants.get(t.perm.leaf);
- return held ? permitsAction(held, action) : false;
+ return held ? permitsAction(held, assertedAction(t.perm.action)) : false;
}
if (principalHasGrantFor(principal.grantedRootTypes, t.perm.grantRoot)) return true;
// Same mapping the permission check uses: `domain:admin` ⇒ `domains:delete`.
- const capability = capabilityFor(t.perm.leaf, action);
+ const capability = capabilityFor(t.perm.leaf, assertedAction(t.perm.action));
return !!capability && !!principal.grantedCapabilities?.has(capability);
});
}
@@ -426,7 +419,6 @@ export function toClientTool(t: McpToolDef) {
annotations: {
readOnlyHint: t.annotations.readOnlyHint,
destructiveHint: t.annotations.destructiveHint,
- openWorldHint: t.annotations.openWorldHint,
},
};
}
diff --git a/apps/api/src/modules/mcp/mcp.routes.ts b/apps/api/src/modules/mcp/mcp.routes.ts
index 16d90eab1..9a80ecf68 100644
--- a/apps/api/src/modules/mcp/mcp.routes.ts
+++ b/apps/api/src/modules/mcp/mcp.routes.ts
@@ -128,7 +128,6 @@ async function resolveMcpCaller(token: string, headers: Headers): Promise();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/migration/migration.controller"); return {} as RevealBody; });
const { serverId, containerId } = body;
if (!serverId) return c.json({ error: "serverId is required" }, 400);
if (!containerId) return c.json({ error: "containerId is required" }, 400);
diff --git a/apps/api/src/modules/migration/platform-import-data.test.ts b/apps/api/src/modules/migration/platform-import-data.test.ts
index 57c86d2f1..c857a2a19 100644
--- a/apps/api/src/modules/migration/platform-import-data.test.ts
+++ b/apps/api/src/modules/migration/platform-import-data.test.ts
@@ -6,8 +6,6 @@ const h = vi.hoisted(() => ({
pinned: vi.fn(),
source: vi.fn(),
target: vi.fn(),
- list: vi.fn(),
- handle: vi.fn(),
produce: vi.fn(),
restore: vi.fn(),
dispose: vi.fn(),
@@ -30,7 +28,7 @@ vi.mock("@repo/db", () => ({
activeDeploymentId: "build",
}),
},
- service: { listByProject: h.list },
+ service: { listByProject: async () => [] },
deployment: { findById: async () => ({ containerId: "target-container" }) },
},
}));
@@ -54,7 +52,7 @@ vi.mock("@repo/platform/engine/lib/project-runtime-lock", () => ({
withProjectRuntimeLock: async (_id: string, work: () => Promise) => work(),
}));
vi.mock("@repo/platform/engine/modules/backups/service-handle", () => ({
- serviceHandleFor: h.handle,
+ serviceHandleFor: vi.fn(),
}));
vi.mock("@repo/platform/engine/modules/services/service-container", () => ({
containerIdForService: vi.fn(),
@@ -109,8 +107,6 @@ let target: BackupExecutor;
beforeEach(() => {
vi.resetAllMocks();
h.workspaceId = undefined;
- h.list.mockResolvedValue([{ id: "db", name: "db", projectId: "project" }]);
- h.handle.mockResolvedValue(handle);
h.activity.mockImplementation(async (_id: string, work: () => Promise) => work());
h.pinned.mockResolvedValue({ ip: "203.0.113.8" });
target = {
@@ -125,23 +121,12 @@ beforeEach(() => {
});
});
describe("provider data copy", () => {
- it("rejects a missing native target service before opening a source or restoring data", async () => {
- h.list.mockResolvedValue([{ id: "other-service", name: "api", projectId: "project" }]);
- await expect(copyPlatformData({
- runId: "run", service, projectId: "project", serviceId: "db", deploymentId: "build",
- signal: new AbortController().signal, log: vi.fn(), progress: vi.fn(),
- })).rejects.toMatchObject({ code: "IMPORT_TARGET_SERVICE_MISSING" });
- expect(h.source).not.toHaveBeenCalled();
- expect(h.restore).not.toHaveBeenCalled();
- expect(h.handle).not.toHaveBeenCalled();
- });
it("leaves a destination changed by the operator untouched", async () => {
await expect(
copyPlatformData({
runId: "run",
service,
projectId: "project",
- serviceId: "db",
deploymentId: "replaced-build",
signal: new AbortController().signal,
log: vi.fn(),
@@ -189,10 +174,6 @@ describe("provider data copy", () => {
).rejects.toMatchObject({ code: "IMPORT_DATABASE_EXTENSIONS_MISSING" });
});
it("streams every byte with backpressure, verifies after restore and closes both transports", async () => {
- const targetRow = { id: "db", name: "database", projectId: "project" };
- h.list.mockResolvedValue([
- { id: "api", name: "api", projectId: "project" }, targetRow,
- ]);
const payload = Buffer.alloc(256 * 1024, 0x41);
let producerCompleted = false;
h.produce.mockImplementation(async function* () {
@@ -216,14 +197,12 @@ describe("provider data copy", () => {
runId: "run",
service,
projectId: "project",
- serviceId: "db",
deploymentId: "build",
signal: new AbortController().signal,
log: vi.fn(),
progress,
});
expect(restored).toEqual(payload);
- expect(h.handle).toHaveBeenCalledWith(targetRow, expect.objectContaining({ projectSlug: "app" }));
expect(producerCompleted).toBe(true);
expect(h.dispose).toHaveBeenCalledOnce();
expect(h.source).not.toHaveBeenCalled();
@@ -249,7 +228,6 @@ describe("provider data copy", () => {
runId: "run",
service,
projectId: "project",
- serviceId: "db",
deploymentId: "build",
signal: new AbortController().signal,
log: vi.fn(),
@@ -267,7 +245,6 @@ describe("provider data copy", () => {
runId: "run",
service,
projectId: "project",
- serviceId: "db",
deploymentId: "build",
signal: new AbortController().signal,
log: vi.fn(),
@@ -292,7 +269,6 @@ it("holds the owning Cloud workspace activity lock for the whole transfer", asyn
runId: "run",
service,
projectId: "project",
- serviceId: "db",
deploymentId: "build",
signal,
log: vi.fn(),
diff --git a/apps/api/src/modules/migration/platform-import-plan.test.ts b/apps/api/src/modules/migration/platform-import-plan.test.ts
index 2acc649ba..910545e3f 100644
--- a/apps/api/src/modules/migration/platform-import-plan.test.ts
+++ b/apps/api/src/modules/migration/platform-import-plan.test.ts
@@ -134,7 +134,7 @@ async function review(
}
describe("reviewed platform imports", () => {
- it("keeps secrets server-side and replaces provider database addresses with native service aliases", async () => {
+ it("keeps secrets server-side and replaces provider database addresses with shared project bindings", async () => {
const plan = await review();
expect(plan.ready).toBe(true);
expect(plan.requiresWritePause).toBe(true);
@@ -147,15 +147,7 @@ describe("reviewed platform imports", () => {
valueTemplate: "postgres://app:source-secret@${host}/app",
},
]);
- expect(privatePlan.services[1].environment.DATABASE_URL).toBe(
- "postgres://app:source-secret@database/app",
- );
- expect(privatePlan.projects[0].create.name).toBe("Project");
- expect(privatePlan.projects[0].create.services?.map((row) => row.name)).toEqual([
- "database",
- "website",
- ]);
- expect(JSON.stringify(privatePlan.projects)).not.toContain("source-secret");
+ expect(privatePlan.services[1].environment).not.toHaveProperty("DATABASE_URL");
expect(privatePlan.services[0].environment.PGHOST).toBe(
privatePlan.services[0].create.internalAlias,
);
@@ -183,113 +175,6 @@ describe("reviewed platform imports", () => {
code: "IMPORT_SOURCE_CHANGED",
});
});
- it("names storage per service inside one destination project", async () => {
- inventory.services[1].volumes = [{ id: "files", mountPath: "/data" }];
- const plan = await loadReviewedImport(ctx, (await review()).planId);
- expect(plan.projects[0].create.services?.flatMap((service) => service.volumes ?? [])).toEqual([
- "database-data-0:/var/lib/postgresql/data",
- "website-data-0:/data",
- ]);
- expect(plan.projects[0].create.services?.[1].dependsOn).toEqual(["database"]);
- });
- it.each(["repository", "commit", "branch"])(
- "splits incompatible Git %s without losing revisions or private connections",
- async (difference) => {
- inventory.services = ["one", "two"].map((id) =>
- service({
- id,
- name: id,
- image: undefined,
- repository: difference === "repository" ? `owner/${id}` : "owner/repo",
- commit: (difference === "commit" && id === "two" ? "b" : "a").repeat(40),
- branch: difference === "branch" ? id : "main",
- privateDomain: `${id}.railway.internal`,
- env: id === "two" ? { API_URL: "http://one.railway.internal:3000/api?secret=keep" } : {},
- }),
- );
- const result = await review(
- inventory.services.map((service) => ({
- id: service.id,
- name: service.name,
- data: "empty",
- })),
- );
- expect(result.ready, JSON.stringify(result)).toBe(true);
- expect(result.projects).toEqual([
- { name: "project-one", serviceIds: ["one"] },
- { name: "project-two", serviceIds: ["two"] },
- ]);
- const plan = await loadReviewedImport(ctx, result.planId);
- expect(plan.projects.map((project) => project.create.gitRepo)).toEqual(
- difference === "repository" ? ["one", "two"] : ["repo", "repo"],
- );
- expect(plan.services[1].bindings).toEqual([
- {
- sourceId: "one",
- envKey: "API_URL",
- valueTemplate: "http://${host}:3000/api?secret=keep",
- },
- ]);
- expect(plan.services.map((s) => s.source.commit)).toEqual(
- inventory.services.map((s) => s.commit),
- );
- expect(h.info.mock.calls.map(([input]) => input.owner)).toEqual(["owner", "owner"]);
- expect(h.info.mock.calls.map(([input]) => input.branch)).toEqual(
- inventory.services.map((s) => s.commit),
- );
- },
- );
- it("keeps compatible source services together and rejects composite cross-project variables during review", async () => {
- const git = (id: string, repository: string) =>
- service({
- id,
- name: id,
- image: undefined,
- repository,
- commit: "a".repeat(40),
- privateDomain: `${id}.railway.internal`,
- });
- inventory.services = [git("one", "owner/repo"), git("two", "owner/repo")];
- const choices = () =>
- inventory.services.map((s) => ({ id: s.id, name: s.name, data: "empty" as const }));
- expect((await review(choices())).projects).toEqual([
- { name: "Project", serviceIds: ["one", "two"] },
- ]);
- inventory.services.push(git("three", "owner/other"));
- inventory.services[2].env = { HOSTS: "one.railway.internal,two.railway.internal" };
- const result = await review(choices());
- expect(result.ready).toBe(false);
- expect(result.services[2].blockers.join(" ")).toContain("separate connection variable");
- });
- it("blocks unavailable private listeners and ambiguous host templates before source downtime", async () => {
- inventory.services = [
- service({
- id: "store",
- name: "store",
- port: undefined,
- privateDomain: "store.railway.internal",
- }),
- ...["one", "two"].map((id) =>
- service({
- id,
- name: id,
- image: undefined,
- repository: `owner/${id}`,
- commit: "a".repeat(40),
- env:
- id === "one"
- ? { HOST: "store.railway.internal" }
- : { HOST: "store.railway.internal-${host}" },
- }),
- ),
- ];
- const result = await review(
- inventory.services.map((s) => ({ id: s.id, name: s.name, data: "empty" })),
- );
- expect(result.ready).toBe(false);
- expect(result.services[1].blockers.join(" ")).toContain("private listener port");
- expect(result.services[2].blockers.join(" ")).toContain("cannot be safely converted");
- });
it("ignores pagination order and changing volume size, but never ignores changed configuration", () => {
const next = structuredClone(inventory);
next.services.reverse();
@@ -317,22 +202,16 @@ describe("reviewed platform imports", () => {
const reviewed = await review();
expect(reviewed.ready).toBe(true);
expect(
- (await loadReviewedImport(ctx, reviewed.planId)).services[1].environment.DATABASE_URL,
- ).toBe("postgres://app:source-secret@database/app");
+ (await loadReviewedImport(ctx, reviewed.planId)).services[1].bindings[0].valueTemplate,
+ ).toBe("postgres://app:source-secret@${host}/app");
});
- it("rejects conflicting service names and enforces destination access before planning", async () => {
+ it("rejects conflicting project names and enforces destination access before planning", async () => {
await expect(
review([
{ id: "db", name: "Same Name", data: "copy" },
{ id: "app", name: "same-name", data: "empty" },
]),
).rejects.toMatchObject({ code: "IMPORT_NAME_INVALID" });
- await expect(
- review([
- { id: "db", name: "api.v2", data: "copy" },
- { id: "app", name: "api v2", data: "empty" },
- ]),
- ).rejects.toMatchObject({ code: "IMPORT_NAME_INVALID" });
h.authorize.mockRejectedValue(new Error("forbidden"));
await expect(review()).rejects.toThrow("forbidden");
});
@@ -373,7 +252,7 @@ describe("reviewed platform imports", () => {
{ sourceId: external.id, envKey: "DATABASE_URL" },
]);
expect(privatePlan.services[1].create.services?.[0].volumes).toEqual([
- "database-data-0:/var/lib/postgresql",
+ "data-0:/var/lib/postgresql",
]);
// Supplying secrets does not falsely report provider configuration drift.
expect(h.discover).toHaveBeenCalledTimes(2);
@@ -402,9 +281,6 @@ it("uses the existing Compose build for a custom Dockerfile and preserves readin
readiness: { path: "/health" },
services: [{ build: "apps/api", dockerfile: "docker/production.Dockerfile" }],
});
- expect(plan.projects[0].create.services?.[0].advanced).toMatchObject({
- readiness: { path: "/health", port: 3000 },
- });
expect(h.info).not.toHaveBeenCalled();
});
it("blocks an unavailable custom Dockerfile before import", async () => {
diff --git a/apps/api/src/modules/migration/platform-import-worker.test.ts b/apps/api/src/modules/migration/platform-import-worker.test.ts
index 446bd3f5c..2f4eaf5e9 100644
--- a/apps/api/src/modules/migration/platform-import-worker.test.ts
+++ b/apps/api/src/modules/migration/platform-import-worker.test.ts
@@ -1,26 +1,20 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
-import { AppError, ConflictError } from "@repo/core";
+import { AppError } from "@repo/core";
import { withProjectRuntimeLock } from "@repo/platform/engine/lib/project-runtime-lock";
import type { ExecutionContext } from "@repo/platform";
import type {
PrivateImportPlan,
PlannedImportService,
} from "@repo/platform/engine/modules/migration/platform-import-plan";
-import { platformImportProjects } from "@repo/platform/engine/modules/migration/platform-import-project";
const h = vi.hoisted(() => ({
ensure: vi.fn(),
merge: vi.fn(),
- list: vi.fn(),
- project: vi.fn(),
- sourceService: vi.fn(),
- rows: [] as Array<{ id: string; projectId: string; name: string }>,
- view: vi.fn(),
connect: vi.fn(),
+ view: vi.fn(),
deploy: vi.fn(),
copy: vi.fn(),
preflight: vi.fn(),
prepareTarget: vi.fn(),
- routes: vi.fn(),
authorize: vi.fn(),
disable: vi.fn(),
bind: vi.fn(),
@@ -35,8 +29,7 @@ const h = vi.hoisted(() => ({
vi.mock("@repo/db", () => ({
withAdvisoryLock: async (_key: string, fn: () => Promise) => fn(),
repos: {
- service: { listByProject: h.list },
- project: { update: h.update, findById: h.project },
+ project: { update: h.update, findById: async (id: string) => ({ id, workspaceId: null }) },
dockerMigrationRun: {
bindImportedProject: h.bind,
findById: h.find,
@@ -47,11 +40,11 @@ vi.mock("@repo/db", () => ({
vi.mock("@repo/platform/engine/modules/projects/project-crud.service", () => ({
ensureProject: h.ensure,
}));
-vi.mock("@repo/platform/engine/modules/services/service-environment-state", () => ({
- mergeServiceEnvVars: h.merge,
+vi.mock("@repo/platform/engine/modules/projects/project-env.service", () => ({
+ mergeEnvVars: h.merge,
}));
-vi.mock("@repo/platform/engine/modules/services/service.service", () => ({
- createService: h.sourceService,
+vi.mock("@repo/platform/engine/modules/projects/project-connection.service", () => ({
+ createConnection: h.connect,
}));
vi.mock("@repo/platform/engine/modules/projects/project-runtime.service", () => ({
disableProject: h.disable,
@@ -59,9 +52,6 @@ vi.mock("@repo/platform/engine/modules/projects/project-runtime.service", () =>
vi.mock("@repo/platform/engine/modules/apps/app-settings.service", () => ({
getAppConnectionView: h.view,
}));
-vi.mock("@repo/platform/engine/modules/projects/project-connection.service", () => ({
- createConnection: h.connect,
-}));
vi.mock("@repo/platform/engine/modules/deployments/build.service", () => ({
triggerDeployment: h.deploy,
}));
@@ -72,9 +62,6 @@ vi.mock("@repo/platform/engine/modules/migration/platform-import-data", () => ({
vi.mock("@repo/platform/engine/modules/migration/migration-runtime", () => ({
prepareMigrationTarget: h.prepareTarget,
}));
-vi.mock("@repo/platform/engine/modules/migration/migration-routes", () => ({
- saveMigrationRoutes: h.routes,
-}));
vi.mock("@repo/platform/engine/modules/migration/platform-import-health", () => ({
verifyPlatformDeployment: h.verify,
}));
@@ -109,11 +96,7 @@ const service = (id: string, kind: "app" | "database" | "worker"): PlannedImport
...(kind === "database" ? { database: "pg_dump" } : { commit: "a".repeat(40), branch: "main" }),
},
data: "copy",
- create: {
- name: id,
- internalAlias: id,
- services: [{ name: id, image: "image:1", volumes: [`${id}-data:/data`] }],
- },
+ create: { name: id },
environment: { TOKEN: "secret" },
bindings: [],
});
@@ -124,19 +107,11 @@ const planFor = (services: PlannedImportService[]) =>
userId: "user",
targetServerId: "server",
services,
- projectName: "imported-project",
- projects: platformImportProjects("imported-project", "server", services),
}) as PrivateImportPlan;
let row: any;
beforeEach(() => {
vi.resetAllMocks();
h.events.length = 0;
- h.rows.length = 0;
- h.routes.mockResolvedValue([]);
- h.project.mockImplementation(async (id) => ({ id, workspaceId: null }));
- h.list.mockImplementation(async (projectId) =>
- h.rows.filter((row) => row.projectId === projectId),
- );
row = {
id: "run",
organizationId: "org",
@@ -154,43 +129,24 @@ beforeEach(() => {
});
h.ensure.mockImplementation(async (body) => {
h.events.push(`create:${body.name}`);
- h.rows.push(
- ...body.services.map((row: { name: string }) => ({
- ...row,
- id: `${body.name}-${row.name}`,
- projectId: body.name,
- })),
- );
return { project_id: body.name };
});
- h.sourceService.mockImplementation(async (_ctx, projectId, body) => {
- h.rows.push({ ...body, id: `${projectId}-${body.name}`, projectId });
- });
- let deploymentCount = 0;
h.deploy.mockImplementation(async (_ctx, input) => {
- h.events.push(`deploy:${input.projectId}:${input.serviceIds.length}`);
- return { deployment: { id: `${input.projectId}-build-${++deploymentCount}` } };
+ h.events.push(`deploy:${input.projectId}`);
+ return { deployment: { id: `${input.projectId}-build` } };
});
h.copy.mockImplementation(async (input) => {
- h.events.push(`copy:${input.service.source.id}`);
+ h.events.push(`copy:${input.projectId}`);
+ });
+ h.view.mockResolvedValue({
+ outputs: [{ id: "database-url", internal: true, value: "postgres://new" }],
});
- h.view.mockImplementation(async () => ({
- outputs: h.rows.map((row) => ({
- id: `${row.id}:url`,
- sourceServiceId: row.id,
- internal: true,
- value: "postgres://new",
- })),
- }));
h.prepareSource.mockImplementation(async () => {
h.events.push("pause-project");
});
h.restoreSource.mockImplementation(async (_run, resume) => {
h.events.push(resume ? "resume-project" : "restore-config");
});
- h.connect.mockImplementation(async (_ctx, target, input) => {
- h.events.push(`connect:${input.sourceProjectId}:${target}`);
- });
});
const lifecycle = (signal = new AbortController().signal) => ({
signal,
@@ -203,149 +159,6 @@ const lifecycle = (signal = new AbortController().signal) => ({
}),
});
describe("provider import through normal project operations", () => {
- it("copies all volumes before deploying multiple repositories in dependency order with native links", async () => {
- const db = service("db", "database"),
- app = service("app", "app"),
- worker = service("worker", "worker");
- for (const entry of [app, worker])
- Object.assign(entry.create, {
- gitProvider: "github",
- gitOwner: "owner",
- gitRepo: entry.source.id,
- gitBranch: "main",
- });
- worker.source.commit = "b".repeat(40);
- app.bindings = [
- { sourceId: "db", envKey: "DB_URL", valueTemplate: "postgres://secret@${host}:5432/store" },
- ];
- worker.bindings = [{ sourceId: "app", envKey: "APP_HOST", valueTemplate: "${host}" }];
- app.environment.DB_URL = "postgres://secret@db:5432/store";
- worker.environment.APP_HOST = "app";
- const services = [worker, app, db];
- const plan = { ...planFor(services), sourceControl: "railway-project" as const };
- await executePlatformImport(ctx, "run", plan, lifecycle());
- expect(h.ensure.mock.calls.map(([body]) => body.gitRepo)).toEqual(["worker", "app", undefined]);
- expect(
- h.ensure.mock.calls.every(([body]) => body.services.every((s: any) => !s.dependsOn.length)),
- ).toBe(true);
- expect(h.copy.mock.calls.map(([input]) => [input.projectId, input.serviceId])).toEqual([
- ["imported-project-db", "imported-project-db-db"],
- ["imported-project-app", "imported-project-app-app"],
- ["imported-project-worker", "imported-project-worker-worker"],
- ]);
- expect(h.events.indexOf("copy:worker")).toBeLessThan(
- h.events.indexOf("deploy:imported-project-db:1"),
- );
- expect(h.events.indexOf("healthy:imported-project-db-build-1")).toBeLessThan(
- h.events.indexOf("connect:imported-project-db:imported-project-app"),
- );
- expect(h.events.indexOf("connect:imported-project-db:imported-project-app")).toBeLessThan(
- h.events.indexOf("deploy:imported-project-app:1"),
- );
- expect(h.connect).toHaveBeenCalledWith(
- ctx,
- "imported-project-app",
- {
- sourceProjectId: "imported-project-db",
- outputId: "imported-project-db-db:url",
- envKey: "DB_URL",
- mode: "internal",
- valueTemplate: "postgres://secret@${host}:5432/store",
- },
- { defer: true },
- );
- expect(
- h.merge.mock.calls.flatMap(([, , , input]) => input.upserts.map((v: any) => v.key)),
- ).not.toContain("DB_URL");
- expect(h.deploy.mock.calls.map(([, input]) => [input.projectId, input.commitSha])).toEqual([
- ["imported-project-db", undefined],
- ["imported-project-app", "a".repeat(40)],
- ["imported-project-worker", "b".repeat(40)],
- ]);
- expect(h.verify).toHaveBeenCalledTimes(3);
- expect(row.recovery.providerImport.completed).toEqual(["db", "app", "worker"]);
- });
- it("does not start a cross-project consumer if its private connection fails", async () => {
- const db = service("db", "database"),
- app = service("app", "app"),
- worker = service("worker", "worker");
- for (const entry of [app, worker])
- Object.assign(entry.create, { gitOwner: "owner", gitRepo: entry.source.id });
- app.bindings = [{ sourceId: "db", envKey: "DB_URL" }];
- const plan = { ...planFor([app, db, worker]), sourceControl: "railway-project" as const };
- row.recovery.providerImport.planEnc = JSON.stringify(plan);
- h.connect.mockRejectedValue(new Error("Private network unavailable"));
- await expect(executePlatformImport(ctx, "run", plan, lifecycle())).rejects.toThrow(
- "Private network unavailable",
- );
- expect(h.deploy).toHaveBeenCalledTimes(1);
- expect(row.recovery.providerImport.completed).toEqual([]);
- expect(h.restoreSource).not.toHaveBeenCalledWith("run", true, expect.anything());
- await pauseFailedPlatformImport("run");
- expect(h.disable).toHaveBeenCalledExactlyOnceWith(
- "imported-project-db",
- "org",
- "imported-project-db-build-1",
- );
- expect(h.restoreSource).toHaveBeenLastCalledWith("run", true);
- expect(h.disable.mock.invocationCallOrder[0]).toBeLessThan(
- h.restoreSource.mock.invocationCallOrder[1],
- );
- });
- it("stages custom domains through native migration routing before pausing the source", async () => {
- const web = service("web", "app");
- web.create.name = "storefront";
- web.source.domains = [
- { hostname: "shop.example.com", portable: true },
- { hostname: "www.example.com", portable: true },
- { hostname: "shop.up.railway.app", portable: false },
- ];
- const plan = { ...planFor([web]), sourceControl: "railway-project" as const };
- const flow = lifecycle();
- await executePlatformImport(ctx, "run", plan, flow);
- expect(h.routes).toHaveBeenCalledWith(
- ctx,
- "imported-project",
- {
- storefront: [
- { domainType: "custom", customDomain: "shop.example.com" },
- { domainType: "custom", customDomain: "www.example.com" },
- ],
- },
- flow.log,
- );
- expect(h.routes.mock.invocationCallOrder[0]).toBeLessThan(
- h.prepareSource.mock.invocationCallOrder[0],
- );
- expect(h.routes.mock.invocationCallOrder[0]).toBeLessThan(h.copy.mock.invocationCallOrder[0]);
- });
-
- it("reports domain conflicts without pausing Railway or deploying the destination", async () => {
- const app = service("app", "app");
- app.source.domains = [{ hostname: "taken.example.com", portable: true }];
- h.routes.mockRejectedValueOnce(
- new ConflictError("The domain is already connected to another project."),
- );
- await expect(
- executePlatformImport(
- ctx,
- "run",
- {
- ...planFor([app]),
- sourceControl: "railway-project",
- },
- lifecycle(),
- ),
- ).rejects.toMatchObject({
- statusCode: 409,
- code: "IMPORT_DOMAIN_REVIEW_REQUIRED",
- message: "The domain is already connected to another project.",
- });
- expect(h.prepareSource).not.toHaveBeenCalled();
- expect(h.copy).not.toHaveBeenCalled();
- expect(h.deploy).not.toHaveBeenCalled();
- });
-
it("prepares managed capacity before pausing Railway and does not stop the source if provisioning fails", async () => {
const plan = { ...planFor([service("app", "app")]), sourceControl: "railway-project" as const };
const flow = lifecycle();
@@ -381,136 +194,6 @@ describe("provider import through normal project operations", () => {
expect(h.events.indexOf("pause-project")).toBeLessThan(h.events.indexOf("copy:db"));
expect(h.events.indexOf("restore-config")).toBeLessThan(firstDeployment);
expect(h.copy.mock.calls.every(([input]) => input.deploymentId === undefined)).toBe(true);
- expect(h.ensure).toHaveBeenCalledTimes(1);
- expect(h.deploy).toHaveBeenCalledTimes(1);
- expect(new Set(h.copy.mock.calls.map(([input]) => input.projectId))).toEqual(
- new Set(["imported-project"]),
- );
- expect(new Set(h.copy.mock.calls.map(([input]) => input.serviceId)).size).toBe(3);
- expect(new Set(Object.values(row.recovery.providerImport.projects))).toEqual(
- new Set(["imported-project"]),
- );
- });
- it("imports two source projects as two native projects, keeping identical service names separate", async () => {
- for (const name of ["first-project", "second-project"]) {
- const services = [service("db", "database"), service("app", "app")];
- services.forEach((service) => (service.transfer = "cold-volume"));
- const plan = { ...planFor(services), sourceControl: "railway-project" as const };
- plan.projectName = name;
- plan.projects[0].create.name = name;
- await executePlatformImport(ctx, name, plan, lifecycle());
- expect(new Set(Object.values(row.recovery.providerImport.projects))).toEqual(new Set([name]));
- }
- expect(h.ensure.mock.calls.map(([body]) => body.name)).toEqual([
- "first-project",
- "second-project",
- ]);
- expect(h.rows.map((row) => row.projectId)).toEqual([
- "first-project",
- "first-project",
- "second-project",
- "second-project",
- ]);
- expect(h.copy.mock.calls.map(([input]) => [input.projectId, input.serviceId])).toEqual([
- ["first-project", "first-project-db"],
- ["first-project", "first-project-app"],
- ["second-project", "second-project-db"],
- ["second-project", "second-project-app"],
- ]);
- });
- it("stores each service's environment separately instead of merging it into project-wide values", async () => {
- const app = service("app", "app"),
- db = service("db", "database");
- app.environment = { PORT: "3000", TOKEN: "app-secret" };
- db.environment = { PORT: "5432", TOKEN: "database-secret" };
- await executePlatformImport(ctx, "run", planFor([app, db]), lifecycle());
- for (const entry of [app, db]) {
- expect(h.merge).toHaveBeenCalledWith(
- ctx,
- "imported-project",
- `imported-project-${entry.source.id}`,
- {
- environment: "production",
- deletes: [],
- upserts: Object.entries(entry.environment).map(([key, value]) => ({
- key,
- value,
- isSecret: true,
- sourceId: null,
- })),
- },
- );
- }
- });
- it("adds a source-built app through the native service creator in the same project", async () => {
- const app = service("app", "app");
- app.create = {
- name: "app",
- gitOwner: "owner",
- gitRepo: "repo",
- gitBranch: "main",
- framework: "nextjs",
- rootDirectory: "apps/web",
- installCommand: "bun install",
- startCommand: "bun start",
- port: 3000,
- };
- await executePlatformImport(ctx, "run", planFor([app, service("db", "database")]), lifecycle());
- expect(h.ensure).toHaveBeenCalledTimes(1);
- expect(h.sourceService).toHaveBeenCalledWith(
- ctx,
- "imported-project",
- expect.objectContaining({
- name: "app",
- kind: "monorepo",
- rootDirectory: "apps/web",
- framework: "nextjs",
- ports: ["3000"],
- exposed: false,
- }),
- );
- expect(h.deploy).toHaveBeenLastCalledWith(
- ctx,
- expect.objectContaining({
- projectId: "imported-project",
- commitSha: "a".repeat(40),
- }),
- );
- });
- it("rejects reviews without destination projects before allocating a destination", async () => {
- const plan = planFor([service("app", "app")]);
- delete (plan as Partial).projects;
- await expect(executePlatformImport(ctx, "run", plan, lifecycle())).rejects.toMatchObject({
- code: "IMPORT_REVIEW_EXPIRED",
- });
- expect(h.ensure).not.toHaveBeenCalled();
- expect(h.prepareSource).not.toHaveBeenCalled();
- });
- it("pauses a shared destination once before restoring the Railway source", async () => {
- const plan = planFor([service("app", "app"), service("db", "database")]);
- Object.assign(row.recovery.providerImport, {
- planEnc: JSON.stringify(plan),
- projects: { app: "shared-project", db: "shared-project" },
- deployments: { app: "shared-build", db: "shared-build" },
- });
- await pauseFailedPlatformImport("run");
- expect(h.disable).toHaveBeenCalledExactlyOnceWith("shared-project", "org", "shared-build");
- expect(h.restoreSource).toHaveBeenCalledTimes(1);
- expect(h.disable.mock.invocationCallOrder[0]).toBeLessThan(
- h.restoreSource.mock.invocationCallOrder[0],
- );
- });
- it("can pause its own database-only predecessor when a complete deployment fails", async () => {
- const plan = planFor([service("app", "app"), service("db", "database")]);
- Object.assign(row.recovery.providerImport, {
- planEnc: JSON.stringify(plan),
- projects: { app: "shared", db: "shared" },
- deployments: { app: "failed-build", db: "failed-build" },
- ownedDeploymentIds: ["database-build", "failed-build"],
- });
- h.project.mockResolvedValue({ id: "shared", activeDeploymentId: "database-build" });
- await pauseFailedPlatformImport("run");
- expect(h.disable).toHaveBeenCalledExactlyOnceWith("shared", "org", "database-build");
});
it("stops every imported Railway workload before resuming the source on failure", async () => {
const plan = {
@@ -536,43 +219,29 @@ describe("provider import through normal project operations", () => {
const plan = planFor([worker, app, db]);
await executePlatformImport(ctx, "run", plan, lifecycle());
expect(h.events).toEqual([
- "create:imported-project",
- "deploy:imported-project:1",
- "healthy:imported-project-build-1",
+ "create:db",
+ "create:app",
+ "create:worker",
+ "deploy:db",
+ "healthy:db-build",
"copy:db",
"copy:app",
+ "deploy:app",
+ "healthy:app-build",
"copy:worker",
- "deploy:imported-project:3",
- "healthy:imported-project-build-2",
+ "deploy:worker",
+ "healthy:worker-build",
]);
- expect(h.ensure).toHaveBeenCalledExactlyOnceWith(plan.projects[0].create, "org", ctx, {
- mustCreate: true,
- });
- expect(h.merge).toHaveBeenCalledWith(
+ expect(h.ensure).toHaveBeenCalledWith(app.create, "org", ctx, { mustCreate: true });
+ expect(h.connect).toHaveBeenCalledWith(
ctx,
- "imported-project",
- "imported-project-app",
- expect.objectContaining({
- upserts: [{ key: "DATABASE_URL", value: "postgres://new", sourceId: null, isSecret: true }],
- }),
+ "app",
+ { sourceProjectId: "db", outputId: "database-url", envKey: "DATABASE_URL", mode: "internal" },
+ { defer: true },
);
- expect(h.deploy).toHaveBeenNthCalledWith(
- 1,
+ expect(h.deploy).toHaveBeenCalledWith(
ctx,
- expect.objectContaining({
- projectId: "imported-project",
- serviceIds: ["imported-project-db"],
- strictServiceScope: true,
- }),
- );
- expect(h.deploy).toHaveBeenNthCalledWith(
- 2,
- ctx,
- expect.objectContaining({
- projectId: "imported-project",
- serviceIds: ["imported-project-db", "imported-project-app", "imported-project-worker"],
- strictServiceScope: true,
- }),
+ expect.objectContaining({ projectId: "app", commitSha: "a".repeat(40), branch: "main" }),
);
expect(row.recovery.providerImport.completed).toEqual(["db", "app", "worker"]);
});
@@ -584,13 +253,7 @@ describe("provider import through normal project operations", () => {
executePlatformImport(ctx, "run", planFor([app, service("db", "database")]), lifecycle()),
).rejects.toThrow("restore failed");
expect(h.deploy).toHaveBeenCalledTimes(1);
- expect(h.deploy).toHaveBeenCalledWith(
- ctx,
- expect.objectContaining({
- projectId: "imported-project",
- serviceIds: ["imported-project-db"],
- }),
- );
+ expect(h.deploy).toHaveBeenCalledWith(ctx, expect.objectContaining({ projectId: "db" }));
});
it("checkpoints the created deployment before observing a cancelled phase", async () => {
const flow = lifecycle();
@@ -600,7 +263,7 @@ describe("provider import through normal project operations", () => {
await expect(
executePlatformImport(ctx, "run", planFor([service("app", "app")]), flow),
).rejects.toThrow("cancelled");
- expect(row.recovery.providerImport.deployments).toEqual({ app: "imported-project-build-1" });
+ expect(row.recovery.providerImport.deployments).toEqual({ app: "app-build" });
});
it("rejects dependency cycles rather than starting a partial recursive import", () => {
const a = service("a", "app"),
@@ -609,7 +272,7 @@ describe("provider import through normal project operations", () => {
b.bindings = [{ sourceId: "a", envKey: "URL" }];
expect(() => orderedImports([a, b])).toThrow(/cycle/);
});
- it("pauses imported deployment identities before releasing source recovery", async () => {
+ it("retains databases and pauses only the import's own app deployment identities on failure", async () => {
const plan = planFor([service("app", "app"), service("db", "database")]);
Object.assign(row.recovery.providerImport, {
planEnc: JSON.stringify(plan),
@@ -617,8 +280,7 @@ describe("provider import through normal project operations", () => {
deployments: { app: "app-build", db: "db-build" },
});
await pauseFailedPlatformImport("run");
- expect(h.disable).toHaveBeenCalledWith("p-app", "org", "app-build");
- expect(h.disable).toHaveBeenCalledWith("p-db", "org", "db-build");
+ expect(h.disable).toHaveBeenCalledExactlyOnceWith("p-app", "org", "app-build");
expect(row.recovery.providerImport.cleanupPending).toBe(false);
});
it("leaves the cleanup checkpoint pending if the destination cannot be reached", async () => {
diff --git a/apps/api/src/modules/migration/project-move-role-work.test.ts b/apps/api/src/modules/migration/project-move-role-work.test.ts
index 9fe1ffabd..da237bdb5 100644
--- a/apps/api/src/modules/migration/project-move-role-work.test.ts
+++ b/apps/api/src/modules/migration/project-move-role-work.test.ts
@@ -13,11 +13,6 @@ const h = vi.hoisted(() => ({
byId: new Map>(),
unsettled: [] as Record[],
hostContacted: 0,
- scanned: 0,
- services: [] as Record[],
- placements: [] as Record[],
- volumes: [] as Record[],
- otherContainers: [] as Record[],
}));
// Only these reads exist: a guard that read wider history would call an unmocked method.
@@ -28,44 +23,13 @@ vi.mock("@repo/db", () => ({
findById: async (id: string) => h.byId.get(id),
listUnsettledByProject: async () => h.unsettled,
},
- service: {
- listByProject: async () => h.services,
- listByDeployment: async () => h.placements,
- },
- },
-}));
-
-vi.mock("@repo/platform/engine/modules/migration/docker-inspect.service", () => ({
- discoverServerStack: async (
- _server: string,
- _org: string,
- _progress: unknown,
- options: { onlyContainerIds: string[] },
- ) => {
- h.scanned++;
- return {
- services: options.onlyContainerIds.map((containerId) => ({
- name: "old-compose-name",
- containerId,
- image: "test:live",
- imageId: "sha256:image",
- ports: [],
- volumes: h.volumes,
- env: {},
- running: true,
- })),
- };
},
}));
vi.mock("@repo/platform/engine/modules/migration/migration-runtime", () => ({
createMigrationDockerRuntime: async () => {
h.hostContacted++;
- return {
- listProjectContainerIds: async () => [],
- dispose: async () => {},
- docker: { listContainers: async () => h.otherContainers },
- };
+ return { listProjectContainerIds: async () => [], dispose: async () => {} };
},
}));
@@ -85,67 +49,10 @@ const dep = (id: string, status: string, over: Record = {}) =>
const roleRefs = [{ role: "queue", replica: 1, containerId: "c_queue" }];
const queue = { name: "queue", kind: "worker", command: "php artisan queue:work" };
-describe("in-place imports keep their exact active container identity", () => {
- const containerId = "a".repeat(64);
- const copy = () =>
- loadProjectMoveWorkload({
- organizationId: ORG,
- projectId: "p1",
- targetServerId: "srv_a",
- intent: "copy",
- serviceNames: ["frontend"],
- });
- beforeEach(() => {
- h.byId.set(
- "dep_active",
- dep("dep_active", "ready", { meta: { adopt: true, serverId: "srv_a" } }),
- );
- h.services = [{ id: "svc_web", name: "frontend" }];
- h.placements = [{ serviceId: "svc_web", containerId }];
- });
- it("finds an unlabeled imported container by its renamed service", async () => {
- expect((await copy()).chosen).toEqual([
- expect.objectContaining({ name: "frontend", containerId }),
- ]);
- expect(h.scanned).toBe(1);
- });
- it.each([
- { organizationId: "other-org" },
- { projectId: "other-project" },
- { meta: { adopt: true, serverId: "different-host" } },
- ])("does not trust an unrelated deployment or server: %j", async (patch) => {
- h.byId.set("dep_active", { ...h.byId.get("dep_active"), ...patch });
- await expect(copy()).rejects.toMatchObject({ code: "unknown_service" });
- expect(h.scanned).toBe(0);
- });
- it("ignores a placement whose service is no longer owned by this project", async () => {
- h.services = [];
- await expect(copy()).rejects.toMatchObject({ code: "unknown_service" });
- expect(h.scanned).toBe(0);
- });
- it("refuses an external storage writer, but permits a read-only consumer", async () => {
- h.volumes = [{ source: "shared-data", target: "/data", type: "volume", rw: true }];
- const mount = {
- Name: "shared-data",
- Source: "/var/lib/docker/volumes/shared-data/_data",
- RW: true,
- };
- h.otherContainers = [{ Id: "b".repeat(64), Mounts: [mount] }];
- await expect(copy()).rejects.toMatchObject({ code: "shared_data" });
- mount.RW = false;
- expect((await copy()).chosen).toHaveLength(1);
- });
-});
-
beforeEach(() => {
h.byId.clear();
h.unsettled = [];
h.hostContacted = 0;
- h.scanned = 0;
- h.services = [];
- h.placements = [];
- h.volumes = [];
- h.otherContainers = [];
h.project = {
id: "p1",
organizationId: ORG,
diff --git a/apps/api/src/modules/migration/project-move.test.ts b/apps/api/src/modules/migration/project-move.test.ts
index c9c2603da..9411cd2ea 100644
--- a/apps/api/src/modules/migration/project-move.test.ts
+++ b/apps/api/src/modules/migration/project-move.test.ts
@@ -75,28 +75,6 @@ describe("planProjectMove refusals", () => {
expect(() => plan({ targetServerId: "srv_a" })).toThrow(/already runs on that server/);
});
- it("allows an independent copy on the same server while retaining ownership and scope checks", () => {
- expect(plan({ targetServerId: "srv_a", intent: "copy", serviceNames: ["web"] }).chosen).toHaveLength(1);
- expect(() => plan({ targetServerId: "srv_a", intent: "copy", serviceNames: ["foreign"] })).toThrow(/No running container/);
- expect(() => plan({ targetServerId: "srv_a", intent: "copy", ourContainerIds: [] })).toThrow(/No running containers/);
- });
-
- it("refuses an explicit empty copy scope instead of copying everything", () => {
- expect(() => plan({ intent: "copy", serviceNames: [] })).toThrow(/Select at least one/);
- expect(() => plan({ intent: "copy", serviceNames: [" "] })).toThrow(/Select at least one/);
- expect(plan({ intent: "copy" }).chosen).toHaveLength(1);
- });
-
- it("requires other writers sharing a volume, but allows unselected read-only consumers", () => {
- const volumes = [{ type: "volume" as const, source: "shared", target: "/data", rw: true }];
- const input = { intent: "copy" as const, serviceNames: ["web"], ourContainerIds: ["c_web", "c_worker"],
- discovered: [svc({ volumes }), svc({ name: "worker", containerId: "c_worker", volumes })] };
- expect(() => plan(input)).toThrow(/Include worker/);
- expect(plan({ ...input, serviceNames: ["web", "worker"] }).chosen).toHaveLength(2);
- input.discovered[1]!.volumes = [{ ...volumes[0]!, rw: false }];
- expect(plan(input).chosen).toHaveLength(1);
- });
-
it("refuses when no live container carries the project's label", () => {
expect(() => plan({ ourContainerIds: [] })).toThrow(/No running containers/);
});
@@ -387,9 +365,9 @@ describe("planProjectMove service scope", () => {
}
});
- it("takes every service only when the scope is absent", () => {
+ it("takes every service when the scope is absent or empty", () => {
expect(plan({ ...twoSvc, intent: "copy" }).chosen).toHaveLength(2);
- expect(() => plan({ ...twoSvc, intent: "copy", serviceNames: [] })).toThrow(/Select at least one/);
+ expect(plan({ ...twoSvc, intent: "copy", serviceNames: [] }).chosen).toHaveLength(2);
});
it("names a service it couldn't find rather than copying a partial set", () => {
diff --git a/apps/api/src/modules/migration/railway-wiring.test.ts b/apps/api/src/modules/migration/railway-wiring.test.ts
index d21c42e47..f0ab87402 100644
--- a/apps/api/src/modules/migration/railway-wiring.test.ts
+++ b/apps/api/src/modules/migration/railway-wiring.test.ts
@@ -42,27 +42,6 @@ describe("provider-independent connection values", () => {
});
});
describe("Railway project wiring", () => {
- it("preserves self references and repeated case-insensitive dependency hosts in one connection", () => {
- const db = service("db", {}, 5432);
- const app = service("app", {
- HOSTS: "DB.railway.internal,db.railway.internal,app.railway.internal",
- });
- expect(
- resolveRailwayBindings(
- app,
- new Map([
- ["db", db],
- ["app", app],
- ]),
- ),
- ).toEqual([
- {
- sourceId: "db",
- envKey: "HOSTS",
- valueTemplate: "${host},${host},import-app",
- },
- ]);
- });
it("binds any private service without inferring its type from its image or variable names", () => {
const store = service("store");
const app = service("app", {
@@ -83,9 +62,7 @@ describe("Railway project wiring", () => {
},
]);
expect(store.source.port).toBe(7878);
- expect(app.source.env).toEqual({
- ARBITRARY_SETTING: "custom://alice:password@import-store:7878/second-db?option=1",
- });
+ expect(app.source.env).toEqual({});
});
it("keeps literal shared secrets and rewrites self-hosts without a recursive connection", () => {
const store = service("store", { TOKEN: "secret", HOST: "store.railway.internal" }, 7878);
@@ -101,23 +78,4 @@ describe("Railway project wiring", () => {
expect(app.source.blockers.join(" ")).toMatch(/MISSING/);
expect(app.source.blockers.join(" ")).toMatch(/UNRESOLVED/);
});
- it("keeps hostname-only and multi-host values on the native project network", () => {
- const db = service("db"),
- redis = service("redis");
- const app = service("app", {
- HOST: "db.railway.internal",
- HOSTS: "db.railway.internal,redis.railway.internal",
- });
- const bindings = resolveRailwayBindings(
- app,
- new Map([
- ["db", db],
- ["redis", redis],
- ["app", app],
- ]),
- );
- expect(app.source.env).toEqual({ HOST: "import-db", HOSTS: "import-db,import-redis" });
- expect(new Set(bindings.map((binding) => binding.sourceId))).toEqual(new Set(["db", "redis"]));
- expect(app.source.blockers).toEqual([]);
- });
});
diff --git a/apps/api/src/modules/migration/rollback-target-volumes.test.ts b/apps/api/src/modules/migration/rollback-target-volumes.test.ts
index 571347423..6473d706c 100644
--- a/apps/api/src/modules/migration/rollback-target-volumes.test.ts
+++ b/apps/api/src/modules/migration/rollback-target-volumes.test.ts
@@ -131,19 +131,6 @@ describe("migration rollback and cleanup", () => {
expect(source.dispose).toHaveBeenCalledOnce();
expect(target.dispose).toHaveBeenCalledOnce();
});
- it("keeps stateless copies running and records no originals to restart", async () => {
- await engine.moveData("project", "source", "source", "org",
- { web: "old-container" }, true, { web: "copy" }, [], [], {}, {}, () => {}, undefined, "run", true);
- expect(source.stop).not.toHaveBeenCalled();
- expect(run.recovery.sourceRunningContainerIds).toEqual({});
- });
- it("still quiesces a stateful same-server copy and never starts originally stopped services", async () => {
- h.plan.mockResolvedValue({ items: [{ key: "data" }], createdVolumes: ["copy"], managedPaths: [] });
- await engine.moveData("project", "source", "source", "org",
- { web: "old-container", worker: "asleep" }, true, { web: "copy" }, [], [], {}, {}, () => {}, undefined, "run", true);
- expect(source.stop).toHaveBeenCalledExactlyOnceWith("old-container");
- expect(run.recovery.sourceRunningContainerIds).toEqual({ web: "old-container" });
- });
it("fails before stopping a source when volume reservation fails", async () => {
h.prepare.mockRejectedValueOnce(new Error("reservation conflict"));
await expect(move()).rejects.toThrow("reservation conflict");
diff --git a/apps/api/src/modules/permissions/permissions.controller.ts b/apps/api/src/modules/permissions/permissions.controller.ts
index fa7c3b76d..e2a9c59e5 100644
--- a/apps/api/src/modules/permissions/permissions.controller.ts
+++ b/apps/api/src/modules/permissions/permissions.controller.ts
@@ -1,5 +1,5 @@
/** HTTP paths and legacy envelopes over the shared permission operations. */
-import { readOptionalJsonBody } from "../../lib/request-body";
+import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
import type { Context } from "hono";
import { getPlatformKernel } from "@repo/platform/engine/lib/platform";
import { operationContext, operationData } from "../../lib/operation-context";
@@ -31,7 +31,7 @@ export async function materializeInvitation(c: Context) { return c.json({ data:
export async function acceptInvitation(c: Context) { return c.json({ data: await operationData(c, operations().acceptInvitation(operationContext(c), param(c, "id"))) }); }
export async function rejectInvitation(c: Context) { return c.json({ data: await operationData(c, operations().rejectInvitation(operationContext(c), param(c, "id"))) }); }
export async function cancelInvitation(c: Context) { return c.json({ data: await operationData(c, operations().cancelInvitation(operationContext(c), param(c, "id"))) }); }
-export async function resendInvitation(c: Context) { return c.json({ data: await operationData(c, operations().resendInvitation(operationContext(c), param(c, "id"), await readOptionalJsonBody(c))) }); }
+export async function resendInvitation(c: Context) { return c.json({ data: await operationData(c, operations().resendInvitation(operationContext(c), param(c, "id"), await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/permissions/permissions.controller"); return ({}); }))) }); }
export async function listMembers(c: Context) { return c.json({ data: await operationData(c, operations().listMembers(operationContext(c))) }); }
export async function setMemberRole(c: Context) { return c.json({ data: await operationData(c, operations().setMemberRole(operationContext(c), param(c, "id"), await c.req.json())) }); }
export async function removeMember(c: Context) { return c.json({ data: await operationData(c, operations().removeMember(operationContext(c), param(c, "id"))) }); }
diff --git a/apps/api/src/modules/projects/folder/folder.controller.ts b/apps/api/src/modules/projects/folder/folder.controller.ts
index e0c20c365..41784ea5e 100644
--- a/apps/api/src/modules/projects/folder/folder.controller.ts
+++ b/apps/api/src/modules/projects/folder/folder.controller.ts
@@ -1,11 +1,13 @@
+import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
import type { Context } from "hono";
+import { ValidationError } from "@repo/core";
import { getPlatformKernel } from "@repo/platform/engine/lib/platform";
import { requestApiPublicUrl } from "@repo/platform/engine/lib/public-url";
import { operationContext, applyOperationContext } from "../../../lib/operation-context";
-import { readOptionalJsonBody } from "../../../lib/request-body";
export async function createSession(c: Context) {
- const result = await getPlatformKernel().sources.open(operationContext(c), await readOptionalJsonBody(c), { apiBaseUrl: requestApiPublicUrl(c.req.raw) });
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/projects/folder/folder.controller"); return ({}); });
+ const result = await getPlatformKernel().sources.open(operationContext(c), body, { apiBaseUrl: requestApiPublicUrl(c.req.raw) });
applyOperationContext(c, result.context);
return c.json({ success: true, ...result.data });
}
@@ -16,7 +18,10 @@ export async function uploadRelay(c: Context) {
}
export async function scanSession(c: Context) {
const sessionId = c.req.param("sessionId")!;
- const result = await getPlatformKernel().sources.scan(operationContext(c), sessionId, await readOptionalJsonBody(c));
+ const body = await c.req.text();
+ const input = body.trim() ? await c.req.json().catch((diagnosticFailure) => {
+ observeCaughtError(diagnosticFailure, "api/modules/projects/folder/folder.controller"); throw new ValidationError("Invalid JSON body"); }) : {};
+ const result = await getPlatformKernel().sources.scan(operationContext(c), sessionId, input);
applyOperationContext(c, result.context);
c.header("Cache-Control", "no-store");
return c.json({ success: true, sessionId, ...result.data });
diff --git a/apps/api/src/modules/projects/folder/folder.service.test.ts b/apps/api/src/modules/projects/folder/folder.service.test.ts
index ac85c40ac..02b956160 100644
--- a/apps/api/src/modules/projects/folder/folder.service.test.ts
+++ b/apps/api/src/modules/projects/folder/folder.service.test.ts
@@ -59,7 +59,7 @@ describe("scanFolderSession", () => {
expect(resolveFromLocalMock).toHaveBeenCalledWith(stagingDir, {
env: { MY_VERSION: "1.2.3" },
composePath: "deploy/compose.yaml",
- }, "app");
+ });
expect(result.services).toBe(refreshed);
expect(upload.services).toBe(initial);
});
diff --git a/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts b/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts
index ef4088610..f66e072ba 100644
--- a/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts
+++ b/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts
@@ -225,7 +225,7 @@ describe("Cloud Docker project teardown", () => {
slug,
domain: "opsh.io",
namespace: fixture.namespace,
- source_vm_id: fixture.scope.workspaceId,
+ source_workspace_id: fixture.scope.workspaceId,
exported_path: `${cloudDockerProjectPaths(owner).routes}/${slug}`,
});
return { ...fixture, addPage };
diff --git a/apps/api/src/modules/projects/project-clone.test.ts b/apps/api/src/modules/projects/project-clone.test.ts
index 2c7f04cce..497aa8279 100644
--- a/apps/api/src/modules/projects/project-clone.test.ts
+++ b/apps/api/src/modules/projects/project-clone.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { beforeEach, describe, expect, it, vi } from "vitest";
/**
* Duplicating a project copies its RECORDS. These tests exist for three things that are invisible
@@ -32,7 +32,8 @@ const h = {
deletedAt: null,
deletionInProgress: false,
lifecycleOperation: { kind: "delete", status: "failed", error: "Previous cleanup failure" },
- iconUrl: "https://clincai.example/icon.png",
+ favicon: "https://clincai.example/favicon.ico",
+ faviconCheckedAt: new Date(),
compositeRoutes: [{ host: "clincai.example" }],
workspaceId: null,
gitProvider: "github",
@@ -193,7 +194,6 @@ describe("the copy direction is COPY-by-default", () => {
await clone();
const p = clonedProject();
expect(p.framework).toBe("nextjs");
- expect(p.iconUrl).toBe("https://clincai.example/icon.png");
expect(p.routeStrategy).toBe("loopback");
expect(p.rollbackWindow).toBe(5);
// Same for the service rows: a build command exists in no container.
@@ -231,7 +231,7 @@ describe("what it deliberately does NOT copy", () => {
const p = clonedProject();
// `id`/`groupId` are the insert's, and name/slug/serverId/workspaceId/activeDeploymentId are set
// explicitly above — the rest must simply be absent.
- for (const field of ["deletedAt", "deletionInProgress", "lifecycleOperation", "disabledAt", "compositeRoutes", "cloudPromotion", "id", "groupId", "createdAt", "updatedAt"]) {
+ for (const field of ["deletedAt", "deletionInProgress", "lifecycleOperation", "disabledAt", "favicon", "faviconCheckedAt", "compositeRoutes", "cloudPromotion", "id", "groupId", "createdAt", "updatedAt"]) {
expect(p, field).not.toHaveProperty(field);
}
});
@@ -386,63 +386,3 @@ describe("the exclusion lists are the contract", () => {
}
});
});
-
-describe("independent copies on the source server", () => {
- let originalServices: typeof h.services;
- beforeEach(() => {
- originalServices = structuredClone(h.services);
- h.servers.push({ id: "srv_a", organizationId: "org1", workspaceId: null, purpose: "deployment" });
- });
- afterEach(() => { h.services = originalServices; });
-
- it("allocates new ports without changing the source or claiming its domains", async () => {
- h.services[0]!.ports = ["127.0.0.1:3100:3000", "5353:53/udp"];
- await clone({ targetServerId: "srv_a", chosen: [{ ...CHOSEN[0]!, ports: ["127.0.0.1:3100:3000", "5353:53/udp"] }] });
- expect(clonedServices()[0]!.row.ports).toEqual(["3000", "53/udp"]);
- expect(clonedServices()[0]!.row).not.toHaveProperty("domain");
- expect(clonedProject()).not.toHaveProperty("compositeRoutes");
- expect(h.services[0]!.ports).toEqual(["127.0.0.1:3100:3000", "5353:53/udp"]);
- expect(h.project.activeDeploymentId).toBe("dep_live");
- });
-
- it("refuses sharing host paths before creating a copy", async () => {
- const chosen = [{ ...CHOSEN[0]!, volumes: [{ type: "bind" as const, source: "/srv/data", target: "/data", rw: false }] }];
- await expect(clone({ targetServerId: "srv_a", chosen })).rejects.toThrow(/host path.*same-server/i);
- expect(createProjectWithRecords).not.toHaveBeenCalled();
- });
-
- it("requires declared dependencies instead of deploying a broken partial copy", async () => {
- h.services[0]!.dependsOn = ["db"];
- await expect(clone({ chosen: [CHOSEN[0]!] })).rejects.toThrow(/Include db/);
- expect(createProjectWithRecords).not.toHaveBeenCalled();
- await expect(clone()).resolves.toMatchObject({ created: true, adopted: ["web", "db"] });
- });
-
- it("refuses a stale partial match before copying data without a corresponding service", async () => {
- await expect(clone({ chosen: [CHOSEN[0]!, { ...CHOSEN[1]!, name: "removed-service" }] }))
- .rejects.toThrow(/no longer match/);
- expect(createProjectWithRecords).not.toHaveBeenCalled();
- });
-
- it("requires namespace dependencies and refuses raw host/container namespaces", async () => {
- h.services[0]!.advanced = { networkMode: "service:db" };
- await expect(clone({ chosen: [CHOSEN[0]!] })).rejects.toThrow(/Include db/);
- h.services[0]!.advanced = { networkMode: "host" };
- await expect(clone()).rejects.toThrow(/host is not supported/);
- expect(createProjectWithRecords).not.toHaveBeenCalled();
- });
-
- it("copies a single application without inventing service rows", async () => {
- h.services = [];
- const result = await clone({ targetServerId: "srv_a", chosen: [{ ...CHOSEN[0]!, volumes: [] }] });
- expect(result).toMatchObject({ created: true, adopted: ["web"], handover: { web: "img/web:live" } });
- expect(clonedServices()).toEqual([]);
- expect(clonedProject()).toMatchObject({ serverId: "srv_a", activeDeploymentId: null });
- });
-
- it("refuses single-application mounts before creating records", async () => {
- h.services = [];
- await expect(clone({ chosen: [CHOSEN[0]!] })).rejects.toThrow(/single application with mounted data/);
- expect(createProjectWithRecords).not.toHaveBeenCalled();
- });
-});
diff --git a/apps/api/src/modules/projects/project.controller.ts b/apps/api/src/modules/projects/project.controller.ts
index 79d4ab8e3..afe6747e1 100644
--- a/apps/api/src/modules/projects/project.controller.ts
+++ b/apps/api/src/modules/projects/project.controller.ts
@@ -1,4 +1,3 @@
-import { readOptionalJsonBody } from "../../lib/request-body";
import { reportCaughtError as observeCaughtError, diagnostics as errorDiagnostics } from "@repo/core/diagnostics";
import { getPlatformKernel } from "@repo/platform/engine/lib/platform";
import { operationContext, applyOperationContext } from "../../lib/operation-context";
@@ -138,6 +137,7 @@ export async function update(c: Context) {
* row only drops after remote cleanup; FK CASCADE handles dependents.
*/
export async function remove(c: Context) {
+ const raw = await c.req.text();
const options = parseProjectDeleteOptions(
{
force: c.req.query("force"),
@@ -146,7 +146,7 @@ export async function remove(c: Context) {
wipeVolumes: c.req.query("wipeVolumes"),
recordOnly: c.req.query("recordOnly"),
},
- await readOptionalJsonBody(c),
+ raw.trim() ? JSON.parse(raw) : undefined,
);
const result = await getPlatformKernel().projects.remove(
operationContext(c),
diff --git a/apps/api/src/modules/projects/project.routes.ts b/apps/api/src/modules/projects/project.routes.ts
index dfa4bce37..13266886e 100644
--- a/apps/api/src/modules/projects/project.routes.ts
+++ b/apps/api/src/modules/projects/project.routes.ts
@@ -14,7 +14,6 @@
import { Hono } from "hono";
import {
- UpdateProjectEdgePagesSchema,
WebhookPageInputSchema,
RecentServerLogsInputSchema,
ListProjectsSchema,
@@ -130,15 +129,6 @@ r.get(
edgeConfig.getEdgeConfig,
);
-r.get("/:id/edge-pages", {
- tag: "project:read", localOnly: true,
- mcp: { description: "Read saved project and hostname maintenance/error pages, their revision, and whether the self-hosted edge has applied them." },
-}, routeRules.getEdgePages);
-r.put("/:id/edge-pages", {
- tag: "project:write", localOnly: true, body: UpdateProjectEdgePagesSchema, auditHandledByOperation: true,
- mcp: { description: "Update maintenance and custom error HTML for a self-hosted project or its hostnames. Read edge-pages first and supply expectedRevision to avoid overwriting concurrent edits. Inspect the returned apply status before reporting success." },
-}, routeRules.updateEdgePages);
-
r.get("/:id/route-protection", {
tag: "project:read", localOnly: true,
mcp: { description: "List saved hostname password protection and whether the self-hosted edge acknowledged it. Never returns passwords or signing keys." },
@@ -226,7 +216,6 @@ r.post(
collectionProject: true,
auditHandledByOperation: true,
body: FolderSessionBody,
- bodyValidatedByOperation: true,
mcp: {
description:
"Open a folder-upload session for projectId. Credentials limited to their own projects must create a project first and pass its id; omitting projectId requires wildcard project write access. Returns upload = { url, absoluteUrl, method, headers, requiresAuth }. An authenticated HTTP uploader must POST the gzipped tarball with the returned headers and the same API credential. Binary upload is not an MCP tool and MCP does not expose its OAuth bearer. For a folder on the desktop controller's machine, use projects/import with localPath instead. After upload: folder/scan → projects/ensure (explicit projectId) → deployments/build/access.",
@@ -242,7 +231,6 @@ r.post(
collectionProject: true,
auditHandledByOperation: true,
body: SourceScanOptionsSchema,
- bodyValidatedByOperation: true,
mcp: {
description:
"Folder-upload deploy — STEP 2/4. Run AFTER the tarball is uploaded. Detects the uploaded source's framework/build config (stack, packageManager, install/build/start commands, outputDirectory, productionPaths, port) and, for a docker-compose folder, the `services` array. Body may be empty ({}). Feed the result into projects/ensure (STEP 3) — including `services` verbatim when present.",
diff --git a/apps/api/src/modules/referrals/referral-program.routes.ts b/apps/api/src/modules/referrals/referral-program.routes.ts
index b27d15601..3d7ad419f 100644
--- a/apps/api/src/modules/referrals/referral-program.routes.ts
+++ b/apps/api/src/modules/referrals/referral-program.routes.ts
@@ -3,7 +3,6 @@ import { ReferralOperationSchemas, ReferralRoutes, type ReferralOperations } fro
import { getPlatformKernel } from "@repo/platform/engine/lib/platform";
import { operationContext, operationData } from "../../lib/operation-context";
import { secureRouter } from "../../lib/secure-router";
-import { readOptionalJsonBody } from "../../lib/request-body";
const metadata = {
authorizationHandledByOperation: true,
@@ -24,7 +23,9 @@ function handler(name: keyof ReferralOperations) {
const input: Record =
ReferralRoutes[name].method === "GET"
? c.req.query()
- : await readOptionalJsonBody(c);
+ : c.req.raw.body
+ ? await c.req.json()
+ : {};
for (const key of ["limit", "offset"])
if (typeof input[key] === "string") input[key] = Number(input[key]);
const operation = getPlatformKernel().referralProgram[name] as (
diff --git a/apps/api/src/modules/route-rules/route-rule.controller.ts b/apps/api/src/modules/route-rules/route-rule.controller.ts
index 252be96d7..cec160647 100644
--- a/apps/api/src/modules/route-rules/route-rule.controller.ts
+++ b/apps/api/src/modules/route-rules/route-rule.controller.ts
@@ -26,10 +26,3 @@ export async function listRouteProtection(c: Context) {
export async function changeRouteProtection(c: Context) {
return c.json({ data: await operationData(c, operations().changeRouteProtection(operationContext(c), param(c, "id"), await c.req.json())) });
}
-
-export async function getEdgePages(c: Context) {
- return c.json(await operationData(c, operations().getEdgePages(operationContext(c), param(c, "id"))));
-}
-export async function updateEdgePages(c: Context) {
- return c.json(await operationData(c, operations().updateEdgePages(operationContext(c), param(c, "id"), await c.req.json())));
-}
diff --git a/apps/api/src/modules/service-terminal/service-terminal.controller.ts b/apps/api/src/modules/service-terminal/service-terminal.controller.ts
index a9b24b57d..f63b90913 100644
--- a/apps/api/src/modules/service-terminal/service-terminal.controller.ts
+++ b/apps/api/src/modules/service-terminal/service-terminal.controller.ts
@@ -257,7 +257,7 @@ async function resolveServiceForOrg(
export async function issueTicket(c: Context) {
const ctx = getRequestContext(c);
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/service-terminal/service-terminal.controller"); return ({} as Record); });
const serviceId = typeof (body as { serviceId?: unknown }).serviceId === "string"
? ((body as { serviceId: string }).serviceId)
: "";
diff --git a/apps/api/src/modules/services/service.controller.ts b/apps/api/src/modules/services/service.controller.ts
index e2ee73724..5f7df5e05 100644
--- a/apps/api/src/modules/services/service.controller.ts
+++ b/apps/api/src/modules/services/service.controller.ts
@@ -144,7 +144,7 @@ export async function revealEnv(c: Context) {
operationContext(c),
param(c, "id"),
param(c, "serviceId"),
- await c.req.json(),
+ await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/services/service.controller"); return ({}); }),
),
);
return c.json({ success: true, environment: data });
diff --git a/apps/api/src/modules/system/connected-server.routes.ts b/apps/api/src/modules/system/connected-server.routes.ts
index 41b57994d..d1369462e 100644
--- a/apps/api/src/modules/system/connected-server.routes.ts
+++ b/apps/api/src/modules/system/connected-server.routes.ts
@@ -3,7 +3,6 @@
import { Hono } from "hono";
import { Type } from "@sinclair/typebox";
import {
- EdgePagesSchema,
RemoveServerInputSchema,
ServerInstallSessionInputSchema,
ApplyAllServerContainersInputSchema,
@@ -86,15 +85,6 @@ r.delete(
// agent to this one box — the per-resource scope the jobs-based workaround could not
// express. MCP-exposed deliberately: this is the sanctioned agent execution point.
-r.get("/servers/:id/edge-pages", {
- tag: "server:read",
- mcp: { description: "Read this server's custom error pages and the fallback page served for unmatched hostnames or direct IP requests." },
-}, rateLimit.getEdgePages);
-r.put("/servers/:id/edge-pages", {
- tag: "server:admin", body: EdgePagesSchema, auditHandledByOperation: true,
- mcp: { description: "Set this server's default error HTML and its fallback page for unmatched hostnames or direct IP requests. Project and hostname overrides remain more specific than these defaults." },
-}, rateLimit.updateEdgePages);
-
/* ── Per-server rate limiting (OpenResty level) ─────────────────── */
r.get(
"/servers/:id/rate-limit",
diff --git a/apps/api/src/modules/system/data-transfer/data-transfer.controller.ts b/apps/api/src/modules/system/data-transfer/data-transfer.controller.ts
index a823408bb..4b0f25e07 100644
--- a/apps/api/src/modules/system/data-transfer/data-transfer.controller.ts
+++ b/apps/api/src/modules/system/data-transfer/data-transfer.controller.ts
@@ -20,7 +20,6 @@ import { PkCollisionError, RestoreSchemaError } from "@repo/db";
import { audit, auditContextFrom } from "../../../lib/audit";
import { getRequestContext } from "../../../lib/request-context";
-import { readOptionalJsonBody } from "../../../lib/request-body";
import { streamSSE } from "../../../lib/sse";
import { assertInstanceAdmin } from "../../../middleware/instance-admin";
import {
@@ -114,7 +113,7 @@ export async function exportInstanceHandler(c: Context) {
const ctx = getRequestContext(c);
await assertInstanceAdmin(ctx);
- const body = (await readOptionalJsonBody(c)) ?? {};
+ const body = ((await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/system/data-transfer/data-transfer.controller"); return ({}); })) ?? {}) as ExportBody;
let file: DataTransferFile;
try {
@@ -152,7 +151,7 @@ export async function previewInstanceExportHandler(c: Context) {
const ctx = getRequestContext(c);
await assertInstanceAdmin(ctx);
try {
- const body = c.req.method === "POST" ? await readOptionalJsonBody(c) : null;
+ const body = c.req.method === "POST" ? await readJsonBody(c) : null;
return c.json(await previewInstanceExport(body?.selection));
} catch (err) {
if (err instanceof CloudInstanceNotTransferableError) {
@@ -167,7 +166,8 @@ export async function previewInstanceExportHandler(c: Context) {
export async function createDirectReceiveSessionHandler(c: Context) {
const ctx = getRequestContext(c);
await assertInstanceAdmin(ctx);
- const body = (await c.req.json()) ?? {};
+ const body = ((await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/system/data-transfer/data-transfer.controller"); return ({}); })) ??
+ {}) as CreateReceiveBody;
if (typeof body.apiBase !== "string") {
return c.json(
{ error: "Missing destination API URL.", code: "INVALID_DIRECT_TRANSFER_CODE" },
@@ -464,7 +464,7 @@ export async function finalizeDirectChunkUploadStreamHandler(c: Context) {
export async function sendDirectTransferHandler(c: Context) {
const ctx = getRequestContext(c);
await assertInstanceAdmin(ctx);
- const body = (await c.req.json()) ?? {};
+ const body = ((await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/system/data-transfer/data-transfer.controller"); return ({}); })) ?? {}) as SendDirectBody;
if (typeof body.code !== "string") {
return c.json({ error: "Missing receive code.", code: "INVALID_DIRECT_TRANSFER_CODE" }, 400);
}
@@ -482,7 +482,7 @@ export async function sendDirectTransferHandler(c: Context) {
export async function sendDirectTransferStreamHandler(c: Context) {
const ctx = getRequestContext(c);
await assertInstanceAdmin(ctx);
- const body = (await c.req.json()) ?? {};
+ const body = ((await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/system/data-transfer/data-transfer.controller"); return ({}); })) ?? {}) as SendDirectBody;
if (typeof body.code !== "string") {
return c.json({ error: "Missing receive code.", code: "INVALID_DIRECT_TRANSFER_CODE" }, 400);
}
diff --git a/apps/api/src/modules/system/rate-limit.controller.ts b/apps/api/src/modules/system/rate-limit.controller.ts
index c70a55c3f..9bb86ff70 100644
--- a/apps/api/src/modules/system/rate-limit.controller.ts
+++ b/apps/api/src/modules/system/rate-limit.controller.ts
@@ -1,4 +1,4 @@
-/** HTTP adapters over shared live OpenResty settings: rate limits and visitor pages. */
+/** HTTP adapters over shared live OpenResty rate-limit operations. */
import type { Context } from "hono";
import { getPlatformKernel } from "@repo/platform/engine/lib/platform";
import { param } from "../../lib/controller-helpers";
@@ -11,10 +11,3 @@ export async function getRateLimit(c: Context) {
export async function updateRateLimit(c: Context) {
return c.json(await operationData(c, operations().updateRateLimit(operationContext(c), param(c, "id"), await c.req.json())));
}
-
-export async function getEdgePages(c: Context) {
- return c.json(await operationData(c, operations().getEdgePages(operationContext(c), param(c, "id"))));
-}
-export async function updateEdgePages(c: Context) {
- return c.json(await operationData(c, operations().updateEdgePages(operationContext(c), param(c, "id"), await c.req.json())));
-}
diff --git a/apps/api/src/modules/system/server-check.controller.ts b/apps/api/src/modules/system/server-check.controller.ts
index 1c8ad128d..76172ae61 100644
--- a/apps/api/src/modules/system/server-check.controller.ts
+++ b/apps/api/src/modules/system/server-check.controller.ts
@@ -1,4 +1,5 @@
/** HTTP adapters over shared server diagnostics, installers, prompts and streams. */
+import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
import type { Context } from "hono";
import { CreateServerInputSchema, OperationError, parseInput } from "@repo/contracts";
import { env } from "@repo/platform/engine/config/index";
@@ -78,7 +79,7 @@ export async function onboardingTestConnection(c: Context) {
// targets — never a legitimate remote SSH server, and the highest-value SSRF
// targets (e.g. 169.254.169.254). Private LAN ranges stay allowed for the
// authorized local operator; anonymous remote callers are rejected above.
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/system/server-check.controller"); return ({}); });
if (isBlockedSshTarget(typeof body?.sshHost === "string" ? body.sshHost.trim() : "")) {
return c.json({ ok: false, message: "This host is not allowed.", code: "blocked_host" }, 400);
}
diff --git a/apps/api/src/modules/system/server-containers.controller.ts b/apps/api/src/modules/system/server-containers.controller.ts
index 920061d31..3ee149918 100644
--- a/apps/api/src/modules/system/server-containers.controller.ts
+++ b/apps/api/src/modules/system/server-containers.controller.ts
@@ -4,7 +4,6 @@ import { getPlatformKernel } from "@repo/platform/engine/lib/platform";
import { operationContext, operationData } from "../../lib/operation-context";
import { operationEvents } from "../../lib/operation-stream";
import { param } from "../../lib/controller-helpers";
-import { readOptionalJsonBody } from "../../lib/request-body";
import type { ServerContainerInput } from "@repo/contracts";
const operations = () => getPlatformKernel().servers;
@@ -29,7 +28,9 @@ export async function listApplyingContainers(c: Context) {
return c.json(await operationData(c, operations().applyingContainers(operationContext(c))));
}
export async function applyAllContainers(c: Context) {
- return c.json(await operationData(c, operations().applyAllContainers(operationContext(c), await readOptionalJsonBody(c))));
+ const text = await c.req.text();
+ const input = text.trim() ? JSON.parse(text) : {};
+ return c.json(await operationData(c, operations().applyAllContainers(operationContext(c), input)));
}
export async function scanServerContainers(c: Context) {
return c.json(await operationData(c, operations().scanContainers(operationContext(c), param(c, "id"))));
diff --git a/apps/api/src/modules/system/setup.controller.ts b/apps/api/src/modules/system/setup.controller.ts
index 4770e16f6..47a90997f 100644
--- a/apps/api/src/modules/system/setup.controller.ts
+++ b/apps/api/src/modules/system/setup.controller.ts
@@ -356,7 +356,7 @@ export async function resetAdminPassword(c: Context) {
// multi-user box the reset never lands on an arbitrary member row.
const admin = await repos.user.findFoundingAdmin();
if (!admin) {
- return c.json({ error: "No admin account exists yet — run `openship` and choose Create first admin, or run `openship up --non-interactive --admin-email ` with OPENSHIP_ADMIN_PASSWORD set." }, 409);
+ return c.json({ error: "No admin account exists yet — run `openship` to create one." }, 409);
}
const email =
diff --git a/apps/api/src/modules/terminal/terminal.controller.ts b/apps/api/src/modules/terminal/terminal.controller.ts
index e43cd06ba..585259821 100644
--- a/apps/api/src/modules/terminal/terminal.controller.ts
+++ b/apps/api/src/modules/terminal/terminal.controller.ts
@@ -119,7 +119,7 @@ type ErrorCode =
export async function issueTicket(c: Context) {
const ctx = getRequestContext(c);
- const body = await c.req.json();
+ const body = await c.req.json().catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "api/modules/terminal/terminal.controller"); return ({}); });
const serverId = typeof body?.serverId === "string" ? body.serverId : "";
if (!serverId) return c.json({ error: "serverId required" }, 400);
const cloud = await prepareCloudTerminal(ctx, "server", serverId);
diff --git a/apps/api/src/modules/updates/updates.controller.ts b/apps/api/src/modules/updates/updates.controller.ts
index 7c0c3c57c..1c3594969 100644
--- a/apps/api/src/modules/updates/updates.controller.ts
+++ b/apps/api/src/modules/updates/updates.controller.ts
@@ -3,7 +3,6 @@ import type { Context } from "hono";
import { getPlatformKernel } from "@repo/platform/engine/lib/platform";
import { operationContext, operationData } from "../../lib/operation-context";
import { param } from "../../lib/controller-helpers";
-import { readOptionalJsonBody } from "../../lib/request-body";
export async function runtimeSource(c: Context) {
return c.json({
data: await operationData(
@@ -118,11 +117,7 @@ export async function applyUpdate(c: Context) {
return c.json({
data: await operationData(
c,
- getPlatformKernel().updates.apply(
- operationContext(c),
- param(c, "projectId"),
- await readOptionalJsonBody(c),
- ),
+ getPlatformKernel().updates.apply(operationContext(c), param(c, "projectId")),
),
});
}
@@ -132,7 +127,7 @@ export async function updateRuntime(c: Context) {
getPlatformKernel().updates.updateRuntime(
operationContext(c),
param(c, "projectId"),
- await readOptionalJsonBody(c),
+ await c.req.json(),
),
);
return c.json({ data }, data.awaiting_actions ? 202 : 200);
@@ -144,7 +139,7 @@ export async function checkRuntime(c: Context) {
getPlatformKernel().updates.checkRuntime(
operationContext(c),
param(c, "projectId"),
- await readOptionalJsonBody(c),
+ await c.req.json(),
),
),
});
diff --git a/apps/api/src/modules/updates/updates.routes.ts b/apps/api/src/modules/updates/updates.routes.ts
index 121c944b3..ef4c3dc13 100644
--- a/apps/api/src/modules/updates/updates.routes.ts
+++ b/apps/api/src/modules/updates/updates.routes.ts
@@ -169,8 +169,6 @@ r.post(
r.post(
"/:projectId/apply",
{
- body: UpdateProjectSchemas.apply.input,
- bodyValidatedByOperation: true,
tag: "project:write",
auditHandledByOperation: true,
ids: { project: "projectId" },
@@ -188,7 +186,6 @@ r.post(
auditHandledByOperation: true,
ids: { project: "projectId" },
body: UpdateProjectSchemas.updateRuntime.input,
- bodyValidatedByOperation: true,
mcp: {
description:
"Refresh published runtime images and rebuild selected services at the active commit, without upgrading application code. Omit serviceIds to update the project.",
@@ -204,7 +201,6 @@ r.post(
readOnly: true,
ids: { project: "projectId" },
body: UpdateProjectSchemas.checkRuntime.input,
- bodyValidatedByOperation: true,
mcp: {
description:
"Check configured image tags and recorded build bases against their current registry digests. Does not deploy.",
diff --git a/apps/api/test/e2e/catalog-inline-build.e2e.test.ts b/apps/api/test/e2e/catalog-inline-build.e2e.test.ts
index 4acac1da7..a78afccd9 100644
--- a/apps/api/test/e2e/catalog-inline-build.e2e.test.ts
+++ b/apps/api/test/e2e/catalog-inline-build.e2e.test.ts
@@ -42,10 +42,7 @@ import { describeDockerE2E, dockerSocketPath, requireDocker } from "../helpers/d
// real @repo/db.
const { listByProjectMock } = vi.hoisted(() => ({ listByProjectMock: vi.fn() }));
vi.mock("@repo/db", () => ({
- repos: {
- service: { listByProject: listByProjectMock },
- project: { getEnvMap: async () => ({}) },
- },
+ repos: { service: { listByProject: listByProjectMock } },
}));
import { buildComposeImages } from "@repo/platform/engine/modules/deployments/compose/build.service";
@@ -139,7 +136,6 @@ describeDockerE2E("catalog inline build through the real build pipeline", () =>
dep: {
id: "d-widget",
branch: "main",
- environment: "production",
commitSha: null,
trigger: "deploy",
meta: null,
diff --git a/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts b/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts
index 15bc3624e..e7c29259f 100644
--- a/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts
+++ b/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts
@@ -152,13 +152,13 @@ describeDockerE2E("multiple projects on one subscribed Docker workspace", () =>
};
const vm = { id: providerVm, namespace, status: "running" };
const provider = {
- vms: {
+ workspaces: {
get: async () => vm,
create: () => {
throw new Error("Project operation attempted to create a second host");
},
},
- vm: () => ({
+ workspace: () => ({
get: async () => vm,
runtime: async () => providerRuntime,
workloads: { list: async () => [] },
@@ -185,7 +185,7 @@ describeDockerE2E("multiple projects on one subscribed Docker workspace", () =>
domain: "opsh.io",
url: `https://${input.slug}.opsh.io`,
namespace,
- source_vm_id: input.vm_id,
+ source_workspace_id: input.workspace_id,
exported_path: input.path,
};
pages.set(input.slug, page);
@@ -359,7 +359,7 @@ describeDockerE2E("multiple projects on one subscribed Docker workspace", () =>
);
expect((await a.listAllContainers()).map((row) => row.id)).toEqual([aId]);
expect(routes.get(`${ids[0]}.opsh.io`).routes[0].action).toMatchObject({
- vm: providerVm,
+ workspace: providerVm,
port: first.hostPortByContainerPort?.[8080],
});
});
diff --git a/apps/api/test/e2e/dockerfile-cache.e2e.test.ts b/apps/api/test/e2e/dockerfile-cache.e2e.test.ts
index e879de581..9efb5b706 100644
--- a/apps/api/test/e2e/dockerfile-cache.e2e.test.ts
+++ b/apps/api/test/e2e/dockerfile-cache.e2e.test.ts
@@ -61,12 +61,8 @@ describeDockerE2E("official Dockerfile cache invalidation", () => {
scripts: { postinstall: `bun -e 'await Bun.write(".install-id", crypto.randomUUID())'` },
});
await write("pnpm-workspace.yaml", "packages:\n - apps/*\n - packages/*\n");
- await copyFile(join(root, "bunfig.toml"), join(directory, "bunfig.toml"));
await write("tsconfig.base.json", "{}");
await write("patches/fixture.patch", "first patch input\n");
- await write("vendor/fixture.txt", "first vendored package input\n");
- await write("scripts/web-client-messages.mjs", "// Website build preparation fixture.\n");
- await write("scripts/web-client-messages.d.mts", "export {};\n");
await write("packages/shared/package.json", {
name: "@fixture/shared",
version: "1.0.0",
@@ -80,11 +76,7 @@ describeDockerE2E("official Dockerfile cache invalidation", () => {
private: true,
type: "module",
dependencies: { "@fixture/shared": "workspace:*" },
- scripts: {
- build: app === "web"
- ? "bun ../../scripts/web-client-messages.mjs && bun build.js"
- : "bun build.js",
- },
+ scripts: { build: "bun build.js" },
});
await write(`apps/${app}/revision.txt`, "first source");
await write(
@@ -184,9 +176,7 @@ describeDockerE2E("official Dockerfile cache invalidation", () => {
"apps/dashboard/package.json",
"packages/shared/package.json",
"bun.lock",
- "bunfig.toml",
"patches/fixture.patch",
- "vendor/fixture.txt",
"apps/email/server/bun.lock",
"apps/email/client/package.json",
]) {
diff --git a/apps/api/test/e2e/edge-upstream-down-page.e2e.test.ts b/apps/api/test/e2e/edge-upstream-down-page.e2e.test.ts
index 9e568c362..a472b4a6d 100644
--- a/apps/api/test/e2e/edge-upstream-down-page.e2e.test.ts
+++ b/apps/api/test/e2e/edge-upstream-down-page.e2e.test.ts
@@ -125,10 +125,10 @@ interface Answer {
}
/** One request with an explicit `Host`, which `fetch` refuses to set. */
-function ask(port: number, path: string, host: string, cookie?: string): Promise {
+function ask(port: number, path: string, host: string): Promise {
return new Promise((resolve, reject) => {
const req = httpRequest(
- { host: "127.0.0.1", port, path, method: "GET", maxHeaderSize: 64 * 1024, headers: { Host: host, ...(cookie ? { Cookie: cookie } : {}) } },
+ { host: "127.0.0.1", port, path, method: "GET", headers: { Host: host } },
(res) => {
const chunks: Buffer[] = [];
res.on("data", (c: Buffer) => chunks.push(c));
@@ -180,20 +180,7 @@ http {
# An app that answers 502 ITSELF. Its body must reach the client untouched.
server { listen ${PORT_OWN_502}; location / { return 502 "BODY-FROM-APP"; } }
# A healthy app, so "the page never fires on a working request" is observable.
- server {
- listen ${PORT_HEALTHY};
- # The stand-in app must accept the headers forwarded by the edge too.
- large_client_header_buffers 4 32k;
- location / { return 200 "BODY-FROM-HEALTHY-APP"; }
- location = /large-headers {
- content_by_lua_block {
- local cookies = {}
- for i = 1, 6 do cookies[i] = "session." .. i .. "=" .. string.rep("a", 3000) .. "; Path=/; HttpOnly" end
- ngx.header["Set-Cookie"] = cookies
- ngx.print("AUTH-RESPONSE")
- }
- }
- }
+ server { listen ${PORT_HEALTHY}; location / { return 200 "BODY-FROM-HEALTHY-APP"; } }
include ${SITES_DIR}/*.conf;
}
@@ -243,10 +230,6 @@ http {
tls: false,
targetUrl: `http://127.0.0.1:${PORT_HEALTHY}`,
}),
- unbuffered: await renderVhost({
- domain: "unbuffered.test", tls: false,
- targetUrl: `http://127.0.0.1:${PORT_HEALTHY}`, proxy: { proxyBuffering: false },
- }),
// No upstream at all: the page must not be in this vhost, so a missing file stays the
// plain 404 it has always been.
staticsite: await renderVhost({ domain: "staticsite.test", tls: false, staticRoot: WWW }),
@@ -275,8 +258,7 @@ http {
const container = await runtime.docker.createContainer({
Image: image,
Entrypoint: ["sh", "-c"],
- // Keep each argv entry below Linux's per-string limit as Lua fixtures grow.
- Cmd: ['printf "%s" "$@" | sh', "openship-edge-e2e", ...script.match(/[\s\S]{1,32768}/g)!],
+ Cmd: [script],
Tty: true,
ExposedPorts: { "80/tcp": {} },
HostConfig: {
@@ -289,7 +271,7 @@ http {
const info = await container.inspect();
const bound = info.NetworkSettings.Ports?.["80/tcp"]?.[0]?.HostPort;
- if (!bound) throw new Error("docker published no host port for 80/tcp: " + (await container.logs({ stdout: true, stderr: true })).toString());
+ if (!bound) throw new Error("docker published no host port for 80/tcp");
const published = Number(bound);
// Ready when it answers, dead when it exits — and a dead edge must report the reason
@@ -349,17 +331,6 @@ http {
expect(res.body).toBe("BODY-FROM-HEALTHY-APP");
});
- it.each(["healthy.test", "unbuffered.test"])("relays large auth headers and accepts the next cookie-bearing request: %s", async host => {
- const res = await ask(port, "/large-headers", host);
- expect(res.status).toBe(200);
- expect(res.body).toBe("AUTH-RESPONSE");
- const cookies = res.headers["set-cookie"] as string[];
- expect(cookies).toHaveLength(6);
- const cookie = cookies.map(value => value.split(";")[0]).join("; ");
- expect(cookie.length).toBeGreaterThan(16 * 1024);
- expect((await ask(port, "/", host, cookie)).status).toBe(200);
- });
-
it("answers text/html even when the URI looks like a stylesheet", async () => {
// `return` with a body types the response from the request URI, so without the empty
// `types { }` map a down app's `/app.css` would be `Content-Type: text/css` holding HTML
diff --git a/apps/api/test/e2e/fixtures/instance-api.ts b/apps/api/test/e2e/fixtures/instance-api.ts
index 7bf882126..97f198dea 100644
--- a/apps/api/test/e2e/fixtures/instance-api.ts
+++ b/apps/api/test/e2e/fixtures/instance-api.ts
@@ -135,7 +135,7 @@ export async function startApi(input: {
}
export async function stopApi(api: RunningApi): Promise {
- if (api.child.exitCode === null && api.child.signalCode === null) {
+ if (api.child.exitCode === null) {
api.child.kill("SIGTERM");
const exited = new Promise((resolve) => api.child.once("exit", () => resolve(true)));
if (!(await Promise.race([exited, delay(15_000).then(() => false)]))) {
diff --git a/apps/api/test/e2e/image-refresh.e2e.test.ts b/apps/api/test/e2e/image-refresh.e2e.test.ts
index af5a0009b..cf2186ee5 100644
--- a/apps/api/test/e2e/image-refresh.e2e.test.ts
+++ b/apps/api/test/e2e/image-refresh.e2e.test.ts
@@ -88,14 +88,6 @@ describeDockerE2E("refreshing cached Docker base images", () => {
const cached = await build(false);
expect(cached.Config.Labels?.[marker]).toBe("old");
expect((await runtime.docker.getImage(base).inspect()).Config.Labels?.[marker]).toBe("old");
-
- // An imported or retagged image can occupy a registry tag without a
- // matching RepoDigest. A direct image refresh must acquire the upstream tag.
- const prepared = await runtime.prepareDeploymentImage(base, { force: true });
- const refreshedImage = await runtime.docker.getImage(prepared.imageId).inspect();
- expect(refreshedImage.Config.Labels?.[marker]).toBeUndefined();
- await runtime.docker.getImage(stale).tag({ repo: "alpine", tag: "3.20" });
-
const refreshed = await build(true);
expect(refreshed.Config.Labels?.[marker]).toBeUndefined();
expect(refreshed.Id).not.toBe(cached.Id);
diff --git a/apps/api/test/e2e/instance-handoff.e2e.test.ts b/apps/api/test/e2e/instance-handoff.e2e.test.ts
index e39c61903..0bb185c46 100644
--- a/apps/api/test/e2e/instance-handoff.e2e.test.ts
+++ b/apps/api/test/e2e/instance-handoff.e2e.test.ts
@@ -5,7 +5,7 @@ import { createRequire } from "node:module";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { afterAll, expect, it } from "vitest";
-import { createServer, request as httpRequest, type Server } from "node:http";
+import { createServer, type Server } from "node:http";
import { createHmac } from "node:crypto";
import { freePort, startApi, stopApi, jsonRequest, type RunningApi } from "./fixtures/instance-api";
import type { DataTransferFile } from "../../src/modules/system/data-transfer/types";
@@ -433,47 +433,6 @@ it("resumes after a lost activation acknowledgement without reimporting or start
).toBe(newer.id);
}, 120_000);
-it.each(["resume", "cancel"] as const)("recovers a persisted quiescing source after restart with %s", async action => {
- const { source, target } = await pair();
- const original = await createProject(source, "Before interrupted drain");
- const offer = await post<{ code: string }>(target, "/api/system/instance/offer", { direction: "target" });
- // A real admitted mutation waits for its remaining request body. The move must
- // keep waiting for it, rather than treating an incomplete drain as a snapshot.
- const held = httpRequest(`${source.baseUrl}/api/projects`, {
- method: "POST", headers: { "content-type": "application/json" },
- });
- held.on("error", () => { /* The fixture intentionally interrupts this request. */ });
- held.write('{"name":');
- let restarted: RunningApi | undefined;
- try {
- await post(source, "/api/system/instance/move", { code: offer.code, confirmReplace: true });
- await expect.poll(async () => (await state(source)).role, { timeout: 15_000 }).toBe("quiescing");
- const exited = new Promise(resolve => source.child.once("exit", () => resolve()));
- source.child.kill("SIGKILL"); // simulate a crash after the durable fence
- await exited;
- held.destroy();
- restarted = await startApi({ dbDir: source.dbDir, port: source.port, secret: source.secret });
- apis.push(restarted);
- expect(await state(restarted)).toMatchObject({ role: "quiescing", handoff: { running: false } });
- expect((await fetch(`${restarted.baseUrl}/api/health`)).status).toBe(200);
- expect((await fetch(`${restarted.baseUrl}/api/projects`)).status).toBe(503);
- await post(restarted, `/api/system/instance/${action}`);
- if (action === "resume") {
- await waitMove(restarted);
- expect((await state(target)).role).toBe("active");
- expect((await jsonRequest<{ data: { id: string } }>(target.baseUrl, `/api/projects/${original.id}`)).data.id).toBe(original.id);
- } else {
- expect(await state(restarted)).toMatchObject({ role: "active", handoff: { status: "aborted" } });
- expect((await jsonRequest<{ data: { id: string } }>(restarted.baseUrl, `/api/projects/${original.id}`)).data.id).toBe(original.id);
- }
- } finally {
- held.destroy();
- await stopApi(source);
- await stopApi(target);
- if (restarted) await stopApi(restarted);
- }
-}, 120_000);
-
it("cancels a prepared but unactivated receiver and restores its recovery archive", async () => {
const { source, target } = await pair();
const old = await createProject(target, "Receiver original");
diff --git a/apps/api/test/e2e/local-image-refresh.e2e.test.ts b/apps/api/test/e2e/local-image-refresh.e2e.test.ts
deleted file mode 100644
index 438161d06..000000000
--- a/apps/api/test/e2e/local-image-refresh.e2e.test.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { randomUUID } from "node:crypto";
-import { mkdtemp, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { DockerRuntime } from "@repo/adapters";
-import { afterAll, beforeAll, expect, it, vi } from "vitest";
-import { describeDockerE2E, requireDocker } from "../helpers/docker-e2e";
-
-describeDockerE2E("refreshing releases with a host-only image", () => {
- const local = `openship/local-refresh-e2e:migration-${randomUUID()}`;
- let runtime: DockerRuntime;
- let root: string;
- beforeAll(async () => {
- await requireDocker();
- runtime = await DockerRuntime.create({ transport: "socket" });
- root = await mkdtemp(join(tmpdir(), "openship-local-refresh-"));
- await writeFile(
- join(root, "Dockerfile"),
- "FROM scratch\nLABEL org.openship.e2e=local-refresh\n",
- );
- const stream = await runtime.docker.buildImage(
- { context: root, src: ["Dockerfile"] },
- { t: local },
- );
- await new Promise((resolve, reject) =>
- runtime.docker.modem.followProgress(stream, (error) => (error ? reject(error) : resolve())),
- );
- });
- afterAll(async () => {
- vi.restoreAllMocks();
- await runtime?.docker
- .getImage(local)
- .remove({ force: true })
- .catch(() => {});
- await runtime?.dispose();
- if (root) await rm(root, { recursive: true, force: true });
- });
-
- it("reuses a host-only image by immutable ID during forced refresh", async () => {
- const before = await runtime.docker.getImage(local).inspect();
- const pull = vi.spyOn(runtime, "pullImage");
- try {
- const kept = await runtime.prepareDeploymentImage(before.Id, { force: true });
- expect(kept.imageId).toBe(before.Id);
- expect(kept.deploymentRef).toBe(before.Id);
- expect(pull).not.toHaveBeenCalled();
- } finally {
- pull.mockRestore();
- }
- });
-
- it("refreshes a registry image while preserving an explicitly retained artifact on either Docker store", async () => {
- const before = await runtime.docker.getImage(local).inspect();
- const remote = "busybox:1.37";
- await runtime.pullImage(remote);
- const pull = vi.spyOn(runtime, "pullImage"); // observes real pulls; no mock transport
- const [preserved, refreshed] = await Promise.all([
- runtime.prepareDeploymentImage(local, { force: true, requirePresent: true }),
- runtime.prepareDeploymentImage(remote, { force: true }),
- ]);
- expect(preserved.imageId).toBe(before.Id);
- expect((await runtime.docker.getImage(local).inspect()).Id).toBe(before.Id);
- expect(refreshed.registryDigest).toMatch(/busybox(?::1\.37)?@sha256:/);
- expect(pull).toHaveBeenCalledTimes(1);
- expect(pull.mock.calls[0]?.[0]).toBe(remote);
- });
-});
diff --git a/apps/api/test/e2e/migration-takeover.e2e.test.ts b/apps/api/test/e2e/migration-takeover.e2e.test.ts
index 720e7446b..95e7a9c60 100644
--- a/apps/api/test/e2e/migration-takeover.e2e.test.ts
+++ b/apps/api/test/e2e/migration-takeover.e2e.test.ts
@@ -12,7 +12,7 @@ import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
import { repos } from "@repo/db";
import type { ExecutionContext } from "@repo/platform";
-import { DockerRuntime, initPlatform, type CommandExecutor } from "@repo/adapters";
+import { initPlatform, type CommandExecutor } from "@repo/adapters";
import { describeDockerE2E, requireDocker } from "../helpers/docker-e2e";
import { seedOrg } from "../helpers/seed";
import { availablePort, sshReady } from "../helpers/migration-host";
@@ -26,7 +26,6 @@ import { revealServiceEnvVars } from "@repo/platform/engine/modules/services/ser
import { applyProjectEdgeRoutes } from "@repo/platform/engine/modules/domains/project-edge.service";
import { removeDomain } from "@repo/platform/engine/modules/domains/domain.service";
import { ENV_MASK } from "@repo/platform/engine/lib/secret-env";
-import { pinnedEdgeImage } from "@repo/platform/engine/lib/edge-image";
const run = promisify(execFile);
const fixture = join(dirname(fileURLToPath(import.meta.url)), "../fixtures/migration-target");
@@ -60,9 +59,7 @@ describeDockerE2E("Compose migration through a remote SSH server", () => {
let temp: string;
let targetId: string;
let input: StartMigrationInput;
- let adoptedProjectId: string;
const image = `openship-migration-test-target:${process.pid}`;
- let builtEdgeImage: string | undefined;
beforeAll(async () => {
await requireDocker();
@@ -88,54 +85,6 @@ describeDockerE2E("Compose migration through a remote SSH server", () => {
)?.stdout.trim(),
);
await waitFor(async () => ((await sshReady(port)) ? true : null), 60_000);
- // Build the real edge once on the fixture daemon and load it into its
- // nested daemon. This preserves the runtime test while reusing Docker's
- // layer cache across runs instead of downloading certbot on every retry.
- const runtime = await DockerRuntime.create({ transport: "socket" });
- const edgeImage = pinnedEdgeImage();
- try {
- const existed = await runtime.docker
- .getImage(edgeImage)
- .inspect()
- .then(
- () => true,
- (error) => {
- if (error.statusCode === 404) return false;
- throw error;
- },
- );
- const stream = await runtime.docker.buildImage(
- {
- context: join(fixture, "../../../../.."),
- src: [
- "apps/edge/Dockerfile",
- "apps/edge/nginx.conf",
- "packages/adapters/src/infra/lua",
- "apps/api/assets/geoip/GeoLite2-Country.mmdb",
- ],
- },
- { dockerfile: "apps/edge/Dockerfile", t: edgeImage },
- );
- await new Promise((resolve, reject) =>
- runtime.docker.modem.followProgress(
- stream,
- (error) => (error ? reject(error) : resolve()),
- (event: { stream?: string }) => {
- if (event.stream?.trim()) console.log(`[migration-test:edge] ${event.stream.trim()}`);
- },
- ),
- );
- if (!existed) builtEdgeImage = edgeImage;
- const archive = join(temp, "edge.tar");
- await run("docker", ["save", "-o", archive, edgeImage], { timeout: 120_000 });
- await run("docker", ["cp", archive, `${targetId}:/tmp/edge.tar`], { timeout: 120_000 });
- await run("docker", ["exec", targetId, "docker", "load", "-i", "/tmp/edge.tar"], {
- timeout: 120_000,
- });
- await run("docker", ["exec", targetId, "rm", "/tmp/edge.tar"]);
- } finally {
- await runtime.dispose();
- }
ctx = (await seedOrg()) as ExecutionContext;
const server = await repos.server.create({
organizationId: ctx.organizationId,
@@ -162,19 +111,13 @@ describeDockerE2E("Compose migration through a remote SSH server", () => {
"/opt/migration-fixture/tls.yml",
"tls:\n certificates:\n - certFile: /certs/cert.pem\n keyFile: /certs/key.pem\n",
);
- const app = (
- name: string,
- rule: string,
- hostname: string,
- extraRouters: Record = {},
- ) => ({
+ const app = (name: string, rule: string, hostname: string, extraRouters: Record = {}) => ({
image: "traefik/whoami:v1.11.0",
hostname,
command: ["--port=3000"],
// Compose expands dollar expressions even in JSON. Escape them so the
// SOURCE container really contains the literal value we will migrate.
environment: { API_TOKEN: SECRET.replace(/\$/g, () => "$$"), APP_NAME: name },
- ...(name === "web" ? { volumes: ["fixture-data:/data"] } : {}),
labels: {
"traefik.enable": "true",
"traefik.docker.network": "migration_source",
@@ -215,8 +158,7 @@ describeDockerE2E("Compose migration through a remote SSH server", () => {
"Host(`api.migration.test`) || (Host(`shop.migration.test`) && PathPrefix(`/api`))",
"original-backend",
{
- "traefik.http.routers.api-paths.rule":
- "Host(`paths.migration.test`) && (PathPrefix(`/v3/`) || Path(`/mcp`))",
+ "traefik.http.routers.api-paths.rule": "Host(`paths.migration.test`) && (PathPrefix(`/v3/`) || Path(`/mcp`))",
"traefik.http.routers.api-paths.tls": "true",
"traefik.http.routers.api-paths.service": "api",
},
@@ -224,7 +166,6 @@ describeDockerE2E("Compose migration through a remote SSH server", () => {
outside: app("outside", "Host(`outside.migration.test`)", "unselected-outside"),
},
networks: { source: { name: "migration_source" } },
- volumes: { "fixture-data": {} },
};
await executor.writeFile("/opt/migration-fixture/compose.json", JSON.stringify(compose));
console.log("[migration-test] Starting Traefik and three private services");
@@ -232,10 +173,6 @@ describeDockerE2E("Compose migration through a remote SSH server", () => {
"docker compose -p migration-source -f /opt/migration-fixture/compose.json up -d",
{ timeout: 180_000 },
);
- await executor.exec(
- "docker run --rm -v migration-source_fixture-data:/data alpine:3.21 sh -c 'echo source-data > /data/sentinel'",
- { timeout: 120_000 },
- );
await waitFor(async () => ((await ask(names[0])).includes("original-frontend") ? true : null));
const stack = await discoverServerStack(serverId, ctx.organizationId);
console.log(
@@ -262,12 +199,7 @@ describeDockerE2E("Compose migration through a remote SSH server", () => {
expect.objectContaining({ containerPort: 3000, path: "/api", domains: [names[0]] }),
expect.objectContaining({ containerPort: 3000, path: "/", domains: [names[2]] }),
expect.objectContaining({ containerPort: 3000, path: "/v3/", domains: [names[4]] }),
- expect.objectContaining({
- containerPort: 3000,
- path: "/mcp",
- exact: true,
- domains: [names[4]],
- }),
+ expect.objectContaining({ containerPort: 3000, path: "/mcp", exact: true, domains: [names[4]] }),
]),
);
input = {
@@ -324,45 +256,27 @@ describeDockerE2E("Compose migration through a remote SSH server", () => {
async function finished(id: string) {
return waitFor(async () => {
const run = await repos.dockerMigrationRun.findById(id);
- return run &&
- run.executionFinishedAt &&
- ["succeeded", "rolled_back", "failed"].includes(run.status)
- ? run
- : null;
+ return run && ["succeeded", "rolled_back", "failed"].includes(run.status) ? run : null;
}, 300_000);
}
it("reviews an omitted catch-all before creating a project or changing source containers", async () => {
const { migrationId } = await migrationOrchestrator.begin(ctx, {
...input,
- routesByServiceName: Object.fromEntries(
- Object.entries(input.routesByServiceName!).map(([id, routes]) => [
- id,
- (Array.isArray(routes) ? routes : [routes]).filter(
- (route) => route.customDomain !== names[0] || route.targetPath !== "/",
- ),
- ]),
- ),
+ routesByServiceName: Object.fromEntries(Object.entries(input.routesByServiceName!).map(([id, routes]) =>
+ [id, (Array.isArray(routes) ? routes : [routes]).filter(route => route.customDomain !== names[0] || route.targetPath !== "/")],
+ )),
});
const prompt = await pending(migrationId);
expect(prompt.details?.hostnames).toEqual([names[0]]);
expect((await repos.dockerMigrationRun.findById(migrationId))?.projectId).toBeNull();
- expect(
- await migrationOrchestrator.respondToPrompt(
- migrationId,
- ctx.organizationId,
- prompt.promptId,
- "cancel",
- ),
- ).toBe(true);
+ expect(await migrationOrchestrator.respondToPrompt(migrationId, ctx.organizationId, prompt.promptId, "cancel")).toBe(true);
const result = await finished(migrationId);
expect(result.status).toBe("rolled_back");
expect(result.projectId).toBeNull();
expect(await ask(names[0])).toContain("original-frontend");
for (const id of input.serviceContainerIds!)
- expect(await executor.exec(`docker inspect --format '{{.State.Running}}' ${id}`)).toContain(
- "true",
- );
+ expect(await executor.exec(`docker inspect --format '{{.State.Running}}' ${id}`)).toContain("true");
});
it("cancels takeover without deleting the original routes or any source container", async () => {
@@ -414,7 +328,6 @@ describeDockerE2E("Compose migration through a remote SSH server", () => {
const result = await finished(migrationId);
expect(result.status, `${result.errorMessage}\n${result.logs}`).toBe("succeeded");
expect(result.errorMessage).toBeNull();
- adoptedProjectId = result.projectId!;
const services = await repos.service.listByProject(result.projectId!);
const frontend = services.find((service) => service.name === "frontend")!;
const backend = services.find((service) => service.name === "backend")!;
@@ -426,19 +339,12 @@ describeDockerE2E("Compose migration through a remote SSH server", () => {
(await revealServiceEnvVars(ctx, result.projectId!, backend.id, "production")).API_TOKEN,
).toBe(SECRET);
const domains = await repos.domain.listByProject(result.projectId!);
- expect(domains.map((domain) => domain.hostname).sort()).toEqual(
- [...names.slice(0, 3), names[4]].sort(),
- );
+ expect(domains.map((domain) => domain.hostname).sort()).toEqual([...names.slice(0, 3), names[4]].sort());
for (const domain of domains)
expect(domain).toMatchObject({
verified: true,
sslStatus: "active",
- serviceId:
- domain.hostname === names[4]
- ? null
- : domain.hostname === names[2]
- ? backend.id
- : frontend.id,
+ serviceId: domain.hostname === names[4] ? null : domain.hostname === names[2] ? backend.id : frontend.id,
});
for (const id of input.serviceContainerIds!)
expect(await executor.exec(`docker inspect --format '{{.State.Running}}' ${id}`)).toContain(
@@ -452,11 +358,7 @@ describeDockerE2E("Compose migration through a remote SSH server", () => {
expect(await ask(names[4], "/v3/items")).toContain("original-backend");
expect(await ask(names[4], "/mcp")).toContain("original-backend");
for (const path of ["/", "/private", "/mcp/child"])
- expect(
- await executor.exec(
- `curl --silent --insecure --output /dev/null --write-out '%{http_code}' --resolve ${names[4]}:443:127.0.0.1 https://${names[4]}${path}`,
- ),
- ).toBe("404");
+ expect(await executor.exec(`curl --silent --insecure --output /dev/null --write-out '%{http_code}' --resolve ${names[4]}:443:127.0.0.1 https://${names[4]}${path}`)).toBe("404");
expect(await applyProjectEdgeRoutes(ctx, result.projectId!, { onLog: () => {} })).toEqual([]);
expect(await ask(names[0], "/api/orders")).toContain("original-backend");
expect(await ask(names[4], "/v3/items")).toContain("original-backend");
@@ -473,116 +375,6 @@ describeDockerE2E("Compose migration through a remote SSH server", () => {
expect(await ask(names[3])).toContain("unselected-outside");
});
- it("refuses an external storage writer before creating a copy or stopping the original", async () => {
- const originalId = input.serviceContainerIds![input.serviceNames.indexOf("web")]!;
- const before = await executor.exec(
- `docker inspect --format '{{.State.StartedAt}}' ${originalId}`,
- );
- await executor.exec(
- "docker run -d --name copy-external-writer -v migration-source_fixture-data:/data alpine:3.21 sleep 300",
- );
- try {
- const { migrationId } = await migrationOrchestrator.begin(ctx, {
- sourceServerId: serverId,
- targetServerId: serverId,
- projectName: "Refused shared data copy",
- organizationId: ctx.organizationId,
- killOriginals: false,
- serviceNames: ["frontend"],
- volumeStrategies: {},
- projectMove: { projectId: adoptedProjectId, intent: "copy", serviceNames: ["frontend"] },
- });
- const result = await finished(migrationId);
- expect(result.status).toBe("rolled_back");
- expect(result.errorMessage).toContain("outside this project");
- expect(result.recovery?.createdProjectId).toBeFalsy();
- expect(
- await executor.exec(`docker inspect --format '{{.State.StartedAt}}' ${originalId}`),
- ).toBe(before);
- expect(await ask(names[2])).toContain("original-backend");
- } finally {
- await executor.exec("docker rm -f copy-external-writer");
- }
- });
-
- it("duplicates a stateful service on the same server into independent storage without moving domains", async () => {
- const domainsBefore = (await repos.domain.listByProject(adoptedProjectId))
- .map((domain) => domain.hostname)
- .sort();
- const originalProject = await repos.project.findById(adoptedProjectId);
- const { migrationId } = await migrationOrchestrator.begin(ctx, {
- sourceServerId: serverId,
- targetServerId: serverId,
- projectName: "Independent frontend copy",
- organizationId: ctx.organizationId,
- killOriginals: false,
- serviceNames: ["frontend"],
- volumeStrategies: {},
- projectMove: { projectId: adoptedProjectId, intent: "copy", serviceNames: ["frontend"] },
- });
- const result = await finished(migrationId);
- expect(result.status, `${result.errorMessage}\n${result.logs}`).toBe("succeeded");
- expect(result.projectId).not.toBe(adoptedProjectId);
- const rows = await repos.service.listByProject(result.projectId!);
- expect(rows.map((row) => row.name)).toEqual(["frontend"]);
- expect(await repos.domain.listByProject(result.projectId!)).toEqual([]);
- const copiedVolume = rows[0]!.volumes![0]!.split(":")[0]!;
- expect(copiedVolume).not.toBe("migration-source_fixture-data");
- expect(copiedVolume).toMatch(/^[a-zA-Z0-9_.-]+$/);
- expect(
- await executor.exec(
- `docker run --rm -v ${copiedVolume}:/data alpine:3.21 cat /data/sentinel`,
- ),
- ).toContain("source-data");
- await executor.exec(
- `docker run --rm -v ${copiedVolume}:/data alpine:3.21 sh -c 'echo changed-copy > /data/sentinel'`,
- );
- expect(
- await executor.exec(
- "docker run --rm -v migration-source_fixture-data:/data alpine:3.21 cat /data/sentinel",
- ),
- ).toContain("source-data");
- expect(
- (await repos.domain.listByProject(adoptedProjectId)).map((domain) => domain.hostname).sort(),
- ).toEqual(domainsBefore);
- expect((await repos.project.findById(adoptedProjectId))?.activeDeploymentId).toBe(
- originalProject?.activeDeploymentId,
- );
- expect(await ask(names[2])).toContain("original-backend");
- for (const id of input.serviceContainerIds!)
- expect(await executor.exec(`docker inspect --format '{{.State.Running}}' ${id}`)).toContain(
- "true",
- );
- });
-
- it("duplicates a stateless service without restarting its original container", async () => {
- const source = await repos.service.listByProject(adoptedProjectId);
- const backend = source.find((row) => row.name === "backend")!;
- const containerId = input.serviceContainerIds![input.serviceNames.indexOf("api")]!;
- const before = await executor.exec(
- `docker inspect --format '{{.State.StartedAt}}' ${containerId}`,
- );
- const { migrationId } = await migrationOrchestrator.begin(ctx, {
- sourceServerId: serverId,
- targetServerId: serverId,
- projectName: "Independent API copy",
- organizationId: ctx.organizationId,
- killOriginals: false,
- serviceNames: [backend.name],
- volumeStrategies: {},
- projectMove: { projectId: adoptedProjectId, intent: "copy", serviceNames: [backend.name] },
- });
- const result = await finished(migrationId);
- expect(result.status, `${result.errorMessage}\n${result.logs}`).toBe("succeeded");
- expect(
- await executor.exec(`docker inspect --format '{{.State.StartedAt}}' ${containerId}`),
- ).toBe(before);
- expect(await ask(names[2])).toContain("original-backend");
- expect((await repos.service.listByProject(result.projectId!)).map((row) => row.name)).toEqual([
- "backend",
- ]);
- });
-
afterAll(async () => {
if (serverId) await sshManager.invalidate(serverId);
if (targetId) {
@@ -591,7 +383,6 @@ describeDockerE2E("Compose migration through a remote SSH server", () => {
}
if (targetId) await run("docker", ["rm", "-f", "-v", targetId]).catch(() => {});
await run("docker", ["image", "rm", image]).catch(() => {});
- if (builtEdgeImage) await run("docker", ["image", "rm", builtEdgeImage]).catch(() => {});
if (temp) await rm(temp, { recursive: true, force: true });
});
});
diff --git a/apps/api/test/e2e/native-compose-build.e2e.test.ts b/apps/api/test/e2e/native-compose-build.e2e.test.ts
index c13176cf8..f9d677040 100644
--- a/apps/api/test/e2e/native-compose-build.e2e.test.ts
+++ b/apps/api/test/e2e/native-compose-build.e2e.test.ts
@@ -318,12 +318,6 @@ describeDockerE2E("native Compose build batches", () => {
stderr: "",
}));
const commands = vi.spyOn(executor, "exec");
- const write = executor.writeFile.bind(executor);
- // An unattainable free-space target reproduces pressure without filling the
- // test host. The production reservedSpace/budget/guard remain unchanged.
- const writes = vi.spyOn(executor, "writeFile").mockImplementation((path, contents, options) =>
- write(path, /^\/tmp\/openship-buildkit-.*\.toml$/.test(path)
- ? contents.replace('minFreeSpace = "20%"', 'minFreeSpace = "100%"') : contents, options));
try {
const batch = specs("protected");
for (const spec of batch) spec.config.resources = { cpuCores: 1, memoryMb: 2048, diskMb: 0 };
@@ -347,18 +341,8 @@ describeDockerE2E("native Compose build batches", () => {
)
).trim(),
).not.toBe("");
- logs.length = 0;
- const warm = await runtime.buildImages(specs("protected-warm").map(spec => ({
- ...spec, config: { ...spec.config, resources: batch[0]!.config.resources },
- })), logger());
- expect(warm.map(entry => entry.result.status), JSON.stringify(warm))
- .toEqual(["deploying", "deploying", "deploying"]);
- expect(logs.map(entry => entry.message).join("\n"))
- .toMatch(/#(\d+) \[[^\n]+\] RUN sleep 2[^\n]*\n(?:\n)*#\1 CACHED/);
- writes.mockRestore();
await verifyGeneratedEnvironmentBatch("protected-secrets", { cpuCores: 2, memoryMb: 2048, diskMb: 0 });
} finally {
- writes.mockRestore();
commands.mockRestore();
await workerImage.dispose();
}
diff --git a/apps/api/test/e2e/platform-import-data.e2e.test.ts b/apps/api/test/e2e/platform-import-data.e2e.test.ts
index ac15215ea..ef24f936c 100644
--- a/apps/api/test/e2e/platform-import-data.e2e.test.ts
+++ b/apps/api/test/e2e/platform-import-data.e2e.test.ts
@@ -23,15 +23,14 @@ import { describeDockerE2E, requireDocker, dockerSocketPath } from "../helpers/d
const h = vi.hoisted(() => ({
project: {} as any,
source: undefined as unknown,
- service: undefined as any,
runtime: undefined as unknown,
workspaceId: undefined as string | undefined,
exportOnly: vi.fn(),
}));
vi.mock("@repo/db", () => ({
repos: {
- project: { findById: async () => h.project, getEnvMap: async () => ({}) },
- service: { listByProject: async () => h.service ? [h.service] : [] },
+ project: { findById: async () => h.project },
+ service: { listByProject: async () => [] },
},
}));
vi.mock("@repo/platform/engine/modules/migration/migration-access", () => ({
@@ -379,16 +378,10 @@ describeDockerE2E("generic stopped-volume provider import", () => {
environment: {},
bindings: [],
} as PlannedImportService;
- h.service = {
- id: `${projectId}-service`, projectId, name: fixture.name,
- image: fixture.image, environment: {},
- volumes: service.create.volumes, namespaceVolumes: true,
- };
const args = {
runId: tag,
service,
projectId,
- serviceId: h.service.id,
signal: new AbortController().signal,
log: () => {},
progress: vi.fn(),
diff --git a/apps/api/test/e2e/platform-import-project.e2e.test.ts b/apps/api/test/e2e/platform-import-project.e2e.test.ts
deleted file mode 100644
index b8de6a4ca..000000000
--- a/apps/api/test/e2e/platform-import-project.e2e.test.ts
+++ /dev/null
@@ -1,569 +0,0 @@
-import { afterAll, beforeAll, expect, it, vi } from "vitest";
-import { randomUUID } from "node:crypto";
-import { spawn } from "node:child_process";
-import { createConnection } from "node:net";
-import { once } from "node:events";
-import { mkdtemp, rm, writeFile } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import {
- BuildLogger,
- CommandSourceBackupExecutor,
- CloudDockerRuntime,
- DockerRuntime,
- type CommandExecutor,
-} from "@repo/adapters";
-import { CloudServerConnection } from "../../../../packages/adapters/src/runtime/cloud/server-connection";
-import { CloudWorkspaceExecutor } from "../../../../packages/adapters/src/runtime/cloud/workspace-executor";
-import { db, repos, schema } from "@repo/db";
-import type { ExecutionContext } from "@repo/platform";
-import type { ProviderInventory } from "@repo/platform/engine/modules/migration/providers/types";
-import { encrypt, decryptEnvMap } from "@repo/platform/engine/lib/encryption";
-import { deployComposeServices } from "@repo/platform/engine/modules/deployments/compose/deploy.service";
-import { projectServicesToDeployableServices } from "@repo/platform/engine/modules/deployments/compose/project-services";
-import { seedDeployment, seedOrg, setActive } from "../helpers/seed";
-import { describeDockerE2E, requireDocker, dockerSocketPath } from "../helpers/docker-e2e";
-import { refreshConnectionEnv } from "@repo/platform/engine/modules/projects/project-connection.service";
-import {
- sharedServiceAlias,
- sharedServiceNetwork,
-} from "@repo/platform/engine/modules/projects/shared-service-network";
-
-// Substitute Railway's control/SSH boundary, Git checkout, destination resolution
-// and the asynchronous build queue. All runtime operations use an isolated daemon.
-// Review, project creation, encrypted environments, migration checkpoints,
-// volume transfer and the ordinary Compose deployment engine remain real.
-const h = vi.hoisted(() => ({
- discover: vi.fn(),
- prepare: vi.fn(),
- assertStopped: vi.fn(),
- openSource: vi.fn(),
- runtime: vi.fn(),
- deploy: vi.fn(),
-}));
-vi.mock("@repo/platform/engine/modules/credentials/connection-authorization", () => ({
- getProviderAccess: async () => ({ provider: "railway", publicFields: {}, secrets: {} }),
-}));
-vi.mock("@repo/platform/engine/modules/migration/providers/railway", () => ({
- railwayMigrationProvider: { discover: h.discover },
-}));
-vi.mock("@repo/platform/engine/modules/migration/providers/railway-project-transfer", () => ({
- prepareRailwayProjectTransfer: h.prepare,
- assertRailwayExportOnly: h.assertStopped,
- restoreRailwayProjectTransfer: async () => {},
-}));
-vi.mock("@repo/platform/engine/modules/migration/providers/railway-data", () => ({
- openRailwayDataSource: h.openSource,
-}));
-vi.mock("@repo/platform/engine/modules/migration/migration-runtime", async (original) => ({
- ...(await original
- {t.auth.register.hasAccount}{" "}
- {t.auth.register.signIn}
+ {t.auth.verifyEmail.backToSignIn}
-
- {t.auth.forgotPassword.title}
-
);
diff --git a/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/components/DnsConfiguration.tsx b/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/components/DnsConfiguration.tsx
index f68b8ffb0..280f2e0c9 100644
--- a/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/components/DnsConfiguration.tsx
+++ b/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/components/DnsConfiguration.tsx
@@ -1,6 +1,5 @@
"use client";
-import { DisclosureSummary } from "@/components/ui/DisclosureSummary";
import React from "react";
import { useI18n } from "@/components/i18n-provider";
import DnsRecordCard from "@/components/domains/DnsRecordCard";
@@ -51,9 +50,9 @@ const DnsConfiguration: React.FC = ({
const manual = displayRecords.length > 0 && (
-
+
{t.autoDns.manualSetup}
-
+
{displayRecords.map((record, i) => (
diff --git a/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/page.server-selection.test.tsx b/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/page.server-selection.test.tsx
index a428213cd..71cb96055 100644
--- a/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/page.server-selection.test.tsx
+++ b/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/page.server-selection.test.tsx
@@ -65,7 +65,6 @@ vi.mock("@/components/shared/ServerSelector", () => ({
ServerSelectorView: ({ selection }: any) => (
),
- ServerSelectionPrompt: () => null,
}));
let host: HTMLDivElement;
diff --git a/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/page.test.tsx b/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/page.test.tsx
index 16b47ddd7..bd43652a8 100644
--- a/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/page.test.tsx
+++ b/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/page.test.tsx
@@ -75,7 +75,6 @@ vi.mock("@/components/shared/ServerSelector", () => ({
readOnly: false,
}),
ServerSelectorView: () => null,
- ServerSelectionPrompt: () => null,
}));
vi.mock("./components/DeployTargetStep", () => ({
default: () => null,
diff --git a/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/page.tsx b/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/page.tsx
index d40f459fb..1dde1ab06 100644
--- a/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/(deployment)/deploy/[slug]/page.tsx
@@ -1,5 +1,4 @@
"use client";
-import { parseDeployDestination } from "@repo/core";
import { ComposeChangeSummary } from "@/hooks/useComposeReview";
import WarningCallout from "@/components/shared/WarningCallout";
@@ -34,7 +33,7 @@ import { usesServiceDeployment, workloadOf } from "@/context/deployment/types";
import { usePlatform } from "@/context/PlatformContext";
import SkeletonLoader from "./components/SkeletonLoader";
import ErrorState from "@/components/shared/ErrorState";
-import { ServerSelectionPrompt, ServerSelectorView, useServerSelection } from "@/components/shared/ServerSelector";
+import { ServerSelectorView, useServerSelection } from "@/components/shared/ServerSelector";
import { PageContainer } from "@/components/ui/PageContainer";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
@@ -190,7 +189,6 @@ const DeployRepository: React.FC = () => {
autoSelectFirst: savedTargetState === "none" && !selectReadServer,
useSavedDefault: savedTargetState === "none" && !selectReadServer,
selfHostedOnly: selectReadServer,
- destinationKind: !loadsSavedTarget && !projectId ? parseDeployDestination(searchParams.get("destination")) : undefined,
onSelect: (server) => updateConfig({
deployTarget: server ? (server.raw.managed ? "cloud" : "server") : (selfHosted ? "server" : "cloud"),
serverId: server?.id,
@@ -471,7 +469,6 @@ const DeployRepository: React.FC = () => {
return (
-
{/* Destination settings share the page's normal content/sidebar layout. */}
{step === "target" && (
{sourceProjects.slice(0, 5).map((p) => (
- removeProject(p.id)} />
+ removeProject(p.id)} />
))}
)}
@@ -198,9 +203,11 @@ export default function DashboardHomeClient({
: null}
>
+ {planCard}
+
{/* Alerts replace the activity summary; Apps stays accessible and
Quick Tip uses only the space left after these cards. */}
- {attention.cards === 0 && (
+ {attention.cards === 0 && (!hostedCloud || projects.length > 0) && (
diff --git a/apps/dashboard/src/app/(dashboard)/apps/new/[appId]/page.tsx b/apps/dashboard/src/app/(dashboard)/apps/new/[appId]/page.tsx
index 07deaeed3..ff8fd2361 100644
--- a/apps/dashboard/src/app/(dashboard)/apps/new/[appId]/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/apps/new/[appId]/page.tsx
@@ -1,5 +1,4 @@
"use client";
-import { parseDeployDestination } from "@repo/core";
import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
import { Icon as UiIcon } from "@repo/ui/icons";
@@ -1890,9 +1889,6 @@ export default function AppInstallPage() {
{filteredApps.length > 0 ? filteredApps.map(app => (
-
removeProject(app.id)} />
+ removeProject(app.id)} />
)) : (
{copy.catalogNoResults}
)}
diff --git a/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx b/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx
index 92eaf168a..105bd759e 100644
--- a/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx
+++ b/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx
@@ -8,8 +8,10 @@ import { DeploymentMenu } from "./DeploymentMenu";
import { CommitDetailsModal } from "./CommitDetailsModal";
import type { Deployment } from "../types";
import { formatDistanceToNow, formatBuildTime, getStatusConfig } from "../utils";
-import { ProjectIcon } from "@/components/shared/ProjectIcon";
+import { ProjectStackIcon } from "@/components/shared/ProjectStackIcon";
+import { AppLogo } from "@/components/AppLogo";
import { useI18n, interpolate } from "@/components/i18n-provider";
+import { useImageFallback } from "@/hooks/useImageFallback";
type ServiceStatusLabels = {
deployed: string;
@@ -120,6 +122,7 @@ export const DeploymentCard: React.FC = ({
const { t } = useI18n();
const [isCommitModalOpen, setIsCommitModalOpen] = useState(false);
const [isMenuOpen, setIsMenuOpen] = useState(false);
+ const favicon = useImageFallback(deployment.favicon);
const statusConfig = getStatusConfig(deployment.status);
const statusLabelMap: Record = {
@@ -148,9 +151,21 @@ export const DeploymentCard: React.FC = ({
aria-label={deployment.projectName || t.deployments.card.unknownProject}
className="absolute inset-0 z-0"
/>
- {/* Project icon → catalog logo → framework or service icon */}
+ {/* App logo (catalog apps) → project favicon → framework icon → initials */}
-
+ {appTemplateId ? (
+
+ ) : favicon.showImage ? (
+

+ ) : (
+
+ )}
{/* Main info */}
diff --git a/apps/dashboard/src/app/(dashboard)/deployments/types.ts b/apps/dashboard/src/app/(dashboard)/deployments/types.ts
index a49f53391..213fb5e83 100644
--- a/apps/dashboard/src/app/(dashboard)/deployments/types.ts
+++ b/apps/dashboard/src/app/(dashboard)/deployments/types.ts
@@ -56,8 +56,9 @@ export interface Deployment {
branch?: string;
projectId?: string;
projectName?: string;
- /** Project icon shared with project lists and settings. */
- iconUrl?: string | null;
+ /** Auto-detected favicon of the deployed site, cached on the project.
+ * When present it replaces the framework/Docker glyph as the row logo. */
+ favicon?: string | null;
failureReason?: string;
/** Rollback state — populated by the orchestrator-aware listing endpoint.
* `artifactRetainedAt` non-null = artifact is archived, rollback-eligible.
diff --git a/apps/dashboard/src/app/(dashboard)/deployments/utils.ts b/apps/dashboard/src/app/(dashboard)/deployments/utils.ts
index 711c32894..f2bc27c23 100644
--- a/apps/dashboard/src/app/(dashboard)/deployments/utils.ts
+++ b/apps/dashboard/src/app/(dashboard)/deployments/utils.ts
@@ -41,7 +41,7 @@ export const mapRowToDeployment = (row: any): Deployment => {
branch: row.branch ?? undefined,
projectId: row.projectId,
projectName: row.projectName,
- iconUrl: row.iconUrl ?? null,
+ favicon: row.favicon ?? null,
failureReason: row.errorMessage ?? undefined,
/* Rollback state — flows from the listing endpoint, which enriches
* each row with isActive and surfaces the orchestrator-owned
diff --git a/apps/dashboard/src/app/(dashboard)/home-cloud-plan.test.tsx b/apps/dashboard/src/app/(dashboard)/home-cloud-plan.test.tsx
new file mode 100644
index 000000000..37ccf6080
--- /dev/null
+++ b/apps/dashboard/src/app/(dashboard)/home-cloud-plan.test.tsx
@@ -0,0 +1,73 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const mocks = vi.hoisted(() => ({
+ deployment: vi.fn(),
+ productView: vi.fn(),
+ home: vi.fn(),
+ billing: vi.fn(),
+}));
+vi.mock("@/lib/server/session", () => ({ getDeploymentInfoOrNull: mocks.deployment }));
+vi.mock("@/lib/server/product-view", () => ({ resolveRequestProductView: mocks.productView }));
+vi.mock("@/lib/server/api", () => ({ serverApi: { get: mocks.home } }));
+vi.mock("./billing/_components/billing-state", () => ({ getBillingPageState: mocks.billing }));
+vi.mock("./emails/_components/mail-console", () => ({ MailConsole: () => null }));
+vi.mock("./DashboardHomeClient", () => ({ default: () => null }));
+
+import DashboardHome from "./page";
+import { CloudHomePlanCard } from "@/components/billing/CloudHomePlanCard";
+
+beforeEach(() => {
+ vi.resetAllMocks();
+ mocks.deployment.mockResolvedValue({ selfHosted: false, deployMode: "docker" });
+ mocks.productView.mockResolvedValue("platform");
+ mocks.home.mockResolvedValue({ projects: [] });
+});
+
+describe("home Cloud billing boundary", () => {
+ it.each([
+ { selfHosted: true, deployMode: "docker" },
+ { selfHosted: true, deployMode: "desktop" },
+ { selfHosted: false, deployMode: "desktop" },
+ null,
+ ])("never mounts or fetches the offer outside the hosted Cloud dashboard: %j", async deployment => {
+ mocks.deployment.mockResolvedValue(deployment);
+ const page = await DashboardHome();
+ expect(page.props.planCard).toBeNull();
+ expect(mocks.billing).not.toHaveBeenCalled();
+ });
+
+ it("keeps the mail home outside project and billing reads", async () => {
+ mocks.productView.mockResolvedValue("mail");
+ await DashboardHome();
+ expect(mocks.home).not.toHaveBeenCalled();
+ expect(mocks.billing).not.toHaveBeenCalled();
+ });
+
+ it("loads billing in its own Suspense slot without blocking the home payload", async () => {
+ const state = { tier: "free", subscription: null, billing: { enabled: true } };
+ mocks.billing.mockResolvedValue({ kind: "ok", state });
+ const page = await DashboardHome();
+ expect(page.props.initialData).toEqual({ projects: [] });
+ expect(page.props.planCard.props.fallback).toBeNull();
+ expect(mocks.billing).not.toHaveBeenCalled();
+ const slot = page.props.planCard.props.children;
+ const card = await slot.type();
+ expect(card.type).toBe(CloudHomePlanCard);
+ expect(card.props.state).toBe(state);
+ expect(mocks.billing).toHaveBeenCalledOnce();
+ });
+
+ it("hides the card for a workspace member without billing access", async () => {
+ mocks.billing.mockResolvedValue({ kind: "unavailable", reason: "billing-forbidden" });
+ const page = await DashboardHome();
+ const slot = page.props.planCard.props.children;
+ expect(await slot.type()).toBeNull();
+ });
+
+ it("hides the card when billing cannot confirm that this is a new customer", async () => {
+ mocks.billing.mockResolvedValue({ kind: "unavailable", reason: "billing-unreachable" });
+ const page = await DashboardHome();
+ const slot = page.props.planCard.props.children;
+ expect(await slot.type()).toBeNull();
+ });
+});
diff --git a/apps/dashboard/src/app/(dashboard)/home.test.tsx b/apps/dashboard/src/app/(dashboard)/home.test.tsx
deleted file mode 100644
index 1ae8f44b0..000000000
--- a/apps/dashboard/src/app/(dashboard)/home.test.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-const mocks = vi.hoisted(() => ({
- deployment: vi.fn(),
- productView: vi.fn(),
- home: vi.fn(),
- billing: vi.fn(),
-}));
-vi.mock("@/lib/server/session", () => ({ getDeploymentInfoOrNull: mocks.deployment }));
-vi.mock("@/lib/server/product-view", () => ({ resolveRequestProductView: mocks.productView }));
-vi.mock("@/lib/server/api", () => ({ serverApi: { get: mocks.home } }));
-vi.mock("./billing/_components/billing-state", () => ({ getBillingPageState: mocks.billing }));
-vi.mock("./emails/_components/mail-console", () => ({ MailConsole: () => null }));
-vi.mock("./DashboardHomeClient", () => ({ default: () => null }));
-
-import DashboardHome from "./page";
-
-beforeEach(() => {
- vi.resetAllMocks();
- mocks.deployment.mockResolvedValue({ selfHosted: false, deployMode: "docker" });
- mocks.productView.mockResolvedValue("platform");
- mocks.home.mockResolvedValue({ projects: [] });
-});
-
-describe("dashboard home data boundary", () => {
- it.each([
- { selfHosted: false, deployMode: "docker" },
- { selfHosted: true, deployMode: "docker" },
- { selfHosted: true, deployMode: "desktop" },
- { selfHosted: false, deployMode: "desktop" },
- null,
- ])(
- "loads the same activity data without billing in every deployment mode: %j",
- async (deployment) => {
- mocks.deployment.mockResolvedValue(deployment);
- const page = await DashboardHome();
- expect(page.props).toEqual({ initialData: { projects: [] } });
- expect(mocks.home).toHaveBeenCalledWith("projects/home", { cache: "no-store" });
- expect(mocks.billing).not.toHaveBeenCalled();
- },
- );
-
- it("keeps the mail home outside project and billing reads", async () => {
- mocks.productView.mockResolvedValue("mail");
- await DashboardHome();
- expect(mocks.home).not.toHaveBeenCalled();
- expect(mocks.billing).not.toHaveBeenCalled();
- });
-});
diff --git a/apps/dashboard/src/app/(dashboard)/layout.tsx b/apps/dashboard/src/app/(dashboard)/layout.tsx
index cc8c81f0c..abb88ac76 100644
--- a/apps/dashboard/src/app/(dashboard)/layout.tsx
+++ b/apps/dashboard/src/app/(dashboard)/layout.tsx
@@ -173,9 +173,10 @@ export default async function DashboardLayout({ children }: { children: React.Re
hostDomain={deploymentInfo.hostDomain}
>
- {/* Full-width update surface. Managed Cloud shows workload security;
- Desktop and self-hosted also show installation updates, operator
- notices and what's new. Empty state adds no chrome. */}
+ {/* Update + platform-status surface — full app width, ABOVE the sidebar.
+ Renders nothing unless there's an advisory / platform notice (SaaS:
+ partial outage, maintenance) / available update / what's-new, so it
+ adds no chrome when idle. */}
{children}
diff --git a/apps/dashboard/src/app/(dashboard)/library/components/UrlImport.tsx b/apps/dashboard/src/app/(dashboard)/library/components/UrlImport.tsx
index 7bc5a25a4..1de78fc95 100644
--- a/apps/dashboard/src/app/(dashboard)/library/components/UrlImport.tsx
+++ b/apps/dashboard/src/app/(dashboard)/library/components/UrlImport.tsx
@@ -9,7 +9,6 @@ import { encodeRepoSlug } from "@/utils/repoSlug";
import { useI18n } from "@/components/i18n-provider";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
-import { parseDeploySource } from "@repo/core";
export function UrlImport({ header }: { header?: React.ReactNode }) {
const { t } = useI18n();
@@ -23,11 +22,19 @@ export function UrlImport({ header }: { header?: React.ReactNode }) {
setError("");
try {
- const source = parseDeploySource({ repo: url });
- if (source.kind !== "repo") return;
- router.push(`/deploy/${encodeRepoSlug(source.owner, source.repo)}`);
+ const parsed = new URL(url.trim());
+ const parts = parsed.pathname.replace(/\/+$/, "").slice(1).split("/");
+ const [owner, rawRepo] = parts;
+ const repo = rawRepo?.replace(/\.git$/, "");
+ if (
+ !["https:", "http:"].includes(parsed.protocol) ||
+ !["github.com", "www.github.com"].includes(parsed.hostname) ||
+ parsed.username || parsed.password || parsed.port ||
+ parts.length !== 2 || !owner || !repo ||
+ !/^[a-zA-Z0-9-]+$/.test(owner) || !/^[a-zA-Z0-9_.-]+$/.test(repo)
+ ) throw new Error("Invalid repository URL");
+ router.push(`/deploy/${encodeRepoSlug(owner, repo)}`);
} catch {
- // diagnostics-ignore: invalid user-entered repository URLs are shown inline.
setError(t.library.urlImport.invalidUrl);
}
};
diff --git a/apps/dashboard/src/app/(dashboard)/page.tsx b/apps/dashboard/src/app/(dashboard)/page.tsx
index 93428ec6d..c04b85bb9 100644
--- a/apps/dashboard/src/app/(dashboard)/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/page.tsx
@@ -1,10 +1,20 @@
import { diagnostics as errorDiagnostics } from "@repo/core/diagnostics";
+import { Suspense } from "react";
import { MailConsole } from "./emails/_components/mail-console";
import { serverApi } from "@/lib/server/api";
import { getDeploymentInfoOrNull } from "@/lib/server/session";
import { resolveRequestProductView } from "@/lib/server/product-view";
+import { CloudHomePlanCard } from "@/components/billing/CloudHomePlanCard";
+import { getBillingPageState } from "./billing/_components/billing-state";
import DashboardHomeClient from "./DashboardHomeClient";
+async function HomePlanCard() {
+ const result = await getBillingPageState();
+ // Show an offer only after billing confirms this workspace's eligibility.
+ if (result.kind !== "ok") return null;
+ return ;
+}
+
/**
* The dashboard home, per product view.
*
@@ -41,5 +51,16 @@ export default async function DashboardHome() {
errorDiagnostics.error("dashboard/app/(dashboard)/page", "Failed to fetch initial dashboard data", error);
}
- return ;
+ const hostedCloud = deploymentInfo?.selfHosted === false && deploymentInfo.deployMode !== "desktop";
+ return (
+
+
+
+ ) : null}
+ />
+ );
}
diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/[[...slug]]/page.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/[[...slug]]/page.tsx
index b1e51ebf8..b840124a0 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/[id]/[[...slug]]/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/[[...slug]]/page.tsx
@@ -16,7 +16,6 @@ import { AdvancedSettings } from "../components/AdvancedSettings";
import { OverviewTab } from "../components/OverviewTab";
import { ServicesTab } from "../components/ServicesTab";
import { ProjectTopologyPage } from "@/components/topology/ProjectTopologyPage";
-import { DomainSection } from "../components/DomainSection";
import { ProjectSidebar, ProjectMobileTabs } from "../components/ProjectSidebar";
import { ProjectTabSections } from "../components/ProjectTabSections";
import { DraftProjectView } from "../components/DraftProjectView";
@@ -29,11 +28,7 @@ import {
projectEnvironmentHref,
removeProjectEnvironment,
} from "@/context/project-environments";
-import {
- useProjectInfo,
- PROJECT_INFO_NOT_FOUND,
- retryProjectRequests,
-} from "@/hooks/useProjectEndpoints";
+import { useProjectInfo, PROJECT_INFO_NOT_FOUND } from "@/hooks/useProjectEndpoints";
import Link from "next/link";
import { useRouter, useSearchParams } from "next/navigation";
import { useToast } from "@/context/ToastContext";
@@ -565,11 +560,7 @@ const ProjectSettingsContent = () => {
// Project shell waits for project info specifically (not analytics).
// Analytics is per-card now; the page-level gate is about whether we
// know enough about the project to even render its tabs.
- const {
- isLoading: isLoadingProjectInfo,
- isRefreshing: isRetryingProjectInfo,
- error: projectInfoError,
- } = useProjectInfo(id);
+ const { isLoading: isLoadingProjectInfo, error: projectInfoError } = useProjectInfo(id);
const [topologyHasPending, setTopologyHasPending] = useState(false);
const [retryDeletionFor, setRetryDeletionFor] = useState(null);
const [unconfirmedDeletionFor, setUnconfirmedDeletionFor] = useState(null);
@@ -941,11 +932,6 @@ const ProjectSettingsContent = () => {
);
case "services":
return ;
- case "routing":
- case "access":
- case "edge-pages":
- case "proxy":
- return ;
case "domains":
return ;
case "actions":
@@ -984,18 +970,6 @@ const ProjectSettingsContent = () => {
// still-loading. The `!projectInfoError` guard avoids an infinite skeleton
// when the fetch genuinely failed (non-404) and the seed will never arrive.
const projectDataReady = projectData.id === id;
- // Keep the error and its actions visible during a retry. The shared reader
- // retains the failure until a new response arrives, then seeds the project.
- if (projectInfoError && projectInfoError !== PROJECT_INFO_NOT_FOUND && !projectDataReady) {
- return (
- retryProjectRequests(id)}
- />
- );
- }
if (isLoadingProjectInfo || (!projectDataReady && !projectInfoError)) {
// Mirror the post-load shell (header + two-column grid) so the
// page doesn't jump when data lands. The right column gets its
@@ -1058,6 +1032,14 @@ const ProjectSettingsContent = () => {
);
}
+ // A non-404 fetch failure (cloud unreachable, network, 5xx) never delivers
+ // the real project — the empty seed still reads as "draft" below, so guard
+ // here and surface the actual load error instead of a fake draft screen.
+ // (404 / access errors are already handled via projectNotFound above.)
+ if (projectInfoError && projectInfoError !== PROJECT_INFO_NOT_FOUND && !projectDataReady) {
+ return ;
+ }
+
// Draft / never-successfully-deployed projects (no active deployment)
// get a focused screen instead of the analytics dashboard, which would
// otherwise render empty. In-flight first builds (queued/building/
diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx
index ba860acae..fa09be27a 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx
@@ -1,6 +1,6 @@
import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
import { Icon as UiIcon, type IconName } from "@repo/ui/icons";
-import React, { useCallback, useEffect, useRef, useState } from "react";
+import React, { useCallback, useEffect, useState } from "react";
import { useProjectSettings } from "@/context/ProjectSettingsContext";
import { DeletionModal } from "./DeletionModal";
import { ProjectRenameModal } from "./ProjectRenameModal";
@@ -13,7 +13,7 @@ import { invalidateProjectCaches } from "@/hooks/useProjectEndpoints";
import { getProjectStatus, migrationNeedsOperator } from "@/utils/project-status";
import { formatBytes } from "@/lib/formatBytes";
import type { RouteStrategy } from "@/lib/api/settings";
-import { isServicesFramework, type OpenshipReadiness } from "@repo/core";
+import type { OpenshipReadiness } from "@repo/core";
import { workloadOf } from "@/context/deployment/types";
import ReadinessSection from "@/components/project-settings/ReadinessSection";
import { ProjectMigrationCard } from "@/components/migration/ProjectMigrationCard";
@@ -27,8 +27,6 @@ import { isSchemaAppTemplate } from "@/components/app-settings/AppSettingsForm";
import { AppConfiguration } from "./AppConfiguration";
import { BuildSettings } from "./BuildSettings";
import { CloudStaticHosting } from "@/components/project-settings/CloudStaticHosting";
-import { ProjectIconSetting } from "@/components/project-settings/ProjectIconSetting";
-import { RuntimeSourceUpdateDialog } from "@/components/updates/RuntimeSourceUpdate";
interface Props {
onDeleteProject: (wipeVolumes?: boolean, recordOnly?: boolean) => void;
@@ -122,7 +120,7 @@ export const AdvancedSettings = ({ onDeleteProject }: Props) => {
const { user } = useAuth();
const { selfHosted } = usePlatform();
const { t } = useI18n();
- const { projectData, servicesData, buildData } = useProjectSettings();
+ const { projectData, servicesData } = useProjectSettings();
const isDeleting = getProjectStatus(projectData) === "deleting";
// `enabled` is the server's answer (derived from disabled_at in enrichProject).
// This local copy exists only so the button flips the instant the call returns;
@@ -132,15 +130,6 @@ export const AdvancedSettings = ({ onDeleteProject }: Props) => {
const [isProjectActive, setIsProjectActive] = useState(projectData?.enabled ?? true);
const [showDeleteModal, setShowDeleteModal] = useState(false);
const [showRenameModal, setShowRenameModal] = useState(false);
- const [projectDialog, setProjectDialog] = useState<"icon" | "source" | null>(null);
- const projectInfoHeader = useRef(null);
- const openProjectDialog = (dialog: "icon" | "source") => {
- // The clicked menu item unmounts; retain the trigger as the dialog's return focus.
- projectInfoHeader.current?.querySelector("button[aria-expanded]")?.focus();
- setProjectDialog(dialog);
- };
- const canProposeImageUpdate = Boolean(projectData.gitOwner && projectData.gitRepo) &&
- (Boolean(projectData.composePath) || isServicesFramework(projectData.framework));
useEffect(() => {
if (typeof projectData?.enabled === "boolean") setIsProjectActive(projectData.enabled);
@@ -273,7 +262,12 @@ export const AdvancedSettings = ({ onDeleteProject }: Props) => {
}
};
- // Project actions reuse the same editors and handlers as the existing settings.
+ /**
+ * Project-level actions for the Project Info header. Only Rename is new; the rest
+ * drive the controls this panel already owns (the pause toggle below, the deletion
+ * modal at the bottom) so there's one implementation of each, reachable from the
+ * heading as well as from its own section.
+ */
const menuActions: MenuAction[] = [
{
id: "rename",
@@ -281,12 +275,6 @@ export const AdvancedSettings = ({ onDeleteProject }: Props) => {
icon: ,
onClick: () => setShowRenameModal(true),
},
- {
- id: "change-icon",
- label: t.projectSettings.icon.change,
- icon: ,
- onClick: () => openProjectDialog("icon"),
- },
{
id: "copy-id",
label: menu.copyId,
@@ -294,13 +282,6 @@ export const AdvancedSettings = ({ onDeleteProject }: Props) => {
onClick: () => void handleCopyProjectId(),
divider: true,
},
- ...(canProposeImageUpdate ? [{
- id: "image-update",
- label: t.projectSettings.sourceImageUpdate.open,
- icon: ,
- onClick: () => openProjectDialog("source"),
- divider: true,
- }] : []),
{
id: "toggle",
label: isProjectActive ? menu.pause : menu.resume,
@@ -355,7 +336,7 @@ export const AdvancedSettings = ({ onDeleteProject }: Props) => {
would cut off. Nothing here needs the clip — the header's rule sits well
below the corner radius. */}
-
+
@@ -366,7 +347,6 @@ export const AdvancedSettings = ({ onDeleteProject }: Props) => {
{/* Project-level actions live on the heading, where the name is shown. */}
}
triggerClassName="-me-1.5 shrink-0 rounded-lg p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground"
className="shrink-0"
@@ -730,17 +710,6 @@ export const AdvancedSettings = ({ onDeleteProject }: Props) => {
- {projectDialog === "icon" && (
-
setProjectDialog(null)} />
- )}
- {projectDialog === "source" && canProposeImageUpdate && (
- setProjectDialog(null)}
- />
- )}
-
setShowRenameModal(false)}
diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AppSettingsTab.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AppSettingsTab.tsx
index 8f0097c62..238384105 100644
--- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AppSettingsTab.tsx
+++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AppSettingsTab.tsx
@@ -55,15 +55,14 @@ export function AppSettingsTab() {
}
};
- const handleApply = async (composeRevision?: string) => {
+ const handleApply = async () => {
setApplying(true);
try {
- await deployApi.trigger({ projectId: id, refresh: true, ...(composeRevision && { composeRevision }) });
+ await deployApi.trigger({ projectId: id, refresh: true });
showToast(ps.applied, "success");
setPendingApply(false);
} catch (err) {
- if (composeRevision) throw err;
- if (!showComposeReview(err, handleApply) && !showCloudPricing(err)) showToast(getApiErrorMessage(err, ps.applyFailed), "error");
+ if (!showComposeReview(err) && !showCloudPricing(err)) showToast(getApiErrorMessage(err, ps.applyFailed), "error");
} finally {
setApplying(false);
}
@@ -108,7 +107,7 @@ export function AppSettingsTab() {
{pendingApply && (