diff --git a/.env.example b/.env.example index fb8123bc7..e0073b4fb 100644 --- a/.env.example +++ b/.env.example @@ -251,8 +251,7 @@ GITHUB_APP_SLUG=openship-io # Set these in the deployed API environment. Both Compose stacks load this # root .env; they do NOT load apps/api/.env.saas (used by dev:saas). # Use the production account's credentials for the production SaaS. -# Optional complete API mount override. Unset uses the Oblien SDK default. -# OBLIEN_API_URL=https://your-proxy.example/api/v1 +# OBLIEN_API_URL=https://api.oblien.com # OBLIEN_CLIENT_ID= # OBLIEN_CLIENT_SECRET= # Optional public base-image pack for NEW managed Cloud spaces only. diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d57b1d29..77670a6ed 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,35 +6,11 @@ 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 29b19ad67..87c2474ab 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -57,12 +57,6 @@ violation. ## Scope -Organization owners and administrators can perform host administration. Ordinary -members retain read/write access but cannot perform operations requiring `admin`, -including server shell execution. Restricted users require explicit resource grants; -scoped tokens also respect their user's current built-in role. Host commands execute -as the server's configured account, so delegate server administration accordingly. - In scope — all Openship components: - Managed Openship Cloud diff --git a/apps/api/.env.saas.example b/apps/api/.env.saas.example index 0c1556ce6..a4f391f91 100644 --- a/apps/api/.env.saas.example +++ b/apps/api/.env.saas.example @@ -31,8 +31,7 @@ BETTER_AUTH_SECRET=change-me-in-production INTERNAL_TOKEN=change-me-32-byte-random-hex # Required for cloud deployments. -# Leave unset to use the installed SDK's default API version. -# OBLIEN_API_URL=https://your-proxy.example/api/v1 +OBLIEN_API_URL=https://api.oblien.com OBLIEN_CLIENT_ID= OBLIEN_CLIENT_SECRET= # Optional: enable only after this software preset is published on your provider. diff --git a/apps/api/scripts/cloud-readiness.ts b/apps/api/scripts/cloud-readiness.ts index 0a483cae5..1c2330b94 100644 --- a/apps/api/scripts/cloud-readiness.ts +++ b/apps/api/scripts/cloud-readiness.ts @@ -1,5 +1,4 @@ /** Read-only release checks. Does not create tokens, checkouts, or resources. */ -import { oblienApiBaseUrl, oblienApiUrl } from "@repo/adapters"; import { runtimeTarget } from "@repo/core"; import { assertOblienEntitlementMatchesSubscription, OblienBillingApi } from "@repo/platform/engine/lib/oblien-billing-api"; import { OBLIEN_WEBHOOK_EVENTS, oblienWebhookUrl } from "@repo/platform/engine/lib/oblien-webhook-config"; @@ -8,13 +7,13 @@ const results: Array<{ check: string; ok: boolean; skipped?: boolean; detail?: s const record = (check: string, ok: boolean, detail?: string) => results.push({ check, ok, ...(detail ? { detail } : {}) }); const clientId = process.env.OBLIEN_CLIENT_ID; const clientSecret = process.env.OBLIEN_CLIENT_SECRET; -const apiBase = oblienApiBaseUrl(process.env.OBLIEN_API_URL); +const apiBase = process.env.OBLIEN_API_URL ?? "https://api.oblien.com"; record("Cloud mode", process.env.CLOUD_MODE === "true"); record("Oblien credentials configured", Boolean(clientId && clientSecret)); record("Webhook secret configured", Boolean(process.env.OBLIEN_WEBHOOK_SECRET)); record("Subscription purchases enabled", process.env.BILLING_ENABLED === "true"); -const billing = new OblienBillingApi({ clientId, clientSecret, baseUrl: apiBase.toString() }); +const billing = new OblienBillingApi({ clientId, clientSecret, baseUrl: apiBase }); const checks = await Promise.allSettled([ (async () => { await billing.assertResellerSupport(); @@ -36,13 +35,13 @@ const checks = await Promise.allSettled([ (async () => { const callback = oblienWebhookUrl(process.env.OBLIEN_WEBHOOK_URL, runtimeTarget.api); if (!clientId || !clientSecret) throw new Error("Oblien credentials are missing"); - const response = await fetch(oblienApiUrl(apiBase, "/webhooks"), { + const response = await fetch(`${apiBase.replace(/\/+$/, "")}/webhooks`, { headers: { "X-Client-ID": clientId, "X-Client-Secret": clientSecret }, redirect: "error", signal: AbortSignal.timeout(15_000), }); if (!response.ok) throw new Error(`Webhook registry HTTP ${response.status}`); const body = await response.json() as { success: boolean; webhooks?: Array<{ url: string; active: boolean; namespace?: string | null; events: string[]; secret?: string | null }> }; - const webhook = body.success ? body.webhooks?.find((item) => item.url === callback && !item.namespace && item.active) : undefined; + const webhook = body.success && body.webhooks?.find((item) => item.url === callback && !item.namespace && item.active); const missing = OBLIEN_WEBHOOK_EVENTS.filter((event) => !webhook || !webhook.events.includes(event)); const maskedSecret = typeof webhook?.secret === "string" && /^[*•*…]+$/u.test(webhook.secret); const matchingSecret = Boolean(webhook?.secret && webhook.secret === process.env.OBLIEN_WEBHOOK_SECRET); @@ -57,7 +56,7 @@ const checks = await Promise.allSettled([ })(), (async () => { if (!clientId || !clientSecret) throw new Error("Oblien credentials are missing"); - const response = await fetch(oblienApiUrl(apiBase, "/namespaces?limit=1"), { + const response = await fetch(`${apiBase.replace(/\/+$/, "")}/namespaces?limit=1`, { headers: { "X-Client-ID": clientId, "X-Client-Secret": clientSecret }, redirect: "error", signal: AbortSignal.timeout(15_000), }); diff --git a/apps/api/src/app.ts b/apps/api/src/app.ts index 0363ab976..264549493 100644 --- a/apps/api/src/app.ts +++ b/apps/api/src/app.ts @@ -23,7 +23,6 @@ import { registerControllerLifecycle, } from "./modules/system/instance/controller-state"; import { resumeControllerSockets } from "./lib/ws"; -import { resumeControllerStreams } from "./lib/sse"; import { trackBackgroundWork } from "@repo/platform/engine/lib/background-work"; import { instanceAuthorityGuard } from "./modules/system/instance/authority-guard"; import { quiesceController } from "./modules/system/instance/quiescence"; @@ -409,7 +408,6 @@ async function startControllerBackground(): Promise { backgroundStarted = true; try { resumeControllerSockets(); - resumeControllerStreams(); // ─── Backup job runner + boot reconcile ───────────────────────────── // // One JobRunner powers all backup work — BullMQ when Redis is diff --git a/apps/api/src/lib/route-permission.ts b/apps/api/src/lib/route-permission.ts index 36deb84ae..39337096d 100644 --- a/apps/api/src/lib/route-permission.ts +++ b/apps/api/src/lib/route-permission.ts @@ -276,8 +276,6 @@ export interface McpRouteMeta { description: string; /** Override the inferred hint for actions such as destructive migration cutover. */ destructive?: boolean; - /** Whether this tool may interact with external systems; defaults to true. */ - openWorld?: boolean; } export interface PermissionSpec { @@ -476,10 +474,13 @@ export function isPublicSpec(spec: RouteSpec): spec is PublicSpec { * Be precise about what that org-wide check buys, because it is easy to misread as * a defense it is not: it is strict only for a RESTRICTED principal (a scoped * token), which needs an all-GitHub grant to pass. For a session-authenticated - * owner/admin it is satisfied by broad membership authority. Ordinary members - * cannot satisfy an admin action. Per-repo read/write authority still belongs - * to `github-access.ts` at the token funnel and mutating service helpers; an - * org-wide tag never substitutes for that repository-specific check. + * owner/admin/**member** it is satisfied by bare membership — + * `roleAllowsResourceType` (permission.ts) ignores the action level for those + * roles, so `github:admin` is no higher a bar than `github:read`. The per-repo, + * read-vs-write authority for those principals is enforced ONLY by + * `github-access.ts` at the token funnel and at the mutating service helpers. + * Reading this comment as "the route layer already gates writes" is what let + * GHSA-hp2g-hw7g-f3vm sit behind a `github:admin` tag. * Paramless GitHub routes (/home, /status, /repos) also stay on the org-wide * path: `filterToolsForPrincipal` already hides them from a scoped token via * `perm.wildcard`, and their handlers narrow results through diff --git a/apps/api/src/lib/sse.ts b/apps/api/src/lib/sse.ts index 469f5dde6..210f16549 100644 --- a/apps/api/src/lib/sse.ts +++ b/apps/api/src/lib/sse.ts @@ -41,12 +41,7 @@ import { SYSTEM } from "@repo/core"; import { trackBackgroundWork } from "@repo/platform/engine/lib/background-work"; const controllerStreams = new Set(); -let accepting = true; -export function resumeControllerStreams(): void { - accepting = true; -} export function closeControllerStreams(): void { - accepting = false; for (const stream of controllerStreams) stream.abort(); } @@ -187,16 +182,6 @@ export function streamSSE( c: Context, cb: (stream: SSEStreamingApi) => Promise, ) { - // An admitted request can finish its permission/metadata read after the HTTP - // fence closed existing streams. Do not give the drain a new live subscriber. - if (!accepting) { - c.header("Retry-After", "5"); - c.header("Cache-Control", "no-store"); - return c.json({ - code: "INSTANCE_CONTROLLER_INACTIVE", - error: "Your instance is moving. Reconnect after the handoff.", - }, 503); - } const context = currentErrorContext(); // Disable reverse-proxy response buffering. nginx/OpenResty buffer proxied // responses by default, which holds SSE events back until the buffer fills — diff --git a/apps/api/src/modules/billing/billing-capacity-catalog.test.ts b/apps/api/src/modules/billing/billing-capacity-catalog.test.ts index eea7004b3..e49d13054 100644 --- a/apps/api/src/modules/billing/billing-capacity-catalog.test.ts +++ b/apps/api/src/modules/billing/billing-capacity-catalog.test.ts @@ -9,7 +9,6 @@ import type { OblienSubscription } from "@repo/platform/engine/lib/oblien-billin import { savedOffer, savedMetadata, savedMonthlyHobby } from "../../../test/helpers/saved-cloud-offer"; import capacityFixture from "../../../test/fixtures/oblien-capacity-catalog.json"; import { oblienCapacityCatalogSchema } from "@repo/platform/engine/lib/oblien-capacity"; -import { cloudBillingContract } from "@repo/adapters"; const savedPro = (): NonNullable => ({ tierId: "reseller", status: "active", billingInterval: "monthly", periodStart: "2026-09-01T00:00:00Z", periodEnd: "2026-10-01T00:00:00Z", cancelAtPeriodEnd: false, canceledAt: null, @@ -18,7 +17,7 @@ const monthlyPro = (): NonNullable => ({ ...savedPro(), offer: subscriptionOffer("pro", "monthly"), metadata: subscriptionMetadata("pro", "org-a", "ns-a") }); describe("funded Cloud offers and isolated capacity", () => { - it.each([undefined, oblienCapacityCatalogSchema.parse(cloudBillingContract(capacityFixture))])( + it.each([undefined, oblienCapacityCatalogSchema.parse(capacityFixture)])( "publishes only subscription plans without prepaid compute offers (with or without provider capacity)", (provider) => { const catalog = presentCloudPlans("en", provider); diff --git a/apps/api/src/modules/billing/billing-checkout.test.ts b/apps/api/src/modules/billing/billing-checkout.test.ts index 58bfb2d97..9bfae4ea9 100644 --- a/apps/api/src/modules/billing/billing-checkout.test.ts +++ b/apps/api/src/modules/billing/billing-checkout.test.ts @@ -37,7 +37,7 @@ vi.mock("@repo/platform/engine/lib/cloud-workspace-host", () => ({ readCloudWorkspaceHost: async () => ({ provider: null }), })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ - getOblienClient: () => ({ vms: { getQuota: h.quota } }), + getOblienClient: () => ({ workspaces: { getQuota: h.quota } }), getOblienBillingApi: () => ({ createCheckout: h.checkout, createPortal: h.portal, diff --git a/apps/api/src/modules/billing/billing-reconcile.test.ts b/apps/api/src/modules/billing/billing-reconcile.test.ts index 3ee761206..5d92b3621 100644 --- a/apps/api/src/modules/billing/billing-reconcile.test.ts +++ b/apps/api/src/modules/billing/billing-reconcile.test.ts @@ -116,25 +116,15 @@ describe("Oblien-managed entitlements", () => { h.balance.mockResolvedValue({ ...state.balance, billingMode: "payg" }); await expect(assertCloudCanSpend("org_1")).rejects.toMatchObject({ code: "CLOUD_BILLING_BLOCKED" }); }); - it.each(["active", "past_due"] as const)("allows billing recovery during a %s unpaid renewal without granting compute or credits", async status => { + it("allows billing recovery after an unpaid renewal without granting compute or credits", async () => { const state = unpaidMonthlyCloudBilling(); - state.subscription.status = status; h.entitlement.mockResolvedValue(state.entitlement); h.subscription.mockResolvedValue({ namespace: state.entitlement.namespace, subscription: state.subscription }); h.balance.mockResolvedValue(state.balance); const result = await syncOblienEntitlement("org_1", { syncResourceLimits: false }); - expect(result).toMatchObject({ tier: "pro", subscription: { status }, entitlement: { status: "canceled", computeCovered: false } }); + expect(result).toMatchObject({ tier: "pro", subscription: { status: "past_due" }, entitlement: { status: "canceled", computeCovered: false } }); await expect(assertNamespaceHasQuota("org_1")).resolves.toBeUndefined(); await expect(assertCloudCanSpend("org_1")).rejects.toMatchObject({ statusCode: 402, code: "CLOUD_BILLING_BLOCKED" }); - expect(h.mirror).toHaveBeenCalledWith("workspace_1", "org_1", "os-customer", { - planTierId: "pro", subscriptionStatus: "canceled", - currentPeriodStart: new Date(state.entitlement.periodStart!), - currentPeriodEnd: new Date(state.entitlement.periodEnd!), - }); - // A newer balance response alone must not turn old, uncovered capacity into - // paid compute. Both authoritative reads must confirm the funded month. - h.balance.mockResolvedValue({ ...state.balance, blocking: false, computeCovered: true }); - await expect(assertCloudCanSpend("org_1")).rejects.toMatchObject({ statusCode: 402, code: "CLOUD_BILLING_BLOCKED" }); expect(h.limits).not.toHaveBeenCalled(); expect(h.setQuota).not.toHaveBeenCalled(); expect(h.resetQuota).not.toHaveBeenCalled(); diff --git a/apps/api/src/modules/billing/oblien-billing-api.test.ts b/apps/api/src/modules/billing/oblien-billing-api.test.ts index 1723cabb3..16fd45c0e 100644 --- a/apps/api/src/modules/billing/oblien-billing-api.test.ts +++ b/apps/api/src/modules/billing/oblien-billing-api.test.ts @@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, it, expect, vi } from "vitest"; import { OblienBillingApi, oblienOfferSchema, assertOblienEntitlementMatchesSubscription } from "@repo/platform/engine/lib/oblien-billing-api"; import { BillingOperationSchemas } from "@repo/contracts"; import { Value } from "@sinclair/typebox/value"; -import { providerBillingFixture } from "../../../test/helpers/oblien-vm-billing"; import capacityCatalog from "../../../test/fixtures/oblien-capacity-catalog.json"; import { monthlyCloudBilling, unpaidMonthlyCloudBilling } from "../../../test/helpers/monthly-cloud-offer"; @@ -26,7 +25,7 @@ const subscription = { success: true, namespace: "os-one", subscription: { cancelAtPeriodEnd: true, canceledAt: "2026-09-15T00:00:00Z", } }; function setup(body: unknown, status = 200) { - const fetcher = vi.fn(async (_url: Parameters[0], _init?: RequestInit) => Response.json(providerBillingFixture(body), { status })); + const fetcher = vi.fn(async (_url: Parameters[0], _init?: RequestInit) => Response.json(body, { status })); const api = new OblienBillingApi({ clientId: "test-id", clientSecret: "test-secret", fetch: fetcher as unknown as typeof fetch }); return { api, fetcher }; } @@ -48,7 +47,7 @@ describe("Oblien billing SDK and transport contract", () => { await api.createCheckout({ namespace: "os-one", kind: "subscription", billingInterval: "yearly", offer: { ...monthlyCloudBilling().subscription.offer!, unitAmount: 12000 }, metadata, affiliateBuyer, affiliateCode: "AF-0123456789", successUrl: "https://app.openship.io", cancelUrl: "https://app.openship.io", idempotencyKey: "referral-transport" }); - expect(fetcher).toHaveBeenCalledExactlyOnceWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({ + expect(fetcher).toHaveBeenCalledExactlyOnceWith("https://api.oblien.com/billing/checkout", expect.objectContaining({ method: "POST", redirect: "error", signal: expect.any(AbortSignal), headers: expect.objectContaining({ "X-Client-ID": "test-id", "X-Client-Secret": "test-secret" }), })); @@ -60,7 +59,7 @@ describe("Oblien billing SDK and transport contract", () => { const live = { success: true, credits_per_dollar: 100, rate_card_id: "live", rates: { cpu_per_min: 1.5, memory_per_gb_min: 0.2, disk_per_gb: 0, network_per_gb: 0.15 } }; const { api, fetcher } = setup({ ...live, compute_rate_cards: [{ chargeEnabled: false, cpu_per_min: 0.001 }] }); expect(await api.getMeteredPricing()).toEqual(live); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/pricing/calculator", expect.objectContaining({ method: "GET", redirect: "error", headers: { Accept: "application/json" } })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/pricing/calculator", expect.objectContaining({ method: "GET", redirect: "error", headers: { Accept: "application/json" } })); }); it.each([ { credits_per_dollar: 50, rate_card_id: "new", rates: { cpu_per_min: 1, memory_per_gb_min: 1, disk_per_gb: 0, network_per_gb: 0 } }, @@ -75,14 +74,14 @@ describe("Oblien billing SDK and transport contract", () => { const { api, fetcher } = setup({ success: true, namespace: "os-one", pendingCheckout, wallet: { balance: 12000 } }); expect(await api.getPendingCapacityCheckout("os-one")).toEqual({ success: true, namespace: "os-one", pendingCheckout: { ...pendingCheckout, quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" } } }); - expect(fetcher.mock.calls[0]![0]).toBe("https://api.oblien.com/v1/billing/capacity?namespace=os-one"); + expect(fetcher.mock.calls[0]![0]).toBe("https://api.oblien.com/billing/capacity?namespace=os-one"); await expect(api.getPendingCapacityCheckout("os-other")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" }); }); it("cancels a capacity payment with the saved provider quote and retry identity", async () => { const { api, fetcher } = setup({ success: true, namespace: "os-one", pendingCheckout: null }); const input = { quoteId: "quote_pending", idempotencyKey: "cancel-once" }; await expect(api.cancelCapacityCheckout("os-one", input)).resolves.toMatchObject({ pendingCheckout: null }); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/capacity/change/cancel", expect.objectContaining({ + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/capacity/change/cancel", expect.objectContaining({ method: "POST", })); expect(JSON.parse(fetcher.mock.calls[0]![1]!.body as string)).toEqual({ namespace: "os-one", ...input }); @@ -102,7 +101,7 @@ describe("Oblien billing SDK and transport contract", () => { (await api.cancelCheckout("os-one", checkout.id, { idempotencyKey: "cancel-once" })).checkout, ).toEqual(checkout); expect(fetcher).toHaveBeenCalledWith( - "https://api.oblien.com/v1/billing/checkout/bco_original/cancel", + "https://api.oblien.com/billing/checkout/bco_original/cancel", expect.objectContaining({ method: "POST", body: JSON.stringify({ namespace: "os-one", idempotencyKey: "cancel-once" }), @@ -124,7 +123,7 @@ describe("Oblien billing SDK and transport contract", () => { it.each([ { quote: { id: "quote_pending", namespace: "os-other", paymentSource: "stripe" }, checkoutId: "cs_requested", url: null }, { quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" }, checkoutId: "cs_requested", url: "https://evil.example/pay" }, - { quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" }, checkoutId: "cs_requested", url: "https://api.oblien.com/v1/not-a-payment#secret" }, + { quote: { id: "quote_pending", namespace: "os-one", paymentSource: "stripe" }, checkoutId: "cs_requested", url: "https://api.oblien.com/not-a-payment#secret" }, ])("rejects foreign capacity scope and untrusted resume URLs", async pendingCheckout => { await expect(setup({ success: true, namespace: "os-one", pendingCheckout }).api.getPendingCapacityCheckout("os-one")).rejects.toThrow(); }); @@ -136,16 +135,16 @@ describe("Oblien billing SDK and transport contract", () => { }); it("scopes complimentary policy writes to the requested namespace and validates the response", async () => { const policy = { quotaLimit: 3000, overdraft: 60, suspendThreshold: 60, onOverdraftAction: "stop_workspaces" as const }; - const result = { success: true, namespace: "os-one", service: "vm_compute", ...policy }; + const result = { success: true, namespace: "os-one", service: "workspace_vm", ...policy }; const { api, fetcher } = setup(result); expect(await api.setPolicy("os-one", policy)).toEqual(result); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/policy/os-one", expect.objectContaining({ method: "PUT", body: JSON.stringify(providerBillingFixture(policy)) })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/policy/os-one", expect.objectContaining({ method: "PUT", body: JSON.stringify(policy) })); await expect(api.setPolicy("os-two", policy)).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" }); }); it("keeps the same provider reset key on retry and rejects an unscoped reset response", async () => { const { api, fetcher } = setup({ success: true, namespace: "os-one", applied: false }); expect(await api.resetQuota("os-one", "2026-10-25T14:00:00.000Z")).toMatchObject({ applied: false }); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/policy/os-one/reset", expect.objectContaining({ method: "POST", body: JSON.stringify({ periodEnd: "2026-10-25T14:00:00.000Z" }) })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/policy/os-one/reset", expect.objectContaining({ method: "POST", body: JSON.stringify({ periodEnd: "2026-10-25T14:00:00.000Z" }) })); await expect(setup({ success: true, applied: true }).api.resetQuota("os-one", "2026-10-25T14:00:00.000Z")) .rejects.toMatchObject({ code: "OBLIEN_BILLING_INVALID_RESPONSE" }); }); @@ -216,7 +215,7 @@ describe("Oblien billing SDK and transport contract", () => { expect(state.checkout).not.toHaveProperty("walletCredits"); expect(state.checkout).not.toHaveProperty("paymentId"); expect(fetcher.mock.calls[0]![0]).toBe( - "https://api.oblien.com/v1/billing/checkout/cs_requested?namespace=os-one", + "https://api.oblien.com/billing/checkout/cs_requested?namespace=os-one", ); await expect(api.getCheckout("os-other", "cs_requested")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH", @@ -252,7 +251,7 @@ describe("Oblien billing SDK and transport contract", () => { it("authenticates server requests and validates the returned customer namespace", async () => { const { api, fetcher } = setup(entitlement); expect((await api.getEntitlement("os-one")).quota.used).toBe(-50); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/entitlement?namespace=os-one", expect.objectContaining({ + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/entitlement?namespace=os-one", expect.objectContaining({ headers: expect.objectContaining({ "X-Client-ID": "test-id", "X-Client-Secret": "test-secret" }), redirect: "error", })); await expect(api.getEntitlement("os-two")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" }); @@ -276,24 +275,22 @@ describe("Oblien billing SDK and transport contract", () => { idempotencyKey: "checkout-123", }; await api.createCheckout(input); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({ method: "POST" })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/checkout", expect.objectContaining({ method: "POST" })); expect(JSON.parse(String(fetcher.mock.calls[0]![1]!.body))).toEqual({ ...input, allowPromotionCodes: true }); }); - it("keeps the hosted payment page unversioned while sending checkout requests to /v1", async () => { + it("accepts the exact Oblien promotion checkout and preserves its opaque ID", async () => { const checkoutId = "bco_24f15202-6a3d-4b27-b7c2-c3abbc401bee"; const url = `https://api.oblien.com/billing/pay#${"a".repeat(43)}`; - const { api, fetcher } = setup({ success: true, url, checkoutId }); + const { api } = setup({ success: true, url, checkoutId }); await expect(api.createCheckout({ namespace: "os-one", kind: "topup", offer, metadata, successUrl: "https://app.openship.io", cancelUrl: "https://app.openship.io", idempotencyKey: "promotion-checkout" })) .resolves.toMatchObject({ url, checkoutId }); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/checkout", expect.objectContaining({ method: "POST" })); }); it.each([ "http://api.oblien.com/billing/pay", "https://api.oblien.com.evil.example/billing/pay", - "https://api.oblien.com/billing/pay?return=https://evil.example", "https://api.oblien.com/v1/other", + "https://api.oblien.com/billing/pay?return=https://evil.example", "https://api.oblien.com/other", "https://api.oblien.com/billing/pay", "https://user@api.oblien.com/billing/pay", "https://api.oblien.com:8443/billing/pay", "https://api.oblien.com/billing/pay/", - "https://api.oblien.com/v1/billing/pay", ])("rejects an invalid promotion checkout URL: %s", async (value) => { const url = value + (value === "https://api.oblien.com/billing/pay" ? "#short" : `#${"a".repeat(43)}`); await expect(setup({ success: true, url, checkoutId: "bco_24f15202-6a3d-4b27-b7c2-c3abbc401bee" }).api.createCheckout({ @@ -556,7 +553,7 @@ describe("Oblien billing SDK and transport contract", () => { const { api, fetcher } = setup({ success: true, namespace: "os-one", url: "https://billing.stripe.com/p/session/test" }); const input = { namespace: "os-one", returnUrl: "https://app.openship.io/billing/overview" }; expect((await api.createPortal(input)).url).toBe("https://billing.stripe.com/p/session/test"); - expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/portal", expect.objectContaining({ method: "POST", body: JSON.stringify(input), redirect: "error", signal: expect.any(AbortSignal) })); + expect(fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/portal", expect.objectContaining({ method: "POST", body: JSON.stringify(input), redirect: "error", signal: expect.any(AbortSignal) })); await expect(api.createPortal({ ...input, namespace: "os-two" })).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" }); }); it("rejects a legacy owner portal even when its hosted URL is otherwise valid", async () => { @@ -575,7 +572,7 @@ describe("Oblien billing SDK and transport contract", () => { ] as const)("uses the SDK %s method and checks the response namespace", async (method, verb, path) => { const { api, fetcher } = setup(subscription); expect(await api[method]("os-one")).toEqual(subscription); - expect(fetcher).toHaveBeenCalledWith(`https://api.oblien.com/v1${path}`, expect.objectContaining({ + expect(fetcher).toHaveBeenCalledWith(`https://api.oblien.com${path}`, expect.objectContaining({ method: verb, ...(verb === "POST" ? { body: JSON.stringify({ namespace: "os-one" }) } : {}), })); await expect(api[method]("os-two")).rejects.toMatchObject({ code: "OBLIEN_BILLING_NAMESPACE_MISMATCH" }); @@ -615,7 +612,7 @@ describe("Oblien monthly capacity contract", () => { const catalog = await api.assertMonthlyCapacitySupport(); expect(catalog.tariff.usage).toEqual({ activeVcpuHourCents: 3, reservedGiBHourCents: 0.8, retainedGiBMonthCents: 5, monthHours: 720 }); const [url, request] = fetcher.mock.calls[0]!; - expect(String(url)).toBe("https://api.oblien.com/v1/billing/capacity/catalog"); + expect(String(url)).toBe("https://api.oblien.com/billing/capacity/catalog"); expect(request?.headers).not.toHaveProperty("X-Client-Secret"); expect(request?.headers).not.toHaveProperty("X-Client-ID"); }); @@ -659,7 +656,7 @@ describe("Oblien monthly capacity contract", () => { .toThrow(/does not match/); } }); - it.each(["active", "past_due", "unpaid", "paused", "canceled"] as const)("keeps billing readable for an expired paid month and a %s renewal", async status => { + it.each(["past_due", "unpaid", "paused", "canceled"] as const)("keeps billing readable for an expired paid month and a %s renewal", async status => { const state = unpaidMonthlyCloudBilling("org-one", "os-one"); state.subscription.status = status; const entitlement = await setup(state.entitlement).api.getEntitlement("os-one"); @@ -668,8 +665,9 @@ describe("Oblien monthly capacity contract", () => { expect(entitlement).toMatchObject({ status: "canceled", computeCovered: false, capacity: { status: "expired", computeCovered: false } }); expect(entitlement.periodEnd).not.toBe(subscription!.periodEnd); }); - it.each(["active", "past_due"] as const)("still rejects funded, overlapping, foreign or inconsistent %s renewal records", status => { + it("still rejects funded, overlapping, foreign or inconsistent unpaid renewal records", () => { for (const mutate of [ + (state: ReturnType) => { state.subscription.status = "active"; }, (state: ReturnType) => { state.subscription.status = "trialing"; }, (state: ReturnType) => { state.entitlement.status = "active"; }, (state: ReturnType) => { state.entitlement.computeCovered = state.entitlement.capacity!.computeCovered = true; }, @@ -680,12 +678,9 @@ describe("Oblien monthly capacity contract", () => { (state: ReturnType) => { state.subscription.periodStart = "2026-10-15T00:00:00Z"; }, (state: ReturnType) => { state.subscription.periodStart = null; }, (state: ReturnType) => { state.subscription.periodEnd = state.subscription.periodStart; }, - (state: ReturnType) => { state.entitlement.periodStart = state.entitlement.capacity!.periodStart = state.entitlement.periodEnd!; }, (state: ReturnType) => { state.entitlement.capacity!.periodEnd = "2026-10-31T00:00:00Z"; }, ]) { - const state = unpaidMonthlyCloudBilling(); - state.subscription.status = status; - mutate(state); + const state = unpaidMonthlyCloudBilling(); mutate(state); expect(() => assertOblienEntitlementMatchesSubscription(state.entitlement, state.subscription)).toThrow(/does not match/); } }); @@ -697,9 +692,9 @@ describe("Oblien monthly capacity contract", () => { offer: subscription.offer!, metadata: subscription.metadata!, idempotencyKey: "saved-monthly-order", successUrl: "https://app.openship.io/billing/overview", cancelUrl: "https://app.openship.io/billing/plans" }); const [url, request] = fetcher.mock.calls[0]!; - expect(String(url)).toBe("https://api.oblien.com/v1/billing/checkout"); + expect(String(url)).toBe("https://api.oblien.com/billing/checkout"); const sent = JSON.parse(String(request?.body)); - expect(sent.offer).toMatchObject({ unitAmount, credits: 0, billingMode: "monthly", capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, vms: 1 } }); + expect(sent.offer).toMatchObject({ unitAmount, credits: 0, billingMode: "monthly", capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, workspaces: 1 } }); expect(sent.offer).not.toHaveProperty("policy"); expect(sent.idempotencyKey).toBe("saved-monthly-order"); expect(sent.allowPromotionCodes).toBe(unitAmount > 0); @@ -768,18 +763,18 @@ describe("Oblien subscription changes", () => { it("delegates all four methods to the official SDK and preserves provider cents and fractional credits", async () => { const preview = setup({ success: true, namespace: "os-one", quote }); expect((await preview.api.previewPlanChange("os-one", input)).quote).toEqual(quote); - expect(preview.fetcher).toHaveBeenCalledWith("https://api.oblien.com/v1/billing/subscription/changes/preview", + expect(preview.fetcher).toHaveBeenCalledWith("https://api.oblien.com/billing/subscription/changes/preview", expect.objectContaining({ method: "POST" })); expect(JSON.parse(String(preview.fetcher.mock.calls[0]![1]!.body))).toEqual({ namespace: "os-one", ...input }); const accept = setup({ success: true, namespace: "os-one", change }, 202); expect((await accept.api.changePlan("os-one", { quoteId: quote.id, idempotencyKey: "confirm-request" })).change.status).toBe("payment_pending"); - expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/billing/subscription/changes", + expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/billing/subscription/changes", expect.objectContaining({ method: "POST" })); expect(JSON.parse(String(accept.fetcher.mock.calls.at(-1)![1]!.body))).toEqual({ namespace: "os-one", quoteId: quote.id, idempotencyKey: "confirm-request" }); await accept.api.getPlanChange("os-one", change.id); - expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/billing/subscription/changes/change_one?namespace=os-one", expect.objectContaining({ method: "GET" })); + expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/billing/subscription/changes/change_one?namespace=os-one", expect.objectContaining({ method: "GET" })); await accept.api.cancelPlanChange("os-one", change.id, "cancel-request"); - expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/v1/billing/subscription/changes/change_one/cancel", + expect(accept.fetcher).toHaveBeenLastCalledWith("https://api.oblien.com/billing/subscription/changes/change_one/cancel", expect.objectContaining({ method: "POST" })); expect(JSON.parse(String(accept.fetcher.mock.calls.at(-1)![1]!.body))).toEqual({ namespace: "os-one", idempotencyKey: "cancel-request" }); }); diff --git a/apps/api/src/modules/billing/oblien-managed-transfer.test.ts b/apps/api/src/modules/billing/oblien-managed-transfer.test.ts index c43a1504f..fb2ed26a8 100644 --- a/apps/api/src/modules/billing/oblien-managed-transfer.test.ts +++ b/apps/api/src/modules/billing/oblien-managed-transfer.test.ts @@ -1,12 +1,11 @@ import { describe, expect, it } from "vitest"; import { Value } from "@sinclair/typebox/value"; import { BillingComputeSchema } from "@repo/contracts"; -import { providerBillingFixture } from "../../../test/helpers/oblien-vm-billing"; import { OblienBillingApi, assertOblienEntitlementMatchesSubscription } from "@repo/platform/engine/lib/oblien-billing-api"; import { monthlyCloudBilling } from "../../../test/helpers/monthly-cloud-offer"; import transfer from "../../../test/fixtures/oblien-managed-transfer.json"; -// Native provider transfer counters with synthetic data. +// SDK 2.10's live response shape, with synthetic counters and no customer data. const unlimited = { ...transfer, unlimited: true, includedBytes: null, includedAvailableBytes: null, availableBytes: null }; async function readTransfer(network: unknown, covered = true) { @@ -15,7 +14,7 @@ async function readTransfer(network: unknown, covered = true) { ...entitlement.capacity, computeCovered: covered, network, } }; const api = new OblienBillingApi({ clientId: "test-id", clientSecret: "test-secret", - fetch: (async () => Response.json(providerBillingFixture(payload))) as typeof fetch }); + fetch: (async () => Response.json(payload)) as typeof fetch }); const result = await api.getEntitlement("os-one"); assertOblienEntitlementMatchesSubscription(result, subscription); return result.capacity!; diff --git a/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts b/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts index 25c707895..d92cc82fe 100644 --- a/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts +++ b/apps/api/src/modules/billing/oblien-webhook-crypto.test.ts @@ -64,7 +64,7 @@ describe("deriveOblienEventId", () => { const base: OblienEventEnvelope = { event: "credits.usage", timestamp: "2026-07-21T10:00:00Z", - data: { namespace: "os-abc", vm_id: "ws_1", period_end: "2026-08-01T00:00:00Z" }, + data: { namespace: "os-abc", workspace_id: "ws_1", period_end: "2026-08-01T00:00:00Z" }, }; it("is deterministic for the same payload", () => { diff --git a/apps/api/src/modules/billing/oblien-webhook.controller.test.ts b/apps/api/src/modules/billing/oblien-webhook.controller.test.ts index 2302b9d73..360375850 100644 --- a/apps/api/src/modules/billing/oblien-webhook.controller.test.ts +++ b/apps/api/src/modules/billing/oblien-webhook.controller.test.ts @@ -294,7 +294,7 @@ describe("oblienWebhook — dispatch", () => { describe("durable quota alert receipt", () => { it("returns 503 without a checkpoint when notification storage fails, then retries the same event", async () => { - const body = JSON.stringify({ id: "evt-critical", event: "credits.depleted", data: { namespace: "os-abc", service: "vm_compute" } }); + const body = JSON.stringify({ id: "evt-critical", event: "credits.depleted", data: { namespace: "os-abc", service: "workspace_vm" } }); h.enqueue.mockRejectedValueOnce(new Error("database unavailable")); expect(((await oblienWebhook(makeCtx(body, sign(body), "evt-critical"))) as unknown as JsonResult).status).toBe(503); expect(h.processed.size).toBe(0); @@ -305,7 +305,7 @@ describe("durable quota alert receipt", () => { expect(h.processed.size).toBe(1); }); it("leaves the event retryable when exhaustion activity cannot be recorded", async () => { - const body = JSON.stringify({ id: "evt-activity", event: "credits.depleted", data: { namespace: "os-abc", service: "vm_compute" } }); + const body = JSON.stringify({ id: "evt-activity", event: "credits.depleted", data: { namespace: "os-abc", service: "workspace_vm" } }); h.auditRecord.mockRejectedValueOnce(new Error("activity storage unavailable")); expect(((await oblienWebhook(makeCtx(body, sign(body), "evt-activity"))) as unknown as JsonResult).status).toBe(503); expect(h.processed.size).toBe(0); diff --git a/apps/api/src/modules/cloud/cloud-pages.service.ts b/apps/api/src/modules/cloud/cloud-pages.service.ts index f2b18387a..9530a4f99 100644 --- a/apps/api/src/modules/cloud/cloud-pages.service.ts +++ b/apps/api/src/modules/cloud/cloud-pages.service.ts @@ -5,7 +5,7 @@ import { authorizeCloudRelayWorkspace } from "./cloud-relay-access"; export async function createCloudPage( ctx: RequestContext, - input: { vm_id: string; path: string; name: string; slug: string; domain?: string }, + input: { workspace_id: string; path: string; name: string; slug: string; domain?: string }, ): Promise { const workspaceId = await authorizeCloudRelayWorkspace(ctx); const namespace = await ensureNamespace(ctx.organizationId, workspaceId); diff --git a/apps/api/src/modules/cloud/cloud-resource.controller.ts b/apps/api/src/modules/cloud/cloud-resource.controller.ts index 34ac7305e..db9cd5e26 100644 --- a/apps/api/src/modules/cloud/cloud-resource.controller.ts +++ b/apps/api/src/modules/cloud/cloud-resource.controller.ts @@ -10,9 +10,9 @@ import { authorizeCloudRelayWorkspace } from "./cloud-relay-access"; const id = z.string().regex(/^[a-zA-Z0-9_-]{1,128}$/); const path = z.string().min(1).max(2048); const domain = z.string().min(1).max(253); -const source = z.object({ vm_id: id, path }).strict(); +const source = z.object({ workspace_id: id, path }).strict(); const action = z.discriminatedUnion("kind", [ - z.object({ kind: z.literal("proxy"), vm: id, port: z.number().int().min(1).max(65535), + z.object({ kind: z.literal("proxy"), workspace: id, port: z.number().int().min(1).max(65535), stripPrefix: z.boolean().optional(), path: path.optional() }).strict(), z.object({ kind: z.literal("rewrite"), to: path }).strict(), z.object({ kind: z.literal("redirect"), to: path, status: z.union([z.literal(301), z.literal(302), z.literal(307), z.literal(308)]).optional() }).strict(), diff --git a/apps/api/src/modules/cloud/cloud-saas.controller.ts b/apps/api/src/modules/cloud/cloud-saas.controller.ts index 10adfda66..03810ef70 100644 --- a/apps/api/src/modules/cloud/cloud-saas.controller.ts +++ b/apps/api/src/modules/cloud/cloud-saas.controller.ts @@ -635,11 +635,11 @@ export async function checkEdgeVerification(c: Context) { // ─── Pages proxy ──────────────────────────────────────────────────────────── /** - * POST /api/cloud/pages { vm_id, path, name, slug, domain? } + * POST /api/cloud/pages { workspace_id, path, name, slug, domain? } * * Forwards to Oblien with the caller's namespace token. Oblien * enforces: - * - `vm_id` must belong to the caller's namespace (or 404) + * - `workspace_id` must belong to the caller's namespace (or 404) * - `slug` must be free on the shared zone (or 409 SLUG_TAKEN) * * Returns the raw Oblien SDK shape so the caller's infrastructure adapter @@ -648,18 +648,18 @@ export async function checkEdgeVerification(c: Context) { export async function pagesProxy(c: Context) { const ctx = getRequestContext(c); const body = await c.req.json<{ - vm_id?: string; + workspace_id?: string; path?: string; name?: string; slug?: string; domain?: string; }>(); - if (!body.vm_id || !body.path || !body.name || !body.slug) { - return c.json({ error: "vm_id, path, name and slug are required" }, 400); + if (!body.workspace_id || !body.path || !body.name || !body.slug) { + return c.json({ error: "workspace_id, path, name and slug are required" }, 400); } try { const result = await createCloudPage(ctx, { - vm_id: body.vm_id, + workspace_id: body.workspace_id, path: body.path, name: body.name, slug: body.slug, diff --git a/apps/api/src/modules/deployments/cancel-is-final.test.ts b/apps/api/src/modules/deployments/cancel-is-final.test.ts index 062a62169..841363250 100644 --- a/apps/api/src/modules/deployments/cancel-is-final.test.ts +++ b/apps/api/src/modules/deployments/cancel-is-final.test.ts @@ -43,6 +43,7 @@ vi.mock("@repo/platform/engine/modules/projects/cleanup-keep-set", () => ({ // Terminal-event side channels, each of which drags in auth/github/mail wiring. vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: mocks.notify } })); vi.mock("../../lib/audit", () => ({ audit: { recordAsync: vi.fn(), record: vi.fn() } })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn(async () => {}) })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(async () => {}), })); diff --git a/apps/api/src/modules/deployments/route-issues-warning.test.ts b/apps/api/src/modules/deployments/route-issues-warning.test.ts index 662d10f40..ef824d981 100644 --- a/apps/api/src/modules/deployments/route-issues-warning.test.ts +++ b/apps/api/src/modules/deployments/route-issues-warning.test.ts @@ -1,11 +1,12 @@ import { describe, expect, it, vi } from "vitest"; // The function under test is pure; everything else this module reaches (DB, SSE, -// notifications) is a side effect the assertion doesn't want. +// notifications, favicon probing) is a side effect the assertion doesn't want. // `@repo/adapters` stays REAL — `isEdgeDownMessage` is the branch being pinned. vi.mock("@repo/db", () => ({ repos: {} })); vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: {} })); vi.mock("../../lib/audit", () => ({ audit: {} })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn() })); vi.mock("@repo/platform/engine/modules/deployments/session-manager", () => ({})); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(), diff --git a/apps/api/src/modules/domains/routing-apply.service.test.ts b/apps/api/src/modules/domains/routing-apply.service.test.ts index c63228aff..c3a3b8933 100644 --- a/apps/api/src/modules/domains/routing-apply.service.test.ts +++ b/apps/api/src/modules/domains/routing-apply.service.test.ts @@ -132,7 +132,7 @@ describe("Cloud Docker route tables", () => { } as Record )[`${container}:${port}`]; if (!published) throw new Error("service port is not published"); - return { vm: "shared-vm", port: published }; + return { workspace: "shared-vm", port: published }; }); }); it("repairs an existing single static container route without rebuilding", async () => { @@ -149,7 +149,7 @@ describe("Cloud Docker route tables", () => { }; domainRepo.listByProject.mockResolvedValue([savedDomain]); domainRepo.findByHostname.mockResolvedValue(savedDomain); - target.mockResolvedValue({ vm: "shared-vm", port: 30000 }); + target.mockResolvedValue({ workspace: "shared-vm", port: 30000 }); await applyCloudRouting({ project: { ...base, workloadType: "static", hasServer: false, port: 3000 } as never, deployment: { @@ -186,9 +186,9 @@ describe("Cloud Docker route tables", () => { ["stack-api.opsh.io", 30003, false], ]); expect(publish.mock.calls.map((call) => call[3].routes[0].action)).toEqual([ - { kind: "proxy", vm: "shared-vm", port: 30001 }, - { kind: "proxy", vm: "shared-vm", port: 30002 }, - { kind: "proxy", vm: "shared-vm", port: 30003 }, + { kind: "proxy", workspace: "shared-vm", port: 30001 }, + { kind: "proxy", workspace: "shared-vm", port: 30002 }, + { kind: "proxy", workspace: "shared-vm", port: 30003 }, ]); }); it("resolves project-level domains to their service's exact published port", async () => { @@ -209,7 +209,7 @@ describe("Cloud Docker route tables", () => { expect.objectContaining({ routes: [ expect.objectContaining({ - action: { kind: "proxy", vm: "shared-vm", port: 30002 }, + action: { kind: "proxy", workspace: "shared-vm", port: 30002 }, }), ], }), @@ -235,15 +235,15 @@ describe("Cloud Docker route tables", () => { expect(writes[0]![3].routes).toEqual([ { match: { path: "/api/status", type: "exact" }, - action: { kind: "proxy", vm: "shared-vm", port: 30001 }, + action: { kind: "proxy", workspace: "shared-vm", port: 30001 }, }, { match: { path: "/api/", type: "prefix" }, - action: { kind: "proxy", vm: "shared-vm", port: 30003 }, + action: { kind: "proxy", workspace: "shared-vm", port: 30003 }, }, { match: { path: "/", type: "prefix" }, - action: { kind: "proxy", vm: "shared-vm", port: 30001 }, + action: { kind: "proxy", workspace: "shared-vm", port: 30001 }, }, ]); }); @@ -259,7 +259,7 @@ describe("Cloud Docker route tables", () => { }], }); expect(publish).toHaveBeenCalledWith("api.onvo.me", undefined, true, { - routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", vm: "shared-vm", port: 30003 } }], + routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", workspace: "shared-vm", port: 30003 } }], }); }); it("keeps the old composite table if any path target is missing, while updating other hosts", async () => { @@ -296,11 +296,11 @@ describe("Cloud Docker route tables", () => { expect(rules).toEqual([ { match: { path: "/api/", type: "prefix" }, - action: { kind: "proxy", vm: "shared-vm", port: 30003 }, + action: { kind: "proxy", workspace: "shared-vm", port: 30003 }, }, { match: { path: "/", type: "prefix" }, - action: { kind: "proxy", vm: "shared-vm", port: 30001 }, + action: { kind: "proxy", workspace: "shared-vm", port: 30001 }, }, ]); }); diff --git a/apps/api/src/modules/images/images.service.ts b/apps/api/src/modules/images/images.service.ts index 6b24ab6c9..b62749d95 100644 --- a/apps/api/src/modules/images/images.service.ts +++ b/apps/api/src/modules/images/images.service.ts @@ -91,7 +91,7 @@ export async function listImages( if (hit) return hit; const client = await getClientForOrg(organizationId); - const response = await client.vms.images.list(params); + const response = await client.workspaces.images.list(params); const images = normalizeImages(response); await store.set(key, images, CACHE_TTL_S); return images; diff --git a/apps/api/src/modules/mcp/mcp-tools.ts b/apps/api/src/modules/mcp/mcp-tools.ts index 12cf298e5..737e8e1fe 100644 --- a/apps/api/src/modules/mcp/mcp-tools.ts +++ b/apps/api/src/modules/mcp/mcp-tools.ts @@ -42,7 +42,7 @@ export interface McpToolDef { name: string; description: string; inputSchema: Record; - annotations: { readOnlyHint: boolean; destructiveHint: boolean; openWorldHint: boolean }; + annotations: { readOnlyHint: boolean; destructiveHint: boolean }; // Dispatch metadata (not sent to the client): method: string; path: string; // full path with :params, e.g. /api/projects/:id @@ -76,8 +76,6 @@ export interface McpPrincipal { /** Resolved with the same persisted instance-authority policy as HTTP calls. */ instanceAdmin?: boolean; role: "owner" | "admin" | "member" | "restricted"; - /** For scoped tokens, the current membership in their bound organization. */ - membershipRole?: "owner" | "admin" | "member" | "restricted"; readOnly: boolean; /** Resource types the token holds grants on — only consulted when role === "restricted". */ grantedRootTypes: ReadonlySet; @@ -186,12 +184,9 @@ function inputSchema( function annotationsFor(route: RegisteredRoute): { readOnlyHint: boolean; destructiveHint: boolean; - openWorldHint: boolean; } { const spec = route.spec; - if (isPublicSpec(spec)) { - return { readOnlyHint: true, destructiveHint: false, openWorldHint: true }; - } + if (isPublicSpec(spec)) return { readOnlyHint: true, destructiveHint: false }; const parsed = parsePermissionTag(spec.tag); const readOnlyHint = route.method === "GET" || spec.readOnly === true; const destructiveHint = @@ -200,7 +195,7 @@ function annotationsFor(route: RegisteredRoute): { (route.method === "DELETE" || parsed.action === "admin" || /delete|teardown|destroy|remove|wipe|revoke/i.test(route.path))); - return { readOnlyHint, destructiveHint, openWorldHint: spec.mcp?.openWorld ?? true }; + return { readOnlyHint, destructiveHint }; } let cached: McpToolDef[] | null = null; @@ -355,10 +350,6 @@ export function filterToolsForPrincipal( principal: McpPrincipal, ): McpToolDef[] { return tools.filter((t) => { - const action = assertedAction(t.perm.action); - const role = principal.membershipRole ?? principal.role; - if (role !== "restricted" && - !roleAllowsResourceType(role, t.perm.leaf as CheckedResourceType, action)) return false; // Read-only tokens can only call GET — the runtime gate rejects mutations by // HTTP method, so mirror that exactly rather than guessing from the tag. if (principal.readOnly && t.method !== "GET") return false; @@ -382,7 +373,9 @@ export function filterToolsForPrincipal( if (principal.role === "restricted" && !caps?.has(needed)) return false; } - if (principal.role !== "restricted") return true; + if (principal.role !== "restricted") { + return roleAllowsResourceType(principal.role, t.perm.leaf as CheckedResourceType); + } // "Own projects" scope: the create-capable project wildcard grant reaches the // dedicated create routes (POST /projects, POST /apps) and the project list // (which the caller filters to its self-created projects). Checked before the @@ -408,11 +401,11 @@ export function filterToolsForPrincipal( // A per-id grant still fails here, correctly: `wildcardGrants` holds only // resourceId "*" rows. const held = principal.wildcardGrants.get(t.perm.leaf); - return held ? permitsAction(held, action) : false; + return held ? permitsAction(held, assertedAction(t.perm.action)) : false; } if (principalHasGrantFor(principal.grantedRootTypes, t.perm.grantRoot)) return true; // Same mapping the permission check uses: `domain:admin` ⇒ `domains:delete`. - const capability = capabilityFor(t.perm.leaf, action); + const capability = capabilityFor(t.perm.leaf, assertedAction(t.perm.action)); return !!capability && !!principal.grantedCapabilities?.has(capability); }); } @@ -426,7 +419,6 @@ export function toClientTool(t: McpToolDef) { annotations: { readOnlyHint: t.annotations.readOnlyHint, destructiveHint: t.annotations.destructiveHint, - openWorldHint: t.annotations.openWorldHint, }, }; } diff --git a/apps/api/src/modules/mcp/mcp.routes.ts b/apps/api/src/modules/mcp/mcp.routes.ts index 16d90eab1..9a80ecf68 100644 --- a/apps/api/src/modules/mcp/mcp.routes.ts +++ b/apps/api/src/modules/mcp/mcp.routes.ts @@ -128,7 +128,6 @@ async function resolveMcpCaller(token: string, headers: Headers): Promise { { 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.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.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.services[0].environment.PGHOST).toBe( privatePlan.services[0].create.internalAlias, ); @@ -186,109 +182,29 @@ 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.projects[0].create.services?.flatMap((service) => service.volumes ?? [])).toEqual([ + expect(plan.project.services?.flatMap((service) => service.volumes ?? [])).toEqual([ "database-data-0:/var/lib/postgresql/data", "website-data-0:/data", ]); - expect(plan.projects[0].create.services?.[1].dependsOn).toEqual(["database"]); + expect(plan.project.services?.[1].dependsOn).toEqual(["database"]); }); - it.each(["repository", "commit", "branch"])( - "splits incompatible Git %s without losing revisions or private connections", - async (difference) => { - inventory.services = ["one", "two"].map((id) => - service({ - id, - name: id, - image: undefined, - repository: difference === "repository" ? `owner/${id}` : "owner/repo", - commit: (difference === "commit" && id === "two" ? "b" : "a").repeat(40), - branch: difference === "branch" ? id : "main", - privateDomain: `${id}.railway.internal`, - env: id === "two" ? { API_URL: "http://one.railway.internal:3000/api?secret=keep" } : {}, - }), - ); - const result = await review( - inventory.services.map((service) => ({ - id: service.id, - name: service.name, - data: "empty", - })), - ); - expect(result.ready, JSON.stringify(result)).toBe(true); - expect(result.projects).toEqual([ - { name: "project-one", serviceIds: ["one"] }, - { name: "project-two", serviceIds: ["two"] }, - ]); - const plan = await loadReviewedImport(ctx, result.planId); - expect(plan.projects.map((project) => project.create.gitRepo)).toEqual( - difference === "repository" ? ["one", "two"] : ["repo", "repo"], - ); - expect(plan.services[1].bindings).toEqual([ - { - sourceId: "one", - envKey: "API_URL", - valueTemplate: "http://${host}:3000/api?secret=keep", - }, - ]); - expect(plan.services.map((s) => s.source.commit)).toEqual( - inventory.services.map((s) => s.commit), - ); - expect(h.info.mock.calls.map(([input]) => input.owner)).toEqual(["owner", "owner"]); - expect(h.info.mock.calls.map(([input]) => input.branch)).toEqual( - inventory.services.map((s) => s.commit), - ); - }, - ); - it("keeps compatible source services together and rejects composite cross-project variables during review", async () => { - const git = (id: string, repository: string) => + it("blocks incompatible Git sources instead of splitting the source project", async () => { + inventory.services = ["one", "two"].map((id) => service({ id, name: id, image: undefined, - repository, + repository: `owner/${id}`, commit: "a".repeat(40), - privateDomain: `${id}.railway.internal`, - }); - inventory.services = [git("one", "owner/repo"), git("two", "owner/repo")]; - const choices = () => - inventory.services.map((s) => ({ id: s.id, name: s.name, data: "empty" as const })); - expect((await review(choices())).projects).toEqual([ - { name: "Project", serviceIds: ["one", "two"] }, - ]); - inventory.services.push(git("three", "owner/other")); - inventory.services[2].env = { HOSTS: "one.railway.internal,two.railway.internal" }; - const result = await review(choices()); - expect(result.ready).toBe(false); - expect(result.services[2].blockers.join(" ")).toContain("separate connection variable"); - }); - it("blocks unavailable private listeners and ambiguous host templates before source downtime", async () => { - inventory.services = [ - service({ - id: "store", - name: "store", - port: undefined, - privateDomain: "store.railway.internal", }), - ...["one", "two"].map((id) => - service({ - id, - name: id, - image: undefined, - repository: `owner/${id}`, - commit: "a".repeat(40), - env: - id === "one" - ? { HOST: "store.railway.internal" } - : { HOST: "store.railway.internal-${host}" }, - }), - ), - ]; + ); const result = await review( - inventory.services.map((s) => ({ id: s.id, name: s.name, data: "empty" })), + inventory.services.map((service) => ({ id: service.id, name: service.name, data: "empty" })), ); expect(result.ready).toBe(false); - expect(result.services[1].blockers.join(" ")).toContain("private listener port"); - expect(result.services[2].blockers.join(" ")).toContain("cannot be safely converted"); + expect(result.services.flatMap((service) => service.blockers).join(" ")).toContain( + "one Git source", + ); }); it("ignores pagination order and changing volume size, but never ignores changed configuration", () => { const next = structuredClone(inventory); @@ -402,9 +318,7 @@ it("uses the existing Compose build for a custom Dockerfile and preserves readin readiness: { path: "/health" }, services: [{ build: "apps/api", dockerfile: "docker/production.Dockerfile" }], }); - expect(plan.projects[0].create.services?.[0].advanced).toMatchObject({ - readiness: { path: "/health", port: 3000 }, - }); + expect(plan.project.services?.[0].advanced).toMatchObject({ readiness: { path: "/health", port: 3000 } }); expect(h.info).not.toHaveBeenCalled(); }); it("blocks an unavailable custom Dockerfile before import", async () => { diff --git a/apps/api/src/modules/migration/platform-import-worker.test.ts b/apps/api/src/modules/migration/platform-import-worker.test.ts index 446bd3f5c..f932056a4 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 { platformImportProjects } from "@repo/platform/engine/modules/migration/platform-import-project"; +import { platformImportProject } from "@repo/platform/engine/modules/migration/platform-import-project"; const h = vi.hoisted(() => ({ ensure: vi.fn(), merge: vi.fn(), @@ -15,7 +15,6 @@ 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(), @@ -59,9 +58,6 @@ vi.mock("@repo/platform/engine/modules/projects/project-runtime.service", () => vi.mock("@repo/platform/engine/modules/apps/app-settings.service", () => ({ getAppConnectionView: h.view, })); -vi.mock("@repo/platform/engine/modules/projects/project-connection.service", () => ({ - createConnection: h.connect, -})); vi.mock("@repo/platform/engine/modules/deployments/build.service", () => ({ triggerDeployment: h.deploy, })); @@ -124,8 +120,7 @@ const planFor = (services: PlannedImportService[]) => userId: "user", targetServerId: "server", services, - projectName: "imported-project", - projects: platformImportProjects("imported-project", "server", services), + project: platformImportProject("imported-project", "server", services), }) as PrivateImportPlan; let row: any; beforeEach(() => { @@ -188,9 +183,6 @@ 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, @@ -203,95 +195,6 @@ const lifecycle = (signal = new AbortController().signal) => ({ }), }); describe("provider import through normal project operations", () => { - it("copies all volumes before deploying multiple repositories in dependency order with native links", async () => { - const db = service("db", "database"), - app = service("app", "app"), - worker = service("worker", "worker"); - for (const entry of [app, worker]) - Object.assign(entry.create, { - gitProvider: "github", - gitOwner: "owner", - gitRepo: entry.source.id, - gitBranch: "main", - }); - worker.source.commit = "b".repeat(40); - app.bindings = [ - { sourceId: "db", envKey: "DB_URL", valueTemplate: "postgres://secret@${host}:5432/store" }, - ]; - worker.bindings = [{ sourceId: "app", envKey: "APP_HOST", valueTemplate: "${host}" }]; - app.environment.DB_URL = "postgres://secret@db:5432/store"; - worker.environment.APP_HOST = "app"; - const services = [worker, app, db]; - const plan = { ...planFor(services), sourceControl: "railway-project" as const }; - await executePlatformImport(ctx, "run", plan, lifecycle()); - expect(h.ensure.mock.calls.map(([body]) => body.gitRepo)).toEqual(["worker", "app", undefined]); - expect( - h.ensure.mock.calls.every(([body]) => body.services.every((s: any) => !s.dependsOn.length)), - ).toBe(true); - expect(h.copy.mock.calls.map(([input]) => [input.projectId, input.serviceId])).toEqual([ - ["imported-project-db", "imported-project-db-db"], - ["imported-project-app", "imported-project-app-app"], - ["imported-project-worker", "imported-project-worker-worker"], - ]); - expect(h.events.indexOf("copy:worker")).toBeLessThan( - h.events.indexOf("deploy:imported-project-db:1"), - ); - expect(h.events.indexOf("healthy:imported-project-db-build-1")).toBeLessThan( - h.events.indexOf("connect:imported-project-db:imported-project-app"), - ); - expect(h.events.indexOf("connect:imported-project-db:imported-project-app")).toBeLessThan( - h.events.indexOf("deploy:imported-project-app:1"), - ); - expect(h.connect).toHaveBeenCalledWith( - ctx, - "imported-project-app", - { - sourceProjectId: "imported-project-db", - outputId: "imported-project-db-db:url", - envKey: "DB_URL", - mode: "internal", - valueTemplate: "postgres://secret@${host}:5432/store", - }, - { defer: true }, - ); - expect( - h.merge.mock.calls.flatMap(([, , , input]) => input.upserts.map((v: any) => v.key)), - ).not.toContain("DB_URL"); - expect(h.deploy.mock.calls.map(([, input]) => [input.projectId, input.commitSha])).toEqual([ - ["imported-project-db", undefined], - ["imported-project-app", "a".repeat(40)], - ["imported-project-worker", "b".repeat(40)], - ]); - expect(h.verify).toHaveBeenCalledTimes(3); - expect(row.recovery.providerImport.completed).toEqual(["db", "app", "worker"]); - }); - it("does not start a cross-project consumer if its private connection fails", async () => { - const db = service("db", "database"), - app = service("app", "app"), - worker = service("worker", "worker"); - for (const entry of [app, worker]) - Object.assign(entry.create, { gitOwner: "owner", gitRepo: entry.source.id }); - app.bindings = [{ sourceId: "db", envKey: "DB_URL" }]; - const plan = { ...planFor([app, db, worker]), sourceControl: "railway-project" as const }; - row.recovery.providerImport.planEnc = JSON.stringify(plan); - h.connect.mockRejectedValue(new Error("Private network unavailable")); - await expect(executePlatformImport(ctx, "run", plan, lifecycle())).rejects.toThrow( - "Private network unavailable", - ); - expect(h.deploy).toHaveBeenCalledTimes(1); - expect(row.recovery.providerImport.completed).toEqual([]); - expect(h.restoreSource).not.toHaveBeenCalledWith("run", true, expect.anything()); - await pauseFailedPlatformImport("run"); - expect(h.disable).toHaveBeenCalledExactlyOnceWith( - "imported-project-db", - "org", - "imported-project-db-build-1", - ); - expect(h.restoreSource).toHaveBeenLastCalledWith("run", true); - expect(h.disable.mock.invocationCallOrder[0]).toBeLessThan( - h.restoreSource.mock.invocationCallOrder[1], - ); - }); it("stages custom domains through native migration routing before pausing the source", async () => { const web = service("web", "app"); web.create.name = "storefront"; @@ -396,8 +299,7 @@ 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.projectName = name; - plan.projects[0].create.name = name; + plan.project.name = name; await executePlatformImport(ctx, name, plan, lifecycle()); expect(new Set(Object.values(row.recovery.providerImport.projects))).toEqual(new Set([name])); } @@ -477,9 +379,9 @@ describe("provider import through normal project operations", () => { }), ); }); - it("rejects reviews without destination projects before allocating a destination", async () => { + it("rejects reviews from the old per-service-project flow before allocating a destination", async () => { const plan = planFor([service("app", "app")]); - delete (plan as Partial).projects; + delete (plan as Partial).project; await expect(executePlatformImport(ctx, "run", plan, lifecycle())).rejects.toMatchObject({ code: "IMPORT_REVIEW_EXPIRED", }); @@ -545,7 +447,7 @@ describe("provider import through normal project operations", () => { "deploy:imported-project:3", "healthy:imported-project-build-2", ]); - expect(h.ensure).toHaveBeenCalledExactlyOnceWith(plan.projects[0].create, "org", ctx, { + expect(h.ensure).toHaveBeenCalledExactlyOnceWith(plan.project, "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 d21c42e47..b7b45588a 100644 --- a/apps/api/src/modules/migration/railway-wiring.test.ts +++ b/apps/api/src/modules/migration/railway-wiring.test.ts @@ -42,27 +42,6 @@ describe("provider-independent connection values", () => { }); }); describe("Railway project wiring", () => { - it("preserves self references and repeated case-insensitive dependency hosts in one connection", () => { - const db = service("db", {}, 5432); - const app = service("app", { - HOSTS: "DB.railway.internal,db.railway.internal,app.railway.internal", - }); - expect( - resolveRailwayBindings( - app, - new Map([ - ["db", db], - ["app", app], - ]), - ), - ).toEqual([ - { - sourceId: "db", - envKey: "HOSTS", - valueTemplate: "${host},${host},import-app", - }, - ]); - }); it("binds any private service without inferring its type from its image or variable names", () => { const store = service("store"); const app = service("app", { @@ -79,7 +58,6 @@ 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 ac85c40ac..02b956160 100644 --- a/apps/api/src/modules/projects/folder/folder.service.test.ts +++ b/apps/api/src/modules/projects/folder/folder.service.test.ts @@ -59,7 +59,7 @@ describe("scanFolderSession", () => { expect(resolveFromLocalMock).toHaveBeenCalledWith(stagingDir, { env: { MY_VERSION: "1.2.3" }, composePath: "deploy/compose.yaml", - }, "app"); + }); expect(result.services).toBe(refreshed); expect(upload.services).toBe(initial); }); diff --git a/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts b/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts index ef4088610..f66e072ba 100644 --- a/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts +++ b/apps/api/src/modules/projects/project-cleanup.ref-shape.test.ts @@ -225,7 +225,7 @@ describe("Cloud Docker project teardown", () => { slug, domain: "opsh.io", namespace: fixture.namespace, - source_vm_id: fixture.scope.workspaceId, + source_workspace_id: fixture.scope.workspaceId, exported_path: `${cloudDockerProjectPaths(owner).routes}/${slug}`, }); return { ...fixture, addPage }; diff --git a/apps/api/src/modules/projects/project-clone.test.ts b/apps/api/src/modules/projects/project-clone.test.ts index 864a94be8..497aa8279 100644 --- a/apps/api/src/modules/projects/project-clone.test.ts +++ b/apps/api/src/modules/projects/project-clone.test.ts @@ -32,7 +32,8 @@ const h = { deletedAt: null, deletionInProgress: false, lifecycleOperation: { kind: "delete", status: "failed", error: "Previous cleanup failure" }, - iconUrl: "https://clincai.example/icon.png", + favicon: "https://clincai.example/favicon.ico", + faviconCheckedAt: new Date(), compositeRoutes: [{ host: "clincai.example" }], workspaceId: null, gitProvider: "github", @@ -193,7 +194,6 @@ describe("the copy direction is COPY-by-default", () => { await clone(); const p = clonedProject(); expect(p.framework).toBe("nextjs"); - expect(p.iconUrl).toBe("https://clincai.example/icon.png"); expect(p.routeStrategy).toBe("loopback"); expect(p.rollbackWindow).toBe(5); // Same for the service rows: a build command exists in no container. @@ -231,7 +231,7 @@ describe("what it deliberately does NOT copy", () => { const p = clonedProject(); // `id`/`groupId` are the insert's, and name/slug/serverId/workspaceId/activeDeploymentId are set // explicitly above — the rest must simply be absent. - for (const field of ["deletedAt", "deletionInProgress", "lifecycleOperation", "disabledAt", "compositeRoutes", "cloudPromotion", "id", "groupId", "createdAt", "updatedAt"]) { + for (const field of ["deletedAt", "deletionInProgress", "lifecycleOperation", "disabledAt", "favicon", "faviconCheckedAt", "compositeRoutes", "cloudPromotion", "id", "groupId", "createdAt", "updatedAt"]) { expect(p, field).not.toHaveProperty(field); } }); diff --git a/apps/api/src/modules/system/setup.controller.ts b/apps/api/src/modules/system/setup.controller.ts index 4770e16f6..47a90997f 100644 --- a/apps/api/src/modules/system/setup.controller.ts +++ b/apps/api/src/modules/system/setup.controller.ts @@ -356,7 +356,7 @@ export async function resetAdminPassword(c: Context) { // multi-user box the reset never lands on an arbitrary member row. const admin = await repos.user.findFoundingAdmin(); if (!admin) { - return c.json({ error: "No admin account exists yet — run `openship` and choose Create first admin, or run `openship up --non-interactive --admin-email ` with OPENSHIP_ADMIN_PASSWORD set." }, 409); + return c.json({ error: "No admin account exists yet — run `openship` to create one." }, 409); } const email = diff --git a/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts b/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts index 15bc3624e..e7c29259f 100644 --- a/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts +++ b/apps/api/test/e2e/cloud-shared-workspace.e2e.test.ts @@ -152,13 +152,13 @@ describeDockerE2E("multiple projects on one subscribed Docker workspace", () => }; const vm = { id: providerVm, namespace, status: "running" }; const provider = { - vms: { + workspaces: { get: async () => vm, create: () => { throw new Error("Project operation attempted to create a second host"); }, }, - vm: () => ({ + workspace: () => ({ get: async () => vm, runtime: async () => providerRuntime, workloads: { list: async () => [] }, @@ -185,7 +185,7 @@ describeDockerE2E("multiple projects on one subscribed Docker workspace", () => domain: "opsh.io", url: `https://${input.slug}.opsh.io`, namespace, - source_vm_id: input.vm_id, + source_workspace_id: input.workspace_id, exported_path: input.path, }; pages.set(input.slug, page); @@ -359,7 +359,7 @@ describeDockerE2E("multiple projects on one subscribed Docker workspace", () => ); expect((await a.listAllContainers()).map((row) => row.id)).toEqual([aId]); expect(routes.get(`${ids[0]}.opsh.io`).routes[0].action).toMatchObject({ - vm: providerVm, + workspace: providerVm, port: first.hostPortByContainerPort?.[8080], }); }); diff --git a/apps/api/test/e2e/fixtures/instance-api.ts b/apps/api/test/e2e/fixtures/instance-api.ts index 7bf882126..97f198dea 100644 --- a/apps/api/test/e2e/fixtures/instance-api.ts +++ b/apps/api/test/e2e/fixtures/instance-api.ts @@ -135,7 +135,7 @@ export async function startApi(input: { } export async function stopApi(api: RunningApi): Promise { - if (api.child.exitCode === null && api.child.signalCode === null) { + if (api.child.exitCode === null) { api.child.kill("SIGTERM"); const exited = new Promise((resolve) => api.child.once("exit", () => resolve(true))); if (!(await Promise.race([exited, delay(15_000).then(() => false)]))) { diff --git a/apps/api/test/e2e/instance-handoff.e2e.test.ts b/apps/api/test/e2e/instance-handoff.e2e.test.ts index e39c61903..0bb185c46 100644 --- a/apps/api/test/e2e/instance-handoff.e2e.test.ts +++ b/apps/api/test/e2e/instance-handoff.e2e.test.ts @@ -5,7 +5,7 @@ import { createRequire } from "node:module"; import { execFile } from "node:child_process"; import { promisify } from "node:util"; import { afterAll, expect, it } from "vitest"; -import { createServer, request as httpRequest, type Server } from "node:http"; +import { createServer, type Server } from "node:http"; import { createHmac } from "node:crypto"; import { freePort, startApi, stopApi, jsonRequest, type RunningApi } from "./fixtures/instance-api"; import type { DataTransferFile } from "../../src/modules/system/data-transfer/types"; @@ -433,47 +433,6 @@ it("resumes after a lost activation acknowledgement without reimporting or start ).toBe(newer.id); }, 120_000); -it.each(["resume", "cancel"] as const)("recovers a persisted quiescing source after restart with %s", async action => { - const { source, target } = await pair(); - const original = await createProject(source, "Before interrupted drain"); - const offer = await post<{ code: string }>(target, "/api/system/instance/offer", { direction: "target" }); - // A real admitted mutation waits for its remaining request body. The move must - // keep waiting for it, rather than treating an incomplete drain as a snapshot. - const held = httpRequest(`${source.baseUrl}/api/projects`, { - method: "POST", headers: { "content-type": "application/json" }, - }); - held.on("error", () => { /* The fixture intentionally interrupts this request. */ }); - held.write('{"name":'); - let restarted: RunningApi | undefined; - try { - await post(source, "/api/system/instance/move", { code: offer.code, confirmReplace: true }); - await expect.poll(async () => (await state(source)).role, { timeout: 15_000 }).toBe("quiescing"); - const exited = new Promise(resolve => source.child.once("exit", () => resolve())); - source.child.kill("SIGKILL"); // simulate a crash after the durable fence - await exited; - held.destroy(); - restarted = await startApi({ dbDir: source.dbDir, port: source.port, secret: source.secret }); - apis.push(restarted); - expect(await state(restarted)).toMatchObject({ role: "quiescing", handoff: { running: false } }); - expect((await fetch(`${restarted.baseUrl}/api/health`)).status).toBe(200); - expect((await fetch(`${restarted.baseUrl}/api/projects`)).status).toBe(503); - await post(restarted, `/api/system/instance/${action}`); - if (action === "resume") { - await waitMove(restarted); - expect((await state(target)).role).toBe("active"); - expect((await jsonRequest<{ data: { id: string } }>(target.baseUrl, `/api/projects/${original.id}`)).data.id).toBe(original.id); - } else { - expect(await state(restarted)).toMatchObject({ role: "active", handoff: { status: "aborted" } }); - expect((await jsonRequest<{ data: { id: string } }>(restarted.baseUrl, `/api/projects/${original.id}`)).data.id).toBe(original.id); - } - } finally { - held.destroy(); - await stopApi(source); - await stopApi(target); - if (restarted) await stopApi(restarted); - } -}, 120_000); - it("cancels a prepared but unactivated receiver and restores its recovery archive", async () => { const { source, target } = await pair(); const old = await createProject(target, "Receiver original"); diff --git a/apps/api/test/e2e/platform-import-project.e2e.test.ts b/apps/api/test/e2e/platform-import-project.e2e.test.ts index b8de6a4ca..e90c76343 100644 --- a/apps/api/test/e2e/platform-import-project.e2e.test.ts +++ b/apps/api/test/e2e/platform-import-project.e2e.test.ts @@ -3,9 +3,6 @@ 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, @@ -23,14 +20,8 @@ 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, Git checkout, destination resolution -// and the asynchronous build queue. All runtime operations use an isolated daemon. +// Substitute Railway's control/SSH boundary and the asynchronous build queue. // Review, project creation, encrypted environments, migration checkpoints, // volume transfer and the ordinary Compose deployment engine remain real. const h = vi.hoisted(() => ({ @@ -59,18 +50,9 @@ 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, @@ -82,8 +64,6 @@ 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; @@ -127,13 +107,11 @@ 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(); }); @@ -150,14 +128,9 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { return container.id; } - it.each([ - { transport: "socket", split: false }, - { transport: "cloud", split: false }, - { transport: "socket", split: true }, - { transport: "cloud", split: true }, - ] as const)( - "imports through $transport (multiple repositories: $split), isolating DNS, env and persisted data", - async ({ transport, split }) => { + it.each(["socket", "cloud"] as const)( + "imports two three-service projects through %s, isolating DNS, env and persisted data", + async (transport) => { const owner = await seedOrg({ ownsHost: true }); const ctx = { ...owner, @@ -165,7 +138,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}-${split}`; + const serverId = `${tag}-${transport}`; await db.insert(schema.servers).values({ id: serverId, organizationId: owner.organizationId, @@ -238,40 +211,6 @@ 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", @@ -288,7 +227,7 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { ? await openRuntime() : await CloudDockerRuntime.forWorkspace( { - vms: { + workspaces: { get: async () => ({ id: serverId, namespace: owner.organizationId, @@ -314,8 +253,7 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { { executor: null, localHost: false, - preparedLocalImages, - builtImages, + preparedLocalImages: new Map(services.map((s) => [s.id, s.image!])), targetServiceIds: new Set(input.serviceIds), }, ); @@ -331,7 +269,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}-${split}-${projectNumber}`; + const marker = `${tag}-${transport}-${projectNumber}`; const services: ProviderInventory["services"] = []; for (const name of ["db", "cache"]) { const id = `${marker}-${name}`; @@ -394,19 +332,6 @@ 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" }, @@ -454,26 +379,21 @@ 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(split ? 3 : 1); + expect(ids).toHaveLength(1); + const id = ids[0]; + expect(await repos.service.listByProject(id)).toHaveLength(3); expect(checkpoint.completed).toHaveLength(3); expect((await repos.project.listByOrganization(owner.organizationId)).total).toBe( - projectNumber * (split ? 3 : 1), + projectNumber, ); - 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 }); - } + expect(await repos.project.getEnvMap(id, "production", null)).toEqual({}); + imported.push({ id, marker }); } // Check both projects AFTER the second import: duplicate service names @@ -487,12 +407,6 @@ 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([ @@ -509,50 +423,13 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { ), ).toBe(true); expect(await exec(container, "wget -qO- http://127.0.0.1:8080")).toBe("ready"); - if (!split) expect(await exec(container, 'printf %s "$BOTH_HOSTS"')).toBe("db,cache"); - else { - const links = await repos.projectConnection.listByTarget(id); - expect(links).toHaveLength(2); - expect( - links.every( - (link) => - link.organizationId === owner.organizationId && - link.mode === "internal" && - link.usesPrivateNetwork, - ), - ).toBe(true); - for (const link of links) { - expect(env[link.envKey]).toBeUndefined(); // Service env must not shadow its native link. - expect(await exec(container, `printenv ${link.envKey}`)).toBe( - sharedServiceAlias(link.sourceServiceId!), - ); - } - } + expect(await exec(container, 'printf %s "$BOTH_HOSTS"')).toBe("db,cache"); 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 78cf91b65..1e937f0cf 100644 --- a/apps/api/test/fixtures/oblien-capacity-catalog.json +++ b/apps/api/test/fixtures/oblien-capacity-catalog.json @@ -56,12 +56,12 @@ "vcpus": 0.5, "memoryMb": 512, "diskGb": 10, - "vms": 4 + "workspaces": 4 }, "monthlyAmount": 500, "paygCapAmount": 625, "resourceLimits": { - "max_vms": 4, + "max_workspaces": 4, "max_vcpus": 1, "max_ram_mb": 512, "max_disk_gb": 10, @@ -76,12 +76,12 @@ "vcpus": 1, "memoryMb": 1024, "diskGb": 20, - "vms": 8 + "workspaces": 8 }, "monthlyAmount": 800, "paygCapAmount": 1000, "resourceLimits": { - "max_vms": 8, + "max_workspaces": 8, "max_vcpus": 1, "max_ram_mb": 1024, "max_disk_gb": 20, @@ -96,12 +96,12 @@ "vcpus": 2, "memoryMb": 4096, "diskGb": 40, - "vms": 12 + "workspaces": 12 }, "monthlyAmount": 1800, "paygCapAmount": 2250, "resourceLimits": { - "max_vms": 12, + "max_workspaces": 12, "max_vcpus": 2, "max_ram_mb": 4096, "max_disk_gb": 40, @@ -116,12 +116,12 @@ "vcpus": 4, "memoryMb": 8192, "diskGb": 80, - "vms": 24 + "workspaces": 24 }, "monthlyAmount": 3600, "paygCapAmount": 4500, "resourceLimits": { - "max_vms": 24, + "max_workspaces": 24, "max_vcpus": 4, "max_ram_mb": 8192, "max_disk_gb": 80, diff --git a/apps/api/test/helpers/monthly-cloud-offer.ts b/apps/api/test/helpers/monthly-cloud-offer.ts index e55e44596..b95c4cb7c 100644 --- a/apps/api/test/helpers/monthly-cloud-offer.ts +++ b/apps/api/test/helpers/monthly-cloud-offer.ts @@ -1,6 +1,6 @@ import type { OblienEntitlement, OblienSubscription } from "@repo/platform/engine/lib/oblien-billing-api"; -/** OpenShip saved v9 terms, independent of today's catalog and provider wire names. */ +/** Saved v9 terms and the SDK 2.8 capacity shape, independent of today's catalog. */ export function monthlyCloudBilling(organizationId = "org_1", namespace = "os-customer") { const periodStart = "2026-10-01T00:00:00Z"; const periodEnd = "2026-11-01T00:00:00Z"; diff --git a/apps/api/test/helpers/oblien-vm-billing.ts b/apps/api/test/helpers/oblien-vm-billing.ts deleted file mode 100644 index 9f8ea75f9..000000000 --- a/apps/api/test/helpers/oblien-vm-billing.ts +++ /dev/null @@ -1,40 +0,0 @@ -/** Build provider HTTP fixtures from OpenShip's saved billing model. This helper - * is only for fixture construction; production must read native SDK 3 payloads. - * Customer metadata and other opaque dictionaries are deliberately untouched. */ -export function providerBillingFixture(value: unknown): unknown { - if (!value || typeof value !== "object" || Array.isArray(value)) return value; - const source = value as Record; - const native = { ...source }; - if ("vcpus" in source && "memoryMb" in source && "diskGb" in source && "workspaces" in source) { - native.vms = source.workspaces; - delete native.workspaces; - } - if (source.resourceLimits && typeof source.resourceLimits === "object") { - const limits = { ...(source.resourceLimits as Record) }; - if ("max_workspaces" in limits) { - limits.max_vms = limits.max_workspaces; - delete limits.max_workspaces; - } - native.resourceLimits = limits; - } - if (source.onOverdraftAction === "stop_workspaces") native.onOverdraftAction = "stop_vms"; - if (source.service === "workspace_vm") native.service = "vm_compute"; - for (const key of [ - "data", - "capacity", - "quote", - "current", - "next", - "subscription", - "offer", - "policy", - "pendingChange", - "change", - "pendingCheckout", - "checkout", - ]) - if (source[key] && typeof source[key] === "object") - native[key] = providerBillingFixture(source[key]); - if (Array.isArray(source.presets)) native.presets = source.presets.map(providerBillingFixture); - return native; -} diff --git a/apps/api/test/lib/cloud-capacity.test.ts b/apps/api/test/lib/cloud-capacity.test.ts index 621c3145c..4be698883 100644 --- a/apps/api/test/lib/cloud-capacity.test.ts +++ b/apps/api/test/lib/cloud-capacity.test.ts @@ -20,7 +20,7 @@ vi.mock("@repo/db", () => ({ })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ getOblienClient: () => ({ - vms: { get: h.workspace }, + workspaces: { get: h.workspace }, namespaces: { get: h.namespace }, }), })); diff --git a/apps/api/test/lib/cloud-docker-workspace.test.ts b/apps/api/test/lib/cloud-docker-workspace.test.ts index 9e4d1f18b..b2c2cf0cf 100644 --- a/apps/api/test/lib/cloud-docker-workspace.test.ts +++ b/apps/api/test/lib/cloud-docker-workspace.test.ts @@ -30,8 +30,8 @@ vi.mock("@repo/adapters", async (original) => ({ ...await original(), Oblien: class { constructor(credentials: unknown) { h.credentials.push(credentials); } - vms = { create: h.create, retryCreation: h.retry, get: h.get, list: h.list }; - vm = (id: string) => ({ id, get: h.get, start: h.start, resume: h.resume, + workspaces = { create: h.create, retryCreation: h.retry, get: h.get, list: h.list }; + workspace = (id: string) => ({ id, get: h.get, start: h.start, resume: h.resume, lifecycle: { makePermanent: h.permanent }, resources: { update: h.resize }, runtime: async () => ({ exec: { run: h.exec } }), invalidateRuntime: h.invalidate }); }, @@ -86,7 +86,7 @@ beforeEach(() => { return { success: true, relaunched: true }; }); h.inFlight.mockResolvedValue([]); - h.list.mockResolvedValue({ vms: [], total: 0, limit: 100, page: 1 }); + h.list.mockResolvedValue({ workspaces: [], total: 0, limit: 100, page: 1 }); h.discard.mockImplementation(async () => { binding = undefined; }); @@ -190,7 +190,7 @@ describe("Subscribed Cloud server provisioning and retry", () => { it("adopts an earlier workspace discovered after a quota refusal instead of creating another", async () => { binding = { ...input, namespace: "namespace-a", provisionKey: "legacy-key", workspaceId: null, state: "provisioning" }; h.create.mockRejectedValue(Object.assign(new Error("namespace workspace limit"), { status: 409, code: "NAMESPACE_LIMIT_REACHED" })); - h.list.mockResolvedValue({ vms: [await h.get()], total: 1, limit: 100, page: 1 }); + h.list.mockResolvedValue({ workspaces: [await h.get()], total: 1, limit: 100, page: 1 }); await expect(ensureCloudDockerWorkspace(input)).resolves.toEqual({ projectId: project.id, workspaceId: "workspace-a", ownerWorkspaceId: "owner-a" }); expect(h.create).toHaveBeenCalledOnce(); expect(h.discard).not.toHaveBeenCalled(); @@ -209,8 +209,8 @@ describe("Subscribed Cloud server provisioning and retry", () => { binding = { ...input, namespace: "namespace-a", provisionKey: "legacy-key", workspaceId: null, state: "provisioning" }; h.create.mockRejectedValue(Object.assign(new Error("namespace workspace limit"), { status: 409, code: "NAMESPACE_LIMIT_REACHED" })); const workspace = await h.get(); - h.list.mockResolvedValueOnce({ vms: [{ ...workspace, namespace: "other-namespace", id: "foreign-vm" }], total: 2, limit: 1, page: 1 }); - h.list.mockResolvedValueOnce({ vms: [workspace], total: 2, limit: 1, page: 2 }); + h.list.mockResolvedValueOnce({ workspaces: [{ ...workspace, namespace: "other-namespace", id: "foreign-vm" }], total: 2, limit: 1, page: 1 }); + h.list.mockResolvedValueOnce({ workspaces: [workspace], total: 2, limit: 1, page: 2 }); await expect(ensureCloudDockerWorkspace(input)).resolves.toMatchObject({ workspaceId: "workspace-a" }); expect(h.list).toHaveBeenNthCalledWith(2, { page: 2, limit: 100 }); expect(h.attach).toHaveBeenCalledExactlyOnceWith(ownerRef, project.organizationId, "namespace-a", "workspace-a"); @@ -219,7 +219,7 @@ describe("Subscribed Cloud server provisioning and retry", () => { binding = { ...input, namespace: "namespace-a", provisionKey: "legacy-key", workspaceId: null, state: "provisioning" }; h.create.mockRejectedValue(Object.assign(new Error("namespace workspace limit"), { status: 409, code: "NAMESPACE_LIMIT_REACHED" })); const workspace = await h.get(); - h.list.mockResolvedValue({ vms: [workspace, { ...workspace, id: "duplicate-vm" }], total: 2, limit: 100, page: 1 }); + h.list.mockResolvedValue({ workspaces: [workspace, { ...workspace, id: "duplicate-vm" }], total: 2, limit: 100, page: 1 }); await expect(ensureCloudDockerWorkspace(input)).rejects.toThrow("Multiple Cloud servers"); expect(h.attach).not.toHaveBeenCalled(); expect(h.discard).not.toHaveBeenCalled(); @@ -288,7 +288,7 @@ describe("Subscribed Cloud server provisioning and retry", () => { const error = Object.assign(new Error("initial provisioning failed"), { status: 422, code: "CREATE_FAILED", - details: { vm_id: "workspace-a" }, + details: { workspace_id: "workspace-a" }, }); h.create.mockRejectedValueOnce(error); await expect(ensureCloudDockerWorkspace(input)).rejects.toBe(error); @@ -328,7 +328,7 @@ describe("Subscribed Cloud server provisioning and retry", () => { h.create.mockRejectedValueOnce( Object.assign(new Error("creation failed"), { status: 422, - details: { vm_id: "workspace-a" }, + details: { workspace_id: "workspace-a" }, }), ); const created = await h.get(); diff --git a/apps/api/test/lib/cloud-namespace-token-reuse.test.ts b/apps/api/test/lib/cloud-namespace-token-reuse.test.ts index f5623dd04..c27c36e3b 100644 --- a/apps/api/test/lib/cloud-namespace-token-reuse.test.ts +++ b/apps/api/test/lib/cloud-namespace-token-reuse.test.ts @@ -98,7 +98,7 @@ it("renews expiring credentials once across concurrent clients", async () => { ]); vi.setSystemTime(Date.now() + 1741_000); await Promise.all( - clients.map(({ client }) => client._http.request({ method: "GET", path: "/vms" })), + clients.map(({ client }) => client._http.request({ method: "GET", path: "/workspace" })), ); expect(h.mint).toHaveBeenCalledTimes(2); expect(fetcher.mock.calls).toHaveLength(2); @@ -111,12 +111,12 @@ it("evicts rejected credentials without replaying a mutation", async () => { .mockImplementation(async () => Response.json({ success: true })); vi.stubGlobal("fetch", fetcher); const { client } = await getNamespaceClient("org", "space"); - await expect(client._http.request({ method: "POST", path: "/vms" })).rejects.toMatchObject({ + await expect(client._http.request({ method: "POST", path: "/workspace" })).rejects.toMatchObject({ status: 401, }); expect(fetcher).toHaveBeenCalledTimes(1); const next = await getNamespaceClient("org", "space"); - await next.client._http.request({ method: "GET", path: "/vms" }); + await next.client._http.request({ method: "GET", path: "/workspace" }); expect(h.mint).toHaveBeenCalledTimes(2); expect(new Headers(fetcher.mock.calls[1]![1].headers).get("authorization")).toBe( "Bearer token-2", @@ -171,9 +171,9 @@ it("does not evict a renewed token when an older request returns a late 401", as .mockImplementation(async () => Response.json({ success: true })); vi.stubGlobal("fetch", fetcher); const { client } = await getNamespaceClient("org", "space"); - const old = client._http.request({ method: "POST", path: "/vms" }).catch((error) => error); + const old = client._http.request({ method: "POST", path: "/workspace" }).catch((error) => error); vi.setSystemTime(Date.now() + 1741_000); - await client._http.request({ method: "GET", path: "/vms" }); + await client._http.request({ method: "GET", path: "/workspace" }); rejectOld(Response.json({ code: "token_revoked" }, { status: 401 })); expect(await old).toMatchObject({ status: 401 }); await getNamespaceClient("org", "space"); diff --git a/apps/api/test/lib/cloud-preflight.test.ts b/apps/api/test/lib/cloud-preflight.test.ts index 2051f666a..e419c3712 100644 --- a/apps/api/test/lib/cloud-preflight.test.ts +++ b/apps/api/test/lib/cloud-preflight.test.ts @@ -1,7 +1,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const h = vi.hoisted(() => ({ token: vi.fn(), routes: vi.fn(), checkSlug: vi.fn(), verify: vi.fn(), scopedVerify: vi.fn(), spend: vi.fn(), createPlatform: vi.fn(), quota: vi.fn() })); -vi.mock("@repo/adapters", async original => ({ ...await original(), createPlatform: h.createPlatform })); +vi.mock("@repo/adapters", () => ({ createPlatform: h.createPlatform })); vi.mock("@repo/platform/engine/config/env", () => ({ env: { OBLIEN_API_URL: "https://api.oblien.com" } })); vi.mock("@repo/platform/engine/lib/routing-domains", () => ({ getRoutingBaseDomain: () => "opsh.io" })); vi.mock("@repo/platform/engine/lib/openship-cloud", () => ({ diff --git a/apps/api/test/lib/cloud-resource-limits.test.ts b/apps/api/test/lib/cloud-resource-limits.test.ts index 69433a654..a25adc3c9 100644 --- a/apps/api/test/lib/cloud-resource-limits.test.ts +++ b/apps/api/test/lib/cloud-resource-limits.test.ts @@ -2,9 +2,8 @@ import { beforeEach, describe, expect, it, vi } from "vitest"; const h = vi.hoisted(() => ({ quota: vi.fn(), get: vi.fn(), update: vi.fn() })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ - getOblienClient: () => ({ vms: { getQuota: h.quota }, namespaces: { get: h.get, update: h.update } }), + getOblienClient: () => ({ workspaces: { getQuota: h.quota }, namespaces: { get: h.get, update: h.update } }), })); -import { toOblienVmLimits } from "@repo/adapters"; import { cloudNamespaceLimits, initialCloudNamespaceLimits, readCloudCapacity, readCloudCapacityPool, syncCloudResourceLimits } from "@repo/platform/engine/lib/cloud-resource-limits"; beforeEach(() => { @@ -12,15 +11,15 @@ beforeEach(() => { h.quota.mockImplementation(() => { throw new Error("Openship must not calculate provider capacity"); }); h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: null } }); h.update.mockImplementation(async (_id, input) => ({ data: { id: "ns-a", slug: "tenant-a", ...input, - effective_resource_limits: { max_vms: 52, max_vcpus: 32, max_ram_mb: 65536, max_disk_gb: 1024 }, + effective_resource_limits: { max_workspaces: 52, max_vcpus: 32, max_ram_mb: 65536, max_disk_gb: 1024 }, } })); }); describe("Oblien-owned namespace capacity", () => { it("displays provider allocations in their real units without using credit balances or owner limits", async () => { h.get.mockResolvedValue({ success: true, data: { slug: "tenant-a", - effective_resource_limits: toOblienVmLimits(cloudNamespaceLimits("pro")), - allocated_resource_usage: { vms: 3, vcpus: 2.5, ram_mb: 4096, disk_gb: 48.5, pending_updates: 1 }, + effective_resource_limits: cloudNamespaceLimits("pro"), + allocated_resource_usage: { workspaces: 3, vcpus: 2.5, ram_mb: 4096, disk_gb: 48.5, pending_updates: 1 }, } }); expect(await readCloudCapacity("tenant-a")).toEqual({ workspaces: { used: 3, max: 1 }, vcpus: { used: 2.5, max: 4 }, ramMb: { used: 4096, max: 16384 }, diskGb: { used: 48.5, max: 250 } }); @@ -37,8 +36,8 @@ describe("Oblien-owned namespace capacity", () => { }); it("converts disk to MB for admission without confusing zero and unlimited", async () => { h.get.mockResolvedValue({ success: true, data: { slug: "tenant-a", - effective_resource_limits: { max_vms: null, max_total_vcpus: 0, max_total_ram_mb: 8192, max_total_disk_gb: 16 }, - allocated_resource_usage: { vms: 0, vcpus: 0, ram_mb: 0, disk_gb: 1.25, pending_updates: 0 }, + effective_resource_limits: { max_workspaces: null, max_total_vcpus: 0, max_total_ram_mb: 8192, max_total_disk_gb: 16 }, + allocated_resource_usage: { workspaces: 0, vcpus: 0, ram_mb: 0, disk_gb: 1.25, pending_updates: 0 }, } }); expect(await readCloudCapacityPool("tenant-a")).toEqual({ workspaces: { used: 0, max: null }, cpuCores: { used: 0, max: 0 }, memoryMb: { used: 0, max: 8192 }, diskMb: { used: 1280, max: 16384 } }); @@ -51,37 +50,37 @@ describe("Oblien-owned namespace capacity", () => { }); it("declares finite retail VM and aggregate caps without reading enterprise owner capacity", async () => { expect(cloudNamespaceLimits("team")).toEqual({ max_workspaces: 1, max_vcpus: 8, max_ram_mb: 32768, max_disk_gb: 600, max_total_vcpus: 8, max_total_ram_mb: 32768, max_total_disk_gb: 600 }); - await expect(initialCloudNamespaceLimits()).resolves.toEqual({ max_vms: 0, max_vcpus: 1, max_ram_mb: 1024, max_disk_gb: 8, max_total_vcpus: 0, max_total_ram_mb: 0, max_total_disk_gb: 0 }); + await expect(initialCloudNamespaceLimits()).resolves.toEqual({ max_workspaces: 0, max_vcpus: 1, max_ram_mb: 1024, max_disk_gb: 8, max_total_vcpus: 0, max_total_ram_mb: 0, max_total_disk_gb: 0 }); await syncCloudResourceLimits("tenant-a", "team"); - expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: toOblienVmLimits(cloudNamespaceLimits("team")) }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: cloudNamespaceLimits("team") }); expect(h.quota).not.toHaveBeenCalled(); }); - it("preserves an older saved offer when sending VM limits and accepts Oblien's lower effective ceiling", async () => { + it("sends an older saved offer unchanged and accepts Oblien's lower effective ceiling", async () => { const saved = Object.freeze({ max_workspaces: 52, max_vcpus: 200, max_ram_mb: 417792, max_disk_gb: 64, max_total_vcpus: 8, max_total_ram_mb: 16384, max_total_disk_gb: 256 }); await syncCloudResourceLimits("tenant-a", "team", saved); - expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: toOblienVmLimits(saved) }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: saved }); expect(saved.max_vcpus).toBe(200); expect(h.quota).not.toHaveBeenCalled(); }); it("preserves explicit customer restrictions even when the owner's capacity is unlimited", async () => { const saved = Object.freeze({ max_workspaces: 7, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 12, max_total_vcpus: 3, max_total_ram_mb: 6144, max_total_disk_gb: 24 }); await syncCloudResourceLimits("tenant-a", "team", saved); - expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: toOblienVmLimits(saved) }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: saved }); expect(h.quota).not.toHaveBeenCalled(); }); it("does not rewrite declared policy when effective capacity differs", async () => { const declared = { max_workspaces: 52, max_vcpus: 200, max_ram_mb: 417792, max_disk_gb: 64, max_total_vcpus: 8, max_total_ram_mb: 16384, max_total_disk_gb: 256 }; - h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: toOblienVmLimits(declared), - effective_resource_limits: { ...toOblienVmLimits(declared), max_vcpus: 32, max_ram_mb: 65536 }, + h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: declared, + effective_resource_limits: { ...declared, max_vcpus: 32, max_ram_mb: 65536 }, } }); await syncCloudResourceLimits("tenant-a", "team", declared); expect(h.update).not.toHaveBeenCalled(); expect(h.quota).not.toHaveBeenCalled(); }); it("clears old declared caps only after a verified enterprise entitlement", async () => { - h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: { max_vms: 5 } } }); + h.get.mockResolvedValue({ data: { id: "ns-a", slug: "tenant-a", resource_limits: { max_workspaces: 5 } } }); await syncCloudResourceLimits("tenant-a", "enterprise"); - expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: { max_vms: null, max_vcpus: null, max_ram_mb: null, max_disk_gb: null, max_total_vcpus: null, max_total_ram_mb: null, max_total_disk_gb: null } }); + expect(h.update).toHaveBeenCalledWith("ns-a", { resource_limits: { max_workspaces: null, max_vcpus: null, max_ram_mb: null, max_disk_gb: null, max_total_vcpus: null, max_total_ram_mb: null, max_total_disk_gb: null } }); }); it("cannot change policy when the provider returns another namespace", async () => { h.get.mockResolvedValue({ data: { id: "ns-b", slug: "tenant-b" } }); diff --git a/apps/api/test/lib/cloud-resource-proxy.test.ts b/apps/api/test/lib/cloud-resource-proxy.test.ts index 0c6168e0a..f41b50777 100644 --- a/apps/api/test/lib/cloud-resource-proxy.test.ts +++ b/apps/api/test/lib/cloud-resource-proxy.test.ts @@ -12,7 +12,7 @@ vi.mock("../../src/lib/request-context", () => ({ getRequestContext: () => ({ or vi.mock("../../src/modules/cloud/cloud-relay-access", () => ({ authorizeCloudRelayWorkspace: async () => null })); vi.mock("@repo/platform/engine/lib/openship-cloud", () => ({ ensureNamespace: async () => "ns-a" })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ getOblienClient: () => ({ - vms: { get: h.workspaceGet }, + workspaces: { get: h.workspaceGet }, pages: { list: h.pageList, get: h.pageGet, create: h.pageCreate, deploy: h.pageDeploy, delete: h.pageDelete }, domain: { routes: h.routes }, routes: { set: h.setRoutes }, }) })); @@ -46,18 +46,18 @@ describe("desktop-to-SaaS Cloud resource delegation", () => { it("round-trips page reads and redeploys through the SaaS ownership checks", async () => { const proxy = createRemoteCloudAdmin("org-a"); expect(await proxy.pages!.get("site-a")).toMatchObject({ page: { namespace: "ns-a" } }); - await proxy.pages!.deploy("site-a", { vm_id: "ws-a", path: "/app/dist" }); - expect(h.pageDeploy).toHaveBeenCalledWith("site-a", { vm_id: "ws-a", path: "/app/dist" }); + await proxy.pages!.deploy("site-a", { workspace_id: "ws-a", path: "/app/dist" }); + expect(h.pageDeploy).toHaveBeenCalledWith("site-a", { workspace_id: "ws-a", path: "/app/dist" }); expect(h.spend).toHaveBeenCalledWith("org-a", null); }); it("ignores the client's namespace and pins a create to its server identity", async () => { - await createRemoteCloudAdmin("org-a").pages!.create({ vm_id: "ws-a", path: "/app/dist", name: "Site", slug: "site-a", namespace: "ns-b" }); + await createRemoteCloudAdmin("org-a").pages!.create({ workspace_id: "ws-a", path: "/app/dist", name: "Site", slug: "site-a", namespace: "ns-b" }); expect(h.pageCreate).toHaveBeenCalledWith(expect.objectContaining({ namespace: "ns-a" })); }); it("refuses both foreign page reads and foreign source exports", async () => { const pages = createRemoteCloudAdmin("org-a").pages!; await expect(pages.get("site-b")).rejects.toMatchObject({ status: 404 }); - await expect(pages.create({ vm_id: "ws-b", path: "/app/dist", name: "Site", slug: "site-a" })).rejects.toMatchObject({ status: 404 }); + await expect(pages.create({ workspace_id: "ws-b", path: "/app/dist", name: "Site", slug: "site-a" })).rejects.toMatchObject({ status: 404 }); expect(h.pageCreate).not.toHaveBeenCalled(); }); it("preserves provider 404 so the runtime can create a missing page", async () => { diff --git a/apps/api/test/lib/cloud-tenant-admin.test.ts b/apps/api/test/lib/cloud-tenant-admin.test.ts index b6e113560..fe6313b97 100644 --- a/apps/api/test/lib/cloud-tenant-admin.test.ts +++ b/apps/api/test/lib/cloud-tenant-admin.test.ts @@ -5,7 +5,7 @@ const h = vi.hoisted(() => ({ workspaceGet: vi.fn(), routes: vi.fn(), setRoutes: vi.fn(), spend: vi.fn(), pageList: vi.fn(), })); vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ getOblienClient: () => ({ - vms: { get: h.workspaceGet }, + workspaces: { get: h.workspaceGet }, pages: { list: h.pageList, get: h.pageGet, create: h.pageCreate, delete: h.pageDelete, disable: h.pageDisable, deploy: h.pageDeploy }, domain: { routes: h.routes }, routes: { set: h.setRoutes }, }) })); @@ -32,12 +32,12 @@ describe("admin-only cloud delegation", () => { }); it("rejects another customer's workspace before exporting a page", async () => { const proxy = createTenantCloudAdmin("org-one", "ns-own"); - await expect(proxy.pages!.create({ vm_id: "ws-other", path: "/app/dist", name: "test", slug: "test" })).rejects.toMatchObject({ statusCode: 404 }); + await expect(proxy.pages!.create({ workspace_id: "ws-other", path: "/app/dist", name: "test", slug: "test" })).rejects.toMatchObject({ statusCode: 404 }); expect(h.pageCreate).not.toHaveBeenCalled(); }); it("pins page creation to the authenticated namespace", async () => { const proxy = createTenantCloudAdmin("org-one", "ns-own"); - await proxy.pages!.create({ vm_id: "ws-own", path: "/app/dist", name: "test", slug: "test", namespace: "ns-other" }); + await proxy.pages!.create({ workspace_id: "ws-own", path: "/app/dist", name: "test", slug: "test", namespace: "ns-other" }); expect(h.pageCreate).toHaveBeenCalledWith(expect.objectContaining({ namespace: "ns-own" })); expect(h.spend).toHaveBeenCalledWith("org-one", undefined); }); @@ -45,7 +45,7 @@ describe("admin-only cloud delegation", () => { const pages = createTenantCloudAdmin("org-one", "ns-own").pages!; await expect(pages.get("other-page")).rejects.toMatchObject({ statusCode: 404 }); await expect(pages.delete("other-page")).rejects.toMatchObject({ statusCode: 404 }); - await expect(pages.deploy("other-page", { vm_id: "ws-own", path: "/app/dist" })).rejects.toMatchObject({ statusCode: 404 }); + await expect(pages.deploy("other-page", { workspace_id: "ws-own", path: "/app/dist" })).rejects.toMatchObject({ statusCode: 404 }); expect(h.pageDelete).not.toHaveBeenCalled(); expect(h.pageDeploy).not.toHaveBeenCalled(); }); @@ -59,11 +59,11 @@ describe("admin-only cloud delegation", () => { }); it("validates both hostname and every route target before an admin mutation", async () => { const proxy = createTenantCloudAdmin("org-one", "ns-own"); - const routes = [{ match: { path: "/" }, action: { kind: "proxy" as const, vm: "ws-other", port: 8080 } }]; + const routes = [{ match: { path: "/" }, action: { kind: "proxy" as const, workspace: "ws-other", port: 8080 } }]; await expect(proxy.setRoutes!("own.opsh.io", { routes })).rejects.toMatchObject({ statusCode: 404 }); await expect(proxy.setRoutes!("other.opsh.io", { routes: [] })).rejects.toMatchObject({ statusCode: 404 }); expect(h.setRoutes).not.toHaveBeenCalled(); - await proxy.setRoutes!("own.opsh.io", { routes: [{ ...routes[0]!, action: { kind: "proxy", vm: "ws-own", port: 8080 } }] }); + await proxy.setRoutes!("own.opsh.io", { routes: [{ ...routes[0]!, action: { kind: "proxy", workspace: "ws-own", port: 8080 } }] }); expect(h.setRoutes).toHaveBeenCalledOnce(); }); it("does not use reseller authority for unverified external proxy origins", async () => { diff --git a/apps/api/test/lib/controller-sse-drain.test.ts b/apps/api/test/lib/controller-sse-drain.test.ts deleted file mode 100644 index fd2e2ffcc..000000000 --- a/apps/api/test/lib/controller-sse-drain.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import { Hono } from "hono"; -import type { SSEStreamingApi } from "hono/streaming"; -import { closeControllerStreams, resumeControllerStreams, streamSSE } from "../../src/lib/sse"; -import { drainBackgroundWork } from "@repo/platform/engine/lib/background-work"; - -beforeEach(() => resumeControllerStreams()); -afterEach(async () => { - closeControllerStreams(); - await drainBackgroundWork(); - resumeControllerStreams(); -}); - -it("refuses a stream admitted before the move but initialized after streams were closed", async () => { - let enter!: () => void; - let proceed!: () => void; - const entered = new Promise(resolve => { enter = resolve; }); - const admitted = new Promise(resolve => { proceed = resolve; }); - const callback = vi.fn(async (stream: SSEStreamingApi) => { - await new Promise(resolve => stream.onAbort(resolve)); - }); - const app = new Hono(); - app.get("/events", async c => { - enter(); - await admitted; // permission/metadata read already admitted by the HTTP guard - return streamSSE(c, callback); - }); - const pending = app.request("/events"); - await entered; - closeControllerStreams(); - proceed(); - const response = await pending; - try { - expect(response.status).toBe(503); - expect(await response.json()).toMatchObject({ code: "INSTANCE_CONTROLLER_INACTIVE" }); - expect(callback).not.toHaveBeenCalled(); - } finally { - closeControllerStreams(); - if (!response.bodyUsed) await response.body?.cancel(); - await drainBackgroundWork(); - } -}); - -it("aborts an existing subscriber so the controller can finish draining", async () => { - const aborted = vi.fn(); - const app = new Hono(); - app.get("/events", c => streamSSE(c, async stream => { - await new Promise(resolve => stream.onAbort(() => { aborted(); resolve(); })); - })); - const response = await app.request("/events"); - expect(response.status).toBe(200); - closeControllerStreams(); - await drainBackgroundWork(); - expect(aborted).toHaveBeenCalledOnce(); - await response.body?.cancel(); -}); - -it("accepts streams again when the active controller is resumed after cancellation", async () => { - const callback = vi.fn(async () => {}); - const app = new Hono(); - app.get("/events", c => streamSSE(c, callback)); - closeControllerStreams(); - const refused = await app.request("/events"); - expect(refused.status).toBe(503); - expect(callback).not.toHaveBeenCalled(); - resumeControllerStreams(); - const response = await app.request("/events"); - expect(response.status).toBe(200); - expect(callback).toHaveBeenCalledOnce(); - await response.body?.cancel(); -}); diff --git a/apps/api/test/lib/email-templates.test.ts b/apps/api/test/lib/email-templates.test.ts index be313f41d..00a84f123 100644 --- a/apps/api/test/lib/email-templates.test.ts +++ b/apps/api/test/lib/email-templates.test.ts @@ -5,11 +5,7 @@ */ import { describe, expect, it } from "vitest"; -import { - existingAccountEmail, - organizationInviteEmail, - resetPasswordOtpEmail, -} from "@repo/platform/engine/lib/email-templates"; +import { organizationInviteEmail, resetPasswordOtpEmail } from "@repo/platform/engine/lib/email-templates"; describe("email-templates — HTML injection is neutralized", () => { it("escapes attacker-controlled org name and inviter name in the invite HTML", () => { @@ -68,15 +64,4 @@ describe("email-templates — HTML injection is neutralized", () => { expect(email.html).not.toContain(" { - const email = existingAccountEmail( - { name: '', email: "customer@example.test" }, - "https://dashboard.example.test", - ); - expect(email.html).not.toContain(" { - vi.unstubAllEnvs(); - vi.resetModules(); -}); - -it.each([ - [undefined, "https://vm.oblien.com"], - ["https://runtime.staging.example", "https://runtime.staging.example"], -])("configures the native VM credential endpoint with override %s", async (override, expected) => { - vi.resetModules(); - vi.stubEnv("NODE_ENV", "test"); - vi.stubEnv("BILLING_ENABLED", "false"); - vi.stubEnv("OBLIEN_RUNTIME_URL", override); - const { env } = await import("@repo/platform/engine/config/env"); - expect(env.OBLIEN_RUNTIME_URL).toBe(expected); -}); diff --git a/apps/api/test/lib/permission-grant-satisfiability.test.ts b/apps/api/test/lib/permission-grant-satisfiability.test.ts index bc4816867..f4baf51a2 100644 --- a/apps/api/test/lib/permission-grant-satisfiability.test.ts +++ b/apps/api/test/lib/permission-grant-satisfiability.test.ts @@ -24,10 +24,9 @@ import type { RequestContext } from "../../src/lib/request-context"; * the grantable surface without proving it authorizes something → this fails. */ -// Exercise grant algebra under an owner's ceiling; members cannot delegate admin. vi.mock("@repo/db", () => ({ repos: { - member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "member" })) }, project: { findById: vi.fn(async (id: string) => (id === "*" ? null : { id, organizationId: "org1" })), findEnvVarById: vi.fn(async () => null), diff --git a/apps/api/test/lib/permission-own-projects.test.ts b/apps/api/test/lib/permission-own-projects.test.ts index 0f3a3edf0..d1b2a52b9 100644 --- a/apps/api/test/lib/permission-own-projects.test.ts +++ b/apps/api/test/lib/permission-own-projects.test.ts @@ -3,10 +3,9 @@ import { describe, it, expect, vi } from "vitest"; // checkPermission touches only member.find (membership gate) and, for a // concrete project id, project.findById (org resolution). We pass the grant // source explicitly via opts, so resourceGrant is never consulted. -// The owner can delegate project admin; the token must still satisfy each grant. vi.mock("@repo/db", () => ({ repos: { - member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "member" })) }, project: { findById: vi.fn(async (id: string) => id === "*" ? null : { id, organizationId: "org1" }, diff --git a/apps/api/test/lib/permission-wildcard-list-arm.test.ts b/apps/api/test/lib/permission-wildcard-list-arm.test.ts index 0620fa0ff..d92e3788a 100644 --- a/apps/api/test/lib/permission-wildcard-list-arm.test.ts +++ b/apps/api/test/lib/permission-wildcard-list-arm.test.ts @@ -19,10 +19,9 @@ import { describe, it, expect, vi } from "vitest"; -// The owner's role ceiling permits delegation; the tests enforce grant widths. vi.mock("@repo/db", () => ({ repos: { - member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "member" })) }, project: { findById: vi.fn(async (id: string) => (id === "*" ? null : { id, organizationId: "org1" })), findEnvVarById: vi.fn(async () => null), @@ -199,7 +198,7 @@ describe("a full project wildcard now lists and creates (deliberate widening)", }); describe("non-restricted roles are untouched by this arm", () => { - it("an owner is authorized by role, without consulting grants", async () => { + it("a member is authorized by role, without consulting grants", async () => { const boom = { findForResource: async () => { throw new Error("the role arm must return before any grant lookup"); diff --git a/apps/api/test/lib/profile-avatar.test.ts b/apps/api/test/lib/profile-avatar.test.ts deleted file mode 100644 index 31d4e4604..000000000 --- a/apps/api/test/lib/profile-avatar.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { expect, it } from "vitest"; -import { auth } from "@repo/platform/engine/lib/auth"; -import { provisionUser } from "@repo/platform/engine/lib/provision-user"; -import { mintSession } from "../../src/lib/cloud-auth-proxy"; -import { db, schema, eq } from "@repo/db"; -import { randomUUID } from "node:crypto"; - -it("updates only the signed-in user's avatar through the existing auth endpoint and rejects unsafe URLs", async () => { - const id = randomUUID(); - await provisionUser({ - id, - email: `${id}@example.test`, - name: "Avatar owner", - emailVerified: true, - }); - const session = await mintSession({ purpose: "local-cookie", userId: id }); - const update = (image: unknown, token: string | null = session.token, extra = {}) => - auth.handler( - new Request("http://localhost:4000/api/auth/update-user", { - method: "POST", - headers: { - "Content-Type": "application/json", - ...(token ? { Authorization: `Bearer ${token}` } : {}), - }, - body: JSON.stringify({ image, ...extra }), - }), - ); - expect((await update("https://cdn.example.test/avatar.png", null)).status).toBe(401); - const result = await update("https://cdn.example.test/avatar.png"); - expect(result.status, await result.clone().text()).toBe(200); - expect(await db.query.user.findFirst({ where: eq(schema.user.id, id) })).toMatchObject({ - image: "https://cdn.example.test/avatar.png", - role: "user", - }); - expect( - await auth.api.getSession({ - headers: new Headers({ Authorization: `Bearer ${session.token}` }), - }), - ).toMatchObject({ user: { image: "https://cdn.example.test/avatar.png" } }); - expect( - (await update("https://cdn.example.test/avatar.png", session.token, { role: "admin" })).status, - ).toBe(400); - for (const image of [ - "javascript:alert(1)", - "data:image/svg+xml,", - "https://user:secret@example.test/a.png", - "/avatar.png", - 123, - ]) - expect((await update(image)).status).toBe(400); - expect((await update(null)).status).toBe(200); - expect(await db.query.user.findFirst({ where: eq(schema.user.id, id) })).toMatchObject({ - image: null, - }); -}); diff --git a/apps/api/test/modules/actions/billing-webhook.test.ts b/apps/api/test/modules/actions/billing-webhook.test.ts index 1eb01e4dc..8e547c7b2 100644 --- a/apps/api/test/modules/actions/billing-webhook.test.ts +++ b/apps/api/test/modules/actions/billing-webhook.test.ts @@ -450,7 +450,7 @@ describe("Actions namespace preparation before checkout", () => { name: "Openship Actions", slug: f.namespace, resource_limits: { - max_vms: 0, + max_workspaces: 0, max_vcpus: 0, max_ram_mb: 0, max_disk_gb: 0, diff --git a/apps/api/test/modules/apps/app-install-routing.test.ts b/apps/api/test/modules/apps/app-install-routing.test.ts index 980fffc58..992ecf782 100644 --- a/apps/api/test/modules/apps/app-install-routing.test.ts +++ b/apps/api/test/modules/apps/app-install-routing.test.ts @@ -703,41 +703,3 @@ it("deduplicates an interpolated secret also declared as a generated config fiel vars.filter((v: { key: string }) => v.key === "OPENSHIP_ADMIN_PASSWORD"), ).toHaveLength(1); }); - -function templateWithConfigPorts() { - const template = structuredClone(getAppTemplate("convex")!); - template.id = "config-ports-test"; - template.configFields = [ - { key: "HOST_PORT", service: "backend", label: "Host port", default: "8181" }, - { key: "HTTP_PORT", service: "backend", label: "Container port", default: "8080" }, - ]; - template.services!.find(service => service.name === "backend")!.ports = ["{{config:HOST_PORT}}:{{config:HTTP_PORT}}/tcp"]; - customTemplateMock.mockResolvedValue({ template }); - return template; -} - -it("substitutes port defaults before validating routes and preserves the cached template", async () => { - const template = templateWithConfigPorts(); - await installApp(ctx, { templateId: template.id, routes: [{ service: "backend", port: 8080, mode: "port" }] }); - expect(payloadFor("backend")?.ports).toEqual(["0.0.0.0:8181:8080/tcp"]); - expect(template.services![0]!.ports).toEqual(["{{config:HOST_PORT}}:{{config:HTTP_PORT}}/tcp"]); -}); - -it("uses supplied port values for both route validation and service creation", async () => { - const template = templateWithConfigPorts(); - await installApp(ctx, { - templateId: template.id, config: { HOST_PORT: "9191", HTTP_PORT: "9090" }, - routes: [{ service: "backend", port: 9090, mode: "port" }], - }); - expect(payloadFor("backend")?.ports).toEqual(["0.0.0.0:9191:9090/tcp"]); -}); - -it("uses resolved authored ports when undoing port-only access on an adopted draft", async () => { - const template = templateWithConfigPorts(); - draftMock.mockResolvedValue({ id: "p1", slug: "draft", name: "Draft" }); - listServicesMock.mockResolvedValue(template.services!.map(service => ({ id: `svc-${service.name}`, name: service.name, ports: service.name === "backend" ? ["0.0.0.0:8181:8080/tcp"] : [] }))); - await installApp(ctx, { templateId: template.id, routes: [{ service: "backend", port: 8080, mode: "custom", customDomain: "ports.example.com" }] }); - expect(updateServiceMock).toHaveBeenCalledWith(ctx, "p1", "svc-backend", expect.objectContaining({ ports: ["8181:8080/tcp"] })); - expect(createServiceMock).not.toHaveBeenCalled(); - expect(setEnvMock).not.toHaveBeenCalled(); -}); diff --git a/apps/api/test/modules/apps/cloud-install-cleanup.integration.test.ts b/apps/api/test/modules/apps/cloud-install-cleanup.integration.test.ts index 383127280..f92314c2a 100644 --- a/apps/api/test/modules/apps/cloud-install-cleanup.integration.test.ts +++ b/apps/api/test/modules/apps/cloud-install-cleanup.integration.test.ts @@ -105,7 +105,7 @@ beforeEach(async () => { } const method = init?.method ?? "GET"; requests.push(`${method} ${url.pathname}`); - if (url.pathname === "/vms" && method === "POST") { + if (url.pathname === "/workspace" && method === "POST") { if (createMode === "quota" || createMode === "legacy-quota") { return Response.json( { success: false, code: "NAMESPACE_LIMIT_REACHED" }, @@ -133,27 +133,27 @@ beforeEach(async () => { return Response.json( { code: "CREATE_FAILED", - details: { vm_id: workspace.id }, + details: { workspace_id: workspace.id }, }, { status: 422 }, ); } - if (url.pathname === "/vms" && method === "GET") { + if (url.pathname === "/workspace" && method === "GET") { return Response.json({ success: true, - vms: [...workspaces.values()], + workspaces: [...workspaces.values()], total: workspaces.size, limit: 100, page: 1, }); } - const workspaceId = url.pathname.match(/^\/vms\/([^/]+)$/)?.[1]; - const retryId = url.pathname.match(/^\/vms\/([^/]+)\/provisioning\/retry$/)?.[1]; + const workspaceId = url.pathname.match(/^\/workspace\/([^/]+)$/)?.[1]; + const retryId = url.pathname.match(/^\/workspace\/([^/]+)\/provisioning\/retry$/)?.[1]; if (retryId && method === "POST") { const workspace = workspaces.get(retryId)!; workspace.status = "running"; workspace.provisioning.state = "ready"; - return Response.json({ success: true, vm: workspace }); + return Response.json({ success: true, workspace }); } if (url.pathname.endsWith("/lifecycle/permanent") && method === "POST") return Response.json({ success: true }); @@ -162,7 +162,7 @@ beforeEach(async () => { if (deleting.has(workspaceId)) workspaces.delete(workspaceId); const workspace = workspaces.get(workspaceId); return workspace - ? Response.json({ success: true, vm: workspace }) + ? Response.json({ success: true, workspace }) : Response.json({ code: "NOT_FOUND" }, { status: 404 }); } if (workspaceId && method === "DELETE") { diff --git a/apps/api/test/modules/billing/billing-sdk-parity.test.ts b/apps/api/test/modules/billing/billing-sdk-parity.test.ts index e7de42cd1..4dea70ffd 100644 --- a/apps/api/test/modules/billing/billing-sdk-parity.test.ts +++ b/apps/api/test/modules/billing/billing-sdk-parity.test.ts @@ -1,5 +1,4 @@ import { savedOffer as subscriptionOffer, savedMetadata as subscriptionMetadata } from "../../helpers/saved-cloud-offer"; -import { providerBillingFixture } from "../../helpers/oblien-vm-billing"; import capacityCatalog from "../../fixtures/oblien-capacity-catalog.json"; import { monthlyCloudBilling } from "../../helpers/monthly-cloud-offer"; import managedTransfer from "../../fixtures/oblien-managed-transfer.json"; @@ -61,7 +60,7 @@ vi.mock("@repo/platform/engine/lib/oblien-client", () => ({ }), }), getOblienClient: () => ({ - vms: { getQuota: provider.quota, get: provider.workspace }, + workspaces: { getQuota: provider.quota, get: provider.workspace }, namespaces: { ensure: provider.namespaces, get: provider.resourceRead, @@ -193,8 +192,8 @@ describe("billing through the same SDK and HTTP application operations", () => { // Exercise the actual SDK/validator before the shared application operation; // a mock entitlement alone missed the provider's newly included transfer. const billing = new OblienBillingApi({ clientId: "test-id", clientSecret: "test-secret", - fetch: (async url => Response.json(providerBillingFixture(new URL(String(url)).pathname === "/v1/billing/balance" - ? monthly.balance : monthly.entitlement))) as typeof fetch }); + fetch: (async url => Response.json(new URL(String(url)).pathname === "/billing/balance" + ? monthly.balance : monthly.entitlement)) as typeof fetch }); provider.subscriptions.set(selected.namespace!, monthly.subscription); provider.entitlement.mockImplementation(async namespace => namespace === selected.namespace ? billing.getEntitlement(namespace) : { success: true, namespace, tierId: null, status: "credit_exhausted", @@ -268,13 +267,13 @@ describe("billing through the same SDK and HTTP application operations", () => { data: { slug, effective_resource_limits: { - max_vms: 12, + max_workspaces: 12, max_total_vcpus: 8, max_total_ram_mb: 16384, max_total_disk_gb: 256, }, allocated_resource_usage: { - vms: 0, + workspaces: 0, vcpus: 0, ram_mb: 0, disk_gb: 0, diff --git a/apps/api/test/modules/billing/credit-alert.test.ts b/apps/api/test/modules/billing/credit-alert.test.ts index 437b90dae..d02ca881d 100644 --- a/apps/api/test/modules/billing/credit-alert.test.ts +++ b/apps/api/test/modules/billing/credit-alert.test.ts @@ -23,19 +23,13 @@ const input = { eventType: "namespace.quota.threshold", eventId: "evt1", timestamp: "2026-09-28T00:00:00Z", - data: { namespace: "tenant", service: "vm_compute", threshold: 95, alert: { limit: 4000 } }, + data: { namespace: "tenant", service: "workspace_vm", threshold: 95, alert: { limit: 4000 } }, organizationId: "org-a", dashboardUrl: "https://app.openship.io", entitlement: state(), }; describe("provider credit alerts", () => { - it("accepts a pre-cutover delivery without changing its idempotency key", () => { - const result = creditAlertNotification({ - ...input, data: { ...input.data, service: "workspace_vm" }, - }); - expect(result).toEqual(creditAlertNotification(input)); - }); it("uses current provider numbers and an organization-bound billing link", () => { const result = creditAlertNotification(input)!; expect(result.payload.message).toContain("95%"); diff --git a/apps/api/test/modules/cloud-execution-access.test.ts b/apps/api/test/modules/cloud-execution-access.test.ts index 1812cf15b..3402dfe1e 100644 --- a/apps/api/test/modules/cloud-execution-access.test.ts +++ b/apps/api/test/modules/cloud-execution-access.test.ts @@ -120,7 +120,7 @@ describe("Cloud relays cannot substitute Cloud feature access for host administr expect(await response.json()).toMatchObject({ data: { token: "provider-secret" } }); }); - it.each(["owner", "admin"])( + it.each(["owner", "admin", "member"])( "preserves existing full host access for the %s role", async (role) => { await db.update(schema.member).set({ role }).where(eq(schema.member.id, memberId)); @@ -129,17 +129,6 @@ describe("Cloud relays cannot substitute Cloud feature access for host administr }, ); - it("denies members host credentials through both Cloud relay selectors", async () => { - await db.update(schema.member).set({ role: "member" }).where(eq(schema.member.id, memberId)); - for (const path of ["token", `token?serverId=${serverId}`, "resource-proxy", `resource-proxy?serverId=${serverId}`]) { - const response = await post(path, { operation: "list" }); - expect(response.status, await response.clone().text()).toBe(404); - } - expect(h.token).not.toHaveBeenCalled(); - expect(h.namespace).not.toHaveBeenCalled(); - expect(h.pages).not.toHaveBeenCalled(); - }); - it("does not bootstrap a server or credentials for an empty organization without host authority", async () => { actor = await seedOwner(); const membership = (await repos.member.find(actor.orgId, actor.userId))!; @@ -222,7 +211,7 @@ describe("Cloud relays cannot substitute Cloud feature access for host administr it.each([ ["preflight", {}], - ["pages", { vm_id: "vm-own", path: "/private", name: "export", slug: "export" }], + ["pages", { workspace_id: "vm-own", path: "/private", name: "export", slug: "export" }], ["pages/enable", { slug: "own-page" }], ["pages/disable", { slug: "own-page" }], ["pages/delete", { slug: "own-page" }], diff --git a/apps/api/test/modules/cloud-workspaces/lifecycle.integration.test.ts b/apps/api/test/modules/cloud-workspaces/lifecycle.integration.test.ts index 34e133682..44dfb01c6 100644 --- a/apps/api/test/modules/cloud-workspaces/lifecycle.integration.test.ts +++ b/apps/api/test/modules/cloud-workspaces/lifecycle.integration.test.ts @@ -218,7 +218,7 @@ beforeEach(async () => { expiresAt: "2030-01-01T00:00:00Z", })), }, - vms: { + workspaces: { create: vi.fn(async (input: any) => { const existing = [...vms.values()].find((vm) => vm.slug === input.slug); if (existing) return existing; @@ -242,7 +242,7 @@ beforeEach(async () => { return vm; }), list: vi.fn(async () => ({ - vms: [...vms.values()], + workspaces: [...vms.values()], total: vms.size, page: 1, limit: 100, @@ -260,9 +260,9 @@ beforeEach(async () => { vms.delete(id); return { success: true }; }), - vm: (id: string) => ({ + workspace: (id: string) => ({ id, - get: () => h.client.vms.get(id), + get: () => h.client.workspaces.get(id), lifecycle: { makePermanent: async () => {} }, resources: { update: (input: any) => h.client.resize(id, input) }, delete: () => h.client.delete(id), @@ -433,7 +433,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { expect((await request("POST", `/${workspace.id}/ensure`, undefined, stranger)).status).toBe( 404, ); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); const invalid = await request("POST", "", { name: "Broken", mode: "shared", @@ -468,7 +468,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { }); expect(observed.isError).toBe(false); expect(JSON.parse(observed.content[0].text).managed.operation.status).toBe("succeeded"); - expect(h.client.vms.create).toHaveBeenCalledTimes(1); + expect(h.client.workspaces.create).toHaveBeenCalledTimes(1); const outsider = await seedOwner(); expect( @@ -492,7 +492,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { }) ).isError, ).toBe(true); - expect(h.client.vms.create).toHaveBeenCalledTimes(1); + expect(h.client.workspaces.create).toHaveBeenCalledTimes(1); }); it("provisions on paid reconciliation and reuses one host across simultaneous project deployments", async () => { await syncOblienEntitlement(owner.orgId, { workspaceId: workspace.id }); @@ -512,7 +512,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { ); expect(targets[0]?.workspaceId).toBe(targets[1]?.workspaceId); expect(targets.map((target) => target.ownerWorkspaceId)).toEqual([workspace.id, workspace.id]); - expect(h.client.vms.create).toHaveBeenCalledTimes(1); + expect(h.client.workspaces.create).toHaveBeenCalledTimes(1); expect(h.client.resize).not.toHaveBeenCalled(); expect(vms.get(targets[0]!.workspaceId).resources).toMatchObject({ cpus: 1, @@ -544,7 +544,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect( resolveSnapshotTarget(saved, { serverId: otherServer.id, deployTarget: "server" }), ).rejects.toMatchObject({ code: "CLOUD_WORKSPACE_TARGET_CONFLICT" }); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("places bare and Docker projects on managed servers without provisioning a second host", async () => { const sdk = await nativeShip(); @@ -557,7 +557,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { const docker = await sdk.projects.create({ name: "Docker app", serverId: selected.serverId }); for (const project of [bare, docker]) expect(await repos.project.findById(project.id)).toMatchObject({ serverId: selected.serverId, workspaceId: selected.id }); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("installs and previews catalog apps on the selected managed server without creating a project VM", async () => { subscribe("starter"); @@ -583,7 +583,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect( stranger.apps.install({ templateId: "redis", serverId: server.id }), ).rejects.toMatchObject({ statusCode: 404 }); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("carries one managed server through source staging, scan and project creation", async () => { const sdk = await nativeShip(); @@ -614,15 +614,15 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect(stranger.sources.scan(staged.sessionId)).rejects.toMatchObject({ statusCode: 404, }); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); } finally { const session = deleteFolderSession(staged.sessionId); if (session?.stagingDir) await rm(session.stagingDir, { recursive: true, force: true }); } }); it("recovers a lost provider create response with the same request and disk", async () => { - const create = h.client.vms.create.getMockImplementation()!; - h.client.vms.create.mockImplementationOnce(async (input: any) => { + const create = h.client.workspaces.create.getMockImplementation()!; + h.client.workspaces.create.mockImplementationOnce(async (input: any) => { await create(input); throw new Error("create response lost"); }); @@ -642,7 +642,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { ); expect(vms.size).toBe(1); expect( - new Set(h.client.vms.create.mock.calls.map(([input]: any[]) => input.idempotency_key)) + new Set(h.client.workspaces.create.mock.calls.map(([input]: any[]) => input.idempotency_key)) .size, ).toBe(1); expect( @@ -651,7 +651,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { ).toBe([...vms.keys()][0]); }); it("stops after three provisioning failures and durably escalates once without retrying the host", async () => { - h.client.vms.create.mockRejectedValue(new AppError("Hosts are temporarily at capacity", 503, "CLOUD_CAPACITY_UNAVAILABLE")); + h.client.workspaces.create.mockRejectedValue(new AppError("Hosts are temporarily at capacity", 503, "CLOUD_CAPACITY_UNAVAILABLE")); expect((await request("POST", `/${workspace.id}/ensure`)).status).toBe(202); await drainBackgroundWork(); const createTicket = vi.spyOn(repos.cloudSupport, "create").mockRejectedValueOnce(new Error("support database temporarily unavailable")); @@ -673,7 +673,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { expect(await repos.cloudSupport.find(ticketId)).toMatchObject({ status: "open", ownerUserId: owner.userId }); expect(await repos.cloudSupport.messages(ticketId)).toHaveLength(2); await processWorkspaceOperation(workspace.id); - expect(h.client.vms.create).toHaveBeenCalledTimes(3); + expect(h.client.workspaces.create).toHaveBeenCalledTimes(3); expect(await repos.cloudSupport.messages(ticketId)).toHaveLength(2); expect((await repos.cloudWorkspace.listPendingOperations()).map(row => row.id)).not.toContain(workspace.id); createTicket.mockRestore(); @@ -707,7 +707,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { }, }); expect((await deliver("bad-signature")).status).toBe(401); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); expect(await db.select().from(schema.cloudCustomerEmail).where(eq(schema.cloudCustomerEmail.organizationId, owner.orgId))).toEqual([]); h.billing.getCheckout.mockImplementation(async () => ({ checkout: { @@ -731,7 +731,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { .map(mail => mail.kind).sort()).toEqual(["invoice", "purchase"]); expect(result[2]).toMatchObject({ fulfilled: true, creditsGranted: 0 }); await drainBackgroundWork(); - expect(h.client.vms.create).toHaveBeenCalledTimes(1); + expect(h.client.workspaces.create).toHaveBeenCalledTimes(1); expect((await repos.cloudWorkspace.findById(workspace.id))?.operation?.status).toBe( "succeeded", ); @@ -764,7 +764,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect(client.resize(server.id, { revision: "a".repeat(64), confirmRestart: true, idempotencyKey: randomUUID() })) .rejects.toMatchObject({ code: "TOKEN_READ_ONLY" }); } - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("recovers one draft and its server across concurrent native/HTTP creates and scopes retries by organization", async () => { @@ -779,7 +779,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { const stranger = await seedOwner(); const other = await (await clients(stranger))[0]!.createManaged(input); expect(other.id).not.toBe(created[0]!.id); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("never recreates a deleted purchase identity or its old provider namespace", async () => { @@ -791,14 +791,14 @@ describe("subscription-owned Cloud workspace lifecycle", () => { await expect(native!.createManaged(input)).rejects.toMatchObject({ code: "CLOUD_WORKSPACE_PURCHASE_REMOVED" }); await expect(remote!.createManaged(input)).rejects.toMatchObject({ code: "CLOUD_WORKSPACE_PURCHASE_REMOVED" }); expect(await repos.cloudWorkspace.findById(created.id)).toBeUndefined(); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("does not provision, stop or change the entitlement mirror when provider billing is unavailable", async () => { await syncOblienEntitlement(owner.orgId, { workspaceId: workspace.id }); h.billing.getEntitlement.mockRejectedValue(new Error("Billing temporarily unavailable")); const response = await request("POST", `/${workspace.id}/ensure`); expect(response.status).toBe(500); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); expect(h.client.delete).not.toHaveBeenCalled(); expect((await repos.cloudWorkspace.findById(workspace.id))?.subscriptionStatus).toBe("active"); }); @@ -917,7 +917,7 @@ describe("subscription-owned Cloud workspace lifecycle", () => { expect((await request("POST", `/${workspace.id}/ensure`)).body.code).toBe( "CLOUD_SERVER_LINK_REQUIRED", ); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); }); @@ -1757,7 +1757,7 @@ describe("managed server free-domain scope", () => { expect((await repos.domain.listByProject(id)).map(domain => domain.hostname)).toContain(`routed-${entry}.opsh.io`); expect(h.billing.getEntitlement).toHaveBeenCalled(); expect(h.billing.getEntitlement.mock.calls.every(([namespace]: [string]) => namespace === workspace.namespace)).toBe(true); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("uses the selected metered server's entitlement and allowance", async () => { subscribe("starter"); @@ -1780,7 +1780,7 @@ describe("managed server free-domain scope", () => { expect((await repos.service.listByProject(project.id))[0]?.domain).toBe("metered-service"); expect(h.billing.getEntitlement).toHaveBeenCalled(); expect(h.billing.getEntitlement.mock.calls.every(([namespace]: [string]) => namespace === workspace.namespace)).toBe(true); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it.each(["ensure", "update"] as const)("refuses excess free domains before %s changes an existing project's fields", async entry => { const sdk = await nativeShip(); @@ -1823,7 +1823,7 @@ describe("managed server free-domain scope", () => { envVars: {}, })).rejects.toMatchObject({ code: "PLAN_UPGRADE_REQUIRED", reason: "free-subdomain-limit" }); expect((await repos.deployment.listByProject(project.id)).rows).toEqual([]); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("does not count dormant routes outside an exclusive service deployment", async () => { const project = await addProject("Exclusive routes"); @@ -1839,7 +1839,7 @@ describe("managed server free-domain scope", () => { envVars: {}, serviceIds: [selected.id], strictServiceScope: true, }); expect(queued).toMatchObject({ status: "queued" }); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("keeps existing free routes editable when the server's allowance is full", async () => { const sdk = await nativeShip(); @@ -1875,7 +1875,7 @@ describe("managed server free-domain scope", () => { expect(await repos.service.findById(service.id)).toMatchObject({ domain: "routed-console-updated" }); expect(h.billing.getEntitlement).toHaveBeenCalled(); expect(h.billing.getEntitlement.mock.calls.every(([namespace]: [string]) => namespace === workspace.namespace)).toBe(true); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); it("does not use a paid sibling's allowance or write a project for an unauthorized server", async () => { const sdk = await nativeShip(); @@ -1890,6 +1890,6 @@ describe("managed server free-domain scope", () => { await expect(sdk.projects.create({ ...input, serverId: foreignServer.id })).rejects.toMatchObject({ statusCode: 404 }); expect((await repos.projectGroup.listByOrganization(owner.orgId, { page: 1, perPage: 1 })).total).toBe(0); expect(h.billing.getEntitlement).not.toHaveBeenCalled(); - expect(h.client.vms.create).not.toHaveBeenCalled(); + expect(h.client.workspaces.create).not.toHaveBeenCalled(); }); }); diff --git a/apps/api/test/modules/customer-email/signup.integration.test.ts b/apps/api/test/modules/customer-email/signup.integration.test.ts index c18513ec7..b5dddde33 100644 --- a/apps/api/test/modules/customer-email/signup.integration.test.ts +++ b/apps/api/test/modules/customer-email/signup.integration.test.ts @@ -52,9 +52,6 @@ it("welcomes a real SaaS email signup only after the real OTP verification flow" password: "valid-test-password-1234!", }); expect(signup.status, await signup.clone().text()).toBe(200); - expect(h.send).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ to: email })); - const initialMail = h.send.mock.calls.at(-1)![0] as { subject: string }; - const initialCode = initialMail.subject.match(/\b\d{6}\b/)![0]; const [user] = await db.select().from(schema.user).where(eq(schema.user.email, email)); expect(user!.emailVerified).toBe(false); expect( @@ -66,7 +63,14 @@ it("welcomes a real SaaS email signup only after the real OTP verification flow" h.send.mockClear(); expect(await service().flush()).toMatchObject({ sent: 0 }); expect(h.send).not.toHaveBeenCalled(); - const verified = await request("/email-otp/verify-email", { email, otp: initialCode }); + const otp = await request("/email-otp/send-verification-otp", { + email, + type: "email-verification", + }); + expect(otp.status, await otp.clone().text()).toBe(200); + const mail = h.send.mock.calls.at(-1)![0] as { subject: string }; + const code = mail.subject.match(/\b\d{6}\b/)![0]; + const verified = await request("/email-otp/verify-email", { email, otp: code }); expect(verified.status, await verified.clone().text()).toBe(200); h.send.mockClear(); await service().flush(); @@ -166,100 +170,3 @@ it("welcomes a verified Google signup through the same outbox without repeating fetch.mockRestore(); } }, 30_000); - -it("keeps one OAuth account on repeat signup and privately explains how to sign in", async () => { - const email = `existing-google-${randomUUID()}@example.com`; - const id = randomUUID(); - await db - .insert(schema.user) - .values({ id, email, name: "Existing Google customer", emailVerified: true }); - await db - .insert(schema.account) - .values({ id: randomUUID(), accountId: randomUUID(), providerId: "google", userId: id }); - h.send.mockClear(); - for (const attempt of [1, 2]) { - const signup = await request("/sign-up/email", { - name: "Signup retry", - email, - password: `attempt-${attempt}-not-an-account-password!`, - }); - expect(signup.status, await signup.clone().text()).toBe(200); - expect((await signup.json()).token).toBeNull(); - } - expect(await db.select().from(schema.user).where(eq(schema.user.email, email))).toHaveLength(1); - expect(await db.select().from(schema.account).where(eq(schema.account.userId, id))).toMatchObject( - [{ providerId: "google", password: null }], - ); - expect(h.send).toHaveBeenCalledWith( - expect.objectContaining({ to: email, subject: "Sign in to your OpenShip account" }), - ); - const notice = h.send.mock.calls.at(-1)![0] as { text: string }; - expect(notice.text).toContain("already have"); - expect(notice.text).toContain("Google"); - const login = await request("/sign-in/email", { - email, - password: "attempt-2-not-an-account-password!", - }); - expect(login.status).toBe(401); - // A provider-only customer can add a password only after proving mailbox - // ownership through the existing recovery flow, never from duplicate signup. - h.send.mockClear(); - const reset = await request("/email-otp/request-password-reset", { email }); - expect(reset.status, await reset.clone().text()).toBe(200); - const resetMail = h.send.mock.calls.at(-1)![0] as { subject: string }; - const otp = resetMail.subject.match(/\b\d{6}\b/)![0]; - const password = "verified-mailbox-owner-new-password-1234!"; - const changed = await request("/email-otp/reset-password", { email, otp, password }); - expect(changed.status, await changed.clone().text()).toBe(200); - expect((await request("/sign-in/email", { email, password })).status).toBe(200); - expect(await db.select().from(schema.account).where(eq(schema.account.userId, id))).toHaveLength( - 2, - ); -}, 30_000); - -it("resends verification on an unverified signup retry without replacing its password", async () => { - const email = `retry-signup-${randomUUID()}@example.com`; - const password = "first-signup-password-1234!"; - const first = await request("/sign-up/email", { email, name: "Signup customer", password }); - expect(first.status).toBe(200); - h.send.mockClear(); - const retry = await request("/sign-up/email", { - email, - name: "Second attempt", - password: "different-retry-password-1234!", - }); - expect(retry.status).toBe(200); - expect(h.send).toHaveBeenCalledWith(expect.objectContaining({ to: email })); - const mail = h.send.mock.calls.at(-1)![0] as { subject: string }; - const otp = mail.subject.match(/\b\d{6}\b/)![0]; - const verified = await request("/email-otp/verify-email", { email, otp }); - expect(verified.status, await verified.clone().text()).toBe(200); - expect((await request("/sign-in/email", { email, password })).status).toBe(200); - expect( - (await request("/sign-in/email", { email, password: "different-retry-password-1234!" })).status, - ).toBe(401); - expect(await db.select().from(schema.user).where(eq(schema.user.email, email))).toHaveLength(1); -}, 30_000); - -it("recovers an initial delivery failure by retrying signup with the same account", async () => { - const email = `smtp-retry-${randomUUID()}@example.com`; - const password = "original-signup-password-1234!"; - h.send.mockClear(); - h.send.mockResolvedValueOnce(false); - const first = await request("/sign-up/email", { email, name: "SMTP retry", password }); - // Better Auth logs background delivery failures while keeping its generic response. - expect(first.status).toBe(200); - h.send.mockClear(); - const retry = await request("/sign-up/email", { - email, - name: "SMTP retry", - password: "a-different-retry-password-1234!", - }); - expect(retry.status, await retry.clone().text()).toBe(200); - expect(h.send).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ to: email })); - const mail = h.send.mock.calls.at(-1)![0] as { subject: string }; - const otp = mail.subject.match(/\b\d{6}\b/)![0]; - expect((await request("/email-otp/verify-email", { email, otp })).status).toBe(200); - expect((await request("/sign-in/email", { email, password })).status).toBe(200); - expect(await db.select().from(schema.user).where(eq(schema.user.email, email))).toHaveLength(1); -}, 30_000); diff --git a/apps/api/test/modules/deployments/build-duration.test.ts b/apps/api/test/modules/deployments/build-duration.test.ts index 8d1e2cecb..026f4db36 100644 --- a/apps/api/test/modules/deployments/build-duration.test.ts +++ b/apps/api/test/modules/deployments/build-duration.test.ts @@ -13,6 +13,7 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: vi.fn() }, })); vi.mock("@repo/platform/engine/lib/audit-emitter", () => ({ audit: { recordAsync: vi.fn() } })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn() })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(), })); diff --git a/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts b/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts index 83322bdd5..58861d410 100644 --- a/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts +++ b/apps/api/test/modules/deployments/compose-host-channel-notice.test.ts @@ -250,7 +250,7 @@ it("deploys Cloud Compose endpoints, internal paths, generated files and contain const configurations: Array> = []; const publishRoute = vi.fn(async () => undefined); const pullImage = vi.fn(async () => undefined); - const resolveRoutingTarget = vi.fn(async (id: string, port: number) => ({ vm: "shared-vm", + const resolveRoutingTarget = vi.fn(async (id: string, port: number) => ({ workspace: "shared-vm", port: id === "web-container" ? (port === 8080 ? 30001 : 30002) : 30003 })); const runtime = Object.assign(Object.create(CloudDockerRuntime.prototype), { name: "docker", workspaceId: "shared-vm", projectId: "p1", unsupportedComposeKeys: new Set(), @@ -314,8 +314,8 @@ it("deploys Cloud Compose endpoints, internal paths, generated files and contain serviceId: "svc-api", allocatedResources: { containerId: "api-container", cpuCores: 2, memoryMb: 2048 }, })); expect(publishRoute).toHaveBeenCalledWith("app.opsh.io", 30001, false, expect.objectContaining({ routes: [ - { match: { path: "/api/", type: "prefix" }, action: { kind: "proxy", vm: "shared-vm", port: 30003 } }, - { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "shared-vm", port: 30001 } }, + { match: { path: "/api/", type: "prefix" }, action: { kind: "proxy", workspace: "shared-vm", port: 30003 } }, + { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "shared-vm", port: 30001 } }, ] })); }); @@ -1599,8 +1599,7 @@ describe("compose deploy — host channel unavailable", () => { expect(base.deployServiceWorkload).not.toHaveBeenCalled(); }); - it.each([null, "server-original"])("refuses ambiguous duplicate containers on %s before repairing or activating anything", async (serverId) => { - h.previousDeployment.meta = { serverId }; + it("refuses ambiguous duplicate containers before repairing or activating anything", async () => { const base = startingRuntime(); const liveContainer = (id: string, name: string) => ({ id, @@ -1666,18 +1665,11 @@ describe("compose deploy — host channel unavailable", () => { { executor: {} as CommandExecutor, hostPortTarget: localHostPortTarget, - serverId: serverId ?? undefined, }, ), - ).rejects.toMatchObject({ - code: "SERVICE_CONTAINER_CONFLICT", - message: expect.stringMatching(/more than one container matching active service "api".*no service activation/i), - details: { - projectId: "p1", serviceId: "svc-api", serviceName: "api", - containerNames: ["openship-app-api-a", "openship-app-api-b"], - serverId, workspaceId: null, - }, - }); + ).rejects.toThrow( + /more than one container matching active service "api".*no service activation/i, + ); expect(h.updateServiceDeployment).not.toHaveBeenCalled(); expect(h.allocateAndReservePinnedHostPort).not.toHaveBeenCalled(); diff --git a/apps/api/test/modules/deployments/compose-noop-settle.test.ts b/apps/api/test/modules/deployments/compose-noop-settle.test.ts index 7a522fa77..100da4d26 100644 --- a/apps/api/test/modules/deployments/compose-noop-settle.test.ts +++ b/apps/api/test/modules/deployments/compose-noop-settle.test.ts @@ -94,6 +94,7 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ vi.mock("../../../src/lib/audit", () => ({ audit: { recordAsync: (_c: unknown, e: { eventType: string }) => h.audits.push(e.eventType) }, })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: async () => {} })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: async () => {}, })); diff --git a/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts b/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts index 52ffd3b75..e847bd792 100644 --- a/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts +++ b/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts @@ -113,6 +113,7 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ }, })); vi.mock("../../../src/lib/audit", () => ({ audit: { recordAsync: () => {} } })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: async () => {} })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: async () => {}, })); diff --git a/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts b/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts index ee521b560..3fd2f63b7 100644 --- a/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts +++ b/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts @@ -13,6 +13,7 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: vi.fn() }, })); vi.mock("@repo/platform/engine/lib/audit-emitter", () => ({ audit: { recordAsync: vi.fn() } })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn() })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(), })); diff --git a/apps/api/test/modules/deployments/native-sdk-parity.test.ts b/apps/api/test/modules/deployments/native-sdk-parity.test.ts index 4b0e0ec0d..6a1cf68ba 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: "NOT_FOUND" }); - await expect(dns.removeCredential("dns-a")).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect(dns.addCredential(input)).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(dns.removeCredential("dns-a")).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); } expect(h.dnsAdd).not.toHaveBeenCalled(); expect(h.dnsRemove).not.toHaveBeenCalled(); @@ -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: "NOT_FOUND" }); - await expect(credentials.update("credential-a", { name: "Renamed" })).rejects.toMatchObject({ code: "NOT_FOUND" }); - await expect(credentials.remove("credential-a")).rejects.toMatchObject({ code: "NOT_FOUND" }); - await expect(credentials.verify("credential-a")).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect(credentials.create({ provider: "docker-registry", name: "Registry", values: { secret: "value" } })).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(credentials.update("credential-a", { name: "Renamed" })).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(credentials.remove("credential-a")).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(credentials.verify("credential-a")).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); } expect(h.credentialCreate).not.toHaveBeenCalled(); expect(h.credentialUpdate).not.toHaveBeenCalled(); @@ -2492,20 +2492,6 @@ describe("server HTTP/native parity", () => { expect(h.serverRemove).not.toHaveBeenCalled(); }); - it("denies ordinary members host execution through native, SDK and raw HTTP operations", async () => { - h.members.set("org-a:alice", { id: "member-a", role: "member" }); - const local = await native(); - for (const servers of [local.servers, remote().servers]) { - await expect(servers.exec("server-a", { command: "whoami" })).rejects.toMatchObject({ code: "NOT_FOUND" }); - } - const response = await app.request("/api/system/servers/server-a/exec", { - method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ command: "whoami" }), - }); - expect(response.status).toBe(404); - expect(h.serverWithExecutor).not.toHaveBeenCalled(); - expect(h.audit.mock.calls.filter(([event]) => event.eventType === "server.exec")).toHaveLength(0); - }); - it("returns the same partial teardown result and keeps HTTP 409", async () => { h.serverWorkloads.mockResolvedValue([{ id: "project-a", name: "Application", appTemplateId: null }]); h.projectTeardown.mockResolvedValue({ rowDeleted: false, orphaned: [], unrecoverable: [{ error: "volume busy" }] }); @@ -2598,11 +2584,11 @@ describe("HTTP/native system parity", () => { for (const system of [local.system, remote().system]) { await expect(system.updateSettings({ productMode: "mail" })).rejects.toMatchObject({ statusCode: 403 }); await expect(system.updateEmailSettings({ host: null })).rejects.toMatchObject({ statusCode: 403 }); - await expect(system.resetSettings()).rejects.toMatchObject({ statusCode: role === "member" ? 404 : 403 }); + await expect(system.resetSettings()).rejects.toMatchObject({ statusCode: 403 }); await expect(system.health()).rejects.toMatchObject({ statusCode: 403 }); await expect(system.browse({ path: "/" })).rejects.toMatchObject({ statusCode: 403 }); await expect(system.listUntrackedEdgeSites()).rejects.toMatchObject({ statusCode: 403 }); - await expect(system.removeUntrackedEdgeSite({ hostname: "orphan.example.test" })).rejects.toMatchObject({ statusCode: role === "member" ? 404 : 403 }); + await expect(system.removeUntrackedEdgeSite({ hostname: "orphan.example.test" })).rejects.toMatchObject({ statusCode: 403 }); } } expect(h.settingsUpsert).not.toHaveBeenCalled(); diff --git a/apps/api/test/modules/deployments/resource-guidance.test.ts b/apps/api/test/modules/deployments/resource-guidance.test.ts index 68b7f89ee..3e0533151 100644 --- a/apps/api/test/modules/deployments/resource-guidance.test.ts +++ b/apps/api/test/modules/deployments/resource-guidance.test.ts @@ -237,21 +237,3 @@ it("retains resource guidance for a published partial rollout without turning it errorDetails: { resourceIssue: "storage-full" }, }); }); - - -it.each([true, false])("restores a container conflict on a Cloud=%s attempt without relabeling it as capacity", async (cloud) => { - const ctx = await attempt(cloud); - const details = { - projectId: ctx.project.id, - serviceId: "app-service", - containerNames: ["app-current", "app-duplicate"], - serverId: ctx.project.serverId ?? "ssh-original", - workspaceId: ctx.project.workspaceId, - }; - await onFailure(ctx, "More than one container matches the active service", undefined, { - errorCode: "SERVICE_CONTAINER_CONFLICT", errorDetails: details, - }); - expect(await getBuildSessionStatus(ctx.dep.id)).toMatchObject({ - status: "failed", errorCode: "SERVICE_CONTAINER_CONFLICT", errorDetails: details, - }); -}); diff --git a/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts b/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts index 5d07a4e0f..5ab30154e 100644 --- a/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts +++ b/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts @@ -32,6 +32,9 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: vi.fn() }, })); vi.mock("../../../src/lib/audit", () => ({ audit: { recordAsync: vi.fn(), record: vi.fn() } })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ + detectAndStoreFavicon: vi.fn(async () => {}), +})); vi.mock("@repo/platform/engine/modules/projects/cleanup-keep-set", () => ({ computeCleanupKeepSet: vi.fn(async () => ({ containers: new Set() })), })); diff --git a/apps/api/test/modules/dns/managed-ingress.test.ts b/apps/api/test/modules/dns/managed-ingress.test.ts index 9593efea9..9bc116e4c 100644 --- a/apps/api/test/modules/dns/managed-ingress.test.ts +++ b/apps/api/test/modules/dns/managed-ingress.test.ts @@ -94,6 +94,6 @@ describe("managed ingress through authenticated HTTP and the public SDK", () => headers, body: JSON.stringify({ credentialId: "no-secret" }), }); - expect(denied.status).toBe(404); + expect(denied.status).toBe(403); }); }); diff --git a/apps/api/test/modules/mcp/mcp-tools-filter.test.ts b/apps/api/test/modules/mcp/mcp-tools-filter.test.ts index be9f00362..719dad2d2 100644 --- a/apps/api/test/modules/mcp/mcp-tools-filter.test.ts +++ b/apps/api/test/modules/mcp/mcp-tools-filter.test.ts @@ -135,7 +135,6 @@ function principal( const granted = new Set([...(p.grantedRootTypes ?? []), ...Object.keys(wildcards)]); return { role: p.role ?? "restricted", - membershipRole: p.membershipRole, readOnly: p.readOnly ?? false, grantedRootTypes: granted, wildcardGrants: p.wildcardGrants ?? new Map(Object.entries(wildcards)), @@ -148,16 +147,6 @@ function principal( const RWA: Permission[] = ["read", "write", "admin"]; describe("filterToolsForPrincipal", () => { - it("hides server administration from members and their existing scoped tokens", () => { - const read = tool({ name: "server_read", method: "GET", perm: { root: "server", leaf: "server", grantRoot: "server", action: "read", wildcard: false } }); - const exec = tool({ name: "server_exec", method: "POST", perm: { root: "server", leaf: "server", grantRoot: "server", action: "admin", wildcard: false } }); - for (const caller of [ - principal({ role: "member" }), - principal({ role: "restricted", membershipRole: "member", grantedRootTypes: new Set(["server"]), wildcards: { server: RWA } }), - ]) expect(names(filterToolsForPrincipal([read, exec], caller))).toEqual(["server_read"]); - expect(names(filterToolsForPrincipal([read, exec], principal({ role: "admin" })))).toEqual(["server_exec", "server_read"]); - }); - it("owner sees everything", () => { const out = filterToolsForPrincipal(ALL, principal({ role: "owner" })); expect(out.length).toBe(ALL.length); diff --git a/apps/api/test/modules/mcp/mcp-workspaces.test.ts b/apps/api/test/modules/mcp/mcp-workspaces.test.ts index 8179cc373..80dbb98b3 100644 --- a/apps/api/test/modules/mcp/mcp-workspaces.test.ts +++ b/apps/api/test/modules/mcp/mcp-workspaces.test.ts @@ -138,22 +138,6 @@ describe("MCP workspace discovery", () => { expect(denied.isError).toBe(true); }); - it.each([false, true])("advertises administration in another workspace only for an unbound credential (bound=%s)", async bound => { - const owner = await seedOwner({ bound }); - await secondWorkspace(owner, "admin"); - await db.update(schema.member).set({ role: "member" }).where(and(eq(schema.member.userId, owner.userId), eq(schema.member.organizationId, owner.orgId))); - const listed = await (await rpc(owner, "tools/list")).json() as { result: { tools: { name: string }[] } }; - expect(listed.result.tools.some(tool => tool.name === "delete_projects_by_id")).toBe(!bound); - if (!bound) { - const group = await repos.projectGroup.create({ organizationId: owner.orgId, name: "Member project", slug: "member-project" }); - const project = await repos.project.create({ organizationId: owner.orgId, groupId: group.id, name: "Member project", slug: "member-project" }); - const denied = await call(owner, "delete_projects_by_id", { id: project.id, organizationId: owner.orgId }); - expect(denied).toMatchObject({ isError: true, data: { code: "NOT_FOUND" } }); - expect(forwarding.fetch).toHaveBeenCalled(); - expect(await repos.project.findById(project.id)).toMatchObject({ id: project.id }); - } - }); - it("shares the discovery contract with SDKs and respects fixed native scopes", async () => { const owner = await seedOwner({ bound: false }); const target = await secondWorkspace(owner); diff --git a/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts b/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts index 06ab6469c..0f616742c 100644 --- a/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts +++ b/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts @@ -133,7 +133,7 @@ describe("notifications shared SDK/HTTP operations", () => { expect(await c.native.listDefaults()).toEqual([value]); expect(await c.native.categories()).toEqual(await c.remote.categories()); await db.update(schema.member).set({ role: "member" }).where(eq(schema.member.userId, owner.userId)); - for (const client of [c.native, c.remote]) await expect(client.upsertDefault({ category: "deploy.failed", defaultEnabled: false })).rejects.toMatchObject({ code: "NOT_FOUND" }); + for (const client of [c.native, c.remote]) await expect(client.upsertDefault({ category: "deploy.failed", defaultEnabled: false })).rejects.toMatchObject({ code: "FORBIDDEN" }); }); it("does not verify a replacement configuration or hide normal delivery failures", async () => { diff --git a/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts b/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts index 10a53e784..a6858b068 100644 --- a/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts +++ b/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts @@ -465,9 +465,8 @@ describe("project promotion recovery", () => { const dump = await dumpSubgraph({ kind: "project", projectId }); const changed = structuredClone(dump); changed.tables.resource_usage.push({ id: "another-sample", projectId, cpu: 42 }); + changed.tables.project[0].favicon = "new favicon"; expect(projectPromotionDigest(changed)).toBe(projectPromotionDigest(dump)); - changed.tables.project[0].iconUrl = "https://cdn.example.test/new-icon.png"; - expect(projectPromotionDigest(changed)).not.toBe(projectPromotionDigest(dump)); changed.tables.project[0].localPath = "/another-source"; expect(projectPromotionDigest(changed)).not.toBe(projectPromotionDigest(dump)); }); diff --git a/apps/api/test/modules/projects/cloud-routing-regression.test.ts b/apps/api/test/modules/projects/cloud-routing-regression.test.ts index a047ea544..a08e2a3ed 100644 --- a/apps/api/test/modules/projects/cloud-routing-regression.test.ts +++ b/apps/api/test/modules/projects/cloud-routing-regression.test.ts @@ -113,7 +113,7 @@ describe("managed Cloud route port edits and repair", () => { await editRoutes(["app.opsh.io"]); expect(h.fixture.pages.create).toHaveBeenCalledOnce(); expect(h.fixture.routes.set).toHaveBeenLastCalledWith("app.opsh.io", expect.objectContaining({ - routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.fixture.workspaceId, port: 32001 } }], + routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.fixture.workspaceId, port: 32001 } }], })); expect(h.syncManagedEdge).not.toHaveBeenCalled(); }); @@ -124,7 +124,7 @@ describe("managed Cloud route port edits and repair", () => { expect(h.fixture.pages.connectDomain).toHaveBeenCalledWith(expect.any(String), { domain: "app.example.com" }); expect(h.fixture.workspace.network.update).toHaveBeenCalledWith(expect.objectContaining({ ingress_ports: [443, 32000] })); expect(h.fixture.routes.set).toHaveBeenCalledWith("app.example.com", expect.objectContaining({ - routes: expect.arrayContaining([expect.objectContaining({ action: { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 } })]), + routes: expect.arrayContaining([expect.objectContaining({ action: { kind: "proxy", workspace: h.fixture.workspaceId, port: 32000 } })]), })); }); @@ -165,8 +165,8 @@ describe("managed Cloud route port edits and repair", () => { h.domains.push({ ...h.domains[0]!, id: "domain-b", hostname: "console.opsh.io", targetPort: 9000, isPrimary: false }); expect(await retryProjectRouting(h.project.id, h.project.organizationId)).toEqual({ ok: true }); expect(h.fixture.routes.set.mock.calls.map(([host, table]) => [host, table.routes[0]?.action])).toEqual([ - ["app.opsh.io", { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 }], - ["console.opsh.io", { kind: "proxy", vm: h.fixture.workspaceId, port: 32001 }], + ["app.opsh.io", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32000 }], + ["console.opsh.io", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32001 }], ]); }); @@ -196,8 +196,8 @@ describe("managed Cloud route port edits and repair", () => { })); expect(await retryProjectRouting(h.project.id, h.project.organizationId)).toEqual({ ok: true }); expect(h.fixture.routes.set.mock.calls.map(([host, table]) => [host, table.routes[0]?.action])).toEqual([ - ["app.example.com", { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 }], - ["alias.example.com", { kind: "proxy", vm: h.fixture.workspaceId, port: 32000 }], + ["app.example.com", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32000 }], + ["alias.example.com", { kind: "proxy", workspace: h.fixture.workspaceId, port: 32000 }], ]); expect(h.fixture.pages.delete).not.toHaveBeenCalled(); }); diff --git a/apps/api/test/modules/projects/folder-upload.test.ts b/apps/api/test/modules/projects/folder-upload.test.ts index 9cc62e6a2..4360dc34f 100644 --- a/apps/api/test/modules/projects/folder-upload.test.ts +++ b/apps/api/test/modules/projects/folder-upload.test.ts @@ -80,11 +80,11 @@ afterAll(async () => { if (root) await rm(root, { recursive: true, force: true }); }); -async function open(name?: string) { +async function open() { const response = await fetch(`${origin}/api/projects/folder/session`, { method: "POST", headers: { ...owner.auth, "Content-Type": "application/json" }, - body: JSON.stringify({ ...(env.CLOUD_MODE ? { serverId: managedServerId } : {}), ...(name ? { name } : {}) }), + body: JSON.stringify(env.CLOUD_MODE ? { serverId: managedServerId } : {}), }); expect(response.status).toBe(200); const target = (await response.json()) as FolderSessionResult; @@ -117,33 +117,6 @@ 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); @@ -160,8 +133,7 @@ describe.each([false, true])("authenticated folder upload over HTTP (Cloud: %s)" it("rejects a truncated gzip, cleans temporary files, and allows a complete retry", async () => { const target = await open(); const response = await upload(target, archive.subarray(0, 10 * 1024 * 1024)); - expect(response.status).toBe(400); - expect(await response.json()).toMatchObject({ error: expect.stringMatching(/incomplete|truncated/i) }); + expect(response.status, await response.text()).toBe(400); const session = getFolderSession(target.sessionId)!; expect(session.uploaded).toBe(false); expect(session.uploading).toBe(false); diff --git a/apps/api/test/modules/projects/project-icon.test.ts b/apps/api/test/modules/projects/project-icon.test.ts deleted file mode 100644 index 4cbd56c71..000000000 --- a/apps/api/test/modules/projects/project-icon.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import "../jobs/_env"; -import { expect, it } from "vitest"; -import { Hono } from "hono"; -import { seedOwner, repos } from "../jobs/_harness"; -import { seedProject, seedDeployment } from "../../helpers/seed"; -import { listDeployments } from "@repo/platform/engine/modules/deployments/deployment.service"; -import { projectRoutes } from "../../../src/modules/projects/project.routes"; -import { handleApiError } from "../../../src/middleware/error-handler"; - -const app = new Hono().onError(handleApiError).route("/api/projects", projectRoutes); - -it("uses one icon URL across authenticated settings, reads and deployment history", async () => { - const owner = await seedOwner(); - const project = await seedProject(owner.orgId); - const custom = "https://cdn.example.test/project.svg"; - const update = (iconUrl: unknown, auth = owner.auth) => - app.request(`/api/projects/${project.id}`, { - method: "PATCH", - headers: { ...auth, "Content-Type": "application/json" }, - body: JSON.stringify({ iconUrl }), - }); - const assertIcon = (data: unknown, expected: string | null) => { - expect(data).toMatchObject({ iconUrl: expected }); - expect(data).not.toHaveProperty("favicon"); - expect(data).not.toHaveProperty("faviconCheckedAt"); - }; - const saved = await update(` ${custom} `); - expect(saved.status, await saved.clone().text()).toBe(200); - assertIcon((await saved.json()).data, custom); - assertIcon(await repos.project.findById(project.id), custom); - const read = await app.request(`/api/projects/${project.id}`, { headers: owner.auth }); - expect(read.status, await read.clone().text()).toBe(200); - assertIcon((await read.json()).data, custom); - await seedDeployment(project); - for (const options of [{ projectId: project.id }, {}]) { - const history = await listDeployments(owner.orgId, options); - assertIcon(history.rows[0], custom); - } - const stranger = await seedOwner(); - expect((await update("https://stranger.example.test/icon.png", stranger.auth)).status).toBe(404); - for (const unsafe of [ - "javascript:alert(1)", - "data:image/png;base64,AAA", - "https://user:password@example.test/i.png", - "/relative.png", - ]) - expect((await update(unsafe)).status).toBe(400); - assertIcon(await repos.project.findById(project.id), custom); - for (const reset of [null, ""]) { - expect((await update(custom)).status).toBe(200); - const cleared = await update(reset); - expect(cleared.status).toBe(200); - assertIcon((await cleared.json()).data, null); - assertIcon(await repos.project.findById(project.id), null); - const history = await listDeployments(owner.orgId, { projectId: project.id }); - assertIcon(history.rows[0], null); - } -}); diff --git a/apps/api/test/modules/projects/project-overview-logs.test.ts b/apps/api/test/modules/projects/project-overview-logs.test.ts index 555e7ddf9..a716386d1 100644 --- a/apps/api/test/modules/projects/project-overview-logs.test.ts +++ b/apps/api/test/modules/projects/project-overview-logs.test.ts @@ -19,6 +19,7 @@ vi.mock("@repo/db", () => ({ repos: { vi.mock("@repo/platform/engine/modules/projects/project.service", () => ({ listProjects: h.list, enrichProjectsBatch: h.enrich, deploymentIsBlocked: () => false })); vi.mock("@repo/platform/engine/lib/authorization", () => ({ authorization: { checkPermissionOnResource: h.canRead, authorize: async (ctx: ExecutionContext) => ctx } })); vi.mock("@repo/platform/engine/lib/cloud/projects", () => ({ fetchOrgCloudProjects: h.cloudProjects })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ refreshProjectFaviconIfStale: vi.fn() })); vi.mock("@repo/platform/engine/config/index", () => ({ env: h.env })); vi.mock("@repo/platform/engine/lib/oblien-user-client", () => ({ getAdminOblienClient: () => h.env.CLOUD_MODE ? { analytics: { streamToken: h.streamToken, requests: h.requests } } : null })); vi.mock("@repo/platform/engine/lib/cloud/client", () => ({ cloudClient: () => ({ analytics: { streamToken: h.streamToken, requests: h.requests } }) })); diff --git a/apps/api/test/modules/projects/shared-service-connections.test.ts b/apps/api/test/modules/projects/shared-service-connections.test.ts index 1df8a5fb8..fc4d00f0b 100644 --- a/apps/api/test/modules/projects/shared-service-connections.test.ts +++ b/apps/api/test/modules/projects/shared-service-connections.test.ts @@ -66,10 +66,9 @@ beforeEach(() => { describe("connections to a service inside a project", () => { it("offers all eligible projects while excluding the current project and read-only access", async () => { - h.candidates = ["source", "read-only", ...Array.from({ length: 120 }, (_, i) => `consumer-${i}`)].map(id => ({ id, name: id, environmentName: "production", appTemplateId: null, iconUrl: "https://cdn.example.test/icon.svg", framework: "nextjs" })); + h.candidates = ["source", "read-only", ...Array.from({ length: 120 }, (_, i) => `consumer-${i}`)].map(id => ({ id, name: id, environmentName: "production", appTemplateId: null })); const choices = await listConnectionCandidates(ctx, "source"); expect(choices).toHaveLength(120); - expect(choices[0]).toMatchObject({ iconUrl: "https://cdn.example.test/icon.svg", framework: "nextjs" }); expect(choices.some(choice => ["source", "read-only"].includes(choice.id))).toBe(false); expect(h.authorize).toHaveBeenCalledWith(ctx, { resourceType: "project", resourceId: "source", action: "write" }); }); diff --git a/apps/api/test/modules/system/server-exec-authorization.test.ts b/apps/api/test/modules/system/server-exec-authorization.test.ts deleted file mode 100644 index 754a3fcb9..000000000 --- a/apps/api/test/modules/system/server-exec-authorization.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import "../jobs/_env"; -import { beforeEach, expect, it, vi } from "vitest"; -import { Hono } from "hono"; -import { and, eq } from "@repo/db"; - -const host = vi.hoisted(() => ({ execute: vi.fn(), command: vi.fn() })); -vi.mock("@repo/platform/engine/lib/server-execution", async original => ({ - ...await original(), - withServerExecution: host.execute, -})); -vi.mock("@repo/platform/engine/lib/agent-exec", () => ({ execOnHost: host.command })); - -import { db, schema, seedOwner } from "../jobs/_harness"; -import { serverResourceRoutes } from "../../../src/modules/system/server-resource.routes"; -import { handleApiError } from "../../../src/middleware/error-handler"; - -const app = new Hono().onError(handleApiError).route("/api/system", serverResourceRoutes); -beforeEach(() => { - vi.clearAllMocks(); - host.command.mockResolvedValue({ output: "probe", exitCode: 0, timedOut: false, truncated: false, durationMs: 1 }); - host.execute.mockImplementation(async (_org, _id, work) => work({})); -}); - -it("rejects an authenticated member before host dispatch and preserves administrator execution", async () => { - const actor = await seedOwner(); - const id = `server-${actor.userId}`; - await db.insert(schema.servers).values({ id, organizationId: actor.orgId, name: "Fixture host", sshHost: "203.0.113.10", sshUser: "root" }); - const membership = and(eq(schema.member.userId, actor.userId), eq(schema.member.organizationId, actor.orgId)); - const execute = (serverId = id) => app.request(`/api/system/servers/${serverId}/exec`, { - method: "POST", headers: { ...actor.auth, "Content-Type": "application/json" }, body: JSON.stringify({ command: "id" }), - }); - await db.update(schema.member).set({ role: "member" }).where(membership); - expect((await execute()).status).toBe(404); - expect(host.execute).not.toHaveBeenCalled(); - expect(host.command).not.toHaveBeenCalled(); - await db.update(schema.member).set({ role: "admin" }).where(membership); - expect((await execute()).status).toBe(200); - expect(host.execute).toHaveBeenCalledOnce(); - expect(host.command).toHaveBeenCalledOnce(); - const other = await seedOwner(); - const otherServer = `server-${other.userId}`; - await db.insert(schema.servers).values({ id: otherServer, organizationId: other.orgId, name: "Other organization", sshHost: "203.0.113.11" }); - expect((await execute(otherServer)).status).toBe(404); - expect(host.command).toHaveBeenCalledOnce(); - await db.update(schema.member).set({ role: "member" }).where(membership); - expect((await execute()).status).toBe(404); - expect(host.command).toHaveBeenCalledOnce(); -}); diff --git a/apps/api/test/modules/system/server-managed-controls.test.ts b/apps/api/test/modules/system/server-managed-controls.test.ts index 364e1abd0..aeea020f2 100644 --- a/apps/api/test/modules/system/server-managed-controls.test.ts +++ b/apps/api/test/modules/system/server-managed-controls.test.ts @@ -72,11 +72,11 @@ let workloads: Map; let vm: any; let handle: any; -const jwt = (id = vmId, type = "vm") => +const jwt = (id = vmId, type = "workspace") => `e30.${Buffer.from( JSON.stringify({ type, - vm_id: id, + workspace_id: id, token: runtimeToken, exp: Math.floor(Date.now() / 1000) + 3600, }), @@ -261,8 +261,8 @@ beforeEach(async () => { { ip: "8.8.4.4", countryCode: "US" }, { ip: "1.1.1.1", countryCode: "AU" }, ]), - vms: { get: vi.fn(async () => vm), invalidateRuntime: vi.fn() }, - vm: vi.fn(() => handle), + workspaces: { get: vi.fn(async () => vm), invalidateRuntime: vi.fn() }, + workspace: vi.fn(() => handle), }; h.namespaceClient.mockImplementation(async () => ({ client: h.client, namespace })); h.canWork.mockResolvedValue(undefined); @@ -402,7 +402,7 @@ describe("managed server controls through real HTTP, policy and SQL ownership", ).toBe(400); expect(handle.ssh.setPassword).not.toHaveBeenCalled(); }); - it("reveals only a VM gateway token and fences repeat rotations", async () => { + it("reveals only a workspace gateway token and fences repeat rotations", async () => { const revealed = await request("managed/runtime-api/credential", "POST", { confirm: true }); expect(revealed.status, JSON.stringify(revealed.body)).toBe(200); expect(revealed.body.endpoint).toBe("https://runtime.example.test"); @@ -414,19 +414,12 @@ describe("managed server controls through real HTTP, policy and SQL ownership", "MANAGED_RUNTIME_TOKEN_CHANGED", ); expect(handle.apiAccess.rotateToken).toHaveBeenCalledTimes(1); - expect(h.client.vms.invalidateRuntime).toHaveBeenCalledWith(vmId); + expect(h.client.workspaces.invalidateRuntime).toHaveBeenCalledWith(vmId); handle.apiAccess.getToken.mockResolvedValue({ token: jwt("another-vm") }); expect( (await request("managed/runtime-api/credential", "POST", { confirm: true })).status, ).toBe(502); }); - it.each(["workspace", "namespace", "account"])("rejects %s credentials even with the selected VM ID", async (type) => { - handle.apiAccess.getToken.mockResolvedValue({ token: jwt(vmId, type) }); - const result = await request("managed/runtime-api/credential", "POST", { confirm: true }); - expect(result.status).toBe(502); - expect(result.body.code).toBe("MANAGED_CREDENTIAL_UNAVAILABLE"); - expect(JSON.stringify(result.body)).not.toContain(runtimeToken); - }); it("keeps the original network response for clients that do not request diagnostics", async () => { const legacy = { internetAccess: true, ingressPorts: [80, 9990] }; expect((await request("network-settings")).body).toEqual(legacy); @@ -489,7 +482,7 @@ describe("managed server controls through real HTTP, policy and SQL ownership", "MANAGED_RUNTIME_TOKEN_CHANGED", ); expect(handle.apiAccess.rotateToken).toHaveBeenCalledTimes(1); - expect(h.client.vms.invalidateRuntime).toHaveBeenCalledWith(vmId); + expect(h.client.workspaces.invalidateRuntime).toHaveBeenCalledWith(vmId); const recovered = await request("managed/runtime-api/credential", "POST", { confirm: true }); expect(recovered.status).toBe(200); expect(recovered.body.revision).not.toBe(input.expectedRevision); diff --git a/apps/api/test/modules/tokens/mint-org-binding.test.ts b/apps/api/test/modules/tokens/mint-org-binding.test.ts index b0998efd1..88e421d30 100644 --- a/apps/api/test/modules/tokens/mint-org-binding.test.ts +++ b/apps/api/test/modules/tokens/mint-org-binding.test.ts @@ -188,16 +188,6 @@ beforeEach(() => { }); describe("finding 1: grant width is checked in the org the binding is written to", () => { - it("refuses server administration grants for an ordinary member", async () => { - const grants = [{ resourceType: "server", resourceId: "*", permissions: ["admin"] }]; - const refused = await authorize(OWNER_ORG, { clientId: "cli", organizationId: VICTIM_ORG, grants }); - expect(refused.status).toBe(403); - expect(refused.body.code).toBe("GRANT_EXCEEDS_ACCESS"); - expect(upsertOAuthBindingWithGrants).not.toHaveBeenCalled(); - const allowed = await authorize(OWNER_ORG, { clientId: "cli", organizationId: OWNER_ORG, grants }); - expect(allowed.status).toBe(200); - }); - /** * `billing` and `audit` are the two types `roleAllowsResourceType` denies a * member, and both are grantable — so they isolate "authority comes from the diff --git a/apps/api/tsconfig.json b/apps/api/tsconfig.json index 94a494d7e..7c483898a 100644 --- a/apps/api/tsconfig.json +++ b/apps/api/tsconfig.json @@ -15,6 +15,6 @@ "declaration": false, "declarationMap": false }, - "include": ["src/**/*.ts", "scripts/cloud-readiness.ts"], + "include": ["src/**/*.ts"], "exclude": ["node_modules", "dist"] } diff --git a/apps/cli/src/commands/domain.ts b/apps/cli/src/commands/domain.ts index 9b6011a8c..5661d5b14 100644 --- a/apps/cli/src/commands/domain.ts +++ b/apps/cli/src/commands/domain.ts @@ -9,7 +9,7 @@ import { exitCommand, rethrowCommandExit } from "../lib/command-exit"; import { Command, Option } from "commander"; import { UploadCertBody, parseInput } from "@repo/contracts"; import { readFileSync } from "node:fs"; -import { prepareCustomDomainEndpoint } from "../lib/custom-domain-endpoint"; +import { attachCustomDomainEndpoint } from "../lib/custom-domain-endpoint"; import { getShipClient } from "../lib/ship-client"; import { spin, fail, confirmOrExit, printResult } from "../lib/cmd-helpers"; import type { Domain, DomainRecords, DomainSsl } from "@repo/sdk/client"; @@ -71,17 +71,14 @@ const addCmd = new Command("add") .argument("", "Domain hostname (e.g. app.example.com)") .requiredOption("-p, --project ", "Project ID to attach the domain to") .option("--primary", "Mark this domain as the project's primary", false) - .option("--service ", "Target service within the selected project") - .option("--port ", "Container port to route (required for ambiguous service ports)", positiveInteger) .action(async (hostname: string, opts) => { const sp = spin(`Adding ${hostname}…`); try { const ship = getShipClient(); - const attach = await prepareCustomDomainEndpoint(ship, opts.project, { service: opts.service, port: opts.port }); const res = await ship.domains.create(opts.project, { hostname, isPrimary: !!opts.primary }); - await attach(res.domain.hostname); + const routed = await attachCustomDomainEndpoint(ship, opts.project, res.domain.hostname); sp?.succeed(`Added ${res.domain.hostname}`); - info(` ${res.domain.hostname} is configured to be routed on the next deploy.`); + if (routed) info(` ${res.domain.hostname} is configured to be routed on the next deploy.`); if (isJsonMode()) { printJson(res); return; diff --git a/apps/cli/src/commands/login.ts b/apps/cli/src/commands/login.ts index fb5e18403..e8da11cd3 100644 --- a/apps/cli/src/commands/login.ts +++ b/apps/cli/src/commands/login.ts @@ -18,7 +18,6 @@ import { fetchCaps } from "../lib/caps"; import { err, info, isJsonMode, ok, printJson } from "../lib/output"; import { exitCommand } from "../lib/command-exit"; import { readSecret } from "../lib/command-input"; -import { discoverPublicInstanceApi } from "../lib/public-instance-api"; export interface LoginOptions { token?: string; @@ -81,7 +80,7 @@ export async function runLogin(options: LoginOptions = {}): Promise { const existing = getContext(contextName); const local = !opts.cloud && !opts.apiUrl && !existing.apiUrl ? localConnectionEndpoints() : undefined; - let apiUrl = opts.cloud ? CLOUD_API_URL : opts.apiUrl || existing.apiUrl || local!.apiUrl; + const apiUrl = opts.cloud ? CLOUD_API_URL : opts.apiUrl || existing.apiUrl || local!.apiUrl; const normalizedApi = new HttpClient({ baseUrl: apiUrl }).apiUrl; const sameEndpoint = existing.apiUrl && new HttpClient({ baseUrl: existing.apiUrl }).apiUrl === normalizedApi; @@ -90,7 +89,7 @@ export async function runLogin(options: LoginOptions = {}): Promise { : opts.dashboardUrl || (sameEndpoint ? existing.dashboardUrl : undefined) || local?.dashboardUrl || - normalizedApi.slice(0, -4).replace(/\/api\/proxy$/, ""); + normalizedApi.slice(0, -4); let token: string | undefined = opts.tokenFile ? readSecret(opts.tokenFile) : opts.token; @@ -133,23 +132,13 @@ export async function runLogin(options: LoginOptions = {}): Promise { // Validate the token against an authenticated endpoint before storing. // 200 → valid; 403 → valid but lacks settings:read scope (still usable). let scoped = false; - for (let attempt = 0; ; attempt++) { - try { - const client = new OpenshipClient({ baseUrl: apiUrl, token, timeoutMs: 8000 }); - await client.tokens.list(); - break; - } catch (error) { - if (error instanceof ApiError && error.status === 403) { - scoped = true; - break; - } - // A missing/non-JSON route can mean the supplied URL is the dashboard. - // An actual authentication refusal must never switch endpoints. - if (attempt === 0 && !opts.cloud && error instanceof ApiError && - (error.status === 404 || error.message === "Invalid JSON response")) { - const discovered = await discoverPublicInstanceApi(apiUrl); - if (discovered) { apiUrl = discovered; continue; } - } + try { + const client = new OpenshipClient({ baseUrl: apiUrl, token, timeoutMs: 8000 }); + await client.tokens.list(); + } catch (error) { + if (error instanceof ApiError && error.status === 403) { + scoped = true; + } else { err( error instanceof ApiError && error.status === 401 ? "Token rejected by the API. Check that it is valid and not revoked." diff --git a/apps/cli/src/commands/service.ts b/apps/cli/src/commands/service.ts index 5243bdc7a..9f830de06 100644 --- a/apps/cli/src/commands/service.ts +++ b/apps/cli/src/commands/service.ts @@ -25,7 +25,6 @@ import { getShipClient, ApiError, hasShipCredentials } from "../lib/ship-client" import { isJsonMode, printJson, printTable, ok, err, info } from "../lib/output"; import { collect, parsePairs, readJsonInput } from "../lib/command-input"; import { fail, confirmOrExit, reportResult, reportExecResult } from "../lib/cmd-helpers"; -import { resolveServiceRef } from "../lib/service-ref"; // ─── Shared helpers ────────────────────────────────────────────────────────── @@ -87,7 +86,19 @@ async function listServices(projectId: string): Promise { /** Resolve a service ref (name or svc_ id) to its row within the stack. */ async function resolveService(projectId: string, ref: string): Promise { - return resolveServiceRef(getShipClient(), projectId, ref); + if (/^svc_/.test(ref)) return getShipClient().services.get(projectId, ref); + const services = await listServices(projectId); + const byId = services.find((s) => s.id === ref); + if (byId) return byId; + const byName = services.filter((s) => s.name === ref); + if (byName.length === 1) return byName[0]; + if (byName.length > 1) { + err(` "${ref}" matches ${byName.length} services — pass the service id (svc_…).`); + exitCommand(1); + } + const known = services.map((s) => s.name).join(", ") || "(none)"; + err(` No service "${ref}" in this stack. Services: ${known}`); + exitCommand(1); } // ─── list / get ─────────────────────────────────────────────────────────────── diff --git a/apps/cli/src/commands/up.ts b/apps/cli/src/commands/up.ts index 5af9fdc1a..51864365e 100644 --- a/apps/cli/src/commands/up.ts +++ b/apps/cli/src/commands/up.ts @@ -11,7 +11,7 @@ import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { ensureDashboard } from "../lib/dashboard"; -import { installAndStart, serviceHeldPorts } from "../lib/service"; +import { installAndStart } from "../lib/service"; import { composeUp, composePrefetch, @@ -44,7 +44,6 @@ import { LocalExecutor } from "@repo/adapters"; import { resolveInstallInputs, headlessProvision, - provisionInstanceDomain, HeadlessInputError, } from "../lib/instance-provision"; import { mintBareInternalToken } from "../lib/internal-token"; @@ -285,26 +284,6 @@ export const upCommand = new Command("up") if (opts.fromSource || opts.source) return runFromSource(opts); if (opts.foreground) return runForeground(opts); const headless = !!(opts.nonInteractive || opts.yes); - // Validate requested provisioning before pulling images or stopping services. - if (headless || opts.managedEdge) { - try { - if (opts.managedEdge) { - opts.publicUrl = effectivePublicUrl(opts.publicUrl); - if (!opts.publicUrl || new URL(opts.publicUrl).protocol !== "https:") - throw new HeadlessInputError("--managed-edge requires --public-url https://your-domain (or an existing saved HTTPS URL)."); - if (opts.domainKind && opts.domainKind !== "custom") - throw new HeadlessInputError("--managed-edge requires --domain-kind custom."); - if (opts.hostname && opts.hostname !== new URL(opts.publicUrl).hostname) - throw new HeadlessInputError("--hostname must match --public-url when using --managed-edge."); - opts.trustProxy = true; - } - if (headless) upInstallInputs(opts); - } catch (error) { - reportCliMessage("error", (error as Error).message); - process.exit(1); - } - } - // Install method: Compose is the default when it can actually work (Docker on // Linux — the edge container needs host networking); else bare. `planMethod` // owns the decision so `--dry-run` predicts the same one. @@ -340,10 +319,9 @@ export const upCommand = new Command("up") if (!token) { reportCliMessage("warn", chalk.yellow( - "\n Couldn't read the stack's internal token (compose/.env). Run this command as the installation owner (or sudo) to finish admin setup.\n", + "\n Couldn't read the stack's internal token (compose/.env) — create the admin from the dashboard.\n", ), ); - process.exit(1); } else { await runHeadlessProvision( opts, @@ -351,18 +329,6 @@ export const upCommand = new Command("up") { token, method: "compose" }, ); } - } else if (opts.managedEdge) { - const result = await provisionInstanceDomain({ - port: started.apiPort, dashPort: started.dashPort, token: composeInternalToken() ?? undefined, - domain: { kind: "custom", hostname: new URL(opts.publicUrl!).hostname, acmeEmail: opts.acmeEmail, - edge: opts.edge === "takeover" || opts.edge === "migrate" ? opts.edge : "cancel" }, - onLog: message => console.log(chalk.dim(` ${message}`)), - }); - for (const warning of result.warnings) reportCliMessage("warn", warning); - if (!result.domainRegistered) { - reportCliMessage("error", "Managed domain registration did not complete. If this is a new install, run `openship` and choose Create first admin, then retry this command."); - process.exit(1); - } } return; } @@ -370,21 +336,6 @@ export const upCommand = new Command("up") if (headless) await runHeadlessProvision(opts, started, { method: "bare" }); }); -/** Flags and preflight share one provisioning interpretation. */ -function upInstallInputs(opts: UpOpts) { - return resolveInstallInputs({ - adminName: opts.adminName, - adminEmail: opts.adminEmail, - adminPassword: opts.adminPassword, - domainKind: opts.domainKind ?? (opts.managedEdge ? "custom" : undefined), - hostname: opts.hostname, - slug: opts.slug, - publicUrl: opts.publicUrl, - acmeEmail: opts.acmeEmail, - edge: opts.edge, - }); -} - /** * Headless install (bare service): after `startService` installs + supervises * the process, create the admin + register the domain from the flags, so a box @@ -398,7 +349,17 @@ export async function runHeadlessProvision( ): Promise { let inputs; try { - inputs = upInstallInputs(opts); + inputs = resolveInstallInputs({ + adminName: opts.adminName, + adminEmail: opts.adminEmail, + adminPassword: opts.adminPassword, + domainKind: opts.domainKind, + hostname: opts.hostname, + slug: opts.slug, + publicUrl: opts.publicUrl, + acmeEmail: opts.acmeEmail, + edge: opts.edge, + }); } catch (err) { if (err instanceof HeadlessInputError) { reportCliMessage("error", chalk.red(`\n ${err.message}\n`)); @@ -416,10 +377,8 @@ export async function runHeadlessProvision( method: extra?.method, onLog: (m) => console.log(chalk.dim(` ${m}`)), }); - for (const w of result.warnings) reportCliMessage("warn", chalk.yellow(` ⚠ ${w}`)); - if (opts.managedEdge && !result.domainRegistered) - throw new Error("Managed domain registration did not complete. Retry after resolving the domain warning above."); console.log(chalk.green(`\n ✓ Openship provisioned${result.liveUrl ? `: ${result.liveUrl}` : "."}`)); + for (const w of result.warnings) reportCliMessage("warn", chalk.yellow(` ⚠ ${w}`)); } catch (err) { observeCaughtError(err, "cli/commands/up"); reportCliMessage("error", chalk.red(`\n Headless provisioning failed: ${(err as Error).message}\n`)); @@ -682,7 +641,7 @@ async function runCompose(opts: UpOpts & { yes?: boolean }): Promise<{ apiPort: chalk.dim(" Images: api + dashboard + edge (OpenResty on :80/:443)\n") + chalk.dim(" Manage: openship stop · openship update · openship status\n") + // In headless mode the admin is bootstrapped below — don't tell the user to do it by hand. - (headless ? "" : chalk.dim(" Admin setup: run `openship` → Create first admin, or use `openship up --non-interactive --admin-email ` with OPENSHIP_ADMIN_PASSWORD set.\n")), + (headless ? "" : chalk.dim(" Create an admin: open the dashboard and register the first account.\n")), ); return { apiPort: res.apiPort, dashPort: res.dashPort }; } @@ -729,13 +688,9 @@ export async function startService( // No permanent port: switch off any occupied default / flag / remembered port // BEFORE writing the service unit, so the chosen ports are baked into its args. - // A re-run finds our own running service on its ports. installAndStart replaces - // that instance, so they're reclaimable rather than busy; otherwise every re-run - // waited out waitPortFree and then moved the install to new ports (#1570). const resolved = await resolvePorts({ api: opts.port ? Number(opts.port) : undefined, dashboard: opts.dashboardPort ? Number(opts.dashboardPort) : undefined, - reclaimable: await serviceHeldPorts(), }); const port = String(resolved.api); const dashPort = String(resolved.dashboard); diff --git a/apps/cli/src/commands/wizard.ts b/apps/cli/src/commands/wizard.ts index ba716acb0..814fe0f28 100644 --- a/apps/cli/src/commands/wizard.ts +++ b/apps/cli/src/commands/wizard.ts @@ -1231,7 +1231,7 @@ export async function runControl(): Promise { `${chalk.dim("Dashboard".padEnd(11))}${dashUrl}\n` + (ports.api ? `${chalk.dim("API".padEnd(11))}http://localhost:${ports.api}\n` : "") + `${chalk.dim("Manager".padEnd(11))}${managerLabel}`, - "Openship is installed", + "Openship is already set up", ); // Crash-looping on a corrupt DB is the one case where "Start" won't help — @@ -1279,7 +1279,6 @@ export async function runControl(): Promise { : { value: "start", label: "Start the service" }, { value: "stop", label: "Stop the service", hint: "won't restart on boot" }, ...(corrupted ? [] : [{ value: "repair", label: "Repair database", hint: "backup → heal a corrupt DB" }]), - { value: "create-admin", label: "Create first admin", hint: "finish a new install; existing accounts stay intact" }, { value: "reset", label: "Reset admin password", hint: "sets a local email + password login" }, { value: "reconfigure", label: "Re-run setup", hint: "reconfigure domain / cloud / admin" }, { value: "quit", label: "Quit" }, @@ -1288,16 +1287,6 @@ export async function runControl(): Promise { ); switch (action) { - case "create-admin": { - const admin = await promptLocalAdmin(); - const result = await bootstrapAdmin(apiPort, admin); - outro(result.ok - ? result.message === "already-exists" - ? "An admin already exists. Use Reset admin password if you need to recover access." - : `Admin created. Sign in at ${primaryUrl}.` - : `Could not create the admin: ${result.message}`); - return; - } case "repair": { const res = await runRepair(); outro(res.healed ? chalk.green(res.detail) : chalk.yellow(res.detail)); diff --git a/apps/cli/src/lib/custom-domain-endpoint.ts b/apps/cli/src/lib/custom-domain-endpoint.ts index b979265ff..1b1c1a8cf 100644 --- a/apps/cli/src/lib/custom-domain-endpoint.ts +++ b/apps/cli/src/lib/custom-domain-endpoint.ts @@ -1,79 +1,71 @@ -import { firstServicePort, resolveRedirectStatus, safeErrorMessage } from "@repo/core"; +import { safeErrorMessage } from "@repo/core"; import type { UpdateProjectInput } from "@repo/contracts"; import type { CliShipClient } from "./ship-client"; -import { resolveServiceRef } from "./service-ref"; +import { reportCliMessage } from "./output"; type PublicEndpoint = NonNullable[number]; -export interface CustomDomainTarget { service?: string; port?: number } - -/** Validate the target before claiming a hostname, then save through the same - * project/service API used by the dashboard. DNS verification and deployment - * remain explicit subsequent steps. */ -export async function prepareCustomDomainEndpoint( - ship: Pick, - projectId: string, - options: CustomDomainTarget = {}, -): Promise<(hostname: string) => Promise> { - const { project } = await ship.projects.getInfo(projectId); - if (!options.service && project.projectType !== "app") - throw new Error("This is a multi-service project. Pass --service and --port to select its route."); - if (!options.service && project.options.workloadType === "worker") - throw new Error("This worker has no public route. Configure a web workload before adding a domain."); - const service = options.service ? await resolveServiceRef(ship, projectId, options.service) : undefined; - const hasServer = !!service || project.options.hasServer; - const endpoints: PublicEndpoint[] = service?.publicEndpoints?.map(endpoint => ({ ...endpoint, redirectStatus: endpoint.redirectStatus !== undefined ? resolveRedirectStatus(endpoint.redirectStatus) : undefined })) ?? - (service ? [] : (project as typeof project & { publicEndpoints?: PublicEndpoint[] }).publicEndpoints ?? []); - const ports = service ? [...new Set([ - ...(service.ports ?? []).map(spec => firstServicePort([spec])), - ...(service.publicEndpoints ?? []).map(endpoint => endpoint.port), - Number(service.exposedPort), - ].filter((value): value is number => Number.isInteger(value) && Number(value) > 0 && Number(value) <= 65535))] : []; - const port = options.port ?? (service - ? ports.length === 1 ? ports[0] : undefined - : Number(project.options.productionPort || project.port)); - if (hasServer && (!Number.isInteger(port) || !port || port < 1 || port > 65535)) - throw new Error("Choose a valid container port with --port <1-65535>; services with multiple ports require an explicit target."); - if (!hasServer && options.port !== undefined) - throw new Error("A static project routes its output directory; --port requires a web service."); - - return async hostname => { - const host = hostname.trim().toLowerCase(); - try { - // Project info adds UI metadata. Send only the accepted save fields, keeping - // every existing target, hostname, redirect, and endpoint position intact. - const publicEndpoints: PublicEndpoint[] = endpoints.map((endpoint) => ({ - ...(endpoint.port !== undefined ? { port: endpoint.port } : {}), - ...(endpoint.targetPath !== undefined ? { targetPath: endpoint.targetPath } : {}), - ...(endpoint.domain !== undefined ? { domain: endpoint.domain } : {}), - ...(endpoint.customDomain !== undefined ? { customDomain: endpoint.customDomain } : {}), - ...(endpoint.domainType !== undefined ? { domainType: endpoint.domainType } : {}), - ...(endpoint.redirectTo !== undefined ? { redirectTo: endpoint.redirectTo } : {}), - ...(endpoint.redirectStatus !== undefined ? { redirectStatus: endpoint.redirectStatus } : {}), - })); - const endpoint = { domainType: "custom" as const, customDomain: host, ...(hasServer ? { port } : { targetPath: "/" }) }; - const index = publicEndpoints.findIndex(value => value.customDomain?.toLowerCase() === host); - if (index >= 0) { - if (options.port === undefined || publicEndpoints[index]!.port === port) return; - publicEndpoints[index] = { ...publicEndpoints[index], ...endpoint }; - } else publicEndpoints.push(endpoint); - if (service) await ship.services.update(projectId, service.id, { exposed: true, publicEndpoints }); - else await ship.projects.update(projectId, { publicEndpoints }); - } catch (error) { - throw new Error( - `Domain ${host} row still exists, but attaching its route failed: ${safeErrorMessage(error)}. Retry in the dashboard project ${projectId} Domains tab: configure this domain's target and save.`, - { cause: error }, - ); - } - }; -} - -/** Existing callers claim a domain before attaching its endpoint. */ +/** Attach the routing endpoint after claiming the domain, as the dashboard does. */ export async function attachCustomDomainEndpoint( - ship: Pick, + ship: Pick, projectId: string, hostname: string, ): Promise { - await (await prepareCustomDomainEndpoint(ship, projectId))(hostname); - return true; + const host = hostname.trim().toLowerCase(); + try { + const { project } = await ship.projects.getInfo(projectId); + const endpoints = + (project as typeof project & { publicEndpoints?: PublicEndpoint[] }).publicEndpoints ?? []; + if (endpoints.some((endpoint) => endpoint.customDomain?.toLowerCase() === host)) return true; + + if (project.options.workloadType === "worker") { + reportCliMessage( + "warn", + `Domain ${host} was added, but this worker has no public route. Configure a web workload and port before attaching it.`, + ); + return false; + } + + if (project.projectType !== "app") { + reportCliMessage( + "warn", + `Domain ${host} was added, but ${project.name || projectId} is a multi-service project, so routes belong to a service. Attach it to a service in the dashboard.`, + ); + return false; + } + + const hasServer = project.options.hasServer; + const port = Number(project.options.productionPort || project.port); + if (hasServer && (!Number.isInteger(port) || port < 1 || port > 65535)) { + reportCliMessage( + "warn", + `Domain ${host} was added, but the project has no valid server port and no public route. Configure a port in the dashboard Domains tab.`, + ); + return false; + } + + // Project info adds UI metadata. Send only the accepted save fields, keeping + // every existing target, hostname, redirect, and endpoint position intact. + const publicEndpoints: PublicEndpoint[] = endpoints.map((endpoint) => ({ + ...(endpoint.port !== undefined ? { port: endpoint.port } : {}), + ...(endpoint.targetPath !== undefined ? { targetPath: endpoint.targetPath } : {}), + ...(endpoint.domain !== undefined ? { domain: endpoint.domain } : {}), + ...(endpoint.customDomain !== undefined ? { customDomain: endpoint.customDomain } : {}), + ...(endpoint.domainType !== undefined ? { domainType: endpoint.domainType } : {}), + ...(endpoint.redirectTo !== undefined ? { redirectTo: endpoint.redirectTo } : {}), + ...(endpoint.redirectStatus !== undefined ? { redirectStatus: endpoint.redirectStatus } : {}), + })); + publicEndpoints.push({ + domainType: "custom", + customDomain: host, + ...(hasServer ? { port } : { targetPath: "/" }), + }); + await ship.projects.update(projectId, { publicEndpoints }); + return true; + } catch (error) { + throw new Error( + `Domain ${host} row still exists, but attaching its route failed: ${safeErrorMessage(error)}. Retry in the dashboard project ${projectId} Domains tab: configure this domain's target and save.`, + { cause: error }, + ); + } } diff --git a/apps/cli/src/lib/instance-provision.ts b/apps/cli/src/lib/instance-provision.ts index 33b13c440..b9801ebc7 100644 --- a/apps/cli/src/lib/instance-provision.ts +++ b/apps/cli/src/lib/instance-provision.ts @@ -268,6 +268,8 @@ export async function headlessProvision(opts: { }): Promise { const { port, inputs, token } = opts; const log = opts.onLog ?? (() => {}); + const warnings: string[] = []; + log("Waiting for the API to become healthy…"); if (!(await waitHealthy(port))) { throw new HeadlessInputError("The API did not become healthy in time — check `openship logs`."); @@ -277,24 +279,8 @@ export async function headlessProvision(opts: { const admin = await bootstrapOrReset(port, inputs.admin, token); if (!admin.ok) throw new HeadlessInputError(`Could not create the admin account: ${admin.message}`); - return { adminReady: true, ...await provisionInstanceDomain({ ...opts, domain: inputs.domain }) }; -} - -/** Register routing independently of credentials, including managed-edge - * re-runs on an already initialized Compose install. */ -export async function provisionInstanceDomain(opts: { - port: string; - dashPort?: string; - domain: InstallInputs["domain"]; - token?: string; - onLog?: (msg: string) => void; - onSlugTaken?: (taken: string) => Promise; -}): Promise> { - const { port, token } = opts; - const log = opts.onLog ?? (() => {}); - const warnings: string[] = []; const dashPort = opts.dashPort ? Number(opts.dashPort) : undefined; - const d = opts.domain; + const d = inputs.domain; let liveUrl: string | undefined; let domainRegistered = false; @@ -406,5 +392,5 @@ export async function provisionInstanceDomain(opts: { } } - return { domainRegistered, liveUrl, warnings }; + return { adminReady: true, domainRegistered, liveUrl, warnings }; } diff --git a/apps/cli/src/lib/public-instance-api.ts b/apps/cli/src/lib/public-instance-api.ts deleted file mode 100644 index 6df441097..000000000 --- a/apps/cli/src/lib/public-instance-api.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { SDK_CAPABILITIES } from "@repo/contracts"; -import { HttpClient } from "@repo/sdk/client"; - -/** A public dashboard may mount the API beneath /api/proxy. Probe without - * credentials and never follow redirects or infer another origin. */ -export async function discoverPublicInstanceApi(baseUrl: string): Promise { - const base = new HttpClient({ baseUrl }).apiUrl.slice(0, -4); - if (/\/(?:api|api\/proxy)$/.test(new URL(baseUrl).pathname.replace(/\/+$/, ""))) return null; - const candidate = `${base}/api/proxy`; - try { - const response = await fetch(`${candidate}/api/health`, { - headers: { Accept: "application/json" }, redirect: "error", signal: AbortSignal.timeout(3_000), - }); - if (!response.ok) return null; - const health = await response.json() as { status?: string; sdk?: { protocol?: number } }; - return health?.status === "ok" && health.sdk?.protocol === SDK_CAPABILITIES.protocol ? candidate : null; - } catch { - // diagnostics-ignore: Optional credential-free discovery; keep the original login failure when this probe cannot identify an API. - return null; - } -} diff --git a/apps/cli/src/lib/service-ref.ts b/apps/cli/src/lib/service-ref.ts deleted file mode 100644 index 619ebbc17..000000000 --- a/apps/cli/src/lib/service-ref.ts +++ /dev/null @@ -1,13 +0,0 @@ -import type { CliShipClient } from "./ship-client"; - -/** Resolve only within the selected project; never fall back to another stack. */ -export async function resolveServiceRef(ship: Pick, projectId: string, ref: string) { - if (/^svc_/.test(ref)) return ship.services.get(projectId, ref); - const services = await ship.services.list(projectId); - const byId = services.find(service => service.id === ref); - if (byId) return byId; - const matches = services.filter(service => service.name === ref); - if (matches.length === 1) return matches[0]!; - if (matches.length > 1) throw new Error(`"${ref}" matches ${matches.length} services — pass the service id (svc_…).`); - throw new Error(`No service "${ref}" in this stack. Services: ${services.map(service => service.name).join(", ") || "(none)"}`); -} diff --git a/apps/cli/src/lib/service.ts b/apps/cli/src/lib/service.ts index 254594a1c..b807497ba 100644 --- a/apps/cli/src/lib/service.ts +++ b/apps/cli/src/lib/service.ts @@ -15,7 +15,6 @@ import { spawnSync } from "node:child_process"; import { existsSync, mkdirSync, writeFileSync, rmSync, readFileSync } from "node:fs"; import { homedir } from "node:os"; import { join, resolve } from "node:path"; -import { LocalExecutor, probeListeningPortOwners } from "@repo/adapters"; import { readCliInstall } from "./cli-install"; import { IS_ALT_HOME, LOG_DIR, OS_DIR } from "./paths"; @@ -391,50 +390,6 @@ export function serviceStatus(): { kind: ServiceKind; installed: boolean; runnin return { kind, installed: false, running: false }; } -/** Only reclaim remembered listeners owned by the installed service's process tree. - * A saved port alone proves no ownership (for example, after `up --no-ui`). - * Unknown service PIDs or incomplete listener ownership use normal port resolution. */ -export async function serviceHeldPorts(): Promise { - const kind = detectKind(); - let pid: number | null = null; - if (kind === "launchd") pid = launchdPid(); - else if (kind === "systemd-user" || kind === "systemd-system") { - const args = kind === "systemd-user" ? ["--user"] : []; - const result = run("systemctl", [...args, "show", SYSTEMD_NAME, "--property=MainPID", "--value"]); - if (result.ok && /^\d+$/.test(result.out)) pid = Number(result.out); - } - // Scheduled Tasks do not expose an authoritative process ID through schtasks. - if (!pid || !Number.isSafeInteger(pid) || pid <= 1) return []; - const processes = run("ps", ["-axo", "pid=,ppid="]); - if (!processes.ok) return []; - const parents = new Map(); - for (const line of processes.out.split("\n")) { - const match = line.match(/^\s*(\d+)\s+(\d+)\s*$/); - if (match) parents.set(Number(match[1]), Number(match[2])); - } - if (!parents.has(pid)) return []; - const belongsToService = (owner: number | null): boolean => { - const seen = new Set(); - while (owner != null && owner > 1 && !seen.has(owner)) { - if (owner === pid) return true; - seen.add(owner); - owner = parents.get(owner) ?? null; - } - return false; - }; - const stored = readStoredPorts(); - const ports = [...new Set([stored?.api, stored?.dashboard])].filter( - (port): port is number => typeof port === "number" && Number.isInteger(port) && port > 0 && port <= 65535, - ); - const executor = new LocalExecutor(); - const held = await Promise.all(ports.map(async (port) => { - const owners = await probeListeningPortOwners(executor, port); - return owners.checked && owners.ownershipComplete && owners.occupants.length > 0 && - owners.occupants.every((owner) => belongsToService(owner.pid)) ? port : null; - })); - return held.filter((port): port is number => port !== null); -} - /** Stop AND disable the service — it won't restart or return on reboot. */ /** * Best-effort reaper for processes still holding our canonical API/dashboard diff --git a/apps/cli/src/lib/up-plan.ts b/apps/cli/src/lib/up-plan.ts index 119d75a95..ee9d9f6c6 100644 --- a/apps/cli/src/lib/up-plan.ts +++ b/apps/cli/src/lib/up-plan.ts @@ -30,7 +30,7 @@ import { previewHostEdge, type EdgePreview } from "./edge-preflight"; import { DEFAULT_REPO, SOURCE_CHECKOUT_DIR, SOURCE_DIST_DIR } from "./from-source"; import { AUTH_SECRET_FILE, DATA_DIR, INTERNAL_TOKEN_FILE, LOG_DIR } from "./paths"; import { PORTS_FILE, resolvePorts, type ResolvedPorts } from "./ports"; -import { installStepFor, preview as previewService, serviceHeldPorts, type ServiceKind } from "./service"; +import { installStepFor, preview as previewService, type ServiceKind } from "./service"; /** How `up` would run: install a supervised service, or stay attached. */ export type UpMode = "service" | "foreground" | "from-source"; @@ -136,7 +136,6 @@ export async function planUp(opts: UpPlanOpts): Promise { { api: opts.port ? Number(opts.port) : undefined, dashboard: opts.dashboardPort ? Number(opts.dashboardPort) : undefined, - reclaimable: mode === "service" ? await serviceHeldPorts() : [], }, { persist: false }, ), diff --git a/apps/cli/test/e2e/domain.test.ts b/apps/cli/test/e2e/domain.test.ts index cae63fd24..e1d2405cf 100644 --- a/apps/cli/test/e2e/domain.test.ts +++ b/apps/cli/test/e2e/domain.test.ts @@ -86,9 +86,9 @@ describe("openship domain add", () => { : { status: 201, json: ADDED }); const { err, code } = await runCommand(domainCommand, ["add", "app.example.com", "-p", "prj1"]); expect(code).toBe(0); - const creation = fetchStub.calls.find(call => call.method === "POST")!; - expect(creation.url).toBe(`${API}/domains`); - expect(creation.body).toEqual({ projectId: "prj1", hostname: "app.example.com", isPrimary: false }); + expect(fetchStub.calls[0].method).toBe("POST"); + expect(fetchStub.calls[0].url).toBe(`${API}/domains`); + expect(fetchStub.calls[0].body).toEqual({ projectId: "prj1", hostname: "app.example.com", isPrimary: false }); expect(err).toContain("openship domain verify d9"); // next-step hint names the new id }); @@ -99,7 +99,7 @@ describe("openship domain add", () => { ? { json: { data: projectInfo.project } } : { status: 201, json: ADDED }); await runCommand(domainCommand, ["add", "app.example.com", "-p", "prj1", "--primary"]); - expect(fetchStub.calls.find(call => call.method === "POST")!.body).toMatchObject({ isPrimary: true }); + expect(fetchStub.calls[0].body).toMatchObject({ isPrimary: true }); }); it("emits the domain and its DNS records as JSON in json mode", async () => { diff --git a/apps/cli/test/e2e/login.test.ts b/apps/cli/test/e2e/login.test.ts index 1116501fd..b869db092 100644 --- a/apps/cli/test/e2e/login.test.ts +++ b/apps/cli/test/e2e/login.test.ts @@ -48,7 +48,6 @@ vi.mock("../../src/lib/local-connection", () => ({ import { loginCommand } from "../../src/commands/login"; import { CLOUD_API_URL, CLOUD_DASHBOARD_URL, LOCAL_DASHBOARD_URL } from "@repo/core"; -import { SDK_CAPABILITIES } from "@repo/contracts"; import { runCommand, stubFetch, type FetchStub } from "../helpers/harness"; import { setJsonMode } from "../../src/lib/output"; @@ -68,38 +67,6 @@ afterEach(() => { }); describe("openship login endpoint preservation", () => { - it.each([404, 200])("discovers the same-origin API after a dashboard response (%s) and saves it", async (status) => { - fetchStub.restore(); - fetchStub = stubFetch(request => { - if (request.url === "https://ship.example.com/api/tokens") return { status, text: "Dashboard" }; - if (request.url.endsWith("/health")) { - expect(request.headers.authorization).toBeUndefined(); - return { json: { status: "ok", sdk: SDK_CAPABILITIES } }; - } - expect(request.url).toBe("https://ship.example.com/api/proxy/api/tokens"); - expect(request.headers.authorization).toBe("Bearer opsh_pat_test"); - return { json: { data: [] } }; - }); - const result = await runCommand(loginCommand, ["--api-url", "https://ship.example.com", "--token", "opsh_pat_test"]); - expect(result.code).toBe(0); - expect(h.added.at(-1)?.opts).toMatchObject({ apiUrl: "https://ship.example.com/api/proxy", dashboardUrl: "https://ship.example.com" }); - expect(fetchStub.calls).toHaveLength(3); - }); - - it("does not send a token to a guessed endpoint without a valid API health response", async () => { - fetchStub.restore(); - fetchStub = stubFetch(() => ({ status: 404, json: { error: "Not found" } })); - const result = await runCommand(loginCommand, ["--api-url", "https://ship.example.com", "--token", "opsh_pat_test"]); - expect(result.code).toBe(1); - expect(h.added).toEqual([]); - expect(fetchStub.calls.map(call => call.url)).toEqual(["https://ship.example.com/api/tokens", "https://ship.example.com/api/proxy/api/health"]); - expect(fetchStub.calls[1]!.headers.authorization).toBeUndefined(); - }); - - it("derives the dashboard correctly for an explicitly supplied proxy API", async () => { - await runCommand(loginCommand, ["--api-url", "https://ship.example.com/api/proxy", "--token", "opsh_pat_test"]); - expect(h.added.at(-1)?.opts.dashboardUrl).toBe("https://ship.example.com"); - }); it("guides a fresh interactive login to Cloud and opens its token page", async () => { h.interactive = true; const result = await runCommand(loginCommand, []); diff --git a/apps/cli/test/e2e/up.test.ts b/apps/cli/test/e2e/up.test.ts index d1716f857..8ffcf15c7 100644 --- a/apps/cli/test/e2e/up.test.ts +++ b/apps/cli/test/e2e/up.test.ts @@ -207,8 +207,6 @@ beforeEach(() => { (upCommand as any).setOptionValue?.("edge", undefined); (upCommand as any).setOptionValue?.("compose", undefined); (upCommand as any).setOptionValue?.("resetSecrets", undefined); - for (const key of ["managedEdge", "publicUrl", "trustProxy", "nonInteractive", "yes", "adminEmail", "adminPassword", "domainKind", "hostname"]) - upCommand.setOptionValue(key, undefined); con = captureConsole(); }); @@ -220,68 +218,6 @@ afterEach(() => { }); describe("openship up --compose (edge chain)", () => { - it("gives a usable first-admin instruction after an ordinary install", async () => { - const result = await runCommand(upCommand, ["--compose"]); - expect(result.code).toBe(0); - expect(con.text()).toContain("Create first admin"); - expect(con.text()).not.toContain("register the first account"); - }); - - it("refuses incomplete non-interactive setup before changing the stack", async () => { - const result = await runCommand(upCommand, ["--compose", "--non-interactive"]); - expect(result.code).toBe(1); - expect(h.prefetchCalls).toBe(0); - expect(h.composeUpCalls).toBe(0); - expect(con.text()).toContain("--admin-email"); - }); - - it("requires an HTTPS hostname before starting managed-edge installation", async () => { - const result = await runCommand(upCommand, ["--compose", "--managed-edge", "--public-url", "http://ops.example.com"]); - expect(result.code).toBe(1); - expect(h.composeUpCalls).toBe(0); - expect(con.text()).toContain("https://"); - }); - - it("honors managed-edge in Compose without changing admin credentials", async () => { - fetchStub = stubFetch(request => { - expect(request.url).toContain("/api/system/self-register"); - expect(request.body).toMatchObject({ domainType: "custom", hostname: "ops.example.com", dashPort: 3001 }); - return { json: { url: "https://ops.example.com" } }; - }); - const result = await runCommand(upCommand, ["--compose", "--managed-edge", "--public-url", "https://ops.example.com"]); - expect(result.code, result.err).toBe(0); - expect(fetchStub.calls).toHaveLength(1); - expect(fetchStub.calls[0]!.headers["x-internal-token"]).toBe("tok"); - }); - - it("provisions the requested managed domain during headless Compose setup", async () => { - fetchStub = stubFetch(request => { - if (request.url.endsWith("/api/health")) return { json: { status: "ok" } }; - if (request.url.endsWith("/api/system/bootstrap-admin")) return { json: { success: true } }; - expect(request.url).toContain("/api/system/self-register"); - expect(request.body).toMatchObject({ domainType: "custom", hostname: "ops.example.com" }); - return { json: { url: "https://ops.example.com" } }; - }); - const result = await runCommand(upCommand, ["--compose", "--managed-edge", "--public-url", "https://ops.example.com", - "--non-interactive", "--admin-email", "owner@example.com", "--admin-password", "strong-initial-password"]); - expect(result.code, con.text()).toBe(0); - expect(fetchStub.calls.map(call => new URL(call.url).pathname)).toEqual([ - "/api/health", "/api/system/bootstrap-admin", "/api/system/self-register", - ]); - }); - - it("does not report managed-edge success when registration fails", async () => { - fetchStub = stubFetch(request => { - if (request.url.endsWith("/api/health")) return { json: { status: "ok" } }; - if (request.url.endsWith("/api/system/bootstrap-admin")) return { json: { success: true } }; - return { status: 503, json: { error: "Edge unavailable" } }; - }); - const result = await runCommand(upCommand, ["--compose", "--managed-edge", "--public-url", "https://ops.example.com", - "--non-interactive", "--admin-email", "owner@example.com", "--admin-password", "strong-initial-password"]); - expect(result.code).toBe(1); - expect(con.text()).toContain("Managed domain registration did not complete"); - expect(con.text()).not.toContain("✓ Openship provisioned"); - }); it("exits before the edge preflight when docker/compose is missing", async () => { h.hasDocker = false; const r = await runCommand(upCommand, ["--compose"]); diff --git a/apps/cli/test/unit/compose-env-preserve.test.ts b/apps/cli/test/unit/compose-env-preserve.test.ts index 7ea232daa..1ca62a9cd 100644 --- a/apps/cli/test/unit/compose-env-preserve.test.ts +++ b/apps/cli/test/unit/compose-env-preserve.test.ts @@ -1753,13 +1753,10 @@ describe("composeUp — the host channel is provisioned out loud (#509)", () => seedHostKey(); h.channelAuth = () => ({ status: 0, stdout: "openship-sudo=refused\n", stderr: "" }); - // Select a non-root session explicitly: the test runner may itself be root, - // whose SSH login already has privilege and needs no sudo warning. - await composeUp({ hostSshUser: "ops" }); + await composeUp({}); // A working channel, so it IS written — just one with no route to root. expect(writtenEnv().OPENSHIP_HOST_SSH_HOST).toBe("host.docker.internal"); - expect(writtenEnv().OPENSHIP_HOST_SSH_USER).toBe("ops"); expect(warned.join("\n")).toContain("no route to it"); }); diff --git a/apps/cli/test/unit/custom-domain-endpoint.test.ts b/apps/cli/test/unit/custom-domain-endpoint.test.ts index 45f0154c9..39d360423 100644 --- a/apps/cli/test/unit/custom-domain-endpoint.test.ts +++ b/apps/cli/test/unit/custom-domain-endpoint.test.ts @@ -4,8 +4,6 @@ const h = vi.hoisted(() => ({ project: {} as Record, rows: [] as unknown[], updates: [] as unknown[], - services: [] as Array>, - serviceUpdates: [] as unknown[], updateError: false, })); vi.mock("../../src/lib/ship-client", async (importOriginal) => { @@ -32,18 +30,6 @@ vi.mock("../../src/lib/ship-client", async (importOriginal) => { h.updates.push({ id, input }); }, }, - services: { - list: async () => h.services, - get: async (_project: string, id: string) => { - const service = h.services.find(service => service.id === id); - if (!service) throw new Error("Service not found in project"); - return service; - }, - update: async (project: string, id: string, input: unknown) => { - if (h.updateError) throw new Error("update unavailable"); - h.serviceUpdates.push({ project, id, input }); - }, - }, domains: { verify: async () => { throw new Error("verification unavailable"); @@ -73,8 +59,6 @@ beforeEach(() => { h.rows = []; h.updates = []; h.updateError = false; - h.services = []; - h.serviceUpdates = []; }); afterEach(() => vi.restoreAllMocks()); @@ -138,48 +122,28 @@ describe("CLI custom domain routing", () => { expect(h.updates).toEqual([]); }); - it("refuses a portless worker before claiming a domain", async () => { + it("warns without attaching a portless worker or failing the command", async () => { h.project = { ...h.project, hasServer: false, workloadType: "worker", port: null }; + const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); const result = await add(); - expect(result.code).toBe(1); - expect(h.rows).toEqual([]); + expect(result.code).toBe(0); + expect(h.rows).toHaveLength(1); expect(h.updates).toEqual([]); - expect(result.err).toContain("worker has no public route"); + expect(warning.mock.calls.flat().join(" ")).toMatch(/worker.*no public route/i); + expect(result.err).not.toContain("routed on the next deploy"); }); - it.each(["services", "monorepo"])("requires an explicit target before claiming a domain for %s", async projectType => { - h.project = { ...h.project, projectType }; + it.each(["services", "monorepo"])("warns without attaching a %s project", async (projectType) => { + h.project = { ...h.project, name: "My project", projectType }; + const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); const result = await add(); - expect(result.code).toBe(1); - expect(h.rows).toEqual([]); - expect(result.err).toContain("--service"); - }); - - it.each(["web", "svc_web"])("attaches to the project-scoped service selected by %s", async ref => { - h.project.projectType = "services"; - const existing = [{ domainType: "free", domain: "existing", port: 8080 }]; - h.services = [{ id: "svc_web", name: "web", ports: ["8080:3000"], publicEndpoints: existing }]; - const result = await runCommand(domainCommand, ["add", "app.example.com", "-p", "project-1", "--service", ref, "--port", "3000"]); - expect(result.code, result.err).toBe(0); + expect(result.code).toBe(0); + expect(h.rows).toHaveLength(1); expect(h.updates).toEqual([]); - expect(h.serviceUpdates).toEqual([{ project: "project-1", id: "svc_web", input: { exposed: true, publicEndpoints: [...existing, { domainType: "custom", customDomain: "app.example.com", port: 3000 }] } }]); - }); - - it.each(["unknown", "svc_foreign"])("rejects an unknown or foreign service %s before claiming the hostname", async ref => { - h.project.projectType = "services"; - const result = await runCommand(domainCommand, ["add", "app.example.com", "-p", "project-1", "--service", ref, "--port", "3000"]); - expect(result.code).toBe(1); - expect(h.rows).toEqual([]); - expect(h.serviceUpdates).toEqual([]); - }); - - it("requires a port when the selected service has several possible targets", async () => { - h.project.projectType = "services"; - h.services = [{ id: "svc_web", name: "web", ports: ["3000", "3001"] }]; - const result = await runCommand(domainCommand, ["add", "app.example.com", "-p", "project-1", "--service", "web"]); - expect(result.code).toBe(1); - expect(h.rows).toEqual([]); - expect(result.err).toContain("--port"); + expect(warning).toHaveBeenCalledWith( + "Domain app.example.com was added, but My project is a multi-service project, so routes belong to a service. Attach it to a service in the dashboard.", + ); + expect(result.err).not.toContain("routed on the next deploy"); }); it.each(["domain", "edge"])( diff --git a/apps/cli/test/unit/headless-provision-domain.test.ts b/apps/cli/test/unit/headless-provision-domain.test.ts index 435f4132f..dd0e2f7f7 100644 --- a/apps/cli/test/unit/headless-provision-domain.test.ts +++ b/apps/cli/test/unit/headless-provision-domain.test.ts @@ -14,7 +14,6 @@ import { describe, it, expect, beforeEach, vi } from "vitest"; const h = vi.hoisted(() => ({ posts: [] as Array<{ path: string; body: Record }>, - bootstrap: vi.fn(async () => ({ ok: true, message: "created" })), })); vi.mock("../../src/lib/loopback-api", () => ({ @@ -23,13 +22,13 @@ vi.mock("../../src/lib/loopback-api", () => ({ return { ok: true, data: { url: "https://ops.example.com" } }; }, waitHealthy: async () => true, - bootstrapAdmin: h.bootstrap, + bootstrapAdmin: async () => ({ ok: true, message: "created" }), // The provision-stream reader goes through this; unreachable here (the stubbed // self-register returns no sessionId), but the module imports it. internalFetch: async () => ({ kind: "unreachable", detail: "not stubbed" }), })); -import { headlessProvision, provisionInstanceDomain } from "../../src/lib/instance-provision"; +import { headlessProvision } from "../../src/lib/instance-provision"; const inputs = { admin: { email: "a@b.com", name: "a", password: "supersecret" }, @@ -40,16 +39,9 @@ const selfRegister = () => h.posts.find((p) => p.path === "/api/system/self-regi beforeEach(() => { h.posts = []; - h.bootstrap.mockClear(); }); describe("headlessProvision — self-app custom domain", () => { - it("can register a managed domain without creating or resetting an existing admin", async () => { - const result = await provisionInstanceDomain({ port: "4000", dashPort: "3001", domain: inputs.domain }); - expect(result.domainRegistered).toBe(true); - expect(h.bootstrap).not.toHaveBeenCalled(); - expect(h.posts.map(post => post.path)).toEqual(["/api/system/self-register"]); - }); it("requests the custom domain on COMPOSE (container edge issues the cert)", async () => { const res = await headlessProvision({ port: "4000", dashPort: "3001", inputs, method: "compose" }); diff --git a/apps/cli/test/unit/public-instance-api.test.ts b/apps/cli/test/unit/public-instance-api.test.ts deleted file mode 100644 index 89ac6d914..000000000 --- a/apps/cli/test/unit/public-instance-api.test.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { afterEach, expect, it, vi } from "vitest"; -import { SDK_CAPABILITIES } from "@repo/contracts"; -import { discoverPublicInstanceApi } from "../../src/lib/public-instance-api"; -afterEach(() => vi.unstubAllGlobals()); - -it("confines credential-free discovery to the supplied origin and refuses redirects", async () => { - const fetcher = vi.fn(async () => Response.json({ status: "ok", sdk: SDK_CAPABILITIES })); - vi.stubGlobal("fetch", fetcher); - expect(await discoverPublicInstanceApi("https://ship.test/prefix/")).toBe("https://ship.test/prefix/api/proxy"); - expect(fetcher).toHaveBeenCalledWith("https://ship.test/prefix/api/proxy/api/health", expect.objectContaining({ redirect: "error", headers: { Accept: "application/json" } })); -}); -it.each(["https://ship.test/api", "https://ship.test/api/proxy", "https://ship.test/prefix/api/proxy/"])("does not reinterpret an explicit API: %s", async url => { - const fetcher = vi.fn(); vi.stubGlobal("fetch", fetcher); - expect(await discoverPublicInstanceApi(url)).toBeNull(); - expect(fetcher).not.toHaveBeenCalled(); -}); -it.each([{ status: "ok" }, { sdk: SDK_CAPABILITIES }, { status: "ok", sdk: { protocol: -1 } }])("ignores an unrelated health response: %j", async body => { - vi.stubGlobal("fetch", vi.fn(async () => Response.json(body))); - expect(await discoverPublicInstanceApi("https://ship.test")).toBeNull(); -}); diff --git a/apps/cli/test/unit/service-held-ports.test.ts b/apps/cli/test/unit/service-held-ports.test.ts deleted file mode 100644 index 8c90f5dc9..000000000 --- a/apps/cli/test/unit/service-held-ports.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { mkdirSync, rmSync, writeFileSync } from "node:fs"; -import { join } from "node:path"; -import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -const state = vi.hoisted(() => { - const home = `${process.env.TMPDIR || "/tmp"}/openship-service-owners-${process.pid}`; - process.env.OPENSHIP_HOME = home; - return { home, pid: 4200, processes: "4200 1\n4201 4200\n4202 4201\n9000 1", probe: vi.fn() }; -}); -vi.mock("@repo/adapters", () => ({ - LocalExecutor: class {}, - probeListeningPortOwners: state.probe, -})); -vi.mock("../../src/lib/this-host", () => ({ - thisHost: () => ({ profile: { serviceManager: "systemd" } }), -})); -const commands = vi.hoisted(() => vi.fn()); -vi.mock("node:child_process", async (original) => ({ - ...(await original()), - spawnSync: commands, -})); -const { serviceHeldPorts } = await import("../../src/lib/service"); -const platform = process.platform; -beforeEach(() => { - Object.defineProperty(process, "platform", { value: "darwin", configurable: true }); - mkdirSync(state.home, { recursive: true }); - writeFileSync(join(state.home, "ports.json"), JSON.stringify({ api: 7100, dashboard: 7200 })); - state.pid = 4200; - state.processes = "4200 1\n4201 4200\n4202 4201\n9000 1"; - state.probe.mockReset().mockResolvedValue({ - checked: true, - ownershipComplete: true, - occupants: [{ pid: 4202 }], - }); - commands.mockReset().mockImplementation((command, args) => { - const stdout = - command === "launchctl" - ? `"PID" = ${state.pid};` - : command === "systemctl" - ? String(state.pid) - : command === "ps" - ? state.processes - : ""; - return { status: 0, stdout, stderr: "" }; - }); -}); -afterEach(() => - Object.defineProperty(process, "platform", { value: platform, configurable: true }), -); -afterAll(() => rmSync(state.home, { recursive: true, force: true })); - -describe("service-held listener ownership", () => { - it("accepts listeners belonging to the service and nested children", async () => { - expect(await serviceHeldPorts()).toEqual([7100, 7200]); - }); - it("rejects a foreign dashboard listener even while the API service runs", async () => { - state.probe.mockImplementation(async (_, port) => ({ - checked: true, - ownershipComplete: true, - occupants: [{ pid: port === 7100 ? 4201 : 9000 }], - })); - expect(await serviceHeldPorts()).toEqual([7100]); - }); - it("rejects mixed owners, hidden owners and incomplete ownership", async () => { - for (const result of [ - { checked: true, ownershipComplete: true, occupants: [{ pid: 4201 }, { pid: 9000 }] }, - { checked: true, ownershipComplete: false, occupants: [{ pid: 4201 }] }, - { checked: true, ownershipComplete: true, occupants: [{ pid: null }] }, - { checked: false, ownershipComplete: false, occupants: [] }, - ]) { - state.probe.mockResolvedValue(result); - expect(await serviceHeldPorts()).toEqual([]); - } - }); - it("does not trust a saved port when its owner is outside the live service tree", async () => { - state.probe.mockResolvedValue({ - checked: true, - ownershipComplete: true, - occupants: [{ pid: 9000 }], - }); - expect(await serviceHeldPorts()).toEqual([]); - }); - it("falls back when the service is stopped or its process tree is unavailable", async () => { - state.pid = 0; - expect(await serviceHeldPorts()).toEqual([]); - expect(state.probe).not.toHaveBeenCalled(); - state.pid = 4200; - state.processes = "9000 1"; - expect(await serviceHeldPorts()).toEqual([]); - expect(state.probe).not.toHaveBeenCalled(); - }); - it("uses the live systemd MainPID for Linux services", async () => { - Object.defineProperty(process, "platform", { value: "linux", configurable: true }); - expect(await serviceHeldPorts()).toEqual([7100, 7200]); - expect( - commands.mock.calls.some( - ([command, args]) => command === "systemctl" && args.includes("--property=MainPID"), - ), - ).toBe(true); - }); - it("does not guess ownership for a scheduled task without a PID", async () => { - Object.defineProperty(process, "platform", { value: "win32", configurable: true }); - expect(await serviceHeldPorts()).toEqual([]); - expect(state.probe).not.toHaveBeenCalled(); - }); - it("ignores malformed stored ports without invoking an ownership probe", async () => { - writeFileSync(join(state.home, "ports.json"), JSON.stringify({ api: "7100", dashboard: -1 })); - expect(await serviceHeldPorts()).toEqual([]); - expect(state.probe).not.toHaveBeenCalled(); - }); -}); diff --git a/apps/cli/test/unit/up-rerun-ports.test.ts b/apps/cli/test/unit/up-rerun-ports.test.ts deleted file mode 100644 index 51dad16e0..000000000 --- a/apps/cli/test/unit/up-rerun-ports.test.ts +++ /dev/null @@ -1,153 +0,0 @@ -import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; -import { createServer, type Server } from "node:net"; -import { join } from "node:path"; -import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from "vitest"; - -/** - * Re-running `openship up` while its own service is running (#1570). - * - * The running service holds the ports in ports.json, so they probe busy. They are - * still ours: installAndStart replaces that instance before the new one binds. - * Treating them as taken moved the install to new ports on every re-run - * (7100 -> 7101), rewrote ports.json, and first sat out waitPortFree on each port. - */ - -// lib/paths reads OPENSHIP_HOME at import time, so set it before anything loads. -const HOME = vi.hoisted(() => { - const dir = `${process.env.TMPDIR?.replace(/\/$/, "") || "/tmp"}/openship-up-rerun-${process.pid}`; - process.env.OPENSHIP_HOME = dir; - return dir; -}); - -const svc = vi.hoisted(() => ({ - running: false, - heldPorts: [] as number[], - installed: [] as Array<{ port: string; dashboardPort: string }>, -})); - -// Only the service manager is faked. The port resolver and ports.json stay real. -vi.mock("../../src/lib/service", async (importOriginal) => ({ - ...(await importOriginal()), - serviceHeldPorts: async () => (svc.running ? svc.heldPorts : []), - installAndStart: (flags: { port: string; dashboardPort: string }) => { - svc.installed.push(flags); - return { kind: "launchd", detail: "test" }; - }, -})); - -const { startService } = await import("../../src/commands/up"); -const { planUp } = await import("../../src/lib/up-plan"); -const { getFreePort, isPortFree } = await import("../../src/lib/ports"); - -const PORTS_FILE = join(HOME, "ports.json"); -const held: Server[] = []; - -/** Bind a port the way a running process would. */ -function hold(port: number): Promise { - return new Promise((resolve, reject) => { - const srv = createServer(); - srv.once("error", reject); - srv.listen(port, "127.0.0.1", () => { - held.push(srv); - resolve(); - }); - }); -} - -/** A free port whose neighbour is free too, so a move to it would be visible. */ -async function freeWithNeighbour(from?: number): Promise { - for (let i = 0; i < 50; i++) { - const port = from === undefined ? await getFreePort() : from + i * 3; - if ((await isPortFree(port)) && (await isPortFree(port + 1))) return port; - } - throw new Error("no free port with a free neighbour"); -} - -/** API and dashboard ports far enough apart that neither move lands on the other. */ -async function freePorts(): Promise<{ api: number; dashboard: number }> { - const api = await freeWithNeighbour(); - return { api, dashboard: await freeWithNeighbour(api + 10) }; -} - -beforeEach(() => { - mkdirSync(HOME, { recursive: true }); - rmSync(PORTS_FILE, { force: true }); - svc.running = false; - svc.heldPorts = []; - svc.installed = []; -}); - -afterEach(async () => { - await Promise.all(held.splice(0).map((s) => new Promise((r) => s.close(r)))); -}); - -afterAll(() => { - rmSync(HOME, { recursive: true, force: true }); -}); - -describe("startService on a re-run", () => { - it("keeps the ports its own running service holds", async () => { - const { api, dashboard } = await freePorts(); - writeFileSync(PORTS_FILE, JSON.stringify({ api, dashboard })); - await hold(api); - await hold(dashboard); - svc.running = true; - svc.heldPorts = [api, dashboard]; - - const r = await startService({}, { quiet: true }); - - expect({ api: r.port, dashboard: r.dashPort }).toEqual({ - api: String(api), - dashboard: String(dashboard), - }); - expect(svc.installed[0]).toMatchObject({ port: String(api), dashboardPort: String(dashboard) }); - expect(JSON.parse(readFileSync(PORTS_FILE, "utf8"))).toEqual({ api, dashboard }); - }, 30_000); - - it("still moves off a remembered port another program holds when the service is not running", async () => { - const { api, dashboard } = await freePorts(); - writeFileSync(PORTS_FILE, JSON.stringify({ api, dashboard })); - await hold(api); - - const r = await startService({}, { quiet: true }); - - expect(r.port).not.toBe(String(api)); - expect(r.dashPort).toBe(String(dashboard)); - }, 30_000); - - it("moves off an unrelated dashboard listener when the running service owns only the API", async () => { - const { api, dashboard } = await freePorts(); - writeFileSync(PORTS_FILE, JSON.stringify({ api, dashboard })); - await hold(api); - await hold(dashboard); - svc.running = true; - svc.heldPorts = [api]; - const r = await startService({}, { quiet: true }); - expect(r.port).toBe(String(api)); - expect(r.dashPort).not.toBe(String(dashboard)); - }, 30_000); - - it("uses the same owned ports for a dry-run and an actual service rerun", async () => { - const { api, dashboard } = await freePorts(); - writeFileSync(PORTS_FILE, JSON.stringify({ api, dashboard })); - await hold(api); - await hold(dashboard); - svc.running = true; - svc.heldPorts = [api, dashboard]; - const plan = await planUp({ bare: true }); - const r = await startService({}, { quiet: true }); - expect(plan.ports.api).toBe(Number(r.port)); - expect(plan.ports.dashboard).toBe(Number(r.dashPort)); - }, 30_000); - - it("does not reclaim service ports for an attached foreground preview", async () => { - const { api, dashboard } = await freePorts(); - writeFileSync(PORTS_FILE, JSON.stringify({ api, dashboard })); - await hold(api); - svc.running = true; - svc.heldPorts = [api]; - const plan = await planUp({ bare: true, foreground: true }); - expect(plan.ports.api).not.toBe(api); - expect(plan.ports.dashboard).toBe(dashboard); - }, 30_000); -}); diff --git a/apps/dashboard/src/app/(auth)/register/signup-next.test.ts b/apps/dashboard/src/app/(auth)/register/signup-next.test.ts index 2c7ece3a7..e5e61f44d 100644 --- a/apps/dashboard/src/app/(auth)/register/signup-next.test.ts +++ b/apps/dashboard/src/app/(auth)/register/signup-next.test.ts @@ -15,7 +15,7 @@ describe("signUpNext", () => { it("goes to verification when sign-up succeeds WITHOUT a session", () => { // The exact better-auth shape for requireEmailVerification. const next = signUpNext({ data: { token: null } }, opts); - expect(next).toEqual({ kind: "verify", href: "/verify-email?email=a%40b.co&signup=1" }); + expect(next).toEqual({ kind: "verify", href: "/verify-email?email=a%40b.co" }); }); it("treats a missing token field the same as an explicit null", () => { @@ -54,16 +54,3 @@ describe("signUpNext", () => { expect(next.kind === "verify" && next.href).toContain("a%2Btag%40b.co"); }); }); - -it("preserves the Cloud consent and PKCE continuation through signup verification", () => { - const returnTo = "/cloud-authorize?mode=device&state=test-state&code_challenge=test-challenge"; - const next = signUpNext( - { data: { token: null } }, - { email: "existing@example.test", authParams: new URLSearchParams({ returnTo }) }, - ); - expect(next.kind).toBe("verify"); - if (next.kind !== "verify") throw new Error("Expected email continuation"); - const params = new URL(next.href, "https://app.example.test").searchParams; - expect(params.get("signup")).toBe("1"); - expect(params.get("returnTo")).toBe(returnTo); -}); diff --git a/apps/dashboard/src/app/(auth)/register/signup-next.ts b/apps/dashboard/src/app/(auth)/register/signup-next.ts index f7ee49d02..1d77fe8d2 100644 --- a/apps/dashboard/src/app/(auth)/register/signup-next.ts +++ b/apps/dashboard/src/app/(auth)/register/signup-next.ts @@ -23,7 +23,7 @@ export type SignUpResultShape = { export type SignUpNext = /** Show the message; stay on the form. */ | { kind: "error"; message: string | null } - /** No session: privately continue by verification code or sign-in instructions. */ + /** Account exists, no session yet — the code screen, reachable unauthenticated. */ | { kind: "verify"; href: string } /** A real session was issued; follow the post-login destination. */ | { kind: "session"; href: string }; @@ -36,9 +36,7 @@ export function signUpNext( authParams?: Parameters[1]; }, ): SignUpNext { - // The same response also protects an existing address from enumeration. Do - // not promise account creation or a code when the email contains sign-in help. - const verifyHref = `${emailVerificationHref(opts.email, opts.authParams ?? new URLSearchParams())}&signup=1`; + const verifyHref = emailVerificationHref(opts.email, opts.authParams ?? new URLSearchParams()); if (result.error) { // Some deployments surface the requirement as an error instead of a null diff --git a/apps/dashboard/src/app/(auth)/verify-email/page.tsx b/apps/dashboard/src/app/(auth)/verify-email/page.tsx index fd3996605..78944d7c5 100644 --- a/apps/dashboard/src/app/(auth)/verify-email/page.tsx +++ b/apps/dashboard/src/app/(auth)/verify-email/page.tsx @@ -33,11 +33,9 @@ function VerifyEmailContent() { const searchParams = useSearchParams(); const token = searchParams.get("token"); const emailParam = searchParams.get("email") ?? ""; - const fromSignup = searchParams.get("signup") === "1"; const { toast } = useToast(); const { t } = useI18n(); const loginHref = buildAuthPageHref("/login", searchParams); - const resetHref = buildAuthPageHref("/forgot-password", searchParams); const [status, setStatus] = useState<"pending" | "verifying" | "verified" | "error">( token ? "verifying" : "pending", @@ -223,14 +221,11 @@ function VerifyEmailContent() {

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

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

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

- {t.auth.register.hasAccount}{" "} - {t.auth.register.signIn} + {t.auth.verifyEmail.backToSignIn}

- - {t.auth.forgotPassword.title} - ); diff --git a/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx b/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx index b9513fcc3..138d19258 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 377e5f5f2..4ba8cd845 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 92eaf168a..105bd759e 100644 --- a/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx +++ b/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx @@ -8,8 +8,10 @@ import { DeploymentMenu } from "./DeploymentMenu"; import { CommitDetailsModal } from "./CommitDetailsModal"; import type { Deployment } from "../types"; import { formatDistanceToNow, formatBuildTime, getStatusConfig } from "../utils"; -import { ProjectIcon } from "@/components/shared/ProjectIcon"; +import { ProjectStackIcon } from "@/components/shared/ProjectStackIcon"; +import { AppLogo } from "@/components/AppLogo"; import { useI18n, interpolate } from "@/components/i18n-provider"; +import { useImageFallback } from "@/hooks/useImageFallback"; type ServiceStatusLabels = { deployed: string; @@ -120,6 +122,7 @@ export const DeploymentCard: React.FC = ({ const { t } = useI18n(); const [isCommitModalOpen, setIsCommitModalOpen] = useState(false); const [isMenuOpen, setIsMenuOpen] = useState(false); + const favicon = useImageFallback(deployment.favicon); const statusConfig = getStatusConfig(deployment.status); const statusLabelMap: Record = { @@ -148,9 +151,21 @@ export const DeploymentCard: React.FC = ({ aria-label={deployment.projectName || t.deployments.card.unknownProject} className="absolute inset-0 z-0" /> - {/* Project icon → catalog logo → framework or service icon */} + {/* App logo (catalog apps) → project favicon → framework icon → initials */}
- + {appTemplateId ? ( + + ) : favicon.showImage ? ( + + ) : ( + + )}
{/* Main info */} diff --git a/apps/dashboard/src/app/(dashboard)/deployments/types.ts b/apps/dashboard/src/app/(dashboard)/deployments/types.ts index a49f53391..213fb5e83 100644 --- a/apps/dashboard/src/app/(dashboard)/deployments/types.ts +++ b/apps/dashboard/src/app/(dashboard)/deployments/types.ts @@ -56,8 +56,9 @@ export interface Deployment { branch?: string; projectId?: string; projectName?: string; - /** Project icon shared with project lists and settings. */ - iconUrl?: string | null; + /** Auto-detected favicon of the deployed site, cached on the project. + * When present it replaces the framework/Docker glyph as the row logo. */ + favicon?: string | null; failureReason?: string; /** Rollback state — populated by the orchestrator-aware listing endpoint. * `artifactRetainedAt` non-null = artifact is archived, rollback-eligible. diff --git a/apps/dashboard/src/app/(dashboard)/deployments/utils.ts b/apps/dashboard/src/app/(dashboard)/deployments/utils.ts index 711c32894..f2bc27c23 100644 --- a/apps/dashboard/src/app/(dashboard)/deployments/utils.ts +++ b/apps/dashboard/src/app/(dashboard)/deployments/utils.ts @@ -41,7 +41,7 @@ export const mapRowToDeployment = (row: any): Deployment => { branch: row.branch ?? undefined, projectId: row.projectId, projectName: row.projectName, - iconUrl: row.iconUrl ?? null, + favicon: row.favicon ?? null, failureReason: row.errorMessage ?? undefined, /* Rollback state — flows from the listing endpoint, which enriches * each row with isActive and surfaces the orchestrator-owned diff --git a/apps/dashboard/src/app/(dashboard)/layout.tsx b/apps/dashboard/src/app/(dashboard)/layout.tsx index cc8c81f0c..abb88ac76 100644 --- a/apps/dashboard/src/app/(dashboard)/layout.tsx +++ b/apps/dashboard/src/app/(dashboard)/layout.tsx @@ -173,9 +173,10 @@ export default async function DashboardLayout({ children }: { children: React.Re hostDomain={deploymentInfo.hostDomain} >
- {/* Full-width update surface. Managed Cloud shows workload security; - Desktop and self-hosted also show installation updates, operator - notices and what's new. Empty state adds no chrome. */} + {/* Update + platform-status surface — full app width, ABOVE the sidebar. + Renders nothing unless there's an advisory / platform notice (SaaS: + partial outage, maintenance) / available update / what's-new, so it + adds no chrome when idle. */} {children}
diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx index 96b71d21c..fa09be27a 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx @@ -27,7 +27,6 @@ import { isSchemaAppTemplate } from "@/components/app-settings/AppSettingsForm"; import { AppConfiguration } from "./AppConfiguration"; import { BuildSettings } from "./BuildSettings"; import { CloudStaticHosting } from "@/components/project-settings/CloudStaticHosting"; -import { ProjectIconSetting } from "@/components/project-settings/ProjectIconSetting"; interface Props { onDeleteProject: (wipeVolumes?: boolean, recordOnly?: boolean) => void; @@ -358,7 +357,6 @@ 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 a4c904295..598bfb73c 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,7 +89,6 @@ beforeEach(() => { afterEach(async () => { await act(async () => root.unmount()); host.remove(); - vi.restoreAllMocks(); vi.unstubAllGlobals(); }); @@ -107,21 +106,6 @@ 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 b0d0c3df0..4975561d6 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx @@ -5,11 +5,10 @@ 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 { ProjectIcon } from "@/components/shared/ProjectIcon"; +import { AppLogo } from "@/components/AppLogo"; import { connectionsApi, type ConnectionMode } from "@/lib/api/connections"; import { getApiErrorMessage } from "@/lib/api/client"; import { useToast } from "@/context/ToastContext"; @@ -50,6 +49,15 @@ 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; @@ -96,7 +104,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"); @@ -156,7 +164,7 @@ export function ProjectConnectionForm({ setLoadingProjects(true); connectionsApi.candidates(fixedSourceId ?? fixedTargetId ?? "") .then(result => { - if (!cancelled) setTargets(result.data); + if (!cancelled) setTargets(result.data.map(project => ({ ...project, appTemplateId: project.appTemplateId ?? undefined }))); }) .catch(error => { if (!cancelled) setLoadError(getApiErrorMessage(error, c.failed)); }) .finally(() => { if (!cancelled) setLoadingProjects(false); }); @@ -229,7 +237,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 85e0967bb..f662bcf33 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx @@ -5,7 +5,8 @@ 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 { ProjectIcon } from "@/components/shared/ProjectIcon"; +import { AppLogo } from "@/components/AppLogo"; +import { ProjectStackIcon } from "@/components/shared/ProjectStackIcon"; import { getFrameworkConfig } from "@/components/import-project/Frameworks"; import { getProjectStatus, projectCardHref, projectDisplayDomain } from "@/utils/project-status"; import { ProjectStatusBadge } from "@/components/shared/ProjectStatusBadge"; @@ -14,6 +15,7 @@ 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 ──────────────────────────────────────────────────────── */ @@ -48,6 +50,9 @@ 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; @@ -56,13 +61,14 @@ interface Props { onChanged?: () => void; } -const ProjectCard: React.FC = ({ project, updateAvailable, onChanged }) => { +const ProjectCard: React.FC = ({ project, preferAppLogo, 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); @@ -112,8 +118,22 @@ const ProjectCard: React.FC = ({ project, updateAvailable, onChanged }) =
+ {/* 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 f1aaa56c9..66f51f1f7 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx @@ -6,12 +6,14 @@ import Link from "next/link"; import { useRouter } from "next/navigation"; import DropdownMenu from "@/components/ui/DropdownMenu"; import { type Project } from "@/constants/mock"; -import { ProjectIcon } from "@/components/shared/ProjectIcon"; +import { AppLogo } from "@/components/AppLogo"; +import { ProjectStackIcon } from "@/components/shared/ProjectStackIcon"; 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. */ @@ -20,10 +22,12 @@ 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, updateAvailable }) => { +}> = ({ project, preferAppLogo, updateAvailable }) => { const { t } = useI18n(); const router = useRouter(); + const favicon = useImageFallback(project.favicon); const domain = projectDisplayDomain(project); const hosting = getHostingLabel(project.deployTarget, project.serverName, t); @@ -61,7 +65,20 @@ 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-icon.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/components/project-favicon.test.tsx similarity index 67% rename from apps/dashboard/src/app/(dashboard)/projects/components/project-icon.test.tsx rename to apps/dashboard/src/app/(dashboard)/projects/components/project-favicon.test.tsx index e2482db84..2165098d3 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/components/project-icon.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/components/project-favicon.test.tsx @@ -39,35 +39,10 @@ afterEach(async () => { }); for (const [name, Card] of [["list", ProjectCard], ["grid", ProjectGridCard]] as const) { - const render = (iconUrl = "/icon-old.png") => ( - + const render = (favicon = "/favicon-old.ico") => ( + ); - 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); - }); - + describe(`${name} favicon`, () => { it("falls back when the image failed before hydration attached its error listener", async () => { const view = render(); container.innerHTML = renderToString(view); @@ -84,16 +59,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("/icon-new.png"))); - expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/icon-new.png"); + await act(async () => root!.render(render("/favicon-new.ico"))); + expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/favicon-new.ico"); }); - it("keeps an image that loaded before hydration", async () => { + it("keeps a successfully cached favicon", 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("/icon-old.png"); + expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/favicon-old.ico"); }); }); } diff --git a/apps/dashboard/src/app/(dashboard)/projects/page.tsx b/apps/dashboard/src/app/(dashboard)/projects/page.tsx index 46aab35f3..c692c689e 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 c6c3d0e49..e1407a0f6 100644 --- a/apps/dashboard/src/app/(dashboard)/providers.tsx +++ b/apps/dashboard/src/app/(dashboard)/providers.tsx @@ -7,7 +7,6 @@ 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 { @@ -51,7 +50,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 6b63ae685..2e4e5cea0 100644 --- a/apps/dashboard/src/app/(dashboard)/settings/page.tsx +++ b/apps/dashboard/src/app/(dashboard)/settings/page.tsx @@ -32,7 +32,6 @@ 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"; @@ -145,7 +144,6 @@ 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 1626849fa..7859cba96 100644 --- a/apps/dashboard/src/app/api/proxy/[...path]/route.test.ts +++ b/apps/dashboard/src/app/api/proxy/[...path]/route.test.ts @@ -1,5 +1,4 @@ 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"; @@ -28,21 +27,6 @@ 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 8b7819c01..15d557a6d 100644 --- a/apps/dashboard/src/components/actions/ActionBudget.test.tsx +++ b/apps/dashboard/src/components/actions/ActionBudget.test.tsx @@ -15,6 +15,8 @@ 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", () => ({ @@ -26,7 +28,10 @@ vi.mock("@/lib/api/billing", () => ({ }, })); vi.mock("@/lib/checkout-navigation", () => ({ - navigateToCheckout: (url: string, preserve: boolean) => h.navigate(url, preserve), + beginCheckoutNavigation: (preserve: boolean) => { + h.begin(preserve); + return { navigate: h.navigate, close: h.closeTab }; + }, })); vi.mock("next/navigation", () => ({ useSearchParams: () => new URLSearchParams(h.query) })); vi.mock("@/lib/auth-client", () => ({ @@ -100,24 +105,25 @@ describe("Actions funding UI", () => { h.navigate.mockImplementation((url: string) => url); await render(true); await act(async () => button("Add $5").click()); - expect(h.navigate).toHaveBeenCalledWith(expect.any(String), true); + expect(h.begin).toHaveBeenCalledWith(true); + expect(h.begin.mock.invocationCallOrder[0]).toBeLessThan(h.checkout.mock.invocationCallOrder[0]!); 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("does not navigate on failure or expose an invalid payment link", async () => { + it("closes an unused payment tab on failure and does not 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.navigate).not.toHaveBeenCalled(); + expect(h.closeTab).toHaveBeenCalledOnce(); 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.navigate).toHaveBeenCalledExactlyOnceWith("javascript:invalid", true); + expect(h.closeTab).toHaveBeenCalledTimes(2); }); it("shows live VM estimates and one usage balance without a separate transfer allowance", async () => { @@ -217,7 +223,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", false); + expect(h.navigate).toHaveBeenCalledWith("https://checkout.stripe.com/saved"); }); 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 fb5659368..5fe5f8876 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 { navigateToCheckout } from "@/lib/checkout-navigation"; +import { beginCheckoutNavigation } from "@/lib/checkout-navigation"; import { randomUUID } from "@/lib/random-uuid"; import { PageContainer } from "@/components/ui/PageContainer"; import { Button } from "@/components/ui/button"; @@ -72,6 +72,7 @@ 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(() => @@ -84,13 +85,15 @@ function Budget({ onClose }: { onClose?: () => void }) { ); if (result?.checkoutUrl) { const url = result.checkoutUrl; - const destination = await mutation.execute(async () => navigateToCheckout(url, !!onClose)); + const destination = await mutation.execute(async () => navigation.navigate(url)); 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 30467cccc..5851f8c66 100644 --- a/apps/dashboard/src/components/billing/CheckoutRecovery.tsx +++ b/apps/dashboard/src/components/billing/CheckoutRecovery.tsx @@ -15,8 +15,7 @@ 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 { navigateToCheckout } from "@/lib/checkout-navigation"; -import { invalidatePayments } from "@/lib/billing-events"; +import { beginCheckoutNavigation } from "@/lib/checkout-navigation"; import { ManagedServerActionFeedback } from "@/components/servers/managed/ManagedServerActionFeedback"; import { useManagedServerActions } from "@/components/servers/managed/useManagedServerActions"; import { useBillingScope } from "./BillingWorkspaceContext"; @@ -245,27 +244,33 @@ 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) return; + if (!mounted.current) { + navigation?.close(); + return; + } setResult(response); if (response.status === "ready") { - if (!response.checkoutUrl || operation !== "resume") throw new Error(copy.actionError); - const url = navigateToCheckout(response.checkoutUrl, preserveProject); + if (!response.checkoutUrl || !navigation) throw new Error(copy.actionError); + const url = navigation.navigate(response.checkoutUrl); 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); @@ -273,7 +278,6 @@ 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 d2f236ad1..e7f552876 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, type PreparedCheckoutWorkspace } from "./useCloudBilling"; +import { useCloudCheckout, useCloudPlans } 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; @@ -101,9 +101,8 @@ function PlanPicker({ Boolean(workspaceId ?? billingWorkspaceId) || (currentPlan === "free" && !subscription && !complimentary); const { payload, loading, error, retry } = useCloudPlans(); - // Preserve an explicit website choice; new purchases start with monthly billing. - const [purchaseInterval, setInterval] = useState<"monthly" | "annual">(requestedInterval ?? "monthly"); - const annualSavings = payload && payload.annual.monthsFree > 0 ? payload.ui.monthsFree : undefined; + // Preserve the website choice. Older links without an interval advertised monthly billing. + const [purchaseInterval, setInterval] = useState<"monthly" | "annual">(requestedInterval ?? (autoCheckout ? "monthly" : "annual")); const interval = subscription && subscription.status !== "canceled" ? subscription.interval : !complimentary && payload?.annual.enabled ? purchaseInterval : "monthly"; const hasPlan = !needsCloudPlan({ tier: currentPlan, subscription, complimentary }); @@ -428,14 +427,13 @@ function PlanPicker({ ) : ( @@ -488,13 +485,16 @@ function PlanPicker({ export function CloudCheckoutNotice({ checkoutUrl }: { checkoutUrl: string }) { const { t } = useI18n(); return ( -
-

{t.billing.deployGate.checkoutOpened}

- +
); } diff --git a/apps/dashboard/src/components/billing/CustomPlanConfigurator.tsx b/apps/dashboard/src/components/billing/CustomPlanConfigurator.tsx index 5d4ad750d..63794a6a5 100644 --- a/apps/dashboard/src/components/billing/CustomPlanConfigurator.tsx +++ b/apps/dashboard/src/components/billing/CustomPlanConfigurator.tsx @@ -24,7 +24,6 @@ export function CustomPlanConfigurator({ allocatedDiskGb, actionLabel, interval = "monthly", - annualSavings, }: { catalog: NonNullable; plans: ApiPlan[]; @@ -37,7 +36,6 @@ export function CustomPlanConfigurator({ allocatedDiskGb?: number | null; actionLabel?: string; interval?: "monthly" | "annual"; - annualSavings?: string; onSelect: (quote: BillingCustomQuote) => void; }) { const { t } = useI18n(); @@ -70,7 +68,9 @@ export function CustomPlanConfigurator({ currentOffer?.price[interval] === quote.priceCents && currentOffer.monthlyCredits === quote.monthlyCredits)), ); - const rates = interval === "annual" ? catalog.extraAnnualCents : catalog.extraMonthlyCents; + const annualRates = interval === "annual" ? catalog.extraAnnualCents : undefined; + const rates = annualRates ?? catalog.extraMonthlyCents; + const rateMonths = annualRates ? 12 : 1; const bundle = plans.find((plan) => plan.id === quote?.basePlanTierId); const money = (cents: number) => `$${(cents / 100).toFixed(cents % 100 === 0 ? 0 : 2)}`; @@ -102,9 +102,7 @@ export function CustomPlanConfigurator({
)} - {rates && ( -

- {interpolate(interval === "annual" ? copy.yearlyRates : copy.rates, { - cpu: money(rates.cpuCore), - memory: money(rates.memoryGb), - disk: money(rates.diskGb), - })} -

- )} +

+ {interpolate(copy.rates, { + cpu: money(rates.cpuCore / rateMonths), + memory: money(rates.memoryGb / rateMonths), + disk: money(rates.diskGb / rateMonths), + })} +

{subscription &&

{copy.applyNotice}

} diff --git a/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx b/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx index d0fbed04f..25446098e 100644 --- a/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx +++ b/apps/dashboard/src/components/billing/PendingCheckoutsContext.tsx @@ -1,6 +1,5 @@ "use client"; -import { reportCaughtError } from "@repo/core/diagnostics"; import { createContext, useCallback, @@ -15,19 +14,13 @@ 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; @@ -37,43 +30,29 @@ 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} @@ -85,13 +64,11 @@ function PendingCheckoutsState({ workspaceId, enabled, waiting, - includeManagement, }: { children: ReactNode; workspaceId?: string; enabled: boolean; waiting?: boolean; - includeManagement: boolean; }) { const { t } = useI18n(); const parent = usePendingCheckouts(); @@ -100,7 +77,6 @@ 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); @@ -110,16 +86,6 @@ 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; @@ -136,7 +102,7 @@ function PendingCheckoutsState({ setLoading(false); } } - }, [enabled, workspaceId, includeManagement, t.billing.pendingPayments.loadError]); + }, [enabled, workspaceId, t.billing.pendingPayments.loadError]); useEffect(() => { mounted.current = true; void refresh(); @@ -145,13 +111,10 @@ 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( @@ -172,7 +135,6 @@ 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/PricingCards.tsx b/apps/dashboard/src/components/billing/PricingCards.tsx index 05dd4db3c..33b050e8b 100644 --- a/apps/dashboard/src/components/billing/PricingCards.tsx +++ b/apps/dashboard/src/components/billing/PricingCards.tsx @@ -115,7 +115,6 @@ interface PricingCardsProps { subscribingPlan?: string | null; purchasesDisabled?: boolean; interval?: "monthly" | "annual"; - annualSavings?: string; workspaceScoped?: boolean; selectionLabel?: string; referralOffer?: ReferralPublicOffer; @@ -132,10 +131,11 @@ function formatPrice( ): { label: string; suffix: string | null } { if (cents === null) return { label: ui.custom, suffix: null }; if (cents === 0) return { label: ui.free, suffix: null }; + const monthlyCents = interval === "annual" ? cents / 12 : cents; // Whole dollars stay whole ($39, not $39.00); a cents-precise price keeps them. return { - label: `$${(cents / 100).toFixed(cents % 100 === 0 ? 0 : 2)}`, - suffix: interval === "annual" ? ui.perYear : ui.perMonth, + label: `$${(monthlyCents / 100).toFixed(monthlyCents % 100 === 0 ? 0 : 2)}`, + suffix: ui.perMonth, }; } @@ -193,7 +193,6 @@ export const PricingCards: React.FC = ({ subscribingPlan, purchasesDisabled = false, interval = "monthly", - annualSavings, workspaceScoped = false, selectionLabel, referralOffer, @@ -219,6 +218,7 @@ export const PricingCards: React.FC = ({ const referral = referralOffer && referralPlans([plan], referralOffer, interval).length ? referralOffer : null; const { listCents, chargedCents, discounted } = resolveCardPrice(plan, interval, referral); + // Compare monthly equivalents; annual cards disclose the full charge below. const { label, suffix } = formatPrice( discounted ? chargedCents : listCents, ui, @@ -307,7 +307,7 @@ export const PricingCards: React.FC = ({

{isPaid ? interval === "annual" - ? annualSavings ?? t.billing.pricing.billedAnnually + ? interpolate(t.billing.pricing.annualTotal, { price: `$${(chargedCents! / 100).toFixed(chargedCents! % 100 === 0 ? 0 : 2)}` }) : ui.billedMonthly : ""}

diff --git a/apps/dashboard/src/components/billing/checkout-recovery.test.tsx b/apps/dashboard/src/components/billing/checkout-recovery.test.tsx index 19a048b40..0d2daa8fc 100644 --- a/apps/dashboard/src/components/billing/checkout-recovery.test.tsx +++ b/apps/dashboard/src/components/billing/checkout-recovery.test.tsx @@ -69,6 +69,12 @@ 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" }); - vi.spyOn(window, "open").mockReturnValue(null); + popup = { opener: {}, closed: false, location: { href: "about:blank" }, close: vi.fn() }; + vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window); host = document.createElement("div"); document.body.append(host); root = createRoot(host); @@ -150,7 +157,8 @@ describe("unfinished checkout recovery", () => { workspaceId: server.id, id: item.id, }); - expect(window.open).toHaveBeenCalledExactlyOnceWith(ready.checkoutUrl, "_blank", "noopener,noreferrer"); + expect(popup.location.href).toBe(ready.checkoutUrl); + expect(popup.opener).toBeNull(); expect(h.started).toHaveBeenCalledExactlyOnceWith(ready.checkoutUrl); expect(dialog()?.querySelector('a[target="_blank"]')?.getAttribute("href")).toBe( ready.checkoutUrl, @@ -366,7 +374,7 @@ describe("unfinished checkout recovery", () => { expect(h.get).toHaveBeenCalledTimes(2); }); - it.each(["local", "cloud"])("ignores earlier payment results after switching the %s account without opening checkout", async (account) => { + it.each(["local", "cloud"])("ignores earlier payment results after switching the %s account and closes its reserved tab", async (account) => { let finish!: (value: unknown) => void; h.post.mockReturnValueOnce( new Promise((resolve) => { @@ -384,7 +392,8 @@ describe("unfinished checkout recovery", () => { h.get.mockResolvedValueOnce({ data: { items: [] } }); await render(); await act(async () => finish({ data: ready })); - expect(window.open).not.toHaveBeenCalled(); + expect(popup.location.href).toBe("about:blank"); + expect(popup.close).toHaveBeenCalled(); expect(h.started).not.toHaveBeenCalled(); expect(dialog()?.textContent).not.toContain(item.name); }); @@ -412,15 +421,4 @@ 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 aa1eb806d..0d6b443f0 100644 --- a/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx +++ b/apps/dashboard/src/components/billing/cloud-deploy-pricing.test.tsx @@ -65,6 +65,7 @@ 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) { @@ -88,7 +89,8 @@ 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" } }); - open = vi.spyOn(window, "open").mockReturnValue(null); + checkoutTab = { opener: window, closed: false, location: { href: "about:blank" }, close: vi.fn() }; + open = vi.spyOn(window, "open").mockReturnValue(checkoutTab as unknown as Window); container = document.createElement("div"); document.body.append(container); root = createRoot(container); @@ -140,13 +142,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).not.toHaveBeenCalled(); + expect(open).toHaveBeenCalledOnce(); + expect(checkoutTab.opener).toBeNull(); + expect(checkoutTab.location.href).toBe("about:blank"); expect(mocks.post).toHaveBeenCalledTimes(1); - expect(mocks.post).toHaveBeenCalledWith("billing/subscription", expect.objectContaining({ planTierId: "starter", interval: "monthly", idempotencyKey: expect.any(String) })); + expect(mocks.post).toHaveBeenCalledWith("billing/subscription", expect.objectContaining({ planTierId: "starter", interval: "annual", idempotencyKey: expect.any(String) })); await act(async () => resolveCheckout({ data: { checkoutUrl: "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(checkoutTab.location.href).toBe("https://checkout.example.test/session"); expect(container.querySelector("input")?.value).toBe("My configured project"); expect(mocks.deploy).toHaveBeenCalledTimes(1); await click(copy.deployGate.checkPlan); @@ -209,7 +211,7 @@ describe("deployment plan selection", () => { await click("Deploy"); await click("Choose Hobby"); expect(document.querySelector('[role="alert"]')?.textContent).toBe("Checkout temporarily unavailable"); - expect(open).not.toHaveBeenCalled(); + expect(checkoutTab.close).toHaveBeenCalledOnce(); 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 03937e70b..87dfc56d0 100644 --- a/apps/dashboard/src/components/billing/server-plan-picker.test.tsx +++ b/apps/dashboard/src/components/billing/server-plan-picker.test.tsx @@ -59,6 +59,7 @@ 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); @@ -100,16 +101,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/checkouts" ? { data: { items: [] } } : path === "/billing/manage" ? { data: management } : path.endsWith("/quote") + h.get.mockImplementation(async (path, options) => 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" } }); - vi.spyOn(window, "open").mockReturnValue(null); + popup = { opener: {}, closed: false, location: { href: "about:blank" }, close: vi.fn() }; + vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window); host = document.createElement("div"); document.body.append(host); root = createRoot(host); }); afterEach(async () => { @@ -229,18 +230,16 @@ describe("referral checkout handoff", () => { : ordinary(path, options)); await render(); const card = (name: string) => host.querySelector(`article[aria-label="${name}"]`)!; - expect(card("Hobby").querySelector("s")).toBeNull(); - await click("Yearly"); - expect(card("Hobby").querySelector(".text-2xl")?.textContent).toBe("$108"); - expect(card("Hobby").querySelector("s")?.textContent).toBe("$120"); + expect(card("Hobby").textContent).toContain("$9"); + expect(card("Hobby").querySelector("s")?.textContent).toBe("$10"); expect(card("Starter").querySelector("s")).toBeNull(); await click("Monthly"); expect(card("Hobby").querySelector("s")).toBeNull(); await click("Yearly"); - expect(card("Hobby").querySelector("s")?.textContent).toBe("$120"); + expect(card("Hobby").querySelector("s")?.textContent).toBe("$10"); await click(baseDictionary.referrals.remove); expect(card("Hobby").querySelector("s")).toBeNull(); - expect(card("Hobby").querySelector(".text-2xl")?.textContent).toBe("$120"); + expect(card("Hobby").textContent).toContain("$10"); expect(h.post).not.toHaveBeenCalled(); }); @@ -258,7 +257,6 @@ 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", @@ -285,20 +283,15 @@ describe("annual Cloud purchases", () => { expect(h.post).not.toHaveBeenCalled(); }); - it("defaults to monthly, shows full yearly prices with savings, and submits the selected interval", async () => { + it("shows monthly equivalents with the upfront annual charge and submits yearly checkout", async () => { await render(purchase()); - expect(buttons(copy.pricing.monthly)[0]?.getAttribute("aria-pressed")).toBe("true"); - expect(host.querySelector("article .text-2xl")?.textContent).toBe("$12"); - await click(copy.pricing.annual); - expect(host.querySelector("article .text-2xl")?.textContent).toBe("$120"); - expect(host.querySelector("article")?.textContent).toContain(pricingUi("en").perYear); - expect(host.querySelector("article")?.textContent).toContain("2 months free"); - expect(host.querySelector("article")?.textContent).not.toContain(pricingUi("en").perMonth); - expect(host.querySelector("article")?.textContent).not.toContain("$120 billed yearly"); + expect(buttons(copy.pricing.annual)[0]?.getAttribute("aria-pressed")).toBe("true"); + expect(host.querySelector("article .text-2xl")?.textContent).toBe("$10"); await click(copy.pricing.monthly); expect(host.querySelector("article .text-2xl")?.textContent).toBe("$12"); - expect(host.querySelector("article")?.textContent).not.toContain("2 months free"); await click(copy.pricing.annual); + expect(host.querySelector("article")?.textContent).toContain("$10"); + expect(host.querySelector("article")?.textContent).toContain("$120 billed yearly"); await click("Choose Hobby"); expect(h.post).toHaveBeenCalledExactlyOnceWith("billing/subscription", expect.objectContaining({ planTierId: "hobby", interval: "annual", workspaceId: "cws-production", @@ -311,12 +304,7 @@ describe("annual Cloud purchases", () => { expect(host.querySelector('form button[type="submit"]')?.hasAttribute("disabled")).toBe(true); expect(h.post).not.toHaveBeenCalled(); await flushQuote(); - expect(host.querySelector("aside .text-3xl")?.textContent).toBe("$1188"); - expect(host.querySelector("aside")?.textContent).toContain(copy.custom.yearlyTotal); - expect(host.querySelector("aside")?.textContent).toContain(pricingUi("en").perYear); - expect(host.querySelector("aside")?.textContent).toContain("2 months free"); - expect(host.querySelector("aside")?.textContent).toContain("Yearly extras: $60/vCPU"); - expect(host.querySelector("aside")?.textContent).not.toContain("Monthly"); + expect(host.querySelector("aside")?.textContent).toContain("$1188 billed yearly"); await act(async () => host.querySelector("form")!.requestSubmit()); expect(h.post).toHaveBeenCalledExactlyOnceWith("billing/subscription", expect.objectContaining({ interval: "annual", custom: expect.objectContaining({ quoteReference: "quote-annual" }), @@ -546,83 +534,7 @@ 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, 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(); + expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName }); }); it("keeps the landing-page plan using the live offer without creating anything on arrival", async () => { @@ -721,8 +633,9 @@ 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(); - expect(h.post).not.toHaveBeenCalled(); + const first = h.post.mock.calls[0][1].idempotencyKey; await click(copy.pendingPayments.cancel); h.post.mockResolvedValueOnce({ data: { status: "expired", checkoutId: "cs_pending", checkoutUrl: null } }); await click(copy.pendingPayments.confirmCancel); @@ -730,15 +643,14 @@ 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).toHaveBeenCalledOnce(); - h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : catalog); + expect(h.post).toHaveBeenCalledTimes(2); await act(async () => root.unmount()); root = createRoot(host); await render(); - expect(h.post).toHaveBeenCalledOnce(); + expect(h.post).toHaveBeenCalledTimes(2); await click("Choose Starter"); - 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); + 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); }); it("starts a fresh explicit purchase after removing the cancelled draft", async () => { @@ -748,6 +660,7 @@ 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 } }); @@ -755,12 +668,11 @@ describe("buying another managed server", () => { h.remove.mockResolvedValueOnce({ data: { accepted: true } }); await click(copy.pendingPayments.deleteServer); await click(copy.workspaces.confirmDelete); - expect(h.create).not.toHaveBeenCalled(); - h.get.mockImplementation(async path => path === "billing/checkouts" ? { data: { items: [] } } : catalog); + expect(h.create).toHaveBeenCalledOnce(); 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[0][0].idempotencyKey).not.toBe(key); + expect(h.create.mock.calls[1][0].idempotencyKey).not.toBe(key); }); it("does not continue a pending pricing purchase in another account or organization", async () => { @@ -782,7 +694,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/checkouts" ? { data: { items: [] } } : path === "billing/state" ? { data: billing } : catalog); + h.get.mockImplementation(async path => path === "billing/state" ? { data: billing } : catalog); const location = window.location.href; await render(); await click("Add a destination"); @@ -817,7 +729,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, idempotencyKey: expect.any(String) }); + expect(h.create).toHaveBeenCalledExactlyOnceWith({ name: copy.workspaces.defaultName }); expect(h.post).not.toHaveBeenCalled(); await act(async () => created(server)); expect(h.post).toHaveBeenCalledWith("billing/subscription", expect.objectContaining({ workspaceId: server.id, planTierId: "starter" })); @@ -826,7 +738,8 @@ 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(window.open).toHaveBeenCalledExactlyOnceWith("https://checkout.example.test/new-server", "_blank", "noopener,noreferrer"); + expect(popup.location.href).toBe("https://checkout.example.test/new-server"); + expect(popup.opener).toBeNull(); }); it("keeps the new server and exact purchase when retrying from unavailable-capacity feedback", async () => { @@ -837,7 +750,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(window.open).not.toHaveBeenCalled(); + expect(popup.close).toHaveBeenCalledOnce(); expect(h.post.mock.calls[0]![1]).toMatchObject({ workspaceId: server.id, planTierId: "pro" }); await click(copy.checkoutUnavailable.retry); expect(h.create).toHaveBeenCalledOnce(); @@ -850,6 +763,7 @@ 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" } }); @@ -859,7 +773,6 @@ 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" }); @@ -867,9 +780,10 @@ 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(1); - expect(attempts[0].workspaceId).toBe(remove ? "cws-replacement" : server.id); - expect(h.create).toHaveBeenCalledTimes(remove ? 1 : 0); + 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); }); it("discards an unavailable checkout when the customer changes organization", async () => { @@ -892,7 +806,7 @@ describe("buying another managed server", () => { await render(); await act(async () => created(server)); expect(h.post).not.toHaveBeenCalled(); - expect(window.open).not.toHaveBeenCalled(); + expect(popup.close).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 8abbeea39..97fc55b83 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 { navigateToCheckout } from "@/lib/checkout-navigation"; -import { invalidatePayments } from "@/lib/billing-events"; +import { beginCheckoutNavigation } from "@/lib/checkout-navigation"; import { endpoints } from "@/lib/api/endpoints"; import { randomUUID } from "@/lib/random-uuid"; import { checkoutFailureKind, type CheckoutFailure } from "@/lib/checkout-failure"; -import { useResourceScope } from "@/hooks/use-scoped-resource"; +import { useSession } from "@/lib/auth-client"; +import { useCloudResourceKey } from "@/context/CloudResourceContext"; import type { ApiPlan, ApiPricingUi } from "./PricingCards"; interface PlansPayload extends Omit { @@ -20,8 +20,6 @@ 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(); @@ -49,7 +47,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; @@ -57,8 +55,9 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS }) { const { t } = useI18n(); const { workspaceId: billingWorkspaceId, organizationId } = useBillingScope(); - const scope = useResourceScope(); - const ownerKey = `${scope}:${organizationId ?? ""}`; + const { data: session } = useSession(); + const cloudKey = useCloudResourceKey(); + const ownerKey = `${cloudKey}:${session?.user.id}:${organizationId ?? session?.session?.activeOrganizationId}`; const workspaceId = selectedWorkspaceId ?? billingWorkspaceId ?? undefined; const [subscribing, setSubscribing] = useState(null); const [error, setError] = useState(null); @@ -79,10 +78,11 @@ 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 || checkoutUrl || planTierId === "free" || planTierId === "enterprise") return; + if (!enabled || busy.current || planTierId === "free" || planTierId === "enterprise") return; busy.current = true; const version = generation.current; - let checkoutStarted = false; + // Open within the user's click, preserving unfinished project configuration. + const navigation = beginCheckoutNavigation(preserveProject); setSubscribing(custom ? "custom" : planTierId); setError(null); setCheckoutUrl(null); @@ -91,13 +91,8 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS let targetWorkspaceId = workspaceId; let requestId: string | undefined; try { - 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; - } + targetWorkspaceId = prepareWorkspace ? await prepareWorkspace() : workspaceId; + if (version !== generation.current) { navigation.close(); 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, @@ -107,14 +102,14 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS planTierId, interval, workspaceId: targetWorkspaceId, custom, idempotencyKey: requestId, ...(referralCode ? { referralCode } : {}), }); - if (version !== generation.current) return; - const url = navigateToCheckout(res.data.checkoutUrl, preserveProject); + if (version !== generation.current) { navigation.close(); return; } + const url = navigation.navigate(res.data.checkoutUrl); 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 }); @@ -125,9 +120,8 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS } } finally { if (version === generation.current) { - busy.current = checkoutStarted; + busy.current = false; setSubscribing(null); - invalidatePayments(); } } } @@ -135,7 +129,7 @@ export function useCloudCheckout({ enabled, preserveProject = false, onCheckoutS recovery: { isOpen: pending !== null, workspaceId: pending?.workspaceId, preserveProject, onClose: () => setPending(null), - onCleared: () => { busy.current = false; attempts.current.clear(); setCheckoutUrl(null); setError(null); onCheckoutSettled?.(); }, + onCleared: () => { attempts.current.clear(); 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/import-project/DeploymentContainerConflictNotice.test.tsx b/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.test.tsx deleted file mode 100644 index 838edb9f4..000000000 --- a/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.test.tsx +++ /dev/null @@ -1,89 +0,0 @@ -// @vitest-environment happy-dom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import { baseDictionary } from "@/i18n"; -import { - DEFAULT_CONFIG, - INITIAL_STATE, - type DeploymentContextType, -} from "@/context/deployment/types"; -import { DeploymentContainerConflictNotice } from "./DeploymentContainerConflictNotice"; - -let deployment: Pick; -vi.mock("@/context/DeploymentContext", () => ({ useDeployment: () => deployment })); -vi.mock("@/components/i18n-provider", () => ({ useI18n: () => ({ t: baseDictionary }) })); -let root: Root; -let host: HTMLDivElement; -const copy = baseDictionary.deployments.containerConflict; -beforeEach(() => { - vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); - deployment = { - config: { - ...structuredClone(DEFAULT_CONFIG), - serverId: "server-current", - workspaceId: "space-current", - }, - state: { - ...structuredClone(INITIAL_STATE), - deploymentId: "attempt-original", - deploymentFailed: true, - errorCode: "SERVICE_CONTAINER_CONFLICT", - errorDetails: { - containerNames: ['', "app-duplicate"], - serverId: "server-original", - }, - }, - deploymentStatus: "failed", - }; - host = document.createElement("div"); - document.body.append(host); - root = createRoot(host); -}); -afterEach(async () => { - await act(async () => root.unmount()); - host.remove(); - vi.unstubAllGlobals(); -}); -async function render() { - await act(async () => root.render()); -} - -it("explains the conflict and links to the recorded server and support, without destructive actions", async () => { - await render(); - expect(host.textContent).toContain(copy.title); - expect(host.textContent).toContain("app-duplicate"); - expect(host.textContent).toContain("attempt-original"); - expect(host.querySelector('a[href="/servers/server-original"]')).not.toBeNull(); - expect(host.querySelector('a[href="/support"]')).not.toBeNull(); - expect(host.querySelectorAll("button")).toHaveLength(0); - expect(host.querySelector("img")).toBeNull(); -}); -it("opens the recorded managed space when no standalone server was recorded", async () => { - deployment.state.errorDetails = { containerNames: ["a", "b"], workspaceId: "space-original" }; - await render(); - expect(host.querySelector('a[href="/resources?pool=space-original"]')).not.toBeNull(); -}); -it("does not guess a missing historical target from current configuration", async () => { - deployment.state.errorDetails = null; - await render(); - expect(host.querySelectorAll("a")).toHaveLength(1); - expect(host.querySelector('a[href="/support"]')).not.toBeNull(); -}); -it.each(["building", "verifying", "ready", "cancelled"] as const)( - "clears the notice for %s", - async (status) => { - deployment.deploymentStatus = status; - await render(); - expect(host.textContent).toBe(""); - }, -); -it("does not reinterpret another error or a cancelled attempt as a container conflict", async () => { - deployment.state.errorCode = "HOST_UNREACHABLE"; - await render(); - expect(host.textContent).toBe(""); - deployment.state.errorCode = "SERVICE_CONTAINER_CONFLICT"; - deployment.state.deploymentCanceled = true; - await render(); - expect(host.textContent).toBe(""); -}); diff --git a/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.tsx b/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.tsx deleted file mode 100644 index 5c30828b0..000000000 --- a/apps/dashboard/src/components/import-project/DeploymentContainerConflictNotice.tsx +++ /dev/null @@ -1,61 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { useDeployment } from "@/context/DeploymentContext"; -import { useI18n } from "@/components/i18n-provider"; -import { Button } from "@/components/ui/button"; - -/** Use this attempt's recorded target, even after the project has moved. */ -export function DeploymentContainerConflictNotice() { - const { state, deploymentStatus } = useDeployment(); - const { t } = useI18n(); - if ( - deploymentStatus !== "failed" || - state.deploymentCanceled || - state.errorCode !== "SERVICE_CONTAINER_CONFLICT" - ) - return null; - const copy = t.deployments.containerConflict; - const details = state.errorDetails; - const names = Array.isArray(details?.containerNames) - ? details.containerNames.filter((value): value is string => typeof value === "string") - : []; - const serverId = typeof details?.serverId === "string" && details.serverId; - const workspaceId = typeof details?.workspaceId === "string" && details.workspaceId; - const targetHref = serverId - ? `/servers/${encodeURIComponent(serverId)}` - : workspaceId - ? `/resources?pool=${encodeURIComponent(workspaceId)}` - : null; - - return ( -
-

{copy.title}

-

{copy.description}

- {names.length > 0 && ( -
    - {names.map((name, index) => ( -
  • - {name} -
  • - ))} -
- )} - {state.deploymentId && ( -

- {copy.reference}: {state.deploymentId} -

- )} -
- {targetHref && ( - - )} - -
-
- ); -} diff --git a/apps/dashboard/src/components/import-project/compose/ComposeDeploymentProcessing.tsx b/apps/dashboard/src/components/import-project/compose/ComposeDeploymentProcessing.tsx index ee5d48346..cf4cc6d1c 100644 --- a/apps/dashboard/src/components/import-project/compose/ComposeDeploymentProcessing.tsx +++ b/apps/dashboard/src/components/import-project/compose/ComposeDeploymentProcessing.tsx @@ -12,7 +12,6 @@ import { DeploymentHeader } from "../DeploymentHeader"; import { DeploymentHealthWarning } from "../DeploymentHealthWarning"; import { CloudBuildQueueNotice } from "../CloudBuildQueueNotice"; import { CloudDeploymentResourceNotice } from "../CloudDeploymentResourceNotice"; -import { DeploymentContainerConflictNotice } from "../DeploymentContainerConflictNotice"; import { DeploymentLayout } from "../DeploymentLayout"; import { DeploymentLogsPanel } from "../DeploymentLogsPanel"; import { PageContainer } from "@/components/ui/PageContainer"; @@ -577,7 +576,7 @@ function ComposeDeploymentBody({ return ( } + notice={} details={} navigation={
diff --git a/apps/dashboard/src/components/instance/InstanceLocation.tsx b/apps/dashboard/src/components/instance/InstanceLocation.tsx index 5b893c744..80efb4396 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 )} - {state.role === "active" && h?.provisioning?.deploymentId && ( + {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 37ab3fa0e..171377bd4 100644 --- a/apps/dashboard/src/components/instance/instance-location.test.tsx +++ b/apps/dashboard/src/components/instance/instance-location.test.tsx @@ -41,14 +41,4 @@ 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 22c607f61..f450af8bb 100644 --- a/apps/dashboard/src/components/migration/PlatformImportReview.tsx +++ b/apps/dashboard/src/components/migration/PlatformImportReview.tsx @@ -37,7 +37,6 @@ export function PlatformImportReview({ onStart: () => void; }) { const imports = plan.services.filter((s) => choices[s.id]?.data !== "external"); - const projectCount = plan.projects?.length ?? 1; return (
@@ -87,15 +86,6 @@ export function PlatformImportReview({

{importDataLabel(service, choice)}

- {projectCount > 1 && ( -

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

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

Review complete

- {projectCount} {projectCount === 1 ? "project" : "projects"} · {imports.length}{" "} - {imports.length === 1 ? "service" : "services"} + One project · {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 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. + Services stay together in one project on its private network. 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 4646d0d7a..60675649a 100644 --- a/apps/dashboard/src/components/migration/platform-import-flow.test.tsx +++ b/apps/dashboard/src/components/migration/platform-import-flow.test.tsx @@ -533,9 +533,7 @@ describe("platform import flow", () => { await render(); await click("Choose services"); expect(button("Check import").disabled).toBe(true); - expect(host.textContent).toContain( - "Services with different Git sources import into separate projects", - ); + expect(host.textContent).toContain("Services stay together in one project"); await fill(host.querySelector('input[type="password"]')!, "fixture-secret"); await click("Check import"); expect(h.review).toHaveBeenCalledWith( @@ -572,25 +570,6 @@ 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 ac1024970..aa0d4fe73 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 { ProjectIcon } from "@/components/shared/ProjectIcon"; +import { AppLogo } from "@/components/AppLogo"; 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/referrals/ReferralLanding.test.tsx b/apps/dashboard/src/components/referrals/ReferralLanding.test.tsx index 2f768970a..046883982 100644 --- a/apps/dashboard/src/components/referrals/ReferralLanding.test.tsx +++ b/apps/dashboard/src/components/referrals/ReferralLanding.test.tsx @@ -74,10 +74,10 @@ afterEach(async () => { vi.unstubAllGlobals(); }); -it("shows the live Cloud cards, defaults to monthly and continues the selected plan with its referral", async () => { +it("shows the live Cloud cards, defaults to annual and continues the selected plan with its referral", async () => { await render(); expect(titles()).toEqual(["Hobby", "Starter", "Pro", "Scale"]); - expect(button("Monthly").getAttribute("aria-pressed")).toBe("true"); + expect(button("Yearly").getAttribute("aria-pressed")).toBe("true"); expect(host.textContent).toContain("Save 5% for 12 months"); expect(h.push).not.toHaveBeenCalled(); await click("Choose Hobby"); @@ -85,23 +85,23 @@ it("shows the live Cloud cards, defaults to monthly and continues the selected p expect(Object.fromEntries(target().searchParams)).toEqual({ newServer: "1", plan: "hobby", - interval: "monthly", + interval: "annual", startCheckout: "1", ref: code, }); expect(validateReturnTo(`${target().pathname}${target().search}`)).not.toBeNull(); }); -it("preserves yearly selection and keeps generic sign-in browse-only", async () => { +it("preserves monthly selection and keeps generic sign-in browse-only", async () => { await render(); const signIn = host.querySelector('a[href^="/login?"]')!; const destination = new URL(signIn.href).searchParams.get("returnTo")!; expect(validateReturnTo(destination)).toBe(destination); expect(destination).toBe(`/billing/plans?newServer=1&ref=${code}`); - await click("Yearly"); + await click("Monthly"); expect(h.push).not.toHaveBeenCalled(); await click("Choose Starter"); - expect(target().searchParams.get("interval")).toBe("annual"); + expect(target().searchParams.get("interval")).toBe("monthly"); expect(target().searchParams.get("ref")).toBe(code); }); @@ -186,19 +186,18 @@ it("limits public cards to the selected plan and billing combinations and choose it.each([ - ["annual", 1000, 12000, 1000, "$108", "$120", "Billed yearly"], + ["annual", 1000, 12000, 1000, "$9", "$10", "$108 billed yearly"], ["monthly", 1200, 12000, 1000, "$10.80", "$12", "billed monthly"], ["monthly", 1231, 12000, 500, "$11.69", "$12.31", "billed monthly"], - ["annual", 1000, 12000, 0, "$120", null, "Billed yearly"], + ["annual", 1000, 12000, 0, "$10", null, "$120 billed yearly"], ["monthly", 1200, 12000, 10000, "Free", "$12", "billed monthly"], ] as const)("shows %s referral prices for %i/%i cents at %i basis points", async (interval, monthly, annual, discountBps, price, original, billing) => { h.offer.mockResolvedValue({ ...offer, discountBps }); catalog([{ ...plans[0]!, price: { monthly, annual }, listPrice: { monthly }, effectivePrice: { monthly } }]); await render(); - if (interval === "annual") await click("Yearly"); + if (interval === "monthly") await click("Monthly"); const card = host.querySelector('article[aria-label="Hobby"]')!; - expect(card.querySelector(".text-2xl")?.textContent).toBe(price); - if (price !== "Free") expect(card.textContent).toContain(interval === "annual" ? pricingUi("en").perYear : pricingUi("en").perMonth); + expect(card.textContent).toContain(price); expect(card.querySelector("s")?.textContent ?? null).toBe(original); expect(card.textContent).toContain(billing); if (discountBps) expect(card.textContent).toContain(`Save ${discountBps / 100}% for 12 months`); diff --git a/apps/dashboard/src/components/referrals/ReferralLanding.tsx b/apps/dashboard/src/components/referrals/ReferralLanding.tsx index 92408efad..fdcb14b6c 100644 --- a/apps/dashboard/src/components/referrals/ReferralLanding.tsx +++ b/apps/dashboard/src/components/referrals/ReferralLanding.tsx @@ -22,7 +22,7 @@ export function ReferralLanding({ code }: { code: string }) { copy = t.referrals; const router = useRouter(); const catalog = useCloudPlans(); - const [selectedInterval, setInterval] = useState<"monthly" | "annual">("monthly"); + const [selectedInterval, setInterval] = useState<"monthly" | "annual">("annual"); const [state, setState] = useState<{ offer?: ReferralPublicOffer; error?: string }>({}); const load = useCallback(async () => { try { @@ -140,7 +140,6 @@ export function ReferralLanding({ code }: { code: string }) { ui={catalog.payload.ui} currentPlan={null} interval={interval} - annualSavings={catalog.payload.annual.monthsFree > 0 ? catalog.payload.ui.monthsFree : undefined} referralOffer={state.offer} workspaceScoped onSelectPlan={(planId) => { diff --git a/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx b/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx index 51eaa78de..c475b1b53 100644 --- a/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx +++ b/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx @@ -1,6 +1,5 @@ "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"; @@ -9,9 +8,8 @@ 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 { getApiErrorCode, getApiErrorMessage } from "@/lib/api/client"; -import { billingApi } from "@/lib/api/billing"; -import { useResourceScope } from "@/hooks/use-scoped-resource"; +import { getApiErrorMessage } from "@/lib/api/client"; +import { useCloudResourceKey } from "@/context/CloudResourceContext"; import { randomUUID } from "@/lib/random-uuid"; import { isCloudPurchaseIntent } from "@/lib/cloud-purchase-intent"; @@ -33,7 +31,8 @@ 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 contextKey = useResourceScope(); + const cloudKey = useCloudResourceKey(); + const contextKey = `${cloudKey}:${session?.user.id ?? "local"}:${session?.session.activeOrganizationId ?? ""}`; 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; @@ -85,55 +84,14 @@ 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() { - 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; + created.current ??= await systemApi.createManagedServer({ + name: t.billing.workspaces.defaultName, + ...(checkoutIntent ? { idempotencyKey: checkoutIntent } : {}), + }); return created.current.id; } diff --git a/apps/dashboard/src/components/settings/ImageUrlEditor.test.tsx b/apps/dashboard/src/components/settings/ImageUrlEditor.test.tsx deleted file mode 100644 index a865f71f8..000000000 --- a/apps/dashboard/src/components/settings/ImageUrlEditor.test.tsx +++ /dev/null @@ -1,102 +0,0 @@ -// @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 deleted file mode 100644 index d2e035f0a..000000000 --- a/apps/dashboard/src/components/settings/ImageUrlEditor.tsx +++ /dev/null @@ -1,143 +0,0 @@ -"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 deleted file mode 100644 index 3a5dd68c1..000000000 --- a/apps/dashboard/src/components/settings/image-settings.test.tsx +++ /dev/null @@ -1,82 +0,0 @@ -// @vitest-environment happy-dom -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import { 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 deleted file mode 100644 index 629e03763..000000000 --- a/apps/dashboard/src/components/shared/ProjectIcon.tsx +++ /dev/null @@ -1,43 +0,0 @@ -"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 6ebfdc608..dc5b314a9 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 project icons ahead of the service-group fallback", () => { + it("keeps favicons 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 00d062b2a..40d63c979 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 project icon or catalog logo, shared by project rows +/** Fallback identity after a catalog logo or favicon, 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 164291992..406f34065 100644 --- a/apps/dashboard/src/components/sidebar.test.tsx +++ b/apps/dashboard/src/components/sidebar.test.tsx @@ -9,8 +9,6 @@ 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", @@ -20,8 +18,6 @@ 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, @@ -29,7 +25,6 @@ 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: [] }), @@ -60,8 +55,6 @@ 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}`); }, }, @@ -81,8 +74,6 @@ 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); @@ -124,48 +115,18 @@ it.each([ expect(mocks.projects).toHaveBeenCalledOnce(); }); -async function render(props: ComponentProps = {}, payments = false) { - const content = ; +async function render(props: ComponentProps = {}) { 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 009db0fe6..3f3f315b4 100644 --- a/apps/dashboard/src/components/sidebar.tsx +++ b/apps/dashboard/src/components/sidebar.tsx @@ -1,7 +1,5 @@ "use client"; -import { UserAvatar } from "@/components/ui/UserAvatar"; - import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics"; import { Icon as UiIcon } from "@repo/ui/icons"; @@ -24,7 +22,6 @@ 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, @@ -156,13 +153,11 @@ 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; }; @@ -378,20 +373,18 @@ 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 attentionLabel = + const issueLabel = key === "issues" && count != null && count > 0 ? `${label(key, labelSource)}: ${count === 1 ? t.dashboard.home.oneIssue : interpolate(t.dashboard.home.manyIssues, { n: String(count) })}` - : key === "billing" && count != null && count > 0 - ? `${label(key, labelSource)}: ${interpolate(t.billing.pendingPayments.count, { count: String(count) })}` - : undefined; + : undefined; return ( @@ -399,18 +392,10 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo {!collapsed && ( {label(key, labelSource)} )} - {/* Keep attention counts accessible when the rail is collapsed. */} - {(!collapsed || key === "billing") && count != null && count > 0 && ( + {/* Hide zero/loading counts; keep issue counts in the collapsed label. */} + {!collapsed && count != null && count > 0 && ( {count} @@ -474,11 +459,9 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo title={collapsed ? activeOrg?.name : undefined} > {/* Org avatar / initial */} - {activeOrg?.id === `org_${user?.id}` ? : ( -
- {activeOrg?.name?.[0] ?? } -
- )} +
+ {activeOrg?.name?.[0] ?? } +
{!collapsed && ( <> @@ -567,7 +550,9 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo {/* Footer separator + signed-in-as + sign out */}
- +
+ {displayInitial} +

{displayName} @@ -614,7 +599,9 @@ 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 deleted file mode 100644 index e398f65d7..000000000 --- a/apps/dashboard/src/components/ui/UserAvatar.tsx +++ /dev/null @@ -1,37 +0,0 @@ -"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/components/updates/RuntimeSourceUpdate.test.tsx b/apps/dashboard/src/components/updates/RuntimeSourceUpdate.test.tsx index 614e607b2..dba1cef03 100644 --- a/apps/dashboard/src/components/updates/RuntimeSourceUpdate.test.tsx +++ b/apps/dashboard/src/components/updates/RuntimeSourceUpdate.test.tsx @@ -7,7 +7,7 @@ import { CloudResourceContext } from "@/context/CloudResourceContext"; import { ApiError, setApiResourceScope } from "@/lib/api/client"; import { RuntimeSourceUpdate } from "./RuntimeSourceUpdate"; import { SecurityProjectReview } from "./SecurityProjectReview"; -import type { ProjectControlOperations, ProjectSecurityResult } from "@repo/contracts"; +import type { ProjectSecurityResult } from "@repo/contracts"; const api = vi.hoisted(() => ({ git: vi.fn(), read: vi.fn(), preview: vi.fn(), publish: vi.fn() })); vi.mock("@/lib/api/projects", () => ({ projectsApi: { getGit: api.git } })); @@ -23,22 +23,6 @@ vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) })); vi.mock("@/context/ToastContext", () => ({ useToast: () => ({ showToast: vi.fn() }) })); vi.mock("@/hooks/useRuntimeUpdate", () => ({ useRuntimeUpdate: () => ({ updating: false }) })); let root: Root, host: HTMLDivElement; -const gitInfo = { - success: true, - provider: "github", - owner: "acme", - repo: "app", - branch: "main", - commits: [], - auto_deploy: false, - webhook_strategy: "app", - webhook_active: true, - webhook_domain: null, - available_strategies: ["app"], - verified_domains: [], - installation_installed: true, - default_rollback_strategy: "git", -} satisfies Awaited>; const source = { owner: "acme", repo: "app", @@ -54,7 +38,12 @@ beforeEach(() => { vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); setApiResourceScope("source-test"); vi.resetAllMocks(); - api.git.mockResolvedValue(gitInfo); + api.git.mockResolvedValue({ + gitProvider: "github", + gitOwner: "acme", + gitRepo: "app", + gitBranch: "main", + }); api.read.mockResolvedValue({ data: source }); api.preview.mockResolvedValue({ data: { @@ -101,8 +90,6 @@ async function setImage(value: string) { it("requires a reviewed diff, invalidates it on edit, and creates a PR without triggering a deployment", async () => { await render(); await click("Propose image update"); - expect(api.read).toHaveBeenCalledWith("project", { path: "Dockerfile", format: "dockerfile" }); - expect(document.body.textContent).toContain("acme/app · main"); await setImage("node:24"); expect(document.body.textContent).not.toContain("Create draft PR"); await click("Review change"); @@ -122,20 +109,6 @@ it("requires a reviewed diff, invalidates it on edit, and creates a PR without t ); expect(document.body.textContent).toContain("Recheck the deployed runtime"); }); -it.each([ - { success: false, error: "No repository connected", code: "NO_REPOSITORY" }, - { ...gitInfo, provider: "local" }, - { ...gitInfo, branch: "" }, -])("does not load or publish source without a supported repository and branch: %j", async (git) => { - api.git.mockResolvedValue(git); - await render(); - await click("Propose image update"); - expect(document.body.textContent).toContain( - "This project needs a connected GitHub repository and deployment branch.", - ); - expect(api.read).not.toHaveBeenCalled(); - expect(api.publish).not.toHaveBeenCalled(); -}); it("discards source and pending responses after an account/workspace switch", async () => { let resolve!: (value: unknown) => void; api.read.mockImplementationOnce( diff --git a/apps/dashboard/src/components/updates/RuntimeSourceUpdate.tsx b/apps/dashboard/src/components/updates/RuntimeSourceUpdate.tsx index 28549358a..0bdecdb2e 100644 --- a/apps/dashboard/src/components/updates/RuntimeSourceUpdate.tsx +++ b/apps/dashboard/src/components/updates/RuntimeSourceUpdate.tsx @@ -122,20 +122,27 @@ function SourceEditor({ setBusy(true); projectsApi .getGit(projectId) - .then(async (git) => { - if (!current(request)) return; - if (!git.success || git.provider !== "github" || !git.owner || !git.repo || !git.branch) { - setError(copy.noRepository); - return; - } - setRepo({ owner: git.owner, repo: git.repo, branch: git.branch }); - const { data } = await updatesApi.runtimeSource(projectId, { - path: initialPath, - format: /\.ya?ml$/i.test(initialPath) ? "compose" : "dockerfile", - ...(serviceId && { serviceId }), - }); - if (current(request)) acceptSource(data); - }) + .then( + async (git: { + gitProvider?: string; + gitOwner?: string; + gitRepo?: string; + gitBranch?: string; + }) => { + if (!current(request)) return; + if (git.gitProvider !== "github" || !git.gitOwner || !git.gitRepo || !git.gitBranch) { + setError(copy.noRepository); + return; + } + setRepo({ owner: git.gitOwner, repo: git.gitRepo, branch: git.gitBranch }); + const { data } = await updatesApi.runtimeSource(projectId, { + path: initialPath, + format: /\.ya?ml$/i.test(initialPath) ? "compose" : "dockerfile", + ...(serviceId && { serviceId }), + }); + if (current(request)) acceptSource(data); + }, + ) .catch((error) => { // diagnostics-ignore: showError reports through getApiErrorMessage and displays recovery. if (current(request)) showError(error); diff --git a/apps/dashboard/src/components/updates/useUpdates.requests.test.tsx b/apps/dashboard/src/components/updates/useUpdates.requests.test.tsx index 611d94b00..743d047a3 100644 --- a/apps/dashboard/src/components/updates/useUpdates.requests.test.tsx +++ b/apps/dashboard/src/components/updates/useUpdates.requests.test.tsx @@ -64,7 +64,6 @@ async function mount() { ); } const releaseRequests = () => fetcher.mock.calls.filter(([url]) => String(url).includes("github")); -const noticeRequests = () => fetcher.mock.calls.filter(([url]) => String(url).endsWith("/notices")); beforeEach(async () => { vi.resetModules(); @@ -155,17 +154,17 @@ describe("advisory dismissal within an app session", () => { expect(state[0].state?.advisories).toEqual([critical, next]); }); - it("also shares dismissal for verified security notices in the cloud dashboard", async () => { + it("also shares dismissal for operator notices in the cloud dashboard", async () => { delete window.desktop; deployment.selfHosted = false; - feed.overview = affectedOverview; + // Every consumer receives its own readable response body. + fetcher.mockImplementation( + async () => new Response(JSON.stringify({ advisories: [critical] })), + ); await mount(); expect(check).toHaveBeenCalledOnce(); - expect(state[0].state?.advisories).toEqual([ - expect.objectContaining({ title: "Affected runtime", severity: "critical" }), - ]); - const noticeId = state[0].state!.advisories[0].id; - await act(async () => state[0].dismissAdvisory(noticeId)); + expect(state[0].state?.advisories).toEqual([critical]); + await act(async () => state[0].dismissAdvisory(critical.id)); await act(async () => state[1].reload()); expect(state[0].state?.advisories).toEqual([]); expect(state[1].state?.advisories).toEqual([]); @@ -193,37 +192,6 @@ afterEach(async () => { }); describe("release check requests (#661)", () => { - it.each([false, true])("only loads verified security for a new Cloud session (affected=%s)", async (affected) => { - delete window.desktop; - deployment.selfHosted = false; - const release = { - ...critical, id: "legacy-release", severity: "recommended", announce: false, affects: "*", - title: "OpenShip 0.9.0 is released", target: { type: "platform" }, - action: { kind: "open-url", label: "View release notes", url: "https://github.com/oblien/openship/releases/tag/v0.9.0" }, - }; - check.mockResolvedValue({ ...snapshot, manifest: { advisories: [release] } }); - fetcher.mockImplementation(async () => new Response(JSON.stringify({ advisories: [release, critical] }))); - if (affected) feed.overview = affectedOverview; - await mount(); - expect(noticeRequests()).toHaveLength(0); - expect(state[0].state?.advisories).toEqual(affected - ? [expect.objectContaining({ title: "Affected runtime", severity: "critical" })] - : []); - expect(state[0].state?.updateAvailable).toBe(false); - expect(state[0].latest).toBeNull(); - expect(localStorage.length).toBe(0); - }); - - it.each(["desktop", "selfhosted"])("keeps release and operator announcements for %s", async (mode) => { - if (mode === "selfhosted") delete window.desktop; - const release = { ...critical, id: "release-notice", severity: "recommended" as const }; - check.mockResolvedValue({ ...snapshot, manifest: { advisories: [release] } }); - fetcher.mockImplementation(async () => new Response(JSON.stringify({ advisories: [critical] }))); - await mount(); - expect(noticeRequests().length).toBeGreaterThan(0); - expect(state[0].state?.advisories.map((notice) => notice.id)).toEqual([critical.id, release.id]); - }); - it.each(["desktop", "selfhosted", "cloud"])( "scopes signed control-plane advisories correctly in %s", async (mode) => { diff --git a/apps/dashboard/src/components/updates/useUpdates.ts b/apps/dashboard/src/components/updates/useUpdates.ts index c4f436f34..120c3c79c 100644 --- a/apps/dashboard/src/components/updates/useUpdates.ts +++ b/apps/dashboard/src/components/updates/useUpdates.ts @@ -304,8 +304,10 @@ function runtimeNotices(overview: SecurityOverview, scope: string): RuntimeAdvis return [...notices.values()]; } -// Operator announcements for Desktop and self-hosted instances. Managed Cloud's -// update banner uses verified workload-security notices, so it skips this feed. +// The SaaS advisory source: operator-pushed platform notices from our own API +// (partial outage, maintenance, upgrade advisories), returned in the SAME +// manifest shape as the GitHub advisory feed so the shared banner renders both +// identically. Same-origin on the SaaS; never throws (offline → no notices). async function fetchNotices(): Promise { try { const res = await fetch(`${getRestApiBaseUrl()}/notices`, { @@ -424,7 +426,7 @@ export function useUpdates(): UseUpdates { const [prefs, remote, notices] = await Promise.all([ getPrefs(), fetchRemote(requestKey), - mode === "cloud" ? Promise.resolve({ advisories: [] }) : fetchNotices(), + fetchNotices(), ]); if (!isCurrent()) return; setCurrentVersion(current); diff --git a/apps/dashboard/src/constants/mock.ts b/apps/dashboard/src/constants/mock.ts index 91532d414..a69bb41eb 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) ─────────────────────── */ - iconUrl?: string | null; + favicon?: string | null; deployTarget?: string | null; serverId?: string | null; serverName?: string | null; diff --git a/apps/dashboard/src/context/ProjectSettingsContext.tsx b/apps/dashboard/src/context/ProjectSettingsContext.tsx index a89f1139d..0a84110b2 100644 --- a/apps/dashboard/src/context/ProjectSettingsContext.tsx +++ b/apps/dashboard/src/context/ProjectSettingsContext.tsx @@ -755,8 +755,7 @@ const ProjectSettingsState: React.FC = ({ verifiedDomains: response.verified_domains, installationInstalled: response.installation_installed, installUrl: response.install_url, - defaultRollbackStrategy: - response.default_rollback_strategy === "snapshot" ? "snapshot" : "git", + defaultRollbackStrategy: response.default_rollback_strategy, }); } else { // "No repository connected" is the NORMAL state for upload/local diff --git a/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx b/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx index 46973e557..a5ea2f0be 100644 --- a/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx +++ b/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx @@ -107,7 +107,8 @@ 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 open = vi.spyOn(window, "open").mockReturnValue(null); + const popup = { close: vi.fn(), opener: null, location: { href: "about:blank" } }; + const open = vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window); const started = vi.fn(); function Checkout() { const checkout = useCloudCheckout({ enabled: true, preserveProject: true, onCheckoutStarted: started }); @@ -120,7 +121,8 @@ 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(open).not.toHaveBeenCalled(); + expect(popup.location.href).toBe("about:blank"); + expect(popup.close).toHaveBeenCalledOnce(); expect(started).not.toHaveBeenCalled(); } finally { open.mockRestore(); } }); diff --git a/apps/dashboard/src/i18n/locales/ar/auth.json b/apps/dashboard/src/i18n/locales/ar/auth.json index 3f552cd63..a414e78af 100644 --- a/apps/dashboard/src/i18n/locales/ar/auth.json +++ b/apps/dashboard/src/i18n/locales/ar/auth.json @@ -70,8 +70,6 @@ "errorDescription": "قد يكون الرمز غير صحيح أو منتهي الصلاحية.", "resendEmail": "إعادة إرسال الرمز", "signIn": "تسجيل الدخول", - "signupTitle": "تحقق من بريدك الإلكتروني", - "signupSentTo": "أرسلنا الخطوة التالية إلى {email}. أدخل الرمز أدناه إذا وصلك، أو اتبع تعليمات تسجيل الدخول في الرسالة.", "pendingTitle": "تحقق من بريدك الإلكتروني", "pendingSentTo": "أرسلنا رمزًا من ٦ أرقام إلى {email}. أدخله أدناه للتحقق من بريدك الإلكتروني.", "pendingGeneric": "أدخل رمز التحقق الذي أرسلناه إلى بريدك الإلكتروني.", diff --git a/apps/dashboard/src/i18n/locales/ar/billing.json b/apps/dashboard/src/i18n/locales/ar/billing.json index 15ef629d7..876f12977 100644 --- a/apps/dashboard/src/i18n/locales/ar/billing.json +++ b/apps/dashboard/src/i18n/locales/ar/billing.json @@ -546,7 +546,6 @@ "diskGrowth": "يمكن زيادة مساحة القرص الحالي. تقليلها يتطلب نقل بياناتك إلى خادم جديد.", "range": "من {min} إلى {max} {unit}", "monthlyTotal": "الإجمالي الشهري", - "yearlyTotal": "الإجمالي السنوي", "choose": "اختيار الخطة المخصصة", "updating": "جارٍ تحديث السعر", "invalid": "أدخل قيمة صحيحة ضمن النطاق المتاح لكل مورد.", @@ -558,7 +557,6 @@ "extraMemory": "ذاكرة إضافية", "extraDisk": "تخزين إضافي", "rates": "الإضافات الشهرية: {cpu} لكل vCPU، و{memory} لكل GB ذاكرة، و{disk} لكل GB تخزين. تُحسب فقط الموارد الزائدة عن الباقة المحددة.", - "yearlyRates": "الإضافات السنوية: {cpu}/وحدة معالجة افتراضية، {memory}/جيجابايت ذاكرة، {disk}/جيجابايت تخزين. تُحتسب فقط للموارد التي تتجاوز الباقة المحددة.", "applyNotice": "تُطبّق الترقيات بعد الدفع. تبدأ التغييرات الأقل تكلفة عند التجديد.", "resizeTitle": "تطبيق موارد اشتراكك", "resizeDescription": "تغيّرت خطتك. راجع السعة الجديدة والمشاريع المتأثرة قبل إعادة تشغيل هذا الخادم.", diff --git a/apps/dashboard/src/i18n/locales/ar/deployments.json b/apps/dashboard/src/i18n/locales/ar/deployments.json index 98aa49310..a6067abae 100644 --- a/apps/dashboard/src/i18n/locales/ar/deployments.json +++ b/apps/dashboard/src/i18n/locales/ar/deployments.json @@ -202,13 +202,6 @@ "pageOf": "الصفحة {page} من {total}", "range": "عمليات النشر {from}–{to} من {total}" }, - "containerConflict": { - "title": "حل تعارض الحاويات المكررة", - "description": "افحص الحاويات ووحدات التخزين المتصلة بها على الخادم المستهدف. احتفظ بالحاوية المطلوبة وبياناتها، واحذف فقط نسخة مكررة تأكدت أنها غير مستخدمة، ثم أعد النشر. إذا لم تكن متأكدًا من الحاوية التي يجب الاحتفاظ بها، فتواصل مع الدعم وأرفق مرجع النشر هذا.", - "containers": "الحاويات المتطابقة", - "reviewServer": "مراجعة الخادم", - "reference": "مرجع النشر" - }, "resourceGuidance": { "label": "إرشادات موارد النشر", "reviewCapacity": "مراجعة السعة", diff --git a/apps/dashboard/src/i18n/locales/ar/projectSettings.json b/apps/dashboard/src/i18n/locales/ar/projectSettings.json index 8ccbdf611..21e36d9ea 100644 --- a/apps/dashboard/src/i18n/locales/ar/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/ar/projectSettings.json @@ -1437,10 +1437,5 @@ "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 7e6d02ff5..360545e81 100644 --- a/apps/dashboard/src/i18n/locales/ar/settings.json +++ b/apps/dashboard/src/i18n/locales/ar/settings.json @@ -1791,21 +1791,5 @@ "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/auth.json b/apps/dashboard/src/i18n/locales/de/auth.json index 10a58a691..c09e5fb7b 100644 --- a/apps/dashboard/src/i18n/locales/de/auth.json +++ b/apps/dashboard/src/i18n/locales/de/auth.json @@ -70,8 +70,6 @@ "errorDescription": "Der Code ist möglicherweise falsch oder abgelaufen.", "resendEmail": "Code erneut senden", "signIn": "Anmelden", - "signupTitle": "Prüfe deine E-Mails", - "signupSentTo": "Wir haben den nächsten Schritt an {email} gesendet. Gib unten den erhaltenen Code ein oder folge den Anweisungen zur Anmeldung in der E-Mail.", "pendingTitle": "Verifizieren Sie Ihre E-Mail-Adresse", "pendingSentTo": "Wir haben einen 6-stelligen Code an {email} gesendet. Geben Sie ihn unten ein, um Ihre E-Mail-Adresse zu verifizieren.", "pendingGeneric": "Geben Sie den Verifizierungscode aus unserer E-Mail ein.", diff --git a/apps/dashboard/src/i18n/locales/de/billing.json b/apps/dashboard/src/i18n/locales/de/billing.json index 868d7ea4c..5382976e0 100644 --- a/apps/dashboard/src/i18n/locales/de/billing.json +++ b/apps/dashboard/src/i18n/locales/de/billing.json @@ -668,7 +668,6 @@ "diskGrowth": "Bestehende Datenträger können vergrößert werden. Zum Verkleinern müssen die Daten auf einen neuen Server verschoben werden.", "range": "{min} bis {max} {unit}", "monthlyTotal": "Monatlicher Gesamtpreis", - "yearlyTotal": "Jährlicher Gesamtpreis", "choose": "Individuell wählen", "updating": "Preis wird aktualisiert", "invalid": "Gib für jede Ressource einen gültigen Wert im angegebenen Bereich ein.", @@ -680,7 +679,6 @@ "extraMemory": "Zusätzlicher Arbeitsspeicher", "extraDisk": "Zusätzlicher Speicherplatz", "rates": "Monatliche Zusatzressourcen: {cpu}/vCPU, {memory}/GB RAM, {disk}/GB Speicherplatz. Berechnet wird nur, was über das gewählte Paket hinausgeht.", - "yearlyRates": "Jährliche Extras: {cpu}/vCPU, {memory}/GB RAM, {disk}/GB Speicher. Nur Ressourcen über das gewählte Paket hinaus werden berechnet.", "applyNotice": "Upgrades gelten nach der Zahlung. Günstigere Änderungen beginnen bei der Verlängerung.", "resizeTitle": "Gebuchte Ressourcen übernehmen", "resizeDescription": "Dein Tarif hat sich geändert. Prüfe die neue Kapazität und die betroffenen Projekte, bevor du diesen Server neu startest.", diff --git a/apps/dashboard/src/i18n/locales/de/deployments.json b/apps/dashboard/src/i18n/locales/de/deployments.json index 5f868daed..2d40185de 100644 --- a/apps/dashboard/src/i18n/locales/de/deployments.json +++ b/apps/dashboard/src/i18n/locales/de/deployments.json @@ -202,13 +202,6 @@ "pageOf": "Seite {page} von {total}", "range": "Bereitstellungen {from}–{to} von {total}" }, - "containerConflict": { - "title": "Doppelte Container prüfen", - "description": "Prüfe die Container und ihre eingebundenen Datenträger auf dem Zielserver. Behalte den vorgesehenen Container und seine Daten. Entferne nur ein nachweislich ungenutztes Duplikat und stelle dann erneut bereit. Bei Unsicherheit kontaktiere den Support mit dieser Bereitstellungsreferenz.", - "containers": "Übereinstimmende Container", - "reviewServer": "Server prüfen", - "reference": "Bereitstellungsreferenz" - }, "resourceGuidance": { "label": "Ressourcenhinweise zur Bereitstellung", "reviewCapacity": "Kapazität prüfen", diff --git a/apps/dashboard/src/i18n/locales/de/projectSettings.json b/apps/dashboard/src/i18n/locales/de/projectSettings.json index 427e82fc1..b21c553ec 100644 --- a/apps/dashboard/src/i18n/locales/de/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/de/projectSettings.json @@ -1437,10 +1437,5 @@ "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 296a00e59..2a500160e 100644 --- a/apps/dashboard/src/i18n/locales/de/settings.json +++ b/apps/dashboard/src/i18n/locales/de/settings.json @@ -1791,21 +1791,5 @@ "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/auth.json b/apps/dashboard/src/i18n/locales/en/auth.json index 99cd7ac94..986626bc2 100644 --- a/apps/dashboard/src/i18n/locales/en/auth.json +++ b/apps/dashboard/src/i18n/locales/en/auth.json @@ -70,8 +70,6 @@ "errorDescription": "The code may be incorrect or expired.", "resendEmail": "Resend code", "signIn": "Sign in", - "signupTitle": "Check your email", - "signupSentTo": "We've emailed the next step to {email}. Enter a code below if you received one, or follow the sign-in instructions in the email.", "pendingTitle": "Verify your email", "pendingSentTo": "We emailed a 6-digit code to {email}. Enter it below to verify your email.", "pendingGeneric": "Enter the verification code we emailed you.", diff --git a/apps/dashboard/src/i18n/locales/en/billing.json b/apps/dashboard/src/i18n/locales/en/billing.json index e1eb92f67..f243b3335 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": "Complete your payment in secure checkout. If it did not open, use the button below.", + "checkoutOpened": "Checkout is ready in a separate tab. If it did not open, use the link 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.", @@ -546,7 +546,6 @@ "diskGrowth": "Storage can grow. Reducing it requires moving your data to a new destination.", "range": "{min}–{max} {unit}", "monthlyTotal": "Monthly total", - "yearlyTotal": "Yearly total", "choose": "Choose Custom", "updating": "Updating price", "invalid": "Enter a valid amount within each resource range.", @@ -558,7 +557,6 @@ "extraMemory": "Additional memory", "extraDisk": "Additional storage", "rates": "Monthly extras: {cpu}/vCPU, {memory}/GB RAM, {disk}/GB storage. Charged only above the selected bundle.", - "yearlyRates": "Yearly extras: {cpu}/vCPU, {memory}/GB RAM, {disk}/GB storage. Charged only above the selected bundle.", "applyNotice": "Upgrades apply after payment. Lower-cost changes start at renewal.", "resizeTitle": "Apply your subscribed resources", "resizeDescription": "Your plan has changed. Review the new capacity and affected projects before applying.", diff --git a/apps/dashboard/src/i18n/locales/en/deployments.json b/apps/dashboard/src/i18n/locales/en/deployments.json index 3478e9803..a4af5e414 100644 --- a/apps/dashboard/src/i18n/locales/en/deployments.json +++ b/apps/dashboard/src/i18n/locales/en/deployments.json @@ -202,13 +202,6 @@ "confirm": "Roll back", "cancel": "Cancel" }, - "containerConflict": { - "title": "Resolve duplicate containers", - "description": "Inspect the containers and their mounts on the target server. Keep the intended container and its data, remove only a confirmed unused duplicate, then redeploy. If you are unsure which to keep, contact support with this deployment reference.", - "containers": "Matching containers", - "reviewServer": "Review server", - "reference": "Deployment reference" - }, "resourceGuidance": { "label": "Deployment resource guidance", "reviewCapacity": "Review capacity", diff --git a/apps/dashboard/src/i18n/locales/en/projectSettings.json b/apps/dashboard/src/i18n/locales/en/projectSettings.json index 283ddea15..09e2bf804 100644 --- a/apps/dashboard/src/i18n/locales/en/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/en/projectSettings.json @@ -1437,10 +1437,5 @@ "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 ff151942c..77286e291 100644 --- a/apps/dashboard/src/i18n/locales/en/settings.json +++ b/apps/dashboard/src/i18n/locales/en/settings.json @@ -1791,21 +1791,5 @@ "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/auth.json b/apps/dashboard/src/i18n/locales/es/auth.json index 664897987..fbdb9cc79 100644 --- a/apps/dashboard/src/i18n/locales/es/auth.json +++ b/apps/dashboard/src/i18n/locales/es/auth.json @@ -70,8 +70,6 @@ "errorDescription": "Puede que el código sea incorrecto o haya caducado.", "resendEmail": "Reenviar código", "signIn": "Iniciar sesión", - "signupTitle": "Revisa tu correo", - "signupSentTo": "Hemos enviado el siguiente paso a {email}. Introduce el código abajo si has recibido uno, o sigue las instrucciones para iniciar sesión del correo.", "pendingTitle": "Verifica tu correo electrónico", "pendingSentTo": "Enviamos un código de 6 dígitos a {email}. Introdúcelo a continuación para verificar tu correo electrónico.", "pendingGeneric": "Introduce el código de verificación que te enviamos por correo electrónico.", diff --git a/apps/dashboard/src/i18n/locales/es/billing.json b/apps/dashboard/src/i18n/locales/es/billing.json index 7ad95265b..e7630cd40 100644 --- a/apps/dashboard/src/i18n/locales/es/billing.json +++ b/apps/dashboard/src/i18n/locales/es/billing.json @@ -668,7 +668,6 @@ "diskGrowth": "Los discos existentes pueden ampliarse. Para reducir el almacenamiento debes mover los datos a un servidor nuevo.", "range": "De {min} a {max} {unit}", "monthlyTotal": "Total mensual", - "yearlyTotal": "Total anual", "choose": "Elegir Personalizado", "updating": "Actualizando precio", "invalid": "Introduce una cantidad válida dentro del rango de cada recurso.", @@ -680,7 +679,6 @@ "extraMemory": "Memoria adicional", "extraDisk": "Almacenamiento adicional", "rates": "Extras mensuales: {cpu}/vCPU, {memory}/GB de RAM, {disk}/GB de almacenamiento. Solo se cobra lo que supere el paquete elegido.", - "yearlyRates": "Extras anuales: {cpu}/vCPU, {memory}/GB de RAM, {disk}/GB de almacenamiento. Solo se cobran los recursos que superen el paquete seleccionado.", "applyNotice": "Las ampliaciones se aplican tras el pago. Los cambios a menor precio comienzan al renovar.", "resizeTitle": "Aplicar los recursos de tu suscripción", "resizeDescription": "Tu plan ha cambiado. Revisa la nueva capacidad y los proyectos afectados antes de reiniciar este servidor.", diff --git a/apps/dashboard/src/i18n/locales/es/deployments.json b/apps/dashboard/src/i18n/locales/es/deployments.json index 894727750..2d367f0c3 100644 --- a/apps/dashboard/src/i18n/locales/es/deployments.json +++ b/apps/dashboard/src/i18n/locales/es/deployments.json @@ -202,13 +202,6 @@ "pageOf": "Página {page} de {total}", "range": "Despliegues {from}–{to} de {total}" }, - "containerConflict": { - "title": "Resolver contenedores duplicados", - "description": "Revisa los contenedores y sus volúmenes montados en el servidor de destino. Conserva el contenedor correcto y sus datos, elimina solo un duplicado que hayas confirmado que no se usa y vuelve a desplegar. Si tienes dudas sobre cuál conservar, contacta con soporte con esta referencia de despliegue.", - "containers": "Contenedores coincidentes", - "reviewServer": "Revisar servidor", - "reference": "Referencia del despliegue" - }, "resourceGuidance": { "label": "Orientación sobre recursos del despliegue", "reviewCapacity": "Revisar capacidad", diff --git a/apps/dashboard/src/i18n/locales/es/projectSettings.json b/apps/dashboard/src/i18n/locales/es/projectSettings.json index fd96834e2..e7e7bfe01 100644 --- a/apps/dashboard/src/i18n/locales/es/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/es/projectSettings.json @@ -1437,10 +1437,5 @@ "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 0d2c5871c..3ab15e30e 100644 --- a/apps/dashboard/src/i18n/locales/es/settings.json +++ b/apps/dashboard/src/i18n/locales/es/settings.json @@ -1791,21 +1791,5 @@ "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/auth.json b/apps/dashboard/src/i18n/locales/fr/auth.json index 79ef148e7..d7c1c0c8c 100644 --- a/apps/dashboard/src/i18n/locales/fr/auth.json +++ b/apps/dashboard/src/i18n/locales/fr/auth.json @@ -70,8 +70,6 @@ "errorDescription": "Le code est peut-être incorrect ou a expiré.", "resendEmail": "Renvoyer le code", "signIn": "Se connecter", - "signupTitle": "Consultez votre messagerie", - "signupSentTo": "Nous avons envoyé la prochaine étape à {email}. Saisissez le code ci-dessous si vous en avez reçu un, ou suivez les instructions de connexion dans le message.", "pendingTitle": "Vérifiez votre e-mail", "pendingSentTo": "Nous avons envoyé un code à 6 chiffres à {email}. Saisissez-le ci-dessous pour vérifier votre e-mail.", "pendingGeneric": "Saisissez le code de vérification que nous vous avons envoyé par e-mail.", diff --git a/apps/dashboard/src/i18n/locales/fr/billing.json b/apps/dashboard/src/i18n/locales/fr/billing.json index 3f805f9d5..1182f4d4e 100644 --- a/apps/dashboard/src/i18n/locales/fr/billing.json +++ b/apps/dashboard/src/i18n/locales/fr/billing.json @@ -668,7 +668,6 @@ "diskGrowth": "Les disques existants peuvent être agrandis. Réduire le stockage nécessite de déplacer vos données vers un nouveau serveur.", "range": "De {min} à {max} {unit}", "monthlyTotal": "Total mensuel", - "yearlyTotal": "Total annuel", "choose": "Choisir Sur mesure", "updating": "Actualisation du prix", "invalid": "Saisissez une valeur valide dans la plage de chaque ressource.", @@ -680,7 +679,6 @@ "extraMemory": "Mémoire supplémentaire", "extraDisk": "Stockage supplémentaire", "rates": "Suppléments mensuels : {cpu}/vCPU, {memory}/Go de RAM, {disk}/Go de stockage. Facturés uniquement au-delà de l’offre choisie.", - "yearlyRates": "Suppléments annuels : {cpu}/vCPU, {memory}/Go de RAM, {disk}/Go de stockage. Seules les ressources dépassant le forfait choisi sont facturées.", "applyNotice": "Les augmentations prennent effet après paiement. Les changements moins chers commencent au renouvellement.", "resizeTitle": "Appliquer les ressources de votre abonnement", "resizeDescription": "Votre offre a changé. Vérifiez la nouvelle capacité et les projets concernés avant de redémarrer ce serveur.", diff --git a/apps/dashboard/src/i18n/locales/fr/deployments.json b/apps/dashboard/src/i18n/locales/fr/deployments.json index ecdbfb85b..8a44f466a 100644 --- a/apps/dashboard/src/i18n/locales/fr/deployments.json +++ b/apps/dashboard/src/i18n/locales/fr/deployments.json @@ -202,13 +202,6 @@ "pageOf": "Page {page} sur {total}", "range": "Déploiements {from}–{to} sur {total}" }, - "containerConflict": { - "title": "Résoudre les conteneurs en double", - "description": "Inspectez les conteneurs et leurs volumes montés sur le serveur cible. Conservez le conteneur prévu et ses données, supprimez uniquement un doublon dont vous avez confirmé qu’il est inutilisé, puis redéployez. En cas de doute, contactez le support avec cette référence de déploiement.", - "containers": "Conteneurs correspondants", - "reviewServer": "Examiner le serveur", - "reference": "Référence du déploiement" - }, "resourceGuidance": { "label": "Conseils sur les ressources du déploiement", "reviewCapacity": "Examiner la capacité", diff --git a/apps/dashboard/src/i18n/locales/fr/projectSettings.json b/apps/dashboard/src/i18n/locales/fr/projectSettings.json index af9bb4454..df9987abb 100644 --- a/apps/dashboard/src/i18n/locales/fr/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/fr/projectSettings.json @@ -1437,10 +1437,5 @@ "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 5614429ab..4a43b3d39 100644 --- a/apps/dashboard/src/i18n/locales/fr/settings.json +++ b/apps/dashboard/src/i18n/locales/fr/settings.json @@ -1791,21 +1791,5 @@ "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/auth.json b/apps/dashboard/src/i18n/locales/ja/auth.json index 923dda1b1..adee5359f 100644 --- a/apps/dashboard/src/i18n/locales/ja/auth.json +++ b/apps/dashboard/src/i18n/locales/ja/auth.json @@ -70,8 +70,6 @@ "errorDescription": "コードが正しくないか、有効期限が切れている可能性があります。", "resendEmail": "コードを再送信", "signIn": "サインイン", - "signupTitle": "メールを確認してください", - "signupSentTo": "次の手順を {email} に送信しました。コードを受け取った場合は下に入力し、それ以外の場合はメールのログイン手順に従ってください。", "pendingTitle": "メールアドレスを確認", "pendingSentTo": "{email} に6桁のコードを送信しました。メールアドレスを確認するには、以下に入力してください。", "pendingGeneric": "メールでお送りした確認コードを入力してください。", diff --git a/apps/dashboard/src/i18n/locales/ja/billing.json b/apps/dashboard/src/i18n/locales/ja/billing.json index 29077300c..831e72314 100644 --- a/apps/dashboard/src/i18n/locales/ja/billing.json +++ b/apps/dashboard/src/i18n/locales/ja/billing.json @@ -668,7 +668,6 @@ "diskGrowth": "既存のディスクは拡張できます。縮小するには、データを新しいサーバーに移す必要があります。", "range": "{min}~{max} {unit}", "monthlyTotal": "月額合計", - "yearlyTotal": "年間合計", "choose": "カスタムを選択", "updating": "価格を更新中", "invalid": "各リソースの範囲内で有効な値を入力してください。", @@ -680,7 +679,6 @@ "extraMemory": "追加メモリ", "extraDisk": "追加ストレージ", "rates": "追加リソースの月額料金:{cpu}/vCPU、{memory}/GB RAM、{disk}/GB ストレージ。選択したパッケージを超える分のみ課金されます。", - "yearlyRates": "年間追加料金:{cpu}/vCPU、{memory}/GB RAM、{disk}/GBストレージ。選択したプランを超えるリソースにのみ課金されます。", "applyNotice": "アップグレードは支払い後に適用されます。料金が下がる変更は更新時から有効です。", "resizeTitle": "契約したリソースを適用", "resizeDescription": "プランが変更されました。新しい容量と影響を受けるプロジェクトを確認してからサーバーを再起動してください。", diff --git a/apps/dashboard/src/i18n/locales/ja/deployments.json b/apps/dashboard/src/i18n/locales/ja/deployments.json index d6dfe0db0..b60d86f1b 100644 --- a/apps/dashboard/src/i18n/locales/ja/deployments.json +++ b/apps/dashboard/src/i18n/locales/ja/deployments.json @@ -202,13 +202,6 @@ "pageOf": "{page} / {total} ページ", "range": "全 {total} 件中 {from}–{to} 件" }, - "containerConflict": { - "title": "重複するコンテナを確認", - "description": "対象サーバーでコンテナとマウントを確認してください。使用するコンテナとそのデータを保持し、未使用と確認できた重複コンテナのみを削除してから再デプロイしてください。判断できない場合は、このデプロイ参照番号を添えてサポートにお問い合わせください。", - "containers": "一致するコンテナ", - "reviewServer": "サーバーを確認", - "reference": "デプロイ参照番号" - }, "resourceGuidance": { "label": "デプロイのリソースガイド", "reviewCapacity": "容量を確認", diff --git a/apps/dashboard/src/i18n/locales/ja/projectSettings.json b/apps/dashboard/src/i18n/locales/ja/projectSettings.json index 17f63ef7a..1829beee8 100644 --- a/apps/dashboard/src/i18n/locales/ja/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/ja/projectSettings.json @@ -1437,10 +1437,5 @@ "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 db135bb68..9394731c4 100644 --- a/apps/dashboard/src/i18n/locales/ja/settings.json +++ b/apps/dashboard/src/i18n/locales/ja/settings.json @@ -1791,21 +1791,5 @@ "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/auth.json b/apps/dashboard/src/i18n/locales/pt/auth.json index ec7e52fe1..733f24529 100644 --- a/apps/dashboard/src/i18n/locales/pt/auth.json +++ b/apps/dashboard/src/i18n/locales/pt/auth.json @@ -70,8 +70,6 @@ "errorDescription": "O código pode estar incorreto ou expirado.", "resendEmail": "Reenviar código", "signIn": "Entrar", - "signupTitle": "Verifique seu e-mail", - "signupSentTo": "Enviamos o próximo passo para {email}. Insira o código abaixo se recebeu um, ou siga as instruções de acesso no e-mail.", "pendingTitle": "Verifique seu email", "pendingSentTo": "Enviamos um código de 6 dígitos para {email}. Digite-o abaixo para verificar seu email.", "pendingGeneric": "Digite o código de verificação que enviamos por email.", diff --git a/apps/dashboard/src/i18n/locales/pt/billing.json b/apps/dashboard/src/i18n/locales/pt/billing.json index bd995162d..58430128f 100644 --- a/apps/dashboard/src/i18n/locales/pt/billing.json +++ b/apps/dashboard/src/i18n/locales/pt/billing.json @@ -668,7 +668,6 @@ "diskGrowth": "Os discos existentes podem ser ampliados. Para reduzir o armazenamento, é necessário mover os dados para um novo servidor.", "range": "De {min} a {max} {unit}", "monthlyTotal": "Total mensal", - "yearlyTotal": "Total anual", "choose": "Escolher Personalizado", "updating": "Atualizando preço", "invalid": "Insira um valor válido dentro do intervalo de cada recurso.", @@ -680,7 +679,6 @@ "extraMemory": "Memória adicional", "extraDisk": "Armazenamento adicional", "rates": "Extras mensais: {cpu}/vCPU, {memory}/GB de RAM, {disk}/GB de armazenamento. Cobrança somente acima do pacote escolhido.", - "yearlyRates": "Extras anuais: {cpu}/vCPU, {memory}/GB de RAM, {disk}/GB de armazenamento. Cobrados apenas pelos recursos que excedem o pacote selecionado.", "applyNotice": "As ampliações são aplicadas após o pagamento. Alterações de menor custo começam na renovação.", "resizeTitle": "Aplicar os recursos da assinatura", "resizeDescription": "Seu plano mudou. Revise a nova capacidade e os projetos afetados antes de reiniciar este servidor.", diff --git a/apps/dashboard/src/i18n/locales/pt/deployments.json b/apps/dashboard/src/i18n/locales/pt/deployments.json index 9f9fc3858..5b6e0dd7c 100644 --- a/apps/dashboard/src/i18n/locales/pt/deployments.json +++ b/apps/dashboard/src/i18n/locales/pt/deployments.json @@ -202,13 +202,6 @@ "pageOf": "Página {page} de {total}", "range": "Implantações {from}–{to} de {total}" }, - "containerConflict": { - "title": "Resolver contêineres duplicados", - "description": "Inspecione os contêineres e seus volumes montados no servidor de destino. Mantenha o contêiner correto e seus dados, remova apenas uma duplicata confirmada como não utilizada e implante novamente. Em caso de dúvida sobre qual manter, contate o suporte com esta referência da implantação.", - "containers": "Contêineres correspondentes", - "reviewServer": "Revisar servidor", - "reference": "Referência da implantação" - }, "resourceGuidance": { "label": "Orientações sobre recursos da implantação", "reviewCapacity": "Revisar capacidade", diff --git a/apps/dashboard/src/i18n/locales/pt/projectSettings.json b/apps/dashboard/src/i18n/locales/pt/projectSettings.json index a3ca74b0a..b27f511cf 100644 --- a/apps/dashboard/src/i18n/locales/pt/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/pt/projectSettings.json @@ -1437,10 +1437,5 @@ "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 883f9ab06..3fa1a6087 100644 --- a/apps/dashboard/src/i18n/locales/pt/settings.json +++ b/apps/dashboard/src/i18n/locales/pt/settings.json @@ -1791,21 +1791,5 @@ "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/auth.json b/apps/dashboard/src/i18n/locales/ru/auth.json index ebc8bd0b0..d823d4c10 100644 --- a/apps/dashboard/src/i18n/locales/ru/auth.json +++ b/apps/dashboard/src/i18n/locales/ru/auth.json @@ -70,8 +70,6 @@ "errorDescription": "Код неверен или срок его действия истёк.", "resendEmail": "Отправить код повторно", "signIn": "Войти", - "signupTitle": "Проверьте почту", - "signupSentTo": "Мы отправили дальнейшие инструкции на {email}. Если вы получили код, введите его ниже. В противном случае следуйте инструкциям для входа в письме.", "pendingTitle": "Подтвердите вашу эл. почту", "pendingSentTo": "Мы отправили 6-значный код на {email}. Введите его ниже для подтверждения эл. почты.", "pendingGeneric": "Введите код подтверждения, отправленный вам по эл. почте.", diff --git a/apps/dashboard/src/i18n/locales/ru/billing.json b/apps/dashboard/src/i18n/locales/ru/billing.json index 45ffb8ac8..3114d95de 100644 --- a/apps/dashboard/src/i18n/locales/ru/billing.json +++ b/apps/dashboard/src/i18n/locales/ru/billing.json @@ -546,7 +546,6 @@ "diskGrowth": "Диски можно расширять. Уменьшение дискового пространства требует переноса данных на новый сервер.", "range": "От {min} до {max} {unit}", "monthlyTotal": "Итого в месяц", - "yearlyTotal": "Итого за год", "choose": "Выбрать индивидуальный", "updating": "Обновление цены", "invalid": "Укажите допустимое значение в пределах диапазона для каждого ресурса.", @@ -558,7 +557,6 @@ "extraMemory": "Дополнительная память", "extraDisk": "Дополнительное хранилище", "rates": "Дополнительно в месяц: {cpu}/vCPU, {memory}/ГБ ОЗУ, {disk}/ГБ хранилища. Оплачивается только сверх выбранного пакета.", - "yearlyRates": "Дополнительные ресурсы за год: {cpu}/vCPU, {memory}/ГБ ОЗУ, {disk}/ГБ хранилища. Оплачиваются только ресурсы сверх выбранного пакета.", "applyNotice": "Повышение тарифа применяется сразу после оплаты. Переход на более дешёвый — со следующего продления.", "resizeTitle": "Применить ресурсы из подписки", "resizeDescription": "Ваш тариф изменился. Проверьте новые мощности и затронутые проекты перед перезапуском сервера.", diff --git a/apps/dashboard/src/i18n/locales/ru/deployments.json b/apps/dashboard/src/i18n/locales/ru/deployments.json index fd49ec67d..de87897c9 100644 --- a/apps/dashboard/src/i18n/locales/ru/deployments.json +++ b/apps/dashboard/src/i18n/locales/ru/deployments.json @@ -202,13 +202,6 @@ "confirm": "Откатить", "cancel": "Отмена" }, - "containerConflict": { - "title": "Устраните дублирование контейнеров", - "description": "Проверьте контейнеры и их подключённые тома на целевом сервере. Сохраните нужный контейнер и его данные, удалите только подтверждённый неиспользуемый дубликат, затем повторите развёртывание. Если вы не уверены, какой контейнер сохранить, обратитесь в поддержку с этим идентификатором развёртывания.", - "containers": "Совпадающие контейнеры", - "reviewServer": "Проверить сервер", - "reference": "Идентификатор развёртывания" - }, "resourceGuidance": { "label": "Рекомендации по ресурсам развёртывания", "reviewCapacity": "Проверить ресурсы", diff --git a/apps/dashboard/src/i18n/locales/ru/projectSettings.json b/apps/dashboard/src/i18n/locales/ru/projectSettings.json index 444152582..80843ddf0 100644 --- a/apps/dashboard/src/i18n/locales/ru/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/ru/projectSettings.json @@ -1437,10 +1437,5 @@ "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 1ee579392..59cb29a08 100644 --- a/apps/dashboard/src/i18n/locales/ru/settings.json +++ b/apps/dashboard/src/i18n/locales/ru/settings.json @@ -1791,21 +1791,5 @@ "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/auth.json b/apps/dashboard/src/i18n/locales/tr/auth.json index 299fd24a7..d99c7b079 100644 --- a/apps/dashboard/src/i18n/locales/tr/auth.json +++ b/apps/dashboard/src/i18n/locales/tr/auth.json @@ -70,8 +70,6 @@ "errorDescription": "Kod hatalı veya süresi dolmuş olabilir.", "resendEmail": "Kodu tekrar gönder", "signIn": "Giriş yap", - "signupTitle": "E-postanızı kontrol edin", - "signupSentTo": "Sonraki adımı {email} adresine gönderdik. Bir kod aldıysanız aşağıya girin veya e-postadaki giriş talimatlarını izleyin.", "pendingTitle": "E-postanızı doğrulayın", "pendingSentTo": "{email} adresine 6 haneli bir kod gönderdik. E-postanızı doğrulamak için aşağıya girin.", "pendingGeneric": "Size e-posta ile gönderdiğimiz doğrulama kodunu girin.", diff --git a/apps/dashboard/src/i18n/locales/tr/billing.json b/apps/dashboard/src/i18n/locales/tr/billing.json index 5b4f6a8fe..bd2710220 100644 --- a/apps/dashboard/src/i18n/locales/tr/billing.json +++ b/apps/dashboard/src/i18n/locales/tr/billing.json @@ -668,7 +668,6 @@ "diskGrowth": "Mevcut diskler büyütülebilir. Depolamayı küçültmek için verilerini yeni bir sunucuya taşıman gerekir.", "range": "{min} ile {max} {unit}", "monthlyTotal": "Aylık toplam", - "yearlyTotal": "Yıllık toplam", "choose": "Özel planı seç", "updating": "Fiyat güncelleniyor", "invalid": "Her kaynak için belirtilen aralıkta geçerli bir miktar gir.", @@ -680,7 +679,6 @@ "extraMemory": "Ek bellek", "extraDisk": "Ek depolama", "rates": "Aylık ek kaynaklar: {cpu}/vCPU, {memory}/GB RAM, {disk}/GB depolama. Yalnızca seçilen paketin üzerindeki kaynaklar ücretlendirilir.", - "yearlyRates": "Yıllık ek kaynaklar: {cpu}/vCPU, {memory}/GB RAM, {disk}/GB depolama. Yalnızca seçilen paketi aşan kaynaklar ücretlendirilir.", "applyNotice": "Yükseltmeler ödemeden sonra uygulanır. Daha düşük ücretli değişiklikler yenilemede başlar.", "resizeTitle": "Aboneliğindeki kaynakları uygula", "resizeDescription": "Planın değişti. Bu sunucuyu yeniden başlatmadan önce yeni kapasiteyi ve etkilenen projeleri incele.", diff --git a/apps/dashboard/src/i18n/locales/tr/deployments.json b/apps/dashboard/src/i18n/locales/tr/deployments.json index 484a9dce8..a079add8b 100644 --- a/apps/dashboard/src/i18n/locales/tr/deployments.json +++ b/apps/dashboard/src/i18n/locales/tr/deployments.json @@ -202,13 +202,6 @@ "pageOf": "Sayfa {page} / {total}", "range": "{total} dağıtımdan {from}–{to}" }, - "containerConflict": { - "title": "Yinelenen kapsayıcıları çözün", - "description": "Hedef sunucudaki kapsayıcıları ve bağlı birimlerini inceleyin. Kullanılacak kapsayıcıyı ve verilerini koruyun, yalnızca kullanılmadığını doğruladığınız kopyayı kaldırın ve yeniden dağıtın. Hangisini koruyacağınızdan emin değilseniz bu dağıtım referansıyla destek ekibine ulaşın.", - "containers": "Eşleşen kapsayıcılar", - "reviewServer": "Sunucuyu incele", - "reference": "Dağıtım referansı" - }, "resourceGuidance": { "label": "Dağıtım kaynak rehberi", "reviewCapacity": "Kapasiteyi incele", diff --git a/apps/dashboard/src/i18n/locales/tr/projectSettings.json b/apps/dashboard/src/i18n/locales/tr/projectSettings.json index 9f55585ea..b81cee71b 100644 --- a/apps/dashboard/src/i18n/locales/tr/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/tr/projectSettings.json @@ -1437,10 +1437,5 @@ "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 563cf2944..343010e85 100644 --- a/apps/dashboard/src/i18n/locales/tr/settings.json +++ b/apps/dashboard/src/i18n/locales/tr/settings.json @@ -1791,21 +1791,5 @@ "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/auth.json b/apps/dashboard/src/i18n/locales/zh/auth.json index 3cb32f509..d5b6eaf90 100644 --- a/apps/dashboard/src/i18n/locales/zh/auth.json +++ b/apps/dashboard/src/i18n/locales/zh/auth.json @@ -70,8 +70,6 @@ "errorDescription": "该验证码可能不正确或已过期。", "resendEmail": "重新发送验证码", "signIn": "登录", - "signupTitle": "请查收邮件", - "signupSentTo": "我们已将后续步骤发送至 {email}。如果您收到了验证码,请在下方输入;否则,请按照邮件中的登录说明操作。", "pendingTitle": "验证你的邮箱", "pendingSentTo": "我们已将 6 位验证码发送至 {email}。请在下方输入验证码以验证你的邮箱。", "pendingGeneric": "请输入我们通过邮件发送的验证码。", diff --git a/apps/dashboard/src/i18n/locales/zh/billing.json b/apps/dashboard/src/i18n/locales/zh/billing.json index 10554d76d..62220c737 100644 --- a/apps/dashboard/src/i18n/locales/zh/billing.json +++ b/apps/dashboard/src/i18n/locales/zh/billing.json @@ -668,7 +668,6 @@ "diskGrowth": "现有磁盘可以扩容。缩减存储需要将数据迁移到新服务器。", "range": "{min} 至 {max} {unit}", "monthlyTotal": "每月总计", - "yearlyTotal": "年度总额", "choose": "选择自定义", "updating": "正在更新价格", "invalid": "请为每项资源输入有效范围内的数值。", @@ -680,7 +679,6 @@ "extraMemory": "额外内存", "extraDisk": "额外存储", "rates": "额外资源月费:{cpu}/vCPU、{memory}/GB 内存、{disk}/GB 存储。仅对超出所选套餐的部分收费。", - "yearlyRates": "年度额外资源费用:{cpu}/vCPU、{memory}/GB 内存、{disk}/GB 存储。仅对超出所选套餐的资源收费。", "applyNotice": "升级在付款后生效。费用更低的变更从续费时开始。", "resizeTitle": "应用已订阅的资源", "resizeDescription": "你的套餐已更改。重启此服务器之前,请查看新容量及受影响的项目。", diff --git a/apps/dashboard/src/i18n/locales/zh/deployments.json b/apps/dashboard/src/i18n/locales/zh/deployments.json index b0816d8ab..925a48d96 100644 --- a/apps/dashboard/src/i18n/locales/zh/deployments.json +++ b/apps/dashboard/src/i18n/locales/zh/deployments.json @@ -202,13 +202,6 @@ "pageOf": "第 {page} 页,共 {total} 页", "range": "第 {from}–{to} 条部署,共 {total} 条" }, - "containerConflict": { - "title": "处理重复容器", - "description": "检查目标服务器上的容器及其挂载。保留预期使用的容器和数据,仅删除已确认不再使用的重复容器,然后重新部署。如果无法确定应保留哪一个,请提供此部署编号并联系支持。", - "containers": "匹配的容器", - "reviewServer": "查看服务器", - "reference": "部署编号" - }, "resourceGuidance": { "label": "部署资源指引", "reviewCapacity": "检查容量", diff --git a/apps/dashboard/src/i18n/locales/zh/projectSettings.json b/apps/dashboard/src/i18n/locales/zh/projectSettings.json index ab52939d9..8d912db95 100644 --- a/apps/dashboard/src/i18n/locales/zh/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/zh/projectSettings.json @@ -1437,10 +1437,5 @@ "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 682c418c8..753bd8f2a 100644 --- a/apps/dashboard/src/i18n/locales/zh/settings.json +++ b/apps/dashboard/src/i18n/locales/zh/settings.json @@ -1791,21 +1791,5 @@ "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 58e3e6043..54c2c54a1 100644 --- a/apps/dashboard/src/lib/api/connections.ts +++ b/apps/dashboard/src/lib/api/connections.ts @@ -1,4 +1,3 @@ -import type { ProjectConnectionCandidate } from "@repo/contracts"; import { api } from "./client"; import { endpoints } from "./endpoints"; @@ -49,7 +48,15 @@ async function notifyConnections(request: Promise): Promise { export const connectionsApi = { candidates: (projectId: string) => - api.get<{ data: ProjectConnectionCandidate[] }>(`${endpoints.projects.connections(projectId)}/candidates`), + api.get<{ + data: Array<{ + id: string; + name: string; + description: string; + appTemplateId: string | null; + clusterId?: string | null; + }>; + }>(`${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 96897fa95..09e72d1c6 100644 --- a/apps/dashboard/src/lib/api/management.ts +++ b/apps/dashboard/src/lib/api/management.ts @@ -1,11 +1,8 @@ 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) => { - try { return (await api.post<{ data: Result }>(`/billing/manage/${path}`, body)).data; } - finally { invalidatePayments(); } -}; +const post = async (path: string, body?: unknown) => + (await api.post<{ data: Result }>(`/billing/manage/${path}`, body)).data; 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/api/projects.ts b/apps/dashboard/src/lib/api/projects.ts index 88f1bf4b1..2c941cff8 100644 --- a/apps/dashboard/src/lib/api/projects.ts +++ b/apps/dashboard/src/lib/api/projects.ts @@ -613,10 +613,7 @@ export const projectsApi = { }>(endpoints.projects.env(id)), /** Get git settings */ - getGit: (id: string | number) => - api.get>>( - endpoints.projects.git(id), - ), + getGit: (id: string | number) => api.get(endpoints.projects.git(id)), /** Link a GitHub repo to an existing project + register webhook */ linkRepo: ( diff --git a/apps/dashboard/src/lib/billing-events.ts b/apps/dashboard/src/lib/billing-events.ts deleted file mode 100644 index 6b75dfafb..000000000 --- a/apps/dashboard/src/lib/billing-events.ts +++ /dev/null @@ -1,6 +0,0 @@ -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 deleted file mode 100644 index d9dcf1cd1..000000000 --- a/apps/dashboard/src/lib/checkout-navigation.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -// @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 7c13e84bf..2d73fd312 100644 --- a/apps/dashboard/src/lib/checkout-navigation.ts +++ b/apps/dashboard/src/lib/checkout-navigation.ts @@ -1,18 +1,19 @@ -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; +/** 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; + }, + }; } diff --git a/apps/dashboard/src/proxy.test.ts b/apps/dashboard/src/proxy.test.ts index 59b96828a..6746ee9ea 100644 --- a/apps/dashboard/src/proxy.test.ts +++ b/apps/dashboard/src/proxy.test.ts @@ -1,17 +1,8 @@ import { describe, expect, it } from "vitest"; import { NextRequest } from "next/server"; -import { unstable_doesMiddlewareMatch } from "next/experimental/testing/server"; -import { config, proxy } from "./proxy"; +import { 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 66af7a4f9..0801bfe61 100644 --- a/apps/dashboard/src/proxy.ts +++ b/apps/dashboard/src/proxy.ts @@ -90,7 +90,5 @@ export function proxy(req: NextRequest) { } export const config = { - // 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|.*\\..*).*)"], + matcher: ["/((?!_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 3951622bd..09a290981 100644 --- a/apps/web/content/docs/cli/projects.mdx +++ b/apps/web/content/docs/cli/projects.mdx @@ -86,17 +86,11 @@ 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 99a5c4ee2..ec444896c 100644 --- a/apps/web/content/docs/cli/reference/domain/index.mdx +++ b/apps/web/content/docs/cli/reference/domain/index.mdx @@ -47,8 +47,6 @@ 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 cb456e05f..c616684dc 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 project icon (set in **Settings → Project Info**), or its app/framework logo, the **name** +Each row shows, left to right: the app's icon (its favicon, or the 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/apps/web/content/docs/mcp.mdx b/apps/web/content/docs/mcp.mdx index 171012209..d32d9550b 100644 --- a/apps/web/content/docs/mcp.mdx +++ b/apps/web/content/docs/mcp.mdx @@ -217,9 +217,9 @@ is built from that route's method and path. So `get_projects` is `GET /api/proje exact set your token can use. Not every route is a tool: a route becomes one only when it **opts in**, so the set is a curated slice of the -API rather than the whole surface. Each exposed tool also carries explicit `readOnlyHint`, -`destructiveHint`, and `openWorldHint` values. These tell a client whether the tool only reads, -may perform destructive changes, and may interact with systems outside Openship. +API rather than the whole surface. Each exposed tool also carries two hints a client can surface — +`readOnlyHint` (the tool only reads) and `destructiveHint` (it deletes or tears something down) — so an agent +UI can flag a destructive call before it runs. | Tool name (examples) | REST route | Reference | |---|---|---| diff --git a/apps/web/src/app/(site)/[locale]/(marketing)/pricing/CloudBilling.tsx b/apps/web/src/app/(site)/[locale]/(marketing)/pricing/CloudBilling.tsx index cb70d9858..991f52277 100644 --- a/apps/web/src/app/(site)/[locale]/(marketing)/pricing/CloudBilling.tsx +++ b/apps/web/src/app/(site)/[locale]/(marketing)/pricing/CloudBilling.tsx @@ -3,80 +3,46 @@ import { useCopy } from "@/i18n/use-copy"; import { useState, type ReactNode } from "react"; -type BillingView = { - plans: ReactNode; - headline: ReactNode; - note: ReactNode; -}; - export function CloudBilling({ monthly, annual, monthsFree, - children, }: { - monthly: BillingView; - annual?: BillingView; + monthly: ReactNode; + annual?: ReactNode; monthsFree: number; - children: ReactNode; }) { const copy = useCopy(); const [interval, setInterval] = useState<"monthly" | "annual">("monthly"); const annualSelected = Boolean(annual) && interval === "annual"; - const selected = annualSelected && annual ? annual : monthly; return ( <> -
-
-

- {copy("Cloud resources for your projects.")} -
- - {selected.headline} - -

- {selected.note &&

{selected.note}

} +
+
+

{copy("Cloud resource pools")}

+

{copy("CPU, RAM and storage shared across your projects and builds.")}

-
-
-
-
-
-

{copy("Cloud resource pools")}

-

{copy("CPU, RAM and storage shared across your projects and builds.")}

-
- {annual && ( -
+ {(["monthly", "annual"] as const).map((value) => ( + - ))} -
- )} + {value === "monthly" ? copy("Monthly") : copy("Yearly")} + {value === "annual" && monthsFree > 0 && ( + {copy("{months} months free", { months: monthsFree })} + )} + + ))}
- - {annual && } - {children} -
-
+ )} +
+ + {annual && } ); } diff --git a/apps/web/src/app/(site)/[locale]/(marketing)/pricing/_data.ts b/apps/web/src/app/(site)/[locale]/(marketing)/pricing/_data.ts index 96537396b..ef60ca052 100644 --- a/apps/web/src/app/(site)/[locale]/(marketing)/pricing/_data.ts +++ b/apps/web/src/app/(site)/[locale]/(marketing)/pricing/_data.ts @@ -22,7 +22,9 @@ export function faq(pricing: CloudPricing, copy: Copy): FaqItem[] { }) : copy("See your dashboard for current Cloud plans and availability."), pricing.annual.enabled - ? copy("Choose Yearly to see the full annual price, paid once a year.") + ? copy( + "Yearly billing is also available; the cards show the monthly equivalent and full yearly charge.", + ) : null, copy( "Each subscription includes one Cloud Space for your projects, with no per-seat fees. Share the included CPU, RAM and storage across your projects and builds.", diff --git a/apps/web/src/app/(site)/[locale]/(marketing)/pricing/page.tsx b/apps/web/src/app/(site)/[locale]/(marketing)/pricing/page.tsx index b792bca8c..b91eefcb9 100644 --- a/apps/web/src/app/(site)/[locale]/(marketing)/pricing/page.tsx +++ b/apps/web/src/app/(site)/[locale]/(marketing)/pricing/page.tsx @@ -11,7 +11,7 @@ import { IllustratedLink } from "@/components/marketing/illustrated-link"; import { CLOUD_SLA } from "@/lib/cloud-service"; import { UI, - startingCloudPlan, + cloudFrom, priceParts, getCloudPricing, cloudPlanSummary, @@ -61,7 +61,6 @@ function PlanCard({ cta, popular, support, - benefits = [], children, }: { name: string; @@ -73,7 +72,6 @@ function PlanCard({ cta: string; popular?: boolean; support: string; - benefits?: string[]; children: ReactNode; }) { const copy = useCopy(); @@ -99,14 +97,10 @@ function PlanCard({ {copy(cta)}