diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d57b1d29..2c1cae888 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,12 +6,6 @@ Runtime security notices use the signed feed published from `security-advisories ## Unreleased -### Authorization - -- Require administrative authority for admin operations across HTTP, SDK, native and - MCP access. Ordinary organization membership no longer grants host command execution; - token grants remain bounded by the user's current built-in role (#1783). - ### Cloud billing - Open checkout only when its payment URL is ready, with a visible fallback button. diff --git a/SECURITY.md b/SECURITY.md index 29b19ad67..87c2474ab 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -57,12 +57,6 @@ violation. ## Scope -Organization owners and administrators can perform host administration. Ordinary -members retain read/write access but cannot perform operations requiring `admin`, -including server shell execution. Restricted users require explicit resource grants; -scoped tokens also respect their user's current built-in role. Host commands execute -as the server's configured account, so delegate server administration accordingly. - In scope — all Openship components: - Managed Openship Cloud diff --git a/apps/api/src/lib/route-permission.ts b/apps/api/src/lib/route-permission.ts index 36deb84ae..42fc2697e 100644 --- a/apps/api/src/lib/route-permission.ts +++ b/apps/api/src/lib/route-permission.ts @@ -476,10 +476,13 @@ export function isPublicSpec(spec: RouteSpec): spec is PublicSpec { * Be precise about what that org-wide check buys, because it is easy to misread as * a defense it is not: it is strict only for a RESTRICTED principal (a scoped * token), which needs an all-GitHub grant to pass. For a session-authenticated - * owner/admin it is satisfied by broad membership authority. Ordinary members - * cannot satisfy an admin action. Per-repo read/write authority still belongs - * to `github-access.ts` at the token funnel and mutating service helpers; an - * org-wide tag never substitutes for that repository-specific check. + * owner/admin/**member** it is satisfied by bare membership — + * `roleAllowsResourceType` (permission.ts) ignores the action level for those + * roles, so `github:admin` is no higher a bar than `github:read`. The per-repo, + * read-vs-write authority for those principals is enforced ONLY by + * `github-access.ts` at the token funnel and at the mutating service helpers. + * Reading this comment as "the route layer already gates writes" is what let + * GHSA-hp2g-hw7g-f3vm sit behind a `github:admin` tag. * Paramless GitHub routes (/home, /status, /repos) also stay on the org-wide * path: `filterToolsForPrincipal` already hides them from a scoped token via * `perm.wildcard`, and their handlers narrow results through diff --git a/apps/api/src/modules/deployments/cancel-is-final.test.ts b/apps/api/src/modules/deployments/cancel-is-final.test.ts index 062a62169..841363250 100644 --- a/apps/api/src/modules/deployments/cancel-is-final.test.ts +++ b/apps/api/src/modules/deployments/cancel-is-final.test.ts @@ -43,6 +43,7 @@ vi.mock("@repo/platform/engine/modules/projects/cleanup-keep-set", () => ({ // Terminal-event side channels, each of which drags in auth/github/mail wiring. vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: mocks.notify } })); vi.mock("../../lib/audit", () => ({ audit: { recordAsync: vi.fn(), record: vi.fn() } })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn(async () => {}) })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(async () => {}), })); diff --git a/apps/api/src/modules/deployments/route-issues-warning.test.ts b/apps/api/src/modules/deployments/route-issues-warning.test.ts index 662d10f40..ef824d981 100644 --- a/apps/api/src/modules/deployments/route-issues-warning.test.ts +++ b/apps/api/src/modules/deployments/route-issues-warning.test.ts @@ -1,11 +1,12 @@ import { describe, expect, it, vi } from "vitest"; // The function under test is pure; everything else this module reaches (DB, SSE, -// notifications) is a side effect the assertion doesn't want. +// notifications, favicon probing) is a side effect the assertion doesn't want. // `@repo/adapters` stays REAL — `isEdgeDownMessage` is the branch being pinned. vi.mock("@repo/db", () => ({ repos: {} })); vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: {} })); vi.mock("../../lib/audit", () => ({ audit: {} })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn() })); vi.mock("@repo/platform/engine/modules/deployments/session-manager", () => ({})); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(), diff --git a/apps/api/src/modules/mcp/mcp-tools.ts b/apps/api/src/modules/mcp/mcp-tools.ts index 12cf298e5..030f788ab 100644 --- a/apps/api/src/modules/mcp/mcp-tools.ts +++ b/apps/api/src/modules/mcp/mcp-tools.ts @@ -76,8 +76,6 @@ export interface McpPrincipal { /** Resolved with the same persisted instance-authority policy as HTTP calls. */ instanceAdmin?: boolean; role: "owner" | "admin" | "member" | "restricted"; - /** For scoped tokens, the current membership in their bound organization. */ - membershipRole?: "owner" | "admin" | "member" | "restricted"; readOnly: boolean; /** Resource types the token holds grants on — only consulted when role === "restricted". */ grantedRootTypes: ReadonlySet; @@ -355,10 +353,6 @@ export function filterToolsForPrincipal( principal: McpPrincipal, ): McpToolDef[] { return tools.filter((t) => { - const action = assertedAction(t.perm.action); - const role = principal.membershipRole ?? principal.role; - if (role !== "restricted" && - !roleAllowsResourceType(role, t.perm.leaf as CheckedResourceType, action)) return false; // Read-only tokens can only call GET — the runtime gate rejects mutations by // HTTP method, so mirror that exactly rather than guessing from the tag. if (principal.readOnly && t.method !== "GET") return false; @@ -382,7 +376,9 @@ export function filterToolsForPrincipal( if (principal.role === "restricted" && !caps?.has(needed)) return false; } - if (principal.role !== "restricted") return true; + if (principal.role !== "restricted") { + return roleAllowsResourceType(principal.role, t.perm.leaf as CheckedResourceType); + } // "Own projects" scope: the create-capable project wildcard grant reaches the // dedicated create routes (POST /projects, POST /apps) and the project list // (which the caller filters to its self-created projects). Checked before the @@ -408,11 +404,11 @@ export function filterToolsForPrincipal( // A per-id grant still fails here, correctly: `wildcardGrants` holds only // resourceId "*" rows. const held = principal.wildcardGrants.get(t.perm.leaf); - return held ? permitsAction(held, action) : false; + return held ? permitsAction(held, assertedAction(t.perm.action)) : false; } if (principalHasGrantFor(principal.grantedRootTypes, t.perm.grantRoot)) return true; // Same mapping the permission check uses: `domain:admin` ⇒ `domains:delete`. - const capability = capabilityFor(t.perm.leaf, action); + const capability = capabilityFor(t.perm.leaf, assertedAction(t.perm.action)); return !!capability && !!principal.grantedCapabilities?.has(capability); }); } diff --git a/apps/api/src/modules/mcp/mcp.routes.ts b/apps/api/src/modules/mcp/mcp.routes.ts index 16d90eab1..9a80ecf68 100644 --- a/apps/api/src/modules/mcp/mcp.routes.ts +++ b/apps/api/src/modules/mcp/mcp.routes.ts @@ -128,7 +128,6 @@ async function resolveMcpCaller(token: string, headers: Headers): Promise { { sourceId: "db", envKey: "DATABASE_URL", - valueTemplate: "postgres://app:source-secret@${host}/app", }, ]); expect(privatePlan.services[1].environment.DATABASE_URL).toBe( "postgres://app:source-secret@database/app", ); - expect(privatePlan.projects[0].create.name).toBe("Project"); - expect(privatePlan.projects[0].create.services?.map((row) => row.name)).toEqual([ - "database", - "website", - ]); - expect(JSON.stringify(privatePlan.projects)).not.toContain("source-secret"); + expect(privatePlan.project.name).toBe("Project"); + expect(privatePlan.project.services?.map((row) => row.name)).toEqual(["database", "website"]); + expect(JSON.stringify(privatePlan.project)).not.toContain("source-secret"); expect(privatePlan.services[0].environment.PGHOST).toBe( privatePlan.services[0].create.internalAlias, ); @@ -186,109 +182,29 @@ describe("reviewed platform imports", () => { it("names storage per service inside one destination project", async () => { inventory.services[1].volumes = [{ id: "files", mountPath: "/data" }]; const plan = await loadReviewedImport(ctx, (await review()).planId); - expect(plan.projects[0].create.services?.flatMap((service) => service.volumes ?? [])).toEqual([ + expect(plan.project.services?.flatMap((service) => service.volumes ?? [])).toEqual([ "database-data-0:/var/lib/postgresql/data", "website-data-0:/data", ]); - expect(plan.projects[0].create.services?.[1].dependsOn).toEqual(["database"]); + expect(plan.project.services?.[1].dependsOn).toEqual(["database"]); }); - it.each(["repository", "commit", "branch"])( - "splits incompatible Git %s without losing revisions or private connections", - async (difference) => { - inventory.services = ["one", "two"].map((id) => - service({ - id, - name: id, - image: undefined, - repository: difference === "repository" ? `owner/${id}` : "owner/repo", - commit: (difference === "commit" && id === "two" ? "b" : "a").repeat(40), - branch: difference === "branch" ? id : "main", - privateDomain: `${id}.railway.internal`, - env: id === "two" ? { API_URL: "http://one.railway.internal:3000/api?secret=keep" } : {}, - }), - ); - const result = await review( - inventory.services.map((service) => ({ - id: service.id, - name: service.name, - data: "empty", - })), - ); - expect(result.ready, JSON.stringify(result)).toBe(true); - expect(result.projects).toEqual([ - { name: "project-one", serviceIds: ["one"] }, - { name: "project-two", serviceIds: ["two"] }, - ]); - const plan = await loadReviewedImport(ctx, result.planId); - expect(plan.projects.map((project) => project.create.gitRepo)).toEqual( - difference === "repository" ? ["one", "two"] : ["repo", "repo"], - ); - expect(plan.services[1].bindings).toEqual([ - { - sourceId: "one", - envKey: "API_URL", - valueTemplate: "http://${host}:3000/api?secret=keep", - }, - ]); - expect(plan.services.map((s) => s.source.commit)).toEqual( - inventory.services.map((s) => s.commit), - ); - expect(h.info.mock.calls.map(([input]) => input.owner)).toEqual(["owner", "owner"]); - expect(h.info.mock.calls.map(([input]) => input.branch)).toEqual( - inventory.services.map((s) => s.commit), - ); - }, - ); - it("keeps compatible source services together and rejects composite cross-project variables during review", async () => { - const git = (id: string, repository: string) => + it("blocks incompatible Git sources instead of splitting the source project", async () => { + inventory.services = ["one", "two"].map((id) => service({ id, name: id, image: undefined, - repository, + repository: `owner/${id}`, commit: "a".repeat(40), - privateDomain: `${id}.railway.internal`, - }); - inventory.services = [git("one", "owner/repo"), git("two", "owner/repo")]; - const choices = () => - inventory.services.map((s) => ({ id: s.id, name: s.name, data: "empty" as const })); - expect((await review(choices())).projects).toEqual([ - { name: "Project", serviceIds: ["one", "two"] }, - ]); - inventory.services.push(git("three", "owner/other")); - inventory.services[2].env = { HOSTS: "one.railway.internal,two.railway.internal" }; - const result = await review(choices()); - expect(result.ready).toBe(false); - expect(result.services[2].blockers.join(" ")).toContain("separate connection variable"); - }); - it("blocks unavailable private listeners and ambiguous host templates before source downtime", async () => { - inventory.services = [ - service({ - id: "store", - name: "store", - port: undefined, - privateDomain: "store.railway.internal", }), - ...["one", "two"].map((id) => - service({ - id, - name: id, - image: undefined, - repository: `owner/${id}`, - commit: "a".repeat(40), - env: - id === "one" - ? { HOST: "store.railway.internal" } - : { HOST: "store.railway.internal-${host}" }, - }), - ), - ]; + ); const result = await review( - inventory.services.map((s) => ({ id: s.id, name: s.name, data: "empty" })), + inventory.services.map((service) => ({ id: service.id, name: service.name, data: "empty" })), ); expect(result.ready).toBe(false); - expect(result.services[1].blockers.join(" ")).toContain("private listener port"); - expect(result.services[2].blockers.join(" ")).toContain("cannot be safely converted"); + expect(result.services.flatMap((service) => service.blockers).join(" ")).toContain( + "one Git source", + ); }); it("ignores pagination order and changing volume size, but never ignores changed configuration", () => { const next = structuredClone(inventory); @@ -402,9 +318,7 @@ it("uses the existing Compose build for a custom Dockerfile and preserves readin readiness: { path: "/health" }, services: [{ build: "apps/api", dockerfile: "docker/production.Dockerfile" }], }); - expect(plan.projects[0].create.services?.[0].advanced).toMatchObject({ - readiness: { path: "/health", port: 3000 }, - }); + expect(plan.project.services?.[0].advanced).toMatchObject({ readiness: { path: "/health", port: 3000 } }); expect(h.info).not.toHaveBeenCalled(); }); it("blocks an unavailable custom Dockerfile before import", async () => { diff --git a/apps/api/src/modules/migration/platform-import-worker.test.ts b/apps/api/src/modules/migration/platform-import-worker.test.ts index 446bd3f5c..f932056a4 100644 --- a/apps/api/src/modules/migration/platform-import-worker.test.ts +++ b/apps/api/src/modules/migration/platform-import-worker.test.ts @@ -6,7 +6,7 @@ import type { PrivateImportPlan, PlannedImportService, } from "@repo/platform/engine/modules/migration/platform-import-plan"; -import { platformImportProjects } from "@repo/platform/engine/modules/migration/platform-import-project"; +import { platformImportProject } from "@repo/platform/engine/modules/migration/platform-import-project"; const h = vi.hoisted(() => ({ ensure: vi.fn(), merge: vi.fn(), @@ -15,7 +15,6 @@ const h = vi.hoisted(() => ({ sourceService: vi.fn(), rows: [] as Array<{ id: string; projectId: string; name: string }>, view: vi.fn(), - connect: vi.fn(), deploy: vi.fn(), copy: vi.fn(), preflight: vi.fn(), @@ -59,9 +58,6 @@ vi.mock("@repo/platform/engine/modules/projects/project-runtime.service", () => vi.mock("@repo/platform/engine/modules/apps/app-settings.service", () => ({ getAppConnectionView: h.view, })); -vi.mock("@repo/platform/engine/modules/projects/project-connection.service", () => ({ - createConnection: h.connect, -})); vi.mock("@repo/platform/engine/modules/deployments/build.service", () => ({ triggerDeployment: h.deploy, })); @@ -124,8 +120,7 @@ const planFor = (services: PlannedImportService[]) => userId: "user", targetServerId: "server", services, - projectName: "imported-project", - projects: platformImportProjects("imported-project", "server", services), + project: platformImportProject("imported-project", "server", services), }) as PrivateImportPlan; let row: any; beforeEach(() => { @@ -188,9 +183,6 @@ beforeEach(() => { h.restoreSource.mockImplementation(async (_run, resume) => { h.events.push(resume ? "resume-project" : "restore-config"); }); - h.connect.mockImplementation(async (_ctx, target, input) => { - h.events.push(`connect:${input.sourceProjectId}:${target}`); - }); }); const lifecycle = (signal = new AbortController().signal) => ({ signal, @@ -203,95 +195,6 @@ const lifecycle = (signal = new AbortController().signal) => ({ }), }); describe("provider import through normal project operations", () => { - it("copies all volumes before deploying multiple repositories in dependency order with native links", async () => { - const db = service("db", "database"), - app = service("app", "app"), - worker = service("worker", "worker"); - for (const entry of [app, worker]) - Object.assign(entry.create, { - gitProvider: "github", - gitOwner: "owner", - gitRepo: entry.source.id, - gitBranch: "main", - }); - worker.source.commit = "b".repeat(40); - app.bindings = [ - { sourceId: "db", envKey: "DB_URL", valueTemplate: "postgres://secret@${host}:5432/store" }, - ]; - worker.bindings = [{ sourceId: "app", envKey: "APP_HOST", valueTemplate: "${host}" }]; - app.environment.DB_URL = "postgres://secret@db:5432/store"; - worker.environment.APP_HOST = "app"; - const services = [worker, app, db]; - const plan = { ...planFor(services), sourceControl: "railway-project" as const }; - await executePlatformImport(ctx, "run", plan, lifecycle()); - expect(h.ensure.mock.calls.map(([body]) => body.gitRepo)).toEqual(["worker", "app", undefined]); - expect( - h.ensure.mock.calls.every(([body]) => body.services.every((s: any) => !s.dependsOn.length)), - ).toBe(true); - expect(h.copy.mock.calls.map(([input]) => [input.projectId, input.serviceId])).toEqual([ - ["imported-project-db", "imported-project-db-db"], - ["imported-project-app", "imported-project-app-app"], - ["imported-project-worker", "imported-project-worker-worker"], - ]); - expect(h.events.indexOf("copy:worker")).toBeLessThan( - h.events.indexOf("deploy:imported-project-db:1"), - ); - expect(h.events.indexOf("healthy:imported-project-db-build-1")).toBeLessThan( - h.events.indexOf("connect:imported-project-db:imported-project-app"), - ); - expect(h.events.indexOf("connect:imported-project-db:imported-project-app")).toBeLessThan( - h.events.indexOf("deploy:imported-project-app:1"), - ); - expect(h.connect).toHaveBeenCalledWith( - ctx, - "imported-project-app", - { - sourceProjectId: "imported-project-db", - outputId: "imported-project-db-db:url", - envKey: "DB_URL", - mode: "internal", - valueTemplate: "postgres://secret@${host}:5432/store", - }, - { defer: true }, - ); - expect( - h.merge.mock.calls.flatMap(([, , , input]) => input.upserts.map((v: any) => v.key)), - ).not.toContain("DB_URL"); - expect(h.deploy.mock.calls.map(([, input]) => [input.projectId, input.commitSha])).toEqual([ - ["imported-project-db", undefined], - ["imported-project-app", "a".repeat(40)], - ["imported-project-worker", "b".repeat(40)], - ]); - expect(h.verify).toHaveBeenCalledTimes(3); - expect(row.recovery.providerImport.completed).toEqual(["db", "app", "worker"]); - }); - it("does not start a cross-project consumer if its private connection fails", async () => { - const db = service("db", "database"), - app = service("app", "app"), - worker = service("worker", "worker"); - for (const entry of [app, worker]) - Object.assign(entry.create, { gitOwner: "owner", gitRepo: entry.source.id }); - app.bindings = [{ sourceId: "db", envKey: "DB_URL" }]; - const plan = { ...planFor([app, db, worker]), sourceControl: "railway-project" as const }; - row.recovery.providerImport.planEnc = JSON.stringify(plan); - h.connect.mockRejectedValue(new Error("Private network unavailable")); - await expect(executePlatformImport(ctx, "run", plan, lifecycle())).rejects.toThrow( - "Private network unavailable", - ); - expect(h.deploy).toHaveBeenCalledTimes(1); - expect(row.recovery.providerImport.completed).toEqual([]); - expect(h.restoreSource).not.toHaveBeenCalledWith("run", true, expect.anything()); - await pauseFailedPlatformImport("run"); - expect(h.disable).toHaveBeenCalledExactlyOnceWith( - "imported-project-db", - "org", - "imported-project-db-build-1", - ); - expect(h.restoreSource).toHaveBeenLastCalledWith("run", true); - expect(h.disable.mock.invocationCallOrder[0]).toBeLessThan( - h.restoreSource.mock.invocationCallOrder[1], - ); - }); it("stages custom domains through native migration routing before pausing the source", async () => { const web = service("web", "app"); web.create.name = "storefront"; @@ -396,8 +299,7 @@ describe("provider import through normal project operations", () => { const services = [service("db", "database"), service("app", "app")]; services.forEach((service) => (service.transfer = "cold-volume")); const plan = { ...planFor(services), sourceControl: "railway-project" as const }; - plan.projectName = name; - plan.projects[0].create.name = name; + plan.project.name = name; await executePlatformImport(ctx, name, plan, lifecycle()); expect(new Set(Object.values(row.recovery.providerImport.projects))).toEqual(new Set([name])); } @@ -477,9 +379,9 @@ describe("provider import through normal project operations", () => { }), ); }); - it("rejects reviews without destination projects before allocating a destination", async () => { + it("rejects reviews from the old per-service-project flow before allocating a destination", async () => { const plan = planFor([service("app", "app")]); - delete (plan as Partial).projects; + delete (plan as Partial).project; await expect(executePlatformImport(ctx, "run", plan, lifecycle())).rejects.toMatchObject({ code: "IMPORT_REVIEW_EXPIRED", }); @@ -545,7 +447,7 @@ describe("provider import through normal project operations", () => { "deploy:imported-project:3", "healthy:imported-project-build-2", ]); - expect(h.ensure).toHaveBeenCalledExactlyOnceWith(plan.projects[0].create, "org", ctx, { + expect(h.ensure).toHaveBeenCalledExactlyOnceWith(plan.project, "org", ctx, { mustCreate: true, }); expect(h.merge).toHaveBeenCalledWith( diff --git a/apps/api/src/modules/migration/railway-wiring.test.ts b/apps/api/src/modules/migration/railway-wiring.test.ts index d21c42e47..b7b45588a 100644 --- a/apps/api/src/modules/migration/railway-wiring.test.ts +++ b/apps/api/src/modules/migration/railway-wiring.test.ts @@ -42,27 +42,6 @@ describe("provider-independent connection values", () => { }); }); describe("Railway project wiring", () => { - it("preserves self references and repeated case-insensitive dependency hosts in one connection", () => { - const db = service("db", {}, 5432); - const app = service("app", { - HOSTS: "DB.railway.internal,db.railway.internal,app.railway.internal", - }); - expect( - resolveRailwayBindings( - app, - new Map([ - ["db", db], - ["app", app], - ]), - ), - ).toEqual([ - { - sourceId: "db", - envKey: "HOSTS", - valueTemplate: "${host},${host},import-app", - }, - ]); - }); it("binds any private service without inferring its type from its image or variable names", () => { const store = service("store"); const app = service("app", { @@ -79,7 +58,6 @@ describe("Railway project wiring", () => { { sourceId: "store", envKey: "ARBITRARY_SETTING", - valueTemplate: "custom://alice:password@${host}:7878/second-db?option=1", }, ]); expect(store.source.port).toBe(7878); diff --git a/apps/api/src/modules/projects/project-clone.test.ts b/apps/api/src/modules/projects/project-clone.test.ts index 864a94be8..497aa8279 100644 --- a/apps/api/src/modules/projects/project-clone.test.ts +++ b/apps/api/src/modules/projects/project-clone.test.ts @@ -32,7 +32,8 @@ const h = { deletedAt: null, deletionInProgress: false, lifecycleOperation: { kind: "delete", status: "failed", error: "Previous cleanup failure" }, - iconUrl: "https://clincai.example/icon.png", + favicon: "https://clincai.example/favicon.ico", + faviconCheckedAt: new Date(), compositeRoutes: [{ host: "clincai.example" }], workspaceId: null, gitProvider: "github", @@ -193,7 +194,6 @@ describe("the copy direction is COPY-by-default", () => { await clone(); const p = clonedProject(); expect(p.framework).toBe("nextjs"); - expect(p.iconUrl).toBe("https://clincai.example/icon.png"); expect(p.routeStrategy).toBe("loopback"); expect(p.rollbackWindow).toBe(5); // Same for the service rows: a build command exists in no container. @@ -231,7 +231,7 @@ describe("what it deliberately does NOT copy", () => { const p = clonedProject(); // `id`/`groupId` are the insert's, and name/slug/serverId/workspaceId/activeDeploymentId are set // explicitly above — the rest must simply be absent. - for (const field of ["deletedAt", "deletionInProgress", "lifecycleOperation", "disabledAt", "compositeRoutes", "cloudPromotion", "id", "groupId", "createdAt", "updatedAt"]) { + for (const field of ["deletedAt", "deletionInProgress", "lifecycleOperation", "disabledAt", "favicon", "faviconCheckedAt", "compositeRoutes", "cloudPromotion", "id", "groupId", "createdAt", "updatedAt"]) { expect(p, field).not.toHaveProperty(field); } }); diff --git a/apps/api/test/e2e/platform-import-project.e2e.test.ts b/apps/api/test/e2e/platform-import-project.e2e.test.ts index b8de6a4ca..a486e13c3 100644 --- a/apps/api/test/e2e/platform-import-project.e2e.test.ts +++ b/apps/api/test/e2e/platform-import-project.e2e.test.ts @@ -3,9 +3,6 @@ import { randomUUID } from "node:crypto"; import { spawn } from "node:child_process"; import { createConnection } from "node:net"; import { once } from "node:events"; -import { mkdtemp, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; import { BuildLogger, CommandSourceBackupExecutor, @@ -23,14 +20,8 @@ import { deployComposeServices } from "@repo/platform/engine/modules/deployments import { projectServicesToDeployableServices } from "@repo/platform/engine/modules/deployments/compose/project-services"; import { seedDeployment, seedOrg, setActive } from "../helpers/seed"; import { describeDockerE2E, requireDocker, dockerSocketPath } from "../helpers/docker-e2e"; -import { refreshConnectionEnv } from "@repo/platform/engine/modules/projects/project-connection.service"; -import { - sharedServiceAlias, - sharedServiceNetwork, -} from "@repo/platform/engine/modules/projects/shared-service-network"; -// Substitute Railway's control/SSH boundary, Git checkout, destination resolution -// and the asynchronous build queue. All runtime operations use an isolated daemon. +// Substitute Railway's control/SSH boundary and the asynchronous build queue. // Review, project creation, encrypted environments, migration checkpoints, // volume transfer and the ordinary Compose deployment engine remain real. const h = vi.hoisted(() => ({ @@ -59,18 +50,9 @@ vi.mock("@repo/platform/engine/modules/migration/migration-runtime", async (orig ...(await original()), createMigrationDockerRuntime: h.runtime, })); -vi.mock("@repo/platform/engine/modules/services/service-container", async (original) => ({ - ...(await original()), - // Resolve private-link operations onto the same isolated daemon as the import. - // Connection authorization, persistence, DNS and network attachment stay real. - resolveServicePlatform: async () => ({ platform: { runtime: await h.runtime() } }), -})); vi.mock("@repo/platform/engine/modules/deployments/build.service", () => ({ triggerDeployment: h.deploy, })); -vi.mock("@repo/platform/engine/modules/deployments/project-reader", () => ({ - createGitHubReader: () => ({ readText: async () => "FROM redis:7-alpine\n" }), -})); import { discoverPlatform, reviewPlatform, @@ -82,8 +64,6 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { const tag = `import-groups-${randomUUID().slice(0, 8)}`; const containers = new Set(); const volumes = new Set(); - const images = new Set(); - const sharedNetworks = new Set(); const projects: Array<{ id: string; slug: string }> = []; const sources = new Map(); let runtime: DockerRuntime; @@ -127,13 +107,11 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { await container.remove({ force: true }); } for (const project of projects) await runtime.removeNetwork(project.slug); - for (const name of sharedNetworks) await runtime.docker.getNetwork(name).remove(); for (const volume of (await runtime.docker.listVolumes()).Volumes ?? []) { if (projects.some((project) => volume.Labels?.["openship.project"] === project.id)) volumes.add(volume.Name); } for (const name of volumes) await runtime.docker.getVolume(name).remove(); - for (const image of images) await runtime.removeImage(image); await runtime.dispose(); vi.restoreAllMocks(); }); @@ -150,14 +128,9 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { return container.id; } - it.each([ - { transport: "socket", split: false }, - { transport: "cloud", split: false }, - { transport: "socket", split: true }, - { transport: "cloud", split: true }, - ] as const)( - "imports through $transport (multiple repositories: $split), isolating DNS, env and persisted data", - async ({ transport, split }) => { + it.each(["socket", "cloud"] as const)( + "imports two three-service projects through %s, isolating DNS, env and persisted data", + async (transport) => { const owner = await seedOrg({ ownsHost: true }); const ctx = { ...owner, @@ -165,7 +138,7 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { user: { id: owner.userId, name: "Test", email: "test@example.test" }, sessionKind: "cookie", } as ExecutionContext; - const serverId = `${tag}-${transport}-${split}`; + const serverId = `${tag}-${transport}`; await db.insert(schema.servers).values({ id: serverId, organizationId: owner.organizationId, @@ -238,40 +211,6 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { await repos.project.update(input.projectId, { routeStrategy: "container-ip" }); const project = (await repos.project.findById(input.projectId))!; const services = await repos.service.listByProject(project.id); - await refreshConnectionEnv(ctx, project.id); - const preparedLocalImages = new Map(); - const builtImages = new Map(); - for (const service of services) { - if (service.image) preparedLocalImages.set(service.id, service.image); - else { - // Stand in for the immutable Git checkout with a distinct build per - // repository/revision. The image build and deployment stay real. - const directory = await mkdtemp(join(tmpdir(), "openship-import-build-")); - const image = `${tag}:${service.id}`; - images.add(image); - try { - await writeFile( - join(directory, "Dockerfile"), - `FROM redis:7-alpine\nRUN echo '${project.gitRepo}:${input.commitSha}' > /source-revision\n`, - ); - const stream = await runtime.docker.buildImage( - { context: directory, src: ["Dockerfile"] }, - { t: image, networkmode: "none", labels: { "openship.project": project.id } }, - ); - await new Promise((resolve, reject) => - runtime.docker.modem.followProgress(stream, (error, output) => { - const failure = output?.find((event: { error?: string }) => event.error)?.error; - if (error || failure) reject(error ?? new Error(failure)); - else resolve(); - }), - ); - preparedLocalImages.set(service.id, image); - builtImages.set(service.id, image); - } finally { - await rm(directory, { recursive: true, force: true }); - } - } - } const deployment = await seedDeployment(project, { status: "deploying", trigger: "manual", @@ -314,8 +253,7 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { { executor: null, localHost: false, - preparedLocalImages, - builtImages, + preparedLocalImages: new Map(services.map((s) => [s.id, s.image!])), targetServiceIds: new Set(input.serviceIds), }, ); @@ -331,7 +269,7 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { const imported: Array<{ id: string; marker: string }> = []; for (const projectNumber of [1, 2]) { - const marker = `${tag}-${transport}-${split}-${projectNumber}`; + const marker = `${tag}-${transport}-${projectNumber}`; const services: ProviderInventory["services"] = []; for (const name of ["db", "cache"]) { const id = `${marker}-${name}`; @@ -394,19 +332,6 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { startCommand: "sh -c 'while true; do printf \"HTTP/1.1 200 OK\\r\\nContent-Length: 6\\r\\nConnection: close\\r\\n\\r\\nready\\n\" | nc -l -p 8080; done'", }); - if (split) { - // Two distinct Git sources plus one image-backed database. All volumes - // must move before either destination Git service is allowed to start. - for (const name of ["cache", "worker"]) { - const source = services.find((service) => service.name === name)!; - source.image = undefined; - source.repository = `fixture/${name}`; - source.commit = (name === "cache" ? "a" : "b").repeat(40); - source.branch = "main"; - source.dockerfile = "Dockerfile"; - } - delete services.find((service) => service.name === "worker")!.env.BOTH_HOSTS; - } const inventory: ProviderInventory = { provider: "railway", source: { connectionId: "fixture", projectId: marker, environmentId: "production" }, @@ -454,26 +379,21 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { }); } finally { const saved = await repos.project.listByOrganization(owner.organizationId); - for (const p of saved.rows) { + for (const p of saved.rows) if (!projects.some((known) => known.id === p.id)) projects.push(p); - for (const link of await repos.projectConnection.listByTarget(p.id)) - if (link.sourceServiceId) - sharedNetworks.add(sharedServiceNetwork(link.sourceServiceId)); - } } const checkpoint = (await repos.dockerMigrationRun.findById(runId))!.recovery .providerImport!; const ids = [...new Set(Object.values(checkpoint.projects))]; - expect(ids).toHaveLength(split ? 3 : 1); + expect(ids).toHaveLength(1); + const id = ids[0]; + expect(await repos.service.listByProject(id)).toHaveLength(3); expect(checkpoint.completed).toHaveLength(3); expect((await repos.project.listByOrganization(owner.organizationId)).total).toBe( - projectNumber * (split ? 3 : 1), + projectNumber, ); - for (const id of ids) { - expect(await repos.service.listByProject(id)).toHaveLength(split ? 1 : 3); - if (!split) expect(await repos.project.getEnvMap(id, "production", null)).toEqual({}); - imported.push({ id, marker }); - } + expect(await repos.project.getEnvMap(id, "production", null)).toEqual({}); + imported.push({ id, marker }); } // Check both projects AFTER the second import: duplicate service names @@ -487,12 +407,6 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { expect(env.SERVICE_SECRET).toBe(`${marker}-${service.name}`); const container = deployed.find((r) => r.serviceId === service.id)!.containerId!; expect(await exec(container, 'printf %s "$SERVICE_SECRET"')).toBe(env.SERVICE_SECRET); - if (split && project.gitRepo) { - const revision = (service.name === "cache" ? "a" : "b").repeat(40); - expect(await exec(container, "cat /source-revision")).toBe( - `${project.gitRepo}:${revision}`, - ); - } if (service.name === "worker") { expect(service.exposed).toBe(true); expect(service.publicEndpoints).toEqual([ @@ -509,50 +423,13 @@ describeDockerE2E("Railway projects retain native service boundaries", () => { ), ).toBe(true); expect(await exec(container, "wget -qO- http://127.0.0.1:8080")).toBe("ready"); - if (!split) expect(await exec(container, 'printf %s "$BOTH_HOSTS"')).toBe("db,cache"); - else { - const links = await repos.projectConnection.listByTarget(id); - expect(links).toHaveLength(2); - expect( - links.every( - (link) => - link.organizationId === owner.organizationId && - link.mode === "internal" && - link.usesPrivateNetwork, - ), - ).toBe(true); - for (const link of links) { - expect(env[link.envKey]).toBeUndefined(); // Service env must not shadow its native link. - expect(await exec(container, `printenv ${link.envKey}`)).toBe( - sharedServiceAlias(link.sourceServiceId!), - ); - } - } + expect(await exec(container, 'printf %s "$BOTH_HOSTS"')).toBe("db,cache"); expect(await exec(container, 'redis-cli -h "$PRIMARY_HOST" GET marker')).toBe( `${marker}-db`, ); expect(await exec(container, 'redis-cli -h "$CACHE_HOST" GET marker')).toBe( `${marker}-cache`, ); - if (split) { - // An ordinary later deployment refreshes the same saved links and - // rejoins the private networks without the import worker involved. - await h.deploy(ctx, { - projectId: id, - serviceIds: [service.id], - commitSha: "b".repeat(40), - }); - const current = (await repos.project.findById(id))!; - const next = (await repos.service.listByDeployment(current.activeDeploymentId!)).find( - (row) => row.serviceId === service.id, - )!; - expect(await exec(next.containerId!, 'redis-cli -h "$PRIMARY_HOST" GET marker')).toBe( - `${marker}-db`, - ); - expect(await exec(next.containerId!, 'redis-cli -h "$CACHE_HOST" GET marker')).toBe( - `${marker}-cache`, - ); - } } else { expect(await exec(container, "redis-cli GET marker")).toBe(`${marker}-${service.name}`); await exec(container, "redis-cli SET new-write survives"); diff --git a/apps/api/test/lib/permission-grant-satisfiability.test.ts b/apps/api/test/lib/permission-grant-satisfiability.test.ts index bc4816867..f4baf51a2 100644 --- a/apps/api/test/lib/permission-grant-satisfiability.test.ts +++ b/apps/api/test/lib/permission-grant-satisfiability.test.ts @@ -24,10 +24,9 @@ import type { RequestContext } from "../../src/lib/request-context"; * the grantable surface without proving it authorizes something → this fails. */ -// Exercise grant algebra under an owner's ceiling; members cannot delegate admin. vi.mock("@repo/db", () => ({ repos: { - member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "member" })) }, project: { findById: vi.fn(async (id: string) => (id === "*" ? null : { id, organizationId: "org1" })), findEnvVarById: vi.fn(async () => null), diff --git a/apps/api/test/lib/permission-own-projects.test.ts b/apps/api/test/lib/permission-own-projects.test.ts index 0f3a3edf0..d1b2a52b9 100644 --- a/apps/api/test/lib/permission-own-projects.test.ts +++ b/apps/api/test/lib/permission-own-projects.test.ts @@ -3,10 +3,9 @@ import { describe, it, expect, vi } from "vitest"; // checkPermission touches only member.find (membership gate) and, for a // concrete project id, project.findById (org resolution). We pass the grant // source explicitly via opts, so resourceGrant is never consulted. -// The owner can delegate project admin; the token must still satisfy each grant. vi.mock("@repo/db", () => ({ repos: { - member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "member" })) }, project: { findById: vi.fn(async (id: string) => id === "*" ? null : { id, organizationId: "org1" }, diff --git a/apps/api/test/lib/permission-wildcard-list-arm.test.ts b/apps/api/test/lib/permission-wildcard-list-arm.test.ts index 0620fa0ff..d92e3788a 100644 --- a/apps/api/test/lib/permission-wildcard-list-arm.test.ts +++ b/apps/api/test/lib/permission-wildcard-list-arm.test.ts @@ -19,10 +19,9 @@ import { describe, it, expect, vi } from "vitest"; -// The owner's role ceiling permits delegation; the tests enforce grant widths. vi.mock("@repo/db", () => ({ repos: { - member: { find: vi.fn(async () => ({ id: "m1", role: "owner" })) }, + member: { find: vi.fn(async () => ({ id: "m1", role: "member" })) }, project: { findById: vi.fn(async (id: string) => (id === "*" ? null : { id, organizationId: "org1" })), findEnvVarById: vi.fn(async () => null), @@ -199,7 +198,7 @@ describe("a full project wildcard now lists and creates (deliberate widening)", }); describe("non-restricted roles are untouched by this arm", () => { - it("an owner is authorized by role, without consulting grants", async () => { + it("a member is authorized by role, without consulting grants", async () => { const boom = { findForResource: async () => { throw new Error("the role arm must return before any grant lookup"); diff --git a/apps/api/test/lib/profile-avatar.test.ts b/apps/api/test/lib/profile-avatar.test.ts deleted file mode 100644 index 31d4e4604..000000000 --- a/apps/api/test/lib/profile-avatar.test.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { expect, it } from "vitest"; -import { auth } from "@repo/platform/engine/lib/auth"; -import { provisionUser } from "@repo/platform/engine/lib/provision-user"; -import { mintSession } from "../../src/lib/cloud-auth-proxy"; -import { db, schema, eq } from "@repo/db"; -import { randomUUID } from "node:crypto"; - -it("updates only the signed-in user's avatar through the existing auth endpoint and rejects unsafe URLs", async () => { - const id = randomUUID(); - await provisionUser({ - id, - email: `${id}@example.test`, - name: "Avatar owner", - emailVerified: true, - }); - const session = await mintSession({ purpose: "local-cookie", userId: id }); - const update = (image: unknown, token: string | null = session.token, extra = {}) => - auth.handler( - new Request("http://localhost:4000/api/auth/update-user", { - method: "POST", - headers: { - "Content-Type": "application/json", - ...(token ? { Authorization: `Bearer ${token}` } : {}), - }, - body: JSON.stringify({ image, ...extra }), - }), - ); - expect((await update("https://cdn.example.test/avatar.png", null)).status).toBe(401); - const result = await update("https://cdn.example.test/avatar.png"); - expect(result.status, await result.clone().text()).toBe(200); - expect(await db.query.user.findFirst({ where: eq(schema.user.id, id) })).toMatchObject({ - image: "https://cdn.example.test/avatar.png", - role: "user", - }); - expect( - await auth.api.getSession({ - headers: new Headers({ Authorization: `Bearer ${session.token}` }), - }), - ).toMatchObject({ user: { image: "https://cdn.example.test/avatar.png" } }); - expect( - (await update("https://cdn.example.test/avatar.png", session.token, { role: "admin" })).status, - ).toBe(400); - for (const image of [ - "javascript:alert(1)", - "data:image/svg+xml,", - "https://user:secret@example.test/a.png", - "/avatar.png", - 123, - ]) - expect((await update(image)).status).toBe(400); - expect((await update(null)).status).toBe(200); - expect(await db.query.user.findFirst({ where: eq(schema.user.id, id) })).toMatchObject({ - image: null, - }); -}); diff --git a/apps/api/test/modules/cloud-execution-access.test.ts b/apps/api/test/modules/cloud-execution-access.test.ts index 1812cf15b..973417ce7 100644 --- a/apps/api/test/modules/cloud-execution-access.test.ts +++ b/apps/api/test/modules/cloud-execution-access.test.ts @@ -120,7 +120,7 @@ describe("Cloud relays cannot substitute Cloud feature access for host administr expect(await response.json()).toMatchObject({ data: { token: "provider-secret" } }); }); - it.each(["owner", "admin"])( + it.each(["owner", "admin", "member"])( "preserves existing full host access for the %s role", async (role) => { await db.update(schema.member).set({ role }).where(eq(schema.member.id, memberId)); @@ -129,17 +129,6 @@ describe("Cloud relays cannot substitute Cloud feature access for host administr }, ); - it("denies members host credentials through both Cloud relay selectors", async () => { - await db.update(schema.member).set({ role: "member" }).where(eq(schema.member.id, memberId)); - for (const path of ["token", `token?serverId=${serverId}`, "resource-proxy", `resource-proxy?serverId=${serverId}`]) { - const response = await post(path, { operation: "list" }); - expect(response.status, await response.clone().text()).toBe(404); - } - expect(h.token).not.toHaveBeenCalled(); - expect(h.namespace).not.toHaveBeenCalled(); - expect(h.pages).not.toHaveBeenCalled(); - }); - it("does not bootstrap a server or credentials for an empty organization without host authority", async () => { actor = await seedOwner(); const membership = (await repos.member.find(actor.orgId, actor.userId))!; diff --git a/apps/api/test/modules/deployments/build-duration.test.ts b/apps/api/test/modules/deployments/build-duration.test.ts index 8d1e2cecb..026f4db36 100644 --- a/apps/api/test/modules/deployments/build-duration.test.ts +++ b/apps/api/test/modules/deployments/build-duration.test.ts @@ -13,6 +13,7 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: vi.fn() }, })); vi.mock("@repo/platform/engine/lib/audit-emitter", () => ({ audit: { recordAsync: vi.fn() } })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn() })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(), })); diff --git a/apps/api/test/modules/deployments/compose-noop-settle.test.ts b/apps/api/test/modules/deployments/compose-noop-settle.test.ts index 7a522fa77..100da4d26 100644 --- a/apps/api/test/modules/deployments/compose-noop-settle.test.ts +++ b/apps/api/test/modules/deployments/compose-noop-settle.test.ts @@ -94,6 +94,7 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ vi.mock("../../../src/lib/audit", () => ({ audit: { recordAsync: (_c: unknown, e: { eventType: string }) => h.audits.push(e.eventType) }, })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: async () => {} })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: async () => {}, })); diff --git a/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts b/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts index 52ffd3b75..e847bd792 100644 --- a/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts +++ b/apps/api/test/modules/deployments/deploy-outcome-vs-logs.test.ts @@ -113,6 +113,7 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ }, })); vi.mock("../../../src/lib/audit", () => ({ audit: { recordAsync: () => {} } })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: async () => {} })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: async () => {}, })); diff --git a/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts b/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts index ee521b560..3fd2f63b7 100644 --- a/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts +++ b/apps/api/test/modules/deployments/deployment-meta-redaction.test.ts @@ -13,6 +13,7 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: vi.fn() }, })); vi.mock("@repo/platform/engine/lib/audit-emitter", () => ({ audit: { recordAsync: vi.fn() } })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ detectAndStoreFavicon: vi.fn() })); vi.mock("@repo/platform/engine/modules/mail/webmail/webmail-install.service", () => ({ onWebmailDeployed: vi.fn(), })); diff --git a/apps/api/test/modules/deployments/native-sdk-parity.test.ts b/apps/api/test/modules/deployments/native-sdk-parity.test.ts index 4b0e0ec0d..6a1cf68ba 100644 --- a/apps/api/test/modules/deployments/native-sdk-parity.test.ts +++ b/apps/api/test/modules/deployments/native-sdk-parity.test.ts @@ -1897,8 +1897,8 @@ describe("domain and DNS HTTP/native parity", () => { const local = await native(); h.members.set("org-a:alice", { id: "member-a", role: "member" }); for (const dns of [remote().dns, local.dns]) { - await expect(dns.addCredential(input)).rejects.toMatchObject({ code: "NOT_FOUND" }); - await expect(dns.removeCredential("dns-a")).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect(dns.addCredential(input)).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(dns.removeCredential("dns-a")).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); } expect(h.dnsAdd).not.toHaveBeenCalled(); expect(h.dnsRemove).not.toHaveBeenCalled(); @@ -2045,10 +2045,10 @@ describe("provider credential HTTP/native parity", () => { const local = await native(); h.members.set("org-a:alice", { id: "member-a", role: "member" }); for (const credentials of [local.credentials, remote().credentials]) { - await expect(credentials.create({ provider: "docker-registry", name: "Registry", values: { secret: "value" } })).rejects.toMatchObject({ code: "NOT_FOUND" }); - await expect(credentials.update("credential-a", { name: "Renamed" })).rejects.toMatchObject({ code: "NOT_FOUND" }); - await expect(credentials.remove("credential-a")).rejects.toMatchObject({ code: "NOT_FOUND" }); - await expect(credentials.verify("credential-a")).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect(credentials.create({ provider: "docker-registry", name: "Registry", values: { secret: "value" } })).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(credentials.update("credential-a", { name: "Renamed" })).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(credentials.remove("credential-a")).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); + await expect(credentials.verify("credential-a")).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); } expect(h.credentialCreate).not.toHaveBeenCalled(); expect(h.credentialUpdate).not.toHaveBeenCalled(); @@ -2492,20 +2492,6 @@ describe("server HTTP/native parity", () => { expect(h.serverRemove).not.toHaveBeenCalled(); }); - it("denies ordinary members host execution through native, SDK and raw HTTP operations", async () => { - h.members.set("org-a:alice", { id: "member-a", role: "member" }); - const local = await native(); - for (const servers of [local.servers, remote().servers]) { - await expect(servers.exec("server-a", { command: "whoami" })).rejects.toMatchObject({ code: "NOT_FOUND" }); - } - const response = await app.request("/api/system/servers/server-a/exec", { - method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ command: "whoami" }), - }); - expect(response.status).toBe(404); - expect(h.serverWithExecutor).not.toHaveBeenCalled(); - expect(h.audit.mock.calls.filter(([event]) => event.eventType === "server.exec")).toHaveLength(0); - }); - it("returns the same partial teardown result and keeps HTTP 409", async () => { h.serverWorkloads.mockResolvedValue([{ id: "project-a", name: "Application", appTemplateId: null }]); h.projectTeardown.mockResolvedValue({ rowDeleted: false, orphaned: [], unrecoverable: [{ error: "volume busy" }] }); @@ -2598,11 +2584,11 @@ describe("HTTP/native system parity", () => { for (const system of [local.system, remote().system]) { await expect(system.updateSettings({ productMode: "mail" })).rejects.toMatchObject({ statusCode: 403 }); await expect(system.updateEmailSettings({ host: null })).rejects.toMatchObject({ statusCode: 403 }); - await expect(system.resetSettings()).rejects.toMatchObject({ statusCode: role === "member" ? 404 : 403 }); + await expect(system.resetSettings()).rejects.toMatchObject({ statusCode: 403 }); await expect(system.health()).rejects.toMatchObject({ statusCode: 403 }); await expect(system.browse({ path: "/" })).rejects.toMatchObject({ statusCode: 403 }); await expect(system.listUntrackedEdgeSites()).rejects.toMatchObject({ statusCode: 403 }); - await expect(system.removeUntrackedEdgeSite({ hostname: "orphan.example.test" })).rejects.toMatchObject({ statusCode: role === "member" ? 404 : 403 }); + await expect(system.removeUntrackedEdgeSite({ hostname: "orphan.example.test" })).rejects.toMatchObject({ statusCode: 403 }); } } expect(h.settingsUpsert).not.toHaveBeenCalled(); diff --git a/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts b/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts index 5d07a4e0f..5ab30154e 100644 --- a/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts +++ b/apps/api/test/modules/deployments/reused-artifact-not-reclaimed.test.ts @@ -32,6 +32,9 @@ vi.mock("@repo/platform/engine/lib/notification-dispatcher", () => ({ notification: { emit: vi.fn() }, })); vi.mock("../../../src/lib/audit", () => ({ audit: { recordAsync: vi.fn(), record: vi.fn() } })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ + detectAndStoreFavicon: vi.fn(async () => {}), +})); vi.mock("@repo/platform/engine/modules/projects/cleanup-keep-set", () => ({ computeCleanupKeepSet: vi.fn(async () => ({ containers: new Set() })), })); diff --git a/apps/api/test/modules/dns/managed-ingress.test.ts b/apps/api/test/modules/dns/managed-ingress.test.ts index 9593efea9..9bc116e4c 100644 --- a/apps/api/test/modules/dns/managed-ingress.test.ts +++ b/apps/api/test/modules/dns/managed-ingress.test.ts @@ -94,6 +94,6 @@ describe("managed ingress through authenticated HTTP and the public SDK", () => headers, body: JSON.stringify({ credentialId: "no-secret" }), }); - expect(denied.status).toBe(404); + expect(denied.status).toBe(403); }); }); diff --git a/apps/api/test/modules/mcp/mcp-tools-filter.test.ts b/apps/api/test/modules/mcp/mcp-tools-filter.test.ts index be9f00362..719dad2d2 100644 --- a/apps/api/test/modules/mcp/mcp-tools-filter.test.ts +++ b/apps/api/test/modules/mcp/mcp-tools-filter.test.ts @@ -135,7 +135,6 @@ function principal( const granted = new Set([...(p.grantedRootTypes ?? []), ...Object.keys(wildcards)]); return { role: p.role ?? "restricted", - membershipRole: p.membershipRole, readOnly: p.readOnly ?? false, grantedRootTypes: granted, wildcardGrants: p.wildcardGrants ?? new Map(Object.entries(wildcards)), @@ -148,16 +147,6 @@ function principal( const RWA: Permission[] = ["read", "write", "admin"]; describe("filterToolsForPrincipal", () => { - it("hides server administration from members and their existing scoped tokens", () => { - const read = tool({ name: "server_read", method: "GET", perm: { root: "server", leaf: "server", grantRoot: "server", action: "read", wildcard: false } }); - const exec = tool({ name: "server_exec", method: "POST", perm: { root: "server", leaf: "server", grantRoot: "server", action: "admin", wildcard: false } }); - for (const caller of [ - principal({ role: "member" }), - principal({ role: "restricted", membershipRole: "member", grantedRootTypes: new Set(["server"]), wildcards: { server: RWA } }), - ]) expect(names(filterToolsForPrincipal([read, exec], caller))).toEqual(["server_read"]); - expect(names(filterToolsForPrincipal([read, exec], principal({ role: "admin" })))).toEqual(["server_exec", "server_read"]); - }); - it("owner sees everything", () => { const out = filterToolsForPrincipal(ALL, principal({ role: "owner" })); expect(out.length).toBe(ALL.length); diff --git a/apps/api/test/modules/mcp/mcp-workspaces.test.ts b/apps/api/test/modules/mcp/mcp-workspaces.test.ts index 8179cc373..80dbb98b3 100644 --- a/apps/api/test/modules/mcp/mcp-workspaces.test.ts +++ b/apps/api/test/modules/mcp/mcp-workspaces.test.ts @@ -138,22 +138,6 @@ describe("MCP workspace discovery", () => { expect(denied.isError).toBe(true); }); - it.each([false, true])("advertises administration in another workspace only for an unbound credential (bound=%s)", async bound => { - const owner = await seedOwner({ bound }); - await secondWorkspace(owner, "admin"); - await db.update(schema.member).set({ role: "member" }).where(and(eq(schema.member.userId, owner.userId), eq(schema.member.organizationId, owner.orgId))); - const listed = await (await rpc(owner, "tools/list")).json() as { result: { tools: { name: string }[] } }; - expect(listed.result.tools.some(tool => tool.name === "delete_projects_by_id")).toBe(!bound); - if (!bound) { - const group = await repos.projectGroup.create({ organizationId: owner.orgId, name: "Member project", slug: "member-project" }); - const project = await repos.project.create({ organizationId: owner.orgId, groupId: group.id, name: "Member project", slug: "member-project" }); - const denied = await call(owner, "delete_projects_by_id", { id: project.id, organizationId: owner.orgId }); - expect(denied).toMatchObject({ isError: true, data: { code: "NOT_FOUND" } }); - expect(forwarding.fetch).toHaveBeenCalled(); - expect(await repos.project.findById(project.id)).toMatchObject({ id: project.id }); - } - }); - it("shares the discovery contract with SDKs and respects fixed native scopes", async () => { const owner = await seedOwner({ bound: false }); const target = await secondWorkspace(owner); diff --git a/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts b/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts index 06ab6469c..0f616742c 100644 --- a/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts +++ b/apps/api/test/modules/notifications/notifications-sdk-parity.test.ts @@ -133,7 +133,7 @@ describe("notifications shared SDK/HTTP operations", () => { expect(await c.native.listDefaults()).toEqual([value]); expect(await c.native.categories()).toEqual(await c.remote.categories()); await db.update(schema.member).set({ role: "member" }).where(eq(schema.member.userId, owner.userId)); - for (const client of [c.native, c.remote]) await expect(client.upsertDefault({ category: "deploy.failed", defaultEnabled: false })).rejects.toMatchObject({ code: "NOT_FOUND" }); + for (const client of [c.native, c.remote]) await expect(client.upsertDefault({ category: "deploy.failed", defaultEnabled: false })).rejects.toMatchObject({ code: "FORBIDDEN" }); }); it("does not verify a replacement configuration or hide normal delivery failures", async () => { diff --git a/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts b/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts index 10a53e784..a6858b068 100644 --- a/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts +++ b/apps/api/test/modules/projects/cloud-promotion-recovery.test.ts @@ -465,9 +465,8 @@ describe("project promotion recovery", () => { const dump = await dumpSubgraph({ kind: "project", projectId }); const changed = structuredClone(dump); changed.tables.resource_usage.push({ id: "another-sample", projectId, cpu: 42 }); + changed.tables.project[0].favicon = "new favicon"; expect(projectPromotionDigest(changed)).toBe(projectPromotionDigest(dump)); - changed.tables.project[0].iconUrl = "https://cdn.example.test/new-icon.png"; - expect(projectPromotionDigest(changed)).not.toBe(projectPromotionDigest(dump)); changed.tables.project[0].localPath = "/another-source"; expect(projectPromotionDigest(changed)).not.toBe(projectPromotionDigest(dump)); }); diff --git a/apps/api/test/modules/projects/project-icon.test.ts b/apps/api/test/modules/projects/project-icon.test.ts deleted file mode 100644 index 4cbd56c71..000000000 --- a/apps/api/test/modules/projects/project-icon.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import "../jobs/_env"; -import { expect, it } from "vitest"; -import { Hono } from "hono"; -import { seedOwner, repos } from "../jobs/_harness"; -import { seedProject, seedDeployment } from "../../helpers/seed"; -import { listDeployments } from "@repo/platform/engine/modules/deployments/deployment.service"; -import { projectRoutes } from "../../../src/modules/projects/project.routes"; -import { handleApiError } from "../../../src/middleware/error-handler"; - -const app = new Hono().onError(handleApiError).route("/api/projects", projectRoutes); - -it("uses one icon URL across authenticated settings, reads and deployment history", async () => { - const owner = await seedOwner(); - const project = await seedProject(owner.orgId); - const custom = "https://cdn.example.test/project.svg"; - const update = (iconUrl: unknown, auth = owner.auth) => - app.request(`/api/projects/${project.id}`, { - method: "PATCH", - headers: { ...auth, "Content-Type": "application/json" }, - body: JSON.stringify({ iconUrl }), - }); - const assertIcon = (data: unknown, expected: string | null) => { - expect(data).toMatchObject({ iconUrl: expected }); - expect(data).not.toHaveProperty("favicon"); - expect(data).not.toHaveProperty("faviconCheckedAt"); - }; - const saved = await update(` ${custom} `); - expect(saved.status, await saved.clone().text()).toBe(200); - assertIcon((await saved.json()).data, custom); - assertIcon(await repos.project.findById(project.id), custom); - const read = await app.request(`/api/projects/${project.id}`, { headers: owner.auth }); - expect(read.status, await read.clone().text()).toBe(200); - assertIcon((await read.json()).data, custom); - await seedDeployment(project); - for (const options of [{ projectId: project.id }, {}]) { - const history = await listDeployments(owner.orgId, options); - assertIcon(history.rows[0], custom); - } - const stranger = await seedOwner(); - expect((await update("https://stranger.example.test/icon.png", stranger.auth)).status).toBe(404); - for (const unsafe of [ - "javascript:alert(1)", - "data:image/png;base64,AAA", - "https://user:password@example.test/i.png", - "/relative.png", - ]) - expect((await update(unsafe)).status).toBe(400); - assertIcon(await repos.project.findById(project.id), custom); - for (const reset of [null, ""]) { - expect((await update(custom)).status).toBe(200); - const cleared = await update(reset); - expect(cleared.status).toBe(200); - assertIcon((await cleared.json()).data, null); - assertIcon(await repos.project.findById(project.id), null); - const history = await listDeployments(owner.orgId, { projectId: project.id }); - assertIcon(history.rows[0], null); - } -}); diff --git a/apps/api/test/modules/projects/project-overview-logs.test.ts b/apps/api/test/modules/projects/project-overview-logs.test.ts index 555e7ddf9..a716386d1 100644 --- a/apps/api/test/modules/projects/project-overview-logs.test.ts +++ b/apps/api/test/modules/projects/project-overview-logs.test.ts @@ -19,6 +19,7 @@ vi.mock("@repo/db", () => ({ repos: { vi.mock("@repo/platform/engine/modules/projects/project.service", () => ({ listProjects: h.list, enrichProjectsBatch: h.enrich, deploymentIsBlocked: () => false })); vi.mock("@repo/platform/engine/lib/authorization", () => ({ authorization: { checkPermissionOnResource: h.canRead, authorize: async (ctx: ExecutionContext) => ctx } })); vi.mock("@repo/platform/engine/lib/cloud/projects", () => ({ fetchOrgCloudProjects: h.cloudProjects })); +vi.mock("@repo/platform/engine/lib/favicon-detector", () => ({ refreshProjectFaviconIfStale: vi.fn() })); vi.mock("@repo/platform/engine/config/index", () => ({ env: h.env })); vi.mock("@repo/platform/engine/lib/oblien-user-client", () => ({ getAdminOblienClient: () => h.env.CLOUD_MODE ? { analytics: { streamToken: h.streamToken, requests: h.requests } } : null })); vi.mock("@repo/platform/engine/lib/cloud/client", () => ({ cloudClient: () => ({ analytics: { streamToken: h.streamToken, requests: h.requests } }) })); diff --git a/apps/api/test/modules/projects/shared-service-connections.test.ts b/apps/api/test/modules/projects/shared-service-connections.test.ts index 1df8a5fb8..fc4d00f0b 100644 --- a/apps/api/test/modules/projects/shared-service-connections.test.ts +++ b/apps/api/test/modules/projects/shared-service-connections.test.ts @@ -66,10 +66,9 @@ beforeEach(() => { describe("connections to a service inside a project", () => { it("offers all eligible projects while excluding the current project and read-only access", async () => { - h.candidates = ["source", "read-only", ...Array.from({ length: 120 }, (_, i) => `consumer-${i}`)].map(id => ({ id, name: id, environmentName: "production", appTemplateId: null, iconUrl: "https://cdn.example.test/icon.svg", framework: "nextjs" })); + h.candidates = ["source", "read-only", ...Array.from({ length: 120 }, (_, i) => `consumer-${i}`)].map(id => ({ id, name: id, environmentName: "production", appTemplateId: null })); const choices = await listConnectionCandidates(ctx, "source"); expect(choices).toHaveLength(120); - expect(choices[0]).toMatchObject({ iconUrl: "https://cdn.example.test/icon.svg", framework: "nextjs" }); expect(choices.some(choice => ["source", "read-only"].includes(choice.id))).toBe(false); expect(h.authorize).toHaveBeenCalledWith(ctx, { resourceType: "project", resourceId: "source", action: "write" }); }); diff --git a/apps/api/test/modules/system/server-exec-authorization.test.ts b/apps/api/test/modules/system/server-exec-authorization.test.ts deleted file mode 100644 index 754a3fcb9..000000000 --- a/apps/api/test/modules/system/server-exec-authorization.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import "../jobs/_env"; -import { beforeEach, expect, it, vi } from "vitest"; -import { Hono } from "hono"; -import { and, eq } from "@repo/db"; - -const host = vi.hoisted(() => ({ execute: vi.fn(), command: vi.fn() })); -vi.mock("@repo/platform/engine/lib/server-execution", async original => ({ - ...await original(), - withServerExecution: host.execute, -})); -vi.mock("@repo/platform/engine/lib/agent-exec", () => ({ execOnHost: host.command })); - -import { db, schema, seedOwner } from "../jobs/_harness"; -import { serverResourceRoutes } from "../../../src/modules/system/server-resource.routes"; -import { handleApiError } from "../../../src/middleware/error-handler"; - -const app = new Hono().onError(handleApiError).route("/api/system", serverResourceRoutes); -beforeEach(() => { - vi.clearAllMocks(); - host.command.mockResolvedValue({ output: "probe", exitCode: 0, timedOut: false, truncated: false, durationMs: 1 }); - host.execute.mockImplementation(async (_org, _id, work) => work({})); -}); - -it("rejects an authenticated member before host dispatch and preserves administrator execution", async () => { - const actor = await seedOwner(); - const id = `server-${actor.userId}`; - await db.insert(schema.servers).values({ id, organizationId: actor.orgId, name: "Fixture host", sshHost: "203.0.113.10", sshUser: "root" }); - const membership = and(eq(schema.member.userId, actor.userId), eq(schema.member.organizationId, actor.orgId)); - const execute = (serverId = id) => app.request(`/api/system/servers/${serverId}/exec`, { - method: "POST", headers: { ...actor.auth, "Content-Type": "application/json" }, body: JSON.stringify({ command: "id" }), - }); - await db.update(schema.member).set({ role: "member" }).where(membership); - expect((await execute()).status).toBe(404); - expect(host.execute).not.toHaveBeenCalled(); - expect(host.command).not.toHaveBeenCalled(); - await db.update(schema.member).set({ role: "admin" }).where(membership); - expect((await execute()).status).toBe(200); - expect(host.execute).toHaveBeenCalledOnce(); - expect(host.command).toHaveBeenCalledOnce(); - const other = await seedOwner(); - const otherServer = `server-${other.userId}`; - await db.insert(schema.servers).values({ id: otherServer, organizationId: other.orgId, name: "Other organization", sshHost: "203.0.113.11" }); - expect((await execute(otherServer)).status).toBe(404); - expect(host.command).toHaveBeenCalledOnce(); - await db.update(schema.member).set({ role: "member" }).where(membership); - expect((await execute()).status).toBe(404); - expect(host.command).toHaveBeenCalledOnce(); -}); diff --git a/apps/api/test/modules/tokens/mint-org-binding.test.ts b/apps/api/test/modules/tokens/mint-org-binding.test.ts index b0998efd1..88e421d30 100644 --- a/apps/api/test/modules/tokens/mint-org-binding.test.ts +++ b/apps/api/test/modules/tokens/mint-org-binding.test.ts @@ -188,16 +188,6 @@ beforeEach(() => { }); describe("finding 1: grant width is checked in the org the binding is written to", () => { - it("refuses server administration grants for an ordinary member", async () => { - const grants = [{ resourceType: "server", resourceId: "*", permissions: ["admin"] }]; - const refused = await authorize(OWNER_ORG, { clientId: "cli", organizationId: VICTIM_ORG, grants }); - expect(refused.status).toBe(403); - expect(refused.body.code).toBe("GRANT_EXCEEDS_ACCESS"); - expect(upsertOAuthBindingWithGrants).not.toHaveBeenCalled(); - const allowed = await authorize(OWNER_ORG, { clientId: "cli", organizationId: OWNER_ORG, grants }); - expect(allowed.status).toBe(200); - }); - /** * `billing` and `audit` are the two types `roleAllowsResourceType` denies a * member, and both are grantable — so they isolate "authority comes from the diff --git a/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx b/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx index b9513fcc3..138d19258 100644 --- a/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx +++ b/apps/dashboard/src/app/(dashboard)/DashboardHomeClient.tsx @@ -143,7 +143,7 @@ export default function DashboardHomeClient({ ) : (
{sourceProjects.slice(0, 5).map((p) => ( - removeProject(p.id)} /> + removeProject(p.id)} /> ))}
)} diff --git a/apps/dashboard/src/app/(dashboard)/apps/page.tsx b/apps/dashboard/src/app/(dashboard)/apps/page.tsx index 377e5f5f2..4ba8cd845 100644 --- a/apps/dashboard/src/app/(dashboard)/apps/page.tsx +++ b/apps/dashboard/src/app/(dashboard)/apps/page.tsx @@ -184,7 +184,7 @@ export default function AppsPage() {
{filteredApps.length > 0 ? filteredApps.map(app => ( - removeProject(app.id)} /> + removeProject(app.id)} /> )) : (

{copy.catalogNoResults}

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

{importDataLabel(service, choice)}

- {projectCount > 1 && ( -

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

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

Review complete

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

- {projectCount > 1 && ( -

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

- )}

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

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

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

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

- {hint} -

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

{c.previewFailed}

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

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

+ {displayInitial} +
{!collapsed && ( <> diff --git a/apps/dashboard/src/components/ui/UserAvatar.tsx b/apps/dashboard/src/components/ui/UserAvatar.tsx deleted file mode 100644 index e398f65d7..000000000 --- a/apps/dashboard/src/components/ui/UserAvatar.tsx +++ /dev/null @@ -1,37 +0,0 @@ -"use client"; - -import { useImageFallback } from "@/hooks/useImageFallback"; -import { cn } from "@/lib/utils"; - -export function UserAvatar({ - image, - name, - className, -}: { - image?: string | null; - name: string; - className?: string; -}) { - const fallback = useImageFallback(image); - return ( - - {fallback.showImage ? ( - - ) : ( - name[0] || "?" - )} - - ); -} diff --git a/apps/dashboard/src/constants/mock.ts b/apps/dashboard/src/constants/mock.ts index 91532d414..a69bb41eb 100644 --- a/apps/dashboard/src/constants/mock.ts +++ b/apps/dashboard/src/constants/mock.ts @@ -78,7 +78,7 @@ export interface Project { lifecycleOperation?: ProjectLifecycleOperation | null; /* ── Hosting info (enriched by API) ─────────────────────── */ - iconUrl?: string | null; + favicon?: string | null; deployTarget?: string | null; serverId?: string | null; serverName?: string | null; diff --git a/apps/dashboard/src/i18n/locales/ar/projectSettings.json b/apps/dashboard/src/i18n/locales/ar/projectSettings.json index 8ccbdf611..21e36d9ea 100644 --- a/apps/dashboard/src/i18n/locales/ar/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/ar/projectSettings.json @@ -1437,10 +1437,5 @@ "bytes": "بايت", "emptyBodyHint": "يتطلب رمز الحالة هذا محتوى استجابة فارغًا.", "headersHint": "أضف ترويسات للتخزين المؤقت أو CORS أو غيرها." - }, - "icon": { - "label": "رابط أيقونة المشروع", - "hint": "استخدم رابط صورة HTTP أو HTTPS. امسحه لاستخدام الأيقونة الافتراضية.", - "reset": "استخدام الأيقونة الافتراضية" } } diff --git a/apps/dashboard/src/i18n/locales/ar/settings.json b/apps/dashboard/src/i18n/locales/ar/settings.json index 7e6d02ff5..360545e81 100644 --- a/apps/dashboard/src/i18n/locales/ar/settings.json +++ b/apps/dashboard/src/i18n/locales/ar/settings.json @@ -1791,21 +1791,5 @@ "confirmCta": "إيقاف الخدمة", "cancel": "إلغاء", "noReverseProxy": "لم يتم اكتشاف وكيل عكسي على هذا الجهاز." - }, - "imageUrl": { - "preview": "معاينة الصورة", - "invalid": "أدخل رابط صورة HTTP أو HTTPS بدون بيانات تسجيل دخول.", - "failed": "تعذّر حفظ رابط الصورة.", - "save": "حفظ", - "saving": "جارٍ الحفظ…", - "saved": "تم الحفظ", - "previewFailed": "المعاينة غير متاحة. تأكد أن الرابط يشير مباشرةً إلى صورة." - }, - "profile": { - "title": "الملف الشخصي", - "description": "صورة حسابك الشخصي.", - "label": "رابط الصورة الشخصية", - "hint": "استخدم رابط صورة مباشرًا. اتركه فارغًا لاستخدام الحرف الأول من اسمك.", - "reset": "استخدام الحرف الأول" } } diff --git a/apps/dashboard/src/i18n/locales/de/projectSettings.json b/apps/dashboard/src/i18n/locales/de/projectSettings.json index 427e82fc1..b21c553ec 100644 --- a/apps/dashboard/src/i18n/locales/de/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/de/projectSettings.json @@ -1437,10 +1437,5 @@ "bytes": "Bytes", "emptyBodyHint": "Dieser Status erfordert einen leeren Antwortinhalt.", "headersHint": "Cache-, CORS- oder andere Antwortheader hinzufügen." - }, - "icon": { - "label": "URL des Projektsymbols", - "hint": "Verwende eine HTTP- oder HTTPS-Bild-URL. Leere sie, um das Standardsymbol zu verwenden.", - "reset": "Standardsymbol verwenden" } } diff --git a/apps/dashboard/src/i18n/locales/de/settings.json b/apps/dashboard/src/i18n/locales/de/settings.json index 296a00e59..2a500160e 100644 --- a/apps/dashboard/src/i18n/locales/de/settings.json +++ b/apps/dashboard/src/i18n/locales/de/settings.json @@ -1791,21 +1791,5 @@ "confirmCta": "Bereitstellung stoppen", "cancel": "Abbrechen", "noReverseProxy": "Auf dieser Maschine wurde kein Reverse-Proxy erkannt." - }, - "imageUrl": { - "preview": "Bildvorschau", - "invalid": "Gib eine HTTP- oder HTTPS-Bild-URL ohne Zugangsdaten ein.", - "failed": "Die Bild-URL konnte nicht gespeichert werden.", - "save": "Speichern", - "saving": "Wird gespeichert…", - "saved": "Gespeichert", - "previewFailed": "Keine Vorschau verfügbar. Prüfe, ob die URL direkt auf ein Bild verweist." - }, - "profile": { - "title": "Profil", - "description": "Das Bild deines persönlichen Kontos.", - "label": "Avatar-URL", - "hint": "Verwende eine direkte Bild-URL. Leer lassen, um deinen Anfangsbuchstaben anzuzeigen.", - "reset": "Anfangsbuchstaben verwenden" } } diff --git a/apps/dashboard/src/i18n/locales/en/projectSettings.json b/apps/dashboard/src/i18n/locales/en/projectSettings.json index 283ddea15..09e2bf804 100644 --- a/apps/dashboard/src/i18n/locales/en/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/en/projectSettings.json @@ -1437,10 +1437,5 @@ "bytes": "bytes", "emptyBodyHint": "This status requires an empty response body.", "headersHint": "Add cache, CORS, or other response headers." - }, - "icon": { - "label": "Project icon URL", - "hint": "Use an HTTP or HTTPS image URL. Clear it to use the default icon.", - "reset": "Use default icon" } } diff --git a/apps/dashboard/src/i18n/locales/en/settings.json b/apps/dashboard/src/i18n/locales/en/settings.json index ff151942c..77286e291 100644 --- a/apps/dashboard/src/i18n/locales/en/settings.json +++ b/apps/dashboard/src/i18n/locales/en/settings.json @@ -1791,21 +1791,5 @@ "title": "Demo mode", "description": "Blur IP addresses, hosts, and environment values during screen-shares and recordings." } - }, - "imageUrl": { - "preview": "Image preview", - "invalid": "Enter an HTTP or HTTPS image URL without embedded credentials.", - "failed": "Could not save the image URL.", - "save": "Save", - "saving": "Saving…", - "saved": "Saved", - "previewFailed": "Preview unavailable. Check that the URL points directly to an image." - }, - "profile": { - "title": "Profile", - "description": "Your personal account image.", - "label": "Avatar URL", - "hint": "Use a direct image URL. Leave empty to use your initial.", - "reset": "Use initial" } } diff --git a/apps/dashboard/src/i18n/locales/es/projectSettings.json b/apps/dashboard/src/i18n/locales/es/projectSettings.json index fd96834e2..e7e7bfe01 100644 --- a/apps/dashboard/src/i18n/locales/es/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/es/projectSettings.json @@ -1437,10 +1437,5 @@ "bytes": "bytes", "emptyBodyHint": "Este estado requiere un cuerpo de respuesta vacío.", "headersHint": "Añade cabeceras de caché, CORS u otras." - }, - "icon": { - "label": "URL del icono del proyecto", - "hint": "Usa una URL de imagen HTTP o HTTPS. Bórrala para usar el icono predeterminado.", - "reset": "Usar icono predeterminado" } } diff --git a/apps/dashboard/src/i18n/locales/es/settings.json b/apps/dashboard/src/i18n/locales/es/settings.json index 0d2c5871c..3ab15e30e 100644 --- a/apps/dashboard/src/i18n/locales/es/settings.json +++ b/apps/dashboard/src/i18n/locales/es/settings.json @@ -1791,21 +1791,5 @@ "confirmCta": "Dejar de servir", "cancel": "Cancelar", "noReverseProxy": "No se detectó ningún proxy inverso en esta máquina." - }, - "imageUrl": { - "preview": "Vista previa de la imagen", - "invalid": "Introduce una URL HTTP o HTTPS sin credenciales.", - "failed": "No se pudo guardar la URL de la imagen.", - "save": "Guardar", - "saving": "Guardando…", - "saved": "Guardado", - "previewFailed": "Vista previa no disponible. Comprueba que la URL enlace directamente a una imagen." - }, - "profile": { - "title": "Perfil", - "description": "La imagen de tu cuenta personal.", - "label": "URL del avatar", - "hint": "Usa una URL directa de imagen. Déjala vacía para mostrar tu inicial.", - "reset": "Usar inicial" } } diff --git a/apps/dashboard/src/i18n/locales/fr/projectSettings.json b/apps/dashboard/src/i18n/locales/fr/projectSettings.json index af9bb4454..df9987abb 100644 --- a/apps/dashboard/src/i18n/locales/fr/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/fr/projectSettings.json @@ -1437,10 +1437,5 @@ "bytes": "octets", "emptyBodyHint": "Ce statut nécessite un corps de réponse vide.", "headersHint": "Ajoutez des en-têtes de cache, CORS ou autres." - }, - "icon": { - "label": "URL de l’icône du projet", - "hint": "Utilisez une URL d’image HTTP ou HTTPS. Effacez-la pour utiliser l’icône par défaut.", - "reset": "Utiliser l’icône par défaut" } } diff --git a/apps/dashboard/src/i18n/locales/fr/settings.json b/apps/dashboard/src/i18n/locales/fr/settings.json index 5614429ab..4a43b3d39 100644 --- a/apps/dashboard/src/i18n/locales/fr/settings.json +++ b/apps/dashboard/src/i18n/locales/fr/settings.json @@ -1791,21 +1791,5 @@ "confirmCta": "Cesser de servir", "cancel": "Annuler", "noReverseProxy": "Aucun proxy inverse détecté sur cette machine." - }, - "imageUrl": { - "preview": "Aperçu de l’image", - "invalid": "Saisissez une URL HTTP ou HTTPS sans identifiants.", - "failed": "Impossible d’enregistrer l’URL de l’image.", - "save": "Enregistrer", - "saving": "Enregistrement…", - "saved": "Enregistré", - "previewFailed": "Aperçu indisponible. Vérifiez que l’URL pointe directement vers une image." - }, - "profile": { - "title": "Profil", - "description": "L’image de votre compte personnel.", - "label": "URL de l’avatar", - "hint": "Utilisez une URL directe d’image. Laissez vide pour afficher votre initiale.", - "reset": "Utiliser l’initiale" } } diff --git a/apps/dashboard/src/i18n/locales/ja/projectSettings.json b/apps/dashboard/src/i18n/locales/ja/projectSettings.json index 17f63ef7a..1829beee8 100644 --- a/apps/dashboard/src/i18n/locales/ja/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/ja/projectSettings.json @@ -1437,10 +1437,5 @@ "bytes": "バイト", "emptyBodyHint": "このステータスではレスポンス本文を空にする必要があります。", "headersHint": "キャッシュ、CORSなどのレスポンスヘッダーを追加します。" - }, - "icon": { - "label": "プロジェクトアイコンの URL", - "hint": "HTTP または HTTPS の画像 URL を指定してください。空にすると既定のアイコンに戻ります。", - "reset": "既定のアイコンを使用" } } diff --git a/apps/dashboard/src/i18n/locales/ja/settings.json b/apps/dashboard/src/i18n/locales/ja/settings.json index db135bb68..9394731c4 100644 --- a/apps/dashboard/src/i18n/locales/ja/settings.json +++ b/apps/dashboard/src/i18n/locales/ja/settings.json @@ -1791,21 +1791,5 @@ "confirmCta": "配信を停止", "cancel": "キャンセル", "noReverseProxy": "このマシンでリバースプロキシが検出されませんでした。" - }, - "imageUrl": { - "preview": "画像プレビュー", - "invalid": "認証情報を含まない HTTP または HTTPS の画像 URL を入力してください。", - "failed": "画像 URL を保存できませんでした。", - "save": "保存", - "saving": "保存中…", - "saved": "保存しました", - "previewFailed": "プレビューを表示できません。画像の直接 URL か確認してください。" - }, - "profile": { - "title": "プロフィール", - "description": "個人アカウントの画像。", - "label": "アバター URL", - "hint": "画像の直接 URL を使用します。空欄にすると名前の頭文字を表示します。", - "reset": "頭文字を使用" } } diff --git a/apps/dashboard/src/i18n/locales/pt/projectSettings.json b/apps/dashboard/src/i18n/locales/pt/projectSettings.json index a3ca74b0a..b27f511cf 100644 --- a/apps/dashboard/src/i18n/locales/pt/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/pt/projectSettings.json @@ -1437,10 +1437,5 @@ "bytes": "bytes", "emptyBodyHint": "Este estado exige um corpo de resposta vazio.", "headersHint": "Adicione cabeçalhos de cache, CORS ou outros." - }, - "icon": { - "label": "URL do ícone do projeto", - "hint": "Use uma URL de imagem HTTP ou HTTPS. Limpe-a para usar o ícone padrão.", - "reset": "Usar ícone padrão" } } diff --git a/apps/dashboard/src/i18n/locales/pt/settings.json b/apps/dashboard/src/i18n/locales/pt/settings.json index 883f9ab06..3fa1a6087 100644 --- a/apps/dashboard/src/i18n/locales/pt/settings.json +++ b/apps/dashboard/src/i18n/locales/pt/settings.json @@ -1791,21 +1791,5 @@ "confirmCta": "Parar de servir", "cancel": "Cancelar", "noReverseProxy": "Nenhum proxy reverso detectado nesta máquina." - }, - "imageUrl": { - "preview": "Prévia da imagem", - "invalid": "Insira uma URL HTTP ou HTTPS sem credenciais.", - "failed": "Não foi possível salvar a URL da imagem.", - "save": "Salvar", - "saving": "Salvando…", - "saved": "Salvo", - "previewFailed": "Prévia indisponível. Verifique se a URL aponta diretamente para uma imagem." - }, - "profile": { - "title": "Perfil", - "description": "A imagem da sua conta pessoal.", - "label": "URL do avatar", - "hint": "Use uma URL direta de imagem. Deixe em branco para usar sua inicial.", - "reset": "Usar inicial" } } diff --git a/apps/dashboard/src/i18n/locales/ru/projectSettings.json b/apps/dashboard/src/i18n/locales/ru/projectSettings.json index 444152582..80843ddf0 100644 --- a/apps/dashboard/src/i18n/locales/ru/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/ru/projectSettings.json @@ -1437,10 +1437,5 @@ "bytes": "байт", "emptyBodyHint": "Этот статус требует пустого тела ответа.", "headersHint": "Добавьте заголовки кеширования, CORS или другие." - }, - "icon": { - "label": "URL значка проекта", - "hint": "Укажите HTTP- или HTTPS-ссылку на изображение. Очистите её, чтобы использовать значок по умолчанию.", - "reset": "Стандартный значок" } } diff --git a/apps/dashboard/src/i18n/locales/ru/settings.json b/apps/dashboard/src/i18n/locales/ru/settings.json index 1ee579392..59cb29a08 100644 --- a/apps/dashboard/src/i18n/locales/ru/settings.json +++ b/apps/dashboard/src/i18n/locales/ru/settings.json @@ -1791,21 +1791,5 @@ "title": "Демо-режим", "description": "Размывать IP-адреса, хосты и переменные окружения при показе экрана и записи видео." } - }, - "imageUrl": { - "preview": "Предпросмотр изображения", - "invalid": "Введите HTTP- или HTTPS-адрес изображения без учётных данных.", - "failed": "Не удалось сохранить адрес изображения.", - "save": "Сохранить", - "saving": "Сохранение…", - "saved": "Сохранено", - "previewFailed": "Предпросмотр недоступен. Проверьте, что URL ведёт прямо к изображению." - }, - "profile": { - "title": "Профиль", - "description": "Изображение вашего личного аккаунта.", - "label": "URL аватара", - "hint": "Укажите прямую ссылку на изображение. Оставьте поле пустым, чтобы показать инициал.", - "reset": "Использовать инициал" } } diff --git a/apps/dashboard/src/i18n/locales/tr/projectSettings.json b/apps/dashboard/src/i18n/locales/tr/projectSettings.json index 9f55585ea..b81cee71b 100644 --- a/apps/dashboard/src/i18n/locales/tr/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/tr/projectSettings.json @@ -1437,10 +1437,5 @@ "bytes": "bayt", "emptyBodyHint": "Bu durum kodu boş bir yanıt gövdesi gerektirir.", "headersHint": "Önbellek, CORS veya diğer yanıt başlıklarını ekleyin." - }, - "icon": { - "label": "Proje simgesi URL’si", - "hint": "HTTP veya HTTPS resim URL’si kullanın. Varsayılan simgeyi kullanmak için URL’yi temizleyin.", - "reset": "Varsayılan simgeyi kullan" } } diff --git a/apps/dashboard/src/i18n/locales/tr/settings.json b/apps/dashboard/src/i18n/locales/tr/settings.json index 563cf2944..343010e85 100644 --- a/apps/dashboard/src/i18n/locales/tr/settings.json +++ b/apps/dashboard/src/i18n/locales/tr/settings.json @@ -1791,21 +1791,5 @@ "confirmCta": "Sunmayı durdur", "cancel": "İptal", "noReverseProxy": "Bu makinede ters proxy algılanmadı." - }, - "imageUrl": { - "preview": "Resim önizlemesi", - "invalid": "Kimlik bilgisi içermeyen bir HTTP veya HTTPS resim URL’si girin.", - "failed": "Resim URL’si kaydedilemedi.", - "save": "Kaydet", - "saving": "Kaydediliyor…", - "saved": "Kaydedildi", - "previewFailed": "Önizleme kullanılamıyor. URL’nin doğrudan bir resme yöneldiğini kontrol edin." - }, - "profile": { - "title": "Profil", - "description": "Kişisel hesabınızın resmi.", - "label": "Avatar URL’si", - "hint": "Doğrudan bir resim URL’si kullanın. Baş harfiniz için boş bırakın.", - "reset": "Baş harfi kullan" } } diff --git a/apps/dashboard/src/i18n/locales/zh/projectSettings.json b/apps/dashboard/src/i18n/locales/zh/projectSettings.json index ab52939d9..8d912db95 100644 --- a/apps/dashboard/src/i18n/locales/zh/projectSettings.json +++ b/apps/dashboard/src/i18n/locales/zh/projectSettings.json @@ -1437,10 +1437,5 @@ "bytes": "字节", "emptyBodyHint": "此状态码要求响应正文为空。", "headersHint": "添加缓存、CORS 或其他响应标头。" - }, - "icon": { - "label": "项目图标 URL", - "hint": "使用 HTTP 或 HTTPS 图片 URL。清空后将使用默认图标。", - "reset": "使用默认图标" } } diff --git a/apps/dashboard/src/i18n/locales/zh/settings.json b/apps/dashboard/src/i18n/locales/zh/settings.json index 682c418c8..753bd8f2a 100644 --- a/apps/dashboard/src/i18n/locales/zh/settings.json +++ b/apps/dashboard/src/i18n/locales/zh/settings.json @@ -1791,21 +1791,5 @@ "confirmCta": "停止服务", "cancel": "取消", "noReverseProxy": "在此机器上未检测到反向代理。" - }, - "imageUrl": { - "preview": "图片预览", - "invalid": "请输入不含凭据的 HTTP 或 HTTPS 图片 URL。", - "failed": "无法保存图片 URL。", - "save": "保存", - "saving": "正在保存…", - "saved": "已保存", - "previewFailed": "无法预览。请检查 URL 是否直接指向图片。" - }, - "profile": { - "title": "个人资料", - "description": "你的个人账户图片。", - "label": "头像 URL", - "hint": "使用图片的直接 URL。留空则显示姓名首字母。", - "reset": "使用首字母" } } diff --git a/apps/dashboard/src/lib/api/connections.ts b/apps/dashboard/src/lib/api/connections.ts index 58e3e6043..54c2c54a1 100644 --- a/apps/dashboard/src/lib/api/connections.ts +++ b/apps/dashboard/src/lib/api/connections.ts @@ -1,4 +1,3 @@ -import type { ProjectConnectionCandidate } from "@repo/contracts"; import { api } from "./client"; import { endpoints } from "./endpoints"; @@ -49,7 +48,15 @@ async function notifyConnections(request: Promise): Promise { export const connectionsApi = { candidates: (projectId: string) => - api.get<{ data: ProjectConnectionCandidate[] }>(`${endpoints.projects.connections(projectId)}/candidates`), + api.get<{ + data: Array<{ + id: string; + name: string; + description: string; + appTemplateId: string | null; + clusterId?: string | null; + }>; + }>(`${endpoints.projects.connections(projectId)}/candidates`), /** Connections wired INTO a project (`projectId` = the consumer). */ list: (projectId: string) => api.get<{ data: ProjectConnection[] }>(endpoints.projects.connections(projectId)), diff --git a/apps/web/content/docs/dashboard/projects.mdx b/apps/web/content/docs/dashboard/projects.mdx index cb456e05f..c616684dc 100644 --- a/apps/web/content/docs/dashboard/projects.mdx +++ b/apps/web/content/docs/dashboard/projects.mdx @@ -13,7 +13,7 @@ its management tabs). Open **Projects** from the left nav. This screen is a single scannable list of every project in your workspace — one row per project. -Each row shows, left to right: the project icon (set in **Settings → Project Info**), or its app/framework logo, the **name** +Each row shows, left to right: the app's icon (its favicon, or the framework logo), the **name** and its live version badge, the primary **domain**, the detected **framework**, where it's hosted (**Cloud**, a **Server** by name, or **Local**), its source (a GitHub repo or a local folder), the build shape (**Services**, **Static**, or **Standalone**), how long ago it changed, and a diff --git a/docs/dashboard-design.md b/docs/dashboard-design.md index b7a1b30f8..d09a84ef8 100644 --- a/docs/dashboard-design.md +++ b/docs/dashboard-design.md @@ -5,13 +5,6 @@ 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. @@ -1072,11 +1065,9 @@ 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 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. +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. 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 60e9dc512..cfa70c3cc 100644 --- a/docs/mail-engine-state.md +++ b/docs/mail-engine-state.md @@ -25,13 +25,10 @@ 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. -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. +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. 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 e72b03223..c9f0baca7 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. 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. +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. 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 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. +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. 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 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 | +| 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 | | 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. 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. +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. 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,18 +70,6 @@ Import tests cover review binding and drift, exact Git revisions, destination pr source downtime, database-first ordering, transfer failures, cancellation and owned SSH-key recovery. Database tests exercise multi-project migration locks and pending cleanup guards. -### Multi-repository verification — 2026-11-16 - -The project import Docker fixture now also covers an image-backed database and two -different Git sources, importing two environments with identical service names into -six destination projects. It checks each repository's revision, real private-network -connections, copied volumes, persistence after restart, and connection refresh during -an ordinary consumer redeployment. Both socket and Cloud Docker transports use an -isolated test daemon. Provider control, Git checkout, runtime destination resolution -and the asynchronous queue are fixture boundaries; this is not a live Railway or SaaS -account test. Focused tests additionally cover dependency ordering, connection failure -and recovery, old-plan rejection, and review blockers before source downtime. - ### Grouped project verification — 2026-11-12 `apps/api/test/e2e/platform-import-project.e2e.test.ts` imports two projects, each with diff --git a/docs/ship-sdk-plan.md b/docs/ship-sdk-plan.md index 9ffc7387c..924be50de 100644 --- a/docs/ship-sdk-plan.md +++ b/docs/ship-sdk-plan.md @@ -202,7 +202,7 @@ Existing patterns can support the main embedding models: - One organization per customer: a stable external customer mapping selects the organization; every operation stays within it. - One personal organization per user: personal project spaces use the existing organization/membership model. -- Several users in one customer organization: restricted roles and project grants provide project-level access. Ordinary members have read/write access but cannot satisfy admin operations; token grants respect the user's current built-in role. +- Several users in one customer organization: restricted roles and project grants provide project-level access. Ordinary membership may be broader, so use the appropriate policy deliberately. - Automated project creation: reuse the create-and-grant semantics of scoped tokens, and extend them deliberately for verified native principals. Project creation and the associated access grant must have defined transactional behavior. - Namespace-oriented products: first map external namespace keys to an existing tenant or appropriate grouping. If nested namespace isolation is required, add a tenant-owned namespace model, grant semantics, scoped queries, and migrations. A string prefix or renamed project group is insufficient. diff --git a/packages/adapters/src/system/mail/ensure-container-mail.test.ts b/packages/adapters/src/system/mail/ensure-container-mail.test.ts index 0025e6c70..e9c66f8d6 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, beforeEach, describe, expect, it, vi } from "vitest"; +import { afterEach, describe, expect, it, vi } from "vitest"; import { buildMailRunCommand, @@ -401,8 +401,7 @@ describe("ensureContainerMail swap", () => { if (cmd.includes("/proc/net/tcp")) return PROC_LISTENING; return ""; }); - const readFile = vi.fn(async () => "FIRST_DOMAIN=mail.example.com\n"); - const executor = { exec, streamExec, writeFile: vi.fn(async () => {}), readFile } as never; + const executor = { exec, streamExec, writeFile: vi.fn(async () => {}) } as never; await ensureContainerMail(executor, { domain: "example.com", @@ -417,123 +416,6 @@ 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 7cba66808..82798ed9f 100644 --- a/packages/adapters/src/system/mail/ensure-container-mail.ts +++ b/packages/adapters/src/system/mail/ensure-container-mail.ts @@ -342,36 +342,6 @@ 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. @@ -686,8 +656,6 @@ 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 254f540ca..05b0d73e4 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()), - iconUrl: Type.Optional(Type.Union([Type.String(), Type.Null()])), + favicon: 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 9d2ec55c9..267209c63 100644 --- a/packages/contracts/src/platform-migration.ts +++ b/packages/contracts/src/platform-migration.ts @@ -72,7 +72,6 @@ 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 bfa89184c..d75ad8545 100644 --- a/packages/contracts/src/project-inputs.ts +++ b/packages/contracts/src/project-inputs.ts @@ -8,7 +8,6 @@ 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, @@ -560,10 +559,7 @@ 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.Object({ - ...Type.Partial(Type.Omit(CreateProjectBody, ["serverId"])).properties, - iconUrl: Type.Optional(Type.Union([Type.String({ maxLength: MAX_IMAGE_URL_LENGTH }), Type.Null()])), -}); +export const UpdateProjectBody = Type.Partial(Type.Omit(CreateProjectBody, ["serverId"])); /** * 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 93a8c3551..5b8f4797e 100644 --- a/packages/contracts/src/project-integrations.ts +++ b/packages/contracts/src/project-integrations.ts @@ -55,21 +55,18 @@ 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(ProjectConnectionCandidateSchema), + output: Type.Array( + Type.Object({ + id: Type.String(), + name: Type.String(), + description: Type.String(), + appTemplateId: nullableString, + clusterId: Type.Optional(nullableString), + }), + ), }, 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 6204f1de6..41eb79398 100644 --- a/packages/contracts/src/projects.ts +++ b/packages/contracts/src/projects.ts @@ -14,7 +14,6 @@ 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 856f2ad0c..8b5151aa4 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:3.4.1", + "image": "ghcr.io/umami-software/umami:postgresql-v2.20.2", "exposedPort": 3000, "exposed": true, "routes": [ diff --git a/packages/core/src/apps/catalog/umami.json b/packages/core/src/apps/catalog/umami.json index 0325382e9..24cbb8d6a 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:3.4.1", + "image": "ghcr.io/umami-software/umami:postgresql-v2.20.2", "exposedPort": 3000, "exposed": true, "routes": [ diff --git a/packages/core/src/apps/umami.test.ts b/packages/core/src/apps/umami.test.ts index 2494a20b3..1fc02cab8 100644 --- a/packages/core/src/apps/umami.test.ts +++ b/packages/core/src/apps/umami.test.ts @@ -2,21 +2,17 @@ import { describe, expect, it } from "vitest"; import { getAppTemplate } from "../app-templates"; describe("Umami catalog security update", () => { - it("uses the security-patched v3 PostgreSQL release", () => { + it("uses the security-patched v2 PostgreSQL release", () => { const umami = getAppTemplate("umami"); const image = umami?.services?.find((service) => service.name === "umami")?.image; - // 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+)$/); + const version = image?.match(/^ghcr\.io\/umami-software\/umami:postgresql-v2\.(\d+)\.(\d+)$/); expect( version, - "Use an official patched v3 image; a major upgrade needs a migration review", + "Use an official patched v2 image; a major upgrade needs a migration review", ).toBeTruthy(); const [, minor, patch] = version!; - // 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); + // v2.20.2 carries the Next.js / React Server Components security fixes. + expect(Number(minor) > 20 || (Number(minor) === 20 && Number(patch) >= 2)).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 deleted file mode 100644 index 79a613338..000000000 --- a/packages/core/src/image-url.test.ts +++ /dev/null @@ -1,25 +0,0 @@ -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 deleted file mode 100644 index 137c1d4a6..000000000 --- a/packages/core/src/image-url.ts +++ /dev/null @@ -1,23 +0,0 @@ -/** 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 2c33b6c39..fa306c0a2 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -1,5 +1,4 @@ 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 deleted file mode 100644 index 5ecc9e5f7..000000000 --- a/packages/db/drizzle/0231_project_icon_url.sql +++ /dev/null @@ -1 +0,0 @@ -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 deleted file mode 100644 index 9ba00e56a..000000000 --- a/packages/db/drizzle/0232_project_icon_cleanup.sql +++ /dev/null @@ -1,17 +0,0 @@ --- 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 71b3a5a43..d7a930769 100644 --- a/packages/db/drizzle/meta/_journal.json +++ b/packages/db/drizzle/meta/_journal.json @@ -1618,20 +1618,6 @@ "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 a2637d446..de514bf69 100644 --- a/packages/db/src/dump-roundtrip.test.ts +++ b/packages/db/src/dump-roundtrip.test.ts @@ -274,35 +274,6 @@ 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 731d8d9ba..cd320b1c9 100644 --- a/packages/db/src/dump.ts +++ b/packages/db/src/dump.ts @@ -1773,11 +1773,6 @@ 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 @@ -1840,11 +1835,6 @@ 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 de5aaf92b..6c50eecbb 100644 --- a/packages/db/src/migrate-chain.test.ts +++ b/packages/db/src/migrate-chain.test.ts @@ -268,47 +268,6 @@ 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"); @@ -327,7 +286,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(({ 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 })), + projects.map((project) => ({ ...project, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false })), ); expect((await client.query("SELECT * FROM deployment")).rows).toEqual( deployments.map((deployment) => ({ @@ -373,7 +332,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(({ 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 })), + 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 })), ); expect( (await client.query("SELECT * FROM drizzle.__drizzle_migrations ORDER BY id")).rows.slice( @@ -571,12 +530,11 @@ 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, favicon, favicon_checked_at: _checked, ...previous } = old as typeof old & Record; + const { cloud_workspace_id: _native, cloud_archive_strategy: _archive, ...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 9defd12db..add5653d8 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, iconUrl: project.iconUrl, + activeDeploymentId: project.activeDeploymentId, favicon: project.favicon, }).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 4488d9649..ffe4aa891 100644 --- a/packages/db/src/repos/project.repo.ts +++ b/packages/db/src/repos/project.repo.ts @@ -661,6 +661,25 @@ 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 098ae3a3d..023ae9fe3 100644 --- a/packages/db/src/schema/project.ts +++ b/packages/db/src/schema/project.ts @@ -69,6 +69,10 @@ 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(), @@ -495,8 +499,10 @@ export const project = pgTable( * nobody opted into paying for this, so nobody keeps paying for it silently. */ collectPaths: boolean("collect_paths").notNull().default(false), - /** Project display image, managed in project settings. */ - iconUrl: text("icon_url"), + /** 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"), /** Soft delete */ deletedAt: timestamp("deleted_at"), /** diff --git a/packages/platform/src/authorization.ts b/packages/platform/src/authorization.ts index 1411936e1..ec818a7db 100644 --- a/packages/platform/src/authorization.ts +++ b/packages/platform/src/authorization.ts @@ -99,8 +99,7 @@ export interface AuthorizationDependencies { } export interface PermissionOptions { - /** A credential may narrow membership authority to its own grants. */ - roleOverride?: "restricted"; + roleOverride?: ContextRole; grants?: PermissionGrantSource; } @@ -119,15 +118,14 @@ export const PROJECT_ROOTED: ReadonlySet = new Set([ "build_session", ]); -/** Shared role ceiling for execution and discovery; restricted roles use grants. */ +/** Shared with capability discovery; restricted roles use grants instead. */ export function roleAllowsResourceType( role: "owner" | "admin" | "member", type: CheckedResourceType, - action: Permission, ): boolean { if (role === "owner") return true; if (role === "admin") return type !== "billing"; - return action !== "admin" && type !== "billing" && type !== "audit"; + return type !== "billing" && type !== "audit"; } export function permitsAction(permissions: readonly GrantPermission[], action: Permission): boolean { @@ -264,12 +262,10 @@ export function createAuthorization(deps: AuthorizationDependencies) { if (!["read", "write", "admin", "create"].includes(input.action)) return false; const persistedRole = membershipRole(member); if (!persistedRole) return false; - // A token narrows its user's current authority. A previously minted grant - // must not retain administration after that user is demoted to member. - if (persistedRole !== "restricted") { - if (!roleAllowsResourceType(persistedRole, input.resourceType, input.action)) return false; - if (opts?.roleOverride !== "restricted") return true; - } + const role = opts?.roleOverride ?? persistedRole; + if (role === "owner" || role === "admin" || role === "member") + return roleAllowsResourceType(role, input.resourceType); + if (role !== "restricted") return false; const source = opts?.grants ?? repos.resourceGrant; // A create-only wildcard permits creation and a filtered list, never an diff --git a/packages/platform/src/engine/lib/auth.ts b/packages/platform/src/engine/lib/auth.ts index b51d75b0c..0528fa7fb 100644 --- a/packages/platform/src/engine/lib/auth.ts +++ b/packages/platform/src/engine/lib/auth.ts @@ -1,4 +1,3 @@ -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"; @@ -279,14 +278,6 @@ 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 20a1679e6..62284ce18 100644 --- a/packages/platform/src/engine/lib/cloud/project-promotion.ts +++ b/packages/platform/src/engine/lib/cloud/project-promotion.ts @@ -45,6 +45,8 @@ 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 new file mode 100644 index 000000000..f0eb03024 --- /dev/null +++ b/packages/platform/src/engine/lib/favicon-detector.ts @@ -0,0 +1,159 @@ +/** + * 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 01f05dd69..91b900d5d 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 and the list card's primaryDomain share, so + * URL, the list card's primaryDomain, and the favicon refresh all share, so * those surfaces can never disagree on which domain is "the" one. */ export function pickCanonicalDomainRow & { hostname?: string }>( rows: T[] | null | undefined, diff --git a/packages/platform/src/engine/modules/actions/triggers.test.ts b/packages/platform/src/engine/modules/actions/triggers.test.ts index a4d9b95d8..c00d616ec 100644 --- a/packages/platform/src/engine/modules/actions/triggers.test.ts +++ b/packages/platform/src/engine/modules/actions/triggers.test.ts @@ -33,7 +33,6 @@ vi.mock("./action.service", () => ({ rerunActionWorkflow: h.rerun, })); import { dispatchActionWebhook, enqueueActionWebhook } from "./triggers"; -import { GitHubApiError } from "../github/github.error"; const base = "a".repeat(40), head = "b".repeat(40), @@ -81,7 +80,6 @@ beforeEach(() => { owner: "acme", repo: "app", path: ".github/workflows/ci.yml", - source: null, authority: {}, allowForks: true, }, @@ -98,66 +96,6 @@ beforeEach(() => { const dispatch = (value = event()) => dispatchActionWebhook("pull_request", value, "delivery", target); -it.each(["push", "pull_request"])( - "ignores a workflow absent at the %s revision", - async (eventName) => { - h.file.mockRejectedValueOnce(new GitHubApiError(404, "Not Found", new Headers())); - const revision = eventName === "push" ? head : base; - h.fetch.mockImplementationOnce(async ({ url }) => { - if (url === `https://api.github.com/repos/acme/app/commits/${revision}`) - return { sha: revision }; - throw new Error(`Unexpected GitHub request: ${url}`); - }); - await dispatchActionWebhook( - eventName, - eventName === "push" ? { ...event(), ref: "refs/heads/other", after: head } : event(), - "delivery", - target, - ); - expect(h.trigger).not.toHaveBeenCalled(); - expect(h.error).toHaveBeenCalledExactlyOnceWith("org", "workflow", null); - }, -); - -it.each([403, 429, 500])("retains workflow source failures from GitHub (%s)", async (status) => { - const error = new GitHubApiError(status, "Unavailable", new Headers()); - h.file.mockRejectedValueOnce(error); - await expect(dispatch()).rejects.toThrow(error); - expect(h.trigger).not.toHaveBeenCalled(); - expect(h.error).toHaveBeenCalledWith("org", "workflow", error.message); -}); - -it("retains a missing revision or inaccessible repository as a workflow error", async () => { - const error = new GitHubApiError(404, "Not Found", new Headers()); - h.file.mockRejectedValueOnce(error); - h.fetch.mockRejectedValueOnce(error); - await expect(dispatch()).rejects.toThrow(error); - expect(h.trigger).not.toHaveBeenCalled(); - expect(h.error).toHaveBeenCalledWith("org", "workflow", error.message); -}); - -it("uses the pushed workflow's branch rules rather than the saved definition", async () => { - const workflows = await h.workflows(); - workflows[0].definition = { triggers: { push: { branches: ["main"] } } }; - h.file.mockResolvedValueOnce({ - content: source.replace( - "pull_request:\n types: [opened, reopened, synchronize, closed]", - "push:\n branches: [deploy/**]", - ), - }); - await dispatchActionWebhook( - "push", - { ...event(), ref: "refs/heads/deploy/topic", after: head }, - "delivery", - target, - ); - expect(h.trigger).toHaveBeenCalledOnce(); - expect(h.trigger.mock.calls[0]![2]).toMatchObject({ - revision: head, - ref: "refs/heads/deploy/topic", - }); -}); - it("routes GitHub-owned events to the exact workflow without storing webhook payloads", async () => { h.workflows.mockResolvedValueOnce([ { ...target, id: "first", controller: "github", githubWorkflowId: "123" }, diff --git a/packages/platform/src/engine/modules/actions/triggers.ts b/packages/platform/src/engine/modules/actions/triggers.ts index 43d4c4672..119ad9b37 100644 --- a/packages/platform/src/engine/modules/actions/triggers.ts +++ b/packages/platform/src/engine/modules/actions/triggers.ts @@ -8,7 +8,6 @@ import { nativeJobsEnabled } from "../../native/execution-policy"; import { resolveExecutionAuthority } from "../../lib/execution-authority"; import { githubFetch } from "../github/github.auth"; import { getFileContent } from "../github/github.service"; -import { GitHubApiError } from "../github/github.error"; import { triggerActionWorkflow, rerunActionWorkflow } from "./action.service"; import { parseActionWorkflow, record } from "./workflow"; import { matchesActionFilters } from "./trigger-pattern"; @@ -151,27 +150,13 @@ export async function dispatchActionWebhook( untrusted = pullRequest.head.repo.id !== pullRequest.repository.id; if (untrusted && !workflow.allowForks) continue; } - let source = workflow.source; - if (source == null) { - try { - source = ( - await getFileContent(ctx, owner, repo, workflow.path, { - branch: workflowRevision ?? revision, - }) - ).content; - } catch (error) { - if (!(error instanceof GitHubApiError && error.status === 404)) throw error; - // Only an absent file is a no-op. Repository and revision access must still work. - await githubFetch({ - ctx, - owner, - repo, - url: `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/commits/${workflowRevision ?? revision}`, - }); - await repos.actions.workflowError(workflow.organizationId, workflow.id, null); - continue; - } - } + const source = + workflow.source ?? + ( + await getFileContent(ctx, owner, repo, workflow.path, { + branch: workflowRevision ?? revision, + }) + ).content; const plan = await parseActionWorkflow(source, workflow.path); if ( !workflow.source && diff --git a/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts b/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts index f276201b8..061720d5a 100644 --- a/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts +++ b/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts @@ -38,6 +38,8 @@ 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"; @@ -1063,6 +1065,11 @@ 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 4b5cbb34b..2efe6c992 100644 --- a/packages/platform/src/engine/modules/deployments/deployment.service.ts +++ b/packages/platform/src/engine/modules/deployments/deployment.service.ts @@ -89,7 +89,9 @@ export async function listDeployments( ...d, isActive: d.id === activeId, projectName: project.name, - iconUrl: project.iconUrl ?? null, + // Project favicon → the dashboard uses it as the row's logo instead + // of the framework/Docker glyph. + favicon: project.favicon ?? null, })), }; } @@ -108,7 +110,8 @@ export async function listDeployments( ...d, projectName: proj?.name ?? "Unknown", isActive: proj?.activeDeploymentId === d.id, - iconUrl: proj?.iconUrl ?? null, + // Project favicon → dashboard row logo (see listByProject above). + favicon: proj?.favicon ?? null, }; }); diff --git a/packages/platform/src/engine/modules/domains/domain.service.ts b/packages/platform/src/engine/modules/domains/domain.service.ts index 91af17542..4e3904afe 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 analytics and the dashboard's project + * hostname — what favicon detection, 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 0ff935b26..15abd2c4e 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.projectName, + projectName: plan.project.name, 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 302c860e0..1f4d3cf13 100644 --- a/packages/platform/src/engine/modules/migration/platform-import-plan.ts +++ b/packages/platform/src/engine/modules/migration/platform-import-plan.ts @@ -1,11 +1,5 @@ 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, @@ -30,7 +24,7 @@ import { } from "./providers/types"; import { discoverExternalDatabases } from "./providers/external-databases"; import { resolveRailwayBindings } from "./providers/railway-wiring"; -import { platformImportProjects, type PlannedImportProject } from "./platform-import-project"; +import { platformImportProject } from "./platform-import-project"; export interface ImportBinding { sourceId: string; @@ -52,8 +46,7 @@ export interface PrivateImportPlan { inventory: ProviderInventory; fingerprint: string; targetServerId: string; - projectName: string; - projects: PlannedImportProject[]; + project: TEnsureProjectBody; services: PlannedImportService[]; requiresWritePause: boolean; requiresWorkerPause: boolean; @@ -535,7 +528,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 projects = platformImportProjects(projectName, input.targetServerId, services); + const project = platformImportProject(projectName, input.targetServerId, services); const plan: PrivateImportPlan = { id: randomUUID(), organizationId: ctx.organizationId, @@ -543,8 +536,7 @@ export async function reviewPlatform( inventory: draft.inventory, fingerprint: inventoryFingerprint(draft.inventory), targetServerId: input.targetServerId, - projectName, - projects, + project, services, ...(inventory.provider === "railway" ? { sourceControl: "railway-project" as const } : {}), requiresWritePause: services.some( @@ -567,10 +559,6 @@ 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, @@ -584,12 +572,8 @@ export async function loadReviewedImport( id: string, ): Promise { const plan = await get(ctx, "plan", id); - if (!plan.projects?.length) - throw new AppError( - "Review this import again before starting it.", - 409, - "IMPORT_REVIEW_EXPIRED", - ); + if (!plan.project) + 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 3415e69fe..61e7b6e53 100644 --- a/packages/platform/src/engine/modules/migration/platform-import-project.ts +++ b/packages/platform/src/engine/modules/migration/platform-import-project.ts @@ -3,83 +3,15 @@ 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.flatMap((binding) => { - const dependency = services.find((candidate) => candidate.source.id === binding.sourceId); - return dependency ? [dependency.create.name] : []; - }), + service.bindings.map( + (binding) => + services.find((dependency) => dependency.source.id === binding.sourceId)!.create.name, + ), ), ]; } @@ -105,8 +37,9 @@ export function platformImportRoutes(services: PlannedImportService[]): Migratio ); } -/** Translate one compatible group into ordinary project and service inputs. */ -function platformImportProject( +/** 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( name: string, serverId: string, services: PlannedImportService[], @@ -120,6 +53,15 @@ 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 b38ccaaf4..a6017cf9a 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, type Service } from "@repo/db"; +import { repos } from "@repo/db"; import type { ExecutionContext } from "../../../context"; import type { PrivateImportPlan, PlannedImportService } from "./platform-import-plan"; import { ensureProject } from "../projects/project-crud.service"; @@ -20,7 +20,6 @@ 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; @@ -77,29 +76,13 @@ export async function executePlatformImport( resourceId: plan.targetServerId, action: "write", }); - if (!plan.projects?.length) + if (!plan.project) 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, { @@ -108,61 +91,44 @@ export async function executePlatformImport( }); lifecycle.signal.throwIfAborted(); await lifecycle.phase("adopting"); - const bySource = new Map(); - for (const destination of destinations) { - lifecycle.signal.throwIfAborted(); - 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, + 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, - platformImportRoutes(destination.services), - lifecycle.log, + )) + ) + throw new AppError( + "The import was cancelled while creating its project. Its saved configuration was retained.", + 409, + "IMPORT_ADMISSION_CLOSED", ); - } 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) { + } + await repos.project.update(projectId, { autoDeploy: false, runtimeMode: "docker" }); + for (const service of services) { + 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) => { const row = rows.find((row) => row.name === service.create.name); if (!row) throw new AppError( @@ -170,9 +136,9 @@ export async function executePlatformImport( 409, "IMPORT_TARGET_SERVICE_MISSING", ); - bySource.set(service.source.id, row); - } - } + return [service.source.id, row] as const; + }), + ); const checkpoint = async () => { const current = (await repos.dockerMigrationRun.findById(runId))?.recovery.providerImport; if (!current) @@ -186,8 +152,7 @@ export async function executePlatformImport( }, }); const saveEnvironment = async (sourceId: string, values: Record) => { - const target = bySource.get(sourceId)!; - await mergeServiceEnvVars(ctx, target.projectId, target.id, { + await mergeServiceEnvVars(ctx, projectId, bySource.get(sourceId)!.id, { environment: "production", deletes: [], upserts: Object.entries(values).map(([key, value]) => ({ @@ -198,33 +163,16 @@ export async function executePlatformImport( })), }); }; - 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) await saveEnvironment(service.source.id, service.environment); 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, dependency.projectId)).outputs.find( + const output = (await getAppConnectionView(ctx, projectId)).outputs.find( (output) => output.internal && output.sourceServiceId === dependency.id && output.value, ); if (!output) @@ -247,7 +195,7 @@ export async function executePlatformImport( await copyPlatformData({ runId, service, - projectId: bySource.get(service.source.id)!.projectId, + projectId, serviceId: bySource.get(service.source.id)!.id, deploymentId, signal: lifecycle.signal, @@ -257,43 +205,11 @@ 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 ${destination.create.name}: ${selected.map((service) => service.create.name).join(", ")}`, + `Deploying ${plan.project.name}: ${selected.map((service) => service.create.name).join(", ")}`, ); - const source = destination.services.find((service) => service.create.gitRepo)?.source; + const source = services.find((service) => service.create.gitRepo)?.source; const result = await triggerDeployment(ctx, { projectId, serverId: plan.targetServerId, @@ -347,19 +263,8 @@ export async function executePlatformImport( } else await transfer(service); } } - // 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), - ), - ); + const deploymentId = await deploy(services); + await verifyPlatformDeployment(projectId, deploymentId, lifecycle.signal); await repos.dockerMigrationRun.updateRecovery(runId, { providerImport: { ...(await checkpoint()), @@ -367,7 +272,7 @@ export async function executePlatformImport( }, }); lifecycle.log( - `${plan.projectName} imported with ${services.length} services in ${destinations.length} project(s); source data retained.`, + `${plan.project.name} imported with ${services.length} services; 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 c880983a0..9aa69ae58 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. Retain a host template for native private - * connections when the destination must span several projects. */ + * aliases inside the imported project. Dependencies describe deployment order; + * they do not create cross-project connections or publish database ports. */ export function resolveRailwayBindings( service: PlannedImportService, selected: Map, @@ -26,32 +26,10 @@ 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.some( - (binding) => binding.sourceId === source!.source.id && binding.envKey === key, - ) - ) - bindings.push({ - sourceId: source!.source.id, - envKey: key, - ...(template === undefined ? {} : { valueTemplate: template }), - }); + if (source !== service) bindings.push({ sourceId: source!.source.id, envKey: key }); // 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) { @@ -60,8 +38,7 @@ export function resolveRailwayBindings( const port = Number( url.port || (url.protocol === "https:" ? 443 : url.protocol === "http:" ? 80 : 0), ); - if (url.hostname.toLowerCase() === host.toLowerCase() && port > 0 && port <= 65535) - source!.source.port = port; + if (url.hostname === host && 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 227c2d705..6abf0122d 100644 --- a/packages/platform/src/engine/modules/projects/project-clone.service.ts +++ b/packages/platform/src/engine/modules/projects/project-clone.service.ts @@ -68,6 +68,10 @@ 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 70a45f7cb..2678838fb 100644 --- a/packages/platform/src/engine/modules/projects/project-connection.service.ts +++ b/packages/platform/src/engine/modules/projects/project-connection.service.ts @@ -87,8 +87,6 @@ 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 ebc17449d..d69a954e3 100644 --- a/packages/platform/src/engine/modules/projects/project-crud.service.ts +++ b/packages/platform/src/engine/modules/projects/project-crud.service.ts @@ -13,7 +13,8 @@ import { type Project, type Server, } from "@repo/db"; -import { isImageUrl, slugify, +import { + slugify, runtimeProjectUpdate, assertRuntimeVersionTarget, AppError, @@ -1901,11 +1902,6 @@ 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 671ff94d0..a2b516850 100644 --- a/packages/platform/src/engine/modules/projects/project-home.operations.ts +++ b/packages/platform/src/engine/modules/projects/project-home.operations.ts @@ -5,6 +5,7 @@ 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"; @@ -85,6 +86,10 @@ 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 bcabfcc9e..e04eefa03 100644 --- a/packages/platform/src/engine/modules/projects/project-inspection.operations.ts +++ b/packages/platform/src/engine/modules/projects/project-inspection.operations.ts @@ -12,7 +12,8 @@ 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 { resolveProjectAccess } from "../../lib/public-endpoints"; +import { refreshProjectFaviconIfStale } from "../../lib/favicon-detector"; +import { pickCanonicalDomainRow, resolveProjectAccess } from "../../lib/public-endpoints"; import { readProjectRoutingClaims } from "../../lib/domain-claims"; import { serviceCustomHostnames } from "../../lib/routing-domains"; import { withDomainDiagnostics } from "../domains/domain-diagnostics"; @@ -106,6 +107,9 @@ 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 b37b91194..5ed4def9a 100644 --- a/packages/platform/src/engine/modules/projects/project.operations.ts +++ b/packages/platform/src/engine/modules/projects/project.operations.ts @@ -10,6 +10,7 @@ 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"; @@ -87,6 +88,7 @@ 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) { @@ -111,6 +113,7 @@ export const projectDependencies: ProjectDependencies = { }), }), }); + result.rows.forEach((row) => refreshProjectFaviconIfStale(row)); return { ...result, rows: result.rows.map((p) => ({ ...p, source: "local" })) }; }, recordAudit, diff --git a/packages/platform/src/engine/modules/system/server.operations.ts b/packages/platform/src/engine/modules/system/server.operations.ts index 207b73bfd..b683ac6e8 100644 --- a/packages/platform/src/engine/modules/system/server.operations.ts +++ b/packages/platform/src/engine/modules/system/server.operations.ts @@ -820,8 +820,9 @@ async function execOnServer( body: Parameters[1], ) { - // The shared server operation asserts server:admin before calling this service - // for every transport. Retain the organization-scoped lookup here as well. + // Primary gate: permission resolver (404 on deny, IDOR-safe). Asserted BEFORE the + // row is read, so a caller without access cannot distinguish "no such server" + // from "not yours". const server = await repos.server.getInOrganization(id, ctx.organizationId); if (!server) return failServer({ error: "Server not found" }, 404); diff --git a/packages/platform/test/authorization.test.ts b/packages/platform/test/authorization.test.ts index 2fb4948d9..465ec67bd 100644 --- a/packages/platform/test/authorization.test.ts +++ b/packages/platform/test/authorization.test.ts @@ -31,45 +31,6 @@ beforeEach(async () => { }); describe("shared authorization", () => { - it("does not grant administration to an ordinary member", async () => { - state.members.set("org-a:alice", { id: "member-a", role: "member" }); - state.servers.set("server-a", { organizationId: "org-a" }); - const input = { resourceType: "server" as const, resourceId: "server-a", action: "admin" as const }; - expect(await auth.checkPermission("alice", "org-a", input)).toBe(false); - expect(await auth.checkPermissionOnResource(context, input)).toBe(false); - await expect(auth.authorize(context, input)).rejects.toMatchObject({ code: "NOT_FOUND" }); - }); - - it("does not let an existing token retain administration after its owner becomes a member", async () => { - state.servers.set("server-a", { organizationId: "org-a" }); - state.tokenGrants.set("token-a:server:server-a", { permissions: ["admin"] }); - const token = await auth.resolveScope({ ...alice, tokenScope: { tokenId: "token-a" }, - credential: { organizationId: "org-a", readOnly: false } }, "org-a"); - const input = { resourceType: "server" as const, resourceId: "server-a", action: "admin" as const }; - await expect(auth.authorize(token, input)).resolves.toBeDefined(); - state.members.set("org-a:alice", { id: "member-a", role: "member" }); - await expect(auth.authorize(token, input)).rejects.toMatchObject({ code: "NOT_FOUND" }); - }); - - it.each(["project", "server", "mail_server", "settings", "job"] as const)( - "keeps member read/write access separate from %s administration", async resourceType => { - state.members.set("org-a:alice", { id: "member-a", role: "member" }); - const input = { resourceType, resourceId: "*" }; - for (const action of ["read", "write"] as const) - expect(await auth.checkPermission("alice", "org-a", { ...input, action })).toBe(true); - expect(await auth.checkPermission("alice", "org-a", { ...input, action: "admin" })).toBe(false); - }, - ); - - it("preserves explicitly delegated administration for a restricted user on one server", async () => { - state.members.set("org-a:alice", { id: "member-a", role: "restricted" }); - state.servers.set("server-a", { organizationId: "org-a" }); - state.servers.set("server-other", { organizationId: "org-a" }); - state.grants.set("org-a:alice:server:server-a", { permissions: ["admin"] }); - await expect(auth.authorize(context, { resourceType: "server", resourceId: "server-a", action: "admin" })).resolves.toBeDefined(); - await expect(auth.authorize(context, { resourceType: "server", resourceId: "server-other", action: "admin" })).rejects.toMatchObject({ code: "NOT_FOUND" }); - }); - it("derives checked resources from core without widening the existing type", () => { expectTypeOf().toEqualTypeOf(); expect(new Set(CHECKED_RESOURCE_TYPES).size).toBe(CHECKED_RESOURCE_TYPES.length); diff --git a/packages/platform/test/domains.test.ts b/packages/platform/test/domains.test.ts index 131f3e09a..3717aee3e 100644 --- a/packages/platform/test/domains.test.ts +++ b/packages/platform/test/domains.test.ts @@ -121,7 +121,7 @@ describe("organization-scoped DNS operations", () => { const dns = createDnsOperations(authorization, { operations: { addCredential } as never, requireAdmin }); const input = { provider: "cloudflare" as const, name: "Production", apiToken: "private" }; state.members.set("org-a:alice", { id: "member-a", role: "member" }); - await expect(dns.addCredential(ctx, input)).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect(dns.addCredential(ctx, input)).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); expect(addCredential).not.toHaveBeenCalled(); state.members.set("org-a:alice", { id: "member-a", role: "owner" }); const identity = { ...alice, tokenScope: { tokenId: "token" }, credential: { organizationId: "org-a", readOnly: false } }; diff --git a/packages/sdk/test/native-runtime.test.ts b/packages/sdk/test/native-runtime.test.ts index 9c607c1ac..daa1440f4 100644 --- a/packages/sdk/test/native-runtime.test.ts +++ b/packages/sdk/test/native-runtime.test.ts @@ -729,7 +729,7 @@ describe("owned native platform on Node", () => { await controls.setSleepMode(projectId, { sleep_mode: "always_on" }); expect((await controls.getResources(projectId)).sleepMode).toBe("always_on"); const bobScope = await first!.ship.scope({ identity: "bob", organizationId: first!.customer.organizationId }); - await expect(bobScope.credentials.create({ provider: "docker-registry", name: "Not an admin", values: { secret: "value" } })).rejects.toMatchObject({ code: "NOT_FOUND" }); + await expect(bobScope.credentials.create({ provider: "docker-registry", name: "Not an admin", values: { secret: "value" } })).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" }); await first!.ship.operator!.setMembership({ organizationId: first!.customer.organizationId, userId: first!.bob.user.id, role: null }); await expect(bobScope.projects.get(projects[0]!.id)).rejects.toMatchObject({ code: "NOT_FOUND" }); await expect(bobScope.projects.setBranch(projectId, { branch: "forbidden" })).rejects.toMatchObject({ code: "NOT_FOUND" });