diff --git a/apps/api/src/modules/system/setup.controller.ts b/apps/api/src/modules/system/setup.controller.ts index 47a90997f..4770e16f6 100644 --- a/apps/api/src/modules/system/setup.controller.ts +++ b/apps/api/src/modules/system/setup.controller.ts @@ -356,7 +356,7 @@ export async function resetAdminPassword(c: Context) { // multi-user box the reset never lands on an arbitrary member row. const admin = await repos.user.findFoundingAdmin(); if (!admin) { - return c.json({ error: "No admin account exists yet — run `openship` to create one." }, 409); + return c.json({ error: "No admin account exists yet — run `openship` and choose Create first admin, or run `openship up --non-interactive --admin-email ` with OPENSHIP_ADMIN_PASSWORD set." }, 409); } const email = diff --git a/apps/cli/src/commands/up.ts b/apps/cli/src/commands/up.ts index b0bf16f53..5af9fdc1a 100644 --- a/apps/cli/src/commands/up.ts +++ b/apps/cli/src/commands/up.ts @@ -44,6 +44,7 @@ import { LocalExecutor } from "@repo/adapters"; import { resolveInstallInputs, headlessProvision, + provisionInstanceDomain, HeadlessInputError, } from "../lib/instance-provision"; import { mintBareInternalToken } from "../lib/internal-token"; @@ -284,6 +285,26 @@ export const upCommand = new Command("up") if (opts.fromSource || opts.source) return runFromSource(opts); if (opts.foreground) return runForeground(opts); const headless = !!(opts.nonInteractive || opts.yes); + // Validate requested provisioning before pulling images or stopping services. + if (headless || opts.managedEdge) { + try { + if (opts.managedEdge) { + opts.publicUrl = effectivePublicUrl(opts.publicUrl); + if (!opts.publicUrl || new URL(opts.publicUrl).protocol !== "https:") + throw new HeadlessInputError("--managed-edge requires --public-url https://your-domain (or an existing saved HTTPS URL)."); + if (opts.domainKind && opts.domainKind !== "custom") + throw new HeadlessInputError("--managed-edge requires --domain-kind custom."); + if (opts.hostname && opts.hostname !== new URL(opts.publicUrl).hostname) + throw new HeadlessInputError("--hostname must match --public-url when using --managed-edge."); + opts.trustProxy = true; + } + if (headless) upInstallInputs(opts); + } catch (error) { + reportCliMessage("error", (error as Error).message); + process.exit(1); + } + } + // Install method: Compose is the default when it can actually work (Docker on // Linux — the edge container needs host networking); else bare. `planMethod` // owns the decision so `--dry-run` predicts the same one. @@ -319,9 +340,10 @@ export const upCommand = new Command("up") if (!token) { reportCliMessage("warn", chalk.yellow( - "\n Couldn't read the stack's internal token (compose/.env) — create the admin from the dashboard.\n", + "\n Couldn't read the stack's internal token (compose/.env). Run this command as the installation owner (or sudo) to finish admin setup.\n", ), ); + process.exit(1); } else { await runHeadlessProvision( opts, @@ -329,6 +351,18 @@ export const upCommand = new Command("up") { token, method: "compose" }, ); } + } else if (opts.managedEdge) { + const result = await provisionInstanceDomain({ + port: started.apiPort, dashPort: started.dashPort, token: composeInternalToken() ?? undefined, + domain: { kind: "custom", hostname: new URL(opts.publicUrl!).hostname, acmeEmail: opts.acmeEmail, + edge: opts.edge === "takeover" || opts.edge === "migrate" ? opts.edge : "cancel" }, + onLog: message => console.log(chalk.dim(` ${message}`)), + }); + for (const warning of result.warnings) reportCliMessage("warn", warning); + if (!result.domainRegistered) { + reportCliMessage("error", "Managed domain registration did not complete. If this is a new install, run `openship` and choose Create first admin, then retry this command."); + process.exit(1); + } } return; } @@ -336,6 +370,21 @@ export const upCommand = new Command("up") if (headless) await runHeadlessProvision(opts, started, { method: "bare" }); }); +/** Flags and preflight share one provisioning interpretation. */ +function upInstallInputs(opts: UpOpts) { + return resolveInstallInputs({ + adminName: opts.adminName, + adminEmail: opts.adminEmail, + adminPassword: opts.adminPassword, + domainKind: opts.domainKind ?? (opts.managedEdge ? "custom" : undefined), + hostname: opts.hostname, + slug: opts.slug, + publicUrl: opts.publicUrl, + acmeEmail: opts.acmeEmail, + edge: opts.edge, + }); +} + /** * Headless install (bare service): after `startService` installs + supervises * the process, create the admin + register the domain from the flags, so a box @@ -349,17 +398,7 @@ export async function runHeadlessProvision( ): Promise { let inputs; try { - inputs = resolveInstallInputs({ - adminName: opts.adminName, - adminEmail: opts.adminEmail, - adminPassword: opts.adminPassword, - domainKind: opts.domainKind, - hostname: opts.hostname, - slug: opts.slug, - publicUrl: opts.publicUrl, - acmeEmail: opts.acmeEmail, - edge: opts.edge, - }); + inputs = upInstallInputs(opts); } catch (err) { if (err instanceof HeadlessInputError) { reportCliMessage("error", chalk.red(`\n ${err.message}\n`)); @@ -377,8 +416,10 @@ export async function runHeadlessProvision( method: extra?.method, onLog: (m) => console.log(chalk.dim(` ${m}`)), }); - console.log(chalk.green(`\n ✓ Openship provisioned${result.liveUrl ? `: ${result.liveUrl}` : "."}`)); for (const w of result.warnings) reportCliMessage("warn", chalk.yellow(` ⚠ ${w}`)); + if (opts.managedEdge && !result.domainRegistered) + throw new Error("Managed domain registration did not complete. Retry after resolving the domain warning above."); + console.log(chalk.green(`\n ✓ Openship provisioned${result.liveUrl ? `: ${result.liveUrl}` : "."}`)); } catch (err) { observeCaughtError(err, "cli/commands/up"); reportCliMessage("error", chalk.red(`\n Headless provisioning failed: ${(err as Error).message}\n`)); @@ -641,7 +682,7 @@ async function runCompose(opts: UpOpts & { yes?: boolean }): Promise<{ apiPort: chalk.dim(" Images: api + dashboard + edge (OpenResty on :80/:443)\n") + chalk.dim(" Manage: openship stop · openship update · openship status\n") + // In headless mode the admin is bootstrapped below — don't tell the user to do it by hand. - (headless ? "" : chalk.dim(" Create an admin: open the dashboard and register the first account.\n")), + (headless ? "" : chalk.dim(" Admin setup: run `openship` → Create first admin, or use `openship up --non-interactive --admin-email ` with OPENSHIP_ADMIN_PASSWORD set.\n")), ); return { apiPort: res.apiPort, dashPort: res.dashPort }; } diff --git a/apps/cli/src/commands/wizard.ts b/apps/cli/src/commands/wizard.ts index 814fe0f28..ba716acb0 100644 --- a/apps/cli/src/commands/wizard.ts +++ b/apps/cli/src/commands/wizard.ts @@ -1231,7 +1231,7 @@ export async function runControl(): Promise { `${chalk.dim("Dashboard".padEnd(11))}${dashUrl}\n` + (ports.api ? `${chalk.dim("API".padEnd(11))}http://localhost:${ports.api}\n` : "") + `${chalk.dim("Manager".padEnd(11))}${managerLabel}`, - "Openship is already set up", + "Openship is installed", ); // Crash-looping on a corrupt DB is the one case where "Start" won't help — @@ -1279,6 +1279,7 @@ export async function runControl(): Promise { : { value: "start", label: "Start the service" }, { value: "stop", label: "Stop the service", hint: "won't restart on boot" }, ...(corrupted ? [] : [{ value: "repair", label: "Repair database", hint: "backup → heal a corrupt DB" }]), + { value: "create-admin", label: "Create first admin", hint: "finish a new install; existing accounts stay intact" }, { value: "reset", label: "Reset admin password", hint: "sets a local email + password login" }, { value: "reconfigure", label: "Re-run setup", hint: "reconfigure domain / cloud / admin" }, { value: "quit", label: "Quit" }, @@ -1287,6 +1288,16 @@ export async function runControl(): Promise { ); switch (action) { + case "create-admin": { + const admin = await promptLocalAdmin(); + const result = await bootstrapAdmin(apiPort, admin); + outro(result.ok + ? result.message === "already-exists" + ? "An admin already exists. Use Reset admin password if you need to recover access." + : `Admin created. Sign in at ${primaryUrl}.` + : `Could not create the admin: ${result.message}`); + return; + } case "repair": { const res = await runRepair(); outro(res.healed ? chalk.green(res.detail) : chalk.yellow(res.detail)); diff --git a/apps/cli/src/lib/instance-provision.ts b/apps/cli/src/lib/instance-provision.ts index b9801ebc7..33b13c440 100644 --- a/apps/cli/src/lib/instance-provision.ts +++ b/apps/cli/src/lib/instance-provision.ts @@ -268,8 +268,6 @@ export async function headlessProvision(opts: { }): Promise { const { port, inputs, token } = opts; const log = opts.onLog ?? (() => {}); - const warnings: string[] = []; - log("Waiting for the API to become healthy…"); if (!(await waitHealthy(port))) { throw new HeadlessInputError("The API did not become healthy in time — check `openship logs`."); @@ -279,8 +277,24 @@ export async function headlessProvision(opts: { const admin = await bootstrapOrReset(port, inputs.admin, token); if (!admin.ok) throw new HeadlessInputError(`Could not create the admin account: ${admin.message}`); + return { adminReady: true, ...await provisionInstanceDomain({ ...opts, domain: inputs.domain }) }; +} + +/** Register routing independently of credentials, including managed-edge + * re-runs on an already initialized Compose install. */ +export async function provisionInstanceDomain(opts: { + port: string; + dashPort?: string; + domain: InstallInputs["domain"]; + token?: string; + onLog?: (msg: string) => void; + onSlugTaken?: (taken: string) => Promise; +}): Promise> { + const { port, token } = opts; + const log = opts.onLog ?? (() => {}); + const warnings: string[] = []; const dashPort = opts.dashPort ? Number(opts.dashPort) : undefined; - const d = inputs.domain; + const d = opts.domain; let liveUrl: string | undefined; let domainRegistered = false; @@ -392,5 +406,5 @@ export async function headlessProvision(opts: { } } - return { adminReady: true, domainRegistered, liveUrl, warnings }; + return { domainRegistered, liveUrl, warnings }; } diff --git a/apps/cli/test/e2e/up.test.ts b/apps/cli/test/e2e/up.test.ts index 8ffcf15c7..d1716f857 100644 --- a/apps/cli/test/e2e/up.test.ts +++ b/apps/cli/test/e2e/up.test.ts @@ -207,6 +207,8 @@ beforeEach(() => { (upCommand as any).setOptionValue?.("edge", undefined); (upCommand as any).setOptionValue?.("compose", undefined); (upCommand as any).setOptionValue?.("resetSecrets", undefined); + for (const key of ["managedEdge", "publicUrl", "trustProxy", "nonInteractive", "yes", "adminEmail", "adminPassword", "domainKind", "hostname"]) + upCommand.setOptionValue(key, undefined); con = captureConsole(); }); @@ -218,6 +220,68 @@ afterEach(() => { }); describe("openship up --compose (edge chain)", () => { + it("gives a usable first-admin instruction after an ordinary install", async () => { + const result = await runCommand(upCommand, ["--compose"]); + expect(result.code).toBe(0); + expect(con.text()).toContain("Create first admin"); + expect(con.text()).not.toContain("register the first account"); + }); + + it("refuses incomplete non-interactive setup before changing the stack", async () => { + const result = await runCommand(upCommand, ["--compose", "--non-interactive"]); + expect(result.code).toBe(1); + expect(h.prefetchCalls).toBe(0); + expect(h.composeUpCalls).toBe(0); + expect(con.text()).toContain("--admin-email"); + }); + + it("requires an HTTPS hostname before starting managed-edge installation", async () => { + const result = await runCommand(upCommand, ["--compose", "--managed-edge", "--public-url", "http://ops.example.com"]); + expect(result.code).toBe(1); + expect(h.composeUpCalls).toBe(0); + expect(con.text()).toContain("https://"); + }); + + it("honors managed-edge in Compose without changing admin credentials", async () => { + fetchStub = stubFetch(request => { + expect(request.url).toContain("/api/system/self-register"); + expect(request.body).toMatchObject({ domainType: "custom", hostname: "ops.example.com", dashPort: 3001 }); + return { json: { url: "https://ops.example.com" } }; + }); + const result = await runCommand(upCommand, ["--compose", "--managed-edge", "--public-url", "https://ops.example.com"]); + expect(result.code, result.err).toBe(0); + expect(fetchStub.calls).toHaveLength(1); + expect(fetchStub.calls[0]!.headers["x-internal-token"]).toBe("tok"); + }); + + it("provisions the requested managed domain during headless Compose setup", async () => { + fetchStub = stubFetch(request => { + if (request.url.endsWith("/api/health")) return { json: { status: "ok" } }; + if (request.url.endsWith("/api/system/bootstrap-admin")) return { json: { success: true } }; + expect(request.url).toContain("/api/system/self-register"); + expect(request.body).toMatchObject({ domainType: "custom", hostname: "ops.example.com" }); + return { json: { url: "https://ops.example.com" } }; + }); + const result = await runCommand(upCommand, ["--compose", "--managed-edge", "--public-url", "https://ops.example.com", + "--non-interactive", "--admin-email", "owner@example.com", "--admin-password", "strong-initial-password"]); + expect(result.code, con.text()).toBe(0); + expect(fetchStub.calls.map(call => new URL(call.url).pathname)).toEqual([ + "/api/health", "/api/system/bootstrap-admin", "/api/system/self-register", + ]); + }); + + it("does not report managed-edge success when registration fails", async () => { + fetchStub = stubFetch(request => { + if (request.url.endsWith("/api/health")) return { json: { status: "ok" } }; + if (request.url.endsWith("/api/system/bootstrap-admin")) return { json: { success: true } }; + return { status: 503, json: { error: "Edge unavailable" } }; + }); + const result = await runCommand(upCommand, ["--compose", "--managed-edge", "--public-url", "https://ops.example.com", + "--non-interactive", "--admin-email", "owner@example.com", "--admin-password", "strong-initial-password"]); + expect(result.code).toBe(1); + expect(con.text()).toContain("Managed domain registration did not complete"); + expect(con.text()).not.toContain("✓ Openship provisioned"); + }); it("exits before the edge preflight when docker/compose is missing", async () => { h.hasDocker = false; const r = await runCommand(upCommand, ["--compose"]); diff --git a/apps/cli/test/unit/headless-provision-domain.test.ts b/apps/cli/test/unit/headless-provision-domain.test.ts index dd0e2f7f7..435f4132f 100644 --- a/apps/cli/test/unit/headless-provision-domain.test.ts +++ b/apps/cli/test/unit/headless-provision-domain.test.ts @@ -14,6 +14,7 @@ import { describe, it, expect, beforeEach, vi } from "vitest"; const h = vi.hoisted(() => ({ posts: [] as Array<{ path: string; body: Record }>, + bootstrap: vi.fn(async () => ({ ok: true, message: "created" })), })); vi.mock("../../src/lib/loopback-api", () => ({ @@ -22,13 +23,13 @@ vi.mock("../../src/lib/loopback-api", () => ({ return { ok: true, data: { url: "https://ops.example.com" } }; }, waitHealthy: async () => true, - bootstrapAdmin: async () => ({ ok: true, message: "created" }), + bootstrapAdmin: h.bootstrap, // The provision-stream reader goes through this; unreachable here (the stubbed // self-register returns no sessionId), but the module imports it. internalFetch: async () => ({ kind: "unreachable", detail: "not stubbed" }), })); -import { headlessProvision } from "../../src/lib/instance-provision"; +import { headlessProvision, provisionInstanceDomain } from "../../src/lib/instance-provision"; const inputs = { admin: { email: "a@b.com", name: "a", password: "supersecret" }, @@ -39,9 +40,16 @@ const selfRegister = () => h.posts.find((p) => p.path === "/api/system/self-regi beforeEach(() => { h.posts = []; + h.bootstrap.mockClear(); }); describe("headlessProvision — self-app custom domain", () => { + it("can register a managed domain without creating or resetting an existing admin", async () => { + const result = await provisionInstanceDomain({ port: "4000", dashPort: "3001", domain: inputs.domain }); + expect(result.domainRegistered).toBe(true); + expect(h.bootstrap).not.toHaveBeenCalled(); + expect(h.posts.map(post => post.path)).toEqual(["/api/system/self-register"]); + }); it("requests the custom domain on COMPOSE (container edge issues the cert)", async () => { const res = await headlessProvision({ port: "4000", dashPort: "3001", inputs, method: "compose" }); diff --git a/docs/installation.md b/docs/installation.md index 756a9f1dc..ffd095be7 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -94,7 +94,7 @@ Fix by moving Docker's data-root to a native `ext4`/`xfs` disk (`/etc/docker/dae ## Users & access (self-hosted) -- **Public signup is disabled after the first account.** The first admin comes from the `openship` setup wizard; with `openship up --compose` (or raw Docker) you register the first account in the dashboard. Everyone after joins by invite. +- **Create the first admin on the server.** Run `openship` and choose **Create first admin**, or use `openship up --non-interactive --admin-email ` with `OPENSHIP_ADMIN_PASSWORD` set. The same setup works for CLI-managed Compose installs. Public signup stays disabled; everyone after joins by invite. - **Invite teammates** from **Settings → Team**. They get an accept link at your instance's URL (so the instance needs to be reachable — a public URL or your LAN). - **Lost the admin password?** Run `openship reset-admin-password` on the box (no sign-in needed; uses the local internal token).