diff --git a/apps/api/src/modules/deployments/cancel-is-final.test.ts b/apps/api/src/modules/deployments/cancel-is-final.test.ts index 841363250..062a62169 100644 --- a/apps/api/src/modules/deployments/cancel-is-final.test.ts +++ b/apps/api/src/modules/deployments/cancel-is-final.test.ts @@ -43,7 +43,6 @@ vi.mock("@repo/platform/engine/modules/projects/cleanup-keep-set", () => ({ // Terminal-event side channels, each of which drags in auth/github/mail wiring. vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: mocks.notify } })); vi.mock("../../lib/audit", () => ({ audit: { recordAsync: vi.fn(), record: vi.fn() } })); -vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn(async () => {}) })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(async () => {}), })); diff --git a/apps/api/src/modules/deployments/route-issues-warning.test.ts b/apps/api/src/modules/deployments/route-issues-warning.test.ts index ef824d981..662d10f40 100644 --- a/apps/api/src/modules/deployments/route-issues-warning.test.ts +++ b/apps/api/src/modules/deployments/route-issues-warning.test.ts @@ -1,12 +1,11 @@ import { describe, expect, it, vi } from "vitest"; // The function under test is pure; everything else this module reaches (DB, SSE, -// notifications, favicon probing) is a side effect the assertion doesn't want. +// notifications) is a side effect the assertion doesn't want. // `@repo/adapters` stays REAL — `isEdgeDownMessage` is the branch being pinned. vi.mock("@repo/db", () => ({ repos: {} })); vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: {} })); vi.mock("../../lib/audit", () => ({ audit: {} })); -vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn() })); vi.mock("@repo/platform/engine/modules/deployments/session-manager", () => ({})); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(), diff --git a/apps/api/src/modules/migration/platform-import-plan.test.ts b/apps/api/src/modules/migration/platform-import-plan.test.ts index 38db65086..2acc649ba 100644 --- a/apps/api/src/modules/migration/platform-import-plan.test.ts +++ b/apps/api/src/modules/migration/platform-import-plan.test.ts @@ -144,14 +144,18 @@ describe("reviewed platform imports", () => { { sourceId: "db", envKey: "DATABASE_URL", + valueTemplate: "postgres://app:source-secret@${host}/app", }, ]); expect(privatePlan.services[1].environment.DATABASE_URL).toBe( "postgres://app:source-secret@database/app", ); - expect(privatePlan.project.name).toBe("Project"); - expect(privatePlan.project.services?.map((row) => row.name)).toEqual(["database", "website"]); - expect(JSON.stringify(privatePlan.project)).not.toContain("source-secret"); + expect(privatePlan.projects[0].create.name).toBe("Project"); + expect(privatePlan.projects[0].create.services?.map((row) => row.name)).toEqual([ + "database", + "website", + ]); + expect(JSON.stringify(privatePlan.projects)).not.toContain("source-secret"); expect(privatePlan.services[0].environment.PGHOST).toBe( privatePlan.services[0].create.internalAlias, ); @@ -182,29 +186,109 @@ describe("reviewed platform imports", () => { it("names storage per service inside one destination project", async () => { inventory.services[1].volumes = [{ id: "files", mountPath: "/data" }]; const plan = await loadReviewedImport(ctx, (await review()).planId); - expect(plan.project.services?.flatMap((service) => service.volumes ?? [])).toEqual([ + expect(plan.projects[0].create.services?.flatMap((service) => service.volumes ?? [])).toEqual([ "database-data-0:/var/lib/postgresql/data", "website-data-0:/data", ]); - expect(plan.project.services?.[1].dependsOn).toEqual(["database"]); + expect(plan.projects[0].create.services?.[1].dependsOn).toEqual(["database"]); }); - it("blocks incompatible Git sources instead of splitting the source project", async () => { - inventory.services = ["one", "two"].map((id) => + it.each(["repository", "commit", "branch"])( + "splits incompatible Git %s without losing revisions or private connections", + async (difference) => { + inventory.services = ["one", "two"].map((id) => + service({ + id, + name: id, + image: undefined, + repository: difference === "repository" ? `owner/${id}` : "owner/repo", + commit: (difference === "commit" && id === "two" ? "b" : "a").repeat(40), + branch: difference === "branch" ? id : "main", + privateDomain: `${id}.railway.internal`, + env: id === "two" ? { API_URL: "http://one.railway.internal:3000/api?secret=keep" } : {}, + }), + ); + const result = await review( + inventory.services.map((service) => ({ + id: service.id, + name: service.name, + data: "empty", + })), + ); + expect(result.ready, JSON.stringify(result)).toBe(true); + expect(result.projects).toEqual([ + { name: "project-one", serviceIds: ["one"] }, + { name: "project-two", serviceIds: ["two"] }, + ]); + const plan = await loadReviewedImport(ctx, result.planId); + expect(plan.projects.map((project) => project.create.gitRepo)).toEqual( + difference === "repository" ? ["one", "two"] : ["repo", "repo"], + ); + expect(plan.services[1].bindings).toEqual([ + { + sourceId: "one", + envKey: "API_URL", + valueTemplate: "http://${host}:3000/api?secret=keep", + }, + ]); + expect(plan.services.map((s) => s.source.commit)).toEqual( + inventory.services.map((s) => s.commit), + ); + expect(h.info.mock.calls.map(([input]) => input.owner)).toEqual(["owner", "owner"]); + expect(h.info.mock.calls.map(([input]) => input.branch)).toEqual( + inventory.services.map((s) => s.commit), + ); + }, + ); + it("keeps compatible source services together and rejects composite cross-project variables during review", async () => { + const git = (id: string, repository: string) => service({ id, name: id, image: undefined, - repository: `owner/${id}`, + repository, commit: "a".repeat(40), + privateDomain: `${id}.railway.internal`, + }); + inventory.services = [git("one", "owner/repo"), git("two", "owner/repo")]; + const choices = () => + inventory.services.map((s) => ({ id: s.id, name: s.name, data: "empty" as const })); + expect((await review(choices())).projects).toEqual([ + { name: "Project", serviceIds: ["one", "two"] }, + ]); + inventory.services.push(git("three", "owner/other")); + inventory.services[2].env = { HOSTS: "one.railway.internal,two.railway.internal" }; + const result = await review(choices()); + expect(result.ready).toBe(false); + expect(result.services[2].blockers.join(" ")).toContain("separate connection variable"); + }); + it("blocks unavailable private listeners and ambiguous host templates before source downtime", async () => { + inventory.services = [ + service({ + id: "store", + name: "store", + port: undefined, + privateDomain: "store.railway.internal", }), - ); + ...["one", "two"].map((id) => + service({ + id, + name: id, + image: undefined, + repository: `owner/${id}`, + commit: "a".repeat(40), + env: + id === "one" + ? { HOST: "store.railway.internal" } + : { HOST: "store.railway.internal-${host}" }, + }), + ), + ]; const result = await review( - inventory.services.map((service) => ({ id: service.id, name: service.name, data: "empty" })), + inventory.services.map((s) => ({ id: s.id, name: s.name, data: "empty" })), ); expect(result.ready).toBe(false); - expect(result.services.flatMap((service) => service.blockers).join(" ")).toContain( - "one Git source", - ); + expect(result.services[1].blockers.join(" ")).toContain("private listener port"); + expect(result.services[2].blockers.join(" ")).toContain("cannot be safely converted"); }); it("ignores pagination order and changing volume size, but never ignores changed configuration", () => { const next = structuredClone(inventory); @@ -318,7 +402,9 @@ it("uses the existing Compose build for a custom Dockerfile and preserves readin readiness: { path: "/health" }, services: [{ build: "apps/api", dockerfile: "docker/production.Dockerfile" }], }); - expect(plan.project.services?.[0].advanced).toMatchObject({ readiness: { path: "/health", port: 3000 } }); + expect(plan.projects[0].create.services?.[0].advanced).toMatchObject({ + readiness: { path: "/health", port: 3000 }, + }); expect(h.info).not.toHaveBeenCalled(); }); it("blocks an unavailable custom Dockerfile before import", async () => { diff --git a/apps/api/src/modules/migration/platform-import-worker.test.ts b/apps/api/src/modules/migration/platform-import-worker.test.ts index f932056a4..446bd3f5c 100644 --- a/apps/api/src/modules/migration/platform-import-worker.test.ts +++ b/apps/api/src/modules/migration/platform-import-worker.test.ts @@ -6,7 +6,7 @@ import type { PrivateImportPlan, PlannedImportService, } from "@repo/platform/engine/modules/migration/platform-import-plan"; -import { platformImportProject } from "@repo/platform/engine/modules/migration/platform-import-project"; +import { platformImportProjects } from "@repo/platform/engine/modules/migration/platform-import-project"; const h = vi.hoisted(() => ({ ensure: vi.fn(), merge: vi.fn(), @@ -15,6 +15,7 @@ const h = vi.hoisted(() => ({ sourceService: vi.fn(), rows: [] as Array<{ id: string; projectId: string; name: string }>, view: vi.fn(), + connect: vi.fn(), deploy: vi.fn(), copy: vi.fn(), preflight: vi.fn(), @@ -58,6 +59,9 @@ vi.mock("@repo/platform/engine/modules/projects/project-runtime.service", () => vi.mock("@repo/platform/engine/modules/apps/app-settings.service", () => ({ getAppConnectionView: h.view, })); +vi.mock("@repo/platform/engine/modules/projects/project-connection.service", () => ({ + createConnection: h.connect, +})); vi.mock("@repo/platform/engine/modules/deployments/build.service", () => ({ triggerDeployment: h.deploy, })); @@ -120,7 +124,8 @@ const planFor = (services: PlannedImportService[]) => userId: "user", targetServerId: "server", services, - project: platformImportProject("imported-project", "server", services), + projectName: "imported-project", + projects: platformImportProjects("imported-project", "server", services), }) as PrivateImportPlan; let row: any; beforeEach(() => { @@ -183,6 +188,9 @@ beforeEach(() => { h.restoreSource.mockImplementation(async (_run, resume) => { h.events.push(resume ? "resume-project" : "restore-config"); }); + h.connect.mockImplementation(async (_ctx, target, input) => { + h.events.push(`connect:${input.sourceProjectId}:${target}`); + }); }); const lifecycle = (signal = new AbortController().signal) => ({ signal, @@ -195,6 +203,95 @@ const lifecycle = (signal = new AbortController().signal) => ({ }), }); describe("provider import through normal project operations", () => { + it("copies all volumes before deploying multiple repositories in dependency order with native links", async () => { + const db = service("db", "database"), + app = service("app", "app"), + worker = service("worker", "worker"); + for (const entry of [app, worker]) + Object.assign(entry.create, { + gitProvider: "github", + gitOwner: "owner", + gitRepo: entry.source.id, + gitBranch: "main", + }); + worker.source.commit = "b".repeat(40); + app.bindings = [ + { sourceId: "db", envKey: "DB_URL", valueTemplate: "postgres://secret@${host}:5432/store" }, + ]; + worker.bindings = [{ sourceId: "app", envKey: "APP_HOST", valueTemplate: "${host}" }]; + app.environment.DB_URL = "postgres://secret@db:5432/store"; + worker.environment.APP_HOST = "app"; + const services = [worker, app, db]; + const plan = { ...planFor(services), sourceControl: "railway-project" as const }; + await executePlatformImport(ctx, "run", plan, lifecycle()); + expect(h.ensure.mock.calls.map(([body]) => body.gitRepo)).toEqual(["worker", "app", undefined]); + expect( + h.ensure.mock.calls.every(([body]) => body.services.every((s: any) => !s.dependsOn.length)), + ).toBe(true); + expect(h.copy.mock.calls.map(([input]) => [input.projectId, input.serviceId])).toEqual([ + ["imported-project-db", "imported-project-db-db"], + ["imported-project-app", "imported-project-app-app"], + ["imported-project-worker", "imported-project-worker-worker"], + ]); + expect(h.events.indexOf("copy:worker")).toBeLessThan( + h.events.indexOf("deploy:imported-project-db:1"), + ); + expect(h.events.indexOf("healthy:imported-project-db-build-1")).toBeLessThan( + h.events.indexOf("connect:imported-project-db:imported-project-app"), + ); + expect(h.events.indexOf("connect:imported-project-db:imported-project-app")).toBeLessThan( + h.events.indexOf("deploy:imported-project-app:1"), + ); + expect(h.connect).toHaveBeenCalledWith( + ctx, + "imported-project-app", + { + sourceProjectId: "imported-project-db", + outputId: "imported-project-db-db:url", + envKey: "DB_URL", + mode: "internal", + valueTemplate: "postgres://secret@${host}:5432/store", + }, + { defer: true }, + ); + expect( + h.merge.mock.calls.flatMap(([, , , input]) => input.upserts.map((v: any) => v.key)), + ).not.toContain("DB_URL"); + expect(h.deploy.mock.calls.map(([, input]) => [input.projectId, input.commitSha])).toEqual([ + ["imported-project-db", undefined], + ["imported-project-app", "a".repeat(40)], + ["imported-project-worker", "b".repeat(40)], + ]); + expect(h.verify).toHaveBeenCalledTimes(3); + expect(row.recovery.providerImport.completed).toEqual(["db", "app", "worker"]); + }); + it("does not start a cross-project consumer if its private connection fails", async () => { + const db = service("db", "database"), + app = service("app", "app"), + worker = service("worker", "worker"); + for (const entry of [app, worker]) + Object.assign(entry.create, { gitOwner: "owner", gitRepo: entry.source.id }); + app.bindings = [{ sourceId: "db", envKey: "DB_URL" }]; + const plan = { ...planFor([app, db, worker]), sourceControl: "railway-project" as const }; + row.recovery.providerImport.planEnc = JSON.stringify(plan); + h.connect.mockRejectedValue(new Error("Private network unavailable")); + await expect(executePlatformImport(ctx, "run", plan, lifecycle())).rejects.toThrow( + "Private network unavailable", + ); + expect(h.deploy).toHaveBeenCalledTimes(1); + expect(row.recovery.providerImport.completed).toEqual([]); + expect(h.restoreSource).not.toHaveBeenCalledWith("run", true, expect.anything()); + await pauseFailedPlatformImport("run"); + expect(h.disable).toHaveBeenCalledExactlyOnceWith( + "imported-project-db", + "org", + "imported-project-db-build-1", + ); + expect(h.restoreSource).toHaveBeenLastCalledWith("run", true); + expect(h.disable.mock.invocationCallOrder[0]).toBeLessThan( + h.restoreSource.mock.invocationCallOrder[1], + ); + }); it("stages custom domains through native migration routing before pausing the source", async () => { const web = service("web", "app"); web.create.name = "storefront"; @@ -299,7 +396,8 @@ describe("provider import through normal project operations", () => { const services = [service("db", "database"), service("app", "app")]; services.forEach((service) => (service.transfer = "cold-volume")); const plan = { ...planFor(services), sourceControl: "railway-project" as const }; - plan.project.name = name; + plan.projectName = name; + plan.projects[0].create.name = name; await executePlatformImport(ctx, name, plan, lifecycle()); expect(new Set(Object.values(row.recovery.providerImport.projects))).toEqual(new Set([name])); } @@ -379,9 +477,9 @@ describe("provider import through normal project operations", () => { }), ); }); - it("rejects reviews from the old per-service-project flow before allocating a destination", async () => { + it("rejects reviews without destination projects before allocating a destination", async () => { const plan = planFor([service("app", "app")]); - delete (plan as Partial).project; + delete (plan as Partial).projects; await expect(executePlatformImport(ctx, "run", plan, lifecycle())).rejects.toMatchObject({ code: "IMPORT_REVIEW_EXPIRED", }); @@ -447,7 +545,7 @@ describe("provider import through normal project operations", () => { "deploy:imported-project:3", "healthy:imported-project-build-2", ]); - expect(h.ensure).toHaveBeenCalledExactlyOnceWith(plan.project, "org", ctx, { + expect(h.ensure).toHaveBeenCalledExactlyOnceWith(plan.projects[0].create, "org", ctx, { mustCreate: true, }); expect(h.merge).toHaveBeenCalledWith( diff --git a/apps/api/src/modules/migration/railway-wiring.test.ts b/apps/api/src/modules/migration/railway-wiring.test.ts index b7b45588a..d21c42e47 100644 --- a/apps/api/src/modules/migration/railway-wiring.test.ts +++ b/apps/api/src/modules/migration/railway-wiring.test.ts @@ -42,6 +42,27 @@ describe("provider-independent connection values", () => { }); }); describe("Railway project wiring", () => { + it("preserves self references and repeated case-insensitive dependency hosts in one connection", () => { + const db = service("db", {}, 5432); + const app = service("app", { + HOSTS: "DB.railway.internal,db.railway.internal,app.railway.internal", + }); + expect( + resolveRailwayBindings( + app, + new Map([ + ["db", db], + ["app", app], + ]), + ), + ).toEqual([ + { + sourceId: "db", + envKey: "HOSTS", + valueTemplate: "${host},${host},import-app", + }, + ]); + }); it("binds any private service without inferring its type from its image or variable names", () => { const store = service("store"); const app = service("app", { @@ -58,6 +79,7 @@ describe("Railway project wiring", () => { { sourceId: "store", envKey: "ARBITRARY_SETTING", + valueTemplate: "custom://alice:password@${host}:7878/second-db?option=1", }, ]); expect(store.source.port).toBe(7878); diff --git a/apps/api/src/modules/projects/project-clone.test.ts b/apps/api/src/modules/projects/project-clone.test.ts index 497aa8279..864a94be8 100644 --- a/apps/api/src/modules/projects/project-clone.test.ts +++ b/apps/api/src/modules/projects/project-clone.test.ts @@ -32,8 +32,7 @@ const h = { deletedAt: null, deletionInProgress: false, lifecycleOperation: { kind: "delete", status: "failed", error: "Previous cleanup failure" }, - favicon: "https://clincai.example/favicon.ico", - faviconCheckedAt: new Date(), + iconUrl: "https://clincai.example/icon.png", compositeRoutes: [{ host: "clincai.example" }], workspaceId: null, gitProvider: "github", @@ -194,6 +193,7 @@ describe("the copy direction is COPY-by-default", () => { await clone(); const p = clonedProject(); expect(p.framework).toBe("nextjs"); + expect(p.iconUrl).toBe("https://clincai.example/icon.png"); expect(p.routeStrategy).toBe("loopback"); expect(p.rollbackWindow).toBe(5); // Same for the service rows: a build command exists in no container. @@ -231,7 +231,7 @@ describe("what it deliberately does NOT copy", () => { const p = clonedProject(); // `id`/`groupId` are the insert's, and name/slug/serverId/workspaceId/activeDeploymentId are set // explicitly above — the rest must simply be absent. - for (const field of ["deletedAt", "deletionInProgress", "lifecycleOperation", "disabledAt", "favicon", "faviconCheckedAt", "compositeRoutes", "cloudPromotion", "id", "groupId", "createdAt", "updatedAt"]) { + for (const field of ["deletedAt", "deletionInProgress", "lifecycleOperation", "disabledAt", "compositeRoutes", "cloudPromotion", "id", "groupId", "createdAt", "updatedAt"]) { expect(p, field).not.toHaveProperty(field); } }); diff --git a/apps/api/test/e2e/platform-import-project.e2e.test.ts b/apps/api/test/e2e/platform-import-project.e2e.test.ts index a486e13c3..b8de6a4ca 100644 --- a/apps/api/test/e2e/platform-import-project.e2e.test.ts +++ b/apps/api/test/e2e/platform-import-project.e2e.test.ts @@ -3,6 +3,9 @@ import { randomUUID } from "node:crypto"; import { spawn } from "node:child_process"; import { createConnection } from "node:net"; import { once } from "node:events"; +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { BuildLogger, CommandSourceBackupExecutor, @@ -20,8 +23,14 @@ import { deployComposeServices } from "@repo/platform/engine/modules/deployments import { projectServicesToDeployableServices } from "@repo/platform/engine/modules/deployments/compose/project-services"; import { seedDeployment, seedOrg, setActive } from "../helpers/seed"; import { describeDockerE2E, requireDocker, dockerSocketPath } from "../helpers/docker-e2e"; +import { refreshConnectionEnv } from "@repo/platform/engine/modules/projects/project-connection.service"; +import { + sharedServiceAlias, + sharedServiceNetwork, +} from "@repo/platform/engine/modules/projects/shared-service-network"; -// Substitute Railway's control/SSH boundary and the asynchronous build queue. +// Substitute Railway's control/SSH boundary, Git checkout, destination resolution +// and the asynchronous build queue. All runtime operations use an isolated daemon. // Review, project creation, encrypted environments, migration checkpoints, // volume transfer and the ordinary Compose deployment engine remain real. const h = vi.hoisted(() => ({ @@ -50,9 +59,18 @@ vi.mock("@repo/platform/engine/modules/migration/migration-runtime", async (orig ...(await original()), createMigrationDockerRuntime: h.runtime, })); +vi.mock("@repo/platform/engine/modules/services/service-container", async (original) => ({ + ...(await original()), + // Resolve private-link operations onto the same isolated daemon as the import. + // Connection authorization, persistence, DNS and network attachment stay real. + resolveServicePlatform: async () => ({ platform: { runtime: await h.runtime() } }), +})); vi.mock("@repo/platform/engine/modules/deployments/build.service", () => ({ triggerDeployment: h.deploy, })); +vi.mock("@repo/platform/engine/modules/deployments/project-reader", () => ({ + createGitHubReader: () => ({ readText: async () => "FROM redis:7-alpine\n" }), +})); import { discoverPlatform, reviewPlatform, @@ -64,6 +82,8 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { const tag = `import-groups-${randomUUID().slice(0, 8)}`; const containers = new Set(); const volumes = new Set(); + const images = new Set(); + const sharedNetworks = new Set(); const projects: Array<{ id: string; slug: string }> = []; const sources = new Map(); let runtime: DockerRuntime; @@ -107,11 +127,13 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { await container.remove({ force: true }); } for (const project of projects) await runtime.removeNetwork(project.slug); + for (const name of sharedNetworks) await runtime.docker.getNetwork(name).remove(); for (const volume of (await runtime.docker.listVolumes()).Volumes ?? []) { if (projects.some((project) => volume.Labels?.["openship.project"] === project.id)) volumes.add(volume.Name); } for (const name of volumes) await runtime.docker.getVolume(name).remove(); + for (const image of images) await runtime.removeImage(image); await runtime.dispose(); vi.restoreAllMocks(); }); @@ -128,9 +150,14 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { return container.id; } - it.each(["socket", "cloud"] as const)( - "imports two three-service projects through %s, isolating DNS, env and persisted data", - async (transport) => { + it.each([ + { transport: "socket", split: false }, + { transport: "cloud", split: false }, + { transport: "socket", split: true }, + { transport: "cloud", split: true }, + ] as const)( + "imports through $transport (multiple repositories: $split), isolating DNS, env and persisted data", + async ({ transport, split }) => { const owner = await seedOrg({ ownsHost: true }); const ctx = { ...owner, @@ -138,7 +165,7 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { user: { id: owner.userId, name: "Test", email: "test@example.test" }, sessionKind: "cookie", } as ExecutionContext; - const serverId = `${tag}-${transport}`; + const serverId = `${tag}-${transport}-${split}`; await db.insert(schema.servers).values({ id: serverId, organizationId: owner.organizationId, @@ -211,6 +238,40 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { await repos.project.update(input.projectId, { routeStrategy: "container-ip" }); const project = (await repos.project.findById(input.projectId))!; const services = await repos.service.listByProject(project.id); + await refreshConnectionEnv(ctx, project.id); + const preparedLocalImages = new Map(); + const builtImages = new Map(); + for (const service of services) { + if (service.image) preparedLocalImages.set(service.id, service.image); + else { + // Stand in for the immutable Git checkout with a distinct build per + // repository/revision. The image build and deployment stay real. + const directory = await mkdtemp(join(tmpdir(), "openship-import-build-")); + const image = `${tag}:${service.id}`; + images.add(image); + try { + await writeFile( + join(directory, "Dockerfile"), + `FROM redis:7-alpine\nRUN echo '${project.gitRepo}:${input.commitSha}' > /source-revision\n`, + ); + const stream = await runtime.docker.buildImage( + { context: directory, src: ["Dockerfile"] }, + { t: image, networkmode: "none", labels: { "openship.project": project.id } }, + ); + await new Promise((resolve, reject) => + runtime.docker.modem.followProgress(stream, (error, output) => { + const failure = output?.find((event: { error?: string }) => event.error)?.error; + if (error || failure) reject(error ?? new Error(failure)); + else resolve(); + }), + ); + preparedLocalImages.set(service.id, image); + builtImages.set(service.id, image); + } finally { + await rm(directory, { recursive: true, force: true }); + } + } + } const deployment = await seedDeployment(project, { status: "deploying", trigger: "manual", @@ -253,7 +314,8 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { { executor: null, localHost: false, - preparedLocalImages: new Map(services.map((s) => [s.id, s.image!])), + preparedLocalImages, + builtImages, targetServiceIds: new Set(input.serviceIds), }, ); @@ -269,7 +331,7 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { const imported: Array<{ id: string; marker: string }> = []; for (const projectNumber of [1, 2]) { - const marker = `${tag}-${transport}-${projectNumber}`; + const marker = `${tag}-${transport}-${split}-${projectNumber}`; const services: ProviderInventory["services"] = []; for (const name of ["db", "cache"]) { const id = `${marker}-${name}`; @@ -332,6 +394,19 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { startCommand: "sh -c 'while true; do printf \"HTTP/1.1 200 OK\\r\\nContent-Length: 6\\r\\nConnection: close\\r\\n\\r\\nready\\n\" | nc -l -p 8080; done'", }); + if (split) { + // Two distinct Git sources plus one image-backed database. All volumes + // must move before either destination Git service is allowed to start. + for (const name of ["cache", "worker"]) { + const source = services.find((service) => service.name === name)!; + source.image = undefined; + source.repository = `fixture/${name}`; + source.commit = (name === "cache" ? "a" : "b").repeat(40); + source.branch = "main"; + source.dockerfile = "Dockerfile"; + } + delete services.find((service) => service.name === "worker")!.env.BOTH_HOSTS; + } const inventory: ProviderInventory = { provider: "railway", source: { connectionId: "fixture", projectId: marker, environmentId: "production" }, @@ -379,21 +454,26 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { }); } finally { const saved = await repos.project.listByOrganization(owner.organizationId); - for (const p of saved.rows) + for (const p of saved.rows) { if (!projects.some((known) => known.id === p.id)) projects.push(p); + for (const link of await repos.projectConnection.listByTarget(p.id)) + if (link.sourceServiceId) + sharedNetworks.add(sharedServiceNetwork(link.sourceServiceId)); + } } const checkpoint = (await repos.dockerMigrationRun.findById(runId))!.recovery .providerImport!; const ids = [...new Set(Object.values(checkpoint.projects))]; - expect(ids).toHaveLength(1); - const id = ids[0]; - expect(await repos.service.listByProject(id)).toHaveLength(3); + expect(ids).toHaveLength(split ? 3 : 1); expect(checkpoint.completed).toHaveLength(3); expect((await repos.project.listByOrganization(owner.organizationId)).total).toBe( - projectNumber, + projectNumber * (split ? 3 : 1), ); - expect(await repos.project.getEnvMap(id, "production", null)).toEqual({}); - imported.push({ id, marker }); + for (const id of ids) { + expect(await repos.service.listByProject(id)).toHaveLength(split ? 1 : 3); + if (!split) expect(await repos.project.getEnvMap(id, "production", null)).toEqual({}); + imported.push({ id, marker }); + } } // Check both projects AFTER the second import: duplicate service names @@ -407,6 +487,12 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { expect(env.SERVICE_SECRET).toBe(`${marker}-${service.name}`); const container = deployed.find((r) => r.serviceId === service.id)!.containerId!; expect(await exec(container, 'printf %s "$SERVICE_SECRET"')).toBe(env.SERVICE_SECRET); + if (split && project.gitRepo) { + const revision = (service.name === "cache" ? "a" : "b").repeat(40); + expect(await exec(container, "cat /source-revision")).toBe( + `${project.gitRepo}:${revision}`, + ); + } if (service.name === "worker") { expect(service.exposed).toBe(true); expect(service.publicEndpoints).toEqual([ @@ -423,13 +509,50 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { ), ).toBe(true); expect(await exec(container, "wget -qO- http://127.0.0.1:8080")).toBe("ready"); - expect(await exec(container, 'printf %s "$BOTH_HOSTS"')).toBe("db,cache"); + if (!split) expect(await exec(container, 'printf %s "$BOTH_HOSTS"')).toBe("db,cache"); + else { + const links = await repos.projectConnection.listByTarget(id); + expect(links).toHaveLength(2); + expect( + links.every( + (link) => + link.organizationId === owner.organizationId && + link.mode === "internal" && + link.usesPrivateNetwork, + ), + ).toBe(true); + for (const link of links) { + expect(env[link.envKey]).toBeUndefined(); // Service env must not shadow its native link. + expect(await exec(container, `printenv ${link.envKey}`)).toBe( + sharedServiceAlias(link.sourceServiceId!), + ); + } + } expect(await exec(container, 'redis-cli -h "$PRIMARY_HOST" GET marker')).toBe( `${marker}-db`, ); expect(await exec(container, 'redis-cli -h "$CACHE_HOST" GET marker')).toBe( `${marker}-cache`, ); + if (split) { + // An ordinary later deployment refreshes the same saved links and + // rejoins the private networks without the import worker involved. + await h.deploy(ctx, { + projectId: id, + serviceIds: [service.id], + commitSha: "b".repeat(40), + }); + const current = (await repos.project.findById(id))!; + const next = (await repos.service.listByDeployment(current.activeDeploymentId!)).find( + (row) => row.serviceId === service.id, + )!; + expect(await exec(next.containerId!, 'redis-cli -h "$PRIMARY_HOST" GET marker')).toBe( + `${marker}-db`, + ); + expect(await exec(next.containerId!, 'redis-cli -h "$CACHE_HOST" GET marker')).toBe( + `${marker}-cache`, + ); + } } else { expect(await exec(container, "redis-cli GET marker")).toBe(`${marker}-${service.name}`); await exec(container, "redis-cli SET new-write survives"); diff --git a/apps/api/test/lib/profile-avatar.test.ts b/apps/api/test/lib/profile-avatar.test.ts new file mode 100644 index 000000000..31d4e4604 --- /dev/null +++ b/apps/api/test/lib/profile-avatar.test.ts @@ -0,0 +1,55 @@ +import { expect, it } from "vitest"; +import { auth } from "@repo/platform/engine/lib/auth"; +import { provisionUser } from "@repo/platform/engine/lib/provision-user"; +import { mintSession } from "../../src/lib/cloud-auth-proxy"; +import { db, schema, eq } from "@repo/db"; +import { randomUUID } from "node:crypto"; + +it("updates only the signed-in user's avatar through the existing auth endpoint and rejects unsafe URLs", async () => { + const id = randomUUID(); + await provisionUser({ + id, + email: `${id}@example.test`, + name: "Avatar owner", + emailVerified: true, + }); + const session = await mintSession({ purpose: "local-cookie", userId: id }); + const update = (image: unknown, token: string | null = session.token, extra = {}) => + auth.handler( + new Request("http://localhost:4000/api/auth/update-user", { + method: "POST", + headers: { + "Content-Type": "application/json", + ...(token ? { Authorization: `Bearer ${token}` } : {}), + }, + body: JSON.stringify({ image, ...extra }), + }), + ); + expect((await update("https://cdn.example.test/avatar.png", null)).status).toBe(401); + const result = await update("https://cdn.example.test/avatar.png"); + expect(result.status, await result.clone().text()).toBe(200); + expect(await db.query.user.findFirst({ where: eq(schema.user.id, id) })).toMatchObject({ + image: "https://cdn.example.test/avatar.png", + role: "user", + }); + expect( + await auth.api.getSession({ + headers: new Headers({ Authorization: `Bearer ${session.token}` }), + }), + ).toMatchObject({ user: { image: "https://cdn.example.test/avatar.png" } }); + expect( + (await update("https://cdn.example.test/avatar.png", session.token, { role: "admin" })).status, + ).toBe(400); + for (const image of [ + "javascript:alert(1)", + "data:image/svg+xml,", + "https://user:secret@example.test/a.png", + "/avatar.png", + 123, + ]) + expect((await update(image)).status).toBe(400); + expect((await update(null)).status).toBe(200); + expect(await db.query.user.findFirst({ where: eq(schema.user.id, id) })).toMatchObject({ + image: null, + }); +}); diff --git a/apps/api/test/modules/deployments/build-duration.test.ts b/apps/api/test/modules/deployments/build-duration.test.ts index 026f4db36..8d1e2cecb 100644 --- a/apps/api/test/modules/deployments/build-duration.test.ts +++ b/apps/api/test/modules/deployments/build-duration.test.ts @@ -13,7 +13,6 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: vi.fn() }, })); vi.mock("@repo/platform/engine/lib/audit-emitter", () => ({ audit: { recordAsync: vi.fn() } })); -vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn() })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(), })); diff --git a/apps/api/test/modules/deployments/compose-noop-settle.test.ts b/apps/api/test/modules/deployments/compose-noop-settle.test.ts index 100da4d26..7a522fa77 100644 --- a/apps/api/test/modules/deployments/compose-noop-settle.test.ts +++ b/apps/api/test/modules/deployments/compose-noop-settle.test.ts @@ -94,7 +94,6 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ vi.mock("../../../src/lib/audit", () => ({ audit: { recordAsync: (_c: unknown, e: { eventType: string }) => h.audits.push(e.eventType) }, })); -vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: async () => {} })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: async () => {}, })); diff --git a/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts b/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts index e847bd792..52ffd3b75 100644 --- a/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts +++ b/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts @@ -113,7 +113,6 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ }, })); vi.mock("../../../src/lib/audit", () => ({ audit: { recordAsync: () => {} } })); -vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: async () => {} })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: async () => {}, })); diff --git a/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts b/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts index 3fd2f63b7..ee521b560 100644 --- a/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts +++ b/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts @@ -13,7 +13,6 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: vi.fn() }, })); vi.mock("@repo/platform/engine/lib/audit-emitter", () => ({ audit: { recordAsync: vi.fn() } })); -vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn() })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(), })); diff --git a/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts b/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts index 5ab30154e..5d07a4e0f 100644 --- a/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts +++ b/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts @@ -32,9 +32,6 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: vi.fn() }, })); vi.mock("../../../src/lib/audit", () => ({ audit: { recordAsync: vi.fn(), record: vi.fn() } })); -vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ - detectAndStoreFavicon: vi.fn(async () => {}), -})); vi.mock("@repo/platform/engine/modules/projects/cleanup-keep-set", () => ({ computeCleanupKeepSet: vi.fn(async () => ({ containers: new Set() })), })); diff --git a/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts b/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts index a6858b068..10a53e784 100644 --- a/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts +++ b/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts @@ -465,8 +465,9 @@ describe("project promotion recovery", () => { const dump = await dumpSubgraph({ kind: "project", projectId }); const changed = structuredClone(dump); changed.tables.resource_usage.push({ id: "another-sample", projectId, cpu: 42 }); - changed.tables.project[0].favicon = "new favicon"; expect(projectPromotionDigest(changed)).toBe(projectPromotionDigest(dump)); + changed.tables.project[0].iconUrl = "https://cdn.example.test/new-icon.png"; + expect(projectPromotionDigest(changed)).not.toBe(projectPromotionDigest(dump)); changed.tables.project[0].localPath = "/another-source"; expect(projectPromotionDigest(changed)).not.toBe(projectPromotionDigest(dump)); }); diff --git a/apps/api/test/modules/projects/project-icon.test.ts b/apps/api/test/modules/projects/project-icon.test.ts new file mode 100644 index 000000000..4cbd56c71 --- /dev/null +++ b/apps/api/test/modules/projects/project-icon.test.ts @@ -0,0 +1,58 @@ +import "../jobs/_env"; +import { expect, it } from "vitest"; +import { Hono } from "hono"; +import { seedOwner, repos } from "../jobs/_harness"; +import { seedProject, seedDeployment } from "../../helpers/seed"; +import { listDeployments } from "@repo/platform/engine/modules/deployments/deployment.service"; +import { projectRoutes } from "../../../src/modules/projects/project.routes"; +import { handleApiError } from "../../../src/middleware/error-handler"; + +const app = new Hono().onError(handleApiError).route("/api/projects", projectRoutes); + +it("uses one icon URL across authenticated settings, reads and deployment history", async () => { + const owner = await seedOwner(); + const project = await seedProject(owner.orgId); + const custom = "https://cdn.example.test/project.svg"; + const update = (iconUrl: unknown, auth = owner.auth) => + app.request(`/api/projects/${project.id}`, { + method: "PATCH", + headers: { ...auth, "Content-Type": "application/json" }, + body: JSON.stringify({ iconUrl }), + }); + const assertIcon = (data: unknown, expected: string | null) => { + expect(data).toMatchObject({ iconUrl: expected }); + expect(data).not.toHaveProperty("favicon"); + expect(data).not.toHaveProperty("faviconCheckedAt"); + }; + const saved = await update(` ${custom} `); + expect(saved.status, await saved.clone().text()).toBe(200); + assertIcon((await saved.json()).data, custom); + assertIcon(await repos.project.findById(project.id), custom); + const read = await app.request(`/api/projects/${project.id}`, { headers: owner.auth }); + expect(read.status, await read.clone().text()).toBe(200); + assertIcon((await read.json()).data, custom); + await seedDeployment(project); + for (const options of [{ projectId: project.id }, {}]) { + const history = await listDeployments(owner.orgId, options); + assertIcon(history.rows[0], custom); + } + const stranger = await seedOwner(); + expect((await update("https://stranger.example.test/icon.png", stranger.auth)).status).toBe(404); + for (const unsafe of [ + "javascript:alert(1)", + "data:image/png;base64,AAA", + "https://user:password@example.test/i.png", + "/relative.png", + ]) + expect((await update(unsafe)).status).toBe(400); + assertIcon(await repos.project.findById(project.id), custom); + for (const reset of [null, ""]) { + expect((await update(custom)).status).toBe(200); + const cleared = await update(reset); + expect(cleared.status).toBe(200); + assertIcon((await cleared.json()).data, null); + assertIcon(await repos.project.findById(project.id), null); + const history = await listDeployments(owner.orgId, { projectId: project.id }); + assertIcon(history.rows[0], null); + } +}); diff --git a/apps/api/test/modules/projects/project-overview-logs.test.ts b/apps/api/test/modules/projects/project-overview-logs.test.ts index a716386d1..555e7ddf9 100644 --- a/apps/api/test/modules/projects/project-overview-logs.test.ts +++ b/apps/api/test/modules/projects/project-overview-logs.test.ts @@ -19,7 +19,6 @@ vi.mock("@repo/db", () => ({ repos: { vi.mock("@repo/platform/engine/modules/projects/project.service", () => ({ listProjects: h.list, enrichProjectsBatch: h.enrich, deploymentIsBlocked: () => false })); vi.mock("@repo/platform/engine/lib/authorization", () => ({ authorization: { checkPermissionOnResource: h.canRead, authorize: async (ctx: ExecutionContext) => ctx } })); vi.mock("@repo/platform/engine/lib/cloud/projects", () => ({ fetchOrgCloudProjects: h.cloudProjects })); -vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ refreshProjectFaviconIfStale: vi.fn() })); vi.mock("@repo/platform/engine/config/index", () => ({ env: h.env })); vi.mock("@repo/platform/engine/lib/oblien-user-client", () => ({ getAdminOblienClient: () => h.env.CLOUD_MODE ? { analytics: { streamToken: h.streamToken, requests: h.requests } } : null })); vi.mock("@repo/platform/engine/lib/cloud/client", () => ({ cloudClient: () => ({ analytics: { streamToken: h.streamToken, requests: h.requests } }) })); diff --git a/apps/api/test/modules/projects/shared-service-connections.test.ts b/apps/api/test/modules/projects/shared-service-connections.test.ts index fc4d00f0b..1df8a5fb8 100644 --- a/apps/api/test/modules/projects/shared-service-connections.test.ts +++ b/apps/api/test/modules/projects/shared-service-connections.test.ts @@ -66,9 +66,10 @@ beforeEach(() => { describe("connections to a service inside a project", () => { it("offers all eligible projects while excluding the current project and read-only access", async () => { - h.candidates = ["source", "read-only", ...Array.from({ length: 120 }, (_, i) => `consumer-${i}`)].map(id => ({ id, name: id, environmentName: "production", appTemplateId: null })); + h.candidates = ["source", "read-only", ...Array.from({ length: 120 }, (_, i) => `consumer-${i}`)].map(id => ({ id, name: id, environmentName: "production", appTemplateId: null, iconUrl: "https://cdn.example.test/icon.svg", framework: "nextjs" })); const choices = await listConnectionCandidates(ctx, "source"); expect(choices).toHaveLength(120); + expect(choices[0]).toMatchObject({ iconUrl: "https://cdn.example.test/icon.svg", framework: "nextjs" }); expect(choices.some(choice => ["source", "read-only"].includes(choice.id))).toBe(false); expect(h.authorize).toHaveBeenCalledWith(ctx, { resourceType: "project", resourceId: "source", action: "write" }); }); diff --git a/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx b/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx index 138d19258..b9513fcc3 100644 --- a/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx +++ b/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx @@ -143,7 +143,7 @@ export default function DashboardHomeClient({ ) : (
{sourceProjects.slice(0, 5).map((p) => ( - removeProject(p.id)} /> + removeProject(p.id)} /> ))}
)} diff --git a/apps/dashboard/src/app/(dashboard)/apps/page.tsx b/apps/dashboard/src/app/(dashboard)/apps/page.tsx index 4ba8cd845..377e5f5f2 100644 --- a/apps/dashboard/src/app/(dashboard)/apps/page.tsx +++ b/apps/dashboard/src/app/(dashboard)/apps/page.tsx @@ -184,7 +184,7 @@ export default function AppsPage() {
{filteredApps.length > 0 ? filteredApps.map(app => ( - removeProject(app.id)} /> + removeProject(app.id)} /> )) : (

{copy.catalogNoResults}

)} diff --git a/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx b/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx index 105bd759e..92eaf168a 100644 --- a/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx +++ b/apps/dashboard/src/app/(dashboard)/deployments/components/DeploymentCard.tsx @@ -8,10 +8,8 @@ import { DeploymentMenu } from "./DeploymentMenu"; import { CommitDetailsModal } from "./CommitDetailsModal"; import type { Deployment } from "../types"; import { formatDistanceToNow, formatBuildTime, getStatusConfig } from "../utils"; -import { ProjectStackIcon } from "@/components/shared/ProjectStackIcon"; -import { AppLogo } from "@/components/AppLogo"; +import { ProjectIcon } from "@/components/shared/ProjectIcon"; import { useI18n, interpolate } from "@/components/i18n-provider"; -import { useImageFallback } from "@/hooks/useImageFallback"; type ServiceStatusLabels = { deployed: string; @@ -122,7 +120,6 @@ export const DeploymentCard: React.FC = ({ const { t } = useI18n(); const [isCommitModalOpen, setIsCommitModalOpen] = useState(false); const [isMenuOpen, setIsMenuOpen] = useState(false); - const favicon = useImageFallback(deployment.favicon); const statusConfig = getStatusConfig(deployment.status); const statusLabelMap: Record = { @@ -151,21 +148,9 @@ export const DeploymentCard: React.FC = ({ aria-label={deployment.projectName || t.deployments.card.unknownProject} className="absolute inset-0 z-0" /> - {/* App logo (catalog apps) → project favicon → framework icon → initials */} + {/* Project icon → catalog logo → framework or service icon */}
- {appTemplateId ? ( - - ) : favicon.showImage ? ( - - ) : ( - - )} +
{/* Main info */} diff --git a/apps/dashboard/src/app/(dashboard)/deployments/types.ts b/apps/dashboard/src/app/(dashboard)/deployments/types.ts index 213fb5e83..a49f53391 100644 --- a/apps/dashboard/src/app/(dashboard)/deployments/types.ts +++ b/apps/dashboard/src/app/(dashboard)/deployments/types.ts @@ -56,9 +56,8 @@ export interface Deployment { branch?: string; projectId?: string; projectName?: string; - /** Auto-detected favicon of the deployed site, cached on the project. - * When present it replaces the framework/Docker glyph as the row logo. */ - favicon?: string | null; + /** Project icon shared with project lists and settings. */ + iconUrl?: string | null; failureReason?: string; /** Rollback state — populated by the orchestrator-aware listing endpoint. * `artifactRetainedAt` non-null = artifact is archived, rollback-eligible. diff --git a/apps/dashboard/src/app/(dashboard)/deployments/utils.ts b/apps/dashboard/src/app/(dashboard)/deployments/utils.ts index f2bc27c23..711c32894 100644 --- a/apps/dashboard/src/app/(dashboard)/deployments/utils.ts +++ b/apps/dashboard/src/app/(dashboard)/deployments/utils.ts @@ -41,7 +41,7 @@ export const mapRowToDeployment = (row: any): Deployment => { branch: row.branch ?? undefined, projectId: row.projectId, projectName: row.projectName, - favicon: row.favicon ?? null, + iconUrl: row.iconUrl ?? null, failureReason: row.errorMessage ?? undefined, /* Rollback state — flows from the listing endpoint, which enriches * each row with isActive and surfaces the orchestrator-owned diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx index fa09be27a..96b71d21c 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/AdvancedSettings.tsx @@ -27,6 +27,7 @@ import { isSchemaAppTemplate } from "@/components/app-settings/AppSettingsForm"; import { AppConfiguration } from "./AppConfiguration"; import { BuildSettings } from "./BuildSettings"; import { CloudStaticHosting } from "@/components/project-settings/CloudStaticHosting"; +import { ProjectIconSetting } from "@/components/project-settings/ProjectIconSetting"; interface Props { onDeleteProject: (wipeVolumes?: boolean, recordOnly?: boolean) => void; @@ -357,6 +358,7 @@ export const AdvancedSettings = ({ onDeleteProject }: Props) => { and collided — and since this card has no `overflow-hidden` (the ⋮ menu needs to escape it), the collision spilled into the neighbouring card. */}
+
{ if (!summary.domainId || summary.isPrimary) return; diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.test.tsx index 598bfb73c..a4c904295 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.test.tsx @@ -89,6 +89,7 @@ beforeEach(() => { afterEach(async () => { await act(async () => root.unmount()); host.remove(); + vi.restoreAllMocks(); vi.unstubAllGlobals(); }); @@ -106,6 +107,21 @@ async function choose(scope: ParentNode, name: string) { await click(option!); } +it("shows the saved project icon in the connection picker", async () => { + vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(false); + h.candidates.mockResolvedValue({ + data: [{ id: "web", name: "Web app", description: "production", appTemplateId: "redis", iconUrl: "https://cdn.example.test/project.svg" }], + }); + await act(async () => root.render( + , + )); + const dialog = document.querySelector("[data-modal-surface]")!; + await click(dialog.querySelector('[aria-haspopup="listbox"]')!); + const image = document.querySelector('[role="option"] img'); + expect(image?.getAttribute("src")).toBe("https://cdn.example.test/project.svg"); + expect(image?.getAttribute("referrerpolicy")).toBe("no-referrer"); +}); + describe("connection form copy", () => { it("names the count and project, and points at the deployment status, after sharing values", async () => { h.candidates.mockResolvedValue({ diff --git a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx index 4975561d6..b0d0c3df0 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/[id]/components/UseInProjectModal.tsx @@ -5,10 +5,11 @@ import { Icon as UiIcon } from "@repo/ui/icons"; import { useEffect, useMemo, useState } from "react"; import { resolveLocalized } from "@repo/core"; +import type { ProjectConnectionCandidate } from "@repo/contracts"; import { Modal } from "@/components/ui/Modal"; import { CustomSelect } from "@/components/ui/CustomSelect"; import { Checkbox } from "@/components/ui/Checkbox"; -import { AppLogo } from "@/components/AppLogo"; +import { ProjectIcon } from "@/components/shared/ProjectIcon"; import { connectionsApi, type ConnectionMode } from "@/lib/api/connections"; import { getApiErrorMessage } from "@/lib/api/client"; import { useToast } from "@/context/ToastContext"; @@ -49,15 +50,6 @@ function InlineHint({ text }: { text: string }) { ); } -interface TargetProject { - id: string; - name: string; - description: string; - appTemplateId?: string; - favicon?: string | null; - clusterId?: string | null; -} - interface ConnectionFormProps { onClose: () => void; hideHeader?: boolean; @@ -104,7 +96,7 @@ export function ProjectConnectionForm({ (!sourceDatabaseId || output.sourceDatabaseId === sourceDatabaseId), ), [suppliedOutputs, view, sourceServiceId, sourceDatabaseId]); - const [targets, setTargets] = useState([]); + const [targets, setTargets] = useState([]); const [loadingProjects, setLoadingProjects] = useState(true); const [targetId, setTargetId] = useState(fixedTargetId ?? ""); const [mode, setMode] = useState(guide?.defaultMode ?? "internal"); @@ -164,7 +156,7 @@ export function ProjectConnectionForm({ setLoadingProjects(true); connectionsApi.candidates(fixedSourceId ?? fixedTargetId ?? "") .then(result => { - if (!cancelled) setTargets(result.data.map(project => ({ ...project, appTemplateId: project.appTemplateId ?? undefined }))); + if (!cancelled) setTargets(result.data); }) .catch(error => { if (!cancelled) setLoadError(getApiErrorMessage(error, c.failed)); }) .finally(() => { if (!cancelled) setLoadingProjects(false); }); @@ -237,7 +229,7 @@ export function ProjectConnectionForm({ label: p.name, description: p.description || undefined, icon: ( - + ), }))} onChange={fixedTargetId ? setSourceProjectId : setTargetId} diff --git a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx index f662bcf33..85e0967bb 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectCard.tsx @@ -5,8 +5,7 @@ import { Icon as UiIcon } from "@repo/ui/icons"; import React, { useState } from "react"; import Link from "next/link"; import { type Project } from "@/constants/mock"; -import { AppLogo } from "@/components/AppLogo"; -import { ProjectStackIcon } from "@/components/shared/ProjectStackIcon"; +import { ProjectIcon } from "@/components/shared/ProjectIcon"; import { getFrameworkConfig } from "@/components/import-project/Frameworks"; import { getProjectStatus, projectCardHref, projectDisplayDomain } from "@/utils/project-status"; import { ProjectStatusBadge } from "@/components/shared/ProjectStatusBadge"; @@ -15,7 +14,6 @@ import { useModal } from "@/context/ModalContext"; import { useToast } from "@/context/ToastContext"; import { projectsApi, getApiErrorMessage } from "@/lib/api"; import { timeAgo } from "@/lib/time"; -import { useImageFallback } from "@/hooks/useImageFallback"; import type { Dictionary } from "@/i18n"; /* ── Helpers ──────────────────────────────────────────────────────── */ @@ -50,9 +48,6 @@ interface Props { * every row by the projects list and `/info`, but isn't declared on `Project` * (constants/mock) yet, so it's spelled out here rather than cast away. */ project: Project & { primaryDomain?: string | null }; - /** On the Apps page: show the catalog app's brand logo instead of the - * framework/service fallback icon. */ - preferAppLogo?: boolean; /** Show an "update available" badge (fed by the update scan). Off by default * so the Projects page is unaffected. */ updateAvailable?: boolean; @@ -61,14 +56,13 @@ interface Props { onChanged?: () => void; } -const ProjectCard: React.FC = ({ project, preferAppLogo, updateAvailable, onChanged }) => { +const ProjectCard: React.FC = ({ project, updateAvailable, onChanged }) => { const { t } = useI18n(); const { showModal, hideModal } = useModal(); const { showToast } = useToast(); const [menuOpen, setMenuOpen] = useState(false); const status = getProjectStatus(project); const fw = getFrameworkConfig(project.framework); - const favicon = useImageFallback(project.favicon); const isLocal = !!project.localPath; const hasRepo = !!(project.gitOwner && project.gitRepo); @@ -118,22 +112,8 @@ const ProjectCard: React.FC = ({ project, preferAppLogo, updateAvailable,
- {/* Icon — on the Apps page show the catalog app's brand logo; otherwise - the project favicon, falling back to the framework/service glyph. */}
- {preferAppLogo && project.isApp ? ( - - ) : favicon.showImage ? ( - - ) : ( - - )} +
{/* Name + domain */} diff --git a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx index 66f51f1f7..f1aaa56c9 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/components/ProjectGridCard.tsx @@ -6,14 +6,12 @@ import Link from "next/link"; import { useRouter } from "next/navigation"; import DropdownMenu from "@/components/ui/DropdownMenu"; import { type Project } from "@/constants/mock"; -import { AppLogo } from "@/components/AppLogo"; -import { ProjectStackIcon } from "@/components/shared/ProjectStackIcon"; +import { ProjectIcon } from "@/components/shared/ProjectIcon"; import { getProjectStatus, projectCardHref, projectDisplayDomain } from "@/utils/project-status"; import { ProjectStatusBadge } from "@/components/shared/ProjectStatusBadge"; import { ServiceStatusIndicator } from "@/components/services/ServiceStatusBadge"; import { useI18n, interpolate } from "@/components/i18n-provider"; import { timeAgo } from "@/lib/time"; -import { useImageFallback } from "@/hooks/useImageFallback"; import { getHostingLabel } from "./ProjectCard"; /** Compact project summary with direct links to its management screens. */ @@ -22,12 +20,10 @@ const ProjectGridCard: React.FC<{ * every row by the projects list and `/info`, but isn't declared on `Project` * (constants/mock) yet, so it's spelled out here rather than cast away. */ project: Project & { primaryDomain?: string | null }; - preferAppLogo?: boolean; updateAvailable?: boolean; -}> = ({ project, preferAppLogo, updateAvailable }) => { +}> = ({ project, updateAvailable }) => { const { t } = useI18n(); const router = useRouter(); - const favicon = useImageFallback(project.favicon); const domain = projectDisplayDomain(project); const hosting = getHostingLabel(project.deployTarget, project.serverName, t); @@ -65,20 +61,7 @@ const ProjectGridCard: React.FC<{
- {preferAppLogo && project.isApp ? ( - - ) : favicon.showImage ? ( - // eslint-disable-next-line @next/next/no-img-element - - ) : ( - - )} +
diff --git a/apps/dashboard/src/app/(dashboard)/projects/components/project-favicon.test.tsx b/apps/dashboard/src/app/(dashboard)/projects/components/project-icon.test.tsx similarity index 67% rename from apps/dashboard/src/app/(dashboard)/projects/components/project-favicon.test.tsx rename to apps/dashboard/src/app/(dashboard)/projects/components/project-icon.test.tsx index 2165098d3..e2482db84 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/components/project-favicon.test.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/components/project-icon.test.tsx @@ -39,10 +39,35 @@ afterEach(async () => { }); for (const [name, Card] of [["list", ProjectCard], ["grid", ProjectGridCard]] as const) { - const render = (favicon = "/favicon-old.ico") => ( - + const render = (iconUrl = "/icon-old.png") => ( + ); - describe(`${name} favicon`, () => { + describe(`${name} iconUrl`, () => { + it("uses a custom icon before the catalog logo on the Apps page", async () => { + complete = false; + root = createRoot(container); + await act(async () => root!.render( + , + )); + expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("https://cdn.example.test/custom.png"); + }); + + it("uses the same catalog fallback when a custom icon fails or is cleared", async () => { + complete = false; + root = createRoot(container); + const custom = "https://cdn.example.test/custom.png"; + const view = (iconUrl: string | null) => ( + + ); + await act(async () => root!.render(view(custom))); + await act(async () => container.querySelector('img[alt=""]')!.dispatchEvent(new Event("error"))); + const fallback = container.querySelector('img[alt=""]')?.getAttribute("src"); + expect(fallback).toBeTruthy(); + expect(fallback).not.toBe(custom); + await act(async () => root!.render(view(null))); + expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe(fallback); + }); + it("falls back when the image failed before hydration attached its error listener", async () => { const view = render(); container.innerHTML = renderToString(view); @@ -59,16 +84,16 @@ for (const [name, Card] of [["list", ProjectCard], ["grid", ProjectGridCard]] as await act(async () => root!.render(render())); await act(async () => container.querySelector('img[alt=""]')!.dispatchEvent(new Event("error"))); expect(container.querySelector('img[alt=""]')).toBeNull(); - await act(async () => root!.render(render("/favicon-new.ico"))); - expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/favicon-new.ico"); + await act(async () => root!.render(render("/icon-new.png"))); + expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/icon-new.png"); }); - it("keeps a successfully cached favicon", async () => { + it("keeps an image that loaded before hydration", async () => { naturalWidth = 32; const view = render(); container.innerHTML = renderToString(view); await act(async () => { root = hydrateRoot(container, view); }); - expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/favicon-old.ico"); + expect(container.querySelector('img[alt=""]')?.getAttribute("src")).toBe("/icon-old.png"); }); }); } diff --git a/apps/dashboard/src/app/(dashboard)/projects/page.tsx b/apps/dashboard/src/app/(dashboard)/projects/page.tsx index c692c689e..46aab35f3 100644 --- a/apps/dashboard/src/app/(dashboard)/projects/page.tsx +++ b/apps/dashboard/src/app/(dashboard)/projects/page.tsx @@ -109,11 +109,11 @@ export default function ProjectsPage() { ) : filtered.length > 0 ? ( view === "grid" ? (
- {filtered.map(project => )} + {filtered.map(project => )}
) : (
- {filtered.map(project => removeProject(project.id)} />)} + {filtered.map(project => removeProject(project.id)} />)}
) ) : ( diff --git a/apps/dashboard/src/app/(dashboard)/settings/_components/ProfileSetting.tsx b/apps/dashboard/src/app/(dashboard)/settings/_components/ProfileSetting.tsx new file mode 100644 index 000000000..12a7600f9 --- /dev/null +++ b/apps/dashboard/src/app/(dashboard)/settings/_components/ProfileSetting.tsx @@ -0,0 +1,29 @@ +"use client"; + +import { useAuth } from "@/context/AuthContext"; +import { authClient } from "@/lib/auth-client"; +import { useI18n } from "@/components/i18n-provider"; +import { ImageUrlEditor } from "@/components/settings/ImageUrlEditor"; +import { SettingsSection } from "./SettingsSection"; + +export function ProfileSetting() { + const { user } = useAuth(); + const { t } = useI18n(); + const c = t.settings.profile; + if (!user) return null; + return ( + + { + const result = await authClient.updateUser({ image }); + if (result.error) throw new Error(result.error.message || t.settings.imageUrl.failed); + }} + /> + + ); +} diff --git a/apps/dashboard/src/app/(dashboard)/settings/page.tsx b/apps/dashboard/src/app/(dashboard)/settings/page.tsx index 2e4e5cea0..6b63ae685 100644 --- a/apps/dashboard/src/app/(dashboard)/settings/page.tsx +++ b/apps/dashboard/src/app/(dashboard)/settings/page.tsx @@ -32,6 +32,7 @@ import { useI18n } from "@/components/i18n-provider"; import { BuildPreferences } from "./_components/BuildPreferences"; import { AppearanceSetting } from "./_components/AppearanceSetting"; +import { ProfileSetting } from "./_components/ProfileSetting"; import { AppearanceEditor } from "@/components/appearance/AppearanceEditor"; import { RoutePreferences } from "./_components/RoutePreferences"; import { DeployDefaults } from "./_components/DeployDefaults"; @@ -144,6 +145,7 @@ function SettingsPageInner() {
{activeTab === "general" && !customizeAppearance && ( <> + {/* Deploy Defaults + Routing hidden for now — advanced/rarely-needed, reduces general-settings noise. The edge defaults to loopback-port diff --git a/apps/dashboard/src/components/migration/PlatformImportReview.tsx b/apps/dashboard/src/components/migration/PlatformImportReview.tsx index f450af8bb..22c607f61 100644 --- a/apps/dashboard/src/components/migration/PlatformImportReview.tsx +++ b/apps/dashboard/src/components/migration/PlatformImportReview.tsx @@ -37,6 +37,7 @@ export function PlatformImportReview({ onStart: () => void; }) { const imports = plan.services.filter((s) => choices[s.id]?.data !== "external"); + const projectCount = plan.projects?.length ?? 1; return (
@@ -86,6 +87,15 @@ export function PlatformImportReview({

{importDataLabel(service, choice)}

+ {projectCount > 1 && ( +

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

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

Review complete

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

+ {projectCount > 1 && ( +

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

+ )}

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

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

+ } + onSave={async (iconUrl) => { + const response = await projectsApi.update(projectData.id, { iconUrl }); + updateProjectData({ iconUrl: response.data.iconUrl }); + invalidateProjectCaches(projectData.id); + }} + /> + ); +} diff --git a/apps/dashboard/src/components/settings/ImageUrlEditor.test.tsx b/apps/dashboard/src/components/settings/ImageUrlEditor.test.tsx new file mode 100644 index 000000000..a865f71f8 --- /dev/null +++ b/apps/dashboard/src/components/settings/ImageUrlEditor.test.tsx @@ -0,0 +1,102 @@ +// @vitest-environment happy-dom +import { act, useState } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { I18nProvider } from "@/components/i18n-provider"; +import { ImageUrlEditor } from "./ImageUrlEditor"; + +let host: HTMLDivElement; +let root: Root; +const save = vi.fn(); +beforeEach(() => { + vi.resetAllMocks(); + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(false); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); +}); +afterEach(async () => { + await act(async () => root.unmount()); + host.remove(); + vi.restoreAllMocks(); + vi.unstubAllGlobals(); +}); + +function Editor({ initial = null }: { initial?: string | null }) { + const [value, setValue] = useState(initial); + return ( + + { + await save(next); + setValue(next); + }} + /> + + ); +} +async function render(initial?: string) { + await act(async () => root.render()); +} +async function edit(value: string) { + await act(async () => { + const input = host.querySelector("input")!; + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); +} +async function submit() { + await act(async () => + host + .querySelector("form")! + .dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })), + ); +} + +it("previews and saves a trimmed image URL", async () => { + await render(); + await edit(" https://cdn.example.test/avatar.png "); + expect(host.querySelector("img")?.getAttribute("src")).toBe( + "https://cdn.example.test/avatar.png", + ); + expect(host.querySelector("img")?.getAttribute("referrerpolicy")).toBe("no-referrer"); + await submit(); + expect(save).toHaveBeenCalledWith("https://cdn.example.test/avatar.png"); + expect(host.querySelector('[role="status"]')?.textContent).toBe("Saved"); +}); + +it("rejects executable image schemes without loading or saving them", async () => { + await render(); + await edit("javascript:alert(1)"); + expect(host.querySelector("img")).toBeNull(); + await submit(); + expect(save).not.toHaveBeenCalled(); + expect(host.querySelector('[role="alert"]')?.textContent).toContain("HTTP or HTTPS"); +}); + +it("clears the saved override using the shared reset action", async () => { + await render("https://cdn.example.test/avatar.png"); + await act(async () => host.querySelector('button[type="button"]')!.click()); + expect(save).toHaveBeenCalledWith(null); + expect(host.querySelector("input")!.value).toBe(""); + expect(host.querySelector("img")).toBeNull(); +}); + +it("falls back for a broken image, retries a changed URL and preserves the draft on save failure", async () => { + await render("https://cdn.example.test/old.png"); + await act(async () => host.querySelector("img")!.dispatchEvent(new Event("error"))); + expect(host.querySelector("img")).toBeNull(); + await edit("https://cdn.example.test/new.png"); + expect(host.querySelector("img")?.getAttribute("src")).toBe("https://cdn.example.test/new.png"); + save.mockRejectedValueOnce(new Error("Permission denied")); + await submit(); + expect(host.querySelector("input")!.value).toBe("https://cdn.example.test/new.png"); + expect(host.querySelector('[role="alert"]')).not.toBeNull(); + expect(host.querySelector('button[type="submit"]')!.disabled).toBe(false); +}); diff --git a/apps/dashboard/src/components/settings/ImageUrlEditor.tsx b/apps/dashboard/src/components/settings/ImageUrlEditor.tsx new file mode 100644 index 000000000..d2e035f0a --- /dev/null +++ b/apps/dashboard/src/components/settings/ImageUrlEditor.tsx @@ -0,0 +1,143 @@ +"use client"; + +import { useEffect, useId, useState, type ReactNode } from "react"; +import { isImageUrl, MAX_IMAGE_URL_LENGTH } from "@repo/core"; +import { useI18n } from "@/components/i18n-provider"; +import { Input } from "@/components/ui/input"; +import { useImageFallback } from "@/hooks/useImageFallback"; +import { getApiErrorMessage } from "@/lib/api/client"; + +/** Shared URL editor; saving never depends on a remote image probe. */ +export function ImageUrlEditor({ + value, + label, + hint, + resetLabel, + fallback, + onSave, +}: { + value: string | null | undefined; + label: string; + hint: string; + resetLabel: string; + fallback: ReactNode; + onSave: (url: string | null) => Promise; +}) { + const { t } = useI18n(); + const c = t.settings.imageUrl; + const id = useId(); + const [draft, setDraft] = useState(value ?? ""); + const [saving, setSaving] = useState(false); + const [error, setError] = useState(""); + const [saved, setSaved] = useState(false); + useEffect(() => { + setDraft(value ?? ""); + }, [value]); + const trimmed = draft.trim(); + const preview = useImageFallback(isImageUrl(trimmed) ? trimmed : null); + const save = async (next: string | null) => { + if (saving) return; + if (next && !isImageUrl(next)) { + setError(c.invalid); + return; + } + setSaving(true); + setError(""); + setSaved(false); + try { + await onSave(next); + setDraft(next ?? ""); + setSaved(true); + } catch (failure) { + setError(getApiErrorMessage(failure, c.failed)); + } finally { + setSaving(false); + } + }; + return ( +

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

+ {hint} +

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

{c.previewFailed}

+ )} + {error && ( + + )} +
+ + {value && ( + + )} + {saved && ( + + {c.saved} + + )} +
+
+ ); +} diff --git a/apps/dashboard/src/components/settings/image-settings.test.tsx b/apps/dashboard/src/components/settings/image-settings.test.tsx new file mode 100644 index 000000000..3a5dd68c1 --- /dev/null +++ b/apps/dashboard/src/components/settings/image-settings.test.tsx @@ -0,0 +1,82 @@ +// @vitest-environment happy-dom +import { act } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { afterEach, beforeEach, expect, it, vi } from "vitest"; +import { I18nProvider } from "@/components/i18n-provider"; +import { ProfileSetting } from "@/app/(dashboard)/settings/_components/ProfileSetting"; +import { ProjectIconSetting } from "@/components/project-settings/ProjectIconSetting"; + +const h = vi.hoisted(() => ({ + profile: vi.fn(), + project: vi.fn(), + update: vi.fn(), + invalidate: vi.fn(), +})); +vi.mock("@/context/AuthContext", () => ({ + useAuth: () => ({ user: { name: "Ada", email: "ada@example.test", image: null } }), +})); +vi.mock("@/lib/auth-client", () => ({ authClient: { updateUser: h.profile } })); +vi.mock("@/context/ProjectSettingsContext", () => ({ + useProjectSettings: () => ({ + projectData: { id: "project-a", iconUrl: "https://cdn.example.test/old.png" }, + updateProjectData: h.update, + }), +})); +vi.mock("@/lib/api", () => ({ projectsApi: { update: h.project } })); +vi.mock("@/hooks/useProjectEndpoints", () => ({ invalidateProjectCaches: h.invalidate })); +let host: HTMLDivElement; +let root: Root; +beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true); + h.profile.mockResolvedValue({ data: { status: true }, error: null }); + h.project.mockImplementation(async (_id, data) => ({ data })); + host = document.createElement("div"); + document.body.append(host); + root = createRoot(host); +}); +afterEach(async () => { + await act(async () => root.unmount()); + host.remove(); + vi.unstubAllGlobals(); +}); + +it("saves the avatar through the current user's existing auth update", async () => { + await act(async () => + root.render( + + + , + ), + ); + await act(async () => { + const input = host.querySelector("input")!; + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call( + input, + "https://cdn.example.test/avatar.png", + ); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + await act(async () => + host + .querySelector("form")! + .dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })), + ); + expect(h.profile).toHaveBeenCalledWith({ image: "https://cdn.example.test/avatar.png" }); +}); + +it("clears the single project icon field through existing settings", async () => { + await act(async () => + root.render( + + + , + ), + ); + await act(async () => host.querySelector('button[type="button"]')!.click()); + expect(h.project).toHaveBeenCalledWith("project-a", { iconUrl: null }); + expect(h.update).toHaveBeenCalledWith({ + iconUrl: null, + }); + expect(h.invalidate).toHaveBeenCalledWith("project-a"); +}); diff --git a/apps/dashboard/src/components/shared/ProjectIcon.tsx b/apps/dashboard/src/components/shared/ProjectIcon.tsx new file mode 100644 index 000000000..629e03763 --- /dev/null +++ b/apps/dashboard/src/components/shared/ProjectIcon.tsx @@ -0,0 +1,43 @@ +"use client"; + +import { AppLogo } from "@/components/AppLogo"; +import { useImageFallback } from "@/hooks/useImageFallback"; +import { ProjectStackIcon } from "./ProjectStackIcon"; + +/** One display order everywhere: project icon, catalog logo, then stack icon. */ +export function ProjectIcon({ + project, + appTemplateId, + className = "size-6", +}: { + project: { + iconUrl?: string | null; + framework?: string | null; + serviceDeploymentMode?: "single" | "services"; + }; + appTemplateId?: string | null; + className?: string; +}) { + const src = project.iconUrl; + const image = useImageFallback(src); + if (image.showImage) + return ( + + ); + if (appTemplateId) + return ; + return ( + + ); +} diff --git a/apps/dashboard/src/components/shared/ProjectStackIcon.test.tsx b/apps/dashboard/src/components/shared/ProjectStackIcon.test.tsx index dc5b314a9..6ebfdc608 100644 --- a/apps/dashboard/src/components/shared/ProjectStackIcon.test.tsx +++ b/apps/dashboard/src/components/shared/ProjectStackIcon.test.tsx @@ -67,10 +67,10 @@ describe("project and deployment icon identity", () => { expect(html).not.toContain("html5"); }); - it("keeps favicons ahead of the service-group fallback", () => { + it("keeps project icons ahead of the service-group fallback", () => { const html = renderToStaticMarkup( - + , ); expect(html).toContain('src="/site.ico"'); diff --git a/apps/dashboard/src/components/shared/ProjectStackIcon.tsx b/apps/dashboard/src/components/shared/ProjectStackIcon.tsx index 40d63c979..00d062b2a 100644 --- a/apps/dashboard/src/components/shared/ProjectStackIcon.tsx +++ b/apps/dashboard/src/components/shared/ProjectStackIcon.tsx @@ -4,7 +4,7 @@ import { isServicesFramework } from "@repo/core"; import { Icon } from "@repo/ui/icons"; import { getFrameworkConfig } from "@/components/import-project/Frameworks"; -/** Fallback identity after a catalog logo or favicon, shared by project rows +/** Fallback identity after a project icon or catalog logo, shared by project rows * and deployment history. A missing framework never implies a static site. */ export function ProjectStackIcon({ framework, diff --git a/apps/dashboard/src/components/sidebar.tsx b/apps/dashboard/src/components/sidebar.tsx index b772b2914..009db0fe6 100644 --- a/apps/dashboard/src/components/sidebar.tsx +++ b/apps/dashboard/src/components/sidebar.tsx @@ -1,5 +1,7 @@ "use client"; +import { UserAvatar } from "@/components/ui/UserAvatar"; + import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics"; import { Icon as UiIcon } from "@repo/ui/icons"; @@ -472,9 +474,11 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo title={collapsed ? activeOrg?.name : undefined} > {/* Org avatar / initial */} -
- {activeOrg?.name?.[0] ?? } -
+ {activeOrg?.id === `org_${user?.id}` ? : ( +
+ {activeOrg?.name?.[0] ?? } +
+ )} {!collapsed && ( <> @@ -563,9 +567,7 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo {/* Footer separator + signed-in-as + sign out */}
-
- {displayInitial} -
+

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

- {displayInitial} -
+ {!collapsed && ( <> diff --git a/apps/dashboard/src/components/ui/UserAvatar.tsx b/apps/dashboard/src/components/ui/UserAvatar.tsx new file mode 100644 index 000000000..e398f65d7 --- /dev/null +++ b/apps/dashboard/src/components/ui/UserAvatar.tsx @@ -0,0 +1,37 @@ +"use client"; + +import { useImageFallback } from "@/hooks/useImageFallback"; +import { cn } from "@/lib/utils"; + +export function UserAvatar({ + image, + name, + className, +}: { + image?: string | null; + name: string; + className?: string; +}) { + const fallback = useImageFallback(image); + return ( + + {fallback.showImage ? ( + + ) : ( + name[0] || "?" + )} + + ); +} diff --git a/apps/dashboard/src/constants/mock.ts b/apps/dashboard/src/constants/mock.ts index a69bb41eb..91532d414 100644 --- a/apps/dashboard/src/constants/mock.ts +++ b/apps/dashboard/src/constants/mock.ts @@ -78,7 +78,7 @@ export interface Project { lifecycleOperation?: ProjectLifecycleOperation | null; /* ── Hosting info (enriched by API) ─────────────────────── */ - favicon?: string | null; + iconUrl?: string | null; deployTarget?: string | null; serverId?: string | null; serverName?: string | null; diff --git a/apps/dashboard/src/i18n/locales/ar/projectSettings.json b/apps/dashboard/src/i18n/locales/ar/projectSettings.json index 21e36d9ea..8ccbdf611 100644 --- a/apps/dashboard/src/i18n/locales/ar/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/ar/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "بايت", "emptyBodyHint": "يتطلب رمز الحالة هذا محتوى استجابة فارغًا.", "headersHint": "أضف ترويسات للتخزين المؤقت أو CORS أو غيرها." + }, + "icon": { + "label": "رابط أيقونة المشروع", + "hint": "استخدم رابط صورة HTTP أو HTTPS. امسحه لاستخدام الأيقونة الافتراضية.", + "reset": "استخدام الأيقونة الافتراضية" } } diff --git a/apps/dashboard/src/i18n/locales/ar/settings.json b/apps/dashboard/src/i18n/locales/ar/settings.json index 360545e81..7e6d02ff5 100644 --- a/apps/dashboard/src/i18n/locales/ar/settings.json +++ b/apps/dashboard/src/i18n/locales/ar/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "إيقاف الخدمة", "cancel": "إلغاء", "noReverseProxy": "لم يتم اكتشاف وكيل عكسي على هذا الجهاز." + }, + "imageUrl": { + "preview": "معاينة الصورة", + "invalid": "أدخل رابط صورة HTTP أو HTTPS بدون بيانات تسجيل دخول.", + "failed": "تعذّر حفظ رابط الصورة.", + "save": "حفظ", + "saving": "جارٍ الحفظ…", + "saved": "تم الحفظ", + "previewFailed": "المعاينة غير متاحة. تأكد أن الرابط يشير مباشرةً إلى صورة." + }, + "profile": { + "title": "الملف الشخصي", + "description": "صورة حسابك الشخصي.", + "label": "رابط الصورة الشخصية", + "hint": "استخدم رابط صورة مباشرًا. اتركه فارغًا لاستخدام الحرف الأول من اسمك.", + "reset": "استخدام الحرف الأول" } } diff --git a/apps/dashboard/src/i18n/locales/de/projectSettings.json b/apps/dashboard/src/i18n/locales/de/projectSettings.json index b21c553ec..427e82fc1 100644 --- a/apps/dashboard/src/i18n/locales/de/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/de/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "Bytes", "emptyBodyHint": "Dieser Status erfordert einen leeren Antwortinhalt.", "headersHint": "Cache-, CORS- oder andere Antwortheader hinzufügen." + }, + "icon": { + "label": "URL des Projektsymbols", + "hint": "Verwende eine HTTP- oder HTTPS-Bild-URL. Leere sie, um das Standardsymbol zu verwenden.", + "reset": "Standardsymbol verwenden" } } diff --git a/apps/dashboard/src/i18n/locales/de/settings.json b/apps/dashboard/src/i18n/locales/de/settings.json index 2a500160e..296a00e59 100644 --- a/apps/dashboard/src/i18n/locales/de/settings.json +++ b/apps/dashboard/src/i18n/locales/de/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "Bereitstellung stoppen", "cancel": "Abbrechen", "noReverseProxy": "Auf dieser Maschine wurde kein Reverse-Proxy erkannt." + }, + "imageUrl": { + "preview": "Bildvorschau", + "invalid": "Gib eine HTTP- oder HTTPS-Bild-URL ohne Zugangsdaten ein.", + "failed": "Die Bild-URL konnte nicht gespeichert werden.", + "save": "Speichern", + "saving": "Wird gespeichert…", + "saved": "Gespeichert", + "previewFailed": "Keine Vorschau verfügbar. Prüfe, ob die URL direkt auf ein Bild verweist." + }, + "profile": { + "title": "Profil", + "description": "Das Bild deines persönlichen Kontos.", + "label": "Avatar-URL", + "hint": "Verwende eine direkte Bild-URL. Leer lassen, um deinen Anfangsbuchstaben anzuzeigen.", + "reset": "Anfangsbuchstaben verwenden" } } diff --git a/apps/dashboard/src/i18n/locales/en/projectSettings.json b/apps/dashboard/src/i18n/locales/en/projectSettings.json index 09e2bf804..283ddea15 100644 --- a/apps/dashboard/src/i18n/locales/en/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/en/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "bytes", "emptyBodyHint": "This status requires an empty response body.", "headersHint": "Add cache, CORS, or other response headers." + }, + "icon": { + "label": "Project icon URL", + "hint": "Use an HTTP or HTTPS image URL. Clear it to use the default icon.", + "reset": "Use default icon" } } diff --git a/apps/dashboard/src/i18n/locales/en/settings.json b/apps/dashboard/src/i18n/locales/en/settings.json index 77286e291..ff151942c 100644 --- a/apps/dashboard/src/i18n/locales/en/settings.json +++ b/apps/dashboard/src/i18n/locales/en/settings.json @@ -1791,5 +1791,21 @@ "title": "Demo mode", "description": "Blur IP addresses, hosts, and environment values during screen-shares and recordings." } + }, + "imageUrl": { + "preview": "Image preview", + "invalid": "Enter an HTTP or HTTPS image URL without embedded credentials.", + "failed": "Could not save the image URL.", + "save": "Save", + "saving": "Saving…", + "saved": "Saved", + "previewFailed": "Preview unavailable. Check that the URL points directly to an image." + }, + "profile": { + "title": "Profile", + "description": "Your personal account image.", + "label": "Avatar URL", + "hint": "Use a direct image URL. Leave empty to use your initial.", + "reset": "Use initial" } } diff --git a/apps/dashboard/src/i18n/locales/es/projectSettings.json b/apps/dashboard/src/i18n/locales/es/projectSettings.json index e7e7bfe01..fd96834e2 100644 --- a/apps/dashboard/src/i18n/locales/es/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/es/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "bytes", "emptyBodyHint": "Este estado requiere un cuerpo de respuesta vacío.", "headersHint": "Añade cabeceras de caché, CORS u otras." + }, + "icon": { + "label": "URL del icono del proyecto", + "hint": "Usa una URL de imagen HTTP o HTTPS. Bórrala para usar el icono predeterminado.", + "reset": "Usar icono predeterminado" } } diff --git a/apps/dashboard/src/i18n/locales/es/settings.json b/apps/dashboard/src/i18n/locales/es/settings.json index 3ab15e30e..0d2c5871c 100644 --- a/apps/dashboard/src/i18n/locales/es/settings.json +++ b/apps/dashboard/src/i18n/locales/es/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "Dejar de servir", "cancel": "Cancelar", "noReverseProxy": "No se detectó ningún proxy inverso en esta máquina." + }, + "imageUrl": { + "preview": "Vista previa de la imagen", + "invalid": "Introduce una URL HTTP o HTTPS sin credenciales.", + "failed": "No se pudo guardar la URL de la imagen.", + "save": "Guardar", + "saving": "Guardando…", + "saved": "Guardado", + "previewFailed": "Vista previa no disponible. Comprueba que la URL enlace directamente a una imagen." + }, + "profile": { + "title": "Perfil", + "description": "La imagen de tu cuenta personal.", + "label": "URL del avatar", + "hint": "Usa una URL directa de imagen. Déjala vacía para mostrar tu inicial.", + "reset": "Usar inicial" } } diff --git a/apps/dashboard/src/i18n/locales/fr/projectSettings.json b/apps/dashboard/src/i18n/locales/fr/projectSettings.json index df9987abb..af9bb4454 100644 --- a/apps/dashboard/src/i18n/locales/fr/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/fr/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "octets", "emptyBodyHint": "Ce statut nécessite un corps de réponse vide.", "headersHint": "Ajoutez des en-têtes de cache, CORS ou autres." + }, + "icon": { + "label": "URL de l’icône du projet", + "hint": "Utilisez une URL d’image HTTP ou HTTPS. Effacez-la pour utiliser l’icône par défaut.", + "reset": "Utiliser l’icône par défaut" } } diff --git a/apps/dashboard/src/i18n/locales/fr/settings.json b/apps/dashboard/src/i18n/locales/fr/settings.json index 4a43b3d39..5614429ab 100644 --- a/apps/dashboard/src/i18n/locales/fr/settings.json +++ b/apps/dashboard/src/i18n/locales/fr/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "Cesser de servir", "cancel": "Annuler", "noReverseProxy": "Aucun proxy inverse détecté sur cette machine." + }, + "imageUrl": { + "preview": "Aperçu de l’image", + "invalid": "Saisissez une URL HTTP ou HTTPS sans identifiants.", + "failed": "Impossible d’enregistrer l’URL de l’image.", + "save": "Enregistrer", + "saving": "Enregistrement…", + "saved": "Enregistré", + "previewFailed": "Aperçu indisponible. Vérifiez que l’URL pointe directement vers une image." + }, + "profile": { + "title": "Profil", + "description": "L’image de votre compte personnel.", + "label": "URL de l’avatar", + "hint": "Utilisez une URL directe d’image. Laissez vide pour afficher votre initiale.", + "reset": "Utiliser l’initiale" } } diff --git a/apps/dashboard/src/i18n/locales/ja/projectSettings.json b/apps/dashboard/src/i18n/locales/ja/projectSettings.json index 1829beee8..17f63ef7a 100644 --- a/apps/dashboard/src/i18n/locales/ja/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/ja/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "バイト", "emptyBodyHint": "このステータスではレスポンス本文を空にする必要があります。", "headersHint": "キャッシュ、CORSなどのレスポンスヘッダーを追加します。" + }, + "icon": { + "label": "プロジェクトアイコンの URL", + "hint": "HTTP または HTTPS の画像 URL を指定してください。空にすると既定のアイコンに戻ります。", + "reset": "既定のアイコンを使用" } } diff --git a/apps/dashboard/src/i18n/locales/ja/settings.json b/apps/dashboard/src/i18n/locales/ja/settings.json index 9394731c4..db135bb68 100644 --- a/apps/dashboard/src/i18n/locales/ja/settings.json +++ b/apps/dashboard/src/i18n/locales/ja/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "配信を停止", "cancel": "キャンセル", "noReverseProxy": "このマシンでリバースプロキシが検出されませんでした。" + }, + "imageUrl": { + "preview": "画像プレビュー", + "invalid": "認証情報を含まない HTTP または HTTPS の画像 URL を入力してください。", + "failed": "画像 URL を保存できませんでした。", + "save": "保存", + "saving": "保存中…", + "saved": "保存しました", + "previewFailed": "プレビューを表示できません。画像の直接 URL か確認してください。" + }, + "profile": { + "title": "プロフィール", + "description": "個人アカウントの画像。", + "label": "アバター URL", + "hint": "画像の直接 URL を使用します。空欄にすると名前の頭文字を表示します。", + "reset": "頭文字を使用" } } diff --git a/apps/dashboard/src/i18n/locales/pt/projectSettings.json b/apps/dashboard/src/i18n/locales/pt/projectSettings.json index b27f511cf..a3ca74b0a 100644 --- a/apps/dashboard/src/i18n/locales/pt/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/pt/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "bytes", "emptyBodyHint": "Este estado exige um corpo de resposta vazio.", "headersHint": "Adicione cabeçalhos de cache, CORS ou outros." + }, + "icon": { + "label": "URL do ícone do projeto", + "hint": "Use uma URL de imagem HTTP ou HTTPS. Limpe-a para usar o ícone padrão.", + "reset": "Usar ícone padrão" } } diff --git a/apps/dashboard/src/i18n/locales/pt/settings.json b/apps/dashboard/src/i18n/locales/pt/settings.json index 3fa1a6087..883f9ab06 100644 --- a/apps/dashboard/src/i18n/locales/pt/settings.json +++ b/apps/dashboard/src/i18n/locales/pt/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "Parar de servir", "cancel": "Cancelar", "noReverseProxy": "Nenhum proxy reverso detectado nesta máquina." + }, + "imageUrl": { + "preview": "Prévia da imagem", + "invalid": "Insira uma URL HTTP ou HTTPS sem credenciais.", + "failed": "Não foi possível salvar a URL da imagem.", + "save": "Salvar", + "saving": "Salvando…", + "saved": "Salvo", + "previewFailed": "Prévia indisponível. Verifique se a URL aponta diretamente para uma imagem." + }, + "profile": { + "title": "Perfil", + "description": "A imagem da sua conta pessoal.", + "label": "URL do avatar", + "hint": "Use uma URL direta de imagem. Deixe em branco para usar sua inicial.", + "reset": "Usar inicial" } } diff --git a/apps/dashboard/src/i18n/locales/ru/projectSettings.json b/apps/dashboard/src/i18n/locales/ru/projectSettings.json index 80843ddf0..444152582 100644 --- a/apps/dashboard/src/i18n/locales/ru/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/ru/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "байт", "emptyBodyHint": "Этот статус требует пустого тела ответа.", "headersHint": "Добавьте заголовки кеширования, CORS или другие." + }, + "icon": { + "label": "URL значка проекта", + "hint": "Укажите HTTP- или HTTPS-ссылку на изображение. Очистите её, чтобы использовать значок по умолчанию.", + "reset": "Стандартный значок" } } diff --git a/apps/dashboard/src/i18n/locales/ru/settings.json b/apps/dashboard/src/i18n/locales/ru/settings.json index 59cb29a08..1ee579392 100644 --- a/apps/dashboard/src/i18n/locales/ru/settings.json +++ b/apps/dashboard/src/i18n/locales/ru/settings.json @@ -1791,5 +1791,21 @@ "title": "Демо-режим", "description": "Размывать IP-адреса, хосты и переменные окружения при показе экрана и записи видео." } + }, + "imageUrl": { + "preview": "Предпросмотр изображения", + "invalid": "Введите HTTP- или HTTPS-адрес изображения без учётных данных.", + "failed": "Не удалось сохранить адрес изображения.", + "save": "Сохранить", + "saving": "Сохранение…", + "saved": "Сохранено", + "previewFailed": "Предпросмотр недоступен. Проверьте, что URL ведёт прямо к изображению." + }, + "profile": { + "title": "Профиль", + "description": "Изображение вашего личного аккаунта.", + "label": "URL аватара", + "hint": "Укажите прямую ссылку на изображение. Оставьте поле пустым, чтобы показать инициал.", + "reset": "Использовать инициал" } } diff --git a/apps/dashboard/src/i18n/locales/tr/projectSettings.json b/apps/dashboard/src/i18n/locales/tr/projectSettings.json index b81cee71b..9f55585ea 100644 --- a/apps/dashboard/src/i18n/locales/tr/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/tr/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "bayt", "emptyBodyHint": "Bu durum kodu boş bir yanıt gövdesi gerektirir.", "headersHint": "Önbellek, CORS veya diğer yanıt başlıklarını ekleyin." + }, + "icon": { + "label": "Proje simgesi URL’si", + "hint": "HTTP veya HTTPS resim URL’si kullanın. Varsayılan simgeyi kullanmak için URL’yi temizleyin.", + "reset": "Varsayılan simgeyi kullan" } } diff --git a/apps/dashboard/src/i18n/locales/tr/settings.json b/apps/dashboard/src/i18n/locales/tr/settings.json index 343010e85..563cf2944 100644 --- a/apps/dashboard/src/i18n/locales/tr/settings.json +++ b/apps/dashboard/src/i18n/locales/tr/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "Sunmayı durdur", "cancel": "İptal", "noReverseProxy": "Bu makinede ters proxy algılanmadı." + }, + "imageUrl": { + "preview": "Resim önizlemesi", + "invalid": "Kimlik bilgisi içermeyen bir HTTP veya HTTPS resim URL’si girin.", + "failed": "Resim URL’si kaydedilemedi.", + "save": "Kaydet", + "saving": "Kaydediliyor…", + "saved": "Kaydedildi", + "previewFailed": "Önizleme kullanılamıyor. URL’nin doğrudan bir resme yöneldiğini kontrol edin." + }, + "profile": { + "title": "Profil", + "description": "Kişisel hesabınızın resmi.", + "label": "Avatar URL’si", + "hint": "Doğrudan bir resim URL’si kullanın. Baş harfiniz için boş bırakın.", + "reset": "Baş harfi kullan" } } diff --git a/apps/dashboard/src/i18n/locales/zh/projectSettings.json b/apps/dashboard/src/i18n/locales/zh/projectSettings.json index 8d912db95..ab52939d9 100644 --- a/apps/dashboard/src/i18n/locales/zh/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/zh/projectSettings.json @@ -1437,5 +1437,10 @@ "bytes": "字节", "emptyBodyHint": "此状态码要求响应正文为空。", "headersHint": "添加缓存、CORS 或其他响应标头。" + }, + "icon": { + "label": "项目图标 URL", + "hint": "使用 HTTP 或 HTTPS 图片 URL。清空后将使用默认图标。", + "reset": "使用默认图标" } } diff --git a/apps/dashboard/src/i18n/locales/zh/settings.json b/apps/dashboard/src/i18n/locales/zh/settings.json index 753bd8f2a..682c418c8 100644 --- a/apps/dashboard/src/i18n/locales/zh/settings.json +++ b/apps/dashboard/src/i18n/locales/zh/settings.json @@ -1791,5 +1791,21 @@ "confirmCta": "停止服务", "cancel": "取消", "noReverseProxy": "在此机器上未检测到反向代理。" + }, + "imageUrl": { + "preview": "图片预览", + "invalid": "请输入不含凭据的 HTTP 或 HTTPS 图片 URL。", + "failed": "无法保存图片 URL。", + "save": "保存", + "saving": "正在保存…", + "saved": "已保存", + "previewFailed": "无法预览。请检查 URL 是否直接指向图片。" + }, + "profile": { + "title": "个人资料", + "description": "你的个人账户图片。", + "label": "头像 URL", + "hint": "使用图片的直接 URL。留空则显示姓名首字母。", + "reset": "使用首字母" } } diff --git a/apps/dashboard/src/lib/api/connections.ts b/apps/dashboard/src/lib/api/connections.ts index 54c2c54a1..58e3e6043 100644 --- a/apps/dashboard/src/lib/api/connections.ts +++ b/apps/dashboard/src/lib/api/connections.ts @@ -1,3 +1,4 @@ +import type { ProjectConnectionCandidate } from "@repo/contracts"; import { api } from "./client"; import { endpoints } from "./endpoints"; @@ -48,15 +49,7 @@ async function notifyConnections(request: Promise): Promise { export const connectionsApi = { candidates: (projectId: string) => - api.get<{ - data: Array<{ - id: string; - name: string; - description: string; - appTemplateId: string | null; - clusterId?: string | null; - }>; - }>(`${endpoints.projects.connections(projectId)}/candidates`), + api.get<{ data: ProjectConnectionCandidate[] }>(`${endpoints.projects.connections(projectId)}/candidates`), /** Connections wired INTO a project (`projectId` = the consumer). */ list: (projectId: string) => api.get<{ data: ProjectConnection[] }>(endpoints.projects.connections(projectId)), diff --git a/apps/web/content/docs/dashboard/projects.mdx b/apps/web/content/docs/dashboard/projects.mdx index c616684dc..cb456e05f 100644 --- a/apps/web/content/docs/dashboard/projects.mdx +++ b/apps/web/content/docs/dashboard/projects.mdx @@ -13,7 +13,7 @@ its management tabs). Open **Projects** from the left nav. This screen is a single scannable list of every project in your workspace — one row per project. -Each row shows, left to right: the app's icon (its favicon, or the framework logo), the **name** +Each row shows, left to right: the project icon (set in **Settings → Project Info**), or its app/framework logo, the **name** and its live version badge, the primary **domain**, the detected **framework**, where it's hosted (**Cloud**, a **Server** by name, or **Local**), its source (a GitHub repo or a local folder), the build shape (**Services**, **Static**, or **Standalone**), how long ago it changed, and a diff --git a/docs/dashboard-design.md b/docs/dashboard-design.md index d09a84ef8..b7a1b30f8 100644 --- a/docs/dashboard-design.md +++ b/docs/dashboard-design.md @@ -5,6 +5,13 @@ and a consistent type hierarchy across light, dim, and dark themes. ## Surfaces and controls +Personal avatar URLs live in Settings → General → Profile. Project icon URLs live +in the Project Info card in project Settings. Both use the shared URL editor with +a preview and a reset action. Each project has one `iconUrl`; project, app, connection +and deployment lists use the same renderer. Clearing the URL restores the catalog +logo or framework/service icon. Image URLs are displayed directly by the browser +with no referrer; the control plane does not fetch them or discover favicons. + Assistant settings belong in **Settings → Assistant**; event-driven flows and run history open from **Automations** in the AI Agents right column. Keep the conversation free of view tabs, with an AI Agents return action on the automations page. @@ -1065,9 +1072,11 @@ from an existing run. Keep loading, fetch errors and empty inventory distinct, a the selected destination's validation and transfer review before enabling Migrate. Platform imports share three steps: Connect, Select services, and Review & import. Show -one destination project for each source project, with its selected services and private -connections kept together. Name the project once in the destination sidebar; service cards -edit service names. Review and progress link to that project without repeating it for each service. +one destination project when the source services share a compatible Git checkout. Environments +with multiple repositories, branches or revisions create a project per service, connected privately +on the same destination server. Show each destination name in review and the project count in its +summary. Name the import once in the destination sidebar; service cards edit service names. +Progress links once per destination project. Review and saved progress share a Domains & DNS guide, using the provider's recorded domain ownership per service. Imported custom domains are saved through the normal migration routing path, initially unverified. Distinguish domains that need DNS changes from provider URLs that diff --git a/docs/mail-engine-state.md b/docs/mail-engine-state.md index cfa70c3cc..60e9dc512 100644 --- a/docs/mail-engine-state.md +++ b/docs/mail-engine-state.md @@ -25,10 +25,13 @@ Supervisor rather than relying on systemd or Debian's service-start policy. `OPENSHIP_MAIL_F2B_IGNOREIP` extends the image's default `ignoreip` list. For a new installation, an operator may set it in the API environment before mail setup. -For an existing server, set the single-line value in that server's retained -`/var/lib/openship/mail/engine.env`, then update/recreate the engine. Different -servers can retain different exclusions. The file contains credentials and must -remain private. +On an engine image update, a nonempty API value replaces this record in the retained +`/var/lib/openship/mail/engine.env`; an explicitly empty API value removes it. +Leaving the API variable unset preserves the server's saved exclusions. Different +servers can retain different lists configured directly in their own `engine.env`. +The override is applied when replacing the engine image; restarting the API or +checking an already-current image does not recreate the engine. The file contains +credentials and must remain private. Move existing manual `ignoreip` edits from the old container into this setting before the first update. Arbitrary files under `/etc/fail2ban` are not persisted; diff --git a/docs/platform-migrations.md b/docs/platform-migrations.md index c9f0baca7..e72b03223 100644 --- a/docs/platform-migrations.md +++ b/docs/platform-migrations.md @@ -6,10 +6,10 @@ New Project → Import existing project offers Server or Docker, Railway, and Ve 1. An organization admin adds a Railway or Vercel connection in Settings → Connections or directly in the import flow. Existing registry and DNS credentials remain on the same page. Old `?tab=credentials` and `?tab=dns` links still work. 2. Select a project and environment. Railway discovers services, deployed revisions, variables, domains, and attached volumes. Vercel discovers a production or latest ready preview deployment and its GitHub source, build configuration, variables, domains, and PostgreSQL URLs. -3. Review all services in the Railway environment together, one destination project name, distinct service names, a managed plan or connected server, and whether to copy storage or explicitly start empty. Each source project becomes one OpenShip project containing its services; importing a second source project creates a separate project. An external PostgreSQL connection can also remain with its current provider. Supply non-exportable secrets and resolve unsupported provider references. +3. Review all services in the Railway environment together, one destination project name, distinct service names, a managed plan or connected server, and whether to copy storage or explicitly start empty. Services sharing one repository, branch and revision stay in one OpenShip project. When Git sources differ, each service gets its own project on the selected server; review shows the exact destination names before import. Importing another source environment creates separate projects. An external PostgreSQL connection can also remain with its current provider. Supply non-exportable secrets and resolve unsupported provider references. 4. Review checks source compatibility, repository access and destination access. The plan expires after 30 minutes. Starting rechecks the provider inventory; changed configuration requires a fresh discovery. Source admission is reserved transactionally by Railway project and environment, across destinations and connection records. -5. Allow Railway project downtime and pause external deployment automation. The worker prepares the selected managed Cloud host before source downtime, creates one destination project with native services, disables automatic push deployments, stops the entire source environment and copies its volumes before deploying the destination. Private addresses resolve through the services' native aliases on the project network. Environment values are encrypted and scoped per service. Named volumes include the service name and use the normal project namespace, keeping databases and separate projects isolated. -6. Follow progress, logs and the project link at `/migrations/`, including after a browser refresh. Review **Domains & DNS**: each saved source hostname is associated with its service. Custom domains and aliases are already added through the same `saveMigrationRoutes` path used by server/Docker migration, initially unverified. Provider-owned Railway and Vercel URLs require replacement addresses and updates to clients, OAuth callbacks and webhooks. **Review domains & DNS** opens the native project Domains & Routes flow. Test the destination, apply the exact DNS records shown for Cloud or the destination server, then verify DNS, HTTPS and application traffic before confirming completion. Retire the old provider resources separately. +5. Allow Railway project downtime and pause external deployment automation. The worker prepares the selected managed Cloud host before source downtime, creates the reviewed destination projects with native services, disables automatic push deployments, stops the entire source environment and copies every selected volume before starting destination workloads. Dependencies deploy before their consumers. Within a project, private addresses use native service aliases; across projects they use ordinary private service connections with immutable service aliases. Environment values remain encrypted. Service-specific values stay scoped to the service; cross-project connection variables are owned by the native connection so later deployments refresh them correctly. Named volumes include the service name and use the normal project namespace, keeping databases and separate projects isolated. +6. Follow progress, logs and the destination project links at `/migrations/`, including after a browser refresh. Review **Domains & DNS**: each saved source hostname is associated with its service. Custom domains and aliases are already added through the same `saveMigrationRoutes` path used by server/Docker migration, initially unverified. Provider-owned Railway and Vercel URLs require replacement addresses and updates to clients, OAuth callbacks and webhooks. **Review domains & DNS** opens the native project Domains & Routes flow. Test the destination, apply the exact DNS records shown for Cloud or the destination server, then verify DNS, HTTPS and application traffic before confirming completion. Retire the old provider resources separately. Domain guidance reuses the public `domains` inventory and its `portable` flag, persisted in the run's input snapshot. Route persistence validates hostname ownership before stopping the source; @@ -22,7 +22,7 @@ reopening a saved run; confirmation remains an operator acknowledgment, not an a | Source | Supported | Explicit review or separate work | | ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Railway | Complete project environments, GitHub repositories at the deployed commit, custom Dockerfiles, portable registry images, build settings, HTTP readiness, restart policy, variables and all selected persistent volume contents | Sealed secrets, unresolved references, dependency cycles, incompatible Git sources, scheduled jobs, multiple replicas, pre-deploy commands, multiple public ports, private registry access and provider-specific features | +| Railway | Complete project environments including multiple GitHub repositories at their own deployed commits, custom Dockerfiles, portable registry images, build settings, HTTP readiness, restart policy, variables and all selected persistent volume contents | Sealed secrets, unresolved references, dependency cycles, variables combining multiple cross-project private hosts, missing private listener ports, scheduled jobs, multiple replicas, pre-deploy commands, multiple public ports, private registry access and provider-specific features | | Vercel | GitHub source at the deployed commit, build/root/output settings, exportable environment values, discovered domains, external PostgreSQL connections | Non-exportable Secret/Sensitive values, functions and provider APIs requiring application changes, Edge Config, Blob, other storage services, and non-GitHub repositories | | External PostgreSQL | A logical copy of the configured database to the selected major version, or preservation of its external connection | Other databases, roles, provider authentication, extensions unavailable in the destination image, pooler/client settings and non-public source endpoints | @@ -34,7 +34,7 @@ Managed Cloud and connected servers use the same import worker and transfer pipe External PostgreSQL copies use the shared logical backup producer. Source/target majors and available extensions are checked before restore, and fresh destination databases must finish initialization before receiving data. External writers still require manual quiescence. -Repository imports use ordinary OpenShip source-service build recipes. Each provider service remains one native service, including explicitly discovered workers. A native project has one Git source: services using different repositories or deployed commits must be aligned before review can succeed. Repository-wide release commands require a service-compatible recipe; review blocks them instead of silently skipping their release phase. Railway pre-deploy commands, cron, replica topology, unsupported Vercel configuration and invalid paths also block review. Railway sleeping services become continuously running services, with a review warning. +Repository imports use ordinary OpenShip source-service build recipes. Each provider service remains one native service, including explicitly discovered workers. Different repositories, branches or deployed commits receive separate projects; each deployment uses that service's reviewed commit. Cross-project private connections preserve protocols, credentials, paths and ports. A variable containing several different private dependency hosts needs separate connection variables before import, and a private dependency needs a discoverable listener port; review explains these cases before source downtime. Repository-wide release commands require a service-compatible recipe; review blocks them instead of silently skipping their release phase. Railway pre-deploy commands, cron, replica topology, unsupported Vercel configuration and invalid paths also block review. Railway sleeping services become continuously running services, with a review warning. Vercel cannot export Secret/Sensitive values. After entering a missing PostgreSQL URL, Review adds its database to the same choice list. It stays external unless the user chooses to copy it. Copies require a direct public PostgreSQL URL with TLS and a source database role permitted to export its contents. DNS is validated and pinned; the client runs inside the destination database container. @@ -70,6 +70,18 @@ Import tests cover review binding and drift, exact Git revisions, destination pr source downtime, database-first ordering, transfer failures, cancellation and owned SSH-key recovery. Database tests exercise multi-project migration locks and pending cleanup guards. +### Multi-repository verification — 2026-11-16 + +The project import Docker fixture now also covers an image-backed database and two +different Git sources, importing two environments with identical service names into +six destination projects. It checks each repository's revision, real private-network +connections, copied volumes, persistence after restart, and connection refresh during +an ordinary consumer redeployment. Both socket and Cloud Docker transports use an +isolated test daemon. Provider control, Git checkout, runtime destination resolution +and the asynchronous queue are fixture boundaries; this is not a live Railway or SaaS +account test. Focused tests additionally cover dependency ordering, connection failure +and recovery, old-plan rejection, and review blockers before source downtime. + ### Grouped project verification — 2026-11-12 `apps/api/test/e2e/platform-import-project.e2e.test.ts` imports two projects, each with diff --git a/packages/adapters/src/system/mail/ensure-container-mail.test.ts b/packages/adapters/src/system/mail/ensure-container-mail.test.ts index e9c66f8d6..0025e6c70 100644 --- a/packages/adapters/src/system/mail/ensure-container-mail.test.ts +++ b/packages/adapters/src/system/mail/ensure-container-mail.test.ts @@ -1,4 +1,4 @@ -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { buildMailRunCommand, @@ -401,7 +401,8 @@ describe("ensureContainerMail swap", () => { if (cmd.includes("/proc/net/tcp")) return PROC_LISTENING; return ""; }); - const executor = { exec, streamExec, writeFile: vi.fn(async () => {}) } as never; + const readFile = vi.fn(async () => "FIRST_DOMAIN=mail.example.com\n"); + const executor = { exec, streamExec, writeFile: vi.fn(async () => {}), readFile } as never; await ensureContainerMail(executor, { domain: "example.com", @@ -416,6 +417,123 @@ describe("ensureContainerMail swap", () => { }); }); +/** Update fixtures retain the installed credentials and run the whole swap. */ +function swapBox(engineEnv: string) { + const streamExec = vi.fn(async (_cmd: string) => ({ code: 0, output: "" })); + const writeFile = vi.fn(async (_path: string, _content: string, _opts?: { mode?: number }) => {}); + const readFile = vi.fn(async (path: string) => { + if (path.endsWith("engine.env")) return engineEnv; + throw new Error("ENOENT"); + }); + const exec = vi.fn(async (cmd: string) => { + if (cmd.includes("opsh_uid=")) return "opsh_uid=0\nopsh_user=root\nopsh_sudo=n\n"; + if (cmd.includes("{{json .Mounts}}")) + return `${"a".repeat(64)}\ttrue\t${JSON.stringify( + MAIL_CONTAINER_MOUNTS.map((m) => ({ + Type: "bind", + Source: m.host, + Destination: m.container, + })), + )}`; + if (cmd.includes(STATE_PROBE)) return stateLine("ghcr.io/x/openship-mail:old"); + if (cmd.includes("docker image inspect")) return "sha256:present\n"; + if (cmd.includes("/proc/net/tcp")) return PROC_LISTENING; + return ""; + }); + const onLog = vi.fn(); + return { + exec, readFile, writeFile, streamExec, onLog, + update: () => ensureContainerMail({ exec, streamExec, writeFile, readFile } as never, { + domain: "mail.example.com", secrets: {}, onLog, + }), + engineEnvWrites: () => writeFile.mock.calls.filter(([path]) => path.endsWith("engine.env")), + }; +} + +describe("ensureContainerMail carries explicit ignore-ip overrides across an update (GH-1768)", () => { + const KEY = "OPENSHIP_MAIL_F2B_IGNOREIP"; + const ENV_BODY = "FIRST_DOMAIN=mail.example.com\nOPENSHIP_MAIL_DB_PORT=5433\nPGSQL_ROOT_PASSWD= retained#secret=one \n"; + + beforeEach(() => { + setDefaultMailImage("ghcr.io/x/openship-mail:pinned"); + vi.stubEnv(KEY, undefined); + }); + afterEach(() => vi.unstubAllEnvs()); + + it.each(["", `${KEY}=192.0.2.9\n`])("sets the override before replacement and retains credentials (previous=%s)", async previous => { + vi.stubEnv(KEY, "203.0.113.5 198.51.100.0/24"); + const box = swapBox(`${ENV_BODY}${previous}`); + expect(await box.update()).toMatchObject({ updated: true, mailDown: false }); + expect(box.engineEnvWrites()).toEqual([[ + `${MAIL_HOST_STATE_DIR}/engine.env`, + `${ENV_BODY}${KEY}=203.0.113.5 198.51.100.0/24\n`, + { mode: 0o600 }, + ]]); + expect(box.writeFile.mock.invocationCallOrder[0]).toBeLessThan(box.streamExec.mock.invocationCallOrder[0]!); + }); + + it("preserves each server's list without reading or rewriting credentials when the API variable is unset", async () => { + for (const addresses of ["192.0.2.9", "198.51.100.0/24"]) { + const box = swapBox(`${ENV_BODY}${KEY}=${addresses}\n`); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.readFile).not.toHaveBeenCalled(); + expect(box.writeFile).not.toHaveBeenCalled(); + } + }); + + it.each(["", " "])("removes only the override when the API explicitly clears it (%j)", async configured => { + vi.stubEnv(KEY, configured); + const box = swapBox(`${ENV_BODY}${KEY}=192.0.2.9\n`); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.engineEnvWrites()).toEqual([[`${MAIL_HOST_STATE_DIR}/engine.env`, ENV_BODY, { mode: 0o600 }]]); + }); + + it.each([ + ["192.0.2.9", `${KEY}=192.0.2.9\n`], + ["", ""], + ])("does not rewrite the secret file when the override already agrees (%j)", async (configured, record) => { + vi.stubEnv(KEY, configured); + const box = swapBox(`${ENV_BODY}${record}`); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.writeFile).not.toHaveBeenCalled(); + }); + + it("reports a failed read and never replaces unknown credentials with an incomplete file", async () => { + vi.stubEnv(KEY, "192.0.2.9"); + const box = swapBox(ENV_BODY); + box.readFile.mockRejectedValue(new Error("permission denied")); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.writeFile).not.toHaveBeenCalled(); + expect(box.onLog).toHaveBeenCalledWith(expect.objectContaining({ level: "warn", message: expect.stringMatching(/Could not update OPENSHIP_MAIL_F2B_IGNOREIP:.*permission denied/) })); + }); + + it("reports a failed write without silently claiming the exclusions were applied", async () => { + vi.stubEnv(KEY, "192.0.2.9"); + const box = swapBox(ENV_BODY); + box.writeFile.mockRejectedValue(new Error("read-only filesystem")); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.onLog).toHaveBeenCalledWith(expect.objectContaining({ level: "warn", message: expect.stringMatching(/Could not update OPENSHIP_MAIL_F2B_IGNOREIP:.*read-only filesystem/) })); + }); + + it("does not replace an empty retained file with missing database credentials", async () => { + vi.stubEnv(KEY, "192.0.2.9"); + const box = swapBox(""); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.writeFile).not.toHaveBeenCalled(); + expect(box.onLog).toHaveBeenCalledWith(expect.objectContaining({ level: "warn", message: expect.stringContaining("restore its credentials") })); + }); + + it("rejects injected environment records before writing and reports the validation failure", async () => { + vi.stubEnv(KEY, "192.0.2.9\nPGSQL_ROOT_PASSWD=injected"); + const box = swapBox(ENV_BODY); + expect(await box.update()).toMatchObject({ updated: true }); + expect(box.writeFile).not.toHaveBeenCalled(); + expect(box.onLog).toHaveBeenCalledWith(expect.objectContaining({ level: "warn", message: expect.stringContaining("spans multiple lines") })); + expect(JSON.stringify(box.onLog.mock.calls)).not.toContain("retained#secret"); + expect(JSON.stringify(box.onLog.mock.calls)).not.toContain("PGSQL_ROOT_PASSWD=injected"); + }); +}); + /** * Env-file record injection (GHSA-x2xg-5h5f-j5m9, second-order). * diff --git a/packages/adapters/src/system/mail/ensure-container-mail.ts b/packages/adapters/src/system/mail/ensure-container-mail.ts index 82798ed9f..7cba66808 100644 --- a/packages/adapters/src/system/mail/ensure-container-mail.ts +++ b/packages/adapters/src/system/mail/ensure-container-mail.ts @@ -342,6 +342,36 @@ async function readEnvFileValue( return null; } +/** Apply an explicit API override without removing a server's own exclusions. */ +async function carryIgnoreIp(executor: CommandExecutor, onLog: SystemLogCallback): Promise { + const key = "OPENSHIP_MAIL_F2B_IGNOREIP"; + const configured = process.env[key]; + // Existing installations may configure different lists directly on each server. + if (configured === undefined) return; + const wanted = configured.trim(); + try { + const host = await rootOrDegrade(executor, { + purpose: "Updating the mail engine's fail2ban exclusions", + consequence: "The exclusions may not be updated.", + report: message => onLog(log(message, "warn")), + }); + const body = await host.readFile(ENGINE_ENV_FILE); + if (!body.trim()) throw new Error(`The retained ${ENGINE_ENV_FILE} is empty; restore its credentials before updating exclusions.`); + const records: Record = Object.create(null); + for (const line of body.split("\n")) { + const eq = line.indexOf("="); + if (eq > 0) records[line.slice(0, eq).trim()] = line.slice(eq + 1); + } + if (wanted ? records[key] === wanted : records[key] === undefined) return; + if (wanted) records[key] = wanted; + else delete records[key]; + await writeEnvFile(host, ENGINE_ENV_FILE, records); + } catch (failure) { + observeCaughtError(failure, "adapters/system/mail/ensure-container-mail"); + onLog(log(`Could not update ${key}: ${safeErrorMessage(failure)}`, "warn")); + } +} + /** * The superuser password an ALREADY-INITIALISED cluster is holding, or null if this is a * first install. @@ -656,6 +686,8 @@ export async function ensureContainerMail( // dies on the client-side `--env-file` open, `swapManagedImage` rolls back through the // same callback and dies identically, and a perfectly healthy engine gets reported as // `mailDown` with nothing in the log pointing at permissions. + // Rewrite that record before the hand-over below, as root where the file is still root-owned. + await carryIgnoreIp(executor, onLog); await handOverEnvFile(executor, ENGINE_ENV_FILE, onLog); const start = makeMailStart(executor, container, opts); diff --git a/packages/contracts/src/deployments.ts b/packages/contracts/src/deployments.ts index 05b0d73e4..254f540ca 100644 --- a/packages/contracts/src/deployments.ts +++ b/packages/contracts/src/deployments.ts @@ -97,7 +97,7 @@ export const DeploymentSchema = Type.Object({ updatedAt: Type.String(), isActive: Type.Optional(Type.Boolean()), projectName: Type.Optional(Type.String()), - favicon: Type.Optional(Type.Union([Type.String(), Type.Null()])), + iconUrl: Type.Optional(Type.Union([Type.String(), Type.Null()])), }); export type Deployment = Static; diff --git a/packages/contracts/src/platform-migration.ts b/packages/contracts/src/platform-migration.ts index 267209c63..9d2ec55c9 100644 --- a/packages/contracts/src/platform-migration.ts +++ b/packages/contracts/src/platform-migration.ts @@ -72,6 +72,7 @@ export const PlatformMigrationPlanSchema = Type.Object({ planId: id, provider, projectName: text, + projects: Type.Optional(Type.Array(Type.Object({ name: text, serviceIds: Type.Array(id) }))), environmentName: text, targetServerId: id, services: Type.Array(PlatformImportServiceSchema), diff --git a/packages/contracts/src/project-inputs.ts b/packages/contracts/src/project-inputs.ts index d75ad8545..bfa89184c 100644 --- a/packages/contracts/src/project-inputs.ts +++ b/packages/contracts/src/project-inputs.ts @@ -8,6 +8,7 @@ import { Type, type Static, type TLiteral } from "@sinclair/typebox"; import { GitHubDeploymentChecksSchema } from "./deployment-checks"; import { STACK_IDS, + MAX_IMAGE_URL_LENGTH, RUNTIME_VERSION_PATTERN, RUNTIME_VERSION_MAX_LENGTH, ALL_PACKAGE_MANAGERS, @@ -559,7 +560,10 @@ export const CreateProjectBody = Type.Object({ // `serverId` is create/ensure-only. Keeping it out of the generic PATCH body is // also what keeps PROJECT_UPDATE_KEYS from becoming a target-retargeting path. -export const UpdateProjectBody = Type.Partial(Type.Omit(CreateProjectBody, ["serverId"])); +export const UpdateProjectBody = Type.Object({ + ...Type.Partial(Type.Omit(CreateProjectBody, ["serverId"])).properties, + iconUrl: Type.Optional(Type.Union([Type.String({ maxLength: MAX_IMAGE_URL_LENGTH }), Type.Null()])), +}); /** * POST /projects/ensure — CreateProjectBody plus an optional `projectId` to diff --git a/packages/contracts/src/project-integrations.ts b/packages/contracts/src/project-integrations.ts index 5b8f4797e..93a8c3551 100644 --- a/packages/contracts/src/project-integrations.ts +++ b/packages/contracts/src/project-integrations.ts @@ -55,18 +55,21 @@ export const ProjectEdgeConfigSchema = Type.Object({ })), }); +export const ProjectConnectionCandidateSchema = Type.Object({ + id: Type.String(), + name: Type.String(), + description: Type.String(), + appTemplateId: nullableString, + iconUrl: Type.Optional(nullableString), + framework: Type.Optional(nullableString), + clusterId: Type.Optional(nullableString), +}); +export type ProjectConnectionCandidate = Static; + export const ProjectIntegrationSchemas = { listConnectionCandidates: { action: "write", - output: Type.Array( - Type.Object({ - id: Type.String(), - name: Type.String(), - description: Type.String(), - appTemplateId: nullableString, - clusterId: Type.Optional(nullableString), - }), - ), + output: Type.Array(ProjectConnectionCandidateSchema), }, listConnections: { action: "read", output: Type.Array(ProjectConnectionSchema) }, listConnectionConsumers: { action: "read", output: Type.Array(ProjectConnectionConsumerSchema) }, diff --git a/packages/contracts/src/projects.ts b/packages/contracts/src/projects.ts index 41eb79398..6204f1de6 100644 --- a/packages/contracts/src/projects.ts +++ b/packages/contracts/src/projects.ts @@ -14,6 +14,7 @@ export const ProjectSchema = Type.Object({ groupId: Type.String({ minLength: 1 }), name: Type.String(), slug: Type.String(), + iconUrl: Type.Optional(nullableString()), createdAt: Type.String(), updatedAt: Type.String(), environmentName: Type.Optional(Type.String()), diff --git a/packages/core/src/apps/catalog.json b/packages/core/src/apps/catalog.json index 8b5151aa4..856f2ad0c 100644 --- a/packages/core/src/apps/catalog.json +++ b/packages/core/src/apps/catalog.json @@ -4177,7 +4177,7 @@ "services": [ { "name": "umami", - "image": "ghcr.io/umami-software/umami:postgresql-v2.20.2", + "image": "ghcr.io/umami-software/umami:3.4.1", "exposedPort": 3000, "exposed": true, "routes": [ diff --git a/packages/core/src/apps/catalog/umami.json b/packages/core/src/apps/catalog/umami.json index 24cbb8d6a..0325382e9 100644 --- a/packages/core/src/apps/catalog/umami.json +++ b/packages/core/src/apps/catalog/umami.json @@ -17,7 +17,7 @@ "services": [ { "name": "umami", - "image": "ghcr.io/umami-software/umami:postgresql-v2.20.2", + "image": "ghcr.io/umami-software/umami:3.4.1", "exposedPort": 3000, "exposed": true, "routes": [ diff --git a/packages/core/src/apps/umami.test.ts b/packages/core/src/apps/umami.test.ts index 1fc02cab8..2494a20b3 100644 --- a/packages/core/src/apps/umami.test.ts +++ b/packages/core/src/apps/umami.test.ts @@ -2,17 +2,21 @@ import { describe, expect, it } from "vitest"; import { getAppTemplate } from "../app-templates"; describe("Umami catalog security update", () => { - it("uses the security-patched v2 PostgreSQL release", () => { + it("uses the security-patched v3 PostgreSQL release", () => { const umami = getAppTemplate("umami"); const image = umami?.services?.find((service) => service.name === "umami")?.image; - const version = image?.match(/^ghcr\.io\/umami-software\/umami:postgresql-v2\.(\d+)\.(\d+)$/); + // v3 dropped the `postgresql-` tag prefix and MySQL support. The catalog + // already runs PostgreSQL and the container auto-applies Prisma migrations + // on start, so the pinned v3 image is a reviewed major upgrade. Moving off + // v3 needs a new migration review. + const version = image?.match(/^ghcr\.io\/umami-software\/umami:3\.(\d+)\.(\d+)$/); expect( version, - "Use an official patched v2 image; a major upgrade needs a migration review", + "Use an official patched v3 image; a major upgrade needs a migration review", ).toBeTruthy(); const [, minor, patch] = version!; - // v2.20.2 carries the Next.js / React Server Components security fixes. - expect(Number(minor) > 20 || (Number(minor) === 20 && Number(patch) >= 2)).toBe(true); + // v3.4.1 carries the Next.js 16.4.2 / React 19.3.1 security fixes. + expect(Number(minor) > 4 || (Number(minor) === 4 && Number(patch) >= 1)).toBe(true); }); it("preserves the existing database, volume, and generated secret contract", () => { diff --git a/packages/core/src/image-url.test.ts b/packages/core/src/image-url.test.ts new file mode 100644 index 000000000..79a613338 --- /dev/null +++ b/packages/core/src/image-url.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vitest"; +import { isImageUrl, MAX_IMAGE_URL_LENGTH } from "./image-url"; + +describe("display image URLs", () => { + it.each([ + "https://cdn.example.test/avatar.png?v=2", + "http://images.example.test/icon.svg", + "https://example.test/a%20b.png", + ])("accepts %s", (url) => expect(isImageUrl(url)).toBe(true)); + it.each([ + null, + 123, + "", + "/icon.png", + "//example.test/icon", + "javascript:alert(1)", + "data:image/svg+xml,", + "file:///etc/passwd", + "blob:https://example.test/id", + "https://user:password@example.test/a.png", + "https://example.test/\nimage.png", + " https://example.test/image.png", + `https://example.test/${"a".repeat(MAX_IMAGE_URL_LENGTH)}`, + ])("refuses unsafe or malformed input %j", (url) => expect(isImageUrl(url)).toBe(false)); +}); diff --git a/packages/core/src/image-url.ts b/packages/core/src/image-url.ts new file mode 100644 index 000000000..137c1d4a6 --- /dev/null +++ b/packages/core/src/image-url.ts @@ -0,0 +1,23 @@ +/** Image URLs are displayed by the browser, never fetched by the control plane. */ +export const MAX_IMAGE_URL_LENGTH = 2048; + +export function isImageUrl(value: unknown): value is string { + if ( + typeof value !== "string" || + !/^https?:\/\//i.test(value) || + value.length > MAX_IMAGE_URL_LENGTH || + /[\u0000-\u0020\u007f]/.test(value) + ) + return false; + try { + const url = new URL(value); + return ( + (url.protocol === "https:" || url.protocol === "http:") && + !!url.hostname && + !url.username && + !url.password + ); + } catch { + return false; + } +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index fa306c0a2..2c33b6c39 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,4 +1,5 @@ export * from "./types"; +export * from "./image-url"; export * from "./docker-swarm"; export * from "./actions"; export * from "./action-capabilities"; diff --git a/packages/db/drizzle/0231_project_icon_url.sql b/packages/db/drizzle/0231_project_icon_url.sql new file mode 100644 index 000000000..5ecc9e5f7 --- /dev/null +++ b/packages/db/drizzle/0231_project_icon_url.sql @@ -0,0 +1 @@ +ALTER TABLE "project" ADD COLUMN IF NOT EXISTS "icon_url" text; diff --git a/packages/db/drizzle/0232_project_icon_cleanup.sql b/packages/db/drizzle/0232_project_icon_cleanup.sql new file mode 100644 index 000000000..9ba00e56a --- /dev/null +++ b/packages/db/drizzle/0232_project_icon_cleanup.sql @@ -0,0 +1,17 @@ +-- Preserve saved images before retiring automatic favicon discovery. +-- An explicit icon always wins; projects without one retain their existing image. +UPDATE "project" +SET "icon_url" = COALESCE( + "icon_url", + "favicon", + (SELECT "favicon" FROM "project_app" WHERE "id" = "project"."app_id") +) +WHERE "icon_url" IS NULL; +--> statement-breakpoint +ALTER TABLE "project" DROP COLUMN IF EXISTS "favicon"; +--> statement-breakpoint +ALTER TABLE "project" DROP COLUMN IF EXISTS "favicon_checked_at"; +--> statement-breakpoint +ALTER TABLE "project_app" DROP COLUMN IF EXISTS "favicon"; +--> statement-breakpoint +ALTER TABLE "project_app" DROP COLUMN IF EXISTS "favicon_checked_at"; diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json index d7a930769..71b3a5a43 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -1618,6 +1618,20 @@ "when": 1794373201000, "tag": "0230_restore_workspace_security_fields", "breakpoints": true + }, + { + "idx": 231, + "version": "7", + "when": 1794373202000, + "tag": "0231_project_icon_url", + "breakpoints": true + }, + { + "idx": 232, + "version": "7", + "when": 1794373203000, + "tag": "0232_project_icon_cleanup", + "breakpoints": true } ] } diff --git a/packages/db/src/dump-roundtrip.test.ts b/packages/db/src/dump-roundtrip.test.ts index de514bf69..a2637d446 100644 --- a/packages/db/src/dump-roundtrip.test.ts +++ b/packages/db/src/dump-roundtrip.test.ts @@ -274,6 +274,35 @@ describe("whole-instance dump → restore round trip", () => { }, ); + it.each(["legacy", "group", "custom", "cleared"] as const)( + "restores %s project images into the single iconUrl field", + async (mode) => { + const original = await dumpSubgraph({ kind: "instance" }); + const archive = JSON.parse(JSON.stringify(original)) as typeof original; + const project = archive.tables.project![0]!; + project.favicon = "https://old.example.test/favicon.ico"; + project.faviconCheckedAt = "2026-11-01T12:00:00Z"; + const group = archive.tables.project_app!.find((row) => row.id === project.groupId)!; + group.favicon = "https://cdn.example.test/group.svg"; + if (mode === "custom") project.iconUrl = "https://cdn.example.test/custom.svg"; + else if (mode === "cleared") project.iconUrl = null; + else delete project.iconUrl; + if (mode === "group") project.favicon = null; + const expected = mode === "custom" ? project.iconUrl : mode === "cleared" ? null : mode === "group" ? group.favicon : project.favicon; + try { + await restoreSubgraph(archive, { mode: "wipe" }); + const restored = await dumpSubgraph({ kind: "instance" }); + expect(restored.tables.project![0]!.iconUrl).toBe(expected); + expect(restored.tables.project![0]).not.toHaveProperty("favicon"); + expect(restored.tables.project![0]).not.toHaveProperty("faviconCheckedAt"); + expect(restored.tables.project_app![0]).not.toHaveProperty("favicon"); + expect(project.faviconCheckedAt).toBe("2026-11-01T12:00:00Z"); + } finally { + await restoreSubgraph(original, { mode: "wipe" }); + } + }, + ); + it("lets callers include follow-up work in the same atomic restore transaction", async () => { const projectSpec = topoOrderedTables().find((s) => s.sqlName === "project")!; const [before] = (await db.select().from(projectSpec.table)) as Array>; diff --git a/packages/db/src/dump.ts b/packages/db/src/dump.ts index cd320b1c9..731d8d9ba 100644 --- a/packages/db/src/dump.ts +++ b/packages/db/src/dump.ts @@ -1773,6 +1773,11 @@ export async function restoreSubgraphInTransaction( } } + // Resolve legacy image inheritance once for large instance archives. + const legacyGroupIcons = new Map( + (dump.tables.project_app ?? []).map((group) => [group.id, group.favicon]), + ); + // Pre-compute the encrypted-column specs keyed by table so the insert // loop below can redact those fields without re-scanning ENCRYPTED_COLUMNS // per row. Redaction on restore is REQUIRED (not optional like the @@ -1835,6 +1840,11 @@ export async function restoreSubgraphInTransaction( const prepared = rows.map((r) => { const { row: next, dropped } = filterRowToKnownColumns(r, knownCols); for (const d of dropped) droppedCols.add(d); + // Archives from before iconUrl used a discovered favicon. Honor an explicit + // iconUrl (including a cleared null) when the archive already has the field. + if (spec.sqlName === "project" && !Object.hasOwn(r, "iconUrl")) { + next.iconUrl = r.favicon ?? legacyGroupIcons.get(r.groupId) ?? null; + } // Older instance dumps predate per-factor confirmation. Preserve active // authenticators while keeping unfinished enrollments unconfirmed. if (spec.sqlName === "two_factor" && !Object.hasOwn(r, "verified")) { diff --git a/packages/db/src/migrate-chain.test.ts b/packages/db/src/migrate-chain.test.ts index 6c50eecbb..de5aaf92b 100644 --- a/packages/db/src/migrate-chain.test.ts +++ b/packages/db/src/migrate-chain.test.ts @@ -268,6 +268,47 @@ describe("migration chain applies to an existing, populated database", () => { expect(await appliedMigrations(client)).toBe(total); }); + test("consolidates saved images into icon_url and preserves explicit icons and resets on retry", async () => { + const cutoff = journal.entries.findIndex((entry) => entry.tag === "0232_project_icon_cleanup"); + expect(journal.entries[cutoff - 1]?.tag).toBe("0231_project_icon_url"); + const legacy = migrationsPrefix(cutoff); + const { client, db } = await freshDb(); + try { + await migrate(db, { migrationsFolder: legacy }); + await client.exec(` + INSERT INTO organization (id, name) VALUES ('org', 'Existing organization'); + INSERT INTO project_app (id, organization_id, name, slug, favicon) VALUES + ('group', 'org', 'Apps', 'apps', NULL), + ('group-icon', 'org', 'Group image', 'group-image', 'https://cdn.example.test/group.svg'); + INSERT INTO project (id, organization_id, app_id, environment_slug, name, slug, favicon, icon_url) VALUES + ('legacy', 'org', 'group', 'legacy', 'Legacy', 'legacy', 'https://app.example.test/favicon.ico', NULL), + ('custom', 'org', 'group', 'custom', 'Custom', 'custom', 'https://old.example.test/favicon.ico', 'https://cdn.example.test/custom.svg'), + ('empty', 'org', 'group', 'empty', 'Empty', 'empty', NULL, NULL), + ('inherited', 'org', 'group-icon', 'inherited', 'Inherited', 'inherited', NULL, NULL); + `); + const projects = (await client.query>("SELECT * FROM project ORDER BY id")).rows; + const groups = (await client.query>("SELECT * FROM project_app ORDER BY id")).rows; + await migrate(db, { migrationsFolder: MIGRATIONS_DIR }); + expect((await client.query("SELECT * FROM project ORDER BY id")).rows).toEqual( + projects.map(({ favicon, favicon_checked_at: _, ...project }) => ({ + ...project, + icon_url: project.icon_url ?? favicon ?? (project.app_id === "group-icon" ? "https://cdn.example.test/group.svg" : null), + })), + ); + expect((await client.query("SELECT * FROM project_app ORDER BY id")).rows).toEqual( + groups.map(({ favicon: _, favicon_checked_at: _checked, ...group }) => group), + ); + await client.exec("UPDATE project SET icon_url = NULL WHERE id = 'legacy'"); + const customized = (await client.query("SELECT * FROM project ORDER BY id")).rows; + await migrate(db, { migrationsFolder: MIGRATIONS_DIR }); + expect((await client.query("SELECT * FROM project ORDER BY id")).rows).toEqual(customized); + expect(await appliedMigrations(client)).toBe(total); + } finally { + await client.close(); + rmSync(legacy, { recursive: true, force: true }); + } + }); + test("adds runtime roles after the applied lifecycle migration without changing existing releases", async () => { const cutoff = journal.entries.findIndex((entry) => entry.tag === "0192_runtime_roles"); expect(journal.entries[cutoff - 1]?.tag).toBe("0191_project_lifecycle_operation"); @@ -286,7 +327,7 @@ describe("migration chain applies to an existing, populated database", () => { await migrate(db, { migrationsFolder: MIGRATIONS_DIR }); expect((await client.query("SELECT * FROM project")).rows).toEqual( - projects.map((project) => ({ ...project, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false })), + projects.map(({ favicon, favicon_checked_at: _, ...project }) => ({ ...project, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false, icon_url: favicon })), ); expect((await client.query("SELECT * FROM deployment")).rows).toEqual( deployments.map((deployment) => ({ @@ -332,7 +373,7 @@ describe("migration chain applies to an existing, populated database", () => { expect(await db.select().from(schema.instanceController)).toEqual([]); expect(await db.select().from(schema.instanceHandoff)).toEqual([]); expect((await client.query("SELECT * FROM project")).rows).toEqual( - projects.map((project) => ({ ...project, github_checks: null, runtime_version: null, runtime_image: null, lifecycle_operation: null, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false })), + projects.map(({ favicon, favicon_checked_at: _, ...project }) => ({ ...project, github_checks: null, runtime_version: null, runtime_image: null, lifecycle_operation: null, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false, icon_url: favicon })), ); expect( (await client.query("SELECT * FROM drizzle.__drizzle_migrations ORDER BY id")).rows.slice( @@ -530,11 +571,12 @@ describe("migration chain applies to an existing, populated database", () => { expect(managed).toHaveLength(2); for (const row of (await selectProjects()).rows) { const old = original.find((project) => project.id === row.id)!; - const { cloud_workspace_id: _native, cloud_archive_strategy: _archive, ...previous } = old as typeof old & Record; + const { cloud_workspace_id: _native, cloud_archive_strategy: _archive, favicon, favicon_checked_at: _checked, ...previous } = old as typeof old & Record; expect(row).toEqual({ ...previous, runtime_version: null, runtime_image: null, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false, + icon_url: favicon, cloud_promotion: null, lifecycle_operation: null, cloud_static_hosting: "pages", diff --git a/packages/db/src/repos/deployment.repo.ts b/packages/db/src/repos/deployment.repo.ts index add5653d8..9defd12db 100644 --- a/packages/db/src/repos/deployment.repo.ts +++ b/packages/db/src/repos/deployment.repo.ts @@ -626,7 +626,7 @@ export function createDeploymentRepo(db: Database, encryption: ConfigurationEncr async listHistoryProjects(organizationId: string) { return db.selectDistinct({ id: project.id, name: project.name, - activeDeploymentId: project.activeDeploymentId, favicon: project.favicon, + activeDeploymentId: project.activeDeploymentId, iconUrl: project.iconUrl, }).from(project).innerJoin(deployment, eq(deployment.projectId, project.id)) .where(and(eq(project.organizationId, organizationId), eq(deployment.organizationId, organizationId))) .orderBy(project.name, project.id); diff --git a/packages/db/src/repos/project.repo.ts b/packages/db/src/repos/project.repo.ts index ffe4aa891..4488d9649 100644 --- a/packages/db/src/repos/project.repo.ts +++ b/packages/db/src/repos/project.repo.ts @@ -661,25 +661,6 @@ export function createProjectRepo(db: Database, encryption: ConfigurationEncrypt }).where(eq(project.id, id)); }, - /** Update favicon cache metadata without touching the user-visible updatedAt field. */ - async updateFaviconCache( - id: string, - data: { favicon?: string | null; faviconCheckedAt?: Date | null }, - ) { - const patch: Partial = {}; - - if (Object.prototype.hasOwnProperty.call(data, "favicon")) { - patch.favicon = data.favicon ?? null; - } - if (Object.prototype.hasOwnProperty.call(data, "faviconCheckedAt")) { - patch.faviconCheckedAt = data.faviconCheckedAt ?? null; - } - - if (Object.keys(patch).length === 0) return; - - await db.update(project).set(patch).where(eq(project.id, id)); - }, - /** Soft-delete a project */ async softDelete(id: string) { await withProjectConfigurationWrite(db, eq(project.id, id), async (tx) => tx diff --git a/packages/db/src/schema/project.ts b/packages/db/src/schema/project.ts index 023ae9fe3..098ae3a3d 100644 --- a/packages/db/src/schema/project.ts +++ b/packages/db/src/schema/project.ts @@ -69,10 +69,6 @@ export const projectGroup = pgTable("project_app", { gitUrl: text("git_url"), installationId: integer("installation_id"), - /** Shared favicon cache */ - favicon: text("favicon"), - faviconCheckedAt: timestamp("favicon_checked_at"), - deletedAt: timestamp("deleted_at"), createdAt: timestamp("created_at").notNull().defaultNow(), updatedAt: timestamp("updated_at").notNull().defaultNow(), @@ -499,10 +495,8 @@ export const project = pgTable( * nobody opted into paying for this, so nobody keeps paying for it silently. */ collectPaths: boolean("collect_paths").notNull().default(false), - /** Auto-detected favicon URL from the deployed site */ - favicon: text("favicon"), - /** Last time favicon detection was attempted for this project */ - faviconCheckedAt: timestamp("favicon_checked_at"), + /** Project display image, managed in project settings. */ + iconUrl: text("icon_url"), /** Soft delete */ deletedAt: timestamp("deleted_at"), /** diff --git a/packages/platform/src/engine/lib/auth.ts b/packages/platform/src/engine/lib/auth.ts index 0528fa7fb..b51d75b0c 100644 --- a/packages/platform/src/engine/lib/auth.ts +++ b/packages/platform/src/engine/lib/auth.ts @@ -1,3 +1,4 @@ +import { isImageUrl } from "@repo/core"; import { diagnostics as errorDiagnostics } from "@repo/core/diagnostics"; import { organizationOptions, isSaasDeployment } from "./organization-lifecycle"; import { betterAuth, type User } from "better-auth"; @@ -278,6 +279,14 @@ export const auth = betterAuth({ /* ---------- Database hooks ---------- */ databaseHooks: { user: { + update: { + before: async (user) => { + if (user.image === undefined) return; + const image = typeof user.image === "string" ? user.image.trim() || null : user.image; + if (image !== null && !isImageUrl(image)) throw new APIError("BAD_REQUEST", { message: "Avatar URL must be an HTTP or HTTPS URL without credentials." }); + return { data: { ...user, image } }; + }, + }, create: { before: async (user, ctx) => { const denyCreation = (message: string): never => { diff --git a/packages/platform/src/engine/lib/cloud/project-promotion.ts b/packages/platform/src/engine/lib/cloud/project-promotion.ts index 62284ce18..20a1679e6 100644 --- a/packages/platform/src/engine/lib/cloud/project-promotion.ts +++ b/packages/platform/src/engine/lib/cloud/project-promotion.ts @@ -45,8 +45,6 @@ export function projectPromotionDigest(dump: DatabaseDump): string { delete row.deletionInProgress; delete row.lifecycleOperation; delete row.updatedAt; - delete row.favicon; - delete row.faviconCheckedAt; } for (const [name, rows] of Object.entries(tables)) { tables[name] = rows diff --git a/packages/platform/src/engine/lib/favicon-detector.ts b/packages/platform/src/engine/lib/favicon-detector.ts deleted file mode 100644 index f0eb03024..000000000 --- a/packages/platform/src/engine/lib/favicon-detector.ts +++ /dev/null @@ -1,159 +0,0 @@ -/** - * Favicon detection - check if a deployed site has a favicon. - * - * Called asynchronously on project reads when the favicon cache is stale. - * Simply checks /favicon.ico - the universal standard. - * - * Returns an absolute URL string or null. - */ - -import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics"; -import { repos } from "@repo/db"; -import { env } from "../config/env"; -import { safeFetch } from "./safe-fetch"; -import { trackBackgroundWork } from "./background-work"; - -const FETCH_TIMEOUT = 8_000; -const FAVICON_REFRESH_TTL_MS = 24 * 60 * 60 * 1000; -const inFlightRefreshes = new Set(); - -interface FaviconRefreshProject { - id: string; - slug?: string | null; - activeDeploymentId?: string | null; - favicon?: string | null; - faviconCheckedAt?: Date | string | null; -} - -interface RefreshOptions { - hostname?: string | null; -} - -function normalizeSiteUrl(siteUrlOrHostname: string): string { - const trimmed = siteUrlOrHostname.trim().replace(/\/$/, ""); - if (!trimmed) return ""; - if (/^https?:\/\//i.test(trimmed)) return trimmed; - return `https://${trimmed}`; -} - -function isRefreshDue(project: FaviconRefreshProject): boolean { - if (!project.faviconCheckedAt) return true; - - const checkedAt = new Date(project.faviconCheckedAt); - if (Number.isNaN(checkedAt.getTime())) return true; - - return Date.now() - checkedAt.getTime() >= FAVICON_REFRESH_TTL_MS; -} - -async function resolvePreferredSiteUrl( - project: FaviconRefreshProject, - options?: RefreshOptions, -): Promise { - if (options?.hostname?.trim()) { - return normalizeSiteUrl(options.hostname); - } - - const primaryDomain = await repos.domain.getPrimaryByProject(project.id); - if (primaryDomain?.verified && primaryDomain.hostname?.trim()) { - return normalizeSiteUrl(primaryDomain.hostname); - } - - return null; -} - -async function probeFavicon(siteUrl: string): Promise { - const base = normalizeSiteUrl(siteUrl); - if (!base) return null; - - const faviconUrl = `${base}/favicon.ico`; - - const tryProbe = async (method: "HEAD" | "GET") => { - // SSRF-safe: `base` is a project's (attacker-controllable-DNS) domain. Pin the - // resolved IP; reject internal targets on the multi-tenant SaaS, allow the - // operator's own LAN on self-hosted. - const res = await safeFetch(faviconUrl, { - method, - timeoutMs: FETCH_TIMEOUT, - allowHttp: true, - allowPrivate: !env.CLOUD_MODE, - maxRedirects: 3, - }); - - if (!res.ok) { - return null; - } - - const ct = res.headers["content-type"] ?? ""; - if (ct.startsWith("image/") || ct === "application/octet-stream") { - return faviconUrl; - } - - return null; - }; - - const headResult = await tryProbe("HEAD"); - if (headResult) { - return headResult; - } - - const getResult = await tryProbe("GET"); - if (getResult) { - return getResult; - } - - return null; -} - -export function refreshProjectFaviconIfStale( - project: FaviconRefreshProject, - options?: RefreshOptions, -): void { - if (!project.activeDeploymentId || !isRefreshDue(project)) { - return; - } - - if (inFlightRefreshes.has(project.id)) { - return; - } - - inFlightRefreshes.add(project.id); - void trackBackgroundWork((async () => { - const siteUrl = await resolvePreferredSiteUrl(project, options); - if (!siteUrl) { - return; - } - - await detectAndStoreFavicon(project.id, siteUrl); - })() - .catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "platform/engine/lib/favicon-detector"); return undefined; }) - .finally(() => { - inFlightRefreshes.delete(project.id); - })); -} - -/** - * Detect and store the favicon for a deployed project. - * Best-effort: update the cache timestamp on every attempt, but only replace - * the stored favicon URL when the fetch succeeds. - */ -export async function detectAndStoreFavicon(projectId: string, siteUrl: string): Promise { - const checkedAt = new Date(); - - try { - const faviconUrl = await probeFavicon(siteUrl); - if (faviconUrl) { - await repos.project.updateFaviconCache(projectId, { - favicon: faviconUrl, - faviconCheckedAt: checkedAt, - }); - return; - } - } catch (diagnosticFailure) { - observeCaughtError(diagnosticFailure, "platform/engine/lib/favicon-detector"); - // Best-effort - don't break anything if this fails - } - - await repos.project.updateFaviconCache(projectId, { - faviconCheckedAt: checkedAt, - }).catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "platform/engine/lib/favicon-detector"); return undefined; }); -} diff --git a/packages/platform/src/engine/lib/public-endpoints.ts b/packages/platform/src/engine/lib/public-endpoints.ts index 91b900d5d..01f05dd69 100644 --- a/packages/platform/src/engine/lib/public-endpoints.ts +++ b/packages/platform/src/engine/lib/public-endpoints.ts @@ -982,7 +982,7 @@ export interface ProjectAccess { /** The project's ONE canonical public domain row, chosen over ALL rows * (project-level AND service-scoped): a verified primary, else the first * verified row, else none. The single primary-selection rule the detail Access - * URL, the list card's primaryDomain, and the favicon refresh all share, so + * URL and the list card's primaryDomain share, so * those surfaces can never disagree on which domain is "the" one. */ export function pickCanonicalDomainRow & { hostname?: string }>( rows: T[] | null | undefined, diff --git a/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts b/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts index 061720d5a..f276201b8 100644 --- a/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts +++ b/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts @@ -38,8 +38,6 @@ import { sanitizeStorableStrings, sliceWithoutSplittingPair, } from "./build-log-sanitize"; -import { detectAndStoreFavicon } from "../../lib/favicon-detector"; -import { trackBackgroundWork } from "../../lib/background-work"; import { onWebmailDeployed } from "../mail/webmail/webmail-install.service"; import { computeCleanupKeepSet } from "../projects/cleanup-keep-set"; import { deploymentResourceFailure, type DeploymentFailureMeta } from "./resource-failure"; @@ -1065,11 +1063,6 @@ export async function onSuccess( }, ); - // Async favicon detection - don't block the deploy response - if (result.url) { - void trackBackgroundWork(detectAndStoreFavicon(project.id, result.url)); - } - // Webmail on Openship Cloud, routed on the mail server's own `mail.`: // the mail VPS proxies that hostname to the cloud URL, which can only be // registered once the URL exists. Await it so the deployment execution lease diff --git a/packages/platform/src/engine/modules/deployments/deployment.service.ts b/packages/platform/src/engine/modules/deployments/deployment.service.ts index 2efe6c992..4b5cbb34b 100644 --- a/packages/platform/src/engine/modules/deployments/deployment.service.ts +++ b/packages/platform/src/engine/modules/deployments/deployment.service.ts @@ -89,9 +89,7 @@ export async function listDeployments( ...d, isActive: d.id === activeId, projectName: project.name, - // Project favicon → the dashboard uses it as the row's logo instead - // of the framework/Docker glyph. - favicon: project.favicon ?? null, + iconUrl: project.iconUrl ?? null, })), }; } @@ -110,8 +108,7 @@ export async function listDeployments( ...d, projectName: proj?.name ?? "Unknown", isActive: proj?.activeDeploymentId === d.id, - // Project favicon → dashboard row logo (see listByProject above). - favicon: proj?.favicon ?? null, + iconUrl: proj?.iconUrl ?? null, }; }); diff --git a/packages/platform/src/engine/modules/domains/domain.service.ts b/packages/platform/src/engine/modules/domains/domain.service.ts index 4e3904afe..91af17542 100644 --- a/packages/platform/src/engine/modules/domains/domain.service.ts +++ b/packages/platform/src/engine/modules/domains/domain.service.ts @@ -108,7 +108,7 @@ export async function getDomain(ctx: RequestContext, domainId: string) { /** * Make a domain the project's primary. Primary is the project's canonical - * hostname — what favicon detection, analytics, and the dashboard's project + * hostname — what analytics and the dashboard's project * link resolve to (getPrimaryByProject). setPrimary unsets any prior primary * for the project and marks this one, so exactly one row stays primary. * Survives redeploys: per-service route registration preserves an existing diff --git a/packages/platform/src/engine/modules/migration/migration.orchestrator.ts b/packages/platform/src/engine/modules/migration/migration.orchestrator.ts index 15abd2c4e..0ff935b26 100644 --- a/packages/platform/src/engine/modules/migration/migration.orchestrator.ts +++ b/packages/platform/src/engine/modules/migration/migration.orchestrator.ts @@ -691,7 +691,7 @@ class MigrationOrchestratorImpl { id: `dmr_${crypto.randomUUID()}`, organizationId: ctx.organizationId, targetServerId: target.id, - projectName: plan.project.name, + projectName: plan.projectName, serviceNames: plan.services.map((s) => s.create.name), status: "queued", mode: "provider_import", diff --git a/packages/platform/src/engine/modules/migration/platform-import-plan.ts b/packages/platform/src/engine/modules/migration/platform-import-plan.ts index 1f4d3cf13..302c860e0 100644 --- a/packages/platform/src/engine/modules/migration/platform-import-plan.ts +++ b/packages/platform/src/engine/modules/migration/platform-import-plan.ts @@ -1,5 +1,11 @@ import { createHash, randomUUID, randomBytes } from "node:crypto"; -import { AppError, normalizeAliasStrict, slugify, normalizeProjectRootDirectory, validateImageReference } from "@repo/core"; +import { + AppError, + normalizeAliasStrict, + slugify, + normalizeProjectRootDirectory, + validateImageReference, +} from "@repo/core"; import type { PlatformDiscovery, PlatformMigrationSource, @@ -24,7 +30,7 @@ import { } from "./providers/types"; import { discoverExternalDatabases } from "./providers/external-databases"; import { resolveRailwayBindings } from "./providers/railway-wiring"; -import { platformImportProject } from "./platform-import-project"; +import { platformImportProjects, type PlannedImportProject } from "./platform-import-project"; export interface ImportBinding { sourceId: string; @@ -46,7 +52,8 @@ export interface PrivateImportPlan { inventory: ProviderInventory; fingerprint: string; targetServerId: string; - project: TEnsureProjectBody; + projectName: string; + projects: PlannedImportProject[]; services: PlannedImportService[]; requiresWritePause: boolean; requiresWorkerPause: boolean; @@ -528,7 +535,7 @@ export async function reviewPlatform( const projectName = (input.projectName ?? inventory.projectName).trim(); if (!slugify(projectName)) throw new AppError("Choose a name for the imported project", 400, "IMPORT_NAME_INVALID"); - const project = platformImportProject(projectName, input.targetServerId, services); + const projects = platformImportProjects(projectName, input.targetServerId, services); const plan: PrivateImportPlan = { id: randomUUID(), organizationId: ctx.organizationId, @@ -536,7 +543,8 @@ export async function reviewPlatform( inventory: draft.inventory, fingerprint: inventoryFingerprint(draft.inventory), targetServerId: input.targetServerId, - project, + projectName, + projects, services, ...(inventory.provider === "railway" ? { sourceControl: "railway-project" as const } : {}), requiresWritePause: services.some( @@ -559,6 +567,10 @@ export async function reviewPlatform( planId: plan.id, ...publicInventory({ ...inventory, services: services.map((s) => s.source) }), projectName, + projects: projects.map(({ create, sourceIds }) => ({ + name: create.name, + serviceIds: sourceIds, + })), targetServerId: plan.targetServerId, requiresWritePause: plan.requiresWritePause, requiresWorkerPause: plan.requiresWorkerPause, @@ -572,8 +584,12 @@ export async function loadReviewedImport( id: string, ): Promise { const plan = await get(ctx, "plan", id); - if (!plan.project) - throw new AppError("Review this import again before starting it.", 409, "IMPORT_REVIEW_EXPIRED"); + if (!plan.projects?.length) + throw new AppError( + "Review this import again before starting it.", + 409, + "IMPORT_REVIEW_EXPIRED", + ); if (!plan.ready) throw new AppError("Resolve the import review before starting", 409, "IMPORT_NOT_READY"); const access = await getProviderAccess(ctx.organizationId, plan.inventory.source.connectionId); diff --git a/packages/platform/src/engine/modules/migration/platform-import-project.ts b/packages/platform/src/engine/modules/migration/platform-import-project.ts index 61e7b6e53..3415e69fe 100644 --- a/packages/platform/src/engine/modules/migration/platform-import-project.ts +++ b/packages/platform/src/engine/modules/migration/platform-import-project.ts @@ -3,15 +3,83 @@ import type { TCreateServiceBody, TEnsureProjectBody, } from "@repo/contracts"; +import { slugify } from "@repo/core"; import type { PlannedImportService } from "./platform-import-plan"; +export interface PlannedImportProject { + create: TEnsureProjectBody; + sourceIds: string[]; +} + +/** A native project has one Git checkout. Keep compatible environments together; + * otherwise give each service its own project and use ordinary private links. */ +export function platformImportProjects( + name: string, + serverId: string, + services: PlannedImportService[], +): PlannedImportProject[] { + const imports = services.filter((service) => service.data !== "external"); + const sources = new Set( + imports + .filter((service) => service.create.gitRepo) + .map((service) => + JSON.stringify([ + service.create.gitProvider, + service.create.gitOwner, + service.create.gitRepo, + service.create.gitBranch, + service.source.commit, + ]), + ), + ); + const groups = sources.size > 1 ? imports.map((service) => [service]) : [imports]; + if (groups.length > 1) { + for (const service of imports) { + const keys = new Set(service.bindings.map((binding) => binding.envKey)); + for (const key of keys) { + const bindings = service.bindings.filter((binding) => binding.envKey === key); + if (new Set(bindings.map((binding) => binding.sourceId)).size > 1) { + service.source.blockers.push( + `Review ${key}: use a separate connection variable for each private service when importing into separate projects.`, + ); + } + for (const binding of bindings) { + if ( + Object.hasOwn(service.environment, key) && + binding.valueTemplate === undefined && + bindings.length === 1 + ) + service.source.blockers.push( + `Review ${key}: its private host cannot be safely converted into a project connection. Provide a destination value explicitly.`, + ); + const dependency = imports.find((candidate) => candidate.source.id === binding.sourceId); + if (dependency && !(dependency.source.port || dependency.create.port)) + service.source.blockers.push( + `Review ${key}: ${dependency.create.name} needs a private listener port for its project connection.`, + ); + } + } + } + } + return groups.map((group) => ({ + create: platformImportProject( + groups.length === 1 + ? name + : `${slugify(name).slice(0, 100 - group[0].create.name.length - 1)}-${group[0].create.name}`, + serverId, + group, + ), + sourceIds: group.map((service) => service.source.id), + })); +} + function dependencyNames(service: PlannedImportService, services: PlannedImportService[]) { return [ ...new Set( - service.bindings.map( - (binding) => - services.find((dependency) => dependency.source.id === binding.sourceId)!.create.name, - ), + service.bindings.flatMap((binding) => { + const dependency = services.find((candidate) => candidate.source.id === binding.sourceId); + return dependency ? [dependency.create.name] : []; + }), ), ]; } @@ -37,9 +105,8 @@ export function platformImportRoutes(services: PlannedImportService[]): Migratio ); } -/** Translate reviewed provider recipes into the same project and service inputs - * used by native imports. A provider project never becomes several projects. */ -export function platformImportProject( +/** Translate one compatible group into ordinary project and service inputs. */ +function platformImportProject( name: string, serverId: string, services: PlannedImportService[], @@ -53,15 +120,6 @@ export function platformImportProject( service.source.blockers.push( "This repository declares project-wide release commands. Review a service-compatible release recipe before importing; grouped imports cannot silently skip those commands.", ); - if ( - service.create.gitOwner !== first.create.gitOwner || - service.create.gitRepo !== first.create.gitRepo || - service.source.commit !== first.source.commit - ) { - service.source.blockers.push( - "These services use different repositories or deployed revisions. A native OpenShip project has one Git source; align the source services before importing them together.", - ); - } } return { name, diff --git a/packages/platform/src/engine/modules/migration/platform-import-worker.ts b/packages/platform/src/engine/modules/migration/platform-import-worker.ts index a6017cf9a..b38ccaaf4 100644 --- a/packages/platform/src/engine/modules/migration/platform-import-worker.ts +++ b/packages/platform/src/engine/modules/migration/platform-import-worker.ts @@ -1,5 +1,5 @@ import { AppError, ConflictError, ValidationError } from "@repo/core"; -import { repos } from "@repo/db"; +import { repos, type Service } from "@repo/db"; import type { ExecutionContext } from "../../../context"; import type { PrivateImportPlan, PlannedImportService } from "./platform-import-plan"; import { ensureProject } from "../projects/project-crud.service"; @@ -20,6 +20,7 @@ import { import { verifyPlatformDeployment } from "./platform-import-health"; import { withProjectRuntimeLock } from "../../lib/project-runtime-lock"; import { prepareMigrationTarget } from "./migration-runtime"; +import { createConnection } from "../projects/project-connection.service"; export interface ImportLifecycle { signal: AbortSignal; @@ -76,13 +77,29 @@ export async function executePlatformImport( resourceId: plan.targetServerId, action: "write", }); - if (!plan.project) + if (!plan.projects?.length) throw new AppError( "Review this import again before starting it.", 409, "IMPORT_REVIEW_EXPIRED", ); const services = orderedImports(plan.services); + const destinations = plan.projects.map((project) => ({ + ...project, + services: services.filter((service) => project.sourceIds.includes(service.source.id)), + projectId: "", + })); + const destinationFor = new Map( + destinations.flatMap((destination) => + destination.sourceIds.map((id) => [id, destination] as const), + ), + ); + if (services.some((service) => !destinationFor.has(service.source.id))) + throw new AppError( + "Review this import again before starting it.", + 409, + "IMPORT_REVIEW_EXPIRED", + ); lifecycle.log("Checking the complete project's storage and destination configuration"); await preflightPlatformData(services, lifecycle.signal); await prepareMigrationTarget(ctx.organizationId, plan.targetServerId, runId, { @@ -91,44 +108,61 @@ export async function executePlatformImport( }); lifecycle.signal.throwIfAborted(); await lifecycle.phase("adopting"); - lifecycle.log(`Creating project ${plan.project.name}`); - const { project_id: projectId } = await ensureProject(plan.project, ctx.organizationId, ctx, { - mustCreate: true, - }); - for (const service of services) { - if ( - !(await repos.dockerMigrationRun.bindImportedProject( - runId, - ctx.organizationId, - service.source.id, - projectId, - )) - ) - throw new AppError( - "The import was cancelled while creating its project. Its saved configuration was retained.", - 409, - "IMPORT_ADMISSION_CLOSED", - ); - } - await repos.project.update(projectId, { autoDeploy: false, runtimeMode: "docker" }); - for (const service of services) { + const bySource = new Map(); + for (const destination of destinations) { lifecycle.signal.throwIfAborted(); - if (!service.create.services?.length) - await createService(ctx, projectId, platformImportSourceService(service, services)); - } - // Use the same pending-domain and ownership path as server/Docker migration. - // Validate every route before pausing Railway or copying data. Deployment will - // reconcile routing normally; neither this step nor import changes external DNS. - try { - await saveMigrationRoutes(ctx, projectId, platformImportRoutes(services), lifecycle.log); - } catch (error) { - if (error instanceof ValidationError || error instanceof ConflictError) - throw new AppError(error.message, error.statusCode, "IMPORT_DOMAIN_REVIEW_REQUIRED"); - throw error; - } - const rows = await repos.service.listByProject(projectId); - const bySource = new Map( - services.map((service) => { + lifecycle.log(`Creating project ${destination.create.name}`); + const { project_id: projectId } = await ensureProject( + destination.create, + ctx.organizationId, + ctx, + { + mustCreate: true, + }, + ); + destination.projectId = projectId; + for (const service of destination.services) { + if ( + !(await repos.dockerMigrationRun.bindImportedProject( + runId, + ctx.organizationId, + service.source.id, + projectId, + )) + ) + throw new AppError( + "The import was cancelled while creating its project. Its saved configuration was retained.", + 409, + "IMPORT_ADMISSION_CLOSED", + ); + } + await repos.project.update(projectId, { autoDeploy: false, runtimeMode: "docker" }); + for (const service of destination.services) { + lifecycle.signal.throwIfAborted(); + if (!service.create.services?.length) + await createService( + ctx, + projectId, + platformImportSourceService(service, destination.services), + ); + } + // Use the same pending-domain and ownership path as server/Docker migration. + // Validate every route before pausing Railway or copying data. Deployment will + // reconcile routing normally; neither this step nor import changes external DNS. + try { + await saveMigrationRoutes( + ctx, + projectId, + platformImportRoutes(destination.services), + lifecycle.log, + ); + } catch (error) { + if (error instanceof ValidationError || error instanceof ConflictError) + throw new AppError(error.message, error.statusCode, "IMPORT_DOMAIN_REVIEW_REQUIRED"); + throw error; + } + const rows = await repos.service.listByProject(projectId); + for (const service of destination.services) { const row = rows.find((row) => row.name === service.create.name); if (!row) throw new AppError( @@ -136,9 +170,9 @@ export async function executePlatformImport( 409, "IMPORT_TARGET_SERVICE_MISSING", ); - return [service.source.id, row] as const; - }), - ); + bySource.set(service.source.id, row); + } + } const checkpoint = async () => { const current = (await repos.dockerMigrationRun.findById(runId))?.recovery.providerImport; if (!current) @@ -152,7 +186,8 @@ export async function executePlatformImport( }, }); const saveEnvironment = async (sourceId: string, values: Record) => { - await mergeServiceEnvVars(ctx, projectId, bySource.get(sourceId)!.id, { + const target = bySource.get(sourceId)!; + await mergeServiceEnvVars(ctx, target.projectId, target.id, { environment: "production", deletes: [], upserts: Object.entries(values).map(([key, value]) => ({ @@ -163,16 +198,33 @@ export async function executePlatformImport( })), }); }; - for (const service of services) await saveEnvironment(service.source.id, service.environment); + const isCrossProject = (service: PlannedImportService, dependencyId: string) => + bySource.get(service.source.id)!.projectId !== bySource.get(dependencyId)?.projectId; + for (const service of services) { + // Native connections own project-level variables. A service-level copy would + // shadow the refreshed value on this deployment and subsequent redeploys. + const linkedKeys = new Set( + service.bindings + .filter((binding) => isCrossProject(service, binding.sourceId)) + .map((binding) => binding.envKey), + ); + await saveEnvironment( + service.source.id, + Object.fromEntries( + Object.entries(service.environment).filter(([key]) => !linkedKeys.has(key)), + ), + ); + } for (const service of services) { const values: Record = {}; for (const binding of service.bindings) { + if (isCrossProject(service, binding.sourceId)) continue; // Railway already resolved these against native service DNS during review. if (Object.hasOwn(service.environment, binding.envKey)) continue; const dependency = bySource.get(binding.sourceId); if (!dependency) throw new AppError("An import dependency is missing", 409, "IMPORT_DEPENDENCY_MISSING"); - const output = (await getAppConnectionView(ctx, projectId)).outputs.find( + const output = (await getAppConnectionView(ctx, dependency.projectId)).outputs.find( (output) => output.internal && output.sourceServiceId === dependency.id && output.value, ); if (!output) @@ -195,7 +247,7 @@ export async function executePlatformImport( await copyPlatformData({ runId, service, - projectId, + projectId: bySource.get(service.source.id)!.projectId, serviceId: bySource.get(service.source.id)!.id, deploymentId, signal: lifecycle.signal, @@ -205,11 +257,43 @@ export async function executePlatformImport( }; const deploy = async (selected: PlannedImportService[]) => { lifecycle.signal.throwIfAborted(); + const destination = destinationFor.get(selected[0].source.id)!; + const projectId = destination.projectId; + for (const service of selected) { + for (const binding of service.bindings) { + if (!isCrossProject(service, binding.sourceId)) continue; + lifecycle.signal.throwIfAborted(); + const dependency = bySource.get(binding.sourceId); + if (!dependency) + throw new AppError("An import dependency is missing", 409, "IMPORT_DEPENDENCY_MISSING"); + const output = (await getAppConnectionView(ctx, dependency.projectId)).outputs.find( + (output) => output.internal && output.sourceServiceId === dependency.id, + ); + if (!output) + throw new AppError( + "The imported dependency has no usable connection output", + 409, + "IMPORT_CONNECTION_NOT_READY", + ); + await createConnection( + ctx, + projectId, + { + sourceProjectId: dependency.projectId, + outputId: output.id, + envKey: binding.envKey, + mode: "internal", + valueTemplate: binding.valueTemplate, + }, + { defer: true }, + ); + } + } await lifecycle.phase("deploying"); lifecycle.log( - `Deploying ${plan.project.name}: ${selected.map((service) => service.create.name).join(", ")}`, + `Deploying ${destination.create.name}: ${selected.map((service) => service.create.name).join(", ")}`, ); - const source = services.find((service) => service.create.gitRepo)?.source; + const source = destination.services.find((service) => service.create.gitRepo)?.source; const result = await triggerDeployment(ctx, { projectId, serverId: plan.targetServerId, @@ -263,8 +347,19 @@ export async function executePlatformImport( } else await transfer(service); } } - const deploymentId = await deploy(services); - await verifyPlatformDeployment(projectId, deploymentId, lifecycle.signal); + // Multi-source plans have one service per project. The service order already + // guarantees each private dependency is deployed before its consumers connect. + const deployed = new Map(); + for (const service of services) { + const destination = destinationFor.get(service.source.id)!; + if (!deployed.has(destination.projectId)) + deployed.set(destination.projectId, await deploy(destination.services)); + } + await Promise.all( + [...deployed].map(([projectId, deploymentId]) => + verifyPlatformDeployment(projectId, deploymentId, lifecycle.signal), + ), + ); await repos.dockerMigrationRun.updateRecovery(runId, { providerImport: { ...(await checkpoint()), @@ -272,7 +367,7 @@ export async function executePlatformImport( }, }); lifecycle.log( - `${plan.project.name} imported with ${services.length} services; source data retained.`, + `${plan.projectName} imported with ${services.length} services in ${destinations.length} project(s); source data retained.`, ); } diff --git a/packages/platform/src/engine/modules/migration/providers/railway-wiring.ts b/packages/platform/src/engine/modules/migration/providers/railway-wiring.ts index 9aa69ae58..c880983a0 100644 --- a/packages/platform/src/engine/modules/migration/providers/railway-wiring.ts +++ b/packages/platform/src/engine/modules/migration/providers/railway-wiring.ts @@ -3,8 +3,8 @@ import type { ImportBinding, PlannedImportService } from "../platform-import-pla const privateHost = /\b[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.railway\.internal\b/gi; /** Keep Railway's resolved values, replacing provider DNS with the native service - * aliases inside the imported project. Dependencies describe deployment order; - * they do not create cross-project connections or publish database ports. */ + * aliases inside the imported project. Retain a host template for native private + * connections when the destination must span several projects. */ export function resolveRailwayBindings( service: PlannedImportService, selected: Map, @@ -26,10 +26,32 @@ export function resolveRailwayBindings( ); continue; } + const external = new Set( + dependencies + .filter(({ source }) => source !== service) + .map(({ source }) => source!.source.id), + ); + const template = + external.size === 1 && !value.includes("${host}") + ? value.replace(privateHost, (host) => { + const dependency = dependencies.find((candidate) => candidate.host === host)!; + return dependency.source === service ? service.create.internalAlias! : "${host}"; + }) + : undefined; let resolved = value; for (const { host, source } of dependencies) { resolved = resolved.replaceAll(host, source!.create.internalAlias!); - if (source !== service) bindings.push({ sourceId: source!.source.id, envKey: key }); + if ( + source !== service && + !bindings.some( + (binding) => binding.sourceId === source!.source.id && binding.envKey === key, + ) + ) + bindings.push({ + sourceId: source!.source.id, + envKey: key, + ...(template === undefined ? {} : { valueTemplate: template }), + }); // A resolved URL can declare an otherwise undiscovered private listener. // A hostname-only value still works through the project network's DNS. if (!source!.source.port) { @@ -38,7 +60,8 @@ export function resolveRailwayBindings( const port = Number( url.port || (url.protocol === "https:" ? 443 : url.protocol === "http:" ? 80 : 0), ); - if (url.hostname === host && port > 0 && port <= 65535) source!.source.port = port; + if (url.hostname.toLowerCase() === host.toLowerCase() && port > 0 && port <= 65535) + source!.source.port = port; } catch { /* diagnostics-ignore: arbitrary strings and hostname-only variables do not declare a listener. */ } diff --git a/packages/platform/src/engine/modules/projects/project-clone.service.ts b/packages/platform/src/engine/modules/projects/project-clone.service.ts index 6abf0122d..227c2d705 100644 --- a/packages/platform/src/engine/modules/projects/project-clone.service.ts +++ b/packages/platform/src/engine/modules/projects/project-clone.service.ts @@ -68,10 +68,6 @@ const PROJECT_FIELDS_NOT_CLONED = [ "deletionInProgress", "lifecycleOperation", "disabledAt", - // Detected from the live site; the copy has no site yet, so copying these would show the - // original's icon next to a project that has never served a request. - "favicon", - "faviconCheckedAt", // Routing that names specific hostnames. The copy starts with no domains (the confirm dialog // promises exactly this) — the originals stay with the project still serving them. "compositeRoutes", diff --git a/packages/platform/src/engine/modules/projects/project-connection.service.ts b/packages/platform/src/engine/modules/projects/project-connection.service.ts index 2678838fb..70a45f7cb 100644 --- a/packages/platform/src/engine/modules/projects/project-connection.service.ts +++ b/packages/platform/src/engine/modules/projects/project-connection.service.ts @@ -87,6 +87,8 @@ export async function listConnectionCandidates(ctx: RequestContext, projectId: s name: project.name, description: project.environmentName, appTemplateId: project.appTemplateId, + iconUrl: project.iconUrl, + framework: project.framework, clusterId: project.clusterId, }); } diff --git a/packages/platform/src/engine/modules/projects/project-crud.service.ts b/packages/platform/src/engine/modules/projects/project-crud.service.ts index d69a954e3..ebc17449d 100644 --- a/packages/platform/src/engine/modules/projects/project-crud.service.ts +++ b/packages/platform/src/engine/modules/projects/project-crud.service.ts @@ -13,8 +13,7 @@ import { type Project, type Server, } from "@repo/db"; -import { - slugify, +import { isImageUrl, slugify, runtimeProjectUpdate, assertRuntimeVersionTarget, AppError, @@ -1902,6 +1901,11 @@ async function updateProjectUnlocked( if (PROJECT_IDENTITY_KEYS.has(key)) continue; if (raw[key] !== undefined) update[key] = raw[key]; } + if (data.iconUrl !== undefined) { + const iconUrl = typeof data.iconUrl === "string" ? data.iconUrl.trim() || null : data.iconUrl; + if (iconUrl !== null && !isImageUrl(iconUrl)) throw new ValidationError("Icon URL must be an HTTP or HTTPS URL without credentials."); + update.iconUrl = iconUrl; + } Object.assign(update, runtimeProjectUpdate(p, update)); assertRuntimeVersionTarget({ ...p, ...update }); await assertBuildCommandUpdate(p, update); diff --git a/packages/platform/src/engine/modules/projects/project-home.operations.ts b/packages/platform/src/engine/modules/projects/project-home.operations.ts index a2b516850..671ff94d0 100644 --- a/packages/platform/src/engine/modules/projects/project-home.operations.ts +++ b/packages/platform/src/engine/modules/projects/project-home.operations.ts @@ -5,7 +5,6 @@ import { OperationError } from "@repo/contracts"; import type { ExecutionContext } from "../../../context"; import { presentProject } from "../../../projects"; import { authorization } from "../../lib/authorization"; -import { refreshProjectFaviconIfStale } from "../../lib/favicon-detector"; import { fetchOrgCloudProjects } from "../../lib/cloud/projects"; import { canProxyCloudResources } from "../../lib/cloud/scope"; import * as projectService from "./project.service"; @@ -86,10 +85,6 @@ export async function getProjectHome(ctx: ExecutionContext) { const primary = primariesByProject.get(original.id); const services = servicesByProject.get(original.id) ?? []; - refreshProjectFaviconIfStale(original, { - hostname: primary?.verified ? primary.hostname : null, - }); - return { ...presentProject(enriched), latestDeploymentId: latest?.id ?? null, diff --git a/packages/platform/src/engine/modules/projects/project-inspection.operations.ts b/packages/platform/src/engine/modules/projects/project-inspection.operations.ts index e04eefa03..bcabfcc9e 100644 --- a/packages/platform/src/engine/modules/projects/project-inspection.operations.ts +++ b/packages/platform/src/engine/modules/projects/project-inspection.operations.ts @@ -12,8 +12,7 @@ import { deploymentWorkload } from "../deployments/deployment-class"; import { serviceKind } from "../../lib/deployable-service"; import { maskDeploymentEnv } from "../../lib/secret-env"; import { listProjectRouteRows, resolveProjectRouteState } from "../domains/project-route.service"; -import { refreshProjectFaviconIfStale } from "../../lib/favicon-detector"; -import { pickCanonicalDomainRow, resolveProjectAccess } from "../../lib/public-endpoints"; +import { resolveProjectAccess } from "../../lib/public-endpoints"; import { readProjectRoutingClaims } from "../../lib/domain-claims"; import { serviceCustomHostnames } from "../../lib/routing-domains"; import { withDomainDiagnostics } from "../domains/domain-diagnostics"; @@ -107,9 +106,6 @@ export function createProjectInspectionOperations( domain: d.hostname, primary: d.isPrimary, })); - refreshProjectFaviconIfStale(project, { - hostname: pickCanonicalDomainRow(rawDomains)?.hostname ?? null, - }); // One server-computed access URL for every client surface. Derived from ALL // domain rows (service-scoped included, which the project-level publicEndpoints // resolver drops) + the effective deploy target, so a multi-service project diff --git a/packages/platform/src/engine/modules/projects/project.operations.ts b/packages/platform/src/engine/modules/projects/project.operations.ts index 5ed4def9a..b37b91194 100644 --- a/packages/platform/src/engine/modules/projects/project.operations.ts +++ b/packages/platform/src/engine/modules/projects/project.operations.ts @@ -10,7 +10,6 @@ import type { ExecutionContext } from "../../../context"; import { authorization } from "../../lib/authorization"; import { audit } from "../../lib/audit-emitter"; import { assertNativeSourcePath } from "../../native/source-policy"; -import { refreshProjectFaviconIfStale } from "../../lib/favicon-detector"; import { createProjectControls } from "./project-controls.operations"; import { clusterDatabaseEvents } from "./cluster-database.operations"; import { clusterVolumeEvents } from "./cluster-volume.operations"; @@ -88,7 +87,6 @@ export const projectDependencies: ProjectDependencies = { async get(ctx, id) { const service = await import("./project.service"); const project = await service.getProject(id, ctx.organizationId); - refreshProjectFaviconIfStale(project); return project; }, async update(ctx, id, input) { @@ -113,7 +111,6 @@ export const projectDependencies: ProjectDependencies = { }), }), }); - result.rows.forEach((row) => refreshProjectFaviconIfStale(row)); return { ...result, rows: result.rows.map((p) => ({ ...p, source: "local" })) }; }, recordAudit,