diff --git a/apps/cli/src/commands/domain.ts b/apps/cli/src/commands/domain.ts index 5661d5b14..9b6011a8c 100644 --- a/apps/cli/src/commands/domain.ts +++ b/apps/cli/src/commands/domain.ts @@ -9,7 +9,7 @@ import { exitCommand, rethrowCommandExit } from "../lib/command-exit"; import { Command, Option } from "commander"; import { UploadCertBody, parseInput } from "@repo/contracts"; import { readFileSync } from "node:fs"; -import { attachCustomDomainEndpoint } from "../lib/custom-domain-endpoint"; +import { prepareCustomDomainEndpoint } from "../lib/custom-domain-endpoint"; import { getShipClient } from "../lib/ship-client"; import { spin, fail, confirmOrExit, printResult } from "../lib/cmd-helpers"; import type { Domain, DomainRecords, DomainSsl } from "@repo/sdk/client"; @@ -71,14 +71,17 @@ const addCmd = new Command("add") .argument("", "Domain hostname (e.g. app.example.com)") .requiredOption("-p, --project ", "Project ID to attach the domain to") .option("--primary", "Mark this domain as the project's primary", false) + .option("--service ", "Target service within the selected project") + .option("--port ", "Container port to route (required for ambiguous service ports)", positiveInteger) .action(async (hostname: string, opts) => { const sp = spin(`Adding ${hostname}…`); try { const ship = getShipClient(); + const attach = await prepareCustomDomainEndpoint(ship, opts.project, { service: opts.service, port: opts.port }); const res = await ship.domains.create(opts.project, { hostname, isPrimary: !!opts.primary }); - const routed = await attachCustomDomainEndpoint(ship, opts.project, res.domain.hostname); + await attach(res.domain.hostname); sp?.succeed(`Added ${res.domain.hostname}`); - if (routed) info(` ${res.domain.hostname} is configured to be routed on the next deploy.`); + info(` ${res.domain.hostname} is configured to be routed on the next deploy.`); if (isJsonMode()) { printJson(res); return; diff --git a/apps/cli/src/commands/service.ts b/apps/cli/src/commands/service.ts index 9f830de06..5243bdc7a 100644 --- a/apps/cli/src/commands/service.ts +++ b/apps/cli/src/commands/service.ts @@ -25,6 +25,7 @@ import { getShipClient, ApiError, hasShipCredentials } from "../lib/ship-client" import { isJsonMode, printJson, printTable, ok, err, info } from "../lib/output"; import { collect, parsePairs, readJsonInput } from "../lib/command-input"; import { fail, confirmOrExit, reportResult, reportExecResult } from "../lib/cmd-helpers"; +import { resolveServiceRef } from "../lib/service-ref"; // ─── Shared helpers ────────────────────────────────────────────────────────── @@ -86,19 +87,7 @@ async function listServices(projectId: string): Promise { /** Resolve a service ref (name or svc_ id) to its row within the stack. */ async function resolveService(projectId: string, ref: string): Promise { - if (/^svc_/.test(ref)) return getShipClient().services.get(projectId, ref); - const services = await listServices(projectId); - const byId = services.find((s) => s.id === ref); - if (byId) return byId; - const byName = services.filter((s) => s.name === ref); - if (byName.length === 1) return byName[0]; - if (byName.length > 1) { - err(` "${ref}" matches ${byName.length} services — pass the service id (svc_…).`); - exitCommand(1); - } - const known = services.map((s) => s.name).join(", ") || "(none)"; - err(` No service "${ref}" in this stack. Services: ${known}`); - exitCommand(1); + return resolveServiceRef(getShipClient(), projectId, ref); } // ─── list / get ─────────────────────────────────────────────────────────────── diff --git a/apps/cli/src/lib/custom-domain-endpoint.ts b/apps/cli/src/lib/custom-domain-endpoint.ts index 1b1c1a8cf..b979265ff 100644 --- a/apps/cli/src/lib/custom-domain-endpoint.ts +++ b/apps/cli/src/lib/custom-domain-endpoint.ts @@ -1,71 +1,79 @@ -import { safeErrorMessage } from "@repo/core"; +import { firstServicePort, resolveRedirectStatus, safeErrorMessage } from "@repo/core"; import type { UpdateProjectInput } from "@repo/contracts"; import type { CliShipClient } from "./ship-client"; -import { reportCliMessage } from "./output"; +import { resolveServiceRef } from "./service-ref"; type PublicEndpoint = NonNullable[number]; -/** Attach the routing endpoint after claiming the domain, as the dashboard does. */ +export interface CustomDomainTarget { service?: string; port?: number } + +/** Validate the target before claiming a hostname, then save through the same + * project/service API used by the dashboard. DNS verification and deployment + * remain explicit subsequent steps. */ +export async function prepareCustomDomainEndpoint( + ship: Pick, + projectId: string, + options: CustomDomainTarget = {}, +): Promise<(hostname: string) => Promise> { + const { project } = await ship.projects.getInfo(projectId); + if (!options.service && project.projectType !== "app") + throw new Error("This is a multi-service project. Pass --service and --port to select its route."); + if (!options.service && project.options.workloadType === "worker") + throw new Error("This worker has no public route. Configure a web workload before adding a domain."); + const service = options.service ? await resolveServiceRef(ship, projectId, options.service) : undefined; + const hasServer = !!service || project.options.hasServer; + const endpoints: PublicEndpoint[] = service?.publicEndpoints?.map(endpoint => ({ ...endpoint, redirectStatus: endpoint.redirectStatus !== undefined ? resolveRedirectStatus(endpoint.redirectStatus) : undefined })) ?? + (service ? [] : (project as typeof project & { publicEndpoints?: PublicEndpoint[] }).publicEndpoints ?? []); + const ports = service ? [...new Set([ + ...(service.ports ?? []).map(spec => firstServicePort([spec])), + ...(service.publicEndpoints ?? []).map(endpoint => endpoint.port), + Number(service.exposedPort), + ].filter((value): value is number => Number.isInteger(value) && Number(value) > 0 && Number(value) <= 65535))] : []; + const port = options.port ?? (service + ? ports.length === 1 ? ports[0] : undefined + : Number(project.options.productionPort || project.port)); + if (hasServer && (!Number.isInteger(port) || !port || port < 1 || port > 65535)) + throw new Error("Choose a valid container port with --port <1-65535>; services with multiple ports require an explicit target."); + if (!hasServer && options.port !== undefined) + throw new Error("A static project routes its output directory; --port requires a web service."); + + return async hostname => { + const host = hostname.trim().toLowerCase(); + try { + // Project info adds UI metadata. Send only the accepted save fields, keeping + // every existing target, hostname, redirect, and endpoint position intact. + const publicEndpoints: PublicEndpoint[] = endpoints.map((endpoint) => ({ + ...(endpoint.port !== undefined ? { port: endpoint.port } : {}), + ...(endpoint.targetPath !== undefined ? { targetPath: endpoint.targetPath } : {}), + ...(endpoint.domain !== undefined ? { domain: endpoint.domain } : {}), + ...(endpoint.customDomain !== undefined ? { customDomain: endpoint.customDomain } : {}), + ...(endpoint.domainType !== undefined ? { domainType: endpoint.domainType } : {}), + ...(endpoint.redirectTo !== undefined ? { redirectTo: endpoint.redirectTo } : {}), + ...(endpoint.redirectStatus !== undefined ? { redirectStatus: endpoint.redirectStatus } : {}), + })); + const endpoint = { domainType: "custom" as const, customDomain: host, ...(hasServer ? { port } : { targetPath: "/" }) }; + const index = publicEndpoints.findIndex(value => value.customDomain?.toLowerCase() === host); + if (index >= 0) { + if (options.port === undefined || publicEndpoints[index]!.port === port) return; + publicEndpoints[index] = { ...publicEndpoints[index], ...endpoint }; + } else publicEndpoints.push(endpoint); + if (service) await ship.services.update(projectId, service.id, { exposed: true, publicEndpoints }); + else await ship.projects.update(projectId, { publicEndpoints }); + } catch (error) { + throw new Error( + `Domain ${host} row still exists, but attaching its route failed: ${safeErrorMessage(error)}. Retry in the dashboard project ${projectId} Domains tab: configure this domain's target and save.`, + { cause: error }, + ); + } + }; +} + +/** Existing callers claim a domain before attaching its endpoint. */ export async function attachCustomDomainEndpoint( - ship: Pick, + ship: Pick, projectId: string, hostname: string, ): Promise { - const host = hostname.trim().toLowerCase(); - try { - const { project } = await ship.projects.getInfo(projectId); - const endpoints = - (project as typeof project & { publicEndpoints?: PublicEndpoint[] }).publicEndpoints ?? []; - if (endpoints.some((endpoint) => endpoint.customDomain?.toLowerCase() === host)) return true; - - if (project.options.workloadType === "worker") { - reportCliMessage( - "warn", - `Domain ${host} was added, but this worker has no public route. Configure a web workload and port before attaching it.`, - ); - return false; - } - - if (project.projectType !== "app") { - reportCliMessage( - "warn", - `Domain ${host} was added, but ${project.name || projectId} is a multi-service project, so routes belong to a service. Attach it to a service in the dashboard.`, - ); - return false; - } - - const hasServer = project.options.hasServer; - const port = Number(project.options.productionPort || project.port); - if (hasServer && (!Number.isInteger(port) || port < 1 || port > 65535)) { - reportCliMessage( - "warn", - `Domain ${host} was added, but the project has no valid server port and no public route. Configure a port in the dashboard Domains tab.`, - ); - return false; - } - - // Project info adds UI metadata. Send only the accepted save fields, keeping - // every existing target, hostname, redirect, and endpoint position intact. - const publicEndpoints: PublicEndpoint[] = endpoints.map((endpoint) => ({ - ...(endpoint.port !== undefined ? { port: endpoint.port } : {}), - ...(endpoint.targetPath !== undefined ? { targetPath: endpoint.targetPath } : {}), - ...(endpoint.domain !== undefined ? { domain: endpoint.domain } : {}), - ...(endpoint.customDomain !== undefined ? { customDomain: endpoint.customDomain } : {}), - ...(endpoint.domainType !== undefined ? { domainType: endpoint.domainType } : {}), - ...(endpoint.redirectTo !== undefined ? { redirectTo: endpoint.redirectTo } : {}), - ...(endpoint.redirectStatus !== undefined ? { redirectStatus: endpoint.redirectStatus } : {}), - })); - publicEndpoints.push({ - domainType: "custom", - customDomain: host, - ...(hasServer ? { port } : { targetPath: "/" }), - }); - await ship.projects.update(projectId, { publicEndpoints }); - return true; - } catch (error) { - throw new Error( - `Domain ${host} row still exists, but attaching its route failed: ${safeErrorMessage(error)}. Retry in the dashboard project ${projectId} Domains tab: configure this domain's target and save.`, - { cause: error }, - ); - } + await (await prepareCustomDomainEndpoint(ship, projectId))(hostname); + return true; } diff --git a/apps/cli/src/lib/service-ref.ts b/apps/cli/src/lib/service-ref.ts new file mode 100644 index 000000000..619ebbc17 --- /dev/null +++ b/apps/cli/src/lib/service-ref.ts @@ -0,0 +1,13 @@ +import type { CliShipClient } from "./ship-client"; + +/** Resolve only within the selected project; never fall back to another stack. */ +export async function resolveServiceRef(ship: Pick, projectId: string, ref: string) { + if (/^svc_/.test(ref)) return ship.services.get(projectId, ref); + const services = await ship.services.list(projectId); + const byId = services.find(service => service.id === ref); + if (byId) return byId; + const matches = services.filter(service => service.name === ref); + if (matches.length === 1) return matches[0]!; + if (matches.length > 1) throw new Error(`"${ref}" matches ${matches.length} services — pass the service id (svc_…).`); + throw new Error(`No service "${ref}" in this stack. Services: ${services.map(service => service.name).join(", ") || "(none)"}`); +} diff --git a/apps/cli/test/e2e/domain.test.ts b/apps/cli/test/e2e/domain.test.ts index e1d2405cf..cae63fd24 100644 --- a/apps/cli/test/e2e/domain.test.ts +++ b/apps/cli/test/e2e/domain.test.ts @@ -86,9 +86,9 @@ describe("openship domain add", () => { : { status: 201, json: ADDED }); const { err, code } = await runCommand(domainCommand, ["add", "app.example.com", "-p", "prj1"]); expect(code).toBe(0); - expect(fetchStub.calls[0].method).toBe("POST"); - expect(fetchStub.calls[0].url).toBe(`${API}/domains`); - expect(fetchStub.calls[0].body).toEqual({ projectId: "prj1", hostname: "app.example.com", isPrimary: false }); + const creation = fetchStub.calls.find(call => call.method === "POST")!; + expect(creation.url).toBe(`${API}/domains`); + expect(creation.body).toEqual({ projectId: "prj1", hostname: "app.example.com", isPrimary: false }); expect(err).toContain("openship domain verify d9"); // next-step hint names the new id }); @@ -99,7 +99,7 @@ describe("openship domain add", () => { ? { json: { data: projectInfo.project } } : { status: 201, json: ADDED }); await runCommand(domainCommand, ["add", "app.example.com", "-p", "prj1", "--primary"]); - expect(fetchStub.calls[0].body).toMatchObject({ isPrimary: true }); + expect(fetchStub.calls.find(call => call.method === "POST")!.body).toMatchObject({ isPrimary: true }); }); it("emits the domain and its DNS records as JSON in json mode", async () => { diff --git a/apps/cli/test/unit/custom-domain-endpoint.test.ts b/apps/cli/test/unit/custom-domain-endpoint.test.ts index 39d360423..45f0154c9 100644 --- a/apps/cli/test/unit/custom-domain-endpoint.test.ts +++ b/apps/cli/test/unit/custom-domain-endpoint.test.ts @@ -4,6 +4,8 @@ const h = vi.hoisted(() => ({ project: {} as Record, rows: [] as unknown[], updates: [] as unknown[], + services: [] as Array>, + serviceUpdates: [] as unknown[], updateError: false, })); vi.mock("../../src/lib/ship-client", async (importOriginal) => { @@ -30,6 +32,18 @@ vi.mock("../../src/lib/ship-client", async (importOriginal) => { h.updates.push({ id, input }); }, }, + services: { + list: async () => h.services, + get: async (_project: string, id: string) => { + const service = h.services.find(service => service.id === id); + if (!service) throw new Error("Service not found in project"); + return service; + }, + update: async (project: string, id: string, input: unknown) => { + if (h.updateError) throw new Error("update unavailable"); + h.serviceUpdates.push({ project, id, input }); + }, + }, domains: { verify: async () => { throw new Error("verification unavailable"); @@ -59,6 +73,8 @@ beforeEach(() => { h.rows = []; h.updates = []; h.updateError = false; + h.services = []; + h.serviceUpdates = []; }); afterEach(() => vi.restoreAllMocks()); @@ -122,28 +138,48 @@ describe("CLI custom domain routing", () => { expect(h.updates).toEqual([]); }); - it("warns without attaching a portless worker or failing the command", async () => { + it("refuses a portless worker before claiming a domain", async () => { h.project = { ...h.project, hasServer: false, workloadType: "worker", port: null }; - const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); const result = await add(); - expect(result.code).toBe(0); - expect(h.rows).toHaveLength(1); + expect(result.code).toBe(1); + expect(h.rows).toEqual([]); expect(h.updates).toEqual([]); - expect(warning.mock.calls.flat().join(" ")).toMatch(/worker.*no public route/i); - expect(result.err).not.toContain("routed on the next deploy"); + expect(result.err).toContain("worker has no public route"); }); - it.each(["services", "monorepo"])("warns without attaching a %s project", async (projectType) => { - h.project = { ...h.project, name: "My project", projectType }; - const warning = vi.spyOn(console, "warn").mockImplementation(() => {}); + it.each(["services", "monorepo"])("requires an explicit target before claiming a domain for %s", async projectType => { + h.project = { ...h.project, projectType }; const result = await add(); - expect(result.code).toBe(0); - expect(h.rows).toHaveLength(1); + expect(result.code).toBe(1); + expect(h.rows).toEqual([]); + expect(result.err).toContain("--service"); + }); + + it.each(["web", "svc_web"])("attaches to the project-scoped service selected by %s", async ref => { + h.project.projectType = "services"; + const existing = [{ domainType: "free", domain: "existing", port: 8080 }]; + h.services = [{ id: "svc_web", name: "web", ports: ["8080:3000"], publicEndpoints: existing }]; + const result = await runCommand(domainCommand, ["add", "app.example.com", "-p", "project-1", "--service", ref, "--port", "3000"]); + expect(result.code, result.err).toBe(0); expect(h.updates).toEqual([]); - expect(warning).toHaveBeenCalledWith( - "Domain app.example.com was added, but My project is a multi-service project, so routes belong to a service. Attach it to a service in the dashboard.", - ); - expect(result.err).not.toContain("routed on the next deploy"); + expect(h.serviceUpdates).toEqual([{ project: "project-1", id: "svc_web", input: { exposed: true, publicEndpoints: [...existing, { domainType: "custom", customDomain: "app.example.com", port: 3000 }] } }]); + }); + + it.each(["unknown", "svc_foreign"])("rejects an unknown or foreign service %s before claiming the hostname", async ref => { + h.project.projectType = "services"; + const result = await runCommand(domainCommand, ["add", "app.example.com", "-p", "project-1", "--service", ref, "--port", "3000"]); + expect(result.code).toBe(1); + expect(h.rows).toEqual([]); + expect(h.serviceUpdates).toEqual([]); + }); + + it("requires a port when the selected service has several possible targets", async () => { + h.project.projectType = "services"; + h.services = [{ id: "svc_web", name: "web", ports: ["3000", "3001"] }]; + const result = await runCommand(domainCommand, ["add", "app.example.com", "-p", "project-1", "--service", "web"]); + expect(result.code).toBe(1); + expect(h.rows).toEqual([]); + expect(result.err).toContain("--port"); }); it.each(["domain", "edge"])( diff --git a/apps/web/content/docs/cli/projects.mdx b/apps/web/content/docs/cli/projects.mdx index 09a290981..3951622bd 100644 --- a/apps/web/content/docs/cli/projects.mdx +++ b/apps/web/content/docs/cli/projects.mdx @@ -86,11 +86,17 @@ command, build settings, routing, ports and enabled state. ```bash openship domain add app.example.com --project proj_123 +# Multi-service project: choose a service and its container port. +openship domain add api.example.com --project proj_123 --service api --port 3000 openship domain records dom_123 openship domain verify dom_123 openship domain verify-ssl dom_123 ``` +Target validation happens before the hostname is claimed. The selected project or service keeps its +existing endpoints; the new domain becomes routable on the next deployment. A multi-service project +requires `--service`; services with several ports also require `--port`. + Follow the returned DNS instructions before verification. See [domain options](/docs/cli/reference/domain) and the [custom-domain guide](/docs/guides/custom-domains) for DNS providers, TLS, and primary domains. diff --git a/apps/web/content/docs/cli/reference/domain/index.mdx b/apps/web/content/docs/cli/reference/domain/index.mdx index ec444896c..99a5c4ee2 100644 --- a/apps/web/content/docs/cli/reference/domain/index.mdx +++ b/apps/web/content/docs/cli/reference/domain/index.mdx @@ -47,6 +47,8 @@ openship domain add [options] | --- | --- | | `-p, --project ` | Project ID to attach the domain to | | `--primary` | Mark this domain as the project's primary (default: false) | +| `--service ` | Target service within the selected project | +| `--port ` | Container port to route (required for ambiguous service ports) | ## openship domain get