('[role="checkbox"]')!.click());
let resolve!: (value: unknown) => void;
h.start.mockImplementation(
@@ -557,7 +366,7 @@ describe("platform import flow", () => {
resolve = done;
}),
);
- const start = button("Import project");
+ const start = button("Import 2 projects");
await act(async () => {
start.click();
start.click();
@@ -572,25 +381,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,
@@ -614,7 +404,7 @@ describe("platform import flow", () => {
expect(h.review).toHaveBeenLastCalledWith(
expect.objectContaining({ targetServerId: "server-b" }),
);
- expect(button("Import project").disabled).toBe(true);
+ expect(button("Import 2 projects").disabled).toBe(true);
});
it("returns to editable services when a review request fails", async () => {
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"
/>
["projectData"];
-
-/** Only fields owned by the shared build form. Environment, routes and source identity
- * have their own owners and must never be serialized by a configuration save. */
-function optionsOf(config: Config): ProjectOptionsBody {
- const options = config.options ?? {};
- return {
- installCommand: options.installCommand ?? "",
- buildCommand: options.buildCommand ?? "",
- startCommand: options.startCommand ?? "",
- outputDirectory: options.outputDirectory ?? "",
- productionPaths: options.productionPaths ?? "",
- rootDirectory: options.rootDirectory ?? "",
- productionPort: options.productionPort ? Number(options.productionPort) : undefined,
- hasBuild: options.hasBuild,
- hasServer: options.hasServer,
- workloadType: options.workloadType,
- buildImage: config.buildImage ?? "",
- runtimeVersion: config.runtimeVersion ?? null,
- runtimeImage: config.runtimeImage ?? null,
- };
-}
-
-export function ApplicationSettingsForm({
- onBusyChange,
-}: {
- onBusyChange?: (busy: boolean) => void;
-}) {
- const { id, projectData, buildData, updateProjectData, updateBuild, refreshEnvironment } =
- useProjectSettings();
- const { t } = useI18n();
- const copy = t.projectSettings.build.runtime;
- const { showToast } = useToast();
- const persisted = useMemo(
- () => ({ ...projectData, options: { ...projectData.options, ...buildData } }),
- [projectData, buildData],
- );
- const [baseline, setBaseline] = useState(persisted);
- const [draft, setDraft] = useState(persisted);
- const [saving, setSaving] = useState(false);
- const [error, setError] = useState(null);
- const mutation = useRef(false);
- const alive = useRef(true);
- const before = optionsOf(baseline);
- const after = optionsOf(draft);
- const patch = Object.fromEntries(
- Object.entries(after).filter(
- ([key, value]) => value !== before[key as keyof ProjectOptionsBody],
- ),
- ) as ProjectOptionsBody;
- const dirty = Object.keys(patch).length > 0;
-
- useEffect(() => {
- alive.current = true;
- return () => {
- alive.current = false;
- };
- }, []);
- useEffect(() => {
- onBusyChange?.(saving);
- }, [saving, onBusyChange]);
- useEffect(() => {
- // A status refresh or an added companion must not erase an unsaved app draft.
- if (!dirty && !mutation.current) {
- setBaseline(persisted);
- setDraft(persisted);
- }
- }, [persisted, dirty]);
- useEffect(() => {
- if (!dirty) return;
- const prevent = (event: BeforeUnloadEvent) => {
- event.preventDefault();
- event.returnValue = "";
- };
- window.addEventListener("beforeunload", prevent);
- return () => window.removeEventListener("beforeunload", prevent);
- }, [dirty]);
-
- const save = async () => {
- if (mutation.current || !dirty || buildData.isLoading || buildData.error) return;
- if (
- Object.hasOwn(patch, "productionPort") &&
- (!Number.isInteger(patch.productionPort) ||
- patch.productionPort! < 1 ||
- patch.productionPort! > 65535)
- ) {
- setError(copy.invalidPort);
- return;
- }
- mutation.current = true;
- setSaving(true);
- setError(null);
- try {
- const result = await projectsApi.setOptions(id, patch);
- if (result.success === false) throw new Error(copy.saveFailed);
- if (!alive.current) return;
- // setOptions returns the flat Project contract; the page uses the nested
- // ProjectDetails projection. Map only this form's options, retaining the
- // server's normalized workload, images and commands.
- const saved = result.data as Config;
- if (!saved || saved.id !== id) throw new Error(copy.saveFailed);
- const workload = resolveWorkload(saved.workloadType, saved.hasServer);
- const options = Object.fromEntries(
- Object.entries(after)
- .filter(([key]) => !["buildImage", "runtimeVersion", "runtimeImage"].includes(key))
- .map(([key, fallback]) => [
- key,
- key === "productionPort"
- ? workload === "web"
- ? String(saved.port ?? 3000)
- : ""
- : key === "workloadType"
- ? workload
- : Object.hasOwn(saved, key)
- ? (saved[key] ?? (typeof fallback === "string" ? "" : fallback))
- : fallback,
- ]),
- );
- const normalized = { ...draft, ...saved, options: { ...draft.options, ...options } };
- updateProjectData(normalized);
- setBaseline(normalized);
- setDraft(normalized);
- invalidateProjectCaches(id);
- showToast(copy.saved, "success");
- } catch (cause) {
- if (alive.current) setError(getApiErrorMessage(cause, copy.saveFailed));
- } finally {
- mutation.current = false;
- if (alive.current) setSaving(false);
- }
- };
-
- return (
-
- {projectData.gitOwner &&
- projectData.gitRepo &&
- (projectData.buildKind === "dockerfile" || projectData.framework === "docker") && (
-
- )}
- {!dirty && (
-
{
- updateBuild(commands);
- await refreshEnvironment();
- }}
- />
- )}
-
-
- {copy.projectSettingsHint}{" "}
-
- {t.projects.sidebar.tabs.settings}
-
-
-
- );
-}
diff --git a/apps/dashboard/src/components/project-settings/ProjectIconSetting.tsx b/apps/dashboard/src/components/project-settings/ProjectIconSetting.tsx
deleted file mode 100644
index 766ad83cd..000000000
--- a/apps/dashboard/src/components/project-settings/ProjectIconSetting.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-"use client";
-
-import { ProjectIcon } from "@/components/shared/ProjectIcon";
-import { useProjectSettings } from "@/context/ProjectSettingsContext";
-import { useI18n } from "@/components/i18n-provider";
-import { ImageUrlEditor } from "@/components/settings/ImageUrlEditor";
-import { projectsApi } from "@/lib/api";
-import { invalidateProjectCaches } from "@/hooks/useProjectEndpoints";
-
-export function ProjectIconSetting() {
- const { projectData, updateProjectData } = useProjectSettings();
- const { t } = useI18n();
- const c = t.projectSettings.icon;
- return (
-
- }
- onSave={async (iconUrl) => {
- const response = await projectsApi.update(projectData.id, { iconUrl });
- updateProjectData({ iconUrl: response.data.iconUrl });
- invalidateProjectCaches(projectData.id);
- }}
- />
- );
-}
diff --git a/apps/dashboard/src/components/referrals/ReferralLanding.test.tsx b/apps/dashboard/src/components/referrals/ReferralLanding.test.tsx
index 2f768970a..046883982 100644
--- a/apps/dashboard/src/components/referrals/ReferralLanding.test.tsx
+++ b/apps/dashboard/src/components/referrals/ReferralLanding.test.tsx
@@ -74,10 +74,10 @@ afterEach(async () => {
vi.unstubAllGlobals();
});
-it("shows the live Cloud cards, defaults to monthly and continues the selected plan with its referral", async () => {
+it("shows the live Cloud cards, defaults to annual and continues the selected plan with its referral", async () => {
await render();
expect(titles()).toEqual(["Hobby", "Starter", "Pro", "Scale"]);
- expect(button("Monthly").getAttribute("aria-pressed")).toBe("true");
+ expect(button("Yearly").getAttribute("aria-pressed")).toBe("true");
expect(host.textContent).toContain("Save 5% for 12 months");
expect(h.push).not.toHaveBeenCalled();
await click("Choose Hobby");
@@ -85,23 +85,23 @@ it("shows the live Cloud cards, defaults to monthly and continues the selected p
expect(Object.fromEntries(target().searchParams)).toEqual({
newServer: "1",
plan: "hobby",
- interval: "monthly",
+ interval: "annual",
startCheckout: "1",
ref: code,
});
expect(validateReturnTo(`${target().pathname}${target().search}`)).not.toBeNull();
});
-it("preserves yearly selection and keeps generic sign-in browse-only", async () => {
+it("preserves monthly selection and keeps generic sign-in browse-only", async () => {
await render();
const signIn = host.querySelector('a[href^="/login?"]')!;
const destination = new URL(signIn.href).searchParams.get("returnTo")!;
expect(validateReturnTo(destination)).toBe(destination);
expect(destination).toBe(`/billing/plans?newServer=1&ref=${code}`);
- await click("Yearly");
+ await click("Monthly");
expect(h.push).not.toHaveBeenCalled();
await click("Choose Starter");
- expect(target().searchParams.get("interval")).toBe("annual");
+ expect(target().searchParams.get("interval")).toBe("monthly");
expect(target().searchParams.get("ref")).toBe(code);
});
@@ -186,19 +186,18 @@ it("limits public cards to the selected plan and billing combinations and choose
it.each([
- ["annual", 1000, 12000, 1000, "$108", "$120", "Billed yearly"],
+ ["annual", 1000, 12000, 1000, "$9", "$10", "$108 billed yearly"],
["monthly", 1200, 12000, 1000, "$10.80", "$12", "billed monthly"],
["monthly", 1231, 12000, 500, "$11.69", "$12.31", "billed monthly"],
- ["annual", 1000, 12000, 0, "$120", null, "Billed yearly"],
+ ["annual", 1000, 12000, 0, "$10", null, "$120 billed yearly"],
["monthly", 1200, 12000, 10000, "Free", "$12", "billed monthly"],
] as const)("shows %s referral prices for %i/%i cents at %i basis points", async (interval, monthly, annual, discountBps, price, original, billing) => {
h.offer.mockResolvedValue({ ...offer, discountBps });
catalog([{ ...plans[0]!, price: { monthly, annual }, listPrice: { monthly }, effectivePrice: { monthly } }]);
await render();
- if (interval === "annual") await click("Yearly");
+ if (interval === "monthly") await click("Monthly");
const card = host.querySelector('article[aria-label="Hobby"]')!;
- expect(card.querySelector(".text-2xl")?.textContent).toBe(price);
- if (price !== "Free") expect(card.textContent).toContain(interval === "annual" ? pricingUi("en").perYear : pricingUi("en").perMonth);
+ expect(card.textContent).toContain(price);
expect(card.querySelector("s")?.textContent ?? null).toBe(original);
expect(card.textContent).toContain(billing);
if (discountBps) expect(card.textContent).toContain(`Save ${discountBps / 100}% for 12 months`);
diff --git a/apps/dashboard/src/components/referrals/ReferralLanding.tsx b/apps/dashboard/src/components/referrals/ReferralLanding.tsx
index 92408efad..fdcb14b6c 100644
--- a/apps/dashboard/src/components/referrals/ReferralLanding.tsx
+++ b/apps/dashboard/src/components/referrals/ReferralLanding.tsx
@@ -22,7 +22,7 @@ export function ReferralLanding({ code }: { code: string }) {
copy = t.referrals;
const router = useRouter();
const catalog = useCloudPlans();
- const [selectedInterval, setInterval] = useState<"monthly" | "annual">("monthly");
+ const [selectedInterval, setInterval] = useState<"monthly" | "annual">("annual");
const [state, setState] = useState<{ offer?: ReferralPublicOffer; error?: string }>({});
const load = useCallback(async () => {
try {
@@ -140,7 +140,6 @@ export function ReferralLanding({ code }: { code: string }) {
ui={catalog.payload.ui}
currentPlan={null}
interval={interval}
- annualSavings={catalog.payload.annual.monthsFree > 0 ? catalog.payload.ui.monthsFree : undefined}
referralOffer={state.offer}
workspaceScoped
onSelectPlan={(planId) => {
diff --git a/apps/dashboard/src/components/routing/DomainResponseRoutes.test.tsx b/apps/dashboard/src/components/routing/DomainResponseRoutes.test.tsx
deleted file mode 100644
index e9b7f1f68..000000000
--- a/apps/dashboard/src/components/routing/DomainResponseRoutes.test.tsx
+++ /dev/null
@@ -1,193 +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 { normalizeEdgeResponse } from "@repo/core";
-import { DomainResponseRoutes } from "./DomainResponseRoutes";
-
-const api = vi.hoisted(() => ({
- listRouteRules: vi.fn(),
- createRouteRule: vi.fn(),
- updateRouteRule: vi.fn(),
- deleteRouteRule: vi.fn(),
-}));
-vi.mock("@/lib/api", () => ({
- projectsApi: api,
- getApiErrorMessage: (error: unknown, fallback: string) =>
- error instanceof Error ? error.message : fallback,
-}));
-let root: Root;
-let container: HTMLDivElement;
-const rule = (overrides = {}) => ({
- id: "response-a",
- projectId: "project",
- domainId: "domain-a",
- pathPrefix: "/x",
- enabled: true,
- spec: {
- response: normalizeEdgeResponse({ body: "original", headers: { "cache-control": "no-store" } }),
- },
- ...overrides,
-});
-beforeEach(() => {
- vi.clearAllMocks();
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- api.listRouteRules.mockResolvedValue({ rules: [] });
- api.createRouteRule.mockImplementation(async (_project, input) => ({
- rule: rule({ ...input, edgeApplied: true }),
- }));
- api.updateRouteRule.mockImplementation(async (_project, _id, input) => ({
- rule: rule({ ...input, edgeApplied: true }),
- }));
- api.deleteRouteRule.mockResolvedValue({ success: true, edgeApplied: true });
- container = document.createElement("div");
- document.body.append(container);
- root = createRoot(container);
-});
-afterEach(async () => {
- await act(async () => root.unmount());
- container.remove();
- vi.unstubAllGlobals();
-});
-async function render() {
- await act(async () =>
- root.render(
- ,
- ),
- );
-}
-async function click(label: string) {
- const button = [...document.querySelectorAll("button")].find(
- (element) =>
- element.getAttribute("aria-label") === label || element.textContent?.trim() === label,
- );
- expect(button, label).toBeTruthy();
- await act(async () => button!.click());
-}
-async function input(selector: string, value: string) {
- const element = document.querySelector(selector)!;
- expect(element, selector).toBeTruthy();
- await act(async () => {
- Object.getOwnPropertyDescriptor(
- element.tagName === "TEXTAREA" ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype,
- "value",
- )!.set!.call(element, value);
- element.dispatchEvent(new Event("input", { bubbles: true }));
- });
-}
-async function submit() {
- await act(async () => {
- document
- .querySelector("form")!
- .dispatchEvent(new Event("submit", { bubbles: true, cancelable: true }));
- });
-}
-
-it("creates a response for this domain, keeps preview HTML inert, and reports edge acknowledgement", async () => {
- await render();
- await click("Add route");
- await input('input[placeholder="/health"]', "/status");
- await input("textarea", "");
- await click("Add header");
- await input('input[aria-label="Header name 1"]', "Cache-Control");
- await input('input[aria-label="Header value 1"]', "no-store");
- await click("Response preview");
- expect(document.querySelector("pre")?.textContent).toContain("",
- headers: { "cache-control": "no-store" },
- match: "exact",
- }),
- },
- }),
- );
- expect(document.body.textContent).toContain("Saved and applied to the edge.");
- expect(document.querySelector('[role="dialog"]')).toBeNull();
-});
-
-it("retains a failed draft, avoids double submit and distinguishes saved from applied", async () => {
- await render();
- await click("Add route");
- await input('input[placeholder="/health"]', "/x");
- await input("textarea", "keep this content");
- let reject!: (error: Error) => void;
- api.createRouteRule.mockImplementationOnce(
- () =>
- new Promise((_, fail) => {
- reject = fail;
- }),
- );
- await submit();
- await submit();
- expect(api.createRouteRule).toHaveBeenCalledTimes(1);
- await act(async () => reject(new Error("offline")));
- expect(document.querySelector("textarea")?.value).toBe("keep this content");
- expect(document.body.textContent).toContain("offline");
- api.createRouteRule.mockResolvedValue({ rule: rule({ edgeApplied: false }) });
- await submit();
- expect(document.body.textContent).toContain("Edge application is pending");
- expect(document.body.textContent).not.toContain("Saved and applied");
-});
-
-it("rejects duplicate or injected headers before sending a mutation", async () => {
- await render();
- await click("Add route");
- await input('input[placeholder="/health"]', "/headers");
- for (const [index, name] of ["X-Test", "x-test"].entries()) {
- await click("Add header");
- await input(`input[aria-label="Header name ${index + 1}"]`, name);
- }
- await submit();
- expect(api.createRouteRule).not.toHaveBeenCalled();
- expect(document.body.textContent).toContain("must be unique");
-});
-
-it("edits only the selected domain response and preserves its disabled state", async () => {
- api.listRouteRules.mockResolvedValue({
- rules: [
- rule({ enabled: false }),
- rule({ id: "other", domainId: "domain-b", pathPrefix: "/other-domain" }),
- rule({ id: "policy", spec: { rateLimit: { rps: 5, burst: 0 } } }),
- ],
- });
- await render();
- expect(container.textContent).not.toContain("/other-domain");
- await click("Edit route /x");
- expect(document.querySelector("textarea")?.value).toBe("original");
- await input("textarea", "changed");
- await submit();
- const patch = api.updateRouteRule.mock.calls[0]![2];
- expect(patch).not.toHaveProperty("enabled");
- expect(patch.spec.response).toMatchObject({
- body: "changed",
- headers: { "cache-control": "no-store" },
- });
- expect(api.createRouteRule).not.toHaveBeenCalled();
-});
-
-it("keeps failed loading distinct from an empty list and requires confirmation to remove", async () => {
- api.listRouteRules.mockRejectedValueOnce(new Error("Cannot reach API"));
- await render();
- expect(container.textContent).toContain("Cannot reach API");
- expect(
- [...container.querySelectorAll("button")].find((button) =>
- button.textContent?.includes("Add route"),
- )?.disabled,
- ).toBe(true);
- api.listRouteRules.mockResolvedValue({ rules: [rule()] });
- await click("Retry");
- await click("Remove /x");
- expect(api.deleteRouteRule).not.toHaveBeenCalled();
- await click("Remove");
- expect(api.deleteRouteRule).toHaveBeenCalledWith("project", "response-a");
- expect(container.textContent).not.toContain("/x");
-});
diff --git a/apps/dashboard/src/components/routing/DomainResponseRoutes.tsx b/apps/dashboard/src/components/routing/DomainResponseRoutes.tsx
deleted file mode 100644
index cb59ad690..000000000
--- a/apps/dashboard/src/components/routing/DomainResponseRoutes.tsx
+++ /dev/null
@@ -1,625 +0,0 @@
-"use client";
-
-import { useCallback, useEffect, useId, useRef, useState } from "react";
-import { Icon } from "@repo/ui/icons";
-import { normalizeEdgeResponse, normalizeResponsePath, EDGE_RESPONSE_MAX_BYTES } from "@repo/core";
-import { useI18n } from "@/components/i18n-provider";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Textarea } from "@/components/ui/textarea";
-import { CustomSelect } from "@/components/ui/CustomSelect";
-import { Modal } from "@/components/ui/Modal";
-import { useDialogFocus } from "@/hooks/useDialogFocus";
-import { projectsApi, getApiErrorMessage, type RouteRuleRow } from "@/lib/api";
-
-type Draft = {
- id?: string;
- path: string;
- match: "exact" | "prefix";
- status: string;
- contentType: string;
- body: string;
- methods: string;
- headers: Array<{ name: string; value: string }>;
-};
-const blank = (): Draft => ({
- path: "",
- match: "exact",
- status: "200",
- contentType: "text/plain; charset=utf-8",
- body: "",
- methods: "GET, HEAD",
- headers: [],
-});
-const fromRule = (rule: RouteRuleRow): Draft => ({
- id: rule.id,
- path: rule.pathPrefix || "/",
- match: rule.spec.response!.match,
- status: String(rule.spec.response!.status),
- contentType: rule.spec.response!.contentType,
- body: rule.spec.response!.body,
- methods: rule.spec.response!.methods.join(", "),
- headers: Object.entries(rule.spec.response!.headers).map(([name, value]) => ({ name, value })),
-});
-
-/** The same domain editor is used by single-app, service and project route cards. */
-export function DomainResponseRoutes({
- projectId,
- domainId,
- hostname,
-}: {
- projectId: string;
- domainId: string;
- hostname: string;
-}) {
- const { t, locale } = useI18n();
- const w = t.projectSettings.responseRoutes;
- const labelId = useId();
- const [rules, setRules] = useState([]);
- const [loading, setLoading] = useState(true);
- const [loadError, setLoadError] = useState("");
- const [error, setError] = useState("");
- const [notice, setNotice] = useState("");
- const [draft, setDraft] = useState(null);
- const [open, setOpen] = useState(false);
- const [preview, setPreview] = useState(false);
- const [busy, setBusy] = useState(false);
- const [removeId, setRemoveId] = useState(null);
- const mutation = useRef(false);
- const alive = useRef(true);
- useEffect(() => {
- alive.current = true;
- return () => {
- alive.current = false;
- };
- }, []);
- const close = () => {
- if (!mutation.current) setOpen(false);
- };
- const { dialog, onKeyDown } = useDialogFocus(close, open);
- const load = useCallback(async () => {
- setLoading(true);
- setLoadError("");
- try {
- const result = await projectsApi.listRouteRules(projectId);
- if (alive.current)
- setRules(result.rules.filter((rule) => rule.domainId === domainId && rule.spec.response));
- } catch (cause) {
- if (alive.current) setLoadError(getApiErrorMessage(cause, w.loadFailed));
- } finally {
- if (alive.current) setLoading(false);
- }
- }, [projectId, domainId, w.loadFailed]);
- useEffect(() => {
- void load();
- }, [load]);
-
- const update = (patch: Partial) =>
- setDraft((current) => current && { ...current, ...patch });
- const edit = (rule?: RouteRuleRow) => {
- setDraft((current) =>
- current && current.id === rule?.id ? current : rule ? fromRule(rule) : blank(),
- );
- setError("");
- setPreview(false);
- setOpen(true);
- };
- const run = async (operation: () => Promise) => {
- if (mutation.current) return;
- mutation.current = true;
- setBusy(true);
- setError("");
- setNotice("");
- try {
- await operation();
- } catch (cause) {
- if (alive.current) setError(getApiErrorMessage(cause, w.saveFailed));
- } finally {
- mutation.current = false;
- if (alive.current) setBusy(false);
- }
- };
- const save = () =>
- run(async () => {
- if (!draft) return;
- const path = normalizeResponsePath(draft.path);
- const headers: Record = {};
- for (const row of draft.headers) {
- if (!row.name && !row.value) continue;
- const name = row.name.trim().toLowerCase();
- if (Object.hasOwn(headers, name)) throw new Error(w.duplicateHeader);
- Object.defineProperty(headers, name, { value: row.value, enumerable: true });
- }
- const response = normalizeEdgeResponse({
- match: draft.match,
- status: Number(draft.status),
- contentType: draft.contentType.trim(),
- body: draft.body,
- headers,
- methods: draft.methods
- .split(/[\s,]+/)
- .filter(Boolean)
- .map((value) => value.toUpperCase()),
- });
- const input = { domainId, pathPrefix: path, spec: { response } };
- const result = draft.id
- ? await projectsApi.updateRouteRule(projectId, draft.id, input)
- : await projectsApi.createRouteRule(projectId, { ...input, enabled: true });
- if (!alive.current) return;
- setRules((current) => [...current.filter((rule) => rule.id !== result.rule.id), result.rule]);
- setDraft(null);
- setOpen(false);
- setNotice(result.rule.edgeApplied === true ? w.saved : w.pending);
- });
- const toggle = (rule: RouteRuleRow) =>
- run(async () => {
- const result = await projectsApi.updateRouteRule(projectId, rule.id, {
- enabled: !rule.enabled,
- });
- if (alive.current) {
- setRules((current) => current.map((row) => (row.id === rule.id ? result.rule : row)));
- setNotice(result.rule.edgeApplied === true ? w.saved : w.pending);
- }
- });
- const remove = (rule: RouteRuleRow) =>
- run(async () => {
- const result = await projectsApi.deleteRouteRule(projectId, rule.id);
- if (!alive.current) return;
- setRules((current) => current.filter((row) => row.id !== rule.id));
- setRemoveId(null);
- setNotice(result.edgeApplied === true ? w.saved : w.pending);
- if (draft?.id === rule.id) setDraft(null);
- });
- const contentTypes = [
- { value: "text/plain; charset=utf-8", label: w.plainText },
- { value: "application/json", label: "JSON" },
- { value: "text/html; charset=utf-8", label: "HTML" },
- { value: "application/xml", label: "XML" },
- ];
- const format =
- draft && contentTypes.some((type) => type.value === draft.contentType)
- ? draft.contentType
- : "custom";
- const contentBytes = new TextEncoder().encode(draft?.body ?? "").length;
- const fieldClass = "bg-muted/60 ring-1 ring-inset ring-border/50 focus:bg-muted/80";
- const bodyless = draft && [204, 205, 304].includes(Number(draft.status));
-
- return (
-
-
-
{w.title}
- edit()}
- >
-
- {w.add}
-
-
- {w.description}
- {loading && (
-
- )}
- {loadError && (
-
-
- {loadError}
-
-
void load()}>
- {w.retry}
-
-
- )}
- {!open && error && (
-
- {error}
-
- )}
- {notice && (
-
- {notice}
-
- )}
-
- {rules.map((rule) => {
- const path = rule.pathPrefix || "/";
- const response = rule.spec.response!;
- return (
-
-
- edit(rule)}
- disabled={busy}
- aria-label={`${w.edit} ${path}`}
- className="min-w-0 flex-1 rounded-md py-1 text-start focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
- >
-
- {path}
-
-
- {response.status} · {response.contentType.split(";")[0]} ·{" "}
- {response.match === "exact" ? w.exact : w.prefix}
-
-
- void toggle(rule)}
- disabled={busy}
- aria-label={`${rule.enabled ? w.disable : w.enable} ${path}`}
- aria-pressed={rule.enabled}
- className="rounded-lg px-2 py-1 text-xs text-muted-foreground hover:bg-muted disabled:opacity-50"
- >
- {rule.enabled ? w.enabled : w.disabled}
-
- setRemoveId(rule.id)}
- disabled={busy}
- aria-label={`${w.remove} ${path}`}
- className="rounded-lg p-2 text-muted-foreground hover:bg-muted disabled:opacity-50"
- >
-
-
-
- {removeId === rule.id && (
-
-
{w.removeHint}
-
setRemoveId(null)}
- >
- {w.cancel}
-
-
void remove(rule)}
- >
- {w.remove}
-
-
- )}
-
- );
- })}
-
-
-
-
-
- );
-}
diff --git a/apps/dashboard/src/components/servers/managed-server.test.tsx b/apps/dashboard/src/components/servers/managed-server.test.tsx
index f9e113a54..0263e9ef8 100644
--- a/apps/dashboard/src/components/servers/managed-server.test.tsx
+++ b/apps/dashboard/src/components/servers/managed-server.test.tsx
@@ -8,7 +8,6 @@ import { baseDictionary } from "@/i18n";
import { PlatformProvider } from "@/context/PlatformContext";
import { AppDestinationPicker, type AppDestination } from "@/components/deploy/AppDestinationPicker";
import ServerSelector from "@/components/shared/ServerSelector";
-import { PlatformImportServices } from "@/components/migration/PlatformImportServices";
import { BillingLink, BillingWorkspaceProvider, workspaceBillingHref } from "@/components/billing/BillingWorkspaceContext";
import { ApiError } from "@/lib/api/client";
import { ServerUsage } from "./ServerUsage";
@@ -83,105 +82,15 @@ afterEach(async () => {
vi.unstubAllGlobals();
});
-it("keeps the only selected server in the shared picker with Add server inside its menu", async () => {
+it("selects the only server without provisioning anything on render", async () => {
const change = vi.fn();
await render( );
expect(change).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ id: server.id }));
expect(host.textContent).toContain("Production");
- const trigger = host.querySelector('button[aria-haspopup="listbox"]');
- expect(trigger).not.toBeNull();
- expect(document.body.textContent).not.toContain(copy.newProjectServer);
+ expect(host.querySelector('[role="combobox"]')).toBeNull();
expect(h.ensure).not.toHaveBeenCalled();
expect(h.add).not.toHaveBeenCalled();
- await act(async () => trigger!.click());
- expect(document.querySelector('[role="listbox"]')?.textContent).toContain("Production");
- const add = [...document.querySelectorAll("button")].find(
- (node) => node.textContent?.trim() === copy.newProjectServer,
- );
- expect(add).toBeDefined();
- await act(async () => add!.click());
- expect(h.add).toHaveBeenCalledOnce();
- expect(document.querySelector('[role="listbox"]')).toBeNull();
- expect(change).toHaveBeenCalledTimes(1);
- expect(h.ensure).not.toHaveBeenCalled();
});
-
-it.each(["railway", "vercel"] as const)(
- "changes the %s import destination through the real shared picker",
- async (provider) => {
- const connected: ServerDetail = {
- ...server,
- id: "connected-server",
- name: "SSH destination",
- managed: undefined,
- connection: "ssh",
- sshHost: "192.0.2.10",
- sshUser: "deploy",
- sshPort: 22,
- };
- h.list.mockResolvedValue({ servers: [connected, server] });
- const target = vi.fn(),
- review = vi.fn();
- function Import() {
- const [id, setId] = useState(connected.id);
- const [ready, setReady] = useState(false);
- return (
- {}}
- onChoose={() => {}}
- onTargetReady={setReady}
- onTarget={(next, name) => {
- setId(next);
- target(next, name);
- }}
- onReview={() => review(id)}
- />
- );
- }
- await render( );
- expect(button("Check import").disabled).toBe(false);
- const trigger = host.querySelector('button[aria-haspopup="listbox"]')!;
- expect(trigger.textContent).toContain(connected.name);
- await act(async () => trigger.click());
- const destination = [...document.querySelectorAll('[role="option"]')].find(
- (node) => node.textContent?.includes(server.name ?? server.id),
- );
- expect(destination).toBeDefined();
- await act(async () => destination!.click());
- expect(target).toHaveBeenCalledExactlyOnceWith(server.id, server.name);
- expect(trigger.textContent).toContain(server.name);
- expect(document.querySelector('[role="listbox"]')).toBeNull();
- await act(async () => button("Check import").click());
- expect(review).toHaveBeenCalledExactlyOnceWith(server.id);
- expect(h.add).not.toHaveBeenCalled();
- expect(h.ensure).not.toHaveBeenCalled();
- },
-);
it.each([true, false])("uses an acquired server for catalog apps (self-hosted: %s)", async selfHosted => {
const changed = vi.fn(), ready = vi.fn();
function Picker() {
diff --git a/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx b/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx
index 51eaa78de..c475b1b53 100644
--- a/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx
+++ b/apps/dashboard/src/components/servers/managed/ManagedServerPurchase.tsx
@@ -1,6 +1,5 @@
"use client";
-import { reportCaughtError } from "@repo/core/diagnostics";
import { useEffect, useRef, useState } from "react";
import type { CloudWorkspaceSummary } from "@repo/contracts";
import { useI18n } from "@/components/i18n-provider";
@@ -9,9 +8,8 @@ import { BillingWorkspaceProvider } from "@/components/billing/BillingWorkspaceC
import { Button } from "@/components/ui/button";
import { useSession } from "@/lib/auth-client";
import { systemApi } from "@/lib/api/system";
-import { getApiErrorCode, getApiErrorMessage } from "@/lib/api/client";
-import { billingApi } from "@/lib/api/billing";
-import { useResourceScope } from "@/hooks/use-scoped-resource";
+import { getApiErrorMessage } from "@/lib/api/client";
+import { useCloudResourceKey } from "@/context/CloudResourceContext";
import { randomUUID } from "@/lib/random-uuid";
import { isCloudPurchaseIntent } from "@/lib/cloud-purchase-intent";
@@ -33,7 +31,8 @@ interface PurchaseProps {
* Browsing does not create a server; retries reuse the identity just created. */
export function ManagedServerPurchase(props: PurchaseProps) {
const { data: session, isPending } = useSession();
- const contextKey = useResourceScope();
+ const cloudKey = useCloudResourceKey();
+ const contextKey = `${cloudKey}:${session?.user.id ?? "local"}:${session?.session.activeOrganizationId ?? ""}`;
const [intent, setIntent] = useState<{ owner: string; key: string; paymentKey: string; automatic: boolean } | null>(null);
useEffect(() => {
if (intent || isPending || !session?.user.id || !session.session.activeOrganizationId) return;
@@ -85,55 +84,14 @@ function Purchase({
onIntentRemoved,
}: PurchaseProps & { sessionPending?: boolean; onCheckoutSettled?: () => void; onIntentRemoved?: () => void }) {
const { t } = useI18n();
- const scope = useResourceScope();
- const owner = useRef(scope);
- owner.current = scope;
- const mounted = useRef(false);
- useEffect(() => { mounted.current = true; return () => { mounted.current = false; }; }, []);
const created = useRef(null);
const [error, setError] = useState(null);
async function prepareWorkspace() {
- if (created.current) return created.current.id;
- // Reopening a modal must recover its unpaid space, not buy another one.
- // Recover its saved payment directly, including processing payments.
- const pending = await billingApi.listCheckouts();
- if (!mounted.current || owner.current !== scope) throw new Error("Purchase scope changed");
- const unfinished = pending.items.find(item => item.kind === "subscription");
- if (unfinished) {
- created.current = unfinished.server;
- return { workspaceId: unfinished.server.id, checkoutPending: true as const };
- }
- const storageKey = `openship:cloud-purchase:${scope}`;
- let key = checkoutIntent;
- if (!key) {
- try { key = sessionStorage.getItem(storageKey) ?? undefined; }
- catch (error) { reportCaughtError(error, "dashboard/components/servers/managed/ManagedServerPurchase"); }
- if (!isCloudPurchaseIntent(key)) key = randomUUID();
- try { sessionStorage.setItem(storageKey, key); }
- catch (error) { reportCaughtError(error, "dashboard/components/servers/managed/ManagedServerPurchase"); }
- }
- const create = (idempotencyKey: string) => {
- if (!mounted.current || owner.current !== scope) throw new Error("Purchase scope changed");
- return systemApi.createManagedServer({ name: t.billing.workspaces.defaultName, idempotencyKey });
- };
- let server: CloudWorkspaceSummary;
- try { server = await create(key); }
- catch (error) {
- if (checkoutIntent || getApiErrorCode(error) !== "CLOUD_WORKSPACE_PURCHASE_REMOVED") throw error;
- key = randomUUID();
- try { sessionStorage.setItem(storageKey, key); }
- catch (error) { reportCaughtError(error, "dashboard/components/servers/managed/ManagedServerPurchase"); }
- server = await create(key);
- }
- if (!checkoutIntent && (server.planTierId !== "free" || server.resources)) {
- // The last purchase completed. This explicit Add space is a new purchase.
- key = randomUUID();
- try { sessionStorage.setItem(storageKey, key); }
- catch (error) { reportCaughtError(error, "dashboard/components/servers/managed/ManagedServerPurchase"); }
- server = await create(key);
- }
- created.current = server;
+ created.current ??= await systemApi.createManagedServer({
+ name: t.billing.workspaces.defaultName,
+ ...(checkoutIntent ? { idempotencyKey: checkoutIntent } : {}),
+ });
return created.current.id;
}
diff --git a/apps/dashboard/src/components/settings/ImageUrlEditor.test.tsx b/apps/dashboard/src/components/settings/ImageUrlEditor.test.tsx
deleted file mode 100644
index a865f71f8..000000000
--- a/apps/dashboard/src/components/settings/ImageUrlEditor.test.tsx
+++ /dev/null
@@ -1,102 +0,0 @@
-// @vitest-environment happy-dom
-import { act, useState } from "react";
-import { createRoot, type Root } from "react-dom/client";
-import { afterEach, beforeEach, expect, it, vi } from "vitest";
-import { I18nProvider } from "@/components/i18n-provider";
-import { ImageUrlEditor } from "./ImageUrlEditor";
-
-let host: HTMLDivElement;
-let root: Root;
-const save = vi.fn();
-beforeEach(() => {
- vi.resetAllMocks();
- vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
- vi.spyOn(HTMLImageElement.prototype, "complete", "get").mockReturnValue(false);
- host = document.createElement("div");
- document.body.append(host);
- root = createRoot(host);
-});
-afterEach(async () => {
- await act(async () => root.unmount());
- host.remove();
- vi.restoreAllMocks();
- vi.unstubAllGlobals();
-});
-
-function Editor({ initial = null }: { initial?: string | null }) {
- const [value, setValue] = useState(initial);
- return (
-
- {
- await save(next);
- setValue(next);
- }}
- />
-
- );
-}
-async function render(initial?: string) {
- await act(async () => root.render( ));
-}
-async function edit(value: string) {
- await act(async () => {
- const input = host.querySelector("input")!;
- Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")!.set!.call(input, value);
- input.dispatchEvent(new Event("input", { bubbles: true }));
- });
-}
-async function submit() {
- await act(async () =>
- host
- .querySelector("form")!
- .dispatchEvent(new Event("submit", { bubbles: true, cancelable: true })),
- );
-}
-
-it("previews and saves a trimmed image URL", async () => {
- await render();
- await edit(" https://cdn.example.test/avatar.png ");
- expect(host.querySelector("img")?.getAttribute("src")).toBe(
- "https://cdn.example.test/avatar.png",
- );
- expect(host.querySelector("img")?.getAttribute("referrerpolicy")).toBe("no-referrer");
- await submit();
- expect(save).toHaveBeenCalledWith("https://cdn.example.test/avatar.png");
- expect(host.querySelector('[role="status"]')?.textContent).toBe("Saved");
-});
-
-it("rejects executable image schemes without loading or saving them", async () => {
- await render();
- await edit("javascript:alert(1)");
- expect(host.querySelector("img")).toBeNull();
- await submit();
- expect(save).not.toHaveBeenCalled();
- expect(host.querySelector('[role="alert"]')?.textContent).toContain("HTTP or HTTPS");
-});
-
-it("clears the saved override using the shared reset action", async () => {
- await render("https://cdn.example.test/avatar.png");
- await act(async () => host.querySelector('button[type="button"]')!.click());
- expect(save).toHaveBeenCalledWith(null);
- expect(host.querySelector("input")!.value).toBe("");
- expect(host.querySelector("img")).toBeNull();
-});
-
-it("falls back for a broken image, retries a changed URL and preserves the draft on save failure", async () => {
- await render("https://cdn.example.test/old.png");
- await act(async () => host.querySelector("img")!.dispatchEvent(new Event("error")));
- expect(host.querySelector("img")).toBeNull();
- await edit("https://cdn.example.test/new.png");
- expect(host.querySelector("img")?.getAttribute("src")).toBe("https://cdn.example.test/new.png");
- save.mockRejectedValueOnce(new Error("Permission denied"));
- await submit();
- expect(host.querySelector("input")!.value).toBe("https://cdn.example.test/new.png");
- expect(host.querySelector('[role="alert"]')).not.toBeNull();
- expect(host.querySelector('button[type="submit"]')!.disabled).toBe(false);
-});
diff --git a/apps/dashboard/src/components/settings/ImageUrlEditor.tsx b/apps/dashboard/src/components/settings/ImageUrlEditor.tsx
deleted file mode 100644
index d2e035f0a..000000000
--- a/apps/dashboard/src/components/settings/ImageUrlEditor.tsx
+++ /dev/null
@@ -1,143 +0,0 @@
-"use client";
-
-import { useEffect, useId, useState, type ReactNode } from "react";
-import { isImageUrl, MAX_IMAGE_URL_LENGTH } from "@repo/core";
-import { useI18n } from "@/components/i18n-provider";
-import { Input } from "@/components/ui/input";
-import { useImageFallback } from "@/hooks/useImageFallback";
-import { getApiErrorMessage } from "@/lib/api/client";
-
-/** Shared URL editor; saving never depends on a remote image probe. */
-export function ImageUrlEditor({
- value,
- label,
- hint,
- resetLabel,
- fallback,
- onSave,
-}: {
- value: string | null | undefined;
- label: string;
- hint: string;
- resetLabel: string;
- fallback: ReactNode;
- onSave: (url: string | null) => Promise;
-}) {
- const { t } = useI18n();
- const c = t.settings.imageUrl;
- const id = useId();
- const [draft, setDraft] = useState(value ?? "");
- const [saving, setSaving] = useState(false);
- const [error, setError] = useState("");
- const [saved, setSaved] = useState(false);
- useEffect(() => {
- setDraft(value ?? "");
- }, [value]);
- const trimmed = draft.trim();
- const preview = useImageFallback(isImageUrl(trimmed) ? trimmed : null);
- const save = async (next: string | null) => {
- if (saving) return;
- if (next && !isImageUrl(next)) {
- setError(c.invalid);
- return;
- }
- setSaving(true);
- setError("");
- setSaved(false);
- try {
- await onSave(next);
- setDraft(next ?? "");
- setSaved(true);
- } catch (failure) {
- setError(getApiErrorMessage(failure, c.failed));
- } finally {
- setSaving(false);
- }
- };
- return (
- {
- event.preventDefault();
- void save(trimmed || null);
- }}
- className="space-y-3"
- >
-
-
- {preview.showImage ? (
-
- ) : (
- fallback
- )}
-
-
-
- {label}
-
- {
- setDraft(event.target.value);
- setError("");
- setSaved(false);
- }}
- />
-
-
-
- {hint}
-
- {isImageUrl(trimmed) && !preview.showImage && (
- {c.previewFailed}
- )}
- {error && (
-
- {error}
-
- )}
-
-
- {saving ? c.saving : c.save}
-
- {value && (
- void save(null)}
- className="text-sm text-muted-foreground hover:text-foreground disabled:opacity-40"
- >
- {resetLabel}
-
- )}
- {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/shared/ServerSelector.tsx b/apps/dashboard/src/components/shared/ServerSelector.tsx
index 45d39a82f..5fb3cae6e 100644
--- a/apps/dashboard/src/components/shared/ServerSelector.tsx
+++ b/apps/dashboard/src/components/shared/ServerSelector.tsx
@@ -8,7 +8,7 @@ import { useI18n } from "@/components/i18n-provider";
import { systemApi, type ServerInfo } from "@/lib/api/system";
import { useServerDestinations } from "@/hooks/useServerDestinations";
import { useAddServerModal } from "@/components/servers/add-server-modal";
-import { ServerPicker } from "@/components/shared/ServerPicker";
+import { ServerPicker, ServerRowContent } from "@/components/shared/ServerPicker";
import { Button } from "@/components/ui/button";
import { usePlatform } from "@/context/PlatformContext";
import { settingsApi } from "@/lib/api/settings";
@@ -297,16 +297,24 @@ export function ServerSelectorView({
) : automaticCloud ? (
) : rows.length > 0 ? (
- select(server.id)}
- onAddServer={canAddServer && !disabled && !disabledReason ? addServer : undefined}
- addServerLabel={addLabel}
- />
+ <>
+ {rows.length === 1 && effective === rows[0]!.id ? (
+
+
+
+ ) : (
+ select(server.id)}
+ onAddServer={canAddServer && !disabled && !disabledReason ? addServer : undefined}
+ addServerLabel={addLabel}
+ />
+ )}
+ >
) : (
@@ -334,7 +342,7 @@ export function ServerSelectorView({
{restrictedSource ? t.migration.sources.hint : forDeployment && !automaticCloud ? managedCopy.existingServerHint : managedCopy.subscriptionHint}
)}
- {canAddServer && automaticCloud && (
+ {canAddServer && (automaticCloud || rows.length === 1) && (
{addLabel}
diff --git a/apps/dashboard/src/components/sidebar.test.tsx b/apps/dashboard/src/components/sidebar.test.tsx
index 164291992..406f34065 100644
--- a/apps/dashboard/src/components/sidebar.test.tsx
+++ b/apps/dashboard/src/components/sidebar.test.tsx
@@ -9,8 +9,6 @@ import { getActiveOrganizationId, setActiveOrganizationId } from "@/lib/api/clie
import { useIssueCounts } from "@/hooks/useIssueCounts";
import { Sidebar } from "./sidebar";
import { SidebarLayoutProvider, useSidebarCollapseRequest } from "@/context/SidebarLayoutContext";
-import { DashboardPaymentsProvider, PendingCheckoutsProvider } from "./billing/PendingCheckoutsContext";
-import { invalidatePayments } from "@/lib/billing-events";
const mocks = vi.hoisted(() => ({
pathname: "/monitoring",
@@ -20,8 +18,6 @@ const mocks = vi.hoisted(() => ({
feed: vi.fn(),
organization: vi.fn(),
projects: vi.fn(),
- payments: vi.fn(),
- management: vi.fn(),
}));
vi.mock("next/navigation", () => ({
usePathname: () => mocks.pathname,
@@ -29,7 +25,6 @@ vi.mock("next/navigation", () => ({
useRouter: () => ({ push: vi.fn() }),
}));
vi.mock("@/lib/auth-client", () => ({
- useSession: () => ({ data: { user: { id: "user-a" }, session: { activeOrganizationId: "org-a" } } }),
authClient: {
organization: {
list: async () => ({ data: [] }),
@@ -60,8 +55,6 @@ vi.mock("@/lib/api/client", async (original) => {
if (path === "issues/summary") return mocks.summary();
if (path === "issues" || path === "issues?status=resolved") return mocks.feed(path);
if (path === "projects/home") return mocks.projects();
- if (path === "billing/checkouts") return mocks.payments();
- if (path === "/billing/manage") return mocks.management();
throw new Error(`Unexpected GET ${path}`);
},
},
@@ -81,8 +74,6 @@ beforeEach(() => {
mocks.organization.mockResolvedValue({ data: { id: "org-a" } });
mocks.summary.mockResolvedValue({ data: counts });
mocks.projects.mockResolvedValue({ success: true, projects: [] });
- mocks.payments.mockResolvedValue({ data: { items: [] } });
- mocks.management.mockResolvedValue({ data: { pendingCheckout: false, subscription: null, change: null } });
host = document.createElement("div");
document.body.append(host);
root = createRoot(host);
@@ -124,48 +115,18 @@ it.each([
expect(mocks.projects).toHaveBeenCalledOnce();
});
-async function render(props: ComponentProps = {}, payments = false) {
- const content = ;
+async function render(props: ComponentProps = {}) {
await act(async () =>
root.render(
- {payments ? {content} : content}
+
+
+
+
,
),
);
}
-
-it("counts unpaid Cloud plans and Manage once in the sidebar and refreshes after payment changes", async () => {
- mocks.cloudConnected = true;
- mocks.payments.mockResolvedValue({ data: { items: [
- { id: "one", server: { id: "space-a" } },
- { id: "two", server: { id: "space-a" } },
- { id: "three", server: { id: "space-b" } },
- ] } });
- mocks.management.mockResolvedValue({ data: { pendingCheckout: true, subscription: null, change: null } });
- await render({}, true);
- const link = () => host.querySelector('a[href="/billing"]')!;
- expect(link().querySelector(".tabular-nums")?.textContent).toBe("3");
- expect(link().querySelector(".tabular-nums")?.className).toContain("text-danger");
- expect(link().getAttribute("aria-label")).toContain("Pending: 3");
- // The hub's nested provider reuses the organization-wide read.
- expect(mocks.payments).toHaveBeenCalledOnce();
- await act(async () => sidebarToggle().click());
- expect(link().title).toContain("Pending: 3");
- expect(link().querySelector(".tabular-nums")?.textContent).toBe("3");
- mocks.payments.mockResolvedValue({ data: { items: [] } });
- mocks.management.mockResolvedValue({ data: { pendingCheckout: false, subscription: null, change: null } });
- await act(async () => invalidatePayments());
- expect(link().getAttribute("aria-label")).toBeNull();
- await act(async () => sidebarToggle().click());
- expect(link().querySelector(".tabular-nums")).toBeNull();
-});
-
-it("does not request payment data on an installation disconnected from Cloud", async () => {
- await render({}, true);
- expect(mocks.payments).not.toHaveBeenCalled();
- expect(mocks.management).not.toHaveBeenCalled();
-});
const monitoring = () => host.querySelector('a[href="/monitoring"]')!;
const badge = () => monitoring().querySelector(".tabular-nums");
const sidebarToggle = () => host.querySelector(
diff --git a/apps/dashboard/src/components/sidebar.tsx b/apps/dashboard/src/components/sidebar.tsx
index 009db0fe6..3f3f315b4 100644
--- a/apps/dashboard/src/components/sidebar.tsx
+++ b/apps/dashboard/src/components/sidebar.tsx
@@ -1,7 +1,5 @@
"use client";
-import { UserAvatar } from "@/components/ui/UserAvatar";
-
import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
import { Icon as UiIcon } from "@repo/ui/icons";
@@ -24,7 +22,6 @@ import { projectsApi } from "@/lib/api";
import { useSidebarCollapse } from "@/hooks/useSidebarCollapse";
import { useSidebarLayout } from "@/context/SidebarLayoutContext";
import { useIssueCounts } from "@/hooks/useIssueCounts";
-import { usePendingCheckouts } from "@/components/billing/PendingCheckoutsContext";
import { countProjectCollections, getSidebarNavCountsRevision, subscribeSidebarNavCounts } from "@/lib/sidebar-nav-counts";
import {
getMailNavSections,
@@ -156,13 +153,11 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo
const [switchingOrgId, setSwitchingOrgId] = useState(null);
const hasMonitoring = navSections.some(({ items }) => items.some(({ key }) => key === "issues"));
const issueCounts = useIssueCounts(orgsLoaded && hasMonitoring ? activeOrgId : undefined);
- const payments = usePendingCheckouts();
const countFor = (key: string): number | null => {
// Match Home's Needs attention card; available updates are advisories.
if (key === "issues")
return issueCounts ? issueCounts.outage + issueCounts.actionRequired : null;
if (key === "projects" || key === "apps") return navCounts?.[key] ?? null;
- if (key === "billing") return payments?.attentionCount ?? null;
return null;
};
@@ -378,20 +373,18 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo
const { key, href, icon: Icon, labelSource } = item;
const active = isNavItemActive(item, navPathname, currentTab);
const count = countFor(key);
- const attentionLabel =
+ const issueLabel =
key === "issues" && count != null && count > 0
? `${label(key, labelSource)}: ${count === 1 ? t.dashboard.home.oneIssue : interpolate(t.dashboard.home.manyIssues, { n: String(count) })}`
- : key === "billing" && count != null && count > 0
- ? `${label(key, labelSource)}: ${interpolate(t.billing.pendingPayments.count, { count: String(count) })}`
- : undefined;
+ : undefined;
return (
@@ -399,18 +392,10 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo
{!collapsed && (
{label(key, labelSource)}
)}
- {/* Keep attention counts accessible when the rail is collapsed. */}
- {(!collapsed || key === "billing") && count != null && count > 0 && (
+ {/* Hide zero/loading counts; keep issue counts in the collapsed label. */}
+ {!collapsed && count != null && count > 0 && (
{count}
@@ -474,11 +459,9 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo
title={collapsed ? activeOrg?.name : undefined}
>
{/* Org avatar / initial */}
- {activeOrg?.id === `org_${user?.id}` ? : (
-
- {activeOrg?.name?.[0] ?? }
-
- )}
+
+ {activeOrg?.name?.[0] ?? }
+
{!collapsed && (
<>
@@ -567,7 +550,9 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo
{/* Footer separator + signed-in-as + sign out */}
-
+
+ {displayInitial}
+
{displayName}
@@ -614,7 +599,9 @@ export function Sidebar({ mobileOpen = false, onCloseMobile }: { mobileOpen?: bo
collapsed ? "justify-center" : "gap-3"
}`}
>
-
+
+ {displayInitial}
+
{!collapsed && (
<>
diff --git a/apps/dashboard/src/components/ui/UserAvatar.tsx b/apps/dashboard/src/components/ui/UserAvatar.tsx
deleted file mode 100644
index e398f65d7..000000000
--- a/apps/dashboard/src/components/ui/UserAvatar.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-"use client";
-
-import { useImageFallback } from "@/hooks/useImageFallback";
-import { cn } from "@/lib/utils";
-
-export function UserAvatar({
- image,
- name,
- className,
-}: {
- image?: string | null;
- name: string;
- className?: string;
-}) {
- const fallback = useImageFallback(image);
- return (
-
- {fallback.showImage ? (
-
- ) : (
- name[0] || "?"
- )}
-
- );
-}
diff --git a/apps/dashboard/src/components/updates/RuntimeSourceUpdate.test.tsx b/apps/dashboard/src/components/updates/RuntimeSourceUpdate.test.tsx
index 614e607b2..dba1cef03 100644
--- a/apps/dashboard/src/components/updates/RuntimeSourceUpdate.test.tsx
+++ b/apps/dashboard/src/components/updates/RuntimeSourceUpdate.test.tsx
@@ -7,7 +7,7 @@ import { CloudResourceContext } from "@/context/CloudResourceContext";
import { ApiError, setApiResourceScope } from "@/lib/api/client";
import { RuntimeSourceUpdate } from "./RuntimeSourceUpdate";
import { SecurityProjectReview } from "./SecurityProjectReview";
-import type { ProjectControlOperations, ProjectSecurityResult } from "@repo/contracts";
+import type { ProjectSecurityResult } from "@repo/contracts";
const api = vi.hoisted(() => ({ git: vi.fn(), read: vi.fn(), preview: vi.fn(), publish: vi.fn() }));
vi.mock("@/lib/api/projects", () => ({ projectsApi: { getGit: api.git } }));
@@ -23,22 +23,6 @@ vi.mock("next/navigation", () => ({ useRouter: () => ({ push: vi.fn() }) }));
vi.mock("@/context/ToastContext", () => ({ useToast: () => ({ showToast: vi.fn() }) }));
vi.mock("@/hooks/useRuntimeUpdate", () => ({ useRuntimeUpdate: () => ({ updating: false }) }));
let root: Root, host: HTMLDivElement;
-const gitInfo = {
- success: true,
- provider: "github",
- owner: "acme",
- repo: "app",
- branch: "main",
- commits: [],
- auto_deploy: false,
- webhook_strategy: "app",
- webhook_active: true,
- webhook_domain: null,
- available_strategies: ["app"],
- verified_domains: [],
- installation_installed: true,
- default_rollback_strategy: "git",
-} satisfies Awaited
>;
const source = {
owner: "acme",
repo: "app",
@@ -54,7 +38,12 @@ beforeEach(() => {
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
setApiResourceScope("source-test");
vi.resetAllMocks();
- api.git.mockResolvedValue(gitInfo);
+ api.git.mockResolvedValue({
+ gitProvider: "github",
+ gitOwner: "acme",
+ gitRepo: "app",
+ gitBranch: "main",
+ });
api.read.mockResolvedValue({ data: source });
api.preview.mockResolvedValue({
data: {
@@ -101,8 +90,6 @@ async function setImage(value: string) {
it("requires a reviewed diff, invalidates it on edit, and creates a PR without triggering a deployment", async () => {
await render();
await click("Propose image update");
- expect(api.read).toHaveBeenCalledWith("project", { path: "Dockerfile", format: "dockerfile" });
- expect(document.body.textContent).toContain("acme/app · main");
await setImage("node:24");
expect(document.body.textContent).not.toContain("Create draft PR");
await click("Review change");
@@ -122,20 +109,6 @@ it("requires a reviewed diff, invalidates it on edit, and creates a PR without t
);
expect(document.body.textContent).toContain("Recheck the deployed runtime");
});
-it.each([
- { success: false, error: "No repository connected", code: "NO_REPOSITORY" },
- { ...gitInfo, provider: "local" },
- { ...gitInfo, branch: "" },
-])("does not load or publish source without a supported repository and branch: %j", async (git) => {
- api.git.mockResolvedValue(git);
- await render();
- await click("Propose image update");
- expect(document.body.textContent).toContain(
- "This project needs a connected GitHub repository and deployment branch.",
- );
- expect(api.read).not.toHaveBeenCalled();
- expect(api.publish).not.toHaveBeenCalled();
-});
it("discards source and pending responses after an account/workspace switch", async () => {
let resolve!: (value: unknown) => void;
api.read.mockImplementationOnce(
diff --git a/apps/dashboard/src/components/updates/RuntimeSourceUpdate.tsx b/apps/dashboard/src/components/updates/RuntimeSourceUpdate.tsx
index 28549358a..0bdecdb2e 100644
--- a/apps/dashboard/src/components/updates/RuntimeSourceUpdate.tsx
+++ b/apps/dashboard/src/components/updates/RuntimeSourceUpdate.tsx
@@ -122,20 +122,27 @@ function SourceEditor({
setBusy(true);
projectsApi
.getGit(projectId)
- .then(async (git) => {
- if (!current(request)) return;
- if (!git.success || git.provider !== "github" || !git.owner || !git.repo || !git.branch) {
- setError(copy.noRepository);
- return;
- }
- setRepo({ owner: git.owner, repo: git.repo, branch: git.branch });
- const { data } = await updatesApi.runtimeSource(projectId, {
- path: initialPath,
- format: /\.ya?ml$/i.test(initialPath) ? "compose" : "dockerfile",
- ...(serviceId && { serviceId }),
- });
- if (current(request)) acceptSource(data);
- })
+ .then(
+ async (git: {
+ gitProvider?: string;
+ gitOwner?: string;
+ gitRepo?: string;
+ gitBranch?: string;
+ }) => {
+ if (!current(request)) return;
+ if (git.gitProvider !== "github" || !git.gitOwner || !git.gitRepo || !git.gitBranch) {
+ setError(copy.noRepository);
+ return;
+ }
+ setRepo({ owner: git.gitOwner, repo: git.gitRepo, branch: git.gitBranch });
+ const { data } = await updatesApi.runtimeSource(projectId, {
+ path: initialPath,
+ format: /\.ya?ml$/i.test(initialPath) ? "compose" : "dockerfile",
+ ...(serviceId && { serviceId }),
+ });
+ if (current(request)) acceptSource(data);
+ },
+ )
.catch((error) => {
// diagnostics-ignore: showError reports through getApiErrorMessage and displays recovery.
if (current(request)) showError(error);
diff --git a/apps/dashboard/src/components/updates/useUpdates.requests.test.tsx b/apps/dashboard/src/components/updates/useUpdates.requests.test.tsx
index 611d94b00..743d047a3 100644
--- a/apps/dashboard/src/components/updates/useUpdates.requests.test.tsx
+++ b/apps/dashboard/src/components/updates/useUpdates.requests.test.tsx
@@ -64,7 +64,6 @@ async function mount() {
);
}
const releaseRequests = () => fetcher.mock.calls.filter(([url]) => String(url).includes("github"));
-const noticeRequests = () => fetcher.mock.calls.filter(([url]) => String(url).endsWith("/notices"));
beforeEach(async () => {
vi.resetModules();
@@ -155,17 +154,17 @@ describe("advisory dismissal within an app session", () => {
expect(state[0].state?.advisories).toEqual([critical, next]);
});
- it("also shares dismissal for verified security notices in the cloud dashboard", async () => {
+ it("also shares dismissal for operator notices in the cloud dashboard", async () => {
delete window.desktop;
deployment.selfHosted = false;
- feed.overview = affectedOverview;
+ // Every consumer receives its own readable response body.
+ fetcher.mockImplementation(
+ async () => new Response(JSON.stringify({ advisories: [critical] })),
+ );
await mount();
expect(check).toHaveBeenCalledOnce();
- expect(state[0].state?.advisories).toEqual([
- expect.objectContaining({ title: "Affected runtime", severity: "critical" }),
- ]);
- const noticeId = state[0].state!.advisories[0].id;
- await act(async () => state[0].dismissAdvisory(noticeId));
+ expect(state[0].state?.advisories).toEqual([critical]);
+ await act(async () => state[0].dismissAdvisory(critical.id));
await act(async () => state[1].reload());
expect(state[0].state?.advisories).toEqual([]);
expect(state[1].state?.advisories).toEqual([]);
@@ -193,37 +192,6 @@ afterEach(async () => {
});
describe("release check requests (#661)", () => {
- it.each([false, true])("only loads verified security for a new Cloud session (affected=%s)", async (affected) => {
- delete window.desktop;
- deployment.selfHosted = false;
- const release = {
- ...critical, id: "legacy-release", severity: "recommended", announce: false, affects: "*",
- title: "OpenShip 0.9.0 is released", target: { type: "platform" },
- action: { kind: "open-url", label: "View release notes", url: "https://github.com/oblien/openship/releases/tag/v0.9.0" },
- };
- check.mockResolvedValue({ ...snapshot, manifest: { advisories: [release] } });
- fetcher.mockImplementation(async () => new Response(JSON.stringify({ advisories: [release, critical] })));
- if (affected) feed.overview = affectedOverview;
- await mount();
- expect(noticeRequests()).toHaveLength(0);
- expect(state[0].state?.advisories).toEqual(affected
- ? [expect.objectContaining({ title: "Affected runtime", severity: "critical" })]
- : []);
- expect(state[0].state?.updateAvailable).toBe(false);
- expect(state[0].latest).toBeNull();
- expect(localStorage.length).toBe(0);
- });
-
- it.each(["desktop", "selfhosted"])("keeps release and operator announcements for %s", async (mode) => {
- if (mode === "selfhosted") delete window.desktop;
- const release = { ...critical, id: "release-notice", severity: "recommended" as const };
- check.mockResolvedValue({ ...snapshot, manifest: { advisories: [release] } });
- fetcher.mockImplementation(async () => new Response(JSON.stringify({ advisories: [critical] })));
- await mount();
- expect(noticeRequests().length).toBeGreaterThan(0);
- expect(state[0].state?.advisories.map((notice) => notice.id)).toEqual([critical.id, release.id]);
- });
-
it.each(["desktop", "selfhosted", "cloud"])(
"scopes signed control-plane advisories correctly in %s",
async (mode) => {
diff --git a/apps/dashboard/src/components/updates/useUpdates.ts b/apps/dashboard/src/components/updates/useUpdates.ts
index c4f436f34..120c3c79c 100644
--- a/apps/dashboard/src/components/updates/useUpdates.ts
+++ b/apps/dashboard/src/components/updates/useUpdates.ts
@@ -304,8 +304,10 @@ function runtimeNotices(overview: SecurityOverview, scope: string): RuntimeAdvis
return [...notices.values()];
}
-// Operator announcements for Desktop and self-hosted instances. Managed Cloud's
-// update banner uses verified workload-security notices, so it skips this feed.
+// The SaaS advisory source: operator-pushed platform notices from our own API
+// (partial outage, maintenance, upgrade advisories), returned in the SAME
+// manifest shape as the GitHub advisory feed so the shared banner renders both
+// identically. Same-origin on the SaaS; never throws (offline → no notices).
async function fetchNotices(): Promise {
try {
const res = await fetch(`${getRestApiBaseUrl()}/notices`, {
@@ -424,7 +426,7 @@ export function useUpdates(): UseUpdates {
const [prefs, remote, notices] = await Promise.all([
getPrefs(),
fetchRemote(requestKey),
- mode === "cloud" ? Promise.resolve({ advisories: [] }) : fetchNotices(),
+ fetchNotices(),
]);
if (!isCurrent()) return;
setCurrentVersion(current);
diff --git a/apps/dashboard/src/constants/mock.ts b/apps/dashboard/src/constants/mock.ts
index 91532d414..a69bb41eb 100644
--- a/apps/dashboard/src/constants/mock.ts
+++ b/apps/dashboard/src/constants/mock.ts
@@ -78,7 +78,7 @@ export interface Project {
lifecycleOperation?: ProjectLifecycleOperation | null;
/* ── Hosting info (enriched by API) ─────────────────────── */
- iconUrl?: string | null;
+ favicon?: string | null;
deployTarget?: string | null;
serverId?: string | null;
serverName?: string | null;
diff --git a/apps/dashboard/src/context/ProjectSettingsContext.tsx b/apps/dashboard/src/context/ProjectSettingsContext.tsx
index a89f1139d..0a84110b2 100644
--- a/apps/dashboard/src/context/ProjectSettingsContext.tsx
+++ b/apps/dashboard/src/context/ProjectSettingsContext.tsx
@@ -755,8 +755,7 @@ const ProjectSettingsState: React.FC = ({
verifiedDomains: response.verified_domains,
installationInstalled: response.installation_installed,
installUrl: response.install_url,
- defaultRollbackStrategy:
- response.default_rollback_strategy === "snapshot" ? "snapshot" : "git",
+ defaultRollbackStrategy: response.default_rollback_strategy,
});
} else {
// "No repository connected" is the NORMAL state for upload/local
diff --git a/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx b/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx
index 46973e557..a5ea2f0be 100644
--- a/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx
+++ b/apps/dashboard/src/hooks/cloud-resource-refresh.test.tsx
@@ -107,7 +107,8 @@ it("discards server-rendered project settings and late services when the Cloud i
it("does not open a checkout returned for a disconnected Cloud account", async () => {
const old = deferred();
h.checkout.mockReturnValue(old.promise);
- const open = vi.spyOn(window, "open").mockReturnValue(null);
+ const popup = { close: vi.fn(), opener: null, location: { href: "about:blank" } };
+ const open = vi.spyOn(window, "open").mockReturnValue(popup as unknown as Window);
const started = vi.fn();
function Checkout() {
const checkout = useCloudCheckout({ enabled: true, preserveProject: true, onCheckoutStarted: started });
@@ -120,7 +121,8 @@ it("does not open a checkout returned for a disconnected Cloud account", async (
await render("account-b", page);
await act(async () => old.resolve({ data: { checkoutUrl: "https://checkout.stripe.com/old-account" } }));
expect(host.textContent).toBe("Choose plan");
- expect(open).not.toHaveBeenCalled();
+ expect(popup.location.href).toBe("about:blank");
+ expect(popup.close).toHaveBeenCalledOnce();
expect(started).not.toHaveBeenCalled();
} finally { open.mockRestore(); }
});
diff --git a/apps/dashboard/src/i18n/locales/ar/auth.json b/apps/dashboard/src/i18n/locales/ar/auth.json
index 3f552cd63..a414e78af 100644
--- a/apps/dashboard/src/i18n/locales/ar/auth.json
+++ b/apps/dashboard/src/i18n/locales/ar/auth.json
@@ -70,8 +70,6 @@
"errorDescription": "قد يكون الرمز غير صحيح أو منتهي الصلاحية.",
"resendEmail": "إعادة إرسال الرمز",
"signIn": "تسجيل الدخول",
- "signupTitle": "تحقق من بريدك الإلكتروني",
- "signupSentTo": "أرسلنا الخطوة التالية إلى {email}. أدخل الرمز أدناه إذا وصلك، أو اتبع تعليمات تسجيل الدخول في الرسالة.",
"pendingTitle": "تحقق من بريدك الإلكتروني",
"pendingSentTo": "أرسلنا رمزًا من ٦ أرقام إلى {email}. أدخله أدناه للتحقق من بريدك الإلكتروني.",
"pendingGeneric": "أدخل رمز التحقق الذي أرسلناه إلى بريدك الإلكتروني.",
diff --git a/apps/dashboard/src/i18n/locales/ar/billing.json b/apps/dashboard/src/i18n/locales/ar/billing.json
index 15ef629d7..876f12977 100644
--- a/apps/dashboard/src/i18n/locales/ar/billing.json
+++ b/apps/dashboard/src/i18n/locales/ar/billing.json
@@ -546,7 +546,6 @@
"diskGrowth": "يمكن زيادة مساحة القرص الحالي. تقليلها يتطلب نقل بياناتك إلى خادم جديد.",
"range": "من {min} إلى {max} {unit}",
"monthlyTotal": "الإجمالي الشهري",
- "yearlyTotal": "الإجمالي السنوي",
"choose": "اختيار الخطة المخصصة",
"updating": "جارٍ تحديث السعر",
"invalid": "أدخل قيمة صحيحة ضمن النطاق المتاح لكل مورد.",
@@ -558,7 +557,6 @@
"extraMemory": "ذاكرة إضافية",
"extraDisk": "تخزين إضافي",
"rates": "الإضافات الشهرية: {cpu} لكل vCPU، و{memory} لكل GB ذاكرة، و{disk} لكل GB تخزين. تُحسب فقط الموارد الزائدة عن الباقة المحددة.",
- "yearlyRates": "الإضافات السنوية: {cpu}/وحدة معالجة افتراضية، {memory}/جيجابايت ذاكرة، {disk}/جيجابايت تخزين. تُحتسب فقط للموارد التي تتجاوز الباقة المحددة.",
"applyNotice": "تُطبّق الترقيات بعد الدفع. تبدأ التغييرات الأقل تكلفة عند التجديد.",
"resizeTitle": "تطبيق موارد اشتراكك",
"resizeDescription": "تغيّرت خطتك. راجع السعة الجديدة والمشاريع المتأثرة قبل إعادة تشغيل هذا الخادم.",
diff --git a/apps/dashboard/src/i18n/locales/ar/deployments.json b/apps/dashboard/src/i18n/locales/ar/deployments.json
index 98aa49310..a6067abae 100644
--- a/apps/dashboard/src/i18n/locales/ar/deployments.json
+++ b/apps/dashboard/src/i18n/locales/ar/deployments.json
@@ -202,13 +202,6 @@
"pageOf": "الصفحة {page} من {total}",
"range": "عمليات النشر {from}–{to} من {total}"
},
- "containerConflict": {
- "title": "حل تعارض الحاويات المكررة",
- "description": "افحص الحاويات ووحدات التخزين المتصلة بها على الخادم المستهدف. احتفظ بالحاوية المطلوبة وبياناتها، واحذف فقط نسخة مكررة تأكدت أنها غير مستخدمة، ثم أعد النشر. إذا لم تكن متأكدًا من الحاوية التي يجب الاحتفاظ بها، فتواصل مع الدعم وأرفق مرجع النشر هذا.",
- "containers": "الحاويات المتطابقة",
- "reviewServer": "مراجعة الخادم",
- "reference": "مرجع النشر"
- },
"resourceGuidance": {
"label": "إرشادات موارد النشر",
"reviewCapacity": "مراجعة السعة",
diff --git a/apps/dashboard/src/i18n/locales/ar/emailsAdmin.json b/apps/dashboard/src/i18n/locales/ar/emailsAdmin.json
index 907a131fe..0398d1184 100644
--- a/apps/dashboard/src/i18n/locales/ar/emailsAdmin.json
+++ b/apps/dashboard/src/i18n/locales/ar/emailsAdmin.json
@@ -519,7 +519,7 @@
"accountsTitle": "الحسابات والنطاقات والأسماء المستعارة",
"accountsDesc": "صناديق البريد (مع تجزئات كلمات المرور) والنطاقات والأسماء المستعارة — قاعدة بيانات vmail.",
"messageTitle": "بيانات رسائل صندوق البريد",
- "messageDesc": "الرسائل والمجلدات وقائمة الانتظار والحجر. يتوقف التسليم وIMAP مؤقتًا أثناء النسخ.",
+ "messageDesc": "كل بريد مخزّن (مجلدات maildir في /var/vmail). قد تكون كبيرة.",
"keysTitle": "مفاتيح وأسرار DKIM",
"keysDesc": "مفاتيح DKIM + الإعدادات + mail-state.json. يبقي DKIM صالحًا عند الاستعادة — لكن الأرشيف عندئذٍ يحتوي على مفاتيح خاصة وأسرار.",
"keysWarning": "ستحتوي النسخة الاحتياطية على تجزئات كلمات المرور ومفاتيح DKIM الخاصة وأسرار بنص صريح. أبقِ الوجهة خاصة.",
diff --git a/apps/dashboard/src/i18n/locales/ar/migration.json b/apps/dashboard/src/i18n/locales/ar/migration.json
index 900e5b892..d7dcc9e26 100644
--- a/apps/dashboard/src/i18n/locales/ar/migration.json
+++ b/apps/dashboard/src/i18n/locales/ar/migration.json
@@ -1,18 +1,4 @@
{
- "platformDomains": {
- "title": "النطاقات وDNS",
- "intro": "الاستيراد لا يغيّر DNS ولا ينقل حركة الزيارات.",
- "customAction": "تحديث DNS",
- "providerAction": "استبدال الرابط",
- "customHint": "تُضاف النطاقات المخصصة إلى النطاقات والمسارات في الخدمة المطابقة. بعد فحص التطبيق المستورد، راجع سجلات DNS وأكمل التحقق.",
- "providerHint": "لا يمكن نقل الروابط المملوكة للمزوّد إلى OpenShip. اختر عنوانًا جديدًا وحدّث روابط التطبيق وعناوين إعادة الاتصال في OAuth والويب هوك التي تستخدم العنوان القديم.",
- "empty": "لم يتم اكتشاف نطاقات عامة. أبقِ الخدمات الداخلية خاصة، وأضف نطاقًا فقط إذا احتاجت الخدمة إلى وصول عام.",
- "next": "قبل تأكيد نقل الزيارات",
- "test": "افتح النطاقات والمسارات لمراجعة المسارات المستوردة. أضف نطاقًا تجريبيًا عند الحاجة وتحقّق من التطبيق وبياناته.",
- "dns": "راجع نطاقاتك المخصصة في النطاقات والمسارات وأضف أي نطاقات مفقودة. ثم طبّق سجلات DNS المعروضة كما هي لدى مزوّد DNS، أو راجع إعداد DNS التلقائي باستخدام اتصال مدعوم. استبدل سجلات التوجيه القديمة واحتفظ بالسجلات الأخرى.",
- "verify": "تحقّق من DNS وHTTPS في OpenShip، ثم اختبر الروابط العامة قبل تأكيد الإكمال.",
- "openDomains": "مراجعة النطاقات وDNS"
- },
"wizard": {
"edgeReview": {
"detected": "تم اكتشاف {proxy}",
diff --git a/apps/dashboard/src/i18n/locales/ar/projectSettings.json b/apps/dashboard/src/i18n/locales/ar/projectSettings.json
index 8ccbdf611..0cdab3a8e 100644
--- a/apps/dashboard/src/i18n/locales/ar/projectSettings.json
+++ b/apps/dashboard/src/i18n/locales/ar/projectSettings.json
@@ -482,7 +482,7 @@
},
"runtime": {
"title": "إعداد وقت التشغيل",
- "description": "احفظ الإعدادات هنا. تسري التغييرات عند النشر التالي.",
+ "description": "للقراءة فقط. عدّل عبر معالج النشر بحيث يُشحن كل تغيير كإصدار جديد.",
"framework": "الإطار",
"packageManager": "مدير الحزم",
"runtimeIsolation": "عزل وقت التشغيل",
@@ -498,11 +498,7 @@
"modeSandboxed": "معزول (حاوية)",
"modeDirect": "مباشر (عملية على المضيف)",
"modeDefault": "افتراضي (يُحدَّد عند النشر)",
- "modeStatic": "لا شيء — يُقدَّم كملفات ثابتة",
- "saved": "تم حفظ الإعدادات. انشر لتطبيق التغييرات.",
- "saveFailed": "تعذر حفظ الإعدادات. لا تزال تغييراتك محفوظة في النموذج.",
- "projectSettingsHint": "تُدار البيئة المشتركة وحدود الموارد من إعدادات المشروع.",
- "invalidPort": "أدخل منفذًا بين 1 و65535."
+ "modeStatic": "لا شيء — يُقدَّم كملفات ثابتة"
},
"storage": {
"title": "تخزين دائم",
@@ -544,7 +540,7 @@
"env": {
"title": "بيئة المشروع",
"sharedTitle": "بيئة المشروع المشتركة",
- "description": "قيم افتراضية مشتركة للبناء والتشغيل. قيم الخدمة لها الأولوية. تبقى الأسرار مخفية.",
+ "description": "تُستخدم أثناء البناء والتشغيل. تبقى الأسرار مخفية.",
"edit": "تعديل"
}
},
@@ -1388,59 +1384,5 @@
"manual": "لم يُعثر على مرجع صورة مباشر قابل للتحرير. افتح ملف المصدر لتحديث المتغيرات أو الصور الموروثة أو منطق البناء المخصص.",
"working": "جارٍ العمل…",
"failed": "تعذّر إعداد تحديث المصدر."
- },
- "responseRoutes": {
- "title": "المسارات الافتراضية",
- "description": "أعِد المحتوى مباشرةً من الحافة عبر مسار على هذا النطاق.",
- "add": "إضافة مسار",
- "edit": "تعديل المسار",
- "staticResponse": "استجابة ثابتة",
- "loading": "جارٍ تحميل المسارات",
- "loadFailed": "تعذّر تحميل المسارات الافتراضية.",
- "retry": "إعادة المحاولة",
- "saveFailed": "تعذّر حفظ المسار.",
- "duplicateHeader": "يجب أن يكون اسم كل ترويسة استجابة فريدًا.",
- "enabled": "مفعّل",
- "disabled": "معطّل",
- "enable": "تفعيل",
- "disable": "تعطيل",
- "remove": "إزالة",
- "removeHint": "هل تريد إزالة هذه الاستجابة؟ ستستخدم الطلبات مسارات النطاق المتبقية.",
- "cancel": "إلغاء",
- "close": "إغلاق",
- "path": "المسار",
- "match": "المطابقة",
- "exact": "مسار مطابق تمامًا",
- "prefix": "بادئة المسار",
- "exactHint": "يطابق هذا المسار فقط. يتم تجاهل معاملات الاستعلام.",
- "prefixHint": "يطابق هذا المسار والمسارات التابعة له. تكون الأولوية للمسار الأكثر تحديدًا.",
- "status": "رمز الحالة",
- "contentType": "نوع المحتوى",
- "plainText": "نص عادي",
- "custom": "مخصّص",
- "customContentType": "نوع محتوى مخصّص",
- "body": "محتوى الاستجابة",
- "bodyPlaceholder": "أدخل المحتوى الذي تريد إرجاعه…",
- "bodyHint": "محتوى نصي بحجم يصل إلى 64 KiB.",
- "headers": "ترويسات الاستجابة",
- "addHeader": "إضافة ترويسة",
- "headerName": "اسم الترويسة",
- "headerValue": "قيمة الترويسة",
- "removeHeader": "إزالة الترويسة",
- "methods": "طرق الطلب",
- "methodsHint": "طرق مفصولة بفواصل. اترك الحقل فارغًا للسماح بجميع الطرق. تشمل GET طريقة HEAD.",
- "preview": "معاينة الاستجابة",
- "applyHint": "يُطبّق دون إعادة نشر التطبيق.",
- "save": "حفظ الاستجابة",
- "saved": "تم الحفظ والتطبيق على الحافة.",
- "pending": "تم الحفظ. التطبيق على الحافة معلّق. حدّث الحافة أو أعد اتصالها، ثم أعد محاولة التوجيه.",
- "bytes": "بايت",
- "emptyBodyHint": "يتطلب رمز الحالة هذا محتوى استجابة فارغًا.",
- "headersHint": "أضف ترويسات للتخزين المؤقت أو CORS أو غيرها."
- },
- "icon": {
- "label": "رابط أيقونة المشروع",
- "hint": "استخدم رابط صورة HTTP أو HTTPS. امسحه لاستخدام الأيقونة الافتراضية.",
- "reset": "استخدام الأيقونة الافتراضية"
}
}
diff --git a/apps/dashboard/src/i18n/locales/ar/settings.json b/apps/dashboard/src/i18n/locales/ar/settings.json
index 7e6d02ff5..360545e81 100644
--- a/apps/dashboard/src/i18n/locales/ar/settings.json
+++ b/apps/dashboard/src/i18n/locales/ar/settings.json
@@ -1791,21 +1791,5 @@
"confirmCta": "إيقاف الخدمة",
"cancel": "إلغاء",
"noReverseProxy": "لم يتم اكتشاف وكيل عكسي على هذا الجهاز."
- },
- "imageUrl": {
- "preview": "معاينة الصورة",
- "invalid": "أدخل رابط صورة HTTP أو HTTPS بدون بيانات تسجيل دخول.",
- "failed": "تعذّر حفظ رابط الصورة.",
- "save": "حفظ",
- "saving": "جارٍ الحفظ…",
- "saved": "تم الحفظ",
- "previewFailed": "المعاينة غير متاحة. تأكد أن الرابط يشير مباشرةً إلى صورة."
- },
- "profile": {
- "title": "الملف الشخصي",
- "description": "صورة حسابك الشخصي.",
- "label": "رابط الصورة الشخصية",
- "hint": "استخدم رابط صورة مباشرًا. اتركه فارغًا لاستخدام الحرف الأول من اسمك.",
- "reset": "استخدام الحرف الأول"
}
}
diff --git a/apps/dashboard/src/i18n/locales/de/auth.json b/apps/dashboard/src/i18n/locales/de/auth.json
index 10a58a691..c09e5fb7b 100644
--- a/apps/dashboard/src/i18n/locales/de/auth.json
+++ b/apps/dashboard/src/i18n/locales/de/auth.json
@@ -70,8 +70,6 @@
"errorDescription": "Der Code ist möglicherweise falsch oder abgelaufen.",
"resendEmail": "Code erneut senden",
"signIn": "Anmelden",
- "signupTitle": "Prüfe deine E-Mails",
- "signupSentTo": "Wir haben den nächsten Schritt an {email} gesendet. Gib unten den erhaltenen Code ein oder folge den Anweisungen zur Anmeldung in der E-Mail.",
"pendingTitle": "Verifizieren Sie Ihre E-Mail-Adresse",
"pendingSentTo": "Wir haben einen 6-stelligen Code an {email} gesendet. Geben Sie ihn unten ein, um Ihre E-Mail-Adresse zu verifizieren.",
"pendingGeneric": "Geben Sie den Verifizierungscode aus unserer E-Mail ein.",
diff --git a/apps/dashboard/src/i18n/locales/de/billing.json b/apps/dashboard/src/i18n/locales/de/billing.json
index 868d7ea4c..5382976e0 100644
--- a/apps/dashboard/src/i18n/locales/de/billing.json
+++ b/apps/dashboard/src/i18n/locales/de/billing.json
@@ -668,7 +668,6 @@
"diskGrowth": "Bestehende Datenträger können vergrößert werden. Zum Verkleinern müssen die Daten auf einen neuen Server verschoben werden.",
"range": "{min} bis {max} {unit}",
"monthlyTotal": "Monatlicher Gesamtpreis",
- "yearlyTotal": "Jährlicher Gesamtpreis",
"choose": "Individuell wählen",
"updating": "Preis wird aktualisiert",
"invalid": "Gib für jede Ressource einen gültigen Wert im angegebenen Bereich ein.",
@@ -680,7 +679,6 @@
"extraMemory": "Zusätzlicher Arbeitsspeicher",
"extraDisk": "Zusätzlicher Speicherplatz",
"rates": "Monatliche Zusatzressourcen: {cpu}/vCPU, {memory}/GB RAM, {disk}/GB Speicherplatz. Berechnet wird nur, was über das gewählte Paket hinausgeht.",
- "yearlyRates": "Jährliche Extras: {cpu}/vCPU, {memory}/GB RAM, {disk}/GB Speicher. Nur Ressourcen über das gewählte Paket hinaus werden berechnet.",
"applyNotice": "Upgrades gelten nach der Zahlung. Günstigere Änderungen beginnen bei der Verlängerung.",
"resizeTitle": "Gebuchte Ressourcen übernehmen",
"resizeDescription": "Dein Tarif hat sich geändert. Prüfe die neue Kapazität und die betroffenen Projekte, bevor du diesen Server neu startest.",
diff --git a/apps/dashboard/src/i18n/locales/de/deployments.json b/apps/dashboard/src/i18n/locales/de/deployments.json
index 5f868daed..2d40185de 100644
--- a/apps/dashboard/src/i18n/locales/de/deployments.json
+++ b/apps/dashboard/src/i18n/locales/de/deployments.json
@@ -202,13 +202,6 @@
"pageOf": "Seite {page} von {total}",
"range": "Bereitstellungen {from}–{to} von {total}"
},
- "containerConflict": {
- "title": "Doppelte Container prüfen",
- "description": "Prüfe die Container und ihre eingebundenen Datenträger auf dem Zielserver. Behalte den vorgesehenen Container und seine Daten. Entferne nur ein nachweislich ungenutztes Duplikat und stelle dann erneut bereit. Bei Unsicherheit kontaktiere den Support mit dieser Bereitstellungsreferenz.",
- "containers": "Übereinstimmende Container",
- "reviewServer": "Server prüfen",
- "reference": "Bereitstellungsreferenz"
- },
"resourceGuidance": {
"label": "Ressourcenhinweise zur Bereitstellung",
"reviewCapacity": "Kapazität prüfen",
diff --git a/apps/dashboard/src/i18n/locales/de/emailsAdmin.json b/apps/dashboard/src/i18n/locales/de/emailsAdmin.json
index 07efa5dfe..48adb4de0 100644
--- a/apps/dashboard/src/i18n/locales/de/emailsAdmin.json
+++ b/apps/dashboard/src/i18n/locales/de/emailsAdmin.json
@@ -519,7 +519,7 @@
"accountsTitle": "Konten, Domains & Aliase",
"accountsDesc": "Postfächer (mit Passwort-Hashes), Domains und Aliase – die vmail-Datenbank.",
"messageTitle": "Postfach-Nachrichtendaten",
- "messageDesc": "Nachrichten, Ordner, Warteschlange und Quarantäne. Zustellung und IMAP pausieren während des Kopierens.",
+ "messageDesc": "Jede gespeicherte E-Mail (die /var/vmail-Maildirs). Kann groß sein.",
"keysTitle": "DKIM-Schlüssel & Geheimnisse",
"keysDesc": "DKIM-Schlüssel + Konfiguration + mail-state.json. Hält DKIM bei der Wiederherstellung gültig – aber das Archiv enthält dann private Schlüssel und Geheimnisse.",
"keysWarning": "Die Sicherung enthält Passwort-Hashes, private DKIM-Schlüssel und Geheimnisse im Klartext. Halte das Ziel privat.",
diff --git a/apps/dashboard/src/i18n/locales/de/migration.json b/apps/dashboard/src/i18n/locales/de/migration.json
index 0faec942d..8fc76620f 100644
--- a/apps/dashboard/src/i18n/locales/de/migration.json
+++ b/apps/dashboard/src/i18n/locales/de/migration.json
@@ -1,18 +1,4 @@
{
- "platformDomains": {
- "title": "Domains und DNS",
- "intro": "Der Import ändert weder DNS noch die Weiterleitung des Datenverkehrs.",
- "customAction": "DNS aktualisieren",
- "providerAction": "URL ersetzen",
- "customHint": "Eigene Domains werden unter Domains & Routen dem passenden Dienst zugeordnet. Prüfe die importierte App, kontrolliere dann ihre DNS-Einträge und schließe die Verifizierung ab.",
- "providerHint": "URLs des Anbieters können nicht zu OpenShip umziehen. Wähle eine neue Adresse und aktualisiere App-URLs, OAuth-Callbacks und Webhooks, die die alte verwenden.",
- "empty": "Es wurden keine öffentlichen Domains gefunden. Halte interne Dienste privat; füge nur dann eine Domain hinzu, wenn ein Dienst öffentlichen Zugriff benötigt.",
- "next": "Vor der Bestätigung der Umstellung",
- "test": "Öffne Domains & Routen, um die importierten Routen zu prüfen. Füge bei Bedarf eine Testdomain hinzu und prüfe die App und ihre Daten.",
- "dns": "Prüfe deine eigenen Domains unter Domains & Routen und füge fehlende hinzu. Übernimm dann die angezeigten DNS-Einträge exakt bei deinem DNS-Anbieter oder prüfe die automatische DNS-Konfiguration mit einer unterstützten Verbindung. Ersetze die alten Routing-Einträge und behalte alle anderen Einträge.",
- "verify": "Prüfe DNS und HTTPS in OpenShip und teste die öffentlichen URLs, bevor du den Abschluss bestätigst.",
- "openDomains": "Domains & DNS prüfen"
- },
"wizard": {
"edgeReview": {
"detected": "{proxy} erkannt",
diff --git a/apps/dashboard/src/i18n/locales/de/projectSettings.json b/apps/dashboard/src/i18n/locales/de/projectSettings.json
index 427e82fc1..174f88f40 100644
--- a/apps/dashboard/src/i18n/locales/de/projectSettings.json
+++ b/apps/dashboard/src/i18n/locales/de/projectSettings.json
@@ -482,7 +482,7 @@
},
"runtime": {
"title": "Laufzeitkonfiguration",
- "description": "Konfiguration hier speichern. Änderungen werden bei der nächsten Bereitstellung wirksam.",
+ "description": "Schreibgeschützt. Bearbeiten Sie über den Deploy-Assistenten, damit jede Änderung als neue Version ausgeliefert wird.",
"framework": "Framework",
"packageManager": "Paketmanager",
"runtimeIsolation": "Laufzeit-Isolation",
@@ -498,11 +498,7 @@
"modeSandboxed": "Sandbox (Container)",
"modeDirect": "Direkt (Host-Prozess)",
"modeDefault": "Standard (beim Deploy aufgelöst)",
- "modeStatic": "Keine – als statische Dateien ausgeliefert",
- "saved": "Konfiguration gespeichert. Stelle die App bereit, um die Änderungen anzuwenden.",
- "saveFailed": "Die Konfiguration konnte nicht gespeichert werden. Deine Änderungen bleiben im Formular erhalten.",
- "projectSettingsHint": "Die gemeinsame Umgebung und Ressourcenlimits werden in den Projekteinstellungen verwaltet.",
- "invalidPort": "Gib einen Port zwischen 1 und 65535 ein."
+ "modeStatic": "Keine – als statische Dateien ausgeliefert"
},
"storage": {
"title": "Dauerhafter Speicher",
@@ -544,7 +540,7 @@
"env": {
"title": "Projektumgebung",
"sharedTitle": "Gemeinsame Projektumgebung",
- "description": "Gemeinsame Standardwerte für Image-Builds und Laufzeit. Dienstwerte haben Vorrang. Geheimnisse bleiben verborgen.",
+ "description": "Wird beim Build und zur Laufzeit verwendet. Geheimnisse bleiben maskiert.",
"edit": "Bearbeiten"
}
},
@@ -1388,59 +1384,5 @@
"manual": "Keine bearbeitbare direkte Image-Referenz gefunden. Öffne die Quelldatei, um Variablen, geerbte Images oder eigene Build-Logik anzupassen.",
"working": "Wird bearbeitet…",
"failed": "Das Quellcode-Update konnte nicht vorbereitet werden."
- },
- "responseRoutes": {
- "title": "Virtuelle Routen",
- "description": "Inhalte an einem Pfad dieser Domain direkt am Edge zurückgeben.",
- "add": "Route hinzufügen",
- "edit": "Route bearbeiten",
- "staticResponse": "Statische Antwort",
- "loading": "Routen werden geladen",
- "loadFailed": "Virtuelle Routen konnten nicht geladen werden.",
- "retry": "Erneut versuchen",
- "saveFailed": "Die Route konnte nicht gespeichert werden.",
- "duplicateHeader": "Jeder Antwort-Header muss einen eindeutigen Namen haben.",
- "enabled": "Aktiviert",
- "disabled": "Deaktiviert",
- "enable": "Aktivieren",
- "disable": "Deaktivieren",
- "remove": "Entfernen",
- "removeHint": "Diese Antwort entfernen? Anfragen verwenden dann die übrigen Domain-Routen.",
- "cancel": "Abbrechen",
- "close": "Schließen",
- "path": "Pfad",
- "match": "Abgleich",
- "exact": "Exakter Pfad",
- "prefix": "Pfadpräfix",
- "exactHint": "Gilt nur für diesen Pfad. Abfrageparameter werden ignoriert.",
- "prefixHint": "Gilt für diesen Pfad und seine Unterpfade. Der spezifischste Pfad hat Vorrang.",
- "status": "Statuscode",
- "contentType": "Inhaltstyp",
- "plainText": "Klartext",
- "custom": "Benutzerdefiniert",
- "customContentType": "Benutzerdefinierter Inhaltstyp",
- "body": "Antwortinhalt",
- "bodyPlaceholder": "Zurückzugebenden Inhalt eingeben…",
- "bodyHint": "Unveränderter Inhalt, bis zu 64 KiB.",
- "headers": "Antwort-Header",
- "addHeader": "Header hinzufügen",
- "headerName": "Header-Name",
- "headerValue": "Header-Wert",
- "removeHeader": "Header entfernen",
- "methods": "Anfragemethoden",
- "methodsHint": "Kommagetrennte Methoden. Leer lassen für alle Methoden. GET schließt HEAD ein.",
- "preview": "Antwortvorschau",
- "applyHint": "Wird ohne erneutes Bereitstellen der App angewendet.",
- "save": "Antwort speichern",
- "saved": "Gespeichert und am Edge angewendet.",
- "pending": "Gespeichert. Anwendung am Edge steht aus. Edge aktualisieren oder verbinden und Routing erneut versuchen.",
- "bytes": "Bytes",
- "emptyBodyHint": "Dieser Status erfordert einen leeren Antwortinhalt.",
- "headersHint": "Cache-, CORS- oder andere Antwortheader hinzufügen."
- },
- "icon": {
- "label": "URL des Projektsymbols",
- "hint": "Verwende eine HTTP- oder HTTPS-Bild-URL. Leere sie, um das Standardsymbol zu verwenden.",
- "reset": "Standardsymbol verwenden"
}
}
diff --git a/apps/dashboard/src/i18n/locales/de/settings.json b/apps/dashboard/src/i18n/locales/de/settings.json
index 296a00e59..2a500160e 100644
--- a/apps/dashboard/src/i18n/locales/de/settings.json
+++ b/apps/dashboard/src/i18n/locales/de/settings.json
@@ -1791,21 +1791,5 @@
"confirmCta": "Bereitstellung stoppen",
"cancel": "Abbrechen",
"noReverseProxy": "Auf dieser Maschine wurde kein Reverse-Proxy erkannt."
- },
- "imageUrl": {
- "preview": "Bildvorschau",
- "invalid": "Gib eine HTTP- oder HTTPS-Bild-URL ohne Zugangsdaten ein.",
- "failed": "Die Bild-URL konnte nicht gespeichert werden.",
- "save": "Speichern",
- "saving": "Wird gespeichert…",
- "saved": "Gespeichert",
- "previewFailed": "Keine Vorschau verfügbar. Prüfe, ob die URL direkt auf ein Bild verweist."
- },
- "profile": {
- "title": "Profil",
- "description": "Das Bild deines persönlichen Kontos.",
- "label": "Avatar-URL",
- "hint": "Verwende eine direkte Bild-URL. Leer lassen, um deinen Anfangsbuchstaben anzuzeigen.",
- "reset": "Anfangsbuchstaben verwenden"
}
}
diff --git a/apps/dashboard/src/i18n/locales/en/auth.json b/apps/dashboard/src/i18n/locales/en/auth.json
index 99cd7ac94..986626bc2 100644
--- a/apps/dashboard/src/i18n/locales/en/auth.json
+++ b/apps/dashboard/src/i18n/locales/en/auth.json
@@ -70,8 +70,6 @@
"errorDescription": "The code may be incorrect or expired.",
"resendEmail": "Resend code",
"signIn": "Sign in",
- "signupTitle": "Check your email",
- "signupSentTo": "We've emailed the next step to {email}. Enter a code below if you received one, or follow the sign-in instructions in the email.",
"pendingTitle": "Verify your email",
"pendingSentTo": "We emailed a 6-digit code to {email}. Enter it below to verify your email.",
"pendingGeneric": "Enter the verification code we emailed you.",
diff --git a/apps/dashboard/src/i18n/locales/en/billing.json b/apps/dashboard/src/i18n/locales/en/billing.json
index e1eb92f67..f243b3335 100644
--- a/apps/dashboard/src/i18n/locales/en/billing.json
+++ b/apps/dashboard/src/i18n/locales/en/billing.json
@@ -334,7 +334,7 @@
"upgradeDescription": "Choose a plan with enough capacity, or adjust your project and try again.",
"manageBilling": "Manage billing",
"topups": "Add usage",
- "checkoutOpened": "Complete your payment in secure checkout. If it did not open, use the button below.",
+ "checkoutOpened": "Checkout is ready in a separate tab. If it did not open, use the link below.",
"continueCheckout": "Continue to checkout",
"reasons": {
"static-only": "Your plan does not include this type of app. Choose a plan that supports it to deploy.",
@@ -546,7 +546,6 @@
"diskGrowth": "Storage can grow. Reducing it requires moving your data to a new destination.",
"range": "{min}–{max} {unit}",
"monthlyTotal": "Monthly total",
- "yearlyTotal": "Yearly total",
"choose": "Choose Custom",
"updating": "Updating price",
"invalid": "Enter a valid amount within each resource range.",
@@ -558,7 +557,6 @@
"extraMemory": "Additional memory",
"extraDisk": "Additional storage",
"rates": "Monthly extras: {cpu}/vCPU, {memory}/GB RAM, {disk}/GB storage. Charged only above the selected bundle.",
- "yearlyRates": "Yearly extras: {cpu}/vCPU, {memory}/GB RAM, {disk}/GB storage. Charged only above the selected bundle.",
"applyNotice": "Upgrades apply after payment. Lower-cost changes start at renewal.",
"resizeTitle": "Apply your subscribed resources",
"resizeDescription": "Your plan has changed. Review the new capacity and affected projects before applying.",
diff --git a/apps/dashboard/src/i18n/locales/en/deployments.json b/apps/dashboard/src/i18n/locales/en/deployments.json
index 3478e9803..a4af5e414 100644
--- a/apps/dashboard/src/i18n/locales/en/deployments.json
+++ b/apps/dashboard/src/i18n/locales/en/deployments.json
@@ -202,13 +202,6 @@
"confirm": "Roll back",
"cancel": "Cancel"
},
- "containerConflict": {
- "title": "Resolve duplicate containers",
- "description": "Inspect the containers and their mounts on the target server. Keep the intended container and its data, remove only a confirmed unused duplicate, then redeploy. If you are unsure which to keep, contact support with this deployment reference.",
- "containers": "Matching containers",
- "reviewServer": "Review server",
- "reference": "Deployment reference"
- },
"resourceGuidance": {
"label": "Deployment resource guidance",
"reviewCapacity": "Review capacity",
diff --git a/apps/dashboard/src/i18n/locales/en/emailsAdmin.json b/apps/dashboard/src/i18n/locales/en/emailsAdmin.json
index 476b59c4b..c80f8fd1c 100644
--- a/apps/dashboard/src/i18n/locales/en/emailsAdmin.json
+++ b/apps/dashboard/src/i18n/locales/en/emailsAdmin.json
@@ -566,7 +566,7 @@
"accountsTitle": "Accounts, domains & aliases",
"accountsDesc": "Mailboxes (with password hashes), domains, and aliases — the vmail database.",
"messageTitle": "Mailbox message data",
- "messageDesc": "Messages, folders, queue and quarantine. Delivery and IMAP pause while copying.",
+ "messageDesc": "Every stored email (the /var/vmail maildirs). Can be large.",
"keysTitle": "DKIM keys & secrets",
"keysDesc": "DKIM keys + config + mail-state.json. Keeps DKIM valid on restore — but the archive then holds private keys and secrets.",
"keysWarning": "The backup will contain password hashes, DKIM private keys, and plaintext secrets. Keep the destination private.",
diff --git a/apps/dashboard/src/i18n/locales/en/migration.json b/apps/dashboard/src/i18n/locales/en/migration.json
index 6f196bf51..94d3314b4 100644
--- a/apps/dashboard/src/i18n/locales/en/migration.json
+++ b/apps/dashboard/src/i18n/locales/en/migration.json
@@ -1,18 +1,4 @@
{
- "platformDomains": {
- "title": "Domains & DNS",
- "intro": "Importing does not change DNS or move traffic.",
- "customAction": "Update DNS",
- "providerAction": "Replace URL",
- "customHint": "Custom domains are carried into Domains & Routes on the matching service. After checking the imported app, review its DNS records and complete verification.",
- "providerHint": "Provider-owned URLs cannot move to OpenShip. Choose a new address and update application URLs, OAuth callbacks and webhooks that use the old one.",
- "empty": "No public domains were discovered. Keep internal services private; add a domain only if a service needs public access.",
- "next": "Before confirming cutover",
- "test": "Open Domains & Routes to review the imported routes. Add a test domain if needed and check the app and its data.",
- "dns": "Review your custom domains in Domains & Routes, adding any missing domains. Then apply the exact DNS records shown at your DNS provider, or review Auto-configure DNS with a supported connection. Replace the old routing records; keep unrelated records.",
- "verify": "Verify DNS and HTTPS in OpenShip, then test the public URLs before confirming completion.",
- "openDomains": "Review domains & DNS"
- },
"wizard": {
"title": "Migrate apps",
"intro": "Inspect this server's running apps and adopt them into OpenShip. It's read-only — nothing changes on the server until you deploy.",
diff --git a/apps/dashboard/src/i18n/locales/en/projectSettings.json b/apps/dashboard/src/i18n/locales/en/projectSettings.json
index 283ddea15..e5975d43f 100644
--- a/apps/dashboard/src/i18n/locales/en/projectSettings.json
+++ b/apps/dashboard/src/i18n/locales/en/projectSettings.json
@@ -532,7 +532,7 @@
},
"runtime": {
"title": "Runtime configuration",
- "description": "Save configuration here. Changes take effect on the next deployment.",
+ "description": "Read-only. Edit through the deploy wizard so each change ships as a new version.",
"framework": "Framework",
"packageManager": "Package manager",
"runtimeIsolation": "Runtime isolation",
@@ -548,11 +548,7 @@
"modeSandboxed": "Sandboxed (container)",
"modeDirect": "Direct (host process)",
"modeDefault": "Default (resolved at deploy)",
- "modeStatic": "None — served as static files",
- "saved": "Configuration saved. Deploy to apply your changes.",
- "saveFailed": "Could not save configuration. Your changes are still here.",
- "projectSettingsHint": "Shared environment and resource limits are managed in project Settings.",
- "invalidPort": "Enter a port between 1 and 65535."
+ "modeStatic": "None — served as static files"
},
"storage": {
"title": "Persistent storage",
@@ -594,7 +590,7 @@
"env": {
"title": "Project environment",
"sharedTitle": "Shared project environment",
- "description": "Shared defaults for image builds and runtime. Service values take precedence. Secrets stay masked.",
+ "description": "Used during builds and at runtime. Secrets stay masked.",
"edit": "Edit"
}
},
@@ -1388,59 +1384,5 @@
"manual": "No editable literal image was found. Open the source file to update variables, inherited images or custom build logic.",
"working": "Working…",
"failed": "Could not prepare the source update."
- },
- "responseRoutes": {
- "title": "Virtual routes",
- "description": "Return content directly from the edge at a path on this domain.",
- "add": "Add route",
- "edit": "Edit route",
- "staticResponse": "Static response",
- "loading": "Loading routes",
- "loadFailed": "Could not load virtual routes.",
- "retry": "Retry",
- "saveFailed": "Could not save the route.",
- "duplicateHeader": "Each response header name must be unique.",
- "enabled": "Enabled",
- "disabled": "Disabled",
- "enable": "Enable",
- "disable": "Disable",
- "remove": "Remove",
- "removeHint": "Remove this response? Requests will use the remaining domain routes.",
- "cancel": "Cancel",
- "close": "Close",
- "path": "Path",
- "match": "Match",
- "exact": "Exact path",
- "prefix": "Path prefix",
- "exactHint": "Matches only this path. Query parameters are ignored.",
- "prefixHint": "Matches this path and its children. The most specific path wins.",
- "status": "Status code",
- "contentType": "Content type",
- "plainText": "Plain text",
- "custom": "Custom",
- "customContentType": "Custom content type",
- "body": "Response body",
- "bodyPlaceholder": "Enter the content to return…",
- "bodyHint": "Literal content, up to 64 KiB.",
- "headers": "Response headers",
- "addHeader": "Add header",
- "headerName": "Header name",
- "headerValue": "Header value",
- "removeHeader": "Remove header",
- "methods": "Request methods",
- "methodsHint": "Comma-separated methods. Leave empty for all methods. GET includes HEAD.",
- "preview": "Response preview",
- "applyHint": "Applies without redeploying the app.",
- "save": "Save response",
- "saved": "Saved and applied to the edge.",
- "pending": "Saved. Edge application is pending. Update or reconnect the edge, then retry routing.",
- "bytes": "bytes",
- "emptyBodyHint": "This status requires an empty response body.",
- "headersHint": "Add cache, CORS, or other response headers."
- },
- "icon": {
- "label": "Project icon URL",
- "hint": "Use an HTTP or HTTPS image URL. Clear it to use the default icon.",
- "reset": "Use default icon"
}
}
diff --git a/apps/dashboard/src/i18n/locales/en/settings.json b/apps/dashboard/src/i18n/locales/en/settings.json
index ff151942c..77286e291 100644
--- a/apps/dashboard/src/i18n/locales/en/settings.json
+++ b/apps/dashboard/src/i18n/locales/en/settings.json
@@ -1791,21 +1791,5 @@
"title": "Demo mode",
"description": "Blur IP addresses, hosts, and environment values during screen-shares and recordings."
}
- },
- "imageUrl": {
- "preview": "Image preview",
- "invalid": "Enter an HTTP or HTTPS image URL without embedded credentials.",
- "failed": "Could not save the image URL.",
- "save": "Save",
- "saving": "Saving…",
- "saved": "Saved",
- "previewFailed": "Preview unavailable. Check that the URL points directly to an image."
- },
- "profile": {
- "title": "Profile",
- "description": "Your personal account image.",
- "label": "Avatar URL",
- "hint": "Use a direct image URL. Leave empty to use your initial.",
- "reset": "Use initial"
}
}
diff --git a/apps/dashboard/src/i18n/locales/es/auth.json b/apps/dashboard/src/i18n/locales/es/auth.json
index 664897987..fbdb9cc79 100644
--- a/apps/dashboard/src/i18n/locales/es/auth.json
+++ b/apps/dashboard/src/i18n/locales/es/auth.json
@@ -70,8 +70,6 @@
"errorDescription": "Puede que el código sea incorrecto o haya caducado.",
"resendEmail": "Reenviar código",
"signIn": "Iniciar sesión",
- "signupTitle": "Revisa tu correo",
- "signupSentTo": "Hemos enviado el siguiente paso a {email}. Introduce el código abajo si has recibido uno, o sigue las instrucciones para iniciar sesión del correo.",
"pendingTitle": "Verifica tu correo electrónico",
"pendingSentTo": "Enviamos un código de 6 dígitos a {email}. Introdúcelo a continuación para verificar tu correo electrónico.",
"pendingGeneric": "Introduce el código de verificación que te enviamos por correo electrónico.",
diff --git a/apps/dashboard/src/i18n/locales/es/billing.json b/apps/dashboard/src/i18n/locales/es/billing.json
index 7ad95265b..e7630cd40 100644
--- a/apps/dashboard/src/i18n/locales/es/billing.json
+++ b/apps/dashboard/src/i18n/locales/es/billing.json
@@ -668,7 +668,6 @@
"diskGrowth": "Los discos existentes pueden ampliarse. Para reducir el almacenamiento debes mover los datos a un servidor nuevo.",
"range": "De {min} a {max} {unit}",
"monthlyTotal": "Total mensual",
- "yearlyTotal": "Total anual",
"choose": "Elegir Personalizado",
"updating": "Actualizando precio",
"invalid": "Introduce una cantidad válida dentro del rango de cada recurso.",
@@ -680,7 +679,6 @@
"extraMemory": "Memoria adicional",
"extraDisk": "Almacenamiento adicional",
"rates": "Extras mensuales: {cpu}/vCPU, {memory}/GB de RAM, {disk}/GB de almacenamiento. Solo se cobra lo que supere el paquete elegido.",
- "yearlyRates": "Extras anuales: {cpu}/vCPU, {memory}/GB de RAM, {disk}/GB de almacenamiento. Solo se cobran los recursos que superen el paquete seleccionado.",
"applyNotice": "Las ampliaciones se aplican tras el pago. Los cambios a menor precio comienzan al renovar.",
"resizeTitle": "Aplicar los recursos de tu suscripción",
"resizeDescription": "Tu plan ha cambiado. Revisa la nueva capacidad y los proyectos afectados antes de reiniciar este servidor.",
diff --git a/apps/dashboard/src/i18n/locales/es/deployments.json b/apps/dashboard/src/i18n/locales/es/deployments.json
index 894727750..2d367f0c3 100644
--- a/apps/dashboard/src/i18n/locales/es/deployments.json
+++ b/apps/dashboard/src/i18n/locales/es/deployments.json
@@ -202,13 +202,6 @@
"pageOf": "Página {page} de {total}",
"range": "Despliegues {from}–{to} de {total}"
},
- "containerConflict": {
- "title": "Resolver contenedores duplicados",
- "description": "Revisa los contenedores y sus volúmenes montados en el servidor de destino. Conserva el contenedor correcto y sus datos, elimina solo un duplicado que hayas confirmado que no se usa y vuelve a desplegar. Si tienes dudas sobre cuál conservar, contacta con soporte con esta referencia de despliegue.",
- "containers": "Contenedores coincidentes",
- "reviewServer": "Revisar servidor",
- "reference": "Referencia del despliegue"
- },
"resourceGuidance": {
"label": "Orientación sobre recursos del despliegue",
"reviewCapacity": "Revisar capacidad",
diff --git a/apps/dashboard/src/i18n/locales/es/emailsAdmin.json b/apps/dashboard/src/i18n/locales/es/emailsAdmin.json
index 42aced8a3..625b45833 100644
--- a/apps/dashboard/src/i18n/locales/es/emailsAdmin.json
+++ b/apps/dashboard/src/i18n/locales/es/emailsAdmin.json
@@ -519,7 +519,7 @@
"accountsTitle": "Cuentas, dominios y alias",
"accountsDesc": "Buzones (con hashes de contraseñas), dominios y alias: la base de datos vmail.",
"messageTitle": "Datos de los mensajes del buzón",
- "messageDesc": "Mensajes, carpetas, cola y cuarentena. La entrega e IMAP se pausan durante la copia.",
+ "messageDesc": "Cada correo almacenado (los maildirs de /var/vmail). Puede ser grande.",
"keysTitle": "Claves DKIM y secretos",
"keysDesc": "Claves DKIM + configuración + mail-state.json. Mantiene DKIM válido al restaurar, pero el archivo contendrá entonces claves privadas y secretos.",
"keysWarning": "La copia de seguridad contendrá hashes de contraseñas, claves privadas DKIM y secretos en texto plano. Mantén el destino privado.",
diff --git a/apps/dashboard/src/i18n/locales/es/migration.json b/apps/dashboard/src/i18n/locales/es/migration.json
index 708b0dac9..2c0bea482 100644
--- a/apps/dashboard/src/i18n/locales/es/migration.json
+++ b/apps/dashboard/src/i18n/locales/es/migration.json
@@ -1,18 +1,4 @@
{
- "platformDomains": {
- "title": "Dominios y DNS",
- "intro": "La importación no cambia el DNS ni mueve el tráfico.",
- "customAction": "Actualizar DNS",
- "providerAction": "Reemplazar URL",
- "customHint": "Los dominios personalizados se incorporan a Dominios y rutas del servicio correspondiente. Tras comprobar la aplicación importada, revisa sus registros DNS y completa la verificación.",
- "providerHint": "Las URL del proveedor no se pueden trasladar a OpenShip. Elige una dirección nueva y actualiza las URL de la aplicación, los callbacks de OAuth y los webhooks que usen la anterior.",
- "empty": "No se encontraron dominios públicos. Mantén privados los servicios internos; añade un dominio solo si un servicio necesita acceso público.",
- "next": "Antes de confirmar el cambio de tráfico",
- "test": "Abre Dominios y rutas para revisar las rutas importadas. Añade un dominio de prueba si es necesario y comprueba la aplicación y sus datos.",
- "dns": "Revisa tus dominios personalizados en Dominios y rutas y añade los que falten. Después aplica los registros DNS exactos que se muestran en tu proveedor de DNS, o revisa la configuración automática de DNS con una conexión compatible. Reemplaza los registros de enrutamiento anteriores y conserva los demás.",
- "verify": "Verifica DNS y HTTPS en OpenShip y prueba las URL públicas antes de confirmar la finalización.",
- "openDomains": "Revisar dominios y DNS"
- },
"wizard": {
"edgeReview": {
"detected": "{proxy} detectado",
diff --git a/apps/dashboard/src/i18n/locales/es/projectSettings.json b/apps/dashboard/src/i18n/locales/es/projectSettings.json
index fd96834e2..3633c6b45 100644
--- a/apps/dashboard/src/i18n/locales/es/projectSettings.json
+++ b/apps/dashboard/src/i18n/locales/es/projectSettings.json
@@ -482,7 +482,7 @@
},
"runtime": {
"title": "Configuración de tiempo de ejecución",
- "description": "Guarda la configuración aquí. Los cambios se aplicarán en el próximo despliegue.",
+ "description": "Solo lectura. Edítalo mediante el asistente de despliegue para que cada cambio se publique como una nueva versión.",
"framework": "Framework",
"packageManager": "Gestor de paquetes",
"runtimeIsolation": "Aislamiento del tiempo de ejecución",
@@ -498,11 +498,7 @@
"modeSandboxed": "En sandbox (contenedor)",
"modeDirect": "Directo (proceso del host)",
"modeDefault": "Predeterminado (resuelto en el despliegue)",
- "modeStatic": "Ninguno: se sirve como archivos estáticos",
- "saved": "Configuración guardada. Despliega para aplicar los cambios.",
- "saveFailed": "No se pudo guardar la configuración. Tus cambios siguen en el formulario.",
- "projectSettingsHint": "El entorno compartido y los límites de recursos se gestionan en los ajustes del proyecto.",
- "invalidPort": "Introduce un puerto entre 1 y 65535."
+ "modeStatic": "Ninguno: se sirve como archivos estáticos"
},
"storage": {
"title": "Almacenamiento persistente",
@@ -544,7 +540,7 @@
"env": {
"title": "Entorno del proyecto",
"sharedTitle": "Entorno compartido del proyecto",
- "description": "Valores predeterminados compartidos para compilar imágenes y ejecutar servicios. Los valores del servicio tienen prioridad. Los secretos permanecen ocultos.",
+ "description": "Se usa durante la compilación y la ejecución. Los secretos permanecen ocultos.",
"edit": "Editar"
}
},
@@ -1388,59 +1384,5 @@
"manual": "No se encontró una referencia directa editable. Abre el archivo fuente para actualizar variables, imágenes heredadas o lógica de compilación personalizada.",
"working": "Procesando…",
"failed": "No se pudo preparar la actualización del código."
- },
- "responseRoutes": {
- "title": "Rutas virtuales",
- "description": "Devuelve contenido directamente desde el edge en una ruta de este dominio.",
- "add": "Añadir ruta",
- "edit": "Editar ruta",
- "staticResponse": "Respuesta estática",
- "loading": "Cargando rutas",
- "loadFailed": "No se pudieron cargar las rutas virtuales.",
- "retry": "Reintentar",
- "saveFailed": "No se pudo guardar la ruta.",
- "duplicateHeader": "Cada cabecera de respuesta debe tener un nombre único.",
- "enabled": "Activada",
- "disabled": "Desactivada",
- "enable": "Activar",
- "disable": "Desactivar",
- "remove": "Eliminar",
- "removeHint": "¿Eliminar esta respuesta? Las solicitudes usarán las demás rutas del dominio.",
- "cancel": "Cancelar",
- "close": "Cerrar",
- "path": "Ruta",
- "match": "Coincidencia",
- "exact": "Ruta exacta",
- "prefix": "Prefijo de ruta",
- "exactHint": "Solo coincide con esta ruta. Se ignoran los parámetros de consulta.",
- "prefixHint": "Coincide con esta ruta y sus subrutas. Tiene prioridad la ruta más específica.",
- "status": "Código de estado",
- "contentType": "Tipo de contenido",
- "plainText": "Texto sin formato",
- "custom": "Personalizado",
- "customContentType": "Tipo de contenido personalizado",
- "body": "Cuerpo de la respuesta",
- "bodyPlaceholder": "Introduce el contenido que se devolverá…",
- "bodyHint": "Contenido literal, hasta 64 KiB.",
- "headers": "Cabeceras de respuesta",
- "addHeader": "Añadir cabecera",
- "headerName": "Nombre de cabecera",
- "headerValue": "Valor de cabecera",
- "removeHeader": "Eliminar cabecera",
- "methods": "Métodos de solicitud",
- "methodsHint": "Métodos separados por comas. Déjalo vacío para todos los métodos. GET incluye HEAD.",
- "preview": "Vista previa de la respuesta",
- "applyHint": "Se aplica sin volver a desplegar la aplicación.",
- "save": "Guardar respuesta",
- "saved": "Guardado y aplicado en el edge.",
- "pending": "Guardado. Pendiente de aplicar en el edge. Actualiza o reconecta el edge y reintenta el enrutamiento.",
- "bytes": "bytes",
- "emptyBodyHint": "Este estado requiere un cuerpo de respuesta vacío.",
- "headersHint": "Añade cabeceras de caché, CORS u otras."
- },
- "icon": {
- "label": "URL del icono del proyecto",
- "hint": "Usa una URL de imagen HTTP o HTTPS. Bórrala para usar el icono predeterminado.",
- "reset": "Usar icono predeterminado"
}
}
diff --git a/apps/dashboard/src/i18n/locales/es/settings.json b/apps/dashboard/src/i18n/locales/es/settings.json
index 0d2c5871c..3ab15e30e 100644
--- a/apps/dashboard/src/i18n/locales/es/settings.json
+++ b/apps/dashboard/src/i18n/locales/es/settings.json
@@ -1791,21 +1791,5 @@
"confirmCta": "Dejar de servir",
"cancel": "Cancelar",
"noReverseProxy": "No se detectó ningún proxy inverso en esta máquina."
- },
- "imageUrl": {
- "preview": "Vista previa de la imagen",
- "invalid": "Introduce una URL HTTP o HTTPS sin credenciales.",
- "failed": "No se pudo guardar la URL de la imagen.",
- "save": "Guardar",
- "saving": "Guardando…",
- "saved": "Guardado",
- "previewFailed": "Vista previa no disponible. Comprueba que la URL enlace directamente a una imagen."
- },
- "profile": {
- "title": "Perfil",
- "description": "La imagen de tu cuenta personal.",
- "label": "URL del avatar",
- "hint": "Usa una URL directa de imagen. Déjala vacía para mostrar tu inicial.",
- "reset": "Usar inicial"
}
}
diff --git a/apps/dashboard/src/i18n/locales/fr/auth.json b/apps/dashboard/src/i18n/locales/fr/auth.json
index 79ef148e7..d7c1c0c8c 100644
--- a/apps/dashboard/src/i18n/locales/fr/auth.json
+++ b/apps/dashboard/src/i18n/locales/fr/auth.json
@@ -70,8 +70,6 @@
"errorDescription": "Le code est peut-être incorrect ou a expiré.",
"resendEmail": "Renvoyer le code",
"signIn": "Se connecter",
- "signupTitle": "Consultez votre messagerie",
- "signupSentTo": "Nous avons envoyé la prochaine étape à {email}. Saisissez le code ci-dessous si vous en avez reçu un, ou suivez les instructions de connexion dans le message.",
"pendingTitle": "Vérifiez votre e-mail",
"pendingSentTo": "Nous avons envoyé un code à 6 chiffres à {email}. Saisissez-le ci-dessous pour vérifier votre e-mail.",
"pendingGeneric": "Saisissez le code de vérification que nous vous avons envoyé par e-mail.",
diff --git a/apps/dashboard/src/i18n/locales/fr/billing.json b/apps/dashboard/src/i18n/locales/fr/billing.json
index 3f805f9d5..1182f4d4e 100644
--- a/apps/dashboard/src/i18n/locales/fr/billing.json
+++ b/apps/dashboard/src/i18n/locales/fr/billing.json
@@ -668,7 +668,6 @@
"diskGrowth": "Les disques existants peuvent être agrandis. Réduire le stockage nécessite de déplacer vos données vers un nouveau serveur.",
"range": "De {min} à {max} {unit}",
"monthlyTotal": "Total mensuel",
- "yearlyTotal": "Total annuel",
"choose": "Choisir Sur mesure",
"updating": "Actualisation du prix",
"invalid": "Saisissez une valeur valide dans la plage de chaque ressource.",
@@ -680,7 +679,6 @@
"extraMemory": "Mémoire supplémentaire",
"extraDisk": "Stockage supplémentaire",
"rates": "Suppléments mensuels : {cpu}/vCPU, {memory}/Go de RAM, {disk}/Go de stockage. Facturés uniquement au-delà de l’offre choisie.",
- "yearlyRates": "Suppléments annuels : {cpu}/vCPU, {memory}/Go de RAM, {disk}/Go de stockage. Seules les ressources dépassant le forfait choisi sont facturées.",
"applyNotice": "Les augmentations prennent effet après paiement. Les changements moins chers commencent au renouvellement.",
"resizeTitle": "Appliquer les ressources de votre abonnement",
"resizeDescription": "Votre offre a changé. Vérifiez la nouvelle capacité et les projets concernés avant de redémarrer ce serveur.",
diff --git a/apps/dashboard/src/i18n/locales/fr/deployments.json b/apps/dashboard/src/i18n/locales/fr/deployments.json
index ecdbfb85b..8a44f466a 100644
--- a/apps/dashboard/src/i18n/locales/fr/deployments.json
+++ b/apps/dashboard/src/i18n/locales/fr/deployments.json
@@ -202,13 +202,6 @@
"pageOf": "Page {page} sur {total}",
"range": "Déploiements {from}–{to} sur {total}"
},
- "containerConflict": {
- "title": "Résoudre les conteneurs en double",
- "description": "Inspectez les conteneurs et leurs volumes montés sur le serveur cible. Conservez le conteneur prévu et ses données, supprimez uniquement un doublon dont vous avez confirmé qu’il est inutilisé, puis redéployez. En cas de doute, contactez le support avec cette référence de déploiement.",
- "containers": "Conteneurs correspondants",
- "reviewServer": "Examiner le serveur",
- "reference": "Référence du déploiement"
- },
"resourceGuidance": {
"label": "Conseils sur les ressources du déploiement",
"reviewCapacity": "Examiner la capacité",
diff --git a/apps/dashboard/src/i18n/locales/fr/emailsAdmin.json b/apps/dashboard/src/i18n/locales/fr/emailsAdmin.json
index 1ecbb2224..0285a517b 100644
--- a/apps/dashboard/src/i18n/locales/fr/emailsAdmin.json
+++ b/apps/dashboard/src/i18n/locales/fr/emailsAdmin.json
@@ -519,7 +519,7 @@
"accountsTitle": "Comptes, domaines et alias",
"accountsDesc": "Boîtes aux lettres (avec les hachages de mots de passe), domaines et alias — la base de données vmail.",
"messageTitle": "Données des messages des boîtes aux lettres",
- "messageDesc": "Messages, dossiers, file d’attente et quarantaine. La livraison et IMAP sont suspendus pendant la copie.",
+ "messageDesc": "Chaque e-mail stocké (les maildirs /var/vmail). Peut être volumineux.",
"keysTitle": "Clés DKIM et secrets",
"keysDesc": "Clés DKIM + configuration + mail-state.json. Maintient le DKIM valide à la restauration — mais l'archive contient alors des clés privées et des secrets.",
"keysWarning": "La sauvegarde contiendra des hachages de mots de passe, des clés privées DKIM et des secrets en clair. Gardez la destination privée.",
diff --git a/apps/dashboard/src/i18n/locales/fr/migration.json b/apps/dashboard/src/i18n/locales/fr/migration.json
index 384384f2a..eac4ee179 100644
--- a/apps/dashboard/src/i18n/locales/fr/migration.json
+++ b/apps/dashboard/src/i18n/locales/fr/migration.json
@@ -1,18 +1,4 @@
{
- "platformDomains": {
- "title": "Domaines et DNS",
- "intro": "L’importation ne modifie pas le DNS et ne déplace pas le trafic.",
- "customAction": "Mettre à jour le DNS",
- "providerAction": "Remplacer l’URL",
- "customHint": "Les domaines personnalisés sont ajoutés dans Domaines et routes au service correspondant. Après avoir testé l’application importée, vérifiez ses enregistrements DNS et terminez la vérification.",
- "providerHint": "Les URL appartenant au fournisseur ne peuvent pas être transférées vers OpenShip. Choisissez une nouvelle adresse et mettez à jour les URL de l’application, les callbacks OAuth et les webhooks qui utilisent l’ancienne.",
- "empty": "Aucun domaine public n’a été trouvé. Gardez les services internes privés ; ajoutez un domaine uniquement si un service nécessite un accès public.",
- "next": "Avant de confirmer le basculement",
- "test": "Ouvrez Domaines et routes pour vérifier les routes importées. Ajoutez un domaine de test si nécessaire et vérifiez l’application et ses données.",
- "dns": "Vérifiez vos domaines personnalisés dans Domaines et routes et ajoutez ceux qui manquent. Appliquez ensuite les enregistrements DNS exacts affichés chez votre fournisseur DNS, ou vérifiez la configuration DNS automatique avec une connexion compatible. Remplacez les anciens enregistrements de routage et conservez les autres.",
- "verify": "Vérifiez le DNS et HTTPS dans OpenShip, puis testez les URL publiques avant de confirmer la fin de la migration.",
- "openDomains": "Vérifier les domaines et le DNS"
- },
"wizard": {
"edgeReview": {
"detected": "{proxy} détecté",
diff --git a/apps/dashboard/src/i18n/locales/fr/projectSettings.json b/apps/dashboard/src/i18n/locales/fr/projectSettings.json
index af9bb4454..5eaed55f8 100644
--- a/apps/dashboard/src/i18n/locales/fr/projectSettings.json
+++ b/apps/dashboard/src/i18n/locales/fr/projectSettings.json
@@ -482,7 +482,7 @@
},
"runtime": {
"title": "Configuration d'exécution",
- "description": "Enregistrez la configuration ici. Les modifications prendront effet au prochain déploiement.",
+ "description": "Lecture seule. Modifiez via l'assistant de déploiement afin que chaque changement soit livré comme une nouvelle version.",
"framework": "Framework",
"packageManager": "Gestionnaire de paquets",
"runtimeIsolation": "Isolation d'exécution",
@@ -498,11 +498,7 @@
"modeSandboxed": "En bac à sable (conteneur)",
"modeDirect": "Direct (processus hôte)",
"modeDefault": "Par défaut (résolu au déploiement)",
- "modeStatic": "Aucun — servi en fichiers statiques",
- "saved": "Configuration enregistrée. Déployez pour appliquer vos modifications.",
- "saveFailed": "Impossible d’enregistrer la configuration. Vos modifications sont conservées dans le formulaire.",
- "projectSettingsHint": "L’environnement partagé et les limites de ressources se gèrent dans les paramètres du projet.",
- "invalidPort": "Saisissez un port compris entre 1 et 65535."
+ "modeStatic": "Aucun — servi en fichiers statiques"
},
"storage": {
"title": "Stockage persistant",
@@ -544,7 +540,7 @@
"env": {
"title": "Environnement du projet",
"sharedTitle": "Environnement partagé du projet",
- "description": "Valeurs par défaut partagées pour la création des images et l’exécution. Les valeurs du service sont prioritaires. Les secrets restent masqués.",
+ "description": "Utilisé lors de la compilation et de l’exécution. Les secrets restent masqués.",
"edit": "Modifier"
}
},
@@ -1388,59 +1384,5 @@
"manual": "Aucune référence directe modifiable trouvée. Ouvrez le fichier source pour modifier les variables, les images héritées ou la logique de build personnalisée.",
"working": "Traitement…",
"failed": "Impossible de préparer la mise à jour du code."
- },
- "responseRoutes": {
- "title": "Routes virtuelles",
- "description": "Renvoyez du contenu directement depuis l’edge sur un chemin de ce domaine.",
- "add": "Ajouter une route",
- "edit": "Modifier la route",
- "staticResponse": "Réponse statique",
- "loading": "Chargement des routes",
- "loadFailed": "Impossible de charger les routes virtuelles.",
- "retry": "Réessayer",
- "saveFailed": "Impossible d’enregistrer la route.",
- "duplicateHeader": "Chaque en-tête de réponse doit avoir un nom unique.",
- "enabled": "Activée",
- "disabled": "Désactivée",
- "enable": "Activer",
- "disable": "Désactiver",
- "remove": "Supprimer",
- "removeHint": "Supprimer cette réponse ? Les requêtes utiliseront les autres routes du domaine.",
- "cancel": "Annuler",
- "close": "Fermer",
- "path": "Chemin",
- "match": "Correspondance",
- "exact": "Chemin exact",
- "prefix": "Préfixe du chemin",
- "exactHint": "Correspond uniquement à ce chemin. Les paramètres de requête sont ignorés.",
- "prefixHint": "Correspond à ce chemin et à ses sous-chemins. Le chemin le plus précis est prioritaire.",
- "status": "Code de statut",
- "contentType": "Type de contenu",
- "plainText": "Texte brut",
- "custom": "Personnalisé",
- "customContentType": "Type de contenu personnalisé",
- "body": "Corps de la réponse",
- "bodyPlaceholder": "Saisissez le contenu à renvoyer…",
- "bodyHint": "Contenu littéral, jusqu’à 64 Kio.",
- "headers": "En-têtes de réponse",
- "addHeader": "Ajouter un en-tête",
- "headerName": "Nom de l’en-tête",
- "headerValue": "Valeur de l’en-tête",
- "removeHeader": "Supprimer l’en-tête",
- "methods": "Méthodes de requête",
- "methodsHint": "Méthodes séparées par des virgules. Laissez vide pour toutes les méthodes. GET inclut HEAD.",
- "preview": "Aperçu de la réponse",
- "applyHint": "S’applique sans redéployer l’application.",
- "save": "Enregistrer la réponse",
- "saved": "Enregistré et appliqué sur l’edge.",
- "pending": "Enregistré. Application sur l’edge en attente. Mettez à jour ou reconnectez l’edge, puis relancez le routage.",
- "bytes": "octets",
- "emptyBodyHint": "Ce statut nécessite un corps de réponse vide.",
- "headersHint": "Ajoutez des en-têtes de cache, CORS ou autres."
- },
- "icon": {
- "label": "URL de l’icône du projet",
- "hint": "Utilisez une URL d’image HTTP ou HTTPS. Effacez-la pour utiliser l’icône par défaut.",
- "reset": "Utiliser l’icône par défaut"
}
}
diff --git a/apps/dashboard/src/i18n/locales/fr/settings.json b/apps/dashboard/src/i18n/locales/fr/settings.json
index 5614429ab..4a43b3d39 100644
--- a/apps/dashboard/src/i18n/locales/fr/settings.json
+++ b/apps/dashboard/src/i18n/locales/fr/settings.json
@@ -1791,21 +1791,5 @@
"confirmCta": "Cesser de servir",
"cancel": "Annuler",
"noReverseProxy": "Aucun proxy inverse détecté sur cette machine."
- },
- "imageUrl": {
- "preview": "Aperçu de l’image",
- "invalid": "Saisissez une URL HTTP ou HTTPS sans identifiants.",
- "failed": "Impossible d’enregistrer l’URL de l’image.",
- "save": "Enregistrer",
- "saving": "Enregistrement…",
- "saved": "Enregistré",
- "previewFailed": "Aperçu indisponible. Vérifiez que l’URL pointe directement vers une image."
- },
- "profile": {
- "title": "Profil",
- "description": "L’image de votre compte personnel.",
- "label": "URL de l’avatar",
- "hint": "Utilisez une URL directe d’image. Laissez vide pour afficher votre initiale.",
- "reset": "Utiliser l’initiale"
}
}
diff --git a/apps/dashboard/src/i18n/locales/ja/auth.json b/apps/dashboard/src/i18n/locales/ja/auth.json
index 923dda1b1..adee5359f 100644
--- a/apps/dashboard/src/i18n/locales/ja/auth.json
+++ b/apps/dashboard/src/i18n/locales/ja/auth.json
@@ -70,8 +70,6 @@
"errorDescription": "コードが正しくないか、有効期限が切れている可能性があります。",
"resendEmail": "コードを再送信",
"signIn": "サインイン",
- "signupTitle": "メールを確認してください",
- "signupSentTo": "次の手順を {email} に送信しました。コードを受け取った場合は下に入力し、それ以外の場合はメールのログイン手順に従ってください。",
"pendingTitle": "メールアドレスを確認",
"pendingSentTo": "{email} に6桁のコードを送信しました。メールアドレスを確認するには、以下に入力してください。",
"pendingGeneric": "メールでお送りした確認コードを入力してください。",
diff --git a/apps/dashboard/src/i18n/locales/ja/billing.json b/apps/dashboard/src/i18n/locales/ja/billing.json
index 29077300c..831e72314 100644
--- a/apps/dashboard/src/i18n/locales/ja/billing.json
+++ b/apps/dashboard/src/i18n/locales/ja/billing.json
@@ -668,7 +668,6 @@
"diskGrowth": "既存のディスクは拡張できます。縮小するには、データを新しいサーバーに移す必要があります。",
"range": "{min}~{max} {unit}",
"monthlyTotal": "月額合計",
- "yearlyTotal": "年間合計",
"choose": "カスタムを選択",
"updating": "価格を更新中",
"invalid": "各リソースの範囲内で有効な値を入力してください。",
@@ -680,7 +679,6 @@
"extraMemory": "追加メモリ",
"extraDisk": "追加ストレージ",
"rates": "追加リソースの月額料金:{cpu}/vCPU、{memory}/GB RAM、{disk}/GB ストレージ。選択したパッケージを超える分のみ課金されます。",
- "yearlyRates": "年間追加料金:{cpu}/vCPU、{memory}/GB RAM、{disk}/GBストレージ。選択したプランを超えるリソースにのみ課金されます。",
"applyNotice": "アップグレードは支払い後に適用されます。料金が下がる変更は更新時から有効です。",
"resizeTitle": "契約したリソースを適用",
"resizeDescription": "プランが変更されました。新しい容量と影響を受けるプロジェクトを確認してからサーバーを再起動してください。",
diff --git a/apps/dashboard/src/i18n/locales/ja/deployments.json b/apps/dashboard/src/i18n/locales/ja/deployments.json
index d6dfe0db0..b60d86f1b 100644
--- a/apps/dashboard/src/i18n/locales/ja/deployments.json
+++ b/apps/dashboard/src/i18n/locales/ja/deployments.json
@@ -202,13 +202,6 @@
"pageOf": "{page} / {total} ページ",
"range": "全 {total} 件中 {from}–{to} 件"
},
- "containerConflict": {
- "title": "重複するコンテナを確認",
- "description": "対象サーバーでコンテナとマウントを確認してください。使用するコンテナとそのデータを保持し、未使用と確認できた重複コンテナのみを削除してから再デプロイしてください。判断できない場合は、このデプロイ参照番号を添えてサポートにお問い合わせください。",
- "containers": "一致するコンテナ",
- "reviewServer": "サーバーを確認",
- "reference": "デプロイ参照番号"
- },
"resourceGuidance": {
"label": "デプロイのリソースガイド",
"reviewCapacity": "容量を確認",
diff --git a/apps/dashboard/src/i18n/locales/ja/emailsAdmin.json b/apps/dashboard/src/i18n/locales/ja/emailsAdmin.json
index 5dbc1c7ee..f69a4bb6a 100644
--- a/apps/dashboard/src/i18n/locales/ja/emailsAdmin.json
+++ b/apps/dashboard/src/i18n/locales/ja/emailsAdmin.json
@@ -519,7 +519,7 @@
"accountsTitle": "アカウント、ドメイン、エイリアス",
"accountsDesc": "メールボックス (パスワードハッシュを含む)、ドメイン、エイリアス — vmail データベースです。",
"messageTitle": "メールボックスのメッセージデータ",
- "messageDesc": "メール、フォルダー、キュー、隔離データ。コピー中は配信とIMAPが一時停止します。",
+ "messageDesc": "保存されているすべてのメール (/var/vmail の maildir)。サイズが大きくなることがあります。",
"keysTitle": "DKIM 鍵とシークレット",
"keysDesc": "DKIM 鍵 + 設定 + mail-state.json。リストア時に DKIM を有効なまま保ちます - ただしアーカイブには秘密鍵とシークレットが含まれることになります。",
"keysWarning": "バックアップにはパスワードハッシュ、DKIM 秘密鍵、平文のシークレットが含まれます。保存先は非公開に保ってください。",
diff --git a/apps/dashboard/src/i18n/locales/ja/migration.json b/apps/dashboard/src/i18n/locales/ja/migration.json
index 04daf97bd..b84817a25 100644
--- a/apps/dashboard/src/i18n/locales/ja/migration.json
+++ b/apps/dashboard/src/i18n/locales/ja/migration.json
@@ -1,18 +1,4 @@
{
- "platformDomains": {
- "title": "ドメインとDNS",
- "intro": "インポートではDNSの変更やトラフィックの切り替えは行われません。",
- "customAction": "DNSを更新",
- "providerAction": "URLを置き換える",
- "customHint": "カスタムドメインは対応するサービスの「ドメインとルート」に引き継がれます。インポートしたアプリを確認してから、DNSレコードを確認し、検証を完了してください。",
- "providerHint": "プロバイダー所有のURLはOpenShipに移行できません。新しいアドレスを選び、古いアドレスを使うアプリのURL、OAuthコールバック、Webhookを更新してください。",
- "empty": "公開ドメインが見つかりませんでした。内部サービスは非公開のままにし、公開アクセスが必要なサービスにのみドメインを追加してください。",
- "next": "切り替え完了を確定する前に",
- "test": "「ドメインとルート」を開いてインポートされたルートを確認します。必要に応じてテスト用ドメインを追加し、アプリとデータを確認してください。",
- "dns": "「ドメインとルート」でカスタムドメインを確認し、不足しているドメインを追加します。表示されたDNSレコードを正確にDNSプロバイダーに設定するか、対応する接続でDNS自動設定を確認してください。古いルーティングレコードを置き換え、無関係なレコードは残してください。",
- "verify": "OpenShipでDNSとHTTPSを確認し、公開URLをテストしてから完了を確定してください。",
- "openDomains": "ドメインとDNSを確認"
- },
"wizard": {
"edgeReview": {
"detected": "{proxy} を検出",
diff --git a/apps/dashboard/src/i18n/locales/ja/projectSettings.json b/apps/dashboard/src/i18n/locales/ja/projectSettings.json
index 17f63ef7a..0200d06b8 100644
--- a/apps/dashboard/src/i18n/locales/ja/projectSettings.json
+++ b/apps/dashboard/src/i18n/locales/ja/projectSettings.json
@@ -482,7 +482,7 @@
},
"runtime": {
"title": "ランタイム設定",
- "description": "ここで設定を保存します。変更は次回のデプロイ時に反映されます。",
+ "description": "読み取り専用。各変更を新しいバージョンとして反映するため、デプロイウィザードから編集してください。",
"framework": "フレームワーク",
"packageManager": "パッケージマネージャー",
"runtimeIsolation": "ランタイム分離",
@@ -498,11 +498,7 @@
"modeSandboxed": "サンドボックス化(コンテナ)",
"modeDirect": "ダイレクト(ホストプロセス)",
"modeDefault": "デフォルト(デプロイ時に解決)",
- "modeStatic": "なし(静的ファイルとして配信)",
- "saved": "設定を保存しました。変更を適用するにはデプロイしてください。",
- "saveFailed": "設定を保存できませんでした。変更内容はフォームに保持されています。",
- "projectSettingsHint": "共有環境とリソース制限はプロジェクト設定で管理します。",
- "invalidPort": "1〜65535のポート番号を入力してください。"
+ "modeStatic": "なし(静的ファイルとして配信)"
},
"storage": {
"title": "永続ストレージ",
@@ -544,7 +540,7 @@
"env": {
"title": "プロジェクトの環境変数",
"sharedTitle": "プロジェクト共通の環境変数",
- "description": "イメージのビルドと実行時に使用する共通のデフォルト値です。サービスの値が優先されます。シークレットはマスクされたままです。",
+ "description": "ビルド時と実行時に使用します。シークレットは非表示のままです。",
"edit": "編集"
}
},
@@ -1388,59 +1384,5 @@
"manual": "編集可能な直接のイメージ参照がありません。ソースファイルを開き、変数、継承されたイメージ、カスタムビルド処理を更新してください。",
"working": "処理中…",
"failed": "ソース更新を準備できませんでした。"
- },
- "responseRoutes": {
- "title": "仮想ルート",
- "description": "このドメインのパスでエッジから直接コンテンツを返します。",
- "add": "ルートを追加",
- "edit": "ルートを編集",
- "staticResponse": "静的レスポンス",
- "loading": "ルートを読み込み中",
- "loadFailed": "仮想ルートを読み込めませんでした。",
- "retry": "再試行",
- "saveFailed": "ルートを保存できませんでした。",
- "duplicateHeader": "レスポンスヘッダー名は重複できません。",
- "enabled": "有効",
- "disabled": "無効",
- "enable": "有効にする",
- "disable": "無効にする",
- "remove": "削除",
- "removeHint": "このレスポンスを削除しますか?リクエストはドメインの他のルートを使用します。",
- "cancel": "キャンセル",
- "close": "閉じる",
- "path": "パス",
- "match": "一致条件",
- "exact": "完全一致",
- "prefix": "パスの接頭辞",
- "exactHint": "このパスのみに一致します。クエリパラメータは無視されます。",
- "prefixHint": "このパスと子パスに一致します。最も具体的なパスが優先されます。",
- "status": "ステータスコード",
- "contentType": "コンテンツタイプ",
- "plainText": "プレーンテキスト",
- "custom": "カスタム",
- "customContentType": "カスタムコンテンツタイプ",
- "body": "レスポンス本文",
- "bodyPlaceholder": "返すコンテンツを入力…",
- "bodyHint": "入力内容をそのまま返します。最大64 KiB。",
- "headers": "レスポンスヘッダー",
- "addHeader": "ヘッダーを追加",
- "headerName": "ヘッダー名",
- "headerValue": "ヘッダー値",
- "removeHeader": "ヘッダーを削除",
- "methods": "リクエストメソッド",
- "methodsHint": "カンマ区切りで指定します。空欄はすべてのメソッドに一致します。GETにはHEADも含まれます。",
- "preview": "レスポンスのプレビュー",
- "applyHint": "アプリの再デプロイなしで適用されます。",
- "save": "レスポンスを保存",
- "saved": "保存し、エッジに適用しました。",
- "pending": "保存しました。エッジへの適用は保留中です。エッジを更新または再接続して、ルーティングを再試行してください。",
- "bytes": "バイト",
- "emptyBodyHint": "このステータスではレスポンス本文を空にする必要があります。",
- "headersHint": "キャッシュ、CORSなどのレスポンスヘッダーを追加します。"
- },
- "icon": {
- "label": "プロジェクトアイコンの URL",
- "hint": "HTTP または HTTPS の画像 URL を指定してください。空にすると既定のアイコンに戻ります。",
- "reset": "既定のアイコンを使用"
}
}
diff --git a/apps/dashboard/src/i18n/locales/ja/settings.json b/apps/dashboard/src/i18n/locales/ja/settings.json
index db135bb68..9394731c4 100644
--- a/apps/dashboard/src/i18n/locales/ja/settings.json
+++ b/apps/dashboard/src/i18n/locales/ja/settings.json
@@ -1791,21 +1791,5 @@
"confirmCta": "配信を停止",
"cancel": "キャンセル",
"noReverseProxy": "このマシンでリバースプロキシが検出されませんでした。"
- },
- "imageUrl": {
- "preview": "画像プレビュー",
- "invalid": "認証情報を含まない HTTP または HTTPS の画像 URL を入力してください。",
- "failed": "画像 URL を保存できませんでした。",
- "save": "保存",
- "saving": "保存中…",
- "saved": "保存しました",
- "previewFailed": "プレビューを表示できません。画像の直接 URL か確認してください。"
- },
- "profile": {
- "title": "プロフィール",
- "description": "個人アカウントの画像。",
- "label": "アバター URL",
- "hint": "画像の直接 URL を使用します。空欄にすると名前の頭文字を表示します。",
- "reset": "頭文字を使用"
}
}
diff --git a/apps/dashboard/src/i18n/locales/pt/auth.json b/apps/dashboard/src/i18n/locales/pt/auth.json
index ec7e52fe1..733f24529 100644
--- a/apps/dashboard/src/i18n/locales/pt/auth.json
+++ b/apps/dashboard/src/i18n/locales/pt/auth.json
@@ -70,8 +70,6 @@
"errorDescription": "O código pode estar incorreto ou expirado.",
"resendEmail": "Reenviar código",
"signIn": "Entrar",
- "signupTitle": "Verifique seu e-mail",
- "signupSentTo": "Enviamos o próximo passo para {email}. Insira o código abaixo se recebeu um, ou siga as instruções de acesso no e-mail.",
"pendingTitle": "Verifique seu email",
"pendingSentTo": "Enviamos um código de 6 dígitos para {email}. Digite-o abaixo para verificar seu email.",
"pendingGeneric": "Digite o código de verificação que enviamos por email.",
diff --git a/apps/dashboard/src/i18n/locales/pt/billing.json b/apps/dashboard/src/i18n/locales/pt/billing.json
index bd995162d..58430128f 100644
--- a/apps/dashboard/src/i18n/locales/pt/billing.json
+++ b/apps/dashboard/src/i18n/locales/pt/billing.json
@@ -668,7 +668,6 @@
"diskGrowth": "Os discos existentes podem ser ampliados. Para reduzir o armazenamento, é necessário mover os dados para um novo servidor.",
"range": "De {min} a {max} {unit}",
"monthlyTotal": "Total mensal",
- "yearlyTotal": "Total anual",
"choose": "Escolher Personalizado",
"updating": "Atualizando preço",
"invalid": "Insira um valor válido dentro do intervalo de cada recurso.",
@@ -680,7 +679,6 @@
"extraMemory": "Memória adicional",
"extraDisk": "Armazenamento adicional",
"rates": "Extras mensais: {cpu}/vCPU, {memory}/GB de RAM, {disk}/GB de armazenamento. Cobrança somente acima do pacote escolhido.",
- "yearlyRates": "Extras anuais: {cpu}/vCPU, {memory}/GB de RAM, {disk}/GB de armazenamento. Cobrados apenas pelos recursos que excedem o pacote selecionado.",
"applyNotice": "As ampliações são aplicadas após o pagamento. Alterações de menor custo começam na renovação.",
"resizeTitle": "Aplicar os recursos da assinatura",
"resizeDescription": "Seu plano mudou. Revise a nova capacidade e os projetos afetados antes de reiniciar este servidor.",
diff --git a/apps/dashboard/src/i18n/locales/pt/deployments.json b/apps/dashboard/src/i18n/locales/pt/deployments.json
index 9f9fc3858..5b6e0dd7c 100644
--- a/apps/dashboard/src/i18n/locales/pt/deployments.json
+++ b/apps/dashboard/src/i18n/locales/pt/deployments.json
@@ -202,13 +202,6 @@
"pageOf": "Página {page} de {total}",
"range": "Implantações {from}–{to} de {total}"
},
- "containerConflict": {
- "title": "Resolver contêineres duplicados",
- "description": "Inspecione os contêineres e seus volumes montados no servidor de destino. Mantenha o contêiner correto e seus dados, remova apenas uma duplicata confirmada como não utilizada e implante novamente. Em caso de dúvida sobre qual manter, contate o suporte com esta referência da implantação.",
- "containers": "Contêineres correspondentes",
- "reviewServer": "Revisar servidor",
- "reference": "Referência da implantação"
- },
"resourceGuidance": {
"label": "Orientações sobre recursos da implantação",
"reviewCapacity": "Revisar capacidade",
diff --git a/apps/dashboard/src/i18n/locales/pt/emailsAdmin.json b/apps/dashboard/src/i18n/locales/pt/emailsAdmin.json
index d4a4f5ff1..c854d778a 100644
--- a/apps/dashboard/src/i18n/locales/pt/emailsAdmin.json
+++ b/apps/dashboard/src/i18n/locales/pt/emailsAdmin.json
@@ -519,7 +519,7 @@
"accountsTitle": "Contas, domínios e aliases",
"accountsDesc": "Caixas de correio (com hashes de senha), domínios e aliases — o banco de dados vmail.",
"messageTitle": "Dados de mensagens das caixas de correio",
- "messageDesc": "Mensagens, pastas, fila e quarentena. A entrega e o IMAP ficam pausados durante a cópia.",
+ "messageDesc": "Cada e-mail armazenado (os maildirs em /var/vmail). Pode ser grande.",
"keysTitle": "Chaves DKIM e segredos",
"keysDesc": "Chaves DKIM + config + mail-state.json. Mantém o DKIM válido na restauração — mas o arquivo então contém chaves privadas e segredos.",
"keysWarning": "O backup conterá hashes de senha, chaves privadas DKIM e segredos em texto puro. Mantenha o destino privado.",
diff --git a/apps/dashboard/src/i18n/locales/pt/migration.json b/apps/dashboard/src/i18n/locales/pt/migration.json
index 7fd764efd..426716b09 100644
--- a/apps/dashboard/src/i18n/locales/pt/migration.json
+++ b/apps/dashboard/src/i18n/locales/pt/migration.json
@@ -1,18 +1,4 @@
{
- "platformDomains": {
- "title": "Domínios e DNS",
- "intro": "A importação não altera o DNS nem transfere o tráfego.",
- "customAction": "Atualizar DNS",
- "providerAction": "Substituir URL",
- "customHint": "Os domínios personalizados são incluídos em Domínios e rotas no serviço correspondente. Depois de verificar a aplicação importada, revise os registros DNS e conclua a verificação.",
- "providerHint": "As URLs do provedor não podem ser transferidas para o OpenShip. Escolha um novo endereço e atualize as URLs da aplicação, os callbacks OAuth e os webhooks que usam o endereço antigo.",
- "empty": "Nenhum domínio público foi encontrado. Mantenha os serviços internos privados; adicione um domínio apenas se um serviço precisar de acesso público.",
- "next": "Antes de confirmar a mudança de tráfego",
- "test": "Abra Domínios e rotas para revisar as rotas importadas. Adicione um domínio de teste se necessário e verifique a aplicação e os seus dados.",
- "dns": "Revise os seus domínios personalizados em Domínios e rotas e adicione os que faltam. Depois aplique os registros DNS exatos exibidos no seu provedor de DNS, ou revise a configuração automática de DNS com uma conexão compatível. Substitua os registros de roteamento antigos e mantenha os demais.",
- "verify": "Verifique DNS e HTTPS no OpenShip e teste as URLs públicas antes de confirmar a conclusão.",
- "openDomains": "Revisar domínios e DNS"
- },
"wizard": {
"edgeReview": {
"detected": "{proxy} detectado",
diff --git a/apps/dashboard/src/i18n/locales/pt/projectSettings.json b/apps/dashboard/src/i18n/locales/pt/projectSettings.json
index a3ca74b0a..aabb2ac19 100644
--- a/apps/dashboard/src/i18n/locales/pt/projectSettings.json
+++ b/apps/dashboard/src/i18n/locales/pt/projectSettings.json
@@ -482,7 +482,7 @@
},
"runtime": {
"title": "Configuração de runtime",
- "description": "Salve a configuração aqui. As alterações entram em vigor na próxima implantação.",
+ "description": "Apenas leitura. Edite através do assistente de implementação para que cada alteração seja publicada como uma nova versão.",
"framework": "Framework",
"packageManager": "Gestor de pacotes",
"runtimeIsolation": "Isolamento de runtime",
@@ -498,11 +498,7 @@
"modeSandboxed": "Isolado (contentor)",
"modeDirect": "Direto (processo do anfitrião)",
"modeDefault": "Predefinido (resolvido na implementação)",
- "modeStatic": "Nenhum — servido como ficheiros estáticos",
- "saved": "Configuração salva. Implante para aplicar as alterações.",
- "saveFailed": "Não foi possível salvar a configuração. Suas alterações continuam no formulário.",
- "projectSettingsHint": "O ambiente compartilhado e os limites de recursos são gerenciados nas configurações do projeto.",
- "invalidPort": "Informe uma porta entre 1 e 65535."
+ "modeStatic": "Nenhum — servido como ficheiros estáticos"
},
"storage": {
"title": "Armazenamento persistente",
@@ -544,7 +540,7 @@
"env": {
"title": "Ambiente do projeto",
"sharedTitle": "Ambiente compartilhado do projeto",
- "description": "Valores padrão compartilhados para criar imagens e executar serviços. Os valores do serviço têm prioridade. Os segredos permanecem ocultos.",
+ "description": "Usado durante a compilação e a execução. Os segredos permanecem ocultos.",
"edit": "Editar"
}
},
@@ -1388,59 +1384,5 @@
"manual": "Nenhuma referência direta editável encontrada. Abra o arquivo de origem para atualizar variáveis, imagens herdadas ou lógica de build personalizada.",
"working": "Processando…",
"failed": "Não foi possível preparar a atualização do código."
- },
- "responseRoutes": {
- "title": "Rotas virtuais",
- "description": "Retorne conteúdo diretamente do edge em um caminho deste domínio.",
- "add": "Adicionar rota",
- "edit": "Editar rota",
- "staticResponse": "Resposta estática",
- "loading": "Carregando rotas",
- "loadFailed": "Não foi possível carregar as rotas virtuais.",
- "retry": "Tentar novamente",
- "saveFailed": "Não foi possível salvar a rota.",
- "duplicateHeader": "Cada cabeçalho de resposta deve ter um nome único.",
- "enabled": "Ativada",
- "disabled": "Desativada",
- "enable": "Ativar",
- "disable": "Desativar",
- "remove": "Remover",
- "removeHint": "Remover esta resposta? As solicitações usarão as demais rotas do domínio.",
- "cancel": "Cancelar",
- "close": "Fechar",
- "path": "Caminho",
- "match": "Correspondência",
- "exact": "Caminho exato",
- "prefix": "Prefixo do caminho",
- "exactHint": "Corresponde apenas a este caminho. Os parâmetros de consulta são ignorados.",
- "prefixHint": "Corresponde a este caminho e seus subcaminhos. O caminho mais específico tem prioridade.",
- "status": "Código de status",
- "contentType": "Tipo de conteúdo",
- "plainText": "Texto simples",
- "custom": "Personalizado",
- "customContentType": "Tipo de conteúdo personalizado",
- "body": "Corpo da resposta",
- "bodyPlaceholder": "Digite o conteúdo que será retornado…",
- "bodyHint": "Conteúdo literal, até 64 KiB.",
- "headers": "Cabeçalhos da resposta",
- "addHeader": "Adicionar cabeçalho",
- "headerName": "Nome do cabeçalho",
- "headerValue": "Valor do cabeçalho",
- "removeHeader": "Remover cabeçalho",
- "methods": "Métodos de solicitação",
- "methodsHint": "Métodos separados por vírgulas. Deixe vazio para todos os métodos. GET inclui HEAD.",
- "preview": "Prévia da resposta",
- "applyHint": "Aplica sem reimplantar o aplicativo.",
- "save": "Salvar resposta",
- "saved": "Salvo e aplicado no edge.",
- "pending": "Salvo. Aplicação no edge pendente. Atualize ou reconecte o edge e tente o roteamento novamente.",
- "bytes": "bytes",
- "emptyBodyHint": "Este estado exige um corpo de resposta vazio.",
- "headersHint": "Adicione cabeçalhos de cache, CORS ou outros."
- },
- "icon": {
- "label": "URL do ícone do projeto",
- "hint": "Use uma URL de imagem HTTP ou HTTPS. Limpe-a para usar o ícone padrão.",
- "reset": "Usar ícone padrão"
}
}
diff --git a/apps/dashboard/src/i18n/locales/pt/settings.json b/apps/dashboard/src/i18n/locales/pt/settings.json
index 883f9ab06..3fa1a6087 100644
--- a/apps/dashboard/src/i18n/locales/pt/settings.json
+++ b/apps/dashboard/src/i18n/locales/pt/settings.json
@@ -1791,21 +1791,5 @@
"confirmCta": "Parar de servir",
"cancel": "Cancelar",
"noReverseProxy": "Nenhum proxy reverso detectado nesta máquina."
- },
- "imageUrl": {
- "preview": "Prévia da imagem",
- "invalid": "Insira uma URL HTTP ou HTTPS sem credenciais.",
- "failed": "Não foi possível salvar a URL da imagem.",
- "save": "Salvar",
- "saving": "Salvando…",
- "saved": "Salvo",
- "previewFailed": "Prévia indisponível. Verifique se a URL aponta diretamente para uma imagem."
- },
- "profile": {
- "title": "Perfil",
- "description": "A imagem da sua conta pessoal.",
- "label": "URL do avatar",
- "hint": "Use uma URL direta de imagem. Deixe em branco para usar sua inicial.",
- "reset": "Usar inicial"
}
}
diff --git a/apps/dashboard/src/i18n/locales/ru/auth.json b/apps/dashboard/src/i18n/locales/ru/auth.json
index ebc8bd0b0..d823d4c10 100644
--- a/apps/dashboard/src/i18n/locales/ru/auth.json
+++ b/apps/dashboard/src/i18n/locales/ru/auth.json
@@ -70,8 +70,6 @@
"errorDescription": "Код неверен или срок его действия истёк.",
"resendEmail": "Отправить код повторно",
"signIn": "Войти",
- "signupTitle": "Проверьте почту",
- "signupSentTo": "Мы отправили дальнейшие инструкции на {email}. Если вы получили код, введите его ниже. В противном случае следуйте инструкциям для входа в письме.",
"pendingTitle": "Подтвердите вашу эл. почту",
"pendingSentTo": "Мы отправили 6-значный код на {email}. Введите его ниже для подтверждения эл. почты.",
"pendingGeneric": "Введите код подтверждения, отправленный вам по эл. почте.",
diff --git a/apps/dashboard/src/i18n/locales/ru/billing.json b/apps/dashboard/src/i18n/locales/ru/billing.json
index 45ffb8ac8..3114d95de 100644
--- a/apps/dashboard/src/i18n/locales/ru/billing.json
+++ b/apps/dashboard/src/i18n/locales/ru/billing.json
@@ -546,7 +546,6 @@
"diskGrowth": "Диски можно расширять. Уменьшение дискового пространства требует переноса данных на новый сервер.",
"range": "От {min} до {max} {unit}",
"monthlyTotal": "Итого в месяц",
- "yearlyTotal": "Итого за год",
"choose": "Выбрать индивидуальный",
"updating": "Обновление цены",
"invalid": "Укажите допустимое значение в пределах диапазона для каждого ресурса.",
@@ -558,7 +557,6 @@
"extraMemory": "Дополнительная память",
"extraDisk": "Дополнительное хранилище",
"rates": "Дополнительно в месяц: {cpu}/vCPU, {memory}/ГБ ОЗУ, {disk}/ГБ хранилища. Оплачивается только сверх выбранного пакета.",
- "yearlyRates": "Дополнительные ресурсы за год: {cpu}/vCPU, {memory}/ГБ ОЗУ, {disk}/ГБ хранилища. Оплачиваются только ресурсы сверх выбранного пакета.",
"applyNotice": "Повышение тарифа применяется сразу после оплаты. Переход на более дешёвый — со следующего продления.",
"resizeTitle": "Применить ресурсы из подписки",
"resizeDescription": "Ваш тариф изменился. Проверьте новые мощности и затронутые проекты перед перезапуском сервера.",
diff --git a/apps/dashboard/src/i18n/locales/ru/deployments.json b/apps/dashboard/src/i18n/locales/ru/deployments.json
index fd49ec67d..de87897c9 100644
--- a/apps/dashboard/src/i18n/locales/ru/deployments.json
+++ b/apps/dashboard/src/i18n/locales/ru/deployments.json
@@ -202,13 +202,6 @@
"confirm": "Откатить",
"cancel": "Отмена"
},
- "containerConflict": {
- "title": "Устраните дублирование контейнеров",
- "description": "Проверьте контейнеры и их подключённые тома на целевом сервере. Сохраните нужный контейнер и его данные, удалите только подтверждённый неиспользуемый дубликат, затем повторите развёртывание. Если вы не уверены, какой контейнер сохранить, обратитесь в поддержку с этим идентификатором развёртывания.",
- "containers": "Совпадающие контейнеры",
- "reviewServer": "Проверить сервер",
- "reference": "Идентификатор развёртывания"
- },
"resourceGuidance": {
"label": "Рекомендации по ресурсам развёртывания",
"reviewCapacity": "Проверить ресурсы",
diff --git a/apps/dashboard/src/i18n/locales/ru/emailsAdmin.json b/apps/dashboard/src/i18n/locales/ru/emailsAdmin.json
index 201136211..21683ef82 100644
--- a/apps/dashboard/src/i18n/locales/ru/emailsAdmin.json
+++ b/apps/dashboard/src/i18n/locales/ru/emailsAdmin.json
@@ -566,7 +566,7 @@
"accountsTitle": "Аккаунты, домены и алиасы",
"accountsDesc": "Почтовые ящики (с хешами паролей), домены и алиасы — база данных vmail.",
"messageTitle": "Сообщения почтовых ящиков",
- "messageDesc": "Письма, папки, очередь и карантин. Доставка и IMAP приостанавливаются на время копирования.",
+ "messageDesc": "Все сохранённые письма (директории /var/vmail). Может занимать много места.",
"keysTitle": "Ключи DKIM и секреты",
"keysDesc": "Ключи DKIM + конфигурация + mail-state.json. Сохраняет валидность DKIM при восстановлении, но архив будет содержать приватные ключи и секреты.",
"keysWarning": "Резервная копия будет содержать хеши паролей, закрытые ключи DKIM и секреты в открытом виде. Хранилище должно быть защищено.",
diff --git a/apps/dashboard/src/i18n/locales/ru/migration.json b/apps/dashboard/src/i18n/locales/ru/migration.json
index c1b25602f..8c3a905d6 100644
--- a/apps/dashboard/src/i18n/locales/ru/migration.json
+++ b/apps/dashboard/src/i18n/locales/ru/migration.json
@@ -1,18 +1,4 @@
{
- "platformDomains": {
- "title": "Домены и DNS",
- "intro": "Импорт не меняет DNS и не переключает трафик.",
- "customAction": "Обновить DNS",
- "providerAction": "Заменить URL",
- "customHint": "Собственные домены переносятся в раздел «Домены и маршруты» соответствующего сервиса. Проверьте импортированное приложение, затем просмотрите записи DNS и завершите проверку.",
- "providerHint": "URL, принадлежащие провайдеру, нельзя перенести в OpenShip. Выберите новый адрес и обновите URL приложения, адреса обратного вызова OAuth и вебхуки, использующие старый адрес.",
- "empty": "Публичные домены не найдены. Оставьте внутренние сервисы закрытыми; добавляйте домен только для сервисов, которым нужен публичный доступ.",
- "next": "Перед подтверждением переключения",
- "test": "Откройте «Домены и маршруты» и проверьте импортированные маршруты. При необходимости добавьте тестовый домен и проверьте приложение и его данные.",
- "dns": "Проверьте собственные домены в разделе «Домены и маршруты» и добавьте недостающие. Затем внесите показанные записи DNS без изменений у своего DNS-провайдера либо проверьте автоматическую настройку DNS через поддерживаемое подключение. Замените старые записи маршрутизации, сохранив остальные.",
- "verify": "Проверьте DNS и HTTPS в OpenShip, затем протестируйте публичные URL перед подтверждением завершения.",
- "openDomains": "Проверить домены и DNS"
- },
"wizard": {
"title": "Миграция приложений",
"intro": "Просканируйте работающие приложения на этом сервере и перенесите их в OpenShip. Это режим только для чтения — на сервере ничего не меняется до деплоя.",
diff --git a/apps/dashboard/src/i18n/locales/ru/projectSettings.json b/apps/dashboard/src/i18n/locales/ru/projectSettings.json
index 444152582..c5474717c 100644
--- a/apps/dashboard/src/i18n/locales/ru/projectSettings.json
+++ b/apps/dashboard/src/i18n/locales/ru/projectSettings.json
@@ -532,7 +532,7 @@
},
"runtime": {
"title": "Конфигурация среды выполнения",
- "description": "Сохраните настройки здесь. Изменения вступят в силу при следующем развёртывании.",
+ "description": "Только чтение. Редактируйте через мастер деплоя, чтобы каждое изменение поставлялось как новая версия.",
"framework": "Фреймворк",
"packageManager": "Менеджер пакетов",
"runtimeIsolation": "Изоляция среды",
@@ -548,11 +548,7 @@
"modeSandboxed": "В песочнице (контейнер)",
"modeDirect": "Прямой (процесс хоста)",
"modeDefault": "По умолчанию (определяется при деплое)",
- "modeStatic": "Нет — отдается как статические файлы",
- "saved": "Настройки сохранены. Выполните развёртывание, чтобы применить изменения.",
- "saveFailed": "Не удалось сохранить настройки. Ваши изменения остались в форме.",
- "projectSettingsHint": "Общая среда и ограничения ресурсов управляются в настройках проекта.",
- "invalidPort": "Введите номер порта от 1 до 65535."
+ "modeStatic": "Нет — отдается как статические файлы"
},
"storage": {
"title": "Постоянное хранилище",
@@ -594,7 +590,7 @@
"env": {
"title": "Окружение проекта",
"sharedTitle": "Общее окружение проекта",
- "description": "Общие значения по умолчанию для сборки образов и выполнения. Значения сервиса имеют приоритет. Секреты остаются скрытыми.",
+ "description": "Используется при сборке и выполнении. Секреты остаются скрытыми.",
"edit": "Редактировать"
}
},
@@ -1388,59 +1384,5 @@
"manual": "Редактируемая прямая ссылка на образ не найдена. Откройте исходный файл, чтобы изменить переменные, унаследованные образы или собственную логику сборки.",
"working": "Обработка…",
"failed": "Не удалось подготовить обновление исходного кода."
- },
- "responseRoutes": {
- "title": "Виртуальные маршруты",
- "description": "Возвращайте содержимое напрямую с edge по пути на этом домене.",
- "add": "Добавить маршрут",
- "edit": "Изменить маршрут",
- "staticResponse": "Статический ответ",
- "loading": "Загрузка маршрутов",
- "loadFailed": "Не удалось загрузить виртуальные маршруты.",
- "retry": "Повторить",
- "saveFailed": "Не удалось сохранить маршрут.",
- "duplicateHeader": "Имя каждого заголовка ответа должно быть уникальным.",
- "enabled": "Включён",
- "disabled": "Выключен",
- "enable": "Включить",
- "disable": "Выключить",
- "remove": "Удалить",
- "removeHint": "Удалить этот ответ? Запросы будут использовать оставшиеся маршруты домена.",
- "cancel": "Отмена",
- "close": "Закрыть",
- "path": "Путь",
- "match": "Совпадение",
- "exact": "Точный путь",
- "prefix": "Префикс пути",
- "exactHint": "Совпадает только с этим путём. Параметры запроса игнорируются.",
- "prefixHint": "Совпадает с этим путём и вложенными путями. Приоритет у самого конкретного пути.",
- "status": "Код состояния",
- "contentType": "Тип содержимого",
- "plainText": "Обычный текст",
- "custom": "Другой",
- "customContentType": "Свой тип содержимого",
- "body": "Тело ответа",
- "bodyPlaceholder": "Введите содержимое ответа…",
- "bodyHint": "Содержимое без обработки, до 64 КиБ.",
- "headers": "Заголовки ответа",
- "addHeader": "Добавить заголовок",
- "headerName": "Имя заголовка",
- "headerValue": "Значение заголовка",
- "removeHeader": "Удалить заголовок",
- "methods": "Методы запроса",
- "methodsHint": "Методы через запятую. Пустое поле означает все методы. GET включает HEAD.",
- "preview": "Предпросмотр ответа",
- "applyHint": "Применяется без повторного развёртывания приложения.",
- "save": "Сохранить ответ",
- "saved": "Сохранено и применено на edge.",
- "pending": "Сохранено. Применение на edge ожидает выполнения. Обновите или подключите edge и повторите маршрутизацию.",
- "bytes": "байт",
- "emptyBodyHint": "Этот статус требует пустого тела ответа.",
- "headersHint": "Добавьте заголовки кеширования, CORS или другие."
- },
- "icon": {
- "label": "URL значка проекта",
- "hint": "Укажите HTTP- или HTTPS-ссылку на изображение. Очистите её, чтобы использовать значок по умолчанию.",
- "reset": "Стандартный значок"
}
}
diff --git a/apps/dashboard/src/i18n/locales/ru/settings.json b/apps/dashboard/src/i18n/locales/ru/settings.json
index 1ee579392..59cb29a08 100644
--- a/apps/dashboard/src/i18n/locales/ru/settings.json
+++ b/apps/dashboard/src/i18n/locales/ru/settings.json
@@ -1791,21 +1791,5 @@
"title": "Демо-режим",
"description": "Размывать IP-адреса, хосты и переменные окружения при показе экрана и записи видео."
}
- },
- "imageUrl": {
- "preview": "Предпросмотр изображения",
- "invalid": "Введите HTTP- или HTTPS-адрес изображения без учётных данных.",
- "failed": "Не удалось сохранить адрес изображения.",
- "save": "Сохранить",
- "saving": "Сохранение…",
- "saved": "Сохранено",
- "previewFailed": "Предпросмотр недоступен. Проверьте, что URL ведёт прямо к изображению."
- },
- "profile": {
- "title": "Профиль",
- "description": "Изображение вашего личного аккаунта.",
- "label": "URL аватара",
- "hint": "Укажите прямую ссылку на изображение. Оставьте поле пустым, чтобы показать инициал.",
- "reset": "Использовать инициал"
}
}
diff --git a/apps/dashboard/src/i18n/locales/tr/auth.json b/apps/dashboard/src/i18n/locales/tr/auth.json
index 299fd24a7..d99c7b079 100644
--- a/apps/dashboard/src/i18n/locales/tr/auth.json
+++ b/apps/dashboard/src/i18n/locales/tr/auth.json
@@ -70,8 +70,6 @@
"errorDescription": "Kod hatalı veya süresi dolmuş olabilir.",
"resendEmail": "Kodu tekrar gönder",
"signIn": "Giriş yap",
- "signupTitle": "E-postanızı kontrol edin",
- "signupSentTo": "Sonraki adımı {email} adresine gönderdik. Bir kod aldıysanız aşağıya girin veya e-postadaki giriş talimatlarını izleyin.",
"pendingTitle": "E-postanızı doğrulayın",
"pendingSentTo": "{email} adresine 6 haneli bir kod gönderdik. E-postanızı doğrulamak için aşağıya girin.",
"pendingGeneric": "Size e-posta ile gönderdiğimiz doğrulama kodunu girin.",
diff --git a/apps/dashboard/src/i18n/locales/tr/billing.json b/apps/dashboard/src/i18n/locales/tr/billing.json
index 5b4f6a8fe..bd2710220 100644
--- a/apps/dashboard/src/i18n/locales/tr/billing.json
+++ b/apps/dashboard/src/i18n/locales/tr/billing.json
@@ -668,7 +668,6 @@
"diskGrowth": "Mevcut diskler büyütülebilir. Depolamayı küçültmek için verilerini yeni bir sunucuya taşıman gerekir.",
"range": "{min} ile {max} {unit}",
"monthlyTotal": "Aylık toplam",
- "yearlyTotal": "Yıllık toplam",
"choose": "Özel planı seç",
"updating": "Fiyat güncelleniyor",
"invalid": "Her kaynak için belirtilen aralıkta geçerli bir miktar gir.",
@@ -680,7 +679,6 @@
"extraMemory": "Ek bellek",
"extraDisk": "Ek depolama",
"rates": "Aylık ek kaynaklar: {cpu}/vCPU, {memory}/GB RAM, {disk}/GB depolama. Yalnızca seçilen paketin üzerindeki kaynaklar ücretlendirilir.",
- "yearlyRates": "Yıllık ek kaynaklar: {cpu}/vCPU, {memory}/GB RAM, {disk}/GB depolama. Yalnızca seçilen paketi aşan kaynaklar ücretlendirilir.",
"applyNotice": "Yükseltmeler ödemeden sonra uygulanır. Daha düşük ücretli değişiklikler yenilemede başlar.",
"resizeTitle": "Aboneliğindeki kaynakları uygula",
"resizeDescription": "Planın değişti. Bu sunucuyu yeniden başlatmadan önce yeni kapasiteyi ve etkilenen projeleri incele.",
diff --git a/apps/dashboard/src/i18n/locales/tr/deployments.json b/apps/dashboard/src/i18n/locales/tr/deployments.json
index 484a9dce8..a079add8b 100644
--- a/apps/dashboard/src/i18n/locales/tr/deployments.json
+++ b/apps/dashboard/src/i18n/locales/tr/deployments.json
@@ -202,13 +202,6 @@
"pageOf": "Sayfa {page} / {total}",
"range": "{total} dağıtımdan {from}–{to}"
},
- "containerConflict": {
- "title": "Yinelenen kapsayıcıları çözün",
- "description": "Hedef sunucudaki kapsayıcıları ve bağlı birimlerini inceleyin. Kullanılacak kapsayıcıyı ve verilerini koruyun, yalnızca kullanılmadığını doğruladığınız kopyayı kaldırın ve yeniden dağıtın. Hangisini koruyacağınızdan emin değilseniz bu dağıtım referansıyla destek ekibine ulaşın.",
- "containers": "Eşleşen kapsayıcılar",
- "reviewServer": "Sunucuyu incele",
- "reference": "Dağıtım referansı"
- },
"resourceGuidance": {
"label": "Dağıtım kaynak rehberi",
"reviewCapacity": "Kapasiteyi incele",
diff --git a/apps/dashboard/src/i18n/locales/tr/emailsAdmin.json b/apps/dashboard/src/i18n/locales/tr/emailsAdmin.json
index 3106e7ab4..a8598cab3 100644
--- a/apps/dashboard/src/i18n/locales/tr/emailsAdmin.json
+++ b/apps/dashboard/src/i18n/locales/tr/emailsAdmin.json
@@ -519,7 +519,7 @@
"accountsTitle": "Hesaplar, alan adları ve takma adlar",
"accountsDesc": "Posta kutuları (parola özetleriyle), alan adları ve takma adlar — vmail veritabanı.",
"messageTitle": "Posta kutusu mesaj verileri",
- "messageDesc": "İletiler, klasörler, kuyruk ve karantina. Kopyalama sırasında teslimat ve IMAP duraklatılır.",
+ "messageDesc": "Saklanan tüm e-postalar (/var/vmail maildir klasörleri). Büyük boyutlu olabilir.",
"keysTitle": "DKIM anahtarları ve gizli veriler",
"keysDesc": "DKIM anahtarları + yapılandırma + mail-state.json. Geri yüklemede DKIM'i geçerli tutar — ancak arşiv özel anahtarları ve gizli verileri barındırır.",
"keysWarning": "Yedek; şifre özetlerini, DKIM özel anahtarlarını ve düz metin hâlindeki gizli verileri içerir. Yedekleme hedefine erişimi kısıtlı tutun.",
diff --git a/apps/dashboard/src/i18n/locales/tr/migration.json b/apps/dashboard/src/i18n/locales/tr/migration.json
index 376a7d56b..68eefee91 100644
--- a/apps/dashboard/src/i18n/locales/tr/migration.json
+++ b/apps/dashboard/src/i18n/locales/tr/migration.json
@@ -1,18 +1,4 @@
{
- "platformDomains": {
- "title": "Alan adları ve DNS",
- "intro": "İçe aktarma DNS’i değiştirmez veya trafiği taşımaz.",
- "customAction": "DNS’i güncelle",
- "providerAction": "URL’yi değiştir",
- "customHint": "Özel alan adları, ilgili hizmetin Alan adları ve rotalar bölümüne aktarılır. İçe aktarılan uygulamayı kontrol ettikten sonra DNS kayıtlarını inceleyin ve doğrulamayı tamamlayın.",
- "providerHint": "Sağlayıcıya ait URL’ler OpenShip’e taşınamaz. Yeni bir adres seçin ve eski adresi kullanan uygulama URL’lerini, OAuth geri çağrılarını ve webhook’ları güncelleyin.",
- "empty": "Herkese açık alan adı bulunamadı. Dahili hizmetleri özel tutun; yalnızca herkese açık erişim gereken hizmetlere alan adı ekleyin.",
- "next": "Trafik geçişini onaylamadan önce",
- "test": "İçe aktarılan rotaları incelemek için Alan adları ve rotaları açın. Gerekirse bir test alan adı ekleyin ve uygulamayı ve verilerini kontrol edin.",
- "dns": "Alan adları ve rotalar bölümünde özel alan adlarınızı inceleyin ve eksik olanları ekleyin. Ardından gösterilen DNS kayıtlarını DNS sağlayıcınızda aynen uygulayın veya desteklenen bir bağlantıyla otomatik DNS yapılandırmasını inceleyin. Eski yönlendirme kayıtlarını değiştirin; diğer kayıtları koruyun.",
- "verify": "OpenShip’te DNS ve HTTPS’i doğrulayın, ardından tamamlandığını onaylamadan önce herkese açık URL’leri test edin.",
- "openDomains": "Alan adlarını ve DNS’i incele"
- },
"wizard": {
"edgeReview": {
"detected": "{proxy} algılandı",
diff --git a/apps/dashboard/src/i18n/locales/tr/projectSettings.json b/apps/dashboard/src/i18n/locales/tr/projectSettings.json
index 9f55585ea..b5ae9bad2 100644
--- a/apps/dashboard/src/i18n/locales/tr/projectSettings.json
+++ b/apps/dashboard/src/i18n/locales/tr/projectSettings.json
@@ -532,7 +532,7 @@
},
"runtime": {
"title": "Çalışma zamanı yapılandırması",
- "description": "Yapılandırmayı buradan kaydedin. Değişiklikler bir sonraki dağıtımda uygulanır.",
+ "description": "Salt okunur. Dağıtım sihirbazı aracılığıyla düzenleyin, böylece her değişiklik yeni bir sürüm olarak yayınlansın.",
"framework": "Framework",
"packageManager": "Paket yöneticisi",
"runtimeIsolation": "Çalışma zamanı izolasyonu",
@@ -548,11 +548,7 @@
"modeSandboxed": "Korumalı Alan (konteyner)",
"modeDirect": "Doğrudan (ana makine süreci)",
"modeDefault": "Varsayılan (dağıtımda çözümlenir)",
- "modeStatic": "Yok — statik dosya olarak sunulur",
- "saved": "Yapılandırma kaydedildi. Değişiklikleri uygulamak için dağıtım yapın.",
- "saveFailed": "Yapılandırma kaydedilemedi. Değişiklikleriniz formda korunuyor.",
- "projectSettingsHint": "Paylaşılan ortam ve kaynak sınırları proje ayarlarından yönetilir.",
- "invalidPort": "1 ile 65535 arasında bir bağlantı noktası girin."
+ "modeStatic": "Yok — statik dosya olarak sunulur"
},
"storage": {
"title": "Kalıcı depolama",
@@ -594,7 +590,7 @@
"env": {
"title": "Proje ortamı",
"sharedTitle": "Paylaşılan proje ortamı",
- "description": "İmaj derlemeleri ve çalışma zamanı için paylaşılan varsayılan değerler. Hizmet değerleri önceliklidir. Gizli değerler maskelenir.",
+ "description": "Derleme ve çalışma sırasında kullanılır. Gizli değerler maskeli kalır.",
"edit": "Düzenle"
}
},
@@ -1388,59 +1384,5 @@
"manual": "Düzenlenebilir doğrudan imaj referansı bulunamadı. Değişkenleri, devralınan imajları veya özel derleme mantığını güncellemek için kaynak dosyasını açın.",
"working": "İşleniyor…",
"failed": "Kaynak güncellemesi hazırlanamadı."
- },
- "responseRoutes": {
- "title": "Sanal rotalar",
- "description": "Bu alan adındaki bir yolda doğrudan edge üzerinden içerik döndürün.",
- "add": "Rota ekle",
- "edit": "Rotayı düzenle",
- "staticResponse": "Statik yanıt",
- "loading": "Rotalar yükleniyor",
- "loadFailed": "Sanal rotalar yüklenemedi.",
- "retry": "Yeniden dene",
- "saveFailed": "Rota kaydedilemedi.",
- "duplicateHeader": "Her yanıt başlığının adı benzersiz olmalıdır.",
- "enabled": "Etkin",
- "disabled": "Devre dışı",
- "enable": "Etkinleştir",
- "disable": "Devre dışı bırak",
- "remove": "Kaldır",
- "removeHint": "Bu yanıt kaldırılsın mı? İstekler alan adının kalan rotalarını kullanır.",
- "cancel": "İptal",
- "close": "Kapat",
- "path": "Yol",
- "match": "Eşleşme",
- "exact": "Tam yol",
- "prefix": "Yol öneki",
- "exactHint": "Yalnızca bu yolla eşleşir. Sorgu parametreleri yok sayılır.",
- "prefixHint": "Bu yol ve alt yollarıyla eşleşir. En özel yol önceliklidir.",
- "status": "Durum kodu",
- "contentType": "İçerik türü",
- "plainText": "Düz metin",
- "custom": "Özel",
- "customContentType": "Özel içerik türü",
- "body": "Yanıt gövdesi",
- "bodyPlaceholder": "Döndürülecek içeriği girin…",
- "bodyHint": "İçerik olduğu gibi döndürülür. En fazla 64 KiB.",
- "headers": "Yanıt başlıkları",
- "addHeader": "Başlık ekle",
- "headerName": "Başlık adı",
- "headerValue": "Başlık değeri",
- "removeHeader": "Başlığı kaldır",
- "methods": "İstek yöntemleri",
- "methodsHint": "Virgülle ayrılmış yöntemler. Tüm yöntemler için boş bırakın. GET, HEAD yöntemini içerir.",
- "preview": "Yanıt önizlemesi",
- "applyHint": "Uygulamayı yeniden dağıtmadan uygulanır.",
- "save": "Yanıtı kaydet",
- "saved": "Kaydedildi ve edge üzerinde uygulandı.",
- "pending": "Kaydedildi. Edge uygulaması bekliyor. Edge'i güncelleyin veya yeniden bağlayın, ardından yönlendirmeyi yeniden deneyin.",
- "bytes": "bayt",
- "emptyBodyHint": "Bu durum kodu boş bir yanıt gövdesi gerektirir.",
- "headersHint": "Önbellek, CORS veya diğer yanıt başlıklarını ekleyin."
- },
- "icon": {
- "label": "Proje simgesi URL’si",
- "hint": "HTTP veya HTTPS resim URL’si kullanın. Varsayılan simgeyi kullanmak için URL’yi temizleyin.",
- "reset": "Varsayılan simgeyi kullan"
}
}
diff --git a/apps/dashboard/src/i18n/locales/tr/settings.json b/apps/dashboard/src/i18n/locales/tr/settings.json
index 563cf2944..343010e85 100644
--- a/apps/dashboard/src/i18n/locales/tr/settings.json
+++ b/apps/dashboard/src/i18n/locales/tr/settings.json
@@ -1791,21 +1791,5 @@
"confirmCta": "Sunmayı durdur",
"cancel": "İptal",
"noReverseProxy": "Bu makinede ters proxy algılanmadı."
- },
- "imageUrl": {
- "preview": "Resim önizlemesi",
- "invalid": "Kimlik bilgisi içermeyen bir HTTP veya HTTPS resim URL’si girin.",
- "failed": "Resim URL’si kaydedilemedi.",
- "save": "Kaydet",
- "saving": "Kaydediliyor…",
- "saved": "Kaydedildi",
- "previewFailed": "Önizleme kullanılamıyor. URL’nin doğrudan bir resme yöneldiğini kontrol edin."
- },
- "profile": {
- "title": "Profil",
- "description": "Kişisel hesabınızın resmi.",
- "label": "Avatar URL’si",
- "hint": "Doğrudan bir resim URL’si kullanın. Baş harfiniz için boş bırakın.",
- "reset": "Baş harfi kullan"
}
}
diff --git a/apps/dashboard/src/i18n/locales/zh/auth.json b/apps/dashboard/src/i18n/locales/zh/auth.json
index 3cb32f509..d5b6eaf90 100644
--- a/apps/dashboard/src/i18n/locales/zh/auth.json
+++ b/apps/dashboard/src/i18n/locales/zh/auth.json
@@ -70,8 +70,6 @@
"errorDescription": "该验证码可能不正确或已过期。",
"resendEmail": "重新发送验证码",
"signIn": "登录",
- "signupTitle": "请查收邮件",
- "signupSentTo": "我们已将后续步骤发送至 {email}。如果您收到了验证码,请在下方输入;否则,请按照邮件中的登录说明操作。",
"pendingTitle": "验证你的邮箱",
"pendingSentTo": "我们已将 6 位验证码发送至 {email}。请在下方输入验证码以验证你的邮箱。",
"pendingGeneric": "请输入我们通过邮件发送的验证码。",
diff --git a/apps/dashboard/src/i18n/locales/zh/billing.json b/apps/dashboard/src/i18n/locales/zh/billing.json
index 10554d76d..62220c737 100644
--- a/apps/dashboard/src/i18n/locales/zh/billing.json
+++ b/apps/dashboard/src/i18n/locales/zh/billing.json
@@ -668,7 +668,6 @@
"diskGrowth": "现有磁盘可以扩容。缩减存储需要将数据迁移到新服务器。",
"range": "{min} 至 {max} {unit}",
"monthlyTotal": "每月总计",
- "yearlyTotal": "年度总额",
"choose": "选择自定义",
"updating": "正在更新价格",
"invalid": "请为每项资源输入有效范围内的数值。",
@@ -680,7 +679,6 @@
"extraMemory": "额外内存",
"extraDisk": "额外存储",
"rates": "额外资源月费:{cpu}/vCPU、{memory}/GB 内存、{disk}/GB 存储。仅对超出所选套餐的部分收费。",
- "yearlyRates": "年度额外资源费用:{cpu}/vCPU、{memory}/GB 内存、{disk}/GB 存储。仅对超出所选套餐的资源收费。",
"applyNotice": "升级在付款后生效。费用更低的变更从续费时开始。",
"resizeTitle": "应用已订阅的资源",
"resizeDescription": "你的套餐已更改。重启此服务器之前,请查看新容量及受影响的项目。",
diff --git a/apps/dashboard/src/i18n/locales/zh/deployments.json b/apps/dashboard/src/i18n/locales/zh/deployments.json
index b0816d8ab..925a48d96 100644
--- a/apps/dashboard/src/i18n/locales/zh/deployments.json
+++ b/apps/dashboard/src/i18n/locales/zh/deployments.json
@@ -202,13 +202,6 @@
"pageOf": "第 {page} 页,共 {total} 页",
"range": "第 {from}–{to} 条部署,共 {total} 条"
},
- "containerConflict": {
- "title": "处理重复容器",
- "description": "检查目标服务器上的容器及其挂载。保留预期使用的容器和数据,仅删除已确认不再使用的重复容器,然后重新部署。如果无法确定应保留哪一个,请提供此部署编号并联系支持。",
- "containers": "匹配的容器",
- "reviewServer": "查看服务器",
- "reference": "部署编号"
- },
"resourceGuidance": {
"label": "部署资源指引",
"reviewCapacity": "检查容量",
diff --git a/apps/dashboard/src/i18n/locales/zh/emailsAdmin.json b/apps/dashboard/src/i18n/locales/zh/emailsAdmin.json
index 8fbfc5381..53effa56c 100644
--- a/apps/dashboard/src/i18n/locales/zh/emailsAdmin.json
+++ b/apps/dashboard/src/i18n/locales/zh/emailsAdmin.json
@@ -519,7 +519,7 @@
"accountsTitle": "账户、域名与别名",
"accountsDesc": "邮箱(含密码哈希)、域名和别名——即 vmail 数据库。",
"messageTitle": "邮箱邮件数据",
- "messageDesc": "邮件、文件夹、队列和隔离数据。复制期间暂停投递和 IMAP。",
+ "messageDesc": "所有已存储的电子邮件(/var/vmail maildir 目录)。可能会很大。",
"keysTitle": "DKIM 密钥与机密信息",
"keysDesc": "DKIM 密钥 + 配置 + mail-state.json。还原后可保持 DKIM 有效——但此后归档文件中将包含私钥和机密信息。",
"keysWarning": "备份将包含密码哈希、DKIM 私钥和明文机密信息。请对目标位置保密。",
diff --git a/apps/dashboard/src/i18n/locales/zh/migration.json b/apps/dashboard/src/i18n/locales/zh/migration.json
index 005173ac1..a2d373af8 100644
--- a/apps/dashboard/src/i18n/locales/zh/migration.json
+++ b/apps/dashboard/src/i18n/locales/zh/migration.json
@@ -1,18 +1,4 @@
{
- "platformDomains": {
- "title": "域名与 DNS",
- "intro": "导入不会更改 DNS 或切换流量。",
- "customAction": "更新 DNS",
- "providerAction": "替换 URL",
- "customHint": "自定义域名会导入对应服务的“域名与路由”。检查导入的应用后,请核对 DNS 记录并完成验证。",
- "providerHint": "提供商拥有的 URL 无法迁移到 OpenShip。请选择新地址,并更新使用旧地址的应用 URL、OAuth 回调和 Webhook。",
- "empty": "未发现公共域名。请将内部服务保持为私有,仅为需要公共访问的服务添加域名。",
- "next": "确认流量切换前",
- "test": "打开“域名与路由”以检查导入的路由。按需添加测试域名,并检查应用及其数据。",
- "dns": "在“域名与路由”中检查自定义域名并添加缺失的域名。然后在 DNS 提供商处准确应用显示的记录,或通过支持的连接检查自动 DNS 配置。替换旧的路由记录,保留无关记录。",
- "verify": "在 OpenShip 中验证 DNS 和 HTTPS,然后测试公共 URL,再确认完成。",
- "openDomains": "检查域名与 DNS"
- },
"wizard": {
"edgeReview": {
"detected": "已检测到 {proxy}",
diff --git a/apps/dashboard/src/i18n/locales/zh/projectSettings.json b/apps/dashboard/src/i18n/locales/zh/projectSettings.json
index ab52939d9..ad661b324 100644
--- a/apps/dashboard/src/i18n/locales/zh/projectSettings.json
+++ b/apps/dashboard/src/i18n/locales/zh/projectSettings.json
@@ -482,7 +482,7 @@
},
"runtime": {
"title": "运行时配置",
- "description": "在此保存配置。更改将在下次部署时生效。",
+ "description": "只读。请通过部署向导进行编辑,使每次更改都作为新版本发布。",
"framework": "框架",
"packageManager": "包管理器",
"runtimeIsolation": "运行时隔离",
@@ -498,11 +498,7 @@
"modeSandboxed": "沙盒化(容器)",
"modeDirect": "直接(主机进程)",
"modeDefault": "默认(部署时解析)",
- "modeStatic": "无 — 以静态文件形式提供",
- "saved": "配置已保存。请部署以应用更改。",
- "saveFailed": "无法保存配置。您的更改仍保留在表单中。",
- "projectSettingsHint": "共享环境和资源限制在项目设置中管理。",
- "invalidPort": "请输入 1 到 65535 之间的端口号。"
+ "modeStatic": "无 — 以静态文件形式提供"
},
"storage": {
"title": "持久化存储",
@@ -544,7 +540,7 @@
"env": {
"title": "项目环境变量",
"sharedTitle": "项目共享环境变量",
- "description": "用于镜像构建和运行时的共享默认值。服务中的值优先,密钥保持隐藏。",
+ "description": "在构建和运行时使用。密钥保持隐藏。",
"edit": "编辑"
}
},
@@ -1388,59 +1384,5 @@
"manual": "未找到可编辑的直接镜像引用。请打开源文件,更新变量、继承的镜像或自定义构建逻辑。",
"working": "处理中…",
"failed": "无法准备源码更新。"
- },
- "responseRoutes": {
- "title": "虚拟路由",
- "description": "在此域名的指定路径上直接由边缘返回内容。",
- "add": "添加路由",
- "edit": "编辑路由",
- "staticResponse": "静态响应",
- "loading": "正在加载路由",
- "loadFailed": "无法加载虚拟路由。",
- "retry": "重试",
- "saveFailed": "无法保存路由。",
- "duplicateHeader": "每个响应头的名称必须唯一。",
- "enabled": "已启用",
- "disabled": "已禁用",
- "enable": "启用",
- "disable": "禁用",
- "remove": "移除",
- "removeHint": "移除此响应?请求将使用该域名的其他路由。",
- "cancel": "取消",
- "close": "关闭",
- "path": "路径",
- "match": "匹配方式",
- "exact": "精确路径",
- "prefix": "路径前缀",
- "exactHint": "仅匹配此路径,忽略查询参数。",
- "prefixHint": "匹配此路径及其子路径,最具体的路径优先。",
- "status": "状态码",
- "contentType": "内容类型",
- "plainText": "纯文本",
- "custom": "自定义",
- "customContentType": "自定义内容类型",
- "body": "响应正文",
- "bodyPlaceholder": "输入要返回的内容…",
- "bodyHint": "原样返回内容,最大 64 KiB。",
- "headers": "响应头",
- "addHeader": "添加响应头",
- "headerName": "响应头名称",
- "headerValue": "响应头值",
- "removeHeader": "移除响应头",
- "methods": "请求方法",
- "methodsHint": "使用逗号分隔,留空表示所有方法。GET包含HEAD。",
- "preview": "响应预览",
- "applyHint": "无需重新部署应用即可生效。",
- "save": "保存响应",
- "saved": "已保存并应用到边缘。",
- "pending": "已保存,等待应用到边缘。请更新或重新连接边缘,然后重试路由。",
- "bytes": "字节",
- "emptyBodyHint": "此状态码要求响应正文为空。",
- "headersHint": "添加缓存、CORS 或其他响应标头。"
- },
- "icon": {
- "label": "项目图标 URL",
- "hint": "使用 HTTP 或 HTTPS 图片 URL。清空后将使用默认图标。",
- "reset": "使用默认图标"
}
}
diff --git a/apps/dashboard/src/i18n/locales/zh/settings.json b/apps/dashboard/src/i18n/locales/zh/settings.json
index 682c418c8..753bd8f2a 100644
--- a/apps/dashboard/src/i18n/locales/zh/settings.json
+++ b/apps/dashboard/src/i18n/locales/zh/settings.json
@@ -1791,21 +1791,5 @@
"confirmCta": "停止服务",
"cancel": "取消",
"noReverseProxy": "在此机器上未检测到反向代理。"
- },
- "imageUrl": {
- "preview": "图片预览",
- "invalid": "请输入不含凭据的 HTTP 或 HTTPS 图片 URL。",
- "failed": "无法保存图片 URL。",
- "save": "保存",
- "saving": "正在保存…",
- "saved": "已保存",
- "previewFailed": "无法预览。请检查 URL 是否直接指向图片。"
- },
- "profile": {
- "title": "个人资料",
- "description": "你的个人账户图片。",
- "label": "头像 URL",
- "hint": "使用图片的直接 URL。留空则显示姓名首字母。",
- "reset": "使用首字母"
}
}
diff --git a/apps/dashboard/src/lib/api/connections.ts b/apps/dashboard/src/lib/api/connections.ts
index 58e3e6043..54c2c54a1 100644
--- a/apps/dashboard/src/lib/api/connections.ts
+++ b/apps/dashboard/src/lib/api/connections.ts
@@ -1,4 +1,3 @@
-import type { ProjectConnectionCandidate } from "@repo/contracts";
import { api } from "./client";
import { endpoints } from "./endpoints";
@@ -49,7 +48,15 @@ async function notifyConnections(request: Promise): Promise {
export const connectionsApi = {
candidates: (projectId: string) =>
- api.get<{ data: ProjectConnectionCandidate[] }>(`${endpoints.projects.connections(projectId)}/candidates`),
+ api.get<{
+ data: Array<{
+ id: string;
+ name: string;
+ description: string;
+ appTemplateId: string | null;
+ clusterId?: string | null;
+ }>;
+ }>(`${endpoints.projects.connections(projectId)}/candidates`),
/** Connections wired INTO a project (`projectId` = the consumer). */
list: (projectId: string) =>
api.get<{ data: ProjectConnection[] }>(endpoints.projects.connections(projectId)),
diff --git a/apps/dashboard/src/lib/api/management.ts b/apps/dashboard/src/lib/api/management.ts
index 96897fa95..09e72d1c6 100644
--- a/apps/dashboard/src/lib/api/management.ts
+++ b/apps/dashboard/src/lib/api/management.ts
@@ -1,11 +1,8 @@
import type { BillingOperations } from "@repo/contracts";
import { api } from "./client";
-import { invalidatePayments } from "@/lib/billing-events";
type Result = Awaited>;
-const post = async (path: string, body?: unknown) => {
- try { return (await api.post<{ data: Result }>(`/billing/manage/${path}`, body)).data; }
- finally { invalidatePayments(); }
-};
+const post = async (path: string, body?: unknown) =>
+ (await api.post<{ data: Result }>(`/billing/manage/${path}`, body)).data;
export const managementApi = {
get: async () => (await api.get<{ data: Result<"getManagement"> }>("/billing/manage")).data,
purchase: (input: Parameters[0]) =>
diff --git a/apps/dashboard/src/lib/api/projects.ts b/apps/dashboard/src/lib/api/projects.ts
index 88f1bf4b1..0d56e6d1b 100644
--- a/apps/dashboard/src/lib/api/projects.ts
+++ b/apps/dashboard/src/lib/api/projects.ts
@@ -189,7 +189,6 @@ export interface RouteRuleRow {
pathPrefix: string | null;
spec: RouteRuleSpec;
enabled: boolean;
- edgeApplied?: boolean;
}
/**
@@ -568,7 +567,7 @@ export const projectsApi = {
updateRouteRule: (id: string | number, ruleId: string, body: RouteRuleInput) =>
api.patch<{ rule: RouteRuleRow }>(endpoints.projects.routeRule(id, ruleId), body),
deleteRouteRule: (id: string | number, ruleId: string) =>
- api.delete<{ success: boolean; edgeApplied?: boolean }>(endpoints.projects.routeRule(id, ruleId)),
+ api.delete<{ success: boolean }>(endpoints.projects.routeRule(id, ruleId)),
/** Create a new deployment session */
createDeploymentSession: (id: string | number) =>
@@ -613,10 +612,7 @@ export const projectsApi = {
}>(endpoints.projects.env(id)),
/** Get git settings */
- getGit: (id: string | number) =>
- api.get>>(
- endpoints.projects.git(id),
- ),
+ getGit: (id: string | number) => api.get(endpoints.projects.git(id)),
/** Link a GitHub repo to an existing project + register webhook */
linkRepo: (
diff --git a/apps/dashboard/src/lib/billing-events.ts b/apps/dashboard/src/lib/billing-events.ts
deleted file mode 100644
index 6b75dfafb..000000000
--- a/apps/dashboard/src/lib/billing-events.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-export const PAYMENTS_CHANGED = "openship:payments-changed";
-
-/** Refresh payment warnings after mutations, including uncertain responses. */
-export function invalidatePayments() {
- window.dispatchEvent(new Event(PAYMENTS_CHANGED));
-}
diff --git a/apps/dashboard/src/lib/checkout-navigation.test.ts b/apps/dashboard/src/lib/checkout-navigation.test.ts
deleted file mode 100644
index d9dcf1cd1..000000000
--- a/apps/dashboard/src/lib/checkout-navigation.test.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-// @vitest-environment happy-dom
-import { afterEach, expect, it, vi } from "vitest";
-import { navigateToCheckout } from "./checkout-navigation";
-
-const diagnostics = vi.hoisted(() => ({ report: vi.fn() }));
-vi.mock("@repo/core/diagnostics", () => ({ reportCaughtError: diagnostics.report }));
-
-afterEach(() => { vi.restoreAllMocks(); vi.clearAllMocks(); });
-
-it.each(["javascript:alert(1)", "data:text/html,checkout", "http://checkout.example.test", ""])(
- "refuses an invalid payment destination before opening a tab: %s", value => {
- const open = vi.spyOn(window, "open");
- const before = window.location.href;
- expect(() => navigateToCheckout(value, true)).toThrow();
- expect(open).not.toHaveBeenCalled();
- expect(window.location.href).toBe(before);
- },
-);
-
-it("opens only the final URL without an opener or referrer, preserving the project", () => {
- const open = vi.spyOn(window, "open").mockReturnValue(null);
- const before = window.location.href;
- expect(navigateToCheckout("https://checkout.example.test/session", true)).toBe("https://checkout.example.test/session");
- expect(open).toHaveBeenCalledExactlyOnceWith("https://checkout.example.test/session", "_blank", "noopener,noreferrer");
- expect(window.location.href).toBe(before);
-});
-
-it("retains the validated fallback URL if the browser throws when refusing a popup", () => {
- vi.spyOn(window, "open").mockImplementation(() => { throw new Error("Popups refused: https://checkout.example.test/private-session"); });
- expect(navigateToCheckout("https://checkout.example.test/session", true)).toBe("https://checkout.example.test/session");
- expect(diagnostics.report).toHaveBeenCalledExactlyOnceWith(expect.any(Error), "dashboard/lib/checkout-navigation");
- const reported = diagnostics.report.mock.calls[0][0] as Error;
- expect(reported.message).toBe("Browser refused to open hosted checkout");
- expect(reported.message).not.toContain("private-session");
-});
-
-it("uses the existing tab when there is no project draft to preserve", () => {
- const open = vi.spyOn(window, "open");
- navigateToCheckout("https://checkout.example.test/session", false);
- expect(window.location.href).toBe("https://checkout.example.test/session");
- expect(open).not.toHaveBeenCalled();
-});
diff --git a/apps/dashboard/src/lib/checkout-navigation.ts b/apps/dashboard/src/lib/checkout-navigation.ts
index 7c13e84bf..2d73fd312 100644
--- a/apps/dashboard/src/lib/checkout-navigation.ts
+++ b/apps/dashboard/src/lib/checkout-navigation.ts
@@ -1,18 +1,19 @@
-import { reportCaughtError } from "@repo/core/diagnostics";
-
-/** The API validates payment hosts. Open only its final HTTPS URL.
- * Blocked popups retain the visible checkout
- * action; failed requests never leave blank tabs or discard project drafts. */
-export function navigateToCheckout(value: string, preserveProject: boolean) {
- const url = new URL(value);
- if (url.protocol !== "https:") throw new Error("Invalid checkout URL");
- if (preserveProject) {
- try { window.open(url.href, "_blank", "noopener,noreferrer"); }
- catch {
- // Browser errors can embed the payment URL. Report no hosted-session data.
- reportCaughtError(new Error("Browser refused to open hosted checkout"), "dashboard/lib/checkout-navigation");
- // Keep the validated manual action available when popups are refused.
- }
- } else window.location.href = url.href;
- return url.href;
+/** Reserve a tab inside the user's click so payment never discards a draft.
+ * The API validates hosted-payment URLs; blocked popups retain a manual link. */
+export function beginCheckoutNavigation(preserveProject: boolean) {
+ const tab = preserveProject ? window.open("about:blank", "_blank") : null;
+ if (tab) tab.opener = null;
+ return {
+ close: () => tab?.close(),
+ navigate(value: string) {
+ const url = new URL(value);
+ if (url.protocol !== "https:") throw new Error("Invalid checkout URL");
+ if (preserveProject) {
+ if (tab && !tab.closed) tab.location.href = url.href;
+ } else {
+ window.location.href = url.href;
+ }
+ return url.href;
+ },
+ };
}
diff --git a/apps/dashboard/src/proxy.test.ts b/apps/dashboard/src/proxy.test.ts
index 59b96828a..6746ee9ea 100644
--- a/apps/dashboard/src/proxy.test.ts
+++ b/apps/dashboard/src/proxy.test.ts
@@ -1,17 +1,8 @@
import { describe, expect, it } from "vitest";
import { NextRequest } from "next/server";
-import { unstable_doesMiddlewareMatch } from "next/experimental/testing/server";
-import { config, proxy } from "./proxy";
+import { proxy } from "./proxy";
describe("dashboard proxy middleware", () => {
- it.each(["/api", "/api/proxy/api/projects/folder/upload/session", "/api/auth/sign-in/email", "/api/mcp"])(
- "does not buffer API request bodies through middleware: %s", (url) => {
- expect(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url })).toBe(false);
- },
- );
- it.each(["/projects", "/login", "/api-docs"])("still matches page requests: %s", (url) => {
- expect(unstable_doesMiddlewareMatch({ config, nextConfig: {}, url })).toBe(true);
- });
it("mirrors a valid theme cookie for the initial server render", () => {
const response = proxy(new NextRequest("https://app.openship.io/login", {
headers: { cookie: "openship-theme=system:dim", "x-openship-theme": "light:light" },
diff --git a/apps/dashboard/src/proxy.ts b/apps/dashboard/src/proxy.ts
index 66af7a4f9..0801bfe61 100644
--- a/apps/dashboard/src/proxy.ts
+++ b/apps/dashboard/src/proxy.ts
@@ -90,7 +90,5 @@ export function proxy(req: NextRequest) {
}
export const config = {
- // API routes authenticate in the API process. Matching them here makes Next
- // clone/buffer uploads, truncating the stream at its middleware body limit.
- matcher: ["/((?!api(?:/|$)|_next/static|_next/image|favicon.ico|.*\\..*).*)"],
+ matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\..*).*)"],
};
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 650107bb7..0891b0b03 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -1,7 +1,7 @@
{
"name": "@repo/desktop",
"productName": "Openship",
- "version": "0.9.12",
+ "version": "0.9.11",
"private": true,
"description": "Openship Desktop - Electron wrapper for the deployment dashboard",
"author": "Oblien",
diff --git a/apps/edge/Dockerfile b/apps/edge/Dockerfile
index e55e7a2fc..9e33ea6f6 100644
--- a/apps/edge/Dockerfile
+++ b/apps/edge/Dockerfile
@@ -19,7 +19,7 @@ FROM openresty/openresty:1.27.1.1-alpine
# (49180) transiently and the edge proxies /.well-known/acme-challenge/ to it
# (see nginx.conf) — zero downtime, no webroot, no port-80 fight.
# procps → `pkill` for the reload command's restart fallback.
-# curl → the mgmt-API exec transport (edge-management.ts execMgmt) reaches
+# curl → the mgmt-API exec transport (project-analytics.ts execMgmt) reaches
# 127.0.0.1:9145 from INSIDE this container, since network_mode: host
# puts that loopback out of the api container's reach.
# openssl → the CLI (the base image ships only the libraries) for the temporary
diff --git a/apps/email/package.json b/apps/email/package.json
index 4dd50ceea..a9211f403 100644
--- a/apps/email/package.json
+++ b/apps/email/package.json
@@ -1,6 +1,6 @@
{
"name": "@repo/email",
- "version": "0.9.12",
+ "version": "0.9.11",
"private": true,
"description": "Self-hosted email - iRedMail (engine) + Zero Email (server + client). Orchestrator package: install and run server + client together.",
"scripts": {
diff --git a/apps/web/content/docs/cli/projects.mdx b/apps/web/content/docs/cli/projects.mdx
index 3951622bd..09a290981 100644
--- a/apps/web/content/docs/cli/projects.mdx
+++ b/apps/web/content/docs/cli/projects.mdx
@@ -86,17 +86,11 @@ command, build settings, routing, ports and enabled state.
```bash
openship domain add app.example.com --project proj_123
-# Multi-service project: choose a service and its container port.
-openship domain add api.example.com --project proj_123 --service api --port 3000
openship domain records dom_123
openship domain verify dom_123
openship domain verify-ssl dom_123
```
-Target validation happens before the hostname is claimed. The selected project or service keeps its
-existing endpoints; the new domain becomes routable on the next deployment. A multi-service project
-requires `--service`; services with several ports also require `--port`.
-
Follow the returned DNS instructions before verification. See [domain options](/docs/cli/reference/domain)
and the [custom-domain guide](/docs/guides/custom-domains) for DNS providers, TLS, and primary domains.
diff --git a/apps/web/content/docs/cli/reference/domain/index.mdx b/apps/web/content/docs/cli/reference/domain/index.mdx
index 99a5c4ee2..ec444896c 100644
--- a/apps/web/content/docs/cli/reference/domain/index.mdx
+++ b/apps/web/content/docs/cli/reference/domain/index.mdx
@@ -47,8 +47,6 @@ openship domain add [options]
| --- | --- |
| `-p, --project ` | Project ID to attach the domain to |
| `--primary` | Mark this domain as the project's primary (default: false) |
-| `--service ` | Target service within the selected project |
-| `--port ` | Container port to route (required for ambiguous service ports) |
## openship domain get
diff --git a/apps/web/content/docs/dashboard/emails.mdx b/apps/web/content/docs/dashboard/emails.mdx
index f91902a99..6a2895f68 100644
--- a/apps/web/content/docs/dashboard/emails.mdx
+++ b/apps/web/content/docs/dashboard/emails.mdx
@@ -285,9 +285,7 @@ usually means this outer layer is dropping the connection.
Backups run through Openship's general backup system, so the mail server is just another backup source.
Choose **what to back up**: accounts, domains & aliases (always included), **Mailbox message data** (the
-maildirs, folders, queue and quarantine — can be large), and **DKIM keys & secrets**.
-New policies include messages and keys by default; existing exclusions are retained.
-Full backups pause delivery and IMAP while copying, then resume the daemons that were running.
+maildirs — can be large), and **DKIM keys & secrets**.
Including keys means the archive holds password hashes, DKIM private keys, and plaintext secrets. Keep the
@@ -297,11 +295,6 @@ destination private.
Pick a **Destination** (managed on the [Backups](/docs/dashboard/backups) page) and an **Automatic backups**
schedule (Manual only / Daily / Weekly), then **Save settings** or **Back up now**. **Recent backups** lists
each run; successful runs offer **Restore** (in place) and **Migrate** (onto another server).
-Prepare the target mail server with the same primary domain and a compatible mail/PostgreSQL version
-first. Restore includes all mail tables, additional domains, managed mailbox/relay credentials and
-DKIM keys; the destination retains its database-role credentials and TLS configuration. Review the
-new DNS/PTR records before cutover. Failed partial restores stay stopped for review and retry.
-Settings → Instance export does not include mailbox messages by default.
### Advanced
diff --git a/apps/web/content/docs/dashboard/projects.mdx b/apps/web/content/docs/dashboard/projects.mdx
index cb456e05f..c616684dc 100644
--- a/apps/web/content/docs/dashboard/projects.mdx
+++ b/apps/web/content/docs/dashboard/projects.mdx
@@ -13,7 +13,7 @@ its management tabs).
Open **Projects** from the left nav. This screen is a single scannable list of every project in
your workspace — one row per project.
-Each row shows, left to right: the project icon (set in **Settings → Project Info**), or its app/framework logo, the **name**
+Each row shows, left to right: the app's icon (its favicon, or the framework logo), the **name**
and its live version badge, the primary **domain**, the detected **framework**, where it's hosted
(**Cloud**, a **Server** by name, or **Local**), its source (a GitHub repo or a local folder),
the build shape (**Services**, **Static**, or **Standalone**), how long ago it changed, and a
diff --git a/apps/web/content/docs/guides/custom-domains.mdx b/apps/web/content/docs/guides/custom-domains.mdx
index 8a895290b..034268fb1 100644
--- a/apps/web/content/docs/guides/custom-domains.mdx
+++ b/apps/web/content/docs/guides/custom-domains.mdx
@@ -186,34 +186,6 @@ require a new TXT challenge at renewal; the domain details show when renewal is
-## Return content directly from the edge
-
-Open the domain card under your app's **Domains** tab or the project's **Domains & Routes**.
-In **Virtual routes**, choose **Add route** to return a small response without changing or
-redeploying your application. Single apps and Compose services use the same editor.
-
-For example, create `/health`, choose status `200` and content type `application/json`,
-and enter `{"status":"ok"}`. Add response headers such as `Cache-Control: no-store`, then
-choose **Save response**. You can edit, pause, or remove the response from that domain card.
-
-- **Exact path** matches only the path you entered; query parameters do not affect it.
-- **Path prefix** also matches child paths. The longest path wins, with exact matches taking
- precedence at the same path.
-- GET and HEAD are selected initially. Request methods can be narrowed in the editor.
-- Content is literal UTF-8 text up to 64 KiB, including JSON, HTML, XML, and custom content types.
- Statuses `204`, `205`, and `304` require an empty body. Protocol headers such as
- `Content-Length` are managed automatically.
-- Each domain can have up to 64 virtual routes, including paused routes.
-
-Existing domain redirects, password protection, access policies, and rate limits still apply.
-Platform and certificate-verification paths are reserved. This feature requires a domain
-served by the OpenShip edge; Cloud, cluster, external-ingress, and redirect-only domains
-are not supported.
-
-**Saved and applied** means the edge acknowledged the update. If the response is saved but
-pending, update or reconnect the edge and use the domain's **Retry routing** action. Older
-edges need updated scripts and a reload before they can serve virtual responses.
-
## Wildcard domains
Add `*.example.com` to the project's **Domains** tab or the service's public routes. Openship
diff --git a/apps/web/content/docs/guides/migrate-from-railway-vercel.mdx b/apps/web/content/docs/guides/migrate-from-railway-vercel.mdx
index 0cd5a92a4..ea4cf7324 100644
--- a/apps/web/content/docs/guides/migrate-from-railway-vercel.mdx
+++ b/apps/web/content/docs/guides/migrate-from-railway-vercel.mdx
@@ -4,8 +4,8 @@ description: Connect a platform, review its services and data, and import throug
---
Open **New project → Import existing project** and choose **Railway** or **Vercel**.
-Railway imports the complete selected environment into one Openship project containing its
-services. Importing another source project creates a separate project. Repository access, deployments, private service
+Railway imports the complete selected project environment in one operation, with each service
+becoming an Openship project. Repository access, deployments, private service
connections, data transfer and destination selection use the same workflows as other projects.
## Connect the source
@@ -29,7 +29,7 @@ register a temporary SSH key and read the attached storage. A metadata-only toke
## Discover and review
Select the source project and environment. Railway keeps all services in the import so their
-writers, dependencies and storage move together. Name the destination project once. Open **Configure** to inspect each service's repository or image, service name,
+writers, dependencies and storage move together. Open **Configure** to inspect the repository or image, destination name,
variables, storage and domains. Missing secrets open automatically. Private repositories
also need [GitHub access](/docs/guides/git-authentication) in Openship.
@@ -41,7 +41,7 @@ health checks and restart policies are preserved when they can be represented in
Exportable variables stay on the server. Railway sealed values and Vercel Secret/Sensitive
values need to be entered again. Optional variables can be excluded. Railway private addresses
-resolve through service names on the project's private network, preserving the original protocol, credentials,
+become ordinary Openship project connections, preserving the original protocol, credentials,
database name and URL options. Unresolved provider references are
shown as blockers instead of being silently copied.
@@ -73,50 +73,22 @@ For an external PostgreSQL copy, pause writers yourself and keep them paused thr
This is not an export of every provider feature. Vercel Blob, Edge Config, provider-specific
functions and external storage other than supported PostgreSQL copies need separate handling. Cron
services, multiple replicas, Railway pre-deploy commands, multiple public ports, non-GitHub
- repositories, unsupported build settings and unresolved connections block review. Source-built
- services must share one repository and deployed revision; project-wide release commands require
- review. Sleeping services run continuously after import. Dependency cycles require review;
- variables containing several private service addresses are preserved with their new service names.
- External PostgreSQL logical copies do not include other
+ repositories, unsupported build settings and unresolved connections block review. Sleeping
+ services run continuously after import. Dependency cycles and variables containing several private
+ service addresses require review. External PostgreSQL logical copies do not include other
databases or server-wide roles; a Railway volume copy preserves the whole persisted directory.
## Import, verify and finish
-Start the reviewed import. The configuration is checked again, one destination project and its services are created,
+Start the reviewed import. The configuration is checked again, destination projects are allocated,
and the source lifecycle and storage copy are recorded in a recovery checkpoint. The saved migration
-page shows progress, deployment logs and a link to the imported project and survives a browser refresh.
+page shows progress, deployment logs and links to every project and survives a browser refresh.
Dependencies deploy before their consumers, and imported containers must pass runtime verification.
-### Move domains and traffic
-
-Importing does not change DNS or move public traffic. **Domains & DNS** in the review and saved
-migration page lists each discovered hostname alongside its service and the required action:
-
-- **Update DNS:** a custom domain you can keep, such as `app.example.com`.
-- **Replace URL:** a provider-owned address, such as `my-app.up.railway.app` or `my-app.vercel.app`.
- These addresses cannot be transferred to OpenShip. Choose a new address and update application
- URLs, OAuth callback URLs, webhook destinations and other clients that use the old address.
-
-After the import reaches **Verify apps and move traffic**:
-
-1. Choose **Review domains & DNS** to open the imported project's **Domains & Routes**.
- Custom domains and aliases are already assigned to their matching services using the same
- routing flow as server/Docker migration. They start unverified; importing never marks them
- verified on your behalf. Add a test domain if needed and verify the app and its copied data.
-2. Open the DNS settings for each imported custom domain. OpenShip shows the exact DNS
- records for that destination, including any ownership verification records. Apply those
- records at your DNS provider, replacing the old routing records for that hostname.
- Keep unrelated records, including email records. If you have a supported DNS connection,
- you can review and apply the changes through **Auto-configure DNS** in the same flow.
-3. Use OpenShip's domain verification, wait for DNS propagation and HTTPS readiness, and test
- the public URLs. Only then choose **Confirm cutover complete** on the migration page.
-
-The destination can be OpenShip Cloud or your server; use the records shown for that destination
-instead of copying the old Railway or Vercel target. See the
-[custom-domain guide](/docs/guides/custom-domains) for DNS setup and verification.
-Keep databases and other internal services private unless they explicitly need public access.
-Confirmation records your review; it does not change DNS or automatically prove that traffic has moved.
+Open the imported projects, verify their data, and add a test domain in **Domains & Routes**.
+Then move your custom domains through the normal domain flow and confirm cutover. Provider-owned
+domains such as `vercel.app` addresses cannot be transferred.
Source services, domains and data remain at the provider. Retire them there after verification.
A failed Railway import retains copied data and configuration, stops the destination workloads
diff --git a/apps/web/content/docs/mcp.mdx b/apps/web/content/docs/mcp.mdx
index 171012209..d32d9550b 100644
--- a/apps/web/content/docs/mcp.mdx
+++ b/apps/web/content/docs/mcp.mdx
@@ -217,9 +217,9 @@ is built from that route's method and path. So `get_projects` is `GET /api/proje
exact set your token can use.
Not every route is a tool: a route becomes one only when it **opts in**, so the set is a curated slice of the
-API rather than the whole surface. Each exposed tool also carries explicit `readOnlyHint`,
-`destructiveHint`, and `openWorldHint` values. These tell a client whether the tool only reads,
-may perform destructive changes, and may interact with systems outside Openship.
+API rather than the whole surface. Each exposed tool also carries two hints a client can surface —
+`readOnlyHint` (the tool only reads) and `destructiveHint` (it deletes or tears something down) — so an agent
+UI can flag a destructive call before it runs.
| Tool name (examples) | REST route | Reference |
|---|---|---|
diff --git a/apps/web/package.json b/apps/web/package.json
index 46eb400b0..6428e814e 100644
--- a/apps/web/package.json
+++ b/apps/web/package.json
@@ -1,6 +1,6 @@
{
"name": "@repo/web",
- "version": "0.9.12",
+ "version": "0.9.11",
"license": "Apache-2.0",
"private": true,
"scripts": {
diff --git a/apps/web/public/icons/translate language-115-1663582874.png b/apps/web/public/icons/translate language-115-1663582874.png
deleted file mode 100644
index 32bfa08cf..000000000
Binary files a/apps/web/public/icons/translate language-115-1663582874.png and /dev/null differ
diff --git a/apps/web/src/app/(site)/[locale]/(marketing)/pricing/CloudBilling.tsx b/apps/web/src/app/(site)/[locale]/(marketing)/pricing/CloudBilling.tsx
index cb70d9858..991f52277 100644
--- a/apps/web/src/app/(site)/[locale]/(marketing)/pricing/CloudBilling.tsx
+++ b/apps/web/src/app/(site)/[locale]/(marketing)/pricing/CloudBilling.tsx
@@ -3,80 +3,46 @@ import { useCopy } from "@/i18n/use-copy";
import { useState, type ReactNode } from "react";
-type BillingView = {
- plans: ReactNode;
- headline: ReactNode;
- note: ReactNode;
-};
-
export function CloudBilling({
monthly,
annual,
monthsFree,
- children,
}: {
- monthly: BillingView;
- annual?: BillingView;
+ monthly: ReactNode;
+ annual?: ReactNode;
monthsFree: number;
- children: ReactNode;
}) {
const copy = useCopy();
const [interval, setInterval] = useState<"monthly" | "annual">("monthly");
const annualSelected = Boolean(annual) && interval === "annual";
- const selected = annualSelected && annual ? annual : monthly;
return (
<>
-
-
-
- {copy("Cloud resources for your projects.")}
-
-
- {selected.headline}
-
-
- {selected.note &&
{selected.note}
}
+
+
+
{copy("Cloud resource pools")}
+
{copy("CPU, RAM and storage shared across your projects and builds.")}
-
-
-
-
-
-
{copy("Cloud resource pools")}
-
{copy("CPU, RAM and storage shared across your projects and builds.")}
-
- {annual && (
-
+ {(["monthly", "annual"] as const).map((value) => (
+ setInterval(value)}
>
- {(["monthly", "annual"] as const).map((value) => (
- setInterval(value)}
- >
- {value === "monthly" ? copy("Monthly") : copy("Yearly")}
- {value === "annual" && monthsFree > 0 && (
- {copy("{months} months free", { months: monthsFree })}
- )}
-
- ))}
-
- )}
+ {value === "monthly" ? copy("Monthly") : copy("Yearly")}
+ {value === "annual" && monthsFree > 0 && (
+
{copy("{months} months free", { months: monthsFree })}
+ )}
+
+ ))}
-
{monthly.plans}
- {annual &&
{annual.plans}
}
- {children}
-
-
+ )}
+
+
{monthly}
+ {annual &&
{annual}
}
>
);
}
diff --git a/apps/web/src/app/(site)/[locale]/(marketing)/pricing/_data.ts b/apps/web/src/app/(site)/[locale]/(marketing)/pricing/_data.ts
index 96537396b..ef60ca052 100644
--- a/apps/web/src/app/(site)/[locale]/(marketing)/pricing/_data.ts
+++ b/apps/web/src/app/(site)/[locale]/(marketing)/pricing/_data.ts
@@ -22,7 +22,9 @@ export function faq(pricing: CloudPricing, copy: Copy): FaqItem[] {
})
: copy("See your dashboard for current Cloud plans and availability."),
pricing.annual.enabled
- ? copy("Choose Yearly to see the full annual price, paid once a year.")
+ ? copy(
+ "Yearly billing is also available; the cards show the monthly equivalent and full yearly charge.",
+ )
: null,
copy(
"Each subscription includes one Cloud Space for your projects, with no per-seat fees. Share the included CPU, RAM and storage across your projects and builds.",
diff --git a/apps/web/src/app/(site)/[locale]/(marketing)/pricing/page.tsx b/apps/web/src/app/(site)/[locale]/(marketing)/pricing/page.tsx
index b792bca8c..b91eefcb9 100644
--- a/apps/web/src/app/(site)/[locale]/(marketing)/pricing/page.tsx
+++ b/apps/web/src/app/(site)/[locale]/(marketing)/pricing/page.tsx
@@ -11,7 +11,7 @@ import { IllustratedLink } from "@/components/marketing/illustrated-link";
import { CLOUD_SLA } from "@/lib/cloud-service";
import {
UI,
- startingCloudPlan,
+ cloudFrom,
priceParts,
getCloudPricing,
cloudPlanSummary,
@@ -61,7 +61,6 @@ function PlanCard({
cta,
popular,
support,
- benefits = [],
children,
}: {
name: string;
@@ -73,7 +72,6 @@ function PlanCard({
cta: string;
popular?: boolean;
support: string;
- benefits?: string[];
children: ReactNode;
}) {
const copy = useCopy();
@@ -99,14 +97,10 @@ function PlanCard({
{copy(cta)}
{children}
-
- {[...benefits, support].map((benefit) => (
-
-
- {copy(benefit)}
-
- ))}
-
+
+
+ {copy(support)}
+
);
}
@@ -167,7 +161,6 @@ async function CloudPlans({
}) {
const copy = await getCopy();
const standard = resolveStandard(await getLocale());
- const plans = pricing.tiers.filter((plan) => plan.price[interval] != null);
if (!pricing.available)
return (
@@ -183,13 +176,13 @@ async function CloudPlans({
return (
<>
- {plans.map((plan) => {
- const price = priceParts(plan, interval);
+ {pricing.tiers.map((plan) => {
+ const billingInterval =
+ interval === "annual" && plan.price.annual != null ? "annual" : "monthly";
+ const price = priceParts(plan, billingInterval);
const billing =
- interval === "annual"
- ? pricing.annual.monthsFree > 0
- ? copy("{months} months free", { months: pricing.annual.monthsFree })
- : copy("Billed yearly")
+ billingInterval === "annual"
+ ? copy("{value0} billed yearly", { value0: String(money(plan.price.annual!)) })
: copy("Billed monthly");
return (
}
- href={cloudPlanHref(plan.id, interval)}
+ href={cloudPlanHref(plan.id, billingInterval)}
cta={copy("Choose {name}", { name: plan.name })}
popular={plan.popular}
support={supportLabels[plan.support] ?? "See support options"}
- benefits={
- pricing.management?.includedWithCloud
- ? [
- copy("Free management for {count} servers", {
- count: pricing.management.includedServers,
- }),
- ]
- : []
- }
>
@@ -234,7 +218,7 @@ async function CloudPlans({
- {plans.every((plan) => plan.billingMode === "monthly")
+ {pricing.tiers.every((plan) => plan.billingMode === "monthly")
? copy(
"CPU, RAM and storage included. Apps and builds share capacity. Managed proxy transfer and backups are billed separately.",
)
@@ -392,76 +376,74 @@ export default async function PricingPage() {
const copy = await getCopy();
const pricing = await getCloudPricing(await getLocale());
- const billingView = (interval: "monthly" | "annual") => {
- const startingPlan = startingCloudPlan(pricing, interval);
- const yearly = interval === "annual";
- return {
- plans: ,
- headline: startingPlan
- ? copy.rich(
- yearly ? "From {amount} /year" : "From {amount} /month",
- {
- amount: priceParts(startingPlan, interval).amount,
- price: (amount) => {amount} ,
- },
- )
- : copy("Choose your capacity."),
- note: !startingPlan
- ? null
- : yearly
- ? pricing.annual.monthsFree > 0
- ? copy("{months} months free", { months: pricing.annual.monthsFree })
- : copy("Billed yearly")
- : copy("Billed monthly"),
- };
- };
+ const from = cloudFrom(pricing);
return (
<>
-
-
-
-
+
+
+
+ {copy("Cloud resources for your projects.")}
+
+
+ {from
+ ? copy("From {value0}/month.", { value0: String(from) })
+ : copy("Choose your capacity.")}
+
+
- {pricing.customTiers.map((plan) => (
-
-
- {copy(plan.name)}
- {copy(plan.description)}
-
-
- {copy(UI.ctaContact)}
-
+
+
+
+
+
+
- ))}
-
+
}
+ annual={
+ pricing.available && pricing.annual.enabled ? (
+
+ ) : undefined
+ }
+ monthsFree={pricing.annual.monthsFree}
+ />
+ {pricing.customTiers.map((plan) => (
+
+ ))}
+
+
diff --git a/apps/web/src/app/globals.css b/apps/web/src/app/globals.css
index 1555e1c12..e7dd91842 100644
--- a/apps/web/src/app/globals.css
+++ b/apps/web/src/app/globals.css
@@ -23,22 +23,10 @@ html[lang="ar"] :where(h1, h2, h3, h4, p, span, a, button, li, dt, dd, strong, l
html[lang="ar"] :where(h1, h2, h3, h4) {
line-height: 1.4;
}
-html[lang="ar"] .landing-hero {
- padding-block: 112px 56px;
-}
-html[lang="ar"] .hero-content {
- max-width: 1000px;
-}
html[lang="ar"] .hero-title > span {
- font-size: clamp(2rem, 4.5vw, 3.75rem);
+ font-size: clamp(2.25rem, 5vw, 3.5rem);
line-height: 1.4;
font-weight: 400;
- text-wrap: balance;
-}
-html[lang="ar"] .landing-hero .hero-description {
- max-width: 680px;
- font-size: clamp(1rem, 1.2vw, 1.125rem);
- line-height: 1.9;
}
html[lang="ar"] .cmp-cell {
line-height: 1.8;
diff --git a/apps/web/src/components/landing/hero.tsx b/apps/web/src/components/landing/hero.tsx
index 0160177a2..188187fa5 100644
--- a/apps/web/src/components/landing/hero.tsx
+++ b/apps/web/src/components/landing/hero.tsx
@@ -29,7 +29,7 @@ export async function Hero() {
const cloudHref = cloudPlanHref();
return (
-
+
{/* ═══════════════ Background layers ═══════════════ */}
@@ -42,7 +42,7 @@ export async function Hero() {
{/* ═══════════════ Content ═══════════════ */}
-
+
OpenShip Cloud
{from && (
diff --git a/apps/web/src/components/landing/language-switcher.tsx b/apps/web/src/components/landing/language-switcher.tsx
index d967f6e84..0dc57b474 100644
--- a/apps/web/src/components/landing/language-switcher.tsx
+++ b/apps/web/src/components/landing/language-switcher.tsx
@@ -4,7 +4,6 @@ import { useLocale } from "next-intl";
import { usePathname } from "next/navigation";
import { useEffect, useId, useRef, useState } from "react";
import { APP_LOCALES, type AppLocale } from "@repo/core/locale";
-import { Icon } from "@repo/ui/icons";
import { isLocalizedPath, languageNames, localizedHref, withoutLocale } from "@/i18n/routing";
import { useCopy } from "@/i18n/use-copy";
@@ -68,10 +67,9 @@ export function LanguageSwitcher({ dark = false }: { dark?: boolean }) {
aria-expanded={open}
aria-controls={id}
onClick={() => setOpen((value) => !value)}
- className="flex h-9 min-w-11 items-center justify-center gap-1.5 rounded-full px-2 text-xs font-medium transition-colors hover:bg-[var(--th-sf-04)] focus-visible:outline-2 focus-visible:outline-offset-2"
+ className="flex h-9 min-w-11 items-center justify-center gap-1 rounded-full px-2 text-xs font-medium transition-colors hover:bg-[var(--th-sf-04)] focus-visible:outline-2 focus-visible:outline-offset-2"
style={{ color: dark ? "rgba(255,255,255,.75)" : "var(--th-text-secondary)" }}
>
-
{languageNames[locale].short}
(null);
const githubLabel =
stars === null
- ? null
- : new Intl.NumberFormat(locale, {
- notation: "compact",
- maximumFractionDigits: 1,
- }).format(stars);
+ ? copy("Stars")
+ : copy("{count} stars", {
+ count: new Intl.NumberFormat(locale, {
+ notation: "compact",
+ maximumFractionDigits: 1,
+ }).format(stars),
+ });
const githubDescription =
stars === null
? copy("Star OpenShip on GitHub")
@@ -267,18 +269,15 @@ export function Navbar() {
- {githubLabel}
+ {copy(githubLabel)}
-
{/* ── Download link + Cloud destination ── */}
-
-
-
+
- {githubLabel}
+ {copy(githubLabel)}
diff --git a/apps/web/src/i18n/messages/ar.json b/apps/web/src/i18n/messages/ar.json
index a7fff290b..55ceddfdb 100644
--- a/apps/web/src/i18n/messages/ar.json
+++ b/apps/web/src/i18n/messages/ar.json
@@ -349,7 +349,6 @@
"m19ofoog": "تكوين الأسرار في وحدة التحكم التي تملك سير العمل.",
"m19scbsz": "تأكيد الدفع رقم 1234",
"m19ud2w": "قم بتخطيط نافذة صيانة عند نقل البيانات بين الخوادم: تتوقف الخدمات المصدر أثناء نقل البيانات وتبدأ الوجهة. يمكن أن يؤدي استخدام نفس الخادم إلى إعادة استخدام الحاويات قيد التشغيل، ولكن تغيير الوكيل العكسي قد يؤدي إلى مقاطعة حركة المرور لفترة وجيزة. تعتمد المدة على تطبيقك واستراتيجية النقل.",
- "m19uqmyr": "اختر الدفع السنوي لعرض السعر السنوي الكامل، الذي يُدفع مرة واحدة في السنة.",
"m19xi0mu": "اقرأ وأرسل",
"m19zmnxd": "مجاني للأبد · Apache 2.0",
"m1a0fr6p": "حافظ على نطاق مساحة عمل الوصول إلى المشروع والبنية التحتية.",
@@ -373,7 +372,7 @@
"m1ao8e9b": "استكشاف الكل",
"m1aot7c5": "ليست هناك حاجة إلى خدمة قاعدة البيانات.",
"m1aoti7n": "تتم إضافة الأرصدة المعتمدة إلى حسابك في غضون {value0} من الأيام بعد الموافقة وتعويض فاتورة الاشتراك المؤهلة التالية التي تبلغ OpenShip Cloud، بما في ذلك التجديد السنوي. الاعتمادات ليست استرداد نقدي ولا يمكن تحويلها إلى حساب آخر. هذه الاعتمادات هي العلاج الذي توفره اتفاقية مستوى الخدمة هذه؛ ولا تحد من الحقوق التي لا يمكن استبعادها بموجب القانون المعمول به. لا تحظى اتفاقية مستوى الخدمة المكتوبة المنفصلة بالأولوية إلا عندما تختلف شروطها صراحةً.",
- "m1ap8aej": "اربط مستودعك وانشر مشروعك، ثم تابع الأداء والسجلات، وأدر النطاقات والنسخ الاحتياطية ومهام الأتمتة. ابدأ على OpenShip Cloud أو اربط خوادمك، مع أدوات التشغيل التي تحتاجها في لوحة واحدة.",
+ "m1ap8aej": "شغّل تطبيقاتك وقواعد بياناتك ومهامك من مكان واحد. ابدأ على OpenShip Cloud أو اربط خوادمك.",
"m1aqip6t": "وسيط رسائل مستمر مع لوحة معلومات الإدارة الرسمية لقوائم الانتظار والتبادلات والاتصالات.",
"m1au9f1c": "تتدفق بيانات العملاء عبر تطبيقاتك. قواعد بياناتك وسجلات تطبيقك هي بياناتك؛ نستضيفهم لكننا لا نقرأهم.",
"m1auowlo": "قم بمراجعة خدمات قالب قاعدة البيانات وإصدارات الصور والموارد والتخزين. استخدم تفاصيل الاتصال الخاصة به في تطبيقك واحتفظ بالبيانات الدائمة منفصلة عن الحاويات البديلة.",
@@ -501,7 +500,6 @@
"m1e1obop": "قم باستيراد تعريف Compose من مستودع أو ملف مكدس. راجع إعدادات الخدمة المدعومة والصور والمتغيرات والتبعيات والتخزين والمسارات العامة في خطة النشر.",
"m1e273m5": "قاعدة بيانات دائمة",
"m1e28n1s": "احتفظ بالكامل",
- "m1e5h57g": "ابتداءً من
{amount} /سنة",
"m1e6063y": "يا فريق،",
"m1e656gd": "الأسعار",
"m1e8gegw": "تثبيت",
@@ -700,7 +698,7 @@
"m1jwmklu": "، وليس فقط الجزء المحلي قبل @. يتطلب إعداد صندوق البريد الظاهري لهذا الخادم العنوان الكامل.",
"m1jwt5qq": "قم بتعيين النسخ المتماثلة للتطبيقات المدعومة أو العمال وفحص القرون الجاهزة والتوجيه. لا يتم تنفيذ القياس التلقائي المستند إلى السياسة، وتجاوز فشل البوابة التلقائية، وقياس الإنشاء من خلال مسار التطبيق هذا.",
"m1jxapmf": "مرجع CLI الكامل",
- "m1jz1ywi": "أطلق تطبيقاتك وقواعد بياناتك.",
+ "m1jz1ywi": "انشر أي شيء.",
"m1k04yvy": "عندما تريد الانتقال",
"m1k056rw": "وحدة المعالجة المركزية (CPU) وذاكرة الوصول العشوائي (RAM) والتخزين المشتركة لمشاريعك.",
"m1k0zoz9": "البريد الوارد الخاص بك، القواعد الخاصة بك. قم بإنشاء تدفقات معالجة بريد إلكتروني مخصصة تتطابق تمامًا مع كيفية تنظيمك وكتابتك والرد وعملك.",
@@ -825,7 +823,7 @@
"m1nj40hk": "راجع كيفية التعامل مع المصادقة والحسابات المتصلة وبيانات الاعتماد بواسطة النظام الأساسي.",
"m1nj6jdz": "{months} شهرًا",
"m1nkenm2": "ليست هناك حاجة إلى تثبيت سطح مكتب منفصل.",
- "m1nob2q": "وأدر بنيتك التحتية من مكان واحد.",
+ "m1nob2q": "امتلك كل شيء.",
"m1nqjs8g": "مرجع سطر الأوامر",
"m1nsamn6": "إلى الحد الأقصى الذي يسمح به القانون، لا يتحمل أي من الطرفين المسؤولية عن الأضرار غير المباشرة أو العرضية أو التبعية.",
"m1nsoqv9": "ثلاث طرق للنشر.",
@@ -1048,7 +1046,6 @@
"m1ulf8lb": "لوحة المعلومات، وCLI، والوكلاء، ومحولات البنية التحتية - كلها عامة، كلها قابلة للقراءة، وكلها قابلة للتدقيق. قم بتشغيله على Raspberry Pi أو أسطول. المساهمة مرة أخرى عندما تريد.",
"m1up62ws": "واجهة جدول بيانات بنمط Airtable للعمل مع البيانات المدعومة بـ SQL.",
"m1up7zq6": "فحص عمليات النشر والخدمات والبنية التحتية ووصول الفريق.",
- "m1upaqs9": "تُدفع سنويًا",
"m1upcpqc": "الحالة المرصودة",
"m1upw6fh": "الفئات",
"m1us78pp": "احتفظ باتصال قاعدة البيانات الخارجية، أو انسخ قاعدة البيانات التي تم تكوينها باستخدام نسخة احتياطية منطقية من عنوان URL المباشر والعام PostgreSQL مع TLS.",
@@ -1211,6 +1208,7 @@
"m2j3iur": "ما هو الجديد",
"m2j49ci": "استوديو المشرف",
"m2jum53": "تتطلب عمليات المجموعة وحدة تحكم ذاتية الاستضافة أو وحدة تحكم سطح المكتب ولا تتوفر على وحدة التحكم السحابية المستضافة.",
+ "m2k6cfa": "الفواتير السنوية متاحة أيضًا؛ تُظهر البطاقات المعادل الشهري والرسم السنوي الكامل.",
"m2k95s1": "اكتشف خدمات Docker الموجودة لديك وصورها الحالية. أعد استخدام أحمال العمل على نفس الخادم، أو قم بمراجعة النقل إلى وجهة أخرى مؤهلة.",
"m2km9co": "حسابات صندوق البريد الموجودة",
"m2kt6l9": "أو الأحدث",
@@ -1449,7 +1447,6 @@
"m9kmb0s": "خصم العملاء",
"m9lq1iz": "فحص الدلاء والكائنات من خلال المتصفح.",
"m9oivcn": "حدود الفعل",
- "m9os5hi": "إدارة مجانية لـ {count} من خوادمك",
"m9pu63g": "التوافق Redis.",
"m9pzyn4": "عملاء السحابة - التخزين الأساسي في غرب الاتحاد الأوروبي (أيرلندا) مع النسخ المتماثلة في شرق الولايات المتحدة وجنوب آسيا والمحيط الهادئ. يمكنك تثبيت مشروع في منطقة واحدة.",
"m9sa70m": "نموذج لتقدم بناء النشر وسجلات بناء الإنتاج في OpenShip.",
@@ -2167,7 +2164,6 @@
"mtzre9v": "K-9، وSpark، وEdison، وFairEmail - أي شيء يتحدث IMAP.",
"mu1k6p6": "الميزات",
"mu2i43h": "عند عرضه - غالبًا ما يختار الاكتشاف التلقائي المنفذ الخطأ.",
- "mu31ilk": "يُدفع
{amount} سنويًا",
"mu5f25e": "بالنسبة لحجم المعاملات، قم بتشغيل",
"mu5wtix": "Windows 10/11 · 64 بت",
"mu6l8j": "أذونات لكل مورد",
diff --git a/apps/web/src/i18n/messages/de.json b/apps/web/src/i18n/messages/de.json
index 51b858464..c2dbcc765 100644
--- a/apps/web/src/i18n/messages/de.json
+++ b/apps/web/src/i18n/messages/de.json
@@ -349,7 +349,6 @@
"m19ofoog": "Konfigurieren Sie Geheimnisse im Controller, der den Workflow besitzt.",
"m19scbsz": "Zahlungsbestätigung #1234",
"m19ud2w": "Planen Sie beim Verschieben von Daten zwischen Servern ein Wartungsfenster ein: Die Quelldienste werden während der Datenübertragung angehalten und das Ziel gestartet. Durch die Verwendung desselben Servers können laufende Container wiederverwendet werden, ein Wechsel des Reverse-Proxys kann jedoch den Datenverkehr kurzzeitig unterbrechen. Die Dauer hängt von Ihrer App und Übertragungsstrategie ab.",
- "m19uqmyr": "Wähle „Jährlich“, um den vollen Jahrespreis zu sehen, der einmal im Jahr bezahlt wird.",
"m19xi0mu": "Lesen und senden",
"m19zmnxd": "Für immer kostenlos · Apache 2.0",
"m1a0fr6p": "Halten Sie den Projekt- und Infrastrukturzugriff arbeitsbereichsbezogen.",
@@ -501,7 +500,6 @@
"m1e1obop": "Importieren Sie eine Compose-Definition aus einem Repository oder einer Stack-Datei. Überprüfen Sie die unterstützten Diensteinstellungen, Bilder, Variablen, Abhängigkeiten, Speicher und öffentlichen Routen im Bereitstellungsplan.",
"m1e273m5": "Persistente Datenbank",
"m1e28n1s": "Behalten Sie die Fülle",
- "m1e5h57g": "Ab
{amount} /Jahr",
"m1e6063y": "Hallo Team,",
"m1e656gd": "Preise",
"m1e8gegw": "Installieren",
@@ -1048,7 +1046,6 @@
"m1ulf8lb": "Das Dashboard, die CLI, die Agenten, die Infrastrukturadapter – alle öffentlich, alle lesbar, alle überprüfbar. Führen Sie es auf einem Raspberry Pi oder einer Flotte aus. Tragen Sie bei, wann immer Sie möchten.",
"m1up62ws": "Eine Tabellenkalkulationsschnittstelle im Airtable-Stil für die Arbeit mit SQL-gestützten Daten.",
"m1up7zq6": "Überprüfen Sie Bereitstellungen, Dienste, Infrastruktur und Teamzugriff.",
- "m1upaqs9": "Jährliche Abrechnung",
"m1upcpqc": "Beobachteter Zustand",
"m1upw6fh": "Kategorien",
"m1us78pp": "Behalten Sie Ihre externe Datenbankverbindung bei oder kopieren Sie die konfigurierte Datenbank mithilfe einer logischen Sicherung von einer direkten, öffentlichen PostgreSQL-URL mit TLS.",
@@ -1211,6 +1208,7 @@
"m2j3iur": "Was ist neu?",
"m2j49ci": "Admin-Studio",
"m2jum53": "Clustervorgänge erfordern einen selbstgehosteten oder Desktop-Controller und sind auf dem gehosteten Cloud-Controller nicht verfügbar.",
+ "m2k6cfa": "Eine jährliche Abrechnung ist ebenfalls möglich; Auf den Karten sind der Monatsäquivalent und die volle Jahresgebühr ausgewiesen.",
"m2k95s1": "Entdecken Sie Ihre bestehenden Docker-Dienste und deren aktuelle Bilder. Verwenden Sie Workloads auf demselben Server wieder oder prüfen Sie eine Verschiebung zu einem anderen geeigneten Ziel.",
"m2km9co": "Vorhandene Postfachkonten",
"m2kt6l9": "oder neuer",
@@ -1449,7 +1447,6 @@
"m9kmb0s": "Kundenrabatt",
"m9lq1iz": "Untersuchen Sie Buckets und Objekte über einen Browser.",
"m9oivcn": "Handlungsgrenzen",
- "m9os5hi": "Kostenlose Verwaltung für {count} Server",
"m9pu63g": "Redis Kompatibilität",
"m9pzyn4": "Cloud-Kunden – Primärspeicher in EU-West (Irland) mit Replikaten in USA-Ost und AP-Süd. Sie können ein Projekt einer einzelnen Region zuordnen.",
"m9sa70m": "Der Build-Fortschritt und die Produktions-Build-Protokolle einer Beispielbereitstellung in OpenShip.",
@@ -2167,7 +2164,6 @@
"mtzre9v": "K-9, Spark, Edison, FairEmail – alles, was IMAP spricht.",
"mu1k6p6": "Funktionen",
"mu2i43h": "Wenn angeboten, wählt die automatische Erkennung häufig den falschen Port aus.",
- "mu31ilk": "
{amount} , jährlich abgerechnet",
"mu5f25e": "Führen Sie Folgendes aus, um das Transaktionsvolumen zu ermitteln:",
"mu5wtix": "Windows 10/11 · 64-Bit",
"mu6l8j": "Berechtigungen pro Ressource",
diff --git a/apps/web/src/i18n/messages/en.json b/apps/web/src/i18n/messages/en.json
index 6ded648a2..d64105df5 100644
--- a/apps/web/src/i18n/messages/en.json
+++ b/apps/web/src/i18n/messages/en.json
@@ -349,7 +349,6 @@
"m19ofoog": "Configure secrets in the controller owning the workflow.",
"m19scbsz": "Payment confirmation #1234",
"m19ud2w": "Plan a maintenance window when moving data between servers: the source services stop while data transfers and the destination starts. Same-server adoption can reuse running containers, but changing the reverse proxy may briefly interrupt traffic. The duration depends on your app and transfer strategy.",
- "m19uqmyr": "Choose Yearly to see the full annual price, paid once a year.",
"m19xi0mu": "Read and send",
"m19zmnxd": "Free forever · Apache 2.0",
"m1a0fr6p": "Keep project and infrastructure access workspace-scoped.",
@@ -501,7 +500,6 @@
"m1e1obop": "Import a Compose definition from a repository or stack file. Review supported service settings, images, variables, dependencies, storage, and public routes in the deployment plan.",
"m1e273m5": "Persistent database",
"m1e28n1s": "Keep the full",
- "m1e5h57g": "From
{amount} /year",
"m1e6063y": "Hey team,",
"m1e656gd": "Pricing",
"m1e8gegw": "Install",
@@ -1048,7 +1046,6 @@
"m1ulf8lb": "The dashboard, the CLI, the agents, the infrastructure adapters - all public, all readable, all auditable. Run it on a Raspberry Pi or a fleet. Contribute back when you want to.",
"m1up62ws": "An Airtable-style spreadsheet interface for working with SQL-backed data.",
"m1up7zq6": "Inspect deployments, services, infrastructure, and team access.",
- "m1upaqs9": "Billed yearly",
"m1upcpqc": "Observed state",
"m1upw6fh": "Categories",
"m1us78pp": "Keep your external database connection, or copy its configured database using a logical backup from a direct, public PostgreSQL URL with TLS.",
@@ -1211,6 +1208,7 @@
"m2j3iur": "What's new",
"m2j49ci": "Admin studio",
"m2jum53": "Cluster operations require a self-hosted or desktop controller and are unavailable on the hosted Cloud controller.",
+ "m2k6cfa": "Yearly billing is also available; the cards show the monthly equivalent and full yearly charge.",
"m2k95s1": "Discover your existing Docker services and their current images. Reuse workloads on the same server, or review a move to another eligible destination.",
"m2km9co": "Existing mailbox accounts",
"m2kt6l9": "or newer",
@@ -1449,7 +1447,6 @@
"m9kmb0s": "Customer discount",
"m9lq1iz": "Inspect buckets and objects through a browser.",
"m9oivcn": "Action boundaries",
- "m9os5hi": "Free management for {count} servers",
"m9pu63g": "Redis compatibility",
"m9pzyn4": "Cloud customers - primary storage in EU-West (Ireland) with replicas in US-East and AP-South. You can pin a project to a single region.",
"m9sa70m": "A sample deployment’s build progress and production build logs in OpenShip.",
@@ -2167,7 +2164,6 @@
"mtzre9v": "K-9, Spark, Edison, FairEmail - anything that speaks IMAP.",
"mu1k6p6": "Features",
"mu2i43h": "when offered - auto-detection often picks the wrong port.",
- "mu31ilk": "
{amount} billed yearly",
"mu5f25e": "For transactional volume, run",
"mu5wtix": "Windows 10/11 · 64-bit",
"mu6l8j": "Per-resource permissions",
diff --git a/apps/web/src/i18n/messages/es.json b/apps/web/src/i18n/messages/es.json
index 2057cfa04..220fd3b61 100644
--- a/apps/web/src/i18n/messages/es.json
+++ b/apps/web/src/i18n/messages/es.json
@@ -349,7 +349,6 @@
"m19ofoog": "Configure secretos en el controlador propietario del flujo de trabajo.",
"m19scbsz": "Confirmación de pago #1234",
"m19ud2w": "Planifique una ventana de mantenimiento al mover datos entre servidores: los servicios de origen se detienen mientras se transfieren los datos y se inicia el destino. La adopción del mismo servidor puede reutilizar contenedores en ejecución, pero cambiar el proxy inverso puede interrumpir brevemente el tráfico. La duración depende de su aplicación y estrategia de transferencia.",
- "m19uqmyr": "Elige Anual para ver el precio anual completo, que se paga una vez al año.",
"m19xi0mu": "leer y enviar",
"m19zmnxd": "Gratis para siempre · Apache 2.0",
"m1a0fr6p": "Mantenga el acceso al proyecto y a la infraestructura dentro del ámbito del espacio de trabajo.",
@@ -501,7 +500,6 @@
"m1e1obop": "Importe una definición de Compose desde un repositorio o archivo de pila. Revise la configuración de servicios admitidos, imágenes, variables, dependencias, almacenamiento y rutas públicas en el plan de implementación.",
"m1e273m5": "Base de datos persistente",
"m1e28n1s": "mantener el lleno",
- "m1e5h57g": "Desde
{amount} /año",
"m1e6063y": "Hola equipo,",
"m1e656gd": "Precios",
"m1e8gegw": "Instalar",
@@ -1048,7 +1046,6 @@
"m1ulf8lb": "El panel, la CLI, los agentes, los adaptadores de infraestructura: todo público, todo legible, todo auditable. Ejecútelo en una Raspberry Pi o una flota. Contribuye cuando quieras.",
"m1up62ws": "Una interfaz de hoja de cálculo estilo Airtable para trabajar con datos respaldados por SQL.",
"m1up7zq6": "Inspeccione implementaciones, servicios, infraestructura y acceso del equipo.",
- "m1upaqs9": "Facturación anual",
"m1upcpqc": "Estado observado",
"m1upw6fh": "Categorías",
"m1us78pp": "Mantenga su conexión de base de datos externa o copie su base de datos configurada utilizando una copia de seguridad lógica desde una URL PostgreSQL pública y directa con TLS.",
@@ -1211,6 +1208,7 @@
"m2j3iur": "¿Qué hay de nuevo?",
"m2j49ci": "estudio de administración",
"m2jum53": "Las operaciones de clúster requieren un controlador de escritorio o autohospedado y no están disponibles en el controlador de nube alojado.",
+ "m2k6cfa": "La facturación anual también está disponible; las tarjetas muestran el equivalente mensual y el cargo anual completo.",
"m2k95s1": "Descubra sus servicios Docker existentes y sus imágenes actuales. Reutilice cargas de trabajo en el mismo servidor o revise un traslado a otro destino elegible.",
"m2km9co": "Cuentas de buzón existentes",
"m2kt6l9": "o más nuevo",
@@ -1449,7 +1447,6 @@
"m9kmb0s": "Descuento al cliente",
"m9lq1iz": "Inspeccione depósitos y objetos a través de un navegador.",
"m9oivcn": "Límites de acción",
- "m9os5hi": "Gestión gratuita de {count} servidores",
"m9pu63g": "Redis compatibilidad",
"m9pzyn4": "Clientes de la nube: almacenamiento primario en UE-Oeste (Irlanda) con réplicas en EE.UU. Este y AP-Sur. Puede anclar un proyecto a una sola región.",
"m9sa70m": "Un ejemplo de registros de compilación de producción y progreso de implementación en OpenShip.",
@@ -2167,7 +2164,6 @@
"mtzre9v": "K-9, Spark, Edison, FairEmail: cualquier cosa que hable IMAP.",
"mu1k6p6": "Características",
"mu2i43h": "cuando se ofrece, la detección automática a menudo selecciona el puerto equivocado.",
- "mu31ilk": "
{amount} facturados anualmente",
"mu5f25e": "Para volumen transaccional, ejecute",
"mu5wtix": "Windows 10/11 · 64 bits",
"mu6l8j": "Permisos por recurso",
diff --git a/apps/web/src/i18n/messages/fr.json b/apps/web/src/i18n/messages/fr.json
index 43273887a..90a2db9f3 100644
--- a/apps/web/src/i18n/messages/fr.json
+++ b/apps/web/src/i18n/messages/fr.json
@@ -349,7 +349,6 @@
"m19ofoog": "Configurez les secrets dans le contrôleur propriétaire du workflow.",
"m19scbsz": "Confirmation de paiement #1234",
"m19ud2w": "Planifiez une fenêtre de maintenance lors du déplacement de données entre serveurs : les services sources s'arrêtent pendant les transferts de données et la destination démarre. L'adoption du même serveur peut réutiliser les conteneurs en cours d'exécution, mais la modification du proxy inverse peut interrompre brièvement le trafic. La durée dépend de votre application et de votre stratégie de transfert.",
- "m19uqmyr": "Choisissez Annuel pour voir le prix annuel total, payé une fois par an.",
"m19xi0mu": "Lire et envoyer",
"m19zmnxd": "Gratuit pour toujours · Apache 2.0",
"m1a0fr6p": "Limitez l’accès aux projets et à l’infrastructure à l’espace de travail.",
@@ -501,7 +500,6 @@
"m1e1obop": "Importez une définition Compose à partir d’un référentiel ou d’un fichier de pile. Passez en revue les paramètres de service, les images, les variables, les dépendances, le stockage et les routes publiques pris en charge dans le plan de déploiement.",
"m1e273m5": "Base de données persistante",
"m1e28n1s": "Gardez le plein",
- "m1e5h57g": "À partir de
{amount} /an",
"m1e6063y": "Salut l'équipe,",
"m1e656gd": "Tarifs",
"m1e8gegw": "Installer",
@@ -1048,7 +1046,6 @@
"m1ulf8lb": "Le tableau de bord, la CLI, les agents, les adaptateurs d'infrastructure : tous publics, tous lisibles, tous auditables. Exécutez-le sur un Raspberry Pi ou une flotte. Contribuez quand vous le souhaitez.",
"m1up62ws": "Une interface de feuille de calcul de style Airtable pour travailler avec des données sauvegardées par SQL.",
"m1up7zq6": "Inspectez les déploiements, les services, l’infrastructure et l’accès des équipes.",
- "m1upaqs9": "Facturation annuelle",
"m1upcpqc": "État observé",
"m1upw6fh": "Catégories",
"m1us78pp": "Conservez votre connexion à la base de données externe ou copiez sa base de données configurée à l'aide d'une sauvegarde logique à partir d'une URL PostgreSQL directe et publique avec TLS.",
@@ -1211,6 +1208,7 @@
"m2j3iur": "Quoi de neuf",
"m2j49ci": "Studio d'administration",
"m2jum53": "Les opérations de cluster nécessitent un contrôleur auto-hébergé ou de bureau et ne sont pas disponibles sur le contrôleur Cloud hébergé.",
+ "m2k6cfa": "La facturation annuelle est également disponible ; les cartes indiquent l'équivalent mensuel et le montant annuel complet.",
"m2k95s1": "Découvrez vos services Docker existants et leurs images actuelles. Réutilisez les charges de travail sur le même serveur ou examinez un déplacement vers une autre destination éligible.",
"m2km9co": "Comptes de boîte aux lettres existants",
"m2kt6l9": "ou plus récent",
@@ -1449,7 +1447,6 @@
"m9kmb0s": "Remise client",
"m9lq1iz": "Inspectez les compartiments et les objets via un navigateur.",
"m9oivcn": "Limites des actions",
- "m9os5hi": "Gestion gratuite de {count} serveurs",
"m9pu63g": "Compatibilité Redis",
"m9pzyn4": "Clients cloud : stockage principal dans l'UE-Ouest (Irlande) avec des réplicas dans l'Est des États-Unis et l'AP-Sud. Vous pouvez épingler un projet à une seule région.",
"m9sa70m": "Un exemple de progression de la construction du déploiement et de journaux de construction de production dans OpenShip.",
@@ -2167,7 +2164,6 @@
"mtzre9v": "K-9, Spark, Edison, FairEmail – tout ce qui parle IMAP.",
"mu1k6p6": "Caractéristiques",
"mu2i43h": "lorsqu'elle est proposée, la détection automatique sélectionne souvent le mauvais port.",
- "mu31ilk": "
{amount} facturés annuellement",
"mu5f25e": "Pour le volume transactionnel, exécutez",
"mu5wtix": "Windows 10/11 · 64 bits",
"mu6l8j": "Autorisations par ressource",
diff --git a/apps/web/src/i18n/messages/ja.json b/apps/web/src/i18n/messages/ja.json
index b0dcd296e..b4b56309d 100644
--- a/apps/web/src/i18n/messages/ja.json
+++ b/apps/web/src/i18n/messages/ja.json
@@ -349,7 +349,6 @@
"m19ofoog": "ワークフローを所有するコントローラーでシークレットを構成します。",
"m19scbsz": "支払い確認 #1234",
"m19ud2w": "サーバー間でデータを移動する場合は、メンテナンス期間を計画します。データ転送中にソース サービスが停止し、宛先サービスが開始されます。同一サーバーを採用すると、実行中のコンテナを再利用できますが、リバース プロキシを変更するとトラフィックが一時的に中断される可能性があります。期間はアプリと転送戦略によって異なります。",
- "m19uqmyr": "年払いを選択すると、年に一度支払う年間料金の総額が表示されます。",
"m19xi0mu": "読んで送信する",
"m19zmnxd": "永久無料 · Apache 2.0",
"m1a0fr6p": "プロジェクトとインフラストラクチャへのアクセスをワークスペース範囲に保ちます。",
@@ -501,7 +500,6 @@
"m1e1obop": "リポジトリまたはスタック ファイルから Compose 定義をインポートします。導入計画でサポートされているサービス設定、イメージ、変数、依存関係、ストレージ、およびパブリック ルートを確認します。",
"m1e273m5": "永続的なデータベース",
"m1e28n1s": "いっぱいにしておいてください",
- "m1e5h57g": "
{amount} /年から",
"m1e6063y": "やあチーム、",
"m1e656gd": "価格設定",
"m1e8gegw": "インストール",
@@ -1048,7 +1046,6 @@
"m1ulf8lb": "ダッシュボード、CLI、エージェント、インフラストラクチャ アダプタはすべて公開されており、すべて読み取り可能で、すべて監査可能です。 Raspberry Pi またはフリートで実行します。必要に応じて貢献してください。",
"m1up62ws": "SQL ベースのデータを操作するための Airtable スタイルのスプレッドシート インターフェイス。",
"m1up7zq6": "導入、サービス、インフラストラクチャ、チームのアクセスを検査します。",
- "m1upaqs9": "年払い",
"m1upcpqc": "観測された状態",
"m1upw6fh": "カテゴリー",
"m1us78pp": "外部データベース接続を維持するか、TLS を使用して直接パブリック PostgreSQL URL から論理バックアップを使用して構成されたデータベースをコピーします。",
@@ -1211,6 +1208,7 @@
"m2j3iur": "新機能",
"m2j49ci": "管理スタジオ",
"m2jum53": "クラスター操作にはセルフホストまたはデスクトップ コントローラーが必要ですが、ホストされたクラウド コントローラーでは使用できません。",
+ "m2k6cfa": "年単位の請求も可能です。カードには、月額相当額と年間全額の料金が表示されます。",
"m2k95s1": "既存の Docker サービスとその現在のイメージを検出します。同じサーバー上のワークロードを再利用するか、別の適格な宛先への移動を検討してください。",
"m2km9co": "既存のメールボックス アカウント",
"m2kt6l9": "またはそれより新しい",
@@ -1449,7 +1447,6 @@
"m9kmb0s": "顧客割引",
"m9lq1iz": "ブラウザを通じてバケットとオブジェクトを検査します。",
"m9oivcn": "行動の境界線",
- "m9os5hi": "サーバー {count} 台を無料で管理",
"m9pu63g": "Redis の互換性",
"m9pzyn4": "クラウドのお客様 - EU 西 (アイルランド) にプライマリ ストレージがあり、米国東部と AP 南にレプリカがあります。プロジェクトを単一のリージョンに固定できます。",
"m9sa70m": "サンプル デプロイメントのビルドの進行状況と運用ビルドのログは OpenShip に記録されます。",
@@ -2167,7 +2164,6 @@
"mtzre9v": "K-9、Spark、Edison、FairEmail - IMAP を話すものなら何でも。",
"mu1k6p6": "特長",
"mu2i43h": "提供された場合、自動検出により間違ったポートが選択されることがよくあります。",
- "mu31ilk": "年額
{amount} ",
"mu5f25e": "トランザクション量については、次を実行します。",
"mu5wtix": "Windows 10/11 · 64 ビット",
"mu6l8j": "リソースごとのアクセス許可",
diff --git a/apps/web/src/i18n/messages/pt.json b/apps/web/src/i18n/messages/pt.json
index 785f30402..2c75523cc 100644
--- a/apps/web/src/i18n/messages/pt.json
+++ b/apps/web/src/i18n/messages/pt.json
@@ -349,7 +349,6 @@
"m19ofoog": "Configure segredos no controlador que possui o fluxo de trabalho.",
"m19scbsz": "Confirmação de pagamento #1234",
"m19ud2w": "Planeje uma janela de manutenção ao mover dados entre servidores: os serviços de origem param enquanto a transferência de dados e o destino são iniciados. A adoção do mesmo servidor pode reutilizar contêineres em execução, mas alterar o proxy reverso pode interromper brevemente o tráfego. A duração depende do seu aplicativo e da estratégia de transferência.",
- "m19uqmyr": "Escolha Anual para ver o preço anual total, pago uma vez por ano.",
"m19xi0mu": "Leia e envie",
"m19zmnxd": "Grátis para sempre · Apache 2.0",
"m1a0fr6p": "Mantenha o escopo do espaço de trabalho do acesso ao projeto e à infraestrutura.",
@@ -501,7 +500,6 @@
"m1e1obop": "Importe uma definição do Compose de um repositório ou arquivo de pilha. Revise as configurações de serviço suportadas, imagens, variáveis, dependências, armazenamento e rotas públicas no plano de implantação.",
"m1e273m5": "Banco de dados persistente",
"m1e28n1s": "Mantenha o completo",
- "m1e5h57g": "A partir de
{amount} /ano",
"m1e6063y": "Olá equipe,",
"m1e656gd": "Preços",
"m1e8gegw": "Instalar",
@@ -1048,7 +1046,6 @@
"m1ulf8lb": "O painel, a CLI, os agentes, os adaptadores de infraestrutura – todos públicos, todos legíveis, todos auditáveis. Execute-o em um Raspberry Pi ou em uma frota. Contribua de volta quando quiser.",
"m1up62ws": "Uma interface de planilha estilo Airtable para trabalhar com dados baseados em SQL.",
"m1up7zq6": "Inspecione implantações, serviços, infraestrutura e acesso da equipe.",
- "m1upaqs9": "Cobrado anualmente",
"m1upcpqc": "Estado observado",
"m1upw6fh": "Categorias",
"m1us78pp": "Mantenha sua conexão com o banco de dados externo ou copie seu banco de dados configurado usando um backup lógico de uma URL PostgreSQL pública e direta com TLS.",
@@ -1211,6 +1208,7 @@
"m2j3iur": "O que há de novo",
"m2j49ci": "Estúdio de administração",
"m2jum53": "As operações de cluster exigem um controlador auto-hospedado ou de desktop e não estão disponíveis no controlador de nuvem hospedado.",
+ "m2k6cfa": "O faturamento anual também está disponível; os cartões mostram o equivalente mensal e a cobrança anual completa.",
"m2k95s1": "Descubra seus serviços Docker existentes e suas imagens atuais. Reutilize cargas de trabalho no mesmo servidor ou revise uma mudança para outro destino qualificado.",
"m2km9co": "Contas de caixa de correio existentes",
"m2kt6l9": "ou mais recente",
@@ -1449,7 +1447,6 @@
"m9kmb0s": "Desconto para cliente",
"m9lq1iz": "Inspecione buckets e objetos por meio de um navegador.",
"m9oivcn": "Limites de ação",
- "m9os5hi": "Gerenciamento grátis de {count} servidores",
"m9pu63g": "Redis compatibilidade",
"m9pzyn4": "Clientes de nuvem - armazenamento primário no oeste da UE (Irlanda) com réplicas no leste dos EUA e AP-sul. Você pode fixar um projeto em uma única região.",
"m9sa70m": "Um exemplo de progresso de construção de implantação e logs de construção de produção em OpenShip.",
@@ -2167,7 +2164,6 @@
"mtzre9v": "K-9, Spark, Edison, FairEmail – qualquer coisa que fale IMAP.",
"mu1k6p6": "Recursos",
"mu2i43h": "quando oferecido - a detecção automática geralmente escolhe a porta errada.",
- "mu31ilk": "
{amount} cobrados anualmente",
"mu5f25e": "Para volume transacional, execute",
"mu5wtix": "Windows 10/11 · 64 bits",
"mu6l8j": "Permissões por recurso",
diff --git a/apps/web/src/i18n/messages/ru.json b/apps/web/src/i18n/messages/ru.json
index 2ac62b297..ce7f167b8 100644
--- a/apps/web/src/i18n/messages/ru.json
+++ b/apps/web/src/i18n/messages/ru.json
@@ -349,7 +349,6 @@
"m19ofoog": "Настройте секреты в контроллере, владеющем рабочим процессом.",
"m19scbsz": "Подтверждение платежа №1234",
"m19ud2w": "Запланируйте период обслуживания при перемещении данных между серверами: исходные службы останавливаются во время передачи данных и запускаются назначения. Внедрение одного и того же сервера может повторно использовать запущенные контейнеры, но смена обратного прокси-сервера может ненадолго прервать трафик. Продолжительность зависит от вашего приложения и стратегии передачи.",
- "m19uqmyr": "Выберите оплату за год, чтобы увидеть полную годовую стоимость, оплачиваемую раз в год.",
"m19xi0mu": "Прочтите и отправьте",
"m19zmnxd": "Бесплатно навсегда · Apache 2.0",
"m1a0fr6p": "Обеспечьте ограниченность рабочей области проекта и доступа к инфраструктуре.",
@@ -501,7 +500,6 @@
"m1e1obop": "Импортируйте определение Compose из репозитория или файла стека. Просмотрите параметры поддерживаемых служб, образы, переменные, зависимости, хранилище и общедоступные маршруты в плане развертывания.",
"m1e273m5": "Постоянная база данных",
"m1e28n1s": "Держите полный",
- "m1e5h57g": "От
{amount} /год",
"m1e6063y": "Привет, команда,",
"m1e656gd": "Цены",
"m1e8gegw": "Установить",
@@ -1048,7 +1046,6 @@
"m1ulf8lb": "Панель мониторинга, интерфейс командной строки, агенты, адаптеры инфраструктуры — все общедоступно, все доступно для чтения и аудита. Запустите его на Raspberry Pi или на автопарке. Внесите свой вклад, когда захотите.",
"m1up62ws": "Интерфейс электронных таблиц в стиле Airtable для работы с данными на основе SQL.",
"m1up7zq6": "Проверяйте развертывания, услуги, инфраструктуру и доступ групп.",
- "m1upaqs9": "Оплата за год",
"m1upcpqc": "Наблюдаемое состояние",
"m1upw6fh": "Категории",
"m1us78pp": "Сохраните подключение к внешней базе данных или скопируйте настроенную базу данных, используя логическую резервную копию с прямого общедоступного URL-адреса PostgreSQL с TLS.",
@@ -1211,6 +1208,7 @@
"m2j3iur": "Что нового",
"m2j49ci": "Админ студия",
"m2jum53": "Для операций кластера требуется автономный или настольный контроллер, и они недоступны на размещенном облачном контроллере.",
+ "m2k6cfa": "Также доступна ежегодная оплата; карты показывают ежемесячный эквивалент и полную годовую плату.",
"m2k95s1": "Откройте для себя существующие сервисы Docker и их текущие образы. Повторно используйте рабочие нагрузки на одном и том же сервере или рассмотрите возможность перехода в другое подходящее место назначения.",
"m2km9co": "Существующие учетные записи почтовых ящиков",
"m2kt6l9": "или новее",
@@ -1449,7 +1447,6 @@
"m9kmb0s": "Скидка клиента",
"m9lq1iz": "Проверяйте корзины и объекты через браузер.",
"m9oivcn": "Границы действий",
- "m9os5hi": "Бесплатное управление серверами: {count}",
"m9pu63g": "Redis совместимость",
"m9pzyn4": "Облачные клиенты — основное хранилище на западе ЕС (Ирландия) с репликами на востоке США и AP-юге. Вы можете прикрепить проект к одному региону.",
"m9sa70m": "Журналы хода сборки примера развертывания и производственной сборки в OpenShip.",
@@ -2167,7 +2164,6 @@
"mtzre9v": "K-9, Spark, Edison, FairEmail — все, что поддерживает IMAP.",
"mu1k6p6": "Особенности",
"mu2i43h": "когда предлагается - автоопределение часто выбирает неправильный порт.",
- "mu31ilk": "
{amount} при ежегодной оплате",
"mu5f25e": "Для объема транзакций запустите",
"mu5wtix": "Windows 10/11 · 64-разрядная версия",
"mu6l8j": "Разрешения для каждого ресурса",
diff --git a/apps/web/src/i18n/messages/tr.json b/apps/web/src/i18n/messages/tr.json
index 76ddc6024..cf9d7d820 100644
--- a/apps/web/src/i18n/messages/tr.json
+++ b/apps/web/src/i18n/messages/tr.json
@@ -349,7 +349,6 @@
"m19ofoog": "İş akışına sahip olan denetleyicideki gizli dizileri yapılandırın.",
"m19scbsz": "Ödeme onayı #1234",
"m19ud2w": "Verileri sunucular arasında taşırken bir bakım penceresi planlayın: veri aktarımları sırasında kaynak hizmetleri durur ve hedef başlar. Aynı sunucunun benimsenmesi, çalışan kapsayıcıları yeniden kullanabilir, ancak ters proxy'yi değiştirmek trafiği kısa süreliğine kesintiye uğratabilir. Süre, uygulamanıza ve aktarım stratejinize bağlıdır.",
- "m19uqmyr": "Yılda bir kez ödenen yıllık toplam fiyatı görmek için Yıllık seçeneğini seçin.",
"m19xi0mu": "Oku ve gönder",
"m19zmnxd": "Sonsuza kadar ücretsiz · Apache 2.0",
"m1a0fr6p": "Proje ve altyapı erişimini çalışma alanı kapsamında tutun.",
@@ -501,7 +500,6 @@
"m1e1obop": "Bir depodan veya yığın dosyasından bir Oluşturma tanımını içe aktarın. Dağıtım planındaki desteklenen hizmet ayarlarını, görüntüleri, değişkenleri, bağımlılıkları, depolamayı ve genel yolları inceleyin.",
"m1e273m5": "Kalıcı veritabanı",
"m1e28n1s": "Dolu tut",
- "m1e5h57g": "
{amount} /yıl’dan başlayan fiyatlarla",
"m1e6063y": "Hey takım,",
"m1e656gd": "Fiyatlandırma",
"m1e8gegw": "Yükle",
@@ -1048,7 +1046,6 @@
"m1ulf8lb": "Kontrol paneli, CLI, aracılar, altyapı bağdaştırıcıları; hepsi herkese açık, hepsi okunabilir, hepsi denetlenebilir. Raspberry Pi veya filo üzerinde çalıştırın. İstediğiniz zaman katkıda bulunun.",
"m1up62ws": "SQL destekli verilerle çalışmak için Airtable tarzı bir elektronik tablo arayüzü.",
"m1up7zq6": "Dağıtımları, hizmetleri, altyapıyı ve ekip erişimini inceleyin.",
- "m1upaqs9": "Yıllık faturalandırılır",
"m1upcpqc": "Gözlemlenen durum",
"m1upw6fh": "Kategoriler",
"m1us78pp": "Harici veritabanı bağlantınızı koruyun veya yapılandırılmış veritabanını, TLS ile doğrudan genel PostgreSQL URL'sinden mantıksal bir yedekleme kullanarak kopyalayın.",
@@ -1211,6 +1208,7 @@
"m2j3iur": "Yenilikler",
"m2j49ci": "Yönetici stüdyosu",
"m2jum53": "Küme işlemleri, şirket içinde barındırılan veya masaüstü denetleyici gerektirir ve barındırılan Bulut denetleyicide kullanılamaz.",
+ "m2k6cfa": "Yıllık faturalandırma da mevcuttur; kartlar aylık eşdeğeri ve tam yıllık ücreti gösterir.",
"m2k95s1": "Mevcut Docker hizmetlerinizi ve bunların mevcut görüntülerini keşfedin. Aynı sunucudaki iş yüklerini yeniden kullanın veya başka bir uygun hedefe taşıma işlemini inceleyin.",
"m2km9co": "Mevcut posta kutusu hesapları",
"m2kt6l9": "veya daha yeni",
@@ -1449,7 +1447,6 @@
"m9kmb0s": "Müşteri indirimi",
"m9lq1iz": "Kovaları ve nesneleri bir tarayıcı aracılığıyla inceleyin.",
"m9oivcn": "Eylem sınırları",
- "m9os5hi": "{count} sunucu için ücretsiz yönetim",
"m9pu63g": "Redis uyumluluk",
"m9pzyn4": "Bulut müşterileri - ABD-Doğu ve AP-Güney'deki kopyalarla AB-Batı'da (İrlanda) birincil depolama. Bir projeyi tek bir bölgeye sabitleyebilirsiniz.",
"m9sa70m": "OpenShip'de örnek bir dağıtımın derleme ilerleme durumu ve üretim derleme günlükleri.",
@@ -2167,7 +2164,6 @@
"mtzre9v": "K-9, Spark, Edison, FairEmail - IMAP konuşan her şey.",
"mu1k6p6": "Özellikler",
"mu2i43h": "teklif edildiğinde - otomatik algılama genellikle yanlış bağlantı noktasını seçer.",
- "mu31ilk": "Yıllık
{amount} faturalandırılır",
"mu5f25e": "İşlem hacmi için çalıştırın",
"mu5wtix": "Windows 10/11 · 64 bit",
"mu6l8j": "Kaynak başına izinler",
diff --git a/apps/web/src/i18n/messages/zh.json b/apps/web/src/i18n/messages/zh.json
index b6429bab7..76bd0fe8d 100644
--- a/apps/web/src/i18n/messages/zh.json
+++ b/apps/web/src/i18n/messages/zh.json
@@ -349,7 +349,6 @@
"m19ofoog": "在拥有工作流的控制器中配置机密。",
"m19scbsz": "付款确认#1234",
"m19ud2w": "在服务器之间移动数据时规划维护时段:源服务在数据传输时停止,目标服务启动。采用同一服务器可以重用正在运行的容器,但更改反向代理可能会短暂中断流量。持续时间取决于您的应用程序和传输策略。",
- "m19uqmyr": "选择按年计费,即可查看每年一次支付的全年总价。",
"m19xi0mu": "阅读并发送",
"m19zmnxd": "永远免费·Apache 2.0",
"m1a0fr6p": "保持项目和基础设施访问工作空间范围。",
@@ -501,7 +500,6 @@
"m1e1obop": "从存储库或堆栈文件导入 Compose 定义。查看部署计划中支持的服务设置、映像、变量、依赖项、存储和公共路由。",
"m1e273m5": "持久数据库",
"m1e28n1s": "保持完整",
- "m1e5h57g": "每年
{amount} 起",
"m1e6063y": "嘿团队,",
"m1e656gd": "定价",
"m1e8gegw": "安装",
@@ -1048,7 +1046,6 @@
"m1ulf8lb": "仪表板、CLI、代理、基础设施适配器——全部公开、全部可读、全部可审计。在 Raspberry Pi 或机群上运行它。当您愿意时,请做出贡献。",
"m1up62ws": "Airtable 风格的电子表格界面,用于处理 SQL 支持的数据。",
"m1up7zq6": "检查部署、服务、基础设施和团队访问。",
- "m1upaqs9": "按年计费",
"m1upcpqc": "观察状态",
"m1upw6fh": "类别",
"m1us78pp": "保持外部数据库连接,或使用逻辑备份从带有 TLS 的直接公共 PostgreSQL URL 复制其配置的数据库。",
@@ -1211,6 +1208,7 @@
"m2j3iur": "有什么新消息",
"m2j49ci": "行政工作室",
"m2jum53": "集群操作需要自托管或桌面控制器,并且在托管云控制器上不可用。",
+ "m2k6cfa": "也可按年计费;这些卡显示每月等额费用和全年费用。",
"m2k95s1": "发现您现有的 Docker 服务及其当前映像。重复使用同一服务器上的工作负载,或查看是否移动到另一个符合条件的目标。",
"m2km9co": "现有邮箱帐户",
"m2kt6l9": "或更新的",
@@ -1449,7 +1447,6 @@
"m9kmb0s": "顾客折扣",
"m9lq1iz": "通过浏览器检查存储桶和对象。",
"m9oivcn": "行动边界",
- "m9os5hi": "免费管理 {count} 台服务器",
"m9pu63g": "Redis 兼容性",
"m9pzyn4": "云客户 - 主存储位于欧盟西部(爱尔兰),副本位于美国东部和亚太南部。您可以将项目固定到单个区域。",
"m9sa70m": "OpenShip 中示例部署的构建进度和生产构建日志。",
@@ -2167,7 +2164,6 @@
"mtzre9v": "K-9、Spark、Edison、FairEmail - 任何使用 IMAP 的软件。",
"mu1k6p6": "特点",
"mu2i43h": "当提供时 - 自动检测通常会选择错误的端口。",
- "mu31ilk": "按年支付
{amount} ",
"mu5f25e": "对于交易量,运行",
"mu5wtix": "Windows 10/11 · 64 位",
"mu6l8j": "每个资源的权限",
diff --git a/apps/web/src/lib/migration-sources.ts b/apps/web/src/lib/migration-sources.ts
index d8a33639d..1618f5c52 100644
--- a/apps/web/src/lib/migration-sources.ts
+++ b/apps/web/src/lib/migration-sources.ts
@@ -46,7 +46,7 @@ export const MIGRATION_SOURCES: MigrationSource[] = [
illustration: "compose-multi-service",
title: "Your services, together",
description:
- "Import the complete selected environment into one OpenShip project. Its services stay together, using compatible GitHub sources or portable registry images.",
+ "Import the complete selected project environment. Each service becomes an OpenShip project, using its GitHub source or portable registry image.",
},
{
illustration: "persistent-storage",
@@ -58,7 +58,7 @@ export const MIGRATION_SOURCES: MigrationSource[] = [
illustration: "private-networking",
title: "Connections between services",
description:
- "Railway private addresses resolve through service names on the project's private network. Credentials, database names and connection options stay with them.",
+ "Railway private addresses become OpenShip project connections. Credentials, database names and connection options stay with them.",
},
{
illustration: "secrets-credentials",
@@ -102,7 +102,7 @@ export const MIGRATION_SOURCES: MigrationSource[] = [
},
{
q: "Can every Railway project move unchanged?",
- a: "Review checks compatibility before import. Source-built services must share a GitHub repository and deployed revision. Scheduled jobs, multiple replicas, pre-deploy commands, multiple public ports and unsupported build settings need changes first. Unresolved connections and dependency cycles also need attention. Sealed variables must be re-entered; sleeping services run continuously after import.",
+ a: "Review checks compatibility before import. Scheduled jobs, multiple replicas, pre-deploy commands, multiple public ports, unsupported build settings and non-GitHub repositories need changes first. Unresolved connections and dependency cycles also need attention. Sealed variables must be re-entered; sleeping services run continuously after import.",
},
{
q: "Will my application be offline?",
diff --git a/apps/web/src/lib/pricing.ts b/apps/web/src/lib/pricing.ts
index f512fc7f8..51a04fcad 100644
--- a/apps/web/src/lib/pricing.ts
+++ b/apps/web/src/lib/pricing.ts
@@ -85,24 +85,23 @@ export function cloudPlanSummary(plan: CloudPlan, copy: Copy): string {
export function priceParts(plan: CloudPlan, interval: "monthly" | "annual" = "monthly") {
const price = plan.price[interval];
return {
- amount: price === null ? UI.custom : price === 0 ? UI.free : money(price),
- per: price !== null && price > 0 ? (interval === "annual" ? UI.perYear : UI.perMonth) : null,
+ amount:
+ price === null
+ ? UI.custom
+ : price === 0
+ ? UI.free
+ : money(interval === "annual" ? price / 12 : price),
+ per: price !== null && price > 0 ? UI.perMonth : null,
};
}
export function cloudFrom(pricing: CloudPricing): string | null {
const plan = startingCloudPlan(pricing);
return plan ? money(plan.price.monthly) : null;
}
-export function startingCloudPlan(
- pricing: CloudPricing,
- interval: "monthly" | "annual" = "monthly",
-): PricedPlan | null {
+export function startingCloudPlan(pricing: CloudPricing): PricedPlan | null {
if (!pricing.available) return null;
return pricing.tiers.reduce
(
- (lowest, plan) =>
- plan.price[interval] != null && (!lowest || plan.price[interval]! < lowest.price[interval]!)
- ? plan
- : lowest,
+ (lowest, plan) => (!lowest || plan.price.monthly < lowest.price.monthly ? plan : lowest),
null,
);
}
diff --git a/apps/web/src/styles/landing.css b/apps/web/src/styles/landing.css
index 5ab6fa758..f366e9573 100644
--- a/apps/web/src/styles/landing.css
+++ b/apps/web/src/styles/landing.css
@@ -1571,7 +1571,7 @@
outline-offset: 5px;
}
.pp-hero {
- padding: 132px 0 44px;
+ padding: 150px 0 64px;
}
.pp-hero-inner {
text-align: center;
@@ -1586,11 +1586,6 @@
.pp-headline span {
color: var(--th-text-secondary);
}
-.pp-hero-billing {
- margin-top: 18px;
- font-size: 14px;
- color: var(--th-text-secondary);
-}
.pp-solid-cta,
.pp-plan-cta {
display: inline-flex;
@@ -1635,7 +1630,9 @@
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px 32px;
- margin-top: 32px;
+ padding-bottom: 24px;
+ margin-bottom: 32px;
+ border-bottom: 1px solid var(--th-bd-default);
}
.pp-offering-section {
padding: 48px 0;
@@ -1827,18 +1824,14 @@
text-align: end;
}
.pp-plan-support {
- display: grid;
+ display: flex;
+ align-items: center;
gap: 8px;
padding-top: 18px;
border-top: 1px solid var(--th-bd-default);
font-size: 13px;
color: var(--th-text-strong);
}
-.pp-plan-support li {
- display: flex;
- align-items: center;
- gap: 8px;
-}
.pp-plan-support svg {
flex-shrink: 0;
}
@@ -2016,7 +2009,8 @@
.pp-cloud-benefits {
grid-template-columns: 1fr;
gap: 8px;
- margin-top: 24px;
+ padding-bottom: 16px;
+ margin-bottom: 24px;
}
.pp-plans {
grid-template-columns: 1fr;
diff --git a/artifacts/project-consistency/.gitignore b/artifacts/project-consistency/.gitignore
new file mode 100644
index 000000000..d39076d5e
--- /dev/null
+++ b/artifacts/project-consistency/.gitignore
@@ -0,0 +1 @@
+/preview-app/
diff --git a/artifacts/project-consistency/after-add-postgres-form.png b/artifacts/project-consistency/after-add-postgres-form.png
new file mode 100644
index 000000000..b96f9823a
Binary files /dev/null and b/artifacts/project-consistency/after-add-postgres-form.png differ
diff --git a/artifacts/project-consistency/after-add-service.png b/artifacts/project-consistency/after-add-service.png
new file mode 100644
index 000000000..38a8b272c
Binary files /dev/null and b/artifacts/project-consistency/after-add-service.png differ
diff --git a/artifacts/project-consistency/after-app-apply.png b/artifacts/project-consistency/after-app-apply.png
new file mode 100644
index 000000000..df1ad8b86
Binary files /dev/null and b/artifacts/project-consistency/after-app-apply.png differ
diff --git a/artifacts/project-consistency/after-app-dark.png b/artifacts/project-consistency/after-app-dark.png
new file mode 100644
index 000000000..997742761
Binary files /dev/null and b/artifacts/project-consistency/after-app-dark.png differ
diff --git a/artifacts/project-consistency/after-app-dim.png b/artifacts/project-consistency/after-app-dim.png
new file mode 100644
index 000000000..6b009399d
Binary files /dev/null and b/artifacts/project-consistency/after-app-dim.png differ
diff --git a/artifacts/project-consistency/after-app-environment.png b/artifacts/project-consistency/after-app-environment.png
new file mode 100644
index 000000000..5824c9f38
Binary files /dev/null and b/artifacts/project-consistency/after-app-environment.png differ
diff --git a/artifacts/project-consistency/after-app-light.png b/artifacts/project-consistency/after-app-light.png
new file mode 100644
index 000000000..79ee3cf37
Binary files /dev/null and b/artifacts/project-consistency/after-app-light.png differ
diff --git a/artifacts/project-consistency/after-app-overview.png b/artifacts/project-consistency/after-app-overview.png
new file mode 100644
index 000000000..717da0f22
Binary files /dev/null and b/artifacts/project-consistency/after-app-overview.png differ
diff --git a/artifacts/project-consistency/after-app-with-postgres.png b/artifacts/project-consistency/after-app-with-postgres.png
new file mode 100644
index 000000000..9f0f9116e
Binary files /dev/null and b/artifacts/project-consistency/after-app-with-postgres.png differ
diff --git a/artifacts/project-consistency/after-arabic-mobile.png b/artifacts/project-consistency/after-arabic-mobile.png
new file mode 100644
index 000000000..3943f641d
Binary files /dev/null and b/artifacts/project-consistency/after-arabic-mobile.png differ
diff --git a/artifacts/project-consistency/after-mobile.png b/artifacts/project-consistency/after-mobile.png
new file mode 100644
index 000000000..96311852e
Binary files /dev/null and b/artifacts/project-consistency/after-mobile.png differ
diff --git a/artifacts/project-consistency/after-postgres-environment.png b/artifacts/project-consistency/after-postgres-environment.png
new file mode 100644
index 000000000..4407398f8
Binary files /dev/null and b/artifacts/project-consistency/after-postgres-environment.png differ
diff --git a/artifacts/project-consistency/after-project-settings.png b/artifacts/project-consistency/after-project-settings.png
new file mode 100644
index 000000000..f22d77399
Binary files /dev/null and b/artifacts/project-consistency/after-project-settings.png differ
diff --git a/artifacts/project-consistency/after-single-app.png b/artifacts/project-consistency/after-single-app.png
new file mode 100644
index 000000000..67e87a115
Binary files /dev/null and b/artifacts/project-consistency/after-single-app.png differ
diff --git a/artifacts/project-consistency/after-with-postgres.png b/artifacts/project-consistency/after-with-postgres.png
new file mode 100644
index 000000000..d66af14ad
Binary files /dev/null and b/artifacts/project-consistency/after-with-postgres.png differ
diff --git a/artifacts/project-consistency/before-after-comparison.png b/artifacts/project-consistency/before-after-comparison.png
new file mode 100644
index 000000000..24caf68a8
Binary files /dev/null and b/artifacts/project-consistency/before-after-comparison.png differ
diff --git a/artifacts/project-consistency/before-apps-services.png b/artifacts/project-consistency/before-apps-services.png
new file mode 100644
index 000000000..4a7b75d92
Binary files /dev/null and b/artifacts/project-consistency/before-apps-services.png differ
diff --git a/artifacts/project-consistency/before-settings-editor.png b/artifacts/project-consistency/before-settings-editor.png
new file mode 100644
index 000000000..c857a21eb
Binary files /dev/null and b/artifacts/project-consistency/before-settings-editor.png differ
diff --git a/artifacts/project-consistency/browser-checks.json b/artifacts/project-consistency/browser-checks.json
new file mode 100644
index 000000000..a7f83c5be
--- /dev/null
+++ b/artifacts/project-consistency/browser-checks.json
@@ -0,0 +1,68 @@
+{
+ "errors": [],
+ "checks": [
+ "single list entry",
+ "same app route after adding PostgreSQL through the real Add form",
+ "saved app env retained",
+ "untouched secret preserved",
+ "save separate from apply",
+ "draft retained across tabs",
+ "shared settings scope",
+ "service editor",
+ "light/dim/dark",
+ "mobile/Arabic overflow"
+ ],
+ "writes": [
+ {
+ "path": "/api/projects/environment-preview/env",
+ "input": {
+ "environment": "production",
+ "upserts": [
+ {
+ "key": "LOG_LEVEL",
+ "value": "debug",
+ "isSecret": false
+ }
+ ],
+ "deletes": []
+ }
+ },
+ {
+ "path": "/api/deployments",
+ "input": {
+ "projectId": "environment-preview",
+ "refresh": true
+ }
+ },
+ {
+ "path": "/api/projects/environment-preview/services",
+ "input": {
+ "name": "postgres",
+ "image": "postgres:16-alpine",
+ "build": "",
+ "dockerfile": "",
+ "ports": [
+ "5432"
+ ],
+ "dependsOn": [],
+ "environment": {
+ "POSTGRES_USER": "postgres",
+ "POSTGRES_PASSWORD": "[preview secret redacted]",
+ "POSTGRES_DB": "app"
+ },
+ "volumes": [
+ "pgdata:/var/lib/postgresql/data"
+ ],
+ "command": "",
+ "restart": "unless-stopped",
+ "enabled": true,
+ "exposed": false,
+ "domainType": "custom"
+ }
+ },
+ {
+ "path": "/api/projects/environment-preview/services/postgres/start",
+ "input": null
+ }
+ ]
+}
diff --git a/artifacts/project-consistency/index.html b/artifacts/project-consistency/index.html
new file mode 100644
index 000000000..f55793209
--- /dev/null
+++ b/artifacts/project-consistency/index.html
@@ -0,0 +1,11 @@
+Apps & Services — consistency review One Apps & Services flow The app is the first row. Adding PostgreSQL adds another row. The app keeps its URL, saved environment, and detail layout.
Open interactive preview ↗ Before / after Add a service Environment Mobile / Arabic Actual dashboard components with sample data. Saving and applying affect only the preview fixture. Existing service overrides keep their ownership.
+The starting project Before · separate application card After · the app is the first list entry
+When PostgreSQL is added One app The same app + PostgreSQL The real Add form was exercised in the browser check. The preview’s Add PostgreSQL shortcut opens the resulting state immediately.
+App overview · shared header and tabs Add PostgreSQL · existing service form
+The same environment editor website · project-owned values postgres · service-owned values Save stores values. Apply starts a runtime update. Rebuild applies build-time changes. Each panel retains the actions supported by its runtime.
+Before · environment in project Settings After · project Settings identifies shared inputs
+Themes Light Dim
+Mobile and Arabic Mobile · 390px Arabic · right to left
+Checks: stable application route through add/remove; existing overrides preserved; separate Save/Apply; untouched secrets retained; draft retained across tabs; theme and overflow checks. Browser verification details .
\ No newline at end of file
diff --git a/artifacts/project-consistency/single-to-postgres-comparison.png b/artifacts/project-consistency/single-to-postgres-comparison.png
new file mode 100644
index 000000000..d1e0d55df
Binary files /dev/null and b/artifacts/project-consistency/single-to-postgres-comparison.png differ
diff --git a/artifacts/project-consistency/validation.json b/artifacts/project-consistency/validation.json
new file mode 100644
index 000000000..8280cd30c
--- /dev/null
+++ b/artifacts/project-consistency/validation.json
@@ -0,0 +1,14 @@
+{
+ "dashboard_tests": {
+ "passed": 167,
+ "files": 11
+ },
+ "api_tests": {
+ "passed": 66,
+ "files": 3
+ },
+ "dashboard_typecheck": "passed",
+ "api_typecheck": "passed",
+ "browser": "passed; real Add form, saved env, stable route, separate save/apply, masked secrets, themes, mobile and Arabic",
+ "preview": "sample data only; no real deployment executed"
+}
diff --git a/artifacts/project-environment/after-application-apply.png b/artifacts/project-environment/after-application-apply.png
new file mode 100644
index 000000000..993e0f634
Binary files /dev/null and b/artifacts/project-environment/after-application-apply.png differ
diff --git a/artifacts/project-environment/after-application-arabic-mobile.png b/artifacts/project-environment/after-application-arabic-mobile.png
new file mode 100644
index 000000000..59e104089
Binary files /dev/null and b/artifacts/project-environment/after-application-arabic-mobile.png differ
diff --git a/artifacts/project-environment/after-application-dim.png b/artifacts/project-environment/after-application-dim.png
new file mode 100644
index 000000000..0433fde8b
Binary files /dev/null and b/artifacts/project-environment/after-application-dim.png differ
diff --git a/artifacts/project-environment/after-application-environment.png b/artifacts/project-environment/after-application-environment.png
new file mode 100644
index 000000000..4d8aa94da
Binary files /dev/null and b/artifacts/project-environment/after-application-environment.png differ
diff --git a/artifacts/project-environment/after-application-light.png b/artifacts/project-environment/after-application-light.png
new file mode 100644
index 000000000..141b6dc08
Binary files /dev/null and b/artifacts/project-environment/after-application-light.png differ
diff --git a/artifacts/project-environment/after-application-mobile.png b/artifacts/project-environment/after-application-mobile.png
new file mode 100644
index 000000000..881626cd3
Binary files /dev/null and b/artifacts/project-environment/after-application-mobile.png differ
diff --git a/artifacts/project-environment/after-apps-services-docker.png b/artifacts/project-environment/after-apps-services-docker.png
new file mode 100644
index 000000000..bcd2546c1
Binary files /dev/null and b/artifacts/project-environment/after-apps-services-docker.png differ
diff --git a/artifacts/project-environment/after-apps-services.png b/artifacts/project-environment/after-apps-services.png
new file mode 100644
index 000000000..0fa49d3de
Binary files /dev/null and b/artifacts/project-environment/after-apps-services.png differ
diff --git a/artifacts/project-environment/after-browser-checks.json b/artifacts/project-environment/after-browser-checks.json
new file mode 100644
index 000000000..1a13ed9cf
--- /dev/null
+++ b/artifacts/project-environment/after-browser-checks.json
@@ -0,0 +1,40 @@
+{
+ "source": "Actual dashboard components with intercepted sample API responses",
+ "errors": [],
+ "writes": [
+ {
+ "path": "/api/projects/environment-preview/env",
+ "input": {
+ "environment": "production",
+ "upserts": [
+ {
+ "key": "LOG_LEVEL",
+ "value": "debug",
+ "isSecret": false
+ }
+ ],
+ "deletes": []
+ }
+ },
+ {
+ "path": "/api/deployments",
+ "input": {
+ "projectId": "environment-preview",
+ "refresh": true
+ }
+ }
+ ],
+ "checks": [
+ "Read-only page load",
+ "Save preserves masked secret",
+ "Apply disabled with unsaved edits",
+ "Save does not deploy",
+ "Apply uses refresh without build",
+ "Update progress link",
+ "Reopen Settings shows the same saved values and Apply",
+ "Static and Cloud require rebuilding",
+ "No mobile overflow",
+ "Light, dim and dark",
+ "Arabic RTL mobile"
+ ]
+}
\ No newline at end of file
diff --git a/artifacts/project-environment/after-settings-editor.png b/artifacts/project-environment/after-settings-editor.png
new file mode 100644
index 000000000..b8c7fe3d7
Binary files /dev/null and b/artifacts/project-environment/after-settings-editor.png differ
diff --git a/artifacts/project-environment/app-card-comparison.png b/artifacts/project-environment/app-card-comparison.png
new file mode 100644
index 000000000..7ab5f42fb
Binary files /dev/null and b/artifacts/project-environment/app-card-comparison.png differ
diff --git a/artifacts/project-environment/before-apps-services.png b/artifacts/project-environment/before-apps-services.png
new file mode 100644
index 000000000..4a7b75d92
Binary files /dev/null and b/artifacts/project-environment/before-apps-services.png differ
diff --git a/artifacts/project-environment/before-browser-checks.json b/artifacts/project-environment/before-browser-checks.json
new file mode 100644
index 000000000..163543be1
--- /dev/null
+++ b/artifacts/project-environment/before-browser-checks.json
@@ -0,0 +1,5 @@
+{
+ "source": "Actual dashboard components with intercepted sample API responses",
+ "errors": [],
+ "writes": []
+}
\ No newline at end of file
diff --git a/artifacts/project-environment/before-settings-editor.png b/artifacts/project-environment/before-settings-editor.png
new file mode 100644
index 000000000..c857a21eb
Binary files /dev/null and b/artifacts/project-environment/before-settings-editor.png differ
diff --git a/artifacts/project-environment/index.html b/artifacts/project-environment/index.html
new file mode 100644
index 000000000..b5c6c85c7
--- /dev/null
+++ b/artifacts/project-environment/index.html
@@ -0,0 +1,14 @@
+
+
+Environment management · before and after
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/artifacts/project-environment/settings-comparison.png b/artifacts/project-environment/settings-comparison.png
new file mode 100644
index 000000000..f34799f3d
Binary files /dev/null and b/artifacts/project-environment/settings-comparison.png differ
diff --git a/artifacts/project-environment/validation.json b/artifacts/project-environment/validation.json
new file mode 100644
index 000000000..b7259e960
--- /dev/null
+++ b/artifacts/project-environment/validation.json
@@ -0,0 +1,16 @@
+{
+ "tests": {
+ "passed": 119,
+ "files": 8
+ },
+ "dashboardTypecheck": "passed",
+ "browser": "See after-browser-checks.json",
+ "galleryImages": 7,
+ "translations": {
+ "missing": 0,
+ "extra": 0,
+ "changedEnvironmentStrings": "passed",
+ "unrelatedUntranslatedStrings": 511
+ },
+ "liveDeploymentExecuted": false
+}
\ No newline at end of file
diff --git a/bun.lock b/bun.lock
index abd3f92cd..38011b2f5 100644
--- a/bun.lock
+++ b/bun.lock
@@ -221,7 +221,7 @@
"ignore": "^7.0.5",
"ioredis": "^5.10.0",
"ipaddr.js": "^2.4.0",
- "oblien": "3.0.2",
+ "oblien": "2.10.0",
"ssh2": "^1.17.0",
"tar-fs": "^2.1.4",
"undici": "^7.30.2",
@@ -2732,7 +2732,7 @@
"object.assign": ["object.assign@4.1.7", "", { "dependencies": { "call-bind": "^1.0.8", "call-bound": "^1.0.3", "define-properties": "^1.2.1", "es-object-atoms": "^1.0.0", "has-symbols": "^1.1.0", "object-keys": "^1.1.1" } }, "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw=="],
- "oblien": ["oblien@3.0.2", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.27.1", "ws": "^8.18.3" }, "bin": { "oblien": "dist/cli/index.js", "oblien-mcp": "dist/mcp/index.js" } }, "sha512-f2hP0e9ujrL/H7eCP7mwAlnpmVa7OSDEgQGFEjwEXaSZUYJlBUwcZx+MPsTU3RNjlRj1tVpCRSa9PT3qi8zkNA=="],
+ "oblien": ["oblien@2.10.0", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.27.1", "ws": "^8.18.3" }, "bin": { "oblien": "dist/cli/index.js", "oblien-mcp": "dist/mcp/index.js" } }, "sha512-ESdeDWuIJ+R0fJtTjHAhU1VRGOqjUtxqMZeL3sm2AgkI4/1nf1FjrqKvha2zsd9nfkbzpJuYwzOOOtQUdhv1hQ=="],
"obug": ["obug@2.2.1", "", {}, "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q=="],
@@ -3892,8 +3892,6 @@
"micromatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
- "mindwire/oblien": ["oblien@2.10.0", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.27.1", "ws": "^8.18.3" }, "bin": { "oblien": "dist/cli/index.js", "oblien-mcp": "dist/mcp/index.js" } }, "sha512-ESdeDWuIJ+R0fJtTjHAhU1VRGOqjUtxqMZeL3sm2AgkI4/1nf1FjrqKvha2zsd9nfkbzpJuYwzOOOtQUdhv1hQ=="],
-
"minipass-collect/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
"minipass-fetch/minipass": ["minipass@3.3.6", "", { "dependencies": { "yallist": "^4.0.0" } }, "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw=="],
@@ -4218,8 +4216,6 @@
"bytesmap/better-auth/jose": ["jose@6.2.13", "", {}, "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ=="],
- "bytesmap/mindwire/oblien": ["oblien@2.10.0", "", { "dependencies": { "@modelcontextprotocol/sdk": "^1.27.1", "ws": "^8.18.3" }, "bin": { "oblien": "dist/cli/index.js", "oblien-mcp": "dist/mcp/index.js" } }, "sha512-ESdeDWuIJ+R0fJtTjHAhU1VRGOqjUtxqMZeL3sm2AgkI4/1nf1FjrqKvha2zsd9nfkbzpJuYwzOOOtQUdhv1hQ=="],
-
"cacache/glob/minimatch": ["minimatch@5.1.9", "", { "dependencies": { "brace-expansion": "^2.0.1" } }, "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw=="],
"cacache/minipass/yallist": ["yallist@4.0.0", "", {}, "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A=="],
diff --git a/docs/backups.md b/docs/backups.md
index 7f56b80d0..c34d0e5b2 100644
--- a/docs/backups.md
+++ b/docs/backups.md
@@ -46,54 +46,6 @@ completion or disconnect removes the subscription and timer. The dashboard ticks
elapsed time independently, updates history in place, and shows the current phase
and transferred bytes without inventing a percentage for an unknown capture size.
-## Mail-server backups and migration
-
-Use **Emails → server → Backup** for mail data. It uses the same destinations,
-workers, integrity checks, retention and restore confirmation as other backups.
-New policies include message data and keys by default. Existing policies retain
-explicit exclusions; review them before relying on a backup for disaster recovery.
-
-The archive contains the complete `vmail` database schema and rows, including
-aliases, forwards, mailing lists, BCC/relay rules, quotas, and `mail_app` settings.
-The mail stack's `amavisd`, `iredapd` and `fail2ban` PostgreSQL databases are included
-when present. It never dumps unrelated databases or cluster-wide role passwords.
-With message data enabled it also captures the whole `/var/vmail` tree, Postfix's
-queued messages, and Amavis quarantine/filter data. With keys enabled it includes
-DKIM private keys and portable mail-server state, including managed mailbox and
-outbound-relay credentials. These are secrets: protect access to the destination.
-Mailbox stores must use the managed `/var/vmail` root, including bind mounts or a
-symlink at that root. A different configured root is refused before pausing mail,
-rather than reporting a full backup that omitted it.
-
-Full captures pause Postfix, Dovecot, Amavis and iRedAPD while copying the snapshot.
-Allow a maintenance window proportional to message volume and destination speed.
-Previously running daemons resume when capture succeeds or fails; daemons already
-stopped are not started. Bare installs use the existing local command transport;
-remote servers use the same flow over SSH. Local workload execution remains
-forbidden on a SaaS controller.
-
-**Restore** replaces the current server's data. **Migrate** restores to another
-registered, installed mail server with the **same primary domain**. Prepare that
-server first with a compatible PostgreSQL/mail version and the mail database roles;
-restoring does not install an operating system or daemons. The destination's engine,
-TLS installation and database-role credentials stay authoritative. Restored mailbox
-and relay credentials are encrypted for the destination controller. DKIM/DNS/relay
-setup uses the same operations as normal mail administration. The target registration
-is updated, while DNS and PTR acknowledgement is cleared for review before cutover.
-Moving mail does not automatically repoint public DNS or the instance SMTP settings.
-
-Each PostgreSQL database restores in a transaction. The complete operation spans
-multiple databases and filesystem stores, so it is not one atomic transaction.
-If a write or configuration recovery fails, the restore reports failure and leaves
-mail stopped for review/retry. Cancellation also stops the active restore command.
-Private staging files are removed after normal success/failure cleanup.
-
-Legacy archives keep their recorded restore command and their original contents;
-an old archive cannot recover messages, tables or state it never captured. Take a
-new full backup after updating. Settings → Instance export remains a control-plane
-export and does **not** include mailbox payloads by default; use the mail archive
-for mail recovery rather than treating an instance JSON export as a message backup.
-
## Global backup pages
`/backups` shows recent runs across destinations, with service/project names,
diff --git a/docs/client-icons.md b/docs/client-icons.md
index 254e0728e..c96aa8ded 100644
--- a/docs/client-icons.md
+++ b/docs/client-icons.md
@@ -165,8 +165,6 @@ Charts, progress geometry, topology edges, decorative illustrations, and the
Openship wordmark remain vectors. Dynamic application/framework/provider logos,
favicons, flags, and user artwork retain their existing content sources. The
separate marketing site and `apps/email/client` are outside this pass.
-The marketing language switcher reuses the catalog's `languages` icon, with the
-same original PNG bundled in `apps/web/public/icons` and the shared mask renderer.
## Asset provenance
diff --git a/docs/cloud-plan-enforcement.md b/docs/cloud-plan-enforcement.md
index f7427e843..8a9f2bc1f 100644
--- a/docs/cloud-plan-enforcement.md
+++ b/docs/cloud-plan-enforcement.md
@@ -12,7 +12,7 @@ Cloud quota gates.
| Scale | $119 | 8 vCPU | 32 GB | 600 GB | 50 | 100 | 20 |
Annual charges are $120, $240, $468 and $1,188 respectively, paid upfront.
-Yearly prices display these full annual amounts per year. Both intervals
+Their displayed monthly equivalents are $10, $20, $39 and $99. Both intervals
use the same capacity and application limits. Catalog changes do not rewrite
existing paid subscription terms or their renewal prices.
diff --git a/docs/dashboard-design.md b/docs/dashboard-design.md
index b7a1b30f8..b4402ac29 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.
@@ -123,15 +116,7 @@ managed image defaults from the stack's runtime policy; show incompatible custom
Blank resets an image override. Unsupported destinations explain which source or server owns the
runtime, and saved overrides remain visible so users can clear them. Static Docker builds show
only the build image. Do not repeat these fields under Advanced. The saved project Configuration
-form reuses these same fields inline, with a separate save action.
-Apps & Services lists the primary app from the start. Adding infrastructure keeps
-its identity, route and detail tabs. App Settings owns build and runtime configuration;
-project Settings always owns shared environment, resource limits and build-cache policy.
-Workload Environment edits inline through the shared environment panel. For a single app,
-Project Settings links to its Environment tab, like the app Settings shortcut. Projects with
-companion services open the shared-variable editor; service overrides retain their source review. Saving never
-deploys implicitly. App and service Domains show their own routes; routing policy and
-route rules stay in project Domains. Keep these owners stable as services are added.
+card shows the selected runtime version.
Build-location choices and summaries describe execution, independently of source cloning.
Keep local building in the destination's advanced controls only when the runtime supports it.
Remote Docker, static sandbox, service, managed Cloud and cluster builds name their build
@@ -181,9 +166,6 @@ The banner settings menu can hide runtime security banners, including critical o
for the current browser/account/workspace. Settings → Notifications restores them.
Keep this visibility choice separate from security checks, notification delivery and
per-project automatic-refresh consent. Operator maintenance notices stay independent.
-Managed Cloud's global update banner shows only verified workload-security notices.
-It skips installation releases, upgrade prompts and the operator-announcements feed;
-Desktop and self-hosted instances retain those feeds.
When the signed advisory has no patched release in the observed runtime's major,
show the required version-change guidance and open the existing saved deployment
configuration. Do not offer another image refresh as a fix or silently upgrade a major.
@@ -516,8 +498,6 @@ Instance relocation has one entry in **Settings → Instance → Instance locati
the control plane, connecting a Desktop, and backup/archive recovery distinct. Reuse the
shared server selector and option cards for API-only versus API + dashboard. Show progress
and recovery in the same card; do not add another direct-transfer or Team migration wizard.
-During server preparation, View deployment opens the saved build view. Hide that action
-while the source is fenced for transfer, when ordinary deployment reads are unavailable.
Keep **Connect to an existing instance** and **Move to a server** visible on Desktop.
A connected Desktop shows **Reconnect** and **Move back to Desktop**. An active server
shows **Connect a Desktop**, **Move to another server**, and **Move to Desktop**.
@@ -789,11 +769,10 @@ check retryable before starting the move.
- Cloud plan purchases place the compact Monthly / Yearly control before Plans / Custom
in the same purchase header. Use the existing secondary fill for the selected interval;
do not add a decorative ring or another label row.
- Default new purchases to Monthly, while preserving a saved
- subscription or an explicit purchase intent. Show it only when the provider enables annual purchases.
- Yearly cards display the full annual price per year, with the catalog's free-month savings below;
- checkout charges that full year. Custom totals, breakdowns and extra-resource rates use the
- same selected period. Custom resets its quote
+ Default new purchases to Yearly, while preserving a saved
+ subscription or an explicit monthly purchase intent. Show it only when the provider enables annual purchases.
+ Yearly cards display a monthly equivalent with the full annual charge directly below;
+ checkout charges that full year. Custom uses the same interval and resets its quote
on interval changes. Existing subscriptions keep their saved interval; Manage remains
monthly. Disable interval changes during checkout and never reuse a quote from another
interval. Do not add another product navigation or price calculator.
@@ -885,14 +864,6 @@ check retryable before starting the move.
cancellation actions in the selected server's billing card, preserve retry
identity after uncertain responses, and never replace the page with a loader.
- Checkout returns verify payment, paid coverage and managed-server readiness separately.
- Open the hosted URL only after checkout is ready; never reserve an empty browser tab.
- Keep a full-width primary checkout action visible if the browser refuses the popup,
- and preserve the project draft. Lock repeat submissions after a successful handoff.
- Reopening Add Cloud space recovers an unfinished subscription before creating another
- space; manual retries retain a customer-scoped creation key across modal dismissal.
- Plans & billing shows a warning count for pending Cloud plans and Manage payment.
- Reuse the organization-wide payment read in the hub and refresh warnings after mutations
- and on return from checkout. Hide zero counts and reset private state on scope changes.
Show the subscription welcome only when setup is complete. Keep preparation and failure
notices compact and above the billing columns, with a recheck action and a link to the existing server Activity tab
for logs and retry. A paid setup failure must never direct the customer to pay again.
@@ -1001,28 +972,6 @@ is an explicit refresh, not an automatic SSH request when the page opens. Show
proxy overrides only for targets that apply them, preserving stored values when
editing other routing rules.
-Literal edge responses live in **Virtual routes** inside each domain card. Single apps,
-Compose services, and project domains use the same `DomainResponseRoutes` list and editor;
-do not add a second Settings form or a page for each path. The shared dialog edits path,
-exact/prefix matching, HTTP status, content type, content, headers, and optional methods.
-Keep its header and Save/Cancel footer fixed while the form body scrolls. On wide screens,
-place response content beside the headers/methods sidebar; stack these on mobile. Use visible
-filled field surfaces within the modal, label the custom content type, and switch the body
-editor between content and an escaped response preview in one compact toolbar.
-Default to exact GET/HEAD matching. Preview content as escaped text, never executable HTML.
-Keep existing drafts on failed saves and distinguish a failed list read from an empty list.
-Show **Saved and applied** only after edge acknowledgement; otherwise show saved/pending and
-point to the domain's existing routing retry. Saves do not trigger an app deployment.
-
-Virtual routes use the existing domain-scoped route-rule API and storage, but stay out of
-the access-policy editor. They run after access policies, rate limits, and password checks.
-The longest matching path wins, with exact before prefix at the same path; prefixes match
-path boundaries. Query strings are ignored. Response content is literal UTF-8 text up to
-64 KiB. Reserved platform and ACME paths are excluded. Offer the editor for domains served
-by the OpenShip edge; Cloud, cluster, external-ingress, and redirect-only domains do not
-support it. Older edges retain their access policies and report responses as pending until
-their scripts are updated and the edge is reloaded.
-
Project and service route saves share the same inline preparation and HTTPS progress viewer.
The first exposed route retains proxy takeover consent and completes domain checks after edge
setup. New custom hostnames on an existing edge use the existing project routing/HTTPS check;
@@ -1072,17 +1021,7 @@ 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.
-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
-need new addresses. Link once per imported project to the existing Domains & Routes flow for
-destination records and verification; do not duplicate DNS editors or imply cutover is automatic.
-Show provider marks through `AppLogo` and service marks through `ServiceIcon`. Reuse the Connections
+provider marks through `AppLogo` and service marks through `ServiceIcon`. Reuse the Connections
form for authorization and tokens, with an explicit access test and retry. The provider import
heading and Change source action belong in one compact `bg-card p-5` sidebar
throughout setup and review. Use the standard 340px right column across these steps, with
@@ -1094,16 +1033,11 @@ owns submission and validation even when its native form buttons appear in the s
API token inputs show the
entered text with autocomplete, capitalization and correction disabled; they retain secret
storage and never prefill saved token values. Keep service cards
-compact; expand configuration for missing secrets and review blockers. Within configuration,
-show environment fields directly under a heading; do not nest another disclosure or change
-their visibility when a missing value is supplied. The final review lists
+compact; expand configuration for missing secrets and review blockers. The final review lists
what will be copied, kept external or started empty, and collects any required source-pause
acknowledgments. Changing the source, destination or selections invalidates that review.
Use the shared destination picker and durable migration progress; never add a preview-only
import path or claim that metadata access verifies a data transfer.
-The shared destination picker stays a dropdown even with one available server or plan.
-Keep Add server in its menu so selection and acquisition use the same control across
-deployment, migration and setup forms. Explicit read-only bindings remain summaries.
Stopping an import is a durable request. Keep Stopping visible across refreshes until the
worker finishes transfer cancellation and recovery. Retain saved projects and copied data;
never show completion merely because the cancellation request was accepted.
diff --git a/docs/installation.md b/docs/installation.md
index ffd095be7..756a9f1dc 100644
--- a/docs/installation.md
+++ b/docs/installation.md
@@ -94,7 +94,7 @@ Fix by moving Docker's data-root to a native `ext4`/`xfs` disk (`/etc/docker/dae
## Users & access (self-hosted)
-- **Create the first admin on the server.** Run `openship` and choose **Create first admin**, or use `openship up --non-interactive --admin-email ` with `OPENSHIP_ADMIN_PASSWORD` set. The same setup works for CLI-managed Compose installs. Public signup stays disabled; everyone after joins by invite.
+- **Public signup is disabled after the first account.** The first admin comes from the `openship` setup wizard; with `openship up --compose` (or raw Docker) you register the first account in the dashboard. Everyone after joins by invite.
- **Invite teammates** from **Settings → Team**. They get an accept link at your instance's URL (so the instance needs to be reachable — a public URL or your LAN).
- **Lost the admin password?** Run `openship reset-admin-password` on the box (no sign-in needed; uses the local internal token).
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/managed-cloud-servers.md b/docs/managed-cloud-servers.md
index 6d2858c3d..2ab754f07 100644
--- a/docs/managed-cloud-servers.md
+++ b/docs/managed-cloud-servers.md
@@ -212,13 +212,11 @@ root-equivalent access to this server, not project-scoped access. Direct SSH/SDK
clients run outside Openship's deployment queue; administrators must coordinate
their own commands with application work.
-The provider Runtime endpoint defaults to `https://vm.oblien.com` and can
-be overridden with `OBLIEN_RUNTIME_URL`. These controls use Oblien SDK 3.0.2 and
-require the matching native VM API/gateway and fresh scoped credentials. Follow
-the [SDK 3 cutover instructions](openship-cloud-launch.md#oblien-sdk-3-and-versioned-api-activation),
-including the Desktop/self-hosted client rollout. Deploy the Openship API and
-dashboard from the same release. Existing OpenShip server response shapes are
-unchanged. Detailed network reads opt in with
+The provider Runtime endpoint defaults to `https://workspace.oblien.com` and can
+be overridden with `OBLIEN_RUNTIME_URL`. All provider methods used here are in
+Oblien SDK 2.10.0; no new provider SDK release is required. Deploy the Openship API
+and dashboard from the same release to use the new controls. Existing server
+response shapes are unchanged. Detailed network reads opt in with
`getNetworkSettings(id, { details: true })` / `?details=true`; writes return
diagnostics only when the caller supplies `expectedRevision`, preserving the
original internet-only contract for older clients.
diff --git a/docs/openship-cloud-launch.md b/docs/openship-cloud-launch.md
index 51b2f7784..033bf2aa8 100644
--- a/docs/openship-cloud-launch.md
+++ b/docs/openship-cloud-launch.md
@@ -582,6 +582,7 @@ assuming the `.env.saas` filename indicates production provider credentials.
```dotenv
CLOUD_MODE=true
OPENSHIP_TARGET=cloud-saas
+ OBLIEN_API_URL=https://api.oblien.com
OBLIEN_CLIENT_ID=
OBLIEN_CLIENT_SECRET=
OBLIEN_WEBHOOK_SECRET=
@@ -804,39 +805,3 @@ and database migration `0153_durable_credit_alerts` before rolling out the API a
[Namespace credit alerts](namespace-credit-alerts.md) is the reference for delivery guarantees,
provider requirements, organization isolation, and verification.
-
-## Oblien SDK 3 and versioned API activation
-
-Cloud uses the native VM contract from Oblien SDK 3.0.2. The SDK owns its default
-control-plane base URL and API version; leave `OBLIEN_API_URL` unset. If an
-operator needs a proxy, the override must be the complete API mount including
-its version. Remove a previously configured unversioned provider origin during
-the coordinated cutover.
-
-The custom checkout browser page remains `https://api.oblien.com/billing/pay`.
-Only its control-plane creation/status requests use `/v1`; do not rewrite the
-returned payment URL or apply the API mount to Runtime/CDN URLs.
-
-Activate the matching Oblien `/v1` API and migrated database before deploying
-this integration. Older SDK routes are not probed and failed writes are not
-replayed. OpenShip's organization/workspace records, managed-server IDs, paid
-offer snapshots and customer metadata retain their existing identities. The
-provider boundary maps those saved workspace counts to native VM capacity.
-
-The matching runtime gateway is `https://vm.oblien.com`; remove or update any
-old `OBLIEN_RUNTIME_URL` override. Runtime credentials must carry `type: "vm"`
-and the selected `vm_id`. Namespace/account tokens are never runtime credentials.
-
-This cutover also requires a Desktop/self-hosted release containing SDK 3 for
-installations that use Cloud servers. Those clients execute provider requests
-directly using scoped tokens; redeploying the hosted API alone cannot upgrade
-their SDK 2 transport. Coordinate that client rollout with the provider cutover,
-and obtain fresh credentials. Existing VM IDs, disks, and project data must be
-preserved. Self-hosted local/SSH-only deployments do not use this provider API.
-
-Before reopening customer operations, run `bun run --cwd apps/api cloud:check`
-with the deployed Cloud environment and both explicit staging verification
-scripts (`verify-cloud-docker.ts` and `verify-cloud-isolation.ts`) against the
-matching API/gateway. Verify an existing VM in addition to disposable creation,
-exec/files, routing, namespace isolation and cleanup. Local HTTP fixtures and
-unit tests do not establish that the provider deployment has been activated.
diff --git a/docs/platform-migrations.md b/docs/platform-migrations.md
index e72b03223..5c7d85f2b 100644
--- a/docs/platform-migrations.md
+++ b/docs/platform-migrations.md
@@ -6,23 +6,16 @@ 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, distinct destination project names, a managed plan or connected server, and whether to copy storage or explicitly start empty. 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.
-
-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;
-cross-project claims and invalid routes stop admission. It never reconstructs DNS records from source hostnames or mutates DNS during
-import. The existing Domains & Routes flow owns route configuration, DNS records, supported
-provider automation and verification. The same guidance is shown before admission and when
-reopening a saved run; confirmation remains an operator acknowledgment, not an automated DNS check.
+5. Allow Railway project downtime and pause external deployment automation. The worker prepares the selected managed Cloud host before source downtime, creates all destination projects, disables automatic push deployments, stops the entire source environment and copies its volumes before deploying any destination. Private addresses become normal project connections with encrypted value templates; only the hostname changes, including when those connections refresh on redeploy.
+6. Follow progress, logs and project links at `/migrations/`, including after a browser refresh. Add a test domain through each project's Domains & Routes, verify the applications, move the existing domains, and confirm completion. Retire the old provider resources separately.
## What transfers
| 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, multi-host connection variables, 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 +27,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 preserve ordinary Openship build roles and release commands. Railway pre-deploy commands, cron, replica topology, unsupported Vercel configuration and invalid paths block review rather than being dropped. 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,64 +63,8 @@ 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
-two Redis services and a worker, through both Docker and Cloud runtime adapters.
-It uses the real migrated control database, review planner, import worker, encrypted
-service environments, volume transfer and native Compose deployment engine. Both
-projects deliberately reuse the same service names: assertions check project and
-service counts, private DNS, separate secrets and volumes, copied data and new writes
-after restart. The worker also serves an HTTP health endpoint: its imported custom
-domain and alias retain the correct service/port and remain unverified, while its
-Railway-owned URL is excluded. Persisted routing tests additionally cover Cloud-owned
-targets, idempotent domain staging and cross-organization hostname conflicts. Public
-DNS cutover is not exercised by these fixtures. The provider control/SSH boundary and asynchronous build queue are
-substituted. The Cloud provider tunnel connects to the test Docker daemon; this is
-not a live SaaS test.
-
-A live Railway project with two Redis volumes and an Alpine worker also passed
-discovery, SSH access, whole-project pause, cold copy, grouped native deployment,
-private service connections and restart persistence on a local Docker destination.
-The original Railway images and commands were restored with the source workloads
-stopped, and its temporary SSH
-key was revoked. The disposable project was removed after verification; the existing
-user project was retained. Railway's account resource limit prevented a second live
-project, so simultaneous two-project isolation is covered by the repeatable Docker
-suite above. Sanitized live evidence is
-`/tmp/openship-railway-grouping-live-evidence.json`.
-
-The grouped flow then passed a separate **live Railway → OpenShip Cloud** run on
-a real managed VM (2 vCPUs, 4 GB RAM). This used the current engine in Cloud mode,
-the normal saved-credential verification, namespace token issuance, managed host
-provisioning, volume transfer, deployment admission/queue and runtime. One source
-project became one destination project with all three services. Both Redis datasets,
-encrypted service environments and private DNS were verified on the Cloud VM.
-After new Redis writes and per-service environment changes, a normal redeployment
-replaced all three containers; the original data, new writes, updated environments
-and service connections all remained correct. Source configuration restoration and
-temporary SSH-key revocation were also confirmed. Only subscription entitlement
-was a test fixture; this does not verify checkout or browser sign-in. Sanitized
-evidence is `/tmp/openship-grouped-cloud-live-evidence.json`.
-The disposable Cloud VM, namespace and Railway project were removed after the run.
-
### Live API and data verification — 2026-11-11 (UTC+2)
-These historical runs predate project grouping; the current grouped-flow checks are
-documented above.
-
| Direction | Result | Verified workload and behavior |
| ------------------------------- | --------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Railway → SSH server | Passed | Four services: PostgreSQL, Redis, SQLite and files; private connections, new writes and recreation of all services through the normal deployment API |
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/docs/ship-sdk-relocations.json b/docs/ship-sdk-relocations.json
index cb718a670..a8f3a3db5 100644
--- a/docs/ship-sdk-relocations.json
+++ b/docs/ship-sdk-relocations.json
@@ -1501,12 +1501,6 @@
"to": "packages/platform/src/engine/modules/jobs/job.types.ts",
"hadBaseline": true
},
- {
- "from": "apps/api/src/modules/mail/admin/backup-plan.ts",
- "to": "packages/platform/src/engine/modules/mail/backup-plan.ts",
- "hadBaseline": true,
- "baselineCommit": "367afdec910ee096bc3427ff52a881aa44025bde"
- },
{
"from": "apps/api/src/modules/mail/admin/domain-dns.service.ts",
"to": "packages/platform/src/engine/modules/mail/admin/domain-dns.service.ts",
diff --git a/package.json b/package.json
index 8e759cd00..a46597d0b 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "@repo/workspace",
- "version": "0.9.12",
+ "version": "0.9.11",
"description": "Open-source, self-hostable deployment platform",
"license": "Apache-2.0",
"repository": {
diff --git a/packages/adapters/package.json b/packages/adapters/package.json
index 4077f40fe..858f55356 100644
--- a/packages/adapters/package.json
+++ b/packages/adapters/package.json
@@ -46,7 +46,7 @@
"ignore": "^7.0.5",
"ioredis": "^5.10.0",
"ipaddr.js": "^2.4.0",
- "oblien": "3.0.2",
+ "oblien": "2.10.0",
"ssh2": "^1.17.0",
"tar-fs": "^2.1.4",
"undici": "^7.30.2",
diff --git a/packages/adapters/scripts/verify-cloud-docker.ts b/packages/adapters/scripts/verify-cloud-docker.ts
index 6e7ab79bb..04b06e02d 100644
--- a/packages/adapters/scripts/verify-cloud-docker.ts
+++ b/packages/adapters/scripts/verify-cloud-docker.ts
@@ -10,7 +10,6 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import { randomUUID } from "node:crypto";
import { Oblien } from "../src/oblien";
-import { oblienApiBaseUrl, oblienApiUrl } from "../src/oblien-contract";
import { CloudDockerRuntime } from "../src/runtime/cloud/docker";
import { CloudProcessSupervisor } from "../src/runtime/cloud/process-supervisor";
import { cloudDockerProjectPaths } from "../src/runtime/cloud/docker-paths";
@@ -34,7 +33,7 @@ const domainFlag = process.argv.indexOf("--public-domain");
const publicDomain = domainFlag >= 0 ? process.argv[domainFlag + 1]! : "opsh.io";
if (!publicDomain || !/^[a-z0-9.-]+$/.test(publicDomain))
throw new Error("Invalid public test domain");
-const baseUrl = oblienApiBaseUrl(configuration.OBLIEN_API_URL).toString();
+const baseUrl = configuration.OBLIEN_API_URL || "https://api.oblien.com";
const presetFlag = process.argv.indexOf("--preset");
const softwarePreset = presetFlag >= 0 ? process.argv[presetFlag + 1] : undefined;
if (presetFlag >= 0 && (!softwarePreset || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(softwarePreset)))
@@ -94,7 +93,7 @@ try {
name: tag,
slug: tag,
type: "testing",
- resource_limits: { max_vms: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 },
+ resource_limits: { max_workspaces: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 },
});
namespaceId = created.data.id;
await save();
@@ -104,7 +103,7 @@ try {
quotaLimit: 100,
overdraft: 0,
suspendThreshold: 0,
- onOverdraftAction: "stop_vms",
+ onOverdraftAction: "stop_workspaces",
});
const token = await admin.tokens.create({ scope: "namespace", namespace: tag, ttl: 1800 });
const client = new Oblien({ token: token.token, baseUrl });
@@ -128,11 +127,11 @@ try {
network_config: { allow_internet: true, public_ingress: false },
},
};
- const workspace = await client.vms.create(createOptions);
+ const workspace = await client.workspaces.create(createOptions);
workspaceId = workspace.id;
await save();
check("workspace created in test namespace", workspace.namespace === tag && workspaceId);
- const replay = await client.vms.create(createOptions);
+ const replay = await client.workspaces.create(createOptions);
check("provider idempotency reuses workspace", replay.id === workspaceId);
const progress = setInterval(() => log("waiting for Docker workspace"), 20_000);
try {
@@ -141,13 +140,13 @@ try {
clearInterval(progress);
}
log("Docker workspace ready");
- await client.vm(workspaceId).lifecycle.makePermanent();
+ await client.workspace(workspaceId).lifecycle.makePermanent();
check(
"managed server can be made permanent",
- (await client.vms.get(workspaceId)).mode === "permanent",
+ (await client.workspaces.get(workspaceId)).mode === "permanent",
);
await client
- .vm(workspaceId)
+ .workspace(workspaceId)
.lifecycle.makeTemporary({ ttl: "20m", ttl_action: "remove", remove_on_exit: false });
const pageMethods = [
"list",
@@ -171,7 +170,7 @@ try {
return { ...result, pages: result.pages.filter((page) => page.namespace === tag) };
};
adminPages.create = async (input) => {
- if (input.vm_id !== workspaceId || !input.slug?.startsWith(tag))
+ if (input.workspace_id !== workspaceId || !input.slug?.startsWith(tag))
throw new Error("Smoke route escaped its workspace");
pages.add(input.slug);
await save();
@@ -474,7 +473,7 @@ try {
await runtime.stop(second.containerId);
check(
"service stop preserves workspace and sibling",
- isDockerWorkspaceRunning(await client.vms.get(workspaceId)) &&
+ isDockerWorkspaceRunning(await client.workspaces.get(workspaceId)) &&
(await runtime.getContainerInfo(internal.containerId)).status === "running",
);
const stoppedPorts = second.hostPortByContainerPort;
@@ -537,7 +536,7 @@ try {
env: { OPENSHIP_SMOKE_PROCESS: "saved" },
};
await processSupervisor.deploy(processOptions);
- const workload = () => client.vm(workspaceId!).workloads.get(`openship-${processId}`);
+ const workload = () => client.workspace(workspaceId!).workloads.get(`openship-${processId}`);
const savedProcess = await workload();
check(
"provider returns saved process configuration",
@@ -566,10 +565,10 @@ try {
);
await processSupervisor.stop(processId);
- check("provider accepts server stop", (await client.vm(workspaceId).stop()).success);
+ check("provider accepts server stop", (await client.workspace(workspaceId).stop()).success);
await waitForCloudWorkspaceStopped(client, workspaceId, tag);
log("workspace stopped for recovery check", {
- status: (await client.vms.get(workspaceId)).status,
+ status: (await client.workspaces.get(workspaceId)).status,
});
check(
"stopped workspace reads do not start compute",
@@ -591,7 +590,7 @@ try {
"bare deletion retains the Docker application and server",
(await processSupervisor.getInfo(processId)).status === "missing" &&
(await runtime.getContainerInfo(second.containerId)).status === "running" &&
- isDockerWorkspaceRunning(await client.vms.get(workspaceId)),
+ isDockerWorkspaceRunning(await client.workspaces.get(workspaceId)),
);
check(
"workspace restart preserves the volume",
@@ -600,7 +599,7 @@ try {
);
check(
"bridge recovery reuses its workload",
- (await client.vm(workspaceId).workloads.list({ name: "openship-docker-api-v1" }))
+ (await client.workspace(workspaceId).workloads.list({ name: "openship-docker-api-v1" }))
.length === 1,
);
const hostnames = await infra.listProjectRouteHostnames();
@@ -631,11 +630,11 @@ try {
}
check(
"one workspace for the whole stack",
- (await client.vms.list()).vms.length === 1,
+ (await client.workspaces.list()).workspaces.length === 1,
);
} catch (error) {
if (workspaceId) {
- const workspace = await admin.vms.get(workspaceId).catch(() => null);
+ const workspace = await admin.workspaces.get(workspaceId).catch(() => null);
if (workspace) {
const provisioning = workspace.provisioning as
| { state?: string; error?: unknown }
@@ -663,7 +662,7 @@ try {
for (const slug of pages) {
try {
const page = (await admin.pages.get(slug)).page;
- if (page.namespace !== tag || page.source_vm_id !== workspaceId)
+ if (page.namespace !== tag || page.source_workspace_id !== workspaceId)
throw new Error("Unexpected smoke page owner");
await admin.pages.delete(slug);
pages.delete(slug);
@@ -677,7 +676,7 @@ try {
}
if (workspaceId) {
try {
- await deleteCloudWorkspace(admin.vm(workspaceId));
+ await deleteCloudWorkspace(admin.workspace(workspaceId));
workspaceId = undefined;
} catch (error) {
if ((error as { status?: number }).status === 404) workspaceId = undefined;
diff --git a/packages/adapters/scripts/verify-cloud-isolation.ts b/packages/adapters/scripts/verify-cloud-isolation.ts
index 131a01d2a..1095a25ba 100644
--- a/packages/adapters/scripts/verify-cloud-isolation.ts
+++ b/packages/adapters/scripts/verify-cloud-isolation.ts
@@ -9,14 +9,13 @@ import { join } from "node:path";
import { randomUUID } from "node:crypto";
import { setTimeout as delay } from "node:timers/promises";
import { Oblien } from "../src/oblien";
-import { oblienApiBaseUrl, oblienApiUrl } from "../src/oblien-contract";
import { cloudWorkspaceStatus, waitForCloudDockerWorkspace } from "../src/runtime/cloud/workspace-ready";
import { CloudWorkspaceExecutor } from "../src/runtime/cloud/workspace-executor";
import { deleteCloudWorkspace } from "../src/runtime/cloud/workspace-delete";
if (process.argv[2] !== "--staging-env" || !process.argv[3]) throw new Error("Provide a confirmed staging credential file with --staging-env");
const config = parseEnv(await readFile(process.argv[3], "utf8"));
-const baseUrl = oblienApiBaseUrl(config.OBLIEN_API_URL).toString();
+const baseUrl = config.OBLIEN_API_URL || "https://api.oblien.com";
if (!config.OBLIEN_CLIENT_ID || !config.OBLIEN_CLIENT_SECRET || new URL(baseUrl).protocol !== "https:") throw new Error("Staging credentials and HTTPS are required");
const admin = new Oblien({ clientId: config.OBLIEN_CLIENT_ID, clientSecret: config.OBLIEN_CLIENT_SECRET, baseUrl });
const tag = `os-cycle-${randomUUID().replaceAll("-", "").slice(0, 14)}`;
@@ -62,7 +61,7 @@ async function suspendedWorkspaceStops(client: Oblien, workspaceId: string, name
let observedState: string | undefined;
try {
await until(name, async () => {
- const workspace = await client.vms.get(workspaceId);
+ const workspace = await client.workspaces.get(workspaceId);
const state = cloudWorkspaceStatus(workspace);
if (state !== observedState) {
const info = workspace.info as { status?: string; is_running?: boolean } | undefined;
@@ -82,13 +81,13 @@ async function suspendedWorkspaceStops(client: Oblien, workspaceId: string, name
message: error instanceof Error ? error.message : "Unknown failure" });
// Preserve the failed automatic-stop result, then exercise the independent
// customer cleanup and explicit-reactivation contract on the same fixture.
- await client.vm(workspaceId).stop();
- await until("explicit Stop completes during suspension", async () => cloudWorkspaceStatus(await client.vms.get(workspaceId)) === "stopped");
+ await client.workspace(workspaceId).stop();
+ await until("explicit Stop completes during suspension", async () => cloudWorkspaceStatus(await client.workspaces.get(workspaceId)) === "stopped");
}
}
const a = `${tag}-a`, b = `${tag}-b`;
-const resources = { max_vms: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 };
-const policy = (quotaLimit: number) => ({ quotaLimit, overdraft: 0, suspendThreshold: 0, onOverdraftAction: "stop_vms" as const });
+const resources = { max_workspaces: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 };
+const policy = (quotaLimit: number) => ({ quotaLimit, overdraft: 0, suspendThreshold: 0, onOverdraftAction: "stop_workspaces" as const });
const create = (namespace: string, suffix: string) => ({ namespace, name: `${namespace}-${suffix}`, slug: `${namespace}-${suffix}`,
image: "oblien/docker:29", mode: "temporary" as const, wait_ready: false, idempotency_key: `${namespace}-${suffix}`,
config: { cpus: 2, memory_mb: 4096, disk_size_mb: 32768, ttl: "15m", ttl_action: "remove" as const,
@@ -97,7 +96,7 @@ const create = (namespace: string, suffix: string) => ({ namespace, name: `${nam
try {
log("starting isolated quota test", { directory });
const defaults = await admin.billing.defaults();
- check("new namespaces have finite automatic onboarding policy", defaults.autoApply && defaults.quotaLimit === 0 && defaults.overdraft === 0 && defaults.suspendThreshold === 0 && defaults.onOverdraftAction === "stop_vms");
+ check("new namespaces have finite automatic onboarding policy", defaults.autoApply && defaults.quotaLimit === 0 && defaults.overdraft === 0 && defaults.suspendThreshold === 0 && defaults.onOverdraftAction === "stop_workspaces");
for (const namespace of [a, b]) {
const input = { name: namespace, slug: namespace, resource_limits: resources };
const { data } = namespace === a ? await admin.namespaces.ensure(input) : await admin.namespaces.create(input);
@@ -109,7 +108,7 @@ try {
log("new namespace billing", { customer: namespace === a ? "A" : "B", method: namespace === a ? "ensure" : "create", entitlement, balance,
policy: inheritedPolicy, subscription: await admin.billing.subscription(namespace) });
check(`${namespace === a ? "A" : "B"}: zero credit inherited without a grant`, entitlement.namespace === namespace && entitlement.quota.limit === 0 && balance.blocking &&
- inheritedPolicy.quotaLimit === 0 && inheritedPolicy.overdraft === 0 && inheritedPolicy.suspendThreshold === 0 && inheritedPolicy.onOverdraftAction === "stop_vms", false);
+ inheritedPolicy.quotaLimit === 0 && inheritedPolicy.overdraft === 0 && inheritedPolicy.suspendThreshold === 0 && inheritedPolicy.onOverdraftAction === "stop_workspaces", false);
const subscription = (await admin.billing.subscription(namespace)).subscription;
check(`${namespace === a ? "A" : "B"}: unpaid namespace cannot inherit the owner's plan`, subscription === null && (entitlement.tierId === null || entitlement.tierId === "free") && entitlement.periodStart === null && entitlement.periodEnd === null, false);
// Continue the independent enforcement checks with an explicit fixture
@@ -126,7 +125,7 @@ try {
const request = client._http.request.bind(client._http);
client._http.request = async (input: Parameters[0]): Promise => {
const result = await request(input);
- if (input.method === "POST" && input.path === "/vms") {
+ if (input.method === "POST" && input.path === "/workspace") {
const data = result as Record;
log("workspace creation response shape", { keys: Object.keys(data), success: data.success, code: data.code,
error: typeof data.error === "string" ? data.error : undefined,
@@ -135,15 +134,15 @@ try {
return result;
};
}
- check("exhausted customers retain scoped inspection access", (await clientA.vms.list()).vms.length === 0);
- await denied("unpaid namespace cannot create compute", () => clientA.vms.create(create(a, "unpaid")), [402, 403]);
+ check("exhausted customers retain scoped inspection access", (await clientA.workspaces.list()).workspaces.length === 0);
+ await denied("unpaid namespace cannot create compute", () => clientA.workspaces.create(create(a, "unpaid")), [402, 403]);
for (const namespace of [a, b]) await admin.billing.setPolicy(namespace, policy(100));
check("isolated test allowance activates only its namespace", (await admin.billing.entitlement(a)).status === "active" && !(await admin.billing.balance(b)).blocking);
const repeated = await admin.namespaces.ensure({ name: a, slug: a, resource_limits: resources });
check("ensure preserves an existing namespace's allowance", repeated.data.id === namespaceIds.get(a) && (await admin.billing.policy(a)).quotaLimit === 100);
- const raced = await Promise.allSettled([clientA.vms.create(create(a, "race-1")), clientA.vms.create(create(a, "race-2"))]);
- const winners = raced.filter((item): item is PromiseFulfilledResult>> => item.status === "fulfilled");
+ const raced = await Promise.allSettled([clientA.workspaces.create(create(a, "race-1")), clientA.workspaces.create(create(a, "race-2"))]);
+ const winners = raced.filter((item): item is PromiseFulfilledResult>> => item.status === "fulfilled");
const losers = raced.filter(item => item.status === "rejected");
log("concurrent create outcomes", { results: raced.map(item => item.status === "fulfilled"
? { state: item.status, workspaceId: item.value?.id, namespace: item.value?.namespace }
@@ -152,19 +151,19 @@ try {
const workspaceA = winners[0]!.value;
// Inspect the actual wire status, independently of Openship's compatibility
// normalization for the provider's former HTTP-200 limit failures.
- const limited = await fetch(oblienApiUrl(new URL(baseUrl), "/vms"), {
+ const limited = await fetch(new URL("/workspace", baseUrl), {
method: "POST", headers: { Authorization: `Bearer ${tokenA}`, "Content-Type": "application/json" },
body: JSON.stringify(create(a, "raw-limit")), redirect: "error", signal: AbortSignal.timeout(30_000),
});
log("workspace cap wire response", { status: limited.status });
check("workspace cap returns HTTP 409", limited.status === 409);
await limited.arrayBuffer();
- const workspaceB = await clientB.vms.create(create(b, "main"));
+ const workspaceB = await clientB.workspaces.create(create(b, "main"));
await waitForCloudDockerWorkspace(clientA, workspaceA.id, a, { signal: abort.signal });
await waitForCloudDockerWorkspace(clientB, workspaceB.id, b, { signal: abort.signal });
check("two customers own different workspaces", workspaceA.id !== workspaceB.id && workspaceA.namespace === a && workspaceB.namespace === b);
for (const [client, workspace, namespace] of [[clientA, workspaceA, a], [clientB, workspaceB, b]] as const) {
- const executor = new CloudWorkspaceExecutor(() => client.vm(workspace.id).runtime());
+ const executor = new CloudWorkspaceExecutor(() => client.workspace(workspace.id).runtime());
const path = `/opt/openship/cloud-docker/routes/${namespace}`;
try {
await executor.mkdir(path); await executor.writeFile(`${path}/index.html`, `Isolated customer ${namespace}`);
@@ -176,16 +175,16 @@ try {
finally { await executor.dispose(); }
pages.set(namespace, namespace);
await save();
- await admin.pages.create({ name: namespace, slug: namespace, namespace, vm_id: workspace.id, path, domain: "preview.oblien.com" });
+ await admin.pages.create({ slug: namespace, namespace, workspace_id: workspace.id, path, domain: "preview.oblien.com" });
}
- const visibleA = (await clientA.vms.list()).vms;
- const visibleB = (await clientB.vms.list()).vms;
+ const visibleA = (await clientA.workspaces.list()).workspaces;
+ const visibleB = (await clientB.workspaces.list()).workspaces;
check("workspace lists are isolated", visibleA.length === 1 && visibleA[0]!.namespace === a && visibleB.length === 1 && visibleB[0]!.namespace === b);
- await denied("customer cannot read another customer's VM", () => clientA.vms.get(workspaceB.id), [403, 404]);
- await denied("customer cannot stop another customer's VM", () => clientA.vm(workspaceB.id).stop(), [403, 404]);
- await denied("customer cannot delete another customer's VM", () => clientA.vms.delete(workspaceB.id), [403, 404]);
- await denied("customer cannot escape its namespace on creation", () => clientA.vms.create(create(b, "escape")), [400, 403, 409, 422]);
- check("foreign namespace still owns exactly its original workspace", (await clientB.vms.list()).vms.length === 1);
+ await denied("customer cannot read another customer's VM", () => clientA.workspaces.get(workspaceB.id), [403, 404]);
+ await denied("customer cannot stop another customer's VM", () => clientA.workspace(workspaceB.id).stop(), [403, 404]);
+ await denied("customer cannot delete another customer's VM", () => clientA.workspaces.delete(workspaceB.id), [403, 404]);
+ await denied("customer cannot escape its namespace on creation", () => clientA.workspaces.create(create(b, "escape")), [400, 403, 409, 422]);
+ check("foreign namespace still owns exactly its original workspace", (await clientB.workspaces.list()).workspaces.length === 1);
await denied("customer cannot access account billing", () => clientA.billing.entitlement(b), [403]);
await denied("customer cannot grant itself credit", () => clientA.billing.setPolicy(a, policy(500)), [403]);
await denied("customer cannot mint a more privileged token", () => clientA.tokens.create({ scope: "namespace", namespace: b }), [403]);
@@ -195,10 +194,10 @@ try {
check("Page listing cannot expose another namespace", visible.every(page => page.namespace === a), false);
} catch (error) { check("Page listing requires privileged proxy", (error as { status?: number }).status === 403); }
await denied("customer cannot read another customer's Page", () => clientA.pages.get(b), [403, 404]);
- await denied("namespace CPU ceiling blocks resize", () => clientA.vm(workspaceA.id).resources.update({ cpus: 3, apply: false }), [400, 409, 422]);
- await denied("namespace RAM ceiling blocks resize", () => clientA.vm(workspaceA.id).resources.update({ memory_mb: 8192, apply: false }), [400, 409, 422]);
- await denied("namespace disk ceiling blocks resize", () => clientA.vm(workspaceA.id).resources.update({ disk_size_mb: 65536, apply: false }), [400, 409, 422]);
- check("rejected resize keeps the original allocation", (await clientA.vms.get(workspaceA.id)).resources?.cpus === 2);
+ await denied("namespace CPU ceiling blocks resize", () => clientA.workspace(workspaceA.id).resources.update({ cpus: 3, apply: false }), [400, 409, 422]);
+ await denied("namespace RAM ceiling blocks resize", () => clientA.workspace(workspaceA.id).resources.update({ memory_mb: 8192, apply: false }), [400, 409, 422]);
+ await denied("namespace disk ceiling blocks resize", () => clientA.workspace(workspaceA.id).resources.update({ disk_size_mb: 65536, apply: false }), [400, 409, 422]);
+ check("rejected resize keeps the original allocation", (await clientA.workspaces.get(workspaceA.id)).resources?.cpus === 2);
try {
await until("provider records compute usage", async () => (await admin.billing.entitlement(a)).quota.used > 0, 300_000);
@@ -229,25 +228,25 @@ try {
check("exhaustion is visible in entitlement and balance", true);
check("new usage crossed the configured credit allowance", effectiveAllowance !== null && (await admin.billing.entitlement(a)).quota.used >= effectiveAllowance);
try {
- await until("provider stops exhausted namespace", async () => cloudWorkspaceStatus(await clientA.vms.get(workspaceA.id)) === "stopped", 90_000);
+ await until("provider stops exhausted namespace", async () => cloudWorkspaceStatus(await clientA.workspaces.get(workspaceA.id)) === "stopped", 90_000);
check("provider stops A on exhaustion", true);
} catch {
check("provider stops A on exhaustion", false, false);
log("explicitly stopping A to continue independent management checks");
- await clientA.vm(workspaceA.id).stop();
+ await clientA.workspace(workspaceA.id).stop();
}
- check("B keeps running when A is exhausted", cloudWorkspaceStatus(await clientB.vms.get(workspaceB.id)) === "running" && !(await admin.billing.balance(b)).blocking);
- await denied("exhausted customer cannot restart compute", () => clientA.vm(workspaceA.id).start(), [402, 403, 409]);
- await denied("exhausted customer cannot create replacement compute", () => clientA.vms.create(create(a, "blocked")), [402, 403, 409]);
- check("exhausted customer can still inspect its stopped VM", (await clientA.vms.get(workspaceA.id)).id === workspaceA.id);
- await clientA.vm(workspaceA.id).stop();
- await clientA.vm(workspaceA.id).stop();
+ check("B keeps running when A is exhausted", cloudWorkspaceStatus(await clientB.workspaces.get(workspaceB.id)) === "running" && !(await admin.billing.balance(b)).blocking);
+ await denied("exhausted customer cannot restart compute", () => clientA.workspace(workspaceA.id).start(), [402, 403, 409]);
+ await denied("exhausted customer cannot create replacement compute", () => clientA.workspaces.create(create(a, "blocked")), [402, 403, 409]);
+ check("exhausted customer can still inspect its stopped VM", (await clientA.workspaces.get(workspaceA.id)).id === workspaceA.id);
+ await clientA.workspace(workspaceA.id).stop();
+ await clientA.workspace(workspaceA.id).stop();
check("billing-suspended customer can repeat Stop", true);
await admin.billing.setPolicy(a, policy(100));
await until("billing restoration", async () => (await admin.billing.entitlement(a)).status === "active" && !(await admin.billing.balance(a)).blocking);
- check("restoring credit does not restart compute implicitly", cloudWorkspaceStatus(await clientA.vms.get(workspaceA.id)) === "stopped");
- await clientA.vm(workspaceA.id).start();
+ check("restoring credit does not restart compute implicitly", cloudWorkspaceStatus(await clientA.workspaces.get(workspaceA.id)) === "stopped");
+ await clientA.workspace(workspaceA.id).start();
await waitForCloudDockerWorkspace(clientA, workspaceA.id, a, { signal: abort.signal });
check("restored customer explicitly resumes the same VM", true);
@@ -255,28 +254,28 @@ try {
await suspendedWorkspaceStops(clientA, workspaceA.id, a, "manual suspension stops A");
await admin.billing.setPolicy(a, policy(200));
check("credit increase cannot undo a manual suspension", (await admin.namespaces.get(a)).data.status === "suspended" && (await admin.billing.balance(a)).blocking);
- await denied("manual suspension blocks Start despite positive credit", () => clientA.vm(workspaceA.id).start(), [402, 403, 409]);
+ await denied("manual suspension blocks Start despite positive credit", () => clientA.workspace(workspaceA.id).start(), [402, 403, 409]);
await admin.namespaces.activate(namespaceIds.get(a)!);
- check("explicit reactivation restores access without starting the VM", (await admin.namespaces.get(a)).data.status === "active" && !(await admin.billing.balance(a)).blocking && cloudWorkspaceStatus(await clientA.vms.get(workspaceA.id)) === "stopped");
- await clientA.vm(workspaceA.id).start();
+ check("explicit reactivation restores access without starting the VM", (await admin.namespaces.get(a)).data.status === "active" && !(await admin.billing.balance(a)).blocking && cloudWorkspaceStatus(await clientA.workspaces.get(workspaceA.id)) === "stopped");
+ await clientA.workspace(workspaceA.id).start();
await waitForCloudDockerWorkspace(clientA, workspaceA.id, a, { signal: abort.signal });
check("manually suspended VM starts only after reactivation", true);
log("second manual suspension response", { namespace: a, response: await admin.namespaces.suspend(namespaceIds.get(a)!) });
await suspendedWorkspaceStops(clientA, workspaceA.id, a, "second manual suspension stops A");
- await clientA.vm(workspaceA.id).stop();
- await clientA.vm(workspaceA.id).stop();
+ await clientA.workspace(workspaceA.id).stop();
+ await clientA.workspace(workspaceA.id).stop();
check("manually suspended customer can repeat Stop", true);
- await deleteCloudWorkspace(clientA.vm(workspaceA.id));
- await until("A disappears from the scoped workspace list", async () => (await clientA.vms.list()).vms.length === 0, 60_000);
- check("suspended customer can delete resources", (await clientA.vms.list()).vms.length === 0);
- check("B remains available after A cleanup", cloudWorkspaceStatus(await clientB.vms.get(workspaceB.id)) === "running");
+ await deleteCloudWorkspace(clientA.workspace(workspaceA.id));
+ await until("A disappears from the scoped workspace list", async () => (await clientA.workspaces.list()).workspaces.length === 0, 60_000);
+ check("suspended customer can delete resources", (await clientA.workspaces.list()).workspaces.length === 0);
+ check("B remains available after A cleanup", cloudWorkspaceStatus(await clientB.workspaces.get(workspaceB.id)) === "running");
await admin.billing.setPolicy(b, policy(0));
- await until("B stops for billing-suspended deletion check", async () => (await admin.billing.balance(b)).blocking && cloudWorkspaceStatus(await clientB.vms.get(workspaceB.id)) === "stopped");
- await clientB.vm(workspaceB.id).stop();
- await clientB.vm(workspaceB.id).stop();
- await deleteCloudWorkspace(clientB.vm(workspaceB.id));
- await until("B disappears from the scoped workspace list", async () => (await clientB.vms.list()).vms.length === 0, 60_000);
- check("billing-suspended customer can inspect, repeat Stop and Delete", (await clientB.vms.list()).vms.length === 0);
+ await until("B stops for billing-suspended deletion check", async () => (await admin.billing.balance(b)).blocking && cloudWorkspaceStatus(await clientB.workspaces.get(workspaceB.id)) === "stopped");
+ await clientB.workspace(workspaceB.id).stop();
+ await clientB.workspace(workspaceB.id).stop();
+ await deleteCloudWorkspace(clientB.workspace(workspaceB.id));
+ await until("B disappears from the scoped workspace list", async () => (await clientB.workspaces.list()).workspaces.length === 0, 60_000);
+ check("billing-suspended customer can inspect, repeat Stop and Delete", (await clientB.workspaces.list()).workspaces.length === 0);
} catch (error) {
check("all lifecycle checks completed", false, false);
log("test failed", { message: error instanceof Error ? error.message.replace(/([?&](?:token|access_token)=)[^&\s]+/gi, "$1[redacted]") : "Unknown failure", status: (error as { status?: number }).status });
@@ -297,7 +296,7 @@ try {
try {
const current = await admin.namespaces.get(id);
if (current.data.slug !== namespace || !namespace.startsWith(`${tag}-`)) throw new Error("Test namespace identity changed");
- await admin.namespaces.delete(id, { deleteVms: true });
+ await admin.namespaces.delete(id, { deleteWorkspaces: true });
namespaceIds.delete(namespace);
} catch (error) {
if ((error as { status?: number }).status === 404) namespaceIds.delete(namespace);
diff --git a/packages/adapters/src/backup/executors/docker.ts b/packages/adapters/src/backup/executors/docker.ts
index 725fa5f0f..a2555e61f 100644
--- a/packages/adapters/src/backup/executors/docker.ts
+++ b/packages/adapters/src/backup/executors/docker.ts
@@ -434,8 +434,9 @@ export class DockerBackupExecutor implements BackupExecutor {
// Idempotent on purpose: the column stores whatever was written at deploy
// time, and for services deployed from an already-scoped spec that is the
// SCOPED name. Prefixing twice named a volume that never existed, which docker
- // creates empty on mount. Capture verifies that the resolved volume exists
- // before mounting it; restore must address the volume the service reads.
+ // creates empty on mount — a capture that archives nothing (now a failure
+ // rather than a green run, via the empty-source gate) and a restore into a
+ // volume nothing reads.
const source =
parsed.type !== "volume" || !service.namespaceVolumes
? parsed.source
@@ -577,23 +578,16 @@ export class DockerBackupExecutor implements BackupExecutor {
const excludeArgs = (opts?.exclude ?? []).flatMap((p) => ["--exclude", shellQuote(p)]);
const tarFlags = compressionFlag(compression);
const isFile = source.type === "bind" && source.isDirectory === false;
- // Docker creates missing named volumes even for read-only mounts. Verify on
- // this daemon before creating the helper; emptiness is not an existence check.
- if (source.type === "volume") await this.dockerode.getVolume(source.source).inspect();
+ if (opts?.allowEmpty && source.type === "volume") await this.dockerode.getVolume(source.source).inspect();
const tarCmd = `tar -c${tarFlags} -C /mnt ${excludeArgs.join(" ")} ${isFile ? "file" : "."}`;
const helperImage = compression === "zstd" ? "alpine:3" : HELPER_IMAGE;
await this.ensureImage(helperImage);
const hostConfig: Dockerode.HostConfig = {
- Mounts: [
- {
- Type: source.type as "bind" | "volume",
- Source: source.source,
- Target: `/mnt${isFile ? "/file" : ""}`,
- ReadOnly: true,
- },
- ],
+ ...(source.type === "bind"
+ ? { Mounts: [{ Type: "bind" as const, Source: source.source, Target: `/mnt${isFile ? "/file" : ""}`, ReadOnly: true }] }
+ : { Binds: [`${source.source}:/mnt:ro`] }),
// OFF, for the reason demuxContainerStream already documents but this line
// used to contradict: AutoRemove lets the daemon reap the helper before
// container.wait() answers and before the attach stream has drained, which
@@ -644,10 +638,29 @@ export class DockerBackupExecutor implements BackupExecutor {
tarCmd,
compression === "zstd" ? "zstd" : "none",
[
- // Bind Mounts reject missing host paths instead of creating them.
- // Named volumes were inspected above. Existing empty sources are valid;
- // tar still fails if the source cannot be read or storage cannot mount.
- // zstd is not in alpine:3, so the helper installs it.
+ // REFUSE an empty mount before doing anything else.
+ //
+ // The daemon CREATES a missing bind directory and a missing named volume
+ // when it honors HostConfig.Binds, so a source that is not on this host
+ // produces a helper that starts fine and a `tar -c` of nothing that exits
+ // 0. That archive is ~350 bytes compressed, so the orchestrator's
+ // zero-byte guard passes and the run is recorded as a successful backup —
+ // a nightly green tick over an external disk that failed to mount, a data
+ // directory that was renamed under a still-running container, or a volume
+ // that `docker system prune --volumes` took.
+ //
+ // An intentionally-empty source fails too, which is the deliberate half of
+ // the trade: an archive of nothing is not a restore point either way, and
+ // the operator has `payloadConfig.sourceIds` to narrow the policy. Silence
+ // is the only outcome that cannot be recovered from.
+ `SRC=${shellQuote(sourceId)}`,
+ opts?.allowEmpty ? "true" : `[ -n "$(ls -A /mnt 2>/dev/null)" ] || { echo "openship: backup source $SRC is ` +
+ `empty or missing on this host, so this archive would contain nothing. ` +
+ `Refusing to record it as a backup. If it is a mount, check that it is ` +
+ `mounted; if it is empty on purpose, narrow the policy's sourceIds." >&2; ` +
+ `exit 91; }`,
+ // zstd is not in alpine:3, so the helper installs it. Second, so a doomed
+ // capture does not pay the ~20s fetch first.
compression === "zstd" ? "apk add --no-cache zstd >/dev/null 2>&1" : null,
]
.filter(Boolean)
diff --git a/packages/adapters/src/backup/producers/custom-command.ts b/packages/adapters/src/backup/producers/custom-command.ts
index afe508b4a..54fb4c1e0 100644
--- a/packages/adapters/src/backup/producers/custom-command.ts
+++ b/packages/adapters/src/backup/producers/custom-command.ts
@@ -73,7 +73,7 @@ class CustomCommandProducerImpl implements BackupProducer {
service: ServiceHandle,
executor: BackupExecutor,
artifact: ArtifactRef,
- opts: RestoreOpts,
+ _opts: RestoreOpts,
): Promise {
const restoreCommand =
(artifact.metadata.restoreCommand as string | null) ?? null;
@@ -104,7 +104,7 @@ class CustomCommandProducerImpl implements BackupProducer {
["sh", "-c", restoreCommand],
body,
// Ceiling from the catalog, so the number is not a per-producer literal.
- { timeoutMs: payloadSpec("custom_command").restoreTimeoutMs, signal: opts.signal },
+ { timeoutMs: payloadSpec("custom_command").restoreTimeoutMs },
);
if (exit.code !== 0) {
throw new Error(
diff --git a/packages/adapters/src/backup/types.ts b/packages/adapters/src/backup/types.ts
index a0895405b..fd2a62443 100644
--- a/packages/adapters/src/backup/types.ts
+++ b/packages/adapters/src/backup/types.ts
@@ -130,6 +130,8 @@ export interface ExecuteCommandOpts {
export interface StreamPathOpts {
compression?: PayloadCompression;
+ /** A migration may intentionally copy an empty source; backups stay strict. */
+ allowEmpty?: boolean;
/** Glob-ish patterns to exclude (passed to tar `--exclude`). */
exclude?: string[];
/**
@@ -399,8 +401,9 @@ export interface ProducerOpts {
export interface RestoreOpts {
/** Pass clearTarget through. */
clearTarget?: boolean;
- /** Abort in-flight restore work. The payload's failure semantics determine
- * whether an interrupted write rolls back or leaves partial data. */
+ /** Forwarded to the executor so a cancel doesn't have to wait out the
+ * whole extract. Producers that restore through `pipeIntoCommand` ignore
+ * it — those writes are transactional at the engine, not the volume. */
signal?: AbortSignal;
}
diff --git a/packages/adapters/src/backup/volume-transfer.ts b/packages/adapters/src/backup/volume-transfer.ts
index 10f6218b9..8d899e748 100644
--- a/packages/adapters/src/backup/volume-transfer.ts
+++ b/packages/adapters/src/backup/volume-transfer.ts
@@ -163,6 +163,7 @@ export async function transferVolume(
// one daemon or across two (src.exec / dst.exec may differ).
const read = await src.exec.streamPath(src.handle, src.sourceId, {
compression: plan.compression,
+ allowEmpty: true,
});
// Observe source termination from the start, including a rejected target
// setup. A broken destination must not leave the producer streaming forever.
diff --git a/packages/adapters/src/index.ts b/packages/adapters/src/index.ts
index 619c8b966..abfbd72c0 100644
--- a/packages/adapters/src/index.ts
+++ b/packages/adapters/src/index.ts
@@ -171,7 +171,6 @@ export {
type AlternativeHostPort,
type SuggestAlternativeHostPort,
probeListeningPort,
- probeListeningPortOwners,
isDockerHostPortAvailable,
ensurePortAvailable,
} from "./runtime/port-conflict";
@@ -606,9 +605,7 @@ export {
// ─── Oblien SDK (re-export for single source of truth) ───────────────────────
export { Oblien, OblienError, cloudWorkspaceCreationFailure } from "./oblien";
-export { oblienApiBaseUrl, oblienApiUrl, toOblienVmLimits, toOblienVmCapacity, toOblienVmPolicy, toOblienVmOffer, cloudBillingContract } from "./oblien-contract";
export type {
- NamespaceResourceLimits,
NamespaceUsageUnits,
NamespaceUsageUnitBucket,
NamespaceUsageUnitsParams,
diff --git a/packages/adapters/src/infra/cloud-routing-sdk.test.ts b/packages/adapters/src/infra/cloud-routing-sdk.test.ts
index 30927a4f5..e96219677 100644
--- a/packages/adapters/src/infra/cloud-routing-sdk.test.ts
+++ b/packages/adapters/src/infra/cloud-routing-sdk.test.ts
@@ -27,14 +27,14 @@ beforeEach(() => {
return page ? Response.json({ success: true, page }) : Response.json({ error: "Not found" }, { status: 404 });
if (url.pathname === "/pages" && method === "POST") {
page = { id: 42, slug: body.slug, domain: body.domain, namespace: h.namespace,
- source_vm_id: body.vm_id, exported_path: body.path, url: `https://${hostname}` };
+ source_workspace_id: body.workspace_id, exported_path: body.path, url: `https://${hostname}` };
return Response.json({ success: true, page });
}
if (url.pathname === "/pages/app/enable" && method === "POST")
return Response.json({ success: true });
- if (url.pathname === `/vms/${h.workspaceId}/network` && method === "GET")
+ if (url.pathname === `/workspace/${h.workspaceId}/network` && method === "GET")
return Response.json({ ingress_ports: [443] });
- if (url.pathname === `/vms/${h.workspaceId}/network` && method === "PATCH")
+ if (url.pathname === `/workspace/${h.workspaceId}/network` && method === "PATCH")
return Response.json({ success: true });
if (url.pathname === `/domain/routes/${hostname}` && method === "PUT")
return Response.json({ success: true, hostname, version: writes.length,
@@ -54,7 +54,7 @@ it.each([301, 302, 307, 308])("sends canonical redirect intent through the real
} });
await provider.registerRoute({ domain: hostname, targetUrl: "http://127.0.0.1:3000", tls: true });
const tables = writes.filter(request => request.path === `/domain/routes/${hostname}`);
- expect(tables.at(-1)?.body).toEqual({ routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }] });
+ expect(tables.at(-1)?.body).toEqual({ routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }] });
expect(writes.filter(request => request.path === "/pages")).toHaveLength(1);
expect(requests.some(url => url.pathname === "/workspace")).toBe(false);
});
@@ -66,13 +66,13 @@ it("reuses the owned Page through the SDK after routes become a compiled table",
const routes = writes.filter(request => request.path === `/domain/routes/${hostname}`);
expect(routes).toHaveLength(2);
expect(routes[1]).toEqual({ method: "PUT", path: `/domain/routes/${hostname}`, body: {
- routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }],
+ routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }],
} });
- expect(writes).toContainEqual({ method: "PATCH", path: `/vms/${h.workspaceId}/network`, body: { ingress_ports: [443, 3000] } });
+ expect(writes).toContainEqual({ method: "PATCH", path: `/workspace/${h.workspaceId}/network`, body: { ingress_ports: [443, 3000] } });
expect(requests.some(url => url.pathname === "/workspace")).toBe(false);
});
-it.each(["namespace", "source_vm_id", "exported_path"])("does not write when the Page's %s changes", async field => {
+it.each(["namespace", "source_workspace_id", "exported_path"])("does not write when the Page's %s changes", async field => {
await provider.registerRoute({ domain: hostname, targetUrl: "http://127.0.0.1:3000", tls: true });
page![field] = "different-owner";
writes.length = 0;
@@ -92,7 +92,7 @@ it("publishes path-only routes through the SDK without a static or SPA fallback"
spa: false,
routes: [{
match: { path: "/api/", type: "prefix" },
- action: { kind: "proxy", vm: h.workspaceId, port: 3000 },
+ action: { kind: "proxy", workspace: h.workspaceId, port: 3000 },
}],
},
});
diff --git a/packages/adapters/src/infra/cloud-routing.test.ts b/packages/adapters/src/infra/cloud-routing.test.ts
index 8b13d6473..b2b973a6c 100644
--- a/packages/adapters/src/infra/cloud-routing.test.ts
+++ b/packages/adapters/src/infra/cloud-routing.test.ts
@@ -14,7 +14,7 @@ describe("project routes on a managed server", () => {
});
expect(h.pages.create).toHaveBeenCalledOnce();
await h.infra.registerRoute(route);
- expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }] });
+ expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }] });
expect(h.pages.create).toHaveBeenCalledOnce();
});
@@ -25,7 +25,7 @@ describe("project routes on a managed server", () => {
});
expect(h.routes.set).toHaveBeenCalledWith(route.domain, {
spa: false,
- routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }],
+ routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }],
});
});
it("updates one project-owned Page repeatedly without a new workspace", async () => {
@@ -33,10 +33,10 @@ describe("project routes on a managed server", () => {
await h.infra.registerRoute(route);
expect(h.pages.create).toHaveBeenCalledOnce();
expect(h.routes.set).toHaveBeenCalledTimes(2);
- expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }] });
+ expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 3000 } }] });
expect(h.workspace.network.update).toHaveBeenCalledWith({ ingress_ports: [443, 3000] });
});
- it.each(["namespace", "source_vm_id", "exported_path"])("refuses a changed %s before mutating the route", async field => {
+ it.each(["namespace", "source_workspace_id", "exported_path"])("refuses a changed %s before mutating the route", async field => {
await h.infra.registerRoute(route);
h.records.get("app")![field] = "another-owner";
h.routes.set.mockClear(); h.pages.enable.mockClear();
@@ -58,8 +58,8 @@ describe("project routes on a managed server", () => {
it("validates every composite backend, not only the root", async () => {
await h.infra.registerRoute(route);
h.routes.set.mockClear();
- await expect(h.infra.setDomainRoutes(route.domain, { routes: [{ match: { path: "/admin", type: "prefix" }, action: { kind: "proxy", vm: "another-vm", port: 3000 } }] })).rejects.toThrow("does not belong");
- await expect(h.infra.setDomainRoutes(route.domain, { routes: [{ match: { path: "/admin", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 4000 } }] })).rejects.toThrow("unowned");
+ await expect(h.infra.setDomainRoutes(route.domain, { routes: [{ match: { path: "/admin", type: "prefix" }, action: { kind: "proxy", workspace: "another-vm", port: 3000 } }] })).rejects.toThrow("does not belong");
+ await expect(h.infra.setDomainRoutes(route.domain, { routes: [{ match: { path: "/admin", type: "prefix" }, action: { kind: "proxy", workspace: h.workspaceId, port: 4000 } }] })).rejects.toThrow("unowned");
expect(h.routes.set).not.toHaveBeenCalled();
});
it("keeps unrelated ingress ports when adding an application", async () => {
diff --git a/packages/adapters/src/infra/cloud.test.ts b/packages/adapters/src/infra/cloud.test.ts
index 4c498d30c..424061879 100644
--- a/packages/adapters/src/infra/cloud.test.ts
+++ b/packages/adapters/src/infra/cloud.test.ts
@@ -15,7 +15,7 @@ let provider: CloudInfraProvider;
beforeEach(() => {
vi.mocked(probePublicTlsCertificate).mockReset().mockImplementation(async domain => ({ domain, verified: true, expiresAt: expiry, issuer: "Let's Encrypt", reason: "issued" }));
page = { slug: "route-one", domain: "opsh.io", url: `https://${hostname}`, custom_domain: hostname,
- namespace: "ns-one", source_vm_id: "ws-one", exported_path: "/opt/openship/cloud-docker/routes/route-one" };
+ namespace: "ns-one", source_workspace_id: "ws-one", exported_path: "/opt/openship/cloud-docker/routes/route-one" };
routes = vi.fn(async () => ({ data: [{ hostname, namespace: "ns-one", owner_type: "page", owner_id: "route-one", is_custom: 1 }] }));
pages = {
list: vi.fn(async () => ({ pages: [page] })), get: vi.fn(async () => ({ page })),
diff --git a/packages/adapters/src/infra/cloud.ts b/packages/adapters/src/infra/cloud.ts
index eae46c2b3..7a8fab081 100644
--- a/packages/adapters/src/infra/cloud.ts
+++ b/packages/adapters/src/infra/cloud.ts
@@ -109,7 +109,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
}
async getQuota(): Promise {
- return this.client.vms.getQuota();
+ return this.client.workspaces.getQuota();
}
// ── Domain / Slug checks ───────────────────────────────────────────────
@@ -199,7 +199,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
if (
!page ||
(this.workspaceId &&
- (page.source_vm_id !== this.workspaceId ||
+ (page.source_workspace_id !== this.workspaceId ||
page.exported_path !== `${this.routeRoot}/${page.slug}`))
)
throw disconnected();
@@ -230,11 +230,11 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
if (route.protection) throw new Error("Password protection is not supported by the Cloud edge.");
if (route.webhookProxy)
throw new Error("Managed application routes cannot proxy control-plane webhooks");
- const proxyTargets = new Map();
+ const proxyTargets = new Map();
for (const location of route.proxyLocations ?? []) {
if (location.external) continue;
proxyTargets.set(location.targetUrl, {
- vm: this.scope.workspaceId,
+ workspace: this.scope.workspaceId,
port: await this.scope.resolveUrl(location.targetUrl),
});
}
@@ -251,7 +251,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
trailingSlash: route.trailingSlash,
},
{
- root: port ? { vm: this.scope.workspaceId, port } : undefined,
+ root: port ? { workspace: this.scope.workspaceId, port } : undefined,
staticPage: route.staticRoot ? slug : undefined,
proxyTargets,
},
@@ -300,7 +300,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
}
if (
page.namespace === this.options.namespace &&
- page.source_vm_id === this.workspaceId &&
+ page.source_workspace_id === this.workspaceId &&
page.exported_path === `${this.routeRoot}/${page.slug}`
)
hostnames.push(...cloudPageHostnames(page));
@@ -348,14 +348,14 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
)
throw new Error("Invalid cloud routing port");
const pathsOnly = hostPort === undefined && !staticRoot;
- if (pathsOnly && !input?.routes?.some((rule) => rule.action.kind === "proxy"))
+ if (pathsOnly && !input?.routes.some((rule) => rule.action.kind === "proxy"))
throw new Error("A route needs a process or a static release");
const slug = this.routeSlug(hostname, custom);
let routes = input ?? {
routes: [
{
match: { path: "/", type: "prefix" as const },
- action: { kind: "proxy" as const, vm: this.scope.workspaceId, port: hostPort! },
+ action: { kind: "proxy" as const, workspace: this.scope.workspaceId, port: hostPort! },
},
],
};
@@ -375,7 +375,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
}
const assertPage = () => {
if (
- page!.source_vm_id !== this.workspaceId ||
+ page!.source_workspace_id !== this.workspaceId ||
page!.namespace !== this.options.namespace ||
page!.exported_path !== path
)
@@ -408,7 +408,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
);
if (page) {
const deployed = await this.pages.deploy(slug, {
- vm_id: this.scope.workspaceId,
+ workspace_id: this.scope.workspaceId,
path,
});
if (!deployed.success) throw new Error("Could not publish the static release");
@@ -422,7 +422,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
if (!page) {
try {
await this.pages.create({
- vm_id: this.scope.workspaceId,
+ workspace_id: this.scope.workspaceId,
path,
name: `Route ${hostname}`,
slug,
@@ -440,9 +440,9 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
if (page.custom_domain !== hostname)
await this.pages.connectDomain(slug, { domain: hostname });
}
- const ports = (routes.routes ?? []).flatMap((rule) =>
+ const ports = routes.routes.flatMap((rule) =>
rule.action.kind === "proxy" &&
- rule.action.vm === this.workspaceId &&
+ rule.action.workspace === this.workspaceId &&
rule.action.port
? [rule.action.port]
: [],
@@ -462,7 +462,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
// would leave a failed release live at the edge.
if (hadPage && restored.trim() === "restored") {
if (
- !(await this.pages.deploy(slug, { vm_id: this.scope.workspaceId, path }))
+ !(await this.pages.deploy(slug, { workspace_id: this.scope.workspaceId, path }))
.success
)
throw new Error("Could not republish the previous static release");
@@ -490,9 +490,9 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
async resolveRoutingTarget(
containerId: string,
port: number,
- ): Promise<{ vm: string; port: number }> {
+ ): Promise<{ workspace: string; port: number }> {
return {
- vm: this.scope.workspaceId,
+ workspace: this.scope.workspaceId,
port: await this.scope.resolveTarget(containerId, port),
};
}
@@ -513,9 +513,9 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
throw new AppError("Domain does not belong to this project", 404, "DOMAIN_NOT_FOUND");
await this.assertRouteTargets(input);
await this.ensureIngressPorts(
- (input.routes ?? []).flatMap((route) =>
+ input.routes.flatMap((route) =>
route.action.kind === "proxy" &&
- route.action.vm === this.workspaceId &&
+ route.action.workspace === this.workspaceId &&
route.action.port
? [route.action.port]
: [],
@@ -534,7 +534,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
const { page } = await this.pages.get(input.static.page);
if (
page.namespace !== this.options.namespace ||
- page.source_vm_id !== this.workspaceId ||
+ page.source_workspace_id !== this.workspaceId ||
page.exported_path !== `${this.routeRoot}/${page.slug}`
)
throw new AppError(
@@ -545,11 +545,11 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
}
const ports = new Set();
if (publishedPort !== undefined) ports.add(publishedPort);
- for (const route of input.routes ?? []) {
+ for (const route of input.routes) {
if (
route.action.kind === "proxy" &&
!route.action.origin &&
- (route.action.vm !== this.workspaceId ||
+ (route.action.workspace !== this.workspaceId ||
typeof route.action.port !== "number")
)
throw new AppError(
@@ -570,7 +570,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
* only ensures the project's validated route ports can receive edge traffic. */
private async ensureIngressPorts(add: number[]) {
if (!add.length) return;
- const workspace = this.client.vm(this.scope.workspaceId);
+ const workspace = this.client.workspace(this.scope.workspaceId);
const network = await workspace.network.get();
const current = Array.isArray(network.ingress_ports) ? (network.ingress_ports as number[]) : [];
const next = [...new Set([...current, ...add])];
@@ -593,7 +593,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
* is uncertain state and must retain the deletion fence. */
private isForeignProjectRoute(page: {
slug: string;
- source_vm_id?: string | null;
+ source_workspace_id?: string | null;
exported_path?: string | null;
}): boolean {
const prefix = `${CLOUD_DOCKER_ROUTE_ROOT}/projects/`;
@@ -602,7 +602,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
if (
!this.routeRoot ||
!canonicalRoot(this.routeRoot) ||
- !page.source_vm_id?.trim() ||
+ !page.source_workspace_id?.trim() ||
!page.exported_path ||
!/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(page.slug)
)
@@ -629,7 +629,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
const page = await this.pageForDomain(domain);
if (!page) return "absent";
if (
- page.source_vm_id !== this.workspaceId ||
+ page.source_workspace_id !== this.workspaceId ||
page.exported_path !== `${this.routeRoot}/${page.slug}`
) {
if (mode === "project-cleanup" && this.isForeignProjectRoute(page)) return "foreign";
diff --git a/packages/adapters/src/infra/lua-embedded.ts b/packages/adapters/src/infra/lua-embedded.ts
index 11fd19078..419db611a 100644
--- a/packages/adapters/src/infra/lua-embedded.ts
+++ b/packages/adapters/src/infra/lua-embedded.ts
@@ -9,14 +9,14 @@
export const EMBEDDED_LUA: Record = {
"geo_country.lua": "LS0gZ2VvX2NvdW50cnkubHVhCi0tIE1heE1pbmQgR2VvTGl0ZTItQ291bnRyeSBsb29rdXAgd2l0aCBwZXItd29ya2VyIExSVSBjYWNoZS4KLS0KLS0gREIgYW5kIGNhY2hlIGFyZSBwZXItd29ya2VyIG9ubHk6IG9uZSBsb2FkIHBlciB3b3JrZXIsIHNoYXJlZCBieSBhbGwKLS0gcmVxdWVzdHMuIE5vIHJlbG9hZCBwZXIgc3RyZWFtIG9yIHBlciByZXF1ZXN0LgotLQotLSBEZXBlbmRlbmNpZXM6Ci0tICAgTHVhIGJpbmRpbmcg4oCUIGBvcGVuc2hpcC5tYXhtaW5kZGJgLCB2ZW5kb3JlZCBiZX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cmVycm9yKGludCBlcnJjb2RlKTsKXV0KCi0tIGVycm9yIGNvZGVzIAotLSBodHRwczovL2dpdGh1Yi5jb20vbWF4bWluZC9saWJtYXhtaW5kZGIvYmxvYi9tYXN0ZXIvaW5jbHVkZS9tYXhtaW5kZGIuaCNMNjYKbG9jYWwgTU1EQl9TVUNDRVNTICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgID0gICAwCmxvY2FsIE1NREJfRklMRV9PUEVOX0VSUk9SICAgICAgICAgICAgICAgICAgICAgICAgICA9ICAgMQpsb2NhbCBNTURCX0NPUlJVUFRfU0VBUkNIX1RSRUVfRVJST1IgICAgICAgICAgICAgICAgPSAgIDIKbG9jYWwgTU1EQl9JTlZBTElEX01FVEFEQVRBX0VSUk9SICAgICAgICAgICAgICAgICAgID0gICAzCmxvY2FsIE1NREJfSU9fRVJST1IgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA9ICAgNApsb2NhbCBNTURCX09VVF9PRl9NRU1PUllfRVJST1IgICAgICAgICAgICAgICAgICAgICAgPSAgIDUKbG9jYWwgTU1EQl9VTktOT1dOX0RBVEFCQVNFX0ZPUk1BVF9FUlJPUiAgICAgICAgICAgID0gICA2CmxvY2FsIE1NREJfSU5WQUxJRF9EQVRBX0VSUk9SICAgICAgICAgICAgICAgICAgICAgICA9ICAgNwpsb2NhbCBNTURCX0lOVkFMSURfTE9PS1VQX1BBVEhfRVJST1IgICAgICAgICAgICAgICAgPSAgIDgKbG9jYWwgTU1EQl9MT09LVVBfUEFUSF9ET0VTX05PVF9NQVRDSF9EQVRBX0VSUk9SICAgID0gICA5CmxvY2FsIE1NREJfSU5WQUxJRF9OT0RFX05VTUJFUl9FUlJPUiAgICAgICAgICAgICAgICA9ICAgMTAKbG9jYWwgTU1EQl9JUFY2X0xPT0tVUF9JTl9JUFY0X0RBVEFCQVNFX0VSUk9SICAgICAgID0gICAxMQoKLS0gZGF0YSB0eXBlCi0tIGh0dHBzOi8vZ2l0aHViLmNvbS9tYXhtaW5kL2xpYm1heG1pbmRkYi9ibG9iL21hc3Rlci9pbmNsdWRlL21heG1pbmRkYi5oI0w0MApsb2NhbCBNTURCX0RBVEFfVFlQRV9FWFRFTkRFRCAgICAgICAgICAgICAgICAgICAgICAgPSAgIDAKbG9jYWwgTU1EQl9EQVRBX1RZUEVfUE9JTlRFUiAgICAgICAgICAgICAgICAgICAgICAgID0gICAxCmxvY2FsIE1NREJfREFUQV9UWVBFX1VURjhfU1RSSU5HICAgICAgICAgICAgICAgICAgICA9ICAgMgpsb2NhbCBNTURCX0RBVEFfVFlQRV9ET1VCTEUgICAgICAgICAgICAgICAgICAgICAgICAgPSAgIDMKbG9jYWwgTU1EQl9EQVRBX1RZUEVfQllURVMgICAgICAgICAgICAgICAgICAgICAgICAgID0gICA0CmxvY2FsIE1NREJfREFUQV9UWVBFX1VJTlQxNiAgICAgICAgICAgICAgICAgICAgICAgICA9ICAgNQpsb2NhbCBNTURCX0RBVEFfVFlQRV9VSU5UMzIgICAgICAgICAgICAgICAgICAgICAgICAgPSAgIDYKbG9jYWwgTU1EQl9EQVRBX1RZUEVfTUFQICAgICAgICAgICAgICAgICAgICAgICAgICAgID0gICA3CmxvY2FsIE1NREJfREFUQV9UWVBFX0lOVDMyICAgICAgICAgICAgICAgICAgICAgICAgICA9ICAgOApsb2NhbCBNTURCX0RBVEFfVFlQRV9VSU5UNjQgICAgICAgICAgICAgICAgICAgICAgICAgPSAgIDkKbG9jYWwgTU1EQl9EQVRBX1RZUEVfVUlOVDEyOCAgICAgICAgICAgICAgICAgICAgICAgID0gICAxMApsb2NhbCBNTURCX0RBVEFfVFlQRV9BUlJBWSAgICAgICAgICAgICAgICAgICAgICAgICAgPSAgIDExCmxvY2FsIE1NREJfREFUQV9UWVBFX0NPTlRBSU5FUiAgICAgICAgICAgICAgICAgICAgICA9ICAgMTIKbG9jYWwgTU1EQl9EQVRBX1RZUEVfRU5EX01BUktFUiAgICAgICAgICAgICAgICAgICAgID0gICAxMwps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yeSB0aGUgc29uYW1lIHRvbyBzbwotLSB0aGUgcnVudGltZSBwYWNrYWdlIGFsb25lIGlzIGVub3VnaCBvbiBldmVyeSBkaXN0cm8uCmxvY2FsIG1heG0KZG8KICAgIGxvY2FsIGNhbmRpZGF0ZXMgPSB7ICdsaWJtYXhtaW5kZGInLCAnbGlibWF4bWluZGRiLnNvLjAnLCAnbGlibWF4bWluZGRiLnNvJyB9CiAgICBsb2NhbCBsYXN0X2VycgogICAgZm9yIGkgPSAxLCAjY2FuZGlkYXRlcyBkbwogICAgICAgIGxvY2FsIG9rLCBsaWIgPSBwY2FsbChmZmkubG9hZCwgY2FuZGlkYXRlc1tpXSkKICAgICAgICBpZiBvayB0aGVuIG1heG0gPSBsaWI7IGJyZWFrIGVuZAogICAgICAgIGxhc3RfZXJyID0gbGliCiAgICBlbmQKICAgIGlmIG5vdCBtYXhtIHRoZW4KICAgICAgICBlcnJvcignbGlibWF4bWluZGRiIG5vdCBsb2FkYWJsZSAodHJpZWQgJyAuLiB0YWJsZS5jb25jYXQoY2FuZGlkYXRlcywgJywgJykgLi4KICAgICAgICAgICAgICAnKTogJyAuLiB0b3N0cmluZyhsYXN0X2VyciksIDIpCiAgICBlbmQKZW5kCi0taHR0cHM6Ly9naXRodWIuY29tL21heG1pbmQvbGlibWF4bWluZGRiCmxvY2FsIG1tZGIgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA9IGZmaV9uZXcoJ01NREJfcycpCmxvY2FsIGluaXR0ZWQgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICA9IGZhbHNlCgpsb2NhbCBmdW5jdGlvbiBtbWRiX3N0cmVycm9yKHJjKQogICAgcmV0dXJuIGZmaV9zdHIobWF4bS5NTURCX3N0cmVycm9yKHJjKSkKZW5kCgpsb2NhbCBmdW5jdGlvbiBnYWlfc3RyZXJyb3IocmMpCiAgICByZXR1cm4gZmZpX3N0cihDLmdhaV9zdHJlcnJvcihyYykpCmVuZAo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dIG9yIHt9CgogICAgICAgIGxvY2FsIGJ1Y2tldHMsIGZsdXNoZWQgPSB7fSwgMAogICAgICAgIGZvciBtID0gdy5mcm9tLCB3LnRvIGRvCiAgICAgICAgICAgIGxvY2FsIHAgPSAiczoiIC4uIGRvbWFpbiAuLiAiOiIgLi4gbQogICAgICAgICAgICAtLSBEcmFpbiBGSVJTVCwgdGhlbiBkZWNpZGU6IGBkcmFpbmAgcmV0dXJucyB3aGF0IGl0IHRvb2ssIGFuZCBhIGNvdW50ZXIgbGVmdAogICAgICAgICAgICAtLSBhdCAwIGJ5IGFuIGVhcmxpZXIgZmx1c2ggbXVzdCBub3QgZW1pdCBhIGJ1Y2tldCBvZiB6ZXJvcy4gKFplcm8gaXMgdHJ1dGh5IGluCiAgICAgICAgICAgIC0tIEx1YSwgc28gdGhlIG9sZCBgaWYgciB0aGVuYCB3b3VsZCBoYXZlIHN0YXJ0ZWQgZG9pbmcgZXhhY3RseSB0aGF0IHRoZSBtb21lbnQKICAgICAgICAgICAgLS0ga2V5cyBzdG9wcGVkIGJlaW5nIGRlbGV0ZWQuKQogICAgICAgICAgICBsb2NhbCByID0gZHJhaW4ocCAuLiAiOnIiKQogICAgICAgICAgICBpZiByID4gMCB0aGVuCiAgICAgICAgICAgICAgICBsb2NhbCBydF91cyA9IGRyYWluKHAgLi4gIjp0IikKICAgICAgICAgICAgICAgIGJ1Y2tldHNbI2J1Y2tldHMgKyAxXSA9IHsKICAgICAgICAgICAgICAgICAgICBtaW51dGUgICAgICAgICAgPSBtLAogICAgICAgICAgICAgICAgICAgIHJlcXVlc3RzICAgICAgICA9IHIsCiAgICAgICAgICAgICAgICAgICAgdW5pcXVlX3JlcXVlc3RzID0gZHJhaW4ocCAuLiAiOnUiKSwKICAgICAgICAgICAgICAgICAgICBiYW5kd2lkdGhfaW4gICAgPSBkcmFpbihwIC4uICI6aSIpLAogICAgICAgICAgICAgICAgICAgIGJhbmR3aWR0aF9vdXQgICA9IGRyYWluKHAgLi4gIjpvIiksCiAgICAgICAgICAgICAgICAgICAgcmVzcG9uc2VfdGltZSAgID0gcnRfdXMgLyAxMDAwMDAwLAogICAgICAgICAgICAgICAgICAgIGNvdW50cmllcyAgICAgICA9IHJlYWRfbWludXRlX2NvdW50cmllcyhjaWR4W21dLCB0cnVlKSwKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGZsdXNoZWQgPSBmbHVzaGVkICsgMQogICAgICAgICAgICBlbmQKICAgICAgICBlbmQKCiAgICAgICAgLS0gRGFpbHkgcm9sbHVwLCBzYW1lIGtleSBjbGFzc2lmaWNhdGlvbiB0aGUgc2luZ2xlLWRvbWFpbiBlbmRwb2ludCB1c2VzLgogICAgICAgIGxvY2FsIGdlbywgcGF0aHMsIHN0YXR1c2VzLCB2aXNpdG9ycyA9IHt9LCB7fSwge30sIDAKICAgICAgICBmb3Igc3VmZml4LCB2IGluIHBhaXJzKHJvbGx1cHNbZG9tYWluXSBvciB7fSkgZG8KICAgICAgICAgICAgaWYgc3VmZml4ID09ICJ2IiB0aGVuCiAgICAgICAgICAgICAgICB2aXNpdG9ycyA9IHYKICAgICAgICAgICAgZWxzZWlmIHN1ZmZpeDpzdWIoMSwgMikgPT0gInA6IiB0aGVuCiAgICAgICAgICAgICAgICBwYXRoc1tzdWZmaXg6c3ViKDMpXSA9IHYKICAgICAgICAgICAgZWxzZWlmIHN1ZmZpeDpzdWIoMSwgMikgPT0gInM6IiB0aGVuCiAgICAgICAgICAgICAgICBzdGF0dXNlc1tzdWZmaXg6c3ViKDMpXSA9IHYKICAgICAgICAgICAgZWxzZWlmIHN1ZmZpeDptYXRjaCgiXiV1JXUkIikgdGhlbgogICAgICAgICAgICAgICAgZ2VvW3N1ZmZpeF0gPSB2CiAgICAgICAgICAgIGVuZAogICAgICAgICAgICAtLSBBbnl0aGluZyBlbHNlIChgcG5gKSBpcyBib29ra2VlcGluZzogbmV2ZXIgcmVwb3J0ZWQgYXMgYSBjb3VudHJ5LgogICAgICAgIGVuZAoKICAgICAgICBvdXRbZG9tYWluXSA9IHsKICAgICAgICAgICAgYnVja2V0cyA9IGJ1Y2tldHMsCiAgICAgICAgICAgIGZsdXNoZWQgPSBmbHVzaGVkLAogICAgICAgICAgICByb2xsdXAgID0gewogICAgICAgICAgICAgICAgZGF5ID0gZGF5LCBjb3VudHJpZXMgPSBnZW8sIHZpc2l0b3JzID0gdmlzaXRvcnMsCiAgICAgICAgICAgICAgICBwYXRocyA9IHBhdGhzLCBzdGF0dXNlcyA9IHN0YXR1c2VzLAogICAgICAgICAgICB9LAogICAgICAgIH0KICAgIGVuZAoKICAgIHJldHVybiBqc29uKHsgZGF5ID0gZGF5LCBkb21haW5zID0gb3V0IH0pCmVuZAoKLS0g4pSA4pSAIEdFVCAvYW5hbHl0aWNzIC0gbWludXRlLWJ1Y2tldCB0aW1lIHNlcmllcyDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKLS0gP2RvbWFpbj1leGFtcGxlLmNvbSZmcm9tPUVQT0NIX01JTiZ0bz1FUE9DSF9NSU4KCmlmIHVyaSA9PSAiL2FuYWx5dGljcyIgdGhlbgogICAgbG9jYWwgZG9tYWluID0gbmd4LnZhci5hcmdfZG9tYWluCiAgICBpZiBub3QgZG9tYWluIG9yIGRvbWFpbiA9PSAiIiB0aGVuIHJldHVybiBiYWQoIm1pc3NpbmcgP2RvbWFpbj0iKSBlbmQKICAgIGRvbWFpbiA9IGRvbWFpbjpsb3dlcigpCgogICAgbG9jYWwgZnJvbV9tID0gdG9udW1iZXIobmd4LnZhci5hcmdfZnJvbSkKICAgIGxvY2FsIHRvX20gICA9IHRvbnVtYmVyKG5neC52YXIuYXJnX3RvKQogICAgaWYgbm90IGZyb21fbSBvciBub3QgdG9fbSB0aGVuCiAgICAgICAgcmV0dXJuIGJhZCgibWlzc2luZyA/ZnJvbT0gYW5kID90bz0gKGVwb2NoIG1pbnV0ZXMpIikKICAgIGVuZAogICAgLS0gQ2FwIGF0IDI0aAogICAgaWYgdG9fbSAtIGZyb21fbSA+IDE0NDAgdGhlbiB0b19tID0gZnJvbV9tICsgMTQ0MCBlbmQKCiAgICAtLSBPTkUgc2NhbiBmb3IgdGhlIHdob2xlIHdpbmRvdyAoc2VlIHNjYW5fY291bnRyeV9pbmRleCkuCiAgICBsb2NhbCBjb3VudHJ5X2luZGV4ID0gc2Nhbl9jb3VudHJ5X2luZGV4KGRvbWFpbiwgZnJvbV9tLCB0b19tKQoKICAgIGxvY2FsIGJ1Y2tldHMgPSB7fQogICAgZm9yIG0gPSBmcm9tX20sIHRvX20gZG8KICAgICAgICBsb2NhbCBwID0gInM6IiAuLiBkb21haW4gLi4gIjoiIC4uIG0KICAgICAgICBsb2NhbCByID0gYW5hbHl0aWNzOmdldChwIC4uICI6ciIpCiAgICAgICAgaWYgciB0aGVuCiAgICAgICAgICAgIC0tIFJlc3BvbnNlIHRpbWUgc3RvcmVkIGFzIG1pY3Jvc2Vjb25kcywgY29udmVydCB0byBzZWNvbmRzIChmbG9hdCkKICAgICAgICAgICAgbG9jYWwgcnRfdXMgPSBhbmFseXRpY3M6Z2V0KHAgLi4gIjp0Iikgb3IgMAogICAgICAgICAgICBidWNrZXRzWyNidWNrZXRzICsgMV0gPSB7CiAgICAgICAgICAgICAgICBtaW51dGUgICAgICAgICAgID0gbSwKICAgICAgICAgICAgICAgIHJlcXVlc3RzICAgICAgICAgPSByLAogICAgICAgICAgICAgICAgdW5pcXVlX3JlcXVlc3RzICA9IGFuYWx5dGljczpnZXQocCAuLiAiOnUiKSBvciAwLAogICAgICAgICAgICAgICAgYmFuZHdpZHRoX2luICAgICA9IGFuYWx5dGljczpnZXQocCAuLiAiOmkiKSBvciAwLAogICAgICAgICAgICAgICAgYmFuZHdpZHRoX291dCAgICA9IGFuYWx5dGljczpnZXQocCAuLiAiOm8iKSBvciAwLAogICAgICAgICAgICAgICAgcmVzcG9uc2V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IG5vdCBmcm9tX20gb3Igbm90IHRvX20gdGhlbgogICAgICAgIHJldHVybiBiYWQoIm1pc3NpbmcgP2Zyb209IGFuZCA/dG89IChlcG9jaCBtaW51dGVzKSIpCiAgICBlbmQKICAgIGlmIHRvX20gLSBmcm9tX20gPiAxNDQwIHRoZW4gdG9fbSA9IGZyb21fbSArIDE0NDAgZW5kCgogICAgLS0gT05FIHNjYW4gZm9yIHRoZSB3aG9sZSB3aW5kb3cgKHNlZSBzY2FuX2NvdW50cnlfaW5kZXgpLgogICAgbG9jYWwgY291bnRyeV9pbmRleCA9IHNjYW5fY291bnRyeV9pbmRleChkb21haW4sIGZyb21fbSwgdG9fbSkKCiAgICBsb2NhbCBidWNrZXRzID0ge30KICAgIGxvY2FsIGZsdXNoZWQgPSAwCiAgICBmb3IgbSA9IGZyb21fbSwgdG9fbSBkbwogICAgICAgIGxvY2FsIHAgPSAiczoiIC4uIGRvbWFpbiAuLiAiOiIgLi4gbQogICAgICAgIC0tIERyYWluLCBkb24ndCBkZWxldGUg4oCUIHNlZSBgZHJhaW5gLiBBIGNvdW50ZXIgYWxyZWFkeSBhdCAwIGlzIG5vdCBhIGJ1Y2tldC4KICAgICAgICBsb2NhbCByID0gZHJhaW4ocCAuLiAiOnIiKQogICAgICAgIGlmIHIgPiAwIHRoZW4KICAgICAgICAgICAgbG9jYWwgcnRfdXMgPSBkcmFpbihwIC4uICI6dCIpCiAgICAgICAgICAgIGJ1Y2tldHNbI2J1Y2tldHMgKyAxXSA9IHsKICAgICAgICAgICAgICAgIG1pbnV0ZSAgICAgICAgICAgPSBtLAogICAgICAgICAgICAgICAgcmVxdWVzdHMgICAgICAgICA9IHIsCiAgICAgICAgICAgICAgICB1bmlxdWVfcmVxdWVzdHMgID0gZHJhaW4ocCAuLiAiOnUiKSwKICAgICAgICAgICAgICAgIGJhbmR3aWR0aF9pbiAgICAgPSBkcmFpbihwIC4uICI6aSIpLAogICAgICAgICAgICAgICAgYmFuZHdpZHRoX291dCAgICA9IGRyYWluKHAgLi4gIjpvIiksCiAgICAgICAgICAgICAgICByZXNwb25zZV90aW1lICAgID0gcnRfdXMgLyAxMDAwMDAwLAogICAgICAgICAgICAgICAgLS0gRHJhaW5lZCB0b286IHRoaXMgZW5kcG9pbnQgaGFuZHMgdGhlIG1pbnV0ZSB0byB0aGUgREIsIHNvIHRoZSBjb3VudHJ5CiAgICAgICAgICAgICAgICAtLSBrZXlzIG11c3QgZ28gd2l0aCBpdCBvciB0aGV5IHdvdWxkIGJlIGNvdW50ZWQgdHdpY2UuCiAgICAgICAgICAgICAgICBjb3VudHJpZXMgICAgICAgID0gcmVhZF9taW51dGVfY291bnRyaWVzKGNvdW50cnlfaW5kZXhbbV0sIHRydWUpLAogICAgICAgICAgICB9CiAgICAgICAgICAgIGZsdXNoZWQgPSBmbHVzaGVkICsgMQogICAgICAgIGVuZAogICAgZW5kCgogICAgcmV0dXJuIGpzb24oeyBkb21haW4gPSBkb21haW4sIGJ1Y2tldHMgPSBidWNrZXRzLCBmbHVzaGVkID0gZmx1c2hlZCB9KQplbmQKCi0tIOKUgOKUgCBHRVQgL2FuYWx5dGljcy90b3RhbHMgLSBsaWZldGltZSBjb3VudGVycyDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKLS0gP2RvbWFpbj1leGFtcGxlLmNvbSAgICAgIOKGkiBzaW5nbGUgZG9tYWluCi0tIChubyBkb21haW4pICAgICAgICAgICAgICDihpIgYWxsIGtub3duIGRvbWFpbnMKCmlmIHVyaSA9PSAiL2FuYWx5dGljcy90b3RhbHMiIHRoZW4KICAgIGxvY2FsIGRvbWFpbiA9IG5neC52YXIuYXJnX2RvbWFpbgoKICAgIGlmIG5vdCBkb21haW4gb3IgZG9tYWluID09ICIiIHRoZW4KICAgICAgICAtLSBUaGUgc2NyYXBlcidzIGRvbWFpbi1kaXNjb3ZlcnkgY2F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m90IGZvdW5kIiB9LCA0MDQpCg==",
+ "mgmt_api.lua": "LS0gbWdtdF9hcGkubHVhCi0tIFJFU1QgYW5hbHl0aWNzIGVuZHBvaW50cyBiYWNrZWQgYnkgbmd4LnNoYXJlZC5kaWN0LgotLSBJbnRlcm5hbCBtYW5hZ2VtZW50IHBvcnQgb25seSAoMTI3LjAuMC4xOjkxNDUpLgoKbG9jYWwgY2pzb24gPSByZXF1aXJlICJjanNvbi5zYWZlIgoKbG9jYWwgYW5hbHl0aWNzICAgID0gbmd4LnNoYXJlZC5hbmFseXRpY3MKbG9jYWwgcmVxdWVzdF9kYXRhID0gbmd4LnNoYXJlZC5yZXF1ZXN0X2RhdGEKbG9jYWwgdXJpICAgICAgICAgID0gbmd4LnZhci51cmkKCmxvY2FsIGZ1bmN0aW9uIGpzb24oZGF0YSwgY29kZSkKICAgIG5neC5zdGF0dXMgPSBjb2RlIG9yIDIwMAogICAgbmd4LmhlYWRlclsiQ29udGVudC1UeXBlIl0gPSAiYXBwbGljYXRpb24vanNvbiIKICAgIG5neC5zYXkoY2pzb24uZW5jb2RlKGRhdGEpKQogICAgcmV0dXJuIG5neC5leGl0KG5neC5zdGF0dXMpCmVuZAoKbG9jYWwgZnVuY3Rpb24gYmFkKG1zZykKICAgIHJldHVybiBqc29uKHsgZXJyb3IgPSBtc2cgfSwgNDAwKQplbmQKCi0tIOKUgOKUgCBHRVQgL2hlYWx0aCDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKLS0gQmFyZSAib2siLCBOT1QgSlNPTi4gcHJvYmVNZ210KCkgaW4gYXBwcy9hcGkvc3JjL2xpYi9wcm9qZWN0LWFuYWx5dGljcy50cwotLSBhc3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2R5KCkKICAgICAgICBsb2NhbCBib2R5ID0gbmd4LnJlcS5nZXRfYm9keV9kYXRhKCkKICAgICAgICBpZiBub3QgYm9keSB0aGVuIHJldHVybiBiYWQoImVtcHR5IGJvZHkiKSBlbmQKICAgICAgICBsb2NhbCBwYXlsb2FkID0gY2pzb24uZGVjb2RlKGJvZHkpCiAgICAgICAgaWYgdHlwZShwYXlsb2FkKSB+PSAidGFibGUiIG9yIHR5cGUocGF5bG9hZC5ob3N0cykgfj0gInRhYmxlIiB0aGVuCiAgICAgICAgICAgIHJldHVybiBiYWQoImV4cGVjdGVkIHsgaG9zdHM6IFsgeyBob3N0LCBwYXRocyB9IF0gfSIpCiAgICAgICAgZW5kCiAgICAgICAgbG9jYWwgYXBwbGllZCA9IDAKICAgICAgICBmb3IgXywgZW50cnkgaW4gaXBhaXJzKHBheWxvYWQuaG9zdHMpIGRvCiAgICAgICAgICAgIGlmIHR5cGUoZW50cnkpID09ICJ0YWJsZSIgYW5kIGVudHJ5Lmhvc3QgdGhlbgogICAgICAgICAgICAgICAgbG9jYWwga2V5ID0gImNmZzoiIC4uIHRvc3RyaW5nKGVudHJ5Lmhvc3QpOmxvd2VyKCkgLi4gIjpwYXRocyIKICAgICAgICAgICAgICAgIGlmIGVudHJ5LnBhdGhzID09IHRydWUgdGhlbgogICAgICAgICAgICAgICAgICAgIHJ1bGVzOnNldChrZXksIDEpCiAgICAgICAgICAgICAgICBlbHNlCiAgICAgICAgICAgICAgICAgICAgLS0gRGVsZXRlZCByYXRoZXIgdGhhbiBzZXQgdG8gMCwgc28gImFic2VudCIgaXMgdGhlIG9ubHkgb2ZmIHN0YXRlIHRoZXJlCiAgICAgICAgICAgICAgICAgICAgLS0gaXMuIFR3byByZXByZXNlbnRhdGlvbnMgb2Ygb2ZmIGlzIGhvdyBhIHJlYWRlciBlbmRzIHVwIHRyZWF0aW5nIG9uZSBvZgogICAgICAgICAgICAgICAgICAgIC0tIHRoZW0gYXMgb24g4oCUIGFuZCBhYn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IGJlaW5nIGRlbGV0ZWQuKQogICAgICAgICAgICBsb2NhbCByID0gZHJhaW4ocCAuLiAiOnIiKQogICAgICAgICAgICBpZiByID4gMCB0aGVuCiAgICAgICAgICAgICAgICBsb2NhbCBydF91cyA9IGRyYWluKHAgLi4gIjp0IikKICAgICAgICAgICAgICAgIGJ1Y2tldHNbI2J1Y2tldHMgKyAxXSA9IHsKICAgICAgICAgICAgICAgICAgICBtaW51dGUgICAgICAgICAgPSBtLAogICAgICAgICAgICAgICAgICAgIHJlcXVlc3RzICAgICAgICA9IHIsCiAgICAgICAgICAgICAgICAgICAgdW5pcXVlX3JlcXVlc3RzID0gZHJhaW4ocCAuLiAiOnUiKSwKICAgICAgICAgICAgICAgICAgICBiYW5kd2lkdGhfaW4gICAgPSBkcmFpbihwIC4uICI6aSIpLAogICAgICAgICAgICAgICAgICAgIGJhbmR3aWR0aF9vdXQgICA9IGRyYWluKHAgLi4gIjpvIiksCiAgICAgICAgICAgICAgICAgICAgcmVzcG9uc2VfdGltZSAgID0gcnRfdXMgLyAxMDAwMDAwLAogICAgICAgICAgICAgICAgICAgIGNvdW50cmllcyAgICAgICA9IHJlYWRfbWludXRlX2NvdW50cmllcyhjaWR4W21dLCB0cnVlKSwKICAgICAgICAgICAgICAgIH0KICAgICAgICAgICAgICAgIGZsdXNoZWQgPSBmbHVzaGVkICsgMQogICAgICAgICAgICBlbmQKICAgICAgICBlbmQKCiAgICAgICAgLS0gRGFpbHkgcm9sbHVwLCBzYW1lIGtleSBjbGFzc2lmaWNhdGlvbiB0aGUgc2luZ2xlLWRvbWFpbiBlbmRwb2ludCB1c2VzLgogICAgICAgIGxvY2FsIGdlbywgcGF0aHMsIHN0YXR1c2VzLCB2aXNpdG9ycyA9IHt9LCB7fSwge30sIDAKICAgICAgICBmb3Igc3VmZml4LCB2IGluIHBhaXJzKHJvbGx1cHNbZG9tYWluXSBvciB7fSkgZG8KICAgICAgICAgICAgaWYgc3VmZml4ID09ICJ2IiB0aGVuCiAgICAgICAgICAgICAgICB2aXNpdG9ycyA9IHYKICAgICAgICAgICAgZWxzZWlmIHN1ZmZpeDpzdWIoMSwgMikgPT0gInA6IiB0aGVuCiAgICAgICAgICAgICAgICBwYXRoc1tzdWZmaXg6c3ViKDMpXSA9IHYKICAgICAgICAgICAgZWxzZWlmIHN1ZmZpeDpzdWIoMSwgMikgPT0gInM6IiB0aGVuCiAgICAgICAgICAgICAgICBzdGF0dXNlc1tzdWZmaXg6c3ViKDMpXSA9IHYKICAgICAgICAgICAgZWxzZWlmIHN1ZmZpeDptYXRjaCgiXiV1JXUkIikgdGhlbgogICAgICAgICAgICAgICAgZ2VvW3N1ZmZpeF0gPSB2CiAgICAgICAgICAgIGVuZAogICAgICAgICAgICAtLSBBbnl0aGluZyBlbHNlIChgcG5gKSBpcyBib29ra2VlcGluZzogbmV2ZXIgcmVwb3J0ZWQgYXMgYSBjb3VudHJ5LgogICAgICAgIGVuZAoKICAgICAgICBvdXRbZG9tYWluXSA9IHsKICAgICAgICAgICAgYnVja2V0cyA9IGJ1Y2tldHMsCiAgICAgICAgICAgIGZsdXNoZWQgPSBmbHVzaGVkLAogICAgICAgICAgICByb2xsdXAgID0gewogICAgICAgICAgICAgICAgZGF5ID0gZGF5LCBjb3VudHJpZXMgPSBnZW8sIHZpc2l0b3JzID0gdmlzaXRvcnMsCiAgICAgICAgICAgICAgICBwYXRocyA9IHBhdGhzLCBzdGF0dXNlcyA9IHN0YXR1c2VzLAogICAgICAgICAgICB9LAogICAgICAgIH0KICAgIGVuZAoKICAgIHJldHVybiBqc29uKHsgZGF5ID0gZGF5LCBkb21haW5zID0gb3V0IH0pCmVuZAoKLS0g4pSA4pSAIEdFVCAvYW5hbHl0aWNzIC0gbWludXRlLWJ1Y2tldCB0aW1lIHNlcmllcyDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKLS0gP2RvbW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gY29udmVydCB0byBzZWNvbmRzIChmbG9hdCkKICAgICAgICAgICAgbG9jYWwgcnRfdXMgPSBhbmFseXRpY3M6Z2V0KHAgLi4gIjp0Iikgb3IgMAogICAgICAgICAgICBidWNrZXRzWyNidWNrZXRzICsgMV0gPSB7CiAgICAgICAgICAgICAgICBtaW51dGUgICAgICAgICAgID0gbSwKICAgICAgICAgICAgICAgIHJlcXVlc3RzICAgICAgICAgPSByLAogICAgICAgICAgICAgICAgdW5pcXVlX3JlcXVlc3RzICA9IGFuYWx5dGljczpnZXQocCAuLiAiOnUiKSBvciAwLAogICAgICAgICAgICAgICAgYmFuZHdpZHRoX2luICAgICA9IGFuYWx5dGljczpnZXQocCAuLiAiOmkiKSBvciAwLAogICAgICAgICAgICAgICAgYmFuZHdpZHRoX291dCAgICA9IGFuYWx5dGljczpnZXQocCAuLiAiOm8iKSBvciAwLAogICAgICAgICAgICAgICAgcmVzcG9uc2VfdGltZSAgICA9IHJ0X3VzIC8gMTAwMDAwMCwKICAgICAgICAgICAgICAgIGNvdW50cmllcyAgICAgICAgPSByZWFkX21pbnV0ZV9jb3VudHJpZXMoY291bnRyeV9pbmRleFttXSwgZmFsc2UpLAogICAgICAgICAgICB9CiAgICAgICAgZW5kCiAgICBlbmQKCiAgICByZXR1cm4ganNvbih7IGRvbWFpbiA9IGRvbWFpbiwgYnVja2V0cyA9IGJ1Y2tldHMgfSkKZW5kCgotLSDilIDilIAgUE9TVCAvYW5hbHl0aWNzL2ZsdXNoIC0gcmVhZCArIGRlbGV0ZSBtaW51dGUgYnVja2V0cyDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKLS0gU2FtZSBhcyBHRVQgL2FuYWx5dGljcyBidXQgZGVsZXRlcyB0aGUgcmV0dXJuZWQgYnVja2V0cyBmcm9tIHNoYXJlZCBtZW1vcnkuCi0tIFVzZWQgYnkgdGhlIHNjcmFwZXIgdG8gYXRvbWljYWxseSBt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gZHJhaW5gLiBBIGNvdW50ZXIgYWxyZWFkeSBhdCAwIGlzIG5vdCBhIGJ1Y2tldC4KICAgICAgICBsb2NhbCByID0gZHJhaW4ocCAuLiAiOnIiKQogICAgICAgIGlmIHIgPiAwIHRoZW4KICAgICAgICAgICAgbG9jYWwgcnRfdXMgPSBkcmFpbihwIC4uICI6dCIpCiAgICAgICAgICAgIGJ1Y2tldHNbI2J1Y2tldHMgKyAxXSA9IHsKICAgICAgICAgICAgICAgIG1pbnV0ZSAgICAgICAgICAgPSBtLAogICAgICAgICAgICAgICAgcmVxdWVzdHMgICAgICAgICA9IHIsCiAgICAgICAgICAgICAgICB1bmlxdWVfcmVxdWVzdHMgID0gZHJhaW4ocCAuLiAiOnUiKSwKICAgICAgICAgICAgICAgIGJhbmR3aWR0aF9pbiAgICAgPSBkcmFpbihwIC4uICI6aSIpLAogICAgICAgICAgICAgICAgYmFuZHdpZHRoX291dCAgICA9IGRyYWluKHAgLi4gIjpvIiksCiAgICAgICAgICAgICAgICByZXNwb25zZV90aW1lICAgID0gcnRfdXMgLyAxMDAwMDAwLAogICAgICAgICAgICAgICAgLS0gRHJhaW5lZCB0b286IHRoaXMgZW5kcG9pbnQgaGFuZHMgdGhlIG1pbnV0ZSB0byB0aGUgREIsIHNvIHRoZSBjb3VudHJ5CiAgICAgICAgICAgICAgICAtLSBrZXlzIG11c3QgZ28gd2l0aCBpdCBvciB0aGV5IHdvdWxkIGJlIGNvdW50ZWQgdHdpY2UuCiAgICAgICAgICAgICAgICBjb3VudHJpZXMgICAgICAgID0gcmVhZF9taW51dGVfY291bnRyaWVzKGNvdW50cnlfaW5kZXhbbV0sIHRydWUpLAogICAgICAgICAgICB9CiAgICAgICAgICAgIGZsdXNoZWQgPSBmbHVzaGVkICsgMQogICAgICAgIGVuZAogICAgZW5kCgogICAgcmV0dXJuIGpzb24oeyBkb21haW4gPSBkb21haW4sIGJ1Y2tldHMgPSBidWNrZXRzLCBmbHVzaGVkID0gZmx1c2hlZC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ZXZpY3RlZDsgcmVwb3J0IGl0CiAgICAgICAgICAgIC0tIHdpdGggemVyb3MgcmF0aGVyIHRoYW4gb21pdHRpbmcgaXQsIHNvIHRoZSBzY3JhcGVyIHN0aWxsIGFza3MgZm9yIGl0cyBidWNrZXRzLgogICAgICAgICAgICBkb21haW5zWyNkb21haW5zICsgMV0gPSB7CiAgICAgICAgICAgICAgICBkb21haW4gICAgICAgID0gZCwKICAgICAgICAgICAgICAgIHJlcXVlc3RzICAgICAgPSBhbmFseXRpY3M6Z2V0KCJ0OiIgLi4gZCAuLiAiOnIiKSBvciAwLAogICAgICAgICAgICAgICAgYmFuZHdpZHRoX2luICA9IGFuYWx5dGljczpnZXQoInQ6IiAuLiBkIC4uICI6aSIpIG9yIDAsCiAgICAgICAgICAgICAgICBiYW5kd2lkdGhfb3V0ID0gYW5hbHl0aWNzOmdldCgidDoiIC4uIGQgLi4gIjpvIikgb3IgMCwKICAgICAgICAgICAgfQogICAgICAgIGVuZAogICAgICAgIHJldHVybiBqc29uKHsgZG9tYWlucyA9IGRvbWFpbnMgfSkKICAgIGVuZAoKICAgIGRvbWFpbiA9IGRvbWFpbjpsb3dlcigpCiAgICByZXR1cm4ganNvbih7CiAgICAgICAgZG9tYWluICAgICAgICA9IGRvbWFpbiwKICAgICAgICByZXF1ZXN0cyAgICAgID0gYW5hbHl0aWNzOmdldCgidDoiIC4uIGRvbWFpbiAuLiAiOnIiKSBvciAwLAogICAgICAgIGJhbmR3aWR0aF9pbiAgPSBhbmFseXRpY3M6Z2V0KCJ0OiIgLi4gZG9tYWluIC4uICI6aSIpIG9yIDAsCiAgICAgICAgYmFuZHdpZHRoX291dCA9IGFuYWx5dGljczpnZXQoInQ6IiAuLiBkb21haW4gLi4gIjpvIikgb3IgMCwKICAgIH0pCmVuZAoKLS0g4pSA4pSAIEdFVCAvYW5hbHl0aWNzL2dlbyAtIGRhaWx5IHJvbGx1cCBmb3IgYSBkYXkg4pSA4pSA4pSA4pSA4pSA4pSA4pS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ICBvdXQucmwgPSB7CiAgICAgICAgICAgIGxpbWl0ID0gbWF0aC5mbG9vcihycHMpICsgbWF0aC5mbG9vcih0b251bWJlcihybC5idXJzdCkgb3IgMCksCiAgICAgICAgICAgIHN0YXR1cyA9IHRvbnVtYmVyKHJsLnN0YXR1cykgb3IgNDI5LAogICAgICAgIH0KICAgIGVuZAoKICAgIGxvY2FsIGJhbiA9IHNwZWMuYmFuCiAgICBpZiB0eXBlKGJhbikgPT0gInRhYmxlIiB0aGVuCiAgICAgICAgb3V0LmJhbiA9IHsKICAgICAgICAgICAgaXBzID0gY29tcGlsZV9saXN0KGJhbi5pcHMpLAogICAgICAgICAgICBjaWRycyA9IGNvbXBpbGVfbGlzdChiYW4uY2lkcnMpLAogICAgICAgICAgICBjb3VudHJpZXMgPSB0b19zZXQoYmFuLmNvdW50cmllcyksCiAgICAgICAgICAgIHVhcyA9IGxvd2VyX2xpc3QoYmFuLnVzZXJBZ2VudHMpLAogICAgICAgICAgICBlbXB0eVVBID0gYmFuLmVtcHR5VXNlckFnZW50ID09IHRydWUsCiAgICAgICAgfQogICAgZW5kCgogICAgbG9jYWwgYWNjID0gc3BlYy5hY2Nlc3MKICAgIGlmIHR5cGUoYWNjKSA9PSAidGFibGUiIHRoZW4KICAgICAgICBvdXQuYWNjZXNzID0gewogICAgICAgICAgICBhbGxvdyA9IGNvbXBpbGVfbGlzdChhY2MuYWxsb3dDaWRycyksCiAgICAgICAgICAgIGRlbnkgPSBjb21waWxlX2xpc3QoYWNjLmRlbnlDaWRycyksCiAgICAgICAgICAgIGFsbG93Q291bnRyaWVzID0gdG9fc2V0KGFjYy5hbGxvd0NvdW50cmllcyksCiAgICAgICAgICAgIG1ldGhvZHMgPSB0b19zZXQoYWNjLm1ldGhvZHMpLAogICAgICAgIH0KICAgIGVuZAoKICAgIGxvY2FsIGhvdCA9IHNwZWMuaG90bGluawogICAgaWYgdHlwZShob3QpID09ICJ0YWJsZSIgdGhlbgogICAgICAgIGxvY2FsIHJl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mFuID0gewogICAgICAgICAgICBpcHMgPSBjb21waWxlX2xpc3QoYmFuLmlwcyksCiAgICAgICAgICAgIGNpZHJzID0gY29tcGlsZV9saXN0KGJhbi5jaWRycyksCiAgICAgICAgICAgIGNvdW50cmllcyA9IHRvX3NldChiYW4uY291bnRyaWVzKSwKICAgICAgICAgICAgdWFzID0gbG93ZXJfbGlzdChiYW4udXNlckFnZW50cyksCiAgICAgICAgICAgIGVtcHR5VUEgPSBiYW4uZW1wdHlVc2VyQWdlbnQgPT0gdHJ1ZSwKICAgICAgICB9CiAgICBlbmQKCiAgICBsb2NhbCBhY2MgPSBzcGVjLmFjY2VzcwogICAgaWYgdHlwZShhY2MpID09ICJ0YWJsZSIgdGhlbgogICAgICAgIG91dC5hY2Nlc3MgPSB7CiAgICAgICAgICAgIGFsbG93ID0gY29tcGlsZV9saXN0KGFjYy5hbGxvd0NpZHJzKSwKICAgICAgICAgICAgZGVueSA9IGNvbXBpbGVfbGlzdChhY2MuZGVueUNpZHJzKSwKICAgICAgICAgICAgYWxsb3dDb3VudHJpZXMgPSB0b19zZXQoYWNjLmFsbG93Q291bnRyaWVzKSwKICAgICAgICAgICAgbWV0aG9kcyA9IHRvX3NldChhY2MubWV0aG9kcyksCiAgICAgICAgfQogICAgZW5kCgogICAgbG9jYWwgaG90ID0gc3BlYy5ob3RsaW5rCiAgICBpZiB0eXBlKGhvdCkgPT0gInRhYmxlIiB0aGVuCiAgICAgICAgbG9jYWwgcmVmcyA9IHRvX3NldChob3QuYWxsb3dSZWZlcmVycywgdHJ1ZSkKICAgICAgICBpZiByZWZzIHRoZW4KICAgICAgICAgICAgb3V0LmhvdGxpbmsgPSB7IHJlZmVyZXJzID0gcmVmcywgYWxsb3dFbXB0eSA9IGhvdC5hbGxvd0VtcHR5IH49IGZhbHNlIH0KICAgICAgICBlbmQKICAgIGVuZAoKICAgIG91dC5ibG9ja1N0YXR1cyA9ICh0eXBlKHNwZWMuYmxvY2spID09ICJ0YWJsZSIgYW5kI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GVuIHJldHVybiBoaXQucGFyc2VkIGVuZAogICAgbG9jYWwgcGFyc2VkID0gcGFyc2UocmF3KQogICAgY2FjaGU6c2V0KGhvc3QsIHsgcmF3ID0gcmF3LCBwYXJzZWQgPSBwYXJzZWQgfSkKICAgIHJldHVybiBwYXJzZWQKZW5kCgpyZXR1cm4gTQo=",
"site_logger.lua": "LS0gc2l0ZV9sb2dnZXIubHVhCi0tIE9wZW5SZXN0eSBsb2dfYnlfbHVhIC0gcnVucyBBRlRFUiB0aGUgcmVzcG9uc2UgaXMgc2VudC4KLS0gUHVyZSBzaGFyZWQtZGljdCBhbmFseXRpY3MuICBObyBSZWRpcywgbm8gdGltZXJzIGZvciBjb3VudGVycywgbm8gYmF0Y2hpbmcuCi0tIEV2ZXJ5IGluY3IoKSBpcyBhdG9taWMgYWNyb3NzIHdvcmtlcnMuCi0tCi0tIFNoYXJlZCBkaWN0IGtleSBzY2hlbWEgKGFuYWx5dGljcyB6b25lKToKLS0gICBzOntkb21haW59OntlcG9jaF9taW59OnIgICAgICAgIHJlcXVlc3QgY291bnQgICAgICAgICAgICAgICAoVFRMIDI0aCkKLS0gICBzOntkb21haW59OntlcG9jaF9taW59OmkgICAgICAgIGJhbmR3aWR0aCBpbiAgYnl0ZXMgICAgICAgICAoVFRMIDI0aCkKLS0gICBzOntkb21haW59OntlcG9jaF9taW59Om8gICAgICAgIGJhbmR3aWR0aCBvdXQgYnl0ZXMgICAgICAgICAoVFRMIDI0aCkKLS0gICBzOntkb21haW59OntlcG9jaF9taW59OnQgICAgICAgIHJlc3BvbnNlIHRpbWUgc3VtIChzZWNvbmRzKSAoVFRMIDI0aCkKLS0gICBzOntkb21haW59OntlcG9jaF9taW59OnUgICAgICAgIHBhZ2UgKG5vbi1zdGF0aWMpIHJlcXVlc3RzICAoVFRMIDI0aCkKLS0gICBjOntkb21haW59OntlcG9jaF9taW59OntDQ30gICAgIGNvdW50cnkgcGVyIG1pbnV0ZSAgICAgICAgICAoVFRMIDI0aCkKLS0gICB0Ontkb21haW59OnIgLyA6aSAvIDpvICAgICAgICAgIGxpZmV0aW1lIHRvdGFscyAgICAgICAgICAgICAobm8gVFRMKQotLSAgIGQ6e2RvbWFpbn0gICAgICAgICAgICAgICAgICAgICAgZG9tYWluIGluZGV4IG1hcmtlciAgICAgICAgIChubyBUVEwpCi0tCi0tICAgRGFpbHkgcm9sbHVwLCBhbGwgdW5kZXIgb25lIGBnOntkb21haW59OntZWVlZTU1ERH06YCBwcmVmaXggc28gbWdtdF9hcGkncwotLSAgIC9hbmFseXRpY3MvZ2VvIHNlcnZlcyB0aGUgd2hvbGUgZGF5IGluIGEgU0lOR0xFIGRpY3Qgc2NhbjoKLS0gICBnOntkb21haW59OntZWVlZTU1ERH06e0NDfSAgICAgIGNvdW50cnkgaGl0IGNvdW50ICAgICAgICAgICAoVFRMIDQ4aCkKLS0gICBnOntkb21haW59OntZWVlZTU1ERH06diAgICAgICAgIGRpc3RpbmN0IHZpc2l0b3JzICAgICAgICAgICAoVFRMIDQ4aCkKLS0gICBnOntkb21haW59OntZWVlZTU1ERH06cDp7cGF0aH0gIHBhdGggaGl0IGNvdW50ICAgICAgICAgICAgICAoVFRMIDQ4aCkKLS0gICBnOntkb21haW59OntZWVlZTU1ERH06czp7Y29kZX0gIHN0YXR1cy1jb2RlIGNvdW50ICAgICAgICAgICAoVFRMIDQ4aCkKLS0KLS0gU2hhcmVkIGRpY3Qga2V5IHNjaGVtYSAodmlzaXRvcnMgem9uZSk6Ci0tICAgdnNhbHQ6e1lZWVlNTUREfSAgICAgICAgICAgICAgICBwZXItZGF5IGhhc2ggc2FsdCAgICAgICAgICAgKFRUTCA0OGgpCi0tICAgdmQ6e2RvbWFpbn06e1lZWVlNTUREfTp7aGFzaH0gICBkaXN0aW5jdC12aXNpdG9yIG1hcmtlciAgICAgKFRUTCA0OGgpCi0tCi0tIFNoYXJlZCBkaWN0IGtleSBzY2hlbWEgKHJlcXVlc3RfZGF0YSB6b25lKToKLS0gICBybG9n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b3VudGVycyDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIAKCmxvY2FsIG1pbnV0ZSA9IG1hdGguZmxvb3IodHMgLyA2MCkKbG9jYWwgcCA9ICJzOiIgLi4gaG9zdCAuLiAiOiIgLi4gbWludXRlCgphbmFseXRpY3M6aW5jcihwIC4uICI6ciIsIDEsICAgICAgMCwgRDI0SCkKYW5hbHl0aWNzOmluY3IocCAuLiAiOmkiLCByZXFfbGVuLCAwLCBEMjRIKQphbmFseXRpY3M6aW5jcihwIC4uICI6byIsIGJ5dGVzLCAgIDAsIEQyNEgpCgotLSBSZXNwb25zZSB0aW1lIGFzIGZsb2F0IHNlY29uZHMgKG1hdGNoZXMgb3JpZ2luYWwgcHJlY2lzaW9uKQppZiBydCA+IDAgdGhlbgogICAgLS0gc2FmZV9hZGQgaW5pdGlhbGl6ZXMsIGluY3IgYWRkcyAtIGVtdWxhdGUgSElOQ1JCWUZMT0FUIHdpdGggaW50ZWdlciBtaWNyb3MKICAgIGxvY2FsIHJ0X3VzID0gbWF0aC5mbG9vcihydCAqIDEwMDAwMDApCiAgICBhbmFseXRpY3M6aW5jcihwIC4uICI6dCIsIHJ0X3VzLCAwLCBEMjRIKQplbmQKCi0tIFVuaXF1ZSAobm9uLXN0YXRpYykgcmVxdWVzdCBjb3VudGVyCmlmIG5vdCBpc19zdGF0aWNfYXNzZXQodXJpKSB0aGVuCiAgICBhbmFseXRpY3M6aW5jcihwIC4uICI6dSIsIDEsIDAsIEQyNEgpCmVuZAoKLS0g4pSA4pSAIDIuIExpZmV0aW1lIHRvdGFscyDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilIDilI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gICAgPSB0cywKICAgICAgICBtZXRob2QgPSBtZXRob2QsCiAgICAgICAgc3RhdHVzID0gc3RhdHVzLAogICAgICAgIHVyaSAgICA9IHVyaSwKICAgICAgICB1YSAgICAgPSB1YSwKICAgICAgICBid19pbiAgPSByZXFfbGVuLAogICAgICAgIGJ3X291dCA9IGJ5dGVzLAogICAgICAgIHJ0ICAgICA9IHJ0LAogICAgfSkKICAgIGlmIG9rX2ogYW5kIGogdGhlbgogICAgICAgIHJlcXVlc3RfZGF0YTpzZXQoInJsb2c6IiAuLiBob3N0IC4uICI6IiAuLiAoc2VxICUgUklORyksIGosIEQxSCkKICAgIGVuZAplbmQpCg==",
"webhook_handler.lua": "LS0gd2ViaG9va19oYW5kbGVyLmx1YQotLSBIYW5kbGVzIGluY29taW5nIHdlYmhvb2sgZXZlbnRzIGZvcndhcmRlZCBmcm9tIHRoZSBTYWFTIGVkZ2UuCi0tIEludGVybmFsIG1hbmFnZW1lbnQgcG9ydCBvbmx5ICgxMjcuMC4wLjE6OTE0NSkuCi0tCi0tIFJvdXRlczoKLS0gICBQT1NUIC9faG9va3MvcHVzaCAgICAgICAgICAtIHJlY2VpdmUgYSBmb3J3YXJkZWQgR2l0SHViIHB1c2ggZXZlbnQKLS0gICBHRVQgIC9faG9va3MvcGVuZGluZyAgICAgICAtIGZldGNoIHN0b3JlZCBldmVudHMgKGZvciBsb2NhbCBhcHAgcG9sbGluZykKLS0gICBQT1NUIC9faG9va3MvYWNrICAgICAgICAgICAtIGFja25vd2xlZGdlIGNvbnN1bWVkIGV2ZW50cwotLQotLSBCZWhhdmlvciBvbiBQT1NUIC9faG9va3MvcHVzaDoKLS0gICAxLiBUcnkgdG8gcHJveHkgdG8gYSBsb2NhbCBPcGVuc2hpcCBBUEkgKGNvbmZpZ3VyYWJsZSB2aWEgWC1PcGVuc2hpcC1VcmwgaGVhZGVyKQotLSAgIDIuIElmIE9wZW5zaGlwIGlzIG5vdCByZWFjaGFibGUsIHN0b3JlIHRoZSBld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zL3B1c2giIGFuZCBtZXRob2QgPT0gIlBPU1QiIHRoZW4KICAgIG5neC5yZXEucmVhZF9ib2R5KCkKICAgIGxvY2FsIGJvZHkgPSBuZ3gucmVxLmdldF9ib2R5X2RhdGEoKQogICAgaWYgbm90IGJvZHkgdGhlbgogICAgICAgIHJldHVybiBqc29uX3Jlc3BvbnNlKHsgZXJyb3IgPSAiZW1wdHkgYm9keSIgfSwgNDAwKQogICAgZW5kCgogICAgbG9jYWwgb3BlbnNoaXBfdXJsID0gbmd4LnJlcS5nZXRfaGVhZGVycygpWyJ4LW9wZW5zaGlwLXVybCJdCgogICAgLS0gSWYgT3BlbnNoaXAgcnVucyBvbiB0aGlzIHNlcnZlciwgcHJveHkgZGlyZWN0bHkKICAgIGlmIG9wZW5zaGlwX3VybCBhbmQgb3BlbnNoaXBfdXJsIH49ICIiIHRoZW4KICAgICAgICBsb2NhbCBodHRwID0gcmVxdWlyZSAicmVzdHkuaHR0cCIKICAgICAgICBsb2NhbCBodHRwYyA9IGh0dHAubmV3KCkKICAgICAgICBodHRwYzpzZXRfdGltZW91dCg1MDAwKQoKICAgICAgICBsb2NhbCB0YXJnZXQgPSBvcGVuc2hpcF91cmwgLi4gIi9hcGkvd2ViaG9va3MvcHVzaCIKICAgICAgICBsb2NhbCByZXMsIGVyciA9IGh0dHBjOnJlcXVlc3RfdXJpKHRhcmdldCwgewogICAgICAgICAgICBtZXRob2QgID0gIlBPU1QiLAogICAgICAgICAgICBib2R5ICAgID0gYm9keSwKICAgICAgICAgICAgaGVhZGVycyA9IHsKICAgICAgICAgICAgICAgIFsiQ29udGVudC1UeXBlIl0gPSAiYXBwbGljYXRpb24vanNvbiIsCiAgICAgICAgICAgICAgICBbIlgtSG9vay1JZCJdICAgID0gbmd4LnJlcS5nZXRfaGVhZGVycygpWyJ4LWhvb2staWQiXSBvciAiIiwKICAgICAgICAgICAgfSwKICAgICAgICB9KQoKICAgICAgICBpZiByZXMgYW5kIHJlcy5zdGF0dXMgPCA1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gOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgOKUgApyZXR1cm4ganNvbl9yZXNwb25zZSh7IGVycm9yID0gIm5vdCBmb3VuZCIgfSwgNDA0KQo=",
};
diff --git a/packages/adapters/src/infra/lua/mgmt_api.lua b/packages/adapters/src/infra/lua/mgmt_api.lua
index 0fd76b037..2f78da6d1 100644
--- a/packages/adapters/src/infra/lua/mgmt_api.lua
+++ b/packages/adapters/src/infra/lua/mgmt_api.lua
@@ -134,12 +134,6 @@ if uri == "/analytics/config" then
return json({ error = "method not allowed" }, 405)
end
--- Safe to probe before sending a new rule kind to an older edge. It cannot
--- clear a ruleset, unlike an empty POST /rules.
-if uri == "/rules/capabilities" then
- return json({ ok = true, staticResponses = require("openship.rules_lib").static_responses == true })
-end
-
if uri == "/rules" then
local rules = ngx.shared.rules
if not rules then return json({ error = "rules dict unavailable" }, 503) end
@@ -150,92 +144,33 @@ if uri == "/rules" then
if not host or host == "" then return bad("missing ?host=") end
host = host:lower()
local raw = rules:get(host)
- local list = raw and cjson.decode(raw) or {}
- local responses = rules:get("responses:" .. host)
- for _, entry in ipairs(responses and cjson.decode(responses) or {}) do
- list[#list + 1] = entry
- end
- return json({ host = host, rules = list })
+ return json({ host = host, rules = raw and cjson.decode(raw) or {} })
end
if method == "DELETE" then
local host = ngx.var.arg_host
if not host or host == "" then return bad("missing ?host=") end
rules:delete(host:lower())
- rules:delete("responses-version:" .. host:lower())
- rules:delete("responses:" .. host:lower())
return json({ ok = true })
end
if method == "POST" then
ngx.req.read_body()
local body = ngx.req.get_body_data()
- -- Literal response content can exceed nginx's in-memory body buffer.
- -- Read only the temporary file nginx created for THIS request.
- if not body then
- local path = ngx.req.get_body_file()
- local file = path and io.open(path, "rb")
- if file then
- body = file:read(8 * 1024 * 1024 + 1)
- file:close()
- end
- end
if not body then return bad("empty body") end
- if #body > 8 * 1024 * 1024 then return bad("rules payload exceeds 8 MiB") end
local payload = cjson.decode(body)
- if type(payload) ~= "table" or type(payload.host) ~= "string"
- or #payload.host == 0 or #payload.host > 253
- or string.find(payload.host, "[^0-9A-Za-z.*_%-]") then
+ if type(payload) ~= "table" or not payload.host then
return bad("expected { host, rules: [...] }")
end
local host = tostring(payload.host):lower()
local list = payload.rules
if type(list) ~= "table" or #list == 0 then
rules:delete(host) -- empty set = clear the host
- rules:delete("responses-version:" .. host)
- rules:delete("responses:" .. host)
return json({ ok = true, host = host, count = 0 })
end
- -- Keep responses out of the legacy policy key. A worker still running
- -- the old guard during an upgrade must never treat one as an empty
- -- access policy and shadow the domain's real protections.
- local policies, responses = {}, {}
- for _, entry in ipairs(list) do
- local target = type(entry) == "table" and type(entry.spec) == "table"
- and entry.spec.response ~= nil and responses or policies
- target[#target + 1] = entry
- end
- local lib = require "openship.rules_lib"
- if #responses > 0 then
- if lib.static_responses ~= true or type(lib.valid_responses) ~= "function"
- or type(lib.response_revision) ~= "function" then
- return json({ error = "reload the edge to enable static responses" }, 409)
- end
- if not lib.valid_responses(responses) then
- return bad("invalid static response rules (maximum 64 per domain)")
- end
- end
- local response_raw = #responses > 0 and cjson.encode(responses) or nil
- local revision = response_raw and lib.response_revision(response_raw) or nil
- if response_raw and not revision then return json({ error = "response digest failed" }, 500) end
- if #policies == 0 then rules:delete(host) else
- -- Literal bodies must not evict this or another host's policies.
- local ok, err = rules:safe_set(host, cjson.encode(policies))
- if not ok then return json({ error = "set failed: " .. (err or "?") }, 503) end
- end
- if response_raw then
- local ok, err = rules:safe_set("responses:" .. host, response_raw)
- if not ok then return json({ error = "set failed: " .. (err or "?") }, 503) end
- -- Publish the small revision last: warm requests never copy the
- -- potentially multi-megabyte response payload out of shared memory.
- ok, err = rules:safe_set("responses-version:" .. host, revision)
- if not ok then return json({ error = "set failed: " .. (err or "?") }, 503) end
- else
- rules:delete("responses-version:" .. host)
- rules:delete("responses:" .. host)
- end
- return json({ ok = true, host = host, count = #list,
- staticResponses = lib.static_responses == true })
+ local ok, err = rules:set(host, cjson.encode(list))
+ if not ok then return json({ error = "set failed: " .. (err or "?") }, 500) end
+ return json({ ok = true, host = host, count = #list })
end
return json({ error = "method not allowed" }, 405)
diff --git a/packages/adapters/src/infra/lua/rules_guard.lua b/packages/adapters/src/infra/lua/rules_guard.lua
index dd0a513f8..8d66ca7fe 100644
--- a/packages/adapters/src/infra/lua/rules_guard.lua
+++ b/packages/adapters/src/infra/lua/rules_guard.lua
@@ -8,7 +8,7 @@
--
-- Enforcement uses the connecting peer (ngx.var.remote_addr); front a real_ip
-- config if behind a trusted proxy. No user-supplied value is ever used as a
--- Lua pattern. Static response headers are validated at the API and compile boundary.
+-- Lua pattern or written into a response header.
-- GeoIP owns the worker's IP cache; share its result with rules and analytics.
-- A lookup failure must not turn ordinary app traffic into a 500.
@@ -34,8 +34,7 @@ local host = ngx.var.host
if not host then return end
local raw = rules:get(host)
-local response_revision = rules:get("responses-version:" .. host)
-if not raw and not response_revision then
+if not raw then
-- A wildcard vhost's rules are stored under its server_name ("*.example.com"),
-- while $host is the concrete name the visitor asked for. Each vhost declares
-- exactly one server_name, so it is the rule key for any subdomain depth.
@@ -43,32 +42,30 @@ if not raw and not response_revision then
if name and name ~= host and string.sub(name, 1, 2) == "*." then
host = name
raw = rules:get(host)
- response_revision = rules:get("responses-version:" .. host)
end
end
-if not raw and not response_revision then return end -- nothing configured for this host
+if not raw then return end -- fast path: nothing configured for this host
local lib = require "openship.rules_lib"
-local entries = raw and lib.get(host, raw) or {}
--- Longest policy prefix wins independently of the virtual response.
+local entries = lib.get(host, raw)
+local n = #entries
+if n == 0 then return end
+
+-- ── Longest matching pathPrefix wins ──
local uri = ngx.var.uri or "/"
local chosen, chosen_len = nil, -1
-for i = 1, #entries do
+for i = 1, n do
local e = entries[i]
local p = e.pathPrefix
- if not e.spec.isResponse then
- if p == nil or p == "" or p == "/" then
- if chosen_len < 0 then chosen, chosen_len = e, 0 end
- elseif uri == p or string.sub(uri, 1, #p) == p then
- if #p > chosen_len then chosen, chosen_len = e, #p end
- end
+ if p == nil or p == "" or p == "/" then
+ if chosen_len < 0 then chosen, chosen_len = e, 0 end
+ elseif uri == p or string.sub(uri, 1, #p) == p then
+ if #p > chosen_len then chosen, chosen_len = e, #p end
end
end
-if not chosen and not response_revision then return end
+if not chosen then return end
--- Select policy independently: a static response can never replace a more
--- general ban, method allow-list, or rate limit simply by matching its path.
-local spec = chosen and chosen.spec or {}
+local spec = chosen.spec
local deny_status = spec.blockStatus or 403
local ips = ngx.var.remote_addr or "0.0.0.0"
@@ -144,29 +141,3 @@ if rl then
return ngx.exit(rl.status)
end
end
-
-local response, method
--- During a rolling script update this file can be new while require() still
--- holds the previous worker library. Keep ordinary policy enforcement working.
-if response_revision and lib.static_responses == true and type(lib.response_for) == "function"
- and not lib.reserved_path(uri) then
- -- Internal SPA/index rewrites must not turn an unrelated request into a
- -- virtual route. Decode the original path only on configured domains.
- local response_uri = ngx.unescape_uri(string.match(ngx.var.request_uri or uri, "^[^?]*"))
- method = ngx.req.get_method()
- response = lib.response_for(host, response_revision, rules, response_uri, method)
-end
-
--- Literal content only, after ALL access policies. Never generated nginx/Lua
--- source. ngx.print preserves the exact body (including an empty response).
-if response then
- ngx.status = response.status
- ngx.header["Content-Type"] = response.contentType
- for name, value in pairs(response.headers) do ngx.header[name] = value end
- if response.status ~= 204 and response.status ~= 304 then
- ngx.header["Content-Length"] = #response.body
- end
- ngx.send_headers()
- if method ~= "HEAD" and response.body ~= "" then ngx.print(response.body) end
- return ngx.exit(ngx.HTTP_OK)
-end
diff --git a/packages/adapters/src/infra/lua/rules_lib.lua b/packages/adapters/src/infra/lua/rules_lib.lua
index bf0a43f69..f48ab50dd 100644
--- a/packages/adapters/src/infra/lua/rules_lib.lua
+++ b/packages/adapters/src/infra/lua/rules_lib.lua
@@ -18,8 +18,6 @@ local cjson = require "cjson.safe"
local lrucache = require "resty.lrucache"
local M = {}
-M.static_responses = true
-M.response_methods = { GET=true, HEAD=true, POST=true, PUT=true, PATCH=true, DELETE=true, OPTIONS=true }
local cache = lrucache.new(1024) -- compiled rules, per worker, ~1024 hosts
@@ -106,87 +104,6 @@ local function to_set(list, lower)
return any and set or nil
end
--- Response validation runs at management writes and on a worker cache miss,
--- never for each request. Keep these bounds aligned with core/edge-response.ts.
-local managed_headers = { ["content-type"]=true, ["content-length"]=true, ["content-encoding"]=true,
- ["transfer-encoding"]=true, connection=true, ["keep-alive"]=true,
- ["proxy-authenticate"]=true, ["proxy-authorization"]=true, te=true, trailer=true,
- upgrade=true, ["x-accel-redirect"]=true }
-local token = "[!#$%%&'*+%.%^_`|~0-9A-Za-z%-]+"
-M.max_responses = 64
-
-local function reserved_path(path)
- return path == "/_openship" or string.sub(path, 1, 11) == "/_openship/"
- or path == "/.openship" or string.sub(path, 1, 11) == "/.openship/"
- or path == "/.well-known/acme-challenge" or string.sub(path, 1, 28) == "/.well-known/acme-challenge/"
-end
-M.reserved_path = reserved_path
-
-local function compile_response(e)
- if type(e) ~= "table" or type(e.spec) ~= "table" then return nil end
- local spec, path = e.spec, e.pathPrefix
- if path == nil or path == cjson.null then path = "/" end
- if type(path) ~= "string" or #path > 512 or string.sub(path, 1, 1) ~= "/"
- or string.find(path, "[%z\1-\32\127?#%%\\]") or string.find(path, "//", 1, true)
- or string.find(path .. "/", "/./", 1, true) or string.find(path .. "/", "/../", 1, true)
- or reserved_path(path) then return nil end
- -- Policies are separate entries, selected independently of response matches.
- if spec.access or spec.ban or spec.hotlink or spec.rateLimit or spec.block then return nil end
- local response = spec.response
- if type(response) ~= "table" or type(response.status) ~= "number"
- or response.status < 200 or response.status > 599 or response.status % 1 ~= 0
- or type(response.body) ~= "string" or #response.body > 65536
- or type(response.contentType) ~= "string" or #response.contentType > 256
- or string.find(response.contentType, "[%z\1-\31\127]")
- or (response.match ~= "exact" and response.match ~= "prefix") then return nil end
- local suffix = string.match(response.contentType, "^" .. token .. "/" .. token .. "(.*)$")
- if not suffix or (suffix ~= "" and not string.match(suffix, "^ *;")) then return nil end
- if (response.status == 204 or response.status == 205 or response.status == 304)
- and response.body ~= "" then return nil end
- if type(response.headers) ~= "table" or type(response.methods) ~= "table"
- or #response.methods > 7 then return nil end
- local headers, seen, count, size = {}, {}, 0, 0
- for name, value in pairs(response.headers) do
- if type(name) ~= "string" or #name == 0 or #name > 128
- or not string.match(name, "^" .. token .. "$")
- or managed_headers[string.lower(name)] or seen[string.lower(name)]
- or type(value) ~= "string" or #value > 2048
- or string.find(value, "[%z\1-\31\127]") then return nil end
- count, size = count + 1, size + #name + #value
- if count > 32 or size > 8192 then return nil end
- seen[string.lower(name)], headers[name] = true, value
- end
- local methods = {}
- for i, method in pairs(response.methods) do
- if type(i) ~= "number" or i < 1 or i > #response.methods or i % 1 ~= 0
- or type(method) ~= "string" or not M.response_methods[method] then return nil end
- methods[method] = true
- end
- return { path=path, boundary=string.sub(path, -1) == "/" and path or path .. "/",
- match=response.match, status=response.status, body=response.body,
- contentType=response.contentType, headers=headers,
- methods=#response.methods > 0 and methods or nil }
-end
-
-function M.valid_responses(entries)
- if #entries > M.max_responses then return false end
- local seen = {}
- for _, e in ipairs(entries) do
- local r = compile_response(e)
- if not r then return false end
- local key = r.match .. ":" .. r.path
- if seen[key] then return false end
- seen[key] = true
- end
- return true
-end
-
-function M.response_revision(raw)
- local hash = require("resty.sha256"):new()
- if not hash or not hash:update(raw) then return nil end
- return hash:final()
-end
-
-- Compile one RouteRuleSpec into a fast-match shape.
local function compile_spec(spec)
if type(spec) ~= "table" then return { blockStatus = 403 } end
@@ -231,9 +148,6 @@ local function compile_spec(spec)
end
out.blockStatus = (type(spec.block) == "table" and tonumber(spec.block.status)) or 403
- -- Response entries can never become empty policies, including malformed
- -- entries left by an interrupted upgrade or an invalid management payload.
- out.isResponse = spec.response ~= nil
return out
end
@@ -263,58 +177,4 @@ function M.get(host, raw)
return parsed
end
--- Only the 32-byte revision is read from shared memory on a warm request.
--- Bodies are fetched/decoded once per configuration change per worker. Keep a
--- separate cache so response bodies cannot displace compiled access policies.
-local responses_cache = lrucache.new(128)
-local response_cache_bytes = 0
-local response_cache_budget = 8 * 1024 * 1024
-local function response_index(host, revision, dict)
- local hit = responses_cache:get(host)
- if hit and hit.revision == revision then return hit end
- local raw = dict:get("responses:" .. host)
- -- A concurrent management write may have changed the body after we read
- -- its revision. Never cache that body under a different revision.
- if not raw or M.response_revision(raw) ~= revision then return nil end
- local entries = cjson.decode(raw)
- local index = { revision=revision, exact={}, prefixes={}, bytes=#raw }
- if type(entries) == "table" and #entries <= M.max_responses then
- for _, e in ipairs(entries) do
- local r = compile_response(e)
- if r then
- if r.match == "exact" then index.exact[r.path] = r
- else index.prefixes[#index.prefixes + 1] = r end
- end
- end
- table.sort(index.prefixes, function(a, b) return #a.path > #b.path end)
- end
- -- Conservatively count even evicted entries until the next flush. This
- -- bounds retained response payloads without running an eviction scan.
- response_cache_bytes = response_cache_bytes - (hit and hit.bytes or 0) + #raw
- if response_cache_bytes > response_cache_budget then
- responses_cache:flush_all()
- response_cache_bytes = #raw
- end
- responses_cache:set(host, index)
- return index
-end
-
-local function accepts_method(r, method)
- return not r.methods or r.methods[method] or method == "HEAD" and r.methods.GET
-end
-
-function M.response_for(host, revision, dict, uri, method)
- if not M.response_methods[method] or reserved_path(uri) then return nil end
- local index = response_index(host, revision, dict)
- if not index then return nil end
- local exact = index.exact[uri]
- if exact and accepts_method(exact, method) then return exact end
- for _, r in ipairs(index.prefixes) do
- local path = r.path
- local boundary = r.boundary
- if (path == "/" or uri == path or string.sub(uri, 1, #boundary) == boundary)
- and accepts_method(r, method) then return r end
- end
-end
-
return M
diff --git a/packages/adapters/src/infra/nginx-dns-hooks.test.ts b/packages/adapters/src/infra/nginx-dns-hooks.test.ts
index 527e37a75..744b4be8c 100644
--- a/packages/adapters/src/infra/nginx-dns-hooks.test.ts
+++ b/packages/adapters/src/infra/nginx-dns-hooks.test.ts
@@ -5,7 +5,7 @@ import { basename, dirname, join } from "node:path";
import { promisify } from "node:util";
import { expect, test } from "vitest";
import { LocalExecutor } from "../system/local-executor";
-import { rootChecked } from "../system/privilege";
+import type { RootChecked } from "../system/privilege";
import { NginxProvider } from "./nginx";
import { OPENRESTY_DEFAULT_PATHS } from "./openresty-lua";
@@ -86,7 +86,7 @@ test.each([
const nginx = new NginxProvider({
paths: { ...OPENRESTY_DEFAULT_PATHS, sitesDir: join(scratch, "sites-enabled") },
certDir: join(root, "live"),
- executor: rootChecked(executor, "Test executor intercepts privileged commands"),
+ executor: executor as RootChecked,
});
try {
await expect(
diff --git a/packages/adapters/src/oblien-contract.test.ts b/packages/adapters/src/oblien-contract.test.ts
deleted file mode 100644
index 66507f17b..000000000
--- a/packages/adapters/src/oblien-contract.test.ts
+++ /dev/null
@@ -1,169 +0,0 @@
-import { createServer } from "node:http";
-import { once } from "node:events";
-import { afterEach, expect, it, vi } from "vitest";
-import { DEFAULT_API_BASE_URL, Oblien as OfficialOblien } from "oblien";
-import { Oblien, cloudWorkspaceCreationFailure } from "./oblien";
-import {
- cloudBillingContract,
- oblienApiBaseUrl,
- oblienApiUrl,
- toOblienVmOffer,
-} from "./oblien-contract";
-
-afterEach(() => vi.unstubAllGlobals());
-
-it("inherits the published SDK default for the adapter and official client", async () => {
- const urls: string[] = [];
- vi.stubGlobal(
- "fetch",
- vi.fn(async (input: string | URL) => {
- urls.push(String(input));
- return Response.json({ success: true, vms: [], namespaces: [] });
- }),
- );
- await new Oblien({ token: "fixture" }).vms.list();
- await new OfficialOblien({ token: "fixture" }).vms.list();
- expect(DEFAULT_API_BASE_URL).toBe("https://api.oblien.com/v1");
- expect(oblienApiBaseUrl().href).toBe(DEFAULT_API_BASE_URL);
- expect(urls).toEqual([`${DEFAULT_API_BASE_URL}/vms`, `${DEFAULT_API_BASE_URL}/vms`]);
-});
-
-it("keeps version and proxy mounts in real SDK JSON, Page, route and SSE requests without replaying a failed create", async () => {
- const calls: Array<{ path: string; body: Record }> = [];
- const server = createServer(async (req, res) => {
- let raw = "";
- for await (const chunk of req) raw += chunk;
- calls.push({ path: req.url!, body: raw ? JSON.parse(raw) : {} });
- if (req.headers.authorization !== "Bearer fixture") {
- res.writeHead(401).end();
- return;
- }
- if (req.url === "/proxy/v1/vms/vm-a/stats/stream") {
- res.writeHead(200, { "Content-Type": "text/event-stream" });
- res.end('data: {"cpu":12}\n\n');
- return;
- }
- res.setHeader("Content-Type", "application/json");
- if (req.url === "/proxy/v1/vms" && req.method === "POST") {
- res.writeHead(422).end(
- JSON.stringify({
- success: false,
- code: "CREATE_FAILED",
- details: { vm_id: "vm-failed" },
- }),
- );
- return;
- }
- if (req.url === "/proxy/v1/vms") {
- res.end(
- JSON.stringify({ success: true, vms: [{ id: "vm-a", namespace: "tenant-a" }], total: 1 }),
- );
- return;
- }
- if (req.url === "/proxy/v1/vms/vm-a") {
- res.end(JSON.stringify({ success: true, vm: { id: "vm-a", namespace: "tenant-a" } }));
- return;
- }
- if (req.url === "/proxy/v1/vms/vm-a/workloads/process-a") {
- res.end(JSON.stringify({ success: true, workload: { id: "process-a", status: "running" } }));
- return;
- }
- if (req.url === "/proxy/v1/pages") {
- res.end(JSON.stringify({ success: true, page: { slug: "site", source_vm_id: "vm-a" } }));
- return;
- }
- if (req.url === "/proxy/v1/domain/routes/site.example") {
- res.end(JSON.stringify({ success: true }));
- return;
- }
- res.writeHead(404).end(JSON.stringify({ success: false }));
- });
- server.listen(0, "127.0.0.1");
- await once(server, "listening");
- const address = server.address();
- if (!address || typeof address === "string") throw new Error("No test listener");
- try {
- const client = new Oblien({
- token: "fixture",
- baseUrl: `http://127.0.0.1:${address.port}/proxy/v1`,
- });
- expect((await client.vms.list()).vms[0]?.id).toBe("vm-a");
- expect((await client.vm("vm-a").get()).namespace).toBe("tenant-a");
- expect(await client.vm("vm-a").workloads.get("process-a")).toMatchObject({
- id: "process-a",
- status: "running",
- });
- await client.pages.create({ vm_id: "vm-a", name: "Site", slug: "site", path: "/dist" });
- await client.routes.set("site.example", {
- routes: [{ match: { path: "/" }, action: { kind: "proxy", vm: "vm-a", port: 3000 } }],
- });
- for await (const sample of client.streamWorkspaceMetrics("vm-a")) {
- expect(sample).toEqual({ cpu: 12 });
- break;
- }
- const failure = await client.vms.create({ wait_ready: false }).catch((error) => error);
- expect(cloudWorkspaceCreationFailure(failure)).toMatchObject({ workspaceId: "vm-failed" });
- expect(
- calls.filter((call) => call.path === "/proxy/v1/vms" && call.body.wait_ready === false),
- ).toHaveLength(1);
- expect(calls.every((call) => call.path.startsWith("/proxy/v1/"))).toBe(true);
- expect(calls.find((call) => call.path.endsWith("/pages"))?.body).toMatchObject({
- vm_id: "vm-a",
- });
- expect(JSON.stringify(calls)).not.toContain("workspace_id");
- } finally {
- server.closeAllConnections();
- await new Promise((resolve, reject) =>
- server.close((error) => (error ? reject(error) : resolve())),
- );
- }
-});
-
-it.each([undefined, null, [], { status: "running" }])(
- "rejects an invalid native workload record: %j",
- async (workload) => {
- vi.stubGlobal(
- "fetch",
- vi.fn(async () => Response.json({ success: true, workload })),
- );
- await expect(
- new Oblien({ token: "fixture" }).vm("vm-a").workloads.get("process-a"),
- ).rejects.toMatchObject({ code: "OBLIEN_WORKLOAD_INVALID" });
- },
-);
-
-it("preserves paid limits, zero and unlimited counts while leaving customer metadata opaque", () => {
- const metadata = {
- workspace: "customer-chosen",
- max_workspaces: "opaque",
- capacity: { vcpus: 8, memoryMb: 16, diskGb: 32, workspaces: 42 },
- };
- const saved = {
- unitAmount: 12000,
- resourceLimits: { max_workspaces: null, max_vcpus: 8 },
- capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, workspaces: 0 },
- policy: { overdraft: 0, onOverdraftAction: "stop_workspaces" as const },
- metadata,
- };
- const native = toOblienVmOffer(saved);
- expect(native).toEqual({
- unitAmount: 12000,
- resourceLimits: { max_vms: null, max_vcpus: 8 },
- capacity: { vcpus: 4, memoryMb: 16384, diskGb: 128, vms: 0 },
- policy: { overdraft: 0, onOverdraftAction: "stop_vms" },
- metadata,
- });
- expect(cloudBillingContract({ success: true, subscription: { offer: native } })).toEqual({
- success: true,
- subscription: { offer: saved },
- });
- expect(native.metadata).toBe(metadata);
- expect(saved.capacity.workspaces).toBe(0);
-});
-
-it("rejects request paths that escape a versioned mount", () => {
- const base = oblienApiBaseUrl("https://provider.example/proxy/v2");
- for (const path of ["../vms", "/../vms", "https://other.example/vms", "//other.example/vms"])
- expect(() => oblienApiUrl(base, path)).toThrow();
- expect(oblienApiUrl(base, "/vms").href).toBe("https://provider.example/proxy/v2/vms");
-});
diff --git a/packages/adapters/src/oblien-contract.ts b/packages/adapters/src/oblien-contract.ts
deleted file mode 100644
index 0b0a5367d..000000000
--- a/packages/adapters/src/oblien-contract.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import { DEFAULT_API_BASE_URL } from "oblien";
-
-/** The SDK owns the default. An operator override is a complete API mount. */
-export function oblienApiBaseUrl(input = DEFAULT_API_BASE_URL): URL {
- const base = new URL(input);
- if (
- base.username ||
- base.password ||
- base.search ||
- base.hash ||
- (base.protocol !== "https:" &&
- !(base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname)))
- ) {
- throw new Error("Oblien API URL must use HTTPS (HTTP is allowed for localhost tests)");
- }
- base.pathname = base.pathname.replace(/\/+$/, "");
- return base;
-}
-
-export function oblienApiUrl(base: URL, path: string): URL {
- if (/^(?:[a-z][a-z\d+.-]*:|\/\/)/i.test(path))
- throw new Error("Oblien request escaped its API origin");
- const root = base.toString().replace(/\/+$/, "") + "/";
- const url = new URL(path.replace(/^\//, ""), root);
- if (url.origin !== base.origin || !url.pathname.startsWith(new URL(root).pathname))
- throw new Error("Oblien request escaped its API mount");
- return url;
-}
-
-/** OpenShip's saved Cloud workspace policies are its own persisted contract.
- * Map that count to provider VMs only at the external boundary. */
-export function toOblienVmLimits(limits: T) {
- const { max_workspaces, ...rest } = limits;
- return { ...rest, max_vms: max_workspaces };
-}
-
-export function toOblienVmCapacity(capacity: T) {
- const { workspaces, ...rest } = capacity;
- return { ...rest, vms: workspaces };
-}
-
-export function toOblienVmPolicy(
- policy: T,
-) {
- const { onOverdraftAction, ...rest } = policy;
- return {
- ...rest,
- onOverdraftAction:
- onOverdraftAction === "stop_workspaces" ? ("stop_vms" as const) : onOverdraftAction,
- };
-}
-
-export function toOblienVmOffer<
- T extends {
- resourceLimits?: { max_workspaces?: number | null };
- capacity?: { vcpus: number; memoryMb: number; diskGb: number; workspaces: number };
- policy?: { onOverdraftAction?: "stop_workspaces" | "block" };
- },
->(offer: T) {
- const { resourceLimits, capacity, policy, ...rest } = offer;
- return {
- ...rest,
- ...(resourceLimits ? { resourceLimits: toOblienVmLimits(resourceLimits) } : {}),
- ...(capacity ? { capacity: toOblienVmCapacity(capacity) } : {}),
- ...(policy ? { policy: toOblienVmPolicy(policy) } : {}),
- };
-}
-
-/** Decode only documented billing-contract nodes. Metadata, signatures and
- * customer dictionaries stay opaque; no recursive word replacement is used. */
-export function cloudBillingContract(value: unknown, depth = 0): unknown {
- if (!value || typeof value !== "object" || Array.isArray(value)) return value;
- if (depth > 12) throw new Error("Oblien returned an invalid billing contract");
- const source = value as Record;
- const result = { ...source };
- if ("vcpus" in source && "memoryMb" in source && "diskGb" in source) {
- result.workspaces = source.vms;
- delete result.vms;
- }
- if (
- source.resourceLimits &&
- typeof source.resourceLimits === "object" &&
- !Array.isArray(source.resourceLimits)
- ) {
- const { max_vms, ...rest } = source.resourceLimits as Record;
- result.resourceLimits = { ...rest, max_workspaces: max_vms };
- }
- if (source.onOverdraftAction === "stop_vms") result.onOverdraftAction = "stop_workspaces";
- for (const key of [
- "data",
- "capacity",
- "quote",
- "current",
- "next",
- "subscription",
- "offer",
- "policy",
- "pendingChange",
- "change",
- "pendingCheckout",
- "checkout",
- ])
- if (source[key] && typeof source[key] === "object")
- result[key] = cloudBillingContract(source[key], depth + 1);
- if (Array.isArray(source.presets))
- result.presets = source.presets.map((item) => cloudBillingContract(item, depth + 1));
- return result;
-}
diff --git a/packages/adapters/src/oblien-metrics.test.ts b/packages/adapters/src/oblien-metrics.test.ts
index 67d449c5b..4068260b6 100644
--- a/packages/adapters/src/oblien-metrics.test.ts
+++ b/packages/adapters/src/oblien-metrics.test.ts
@@ -32,7 +32,7 @@ it("keeps provider credentials server-side, rejects redirects and releases the r
}
expect(cancel).toHaveBeenCalledOnce();
const [url, request] = fetcher.mock.calls[0]! as unknown as [URL, RequestInit];
- expect(url.href).toBe("https://api.oblien.com/v1/vms/ws-owned/stats/stream");
+ expect(url.href).toBe("https://api.oblien.com/workspace/ws-owned/stats/stream");
expect(request.redirect).toBe("error");
expect(new Headers(request.headers).get("Authorization")).toBe("Bearer scoped-token");
expect(request.signal?.aborted).toBe(true);
diff --git a/packages/adapters/src/oblien.test.ts b/packages/adapters/src/oblien.test.ts
index b3748bca9..52b806a6e 100644
--- a/packages/adapters/src/oblien.test.ts
+++ b/packages/adapters/src/oblien.test.ts
@@ -7,7 +7,7 @@ describe("Oblien SDK transport", () => {
status: 429, headers: { "Retry-After": retryAfter },
}));
vi.stubGlobal("fetch", fetcher);
- const error = await new Oblien({ token: "test" }).vms.create({ wait_ready: false }).catch(error => error);
+ const error = await new Oblien({ token: "test" }).workspaces.create({ wait_ready: false }).catch(error => error);
expect(error).toMatchObject({ status: 429, code: "OBLIEN_RATE_LIMITED" });
expect(error.details.retryAfterSeconds).toBeGreaterThan(0);
expect(error.details.retryAfterSeconds).toBeLessThanOrEqual(30);
@@ -17,7 +17,7 @@ describe("Oblien SDK transport", () => {
});
it.each(["invalid", "-1", "99999999999999999999999"])("ignores invalid Retry-After %s", async (retryAfter) => {
vi.stubGlobal("fetch", vi.fn(async () => new Response("", { status: 503, headers: { "Retry-After": retryAfter } })));
- const error = await new Oblien({ token: "test" }).vms.get("ws").catch(error => error);
+ const error = await new Oblien({ token: "test" }).workspaces.get("ws").catch(error => error);
expect(error.status).toBe(503);
expect(error.details).toBeUndefined();
});
@@ -30,7 +30,7 @@ describe("Oblien SDK transport", () => {
vi.stubGlobal("fetch", fetcher);
const choices = await new Oblien({ token: "fixture-token" }).listOutboundIps();
expect(choices).toEqual([{ ip: "8.8.4.4", countryCode: "US" }, { ip: "1.1.1.1", countryCode: null }]);
- expect(String(fetcher.mock.calls[0]?.[0])).toBe("https://api.oblien.com/v1/zone/mine");
+ expect(String(fetcher.mock.calls[0]?.[0])).toBe("https://api.oblien.com/zone/mine");
expect(JSON.stringify(choices)).not.toMatch(/pool-user|pool-password|private-id/);
});
it("rejects an unreadable pool instead of presenting a successful empty picker", async () => {
@@ -40,13 +40,13 @@ describe("Oblien SDK transport", () => {
it("propagates an HTTP quota refusal even without success:false", async () => {
vi.stubGlobal("fetch", vi.fn(async () => Response.json({ error: "NAMESPACE_LIMIT_REACHED" }, { status: 409 })));
const client = new Oblien({ token: "scoped-test-token" });
- const error = await client.vms.create({ namespace: "tenant-a", wait_ready: false }).catch(error => error);
+ const error = await client.workspaces.create({ namespace: "tenant-a", wait_ready: false }).catch(error => error);
expect(error).toMatchObject({ status: 409, code: "NAMESPACE_LIMIT_REACHED" });
expect(cloudWorkspaceCreationFailure(error)).toMatchObject({ capacityRejected: true, rejected: true });
});
it("rejects an error HTTP status even when a payload claims success", async () => {
- vi.stubGlobal("fetch", vi.fn(async () => Response.json({ success: true, vm: { id: "not-created" } }, { status: 503 })));
- await expect(new Oblien({ token: "test" }).vms.create({ wait_ready: false })).rejects.toMatchObject({ status: 503 });
+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({ success: true, workspace: { id: "not-created" } }, { status: 503 })));
+ await expect(new Oblien({ token: "test" }).workspaces.create({ wait_ready: false })).rejects.toMatchObject({ status: 503 });
});
it.each(["NAMESPACE_LIMIT_REACHED", "SANDBOX_LIMIT_REACHED", "POOL_LIMIT_REACHED"])(
"normalizes the provider's HTTP 200 %s refusal",
@@ -56,31 +56,31 @@ describe("Oblien SDK transport", () => {
vi.fn(async () => Response.json({ valid: false, error: "capacity exceeded", code })),
);
await expect(
- new Oblien({ token: "test" }).vms.create({ wait_ready: false }),
+ new Oblien({ token: "test" }).workspaces.create({ wait_ready: false }),
).rejects.toMatchObject({ status: 409, code });
},
);
it("keeps official request formatting and never follows authenticated redirects", async () => {
- const fetcher = vi.fn(async () => Response.json({ success: true, vm: { id: "ws-a", namespace: "tenant-a" } }));
+ const fetcher = vi.fn(async () => Response.json({ success: true, workspace: { id: "ws-a", namespace: "tenant-a" } }));
vi.stubGlobal("fetch", fetcher);
const client = new Oblien({ clientId: "test-owner", clientSecret: "test-secret" });
- await client.vms.create({ namespace: "tenant-a", cpus: 2, wait_ready: false });
+ await client.workspaces.create({ namespace: "tenant-a", cpus: 2, wait_ready: false });
const [url, init] = fetcher.mock.calls[0]! as unknown as [URL, RequestInit];
- expect(url.pathname).toBe("/v1/vms"); expect(init.redirect).toBe("error"); expect(init.signal).toBeInstanceOf(AbortSignal);
+ expect(url.pathname).toBe("/workspace"); expect(init.redirect).toBe("error"); expect(init.signal).toBeInstanceOf(AbortSignal);
expect(JSON.parse(init.body as string)).toMatchObject({ namespace: "tenant-a", config: { cpus: 2 } });
});
it("tracks token refresh and authentication restore without mixing scopes", async () => {
const headers: Headers[] = [];
- vi.stubGlobal("fetch", vi.fn(async (_url, init) => { headers.push(new Headers(init.headers)); return Response.json({ success: true, vms: [] }); }));
+ vi.stubGlobal("fetch", vi.fn(async (_url, init) => { headers.push(new Headers(init.headers)); return Response.json({ success: true, workspaces: [] }); }));
const client = new Oblien({ clientId: "test-owner", clientSecret: "test-secret" });
- await client.vms.list(); client.setToken("namespace-token"); await client.vms.list(); client._http.restoreAuth(); await client.vms.list();
+ await client.workspaces.list(); client.setToken("namespace-token"); await client.workspaces.list(); client._http.restoreAuth(); await client.workspaces.list();
expect(headers[0]!.get("X-Client-ID")).toBe("test-owner");
expect(headers[1]!.get("Authorization")).toBe("Bearer namespace-token"); expect(headers[1]!.has("X-Client-Secret")).toBe(false);
expect(headers[2]!.get("X-Client-ID")).toBe("test-owner"); expect(headers[2]!.has("Authorization")).toBe(false);
});
it("does not expose provider error details or tokens", async () => {
vi.stubGlobal("fetch", vi.fn(async () => Response.json({ error: "scope_denied", message: "private-secret", details: { token: "private-secret" } }, { status: 403 })));
- const error = await new Oblien({ token: "test" }).vms.get("ws-b").catch(error => error);
+ const error = await new Oblien({ token: "test" }).workspaces.get("ws-b").catch(error => error);
expect(error.message).not.toContain("private-secret"); expect(error.details).toBeUndefined(); expect(error.status).toBe(403);
expect(cloudWorkspaceCreationFailure(error)).toMatchObject({ capacityRejected: false, rejected: true });
});
@@ -108,7 +108,7 @@ describe("Oblien SDK transport", () => {
),
),
);
- const error = await new Oblien({ token: "test" }).vms
+ const error = await new Oblien({ token: "test" }).workspaces
.create({ wait_ready: false })
.catch((error) => error);
expect(error).toMatchObject({
@@ -159,7 +159,7 @@ describe("Oblien SDK transport", () => {
),
),
);
- const error = await new Oblien({ token: "test" }).vms
+ const error = await new Oblien({ token: "test" }).workspaces
.create({ wait_ready: false })
.catch((error) => error);
expect(error.details.violations).toEqual([
@@ -212,7 +212,7 @@ describe("Oblien SDK transport", () => {
),
),
);
- const error = await new Oblien({ token: "test" }).vms
+ const error = await new Oblien({ token: "test" }).workspaces
.create({ wait_ready: false })
.catch((error) => error);
expect(error.details).toBeUndefined();
@@ -228,7 +228,7 @@ describe("Oblien SDK transport", () => {
code: "CREATE_FAILED",
message: "private-account-data",
details: {
- vm_id: "ws-failed",
+ workspace_id: "ws-failed",
token: "private-secret",
workspace: { env: { SECRET: "private-secret" } },
},
@@ -237,13 +237,13 @@ describe("Oblien SDK transport", () => {
),
),
);
- const error = await new Oblien({ token: "test" }).vms
+ const error = await new Oblien({ token: "test" }).workspaces
.create({ wait_ready: false })
.catch((error) => error);
expect(error).toMatchObject({
status: 422,
code: "CREATE_FAILED",
- details: { vm_id: "ws-failed" },
+ details: { workspace_id: "ws-failed" },
});
expect(cloudWorkspaceCreationFailure(error)).toEqual({ workspaceId: "ws-failed", capacityRejected: false, rejected: false });
expect(JSON.stringify(error)).not.toContain("private-");
@@ -257,7 +257,7 @@ describe("Oblien SDK transport", () => {
vi.stubGlobal("fetch", vi.fn(async () => Response.json({
error: code, message: "private-account-data", details: { violations: ["private-namespace-name"] },
}, { status: 400 })));
- const error = await new Oblien({ token: "scoped-test-token" }).vms.get("ws-a").catch(error => error);
+ const error = await new Oblien({ token: "scoped-test-token" }).workspaces.get("ws-a").catch(error => error);
expect(error).toMatchObject({ status: 400, code });
expect(error.message).toContain(description);
expect(error.message).not.toContain("private-");
@@ -272,7 +272,7 @@ describe("Oblien SDK transport", () => {
const fetcher = vi.fn(); vi.stubGlobal("fetch", fetcher);
const controller = new AbortController();
const reason = new Error("Deployment cancelled"); controller.abort(reason);
- await expect(new Oblien({ token: "test" }).vms.create({ wait_ready: false }, { signal: controller.signal })).rejects.toBe(reason);
+ await expect(new Oblien({ token: "test" }).workspaces.create({ wait_ready: false }, { signal: controller.signal })).rejects.toBe(reason);
expect(fetcher).not.toHaveBeenCalled();
});
it("preserves SDK cancellation during a request instead of returning a retryable provider error", async () => {
@@ -283,7 +283,7 @@ describe("Oblien SDK transport", () => {
})));
const controller = new AbortController();
const reason = new Error("Deployment cancelled");
- const pending = new Oblien({ token: "test" }).vms.create({ wait_ready: false }, { signal: controller.signal });
+ const pending = new Oblien({ token: "test" }).workspaces.create({ wait_ready: false }, { signal: controller.signal });
const result = expect(pending).rejects.toBe(reason);
controller.abort(reason);
await result;
diff --git a/packages/adapters/src/oblien.ts b/packages/adapters/src/oblien.ts
index aabc70696..530ad51ad 100644
--- a/packages/adapters/src/oblien.ts
+++ b/packages/adapters/src/oblien.ts
@@ -1,5 +1,4 @@
import { workspaceMetricsStream } from "./oblien-metrics";
-import { oblienApiBaseUrl, oblienApiUrl } from "./oblien-contract";
import { diagnosticTraceparent, reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
import { withDiagnosticSpan } from "@repo/core/diagnostics/node";
import {
@@ -37,13 +36,13 @@ const resourceUnits = {
cpus: "vCPU",
memory_mb: "MB",
disk_size_mb: "MB",
- vms: "VMs",
+ workspaces: "workspaces",
} as const;
const resourceLabels = {
cpus: "CPU",
memory_mb: "RAM",
disk_size_mb: "Disk",
- vms: "VMs",
+ workspaces: "Workspaces",
} as const;
type CapacityViolation = {
resource: keyof typeof resourceUnits;
@@ -92,7 +91,7 @@ function namespaceCapacityDetails(raw: unknown) {
}
function workspaceIdFromDetails(details: unknown): string | undefined {
- const id = (details as { vm_id?: unknown } | null)?.vm_id;
+ const id = (details as { workspace_id?: unknown } | null)?.workspace_id;
return typeof id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(id) ? id : undefined;
}
@@ -141,7 +140,7 @@ function providerError(status: number, body: unknown, retryAfter: string | null
const retryAfterSeconds = Number.isSafeInteger(delay) && delay >= 0 && delay <= 86400 ? delay : undefined;
const details = capacity || workspaceId || retryAfterSeconds !== undefined ? {
...capacity,
- ...(workspaceId ? { vm_id: workspaceId } : {}),
+ ...(workspaceId ? { workspace_id: workspaceId } : {}),
...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),
} : undefined;
const requestId =
@@ -154,7 +153,7 @@ function providerError(status: number, body: unknown, retryAfter: string | null
const scope =
value.enforcementScope === "namespace_allocated_pool"
? "namespace total"
- : value.resource === "vms"
+ : value.resource === "workspaces"
? "namespace workspace count"
: "per workspace";
return (
@@ -220,7 +219,11 @@ export class Oblien extends OblienSdk {
invalidate?(rejectedToken: string): Promise;
};
}) {
- const base = oblienApiBaseUrl(options.baseUrl);
+ const base = new URL(options.baseUrl ?? "https://api.oblien.com");
+ if (base.username || base.password || base.search || base.hash ||
+ (base.protocol !== "https:" && !(base.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(base.hostname)))) {
+ throw new Error("Oblien API URL must use HTTPS (HTTP is allowed for localhost tests)");
+ }
super(options);
const original = new Headers();
if ("token" in options) { if (options.token) original.set("Authorization", `Bearer ${options.token}`); }
@@ -259,7 +262,7 @@ export class Oblien extends OblienSdk {
const renewal = ensureAuth();
if (renewal) await renewal;
subscriptionSignal.throwIfAborted();
- const url = oblienApiUrl(base, `/vms/${encodeURIComponent(workspaceId)}/stats/stream`);
+ const url = new URL(`/workspace/${encodeURIComponent(workspaceId)}/stats/stream`, base);
const headers = new Headers(auth);
headers.set("Accept", "text/event-stream");
const response = await fetch(url, { headers, redirect: "error", signal: subscriptionSignal });
@@ -268,7 +271,7 @@ export class Oblien extends OblienSdk {
}, signal);
this._http.request = async (request: RequestOptions): Promise => withDiagnosticSpan({ kind: "operation", component: "oblien", operation: "oblien.request", method: request.method }, async () => {
request.signal?.throwIfAborted();
- const url = oblienApiUrl(base, request.path);
+ const url = new URL(request.path, base);
if (url.origin !== base.origin || url.username || url.password) throw new Error("Oblien request escaped its API origin");
const renewal = ensureAuth();
if (renewal) await renewal;
@@ -281,7 +284,7 @@ export class Oblien extends OblienSdk {
headers.set("Accept", "application/json");
headers.set("Content-Type", "application/json");
for (const [key, value] of auth) headers.set(key, value);
- const waitingCreate = request.method === "POST" && /^\/vms\/?$/.test(request.path) &&
+ const waitingCreate = request.method === "POST" && /^\/workspace\/?$/.test(url.pathname) &&
(request.body as { wait_ready?: boolean } | undefined)?.wait_ready !== false;
let response: Response;
let body: unknown;
@@ -320,15 +323,18 @@ export class Oblien extends OblienSdk {
}
return body as T;
}, { kind: "client" });
- // Validate the native record before process control and resize recovery.
- const getWorkload = this.vms.workloads.get.bind(this.vms.workloads);
- this.vms.workloads.get = async (workspaceId, workloadId) => {
- const workload = await getWorkload(workspaceId, workloadId);
+ // SDK 2.5 types get() as WorkloadInfo but leaves the HTTP envelope intact,
+ // unlike create() and list(). Normalize at the provider boundary so process
+ // control and server-resize recovery read the same saved workload record.
+ const getWorkload = this.workspaces.workloads.get.bind(this.workspaces.workloads);
+ this.workspaces.workloads.get = async (workspaceId, workloadId) => {
+ const response = await getWorkload(workspaceId, workloadId);
+ const workload = response.workload ?? response;
if (!workload || typeof workload !== "object" || Array.isArray(workload) ||
!("id" in workload) || typeof workload.id !== "string") {
throw new OblienError("Oblien returned an invalid application process record", 502, "OBLIEN_WORKLOAD_INVALID");
}
- return workload;
+ return workload as typeof response;
};
}
}
diff --git a/packages/adapters/src/runtime/cloud-deploy-static.test.ts b/packages/adapters/src/runtime/cloud-deploy-static.test.ts
index c06209b7a..155b826e3 100644
--- a/packages/adapters/src/runtime/cloud-deploy-static.test.ts
+++ b/packages/adapters/src/runtime/cloud-deploy-static.test.ts
@@ -6,7 +6,7 @@ beforeEach(() => { h = managedRoutingFixture(); });
describe("shared static releases on managed ingress", () => {
it.each([".", "dist"])("normalizes %s under its owned release and exports only the project route tree", async output => {
await h.infra.registerRoute({ domain: "site.opsh.io", staticRoot: `${h.scope.staticReleaseRoot}/release-a/${output}`, tls: true });
- expect(h.pages.create).toHaveBeenCalledWith(expect.objectContaining({ vm_id: h.workspaceId, path: `${h.paths.routes}/site` }));
+ expect(h.pages.create).toHaveBeenCalledWith(expect.objectContaining({ workspace_id: h.workspaceId, path: `${h.paths.routes}/site` }));
expect(h.scope.resolveUrl).not.toHaveBeenCalled();
expect(h.routes.set).toHaveBeenCalledOnce();
});
@@ -33,7 +33,7 @@ describe("shared static releases on managed ingress", () => {
h.routes.set.mockRejectedValueOnce(new Error("route table unavailable"));
await expect(h.infra.registerRoute({ domain: "site.opsh.io", staticRoot: `${h.scope.staticReleaseRoot}/release-b`, tls: true })).rejects.toThrow("route table unavailable");
expect(h.pages.deploy).toHaveBeenCalledTimes(2);
- expect(h.pages.deploy).toHaveBeenLastCalledWith("site", { vm_id: h.workspaceId, path: `${h.paths.routes}/site` });
+ expect(h.pages.deploy).toHaveBeenLastCalledWith("site", { workspace_id: h.workspaceId, path: `${h.paths.routes}/site` });
});
});
@@ -48,7 +48,7 @@ it("switches a live proxy hostname to exported files and back without claiming a
});
expect(h.records.get("site")).toBe(page);
expect(h.pages.deploy).toHaveBeenCalledWith("site", {
- vm_id: h.workspaceId,
+ workspace_id: h.workspaceId,
path: `${h.paths.routes}/site`,
});
expect(JSON.stringify(h.routes.set.mock.lastCall)).toContain('"static"');
diff --git a/packages/adapters/src/runtime/cloud-host-build-refusal.test.ts b/packages/adapters/src/runtime/cloud-host-build-refusal.test.ts
index bca0b073f..ae6213923 100644
--- a/packages/adapters/src/runtime/cloud-host-build-refusal.test.ts
+++ b/packages/adapters/src/runtime/cloud-host-build-refusal.test.ts
@@ -16,7 +16,7 @@ const config = { target: "cloud" as const, cloudToken: "namespace-token", cloudN
beforeEach(() => {
const row = { id: "vm-a", namespace: "namespace-a", status: "running" };
- fixture.client = { vm: vi.fn(() => ({ get: vi.fn(async () => row), workloads: { list: vi.fn(async () => []) } })), vms: { get: vi.fn(async () => row), create: vi.fn(), delete: vi.fn() } };
+ fixture.client = { workspace: vi.fn(() => ({ get: vi.fn(async () => row), workloads: { list: vi.fn(async () => []) } })), workspaces: { get: vi.fn(async () => row), create: vi.fn(), delete: vi.fn() } };
});
afterEach(async () => {
for (const platform of platforms.splice(0)) await platform.runtime.dispose?.();
@@ -35,13 +35,13 @@ describe("Cloud changes the execution destination, not the deployment runtime",
expect(platform.executor).toBeInstanceOf(CloudWorkspaceExecutor);
expect(platform.localHost).toBe(false);
expect(platform.system).toBeNull();
- expect(fixture.client.vms.create).not.toHaveBeenCalled();
+ expect(fixture.client.workspaces.create).not.toHaveBeenCalled();
});
it("has no implicit host when a Cloud destination is absent", async () => {
const platform = await make({ cloudServer: undefined });
await expect(platform.runtime.build({ projectId: "project-a", buildStrategy: "local" } as never)).rejects.toMatchObject({ code: "DEPLOYMENT_SERVER_REQUIRED" });
expect(platform.executor).toBeNull();
- expect(fixture.client.vm).not.toHaveBeenCalled();
+ expect(fixture.client.workspace).not.toHaveBeenCalled();
});
it.each(["docker", "bare"] as const)("requires namespace-scoped credentials for %s", async runtime => {
await expect(make({ runtime, cloudToken: undefined })).rejects.toThrow("organization-scoped credentials");
@@ -52,14 +52,14 @@ describe("Cloud changes the execution destination, not the deployment runtime",
const transfer = vi.spyOn(platform.executor!, "transferIn");
await expect(platform.runtime.build({ projectId: "project-a", localPath: "/etc", buildStrategy: "local" } as never)).rejects.toThrow(/control-plane|host/i);
expect(transfer).not.toHaveBeenCalled();
- expect(fixture.client.vms.create).not.toHaveBeenCalled();
+ expect(fixture.client.workspaces.create).not.toHaveBeenCalled();
});
it("resolves bare process ports without opening Docker and rejects sibling ports", async () => {
const workloads = [
{ id: "openship-release-a", labels: { "openship.project": "project-a", "openship.deployment": "release-a", "openship.ports": "[3000]" } },
{ id: "openship-release-b", labels: { "openship.project": "project-b", "openship.deployment": "release-b", "openship.ports": "[4000]" } },
];
- fixture.client.vm.mockReturnValue({ workloads: { list: async () => workloads } });
+ fixture.client.workspace.mockReturnValue({ workloads: { list: async () => workloads } });
const connection = new CloudServerConnection(fixture.client, { workspaceId: server.workspaceId, namespace: config.cloudNamespace });
const containers = vi.fn(async () => ({ resolveUrl: async () => { throw new Error("unowned port"); }, resolveTarget: vi.fn() }));
const scope = managedProjectRoutingScope(connection, server, containers);
diff --git a/packages/adapters/src/runtime/cloud/docker.test.ts b/packages/adapters/src/runtime/cloud/docker.test.ts
index 9be7fe688..ad9e34fb9 100644
--- a/packages/adapters/src/runtime/cloud/docker.test.ts
+++ b/packages/adapters/src/runtime/cloud/docker.test.ts
@@ -54,13 +54,13 @@ beforeEach(async () => {
if (!page) throw new NotFoundError("missing");
return { page };
}),
- create: vi.fn(async (input: { slug: string; vm_id: string; path: string }) => {
- const page = { slug: input.slug, domain: "opsh.io", url: `https://${input.slug}.opsh.io`, namespace: "namespace-a", source_vm_id: input.vm_id, exported_path: input.path };
+ create: vi.fn(async (input: { slug: string; workspace_id: string; path: string }) => {
+ const page = { slug: input.slug, domain: "opsh.io", url: `https://${input.slug}.opsh.io`, namespace: "namespace-a", source_workspace_id: input.workspace_id, exported_path: input.path };
pageRows.set(input.slug, page); return { page };
}),
enable: vi.fn(async () => ({ success: true })), connectDomain: vi.fn(), delete: vi.fn(async () => ({ success: true })),
};
- provider = { vm: vi.fn(() => ws), vms: { get: ws.get, create: vi.fn(), delete: vi.fn() }, pages };
+ provider = { workspace: vi.fn(() => ws), workspaces: { get: ws.get, create: vi.fn(), delete: vi.fn() }, pages };
runtime = await CloudDockerRuntime.forWorkspace(provider as unknown as Oblien, {
projectId: "project-a", ownerWorkspaceId: "managed-a", workspaceId: "workspace-a", namespace: "namespace-a", beforeProvision: async () => { await spend(); },
provisionLock: { run: fn => fn() }, resolveRegistryAuth: async () => undefined,
@@ -145,7 +145,7 @@ describe("containers on one Oblien Docker workspace", () => {
const options = { projectId: "project-a", serviceName: "api", onReplaced: vi.fn() };
await expect(runtime.applyEnvironment("container-a", { VALUE: "new" }, options)).resolves.toEqual({ containerId: "replacement-a" });
expect(apply).toHaveBeenCalledExactlyOnceWith("container-a", { VALUE: "new" }, options);
- expect(provider.vms.create).not.toHaveBeenCalled();
+ expect(provider.workspaces.create).not.toHaveBeenCalled();
expect(ws.restart).not.toHaveBeenCalled();
expect(ws.delete).not.toHaveBeenCalled();
expect(spend).toHaveBeenCalled();
@@ -356,8 +356,8 @@ describe("containers on one Oblien Docker workspace", () => {
expect(first.hostPortByContainerPort![8080]).not.toBe(first.hostPortByContainerPort![9090]);
expect(next.hostPortByContainerPort![8080]).toBe(first.hostPortByContainerPort![8080]);
await infra.publishRoute("project-a.opsh.io", next.hostPortByContainerPort![8080]!, false);
- expect(routes).toHaveBeenCalledWith("project-a.opsh.io", expect.objectContaining({ routes: [expect.objectContaining({ action: { kind: "proxy", vm: "workspace-a", port: next.hostPortByContainerPort![8080] } })] }));
- expect(provider.vms.create).not.toHaveBeenCalled();
+ expect(routes).toHaveBeenCalledWith("project-a.opsh.io", expect.objectContaining({ routes: [expect.objectContaining({ action: { kind: "proxy", workspace: "workspace-a", port: next.hostPortByContainerPort![8080] } })] }));
+ expect(provider.workspaces.create).not.toHaveBeenCalled();
});
it("keeps named and image-declared volume identities across container replacements", async () => {
await runtime.deployServiceWorkload(group, config);
@@ -496,7 +496,7 @@ describe("containers on one Oblien Docker workspace", () => {
expect(ws.delete).not.toHaveBeenCalled();
});
it("does not take over another project's hostname in the same organization", async () => {
- pageRows.set("project-a", { namespace: "namespace-a", source_vm_id: "workspace-other", exported_path: "/app" });
+ pageRows.set("project-a", { namespace: "namespace-a", source_workspace_id: "workspace-other", exported_path: "/app" });
const result = await runtime.deployServiceWorkload(group, config);
await expect(infra.publishRoute("project-a.opsh.io", result.hostPortByContainerPort![8080]!, false)).rejects.toThrow(/owned|belong/);
expect(pages.enable).not.toHaveBeenCalled();
@@ -549,7 +549,7 @@ describe("containers on one Oblien Docker workspace", () => {
const failure = Object.assign(new Error("Provider unavailable"), { status: 503 });
ws.get.mockRejectedValue(failure);
await expect(runtime.listAllContainers()).rejects.toBe(failure);
- expect(provider.vms.create).not.toHaveBeenCalled();
+ expect(provider.workspaces.create).not.toHaveBeenCalled();
});
it("refuses another namespace's container inventory", async () => {
ws.get.mockResolvedValue({ namespace: "another-namespace", status: "running" });
@@ -603,7 +603,7 @@ describe("containers on one Oblien Docker workspace", () => {
adminProxy: { pages: pages as never, domainRoutes: async () => ({ data: [{ hostname: "project-a.opsh.io", namespace: "namespace-a", owner_type: "page", owner_id: "project-a" }] }) as never } });
await cleanup.removeRoute("project-a.opsh.io");
expect(pages.delete).toHaveBeenCalledWith("project-a");
- pageRows.get("project-a")!.source_vm_id = "workspace-other";
+ pageRows.get("project-a")!.source_workspace_id = "workspace-other";
await expect(cleanup.removeRoute("project-a.opsh.io")).rejects.toThrow("not owned");
});
it("inventories disabled routing Pages without confusing their numeric IDs with slugs", async () => {
@@ -611,7 +611,7 @@ describe("containers on one Oblien Docker workspace", () => {
Ports: [{ PrivatePort: 8080, PublicPort: 30001, Type: "tcp" }] }];
await infra.publishRoute("project-a.opsh.io", 30001, false);
pageRows.get("project-a")!.status = "disabled";
- pageRows.set("other", { slug: "other", domain: "opsh.io", namespace: "namespace-a", source_vm_id: "workspace-other", exported_path: "/opt/openship/cloud-docker/routes/other" });
+ pageRows.set("other", { slug: "other", domain: "opsh.io", namespace: "namespace-a", source_workspace_id: "workspace-other", exported_path: "/opt/openship/cloud-docker/routes/other" });
expect(await infra.listProjectRouteHostnames()).toEqual(["project-a.opsh.io"]);
const cleanup = new CloudInfraProvider(provider as unknown as Oblien, { namespace: "namespace-a", scope: runtime.routingScope() });
await cleanup.removeRoute("project-a.opsh.io");
@@ -707,7 +707,7 @@ describe("containers on one Oblien Docker workspace", () => {
expect(dockerfile).toContain("OPENSHIP_BUILD_PACKAGE_MANAGER_VERSION='1.4.4'");
expect(transfer).not.toHaveBeenCalled();
expect(runtime.connectionOptions?.executor).toBe(runtime.executor);
- expect(provider.vms.create).not.toHaveBeenCalled();
+ expect(provider.workspaces.create).not.toHaveBeenCalled();
});
it("does not let an empty image-only source mask a later inline build context", async () => {
const source = { projectId: "project-a", sessionId: "build-a", repoUrl: "" };
diff --git a/packages/adapters/src/runtime/cloud/docker.ts b/packages/adapters/src/runtime/cloud/docker.ts
index 7c3d33f17..6f1023f13 100644
--- a/packages/adapters/src/runtime/cloud/docker.ts
+++ b/packages/adapters/src/runtime/cloud/docker.ts
@@ -789,7 +789,7 @@ export class CloudDockerRuntime extends DockerRuntime {
};
}
override async listAllContainers() {
- const workspace = await this.client.vms.get(this.workspaceId);
+ const workspace = await this.client.workspaces.get(this.workspaceId);
assertDockerWorkspaceOwner(workspace, this.options.namespace, this.workspaceId);
assertCloudWorkspaceRunning(workspace);
const containers = await super.listAllContainers();
@@ -802,7 +802,7 @@ export class CloudDockerRuntime extends DockerRuntime {
throw new Error("A Docker workspace is not a service container");
let workspace;
try {
- workspace = await this.client.vms.get(this.workspaceId);
+ workspace = await this.client.workspaces.get(this.workspaceId);
} catch (error) {
if (notFound(error)) return { containerId, status: "missing" };
throw error;
@@ -841,7 +841,7 @@ export class CloudDockerRuntime extends DockerRuntime {
override async stop(containerId: string) {
if (containerId === this.workspaceId)
throw new Error("A Docker workspace is not a service container");
- const workspace = await this.client.vms.get(this.workspaceId);
+ const workspace = await this.client.workspaces.get(this.workspaceId);
assertDockerWorkspaceOwner(workspace, this.options.namespace, this.workspaceId);
if (!isDockerWorkspaceRunning(workspace)) return;
return super.stop(containerId);
diff --git a/packages/adapters/src/runtime/cloud/server-connection.ts b/packages/adapters/src/runtime/cloud/server-connection.ts
index a55a2dc8f..3dd7ac665 100644
--- a/packages/adapters/src/runtime/cloud/server-connection.ts
+++ b/packages/adapters/src/runtime/cloud/server-connection.ts
@@ -60,7 +60,7 @@ export function managedProcessState(workload: WorkloadInfo): ContainerStatus {
/** Workload GET is saved configuration and can retain an old state after a VM
* restart. The provider's status endpoint is the live process authority. */
export async function readManagedProcessStatus(
- workloads: ReturnType["workloads"],
+ workloads: ReturnType["workloads"],
saved: WorkloadInfo,
): Promise {
let result: Awaited>;
@@ -147,7 +147,7 @@ export class CloudServerConnection {
}
workspace() {
- return this.client.vm(this.workspaceId);
+ return this.client.workspace(this.workspaceId);
}
runtime(options?: { force?: boolean }): Promise {
@@ -230,7 +230,7 @@ export class CloudServerConnection {
private ensureBridge(): Promise {
const initialize = async () => {
- const info = await this.client.vms.get(this.workspaceId);
+ const info = await this.client.workspaces.get(this.workspaceId);
assertDockerWorkspaceOwner(info, this.options.namespace, this.workspaceId);
assertCloudWorkspaceRunning(info);
let runtime = await this.runtime();
@@ -263,7 +263,7 @@ export class CloudServerConnection {
try {
// Refresh only through this namespace's existing client. A revoked
// namespace credential must still fail the control-plane check.
- runtime = await this.client.vm(this.workspaceId).runtime({ force: true });
+ runtime = await this.client.workspace(this.workspaceId).runtime({ force: true });
} catch (diagnosticFailure) {
observeCaughtError(diagnosticFailure, "adapters/runtime/cloud/server-connection");
throw new AppError(
@@ -304,7 +304,7 @@ export class CloudServerConnection {
// A modified image missing it must fail at that boundary, not attempt to
// bootstrap Python through the transport which already requires it.
await this.executor.writeFile(BRIDGE_SCRIPT, CLOUD_DOCKER_BRIDGE_SOURCE, { mode: 0o700 });
- const workspace = this.client.vm(this.workspaceId);
+ const workspace = this.client.workspace(this.workspaceId);
const workload = (await workspace.workloads.list({ name: BRIDGE_WORKLOAD })).find(
(item) => item.name === BRIDGE_WORKLOAD,
);
@@ -354,7 +354,7 @@ export class CloudServerConnection {
async resume(): Promise {
await this.options.beforeProvision?.();
- const ws = this.client.vm(this.workspaceId);
+ const ws = this.client.workspace(this.workspaceId);
const data = await ws.get();
assertDockerWorkspaceOwner(data, this.options.namespace, this.workspaceId);
if (isDockerWorkspaceRunning(data)) return;
diff --git a/packages/adapters/src/runtime/cloud/workspace-delete.ts b/packages/adapters/src/runtime/cloud/workspace-delete.ts
index 507616a0c..a6cbca3c9 100644
--- a/packages/adapters/src/runtime/cloud/workspace-delete.ts
+++ b/packages/adapters/src/runtime/cloud/workspace-delete.ts
@@ -1,10 +1,10 @@
import { setTimeout as delay } from "node:timers/promises";
-import type { VMHandle } from "oblien";
+import type { WorkspaceHandle } from "oblien";
/** An accepted deletion is still running on Oblien. Keep local cleanup pending
* until the scoped resource is absent; a failed read must not erase ownership. */
export async function deleteCloudWorkspace(
- workspace: Pick,
+ workspace: Pick,
options: { timeoutMs?: number } = {},
): Promise {
try {
diff --git a/packages/adapters/src/runtime/cloud/workspace-ready.test.ts b/packages/adapters/src/runtime/cloud/workspace-ready.test.ts
index 421cf754b..4a4b7e426 100644
--- a/packages/adapters/src/runtime/cloud/workspace-ready.test.ts
+++ b/packages/adapters/src/runtime/cloud/workspace-ready.test.ts
@@ -8,7 +8,7 @@ describe("Docker workspace readiness", () => {
vi.useFakeTimers();
const get = vi.fn().mockResolvedValueOnce({ id: "owned-vm", namespace: "tenant", ...state, ready: false, provisioning: { state: "running" } })
.mockResolvedValue({ id: "owned-vm", namespace: "tenant", ...state, ready: true, provisioning: { state: "ready" } });
- const waiting = waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "owned-vm", "tenant");
+ const waiting = waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "owned-vm", "tenant");
await vi.advanceTimersByTimeAsync(1000);
await expect(waiting).resolves.toMatchObject({ ready: true });
expect(get).toHaveBeenCalledTimes(2);
@@ -16,25 +16,25 @@ describe("Docker workspace readiness", () => {
});
it("uses the live VM state even while the workspace record remains active", async () => {
const get = vi.fn().mockResolvedValue({ id: "vm", namespace: "tenant", status: "active", info: { status: "stopped" }, provisioning: { state: "ready" } });
- await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant", { timeoutMs: 0 })).rejects.toThrow("still starting");
+ await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant", { timeoutMs: 0 })).rejects.toThrow("still starting");
expect(cloudWorkspaceStatus({ status: "active", info: { is_running: false } })).toBe("stopped");
expect(cloudWorkspaceStatus({ status: "active", info: { is_running: true } })).toBe("running");
});
it("rejects a changed namespace even when the VM is ready", async () => {
const get = vi.fn().mockResolvedValue({ id: "vm", namespace: "other-tenant", status: "active", ready: true });
- await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" });
+ await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" });
});
it("rejects a different server in the same namespace before using its state", async () => {
const get = vi.fn().mockResolvedValue({ id: "different-vm", namespace: "tenant", status: "running", ready: true });
- await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" });
+ await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" });
});
it("surfaces a failed provisioning attempt without creating a replacement", async () => {
const get = vi.fn().mockResolvedValue({ id: "vm", namespace: "tenant", status: "error", provisioning: { state: "failed" } });
- await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toThrow("existing disk");
+ await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toThrow("existing disk");
});
it("cancels the wait before another provider read", async () => {
const get = vi.fn();
- await expect(waitForCloudDockerWorkspace({ vms: { get } } as unknown as Oblien, "vm", "tenant", { signal: AbortSignal.abort() })).rejects.toThrow();
+ await expect(waitForCloudDockerWorkspace({ workspaces: { get } } as unknown as Oblien, "vm", "tenant", { signal: AbortSignal.abort() })).rejects.toThrow();
expect(get).not.toHaveBeenCalled();
});
});
diff --git a/packages/adapters/src/runtime/cloud/workspace-ready.ts b/packages/adapters/src/runtime/cloud/workspace-ready.ts
index 2daf9c604..de1010f56 100644
--- a/packages/adapters/src/runtime/cloud/workspace-ready.ts
+++ b/packages/adapters/src/runtime/cloud/workspace-ready.ts
@@ -1,8 +1,8 @@
import { setTimeout as delay } from "node:timers/promises";
-import type { Oblien, VMData } from "oblien";
+import type { Oblien, WorkspaceData } from "oblien";
import { AppError } from "@repo/core";
-export function assertDockerWorkspaceOwner(workspace: VMData, namespace: string, workspaceId: string): void {
+export function assertDockerWorkspaceOwner(workspace: WorkspaceData, namespace: string, workspaceId: string): void {
if (workspace.namespace !== namespace || workspace.id !== workspaceId)
throw new AppError("Cloud workspace identity does not match its server", 502, "CLOUD_SERVER_IDENTITY_MISMATCH");
}
@@ -20,7 +20,7 @@ export function isDockerWorkspaceRunning(workspace: { status: string; info?: unk
return cloudWorkspaceStatus(workspace) === "running";
}
-export function assertCloudWorkspaceRunning(workspace: VMData): void {
+export function assertCloudWorkspaceRunning(workspace: WorkspaceData): void {
const state = cloudWorkspaceStatus(workspace);
if (state === "running") return;
if (["stopped", "paused", "suspended"].includes(state))
@@ -35,7 +35,7 @@ export function assertCloudWorkspaceRunning(workspace: VMData): void {
export async function waitForCloudWorkspaceStopped(client: Oblien, workspaceId: string, namespace: string) {
const deadline = Date.now() + 60_000;
for (;;) {
- const workspace = await client.vms.get(workspaceId);
+ const workspace = await client.workspaces.get(workspaceId);
assertDockerWorkspaceOwner(workspace, namespace, workspaceId);
if (["stopped", "paused", "suspended"].includes(cloudWorkspaceStatus(workspace))) return;
if (Date.now() >= deadline) throw new Error("The managed server has not returned to its stopped state");
@@ -47,11 +47,11 @@ export async function waitForCloudWorkspaceStopped(client: Oblien, workspaceId:
export async function waitForCloudDockerWorkspace(
client: Oblien, workspaceId: string, namespace: string,
options: { signal?: AbortSignal; timeoutMs?: number } = {},
-): Promise {
+): Promise {
const deadline = Date.now() + (options.timeoutMs ?? 600_000);
while (true) {
options.signal?.throwIfAborted();
- const workspace = await client.vms.get(workspaceId);
+ const workspace = await client.workspaces.get(workspaceId);
assertDockerWorkspaceOwner(workspace, namespace, workspaceId);
const provisioning = workspace.provisioning as { state?: string; error?: unknown } | undefined;
if (provisioning?.state === "failed" || ["error", "failed"].includes(cloudWorkspaceStatus(workspace))) {
diff --git a/packages/adapters/src/runtime/cloud/workspace-resources.ts b/packages/adapters/src/runtime/cloud/workspace-resources.ts
index 627e4a124..e6440d18e 100644
--- a/packages/adapters/src/runtime/cloud/workspace-resources.ts
+++ b/packages/adapters/src/runtime/cloud/workspace-resources.ts
@@ -1,4 +1,4 @@
-import type { VMData, VMHandle } from "oblien";
+import type { WorkspaceData, WorkspaceHandle } from "oblien";
import { cloudCpus, type ResourceConfig } from "../../types";
import { cloudWorkspaceStatus } from "./workspace-ready";
@@ -6,7 +6,7 @@ type WorkspaceResources = Pick &
Partial>;
export function cloudWorkspaceHasResources(
- workspace: Pick,
+ workspace: Pick,
expected: WorkspaceResources,
): boolean {
const actual = workspace.resources;
@@ -21,9 +21,9 @@ export function cloudWorkspaceHasResources(
* Require an applied change and read the allocation back before claiming the
* runtime was resized. Callers retain ownership of readiness and restoration. */
export async function updateCloudWorkspaceResources(
- workspace: VMHandle,
+ workspace: WorkspaceHandle,
resources: WorkspaceResources,
- current?: VMData,
+ current?: WorkspaceData,
): Promise {
const before = current ?? (await workspace.get());
if (before.id !== workspace.id)
diff --git a/packages/adapters/src/runtime/git-clone.test.ts b/packages/adapters/src/runtime/git-clone.test.ts
index 4a210eb6d..c80674ecc 100644
--- a/packages/adapters/src/runtime/git-clone.test.ts
+++ b/packages/adapters/src/runtime/git-clone.test.ts
@@ -1,6 +1,6 @@
import { describe, it, expect } from "vitest";
import { execFileSync, spawnSync } from "node:child_process";
-import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import {
@@ -163,38 +163,6 @@ describe("assembleGitClone — token / public mode", () => {
const pub = assembleGitClone({ repoUrl: "https://github.com/owner/repo.git" });
expect(pub.cloneUrl).toBe("https://github.com/owner/repo.git");
});
- it("stays on HTTPS when the user's git config rewrites https:// to ssh", () => {
- // Token clones allow only HTTPS. A common global rule such as
- // `url."git@github.com:".insteadOf https://github.com/` would turn the clone URL
- // into ssh and fail with "transport 'ssh' not allowed". `ls-remote --get-url`
- // applies the same rewrites as a clone, without touching the network.
- const dir = mkdtempSync(join(tmpdir(), "openship-git-rewrite-"));
- const globalConfig = join(dir, "gitconfig");
- const rules = [
- ["git@github.com:", "https://github.com/"], // host-wide
- ["git@github.com:owner/", "https://github.com/owner/"], // namespace-wide
- ["git@github.com:owner/repo", "https://github.com/owner/repo"], // this repo, without .git
- ];
- writeFileSync(
- globalConfig,
- rules.map(([to, from]) => `[url "${to}"]\n\tinsteadOf = ${from}\n`).join(""),
- );
- const env = {
- ...Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_"))),
- GIT_CONFIG_NOSYSTEM: "1",
- GIT_CONFIG_GLOBAL: globalConfig,
- };
- try {
- const resolved = execFileSync(
- "sh",
- ["-c", gitShellCommand(inv, `ls-remote --get-url ${sq(inv.cloneUrl)}`)],
- { encoding: "utf8", cwd: dir, env },
- ).trim();
- expect(resolved).toBe("https://github.com/owner/repo.git");
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
- });
});
describe("assembleGitClone — relay (desktop credential helper) mode", () => {
diff --git a/packages/adapters/src/runtime/git-clone.ts b/packages/adapters/src/runtime/git-clone.ts
index 4ff5cf347..f5a9cd9b4 100644
--- a/packages/adapters/src/runtime/git-clone.ts
+++ b/packages/adapters/src/runtime/git-clone.ts
@@ -246,8 +246,6 @@ function scopedTokenInvocation(auth: GitCloneAuth): GitCloneInvocation {
url.password = "";
const pair = gitCredentialPair(url.hostname, auth.gitToken!.trim());
const base = `https://${url.host}/`;
- const repoUrl = `${base}${url.pathname.replace(/^\/+/, "")}`;
- const namespaceUrl = `${base}${segments.join("/")}/`;
const settings = [
["credential.helper", ""],
["credential.helper", SCOPED_TOKEN_HELPER],
@@ -261,14 +259,6 @@ function scopedTokenInvocation(auth: GitCloneAuth): GitCloneInvocation {
[`url.${base}.insteadOf`, `git@${url.hostname}:`],
[`url.${base}.insteadOf`, `ssh://git@${url.hostname}/`],
[`url.${base}.insteadOf`, `ssh://${url.hostname}/`],
- // The opposite rewrite, https:// to ssh, is a common user setting that this
- // clone must not follow: only HTTPS is allowed above, so git would fail with
- // "transport 'ssh' not allowed". Git applies the longest matching insteadOf,
- // so mapping the repository and its namespace onto themselves outranks a
- // broader rule in the user's global or system config. A rule of exactly the
- // same length as ours is still ordered by config scope and can win.
- [`url.${repoUrl}.insteadOf`, repoUrl],
- [`url.${namespaceUrl}.insteadOf`, namespaceUrl],
];
const baseInvocation = invocation(
url.href,
diff --git a/packages/adapters/src/runtime/oblien-routing.ts b/packages/adapters/src/runtime/oblien-routing.ts
index 542192084..6a232b1d1 100644
--- a/packages/adapters/src/runtime/oblien-routing.ts
+++ b/packages/adapters/src/runtime/oblien-routing.ts
@@ -18,12 +18,12 @@ import type { RoutingConfig } from "@repo/core";
import { compileVercelRouting, type CompiledRouting } from "../infra/vercel-routing";
/** Sentinel so reused `compileVercelRouting` marks which proxy targets are the
- * owned backend (→ Oblien `vm`+`port`) vs. a literal external URL. */
+ * owned backend (→ Oblien `workspace`+`port`) vs. a literal external URL. */
const BACKEND_SENTINEL = "oblien-backend://self";
-/** An owned Oblien VM to reverse-proxy to. */
-export interface OblienVmTarget {
- vm: string;
+/** An owned Oblien workspace to reverse-proxy to. */
+export interface OblienWorkspaceTarget {
+ workspace: string;
port: number;
}
@@ -34,11 +34,11 @@ export interface OblienRoutingContext {
/** Workspace backing `/` when the frontend runs as a container instead of a
* Page (a catch-all `/` proxy is appended last). Mutually exclusive with
* `staticPage`. Also the server-only shape: set `root`, omit `backend`. */
- root?: OblienVmTarget;
+ root?: OblienWorkspaceTarget;
/** Backend workspace that path rewrites (e.g. `/api/*`) proxy to. */
- backend?: OblienVmTarget;
+ backend?: OblienWorkspaceTarget;
/** Resolved internal URLs, shared by the generic route-registration path. */
- proxyTargets?: ReadonlyMap;
+ proxyTargets?: ReadonlyMap;
}
/** Oblien only accepts 301/302/307/308; coerce anything else to a safe default
@@ -51,7 +51,7 @@ function toOblienRedirectStatus(code: number): 301 | 302 | 307 | 308 {
export function compileRoutingToOblien(
routing: RoutingConfig,
ctx: OblienRoutingContext = {},
-): RoutesInput & { routes: RouteRule[] } {
+): RoutesInput {
const compiled = compileVercelRouting(routing, {
backendTargetUrl: ctx.backend ? BACKEND_SENTINEL : undefined,
});
@@ -63,7 +63,7 @@ export function compileRoutingToOblien(
export function compileResolvedRoutingToOblien(
compiled: Pick,
ctx: OblienRoutingContext = {},
-): RoutesInput & { routes: RouteRule[] } {
+): RoutesInput {
const routes: RouteRule[] = [];
// Terminal rules are first-match-wins, evaluated before static files; order
@@ -88,7 +88,7 @@ export function compileResolvedRoutingToOblien(
for (const loc of compiled.proxyLocations) {
const owned = loc.targetUrl === BACKEND_SENTINEL ? ctx.backend : ctx.proxyTargets?.get(loc.targetUrl);
const action: RouteProxyAction = owned
- ? { kind: "proxy", vm: owned.vm, port: owned.port }
+ ? { kind: "proxy", workspace: owned.workspace, port: owned.port }
: { kind: "proxy", origin: loc.targetUrl };
// A capture-bearing rewrite carries its upstream path as a `$1..$9` template —
// exactly what `RouteProxyAction.path` takes, against a `wildcard` match.
@@ -107,7 +107,7 @@ export function compileResolvedRoutingToOblien(
if (ctx.root) {
routes.push({
match: { path: "/", type: "prefix" },
- action: { kind: "proxy", vm: ctx.root.vm, port: ctx.root.port },
+ action: { kind: "proxy", workspace: ctx.root.workspace, port: ctx.root.port },
});
}
@@ -118,7 +118,7 @@ export function compileResolvedRoutingToOblien(
});
}
- const input: RoutesInput & { routes: RouteRule[] } = { routes };
+ const input: RoutesInput = { routes };
if (ctx.staticPage) {
input.static = { page: ctx.staticPage };
if (compiled.spaFallback !== undefined) input.spa = compiled.spaFallback;
diff --git a/packages/adapters/src/runtime/transfer.ts b/packages/adapters/src/runtime/transfer.ts
index a630ce5a5..f5a80b487 100644
--- a/packages/adapters/src/runtime/transfer.ts
+++ b/packages/adapters/src/runtime/transfer.ts
@@ -1,6 +1,6 @@
import { execFile } from "node:child_process";
-import type { VMHandle } from "oblien";
+import type { WorkspaceHandle } from "oblien";
import { TRANSFER_EXCLUDES, safeErrorMessage } from "@repo/core";
import { getTarCreateEnv, prepareSourceTarArgs } from "../archive";
@@ -24,7 +24,7 @@ export type LocalDirectoryTarget =
}
| {
kind: "cloud-runtime";
- runtime: Awaited>;
+ runtime: Awaited>;
path: string;
};
diff --git a/packages/adapters/src/system/edge-container-executor.test.ts b/packages/adapters/src/system/edge-container-executor.test.ts
index ab9e53bf4..950d8617c 100644
--- a/packages/adapters/src/system/edge-container-executor.test.ts
+++ b/packages/adapters/src/system/edge-container-executor.test.ts
@@ -46,12 +46,6 @@ describe("containerCommand", () => {
const wrapped = containerCommand("openship-edge", `pkill -f '[o]penresty'`);
expect(wrapped).toBe(`docker exec 'openship-edge' sh -c 'pkill -f '\\''[o]penresty'\\'''`);
});
-
- it("keeps stdin attached only when an upload requests it", () => {
- expect(containerCommand("openship-edge", "cat > /tmp/request.json", { stdin: true })).toBe(
- "docker exec -i 'openship-edge' sh -c 'cat > /tmp/request.json'",
- );
- });
});
describe("edgeContainerExecutor", () => {
diff --git a/packages/adapters/src/system/edge-container-executor.ts b/packages/adapters/src/system/edge-container-executor.ts
index 96c2c4dbe..21f9ac1f5 100644
--- a/packages/adapters/src/system/edge-container-executor.ts
+++ b/packages/adapters/src/system/edge-container-executor.ts
@@ -7,8 +7,8 @@ import { explainEdgeDown, isEdgeDownFailure } from "./edge-exec-error";
import { framedCatCommand, unframeFileRead } from "./exact-file-read";
/** Wrap a command so it runs INSIDE the named edge container. */
-export function containerCommand(container: string, command: string, opts?: { stdin?: boolean }): string {
- return `docker exec ${opts?.stdin ? "-i " : ""}${sq(container)} sh -c ${sq(command)}`;
+export function containerCommand(container: string, command: string): string {
+ return `docker exec ${sq(container)} sh -c ${sq(command)}`;
}
/**
diff --git a/packages/adapters/src/system/elevated-executor.test.ts b/packages/adapters/src/system/elevated-executor.test.ts
index e1e42972e..bbef511bc 100644
--- a/packages/adapters/src/system/elevated-executor.test.ts
+++ b/packages/adapters/src/system/elevated-executor.test.ts
@@ -1,6 +1,5 @@
import { describe, it, expect, vi } from "vitest";
import { execFileSync } from "node:child_process";
-import { Readable } from "node:stream";
import { elevatedExecutor, elevateCommand, ensureOwnedDir } from "./elevated-executor";
import { framedCatCommand } from "./exact-file-read";
import { probeOutput } from "./environment.fixtures";
@@ -64,17 +63,6 @@ describe("elevateCommand", () => {
});
describe("elevatedExecutor", () => {
- it("preserves elevation and stream identity for stdin uploads without inventing capability", async () => {
- const { inner } = fakeExecutor();
- expect(elevatedExecutor(inner).execWithInput).toBeUndefined();
- const body = Readable.from(["request bytes"]);
- const result = { code: 0, stdout: "", stderr: "" };
- inner.execWithInput = vi.fn(async () => result);
- const command = "docker exec -i edge sh -c 'cat > /tmp/request'";
- expect(await elevatedExecutor(inner).execWithInput!(command, body)).toBe(result);
- expect(inner.execWithInput).toHaveBeenCalledWith(elevateCommand(command), body);
- });
-
it("elevates exec and streamExec", async () => {
const { inner, exec, streamExec } = fakeExecutor();
const el = elevatedExecutor(inner);
diff --git a/packages/adapters/src/system/elevated-executor.ts b/packages/adapters/src/system/elevated-executor.ts
index 5f246f04e..c09b09e3e 100644
--- a/packages/adapters/src/system/elevated-executor.ts
+++ b/packages/adapters/src/system/elevated-executor.ts
@@ -150,9 +150,6 @@ export function elevatedExecutor(inner: CommandExecutor): CommandExecutor {
inner.exec(elevateCommand(command), opts),
streamExec: (command: string, onLog: (log: LogEntry) => void, opts?: { signal?: AbortSignal }) =>
inner.streamExec(elevateCommand(command), onLog, opts),
- ...(inner.execWithInput ? {
- execWithInput: (command, body) => inner.execWithInput!(elevateCommand(command), body),
- } satisfies Partial : {}),
writeFile: writeFileElevated,
readFile: readFileElevated,
exists: existsElevated,
diff --git a/packages/adapters/src/system/local-execution-policy.test.ts b/packages/adapters/src/system/local-execution-policy.test.ts
index 877d4372a..09056eae0 100644
--- a/packages/adapters/src/system/local-execution-policy.test.ts
+++ b/packages/adapters/src/system/local-execution-policy.test.ts
@@ -2,7 +2,6 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { access, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
-import { Readable } from "node:stream";
import { LocalExecutor } from "./local-executor";
import { hasLocalCommand, sq } from "./local-shell";
import { createExecutor } from "./executor";
@@ -37,8 +36,6 @@ describe("Cloud cannot execute on the API host", () => {
for (const operation of [
() => executor.exec(command),
() => direct.exec(command),
- () => direct.rawExec(command),
- () => direct.execWithInput(command, Readable.from(["private backup data"])),
() => executor.streamExec(command, onLog),
() => executor.streamExec(command, onLog, { signal: AbortSignal.abort() }),
() => executor.transferIn!("/does-not-exist", path),
diff --git a/packages/adapters/src/system/local-executor-stream.test.ts b/packages/adapters/src/system/local-executor-stream.test.ts
deleted file mode 100644
index 14c36ca1a..000000000
--- a/packages/adapters/src/system/local-executor-stream.test.ts
+++ /dev/null
@@ -1,154 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-import { createHash } from "node:crypto";
-import { mkdtemp, readFile, rm } from "node:fs/promises";
-import { tmpdir } from "node:os";
-import { join } from "node:path";
-import { Readable, Writable } from "node:stream";
-import { pipeline } from "node:stream/promises";
-import { LocalExecutor } from "./local-executor";
-import { sq } from "./local-shell";
-import { BareRuntime } from "../runtime/bare";
-import { BareBackupExecutor } from "../backup/executors/bare";
-import { CustomCommandProducer } from "../backup/producers/custom-command";
-
-const executors: LocalExecutor[] = [];
-const dirs: string[] = [];
-const node = (script: string) => `${sq(process.execPath)} -e ${sq(script)}`;
-function executor() {
- vi.stubEnv("CLOUD_MODE", "false");
- const result = new LocalExecutor();
- executors.push(result);
- return result;
-}
-afterEach(async () => {
- await Promise.all(executors.splice(0).map((exec) => exec.dispose()));
- await Promise.all(dirs.splice(0).map((path) => rm(path, { recursive: true, force: true })));
- vi.unstubAllEnvs();
-});
-
-describe("local bare backup command streams", () => {
- it("captures and restores a binary artifact through the real bare executor", async () => {
- const dir = await mkdtemp(join(tmpdir(), "openship-local-backup-"));
- dirs.push(dir);
- const file = join(dir, "restored.bin");
- const transport = executor();
- const bare = new BareBackupExecutor(new BareRuntime({ executor: transport }));
- const service = { id: "mail", name: "mail", projectId: "", volumes: [], env: {} } as never;
- const payload = Buffer.from(Array.from({ length: 256 }, (_, i) => i));
- const expected = createHash("sha256");
- for (let i = 0; i < 8192; i++) expected.update(payload);
- const capture = await bare.execStream(service, [
- "sh",
- "-c",
- node(
- "const b=Buffer.from(Array.from({length:256},(_,i)=>i));for(let i=0;i<8192;i++)process.stdout.write(b)",
- ),
- ]);
- const hash = createHash("sha256");
- const restore = bare.pipeIntoCommand(
- service,
- ["sh", "-c", `cat > ${sq(file)}`],
- capture.stdout,
- );
- expect(await restore).toMatchObject({ code: 0 });
- expect(await capture.awaitExit).toMatchObject({ code: 0 });
- const restored = await readFile(file);
- hash.update(restored);
- expect(restored.length).toBe(256 * 8192);
- expect(hash.digest("hex")).toBe(expected.digest("hex"));
- });
-
- it("preserves a failing loader's exit status and bounded diagnostic tail", async () => {
- const exec = executor();
- const result = await exec.execWithInput(
- node(
- "process.stdin.resume();process.stdin.on('end',()=>{process.stderr.write('x'.repeat(32768)+'loader failed');process.exitCode=42})",
- ),
- Readable.from([Buffer.from([0, 255, 128])]),
- );
- expect(result.code).toBe(42);
- expect(result.stderr).toHaveLength(16 * 1024);
- expect(result.stderr).toMatch(/loader failed$/);
- });
-
- it("propagates an input failure instead of accepting a partial restore", async () => {
- const exec = executor();
- const source = Readable.from(
- (async function* () {
- yield Buffer.from("partial");
- throw new Error("object download interrupted");
- })(),
- );
- await expect(exec.execWithInput("cat >/dev/null", source)).rejects.toThrow(
- "object download interrupted",
- );
- });
-
- it("cancels a command that has consumed stdin but is still running", async () => {
- const exec = executor();
- const cancel = new AbortController();
- const result = exec.runWithAbortSignal(cancel.signal, () =>
- exec.execWithInput(
- node("process.stdin.resume();process.stdin.on('end',()=>setInterval(()=>{},1000))"),
- Readable.from(["data"]),
- ),
- );
- const assertion = expect(result).rejects.toThrow("stop restore");
- setTimeout(() => cancel.abort(new Error("stop restore")), 150);
- await assertion;
- });
-
- it("forwards restore cancellation through the shared custom-command producer", async () => {
- const transport = executor();
- const bare = new BareBackupExecutor(new BareRuntime({ executor: transport }));
- const cancel = new AbortController();
- const service = { id: "mail", name: "mail", projectId: "", volumes: [], env: {} } as never;
- const restore = CustomCommandProducer.restore(
- service,
- bare,
- {
- key: "mail.tar.zst",
- payloadKind: "custom_command",
- sha256: "",
- sizeBytes: 4,
- metadata: {
- restoreCommand: node(
- "process.stdin.resume();process.stdin.on('end',()=>setInterval(()=>{},1000))",
- ),
- },
- open: async () => Readable.from(["mail"]),
- },
- { signal: cancel.signal },
- );
- const assertion = expect(restore).rejects.toThrow("stop mail restore");
- setTimeout(() => cancel.abort(new Error("stop mail restore")), 150);
- await assertion;
- });
-
- it("streams with backpressure and reports a capture failure", async () => {
- const exec = executor();
- const capture = await exec.rawExec(
- node(
- "process.stdout.write(Buffer.alloc(100000));process.stderr.write('capture failed');process.exitCode=7",
- ),
- );
- let bytes = 0;
- let stderr = "";
- capture.stderr.on("data", (chunk) => {
- stderr += chunk;
- });
- await pipeline(
- capture.stdout,
- new Writable({
- highWaterMark: 1024,
- write(chunk, _encoding, done) {
- bytes += chunk.length;
- setTimeout(done, 1);
- },
- }),
- );
- expect(await capture.onClose).toBe(7);
- expect(bytes).toBe(100000);
- expect(stderr).toBe("capture failed");
- });
-});
diff --git a/packages/adapters/src/system/local-executor.ts b/packages/adapters/src/system/local-executor.ts
index ca85ef655..06daaa8fd 100644
--- a/packages/adapters/src/system/local-executor.ts
+++ b/packages/adapters/src/system/local-executor.ts
@@ -1,8 +1,5 @@
import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
-import { AsyncLocalStorage } from "node:async_hooks";
import { exec, spawn } from "node:child_process";
-import { pipeline, type Readable } from "node:stream";
-import { promisify } from "node:util";
import {
access,
mkdir as fsMkdir,
@@ -30,103 +27,6 @@ import {
* File operations use node:fs directly.
*/
export class LocalExecutor implements CommandExecutor {
- private readonly abortScope = new AsyncLocalStorage();
- private readonly activeRawCommands = new Set<{ kill: () => void; onClose: Promise }>();
-
- runWithAbortSignal(signal: AbortSignal, work: () => Promise): Promise {
- return this.abortScope.run(signal, work);
- }
-
- /** Binary transport for self-hosted/desktop workloads. Never available to a
- * Cloud controller, including when this executor predates mode initialization. */
- private async spawnRawCommand(command: string) {
- assertLocalHostExecutionAllowed();
- const signal = this.abortScope.getStore();
- signal?.throwIfAborted();
- const grouped = process.platform !== "win32";
- const child = spawn(getLocalShellPath(), getLocalShellArgs(command), {
- stdio: ["pipe", "pipe", "pipe"],
- env: getLocalExecEnv(),
- detached: grouped,
- });
- let terminating = false;
- let escalation: ReturnType | undefined;
- const send = (kind: NodeJS.Signals) => {
- try {
- if (grouped && child.pid) process.kill(-child.pid, kind);
- else child.kill(kind);
- } catch (error) {
- // A child can exit between the close event and cancellation.
- if ((error as NodeJS.ErrnoException).code !== "ESRCH")
- observeCaughtError(error, "adapters/system/local-executor");
- }
- };
- const kill = () => {
- if (terminating) return;
- terminating = true;
- send("SIGTERM");
- escalation = setTimeout(() => send("SIGKILL"), 1_000);
- escalation.unref?.();
- };
- const onClose = new Promise((resolve, reject) => {
- let failure: Error | undefined;
- child.once("error", (error) => {
- // diagnostics-ignore: onClose rejects with this failure after stdio closes.
- failure = error;
- });
- child.once("close", (code) => {
- if (terminating && grouped) send("SIGKILL");
- clearTimeout(escalation);
- signal?.removeEventListener("abort", kill);
- this.activeRawCommands.delete(active);
- if (signal?.aborted) reject(signal.reason ?? new Error("Local command cancelled"));
- else if (failure) reject(failure);
- else resolve(code ?? 1);
- });
- });
- // The process can fail before the caller attaches its stream lifecycle.
- void onClose.catch((error) => observeCaughtError(error, "adapters/system/local-executor"));
- const active = { kill, onClose };
- this.activeRawCommands.add(active);
- signal?.addEventListener("abort", kill, { once: true });
- if (signal?.aborted) kill();
- await new Promise((resolve, reject) => {
- child.once("spawn", resolve);
- child.once("error", reject);
- });
- return { child, ...active };
- }
-
- async rawExec(command: string) {
- const { child, onClose, kill } = await this.spawnRawCommand(command);
- child.stdin.end();
- return { stdout: child.stdout, stderr: child.stderr, onClose, kill };
- }
-
- async execWithInput(command: string, body: Readable) {
- const { child, onClose, kill } = await this.spawnRawCommand(command);
- let stderr = "";
- let stdout = "";
- child.stdout.on("data", (data: Buffer) => { stdout = (stdout + data.toString()).slice(-16 * 1024); });
- child.stderr.on("data", (data: Buffer) => { stderr = (stderr + data.toString()).slice(-16 * 1024); });
- let inputError: NodeJS.ErrnoException | undefined;
- const input = promisify(pipeline)(body, child.stdin).catch((error) => {
- // diagnostics-ignore: propagated below after the subprocess and input settle.
- inputError = error;
- kill();
- });
- try {
- const code = await onClose;
- await input;
- if (inputError && (code === 0 || !["EPIPE", "ERR_STREAM_PREMATURE_CLOSE"].includes(inputError.code ?? "")))
- throw inputError;
- return { code, stderr: stderr.trim(), stdout: stdout.trim() };
- } finally {
- // Await upstream teardown before a restore releases its execution lock.
- await input;
- }
- }
-
async exec(command: string, opts?: { timeout?: number }): Promise {
assertLocalHostExecutionAllowed();
return new Promise((resolve, reject) => {
@@ -321,8 +221,6 @@ export class LocalExecutor implements CommandExecutor {
}
async dispose(): Promise {
- const commands = [...this.activeRawCommands];
- for (const command of commands) command.kill();
- await Promise.allSettled(commands.map((command) => command.onClose));
+ // Nothing to clean up for local execution
}
}
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/adapters/src/system/proxy/replace-edge-container.test.ts b/packages/adapters/src/system/proxy/replace-edge-container.test.ts
index 3f011ba44..403685e71 100644
--- a/packages/adapters/src/system/proxy/replace-edge-container.test.ts
+++ b/packages/adapters/src/system/proxy/replace-edge-container.test.ts
@@ -110,9 +110,7 @@ default: throw new Error('Unexpected Docker command: ' + a.join(' '));
container: "test-edge",
image: "edge:new",
mounts: [],
- // These probes launch a real CLI process. Allow startup under CI contention;
- // a one-second rounded deadline can expire before the first probe even runs.
- verifyTimeoutMs: 5_000,
+ verifyTimeoutMs: 1,
predecessor: {
id: old,
labels: {
@@ -176,8 +174,7 @@ describe("server-owned edge replacement", () => {
it("validates before stopping and removes the predecessor only after the new edge is healthy", async () => {
const f = await fixture();
- const result = await f.run();
- expect(result.code, result.stderr).toBe(0);
+ expect((await f.run()).code).toBe(0);
const state = await f.state();
expect(Object.keys(state)).toEqual([next]);
expect(state[next]).toMatchObject({
diff --git a/packages/adapters/src/types.ts b/packages/adapters/src/types.ts
index a0fe5b399..03ac2b605 100644
--- a/packages/adapters/src/types.ts
+++ b/packages/adapters/src/types.ts
@@ -983,7 +983,7 @@ export interface CommandExecutor extends ExecOnly {
* Run a command and return the raw stdout/stderr streams without
* line splitting. Enables byte-for-byte piping of command output.
*
- * Local execution enforces the shared Cloud-host refusal at invocation time.
+ * Only available on SshExecutor - local executors do not implement this.
*/
rawExec?(command: string): Promise<{
stdout: Readable;
@@ -999,7 +999,7 @@ export interface CommandExecutor extends ExecOnly {
* rawExec (stdout) — lets a Readable move INTO a remote command byte-for-byte
* without staging to a temp file first.
*
- * Local execution enforces the shared Cloud-host refusal at invocation time.
+ * Only available on SshExecutor — local executors do not implement this.
*/
execWithInput?(
command: string,
diff --git a/packages/adapters/test/backup-empty-source-guard.test.ts b/packages/adapters/test/backup-empty-source-guard.test.ts
index 79fe65b46..9edb63413 100644
--- a/packages/adapters/test/backup-empty-source-guard.test.ts
+++ b/packages/adapters/test/backup-empty-source-guard.test.ts
@@ -1,137 +1,138 @@
-/** Verified empty sources are valid; missing sources must never be created by capture. */
+/**
+ * A volume capture must not record an archive of nothing as a backup.
+ *
+ * The daemon CREATES a missing bind directory and a missing named volume when it
+ * honors `HostConfig.Binds`. So a source that is not on the host — an external disk
+ * that failed to mount, a data directory renamed under a still-running container, a
+ * volume `docker system prune --volumes` took — produced a helper that started fine
+ * and a `tar -c` of an empty mount that exited 0.
+ *
+ * Nothing downstream could tell that apart from a real backup: an empty tar is 10240
+ * bytes and ~350 compressed, so the orchestrator's only emptiness guard
+ * (`sizeBytes === 0`) passed, and the producer's guards only cover "no sources listed
+ * at all", never "the source turned out to be empty".
+ *
+ * Two halves are asserted, because either alone is a false pass: that the generated
+ * command CARRIES the gate, and that the gate actually does what it claims when a
+ * real shell runs it.
+ */
+
import { spawnSync } from "node:child_process";
-import { mkdtemp, rm, stat } from "node:fs/promises";
+import { mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { randomUUID } from "node:crypto";
-import { describe, expect, it, beforeAll, afterAll } from "vitest";
-import { DockerRuntime } from "../src/runtime/docker";
-import { DockerBackupExecutor } from "../src/backup/executors/docker";
-import { VolumeCopyProducer } from "../src/backup/producers/volume";
+import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
+import { FakeAttachStream, harness } from "./helpers/docker-helper-harness";
import type { ServiceHandle } from "../src/backup/types";
+const attachControl: { stream: FakeAttachStream | null } = { stream: null };
+
+// Partial mock: the executor also imports `daemonConnectionFrom` from this module.
+vi.mock(import("../src/runtime/docker-exec-stream"), async (importOriginal) => ({
+ ...(await importOriginal()),
+ startAttachStream: async () => attachControl.stream as never,
+ startExecStream: async () => attachControl.stream as never,
+}));
+
const SERVICE: ServiceHandle = {
id: "svc_1",
projectId: "prj_1",
- name: "optional-storage",
- image: "alpine:3",
+ name: "db",
+ image: "postgres:16",
env: {},
- volumes: [],
+ volumes: ["pgdata:/var/lib/postgresql/data"],
containerId: null,
- projectSlug: "backup-empty-regression",
+ projectSlug: "shop",
namespaceVolumes: false,
};
-const dockerAvailable = spawnSync("docker", ["info"], { stdio: "ignore" }).status === 0;
-const dockerRequired = process.env.RUN_DOCKER_E2E === "1";
+beforeEach(() => {
+ attachControl.stream = new FakeAttachStream();
+});
+afterEach(() => {
+ vi.restoreAllMocks();
+});
-describe.skipIf(!dockerAvailable && !dockerRequired)("Docker capture source existence", () => {
- let runtime: DockerRuntime;
- let executor: DockerBackupExecutor;
- let root: string;
- let containerId: string;
- const prefix = `openship-empty-${randomUUID()}`;
- const volumes = ["empty", "populated", "unavailable"].map((name) => `${prefix}-${name}`);
+/** The helper command the executor asked the daemon to run. */
+async function capturedCmd(compression: "none" | "zstd" | "gzip"): Promise {
+ const h = harness({ wait: 0 }, () => ({}));
+ const exec = await h.executor();
+ const { stdout, awaitExit } = await exec.streamPath(SERVICE, "pgdata-0", { compression });
+ stdout.on("data", () => {});
+ stdout.on("error", () => {});
+ attachControl.stream!.end?.();
+ await awaitExit.catch(() => {});
+ const spec = h.created.at(-1) as { Cmd?: string[] } | undefined;
+ expect(spec?.Cmd, JSON.stringify(h.created)).toBeTruthy();
+ return (spec!.Cmd as string[]).join("\n");
+}
- beforeAll(async () => {
- if (!dockerAvailable) throw new Error("RUN_DOCKER_E2E=1 requires Docker");
- runtime = await DockerRuntime.create({ transport: "socket" });
- executor = new DockerBackupExecutor(runtime);
- await runtime.pullImage("alpine:3");
- root = await mkdtemp(join(tmpdir(), "openship-empty-source-"));
- for (const name of volumes.slice(0, 2)) await runtime.docker.createVolume({ Name: name });
- await runtime.docker.createVolume({
- Name: volumes[2],
- Driver: "local",
- DriverOpts: { type: "none", o: "bind", device: join(root, "missing-storage") },
- });
- const helper = await runtime.docker.createContainer({
- Image: "alpine:3",
- Cmd: ["sh", "-c", "echo important-data > /data/keep.txt"],
- HostConfig: { Binds: [`${volumes[1]}:/data`] },
- });
- try {
- await helper.start();
- expect((await helper.wait()).StatusCode).toBe(0);
- } finally {
- await helper.remove({ force: true });
+describe("the capture command carries an empty-source gate", () => {
+ it("gates every codec, not just the compressed ones", async () => {
+ // `none` and `gzip` skip the pipeline entirely (busybox tar compresses in
+ // process) and take a different branch of safeDumpCommand, so a gate added only
+ // to the zstd prelude would leave the other two silently backing up nothing.
+ for (const compression of ["none", "gzip", "zstd"] as const) {
+ const cmd = await capturedCmd(compression);
+ expect(cmd, compression).toContain("ls -A /mnt");
+ expect(cmd, compression).toContain("exit 91");
+ // The source id is named, because "something was empty" is not actionable.
+ expect(cmd, compression).toContain("pgdata-0");
}
- const service = await runtime.docker.createContainer({
- Image: "alpine:3",
- Cmd: ["sleep", "300"],
- HostConfig: {
- Binds: [`${volumes[0]}:/optional`, `${root}:/empty-bind`, `${volumes[1]}:/data`],
- },
- });
- containerId = service.id;
- await service.start();
- }, 120_000);
-
- afterAll(async () => {
- if (containerId) await runtime.docker.getContainer(containerId).remove({ force: true });
- if (runtime)
- for (const name of volumes)
- await runtime.docker
- .getVolume(name)
- .remove()
- .catch(() => {});
- if (root) await rm(root, { recursive: true, force: true });
});
- const collect = async (stdout: NodeJS.ReadableStream) => {
- const chunks: Buffer[] = [];
- for await (const chunk of stdout) chunks.push(Buffer.from(chunk));
- return Buffer.concat(chunks);
- };
+ it("runs the gate BEFORE installing the compressor", async () => {
+ // Ordering is not cosmetic: `apk add zstd` costs ~20s per helper and needs
+ // network egress, so paying it for a capture that cannot produce anything is
+ // pure latency on the failure path.
+ const cmd = await capturedCmd("zstd");
+ expect(cmd.indexOf("ls -A /mnt")).toBeLessThan(cmd.indexOf("apk add"));
+ });
+});
+
+describe("the gate refuses an empty mount and passes a populated one", () => {
+ /** The gate as generated, with /mnt pointed at a real directory. */
+ const gateFor = (dir: string) =>
+ [
+ `SRC='pgdata-0'`,
+ `[ -n "$(ls -A ${dir} 2>/dev/null)" ] || { echo "openship: backup source $SRC is empty` +
+ ` or missing on this host" >&2; exit 91; }`,
+ `tar -c -C ${dir} . | wc -c`,
+ ].join("\n");
- it("captures empty named and bind sources alongside a populated sibling", async () => {
- const service = { ...SERVICE, containerId };
- const archives = new Map();
- for await (const artifact of VolumeCopyProducer.produce(service, executor, {
- compression: "gzip",
- })) {
- const bytes = await collect(artifact.stream);
- archives.set(String(artifact.metadata.volumeSource), bytes);
- }
- expect(archives.size).toBe(3);
- for (const source of [volumes[0], root]) {
- const bytes = archives.get(source)!;
- const listing = spawnSync("tar", ["-tzf", "-"], { input: bytes });
- expect(listing.status, listing.stderr.toString()).toBe(0);
- expect(listing.stdout.toString().trim()).toBe("./");
- }
- const restored = spawnSync("tar", ["-xzOf", "-", "./keep.txt"], {
- input: archives.get(volumes[1]),
- });
- expect(restored.status, restored.stderr.toString()).toBe(0);
- expect(restored.stdout.toString()).toBe("important-data\n");
+ it("exits 91 on an empty directory", () => {
+ const empty = mkdtempSync(join(tmpdir(), "openship-empty-src-"));
+ const run = spawnSync("/bin/sh", ["-c", gateFor(empty)]);
+ expect(run.status).toBe(91);
+ expect(run.stderr.toString()).toContain("empty or missing");
});
- it("rejects a volume absent from this daemon without creating it", async () => {
- const name = `${prefix}-wrong-host`;
- const service = { ...SERVICE, volumes: [`${name}:/data`] };
- await expect(
- executor.streamPath(service, `${name}-0`, { compression: "gzip" }),
- ).rejects.toThrow();
- await expect(runtime.docker.getVolume(name).inspect()).rejects.toMatchObject({
- statusCode: 404,
- });
+ it("exits 91 on a path that does not exist at all", () => {
+ // What the daemon would have CREATED for us, silently.
+ const missing = join(tmpdir(), "openship-definitely-not-here-9f2c1");
+ const run = spawnSync("/bin/sh", ["-c", gateFor(missing)]);
+ expect(run.status).toBe(91);
});
- it("rejects a missing bind path without creating a directory", async () => {
- const missing = join(root, "missing-bind");
- const service = { ...SERVICE, volumes: [`${missing}:/data`] };
- await expect(
- executor.streamPath(service, `${missing}-0`, { compression: "gzip" }),
- ).rejects.toThrow();
- await expect(stat(missing)).rejects.toMatchObject({ code: "ENOENT" });
+ it("passes a directory with content", () => {
+ const full = mkdtempSync(join(tmpdir(), "openship-full-src-"));
+ writeFileSync(join(full, "pg_control"), "real data");
+ const run = spawnSync("/bin/sh", ["-c", gateFor(full)]);
+ expect(run.status, run.stderr?.toString()).toBe(0);
+ // A byte count proves nothing here — tar's default 10240-byte blocking means a
+ // small file archives to exactly the same size as nothing at all, which is the
+ // reason the zero-byte guard could not tell them apart. Assert the CONTENT.
+ const listed = spawnSync("/bin/sh", ["-c", `tar -t -C ${full} -f - < /dev/null; tar -c -C ${full} . | tar -t`]);
+ expect(listed.stdout.toString()).toContain("pg_control");
});
- it("rejects an existing volume whose backing storage is unavailable", async () => {
- const name = volumes[2];
- const service = { ...SERVICE, volumes: [`${name}:/data`] };
- await expect(
- executor.streamPath(service, `${name}-0`, { compression: "gzip" }),
- ).rejects.toThrow();
+ it("shows why the zero-byte check could never have caught this", () => {
+ // An empty tar is a VALID archive of 10240 bytes, so `sizeBytes === 0` passes.
+ // This is the number that made the old behaviour indistinguishable from a real
+ // backup, asserted so nobody re-derives it.
+ const empty = mkdtempSync(join(tmpdir(), "openship-empty-tar-"));
+ const run = spawnSync("/bin/sh", ["-c", `tar -c -C ${empty} . | wc -c`]);
+ expect(run.status).toBe(0);
+ expect(Number(run.stdout.toString().trim())).toBe(10240);
});
});
diff --git a/packages/adapters/test/backup-helper-logging.test.ts b/packages/adapters/test/backup-helper-logging.test.ts
index a6d87db31..2fd798dcf 100644
--- a/packages/adapters/test/backup-helper-logging.test.ts
+++ b/packages/adapters/test/backup-helper-logging.test.ts
@@ -1,6 +1,7 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-import type { ServiceHandle } from "../src/backup/types";
-import { FakeAttachStream, harness } from "./helpers/docker-helper-harness";
+import { describe, expect, it } from "vitest";
+import { readFileSync } from "node:fs";
+import { join, dirname } from "node:path";
+import { fileURLToPath } from "node:url";
/**
* The backup helper streams a volume's archive over `attach()`. With the
@@ -10,45 +11,34 @@ import { FakeAttachStream, harness } from "./helpers/docker-helper-harness";
* volume produced a 12 GB log, so a backup spiked host disk by far more than
* it read and only released it when the helper exited.
*
- * Exercise the executor's actual helper configuration for each codec.
+ * Asserted against the source because the alternative is a full dockerode
+ * double, which would pin far more of the executor's shape than this one
+ * property is worth.
*/
-const attach = vi.hoisted(() => ({ stream: null as FakeAttachStream | null }));
-vi.mock("../src/runtime/docker-exec-stream", async (original) => ({
- ...(await original()),
- startAttachStream: async () => attach.stream!,
-}));
-
-afterEach(() => vi.restoreAllMocks());
-
-const service: ServiceHandle = {
- id: "svc_1",
- projectId: "prj_1",
- name: "db",
- image: "postgres:16",
- env: {},
- volumes: ["pgdata:/var/lib/postgresql/data"],
- containerId: null,
- projectSlug: "shop",
- namespaceVolumes: false,
-};
+const executorSource = readFileSync(
+ join(dirname(fileURLToPath(import.meta.url)), "../src/backup/executors/docker.ts"),
+ "utf8",
+);
describe("backup helper container", () => {
- it.each(["none", "gzip", "zstd"] as const)(
- "keeps %s capture read-only with logging disabled and cleanup owned by the executor",
- async (compression) => {
- attach.stream = new FakeAttachStream();
- const h = harness({ wait: 0 }, () => ({}));
- const executor = await h.executor();
- const { stdout, awaitExit } = await executor.streamPath(service, "pgdata-0", { compression });
- stdout.resume();
- attach.stream.finish();
- await awaitExit;
- expect(h.created.at(-1)?.HostConfig).toMatchObject({
- Mounts: [{ Type: "volume", Source: "pgdata", Target: "/mnt", ReadOnly: true }],
- AutoRemove: false,
- LogConfig: { Type: "none", Config: {} },
- });
- expect(h.removals).toHaveLength(1);
- },
- );
+ it("disables container logging for the archive stream", () => {
+ expect(executorSource).toMatch(/LogConfig:\s*\{\s*Type:\s*"none"/);
+ });
+
+ it("keeps the log config on the same HostConfig that binds the source", () => {
+ // Anchored to the statement that immediately follows the literal, so the
+ // slice stays inside streamPath — `const helper =` moved into the shared
+ // withHelper/handOffHelper wrappers and would now widen this to two methods.
+ const hostConfig = executorSource.slice(
+ executorSource.indexOf("const hostConfig"),
+ executorSource.indexOf("return this.handOffHelper("),
+ );
+ expect(hostConfig).toContain(":/mnt:ro");
+ // AutoRemove must stay OFF: the daemon reaping the helper at exit races
+ // container.wait() (404 on the exit status) and tears down the attach socket
+ // while bytes are still buffered (truncated tar). demuxContainerStream owns
+ // the removal instead, once the archive is fully demuxed.
+ expect(hostConfig).toContain("AutoRemove: false");
+ expect(hostConfig).toMatch(/LogConfig/);
+ });
});
diff --git a/packages/adapters/test/cloud-infra.test.ts b/packages/adapters/test/cloud-infra.test.ts
index 170cdb457..6fede0853 100644
--- a/packages/adapters/test/cloud-infra.test.ts
+++ b/packages/adapters/test/cloud-infra.test.ts
@@ -23,7 +23,7 @@ describe("managed route cleanup", () => {
await h.infra.removeRoute("app.opsh.io");
expect(h.pages.delete).toHaveBeenCalledWith("app");
});
- it.each(["source_vm_id", "exported_path"])("refuses cleanup after %s changes", async field => {
+ it.each(["source_workspace_id", "exported_path"])("refuses cleanup after %s changes", async field => {
h.records.get("app")![field] = "another-owner";
await expect(h.infra.removeRoute("app.opsh.io")).rejects.toThrow("not owned");
expect(h.pages.delete).not.toHaveBeenCalled();
diff --git a/packages/adapters/test/cloud-project-route-cleanup.test.ts b/packages/adapters/test/cloud-project-route-cleanup.test.ts
index 98284162c..c2d1b7605 100644
--- a/packages/adapters/test/cloud-project-route-cleanup.test.ts
+++ b/packages/adapters/test/cloud-project-route-cleanup.test.ts
@@ -17,7 +17,7 @@ describe("project-scoped route cleanup", () => {
it.each(["workspace-one", "another-workspace"])(
"preserves a different project's Page on %s while explicit removal stays strict",
async (workspaceId) => {
- h.records.get("app")!.source_vm_id = workspaceId;
+ h.records.get("app")!.source_workspace_id = workspaceId;
h.records.get("app")!.exported_path =
`${cloudDockerProjectPaths("active-project").routes}/app`;
const activePage = structuredClone(h.records.get("app"));
@@ -61,13 +61,13 @@ describe("project-scoped route cleanup", () => {
});
it.each([
- { source_vm_id: "another-workspace" },
+ { source_workspace_id: "another-workspace" },
{ exported_path: undefined },
{ exported_path: "/unrecognised-owner/app" },
{ exported_path: `${cloudDockerProjectPaths("active-project").routes}/wrong-slug` },
{
exported_path: `${cloudDockerProjectPaths("active-project").routes}/app`,
- source_vm_id: null,
+ source_workspace_id: null,
},
])("blocks deletion when foreign ownership is unproven: %j", async (changes) => {
Object.assign(h.records.get("app")!, changes);
diff --git a/packages/adapters/test/helpers/docker-helper-harness.ts b/packages/adapters/test/helpers/docker-helper-harness.ts
index fd82d80a5..54acc5406 100644
--- a/packages/adapters/test/helpers/docker-helper-harness.ts
+++ b/packages/adapters/test/helpers/docker-helper-harness.ts
@@ -135,7 +135,6 @@ export function harness(
const runtime = await DockerRuntime.create();
// ensureImage → runtime.pullImage; never touch a registry in a unit test.
(runtime as unknown as { pullImage: () => Promise }).pullImage = async () => {};
- runtime.docker.getVolume = (() => ({ inspect: async () => ({}) })) as never;
runtime.docker.createContainer = (async (opts: Record) => {
created.push(opts);
return helper;
diff --git a/packages/adapters/test/managed-routing-fixture.ts b/packages/adapters/test/managed-routing-fixture.ts
index 6123076b7..5521a4611 100644
--- a/packages/adapters/test/managed-routing-fixture.ts
+++ b/packages/adapters/test/managed-routing-fixture.ts
@@ -26,8 +26,8 @@ export function managedRoutingFixture(): {
if (!records.has(slug)) throw new NotFoundError("missing Page");
return { page: records.get(slug)! };
}),
- create: vi.fn(async (input: { slug: string; domain: string; path: string; vm_id: string }) => {
- const page = { id: records.size + 1, slug: input.slug, domain: input.domain, namespace, source_vm_id: input.vm_id, exported_path: input.path, url: `https://${input.slug}.${input.domain}` };
+ create: vi.fn(async (input: { slug: string; domain: string; path: string; workspace_id: string }) => {
+ const page = { id: records.size + 1, slug: input.slug, domain: input.domain, namespace, source_workspace_id: input.workspace_id, exported_path: input.path, url: `https://${input.slug}.${input.domain}` };
records.set(input.slug, page); return { success: true, page };
}),
deploy: vi.fn(async () => ({ success: true })),
@@ -51,7 +51,7 @@ export function managedRoutingFixture(): {
{ hostname: `${page.slug}.${page.domain}`, namespace: page.namespace, owner_type: "page", owner_id: page.id, is_custom: false },
...(page.custom_domain ? [{ hostname: page.custom_domain, namespace: page.namespace, owner_type: "page", owner_id: page.id, is_custom: true }] : []),
]) })) };
- const client = { pages, routes, domain, vm: vi.fn(() => workspace) } as unknown as Oblien;
+ const client = { pages, routes, domain, workspace: vi.fn(() => workspace) } as unknown as Oblien;
const infra = new CloudInfraProvider(client, { namespace, scope });
return { namespace, workspaceId, projectId, paths, records, pages, executor, scope, workspace, routes, domain, client, infra };
}
diff --git a/packages/adapters/test/oblien-routing.test.ts b/packages/adapters/test/oblien-routing.test.ts
index dbaf58071..2f29cc418 100644
--- a/packages/adapters/test/oblien-routing.test.ts
+++ b/packages/adapters/test/oblien-routing.test.ts
@@ -11,7 +11,7 @@ describe("compileRoutingToOblien", () => {
{ source: "/(.*)", destination: "/index.html" },
],
},
- { staticPage: "my-frontend", backend: { vm: "ws_backend", port: 3000 } },
+ { staticPage: "my-frontend", backend: { workspace: "ws_backend", port: 3000 } },
);
expect(input.static).toEqual({ page: "my-frontend" });
@@ -19,7 +19,7 @@ describe("compileRoutingToOblien", () => {
expect(input.routes).toEqual([
{
match: { path: "/api/", type: "prefix" },
- action: { kind: "proxy", vm: "ws_backend", port: 3000 },
+ action: { kind: "proxy", workspace: "ws_backend", port: 3000 },
},
]);
});
@@ -27,27 +27,27 @@ describe("compileRoutingToOblien", () => {
it("builds a COMPLETE table for the workspace topology (frontend + backend both workspaces)", () => {
const input = compileRoutingToOblien(
{ rewrites: [{ source: "/api/(.*)", destination: "/api/index.js" }] },
- { root: { vm: "ws_frontend", port: 8080 }, backend: { vm: "ws_backend", port: 3000 } },
+ { root: { workspace: "ws_frontend", port: 8080 }, backend: { workspace: "ws_backend", port: 3000 } },
);
expect(input.static).toBeUndefined();
// /api proxies to the backend; `/` catch-all proxies to the frontend LAST.
expect(input.routes).toEqual([
- { match: { path: "/api/", type: "prefix" }, action: { kind: "proxy", vm: "ws_backend", port: 3000 } },
- { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "ws_frontend", port: 8080 } },
+ { match: { path: "/api/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_backend", port: 3000 } },
+ { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_frontend", port: 8080 } },
]);
});
it("builds a server-only table (root workspace backs everything)", () => {
- const input = compileRoutingToOblien({}, { root: { vm: "ws_api", port: 8080 } });
+ const input = compileRoutingToOblien({}, { root: { workspace: "ws_api", port: 8080 } });
expect(input.routes).toEqual([
- { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "ws_api", port: 8080 } },
+ { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_api", port: 8080 } },
]);
});
it("proxies a full-URL rewrite to a literal origin (not the owned workspace)", () => {
const input = compileRoutingToOblien(
{ rewrites: [{ source: "/proxy/(.*)", destination: "https://api.example.com/fixed" }] },
- { backend: { vm: "ws_backend", port: 3000 } },
+ { backend: { workspace: "ws_backend", port: 3000 } },
);
expect(input.routes).toEqual([
{
@@ -80,13 +80,13 @@ describe("compileRoutingToOblien", () => {
{ source: "/see", destination: "/other", statusCode: 303 }, // Oblien has no 303 → 307
],
},
- { root: { vm: "ws_app", port: 8080 } },
+ { root: { workspace: "ws_app", port: 8080 } },
);
expect(input.routes).toEqual([
{ match: { path: "/old", type: "exact" }, action: { kind: "redirect", status: 308, to: "/new" } },
{ match: { path: "/tmp", type: "exact" }, action: { kind: "redirect", status: 307, to: "/temp" } },
{ match: { path: "/see", type: "exact" }, action: { kind: "redirect", status: 307, to: "/other" } },
- { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "ws_app", port: 8080 } },
+ { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_app", port: 8080 } },
]);
});
@@ -101,7 +101,7 @@ describe("compileRoutingToOblien", () => {
{ source: "/docs/(.*)", destination: "/documentation/$1" },
],
},
- { root: { vm: "ws_app", port: 8080 } },
+ { root: { workspace: "ws_app", port: 8080 } },
);
expect(input.routes).toEqual([
{
@@ -112,7 +112,7 @@ describe("compileRoutingToOblien", () => {
match: { path: "/docs/(.*)", type: "wildcard" },
action: { kind: "redirect", status: 308, to: "/documentation/$1" },
},
- { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "ws_app", port: 8080 } },
+ { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_app", port: 8080 } },
]);
});
@@ -155,7 +155,7 @@ describe("compileRoutingToOblien", () => {
rewrites: [{ source: "/evil; } location / { proxy_pass http://x; }", destination: "/api" }],
redirects: [{ source: "/r", destination: "/y; return 200 'pwned'" }],
},
- { backend: { vm: "ws_backend", port: 3000 } },
+ { backend: { workspace: "ws_backend", port: 3000 } },
);
expect(input.routes).toEqual([]);
});
@@ -165,6 +165,6 @@ describe("compileRoutingToOblien", () => {
describe("Cloud static fallback", () => {
it.each([undefined, true, false])("carries the static setting to the provider: %s", (spaFallback) => {
expect(compileRoutingToOblien({ spaFallback }, { staticPage: "site" }).spa).toBe(spaFallback);
- expect(compileRoutingToOblien({ spaFallback }, { root: { vm: "app", port: 8080 } })).not.toHaveProperty("spa");
+ expect(compileRoutingToOblien({ spaFallback }, { root: { workspace: "app", port: 8080 } })).not.toHaveProperty("spa");
});
});
diff --git a/packages/adapters/tsconfig.json b/packages/adapters/tsconfig.json
index cc2e306d2..a22f17e3d 100644
--- a/packages/adapters/tsconfig.json
+++ b/packages/adapters/tsconfig.json
@@ -6,6 +6,6 @@
"types": ["node"],
"outDir": "dist"
},
- "include": ["src/**/*.ts", "scripts/verify-cloud-docker.ts", "scripts/verify-cloud-isolation.ts"],
+ "include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist"]
}
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..61fa380d0 100644
--- a/packages/contracts/src/platform-migration.ts
+++ b/packages/contracts/src/platform-migration.ts
@@ -62,7 +62,6 @@ export const PlatformMigrationReviewSchema = Type.Object(
{
draftId: id,
targetServerId: id,
- projectName: Type.Optional(Type.String({ minLength: 1, maxLength: 100 })),
services: Type.Array(serviceChoice, { minItems: 1, maxItems: 50 }),
},
{ additionalProperties: false },
@@ -72,7 +71,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/project-routing.ts b/packages/contracts/src/project-routing.ts
index ff7ca928f..f5ae5c2fc 100644
--- a/packages/contracts/src/project-routing.ts
+++ b/packages/contracts/src/project-routing.ts
@@ -37,13 +37,6 @@ export const ProjectRoutingRetrySchema = Type.Object({
export type ProjectRoutingRetry = Static;
const list = Type.Optional(Type.Array(Type.String()));
export const RouteRuleSpecSchema = Type.Object({
- response: Type.Optional(Type.Object({
- match: Type.Union([Type.Literal("exact"), Type.Literal("prefix")]),
- status: Type.Integer({ minimum: 200, maximum: 599 }),
- contentType: Type.String(), body: Type.String(),
- headers: Type.Record(Type.String(), Type.String()),
- methods: Type.Array(Type.String()),
- })),
rateLimit: Type.Optional(Type.Object({ rps: Type.Number(), burst: Type.Number(), key: Type.Optional(Type.Literal("ip")), status: Type.Optional(Type.Number()) })),
ban: Type.Optional(Type.Object({ ips: list, cidrs: list, countries: list, userAgents: list, emptyUserAgent: Type.Optional(Type.Boolean()) })),
access: Type.Optional(Type.Object({ allowCidrs: list, denyCidrs: list, allowCountries: list, methods: list })),
@@ -54,7 +47,6 @@ export const RouteRuleSchema = Type.Object({
id: Type.String(), organizationId: Type.String(), projectId: Type.String(),
domainId: nullableString, pathPrefix: nullableString, spec: RouteRuleSpecSchema,
enabled: Type.Boolean(), createdAt: Type.String(), updatedAt: Type.String(),
- edgeApplied: Type.Optional(Type.Boolean({ description: "Mutation result: false means saved but edge publication is pending." })),
});
export type RouteRule = Static;
export const RouteRuleInputSchema = Type.Object({
@@ -104,7 +96,7 @@ export const ProjectRoutingSchemas = {
listRouteRules: { action: "read", output: Type.Array(RouteRuleSchema) },
createRouteRule: { action: "write", input: RouteRuleInputSchema, output: RouteRuleSchema },
updateRouteRule: { action: "write", input: UpdateRouteRuleInputSchema, output: RouteRuleSchema },
- removeRouteRule: { action: "write", input: ResourceIdSchema, output: Type.Object({ success: Type.Literal(true), edgeApplied: Type.Optional(Type.Boolean()) }) },
+ removeRouteRule: { action: "write", input: ResourceIdSchema, output: Type.Object({ success: Type.Literal(true) }) },
getIncidents: { action: "read", output: ProjectIncidentsSchema },
connectDomain: { action: "write", input: ConnectProjectDomainInputSchema, output: Type.Composite([CreateDomainResultSchema, Type.Object({ success: Type.Literal(true) })]) },
} as const satisfies Record;
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/edge-response.test.ts b/packages/core/src/edge-response.test.ts
deleted file mode 100644
index 6664326c1..000000000
--- a/packages/core/src/edge-response.test.ts
+++ /dev/null
@@ -1,76 +0,0 @@
-import { describe, expect, it } from "vitest";
-import {
- normalizeEdgeResponse,
- normalizeResponsePath,
- EDGE_RESPONSE_MAX_BYTES,
-} from "./edge-response";
-
-describe("edge response input", () => {
- it("preserves literal content and normalizes headers without interpreting code", () => {
- const body = '\nمرحبا';
- expect(normalizeEdgeResponse({ body, headers: { "X-Example": "$host" } })).toEqual({
- match: "exact",
- status: 200,
- contentType: "text/plain; charset=utf-8",
- body,
- headers: { "x-example": "$host" },
- methods: ["GET", "HEAD"],
- });
- });
- it("rejects header injection, duplicate case variants, and protocol-controlled headers", () => {
- for (const headers of [
- { "X-Test": "ok\r\nInjected: yes" },
- { "X-Test\n": "bad" },
- { "Content-Length": "500" },
- { "Transfer-Encoding": "chunked" },
- { "Content-Type": "text/html" },
- { "X-Test": "one", "x-test": "two" },
- ]) {
- expect(() => normalizeEdgeResponse({ headers })).toThrow();
- }
- expect(() => normalizeEdgeResponse({ contentType: "text/html\r\nInjected: true" })).toThrow();
- expect(() =>
- normalizeEdgeResponse({ contentType: `text/plain; note=${"ع".repeat(128)}` }),
- ).toThrow();
- });
- it("bounds UTF-8 bytes without truncating the response", () => {
- expect(normalizeEdgeResponse({ body: "a".repeat(EDGE_RESPONSE_MAX_BYTES) }).body).toHaveLength(
- EDGE_RESPONSE_MAX_BYTES,
- );
- expect(() => normalizeEdgeResponse({ body: "ع".repeat(EDGE_RESPONSE_MAX_BYTES) })).toThrow(
- /64 KiB/,
- );
- });
- it("enforces no-content statuses and valid final response codes", () => {
- for (const status of [204, 205, 304]) {
- expect(normalizeEdgeResponse({ status }).body).toBe("");
- expect(() => normalizeEdgeResponse({ status, body: "not empty" })).toThrow(/empty/);
- }
- for (const status of [101, 600, 200.5, "200"])
- expect(() => normalizeEdgeResponse({ status })).toThrow();
- expect(normalizeEdgeResponse({ status: 404, body: "Missing" }).status).toBe(404);
- });
- it("rejects misspelled methods instead of silently matching all traffic", () => {
- expect(() => normalizeEdgeResponse({ methods: ["GTE"] })).toThrow();
- expect(normalizeEdgeResponse({ methods: [] }).methods).toEqual([]);
- });
- it("canonicalizes encoded paths and protects platform endpoints", () => {
- expect(normalizeResponsePath("/r%C3%A9ponse")).toBe("/réponse");
- expect(normalizeResponsePath("/.well-known/assetlinks.json")).toBe(
- "/.well-known/assetlinks.json",
- );
- for (const path of [
- "x",
- "/x?y=1",
- "/x#y",
- "/x/../y",
- "//x",
- "/x\\y",
- "/%ZZ",
- "/_openship/auth",
- "/.well-known/acme-challenge/token",
- ]) {
- expect(() => normalizeResponsePath(path)).toThrow();
- }
- });
-});
diff --git a/packages/core/src/edge-response.ts b/packages/core/src/edge-response.ts
deleted file mode 100644
index c450a2233..000000000
--- a/packages/core/src/edge-response.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import { ValidationError } from "./errors";
-
-export const EDGE_RESPONSE_MAX_BYTES = 64 * 1024;
-export const EDGE_RESPONSE_MAX_HEADERS = 32;
-export const EDGE_RESPONSE_MAX_ROUTES = 64;
-export const EDGE_RESPONSE_METHODS = [
- "GET",
- "HEAD",
- "POST",
- "PUT",
- "PATCH",
- "DELETE",
- "OPTIONS",
-] as const;
-
-/** A literal response, served after the domain's access policies. Never executable code. */
-export interface EdgeResponse {
- match: "exact" | "prefix";
- status: number;
- contentType: string;
- body: string;
- headers: Record;
- /** An empty list matches all supported methods. GET also matches HEAD. */
- methods: string[];
-}
-
-const HEADER_NAME = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;
-const CONTROL = /[\u0000-\u001f\u007f]/;
-const MANAGED_HEADERS = new Set([
- "content-type",
- "content-length",
- "content-encoding",
- "transfer-encoding",
- "connection",
- "keep-alive",
- "proxy-authenticate",
- "proxy-authorization",
- "te",
- "trailer",
- "upgrade",
- "x-accel-redirect",
-]);
-const bytes = (value: string) => new TextEncoder().encode(value).length;
-
-export function normalizeResponsePath(input: unknown): string {
- if (typeof input !== "string" || !input.startsWith("/"))
- throw new ValidationError("Enter a path starting with /.");
- let path: string;
- try {
- path = decodeURIComponent(input.trim());
- } catch {
- throw new ValidationError("Enter a valid URL path.");
- }
- if (
- bytes(path) > 512 ||
- /[\u0000-\u0020\u007f?#\\%]/.test(path) ||
- path.includes("//") ||
- path.split("/").some((segment) => segment === "." || segment === "..")
- )
- throw new ValidationError("Use a path without query parameters, fragments, or dot segments.");
- if (
- /^\/(?:_openship|\.openship)(?:\/|$)/.test(path) ||
- /^\/\.well-known\/acme-challenge(?:\/|$)/.test(path)
- )
- throw new ValidationError("This path is reserved for domain verification or platform routes.");
- return path;
-}
-
-/** Shared by the editor and API. Invalid content must fail, never silently truncate. */
-export function normalizeEdgeResponse(input: unknown): EdgeResponse {
- if (!input || typeof input !== "object" || Array.isArray(input))
- throw new ValidationError("Enter a static response.");
- const value = input as Record;
- const match = value.match ?? "exact";
- if (match !== "exact" && match !== "prefix")
- throw new ValidationError("Choose exact path or path prefix.");
- const status = value.status ?? 200;
- if (typeof status !== "number" || !Number.isInteger(status) || status < 200 || status > 599)
- throw new ValidationError("Response status must be a whole number from 200 to 599.");
- const body = value.body ?? "";
- if (typeof body !== "string" || bytes(body) > EDGE_RESPONSE_MAX_BYTES)
- throw new ValidationError("Response content must be text of at most 64 KiB.");
- if ([204, 205, 304].includes(status) && body !== "")
- throw new ValidationError("Statuses 204, 205, and 304 require an empty response body.");
- const contentType = value.contentType ?? "text/plain; charset=utf-8";
- if (
- typeof contentType !== "string" ||
- bytes(contentType) > 256 ||
- CONTROL.test(contentType) ||
- !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+(?:\s*;[^\r\n]*)?$/.test(contentType)
- )
- throw new ValidationError(
- "Enter a valid content type, such as text/plain or application/json.",
- );
- const entries =
- value.headers === undefined
- ? []
- : value.headers && typeof value.headers === "object" && !Array.isArray(value.headers)
- ? Object.entries(value.headers)
- : null;
- if (!entries || entries.length > EDGE_RESPONSE_MAX_HEADERS)
- throw new ValidationError("A response can contain at most 32 headers.");
- const headers: Record = {};
- let headerBytes = 0;
- for (const [name, headerValue] of entries) {
- const key = name.toLowerCase();
- if (name.length > 128 || !HEADER_NAME.test(name) || MANAGED_HEADERS.has(key))
- throw new ValidationError(
- `Header ${name.slice(0, 128)} is invalid or managed by the edge. Use the content type field for Content-Type.`,
- );
- if (Object.hasOwn(headers, key)) throw new ValidationError(`Header ${name} is repeated.`);
- if (typeof headerValue !== "string" || CONTROL.test(headerValue) || bytes(headerValue) > 2048)
- throw new ValidationError(`Header ${name} must be a single line of at most 2 KiB.`);
- headerBytes += bytes(name) + bytes(headerValue);
- if (headerBytes > 8192) throw new ValidationError("Response headers must fit within 8 KiB.");
- Object.defineProperty(headers, key, {
- value: headerValue,
- enumerable: true,
- configurable: true,
- writable: true,
- });
- }
- const methods = value.methods ?? ["GET", "HEAD"];
- if (
- !Array.isArray(methods) ||
- methods.length > EDGE_RESPONSE_METHODS.length ||
- methods.some(
- (method) =>
- typeof method !== "string" ||
- !(EDGE_RESPONSE_METHODS as readonly string[]).includes(method),
- )
- )
- throw new ValidationError("Choose supported HTTP request methods.");
- return { match, status, body, contentType, headers, methods: [...new Set(methods)] };
-}
diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.ts
index 0974f072b..b9b9067ef 100644
--- a/packages/core/src/errors.ts
+++ b/packages/core/src/errors.ts
@@ -72,7 +72,6 @@ export class HostUnreachableError extends AppError {
* Codes:
* PORT_IN_USE - target port is occupied by another process
* FOREIGN_COMPOSE_STACK - an unowned same-project Compose stack exists on the target
- * SERVICE_CONTAINER_CONFLICT - more than one live container matches an active service
*/
export class DeployError extends AppError {
constructor(
diff --git a/packages/core/src/host-channel.ts b/packages/core/src/host-channel.ts
index 1eed55f40..d202eac67 100644
--- a/packages/core/src/host-channel.ts
+++ b/packages/core/src/host-channel.ts
@@ -33,7 +33,7 @@ export const HOST_CHANNEL_UNAFFECTED =
/** Everything that genuinely stops working. Verified against the call sites, not guessed. */
export const HOST_CHANNEL_BLOCKED: readonly string[] = [
"the host terminal, host system info and host port scans",
- "taking over :80/:443 from a proxy OpenShip didn't start",
+ "taking over :80/:443 from a proxy Openship didn't start",
"installing or updating the mail engine",
"deploying a catalog app that needs a generated config file on the host (Supabase's kong.yml, say)",
];
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..29e6ef09c 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";
@@ -145,4 +144,3 @@ export * from "./service-env-layers";
export * from "./locale";
export * from "./concurrency";
export * from "./migration-links";
-export * from "./edge-response";
diff --git a/packages/core/src/pricing/README.md b/packages/core/src/pricing/README.md
index d8c27e084..030d2ffe2 100644
--- a/packages/core/src/pricing/README.md
+++ b/packages/core/src/pricing/README.md
@@ -14,8 +14,8 @@ payment settlement, resource admission, metering and paid coverage.
| Pro | $47 | $468 | $39 | 4 | 16 GiB | 250 GiB | 1 |
| Scale | $119 | $1,188 | $99 | 8 | 32 GiB | 600 GiB | 1 |
-Annual is charged in full upfront. The dashboard and website display the full annual
-price per year with the free-month savings below; the selected interval is sent through checkout.
+Annual is charged in full upfront. The dashboard displays the monthly equivalent
+and full annual charge together; the selected interval is sent through checkout.
Manage remains monthly, separately from Cloud compute. Annual purchases require
Oblien's `resellerSubscriptionIntervals` capability to include `yearly`.
diff --git a/packages/core/src/pricing/locales/en.json b/packages/core/src/pricing/locales/en.json
index a17513c74..fca460ce1 100644
--- a/packages/core/src/pricing/locales/en.json
+++ b/packages/core/src/pricing/locales/en.json
@@ -76,7 +76,7 @@
},
"ui": {
"perMonth": "/mo",
- "perYear": "/year",
+ "perYear": "/yr",
"custom": "Custom",
"free": "Free",
"unlimited": "Unlimited",
diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts
index 5a86399ed..6698c6917 100644
--- a/packages/core/src/types.ts
+++ b/packages/core/src/types.ts
@@ -491,8 +491,6 @@ export function mergeAdvanced(
* upstream/LB weights, …) as a pure shape-widening — no migration (JSONB).
*/
export type RouteRuleSpec = {
- /** Domain-scoped virtual route. Access rules are evaluated independently first. */
- response?: import("./edge-response").EdgeResponse;
/**
* Per-client rate limit (fixed 1s window, keyed by client IP). Omit = unlimited.
* `status` overrides the 429 response code. Runs alongside (does not replace)
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/repos/route-rule-response.test.ts b/packages/db/src/repos/route-rule-response.test.ts
deleted file mode 100644
index 06d1e8b4d..000000000
--- a/packages/db/src/repos/route-rule-response.test.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-import { afterAll, beforeAll, describe, expect, it } from "vitest";
-import { normalizeEdgeResponse, EDGE_RESPONSE_MAX_ROUTES } from "@repo/core";
-import { createDatabase, createRepositories, schema, type DatabaseConnection } from "../factory";
-import { createEncryption } from "../encryption";
-
-describe("static response route persistence", () => {
- let connection: DatabaseConnection;
- let repos: ReturnType;
- let projectId: string;
- let domainId: string;
- beforeAll(async () => {
- connection = await createDatabase({ driver: "pglite", dataDir: "memory://" });
- repos = createRepositories(connection.db, createEncryption("response-route-test"));
- await connection.db
- .insert(schema.organization)
- .values({ id: "response-org", name: "Responses" });
- const group = await repos.projectGroup.create({
- organizationId: "response-org",
- name: "Routes",
- slug: "routes",
- });
- const project = await repos.project.create({
- organizationId: "response-org",
- groupId: group.id,
- name: "Routes",
- slug: "routes",
- });
- projectId = project.id;
- domainId = (
- await repos.domain.create({ projectId, hostname: "response.test", domainType: "custom" })
- ).id;
- });
- afterAll(async () => {
- await connection?.close();
- });
- const input = (pathPrefix: string | null, match: "exact" | "prefix" = "exact") => ({
- organizationId: "response-org",
- projectId,
- domainId,
- pathPrefix,
- spec: { response: normalizeEdgeResponse({ match, body: "original" }) },
- enabled: true,
- });
- it("serializes concurrent duplicate creates while permitting different match modes", async () => {
- const attempts = await Promise.allSettled([
- repos.routeRule.create(input("/race")),
- repos.routeRule.create(input("/race")),
- ]);
- expect(attempts.filter((result) => result.status === "fulfilled")).toHaveLength(1);
- expect(attempts.find((result) => result.status === "rejected")).toMatchObject({
- reason: { code: "EDGE_RESPONSE_EXISTS" },
- });
- await expect(repos.routeRule.create(input("/race", "prefix"))).resolves.toMatchObject({
- pathPrefix: "/race",
- });
- });
- it("preserves response fields and prevents moving an existing route onto an occupied path", async () => {
- const first = await repos.routeRule.create(input("/first"));
- const second = await repos.routeRule.create(input("/second"));
- await repos.routeRule.update(first.id, { enabled: false });
- expect(await repos.routeRule.get(first.id)).toMatchObject({ enabled: false, spec: first.spec });
- await expect(repos.routeRule.update(second.id, { pathPrefix: "/first" })).rejects.toMatchObject(
- { code: "EDGE_RESPONSE_EXISTS" },
- );
- expect(await repos.routeRule.get(second.id)).toMatchObject({ pathPrefix: "/second" });
- await repos.routeRule.removeForProject("another-project", first.id);
- expect(await repos.routeRule.get(first.id)).toBeDefined();
- await repos.routeRule.removeForProject(projectId, first.id);
- expect(await repos.routeRule.get(first.id)).toBeUndefined();
- });
- it("enforces the per-domain bound under concurrent saves and allows editing a full domain", async () => {
- const boundedDomain = await repos.domain.create({
- projectId,
- hostname: "bounded.test",
- domainType: "custom",
- });
- for (let i = 0; i < EDGE_RESPONSE_MAX_ROUTES - 1; i++) {
- await repos.routeRule.create({
- ...input(`/bounded/${i}`),
- domainId: boundedDomain.id,
- enabled: false,
- });
- }
- const attempts = await Promise.allSettled(
- [0, 1].map((i) =>
- repos.routeRule.create({
- ...input(`/last/${i}`),
- domainId: boundedDomain.id,
- }),
- ),
- );
- expect(attempts.filter((result) => result.status === "fulfilled")).toHaveLength(1);
- expect(attempts.find((result) => result.status === "rejected")).toMatchObject({
- reason: { code: "EDGE_RESPONSE_LIMIT" },
- });
- const rows = await repos.routeRule.listByDomain(boundedDomain.id);
- expect(rows).toHaveLength(EDGE_RESPONSE_MAX_ROUTES);
- await expect(repos.routeRule.update(rows[0]!.id, { enabled: true })).resolves.toBeUndefined();
- const other = await repos.routeRule.create(input("/move-to-full"));
- await expect(
- repos.routeRule.update(other.id, { domainId: boundedDomain.id }),
- ).rejects.toMatchObject({ code: "EDGE_RESPONSE_LIMIT" });
- expect((await repos.routeRule.get(other.id))?.domainId).toBe(domainId);
- });
-});
diff --git a/packages/db/src/repos/route-rule.repo.ts b/packages/db/src/repos/route-rule.repo.ts
index 982506100..8adeda8a0 100644
--- a/packages/db/src/repos/route-rule.repo.ts
+++ b/packages/db/src/repos/route-rule.repo.ts
@@ -1,5 +1,5 @@
-import { eq, and, inArray, or, ne, isNull, sql } from "drizzle-orm";
-import { generateId, AppError, EDGE_RESPONSE_MAX_ROUTES } from "@repo/core";
+import { eq, and, inArray, or } from "drizzle-orm";
+import { generateId } from "@repo/core";
import type { Database } from "../client";
import { project, routeRule } from "../schema";
import { withProjectConfigurationWrite } from "./project-work-admission";
@@ -9,26 +9,6 @@ import { withProjectConfigurationWrite } from "./project-work-admission";
export type RouteRule = typeof routeRule.$inferSelect;
export type NewRouteRule = typeof routeRule.$inferInsert;
-/** The project write lock also makes duplicate-path checks safe under concurrent saves. */
-async function assertResponseSlot(db: Pick, data: NewRouteRule, ignoreId?: string) {
- const response = data.spec?.response;
- if (!response) return;
- const responses = await db.select({
- pathPrefix: routeRule.pathPrefix,
- match: sql`coalesce(${routeRule.spec}->'response'->>'match', 'exact')`,
- }).from(routeRule).where(and(
- eq(routeRule.projectId, data.projectId),
- data.domainId ? eq(routeRule.domainId, data.domainId) : isNull(routeRule.domainId),
- sql`${routeRule.spec}->'response' is not null`,
- ignoreId ? ne(routeRule.id, ignoreId) : undefined,
- )).limit(EDGE_RESPONSE_MAX_ROUTES);
- const duplicate = responses.some((existing) =>
- (existing.pathPrefix || "/") === (data.pathPrefix || "/") && existing.match === response.match);
- if (duplicate) throw new AppError("A static response already exists for this domain, path, and match type. Edit the existing route.", 409, "EDGE_RESPONSE_EXISTS");
- if (responses.length >= EDGE_RESPONSE_MAX_ROUTES)
- throw new AppError("A domain can have at most 64 static responses. Remove a route before adding another.", 409, "EDGE_RESPONSE_LIMIT");
-}
-
// ─── Repository ──────────────────────────────────────────────────────────────
export function createRouteRuleRepo(db: Database) {
@@ -55,20 +35,16 @@ export function createRouteRuleRepo(db: Database) {
async create(data: Omit): Promise {
const id = generateId("rr");
const row = { id, ...data };
- await withProjectConfigurationWrite(db, eq(project.id, data.projectId), async (tx) => {
- await assertResponseSlot(tx, row);
- await tx.insert(routeRule).values(row);
- });
+ await withProjectConfigurationWrite(db, eq(project.id, data.projectId), async (tx) => tx.insert(routeRule).values(row));
return { ...row, createdAt: new Date(), updatedAt: new Date() } as RouteRule;
},
async update(id: string, data: Partial) {
const predicate = or(ownerPredicate(id), data.projectId ? eq(project.id, data.projectId) : undefined)!;
- await withProjectConfigurationWrite(db, predicate, async (tx) => {
- const [existing] = await tx.select().from(routeRule).where(eq(routeRule.id, id)).limit(1);
- if (existing) await assertResponseSlot(tx, { ...existing, ...data }, id);
- await tx.update(routeRule).set({ ...data, updatedAt: new Date() }).where(eq(routeRule.id, id));
- });
+ await withProjectConfigurationWrite(db, predicate, async (tx) => tx
+ .update(routeRule)
+ .set({ ...data, updatedAt: new Date() })
+ .where(eq(routeRule.id, id)));
},
async remove(id: string) {
diff --git a/packages/db/src/schema/docker-migration.ts b/packages/db/src/schema/docker-migration.ts
index ff7579ac4..390b044e5 100644
--- a/packages/db/src/schema/docker-migration.ts
+++ b/packages/db/src/schema/docker-migration.ts
@@ -25,12 +25,8 @@ export interface DockerMigrationRecovery {
planEnc: string;
connectionId: string;
projects: Record;
- /** Provider service → native service row, all within the imported project. */
- services?: Record;
completed: string[];
deployments?: Record;
- /** All deployments admitted by this import, including database-only restores. */
- ownedDeploymentIds?: string[];
cleanupPending?: boolean;
sshKeyId?: string;
sshPrivateKeyEnc?: string;
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/openship/package.json b/packages/openship/package.json
index 2fc5e0be4..dc7ee887a 100644
--- a/packages/openship/package.json
+++ b/packages/openship/package.json
@@ -1,6 +1,6 @@
{
"name": "openship",
- "version": "0.9.12",
+ "version": "0.9.11",
"license": "Apache-2.0",
"repository": {
"type": "git",
diff --git a/packages/platform/package.json b/packages/platform/package.json
index a4f78b9ea..deacb4a64 100644
--- a/packages/platform/package.json
+++ b/packages/platform/package.json
@@ -1,6 +1,6 @@
{
"name": "@repo/platform",
- "version": "0.9.12",
+ "version": "0.9.11",
"private": true,
"type": "module",
"main": "src/index.ts",
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/config/env.ts b/packages/platform/src/engine/config/env.ts
index 1be661c5a..fe6eb4b37 100644
--- a/packages/platform/src/engine/config/env.ts
+++ b/packages/platform/src/engine/config/env.ts
@@ -375,8 +375,8 @@ const envSchema = z.object({
OBLIEN_CLIENT_ID: z.string().optional(),
OBLIEN_CLIENT_SECRET: z.string().optional(),
/** Control-plane endpoint. Override only for an Oblien staging installation. */
- OBLIEN_API_URL: z.url().optional(),
- OBLIEN_RUNTIME_URL: z.url().default("https://vm.oblien.com"),
+ OBLIEN_API_URL: z.url().default("https://api.oblien.com"),
+ OBLIEN_RUNTIME_URL: z.url().default("https://workspace.oblien.com"),
/** Optional published software preset for NEW managed Docker workspaces. */
OBLIEN_DOCKER_PRESET: z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/).optional(),
/**
diff --git a/packages/platform/src/engine/lib/auth.ts b/packages/platform/src/engine/lib/auth.ts
index b51d75b0c..dd1d25a48 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";
@@ -18,7 +17,6 @@ import {
resetPasswordOtpEmail,
verifyEmailTemplate,
verifyOtpEmailTemplate,
- existingAccountEmail,
} from "./email-templates";
import { provisionUser } from "./provision-user";
import { oidcOAuthPlugin } from "./oidc";
@@ -178,23 +176,6 @@ export const auth = betterAuth({
configured, so a platform-mailbox instance isn't locked out by a
transient mail-server fault mid-signup. */
requireEmailVerification: isSaasDeployment ? true : requireEmailVerificationStrict,
- // Better Auth deliberately returns the same response for existing addresses.
- // Continue privately by email without adding a credential or replacing a
- // password on an account whose ownership has not been proved.
- onExistingUserSignUp: async ({ user }): Promise => {
- if (!user.emailVerified) {
- await auth.api.sendVerificationOTP({
- body: { email: user.email, type: "email-verification" },
- });
- return;
- }
- const email = existingAccountEmail(user, resolveDashboardPublicUrl());
- if (!(await sendMail({ to: user.email, ...email }))) {
- throw new APIError("SERVICE_UNAVAILABLE", {
- message: "Could not send the sign-in email. Please try again.",
- });
- }
- },
sendVerificationEmail: smtpEnabled
? async ({ user, url }: { user: User; url: string; token: string }) => {
const email = verifyEmailTemplate(user, url);
@@ -279,14 +260,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-capacity.ts b/packages/platform/src/engine/lib/cloud-capacity.ts
index 3c4696c2c..c651a5934 100644
--- a/packages/platform/src/engine/lib/cloud-capacity.ts
+++ b/packages/platform/src/engine/lib/cloud-capacity.ts
@@ -14,7 +14,7 @@ const workspaceResources = z.object({
/** One ownership/shape check for both previews and deployment admission. */
export async function readCloudWorkspaceAllocation(workspaceId: string, namespace: string) {
- const workspace = await getOblienClient().vms.get(workspaceId);
+ const workspace = await getOblienClient().workspaces.get(workspaceId);
if (workspace.id !== workspaceId || workspace.namespace !== namespace) {
throw new AppError("Cloud workspace ownership changed", 409, "CLOUD_NAMESPACE_MISMATCH");
}
diff --git a/packages/platform/src/engine/lib/cloud-docker-workspace.ts b/packages/platform/src/engine/lib/cloud-docker-workspace.ts
index 65b9334d1..b946e6500 100644
--- a/packages/platform/src/engine/lib/cloud-docker-workspace.ts
+++ b/packages/platform/src/engine/lib/cloud-docker-workspace.ts
@@ -42,10 +42,10 @@ export async function findOwnedDockerWorkspace(
ownerWorkspaceId: string,
namespace: string,
) {
- let found: Awaited> | undefined;
+ let found: Awaited> | undefined;
for (let page = 1; ; page++) {
- const result = await client.vms.list({ page, limit: 100 });
- const matches = result.vms.filter(
+ const result = await client.workspaces.list({ page, limit: 100 });
+ const matches = result.workspaces.filter(
(item) => item.slug === workspaceSlug(ownerWorkspaceId) && item.namespace === namespace,
);
for (const workspace of matches) {
@@ -55,7 +55,7 @@ export async function findOwnedDockerWorkspace(
);
found = workspace;
}
- if (!result.vms.length || page * result.limit >= result.total) return found;
+ if (!result.workspaces.length || page * result.limit >= result.total) return found;
}
}
@@ -78,7 +78,7 @@ export async function resizeDockerWorkspace(input: {
save(workloads: NonNullable): Promise;
};
}) {
- const ws = input.client.vm(input.workspaceId);
+ const ws = input.client.workspace(input.workspaceId);
const executor = new CloudWorkspaceExecutor(options => ws.runtime(options), input.workspaceId);
try {
const inspect = () =>
@@ -331,7 +331,7 @@ async function ensureDockerHost(
);
input.signal.throwIfAborted();
}
- const workspace = await client.vms
+ const workspace = await client.workspaces
.create({
name: managed.name,
slug: workspaceSlug(ownerId),
@@ -355,7 +355,7 @@ async function ensureDockerHost(
.catch(async (error) => {
const failure = cloudWorkspaceCreationFailure(error);
if (failure.workspaceId) {
- const created = await client.vms.get(failure.workspaceId);
+ const created = await client.workspaces.get(failure.workspaceId);
if (
created.id !== failure.workspaceId ||
created.namespace !== namespace ||
@@ -387,7 +387,7 @@ async function ensureDockerHost(
// Complete this even after cancellation: retries must know which disk exists.
await repos.cloudDockerWorkspace.attach(owner, input.organizationId, namespace, workspaceId);
}
- const ws = client.vm(workspaceId);
+ const ws = client.workspace(workspaceId);
const current = await ws.get();
if (current.namespace !== namespace) throw new Error("Cloud workspace namespace changed");
input.signal?.throwIfAborted();
@@ -397,7 +397,7 @@ async function ensureDockerHost(
input.onProgress?.(
"Retrying the managed server's initial provisioning with its existing disk.\n",
);
- const retried = await client.vms.retryCreation(workspaceId);
+ const retried = await client.workspaces.retryCreation(workspaceId);
if (retried.id !== workspaceId || retried.namespace !== namespace)
throw new Error("Cloud provisioning retry returned an unexpected workspace");
} else if (status === "stopped") await ws.start();
diff --git a/packages/platform/src/engine/lib/cloud-preflight.ts b/packages/platform/src/engine/lib/cloud-preflight.ts
index b3256be79..8515d80d3 100644
--- a/packages/platform/src/engine/lib/cloud-preflight.ts
+++ b/packages/platform/src/engine/lib/cloud-preflight.ts
@@ -1,5 +1,5 @@
import { reportCaughtError as observeCaughtError, diagnostics as errorDiagnostics } from "@repo/core/diagnostics";
-import { createPlatform, oblienApiBaseUrl, type CloudInfraProvider } from "@repo/adapters";
+import { createPlatform, type CloudInfraProvider } from "@repo/adapters";
import { ensureNamespace, getOblienClient, issueNamespaceToken } from "./openship-cloud";
import { env } from "../config/env";
import { assertCloudCanSpend } from "../modules/billing/billing-oblien-quota";
@@ -99,7 +99,7 @@ export async function runCloudPreflight(
await assertCloudCanSpend(organizationId, opts.workspaceId);
const cloudPlatform = await createPlatform({
target: "cloud", cloudToken: token.token, cloudNamespace: token.namespace,
- cloudApiUrl: oblienApiBaseUrl(env.OBLIEN_API_URL).toString(),
+ cloudApiUrl: env.OBLIEN_API_URL,
});
cloud = cloudPlatform.routing as CloudInfraProvider;
} catch (err) {
diff --git a/packages/platform/src/engine/lib/cloud-resource-limits.ts b/packages/platform/src/engine/lib/cloud-resource-limits.ts
index eac0f264c..64455831a 100644
--- a/packages/platform/src/engine/lib/cloud-resource-limits.ts
+++ b/packages/platform/src/engine/lib/cloud-resource-limits.ts
@@ -1,7 +1,6 @@
import { AppError, resolvePlan, type CloudCapacityPool, type PlanTierId } from "@repo/core";
import { getOblienClient } from "./oblien-client";
import { z } from "zod";
-import { toOblienVmLimits, type NamespaceResourceLimits } from "@repo/adapters";
type NamespaceLimits = ReturnType;
@@ -11,8 +10,8 @@ export function cloudNamespaceLimits(tier: PlanTierId) {
return { ...resolvePlan(tier).oblienLimits };
}
-export async function initialCloudNamespaceLimits() {
- return toOblienVmLimits(cloudNamespaceLimits("free"));
+export async function initialCloudNamespaceLimits(): Promise {
+ return cloudNamespaceLimits("free");
}
/** Submit the verified subscription's declared policy under the billing lock.
@@ -26,14 +25,13 @@ export async function syncCloudResourceLimits(
): Promise {
const client = getOblienClient();
const { data: current } = await client.namespaces.get(namespace);
- const providerLimits = toOblienVmLimits(desired);
if (current.slug !== namespace) throw new AppError("Cloud namespace ownership changed", 502, "CLOUD_NAMESPACE_MISMATCH");
// Compare declared policy, never Oblien's effective_resource_limits: account
// capacity may change without changing the customer's purchase contract.
- const matches = (limits: NamespaceResourceLimits | null | undefined) =>
- (Object.keys(providerLimits) as Array).every(key => (limits?.[key] ?? null) === providerLimits[key]);
+ const matches = (limits: Partial | null | undefined) =>
+ (Object.keys(desired) as Array).every(key => (limits?.[key] ?? null) === desired[key]);
if (matches(current.resource_limits)) return;
- const { data: updated } = await client.namespaces.update(current.id, { resource_limits: providerLimits });
+ const { data: updated } = await client.namespaces.update(current.id, { resource_limits: { ...desired } });
if (updated.slug !== namespace || !matches(updated.resource_limits)) {
throw new AppError("Cloud resource limits were not confirmed", 502, "CLOUD_RESOURCE_LIMITS_UNCONFIRMED");
}
@@ -41,13 +39,13 @@ export async function syncCloudResourceLimits(
const capacityResponse = z.object({ success: z.literal(true), data: z.object({
slug: z.string(),
- effective_resource_limits: z.object({ max_vms: z.number().nonnegative().nullable(),
+ effective_resource_limits: z.object({ max_workspaces: z.number().nonnegative().nullable(),
max_vcpus: z.number().nonnegative().nullable().optional(),
max_ram_mb: z.number().nonnegative().nullable().optional(),
max_disk_gb: z.number().nonnegative().nullable().optional(),
max_total_vcpus: z.number().nonnegative().nullable(), max_total_ram_mb: z.number().nonnegative().nullable(),
max_total_disk_gb: z.number().nonnegative().nullable() }).optional(),
- allocated_resource_usage: z.object({ vms: z.number().nonnegative(), vcpus: z.number().nonnegative(),
+ allocated_resource_usage: z.object({ workspaces: z.number().nonnegative(), vcpus: z.number().nonnegative(),
ram_mb: z.number().nonnegative(), disk_gb: z.number().nonnegative(), pending_updates: z.number().int().nonnegative() }).optional(),
}) });
@@ -65,7 +63,7 @@ function presentCapacity(data: Awaited>
const limits = data.effective_resource_limits, used = data.allocated_resource_usage;
if (!limits || !used) return {};
return {
- workspaces: { used: used.vms, max: limits.max_vms },
+ workspaces: { used: used.workspaces, max: limits.max_workspaces },
vcpus: { used: used.vcpus, max: limits.max_total_vcpus },
ramMb: { used: used.ram_mb, max: limits.max_total_ram_mb },
diskGb: { used: used.disk_gb, max: limits.max_total_disk_gb },
diff --git a/packages/platform/src/engine/lib/cloud-tenant-admin.ts b/packages/platform/src/engine/lib/cloud-tenant-admin.ts
index f7f0b032b..8be2b268f 100644
--- a/packages/platform/src/engine/lib/cloud-tenant-admin.ts
+++ b/packages/platform/src/engine/lib/cloud-tenant-admin.ts
@@ -17,7 +17,7 @@ export function createTenantCloudAdmin(organizationId: string, namespace: string
};
const requireWorkspace = async (id: string) => {
validateId(id);
- const workspace = await admin.vms.get(id);
+ const workspace = await admin.workspaces.get(id);
if (workspace.namespace !== namespace) throw deny();
return workspace;
};
@@ -47,13 +47,13 @@ export function createTenantCloudAdmin(organizationId: string, namespace: string
get: requirePage,
create: async (input) => {
if (input.slug) validateId(input.slug);
- await requireWorkspace(input.vm_id);
+ await requireWorkspace(input.workspace_id);
await assertCloudCanSpend(organizationId, workspaceId);
return admin.pages.create({ ...input, namespace });
},
deploy: async (slug, input) => {
await requirePage(slug);
- await requireWorkspace(input.vm_id);
+ await requireWorkspace(input.workspace_id);
await assertCloudCanSpend(organizationId, workspaceId);
return admin.pages.deploy(slug, input);
},
@@ -83,14 +83,14 @@ export function createTenantCloudAdmin(organizationId: string, namespace: string
if (!owned) throw deny();
if (input.static) await requirePage(input.static.page);
const workspaces = new Set();
- for (const rule of input.routes ?? []) {
+ for (const rule of input.routes) {
if (rule.action.kind !== "proxy") continue;
// External origins need separate tenant ownership verification. Admin
// scope alone would authorize another customer's verified origin.
- if (rule.action.origin || !rule.action.vm) {
+ if (rule.action.origin || !rule.action.workspace) {
throw new AppError("Cloud routes must target a workspace in this organization", 400, "CLOUD_ROUTE_TARGET_INVALID");
}
- workspaces.add(rule.action.vm);
+ workspaces.add(rule.action.workspace);
}
await Promise.all([...workspaces].map(requireWorkspace));
return admin.routes.set(normalized, input);
diff --git a/packages/platform/src/engine/lib/cloud-workspace-host.ts b/packages/platform/src/engine/lib/cloud-workspace-host.ts
index cd3175dc9..2ca3a9305 100644
--- a/packages/platform/src/engine/lib/cloud-workspace-host.ts
+++ b/packages/platform/src/engine/lib/cloud-workspace-host.ts
@@ -32,7 +32,7 @@ export async function readCloudWorkspaceHost(organizationId: string, id: string)
if (!env.CLOUD_MODE) {
const connection = await remoteServerConnection(organizationId, id);
const { client } = await getNamespaceClient(organizationId, id, connection);
- const workspace = await client.vms.get(connection.workspaceId);
+ const workspace = await client.workspaces.get(connection.workspaceId);
if (workspace.namespace !== connection.namespace) throw new AppError("Cloud space ownership changed", 409, "CLOUD_NAMESPACE_MISMATCH");
if (workspace.id !== connection.workspaceId)
throw new AppError("Cloud returned a different Cloud space", 502, "CLOUD_SERVER_IDENTITY_MISMATCH");
@@ -76,7 +76,7 @@ async function runningConnection(organizationId: string, id: string) {
* a host or installing the Docker API bridge just to read metrics/open a shell. */
export async function openCloudWorkspaceExecutor(organizationId: string, id: string) {
const { client, binding } = await runningConnection(organizationId, id);
- return new CloudWorkspaceExecutor(options => client.vm(binding.workspaceId!).runtime(options), binding.workspaceId!);
+ return new CloudWorkspaceExecutor(options => client.workspace(binding.workspaceId!).runtime(options), binding.workspaceId!);
}
/** Server-authorized Docker operations (inventory and migration). Applications
@@ -127,7 +127,7 @@ async function measuredHost(organizationId: string, id: string) {
export async function sampleCloudWorkspaceResources(organizationId: string, id: string, sampleUsage = true) {
const { client, binding, provider } = await runningConnection(organizationId, id);
if (!sampleUsage) return { capacity: provider.allocation, usage: unavailableServerUsage("Not sampled for an uncapped build") };
- const executor = new CloudWorkspaceExecutor(options => client.vm(binding.workspaceId!).runtime(options), binding.workspaceId!);
+ const executor = new CloudWorkspaceExecutor(options => client.workspace(binding.workspaceId!).runtime(options), binding.workspaceId!);
try {
return { capacity: provider.allocation, usage: await sampleServerUsage(executor) };
} finally {
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/cloud/types.ts b/packages/platform/src/engine/lib/cloud/types.ts
index 530b6a914..bc667d548 100644
--- a/packages/platform/src/engine/lib/cloud/types.ts
+++ b/packages/platform/src/engine/lib/cloud/types.ts
@@ -115,7 +115,7 @@ export interface CloudClient {
};
pages: {
create(input: {
- vm_id: string;
+ workspace_id: string;
path: string;
name: string;
slug: string;
diff --git a/packages/platform/src/engine/lib/edge-management.ts b/packages/platform/src/engine/lib/edge-management.ts
deleted file mode 100644
index e7c4e8284..000000000
--- a/packages/platform/src/engine/lib/edge-management.ts
+++ /dev/null
@@ -1,337 +0,0 @@
-/**
- * Shared OpenResty management client for route rules, analytics and live logs.
- * Remote edges use the pooled SSH tunnel; hosts without a usable tunnel run
- * curl inside their edge container, where the management loopback is reachable.
- */
-
-import { randomUUID } from "node:crypto";
-import { Readable } from "node:stream";
-import {
- reportCaughtError as observeCaughtError,
- diagnostics as errorDiagnostics,
-} from "@repo/core/diagnostics";
-import { safeErrorMessage } from "@repo/core";
-import { repos } from "@repo/db";
-import {
- OPENRESTY_MGMT_PORT,
- containerCommand,
- resolveOurEdgeContainer,
- sq,
- type LogEntry,
-} from "@repo/adapters";
-import { tunnelRequest, tunnelStream } from "./ssh-tunnel";
-import { sshManager } from "./ssh-manager";
-import { systemDebug } from "./system-debug";
-
-async function execMgmt(
- serverId: string,
- path: string,
- opts: { method?: string; json?: unknown } = {},
-): Promise<{ statusCode: number; body: string } | null> {
- try {
- const executor = await sshManager.acquire(serverId);
- const container = await resolveOurEdgeContainer(executor);
- if (!container) return null;
-
- const url = `http://127.0.0.1:${OPENRESTY_MGMT_PORT}${path}`;
- // Status to stdout via -w, body to a temp file, emitted as "\n"
- // — status FIRST so a JSON body containing newlines survives intact.
- // --fail-with-body isn't usable: we want the mgmt API's own error body.
- //
- // mktemp, not a fixed path: the scraper issues several of these per tick
- // (totals, then one per domain for geo), and a shared /tmp name would let
- // concurrent calls read each other's bodies. The inner `sh -c` expands "$B";
- // containerCommand owns the outer quoting.
- const payload = opts.json === undefined ? undefined : JSON.stringify(opts.json);
- // JSON always travels as data. This avoids command-size thresholds and
- // nested quoting differences between local, SSH and elevated executors.
- const requestFile =
- payload === undefined ? undefined : `/tmp/openship-edge-request-${randomUUID()}.json`;
- const uploadWithInput = requestFile ? executor.execWithInput?.bind(executor) : undefined;
- const parts = [`B="$(mktemp)"; curl -s -o "$B" -w '%{http_code}'`];
- if (opts.method && opts.method !== "GET") parts.push(`-X ${opts.method}`);
- if (requestFile) {
- parts.push("-H 'Content-Type: application/json'");
- parts.push(`--data-binary ${sq(`@${requestFile}`)}`);
- }
- parts.push(sq(url));
- const cmd = `${parts.join(" ")}; printf '\\n'; cat "$B"; rm -f "$B"`;
-
- let out: string;
- try {
- if (requestFile) {
- if (uploadWithInput) {
- // execWithInput bounds captured stdout. Upload only the request here
- // so a large analytics reply still uses the ordinary response reader.
- const uploaded = await uploadWithInput(
- containerCommand(container, `umask 077; cat > ${sq(requestFile)}`, { stdin: true }),
- Readable.from([payload!]),
- );
- if (uploaded.code !== 0) throw new Error(uploaded.stderr || "Edge request upload failed");
- } else {
- await executor.writeFile(requestFile, payload!, { mode: 0o600 });
- await executor.exec(`docker cp ${sq(requestFile)} ${sq(`${container}:${requestFile}`)}`);
- }
- }
- out = await executor.exec(containerCommand(container, cmd));
- } finally {
- if (requestFile) {
- await executor
- .exec(containerCommand(container, `rm -f ${sq(requestFile)}`))
- .catch((error) => {
- observeCaughtError(error, "platform/engine/lib/edge-management");
- });
- if (!uploadWithInput) {
- await executor.rm(requestFile).catch((error) => {
- observeCaughtError(error, "platform/engine/lib/edge-management");
- });
- }
- }
- }
- // "\n" — status first so a body containing newlines survives.
- const nl = out.indexOf("\n");
- if (nl < 0) return null;
- const statusCode = Number.parseInt(out.slice(0, nl).trim(), 10);
- if (!Number.isFinite(statusCode)) return null;
- return { statusCode, body: out.slice(nl + 1) };
- } catch (err) {
- observeCaughtError(err, "platform/engine/lib/edge-management");
- systemDebug(
- "edge-management",
- `execMgmt failed: ${err instanceof Error ? err.message : String(err)}`,
- );
- return null;
- }
-}
-
-/** Does this server need the exec transport (no SSH port-forward available)? */
-async function needsExecTransport(serverId: string): Promise {
- try {
- const executor = await sshManager.acquire(serverId);
- return typeof executor.forwardPort !== "function";
- } catch (diagnosticFailure) {
- observeCaughtError(diagnosticFailure, "platform/engine/lib/edge-management");
- return false;
- }
-}
-
-/**
- * One request to the mgmt API over whichever transport this server supports.
- * Tries the SSH forward first when the executor has one, and falls back to the
- * exec transport — a remote box whose forward is blocked still gets answered.
- */
-async function mgmtRequest(
- serverId: string,
- path: string,
- opts: { method?: string; json?: unknown } = {},
-): Promise<{ statusCode: number; body: string } | null> {
- if (!(await needsExecTransport(serverId))) {
- const viaTunnel = await tunnelRequest(serverId, OPENRESTY_MGMT_PORT, path, {
- method: opts.method,
- ...(opts.json !== undefined
- ? {
- headers: { "Content-Type": "application/json" },
- body: JSON.stringify(opts.json),
- }
- : {}),
- });
- if (viaTunnel) return { statusCode: viaTunnel.statusCode, body: viaTunnel.body };
- }
- return execMgmt(serverId, path, opts);
-}
-
-async function requestMgmtJson(
- serverId: string,
- path: string,
- opts: { method?: string; json?: unknown } = {},
-): Promise {
- const res = await mgmtRequest(serverId, path, opts);
- if (!res || res.statusCode < 200 || res.statusCode >= 300) return null;
- try {
- return JSON.parse(res.body) as T;
- } catch {
- return null;
- }
-}
-
-export function fetchMgmt(serverId: string, path: string): Promise {
- return requestMgmtJson(serverId, path);
-}
-
-/**
- * Resolve a missing server to the organization's local server row, then use
- * the same management client as every remote edge. The API's own loopback is
- * never a substitute for the edge's loopback. Failed publication returns null
- * so callers can distinguish persistence from an acknowledged edge update.
- */
-export async function postEdgeMgmt(
- serverId: string | null,
- path: string,
- json: unknown,
- organizationId?: string,
-): Promise {
- let target = serverId;
- if (!target) {
- if (!organizationId) {
- systemDebug("edge-management", `${path}: no serverId and no org to resolve the local one`);
- return null;
- }
- const local = await repos.server.findLocal(organizationId).catch((diagnosticFailure) => {
- observeCaughtError(diagnosticFailure, "platform/engine/lib/edge-management");
- return undefined;
- });
- if (!local) {
- systemDebug("edge-management", `${path}: no local server row; nothing of ours to configure`);
- return null;
- }
- target = local.id;
- }
- return postMgmtJson(target, path, json).catch((err) => {
- errorDiagnostics.warn(
- "platform/engine/lib/edge-management",
- `[edge-mgmt] ${path} failed for server ${target}: ${safeErrorMessage(err)}`,
- err,
- );
- return null;
- });
-}
-
-export function postMgmtJson(serverId: string, path: string, json: unknown): Promise {
- return requestMgmtJson(serverId, path, { method: "POST", json });
-}
-
-/**
- * Lightweight health probe for the OpenResty management port.
- */
-export async function probeMgmt(serverId: string): Promise {
- const res = await mgmtRequest(serverId, "/health");
- return res?.body.trim() === "ok";
-}
-
-/**
- * Open a streaming SSE connection to the OpenResty management API.
- * Returns a tunnel stream handle - caller pipes `handle.stream.on("data", ...)`
- * to the SSE client.
- */
-export async function mgmtStream(serverId: string, path: string) {
- if (!(await needsExecTransport(serverId))) {
- return tunnelStream(serverId, OPENRESTY_MGMT_PORT, path);
- }
- return execMgmtStream(serverId, path);
-}
-
-/**
- * The exact bytes a `streamExec` chunk carried.
- *
- * `streamExec` is a RAW passthrough on every real executor — LocalExecutor and
- * SystemSshExecutor both say "Do NOT split on \n or trim here" — so a chunk is an
- * arbitrary slice of the byte stream: several frames, one frame, or half a line.
- * `rawData` is base64 of the untouched bytes; `message` is the decoded text and is
- * all a synthesized entry (a process error) has.
- *
- * Exported for the test that pins SSE framing across a mid-frame split.
- */
-export function streamChunkBytes(log: LogEntry): Buffer {
- return log.rawData ? Buffer.from(log.rawData, "base64") : Buffer.from(log.message, "utf8");
-}
-
-/**
- * Live log streaming over the exec transport, for a local/containerized edge that
- * has no SSH forward. Same `TunnelStreamHandle` shape as the tunnel version, so
- * the SSE controllers piping this are unchanged.
- *
- * `curl -N` disables buffering so each frame the mgmt API emits arrives as it is
- * produced rather than in blocks. Without this branch the server-logs stream was
- * as dead as the analytics scrape on every CLI / compose install.
- */
-async function execMgmtStream(serverId: string, path: string) {
- const executor = await sshManager.acquire(serverId);
- const container = await resolveOurEdgeContainer(executor);
- if (!container) throw new Error("No Openship edge container on this server");
-
- const { PassThrough } = await import("node:stream");
- const stream = new PassThrough();
- const url = `http://127.0.0.1:${OPENRESTY_MGMT_PORT}${path}`;
-
- // Tears the transport down on browser disconnect: LocalExecutor kills the curl child,
- // SshExecutor closes the ssh2 channel (which EPIPEs the remote curl within a heartbeat).
- // The edge log source is now the shared ring read by a per-connection cursor, so a
- // lingering orphan can no longer steal frames from the next subscriber — but it still
- // holds an SSH session, so honouring the signal keeps refreshes from exhausting
- // sshd `MaxSessions`. The bare→containerized switch removed the TCP socket whose close
- // used to do this for free; the abort signal is the replacement handle.
- const abort = new AbortController();
- let ended = false;
- let torndown = false;
- let forwarded = false;
- const errParts: string[] = [];
- const finish = () => {
- if (ended) return;
- ended = true;
- stream.end();
- };
-
- // `-f` fails fast on an HTTP error (no body, non-zero exit) and `-S` lets curl print
- // WHY to stderr even under `-s` — together they turn a dead/misrouted edge from a
- // silent empty stream into a diagnosable one. `-N` keeps SSE unbuffered.
- void executor
- .streamExec(
- containerCommand(container, `curl -fsSN ${sq(url)}`),
- (log) => {
- if (ended) return;
- // Only stdout is the SSE body. stderr (curl's own error under `-S`) is a
- // DIAGNOSTIC — forwarding it as bytes would both corrupt framing (dropped by
- // the client) and mask the real failure by making `forwarded` go true.
- if (log.level !== "info") {
- if (log.message) errParts.push(log.message);
- return;
- }
- // Byte-exact, NO added newline: frame boundaries belong to the edge
- // (pipe_stream.lua emits `event: request\ndata: …\n\n`); a chunk is an arbitrary
- // slice, so any reinterpretation here truncates a frame and the client drops it.
- const bytes = streamChunkBytes(log);
- if (bytes.length) forwarded = true;
- stream.write(bytes);
- },
- { signal: abort.signal },
- )
- .then((result) => {
- // curl exited on its own. If it never forwarded a byte and this wasn't an
- // intentional teardown, the browser would otherwise just watch the socket close
- // with no reason — the exec transport has no HTTP status to hand back (it used to
- // report 200 unconditionally, so a dead edge looked identical to an idle one).
- // Speak the failure in a frame the client already understands (`event: error`),
- // the same shape the tunnel-null path in the controller uses.
- if (!torndown && !forwarded && !ended) {
- const detail = errParts.join("").trim() || (result?.output || "").trim();
- const reason =
- `Couldn't reach the Openship edge's log service on this server` +
- `${detail ? `: ${detail}` : ""}. Make sure the edge is running ` +
- "(`docker ps` should show openship-edge) and redeploy the routing if it isn't.";
- stream.write(`event: error\ndata: ${JSON.stringify({ error: reason })}\n\n`);
- }
- finish();
- })
- .catch((err) => {
- observeCaughtError(err, "platform/engine/lib/edge-management");
- systemDebug(
- "edge-management",
- `execMgmtStream ended: ${err instanceof Error ? err.message : String(err)}`,
- );
- finish();
- });
-
- return {
- stream,
- // No HTTP response envelope to read — curl consumed it. A real failure now arrives as
- // the `error` frame above rather than a status code, so this stays 200.
- statusCode: 200,
- headers: {} as Record