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()), - createMigrationDockerRuntime: h.runtime, -})); -vi.mock("@repo/platform/engine/modules/services/service-container", async (original) => ({ - ...(await original()), - // Resolve private-link operations onto the same isolated daemon as the import. - // Connection authorization, persistence, DNS and network attachment stay real. - resolveServicePlatform: async () => ({ platform: { runtime: await h.runtime() } }), -})); -vi.mock("@repo/platform/engine/modules/deployments/build.service", () => ({ - triggerDeployment: h.deploy, -})); -vi.mock("@repo/platform/engine/modules/deployments/project-reader", () => ({ - createGitHubReader: () => ({ readText: async () => "FROM redis:7-alpine\n" }), -})); -import { - discoverPlatform, - reviewPlatform, - loadReviewedImport, -} from "@repo/platform/engine/modules/migration/platform-import-plan"; -import { executePlatformImport } from "@repo/platform/engine/modules/migration/platform-import-worker"; - -describeDockerE2E("Railway projects retain native service boundaries", () => { - const tag = `import-groups-${randomUUID().slice(0, 8)}`; - const containers = new Set(); - const volumes = new Set(); - const images = new Set(); - const sharedNetworks = new Set(); - const projects: Array<{ id: string; slug: string }> = []; - const sources = new Map(); - let runtime: DockerRuntime; - const exec = async (id: string, command: string) => - (await (await runtime.inContainerExecutor(id)).exec(command)).trim(); - - beforeAll(async () => { - await requireDocker(); - runtime = await DockerRuntime.create({ transport: "socket" }); - await runtime.pullImage("redis:7-alpine"); - await runtime.pullImage("alpine:3"); - const host = await runtime.docker.createContainer({ - Image: "alpine:3", - Cmd: ["sleep", "infinity"], - Labels: { "openship.test": tag }, - HostConfig: { NetworkMode: "host" }, - }); - containers.add(host.id); - await host.start(); - vi.spyOn(CloudServerConnection.prototype, "connectDocker").mockImplementation(async () => { - const socket = createConnection(dockerSocketPath); - await once(socket, "connect"); - return socket; - }); - vi.spyOn(CloudServerConnection.prototype, "ensureDocker").mockResolvedValue(); - vi.spyOn(CloudServerConnection.prototype, "publishedPorts").mockResolvedValue([]); - vi.spyOn(CloudWorkspaceExecutor.prototype, "exec").mockImplementation((command) => - exec(host.id, command), - ); - }); - afterAll(async () => { - if (!runtime) return; - for (const project of projects) { - for (const id of await runtime.listProjectContainerIds(project.id)) containers.add(id); - } - for (const id of containers) { - const container = runtime.docker.getContainer(id); - for (const mount of (await container.inspect()).Mounts) { - if (mount.Type === "volume" && mount.Name) volumes.add(mount.Name); - } - await container.remove({ force: true }); - } - for (const project of projects) await runtime.removeNetwork(project.slug); - for (const name of sharedNetworks) await runtime.docker.getNetwork(name).remove(); - for (const volume of (await runtime.docker.listVolumes()).Volumes ?? []) { - if (projects.some((project) => volume.Labels?.["openship.project"] === project.id)) - volumes.add(volume.Name); - } - for (const name of volumes) await runtime.docker.getVolume(name).remove(); - for (const image of images) await runtime.removeImage(image); - await runtime.dispose(); - vi.restoreAllMocks(); - }); - - async function start(image: string, volume: string, command: string[]) { - const container = await runtime.docker.createContainer({ - Image: image, - Cmd: command, - Labels: { "openship.test": tag }, - HostConfig: { Binds: [`${volume}:/data`] }, - }); - containers.add(container.id); - await container.start(); - return container.id; - } - - it.each([ - { transport: "socket", split: false }, - { transport: "cloud", split: false }, - { transport: "socket", split: true }, - { transport: "cloud", split: true }, - ] as const)( - "imports through $transport (multiple repositories: $split), isolating DNS, env and persisted data", - async ({ transport, split }) => { - const owner = await seedOrg({ ownsHost: true }); - const ctx = { - ...owner, - role: "owner", - user: { id: owner.userId, name: "Test", email: "test@example.test" }, - sessionKind: "cookie", - } as ExecutionContext; - const serverId = `${tag}-${transport}-${split}`; - await db.insert(schema.servers).values({ - id: serverId, - organizationId: owner.organizationId, - isLocal: true, - sshHost: "localhost", - sshUser: "root", - sshAuthMethod: "key", - }); - const openRuntime = () => - DockerRuntime.create( - transport === "socket" - ? { transport: "socket" } - : { - transport: "cloud", - // The real managed Docker transport, with only its provider tunnel - // replaced. Host execution must never be used for copying data. - cloudConnection: async () => { - const socket = createConnection(dockerSocketPath); - await once(socket, "connect"); - return socket; - }, - executor: { - exec: async () => { - throw new Error("Unexpected API-host execution"); - }, - dispose: async () => {}, - } as unknown as CommandExecutor, - }, - ); - h.runtime.mockImplementation(openRuntime); - h.prepare.mockImplementation(async (_run, plan) => { - for (const service of plan.services) { - const source = sources.get(service.source.id); - if (source) await runtime.docker.getContainer(source.container).stop({ t: 10 }); - } - }); - h.assertStopped.mockImplementation(async () => { - for (const source of sources.values()) { - expect( - (await runtime.docker.getContainer(source.container).inspect()).State.Running, - ).toBe(false); - } - }); - h.openSource.mockImplementation(async (_run, service) => { - const source = sources.get(service.id)!; - const channel = { - rawExec: async (command: string) => { - const child = spawn("docker", ["exec", source.exporter, "sh", "-c", command]); - return { - stdout: child.stdout, - stderr: child.stderr, - kill: () => { - child.kill("SIGKILL"); - }, - onClose: new Promise((resolve, reject) => { - child.once("error", reject); - child.once("close", (code) => resolve(code ?? 1)); - }), - }; - }, - } as CommandExecutor; - return { - executor: new CommandSourceBackupExecutor(channel, ["/data"]), - dispose: async () => {}, - }; - }); - h.deploy.mockImplementation(async (_ctx, input) => { - // This isolated daemon uses its private project networks; no edge or - // published host ports are needed for this container-IP routing fixture. - await repos.project.update(input.projectId, { routeStrategy: "container-ip" }); - const project = (await repos.project.findById(input.projectId))!; - const services = await repos.service.listByProject(project.id); - await refreshConnectionEnv(ctx, project.id); - const preparedLocalImages = new Map(); - const builtImages = new Map(); - for (const service of services) { - if (service.image) preparedLocalImages.set(service.id, service.image); - else { - // Stand in for the immutable Git checkout with a distinct build per - // repository/revision. The image build and deployment stay real. - const directory = await mkdtemp(join(tmpdir(), "openship-import-build-")); - const image = `${tag}:${service.id}`; - images.add(image); - try { - await writeFile( - join(directory, "Dockerfile"), - `FROM redis:7-alpine\nRUN echo '${project.gitRepo}:${input.commitSha}' > /source-revision\n`, - ); - const stream = await runtime.docker.buildImage( - { context: directory, src: ["Dockerfile"] }, - { t: image, networkmode: "none", labels: { "openship.project": project.id } }, - ); - await new Promise((resolve, reject) => - runtime.docker.modem.followProgress(stream, (error, output) => { - const failure = output?.find((event: { error?: string }) => event.error)?.error; - if (error || failure) reject(error ?? new Error(failure)); - else resolve(); - }), - ); - preparedLocalImages.set(service.id, image); - builtImages.set(service.id, image); - } finally { - await rm(directory, { recursive: true, force: true }); - } - } - } - const deployment = await seedDeployment(project, { - status: "deploying", - trigger: "manual", - imageRef: "compose", - containerId: "compose", - meta: { - runtimeMode: "docker", - deployTarget: "local", - composeServices: projectServicesToDeployableServices(services), - }, - }); - const target = - transport === "socket" - ? await openRuntime() - : await CloudDockerRuntime.forWorkspace( - { - vms: { - get: async () => ({ - id: serverId, - namespace: owner.organizationId, - status: "running", - }), - }, - } as unknown as Parameters[0], - { - workspaceId: serverId, - ownerWorkspaceId: serverId, - projectId: project.id, - namespace: owner.organizationId, - provisionLock: { run: (work) => work() }, - resolveRegistryAuth: async () => undefined, - }, - ); - try { - const result = await deployComposeServices( - project, - deployment, - target, - new BuildLogger(() => {}), - { - executor: null, - localHost: false, - preparedLocalImages, - builtImages, - targetServiceIds: new Set(input.serviceIds), - }, - ); - expect(result.status, JSON.stringify(result)).toBe("ready"); - await repos.deployment.updateStatus(deployment.id, "ready"); - await setActive(project.id, deployment.id); - await result.cutover?.commit(); - } finally { - await target.dispose(); - } - return { deployment }; - }); - - const imported: Array<{ id: string; marker: string }> = []; - for (const projectNumber of [1, 2]) { - const marker = `${tag}-${transport}-${split}-${projectNumber}`; - const services: ProviderInventory["services"] = []; - for (const name of ["db", "cache"]) { - const id = `${marker}-${name}`; - const volume = `${id}-source`; - await runtime.docker.createVolume({ Name: volume }); - volumes.add(volume); - const container = await start("redis:7-alpine", volume, [ - "redis-server", - "--appendonly", - "yes", - ]); - await expect - .poll(() => exec(container, "redis-cli PING"), { timeout: 10_000 }) - .toBe("PONG"); - await exec(container, `redis-cli SET marker '${marker}-${name}'`); - const exporter = await start("alpine:3", volume, ["sleep", "infinity"]); - sources.set(id, { container, exporter }); - services.push({ - id, - name, - kind: "database", - database: "redis_rdb", - image: "redis:7-alpine", - instanceId: container, - privateDomain: `${name}.railway.internal`, - port: 6379, - env: { SERVICE_SECRET: `${marker}-${name}` }, - rawEnv: {}, - variables: [], - volumes: [{ id: volume, mountPath: "/data" }], - domains: [], - warnings: [], - blockers: [], - startCommand: "redis-server --appendonly yes", - }); - } - services.push({ - id: `${marker}-worker`, - name: "worker", - kind: "worker", - image: "redis:7-alpine", - instanceId: "source-worker", - port: 8080, - env: { - SERVICE_SECRET: `${marker}-worker`, - PRIMARY_HOST: "db.railway.internal", - CACHE_HOST: "cache.railway.internal", - BOTH_HOSTS: "db.railway.internal,cache.railway.internal", - }, - rawEnv: {}, - variables: [], - volumes: [], - domains: [ - { hostname: `${marker}.example.com`, portable: true }, - { hostname: `www.${marker}.example.com`, portable: true }, - { hostname: `${marker}.up.railway.app`, portable: false }, - ], - warnings: [], - blockers: [], - startCommand: - "sh -c 'while true; do printf \"HTTP/1.1 200 OK\\r\\nContent-Length: 6\\r\\nConnection: close\\r\\n\\r\\nready\\n\" | nc -l -p 8080; done'", - }); - if (split) { - // Two distinct Git sources plus one image-backed database. All volumes - // must move before either destination Git service is allowed to start. - for (const name of ["cache", "worker"]) { - const source = services.find((service) => service.name === name)!; - source.image = undefined; - source.repository = `fixture/${name}`; - source.commit = (name === "cache" ? "a" : "b").repeat(40); - source.branch = "main"; - source.dockerfile = "Dockerfile"; - } - delete services.find((service) => service.name === "worker")!.env.BOTH_HOSTS; - } - const inventory: ProviderInventory = { - provider: "railway", - source: { connectionId: "fixture", projectId: marker, environmentId: "production" }, - projectName: marker, - environmentName: "Production", - services, - warnings: [], - }; - h.discover.mockImplementation(async () => structuredClone(inventory)); - const discovery = await discoverPlatform(ctx, inventory.source); - const review = await reviewPlatform(ctx, { - draftId: discovery.draftId, - targetServerId: serverId, - services: discovery.services.map((s) => ({ id: s.id, name: s.name, data: "copy" })), - }); - expect(review.ready, JSON.stringify(review)).toBe(true); - const plan = await loadReviewedImport(ctx, review.planId); - const runId = `${marker}-run`; - await repos.dockerMigrationRun.create({ - id: runId, - organizationId: owner.organizationId, - targetServerId: serverId, - projectName: marker, - mode: "provider_import", - status: "adopting", - inputSnapshot: { provider: "railway", source: inventory.source }, - recovery: { - providerImport: { - planId: plan.id, - planEnc: encrypt(JSON.stringify(plan)), - connectionId: "fixture", - projects: {}, - completed: [], - cleanupPending: true, - }, - }, - }); - try { - await executePlatformImport(ctx, runId, plan, { - signal: new AbortController().signal, - log: () => {}, - progress: () => {}, - phase: async () => {}, - wait: async (id) => (await repos.deployment.findById(id))?.status === "ready", - }); - } finally { - const saved = await repos.project.listByOrganization(owner.organizationId); - for (const p of saved.rows) { - if (!projects.some((known) => known.id === p.id)) projects.push(p); - for (const link of await repos.projectConnection.listByTarget(p.id)) - if (link.sourceServiceId) - sharedNetworks.add(sharedServiceNetwork(link.sourceServiceId)); - } - } - const checkpoint = (await repos.dockerMigrationRun.findById(runId))!.recovery - .providerImport!; - const ids = [...new Set(Object.values(checkpoint.projects))]; - expect(ids).toHaveLength(split ? 3 : 1); - expect(checkpoint.completed).toHaveLength(3); - expect((await repos.project.listByOrganization(owner.organizationId)).total).toBe( - projectNumber * (split ? 3 : 1), - ); - for (const id of ids) { - expect(await repos.service.listByProject(id)).toHaveLength(split ? 1 : 3); - if (!split) expect(await repos.project.getEnvMap(id, "production", null)).toEqual({}); - imported.push({ id, marker }); - } - } - - // Check both projects AFTER the second import: duplicate service names - // must not redirect the first project's DNS or overwrite its storage. - for (const { id, marker } of imported) { - const project = (await repos.project.findById(id))!; - const rows = await repos.service.listByProject(id); - const deployed = await repos.service.listByDeployment(project.activeDeploymentId!); - for (const service of rows) { - const env = decryptEnvMap(await repos.project.getEnvMap(id, "production", service.id)); - expect(env.SERVICE_SECRET).toBe(`${marker}-${service.name}`); - const container = deployed.find((r) => r.serviceId === service.id)!.containerId!; - expect(await exec(container, 'printf %s "$SERVICE_SECRET"')).toBe(env.SERVICE_SECRET); - if (split && project.gitRepo) { - const revision = (service.name === "cache" ? "a" : "b").repeat(40); - expect(await exec(container, "cat /source-revision")).toBe( - `${project.gitRepo}:${revision}`, - ); - } - if (service.name === "worker") { - expect(service.exposed).toBe(true); - expect(service.publicEndpoints).toEqual([ - expect.objectContaining({ port: 8080, customDomain: `${marker}.example.com` }), - ]); - const domains = await repos.domain.listByProject(id); - expect(domains.map((domain) => domain.hostname).sort()).toEqual( - [`${marker}.example.com`, `www.${marker}.example.com`].sort(), - ); - expect( - domains.every( - (domain) => - domain.serviceId === service.id && domain.targetPort === 8080 && !domain.verified, - ), - ).toBe(true); - expect(await exec(container, "wget -qO- http://127.0.0.1:8080")).toBe("ready"); - if (!split) expect(await exec(container, 'printf %s "$BOTH_HOSTS"')).toBe("db,cache"); - else { - const links = await repos.projectConnection.listByTarget(id); - expect(links).toHaveLength(2); - expect( - links.every( - (link) => - link.organizationId === owner.organizationId && - link.mode === "internal" && - link.usesPrivateNetwork, - ), - ).toBe(true); - for (const link of links) { - expect(env[link.envKey]).toBeUndefined(); // Service env must not shadow its native link. - expect(await exec(container, `printenv ${link.envKey}`)).toBe( - sharedServiceAlias(link.sourceServiceId!), - ); - } - } - expect(await exec(container, 'redis-cli -h "$PRIMARY_HOST" GET marker')).toBe( - `${marker}-db`, - ); - expect(await exec(container, 'redis-cli -h "$CACHE_HOST" GET marker')).toBe( - `${marker}-cache`, - ); - if (split) { - // An ordinary later deployment refreshes the same saved links and - // rejoins the private networks without the import worker involved. - await h.deploy(ctx, { - projectId: id, - serviceIds: [service.id], - commitSha: "b".repeat(40), - }); - const current = (await repos.project.findById(id))!; - const next = (await repos.service.listByDeployment(current.activeDeploymentId!)).find( - (row) => row.serviceId === service.id, - )!; - expect(await exec(next.containerId!, 'redis-cli -h "$PRIMARY_HOST" GET marker')).toBe( - `${marker}-db`, - ); - expect(await exec(next.containerId!, 'redis-cli -h "$CACHE_HOST" GET marker')).toBe( - `${marker}-cache`, - ); - } - } else { - expect(await exec(container, "redis-cli GET marker")).toBe(`${marker}-${service.name}`); - await exec(container, "redis-cli SET new-write survives"); - await runtime.docker.getContainer(container).restart({ t: 10 }); - await expect - .poll(() => exec(container, "redis-cli GET marker"), { timeout: 10_000 }) - .toBe(`${marker}-${service.name}`); - expect(await exec(container, "redis-cli GET new-write")).toBe("survives"); - } - } - } - }, - ); -}); diff --git a/apps/api/test/e2e/route-protection.e2e.test.ts b/apps/api/test/e2e/route-protection.e2e.test.ts index 10a4cc5a1..c00322877 100644 --- a/apps/api/test/e2e/route-protection.e2e.test.ts +++ b/apps/api/test/e2e/route-protection.e2e.test.ts @@ -6,8 +6,6 @@ import { PassThrough } from "node:stream"; import { readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { gzipSync } from "node:zlib"; -import { compileEdgePages, normalizeEdgeResponse, type EdgePages } from "@repo/core"; import { NginxProvider, OPENRESTY_DEFAULT_PATHS, @@ -36,7 +34,6 @@ let docker: Docker; const paths = OPENRESTY_DEFAULT_PATHS; const proxyLocations = [ { pathPrefix: "/api/", targetUrl: "http://127.0.0.1:39482", external: true }, - { pathPrefix: "/offline/", targetUrl: "http://127.0.0.1:39483", external: true }, ]; async function exec(command: string, options?: { user?: string; timeout?: number }): Promise { @@ -60,14 +57,10 @@ async function exec(command: string, options?: { user?: string; timeout?: number return text; } async function write(path: string, contents: string, mode = 0o644) { - // Match the container executor's bounded writes: HTML can exceed the kernel's - // per-argument limit once encoded in a vhost. Never expand payload as shell code. + // No shell expansion of the payload, including passwords or Lua source. await exec( - `mkdir -p ${sq(path.substring(0, path.lastIndexOf("/")))} && (umask 077; : > ${sq(path)}) && chmod ${mode.toString(8)} ${sq(path)}`, + `mkdir -p ${sq(path.substring(0, path.lastIndexOf("/")))} && (umask 077; printf %s ${sq(Buffer.from(contents).toString("base64"))} | base64 -d > ${sq(path)}) && chmod ${mode.toString(8)} ${sq(path)}`, ); - const encoded = Buffer.from(contents).toString("base64"); - for (let offset = 0; offset < encoded.length; offset += 32768) - await exec(`printf %s ${sq(encoded.slice(offset, offset + 32768))} | base64 -d >> ${sq(path)}`); } type Answer = { status: number; headers: IncomingHttpHeaders; body: string }; function ask( @@ -210,28 +203,6 @@ describeDockerE2E("password-protected routes through the real edge", () => { `${paths.sitesDir}/_test_upstream.conf`, `server { listen 127.0.0.1:39482; - header_filter_by_lua_block { } - body_filter_by_lua_block { } - location = /api/authorization { - content_by_lua_block { ngx.print((ngx.var.http_authorization or "none") .. "|" .. (ngx.var.http_cookie or "none")) } - } - location = /api/error { - content_by_lua_block { - ngx.status = tonumber(ngx.var.arg_status) or 502 - ngx.header["Content-Type"] = "application/json" - ngx.header["Content-Security-Policy"] = "default-src 'none'" - ngx.print('{"error":"original app response"}') - } - } - location = /api/compressed { - content_by_lua_block { - ngx.status = 502 - ngx.header["Content-Encoding"] = "gzip" - ngx.print(ngx.decode_base64("${gzipSync("original compressed error").toString("base64")}")) - } - } - # Test-only bridge to the loopback management listener. - location = /api/test-rules { proxy_pass http://127.0.0.1:9145/rules; } location / { add_header Cache-Control "public, max-age=3600"; content_by_lua_block { ngx.print(ngx.var.http_cookie or "none") } @@ -381,21 +352,6 @@ describeDockerE2E("password-protected routes through the real edge", () => { } }); - it("protects literal edge responses and prevents them from making private content cacheable", async () => { - const payload = JSON.stringify({ host: "private.test", rules: [{ pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ body: "private response", headers: { "Cache-Control": "public, max-age=3600" } }) } }] }); - try { - const applied = await ask("/api/test-rules", { cookie, method: "POST", body: payload, headers: { "Content-Type": "application/json" } }); - expect(applied.status).toBe(200); - expect(JSON.parse(applied.body)).toMatchObject({ ok: true, staticResponses: true }); - expect((await ask("/virtual")).status).toBe(401); - const response = await ask("/virtual", { cookie }); - expect(response).toMatchObject({ status: 200, body: "private response" }); - expect(response.headers["cache-control"]).toBe("private, no-store"); - } finally { - expect((await ask("/api/test-rules?host=private.test", { cookie, method: "DELETE" })).status).toBe(200); - } - }); - it("rejects cross-origin sign-in and unsafe return locations", async () => { const csrf = (await ask("/")).body.match(/name="csrf" value="([^"]+)"/)![1]; for (const origin of ["https://attacker.test", "null"]) { @@ -509,131 +465,6 @@ describeDockerE2E("password-protected routes through the real edge", () => { } }); - it("uses browser authentication without HTML, strips credentials, and revokes cached passwords", async () => { - const headers = { Authorization: `Basic ${Buffer.from(`viewer:${password}`).toString("base64")}` }; - const basic = { ...protection, mode: "basic" as const, username: "viewer" }; - try { - await nginx.setRouteProtection("other.test", basic); - await settleReload(); - const rejected = await ask("/", { host: "other.test" }); - expect(rejected.status).toBe(401); - expect(rejected.headers["www-authenticate"]).toContain("Basic"); - expect(rejected.body).not.toContain(" { - const loginHtml = `Our private site
{{form}}
`; - try { - await nginx.setRouteProtection("private.test", { ...protection, loginHtml }); - await settleReload(); - const page = await ask("/"); - expect(page.status).toBe(401); - expect(page.body).toContain("Our private site"); - expect(page.body).toContain('name="csrf"'); - expect(page.body).not.toContain("{{form}}"); - expect(page.headers["content-security-policy"]).toContain("default-src 'none'"); - expect((await login()).status).toBe(303); - } finally { - await nginx.setRouteProtection("private.test", protection); - await settleReload(); - } - }); - - it("serves maintenance at the edge for all methods and paths without bypassing authentication", async () => { - const html = '

Back after our upgrade

'; - const pages = compileEdgePages({ files: [{ id: "maintenance", name: "maintenance.html", html }], errors: [], maintenance: { enabled: true, pageId: "maintenance", retryAfter: 600 } })!; - try { - await nginx.setRouteEdgePages("private.test", pages); - await settleReload(); - for (const path of ["/", "/api/error", "/old", "/asset.js", "/missing"]) { - expect((await ask(path)).status).toBe(401); - const response = await ask(path, { cookie }); - expect(response).toMatchObject({ status: 503, body: html }); - expect(response.headers["retry-after"]).toBe("600"); - expect(response.headers["cache-control"]).toBe("private, no-store"); - } - expect((await ask("/api/error", { method: "POST", body: "data", cookie })).status).toBe(503); - expect(await ask("/", { method: "HEAD", cookie })).toMatchObject({ status: 503, body: "" }); - expect((await ask("/_openship/access")).status).toBe(401); - expect((await ask("/.well-known/acme-challenge/verify_123")).status).not.toBe(503); - expect((await ask("/", { host: "public.test" })).status).toBe(200); - // Changing the route target must retain maintenance, including a restart. - await nginx.registerRoute({ domain: "private.test", tls: true, terminatesTlsLocally: true, staticRoot: "/opt/openship/route-test", proxyLocations }); - await exec("openresty -s stop && sleep 1 && openresty"); - expect((await ask("/", { cookie })).status).toBe(503); - // A rejected update restores both the generated vhost and its durable state. - await write(`${paths.sitesDir}/invalid.conf`, "not_an_nginx_directive;"); - await expect(nginx.setRouteEdgePages("private.test", null)).rejects.toThrow(); - expect(await nginx.getRouteEdgePages("private.test")).toEqual(pages); - expect((await ask("/", { cookie })).status).toBe(503); - } finally { - await exec(`rm -f ${sq(`${paths.sitesDir}/invalid.conf`)}`); - await nginx.setRouteEdgePages("private.test", null); - await settleReload(); - } - expect((await ask("/", { cookie })).status).toBe(200); - }); - - it("inherits server error pages, overrides per hostname, and keeps status codes and IP defaults", async () => { - const serverHtml = `

Server unavailable

`; - const hostHtml = '

Project unavailable

'; - const addressHtml = '

Choose a connected domain

'; - const config: EdgePages = { files: [ - { id: "error", name: "unavailable.html", html: serverHtml }, - { id: "address", name: "address.html", html: addressHtml }, - ], errors: [{ status: 502, pageId: "error" }, { status: 503, pageId: "error" }], defaultPageId: "address" }; - try { - await nginx.setEdgePages(config); - await nginx.setRouteEdgePages("private.test", { errors: { "502": hostHtml } }); - await settleReload(); - expect(await nginx.getEdgePages()).toEqual(config); - expect(await ask("/api/error?status=502", { cookie })).toMatchObject({ status: 502, body: hostHtml }); - expect(await ask("/offline/", { cookie })).toMatchObject({ status: 502, body: hostHtml }); - const compressed = await ask("/api/compressed", { cookie }); - expect(compressed).toMatchObject({ status: 502, body: hostHtml }); - expect(compressed.headers["content-encoding"]).toBeUndefined(); - const inherited = await ask("/api/error?status=503", { cookie }); - expect(inherited).toMatchObject({ status: 503, body: serverHtml }); - expect(inherited.headers["content-type"]).toContain("text/html"); - expect(inherited.headers["content-security-policy"]).toBeUndefined(); - expect(inherited.headers["cache-control"]).toBe("private, no-store"); - expect(await ask("/api/error?status=502", { method: "HEAD", cookie })).toMatchObject({ status: 502, body: "" }); - expect(await ask("/api/error?status=502", { host: "public.test" })).toMatchObject({ status: 502, body: serverHtml }); - expect(await ask("/api/error?status=504", { cookie })).toMatchObject({ status: 504, body: '{"error":"original app response"}' }); - expect((await ask("/api/error?status=502")).status).toBe(401); - expect(await ask("/", { host: "unmatched.test", http: true })).toMatchObject({ status: 404, body: addressHtml }); - expect(await ask("/", { host: "127.0.0.1", http: true })).toMatchObject({ status: 404, body: addressHtml }); - expect((await ask("/.well-known/acme-challenge/unknown", { host: "unmatched.test", http: true })).body).not.toContain("Choose a connected domain"); - await write(`${paths.sitesDir}/invalid.conf`, "not_an_nginx_directive;"); - await expect(nginx.setEdgePages({ files: [], errors: [] })).rejects.toThrow(); - expect(await nginx.getEdgePages()).toEqual(config); - } finally { - await exec(`rm -f ${sq(`${paths.sitesDir}/invalid.conf`)}`); - await nginx.setEdgePages({ files: [], errors: [] }); - await nginx.setRouteEdgePages("private.test", null); - await settleReload(); - } - expect(await ask("/api/error?status=502", { host: "public.test" })).toMatchObject({ status: 502, body: '{"error":"original app response"}' }); - }); - it("invalidates old cookies and restores the previous lock after a rejected config update", async () => { protection = revokeRouteSessions(protection); await nginx.setRouteProtection("private.test", protection); diff --git a/apps/api/test/e2e/routing-rules.e2e.test.ts b/apps/api/test/e2e/routing-rules.e2e.test.ts index 5bb132807..d7d7585b8 100644 --- a/apps/api/test/e2e/routing-rules.e2e.test.ts +++ b/apps/api/test/e2e/routing-rules.e2e.test.ts @@ -69,14 +69,13 @@ import { type RootChecked, type RouteConfig, } from "@repo/adapters"; -import { normalizeEdgeResponse, type RoutingConfig } from "@repo/core"; +import type { RoutingConfig } from "@repo/core"; import { compileProjectRoutingFields } from "@repo/platform/engine/lib/project-routing-fields"; import { buildDomainFanoutRegistrations } from "@repo/platform/engine/modules/deployments/compose/composite-route"; import type Dockerode from "dockerode"; import { describeDockerE2E, requireDocker } from "../helpers/docker-e2e"; import { freePort } from "../helpers/free-port"; import { EMBEDDED_LUA } from "../../../../packages/adapters/src/infra/lua-embedded"; -import { EDGE_CLIENT_MAX_BODY_SIZE } from "../../../../packages/adapters/src/infra/openresty-lua"; import type { HostRuleEntry } from "@repo/platform/engine/modules/route-rules/route-rule.service"; const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), "../../../.."); @@ -269,94 +268,16 @@ events { worker_connections 128; } http { include ${OPENRESTY_DEFAULT_PATHS.confDir}/mime.types; default_type application/octet-stream; - client_max_body_size ${EDGE_CLIENT_MAX_BODY_SIZE}; access_log off; lua_package_path "/usr/local/openresty/site/lualib/?.lua;;"; ${EDGE_SHARED_DICTS.filter(({ name }) => name === "rules" || name === "rl_counters") .map(({ name, size }) => `lua_shared_dict ${name} ${size};`) .join("\n ")} - # Deterministic hot-path instrumentation, isolated to this fixture worker. - init_worker_by_lua_block { - local counts = { decodes=0, pathDecodes=0, bodyReads=0, bodyBytes=0, hashes=0 } - package.loaded.response_test_costs = counts - local json = require "cjson.safe" - local decode = json.decode - json.decode = function(...) - counts.decodes = counts.decodes + 1 - return decode(...) - end - local unescape = ngx.unescape_uri - ngx.unescape_uri = function(...) - counts.pathDecodes = counts.pathDecodes + 1 - return unescape(...) - end - local dict = ngx.shared.rules - local get = dict.get - dict.get = function(self, key, ...) - local value = get(self, key, ...) - if string.sub(key, 1, 10) == "responses:" then - counts.bodyReads = counts.bodyReads + 1 - counts.bodyBytes = counts.bodyBytes + (value and #value or 0) - end - return value - end - local lib = require "openship.rules_lib" - local digest = lib.response_revision - lib.response_revision = function(...) - counts.hashes = counts.hashes + 1 - return digest(...) - end - } - # Test-only management vhost, on the same loopback-published test port. server { listen 80; server_name management.test; - location = /response-legacy-worker { - content_by_lua_block { - local lib = require "openship.rules_lib" - if ngx.req.get_method() == "POST" then - local previous = {} - for _, key in ipairs({ "static_responses", "valid_responses", "response_revision", "response_for" }) do - previous[key], lib[key] = lib[key], nil - end - package.loaded.response_test_previous = previous - else - for key, value in pairs(package.loaded.response_test_previous or {}) do lib[key] = value end - end - ngx.say("ok") - } - } - location = /response-costs { - content_by_lua_block { - local counts = package.loaded.response_test_costs - if ngx.req.get_method() == "POST" then - for key in pairs(counts) do counts[key] = 0 end - end - ngx.say(require("cjson.safe").encode(counts)) - } - } - location = /response-memory { - content_by_lua_block { - local dict = ngx.shared.rules - if ngx.req.get_method() == "POST" then - local i = 0 - while dict:safe_set("test-fill:" .. i, string.rep("x", 65536)) do i = i + 1 end - ngx.say(i) - else - for _, key in ipairs(dict:get_keys(0)) do - if string.sub(key, 1, 10) == "test-fill:" then dict:delete(key) end - end - ngx.say("cleared") - end - } - } - location = /policy-cache-check { - content_by_lua_block { - ngx.say(ngx.shared.rules:get("rules.test") or "[]") - } - } location = /country-cache-check { content_by_lua_block { ngx.say(assert(loadfile("/tmp/visitor-country.lua"))()) @@ -1013,9 +934,8 @@ http { pathPrefix?: string | null; } >, - targetPort = port, ): Promise { - const response = await ask(targetPort, "/rules", "management.test", { + const response = await ask(port, "/rules", "management.test", { method: "POST", body: JSON.stringify({ host, rules }), }); @@ -1023,370 +943,6 @@ http { expect(JSON.parse(response.body)).toMatchObject({ ok: true, host, count: rules.length }); } - it("serves exact literal responses with headers, query strings, Unicode and HEAD", async () => { - const body = '{"message":"مرحبا","literal":"$host; return 500;"}'; - await pushRules("rules.test", [ - { - pathPrefix: "/virtual", - spec: { - response: normalizeEdgeResponse({ - status: 201, - contentType: "application/json", - body, - headers: { "X-Example": "literal-$host" }, - }), - }, - }, - ]); - const result = await ask(port, "/virtual?source=test", "rules.test"); - expect(result).toMatchObject({ status: 201, body }); - expect(result.headers["content-type"]).toBe("application/json"); - expect(result.headers["x-example"]).toBe("literal-$host"); - expect(result.headers["content-length"]).toBe(String(Buffer.byteLength(body))); - const head = await ask(port, "/virtual", "rules.test", { method: "HEAD" }); - expect(head).toMatchObject({ status: 201, body: "" }); - expect(head.headers["content-length"]).toBe(String(Buffer.byteLength(body))); - for (const path of ["/virtual/child", "/virtual-other"]) { - expect((await ask(port, path, "rules.test")).body).not.toBe(body); - } - expect((await ask(port, "/virtual", "other-rules.test")).body).not.toBe(body); - expect((await ask(port, "/virtual", "rules.test", { method: "POST" })).status).not.toBe(201); - }); - - it("keeps responses out of the legacy policy cache during edge upgrades", async () => { - const capability = await ask(port, "/rules/capabilities", "management.test", { - method: "POST", - body: "{}", - }); - expect(JSON.parse(capability.body)).toMatchObject({ ok: true, staticResponses: true }); - const policy = { pathPrefix: null, spec: { access: { methods: ["GET"] } } }; - await pushRules("rules.test", [ - policy, - { pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ body: "ready" }) } }, - ]); - const legacy = await ask(port, "/policy-cache-check", "management.test"); - expect(JSON.parse(legacy.body)).toEqual([policy]); - const stored = await ask(port, "/rules?host=rules.test", "management.test"); - expect(JSON.parse(stored.body).rules).toHaveLength(2); - await ask(port, "/rules?host=rules.test", "management.test", { method: "DELETE" }); - expect((await ask(port, "/virtual", "rules.test")).body).not.toBe("ready"); - }); - - it("still publishes policies while a worker has the previous rules library loaded", async () => { - // Earlier route-update tests gracefully reload the shared edge. Their old - // and new workers can briefly overlap, so a worker-local library mutation - // must use a fresh edge whose single worker is stable across these requests. - const legacyPort = await bootAll(); - await pushRules("rules.test", [ - { pathPrefix: null, spec: { access: { methods: ["GET"] } } }, - { - pathPrefix: "/virtual", - spec: { response: normalizeEdgeResponse({ body: "new worker response" }) }, - }, - ], legacyPort); - await ask(legacyPort, "/response-legacy-worker", "management.test", { method: "POST" }); - try { - // A new worker may already have published a response into shared memory. - // This worker must still enforce its policies and serve ordinary traffic. - const ordinary = await ask(legacyPort, "/virtual", "rules.test"); - expect(ordinary.status).toBe(200); - expect(ordinary.body).not.toBe("new worker response"); - expect((await ask(legacyPort, "/virtual", "rules.test", { method: "POST" })).status).toBe(403); - await pushRules("rules.test", [{ pathPrefix: null, spec: { access: { methods: ["GET"] } } }], legacyPort); - const capability = await ask(legacyPort, "/rules/capabilities", "management.test"); - expect(JSON.parse(capability.body).staticResponses).toBe(false); - const response = await ask(legacyPort, "/rules", "management.test", { - method: "POST", - body: JSON.stringify({ - host: "rules.test", - rules: [ - { - pathPrefix: "/virtual", - spec: { response: normalizeEdgeResponse({ body: "not yet" }) }, - }, - ], - }), - }); - expect(response.status).toBe(409); - expect((await ask(legacyPort, "/virtual", "rules.test", { method: "POST" })).status).toBe(403); - } finally { - await ask(legacyPort, "/response-legacy-worker", "management.test", { method: "DELETE" }); - } - }); - - it("retains domain access, bans and rate limits in front of a static response", async () => { - const response = { - pathPrefix: "/virtual", - spec: { response: normalizeEdgeResponse({ body: "answer", methods: [] }) }, - }; - for (const policy of [ - { access: { methods: ["POST"] } }, - { ban: { userAgents: ["blocked-client"] } }, - { hotlink: { allowReferers: ["allowed.test"], allowEmpty: false } }, - ]) { - await pushRules("rules.test", [response, { pathPrefix: null, spec: policy }]); - expect( - (await ask(port, "/virtual", "rules.test", { headers: { "User-Agent": "blocked-client" } })) - .status, - ).toBe(403); - } - await pushRules("rules.test", [ - response, - { pathPrefix: "/virtual", spec: { rateLimit: { rps: 1, burst: 0 } } }, - ]); - const statuses = await Promise.all( - Array.from({ length: 8 }, () => ask(port, "/virtual", "rules.test").then((r) => r.status)), - ); - expect(statuses).toContain(429); - }); - - it("matches prefixes at a path boundary and gives exact responses precedence", async () => { - const rules = [ - { - pathPrefix: "/virtual", - spec: { response: normalizeEdgeResponse({ match: "prefix", body: "prefix" }) }, - }, - { pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ body: "exact" }) } }, - ]; - for (const ordered of [rules, [...rules].reverse()]) { - await pushRules("rules.test", ordered); - expect((await ask(port, "/virtual", "rules.test")).body).toBe("exact"); - expect((await ask(port, "/virtual/child", "rules.test")).body).toBe("prefix"); - expect((await ask(port, "/virtual-other", "rules.test")).body).not.toBe("prefix"); - } - await pushRules("rules.test", [ - { - pathPrefix: "/index.html", - spec: { response: normalizeEdgeResponse({ body: "only-index" }) }, - }, - ]); - expect((await ask(port, "/unmatched-spa-path", "rules.test")).body).not.toBe("only-index"); - }); - - it("keeps custom error content and empty responses exact, including bodyless statuses", async () => { - for (const [status, body] of [ - [404, "Custom missing page"], - [503, ""], - [204, ""], - [205, ""], - [304, ""], - ] as const) { - await pushRules("rules.test", [ - { pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ status, body }) } }, - ]); - const answer = await ask(port, "/virtual", "rules.test"); - expect(answer).toMatchObject({ status, body }); - if (status === 204 || status === 304) - expect(answer.headers["content-length"]).toBeUndefined(); - } - }); - - it("applies large bodies, updates and removal without a reload", async () => { - const body = "ع".repeat(32000); - await pushRules("rules.test", [ - { pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ body }) } }, - ]); - expect((await ask(port, "/virtual", "rules.test")).body).toBe(body); - await pushRules("rules.test", [ - { pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ body: "updated" }) } }, - ]); - expect((await ask(port, "/virtual", "rules.test")).body).toBe("updated"); - await pushRules("rules.test", []); - expect((await ask(port, "/virtual", "rules.test")).body).not.toBe("updated"); - }); - - it("rejects unsafe or malformed responses before changing active rules", async () => { - const original = normalizeEdgeResponse({ body: "original response" }); - await pushRules("rules.test", [ - { pathPrefix: null, spec: { access: { methods: ["GET"] } } }, - { pathPrefix: "/virtual", spec: { response: original } }, - ]); - const invalid = [ - { headers: { "X-Test": "ok\r\nInjected: yes" } }, - { headers: { "X-Test": "nul\0value" } }, - { headers: { "Bad Header": "value" } }, - { headers: { "X-Test": "one", "x-test": "two" } }, - ...[ - "Content-Length", - "Transfer-Encoding", - "Content-Encoding", - "Connection", - "X-Accel-Redirect", - ].map((name) => ({ headers: { [name]: "unsafe" } })), - { headers: { "X-Test": "a".repeat(2049) } }, - { headers: Object.fromEntries(Array.from({ length: 33 }, (_, i) => [`X-${i}`, "value"])) }, - { - headers: Object.fromEntries( - Array.from({ length: 5 }, (_, i) => [`X-${i}`, "a".repeat(2048)]), - ), - }, - { body: "ع".repeat(32769) }, - { status: 101 }, - { status: 204 }, - { status: 200.5 }, - { contentType: "text/plain\r\nInjected: yes" }, - { contentType: "bad-type" }, - { methods: "GET" }, - { methods: ["TRACE"] }, - { methods: { GET: true } }, - { match: "regex" }, - ]; - for (const override of invalid) { - const rejected = await ask(port, "/rules", "management.test", { - method: "POST", - body: JSON.stringify({ - host: "rules.test", - rules: [{ pathPrefix: "/virtual", spec: { response: { ...original, ...override } } }], - }), - }); - expect(rejected.status, JSON.stringify(override).slice(0, 100)).toBe(400); - const answer = await ask(port, "/virtual", "rules.test"); - expect(answer.body).toBe(original.body); - expect(answer.headers["injected"]).toBeUndefined(); - expect((await ask(port, "/virtual", "rules.test", { method: "POST" })).status).toBe(403); - } - for (const pathPrefix of [ - "/_openship/hooks/probe", - "/.openship/auth", - "/.well-known/acme-challenge/probe", - "/../virtual", - "/bad//path", - "/bad%2Fpath", - "/" + "x".repeat(512), - ]) { - const rejected = await ask(port, "/rules", "management.test", { - method: "POST", - body: JSON.stringify({ - host: "rules.test", - rules: [{ pathPrefix, spec: { response: original } }], - }), - }); - expect(rejected.status, pathPrefix).toBe(400); - } - }); - - it("bounds route counts and preserves access policies when response storage is full", async () => { - const responses = Array.from({ length: 64 }, (_, i) => ({ - pathPrefix: `/bounded/${i}`, - spec: { response: normalizeEdgeResponse({ body: `response-${i}` }) }, - })); - await pushRules("rules.test", responses); - expect((await ask(port, "/bounded/63", "rules.test")).body).toBe("response-63"); - for (const extra of [responses[0], { ...responses[0], pathPrefix: "/overflow" }]) { - const rejected = await ask(port, "/rules", "management.test", { - method: "POST", - body: JSON.stringify({ host: "rules.test", rules: [...responses, extra] }), - }); - expect(rejected.status).toBe(400); - expect((await ask(port, "/bounded/63", "rules.test")).body).toBe("response-63"); - } - await pushRules("rules.test", [{ pathPrefix: null, spec: { access: { methods: ["GET"] } } }]); - try { - expect( - (await ask(port, "/response-memory", "management.test", { method: "POST" })).status, - ).toBe(200); - const failed = await ask(port, "/rules", "management.test", { - method: "POST", - body: JSON.stringify({ - host: "other-rules.test", - rules: responses.map((entry) => ({ - ...entry, - spec: { response: normalizeEdgeResponse({ body: "x".repeat(65536) }) }, - })), - }), - }); - expect(failed.status, failed.body).toBe(503); - expect((await ask(port, "/virtual", "rules.test", { method: "POST" })).status).toBe(403); - } finally { - await ask(port, "/response-memory", "management.test", { method: "DELETE" }); - } - }); - - it("keeps unconfigured traffic cheap and reuses compiled responses without copying bodies", async () => { - const reset = () => ask(port, "/response-costs", "management.test", { method: "POST" }); - const costs = async () => - JSON.parse((await ask(port, "/response-costs", "management.test")).body); - for (const policies of [[], [{ pathPrefix: null, spec: { access: { methods: ["GET"] } } }]]) { - await pushRules("rules.test", policies); - await ask(port, "/", "rules.test"); // warm existing policy/GeoIP caches - await reset(); - for (let i = 0; i < 16; i++) await ask(port, "/", "rules.test"); - expect(await costs()).toEqual({ - decodes: 0, - pathDecodes: 0, - bodyReads: 0, - bodyBytes: 0, - hashes: 0, - }); - } - const entries = (body: string) => [ - { pathPrefix: "/virtual", spec: { response: normalizeEdgeResponse({ body }) } }, - ]; - const body = "x".repeat(65536); - await pushRules("rules.test", entries(body)); - await reset(); - expect((await ask(port, "/virtual", "rules.test")).body).toBe(body); - expect(await costs()).toMatchObject({ decodes: 1, pathDecodes: 1, bodyReads: 1, hashes: 1 }); - await reset(); - for (let i = 0; i < 16; i++) - expect((await ask(port, `/virtual?request=${i}`, "rules.test")).body).toBe(body); - expect(await costs()).toEqual({ - decodes: 0, - pathDecodes: 16, - bodyReads: 0, - bodyBytes: 0, - hashes: 0, - }); - await pushRules("rules.test", entries("refreshed")); - await reset(); - expect((await ask(port, "/virtual", "rules.test")).body).toBe("refreshed"); - expect(await costs()).toMatchObject({ decodes: 1, bodyReads: 1, hashes: 1 }); - await pushRules("rules.test", []); - await reset(); - expect((await ask(port, "/virtual", "rules.test")).body).not.toBe("refreshed"); - expect(await costs()).toEqual({ - decodes: 0, - pathDecodes: 0, - bodyReads: 0, - bodyBytes: 0, - hashes: 0, - }); - }); - - it("supports an OPTIONS response and leaves platform paths alone under a catch-all", async () => { - await pushRules("rules.test", [ - { - pathPrefix: "/virtual", - spec: { - response: normalizeEdgeResponse({ - status: 204, - methods: ["OPTIONS"], - headers: { "Access-Control-Allow-Origin": "https://client.test" }, - }), - }, - }, - ]); - const options = await ask(port, "/virtual", "rules.test", { method: "OPTIONS" }); - expect(options).toMatchObject({ status: 204, body: "" }); - expect(options.headers["access-control-allow-origin"]).toBe("https://client.test"); - await pushRules("rules.test", [ - { - pathPrefix: null, - spec: { response: normalizeEdgeResponse({ match: "prefix", body: "catch-all" }) }, - }, - ]); - expect((await ask(port, "/ordinary", "rules.test")).body).toBe("catch-all"); - for (const path of [ - "/_openship/hooks/probe", - "/.openship/auth", - "/.well-known/acme-challenge/probe", - "/ignored/../.openship/auth", - "//.openship/auth", - ]) { - expect((await ask(port, path, "rules.test")).body).not.toBe("catch-all"); - } - }); - it.each([ ["JSON null", null], ["omitted", undefined], diff --git a/apps/api/test/e2e/scaling-databases.e2e.test.ts b/apps/api/test/e2e/scaling-databases.e2e.test.ts index e607b9433..fe5b603f9 100644 --- a/apps/api/test/e2e/scaling-databases.e2e.test.ts +++ b/apps/api/test/e2e/scaling-databases.e2e.test.ts @@ -15,7 +15,6 @@ import { type KubernetesObject, } from "@repo/adapters"; import type { ClusterRuntimePlan, ClusterDatabaseConfig } from "@repo/core"; -import { SecretValues } from "@repo/core/diagnostics"; import type { ClusterDatabase } from "@repo/contracts"; import { DATABASE_IMAGES, @@ -442,47 +441,8 @@ done afterEach(async (context) => { console.info(`[database-e2e] ${context.task.result?.state}: ${context.task.name}`); - if (context.task.result?.state !== "fail") return; - console.error(await lab.diagnostics()); - // Pod readiness alone cannot explain an operator stalled during a resize. - // Keep its status and reconciliation errors, with the lab's secrets masked. - try { - const secrets = await lab.api.request<{ items: KubernetesObject[] }>( - "GET", - `/api/v1/secrets?labelSelector=${encodeURIComponent(`openship.io/runtime=${lab.runtimeId}`)}`, - ); - const redactor = new SecretValues( - secrets.items.flatMap((secret) => - Object.values(secret.data ?? {}).map((value) => - Buffer.from(String(value), "base64").toString(), - ), - ), - ); - for (const args of [ - ["get", "redisclusters", "-A", "-o", "yaml"], - ["get", "redisreplications,redissentinels", "-A", "-o", "yaml"], - ["logs", "-n", "ot-operators", "deployment/redis-operator", "--tail=200"], - ]) { - console.error(redactor.redact(await lab.nodeExec(0, ["kubectl", ...args]))); - } - const pods = await lab.api.request<{ items: KubernetesObject[] }>( - "GET", - `/api/v1/pods?labelSelector=${encodeURIComponent(`openship.io/runtime=${lab.runtimeId},redis_setup_type`)}`, - ); - for (const pod of pods.items) { - try { - console.error(redactor.redact(await lab.nodeExec(0, [ - "kubectl", "logs", "-n", pod.metadata.namespace!, pod.metadata.name!, - "--tail=100", "--request-timeout=8s", "--all-containers=true", "--prefix=true", - ], 12))); - } catch (error) { - console.error(redactor.redact(`Redis pod logs unavailable: ${String(error)}`)); - } - } - } catch (error) { - console.error("Database operator diagnostics unavailable:", String(error)); - } - }, 180000); + if (context.task.result?.state === "fail") console.error(await lab.diagnostics()); + }); afterAll(async () => { for (const index of paused) await resume(index).catch(() => {}); const { stopNetworkSetups } = diff --git a/apps/api/test/fixtures/oblien-capacity-catalog.json b/apps/api/test/fixtures/oblien-capacity-catalog.json index 78cf91b65..1e937f0cf 100644 --- a/apps/api/test/fixtures/oblien-capacity-catalog.json +++ b/apps/api/test/fixtures/oblien-capacity-catalog.json @@ -56,12 +56,12 @@ "vcpus": 0.5, "memoryMb": 512, "diskGb": 10, - "vms": 4 + "workspaces": 4 }, "monthlyAmount": 500, "paygCapAmount": 625, "resourceLimits": { - "max_vms": 4, + "max_workspaces": 4, "max_vcpus": 1, "max_ram_mb": 512, "max_disk_gb": 10, @@ -76,12 +76,12 @@ "vcpus": 1, "memoryMb": 1024, "diskGb": 20, - "vms": 8 + "workspaces": 8 }, "monthlyAmount": 800, "paygCapAmount": 1000, "resourceLimits": { - "max_vms": 8, + "max_workspaces": 8, "max_vcpus": 1, "max_ram_mb": 1024, "max_disk_gb": 20, @@ -96,12 +96,12 @@ "vcpus": 2, "memoryMb": 4096, "diskGb": 40, - "vms": 12 + "workspaces": 12 }, "monthlyAmount": 1800, "paygCapAmount": 2250, "resourceLimits": { - "max_vms": 12, + "max_workspaces": 12, "max_vcpus": 2, "max_ram_mb": 4096, "max_disk_gb": 40, @@ -116,12 +116,12 @@ "vcpus": 4, "memoryMb": 8192, "diskGb": 80, - "vms": 24 + "workspaces": 24 }, "monthlyAmount": 3600, "paygCapAmount": 4500, "resourceLimits": { - "max_vms": 24, + "max_workspaces": 24, "max_vcpus": 4, "max_ram_mb": 8192, "max_disk_gb": 80, diff --git a/apps/api/test/fixtures/upgrade/compose-0.9.11.yml b/apps/api/test/fixtures/upgrade/compose-0.9.11.yml deleted file mode 100644 index d9da40163..000000000 --- a/apps/api/test/fixtures/upgrade/compose-0.9.11.yml +++ /dev/null @@ -1,153 +0,0 @@ -# Frozen CLI template from v0.9.11:apps/cli/src/lib/compose.ts. -# Only test isolation (paths, images and container name) is applied at runtime. -# Managed by `openship up` — do not edit; re-run `openship up` to regenerate. -x-logging: &default-logging - driver: "json-file" - options: - max-size: "20m" - max-file: "3" - -services: - postgres: - image: postgres:16-alpine - restart: unless-stopped - logging: *default-logging - environment: - # Keep the data dir in a subdirectory of the volume so a fresh install never - # runs initdb against a bare mount root (which fails on quirky host - # filesystems with EPERM — #350). OPENSHIP_PGDATA is decided ONCE at install - # by the CLI (fresh → subdir, pre-existing volume → root) and preserved in - # .env, so this never moves an existing database. - PGDATA: ${OPENSHIP_PGDATA:-/var/lib/postgresql/data/pgdata} - POSTGRES_USER: ${POSTGRES_USER:-openship} - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?missing from .env — re-run openship up to regenerate it} - POSTGRES_DB: ${POSTGRES_DB:-openship} - expose: ["5432"] - volumes: [postgres_data:/var/lib/postgresql/data] - healthcheck: - test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-openship} -d ${POSTGRES_DB:-openship}"] - interval: 5s - timeout: 3s - retries: 12 - - redis: - image: redis:7-alpine - restart: unless-stopped - logging: *default-logging - command: ["redis-server", "--appendonly", "yes"] - expose: ["6379"] - volumes: [redis_data:/data] - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 5s - timeout: 3s - retries: 12 - - api: - image: ${OPENSHIP_IMAGE_REGISTRY:-ghcr.io/oblien}/openship-api:${OPENSHIP_VERSION:-latest} - restart: unless-stopped - logging: *default-logging - # Loopback by default — the host-net edge reaches it over loopback, so nothing - # sits on a public interface. OPENSHIP_BIND_ADDR opts into a public/LAN interface - # (set by `openship up` when a public URL is configured for off-box access). - ports: ["${OPENSHIP_BIND_ADDR:-127.0.0.1}:${API_PORT:-4000}:${API_PORT:-4000}"] - volumes: - # The daemon socket, at the path the api's own default expects INSIDE the - # container. The HOST side is a variable because it MOVES: a rootless daemon - # keeps its socket under the invoking user's runtime dir, and Docker creates a - # missing bind source as an empty DIRECTORY instead of failing — so the rootful - # path there brings the stack up and then fails every container operation in - # the transport, naming neither the path nor the cause (#482). `openship up` - # writes OPENSHIP_DOCKER_SOCKET when the detected path isn't this default. - - ${OPENSHIP_DOCKER_SOCKET:-/var/run/docker.sock}:/var/run/docker.sock - # Registry credentials for private-image pulls. The API talks to the daemon over - # the socket above via dockerode, which — unlike the docker CLI — reads no - # config.json of its own, so a private pull went out anonymous on a logged-in - # host (#581). Mounted READ-ONLY and only into this service; absent entirely when - # the host has no config, so nothing is invented. Substituted at write time (the - # path depends on DOCKER_CONFIG and on the file existing), hence the marker. - # Routing state shared with the edge, as HOST BIND MOUNTS (generated from - # EDGE_CONTAINER_MOUNTS): the vhost tree, /etc/letsencrypt, the ACME webroot - # and the static doc-roots the API writes and the edge serves. Named volumes - # hid all of it from every host-side reader (migrate's proxy scan, cert carry, - # cert reuse, mail cert symlinks), each of which then silently saw "nothing". - - /private/var/lib/openship/edge/sites-enabled:/usr/local/openresty/nginx/conf/sites-enabled:z - - /private/etc/letsencrypt:/etc/letsencrypt:z - - /private/var/lib/openship/edge/acme:/var/www/acme:z - - /opt/openship/static:/opt/openship/static:z - # Host-op SSH key (createHostExecutor → host.docker.internal). /dev/null - # when the host channel isn't provisioned → OPENSHIP_HOST_SSH_HOST stays - # unset, and host operations REFUSE (they'd otherwise run against this - # container's filesystem, #509) while ordinary deploys keep working over - # the socket below. - - ${OPENSHIP_HOST_KEY_PATH:-/dev/null}:/run/secrets/openship_host_key:ro - # `host-gateway` is resolved by the daemon and is right on a stock rootful - # install. It is NOT universally right: under rootless Docker it lands in - # RootlessKit's namespace rather than the host's, so the host's sshd isn't - # there (#482). OPENSHIP_HOST_GATEWAY re-points the alias (e.g. at the box's - # LAN address) without patching this file, which `openship up` rewrites. - extra_hosts: ["host.docker.internal:${OPENSHIP_HOST_GATEWAY:-host-gateway}"] - env_file: [.env] - environment: - NODE_ENV: production - PORT: "${API_PORT:-4000}" - DATABASE_URL: postgresql://${POSTGRES_USER:-openship}:${POSTGRES_PASSWORD:?missing from .env — re-run openship up to regenerate it}@postgres:5432/${POSTGRES_DB:-openship} - REDIS_URL: redis://redis:6379 - OPENSHIP_EDGE_MODE: docker - OPENSHIP_EDGE_CONTAINER: openship-edge - depends_on: - postgres: { condition: service_healthy } - redis: { condition: service_healthy } - healthcheck: - test: ["CMD-SHELL", "node -e \"fetch('http://127.0.0.1:${API_PORT:-4000}/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))\""] - interval: 10s - timeout: 5s - retries: 12 - start_period: 40s - - dashboard: - image: ${OPENSHIP_IMAGE_REGISTRY:-ghcr.io/oblien}/openship-dashboard:${OPENSHIP_VERSION:-latest} - restart: unless-stopped - logging: *default-logging - # Loopback by default (see api note); OPENSHIP_BIND_ADDR opts into a public interface. - ports: ["${OPENSHIP_BIND_ADDR:-127.0.0.1}:${DASHBOARD_PORT:-3001}:${DASHBOARD_PORT:-3001}"] - env_file: [.env] - environment: - NODE_ENV: production - PORT: "${DASHBOARD_PORT:-3001}" - HOSTNAME: "0.0.0.0" - INTERNAL_API_URL: http://api:${API_PORT:-4000} - depends_on: - api: { condition: service_healthy } - healthcheck: - test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:'+process.env.PORT+'/',{redirect:'manual'}).then(r=>process.exit(r.status<500?0:1)).catch(()=>process.exit(1))"] - interval: 5s - timeout: 5s - retries: 24 - start_period: 20s - - edge: - image: ${OPENSHIP_IMAGE_REGISTRY:-ghcr.io/oblien}/openship-edge:${OPENSHIP_VERSION:-latest} - # PINNED, and it must stay pinned: the api reaches the edge by NAME through - # DockerEdgeExecutor (OPENSHIP_EDGE_CONTAINER above), and "ours" edge - # detection greps `docker ps --filter name=openship-edge`. Without this, - # compose derives `-edge-1` from the directory and every - # `docker exec` into the edge fails with "No such container: openship-edge" — - # which silently migrated 0 sites after the operator's proxy was stopped. - # Safe here: the edge is a singleton (host networking, one per box). - container_name: openship-edge - restart: unless-stopped - logging: *default-logging - network_mode: host - depends_on: - api: { condition: service_healthy } - dashboard: { condition: service_healthy } - volumes: - - /private/var/lib/openship/edge/sites-enabled:/usr/local/openresty/nginx/conf/sites-enabled:z - - /private/etc/letsencrypt:/etc/letsencrypt:z - - /private/var/lib/openship/edge/acme:/var/www/acme:z - - /opt/openship/static:/opt/openship/static:z - -volumes: - postgres_data: - redis_data: diff --git a/apps/api/test/fixtures/upgrade/compose-0.9.12.yml b/apps/api/test/fixtures/upgrade/compose-0.9.12.yml deleted file mode 100644 index b0989b980..000000000 --- a/apps/api/test/fixtures/upgrade/compose-0.9.12.yml +++ /dev/null @@ -1,153 +0,0 @@ -# Frozen CLI template from v0.9.12:apps/cli/src/lib/compose.ts. -# Only test isolation (paths, images and container name) is applied at runtime. -# Managed by `openship up` — do not edit; re-run `openship up` to regenerate. -x-logging: &default-logging - driver: "json-file" - options: - max-size: "20m" - max-file: "3" - -services: - postgres: - image: postgres:16-alpine - restart: unless-stopped - logging: *default-logging - environment: - # Keep the data dir in a subdirectory of the volume so a fresh install never - # runs initdb against a bare mount root (which fails on quirky host - # filesystems with EPERM — #350). OPENSHIP_PGDATA is decided ONCE at install - # by the CLI (fresh → subdir, pre-existing volume → root) and preserved in - # .env, so this never moves an existing database. - PGDATA: ${OPENSHIP_PGDATA:-/var/lib/postgresql/data/pgdata} - POSTGRES_USER: ${POSTGRES_USER:-openship} - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?missing from .env — re-run openship up to regenerate it} - POSTGRES_DB: ${POSTGRES_DB:-openship} - expose: ["5432"] - volumes: [postgres_data:/var/lib/postgresql/data] - healthcheck: - test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-openship} -d ${POSTGRES_DB:-openship}"] - interval: 5s - timeout: 3s - retries: 12 - - redis: - image: redis:7-alpine - restart: unless-stopped - logging: *default-logging - command: ["redis-server", "--appendonly", "yes"] - expose: ["6379"] - volumes: [redis_data:/data] - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 5s - timeout: 3s - retries: 12 - - api: - image: ${OPENSHIP_IMAGE_REGISTRY:-ghcr.io/oblien}/openship-api:${OPENSHIP_VERSION:-latest} - restart: unless-stopped - logging: *default-logging - # Loopback by default — the host-net edge reaches it over loopback, so nothing - # sits on a public interface. OPENSHIP_BIND_ADDR opts into a public/LAN interface - # (set by `openship up` when a public URL is configured for off-box access). - ports: ["${OPENSHIP_BIND_ADDR:-127.0.0.1}:${API_PORT:-4000}:${API_PORT:-4000}"] - volumes: - # The daemon socket, at the path the api's own default expects INSIDE the - # container. The HOST side is a variable because it MOVES: a rootless daemon - # keeps its socket under the invoking user's runtime dir, and Docker creates a - # missing bind source as an empty DIRECTORY instead of failing — so the rootful - # path there brings the stack up and then fails every container operation in - # the transport, naming neither the path nor the cause (#482). `openship up` - # writes OPENSHIP_DOCKER_SOCKET when the detected path isn't this default. - - ${OPENSHIP_DOCKER_SOCKET:-/var/run/docker.sock}:/var/run/docker.sock - # Registry credentials for private-image pulls. The API talks to the daemon over - # the socket above via dockerode, which — unlike the docker CLI — reads no - # config.json of its own, so a private pull went out anonymous on a logged-in - # host (#581). Mounted READ-ONLY and only into this service; absent entirely when - # the host has no config, so nothing is invented. Substituted at write time (the - # path depends on DOCKER_CONFIG and on the file existing), hence the marker. - # Routing state shared with the edge, as HOST BIND MOUNTS (generated from - # EDGE_CONTAINER_MOUNTS): the vhost tree, /etc/letsencrypt, the ACME webroot - # and the static doc-roots the API writes and the edge serves. Named volumes - # hid all of it from every host-side reader (migrate's proxy scan, cert carry, - # cert reuse, mail cert symlinks), each of which then silently saw "nothing". - - /private/var/lib/openship/edge/sites-enabled:/usr/local/openresty/nginx/conf/sites-enabled:z - - /private/etc/letsencrypt:/etc/letsencrypt:z - - /private/var/lib/openship/edge/acme:/var/www/acme:z - - /opt/openship/static:/opt/openship/static:z - # Host-op SSH key (createHostExecutor → host.docker.internal). /dev/null - # when the host channel isn't provisioned → OPENSHIP_HOST_SSH_HOST stays - # unset, and host operations REFUSE (they'd otherwise run against this - # container's filesystem, #509) while ordinary deploys keep working over - # the socket below. - - ${OPENSHIP_HOST_KEY_PATH:-/dev/null}:/run/secrets/openship_host_key:ro - # `host-gateway` is resolved by the daemon and is right on a stock rootful - # install. It is NOT universally right: under rootless Docker it lands in - # RootlessKit's namespace rather than the host's, so the host's sshd isn't - # there (#482). OPENSHIP_HOST_GATEWAY re-points the alias (e.g. at the box's - # LAN address) without patching this file, which `openship up` rewrites. - extra_hosts: ["host.docker.internal:${OPENSHIP_HOST_GATEWAY:-host-gateway}"] - env_file: [.env] - environment: - NODE_ENV: production - PORT: "${API_PORT:-4000}" - DATABASE_URL: postgresql://${POSTGRES_USER:-openship}:${POSTGRES_PASSWORD:?missing from .env — re-run openship up to regenerate it}@postgres:5432/${POSTGRES_DB:-openship} - REDIS_URL: redis://redis:6379 - OPENSHIP_EDGE_MODE: docker - OPENSHIP_EDGE_CONTAINER: openship-edge - depends_on: - postgres: { condition: service_healthy } - redis: { condition: service_healthy } - healthcheck: - test: ["CMD-SHELL", "node -e \"fetch('http://127.0.0.1:${API_PORT:-4000}/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))\""] - interval: 10s - timeout: 5s - retries: 12 - start_period: 40s - - dashboard: - image: ${OPENSHIP_IMAGE_REGISTRY:-ghcr.io/oblien}/openship-dashboard:${OPENSHIP_VERSION:-latest} - restart: unless-stopped - logging: *default-logging - # Loopback by default (see api note); OPENSHIP_BIND_ADDR opts into a public interface. - ports: ["${OPENSHIP_BIND_ADDR:-127.0.0.1}:${DASHBOARD_PORT:-3001}:${DASHBOARD_PORT:-3001}"] - env_file: [.env] - environment: - NODE_ENV: production - PORT: "${DASHBOARD_PORT:-3001}" - HOSTNAME: "0.0.0.0" - INTERNAL_API_URL: http://api:${API_PORT:-4000} - depends_on: - api: { condition: service_healthy } - healthcheck: - test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:'+process.env.PORT+'/',{redirect:'manual'}).then(r=>process.exit(r.status<500?0:1)).catch(()=>process.exit(1))"] - interval: 5s - timeout: 5s - retries: 24 - start_period: 20s - - edge: - image: ${OPENSHIP_IMAGE_REGISTRY:-ghcr.io/oblien}/openship-edge:${OPENSHIP_VERSION:-latest} - # PINNED, and it must stay pinned: the api reaches the edge by NAME through - # DockerEdgeExecutor (OPENSHIP_EDGE_CONTAINER above), and "ours" edge - # detection greps `docker ps --filter name=openship-edge`. Without this, - # compose derives `-edge-1` from the directory and every - # `docker exec` into the edge fails with "No such container: openship-edge" — - # which silently migrated 0 sites after the operator's proxy was stopped. - # Safe here: the edge is a singleton (host networking, one per box). - container_name: openship-edge - restart: unless-stopped - logging: *default-logging - network_mode: host - depends_on: - api: { condition: service_healthy } - dashboard: { condition: service_healthy } - volumes: - - /private/var/lib/openship/edge/sites-enabled:/usr/local/openresty/nginx/conf/sites-enabled:z - - /private/etc/letsencrypt:/etc/letsencrypt:z - - /private/var/lib/openship/edge/acme:/var/www/acme:z - - /opt/openship/static:/opt/openship/static:z - -volumes: - postgres_data: - redis_data: diff --git a/apps/api/test/fixtures/upgrade/compose-1.0.0.yml b/apps/api/test/fixtures/upgrade/compose-1.0.0.yml deleted file mode 100644 index 4b7b8beb0..000000000 --- a/apps/api/test/fixtures/upgrade/compose-1.0.0.yml +++ /dev/null @@ -1,153 +0,0 @@ -# Frozen CLI template from v1.0.0:apps/cli/src/lib/compose.ts. -# Only test isolation (paths, images and container name) is applied at runtime. -# Managed by `openship up` — do not edit; re-run `openship up` to regenerate. -x-logging: &default-logging - driver: "json-file" - options: - max-size: "20m" - max-file: "3" - -services: - postgres: - image: postgres:16-alpine - restart: unless-stopped - logging: *default-logging - environment: - # Keep the data dir in a subdirectory of the volume so a fresh install never - # runs initdb against a bare mount root (which fails on quirky host - # filesystems with EPERM — #350). OPENSHIP_PGDATA is decided ONCE at install - # by the CLI (fresh → subdir, pre-existing volume → root) and preserved in - # .env, so this never moves an existing database. - PGDATA: ${OPENSHIP_PGDATA:-/var/lib/postgresql/data/pgdata} - POSTGRES_USER: ${POSTGRES_USER:-openship} - POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?missing from .env — re-run openship up to regenerate it} - POSTGRES_DB: ${POSTGRES_DB:-openship} - expose: ["5432"] - volumes: [postgres_data:/var/lib/postgresql/data] - healthcheck: - test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER:-openship} -d ${POSTGRES_DB:-openship}"] - interval: 5s - timeout: 3s - retries: 12 - - redis: - image: redis:7-alpine - restart: unless-stopped - logging: *default-logging - command: ["redis-server", "--appendonly", "yes"] - expose: ["6379"] - volumes: [redis_data:/data] - healthcheck: - test: ["CMD", "redis-cli", "ping"] - interval: 5s - timeout: 3s - retries: 12 - - api: - image: ${OPENSHIP_IMAGE_REGISTRY:-ghcr.io/oblien}/openship-api:${OPENSHIP_VERSION:-latest} - restart: unless-stopped - logging: *default-logging - # Loopback by default — the host-net edge reaches it over loopback, so nothing - # sits on a public interface. OPENSHIP_BIND_ADDR opts into a public/LAN interface - # (set by `openship up` when a public URL is configured for off-box access). - ports: ["${OPENSHIP_BIND_ADDR:-127.0.0.1}:${API_PORT:-4000}:${API_PORT:-4000}"] - volumes: - # The daemon socket, at the path the api's own default expects INSIDE the - # container. The HOST side is a variable because it MOVES: a rootless daemon - # keeps its socket under the invoking user's runtime dir, and Docker creates a - # missing bind source as an empty DIRECTORY instead of failing — so the rootful - # path there brings the stack up and then fails every container operation in - # the transport, naming neither the path nor the cause (#482). `openship up` - # writes OPENSHIP_DOCKER_SOCKET when the detected path isn't this default. - - ${OPENSHIP_DOCKER_SOCKET:-/var/run/docker.sock}:/var/run/docker.sock - # Registry credentials for private-image pulls. The API talks to the daemon over - # the socket above via dockerode, which — unlike the docker CLI — reads no - # config.json of its own, so a private pull went out anonymous on a logged-in - # host (#581). Mounted READ-ONLY and only into this service; absent entirely when - # the host has no config, so nothing is invented. Substituted at write time (the - # path depends on DOCKER_CONFIG and on the file existing), hence the marker. - # Routing state shared with the edge, as HOST BIND MOUNTS (generated from - # EDGE_CONTAINER_MOUNTS): the vhost tree, /etc/letsencrypt, the ACME webroot - # and the static doc-roots the API writes and the edge serves. Named volumes - # hid all of it from every host-side reader (migrate's proxy scan, cert carry, - # cert reuse, mail cert symlinks), each of which then silently saw "nothing". - - /var/lib/openship/edge/sites-enabled:/usr/local/openresty/nginx/conf/sites-enabled:z - - /etc/letsencrypt:/etc/letsencrypt:z - - /var/lib/openship/edge/acme:/var/www/acme:z - - /opt/openship/static:/opt/openship/static:z - # Host-op SSH key (createHostExecutor → host.docker.internal). /dev/null - # when the host channel isn't provisioned → OPENSHIP_HOST_SSH_HOST stays - # unset, and host operations REFUSE (they'd otherwise run against this - # container's filesystem, #509) while ordinary deploys keep working over - # the socket below. - - ${OPENSHIP_HOST_KEY_PATH:-/dev/null}:/run/secrets/openship_host_key:ro - # `host-gateway` is resolved by the daemon and is right on a stock rootful - # install. It is NOT universally right: under rootless Docker it lands in - # RootlessKit's namespace rather than the host's, so the host's sshd isn't - # there (#482). OPENSHIP_HOST_GATEWAY re-points the alias (e.g. at the box's - # LAN address) without patching this file, which `openship up` rewrites. - extra_hosts: ["host.docker.internal:${OPENSHIP_HOST_GATEWAY:-host-gateway}"] - env_file: [.env] - environment: - NODE_ENV: production - PORT: "${API_PORT:-4000}" - DATABASE_URL: postgresql://${POSTGRES_USER:-openship}:${POSTGRES_PASSWORD:?missing from .env — re-run openship up to regenerate it}@postgres:5432/${POSTGRES_DB:-openship} - REDIS_URL: redis://redis:6379 - OPENSHIP_EDGE_MODE: docker - OPENSHIP_EDGE_CONTAINER: openship-edge - depends_on: - postgres: { condition: service_healthy } - redis: { condition: service_healthy } - healthcheck: - test: ["CMD-SHELL", "node -e \"fetch('http://127.0.0.1:${API_PORT:-4000}/api/health').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))\""] - interval: 10s - timeout: 5s - retries: 12 - start_period: 40s - - dashboard: - image: ${OPENSHIP_IMAGE_REGISTRY:-ghcr.io/oblien}/openship-dashboard:${OPENSHIP_VERSION:-latest} - restart: unless-stopped - logging: *default-logging - # Loopback by default (see api note); OPENSHIP_BIND_ADDR opts into a public interface. - ports: ["${OPENSHIP_BIND_ADDR:-127.0.0.1}:${DASHBOARD_PORT:-3001}:${DASHBOARD_PORT:-3001}"] - env_file: [.env] - environment: - NODE_ENV: production - PORT: "${DASHBOARD_PORT:-3001}" - HOSTNAME: "0.0.0.0" - INTERNAL_API_URL: http://api:${API_PORT:-4000} - depends_on: - api: { condition: service_healthy } - healthcheck: - test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:'+process.env.PORT+'/',{redirect:'manual'}).then(r=>process.exit(r.status<500?0:1)).catch(()=>process.exit(1))"] - interval: 5s - timeout: 5s - retries: 24 - start_period: 20s - - edge: - image: ${OPENSHIP_IMAGE_REGISTRY:-ghcr.io/oblien}/openship-edge:${OPENSHIP_VERSION:-latest} - # PINNED, and it must stay pinned: the api reaches the edge by NAME through - # DockerEdgeExecutor (OPENSHIP_EDGE_CONTAINER above), and "ours" edge - # detection greps `docker ps --filter name=openship-edge`. Without this, - # compose derives `-edge-1` from the directory and every - # `docker exec` into the edge fails with "No such container: openship-edge" — - # which silently migrated 0 sites after the operator's proxy was stopped. - # Safe here: the edge is a singleton (host networking, one per box). - container_name: openship-edge - restart: unless-stopped - logging: *default-logging - network_mode: host - depends_on: - api: { condition: service_healthy } - dashboard: { condition: service_healthy } - volumes: - - /var/lib/openship/edge/sites-enabled:/usr/local/openresty/nginx/conf/sites-enabled:z - - /etc/letsencrypt:/etc/letsencrypt:z - - /var/lib/openship/edge/acme:/var/www/acme:z - - /opt/openship/static:/opt/openship/static:z - -volumes: - postgres_data: - redis_data: diff --git a/apps/api/test/helpers/monthly-cloud-offer.ts b/apps/api/test/helpers/monthly-cloud-offer.ts index e55e44596..b95c4cb7c 100644 --- a/apps/api/test/helpers/monthly-cloud-offer.ts +++ b/apps/api/test/helpers/monthly-cloud-offer.ts @@ -1,6 +1,6 @@ import type { OblienEntitlement, OblienSubscription } from "@repo/platform/engine/lib/oblien-billing-api"; -/** OpenShip saved v9 terms, independent of today's catalog and provider wire names. */ +/** Saved v9 terms and the SDK 2.8 capacity shape, independent of today's catalog. */ export function monthlyCloudBilling(organizationId = "org_1", namespace = "os-customer") { const periodStart = "2026-10-01T00:00:00Z"; const periodEnd = "2026-11-01T00:00:00Z"; diff --git a/apps/api/test/helpers/oblien-vm-billing.ts b/apps/api/test/helpers/oblien-vm-billing.ts deleted file mode 100644 index 9f8ea75f9..000000000 --- a/apps/api/test/helpers/oblien-vm-billing.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** Build provider HTTP fixtures from OpenShip's saved billing model. This helper - * is only for fixture construction; production must read native SDK 3 payloads. - * Customer metadata and other opaque dictionaries are deliberately untouched. */ -export function providerBillingFixture(value: unknown): unknown { - if (!value || typeof value !== "object" || Array.isArray(value)) return value; - const source = value as Record; - const native = { ...source }; - if ("vcpus" in source && "memoryMb" in source && "diskGb" in source && "workspaces" in source) { - native.vms = source.workspaces; - delete native.workspaces; - } - if (source.resourceLimits && typeof source.resourceLimits === "object") { - const limits = { ...(source.resourceLimits as Record) }; - if ("max_workspaces" in limits) { - limits.max_vms = limits.max_workspaces; - delete limits.max_workspaces; - } - native.resourceLimits = limits; - } - if (source.onOverdraftAction === "stop_workspaces") native.onOverdraftAction = "stop_vms"; - if (source.service === "workspace_vm") native.service = "vm_compute"; - for (const key of [ - "data", - "capacity", - "quote", - "current", - "next", - "subscription", - "offer", - "policy", - "pendingChange", - "change", - "pendingCheckout", - "checkout", - ]) - if (source[key] && typeof source[key] === "object") - native[key] = providerBillingFixture(source[key]); - if (Array.isArray(source.presets)) native.presets = source.presets.map(providerBillingFixture); - return native; -} diff --git a/apps/api/test/lib/cloud-capacity.test.ts b/apps/api/test/lib/cloud-capacity.test.ts index 621c3145c..4be698883 100644 --- a/apps/api/test/lib/cloud-capacity.test.ts +++ b/apps/api/test/lib/cloud-capacity.test.ts @@ -20,7 +20,7 @@ vi.mock("@repo/db", () => ({ })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ getOblienClient: () => ({ - vms: { get: h.workspace }, + workspaces: { get: h.workspace }, namespaces: { get: h.namespace }, }), })); diff --git a/apps/api/test/lib/cloud-docker-workspace.test.ts b/apps/api/test/lib/cloud-docker-workspace.test.ts index 9e4d1f18b..b2c2cf0cf 100644 --- a/apps/api/test/lib/cloud-docker-workspace.test.ts +++ b/apps/api/test/lib/cloud-docker-workspace.test.ts @@ -30,8 +30,8 @@ vi.mock("@repo/adapters", async (original) => ({ ...await original(), Oblien: class { constructor(credentials: unknown) { h.credentials.push(credentials); } - vms = { create: h.create, retryCreation: h.retry, get: h.get, list: h.list }; - vm = (id: string) => ({ id, get: h.get, start: h.start, resume: h.resume, + workspaces = { create: h.create, retryCreation: h.retry, get: h.get, list: h.list }; + workspace = (id: string) => ({ id, get: h.get, start: h.start, resume: h.resume, lifecycle: { makePermanent: h.permanent }, resources: { update: h.resize }, runtime: async () => ({ exec: { run: h.exec } }), invalidateRuntime: h.invalidate }); }, @@ -86,7 +86,7 @@ beforeEach(() => { return { success: true, relaunched: true }; }); h.inFlight.mockResolvedValue([]); - h.list.mockResolvedValue({ vms: [], total: 0, limit: 100, page: 1 }); + h.list.mockResolvedValue({ workspaces: [], total: 0, limit: 100, page: 1 }); h.discard.mockImplementation(async () => { binding = undefined; }); @@ -190,7 +190,7 @@ describe("Subscribed Cloud server provisioning and retry", () => { it("adopts an earlier workspace discovered after a quota refusal instead of creating another", async () => { binding = { ...input, namespace: "namespace-a", provisionKey: "legacy-key", workspaceId: null, state: "provisioning" }; h.create.mockRejectedValue(Object.assign(new Error("namespace workspace limit"), { status: 409, code: "NAMESPACE_LIMIT_REACHED" })); - h.list.mockResolvedValue({ vms: [await h.get()], total: 1, limit: 100, page: 1 }); + h.list.mockResolvedValue({ workspaces: [await h.get()], total: 1, limit: 100, page: 1 }); await expect(ensureCloudDockerWorkspace(input)).resolves.toEqual({ projectId: project.id, workspaceId: "workspace-a", ownerWorkspaceId: "owner-a" }); expect(h.create).toHaveBeenCalledOnce(); expect(h.discard).not.toHaveBeenCalled(); @@ -209,8 +209,8 @@ describe("Subscribed Cloud server provisioning and retry", () => { binding = { ...input, namespace: "namespace-a", provisionKey: "legacy-key", workspaceId: null, state: "provisioning" }; h.create.mockRejectedValue(Object.assign(new Error("namespace workspace limit"), { status: 409, code: "NAMESPACE_LIMIT_REACHED" })); const workspace = await h.get(); - h.list.mockResolvedValueOnce({ vms: [{ ...workspace, namespace: "other-namespace", id: "foreign-vm" }], total: 2, limit: 1, page: 1 }); - h.list.mockResolvedValueOnce({ vms: [workspace], total: 2, limit: 1, page: 2 }); + h.list.mockResolvedValueOnce({ workspaces: [{ ...workspace, namespace: "other-namespace", id: "foreign-vm" }], total: 2, limit: 1, page: 1 }); + h.list.mockResolvedValueOnce({ workspaces: [workspace], total: 2, limit: 1, page: 2 }); await expect(ensureCloudDockerWorkspace(input)).resolves.toMatchObject({ workspaceId: "workspace-a" }); expect(h.list).toHaveBeenNthCalledWith(2, { page: 2, limit: 100 }); expect(h.attach).toHaveBeenCalledExactlyOnceWith(ownerRef, project.organizationId, "namespace-a", "workspace-a"); @@ -219,7 +219,7 @@ describe("Subscribed Cloud server provisioning and retry", () => { binding = { ...input, namespace: "namespace-a", provisionKey: "legacy-key", workspaceId: null, state: "provisioning" }; h.create.mockRejectedValue(Object.assign(new Error("namespace workspace limit"), { status: 409, code: "NAMESPACE_LIMIT_REACHED" })); const workspace = await h.get(); - h.list.mockResolvedValue({ vms: [workspace, { ...workspace, id: "duplicate-vm" }], total: 2, limit: 100, page: 1 }); + h.list.mockResolvedValue({ workspaces: [workspace, { ...workspace, id: "duplicate-vm" }], total: 2, limit: 100, page: 1 }); await expect(ensureCloudDockerWorkspace(input)).rejects.toThrow("Multiple Cloud servers"); expect(h.attach).not.toHaveBeenCalled(); expect(h.discard).not.toHaveBeenCalled(); @@ -288,7 +288,7 @@ describe("Subscribed Cloud server provisioning and retry", () => { const error = Object.assign(new Error("initial provisioning failed"), { status: 422, code: "CREATE_FAILED", - details: { vm_id: "workspace-a" }, + details: { workspace_id: "workspace-a" }, }); h.create.mockRejectedValueOnce(error); await expect(ensureCloudDockerWorkspace(input)).rejects.toBe(error); @@ -328,7 +328,7 @@ describe("Subscribed Cloud server provisioning and retry", () => { h.create.mockRejectedValueOnce( Object.assign(new Error("creation failed"), { status: 422, - details: { vm_id: "workspace-a" }, + details: { workspace_id: "workspace-a" }, }), ); const created = await h.get(); diff --git a/apps/api/test/lib/cloud-namespace-token-reuse.test.ts b/apps/api/test/lib/cloud-namespace-token-reuse.test.ts index f5623dd04..c27c36e3b 100644 --- a/apps/api/test/lib/cloud-namespace-token-reuse.test.ts +++ b/apps/api/test/lib/cloud-namespace-token-reuse.test.ts @@ -98,7 +98,7 @@ it("renews expiring credentials once across concurrent clients", async () => { ]); vi.setSystemTime(Date.now() + 1741_000); await Promise.all( - clients.map(({ client }) => client._http.request({ method: "GET", path: "/vms" })), + clients.map(({ client }) => client._http.request({ method: "GET", path: "/workspace" })), ); expect(h.mint).toHaveBeenCalledTimes(2); expect(fetcher.mock.calls).toHaveLength(2); @@ -111,12 +111,12 @@ it("evicts rejected credentials without replaying a mutation", async () => { .mockImplementation(async () => Response.json({ success: true })); vi.stubGlobal("fetch", fetcher); const { client } = await getNamespaceClient("org", "space"); - await expect(client._http.request({ method: "POST", path: "/vms" })).rejects.toMatchObject({ + await expect(client._http.request({ method: "POST", path: "/workspace" })).rejects.toMatchObject({ status: 401, }); expect(fetcher).toHaveBeenCalledTimes(1); const next = await getNamespaceClient("org", "space"); - await next.client._http.request({ method: "GET", path: "/vms" }); + await next.client._http.request({ method: "GET", path: "/workspace" }); expect(h.mint).toHaveBeenCalledTimes(2); expect(new Headers(fetcher.mock.calls[1]![1].headers).get("authorization")).toBe( "Bearer token-2", @@ -171,9 +171,9 @@ it("does not evict a renewed token when an older request returns a late 401", as .mockImplementation(async () => Response.json({ success: true })); vi.stubGlobal("fetch", fetcher); const { client } = await getNamespaceClient("org", "space"); - const old = client._http.request({ method: "POST", path: "/vms" }).catch((error) => error); + const old = client._http.request({ method: "POST", path: "/workspace" }).catch((error) => error); vi.setSystemTime(Date.now() + 1741_000); - await client._http.request({ method: "GET", path: "/vms" }); + await client._http.request({ method: "GET", path: "/workspace" }); rejectOld(Response.json({ code: "token_revoked" }, { status: 401 })); expect(await old).toMatchObject({ status: 401 }); await getNamespaceClient("org", "space"); diff --git a/apps/api/test/lib/cloud-preflight.test.ts b/apps/api/test/lib/cloud-preflight.test.ts index 2051f666a..e419c3712 100644 --- a/apps/api/test/lib/cloud-preflight.test.ts +++ b/apps/api/test/lib/cloud-preflight.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const h = vi.hoisted(() => ({ token: vi.fn(), routes: vi.fn(), checkSlug: vi.fn(), verify: vi.fn(), scopedVerify: vi.fn(), spend: vi.fn(), createPlatform: vi.fn(), quota: vi.fn() })); -vi.mock("@repo/adapters", async original => ({ ...await original(), createPlatform: h.createPlatform })); +vi.mock("@repo/adapters", () => ({ createPlatform: h.createPlatform })); vi.mock("@repo/platform/engine/config/env", () => ({ env: { OBLIEN_API_URL: "https://api.oblien.com" } })); vi.mock("@repo/platform/engine/lib/routing-domains", () => ({ getRoutingBaseDomain: () => "opsh.io" })); vi.mock("@repo/platform/engine/lib/openship-cloud", () => ({ diff --git a/apps/api/test/lib/cloud-resource-limits.test.ts b/apps/api/test/lib/cloud-resource-limits.test.ts index 69433a654..a25adc3c9 100644 --- a/apps/api/test/lib/cloud-resource-limits.test.ts +++ b/apps/api/test/lib/cloud-resource-limits.test.ts @@ -2,9 +2,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const h = vi.hoisted(() => ({ quota: vi.fn(), get: vi.fn(), update: vi.fn() })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ - getOblienClient: () => ({ vms: { getQuota: h.quota }, namespaces: { get: h.get, update: h.update } }), + getOblienClient: () => ({ workspaces: { getQuota: h.quota }, namespaces: { get: h.get, update: h.update } }), })); -import { toOblienVmLimits } from "@repo/adapters"; import { cloudNamespaceLimits, initialCloudNamespaceLimits, readCloudCapacity, readCloudCapacityPool, syncCloudResourceLimits } from "@repo/platform/engine/lib/cloud-resource-limits"; beforeEach(() => { @@ -12,15 +11,15 @@ beforeEach(() => { h.quota.mockImplementation(() => { throw new Error("Openship must not calculate provider capacity"); }); h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: null } }); h.update.mockImplementation(async (_id, input) => ({ data: { id: "ns-a", slug: "tenant-a", ...input, - effective_resource_limits: { max_vms: 52, max_vcpus: 32, max_ram_mb: 65536, max_disk_gb: 1024 }, + effective_resource_limits: { max_workspaces: 52, max_vcpus: 32, max_ram_mb: 65536, max_disk_gb: 1024 }, } })); }); describe("Oblien-owned namespace capacity", () => { it("displays provider allocations in their real units without using credit balances or owner limits", async () => { h.get.mockResolvedValue({ success: true, data: { slug: "tenant-a", - effective_resource_limits: toOblienVmLimits(cloudNamespaceLimits("pro")), - allocated_resource_usage: { vms: 3, vcpus: 2.5, ram_mb: 4096, disk_gb: 48.5, pending_updates: 1 }, + effective_resource_limits: cloudNamespaceLimits("pro"), + allocated_resource_usage: { workspaces: 3, vcpus: 2.5, ram_mb: 4096, disk_gb: 48.5, pending_updates: 1 }, } }); expect(await readCloudCapacity("tenant-a")).toEqual({ workspaces: { used: 3, max: 1 }, vcpus: { used: 2.5, max: 4 }, ramMb: { used: 4096, max: 16384 }, diskGb: { used: 48.5, max: 250 } }); @@ -37,8 +36,8 @@ describe("Oblien-owned namespace capacity", () => { }); it("converts disk to MB for admission without confusing zero and unlimited", async () => { h.get.mockResolvedValue({ success: true, data: { slug: "tenant-a", - effective_resource_limits: { max_vms: null, max_total_vcpus: 0, max_total_ram_mb: 8192, max_total_disk_gb: 16 }, - allocated_resource_usage: { vms: 0, vcpus: 0, ram_mb: 0, disk_gb: 1.25, pending_updates: 0 }, + effective_resource_limits: { max_workspaces: null, max_total_vcpus: 0, max_total_ram_mb: 8192, max_total_disk_gb: 16 }, + allocated_resource_usage: { workspaces: 0, vcpus: 0, ram_mb: 0, disk_gb: 1.25, pending_updates: 0 }, } }); expect(await readCloudCapacityPool("tenant-a")).toEqual({ workspaces: { used: 0, max: null }, cpuCores: { used: 0, max: 0 }, memoryMb: { used: 0, max: 8192 }, diskMb: { used: 1280, max: 16384 } }); @@ -51,37 +50,37 @@ describe("Oblien-owned namespace capacity", () => { }); it("declares finite retail VM and aggregate caps without reading enterprise owner capacity", async () => { expect(cloudNamespaceLimits("team")).toEqual({ max_workspaces: 1, max_vcpus: 8, max_ram_mb: 32768, max_disk_gb: 600, max_total_vcpus: 8, max_total_ram_mb: 32768, max_total_disk_gb: 600 }); - await expect(initialCloudNamespaceLimits()).resolves.toEqual({ max_vms: 0, max_vcpus: 1, max_ram_mb: 1024, max_disk_gb: 8, max_total_vcpus: 0, max_total_ram_mb: 0, max_total_disk_gb: 0 }); + await expect(initialCloudNamespaceLimits()).resolves.toEqual({ max_workspaces: 0, max_vcpus: 1, max_ram_mb: 1024, max_disk_gb: 8, max_total_vcpus: 0, max_total_ram_mb: 0, max_total_disk_gb: 0 }); await syncCloudResourceLimits("tenant-a", "team"); - expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: toOblienVmLimits(cloudNamespaceLimits("team")) }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: cloudNamespaceLimits("team") }); expect(h.quota).not.toHaveBeenCalled(); }); - it("preserves an older saved offer when sending VM limits and accepts Oblien's lower effective ceiling", async () => { + it("sends an older saved offer unchanged and accepts Oblien's lower effective ceiling", async () => { const saved = Object.freeze({ max_workspaces: 52, max_vcpus: 200, max_ram_mb: 417792, max_disk_gb: 64, max_total_vcpus: 8, max_total_ram_mb: 16384, max_total_disk_gb: 256 }); await syncCloudResourceLimits("tenant-a", "team", saved); - expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: toOblienVmLimits(saved) }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: saved }); expect(saved.max_vcpus).toBe(200); expect(h.quota).not.toHaveBeenCalled(); }); it("preserves explicit customer restrictions even when the owner's capacity is unlimited", async () => { const saved = Object.freeze({ max_workspaces: 7, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 12, max_total_vcpus: 3, max_total_ram_mb: 6144, max_total_disk_gb: 24 }); await syncCloudResourceLimits("tenant-a", "team", saved); - expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: toOblienVmLimits(saved) }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: saved }); expect(h.quota).not.toHaveBeenCalled(); }); it("does not rewrite declared policy when effective capacity differs", async () => { const declared = { max_workspaces: 52, max_vcpus: 200, max_ram_mb: 417792, max_disk_gb: 64, max_total_vcpus: 8, max_total_ram_mb: 16384, max_total_disk_gb: 256 }; - h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: toOblienVmLimits(declared), - effective_resource_limits: { ...toOblienVmLimits(declared), max_vcpus: 32, max_ram_mb: 65536 }, + h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: declared, + effective_resource_limits: { ...declared, max_vcpus: 32, max_ram_mb: 65536 }, } }); await syncCloudResourceLimits("tenant-a", "team", declared); expect(h.update).not.toHaveBeenCalled(); expect(h.quota).not.toHaveBeenCalled(); }); it("clears old declared caps only after a verified enterprise entitlement", async () => { - h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: { max_vms: 5 } } }); + h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: { max_workspaces: 5 } } }); await syncCloudResourceLimits("tenant-a", "enterprise"); - expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: { max_vms: null, max_vcpus: null, max_ram_mb: null, max_disk_gb: null, max_total_vcpus: null, max_total_ram_mb: null, max_total_disk_gb: null } }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: { max_workspaces: null, max_vcpus: null, max_ram_mb: null, max_disk_gb: null, max_total_vcpus: null, max_total_ram_mb: null, max_total_disk_gb: null } }); }); it("cannot change policy when the provider returns another namespace", async () => { h.get.mockResolvedValue({ data: { id: "ns-b", slug: "tenant-b" } }); diff --git a/apps/api/test/lib/cloud-resource-proxy.test.ts b/apps/api/test/lib/cloud-resource-proxy.test.ts index 0c6168e0a..f41b50777 100644 --- a/apps/api/test/lib/cloud-resource-proxy.test.ts +++ b/apps/api/test/lib/cloud-resource-proxy.test.ts @@ -12,7 +12,7 @@ vi.mock("../../src/lib/request-context", () => ({ getRequestContext: () => ({ or vi.mock("../../src/modules/cloud/cloud-relay-access", () => ({ authorizeCloudRelayWorkspace: async () => null })); vi.mock("@repo/platform/engine/lib/openship-cloud", () => ({ ensureNamespace: async () => "ns-a" })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ getOblienClient: () => ({ - vms: { get: h.workspaceGet }, + workspaces: { get: h.workspaceGet }, pages: { list: h.pageList, get: h.pageGet, create: h.pageCreate, deploy: h.pageDeploy, delete: h.pageDelete }, domain: { routes: h.routes }, routes: { set: h.setRoutes }, }) })); @@ -46,18 +46,18 @@ describe("desktop-to-SaaS Cloud resource delegation", () => { it("round-trips page reads and redeploys through the SaaS ownership checks", async () => { const proxy = createRemoteCloudAdmin("org-a"); expect(await proxy.pages!.get("site-a")).toMatchObject({ page: { namespace: "ns-a" } }); - await proxy.pages!.deploy("site-a", { vm_id: "ws-a", path: "/app/dist" }); - expect(h.pageDeploy).toHaveBeenCalledWith("site-a", { vm_id: "ws-a", path: "/app/dist" }); + await proxy.pages!.deploy("site-a", { workspace_id: "ws-a", path: "/app/dist" }); + expect(h.pageDeploy).toHaveBeenCalledWith("site-a", { workspace_id: "ws-a", path: "/app/dist" }); expect(h.spend).toHaveBeenCalledWith("org-a", null); }); it("ignores the client's namespace and pins a create to its server identity", async () => { - await createRemoteCloudAdmin("org-a").pages!.create({ vm_id: "ws-a", path: "/app/dist", name: "Site", slug: "site-a", namespace: "ns-b" }); + await createRemoteCloudAdmin("org-a").pages!.create({ workspace_id: "ws-a", path: "/app/dist", name: "Site", slug: "site-a", namespace: "ns-b" }); expect(h.pageCreate).toHaveBeenCalledWith(expect.objectContaining({ namespace: "ns-a" })); }); it("refuses both foreign page reads and foreign source exports", async () => { const pages = createRemoteCloudAdmin("org-a").pages!; await expect(pages.get("site-b")).rejects.toMatchObject({ status: 404 }); - await expect(pages.create({ vm_id: "ws-b", path: "/app/dist", name: "Site", slug: "site-a" })).rejects.toMatchObject({ status: 404 }); + await expect(pages.create({ workspace_id: "ws-b", path: "/app/dist", name: "Site", slug: "site-a" })).rejects.toMatchObject({ status: 404 }); expect(h.pageCreate).not.toHaveBeenCalled(); }); it("preserves provider 404 so the runtime can create a missing page", async () => { diff --git a/apps/api/test/lib/cloud-tenant-admin.test.ts b/apps/api/test/lib/cloud-tenant-admin.test.ts index b6e113560..fe6313b97 100644 --- a/apps/api/test/lib/cloud-tenant-admin.test.ts +++ b/apps/api/test/lib/cloud-tenant-admin.test.ts @@ -5,7 +5,7 @@ const h = vi.hoisted(() => ({ workspaceGet: vi.fn(), routes: vi.fn(), setRoutes: vi.fn(), spend: vi.fn(), pageList: vi.fn(), })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ getOblienClient: () => ({ - vms: { get: h.workspaceGet }, + workspaces: { get: h.workspaceGet }, pages: { list: h.pageList, get: h.pageGet, create: h.pageCreate, delete: h.pageDelete, disable: h.pageDisable, deploy: h.pageDeploy }, domain: { routes: h.routes }, routes: { set: h.setRoutes }, }) })); @@ -32,12 +32,12 @@ describe("admin-only cloud delegation", () => { }); it("rejects another customer's workspace before exporting a page", async () => { const proxy = createTenantCloudAdmin("org-one", "ns-own"); - await expect(proxy.pages!.create({ vm_id: "ws-other", path: "/app/dist", name: "test", slug: "test" })).rejects.toMatchObject({ statusCode: 404 }); + await expect(proxy.pages!.create({ workspace_id: "ws-other", path: "/app/dist", name: "test", slug: "test" })).rejects.toMatchObject({ statusCode: 404 }); expect(h.pageCreate).not.toHaveBeenCalled(); }); it("pins page creation to the authenticated namespace", async () => { const proxy = createTenantCloudAdmin("org-one", "ns-own"); - await proxy.pages!.create({ vm_id: "ws-own", path: "/app/dist", name: "test", slug: "test", namespace: "ns-other" }); + await proxy.pages!.create({ workspace_id: "ws-own", path: "/app/dist", name: "test", slug: "test", namespace: "ns-other" }); expect(h.pageCreate).toHaveBeenCalledWith(expect.objectContaining({ namespace: "ns-own" })); expect(h.spend).toHaveBeenCalledWith("org-one", undefined); }); @@ -45,7 +45,7 @@ describe("admin-only cloud delegation", () => { const pages = createTenantCloudAdmin("org-one", "ns-own").pages!; await expect(pages.get("other-page")).rejects.toMatchObject({ statusCode: 404 }); await expect(pages.delete("other-page")).rejects.toMatchObject({ statusCode: 404 }); - await expect(pages.deploy("other-page", { vm_id: "ws-own", path: "/app/dist" })).rejects.toMatchObject({ statusCode: 404 }); + await expect(pages.deploy("other-page", { workspace_id: "ws-own", path: "/app/dist" })).rejects.toMatchObject({ statusCode: 404 }); expect(h.pageDelete).not.toHaveBeenCalled(); expect(h.pageDeploy).not.toHaveBeenCalled(); }); @@ -59,11 +59,11 @@ describe("admin-only cloud delegation", () => { }); it("validates both hostname and every route target before an admin mutation", async () => { const proxy = createTenantCloudAdmin("org-one", "ns-own"); - const routes = [{ match: { path: "/" }, action: { kind: "proxy" as const, vm: "ws-other", port: 8080 } }]; + const routes = [{ match: { path: "/" }, action: { kind: "proxy" as const, workspace: "ws-other", port: 8080 } }]; await expect(proxy.setRoutes!("own.opsh.io", { routes })).rejects.toMatchObject({ statusCode: 404 }); await expect(proxy.setRoutes!("other.opsh.io", { routes: [] })).rejects.toMatchObject({ statusCode: 404 }); expect(h.setRoutes).not.toHaveBeenCalled(); - await proxy.setRoutes!("own.opsh.io", { routes: [{ ...routes[0]!, action: { kind: "proxy", vm: "ws-own", port: 8080 } }] }); + await proxy.setRoutes!("own.opsh.io", { routes: [{ ...routes[0]!, action: { kind: "proxy", workspace: "ws-own", port: 8080 } }] }); expect(h.setRoutes).toHaveBeenCalledOnce(); }); it("does not use reseller authority for unverified external proxy origins", async () => { diff --git a/apps/api/test/lib/compose-parser.test.ts b/apps/api/test/lib/compose-parser.test.ts index 7f885cf14..2b366d31d 100644 --- a/apps/api/test/lib/compose-parser.test.ts +++ b/apps/api/test/lib/compose-parser.test.ts @@ -9,16 +9,6 @@ import { } from "@repo/platform/engine/lib/compose-parser"; describe("parseComposeFile", () => { - it("keeps the container ports a compose file declares with `expose`", () => { - const parsed = parseComposeFile( - "services:\n web:\n image: app:test\n expose:\n - 3000\n - \"8080/udp\"\n", - ); - expect(parsed.services[0]?.expose).toEqual(["3000", "8080/udp"]); - // `expose` is read now, so it is no longer reported as a dropped key. - expect(parsed.unsupported).not.toEqual( - expect.arrayContaining([expect.objectContaining({ field: "expose" })]), - ); - }); it("keeps shared memory capacity and reports invalid values as blocking", () => { const parsed = parseComposeFile("services:\n inference:\n image: vllm:test\n shm_size: ${SHM}\n", { envFileContent: "SHM=2g\n" }); expect(parsed.services[0]?.advanced?.shmSize).toBe(2147483648); diff --git a/apps/api/test/lib/controller-sse-drain.test.ts b/apps/api/test/lib/controller-sse-drain.test.ts deleted file mode 100644 index fd2e2ffcc..000000000 --- a/apps/api/test/lib/controller-sse-drain.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import { Hono } from "hono"; -import type { SSEStreamingApi } from "hono/streaming"; -import { closeControllerStreams, resumeControllerStreams, streamSSE } from "../../src/lib/sse"; -import { drainBackgroundWork } from "@repo/platform/engine/lib/background-work"; - -beforeEach(() => resumeControllerStreams()); -afterEach(async () => { - closeControllerStreams(); - await drainBackgroundWork(); - resumeControllerStreams(); -}); - -it("refuses a stream admitted before the move but initialized after streams were closed", async () => { - let enter!: () => void; - let proceed!: () => void; - const entered = new Promise(resolve => { enter = resolve; }); - const admitted = new Promise(resolve => { proceed = resolve; }); - const callback = vi.fn(async (stream: SSEStreamingApi) => { - await new Promise(resolve => stream.onAbort(resolve)); - }); - const app = new Hono(); - app.get("/events", async c => { - enter(); - await admitted; // permission/metadata read already admitted by the HTTP guard - return streamSSE(c, callback); - }); - const pending = app.request("/events"); - await entered; - closeControllerStreams(); - proceed(); - const response = await pending; - try { - expect(response.status).toBe(503); - expect(await response.json()).toMatchObject({ code: "INSTANCE_CONTROLLER_INACTIVE" }); - expect(callback).not.toHaveBeenCalled(); - } finally { - closeControllerStreams(); - if (!response.bodyUsed) await response.body?.cancel(); - await drainBackgroundWork(); - } -}); - -it("aborts an existing subscriber so the controller can finish draining", async () => { - const aborted = vi.fn(); - const app = new Hono(); - app.get("/events", c => streamSSE(c, async stream => { - await new Promise(resolve => stream.onAbort(() => { aborted(); resolve(); })); - })); - const response = await app.request("/events"); - expect(response.status).toBe(200); - closeControllerStreams(); - await drainBackgroundWork(); - expect(aborted).toHaveBeenCalledOnce(); - await response.body?.cancel(); -}); - -it("accepts streams again when the active controller is resumed after cancellation", async () => { - const callback = vi.fn(async () => {}); - const app = new Hono(); - app.get("/events", c => streamSSE(c, callback)); - closeControllerStreams(); - const refused = await app.request("/events"); - expect(refused.status).toBe(503); - expect(callback).not.toHaveBeenCalled(); - resumeControllerStreams(); - const response = await app.request("/events"); - expect(response.status).toBe(200); - expect(callback).toHaveBeenCalledOnce(); - await response.body?.cancel(); -}); diff --git a/apps/api/test/lib/dockerignore-source-coverage.test.ts b/apps/api/test/lib/dockerignore-source-coverage.test.ts index c6a71c214..ec71de91d 100644 --- a/apps/api/test/lib/dockerignore-source-coverage.test.ts +++ b/apps/api/test/lib/dockerignore-source-coverage.test.ts @@ -1,6 +1,6 @@ import { execFileSync } from "node:child_process"; import { readFileSync } from "node:fs"; -import { join, posix } from "node:path"; +import { join } from "node:path"; import { describe, expect, it } from "vitest"; @@ -93,81 +93,6 @@ const tracked = execFileSync("git", ["ls-files", "-z"], { * exempted here: `.dockerignore`'s `*.md` is unanchored and so drops only root-level * files, and apps/web/Dockerfile compiles the 102 `.mdx` files under content/. */ const DELIBERATE = /(^|\/)\.env($|\.)/; -const contextFiles = tracked.filter((file) => !isExcluded(file, patterns)); - -/** Map repository files to their paths in the first dependency-install stage. - * This deliberately handles only the COPY/WORKDIR syntax used by our images; - * validating a manifest against the full checkout would miss absent build inputs. - */ -function dependencyInputs(dockerfile: string): Map { - let directory = "/"; - const files = new Map(); - for (const line of dockerfile.replace(/\\\r?\n/g, " ").split("\n")) { - const [instruction, ...args] = line.trim().split(/\s+/); - if (instruction === "FROM") { - directory = "/"; - files.clear(); - } else if (instruction === "WORKDIR") { - directory = posix.resolve(directory, args[0]); - } else if (instruction === "COPY" && !args.some((arg) => arg.startsWith("--from="))) { - const parents = args.includes("--parents"); - const paths = args.filter((arg) => !arg.startsWith("--")); - const destination = posix.resolve(directory, paths.pop()!); - for (const source of paths) { - const pattern = toRegex(source); - const prefix = source.replace(/\/$/, "") + "/"; - for (const file of contextFiles) { - if (pattern.test(file)) { - files.set(posix.join(destination, parents ? file : posix.basename(file)), file); - } else if (file.startsWith(prefix)) { - files.set(posix.join(destination, file.slice(prefix.length)), file); - } - } - } - } else if (instruction === "RUN" && /\bbun install\b/.test(line)) { - return files; - } - } - throw new Error("No dependency installation found in Dockerfile"); -} - -describe("Docker dependency inputs", () => { - it.each([ - "apps/api/Dockerfile", - "apps/dashboard/Dockerfile", - "apps/web/Dockerfile", - "apps/email/Dockerfile.webmail", - ])("resolves local package archives inside %s before installation", (path) => { - const inputs = dependencyInputs(readFileSync(join(REPO_ROOT, path), "utf8")); - let checked = 0; - for (const [destination, source] of inputs) { - if (!destination.endsWith("/package.json")) continue; - const manifest = JSON.parse(readFileSync(join(REPO_ROOT, source), "utf8")); - for (const dependency of Object.values({ - ...manifest.dependencies, - ...manifest.devDependencies, - ...manifest.optionalDependencies, - })) { - if (typeof dependency !== "string" || !dependency.startsWith("file:")) continue; - const resolved = posix.resolve(posix.dirname(destination), dependency.slice(5)); - expect( - inputs.has(resolved) || inputs.has(posix.join(resolved, "package.json")), - `${destination}: missing ${resolved}`, - ).toBe(true); - checked++; - } - if (manifest.workspaces) { - expect(inputs.get(posix.join(posix.dirname(destination), "bunfig.toml"))).toBe("bunfig.toml"); - } - for (const patch of Object.values(manifest.patchedDependencies ?? {})) { - if (typeof patch !== "string") continue; - const resolved = posix.resolve(posix.dirname(destination), patch); - expect(inputs.has(resolved), `${destination}: missing dependency patch ${resolved}`).toBe(true); - } - } - expect(checked).toBeGreaterThan(0); - }); -}); describe(".dockerignore vs tracked source", () => { it("sees the repo (git ls-files returned files)", () => { @@ -200,17 +125,4 @@ describe(".dockerignore vs tracked source", () => { expect(isExcluded("apps/api/.env.example", p)).toBe(false); expect(isExcluded("packages/platform/src/engine/config/env.ts", p)).toBe(false); }); - - it("excludes generated mail credentials and keys but retains vendored dependencies", () => { - for (const path of [ - "apps/email/.dev-mail/server.env", - "apps/email/.dev-mail/tls/key.pem", - "apps/email/.dev-mail/data/dovecot-keys/private.key", - ]) { - expect(isExcluded(path, patterns), path).toBe(true); - } - for (const path of tracked.filter((file) => file.startsWith("vendor/"))) { - expect(isExcluded(path, patterns), path).toBe(false); - } - }); }); diff --git a/apps/api/test/lib/edge-mgmt-large-body.test.ts b/apps/api/test/lib/edge-mgmt-large-body.test.ts deleted file mode 100644 index 64d0515cb..000000000 --- a/apps/api/test/lib/edge-mgmt-large-body.test.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { exec as shellExec } from "node:child_process"; -import { access, mkdtemp, readFile, rm, stat, writeFile } from "node:fs/promises"; -import { createServer, type Server } from "node:http"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { promisify } from "node:util"; -import { LocalExecutor } from "@repo/adapters"; - -const { acquire } = vi.hoisted(() => ({ acquire: vi.fn() })); -vi.mock("@repo/platform/engine/lib/ssh-manager", () => ({ sshManager: { acquire } })); -vi.mock("@repo/platform/engine/lib/ssh-tunnel", () => ({ - tunnelRequest: vi.fn(async () => null), - tunnelStream: vi.fn(), -})); -vi.mock("@repo/adapters", async (original) => ({ - ...(await original()), - resolveOurEdgeContainer: async () => "fixture-edge", -})); - -const { postEdgeMgmt } = await import("@repo/platform/engine/lib/edge-management"); -const exec = promisify(shellExec); -let server: Server | undefined; -let directory: string | undefined; -const files: string[] = []; -let local: LocalExecutor; -beforeEach(() => { - vi.stubEnv("CLOUD_MODE", "false"); - local = new LocalExecutor(); -}); -afterEach(async () => { - await new Promise((resolve) => (server ? server.close(() => resolve()) : resolve())); - server = undefined; - for (const file of files.splice(0)) await rm(file, { force: true }); - if (directory) await rm(directory, { recursive: true, force: true }); - directory = undefined; - await local.dispose(); - vi.unstubAllEnvs(); -}); - -describe("large edge management requests", () => { - it.each([ - { transport: "stdin", bytes: 64000 }, - { transport: "file", bytes: 64000 }, - { transport: "tunnel fallback", bytes: 64000 }, - { transport: "stdin", bytes: 0 }, - { transport: "file", bytes: 0 }, - ])( - "delivers literal JSON via $transport ($bytes padding bytes) and preserves large replies", - async ({ transport, bytes }) => { - directory = await mkdtemp(join(tmpdir(), "openship-response-transport-")); - const marker = join(directory, "must-not-execute"); - const literal = `'; touch ${marker}; $(touch ${marker}) \`touch ${marker}\`\nمرحبا\u0000`; - const payload = { - host: "response.test", - rules: Array.from({ length: 4 }, (_, i) => ({ - pathPrefix: `/response/${i}`, - spec: { response: { body: literal + "x".repeat(bytes) } }, - })), - }; - const reply = { ok: true, count: 4, collected: "مرحبا".repeat(10000) }; - let received = ""; - server = createServer(async (request, response) => { - const chunks: Buffer[] = []; - for await (const chunk of request) chunks.push(Buffer.from(chunk)); - received = Buffer.concat(chunks).toString("utf8"); - response.setHeader("Content-Type", "application/json"); - response.end(JSON.stringify(reply)); - }); - await new Promise((resolve) => server!.listen(0, "127.0.0.1", resolve)); - const address = server.address(); - if (!address || typeof address === "string") throw new Error("Missing fixture port"); - const stdin = transport !== "file"; - const hostWrite = vi.fn(async (path: string, body: string, options: { mode: number }) => { - files.push(path); - await writeFile(path, body, options); - expect((await stat(path)).mode & 0o777).toBe(0o600); - }); - const hostRemove = vi.fn((path: string) => rm(path, { force: true })); - const toLocal = (command: string, input = false) => { - if (Buffer.byteLength(command) >= 128 * 1024) throw new Error("E2BIG"); - const prefix = `docker exec ${input ? "-i " : ""}'fixture-edge' `; - if (!command.startsWith(prefix)) throw new Error("Unexpected fixture command"); - return command.slice(prefix.length).replace("127.0.0.1:9145", `127.0.0.1:${address.port}`); - }; - acquire.mockResolvedValue({ - ...(transport === "tunnel fallback" ? { forwardPort: vi.fn() } : {}), - ...(stdin - ? { - execWithInput: async (command: string, body: import("node:stream").Readable) => { - const path = command.match(/\/tmp\/openship-edge-request-[\w-]+\.json/)?.[0]; - if (!path) throw new Error("Missing private upload path"); - files.push(path); - const result = await local.execWithInput(toLocal(command, true), body); - expect((await stat(path)).mode & 0o777).toBe(0o600); - return result; - }, - } - : {}), - writeFile: hostWrite, - rm: hostRemove, - exec: async (command: string) => { - // Only Docker isolation is elided: stdin, curl, shell, files and HTTP - // are real. The fixture shares the container's file with the host. - if (command.startsWith("docker cp ")) { - if (stdin) throw new Error("stdin-capable executors must not stage a host copy"); - return ""; - } - return (await exec(toLocal(command))).stdout; - }, - }); - await expect(postEdgeMgmt("fixture-server", "/rules", payload)).resolves.toEqual(reply); - expect(JSON.parse(received)).toEqual(payload); - await expect(access(marker)).rejects.toMatchObject({ code: "ENOENT" }); - expect(files).toHaveLength(1); - await expect(access(files[0]!)).rejects.toMatchObject({ code: "ENOENT" }); - if (stdin) { - expect(hostWrite).not.toHaveBeenCalled(); - expect(hostRemove).not.toHaveBeenCalled(); - } - }, - ); - - it("cleans up a failed stdin upload without publishing or retrying through a host copy", async () => { - const hostWrite = vi.fn(); - const commands: string[] = []; - acquire.mockResolvedValue({ - execWithInput: async (command: string) => { - const path = command.match(/\/tmp\/openship-edge-request-[\w-]+\.json/)?.[0]; - if (!path) throw new Error("Missing upload path"); - files.push(path); - await writeFile(path, "partial", { mode: 0o600 }); - return { code: 1, stdout: "", stderr: "connection interrupted" }; - }, - exec: async (command: string) => { - commands.push(command); - if (command.includes("curl") || command.startsWith("docker cp ")) - throw new Error("Failed upload must not publish"); - return (await exec(command.slice("docker exec 'fixture-edge' ".length))).stdout; - }, - writeFile: hostWrite, - }); - await expect( - postEdgeMgmt("fixture-server", "/rules", { body: "x".repeat(65536) }), - ).resolves.toBeNull(); - expect(hostWrite).not.toHaveBeenCalled(); - expect( - commands.some((command) => command.includes("curl") || command.startsWith("docker cp ")), - ).toBe(false); - expect(files).toHaveLength(1); - await expect(access(files[0]!)).rejects.toMatchObject({ code: "ENOENT" }); - }); - - it("cleans up private request files when copying to the edge fails", async () => { - acquire.mockResolvedValue({ - writeFile: async (path: string, body: string, options: { mode: number }) => { - files.push(path); - await writeFile(path, body, options); - }, - exec: async (command: string) => { - if (command.startsWith("docker cp ")) throw new Error("edge unavailable"); - return ""; - }, - rm: (path: string) => rm(path, { force: true }), - }); - await expect( - postEdgeMgmt("fixture-server", "/rules", { body: "x".repeat(65536) }), - ).resolves.toBeNull(); - expect(files).toHaveLength(1); - await expect(readFile(files[0]!)).rejects.toMatchObject({ code: "ENOENT" }); - }); -}); diff --git a/apps/api/test/lib/email-templates.test.ts b/apps/api/test/lib/email-templates.test.ts index be313f41d..00a84f123 100644 --- a/apps/api/test/lib/email-templates.test.ts +++ b/apps/api/test/lib/email-templates.test.ts @@ -5,11 +5,7 @@ */ import { describe, expect, it } from "vitest"; -import { - existingAccountEmail, - organizationInviteEmail, - resetPasswordOtpEmail, -} from "@repo/platform/engine/lib/email-templates"; +import { organizationInviteEmail, resetPasswordOtpEmail } from "@repo/platform/engine/lib/email-templates"; describe("email-templates — HTML injection is neutralized", () => { it("escapes attacker-controlled org name and inviter name in the invite HTML", () => { @@ -68,15 +64,4 @@ describe("email-templates — HTML injection is neutralized", () => { expect(email.html).not.toContain(" { - const email = existingAccountEmail( - { name: '', email: "customer@example.test" }, - "https://dashboard.example.test", - ); - expect(email.html).not.toContain(" { - vi.unstubAllEnvs(); - vi.resetModules(); -}); - -it.each([ - [undefined, "https://vm.oblien.com"], - ["https://runtime.staging.example", "https://runtime.staging.example"], -])("configures the native VM credential endpoint with override %s", async (override, expected) => { - vi.resetModules(); - vi.stubEnv("NODE_ENV", "test"); - vi.stubEnv("BILLING_ENABLED", "false"); - vi.stubEnv("OBLIEN_RUNTIME_URL", override); - const { env } = await import("@repo/platform/engine/config/env"); - expect(env.OBLIEN_RUNTIME_URL).toBe(expected); -}); diff --git a/apps/api/test/lib/permission-grant-satisfiability.test.ts b/apps/api/test/lib/permission-grant-satisfiability.test.ts index bc4816867..f4baf51a2 100644 --- a/apps/api/test/lib/permission-grant-satisfiability.test.ts +++ b/apps/api/test/lib/permission-grant-satisfiability.test.ts @@ -24,10 +24,9 @@ import type { RequestContext } from "../../src/lib/request-context"; * the grantable surface without proving it authorizes something → this fails. */ -// Exercise grant algebra under an owner's ceiling; members cannot delegate admin. vi.mock("@repo/db", () => ({ repos: { - member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "member" })) }, project: { findById: vi.fn(async (id: string) => (id === "*" ? null : { id, organizationId: "org1" })), findEnvVarById: vi.fn(async () => null), diff --git a/apps/api/test/lib/permission-own-projects.test.ts b/apps/api/test/lib/permission-own-projects.test.ts index 0f3a3edf0..d1b2a52b9 100644 --- a/apps/api/test/lib/permission-own-projects.test.ts +++ b/apps/api/test/lib/permission-own-projects.test.ts @@ -3,10 +3,9 @@ import { describe, it, expect, vi } from "vitest"; // checkPermission touches only member.find (membership gate) and, for a // concrete project id, project.findById (org resolution). We pass the grant // source explicitly via opts, so resourceGrant is never consulted. -// The owner can delegate project admin; the token must still satisfy each grant. vi.mock("@repo/db", () => ({ repos: { - member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "member" })) }, project: { findById: vi.fn(async (id: string) => id === "*" ? null : { id, organizationId: "org1" }, diff --git a/apps/api/test/lib/permission-wildcard-list-arm.test.ts b/apps/api/test/lib/permission-wildcard-list-arm.test.ts index 0620fa0ff..d92e3788a 100644 --- a/apps/api/test/lib/permission-wildcard-list-arm.test.ts +++ b/apps/api/test/lib/permission-wildcard-list-arm.test.ts @@ -19,10 +19,9 @@ import { describe, it, expect, vi } from "vitest"; -// The owner's role ceiling permits delegation; the tests enforce grant widths. vi.mock("@repo/db", () => ({ repos: { - member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "member" })) }, project: { findById: vi.fn(async (id: string) => (id === "*" ? null : { id, organizationId: "org1" })), findEnvVarById: vi.fn(async () => null), @@ -199,7 +198,7 @@ describe("a full project wildcard now lists and creates (deliberate widening)", }); describe("non-restricted roles are untouched by this arm", () => { - it("an owner is authorized by role, without consulting grants", async () => { + it("a member is authorized by role, without consulting grants", async () => { const boom = { findForResource: async () => { throw new Error("the role arm must return before any grant lookup"); diff --git a/apps/api/test/lib/post-edge-mgmt.test.ts b/apps/api/test/lib/post-edge-mgmt.test.ts index 8a41c016b..9031b4275 100644 --- a/apps/api/test/lib/post-edge-mgmt.test.ts +++ b/apps/api/test/lib/post-edge-mgmt.test.ts @@ -31,6 +31,7 @@ vi.mock("@repo/platform/engine/lib/ssh-tunnel", () => ({ vi.mock("@repo/platform/engine/lib/ssh-manager", () => ({ sshManager: { retain: vi.fn(), release: vi.fn(), acquire: vi.fn() }, })); +vi.mock("@repo/platform/engine/lib/platform-mode", () => ({ isOblienBackedDeployment: async () => false })); const { findLocal } = vi.hoisted(() => ({ findLocal: vi.fn() })); vi.mock("@repo/db", () => ({ repos: { @@ -38,7 +39,7 @@ vi.mock("@repo/db", () => ({ }, })); -const { postEdgeMgmt } = await import("@repo/platform/engine/lib/edge-management"); +const { postEdgeMgmt } = await import("@repo/platform/engine/lib/project-analytics"); beforeEach(() => { vi.clearAllMocks(); @@ -122,13 +123,13 @@ describe("failure is best-effort by contract", () => { // would abort a routing reconcile over a metrics setting. await expect( postEdgeMgmt(null, "/analytics/config", { hosts: [] }, "org1"), - ).resolves.toBeNull(); + ).resolves.toBeUndefined(); }); it("resolves when the tunnel fails", async () => { tunnelRequest.mockRejectedValue(new Error("tunnel closed")); await expect( postEdgeMgmt("srv1", "/analytics/config", { host: "a.com", paths: true }), - ).resolves.toBeNull(); + ).resolves.toBeUndefined(); }); }); diff --git a/apps/api/test/lib/profile-avatar.test.ts b/apps/api/test/lib/profile-avatar.test.ts deleted file mode 100644 index 31d4e4604..000000000 --- a/apps/api/test/lib/profile-avatar.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { expect, it } from "vitest"; -import { auth } from "@repo/platform/engine/lib/auth"; -import { provisionUser } from "@repo/platform/engine/lib/provision-user"; -import { mintSession } from "../../src/lib/cloud-auth-proxy"; -import { db, schema, eq } from "@repo/db"; -import { randomUUID } from "node:crypto"; - -it("updates only the signed-in user's avatar through the existing auth endpoint and rejects unsafe URLs", async () => { - const id = randomUUID(); - await provisionUser({ - id, - email: `${id}@example.test`, - name: "Avatar owner", - emailVerified: true, - }); - const session = await mintSession({ purpose: "local-cookie", userId: id }); - const update = (image: unknown, token: string | null = session.token, extra = {}) => - auth.handler( - new Request("http://localhost:4000/api/auth/update-user", { - method: "POST", - headers: { - "Content-Type": "application/json", - ...(token ? { Authorization: `Bearer ${token}` } : {}), - }, - body: JSON.stringify({ image, ...extra }), - }), - ); - expect((await update("https://cdn.example.test/avatar.png", null)).status).toBe(401); - const result = await update("https://cdn.example.test/avatar.png"); - expect(result.status, await result.clone().text()).toBe(200); - expect(await db.query.user.findFirst({ where: eq(schema.user.id, id) })).toMatchObject({ - image: "https://cdn.example.test/avatar.png", - role: "user", - }); - expect( - await auth.api.getSession({ - headers: new Headers({ Authorization: `Bearer ${session.token}` }), - }), - ).toMatchObject({ user: { image: "https://cdn.example.test/avatar.png" } }); - expect( - (await update("https://cdn.example.test/avatar.png", session.token, { role: "admin" })).status, - ).toBe(400); - for (const image of [ - "javascript:alert(1)", - "data:image/svg+xml,", - "https://user:secret@example.test/a.png", - "/avatar.png", - 123, - ]) - expect((await update(image)).status).toBe(400); - expect((await update(null)).status).toBe(200); - expect(await db.query.user.findFirst({ where: eq(schema.user.id, id) })).toMatchObject({ - image: null, - }); -}); diff --git a/apps/api/test/lib/project-edge-pages.test.ts b/apps/api/test/lib/project-edge-pages.test.ts deleted file mode 100644 index c3752ca3a..000000000 --- a/apps/api/test/lib/project-edge-pages.test.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { beforeEach, expect, it, vi } from "vitest"; -import type { ExecutionContext } from "@repo/platform"; -import type { CompiledEdgePages, ProjectEdgePages } from "@repo/core"; -const h = vi.hoisted(() => ({ - project: {} as Record, - target: "local", - deployment: true, - persisted: vi.fn(), - publish: vi.fn(), - read: vi.fn(), - admission: vi.fn(), -})); -vi.mock("@repo/db", () => ({ - repos: { - project: { findById: async () => h.project, update: h.persisted }, - domain: { listByProject: async () => [{ id: "host", hostname: "site.test" }] }, - }, -})); -vi.mock("@repo/platform/engine/lib/active-deployment", () => ({ - findActiveDeployment: async () => (h.deployment ? { id: "release" } : null), -})); -vi.mock("@repo/platform/engine/lib/deployment-runtime", () => ({ - withDeploymentPlatform: async (_: unknown, work: Function) => - work({ routing: { setRouteEdgePages: h.publish, getRouteEdgePages: h.read } }), -})); -vi.mock("@repo/platform/engine/lib/project-runtime-lock", () => ({ - withProjectRuntimeLock: async (_: string, work: Function) => work(), -})); -vi.mock("@repo/platform/engine/lib/route-protection", () => ({ - withRouteProtectionLock: async (_: string, work: Function) => work(), -})); -vi.mock("@repo/platform/engine/modules/projects/project-deploy-target", () => ({ - resolveProjectDeployTarget: async () => ({ deployTarget: h.target }), -})); -vi.mock("@repo/platform/engine/modules/domains/domain-execution", () => ({ - domainExecution: h.admission, -})); -vi.mock("@repo/platform/engine/lib/audit-emitter", () => ({ - audit: { recordAsync: vi.fn() }, - operationAuditContext: () => ({}), -})); -import { projectEdgePageResources as pages } from "@repo/platform/engine/modules/projects/project-edge-pages.operations"; -import { assertProjectEdgePagesTarget } from "@repo/platform/engine/modules/projects/project-routing-capabilities"; -const ctx = { organizationId: "org" } as ExecutionContext; -const config: ProjectEdgePages = { - defaults: { files: [], errors: [], maintenance: { enabled: true, retryAfter: 300 } }, -}; -beforeEach(() => { - vi.resetAllMocks(); - h.target = "local"; - h.deployment = true; - h.project = { id: "project", organizationId: "org", routingConfig: { cleanUrls: true } }; - h.persisted.mockImplementation(async (_: string, update: object) => - Object.assign(h.project, update), - ); - h.publish.mockResolvedValue(true); - h.read.mockResolvedValue(null); -}); -it("keeps a failed application pending, preserves intent, and retries through the same route provider", async () => { - const initial = await pages.getEdgePages(ctx, "project"); - h.publish.mockRejectedValueOnce(new Error("edge reload failed")); - const saved = await pages.updateEdgePages(ctx, "project", { - config, - expectedRevision: initial.revision, - }); - expect(saved).toMatchObject({ config, status: "pending", message: "edge reload failed" }); - expect(h.project.routingConfig).toEqual({ cleanUrls: true, edgePages: config }); - expect(h.persisted.mock.invocationCallOrder[0]).toBeLessThan( - h.publish.mock.invocationCallOrder[0], - ); - const retried = await pages.updateEdgePages(ctx, "project", { - config, - expectedRevision: saved.revision, - }); - expect(retried.status).toBe("applied"); - const compiled: CompiledEdgePages = { - errors: {}, - maintenance: { enabled: true, retryAfter: 300 }, - }; - expect(h.publish).toHaveBeenLastCalledWith("site.test", compiled); - h.read.mockResolvedValue(compiled); - expect((await pages.getEdgePages(ctx, "project")).status).toBe("applied"); - h.read.mockResolvedValue(undefined); - expect((await pages.getEdgePages(ctx, "project")).status).toBe("pending"); -}); -it.each(["cloud", "workspace", "cluster"])( - "rejects provider-owned or unsupported target %s before persistence or execution", - async (kind) => { - if (kind === "cloud") h.target = "cloud"; - else h.project[kind === "workspace" ? "workspaceId" : "clusterId"] = "provider-owned"; - await expect( - pages.updateEdgePages(ctx, "project", { config, expectedRevision: "a".repeat(64) }), - ).rejects.toMatchObject({ code: "EDGE_PAGES_UNSUPPORTED" }); - expect(h.persisted).not.toHaveBeenCalled(); - expect(h.publish).not.toHaveBeenCalled(); - }, -); -it("checks tenant and native host permission before saving or touching an edge", async () => { - await expect( - pages.getEdgePages({ organizationId: "foreign" } as ExecutionContext, "project"), - ).rejects.toMatchObject({ statusCode: 404 }); - expect(h.read).not.toHaveBeenCalled(); - const initial = await pages.getEdgePages(ctx, "project"); - h.admission.mockRejectedValue(new Error("Host execution is disabled")); - await expect( - pages.updateEdgePages(ctx, "project", { config, expectedRevision: initial.revision }), - ).rejects.toThrow("Host execution is disabled"); - expect(h.persisted).not.toHaveBeenCalled(); - expect(h.publish).not.toHaveBeenCalled(); -}); -it("drops unchanged overrides for deleted domains without accepting new unowned-host settings", async () => { - h.project.routingConfig = { edgePages: { hosts: { "removed.test": config.defaults } } }; - const previous = await pages.getEdgePages(ctx, "project"); - await expect( - pages.updateEdgePages(ctx, "project", { - config: { hosts: { "removed.test": { files: [], errors: [] } } }, - expectedRevision: previous.revision, - }), - ).rejects.toMatchObject({ code: "INVALID_DOMAIN" }); - expect(h.persisted).not.toHaveBeenCalled(); - const saved = await pages.updateEdgePages(ctx, "project", { - config: previous.config, - expectedRevision: previous.revision, - }); - expect(saved.config).toEqual({ hosts: {} }); -}); -it.each(["cloud", "cluster"])("guards a move to %s only while pages need an edge", (target) => { - expect(() => - assertProjectEdgePagesTarget({ routingConfig: { edgePages: config } }, target), - ).toThrow("Remove their assignments"); - expect(() => - assertProjectEdgePagesTarget( - { - routingConfig: { - edgePages: { - hosts: { "site.test": config.defaults! }, - }, - }, - }, - target, - ), - ).toThrow("Remove their assignments"); - expect(() => - assertProjectEdgePagesTarget( - { - routingConfig: { - edgePages: { - defaults: { - files: [{ id: "unused", name: "unused.html", html: "

Unused

" }], - errors: [], - maintenance: { enabled: false, retryAfter: 300 }, - }, - }, - }, - }, - target, - ), - ).not.toThrow(); -}); diff --git a/apps/api/test/lib/referral-routes.test.ts b/apps/api/test/lib/referral-routes.test.ts index b389e80bb..72092d85d 100644 --- a/apps/api/test/lib/referral-routes.test.ts +++ b/apps/api/test/lib/referral-routes.test.ts @@ -98,14 +98,6 @@ describe("referral HTTP authority", () => { ); }); - it("accepts an empty request stream for referral enrollment", async () => { - const response = await app.request("/api/referral-program/enroll", { - method: "POST", headers: { "x-user": "alice" }, body: "", - }); - expect(response.status).toBe(200); - expect(h.collection).toHaveBeenCalledWith(expect.objectContaining({ userId: "alice" }), undefined); - }); - it("denies scoped credentials and read-only payout requests before provider access", async () => { expect( (await request("", undefined, { "x-user": "alice", "x-project-token": "1" })).status, diff --git a/apps/api/test/lib/route-protection.test.ts b/apps/api/test/lib/route-protection.test.ts index 6674e5f01..c41bf10b4 100644 --- a/apps/api/test/lib/route-protection.test.ts +++ b/apps/api/test/lib/route-protection.test.ts @@ -119,7 +119,6 @@ beforeEach(() => { state.sourceRow = null; delete state.project.environmentType; delete state.project.previewSettings; - delete state.project.routingConfig; state.project.organizationId = "org"; state.project.deletionInProgress = false; state.domain.projectId = "proj"; @@ -135,19 +134,6 @@ beforeEach(() => { state.hostAdmission.mockResolvedValue(undefined); }); -it("publishes current maintenance intent on redeploy and clears pages for an unconfigured owner", async () => { - state.project.routingConfig = { edgePages: { - defaults: { files: [], errors: [], maintenance: { enabled: true, retryAfter: 300 } }, - } }; - await registerProjectRoute({ id: "proj" }, { registerRoute: state.register }, route); - expect(state.register).toHaveBeenLastCalledWith(expect.objectContaining({ - edgePages: { errors: {}, maintenance: { enabled: true, retryAfter: 300 } }, - })); - delete state.project.routingConfig; - await registerProjectRoute({ id: "proj" }, { registerRoute: state.register }, route); - expect(state.register).toHaveBeenLastCalledWith(expect.objectContaining({ edgePages: null })); -}); - describe("native preview password inheritance", () => { function preview() { state.project.environmentType = "preview"; @@ -294,7 +280,6 @@ describe("route protection admission and publication", () => { expect(state.register).toHaveBeenLastCalledWith({ ...route, protection: policy, - edgePages: null, terminatesTlsLocally: true, }); state.row!.secret = null; @@ -336,7 +321,7 @@ describe("route protection admission and publication", () => { { registerRoute: state.register }, { ...route, protection: policy }, ); - expect(state.register).toHaveBeenCalledWith({ ...route, protection: null, edgePages: null }); + expect(state.register).toHaveBeenCalledWith({ ...route, protection: null }); expect(state.markApplied).not.toHaveBeenCalled(); }); @@ -348,7 +333,7 @@ describe("route protection admission and publication", () => { { registerRoute: state.register }, { ...route, protection: policy }, ); - expect(state.register).toHaveBeenCalledWith({ ...route, protection: null, edgePages: null }); + expect(state.register).toHaveBeenCalledWith({ ...route, protection: null }); expect(state.markApplied).toHaveBeenCalledWith("proj", "private.test", "v1"); }); @@ -435,7 +420,6 @@ describe("route protection admission and publication", () => { expect(state.register).toHaveBeenCalledWith({ ...route, protection: policy, - edgePages: null, terminatesTlsLocally: true, }); state.register.mockClear(); diff --git a/apps/api/test/lib/safe-fetch.test.ts b/apps/api/test/lib/safe-fetch.test.ts index e0684479b..f16869a8e 100644 --- a/apps/api/test/lib/safe-fetch.test.ts +++ b/apps/api/test/lib/safe-fetch.test.ts @@ -86,25 +86,6 @@ describe("safeFetch — SSRF pinning", () => { expect(json.body).toBe("hi"); }); - it("limits authenticated verification redirects to the original origin", async () => { - const [sourcePort, destinationPort] = await Promise.all([listening, redirectReceiverListening]); - const origin = `http://127.0.0.1:${sourcePort}`; - const options = { - headers: { authorization: "Basic test-fixture" }, - allowHttp: true, - allowPrivate: true, - maxRedirects: 1, - sameOriginRedirectsOnly: true, - }; - - redirectTarget = `http://127.0.0.1:${destinationPort}/capture`; - expect((await safeFetch(`${origin}/redirect`, options)).status).toBe(302); - - redirectTarget = "/echo"; - const response = await safeFetch(`${origin}/redirect`, options); - expect(await response.json()).toMatchObject({ authorization: "Basic test-fixture" }); - }); - it("strips credentials before following a cross-origin redirect", async () => { const [sourcePort, destinationPort] = await Promise.all([listening, redirectReceiverListening]); redirectTarget = `http://127.0.0.1:${destinationPort}/capture`; diff --git a/apps/api/test/lib/secure-router-body-validation.test.ts b/apps/api/test/lib/secure-router-body-validation.test.ts index a422f536f..38b8d6c8a 100644 --- a/apps/api/test/lib/secure-router-body-validation.test.ts +++ b/apps/api/test/lib/secure-router-body-validation.test.ts @@ -98,20 +98,6 @@ describe("secureRouter auto-wires validation from spec.body", () => { expect(res.status).toBe(200); }); - it.each([undefined, ""])("accepts an empty action without requiring JSON: %j", async body => { - const app = buildApp(); - const init = { - method: "POST", - headers: { "content-type": "application/json" }, - ...(body === undefined ? {} : { body }), - }; - const response = await app.request("/api/t/no-body", init); - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ ok: true }); - // The same transport must still enforce a route's required input. - expect((await app.request("/api/t/with-body", init)).status).toBe(400); - }); - it("preserves optional bodies when their shared operation owns validation", async () => { const response = await buildApp().request("/api/t/operation", { method: "POST", headers: { "Content-Type": "application/json" } }); expect(response.status).toBe(200); diff --git a/apps/api/test/lib/server-log-stream-framing.test.ts b/apps/api/test/lib/server-log-stream-framing.test.ts index e641ab402..877b4219b 100644 --- a/apps/api/test/lib/server-log-stream-framing.test.ts +++ b/apps/api/test/lib/server-log-stream-framing.test.ts @@ -1,6 +1,6 @@ import { describe, it, expect } from "vitest"; -import { streamChunkBytes } from "@repo/platform/engine/lib/edge-management"; +import { streamChunkBytes } from "@repo/platform/engine/lib/project-analytics"; /** * The server-logs live tail relays the EDGE's SSE frames. `pipe_stream.lua` emits diff --git a/apps/api/test/modules/actions/billing-webhook.test.ts b/apps/api/test/modules/actions/billing-webhook.test.ts index 1eb01e4dc..8e547c7b2 100644 --- a/apps/api/test/modules/actions/billing-webhook.test.ts +++ b/apps/api/test/modules/actions/billing-webhook.test.ts @@ -450,7 +450,7 @@ describe("Actions namespace preparation before checkout", () => { name: "Openship Actions", slug: f.namespace, resource_limits: { - max_vms: 0, + max_workspaces: 0, max_vcpus: 0, max_ram_mb: 0, max_disk_gb: 0, diff --git a/apps/api/test/modules/analytics/analytics-config-push.test.ts b/apps/api/test/modules/analytics/analytics-config-push.test.ts index 4ec55da96..bef7892dc 100644 --- a/apps/api/test/modules/analytics/analytics-config-push.test.ts +++ b/apps/api/test/modules/analytics/analytics-config-push.test.ts @@ -32,12 +32,10 @@ vi.mock("@repo/db", () => ({ })); vi.mock("@repo/platform/engine/lib/project-analytics", () => ({ - resolveProjectTrafficSources: vi.fn(async (id: string) => h.sourcesByProject[id] ?? []), -})); -vi.mock("@repo/platform/engine/lib/edge-management", () => ({ postEdgeMgmt: vi.fn(async (serverId: string | null, path: string, body: unknown) => { h.pushes.push({ serverId, path, body }); }), + resolveProjectTrafficSources: vi.fn(async (id: string) => h.sourcesByProject[id] ?? []), })); const { pushProjectAnalyticsConfig, reconcileAnalyticsConfig } = await import( diff --git a/apps/api/test/modules/analytics/geo-rollup.test.ts b/apps/api/test/modules/analytics/geo-rollup.test.ts index 84a37d471..d195752ba 100644 --- a/apps/api/test/modules/analytics/geo-rollup.test.ts +++ b/apps/api/test/modules/analytics/geo-rollup.test.ts @@ -34,8 +34,6 @@ vi.mock("@repo/db", () => ({ vi.mock("@repo/platform/engine/lib/project-analytics", () => ({ resolveProjectTrafficSources: vi.fn(async () => h.sources), -})); -vi.mock("@repo/platform/engine/lib/edge-management", () => ({ fetchMgmt: vi.fn(async (_serverId: string, path: string) => { for (const [prefix, value] of h.mgmt) { if (path.startsWith(prefix)) return value; diff --git a/apps/api/test/modules/analytics/overview-traffic.test.ts b/apps/api/test/modules/analytics/overview-traffic.test.ts index e88094fc4..6efa816cf 100644 --- a/apps/api/test/modules/analytics/overview-traffic.test.ts +++ b/apps/api/test/modules/analytics/overview-traffic.test.ts @@ -28,8 +28,6 @@ vi.mock("@repo/db", () => ({ repos: { vi.mock("@repo/platform/engine/lib/project-analytics", () => ({ resolveProjectTrafficSources: async (_id: string, options: { domain?: string }) => h.sources.filter((source) => !options.domain || source.domain === options.domain), -})); -vi.mock("@repo/platform/engine/lib/edge-management", () => ({ fetchMgmt: h.readLive, })); vi.mock("@repo/platform/engine/modules/system/analytics-scraper", () => ({ scrapeServerIfStale: h.scrape })); diff --git a/apps/api/test/modules/analytics/scrape-to-db.test.ts b/apps/api/test/modules/analytics/scrape-to-db.test.ts index 4ac9d46f4..d8c9fde24 100644 --- a/apps/api/test/modules/analytics/scrape-to-db.test.ts +++ b/apps/api/test/modules/analytics/scrape-to-db.test.ts @@ -87,7 +87,7 @@ vi.mock("@repo/db", () => ({ }, })); -vi.mock("@repo/platform/engine/lib/edge-management", () => ({ +vi.mock("@repo/platform/engine/lib/project-analytics", () => ({ fetchMgmt: vi.fn(async (_serverId: string, path: string) => path.startsWith("/analytics/totals") ? h.totals : null, ), @@ -209,7 +209,7 @@ describe("retained minute history", () => { const now = Math.floor(Date.now() / 60_000); h.lastMinute = lastOffset === null ? null : now + lastOffset; const edge = new Map([[now - 300, 40], [now - 2, 8], [now, 3]]); - const { postMgmtJson } = await import("@repo/platform/engine/lib/edge-management"); + const { postMgmtJson } = await import("@repo/platform/engine/lib/project-analytics"); const collect = async (_server: string, _path: string, body: unknown) => { const request = body as { domains: Array<{ domain: string; from: number; to: number }> }; const { from, to } = request.domains[0]; diff --git a/apps/api/test/modules/apps/app-install-routing.test.ts b/apps/api/test/modules/apps/app-install-routing.test.ts index 980fffc58..992ecf782 100644 --- a/apps/api/test/modules/apps/app-install-routing.test.ts +++ b/apps/api/test/modules/apps/app-install-routing.test.ts @@ -703,41 +703,3 @@ it("deduplicates an interpolated secret also declared as a generated config fiel vars.filter((v: { key: string }) => v.key === "OPENSHIP_ADMIN_PASSWORD"), ).toHaveLength(1); }); - -function templateWithConfigPorts() { - const template = structuredClone(getAppTemplate("convex")!); - template.id = "config-ports-test"; - template.configFields = [ - { key: "HOST_PORT", service: "backend", label: "Host port", default: "8181" }, - { key: "HTTP_PORT", service: "backend", label: "Container port", default: "8080" }, - ]; - template.services!.find(service => service.name === "backend")!.ports = ["{{config:HOST_PORT}}:{{config:HTTP_PORT}}/tcp"]; - customTemplateMock.mockResolvedValue({ template }); - return template; -} - -it("substitutes port defaults before validating routes and preserves the cached template", async () => { - const template = templateWithConfigPorts(); - await installApp(ctx, { templateId: template.id, routes: [{ service: "backend", port: 8080, mode: "port" }] }); - expect(payloadFor("backend")?.ports).toEqual(["0.0.0.0:8181:8080/tcp"]); - expect(template.services![0]!.ports).toEqual(["{{config:HOST_PORT}}:{{config:HTTP_PORT}}/tcp"]); -}); - -it("uses supplied port values for both route validation and service creation", async () => { - const template = templateWithConfigPorts(); - await installApp(ctx, { - templateId: template.id, config: { HOST_PORT: "9191", HTTP_PORT: "9090" }, - routes: [{ service: "backend", port: 9090, mode: "port" }], - }); - expect(payloadFor("backend")?.ports).toEqual(["0.0.0.0:9191:9090/tcp"]); -}); - -it("uses resolved authored ports when undoing port-only access on an adopted draft", async () => { - const template = templateWithConfigPorts(); - draftMock.mockResolvedValue({ id: "p1", slug: "draft", name: "Draft" }); - listServicesMock.mockResolvedValue(template.services!.map(service => ({ id: `svc-${service.name}`, name: service.name, ports: service.name === "backend" ? ["0.0.0.0:8181:8080/tcp"] : [] }))); - await installApp(ctx, { templateId: template.id, routes: [{ service: "backend", port: 8080, mode: "custom", customDomain: "ports.example.com" }] }); - expect(updateServiceMock).toHaveBeenCalledWith(ctx, "p1", "svc-backend", expect.objectContaining({ ports: ["8181:8080/tcp"] })); - expect(createServiceMock).not.toHaveBeenCalled(); - expect(setEnvMock).not.toHaveBeenCalled(); -}); diff --git a/apps/api/test/modules/apps/cloud-install-cleanup.integration.test.ts b/apps/api/test/modules/apps/cloud-install-cleanup.integration.test.ts index 383127280..f92314c2a 100644 --- a/apps/api/test/modules/apps/cloud-install-cleanup.integration.test.ts +++ b/apps/api/test/modules/apps/cloud-install-cleanup.integration.test.ts @@ -105,7 +105,7 @@ beforeEach(async () => { } const method = init?.method ?? "GET"; requests.push(`${method} ${url.pathname}`); - if (url.pathname === "/vms" && method === "POST") { + if (url.pathname === "/workspace" && method === "POST") { if (createMode === "quota" || createMode === "legacy-quota") { return Response.json( { success: false, code: "NAMESPACE_LIMIT_REACHED" }, @@ -133,27 +133,27 @@ beforeEach(async () => { return Response.json( { code: "CREATE_FAILED", - details: { vm_id: workspace.id }, + details: { workspace_id: workspace.id }, }, { status: 422 }, ); } - if (url.pathname === "/vms" && method === "GET") { + if (url.pathname === "/workspace" && method === "GET") { return Response.json({ success: true, - vms: [...workspaces.values()], + workspaces: [...workspaces.values()], total: workspaces.size, limit: 100, page: 1, }); } - const workspaceId = url.pathname.match(/^\/vms\/([^/]+)$/)?.[1]; - const retryId = url.pathname.match(/^\/vms\/([^/]+)\/provisioning\/retry$/)?.[1]; + const workspaceId = url.pathname.match(/^\/workspace\/([^/]+)$/)?.[1]; + const retryId = url.pathname.match(/^\/workspace\/([^/]+)\/provisioning\/retry$/)?.[1]; if (retryId && method === "POST") { const workspace = workspaces.get(retryId)!; workspace.status = "running"; workspace.provisioning.state = "ready"; - return Response.json({ success: true, vm: workspace }); + return Response.json({ success: true, workspace }); } if (url.pathname.endsWith("/lifecycle/permanent") && method === "POST") return Response.json({ success: true }); @@ -162,7 +162,7 @@ beforeEach(async () => { if (deleting.has(workspaceId)) workspaces.delete(workspaceId); const workspace = workspaces.get(workspaceId); return workspace - ? Response.json({ success: true, vm: workspace }) + ? Response.json({ success: true, workspace }) : Response.json({ code: "NOT_FOUND" }, { status: 404 }); } if (workspaceId && method === "DELETE") { diff --git a/apps/api/test/modules/billing/billing-sdk-parity.test.ts b/apps/api/test/modules/billing/billing-sdk-parity.test.ts index 84c5b6010..4dea70ffd 100644 --- a/apps/api/test/modules/billing/billing-sdk-parity.test.ts +++ b/apps/api/test/modules/billing/billing-sdk-parity.test.ts @@ -1,5 +1,4 @@ import { savedOffer as subscriptionOffer, savedMetadata as subscriptionMetadata } from "../../helpers/saved-cloud-offer"; -import { providerBillingFixture } from "../../helpers/oblien-vm-billing"; import capacityCatalog from "../../fixtures/oblien-capacity-catalog.json"; import { monthlyCloudBilling } from "../../helpers/monthly-cloud-offer"; import managedTransfer from "../../fixtures/oblien-managed-transfer.json"; @@ -61,7 +60,7 @@ vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ }), }), getOblienClient: () => ({ - vms: { getQuota: provider.quota, get: provider.workspace }, + workspaces: { getQuota: provider.quota, get: provider.workspace }, namespaces: { ensure: provider.namespaces, get: provider.resourceRead, @@ -193,8 +192,8 @@ describe("billing through the same SDK and HTTP application operations", () => { // Exercise the actual SDK/validator before the shared application operation; // a mock entitlement alone missed the provider's newly included transfer. const billing = new OblienBillingApi({ clientId: "test-id", clientSecret: "test-secret", - fetch: (async url => Response.json(providerBillingFixture(new URL(String(url)).pathname === "/v1/billing/balance" - ? monthly.balance : monthly.entitlement))) as typeof fetch }); + fetch: (async url => Response.json(new URL(String(url)).pathname === "/billing/balance" + ? monthly.balance : monthly.entitlement)) as typeof fetch }); provider.subscriptions.set(selected.namespace!, monthly.subscription); provider.entitlement.mockImplementation(async namespace => namespace === selected.namespace ? billing.getEntitlement(namespace) : { success: true, namespace, tierId: null, status: "credit_exhausted", @@ -268,13 +267,13 @@ describe("billing through the same SDK and HTTP application operations", () => { data: { slug, effective_resource_limits: { - max_vms: 12, + max_workspaces: 12, max_total_vcpus: 8, max_total_ram_mb: 16384, max_total_disk_gb: 256, }, allocated_resource_usage: { - vms: 0, + workspaces: 0, vcpus: 0, ram_mb: 0, disk_gb: 0, @@ -731,26 +730,6 @@ describe("billing through the same SDK and HTTP application operations", () => { expect(provider.checkout).not.toHaveBeenCalled(); }); - it("accepts empty request streams for optional billing actions", async () => { - const owner = await seedOwner(), c = await clients(owner); - await c.native.getState(); - const namespace = (await billingWorkspace(owner)).namespace!; - provider.subscriptions.set(namespace, { - tierId: "hobby", status: "active", billingInterval: "yearly", periodStart: "2026-09-01T00:00:00Z", periodEnd: "2027-09-01T00:00:00Z", - cancelAtPeriodEnd: false, canceledAt: null, - }); - for (const endpoint of ["portal", "cancel", "resume"]) { - const response = await app.request(`/api/billing/${endpoint}`, { - method: "POST", headers: { Authorization: `Bearer ${owner.token}`, "X-Organization-Id": owner.orgId }, body: "", - }); - expect(response.status).toBe(200); - } - expect(provider.portal).toHaveBeenCalledWith(expect.objectContaining({ namespace })); - expect(provider.cancel).toHaveBeenCalledWith(namespace); - expect(provider.resume).toHaveBeenCalledWith(namespace); - expect(provider.checkout).not.toHaveBeenCalled(); - }); - it("isolates portal and renewal operations across tenants and exposes pending cancellation", async () => { const owner = await seedOwner(), other = await seedOwner(), c = await clients(owner), otherClients = await clients(other); await c.native.getState(); diff --git a/apps/api/test/modules/billing/credit-alert.test.ts b/apps/api/test/modules/billing/credit-alert.test.ts index 437b90dae..d02ca881d 100644 --- a/apps/api/test/modules/billing/credit-alert.test.ts +++ b/apps/api/test/modules/billing/credit-alert.test.ts @@ -23,19 +23,13 @@ const input = { eventType: "namespace.quota.threshold", eventId: "evt1", timestamp: "2026-09-28T00:00:00Z", - data: { namespace: "tenant", service: "vm_compute", threshold: 95, alert: { limit: 4000 } }, + data: { namespace: "tenant", service: "workspace_vm", threshold: 95, alert: { limit: 4000 } }, organizationId: "org-a", dashboardUrl: "https://app.openship.io", entitlement: state(), }; describe("provider credit alerts", () => { - it("accepts a pre-cutover delivery without changing its idempotency key", () => { - const result = creditAlertNotification({ - ...input, data: { ...input.data, service: "workspace_vm" }, - }); - expect(result).toEqual(creditAlertNotification(input)); - }); it("uses current provider numbers and an organization-bound billing link", () => { const result = creditAlertNotification(input)!; expect(result.payload.message).toContain("95%"); diff --git a/apps/api/test/modules/cloud-execution-access.test.ts b/apps/api/test/modules/cloud-execution-access.test.ts index 1812cf15b..3402dfe1e 100644 --- a/apps/api/test/modules/cloud-execution-access.test.ts +++ b/apps/api/test/modules/cloud-execution-access.test.ts @@ -120,7 +120,7 @@ describe("Cloud relays cannot substitute Cloud feature access for host administr expect(await response.json()).toMatchObject({ data: { token: "provider-secret" } }); }); - it.each(["owner", "admin"])( + it.each(["owner", "admin", "member"])( "preserves existing full host access for the %s role", async (role) => { await db.update(schema.member).set({ role }).where(eq(schema.member.id, memberId)); @@ -129,17 +129,6 @@ describe("Cloud relays cannot substitute Cloud feature access for host administr }, ); - it("denies members host credentials through both Cloud relay selectors", async () => { - await db.update(schema.member).set({ role: "member" }).where(eq(schema.member.id, memberId)); - for (const path of ["token", `token?serverId=${serverId}`, "resource-proxy", `resource-proxy?serverId=${serverId}`]) { - const response = await post(path, { operation: "list" }); - expect(response.status, await response.clone().text()).toBe(404); - } - expect(h.token).not.toHaveBeenCalled(); - expect(h.namespace).not.toHaveBeenCalled(); - expect(h.pages).not.toHaveBeenCalled(); - }); - it("does not bootstrap a server or credentials for an empty organization without host authority", async () => { actor = await seedOwner(); const membership = (await repos.member.find(actor.orgId, actor.userId))!; @@ -222,7 +211,7 @@ describe("Cloud relays cannot substitute Cloud feature access for host administr it.each([ ["preflight", {}], - ["pages", { vm_id: "vm-own", path: "/private", name: "export", slug: "export" }], + ["pages", { workspace_id: "vm-own", path: "/private", name: "export", slug: "export" }], ["pages/enable", { slug: "own-page" }], ["pages/disable", { slug: "own-page" }], ["pages/delete", { slug: "own-page" }], diff --git a/apps/api/test/modules/cloud-workspaces/lifecycle.integration.test.ts b/apps/api/test/modules/cloud-workspaces/lifecycle.integration.test.ts index 34e133682..44dfb01c6 100644 --- a/apps/api/test/modules/cloud-workspaces/lifecycle.integration.test.ts +++ b/apps/api/test/modules/cloud-workspaces/lifecycle.integration.test.ts @@ -218,7 +218,7 @@ beforeEach(async () => { expiresAt: "2030-01-01T00:00:00Z", })), }, - vms: { + workspaces: { create: vi.fn(async (input: any) => { const existing = [...vms.values()].find((vm) => vm.slug === input.slug); if (existing) return existing; @@ -242,7 +242,7 @@ beforeEach(async () => { return vm; }), list: vi.fn(async () => ({ - vms: [...vms.values()], + workspaces: [...vms.values()], total: vms.size, page: 1, limit: 100, @@ -260,9 +260,9 @@ beforeEach(async () => { vms.delete(id); return { success: true }; }), - vm: (id: string) => ({ + workspace: (id: string) => ({ id, - get: () => h.client.vms.get(id), + get: () => h.client.workspaces.get(id), lifecycle: { makePermanent: async () => {} }, resources: { update: (input: any) => h.client.resize(id, input) }, delete: () => h.client.delete(id), @@ -433,7 +433,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { expect((await request("POST", `/${workspace.id}/ensure`, undefined, stranger)).status).toBe( 404, ); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); const invalid = await request("POST", "", { name: "Broken", mode: "shared", @@ -468,7 +468,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { }); expect(observed.isError).toBe(false); expect(JSON.parse(observed.content[0].text).managed.operation.status).toBe("succeeded"); - expect(h.client.vms.create).toHaveBeenCalledTimes(1); + expect(h.client.workspaces.create).toHaveBeenCalledTimes(1); const outsider = await seedOwner(); expect( @@ -492,7 +492,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { }) ).isError, ).toBe(true); - expect(h.client.vms.create).toHaveBeenCalledTimes(1); + expect(h.client.workspaces.create).toHaveBeenCalledTimes(1); }); it("provisions on paid reconciliation and reuses one host across simultaneous project deployments", async () => { await syncOblienEntitlement(owner.orgId, { workspaceId: workspace.id }); @@ -512,7 +512,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { ); expect(targets[0]?.workspaceId).toBe(targets[1]?.workspaceId); expect(targets.map((target) => target.ownerWorkspaceId)).toEqual([workspace.id, workspace.id]); - expect(h.client.vms.create).toHaveBeenCalledTimes(1); + expect(h.client.workspaces.create).toHaveBeenCalledTimes(1); expect(h.client.resize).not.toHaveBeenCalled(); expect(vms.get(targets[0]!.workspaceId).resources).toMatchObject({ cpus: 1, @@ -544,7 +544,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect( resolveSnapshotTarget(saved, { serverId: otherServer.id, deployTarget: "server" }), ).rejects.toMatchObject({ code: "CLOUD_WORKSPACE_TARGET_CONFLICT" }); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("places bare and Docker projects on managed servers without provisioning a second host", async () => { const sdk = await nativeShip(); @@ -557,7 +557,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { const docker = await sdk.projects.create({ name: "Docker app", serverId: selected.serverId }); for (const project of [bare, docker]) expect(await repos.project.findById(project.id)).toMatchObject({ serverId: selected.serverId, workspaceId: selected.id }); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("installs and previews catalog apps on the selected managed server without creating a project VM", async () => { subscribe("starter"); @@ -583,7 +583,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect( stranger.apps.install({ templateId: "redis", serverId: server.id }), ).rejects.toMatchObject({ statusCode: 404 }); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("carries one managed server through source staging, scan and project creation", async () => { const sdk = await nativeShip(); @@ -614,15 +614,15 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect(stranger.sources.scan(staged.sessionId)).rejects.toMatchObject({ statusCode: 404, }); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); } finally { const session = deleteFolderSession(staged.sessionId); if (session?.stagingDir) await rm(session.stagingDir, { recursive: true, force: true }); } }); it("recovers a lost provider create response with the same request and disk", async () => { - const create = h.client.vms.create.getMockImplementation()!; - h.client.vms.create.mockImplementationOnce(async (input: any) => { + const create = h.client.workspaces.create.getMockImplementation()!; + h.client.workspaces.create.mockImplementationOnce(async (input: any) => { await create(input); throw new Error("create response lost"); }); @@ -642,7 +642,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { ); expect(vms.size).toBe(1); expect( - new Set(h.client.vms.create.mock.calls.map(([input]: any[]) => input.idempotency_key)) + new Set(h.client.workspaces.create.mock.calls.map(([input]: any[]) => input.idempotency_key)) .size, ).toBe(1); expect( @@ -651,7 +651,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { ).toBe([...vms.keys()][0]); }); it("stops after three provisioning failures and durably escalates once without retrying the host", async () => { - h.client.vms.create.mockRejectedValue(new AppError("Hosts are temporarily at capacity", 503, "CLOUD_CAPACITY_UNAVAILABLE")); + h.client.workspaces.create.mockRejectedValue(new AppError("Hosts are temporarily at capacity", 503, "CLOUD_CAPACITY_UNAVAILABLE")); expect((await request("POST", `/${workspace.id}/ensure`)).status).toBe(202); await drainBackgroundWork(); const createTicket = vi.spyOn(repos.cloudSupport, "create").mockRejectedValueOnce(new Error("support database temporarily unavailable")); @@ -673,7 +673,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { expect(await repos.cloudSupport.find(ticketId)).toMatchObject({ status: "open", ownerUserId: owner.userId }); expect(await repos.cloudSupport.messages(ticketId)).toHaveLength(2); await processWorkspaceOperation(workspace.id); - expect(h.client.vms.create).toHaveBeenCalledTimes(3); + expect(h.client.workspaces.create).toHaveBeenCalledTimes(3); expect(await repos.cloudSupport.messages(ticketId)).toHaveLength(2); expect((await repos.cloudWorkspace.listPendingOperations()).map(row => row.id)).not.toContain(workspace.id); createTicket.mockRestore(); @@ -707,7 +707,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { }, }); expect((await deliver("bad-signature")).status).toBe(401); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); expect(await db.select().from(schema.cloudCustomerEmail).where(eq(schema.cloudCustomerEmail.organizationId, owner.orgId))).toEqual([]); h.billing.getCheckout.mockImplementation(async () => ({ checkout: { @@ -731,7 +731,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { .map(mail => mail.kind).sort()).toEqual(["invoice", "purchase"]); expect(result[2]).toMatchObject({ fulfilled: true, creditsGranted: 0 }); await drainBackgroundWork(); - expect(h.client.vms.create).toHaveBeenCalledTimes(1); + expect(h.client.workspaces.create).toHaveBeenCalledTimes(1); expect((await repos.cloudWorkspace.findById(workspace.id))?.operation?.status).toBe( "succeeded", ); @@ -764,7 +764,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect(client.resize(server.id, { revision: "a".repeat(64), confirmRestart: true, idempotencyKey: randomUUID() })) .rejects.toMatchObject({ code: "TOKEN_READ_ONLY" }); } - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("recovers one draft and its server across concurrent native/HTTP creates and scopes retries by organization", async () => { @@ -779,7 +779,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { const stranger = await seedOwner(); const other = await (await clients(stranger))[0]!.createManaged(input); expect(other.id).not.toBe(created[0]!.id); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("never recreates a deleted purchase identity or its old provider namespace", async () => { @@ -791,14 +791,14 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect(native!.createManaged(input)).rejects.toMatchObject({ code: "CLOUD_WORKSPACE_PURCHASE_REMOVED" }); await expect(remote!.createManaged(input)).rejects.toMatchObject({ code: "CLOUD_WORKSPACE_PURCHASE_REMOVED" }); expect(await repos.cloudWorkspace.findById(created.id)).toBeUndefined(); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("does not provision, stop or change the entitlement mirror when provider billing is unavailable", async () => { await syncOblienEntitlement(owner.orgId, { workspaceId: workspace.id }); h.billing.getEntitlement.mockRejectedValue(new Error("Billing temporarily unavailable")); const response = await request("POST", `/${workspace.id}/ensure`); expect(response.status).toBe(500); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); expect(h.client.delete).not.toHaveBeenCalled(); expect((await repos.cloudWorkspace.findById(workspace.id))?.subscriptionStatus).toBe("active"); }); @@ -917,7 +917,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { expect((await request("POST", `/${workspace.id}/ensure`)).body.code).toBe( "CLOUD_SERVER_LINK_REQUIRED", ); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); }); @@ -1757,7 +1757,7 @@ describe("managed server free-domain scope", () => { expect((await repos.domain.listByProject(id)).map(domain => domain.hostname)).toContain(`routed-${entry}.opsh.io`); expect(h.billing.getEntitlement).toHaveBeenCalled(); expect(h.billing.getEntitlement.mock.calls.every(([namespace]: [string]) => namespace === workspace.namespace)).toBe(true); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("uses the selected metered server's entitlement and allowance", async () => { subscribe("starter"); @@ -1780,7 +1780,7 @@ describe("managed server free-domain scope", () => { expect((await repos.service.listByProject(project.id))[0]?.domain).toBe("metered-service"); expect(h.billing.getEntitlement).toHaveBeenCalled(); expect(h.billing.getEntitlement.mock.calls.every(([namespace]: [string]) => namespace === workspace.namespace)).toBe(true); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it.each(["ensure", "update"] as const)("refuses excess free domains before %s changes an existing project's fields", async entry => { const sdk = await nativeShip(); @@ -1823,7 +1823,7 @@ describe("managed server free-domain scope", () => { envVars: {}, })).rejects.toMatchObject({ code: "PLAN_UPGRADE_REQUIRED", reason: "free-subdomain-limit" }); expect((await repos.deployment.listByProject(project.id)).rows).toEqual([]); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("does not count dormant routes outside an exclusive service deployment", async () => { const project = await addProject("Exclusive routes"); @@ -1839,7 +1839,7 @@ describe("managed server free-domain scope", () => { envVars: {}, serviceIds: [selected.id], strictServiceScope: true, }); expect(queued).toMatchObject({ status: "queued" }); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("keeps existing free routes editable when the server's allowance is full", async () => { const sdk = await nativeShip(); @@ -1875,7 +1875,7 @@ describe("managed server free-domain scope", () => { expect(await repos.service.findById(service.id)).toMatchObject({ domain: "routed-console-updated" }); expect(h.billing.getEntitlement).toHaveBeenCalled(); expect(h.billing.getEntitlement.mock.calls.every(([namespace]: [string]) => namespace === workspace.namespace)).toBe(true); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("does not use a paid sibling's allowance or write a project for an unauthorized server", async () => { const sdk = await nativeShip(); @@ -1890,6 +1890,6 @@ describe("managed server free-domain scope", () => { await expect(sdk.projects.create({ ...input, serverId: foreignServer.id })).rejects.toMatchObject({ statusCode: 404 }); expect((await repos.projectGroup.listByOrganization(owner.orgId, { page: 1, perPage: 1 })).total).toBe(0); expect(h.billing.getEntitlement).not.toHaveBeenCalled(); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); }); diff --git a/apps/api/test/modules/credentials/credential-selector-secret.test.ts b/apps/api/test/modules/credentials/credential-selector-secret.test.ts index 9e66b3c8c..ccf2f96c0 100644 --- a/apps/api/test/modules/credentials/credential-selector-secret.test.ts +++ b/apps/api/test/modules/credentials/credential-selector-secret.test.ts @@ -4,7 +4,6 @@ const h = vi.hoisted(() => ({ credentialRepo: { findById: vi.fn(), nameTaken: vi.fn(async () => false), - create: vi.fn(), update: vi.fn(), }, verifyCredentialValues: vi.fn(), @@ -23,10 +22,7 @@ vi.mock("@repo/platform/engine/modules/credentials/verify", () => ({ verifyCredentialValues: h.verifyCredentialValues, })); -import { - createCredential, - updateCredential, -} from "@repo/platform/engine/modules/credentials/credential.service"; +import { updateCredential } from "@repo/platform/engine/modules/credentials/credential.service"; const stored = (overrides: Record = {}) => ({ id: "cred_1", @@ -102,24 +98,3 @@ describe("credential destination changes", () => { ); }); }); - -it("saves an unchallenged registry login without a verification date on create or rotation", async () => { - h.verifyCredentialValues.mockResolvedValue({ - ok: true, - unverifiedReason: "Registry allows anonymous access.", - }); - h.credentialRepo.create.mockImplementation(async (data) => stored(data)); - const values = { username: "operator", secret: "new-token" }; - - const created = await createCredential("org_1", { - provider: "docker-registry", - name: "Production registry", - selector: "registry.example.com", - values, - }); - const updated = await updateCredential("org_1", "cred_1", { values }); - - for (const credential of [created, updated]) { - expect(credential).toMatchObject({ status: "active", lastVerifiedAt: null }); - } -}); diff --git a/apps/api/test/modules/credentials/registry-recheck.test.ts b/apps/api/test/modules/credentials/registry-recheck.test.ts deleted file mode 100644 index 67c070287..000000000 --- a/apps/api/test/modules/credentials/registry-recheck.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -import { beforeEach, describe, expect, it, vi } from "vitest"; - -const h = vi.hoisted(() => ({ - credential: { findActive: vi.fn(), findById: vi.fn(), recordVerification: vi.fn() }, - verify: vi.fn(), - providerAccess: vi.fn(), -})); -vi.mock("@repo/db", () => ({ repos: { credential: h.credential } })); -vi.mock("@repo/platform/engine/lib/provision-lock", () => ({ - createProvisionLock: () => ({ run: (work: () => Promise) => work() }), -})); -vi.mock("@repo/platform/engine/lib/credential-encryption", () => ({ - encryptSecretField: (value: string) => value, - decryptSecretField: (value: string) => value, -})); -vi.mock("@repo/platform/engine/modules/credentials/verify", () => ({ - hasVerifier: () => true, - verifyCredentialValues: h.verify, -})); -vi.mock("@repo/platform/engine/modules/credentials/connection-authorization", () => ({ - getProviderAccess: h.providerAccess, -})); -import { - recheckRejectedRegistryCredential, - verifyCredential, -} from "@repo/platform/engine/modules/credentials/credential.service"; - -const row = { - id: "credential-a", - organizationId: "org-a", - provider: "docker-registry", - name: "Production GHCR", - selector: "ghcr.io", - publicFields: { username: "owner" }, - secretsEnc: JSON.stringify({ secret: "old-secret" }), - status: "active", - lastVerifiedAt: new Date("2026-10-01"), - lastError: null, - createdAt: new Date("2026-10-01"), - updatedAt: new Date("2026-10-01"), -}; -beforeEach(() => { - vi.resetAllMocks(); - h.credential.findActive.mockResolvedValue(row); - h.credential.findById.mockResolvedValue(row); -}); - -describe("rechecking a registry after an image access denial", () => { - it("records a rejected login only against the exact credential checked in the owning org", async () => { - const verdict = { - ok: false, - credentialRejected: true, - reason: "ghcr.io rejected these credentials.", - }; - h.verify.mockResolvedValue(verdict); - await recheckRejectedRegistryCredential("org-a", "https://GHCR.IO/"); - expect(h.credential.findActive).toHaveBeenCalledWith("org-a", "docker-registry", "ghcr.io"); - expect(h.verify).toHaveBeenCalledWith(expect.objectContaining({ id: "docker-registry" }), { - selector: "ghcr.io", - publicFields: { username: "owner" }, - secrets: { secret: "old-secret" }, - }); - expect(h.credential.recordVerification).toHaveBeenCalledWith(row, verdict); - }); - - it("keeps a valid login active when one package denies access", async () => { - h.verify.mockResolvedValue({ ok: true }); - await recheckRejectedRegistryCredential("org-a", "ghcr.io"); - expect(h.credential.recordVerification).toHaveBeenCalledWith(row, { ok: true }); - }); - - it.each(["timed out", "TLS failed", "answered 429", "answered 503"])( - "does not invalidate credentials when the check %s", - async (reason) => { - h.verify.mockResolvedValue({ ok: false, reason }); - await recheckRejectedRegistryCredential("org-a", "ghcr.io"); - expect(h.credential.recordVerification).not.toHaveBeenCalled(); - }, - ); - - it("leaves the saved status and date alone when the registry allows anonymous access", async () => { - h.verify.mockResolvedValue({ ok: true, unverifiedReason: "Registry allows anonymous access." }); - await recheckRejectedRegistryCredential("org-a", "ghcr.io"); - await expect(verifyCredential("org-a", row.id)).rejects.toThrow( - "Registry allows anonymous access.", - ); - expect(h.credential.recordVerification).not.toHaveBeenCalled(); - }); - - it("reports a manual registry outage without disabling the login", async () => { - h.verify.mockResolvedValue({ ok: false, reason: "Registry unavailable." }); - await expect(verifyCredential("org-a", row.id)).rejects.toThrow("Registry unavailable."); - expect(h.credential.recordVerification).not.toHaveBeenCalled(); - }); - - it("does not look up another organization's credentials or probe an unsaved registry", async () => { - h.credential.findActive.mockResolvedValue(undefined); - await recheckRejectedRegistryCredential("org-b", "ghcr.io"); - expect(h.credential.findActive).toHaveBeenCalledExactlyOnceWith( - "org-b", - "docker-registry", - "ghcr.io", - ); - expect(h.verify).not.toHaveBeenCalled(); - expect(h.credential.recordVerification).not.toHaveBeenCalled(); - }); - - it("manual verification returns the replacement row when credentials rotate during a check", async () => { - h.verify.mockImplementation(async () => { - h.credential.findById.mockResolvedValue({ - ...row, - secretsEnc: JSON.stringify({ secret: "new-secret" }), - }); - return { ok: false, credentialRejected: true }; - }); - const result = await verifyCredential("org-a", row.id); - expect(h.credential.recordVerification).toHaveBeenCalledWith(row, { - ok: false, - credentialRejected: true, - }); - expect(result.status).toBe("active"); - expect(JSON.stringify(result)).not.toMatch(/old-secret|new-secret/); - }); - - it("records manual verification against the refreshed OAuth token", async () => { - const before = { - ...row, - provider: "railway", - selector: null, - publicFields: { authorization: "oauth" }, - secretsEnc: JSON.stringify({ apiToken: "expired-token" }), - status: "invalid", - }; - const refreshed = { ...before, secretsEnc: JSON.stringify({ apiToken: "refreshed-token" }) }; - h.credential.findById.mockResolvedValueOnce(before).mockResolvedValue(refreshed); - h.verify.mockResolvedValue({ ok: true }); - - await verifyCredential("org-a", row.id); - - expect(h.providerAccess).toHaveBeenCalledWith("org-a", row.id, { allowInvalid: true }); - expect(h.verify).toHaveBeenCalledWith(expect.objectContaining({ id: "railway" }), { - selector: null, - publicFields: { authorization: "oauth" }, - secrets: { apiToken: "refreshed-token" }, - }); - expect(h.credential.recordVerification).toHaveBeenCalledWith(refreshed, { ok: true }); - }); -}); diff --git a/apps/api/test/modules/credentials/verify-ssrf.test.ts b/apps/api/test/modules/credentials/verify-ssrf.test.ts index b1a915734..d04c3e312 100644 --- a/apps/api/test/modules/credentials/verify-ssrf.test.ts +++ b/apps/api/test/modules/credentials/verify-ssrf.test.ts @@ -13,13 +13,13 @@ import { verifyCredentialValues } from "@repo/platform/engine/modules/credential const provider = getCredentialProvider("docker-registry")!; -function response(status: number, headers: Record = {}, body: unknown = {}) { +function response(status: number, headers: Record = {}) { return { status, ok: status >= 200 && status < 300, headers, - text: async () => JSON.stringify(body), - json: async () => body, + text: async () => "", + json: async () => ({}), bytes: async () => Buffer.alloc(0), }; } @@ -46,7 +46,7 @@ describe("container-registry credential verification SSRF policy", () => { ); expect(h.safeFetch).toHaveBeenCalledWith("http://127.0.0.1:8080/v2/", { - sameOriginRedirectsOnly: true, + headers: undefined, timeoutMs: 10_000, allowHttp: false, allowPrivate: false, @@ -76,7 +76,7 @@ describe("container-registry credential verification SSRF policy", () => { ["registry.example.com", "https://registry.example.com/token"], ])("preserves trusted token authentication for %s", async (registry, realm) => { h.safeFetch.mockResolvedValueOnce(response(401, { "www-authenticate": `Bearer realm="${realm}"` })) - .mockResolvedValueOnce(response(200, {}, { token: "fixture-token" })); + .mockResolvedValueOnce(response(200)); expect(await verifyCredentialValues(provider, values(registry))).toEqual({ ok: true }); expect(h.safeFetch).toHaveBeenNthCalledWith(2, realm, expect.objectContaining({ headers: { authorization: `Basic ${Buffer.from("operator:registry-token").toString("base64")}` }, @@ -102,7 +102,6 @@ describe("container-registry credential verification SSRF policy", () => { }, allowPrivate: false, maxRedirects: 3, - sameOriginRedirectsOnly: true, }), ); }); @@ -111,9 +110,8 @@ describe("container-registry credential verification SSRF policy", () => { h.env.CLOUD_MODE = false; h.safeFetch.mockResolvedValueOnce(response(200)); - await expect(verifyCredentialValues(provider, values("localhost:5000"))).resolves.toMatchObject({ + await expect(verifyCredentialValues(provider, values("localhost:5000"))).resolves.toEqual({ ok: true, - unverifiedReason: expect.stringContaining("could not verify"), }); expect(h.safeFetch).toHaveBeenCalledWith( @@ -124,64 +122,6 @@ describe("container-registry credential verification SSRF policy", () => { }); describe("registry connection errors", () => { - it("checks the registry login without a repository scope supplied in the challenge", async () => { - h.safeFetch - .mockResolvedValueOnce(response(401, { - "www-authenticate": 'Bearer realm="https://registry.example.com/token?scope=repository:private:pull",service="registry.example.com"', - })) - .mockResolvedValueOnce(response(200, {}, { access_token: "fixture-token" })); - - expect(await verifyCredentialValues(provider, values("registry.example.com"))).toEqual({ ok: true }); - expect(h.safeFetch).toHaveBeenNthCalledWith( - 2, - "https://registry.example.com/token?service=registry.example.com", - expect.objectContaining({ sameOriginRedirectsOnly: true }), - ); - }); - - it.each(["{}", "invalid JSON"])( - "does not verify a login from a successful response without a token (%s)", - async (body) => { - h.safeFetch - .mockResolvedValueOnce( - response(401, { - "www-authenticate": 'Bearer realm="https://registry.example.com/token"', - }), - ) - .mockResolvedValueOnce({ ...response(200), text: async () => body }); - - await expect( - verifyCredentialValues(provider, values("registry.example.com")), - ).resolves.toMatchObject({ - ok: false, - reason: expect.stringContaining("did not return a registry token"), - }); - }, - ); - - it("treats a blocked authentication redirect as inconclusive", async () => { - h.safeFetch - .mockResolvedValueOnce(response(401, { "www-authenticate": 'Basic realm="registry"' })) - .mockResolvedValueOnce(response(302, { location: "https://other.example.com/login" })); - - const result = await verifyCredentialValues(provider, values("registry.example.com")); - expect(result).toEqual({ ok: false, reason: expect.stringContaining("answered 302") }); - }); - - it.each([ - 'Bearer realm="https://registry.example.com/token",service="registry.example.com"', - 'Basic realm="registry"', - ])("distinguishes a rejected login from an unavailable authentication endpoint: %s", async challenge => { - for (const status of [401, 403, 429, 500, 503]) { - h.safeFetch.mockResolvedValueOnce(response(401, { "www-authenticate": challenge })) - .mockResolvedValueOnce(response(status)); - const result = await verifyCredentialValues(provider, values("registry.example.com")); - expect(result.ok).toBe(false); - expect("credentialRejected" in result).toBe(status === 401); - } - for (const [url] of h.safeFetch.mock.calls) expect(new URL(url).searchParams.has("scope")).toBe(false); - }); - it.each([ ["probe", undefined, "ERR_TLS_CERT_ALTNAME_INVALID"], [ diff --git a/apps/api/test/modules/customer-email/signup.integration.test.ts b/apps/api/test/modules/customer-email/signup.integration.test.ts index c18513ec7..b5dddde33 100644 --- a/apps/api/test/modules/customer-email/signup.integration.test.ts +++ b/apps/api/test/modules/customer-email/signup.integration.test.ts @@ -52,9 +52,6 @@ it("welcomes a real SaaS email signup only after the real OTP verification flow" password: "valid-test-password-1234!", }); expect(signup.status, await signup.clone().text()).toBe(200); - expect(h.send).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ to: email })); - const initialMail = h.send.mock.calls.at(-1)![0] as { subject: string }; - const initialCode = initialMail.subject.match(/\b\d{6}\b/)![0]; const [user] = await db.select().from(schema.user).where(eq(schema.user.email, email)); expect(user!.emailVerified).toBe(false); expect( @@ -66,7 +63,14 @@ it("welcomes a real SaaS email signup only after the real OTP verification flow" h.send.mockClear(); expect(await service().flush()).toMatchObject({ sent: 0 }); expect(h.send).not.toHaveBeenCalled(); - const verified = await request("/email-otp/verify-email", { email, otp: initialCode }); + const otp = await request("/email-otp/send-verification-otp", { + email, + type: "email-verification", + }); + expect(otp.status, await otp.clone().text()).toBe(200); + const mail = h.send.mock.calls.at(-1)![0] as { subject: string }; + const code = mail.subject.match(/\b\d{6}\b/)![0]; + const verified = await request("/email-otp/verify-email", { email, otp: code }); expect(verified.status, await verified.clone().text()).toBe(200); h.send.mockClear(); await service().flush(); @@ -166,100 +170,3 @@ it("welcomes a verified Google signup through the same outbox without repeating fetch.mockRestore(); } }, 30_000); - -it("keeps one OAuth account on repeat signup and privately explains how to sign in", async () => { - const email = `existing-google-${randomUUID()}@example.com`; - const id = randomUUID(); - await db - .insert(schema.user) - .values({ id, email, name: "Existing Google customer", emailVerified: true }); - await db - .insert(schema.account) - .values({ id: randomUUID(), accountId: randomUUID(), providerId: "google", userId: id }); - h.send.mockClear(); - for (const attempt of [1, 2]) { - const signup = await request("/sign-up/email", { - name: "Signup retry", - email, - password: `attempt-${attempt}-not-an-account-password!`, - }); - expect(signup.status, await signup.clone().text()).toBe(200); - expect((await signup.json()).token).toBeNull(); - } - expect(await db.select().from(schema.user).where(eq(schema.user.email, email))).toHaveLength(1); - expect(await db.select().from(schema.account).where(eq(schema.account.userId, id))).toMatchObject( - [{ providerId: "google", password: null }], - ); - expect(h.send).toHaveBeenCalledWith( - expect.objectContaining({ to: email, subject: "Sign in to your OpenShip account" }), - ); - const notice = h.send.mock.calls.at(-1)![0] as { text: string }; - expect(notice.text).toContain("already have"); - expect(notice.text).toContain("Google"); - const login = await request("/sign-in/email", { - email, - password: "attempt-2-not-an-account-password!", - }); - expect(login.status).toBe(401); - // A provider-only customer can add a password only after proving mailbox - // ownership through the existing recovery flow, never from duplicate signup. - h.send.mockClear(); - const reset = await request("/email-otp/request-password-reset", { email }); - expect(reset.status, await reset.clone().text()).toBe(200); - const resetMail = h.send.mock.calls.at(-1)![0] as { subject: string }; - const otp = resetMail.subject.match(/\b\d{6}\b/)![0]; - const password = "verified-mailbox-owner-new-password-1234!"; - const changed = await request("/email-otp/reset-password", { email, otp, password }); - expect(changed.status, await changed.clone().text()).toBe(200); - expect((await request("/sign-in/email", { email, password })).status).toBe(200); - expect(await db.select().from(schema.account).where(eq(schema.account.userId, id))).toHaveLength( - 2, - ); -}, 30_000); - -it("resends verification on an unverified signup retry without replacing its password", async () => { - const email = `retry-signup-${randomUUID()}@example.com`; - const password = "first-signup-password-1234!"; - const first = await request("/sign-up/email", { email, name: "Signup customer", password }); - expect(first.status).toBe(200); - h.send.mockClear(); - const retry = await request("/sign-up/email", { - email, - name: "Second attempt", - password: "different-retry-password-1234!", - }); - expect(retry.status).toBe(200); - expect(h.send).toHaveBeenCalledWith(expect.objectContaining({ to: email })); - const mail = h.send.mock.calls.at(-1)![0] as { subject: string }; - const otp = mail.subject.match(/\b\d{6}\b/)![0]; - const verified = await request("/email-otp/verify-email", { email, otp }); - expect(verified.status, await verified.clone().text()).toBe(200); - expect((await request("/sign-in/email", { email, password })).status).toBe(200); - expect( - (await request("/sign-in/email", { email, password: "different-retry-password-1234!" })).status, - ).toBe(401); - expect(await db.select().from(schema.user).where(eq(schema.user.email, email))).toHaveLength(1); -}, 30_000); - -it("recovers an initial delivery failure by retrying signup with the same account", async () => { - const email = `smtp-retry-${randomUUID()}@example.com`; - const password = "original-signup-password-1234!"; - h.send.mockClear(); - h.send.mockResolvedValueOnce(false); - const first = await request("/sign-up/email", { email, name: "SMTP retry", password }); - // Better Auth logs background delivery failures while keeping its generic response. - expect(first.status).toBe(200); - h.send.mockClear(); - const retry = await request("/sign-up/email", { - email, - name: "SMTP retry", - password: "a-different-retry-password-1234!", - }); - expect(retry.status, await retry.clone().text()).toBe(200); - expect(h.send).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ to: email })); - const mail = h.send.mock.calls.at(-1)![0] as { subject: string }; - const otp = mail.subject.match(/\b\d{6}\b/)![0]; - expect((await request("/email-otp/verify-email", { email, otp })).status).toBe(200); - expect((await request("/sign-in/email", { email, password })).status).toBe(200); - expect(await db.select().from(schema.user).where(eq(schema.user.email, email))).toHaveLength(1); -}, 30_000); diff --git a/apps/api/test/modules/data-transfer-errors.test.ts b/apps/api/test/modules/data-transfer-errors.test.ts index 14997c725..03088939a 100644 --- a/apps/api/test/modules/data-transfer-errors.test.ts +++ b/apps/api/test/modules/data-transfer-errors.test.ts @@ -3,12 +3,7 @@ import { Hono } from "hono"; import { db, schema, RestoreSchemaError } from "@repo/db"; import { readSseTerminalEvent } from "@repo/core"; -const h = vi.hoisted(() => ({ importInstance: vi.fn(), finalizeFileUpload: vi.fn(), exportInstance: vi.fn(), previewInstanceExport: vi.fn() })); -vi.mock("../../src/modules/system/data-transfer/export.service", async (original) => ({ - ...await original(), - exportInstance: h.exportInstance, - previewInstanceExport: h.previewInstanceExport, -})); +const h = vi.hoisted(() => ({ importInstance: vi.fn(), finalizeFileUpload: vi.fn() })); vi.mock("../../src/modules/system/data-transfer/import.service", async (original) => ({ ...await original(), importInstance: h.importInstance, @@ -21,21 +16,15 @@ vi.mock("../../src/modules/system/data-transfer/file-upload.service", async (ori import { importInstanceHandler, finalizeFileUploadStreamHandler, - exportInstanceHandler, - previewInstanceExportHandler, } from "../../src/modules/system/data-transfer/data-transfer.controller"; -import { handleApiError } from "../../src/middleware/error-handler"; const app = new Hono(); -app.onError(handleApiError); app.use("*", async (c, next) => { c.set("ctx" as never, { userId: "transfer-admin", organizationId: "workspace" } as never); await next(); }); app.post("/import", importInstanceHandler); app.post("/uploads/:sessionId/finalize", finalizeFileUploadStreamHandler); -app.post("/export", exportInstanceHandler); -app.post("/export/preview", previewInstanceExportHandler); beforeAll(async () => { await db.insert(schema.user).values({ @@ -44,22 +33,9 @@ beforeAll(async () => { }); beforeEach(() => { - vi.clearAllMocks(); const error = new RestoreSchemaError(new Error("private SQL: credential=must-not-leak")); h.importInstance.mockRejectedValue(error); h.finalizeFileUpload.mockRejectedValue(error); - h.exportInstance.mockResolvedValue({ dump: { tables: {} } }); - h.previewInstanceExport.mockResolvedValue({}); -}); - -it.each(["/export", "/export/preview"])("does not turn a malformed selection into a full instance export at %s", async path => { - const response = await app.request(path, { - method: "POST", headers: { "content-type": "application/json" }, body: '{"selection":', - }); - expect(response.status).toBe(400); - expect(await response.json()).toMatchObject({ code: "INVALID_JSON" }); - expect(h.exportInstance).not.toHaveBeenCalled(); - expect(h.previewInstanceExport).not.toHaveBeenCalled(); }); it.each(["json", "stream"])("returns an actionable schema error through %s without exposing database values", async (transport) => { diff --git a/apps/api/test/modules/deployments/build-duration.test.ts b/apps/api/test/modules/deployments/build-duration.test.ts index 8d1e2cecb..026f4db36 100644 --- a/apps/api/test/modules/deployments/build-duration.test.ts +++ b/apps/api/test/modules/deployments/build-duration.test.ts @@ -13,6 +13,7 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: vi.fn() }, })); vi.mock("@repo/platform/engine/lib/audit-emitter", () => ({ audit: { recordAsync: vi.fn() } })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn() })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(), })); diff --git a/apps/api/test/modules/deployments/build.service.test.ts b/apps/api/test/modules/deployments/build.service.test.ts index 2418e5500..446d660d3 100644 --- a/apps/api/test/modules/deployments/build.service.test.ts +++ b/apps/api/test/modules/deployments/build.service.test.ts @@ -657,36 +657,6 @@ describe("buildConfigSnapshot: roles", () => { }); describe("triggerDeployment", () => { - it("reviews a source edit then deploys only the exact revision accepted in the modal", async () => { - repos.project.findById.mockResolvedValue(baseProject({ - composePath: "compose.yml", localPath: null, - gitProvider: "github", gitUrl: "https://github.com/acme/app.git", gitOwner: "acme", gitRepo: "app", - })); - const original = composeServices[0]!; - repos.service.listByProject.mockResolvedValue([ - { ...original, projectId: "project-1", importedSpec: toComposeSpec(original) }, - ]); - const source = [{ ...original, image: "ghcr.io/acme/review:2" }]; - resolveProjectInfo.mockResolvedValue({ services: source }); - let review: any; - try { await triggerDeployment(ctx, { projectId: "project-1", smartRoute: true }); } - catch (error) { review = error; } - expect(review).toMatchObject({ code: "COMPOSE_REVIEW_REQUIRED", details: { - composeRevision: composeSourceRevision("project-1", source), - composeChanges: { changed: [original.name] }, - composeDiff: [expect.objectContaining({ name: original.name, fields: expect.arrayContaining([ - expect.objectContaining({ path: "image", after: "ghcr.io/acme/review:2" }), - ]) })], - } }); - expect(repos.deployment.create).not.toHaveBeenCalled(); - expect(repos.service.reconcileFromCompose).not.toHaveBeenCalled(); - await expect(triggerDeployment(ctx, { projectId: "project-1", composeRevision: "f".repeat(64) })).rejects.toMatchObject({ code: "COMPOSE_REVIEW_REQUIRED" }); - expect(repos.deployment.create).not.toHaveBeenCalled(); - await triggerDeployment(ctx, { projectId: "project-1", smartRoute: true, composeRevision: review.details.composeRevision }); - expect(repos.service.reconcileFromCompose).toHaveBeenCalledExactlyOnceWith("project-1", source); - expect(repos.deployment.create).toHaveBeenCalledOnce(); - }); - beforeEach(() => { vi.clearAllMocks(); queueActionDeployment.mockReset().mockResolvedValue(undefined); diff --git a/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts b/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts index 83322bdd5..58861d410 100644 --- a/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts +++ b/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts @@ -250,7 +250,7 @@ it("deploys Cloud Compose endpoints, internal paths, generated files and contain const configurations: Array> = []; const publishRoute = vi.fn(async () => undefined); const pullImage = vi.fn(async () => undefined); - const resolveRoutingTarget = vi.fn(async (id: string, port: number) => ({ vm: "shared-vm", + const resolveRoutingTarget = vi.fn(async (id: string, port: number) => ({ workspace: "shared-vm", port: id === "web-container" ? (port === 8080 ? 30001 : 30002) : 30003 })); const runtime = Object.assign(Object.create(CloudDockerRuntime.prototype), { name: "docker", workspaceId: "shared-vm", projectId: "p1", unsupportedComposeKeys: new Set(), @@ -314,8 +314,8 @@ it("deploys Cloud Compose endpoints, internal paths, generated files and contain serviceId: "svc-api", allocatedResources: { containerId: "api-container", cpuCores: 2, memoryMb: 2048 }, })); expect(publishRoute).toHaveBeenCalledWith("app.opsh.io", 30001, false, expect.objectContaining({ routes: [ - { match: { path: "/api/", type: "prefix" }, action: { kind: "proxy", vm: "shared-vm", port: 30003 } }, - { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "shared-vm", port: 30001 } }, + { match: { path: "/api/", type: "prefix" }, action: { kind: "proxy", workspace: "shared-vm", port: 30003 } }, + { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "shared-vm", port: 30001 } }, ] })); }); @@ -1599,8 +1599,7 @@ describe("compose deploy — host channel unavailable", () => { expect(base.deployServiceWorkload).not.toHaveBeenCalled(); }); - it.each([null, "server-original"])("refuses ambiguous duplicate containers on %s before repairing or activating anything", async (serverId) => { - h.previousDeployment.meta = { serverId }; + it("refuses ambiguous duplicate containers before repairing or activating anything", async () => { const base = startingRuntime(); const liveContainer = (id: string, name: string) => ({ id, @@ -1666,18 +1665,11 @@ describe("compose deploy — host channel unavailable", () => { { executor: {} as CommandExecutor, hostPortTarget: localHostPortTarget, - serverId: serverId ?? undefined, }, ), - ).rejects.toMatchObject({ - code: "SERVICE_CONTAINER_CONFLICT", - message: expect.stringMatching(/more than one container matching active service "api".*no service activation/i), - details: { - projectId: "p1", serviceId: "svc-api", serviceName: "api", - containerNames: ["openship-app-api-a", "openship-app-api-b"], - serverId, workspaceId: null, - }, - }); + ).rejects.toThrow( + /more than one container matching active service "api".*no service activation/i, + ); expect(h.updateServiceDeployment).not.toHaveBeenCalled(); expect(h.allocateAndReservePinnedHostPort).not.toHaveBeenCalled(); diff --git a/apps/api/test/modules/deployments/compose-noop-settle.test.ts b/apps/api/test/modules/deployments/compose-noop-settle.test.ts index 7a522fa77..100da4d26 100644 --- a/apps/api/test/modules/deployments/compose-noop-settle.test.ts +++ b/apps/api/test/modules/deployments/compose-noop-settle.test.ts @@ -94,6 +94,7 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ vi.mock("../../../src/lib/audit", () => ({ audit: { recordAsync: (_c: unknown, e: { eventType: string }) => h.audits.push(e.eventType) }, })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: async () => {} })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: async () => {}, })); diff --git a/apps/api/test/modules/deployments/compose-review-diff.test.ts b/apps/api/test/modules/deployments/compose-review-diff.test.ts deleted file mode 100644 index 3f6990317..000000000 --- a/apps/api/test/modules/deployments/compose-review-diff.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { describe, expect, it, vi } from "vitest"; - -vi.mock("@repo/platform/engine/config/env", () => ({ env: { BETTER_AUTH_SECRET: "test-review-secret" } })); -// Use the production spec normalizer and merge, without booting a database. -vi.mock("@repo/db", async () => { - const module = await import("../../../../../packages/db/src/repos/service.repo"); - return { toComposeSpec: module.toComposeSpec, composeSpecDiff: module.composeSpecDiff }; -}); - -import { toComposeSpec, type Service } from "@repo/db"; -import type { ComposeReview } from "@repo/contracts"; -import { assertComposeReviewed, composeSourceRevision, type SourceService } from "@repo/platform/engine/modules/deployments/compose-review"; - -function row(name: string, spec: SourceService): Service { - return { name, kind: "compose", importedSpec: toComposeSpec(spec) } as Service; -} -function review(rows: Service[], source: SourceService[], revision?: string): ComposeReview { - try { - assertComposeReviewed("project", rows, source, revision); - } catch (error) { - return (error as { details: ComposeReview }).details; - } - throw new Error("Expected review gate"); -} - -describe("Compose review details", () => { - it("shows changed fields, added and removed services from the import baseline", () => { - const rows = [ - row("worker", { name: "worker", image: "worker:1", command: "node old.js" }), - row("legacy", { name: "legacy", image: "redis:7", volumes: ["data:/data"] }), - ]; - const source = [ - { name: "worker", image: "worker:2", command: "node new.js" }, - { name: "cache", image: "redis:8" }, - ]; - const result = review(rows, source); - expect(result.composeChanges).toEqual({ - added: ["cache"], - changed: ["worker"], - removed: ["legacy"], - }); - expect(result.composeDiff[0]!.fields).toEqual( - expect.arrayContaining([ - { path: "image", before: "worker:1", after: "worker:2" }, - { path: "command", before: '["node","old.js"]', after: '["node","new.js"]' }, - ]), - ); - expect(result.composeRevision).toBe(composeSourceRevision("project", source)); - expect(() => - assertComposeReviewed("project", rows, source, result.composeRevision), - ).not.toThrow(); - // Review is pure, never a reconciliation or removal. - expect(rows[0]!.importedSpec?.image).toBe("worker:1"); - expect(rows[1]!.importedSpec?.volumes).toEqual(["data:/data"]); - }); - - it("refuses an obsolete revision and one reviewed for another project", () => { - const rows = [row("worker", { name: "worker", image: "worker:1" })]; - const source = [{ name: "worker", image: "worker:2" }]; - const first = review(rows, source); - const newer = [{ name: "worker", image: "worker:3" }]; - expect(review(rows, newer, first.composeRevision).composeDiff[0]!.fields).toContainEqual({ - path: "image", - before: "worker:1", - after: "worker:3", - }); - expect(() => - assertComposeReviewed("other-project", rows, source, first.composeRevision), - ).toThrow(); - }); - - it("compares secret changes before masking, without leaking values or defaults", () => { - const old = { - name: "worker", - environment: { ODD_NAME: "old-private-value", REMOVED: "removed-private-value" }, - buildArgs: { CREDENTIAL: "old-build-secret" }, - }; - const next = { - name: "worker", - environment: { ODD_NAME: "new-private-value", ADDED: "added-private-value" }, - buildArgs: { CREDENTIAL: "new-build-secret" }, - command: "node app.js --token new-private-value", - }; - const result = review([row("worker", old)], [next]); - const serialized = JSON.stringify(result); - for (const value of [ - ...Object.values(old.environment), - ...Object.values(next.environment), - "old-build-secret", - "new-build-secret", - ]) - expect(serialized).not.toContain(value); - expect(result.composeDiff[0]!.fields).toContainEqual({ - path: "environment.ODD_NAME", - before: "••••••••", - after: "••••••••", - }); - expect(result.composeDiff[0]!.fields).toContainEqual({ - path: "environment.REMOVED", - before: "••••••••", - after: null, - }); - }); - - it.each([ - ["--password", "private-password"], - ["--token", "private-token"], - ["--api-key", "private-key"], - ["--requirepass", "private-redis-password"], - ["--token", 'private-"quoted"-token'], - ])("masks inline %s arguments before returning the diff", (flag, secret) => { - const source = [{ name: "worker", commandArgv: ["worker", flag, secret] }]; - const result = review([row("worker", { name: "worker", commandArgv: ["worker"] })], source); - expect(JSON.stringify(result)).not.toContain(secret); - }); - - it.each(["-", ":-", "+", ":+", "?", ":?", ":-${OTHER:-nested}-"])("masks defaults in Compose expressions using %s", (operator) => { - const expression = "registry/app:${TAG" + operator + "private-default}"; - const source = [{ name: "worker", image: "registry/app:private-default", advanced: { - imageTemplate: { expression, unresolvedVariables: [] }, - } }]; - const result = review([row("worker", { name: "worker", image: "registry/app:old" })], source); - expect(JSON.stringify(result)).not.toContain("private-default"); - }); - - it("ignores interpolation values, legacy baselines and independently added services", () => { - const source = { - name: "worker", - image: "worker:1", - environment: { MODE: "old" }, - environmentTemplates: { MODE: "${MODE}" }, - }; - const rows = [ - row("worker", source), - { name: "manual", kind: "compose", importedSpec: null } as Service, - ]; - expect(() => - assertComposeReviewed("project", rows, [{ ...source, environment: { MODE: "new" } }]), - ).not.toThrow(); - }); - - it("distinguishes an inherited build argument from a removed argument", () => { - const original = { name: "worker", buildArgs: { INHERITED: null, REMOVED: null } }; - const result = review( - [row("worker", original)], - [{ name: "worker", buildArgs: { INHERITED: "literal" } }], - ); - expect(result.composeDiff[0]!.fields).toEqual( - expect.arrayContaining([ - { path: "build.args.INHERITED", before: "null", after: "••••••••" }, - { path: "build.args.REMOVED", before: "null", after: null }, - ]), - ); - }); -}); diff --git a/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts b/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts index 87d2be394..e847bd792 100644 --- a/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts +++ b/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts @@ -35,7 +35,6 @@ function jsonbRejection(value: unknown): string | null { } const h = vi.hoisted(() => ({ - registryRecheck: vi.fn(), finishError: null as Error | null, /** Rejects every status write, whatever the payload (a dead connection). */ rejectAllStatusWrites: false, @@ -51,11 +50,6 @@ const h = vi.hoisted(() => ({ finishedLogs: [] as unknown[][], })); -vi.mock("@repo/platform/engine/modules/credentials/credential.service", async importOriginal => ({ - ...await importOriginal(), - recheckRejectedRegistryCredential: h.registryRecheck, -})); - vi.mock("@repo/db", () => ({ repos: { deployment: { @@ -119,6 +113,7 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ }, })); vi.mock("../../../src/lib/audit", () => ({ audit: { recordAsync: () => {} } })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: async () => {} })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: async () => {}, })); @@ -155,35 +150,6 @@ function deeplyNestedHostile(): Record { const statusPairs = () => h.statusWrites.map((w) => `${w.id}:${w.status}`); -describe("registry checks after deployment failure", () => { - it("publishes the original failure before rechecking the owning organization's registry", async () => { - h.registryRecheck.mockImplementation(async () => { - expect(statusPairs()).toContain("dep_1:failed"); - expect(h.sessionStatuses).toContainEqual(expect.objectContaining({ id: "dep_1", status: "failed" })); - }); - await onFailure(ctxFor(), "Image denied", 1000, { - errorCode: "REGISTRY_ACCESS_DENIED", errorDetails: { registry: "ghcr.io" }, - }); - expect(h.registryRecheck).toHaveBeenCalledExactlyOnceWith("org_1", "ghcr.io"); - expect(h.statusWrites.at(-1)?.extra).toMatchObject({ errorCode: "REGISTRY_ACCESS_DENIED", errorMessage: "Image denied" }); - }); - - it("does not replace the pull failure if the diagnostic check fails", async () => { - h.registryRecheck.mockRejectedValue(new Error("Verification unavailable")); - const ctx = ctxFor(); - await expect(onFailure(ctx, "Image denied", 1000, { - errorCode: "REGISTRY_ACCESS_DENIED", errorDetails: { registry: "ghcr.io" }, - })).resolves.toBeUndefined(); - expect(ctx.settled).toBe("failed"); - expect(h.statusWrites.at(-1)?.extra?.errorMessage).toBe("Image denied"); - }); - - it("does not probe credentials for unrelated failures", async () => { - await onFailure(ctxFor(), "Host unavailable", 1000, { errorCode: "HOST_UNREACHABLE" }); - expect(h.registryRecheck).not.toHaveBeenCalled(); - }); -}); - function loggerSpy() { const lines: Array<{ message: string; level?: string }> = []; return { @@ -193,7 +159,6 @@ function loggerSpy() { } beforeEach(() => { - h.registryRecheck.mockReset(); h.finishError = null; h.rejectAllStatusWrites = false; h.containerIdError = null; diff --git a/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts b/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts index ee521b560..3fd2f63b7 100644 --- a/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts +++ b/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts @@ -13,6 +13,7 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: vi.fn() }, })); vi.mock("@repo/platform/engine/lib/audit-emitter", () => ({ audit: { recordAsync: vi.fn() } })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn() })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(), })); diff --git a/apps/api/test/modules/deployments/native-sdk-parity.test.ts b/apps/api/test/modules/deployments/native-sdk-parity.test.ts index a95cbadb0..a247e0c27 100644 --- a/apps/api/test/modules/deployments/native-sdk-parity.test.ts +++ b/apps/api/test/modules/deployments/native-sdk-parity.test.ts @@ -6,7 +6,7 @@ import { join } from "node:path"; import { createShip } from "@repo/sdk/native"; import { OpenshipClient } from "@repo/sdk/client"; import type { VerifiedIdentity } from "@repo/platform"; -import { ENV_MASK, normalizeEdgeResponse, type AppTemplate } from "@repo/core"; +import { ENV_MASK, type AppTemplate } from "@repo/core"; import type { BackupDestination as StoredBackupDestination } from "@repo/db"; import type { ProjectInfo } from "@repo/platform/engine/modules/deployments/prepare.service"; import { alice, storedDeployment } from "../../../../../packages/platform/test/fixtures"; @@ -436,15 +436,6 @@ const native = (organizationId = "org-a") => organizationId, }); -it.each(["redeploy", "pin"])("rejects broken JSON before a deployment %s can use default options", async action => { - const response = await app.request(`/api/deployments/dep-project-a/${action}`, { - method: "POST", headers: { "Content-Type": "application/json" }, body: "{invalid", - }); - expect(response.status).toBe(400); - expect(await response.json()).toMatchObject({ code: "INVALID_JSON" }); - expect(h.trigger).not.toHaveBeenCalled(); -}); - describe("deployment preparation HTTP/native parity", () => { const remote = () => new OpenshipClient({ baseUrl: "http://openship.test", organizationId: "org-a", fetch: ((url, init) => app.request(url as string, init)) as typeof fetch }); let info: ProjectInfo; @@ -1885,19 +1876,6 @@ describe("domain and DNS HTTP/native parity", () => { expect(await contextFor("domain-b", "provision")).toBeNull(); } }); - it("accepts empty verification options but never turns malformed JSON into a batch scan", async () => { - const data = { verified: 0, stillPending: 0, failed: 0, total: 0, details: [] }; - h.domainPending.mockResolvedValue(data); - for (const body of [undefined, "", "{invalid", '{"limit":"all"}']) { - const response = await app.request("/api/domains/verify-pending", { - method: "POST", headers: { "Content-Type": "application/json" }, - ...(body === undefined ? {} : { body }), - }); - expect(response.status).toBe(body ? 400 : 200); - if (!body) expect(await response.json()).toEqual({ data }); - } - expect(h.domainPending).toHaveBeenCalledTimes(2); - }); it("keeps certificate contents out of audit and refuses uploads to provider-managed Cloud domains", async () => { h.domainUpload.mockResolvedValue({ domain: "app.example.com", sslStatus: "active", issuer: "manual" }); const local = await native(); @@ -1919,8 +1897,8 @@ describe("domain and DNS HTTP/native parity", () => { const local = await native(); h.members.set("org-a:alice", { id: "member-a", role: "member" }); for (const dns of [remote().dns, local.dns]) { - await expect(dns.addCredential(input)).rejects.toMatchObject({ code: "NOT_FOUND" }); - await expect(dns.removeCredential("dns-a")).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect(dns.addCredential(input)).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(dns.removeCredential("dns-a")).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); } expect(h.dnsAdd).not.toHaveBeenCalled(); expect(h.dnsRemove).not.toHaveBeenCalled(); @@ -1932,9 +1910,6 @@ describe("domain and DNS HTTP/native parity", () => { }); describe("project routing HTTP/native parity", () => { - beforeEach(() => { - for (const id of ["project-a", "project-b", "project-sibling"]) h.projects.set(id, { ...h.projects.get(id)!, id }); - }); const remote = () => new OpenshipClient({ baseUrl: "http://openship.test", organizationId: "org-a", fetch: ((url, init) => app.request(url as string, init)) as typeof fetch }); const rule = { id: "rule-a", organizationId: "org-a", projectId: "project-a", domainId: "domain-a", pathPrefix: "/api", spec: { access: { methods: ["GET"] } }, enabled: true, createdAt: "2026-09-12T00:00:00.000Z", updatedAt: "2026-09-12T00:00:00.000Z" }; it("retains the sanitizer, project/domain checks, edge push, and one audit per facade", async () => { @@ -1961,41 +1936,6 @@ describe("project routing HTTP/native parity", () => { expect(h.ruleUpdate).not.toHaveBeenCalled(); for (const args of h.ruleRemove.mock.calls) expect(args).toEqual(["project-sibling", rule.id]); }); - it("validates domain responses in both facades and distinguishes persistence from edge application", async () => { - const local = await native(); - h.ruleCreate.mockImplementation(async data => ({ ...rule, ...data })); - const input = { domainId: "domain-a", pathPrefix: "/status", spec: { response: normalizeEdgeResponse({ body: "ready", headers: { "Cache-Control": "no-store" } }) } }; - for (const projects of [remote().projects, local.projects]) { - h.rulePush.mockResolvedValue(true); - expect(await projects.createRouteRule("project-a", input)).toMatchObject({ domainId: "domain-a", pathPrefix: "/status", edgeApplied: true, spec: { response: { match: "exact", status: 200, body: "ready", headers: { "cache-control": "no-store" } } } }); - h.rulePush.mockResolvedValue(false); - expect(await projects.createRouteRule("project-a", input)).toMatchObject({ edgeApplied: false }); - for (const invalid of [ - { ...input, domainId: null }, - { ...input, domainId: "domain-b" }, - { ...input, pathPrefix: "/_openship/auth" }, - { ...input, spec: { response: { ...input.spec.response, headers: { "X-Test": "ok\r\nInjected: yes" } } } }, - { ...input, spec: { ...input.spec, access: { methods: ["GET"] } } }, - ]) await expect(projects.createRouteRule("project-a", invalid)).rejects.toMatchObject({ statusCode: 400 }); - } - expect(h.ruleCreate).toHaveBeenCalledTimes(4); - }); - it("refuses unsupported edge targets and prevents changing a response to a foreign domain", async () => { - const local = await native(); - const input = { domainId: "domain-a", spec: { response: normalizeEdgeResponse({ body: "ready" }) } }; - for (const projects of [remote().projects, local.projects]) { - h.domains.set("domain-a", { projectId: "project-a", externalIngress: true }); - await expect(projects.createRouteRule("project-a", input)).rejects.toMatchObject({ code: "EDGE_RESPONSE_UNSUPPORTED" }); - h.domains.set("domain-a", { projectId: "project-a" }); - h.projects.set("project-a", { id: "project-a", organizationId: "org-a", workspaceId: "workspace" }); - await expect(projects.createRouteRule("project-a", input)).rejects.toMatchObject({ code: "EDGE_RESPONSE_UNSUPPORTED" }); - h.projects.set("project-a", { id: "project-a", organizationId: "org-a" }); - h.ruleGet.mockResolvedValue({ ...rule, spec: input.spec }); - await expect(projects.updateRouteRule("project-a", { ruleId: rule.id, domainId: "domain-b" })).rejects.toMatchObject({ code: "INVALID_DOMAIN" }); - } - expect(h.ruleCreate).not.toHaveBeenCalled(); - expect(h.ruleUpdate).not.toHaveBeenCalled(); - }); it("connects a primary domain through the same domain operation and retains legacy errors", async () => { h.domainCreate.mockResolvedValue({ domain: domainFixture(), records: { mode: "external", records: [] }, wwwError: "sibling is already owned" }); const local = await native(); @@ -2067,10 +2007,10 @@ describe("provider credential HTTP/native parity", () => { const local = await native(); h.members.set("org-a:alice", { id: "member-a", role: "member" }); for (const credentials of [local.credentials, remote().credentials]) { - await expect(credentials.create({ provider: "docker-registry", name: "Registry", values: { secret: "value" } })).rejects.toMatchObject({ code: "NOT_FOUND" }); - await expect(credentials.update("credential-a", { name: "Renamed" })).rejects.toMatchObject({ code: "NOT_FOUND" }); - await expect(credentials.remove("credential-a")).rejects.toMatchObject({ code: "NOT_FOUND" }); - await expect(credentials.verify("credential-a")).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect(credentials.create({ provider: "docker-registry", name: "Registry", values: { secret: "value" } })).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(credentials.update("credential-a", { name: "Renamed" })).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(credentials.remove("credential-a")).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(credentials.verify("credential-a")).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); } expect(h.credentialCreate).not.toHaveBeenCalled(); expect(h.credentialUpdate).not.toHaveBeenCalled(); @@ -2514,20 +2454,6 @@ describe("server HTTP/native parity", () => { expect(h.serverRemove).not.toHaveBeenCalled(); }); - it("denies ordinary members host execution through native, SDK and raw HTTP operations", async () => { - h.members.set("org-a:alice", { id: "member-a", role: "member" }); - const local = await native(); - for (const servers of [local.servers, remote().servers]) { - await expect(servers.exec("server-a", { command: "whoami" })).rejects.toMatchObject({ code: "NOT_FOUND" }); - } - const response = await app.request("/api/system/servers/server-a/exec", { - method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ command: "whoami" }), - }); - expect(response.status).toBe(404); - expect(h.serverWithExecutor).not.toHaveBeenCalled(); - expect(h.audit.mock.calls.filter(([event]) => event.eventType === "server.exec")).toHaveLength(0); - }); - it("returns the same partial teardown result and keeps HTTP 409", async () => { h.serverWorkloads.mockResolvedValue([{ id: "project-a", name: "Application", appTemplateId: null }]); h.projectTeardown.mockResolvedValue({ rowDeleted: false, orphaned: [], unrecoverable: [{ error: "volume busy" }] }); @@ -2620,11 +2546,11 @@ describe("HTTP/native system parity", () => { for (const system of [local.system, remote().system]) { await expect(system.updateSettings({ productMode: "mail" })).rejects.toMatchObject({ statusCode: 403 }); await expect(system.updateEmailSettings({ host: null })).rejects.toMatchObject({ statusCode: 403 }); - await expect(system.resetSettings()).rejects.toMatchObject({ statusCode: role === "member" ? 404 : 403 }); + await expect(system.resetSettings()).rejects.toMatchObject({ statusCode: 403 }); await expect(system.health()).rejects.toMatchObject({ statusCode: 403 }); await expect(system.browse({ path: "/" })).rejects.toMatchObject({ statusCode: 403 }); await expect(system.listUntrackedEdgeSites()).rejects.toMatchObject({ statusCode: 403 }); - await expect(system.removeUntrackedEdgeSite({ hostname: "orphan.example.test" })).rejects.toMatchObject({ statusCode: role === "member" ? 404 : 403 }); + await expect(system.removeUntrackedEdgeSite({ hostname: "orphan.example.test" })).rejects.toMatchObject({ statusCode: 403 }); } } expect(h.settingsUpsert).not.toHaveBeenCalled(); @@ -2893,51 +2819,6 @@ describe("backup HTTP/native parity with retained policy services", () => { h.backupCancel.mockResolvedValue({ accepted: true, status: "applying", destructive: true, forced: false }); }); - it.each([ - ["/api/backup-policies/policy-a/run", { runId: "run-a", runIds: ["run-a"] }], - ["/api/backup-runs/run-a/protect", { ok: true, retentionLockedUntil: "2099-12-31T23:59:59.000Z" }], - ["/api/backup-runs/run-a/restore/prepare", { restoreId: "restore-a", confirmationToken: "in-force-token" }], - ])("accepts omitted and zero-byte options through %s", async (path, data) => { - for (const body of [undefined, "", "{}"]) { - const response = await app.request(path as string, { - method: "POST", headers: { "Content-Type": "application/json" }, - ...(body === undefined ? {} : { body }), - }); - expect(response.status).toBe(200); - expect(await response.json()).toEqual({ data }); - } - }); - - it.each([ - ["/api/backup-policies/policy-a/run", { serviceId: 42 }], - ["/api/backup-runs/run-a/protect", { protected: "false" }], - ["/api/backup-runs/run-a/restore/prepare", { mode: "wrong" }], - ])("rejects malformed JSON and invalid options before %s acts", async (path, invalid) => { - for (const body of ["{invalid", " ", "null", "[]", JSON.stringify(invalid)]) { - const response = await app.request(path as string, { - method: "POST", headers: { "Content-Type": "application/json" }, body, - }); - expect(response.status).toBe(400); - } - expect(h.backupEnqueue).not.toHaveBeenCalled(); - expect(h.backupRetentionLock).not.toHaveBeenCalled(); - expect(h.backupPrepare).not.toHaveBeenCalled(); - }); - - it("keeps empty backup actions scoped and restore confirmation required", async () => { - const post = (path: string) => app.request(path, { - method: "POST", headers: { "Content-Type": "application/json" }, body: "", - }); - expect((await post("/api/backup-restores/restore-a/apply")).status).toBe(400); - h.members.set("org-a:alice", { id: "member-a", role: "restricted" }); - h.grants.set("org-a:alice:backup_destination:destination-a", { permissions: ["admin"] }); - expect((await post("/api/backup-policies/policy-a/run")).status).toBe(404); - expect((await post("/api/backup-runs/run-a/restore/prepare")).status).toBe(404); - expect(h.backupEnqueue).not.toHaveBeenCalled(); - expect(h.backupPrepare).not.toHaveBeenCalled(); - expect(h.backupApply).not.toHaveBeenCalled(); - }); - it("preserves project-write enumeration while direct destination readers receive masked snapshots", async () => { h.members.set("org-a:alice", { id: "member-a", role: "restricted" }); h.grants.set("org-a:alice:backup_destination:destination-a", { permissions: ["read"] }); diff --git a/apps/api/test/modules/deployments/resource-guidance.test.ts b/apps/api/test/modules/deployments/resource-guidance.test.ts index 68b7f89ee..3e0533151 100644 --- a/apps/api/test/modules/deployments/resource-guidance.test.ts +++ b/apps/api/test/modules/deployments/resource-guidance.test.ts @@ -237,21 +237,3 @@ it("retains resource guidance for a published partial rollout without turning it errorDetails: { resourceIssue: "storage-full" }, }); }); - - -it.each([true, false])("restores a container conflict on a Cloud=%s attempt without relabeling it as capacity", async (cloud) => { - const ctx = await attempt(cloud); - const details = { - projectId: ctx.project.id, - serviceId: "app-service", - containerNames: ["app-current", "app-duplicate"], - serverId: ctx.project.serverId ?? "ssh-original", - workspaceId: ctx.project.workspaceId, - }; - await onFailure(ctx, "More than one container matches the active service", undefined, { - errorCode: "SERVICE_CONTAINER_CONFLICT", errorDetails: details, - }); - expect(await getBuildSessionStatus(ctx.dep.id)).toMatchObject({ - status: "failed", errorCode: "SERVICE_CONTAINER_CONFLICT", errorDetails: details, - }); -}); diff --git a/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts b/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts index 5d07a4e0f..5ab30154e 100644 --- a/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts +++ b/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts @@ -32,6 +32,9 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: vi.fn() }, })); vi.mock("../../../src/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/projects/cleanup-keep-set", () => ({ computeCleanupKeepSet: vi.fn(async () => ({ containers: new Set() })), })); diff --git a/apps/api/test/modules/deployments/server-github-prepare.integration.test.ts b/apps/api/test/modules/deployments/server-github-prepare.integration.test.ts index 4a02d4454..469499fba 100644 --- a/apps/api/test/modules/deployments/server-github-prepare.integration.test.ts +++ b/apps/api/test/modules/deployments/server-github-prepare.integration.test.ts @@ -1,5 +1,4 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { generateKeyPairSync } from "node:crypto"; import { Hono } from "hono"; // Keep all storage, permissions, encryption, readers and detection real. Only // the external GitHub API and the host's ambient gh identity are replaced. @@ -18,16 +17,10 @@ import { import { eq } from "@repo/db"; import { env } from "@repo/platform/engine/config/env"; import { encrypt } from "@repo/platform/engine/lib/encryption"; -import { encryptSecretField } from "@repo/platform/engine/lib/credential-encryption"; import { buildBackgroundContext } from "@repo/platform/engine/lib/background-context"; import { buildDependencies } from "@repo/platform/engine/modules/deployments/build.operations"; import { resolveBuildGitToken } from "@repo/platform/engine/modules/github/clone-auth"; -import { - githubFetch, - type GitHubFetchOptions, -} from "@repo/platform/engine/modules/github/github.auth"; import { OpenshipClient } from "@repo/sdk/client"; -import { parseDeploySource } from "@repo/core"; import { githubRoutes } from "../../../src/modules/github/github.routes"; import { deploymentRoutes } from "../../../src/modules/deployments/deployment.routes"; import { handleApiError } from "../../../src/middleware/error-handler"; @@ -39,9 +32,6 @@ const app = new Hono() .route("/api/github", githubRoutes); const origin = "https://openship.test"; const pat = "test-server-only-pat-never-returned"; -const appPrivateKey = generateKeyPairSync("rsa", { modulusLength: 2048 }) - .privateKey.export({ type: "pkcs8", format: "pem" }) - .toString(); const files: Record = { "package.json": JSON.stringify({ private: true, workspaces: ["apps/*"] }), "apps/web/package.json": JSON.stringify({ name: "web", scripts: { start: "node server.js" } }), @@ -53,59 +43,39 @@ let requests: { path: string; token: string | null }[]; let rejectAccount: boolean; let providerStatus: number; let publicReadAllowed: boolean; -let appMintStatus: number; -let appReadStatus: number; beforeEach(async () => { env.CLOUD_MODE = false; owner = await seedOwner(); serverId = await seedServer(owner.orgId); await db.update(schema.servers).set({ isLocal: true }).where(eq(schema.servers.id, serverId)); - await setServerPat(serverId); + await repos.serverGithubAuth.upsert({ + serverId, + organizationId: owner.orgId, + mode: "token", + tokenEncrypted: encrypt(pat), + tokenSource: "pat", + }); requests = []; rejectAccount = false; providerStatus = 200; publicReadAllowed = false; - appMintStatus = 403; - appReadStatus = 403; vi.stubGlobal( "fetch", vi.fn(async (input: string | URL | Request, init?: RequestInit) => { const req = new Request(input, init); const url = new URL(req.url); if (url.origin === origin) return app.request(req); - if (url.origin !== "https://api.github.com" && url.origin !== "https://github.internal.test") + if (url.origin !== "https://api.github.com") throw new Error(`Unexpected network destination ${url.origin}`); const token = req.headers.get("authorization"); requests.push({ path: url.pathname, token }); - if (url.pathname.endsWith("/app/installations/42/access_tokens")) - return appMintStatus === 201 - ? Response.json( - { - token: "custom-app-token", - expires_at: new Date(Date.now() + 3_600_000).toISOString(), - }, - { status: 201 }, - ) - : Response.json( - { message: "Resource not accessible by integration" }, - { status: appMintStatus }, - ); - if (token === "Bearer custom-app-token" && appReadStatus !== 200) - return Response.json( - { message: "Resource not accessible by integration" }, - { status: appReadStatus }, - ); if (rejectAccount && token === "Bearer rejected-account-pat") return Response.json( { message: "Resource not accessible by personal access token" }, { status: 403 }, ); - if ( - token !== `Bearer ${pat}` && - token !== "Bearer custom-app-token" && - !(publicReadAllowed && token === null) - ) + if (token !== `Bearer ${pat}` && !(publicReadAllowed && token === null)) return Response.json({ message: "Not Found" }, { status: 404 }); if (providerStatus !== 200) return Response.json({ message: "Provider unavailable" }, { status: providerStatus }); @@ -176,160 +146,23 @@ const source = { branch: "main", }; -async function setServerPat(id: string, token = pat) { - await repos.serverGithubAuth.upsert({ - serverId: id, - organizationId: owner.orgId, - mode: "token", - tokenEncrypted: encrypt(token), - tokenSource: "pat", - }); -} - -async function addConnectedServerWithPat() { - const id = await seedServer(owner.orgId, "connected-deploy"); - await setServerPat(id); - return id; -} - async function addOtherServerToken() { const id = await seedServer(owner.orgId, "other-repository"); await db .update(schema.servers) .set({ createdAt: new Date("2000-01-01T00:00:00Z") }) .where(eq(schema.servers.id, id)); - await setServerPat(id, "unrelated-repository-pat"); + await repos.serverGithubAuth.upsert({ + serverId: id, + organizationId: owner.orgId, + mode: "token", + tokenEncrypted: encrypt("unrelated-repository-pat"), + tokenSource: "pat", + }); return id; } -async function addCustomApp(apiBaseUrl = "https://api.github.com") { - const appSource = await repos.gitSource.create({ - organizationId: owner.orgId, - name: "Workspace GitHub App", - appId: 9, - slug: "workspace-app", - apiBaseUrl, - webhookUrl: "https://openship.test/api/github/webhook", - secretsEnc: encryptSecretField( - JSON.stringify({ privateKeyPem: appPrivateKey, webhookSecret: "test-webhook-secret" }), - )!, - }); - await repos.gitInstallation.upsert({ - userId: owner.userId, - organizationId: owner.orgId, - sourceId: appSource.id, - owner: source.owner, - installationId: 42, - }); -} - describe("server PAT-only preparation through the real authenticated HTTP/SDK flow (#1500)", () => { - it.each([ - { explicit: false, mintStatus: 403 }, - { explicit: true, mintStatus: 403 }, - { explicit: false, mintStatus: 201 }, - { explicit: true, mintStatus: 201 }, - ])( - "scans through the SSH server PAT when its github.com App cannot read the repo (#1814): %j", - async ({ explicit, mintStatus }) => { - await db - .update(schema.servers) - .set({ isLocal: false }) - .where(eq(schema.servers.id, serverId)); - const foreign = await seedOwner(); - const foreignServer = await seedServer(foreign.orgId); - await db - .update(schema.servers) - .set({ isLocal: true }) - .where(eq(schema.servers.id, foreignServer)); - await addCustomApp(); - appMintStatus = mintStatus; - - const scan = await client().deployments.prepare({ - ...source, - ...(explicit ? { serverId } : {}), - }); - expect(scan.projectType).toBe("monorepo"); - expect(scan.monorepoApps?.map((app) => app.rootDirectory)).toEqual( - expect.arrayContaining(["apps/web", "apps/api"]), - ); - expect(requests).toEqual( - expect.arrayContaining([ - { path: "/repos/acme/private-workspace", token: `Bearer ${pat}` }, - { path: "/repos/acme/private-workspace/branches", token: `Bearer ${pat}` }, - { path: "/repos/acme/private-workspace/contents/package.json", token: `Bearer ${pat}` }, - ]), - ); - expect(JSON.stringify(scan)).not.toContain(pat); - expect(JSON.stringify(scan)).not.toContain(appPrivateKey); - }, - ); - it("keeps a working github.com App ahead of the server PAT", async () => { - await addCustomApp(); - appMintStatus = 201; - appReadStatus = 200; - expect((await client().deployments.prepare({ ...source, serverId })).projectType).toBe( - "monorepo", - ); - expect(requests.filter((req) => req.path.startsWith("/repos/"))).toEqual( - expect.arrayContaining([ - { path: "/repos/acme/private-workspace", token: "Bearer custom-app-token" }, - ]), - ); - expect(requests.every((req) => req.token !== `Bearer ${pat}`)).toBe(true); - }); - it("keeps Enterprise repositories on their own source when its App fails", async () => { - await addCustomApp("https://github.internal.test/api/v3"); - publicReadAllowed = true; - await expect(client().deployments.prepare({ ...source, serverId })).rejects.toMatchObject({ - status: 403, - body: { code: "GITHUB_TOKEN_REQUIRED" }, - }); - expect(requests).toEqual([ - { path: "/api/v3/app/installations/42/access_tokens", token: expect.any(String) }, - ]); - expect(requests[0]?.token).not.toBe(`Bearer ${pat}`); - }); - it.each([429, 503])( - "does not fall back to a server PAT during an App %s failure", - async (status) => { - await addCustomApp(); - appMintStatus = status; - await expect(client().deployments.prepare({ ...source, serverId })).rejects.toThrow( - `GitHub App API error (${status})`, - ); - expect(requests).toHaveLength(1); - expect(requests[0]?.path).toBe("/app/installations/42/access_tokens"); - expect(requests[0]?.token).not.toBe(`Bearer ${pat}`); - }, - ); - it.each([ - { credential: ["app-installation"] }, - { method: "POST", authorizeAs: "read" }, - { method: "DELETE" }, - { authorizeAs: "write" }, - { url: "https://api.github.com/user" }, - { url: "https://api.github.com/repos/acme/another-repo" }, - ] satisfies Partial[])( - "keeps the App credential boundary for %j", - async (options) => { - await addCustomApp(); - const ctx = buildBackgroundContext({ userId: owner.userId, organizationId: owner.orgId }); - await expect( - githubFetch({ - ctx, - owner: source.owner, - repo: source.repo, - serverId, - url: "https://api.github.com/repos/acme/private-workspace", - ...options, - }), - ).rejects.toMatchObject({ statusCode: 403, code: "GITHUB_TOKEN_REQUIRED" }); - expect(requests).toHaveLength(1); - expect(requests[0]?.path).toBe("/app/installations/42/access_tokens"); - expect(requests[0]?.token).not.toBe(`Bearer ${pat}`); - }, - ); it.each([false, true])( "detects the monorepo and sub-app using the same credential as deploy (explicit server=%s)", async (explicit) => { @@ -378,89 +211,6 @@ describe("server PAT-only preparation through the real authenticated HTTP/SDK fl ); expect(requests.some((req) => req.token === `Bearer ${pat}`)).toBe(true); }); - it("falls back to the connected server when the local row holds no usable GitHub credential (#1814)", async () => { - // A self-hosted boot registers the "This Server" row whether or not GitHub - // was ever connected on it; the org's PAT lives on the connected server. - await repos.serverGithubAuth.deleteByServer(serverId); - const connectedId = await addConnectedServerWithPat(); - // Naming the credential-holding server explicitly resolves it the same way. - expect( - (await client().deployments.prepare({ ...source, serverId: connectedId })).projectType, - ).toBe("monorepo"); - expect(requests.every((req) => req.token === `Bearer ${pat}`)).toBe(true); - requests = []; - const scan = await client().deployments.prepare(source); - expect(scan.projectType).toBe("monorepo"); - expect(requests.some((req) => req.token === `Bearer ${pat}`)).toBe(true); - }); - it("reads through the connected server when the local row's only credential is SSH (#1814)", async () => { - // Repository REST reads are token-only; a local row holding just SSH - // material can clone for deploys but cannot answer an api.github.com read. - await repos.serverGithubAuth.upsert({ - serverId, - organizationId: owner.orgId, - mode: "ssh-server-key", - serverKeyPrivateEncrypted: encrypt("ssh-private-key-material"), - serverKeyPublic: "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAtest", - }); - await addConnectedServerWithPat(); - expect((await client().deployments.prepare(source)).projectType).toBe("monorepo"); - expect(requests.some((req) => req.token === `Bearer ${pat}`)).toBe(true); - expect(requests.every((req) => req.token !== "ssh-private-key-material")).toBe(true); - }); - it("requires a selection when a credential-less local row hides several eligible servers (#1814)", async () => { - await repos.serverGithubAuth.deleteByServer(serverId); - await addOtherServerToken(); - await addConnectedServerWithPat(); - await expect(client().deployments.prepare(source)).rejects.toMatchObject({ - status: 409, - body: { code: "GITHUB_SERVER_SELECTION_REQUIRED" }, - }); - expect(requests.every((request) => request.token === null)).toBe(true); - }); - it("still reports GITHUB_TOKEN_REQUIRED when the credential-less local row is the only server (#1814)", async () => { - await repos.serverGithubAuth.deleteByServer(serverId); - await expect(client().deployments.prepare(source)).rejects.toMatchObject({ - status: 403, - body: { code: "GITHUB_TOKEN_REQUIRED" }, - }); - expect(requests.every((req) => req.token !== `Bearer ${pat}`)).toBe(true); - }); - it("uses the sole writable connected server when the local PAT is out of scope", async () => { - await setServerPat(serverId, "local-server-pat"); - const connectedId = await addConnectedServerWithPat(); - const member = await repos.member.find(owner.orgId, owner.userId); - await db - .update(schema.member) - .set({ role: "restricted" }) - .where(eq(schema.member.id, member!.id)); - await db.insert(schema.resourceGrant).values( - [ - { - resourceType: "github_repository", - resourceId: "acme/private-workspace", - permissionsJson: '["read"]', - }, - { resourceType: "server", resourceId: connectedId, permissionsJson: '["write"]' }, - { resourceType: "deployment", resourceId: "*", permissionsJson: '["read", "write"]' }, - ].map((grant) => ({ - ...grant, - id: crypto.randomUUID(), - organizationId: owner.orgId, - userId: owner.userId, - })), - ); - - await expect(client().deployments.prepare({ ...source, serverId })).rejects.toMatchObject({ - status: 403, - body: { code: "GITHUB_TOKEN_REQUIRED" }, - }); - expect(requests.every((request) => request.token === null)).toBe(true); - requests = []; - expect((await client().deployments.prepare(source)).projectType).toBe("monorepo"); - expect(requests.length).toBeGreaterThan(0); - expect(requests.every((request) => request.token === `Bearer ${pat}`)).toBe(true); - }); it("requires a selection before trying ambiguous server tokens, then scans with the selected server", async () => { await db.update(schema.servers).set({ isLocal: false }).where(eq(schema.servers.id, serverId)); const otherId = await addOtherServerToken(); @@ -491,71 +241,6 @@ describe("server PAT-only preparation through the real authenticated HTTP/SDK fl expect(requests.length).toBeGreaterThan(0); expect(requests.every((request) => request.token === null)).toBe(true); }); - it.each([false, true])( - "prepares an uncatalogued repository's openship.json services (Cloud=%s)", - async (cloudMode) => { - env.CLOUD_MODE = cloudMode; - publicReadAllowed = true; - const originalFiles = { ...files }; - // A README and manifest are sufficient: no catalog entry, package.json, - // Dockerfile or Compose file participates in this source preparation. - for (const name of Object.keys(files)) delete files[name]; - Object.assign(files, { - "README.md": "Deploy this project with OpenShip.\n", - "openship.json": JSON.stringify({ - services: [ - { - name: "web", - image: "nginx:stable-alpine", - exposed: true, - exposedPort: "80", - dependsOn: ["cache"], - }, - { name: "cache", image: "valkey/valkey:8-alpine", volumes: ["cache-data:/data"] }, - ], - }), - }); - try { - const intent = parseDeploySource({ - repo: "https://github.com/acme/private-workspace", - branch: "main", - }); - if (intent.kind !== "repo") throw new Error("Expected a repository deployment link"); - const scan = await client().deployments.prepare({ - source: "github", - owner: intent.owner, - repo: intent.repo, - branch: intent.branch, - }); - expect(scan.projectType).toBe("services"); - expect(scan.services).toHaveLength(2); - expect(scan.services?.[0]).toMatchObject({ - name: "web", - image: "nginx:stable-alpine", - exposed: true, - exposedPort: "80", - dependsOn: ["cache"], - }); - expect(scan.services?.[1]).toMatchObject({ - name: "cache", - image: "valkey/valkey:8-alpine", - volumes: ["cache-data:/data"], - }); - expect(scan.configDiagnostics?.errors ?? []).toEqual([]); - expect(requests.some((request) => request.path.endsWith("/contents/openship.json"))).toBe( - true, - ); - // Self-hosting reuses its configured local server credential. Cloud has - // no account connection here and reads the public repository anonymously. - expect(new Set(requests.map((request) => request.token))).toEqual( - new Set([cloudMode ? null : `Bearer ${pat}`]), - ); - } finally { - for (const name of Object.keys(files)) delete files[name]; - Object.assign(files, originalFiles); - } - }, - ); it("keeps an explicitly selected remote server through branch and folder browsing", async () => { await db.update(schema.servers).set({ isLocal: false }).where(eq(schema.servers.id, serverId)); const repo = { owner: source.owner, repo: source.repo, serverId }; @@ -632,7 +317,6 @@ describe("server PAT-only preparation through the real authenticated HTTP/SDK fl expect(requests.every((req) => req.token !== `Bearer ${pat}`)).toBe(true); }); it("requires server write permission in addition to repository access", async () => { - await addCustomApp(); const member = await repos.member.find(owner.orgId, owner.userId); await db .update(schema.member) @@ -685,19 +369,10 @@ describe("server PAT-only preparation through the real authenticated HTTP/SDK fl ).rejects.toMatchObject({ statusCode: 404 }); expect(requests).toHaveLength(0); }); - it.each([ - { explicit: false, customApp: false }, - { explicit: true, customApp: false }, - { explicit: false, customApp: true }, - { explicit: true, customApp: true }, - ])( - "does not let server write permission replace repository access: %j", - async ({ explicit, customApp }) => { - if (customApp) await addCustomApp(); - await db - .update(schema.servers) - .set({ isLocal: false }) - .where(eq(schema.servers.id, serverId)); + it.each([false, true])( + "does not let server write permission replace repository access (explicit=%s)", + async (explicit) => { + await db.update(schema.servers).set({ isLocal: false }).where(eq(schema.servers.id, serverId)); const member = await repos.member.find(owner.orgId, owner.userId); await db .update(schema.member) @@ -730,17 +405,13 @@ describe("server PAT-only preparation through the real authenticated HTTP/SDK fl expect(requests.every((request) => request.token !== `Bearer ${pat}`)).toBe(true); }, ); - it.each([false, true])( - "leaves Cloud's account-only authentication unchanged (custom App=%s)", - async (customApp) => { - if (customApp) await addCustomApp(); - env.CLOUD_MODE = true; - await expect(client().deployments.prepare({ ...source, serverId })).rejects.toMatchObject({ - status: 403, - }); - expect(requests.every((req) => req.token !== `Bearer ${pat}`)).toBe(true); - }, - ); + it("leaves Cloud's account-only authentication unchanged", async () => { + env.CLOUD_MODE = true; + await expect(client().deployments.prepare({ ...source, serverId })).rejects.toMatchObject({ + status: 403, + }); + expect(requests.every((req) => req.token !== `Bearer ${pat}`)).toBe(true); + }); it.each([429, 503])("does not hide a provider %s as a successful scan", async (status) => { providerStatus = status; await expect(client().deployments.prepare({ ...source, serverId })).rejects.toThrow( diff --git a/apps/api/test/modules/dns/managed-ingress.test.ts b/apps/api/test/modules/dns/managed-ingress.test.ts index 9593efea9..9bc116e4c 100644 --- a/apps/api/test/modules/dns/managed-ingress.test.ts +++ b/apps/api/test/modules/dns/managed-ingress.test.ts @@ -94,6 +94,6 @@ describe("managed ingress through authenticated HTTP and the public SDK", () => headers, body: JSON.stringify({ credentialId: "no-secret" }), }); - expect(denied.status).toBe(404); + expect(denied.status).toBe(403); }); }); diff --git a/apps/api/test/modules/github/github-sdk-parity.test.ts b/apps/api/test/modules/github/github-sdk-parity.test.ts index 917bf45b2..c31d438df 100644 --- a/apps/api/test/modules/github/github-sdk-parity.test.ts +++ b/apps/api/test/modules/github/github-sdk-parity.test.ts @@ -40,23 +40,6 @@ const entry = (path: string, type = "file") => ({ name: path.split("/").pop(), p afterEach(async () => { vi.clearAllMocks(); await setStoredDeviceToken(null); }); describe("GitHub operations shared by SDK and HTTP", () => { - it("rejects malformed connection options without disconnecting stored credentials", async () => { - const admin = await seedOwner({ instanceAdmin: true }); - await setStoredDeviceToken("saved-instance-token", "token"); - const before = (await repos.instanceSettings.get())?.ghDeviceTokenEncrypted; - expect(before).toBeTruthy(); - for (const path of ["/connect", "/disconnect?source=cli"]) { - const response = await app.request(`/api/github${path}`, { - method: "POST", - headers: { Authorization: `Bearer ${admin.token}`, "Content-Type": "application/json" }, - body: "{invalid", - }); - expect(response.status).toBe(400); - expect(await response.json()).toMatchObject({ code: "INVALID_JSON" }); - expect((await repos.instanceSettings.get())?.ghDeviceTokenEncrypted).toBe(before); - } - }); - it("publishes a single commit and draft PR through SDK and HTTP with the same source permissions", async () => { const owner = await seedOwner(), c = await clients(owner); const base = "a".repeat(40), tree = "b".repeat(40), next = "c".repeat(40), commit = "d".repeat(40); diff --git a/apps/api/test/modules/mail/mail-credentials.service.test.ts b/apps/api/test/modules/mail/mail-credentials.service.test.ts deleted file mode 100644 index 30593a5cb..000000000 --- a/apps/api/test/modules/mail/mail-credentials.service.test.ts +++ /dev/null @@ -1,50 +0,0 @@ -import { PGlite } from "@electric-sql/pglite"; -import type { CommandExecutor } from "@repo/adapters"; -import { runMailSql } from "@repo/platform/engine/modules/mail/mail-engine"; -import { expect, it, vi } from "vitest"; -import { updatePostmasterPassword } from "../../../src/modules/mail/mail-credentials.service"; - -vi.mock("@repo/platform/engine/modules/mail/admin/password", () => ({ - hashPassword: async () => "{SSHA512}fixture-hash", -})); -vi.mock("@repo/platform/engine/modules/mail/mail-engine", () => ({ - runMailSql: vi.fn(), -})); -vi.mock("@repo/platform/engine/modules/mail/mail-state", () => ({ - readState: async () => null, - mutateState: vi.fn(), -})); - -it("advances the postmaster password timestamp when rotating the hash", async () => { - const db = new PGlite(); - try { - // Execute the service's real SQL against the relevant iRedMail columns. - await db.exec(` - CREATE TABLE mailbox ( - username text PRIMARY KEY, - password text NOT NULL, - passwordlastchange timestamp NOT NULL DEFAULT NOW() - ); - INSERT INTO mailbox VALUES - ('postmaster@example.test', 'old-hash', TIMESTAMP '2000-01-01'), - ('alice@example.test', 'untouched-hash', TIMESTAMP '2000-01-01'); - `); - vi.mocked(runMailSql).mockImplementation(async (_target, statement) => { - await db.query(statement); - return ""; - }); - - await updatePostmasterPassword({} as CommandExecutor, "example.test", "fixture-password"); - - const { rows } = await db.query(` - SELECT username, password, passwordlastchange > TIMESTAMP '2000-01-01' AS rotated - FROM mailbox ORDER BY username - `); - expect(rows).toEqual([ - { username: "alice@example.test", password: "untouched-hash", rotated: false }, - { username: "postmaster@example.test", password: "{SSHA512}fixture-hash", rotated: true }, - ]); - } finally { - await db.close(); - } -}); diff --git a/apps/api/test/modules/mcp/mcp-tools-filter.test.ts b/apps/api/test/modules/mcp/mcp-tools-filter.test.ts index be9f00362..719dad2d2 100644 --- a/apps/api/test/modules/mcp/mcp-tools-filter.test.ts +++ b/apps/api/test/modules/mcp/mcp-tools-filter.test.ts @@ -135,7 +135,6 @@ function principal( const granted = new Set([...(p.grantedRootTypes ?? []), ...Object.keys(wildcards)]); return { role: p.role ?? "restricted", - membershipRole: p.membershipRole, readOnly: p.readOnly ?? false, grantedRootTypes: granted, wildcardGrants: p.wildcardGrants ?? new Map(Object.entries(wildcards)), @@ -148,16 +147,6 @@ function principal( const RWA: Permission[] = ["read", "write", "admin"]; describe("filterToolsForPrincipal", () => { - it("hides server administration from members and their existing scoped tokens", () => { - const read = tool({ name: "server_read", method: "GET", perm: { root: "server", leaf: "server", grantRoot: "server", action: "read", wildcard: false } }); - const exec = tool({ name: "server_exec", method: "POST", perm: { root: "server", leaf: "server", grantRoot: "server", action: "admin", wildcard: false } }); - for (const caller of [ - principal({ role: "member" }), - principal({ role: "restricted", membershipRole: "member", grantedRootTypes: new Set(["server"]), wildcards: { server: RWA } }), - ]) expect(names(filterToolsForPrincipal([read, exec], caller))).toEqual(["server_read"]); - expect(names(filterToolsForPrincipal([read, exec], principal({ role: "admin" })))).toEqual(["server_exec", "server_read"]); - }); - it("owner sees everything", () => { const out = filterToolsForPrincipal(ALL, principal({ role: "owner" })); expect(out.length).toBe(ALL.length); diff --git a/apps/api/test/modules/mcp/mcp-workspaces.test.ts b/apps/api/test/modules/mcp/mcp-workspaces.test.ts index 8179cc373..80dbb98b3 100644 --- a/apps/api/test/modules/mcp/mcp-workspaces.test.ts +++ b/apps/api/test/modules/mcp/mcp-workspaces.test.ts @@ -138,22 +138,6 @@ describe("MCP workspace discovery", () => { expect(denied.isError).toBe(true); }); - it.each([false, true])("advertises administration in another workspace only for an unbound credential (bound=%s)", async bound => { - const owner = await seedOwner({ bound }); - await secondWorkspace(owner, "admin"); - await db.update(schema.member).set({ role: "member" }).where(and(eq(schema.member.userId, owner.userId), eq(schema.member.organizationId, owner.orgId))); - const listed = await (await rpc(owner, "tools/list")).json() as { result: { tools: { name: string }[] } }; - expect(listed.result.tools.some(tool => tool.name === "delete_projects_by_id")).toBe(!bound); - if (!bound) { - const group = await repos.projectGroup.create({ organizationId: owner.orgId, name: "Member project", slug: "member-project" }); - const project = await repos.project.create({ organizationId: owner.orgId, groupId: group.id, name: "Member project", slug: "member-project" }); - const denied = await call(owner, "delete_projects_by_id", { id: project.id, organizationId: owner.orgId }); - expect(denied).toMatchObject({ isError: true, data: { code: "NOT_FOUND" } }); - expect(forwarding.fetch).toHaveBeenCalled(); - expect(await repos.project.findById(project.id)).toMatchObject({ id: project.id }); - } - }); - it("shares the discovery contract with SDKs and respects fixed native scopes", async () => { const owner = await seedOwner({ bound: false }); const target = await secondWorkspace(owner); diff --git a/apps/api/test/modules/migration/platform-import-domains.test.ts b/apps/api/test/modules/migration/platform-import-domains.test.ts deleted file mode 100644 index 26c5800b8..000000000 --- a/apps/api/test/modules/migration/platform-import-domains.test.ts +++ /dev/null @@ -1,185 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { db, eq, repos, schema, type Service } from "@repo/db"; -import type { ExecutionContext } from "@repo/platform"; -import type { PlannedImportService } from "@repo/platform/engine/modules/migration/platform-import-plan"; -import { platformImportRoutes } from "@repo/platform/engine/modules/migration/platform-import-project"; -import { saveMigrationRoutes } from "@repo/platform/engine/modules/migration/migration-routes"; -import { seedOrg, seedProject, seedService } from "../../helpers/seed"; - -const live = vi.hoisted(() => ({ reconcile: vi.fn() })); -vi.mock("@repo/platform/engine/lib/route-apply.service", async (original) => ({ - ...(await original()), - reconcileProjectRoutes: live.reconcile, -})); - -function recipe( - service: Service, - domains: PlannedImportService["source"]["domains"], - data: PlannedImportService["data"] = "empty", -): PlannedImportService { - return { - source: { - id: `source-${service.id}`, - name: "Provider name", - kind: "app", - domains, - env: {}, - rawEnv: {}, - variables: [], - volumes: [], - warnings: [], - blockers: [], - }, - data, - create: { name: service.name }, - environment: {}, - bindings: [], - }; -} - -describe("provider imports share native pending-domain persistence", () => { - const organizations: string[] = []; - let ctx: ExecutionContext; - beforeEach(async () => { - vi.clearAllMocks(); - ctx = (await seedOrg()) as ExecutionContext; - organizations.push(ctx.organizationId); - }); - afterEach(async () => { - for (const id of organizations.splice(0)) { - await db.delete(schema.project).where(eq(schema.project.organizationId, id)); - await db.delete(schema.servers).where(eq(schema.servers.organizationId, id)); - await db.delete(schema.cloudWorkspace).where(eq(schema.cloudWorkspace.organizationId, id)); - await db.delete(schema.organization).where(eq(schema.organization.id, id)); - } - }); - - it.each(["server", "cloud"])( - "saves custom aliases on their services without verifying or applying live routes (%s)", - async (target) => { - const managed = - target === "cloud" - ? await repos.cloudWorkspace.create({ - organizationId: ctx.organizationId, - name: "Import destination", - }) - : null; - const server = managed - ? await repos.server.findByWorkspace(managed.id, ctx.organizationId) - : null; - const project = await seedProject(ctx.organizationId, { - framework: "docker-compose", - serverId: server?.id, - }); - const web = await seedService(project.id, { - name: "storefront", - ports: ["8080"], - exposed: false, - }); - const api = await seedService(project.id, { - name: "api", - kind: "monorepo", - ports: ["3000"], - exposed: false, - }); - const internal = await seedService(project.id, { - name: "worker", - ports: ["9000"], - exposed: false, - }); - const plans = [ - recipe(web, [ - { hostname: "shop.example.com", portable: true }, - { hostname: "www.example.com", portable: true }, - { hostname: "shop.up.railway.app", portable: false }, - ]), - recipe(api, [ - { hostname: "api.example.com", portable: true }, - { hostname: "api.vercel.app", portable: false }, - ]), - recipe(internal, [{ hostname: "worker.up.railway.app", portable: false }]), - recipe(internal, [{ hostname: "external.example.com", portable: true }], "external"), - ]; - const routes = platformImportRoutes(plans); - await saveMigrationRoutes(ctx, project.id, routes, () => {}); - // Re-saving uses the existing rows, including verification tokens and aliases. - const original = await repos.domain.listByProject(project.id); - await saveMigrationRoutes(ctx, project.id, routes, () => {}); - const domains = await repos.domain.listByProject(project.id); - expect(domains.map((domain) => domain.id).sort()).toEqual( - original.map((domain) => domain.id).sort(), - ); - expect(domains).toHaveLength(3); - for (const [hostname, serviceId, targetPort] of [ - ["shop.example.com", web.id, 8080], - ["www.example.com", web.id, 8080], - ["api.example.com", api.id, 3000], - ] as const) { - const domain = domains.find((item) => item.hostname === hostname)!; - expect(domain).toMatchObject({ - projectId: project.id, - serviceId, - targetPort, - verified: false, - status: "pending", - }); - expect(domain.verificationToken).toBeTruthy(); - expect(domain.verificationToken).toBe( - original.find((item) => item.id === domain.id)?.verificationToken, - ); - } - expect((await repos.service.findById(web.id))?.publicEndpoints).toEqual([ - expect.objectContaining({ port: 8080, customDomain: "shop.example.com" }), - ]); - expect((await repos.project.findById(project.id))?.compositeRoutes).toEqual([ - expect.objectContaining({ - hostname: "www.example.com", - rootServiceId: web.id, - rootPort: 8080, - }), - ]); - expect((await repos.service.findById(internal.id))?.exposed).toBe(false); - expect(live.reconcile).not.toHaveBeenCalled(); - }, - ); - - it("refuses a cross-organization domain before saving any imported route", async () => { - const foreign = (await seedOrg()) as ExecutionContext; - organizations.push(foreign.organizationId); - const existingProject = await seedProject(foreign.organizationId, { - framework: "docker-compose", - }); - const existingService = await seedService(existingProject.id, { - name: "owner", - ports: ["8080"], - }); - await saveMigrationRoutes( - foreign, - existingProject.id, - platformImportRoutes([ - recipe(existingService, [{ hostname: "taken.example.com", portable: true }]), - ]), - () => {}, - ); - const original = await repos.domain.listByProject(existingProject.id); - const project = await seedProject(ctx.organizationId, { framework: "docker-compose" }); - const web = await seedService(project.id, { name: "web", ports: ["8080"], exposed: false }); - await expect( - saveMigrationRoutes( - ctx, - project.id, - platformImportRoutes([ - recipe(web, [ - { hostname: "available.example.com", portable: true }, - { hostname: "taken.example.com", portable: true }, - ]), - ]), - () => {}, - ), - ).rejects.toThrow("already connected to another project"); - expect(await repos.domain.listByProject(project.id)).toEqual([]); - expect((await repos.service.findById(web.id))?.exposed).toBe(false); - expect(await repos.domain.listByProject(existingProject.id)).toEqual(original); - expect(live.reconcile).not.toHaveBeenCalled(); - }); -}); diff --git a/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts b/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts index 06ab6469c..0f616742c 100644 --- a/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts +++ b/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts @@ -133,7 +133,7 @@ describe("notifications shared SDK/HTTP operations", () => { expect(await c.native.listDefaults()).toEqual([value]); expect(await c.native.categories()).toEqual(await c.remote.categories()); await db.update(schema.member).set({ role: "member" }).where(eq(schema.member.userId, owner.userId)); - for (const client of [c.native, c.remote]) await expect(client.upsertDefault({ category: "deploy.failed", defaultEnabled: false })).rejects.toMatchObject({ code: "NOT_FOUND" }); + for (const client of [c.native, c.remote]) await expect(client.upsertDefault({ category: "deploy.failed", defaultEnabled: false })).rejects.toMatchObject({ code: "FORBIDDEN" }); }); it("does not verify a replacement configuration or hide normal delivery failures", async () => { diff --git a/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts b/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts index 10a53e784..a6858b068 100644 --- a/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts +++ b/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts @@ -465,9 +465,8 @@ describe("project promotion recovery", () => { const dump = await dumpSubgraph({ kind: "project", projectId }); const changed = structuredClone(dump); changed.tables.resource_usage.push({ id: "another-sample", projectId, cpu: 42 }); + changed.tables.project[0].favicon = "new favicon"; expect(projectPromotionDigest(changed)).toBe(projectPromotionDigest(dump)); - changed.tables.project[0].iconUrl = "https://cdn.example.test/new-icon.png"; - expect(projectPromotionDigest(changed)).not.toBe(projectPromotionDigest(dump)); changed.tables.project[0].localPath = "/another-source"; expect(projectPromotionDigest(changed)).not.toBe(projectPromotionDigest(dump)); }); diff --git a/apps/api/test/modules/projects/cloud-routing-regression.test.ts b/apps/api/test/modules/projects/cloud-routing-regression.test.ts index a047ea544..a08e2a3ed 100644 --- a/apps/api/test/modules/projects/cloud-routing-regression.test.ts +++ b/apps/api/test/modules/projects/cloud-routing-regression.test.ts @@ -113,7 +113,7 @@ describe("managed Cloud route port edits and repair", () => { await editRoutes(["app.opsh.io"]); expect(h.fixture.pages.create).toHaveBeenCalledOnce(); expect(h.fixture.routes.set).toHaveBeenLastCalledWith("app.opsh.io", expect.objectContaining({ - routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.fixture.workspaceId, port: 32001 } }], + routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.fixture.workspaceId, port: 32001 } }], })); expect(h.syncManagedEdge).not.toHaveBeenCalled(); }); @@ -124,7 +124,7 @@ describe("managed Cloud route port edits and repair", () => { expect(h.fixture.pages.connectDomain).toHaveBeenCalledWith(expect.any(String), { domain: "app.example.com" }); expect(h.fixture.workspace.network.update).toHaveBeenCalledWith(expect.objectContaining({ ingress_ports: [443, 32000] })); expect(h.fixture.routes.set).toHaveBeenCalledWith("app.example.com", expect.objectContaining({ - routes: expect.arrayContaining([expect.objectContaining({ action: { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 } })]), + routes: expect.arrayContaining([expect.objectContaining({ action: { kind: "proxy", workspace: h.fixture.workspaceId, port: 32000 } })]), })); }); @@ -165,8 +165,8 @@ describe("managed Cloud route port edits and repair", () => { h.domains.push({ ...h.domains[0]!, id: "domain-b", hostname: "console.opsh.io", targetPort: 9000, isPrimary: false }); expect(await retryProjectRouting(h.project.id, h.project.organizationId)).toEqual({ ok: true }); expect(h.fixture.routes.set.mock.calls.map(([host, table]) => [host, table.routes[0]?.action])).toEqual([ - ["app.opsh.io", { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 }], - ["console.opsh.io", { kind: "proxy", vm: h.fixture.workspaceId, port: 32001 }], + ["app.opsh.io", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32000 }], + ["console.opsh.io", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32001 }], ]); }); @@ -196,8 +196,8 @@ describe("managed Cloud route port edits and repair", () => { })); expect(await retryProjectRouting(h.project.id, h.project.organizationId)).toEqual({ ok: true }); expect(h.fixture.routes.set.mock.calls.map(([host, table]) => [host, table.routes[0]?.action])).toEqual([ - ["app.example.com", { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 }], - ["alias.example.com", { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 }], + ["app.example.com", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32000 }], + ["alias.example.com", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32000 }], ]); expect(h.fixture.pages.delete).not.toHaveBeenCalled(); }); diff --git a/apps/api/test/modules/projects/edge-config-read.test.ts b/apps/api/test/modules/projects/edge-config-read.test.ts index 13b961a24..6308cfe1d 100644 --- a/apps/api/test/modules/projects/edge-config-read.test.ts +++ b/apps/api/test/modules/projects/edge-config-read.test.ts @@ -44,17 +44,12 @@ const project = (over: Partial = {}) => ({ id: "p1", slug: "app", routingConfig: null, ...over }) as Project; /** A live vhost as the nginx parser would hand it back. */ -const managedHeaderBuffers = { - proxyBufferSize: "32k", proxyBuffers: "8 32k", proxyBusyBuffersSize: "64k", - largeClientHeaderBuffers: "4 32k", -}; const site = (over: Partial = {}): ImportedSite => ({ serverNames: ["app.example.com"], ssl: true, target: { kind: "proxy", url: "http://127.0.0.1:3000" }, ...over, - proxy: { ...managedHeaderBuffers, ...over.proxy }, }) as ImportedSite; /** @@ -157,20 +152,7 @@ describe("readProjectEdgeConfig — agreement", () => { const r = await readProjectEdgeConfig( project({ routingConfig: { proxy: { clientMaxBodySize: "50m" } } }), ); - expect(r.hosts[0]!.directives.map((d) => d.key).sort()).toEqual([ - "clientMaxBodySize", ...Object.keys(managedHeaderBuffers), - ].sort()); - }); - - it("flags an older vhost until its new managed header defaults are applied", async () => { - box({ sites: { "app.example.com": site({ proxy: { - proxyBufferSize: undefined, proxyBuffers: undefined, proxyBusyBuffersSize: undefined, - largeClientHeaderBuffers: undefined, - } }) } }); - const report = await readProjectEdgeConfig(project()); - expect(report.hosts[0]!.driftCount).toBe(4); - expect(byKey(report, "proxyBufferSize")).toMatchObject({ expected: "32k", drift: true }); - expect(report.hosts[0]!.adoptable).toEqual({}); + expect(r.hosts[0]!.directives.map((d) => d.key)).toEqual(["clientMaxBodySize"]); }); it("passes the box's nginx version through, since the floor depends on it", async () => { diff --git a/apps/api/test/modules/projects/edge-pages.integration.test.ts b/apps/api/test/modules/projects/edge-pages.integration.test.ts deleted file mode 100644 index 5eb2cc4f1..000000000 --- a/apps/api/test/modules/projects/edge-pages.integration.test.ts +++ /dev/null @@ -1,95 +0,0 @@ -import { expect, it } from "vitest"; -import { Hono } from "hono"; -import { repos, seedOwner } from "../jobs/_harness"; -import { OpenshipClient } from "@repo/sdk/client"; -import { projectRoutes } from "../../../src/modules/projects/project.routes"; -import { healthRoutes } from "../../../src/modules/health/health.routes"; -import { handleApiError } from "../../../src/middleware/error-handler"; -import type { ProjectEdgePages } from "@repo/core"; - -const app = new Hono() - .onError(handleApiError) - .route("/api/health", healthRoutes) - .route("/api/projects", projectRoutes); -const remote = (token: string, organizationId: string) => - new OpenshipClient({ - baseUrl: "http://openship.test", - token, - organizationId, - fetch: ((url, init) => app.request(url as string, init)) as typeof fetch, - }).projects; - -it("persists staged pages through the SDK/HTTP boundary with revision, scope and ownership checks", async () => { - const owner = await seedOwner(); - const group = await repos.projectGroup.create({ - organizationId: owner.orgId, - name: "Pages", - slug: "pages", - }); - const project = await repos.project.create({ - organizationId: owner.orgId, - groupId: group.id, - name: "Pages", - slug: "pages", - }); - const client = remote(owner.token, owner.orgId); - const original = await client.getEdgePages(project.id); - expect(original).toMatchObject({ config: {}, status: "unpublished" }); - const config: ProjectEdgePages = { - defaults: { - files: [ - { - id: "maintenance", - name: "maintenance.html", - html: '

Upgrade

', - }, - ], - errors: [{ status: 503, pageId: "maintenance" }], - maintenance: { enabled: true, pageId: "maintenance", retryAfter: 300 }, - }, - }; - const saved = await client.updateEdgePages(project.id, { - config, - expectedRevision: original.revision, - }); - expect(saved).toMatchObject({ config, status: "unpublished" }); - expect(saved.revision).not.toBe(original.revision); - expect(await client.getEdgePages(project.id)).toEqual(saved); - await expect( - client.updateEdgePages(project.id, { config: {}, expectedRevision: original.revision }), - ).rejects.toMatchObject({ statusCode: 409 }); - await expect( - client.updateEdgePages(project.id, { - config: { hosts: { "other.test": config.defaults! } }, - expectedRevision: saved.revision, - }), - ).rejects.toMatchObject({ statusCode: 400 }); - // Routing forms/source imports cannot clear maintenance or overwrite it from - // a stale configuration object. Only the revision-checked pages operation can. - await client.update(project.id, { routingConfig: { cleanUrls: true } }); - expect((await client.getEdgePages(project.id)).config).toEqual(config); - await expect( - client.update(project.id, { routingConfig: { edgePages: {} } }), - ).rejects.toMatchObject({ statusCode: 409 }); - expect((await repos.project.findById(project.id))?.routingConfig?.edgePages).toEqual(config); - const stranger = await seedOwner(); - const foreign = remote(stranger.token, stranger.orgId); - await expect(foreign.getEdgePages(project.id)).rejects.toMatchObject({ statusCode: 404 }); - await expect( - foreign.updateEdgePages(project.id, { config: {}, expectedRevision: saved.revision }), - ).rejects.toMatchObject({ statusCode: 404 }); - await expect( - client.updateEdgePages(project.id, { - config: { - defaults: { ...config.defaults!, errors: [{ status: 401 as 503, pageId: "maintenance" }] }, - }, - expectedRevision: saved.revision, - }), - ).rejects.toMatchObject({ statusCode: 400 }); - const reset = await client.updateEdgePages(project.id, { - config: {}, - expectedRevision: saved.revision, - }); - expect(reset.config).toEqual({}); - expect((await repos.project.findById(project.id))?.routingConfig?.cleanUrls).toBe(true); -}); diff --git a/apps/api/test/modules/projects/folder-upload.test.ts b/apps/api/test/modules/projects/folder-upload.test.ts index 0238895b7..4360dc34f 100644 --- a/apps/api/test/modules/projects/folder-upload.test.ts +++ b/apps/api/test/modules/projects/folder-upload.test.ts @@ -80,11 +80,11 @@ afterAll(async () => { if (root) await rm(root, { recursive: true, force: true }); }); -async function open(name?: string) { +async function open() { const response = await fetch(`${origin}/api/projects/folder/session`, { method: "POST", headers: { ...owner.auth, "Content-Type": "application/json" }, - body: JSON.stringify({ ...(env.CLOUD_MODE ? { serverId: managedServerId } : {}), ...(name ? { name } : {}) }), + body: JSON.stringify(env.CLOUD_MODE ? { serverId: managedServerId } : {}), }); expect(response.status).toBe(200); const target = (await response.json()) as FolderSessionResult; @@ -115,49 +115,8 @@ function upload(target: FolderSessionResult, bytes = archive, chunked = false) { } as RequestInit); } -it("opens a local upload session with omitted options and rejects malformed options", async () => { - env.CLOUD_MODE = false; - for (const body of [undefined, "", "{invalid"]) { - const response = await fetch(`${origin}/api/projects/folder/session`, { - method: "POST", headers: { ...owner.auth, "Content-Type": "application/json" }, - ...(body === undefined ? {} : { body }), - }); - const result = await response.json() as FolderSessionResult; - if (result.sessionId) sessions.push(result.sessionId); - expect(response.status).toBe(body ? 400 : 200); - if (!body) expect(result.sessionId).toBeTruthy(); - } -}); - describe.each([false, true])("authenticated folder upload over HTTP (Cloud: %s)", (cloudMode) => { beforeEach(() => { env.CLOUD_MODE = cloudMode; }); - it.each([undefined, "my-folder-app"])("uses a client name or stable fallback instead of the staging path: %s", async (name) => { - const target = await open(name); - const uploaded = await upload(target); - expect(uploaded.status).toBe(200); - const response = await fetch(`${origin}/api/projects/folder/scan/${target.sessionId}`, { - method: "POST", headers: { ...owner.auth, "Content-Type": "application/json" }, body: "", - }); - expect(response.status, await response.clone().text()).toBe(200); - expect(await response.json()).toMatchObject({ name: name ?? "app" }); - }); - - it("returns the safe Compose refusal through the actual folder scan route", async () => { - const source = await mkdtemp(join(root, "host-network-")); - await writeFile(join(source, "compose.yaml"), "services:\n web:\n image: nginx:alpine\n network_mode: host\n"); - const packed = await archiveSourceDirectory(source, { temporaryRoot: join(root, "archives") }); - try { - const target = await open(); - expect((await upload(target, await readFile(packed.path))).status).toBe(200); - const response = await fetch(`${origin}/api/projects/folder/scan/${target.sessionId}`, { - method: "POST", headers: { ...owner.auth, "Content-Type": "application/json" }, body: "{}", - }); - expect(response.status).toBe(400); - expect(await response.json()).toMatchObject({ - code: "COMPOSE_CONFIGURATION_INVALID", error: expect.stringContaining("network_mode"), - }); - } finally { await packed.dispose(); } - }); it.each([false, true])("preserves every byte above 10 MiB (chunked: %s)", async (chunked) => { const target = await open(); const response = await upload(target, archive, chunked); @@ -174,8 +133,7 @@ describe.each([false, true])("authenticated folder upload over HTTP (Cloud: %s)" it("rejects a truncated gzip, cleans temporary files, and allows a complete retry", async () => { const target = await open(); const response = await upload(target, archive.subarray(0, 10 * 1024 * 1024)); - expect(response.status).toBe(400); - expect(await response.json()).toMatchObject({ error: expect.stringMatching(/incomplete|truncated/i) }); + expect(response.status, await response.text()).toBe(400); const session = getFolderSession(target.sessionId)!; expect(session.uploaded).toBe(false); expect(session.uploading).toBe(false); diff --git a/apps/api/test/modules/projects/project-icon.test.ts b/apps/api/test/modules/projects/project-icon.test.ts deleted file mode 100644 index 4cbd56c71..000000000 --- a/apps/api/test/modules/projects/project-icon.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import "../jobs/_env"; -import { expect, it } from "vitest"; -import { Hono } from "hono"; -import { seedOwner, repos } from "../jobs/_harness"; -import { seedProject, seedDeployment } from "../../helpers/seed"; -import { listDeployments } from "@repo/platform/engine/modules/deployments/deployment.service"; -import { projectRoutes } from "../../../src/modules/projects/project.routes"; -import { handleApiError } from "../../../src/middleware/error-handler"; - -const app = new Hono().onError(handleApiError).route("/api/projects", projectRoutes); - -it("uses one icon URL across authenticated settings, reads and deployment history", async () => { - const owner = await seedOwner(); - const project = await seedProject(owner.orgId); - const custom = "https://cdn.example.test/project.svg"; - const update = (iconUrl: unknown, auth = owner.auth) => - app.request(`/api/projects/${project.id}`, { - method: "PATCH", - headers: { ...auth, "Content-Type": "application/json" }, - body: JSON.stringify({ iconUrl }), - }); - const assertIcon = (data: unknown, expected: string | null) => { - expect(data).toMatchObject({ iconUrl: expected }); - expect(data).not.toHaveProperty("favicon"); - expect(data).not.toHaveProperty("faviconCheckedAt"); - }; - const saved = await update(` ${custom} `); - expect(saved.status, await saved.clone().text()).toBe(200); - assertIcon((await saved.json()).data, custom); - assertIcon(await repos.project.findById(project.id), custom); - const read = await app.request(`/api/projects/${project.id}`, { headers: owner.auth }); - expect(read.status, await read.clone().text()).toBe(200); - assertIcon((await read.json()).data, custom); - await seedDeployment(project); - for (const options of [{ projectId: project.id }, {}]) { - const history = await listDeployments(owner.orgId, options); - assertIcon(history.rows[0], custom); - } - const stranger = await seedOwner(); - expect((await update("https://stranger.example.test/icon.png", stranger.auth)).status).toBe(404); - for (const unsafe of [ - "javascript:alert(1)", - "data:image/png;base64,AAA", - "https://user:password@example.test/i.png", - "/relative.png", - ]) - expect((await update(unsafe)).status).toBe(400); - assertIcon(await repos.project.findById(project.id), custom); - for (const reset of [null, ""]) { - expect((await update(custom)).status).toBe(200); - const cleared = await update(reset); - expect(cleared.status).toBe(200); - assertIcon((await cleared.json()).data, null); - assertIcon(await repos.project.findById(project.id), null); - const history = await listDeployments(owner.orgId, { projectId: project.id }); - assertIcon(history.rows[0], null); - } -}); diff --git a/apps/api/test/modules/projects/project-overview-logs.test.ts b/apps/api/test/modules/projects/project-overview-logs.test.ts index 555e7ddf9..05434455e 100644 --- a/apps/api/test/modules/projects/project-overview-logs.test.ts +++ b/apps/api/test/modules/projects/project-overview-logs.test.ts @@ -19,6 +19,7 @@ vi.mock("@repo/db", () => ({ repos: { vi.mock("@repo/platform/engine/modules/projects/project.service", () => ({ listProjects: h.list, enrichProjectsBatch: h.enrich, deploymentIsBlocked: () => false })); vi.mock("@repo/platform/engine/lib/authorization", () => ({ authorization: { checkPermissionOnResource: h.canRead, authorize: async (ctx: ExecutionContext) => ctx } })); vi.mock("@repo/platform/engine/lib/cloud/projects", () => ({ fetchOrgCloudProjects: h.cloudProjects })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ refreshProjectFaviconIfStale: vi.fn() })); vi.mock("@repo/platform/engine/config/index", () => ({ env: h.env })); vi.mock("@repo/platform/engine/lib/oblien-user-client", () => ({ getAdminOblienClient: () => h.env.CLOUD_MODE ? { analytics: { streamToken: h.streamToken, requests: h.requests } } : null })); vi.mock("@repo/platform/engine/lib/cloud/client", () => ({ cloudClient: () => ({ analytics: { streamToken: h.streamToken, requests: h.requests } }) })); @@ -26,8 +27,6 @@ vi.mock("@repo/platform/engine/lib/ssh-manager", () => ({ sshManager: {} })); vi.mock("@repo/platform/engine/lib/openresty-paths", () => ({ getOpenRestyPaths: vi.fn() })); vi.mock("@repo/platform/engine/lib/project-analytics", () => ({ resolveProjectTrafficSource: h.source, resolveProjectTrafficSources: h.sources, -})); -vi.mock("@repo/platform/engine/lib/edge-management", () => ({ fetchMgmt: h.fetchMgmt, mgmtStream: vi.fn(), probeMgmt: vi.fn(), })); import { getProjectHome } from "@repo/platform/engine/modules/projects/project-home.operations"; diff --git a/apps/api/test/modules/projects/route-protection.integration.test.ts b/apps/api/test/modules/projects/route-protection.integration.test.ts index 0bc89adc7..836114e8c 100644 --- a/apps/api/test/modules/projects/route-protection.integration.test.ts +++ b/apps/api/test/modules/projects/route-protection.integration.test.ts @@ -56,25 +56,13 @@ it("shares pending protection through real native/HTTP operations without leakin }; const pending = await native.projects.changeRouteProtection(project.id, input); - expect(pending).toEqual({ hostname: input.hostname, enabled: true, status: "pending", options: { mode: "page", username: "visitor", sessionSeconds: 86400 } }); + expect(pending).toEqual({ hostname: input.hostname, enabled: true, status: "pending" }); expect(await client.listRouteProtection(project.id)).toEqual([pending]); expect(JSON.stringify(pending)).not.toContain(input.password); expect( await client.changeRouteProtection(project.id, { hostname: input.hostname, action: "retry" }), ).toEqual(pending); - const configured = await client.changeRouteProtection(project.id, { - hostname: input.hostname, action: "configure", - options: { mode: "page", sessionSeconds: 3600, loginHtml: "
{{form}}
" }, - }); - expect(configured.options?.loginHtml).toBe("
{{form}}
"); - const browser = await client.changeRouteProtection(project.id, { - hostname: input.hostname, action: "configure", options: { mode: "basic", username: "viewer", sessionSeconds: 3600 }, - }); - expect(browser.options).toEqual({ mode: "basic", username: "viewer", sessionSeconds: 3600 }); - expect((await client.listRouteProtection(project.id))[0].options).toEqual(browser.options); const policy = (await repos.routeProtection.readPrivate(project.id, input.hostname))!.secret!; - expect(JSON.parse(policy).loginHtml).toBeUndefined(); - for (const key of ["verifier", "signingKey", "salt"]) expect(JSON.stringify(browser)).not.toContain(key); const other = await seedOwner(); const stranger = remote(other.token, other.orgId); diff --git a/apps/api/test/modules/projects/shared-service-connections.test.ts b/apps/api/test/modules/projects/shared-service-connections.test.ts index 1df8a5fb8..fc4d00f0b 100644 --- a/apps/api/test/modules/projects/shared-service-connections.test.ts +++ b/apps/api/test/modules/projects/shared-service-connections.test.ts @@ -66,10 +66,9 @@ beforeEach(() => { describe("connections to a service inside a project", () => { it("offers all eligible projects while excluding the current project and read-only access", async () => { - h.candidates = ["source", "read-only", ...Array.from({ length: 120 }, (_, i) => `consumer-${i}`)].map(id => ({ id, name: id, environmentName: "production", appTemplateId: null, iconUrl: "https://cdn.example.test/icon.svg", framework: "nextjs" })); + h.candidates = ["source", "read-only", ...Array.from({ length: 120 }, (_, i) => `consumer-${i}`)].map(id => ({ id, name: id, environmentName: "production", appTemplateId: null })); const choices = await listConnectionCandidates(ctx, "source"); expect(choices).toHaveLength(120); - expect(choices[0]).toMatchObject({ iconUrl: "https://cdn.example.test/icon.svg", framework: "nextjs" }); expect(choices.some(choice => ["source", "read-only"].includes(choice.id))).toBe(false); expect(h.authorize).toHaveBeenCalledWith(ctx, { resourceType: "project", resourceId: "source", action: "write" }); }); diff --git a/apps/api/test/modules/route-rules/route-rule-push.test.ts b/apps/api/test/modules/route-rules/route-rule-push.test.ts index 0b1ec36ee..947253175 100644 --- a/apps/api/test/modules/route-rules/route-rule-push.test.ts +++ b/apps/api/test/modules/route-rules/route-rule-push.test.ts @@ -1,6 +1,6 @@ import { diagnostics as errorDiagnostics } from "@repo/core/diagnostics"; import { describe, expect, it, vi, beforeEach } from "vitest"; -import { normalizeEdgeResponse, type RouteRuleSpec } from "@repo/core"; +import type { RouteRuleSpec } from "@repo/core"; /** * The DB is the source of truth for route rules; the edge only knows what was last @@ -41,8 +41,8 @@ vi.mock("@repo/db", async (importOriginal) => ({ }, })); -vi.mock("@repo/platform/engine/lib/edge-management", async (importOriginal) => ({ - ...(await importOriginal()), +vi.mock("@repo/platform/engine/lib/project-analytics", async (importOriginal) => ({ + ...(await importOriginal()), postEdgeMgmt, })); @@ -88,7 +88,7 @@ function capturedPushes() { beforeEach(() => { vi.clearAllMocks(); - postEdgeMgmt.mockResolvedValue({ ok: true, staticResponses: true }); + postEdgeMgmt.mockResolvedValue(undefined); // pushProjectRules now loads the project too, for the organizationId that resolves a // null serverId to the "This Server" row. The real repo always returns a promise; an // unset mock returns undefined and blows up on `.catch`. @@ -171,38 +171,6 @@ describe("serializeProjectRules", () => { }); describe("pushProjectRules", () => { - it("checks response support before publishing and keeps the response bound to its domain", async () => { - const response = { response: normalizeEdgeResponse({ body: "ready" }) }; - listByProject.mockResolvedValue([rule({ domainId: "d1", pathPrefix: "/health", spec: response })]); - listDomains.mockResolvedValue([domain("d1", "a.com"), domain("d2", "b.com")]); - await expect(pushProjectRules("p1", "srv1")).resolves.toBe(true); - const calls = capturedPushes(); - expect(calls.findIndex(call => call.path === "/rules/capabilities")).toBeLessThan( - calls.findIndex(call => call.path === "/rules" && call.body.host === "a.com")); - expect(calls.find(call => call.body.host === "a.com")?.body.rules).toEqual([{ pathPrefix: "/health", spec: response }]); - expect(calls.find(call => call.body.host === "b.com")?.body.rules).toEqual([]); - }); - - it.each([null, { ok: true }, { ok: true, staticResponses: false }])("does not send a response to an older edge: %j", async (capability) => { - listByProject.mockResolvedValue([rule(), rule({ id: "response", domainId: "d1", spec: { response: normalizeEdgeResponse({ body: "ready" }) } })]); - listDomains.mockResolvedValue([domain("d1", "a.com")]); - postEdgeMgmt.mockImplementation(async (_server, path) => path === "/rules/capabilities" ? capability : { ok: true }); - const warn = vi.spyOn(errorDiagnostics, "warn").mockImplementation(() => {}); - try { - await expect(pushProjectRules("p1", "srv1")).resolves.toBe(false); - expect(capturedPushes().find(call => call.path === "/rules")?.body.rules).toEqual([{ pathPrefix: null, spec: RL }]); - } finally { warn.mockRestore(); } - }); - - it("reports an unacknowledged push as pending", async () => { - listByProject.mockResolvedValue([]); - listDomains.mockResolvedValue([domain("d1", "a.com")]); - postEdgeMgmt.mockResolvedValue(null); - const warn = vi.spyOn(errorDiagnostics, "warn").mockImplementation(() => {}); - try { await expect(pushProjectRules("p1", "srv1")).resolves.toBe(false); } - finally { warn.mockRestore(); } - }); - it("pushes every current host, even the ones with no rules", async () => { // An empty ruleset is how a host is CLEARED. Pushing only hosts that still have // rules is exactly the bug where a deleted rule keeps enforcing. @@ -244,7 +212,7 @@ describe("pushProjectRules", () => { postEdgeMgmt.mockRejectedValueOnce(new Error("tunnel closed")).mockResolvedValue({ ok: true }); const warn = vi.spyOn(errorDiagnostics, "warn").mockImplementation(() => {}); - await expect(pushProjectRules("p1", "srv1")).resolves.toBe(false); + await expect(pushProjectRules("p1", "srv1")).resolves.toBeUndefined(); expect(postEdgeMgmt).toHaveBeenCalledTimes(2); expect(warn).toHaveBeenCalled(); warn.mockRestore(); diff --git a/apps/api/test/modules/route-rules/rules-lua-contract.test.ts b/apps/api/test/modules/route-rules/rules-lua-contract.test.ts index 4fc4e0ea7..23c058eb6 100644 --- a/apps/api/test/modules/route-rules/rules-lua-contract.test.ts +++ b/apps/api/test/modules/route-rules/rules-lua-contract.test.ts @@ -202,7 +202,7 @@ describe("rules_guard.lua keeps the properties its comments promise", () => { it("returns early when the host has no rules (the common case)", () => { const head = guard.slice(0, guard.indexOf("local lib =")); - expect(head).toContain("if not raw and not response_revision then return end"); + expect(head).toContain("if not raw then return end"); }); it("picks the longest matching path prefix", () => { @@ -231,8 +231,10 @@ describe("rules_guard.lua keeps the properties its comments promise", () => { expect(guard).not.toContain("http_x_forwarded_for"); }); - // Literal response headers now have an explicit validator. Header injection - // and access-policy preservation are exercised by routing-rules.e2e.test.ts. + it("never writes a rule value into a response header", () => { + const headerWrites = [...guard.matchAll(/ngx\.header\[[^\]]+\]\s*=\s*(.+)/g)].map((m) => m[1]!); + expect(headerWrites).toEqual(['"1"']); // Retry-After only, a literal + }); it("applies access before ban before hotlink before rate limit", () => { // After resolving the country header, keep the cheaper access/ban checks diff --git a/apps/api/test/modules/services/service-domain-aliases.integration.test.ts b/apps/api/test/modules/services/service-domain-aliases.integration.test.ts index 4e9bdebab..a7e62edcd 100644 --- a/apps/api/test/modules/services/service-domain-aliases.integration.test.ts +++ b/apps/api/test/modules/services/service-domain-aliases.integration.test.ts @@ -31,7 +31,7 @@ beforeEach(() => { h.freeGate.mockReset().mockResolvedValue(undefined); }); -async function seed(apex = false) { +async function seed() { const actor = await seedOwner(); const group = await repos.projectGroup.create({ organizationId: actor.orgId, @@ -45,8 +45,8 @@ async function seed(apex = false) { slug: actor.orgId, }); const label = project.id.replace(/[^a-z0-9]/gi, "").toLowerCase(); - const primary = apex ? `${label}.com` : `${label}.example.com`; - const alias = apex ? `www.${primary}` : `alias-${label}.example.com`; + const primary = `${label}.example.com`; + const alias = `alias-${label}.example.com`; const endpoints: ServicePublicEndpoint[] = [ { port: 4000, domainType: "custom", customDomain: primary }, ]; @@ -86,62 +86,6 @@ async function seed(apex = false) { } describe("same-port service domains with real persistence", () => { - it("enables www, changes its direction and disables it without resetting the root certificate", async () => { - const s = await seed(true); - const bare = { ...s.endpoints[0]!, redirectTo: "" }; - const www = { ...bare, customDomain: s.alias, redirectTo: s.primary, redirectStatus: 301 }; - await updateService(s.ctx, s.project.id, s.service.id, { publicEndpoints: [bare, www] }); - expect(await repos.domain.findById(s.domain.id)).toEqual({ - ...s.domain, - updatedAt: expect.any(Date), - }); - expect(await repos.domain.findByHostname(s.alias)).toMatchObject({ - verified: false, - redirectTo: s.primary, - redirectStatus: 301, - }); - expect(h.edge.mock.calls.at(-1)?.[1].registers).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - hostname: s.alias, - redirectHost: { target: s.primary, statusCode: 301 }, - }), - ]), - ); - - // Reverse the pair in one write: the newly serving hostname must explicitly - // clear its previous redirect before the root can redirect to it. - await updateService(s.ctx, s.project.id, s.service.id, { - publicEndpoints: [ - { ...bare, customDomain: s.alias }, - { ...bare, redirectTo: s.alias, redirectStatus: 301 }, - ], - }); - expect(await repos.domain.findByHostname(s.alias)).toMatchObject({ redirectTo: null }); - expect(await repos.domain.findById(s.domain.id)).toMatchObject({ - redirectTo: s.alias, - verified: true, - sslStatus: "active", - }); - - await updateService(s.ctx, s.project.id, s.service.id, { publicEndpoints: [bare, www] }); - await updateService(s.ctx, s.project.id, s.service.id, { publicEndpoints: [bare] }); - expect(await repos.domain.findByHostname(s.alias)).toBeUndefined(); - expect(await repos.domain.findById(s.domain.id)).toMatchObject({ - hostname: s.primary, - redirectTo: null, - verified: true, - status: "active", - sslStatus: "active", - }); - expect(h.edge.mock.calls.at(-1)?.[1].removes).toEqual([ - { hostname: s.alias, isCustomDomain: true }, - ]); - expect( - h.edge.mock.calls.at(-1)?.[1].registers.map((route: { hostname: string }) => route.hostname), - ).toEqual([s.primary]); - }); - it("adds an alias without removing the verified primary and removes only the chosen alias", async () => { const s = await seed(); const routes: ServicePublicEndpoint[] = [ diff --git a/apps/api/test/modules/system/analytics-scrape-sweep.test.ts b/apps/api/test/modules/system/analytics-scrape-sweep.test.ts index 40eb4a913..ef0d25e3e 100644 --- a/apps/api/test/modules/system/analytics-scrape-sweep.test.ts +++ b/apps/api/test/modules/system/analytics-scrape-sweep.test.ts @@ -51,14 +51,14 @@ vi.mock("@repo/platform/engine/lib/system-debug", () => ({ formatDuration: () => "1ms", })); -vi.mock("@repo/platform/engine/lib/edge-management", () => ({ +vi.mock("@repo/platform/engine/lib/project-analytics", () => ({ probeMgmt: vi.fn(async (serverId: string) => { h.scraped.push(serverId); if (h.failing.has(serverId)) throw new Error("ssh refused"); return true; }), fetchMgmt: vi.fn(async () => h.totals), - postMgmtJson: vi.fn(async () => ({ buckets: [], flushed: 0 })), + postMgmt: vi.fn(async () => ({ buckets: [], flushed: 0 })), })); const { runAnalyticsScrapeSweep } = await import("@repo/platform/engine/modules/system/analytics-scraper"); @@ -98,7 +98,7 @@ describe("runAnalyticsScrapeSweep", () => { it("goes one server at a time — a 50-box control plane must not connect to all at once", async () => { let concurrent = 0; let peak = 0; - const { probeMgmt } = await import("@repo/platform/engine/lib/edge-management"); + const { probeMgmt } = await import("@repo/platform/engine/lib/project-analytics"); (probeMgmt as unknown as { mockImplementation: (f: unknown) => void }).mockImplementation( async (serverId: string) => { concurrent += 1; diff --git a/apps/api/test/modules/system/server-edge-pages.integration.test.ts b/apps/api/test/modules/system/server-edge-pages.integration.test.ts deleted file mode 100644 index 4d25638d4..000000000 --- a/apps/api/test/modules/system/server-edge-pages.integration.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { beforeEach, expect, it, vi } from "vitest"; -import { Hono } from "hono"; -import { repos, seedOwner, seedServer } from "../jobs/_harness"; -import { mintPatToken } from "@repo/platform/engine/lib/pat"; -import { OpenshipClient } from "@repo/sdk/client"; -import { connectedServerRoutes } from "../../../src/modules/system/connected-server.routes"; -import { healthRoutes } from "../../../src/modules/health/health.routes"; -import { handleApiError } from "../../../src/middleware/error-handler"; -const edge = vi.hoisted(() => ({ getEdgePages: vi.fn(), setEdgePages: vi.fn() })); -vi.mock("@repo/platform/engine/lib/openresty-paths", () => ({ - withOpenRestyRouting: async (_id: string, work: (routing: typeof edge) => unknown) => work(edge), -})); -const app = new Hono() - .onError(handleApiError) - .route("/api/health", healthRoutes) - .route("/api/system", connectedServerRoutes); -const client = (token: string, organizationId: string) => - new OpenshipClient({ - baseUrl: "http://openship.test", - token, - organizationId, - fetch: ((url, init) => app.request(url as string, init)) as typeof fetch, - }).servers; -const config = { - files: [{ id: "default", name: "default.html", html: "

Choose a domain

" }], - errors: [], - defaultPageId: "default", -}; -beforeEach(() => { - vi.resetAllMocks(); - edge.getEdgePages.mockResolvedValue(config); - edge.setEdgePages.mockResolvedValue(undefined); -}); -it("shares server pages through the SDK and enforces ownership and read-only credentials before execution", async () => { - const owner = await seedOwner(); - const serverId = await seedServer(owner.orgId); - const remote = client(owner.token, owner.orgId); - expect(await remote.getEdgePages(serverId)).toEqual({ config }); - expect(await remote.updateEdgePages(serverId, config)).toEqual({ config }); - expect(edge.setEdgePages).toHaveBeenCalledExactlyOnceWith(config); - edge.getEdgePages.mockClear(); - edge.setEdgePages.mockClear(); - const other = await seedOwner(); - await expect(client(other.token, other.orgId).getEdgePages(serverId)).rejects.toMatchObject({ - statusCode: 404, - }); - await expect( - client(other.token, other.orgId).updateEdgePages(serverId, config), - ).rejects.toMatchObject({ statusCode: 404 }); - const pat = mintPatToken(); - await repos.personalAccessToken.create({ - userId: owner.userId, - organizationId: owner.orgId, - name: "read only", - tokenPrefix: pat.tokenPrefix, - tokenHash: pat.tokenHash, - readOnly: true, - scoped: false, - expiresAt: null, - }); - await expect( - client(pat.token, owner.orgId).updateEdgePages(serverId, config), - ).rejects.toMatchObject({ statusCode: 403 }); - expect(edge.getEdgePages).not.toHaveBeenCalled(); - expect(edge.setEdgePages).not.toHaveBeenCalled(); -}); -it("rejects provider-owned server pages before reaching the edge", async () => { - const owner = await seedOwner(); - const workspace = await repos.cloudWorkspace.create({ - organizationId: owner.orgId, - name: "Managed", - }); - const serverId = (await repos.server.findByWorkspace(workspace.id, owner.orgId))!.id; - const remote = client(owner.token, owner.orgId); - await expect(remote.getEdgePages(serverId)).rejects.toMatchObject({ statusCode: 409 }); - await expect(remote.updateEdgePages(serverId, config)).rejects.toMatchObject({ statusCode: 409 }); - expect(edge.getEdgePages).not.toHaveBeenCalled(); - expect(edge.setEdgePages).not.toHaveBeenCalled(); -}); diff --git a/apps/api/test/modules/system/server-exec-authorization.test.ts b/apps/api/test/modules/system/server-exec-authorization.test.ts deleted file mode 100644 index 754a3fcb9..000000000 --- a/apps/api/test/modules/system/server-exec-authorization.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import "../jobs/_env"; -import { beforeEach, expect, it, vi } from "vitest"; -import { Hono } from "hono"; -import { and, eq } from "@repo/db"; - -const host = vi.hoisted(() => ({ execute: vi.fn(), command: vi.fn() })); -vi.mock("@repo/platform/engine/lib/server-execution", async original => ({ - ...await original(), - withServerExecution: host.execute, -})); -vi.mock("@repo/platform/engine/lib/agent-exec", () => ({ execOnHost: host.command })); - -import { db, schema, seedOwner } from "../jobs/_harness"; -import { serverResourceRoutes } from "../../../src/modules/system/server-resource.routes"; -import { handleApiError } from "../../../src/middleware/error-handler"; - -const app = new Hono().onError(handleApiError).route("/api/system", serverResourceRoutes); -beforeEach(() => { - vi.clearAllMocks(); - host.command.mockResolvedValue({ output: "probe", exitCode: 0, timedOut: false, truncated: false, durationMs: 1 }); - host.execute.mockImplementation(async (_org, _id, work) => work({})); -}); - -it("rejects an authenticated member before host dispatch and preserves administrator execution", async () => { - const actor = await seedOwner(); - const id = `server-${actor.userId}`; - await db.insert(schema.servers).values({ id, organizationId: actor.orgId, name: "Fixture host", sshHost: "203.0.113.10", sshUser: "root" }); - const membership = and(eq(schema.member.userId, actor.userId), eq(schema.member.organizationId, actor.orgId)); - const execute = (serverId = id) => app.request(`/api/system/servers/${serverId}/exec`, { - method: "POST", headers: { ...actor.auth, "Content-Type": "application/json" }, body: JSON.stringify({ command: "id" }), - }); - await db.update(schema.member).set({ role: "member" }).where(membership); - expect((await execute()).status).toBe(404); - expect(host.execute).not.toHaveBeenCalled(); - expect(host.command).not.toHaveBeenCalled(); - await db.update(schema.member).set({ role: "admin" }).where(membership); - expect((await execute()).status).toBe(200); - expect(host.execute).toHaveBeenCalledOnce(); - expect(host.command).toHaveBeenCalledOnce(); - const other = await seedOwner(); - const otherServer = `server-${other.userId}`; - await db.insert(schema.servers).values({ id: otherServer, organizationId: other.orgId, name: "Other organization", sshHost: "203.0.113.11" }); - expect((await execute(otherServer)).status).toBe(404); - expect(host.command).toHaveBeenCalledOnce(); - await db.update(schema.member).set({ role: "member" }).where(membership); - expect((await execute()).status).toBe(404); - expect(host.command).toHaveBeenCalledOnce(); -}); diff --git a/apps/api/test/modules/system/server-managed-controls.test.ts b/apps/api/test/modules/system/server-managed-controls.test.ts index 364e1abd0..aeea020f2 100644 --- a/apps/api/test/modules/system/server-managed-controls.test.ts +++ b/apps/api/test/modules/system/server-managed-controls.test.ts @@ -72,11 +72,11 @@ let workloads: Map; let vm: any; let handle: any; -const jwt = (id = vmId, type = "vm") => +const jwt = (id = vmId, type = "workspace") => `e30.${Buffer.from( JSON.stringify({ type, - vm_id: id, + workspace_id: id, token: runtimeToken, exp: Math.floor(Date.now() / 1000) + 3600, }), @@ -261,8 +261,8 @@ beforeEach(async () => { { ip: "8.8.4.4", countryCode: "US" }, { ip: "1.1.1.1", countryCode: "AU" }, ]), - vms: { get: vi.fn(async () => vm), invalidateRuntime: vi.fn() }, - vm: vi.fn(() => handle), + workspaces: { get: vi.fn(async () => vm), invalidateRuntime: vi.fn() }, + workspace: vi.fn(() => handle), }; h.namespaceClient.mockImplementation(async () => ({ client: h.client, namespace })); h.canWork.mockResolvedValue(undefined); @@ -402,7 +402,7 @@ describe("managed server controls through real HTTP, policy and SQL ownership", ).toBe(400); expect(handle.ssh.setPassword).not.toHaveBeenCalled(); }); - it("reveals only a VM gateway token and fences repeat rotations", async () => { + it("reveals only a workspace gateway token and fences repeat rotations", async () => { const revealed = await request("managed/runtime-api/credential", "POST", { confirm: true }); expect(revealed.status, JSON.stringify(revealed.body)).toBe(200); expect(revealed.body.endpoint).toBe("https://runtime.example.test"); @@ -414,19 +414,12 @@ describe("managed server controls through real HTTP, policy and SQL ownership", "MANAGED_RUNTIME_TOKEN_CHANGED", ); expect(handle.apiAccess.rotateToken).toHaveBeenCalledTimes(1); - expect(h.client.vms.invalidateRuntime).toHaveBeenCalledWith(vmId); + expect(h.client.workspaces.invalidateRuntime).toHaveBeenCalledWith(vmId); handle.apiAccess.getToken.mockResolvedValue({ token: jwt("another-vm") }); expect( (await request("managed/runtime-api/credential", "POST", { confirm: true })).status, ).toBe(502); }); - it.each(["workspace", "namespace", "account"])("rejects %s credentials even with the selected VM ID", async (type) => { - handle.apiAccess.getToken.mockResolvedValue({ token: jwt(vmId, type) }); - const result = await request("managed/runtime-api/credential", "POST", { confirm: true }); - expect(result.status).toBe(502); - expect(result.body.code).toBe("MANAGED_CREDENTIAL_UNAVAILABLE"); - expect(JSON.stringify(result.body)).not.toContain(runtimeToken); - }); it("keeps the original network response for clients that do not request diagnostics", async () => { const legacy = { internetAccess: true, ingressPorts: [80, 9990] }; expect((await request("network-settings")).body).toEqual(legacy); @@ -489,7 +482,7 @@ describe("managed server controls through real HTTP, policy and SQL ownership", "MANAGED_RUNTIME_TOKEN_CHANGED", ); expect(handle.apiAccess.rotateToken).toHaveBeenCalledTimes(1); - expect(h.client.vms.invalidateRuntime).toHaveBeenCalledWith(vmId); + expect(h.client.workspaces.invalidateRuntime).toHaveBeenCalledWith(vmId); const recovered = await request("managed/runtime-api/credential", "POST", { confirm: true }); expect(recovered.status).toBe(200); expect(recovered.body.revision).not.toBe(input.expectedRevision); diff --git a/apps/api/test/modules/tokens/mint-org-binding.test.ts b/apps/api/test/modules/tokens/mint-org-binding.test.ts index b0998efd1..88e421d30 100644 --- a/apps/api/test/modules/tokens/mint-org-binding.test.ts +++ b/apps/api/test/modules/tokens/mint-org-binding.test.ts @@ -188,16 +188,6 @@ beforeEach(() => { }); describe("finding 1: grant width is checked in the org the binding is written to", () => { - it("refuses server administration grants for an ordinary member", async () => { - const grants = [{ resourceType: "server", resourceId: "*", permissions: ["admin"] }]; - const refused = await authorize(OWNER_ORG, { clientId: "cli", organizationId: VICTIM_ORG, grants }); - expect(refused.status).toBe(403); - expect(refused.body.code).toBe("GRANT_EXCEEDS_ACCESS"); - expect(upsertOAuthBindingWithGrants).not.toHaveBeenCalled(); - const allowed = await authorize(OWNER_ORG, { clientId: "cli", organizationId: OWNER_ORG, grants }); - expect(allowed.status).toBe(200); - }); - /** * `billing` and `audit` are the two types `roleAllowsResourceType` denies a * member, and both are grantable — so they isolate "authority comes from the diff --git a/apps/api/test/modules/updates/runtime-image-check.test.ts b/apps/api/test/modules/updates/runtime-image-check.test.ts index 00ad42785..4271fb8e2 100644 --- a/apps/api/test/modules/updates/runtime-image-check.test.ts +++ b/apps/api/test/modules/updates/runtime-image-check.test.ts @@ -89,19 +89,6 @@ async function clients(owner: SeededOwner) { ]; } -it.each([undefined, "", "{}"])("accepts optional image-check input over HTTP: %j", async body => { - const { owner, project, deployment } = await fixture(); - await setMeta(deployment.id, { - runtimeImages: { app: [{ ref: "php:8.4-cli-bookworm", digest: OLD }], artifacts: { app: deployment.imageRef } }, - }); - const response = await app.request(`/api/updates/${project.id}/runtime/check`, { - method: "POST", headers: { ...owner.auth, "content-type": "application/json" }, - ...(body === undefined ? {} : { body }), - }); - expect(response.status).toBe(200); - expect(await response.json()).toMatchObject({ data: { images: [{ ref: "php:8.4-cli-bookworm", status: "update_available" }] } }); -}); - it("compares recorded source image bases independently of newer Git commits", async () => { const { owner, project, deployment } = await fixture(); await setMeta(deployment.id, { diff --git a/apps/api/test/modules/updates/runtime-update.test.ts b/apps/api/test/modules/updates/runtime-update.test.ts index 2ef70ee2c..94b00f330 100644 --- a/apps/api/test/modules/updates/runtime-update.test.ts +++ b/apps/api/test/modules/updates/runtime-update.test.ts @@ -90,38 +90,6 @@ async function project(owner: SeededOwner, name: string, deployed = true) { } describe("runtime update shared SDK/HTTP operation", () => { - it.each(["runtime", "runtime/check"])("rejects malformed optional input on %s", async path => { - const owner = await seedOwner(), p = await project(owner, "invalid-runtime-input"); - for (const body of ["{", '{"serviceIds":"invalid"}']) { - const response = await app.request(`/api/updates/${p.id}/${path}`, { - method: "POST", headers: { ...owner.auth, "content-type": "application/json" }, body, - }); - expect(response.status).toBe(400); - } - expect(provider.deploy).not.toHaveBeenCalled(); - }); - - it.each([undefined, "", "{}"])("accepts optional runtime-update input over HTTP: %j", async body => { - const owner = await seedOwner(), p = await project(owner, "optional-runtime-input"); - const response = await app.request(`/api/updates/${p.id}/runtime`, { - method: "POST", headers: { ...owner.auth, "content-type": "application/json" }, - ...(body === undefined ? {} : { body }), - }); - expect(await response.json()).toEqual({ data: { project_id: p.id, deployment_id: "runtime-update" } }); - expect(response.status).toBe(200); - expect(provider.deploy).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ organizationId: owner.orgId }), expect.objectContaining({ - projectId: p.id, trigger: "update", forcePullImages: true, commitSha: shipped, - })); - }); - - it("preserves the Compose review revision through native and HTTP runtime refresh", async () => { - const owner = await seedOwner(), p = await project(owner, "reviewed-runtime"), c = await clients(owner); - const composeRevision = "b".repeat(64); - for (const client of [c.native.updates, c.remote.updates]) await client.updateRuntime(p.id, { composeRevision }); - expect(provider.deploy).toHaveBeenCalledTimes(2); - for (const [, input] of provider.deploy.mock.calls) expect(input).toMatchObject({ projectId: p.id, composeRevision, forcePullImages: true }); - }); - it("rebuilds a source runtime at the active commit without requiring source drift", async () => { const owner = await seedOwner(), p = await project(owner, "source"), diff --git a/apps/api/test/modules/updates/updates-sdk-parity.test.ts b/apps/api/test/modules/updates/updates-sdk-parity.test.ts index 5ee5b5bb6..074ad7f9c 100644 --- a/apps/api/test/modules/updates/updates-sdk-parity.test.ts +++ b/apps/api/test/modules/updates/updates-sdk-parity.test.ts @@ -191,51 +191,6 @@ describe("updates shared SDK/HTTP operations", () => { expect(provider.redeploy).not.toHaveBeenCalled(); }); - - it("carries a reviewed Compose revision through native and HTTP updates", async () => { - const owner = await seedOwner(), p = await project(owner, "reviewed-apply"), c = await clients(owner); - const composeRevision = "a".repeat(64); - provider.redeploy.mockResolvedValue({ project_id: p.id, deployment_id: "reviewed-deployment" }); - for (const client of [c.native.updates, c.remote.updates]) await client.apply(p.id, { composeRevision }); - expect(provider.redeploy).toHaveBeenCalledTimes(2); - for (const [, , input] of provider.redeploy.mock.calls) expect(input).toEqual({ trigger: "update", composeRevision }); - }); - it.each(["absent", "empty stream"] as const)("updates a webmail image with an %s request body", async body => { - const owner = await seedOwner(), p = await project(owner, `webmail-${body.replace(" ", "-")}`); - await repos.project.update(p.id, { - gitProvider: null, gitOwner: null, gitRepo: null, framework: "webmail", appTemplateId: "webmail", - }); - const image = "ghcr.io/oblien/openship-webmail:latest"; - const webmail = await repos.service.create({ projectId: p.id, name: "webmail", image, enabled: true }); - await repos.service.upsertServiceDeployment({ - deploymentId: p.activeDeploymentId!, serviceId: webmail.id, status: "success", - imageRef: image, imageDigest: `sha256:${"1".repeat(64)}`, containerId: "webmail-container", - }); - provider.poll.mockResolvedValue({ supported: true, mode: "image", digestByRef: { [image]: `sha256:${"2".repeat(64)}` } }); - provider.deploy.mockResolvedValue({ deployment: { id: "webmail-update" } }); - const request = new Request(`http://openship.test/api/updates/${p.id}/apply`, { - method: "POST", headers: owner.auth, ...(body === "empty stream" ? { body: "" } : {}), - }); - if (body === "empty stream") expect(request.body).not.toBeNull(); - const response = await app.request(request); - expect(await response.json()).toEqual({ data: { success: true, project_id: p.id, deployment_id: "webmail-update" } }); - expect(response.status).toBe(200); - expect(provider.deploy).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ organizationId: owner.orgId, userId: owner.userId }), expect.objectContaining({ - projectId: p.id, trigger: "update", serviceIds: [webmail.id], strictServiceScope: true, - })); - expect(provider.redeploy).not.toHaveBeenCalled(); - }); - - it.each(["{", '{"composeRevision":false}'])("rejects malformed update input before deployment: %s", async body => { - const owner = await seedOwner(), p = await project(owner, "invalid-update-body"); - const response = await app.request(`/api/updates/${p.id}/apply`, { - method: "POST", headers: { ...owner.auth, "content-type": "application/json" }, body, - }); - expect(response.status).toBe(400); - expect(provider.redeploy).not.toHaveBeenCalled(); - expect(provider.deploy).not.toHaveBeenCalled(); - }); - it("retains the update trigger and records one audit through either interface", async () => { const owner = await seedOwner(), p = await project(owner, "apply"), diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json index 94a494d7e..7c483898a 100644 --- a/apps/api/tsconfig.json +++ b/apps/api/tsconfig.json @@ -15,6 +15,6 @@ "declaration": false, "declarationMap": false }, - "include": ["src/**/*.ts", "scripts/cloud-readiness.ts"], + "include": ["src/**/*.ts"], "exclude": ["node_modules", "dist"] } diff --git a/apps/api/vitest.config.ts b/apps/api/vitest.config.ts index f7fc2300f..e7faffa8a 100644 --- a/apps/api/vitest.config.ts +++ b/apps/api/vitest.config.ts @@ -21,9 +21,6 @@ export const sharedTestOptions = { // auth-mode/zero-auth behaviour unchanged (see test/modules/mail/_setup-env.ts). env: { INTERNAL_TOKEN: "test-internal-token-0000000000000000000000000000", - // cron-parser reads schedules in the process's local time, and the - // expected run times in the tests are written in UTC, as CI runs. - TZ: "UTC", }, }; diff --git a/apps/cli/package.json b/apps/cli/package.json index ac7169afb..a13d32459 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -1,6 +1,6 @@ { "name": "@repo/cli", - "version": "1.0.1", + "version": "0.9.11", "description": "Openship CLI - deploy, manage, and open your Openship platform from the terminal", "license": "Apache-2.0", "repository": { diff --git a/apps/cli/src/commands/domain.ts b/apps/cli/src/commands/domain.ts index 9b6011a8c..5661d5b14 100644 --- a/apps/cli/src/commands/domain.ts +++ b/apps/cli/src/commands/domain.ts @@ -9,7 +9,7 @@ import { exitCommand, rethrowCommandExit } from "../lib/command-exit"; import { Command, Option } from "commander"; import { UploadCertBody, parseInput } from "@repo/contracts"; import { readFileSync } from "node:fs"; -import { prepareCustomDomainEndpoint } from "../lib/custom-domain-endpoint"; +import { attachCustomDomainEndpoint } from "../lib/custom-domain-endpoint"; import { getShipClient } from "../lib/ship-client"; import { spin, fail, confirmOrExit, printResult } from "../lib/cmd-helpers"; import type { Domain, DomainRecords, DomainSsl } from "@repo/sdk/client"; @@ -71,17 +71,14 @@ const addCmd = new Command("add") .argument("", "Domain hostname (e.g. app.example.com)") .requiredOption("-p, --project ", "Project ID to attach the domain to") .option("--primary", "Mark this domain as the project's primary", false) - .option("--service ", "Target service within the selected project") - .option("--port ", "Container port to route (required for ambiguous service ports)", positiveInteger) .action(async (hostname: string, opts) => { const sp = spin(`Adding ${hostname}…`); try { const ship = getShipClient(); - const attach = await prepareCustomDomainEndpoint(ship, opts.project, { service: opts.service, port: opts.port }); const res = await ship.domains.create(opts.project, { hostname, isPrimary: !!opts.primary }); - await attach(res.domain.hostname); + const routed = await attachCustomDomainEndpoint(ship, opts.project, res.domain.hostname); sp?.succeed(`Added ${res.domain.hostname}`); - info(` ${res.domain.hostname} is configured to be routed on the next deploy.`); + if (routed) info(` ${res.domain.hostname} is configured to be routed on the next deploy.`); if (isJsonMode()) { printJson(res); return; diff --git a/apps/cli/src/commands/launch.ts b/apps/cli/src/commands/launch.ts deleted file mode 100644 index 85532af19..000000000 --- a/apps/cli/src/commands/launch.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { Command, Option } from "commander"; -import { confirm, isCancel, log, note, outro } from "@clack/prompts"; -import { parseDeploySource, deploySetupHref } from "@repo/core"; -import { waitForApi } from "@repo/onboarding"; -import { isJsonMode } from "../lib/output"; -import { exitCommand } from "../lib/command-exit"; -import { localConnectionEndpoints } from "../lib/local-connection"; -import { readInstallMethod, composeStart } from "../lib/compose"; -import { serviceStatus } from "../lib/service"; -import { storedDashboardPort } from "../lib/ports"; -import { isSetupInProgress, runWizard } from "./wizard"; -import { startService } from "./up"; -import { reportCaughtError } from "@repo/core/diagnostics"; - -async function ask(message: string) { - const answer = await confirm({ message, initialValue: false }); - if (isCancel(answer) || !answer) exitCommand(0); -} - -/** - * The deploy button's local bootstrap. Installation is interactive; application - * configuration stays in the existing app/repository wizard, including its - * Compose, env, domains, billing and review gates. Never selects a CLI context. - */ -export const launchCommand = new Command("launch") - .description("Set up this machine and open an app or repository's deployment wizard") - .addOption(new Option("--app ", "Catalog app ID").conflicts("repo")) - .addOption(new Option("--repo ", "Public GitHub repository URL").conflicts("app")) - .option("--branch ", "Repository branch (defaults to the repository's default)") - .action(async (opts) => { - const source = parseDeploySource(opts); - if (!process.stdin.isTTY || isJsonMode()) - throw new Error( - "Run openship launch in an interactive terminal. It never installs or deploys unattended.", - ); - - const installed = readInstallMethod() === "compose" || serviceStatus().installed; - if (!installed || isSetupInProgress()) { - await ask("Set up OpenShip on this machine before configuring your app?"); - await runWizard(); - } else if (!(await waitForApi({ apiUrl: localConnectionEndpoints().apiUrl }, 1, 0))) { - await ask("Start the existing OpenShip installation on this machine?"); - if (readInstallMethod() === "compose") { - if (!composeStart()) - throw new Error("Could not start OpenShip. Run openship up to inspect the installation."); - } else { - await startService({}); - } - } - // Setup can move the ports or establish a public hostname. Re-read only - // this installation; OPENSHIP_API_URL/TOKEN and saved Cloud contexts do not participate. - const local = localConnectionEndpoints(); - if (!(await waitForApi({ apiUrl: local.apiUrl }, 5, 1000))) - throw new Error("OpenShip is not ready. Run openship doctor, then retry this command."); - const target = new URL(deploySetupHref(source, "server"), local.dashboardUrl); - if (!["http:", "https:"].includes(target.protocol) || target.username || target.password) - throw new Error( - "The local installation has an invalid dashboard URL. Check its instance configuration.", - ); - note(target.href, "Continue in your OpenShip dashboard"); - log.info( - "Review the destination, environment, storage and domains, then choose Deploy. No app has been deployed yet.", - ); - if ( - process.env.SSH_CONNECTION && - ["localhost", "127.0.0.1", "[::1]"].includes(target.hostname) - ) { - const port = storedDashboardPort(); - note( - `ssh -L ${port}:127.0.0.1:${port} @\n\nThen open the link above on your computer.`, - "Reach a private dashboard over SSH", - ); - } else if (!process.env.SSH_CONNECTION) { - await ask("Open the deployment setup in your browser?"); - try { - const { default: open } = await import("open"); - await open(target.href); - } catch (error) { - reportCaughtError(error, "cli/commands/launch"); - log.info("Open the link above in your browser to continue."); - } - } - outro("Your deployment settings are ready to review."); - }); diff --git a/apps/cli/src/commands/login.ts b/apps/cli/src/commands/login.ts index fb5e18403..e8da11cd3 100644 --- a/apps/cli/src/commands/login.ts +++ b/apps/cli/src/commands/login.ts @@ -18,7 +18,6 @@ import { fetchCaps } from "../lib/caps"; import { err, info, isJsonMode, ok, printJson } from "../lib/output"; import { exitCommand } from "../lib/command-exit"; import { readSecret } from "../lib/command-input"; -import { discoverPublicInstanceApi } from "../lib/public-instance-api"; export interface LoginOptions { token?: string; @@ -81,7 +80,7 @@ export async function runLogin(options: LoginOptions = {}): Promise { const existing = getContext(contextName); const local = !opts.cloud && !opts.apiUrl && !existing.apiUrl ? localConnectionEndpoints() : undefined; - let apiUrl = opts.cloud ? CLOUD_API_URL : opts.apiUrl || existing.apiUrl || local!.apiUrl; + const apiUrl = opts.cloud ? CLOUD_API_URL : opts.apiUrl || existing.apiUrl || local!.apiUrl; const normalizedApi = new HttpClient({ baseUrl: apiUrl }).apiUrl; const sameEndpoint = existing.apiUrl && new HttpClient({ baseUrl: existing.apiUrl }).apiUrl === normalizedApi; @@ -90,7 +89,7 @@ export async function runLogin(options: LoginOptions = {}): Promise { : opts.dashboardUrl || (sameEndpoint ? existing.dashboardUrl : undefined) || local?.dashboardUrl || - normalizedApi.slice(0, -4).replace(/\/api\/proxy$/, ""); + normalizedApi.slice(0, -4); let token: string | undefined = opts.tokenFile ? readSecret(opts.tokenFile) : opts.token; @@ -133,23 +132,13 @@ export async function runLogin(options: LoginOptions = {}): Promise { // Validate the token against an authenticated endpoint before storing. // 200 → valid; 403 → valid but lacks settings:read scope (still usable). let scoped = false; - for (let attempt = 0; ; attempt++) { - try { - const client = new OpenshipClient({ baseUrl: apiUrl, token, timeoutMs: 8000 }); - await client.tokens.list(); - break; - } catch (error) { - if (error instanceof ApiError && error.status === 403) { - scoped = true; - break; - } - // A missing/non-JSON route can mean the supplied URL is the dashboard. - // An actual authentication refusal must never switch endpoints. - if (attempt === 0 && !opts.cloud && error instanceof ApiError && - (error.status === 404 || error.message === "Invalid JSON response")) { - const discovered = await discoverPublicInstanceApi(apiUrl); - if (discovered) { apiUrl = discovered; continue; } - } + try { + const client = new OpenshipClient({ baseUrl: apiUrl, token, timeoutMs: 8000 }); + await client.tokens.list(); + } catch (error) { + if (error instanceof ApiError && error.status === 403) { + scoped = true; + } else { err( error instanceof ApiError && error.status === 401 ? "Token rejected by the API. Check that it is valid and not revoked." diff --git a/apps/cli/src/commands/service.ts b/apps/cli/src/commands/service.ts index 5243bdc7a..9f830de06 100644 --- a/apps/cli/src/commands/service.ts +++ b/apps/cli/src/commands/service.ts @@ -25,7 +25,6 @@ import { getShipClient, ApiError, hasShipCredentials } from "../lib/ship-client" import { isJsonMode, printJson, printTable, ok, err, info } from "../lib/output"; import { collect, parsePairs, readJsonInput } from "../lib/command-input"; import { fail, confirmOrExit, reportResult, reportExecResult } from "../lib/cmd-helpers"; -import { resolveServiceRef } from "../lib/service-ref"; // ─── Shared helpers ────────────────────────────────────────────────────────── @@ -87,7 +86,19 @@ async function listServices(projectId: string): Promise { /** Resolve a service ref (name or svc_ id) to its row within the stack. */ async function resolveService(projectId: string, ref: string): Promise { - return resolveServiceRef(getShipClient(), projectId, ref); + if (/^svc_/.test(ref)) return getShipClient().services.get(projectId, ref); + const services = await listServices(projectId); + const byId = services.find((s) => s.id === ref); + if (byId) return byId; + const byName = services.filter((s) => s.name === ref); + if (byName.length === 1) return byName[0]; + if (byName.length > 1) { + err(` "${ref}" matches ${byName.length} services — pass the service id (svc_…).`); + exitCommand(1); + } + const known = services.map((s) => s.name).join(", ") || "(none)"; + err(` No service "${ref}" in this stack. Services: ${known}`); + exitCommand(1); } // ─── list / get ─────────────────────────────────────────────────────────────── diff --git a/apps/cli/src/commands/up.ts b/apps/cli/src/commands/up.ts index 4c8e9bcd3..51864365e 100644 --- a/apps/cli/src/commands/up.ts +++ b/apps/cli/src/commands/up.ts @@ -11,7 +11,7 @@ import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { ensureDashboard } from "../lib/dashboard"; -import { installAndStart, serviceHeldPorts } from "../lib/service"; +import { installAndStart } from "../lib/service"; import { composeUp, composePrefetch, @@ -44,7 +44,6 @@ import { LocalExecutor } from "@repo/adapters"; import { resolveInstallInputs, headlessProvision, - provisionInstanceDomain, HeadlessInputError, } from "../lib/instance-provision"; import { mintBareInternalToken } from "../lib/internal-token"; @@ -285,26 +284,6 @@ export const upCommand = new Command("up") if (opts.fromSource || opts.source) return runFromSource(opts); if (opts.foreground) return runForeground(opts); const headless = !!(opts.nonInteractive || opts.yes); - // Validate requested provisioning before pulling images or stopping services. - if (headless || opts.managedEdge) { - try { - if (opts.managedEdge) { - opts.publicUrl = effectivePublicUrl(opts.publicUrl); - if (!opts.publicUrl || new URL(opts.publicUrl).protocol !== "https:") - throw new HeadlessInputError("--managed-edge requires --public-url https://your-domain (or an existing saved HTTPS URL)."); - if (opts.domainKind && opts.domainKind !== "custom") - throw new HeadlessInputError("--managed-edge requires --domain-kind custom."); - if (opts.hostname && opts.hostname !== new URL(opts.publicUrl).hostname) - throw new HeadlessInputError("--hostname must match --public-url when using --managed-edge."); - opts.trustProxy = true; - } - if (headless) upInstallInputs(opts); - } catch (error) { - reportCliMessage("error", (error as Error).message); - process.exit(1); - } - } - // Install method: Compose is the default when it can actually work (Docker on // Linux — the edge container needs host networking); else bare. `planMethod` // owns the decision so `--dry-run` predicts the same one. @@ -340,10 +319,9 @@ export const upCommand = new Command("up") if (!token) { reportCliMessage("warn", chalk.yellow( - "\n Couldn't read the stack's internal token (compose/.env). Run this command as the installation owner (or sudo) to finish admin setup.\n", + "\n Couldn't read the stack's internal token (compose/.env) — create the admin from the dashboard.\n", ), ); - process.exit(1); } else { await runHeadlessProvision( opts, @@ -351,18 +329,6 @@ export const upCommand = new Command("up") { token, method: "compose" }, ); } - } else if (opts.managedEdge) { - const result = await provisionInstanceDomain({ - port: started.apiPort, dashPort: started.dashPort, token: composeInternalToken() ?? undefined, - domain: { kind: "custom", hostname: new URL(opts.publicUrl!).hostname, acmeEmail: opts.acmeEmail, - edge: opts.edge === "takeover" || opts.edge === "migrate" ? opts.edge : "cancel" }, - onLog: message => console.log(chalk.dim(` ${message}`)), - }); - for (const warning of result.warnings) reportCliMessage("warn", warning); - if (!result.domainRegistered) { - reportCliMessage("error", "Managed domain registration did not complete. If this is a new install, run `openship` and choose Create first admin, then retry this command."); - process.exit(1); - } } return; } @@ -370,21 +336,6 @@ export const upCommand = new Command("up") if (headless) await runHeadlessProvision(opts, started, { method: "bare" }); }); -/** Flags and preflight share one provisioning interpretation. */ -function upInstallInputs(opts: UpOpts) { - return resolveInstallInputs({ - adminName: opts.adminName, - adminEmail: opts.adminEmail, - adminPassword: opts.adminPassword, - domainKind: opts.domainKind ?? (opts.managedEdge ? "custom" : undefined), - hostname: opts.hostname, - slug: opts.slug, - publicUrl: opts.publicUrl, - acmeEmail: opts.acmeEmail, - edge: opts.edge, - }); -} - /** * Headless install (bare service): after `startService` installs + supervises * the process, create the admin + register the domain from the flags, so a box @@ -398,7 +349,17 @@ export async function runHeadlessProvision( ): Promise { let inputs; try { - inputs = upInstallInputs(opts); + inputs = resolveInstallInputs({ + adminName: opts.adminName, + adminEmail: opts.adminEmail, + adminPassword: opts.adminPassword, + domainKind: opts.domainKind, + hostname: opts.hostname, + slug: opts.slug, + publicUrl: opts.publicUrl, + acmeEmail: opts.acmeEmail, + edge: opts.edge, + }); } catch (err) { if (err instanceof HeadlessInputError) { reportCliMessage("error", chalk.red(`\n ${err.message}\n`)); @@ -416,10 +377,8 @@ export async function runHeadlessProvision( method: extra?.method, onLog: (m) => console.log(chalk.dim(` ${m}`)), }); - for (const w of result.warnings) reportCliMessage("warn", chalk.yellow(` ⚠ ${w}`)); - if (opts.managedEdge && !result.domainRegistered) - throw new Error("Managed domain registration did not complete. Retry after resolving the domain warning above."); console.log(chalk.green(`\n ✓ Openship provisioned${result.liveUrl ? `: ${result.liveUrl}` : "."}`)); + for (const w of result.warnings) reportCliMessage("warn", chalk.yellow(` ⚠ ${w}`)); } catch (err) { observeCaughtError(err, "cli/commands/up"); reportCliMessage("error", chalk.red(`\n Headless provisioning failed: ${(err as Error).message}\n`)); @@ -682,7 +641,7 @@ async function runCompose(opts: UpOpts & { yes?: boolean }): Promise<{ apiPort: chalk.dim(" Images: api + dashboard + edge (OpenResty on :80/:443)\n") + chalk.dim(" Manage: openship stop · openship update · openship status\n") + // In headless mode the admin is bootstrapped below — don't tell the user to do it by hand. - (headless ? "" : chalk.dim(" Admin setup: run `openship` → Create first admin, or use `openship up --non-interactive --admin-email ` with OPENSHIP_ADMIN_PASSWORD set.\n")), + (headless ? "" : chalk.dim(" Create an admin: open the dashboard and register the first account.\n")), ); return { apiPort: res.apiPort, dashPort: res.dashPort }; } @@ -729,13 +688,9 @@ export async function startService( // No permanent port: switch off any occupied default / flag / remembered port // BEFORE writing the service unit, so the chosen ports are baked into its args. - // A re-run finds our own running service on its ports. installAndStart replaces - // that instance, so they're reclaimable rather than busy; otherwise every re-run - // waited out waitPortFree and then moved the install to new ports (#1570). const resolved = await resolvePorts({ api: opts.port ? Number(opts.port) : undefined, dashboard: opts.dashboardPort ? Number(opts.dashboardPort) : undefined, - reclaimable: await serviceHeldPorts(), }); const port = String(resolved.api); const dashPort = String(resolved.dashboard); @@ -937,6 +892,46 @@ async function runForeground(opts: UpOpts, source?: FromSourceRun): Promise instanceLog.write(d)); child.stderr.on("data", (d) => instanceLog.write(d)); + // Buffer output until healthy; on early exit, surface the tail. + let buffered = ""; + const buffer = (d: Buffer) => { + buffered += d.toString(); + }; + child.stdout.on("data", buffer); + child.stderr.on("data", buffer); + child.on("exit", (code) => { + if (code && code !== 0) { + spinner.fail(`Openship server exited (code ${code})`); + process.stderr.write(buffered.slice(-2000)); + process.exit(code); + } + }); + + const healthUrl = `http://127.0.0.1:${port}/api/health`; + let healthy = false; + for (let i = 0; i < 60 && child.exitCode === null; i++) { + await new Promise((r) => setTimeout(r, 1000)); + try { + const res = await fetch(healthUrl, { signal: AbortSignal.timeout(2000) }); + if (res.ok) { + healthy = true; + break; + } + } catch (diagnosticFailure) { + observeCaughtError(diagnosticFailure, "cli/commands/up"); + // not up yet + } + } + + if (!healthy) { + spinner.fail("Openship did not become healthy in time"); + process.stderr.write(buffered.slice(-2000)); + child.kill("SIGTERM"); + process.exit(1); + } + + spinner.succeed(`Openship API running at http://localhost:${port}`); + // Track every child so Ctrl-C / a fatal exit / `openship stop` tears them all // down together. The API + dashboard hold keep-alive sockets to EACH OTHER, // so SIGTERM alone can hang their graceful shutdown (mutual wait) — we MUST @@ -971,57 +966,6 @@ async function runForeground(opts: UpOpts, source?: FromSourceRun): Promise stopAll(0)); - process.on("SIGTERM", () => stopAll(0)); - - // Buffer output until healthy; on early exit, surface the tail. - let buffered = ""; - const buffer = (d: Buffer) => { - buffered += d.toString(); - }; - child.stdout.on("data", buffer); - child.stderr.on("data", buffer); - child.on("exit", (code) => { - if (code && code !== 0 && !stopping) { - spinner.fail(`Openship server exited (code ${code})`); - process.stderr.write(buffered.slice(-2000)); - process.exit(code); - } - }); - - const healthUrl = `http://127.0.0.1:${port}/api/health`; - let healthy = false; - for (let i = 0; i < 60 && child.exitCode === null && !stopping; i++) { - await new Promise((r) => setTimeout(r, 1000)); - try { - const res = await fetch(healthUrl, { signal: AbortSignal.timeout(2000) }); - if (res.ok) { - healthy = true; - break; - } - } catch (diagnosticFailure) { - observeCaughtError(diagnosticFailure, "cli/commands/up"); - // not up yet - } - } - - // Stopped while starting: stopAll is already taking the API down and exits. - if (stopping) return; - - if (!healthy) { - spinner.fail("Openship did not become healthy in time"); - process.stderr.write(buffered.slice(-2000)); - child.kill("SIGTERM"); - process.exit(1); - } - - spinner.succeed(`Openship API running at http://localhost:${port}`); // Dashboard (unless --no-ui): lazy-downloaded from GitHub releases, then run // alongside the API. A UI failure is non-fatal — the API keeps serving. @@ -1143,6 +1087,10 @@ async function runForeground(opts: UpOpts, source?: FromSourceRun): Promise process.stdout.write(d)); child.stderr.on("data", (d) => process.stderr.write(d)); + // stopAll owns the exit (it force-kills after a grace, THEN process.exit). + // Calling process.exit() here would kill that timer and orphan the tree. + process.on("SIGINT", () => stopAll(0)); + process.on("SIGTERM", () => stopAll(0)); // If the API dies, bring the dashboard down with it and exit with its code. child.on("exit", (code) => stopAll(code ?? 0)); } diff --git a/apps/cli/src/commands/wizard.ts b/apps/cli/src/commands/wizard.ts index ba716acb0..814fe0f28 100644 --- a/apps/cli/src/commands/wizard.ts +++ b/apps/cli/src/commands/wizard.ts @@ -1231,7 +1231,7 @@ export async function runControl(): Promise { `${chalk.dim("Dashboard".padEnd(11))}${dashUrl}\n` + (ports.api ? `${chalk.dim("API".padEnd(11))}http://localhost:${ports.api}\n` : "") + `${chalk.dim("Manager".padEnd(11))}${managerLabel}`, - "Openship is installed", + "Openship is already set up", ); // Crash-looping on a corrupt DB is the one case where "Start" won't help — @@ -1279,7 +1279,6 @@ export async function runControl(): Promise { : { value: "start", label: "Start the service" }, { value: "stop", label: "Stop the service", hint: "won't restart on boot" }, ...(corrupted ? [] : [{ value: "repair", label: "Repair database", hint: "backup → heal a corrupt DB" }]), - { value: "create-admin", label: "Create first admin", hint: "finish a new install; existing accounts stay intact" }, { value: "reset", label: "Reset admin password", hint: "sets a local email + password login" }, { value: "reconfigure", label: "Re-run setup", hint: "reconfigure domain / cloud / admin" }, { value: "quit", label: "Quit" }, @@ -1288,16 +1287,6 @@ export async function runControl(): Promise { ); switch (action) { - case "create-admin": { - const admin = await promptLocalAdmin(); - const result = await bootstrapAdmin(apiPort, admin); - outro(result.ok - ? result.message === "already-exists" - ? "An admin already exists. Use Reset admin password if you need to recover access." - : `Admin created. Sign in at ${primaryUrl}.` - : `Could not create the admin: ${result.message}`); - return; - } case "repair": { const res = await runRepair(); outro(res.healed ? chalk.green(res.detail) : chalk.yellow(res.detail)); diff --git a/apps/cli/src/index.ts b/apps/cli/src/index.ts index 69e24b6b6..24ae1a7b5 100644 --- a/apps/cli/src/index.ts +++ b/apps/cli/src/index.ts @@ -24,7 +24,6 @@ import { doctorCommand } from "./commands/doctor"; // Deploy loop import { deployCommand } from "./commands/deploy"; -import { launchCommand } from "./commands/launch"; import { deploymentCommand } from "./commands/deployment"; import { logsCommand } from "./commands/logs"; @@ -164,7 +163,6 @@ program.addCommand(doctorCommand); // Deploy loop program.addCommand(deployCommand); -program.addCommand(launchCommand); program.addCommand(deploymentCommand); program.addCommand(logsCommand); diff --git a/apps/cli/src/lib/custom-domain-endpoint.ts b/apps/cli/src/lib/custom-domain-endpoint.ts index b979265ff..1b1c1a8cf 100644 --- a/apps/cli/src/lib/custom-domain-endpoint.ts +++ b/apps/cli/src/lib/custom-domain-endpoint.ts @@ -1,79 +1,71 @@ -import { firstServicePort, resolveRedirectStatus, safeErrorMessage } from "@repo/core"; +import { safeErrorMessage } from "@repo/core"; import type { UpdateProjectInput } from "@repo/contracts"; import type { CliShipClient } from "./ship-client"; -import { resolveServiceRef } from "./service-ref"; +import { reportCliMessage } from "./output"; type PublicEndpoint = NonNullable[number]; -export interface CustomDomainTarget { service?: string; port?: number } - -/** Validate the target before claiming a hostname, then save through the same - * project/service API used by the dashboard. DNS verification and deployment - * remain explicit subsequent steps. */ -export async function prepareCustomDomainEndpoint( - ship: Pick, - projectId: string, - options: CustomDomainTarget = {}, -): Promise<(hostname: string) => Promise> { - const { project } = await ship.projects.getInfo(projectId); - if (!options.service && project.projectType !== "app") - throw new Error("This is a multi-service project. Pass --service and --port to select its route."); - if (!options.service && project.options.workloadType === "worker") - throw new Error("This worker has no public route. Configure a web workload before adding a domain."); - const service = options.service ? await resolveServiceRef(ship, projectId, options.service) : undefined; - const hasServer = !!service || project.options.hasServer; - const endpoints: PublicEndpoint[] = service?.publicEndpoints?.map(endpoint => ({ ...endpoint, redirectStatus: endpoint.redirectStatus !== undefined ? resolveRedirectStatus(endpoint.redirectStatus) : undefined })) ?? - (service ? [] : (project as typeof project & { publicEndpoints?: PublicEndpoint[] }).publicEndpoints ?? []); - const ports = service ? [...new Set([ - ...(service.ports ?? []).map(spec => firstServicePort([spec])), - ...(service.publicEndpoints ?? []).map(endpoint => endpoint.port), - Number(service.exposedPort), - ].filter((value): value is number => Number.isInteger(value) && Number(value) > 0 && Number(value) <= 65535))] : []; - const port = options.port ?? (service - ? ports.length === 1 ? ports[0] : undefined - : Number(project.options.productionPort || project.port)); - if (hasServer && (!Number.isInteger(port) || !port || port < 1 || port > 65535)) - throw new Error("Choose a valid container port with --port <1-65535>; services with multiple ports require an explicit target."); - if (!hasServer && options.port !== undefined) - throw new Error("A static project routes its output directory; --port requires a web service."); - - return async hostname => { - const host = hostname.trim().toLowerCase(); - try { - // Project info adds UI metadata. Send only the accepted save fields, keeping - // every existing target, hostname, redirect, and endpoint position intact. - const publicEndpoints: PublicEndpoint[] = endpoints.map((endpoint) => ({ - ...(endpoint.port !== undefined ? { port: endpoint.port } : {}), - ...(endpoint.targetPath !== undefined ? { targetPath: endpoint.targetPath } : {}), - ...(endpoint.domain !== undefined ? { domain: endpoint.domain } : {}), - ...(endpoint.customDomain !== undefined ? { customDomain: endpoint.customDomain } : {}), - ...(endpoint.domainType !== undefined ? { domainType: endpoint.domainType } : {}), - ...(endpoint.redirectTo !== undefined ? { redirectTo: endpoint.redirectTo } : {}), - ...(endpoint.redirectStatus !== undefined ? { redirectStatus: endpoint.redirectStatus } : {}), - })); - const endpoint = { domainType: "custom" as const, customDomain: host, ...(hasServer ? { port } : { targetPath: "/" }) }; - const index = publicEndpoints.findIndex(value => value.customDomain?.toLowerCase() === host); - if (index >= 0) { - if (options.port === undefined || publicEndpoints[index]!.port === port) return; - publicEndpoints[index] = { ...publicEndpoints[index], ...endpoint }; - } else publicEndpoints.push(endpoint); - if (service) await ship.services.update(projectId, service.id, { exposed: true, publicEndpoints }); - else await ship.projects.update(projectId, { publicEndpoints }); - } catch (error) { - throw new Error( - `Domain ${host} row still exists, but attaching its route failed: ${safeErrorMessage(error)}. Retry in the dashboard project ${projectId} Domains tab: configure this domain's target and save.`, - { cause: error }, - ); - } - }; -} - -/** Existing callers claim a domain before attaching its endpoint. */ +/** Attach the routing endpoint after claiming the domain, as the dashboard does. */ export async function attachCustomDomainEndpoint( - ship: Pick, + ship: Pick, projectId: string, hostname: string, ): Promise { - await (await prepareCustomDomainEndpoint(ship, projectId))(hostname); - return true; + const host = hostname.trim().toLowerCase(); + try { + const { project } = await ship.projects.getInfo(projectId); + const endpoints = + (project as typeof project & { publicEndpoints?: PublicEndpoint[] }).publicEndpoints ?? []; + if (endpoints.some((endpoint) => endpoint.customDomain?.toLowerCase() === host)) return true; + + if (project.options.workloadType === "worker") { + reportCliMessage( + "warn", + `Domain ${host} was added, but this worker has no public route. Configure a web workload and port before attaching it.`, + ); + return false; + } + + if (project.projectType !== "app") { + reportCliMessage( + "warn", + `Domain ${host} was added, but ${project.name || projectId} is a multi-service project, so routes belong to a service. Attach it to a service in the dashboard.`, + ); + return false; + } + + const hasServer = project.options.hasServer; + const port = Number(project.options.productionPort || project.port); + if (hasServer && (!Number.isInteger(port) || port < 1 || port > 65535)) { + reportCliMessage( + "warn", + `Domain ${host} was added, but the project has no valid server port and no public route. Configure a port in the dashboard Domains tab.`, + ); + return false; + } + + // Project info adds UI metadata. Send only the accepted save fields, keeping + // every existing target, hostname, redirect, and endpoint position intact. + const publicEndpoints: PublicEndpoint[] = endpoints.map((endpoint) => ({ + ...(endpoint.port !== undefined ? { port: endpoint.port } : {}), + ...(endpoint.targetPath !== undefined ? { targetPath: endpoint.targetPath } : {}), + ...(endpoint.domain !== undefined ? { domain: endpoint.domain } : {}), + ...(endpoint.customDomain !== undefined ? { customDomain: endpoint.customDomain } : {}), + ...(endpoint.domainType !== undefined ? { domainType: endpoint.domainType } : {}), + ...(endpoint.redirectTo !== undefined ? { redirectTo: endpoint.redirectTo } : {}), + ...(endpoint.redirectStatus !== undefined ? { redirectStatus: endpoint.redirectStatus } : {}), + })); + publicEndpoints.push({ + domainType: "custom", + customDomain: host, + ...(hasServer ? { port } : { targetPath: "/" }), + }); + await ship.projects.update(projectId, { publicEndpoints }); + return true; + } catch (error) { + throw new Error( + `Domain ${host} row still exists, but attaching its route failed: ${safeErrorMessage(error)}. Retry in the dashboard project ${projectId} Domains tab: configure this domain's target and save.`, + { cause: error }, + ); + } } diff --git a/apps/cli/src/lib/host-channel-preflight.ts b/apps/cli/src/lib/host-channel-preflight.ts index dd88c8dbf..b1ae9370e 100644 --- a/apps/cli/src/lib/host-channel-preflight.ts +++ b/apps/cli/src/lib/host-channel-preflight.ts @@ -188,7 +188,7 @@ async function realProbe(host: string, port: number): Promise { "-e", `OPENSHIP_PROBE_PORT=${port}`, "api", - "node", + "bun", "-e", PROBE_SCRIPT, ], diff --git a/apps/cli/src/lib/instance-provision.ts b/apps/cli/src/lib/instance-provision.ts index 33b13c440..b9801ebc7 100644 --- a/apps/cli/src/lib/instance-provision.ts +++ b/apps/cli/src/lib/instance-provision.ts @@ -268,6 +268,8 @@ export async function headlessProvision(opts: { }): Promise { const { port, inputs, token } = opts; const log = opts.onLog ?? (() => {}); + const warnings: string[] = []; + log("Waiting for the API to become healthy…"); if (!(await waitHealthy(port))) { throw new HeadlessInputError("The API did not become healthy in time — check `openship logs`."); @@ -277,24 +279,8 @@ export async function headlessProvision(opts: { const admin = await bootstrapOrReset(port, inputs.admin, token); if (!admin.ok) throw new HeadlessInputError(`Could not create the admin account: ${admin.message}`); - return { adminReady: true, ...await provisionInstanceDomain({ ...opts, domain: inputs.domain }) }; -} - -/** Register routing independently of credentials, including managed-edge - * re-runs on an already initialized Compose install. */ -export async function provisionInstanceDomain(opts: { - port: string; - dashPort?: string; - domain: InstallInputs["domain"]; - token?: string; - onLog?: (msg: string) => void; - onSlugTaken?: (taken: string) => Promise; -}): Promise> { - const { port, token } = opts; - const log = opts.onLog ?? (() => {}); - const warnings: string[] = []; const dashPort = opts.dashPort ? Number(opts.dashPort) : undefined; - const d = opts.domain; + const d = inputs.domain; let liveUrl: string | undefined; let domainRegistered = false; @@ -406,5 +392,5 @@ export async function provisionInstanceDomain(opts: { } } - return { domainRegistered, liveUrl, warnings }; + return { adminReady: true, domainRegistered, liveUrl, warnings }; } diff --git a/apps/cli/src/lib/public-instance-api.ts b/apps/cli/src/lib/public-instance-api.ts deleted file mode 100644 index 6df441097..000000000 --- a/apps/cli/src/lib/public-instance-api.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { SDK_CAPABILITIES } from "@repo/contracts"; -import { HttpClient } from "@repo/sdk/client"; - -/** A public dashboard may mount the API beneath /api/proxy. Probe without - * credentials and never follow redirects or infer another origin. */ -export async function discoverPublicInstanceApi(baseUrl: string): Promise { - const base = new HttpClient({ baseUrl }).apiUrl.slice(0, -4); - if (/\/(?:api|api\/proxy)$/.test(new URL(baseUrl).pathname.replace(/\/+$/, ""))) return null; - const candidate = `${base}/api/proxy`; - try { - const response = await fetch(`${candidate}/api/health`, { - headers: { Accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(3_000), - }); - if (!response.ok) return null; - const health = await response.json() as { status?: string; sdk?: { protocol?: number } }; - return health?.status === "ok" && health.sdk?.protocol === SDK_CAPABILITIES.protocol ? candidate : null; - } catch { - // diagnostics-ignore: Optional credential-free discovery; keep the original login failure when this probe cannot identify an API. - return null; - } -} diff --git a/apps/cli/src/lib/service-ref.ts b/apps/cli/src/lib/service-ref.ts deleted file mode 100644 index 619ebbc17..000000000 --- a/apps/cli/src/lib/service-ref.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { CliShipClient } from "./ship-client"; - -/** Resolve only within the selected project; never fall back to another stack. */ -export async function resolveServiceRef(ship: Pick, projectId: string, ref: string) { - if (/^svc_/.test(ref)) return ship.services.get(projectId, ref); - const services = await ship.services.list(projectId); - const byId = services.find(service => service.id === ref); - if (byId) return byId; - const matches = services.filter(service => service.name === ref); - if (matches.length === 1) return matches[0]!; - if (matches.length > 1) throw new Error(`"${ref}" matches ${matches.length} services — pass the service id (svc_…).`); - throw new Error(`No service "${ref}" in this stack. Services: ${services.map(service => service.name).join(", ") || "(none)"}`); -} diff --git a/apps/cli/src/lib/service.ts b/apps/cli/src/lib/service.ts index 989a69114..b807497ba 100644 --- a/apps/cli/src/lib/service.ts +++ b/apps/cli/src/lib/service.ts @@ -15,7 +15,6 @@ import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, writeFileSync, rmSync, readFileSync } from "node:fs"; import { homedir } from "node:os"; import { join, resolve } from "node:path"; -import { LocalExecutor, probeListeningPortOwners } from "@repo/adapters"; import { readCliInstall } from "./cli-install"; import { IS_ALT_HOME, LOG_DIR, OS_DIR } from "./paths"; @@ -96,9 +95,9 @@ function runArgv(flags: UpFlags): string[] { return [runtime, ...args, ...upArgs(flags)]; } -function run(cmd: string, args: string[]): { ok: boolean; status: number | null; out: string } { +function run(cmd: string, args: string[]): { ok: boolean; out: string } { const r = spawnSync(cmd, args, { encoding: "utf8" }); - return { ok: r.status === 0, status: r.status, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() }; + return { ok: r.status === 0, out: `${r.stdout ?? ""}${r.stderr ?? ""}`.trim() }; } /** Block synchronously for `ms` — restart()/serviceStatus() are sync and the @@ -127,38 +126,6 @@ function launchdLastExit(): number | null { return m ? Number(m[1]) : null; } -/** - * `launchctl bootout` returns before launchd has removed the job, and - * bootstrapping the same label while it's still there fails with - * `5: Input/output error`. Wait (up to ~10s) until `launchctl list` no longer - * knows the label. - */ -function waitForLaunchdUnload(bootoutError: string): void { - for (let i = 0; i <= 50; i++) { - const result = run("launchctl", ["list", MAC_LABEL]); - // launchctl returns 113 when this service label is absent. - if (result.status === 113) return; - if (!result.ok) { - throw new Error( - `Couldn't check launchd agent ${MAC_LABEL}: ${result.out || "launchctl list failed"}`, - ); - } - if (i < 50) sleepSync(200); - } - throw new Error( - `launchd agent ${MAC_LABEL} is still loaded after 10s${bootoutError ? `: ${bootoutError}` : ""}`, - ); -} - -/** Wait for launchd to report a live PID after requesting a start. */ -function waitForLaunchdStart(): boolean { - for (let i = 0; i < 6; i++) { - sleepSync(500); - if (launchdPid() != null) return true; - } - return false; -} - function isRoot(): boolean { return typeof process.getuid === "function" && process.getuid() === 0; } @@ -304,25 +271,14 @@ export function installAndStart(flags: UpFlags): ServiceResult { if (kind === "launchd") { mkdirSync(join(HOME, "Library", "LaunchAgents"), { recursive: true }); - const uid = String(process.getuid?.() ?? ""); // Replace any previous instance first so a re-run picks up new flags. - const bootout = run("launchctl", ["bootout", `gui/${uid}/${MAC_LABEL}`]); - waitForLaunchdUnload(bootout.ok ? "" : bootout.out); + run("launchctl", ["bootout", `gui/${process.getuid?.() ?? ""}/${MAC_LABEL}`]); writeFileSync(MAC_PLIST, plist(flags)); + const uid = String(process.getuid?.() ?? ""); let r = run("launchctl", ["bootstrap", `gui/${uid}`, MAC_PLIST]); if (!r.ok) r = run("launchctl", ["load", "-w", MAC_PLIST]); // older macOS fallback if (!r.ok) throw new Error(`launchctl failed to load the agent: ${r.out}`); - // `load -w` prints "Load failed" but still exits 0, and an agent can load and - // crash at once. As in restart(), only report success once a PID is live. - if (waitForLaunchdStart()) { - return { kind, detail: `launchd agent ${MAC_LABEL} (logs: ${LOG_DIR})` }; - } - const exit = launchdLastExit(); - throw new Error( - `launchd agent ${MAC_LABEL} didn't start${exit != null ? ` (last exit ${exit})` : ""}${ - r.out ? `: ${r.out}` : "" - } — check logs in ${LOG_DIR}`, - ); + return { kind, detail: `launchd agent ${MAC_LABEL} (logs: ${LOG_DIR})` }; } if (kind === "systemd-user" || kind === "systemd-system") { @@ -374,7 +330,10 @@ export function restart(): { restarted: boolean; detail: string } { // (port already bound, PGlite data-dir lock held by another process, a bad // bundle/env). Poll for a live PID so we only claim success once it's // actually running. - if (waitForLaunchdStart()) return { restarted: true, detail: `restarted ${MAC_LABEL}` }; + for (let i = 0; i < 6; i++) { + sleepSync(500); + if (launchdPid() != null) return { restarted: true, detail: `restarted ${MAC_LABEL}` }; + } const exit = launchdLastExit(); return { restarted: false, @@ -431,50 +390,6 @@ export function serviceStatus(): { kind: ServiceKind; installed: boolean; runnin return { kind, installed: false, running: false }; } -/** Only reclaim remembered listeners owned by the installed service's process tree. - * A saved port alone proves no ownership (for example, after `up --no-ui`). - * Unknown service PIDs or incomplete listener ownership use normal port resolution. */ -export async function serviceHeldPorts(): Promise { - const kind = detectKind(); - let pid: number | null = null; - if (kind === "launchd") pid = launchdPid(); - else if (kind === "systemd-user" || kind === "systemd-system") { - const args = kind === "systemd-user" ? ["--user"] : []; - const result = run("systemctl", [...args, "show", SYSTEMD_NAME, "--property=MainPID", "--value"]); - if (result.ok && /^\d+$/.test(result.out)) pid = Number(result.out); - } - // Scheduled Tasks do not expose an authoritative process ID through schtasks. - if (!pid || !Number.isSafeInteger(pid) || pid <= 1) return []; - const processes = run("ps", ["-axo", "pid=,ppid="]); - if (!processes.ok) return []; - const parents = new Map(); - for (const line of processes.out.split("\n")) { - const match = line.match(/^\s*(\d+)\s+(\d+)\s*$/); - if (match) parents.set(Number(match[1]), Number(match[2])); - } - if (!parents.has(pid)) return []; - const belongsToService = (owner: number | null): boolean => { - const seen = new Set(); - while (owner != null && owner > 1 && !seen.has(owner)) { - if (owner === pid) return true; - seen.add(owner); - owner = parents.get(owner) ?? null; - } - return false; - }; - const stored = readStoredPorts(); - const ports = [...new Set([stored?.api, stored?.dashboard])].filter( - (port): port is number => typeof port === "number" && Number.isInteger(port) && port > 0 && port <= 65535, - ); - const executor = new LocalExecutor(); - const held = await Promise.all(ports.map(async (port) => { - const owners = await probeListeningPortOwners(executor, port); - return owners.checked && owners.ownershipComplete && owners.occupants.length > 0 && - owners.occupants.every((owner) => belongsToService(owner.pid)) ? port : null; - })); - return held.filter((port): port is number => port !== null); -} - /** Stop AND disable the service — it won't restart or return on reboot. */ /** * Best-effort reaper for processes still holding our canonical API/dashboard diff --git a/apps/cli/src/lib/up-plan.ts b/apps/cli/src/lib/up-plan.ts index 119d75a95..ee9d9f6c6 100644 --- a/apps/cli/src/lib/up-plan.ts +++ b/apps/cli/src/lib/up-plan.ts @@ -30,7 +30,7 @@ import { previewHostEdge, type EdgePreview } from "./edge-preflight"; import { DEFAULT_REPO, SOURCE_CHECKOUT_DIR, SOURCE_DIST_DIR } from "./from-source"; import { AUTH_SECRET_FILE, DATA_DIR, INTERNAL_TOKEN_FILE, LOG_DIR } from "./paths"; import { PORTS_FILE, resolvePorts, type ResolvedPorts } from "./ports"; -import { installStepFor, preview as previewService, serviceHeldPorts, type ServiceKind } from "./service"; +import { installStepFor, preview as previewService, type ServiceKind } from "./service"; /** How `up` would run: install a supervised service, or stay attached. */ export type UpMode = "service" | "foreground" | "from-source"; @@ -136,7 +136,6 @@ export async function planUp(opts: UpPlanOpts): Promise { { api: opts.port ? Number(opts.port) : undefined, dashboard: opts.dashboardPort ? Number(opts.dashboardPort) : undefined, - reclaimable: mode === "service" ? await serviceHeldPorts() : [], }, { persist: false }, ), diff --git a/apps/cli/test/e2e/domain.test.ts b/apps/cli/test/e2e/domain.test.ts index cae63fd24..e1d2405cf 100644 --- a/apps/cli/test/e2e/domain.test.ts +++ b/apps/cli/test/e2e/domain.test.ts @@ -86,9 +86,9 @@ describe("openship domain add", () => { : { status: 201, json: ADDED }); const { err, code } = await runCommand(domainCommand, ["add", "app.example.com", "-p", "prj1"]); expect(code).toBe(0); - const creation = fetchStub.calls.find(call => call.method === "POST")!; - expect(creation.url).toBe(`${API}/domains`); - expect(creation.body).toEqual({ projectId: "prj1", hostname: "app.example.com", isPrimary: false }); + expect(fetchStub.calls[0].method).toBe("POST"); + expect(fetchStub.calls[0].url).toBe(`${API}/domains`); + expect(fetchStub.calls[0].body).toEqual({ projectId: "prj1", hostname: "app.example.com", isPrimary: false }); expect(err).toContain("openship domain verify d9"); // next-step hint names the new id }); @@ -99,7 +99,7 @@ describe("openship domain add", () => { ? { json: { data: projectInfo.project } } : { status: 201, json: ADDED }); await runCommand(domainCommand, ["add", "app.example.com", "-p", "prj1", "--primary"]); - expect(fetchStub.calls.find(call => call.method === "POST")!.body).toMatchObject({ isPrimary: true }); + expect(fetchStub.calls[0].body).toMatchObject({ isPrimary: true }); }); it("emits the domain and its DNS records as JSON in json mode", async () => { diff --git a/apps/cli/test/e2e/host-channel-container.test.ts b/apps/cli/test/e2e/host-channel-container.test.ts deleted file mode 100644 index 0a202d7f3..000000000 --- a/apps/cli/test/e2e/host-channel-container.test.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { checkHostChannel } from "../../src/lib/host-channel-preflight"; - -// Requires an installed Compose stack with a configured, reachable host SSH channel. -// Run with OPENSHIP_TEST_HOST_CHANNEL=1; never change the host firewall. -describe.skipIf(process.env.OPENSHIP_TEST_HOST_CHANNEL !== "1")("host channel in the API image", () => { - it("reaches the configured host from the actual API container", async () => { - const result = await checkHostChannel(); - expect(result.configured).toBe(true); - expect(result.code).toBe("open"); - }); - - it("distinguishes a refused connection from an unavailable probe", async () => { - const result = await checkHostChannel({ - channel: () => ({ host: "127.0.0.1", port: 1, user: "unused" }), - }); - expect(result.code).toBe("refused"); - }); -}); diff --git a/apps/cli/test/e2e/launch.test.ts b/apps/cli/test/e2e/launch.test.ts deleted file mode 100644 index 0dbc85871..000000000 --- a/apps/cli/test/e2e/launch.test.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -const h = vi.hoisted(() => ({ - confirm: vi.fn(), - note: vi.fn(), - info: vi.fn(), - wizard: vi.fn(), - start: vi.fn(), - composeStart: vi.fn(), - wait: vi.fn(), - open: vi.fn(), - method: "compose" as string | null, - installed: false, - resuming: false, - local: { apiUrl: "http://127.0.0.1:4100", dashboardUrl: "https://my-server.test" }, -})); -vi.mock("@clack/prompts", () => ({ - confirm: h.confirm, - isCancel: (v: unknown) => typeof v === "symbol", - note: h.note, - log: { info: h.info }, - outro: vi.fn(), -})); -vi.mock("@repo/onboarding", () => ({ waitForApi: h.wait })); -vi.mock("../../src/lib/local-connection", () => ({ localConnectionEndpoints: () => h.local })); -vi.mock("../../src/lib/compose", () => ({ - readInstallMethod: () => h.method, - composeStart: h.composeStart, -})); -vi.mock("../../src/lib/service", () => ({ serviceStatus: () => ({ installed: h.installed }) })); -vi.mock("../../src/lib/ports", () => ({ storedDashboardPort: () => 3100 })); -vi.mock("../../src/commands/wizard", () => ({ - isSetupInProgress: () => h.resuming, - runWizard: h.wizard, -})); -vi.mock("../../src/commands/up", () => ({ startService: h.start })); -vi.mock("open", () => ({ default: h.open })); - -let tty: PropertyDescriptor | undefined; -beforeEach(() => { - vi.resetModules(); - vi.resetAllMocks(); - tty = Object.getOwnPropertyDescriptor(process.stdin, "isTTY"); - Object.defineProperty(process.stdin, "isTTY", { value: true, configurable: true }); - h.method = "compose"; - h.installed = false; - h.resuming = false; - h.local = { apiUrl: "http://127.0.0.1:4100", dashboardUrl: "https://my-server.test" }; - h.wait.mockResolvedValue(true); - h.confirm.mockResolvedValue(true); - h.composeStart.mockReturnValue(true); - vi.stubEnv("SSH_CONNECTION", ""); - vi.stubEnv("OPENSHIP_API_URL", "https://api.openship.io"); - vi.stubEnv("OPENSHIP_TOKEN", "must-not-be-used"); -}); -afterEach(() => { - if (tty) Object.defineProperty(process.stdin, "isTTY", tty); - else Reflect.deleteProperty(process.stdin, "isTTY"); - vi.unstubAllEnvs(); -}); -async function launch(args: string[]) { - const { launchCommand } = await import("../../src/commands/launch"); - return launchCommand.parseAsync(args, { from: "user" }); -} - -describe("deploy button local launch", () => { - it("reuses the installation and opens the existing wizard, ignoring ambient Cloud credentials", async () => { - await launch(["--repo", "https://github.com/owner/repo", "--branch", "release/v2"]); - expect(h.wizard).not.toHaveBeenCalled(); - expect(h.start).not.toHaveBeenCalled(); - expect(h.composeStart).not.toHaveBeenCalled(); - expect(h.wait.mock.calls.every(([options]) => options.apiUrl === "http://127.0.0.1:4100")).toBe( - true, - ); - const url = new URL(h.open.mock.calls[0][0]); - expect(url.origin).toBe("https://my-server.test"); - expect(Buffer.from(url.pathname.split("/").pop()!, "base64url").toString()).toBe("owner/repo"); - expect(Object.fromEntries(url.searchParams)).toEqual({ - branch: "release/v2", - destination: "server", - }); - }); - it("finishes interactive setup before resolving the new instance URL", async () => { - h.method = null; - h.wizard.mockImplementation(async () => { - h.local.dashboardUrl = "https://new-server.test"; - }); - await launch(["--app", "n8n"]); - expect(h.wizard).toHaveBeenCalledOnce(); - expect(h.open).toHaveBeenCalledExactlyOnceWith( - "https://new-server.test/apps/new/n8n?destination=server", - ); - }); - it("does not install when setup is declined", async () => { - h.method = null; - h.confirm.mockResolvedValue(false); - await expect(launch(["--app", "n8n"])).rejects.toMatchObject({ code: 0 }); - expect(h.wizard).not.toHaveBeenCalled(); - expect(h.wait).not.toHaveBeenCalled(); - expect(h.open).not.toHaveBeenCalled(); - }); - it("starts an existing stopped Compose installation only after confirmation", async () => { - h.wait.mockResolvedValueOnce(false); - await launch(["--app", "n8n"]); - expect(h.composeStart).toHaveBeenCalledOnce(); - expect(h.wizard).not.toHaveBeenCalled(); - expect(h.confirm.mock.calls[0][0].message).toContain("Start the existing"); - }); - it("refuses a broken existing installation without launching an unready dashboard", async () => { - h.wait.mockResolvedValue(false); - h.composeStart.mockReturnValue(false); - await expect(launch(["--app", "n8n"])).rejects.toThrow("Could not start"); - expect(h.open).not.toHaveBeenCalled(); - expect(h.wizard).not.toHaveBeenCalled(); - }); - it("prints a private dashboard tunnel for SSH users without opening a server-side browser", async () => { - vi.stubEnv("SSH_CONNECTION", "test-ssh"); - h.local.dashboardUrl = "http://localhost:3100"; - await launch(["--app", "n8n"]); - expect(h.open).not.toHaveBeenCalled(); - expect(h.note.mock.calls.some(([value]) => value.includes("ssh -L 3100:127.0.0.1:3100"))).toBe( - true, - ); - }); - it("rejects invalid sources before any installation or network activity", async () => { - await expect(launch(["--repo", "https://token@github.com/a/b"])).rejects.toThrow( - "without credentials", - ); - expect(h.wizard).not.toHaveBeenCalled(); - expect(h.wait).not.toHaveBeenCalled(); - expect(h.confirm).not.toHaveBeenCalled(); - }); - it("never guesses confirmation answers without a terminal", async () => { - Object.defineProperty(process.stdin, "isTTY", { value: false, configurable: true }); - await expect(launch(["--app", "n8n"])).rejects.toThrow("interactive terminal"); - expect(h.wizard).not.toHaveBeenCalled(); - expect(h.wait).not.toHaveBeenCalled(); - }); -}); diff --git a/apps/cli/test/e2e/login.test.ts b/apps/cli/test/e2e/login.test.ts index 1116501fd..b869db092 100644 --- a/apps/cli/test/e2e/login.test.ts +++ b/apps/cli/test/e2e/login.test.ts @@ -48,7 +48,6 @@ vi.mock("../../src/lib/local-connection", () => ({ import { loginCommand } from "../../src/commands/login"; import { CLOUD_API_URL, CLOUD_DASHBOARD_URL, LOCAL_DASHBOARD_URL } from "@repo/core"; -import { SDK_CAPABILITIES } from "@repo/contracts"; import { runCommand, stubFetch, type FetchStub } from "../helpers/harness"; import { setJsonMode } from "../../src/lib/output"; @@ -68,38 +67,6 @@ afterEach(() => { }); describe("openship login endpoint preservation", () => { - it.each([404, 200])("discovers the same-origin API after a dashboard response (%s) and saves it", async (status) => { - fetchStub.restore(); - fetchStub = stubFetch(request => { - if (request.url === "https://ship.example.com/api/tokens") return { status, text: "Dashboard" }; - if (request.url.endsWith("/health")) { - expect(request.headers.authorization).toBeUndefined(); - return { json: { status: "ok", sdk: SDK_CAPABILITIES } }; - } - expect(request.url).toBe("https://ship.example.com/api/proxy/api/tokens"); - expect(request.headers.authorization).toBe("Bearer opsh_pat_test"); - return { json: { data: [] } }; - }); - const result = await runCommand(loginCommand, ["--api-url", "https://ship.example.com", "--token", "opsh_pat_test"]); - expect(result.code).toBe(0); - expect(h.added.at(-1)?.opts).toMatchObject({ apiUrl: "https://ship.example.com/api/proxy", dashboardUrl: "https://ship.example.com" }); - expect(fetchStub.calls).toHaveLength(3); - }); - - it("does not send a token to a guessed endpoint without a valid API health response", async () => { - fetchStub.restore(); - fetchStub = stubFetch(() => ({ status: 404, json: { error: "Not found" } })); - const result = await runCommand(loginCommand, ["--api-url", "https://ship.example.com", "--token", "opsh_pat_test"]); - expect(result.code).toBe(1); - expect(h.added).toEqual([]); - expect(fetchStub.calls.map(call => call.url)).toEqual(["https://ship.example.com/api/tokens", "https://ship.example.com/api/proxy/api/health"]); - expect(fetchStub.calls[1]!.headers.authorization).toBeUndefined(); - }); - - it("derives the dashboard correctly for an explicitly supplied proxy API", async () => { - await runCommand(loginCommand, ["--api-url", "https://ship.example.com/api/proxy", "--token", "opsh_pat_test"]); - expect(h.added.at(-1)?.opts.dashboardUrl).toBe("https://ship.example.com"); - }); it("guides a fresh interactive login to Cloud and opens its token page", async () => { h.interactive = true; const result = await runCommand(loginCommand, []); diff --git a/apps/cli/test/e2e/up.test.ts b/apps/cli/test/e2e/up.test.ts index d1716f857..8ffcf15c7 100644 --- a/apps/cli/test/e2e/up.test.ts +++ b/apps/cli/test/e2e/up.test.ts @@ -207,8 +207,6 @@ beforeEach(() => { (upCommand as any).setOptionValue?.("edge", undefined); (upCommand as any).setOptionValue?.("compose", undefined); (upCommand as any).setOptionValue?.("resetSecrets", undefined); - for (const key of ["managedEdge", "publicUrl", "trustProxy", "nonInteractive", "yes", "adminEmail", "adminPassword", "domainKind", "hostname"]) - upCommand.setOptionValue(key, undefined); con = captureConsole(); }); @@ -220,68 +218,6 @@ afterEach(() => { }); describe("openship up --compose (edge chain)", () => { - it("gives a usable first-admin instruction after an ordinary install", async () => { - const result = await runCommand(upCommand, ["--compose"]); - expect(result.code).toBe(0); - expect(con.text()).toContain("Create first admin"); - expect(con.text()).not.toContain("register the first account"); - }); - - it("refuses incomplete non-interactive setup before changing the stack", async () => { - const result = await runCommand(upCommand, ["--compose", "--non-interactive"]); - expect(result.code).toBe(1); - expect(h.prefetchCalls).toBe(0); - expect(h.composeUpCalls).toBe(0); - expect(con.text()).toContain("--admin-email"); - }); - - it("requires an HTTPS hostname before starting managed-edge installation", async () => { - const result = await runCommand(upCommand, ["--compose", "--managed-edge", "--public-url", "http://ops.example.com"]); - expect(result.code).toBe(1); - expect(h.composeUpCalls).toBe(0); - expect(con.text()).toContain("https://"); - }); - - it("honors managed-edge in Compose without changing admin credentials", async () => { - fetchStub = stubFetch(request => { - expect(request.url).toContain("/api/system/self-register"); - expect(request.body).toMatchObject({ domainType: "custom", hostname: "ops.example.com", dashPort: 3001 }); - return { json: { url: "https://ops.example.com" } }; - }); - const result = await runCommand(upCommand, ["--compose", "--managed-edge", "--public-url", "https://ops.example.com"]); - expect(result.code, result.err).toBe(0); - expect(fetchStub.calls).toHaveLength(1); - expect(fetchStub.calls[0]!.headers["x-internal-token"]).toBe("tok"); - }); - - it("provisions the requested managed domain during headless Compose setup", async () => { - fetchStub = stubFetch(request => { - if (request.url.endsWith("/api/health")) return { json: { status: "ok" } }; - if (request.url.endsWith("/api/system/bootstrap-admin")) return { json: { success: true } }; - expect(request.url).toContain("/api/system/self-register"); - expect(request.body).toMatchObject({ domainType: "custom", hostname: "ops.example.com" }); - return { json: { url: "https://ops.example.com" } }; - }); - const result = await runCommand(upCommand, ["--compose", "--managed-edge", "--public-url", "https://ops.example.com", - "--non-interactive", "--admin-email", "owner@example.com", "--admin-password", "strong-initial-password"]); - expect(result.code, con.text()).toBe(0); - expect(fetchStub.calls.map(call => new URL(call.url).pathname)).toEqual([ - "/api/health", "/api/system/bootstrap-admin", "/api/system/self-register", - ]); - }); - - it("does not report managed-edge success when registration fails", async () => { - fetchStub = stubFetch(request => { - if (request.url.endsWith("/api/health")) return { json: { status: "ok" } }; - if (request.url.endsWith("/api/system/bootstrap-admin")) return { json: { success: true } }; - return { status: 503, json: { error: "Edge unavailable" } }; - }); - const result = await runCommand(upCommand, ["--compose", "--managed-edge", "--public-url", "https://ops.example.com", - "--non-interactive", "--admin-email", "owner@example.com", "--admin-password", "strong-initial-password"]); - expect(result.code).toBe(1); - expect(con.text()).toContain("Managed domain registration did not complete"); - expect(con.text()).not.toContain("✓ Openship provisioned"); - }); it("exits before the edge preflight when docker/compose is missing", async () => { h.hasDocker = false; const r = await runCommand(upCommand, ["--compose"]); diff --git a/apps/cli/test/unit/compose-env-preserve.test.ts b/apps/cli/test/unit/compose-env-preserve.test.ts index 7ea232daa..1ca62a9cd 100644 --- a/apps/cli/test/unit/compose-env-preserve.test.ts +++ b/apps/cli/test/unit/compose-env-preserve.test.ts @@ -1753,13 +1753,10 @@ describe("composeUp — the host channel is provisioned out loud (#509)", () => seedHostKey(); h.channelAuth = () => ({ status: 0, stdout: "openship-sudo=refused\n", stderr: "" }); - // Select a non-root session explicitly: the test runner may itself be root, - // whose SSH login already has privilege and needs no sudo warning. - await composeUp({ hostSshUser: "ops" }); + await composeUp({}); // A working channel, so it IS written — just one with no route to root. expect(writtenEnv().OPENSHIP_HOST_SSH_HOST).toBe("host.docker.internal"); - expect(writtenEnv().OPENSHIP_HOST_SSH_USER).toBe("ops"); expect(warned.join("\n")).toContain("no route to it"); }); diff --git a/apps/cli/test/unit/custom-domain-endpoint.test.ts b/apps/cli/test/unit/custom-domain-endpoint.test.ts index 45f0154c9..39d360423 100644 --- a/apps/cli/test/unit/custom-domain-endpoint.test.ts +++ b/apps/cli/test/unit/custom-domain-endpoint.test.ts @@ -4,8 +4,6 @@ const h = vi.hoisted(() => ({ project: {} as Record, rows: [] as unknown[], updates: [] as unknown[], - services: [] as Array>, - serviceUpdates: [] as unknown[], updateError: false, })); vi.mock("../../src/lib/ship-client", async (importOriginal) => { @@ -32,18 +30,6 @@ vi.mock("../../src/lib/ship-client", async (importOriginal) => { h.updates.push({ id, input }); }, }, - services: { - list: async () => h.services, - get: async (_project: string, id: string) => { - const service = h.services.find(service => service.id === id); - if (!service) throw new Error("Service not found in project"); - return service; - }, - update: async (project: string, id: string, input: unknown) => { - if (h.updateError) throw new Error("update unavailable"); - h.serviceUpdates.push({ project, id, input }); - }, - }, domains: { verify: async () => { throw new Error("verification unavailable"); @@ -73,8 +59,6 @@ beforeEach(() => { h.rows = []; h.updates = []; h.updateError = false; - h.services = []; - h.serviceUpdates = []; }); afterEach(() => vi.restoreAllMocks()); @@ -138,48 +122,28 @@ describe("CLI custom domain routing", () => { expect(h.updates).toEqual([]); }); - it("refuses a portless worker before claiming a domain", async () => { + it("warns without attaching a portless worker or failing the command", async () => { h.project = { ...h.project, hasServer: false, workloadType: "worker", port: null }; + const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); const result = await add(); - expect(result.code).toBe(1); - expect(h.rows).toEqual([]); + expect(result.code).toBe(0); + expect(h.rows).toHaveLength(1); expect(h.updates).toEqual([]); - expect(result.err).toContain("worker has no public route"); + expect(warning.mock.calls.flat().join(" ")).toMatch(/worker.*no public route/i); + expect(result.err).not.toContain("routed on the next deploy"); }); - it.each(["services", "monorepo"])("requires an explicit target before claiming a domain for %s", async projectType => { - h.project = { ...h.project, projectType }; + it.each(["services", "monorepo"])("warns without attaching a %s project", async (projectType) => { + h.project = { ...h.project, name: "My project", projectType }; + const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); const result = await add(); - expect(result.code).toBe(1); - expect(h.rows).toEqual([]); - expect(result.err).toContain("--service"); - }); - - it.each(["web", "svc_web"])("attaches to the project-scoped service selected by %s", async ref => { - h.project.projectType = "services"; - const existing = [{ domainType: "free", domain: "existing", port: 8080 }]; - h.services = [{ id: "svc_web", name: "web", ports: ["8080:3000"], publicEndpoints: existing }]; - const result = await runCommand(domainCommand, ["add", "app.example.com", "-p", "project-1", "--service", ref, "--port", "3000"]); - expect(result.code, result.err).toBe(0); + expect(result.code).toBe(0); + expect(h.rows).toHaveLength(1); expect(h.updates).toEqual([]); - expect(h.serviceUpdates).toEqual([{ project: "project-1", id: "svc_web", input: { exposed: true, publicEndpoints: [...existing, { domainType: "custom", customDomain: "app.example.com", port: 3000 }] } }]); - }); - - it.each(["unknown", "svc_foreign"])("rejects an unknown or foreign service %s before claiming the hostname", async ref => { - h.project.projectType = "services"; - const result = await runCommand(domainCommand, ["add", "app.example.com", "-p", "project-1", "--service", ref, "--port", "3000"]); - expect(result.code).toBe(1); - expect(h.rows).toEqual([]); - expect(h.serviceUpdates).toEqual([]); - }); - - it("requires a port when the selected service has several possible targets", async () => { - h.project.projectType = "services"; - h.services = [{ id: "svc_web", name: "web", ports: ["3000", "3001"] }]; - const result = await runCommand(domainCommand, ["add", "app.example.com", "-p", "project-1", "--service", "web"]); - expect(result.code).toBe(1); - expect(h.rows).toEqual([]); - expect(result.err).toContain("--port"); + expect(warning).toHaveBeenCalledWith( + "Domain app.example.com was added, but My project is a multi-service project, so routes belong to a service. Attach it to a service in the dashboard.", + ); + expect(result.err).not.toContain("routed on the next deploy"); }); it.each(["domain", "edge"])( diff --git a/apps/cli/test/unit/headless-provision-domain.test.ts b/apps/cli/test/unit/headless-provision-domain.test.ts index 435f4132f..dd0e2f7f7 100644 --- a/apps/cli/test/unit/headless-provision-domain.test.ts +++ b/apps/cli/test/unit/headless-provision-domain.test.ts @@ -14,7 +14,6 @@ import { describe, it, expect, beforeEach, vi } from "vitest"; const h = vi.hoisted(() => ({ posts: [] as Array<{ path: string; body: Record }>, - bootstrap: vi.fn(async () => ({ ok: true, message: "created" })), })); vi.mock("../../src/lib/loopback-api", () => ({ @@ -23,13 +22,13 @@ vi.mock("../../src/lib/loopback-api", () => ({ return { ok: true, data: { url: "https://ops.example.com" } }; }, waitHealthy: async () => true, - bootstrapAdmin: h.bootstrap, + bootstrapAdmin: async () => ({ ok: true, message: "created" }), // The provision-stream reader goes through this; unreachable here (the stubbed // self-register returns no sessionId), but the module imports it. internalFetch: async () => ({ kind: "unreachable", detail: "not stubbed" }), })); -import { headlessProvision, provisionInstanceDomain } from "../../src/lib/instance-provision"; +import { headlessProvision } from "../../src/lib/instance-provision"; const inputs = { admin: { email: "a@b.com", name: "a", password: "supersecret" }, @@ -40,16 +39,9 @@ const selfRegister = () => h.posts.find((p) => p.path === "/api/system/self-regi beforeEach(() => { h.posts = []; - h.bootstrap.mockClear(); }); describe("headlessProvision — self-app custom domain", () => { - it("can register a managed domain without creating or resetting an existing admin", async () => { - const result = await provisionInstanceDomain({ port: "4000", dashPort: "3001", domain: inputs.domain }); - expect(result.domainRegistered).toBe(true); - expect(h.bootstrap).not.toHaveBeenCalled(); - expect(h.posts.map(post => post.path)).toEqual(["/api/system/self-register"]); - }); it("requests the custom domain on COMPOSE (container edge issues the cert)", async () => { const res = await headlessProvision({ port: "4000", dashPort: "3001", inputs, method: "compose" }); diff --git a/apps/cli/test/unit/public-instance-api.test.ts b/apps/cli/test/unit/public-instance-api.test.ts deleted file mode 100644 index 89ac6d914..000000000 --- a/apps/cli/test/unit/public-instance-api.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { afterEach, expect, it, vi } from "vitest"; -import { SDK_CAPABILITIES } from "@repo/contracts"; -import { discoverPublicInstanceApi } from "../../src/lib/public-instance-api"; -afterEach(() => vi.unstubAllGlobals()); - -it("confines credential-free discovery to the supplied origin and refuses redirects", async () => { - const fetcher = vi.fn(async () => Response.json({ status: "ok", sdk: SDK_CAPABILITIES })); - vi.stubGlobal("fetch", fetcher); - expect(await discoverPublicInstanceApi("https://ship.test/prefix/")).toBe("https://ship.test/prefix/api/proxy"); - expect(fetcher).toHaveBeenCalledWith("https://ship.test/prefix/api/proxy/api/health", expect.objectContaining({ redirect: "error", headers: { Accept: "application/json" } })); -}); -it.each(["https://ship.test/api", "https://ship.test/api/proxy", "https://ship.test/prefix/api/proxy/"])("does not reinterpret an explicit API: %s", async url => { - const fetcher = vi.fn(); vi.stubGlobal("fetch", fetcher); - expect(await discoverPublicInstanceApi(url)).toBeNull(); - expect(fetcher).not.toHaveBeenCalled(); -}); -it.each([{ status: "ok" }, { sdk: SDK_CAPABILITIES }, { status: "ok", sdk: { protocol: -1 } }])("ignores an unrelated health response: %j", async body => { - vi.stubGlobal("fetch", vi.fn(async () => Response.json(body))); - expect(await discoverPublicInstanceApi("https://ship.test")).toBeNull(); -}); diff --git a/apps/cli/test/unit/service-held-ports.test.ts b/apps/cli/test/unit/service-held-ports.test.ts deleted file mode 100644 index 8c90f5dc9..000000000 --- a/apps/cli/test/unit/service-held-ports.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { mkdirSync, rmSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -const state = vi.hoisted(() => { - const home = `${process.env.TMPDIR || "/tmp"}/openship-service-owners-${process.pid}`; - process.env.OPENSHIP_HOME = home; - return { home, pid: 4200, processes: "4200 1\n4201 4200\n4202 4201\n9000 1", probe: vi.fn() }; -}); -vi.mock("@repo/adapters", () => ({ - LocalExecutor: class {}, - probeListeningPortOwners: state.probe, -})); -vi.mock("../../src/lib/this-host", () => ({ - thisHost: () => ({ profile: { serviceManager: "systemd" } }), -})); -const commands = vi.hoisted(() => vi.fn()); -vi.mock("node:child_process", async (original) => ({ - ...(await original()), - spawnSync: commands, -})); -const { serviceHeldPorts } = await import("../../src/lib/service"); -const platform = process.platform; -beforeEach(() => { - Object.defineProperty(process, "platform", { value: "darwin", configurable: true }); - mkdirSync(state.home, { recursive: true }); - writeFileSync(join(state.home, "ports.json"), JSON.stringify({ api: 7100, dashboard: 7200 })); - state.pid = 4200; - state.processes = "4200 1\n4201 4200\n4202 4201\n9000 1"; - state.probe.mockReset().mockResolvedValue({ - checked: true, - ownershipComplete: true, - occupants: [{ pid: 4202 }], - }); - commands.mockReset().mockImplementation((command, args) => { - const stdout = - command === "launchctl" - ? `"PID" = ${state.pid};` - : command === "systemctl" - ? String(state.pid) - : command === "ps" - ? state.processes - : ""; - return { status: 0, stdout, stderr: "" }; - }); -}); -afterEach(() => - Object.defineProperty(process, "platform", { value: platform, configurable: true }), -); -afterAll(() => rmSync(state.home, { recursive: true, force: true })); - -describe("service-held listener ownership", () => { - it("accepts listeners belonging to the service and nested children", async () => { - expect(await serviceHeldPorts()).toEqual([7100, 7200]); - }); - it("rejects a foreign dashboard listener even while the API service runs", async () => { - state.probe.mockImplementation(async (_, port) => ({ - checked: true, - ownershipComplete: true, - occupants: [{ pid: port === 7100 ? 4201 : 9000 }], - })); - expect(await serviceHeldPorts()).toEqual([7100]); - }); - it("rejects mixed owners, hidden owners and incomplete ownership", async () => { - for (const result of [ - { checked: true, ownershipComplete: true, occupants: [{ pid: 4201 }, { pid: 9000 }] }, - { checked: true, ownershipComplete: false, occupants: [{ pid: 4201 }] }, - { checked: true, ownershipComplete: true, occupants: [{ pid: null }] }, - { checked: false, ownershipComplete: false, occupants: [] }, - ]) { - state.probe.mockResolvedValue(result); - expect(await serviceHeldPorts()).toEqual([]); - } - }); - it("does not trust a saved port when its owner is outside the live service tree", async () => { - state.probe.mockResolvedValue({ - checked: true, - ownershipComplete: true, - occupants: [{ pid: 9000 }], - }); - expect(await serviceHeldPorts()).toEqual([]); - }); - it("falls back when the service is stopped or its process tree is unavailable", async () => { - state.pid = 0; - expect(await serviceHeldPorts()).toEqual([]); - expect(state.probe).not.toHaveBeenCalled(); - state.pid = 4200; - state.processes = "9000 1"; - expect(await serviceHeldPorts()).toEqual([]); - expect(state.probe).not.toHaveBeenCalled(); - }); - it("uses the live systemd MainPID for Linux services", async () => { - Object.defineProperty(process, "platform", { value: "linux", configurable: true }); - expect(await serviceHeldPorts()).toEqual([7100, 7200]); - expect( - commands.mock.calls.some( - ([command, args]) => command === "systemctl" && args.includes("--property=MainPID"), - ), - ).toBe(true); - }); - it("does not guess ownership for a scheduled task without a PID", async () => { - Object.defineProperty(process, "platform", { value: "win32", configurable: true }); - expect(await serviceHeldPorts()).toEqual([]); - expect(state.probe).not.toHaveBeenCalled(); - }); - it("ignores malformed stored ports without invoking an ownership probe", async () => { - writeFileSync(join(state.home, "ports.json"), JSON.stringify({ api: "7100", dashboard: -1 })); - expect(await serviceHeldPorts()).toEqual([]); - expect(state.probe).not.toHaveBeenCalled(); - }); -}); diff --git a/apps/cli/test/unit/service-launchd-install.test.ts b/apps/cli/test/unit/service-launchd-install.test.ts deleted file mode 100644 index 5340429cd..000000000 --- a/apps/cli/test/unit/service-launchd-install.test.ts +++ /dev/null @@ -1,160 +0,0 @@ -import { mkdirSync, readFileSync, rmSync } from "node:fs"; -import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -const state = vi.hoisted(() => { - const home = `${process.env.TMPDIR || "/tmp"}/openship-launchd-install-${process.pid}`; - process.env.OPENSHIP_HOME = `${home}/.openship`; - return { home }; -}); -// The agent's plist goes under homedir(); keep it out of the real ~/Library. -vi.mock("node:os", async (original) => ({ - ...(await original()), - homedir: () => state.home, -})); -vi.mock("@repo/adapters", () => ({ - LocalExecutor: class {}, - probeListeningPortOwners: vi.fn(), -})); - -/** - * A small launchd. Like the real one, `bootout` returns before the job is gone: - * the label stays loaded for `unloadPolls` more `launchctl list` calls, and a - * `bootstrap` of a label that is still loaded fails with EIO. `load -w` exits 0 - * even when it prints "Load failed". - */ -const launchd = vi.hoisted(() => ({ - loaded: false, - pid: null as number | null, - stopping: 0, - unloadPolls: 0, - startsProcess: true, - bootstrapFails: false, - bootoutFails: false, - listFails: false, - calls: [] as string[], -})); -const NEW_PID = 4321; - -function start(): void { - launchd.loaded = true; - launchd.pid = launchd.startsProcess ? NEW_PID : null; -} - -const commands = vi.hoisted(() => vi.fn()); -vi.mock("node:child_process", async (original) => ({ - ...(await original()), - spawnSync: commands, -})); -const { installAndStart, preview } = await import("../../src/lib/service"); - -const platform = process.platform; -beforeEach(() => { - Object.defineProperty(process, "platform", { value: "darwin", configurable: true }); - vi.spyOn(Atomics, "wait").mockReturnValue("timed-out"); - mkdirSync(state.home, { recursive: true }); - Object.assign(launchd, { - loaded: false, - pid: null, - stopping: 0, - unloadPolls: 0, - startsProcess: true, - bootstrapFails: false, - bootoutFails: false, - listFails: false, - calls: [], - }); - commands.mockReset().mockImplementation((command: string, args: string[]) => { - if (command !== "launchctl") return { status: 0, stdout: "", stderr: "" }; - const sub = args[0]; - launchd.calls.push(sub); - if (sub === "bootout") { - if (!launchd.loaded) return { status: 3, stdout: "", stderr: "No such process" }; - if (launchd.bootoutFails) { - return { status: 5, stdout: "", stderr: "Boot-out failed: 5: Input/output error" }; - } - launchd.pid = null; - launchd.stopping = launchd.unloadPolls; - if (launchd.stopping === 0) launchd.loaded = false; - return { status: 0, stdout: "", stderr: "" }; - } - if (sub === "list") { - if (launchd.listFails) return { status: 5, stdout: "", stderr: "Input/output error" }; - if (!launchd.loaded) { - return { status: 113, stdout: "", stderr: `Could not find service "${args[1]}"` }; - } - if (launchd.stopping > 0 && --launchd.stopping === 0) launchd.loaded = false; - const stdout = launchd.pid != null ? `"PID" = ${launchd.pid};` : `"LastExitStatus" = 256;`; - return { status: 0, stdout, stderr: "" }; - } - if (sub === "bootstrap") { - if (launchd.loaded || launchd.bootstrapFails) { - return { status: 5, stdout: "", stderr: "Bootstrap failed: 5: Input/output error" }; - } - start(); - return { status: 0, stdout: "", stderr: "" }; - } - if (sub === "load") { - if (launchd.loaded || launchd.bootstrapFails) { - return { status: 0, stdout: "", stderr: "Load failed: 5: Input/output error" }; - } - start(); - return { status: 0, stdout: "", stderr: "" }; - } - return { status: 0, stdout: "", stderr: "" }; - }); -}); -afterEach(() => { - Object.defineProperty(process, "platform", { value: platform, configurable: true }); - vi.restoreAllMocks(); -}); -afterAll(() => rmSync(state.home, { recursive: true, force: true })); - -describe("installAndStart on launchd", () => { - it("installs and starts an agent that isn't loaded yet", () => { - expect(installAndStart({ port: "7100" }).kind).toBe("launchd"); - expect(launchd.pid).toBe(NEW_PID); - }); - - it("waits for the running agent to unload before bootstrapping it again", () => { - // A re-run of `openship up` while the service is running. - Object.assign(launchd, { loaded: true, pid: 1111, unloadPolls: 3 }); - - expect(installAndStart({ port: "7100" }).kind).toBe("launchd"); - - expect(launchd.pid).toBe(NEW_PID); - expect(launchd.calls).not.toContain("load"); - }); - - it.each([ - { setup: { bootoutFails: true }, error: /still loaded after 10s.*Boot-out failed/ }, - { setup: { unloadPolls: 100 }, error: /still loaded after 10s/ }, - { setup: { listFails: true }, error: /Couldn't check launchd agent.*Input\/output error/ }, - ])( - "preserves the existing plist when unloading cannot be confirmed: $setup", - ({ setup, error }) => { - const flags = { port: "7100" }; - installAndStart(flags); - const { path } = preview(flags); - const installed = readFileSync(path, "utf8"); - launchd.calls.length = 0; - Object.assign(launchd, setup); - - expect(() => installAndStart({ port: "7300" })).toThrow(error); - expect(readFileSync(path, "utf8")).toBe(installed); - expect(launchd.calls).not.toContain("bootstrap"); - expect(launchd.calls).not.toContain("load"); - }, - ); - - it("fails instead of reporting success when the agent doesn't stay up", () => { - launchd.startsProcess = false; - - expect(() => installAndStart({ port: "7100" })).toThrow(/didn't start \(last exit 256\)/); - }, 10_000); - - it("fails when `launchctl load` prints Load failed and still exits 0", () => { - launchd.bootstrapFails = true; - - expect(() => installAndStart({ port: "7100" })).toThrow(/didn't start.*Load failed/); - }, 10_000); -}); diff --git a/apps/cli/test/unit/up-foreground-early-stop.test.ts b/apps/cli/test/unit/up-foreground-early-stop.test.ts deleted file mode 100644 index 76cf5f652..000000000 --- a/apps/cli/test/unit/up-foreground-early-stop.test.ts +++ /dev/null @@ -1,112 +0,0 @@ -import { rmSync } from "node:fs"; -import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -/** - * `openship up --foreground` (what the service runs) stopped while the API is - * still starting. The API runs in its own process group, so launchd stopping - * the supervisor never reaches it. The supervisor has to take it down itself, - * or the API keeps the port and the PGlite lock and the next start fails. - */ - -// lib/paths reads OPENSHIP_HOME at import time, so set it before anything loads. -const HOME = vi.hoisted(() => { - const dir = `${process.env.TMPDIR?.replace(/\/$/, "") || "/tmp"}/openship-up-early-stop-${process.pid}`; - process.env.OPENSHIP_HOME = dir; - return dir; -}); - -const api = vi.hoisted(() => ({ pid: undefined as number | undefined })); - -// The API is a real detached process that never becomes healthy, so the -// supervisor is still in its startup wait when the signal arrives. -vi.mock("node:child_process", async (importOriginal) => { - const real = await importOriginal(); - return { - ...real, - spawn: ( - _command: string, - _args: string[], - options: import("node:child_process").SpawnOptions, - ) => { - const child = real.spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], options); - api.pid = child.pid; - return child; - }, - }; -}); -// No staged server bundle under src/; pretend it's there. -vi.mock("node:fs", async (importOriginal) => { - const real = await importOriginal(); - return { - ...real, - existsSync: (path: string) => - String(path).endsWith("/server/index.js") || real.existsSync(path), - }; -}); -// A TTY spinner would add its own signal listeners; keep the test to ours. -vi.mock("ora", () => ({ - default: () => { - const spinner = { - text: "", - start: () => spinner, - succeed: () => spinner, - fail: () => spinner, - warn: () => spinner, - }; - return spinner; - }, -})); - -const { upCommand } = await import("../../src/commands/up"); -const { getFreePort } = await import("../../src/lib/ports"); - -function alive(pid: number): boolean { - try { - process.kill(pid, 0); - return true; - } catch { - return false; - } -} - -const SIGNALS = ["SIGINT", "SIGTERM"] as const; -let before: Record; -let exit: ReturnType; - -beforeEach(() => { - api.pid = undefined; - before = Object.fromEntries(SIGNALS.map((s) => [s, process.listeners(s)])); - exit = vi.spyOn(process, "exit").mockImplementation((() => undefined) as never); -}); - -afterEach(() => { - if (api.pid && alive(api.pid)) process.kill(-api.pid, "SIGKILL"); - for (const s of SIGNALS) { - for (const l of process.listeners(s)) { - if (!before[s].includes(l)) process.removeListener(s, l as () => void); - } - } - exit.mockRestore(); -}); - -afterAll(() => rmSync(HOME, { recursive: true, force: true })); - -describe("openship up --foreground stopped during startup", () => { - it("takes the starting API down with it and exits cleanly", async () => { - const [port, dashboardPort] = [String(await getFreePort()), String(await getFreePort())]; - const args = ["--foreground", "--no-ui", "--port", port, "--dashboard-port", dashboardPort]; - const run = upCommand.parseAsync(args, { from: "user" }); - - await vi.waitFor(() => expect(api.pid).toBeDefined(), { timeout: 5000 }); - const pid = api.pid!; - expect(alive(pid)).toBe(true); - - // What launchd does on `openship stop`, or a re-run replacing the service. - process.emit("SIGTERM", "SIGTERM"); - - await vi.waitFor(() => expect(alive(pid)).toBe(false), { timeout: 3000 }); - await vi.waitFor(() => expect(exit).toHaveBeenCalledWith(0), { timeout: 3000 }); - expect(exit).not.toHaveBeenCalledWith(1); - await run; - }, 15_000); -}); diff --git a/apps/cli/test/unit/up-rerun-ports.test.ts b/apps/cli/test/unit/up-rerun-ports.test.ts deleted file mode 100644 index 51dad16e0..000000000 --- a/apps/cli/test/unit/up-rerun-ports.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { createServer, type Server } from "node:net"; -import { join } from "node:path"; -import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -/** - * Re-running `openship up` while its own service is running (#1570). - * - * The running service holds the ports in ports.json, so they probe busy. They are - * still ours: installAndStart replaces that instance before the new one binds. - * Treating them as taken moved the install to new ports on every re-run - * (7100 -> 7101), rewrote ports.json, and first sat out waitPortFree on each port. - */ - -// lib/paths reads OPENSHIP_HOME at import time, so set it before anything loads. -const HOME = vi.hoisted(() => { - const dir = `${process.env.TMPDIR?.replace(/\/$/, "") || "/tmp"}/openship-up-rerun-${process.pid}`; - process.env.OPENSHIP_HOME = dir; - return dir; -}); - -const svc = vi.hoisted(() => ({ - running: false, - heldPorts: [] as number[], - installed: [] as Array<{ port: string; dashboardPort: string }>, -})); - -// Only the service manager is faked. The port resolver and ports.json stay real. -vi.mock("../../src/lib/service", async (importOriginal) => ({ - ...(await importOriginal()), - serviceHeldPorts: async () => (svc.running ? svc.heldPorts : []), - installAndStart: (flags: { port: string; dashboardPort: string }) => { - svc.installed.push(flags); - return { kind: "launchd", detail: "test" }; - }, -})); - -const { startService } = await import("../../src/commands/up"); -const { planUp } = await import("../../src/lib/up-plan"); -const { getFreePort, isPortFree } = await import("../../src/lib/ports"); - -const PORTS_FILE = join(HOME, "ports.json"); -const held: Server[] = []; - -/** Bind a port the way a running process would. */ -function hold(port: number): Promise { - return new Promise((resolve, reject) => { - const srv = createServer(); - srv.once("error", reject); - srv.listen(port, "127.0.0.1", () => { - held.push(srv); - resolve(); - }); - }); -} - -/** A free port whose neighbour is free too, so a move to it would be visible. */ -async function freeWithNeighbour(from?: number): Promise { - for (let i = 0; i < 50; i++) { - const port = from === undefined ? await getFreePort() : from + i * 3; - if ((await isPortFree(port)) && (await isPortFree(port + 1))) return port; - } - throw new Error("no free port with a free neighbour"); -} - -/** API and dashboard ports far enough apart that neither move lands on the other. */ -async function freePorts(): Promise<{ api: number; dashboard: number }> { - const api = await freeWithNeighbour(); - return { api, dashboard: await freeWithNeighbour(api + 10) }; -} - -beforeEach(() => { - mkdirSync(HOME, { recursive: true }); - rmSync(PORTS_FILE, { force: true }); - svc.running = false; - svc.heldPorts = []; - svc.installed = []; -}); - -afterEach(async () => { - await Promise.all(held.splice(0).map((s) => new Promise((r) => s.close(r)))); -}); - -afterAll(() => { - rmSync(HOME, { recursive: true, force: true }); -}); - -describe("startService on a re-run", () => { - it("keeps the ports its own running service holds", async () => { - const { api, dashboard } = await freePorts(); - writeFileSync(PORTS_FILE, JSON.stringify({ api, dashboard })); - await hold(api); - await hold(dashboard); - svc.running = true; - svc.heldPorts = [api, dashboard]; - - const r = await startService({}, { quiet: true }); - - expect({ api: r.port, dashboard: r.dashPort }).toEqual({ - api: String(api), - dashboard: String(dashboard), - }); - expect(svc.installed[0]).toMatchObject({ port: String(api), dashboardPort: String(dashboard) }); - expect(JSON.parse(readFileSync(PORTS_FILE, "utf8"))).toEqual({ api, dashboard }); - }, 30_000); - - it("still moves off a remembered port another program holds when the service is not running", async () => { - const { api, dashboard } = await freePorts(); - writeFileSync(PORTS_FILE, JSON.stringify({ api, dashboard })); - await hold(api); - - const r = await startService({}, { quiet: true }); - - expect(r.port).not.toBe(String(api)); - expect(r.dashPort).toBe(String(dashboard)); - }, 30_000); - - it("moves off an unrelated dashboard listener when the running service owns only the API", async () => { - const { api, dashboard } = await freePorts(); - writeFileSync(PORTS_FILE, JSON.stringify({ api, dashboard })); - await hold(api); - await hold(dashboard); - svc.running = true; - svc.heldPorts = [api]; - const r = await startService({}, { quiet: true }); - expect(r.port).toBe(String(api)); - expect(r.dashPort).not.toBe(String(dashboard)); - }, 30_000); - - it("uses the same owned ports for a dry-run and an actual service rerun", async () => { - const { api, dashboard } = await freePorts(); - writeFileSync(PORTS_FILE, JSON.stringify({ api, dashboard })); - await hold(api); - await hold(dashboard); - svc.running = true; - svc.heldPorts = [api, dashboard]; - const plan = await planUp({ bare: true }); - const r = await startService({}, { quiet: true }); - expect(plan.ports.api).toBe(Number(r.port)); - expect(plan.ports.dashboard).toBe(Number(r.dashPort)); - }, 30_000); - - it("does not reclaim service ports for an attached foreground preview", async () => { - const { api, dashboard } = await freePorts(); - writeFileSync(PORTS_FILE, JSON.stringify({ api, dashboard })); - await hold(api); - svc.running = true; - svc.heldPorts = [api]; - const plan = await planUp({ bare: true, foreground: true }); - expect(plan.ports.api).not.toBe(api); - expect(plan.ports.dashboard).toBe(dashboard); - }, 30_000); -}); diff --git a/apps/dashboard/Dockerfile b/apps/dashboard/Dockerfile index b4c86fca9..be63080bc 100644 --- a/apps/dashboard/Dockerfile +++ b/apps/dashboard/Dockerfile @@ -4,12 +4,11 @@ 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/dashboard/package.json b/apps/dashboard/package.json index d0059cfda..47f044dc6 100644 --- a/apps/dashboard/package.json +++ b/apps/dashboard/package.json @@ -18,14 +18,12 @@ "dependencies": { "@better-auth/oauth-provider": "1.7.15", "@better-auth/passkey": "1.7.15", - "@mindwire-ai/client": "file:../../vendor/mindwire-client-0.1.0-beta.3-83f1a8478412.tgz", "@noble/hashes": "^2.0.1", "@radix-ui/react-slot": "^1.2.4", "@repo/contracts": "workspace:*", "@repo/core": "workspace:*", "@repo/onboarding": "workspace:*", "@repo/ui": "workspace:*", - "@sinclair/typebox": "^0.34.48", "@streamdown/code": "2.0.0", "@xterm/addon-fit": "^0.11.0", "@xterm/addon-search": "^0.16.0", diff --git a/apps/dashboard/src/app/(auth)/register/signup-next.test.ts b/apps/dashboard/src/app/(auth)/register/signup-next.test.ts index 2c7ece3a7..e5e61f44d 100644 --- a/apps/dashboard/src/app/(auth)/register/signup-next.test.ts +++ b/apps/dashboard/src/app/(auth)/register/signup-next.test.ts @@ -15,7 +15,7 @@ describe("signUpNext", () => { it("goes to verification when sign-up succeeds WITHOUT a session", () => { // The exact better-auth shape for requireEmailVerification. const next = signUpNext({ data: { token: null } }, opts); - expect(next).toEqual({ kind: "verify", href: "/verify-email?email=a%40b.co&signup=1" }); + expect(next).toEqual({ kind: "verify", href: "/verify-email?email=a%40b.co" }); }); it("treats a missing token field the same as an explicit null", () => { @@ -54,16 +54,3 @@ describe("signUpNext", () => { expect(next.kind === "verify" && next.href).toContain("a%2Btag%40b.co"); }); }); - -it("preserves the Cloud consent and PKCE continuation through signup verification", () => { - const returnTo = "/cloud-authorize?mode=device&state=test-state&code_challenge=test-challenge"; - const next = signUpNext( - { data: { token: null } }, - { email: "existing@example.test", authParams: new URLSearchParams({ returnTo }) }, - ); - expect(next.kind).toBe("verify"); - if (next.kind !== "verify") throw new Error("Expected email continuation"); - const params = new URL(next.href, "https://app.example.test").searchParams; - expect(params.get("signup")).toBe("1"); - expect(params.get("returnTo")).toBe(returnTo); -}); diff --git a/apps/dashboard/src/app/(auth)/register/signup-next.ts b/apps/dashboard/src/app/(auth)/register/signup-next.ts index f7ee49d02..1d77fe8d2 100644 --- a/apps/dashboard/src/app/(auth)/register/signup-next.ts +++ b/apps/dashboard/src/app/(auth)/register/signup-next.ts @@ -23,7 +23,7 @@ export type SignUpResultShape = { export type SignUpNext = /** Show the message; stay on the form. */ | { kind: "error"; message: string | null } - /** No session: privately continue by verification code or sign-in instructions. */ + /** Account exists, no session yet — the code screen, reachable unauthenticated. */ | { kind: "verify"; href: string } /** A real session was issued; follow the post-login destination. */ | { kind: "session"; href: string }; @@ -36,9 +36,7 @@ export function signUpNext( authParams?: Parameters[1]; }, ): SignUpNext { - // The same response also protects an existing address from enumeration. Do - // not promise account creation or a code when the email contains sign-in help. - const verifyHref = `${emailVerificationHref(opts.email, opts.authParams ?? new URLSearchParams())}&signup=1`; + const verifyHref = emailVerificationHref(opts.email, opts.authParams ?? new URLSearchParams()); if (result.error) { // Some deployments surface the requirement as an error instead of a null diff --git a/apps/dashboard/src/app/(auth)/verify-email/page.tsx b/apps/dashboard/src/app/(auth)/verify-email/page.tsx index fd3996605..78944d7c5 100644 --- a/apps/dashboard/src/app/(auth)/verify-email/page.tsx +++ b/apps/dashboard/src/app/(auth)/verify-email/page.tsx @@ -33,11 +33,9 @@ function VerifyEmailContent() { const searchParams = useSearchParams(); const token = searchParams.get("token"); const emailParam = searchParams.get("email") ?? ""; - const fromSignup = searchParams.get("signup") === "1"; const { toast } = useToast(); const { t } = useI18n(); const loginHref = buildAuthPageHref("/login", searchParams); - const resetHref = buildAuthPageHref("/forgot-password", searchParams); const [status, setStatus] = useState<"pending" | "verifying" | "verified" | "error">( token ? "verifying" : "pending", @@ -223,14 +221,11 @@ function VerifyEmailContent() {

- {fromSignup ? t.auth.verifyEmail.signupTitle : t.auth.verifyEmail.pendingTitle} + {t.auth.verifyEmail.pendingTitle}

{emailParam - ? interpolate( - fromSignup ? t.auth.verifyEmail.signupSentTo : t.auth.verifyEmail.pendingSentTo, - { email: emailParam }, - ) + ? interpolate(t.auth.verifyEmail.pendingSentTo, { email: emailParam }) : t.auth.verifyEmail.pendingGeneric}

@@ -269,17 +264,10 @@ function VerifyEmailContent() {

- {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 && ( - )} + } /> - {!opensApplication && ( - setEnvOpen(false)} /> - )} + setEnvOpen(false)} /> ); } diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/Deployments.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/Deployments.test.tsx index 4412a4521..b6c93dedd 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/Deployments.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/Deployments.test.tsx @@ -250,7 +250,7 @@ it("makes a detected image update actionable through the shared update operation expect(container.textContent).toContain("redis (redis:7)"); expect(container.textContent).not.toContain("db (postgres:16)"); await act(async () => button(baseDictionary.projectSettings.appSource.update).click()); - expect(mocks.applyUpdate).toHaveBeenCalledExactlyOnceWith("project", undefined); + expect(mocks.applyUpdate).toHaveBeenCalledExactlyOnceWith("project"); expect(mocks.trigger).not.toHaveBeenCalled(); expect(mocks.openBuild).toHaveBeenCalledWith( expect.anything(), { data: { deployment: { id: "image-update" } } }, "project", @@ -302,29 +302,12 @@ it.each(["cancel", "configure"] as const)("reviews new Compose services before r await redeploy(); expect(mocks.openBuild).not.toHaveBeenCalled(); const modal = mocks.showModal.mock.calls.at(-1)![0]; - await act(async () => root.render(<>{modal.customContent})); + await act(async () => root.render(modal.customContent)); const copy = baseDictionary.projects.redeploy.composeReview; - expect(container.textContent).toContain(copy.title); + expect(container.textContent).toContain(copy.addedTitle); expect(container.textContent).toContain("old-worker"); await act(async () => button(copy[action]).click()); expect(mocks.trigger).toHaveBeenCalledTimes(1); if (action === "cancel") expect(mocks.push).not.toHaveBeenCalled(); else expect(mocks.push).toHaveBeenCalledWith(expect.stringMatching(/^\/deploy\/.+\?reviewCompose=1$/)); }); - -it("applies the reviewed Compose revision through the original smart redeploy", async () => { - context.hasMultipleServices = false; - mocks.trigger.mockRejectedValueOnce({ body: { - code: "COMPOSE_REVIEW_REQUIRED", projectId: "project", composeRevision: "a".repeat(64), - composeChanges: { added: [], changed: ["worker"], removed: [] }, - composeDiff: [{ name: "worker", kind: "changed", fields: [{ path: "image", before: "worker:1", after: "worker:2" }] }], - } }); - await redeploy(); - const modal = mocks.showModal.mock.calls.at(-1)![0]; - await act(async () => root.render(<>{modal.customContent})); - await act(async () => button(baseDictionary.projects.redeploy.composeReview.apply).click()); - expect(mocks.trigger).toHaveBeenLastCalledWith({ projectId: "project", smartRoute: true, composeRevision: "a".repeat(64) }); - expect(mocks.trigger).toHaveBeenCalledTimes(2); - expect(mocks.openBuild).toHaveBeenCalledOnce(); - expect(mocks.push).not.toHaveBeenCalled(); -}); diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/Deployments.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/Deployments.tsx index 1a45ca8b2..e0d0a86cb 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/Deployments.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/Deployments.tsx @@ -91,16 +91,16 @@ export const Deployments = () => { }, [projectData?.id, isBlocked, projectData?.latestDeploymentId]); // Redeploy saved settings against the latest source. Source changes stop at - // the shared review gate, then retry this same operation after explicit review. + // the shared review gate and open the existing configuration wizard. const runRedeploy = React.useCallback( - async function runRedeploy(mode: "smart" | "all" | "refresh" | "update" = "smart", composeRevision?: string): Promise { + async (mode: "smart" | "all" | "refresh" | "update" = "smart") => { if (!projectData?.id) return; setIsRedeploying(true); // drive the loading state for menu paths too try { if (mode === "update") { // Image updates must force-pull the tag through the existing update // operation; a normal rebuild can reuse the currently running image. - const res = await updatesApi.apply(projectData.id, composeRevision ? { composeRevision } : undefined); + const res = await updatesApi.apply(projectData.id); openTriggeredBuild( router, { data: { deployment: { id: res.data?.deployment_id } } }, @@ -114,11 +114,10 @@ export const Deployments = () => { : mode === "refresh" ? { projectId: projectData.id, refresh: true } : { projectId: projectData.id, smartRoute: true }; - const res = await deployApi.trigger({ ...body, ...(composeRevision && { composeRevision }) }); + const res = await deployApi.trigger(body); openTriggeredBuild(router, res, projectData.id); } catch (error) { - if (composeRevision && !isAbortError(error)) { setIsRedeploying(false); throw error; } - if (showComposeReview(error, (revision) => runRedeploy(mode, revision))) { + if (showComposeReview(error)) { setIsRedeploying(false); return; } diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSection.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSection.test.tsx deleted file mode 100644 index f421d3863..000000000 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSection.test.tsx +++ /dev/null @@ -1,99 +0,0 @@ -// @vitest-environment happy-dom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import { DomainSection } from "./DomainSection"; - -const state = vi.hoisted(() => ({ - query: "hostname=second.test", - replace: vi.fn(), - listRouteProtection: vi.fn(), - changeRouteProtection: vi.fn(), -})); -vi.mock("next/navigation", () => ({ - useRouter: () => ({ replace: state.replace }), - useSearchParams: () => new URLSearchParams(state.query), -})); -vi.mock("@/context/ProjectSettingsContext", () => ({ - useProjectSettings: () => ({ - projectData: { - id: "proj", - deployTarget: "server", - domains: [{ domain: "first.test" }, { hostname: "second.test" }], - }, - setProjectData: vi.fn(), - }), -})); -vi.mock("@/lib/api", () => ({ - projectsApi: state, - getApiErrorMessage: (_: unknown, fallback: string) => fallback, -})); -vi.mock("./RoutingConfigCard", () => ({ RoutingConfigCard: () => null })); -vi.mock("./RouteRules", () => ({ RouteRules: () => null })); -vi.mock("@/components/routing/EdgePagesPanel", () => ({ EdgePagesPanel: () => null })); - -let container: HTMLDivElement; -let root: Root; -beforeEach(() => { - vi.clearAllMocks(); - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - state.query = "hostname=second.test"; - state.listRouteProtection.mockResolvedValue({ - data: [{ hostname: "second.test", enabled: true, status: "applied" }], - }); - container = document.createElement("div"); - document.body.append(container); - root = createRoot(container); -}); -afterEach(async () => { - await act(async () => root.unmount()); - container.remove(); - vi.unstubAllGlobals(); -}); - -it("opens the linked hostname inline and keeps hostname selection in the URL", async () => { - await act(async () => root.render()); - expect(container.querySelector('[role="status"]')?.textContent).toContain( - "Password protection is active", - ); - expect(container.querySelector('[role="dialog"]')).toBeNull(); - const selector = container.querySelector( - 'button[aria-label="Choose a hostname first"]', - )!; - expect(selector.textContent).toContain("second.test"); - await act(async () => selector.click()); - const option = [...document.querySelectorAll('[role="option"]')].find((item) => - item.textContent?.includes("first.test"), - )!; - expect(option).toBeTruthy(); - await act(async () => option.click()); - expect(state.replace).toHaveBeenCalledWith("/projects/proj/access?hostname=first.test", { - scroll: false, - }); -}); - -it("clears a hostname's unfinished password when navigation selects another hostname", async () => { - await act(async () => root.render()); - const password = container.querySelector('input[type="password"]')!; - await act(async () => { - Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call( - password, - "not-for-another-host", - ); - password.dispatchEvent(new Event("input", { bubbles: true })); - }); - state.query = "hostname=first.test"; - await act(async () => root.render()); - expect(container.querySelector('input[type="password"]')!.value).toBe(""); - expect(container.querySelector('[role="status"]')?.textContent).toContain("This route is public"); - expect(state.changeRouteProtection).not.toHaveBeenCalled(); -}); - -it("ignores unknown hostnames in the query and selects an owned domain", async () => { - state.query = "hostname=unowned.test"; - await act(async () => root.render()); - expect( - container.querySelector('button[aria-label="Choose a hostname first"]')?.textContent, - ).toContain("first.test"); - expect(container.textContent).not.toContain("unowned.test"); -}); diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSection.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSection.tsx deleted file mode 100644 index d56a6d2e2..000000000 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSection.tsx +++ /dev/null @@ -1,109 +0,0 @@ -"use client"; - -import { useProjectSettings } from "@/context/ProjectSettingsContext"; -import { useI18n } from "@/components/i18n-provider"; -import { RoutingConfigCard } from "./RoutingConfigCard"; -import { - RouteProtectionPanel, - routeProtectionHref, -} from "@/components/routing/RouteProtectionButton"; -import { CustomSelect } from "@/components/ui/CustomSelect"; -import { useRouter, useSearchParams } from "next/navigation"; -import { EdgePagesPanel } from "@/components/routing/EdgePagesPanel"; -import { RouteRules } from "./RouteRules"; - -export function DomainSection({ - section, -}: { - section: "routing" | "proxy" | "access" | "edge-pages"; -}) { - const { projectData, setProjectData } = useProjectSettings(); - const id = String(projectData.id); - const cloud = projectData.deployTarget === "cloud" || !!projectData.workspaceId; - const domains = (projectData.domains ?? []) - .map((domain) => ({ - hostname: domain.hostname ?? domain.domain, - external: domain.externalIngress || domain.domainType === "free", - })) - .filter((domain): domain is { hostname: string; external: boolean } => !!domain.hostname); - if (section === "routing" || section === "proxy") - return ( - setProjectData((current) => ({ ...current, routingConfig }))} - /> - ); - if (cloud || projectData.deployTarget === "cluster" || projectData.clusterId) return null; - if (section === "edge-pages") - return ( - domain.hostname)} - onSaved={(edgePages) => - setProjectData((current) => ({ - ...current, - routingConfig: { ...current.routingConfig, edgePages }, - })) - } - /> - ); - return ( -
- - -
- ); -} - -function AccessSettings({ - projectId, - domains, -}: { - projectId: string; - domains: { hostname: string; external?: boolean }[]; -}) { - const { t } = useI18n(); - const router = useRouter(); - const requested = useSearchParams().get("hostname"); - const selected = domains.find((domain) => domain.hostname === requested) ?? domains[0]; - return ( -
-
-
-

{t.widgets.routing.protection.title}

-

{t.widgets.routing.pages.accessHint}

-
- {selected && ( - ({ - value: domain.hostname, - label: domain.hostname, - }))} - onChange={(hostname) => - router.replace(routeProtectionHref(projectId, hostname), { scroll: false }) - } - className="w-full sm:w-72" - variant="filled" - triggerClassName="bg-muted/60 hover:bg-muted" - /> - )} -
- {selected ? ( - - ) : ( -

- {t.widgets.routing.protection.chooseHostname} -

- )} -
- ); -} diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSettings.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSettings.tsx index f120c9b53..43691ed49 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSettings.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/DomainSettings.tsx @@ -9,7 +9,8 @@ import { getPortCheckIssue } from "@repo/core"; import React, { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useRouter } from "next/navigation"; import { useProjectSettings } from "@/context/ProjectSettingsContext"; -import { DomainResponseRoutes } from "@/components/routing/DomainResponseRoutes"; +import { RoutingConfigCard } from "./RoutingConfigCard"; +import { RouteRules } from "./RouteRules"; import { RoutingUnsyncedCallout } from "./RoutingUnsyncedCallout"; import { localizeDiagnosisMessage } from "@/lib/i18n/localize-issues"; import { invalidateProjectCaches } from "@/hooks/useProjectEndpoints"; @@ -25,6 +26,7 @@ import PublicEndpointsCard from "@/components/routing/PublicEndpointsCard"; import DnsRecordCard from "@/components/domains/DnsRecordCard"; import DnsChallengePanel from "@/components/domains/DnsChallengePanel"; import { AutoDnsPanel } from "@/components/shared/AutoDnsPanel"; +import { RoutingSettingsCard } from "@/components/routing/RoutingSettingsCard"; import { PrepareStreamContent, useEdgeModal, @@ -49,7 +51,6 @@ import { } from "@/lib/public-endpoint-payload"; import { buildOptimisticDomainRow, findLoadedDomainRow } from "./optimistic-domain-row"; import { configuredServiceEndpoints, serviceEndpointsPatch, servicePortTargets, type ServiceEndpoint } from "@/lib/service-endpoints"; -import { getWwwDomainRouting } from "@/lib/www-domain-routing"; interface DnsRecord { type: "CNAME" | "A" | "TXT"; @@ -606,11 +607,14 @@ export const DomainSettings = ({ applicationScope = false, serviceScope, onRoute const [routeSavingServiceId, setRouteSavingServiceId] = useState(null); // Local draft for the "Edit route" modal — the card edits this in memory; the // API is hit ONCE on Save (not on every toggle/keystroke). - const [routeDraft, setRouteDraft] = useState(null); - const originalRouteDraft = useRef<{ configured: PublicEndpoint[]; editable: PublicEndpoint[] }>({ - configured: [], - editable: [], - }); + const [routeDraft, setRouteDraft] = useState<{ + domainType: "free" | "custom"; + domain: string; + customDomain: string; + exposedPort: string; + redirectTo: string; + redirectStatus: number; + } | null>(null); // "Add route" form: bind a domain and container port to the selected service. const [showAddRoute, setShowAddRoute] = useState(serviceScope?.add ?? false); const [portFilter, setPortFilter] = useState(serviceScope?.port); @@ -931,32 +935,20 @@ export const DomainSettings = ({ applicationScope = false, serviceScope, onRoute // must not clobber an in-progress draft. useEffect(() => { const svc = services.find((s) => s.id === editingRouteServiceId); - const endpoints = svc ? configuredServiceEndpoints(svc).map(toEditablePublicEndpoint) : []; - const endpoint = endpoints.find((route) => + const endpoint = svc && configuredServiceEndpoints(svc).find((route) => resolvePublicEndpointHostname(route, baseDomain) === editingRouteTarget?.hostname.toLowerCase()); if (!endpoint) { setRouteDraft(null); return; } - // Edit the selected hostname and its own www pair together. Other ports and - // domains stay outside the draft and are merged from a fresh service read. - const pair = endpoint.domainType === "custom" ? getWwwDomainRouting(endpoints, endpoint.customDomain) : null; - const selected = new Set([endpoint.id, pair?.bare?.id, pair?.www?.id]); - const configured = endpoints.filter((route) => selected.has(route.id)); - const draft = configured.map((route) => { - const row = findLoadedDomainRow(domainsData.domains, resolvePublicEndpointHostname(route, baseDomain)); - const domain = !row?.serviceId || row.serviceId === svc?.id ? row : undefined; - return { - ...route, - // Older API-created redirects can live only on the domain row. Keep - // their effective behavior in the editor while comparing fresh service - // reads against the original service configuration below. - redirectTo: route.redirectTo ?? (typeof domain?.redirectTo === "string" ? domain.redirectTo : ""), - redirectStatus: route.redirectStatus ?? (typeof domain?.redirectStatus === "number" ? domain.redirectStatus : 301), - }; + setRouteDraft({ + domainType: endpoint.domainType, + domain: endpoint.domain ?? "", + customDomain: endpoint.customDomain ?? "", + exposedPort: endpoint.port === undefined ? "" : String(endpoint.port), + redirectTo: endpoint.redirectTo ?? editingRouteTarget?.redirectTo ?? "", + redirectStatus: endpoint.redirectStatus ?? editingRouteTarget?.redirectStatus ?? 301, }); - originalRouteDraft.current = { configured, editable: draft }; - setRouteDraft(draft); // eslint-disable-next-line react-hooks/exhaustive-deps }, [editingRouteTarget]); @@ -1432,7 +1424,6 @@ export const DomainSettings = ({ applicationScope = false, serviceScope, onRoute }; const handleCancelEditingDomains = () => { - if (isSavingPublicEndpoints) return; setPublicEndpoints(draftPublicEndpoints); setIsEditingDomains(false); }; @@ -1556,7 +1547,6 @@ export const DomainSettings = ({ applicationScope = false, serviceScope, onRoute }; const handleSavePublicEndpoints = async () => { - if (isSavingPublicEndpoints) return; // Free . domains route through the Openship Cloud edge — block // the save (opening the connect-cloud modal) when one is present without a // cloud connection, so an edit can't persist a domain that can't route. @@ -1590,7 +1580,7 @@ export const DomainSettings = ({ applicationScope = false, serviceScope, onRoute // Per-service domains have no endpoint order to reorder — primary is the // domain row's isPrimary flag. Flip it via the API, then reflect locally // (exactly one primary per project). getPrimaryByProject picks this up for - // the project's canonical URL / analytics, and it survives + // the project's canonical URL / favicon / analytics, and it survives // redeploys (service route registration preserves an existing isPrimary). const handleSetPrimaryServiceDomain = async (summary: DomainSummaryItem) => { if (!summary.domainId || summary.isPrimary) return; @@ -2018,11 +2008,6 @@ export const DomainSettings = ({ applicationScope = false, serviceScope, onRoute - ) : undefined} protectionControl={} menuActions={menuActions} @@ -2074,18 +2059,28 @@ export const DomainSettings = ({ applicationScope = false, serviceScope, onRoute const editingRouteService = services.find((service) => service.id === editingRouteServiceId) ?? null; + const editingEndpoint = editingRouteService && configuredServiceEndpoints(editingRouteService).find((endpoint) => + resolvePublicEndpointHostname(endpoint, baseDomain) === editingRouteTarget?.hostname.toLowerCase()); const routeDirty = Boolean( - routeDraft && JSON.stringify(routeDraft.map((route) => validatedPublicEndpointPayload(route, true))) !== - JSON.stringify(originalRouteDraft.current.editable.map((route) => validatedPublicEndpointPayload(route, true))), + editingEndpoint && + routeDraft && + (routeDraft.domainType !== editingEndpoint.domainType || + routeDraft.domain !== (editingEndpoint.domain ?? "") || + routeDraft.customDomain !== (editingEndpoint.customDomain ?? "") || + routeDraft.exposedPort !== (editingEndpoint.port === undefined ? "" : String(editingEndpoint.port)) || + routeDraft.redirectTo !== (editingEndpoint.redirectTo ?? editingRouteTarget?.redirectTo ?? "") || + routeDraft.redirectStatus !== (editingEndpoint.redirectStatus ?? editingRouteTarget?.redirectStatus ?? 301)), ); const routeSaving = editingRouteService ? routeSavingServiceId === editingRouteService.id : false; const handleSaveRoute = async () => { if (!editingRouteService || !editingRouteTarget || !routeDraft || routeSaving) return; // A free route rides the cloud edge — gate the save behind connect-cloud. - if (routeDraft.some((route) => route.domainType === "free") && !(await freeNeedsCloud())) return; - const payloads = routeDraft.map((route) => validatedPublicEndpointPayload(route, true)); - if (payloads.some((payload) => !payload || (!payload.redirectTo && (!payload.port || !Number.isInteger(payload.port))))) { + if (routeDraft.domainType === "free" && !(await freeNeedsCloud())) return; + const payload = validatedPublicEndpointPayload(createPublicEndpoint({ + ...routeDraft, port: routeDraft.exposedPort, + }), true); + if (!payload || (!payload.redirectTo && (!payload.port || !Number.isInteger(payload.port)))) { showToast(t.projectSettings.domains.toast.completeEndpoints, "error"); return; } @@ -2094,28 +2089,16 @@ export const DomainSettings = ({ applicationScope = false, serviceScope, onRoute const current = await servicesApi.get(id, editingRouteService.id); if (!current.success) throw new Error(t.projectSettings.domains.toast.routeUpdateFailed); const endpoints = configuredServiceEndpoints(current.service); - const original = originalRouteDraft.current.configured; - const originalHosts = new Set(original.map((route) => resolvePublicEndpointHostname(route, baseDomain))); - for (const route of original) { - const saved = endpoints.find((item) => resolvePublicEndpointHostname(item, baseDomain) === resolvePublicEndpointHostname(route, baseDomain)); - if (!saved || JSON.stringify(validatedPublicEndpointPayload(toEditablePublicEndpoint(saved), true)) !== - JSON.stringify(validatedPublicEndpointPayload(route, true))) { - throw new Error(t.projectDetail.services.detail.networking.routeChanged); - } + const index = endpoints.findIndex((endpoint) => + resolvePublicEndpointHostname(endpoint, baseDomain) === editingRouteTarget.hostname.toLowerCase()); + if (index < 0) throw new Error(t.projectDetail.services.detail.networking.routeChanged); + const next: ServiceEndpoint = { ...payload, redirectTo: routeDraft.redirectTo }; + const hostname = resolvePublicEndpointHostname(next, baseDomain); + if (endpoints.some((endpoint, i) => i !== index && resolvePublicEndpointHostname(endpoint, baseDomain) === hostname)) { + throw new Error(t.projectSettings.domains.add.noWww); } - const index = endpoints.findIndex((route) => originalHosts.has(resolvePublicEndpointHostname(route, baseDomain))); - const next = endpoints.filter((route) => !originalHosts.has(resolvePublicEndpointHostname(route, baseDomain))); - const hosts = new Set(next.map((route) => resolvePublicEndpointHostname(route, baseDomain))); - for (const route of payloads) { - const hostname = resolvePublicEndpointHostname(route!, baseDomain); - if (hosts.has(hostname)) throw new Error(t.projectSettings.domains.add.noWww); - hosts.add(hostname); - } - // An omitted redirect preserves legacy domain-row redirects in service - // updates. Explicitly clear it when this editor chooses to serve the app. - const edited = (payloads as ServiceEndpoint[]).map((route) => ({ ...route, redirectTo: route.redirectTo ?? "" })); - next.splice(index, 0, ...edited); - const ok = await handleServiceRouteUpdate(editingRouteService.id, serviceEndpointsPatch(next, current.service.exposed)); + endpoints[index] = next; + const ok = await handleServiceRouteUpdate(editingRouteService.id, serviceEndpointsPatch(endpoints, current.service.exposed)); if (ok) setEditingRouteTarget(null); } catch (error) { showToast(getApiErrorMessage(error, t.projectSettings.domains.toast.routeUpdateFailed), "error"); @@ -2573,7 +2556,7 @@ export const DomainSettings = ({ applicationScope = false, serviceScope, onRoute onClick={handleCancelEditingDomains} >
event.stopPropagation()} >
@@ -2595,7 +2578,7 @@ export const DomainSettings = ({ applicationScope = false, serviceScope, onRoute
-
+
setPublicEndpoints(nextEndpoints)} allowRemoveAll allowRedirects - allowWww /> -
+
-
-
- !route.redirectTo)?.port || editingRouteService.exposedPort || ""} - ports={servicePortTargets(editingRouteService, baseDomain).filter((target) => target.port && target.protocol === "tcp").map((target) => String(target.port))} - onChange={setRouteDraft} - allowWww - allowRedirects - redirectTargets={[ - ...domainSummaries.filter((domain) => !domain.redirectTo).map((domain) => domain.hostname), - ...services.flatMap((service) => configuredServiceEndpoints(service).filter((route) => !route.redirectTo).map((route) => resolvePublicEndpointHostname(route, baseDomain))), - ].filter((host) => !originalRouteDraft.current.configured.some((route) => resolvePublicEndpointHostname(route, baseDomain) === host))} - portInline - hideHeader - saveMode="change" - /> -
+
+ target.port && target.protocol === "tcp").map((target) => String(target.port))} + exposedPort={routeDraft.exposedPort} + disabled={routeSaving} + liveUrl={editingRouteTarget.liveUrl} + redirect={{ + to: routeDraft.redirectTo, + status: routeDraft.redirectStatus, + targets: [...new Set([ + ...domainSummaries.map(domain => domain.hostname), + ...services.flatMap(service => configuredServiceEndpoints(service).map(endpoint => resolvePublicEndpointHostname(endpoint, baseDomain))), + ])].filter(host => host && host !== editingRouteTarget.hostname && !host.startsWith("*.")), + onChange: ({ to, status }) => setRouteDraft(previous => previous ? { ...previous, redirectTo: to, redirectStatus: status } : previous), + }} + portInline + // The card edits the in-memory draft only — the API is hit ONCE + // on Save. saveMode="change" reports each edit straight to state + // (no per-keystroke/per-toggle request, no inline pill). + onDomainTypeChange={async (value) => { + if (value === "free" && !(await freeNeedsCloud())) return; + setRouteDraft((prev) => (prev ? { ...prev, domainType: value } : prev)); + }} + onDomainChange={(value) => setRouteDraft((prev) => (prev ? { ...prev, domain: value } : prev))} + onCustomDomainChange={(value) => setRouteDraft((prev) => (prev ? { ...prev, customDomain: value } : prev))} + onExposedPortChange={(value) => setRouteDraft((prev) => (prev ? { ...prev, exposedPort: value } : prev))} + saveMode="change" + /> {!editingRouteService.enabled && (

{t.projectSettings.domains.editRoute.disabledWarning} @@ -3098,7 +3109,6 @@ function DiagnosablePill({ function DomainOverviewCard({ domain, - responseRoutes, protectionControl, menuActions = [], sslActionBusy = false, @@ -3118,7 +3128,6 @@ function DomainOverviewCard({ ingressSettings, }: { domain: DomainSummaryItem; - responseRoutes?: React.ReactNode; protectionControl?: React.ReactNode; /** Secondary actions (edit, renew, …) collapsed into a ⋯ menu. Visit is a * plain icon; Verify is a direct inline button below, not a menu item. */ @@ -3492,7 +3501,6 @@ function DomainOverviewCard({

) : null}
- {responseRoutes}
); } diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx index 845559b21..e10f0b21b 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RouteRules.tsx @@ -69,7 +69,7 @@ export function RouteRules() { setLoading(true); try { const res = await projectsApi.listRouteRules(projectData.id); - const list = (res?.rules ?? []).filter(rule => !rule.spec.response); + const list = res?.rules ?? []; setRules(list); if (!autoOpened.current && list.length > 0) { setOpen(true); diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RoutingConfigCard.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RoutingConfigCard.tsx index 0e6bc04a1..ed6423a44 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RoutingConfigCard.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/RoutingConfigCard.tsx @@ -12,7 +12,6 @@ import { RoutingConfigEditor } from "@/components/routing/RoutingConfigEditor"; import { Button } from "@/components/ui/button"; type Props = { - section?: "routing" | "proxy"; id: string; initial: RoutingConfig | null | undefined; /** Project deployment target, independent of the dashboard hosting mode. */ @@ -25,7 +24,7 @@ export function RoutingConfigCard(props: Props) { return ; } -function ProjectRoutingEditor({ id, initial, onSaved, isCloudProject = false, section }: Props) { +function ProjectRoutingEditor({ id, initial, onSaved, isCloudProject = false }: Props) { const { showToast } = useToast(); const { t } = useI18n(); const w = t.widgets.routing.configEditor; @@ -99,11 +98,11 @@ function ProjectRoutingEditor({ id, initial, onSaved, isCloudProject = false, se }; return ( -
+
-

{section === "proxy" ? t.widgets.routing.pages.tabs.proxy : w.title}

-

{section === "proxy" ? t.widgets.routing.pages.proxyHint : w.description}

+

{w.title}

+

{w.description}