diff --git a/.env.example b/.env.example index e0073b4fb..fb8123bc7 100644 --- a/.env.example +++ b/.env.example @@ -251,7 +251,8 @@ 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. -# OBLIEN_API_URL=https://api.oblien.com +# Optional complete API mount override. Unset uses the Oblien SDK default. +# OBLIEN_API_URL=https://your-proxy.example/api/v1 # OBLIEN_CLIENT_ID= # OBLIEN_CLIENT_SECRET= # Optional public base-image pack for NEW managed Cloud spaces only. diff --git a/CHANGELOG.md b/CHANGELOG.md index 77670a6ed..0d57b1d29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,11 +6,35 @@ Runtime security notices use the signed feed published from `security-advisories ## Unreleased +### Authorization + +- Require administrative authority for admin operations across HTTP, SDK, native and + MCP access. Ordinary organization membership no longer grants host command execution; + token grants remain bounded by the user's current built-in role (#1783). + +### Cloud billing + +- Open checkout only when its payment URL is ready, with a visible fallback button. + Recover unfinished Cloud purchases when reopening setup instead of creating duplicate + unpaid spaces. Show pending-plan warnings in the Plans & billing sidebar entry. + +### Backups + +- Back up verified existing empty Docker volumes and bind directories without blocking + populated sibling sources. Reject missing sources before capture and preserve failures + for unavailable backing storage (#1767). + ### CLI - Run the container-to-host connectivity probe with Node.js, matching the API image, so `openship up` and `openship doctor` can diagnose the host channel without Bun. +### Instance relocation + +- Fence event-stream admission while moving the controller so a late subscriber cannot + keep the source draining indefinitely. Restore stream access when the controller resumes, + and link server preparation to its build view while deployment reads remain available. + ## 0.9.12 **Critical update** for build-secret protection, database upgrade repairs and diff --git a/SECURITY.md b/SECURITY.md index 87c2474ab..29b19ad67 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -57,6 +57,12 @@ 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 a4f391f91..0c1556ce6 100644 --- a/apps/api/.env.saas.example +++ b/apps/api/.env.saas.example @@ -31,7 +31,8 @@ BETTER_AUTH_SECRET=change-me-in-production INTERNAL_TOKEN=change-me-32-byte-random-hex # Required for cloud deployments. -OBLIEN_API_URL=https://api.oblien.com +# Leave unset to use the installed SDK's default API version. +# OBLIEN_API_URL=https://your-proxy.example/api/v1 OBLIEN_CLIENT_ID= OBLIEN_CLIENT_SECRET= # Optional: enable only after this software preset is published on your provider. diff --git a/apps/api/scripts/cloud-readiness.ts b/apps/api/scripts/cloud-readiness.ts index 1c2330b94..0a483cae5 100644 --- a/apps/api/scripts/cloud-readiness.ts +++ b/apps/api/scripts/cloud-readiness.ts @@ -1,4 +1,5 @@ /** 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"; @@ -7,13 +8,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 = process.env.OBLIEN_API_URL ?? "https://api.oblien.com"; +const apiBase = oblienApiBaseUrl(process.env.OBLIEN_API_URL); 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 }); +const billing = new OblienBillingApi({ clientId, clientSecret, baseUrl: apiBase.toString() }); const checks = await Promise.allSettled([ (async () => { await billing.assertResellerSupport(); @@ -35,13 +36,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(`${apiBase.replace(/\/+$/, "")}/webhooks`, { + const response = await fetch(oblienApiUrl(apiBase, "/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); + const webhook = body.success ? body.webhooks?.find((item) => item.url === callback && !item.namespace && item.active) : undefined; 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); @@ -56,7 +57,7 @@ const checks = await Promise.allSettled([ })(), (async () => { if (!clientId || !clientSecret) throw new Error("Oblien credentials are missing"); - const response = await fetch(`${apiBase.replace(/\/+$/, "")}/namespaces?limit=1`, { + const response = await fetch(oblienApiUrl(apiBase, "/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 264549493..0363ab976 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -23,6 +23,7 @@ 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"; @@ -408,6 +409,7 @@ 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/route-permission.ts b/apps/api/src/lib/route-permission.ts index 42fc2697e..36deb84ae 100644 --- a/apps/api/src/lib/route-permission.ts +++ b/apps/api/src/lib/route-permission.ts @@ -476,13 +476,10 @@ 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/**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. + * 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. * 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 210f16549..469f5dde6 100644 --- a/apps/api/src/lib/sse.ts +++ b/apps/api/src/lib/sse.ts @@ -41,7 +41,12 @@ 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(); } @@ -182,6 +187,16 @@ 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/billing/billing-capacity-catalog.test.ts b/apps/api/src/modules/billing/billing-capacity-catalog.test.ts index e49d13054..eea7004b3 100644 --- a/apps/api/src/modules/billing/billing-capacity-catalog.test.ts +++ b/apps/api/src/modules/billing/billing-capacity-catalog.test.ts @@ -9,6 +9,7 @@ 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, @@ -17,7 +18,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(capacityFixture)])( + it.each([undefined, oblienCapacityCatalogSchema.parse(cloudBillingContract(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 9bfae4ea9..58bfb2d97 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: () => ({ workspaces: { getQuota: h.quota } }), + getOblienClient: () => ({ vms: { 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 5d92b3621..3ee761206 100644 --- a/apps/api/src/modules/billing/billing-reconcile.test.ts +++ b/apps/api/src/modules/billing/billing-reconcile.test.ts @@ -116,15 +116,25 @@ describe("Oblien-managed entitlements", () => { h.balance.mockResolvedValue({ ...state.balance, billingMode: "payg" }); await expect(assertCloudCanSpend("org_1")).rejects.toMatchObject({ code: "CLOUD_BILLING_BLOCKED" }); }); - it("allows billing recovery after an unpaid renewal without granting compute or credits", async () => { + it.each(["active", "past_due"] as const)("allows billing recovery during a %s unpaid renewal without granting compute or credits", async status => { 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: "past_due" }, entitlement: { status: "canceled", computeCovered: false } }); + expect(result).toMatchObject({ tier: "pro", subscription: { status }, 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/oblien-billing-api.test.ts b/apps/api/src/modules/billing/oblien-billing-api.test.ts index 16fd45c0e..1723cabb3 100644 --- a/apps/api/src/modules/billing/oblien-billing-api.test.ts +++ b/apps/api/src/modules/billing/oblien-billing-api.test.ts @@ -3,6 +3,7 @@ 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"; @@ -25,7 +26,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(body, { status })); + const fetcher = vi.fn(async (_url: Parameters[0], _init?: RequestInit) => Response.json(providerBillingFixture(body), { status })); const api = new OblienBillingApi({ clientId: "test-id", clientSecret: "test-secret", fetch: fetcher as unknown as typeof fetch }); return { api, fetcher }; } @@ -47,7 +48,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/billing/checkout", expect.objectContaining({ + expect(fetcher).toHaveBeenCalledExactlyOnceWith("https://api.oblien.com/v1/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" }), })); @@ -59,7 +60,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/pricing/calculator", expect.objectContaining({ method: "GET", redirect: "error", headers: { Accept: "application/json" } })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/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 } }, @@ -74,14 +75,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/billing/capacity?namespace=os-one"); + expect(fetcher.mock.calls[0]![0]).toBe("https://api.oblien.com/v1/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/billing/capacity/change/cancel", expect.objectContaining({ + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/capacity/change/cancel", expect.objectContaining({ method: "POST", })); expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual({ namespace: "os-one", ...input }); @@ -101,7 +102,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/billing/checkout/bco_original/cancel", + "https://api.oblien.com/v1/billing/checkout/bco_original/cancel", expect.objectContaining({ method: "POST", body: JSON.stringify({ namespace: "os-one", idempotencyKey: "cancel-once" }), @@ -123,7 +124,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/not-a-payment#secret" }, + { quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" }, checkoutId: "cs_requested", url: "https://api.oblien.com/v1/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(); }); @@ -135,16 +136,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: "workspace_vm", ...policy }; + const result = { success: true, namespace: "os-one", service: "vm_compute", ...policy }; const { api, fetcher } = setup(result); expect(await api.setPolicy("os-one", policy)).toEqual(result); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/policy/os-one", expect.objectContaining({ method: "PUT", body: JSON.stringify(policy) })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/policy/os-one", expect.objectContaining({ method: "PUT", body: JSON.stringify(providerBillingFixture(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/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/v1/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" }); }); @@ -215,7 +216,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/billing/checkout/cs_requested?namespace=os-one", + "https://api.oblien.com/v1/billing/checkout/cs_requested?namespace=os-one", ); await expect(api.getCheckout("os-other", "cs_requested")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH", @@ -251,7 +252,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/billing/entitlement?namespace=os-one", expect.objectContaining({ + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/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" }); @@ -275,22 +276,24 @@ describe("Oblien billing SDK and transport contract", () => { idempotencyKey: "checkout-123", }; await api.createCheckout(input); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/checkout", expect.objectContaining({ method: "POST" })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({ method: "POST" })); expect(JSON.parse(String(fetcher.mock.calls[0]![1]!.body))).toEqual({ ...input, allowPromotionCodes: true }); }); - it("accepts the exact Oblien promotion checkout and preserves its opaque ID", async () => { + it("keeps the hosted payment page unversioned while sending checkout requests to /v1", async () => { const checkoutId = "bco_24f15202-6a3d-4b27-b7c2-c3abbc401bee"; const url = `https://api.oblien.com/billing/pay#${"a".repeat(43)}`; - const { api } = setup({ success: true, url, checkoutId }); + const { api, fetcher } = 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/other", + "https://api.oblien.com/billing/pay?return=https://evil.example", "https://api.oblien.com/v1/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({ @@ -553,7 +556,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/billing/portal", expect.objectContaining({ method: "POST", body: JSON.stringify(input), redirect: "error", signal: expect.any(AbortSignal) })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/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 () => { @@ -572,7 +575,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${path}`, expect.objectContaining({ + expect(fetcher).toHaveBeenCalledWith(`https://api.oblien.com/v1${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" }); @@ -612,7 +615,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/billing/capacity/catalog"); + expect(String(url)).toBe("https://api.oblien.com/v1/billing/capacity/catalog"); expect(request?.headers).not.toHaveProperty("X-Client-Secret"); expect(request?.headers).not.toHaveProperty("X-Client-ID"); }); @@ -656,7 +659,7 @@ describe("Oblien monthly capacity contract", () => { .toThrow(/does not match/); } }); - it.each(["past_due", "unpaid", "paused", "canceled"] as const)("keeps billing readable for an expired paid month and a %s renewal", async status => { + it.each(["active", "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"); @@ -665,9 +668,8 @@ 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("still rejects funded, overlapping, foreign or inconsistent unpaid renewal records", () => { + it.each(["active", "past_due"] as const)("still rejects funded, overlapping, foreign or inconsistent %s renewal records", status => { 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; }, @@ -678,9 +680,12 @@ 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(); mutate(state); + const state = unpaidMonthlyCloudBilling(); + state.subscription.status = status; + mutate(state); expect(() => assertOblienEntitlementMatchesSubscription(state.entitlement, state.subscription)).toThrow(/does not match/); } }); @@ -692,9 +697,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/billing/checkout"); + expect(String(url)).toBe("https://api.oblien.com/v1/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, workspaces: 1 } }); + expect(sent.offer).toMatchObject({ unitAmount, credits: 0, billingMode: "monthly", capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, vms: 1 } }); expect(sent.offer).not.toHaveProperty("policy"); expect(sent.idempotencyKey).toBe("saved-monthly-order"); expect(sent.allowPromotionCodes).toBe(unitAmount > 0); @@ -763,18 +768,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/billing/subscription/changes/preview", + expect(preview.fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/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/billing/subscription/changes", + expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/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/billing/subscription/changes/change_one?namespace=os-one", expect.objectContaining({ method: "GET" })); + expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/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/billing/subscription/changes/change_one/cancel", + expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/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 fb2ed26a8..c43a1504f 100644 --- a/apps/api/src/modules/billing/oblien-managed-transfer.test.ts +++ b/apps/api/src/modules/billing/oblien-managed-transfer.test.ts @@ -1,11 +1,12 @@ 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"; -// SDK 2.10's live response shape, with synthetic counters and no customer data. +// Native provider transfer counters with synthetic data. const unlimited = { ...transfer, unlimited: true, includedBytes: null, includedAvailableBytes: null, availableBytes: null }; async function readTransfer(network: unknown, covered = true) { @@ -14,7 +15,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(payload)) as typeof fetch }); + fetch: (async () => Response.json(providerBillingFixture(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 d92cc82fe..25c707895 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", workspace_id: "ws_1", period_end: "2026-08-01T00:00:00Z" }, + data: { namespace: "os-abc", vm_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 360375850..2302b9d73 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: "workspace_vm" } }); + const body = JSON.stringify({ id: "evt-critical", event: "credits.depleted", data: { namespace: "os-abc", service: "vm_compute" } }); 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: "workspace_vm" } }); + const body = JSON.stringify({ id: "evt-activity", event: "credits.depleted", data: { namespace: "os-abc", service: "vm_compute" } }); 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 9530a4f99..f2b18387a 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: { workspace_id: string; path: string; name: string; slug: string; domain?: string }, + input: { vm_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 db9cd5e26..34ac7305e 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({ workspace_id: id, path }).strict(); +const source = z.object({ vm_id: id, path }).strict(); const action = z.discriminatedUnion("kind", [ - z.object({ kind: z.literal("proxy"), workspace: id, port: z.number().int().min(1).max(65535), + z.object({ kind: z.literal("proxy"), vm: 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 03810ef70..10adfda66 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 { workspace_id, path, name, slug, domain? } + * POST /api/cloud/pages { vm_id, path, name, slug, domain? } * * Forwards to Oblien with the caller's namespace token. Oblien * enforces: - * - `workspace_id` must belong to the caller's namespace (or 404) + * - `vm_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<{ - workspace_id?: string; + vm_id?: string; path?: string; name?: string; slug?: string; domain?: string; }>(); - if (!body.workspace_id || !body.path || !body.name || !body.slug) { - return c.json({ error: "workspace_id, path, name and slug are required" }, 400); + if (!body.vm_id || !body.path || !body.name || !body.slug) { + return c.json({ error: "vm_id, path, name and slug are required" }, 400); } try { const result = await createCloudPage(ctx, { - workspace_id: body.workspace_id, + vm_id: body.vm_id, path: body.path, name: body.name, slug: body.slug, 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 841363250..062a62169 100644 --- a/apps/api/src/modules/deployments/cancel-is-final.test.ts +++ b/apps/api/src/modules/deployments/cancel-is-final.test.ts @@ -43,7 +43,6 @@ 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/route-issues-warning.test.ts b/apps/api/src/modules/deployments/route-issues-warning.test.ts index ef824d981..662d10f40 100644 --- a/apps/api/src/modules/deployments/route-issues-warning.test.ts +++ b/apps/api/src/modules/deployments/route-issues-warning.test.ts @@ -1,12 +1,11 @@ import { describe, expect, it, vi } from "vitest"; // The function under test is pure; everything else this module reaches (DB, SSE, -// notifications, favicon probing) is a side effect the assertion doesn't want. +// notifications) 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/routing-apply.service.test.ts b/apps/api/src/modules/domains/routing-apply.service.test.ts index c3a3b8933..c63228aff 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 { workspace: "shared-vm", port: published }; + return { vm: "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({ workspace: "shared-vm", port: 30000 }); + target.mockResolvedValue({ vm: "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", workspace: "shared-vm", port: 30001 }, - { kind: "proxy", workspace: "shared-vm", port: 30002 }, - { kind: "proxy", workspace: "shared-vm", port: 30003 }, + { kind: "proxy", vm: "shared-vm", port: 30001 }, + { kind: "proxy", vm: "shared-vm", port: 30002 }, + { kind: "proxy", vm: "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", workspace: "shared-vm", port: 30002 }, + action: { kind: "proxy", vm: "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", workspace: "shared-vm", port: 30001 }, + action: { kind: "proxy", vm: "shared-vm", port: 30001 }, }, { match: { path: "/api/", type: "prefix" }, - action: { kind: "proxy", workspace: "shared-vm", port: 30003 }, + action: { kind: "proxy", vm: "shared-vm", port: 30003 }, }, { match: { path: "/", type: "prefix" }, - action: { kind: "proxy", workspace: "shared-vm", port: 30001 }, + action: { kind: "proxy", vm: "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", workspace: "shared-vm", port: 30003 } }], + routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", vm: "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", workspace: "shared-vm", port: 30003 }, + action: { kind: "proxy", vm: "shared-vm", port: 30003 }, }, { match: { path: "/", type: "prefix" }, - action: { kind: "proxy", workspace: "shared-vm", port: 30001 }, + action: { kind: "proxy", vm: "shared-vm", port: 30001 }, }, ]); }); diff --git a/apps/api/src/modules/images/images.service.ts b/apps/api/src/modules/images/images.service.ts index b62749d95..6b24ab6c9 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.workspaces.images.list(params); + const response = await client.vms.images.list(params); const images = normalizeImages(response); await store.set(key, images, CACHE_TTL_S); return images; diff --git a/apps/api/src/modules/mcp/mcp-tools.ts b/apps/api/src/modules/mcp/mcp-tools.ts index 030f788ab..12cf298e5 100644 --- a/apps/api/src/modules/mcp/mcp-tools.ts +++ b/apps/api/src/modules/mcp/mcp-tools.ts @@ -76,6 +76,8 @@ 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; @@ -353,6 +355,10 @@ 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; @@ -376,9 +382,7 @@ export function filterToolsForPrincipal( if (principal.role === "restricted" && !caps?.has(needed)) return false; } - if (principal.role !== "restricted") { - return roleAllowsResourceType(principal.role, t.perm.leaf as CheckedResourceType); - } + if (principal.role !== "restricted") return true; // "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 @@ -404,11 +408,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, assertedAction(t.perm.action)) : false; + return held ? permitsAction(held, 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, assertedAction(t.perm.action)); + const capability = capabilityFor(t.perm.leaf, action); return !!capability && !!principal.grantedCapabilities?.has(capability); }); } diff --git a/apps/api/src/modules/mcp/mcp.routes.ts b/apps/api/src/modules/mcp/mcp.routes.ts index 9a80ecf68..16d90eab1 100644 --- a/apps/api/src/modules/mcp/mcp.routes.ts +++ b/apps/api/src/modules/mcp/mcp.routes.ts @@ -128,6 +128,7 @@ async function resolveMcpCaller(token: string, headers: Headers): Promise { { sourceId: "db", envKey: "DATABASE_URL", + valueTemplate: "postgres://app:source-secret@${host}/app", }, ]); expect(privatePlan.services[1].environment.DATABASE_URL).toBe( "postgres://app:source-secret@database/app", ); - expect(privatePlan.project.name).toBe("Project"); - expect(privatePlan.project.services?.map((row) => row.name)).toEqual(["database", "website"]); - expect(JSON.stringify(privatePlan.project)).not.toContain("source-secret"); + 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[0].environment.PGHOST).toBe( privatePlan.services[0].create.internalAlias, ); @@ -182,29 +186,109 @@ describe("reviewed platform imports", () => { 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.project.services?.flatMap((service) => service.volumes ?? [])).toEqual([ + expect(plan.projects[0].create.services?.flatMap((service) => service.volumes ?? [])).toEqual([ "database-data-0:/var/lib/postgresql/data", "website-data-0:/data", ]); - expect(plan.project.services?.[1].dependsOn).toEqual(["database"]); + expect(plan.projects[0].create.services?.[1].dependsOn).toEqual(["database"]); }); - it("blocks incompatible Git sources instead of splitting the source project", async () => { - inventory.services = ["one", "two"].map((id) => + 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: `owner/${id}`, + 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((service) => ({ id: service.id, name: service.name, data: "empty" })), + inventory.services.map((s) => ({ id: s.id, name: s.name, data: "empty" })), ); expect(result.ready).toBe(false); - expect(result.services.flatMap((service) => service.blockers).join(" ")).toContain( - "one Git source", - ); + 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); @@ -318,7 +402,9 @@ 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.project.services?.[0].advanced).toMatchObject({ readiness: { path: "/health", port: 3000 } }); + 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 f932056a4..446bd3f5c 100644 --- a/apps/api/src/modules/migration/platform-import-worker.test.ts +++ b/apps/api/src/modules/migration/platform-import-worker.test.ts @@ -6,7 +6,7 @@ import type { PrivateImportPlan, PlannedImportService, } from "@repo/platform/engine/modules/migration/platform-import-plan"; -import { platformImportProject } from "@repo/platform/engine/modules/migration/platform-import-project"; +import { platformImportProjects } from "@repo/platform/engine/modules/migration/platform-import-project"; const h = vi.hoisted(() => ({ ensure: vi.fn(), merge: vi.fn(), @@ -15,6 +15,7 @@ const h = vi.hoisted(() => ({ sourceService: vi.fn(), rows: [] as Array<{ id: string; projectId: string; name: string }>, view: vi.fn(), + connect: vi.fn(), deploy: vi.fn(), copy: vi.fn(), preflight: vi.fn(), @@ -58,6 +59,9 @@ 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, })); @@ -120,7 +124,8 @@ const planFor = (services: PlannedImportService[]) => userId: "user", targetServerId: "server", services, - project: platformImportProject("imported-project", "server", services), + projectName: "imported-project", + projects: platformImportProjects("imported-project", "server", services), }) as PrivateImportPlan; let row: any; beforeEach(() => { @@ -183,6 +188,9 @@ beforeEach(() => { 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, @@ -195,6 +203,95 @@ 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"; @@ -299,7 +396,8 @@ describe("provider import through normal project operations", () => { 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.project.name = name; + 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])); } @@ -379,9 +477,9 @@ describe("provider import through normal project operations", () => { }), ); }); - it("rejects reviews from the old per-service-project flow before allocating a destination", async () => { + it("rejects reviews without destination projects before allocating a destination", async () => { const plan = planFor([service("app", "app")]); - delete (plan as Partial).project; + delete (plan as Partial).projects; await expect(executePlatformImport(ctx, "run", plan, lifecycle())).rejects.toMatchObject({ code: "IMPORT_REVIEW_EXPIRED", }); @@ -447,7 +545,7 @@ describe("provider import through normal project operations", () => { "deploy:imported-project:3", "healthy:imported-project-build-2", ]); - expect(h.ensure).toHaveBeenCalledExactlyOnceWith(plan.project, "org", ctx, { + expect(h.ensure).toHaveBeenCalledExactlyOnceWith(plan.projects[0].create, "org", ctx, { mustCreate: true, }); expect(h.merge).toHaveBeenCalledWith( diff --git a/apps/api/src/modules/migration/railway-wiring.test.ts b/apps/api/src/modules/migration/railway-wiring.test.ts index b7b45588a..d21c42e47 100644 --- a/apps/api/src/modules/migration/railway-wiring.test.ts +++ b/apps/api/src/modules/migration/railway-wiring.test.ts @@ -42,6 +42,27 @@ 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", { @@ -58,6 +79,7 @@ describe("Railway project wiring", () => { { sourceId: "store", envKey: "ARBITRARY_SETTING", + valueTemplate: "custom://alice:password@${host}:7878/second-db?option=1", }, ]); expect(store.source.port).toBe(7878); 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 02b956160..ac85c40ac 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 f66e072ba..ef4088610 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_workspace_id: fixture.scope.workspaceId, + source_vm_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 497aa8279..864a94be8 100644 --- a/apps/api/src/modules/projects/project-clone.test.ts +++ b/apps/api/src/modules/projects/project-clone.test.ts @@ -32,8 +32,7 @@ const h = { deletedAt: null, deletionInProgress: false, lifecycleOperation: { kind: "delete", status: "failed", error: "Previous cleanup failure" }, - favicon: "https://clincai.example/favicon.ico", - faviconCheckedAt: new Date(), + iconUrl: "https://clincai.example/icon.png", compositeRoutes: [{ host: "clincai.example" }], workspaceId: null, gitProvider: "github", @@ -194,6 +193,7 @@ 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", "favicon", "faviconCheckedAt", "compositeRoutes", "cloudPromotion", "id", "groupId", "createdAt", "updatedAt"]) { + for (const field of ["deletedAt", "deletionInProgress", "lifecycleOperation", "disabledAt", "compositeRoutes", "cloudPromotion", "id", "groupId", "createdAt", "updatedAt"]) { expect(p, field).not.toHaveProperty(field); } }); diff --git a/apps/api/src/modules/system/setup.controller.ts b/apps/api/src/modules/system/setup.controller.ts index 47a90997f..4770e16f6 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` to create one." }, 409); + 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); } const email = 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 e7c29259f..15bc3624e 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 = { - workspaces: { + vms: { get: async () => vm, create: () => { throw new Error("Project operation attempted to create a second host"); }, }, - workspace: () => ({ + vm: () => ({ 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_workspace_id: input.workspace_id, + source_vm_id: input.vm_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({ - workspace: providerVm, + vm: providerVm, port: first.hostPortByContainerPort?.[8080], }); }); diff --git a/apps/api/test/e2e/fixtures/instance-api.ts b/apps/api/test/e2e/fixtures/instance-api.ts index 97f198dea..7bf882126 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) { + if (api.child.exitCode === null && api.child.signalCode === 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/instance-handoff.e2e.test.ts b/apps/api/test/e2e/instance-handoff.e2e.test.ts index 0bb185c46..e39c61903 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, type Server } from "node:http"; +import { createServer, request as httpRequest, 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,6 +433,47 @@ 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/platform-import-project.e2e.test.ts b/apps/api/test/e2e/platform-import-project.e2e.test.ts index e90c76343..b8de6a4ca 100644 --- a/apps/api/test/e2e/platform-import-project.e2e.test.ts +++ b/apps/api/test/e2e/platform-import-project.e2e.test.ts @@ -3,6 +3,9 @@ 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, @@ -20,8 +23,14 @@ import { deployComposeServices } from "@repo/platform/engine/modules/deployments 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 and the asynchronous build queue. +// 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(() => ({ @@ -50,9 +59,18 @@ vi.mock("@repo/platform/engine/modules/migration/migration-runtime", async (orig ...(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, @@ -64,6 +82,8 @@ 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; @@ -107,11 +127,13 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { 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(); }); @@ -128,9 +150,14 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { return container.id; } - it.each(["socket", "cloud"] as const)( - "imports two three-service projects through %s, isolating DNS, env and persisted data", - async (transport) => { + 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, @@ -138,7 +165,7 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { user: { id: owner.userId, name: "Test", email: "test@example.test" }, sessionKind: "cookie", } as ExecutionContext; - const serverId = `${tag}-${transport}`; + const serverId = `${tag}-${transport}-${split}`; await db.insert(schema.servers).values({ id: serverId, organizationId: owner.organizationId, @@ -211,6 +238,40 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { 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", @@ -227,7 +288,7 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { ? await openRuntime() : await CloudDockerRuntime.forWorkspace( { - workspaces: { + vms: { get: async () => ({ id: serverId, namespace: owner.organizationId, @@ -253,7 +314,8 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { { executor: null, localHost: false, - preparedLocalImages: new Map(services.map((s) => [s.id, s.image!])), + preparedLocalImages, + builtImages, targetServiceIds: new Set(input.serviceIds), }, ); @@ -269,7 +331,7 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { const imported: Array<{ id: string; marker: string }> = []; for (const projectNumber of [1, 2]) { - const marker = `${tag}-${transport}-${projectNumber}`; + const marker = `${tag}-${transport}-${split}-${projectNumber}`; const services: ProviderInventory["services"] = []; for (const name of ["db", "cache"]) { const id = `${marker}-${name}`; @@ -332,6 +394,19 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { 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" }, @@ -379,21 +454,26 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { }); } finally { const saved = await repos.project.listByOrganization(owner.organizationId); - for (const p of saved.rows) + 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(1); - const id = ids[0]; - expect(await repos.service.listByProject(id)).toHaveLength(3); + expect(ids).toHaveLength(split ? 3 : 1); expect(checkpoint.completed).toHaveLength(3); expect((await repos.project.listByOrganization(owner.organizationId)).total).toBe( - projectNumber, + projectNumber * (split ? 3 : 1), ); - expect(await repos.project.getEnvMap(id, "production", null)).toEqual({}); - imported.push({ id, marker }); + 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 @@ -407,6 +487,12 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { 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([ @@ -423,13 +509,50 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { ), ).toBe(true); expect(await exec(container, "wget -qO- http://127.0.0.1:8080")).toBe("ready"); - expect(await exec(container, 'printf %s "$BOTH_HOSTS"')).toBe("db,cache"); + 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"); diff --git a/apps/api/test/fixtures/oblien-capacity-catalog.json b/apps/api/test/fixtures/oblien-capacity-catalog.json index 1e937f0cf..78cf91b65 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, - "workspaces": 4 + "vms": 4 }, "monthlyAmount": 500, "paygCapAmount": 625, "resourceLimits": { - "max_workspaces": 4, + "max_vms": 4, "max_vcpus": 1, "max_ram_mb": 512, "max_disk_gb": 10, @@ -76,12 +76,12 @@ "vcpus": 1, "memoryMb": 1024, "diskGb": 20, - "workspaces": 8 + "vms": 8 }, "monthlyAmount": 800, "paygCapAmount": 1000, "resourceLimits": { - "max_workspaces": 8, + "max_vms": 8, "max_vcpus": 1, "max_ram_mb": 1024, "max_disk_gb": 20, @@ -96,12 +96,12 @@ "vcpus": 2, "memoryMb": 4096, "diskGb": 40, - "workspaces": 12 + "vms": 12 }, "monthlyAmount": 1800, "paygCapAmount": 2250, "resourceLimits": { - "max_workspaces": 12, + "max_vms": 12, "max_vcpus": 2, "max_ram_mb": 4096, "max_disk_gb": 40, @@ -116,12 +116,12 @@ "vcpus": 4, "memoryMb": 8192, "diskGb": 80, - "workspaces": 24 + "vms": 24 }, "monthlyAmount": 3600, "paygCapAmount": 4500, "resourceLimits": { - "max_workspaces": 24, + "max_vms": 24, "max_vcpus": 4, "max_ram_mb": 8192, "max_disk_gb": 80, diff --git a/apps/api/test/helpers/monthly-cloud-offer.ts b/apps/api/test/helpers/monthly-cloud-offer.ts index b95c4cb7c..e55e44596 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"; -/** Saved v9 terms and the SDK 2.8 capacity shape, independent of today's catalog. */ +/** OpenShip saved v9 terms, independent of today's catalog and provider wire names. */ 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 new file mode 100644 index 000000000..9f8ea75f9 --- /dev/null +++ b/apps/api/test/helpers/oblien-vm-billing.ts @@ -0,0 +1,40 @@ +/** 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 4be698883..621c3145c 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: () => ({ - workspaces: { get: h.workspace }, + vms: { 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 b2c2cf0cf..9e4d1f18b 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); } - 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, + 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, 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({ workspaces: [], total: 0, limit: 100, page: 1 }); + h.list.mockResolvedValue({ vms: [], 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({ workspaces: [await h.get()], total: 1, limit: 100, page: 1 }); + h.list.mockResolvedValue({ vms: [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({ 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 }); + 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 }); 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({ workspaces: [workspace, { ...workspace, id: "duplicate-vm" }], total: 2, limit: 100, page: 1 }); + h.list.mockResolvedValue({ vms: [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: { workspace_id: "workspace-a" }, + details: { vm_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: { workspace_id: "workspace-a" }, + details: { vm_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 c27c36e3b..f5623dd04 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: "/workspace" })), + clients.map(({ client }) => client._http.request({ method: "GET", path: "/vms" })), ); 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: "/workspace" })).rejects.toMatchObject({ + await expect(client._http.request({ method: "POST", path: "/vms" })).rejects.toMatchObject({ status: 401, }); expect(fetcher).toHaveBeenCalledTimes(1); const next = await getNamespaceClient("org", "space"); - await next.client._http.request({ method: "GET", path: "/workspace" }); + await next.client._http.request({ method: "GET", path: "/vms" }); 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: "/workspace" }).catch((error) => error); + const old = client._http.request({ method: "POST", path: "/vms" }).catch((error) => error); vi.setSystemTime(Date.now() + 1741_000); - await client._http.request({ method: "GET", path: "/workspace" }); + await client._http.request({ method: "GET", path: "/vms" }); 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 e419c3712..2051f666a 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", () => ({ createPlatform: h.createPlatform })); +vi.mock("@repo/adapters", async original => ({ ...await original(), 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 a25adc3c9..69433a654 100644 --- a/apps/api/test/lib/cloud-resource-limits.test.ts +++ b/apps/api/test/lib/cloud-resource-limits.test.ts @@ -2,8 +2,9 @@ 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: () => ({ workspaces: { getQuota: h.quota }, namespaces: { get: h.get, update: h.update } }), + getOblienClient: () => ({ vms: { 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(() => { @@ -11,15 +12,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_workspaces: 52, max_vcpus: 32, max_ram_mb: 65536, max_disk_gb: 1024 }, + effective_resource_limits: { max_vms: 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: cloudNamespaceLimits("pro"), - allocated_resource_usage: { workspaces: 3, vcpus: 2.5, ram_mb: 4096, disk_gb: 48.5, pending_updates: 1 }, + effective_resource_limits: toOblienVmLimits(cloudNamespaceLimits("pro")), + allocated_resource_usage: { vms: 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 } }); @@ -36,8 +37,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_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 }, + 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 }, } }); 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 } }); @@ -50,37 +51,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_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 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 syncCloudResourceLimits("tenant-a", "team"); - expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: cloudNamespaceLimits("team") }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: toOblienVmLimits(cloudNamespaceLimits("team")) }); expect(h.quota).not.toHaveBeenCalled(); }); - it("sends an older saved offer unchanged and accepts Oblien's lower effective ceiling", async () => { + it("preserves an older saved offer when sending VM limits 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: saved }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: toOblienVmLimits(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: saved }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: toOblienVmLimits(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: declared, - effective_resource_limits: { ...declared, max_vcpus: 32, max_ram_mb: 65536 }, + 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 }, } }); 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_workspaces: 5 } } }); + h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: { max_vms: 5 } } }); await syncCloudResourceLimits("tenant-a", "enterprise"); - 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 } }); + 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 } }); }); 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 f41b50777..0c6168e0a 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: () => ({ - workspaces: { get: h.workspaceGet }, + vms: { 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", { workspace_id: "ws-a", path: "/app/dist" }); - expect(h.pageDeploy).toHaveBeenCalledWith("site-a", { workspace_id: "ws-a", path: "/app/dist" }); + 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" }); 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({ workspace_id: "ws-a", path: "/app/dist", name: "Site", slug: "site-a", namespace: "ns-b" }); + await createRemoteCloudAdmin("org-a").pages!.create({ vm_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({ workspace_id: "ws-b", path: "/app/dist", name: "Site", slug: "site-a" })).rejects.toMatchObject({ status: 404 }); + await expect(pages.create({ vm_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 fe6313b97..b6e113560 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: () => ({ - workspaces: { get: h.workspaceGet }, + vms: { 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({ workspace_id: "ws-other", path: "/app/dist", name: "test", slug: "test" })).rejects.toMatchObject({ statusCode: 404 }); + await expect(proxy.pages!.create({ vm_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({ workspace_id: "ws-own", path: "/app/dist", name: "test", slug: "test", namespace: "ns-other" }); + await proxy.pages!.create({ vm_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", { workspace_id: "ws-own", path: "/app/dist" })).rejects.toMatchObject({ statusCode: 404 }); + await expect(pages.deploy("other-page", { vm_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, workspace: "ws-other", port: 8080 } }]; + const routes = [{ match: { path: "/" }, action: { kind: "proxy" as const, vm: "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", workspace: "ws-own", port: 8080 } }] }); + await proxy.setRoutes!("own.opsh.io", { routes: [{ ...routes[0]!, action: { kind: "proxy", vm: "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/controller-sse-drain.test.ts b/apps/api/test/lib/controller-sse-drain.test.ts new file mode 100644 index 000000000..fd2e2ffcc --- /dev/null +++ b/apps/api/test/lib/controller-sse-drain.test.ts @@ -0,0 +1,71 @@ +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/oblien-runtime-env.test.ts b/apps/api/test/lib/oblien-runtime-env.test.ts new file mode 100644 index 000000000..a8fd024d3 --- /dev/null +++ b/apps/api/test/lib/oblien-runtime-env.test.ts @@ -0,0 +1,18 @@ +import { afterEach, expect, it, vi } from "vitest"; + +afterEach(() => { + 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 f4baf51a2..bc4816867 100644 --- a/apps/api/test/lib/permission-grant-satisfiability.test.ts +++ b/apps/api/test/lib/permission-grant-satisfiability.test.ts @@ -24,9 +24,10 @@ 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: "member" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, 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 d1b2a52b9..0f3a3edf0 100644 --- a/apps/api/test/lib/permission-own-projects.test.ts +++ b/apps/api/test/lib/permission-own-projects.test.ts @@ -3,9 +3,10 @@ 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: "member" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, 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 d92e3788a..0620fa0ff 100644 --- a/apps/api/test/lib/permission-wildcard-list-arm.test.ts +++ b/apps/api/test/lib/permission-wildcard-list-arm.test.ts @@ -19,9 +19,10 @@ 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: "member" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, project: { findById: vi.fn(async (id: string) => (id === "*" ? null : { id, organizationId: "org1" })), findEnvVarById: vi.fn(async () => null), @@ -198,7 +199,7 @@ describe("a full project wildcard now lists and creates (deliberate widening)", }); describe("non-restricted roles are untouched by this arm", () => { - it("a member is authorized by role, without consulting grants", async () => { + it("an owner 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/profile-avatar.test.ts b/apps/api/test/lib/profile-avatar.test.ts new file mode 100644 index 000000000..31d4e4604 --- /dev/null +++ b/apps/api/test/lib/profile-avatar.test.ts @@ -0,0 +1,55 @@ +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/modules/actions/billing-webhook.test.ts b/apps/api/test/modules/actions/billing-webhook.test.ts index 8e547c7b2..1eb01e4dc 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_workspaces: 0, + max_vms: 0, max_vcpus: 0, max_ram_mb: 0, max_disk_gb: 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 992ecf782..980fffc58 100644 --- a/apps/api/test/modules/apps/app-install-routing.test.ts +++ b/apps/api/test/modules/apps/app-install-routing.test.ts @@ -703,3 +703,41 @@ 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 f92314c2a..383127280 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 === "/workspace" && method === "POST") { + if (url.pathname === "/vms" && 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: { workspace_id: workspace.id }, + details: { vm_id: workspace.id }, }, { status: 422 }, ); } - if (url.pathname === "/workspace" && method === "GET") { + if (url.pathname === "/vms" && method === "GET") { return Response.json({ success: true, - workspaces: [...workspaces.values()], + vms: [...workspaces.values()], total: workspaces.size, limit: 100, page: 1, }); } - const workspaceId = url.pathname.match(/^\/workspace\/([^/]+)$/)?.[1]; - const retryId = url.pathname.match(/^\/workspace\/([^/]+)\/provisioning\/retry$/)?.[1]; + const workspaceId = url.pathname.match(/^\/vms\/([^/]+)$/)?.[1]; + const retryId = url.pathname.match(/^\/vms\/([^/]+)\/provisioning\/retry$/)?.[1]; if (retryId && method === "POST") { const workspace = workspaces.get(retryId)!; workspace.status = "running"; workspace.provisioning.state = "ready"; - return Response.json({ success: true, workspace }); + return Response.json({ success: true, vm: 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, workspace }) + ? Response.json({ success: true, vm: 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 4dea70ffd..e7de42cd1 100644 --- a/apps/api/test/modules/billing/billing-sdk-parity.test.ts +++ b/apps/api/test/modules/billing/billing-sdk-parity.test.ts @@ -1,4 +1,5 @@ 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"; @@ -60,7 +61,7 @@ vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ }), }), getOblienClient: () => ({ - workspaces: { getQuota: provider.quota, get: provider.workspace }, + vms: { getQuota: provider.quota, get: provider.workspace }, namespaces: { ensure: provider.namespaces, get: provider.resourceRead, @@ -192,8 +193,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(new URL(String(url)).pathname === "/billing/balance" - ? monthly.balance : monthly.entitlement)) as typeof fetch }); + fetch: (async url => Response.json(providerBillingFixture(new URL(String(url)).pathname === "/v1/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", @@ -267,13 +268,13 @@ describe("billing through the same SDK and HTTP application operations", () => { data: { slug, effective_resource_limits: { - max_workspaces: 12, + max_vms: 12, max_total_vcpus: 8, max_total_ram_mb: 16384, max_total_disk_gb: 256, }, allocated_resource_usage: { - workspaces: 0, + vms: 0, vcpus: 0, ram_mb: 0, disk_gb: 0, diff --git a/apps/api/test/modules/billing/credit-alert.test.ts b/apps/api/test/modules/billing/credit-alert.test.ts index d02ca881d..437b90dae 100644 --- a/apps/api/test/modules/billing/credit-alert.test.ts +++ b/apps/api/test/modules/billing/credit-alert.test.ts @@ -23,13 +23,19 @@ const input = { eventType: "namespace.quota.threshold", eventId: "evt1", timestamp: "2026-09-28T00:00:00Z", - data: { namespace: "tenant", service: "workspace_vm", threshold: 95, alert: { limit: 4000 } }, + data: { namespace: "tenant", service: "vm_compute", 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 3402dfe1e..1812cf15b 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", "member"])( + it.each(["owner", "admin"])( "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,6 +129,17 @@ 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))!; @@ -211,7 +222,7 @@ describe("Cloud relays cannot substitute Cloud feature access for host administr it.each([ ["preflight", {}], - ["pages", { workspace_id: "vm-own", path: "/private", name: "export", slug: "export" }], + ["pages", { vm_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 44dfb01c6..34e133682 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", })), }, - workspaces: { + vms: { 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 () => ({ - workspaces: [...vms.values()], + vms: [...vms.values()], total: vms.size, page: 1, limit: 100, @@ -260,9 +260,9 @@ beforeEach(async () => { vms.delete(id); return { success: true }; }), - workspace: (id: string) => ({ + vm: (id: string) => ({ id, - get: () => h.client.workspaces.get(id), + get: () => h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).toHaveBeenCalledTimes(1); + expect(h.client.vms.create).toHaveBeenCalledTimes(1); const outsider = await seedOwner(); expect( @@ -492,7 +492,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { }) ).isError, ).toBe(true); - expect(h.client.workspaces.create).toHaveBeenCalledTimes(1); + expect(h.client.vms.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.workspaces.create).toHaveBeenCalledTimes(1); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create.getMockImplementation()!; - h.client.workspaces.create.mockImplementationOnce(async (input: any) => { + const create = h.client.vms.create.getMockImplementation()!; + h.client.vms.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.workspaces.create.mock.calls.map(([input]: any[]) => input.idempotency_key)) + new Set(h.client.vms.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.workspaces.create.mockRejectedValue(new AppError("Hosts are temporarily at capacity", 503, "CLOUD_CAPACITY_UNAVAILABLE")); + h.client.vms.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.workspaces.create).toHaveBeenCalledTimes(3); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).toHaveBeenCalledTimes(1); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.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.workspaces.create).not.toHaveBeenCalled(); + expect(h.client.vms.create).not.toHaveBeenCalled(); }); }); diff --git a/apps/api/test/modules/deployments/build-duration.test.ts b/apps/api/test/modules/deployments/build-duration.test.ts index 026f4db36..8d1e2cecb 100644 --- a/apps/api/test/modules/deployments/build-duration.test.ts +++ b/apps/api/test/modules/deployments/build-duration.test.ts @@ -13,7 +13,6 @@ 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/compose-host-channel-notice.test.ts b/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts index 7ef67833d..83322bdd5 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) => ({ workspace: "shared-vm", + const resolveRoutingTarget = vi.fn(async (id: string, port: number) => ({ vm: "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", workspace: "shared-vm", port: 30003 } }, - { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "shared-vm", port: 30001 } }, + { 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 } }, ] })); }); 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 100da4d26..7a522fa77 100644 --- a/apps/api/test/modules/deployments/compose-noop-settle.test.ts +++ b/apps/api/test/modules/deployments/compose-noop-settle.test.ts @@ -94,7 +94,6 @@ 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/deploy-outcome-vs-logs.test.ts b/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts index e847bd792..52ffd3b75 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 @@ -113,7 +113,6 @@ 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 () => {}, })); 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 3fd2f63b7..ee521b560 100644 --- a/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts +++ b/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts @@ -13,7 +13,6 @@ 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 6a1cf68ba..4b0e0ec0d 100644 --- a/apps/api/test/modules/deployments/native-sdk-parity.test.ts +++ b/apps/api/test/modules/deployments/native-sdk-parity.test.ts @@ -1897,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: "INSUFFICIENT_ROLE" }); - await expect(dns.removeCredential("dns-a")).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(dns.addCredential(input)).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect(dns.removeCredential("dns-a")).rejects.toMatchObject({ code: "NOT_FOUND" }); } expect(h.dnsAdd).not.toHaveBeenCalled(); expect(h.dnsRemove).not.toHaveBeenCalled(); @@ -2045,10 +2045,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: "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" }); + 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" }); } expect(h.credentialCreate).not.toHaveBeenCalled(); expect(h.credentialUpdate).not.toHaveBeenCalled(); @@ -2492,6 +2492,20 @@ 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" }] }); @@ -2584,11 +2598,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: 403 }); + await expect(system.resetSettings()).rejects.toMatchObject({ statusCode: role === "member" ? 404 : 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: 403 }); + await expect(system.removeUntrackedEdgeSite({ hostname: "orphan.example.test" })).rejects.toMatchObject({ statusCode: role === "member" ? 404 : 403 }); } } expect(h.settingsUpsert).not.toHaveBeenCalled(); 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 5ab30154e..5d07a4e0f 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,9 +32,6 @@ 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/dns/managed-ingress.test.ts b/apps/api/test/modules/dns/managed-ingress.test.ts index 9bc116e4c..9593efea9 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(403); + expect(denied.status).toBe(404); }); }); 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 719dad2d2..be9f00362 100644 --- a/apps/api/test/modules/mcp/mcp-tools-filter.test.ts +++ b/apps/api/test/modules/mcp/mcp-tools-filter.test.ts @@ -135,6 +135,7 @@ 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)), @@ -147,6 +148,16 @@ 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 80dbb98b3..8179cc373 100644 --- a/apps/api/test/modules/mcp/mcp-workspaces.test.ts +++ b/apps/api/test/modules/mcp/mcp-workspaces.test.ts @@ -138,6 +138,22 @@ 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/notifications/notifications-sdk-parity.test.ts b/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts index 0f616742c..06ab6469c 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: "FORBIDDEN" }); + for (const client of [c.native, c.remote]) await expect(client.upsertDefault({ category: "deploy.failed", defaultEnabled: false })).rejects.toMatchObject({ code: "NOT_FOUND" }); }); 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 a6858b068..10a53e784 100644 --- a/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts +++ b/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts @@ -465,8 +465,9 @@ 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 a08e2a3ed..a047ea544 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", workspace: h.fixture.workspaceId, port: 32001 } }], + routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: 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", workspace: h.fixture.workspaceId, port: 32000 } })]), + routes: expect.arrayContaining([expect.objectContaining({ action: { kind: "proxy", vm: 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", workspace: h.fixture.workspaceId, port: 32000 }], - ["console.opsh.io", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32001 }], + ["app.opsh.io", { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 }], + ["console.opsh.io", { kind: "proxy", vm: 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", workspace: h.fixture.workspaceId, port: 32000 }], - ["alias.example.com", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32000 }], + ["app.example.com", { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 }], + ["alias.example.com", { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 }], ]); expect(h.fixture.pages.delete).not.toHaveBeenCalled(); }); diff --git a/apps/api/test/modules/projects/folder-upload.test.ts b/apps/api/test/modules/projects/folder-upload.test.ts index 4360dc34f..9cc62e6a2 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() { +async function open(name?: string) { 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 } : {}), + body: JSON.stringify({ ...(env.CLOUD_MODE ? { serverId: managedServerId } : {}), ...(name ? { name } : {}) }), }); expect(response.status).toBe(200); const target = (await response.json()) as FolderSessionResult; @@ -117,6 +117,33 @@ function upload(target: FolderSessionResult, bytes = archive, chunked = false) { 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); @@ -133,7 +160,8 @@ 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, await response.text()).toBe(400); + expect(response.status).toBe(400); + expect(await response.json()).toMatchObject({ error: expect.stringMatching(/incomplete|truncated/i) }); 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 new file mode 100644 index 000000000..4cbd56c71 --- /dev/null +++ b/apps/api/test/modules/projects/project-icon.test.ts @@ -0,0 +1,58 @@ +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 a716386d1..555e7ddf9 100644 --- a/apps/api/test/modules/projects/project-overview-logs.test.ts +++ b/apps/api/test/modules/projects/project-overview-logs.test.ts @@ -19,7 +19,6 @@ 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 } }) })); 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 fc4d00f0b..1df8a5fb8 100644 --- a/apps/api/test/modules/projects/shared-service-connections.test.ts +++ b/apps/api/test/modules/projects/shared-service-connections.test.ts @@ -66,9 +66,10 @@ 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 })); + 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" })); 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/system/server-exec-authorization.test.ts b/apps/api/test/modules/system/server-exec-authorization.test.ts new file mode 100644 index 000000000..754a3fcb9 --- /dev/null +++ b/apps/api/test/modules/system/server-exec-authorization.test.ts @@ -0,0 +1,48 @@ +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 aeea020f2..364e1abd0 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 = "workspace") => +const jwt = (id = vmId, type = "vm") => `e30.${Buffer.from( JSON.stringify({ type, - workspace_id: id, + vm_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" }, ]), - workspaces: { get: vi.fn(async () => vm), invalidateRuntime: vi.fn() }, - workspace: vi.fn(() => handle), + vms: { get: vi.fn(async () => vm), invalidateRuntime: vi.fn() }, + vm: 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 workspace gateway token and fences repeat rotations", async () => { + it("reveals only a VM 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,12 +414,19 @@ describe("managed server controls through real HTTP, policy and SQL ownership", "MANAGED_RUNTIME_TOKEN_CHANGED", ); expect(handle.apiAccess.rotateToken).toHaveBeenCalledTimes(1); - expect(h.client.workspaces.invalidateRuntime).toHaveBeenCalledWith(vmId); + expect(h.client.vms.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); @@ -482,7 +489,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.workspaces.invalidateRuntime).toHaveBeenCalledWith(vmId); + expect(h.client.vms.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 88e421d30..b0998efd1 100644 --- a/apps/api/test/modules/tokens/mint-org-binding.test.ts +++ b/apps/api/test/modules/tokens/mint-org-binding.test.ts @@ -188,6 +188,16 @@ 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/tsconfig.json b/apps/api/tsconfig.json index 7c483898a..94a494d7e 100644 --- a/apps/api/tsconfig.json +++ b/apps/api/tsconfig.json @@ -15,6 +15,6 @@ "declaration": false, "declarationMap": false }, - "include": ["src/**/*.ts"], + "include": ["src/**/*.ts", "scripts/cloud-readiness.ts"], "exclude": ["node_modules", "dist"] } diff --git a/apps/cli/src/commands/domain.ts b/apps/cli/src/commands/domain.ts index 5661d5b14..9b6011a8c 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 { attachCustomDomainEndpoint } from "../lib/custom-domain-endpoint"; +import { prepareCustomDomainEndpoint } 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,14 +71,17 @@ 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 }); - const routed = await attachCustomDomainEndpoint(ship, opts.project, res.domain.hostname); + await attach(res.domain.hostname); sp?.succeed(`Added ${res.domain.hostname}`); - if (routed) info(` ${res.domain.hostname} is configured to be routed on the next deploy.`); + 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/login.ts b/apps/cli/src/commands/login.ts index e8da11cd3..fb5e18403 100644 --- a/apps/cli/src/commands/login.ts +++ b/apps/cli/src/commands/login.ts @@ -18,6 +18,7 @@ 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; @@ -80,7 +81,7 @@ export async function runLogin(options: LoginOptions = {}): Promise { const existing = getContext(contextName); const local = !opts.cloud && !opts.apiUrl && !existing.apiUrl ? localConnectionEndpoints() : undefined; - const apiUrl = opts.cloud ? CLOUD_API_URL : opts.apiUrl || existing.apiUrl || local!.apiUrl; + let 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; @@ -89,7 +90,7 @@ export async function runLogin(options: LoginOptions = {}): Promise { : opts.dashboardUrl || (sameEndpoint ? existing.dashboardUrl : undefined) || local?.dashboardUrl || - normalizedApi.slice(0, -4); + normalizedApi.slice(0, -4).replace(/\/api\/proxy$/, ""); let token: string | undefined = opts.tokenFile ? readSecret(opts.tokenFile) : opts.token; @@ -132,13 +133,23 @@ 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; - 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 { + 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; } + } 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 9f830de06..5243bdc7a 100644 --- a/apps/cli/src/commands/service.ts +++ b/apps/cli/src/commands/service.ts @@ -25,6 +25,7 @@ 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 ────────────────────────────────────────────────────────── @@ -86,19 +87,7 @@ 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 { - 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); + return resolveServiceRef(getShipClient(), projectId, ref); } // ─── list / get ─────────────────────────────────────────────────────────────── diff --git a/apps/cli/src/commands/up.ts b/apps/cli/src/commands/up.ts index b0bf16f53..5af9fdc1a 100644 --- a/apps/cli/src/commands/up.ts +++ b/apps/cli/src/commands/up.ts @@ -44,6 +44,7 @@ import { LocalExecutor } from "@repo/adapters"; import { resolveInstallInputs, headlessProvision, + provisionInstanceDomain, HeadlessInputError, } from "../lib/instance-provision"; import { mintBareInternalToken } from "../lib/internal-token"; @@ -284,6 +285,26 @@ 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. @@ -319,9 +340,10 @@ export const upCommand = new Command("up") if (!token) { reportCliMessage("warn", chalk.yellow( - "\n Couldn't read the stack's internal token (compose/.env) — create the admin from the dashboard.\n", + "\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", ), ); + process.exit(1); } else { await runHeadlessProvision( opts, @@ -329,6 +351,18 @@ 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; } @@ -336,6 +370,21 @@ 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 @@ -349,17 +398,7 @@ export async function runHeadlessProvision( ): Promise { let inputs; try { - 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, - }); + inputs = upInstallInputs(opts); } catch (err) { if (err instanceof HeadlessInputError) { reportCliMessage("error", chalk.red(`\n ${err.message}\n`)); @@ -377,8 +416,10 @@ export async function runHeadlessProvision( method: extra?.method, onLog: (m) => console.log(chalk.dim(` ${m}`)), }); - console.log(chalk.green(`\n ✓ Openship provisioned${result.liveUrl ? `: ${result.liveUrl}` : "."}`)); 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}` : "."}`)); } catch (err) { observeCaughtError(err, "cli/commands/up"); reportCliMessage("error", chalk.red(`\n Headless provisioning failed: ${(err as Error).message}\n`)); @@ -641,7 +682,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(" Create an admin: open the dashboard and register the first account.\n")), + (headless ? "" : chalk.dim(" Admin setup: run `openship` → Create first admin, or use `openship up --non-interactive --admin-email ` with OPENSHIP_ADMIN_PASSWORD set.\n")), ); return { apiPort: res.apiPort, dashPort: res.dashPort }; } diff --git a/apps/cli/src/commands/wizard.ts b/apps/cli/src/commands/wizard.ts index 814fe0f28..ba716acb0 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 already set up", + "Openship is installed", ); // Crash-looping on a corrupt DB is the one case where "Start" won't help — @@ -1279,6 +1279,7 @@ 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" }, @@ -1287,6 +1288,16 @@ 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/lib/custom-domain-endpoint.ts b/apps/cli/src/lib/custom-domain-endpoint.ts index 1b1c1a8cf..b979265ff 100644 --- a/apps/cli/src/lib/custom-domain-endpoint.ts +++ b/apps/cli/src/lib/custom-domain-endpoint.ts @@ -1,71 +1,79 @@ -import { safeErrorMessage } from "@repo/core"; +import { firstServicePort, resolveRedirectStatus, safeErrorMessage } from "@repo/core"; import type { UpdateProjectInput } from "@repo/contracts"; import type { CliShipClient } from "./ship-client"; -import { reportCliMessage } from "./output"; +import { resolveServiceRef } from "./service-ref"; type PublicEndpoint = NonNullable[number]; -/** Attach the routing endpoint after claiming the domain, as the dashboard does. */ +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. */ export async function attachCustomDomainEndpoint( - ship: Pick, + ship: Pick, projectId: string, hostname: string, ): Promise { - 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 }, - ); - } + await (await prepareCustomDomainEndpoint(ship, projectId))(hostname); + return true; } diff --git a/apps/cli/src/lib/instance-provision.ts b/apps/cli/src/lib/instance-provision.ts index b9801ebc7..33b13c440 100644 --- a/apps/cli/src/lib/instance-provision.ts +++ b/apps/cli/src/lib/instance-provision.ts @@ -268,8 +268,6 @@ 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`."); @@ -279,8 +277,24 @@ 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 = inputs.domain; + const d = opts.domain; let liveUrl: string | undefined; let domainRegistered = false; @@ -392,5 +406,5 @@ export async function headlessProvision(opts: { } } - return { adminReady: true, domainRegistered, liveUrl, warnings }; + return { domainRegistered, liveUrl, warnings }; } diff --git a/apps/cli/src/lib/public-instance-api.ts b/apps/cli/src/lib/public-instance-api.ts new file mode 100644 index 000000000..6df441097 --- /dev/null +++ b/apps/cli/src/lib/public-instance-api.ts @@ -0,0 +1,21 @@ +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 new file mode 100644 index 000000000..619ebbc17 --- /dev/null +++ b/apps/cli/src/lib/service-ref.ts @@ -0,0 +1,13 @@ +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/test/e2e/domain.test.ts b/apps/cli/test/e2e/domain.test.ts index e1d2405cf..cae63fd24 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); - 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 }); + 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(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[0].body).toMatchObject({ isPrimary: true }); + expect(fetchStub.calls.find(call => call.method === "POST")!.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/login.test.ts b/apps/cli/test/e2e/login.test.ts index b869db092..1116501fd 100644 --- a/apps/cli/test/e2e/login.test.ts +++ b/apps/cli/test/e2e/login.test.ts @@ -48,6 +48,7 @@ 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"; @@ -67,6 +68,38 @@ 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 8ffcf15c7..d1716f857 100644 --- a/apps/cli/test/e2e/up.test.ts +++ b/apps/cli/test/e2e/up.test.ts @@ -207,6 +207,8 @@ 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(); }); @@ -218,6 +220,68 @@ 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 1ca62a9cd..7ea232daa 100644 --- a/apps/cli/test/unit/compose-env-preserve.test.ts +++ b/apps/cli/test/unit/compose-env-preserve.test.ts @@ -1753,10 +1753,13 @@ describe("composeUp — the host channel is provisioned out loud (#509)", () => seedHostKey(); h.channelAuth = () => ({ status: 0, stdout: "openship-sudo=refused\n", stderr: "" }); - await composeUp({}); + // 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" }); // 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 39d360423..45f0154c9 100644 --- a/apps/cli/test/unit/custom-domain-endpoint.test.ts +++ b/apps/cli/test/unit/custom-domain-endpoint.test.ts @@ -4,6 +4,8 @@ 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) => { @@ -30,6 +32,18 @@ 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"); @@ -59,6 +73,8 @@ beforeEach(() => { h.rows = []; h.updates = []; h.updateError = false; + h.services = []; + h.serviceUpdates = []; }); afterEach(() => vi.restoreAllMocks()); @@ -122,28 +138,48 @@ describe("CLI custom domain routing", () => { expect(h.updates).toEqual([]); }); - it("warns without attaching a portless worker or failing the command", async () => { + it("refuses a portless worker before claiming a domain", 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(0); - expect(h.rows).toHaveLength(1); + expect(result.code).toBe(1); + expect(h.rows).toEqual([]); expect(h.updates).toEqual([]); - expect(warning.mock.calls.flat().join(" ")).toMatch(/worker.*no public route/i); - expect(result.err).not.toContain("routed on the next deploy"); + expect(result.err).toContain("worker has no public route"); }); - 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(() => {}); + it.each(["services", "monorepo"])("requires an explicit target before claiming a domain for %s", async projectType => { + h.project = { ...h.project, projectType }; const result = await add(); - expect(result.code).toBe(0); - expect(h.rows).toHaveLength(1); + 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(h.updates).toEqual([]); - 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"); + 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"); }); 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 dd0e2f7f7..435f4132f 100644 --- a/apps/cli/test/unit/headless-provision-domain.test.ts +++ b/apps/cli/test/unit/headless-provision-domain.test.ts @@ -14,6 +14,7 @@ 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", () => ({ @@ -22,13 +23,13 @@ vi.mock("../../src/lib/loopback-api", () => ({ return { ok: true, data: { url: "https://ops.example.com" } }; }, waitHealthy: async () => true, - bootstrapAdmin: async () => ({ ok: true, message: "created" }), + bootstrapAdmin: h.bootstrap, // 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 } from "../../src/lib/instance-provision"; +import { headlessProvision, provisionInstanceDomain } from "../../src/lib/instance-provision"; const inputs = { admin: { email: "a@b.com", name: "a", password: "supersecret" }, @@ -39,9 +40,16 @@ 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 new file mode 100644 index 000000000..89ac6d914 --- /dev/null +++ b/apps/cli/test/unit/public-instance-api.test.ts @@ -0,0 +1,20 @@ +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/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx b/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx index 138d19258..b9513fcc3 100644 --- a/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx +++ b/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx @@ -143,7 +143,7 @@ export default function DashboardHomeClient({ ) : (
{sourceProjects.slice(0, 5).map((p) => ( - removeProject(p.id)} /> + removeProject(p.id)} /> ))}
)} diff --git a/apps/dashboard/src/app/(dashboard)/apps/page.tsx b/apps/dashboard/src/app/(dashboard)/apps/page.tsx index 4ba8cd845..377e5f5f2 100644 --- a/apps/dashboard/src/app/(dashboard)/apps/page.tsx +++ b/apps/dashboard/src/app/(dashboard)/apps/page.tsx @@ -184,7 +184,7 @@ export default function AppsPage() {
{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 105bd759e..92eaf168a 100644 --- a/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx +++ b/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx @@ -8,10 +8,8 @@ import { DeploymentMenu } from "./DeploymentMenu"; import { CommitDetailsModal } from "./CommitDetailsModal"; import type { Deployment } from "../types"; import { formatDistanceToNow, formatBuildTime, getStatusConfig } from "../utils"; -import { ProjectStackIcon } from "@/components/shared/ProjectStackIcon"; -import { AppLogo } from "@/components/AppLogo"; +import { ProjectIcon } from "@/components/shared/ProjectIcon"; import { useI18n, interpolate } from "@/components/i18n-provider"; -import { useImageFallback } from "@/hooks/useImageFallback"; type ServiceStatusLabels = { deployed: string; @@ -122,7 +120,6 @@ 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 = { @@ -151,21 +148,9 @@ export const DeploymentCard: React.FC = ({ aria-label={deployment.projectName || t.deployments.card.unknownProject} className="absolute inset-0 z-0" /> - {/* App logo (catalog apps) → project favicon → framework icon → initials */} + {/* Project icon → catalog logo → framework or service icon */}
- {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 213fb5e83..a49f53391 100644 --- a/apps/dashboard/src/app/(dashboard)/deployments/types.ts +++ b/apps/dashboard/src/app/(dashboard)/deployments/types.ts @@ -56,9 +56,8 @@ export interface Deployment { branch?: string; projectId?: string; projectName?: string; - /** 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; + /** Project icon shared with project lists and settings. */ + iconUrl?: 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 f2bc27c23..711c32894 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, - favicon: row.favicon ?? null, + iconUrl: row.iconUrl ?? 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)/projects/[id]/components/AdvancedSettings.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx index fa09be27a..96b71d21c 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx @@ -27,6 +27,7 @@ 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"; interface Props { onDeleteProject: (wipeVolumes?: boolean, recordOnly?: boolean) => void; @@ -357,6 +358,7 @@ export const AdvancedSettings = ({ onDeleteProject }: Props) => { and collided — and since this card has no `overflow-hidden` (the ⋮ menu needs to escape it), the collision spilled into the neighbouring card. */}
+
{ if (!summary.domainId || summary.isPrimary) return; diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.test.tsx index 598bfb73c..a4c904295 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.test.tsx @@ -89,6 +89,7 @@ beforeEach(() => { afterEach(async () => { await act(async () => root.unmount()); host.remove(); + vi.restoreAllMocks(); vi.unstubAllGlobals(); }); @@ -106,6 +107,21 @@ async function choose(scope: ParentNode, name: string) { await click(option!); } +it("shows the saved project icon in the connection picker", async () => { + vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(false); + h.candidates.mockResolvedValue({ + data: [{ id: "web", name: "Web app", description: "production", appTemplateId: "redis", iconUrl: "https://cdn.example.test/project.svg" }], + }); + await act(async () => root.render( + , + )); + const dialog = document.querySelector("[data-modal-surface]")!; + await click(dialog.querySelector('[aria-haspopup="listbox"]')!); + const image = document.querySelector('[role="option"] img'); + expect(image?.getAttribute("src")).toBe("https://cdn.example.test/project.svg"); + expect(image?.getAttribute("referrerpolicy")).toBe("no-referrer"); +}); + describe("connection form copy", () => { it("names the count and project, and points at the deployment status, after sharing values", async () => { h.candidates.mockResolvedValue({ diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx index 4975561d6..b0d0c3df0 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx @@ -5,10 +5,11 @@ import { Icon as UiIcon } from "@repo/ui/icons"; import { useEffect, useMemo, useState } from "react"; import { resolveLocalized } from "@repo/core"; +import type { ProjectConnectionCandidate } from "@repo/contracts"; import { Modal } from "@/components/ui/Modal"; import { CustomSelect } from "@/components/ui/CustomSelect"; import { Checkbox } from "@/components/ui/Checkbox"; -import { AppLogo } from "@/components/AppLogo"; +import { ProjectIcon } from "@/components/shared/ProjectIcon"; import { connectionsApi, type ConnectionMode } from "@/lib/api/connections"; import { getApiErrorMessage } from "@/lib/api/client"; import { useToast } from "@/context/ToastContext"; @@ -49,15 +50,6 @@ function InlineHint({ text }: { text: string }) { ); } -interface TargetProject { - id: string; - name: string; - description: string; - appTemplateId?: string; - favicon?: string | null; - clusterId?: string | null; -} - interface ConnectionFormProps { onClose: () => void; hideHeader?: boolean; @@ -104,7 +96,7 @@ export function ProjectConnectionForm({ (!sourceDatabaseId || output.sourceDatabaseId === sourceDatabaseId), ), [suppliedOutputs, view, sourceServiceId, sourceDatabaseId]); - const [targets, setTargets] = useState([]); + const [targets, setTargets] = useState([]); const [loadingProjects, setLoadingProjects] = useState(true); const [targetId, setTargetId] = useState(fixedTargetId ?? ""); const [mode, setMode] = useState(guide?.defaultMode ?? "internal"); @@ -164,7 +156,7 @@ export function ProjectConnectionForm({ setLoadingProjects(true); connectionsApi.candidates(fixedSourceId ?? fixedTargetId ?? "") .then(result => { - if (!cancelled) setTargets(result.data.map(project => ({ ...project, appTemplateId: project.appTemplateId ?? undefined }))); + if (!cancelled) setTargets(result.data); }) .catch(error => { if (!cancelled) setLoadError(getApiErrorMessage(error, c.failed)); }) .finally(() => { if (!cancelled) setLoadingProjects(false); }); @@ -237,7 +229,7 @@ export function ProjectConnectionForm({ label: p.name, description: p.description || undefined, icon: ( - + ), }))} onChange={fixedTargetId ? setSourceProjectId : setTargetId} diff --git a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx index f662bcf33..85e0967bb 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx @@ -5,8 +5,7 @@ import { Icon as UiIcon } from "@repo/ui/icons"; import React, { useState } from "react"; import Link from "next/link"; import { type Project } from "@/constants/mock"; -import { AppLogo } from "@/components/AppLogo"; -import { ProjectStackIcon } from "@/components/shared/ProjectStackIcon"; +import { ProjectIcon } from "@/components/shared/ProjectIcon"; import { getFrameworkConfig } from "@/components/import-project/Frameworks"; import { getProjectStatus, projectCardHref, projectDisplayDomain } from "@/utils/project-status"; import { ProjectStatusBadge } from "@/components/shared/ProjectStatusBadge"; @@ -15,7 +14,6 @@ import { useModal } from "@/context/ModalContext"; import { useToast } from "@/context/ToastContext"; import { projectsApi, getApiErrorMessage } from "@/lib/api"; import { timeAgo } from "@/lib/time"; -import { useImageFallback } from "@/hooks/useImageFallback"; import type { Dictionary } from "@/i18n"; /* ── Helpers ──────────────────────────────────────────────────────── */ @@ -50,9 +48,6 @@ interface Props { * every row by the projects list and `/info`, but isn't declared on `Project` * (constants/mock) yet, so it's spelled out here rather than cast away. */ project: Project & { primaryDomain?: string | null }; - /** On the Apps page: show the catalog app's brand logo instead of the - * framework/service fallback icon. */ - preferAppLogo?: boolean; /** Show an "update available" badge (fed by the update scan). Off by default * so the Projects page is unaffected. */ updateAvailable?: boolean; @@ -61,14 +56,13 @@ interface Props { onChanged?: () => void; } -const ProjectCard: React.FC = ({ project, preferAppLogo, updateAvailable, onChanged }) => { +const ProjectCard: React.FC = ({ project, updateAvailable, onChanged }) => { const { t } = useI18n(); const { showModal, hideModal } = useModal(); const { showToast } = useToast(); const [menuOpen, setMenuOpen] = useState(false); const status = getProjectStatus(project); const fw = getFrameworkConfig(project.framework); - const favicon = useImageFallback(project.favicon); const isLocal = !!project.localPath; const hasRepo = !!(project.gitOwner && project.gitRepo); @@ -118,22 +112,8 @@ const ProjectCard: React.FC = ({ project, preferAppLogo, updateAvailable,
- {/* Icon — on the Apps page show the catalog app's brand logo; otherwise - the project favicon, falling back to the framework/service glyph. */}
- {preferAppLogo && project.isApp ? ( - - ) : favicon.showImage ? ( - - ) : ( - - )} +
{/* Name + domain */} diff --git a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx index 66f51f1f7..f1aaa56c9 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx @@ -6,14 +6,12 @@ import Link from "next/link"; import { useRouter } from "next/navigation"; import DropdownMenu from "@/components/ui/DropdownMenu"; import { type Project } from "@/constants/mock"; -import { AppLogo } from "@/components/AppLogo"; -import { ProjectStackIcon } from "@/components/shared/ProjectStackIcon"; +import { ProjectIcon } from "@/components/shared/ProjectIcon"; import { getProjectStatus, projectCardHref, projectDisplayDomain } from "@/utils/project-status"; import { ProjectStatusBadge } from "@/components/shared/ProjectStatusBadge"; import { ServiceStatusIndicator } from "@/components/services/ServiceStatusBadge"; import { useI18n, interpolate } from "@/components/i18n-provider"; import { timeAgo } from "@/lib/time"; -import { useImageFallback } from "@/hooks/useImageFallback"; import { getHostingLabel } from "./ProjectCard"; /** Compact project summary with direct links to its management screens. */ @@ -22,12 +20,10 @@ const ProjectGridCard: React.FC<{ * every row by the projects list and `/info`, but isn't declared on `Project` * (constants/mock) yet, so it's spelled out here rather than cast away. */ project: Project & { primaryDomain?: string | null }; - preferAppLogo?: boolean; updateAvailable?: boolean; -}> = ({ project, preferAppLogo, updateAvailable }) => { +}> = ({ project, updateAvailable }) => { const { t } = useI18n(); const router = useRouter(); - const favicon = useImageFallback(project.favicon); const domain = projectDisplayDomain(project); const hosting = getHostingLabel(project.deployTarget, project.serverName, t); @@ -65,20 +61,7 @@ const ProjectGridCard: React.FC<{
- {preferAppLogo && project.isApp ? ( - - ) : favicon.showImage ? ( - // eslint-disable-next-line @next/next/no-img-element - - ) : ( - - )} +
diff --git a/apps/dashboard/src/app/(dashboard)/projects/components/project-favicon.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/components/project-icon.test.tsx similarity index 67% rename from apps/dashboard/src/app/(dashboard)/projects/components/project-favicon.test.tsx rename to apps/dashboard/src/app/(dashboard)/projects/components/project-icon.test.tsx index 2165098d3..e2482db84 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/components/project-favicon.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/components/project-icon.test.tsx @@ -39,10 +39,35 @@ afterEach(async () => { }); for (const [name, Card] of [["list", ProjectCard], ["grid", ProjectGridCard]] as const) { - const render = (favicon = "/favicon-old.ico") => ( - + const render = (iconUrl = "/icon-old.png") => ( + ); - describe(`${name} favicon`, () => { + describe(`${name} iconUrl`, () => { + it("uses a custom icon before the catalog logo on the Apps page", async () => { + complete = false; + root = createRoot(container); + await act(async () => root!.render( + , + )); + expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("https://cdn.example.test/custom.png"); + }); + + it("uses the same catalog fallback when a custom icon fails or is cleared", async () => { + complete = false; + root = createRoot(container); + const custom = "https://cdn.example.test/custom.png"; + const view = (iconUrl: string | null) => ( + + ); + await act(async () => root!.render(view(custom))); + await act(async () => container.querySelector('img[alt=""]')!.dispatchEvent(new Event("error"))); + const fallback = container.querySelector('img[alt=""]')?.getAttribute("src"); + expect(fallback).toBeTruthy(); + expect(fallback).not.toBe(custom); + await act(async () => root!.render(view(null))); + expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe(fallback); + }); + it("falls back when the image failed before hydration attached its error listener", async () => { const view = render(); container.innerHTML = renderToString(view); @@ -59,16 +84,16 @@ for (const [name, Card] of [["list", ProjectCard], ["grid", ProjectGridCard]] as await act(async () => root!.render(render())); await act(async () => container.querySelector('img[alt=""]')!.dispatchEvent(new Event("error"))); expect(container.querySelector('img[alt=""]')).toBeNull(); - await act(async () => root!.render(render("/favicon-new.ico"))); - expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/favicon-new.ico"); + await act(async () => root!.render(render("/icon-new.png"))); + expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/icon-new.png"); }); - it("keeps a successfully cached favicon", async () => { + it("keeps an image that loaded before hydration", async () => { naturalWidth = 32; const view = render(); container.innerHTML = renderToString(view); await act(async () => { root = hydrateRoot(container, view); }); - expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/favicon-old.ico"); + expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/icon-old.png"); }); }); } diff --git a/apps/dashboard/src/app/(dashboard)/projects/page.tsx b/apps/dashboard/src/app/(dashboard)/projects/page.tsx index c692c689e..46aab35f3 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/page.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/page.tsx @@ -109,11 +109,11 @@ export default function ProjectsPage() { ) : filtered.length > 0 ? ( view === "grid" ? (
- {filtered.map(project => )} + {filtered.map(project => )}
) : (
- {filtered.map(project => removeProject(project.id)} />)} + {filtered.map(project => removeProject(project.id)} />)}
) ) : ( diff --git a/apps/dashboard/src/app/(dashboard)/providers.tsx b/apps/dashboard/src/app/(dashboard)/providers.tsx index e1407a0f6..c6c3d0e49 100644 --- a/apps/dashboard/src/app/(dashboard)/providers.tsx +++ b/apps/dashboard/src/app/(dashboard)/providers.tsx @@ -7,6 +7,7 @@ import { PlatformProvider } from "@/context/PlatformContext"; import { MailScopeProvider } from "@/context/MailScopeContext"; import { AuthProvider, type AuthUser } from "@/context/AuthContext"; import { ModalProvider } from "@/context/ModalContext"; +import { DashboardPaymentsProvider } from "@/components/billing/PendingCheckoutsContext"; import type { ProductView } from "@/lib/product-view"; interface DashboardProvidersProps { @@ -50,7 +51,7 @@ export function DashboardProviders({ // Modal content renders where its provider lives, even when opened by a // descendant. Keep dashboard dialogs inside their platform/auth/mail context; // the root layout's provider serves public screens outside this shell. - const content = {children}; + const content = {children}; return ( + { + const result = await authClient.updateUser({ image }); + if (result.error) throw new Error(result.error.message || t.settings.imageUrl.failed); + }} + /> + + ); +} diff --git a/apps/dashboard/src/app/(dashboard)/settings/page.tsx b/apps/dashboard/src/app/(dashboard)/settings/page.tsx index 2e4e5cea0..6b63ae685 100644 --- a/apps/dashboard/src/app/(dashboard)/settings/page.tsx +++ b/apps/dashboard/src/app/(dashboard)/settings/page.tsx @@ -32,6 +32,7 @@ import { useI18n } from "@/components/i18n-provider"; import { BuildPreferences } from "./_components/BuildPreferences"; import { AppearanceSetting } from "./_components/AppearanceSetting"; +import { ProfileSetting } from "./_components/ProfileSetting"; import { AppearanceEditor } from "@/components/appearance/AppearanceEditor"; import { RoutePreferences } from "./_components/RoutePreferences"; import { DeployDefaults } from "./_components/DeployDefaults"; @@ -144,6 +145,7 @@ function SettingsPageInner() {
{activeTab === "general" && !customizeAppearance && ( <> + {/* Deploy Defaults + Routing hidden for now — advanced/rarely-needed, reduces general-settings noise. The edge defaults to loopback-port diff --git a/apps/dashboard/src/app/api/proxy/[...path]/route.test.ts b/apps/dashboard/src/app/api/proxy/[...path]/route.test.ts index 7859cba96..1626849fa 100644 --- a/apps/dashboard/src/app/api/proxy/[...path]/route.test.ts +++ b/apps/dashboard/src/app/api/proxy/[...path]/route.test.ts @@ -1,4 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { createHash } from "node:crypto"; import { NextRequest } from "next/server"; import { errorReporter, consoleErrorSink, type ErrorEvent } from "@repo/core/diagnostics"; @@ -27,6 +28,21 @@ afterEach(async () => { upstreamFetch.mockReset(); }); +it("streams folder uploads larger than the middleware default without changing their bytes", async () => { + const bytes = new Uint8Array(12 * 1024 * 1024).fill(117); + upstreamFetch.mockImplementationOnce(async (_url, init) => { + const received = new Uint8Array(await new Response(init?.body).arrayBuffer()); + expect(createHash("sha256").update(received).digest("hex")).toBe(createHash("sha256").update(bytes).digest("hex")); + expect(new Headers(init?.headers).get("authorization")).toBe("Bearer upload-test"); + return Response.json({ received: received.length }); + }); + const response = await POST(new NextRequest("https://ops.example.com/api/proxy/api/projects/folder/upload/session", { + method: "POST", headers: { authorization: "Bearer upload-test", "Content-Type": "application/gzip" }, body: bytes, + }), { params: Promise.resolve({ path: ["api", "projects", "folder", "upload", "session"] }) }); + expect(response.status).toBe(200); + expect(await response.json()).toEqual({ received: bytes.length }); +}); + it("correlates proxy network failures without logging credentials or request contents", async () => { upstreamFetch.mockRejectedValueOnce(Object.assign(new Error("Connection refused"), { code: "ECONNREFUSED", headers: { authorization: "private-proxy-token-913" }, diff --git a/apps/dashboard/src/components/actions/ActionBudget.test.tsx b/apps/dashboard/src/components/actions/ActionBudget.test.tsx index 15d557a6d..8b7819c01 100644 --- a/apps/dashboard/src/components/actions/ActionBudget.test.tsx +++ b/apps/dashboard/src/components/actions/ActionBudget.test.tsx @@ -15,8 +15,6 @@ const h = vi.hoisted(() => ({ checkout: vi.fn(), resume: vi.fn(), navigate: vi.fn(), - begin: vi.fn(), - closeTab: vi.fn(), closeDialog: vi.fn(), })); vi.mock("@/lib/api/billing", () => ({ @@ -28,10 +26,7 @@ vi.mock("@/lib/api/billing", () => ({ }, })); vi.mock("@/lib/checkout-navigation", () => ({ - beginCheckoutNavigation: (preserve: boolean) => { - h.begin(preserve); - return { navigate: h.navigate, close: h.closeTab }; - }, + navigateToCheckout: (url: string, preserve: boolean) => h.navigate(url, preserve), })); vi.mock("next/navigation", () => ({ useSearchParams: () => new URLSearchParams(h.query) })); vi.mock("@/lib/auth-client", () => ({ @@ -105,25 +100,24 @@ describe("Actions funding UI", () => { h.navigate.mockImplementation((url: string) => url); await render(true); await act(async () => button("Add $5").click()); - expect(h.begin).toHaveBeenCalledWith(true); - expect(h.begin.mock.invocationCallOrder[0]).toBeLessThan(h.checkout.mock.invocationCallOrder[0]!); + expect(h.navigate).toHaveBeenCalledWith(expect.any(String), true); expect(document.querySelector('a[href="https://checkout.stripe.com/saved"]')?.getAttribute("target")).toBe("_blank"); expect(h.closeDialog).not.toHaveBeenCalled(); await act(async () => button("Back to workflow").click()); expect(h.closeDialog).toHaveBeenCalledOnce(); }); - it("closes an unused payment tab on failure and does not expose an invalid payment link", async () => { + it("does not navigate on failure or expose an invalid payment link", async () => { h.budget.mockResolvedValue({ ...initial(), purchasesAvailable: true }); h.checkout.mockRejectedValueOnce(new Error("Provider unavailable")); await render(true); await act(async () => button("Add $5").click()); - expect(h.closeTab).toHaveBeenCalledOnce(); + expect(h.navigate).not.toHaveBeenCalled(); h.checkout.mockResolvedValue({ checkoutUrl: "javascript:invalid" }); h.navigate.mockImplementationOnce(() => { throw new Error("Invalid checkout URL"); }); await act(async () => button("Add $5").click()); expect(document.querySelector('a[href="javascript:invalid"]')).toBeNull(); - expect(h.closeTab).toHaveBeenCalledTimes(2); + expect(h.navigate).toHaveBeenCalledExactlyOnceWith("javascript:invalid", true); }); it("shows live VM estimates and one usage balance without a separate transfer allowance", async () => { @@ -223,7 +217,7 @@ describe("Actions funding UI", () => { await act(async () => button("Add $5").click()); await act(async () => button("Add $5").click()); expect(h.checkout.mock.calls[0]).toEqual(h.checkout.mock.calls[1]); - expect(h.navigate).toHaveBeenCalledWith("https://checkout.stripe.com/saved"); + expect(h.navigate).toHaveBeenCalledWith("https://checkout.stripe.com/saved", false); }); it("distinguishes a funded but paused budget from a balance that needs topping up", async () => { diff --git a/apps/dashboard/src/components/actions/ActionBudget.tsx b/apps/dashboard/src/components/actions/ActionBudget.tsx index 5fe5f8876..fb5659368 100644 --- a/apps/dashboard/src/components/actions/ActionBudget.tsx +++ b/apps/dashboard/src/components/actions/ActionBudget.tsx @@ -6,7 +6,7 @@ import { useSearchParams } from "next/navigation"; import { Icon } from "@repo/ui/icons"; import type { ActionBudget as BudgetData, ActionCreditPurchase } from "@repo/contracts"; import { billingApi } from "@/lib/api/billing"; -import { beginCheckoutNavigation } from "@/lib/checkout-navigation"; +import { navigateToCheckout } from "@/lib/checkout-navigation"; import { randomUUID } from "@/lib/random-uuid"; import { PageContainer } from "@/components/ui/PageContainer"; import { Button } from "@/components/ui/button"; @@ -72,7 +72,6 @@ function Budget({ onClose }: { onClose?: () => void }) { async function checkout(id?: string) { if (!data?.purchasesAvailable || mutation.busy) return; - const navigation = beginCheckoutNavigation(!!onClose); setCheckoutUrl(null); if (!attempts.current.has(deposit)) attempts.current.set(deposit, randomUUID()); const result = await mutation.execute(() => @@ -85,15 +84,13 @@ function Budget({ onClose }: { onClose?: () => void }) { ); if (result?.checkoutUrl) { const url = result.checkoutUrl; - const destination = await mutation.execute(async () => navigation.navigate(url)); + const destination = await mutation.execute(async () => navigateToCheckout(url, !!onClose)); if (destination) setCheckoutUrl(destination); - else navigation.close(); } else if (result && !id) { // A completed/expired intent is no longer a new deposit. A subsequent // explicit purchase gets its own key; uncertain responses keep this one. attempts.current.delete(deposit); } - if (!result?.checkoutUrl) navigation.close(); budget.refresh(); } diff --git a/apps/dashboard/src/components/billing/CheckoutRecovery.tsx b/apps/dashboard/src/components/billing/CheckoutRecovery.tsx index 5851f8c66..30467cccc 100644 --- a/apps/dashboard/src/components/billing/CheckoutRecovery.tsx +++ b/apps/dashboard/src/components/billing/CheckoutRecovery.tsx @@ -15,7 +15,8 @@ import { getApiErrorCode, getApiErrorMessage } from "@/lib/api/client"; import { useSession } from "@/lib/auth-client"; import { useCloudResourceKey } from "@/context/CloudResourceContext"; import { newServerBillingHref, scopedBillingHref } from "@/lib/billing-links"; -import { beginCheckoutNavigation } from "@/lib/checkout-navigation"; +import { navigateToCheckout } from "@/lib/checkout-navigation"; +import { invalidatePayments } from "@/lib/billing-events"; import { ManagedServerActionFeedback } from "@/components/servers/managed/ManagedServerActionFeedback"; import { useManagedServerActions } from "@/components/servers/managed/useManagedServerActions"; import { useBillingScope } from "./BillingWorkspaceContext"; @@ -244,33 +245,27 @@ function CheckoutRow({ setBusy(operation); setError(null); setConfirmCancel(false); - const navigation = operation === "resume" ? beginCheckoutNavigation(preserveProject) : null; if (operation === "cancel") setCancelAttempted(true); try { const response = await billingApi[ operation === "resume" ? "resumeCheckout" : "cancelCheckout" ]({ workspaceId: item.server.id, id: item.id }); - if (!mounted.current) { - navigation?.close(); - return; - } + if (!mounted.current) return; setResult(response); if (response.status === "ready") { - if (!response.checkoutUrl || !navigation) throw new Error(copy.actionError); - const url = navigation.navigate(response.checkoutUrl); + if (!response.checkoutUrl || operation !== "resume") throw new Error(copy.actionError); + const url = navigateToCheckout(response.checkoutUrl, preserveProject); if (preserveProject) { setCheckoutUrl(url); onCheckoutStarted?.(url); } void onRefresh(); } else { - navigation?.close(); setCheckoutUrl(null); if (response.status === "expired") onCleared?.(); router.refresh(); } } catch (err) { - navigation?.close(); if (!mounted.current) return; setError(getApiErrorMessage(err, copy.actionError)); if (getApiErrorCode(err) === "BILLING_CHECKOUT_CANCEL_UNAVAILABLE") setCancelAttempted(false); @@ -278,6 +273,7 @@ function CheckoutRow({ // Refresh reads persisted recovery state; it never starts another checkout. void onRefresh(); } finally { + if (mounted.current) invalidatePayments(); busyRef.current = false; if (mounted.current) setBusy(null); } diff --git a/apps/dashboard/src/components/billing/CloudPlanPicker.tsx b/apps/dashboard/src/components/billing/CloudPlanPicker.tsx index 1ba60de9e..d2f236ad1 100644 --- a/apps/dashboard/src/components/billing/CloudPlanPicker.tsx +++ b/apps/dashboard/src/components/billing/CloudPlanPicker.tsx @@ -13,7 +13,7 @@ import { useI18n } from "@/components/i18n-provider"; import type { BillingSubscription } from "@repo/contracts"; import type { BillingState } from "@/lib/api/billing"; import { needsCloudPlan } from "@/lib/billing-presentation"; -import { useCloudCheckout, useCloudPlans } from "./useCloudBilling"; +import { useCloudCheckout, useCloudPlans, type PreparedCheckoutWorkspace } from "./useCloudBilling"; import { useBillingWorkspace } from "./BillingWorkspaceContext"; import { CustomPlanConfigurator } from "./CustomPlanConfigurator"; import type { ApiPlan } from "./PricingCards"; @@ -86,7 +86,7 @@ function PlanPicker({ preserveProject?: boolean; onCheckoutStarted?: (checkoutUrl?: string) => void; /** New server acquisition resolves its identity only after choosing a plan. */ - prepareWorkspace?: () => Promise; + prepareWorkspace?: () => Promise; onWorkspaceRemoved?: (workspaceId: string) => void; purchaseDetails?: ReactNode; purchaseDisabled?: boolean; @@ -435,7 +435,7 @@ function PlanPicker({ currentOffer={currentOffer} subscription={subscription} allocatedDiskGb={allocatedDiskGb} - disabled={!selectable || purchaseDisabled || managing || (canPurchase && !referral.ready)} + disabled={!selectable || purchaseDisabled || managing || Boolean(checkoutUrl) || (canPurchase && !referral.ready)} busy={busy} actionLabel={canModify ? t.billing.planChange.review : undefined} quoteRevision={quoteRevision} @@ -454,7 +454,7 @@ function PlanPicker({ currentPlan={selectedCurrentPlan} onSelectPlan={handleSelectPlan} subscribingPlan={subscribing} - purchasesDisabled={!selectable || changes.busy || purchaseDisabled || managing || (canPurchase && !referral.ready)} + purchasesDisabled={!selectable || changes.busy || purchaseDisabled || managing || Boolean(checkoutUrl) || (canPurchase && !referral.ready)} selectionLabel={canModify ? t.billing.planChange.review : undefined} interval={interval} annualSavings={annualSavings} @@ -488,16 +488,13 @@ function PlanPicker({ export function CloudCheckoutNotice({ checkoutUrl }: { checkoutUrl: string }) { const { t } = useI18n(); return ( -
-

{t.billing.deployGate.checkoutOpened}

- - {t.billing.deployGate.continueCheckout} - +
+

{t.billing.deployGate.checkoutOpened}

+
); } diff --git a/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx b/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx index 25446098e..d0fbed04f 100644 --- a/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx +++ b/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx @@ -1,5 +1,6 @@ "use client"; +import { reportCaughtError } from "@repo/core/diagnostics"; import { createContext, useCallback, @@ -14,13 +15,19 @@ import { useResourceScope } from "@/hooks/use-scoped-resource"; import { useSession } from "@/lib/auth-client"; import { billingApi } from "@/lib/api/billing"; import { getApiErrorMessage } from "@/lib/api/client"; +import { managementApi } from "@/lib/api/management"; +import { subscriptionNeedsPayment } from "@/lib/billing-presentation"; +import { usePlatform } from "@/context/PlatformContext"; +import { useCloud } from "@/context/CloudContext"; import { useI18n } from "@/components/i18n-provider"; import { useBillingScope } from "./BillingWorkspaceContext"; +import { PAYMENTS_CHANGED } from "@/lib/billing-events"; type PendingCheckouts = { workspaceId?: string; items: BillingPendingCheckout[]; count: number; + attentionCount: number; loading: boolean; error: string | null; refresh: () => Promise; @@ -30,29 +37,43 @@ type PendingCheckouts = { const PendingCheckoutsContext = createContext(null); export const usePendingCheckouts = () => useContext(PendingCheckoutsContext); +/** One organization-wide payment read supplies the rail and billing hub. */ +export function DashboardPaymentsProvider({ children }: { children: ReactNode }) { + const { selfHosted, deployMode } = usePlatform(); + const { connected } = useCloud(); + return + {children} + ; +} + /** Share one read between billing navigation and recovery; never share customer data across scopes. */ export function PendingCheckoutsProvider({ children, workspaceId, enabled = true, + includeManagement = false, }: { children: ReactNode; workspaceId?: string; enabled?: boolean; + includeManagement?: boolean; }) { const scope = useResourceScope(); const { data: session, isPending } = useSession(); const { organizationId } = useBillingScope(); + const parent = usePendingCheckouts(); const allowed = enabled && !isPending && (!organizationId || organizationId === session?.session.activeOrganizationId); + if (parent && parent.workspaceId === workspaceId && allowed && !includeManagement) return children; return ( {children} @@ -64,11 +85,13 @@ function PendingCheckoutsState({ workspaceId, enabled, waiting, + includeManagement, }: { children: ReactNode; workspaceId?: string; enabled: boolean; waiting?: boolean; + includeManagement: boolean; }) { const { t } = useI18n(); const parent = usePendingCheckouts(); @@ -77,6 +100,7 @@ function PendingCheckoutsState({ const [closed, setClosed] = useState>(() => new Set()); const [loading, setLoading] = useState(enabled); const [error, setError] = useState(null); + const [managementPending, setManagementPending] = useState(false); const mounted = useRef(false); const revision = useRef(0); const refreshing = useRef(false); @@ -86,6 +110,16 @@ function PendingCheckoutsState({ refreshing.current = true; setLoading(true); setError(null); + if (includeManagement) { + // Keep compute recovery usable if this account cannot read Manage billing. + void managementApi.get().then(state => { + if (mounted.current && revision.current === request) setManagementPending(Boolean( + state.pendingCheckout || state.change?.paymentUrl || subscriptionNeedsPayment(state.subscription?.status), + )); + }).catch(error => { + reportCaughtError(error, "dashboard/components/billing/PendingCheckoutsContext"); + }); + } try { const result = await billingApi.listCheckouts(workspaceId); if (!mounted.current || revision.current !== request) return; @@ -102,7 +136,7 @@ function PendingCheckoutsState({ setLoading(false); } } - }, [enabled, workspaceId, t.billing.pendingPayments.loadError]); + }, [enabled, workspaceId, includeManagement, t.billing.pendingPayments.loadError]); useEffect(() => { mounted.current = true; void refresh(); @@ -111,10 +145,13 @@ function PendingCheckoutsState({ if (document.visibilityState === "visible" && !refreshing.current) void refresh(); }; window.addEventListener("focus", onFocus); + const onChanged = () => { void refresh(); }; + window.addEventListener(PAYMENTS_CHANGED, onChanged); return () => { mounted.current = false; revision.current++; window.removeEventListener("focus", onFocus); + window.removeEventListener(PAYMENTS_CHANGED, onChanged); }; }, [refresh]); const markCleared = useCallback( @@ -135,6 +172,7 @@ function PendingCheckoutsState({ refresh, markCleared, count: enabled ? items.filter((item) => !closed.has(item.id)).length : 0, + attentionCount: enabled ? new Set(items.filter(item => !closed.has(item.id)).map(item => item.server.id)).size + Number(managementPending) : 0, }} > {children} diff --git a/apps/dashboard/src/components/billing/checkout-recovery.test.tsx b/apps/dashboard/src/components/billing/checkout-recovery.test.tsx index 0d2daa8fc..19a048b40 100644 --- a/apps/dashboard/src/components/billing/checkout-recovery.test.tsx +++ b/apps/dashboard/src/components/billing/checkout-recovery.test.tsx @@ -69,12 +69,6 @@ const ready = { const expired = { status: "expired", checkoutId: "cs_pending", checkoutUrl: null }; let root: Root; let host: HTMLDivElement; -let popup: { - opener: object | null; - closed: boolean; - location: { href: string }; - close: ReturnType; -}; const recovery = () => ( { h.get.mockImplementation(async () => ({ data: { items: [structuredClone(item)] } })); h.post.mockResolvedValue({ data: ready }); h.remove.mockResolvedValue({ ...server, state: "deleting" }); - popup = { opener: {}, closed: false, location: { href: "about:blank" }, close: vi.fn() }; - vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window); + vi.spyOn(window, "open").mockReturnValue(null); host = document.createElement("div"); document.body.append(host); root = createRoot(host); @@ -157,8 +150,7 @@ describe("unfinished checkout recovery", () => { workspaceId: server.id, id: item.id, }); - expect(popup.location.href).toBe(ready.checkoutUrl); - expect(popup.opener).toBeNull(); + expect(window.open).toHaveBeenCalledExactlyOnceWith(ready.checkoutUrl, "_blank", "noopener,noreferrer"); expect(h.started).toHaveBeenCalledExactlyOnceWith(ready.checkoutUrl); expect(dialog()?.querySelector('a[target="_blank"]')?.getAttribute("href")).toBe( ready.checkoutUrl, @@ -374,7 +366,7 @@ describe("unfinished checkout recovery", () => { expect(h.get).toHaveBeenCalledTimes(2); }); - it.each(["local", "cloud"])("ignores earlier payment results after switching the %s account and closes its reserved tab", async (account) => { + it.each(["local", "cloud"])("ignores earlier payment results after switching the %s account without opening checkout", async (account) => { let finish!: (value: unknown) => void; h.post.mockReturnValueOnce( new Promise((resolve) => { @@ -392,8 +384,7 @@ describe("unfinished checkout recovery", () => { h.get.mockResolvedValueOnce({ data: { items: [] } }); await render(); await act(async () => finish({ data: ready })); - expect(popup.location.href).toBe("about:blank"); - expect(popup.close).toHaveBeenCalled(); + expect(window.open).not.toHaveBeenCalled(); expect(h.started).not.toHaveBeenCalled(); expect(dialog()?.textContent).not.toContain(item.name); }); @@ -421,4 +412,15 @@ describe("unfinished checkout recovery", () => { expect(host.querySelector("output")?.textContent).toBe("0"); expect(dialog()?.textContent).toContain(copy.canceled); }); + + it("does not reuse the organization's payment data in a foreign billing scope", async () => { + function Count({ id }: { id: string }) { return {usePendingCheckouts()?.count}; } + await render( + + + ); + expect(host.querySelector("#current")?.textContent).toBe("1"); + expect(host.querySelector("#foreign")?.textContent).toBe("0"); + expect(h.get).toHaveBeenCalledOnce(); + }); }); diff --git a/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx b/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx index 22b68b439..aa1eb806d 100644 --- a/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx +++ b/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx @@ -65,7 +65,6 @@ function Harness() { let root: Root; let container: HTMLDivElement; -let checkoutTab: { opener: unknown; closed: boolean; location: { href: string }; close: ReturnType }; let open: ReturnType; const restriction = () => new ApiError(402, "Payment Required", { code: "CLOUD_BILLING_BLOCKED" }); function button(label: string) { @@ -89,8 +88,7 @@ beforeEach(() => { mocks.get.mockResolvedValue({ data: { locale: "en", annual: { enabled: true, monthsFree: 0 }, ui: pricingUi("en"), plans } }); mocks.deploy.mockRejectedValue(restriction()); mocks.post.mockResolvedValue({ data: { checkoutUrl: "https://checkout.example.test/session" } }); - checkoutTab = { opener: window, closed: false, location: { href: "about:blank" }, close: vi.fn() }; - open = vi.spyOn(window, "open").mockReturnValue(checkoutTab as unknown as Window); + open = vi.spyOn(window, "open").mockReturnValue(null); container = document.createElement("div"); document.body.append(container); root = createRoot(container); @@ -142,13 +140,13 @@ describe("deployment plan selection", () => { let resolveCheckout!: (value: unknown) => void; mocks.post.mockReturnValueOnce(new Promise((resolve) => { resolveCheckout = resolve; })); await act(async () => { button("Choose Hobby").click(); button("Choose Hobby").click(); }); - expect(open).toHaveBeenCalledOnce(); - expect(checkoutTab.opener).toBeNull(); - expect(checkoutTab.location.href).toBe("about:blank"); + expect(open).not.toHaveBeenCalled(); expect(mocks.post).toHaveBeenCalledTimes(1); expect(mocks.post).toHaveBeenCalledWith("billing/subscription", expect.objectContaining({ planTierId: "starter", interval: "monthly", idempotencyKey: expect.any(String) })); await act(async () => resolveCheckout({ data: { checkoutUrl: "https://checkout.example.test/session" } })); - expect(checkoutTab.location.href).toBe("https://checkout.example.test/session"); + expect(open).toHaveBeenCalledExactlyOnceWith("https://checkout.example.test/session", "_blank", "noopener,noreferrer"); + await click("Choose Hobby"); + expect(mocks.post).toHaveBeenCalledTimes(1); expect(container.querySelector("input")?.value).toBe("My configured project"); expect(mocks.deploy).toHaveBeenCalledTimes(1); await click(copy.deployGate.checkPlan); @@ -211,7 +209,7 @@ describe("deployment plan selection", () => { await click("Deploy"); await click("Choose Hobby"); expect(document.querySelector('[role="alert"]')?.textContent).toBe("Checkout temporarily unavailable"); - expect(checkoutTab.close).toHaveBeenCalledOnce(); + expect(open).not.toHaveBeenCalled(); await click("Choose Hobby"); expect(mocks.post.mock.calls[1]![1].idempotencyKey).toBe(mocks.post.mock.calls[0]![1].idempotencyKey); }); diff --git a/apps/dashboard/src/components/billing/server-plan-picker.test.tsx b/apps/dashboard/src/components/billing/server-plan-picker.test.tsx index 4cfd4208f..03937e70b 100644 --- a/apps/dashboard/src/components/billing/server-plan-picker.test.tsx +++ b/apps/dashboard/src/components/billing/server-plan-picker.test.tsx @@ -59,7 +59,6 @@ function customQuote(resources: CustomServerResources): BillingCustomQuote { let management: ManagementState; let root: Root; let host: HTMLDivElement; -let popup: { opener: object | null; closed: boolean; location: { href: string }; close: ReturnType }; function SidebarState() { const { autoCollapse } = useSidebarLayout(); const { collapsed } = useSidebarCollapse("plans", autoCollapse); @@ -101,16 +100,16 @@ beforeEach(() => { vi.resetAllMocks(); vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); h.user = "user-a"; h.org = "org-a"; h.connected = true; h.sessionPending = false; window.location.href = "http://localhost:3000/"; + sessionStorage.clear(); management = { pricing: PRICING.management, purchasesAvailable: true, cloudIncluded: false, active: false, serverLimit: 0, connectedServers: 0, pendingCheckout: false, subscription: null, change: null }; - h.get.mockImplementation(async (path, options) => path === "/billing/manage" ? { data: management } : path.endsWith("/quote") + h.get.mockImplementation(async (path, options) => path === "billing/checkouts" ? { data: { items: [] } } : path === "/billing/manage" ? { data: management } : path.endsWith("/quote") ? { data: customQuote(options.params) } : catalog); h.create.mockResolvedValue(server); h.readServer.mockResolvedValue({ id: server.serverId, name: server.name, managed: server }); h.available.mockResolvedValue({ servers: [] }); h.post.mockResolvedValue({ data: { checkoutUrl: "https://checkout.example.test/new-server" } }); - popup = { opener: {}, closed: false, location: { href: "about:blank" }, close: vi.fn() }; - vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window); + vi.spyOn(window, "open").mockReturnValue(null); host = document.createElement("div"); document.body.append(host); root = createRoot(host); }); afterEach(async () => { @@ -259,6 +258,7 @@ describe("referral checkout handoff", () => { describe("annual Cloud purchases", () => { beforeEach(() => { h.get.mockImplementation(async (path, options) => { + if (path === "billing/checkouts") return { data: { items: [] } }; if (path.endsWith("/quote")) { const annual = options.params.interval === "annual"; return { data: { ...customQuote(options.params), reference: annual ? "quote-annual" : "quote-monthly", @@ -546,7 +546,83 @@ describe("buying another managed server", () => { expect(h.create).not.toHaveBeenCalled(); expect(h.post).not.toHaveBeenCalled(); await click("Choose Starter"); - expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName }); + expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName, idempotencyKey: expect.any(String) }); + }); + + it("reuses the manual server identity after a lost response and reopening the modal", async () => { + h.create.mockRejectedValueOnce(new Error("Creation response lost")); + await render(); + await click("Choose Hobby"); + expect(h.post).not.toHaveBeenCalled(); + const first = h.create.mock.calls[0]; + await act(async () => root.unmount()); root = createRoot(host); + await render(); + await click("Choose Hobby"); + expect(h.create.mock.calls[1]).toEqual(first); + expect(h.post).toHaveBeenCalledOnce(); + await click("Choose Hobby"); + expect(h.post).toHaveBeenCalledOnce(); + }); + + it("reopens an existing unpaid purchase without creating another Cloud space", async () => { + await render(); + await click("Add a destination"); await click("Choose Hobby"); + expect(h.create).toHaveBeenCalledOnce(); + await click(copy.workspaces.returnToSetup); + const ordinary = h.get.getMockImplementation()!; + h.get.mockImplementation((path, options) => path === "billing/checkouts" ? Promise.resolve({ data: { items: [{ + id: "a".repeat(64), checkoutId: "cs_pending", server, kind: "subscription", name: "Saved Hobby", + amountCents: 1200, currency: "usd", interval: "monthly", state: "open", canResume: true, canCancel: true, + }] } }) : ordinary(path, options)); + await click("Add a destination"); await click("Choose Hobby"); + expect(h.create).toHaveBeenCalledOnce(); + expect(document.body.textContent).toContain("Saved Hobby"); + expect(h.post).toHaveBeenCalledOnce(); + h.post.mockResolvedValueOnce({ data: { status: "ready", checkoutId: "cs_pending", checkoutUrl: "https://checkout.example.test/original" } }); + await click(copy.pendingPayments.resume); + expect(h.post).toHaveBeenLastCalledWith("billing/checkout/resume", { workspaceId: server.id, id: "a".repeat(64) }); + expect(window.open).toHaveBeenLastCalledWith("https://checkout.example.test/original", "_blank", "noopener,noreferrer"); + }); + + it("never creates resources when pending payments cannot be checked", async () => { + const ordinary = h.get.getMockImplementation()!; + h.get.mockImplementation((path, options) => path === "billing/checkouts" ? Promise.reject(new Error("Payment status unavailable")) : ordinary(path, options)); + await render(); await click("Choose Hobby"); + expect(h.create).not.toHaveBeenCalled(); expect(h.post).not.toHaveBeenCalled(); + expect(window.open).not.toHaveBeenCalled(); + expect(host.textContent).toContain("Payment status unavailable"); + }); + + it("opens recovery for a submitted payment without attempting another subscription", async () => { + const ordinary = h.get.getMockImplementation()!; + h.get.mockImplementation((path, options) => path === "billing/checkouts" ? Promise.resolve({ data: { items: [{ + id: "a".repeat(64), checkoutId: "cs_processing", server: { ...server, planTierId: "hobby" }, + kind: "subscription", name: "Submitted Hobby payment", amountCents: 1200, currency: "usd", + interval: "monthly", state: "processing", canResume: false, canCancel: false, + }] } }) : ordinary(path, options)); + await render(); await click("Choose Hobby"); + expect(h.create).not.toHaveBeenCalled(); expect(h.post).not.toHaveBeenCalled(); + expect(document.body.textContent).toContain("Submitted Hobby payment"); + expect(document.body.textContent).toContain(copy.pendingPayments.states.processing); + }); + + it("starts a new manual space after the previous purchase completed", async () => { + h.create.mockResolvedValueOnce({ ...server, planTierId: "hobby", state: "running" }); + await render(); await click("Choose Hobby"); + expect(h.create).toHaveBeenCalledTimes(2); + expect(h.create.mock.calls[1][0].idempotencyKey).not.toBe(h.create.mock.calls[0][0].idempotencyKey); + expect(h.post).toHaveBeenCalledOnce(); + }); + + it("does not create a space after the pending-payment read resolves for a different account", async () => { + let finish!: (value: unknown) => void; + const ordinary = h.get.getMockImplementation()!; + h.get.mockImplementation((path, options) => path === "billing/checkouts" ? new Promise(resolve => { finish = resolve; }) : ordinary(path, options)); + await render(); await click("Choose Hobby"); + h.org = "org-b"; await render(); + await act(async () => finish({ data: { items: [] } })); + expect(h.create).not.toHaveBeenCalled(); expect(h.post).not.toHaveBeenCalled(); + expect(window.open).not.toHaveBeenCalled(); }); it("keeps the landing-page plan using the live offer without creating anything on arrival", async () => { @@ -645,9 +721,8 @@ describe("buying another managed server", () => { id: "a".repeat(64), checkoutId: "cs_pending", server, kind: "subscription", name: "Starter", amountCents: 2000, currency: "usd", interval: "monthly", state: "open", canResume: true, canCancel: true, }] } } : catalog); - h.post.mockRejectedValueOnce(new ApiError(409, "Already pending", { code: "CLOUD_WORKSPACE_CHECKOUT_PENDING" })); await render(); - const first = h.post.mock.calls[0][1].idempotencyKey; + expect(h.post).not.toHaveBeenCalled(); await click(copy.pendingPayments.cancel); h.post.mockResolvedValueOnce({ data: { status: "expired", checkoutId: "cs_pending", checkoutUrl: null } }); await click(copy.pendingPayments.confirmCancel); @@ -655,14 +730,15 @@ describe("buying another managed server", () => { expect(url.searchParams.has("startCheckout")).toBe(false); expect(url.searchParams.get("checkoutIntent")).toBe(key); expect(url.searchParams.get("checkoutAttempt")).not.toBe(key); - expect(h.post).toHaveBeenCalledTimes(2); + expect(h.post).toHaveBeenCalledOnce(); + h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : catalog); await act(async () => root.unmount()); root = createRoot(host); await render(); - expect(h.post).toHaveBeenCalledTimes(2); + expect(h.post).toHaveBeenCalledOnce(); await click("Choose Starter"); - expect(h.create.mock.calls[1]).toEqual(h.create.mock.calls[0]); - expect(h.post.mock.calls[2][1].idempotencyKey).not.toBe(first); - expect(h.post.mock.calls[2][1].workspaceId).toBe(server.id); + expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName, idempotencyKey: key }); + expect(h.post.mock.calls[1][1].idempotencyKey).toBe(`${url.searchParams.get("checkoutAttempt")}-starter-monthly`); + expect(h.post.mock.calls[1][1].workspaceId).toBe(server.id); }); it("starts a fresh explicit purchase after removing the cancelled draft", async () => { @@ -672,7 +748,6 @@ describe("buying another managed server", () => { id: "a".repeat(64), checkoutId: "cs_pending", server, kind: "subscription", name: "Starter", amountCents: 2000, currency: "usd", interval: "monthly", state: "open", canResume: true, canCancel: true, }] } } : catalog); - h.post.mockRejectedValueOnce(new ApiError(409, "Already pending", { code: "CLOUD_WORKSPACE_CHECKOUT_PENDING" })); await render(); await click(copy.pendingPayments.cancel); h.post.mockResolvedValueOnce({ data: { status: "expired", checkoutId: "cs_pending", checkoutUrl: null } }); @@ -680,11 +755,12 @@ describe("buying another managed server", () => { h.remove.mockResolvedValueOnce({ data: { accepted: true } }); await click(copy.pendingPayments.deleteServer); await click(copy.workspaces.confirmDelete); - expect(h.create).toHaveBeenCalledOnce(); + expect(h.create).not.toHaveBeenCalled(); + h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : catalog); expect(new URL(window.location.href).searchParams.get("checkoutIntent")).not.toBe(key); expect(new URL(window.location.href).searchParams.has("startCheckout")).toBe(false); await click("Choose Starter"); - expect(h.create.mock.calls[1][0].idempotencyKey).not.toBe(key); + expect(h.create.mock.calls[0][0].idempotencyKey).not.toBe(key); }); it("does not continue a pending pricing purchase in another account or organization", async () => { @@ -706,7 +782,7 @@ describe("buying another managed server", () => { currentPeriod: { start: null, end: null }, monthlyCreditLimit: 0, buildTimeMinutes: 0, balance: { total: 0, quotaLimit: 0, quotaUsed: 0, quotaRemaining: 0 }, workspace: server, billing: { enabled: true } }; - h.get.mockImplementation(async path => path === "billing/state" ? { data: billing } : catalog); + h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : path === "billing/state" ? { data: billing } : catalog); const location = window.location.href; await render(); await click("Add a destination"); @@ -741,7 +817,7 @@ describe("buying another managed server", () => { const started = vi.fn(); await render(); await act(async () => { buttons("Choose Starter")[0]!.click(); buttons("Choose Starter")[0]!.click(); }); - expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName }); + expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName, idempotencyKey: expect.any(String) }); expect(h.post).not.toHaveBeenCalled(); await act(async () => created(server)); expect(h.post).toHaveBeenCalledWith("billing/subscription", expect.objectContaining({ workspaceId: server.id, planTierId: "starter" })); @@ -750,8 +826,7 @@ describe("buying another managed server", () => { expect(h.create).toHaveBeenCalledOnce(); expect(h.post.mock.calls[1]).toEqual(h.post.mock.calls[0]); expect(started).toHaveBeenCalledWith(server, "https://checkout.example.test/new-server"); - expect(popup.location.href).toBe("https://checkout.example.test/new-server"); - expect(popup.opener).toBeNull(); + expect(window.open).toHaveBeenCalledExactlyOnceWith("https://checkout.example.test/new-server", "_blank", "noopener,noreferrer"); }); it("keeps the new server and exact purchase when retrying from unavailable-capacity feedback", async () => { @@ -762,7 +837,7 @@ describe("buying another managed server", () => { await click("Choose Pro"); expect(document.querySelector('[role="dialog"]')?.textContent).toContain(copy.checkoutUnavailable.capacityTitle); expect(document.body.textContent).not.toContain("Raw provider failure"); - expect(popup.close).toHaveBeenCalledOnce(); + expect(window.open).not.toHaveBeenCalled(); expect(h.post.mock.calls[0]![1]).toMatchObject({ workspaceId: server.id, planTierId: "pro" }); await click(copy.checkoutUnavailable.retry); expect(h.create).toHaveBeenCalledOnce(); @@ -775,7 +850,6 @@ describe("buying another managed server", () => { id: "a".repeat(64), checkoutId: "cs_pending", server, kind: "subscription", name: "Saved Starter", amountCents: 2000, currency: "usd", interval: "monthly", state: "open", canResume: true, canCancel: true, }] } } : catalog); - h.post.mockRejectedValueOnce(new ApiError(409, "Blocked", { code: "CLOUD_WORKSPACE_CHECKOUT_PENDING", error: "Raw pending error" })); h.post.mockImplementation(async path => path === "billing/checkout/cancel" ? { data: { status: "expired", checkoutId: "cs_pending", checkoutUrl: null } } : { data: { checkoutUrl: "https://checkout.example.test/new-server" } }); @@ -785,6 +859,7 @@ describe("buying another managed server", () => { expect(document.querySelector('[role="dialog"]')?.textContent).toContain(copy.pendingPayments.title); expect(document.body.textContent).not.toContain("Raw pending error"); await click(copy.pendingPayments.cancel); await click(copy.pendingPayments.confirmCancel); + h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : catalog); if (remove) { await click(copy.pendingPayments.deleteServer); await click(copy.workspaces.confirmDelete); h.create.mockResolvedValueOnce({ ...server, id: "cws-replacement", serverId: "server-replacement" }); @@ -792,10 +867,9 @@ describe("buying another managed server", () => { await act(async () => document.querySelector(`button[aria-label="${copy.checkoutUnavailable.close}"]`)!.click()); await click("Choose Starter"); const attempts = h.post.mock.calls.filter(([path]) => path === "billing/subscription").map(([, input]) => input); - expect(attempts).toHaveLength(2); - expect(attempts[1].idempotencyKey).not.toBe(attempts[0].idempotencyKey); - expect(attempts[1].workspaceId).toBe(remove ? "cws-replacement" : server.id); - expect(h.create).toHaveBeenCalledTimes(remove ? 2 : 1); + expect(attempts).toHaveLength(1); + expect(attempts[0].workspaceId).toBe(remove ? "cws-replacement" : server.id); + expect(h.create).toHaveBeenCalledTimes(remove ? 1 : 0); }); it("discards an unavailable checkout when the customer changes organization", async () => { @@ -818,7 +892,7 @@ describe("buying another managed server", () => { await render(); await act(async () => created(server)); expect(h.post).not.toHaveBeenCalled(); - expect(popup.close).toHaveBeenCalled(); + expect(window.open).not.toHaveBeenCalled(); h.create.mockResolvedValueOnce({ ...server, id: "cws-org-b" }); await click("Choose Starter"); expect(h.post).toHaveBeenCalledWith("billing/subscription", expect.objectContaining({ workspaceId: "cws-org-b" })); diff --git a/apps/dashboard/src/components/billing/useCloudBilling.ts b/apps/dashboard/src/components/billing/useCloudBilling.ts index 97fc55b83..8abbeea39 100644 --- a/apps/dashboard/src/components/billing/useCloudBilling.ts +++ b/apps/dashboard/src/components/billing/useCloudBilling.ts @@ -7,12 +7,12 @@ import type { PlanTierId } from "@repo/core"; import type { BillingPlans, CustomSubscriptionSelection } from "@repo/contracts"; import { useI18n } from "@/components/i18n-provider"; import { api, ApiError, getApiErrorCode, getApiErrorMessage } from "@/lib/api/client"; -import { beginCheckoutNavigation } from "@/lib/checkout-navigation"; +import { navigateToCheckout } from "@/lib/checkout-navigation"; +import { invalidatePayments } from "@/lib/billing-events"; import { endpoints } from "@/lib/api/endpoints"; import { randomUUID } from "@/lib/random-uuid"; import { checkoutFailureKind, type CheckoutFailure } from "@/lib/checkout-failure"; -import { useSession } from "@/lib/auth-client"; -import { useCloudResourceKey } from "@/context/CloudResourceContext"; +import { useResourceScope } from "@/hooks/use-scoped-resource"; import type { ApiPlan, ApiPricingUi } from "./PricingCards"; interface PlansPayload extends Omit { @@ -20,6 +20,8 @@ interface PlansPayload extends Omit { plans: ApiPlan[]; } +export type PreparedCheckoutWorkspace = string | { workspaceId: string; checkoutPending: true }; + /** Both the recommendation and comparison use the same live checkout catalog. */ export function useCloudPlans() { const { t, locale } = useI18n(); @@ -47,7 +49,7 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS workspaceId?: string; preserveProject?: boolean; onCheckoutStarted?: (checkoutUrl: string) => void; - prepareWorkspace?: () => Promise; + prepareWorkspace?: () => Promise; onWorkspaceRemoved?: (workspaceId: string) => void; idempotencyKey?: string; referralCode?: string; @@ -55,9 +57,8 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS }) { const { t } = useI18n(); const { workspaceId: billingWorkspaceId, organizationId } = useBillingScope(); - const { data: session } = useSession(); - const cloudKey = useCloudResourceKey(); - const ownerKey = `${cloudKey}:${session?.user.id}:${organizationId ?? session?.session?.activeOrganizationId}`; + const scope = useResourceScope(); + const ownerKey = `${scope}:${organizationId ?? ""}`; const workspaceId = selectedWorkspaceId ?? billingWorkspaceId ?? undefined; const [subscribing, setSubscribing] = useState(null); const [error, setError] = useState(null); @@ -78,11 +79,10 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS useEffect(() => { attempts.current.clear(); }, [idempotencyKey]); async function startCheckout(planTierId: PlanTierId, interval: "monthly" | "annual", custom?: CustomSubscriptionSelection) { - if (!enabled || busy.current || planTierId === "free" || planTierId === "enterprise") return; + if (!enabled || busy.current || checkoutUrl || planTierId === "free" || planTierId === "enterprise") return; busy.current = true; const version = generation.current; - // Open within the user's click, preserving unfinished project configuration. - const navigation = beginCheckoutNavigation(preserveProject); + let checkoutStarted = false; setSubscribing(custom ? "custom" : planTierId); setError(null); setCheckoutUrl(null); @@ -91,8 +91,13 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS let targetWorkspaceId = workspaceId; let requestId: string | undefined; try { - targetWorkspaceId = prepareWorkspace ? await prepareWorkspace() : workspaceId; - if (version !== generation.current) { navigation.close(); return; } + const prepared = prepareWorkspace ? await prepareWorkspace() : workspaceId; + targetWorkspaceId = typeof prepared === "object" ? prepared.workspaceId : prepared; + if (version !== generation.current) return; + if (typeof prepared === "object" && prepared.checkoutPending) { + setPending({ workspaceId: prepared.workspaceId }); + return; + } if (prepareWorkspace && !targetWorkspaceId) throw new Error(t.billing.plansRoute.checkoutError); const attempt = `${targetWorkspaceId ?? "initial"}:${custom?.quoteReference ?? planTierId}:${interval}:${referralCode ?? ""}`; if (!attempts.current.has(attempt)) attempts.current.set(attempt, @@ -102,14 +107,14 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS planTierId, interval, workspaceId: targetWorkspaceId, custom, idempotencyKey: requestId, ...(referralCode ? { referralCode } : {}), }); - if (version !== generation.current) { navigation.close(); return; } - const url = navigation.navigate(res.data.checkoutUrl); + if (version !== generation.current) return; + const url = navigateToCheckout(res.data.checkoutUrl, preserveProject); if (preserveProject) { + checkoutStarted = true; setCheckoutUrl(url); onCheckoutStarted?.(url); } } catch (err) { - navigation.close(); if (version !== generation.current) return; const kind = checkoutFailureKind(err); if (getApiErrorCode(err) === "CLOUD_WORKSPACE_CHECKOUT_PENDING") setPending({ workspaceId: targetWorkspaceId }); @@ -120,8 +125,9 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS } } finally { if (version === generation.current) { - busy.current = false; + busy.current = checkoutStarted; setSubscribing(null); + invalidatePayments(); } } } @@ -129,7 +135,7 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS recovery: { isOpen: pending !== null, workspaceId: pending?.workspaceId, preserveProject, onClose: () => setPending(null), - onCleared: () => { attempts.current.clear(); setError(null); onCheckoutSettled?.(); }, + onCleared: () => { busy.current = false; attempts.current.clear(); setCheckoutUrl(null); setError(null); onCheckoutSettled?.(); }, onCheckoutStarted: (url: string) => { setCheckoutUrl(url); onCheckoutStarted?.(url); }, onServerRemoved: (id: string) => { attempts.current.clear(); setCheckoutUrl(null); onWorkspaceRemoved?.(id); diff --git a/apps/dashboard/src/components/instance/InstanceLocation.tsx b/apps/dashboard/src/components/instance/InstanceLocation.tsx index 80efb4396..5b893c744 100644 --- a/apps/dashboard/src/components/instance/InstanceLocation.tsx +++ b/apps/dashboard/src/components/instance/InstanceLocation.tsx @@ -129,9 +129,9 @@ export function InstanceProgress({ Cancel move )} - {h?.provisioning?.deploymentId && ( + {state.role === "active" && h?.provisioning?.deploymentId && ( )}
diff --git a/apps/dashboard/src/components/instance/instance-location.test.tsx b/apps/dashboard/src/components/instance/instance-location.test.tsx index 171377bd4..37ab3fa0e 100644 --- a/apps/dashboard/src/components/instance/instance-location.test.tsx +++ b/apps/dashboard/src/components/instance/instance-location.test.tsx @@ -41,4 +41,14 @@ describe("instance handoff recovery UI", () => { expect(html).not.toContain("Cancel move"); expect(instanceProgress(retired)).toBe("Connecting to the new control plane"); }); + it("links server preparation to its build view while the source controller is active", () => { + const preparing: InstanceStatus = { ...state, role: "active", handoff: { + ...state.handoff!, provisioning: { projectId: "project", deploymentId: "deploy", access: "desktop" }, + } }; + const html = renderToStaticMarkup( {}} />); + expect(html).toContain('href="/build/deploy"'); + expect(html).not.toContain('href="/deployments/deploy"'); + const frozen = renderToStaticMarkup( {}} />); + expect(frozen).not.toContain("View deployment"); + }); }); diff --git a/apps/dashboard/src/components/migration/PlatformImportReview.tsx b/apps/dashboard/src/components/migration/PlatformImportReview.tsx index f450af8bb..22c607f61 100644 --- a/apps/dashboard/src/components/migration/PlatformImportReview.tsx +++ b/apps/dashboard/src/components/migration/PlatformImportReview.tsx @@ -37,6 +37,7 @@ export function PlatformImportReview({ onStart: () => void; }) { const imports = plan.services.filter((s) => choices[s.id]?.data !== "external"); + const projectCount = plan.projects?.length ?? 1; return (
@@ -86,6 +87,15 @@ export function PlatformImportReview({

{importDataLabel(service, choice)}

+ {projectCount > 1 && ( +

+ Project:{" "} + { + plan.projects?.find((project) => project.serviceIds.includes(service.id)) + ?.name + } +

+ )}
{service.commit @@ -161,8 +171,15 @@ export function PlatformImportReview({

Review complete

- One project · {imports.length} {imports.length === 1 ? "service" : "services"} + {projectCount} {projectCount === 1 ? "project" : "projects"} · {imports.length}{" "} + {imports.length === 1 ? "service" : "services"}

+ {projectCount > 1 && ( +

+ Separate projects keep each service’s repository and revision. Dependencies use + private connections on the destination server. +

+ )}

- Services stay together in one project on its private network. Configure test domains after - import, then move production traffic. + Services with different Git sources import into separate projects with private + connections. Review the destination projects before importing. Configure test domains + after import, then move production traffic.

diff --git a/apps/dashboard/src/components/migration/platform-import-flow.test.tsx b/apps/dashboard/src/components/migration/platform-import-flow.test.tsx index 60675649a..4646d0d7a 100644 --- a/apps/dashboard/src/components/migration/platform-import-flow.test.tsx +++ b/apps/dashboard/src/components/migration/platform-import-flow.test.tsx @@ -533,7 +533,9 @@ describe("platform import flow", () => { await render(); await click("Choose services"); expect(button("Check import").disabled).toBe(true); - expect(host.textContent).toContain("Services stay together in one project"); + expect(host.textContent).toContain( + "Services with different Git sources import into separate projects", + ); await fill(host.querySelector('input[type="password"]')!, "fixture-secret"); await click("Check import"); expect(h.review).toHaveBeenCalledWith( @@ -570,6 +572,25 @@ describe("platform import flow", () => { expect(h.push).toHaveBeenCalledWith("/migrations/run"); }); + it("shows separate destination projects before approving a multi-repository import", async () => { + h.review.mockResolvedValueOnce({ + ...plan, + projects: [ + { name: "production-database", serviceIds: ["db"] }, + { name: "production-website", serviceIds: ["web"] }, + ], + }); + await render(); + await selectServices(); + await click("Check import"); + expect(host.textContent).toContain("2 projects · 2 services"); + expect(host.textContent).toContain("Project: production-database"); + expect(host.textContent).toContain("Project: production-website"); + expect(host.textContent).toContain("Dependencies use private connections"); + expect(button("Import project").disabled).toBe(true); + expect(h.start).not.toHaveBeenCalled(); + }); + it("keeps blocked reviews in the editor and requires a fresh review after changing destination", async () => { h.review.mockResolvedValueOnce({ ...plan, diff --git a/apps/dashboard/src/components/overview/HomeAppsCard.tsx b/apps/dashboard/src/components/overview/HomeAppsCard.tsx index aa0d4fe73..ac1024970 100644 --- a/apps/dashboard/src/components/overview/HomeAppsCard.tsx +++ b/apps/dashboard/src/components/overview/HomeAppsCard.tsx @@ -4,7 +4,7 @@ import { useId } from "react"; import Link from "next/link"; import { Icon } from "@repo/ui/icons"; import type { Project } from "@/constants/mock"; -import { AppLogo } from "@/components/AppLogo"; +import { ProjectIcon } from "@/components/shared/ProjectIcon"; import { useI18n } from "@/components/i18n-provider"; import { ProjectStatusBadge } from "@/components/shared/ProjectStatusBadge"; import { Button } from "@/components/ui/button"; @@ -66,7 +66,7 @@ export default function HomeAppsCard({ className="absolute inset-0 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring" />
- +

+ } + onSave={async (iconUrl) => { + const response = await projectsApi.update(projectData.id, { iconUrl }); + updateProjectData({ iconUrl: response.data.iconUrl }); + invalidateProjectCaches(projectData.id); + }} + /> + ); +} diff --git a/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx b/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx index c475b1b53..51eaa78de 100644 --- a/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx +++ b/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx @@ -1,5 +1,6 @@ "use client"; +import { reportCaughtError } from "@repo/core/diagnostics"; import { useEffect, useRef, useState } from "react"; import type { CloudWorkspaceSummary } from "@repo/contracts"; import { useI18n } from "@/components/i18n-provider"; @@ -8,8 +9,9 @@ import { BillingWorkspaceProvider } from "@/components/billing/BillingWorkspaceC import { Button } from "@/components/ui/button"; import { useSession } from "@/lib/auth-client"; import { systemApi } from "@/lib/api/system"; -import { getApiErrorMessage } from "@/lib/api/client"; -import { useCloudResourceKey } from "@/context/CloudResourceContext"; +import { getApiErrorCode, getApiErrorMessage } from "@/lib/api/client"; +import { billingApi } from "@/lib/api/billing"; +import { useResourceScope } from "@/hooks/use-scoped-resource"; import { randomUUID } from "@/lib/random-uuid"; import { isCloudPurchaseIntent } from "@/lib/cloud-purchase-intent"; @@ -31,8 +33,7 @@ interface PurchaseProps { * Browsing does not create a server; retries reuse the identity just created. */ export function ManagedServerPurchase(props: PurchaseProps) { const { data: session, isPending } = useSession(); - const cloudKey = useCloudResourceKey(); - const contextKey = `${cloudKey}:${session?.user.id ?? "local"}:${session?.session.activeOrganizationId ?? ""}`; + const contextKey = useResourceScope(); const [intent, setIntent] = useState<{ owner: string; key: string; paymentKey: string; automatic: boolean } | null>(null); useEffect(() => { if (intent || isPending || !session?.user.id || !session.session.activeOrganizationId) return; @@ -84,14 +85,55 @@ function Purchase({ onIntentRemoved, }: PurchaseProps & { sessionPending?: boolean; onCheckoutSettled?: () => void; onIntentRemoved?: () => void }) { const { t } = useI18n(); + const scope = useResourceScope(); + const owner = useRef(scope); + owner.current = scope; + const mounted = useRef(false); + useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []); const created = useRef(null); const [error, setError] = useState(null); async function prepareWorkspace() { - created.current ??= await systemApi.createManagedServer({ - name: t.billing.workspaces.defaultName, - ...(checkoutIntent ? { idempotencyKey: checkoutIntent } : {}), - }); + if (created.current) return created.current.id; + // Reopening a modal must recover its unpaid space, not buy another one. + // Recover its saved payment directly, including processing payments. + const pending = await billingApi.listCheckouts(); + if (!mounted.current || owner.current !== scope) throw new Error("Purchase scope changed"); + const unfinished = pending.items.find(item => item.kind === "subscription"); + if (unfinished) { + created.current = unfinished.server; + return { workspaceId: unfinished.server.id, checkoutPending: true as const }; + } + const storageKey = `openship:cloud-purchase:${scope}`; + let key = checkoutIntent; + if (!key) { + try { key = sessionStorage.getItem(storageKey) ?? undefined; } + catch (error) { reportCaughtError(error, "dashboard/components/servers/managed/ManagedServerPurchase"); } + if (!isCloudPurchaseIntent(key)) key = randomUUID(); + try { sessionStorage.setItem(storageKey, key); } + catch (error) { reportCaughtError(error, "dashboard/components/servers/managed/ManagedServerPurchase"); } + } + const create = (idempotencyKey: string) => { + if (!mounted.current || owner.current !== scope) throw new Error("Purchase scope changed"); + return systemApi.createManagedServer({ name: t.billing.workspaces.defaultName, idempotencyKey }); + }; + let server: CloudWorkspaceSummary; + try { server = await create(key); } + catch (error) { + if (checkoutIntent || getApiErrorCode(error) !== "CLOUD_WORKSPACE_PURCHASE_REMOVED") throw error; + key = randomUUID(); + try { sessionStorage.setItem(storageKey, key); } + catch (error) { reportCaughtError(error, "dashboard/components/servers/managed/ManagedServerPurchase"); } + server = await create(key); + } + if (!checkoutIntent && (server.planTierId !== "free" || server.resources)) { + // The last purchase completed. This explicit Add space is a new purchase. + key = randomUUID(); + try { sessionStorage.setItem(storageKey, key); } + catch (error) { reportCaughtError(error, "dashboard/components/servers/managed/ManagedServerPurchase"); } + server = await create(key); + } + created.current = server; return created.current.id; } diff --git a/apps/dashboard/src/components/settings/ImageUrlEditor.test.tsx b/apps/dashboard/src/components/settings/ImageUrlEditor.test.tsx new file mode 100644 index 000000000..a865f71f8 --- /dev/null +++ b/apps/dashboard/src/components/settings/ImageUrlEditor.test.tsx @@ -0,0 +1,102 @@ +// @vitest-environment happy-dom +import { act, useState } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { I18nProvider } from "@/components/i18n-provider"; +import { ImageUrlEditor } from "./ImageUrlEditor"; + +let host: HTMLDivElement; +let root: Root; +const save = vi.fn(); +beforeEach(() => { + vi.resetAllMocks(); + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(false); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); +}); +afterEach(async () => { + await act(async () => root.unmount()); + host.remove(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +function Editor({ initial = null }: { initial?: string | null }) { + const [value, setValue] = useState(initial); + return ( + + { + await save(next); + setValue(next); + }} + /> + + ); +} +async function render(initial?: string) { + await act(async () => root.render()); +} +async function edit(value: string) { + await act(async () => { + const input = host.querySelector("input")!; + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); +} +async function submit() { + await act(async () => + host + .querySelector("form")! + .dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })), + ); +} + +it("previews and saves a trimmed image URL", async () => { + await render(); + await edit(" https://cdn.example.test/avatar.png "); + expect(host.querySelector("img")?.getAttribute("src")).toBe( + "https://cdn.example.test/avatar.png", + ); + expect(host.querySelector("img")?.getAttribute("referrerpolicy")).toBe("no-referrer"); + await submit(); + expect(save).toHaveBeenCalledWith("https://cdn.example.test/avatar.png"); + expect(host.querySelector('[role="status"]')?.textContent).toBe("Saved"); +}); + +it("rejects executable image schemes without loading or saving them", async () => { + await render(); + await edit("javascript:alert(1)"); + expect(host.querySelector("img")).toBeNull(); + await submit(); + expect(save).not.toHaveBeenCalled(); + expect(host.querySelector('[role="alert"]')?.textContent).toContain("HTTP or HTTPS"); +}); + +it("clears the saved override using the shared reset action", async () => { + await render("https://cdn.example.test/avatar.png"); + await act(async () => host.querySelector('button[type="button"]')!.click()); + expect(save).toHaveBeenCalledWith(null); + expect(host.querySelector("input")!.value).toBe(""); + expect(host.querySelector("img")).toBeNull(); +}); + +it("falls back for a broken image, retries a changed URL and preserves the draft on save failure", async () => { + await render("https://cdn.example.test/old.png"); + await act(async () => host.querySelector("img")!.dispatchEvent(new Event("error"))); + expect(host.querySelector("img")).toBeNull(); + await edit("https://cdn.example.test/new.png"); + expect(host.querySelector("img")?.getAttribute("src")).toBe("https://cdn.example.test/new.png"); + save.mockRejectedValueOnce(new Error("Permission denied")); + await submit(); + expect(host.querySelector("input")!.value).toBe("https://cdn.example.test/new.png"); + expect(host.querySelector('[role="alert"]')).not.toBeNull(); + expect(host.querySelector('button[type="submit"]')!.disabled).toBe(false); +}); diff --git a/apps/dashboard/src/components/settings/ImageUrlEditor.tsx b/apps/dashboard/src/components/settings/ImageUrlEditor.tsx new file mode 100644 index 000000000..d2e035f0a --- /dev/null +++ b/apps/dashboard/src/components/settings/ImageUrlEditor.tsx @@ -0,0 +1,143 @@ +"use client"; + +import { useEffect, useId, useState, type ReactNode } from "react"; +import { isImageUrl, MAX_IMAGE_URL_LENGTH } from "@repo/core"; +import { useI18n } from "@/components/i18n-provider"; +import { Input } from "@/components/ui/input"; +import { useImageFallback } from "@/hooks/useImageFallback"; +import { getApiErrorMessage } from "@/lib/api/client"; + +/** Shared URL editor; saving never depends on a remote image probe. */ +export function ImageUrlEditor({ + value, + label, + hint, + resetLabel, + fallback, + onSave, +}: { + value: string | null | undefined; + label: string; + hint: string; + resetLabel: string; + fallback: ReactNode; + onSave: (url: string | null) => Promise; +}) { + const { t } = useI18n(); + const c = t.settings.imageUrl; + const id = useId(); + const [draft, setDraft] = useState(value ?? ""); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(""); + const [saved, setSaved] = useState(false); + useEffect(() => { + setDraft(value ?? ""); + }, [value]); + const trimmed = draft.trim(); + const preview = useImageFallback(isImageUrl(trimmed) ? trimmed : null); + const save = async (next: string | null) => { + if (saving) return; + if (next && !isImageUrl(next)) { + setError(c.invalid); + return; + } + setSaving(true); + setError(""); + setSaved(false); + try { + await onSave(next); + setDraft(next ?? ""); + setSaved(true); + } catch (failure) { + setError(getApiErrorMessage(failure, c.failed)); + } finally { + setSaving(false); + } + }; + return ( +

{ + event.preventDefault(); + void save(trimmed || null); + }} + className="space-y-3" + > +
+
+ {preview.showImage ? ( + + ) : ( + fallback + )} +
+
+ + { + setDraft(event.target.value); + setError(""); + setSaved(false); + }} + /> +
+
+

+ {hint} +

+ {isImageUrl(trimmed) && !preview.showImage && ( +

{c.previewFailed}

+ )} + {error && ( + + )} +
+ + {value && ( + + )} + {saved && ( + + {c.saved} + + )} +
+
+ ); +} diff --git a/apps/dashboard/src/components/settings/image-settings.test.tsx b/apps/dashboard/src/components/settings/image-settings.test.tsx new file mode 100644 index 000000000..3a5dd68c1 --- /dev/null +++ b/apps/dashboard/src/components/settings/image-settings.test.tsx @@ -0,0 +1,82 @@ +// @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 { I18nProvider } from "@/components/i18n-provider"; +import { ProfileSetting } from "@/app/(dashboard)/settings/_components/ProfileSetting"; +import { ProjectIconSetting } from "@/components/project-settings/ProjectIconSetting"; + +const h = vi.hoisted(() => ({ + profile: vi.fn(), + project: vi.fn(), + update: vi.fn(), + invalidate: vi.fn(), +})); +vi.mock("@/context/AuthContext", () => ({ + useAuth: () => ({ user: { name: "Ada", email: "ada@example.test", image: null } }), +})); +vi.mock("@/lib/auth-client", () => ({ authClient: { updateUser: h.profile } })); +vi.mock("@/context/ProjectSettingsContext", () => ({ + useProjectSettings: () => ({ + projectData: { id: "project-a", iconUrl: "https://cdn.example.test/old.png" }, + updateProjectData: h.update, + }), +})); +vi.mock("@/lib/api", () => ({ projectsApi: { update: h.project } })); +vi.mock("@/hooks/useProjectEndpoints", () => ({ invalidateProjectCaches: h.invalidate })); +let host: HTMLDivElement; +let root: Root; +beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + h.profile.mockResolvedValue({ data: { status: true }, error: null }); + h.project.mockImplementation(async (_id, data) => ({ data })); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); +}); +afterEach(async () => { + await act(async () => root.unmount()); + host.remove(); + vi.unstubAllGlobals(); +}); + +it("saves the avatar through the current user's existing auth update", async () => { + await act(async () => + root.render( + + + , + ), + ); + await act(async () => { + const input = host.querySelector("input")!; + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call( + input, + "https://cdn.example.test/avatar.png", + ); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + await act(async () => + host + .querySelector("form")! + .dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })), + ); + expect(h.profile).toHaveBeenCalledWith({ image: "https://cdn.example.test/avatar.png" }); +}); + +it("clears the single project icon field through existing settings", async () => { + await act(async () => + root.render( + + + , + ), + ); + await act(async () => host.querySelector('button[type="button"]')!.click()); + expect(h.project).toHaveBeenCalledWith("project-a", { iconUrl: null }); + expect(h.update).toHaveBeenCalledWith({ + iconUrl: null, + }); + expect(h.invalidate).toHaveBeenCalledWith("project-a"); +}); diff --git a/apps/dashboard/src/components/shared/ProjectIcon.tsx b/apps/dashboard/src/components/shared/ProjectIcon.tsx new file mode 100644 index 000000000..629e03763 --- /dev/null +++ b/apps/dashboard/src/components/shared/ProjectIcon.tsx @@ -0,0 +1,43 @@ +"use client"; + +import { AppLogo } from "@/components/AppLogo"; +import { useImageFallback } from "@/hooks/useImageFallback"; +import { ProjectStackIcon } from "./ProjectStackIcon"; + +/** One display order everywhere: project icon, catalog logo, then stack icon. */ +export function ProjectIcon({ + project, + appTemplateId, + className = "size-6", +}: { + project: { + iconUrl?: string | null; + framework?: string | null; + serviceDeploymentMode?: "single" | "services"; + }; + appTemplateId?: string | null; + className?: string; +}) { + const src = project.iconUrl; + const image = useImageFallback(src); + if (image.showImage) + return ( + + ); + if (appTemplateId) + return ; + return ( + + ); +} diff --git a/apps/dashboard/src/components/shared/ProjectStackIcon.test.tsx b/apps/dashboard/src/components/shared/ProjectStackIcon.test.tsx index dc5b314a9..6ebfdc608 100644 --- a/apps/dashboard/src/components/shared/ProjectStackIcon.test.tsx +++ b/apps/dashboard/src/components/shared/ProjectStackIcon.test.tsx @@ -67,10 +67,10 @@ describe("project and deployment icon identity", () => { expect(html).not.toContain("html5"); }); - it("keeps favicons ahead of the service-group fallback", () => { + it("keeps project icons ahead of the service-group fallback", () => { const html = renderToStaticMarkup( - + , ); expect(html).toContain('src="/site.ico"'); diff --git a/apps/dashboard/src/components/shared/ProjectStackIcon.tsx b/apps/dashboard/src/components/shared/ProjectStackIcon.tsx index 40d63c979..00d062b2a 100644 --- a/apps/dashboard/src/components/shared/ProjectStackIcon.tsx +++ b/apps/dashboard/src/components/shared/ProjectStackIcon.tsx @@ -4,7 +4,7 @@ import { isServicesFramework } from "@repo/core"; import { Icon } from "@repo/ui/icons"; import { getFrameworkConfig } from "@/components/import-project/Frameworks"; -/** Fallback identity after a catalog logo or favicon, shared by project rows +/** Fallback identity after a project icon or catalog logo, shared by project rows * and deployment history. A missing framework never implies a static site. */ export function ProjectStackIcon({ framework, diff --git a/apps/dashboard/src/components/sidebar.test.tsx b/apps/dashboard/src/components/sidebar.test.tsx index 406f34065..164291992 100644 --- a/apps/dashboard/src/components/sidebar.test.tsx +++ b/apps/dashboard/src/components/sidebar.test.tsx @@ -9,6 +9,8 @@ import { getActiveOrganizationId, setActiveOrganizationId } from "@/lib/api/clie import { useIssueCounts } from "@/hooks/useIssueCounts"; import { Sidebar } from "./sidebar"; import { SidebarLayoutProvider, useSidebarCollapseRequest } from "@/context/SidebarLayoutContext"; +import { DashboardPaymentsProvider, PendingCheckoutsProvider } from "./billing/PendingCheckoutsContext"; +import { invalidatePayments } from "@/lib/billing-events"; const mocks = vi.hoisted(() => ({ pathname: "/monitoring", @@ -18,6 +20,8 @@ const mocks = vi.hoisted(() => ({ feed: vi.fn(), organization: vi.fn(), projects: vi.fn(), + payments: vi.fn(), + management: vi.fn(), })); vi.mock("next/navigation", () => ({ usePathname: () => mocks.pathname, @@ -25,6 +29,7 @@ vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }), })); vi.mock("@/lib/auth-client", () => ({ + useSession: () => ({ data: { user: { id: "user-a" }, session: { activeOrganizationId: "org-a" } } }), authClient: { organization: { list: async () => ({ data: [] }), @@ -55,6 +60,8 @@ vi.mock("@/lib/api/client", async (original) => { if (path === "issues/summary") return mocks.summary(); if (path === "issues" || path === "issues?status=resolved") return mocks.feed(path); if (path === "projects/home") return mocks.projects(); + if (path === "billing/checkouts") return mocks.payments(); + if (path === "/billing/manage") return mocks.management(); throw new Error(`Unexpected GET ${path}`); }, }, @@ -74,6 +81,8 @@ beforeEach(() => { mocks.organization.mockResolvedValue({ data: { id: "org-a" } }); mocks.summary.mockResolvedValue({ data: counts }); mocks.projects.mockResolvedValue({ success: true, projects: [] }); + mocks.payments.mockResolvedValue({ data: { items: [] } }); + mocks.management.mockResolvedValue({ data: { pendingCheckout: false, subscription: null, change: null } }); host = document.createElement("div"); document.body.append(host); root = createRoot(host); @@ -115,18 +124,48 @@ it.each([ expect(mocks.projects).toHaveBeenCalledOnce(); }); -async function render(props: ComponentProps = {}) { +async function render(props: ComponentProps = {}, payments = false) { + const content = ; await act(async () => root.render( - - - - + {payments ? {content} : content} , ), ); } + +it("counts unpaid Cloud plans and Manage once in the sidebar and refreshes after payment changes", async () => { + mocks.cloudConnected = true; + mocks.payments.mockResolvedValue({ data: { items: [ + { id: "one", server: { id: "space-a" } }, + { id: "two", server: { id: "space-a" } }, + { id: "three", server: { id: "space-b" } }, + ] } }); + mocks.management.mockResolvedValue({ data: { pendingCheckout: true, subscription: null, change: null } }); + await render({}, true); + const link = () => host.querySelector('a[href="/billing"]')!; + expect(link().querySelector(".tabular-nums")?.textContent).toBe("3"); + expect(link().querySelector(".tabular-nums")?.className).toContain("text-danger"); + expect(link().getAttribute("aria-label")).toContain("Pending: 3"); + // The hub's nested provider reuses the organization-wide read. + expect(mocks.payments).toHaveBeenCalledOnce(); + await act(async () => sidebarToggle().click()); + expect(link().title).toContain("Pending: 3"); + expect(link().querySelector(".tabular-nums")?.textContent).toBe("3"); + mocks.payments.mockResolvedValue({ data: { items: [] } }); + mocks.management.mockResolvedValue({ data: { pendingCheckout: false, subscription: null, change: null } }); + await act(async () => invalidatePayments()); + expect(link().getAttribute("aria-label")).toBeNull(); + await act(async () => sidebarToggle().click()); + expect(link().querySelector(".tabular-nums")).toBeNull(); +}); + +it("does not request payment data on an installation disconnected from Cloud", async () => { + await render({}, true); + expect(mocks.payments).not.toHaveBeenCalled(); + expect(mocks.management).not.toHaveBeenCalled(); +}); const monitoring = () => host.querySelector('a[href="/monitoring"]')!; const badge = () => monitoring().querySelector(".tabular-nums"); const sidebarToggle = () => host.querySelector( diff --git a/apps/dashboard/src/components/sidebar.tsx b/apps/dashboard/src/components/sidebar.tsx index 3f3f315b4..009db0fe6 100644 --- a/apps/dashboard/src/components/sidebar.tsx +++ b/apps/dashboard/src/components/sidebar.tsx @@ -1,5 +1,7 @@ "use client"; +import { UserAvatar } from "@/components/ui/UserAvatar"; + import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics"; import { Icon as UiIcon } from "@repo/ui/icons"; @@ -22,6 +24,7 @@ import { projectsApi } from "@/lib/api"; import { useSidebarCollapse } from "@/hooks/useSidebarCollapse"; import { useSidebarLayout } from "@/context/SidebarLayoutContext"; import { useIssueCounts } from "@/hooks/useIssueCounts"; +import { usePendingCheckouts } from "@/components/billing/PendingCheckoutsContext"; import { countProjectCollections, getSidebarNavCountsRevision, subscribeSidebarNavCounts } from "@/lib/sidebar-nav-counts"; import { getMailNavSections, @@ -153,11 +156,13 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo const [switchingOrgId, setSwitchingOrgId] = useState(null); const hasMonitoring = navSections.some(({ items }) => items.some(({ key }) => key === "issues")); const issueCounts = useIssueCounts(orgsLoaded && hasMonitoring ? activeOrgId : undefined); + const payments = usePendingCheckouts(); const countFor = (key: string): number | null => { // Match Home's Needs attention card; available updates are advisories. if (key === "issues") return issueCounts ? issueCounts.outage + issueCounts.actionRequired : null; if (key === "projects" || key === "apps") return navCounts?.[key] ?? null; + if (key === "billing") return payments?.attentionCount ?? null; return null; }; @@ -373,18 +378,20 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo const { key, href, icon: Icon, labelSource } = item; const active = isNavItemActive(item, navPathname, currentTab); const count = countFor(key); - const issueLabel = + const attentionLabel = key === "issues" && count != null && count > 0 ? `${label(key, labelSource)}: ${count === 1 ? t.dashboard.home.oneIssue : interpolate(t.dashboard.home.manyIssues, { n: String(count) })}` - : undefined; + : key === "billing" && count != null && count > 0 + ? `${label(key, labelSource)}: ${interpolate(t.billing.pendingPayments.count, { count: String(count) })}` + : undefined; return ( @@ -392,10 +399,18 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo {!collapsed && ( {label(key, labelSource)} )} - {/* Hide zero/loading counts; keep issue counts in the collapsed label. */} - {!collapsed && count != null && count > 0 && ( + {/* Keep attention counts accessible when the rail is collapsed. */} + {(!collapsed || key === "billing") && count != null && count > 0 && ( {count} @@ -459,9 +474,11 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo title={collapsed ? activeOrg?.name : undefined} > {/* Org avatar / initial */} -
- {activeOrg?.name?.[0] ?? } -
+ {activeOrg?.id === `org_${user?.id}` ? : ( +
+ {activeOrg?.name?.[0] ?? } +
+ )} {!collapsed && ( <> @@ -550,9 +567,7 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo {/* Footer separator + signed-in-as + sign out */}
-
- {displayInitial} -
+

{displayName} @@ -599,9 +614,7 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo collapsed ? "justify-center" : "gap-3" }`} > -

- {displayInitial} -
+ {!collapsed && ( <> diff --git a/apps/dashboard/src/components/ui/UserAvatar.tsx b/apps/dashboard/src/components/ui/UserAvatar.tsx new file mode 100644 index 000000000..e398f65d7 --- /dev/null +++ b/apps/dashboard/src/components/ui/UserAvatar.tsx @@ -0,0 +1,37 @@ +"use client"; + +import { useImageFallback } from "@/hooks/useImageFallback"; +import { cn } from "@/lib/utils"; + +export function UserAvatar({ + image, + name, + className, +}: { + image?: string | null; + name: string; + className?: string; +}) { + const fallback = useImageFallback(image); + return ( + + {fallback.showImage ? ( + + ) : ( + name[0] || "?" + )} + + ); +} diff --git a/apps/dashboard/src/constants/mock.ts b/apps/dashboard/src/constants/mock.ts index a69bb41eb..91532d414 100644 --- a/apps/dashboard/src/constants/mock.ts +++ b/apps/dashboard/src/constants/mock.ts @@ -78,7 +78,7 @@ export interface Project { lifecycleOperation?: ProjectLifecycleOperation | null; /* ── Hosting info (enriched by API) ─────────────────────── */ - favicon?: string | null; + iconUrl?: string | null; deployTarget?: string | null; serverId?: string | null; serverName?: string | null; diff --git a/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx b/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx index a5ea2f0be..46973e557 100644 --- a/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx +++ b/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx @@ -107,8 +107,7 @@ it("discards server-rendered project settings and late services when the Cloud i it("does not open a checkout returned for a disconnected Cloud account", async () => { const old = deferred(); h.checkout.mockReturnValue(old.promise); - const popup = { close: vi.fn(), opener: null, location: { href: "about:blank" } }; - const open = vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window); + const open = vi.spyOn(window, "open").mockReturnValue(null); const started = vi.fn(); function Checkout() { const checkout = useCloudCheckout({ enabled: true, preserveProject: true, onCheckoutStarted: started }); @@ -121,8 +120,7 @@ it("does not open a checkout returned for a disconnected Cloud account", async ( await render("account-b", page); await act(async () => old.resolve({ data: { checkoutUrl: "https://checkout.stripe.com/old-account" } })); expect(host.textContent).toBe("Choose plan"); - expect(popup.location.href).toBe("about:blank"); - expect(popup.close).toHaveBeenCalledOnce(); + expect(open).not.toHaveBeenCalled(); expect(started).not.toHaveBeenCalled(); } finally { open.mockRestore(); } }); diff --git a/apps/dashboard/src/i18n/locales/ar/projectSettings.json b/apps/dashboard/src/i18n/locales/ar/projectSettings.json index 21e36d9ea..8ccbdf611 100644 --- a/apps/dashboard/src/i18n/locales/ar/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/ar/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "بايت", "emptyBodyHint": "يتطلب رمز الحالة هذا محتوى استجابة فارغًا.", "headersHint": "أضف ترويسات للتخزين المؤقت أو CORS أو غيرها." + }, + "icon": { + "label": "رابط أيقونة المشروع", + "hint": "استخدم رابط صورة HTTP أو HTTPS. امسحه لاستخدام الأيقونة الافتراضية.", + "reset": "استخدام الأيقونة الافتراضية" } } diff --git a/apps/dashboard/src/i18n/locales/ar/settings.json b/apps/dashboard/src/i18n/locales/ar/settings.json index 360545e81..7e6d02ff5 100644 --- a/apps/dashboard/src/i18n/locales/ar/settings.json +++ b/apps/dashboard/src/i18n/locales/ar/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "إيقاف الخدمة", "cancel": "إلغاء", "noReverseProxy": "لم يتم اكتشاف وكيل عكسي على هذا الجهاز." + }, + "imageUrl": { + "preview": "معاينة الصورة", + "invalid": "أدخل رابط صورة HTTP أو HTTPS بدون بيانات تسجيل دخول.", + "failed": "تعذّر حفظ رابط الصورة.", + "save": "حفظ", + "saving": "جارٍ الحفظ…", + "saved": "تم الحفظ", + "previewFailed": "المعاينة غير متاحة. تأكد أن الرابط يشير مباشرةً إلى صورة." + }, + "profile": { + "title": "الملف الشخصي", + "description": "صورة حسابك الشخصي.", + "label": "رابط الصورة الشخصية", + "hint": "استخدم رابط صورة مباشرًا. اتركه فارغًا لاستخدام الحرف الأول من اسمك.", + "reset": "استخدام الحرف الأول" } } diff --git a/apps/dashboard/src/i18n/locales/de/projectSettings.json b/apps/dashboard/src/i18n/locales/de/projectSettings.json index b21c553ec..427e82fc1 100644 --- a/apps/dashboard/src/i18n/locales/de/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/de/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "Bytes", "emptyBodyHint": "Dieser Status erfordert einen leeren Antwortinhalt.", "headersHint": "Cache-, CORS- oder andere Antwortheader hinzufügen." + }, + "icon": { + "label": "URL des Projektsymbols", + "hint": "Verwende eine HTTP- oder HTTPS-Bild-URL. Leere sie, um das Standardsymbol zu verwenden.", + "reset": "Standardsymbol verwenden" } } diff --git a/apps/dashboard/src/i18n/locales/de/settings.json b/apps/dashboard/src/i18n/locales/de/settings.json index 2a500160e..296a00e59 100644 --- a/apps/dashboard/src/i18n/locales/de/settings.json +++ b/apps/dashboard/src/i18n/locales/de/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "Bereitstellung stoppen", "cancel": "Abbrechen", "noReverseProxy": "Auf dieser Maschine wurde kein Reverse-Proxy erkannt." + }, + "imageUrl": { + "preview": "Bildvorschau", + "invalid": "Gib eine HTTP- oder HTTPS-Bild-URL ohne Zugangsdaten ein.", + "failed": "Die Bild-URL konnte nicht gespeichert werden.", + "save": "Speichern", + "saving": "Wird gespeichert…", + "saved": "Gespeichert", + "previewFailed": "Keine Vorschau verfügbar. Prüfe, ob die URL direkt auf ein Bild verweist." + }, + "profile": { + "title": "Profil", + "description": "Das Bild deines persönlichen Kontos.", + "label": "Avatar-URL", + "hint": "Verwende eine direkte Bild-URL. Leer lassen, um deinen Anfangsbuchstaben anzuzeigen.", + "reset": "Anfangsbuchstaben verwenden" } } diff --git a/apps/dashboard/src/i18n/locales/en/billing.json b/apps/dashboard/src/i18n/locales/en/billing.json index 922850fa5..e1eb92f67 100644 --- a/apps/dashboard/src/i18n/locales/en/billing.json +++ b/apps/dashboard/src/i18n/locales/en/billing.json @@ -334,7 +334,7 @@ "upgradeDescription": "Choose a plan with enough capacity, or adjust your project and try again.", "manageBilling": "Manage billing", "topups": "Add usage", - "checkoutOpened": "Checkout is ready in a separate tab. If it did not open, use the link below.", + "checkoutOpened": "Complete your payment in secure checkout. If it did not open, use the button below.", "continueCheckout": "Continue to checkout", "reasons": { "static-only": "Your plan does not include this type of app. Choose a plan that supports it to deploy.", diff --git a/apps/dashboard/src/i18n/locales/en/projectSettings.json b/apps/dashboard/src/i18n/locales/en/projectSettings.json index 09e2bf804..283ddea15 100644 --- a/apps/dashboard/src/i18n/locales/en/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/en/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "bytes", "emptyBodyHint": "This status requires an empty response body.", "headersHint": "Add cache, CORS, or other response headers." + }, + "icon": { + "label": "Project icon URL", + "hint": "Use an HTTP or HTTPS image URL. Clear it to use the default icon.", + "reset": "Use default icon" } } diff --git a/apps/dashboard/src/i18n/locales/en/settings.json b/apps/dashboard/src/i18n/locales/en/settings.json index 77286e291..ff151942c 100644 --- a/apps/dashboard/src/i18n/locales/en/settings.json +++ b/apps/dashboard/src/i18n/locales/en/settings.json @@ -1791,5 +1791,21 @@ "title": "Demo mode", "description": "Blur IP addresses, hosts, and environment values during screen-shares and recordings." } + }, + "imageUrl": { + "preview": "Image preview", + "invalid": "Enter an HTTP or HTTPS image URL without embedded credentials.", + "failed": "Could not save the image URL.", + "save": "Save", + "saving": "Saving…", + "saved": "Saved", + "previewFailed": "Preview unavailable. Check that the URL points directly to an image." + }, + "profile": { + "title": "Profile", + "description": "Your personal account image.", + "label": "Avatar URL", + "hint": "Use a direct image URL. Leave empty to use your initial.", + "reset": "Use initial" } } diff --git a/apps/dashboard/src/i18n/locales/es/projectSettings.json b/apps/dashboard/src/i18n/locales/es/projectSettings.json index e7e7bfe01..fd96834e2 100644 --- a/apps/dashboard/src/i18n/locales/es/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/es/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "bytes", "emptyBodyHint": "Este estado requiere un cuerpo de respuesta vacío.", "headersHint": "Añade cabeceras de caché, CORS u otras." + }, + "icon": { + "label": "URL del icono del proyecto", + "hint": "Usa una URL de imagen HTTP o HTTPS. Bórrala para usar el icono predeterminado.", + "reset": "Usar icono predeterminado" } } diff --git a/apps/dashboard/src/i18n/locales/es/settings.json b/apps/dashboard/src/i18n/locales/es/settings.json index 3ab15e30e..0d2c5871c 100644 --- a/apps/dashboard/src/i18n/locales/es/settings.json +++ b/apps/dashboard/src/i18n/locales/es/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "Dejar de servir", "cancel": "Cancelar", "noReverseProxy": "No se detectó ningún proxy inverso en esta máquina." + }, + "imageUrl": { + "preview": "Vista previa de la imagen", + "invalid": "Introduce una URL HTTP o HTTPS sin credenciales.", + "failed": "No se pudo guardar la URL de la imagen.", + "save": "Guardar", + "saving": "Guardando…", + "saved": "Guardado", + "previewFailed": "Vista previa no disponible. Comprueba que la URL enlace directamente a una imagen." + }, + "profile": { + "title": "Perfil", + "description": "La imagen de tu cuenta personal.", + "label": "URL del avatar", + "hint": "Usa una URL directa de imagen. Déjala vacía para mostrar tu inicial.", + "reset": "Usar inicial" } } diff --git a/apps/dashboard/src/i18n/locales/fr/projectSettings.json b/apps/dashboard/src/i18n/locales/fr/projectSettings.json index df9987abb..af9bb4454 100644 --- a/apps/dashboard/src/i18n/locales/fr/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/fr/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "octets", "emptyBodyHint": "Ce statut nécessite un corps de réponse vide.", "headersHint": "Ajoutez des en-têtes de cache, CORS ou autres." + }, + "icon": { + "label": "URL de l’icône du projet", + "hint": "Utilisez une URL d’image HTTP ou HTTPS. Effacez-la pour utiliser l’icône par défaut.", + "reset": "Utiliser l’icône par défaut" } } diff --git a/apps/dashboard/src/i18n/locales/fr/settings.json b/apps/dashboard/src/i18n/locales/fr/settings.json index 4a43b3d39..5614429ab 100644 --- a/apps/dashboard/src/i18n/locales/fr/settings.json +++ b/apps/dashboard/src/i18n/locales/fr/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "Cesser de servir", "cancel": "Annuler", "noReverseProxy": "Aucun proxy inverse détecté sur cette machine." + }, + "imageUrl": { + "preview": "Aperçu de l’image", + "invalid": "Saisissez une URL HTTP ou HTTPS sans identifiants.", + "failed": "Impossible d’enregistrer l’URL de l’image.", + "save": "Enregistrer", + "saving": "Enregistrement…", + "saved": "Enregistré", + "previewFailed": "Aperçu indisponible. Vérifiez que l’URL pointe directement vers une image." + }, + "profile": { + "title": "Profil", + "description": "L’image de votre compte personnel.", + "label": "URL de l’avatar", + "hint": "Utilisez une URL directe d’image. Laissez vide pour afficher votre initiale.", + "reset": "Utiliser l’initiale" } } diff --git a/apps/dashboard/src/i18n/locales/ja/projectSettings.json b/apps/dashboard/src/i18n/locales/ja/projectSettings.json index 1829beee8..17f63ef7a 100644 --- a/apps/dashboard/src/i18n/locales/ja/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/ja/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "バイト", "emptyBodyHint": "このステータスではレスポンス本文を空にする必要があります。", "headersHint": "キャッシュ、CORSなどのレスポンスヘッダーを追加します。" + }, + "icon": { + "label": "プロジェクトアイコンの URL", + "hint": "HTTP または HTTPS の画像 URL を指定してください。空にすると既定のアイコンに戻ります。", + "reset": "既定のアイコンを使用" } } diff --git a/apps/dashboard/src/i18n/locales/ja/settings.json b/apps/dashboard/src/i18n/locales/ja/settings.json index 9394731c4..db135bb68 100644 --- a/apps/dashboard/src/i18n/locales/ja/settings.json +++ b/apps/dashboard/src/i18n/locales/ja/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "配信を停止", "cancel": "キャンセル", "noReverseProxy": "このマシンでリバースプロキシが検出されませんでした。" + }, + "imageUrl": { + "preview": "画像プレビュー", + "invalid": "認証情報を含まない HTTP または HTTPS の画像 URL を入力してください。", + "failed": "画像 URL を保存できませんでした。", + "save": "保存", + "saving": "保存中…", + "saved": "保存しました", + "previewFailed": "プレビューを表示できません。画像の直接 URL か確認してください。" + }, + "profile": { + "title": "プロフィール", + "description": "個人アカウントの画像。", + "label": "アバター URL", + "hint": "画像の直接 URL を使用します。空欄にすると名前の頭文字を表示します。", + "reset": "頭文字を使用" } } diff --git a/apps/dashboard/src/i18n/locales/pt/projectSettings.json b/apps/dashboard/src/i18n/locales/pt/projectSettings.json index b27f511cf..a3ca74b0a 100644 --- a/apps/dashboard/src/i18n/locales/pt/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/pt/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "bytes", "emptyBodyHint": "Este estado exige um corpo de resposta vazio.", "headersHint": "Adicione cabeçalhos de cache, CORS ou outros." + }, + "icon": { + "label": "URL do ícone do projeto", + "hint": "Use uma URL de imagem HTTP ou HTTPS. Limpe-a para usar o ícone padrão.", + "reset": "Usar ícone padrão" } } diff --git a/apps/dashboard/src/i18n/locales/pt/settings.json b/apps/dashboard/src/i18n/locales/pt/settings.json index 3fa1a6087..883f9ab06 100644 --- a/apps/dashboard/src/i18n/locales/pt/settings.json +++ b/apps/dashboard/src/i18n/locales/pt/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "Parar de servir", "cancel": "Cancelar", "noReverseProxy": "Nenhum proxy reverso detectado nesta máquina." + }, + "imageUrl": { + "preview": "Prévia da imagem", + "invalid": "Insira uma URL HTTP ou HTTPS sem credenciais.", + "failed": "Não foi possível salvar a URL da imagem.", + "save": "Salvar", + "saving": "Salvando…", + "saved": "Salvo", + "previewFailed": "Prévia indisponível. Verifique se a URL aponta diretamente para uma imagem." + }, + "profile": { + "title": "Perfil", + "description": "A imagem da sua conta pessoal.", + "label": "URL do avatar", + "hint": "Use uma URL direta de imagem. Deixe em branco para usar sua inicial.", + "reset": "Usar inicial" } } diff --git a/apps/dashboard/src/i18n/locales/ru/projectSettings.json b/apps/dashboard/src/i18n/locales/ru/projectSettings.json index 80843ddf0..444152582 100644 --- a/apps/dashboard/src/i18n/locales/ru/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/ru/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "байт", "emptyBodyHint": "Этот статус требует пустого тела ответа.", "headersHint": "Добавьте заголовки кеширования, CORS или другие." + }, + "icon": { + "label": "URL значка проекта", + "hint": "Укажите HTTP- или HTTPS-ссылку на изображение. Очистите её, чтобы использовать значок по умолчанию.", + "reset": "Стандартный значок" } } diff --git a/apps/dashboard/src/i18n/locales/ru/settings.json b/apps/dashboard/src/i18n/locales/ru/settings.json index 59cb29a08..1ee579392 100644 --- a/apps/dashboard/src/i18n/locales/ru/settings.json +++ b/apps/dashboard/src/i18n/locales/ru/settings.json @@ -1791,5 +1791,21 @@ "title": "Демо-режим", "description": "Размывать IP-адреса, хосты и переменные окружения при показе экрана и записи видео." } + }, + "imageUrl": { + "preview": "Предпросмотр изображения", + "invalid": "Введите HTTP- или HTTPS-адрес изображения без учётных данных.", + "failed": "Не удалось сохранить адрес изображения.", + "save": "Сохранить", + "saving": "Сохранение…", + "saved": "Сохранено", + "previewFailed": "Предпросмотр недоступен. Проверьте, что URL ведёт прямо к изображению." + }, + "profile": { + "title": "Профиль", + "description": "Изображение вашего личного аккаунта.", + "label": "URL аватара", + "hint": "Укажите прямую ссылку на изображение. Оставьте поле пустым, чтобы показать инициал.", + "reset": "Использовать инициал" } } diff --git a/apps/dashboard/src/i18n/locales/tr/projectSettings.json b/apps/dashboard/src/i18n/locales/tr/projectSettings.json index b81cee71b..9f55585ea 100644 --- a/apps/dashboard/src/i18n/locales/tr/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/tr/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "bayt", "emptyBodyHint": "Bu durum kodu boş bir yanıt gövdesi gerektirir.", "headersHint": "Önbellek, CORS veya diğer yanıt başlıklarını ekleyin." + }, + "icon": { + "label": "Proje simgesi URL’si", + "hint": "HTTP veya HTTPS resim URL’si kullanın. Varsayılan simgeyi kullanmak için URL’yi temizleyin.", + "reset": "Varsayılan simgeyi kullan" } } diff --git a/apps/dashboard/src/i18n/locales/tr/settings.json b/apps/dashboard/src/i18n/locales/tr/settings.json index 343010e85..563cf2944 100644 --- a/apps/dashboard/src/i18n/locales/tr/settings.json +++ b/apps/dashboard/src/i18n/locales/tr/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "Sunmayı durdur", "cancel": "İptal", "noReverseProxy": "Bu makinede ters proxy algılanmadı." + }, + "imageUrl": { + "preview": "Resim önizlemesi", + "invalid": "Kimlik bilgisi içermeyen bir HTTP veya HTTPS resim URL’si girin.", + "failed": "Resim URL’si kaydedilemedi.", + "save": "Kaydet", + "saving": "Kaydediliyor…", + "saved": "Kaydedildi", + "previewFailed": "Önizleme kullanılamıyor. URL’nin doğrudan bir resme yöneldiğini kontrol edin." + }, + "profile": { + "title": "Profil", + "description": "Kişisel hesabınızın resmi.", + "label": "Avatar URL’si", + "hint": "Doğrudan bir resim URL’si kullanın. Baş harfiniz için boş bırakın.", + "reset": "Baş harfi kullan" } } diff --git a/apps/dashboard/src/i18n/locales/zh/projectSettings.json b/apps/dashboard/src/i18n/locales/zh/projectSettings.json index 8d912db95..ab52939d9 100644 --- a/apps/dashboard/src/i18n/locales/zh/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/zh/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "字节", "emptyBodyHint": "此状态码要求响应正文为空。", "headersHint": "添加缓存、CORS 或其他响应标头。" + }, + "icon": { + "label": "项目图标 URL", + "hint": "使用 HTTP 或 HTTPS 图片 URL。清空后将使用默认图标。", + "reset": "使用默认图标" } } diff --git a/apps/dashboard/src/i18n/locales/zh/settings.json b/apps/dashboard/src/i18n/locales/zh/settings.json index 753bd8f2a..682c418c8 100644 --- a/apps/dashboard/src/i18n/locales/zh/settings.json +++ b/apps/dashboard/src/i18n/locales/zh/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "停止服务", "cancel": "取消", "noReverseProxy": "在此机器上未检测到反向代理。" + }, + "imageUrl": { + "preview": "图片预览", + "invalid": "请输入不含凭据的 HTTP 或 HTTPS 图片 URL。", + "failed": "无法保存图片 URL。", + "save": "保存", + "saving": "正在保存…", + "saved": "已保存", + "previewFailed": "无法预览。请检查 URL 是否直接指向图片。" + }, + "profile": { + "title": "个人资料", + "description": "你的个人账户图片。", + "label": "头像 URL", + "hint": "使用图片的直接 URL。留空则显示姓名首字母。", + "reset": "使用首字母" } } diff --git a/apps/dashboard/src/lib/api/connections.ts b/apps/dashboard/src/lib/api/connections.ts index 54c2c54a1..58e3e6043 100644 --- a/apps/dashboard/src/lib/api/connections.ts +++ b/apps/dashboard/src/lib/api/connections.ts @@ -1,3 +1,4 @@ +import type { ProjectConnectionCandidate } from "@repo/contracts"; import { api } from "./client"; import { endpoints } from "./endpoints"; @@ -48,15 +49,7 @@ async function notifyConnections(request: Promise): Promise { export const connectionsApi = { candidates: (projectId: string) => - api.get<{ - data: Array<{ - id: string; - name: string; - description: string; - appTemplateId: string | null; - clusterId?: string | null; - }>; - }>(`${endpoints.projects.connections(projectId)}/candidates`), + api.get<{ data: ProjectConnectionCandidate[] }>(`${endpoints.projects.connections(projectId)}/candidates`), /** Connections wired INTO a project (`projectId` = the consumer). */ list: (projectId: string) => api.get<{ data: ProjectConnection[] }>(endpoints.projects.connections(projectId)), diff --git a/apps/dashboard/src/lib/api/management.ts b/apps/dashboard/src/lib/api/management.ts index 09e72d1c6..96897fa95 100644 --- a/apps/dashboard/src/lib/api/management.ts +++ b/apps/dashboard/src/lib/api/management.ts @@ -1,8 +1,11 @@ import type { BillingOperations } from "@repo/contracts"; import { api } from "./client"; +import { invalidatePayments } from "@/lib/billing-events"; type Result = Awaited>; -const post = async (path: string, body?: unknown) => - (await api.post<{ data: Result }>(`/billing/manage/${path}`, body)).data; +const post = async (path: string, body?: unknown) => { + try { return (await api.post<{ data: Result }>(`/billing/manage/${path}`, body)).data; } + finally { invalidatePayments(); } +}; export const managementApi = { get: async () => (await api.get<{ data: Result<"getManagement"> }>("/billing/manage")).data, purchase: (input: Parameters[0]) => diff --git a/apps/dashboard/src/lib/billing-events.ts b/apps/dashboard/src/lib/billing-events.ts new file mode 100644 index 000000000..6b75dfafb --- /dev/null +++ b/apps/dashboard/src/lib/billing-events.ts @@ -0,0 +1,6 @@ +export const PAYMENTS_CHANGED = "openship:payments-changed"; + +/** Refresh payment warnings after mutations, including uncertain responses. */ +export function invalidatePayments() { + window.dispatchEvent(new Event(PAYMENTS_CHANGED)); +} diff --git a/apps/dashboard/src/lib/checkout-navigation.test.ts b/apps/dashboard/src/lib/checkout-navigation.test.ts new file mode 100644 index 000000000..d9dcf1cd1 --- /dev/null +++ b/apps/dashboard/src/lib/checkout-navigation.test.ts @@ -0,0 +1,42 @@ +// @vitest-environment happy-dom +import { afterEach, expect, it, vi } from "vitest"; +import { navigateToCheckout } from "./checkout-navigation"; + +const diagnostics = vi.hoisted(() => ({ report: vi.fn() })); +vi.mock("@repo/core/diagnostics", () => ({ reportCaughtError: diagnostics.report })); + +afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks(); }); + +it.each(["javascript:alert(1)", "data:text/html,checkout", "http://checkout.example.test", ""])( + "refuses an invalid payment destination before opening a tab: %s", value => { + const open = vi.spyOn(window, "open"); + const before = window.location.href; + expect(() => navigateToCheckout(value, true)).toThrow(); + expect(open).not.toHaveBeenCalled(); + expect(window.location.href).toBe(before); + }, +); + +it("opens only the final URL without an opener or referrer, preserving the project", () => { + const open = vi.spyOn(window, "open").mockReturnValue(null); + const before = window.location.href; + expect(navigateToCheckout("https://checkout.example.test/session", true)).toBe("https://checkout.example.test/session"); + expect(open).toHaveBeenCalledExactlyOnceWith("https://checkout.example.test/session", "_blank", "noopener,noreferrer"); + expect(window.location.href).toBe(before); +}); + +it("retains the validated fallback URL if the browser throws when refusing a popup", () => { + vi.spyOn(window, "open").mockImplementation(() => { throw new Error("Popups refused: https://checkout.example.test/private-session"); }); + expect(navigateToCheckout("https://checkout.example.test/session", true)).toBe("https://checkout.example.test/session"); + expect(diagnostics.report).toHaveBeenCalledExactlyOnceWith(expect.any(Error), "dashboard/lib/checkout-navigation"); + const reported = diagnostics.report.mock.calls[0][0] as Error; + expect(reported.message).toBe("Browser refused to open hosted checkout"); + expect(reported.message).not.toContain("private-session"); +}); + +it("uses the existing tab when there is no project draft to preserve", () => { + const open = vi.spyOn(window, "open"); + navigateToCheckout("https://checkout.example.test/session", false); + expect(window.location.href).toBe("https://checkout.example.test/session"); + expect(open).not.toHaveBeenCalled(); +}); diff --git a/apps/dashboard/src/lib/checkout-navigation.ts b/apps/dashboard/src/lib/checkout-navigation.ts index 2d73fd312..7c13e84bf 100644 --- a/apps/dashboard/src/lib/checkout-navigation.ts +++ b/apps/dashboard/src/lib/checkout-navigation.ts @@ -1,19 +1,18 @@ -/** Reserve a tab inside the user's click so payment never discards a draft. - * The API validates hosted-payment URLs; blocked popups retain a manual link. */ -export function beginCheckoutNavigation(preserveProject: boolean) { - const tab = preserveProject ? window.open("about:blank", "_blank") : null; - if (tab) tab.opener = null; - return { - close: () => tab?.close(), - navigate(value: string) { - const url = new URL(value); - if (url.protocol !== "https:") throw new Error("Invalid checkout URL"); - if (preserveProject) { - if (tab && !tab.closed) tab.location.href = url.href; - } else { - window.location.href = url.href; - } - return url.href; - }, - }; +import { reportCaughtError } from "@repo/core/diagnostics"; + +/** The API validates payment hosts. Open only its final HTTPS URL. + * Blocked popups retain the visible checkout + * action; failed requests never leave blank tabs or discard project drafts. */ +export function navigateToCheckout(value: string, preserveProject: boolean) { + const url = new URL(value); + if (url.protocol !== "https:") throw new Error("Invalid checkout URL"); + if (preserveProject) { + try { window.open(url.href, "_blank", "noopener,noreferrer"); } + catch { + // Browser errors can embed the payment URL. Report no hosted-session data. + reportCaughtError(new Error("Browser refused to open hosted checkout"), "dashboard/lib/checkout-navigation"); + // Keep the validated manual action available when popups are refused. + } + } else window.location.href = url.href; + return url.href; } diff --git a/apps/dashboard/src/proxy.test.ts b/apps/dashboard/src/proxy.test.ts index 6746ee9ea..59b96828a 100644 --- a/apps/dashboard/src/proxy.test.ts +++ b/apps/dashboard/src/proxy.test.ts @@ -1,8 +1,17 @@ import { describe, expect, it } from "vitest"; import { NextRequest } from "next/server"; -import { proxy } from "./proxy"; +import { unstable_doesMiddlewareMatch } from "next/experimental/testing/server"; +import { config, proxy } from "./proxy"; describe("dashboard proxy middleware", () => { + it.each(["/api", "/api/proxy/api/projects/folder/upload/session", "/api/auth/sign-in/email", "/api/mcp"])( + "does not buffer API request bodies through middleware: %s", (url) => { + expect(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url })).toBe(false); + }, + ); + it.each(["/projects", "/login", "/api-docs"])("still matches page requests: %s", (url) => { + expect(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url })).toBe(true); + }); it("mirrors a valid theme cookie for the initial server render", () => { const response = proxy(new NextRequest("https://app.openship.io/login", { headers: { cookie: "openship-theme=system:dim", "x-openship-theme": "light:light" }, diff --git a/apps/dashboard/src/proxy.ts b/apps/dashboard/src/proxy.ts index 0801bfe61..66af7a4f9 100644 --- a/apps/dashboard/src/proxy.ts +++ b/apps/dashboard/src/proxy.ts @@ -90,5 +90,7 @@ export function proxy(req: NextRequest) { } export const config = { - matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\..*).*)"], + // API routes authenticate in the API process. Matching them here makes Next + // clone/buffer uploads, truncating the stream at its middleware body limit. + matcher: ["/((?!api(?:/|$)|_next/static|_next/image|favicon.ico|.*\\..*).*)"], }; diff --git a/apps/web/content/docs/cli/projects.mdx b/apps/web/content/docs/cli/projects.mdx index 09a290981..3951622bd 100644 --- a/apps/web/content/docs/cli/projects.mdx +++ b/apps/web/content/docs/cli/projects.mdx @@ -86,11 +86,17 @@ command, build settings, routing, ports and enabled state. ```bash openship domain add app.example.com --project proj_123 +# Multi-service project: choose a service and its container port. +openship domain add api.example.com --project proj_123 --service api --port 3000 openship domain records dom_123 openship domain verify dom_123 openship domain verify-ssl dom_123 ``` +Target validation happens before the hostname is claimed. The selected project or service keeps its +existing endpoints; the new domain becomes routable on the next deployment. A multi-service project +requires `--service`; services with several ports also require `--port`. + Follow the returned DNS instructions before verification. See [domain options](/docs/cli/reference/domain) and the [custom-domain guide](/docs/guides/custom-domains) for DNS providers, TLS, and primary domains. diff --git a/apps/web/content/docs/cli/reference/domain/index.mdx b/apps/web/content/docs/cli/reference/domain/index.mdx index ec444896c..99a5c4ee2 100644 --- a/apps/web/content/docs/cli/reference/domain/index.mdx +++ b/apps/web/content/docs/cli/reference/domain/index.mdx @@ -47,6 +47,8 @@ openship domain add [options] | --- | --- | | `-p, --project ` | Project ID to attach the domain to | | `--primary` | Mark this domain as the project's primary (default: false) | +| `--service ` | Target service within the selected project | +| `--port ` | Container port to route (required for ambiguous service ports) | ## openship domain get diff --git a/apps/web/content/docs/dashboard/projects.mdx b/apps/web/content/docs/dashboard/projects.mdx index c616684dc..cb456e05f 100644 --- a/apps/web/content/docs/dashboard/projects.mdx +++ b/apps/web/content/docs/dashboard/projects.mdx @@ -13,7 +13,7 @@ its management tabs). Open **Projects** from the left nav. This screen is a single scannable list of every project in your workspace — one row per project. -Each row shows, left to right: the app's icon (its favicon, or the framework logo), the **name** +Each row shows, left to right: the project icon (set in **Settings → Project Info**), or its app/framework logo, the **name** and its live version badge, the primary **domain**, the detected **framework**, where it's hosted (**Cloud**, a **Server** by name, or **Local**), its source (a GitHub repo or a local folder), the build shape (**Services**, **Static**, or **Standalone**), how long ago it changed, and a diff --git a/bun.lock b/bun.lock index 38011b2f5..abd3f92cd 100644 --- a/bun.lock +++ b/bun.lock @@ -221,7 +221,7 @@ "ignore": "^7.0.5", "ioredis": "^5.10.0", "ipaddr.js": "^2.4.0", - "oblien": "2.10.0", + "oblien": "3.0.2", "ssh2": "^1.17.0", "tar-fs": "^2.1.4", "undici": "^7.30.2", @@ -2732,7 +2732,7 @@ "object.assign": ["object.assign@4.1.7", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0", "has-symbols": "^1.1.0", "object-keys": "^1.1.1" } }, "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw=="], - "oblien": ["oblien@2.10.0", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.27.1", "ws": "^8.18.3" }, "bin": { "oblien": "dist/cli/index.js", "oblien-mcp": "dist/mcp/index.js" } }, "sha512-ESdeDWuIJ+R0fJtTjHAhU1VRGOqjUtxqMZeL3sm2AgkI4/1nf1FjrqKvha2zsd9nfkbzpJuYwzOOOtQUdhv1hQ=="], + "oblien": ["oblien@3.0.2", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.27.1", "ws": "^8.18.3" }, "bin": { "oblien": "dist/cli/index.js", "oblien-mcp": "dist/mcp/index.js" } }, "sha512-f2hP0e9ujrL/H7eCP7mwAlnpmVa7OSDEgQGFEjwEXaSZUYJlBUwcZx+MPsTU3RNjlRj1tVpCRSa9PT3qi8zkNA=="], "obug": ["obug@2.2.1", "", {}, "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q=="], @@ -3892,6 +3892,8 @@ "micromatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="], + "mindwire/oblien": ["oblien@2.10.0", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.27.1", "ws": "^8.18.3" }, "bin": { "oblien": "dist/cli/index.js", "oblien-mcp": "dist/mcp/index.js" } }, "sha512-ESdeDWuIJ+R0fJtTjHAhU1VRGOqjUtxqMZeL3sm2AgkI4/1nf1FjrqKvha2zsd9nfkbzpJuYwzOOOtQUdhv1hQ=="], + "minipass-collect/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], "minipass-fetch/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="], @@ -4216,6 +4218,8 @@ "bytesmap/better-auth/jose": ["jose@6.2.13", "", {}, "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ=="], + "bytesmap/mindwire/oblien": ["oblien@2.10.0", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.27.1", "ws": "^8.18.3" }, "bin": { "oblien": "dist/cli/index.js", "oblien-mcp": "dist/mcp/index.js" } }, "sha512-ESdeDWuIJ+R0fJtTjHAhU1VRGOqjUtxqMZeL3sm2AgkI4/1nf1FjrqKvha2zsd9nfkbzpJuYwzOOOtQUdhv1hQ=="], + "cacache/glob/minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="], "cacache/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="], diff --git a/docs/dashboard-design.md b/docs/dashboard-design.md index c71a2d330..b7a1b30f8 100644 --- a/docs/dashboard-design.md +++ b/docs/dashboard-design.md @@ -5,6 +5,13 @@ and a consistent type hierarchy across light, dim, and dark themes. ## Surfaces and controls +Personal avatar URLs live in Settings → General → Profile. Project icon URLs live +in the Project Info card in project Settings. Both use the shared URL editor with +a preview and a reset action. Each project has one `iconUrl`; project, app, connection +and deployment lists use the same renderer. Clearing the URL restores the catalog +logo or framework/service icon. Image URLs are displayed directly by the browser +with no referrer; the control plane does not fetch them or discover favicons. + Assistant settings belong in **Settings → Assistant**; event-driven flows and run history open from **Automations** in the AI Agents right column. Keep the conversation free of view tabs, with an AI Agents return action on the automations page. @@ -509,6 +516,8 @@ Instance relocation has one entry in **Settings → Instance → Instance locati the control plane, connecting a Desktop, and backup/archive recovery distinct. Reuse the shared server selector and option cards for API-only versus API + dashboard. Show progress and recovery in the same card; do not add another direct-transfer or Team migration wizard. +During server preparation, View deployment opens the saved build view. Hide that action +while the source is fenced for transfer, when ordinary deployment reads are unavailable. Keep **Connect to an existing instance** and **Move to a server** visible on Desktop. A connected Desktop shows **Reconnect** and **Move back to Desktop**. An active server shows **Connect a Desktop**, **Move to another server**, and **Move to Desktop**. @@ -876,6 +885,14 @@ check retryable before starting the move. cancellation actions in the selected server's billing card, preserve retry identity after uncertain responses, and never replace the page with a loader. - Checkout returns verify payment, paid coverage and managed-server readiness separately. + Open the hosted URL only after checkout is ready; never reserve an empty browser tab. + Keep a full-width primary checkout action visible if the browser refuses the popup, + and preserve the project draft. Lock repeat submissions after a successful handoff. + Reopening Add Cloud space recovers an unfinished subscription before creating another + space; manual retries retain a customer-scoped creation key across modal dismissal. + Plans & billing shows a warning count for pending Cloud plans and Manage payment. + Reuse the organization-wide payment read in the hub and refresh warnings after mutations + and on return from checkout. Hide zero counts and reset private state on scope changes. Show the subscription welcome only when setup is complete. Keep preparation and failure notices compact and above the billing columns, with a recheck action and a link to the existing server Activity tab for logs and retry. A paid setup failure must never direct the customer to pay again. @@ -1055,9 +1072,11 @@ from an existing run. Keep loading, fetch errors and empty inventory distinct, a the selected destination's validation and transfer review before enabling Migrate. Platform imports share three steps: Connect, Select services, and Review & import. Show -one destination project for each source project, with its selected services and private -connections kept together. Name the project once in the destination sidebar; service cards -edit service names. Review and progress link to that project without repeating it for each service. +one destination project when the source services share a compatible Git checkout. Environments +with multiple repositories, branches or revisions create a project per service, connected privately +on the same destination server. Show each destination name in review and the project count in its +summary. Name the import once in the destination sidebar; service cards edit service names. +Progress links once per destination project. Review and saved progress share a Domains & DNS guide, using the provider's recorded domain ownership per service. Imported custom domains are saved through the normal migration routing path, initially unverified. Distinguish domains that need DNS changes from provider URLs that diff --git a/docs/installation.md b/docs/installation.md index 756a9f1dc..ffd095be7 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -94,7 +94,7 @@ Fix by moving Docker's data-root to a native `ext4`/`xfs` disk (`/etc/docker/dae ## Users & access (self-hosted) -- **Public signup is disabled after the first account.** The first admin comes from the `openship` setup wizard; with `openship up --compose` (or raw Docker) you register the first account in the dashboard. Everyone after joins by invite. +- **Create the first admin on the server.** Run `openship` and choose **Create first admin**, or use `openship up --non-interactive --admin-email ` with `OPENSHIP_ADMIN_PASSWORD` set. The same setup works for CLI-managed Compose installs. Public signup stays disabled; everyone after joins by invite. - **Invite teammates** from **Settings → Team**. They get an accept link at your instance's URL (so the instance needs to be reachable — a public URL or your LAN). - **Lost the admin password?** Run `openship reset-admin-password` on the box (no sign-in needed; uses the local internal token). diff --git a/docs/mail-engine-state.md b/docs/mail-engine-state.md index cfa70c3cc..60e9dc512 100644 --- a/docs/mail-engine-state.md +++ b/docs/mail-engine-state.md @@ -25,10 +25,13 @@ Supervisor rather than relying on systemd or Debian's service-start policy. `OPENSHIP_MAIL_F2B_IGNOREIP` extends the image's default `ignoreip` list. For a new installation, an operator may set it in the API environment before mail setup. -For an existing server, set the single-line value in that server's retained -`/var/lib/openship/mail/engine.env`, then update/recreate the engine. Different -servers can retain different exclusions. The file contains credentials and must -remain private. +On an engine image update, a nonempty API value replaces this record in the retained +`/var/lib/openship/mail/engine.env`; an explicitly empty API value removes it. +Leaving the API variable unset preserves the server's saved exclusions. Different +servers can retain different lists configured directly in their own `engine.env`. +The override is applied when replacing the engine image; restarting the API or +checking an already-current image does not recreate the engine. The file contains +credentials and must remain private. Move existing manual `ignoreip` edits from the old container into this setting before the first update. Arbitrary files under `/etc/fail2ban` are not persisted; diff --git a/docs/managed-cloud-servers.md b/docs/managed-cloud-servers.md index 2ab754f07..6d2858c3d 100644 --- a/docs/managed-cloud-servers.md +++ b/docs/managed-cloud-servers.md @@ -212,11 +212,13 @@ root-equivalent access to this server, not project-scoped access. Direct SSH/SDK clients run outside Openship's deployment queue; administrators must coordinate their own commands with application work. -The provider Runtime endpoint defaults to `https://workspace.oblien.com` and can -be overridden with `OBLIEN_RUNTIME_URL`. All provider methods used here are in -Oblien SDK 2.10.0; no new provider SDK release is required. Deploy the Openship API -and dashboard from the same release to use the new controls. Existing server -response shapes are unchanged. Detailed network reads opt in with +The provider Runtime endpoint defaults to `https://vm.oblien.com` and can +be overridden with `OBLIEN_RUNTIME_URL`. These controls use Oblien SDK 3.0.2 and +require the matching native VM API/gateway and fresh scoped credentials. Follow +the [SDK 3 cutover instructions](openship-cloud-launch.md#oblien-sdk-3-and-versioned-api-activation), +including the Desktop/self-hosted client rollout. Deploy the Openship API and +dashboard from the same release. Existing OpenShip server response shapes are +unchanged. Detailed network reads opt in with `getNetworkSettings(id, { details: true })` / `?details=true`; writes return diagnostics only when the caller supplies `expectedRevision`, preserving the original internet-only contract for older clients. diff --git a/docs/openship-cloud-launch.md b/docs/openship-cloud-launch.md index 033bf2aa8..51b2f7784 100644 --- a/docs/openship-cloud-launch.md +++ b/docs/openship-cloud-launch.md @@ -582,7 +582,6 @@ assuming the `.env.saas` filename indicates production provider credentials. ```dotenv CLOUD_MODE=true OPENSHIP_TARGET=cloud-saas - OBLIEN_API_URL=https://api.oblien.com OBLIEN_CLIENT_ID= OBLIEN_CLIENT_SECRET= OBLIEN_WEBHOOK_SECRET= @@ -805,3 +804,39 @@ and database migration `0153_durable_credit_alerts` before rolling out the API a [Namespace credit alerts](namespace-credit-alerts.md) is the reference for delivery guarantees, provider requirements, organization isolation, and verification. + +## Oblien SDK 3 and versioned API activation + +Cloud uses the native VM contract from Oblien SDK 3.0.2. The SDK owns its default +control-plane base URL and API version; leave `OBLIEN_API_URL` unset. If an +operator needs a proxy, the override must be the complete API mount including +its version. Remove a previously configured unversioned provider origin during +the coordinated cutover. + +The custom checkout browser page remains `https://api.oblien.com/billing/pay`. +Only its control-plane creation/status requests use `/v1`; do not rewrite the +returned payment URL or apply the API mount to Runtime/CDN URLs. + +Activate the matching Oblien `/v1` API and migrated database before deploying +this integration. Older SDK routes are not probed and failed writes are not +replayed. OpenShip's organization/workspace records, managed-server IDs, paid +offer snapshots and customer metadata retain their existing identities. The +provider boundary maps those saved workspace counts to native VM capacity. + +The matching runtime gateway is `https://vm.oblien.com`; remove or update any +old `OBLIEN_RUNTIME_URL` override. Runtime credentials must carry `type: "vm"` +and the selected `vm_id`. Namespace/account tokens are never runtime credentials. + +This cutover also requires a Desktop/self-hosted release containing SDK 3 for +installations that use Cloud servers. Those clients execute provider requests +directly using scoped tokens; redeploying the hosted API alone cannot upgrade +their SDK 2 transport. Coordinate that client rollout with the provider cutover, +and obtain fresh credentials. Existing VM IDs, disks, and project data must be +preserved. Self-hosted local/SSH-only deployments do not use this provider API. + +Before reopening customer operations, run `bun run --cwd apps/api cloud:check` +with the deployed Cloud environment and both explicit staging verification +scripts (`verify-cloud-docker.ts` and `verify-cloud-isolation.ts`) against the +matching API/gateway. Verify an existing VM in addition to disposable creation, +exec/files, routing, namespace isolation and cleanup. Local HTTP fixtures and +unit tests do not establish that the provider deployment has been activated. diff --git a/docs/platform-migrations.md b/docs/platform-migrations.md index c9f0baca7..e72b03223 100644 --- a/docs/platform-migrations.md +++ b/docs/platform-migrations.md @@ -6,10 +6,10 @@ New Project → Import existing project offers Server or Docker, Railway, and Ve 1. An organization admin adds a Railway or Vercel connection in Settings → Connections or directly in the import flow. Existing registry and DNS credentials remain on the same page. Old `?tab=credentials` and `?tab=dns` links still work. 2. Select a project and environment. Railway discovers services, deployed revisions, variables, domains, and attached volumes. Vercel discovers a production or latest ready preview deployment and its GitHub source, build configuration, variables, domains, and PostgreSQL URLs. -3. Review all services in the Railway environment together, one destination project name, distinct service names, a managed plan or connected server, and whether to copy storage or explicitly start empty. Each source project becomes one OpenShip project containing its services; importing a second source project creates a separate project. An external PostgreSQL connection can also remain with its current provider. Supply non-exportable secrets and resolve unsupported provider references. +3. Review all services in the Railway environment together, one destination project name, distinct service names, a managed plan or connected server, and whether to copy storage or explicitly start empty. Services sharing one repository, branch and revision stay in one OpenShip project. When Git sources differ, each service gets its own project on the selected server; review shows the exact destination names before import. Importing another source environment creates separate projects. An external PostgreSQL connection can also remain with its current provider. Supply non-exportable secrets and resolve unsupported provider references. 4. Review checks source compatibility, repository access and destination access. The plan expires after 30 minutes. Starting rechecks the provider inventory; changed configuration requires a fresh discovery. Source admission is reserved transactionally by Railway project and environment, across destinations and connection records. -5. Allow Railway project downtime and pause external deployment automation. The worker prepares the selected managed Cloud host before source downtime, creates one destination project with native services, disables automatic push deployments, stops the entire source environment and copies its volumes before deploying the destination. Private addresses resolve through the services' native aliases on the project network. Environment values are encrypted and scoped per service. Named volumes include the service name and use the normal project namespace, keeping databases and separate projects isolated. -6. Follow progress, logs and the project link at `/migrations/`, including after a browser refresh. Review **Domains & DNS**: each saved source hostname is associated with its service. Custom domains and aliases are already added through the same `saveMigrationRoutes` path used by server/Docker migration, initially unverified. Provider-owned Railway and Vercel URLs require replacement addresses and updates to clients, OAuth callbacks and webhooks. **Review domains & DNS** opens the native project Domains & Routes flow. Test the destination, apply the exact DNS records shown for Cloud or the destination server, then verify DNS, HTTPS and application traffic before confirming completion. Retire the old provider resources separately. +5. Allow Railway project downtime and pause external deployment automation. The worker prepares the selected managed Cloud host before source downtime, creates the reviewed destination projects with native services, disables automatic push deployments, stops the entire source environment and copies every selected volume before starting destination workloads. Dependencies deploy before their consumers. Within a project, private addresses use native service aliases; across projects they use ordinary private service connections with immutable service aliases. Environment values remain encrypted. Service-specific values stay scoped to the service; cross-project connection variables are owned by the native connection so later deployments refresh them correctly. Named volumes include the service name and use the normal project namespace, keeping databases and separate projects isolated. +6. Follow progress, logs and the destination project links at `/migrations/`, including after a browser refresh. Review **Domains & DNS**: each saved source hostname is associated with its service. Custom domains and aliases are already added through the same `saveMigrationRoutes` path used by server/Docker migration, initially unverified. Provider-owned Railway and Vercel URLs require replacement addresses and updates to clients, OAuth callbacks and webhooks. **Review domains & DNS** opens the native project Domains & Routes flow. Test the destination, apply the exact DNS records shown for Cloud or the destination server, then verify DNS, HTTPS and application traffic before confirming completion. Retire the old provider resources separately. Domain guidance reuses the public `domains` inventory and its `portable` flag, persisted in the run's input snapshot. Route persistence validates hostname ownership before stopping the source; @@ -22,7 +22,7 @@ reopening a saved run; confirmation remains an operator acknowledgment, not an a | Source | Supported | Explicit review or separate work | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Railway | Complete project environments, GitHub repositories at the deployed commit, custom Dockerfiles, portable registry images, build settings, HTTP readiness, restart policy, variables and all selected persistent volume contents | Sealed secrets, unresolved references, dependency cycles, incompatible Git sources, scheduled jobs, multiple replicas, pre-deploy commands, multiple public ports, private registry access and provider-specific features | +| Railway | Complete project environments including multiple GitHub repositories at their own deployed commits, custom Dockerfiles, portable registry images, build settings, HTTP readiness, restart policy, variables and all selected persistent volume contents | Sealed secrets, unresolved references, dependency cycles, variables combining multiple cross-project private hosts, missing private listener ports, scheduled jobs, multiple replicas, pre-deploy commands, multiple public ports, private registry access and provider-specific features | | Vercel | GitHub source at the deployed commit, build/root/output settings, exportable environment values, discovered domains, external PostgreSQL connections | Non-exportable Secret/Sensitive values, functions and provider APIs requiring application changes, Edge Config, Blob, other storage services, and non-GitHub repositories | | External PostgreSQL | A logical copy of the configured database to the selected major version, or preservation of its external connection | Other databases, roles, provider authentication, extensions unavailable in the destination image, pooler/client settings and non-public source endpoints | @@ -34,7 +34,7 @@ Managed Cloud and connected servers use the same import worker and transfer pipe External PostgreSQL copies use the shared logical backup producer. Source/target majors and available extensions are checked before restore, and fresh destination databases must finish initialization before receiving data. External writers still require manual quiescence. -Repository imports use ordinary OpenShip source-service build recipes. Each provider service remains one native service, including explicitly discovered workers. A native project has one Git source: services using different repositories or deployed commits must be aligned before review can succeed. Repository-wide release commands require a service-compatible recipe; review blocks them instead of silently skipping their release phase. Railway pre-deploy commands, cron, replica topology, unsupported Vercel configuration and invalid paths also block review. Railway sleeping services become continuously running services, with a review warning. +Repository imports use ordinary OpenShip source-service build recipes. Each provider service remains one native service, including explicitly discovered workers. Different repositories, branches or deployed commits receive separate projects; each deployment uses that service's reviewed commit. Cross-project private connections preserve protocols, credentials, paths and ports. A variable containing several different private dependency hosts needs separate connection variables before import, and a private dependency needs a discoverable listener port; review explains these cases before source downtime. Repository-wide release commands require a service-compatible recipe; review blocks them instead of silently skipping their release phase. Railway pre-deploy commands, cron, replica topology, unsupported Vercel configuration and invalid paths also block review. Railway sleeping services become continuously running services, with a review warning. Vercel cannot export Secret/Sensitive values. After entering a missing PostgreSQL URL, Review adds its database to the same choice list. It stays external unless the user chooses to copy it. Copies require a direct public PostgreSQL URL with TLS and a source database role permitted to export its contents. DNS is validated and pinned; the client runs inside the destination database container. @@ -70,6 +70,18 @@ Import tests cover review binding and drift, exact Git revisions, destination pr source downtime, database-first ordering, transfer failures, cancellation and owned SSH-key recovery. Database tests exercise multi-project migration locks and pending cleanup guards. +### Multi-repository verification — 2026-11-16 + +The project import Docker fixture now also covers an image-backed database and two +different Git sources, importing two environments with identical service names into +six destination projects. It checks each repository's revision, real private-network +connections, copied volumes, persistence after restart, and connection refresh during +an ordinary consumer redeployment. Both socket and Cloud Docker transports use an +isolated test daemon. Provider control, Git checkout, runtime destination resolution +and the asynchronous queue are fixture boundaries; this is not a live Railway or SaaS +account test. Focused tests additionally cover dependency ordering, connection failure +and recovery, old-plan rejection, and review blockers before source downtime. + ### Grouped project verification — 2026-11-12 `apps/api/test/e2e/platform-import-project.e2e.test.ts` imports two projects, each with diff --git a/docs/ship-sdk-plan.md b/docs/ship-sdk-plan.md index 924be50de..9ffc7387c 100644 --- a/docs/ship-sdk-plan.md +++ b/docs/ship-sdk-plan.md @@ -202,7 +202,7 @@ Existing patterns can support the main embedding models: - One organization per customer: a stable external customer mapping selects the organization; every operation stays within it. - One personal organization per user: personal project spaces use the existing organization/membership model. -- Several users in one customer organization: restricted roles and project grants provide project-level access. Ordinary membership may be broader, so use the appropriate policy deliberately. +- Several users in one customer organization: restricted roles and project grants provide project-level access. Ordinary members have read/write access but cannot satisfy admin operations; token grants respect the user's current built-in role. - Automated project creation: reuse the create-and-grant semantics of scoped tokens, and extend them deliberately for verified native principals. Project creation and the associated access grant must have defined transactional behavior. - Namespace-oriented products: first map external namespace keys to an existing tenant or appropriate grouping. If nested namespace isolation is required, add a tenant-owned namespace model, grant semantics, scoped queries, and migrations. A string prefix or renamed project group is insufficient. diff --git a/packages/adapters/package.json b/packages/adapters/package.json index 858f55356..4077f40fe 100644 --- a/packages/adapters/package.json +++ b/packages/adapters/package.json @@ -46,7 +46,7 @@ "ignore": "^7.0.5", "ioredis": "^5.10.0", "ipaddr.js": "^2.4.0", - "oblien": "2.10.0", + "oblien": "3.0.2", "ssh2": "^1.17.0", "tar-fs": "^2.1.4", "undici": "^7.30.2", diff --git a/packages/adapters/scripts/verify-cloud-docker.ts b/packages/adapters/scripts/verify-cloud-docker.ts index 04b06e02d..6e7ab79bb 100644 --- a/packages/adapters/scripts/verify-cloud-docker.ts +++ b/packages/adapters/scripts/verify-cloud-docker.ts @@ -10,6 +10,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { randomUUID } from "node:crypto"; import { Oblien } from "../src/oblien"; +import { oblienApiBaseUrl, oblienApiUrl } from "../src/oblien-contract"; import { CloudDockerRuntime } from "../src/runtime/cloud/docker"; import { CloudProcessSupervisor } from "../src/runtime/cloud/process-supervisor"; import { cloudDockerProjectPaths } from "../src/runtime/cloud/docker-paths"; @@ -33,7 +34,7 @@ const domainFlag = process.argv.indexOf("--public-domain"); const publicDomain = domainFlag >= 0 ? process.argv[domainFlag + 1]! : "opsh.io"; if (!publicDomain || !/^[a-z0-9.-]+$/.test(publicDomain)) throw new Error("Invalid public test domain"); -const baseUrl = configuration.OBLIEN_API_URL || "https://api.oblien.com"; +const baseUrl = oblienApiBaseUrl(configuration.OBLIEN_API_URL).toString(); const presetFlag = process.argv.indexOf("--preset"); const softwarePreset = presetFlag >= 0 ? process.argv[presetFlag + 1] : undefined; if (presetFlag >= 0 && (!softwarePreset || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(softwarePreset))) @@ -93,7 +94,7 @@ try { name: tag, slug: tag, type: "testing", - resource_limits: { max_workspaces: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 }, + resource_limits: { max_vms: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 }, }); namespaceId = created.data.id; await save(); @@ -103,7 +104,7 @@ try { quotaLimit: 100, overdraft: 0, suspendThreshold: 0, - onOverdraftAction: "stop_workspaces", + onOverdraftAction: "stop_vms", }); const token = await admin.tokens.create({ scope: "namespace", namespace: tag, ttl: 1800 }); const client = new Oblien({ token: token.token, baseUrl }); @@ -127,11 +128,11 @@ try { network_config: { allow_internet: true, public_ingress: false }, }, }; - const workspace = await client.workspaces.create(createOptions); + const workspace = await client.vms.create(createOptions); workspaceId = workspace.id; await save(); check("workspace created in test namespace", workspace.namespace === tag && workspaceId); - const replay = await client.workspaces.create(createOptions); + const replay = await client.vms.create(createOptions); check("provider idempotency reuses workspace", replay.id === workspaceId); const progress = setInterval(() => log("waiting for Docker workspace"), 20_000); try { @@ -140,13 +141,13 @@ try { clearInterval(progress); } log("Docker workspace ready"); - await client.workspace(workspaceId).lifecycle.makePermanent(); + await client.vm(workspaceId).lifecycle.makePermanent(); check( "managed server can be made permanent", - (await client.workspaces.get(workspaceId)).mode === "permanent", + (await client.vms.get(workspaceId)).mode === "permanent", ); await client - .workspace(workspaceId) + .vm(workspaceId) .lifecycle.makeTemporary({ ttl: "20m", ttl_action: "remove", remove_on_exit: false }); const pageMethods = [ "list", @@ -170,7 +171,7 @@ try { return { ...result, pages: result.pages.filter((page) => page.namespace === tag) }; }; adminPages.create = async (input) => { - if (input.workspace_id !== workspaceId || !input.slug?.startsWith(tag)) + if (input.vm_id !== workspaceId || !input.slug?.startsWith(tag)) throw new Error("Smoke route escaped its workspace"); pages.add(input.slug); await save(); @@ -473,7 +474,7 @@ try { await runtime.stop(second.containerId); check( "service stop preserves workspace and sibling", - isDockerWorkspaceRunning(await client.workspaces.get(workspaceId)) && + isDockerWorkspaceRunning(await client.vms.get(workspaceId)) && (await runtime.getContainerInfo(internal.containerId)).status === "running", ); const stoppedPorts = second.hostPortByContainerPort; @@ -536,7 +537,7 @@ try { env: { OPENSHIP_SMOKE_PROCESS: "saved" }, }; await processSupervisor.deploy(processOptions); - const workload = () => client.workspace(workspaceId!).workloads.get(`openship-${processId}`); + const workload = () => client.vm(workspaceId!).workloads.get(`openship-${processId}`); const savedProcess = await workload(); check( "provider returns saved process configuration", @@ -565,10 +566,10 @@ try { ); await processSupervisor.stop(processId); - check("provider accepts server stop", (await client.workspace(workspaceId).stop()).success); + check("provider accepts server stop", (await client.vm(workspaceId).stop()).success); await waitForCloudWorkspaceStopped(client, workspaceId, tag); log("workspace stopped for recovery check", { - status: (await client.workspaces.get(workspaceId)).status, + status: (await client.vms.get(workspaceId)).status, }); check( "stopped workspace reads do not start compute", @@ -590,7 +591,7 @@ try { "bare deletion retains the Docker application and server", (await processSupervisor.getInfo(processId)).status === "missing" && (await runtime.getContainerInfo(second.containerId)).status === "running" && - isDockerWorkspaceRunning(await client.workspaces.get(workspaceId)), + isDockerWorkspaceRunning(await client.vms.get(workspaceId)), ); check( "workspace restart preserves the volume", @@ -599,7 +600,7 @@ try { ); check( "bridge recovery reuses its workload", - (await client.workspace(workspaceId).workloads.list({ name: "openship-docker-api-v1" })) + (await client.vm(workspaceId).workloads.list({ name: "openship-docker-api-v1" })) .length === 1, ); const hostnames = await infra.listProjectRouteHostnames(); @@ -630,11 +631,11 @@ try { } check( "one workspace for the whole stack", - (await client.workspaces.list()).workspaces.length === 1, + (await client.vms.list()).vms.length === 1, ); } catch (error) { if (workspaceId) { - const workspace = await admin.workspaces.get(workspaceId).catch(() => null); + const workspace = await admin.vms.get(workspaceId).catch(() => null); if (workspace) { const provisioning = workspace.provisioning as | { state?: string; error?: unknown } @@ -662,7 +663,7 @@ try { for (const slug of pages) { try { const page = (await admin.pages.get(slug)).page; - if (page.namespace !== tag || page.source_workspace_id !== workspaceId) + if (page.namespace !== tag || page.source_vm_id !== workspaceId) throw new Error("Unexpected smoke page owner"); await admin.pages.delete(slug); pages.delete(slug); @@ -676,7 +677,7 @@ try { } if (workspaceId) { try { - await deleteCloudWorkspace(admin.workspace(workspaceId)); + await deleteCloudWorkspace(admin.vm(workspaceId)); workspaceId = undefined; } catch (error) { if ((error as { status?: number }).status === 404) workspaceId = undefined; diff --git a/packages/adapters/scripts/verify-cloud-isolation.ts b/packages/adapters/scripts/verify-cloud-isolation.ts index 1095a25ba..131a01d2a 100644 --- a/packages/adapters/scripts/verify-cloud-isolation.ts +++ b/packages/adapters/scripts/verify-cloud-isolation.ts @@ -9,13 +9,14 @@ import { join } from "node:path"; import { randomUUID } from "node:crypto"; import { setTimeout as delay } from "node:timers/promises"; import { Oblien } from "../src/oblien"; +import { oblienApiBaseUrl, oblienApiUrl } from "../src/oblien-contract"; import { cloudWorkspaceStatus, waitForCloudDockerWorkspace } from "../src/runtime/cloud/workspace-ready"; import { CloudWorkspaceExecutor } from "../src/runtime/cloud/workspace-executor"; import { deleteCloudWorkspace } from "../src/runtime/cloud/workspace-delete"; if (process.argv[2] !== "--staging-env" || !process.argv[3]) throw new Error("Provide a confirmed staging credential file with --staging-env"); const config = parseEnv(await readFile(process.argv[3], "utf8")); -const baseUrl = config.OBLIEN_API_URL || "https://api.oblien.com"; +const baseUrl = oblienApiBaseUrl(config.OBLIEN_API_URL).toString(); if (!config.OBLIEN_CLIENT_ID || !config.OBLIEN_CLIENT_SECRET || new URL(baseUrl).protocol !== "https:") throw new Error("Staging credentials and HTTPS are required"); const admin = new Oblien({ clientId: config.OBLIEN_CLIENT_ID, clientSecret: config.OBLIEN_CLIENT_SECRET, baseUrl }); const tag = `os-cycle-${randomUUID().replaceAll("-", "").slice(0, 14)}`; @@ -61,7 +62,7 @@ async function suspendedWorkspaceStops(client: Oblien, workspaceId: string, name let observedState: string | undefined; try { await until(name, async () => { - const workspace = await client.workspaces.get(workspaceId); + const workspace = await client.vms.get(workspaceId); const state = cloudWorkspaceStatus(workspace); if (state !== observedState) { const info = workspace.info as { status?: string; is_running?: boolean } | undefined; @@ -81,13 +82,13 @@ async function suspendedWorkspaceStops(client: Oblien, workspaceId: string, name message: error instanceof Error ? error.message : "Unknown failure" }); // Preserve the failed automatic-stop result, then exercise the independent // customer cleanup and explicit-reactivation contract on the same fixture. - await client.workspace(workspaceId).stop(); - await until("explicit Stop completes during suspension", async () => cloudWorkspaceStatus(await client.workspaces.get(workspaceId)) === "stopped"); + await client.vm(workspaceId).stop(); + await until("explicit Stop completes during suspension", async () => cloudWorkspaceStatus(await client.vms.get(workspaceId)) === "stopped"); } } const a = `${tag}-a`, b = `${tag}-b`; -const resources = { max_workspaces: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 }; -const policy = (quotaLimit: number) => ({ quotaLimit, overdraft: 0, suspendThreshold: 0, onOverdraftAction: "stop_workspaces" as const }); +const resources = { max_vms: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 }; +const policy = (quotaLimit: number) => ({ quotaLimit, overdraft: 0, suspendThreshold: 0, onOverdraftAction: "stop_vms" as const }); const create = (namespace: string, suffix: string) => ({ namespace, name: `${namespace}-${suffix}`, slug: `${namespace}-${suffix}`, image: "oblien/docker:29", mode: "temporary" as const, wait_ready: false, idempotency_key: `${namespace}-${suffix}`, config: { cpus: 2, memory_mb: 4096, disk_size_mb: 32768, ttl: "15m", ttl_action: "remove" as const, @@ -96,7 +97,7 @@ const create = (namespace: string, suffix: string) => ({ namespace, name: `${nam try { log("starting isolated quota test", { directory }); const defaults = await admin.billing.defaults(); - check("new namespaces have finite automatic onboarding policy", defaults.autoApply && defaults.quotaLimit === 0 && defaults.overdraft === 0 && defaults.suspendThreshold === 0 && defaults.onOverdraftAction === "stop_workspaces"); + check("new namespaces have finite automatic onboarding policy", defaults.autoApply && defaults.quotaLimit === 0 && defaults.overdraft === 0 && defaults.suspendThreshold === 0 && defaults.onOverdraftAction === "stop_vms"); for (const namespace of [a, b]) { const input = { name: namespace, slug: namespace, resource_limits: resources }; const { data } = namespace === a ? await admin.namespaces.ensure(input) : await admin.namespaces.create(input); @@ -108,7 +109,7 @@ try { log("new namespace billing", { customer: namespace === a ? "A" : "B", method: namespace === a ? "ensure" : "create", entitlement, balance, policy: inheritedPolicy, subscription: await admin.billing.subscription(namespace) }); check(`${namespace === a ? "A" : "B"}: zero credit inherited without a grant`, entitlement.namespace === namespace && entitlement.quota.limit === 0 && balance.blocking && - inheritedPolicy.quotaLimit === 0 && inheritedPolicy.overdraft === 0 && inheritedPolicy.suspendThreshold === 0 && inheritedPolicy.onOverdraftAction === "stop_workspaces", false); + inheritedPolicy.quotaLimit === 0 && inheritedPolicy.overdraft === 0 && inheritedPolicy.suspendThreshold === 0 && inheritedPolicy.onOverdraftAction === "stop_vms", false); const subscription = (await admin.billing.subscription(namespace)).subscription; check(`${namespace === a ? "A" : "B"}: unpaid namespace cannot inherit the owner's plan`, subscription === null && (entitlement.tierId === null || entitlement.tierId === "free") && entitlement.periodStart === null && entitlement.periodEnd === null, false); // Continue the independent enforcement checks with an explicit fixture @@ -125,7 +126,7 @@ try { const request = client._http.request.bind(client._http); client._http.request = async (input: Parameters[0]): Promise => { const result = await request(input); - if (input.method === "POST" && input.path === "/workspace") { + if (input.method === "POST" && input.path === "/vms") { const data = result as Record; log("workspace creation response shape", { keys: Object.keys(data), success: data.success, code: data.code, error: typeof data.error === "string" ? data.error : undefined, @@ -134,15 +135,15 @@ try { return result; }; } - check("exhausted customers retain scoped inspection access", (await clientA.workspaces.list()).workspaces.length === 0); - await denied("unpaid namespace cannot create compute", () => clientA.workspaces.create(create(a, "unpaid")), [402, 403]); + check("exhausted customers retain scoped inspection access", (await clientA.vms.list()).vms.length === 0); + await denied("unpaid namespace cannot create compute", () => clientA.vms.create(create(a, "unpaid")), [402, 403]); for (const namespace of [a, b]) await admin.billing.setPolicy(namespace, policy(100)); check("isolated test allowance activates only its namespace", (await admin.billing.entitlement(a)).status === "active" && !(await admin.billing.balance(b)).blocking); const repeated = await admin.namespaces.ensure({ name: a, slug: a, resource_limits: resources }); check("ensure preserves an existing namespace's allowance", repeated.data.id === namespaceIds.get(a) && (await admin.billing.policy(a)).quotaLimit === 100); - const raced = await Promise.allSettled([clientA.workspaces.create(create(a, "race-1")), clientA.workspaces.create(create(a, "race-2"))]); - const winners = raced.filter((item): item is PromiseFulfilledResult>> => item.status === "fulfilled"); + const raced = await Promise.allSettled([clientA.vms.create(create(a, "race-1")), clientA.vms.create(create(a, "race-2"))]); + const winners = raced.filter((item): item is PromiseFulfilledResult>> => item.status === "fulfilled"); const losers = raced.filter(item => item.status === "rejected"); log("concurrent create outcomes", { results: raced.map(item => item.status === "fulfilled" ? { state: item.status, workspaceId: item.value?.id, namespace: item.value?.namespace } @@ -151,19 +152,19 @@ try { const workspaceA = winners[0]!.value; // Inspect the actual wire status, independently of Openship's compatibility // normalization for the provider's former HTTP-200 limit failures. - const limited = await fetch(new URL("/workspace", baseUrl), { + const limited = await fetch(oblienApiUrl(new URL(baseUrl), "/vms"), { method: "POST", headers: { Authorization: `Bearer ${tokenA}`, "Content-Type": "application/json" }, body: JSON.stringify(create(a, "raw-limit")), redirect: "error", signal: AbortSignal.timeout(30_000), }); log("workspace cap wire response", { status: limited.status }); check("workspace cap returns HTTP 409", limited.status === 409); await limited.arrayBuffer(); - const workspaceB = await clientB.workspaces.create(create(b, "main")); + const workspaceB = await clientB.vms.create(create(b, "main")); await waitForCloudDockerWorkspace(clientA, workspaceA.id, a, { signal: abort.signal }); await waitForCloudDockerWorkspace(clientB, workspaceB.id, b, { signal: abort.signal }); check("two customers own different workspaces", workspaceA.id !== workspaceB.id && workspaceA.namespace === a && workspaceB.namespace === b); for (const [client, workspace, namespace] of [[clientA, workspaceA, a], [clientB, workspaceB, b]] as const) { - const executor = new CloudWorkspaceExecutor(() => client.workspace(workspace.id).runtime()); + const executor = new CloudWorkspaceExecutor(() => client.vm(workspace.id).runtime()); const path = `/opt/openship/cloud-docker/routes/${namespace}`; try { await executor.mkdir(path); await executor.writeFile(`${path}/index.html`, `Isolated customer ${namespace}`); @@ -175,16 +176,16 @@ try { finally { await executor.dispose(); } pages.set(namespace, namespace); await save(); - await admin.pages.create({ slug: namespace, namespace, workspace_id: workspace.id, path, domain: "preview.oblien.com" }); + await admin.pages.create({ name: namespace, slug: namespace, namespace, vm_id: workspace.id, path, domain: "preview.oblien.com" }); } - const visibleA = (await clientA.workspaces.list()).workspaces; - const visibleB = (await clientB.workspaces.list()).workspaces; + const visibleA = (await clientA.vms.list()).vms; + const visibleB = (await clientB.vms.list()).vms; check("workspace lists are isolated", visibleA.length === 1 && visibleA[0]!.namespace === a && visibleB.length === 1 && visibleB[0]!.namespace === b); - await denied("customer cannot read another customer's VM", () => clientA.workspaces.get(workspaceB.id), [403, 404]); - await denied("customer cannot stop another customer's VM", () => clientA.workspace(workspaceB.id).stop(), [403, 404]); - await denied("customer cannot delete another customer's VM", () => clientA.workspaces.delete(workspaceB.id), [403, 404]); - await denied("customer cannot escape its namespace on creation", () => clientA.workspaces.create(create(b, "escape")), [400, 403, 409, 422]); - check("foreign namespace still owns exactly its original workspace", (await clientB.workspaces.list()).workspaces.length === 1); + await denied("customer cannot read another customer's VM", () => clientA.vms.get(workspaceB.id), [403, 404]); + await denied("customer cannot stop another customer's VM", () => clientA.vm(workspaceB.id).stop(), [403, 404]); + await denied("customer cannot delete another customer's VM", () => clientA.vms.delete(workspaceB.id), [403, 404]); + await denied("customer cannot escape its namespace on creation", () => clientA.vms.create(create(b, "escape")), [400, 403, 409, 422]); + check("foreign namespace still owns exactly its original workspace", (await clientB.vms.list()).vms.length === 1); await denied("customer cannot access account billing", () => clientA.billing.entitlement(b), [403]); await denied("customer cannot grant itself credit", () => clientA.billing.setPolicy(a, policy(500)), [403]); await denied("customer cannot mint a more privileged token", () => clientA.tokens.create({ scope: "namespace", namespace: b }), [403]); @@ -194,10 +195,10 @@ try { check("Page listing cannot expose another namespace", visible.every(page => page.namespace === a), false); } catch (error) { check("Page listing requires privileged proxy", (error as { status?: number }).status === 403); } await denied("customer cannot read another customer's Page", () => clientA.pages.get(b), [403, 404]); - await denied("namespace CPU ceiling blocks resize", () => clientA.workspace(workspaceA.id).resources.update({ cpus: 3, apply: false }), [400, 409, 422]); - await denied("namespace RAM ceiling blocks resize", () => clientA.workspace(workspaceA.id).resources.update({ memory_mb: 8192, apply: false }), [400, 409, 422]); - await denied("namespace disk ceiling blocks resize", () => clientA.workspace(workspaceA.id).resources.update({ disk_size_mb: 65536, apply: false }), [400, 409, 422]); - check("rejected resize keeps the original allocation", (await clientA.workspaces.get(workspaceA.id)).resources?.cpus === 2); + await denied("namespace CPU ceiling blocks resize", () => clientA.vm(workspaceA.id).resources.update({ cpus: 3, apply: false }), [400, 409, 422]); + await denied("namespace RAM ceiling blocks resize", () => clientA.vm(workspaceA.id).resources.update({ memory_mb: 8192, apply: false }), [400, 409, 422]); + await denied("namespace disk ceiling blocks resize", () => clientA.vm(workspaceA.id).resources.update({ disk_size_mb: 65536, apply: false }), [400, 409, 422]); + check("rejected resize keeps the original allocation", (await clientA.vms.get(workspaceA.id)).resources?.cpus === 2); try { await until("provider records compute usage", async () => (await admin.billing.entitlement(a)).quota.used > 0, 300_000); @@ -228,25 +229,25 @@ try { check("exhaustion is visible in entitlement and balance", true); check("new usage crossed the configured credit allowance", effectiveAllowance !== null && (await admin.billing.entitlement(a)).quota.used >= effectiveAllowance); try { - await until("provider stops exhausted namespace", async () => cloudWorkspaceStatus(await clientA.workspaces.get(workspaceA.id)) === "stopped", 90_000); + await until("provider stops exhausted namespace", async () => cloudWorkspaceStatus(await clientA.vms.get(workspaceA.id)) === "stopped", 90_000); check("provider stops A on exhaustion", true); } catch { check("provider stops A on exhaustion", false, false); log("explicitly stopping A to continue independent management checks"); - await clientA.workspace(workspaceA.id).stop(); + await clientA.vm(workspaceA.id).stop(); } - check("B keeps running when A is exhausted", cloudWorkspaceStatus(await clientB.workspaces.get(workspaceB.id)) === "running" && !(await admin.billing.balance(b)).blocking); - await denied("exhausted customer cannot restart compute", () => clientA.workspace(workspaceA.id).start(), [402, 403, 409]); - await denied("exhausted customer cannot create replacement compute", () => clientA.workspaces.create(create(a, "blocked")), [402, 403, 409]); - check("exhausted customer can still inspect its stopped VM", (await clientA.workspaces.get(workspaceA.id)).id === workspaceA.id); - await clientA.workspace(workspaceA.id).stop(); - await clientA.workspace(workspaceA.id).stop(); + check("B keeps running when A is exhausted", cloudWorkspaceStatus(await clientB.vms.get(workspaceB.id)) === "running" && !(await admin.billing.balance(b)).blocking); + await denied("exhausted customer cannot restart compute", () => clientA.vm(workspaceA.id).start(), [402, 403, 409]); + await denied("exhausted customer cannot create replacement compute", () => clientA.vms.create(create(a, "blocked")), [402, 403, 409]); + check("exhausted customer can still inspect its stopped VM", (await clientA.vms.get(workspaceA.id)).id === workspaceA.id); + await clientA.vm(workspaceA.id).stop(); + await clientA.vm(workspaceA.id).stop(); check("billing-suspended customer can repeat Stop", true); await admin.billing.setPolicy(a, policy(100)); await until("billing restoration", async () => (await admin.billing.entitlement(a)).status === "active" && !(await admin.billing.balance(a)).blocking); - check("restoring credit does not restart compute implicitly", cloudWorkspaceStatus(await clientA.workspaces.get(workspaceA.id)) === "stopped"); - await clientA.workspace(workspaceA.id).start(); + check("restoring credit does not restart compute implicitly", cloudWorkspaceStatus(await clientA.vms.get(workspaceA.id)) === "stopped"); + await clientA.vm(workspaceA.id).start(); await waitForCloudDockerWorkspace(clientA, workspaceA.id, a, { signal: abort.signal }); check("restored customer explicitly resumes the same VM", true); @@ -254,28 +255,28 @@ try { await suspendedWorkspaceStops(clientA, workspaceA.id, a, "manual suspension stops A"); await admin.billing.setPolicy(a, policy(200)); check("credit increase cannot undo a manual suspension", (await admin.namespaces.get(a)).data.status === "suspended" && (await admin.billing.balance(a)).blocking); - await denied("manual suspension blocks Start despite positive credit", () => clientA.workspace(workspaceA.id).start(), [402, 403, 409]); + await denied("manual suspension blocks Start despite positive credit", () => clientA.vm(workspaceA.id).start(), [402, 403, 409]); await admin.namespaces.activate(namespaceIds.get(a)!); - check("explicit reactivation restores access without starting the VM", (await admin.namespaces.get(a)).data.status === "active" && !(await admin.billing.balance(a)).blocking && cloudWorkspaceStatus(await clientA.workspaces.get(workspaceA.id)) === "stopped"); - await clientA.workspace(workspaceA.id).start(); + check("explicit reactivation restores access without starting the VM", (await admin.namespaces.get(a)).data.status === "active" && !(await admin.billing.balance(a)).blocking && cloudWorkspaceStatus(await clientA.vms.get(workspaceA.id)) === "stopped"); + await clientA.vm(workspaceA.id).start(); await waitForCloudDockerWorkspace(clientA, workspaceA.id, a, { signal: abort.signal }); check("manually suspended VM starts only after reactivation", true); log("second manual suspension response", { namespace: a, response: await admin.namespaces.suspend(namespaceIds.get(a)!) }); await suspendedWorkspaceStops(clientA, workspaceA.id, a, "second manual suspension stops A"); - await clientA.workspace(workspaceA.id).stop(); - await clientA.workspace(workspaceA.id).stop(); + await clientA.vm(workspaceA.id).stop(); + await clientA.vm(workspaceA.id).stop(); check("manually suspended customer can repeat Stop", true); - await deleteCloudWorkspace(clientA.workspace(workspaceA.id)); - await until("A disappears from the scoped workspace list", async () => (await clientA.workspaces.list()).workspaces.length === 0, 60_000); - check("suspended customer can delete resources", (await clientA.workspaces.list()).workspaces.length === 0); - check("B remains available after A cleanup", cloudWorkspaceStatus(await clientB.workspaces.get(workspaceB.id)) === "running"); + await deleteCloudWorkspace(clientA.vm(workspaceA.id)); + await until("A disappears from the scoped workspace list", async () => (await clientA.vms.list()).vms.length === 0, 60_000); + check("suspended customer can delete resources", (await clientA.vms.list()).vms.length === 0); + check("B remains available after A cleanup", cloudWorkspaceStatus(await clientB.vms.get(workspaceB.id)) === "running"); await admin.billing.setPolicy(b, policy(0)); - await until("B stops for billing-suspended deletion check", async () => (await admin.billing.balance(b)).blocking && cloudWorkspaceStatus(await clientB.workspaces.get(workspaceB.id)) === "stopped"); - await clientB.workspace(workspaceB.id).stop(); - await clientB.workspace(workspaceB.id).stop(); - await deleteCloudWorkspace(clientB.workspace(workspaceB.id)); - await until("B disappears from the scoped workspace list", async () => (await clientB.workspaces.list()).workspaces.length === 0, 60_000); - check("billing-suspended customer can inspect, repeat Stop and Delete", (await clientB.workspaces.list()).workspaces.length === 0); + await until("B stops for billing-suspended deletion check", async () => (await admin.billing.balance(b)).blocking && cloudWorkspaceStatus(await clientB.vms.get(workspaceB.id)) === "stopped"); + await clientB.vm(workspaceB.id).stop(); + await clientB.vm(workspaceB.id).stop(); + await deleteCloudWorkspace(clientB.vm(workspaceB.id)); + await until("B disappears from the scoped workspace list", async () => (await clientB.vms.list()).vms.length === 0, 60_000); + check("billing-suspended customer can inspect, repeat Stop and Delete", (await clientB.vms.list()).vms.length === 0); } catch (error) { check("all lifecycle checks completed", false, false); log("test failed", { message: error instanceof Error ? error.message.replace(/([?&](?:token|access_token)=)[^&\s]+/gi, "$1[redacted]") : "Unknown failure", status: (error as { status?: number }).status }); @@ -296,7 +297,7 @@ try { try { const current = await admin.namespaces.get(id); if (current.data.slug !== namespace || !namespace.startsWith(`${tag}-`)) throw new Error("Test namespace identity changed"); - await admin.namespaces.delete(id, { deleteWorkspaces: true }); + await admin.namespaces.delete(id, { deleteVms: true }); namespaceIds.delete(namespace); } catch (error) { if ((error as { status?: number }).status === 404) namespaceIds.delete(namespace); diff --git a/packages/adapters/src/backup/executors/docker.ts b/packages/adapters/src/backup/executors/docker.ts index a2555e61f..725fa5f0f 100644 --- a/packages/adapters/src/backup/executors/docker.ts +++ b/packages/adapters/src/backup/executors/docker.ts @@ -434,9 +434,8 @@ export class DockerBackupExecutor implements BackupExecutor { // Idempotent on purpose: the column stores whatever was written at deploy // time, and for services deployed from an already-scoped spec that is the // SCOPED name. Prefixing twice named a volume that never existed, which docker - // creates empty on mount — a capture that archives nothing (now a failure - // rather than a green run, via the empty-source gate) and a restore into a - // volume nothing reads. + // creates empty on mount. Capture verifies that the resolved volume exists + // before mounting it; restore must address the volume the service reads. const source = parsed.type !== "volume" || !service.namespaceVolumes ? parsed.source @@ -578,16 +577,23 @@ export class DockerBackupExecutor implements BackupExecutor { const excludeArgs = (opts?.exclude ?? []).flatMap((p) => ["--exclude", shellQuote(p)]); const tarFlags = compressionFlag(compression); const isFile = source.type === "bind" && source.isDirectory === false; - if (opts?.allowEmpty && source.type === "volume") await this.dockerode.getVolume(source.source).inspect(); + // Docker creates missing named volumes even for read-only mounts. Verify on + // this daemon before creating the helper; emptiness is not an existence check. + if (source.type === "volume") await this.dockerode.getVolume(source.source).inspect(); const tarCmd = `tar -c${tarFlags} -C /mnt ${excludeArgs.join(" ")} ${isFile ? "file" : "."}`; const helperImage = compression === "zstd" ? "alpine:3" : HELPER_IMAGE; await this.ensureImage(helperImage); const hostConfig: Dockerode.HostConfig = { - ...(source.type === "bind" - ? { Mounts: [{ Type: "bind" as const, Source: source.source, Target: `/mnt${isFile ? "/file" : ""}`, ReadOnly: true }] } - : { Binds: [`${source.source}:/mnt:ro`] }), + Mounts: [ + { + Type: source.type as "bind" | "volume", + Source: source.source, + Target: `/mnt${isFile ? "/file" : ""}`, + ReadOnly: true, + }, + ], // OFF, for the reason demuxContainerStream already documents but this line // used to contradict: AutoRemove lets the daemon reap the helper before // container.wait() answers and before the attach stream has drained, which @@ -638,29 +644,10 @@ export class DockerBackupExecutor implements BackupExecutor { tarCmd, compression === "zstd" ? "zstd" : "none", [ - // REFUSE an empty mount before doing anything else. - // - // The daemon CREATES a missing bind directory and a missing named volume - // when it honors HostConfig.Binds, so a source that is not on this host - // produces a helper that starts fine and a `tar -c` of nothing that exits - // 0. That archive is ~350 bytes compressed, so the orchestrator's - // zero-byte guard passes and the run is recorded as a successful backup — - // a nightly green tick over an external disk that failed to mount, a data - // directory that was renamed under a still-running container, or a volume - // that `docker system prune --volumes` took. - // - // An intentionally-empty source fails too, which is the deliberate half of - // the trade: an archive of nothing is not a restore point either way, and - // the operator has `payloadConfig.sourceIds` to narrow the policy. Silence - // is the only outcome that cannot be recovered from. - `SRC=${shellQuote(sourceId)}`, - opts?.allowEmpty ? "true" : `[ -n "$(ls -A /mnt 2>/dev/null)" ] || { echo "openship: backup source $SRC is ` + - `empty or missing on this host, so this archive would contain nothing. ` + - `Refusing to record it as a backup. If it is a mount, check that it is ` + - `mounted; if it is empty on purpose, narrow the policy's sourceIds." >&2; ` + - `exit 91; }`, - // zstd is not in alpine:3, so the helper installs it. Second, so a doomed - // capture does not pay the ~20s fetch first. + // Bind Mounts reject missing host paths instead of creating them. + // Named volumes were inspected above. Existing empty sources are valid; + // tar still fails if the source cannot be read or storage cannot mount. + // zstd is not in alpine:3, so the helper installs it. compression === "zstd" ? "apk add --no-cache zstd >/dev/null 2>&1" : null, ] .filter(Boolean) diff --git a/packages/adapters/src/backup/types.ts b/packages/adapters/src/backup/types.ts index eac679419..a0895405b 100644 --- a/packages/adapters/src/backup/types.ts +++ b/packages/adapters/src/backup/types.ts @@ -130,8 +130,6 @@ export interface ExecuteCommandOpts { export interface StreamPathOpts { compression?: PayloadCompression; - /** A migration may intentionally copy an empty source; backups stay strict. */ - allowEmpty?: boolean; /** Glob-ish patterns to exclude (passed to tar `--exclude`). */ exclude?: string[]; /** diff --git a/packages/adapters/src/backup/volume-transfer.ts b/packages/adapters/src/backup/volume-transfer.ts index 8d899e748..10f6218b9 100644 --- a/packages/adapters/src/backup/volume-transfer.ts +++ b/packages/adapters/src/backup/volume-transfer.ts @@ -163,7 +163,6 @@ export async function transferVolume( // one daemon or across two (src.exec / dst.exec may differ). const read = await src.exec.streamPath(src.handle, src.sourceId, { compression: plan.compression, - allowEmpty: true, }); // Observe source termination from the start, including a rejected target // setup. A broken destination must not leave the producer streaming forever. diff --git a/packages/adapters/src/index.ts b/packages/adapters/src/index.ts index 233833643..619c8b966 100644 --- a/packages/adapters/src/index.ts +++ b/packages/adapters/src/index.ts @@ -606,7 +606,9 @@ export { // ─── Oblien SDK (re-export for single source of truth) ─────────────────────── export { Oblien, OblienError, cloudWorkspaceCreationFailure } from "./oblien"; +export { oblienApiBaseUrl, oblienApiUrl, toOblienVmLimits, toOblienVmCapacity, toOblienVmPolicy, toOblienVmOffer, cloudBillingContract } from "./oblien-contract"; export type { + NamespaceResourceLimits, NamespaceUsageUnits, NamespaceUsageUnitBucket, NamespaceUsageUnitsParams, diff --git a/packages/adapters/src/infra/cloud-routing-sdk.test.ts b/packages/adapters/src/infra/cloud-routing-sdk.test.ts index e96219677..30927a4f5 100644 --- a/packages/adapters/src/infra/cloud-routing-sdk.test.ts +++ b/packages/adapters/src/infra/cloud-routing-sdk.test.ts @@ -27,14 +27,14 @@ beforeEach(() => { return page ? Response.json({ success: true, page }) : Response.json({ error: "Not found" }, { status: 404 }); if (url.pathname === "/pages" && method === "POST") { page = { id: 42, slug: body.slug, domain: body.domain, namespace: h.namespace, - source_workspace_id: body.workspace_id, exported_path: body.path, url: `https://${hostname}` }; + source_vm_id: body.vm_id, exported_path: body.path, url: `https://${hostname}` }; return Response.json({ success: true, page }); } if (url.pathname === "/pages/app/enable" && method === "POST") return Response.json({ success: true }); - if (url.pathname === `/workspace/${h.workspaceId}/network` && method === "GET") + if (url.pathname === `/vms/${h.workspaceId}/network` && method === "GET") return Response.json({ ingress_ports: [443] }); - if (url.pathname === `/workspace/${h.workspaceId}/network` && method === "PATCH") + if (url.pathname === `/vms/${h.workspaceId}/network` && method === "PATCH") return Response.json({ success: true }); if (url.pathname === `/domain/routes/${hostname}` && method === "PUT") return Response.json({ success: true, hostname, version: writes.length, @@ -54,7 +54,7 @@ it.each([301, 302, 307, 308])("sends canonical redirect intent through the real } }); await provider.registerRoute({ domain: hostname, targetUrl: "http://127.0.0.1:3000", tls: true }); const tables = writes.filter(request => request.path === `/domain/routes/${hostname}`); - expect(tables.at(-1)?.body).toEqual({ routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }] }); + expect(tables.at(-1)?.body).toEqual({ routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }] }); expect(writes.filter(request => request.path === "/pages")).toHaveLength(1); expect(requests.some(url => url.pathname === "/workspace")).toBe(false); }); @@ -66,13 +66,13 @@ it("reuses the owned Page through the SDK after routes become a compiled table", const routes = writes.filter(request => request.path === `/domain/routes/${hostname}`); expect(routes).toHaveLength(2); expect(routes[1]).toEqual({ method: "PUT", path: `/domain/routes/${hostname}`, body: { - routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }], + routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }], } }); - expect(writes).toContainEqual({ method: "PATCH", path: `/workspace/${h.workspaceId}/network`, body: { ingress_ports: [443, 3000] } }); + expect(writes).toContainEqual({ method: "PATCH", path: `/vms/${h.workspaceId}/network`, body: { ingress_ports: [443, 3000] } }); expect(requests.some(url => url.pathname === "/workspace")).toBe(false); }); -it.each(["namespace", "source_workspace_id", "exported_path"])("does not write when the Page's %s changes", async field => { +it.each(["namespace", "source_vm_id", "exported_path"])("does not write when the Page's %s changes", async field => { await provider.registerRoute({ domain: hostname, targetUrl: "http://127.0.0.1:3000", tls: true }); page![field] = "different-owner"; writes.length = 0; @@ -92,7 +92,7 @@ it("publishes path-only routes through the SDK without a static or SPA fallback" spa: false, routes: [{ match: { path: "/api/", type: "prefix" }, - action: { kind: "proxy", workspace: h.workspaceId, port: 3000 }, + action: { kind: "proxy", vm: h.workspaceId, port: 3000 }, }], }, }); diff --git a/packages/adapters/src/infra/cloud-routing.test.ts b/packages/adapters/src/infra/cloud-routing.test.ts index b2b973a6c..8b13d6473 100644 --- a/packages/adapters/src/infra/cloud-routing.test.ts +++ b/packages/adapters/src/infra/cloud-routing.test.ts @@ -14,7 +14,7 @@ describe("project routes on a managed server", () => { }); expect(h.pages.create).toHaveBeenCalledOnce(); await h.infra.registerRoute(route); - expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }] }); + expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }] }); expect(h.pages.create).toHaveBeenCalledOnce(); }); @@ -25,7 +25,7 @@ describe("project routes on a managed server", () => { }); expect(h.routes.set).toHaveBeenCalledWith(route.domain, { spa: false, - routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }], + routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }], }); }); it("updates one project-owned Page repeatedly without a new workspace", async () => { @@ -33,10 +33,10 @@ describe("project routes on a managed server", () => { await h.infra.registerRoute(route); expect(h.pages.create).toHaveBeenCalledOnce(); expect(h.routes.set).toHaveBeenCalledTimes(2); - expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }] }); + expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }] }); expect(h.workspace.network.update).toHaveBeenCalledWith({ ingress_ports: [443, 3000] }); }); - it.each(["namespace", "source_workspace_id", "exported_path"])("refuses a changed %s before mutating the route", async field => { + it.each(["namespace", "source_vm_id", "exported_path"])("refuses a changed %s before mutating the route", async field => { await h.infra.registerRoute(route); h.records.get("app")![field] = "another-owner"; h.routes.set.mockClear(); h.pages.enable.mockClear(); @@ -58,8 +58,8 @@ describe("project routes on a managed server", () => { it("validates every composite backend, not only the root", async () => { await h.infra.registerRoute(route); h.routes.set.mockClear(); - await expect(h.infra.setDomainRoutes(route.domain, { routes: [{ match: { path: "/admin", type: "prefix" }, action: { kind: "proxy", workspace: "another-vm", port: 3000 } }] })).rejects.toThrow("does not belong"); - await expect(h.infra.setDomainRoutes(route.domain, { routes: [{ match: { path: "/admin", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 4000 } }] })).rejects.toThrow("unowned"); + await expect(h.infra.setDomainRoutes(route.domain, { routes: [{ match: { path: "/admin", type: "prefix" }, action: { kind: "proxy", vm: "another-vm", port: 3000 } }] })).rejects.toThrow("does not belong"); + await expect(h.infra.setDomainRoutes(route.domain, { routes: [{ match: { path: "/admin", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 4000 } }] })).rejects.toThrow("unowned"); expect(h.routes.set).not.toHaveBeenCalled(); }); it("keeps unrelated ingress ports when adding an application", async () => { diff --git a/packages/adapters/src/infra/cloud.test.ts b/packages/adapters/src/infra/cloud.test.ts index 424061879..4c498d30c 100644 --- a/packages/adapters/src/infra/cloud.test.ts +++ b/packages/adapters/src/infra/cloud.test.ts @@ -15,7 +15,7 @@ let provider: CloudInfraProvider; beforeEach(() => { vi.mocked(probePublicTlsCertificate).mockReset().mockImplementation(async domain => ({ domain, verified: true, expiresAt: expiry, issuer: "Let's Encrypt", reason: "issued" })); page = { slug: "route-one", domain: "opsh.io", url: `https://${hostname}`, custom_domain: hostname, - namespace: "ns-one", source_workspace_id: "ws-one", exported_path: "/opt/openship/cloud-docker/routes/route-one" }; + namespace: "ns-one", source_vm_id: "ws-one", exported_path: "/opt/openship/cloud-docker/routes/route-one" }; routes = vi.fn(async () => ({ data: [{ hostname, namespace: "ns-one", owner_type: "page", owner_id: "route-one", is_custom: 1 }] })); pages = { list: vi.fn(async () => ({ pages: [page] })), get: vi.fn(async () => ({ page })), diff --git a/packages/adapters/src/infra/cloud.ts b/packages/adapters/src/infra/cloud.ts index 7a8fab081..eae46c2b3 100644 --- a/packages/adapters/src/infra/cloud.ts +++ b/packages/adapters/src/infra/cloud.ts @@ -109,7 +109,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { } async getQuota(): Promise { - return this.client.workspaces.getQuota(); + return this.client.vms.getQuota(); } // ── Domain / Slug checks ─────────────────────────────────────────────── @@ -199,7 +199,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { if ( !page || (this.workspaceId && - (page.source_workspace_id !== this.workspaceId || + (page.source_vm_id !== this.workspaceId || page.exported_path !== `${this.routeRoot}/${page.slug}`)) ) throw disconnected(); @@ -230,11 +230,11 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { if (route.protection) throw new Error("Password protection is not supported by the Cloud edge."); if (route.webhookProxy) throw new Error("Managed application routes cannot proxy control-plane webhooks"); - const proxyTargets = new Map(); + const proxyTargets = new Map(); for (const location of route.proxyLocations ?? []) { if (location.external) continue; proxyTargets.set(location.targetUrl, { - workspace: this.scope.workspaceId, + vm: this.scope.workspaceId, port: await this.scope.resolveUrl(location.targetUrl), }); } @@ -251,7 +251,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { trailingSlash: route.trailingSlash, }, { - root: port ? { workspace: this.scope.workspaceId, port } : undefined, + root: port ? { vm: this.scope.workspaceId, port } : undefined, staticPage: route.staticRoot ? slug : undefined, proxyTargets, }, @@ -300,7 +300,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { } if ( page.namespace === this.options.namespace && - page.source_workspace_id === this.workspaceId && + page.source_vm_id === this.workspaceId && page.exported_path === `${this.routeRoot}/${page.slug}` ) hostnames.push(...cloudPageHostnames(page)); @@ -348,14 +348,14 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { ) throw new Error("Invalid cloud routing port"); const pathsOnly = hostPort === undefined && !staticRoot; - if (pathsOnly && !input?.routes.some((rule) => rule.action.kind === "proxy")) + if (pathsOnly && !input?.routes?.some((rule) => rule.action.kind === "proxy")) throw new Error("A route needs a process or a static release"); const slug = this.routeSlug(hostname, custom); let routes = input ?? { routes: [ { match: { path: "/", type: "prefix" as const }, - action: { kind: "proxy" as const, workspace: this.scope.workspaceId, port: hostPort! }, + action: { kind: "proxy" as const, vm: this.scope.workspaceId, port: hostPort! }, }, ], }; @@ -375,7 +375,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { } const assertPage = () => { if ( - page!.source_workspace_id !== this.workspaceId || + page!.source_vm_id !== this.workspaceId || page!.namespace !== this.options.namespace || page!.exported_path !== path ) @@ -408,7 +408,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { ); if (page) { const deployed = await this.pages.deploy(slug, { - workspace_id: this.scope.workspaceId, + vm_id: this.scope.workspaceId, path, }); if (!deployed.success) throw new Error("Could not publish the static release"); @@ -422,7 +422,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { if (!page) { try { await this.pages.create({ - workspace_id: this.scope.workspaceId, + vm_id: this.scope.workspaceId, path, name: `Route ${hostname}`, slug, @@ -440,9 +440,9 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { if (page.custom_domain !== hostname) await this.pages.connectDomain(slug, { domain: hostname }); } - const ports = routes.routes.flatMap((rule) => + const ports = (routes.routes ?? []).flatMap((rule) => rule.action.kind === "proxy" && - rule.action.workspace === this.workspaceId && + rule.action.vm === this.workspaceId && rule.action.port ? [rule.action.port] : [], @@ -462,7 +462,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { // would leave a failed release live at the edge. if (hadPage && restored.trim() === "restored") { if ( - !(await this.pages.deploy(slug, { workspace_id: this.scope.workspaceId, path })) + !(await this.pages.deploy(slug, { vm_id: this.scope.workspaceId, path })) .success ) throw new Error("Could not republish the previous static release"); @@ -490,9 +490,9 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { async resolveRoutingTarget( containerId: string, port: number, - ): Promise<{ workspace: string; port: number }> { + ): Promise<{ vm: string; port: number }> { return { - workspace: this.scope.workspaceId, + vm: this.scope.workspaceId, port: await this.scope.resolveTarget(containerId, port), }; } @@ -513,9 +513,9 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { throw new AppError("Domain does not belong to this project", 404, "DOMAIN_NOT_FOUND"); await this.assertRouteTargets(input); await this.ensureIngressPorts( - input.routes.flatMap((route) => + (input.routes ?? []).flatMap((route) => route.action.kind === "proxy" && - route.action.workspace === this.workspaceId && + route.action.vm === this.workspaceId && route.action.port ? [route.action.port] : [], @@ -534,7 +534,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { const { page } = await this.pages.get(input.static.page); if ( page.namespace !== this.options.namespace || - page.source_workspace_id !== this.workspaceId || + page.source_vm_id !== this.workspaceId || page.exported_path !== `${this.routeRoot}/${page.slug}` ) throw new AppError( @@ -545,11 +545,11 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { } const ports = new Set(); if (publishedPort !== undefined) ports.add(publishedPort); - for (const route of input.routes) { + for (const route of input.routes ?? []) { if ( route.action.kind === "proxy" && !route.action.origin && - (route.action.workspace !== this.workspaceId || + (route.action.vm !== this.workspaceId || typeof route.action.port !== "number") ) throw new AppError( @@ -570,7 +570,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { * only ensures the project's validated route ports can receive edge traffic. */ private async ensureIngressPorts(add: number[]) { if (!add.length) return; - const workspace = this.client.workspace(this.scope.workspaceId); + const workspace = this.client.vm(this.scope.workspaceId); const network = await workspace.network.get(); const current = Array.isArray(network.ingress_ports) ? (network.ingress_ports as number[]) : []; const next = [...new Set([...current, ...add])]; @@ -593,7 +593,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { * is uncertain state and must retain the deletion fence. */ private isForeignProjectRoute(page: { slug: string; - source_workspace_id?: string | null; + source_vm_id?: string | null; exported_path?: string | null; }): boolean { const prefix = `${CLOUD_DOCKER_ROUTE_ROOT}/projects/`; @@ -602,7 +602,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { if ( !this.routeRoot || !canonicalRoot(this.routeRoot) || - !page.source_workspace_id?.trim() || + !page.source_vm_id?.trim() || !page.exported_path || !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(page.slug) ) @@ -629,7 +629,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider { const page = await this.pageForDomain(domain); if (!page) return "absent"; if ( - page.source_workspace_id !== this.workspaceId || + page.source_vm_id !== this.workspaceId || page.exported_path !== `${this.routeRoot}/${page.slug}` ) { if (mode === "project-cleanup" && this.isForeignProjectRoute(page)) return "foreign"; diff --git a/packages/adapters/src/oblien-contract.test.ts b/packages/adapters/src/oblien-contract.test.ts new file mode 100644 index 000000000..66507f17b --- /dev/null +++ b/packages/adapters/src/oblien-contract.test.ts @@ -0,0 +1,169 @@ +import { createServer } from "node:http"; +import { once } from "node:events"; +import { afterEach, expect, it, vi } from "vitest"; +import { DEFAULT_API_BASE_URL, Oblien as OfficialOblien } from "oblien"; +import { Oblien, cloudWorkspaceCreationFailure } from "./oblien"; +import { + cloudBillingContract, + oblienApiBaseUrl, + oblienApiUrl, + toOblienVmOffer, +} from "./oblien-contract"; + +afterEach(() => vi.unstubAllGlobals()); + +it("inherits the published SDK default for the adapter and official client", async () => { + const urls: string[] = []; + vi.stubGlobal( + "fetch", + vi.fn(async (input: string | URL) => { + urls.push(String(input)); + return Response.json({ success: true, vms: [], namespaces: [] }); + }), + ); + await new Oblien({ token: "fixture" }).vms.list(); + await new OfficialOblien({ token: "fixture" }).vms.list(); + expect(DEFAULT_API_BASE_URL).toBe("https://api.oblien.com/v1"); + expect(oblienApiBaseUrl().href).toBe(DEFAULT_API_BASE_URL); + expect(urls).toEqual([`${DEFAULT_API_BASE_URL}/vms`, `${DEFAULT_API_BASE_URL}/vms`]); +}); + +it("keeps version and proxy mounts in real SDK JSON, Page, route and SSE requests without replaying a failed create", async () => { + const calls: Array<{ path: string; body: Record }> = []; + const server = createServer(async (req, res) => { + let raw = ""; + for await (const chunk of req) raw += chunk; + calls.push({ path: req.url!, body: raw ? JSON.parse(raw) : {} }); + if (req.headers.authorization !== "Bearer fixture") { + res.writeHead(401).end(); + return; + } + if (req.url === "/proxy/v1/vms/vm-a/stats/stream") { + res.writeHead(200, { "Content-Type": "text/event-stream" }); + res.end('data: {"cpu":12}\n\n'); + return; + } + res.setHeader("Content-Type", "application/json"); + if (req.url === "/proxy/v1/vms" && req.method === "POST") { + res.writeHead(422).end( + JSON.stringify({ + success: false, + code: "CREATE_FAILED", + details: { vm_id: "vm-failed" }, + }), + ); + return; + } + if (req.url === "/proxy/v1/vms") { + res.end( + JSON.stringify({ success: true, vms: [{ id: "vm-a", namespace: "tenant-a" }], total: 1 }), + ); + return; + } + if (req.url === "/proxy/v1/vms/vm-a") { + res.end(JSON.stringify({ success: true, vm: { id: "vm-a", namespace: "tenant-a" } })); + return; + } + if (req.url === "/proxy/v1/vms/vm-a/workloads/process-a") { + res.end(JSON.stringify({ success: true, workload: { id: "process-a", status: "running" } })); + return; + } + if (req.url === "/proxy/v1/pages") { + res.end(JSON.stringify({ success: true, page: { slug: "site", source_vm_id: "vm-a" } })); + return; + } + if (req.url === "/proxy/v1/domain/routes/site.example") { + res.end(JSON.stringify({ success: true })); + return; + } + res.writeHead(404).end(JSON.stringify({ success: false })); + }); + server.listen(0, "127.0.0.1"); + await once(server, "listening"); + const address = server.address(); + if (!address || typeof address === "string") throw new Error("No test listener"); + try { + const client = new Oblien({ + token: "fixture", + baseUrl: `http://127.0.0.1:${address.port}/proxy/v1`, + }); + expect((await client.vms.list()).vms[0]?.id).toBe("vm-a"); + expect((await client.vm("vm-a").get()).namespace).toBe("tenant-a"); + expect(await client.vm("vm-a").workloads.get("process-a")).toMatchObject({ + id: "process-a", + status: "running", + }); + await client.pages.create({ vm_id: "vm-a", name: "Site", slug: "site", path: "/dist" }); + await client.routes.set("site.example", { + routes: [{ match: { path: "/" }, action: { kind: "proxy", vm: "vm-a", port: 3000 } }], + }); + for await (const sample of client.streamWorkspaceMetrics("vm-a")) { + expect(sample).toEqual({ cpu: 12 }); + break; + } + const failure = await client.vms.create({ wait_ready: false }).catch((error) => error); + expect(cloudWorkspaceCreationFailure(failure)).toMatchObject({ workspaceId: "vm-failed" }); + expect( + calls.filter((call) => call.path === "/proxy/v1/vms" && call.body.wait_ready === false), + ).toHaveLength(1); + expect(calls.every((call) => call.path.startsWith("/proxy/v1/"))).toBe(true); + expect(calls.find((call) => call.path.endsWith("/pages"))?.body).toMatchObject({ + vm_id: "vm-a", + }); + expect(JSON.stringify(calls)).not.toContain("workspace_id"); + } finally { + server.closeAllConnections(); + await new Promise((resolve, reject) => + server.close((error) => (error ? reject(error) : resolve())), + ); + } +}); + +it.each([undefined, null, [], { status: "running" }])( + "rejects an invalid native workload record: %j", + async (workload) => { + vi.stubGlobal( + "fetch", + vi.fn(async () => Response.json({ success: true, workload })), + ); + await expect( + new Oblien({ token: "fixture" }).vm("vm-a").workloads.get("process-a"), + ).rejects.toMatchObject({ code: "OBLIEN_WORKLOAD_INVALID" }); + }, +); + +it("preserves paid limits, zero and unlimited counts while leaving customer metadata opaque", () => { + const metadata = { + workspace: "customer-chosen", + max_workspaces: "opaque", + capacity: { vcpus: 8, memoryMb: 16, diskGb: 32, workspaces: 42 }, + }; + const saved = { + unitAmount: 12000, + resourceLimits: { max_workspaces: null, max_vcpus: 8 }, + capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, workspaces: 0 }, + policy: { overdraft: 0, onOverdraftAction: "stop_workspaces" as const }, + metadata, + }; + const native = toOblienVmOffer(saved); + expect(native).toEqual({ + unitAmount: 12000, + resourceLimits: { max_vms: null, max_vcpus: 8 }, + capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, vms: 0 }, + policy: { overdraft: 0, onOverdraftAction: "stop_vms" }, + metadata, + }); + expect(cloudBillingContract({ success: true, subscription: { offer: native } })).toEqual({ + success: true, + subscription: { offer: saved }, + }); + expect(native.metadata).toBe(metadata); + expect(saved.capacity.workspaces).toBe(0); +}); + +it("rejects request paths that escape a versioned mount", () => { + const base = oblienApiBaseUrl("https://provider.example/proxy/v2"); + for (const path of ["../vms", "/../vms", "https://other.example/vms", "//other.example/vms"]) + expect(() => oblienApiUrl(base, path)).toThrow(); + expect(oblienApiUrl(base, "/vms").href).toBe("https://provider.example/proxy/v2/vms"); +}); diff --git a/packages/adapters/src/oblien-contract.ts b/packages/adapters/src/oblien-contract.ts new file mode 100644 index 000000000..0b0a5367d --- /dev/null +++ b/packages/adapters/src/oblien-contract.ts @@ -0,0 +1,108 @@ +import { DEFAULT_API_BASE_URL } from "oblien"; + +/** The SDK owns the default. An operator override is a complete API mount. */ +export function oblienApiBaseUrl(input = DEFAULT_API_BASE_URL): URL { + const base = new URL(input); + if ( + base.username || + base.password || + base.search || + base.hash || + (base.protocol !== "https:" && + !(base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname))) + ) { + throw new Error("Oblien API URL must use HTTPS (HTTP is allowed for localhost tests)"); + } + base.pathname = base.pathname.replace(/\/+$/, ""); + return base; +} + +export function oblienApiUrl(base: URL, path: string): URL { + if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(path)) + throw new Error("Oblien request escaped its API origin"); + const root = base.toString().replace(/\/+$/, "") + "/"; + const url = new URL(path.replace(/^\//, ""), root); + if (url.origin !== base.origin || !url.pathname.startsWith(new URL(root).pathname)) + throw new Error("Oblien request escaped its API mount"); + return url; +} + +/** OpenShip's saved Cloud workspace policies are its own persisted contract. + * Map that count to provider VMs only at the external boundary. */ +export function toOblienVmLimits(limits: T) { + const { max_workspaces, ...rest } = limits; + return { ...rest, max_vms: max_workspaces }; +} + +export function toOblienVmCapacity(capacity: T) { + const { workspaces, ...rest } = capacity; + return { ...rest, vms: workspaces }; +} + +export function toOblienVmPolicy( + policy: T, +) { + const { onOverdraftAction, ...rest } = policy; + return { + ...rest, + onOverdraftAction: + onOverdraftAction === "stop_workspaces" ? ("stop_vms" as const) : onOverdraftAction, + }; +} + +export function toOblienVmOffer< + T extends { + resourceLimits?: { max_workspaces?: number | null }; + capacity?: { vcpus: number; memoryMb: number; diskGb: number; workspaces: number }; + policy?: { onOverdraftAction?: "stop_workspaces" | "block" }; + }, +>(offer: T) { + const { resourceLimits, capacity, policy, ...rest } = offer; + return { + ...rest, + ...(resourceLimits ? { resourceLimits: toOblienVmLimits(resourceLimits) } : {}), + ...(capacity ? { capacity: toOblienVmCapacity(capacity) } : {}), + ...(policy ? { policy: toOblienVmPolicy(policy) } : {}), + }; +} + +/** Decode only documented billing-contract nodes. Metadata, signatures and + * customer dictionaries stay opaque; no recursive word replacement is used. */ +export function cloudBillingContract(value: unknown, depth = 0): unknown { + if (!value || typeof value !== "object" || Array.isArray(value)) return value; + if (depth > 12) throw new Error("Oblien returned an invalid billing contract"); + const source = value as Record; + const result = { ...source }; + if ("vcpus" in source && "memoryMb" in source && "diskGb" in source) { + result.workspaces = source.vms; + delete result.vms; + } + if ( + source.resourceLimits && + typeof source.resourceLimits === "object" && + !Array.isArray(source.resourceLimits) + ) { + const { max_vms, ...rest } = source.resourceLimits as Record; + result.resourceLimits = { ...rest, max_workspaces: max_vms }; + } + if (source.onOverdraftAction === "stop_vms") result.onOverdraftAction = "stop_workspaces"; + for (const key of [ + "data", + "capacity", + "quote", + "current", + "next", + "subscription", + "offer", + "policy", + "pendingChange", + "change", + "pendingCheckout", + "checkout", + ]) + if (source[key] && typeof source[key] === "object") + result[key] = cloudBillingContract(source[key], depth + 1); + if (Array.isArray(source.presets)) + result.presets = source.presets.map((item) => cloudBillingContract(item, depth + 1)); + return result; +} diff --git a/packages/adapters/src/oblien-metrics.test.ts b/packages/adapters/src/oblien-metrics.test.ts index 4068260b6..67d449c5b 100644 --- a/packages/adapters/src/oblien-metrics.test.ts +++ b/packages/adapters/src/oblien-metrics.test.ts @@ -32,7 +32,7 @@ it("keeps provider credentials server-side, rejects redirects and releases the r } expect(cancel).toHaveBeenCalledOnce(); const [url, request] = fetcher.mock.calls[0]! as unknown as [URL, RequestInit]; - expect(url.href).toBe("https://api.oblien.com/workspace/ws-owned/stats/stream"); + expect(url.href).toBe("https://api.oblien.com/v1/vms/ws-owned/stats/stream"); expect(request.redirect).toBe("error"); expect(new Headers(request.headers).get("Authorization")).toBe("Bearer scoped-token"); expect(request.signal?.aborted).toBe(true); diff --git a/packages/adapters/src/oblien.test.ts b/packages/adapters/src/oblien.test.ts index 52b806a6e..b3748bca9 100644 --- a/packages/adapters/src/oblien.test.ts +++ b/packages/adapters/src/oblien.test.ts @@ -7,7 +7,7 @@ describe("Oblien SDK transport", () => { status: 429, headers: { "Retry-After": retryAfter }, })); vi.stubGlobal("fetch", fetcher); - const error = await new Oblien({ token: "test" }).workspaces.create({ wait_ready: false }).catch(error => error); + const error = await new Oblien({ token: "test" }).vms.create({ wait_ready: false }).catch(error => error); expect(error).toMatchObject({ status: 429, code: "OBLIEN_RATE_LIMITED" }); expect(error.details.retryAfterSeconds).toBeGreaterThan(0); expect(error.details.retryAfterSeconds).toBeLessThanOrEqual(30); @@ -17,7 +17,7 @@ describe("Oblien SDK transport", () => { }); it.each(["invalid", "-1", "99999999999999999999999"])("ignores invalid Retry-After %s", async (retryAfter) => { vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 503, headers: { "Retry-After": retryAfter } }))); - const error = await new Oblien({ token: "test" }).workspaces.get("ws").catch(error => error); + const error = await new Oblien({ token: "test" }).vms.get("ws").catch(error => error); expect(error.status).toBe(503); expect(error.details).toBeUndefined(); }); @@ -30,7 +30,7 @@ describe("Oblien SDK transport", () => { vi.stubGlobal("fetch", fetcher); const choices = await new Oblien({ token: "fixture-token" }).listOutboundIps(); expect(choices).toEqual([{ ip: "8.8.4.4", countryCode: "US" }, { ip: "1.1.1.1", countryCode: null }]); - expect(String(fetcher.mock.calls[0]?.[0])).toBe("https://api.oblien.com/zone/mine"); + expect(String(fetcher.mock.calls[0]?.[0])).toBe("https://api.oblien.com/v1/zone/mine"); expect(JSON.stringify(choices)).not.toMatch(/pool-user|pool-password|private-id/); }); it("rejects an unreadable pool instead of presenting a successful empty picker", async () => { @@ -40,13 +40,13 @@ describe("Oblien SDK transport", () => { it("propagates an HTTP quota refusal even without success:false", async () => { vi.stubGlobal("fetch", vi.fn(async () => Response.json({ error: "NAMESPACE_LIMIT_REACHED" }, { status: 409 }))); const client = new Oblien({ token: "scoped-test-token" }); - const error = await client.workspaces.create({ namespace: "tenant-a", wait_ready: false }).catch(error => error); + const error = await client.vms.create({ namespace: "tenant-a", wait_ready: false }).catch(error => error); expect(error).toMatchObject({ status: 409, code: "NAMESPACE_LIMIT_REACHED" }); expect(cloudWorkspaceCreationFailure(error)).toMatchObject({ capacityRejected: true, rejected: true }); }); it("rejects an error HTTP status even when a payload claims success", async () => { - vi.stubGlobal("fetch", vi.fn(async () => Response.json({ success: true, workspace: { id: "not-created" } }, { status: 503 }))); - await expect(new Oblien({ token: "test" }).workspaces.create({ wait_ready: false })).rejects.toMatchObject({ status: 503 }); + vi.stubGlobal("fetch", vi.fn(async () => Response.json({ success: true, vm: { id: "not-created" } }, { status: 503 }))); + await expect(new Oblien({ token: "test" }).vms.create({ wait_ready: false })).rejects.toMatchObject({ status: 503 }); }); it.each(["NAMESPACE_LIMIT_REACHED", "SANDBOX_LIMIT_REACHED", "POOL_LIMIT_REACHED"])( "normalizes the provider's HTTP 200 %s refusal", @@ -56,31 +56,31 @@ describe("Oblien SDK transport", () => { vi.fn(async () => Response.json({ valid: false, error: "capacity exceeded", code })), ); await expect( - new Oblien({ token: "test" }).workspaces.create({ wait_ready: false }), + new Oblien({ token: "test" }).vms.create({ wait_ready: false }), ).rejects.toMatchObject({ status: 409, code }); }, ); it("keeps official request formatting and never follows authenticated redirects", async () => { - const fetcher = vi.fn(async () => Response.json({ success: true, workspace: { id: "ws-a", namespace: "tenant-a" } })); + const fetcher = vi.fn(async () => Response.json({ success: true, vm: { id: "ws-a", namespace: "tenant-a" } })); vi.stubGlobal("fetch", fetcher); const client = new Oblien({ clientId: "test-owner", clientSecret: "test-secret" }); - await client.workspaces.create({ namespace: "tenant-a", cpus: 2, wait_ready: false }); + await client.vms.create({ namespace: "tenant-a", cpus: 2, wait_ready: false }); const [url, init] = fetcher.mock.calls[0]! as unknown as [URL, RequestInit]; - expect(url.pathname).toBe("/workspace"); expect(init.redirect).toBe("error"); expect(init.signal).toBeInstanceOf(AbortSignal); + expect(url.pathname).toBe("/v1/vms"); expect(init.redirect).toBe("error"); expect(init.signal).toBeInstanceOf(AbortSignal); expect(JSON.parse(init.body as string)).toMatchObject({ namespace: "tenant-a", config: { cpus: 2 } }); }); it("tracks token refresh and authentication restore without mixing scopes", async () => { const headers: Headers[] = []; - vi.stubGlobal("fetch", vi.fn(async (_url, init) => { headers.push(new Headers(init.headers)); return Response.json({ success: true, workspaces: [] }); })); + vi.stubGlobal("fetch", vi.fn(async (_url, init) => { headers.push(new Headers(init.headers)); return Response.json({ success: true, vms: [] }); })); const client = new Oblien({ clientId: "test-owner", clientSecret: "test-secret" }); - await client.workspaces.list(); client.setToken("namespace-token"); await client.workspaces.list(); client._http.restoreAuth(); await client.workspaces.list(); + await client.vms.list(); client.setToken("namespace-token"); await client.vms.list(); client._http.restoreAuth(); await client.vms.list(); expect(headers[0]!.get("X-Client-ID")).toBe("test-owner"); expect(headers[1]!.get("Authorization")).toBe("Bearer namespace-token"); expect(headers[1]!.has("X-Client-Secret")).toBe(false); expect(headers[2]!.get("X-Client-ID")).toBe("test-owner"); expect(headers[2]!.has("Authorization")).toBe(false); }); it("does not expose provider error details or tokens", async () => { vi.stubGlobal("fetch", vi.fn(async () => Response.json({ error: "scope_denied", message: "private-secret", details: { token: "private-secret" } }, { status: 403 }))); - const error = await new Oblien({ token: "test" }).workspaces.get("ws-b").catch(error => error); + const error = await new Oblien({ token: "test" }).vms.get("ws-b").catch(error => error); expect(error.message).not.toContain("private-secret"); expect(error.details).toBeUndefined(); expect(error.status).toBe(403); expect(cloudWorkspaceCreationFailure(error)).toMatchObject({ capacityRejected: false, rejected: true }); }); @@ -108,7 +108,7 @@ describe("Oblien SDK transport", () => { ), ), ); - const error = await new Oblien({ token: "test" }).workspaces + const error = await new Oblien({ token: "test" }).vms .create({ wait_ready: false }) .catch((error) => error); expect(error).toMatchObject({ @@ -159,7 +159,7 @@ describe("Oblien SDK transport", () => { ), ), ); - const error = await new Oblien({ token: "test" }).workspaces + const error = await new Oblien({ token: "test" }).vms .create({ wait_ready: false }) .catch((error) => error); expect(error.details.violations).toEqual([ @@ -212,7 +212,7 @@ describe("Oblien SDK transport", () => { ), ), ); - const error = await new Oblien({ token: "test" }).workspaces + const error = await new Oblien({ token: "test" }).vms .create({ wait_ready: false }) .catch((error) => error); expect(error.details).toBeUndefined(); @@ -228,7 +228,7 @@ describe("Oblien SDK transport", () => { code: "CREATE_FAILED", message: "private-account-data", details: { - workspace_id: "ws-failed", + vm_id: "ws-failed", token: "private-secret", workspace: { env: { SECRET: "private-secret" } }, }, @@ -237,13 +237,13 @@ describe("Oblien SDK transport", () => { ), ), ); - const error = await new Oblien({ token: "test" }).workspaces + const error = await new Oblien({ token: "test" }).vms .create({ wait_ready: false }) .catch((error) => error); expect(error).toMatchObject({ status: 422, code: "CREATE_FAILED", - details: { workspace_id: "ws-failed" }, + details: { vm_id: "ws-failed" }, }); expect(cloudWorkspaceCreationFailure(error)).toEqual({ workspaceId: "ws-failed", capacityRejected: false, rejected: false }); expect(JSON.stringify(error)).not.toContain("private-"); @@ -257,7 +257,7 @@ describe("Oblien SDK transport", () => { vi.stubGlobal("fetch", vi.fn(async () => Response.json({ error: code, message: "private-account-data", details: { violations: ["private-namespace-name"] }, }, { status: 400 }))); - const error = await new Oblien({ token: "scoped-test-token" }).workspaces.get("ws-a").catch(error => error); + const error = await new Oblien({ token: "scoped-test-token" }).vms.get("ws-a").catch(error => error); expect(error).toMatchObject({ status: 400, code }); expect(error.message).toContain(description); expect(error.message).not.toContain("private-"); @@ -272,7 +272,7 @@ describe("Oblien SDK transport", () => { const fetcher = vi.fn(); vi.stubGlobal("fetch", fetcher); const controller = new AbortController(); const reason = new Error("Deployment cancelled"); controller.abort(reason); - await expect(new Oblien({ token: "test" }).workspaces.create({ wait_ready: false }, { signal: controller.signal })).rejects.toBe(reason); + await expect(new Oblien({ token: "test" }).vms.create({ wait_ready: false }, { signal: controller.signal })).rejects.toBe(reason); expect(fetcher).not.toHaveBeenCalled(); }); it("preserves SDK cancellation during a request instead of returning a retryable provider error", async () => { @@ -283,7 +283,7 @@ describe("Oblien SDK transport", () => { }))); const controller = new AbortController(); const reason = new Error("Deployment cancelled"); - const pending = new Oblien({ token: "test" }).workspaces.create({ wait_ready: false }, { signal: controller.signal }); + const pending = new Oblien({ token: "test" }).vms.create({ wait_ready: false }, { signal: controller.signal }); const result = expect(pending).rejects.toBe(reason); controller.abort(reason); await result; diff --git a/packages/adapters/src/oblien.ts b/packages/adapters/src/oblien.ts index 530ad51ad..aabc70696 100644 --- a/packages/adapters/src/oblien.ts +++ b/packages/adapters/src/oblien.ts @@ -1,4 +1,5 @@ import { workspaceMetricsStream } from "./oblien-metrics"; +import { oblienApiBaseUrl, oblienApiUrl } from "./oblien-contract"; import { diagnosticTraceparent, reportCaughtError as observeCaughtError } from "@repo/core/diagnostics"; import { withDiagnosticSpan } from "@repo/core/diagnostics/node"; import { @@ -36,13 +37,13 @@ const resourceUnits = { cpus: "vCPU", memory_mb: "MB", disk_size_mb: "MB", - workspaces: "workspaces", + vms: "VMs", } as const; const resourceLabels = { cpus: "CPU", memory_mb: "RAM", disk_size_mb: "Disk", - workspaces: "Workspaces", + vms: "VMs", } as const; type CapacityViolation = { resource: keyof typeof resourceUnits; @@ -91,7 +92,7 @@ function namespaceCapacityDetails(raw: unknown) { } function workspaceIdFromDetails(details: unknown): string | undefined { - const id = (details as { workspace_id?: unknown } | null)?.workspace_id; + const id = (details as { vm_id?: unknown } | null)?.vm_id; return typeof id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(id) ? id : undefined; } @@ -140,7 +141,7 @@ function providerError(status: number, body: unknown, retryAfter: string | null const retryAfterSeconds = Number.isSafeInteger(delay) && delay >= 0 && delay <= 86400 ? delay : undefined; const details = capacity || workspaceId || retryAfterSeconds !== undefined ? { ...capacity, - ...(workspaceId ? { workspace_id: workspaceId } : {}), + ...(workspaceId ? { vm_id: workspaceId } : {}), ...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}), } : undefined; const requestId = @@ -153,7 +154,7 @@ function providerError(status: number, body: unknown, retryAfter: string | null const scope = value.enforcementScope === "namespace_allocated_pool" ? "namespace total" - : value.resource === "workspaces" + : value.resource === "vms" ? "namespace workspace count" : "per workspace"; return ( @@ -219,11 +220,7 @@ export class Oblien extends OblienSdk { invalidate?(rejectedToken: string): Promise; }; }) { - const base = new URL(options.baseUrl ?? "https://api.oblien.com"); - if (base.username || base.password || base.search || base.hash || - (base.protocol !== "https:" && !(base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname)))) { - throw new Error("Oblien API URL must use HTTPS (HTTP is allowed for localhost tests)"); - } + const base = oblienApiBaseUrl(options.baseUrl); super(options); const original = new Headers(); if ("token" in options) { if (options.token) original.set("Authorization", `Bearer ${options.token}`); } @@ -262,7 +259,7 @@ export class Oblien extends OblienSdk { const renewal = ensureAuth(); if (renewal) await renewal; subscriptionSignal.throwIfAborted(); - const url = new URL(`/workspace/${encodeURIComponent(workspaceId)}/stats/stream`, base); + const url = oblienApiUrl(base, `/vms/${encodeURIComponent(workspaceId)}/stats/stream`); const headers = new Headers(auth); headers.set("Accept", "text/event-stream"); const response = await fetch(url, { headers, redirect: "error", signal: subscriptionSignal }); @@ -271,7 +268,7 @@ export class Oblien extends OblienSdk { }, signal); this._http.request = async (request: RequestOptions): Promise => withDiagnosticSpan({ kind: "operation", component: "oblien", operation: "oblien.request", method: request.method }, async () => { request.signal?.throwIfAborted(); - const url = new URL(request.path, base); + const url = oblienApiUrl(base, request.path); if (url.origin !== base.origin || url.username || url.password) throw new Error("Oblien request escaped its API origin"); const renewal = ensureAuth(); if (renewal) await renewal; @@ -284,7 +281,7 @@ export class Oblien extends OblienSdk { headers.set("Accept", "application/json"); headers.set("Content-Type", "application/json"); for (const [key, value] of auth) headers.set(key, value); - const waitingCreate = request.method === "POST" && /^\/workspace\/?$/.test(url.pathname) && + const waitingCreate = request.method === "POST" && /^\/vms\/?$/.test(request.path) && (request.body as { wait_ready?: boolean } | undefined)?.wait_ready !== false; let response: Response; let body: unknown; @@ -323,18 +320,15 @@ export class Oblien extends OblienSdk { } return body as T; }, { kind: "client" }); - // SDK 2.5 types get() as WorkloadInfo but leaves the HTTP envelope intact, - // unlike create() and list(). Normalize at the provider boundary so process - // control and server-resize recovery read the same saved workload record. - const getWorkload = this.workspaces.workloads.get.bind(this.workspaces.workloads); - this.workspaces.workloads.get = async (workspaceId, workloadId) => { - const response = await getWorkload(workspaceId, workloadId); - const workload = response.workload ?? response; + // Validate the native record before process control and resize recovery. + const getWorkload = this.vms.workloads.get.bind(this.vms.workloads); + this.vms.workloads.get = async (workspaceId, workloadId) => { + const workload = await getWorkload(workspaceId, workloadId); if (!workload || typeof workload !== "object" || Array.isArray(workload) || !("id" in workload) || typeof workload.id !== "string") { throw new OblienError("Oblien returned an invalid application process record", 502, "OBLIEN_WORKLOAD_INVALID"); } - return workload as typeof response; + return workload; }; } } diff --git a/packages/adapters/src/runtime/cloud-deploy-static.test.ts b/packages/adapters/src/runtime/cloud-deploy-static.test.ts index 155b826e3..c06209b7a 100644 --- a/packages/adapters/src/runtime/cloud-deploy-static.test.ts +++ b/packages/adapters/src/runtime/cloud-deploy-static.test.ts @@ -6,7 +6,7 @@ beforeEach(() => { h = managedRoutingFixture(); }); describe("shared static releases on managed ingress", () => { it.each([".", "dist"])("normalizes %s under its owned release and exports only the project route tree", async output => { await h.infra.registerRoute({ domain: "site.opsh.io", staticRoot: `${h.scope.staticReleaseRoot}/release-a/${output}`, tls: true }); - expect(h.pages.create).toHaveBeenCalledWith(expect.objectContaining({ workspace_id: h.workspaceId, path: `${h.paths.routes}/site` })); + expect(h.pages.create).toHaveBeenCalledWith(expect.objectContaining({ vm_id: h.workspaceId, path: `${h.paths.routes}/site` })); expect(h.scope.resolveUrl).not.toHaveBeenCalled(); expect(h.routes.set).toHaveBeenCalledOnce(); }); @@ -33,7 +33,7 @@ describe("shared static releases on managed ingress", () => { h.routes.set.mockRejectedValueOnce(new Error("route table unavailable")); await expect(h.infra.registerRoute({ domain: "site.opsh.io", staticRoot: `${h.scope.staticReleaseRoot}/release-b`, tls: true })).rejects.toThrow("route table unavailable"); expect(h.pages.deploy).toHaveBeenCalledTimes(2); - expect(h.pages.deploy).toHaveBeenLastCalledWith("site", { workspace_id: h.workspaceId, path: `${h.paths.routes}/site` }); + expect(h.pages.deploy).toHaveBeenLastCalledWith("site", { vm_id: h.workspaceId, path: `${h.paths.routes}/site` }); }); }); @@ -48,7 +48,7 @@ it("switches a live proxy hostname to exported files and back without claiming a }); expect(h.records.get("site")).toBe(page); expect(h.pages.deploy).toHaveBeenCalledWith("site", { - workspace_id: h.workspaceId, + vm_id: h.workspaceId, path: `${h.paths.routes}/site`, }); expect(JSON.stringify(h.routes.set.mock.lastCall)).toContain('"static"'); diff --git a/packages/adapters/src/runtime/cloud-host-build-refusal.test.ts b/packages/adapters/src/runtime/cloud-host-build-refusal.test.ts index ae6213923..bca0b073f 100644 --- a/packages/adapters/src/runtime/cloud-host-build-refusal.test.ts +++ b/packages/adapters/src/runtime/cloud-host-build-refusal.test.ts @@ -16,7 +16,7 @@ const config = { target: "cloud" as const, cloudToken: "namespace-token", cloudN beforeEach(() => { const row = { id: "vm-a", namespace: "namespace-a", status: "running" }; - fixture.client = { workspace: vi.fn(() => ({ get: vi.fn(async () => row), workloads: { list: vi.fn(async () => []) } })), workspaces: { get: vi.fn(async () => row), create: vi.fn(), delete: vi.fn() } }; + fixture.client = { vm: vi.fn(() => ({ get: vi.fn(async () => row), workloads: { list: vi.fn(async () => []) } })), vms: { get: vi.fn(async () => row), create: vi.fn(), delete: vi.fn() } }; }); afterEach(async () => { for (const platform of platforms.splice(0)) await platform.runtime.dispose?.(); @@ -35,13 +35,13 @@ describe("Cloud changes the execution destination, not the deployment runtime", expect(platform.executor).toBeInstanceOf(CloudWorkspaceExecutor); expect(platform.localHost).toBe(false); expect(platform.system).toBeNull(); - expect(fixture.client.workspaces.create).not.toHaveBeenCalled(); + expect(fixture.client.vms.create).not.toHaveBeenCalled(); }); it("has no implicit host when a Cloud destination is absent", async () => { const platform = await make({ cloudServer: undefined }); await expect(platform.runtime.build({ projectId: "project-a", buildStrategy: "local" } as never)).rejects.toMatchObject({ code: "DEPLOYMENT_SERVER_REQUIRED" }); expect(platform.executor).toBeNull(); - expect(fixture.client.workspace).not.toHaveBeenCalled(); + expect(fixture.client.vm).not.toHaveBeenCalled(); }); it.each(["docker", "bare"] as const)("requires namespace-scoped credentials for %s", async runtime => { await expect(make({ runtime, cloudToken: undefined })).rejects.toThrow("organization-scoped credentials"); @@ -52,14 +52,14 @@ describe("Cloud changes the execution destination, not the deployment runtime", const transfer = vi.spyOn(platform.executor!, "transferIn"); await expect(platform.runtime.build({ projectId: "project-a", localPath: "/etc", buildStrategy: "local" } as never)).rejects.toThrow(/control-plane|host/i); expect(transfer).not.toHaveBeenCalled(); - expect(fixture.client.workspaces.create).not.toHaveBeenCalled(); + expect(fixture.client.vms.create).not.toHaveBeenCalled(); }); it("resolves bare process ports without opening Docker and rejects sibling ports", async () => { const workloads = [ { id: "openship-release-a", labels: { "openship.project": "project-a", "openship.deployment": "release-a", "openship.ports": "[3000]" } }, { id: "openship-release-b", labels: { "openship.project": "project-b", "openship.deployment": "release-b", "openship.ports": "[4000]" } }, ]; - fixture.client.workspace.mockReturnValue({ workloads: { list: async () => workloads } }); + fixture.client.vm.mockReturnValue({ workloads: { list: async () => workloads } }); const connection = new CloudServerConnection(fixture.client, { workspaceId: server.workspaceId, namespace: config.cloudNamespace }); const containers = vi.fn(async () => ({ resolveUrl: async () => { throw new Error("unowned port"); }, resolveTarget: vi.fn() })); const scope = managedProjectRoutingScope(connection, server, containers); diff --git a/packages/adapters/src/runtime/cloud/docker.test.ts b/packages/adapters/src/runtime/cloud/docker.test.ts index ad9e34fb9..9be7fe688 100644 --- a/packages/adapters/src/runtime/cloud/docker.test.ts +++ b/packages/adapters/src/runtime/cloud/docker.test.ts @@ -54,13 +54,13 @@ beforeEach(async () => { if (!page) throw new NotFoundError("missing"); return { page }; }), - create: vi.fn(async (input: { slug: string; workspace_id: string; path: string }) => { - const page = { slug: input.slug, domain: "opsh.io", url: `https://${input.slug}.opsh.io`, namespace: "namespace-a", source_workspace_id: input.workspace_id, exported_path: input.path }; + create: vi.fn(async (input: { slug: string; vm_id: string; path: string }) => { + const page = { slug: input.slug, domain: "opsh.io", url: `https://${input.slug}.opsh.io`, namespace: "namespace-a", source_vm_id: input.vm_id, exported_path: input.path }; pageRows.set(input.slug, page); return { page }; }), enable: vi.fn(async () => ({ success: true })), connectDomain: vi.fn(), delete: vi.fn(async () => ({ success: true })), }; - provider = { workspace: vi.fn(() => ws), workspaces: { get: ws.get, create: vi.fn(), delete: vi.fn() }, pages }; + provider = { vm: vi.fn(() => ws), vms: { get: ws.get, create: vi.fn(), delete: vi.fn() }, pages }; runtime = await CloudDockerRuntime.forWorkspace(provider as unknown as Oblien, { projectId: "project-a", ownerWorkspaceId: "managed-a", workspaceId: "workspace-a", namespace: "namespace-a", beforeProvision: async () => { await spend(); }, provisionLock: { run: fn => fn() }, resolveRegistryAuth: async () => undefined, @@ -145,7 +145,7 @@ describe("containers on one Oblien Docker workspace", () => { const options = { projectId: "project-a", serviceName: "api", onReplaced: vi.fn() }; await expect(runtime.applyEnvironment("container-a", { VALUE: "new" }, options)).resolves.toEqual({ containerId: "replacement-a" }); expect(apply).toHaveBeenCalledExactlyOnceWith("container-a", { VALUE: "new" }, options); - expect(provider.workspaces.create).not.toHaveBeenCalled(); + expect(provider.vms.create).not.toHaveBeenCalled(); expect(ws.restart).not.toHaveBeenCalled(); expect(ws.delete).not.toHaveBeenCalled(); expect(spend).toHaveBeenCalled(); @@ -356,8 +356,8 @@ describe("containers on one Oblien Docker workspace", () => { expect(first.hostPortByContainerPort![8080]).not.toBe(first.hostPortByContainerPort![9090]); expect(next.hostPortByContainerPort![8080]).toBe(first.hostPortByContainerPort![8080]); await infra.publishRoute("project-a.opsh.io", next.hostPortByContainerPort![8080]!, false); - expect(routes).toHaveBeenCalledWith("project-a.opsh.io", expect.objectContaining({ routes: [expect.objectContaining({ action: { kind: "proxy", workspace: "workspace-a", port: next.hostPortByContainerPort![8080] } })] })); - expect(provider.workspaces.create).not.toHaveBeenCalled(); + expect(routes).toHaveBeenCalledWith("project-a.opsh.io", expect.objectContaining({ routes: [expect.objectContaining({ action: { kind: "proxy", vm: "workspace-a", port: next.hostPortByContainerPort![8080] } })] })); + expect(provider.vms.create).not.toHaveBeenCalled(); }); it("keeps named and image-declared volume identities across container replacements", async () => { await runtime.deployServiceWorkload(group, config); @@ -496,7 +496,7 @@ describe("containers on one Oblien Docker workspace", () => { expect(ws.delete).not.toHaveBeenCalled(); }); it("does not take over another project's hostname in the same organization", async () => { - pageRows.set("project-a", { namespace: "namespace-a", source_workspace_id: "workspace-other", exported_path: "/app" }); + pageRows.set("project-a", { namespace: "namespace-a", source_vm_id: "workspace-other", exported_path: "/app" }); const result = await runtime.deployServiceWorkload(group, config); await expect(infra.publishRoute("project-a.opsh.io", result.hostPortByContainerPort![8080]!, false)).rejects.toThrow(/owned|belong/); expect(pages.enable).not.toHaveBeenCalled(); @@ -549,7 +549,7 @@ describe("containers on one Oblien Docker workspace", () => { const failure = Object.assign(new Error("Provider unavailable"), { status: 503 }); ws.get.mockRejectedValue(failure); await expect(runtime.listAllContainers()).rejects.toBe(failure); - expect(provider.workspaces.create).not.toHaveBeenCalled(); + expect(provider.vms.create).not.toHaveBeenCalled(); }); it("refuses another namespace's container inventory", async () => { ws.get.mockResolvedValue({ namespace: "another-namespace", status: "running" }); @@ -603,7 +603,7 @@ describe("containers on one Oblien Docker workspace", () => { adminProxy: { pages: pages as never, domainRoutes: async () => ({ data: [{ hostname: "project-a.opsh.io", namespace: "namespace-a", owner_type: "page", owner_id: "project-a" }] }) as never } }); await cleanup.removeRoute("project-a.opsh.io"); expect(pages.delete).toHaveBeenCalledWith("project-a"); - pageRows.get("project-a")!.source_workspace_id = "workspace-other"; + pageRows.get("project-a")!.source_vm_id = "workspace-other"; await expect(cleanup.removeRoute("project-a.opsh.io")).rejects.toThrow("not owned"); }); it("inventories disabled routing Pages without confusing their numeric IDs with slugs", async () => { @@ -611,7 +611,7 @@ describe("containers on one Oblien Docker workspace", () => { Ports: [{ PrivatePort: 8080, PublicPort: 30001, Type: "tcp" }] }]; await infra.publishRoute("project-a.opsh.io", 30001, false); pageRows.get("project-a")!.status = "disabled"; - pageRows.set("other", { slug: "other", domain: "opsh.io", namespace: "namespace-a", source_workspace_id: "workspace-other", exported_path: "/opt/openship/cloud-docker/routes/other" }); + pageRows.set("other", { slug: "other", domain: "opsh.io", namespace: "namespace-a", source_vm_id: "workspace-other", exported_path: "/opt/openship/cloud-docker/routes/other" }); expect(await infra.listProjectRouteHostnames()).toEqual(["project-a.opsh.io"]); const cleanup = new CloudInfraProvider(provider as unknown as Oblien, { namespace: "namespace-a", scope: runtime.routingScope() }); await cleanup.removeRoute("project-a.opsh.io"); @@ -707,7 +707,7 @@ describe("containers on one Oblien Docker workspace", () => { expect(dockerfile).toContain("OPENSHIP_BUILD_PACKAGE_MANAGER_VERSION='1.4.4'"); expect(transfer).not.toHaveBeenCalled(); expect(runtime.connectionOptions?.executor).toBe(runtime.executor); - expect(provider.workspaces.create).not.toHaveBeenCalled(); + expect(provider.vms.create).not.toHaveBeenCalled(); }); it("does not let an empty image-only source mask a later inline build context", async () => { const source = { projectId: "project-a", sessionId: "build-a", repoUrl: "" }; diff --git a/packages/adapters/src/runtime/cloud/docker.ts b/packages/adapters/src/runtime/cloud/docker.ts index 6f1023f13..7c3d33f17 100644 --- a/packages/adapters/src/runtime/cloud/docker.ts +++ b/packages/adapters/src/runtime/cloud/docker.ts @@ -789,7 +789,7 @@ export class CloudDockerRuntime extends DockerRuntime { }; } override async listAllContainers() { - const workspace = await this.client.workspaces.get(this.workspaceId); + const workspace = await this.client.vms.get(this.workspaceId); assertDockerWorkspaceOwner(workspace, this.options.namespace, this.workspaceId); assertCloudWorkspaceRunning(workspace); const containers = await super.listAllContainers(); @@ -802,7 +802,7 @@ export class CloudDockerRuntime extends DockerRuntime { throw new Error("A Docker workspace is not a service container"); let workspace; try { - workspace = await this.client.workspaces.get(this.workspaceId); + workspace = await this.client.vms.get(this.workspaceId); } catch (error) { if (notFound(error)) return { containerId, status: "missing" }; throw error; @@ -841,7 +841,7 @@ export class CloudDockerRuntime extends DockerRuntime { override async stop(containerId: string) { if (containerId === this.workspaceId) throw new Error("A Docker workspace is not a service container"); - const workspace = await this.client.workspaces.get(this.workspaceId); + const workspace = await this.client.vms.get(this.workspaceId); assertDockerWorkspaceOwner(workspace, this.options.namespace, this.workspaceId); if (!isDockerWorkspaceRunning(workspace)) return; return super.stop(containerId); diff --git a/packages/adapters/src/runtime/cloud/server-connection.ts b/packages/adapters/src/runtime/cloud/server-connection.ts index 3dd7ac665..a55a2dc8f 100644 --- a/packages/adapters/src/runtime/cloud/server-connection.ts +++ b/packages/adapters/src/runtime/cloud/server-connection.ts @@ -60,7 +60,7 @@ export function managedProcessState(workload: WorkloadInfo): ContainerStatus { /** Workload GET is saved configuration and can retain an old state after a VM * restart. The provider's status endpoint is the live process authority. */ export async function readManagedProcessStatus( - workloads: ReturnType["workloads"], + workloads: ReturnType["workloads"], saved: WorkloadInfo, ): Promise { let result: Awaited>; @@ -147,7 +147,7 @@ export class CloudServerConnection { } workspace() { - return this.client.workspace(this.workspaceId); + return this.client.vm(this.workspaceId); } runtime(options?: { force?: boolean }): Promise { @@ -230,7 +230,7 @@ export class CloudServerConnection { private ensureBridge(): Promise { const initialize = async () => { - const info = await this.client.workspaces.get(this.workspaceId); + const info = await this.client.vms.get(this.workspaceId); assertDockerWorkspaceOwner(info, this.options.namespace, this.workspaceId); assertCloudWorkspaceRunning(info); let runtime = await this.runtime(); @@ -263,7 +263,7 @@ export class CloudServerConnection { try { // Refresh only through this namespace's existing client. A revoked // namespace credential must still fail the control-plane check. - runtime = await this.client.workspace(this.workspaceId).runtime({ force: true }); + runtime = await this.client.vm(this.workspaceId).runtime({ force: true }); } catch (diagnosticFailure) { observeCaughtError(diagnosticFailure, "adapters/runtime/cloud/server-connection"); throw new AppError( @@ -304,7 +304,7 @@ export class CloudServerConnection { // A modified image missing it must fail at that boundary, not attempt to // bootstrap Python through the transport which already requires it. await this.executor.writeFile(BRIDGE_SCRIPT, CLOUD_DOCKER_BRIDGE_SOURCE, { mode: 0o700 }); - const workspace = this.client.workspace(this.workspaceId); + const workspace = this.client.vm(this.workspaceId); const workload = (await workspace.workloads.list({ name: BRIDGE_WORKLOAD })).find( (item) => item.name === BRIDGE_WORKLOAD, ); @@ -354,7 +354,7 @@ export class CloudServerConnection { async resume(): Promise { await this.options.beforeProvision?.(); - const ws = this.client.workspace(this.workspaceId); + const ws = this.client.vm(this.workspaceId); const data = await ws.get(); assertDockerWorkspaceOwner(data, this.options.namespace, this.workspaceId); if (isDockerWorkspaceRunning(data)) return; diff --git a/packages/adapters/src/runtime/cloud/workspace-delete.ts b/packages/adapters/src/runtime/cloud/workspace-delete.ts index a6cbca3c9..507616a0c 100644 --- a/packages/adapters/src/runtime/cloud/workspace-delete.ts +++ b/packages/adapters/src/runtime/cloud/workspace-delete.ts @@ -1,10 +1,10 @@ import { setTimeout as delay } from "node:timers/promises"; -import type { WorkspaceHandle } from "oblien"; +import type { VMHandle } from "oblien"; /** An accepted deletion is still running on Oblien. Keep local cleanup pending * until the scoped resource is absent; a failed read must not erase ownership. */ export async function deleteCloudWorkspace( - workspace: Pick, + workspace: Pick, options: { timeoutMs?: number } = {}, ): Promise { try { diff --git a/packages/adapters/src/runtime/cloud/workspace-ready.test.ts b/packages/adapters/src/runtime/cloud/workspace-ready.test.ts index 4a4b7e426..421cf754b 100644 --- a/packages/adapters/src/runtime/cloud/workspace-ready.test.ts +++ b/packages/adapters/src/runtime/cloud/workspace-ready.test.ts @@ -8,7 +8,7 @@ describe("Docker workspace readiness", () => { vi.useFakeTimers(); const get = vi.fn().mockResolvedValueOnce({ id: "owned-vm", namespace: "tenant", ...state, ready: false, provisioning: { state: "running" } }) .mockResolvedValue({ id: "owned-vm", namespace: "tenant", ...state, ready: true, provisioning: { state: "ready" } }); - const waiting = waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "owned-vm", "tenant"); + const waiting = waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "owned-vm", "tenant"); await vi.advanceTimersByTimeAsync(1000); await expect(waiting).resolves.toMatchObject({ ready: true }); expect(get).toHaveBeenCalledTimes(2); @@ -16,25 +16,25 @@ describe("Docker workspace readiness", () => { }); it("uses the live VM state even while the workspace record remains active", async () => { const get = vi.fn().mockResolvedValue({ id: "vm", namespace: "tenant", status: "active", info: { status: "stopped" }, provisioning: { state: "ready" } }); - await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant", { timeoutMs: 0 })).rejects.toThrow("still starting"); + await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant", { timeoutMs: 0 })).rejects.toThrow("still starting"); expect(cloudWorkspaceStatus({ status: "active", info: { is_running: false } })).toBe("stopped"); expect(cloudWorkspaceStatus({ status: "active", info: { is_running: true } })).toBe("running"); }); it("rejects a changed namespace even when the VM is ready", async () => { const get = vi.fn().mockResolvedValue({ id: "vm", namespace: "other-tenant", status: "active", ready: true }); - await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" }); + await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" }); }); it("rejects a different server in the same namespace before using its state", async () => { const get = vi.fn().mockResolvedValue({ id: "different-vm", namespace: "tenant", status: "running", ready: true }); - await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" }); + await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" }); }); it("surfaces a failed provisioning attempt without creating a replacement", async () => { const get = vi.fn().mockResolvedValue({ id: "vm", namespace: "tenant", status: "error", provisioning: { state: "failed" } }); - await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toThrow("existing disk"); + await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toThrow("existing disk"); }); it("cancels the wait before another provider read", async () => { const get = vi.fn(); - await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant", { signal: AbortSignal.abort() })).rejects.toThrow(); + await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant", { signal: AbortSignal.abort() })).rejects.toThrow(); expect(get).not.toHaveBeenCalled(); }); }); diff --git a/packages/adapters/src/runtime/cloud/workspace-ready.ts b/packages/adapters/src/runtime/cloud/workspace-ready.ts index de1010f56..2daf9c604 100644 --- a/packages/adapters/src/runtime/cloud/workspace-ready.ts +++ b/packages/adapters/src/runtime/cloud/workspace-ready.ts @@ -1,8 +1,8 @@ import { setTimeout as delay } from "node:timers/promises"; -import type { Oblien, WorkspaceData } from "oblien"; +import type { Oblien, VMData } from "oblien"; import { AppError } from "@repo/core"; -export function assertDockerWorkspaceOwner(workspace: WorkspaceData, namespace: string, workspaceId: string): void { +export function assertDockerWorkspaceOwner(workspace: VMData, namespace: string, workspaceId: string): void { if (workspace.namespace !== namespace || workspace.id !== workspaceId) throw new AppError("Cloud workspace identity does not match its server", 502, "CLOUD_SERVER_IDENTITY_MISMATCH"); } @@ -20,7 +20,7 @@ export function isDockerWorkspaceRunning(workspace: { status: string; info?: unk return cloudWorkspaceStatus(workspace) === "running"; } -export function assertCloudWorkspaceRunning(workspace: WorkspaceData): void { +export function assertCloudWorkspaceRunning(workspace: VMData): void { const state = cloudWorkspaceStatus(workspace); if (state === "running") return; if (["stopped", "paused", "suspended"].includes(state)) @@ -35,7 +35,7 @@ export function assertCloudWorkspaceRunning(workspace: WorkspaceData): void { export async function waitForCloudWorkspaceStopped(client: Oblien, workspaceId: string, namespace: string) { const deadline = Date.now() + 60_000; for (;;) { - const workspace = await client.workspaces.get(workspaceId); + const workspace = await client.vms.get(workspaceId); assertDockerWorkspaceOwner(workspace, namespace, workspaceId); if (["stopped", "paused", "suspended"].includes(cloudWorkspaceStatus(workspace))) return; if (Date.now() >= deadline) throw new Error("The managed server has not returned to its stopped state"); @@ -47,11 +47,11 @@ export async function waitForCloudWorkspaceStopped(client: Oblien, workspaceId: export async function waitForCloudDockerWorkspace( client: Oblien, workspaceId: string, namespace: string, options: { signal?: AbortSignal; timeoutMs?: number } = {}, -): Promise { +): Promise { const deadline = Date.now() + (options.timeoutMs ?? 600_000); while (true) { options.signal?.throwIfAborted(); - const workspace = await client.workspaces.get(workspaceId); + const workspace = await client.vms.get(workspaceId); assertDockerWorkspaceOwner(workspace, namespace, workspaceId); const provisioning = workspace.provisioning as { state?: string; error?: unknown } | undefined; if (provisioning?.state === "failed" || ["error", "failed"].includes(cloudWorkspaceStatus(workspace))) { diff --git a/packages/adapters/src/runtime/cloud/workspace-resources.ts b/packages/adapters/src/runtime/cloud/workspace-resources.ts index e6440d18e..627e4a124 100644 --- a/packages/adapters/src/runtime/cloud/workspace-resources.ts +++ b/packages/adapters/src/runtime/cloud/workspace-resources.ts @@ -1,4 +1,4 @@ -import type { WorkspaceData, WorkspaceHandle } from "oblien"; +import type { VMData, VMHandle } from "oblien"; import { cloudCpus, type ResourceConfig } from "../../types"; import { cloudWorkspaceStatus } from "./workspace-ready"; @@ -6,7 +6,7 @@ type WorkspaceResources = Pick & Partial>; export function cloudWorkspaceHasResources( - workspace: Pick, + workspace: Pick, expected: WorkspaceResources, ): boolean { const actual = workspace.resources; @@ -21,9 +21,9 @@ export function cloudWorkspaceHasResources( * Require an applied change and read the allocation back before claiming the * runtime was resized. Callers retain ownership of readiness and restoration. */ export async function updateCloudWorkspaceResources( - workspace: WorkspaceHandle, + workspace: VMHandle, resources: WorkspaceResources, - current?: WorkspaceData, + current?: VMData, ): Promise { const before = current ?? (await workspace.get()); if (before.id !== workspace.id) diff --git a/packages/adapters/src/runtime/oblien-routing.ts b/packages/adapters/src/runtime/oblien-routing.ts index 6a232b1d1..542192084 100644 --- a/packages/adapters/src/runtime/oblien-routing.ts +++ b/packages/adapters/src/runtime/oblien-routing.ts @@ -18,12 +18,12 @@ import type { RoutingConfig } from "@repo/core"; import { compileVercelRouting, type CompiledRouting } from "../infra/vercel-routing"; /** Sentinel so reused `compileVercelRouting` marks which proxy targets are the - * owned backend (→ Oblien `workspace`+`port`) vs. a literal external URL. */ + * owned backend (→ Oblien `vm`+`port`) vs. a literal external URL. */ const BACKEND_SENTINEL = "oblien-backend://self"; -/** An owned Oblien workspace to reverse-proxy to. */ -export interface OblienWorkspaceTarget { - workspace: string; +/** An owned Oblien VM to reverse-proxy to. */ +export interface OblienVmTarget { + vm: string; port: number; } @@ -34,11 +34,11 @@ export interface OblienRoutingContext { /** Workspace backing `/` when the frontend runs as a container instead of a * Page (a catch-all `/` proxy is appended last). Mutually exclusive with * `staticPage`. Also the server-only shape: set `root`, omit `backend`. */ - root?: OblienWorkspaceTarget; + root?: OblienVmTarget; /** Backend workspace that path rewrites (e.g. `/api/*`) proxy to. */ - backend?: OblienWorkspaceTarget; + backend?: OblienVmTarget; /** Resolved internal URLs, shared by the generic route-registration path. */ - proxyTargets?: ReadonlyMap; + proxyTargets?: ReadonlyMap; } /** Oblien only accepts 301/302/307/308; coerce anything else to a safe default @@ -51,7 +51,7 @@ function toOblienRedirectStatus(code: number): 301 | 302 | 307 | 308 { export function compileRoutingToOblien( routing: RoutingConfig, ctx: OblienRoutingContext = {}, -): RoutesInput { +): RoutesInput & { routes: RouteRule[] } { const compiled = compileVercelRouting(routing, { backendTargetUrl: ctx.backend ? BACKEND_SENTINEL : undefined, }); @@ -63,7 +63,7 @@ export function compileRoutingToOblien( export function compileResolvedRoutingToOblien( compiled: Pick, ctx: OblienRoutingContext = {}, -): RoutesInput { +): RoutesInput & { routes: RouteRule[] } { const routes: RouteRule[] = []; // Terminal rules are first-match-wins, evaluated before static files; order @@ -88,7 +88,7 @@ export function compileResolvedRoutingToOblien( for (const loc of compiled.proxyLocations) { const owned = loc.targetUrl === BACKEND_SENTINEL ? ctx.backend : ctx.proxyTargets?.get(loc.targetUrl); const action: RouteProxyAction = owned - ? { kind: "proxy", workspace: owned.workspace, port: owned.port } + ? { kind: "proxy", vm: owned.vm, port: owned.port } : { kind: "proxy", origin: loc.targetUrl }; // A capture-bearing rewrite carries its upstream path as a `$1..$9` template — // exactly what `RouteProxyAction.path` takes, against a `wildcard` match. @@ -107,7 +107,7 @@ export function compileResolvedRoutingToOblien( if (ctx.root) { routes.push({ match: { path: "/", type: "prefix" }, - action: { kind: "proxy", workspace: ctx.root.workspace, port: ctx.root.port }, + action: { kind: "proxy", vm: ctx.root.vm, port: ctx.root.port }, }); } @@ -118,7 +118,7 @@ export function compileResolvedRoutingToOblien( }); } - const input: RoutesInput = { routes }; + const input: RoutesInput & { routes: RouteRule[] } = { routes }; if (ctx.staticPage) { input.static = { page: ctx.staticPage }; if (compiled.spaFallback !== undefined) input.spa = compiled.spaFallback; diff --git a/packages/adapters/src/runtime/transfer.ts b/packages/adapters/src/runtime/transfer.ts index f5a80b487..a630ce5a5 100644 --- a/packages/adapters/src/runtime/transfer.ts +++ b/packages/adapters/src/runtime/transfer.ts @@ -1,6 +1,6 @@ import { execFile } from "node:child_process"; -import type { WorkspaceHandle } from "oblien"; +import type { VMHandle } from "oblien"; import { TRANSFER_EXCLUDES, safeErrorMessage } from "@repo/core"; import { getTarCreateEnv, prepareSourceTarArgs } from "../archive"; @@ -24,7 +24,7 @@ export type LocalDirectoryTarget = } | { kind: "cloud-runtime"; - runtime: Awaited>; + runtime: Awaited>; path: string; }; diff --git a/packages/adapters/src/system/mail/ensure-container-mail.test.ts b/packages/adapters/src/system/mail/ensure-container-mail.test.ts index e9c66f8d6..0025e6c70 100644 --- a/packages/adapters/src/system/mail/ensure-container-mail.test.ts +++ b/packages/adapters/src/system/mail/ensure-container-mail.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { buildMailRunCommand, @@ -401,7 +401,8 @@ describe("ensureContainerMail swap", () => { if (cmd.includes("/proc/net/tcp")) return PROC_LISTENING; return ""; }); - const executor = { exec, streamExec, writeFile: vi.fn(async () => {}) } as never; + const readFile = vi.fn(async () => "FIRST_DOMAIN=mail.example.com\n"); + const executor = { exec, streamExec, writeFile: vi.fn(async () => {}), readFile } as never; await ensureContainerMail(executor, { domain: "example.com", @@ -416,6 +417,123 @@ describe("ensureContainerMail swap", () => { }); }); +/** Update fixtures retain the installed credentials and run the whole swap. */ +function swapBox(engineEnv: string) { + const streamExec = vi.fn(async (_cmd: string) => ({ code: 0, output: "" })); + const writeFile = vi.fn(async (_path: string, _content: string, _opts?: { mode?: number }) => {}); + const readFile = vi.fn(async (path: string) => { + if (path.endsWith("engine.env")) return engineEnv; + throw new Error("ENOENT"); + }); + const exec = vi.fn(async (cmd: string) => { + if (cmd.includes("opsh_uid=")) return "opsh_uid=0\nopsh_user=root\nopsh_sudo=n\n"; + if (cmd.includes("{{json .Mounts}}")) + return `${"a".repeat(64)}\ttrue\t${JSON.stringify( + MAIL_CONTAINER_MOUNTS.map((m) => ({ + Type: "bind", + Source: m.host, + Destination: m.container, + })), + )}`; + if (cmd.includes(STATE_PROBE)) return stateLine("ghcr.io/x/openship-mail:old"); + if (cmd.includes("docker image inspect")) return "sha256:present\n"; + if (cmd.includes("/proc/net/tcp")) return PROC_LISTENING; + return ""; + }); + const onLog = vi.fn(); + return { + exec, readFile, writeFile, streamExec, onLog, + update: () => ensureContainerMail({ exec, streamExec, writeFile, readFile } as never, { + domain: "mail.example.com", secrets: {}, onLog, + }), + engineEnvWrites: () => writeFile.mock.calls.filter(([path]) => path.endsWith("engine.env")), + }; +} + +describe("ensureContainerMail carries explicit ignore-ip overrides across an update (GH-1768)", () => { + const KEY = "OPENSHIP_MAIL_F2B_IGNOREIP"; + const ENV_BODY = "FIRST_DOMAIN=mail.example.com\nOPENSHIP_MAIL_DB_PORT=5433\nPGSQL_ROOT_PASSWD= retained#secret=one \n"; + + beforeEach(() => { + setDefaultMailImage("ghcr.io/x/openship-mail:pinned"); + vi.stubEnv(KEY, undefined); + }); + afterEach(() => vi.unstubAllEnvs()); + + it.each(["", `${KEY}=192.0.2.9\n`])("sets the override before replacement and retains credentials (previous=%s)", async previous => { + vi.stubEnv(KEY, "203.0.113.5 198.51.100.0/24"); + const box = swapBox(`${ENV_BODY}${previous}`); + expect(await box.update()).toMatchObject({ updated: true, mailDown: false }); + expect(box.engineEnvWrites()).toEqual([[ + `${MAIL_HOST_STATE_DIR}/engine.env`, + `${ENV_BODY}${KEY}=203.0.113.5 198.51.100.0/24\n`, + { mode: 0o600 }, + ]]); + expect(box.writeFile.mock.invocationCallOrder[0]).toBeLessThan(box.streamExec.mock.invocationCallOrder[0]!); + }); + + it("preserves each server's list without reading or rewriting credentials when the API variable is unset", async () => { + for (const addresses of ["192.0.2.9", "198.51.100.0/24"]) { + const box = swapBox(`${ENV_BODY}${KEY}=${addresses}\n`); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.readFile).not.toHaveBeenCalled(); + expect(box.writeFile).not.toHaveBeenCalled(); + } + }); + + it.each(["", " "])("removes only the override when the API explicitly clears it (%j)", async configured => { + vi.stubEnv(KEY, configured); + const box = swapBox(`${ENV_BODY}${KEY}=192.0.2.9\n`); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.engineEnvWrites()).toEqual([[`${MAIL_HOST_STATE_DIR}/engine.env`, ENV_BODY, { mode: 0o600 }]]); + }); + + it.each([ + ["192.0.2.9", `${KEY}=192.0.2.9\n`], + ["", ""], + ])("does not rewrite the secret file when the override already agrees (%j)", async (configured, record) => { + vi.stubEnv(KEY, configured); + const box = swapBox(`${ENV_BODY}${record}`); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.writeFile).not.toHaveBeenCalled(); + }); + + it("reports a failed read and never replaces unknown credentials with an incomplete file", async () => { + vi.stubEnv(KEY, "192.0.2.9"); + const box = swapBox(ENV_BODY); + box.readFile.mockRejectedValue(new Error("permission denied")); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.writeFile).not.toHaveBeenCalled(); + expect(box.onLog).toHaveBeenCalledWith(expect.objectContaining({ level: "warn", message: expect.stringMatching(/Could not update OPENSHIP_MAIL_F2B_IGNOREIP:.*permission denied/) })); + }); + + it("reports a failed write without silently claiming the exclusions were applied", async () => { + vi.stubEnv(KEY, "192.0.2.9"); + const box = swapBox(ENV_BODY); + box.writeFile.mockRejectedValue(new Error("read-only filesystem")); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.onLog).toHaveBeenCalledWith(expect.objectContaining({ level: "warn", message: expect.stringMatching(/Could not update OPENSHIP_MAIL_F2B_IGNOREIP:.*read-only filesystem/) })); + }); + + it("does not replace an empty retained file with missing database credentials", async () => { + vi.stubEnv(KEY, "192.0.2.9"); + const box = swapBox(""); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.writeFile).not.toHaveBeenCalled(); + expect(box.onLog).toHaveBeenCalledWith(expect.objectContaining({ level: "warn", message: expect.stringContaining("restore its credentials") })); + }); + + it("rejects injected environment records before writing and reports the validation failure", async () => { + vi.stubEnv(KEY, "192.0.2.9\nPGSQL_ROOT_PASSWD=injected"); + const box = swapBox(ENV_BODY); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.writeFile).not.toHaveBeenCalled(); + expect(box.onLog).toHaveBeenCalledWith(expect.objectContaining({ level: "warn", message: expect.stringContaining("spans multiple lines") })); + expect(JSON.stringify(box.onLog.mock.calls)).not.toContain("retained#secret"); + expect(JSON.stringify(box.onLog.mock.calls)).not.toContain("PGSQL_ROOT_PASSWD=injected"); + }); +}); + /** * Env-file record injection (GHSA-x2xg-5h5f-j5m9, second-order). * diff --git a/packages/adapters/src/system/mail/ensure-container-mail.ts b/packages/adapters/src/system/mail/ensure-container-mail.ts index 82798ed9f..7cba66808 100644 --- a/packages/adapters/src/system/mail/ensure-container-mail.ts +++ b/packages/adapters/src/system/mail/ensure-container-mail.ts @@ -342,6 +342,36 @@ async function readEnvFileValue( return null; } +/** Apply an explicit API override without removing a server's own exclusions. */ +async function carryIgnoreIp(executor: CommandExecutor, onLog: SystemLogCallback): Promise { + const key = "OPENSHIP_MAIL_F2B_IGNOREIP"; + const configured = process.env[key]; + // Existing installations may configure different lists directly on each server. + if (configured === undefined) return; + const wanted = configured.trim(); + try { + const host = await rootOrDegrade(executor, { + purpose: "Updating the mail engine's fail2ban exclusions", + consequence: "The exclusions may not be updated.", + report: message => onLog(log(message, "warn")), + }); + const body = await host.readFile(ENGINE_ENV_FILE); + if (!body.trim()) throw new Error(`The retained ${ENGINE_ENV_FILE} is empty; restore its credentials before updating exclusions.`); + const records: Record = Object.create(null); + for (const line of body.split("\n")) { + const eq = line.indexOf("="); + if (eq > 0) records[line.slice(0, eq).trim()] = line.slice(eq + 1); + } + if (wanted ? records[key] === wanted : records[key] === undefined) return; + if (wanted) records[key] = wanted; + else delete records[key]; + await writeEnvFile(host, ENGINE_ENV_FILE, records); + } catch (failure) { + observeCaughtError(failure, "adapters/system/mail/ensure-container-mail"); + onLog(log(`Could not update ${key}: ${safeErrorMessage(failure)}`, "warn")); + } +} + /** * The superuser password an ALREADY-INITIALISED cluster is holding, or null if this is a * first install. @@ -656,6 +686,8 @@ export async function ensureContainerMail( // dies on the client-side `--env-file` open, `swapManagedImage` rolls back through the // same callback and dies identically, and a perfectly healthy engine gets reported as // `mailDown` with nothing in the log pointing at permissions. + // Rewrite that record before the hand-over below, as root where the file is still root-owned. + await carryIgnoreIp(executor, onLog); await handOverEnvFile(executor, ENGINE_ENV_FILE, onLog); const start = makeMailStart(executor, container, opts); diff --git a/packages/adapters/test/backup-empty-source-guard.test.ts b/packages/adapters/test/backup-empty-source-guard.test.ts index 9edb63413..79fe65b46 100644 --- a/packages/adapters/test/backup-empty-source-guard.test.ts +++ b/packages/adapters/test/backup-empty-source-guard.test.ts @@ -1,138 +1,137 @@ -/** - * A volume capture must not record an archive of nothing as a backup. - * - * The daemon CREATES a missing bind directory and a missing named volume when it - * honors `HostConfig.Binds`. So a source that is not on the host — an external disk - * that failed to mount, a data directory renamed under a still-running container, a - * volume `docker system prune --volumes` took — produced a helper that started fine - * and a `tar -c` of an empty mount that exited 0. - * - * Nothing downstream could tell that apart from a real backup: an empty tar is 10240 - * bytes and ~350 compressed, so the orchestrator's only emptiness guard - * (`sizeBytes === 0`) passed, and the producer's guards only cover "no sources listed - * at all", never "the source turned out to be empty". - * - * Two halves are asserted, because either alone is a false pass: that the generated - * command CARRIES the gate, and that the gate actually does what it claims when a - * real shell runs it. - */ - +/** Verified empty sources are valid; missing sources must never be created by capture. */ import { spawnSync } from "node:child_process"; -import { mkdtempSync, writeFileSync } from "node:fs"; +import { mkdtemp, rm, stat } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; -import { describe, expect, it, vi, beforeEach, afterEach } from "vitest"; -import { FakeAttachStream, harness } from "./helpers/docker-helper-harness"; +import { randomUUID } from "node:crypto"; +import { describe, expect, it, beforeAll, afterAll } from "vitest"; +import { DockerRuntime } from "../src/runtime/docker"; +import { DockerBackupExecutor } from "../src/backup/executors/docker"; +import { VolumeCopyProducer } from "../src/backup/producers/volume"; import type { ServiceHandle } from "../src/backup/types"; -const attachControl: { stream: FakeAttachStream | null } = { stream: null }; - -// Partial mock: the executor also imports `daemonConnectionFrom` from this module. -vi.mock(import("../src/runtime/docker-exec-stream"), async (importOriginal) => ({ - ...(await importOriginal()), - startAttachStream: async () => attachControl.stream as never, - startExecStream: async () => attachControl.stream as never, -})); - const SERVICE: ServiceHandle = { id: "svc_1", projectId: "prj_1", - name: "db", - image: "postgres:16", + name: "optional-storage", + image: "alpine:3", env: {}, - volumes: ["pgdata:/var/lib/postgresql/data"], + volumes: [], containerId: null, - projectSlug: "shop", + projectSlug: "backup-empty-regression", namespaceVolumes: false, }; -beforeEach(() => { - attachControl.stream = new FakeAttachStream(); -}); -afterEach(() => { - vi.restoreAllMocks(); -}); +const dockerAvailable = spawnSync("docker", ["info"], { stdio: "ignore" }).status === 0; +const dockerRequired = process.env.RUN_DOCKER_E2E === "1"; -/** The helper command the executor asked the daemon to run. */ -async function capturedCmd(compression: "none" | "zstd" | "gzip"): Promise { - const h = harness({ wait: 0 }, () => ({})); - const exec = await h.executor(); - const { stdout, awaitExit } = await exec.streamPath(SERVICE, "pgdata-0", { compression }); - stdout.on("data", () => {}); - stdout.on("error", () => {}); - attachControl.stream!.end?.(); - await awaitExit.catch(() => {}); - const spec = h.created.at(-1) as { Cmd?: string[] } | undefined; - expect(spec?.Cmd, JSON.stringify(h.created)).toBeTruthy(); - return (spec!.Cmd as string[]).join("\n"); -} +describe.skipIf(!dockerAvailable && !dockerRequired)("Docker capture source existence", () => { + let runtime: DockerRuntime; + let executor: DockerBackupExecutor; + let root: string; + let containerId: string; + const prefix = `openship-empty-${randomUUID()}`; + const volumes = ["empty", "populated", "unavailable"].map((name) => `${prefix}-${name}`); -describe("the capture command carries an empty-source gate", () => { - it("gates every codec, not just the compressed ones", async () => { - // `none` and `gzip` skip the pipeline entirely (busybox tar compresses in - // process) and take a different branch of safeDumpCommand, so a gate added only - // to the zstd prelude would leave the other two silently backing up nothing. - for (const compression of ["none", "gzip", "zstd"] as const) { - const cmd = await capturedCmd(compression); - expect(cmd, compression).toContain("ls -A /mnt"); - expect(cmd, compression).toContain("exit 91"); - // The source id is named, because "something was empty" is not actionable. - expect(cmd, compression).toContain("pgdata-0"); + beforeAll(async () => { + if (!dockerAvailable) throw new Error("RUN_DOCKER_E2E=1 requires Docker"); + runtime = await DockerRuntime.create({ transport: "socket" }); + executor = new DockerBackupExecutor(runtime); + await runtime.pullImage("alpine:3"); + root = await mkdtemp(join(tmpdir(), "openship-empty-source-")); + for (const name of volumes.slice(0, 2)) await runtime.docker.createVolume({ Name: name }); + await runtime.docker.createVolume({ + Name: volumes[2], + Driver: "local", + DriverOpts: { type: "none", o: "bind", device: join(root, "missing-storage") }, + }); + const helper = await runtime.docker.createContainer({ + Image: "alpine:3", + Cmd: ["sh", "-c", "echo important-data > /data/keep.txt"], + HostConfig: { Binds: [`${volumes[1]}:/data`] }, + }); + try { + await helper.start(); + expect((await helper.wait()).StatusCode).toBe(0); + } finally { + await helper.remove({ force: true }); } + const service = await runtime.docker.createContainer({ + Image: "alpine:3", + Cmd: ["sleep", "300"], + HostConfig: { + Binds: [`${volumes[0]}:/optional`, `${root}:/empty-bind`, `${volumes[1]}:/data`], + }, + }); + containerId = service.id; + await service.start(); + }, 120_000); + + afterAll(async () => { + if (containerId) await runtime.docker.getContainer(containerId).remove({ force: true }); + if (runtime) + for (const name of volumes) + await runtime.docker + .getVolume(name) + .remove() + .catch(() => {}); + if (root) await rm(root, { recursive: true, force: true }); }); - it("runs the gate BEFORE installing the compressor", async () => { - // Ordering is not cosmetic: `apk add zstd` costs ~20s per helper and needs - // network egress, so paying it for a capture that cannot produce anything is - // pure latency on the failure path. - const cmd = await capturedCmd("zstd"); - expect(cmd.indexOf("ls -A /mnt")).toBeLessThan(cmd.indexOf("apk add")); - }); -}); - -describe("the gate refuses an empty mount and passes a populated one", () => { - /** The gate as generated, with /mnt pointed at a real directory. */ - const gateFor = (dir: string) => - [ - `SRC='pgdata-0'`, - `[ -n "$(ls -A ${dir} 2>/dev/null)" ] || { echo "openship: backup source $SRC is empty` + - ` or missing on this host" >&2; exit 91; }`, - `tar -c -C ${dir} . | wc -c`, - ].join("\n"); + const collect = async (stdout: NodeJS.ReadableStream) => { + const chunks: Buffer[] = []; + for await (const chunk of stdout) chunks.push(Buffer.from(chunk)); + return Buffer.concat(chunks); + }; - it("exits 91 on an empty directory", () => { - const empty = mkdtempSync(join(tmpdir(), "openship-empty-src-")); - const run = spawnSync("/bin/sh", ["-c", gateFor(empty)]); - expect(run.status).toBe(91); - expect(run.stderr.toString()).toContain("empty or missing"); + it("captures empty named and bind sources alongside a populated sibling", async () => { + const service = { ...SERVICE, containerId }; + const archives = new Map(); + for await (const artifact of VolumeCopyProducer.produce(service, executor, { + compression: "gzip", + })) { + const bytes = await collect(artifact.stream); + archives.set(String(artifact.metadata.volumeSource), bytes); + } + expect(archives.size).toBe(3); + for (const source of [volumes[0], root]) { + const bytes = archives.get(source)!; + const listing = spawnSync("tar", ["-tzf", "-"], { input: bytes }); + expect(listing.status, listing.stderr.toString()).toBe(0); + expect(listing.stdout.toString().trim()).toBe("./"); + } + const restored = spawnSync("tar", ["-xzOf", "-", "./keep.txt"], { + input: archives.get(volumes[1]), + }); + expect(restored.status, restored.stderr.toString()).toBe(0); + expect(restored.stdout.toString()).toBe("important-data\n"); }); - it("exits 91 on a path that does not exist at all", () => { - // What the daemon would have CREATED for us, silently. - const missing = join(tmpdir(), "openship-definitely-not-here-9f2c1"); - const run = spawnSync("/bin/sh", ["-c", gateFor(missing)]); - expect(run.status).toBe(91); + it("rejects a volume absent from this daemon without creating it", async () => { + const name = `${prefix}-wrong-host`; + const service = { ...SERVICE, volumes: [`${name}:/data`] }; + await expect( + executor.streamPath(service, `${name}-0`, { compression: "gzip" }), + ).rejects.toThrow(); + await expect(runtime.docker.getVolume(name).inspect()).rejects.toMatchObject({ + statusCode: 404, + }); }); - it("passes a directory with content", () => { - const full = mkdtempSync(join(tmpdir(), "openship-full-src-")); - writeFileSync(join(full, "pg_control"), "real data"); - const run = spawnSync("/bin/sh", ["-c", gateFor(full)]); - expect(run.status, run.stderr?.toString()).toBe(0); - // A byte count proves nothing here — tar's default 10240-byte blocking means a - // small file archives to exactly the same size as nothing at all, which is the - // reason the zero-byte guard could not tell them apart. Assert the CONTENT. - const listed = spawnSync("/bin/sh", ["-c", `tar -t -C ${full} -f - < /dev/null; tar -c -C ${full} . | tar -t`]); - expect(listed.stdout.toString()).toContain("pg_control"); + it("rejects a missing bind path without creating a directory", async () => { + const missing = join(root, "missing-bind"); + const service = { ...SERVICE, volumes: [`${missing}:/data`] }; + await expect( + executor.streamPath(service, `${missing}-0`, { compression: "gzip" }), + ).rejects.toThrow(); + await expect(stat(missing)).rejects.toMatchObject({ code: "ENOENT" }); }); - it("shows why the zero-byte check could never have caught this", () => { - // An empty tar is a VALID archive of 10240 bytes, so `sizeBytes === 0` passes. - // This is the number that made the old behaviour indistinguishable from a real - // backup, asserted so nobody re-derives it. - const empty = mkdtempSync(join(tmpdir(), "openship-empty-tar-")); - const run = spawnSync("/bin/sh", ["-c", `tar -c -C ${empty} . | wc -c`]); - expect(run.status).toBe(0); - expect(Number(run.stdout.toString().trim())).toBe(10240); + it("rejects an existing volume whose backing storage is unavailable", async () => { + const name = volumes[2]; + const service = { ...SERVICE, volumes: [`${name}:/data`] }; + await expect( + executor.streamPath(service, `${name}-0`, { compression: "gzip" }), + ).rejects.toThrow(); }); }); diff --git a/packages/adapters/test/backup-helper-logging.test.ts b/packages/adapters/test/backup-helper-logging.test.ts index 2fd798dcf..a6d87db31 100644 --- a/packages/adapters/test/backup-helper-logging.test.ts +++ b/packages/adapters/test/backup-helper-logging.test.ts @@ -1,7 +1,6 @@ -import { describe, expect, it } from "vitest"; -import { readFileSync } from "node:fs"; -import { join, dirname } from "node:path"; -import { fileURLToPath } from "node:url"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import type { ServiceHandle } from "../src/backup/types"; +import { FakeAttachStream, harness } from "./helpers/docker-helper-harness"; /** * The backup helper streams a volume's archive over `attach()`. With the @@ -11,34 +10,45 @@ import { fileURLToPath } from "node:url"; * volume produced a 12 GB log, so a backup spiked host disk by far more than * it read and only released it when the helper exited. * - * Asserted against the source because the alternative is a full dockerode - * double, which would pin far more of the executor's shape than this one - * property is worth. + * Exercise the executor's actual helper configuration for each codec. */ -const executorSource = readFileSync( - join(dirname(fileURLToPath(import.meta.url)), "../src/backup/executors/docker.ts"), - "utf8", -); +const attach = vi.hoisted(() => ({ stream: null as FakeAttachStream | null })); +vi.mock("../src/runtime/docker-exec-stream", async (original) => ({ + ...(await original()), + startAttachStream: async () => attach.stream!, +})); + +afterEach(() => vi.restoreAllMocks()); + +const service: ServiceHandle = { + id: "svc_1", + projectId: "prj_1", + name: "db", + image: "postgres:16", + env: {}, + volumes: ["pgdata:/var/lib/postgresql/data"], + containerId: null, + projectSlug: "shop", + namespaceVolumes: false, +}; describe("backup helper container", () => { - it("disables container logging for the archive stream", () => { - expect(executorSource).toMatch(/LogConfig:\s*\{\s*Type:\s*"none"/); - }); - - it("keeps the log config on the same HostConfig that binds the source", () => { - // Anchored to the statement that immediately follows the literal, so the - // slice stays inside streamPath — `const helper =` moved into the shared - // withHelper/handOffHelper wrappers and would now widen this to two methods. - const hostConfig = executorSource.slice( - executorSource.indexOf("const hostConfig"), - executorSource.indexOf("return this.handOffHelper("), - ); - expect(hostConfig).toContain(":/mnt:ro"); - // AutoRemove must stay OFF: the daemon reaping the helper at exit races - // container.wait() (404 on the exit status) and tears down the attach socket - // while bytes are still buffered (truncated tar). demuxContainerStream owns - // the removal instead, once the archive is fully demuxed. - expect(hostConfig).toContain("AutoRemove: false"); - expect(hostConfig).toMatch(/LogConfig/); - }); + it.each(["none", "gzip", "zstd"] as const)( + "keeps %s capture read-only with logging disabled and cleanup owned by the executor", + async (compression) => { + attach.stream = new FakeAttachStream(); + const h = harness({ wait: 0 }, () => ({})); + const executor = await h.executor(); + const { stdout, awaitExit } = await executor.streamPath(service, "pgdata-0", { compression }); + stdout.resume(); + attach.stream.finish(); + await awaitExit; + expect(h.created.at(-1)?.HostConfig).toMatchObject({ + Mounts: [{ Type: "volume", Source: "pgdata", Target: "/mnt", ReadOnly: true }], + AutoRemove: false, + LogConfig: { Type: "none", Config: {} }, + }); + expect(h.removals).toHaveLength(1); + }, + ); }); diff --git a/packages/adapters/test/cloud-infra.test.ts b/packages/adapters/test/cloud-infra.test.ts index 6fede0853..170cdb457 100644 --- a/packages/adapters/test/cloud-infra.test.ts +++ b/packages/adapters/test/cloud-infra.test.ts @@ -23,7 +23,7 @@ describe("managed route cleanup", () => { await h.infra.removeRoute("app.opsh.io"); expect(h.pages.delete).toHaveBeenCalledWith("app"); }); - it.each(["source_workspace_id", "exported_path"])("refuses cleanup after %s changes", async field => { + it.each(["source_vm_id", "exported_path"])("refuses cleanup after %s changes", async field => { h.records.get("app")![field] = "another-owner"; await expect(h.infra.removeRoute("app.opsh.io")).rejects.toThrow("not owned"); expect(h.pages.delete).not.toHaveBeenCalled(); diff --git a/packages/adapters/test/cloud-project-route-cleanup.test.ts b/packages/adapters/test/cloud-project-route-cleanup.test.ts index c2d1b7605..98284162c 100644 --- a/packages/adapters/test/cloud-project-route-cleanup.test.ts +++ b/packages/adapters/test/cloud-project-route-cleanup.test.ts @@ -17,7 +17,7 @@ describe("project-scoped route cleanup", () => { it.each(["workspace-one", "another-workspace"])( "preserves a different project's Page on %s while explicit removal stays strict", async (workspaceId) => { - h.records.get("app")!.source_workspace_id = workspaceId; + h.records.get("app")!.source_vm_id = workspaceId; h.records.get("app")!.exported_path = `${cloudDockerProjectPaths("active-project").routes}/app`; const activePage = structuredClone(h.records.get("app")); @@ -61,13 +61,13 @@ describe("project-scoped route cleanup", () => { }); it.each([ - { source_workspace_id: "another-workspace" }, + { source_vm_id: "another-workspace" }, { exported_path: undefined }, { exported_path: "/unrecognised-owner/app" }, { exported_path: `${cloudDockerProjectPaths("active-project").routes}/wrong-slug` }, { exported_path: `${cloudDockerProjectPaths("active-project").routes}/app`, - source_workspace_id: null, + source_vm_id: null, }, ])("blocks deletion when foreign ownership is unproven: %j", async (changes) => { Object.assign(h.records.get("app")!, changes); diff --git a/packages/adapters/test/helpers/docker-helper-harness.ts b/packages/adapters/test/helpers/docker-helper-harness.ts index 54acc5406..fd82d80a5 100644 --- a/packages/adapters/test/helpers/docker-helper-harness.ts +++ b/packages/adapters/test/helpers/docker-helper-harness.ts @@ -135,6 +135,7 @@ export function harness( const runtime = await DockerRuntime.create(); // ensureImage → runtime.pullImage; never touch a registry in a unit test. (runtime as unknown as { pullImage: () => Promise }).pullImage = async () => {}; + runtime.docker.getVolume = (() => ({ inspect: async () => ({}) })) as never; runtime.docker.createContainer = (async (opts: Record) => { created.push(opts); return helper; diff --git a/packages/adapters/test/managed-routing-fixture.ts b/packages/adapters/test/managed-routing-fixture.ts index 5521a4611..6123076b7 100644 --- a/packages/adapters/test/managed-routing-fixture.ts +++ b/packages/adapters/test/managed-routing-fixture.ts @@ -26,8 +26,8 @@ export function managedRoutingFixture(): { if (!records.has(slug)) throw new NotFoundError("missing Page"); return { page: records.get(slug)! }; }), - create: vi.fn(async (input: { slug: string; domain: string; path: string; workspace_id: string }) => { - const page = { id: records.size + 1, slug: input.slug, domain: input.domain, namespace, source_workspace_id: input.workspace_id, exported_path: input.path, url: `https://${input.slug}.${input.domain}` }; + create: vi.fn(async (input: { slug: string; domain: string; path: string; vm_id: string }) => { + const page = { id: records.size + 1, slug: input.slug, domain: input.domain, namespace, source_vm_id: input.vm_id, exported_path: input.path, url: `https://${input.slug}.${input.domain}` }; records.set(input.slug, page); return { success: true, page }; }), deploy: vi.fn(async () => ({ success: true })), @@ -51,7 +51,7 @@ export function managedRoutingFixture(): { { hostname: `${page.slug}.${page.domain}`, namespace: page.namespace, owner_type: "page", owner_id: page.id, is_custom: false }, ...(page.custom_domain ? [{ hostname: page.custom_domain, namespace: page.namespace, owner_type: "page", owner_id: page.id, is_custom: true }] : []), ]) })) }; - const client = { pages, routes, domain, workspace: vi.fn(() => workspace) } as unknown as Oblien; + const client = { pages, routes, domain, vm: vi.fn(() => workspace) } as unknown as Oblien; const infra = new CloudInfraProvider(client, { namespace, scope }); return { namespace, workspaceId, projectId, paths, records, pages, executor, scope, workspace, routes, domain, client, infra }; } diff --git a/packages/adapters/test/oblien-routing.test.ts b/packages/adapters/test/oblien-routing.test.ts index 2f29cc418..dbaf58071 100644 --- a/packages/adapters/test/oblien-routing.test.ts +++ b/packages/adapters/test/oblien-routing.test.ts @@ -11,7 +11,7 @@ describe("compileRoutingToOblien", () => { { source: "/(.*)", destination: "/index.html" }, ], }, - { staticPage: "my-frontend", backend: { workspace: "ws_backend", port: 3000 } }, + { staticPage: "my-frontend", backend: { vm: "ws_backend", port: 3000 } }, ); expect(input.static).toEqual({ page: "my-frontend" }); @@ -19,7 +19,7 @@ describe("compileRoutingToOblien", () => { expect(input.routes).toEqual([ { match: { path: "/api/", type: "prefix" }, - action: { kind: "proxy", workspace: "ws_backend", port: 3000 }, + action: { kind: "proxy", vm: "ws_backend", port: 3000 }, }, ]); }); @@ -27,27 +27,27 @@ describe("compileRoutingToOblien", () => { it("builds a COMPLETE table for the workspace topology (frontend + backend both workspaces)", () => { const input = compileRoutingToOblien( { rewrites: [{ source: "/api/(.*)", destination: "/api/index.js" }] }, - { root: { workspace: "ws_frontend", port: 8080 }, backend: { workspace: "ws_backend", port: 3000 } }, + { root: { vm: "ws_frontend", port: 8080 }, backend: { vm: "ws_backend", port: 3000 } }, ); expect(input.static).toBeUndefined(); // /api proxies to the backend; `/` catch-all proxies to the frontend LAST. expect(input.routes).toEqual([ - { match: { path: "/api/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_backend", port: 3000 } }, - { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_frontend", port: 8080 } }, + { match: { path: "/api/", type: "prefix" }, action: { kind: "proxy", vm: "ws_backend", port: 3000 } }, + { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "ws_frontend", port: 8080 } }, ]); }); it("builds a server-only table (root workspace backs everything)", () => { - const input = compileRoutingToOblien({}, { root: { workspace: "ws_api", port: 8080 } }); + const input = compileRoutingToOblien({}, { root: { vm: "ws_api", port: 8080 } }); expect(input.routes).toEqual([ - { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_api", port: 8080 } }, + { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "ws_api", port: 8080 } }, ]); }); it("proxies a full-URL rewrite to a literal origin (not the owned workspace)", () => { const input = compileRoutingToOblien( { rewrites: [{ source: "/proxy/(.*)", destination: "https://api.example.com/fixed" }] }, - { backend: { workspace: "ws_backend", port: 3000 } }, + { backend: { vm: "ws_backend", port: 3000 } }, ); expect(input.routes).toEqual([ { @@ -80,13 +80,13 @@ describe("compileRoutingToOblien", () => { { source: "/see", destination: "/other", statusCode: 303 }, // Oblien has no 303 → 307 ], }, - { root: { workspace: "ws_app", port: 8080 } }, + { root: { vm: "ws_app", port: 8080 } }, ); expect(input.routes).toEqual([ { match: { path: "/old", type: "exact" }, action: { kind: "redirect", status: 308, to: "/new" } }, { match: { path: "/tmp", type: "exact" }, action: { kind: "redirect", status: 307, to: "/temp" } }, { match: { path: "/see", type: "exact" }, action: { kind: "redirect", status: 307, to: "/other" } }, - { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_app", port: 8080 } }, + { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "ws_app", port: 8080 } }, ]); }); @@ -101,7 +101,7 @@ describe("compileRoutingToOblien", () => { { source: "/docs/(.*)", destination: "/documentation/$1" }, ], }, - { root: { workspace: "ws_app", port: 8080 } }, + { root: { vm: "ws_app", port: 8080 } }, ); expect(input.routes).toEqual([ { @@ -112,7 +112,7 @@ describe("compileRoutingToOblien", () => { match: { path: "/docs/(.*)", type: "wildcard" }, action: { kind: "redirect", status: 308, to: "/documentation/$1" }, }, - { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_app", port: 8080 } }, + { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "ws_app", port: 8080 } }, ]); }); @@ -155,7 +155,7 @@ describe("compileRoutingToOblien", () => { rewrites: [{ source: "/evil; } location / { proxy_pass http://x; }", destination: "/api" }], redirects: [{ source: "/r", destination: "/y; return 200 'pwned'" }], }, - { backend: { workspace: "ws_backend", port: 3000 } }, + { backend: { vm: "ws_backend", port: 3000 } }, ); expect(input.routes).toEqual([]); }); @@ -165,6 +165,6 @@ describe("compileRoutingToOblien", () => { describe("Cloud static fallback", () => { it.each([undefined, true, false])("carries the static setting to the provider: %s", (spaFallback) => { expect(compileRoutingToOblien({ spaFallback }, { staticPage: "site" }).spa).toBe(spaFallback); - expect(compileRoutingToOblien({ spaFallback }, { root: { workspace: "app", port: 8080 } })).not.toHaveProperty("spa"); + expect(compileRoutingToOblien({ spaFallback }, { root: { vm: "app", port: 8080 } })).not.toHaveProperty("spa"); }); }); diff --git a/packages/adapters/tsconfig.json b/packages/adapters/tsconfig.json index a22f17e3d..cc2e306d2 100644 --- a/packages/adapters/tsconfig.json +++ b/packages/adapters/tsconfig.json @@ -6,6 +6,6 @@ "types": ["node"], "outDir": "dist" }, - "include": ["src/**/*.ts"], + "include": ["src/**/*.ts", "scripts/verify-cloud-docker.ts", "scripts/verify-cloud-isolation.ts"], "exclude": ["node_modules", "dist"] } diff --git a/packages/contracts/src/deployments.ts b/packages/contracts/src/deployments.ts index 05b0d73e4..254f540ca 100644 --- a/packages/contracts/src/deployments.ts +++ b/packages/contracts/src/deployments.ts @@ -97,7 +97,7 @@ export const DeploymentSchema = Type.Object({ updatedAt: Type.String(), isActive: Type.Optional(Type.Boolean()), projectName: Type.Optional(Type.String()), - favicon: Type.Optional(Type.Union([Type.String(), Type.Null()])), + iconUrl: Type.Optional(Type.Union([Type.String(), Type.Null()])), }); export type Deployment = Static; diff --git a/packages/contracts/src/platform-migration.ts b/packages/contracts/src/platform-migration.ts index 267209c63..9d2ec55c9 100644 --- a/packages/contracts/src/platform-migration.ts +++ b/packages/contracts/src/platform-migration.ts @@ -72,6 +72,7 @@ export const PlatformMigrationPlanSchema = Type.Object({ planId: id, provider, projectName: text, + projects: Type.Optional(Type.Array(Type.Object({ name: text, serviceIds: Type.Array(id) }))), environmentName: text, targetServerId: id, services: Type.Array(PlatformImportServiceSchema), diff --git a/packages/contracts/src/project-inputs.ts b/packages/contracts/src/project-inputs.ts index d75ad8545..bfa89184c 100644 --- a/packages/contracts/src/project-inputs.ts +++ b/packages/contracts/src/project-inputs.ts @@ -8,6 +8,7 @@ import { Type, type Static, type TLiteral } from "@sinclair/typebox"; import { GitHubDeploymentChecksSchema } from "./deployment-checks"; import { STACK_IDS, + MAX_IMAGE_URL_LENGTH, RUNTIME_VERSION_PATTERN, RUNTIME_VERSION_MAX_LENGTH, ALL_PACKAGE_MANAGERS, @@ -559,7 +560,10 @@ export const CreateProjectBody = Type.Object({ // `serverId` is create/ensure-only. Keeping it out of the generic PATCH body is // also what keeps PROJECT_UPDATE_KEYS from becoming a target-retargeting path. -export const UpdateProjectBody = Type.Partial(Type.Omit(CreateProjectBody, ["serverId"])); +export const UpdateProjectBody = Type.Object({ + ...Type.Partial(Type.Omit(CreateProjectBody, ["serverId"])).properties, + iconUrl: Type.Optional(Type.Union([Type.String({ maxLength: MAX_IMAGE_URL_LENGTH }), Type.Null()])), +}); /** * POST /projects/ensure — CreateProjectBody plus an optional `projectId` to diff --git a/packages/contracts/src/project-integrations.ts b/packages/contracts/src/project-integrations.ts index 5b8f4797e..93a8c3551 100644 --- a/packages/contracts/src/project-integrations.ts +++ b/packages/contracts/src/project-integrations.ts @@ -55,18 +55,21 @@ export const ProjectEdgeConfigSchema = Type.Object({ })), }); +export const ProjectConnectionCandidateSchema = Type.Object({ + id: Type.String(), + name: Type.String(), + description: Type.String(), + appTemplateId: nullableString, + iconUrl: Type.Optional(nullableString), + framework: Type.Optional(nullableString), + clusterId: Type.Optional(nullableString), +}); +export type ProjectConnectionCandidate = Static; + export const ProjectIntegrationSchemas = { listConnectionCandidates: { action: "write", - output: Type.Array( - Type.Object({ - id: Type.String(), - name: Type.String(), - description: Type.String(), - appTemplateId: nullableString, - clusterId: Type.Optional(nullableString), - }), - ), + output: Type.Array(ProjectConnectionCandidateSchema), }, listConnections: { action: "read", output: Type.Array(ProjectConnectionSchema) }, listConnectionConsumers: { action: "read", output: Type.Array(ProjectConnectionConsumerSchema) }, diff --git a/packages/contracts/src/projects.ts b/packages/contracts/src/projects.ts index 41eb79398..6204f1de6 100644 --- a/packages/contracts/src/projects.ts +++ b/packages/contracts/src/projects.ts @@ -14,6 +14,7 @@ export const ProjectSchema = Type.Object({ groupId: Type.String({ minLength: 1 }), name: Type.String(), slug: Type.String(), + iconUrl: Type.Optional(nullableString()), createdAt: Type.String(), updatedAt: Type.String(), environmentName: Type.Optional(Type.String()), diff --git a/packages/core/src/apps/catalog.json b/packages/core/src/apps/catalog.json index 8b5151aa4..856f2ad0c 100644 --- a/packages/core/src/apps/catalog.json +++ b/packages/core/src/apps/catalog.json @@ -4177,7 +4177,7 @@ "services": [ { "name": "umami", - "image": "ghcr.io/umami-software/umami:postgresql-v2.20.2", + "image": "ghcr.io/umami-software/umami:3.4.1", "exposedPort": 3000, "exposed": true, "routes": [ diff --git a/packages/core/src/apps/catalog/umami.json b/packages/core/src/apps/catalog/umami.json index 24cbb8d6a..0325382e9 100644 --- a/packages/core/src/apps/catalog/umami.json +++ b/packages/core/src/apps/catalog/umami.json @@ -17,7 +17,7 @@ "services": [ { "name": "umami", - "image": "ghcr.io/umami-software/umami:postgresql-v2.20.2", + "image": "ghcr.io/umami-software/umami:3.4.1", "exposedPort": 3000, "exposed": true, "routes": [ diff --git a/packages/core/src/apps/umami.test.ts b/packages/core/src/apps/umami.test.ts index 1fc02cab8..2494a20b3 100644 --- a/packages/core/src/apps/umami.test.ts +++ b/packages/core/src/apps/umami.test.ts @@ -2,17 +2,21 @@ import { describe, expect, it } from "vitest"; import { getAppTemplate } from "../app-templates"; describe("Umami catalog security update", () => { - it("uses the security-patched v2 PostgreSQL release", () => { + it("uses the security-patched v3 PostgreSQL release", () => { const umami = getAppTemplate("umami"); const image = umami?.services?.find((service) => service.name === "umami")?.image; - const version = image?.match(/^ghcr\.io\/umami-software\/umami:postgresql-v2\.(\d+)\.(\d+)$/); + // v3 dropped the `postgresql-` tag prefix and MySQL support. The catalog + // already runs PostgreSQL and the container auto-applies Prisma migrations + // on start, so the pinned v3 image is a reviewed major upgrade. Moving off + // v3 needs a new migration review. + const version = image?.match(/^ghcr\.io\/umami-software\/umami:3\.(\d+)\.(\d+)$/); expect( version, - "Use an official patched v2 image; a major upgrade needs a migration review", + "Use an official patched v3 image; a major upgrade needs a migration review", ).toBeTruthy(); const [, minor, patch] = version!; - // v2.20.2 carries the Next.js / React Server Components security fixes. - expect(Number(minor) > 20 || (Number(minor) === 20 && Number(patch) >= 2)).toBe(true); + // v3.4.1 carries the Next.js 16.4.2 / React 19.3.1 security fixes. + expect(Number(minor) > 4 || (Number(minor) === 4 && Number(patch) >= 1)).toBe(true); }); it("preserves the existing database, volume, and generated secret contract", () => { diff --git a/packages/core/src/image-url.test.ts b/packages/core/src/image-url.test.ts new file mode 100644 index 000000000..79a613338 --- /dev/null +++ b/packages/core/src/image-url.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vitest"; +import { isImageUrl, MAX_IMAGE_URL_LENGTH } from "./image-url"; + +describe("display image URLs", () => { + it.each([ + "https://cdn.example.test/avatar.png?v=2", + "http://images.example.test/icon.svg", + "https://example.test/a%20b.png", + ])("accepts %s", (url) => expect(isImageUrl(url)).toBe(true)); + it.each([ + null, + 123, + "", + "/icon.png", + "//example.test/icon", + "javascript:alert(1)", + "data:image/svg+xml,", + "file:///etc/passwd", + "blob:https://example.test/id", + "https://user:password@example.test/a.png", + "https://example.test/\nimage.png", + " https://example.test/image.png", + `https://example.test/${"a".repeat(MAX_IMAGE_URL_LENGTH)}`, + ])("refuses unsafe or malformed input %j", (url) => expect(isImageUrl(url)).toBe(false)); +}); diff --git a/packages/core/src/image-url.ts b/packages/core/src/image-url.ts new file mode 100644 index 000000000..137c1d4a6 --- /dev/null +++ b/packages/core/src/image-url.ts @@ -0,0 +1,23 @@ +/** Image URLs are displayed by the browser, never fetched by the control plane. */ +export const MAX_IMAGE_URL_LENGTH = 2048; + +export function isImageUrl(value: unknown): value is string { + if ( + typeof value !== "string" || + !/^https?:\/\//i.test(value) || + value.length > MAX_IMAGE_URL_LENGTH || + /[\u0000-\u0020\u007f]/.test(value) + ) + return false; + try { + const url = new URL(value); + return ( + (url.protocol === "https:" || url.protocol === "http:") && + !!url.hostname && + !url.username && + !url.password + ); + } catch { + return false; + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index fa306c0a2..2c33b6c39 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,4 +1,5 @@ export * from "./types"; +export * from "./image-url"; export * from "./docker-swarm"; export * from "./actions"; export * from "./action-capabilities"; diff --git a/packages/db/drizzle/0231_project_icon_url.sql b/packages/db/drizzle/0231_project_icon_url.sql new file mode 100644 index 000000000..5ecc9e5f7 --- /dev/null +++ b/packages/db/drizzle/0231_project_icon_url.sql @@ -0,0 +1 @@ +ALTER TABLE "project" ADD COLUMN IF NOT EXISTS "icon_url" text; diff --git a/packages/db/drizzle/0232_project_icon_cleanup.sql b/packages/db/drizzle/0232_project_icon_cleanup.sql new file mode 100644 index 000000000..9ba00e56a --- /dev/null +++ b/packages/db/drizzle/0232_project_icon_cleanup.sql @@ -0,0 +1,17 @@ +-- Preserve saved images before retiring automatic favicon discovery. +-- An explicit icon always wins; projects without one retain their existing image. +UPDATE "project" +SET "icon_url" = COALESCE( + "icon_url", + "favicon", + (SELECT "favicon" FROM "project_app" WHERE "id" = "project"."app_id") +) +WHERE "icon_url" IS NULL; +--> statement-breakpoint +ALTER TABLE "project" DROP COLUMN IF EXISTS "favicon"; +--> statement-breakpoint +ALTER TABLE "project" DROP COLUMN IF EXISTS "favicon_checked_at"; +--> statement-breakpoint +ALTER TABLE "project_app" DROP COLUMN IF EXISTS "favicon"; +--> statement-breakpoint +ALTER TABLE "project_app" DROP COLUMN IF EXISTS "favicon_checked_at"; diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index d7a930769..71b3a5a43 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -1618,6 +1618,20 @@ "when": 1794373201000, "tag": "0230_restore_workspace_security_fields", "breakpoints": true + }, + { + "idx": 231, + "version": "7", + "when": 1794373202000, + "tag": "0231_project_icon_url", + "breakpoints": true + }, + { + "idx": 232, + "version": "7", + "when": 1794373203000, + "tag": "0232_project_icon_cleanup", + "breakpoints": true } ] } diff --git a/packages/db/src/dump-roundtrip.test.ts b/packages/db/src/dump-roundtrip.test.ts index de514bf69..a2637d446 100644 --- a/packages/db/src/dump-roundtrip.test.ts +++ b/packages/db/src/dump-roundtrip.test.ts @@ -274,6 +274,35 @@ describe("whole-instance dump → restore round trip", () => { }, ); + it.each(["legacy", "group", "custom", "cleared"] as const)( + "restores %s project images into the single iconUrl field", + async (mode) => { + const original = await dumpSubgraph({ kind: "instance" }); + const archive = JSON.parse(JSON.stringify(original)) as typeof original; + const project = archive.tables.project![0]!; + project.favicon = "https://old.example.test/favicon.ico"; + project.faviconCheckedAt = "2026-11-01T12:00:00Z"; + const group = archive.tables.project_app!.find((row) => row.id === project.groupId)!; + group.favicon = "https://cdn.example.test/group.svg"; + if (mode === "custom") project.iconUrl = "https://cdn.example.test/custom.svg"; + else if (mode === "cleared") project.iconUrl = null; + else delete project.iconUrl; + if (mode === "group") project.favicon = null; + const expected = mode === "custom" ? project.iconUrl : mode === "cleared" ? null : mode === "group" ? group.favicon : project.favicon; + try { + await restoreSubgraph(archive, { mode: "wipe" }); + const restored = await dumpSubgraph({ kind: "instance" }); + expect(restored.tables.project![0]!.iconUrl).toBe(expected); + expect(restored.tables.project![0]).not.toHaveProperty("favicon"); + expect(restored.tables.project![0]).not.toHaveProperty("faviconCheckedAt"); + expect(restored.tables.project_app![0]).not.toHaveProperty("favicon"); + expect(project.faviconCheckedAt).toBe("2026-11-01T12:00:00Z"); + } finally { + await restoreSubgraph(original, { mode: "wipe" }); + } + }, + ); + it("lets callers include follow-up work in the same atomic restore transaction", async () => { const projectSpec = topoOrderedTables().find((s) => s.sqlName === "project")!; const [before] = (await db.select().from(projectSpec.table)) as Array>; diff --git a/packages/db/src/dump.ts b/packages/db/src/dump.ts index cd320b1c9..731d8d9ba 100644 --- a/packages/db/src/dump.ts +++ b/packages/db/src/dump.ts @@ -1773,6 +1773,11 @@ export async function restoreSubgraphInTransaction( } } + // Resolve legacy image inheritance once for large instance archives. + const legacyGroupIcons = new Map( + (dump.tables.project_app ?? []).map((group) => [group.id, group.favicon]), + ); + // Pre-compute the encrypted-column specs keyed by table so the insert // loop below can redact those fields without re-scanning ENCRYPTED_COLUMNS // per row. Redaction on restore is REQUIRED (not optional like the @@ -1835,6 +1840,11 @@ export async function restoreSubgraphInTransaction( const prepared = rows.map((r) => { const { row: next, dropped } = filterRowToKnownColumns(r, knownCols); for (const d of dropped) droppedCols.add(d); + // Archives from before iconUrl used a discovered favicon. Honor an explicit + // iconUrl (including a cleared null) when the archive already has the field. + if (spec.sqlName === "project" && !Object.hasOwn(r, "iconUrl")) { + next.iconUrl = r.favicon ?? legacyGroupIcons.get(r.groupId) ?? null; + } // Older instance dumps predate per-factor confirmation. Preserve active // authenticators while keeping unfinished enrollments unconfirmed. if (spec.sqlName === "two_factor" && !Object.hasOwn(r, "verified")) { diff --git a/packages/db/src/migrate-chain.test.ts b/packages/db/src/migrate-chain.test.ts index 6c50eecbb..de5aaf92b 100644 --- a/packages/db/src/migrate-chain.test.ts +++ b/packages/db/src/migrate-chain.test.ts @@ -268,6 +268,47 @@ describe("migration chain applies to an existing, populated database", () => { expect(await appliedMigrations(client)).toBe(total); }); + test("consolidates saved images into icon_url and preserves explicit icons and resets on retry", async () => { + const cutoff = journal.entries.findIndex((entry) => entry.tag === "0232_project_icon_cleanup"); + expect(journal.entries[cutoff - 1]?.tag).toBe("0231_project_icon_url"); + const legacy = migrationsPrefix(cutoff); + const { client, db } = await freshDb(); + try { + await migrate(db, { migrationsFolder: legacy }); + await client.exec(` + INSERT INTO organization (id, name) VALUES ('org', 'Existing organization'); + INSERT INTO project_app (id, organization_id, name, slug, favicon) VALUES + ('group', 'org', 'Apps', 'apps', NULL), + ('group-icon', 'org', 'Group image', 'group-image', 'https://cdn.example.test/group.svg'); + INSERT INTO project (id, organization_id, app_id, environment_slug, name, slug, favicon, icon_url) VALUES + ('legacy', 'org', 'group', 'legacy', 'Legacy', 'legacy', 'https://app.example.test/favicon.ico', NULL), + ('custom', 'org', 'group', 'custom', 'Custom', 'custom', 'https://old.example.test/favicon.ico', 'https://cdn.example.test/custom.svg'), + ('empty', 'org', 'group', 'empty', 'Empty', 'empty', NULL, NULL), + ('inherited', 'org', 'group-icon', 'inherited', 'Inherited', 'inherited', NULL, NULL); + `); + const projects = (await client.query>("SELECT * FROM project ORDER BY id")).rows; + const groups = (await client.query>("SELECT * FROM project_app ORDER BY id")).rows; + await migrate(db, { migrationsFolder: MIGRATIONS_DIR }); + expect((await client.query("SELECT * FROM project ORDER BY id")).rows).toEqual( + projects.map(({ favicon, favicon_checked_at: _, ...project }) => ({ + ...project, + icon_url: project.icon_url ?? favicon ?? (project.app_id === "group-icon" ? "https://cdn.example.test/group.svg" : null), + })), + ); + expect((await client.query("SELECT * FROM project_app ORDER BY id")).rows).toEqual( + groups.map(({ favicon: _, favicon_checked_at: _checked, ...group }) => group), + ); + await client.exec("UPDATE project SET icon_url = NULL WHERE id = 'legacy'"); + const customized = (await client.query("SELECT * FROM project ORDER BY id")).rows; + await migrate(db, { migrationsFolder: MIGRATIONS_DIR }); + expect((await client.query("SELECT * FROM project ORDER BY id")).rows).toEqual(customized); + expect(await appliedMigrations(client)).toBe(total); + } finally { + await client.close(); + rmSync(legacy, { recursive: true, force: true }); + } + }); + test("adds runtime roles after the applied lifecycle migration without changing existing releases", async () => { const cutoff = journal.entries.findIndex((entry) => entry.tag === "0192_runtime_roles"); expect(journal.entries[cutoff - 1]?.tag).toBe("0191_project_lifecycle_operation"); @@ -286,7 +327,7 @@ describe("migration chain applies to an existing, populated database", () => { await migrate(db, { migrationsFolder: MIGRATIONS_DIR }); expect((await client.query("SELECT * FROM project")).rows).toEqual( - projects.map((project) => ({ ...project, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false })), + projects.map(({ favicon, favicon_checked_at: _, ...project }) => ({ ...project, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false, icon_url: favicon })), ); expect((await client.query("SELECT * FROM deployment")).rows).toEqual( deployments.map((deployment) => ({ @@ -332,7 +373,7 @@ describe("migration chain applies to an existing, populated database", () => { expect(await db.select().from(schema.instanceController)).toEqual([]); expect(await db.select().from(schema.instanceHandoff)).toEqual([]); expect((await client.query("SELECT * FROM project")).rows).toEqual( - projects.map((project) => ({ ...project, github_checks: null, runtime_version: null, runtime_image: null, lifecycle_operation: null, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false })), + projects.map(({ favicon, favicon_checked_at: _, ...project }) => ({ ...project, github_checks: null, runtime_version: null, runtime_image: null, lifecycle_operation: null, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false, icon_url: favicon })), ); expect( (await client.query("SELECT * FROM drizzle.__drizzle_migrations ORDER BY id")).rows.slice( @@ -530,11 +571,12 @@ describe("migration chain applies to an existing, populated database", () => { expect(managed).toHaveLength(2); for (const row of (await selectProjects()).rows) { const old = original.find((project) => project.id === row.id)!; - const { cloud_workspace_id: _native, cloud_archive_strategy: _archive, ...previous } = old as typeof old & Record; + const { cloud_workspace_id: _native, cloud_archive_strategy: _archive, favicon, favicon_checked_at: _checked, ...previous } = old as typeof old & Record; expect(row).toEqual({ ...previous, runtime_version: null, runtime_image: null, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false, + icon_url: favicon, cloud_promotion: null, lifecycle_operation: null, cloud_static_hosting: "pages", diff --git a/packages/db/src/repos/deployment.repo.ts b/packages/db/src/repos/deployment.repo.ts index add5653d8..9defd12db 100644 --- a/packages/db/src/repos/deployment.repo.ts +++ b/packages/db/src/repos/deployment.repo.ts @@ -626,7 +626,7 @@ export function createDeploymentRepo(db: Database, encryption: ConfigurationEncr async listHistoryProjects(organizationId: string) { return db.selectDistinct({ id: project.id, name: project.name, - activeDeploymentId: project.activeDeploymentId, favicon: project.favicon, + activeDeploymentId: project.activeDeploymentId, iconUrl: project.iconUrl, }).from(project).innerJoin(deployment, eq(deployment.projectId, project.id)) .where(and(eq(project.organizationId, organizationId), eq(deployment.organizationId, organizationId))) .orderBy(project.name, project.id); diff --git a/packages/db/src/repos/project.repo.ts b/packages/db/src/repos/project.repo.ts index ffe4aa891..4488d9649 100644 --- a/packages/db/src/repos/project.repo.ts +++ b/packages/db/src/repos/project.repo.ts @@ -661,25 +661,6 @@ export function createProjectRepo(db: Database, encryption: ConfigurationEncrypt }).where(eq(project.id, id)); }, - /** Update favicon cache metadata without touching the user-visible updatedAt field. */ - async updateFaviconCache( - id: string, - data: { favicon?: string | null; faviconCheckedAt?: Date | null }, - ) { - const patch: Partial = {}; - - if (Object.prototype.hasOwnProperty.call(data, "favicon")) { - patch.favicon = data.favicon ?? null; - } - if (Object.prototype.hasOwnProperty.call(data, "faviconCheckedAt")) { - patch.faviconCheckedAt = data.faviconCheckedAt ?? null; - } - - if (Object.keys(patch).length === 0) return; - - await db.update(project).set(patch).where(eq(project.id, id)); - }, - /** Soft-delete a project */ async softDelete(id: string) { await withProjectConfigurationWrite(db, eq(project.id, id), async (tx) => tx diff --git a/packages/db/src/schema/project.ts b/packages/db/src/schema/project.ts index 023ae9fe3..098ae3a3d 100644 --- a/packages/db/src/schema/project.ts +++ b/packages/db/src/schema/project.ts @@ -69,10 +69,6 @@ export const projectGroup = pgTable("project_app", { gitUrl: text("git_url"), installationId: integer("installation_id"), - /** Shared favicon cache */ - favicon: text("favicon"), - faviconCheckedAt: timestamp("favicon_checked_at"), - deletedAt: timestamp("deleted_at"), createdAt: timestamp("created_at").notNull().defaultNow(), updatedAt: timestamp("updated_at").notNull().defaultNow(), @@ -499,10 +495,8 @@ export const project = pgTable( * nobody opted into paying for this, so nobody keeps paying for it silently. */ collectPaths: boolean("collect_paths").notNull().default(false), - /** Auto-detected favicon URL from the deployed site */ - favicon: text("favicon"), - /** Last time favicon detection was attempted for this project */ - faviconCheckedAt: timestamp("favicon_checked_at"), + /** Project display image, managed in project settings. */ + iconUrl: text("icon_url"), /** Soft delete */ deletedAt: timestamp("deleted_at"), /** diff --git a/packages/platform/src/authorization.ts b/packages/platform/src/authorization.ts index ec818a7db..1411936e1 100644 --- a/packages/platform/src/authorization.ts +++ b/packages/platform/src/authorization.ts @@ -99,7 +99,8 @@ export interface AuthorizationDependencies { } export interface PermissionOptions { - roleOverride?: ContextRole; + /** A credential may narrow membership authority to its own grants. */ + roleOverride?: "restricted"; grants?: PermissionGrantSource; } @@ -118,14 +119,15 @@ export const PROJECT_ROOTED: ReadonlySet = new Set([ "build_session", ]); -/** Shared with capability discovery; restricted roles use grants instead. */ +/** Shared role ceiling for execution and discovery; restricted roles use grants. */ export function roleAllowsResourceType( role: "owner" | "admin" | "member", type: CheckedResourceType, + action: Permission, ): boolean { if (role === "owner") return true; if (role === "admin") return type !== "billing"; - return type !== "billing" && type !== "audit"; + return action !== "admin" && type !== "billing" && type !== "audit"; } export function permitsAction(permissions: readonly GrantPermission[], action: Permission): boolean { @@ -262,10 +264,12 @@ export function createAuthorization(deps: AuthorizationDependencies) { if (!["read", "write", "admin", "create"].includes(input.action)) return false; const persistedRole = membershipRole(member); if (!persistedRole) return false; - const role = opts?.roleOverride ?? persistedRole; - if (role === "owner" || role === "admin" || role === "member") - return roleAllowsResourceType(role, input.resourceType); - if (role !== "restricted") return false; + // A token narrows its user's current authority. A previously minted grant + // must not retain administration after that user is demoted to member. + if (persistedRole !== "restricted") { + if (!roleAllowsResourceType(persistedRole, input.resourceType, input.action)) return false; + if (opts?.roleOverride !== "restricted") return true; + } const source = opts?.grants ?? repos.resourceGrant; // A create-only wildcard permits creation and a filtered list, never an diff --git a/packages/platform/src/engine/config/env.ts b/packages/platform/src/engine/config/env.ts index fe6eb4b37..1be661c5a 100644 --- a/packages/platform/src/engine/config/env.ts +++ b/packages/platform/src/engine/config/env.ts @@ -375,8 +375,8 @@ const envSchema = z.object({ OBLIEN_CLIENT_ID: z.string().optional(), OBLIEN_CLIENT_SECRET: z.string().optional(), /** Control-plane endpoint. Override only for an Oblien staging installation. */ - OBLIEN_API_URL: z.url().default("https://api.oblien.com"), - OBLIEN_RUNTIME_URL: z.url().default("https://workspace.oblien.com"), + OBLIEN_API_URL: z.url().optional(), + OBLIEN_RUNTIME_URL: z.url().default("https://vm.oblien.com"), /** Optional published software preset for NEW managed Docker workspaces. */ OBLIEN_DOCKER_PRESET: z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/).optional(), /** diff --git a/packages/platform/src/engine/lib/auth.ts b/packages/platform/src/engine/lib/auth.ts index 0528fa7fb..b51d75b0c 100644 --- a/packages/platform/src/engine/lib/auth.ts +++ b/packages/platform/src/engine/lib/auth.ts @@ -1,3 +1,4 @@ +import { isImageUrl } from "@repo/core"; import { diagnostics as errorDiagnostics } from "@repo/core/diagnostics"; import { organizationOptions, isSaasDeployment } from "./organization-lifecycle"; import { betterAuth, type User } from "better-auth"; @@ -278,6 +279,14 @@ export const auth = betterAuth({ /* ---------- Database hooks ---------- */ databaseHooks: { user: { + update: { + before: async (user) => { + if (user.image === undefined) return; + const image = typeof user.image === "string" ? user.image.trim() || null : user.image; + if (image !== null && !isImageUrl(image)) throw new APIError("BAD_REQUEST", { message: "Avatar URL must be an HTTP or HTTPS URL without credentials." }); + return { data: { ...user, image } }; + }, + }, create: { before: async (user, ctx) => { const denyCreation = (message: string): never => { diff --git a/packages/platform/src/engine/lib/cloud-capacity.ts b/packages/platform/src/engine/lib/cloud-capacity.ts index c651a5934..3c4696c2c 100644 --- a/packages/platform/src/engine/lib/cloud-capacity.ts +++ b/packages/platform/src/engine/lib/cloud-capacity.ts @@ -14,7 +14,7 @@ const workspaceResources = z.object({ /** One ownership/shape check for both previews and deployment admission. */ export async function readCloudWorkspaceAllocation(workspaceId: string, namespace: string) { - const workspace = await getOblienClient().workspaces.get(workspaceId); + const workspace = await getOblienClient().vms.get(workspaceId); if (workspace.id !== workspaceId || workspace.namespace !== namespace) { throw new AppError("Cloud workspace ownership changed", 409, "CLOUD_NAMESPACE_MISMATCH"); } diff --git a/packages/platform/src/engine/lib/cloud-docker-workspace.ts b/packages/platform/src/engine/lib/cloud-docker-workspace.ts index b946e6500..65b9334d1 100644 --- a/packages/platform/src/engine/lib/cloud-docker-workspace.ts +++ b/packages/platform/src/engine/lib/cloud-docker-workspace.ts @@ -42,10 +42,10 @@ export async function findOwnedDockerWorkspace( ownerWorkspaceId: string, namespace: string, ) { - let found: Awaited> | undefined; + let found: Awaited> | undefined; for (let page = 1; ; page++) { - const result = await client.workspaces.list({ page, limit: 100 }); - const matches = result.workspaces.filter( + const result = await client.vms.list({ page, limit: 100 }); + const matches = result.vms.filter( (item) => item.slug === workspaceSlug(ownerWorkspaceId) && item.namespace === namespace, ); for (const workspace of matches) { @@ -55,7 +55,7 @@ export async function findOwnedDockerWorkspace( ); found = workspace; } - if (!result.workspaces.length || page * result.limit >= result.total) return found; + if (!result.vms.length || page * result.limit >= result.total) return found; } } @@ -78,7 +78,7 @@ export async function resizeDockerWorkspace(input: { save(workloads: NonNullable): Promise; }; }) { - const ws = input.client.workspace(input.workspaceId); + const ws = input.client.vm(input.workspaceId); const executor = new CloudWorkspaceExecutor(options => ws.runtime(options), input.workspaceId); try { const inspect = () => @@ -331,7 +331,7 @@ async function ensureDockerHost( ); input.signal.throwIfAborted(); } - const workspace = await client.workspaces + const workspace = await client.vms .create({ name: managed.name, slug: workspaceSlug(ownerId), @@ -355,7 +355,7 @@ async function ensureDockerHost( .catch(async (error) => { const failure = cloudWorkspaceCreationFailure(error); if (failure.workspaceId) { - const created = await client.workspaces.get(failure.workspaceId); + const created = await client.vms.get(failure.workspaceId); if ( created.id !== failure.workspaceId || created.namespace !== namespace || @@ -387,7 +387,7 @@ async function ensureDockerHost( // Complete this even after cancellation: retries must know which disk exists. await repos.cloudDockerWorkspace.attach(owner, input.organizationId, namespace, workspaceId); } - const ws = client.workspace(workspaceId); + const ws = client.vm(workspaceId); const current = await ws.get(); if (current.namespace !== namespace) throw new Error("Cloud workspace namespace changed"); input.signal?.throwIfAborted(); @@ -397,7 +397,7 @@ async function ensureDockerHost( input.onProgress?.( "Retrying the managed server's initial provisioning with its existing disk.\n", ); - const retried = await client.workspaces.retryCreation(workspaceId); + const retried = await client.vms.retryCreation(workspaceId); if (retried.id !== workspaceId || retried.namespace !== namespace) throw new Error("Cloud provisioning retry returned an unexpected workspace"); } else if (status === "stopped") await ws.start(); diff --git a/packages/platform/src/engine/lib/cloud-preflight.ts b/packages/platform/src/engine/lib/cloud-preflight.ts index 8515d80d3..b3256be79 100644 --- a/packages/platform/src/engine/lib/cloud-preflight.ts +++ b/packages/platform/src/engine/lib/cloud-preflight.ts @@ -1,5 +1,5 @@ import { reportCaughtError as observeCaughtError, diagnostics as errorDiagnostics } from "@repo/core/diagnostics"; -import { createPlatform, type CloudInfraProvider } from "@repo/adapters"; +import { createPlatform, oblienApiBaseUrl, type CloudInfraProvider } from "@repo/adapters"; import { ensureNamespace, getOblienClient, issueNamespaceToken } from "./openship-cloud"; import { env } from "../config/env"; import { assertCloudCanSpend } from "../modules/billing/billing-oblien-quota"; @@ -99,7 +99,7 @@ export async function runCloudPreflight( await assertCloudCanSpend(organizationId, opts.workspaceId); const cloudPlatform = await createPlatform({ target: "cloud", cloudToken: token.token, cloudNamespace: token.namespace, - cloudApiUrl: env.OBLIEN_API_URL, + cloudApiUrl: oblienApiBaseUrl(env.OBLIEN_API_URL).toString(), }); cloud = cloudPlatform.routing as CloudInfraProvider; } catch (err) { diff --git a/packages/platform/src/engine/lib/cloud-resource-limits.ts b/packages/platform/src/engine/lib/cloud-resource-limits.ts index 64455831a..eac0f264c 100644 --- a/packages/platform/src/engine/lib/cloud-resource-limits.ts +++ b/packages/platform/src/engine/lib/cloud-resource-limits.ts @@ -1,6 +1,7 @@ import { AppError, resolvePlan, type CloudCapacityPool, type PlanTierId } from "@repo/core"; import { getOblienClient } from "./oblien-client"; import { z } from "zod"; +import { toOblienVmLimits, type NamespaceResourceLimits } from "@repo/adapters"; type NamespaceLimits = ReturnType; @@ -10,8 +11,8 @@ export function cloudNamespaceLimits(tier: PlanTierId) { return { ...resolvePlan(tier).oblienLimits }; } -export async function initialCloudNamespaceLimits(): Promise { - return cloudNamespaceLimits("free"); +export async function initialCloudNamespaceLimits() { + return toOblienVmLimits(cloudNamespaceLimits("free")); } /** Submit the verified subscription's declared policy under the billing lock. @@ -25,13 +26,14 @@ export async function syncCloudResourceLimits( ): Promise { const client = getOblienClient(); const { data: current } = await client.namespaces.get(namespace); + const providerLimits = toOblienVmLimits(desired); if (current.slug !== namespace) throw new AppError("Cloud namespace ownership changed", 502, "CLOUD_NAMESPACE_MISMATCH"); // Compare declared policy, never Oblien's effective_resource_limits: account // capacity may change without changing the customer's purchase contract. - const matches = (limits: Partial | null | undefined) => - (Object.keys(desired) as Array).every(key => (limits?.[key] ?? null) === desired[key]); + const matches = (limits: NamespaceResourceLimits | null | undefined) => + (Object.keys(providerLimits) as Array).every(key => (limits?.[key] ?? null) === providerLimits[key]); if (matches(current.resource_limits)) return; - const { data: updated } = await client.namespaces.update(current.id, { resource_limits: { ...desired } }); + const { data: updated } = await client.namespaces.update(current.id, { resource_limits: providerLimits }); if (updated.slug !== namespace || !matches(updated.resource_limits)) { throw new AppError("Cloud resource limits were not confirmed", 502, "CLOUD_RESOURCE_LIMITS_UNCONFIRMED"); } @@ -39,13 +41,13 @@ export async function syncCloudResourceLimits( const capacityResponse = z.object({ success: z.literal(true), data: z.object({ slug: z.string(), - effective_resource_limits: z.object({ max_workspaces: z.number().nonnegative().nullable(), + effective_resource_limits: z.object({ max_vms: z.number().nonnegative().nullable(), max_vcpus: z.number().nonnegative().nullable().optional(), max_ram_mb: z.number().nonnegative().nullable().optional(), max_disk_gb: z.number().nonnegative().nullable().optional(), max_total_vcpus: z.number().nonnegative().nullable(), max_total_ram_mb: z.number().nonnegative().nullable(), max_total_disk_gb: z.number().nonnegative().nullable() }).optional(), - allocated_resource_usage: z.object({ workspaces: z.number().nonnegative(), vcpus: z.number().nonnegative(), + allocated_resource_usage: z.object({ vms: z.number().nonnegative(), vcpus: z.number().nonnegative(), ram_mb: z.number().nonnegative(), disk_gb: z.number().nonnegative(), pending_updates: z.number().int().nonnegative() }).optional(), }) }); @@ -63,7 +65,7 @@ function presentCapacity(data: Awaited> const limits = data.effective_resource_limits, used = data.allocated_resource_usage; if (!limits || !used) return {}; return { - workspaces: { used: used.workspaces, max: limits.max_workspaces }, + workspaces: { used: used.vms, max: limits.max_vms }, vcpus: { used: used.vcpus, max: limits.max_total_vcpus }, ramMb: { used: used.ram_mb, max: limits.max_total_ram_mb }, diskGb: { used: used.disk_gb, max: limits.max_total_disk_gb }, diff --git a/packages/platform/src/engine/lib/cloud-tenant-admin.ts b/packages/platform/src/engine/lib/cloud-tenant-admin.ts index 8be2b268f..f7f0b032b 100644 --- a/packages/platform/src/engine/lib/cloud-tenant-admin.ts +++ b/packages/platform/src/engine/lib/cloud-tenant-admin.ts @@ -17,7 +17,7 @@ export function createTenantCloudAdmin(organizationId: string, namespace: string }; const requireWorkspace = async (id: string) => { validateId(id); - const workspace = await admin.workspaces.get(id); + const workspace = await admin.vms.get(id); if (workspace.namespace !== namespace) throw deny(); return workspace; }; @@ -47,13 +47,13 @@ export function createTenantCloudAdmin(organizationId: string, namespace: string get: requirePage, create: async (input) => { if (input.slug) validateId(input.slug); - await requireWorkspace(input.workspace_id); + await requireWorkspace(input.vm_id); await assertCloudCanSpend(organizationId, workspaceId); return admin.pages.create({ ...input, namespace }); }, deploy: async (slug, input) => { await requirePage(slug); - await requireWorkspace(input.workspace_id); + await requireWorkspace(input.vm_id); await assertCloudCanSpend(organizationId, workspaceId); return admin.pages.deploy(slug, input); }, @@ -83,14 +83,14 @@ export function createTenantCloudAdmin(organizationId: string, namespace: string if (!owned) throw deny(); if (input.static) await requirePage(input.static.page); const workspaces = new Set(); - for (const rule of input.routes) { + for (const rule of input.routes ?? []) { if (rule.action.kind !== "proxy") continue; // External origins need separate tenant ownership verification. Admin // scope alone would authorize another customer's verified origin. - if (rule.action.origin || !rule.action.workspace) { + if (rule.action.origin || !rule.action.vm) { throw new AppError("Cloud routes must target a workspace in this organization", 400, "CLOUD_ROUTE_TARGET_INVALID"); } - workspaces.add(rule.action.workspace); + workspaces.add(rule.action.vm); } await Promise.all([...workspaces].map(requireWorkspace)); return admin.routes.set(normalized, input); diff --git a/packages/platform/src/engine/lib/cloud-workspace-host.ts b/packages/platform/src/engine/lib/cloud-workspace-host.ts index 2ca3a9305..cd3175dc9 100644 --- a/packages/platform/src/engine/lib/cloud-workspace-host.ts +++ b/packages/platform/src/engine/lib/cloud-workspace-host.ts @@ -32,7 +32,7 @@ export async function readCloudWorkspaceHost(organizationId: string, id: string) if (!env.CLOUD_MODE) { const connection = await remoteServerConnection(organizationId, id); const { client } = await getNamespaceClient(organizationId, id, connection); - const workspace = await client.workspaces.get(connection.workspaceId); + const workspace = await client.vms.get(connection.workspaceId); if (workspace.namespace !== connection.namespace) throw new AppError("Cloud space ownership changed", 409, "CLOUD_NAMESPACE_MISMATCH"); if (workspace.id !== connection.workspaceId) throw new AppError("Cloud returned a different Cloud space", 502, "CLOUD_SERVER_IDENTITY_MISMATCH"); @@ -76,7 +76,7 @@ async function runningConnection(organizationId: string, id: string) { * a host or installing the Docker API bridge just to read metrics/open a shell. */ export async function openCloudWorkspaceExecutor(organizationId: string, id: string) { const { client, binding } = await runningConnection(organizationId, id); - return new CloudWorkspaceExecutor(options => client.workspace(binding.workspaceId!).runtime(options), binding.workspaceId!); + return new CloudWorkspaceExecutor(options => client.vm(binding.workspaceId!).runtime(options), binding.workspaceId!); } /** Server-authorized Docker operations (inventory and migration). Applications @@ -127,7 +127,7 @@ async function measuredHost(organizationId: string, id: string) { export async function sampleCloudWorkspaceResources(organizationId: string, id: string, sampleUsage = true) { const { client, binding, provider } = await runningConnection(organizationId, id); if (!sampleUsage) return { capacity: provider.allocation, usage: unavailableServerUsage("Not sampled for an uncapped build") }; - const executor = new CloudWorkspaceExecutor(options => client.workspace(binding.workspaceId!).runtime(options), binding.workspaceId!); + const executor = new CloudWorkspaceExecutor(options => client.vm(binding.workspaceId!).runtime(options), binding.workspaceId!); try { return { capacity: provider.allocation, usage: await sampleServerUsage(executor) }; } finally { diff --git a/packages/platform/src/engine/lib/cloud/project-promotion.ts b/packages/platform/src/engine/lib/cloud/project-promotion.ts index 62284ce18..20a1679e6 100644 --- a/packages/platform/src/engine/lib/cloud/project-promotion.ts +++ b/packages/platform/src/engine/lib/cloud/project-promotion.ts @@ -45,8 +45,6 @@ export function projectPromotionDigest(dump: DatabaseDump): string { delete row.deletionInProgress; delete row.lifecycleOperation; delete row.updatedAt; - delete row.favicon; - delete row.faviconCheckedAt; } for (const [name, rows] of Object.entries(tables)) { tables[name] = rows diff --git a/packages/platform/src/engine/lib/cloud/types.ts b/packages/platform/src/engine/lib/cloud/types.ts index bc667d548..530b6a914 100644 --- a/packages/platform/src/engine/lib/cloud/types.ts +++ b/packages/platform/src/engine/lib/cloud/types.ts @@ -115,7 +115,7 @@ export interface CloudClient { }; pages: { create(input: { - workspace_id: string; + vm_id: string; path: string; name: string; slug: string; diff --git a/packages/platform/src/engine/lib/favicon-detector.ts b/packages/platform/src/engine/lib/favicon-detector.ts deleted file mode 100644 index f0eb03024..000000000 --- a/packages/platform/src/engine/lib/favicon-detector.ts +++ /dev/null @@ -1,159 +0,0 @@ -/** - * Favicon detection - check if a deployed site has a favicon. - * - * Called asynchronously on project reads when the favicon cache is stale. - * Simply checks /favicon.ico - the universal standard. - * - * Returns an absolute URL string or null. - */ - -import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics"; -import { repos } from "@repo/db"; -import { env } from "../config/env"; -import { safeFetch } from "./safe-fetch"; -import { trackBackgroundWork } from "./background-work"; - -const FETCH_TIMEOUT = 8_000; -const FAVICON_REFRESH_TTL_MS = 24 * 60 * 60 * 1000; -const inFlightRefreshes = new Set(); - -interface FaviconRefreshProject { - id: string; - slug?: string | null; - activeDeploymentId?: string | null; - favicon?: string | null; - faviconCheckedAt?: Date | string | null; -} - -interface RefreshOptions { - hostname?: string | null; -} - -function normalizeSiteUrl(siteUrlOrHostname: string): string { - const trimmed = siteUrlOrHostname.trim().replace(/\/$/, ""); - if (!trimmed) return ""; - if (/^https?:\/\//i.test(trimmed)) return trimmed; - return `https://${trimmed}`; -} - -function isRefreshDue(project: FaviconRefreshProject): boolean { - if (!project.faviconCheckedAt) return true; - - const checkedAt = new Date(project.faviconCheckedAt); - if (Number.isNaN(checkedAt.getTime())) return true; - - return Date.now() - checkedAt.getTime() >= FAVICON_REFRESH_TTL_MS; -} - -async function resolvePreferredSiteUrl( - project: FaviconRefreshProject, - options?: RefreshOptions, -): Promise { - if (options?.hostname?.trim()) { - return normalizeSiteUrl(options.hostname); - } - - const primaryDomain = await repos.domain.getPrimaryByProject(project.id); - if (primaryDomain?.verified && primaryDomain.hostname?.trim()) { - return normalizeSiteUrl(primaryDomain.hostname); - } - - return null; -} - -async function probeFavicon(siteUrl: string): Promise { - const base = normalizeSiteUrl(siteUrl); - if (!base) return null; - - const faviconUrl = `${base}/favicon.ico`; - - const tryProbe = async (method: "HEAD" | "GET") => { - // SSRF-safe: `base` is a project's (attacker-controllable-DNS) domain. Pin the - // resolved IP; reject internal targets on the multi-tenant SaaS, allow the - // operator's own LAN on self-hosted. - const res = await safeFetch(faviconUrl, { - method, - timeoutMs: FETCH_TIMEOUT, - allowHttp: true, - allowPrivate: !env.CLOUD_MODE, - maxRedirects: 3, - }); - - if (!res.ok) { - return null; - } - - const ct = res.headers["content-type"] ?? ""; - if (ct.startsWith("image/") || ct === "application/octet-stream") { - return faviconUrl; - } - - return null; - }; - - const headResult = await tryProbe("HEAD"); - if (headResult) { - return headResult; - } - - const getResult = await tryProbe("GET"); - if (getResult) { - return getResult; - } - - return null; -} - -export function refreshProjectFaviconIfStale( - project: FaviconRefreshProject, - options?: RefreshOptions, -): void { - if (!project.activeDeploymentId || !isRefreshDue(project)) { - return; - } - - if (inFlightRefreshes.has(project.id)) { - return; - } - - inFlightRefreshes.add(project.id); - void trackBackgroundWork((async () => { - const siteUrl = await resolvePreferredSiteUrl(project, options); - if (!siteUrl) { - return; - } - - await detectAndStoreFavicon(project.id, siteUrl); - })() - .catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "platform/engine/lib/favicon-detector"); return undefined; }) - .finally(() => { - inFlightRefreshes.delete(project.id); - })); -} - -/** - * Detect and store the favicon for a deployed project. - * Best-effort: update the cache timestamp on every attempt, but only replace - * the stored favicon URL when the fetch succeeds. - */ -export async function detectAndStoreFavicon(projectId: string, siteUrl: string): Promise { - const checkedAt = new Date(); - - try { - const faviconUrl = await probeFavicon(siteUrl); - if (faviconUrl) { - await repos.project.updateFaviconCache(projectId, { - favicon: faviconUrl, - faviconCheckedAt: checkedAt, - }); - return; - } - } catch (diagnosticFailure) { - observeCaughtError(diagnosticFailure, "platform/engine/lib/favicon-detector"); - // Best-effort - don't break anything if this fails - } - - await repos.project.updateFaviconCache(projectId, { - faviconCheckedAt: checkedAt, - }).catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "platform/engine/lib/favicon-detector"); return undefined; }); -} diff --git a/packages/platform/src/engine/lib/oblien-billing-api.ts b/packages/platform/src/engine/lib/oblien-billing-api.ts index e8b612c25..6d9e7ee50 100644 --- a/packages/platform/src/engine/lib/oblien-billing-api.ts +++ b/packages/platform/src/engine/lib/oblien-billing-api.ts @@ -3,7 +3,7 @@ import { withDiagnosticSpan } from "@repo/core/diagnostics/node"; import { z } from "zod"; import { AppError } from "@repo/core"; import { OperationError } from "@repo/contracts"; -import { Oblien } from "@repo/adapters"; +import { Oblien, oblienApiBaseUrl, oblienApiUrl, toOblienVmOffer, toOblienVmPolicy, cloudBillingContract } from "@repo/adapters"; import { isDeepStrictEqual } from "node:util"; import { computeBillingModeSchema, oblienCapacityCatalogSchema, oblienCapacityPoolSchema, oblienNamespaceCapacitySchema } from "./oblien-capacity"; @@ -197,7 +197,7 @@ export type OblienPlanChangeQuote = z.infer; export type OblienPlanChange = z.infer; const policySchema = z.object({ - success: z.literal(true), service: z.literal("workspace_vm"), + success: z.literal(true), service: z.literal("vm_compute"), quotaLimit: allowance, overdraft: amount.nonnegative(), onOverdraftAction: z.enum(["stop_workspaces", "block"]), suspendThreshold: allowance, }); @@ -231,12 +231,13 @@ export function assertOblienEntitlementMatchesSubscription(entitlement: OblienEn const monthly = subscription?.offer?.billingMode === "monthly"; const expectedTier = monthly ? "capacity" : subscription?.tierId ?? "free"; const capacity = entitlement.capacity; - // An unpaid renewal advances Stripe's invoice period without buying another - // month of compute. The retained, expired capacity still describes the last - // funded period. Keep billing readable so the customer can pay, while the - // provider's uncovered entitlement continues to block new billable work. + // Stripe can advance an active subscription's period while its renewal invoice + // is still a draft, before attempting payment. An overdue renewal has the same + // period split: expired capacity describes the last funded month. Accept this + // uncovered state for billing/management reads without granting compute or + // inventing a grace period; billable work still requires provider coverage. const unpaidRenewal = monthly && subscription && - ["past_due", "unpaid", "paused", "canceled"].includes(subscription.status) && + ["active", "past_due", "unpaid", "paused", "canceled"].includes(subscription.status) && entitlement.status !== "active" && entitlement.computeCovered === false && capacity?.computeCovered === false && capacity.status === "expired" && entitlement.periodStart !== null && entitlement.periodEnd !== null && @@ -314,11 +315,7 @@ export class OblienBillingApi { clientId?: string; clientSecret?: string; baseUrl?: string; fetch?: typeof fetch; timeoutMs?: number; } = {}) { - const url = new URL(options.baseUrl ?? "https://api.oblien.com"); - if (url.username || url.password || url.search || url.hash || - (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)))) { - throw new Error("Oblien API URL must use HTTPS (HTTP is allowed for localhost tests)"); - } + const url = oblienApiBaseUrl(options.baseUrl); this.baseUrl = url.toString().replace(/\/+$/, ""); this.fetcher = options.fetch ?? fetch; // The SDK has no client-wide fetch/timeout option. Replace this transport @@ -336,7 +333,7 @@ export class OblienBillingApi { private async requestBilling({ method, path, body, query }: Parameters[0]): Promise { const meteredPricing = method === "GET" && path === "/pricing/calculator"; if (!path.startsWith("/billing/") && !meteredPricing) throw new Error("Billing transport only accepts billing routes"); - const url = new URL(`${this.baseUrl}${path}`); + const url = oblienApiUrl(oblienApiBaseUrl(this.baseUrl), path); for (const [key, value] of Object.entries(query ?? {})) { if (value !== undefined) url.searchParams.set(key, String(value)); } @@ -466,7 +463,7 @@ export class OblienBillingApi { ...(Object.keys(diagnostic).length ? { details: diagnostic } : {}), }); } - return payload as T; + return cloudBillingContract(payload) as T; } private async validate(response: Promise, schema: z.ZodType, slug?: string): Promise { @@ -612,7 +609,7 @@ export class OblienBillingApi { /** Mode A only: the complimentary-plan service owns these explicit grants. */ setPolicy(slug: string, input: Pick) { - return this.validate(this.billing.setPolicy(slug, input), policySchema.extend({ namespace }), slug); + return this.validate(this.billing.setPolicy(slug, toOblienVmPolicy(input)), policySchema.extend({ namespace }), slug); } resetQuota(slug: string, periodEnd: string) { @@ -641,9 +638,10 @@ export class OblienBillingApi { async previewPlanChange(slug: string, input: OblienPlanChangeInput) { const request = oblienPlanChangeInputSchema.parse(input); + const offer = toOblienVmOffer(request.offer); const result = await this.validate(request.offer.billingMode === "service" - ? this.request({ method: "POST", path: "/billing/subscription/changes/preview", body: { namespace: slug, ...request } }) - : this.billing.previewPlanChange(slug, { ...request, offer: { ...request.offer, billingMode: request.offer.billingMode } }), z.object({ + ? this.request({ method: "POST", path: "/billing/subscription/changes/preview", body: { namespace: slug, ...request, offer } }) + : this.billing.previewPlanChange(slug, { ...request, offer: { ...offer, billingMode: request.offer.billingMode } }), z.object({ success: z.literal(true), namespace, quote: oblienPlanChangeQuoteSchema, }), slug); if (result.quote.namespace !== slug || result.quote.billingInterval !== input.billingInterval) @@ -691,9 +689,10 @@ export class OblienBillingApi { // and this saved namespace offer before creating the Stripe session. const parsed = oblienCheckoutInputSchema.parse(input); const request = { ...parsed, allowPromotionCodes: parsed.offer?.unitAmount !== 0 }; + const offer = request.offer ? toOblienVmOffer(request.offer) : undefined; const result = await this.validate((request.offer?.billingMode === "service" || (request.kind === "subscription" && !!request.affiliateBuyer)) - ? this.request({ method: "POST", path: "/billing/checkout", body: request }) - : this.billing.checkout({ ...request, offer: request.offer ? { ...request.offer, billingMode: request.offer.billingMode === "monthly" ? "monthly" : request.offer.billingMode === "payg" ? "payg" : undefined } : undefined }), checkoutSchema); + ? this.request({ method: "POST", path: "/billing/checkout", body: { ...request, offer } }) + : this.billing.checkout({ ...request, offer: offer ? { ...offer, billingMode: request.offer?.billingMode === "monthly" ? "monthly" : request.offer?.billingMode === "payg" ? "payg" : undefined } : undefined }), checkoutSchema); this.validateCheckoutUrl(result.url); return result; } @@ -702,6 +701,7 @@ export class OblienBillingApi { const url = new URL(value); if (url.hostname === "api.oblien.com") { this.validateHostedUrl(value, "api.oblien.com"); + // This is the hosted browser page, not a versioned control-plane endpoint. if (url.pathname === "/billing/pay" && !url.search && /^#[A-Za-z0-9_-]{43}$/.test(url.hash)) return; throw new AppError("Cloud billing returned an invalid hosted URL", 502, "OBLIEN_BILLING_INVALID_RESPONSE"); } diff --git a/packages/platform/src/engine/lib/oblien-namespace.ts b/packages/platform/src/engine/lib/oblien-namespace.ts index 850b79330..a387bd59b 100644 --- a/packages/platform/src/engine/lib/oblien-namespace.ts +++ b/packages/platform/src/engine/lib/oblien-namespace.ts @@ -1,4 +1,5 @@ -import { AppError, type OblienLimits } from "@repo/core"; +import { AppError } from "@repo/core"; +import type { NamespaceResourceLimits } from "@repo/adapters"; import { getOblienClient } from "./oblien-client"; import { ensureOblienDefaultQuota } from "../modules/billing/billing-oblien-quota"; @@ -7,7 +8,7 @@ import { ensureOblienDefaultQuota } from "../modules/billing/billing-oblien-quot export async function ensureCloudNamespace(input: { name: string; slug: string; - resource_limits: OblienLimits; + resource_limits: NamespaceResourceLimits; }): Promise { await ensureOblienDefaultQuota(); const ensured = await getOblienClient().namespaces.ensure(input); diff --git a/packages/platform/src/engine/lib/openship-cloud.ts b/packages/platform/src/engine/lib/openship-cloud.ts index 6552d0582..2cb6d116c 100644 --- a/packages/platform/src/engine/lib/openship-cloud.ts +++ b/packages/platform/src/engine/lib/openship-cloud.ts @@ -5,7 +5,7 @@ */ import { diagnostics as errorDiagnostics } from "@repo/core/diagnostics"; import { createHash } from "node:crypto"; -import { Oblien, OblienError } from "@repo/adapters"; +import { Oblien, OblienError, oblienApiBaseUrl } from "@repo/adapters"; import { OperationError } from "@repo/contracts"; import { AppError, safeErrorMessage } from "@repo/core"; import { repos } from "@repo/db"; @@ -108,7 +108,7 @@ export async function issueNamespaceToken(organizationId: string, workspaceId?: const namespace = await ensureNamespaceWithQuota(organizationId, workspaceId); try { const result = await getOblienClient().tokens.create({ scope: "namespace", namespace, ttl: 1800 }); - return { token: result.token, namespace, expiresAt: result.expiresAt, providerApiUrl: env.OBLIEN_API_URL }; + return { token: result.token, namespace, expiresAt: result.expiresAt, providerApiUrl: oblienApiBaseUrl(env.OBLIEN_API_URL).toString() }; } catch (error) { errorDiagnostics.warn("platform/engine/lib/openship-cloud", `[oblien] token issuance failed for org ${organizationId}: ${safeErrorMessage(error)}`, error); if (error instanceof OblienError && typeof error.status === "number" && [429, 502, 503, 504].includes(error.status)) { @@ -130,7 +130,7 @@ async function internalNamespaceToken(organizationId: string, workspaceId?: Clou // Authorization is always read before cache lookup. A token cache must never // turn a deleted/moved workspace into access granted by an earlier request. const namespace = await ensureNamespaceWithQuota(organizationId, workspaceId); - const key = namespaceTokenKey(organizationId, namespace, env.OBLIEN_API_URL); + const key = namespaceTokenKey(organizationId, namespace, oblienApiBaseUrl(env.OBLIEN_API_URL).toString()); const store = await cacheStore("oblien-internal-tokens", { maxSize: 10_000 }); const readFresh = async () => { const cached = await store.get(key); @@ -142,7 +142,7 @@ async function internalNamespaceToken(organizationId: string, workspaceId?: Clou const renewed = await readFresh(); if (renewed) return renewed; const credentials = await issueNamespaceToken(organizationId, workspaceId); - if (credentials.namespace !== namespace || credentials.providerApiUrl !== env.OBLIEN_API_URL) + if (credentials.namespace !== namespace || credentials.providerApiUrl !== oblienApiBaseUrl(env.OBLIEN_API_URL).toString()) throw new AppError("Cloud execution ownership changed", 409, "CLOUD_NAMESPACE_MISMATCH"); const ttl = Math.floor((Date.parse(credentials.expiresAt) - Date.now() - 60_000) / 1000); if (!credentials.token || !Number.isFinite(ttl) || ttl <= 0) diff --git a/packages/platform/src/engine/lib/public-endpoints.ts b/packages/platform/src/engine/lib/public-endpoints.ts index 91b900d5d..01f05dd69 100644 --- a/packages/platform/src/engine/lib/public-endpoints.ts +++ b/packages/platform/src/engine/lib/public-endpoints.ts @@ -982,7 +982,7 @@ export interface ProjectAccess { /** The project's ONE canonical public domain row, chosen over ALL rows * (project-level AND service-scoped): a verified primary, else the first * verified row, else none. The single primary-selection rule the detail Access - * URL, the list card's primaryDomain, and the favicon refresh all share, so + * URL and the list card's primaryDomain share, so * those surfaces can never disagree on which domain is "the" one. */ export function pickCanonicalDomainRow & { hostname?: string }>( rows: T[] | null | undefined, diff --git a/packages/platform/src/engine/modules/actions/billing-namespace.ts b/packages/platform/src/engine/modules/actions/billing-namespace.ts index afb9e861c..c7cf99aae 100644 --- a/packages/platform/src/engine/modules/actions/billing-namespace.ts +++ b/packages/platform/src/engine/modules/actions/billing-namespace.ts @@ -30,7 +30,7 @@ export async function ensureActionsBillingNamespace(organizationId: string): Pro // Preparing checkout must not permit compute before paid runner setup. // These initial caps do not replace an existing namespace's limits. resource_limits: { - max_workspaces: 0, + max_vms: 0, max_vcpus: 0, max_ram_mb: 0, max_disk_gb: 0, @@ -79,7 +79,7 @@ export async function ensureFundedActionRunners(organizationId: string): Promise disk: Math.max(...runners.map((r) => r.diskGb)), }; const limits = { - max_workspaces: maxParallel, + max_vms: maxParallel, max_vcpus: maximum.cpu, max_ram_mb: maximum.memory, max_disk_gb: maximum.disk, diff --git a/packages/platform/src/engine/modules/actions/cloud-runner.test.ts b/packages/platform/src/engine/modules/actions/cloud-runner.test.ts index 1390c3d64..7679d3099 100644 --- a/packages/platform/src/engine/modules/actions/cloud-runner.test.ts +++ b/packages/platform/src/engine/modules/actions/cloud-runner.test.ts @@ -30,7 +30,7 @@ vi.mock("@repo/adapters", async (original) => ({ prepare = state.prepare; }, Oblien: class { - workspaces = { + vms = { create: state.create, get: state.get, delete: state.remove, diff --git a/packages/platform/src/engine/modules/actions/cloud-runner.ts b/packages/platform/src/engine/modules/actions/cloud-runner.ts index ee84aad79..6079ce3da 100644 --- a/packages/platform/src/engine/modules/actions/cloud-runner.ts +++ b/packages/platform/src/engine/modules/actions/cloud-runner.ts @@ -268,8 +268,8 @@ export async function openCloudActionWorker( let workspace; try { workspace = job.providerWorkspaceId - ? await client.workspaces.get(job.providerWorkspaceId) - : await client.workspaces.create(workspaceInput(job, runner)); + ? await client.vms.get(job.providerWorkspaceId) + : await client.vms.create(workspaceInput(job, runner)); } catch (error) { if (job.providerWorkspaceId && isMissing(error)) throw new AppError( @@ -318,7 +318,7 @@ export async function openCloudActionWorker( } if (workspace.ready === false || !["active", "running"].includes(status)) return null; const executor = new CloudWorkspaceExecutor( - options => client.workspace(workspace.id).runtime(options), + options => client.vm(workspace.id).runtime(options), workspace.id, ); try { @@ -333,7 +333,7 @@ export async function openCloudActionWorker( // The authenticated Runtime API gateway needs host ingress. Enabling the // API adds its port but does not enable that firewall path. Restrict this // disposable VM to the API port; do not expose SSH or workflow services. - await client.workspaces.network.update(workspace.id, { + await client.vms.network.update(workspace.id, { public_access: true, ingress_ports: [9990], }); @@ -386,8 +386,8 @@ export async function removeCloudActionWorker( // An uncertain create is resolved with its ORIGINAL key and config. No new // key, image, resources or paid purchase is introduced by cleanup retries. const workspace = job.providerWorkspaceId - ? await client.workspaces.get(job.providerWorkspaceId) - : await client.workspaces.create(workspaceInput(job, runner)); + ? await client.vms.get(job.providerWorkspaceId) + : await client.vms.create(workspaceInput(job, runner)); assertWorkspace(workspace, job, runner); if (!job.providerWorkspaceId) { const saved = await update({ @@ -396,9 +396,9 @@ export async function removeCloudActionWorker( if (!saved) throw new Error("Actions lease changed before worker cleanup"); job = saved; } - await client.workspaces.delete(workspace.id); + await client.vms.delete(workspace.id); try { - await client.workspaces.get(workspace.id); + await client.vms.get(workspace.id); // Deletion is asynchronous. Keep the scheduler slot and poll on the // next tick without replacing the workflow result with a cleanup error. return false; diff --git a/packages/platform/src/engine/modules/actions/triggers.test.ts b/packages/platform/src/engine/modules/actions/triggers.test.ts index c00d616ec..a4d9b95d8 100644 --- a/packages/platform/src/engine/modules/actions/triggers.test.ts +++ b/packages/platform/src/engine/modules/actions/triggers.test.ts @@ -33,6 +33,7 @@ vi.mock("./action.service", () => ({ rerunActionWorkflow: h.rerun, })); import { dispatchActionWebhook, enqueueActionWebhook } from "./triggers"; +import { GitHubApiError } from "../github/github.error"; const base = "a".repeat(40), head = "b".repeat(40), @@ -80,6 +81,7 @@ beforeEach(() => { owner: "acme", repo: "app", path: ".github/workflows/ci.yml", + source: null, authority: {}, allowForks: true, }, @@ -96,6 +98,66 @@ beforeEach(() => { const dispatch = (value = event()) => dispatchActionWebhook("pull_request", value, "delivery", target); +it.each(["push", "pull_request"])( + "ignores a workflow absent at the %s revision", + async (eventName) => { + h.file.mockRejectedValueOnce(new GitHubApiError(404, "Not Found", new Headers())); + const revision = eventName === "push" ? head : base; + h.fetch.mockImplementationOnce(async ({ url }) => { + if (url === `https://api.github.com/repos/acme/app/commits/${revision}`) + return { sha: revision }; + throw new Error(`Unexpected GitHub request: ${url}`); + }); + await dispatchActionWebhook( + eventName, + eventName === "push" ? { ...event(), ref: "refs/heads/other", after: head } : event(), + "delivery", + target, + ); + expect(h.trigger).not.toHaveBeenCalled(); + expect(h.error).toHaveBeenCalledExactlyOnceWith("org", "workflow", null); + }, +); + +it.each([403, 429, 500])("retains workflow source failures from GitHub (%s)", async (status) => { + const error = new GitHubApiError(status, "Unavailable", new Headers()); + h.file.mockRejectedValueOnce(error); + await expect(dispatch()).rejects.toThrow(error); + expect(h.trigger).not.toHaveBeenCalled(); + expect(h.error).toHaveBeenCalledWith("org", "workflow", error.message); +}); + +it("retains a missing revision or inaccessible repository as a workflow error", async () => { + const error = new GitHubApiError(404, "Not Found", new Headers()); + h.file.mockRejectedValueOnce(error); + h.fetch.mockRejectedValueOnce(error); + await expect(dispatch()).rejects.toThrow(error); + expect(h.trigger).not.toHaveBeenCalled(); + expect(h.error).toHaveBeenCalledWith("org", "workflow", error.message); +}); + +it("uses the pushed workflow's branch rules rather than the saved definition", async () => { + const workflows = await h.workflows(); + workflows[0].definition = { triggers: { push: { branches: ["main"] } } }; + h.file.mockResolvedValueOnce({ + content: source.replace( + "pull_request:\n types: [opened, reopened, synchronize, closed]", + "push:\n branches: [deploy/**]", + ), + }); + await dispatchActionWebhook( + "push", + { ...event(), ref: "refs/heads/deploy/topic", after: head }, + "delivery", + target, + ); + expect(h.trigger).toHaveBeenCalledOnce(); + expect(h.trigger.mock.calls[0]![2]).toMatchObject({ + revision: head, + ref: "refs/heads/deploy/topic", + }); +}); + it("routes GitHub-owned events to the exact workflow without storing webhook payloads", async () => { h.workflows.mockResolvedValueOnce([ { ...target, id: "first", controller: "github", githubWorkflowId: "123" }, diff --git a/packages/platform/src/engine/modules/actions/triggers.ts b/packages/platform/src/engine/modules/actions/triggers.ts index 119ad9b37..43d4c4672 100644 --- a/packages/platform/src/engine/modules/actions/triggers.ts +++ b/packages/platform/src/engine/modules/actions/triggers.ts @@ -8,6 +8,7 @@ import { nativeJobsEnabled } from "../../native/execution-policy"; import { resolveExecutionAuthority } from "../../lib/execution-authority"; import { githubFetch } from "../github/github.auth"; import { getFileContent } from "../github/github.service"; +import { GitHubApiError } from "../github/github.error"; import { triggerActionWorkflow, rerunActionWorkflow } from "./action.service"; import { parseActionWorkflow, record } from "./workflow"; import { matchesActionFilters } from "./trigger-pattern"; @@ -150,13 +151,27 @@ export async function dispatchActionWebhook( untrusted = pullRequest.head.repo.id !== pullRequest.repository.id; if (untrusted && !workflow.allowForks) continue; } - const source = - workflow.source ?? - ( - await getFileContent(ctx, owner, repo, workflow.path, { - branch: workflowRevision ?? revision, - }) - ).content; + let source = workflow.source; + if (source == null) { + try { + source = ( + await getFileContent(ctx, owner, repo, workflow.path, { + branch: workflowRevision ?? revision, + }) + ).content; + } catch (error) { + if (!(error instanceof GitHubApiError && error.status === 404)) throw error; + // Only an absent file is a no-op. Repository and revision access must still work. + await githubFetch({ + ctx, + owner, + repo, + url: `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/commits/${workflowRevision ?? revision}`, + }); + await repos.actions.workflowError(workflow.organizationId, workflow.id, null); + continue; + } + } const plan = await parseActionWorkflow(source, workflow.path); if ( !workflow.source && diff --git a/packages/platform/src/engine/modules/apps/app-install.service.ts b/packages/platform/src/engine/modules/apps/app-install.service.ts index d4b3d97e8..74f0d6f26 100644 --- a/packages/platform/src/engine/modules/apps/app-install.service.ts +++ b/packages/platform/src/engine/modules/apps/app-install.service.ts @@ -394,7 +394,53 @@ export async function installApp( return { kind: "flow", flowHref: template.flowHref ?? "/" }; } - assertInstallRoutes(template, input.routes); + // Resolve config values. Secrets sharing a `generateGroup` get ONE generated + // value (e.g. a DB password that must match across two services). + const groupSecret = new Map(); + // Pre-generate every grouped secret so generate:"jwt" fields can sign with + // them regardless of field order (the JWT secret must exist before the keys). + for (const field of template.configFields ?? []) { + if (field.generate === "secret" && field.generateGroup && !groupSecret.has(field.generateGroup)) { + groupSecret.set(field.generateGroup, generateSecret()); + } + } + const valueFor = (field: AppConfigField): string => { + if (field.generate === "secret") { + if (field.generateGroup) { + const existing = groupSecret.get(field.generateGroup); + if (existing) return existing; + const secret = generateSecret(); + groupSecret.set(field.generateGroup, secret); + return secret; + } + return generateSecret(); + } + if (field.generate === "jwt") { + const secret = field.jwtSecretGroup ? groupSecret.get(field.jwtSecretGroup) : undefined; + if (!secret || !field.jwtRole) return ""; + return signHs256Jwt(secret, field.jwtRole); + } + return input.config?.[field.key] ?? field.default ?? ""; + }; + + // Resolve each field's final value EXACTLY once (a non-grouped secret would + // otherwise differ between the env write and the file substitution below). + const resolved = new Map(); + for (const field of template.configFields ?? []) resolved.set(field.key, valueFor(field)); + + // Inline generated config values (`{{config:KEY}}`) now — in both service env + // and mounted files — while leaving `{{publicUrl:…}}` for deploy-time. This + // lets a service env embed a generated secret it can't otherwise interpolate + // (e.g. a full `postgres://user:PASSWORD@db/…` connection URL). + const inlineConfig = (s: string): string => + s.replace(CONFIG_TOKEN_RE, (_m, k) => resolved.get(k) ?? ""); + + // Resolve the same specs for route validation, fresh rows and draft repair. + // Never mutate the catalog template shared by other installations. + const serviceSpecs = (template.services ?? []).map(service => ({ + ...service, ports: service.ports?.map(inlineConfig), + })); + assertInstallRoutes({ services: serviceSpecs }, input.routes); let workspaceId: string | undefined; // Linked Cloud servers retain their workspace on self-hosted control planes @@ -489,47 +535,6 @@ export async function installApp( project = created!; } - // Resolve config values. Secrets sharing a `generateGroup` get ONE generated - // value (e.g. a DB password that must match across two services). - const groupSecret = new Map(); - // Pre-generate every grouped secret so generate:"jwt" fields can sign with - // them regardless of field order (the JWT secret must exist before the keys). - for (const field of template.configFields ?? []) { - if (field.generate === "secret" && field.generateGroup && !groupSecret.has(field.generateGroup)) { - groupSecret.set(field.generateGroup, generateSecret()); - } - } - const valueFor = (field: AppConfigField): string => { - if (field.generate === "secret") { - if (field.generateGroup) { - const existing = groupSecret.get(field.generateGroup); - if (existing) return existing; - const secret = generateSecret(); - groupSecret.set(field.generateGroup, secret); - return secret; - } - return generateSecret(); - } - if (field.generate === "jwt") { - const secret = field.jwtSecretGroup ? groupSecret.get(field.jwtSecretGroup) : undefined; - if (!secret || !field.jwtRole) return ""; - return signHs256Jwt(secret, field.jwtRole); - } - return input.config?.[field.key] ?? field.default ?? ""; - }; - - // Resolve each field's final value EXACTLY once (a non-grouped secret would - // otherwise differ between the env write and the file substitution below). - const resolved = new Map(); - for (const field of template.configFields ?? []) resolved.set(field.key, valueFor(field)); - - // Inline generated config values (`{{config:KEY}}`) now — in both service env - // and mounted files — while leaving `{{publicUrl:…}}` for deploy-time. This - // lets a service env embed a generated secret it can't otherwise interpolate - // (e.g. a full `postgres://user:PASSWORD@db/…` connection URL). - const inlineConfig = (s: string): string => - s.replace(CONFIG_TOKEN_RE, (_m, k) => resolved.get(k) ?? ""); - // Resolve template files per service. const filesByService = new Map(); for (const f of template.files ?? []) { @@ -562,7 +567,7 @@ export async function installApp( const varsByService = new Map(); // The operator's routing, resolved once for the whole stack. - const routingPlan = planInstallRouting(template, project.slug ?? project.name, input.routes); + const routingPlan = planInstallRouting({ services: serviceSpecs }, project.slug ?? project.name, input.routes); // Rows the adopted draft already has. A fresh project has none, so the loop // below reduces to a plain seed. @@ -578,7 +583,7 @@ export async function installApp( // Seed the compose service rows — or, on an adopted draft, re-apply the chosen // routing to the rows that already exist and seed only what's missing (a first // install that died part-way left the project with fewer rows than the template). - for (const svc of template.services ?? []) { + for (const svc of serviceSpecs) { const routing = routingPlan.get(svc.name) ?? { exposed: false, publicEndpoints: [] }; const existingRow = rowByName.get(svc.name); @@ -729,9 +734,10 @@ function inlinedConfigKeys(template: AppTemplate): ReadonlySet { if (!text) return; for (const [, key] of text.matchAll(CONFIG_TOKEN_RE)) keys.add(key); }; - // The four places `inlineConfig` is applied, and only those. + // Every surface that copies a resolved config value at installation. for (const svc of template.services ?? []) { for (const value of Object.values(svc.environment ?? {})) scan(value); + for (const port of svc.ports ?? []) scan(port); scan(svc.build?.dockerfile); for (const file of svc.build?.files ?? []) scan(file.content); } diff --git a/packages/platform/src/engine/modules/assistant/remote-target.ts b/packages/platform/src/engine/modules/assistant/remote-target.ts index b65fd7d51..180f59a30 100644 --- a/packages/platform/src/engine/modules/assistant/remote-target.ts +++ b/packages/platform/src/engine/modules/assistant/remote-target.ts @@ -187,7 +187,7 @@ export async function createRemoteAssistantClient( connection.organizationId, server!.workspaceId, ); - let runtime = await owned.client.workspace(owned.binding.workspaceId!).runtime(); + let runtime = await owned.client.vm(owned.binding.workspaceId!).runtime(); const baseUrl = "http://openship-assistant.invalid"; return { id: `assistant:${server!.id}`, @@ -210,7 +210,7 @@ export async function createRemoteAssistantClient( let result = await send(); if (result.status === 401) { runtime = await owned.client - .workspace(owned.binding.workspaceId!) + .vm(owned.binding.workspaceId!) .runtime({ force: true }); result = await send(); } diff --git a/packages/platform/src/engine/modules/billing/billing-credit-alert.ts b/packages/platform/src/engine/modules/billing/billing-credit-alert.ts index a3211e1c9..6140a439c 100644 --- a/packages/platform/src/engine/modules/billing/billing-credit-alert.ts +++ b/packages/platform/src/engine/modules/billing/billing-credit-alert.ts @@ -14,7 +14,8 @@ export function creditAlertNotification(input: { const { eventType, eventId, data, entitlement, organizationId } = input; // Late credit events cannot turn a paid capacity contract into a credit alert. if (entitlement.tierId === "capacity") return null; - if (data.service !== undefined && data.service !== "workspace_vm") return null; + // Signed deliveries queued before the VM API cutover can still name the old service. + if (data.service !== undefined && data.service !== "vm_compute" && data.service !== "workspace_vm") return null; const alert = entitlement.quota.alert; if (!alert || !["low", "grace", "depleted"].includes(alert.state)) return null; const created = diff --git a/packages/platform/src/engine/modules/billing/billing-resources.service.ts b/packages/platform/src/engine/modules/billing/billing-resources.service.ts index 987fd3b5f..1d7657156 100644 --- a/packages/platform/src/engine/modules/billing/billing-resources.service.ts +++ b/packages/platform/src/engine/modules/billing/billing-resources.service.ts @@ -1,7 +1,7 @@ /** Display telemetry is independent of checkout, entitlements and provisioning. */ import { observedAllSettled, diagnostics as errorDiagnostics } from "@repo/core/diagnostics"; import { z } from "zod"; -import { Oblien } from "@repo/adapters"; +import { Oblien, oblienApiBaseUrl, oblienApiUrl } from "@repo/adapters"; import { type PlanTierId } from "@repo/core"; import type { BillingResources } from "@repo/contracts"; import { env } from "../../config/env"; @@ -28,12 +28,12 @@ function timedClient(options: ConstructorParameters[0], signal: A const client = new Oblien(options); // The SDK owns endpoint formatting; its default transport has no redirect // control. Never forward owner credentials or a scoped token to another host. - const base = (options.baseUrl ?? "https://api.oblien.com").replace(/\/+$/, ""); + const base = oblienApiBaseUrl(options.baseUrl); const headers = { "Content-Type": "application/json", ...("token" in options ? { Authorization: `Bearer ${options.token}` } : { "X-Client-ID": options.clientId, "X-Client-Secret": options.clientSecret }) }; client._http.request = async ({ path, method, query, body }: Parameters[0]): Promise => { - const url = new URL(`${base}${path}`); + const url = oblienApiUrl(base, path); for (const [key, value] of Object.entries(query ?? {})) if (value !== undefined) url.searchParams.set(key, String(value)); const response = await fetch(url.toString(), { method, headers, signal, redirect: "error", ...(body === undefined ? {} : { body: JSON.stringify(body) }), diff --git a/packages/platform/src/engine/modules/billing/management.service.ts b/packages/platform/src/engine/modules/billing/management.service.ts index dda956942..3a1b7ca0b 100644 --- a/packages/platform/src/engine/modules/billing/management.service.ts +++ b/packages/platform/src/engine/modules/billing/management.service.ts @@ -243,7 +243,7 @@ export async function purchaseManagement(ctx: ExecutionContext, input: Managemen name: "Openship Manage", slug: owner.namespace, resource_limits: { - max_workspaces: 0, + max_vms: 0, max_vcpus: 0, max_ram_mb: 0, max_disk_gb: 0, diff --git a/packages/platform/src/engine/modules/billing/oblien-webhook-crypto.ts b/packages/platform/src/engine/modules/billing/oblien-webhook-crypto.ts index a22939167..0a2c01839 100644 --- a/packages/platform/src/engine/modules/billing/oblien-webhook-crypto.ts +++ b/packages/platform/src/engine/modules/billing/oblien-webhook-crypto.ts @@ -29,7 +29,7 @@ export interface OblienEventEnvelope { namespace?: string; data?: { namespace?: string; - workspace_id?: string; + vm_id?: string; period_end?: string; [key: string]: unknown; }; diff --git a/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts b/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts index 9ee03e86a..e14a9978f 100644 --- a/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts +++ b/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts @@ -39,8 +39,8 @@ interface OblienUsageBucket { interface OblienWebhookData { namespace?: string; - workspace_id?: string; - workspace_name?: string; + vm_id?: string; + vm_name?: string; service?: string; /** credits.usage */ balance?: number; diff --git a/packages/platform/src/engine/modules/cloud-workspaces/cloud-workspace.service.ts b/packages/platform/src/engine/modules/cloud-workspaces/cloud-workspace.service.ts index c9ad35403..97265587e 100644 --- a/packages/platform/src/engine/modules/cloud-workspaces/cloud-workspace.service.ts +++ b/packages/platform/src/engine/modules/cloud-workspaces/cloud-workspace.service.ts @@ -704,7 +704,7 @@ export async function processWorkspaceOperation(id: string): Promise { const namespace = row.namespace; if (!namespace || namespace !== binding.namespace) throw new Error("Cloud workspace namespace changed"); - const ws = client.workspace(binding.workspaceId); + const ws = client.vm(binding.workspaceId); try { const current = await ws.get(); if (current.namespace !== namespace) diff --git a/packages/platform/src/engine/modules/deployments/compose-configuration-error.ts b/packages/platform/src/engine/modules/deployments/compose-configuration-error.ts index 89210d3ef..4758070f5 100644 --- a/packages/platform/src/engine/modules/deployments/compose-configuration-error.ts +++ b/packages/platform/src/engine/modules/deployments/compose-configuration-error.ts @@ -6,9 +6,12 @@ * service shape, but must never do that for this error: deploying stale Compose * configuration after the file changed is less safe than refusing the deploy. */ -export class ComposeConfigurationError extends Error { +import { AppError } from "@repo/core"; + +export class ComposeConfigurationError extends AppError { constructor(message: string, options?: ErrorOptions) { - super(message, options); + super(message, 400, "COMPOSE_CONFIGURATION_INVALID"); + if (options?.cause !== undefined) this.cause = options.cause; this.name = "ComposeConfigurationError"; } } diff --git a/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts b/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts index 061720d5a..f276201b8 100644 --- a/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts +++ b/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts @@ -38,8 +38,6 @@ import { sanitizeStorableStrings, sliceWithoutSplittingPair, } from "./build-log-sanitize"; -import { detectAndStoreFavicon } from "../../lib/favicon-detector"; -import { trackBackgroundWork } from "../../lib/background-work"; import { onWebmailDeployed } from "../mail/webmail/webmail-install.service"; import { computeCleanupKeepSet } from "../projects/cleanup-keep-set"; import { deploymentResourceFailure, type DeploymentFailureMeta } from "./resource-failure"; @@ -1065,11 +1063,6 @@ export async function onSuccess( }, ); - // Async favicon detection - don't block the deploy response - if (result.url) { - void trackBackgroundWork(detectAndStoreFavicon(project.id, result.url)); - } - // Webmail on Openship Cloud, routed on the mail server's own `mail.`: // the mail VPS proxies that hostname to the cloud URL, which can only be // registered once the URL exists. Await it so the deployment execution lease diff --git a/packages/platform/src/engine/modules/deployments/deployment.service.ts b/packages/platform/src/engine/modules/deployments/deployment.service.ts index 2efe6c992..4b5cbb34b 100644 --- a/packages/platform/src/engine/modules/deployments/deployment.service.ts +++ b/packages/platform/src/engine/modules/deployments/deployment.service.ts @@ -89,9 +89,7 @@ export async function listDeployments( ...d, isActive: d.id === activeId, projectName: project.name, - // Project favicon → the dashboard uses it as the row's logo instead - // of the framework/Docker glyph. - favicon: project.favicon ?? null, + iconUrl: project.iconUrl ?? null, })), }; } @@ -110,8 +108,7 @@ export async function listDeployments( ...d, projectName: proj?.name ?? "Unknown", isActive: proj?.activeDeploymentId === d.id, - // Project favicon → dashboard row logo (see listByProject above). - favicon: proj?.favicon ?? null, + iconUrl: proj?.iconUrl ?? null, }; }); diff --git a/packages/platform/src/engine/modules/deployments/local-source.ts b/packages/platform/src/engine/modules/deployments/local-source.ts index bd03064d7..a7fbbf3bc 100644 --- a/packages/platform/src/engine/modules/deployments/local-source.ts +++ b/packages/platform/src/engine/modules/deployments/local-source.ts @@ -95,6 +95,7 @@ export async function resolveSourceEnvFromLocal( export async function resolveFromLocal( dirPath: string, opts: ResolveOptions = {}, + fallbackName = basename(dirPath), ): Promise { const st = await stat(dirPath); if (!st.isDirectory()) { @@ -103,7 +104,7 @@ export async function resolveFromLocal( const reader = createLocalReader(dirPath); const rootPackageJson = await reader.readJson("package.json"); - const name = (rootPackageJson?.name as string) ?? basename(dirPath); + const name = (rootPackageJson?.name as string) || fallbackName; return resolveFromReader( reader, diff --git a/packages/platform/src/engine/modules/domains/domain.service.ts b/packages/platform/src/engine/modules/domains/domain.service.ts index 4e3904afe..91af17542 100644 --- a/packages/platform/src/engine/modules/domains/domain.service.ts +++ b/packages/platform/src/engine/modules/domains/domain.service.ts @@ -108,7 +108,7 @@ export async function getDomain(ctx: RequestContext, domainId: string) { /** * Make a domain the project's primary. Primary is the project's canonical - * hostname — what favicon detection, analytics, and the dashboard's project + * hostname — what analytics and the dashboard's project * link resolve to (getPrimaryByProject). setPrimary unsets any prior primary * for the project and marks this one, so exactly one row stays primary. * Survives redeploys: per-service route registration preserves an existing diff --git a/packages/platform/src/engine/modules/domains/routing-apply.service.ts b/packages/platform/src/engine/modules/domains/routing-apply.service.ts index 599377080..25ae28ddd 100644 --- a/packages/platform/src/engine/modules/domains/routing-apply.service.ts +++ b/packages/platform/src/engine/modules/domains/routing-apply.service.ts @@ -538,7 +538,7 @@ export async function applyCloudRouting(opts: { !input.routes.some( (rule) => rule.action.kind === "proxy" && - rule.action.workspace === backend.workspace && + rule.action.vm === backend.vm && rule.action.port === backend.port, ) ) { diff --git a/packages/platform/src/engine/modules/migration/migration.orchestrator.ts b/packages/platform/src/engine/modules/migration/migration.orchestrator.ts index 15abd2c4e..0ff935b26 100644 --- a/packages/platform/src/engine/modules/migration/migration.orchestrator.ts +++ b/packages/platform/src/engine/modules/migration/migration.orchestrator.ts @@ -691,7 +691,7 @@ class MigrationOrchestratorImpl { id: `dmr_${crypto.randomUUID()}`, organizationId: ctx.organizationId, targetServerId: target.id, - projectName: plan.project.name, + projectName: plan.projectName, serviceNames: plan.services.map((s) => s.create.name), status: "queued", mode: "provider_import", diff --git a/packages/platform/src/engine/modules/migration/platform-import-plan.ts b/packages/platform/src/engine/modules/migration/platform-import-plan.ts index 1f4d3cf13..302c860e0 100644 --- a/packages/platform/src/engine/modules/migration/platform-import-plan.ts +++ b/packages/platform/src/engine/modules/migration/platform-import-plan.ts @@ -1,5 +1,11 @@ import { createHash, randomUUID, randomBytes } from "node:crypto"; -import { AppError, normalizeAliasStrict, slugify, normalizeProjectRootDirectory, validateImageReference } from "@repo/core"; +import { + AppError, + normalizeAliasStrict, + slugify, + normalizeProjectRootDirectory, + validateImageReference, +} from "@repo/core"; import type { PlatformDiscovery, PlatformMigrationSource, @@ -24,7 +30,7 @@ import { } from "./providers/types"; import { discoverExternalDatabases } from "./providers/external-databases"; import { resolveRailwayBindings } from "./providers/railway-wiring"; -import { platformImportProject } from "./platform-import-project"; +import { platformImportProjects, type PlannedImportProject } from "./platform-import-project"; export interface ImportBinding { sourceId: string; @@ -46,7 +52,8 @@ export interface PrivateImportPlan { inventory: ProviderInventory; fingerprint: string; targetServerId: string; - project: TEnsureProjectBody; + projectName: string; + projects: PlannedImportProject[]; services: PlannedImportService[]; requiresWritePause: boolean; requiresWorkerPause: boolean; @@ -528,7 +535,7 @@ export async function reviewPlatform( const projectName = (input.projectName ?? inventory.projectName).trim(); if (!slugify(projectName)) throw new AppError("Choose a name for the imported project", 400, "IMPORT_NAME_INVALID"); - const project = platformImportProject(projectName, input.targetServerId, services); + const projects = platformImportProjects(projectName, input.targetServerId, services); const plan: PrivateImportPlan = { id: randomUUID(), organizationId: ctx.organizationId, @@ -536,7 +543,8 @@ export async function reviewPlatform( inventory: draft.inventory, fingerprint: inventoryFingerprint(draft.inventory), targetServerId: input.targetServerId, - project, + projectName, + projects, services, ...(inventory.provider === "railway" ? { sourceControl: "railway-project" as const } : {}), requiresWritePause: services.some( @@ -559,6 +567,10 @@ export async function reviewPlatform( planId: plan.id, ...publicInventory({ ...inventory, services: services.map((s) => s.source) }), projectName, + projects: projects.map(({ create, sourceIds }) => ({ + name: create.name, + serviceIds: sourceIds, + })), targetServerId: plan.targetServerId, requiresWritePause: plan.requiresWritePause, requiresWorkerPause: plan.requiresWorkerPause, @@ -572,8 +584,12 @@ export async function loadReviewedImport( id: string, ): Promise { const plan = await get(ctx, "plan", id); - if (!plan.project) - throw new AppError("Review this import again before starting it.", 409, "IMPORT_REVIEW_EXPIRED"); + if (!plan.projects?.length) + throw new AppError( + "Review this import again before starting it.", + 409, + "IMPORT_REVIEW_EXPIRED", + ); if (!plan.ready) throw new AppError("Resolve the import review before starting", 409, "IMPORT_NOT_READY"); const access = await getProviderAccess(ctx.organizationId, plan.inventory.source.connectionId); diff --git a/packages/platform/src/engine/modules/migration/platform-import-project.ts b/packages/platform/src/engine/modules/migration/platform-import-project.ts index 61e7b6e53..3415e69fe 100644 --- a/packages/platform/src/engine/modules/migration/platform-import-project.ts +++ b/packages/platform/src/engine/modules/migration/platform-import-project.ts @@ -3,15 +3,83 @@ import type { TCreateServiceBody, TEnsureProjectBody, } from "@repo/contracts"; +import { slugify } from "@repo/core"; import type { PlannedImportService } from "./platform-import-plan"; +export interface PlannedImportProject { + create: TEnsureProjectBody; + sourceIds: string[]; +} + +/** A native project has one Git checkout. Keep compatible environments together; + * otherwise give each service its own project and use ordinary private links. */ +export function platformImportProjects( + name: string, + serverId: string, + services: PlannedImportService[], +): PlannedImportProject[] { + const imports = services.filter((service) => service.data !== "external"); + const sources = new Set( + imports + .filter((service) => service.create.gitRepo) + .map((service) => + JSON.stringify([ + service.create.gitProvider, + service.create.gitOwner, + service.create.gitRepo, + service.create.gitBranch, + service.source.commit, + ]), + ), + ); + const groups = sources.size > 1 ? imports.map((service) => [service]) : [imports]; + if (groups.length > 1) { + for (const service of imports) { + const keys = new Set(service.bindings.map((binding) => binding.envKey)); + for (const key of keys) { + const bindings = service.bindings.filter((binding) => binding.envKey === key); + if (new Set(bindings.map((binding) => binding.sourceId)).size > 1) { + service.source.blockers.push( + `Review ${key}: use a separate connection variable for each private service when importing into separate projects.`, + ); + } + for (const binding of bindings) { + if ( + Object.hasOwn(service.environment, key) && + binding.valueTemplate === undefined && + bindings.length === 1 + ) + service.source.blockers.push( + `Review ${key}: its private host cannot be safely converted into a project connection. Provide a destination value explicitly.`, + ); + const dependency = imports.find((candidate) => candidate.source.id === binding.sourceId); + if (dependency && !(dependency.source.port || dependency.create.port)) + service.source.blockers.push( + `Review ${key}: ${dependency.create.name} needs a private listener port for its project connection.`, + ); + } + } + } + } + return groups.map((group) => ({ + create: platformImportProject( + groups.length === 1 + ? name + : `${slugify(name).slice(0, 100 - group[0].create.name.length - 1)}-${group[0].create.name}`, + serverId, + group, + ), + sourceIds: group.map((service) => service.source.id), + })); +} + function dependencyNames(service: PlannedImportService, services: PlannedImportService[]) { return [ ...new Set( - service.bindings.map( - (binding) => - services.find((dependency) => dependency.source.id === binding.sourceId)!.create.name, - ), + service.bindings.flatMap((binding) => { + const dependency = services.find((candidate) => candidate.source.id === binding.sourceId); + return dependency ? [dependency.create.name] : []; + }), ), ]; } @@ -37,9 +105,8 @@ export function platformImportRoutes(services: PlannedImportService[]): Migratio ); } -/** Translate reviewed provider recipes into the same project and service inputs - * used by native imports. A provider project never becomes several projects. */ -export function platformImportProject( +/** Translate one compatible group into ordinary project and service inputs. */ +function platformImportProject( name: string, serverId: string, services: PlannedImportService[], @@ -53,15 +120,6 @@ export function platformImportProject( service.source.blockers.push( "This repository declares project-wide release commands. Review a service-compatible release recipe before importing; grouped imports cannot silently skip those commands.", ); - if ( - service.create.gitOwner !== first.create.gitOwner || - service.create.gitRepo !== first.create.gitRepo || - service.source.commit !== first.source.commit - ) { - service.source.blockers.push( - "These services use different repositories or deployed revisions. A native OpenShip project has one Git source; align the source services before importing them together.", - ); - } } return { name, diff --git a/packages/platform/src/engine/modules/migration/platform-import-worker.ts b/packages/platform/src/engine/modules/migration/platform-import-worker.ts index a6017cf9a..b38ccaaf4 100644 --- a/packages/platform/src/engine/modules/migration/platform-import-worker.ts +++ b/packages/platform/src/engine/modules/migration/platform-import-worker.ts @@ -1,5 +1,5 @@ import { AppError, ConflictError, ValidationError } from "@repo/core"; -import { repos } from "@repo/db"; +import { repos, type Service } from "@repo/db"; import type { ExecutionContext } from "../../../context"; import type { PrivateImportPlan, PlannedImportService } from "./platform-import-plan"; import { ensureProject } from "../projects/project-crud.service"; @@ -20,6 +20,7 @@ import { import { verifyPlatformDeployment } from "./platform-import-health"; import { withProjectRuntimeLock } from "../../lib/project-runtime-lock"; import { prepareMigrationTarget } from "./migration-runtime"; +import { createConnection } from "../projects/project-connection.service"; export interface ImportLifecycle { signal: AbortSignal; @@ -76,13 +77,29 @@ export async function executePlatformImport( resourceId: plan.targetServerId, action: "write", }); - if (!plan.project) + if (!plan.projects?.length) throw new AppError( "Review this import again before starting it.", 409, "IMPORT_REVIEW_EXPIRED", ); const services = orderedImports(plan.services); + const destinations = plan.projects.map((project) => ({ + ...project, + services: services.filter((service) => project.sourceIds.includes(service.source.id)), + projectId: "", + })); + const destinationFor = new Map( + destinations.flatMap((destination) => + destination.sourceIds.map((id) => [id, destination] as const), + ), + ); + if (services.some((service) => !destinationFor.has(service.source.id))) + throw new AppError( + "Review this import again before starting it.", + 409, + "IMPORT_REVIEW_EXPIRED", + ); lifecycle.log("Checking the complete project's storage and destination configuration"); await preflightPlatformData(services, lifecycle.signal); await prepareMigrationTarget(ctx.organizationId, plan.targetServerId, runId, { @@ -91,44 +108,61 @@ export async function executePlatformImport( }); lifecycle.signal.throwIfAborted(); await lifecycle.phase("adopting"); - lifecycle.log(`Creating project ${plan.project.name}`); - const { project_id: projectId } = await ensureProject(plan.project, ctx.organizationId, ctx, { - mustCreate: true, - }); - for (const service of services) { - if ( - !(await repos.dockerMigrationRun.bindImportedProject( - runId, - ctx.organizationId, - service.source.id, - projectId, - )) - ) - throw new AppError( - "The import was cancelled while creating its project. Its saved configuration was retained.", - 409, - "IMPORT_ADMISSION_CLOSED", - ); - } - await repos.project.update(projectId, { autoDeploy: false, runtimeMode: "docker" }); - for (const service of services) { + const bySource = new Map(); + for (const destination of destinations) { lifecycle.signal.throwIfAborted(); - if (!service.create.services?.length) - await createService(ctx, projectId, platformImportSourceService(service, services)); - } - // Use the same pending-domain and ownership path as server/Docker migration. - // Validate every route before pausing Railway or copying data. Deployment will - // reconcile routing normally; neither this step nor import changes external DNS. - try { - await saveMigrationRoutes(ctx, projectId, platformImportRoutes(services), lifecycle.log); - } catch (error) { - if (error instanceof ValidationError || error instanceof ConflictError) - throw new AppError(error.message, error.statusCode, "IMPORT_DOMAIN_REVIEW_REQUIRED"); - throw error; - } - const rows = await repos.service.listByProject(projectId); - const bySource = new Map( - services.map((service) => { + lifecycle.log(`Creating project ${destination.create.name}`); + const { project_id: projectId } = await ensureProject( + destination.create, + ctx.organizationId, + ctx, + { + mustCreate: true, + }, + ); + destination.projectId = projectId; + for (const service of destination.services) { + if ( + !(await repos.dockerMigrationRun.bindImportedProject( + runId, + ctx.organizationId, + service.source.id, + projectId, + )) + ) + throw new AppError( + "The import was cancelled while creating its project. Its saved configuration was retained.", + 409, + "IMPORT_ADMISSION_CLOSED", + ); + } + await repos.project.update(projectId, { autoDeploy: false, runtimeMode: "docker" }); + for (const service of destination.services) { + lifecycle.signal.throwIfAborted(); + if (!service.create.services?.length) + await createService( + ctx, + projectId, + platformImportSourceService(service, destination.services), + ); + } + // Use the same pending-domain and ownership path as server/Docker migration. + // Validate every route before pausing Railway or copying data. Deployment will + // reconcile routing normally; neither this step nor import changes external DNS. + try { + await saveMigrationRoutes( + ctx, + projectId, + platformImportRoutes(destination.services), + lifecycle.log, + ); + } catch (error) { + if (error instanceof ValidationError || error instanceof ConflictError) + throw new AppError(error.message, error.statusCode, "IMPORT_DOMAIN_REVIEW_REQUIRED"); + throw error; + } + const rows = await repos.service.listByProject(projectId); + for (const service of destination.services) { const row = rows.find((row) => row.name === service.create.name); if (!row) throw new AppError( @@ -136,9 +170,9 @@ export async function executePlatformImport( 409, "IMPORT_TARGET_SERVICE_MISSING", ); - return [service.source.id, row] as const; - }), - ); + bySource.set(service.source.id, row); + } + } const checkpoint = async () => { const current = (await repos.dockerMigrationRun.findById(runId))?.recovery.providerImport; if (!current) @@ -152,7 +186,8 @@ export async function executePlatformImport( }, }); const saveEnvironment = async (sourceId: string, values: Record) => { - await mergeServiceEnvVars(ctx, projectId, bySource.get(sourceId)!.id, { + const target = bySource.get(sourceId)!; + await mergeServiceEnvVars(ctx, target.projectId, target.id, { environment: "production", deletes: [], upserts: Object.entries(values).map(([key, value]) => ({ @@ -163,16 +198,33 @@ export async function executePlatformImport( })), }); }; - for (const service of services) await saveEnvironment(service.source.id, service.environment); + const isCrossProject = (service: PlannedImportService, dependencyId: string) => + bySource.get(service.source.id)!.projectId !== bySource.get(dependencyId)?.projectId; + for (const service of services) { + // Native connections own project-level variables. A service-level copy would + // shadow the refreshed value on this deployment and subsequent redeploys. + const linkedKeys = new Set( + service.bindings + .filter((binding) => isCrossProject(service, binding.sourceId)) + .map((binding) => binding.envKey), + ); + await saveEnvironment( + service.source.id, + Object.fromEntries( + Object.entries(service.environment).filter(([key]) => !linkedKeys.has(key)), + ), + ); + } for (const service of services) { const values: Record = {}; for (const binding of service.bindings) { + if (isCrossProject(service, binding.sourceId)) continue; // Railway already resolved these against native service DNS during review. if (Object.hasOwn(service.environment, binding.envKey)) continue; const dependency = bySource.get(binding.sourceId); if (!dependency) throw new AppError("An import dependency is missing", 409, "IMPORT_DEPENDENCY_MISSING"); - const output = (await getAppConnectionView(ctx, projectId)).outputs.find( + const output = (await getAppConnectionView(ctx, dependency.projectId)).outputs.find( (output) => output.internal && output.sourceServiceId === dependency.id && output.value, ); if (!output) @@ -195,7 +247,7 @@ export async function executePlatformImport( await copyPlatformData({ runId, service, - projectId, + projectId: bySource.get(service.source.id)!.projectId, serviceId: bySource.get(service.source.id)!.id, deploymentId, signal: lifecycle.signal, @@ -205,11 +257,43 @@ export async function executePlatformImport( }; const deploy = async (selected: PlannedImportService[]) => { lifecycle.signal.throwIfAborted(); + const destination = destinationFor.get(selected[0].source.id)!; + const projectId = destination.projectId; + for (const service of selected) { + for (const binding of service.bindings) { + if (!isCrossProject(service, binding.sourceId)) continue; + lifecycle.signal.throwIfAborted(); + const dependency = bySource.get(binding.sourceId); + if (!dependency) + throw new AppError("An import dependency is missing", 409, "IMPORT_DEPENDENCY_MISSING"); + const output = (await getAppConnectionView(ctx, dependency.projectId)).outputs.find( + (output) => output.internal && output.sourceServiceId === dependency.id, + ); + if (!output) + throw new AppError( + "The imported dependency has no usable connection output", + 409, + "IMPORT_CONNECTION_NOT_READY", + ); + await createConnection( + ctx, + projectId, + { + sourceProjectId: dependency.projectId, + outputId: output.id, + envKey: binding.envKey, + mode: "internal", + valueTemplate: binding.valueTemplate, + }, + { defer: true }, + ); + } + } await lifecycle.phase("deploying"); lifecycle.log( - `Deploying ${plan.project.name}: ${selected.map((service) => service.create.name).join(", ")}`, + `Deploying ${destination.create.name}: ${selected.map((service) => service.create.name).join(", ")}`, ); - const source = services.find((service) => service.create.gitRepo)?.source; + const source = destination.services.find((service) => service.create.gitRepo)?.source; const result = await triggerDeployment(ctx, { projectId, serverId: plan.targetServerId, @@ -263,8 +347,19 @@ export async function executePlatformImport( } else await transfer(service); } } - const deploymentId = await deploy(services); - await verifyPlatformDeployment(projectId, deploymentId, lifecycle.signal); + // Multi-source plans have one service per project. The service order already + // guarantees each private dependency is deployed before its consumers connect. + const deployed = new Map(); + for (const service of services) { + const destination = destinationFor.get(service.source.id)!; + if (!deployed.has(destination.projectId)) + deployed.set(destination.projectId, await deploy(destination.services)); + } + await Promise.all( + [...deployed].map(([projectId, deploymentId]) => + verifyPlatformDeployment(projectId, deploymentId, lifecycle.signal), + ), + ); await repos.dockerMigrationRun.updateRecovery(runId, { providerImport: { ...(await checkpoint()), @@ -272,7 +367,7 @@ export async function executePlatformImport( }, }); lifecycle.log( - `${plan.project.name} imported with ${services.length} services; source data retained.`, + `${plan.projectName} imported with ${services.length} services in ${destinations.length} project(s); source data retained.`, ); } diff --git a/packages/platform/src/engine/modules/migration/providers/railway-wiring.ts b/packages/platform/src/engine/modules/migration/providers/railway-wiring.ts index 9aa69ae58..c880983a0 100644 --- a/packages/platform/src/engine/modules/migration/providers/railway-wiring.ts +++ b/packages/platform/src/engine/modules/migration/providers/railway-wiring.ts @@ -3,8 +3,8 @@ import type { ImportBinding, PlannedImportService } from "../platform-import-pla const privateHost = /\b[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.railway\.internal\b/gi; /** Keep Railway's resolved values, replacing provider DNS with the native service - * aliases inside the imported project. Dependencies describe deployment order; - * they do not create cross-project connections or publish database ports. */ + * aliases inside the imported project. Retain a host template for native private + * connections when the destination must span several projects. */ export function resolveRailwayBindings( service: PlannedImportService, selected: Map, @@ -26,10 +26,32 @@ export function resolveRailwayBindings( ); continue; } + const external = new Set( + dependencies + .filter(({ source }) => source !== service) + .map(({ source }) => source!.source.id), + ); + const template = + external.size === 1 && !value.includes("${host}") + ? value.replace(privateHost, (host) => { + const dependency = dependencies.find((candidate) => candidate.host === host)!; + return dependency.source === service ? service.create.internalAlias! : "${host}"; + }) + : undefined; let resolved = value; for (const { host, source } of dependencies) { resolved = resolved.replaceAll(host, source!.create.internalAlias!); - if (source !== service) bindings.push({ sourceId: source!.source.id, envKey: key }); + if ( + source !== service && + !bindings.some( + (binding) => binding.sourceId === source!.source.id && binding.envKey === key, + ) + ) + bindings.push({ + sourceId: source!.source.id, + envKey: key, + ...(template === undefined ? {} : { valueTemplate: template }), + }); // A resolved URL can declare an otherwise undiscovered private listener. // A hostname-only value still works through the project network's DNS. if (!source!.source.port) { @@ -38,7 +60,8 @@ export function resolveRailwayBindings( const port = Number( url.port || (url.protocol === "https:" ? 443 : url.protocol === "http:" ? 80 : 0), ); - if (url.hostname === host && port > 0 && port <= 65535) source!.source.port = port; + if (url.hostname.toLowerCase() === host.toLowerCase() && port > 0 && port <= 65535) + source!.source.port = port; } catch { /* diagnostics-ignore: arbitrary strings and hostname-only variables do not declare a listener. */ } diff --git a/packages/platform/src/engine/modules/projects/folder/folder.service.ts b/packages/platform/src/engine/modules/projects/folder/folder.service.ts index 0b9a6c717..06e68493d 100644 --- a/packages/platform/src/engine/modules/projects/folder/folder.service.ts +++ b/packages/platform/src/engine/modules/projects/folder/folder.service.ts @@ -257,5 +257,6 @@ async function scanSource(session: FolderSession, opts: ResolveOptions = {}) { const st = await stat(session.stagingDir).catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "platform/engine/modules/projects/folder/folder.service"); return null; }); if (!st?.isDirectory()) throw new Error("Uploaded source not found"); const { resolveFromLocal } = await import("../../deployments/local-source"); - return resolveFromLocal(session.stagingDir, opts); + // Staging paths are private implementation details, not project names. + return resolveFromLocal(session.stagingDir, opts, session.name?.trim() || "app"); } diff --git a/packages/platform/src/engine/modules/projects/project-clone.service.ts b/packages/platform/src/engine/modules/projects/project-clone.service.ts index 6abf0122d..227c2d705 100644 --- a/packages/platform/src/engine/modules/projects/project-clone.service.ts +++ b/packages/platform/src/engine/modules/projects/project-clone.service.ts @@ -68,10 +68,6 @@ const PROJECT_FIELDS_NOT_CLONED = [ "deletionInProgress", "lifecycleOperation", "disabledAt", - // Detected from the live site; the copy has no site yet, so copying these would show the - // original's icon next to a project that has never served a request. - "favicon", - "faviconCheckedAt", // Routing that names specific hostnames. The copy starts with no domains (the confirm dialog // promises exactly this) — the originals stay with the project still serving them. "compositeRoutes", diff --git a/packages/platform/src/engine/modules/projects/project-connection.service.ts b/packages/platform/src/engine/modules/projects/project-connection.service.ts index 2678838fb..70a45f7cb 100644 --- a/packages/platform/src/engine/modules/projects/project-connection.service.ts +++ b/packages/platform/src/engine/modules/projects/project-connection.service.ts @@ -87,6 +87,8 @@ export async function listConnectionCandidates(ctx: RequestContext, projectId: s name: project.name, description: project.environmentName, appTemplateId: project.appTemplateId, + iconUrl: project.iconUrl, + framework: project.framework, clusterId: project.clusterId, }); } diff --git a/packages/platform/src/engine/modules/projects/project-crud.service.ts b/packages/platform/src/engine/modules/projects/project-crud.service.ts index d69a954e3..ebc17449d 100644 --- a/packages/platform/src/engine/modules/projects/project-crud.service.ts +++ b/packages/platform/src/engine/modules/projects/project-crud.service.ts @@ -13,8 +13,7 @@ import { type Project, type Server, } from "@repo/db"; -import { - slugify, +import { isImageUrl, slugify, runtimeProjectUpdate, assertRuntimeVersionTarget, AppError, @@ -1902,6 +1901,11 @@ async function updateProjectUnlocked( if (PROJECT_IDENTITY_KEYS.has(key)) continue; if (raw[key] !== undefined) update[key] = raw[key]; } + if (data.iconUrl !== undefined) { + const iconUrl = typeof data.iconUrl === "string" ? data.iconUrl.trim() || null : data.iconUrl; + if (iconUrl !== null && !isImageUrl(iconUrl)) throw new ValidationError("Icon URL must be an HTTP or HTTPS URL without credentials."); + update.iconUrl = iconUrl; + } Object.assign(update, runtimeProjectUpdate(p, update)); assertRuntimeVersionTarget({ ...p, ...update }); await assertBuildCommandUpdate(p, update); diff --git a/packages/platform/src/engine/modules/projects/project-home.operations.ts b/packages/platform/src/engine/modules/projects/project-home.operations.ts index a2b516850..671ff94d0 100644 --- a/packages/platform/src/engine/modules/projects/project-home.operations.ts +++ b/packages/platform/src/engine/modules/projects/project-home.operations.ts @@ -5,7 +5,6 @@ import { OperationError } from "@repo/contracts"; import type { ExecutionContext } from "../../../context"; import { presentProject } from "../../../projects"; import { authorization } from "../../lib/authorization"; -import { refreshProjectFaviconIfStale } from "../../lib/favicon-detector"; import { fetchOrgCloudProjects } from "../../lib/cloud/projects"; import { canProxyCloudResources } from "../../lib/cloud/scope"; import * as projectService from "./project.service"; @@ -86,10 +85,6 @@ export async function getProjectHome(ctx: ExecutionContext) { const primary = primariesByProject.get(original.id); const services = servicesByProject.get(original.id) ?? []; - refreshProjectFaviconIfStale(original, { - hostname: primary?.verified ? primary.hostname : null, - }); - return { ...presentProject(enriched), latestDeploymentId: latest?.id ?? null, diff --git a/packages/platform/src/engine/modules/projects/project-inspection.operations.ts b/packages/platform/src/engine/modules/projects/project-inspection.operations.ts index e04eefa03..bcabfcc9e 100644 --- a/packages/platform/src/engine/modules/projects/project-inspection.operations.ts +++ b/packages/platform/src/engine/modules/projects/project-inspection.operations.ts @@ -12,8 +12,7 @@ import { deploymentWorkload } from "../deployments/deployment-class"; import { serviceKind } from "../../lib/deployable-service"; import { maskDeploymentEnv } from "../../lib/secret-env"; import { listProjectRouteRows, resolveProjectRouteState } from "../domains/project-route.service"; -import { refreshProjectFaviconIfStale } from "../../lib/favicon-detector"; -import { pickCanonicalDomainRow, resolveProjectAccess } from "../../lib/public-endpoints"; +import { resolveProjectAccess } from "../../lib/public-endpoints"; import { readProjectRoutingClaims } from "../../lib/domain-claims"; import { serviceCustomHostnames } from "../../lib/routing-domains"; import { withDomainDiagnostics } from "../domains/domain-diagnostics"; @@ -107,9 +106,6 @@ export function createProjectInspectionOperations( domain: d.hostname, primary: d.isPrimary, })); - refreshProjectFaviconIfStale(project, { - hostname: pickCanonicalDomainRow(rawDomains)?.hostname ?? null, - }); // One server-computed access URL for every client surface. Derived from ALL // domain rows (service-scoped included, which the project-level publicEndpoints // resolver drops) + the effective deploy target, so a multi-service project diff --git a/packages/platform/src/engine/modules/projects/project.operations.ts b/packages/platform/src/engine/modules/projects/project.operations.ts index 5ed4def9a..b37b91194 100644 --- a/packages/platform/src/engine/modules/projects/project.operations.ts +++ b/packages/platform/src/engine/modules/projects/project.operations.ts @@ -10,7 +10,6 @@ import type { ExecutionContext } from "../../../context"; import { authorization } from "../../lib/authorization"; import { audit } from "../../lib/audit-emitter"; import { assertNativeSourcePath } from "../../native/source-policy"; -import { refreshProjectFaviconIfStale } from "../../lib/favicon-detector"; import { createProjectControls } from "./project-controls.operations"; import { clusterDatabaseEvents } from "./cluster-database.operations"; import { clusterVolumeEvents } from "./cluster-volume.operations"; @@ -88,7 +87,6 @@ export const projectDependencies: ProjectDependencies = { async get(ctx, id) { const service = await import("./project.service"); const project = await service.getProject(id, ctx.organizationId); - refreshProjectFaviconIfStale(project); return project; }, async update(ctx, id, input) { @@ -113,7 +111,6 @@ export const projectDependencies: ProjectDependencies = { }), }), }); - result.rows.forEach((row) => refreshProjectFaviconIfStale(row)); return { ...result, rows: result.rows.map((p) => ({ ...p, source: "local" })) }; }, recordAudit, diff --git a/packages/platform/src/engine/modules/system/managed-server-access.ts b/packages/platform/src/engine/modules/system/managed-server-access.ts index cab255ce0..ca1ede263 100644 --- a/packages/platform/src/engine/modules/system/managed-server-access.ts +++ b/packages/platform/src/engine/modules/system/managed-server-access.ts @@ -25,7 +25,7 @@ export async function managedConnection(ctx: ExecutionContext, id: string) { return { ...connection, workspaceId, - workspace: connection.client.workspace(connection.binding.workspaceId!), + workspace: connection.client.vm(connection.binding.workspaceId!), }; } export type ManagedConnection = Awaited>; diff --git a/packages/platform/src/engine/modules/system/server-managed.operations.ts b/packages/platform/src/engine/modules/system/server-managed.operations.ts index 89be3401f..ab41cb5a3 100644 --- a/packages/platform/src/engine/modules/system/server-managed.operations.ts +++ b/packages/platform/src/engine/modules/system/server-managed.operations.ts @@ -75,8 +75,8 @@ async function runtimeCredential(connection: ManagedConnection) { } if ( !result.token || - claims.type !== "workspace" || - claims.workspace_id !== connection.binding.workspaceId || + claims.type !== "vm" || + claims.vm_id !== connection.binding.workspaceId || typeof claims.token !== "string" || claims.token.length < 16 || typeof claims.exp !== "number" || @@ -267,7 +267,7 @@ const controls: ResourceServices = { if ((await runtimeStatus(connection)).enabled !== true) { const result = await connection.workspace.apiAccess.enable(); requireProviderSuccess(result); - connection.client.workspaces.invalidateRuntime(connection.binding.workspaceId!); + connection.client.vms.invalidateRuntime(connection.binding.workspaceId!); auditManagedControl(ctx, id, "runtime.enable"); } const after = await runtimeStatus(connection); @@ -299,7 +299,7 @@ const controls: ResourceServices = { try { requireProviderSuccess(await connection.workspace.apiAccess.rotateToken()); } finally { - connection.client.workspaces.invalidateRuntime(connection.binding.workspaceId!); + connection.client.vms.invalidateRuntime(connection.binding.workspaceId!); } const after = await runtimeCredential(connection); if (after.revision === before.revision) diff --git a/packages/platform/src/engine/modules/system/server.operations.ts b/packages/platform/src/engine/modules/system/server.operations.ts index b683ac6e8..207b73bfd 100644 --- a/packages/platform/src/engine/modules/system/server.operations.ts +++ b/packages/platform/src/engine/modules/system/server.operations.ts @@ -820,9 +820,8 @@ async function execOnServer( body: Parameters[1], ) { - // Primary gate: permission resolver (404 on deny, IDOR-safe). Asserted BEFORE the - // row is read, so a caller without access cannot distinguish "no such server" - // from "not yours". + // The shared server operation asserts server:admin before calling this service + // for every transport. Retain the organization-scoped lookup here as well. const server = await repos.server.getInOrganization(id, ctx.organizationId); if (!server) return failServer({ error: "Server not found" }, 404); diff --git a/packages/platform/src/source-archive.ts b/packages/platform/src/source-archive.ts index 6942c6e65..0f97e1635 100644 --- a/packages/platform/src/source-archive.ts +++ b/packages/platform/src/source-archive.ts @@ -62,6 +62,8 @@ export async function extractSourceArchive(archive: string, destination: string) await pipeline(createReadStream(archive), createGunzip(), sourceByteLimit(MAX_SOURCE_BYTES + MAX_SOURCE_ENTRIES * 1024 + 16 * 1024 * 1024), parser); } catch (error) { if (validationError) throw validationError; + if ((error as { code?: string }).code === "Z_BUF_ERROR") + throw new ValidationError("Source archive is incomplete or truncated. Retry the upload (maximum 300MB)."); if (/^(?:TAR_|Z_)/.test(String((error as { code?: string }).code))) throw new ValidationError("Invalid source archive"); throw error; } diff --git a/packages/platform/test/authorization.test.ts b/packages/platform/test/authorization.test.ts index 465ec67bd..2fb4948d9 100644 --- a/packages/platform/test/authorization.test.ts +++ b/packages/platform/test/authorization.test.ts @@ -31,6 +31,45 @@ beforeEach(async () => { }); describe("shared authorization", () => { + it("does not grant administration to an ordinary member", async () => { + state.members.set("org-a:alice", { id: "member-a", role: "member" }); + state.servers.set("server-a", { organizationId: "org-a" }); + const input = { resourceType: "server" as const, resourceId: "server-a", action: "admin" as const }; + expect(await auth.checkPermission("alice", "org-a", input)).toBe(false); + expect(await auth.checkPermissionOnResource(context, input)).toBe(false); + await expect(auth.authorize(context, input)).rejects.toMatchObject({ code: "NOT_FOUND" }); + }); + + it("does not let an existing token retain administration after its owner becomes a member", async () => { + state.servers.set("server-a", { organizationId: "org-a" }); + state.tokenGrants.set("token-a:server:server-a", { permissions: ["admin"] }); + const token = await auth.resolveScope({ ...alice, tokenScope: { tokenId: "token-a" }, + credential: { organizationId: "org-a", readOnly: false } }, "org-a"); + const input = { resourceType: "server" as const, resourceId: "server-a", action: "admin" as const }; + await expect(auth.authorize(token, input)).resolves.toBeDefined(); + state.members.set("org-a:alice", { id: "member-a", role: "member" }); + await expect(auth.authorize(token, input)).rejects.toMatchObject({ code: "NOT_FOUND" }); + }); + + it.each(["project", "server", "mail_server", "settings", "job"] as const)( + "keeps member read/write access separate from %s administration", async resourceType => { + state.members.set("org-a:alice", { id: "member-a", role: "member" }); + const input = { resourceType, resourceId: "*" }; + for (const action of ["read", "write"] as const) + expect(await auth.checkPermission("alice", "org-a", { ...input, action })).toBe(true); + expect(await auth.checkPermission("alice", "org-a", { ...input, action: "admin" })).toBe(false); + }, + ); + + it("preserves explicitly delegated administration for a restricted user on one server", async () => { + state.members.set("org-a:alice", { id: "member-a", role: "restricted" }); + state.servers.set("server-a", { organizationId: "org-a" }); + state.servers.set("server-other", { organizationId: "org-a" }); + state.grants.set("org-a:alice:server:server-a", { permissions: ["admin"] }); + await expect(auth.authorize(context, { resourceType: "server", resourceId: "server-a", action: "admin" })).resolves.toBeDefined(); + await expect(auth.authorize(context, { resourceType: "server", resourceId: "server-other", action: "admin" })).rejects.toMatchObject({ code: "NOT_FOUND" }); + }); + it("derives checked resources from core without widening the existing type", () => { expectTypeOf().toEqualTypeOf(); expect(new Set(CHECKED_RESOURCE_TYPES).size).toBe(CHECKED_RESOURCE_TYPES.length); diff --git a/packages/platform/test/deployment-container-info-schema.test.ts b/packages/platform/test/deployment-container-info-schema.test.ts index 273113f3a..409a1f8c6 100644 --- a/packages/platform/test/deployment-container-info-schema.test.ts +++ b/packages/platform/test/deployment-container-info-schema.test.ts @@ -15,7 +15,7 @@ async function createRuntime(kind: "Docker" | "Cloud", workspaceStatus = "runnin ? await DockerRuntime.create({ dockerSocketPath: "/tmp/openship-test-absent.sock" }) : await CloudDockerRuntime.forWorkspace( { - workspaces: { + vms: { get: async () => ({ id: "workspace-a", namespace: "namespace-a", diff --git a/packages/platform/test/domains.test.ts b/packages/platform/test/domains.test.ts index 3717aee3e..131f3e09a 100644 --- a/packages/platform/test/domains.test.ts +++ b/packages/platform/test/domains.test.ts @@ -121,7 +121,7 @@ describe("organization-scoped DNS operations", () => { const dns = createDnsOperations(authorization, { operations: { addCredential } as never, requireAdmin }); const input = { provider: "cloudflare" as const, name: "Production", apiToken: "private" }; state.members.set("org-a:alice", { id: "member-a", role: "member" }); - await expect(dns.addCredential(ctx, input)).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(dns.addCredential(ctx, input)).rejects.toMatchObject({ code: "NOT_FOUND" }); expect(addCredential).not.toHaveBeenCalled(); state.members.set("org-a:alice", { id: "member-a", role: "owner" }); const identity = { ...alice, tokenScope: { tokenId: "token" }, credential: { organizationId: "org-a", readOnly: false } }; diff --git a/packages/sdk/src/source-workflow.ts b/packages/sdk/src/source-workflow.ts index a57e397fc..4362fca95 100644 --- a/packages/sdk/src/source-workflow.ts +++ b/packages/sdk/src/source-workflow.ts @@ -15,7 +15,7 @@ export async function deploySourceWorkflow(ship: { projects: ProjectOperations; step("Creating project"); const hasBuild = Boolean(scan.buildCommand) || runtimeNeedsInstall(scan.stack, scan.runtimeVersion, scan.installCommand), hasServer = scan.workloadType !== "worker" && Boolean(scan.startCommand); const ensured = await ship.projects.ensure(parseInput(EnsureProjectBody, { - name: scan.name || input.name || "app", projectId: input.projectId, serverId, + name: input.name || scan.name || "app", projectId: input.projectId, serverId, deploymentEnvironment: input.environment, gitProvider: "upload", uploadSessionId: session.sessionId, framework: scan.stack, projectType: scan.projectType, packageManager: scan.packageManager, diff --git a/packages/sdk/test/native-runtime.test.ts b/packages/sdk/test/native-runtime.test.ts index daa1440f4..9c607c1ac 100644 --- a/packages/sdk/test/native-runtime.test.ts +++ b/packages/sdk/test/native-runtime.test.ts @@ -729,7 +729,7 @@ describe("owned native platform on Node", () => { await controls.setSleepMode(projectId, { sleep_mode: "always_on" }); expect((await controls.getResources(projectId)).sleepMode).toBe("always_on"); const bobScope = await first!.ship.scope({ identity: "bob", organizationId: first!.customer.organizationId }); - await expect(bobScope.credentials.create({ provider: "docker-registry", name: "Not an admin", values: { secret: "value" } })).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(bobScope.credentials.create({ provider: "docker-registry", name: "Not an admin", values: { secret: "value" } })).rejects.toMatchObject({ code: "NOT_FOUND" }); await first!.ship.operator!.setMembership({ organizationId: first!.customer.organizationId, userId: first!.bob.user.id, role: null }); await expect(bobScope.projects.get(projects[0]!.id)).rejects.toMatchObject({ code: "NOT_FOUND" }); await expect(bobScope.projects.setBranch(projectId, { branch: "forbidden" })).rejects.toMatchObject({ code: "NOT_FOUND" }); diff --git a/packages/sdk/test/sources.test.ts b/packages/sdk/test/sources.test.ts index 3af808d9c..58244da81 100644 --- a/packages/sdk/test/sources.test.ts +++ b/packages/sdk/test/sources.test.ts @@ -122,7 +122,7 @@ describe("SDK source deployments", () => { expect(s.tar()).toContain("initial-content"); expect(s.tar()).toContain("published-site"); expect(s.commands[2]?.body).toMatchObject({ - projectId: "existing", serverId: "server-a", name: "detected", deploymentEnvironment: "preview", + projectId: "existing", serverId: "server-a", name: "app", deploymentEnvironment: "preview", }); expect(s.commands[3]?.body).toMatchObject({ projectId: "project-a", uploadSessionId: "session/opaque", serverId: "server-a",