>
);
}
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 ef60ca052..96537396b 100644
--- a/apps/web/src/app/(site)/[locale]/(marketing)/pricing/_data.ts
+++ b/apps/web/src/app/(site)/[locale]/(marketing)/pricing/_data.ts
@@ -22,9 +22,7 @@ export function faq(pricing: CloudPricing, copy: Copy): FaqItem[] {
})
: copy("See your dashboard for current Cloud plans and availability."),
pricing.annual.enabled
- ? copy(
- "Yearly billing is also available; the cards show the monthly equivalent and full yearly charge.",
- )
+ ? copy("Choose Yearly to see the full annual price, paid once a year.")
: 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 b91eefcb9..b792bca8c 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,
- cloudFrom,
+ startingCloudPlan,
priceParts,
getCloudPricing,
cloudPlanSummary,
@@ -61,6 +61,7 @@ function PlanCard({
cta,
popular,
support,
+ benefits = [],
children,
}: {
name: string;
@@ -72,6 +73,7 @@ function PlanCard({
cta: string;
popular?: boolean;
support: string;
+ benefits?: string[];
children: ReactNode;
}) {
const copy = useCopy();
@@ -97,10 +99,14 @@ function PlanCard({
{copy(cta)}
);
}
@@ -161,6 +167,7 @@ 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 (
@@ -176,13 +183,13 @@ async function CloudPlans({
return (
<>
- {pricing.tiers.every((plan) => plan.billingMode === "monthly")
+ {plans.every((plan) => plan.billingMode === "monthly")
? copy(
"CPU, RAM and storage included. Apps and builds share capacity. Managed proxy transfer and backups are billed separately.",
)
@@ -376,74 +392,76 @@ export default async function PricingPage() {
const copy = await getCopy();
const pricing = await getCloudPricing(await getLocale());
- const from = cloudFrom(pricing);
+ 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"),
+ };
+ };
return (
<>
-
-
-
- {copy("Cloud resources for your projects.")}
-
-
- {from
- ? copy("From {value0}/month.", { value0: String(from) })
- : copy("Choose your capacity.")}
-
-
-
-
-
-
-
-
-
-
-
}
- annual={
- pricing.available && pricing.annual.enabled ? (
-
- ) : undefined
- }
- monthsFree={pricing.annual.monthsFree}
+
+
+
- {pricing.customTiers.map((plan) => (
-
- ))}
-
+ {pricing.customTiers.map((plan) => (
+
+ ))}
+
diff --git a/apps/web/src/i18n/messages/ar.json b/apps/web/src/i18n/messages/ar.json
index 6a7ac1aff..a7fff290b 100644
--- a/apps/web/src/i18n/messages/ar.json
+++ b/apps/web/src/i18n/messages/ar.json
@@ -349,6 +349,7 @@
"m19ofoog": "تكوين الأسرار في وحدة التحكم التي تملك سير العمل.",
"m19scbsz": "تأكيد الدفع رقم 1234",
"m19ud2w": "قم بتخطيط نافذة صيانة عند نقل البيانات بين الخوادم: تتوقف الخدمات المصدر أثناء نقل البيانات وتبدأ الوجهة. يمكن أن يؤدي استخدام نفس الخادم إلى إعادة استخدام الحاويات قيد التشغيل، ولكن تغيير الوكيل العكسي قد يؤدي إلى مقاطعة حركة المرور لفترة وجيزة. تعتمد المدة على تطبيقك واستراتيجية النقل.",
+ "m19uqmyr": "اختر الدفع السنوي لعرض السعر السنوي الكامل، الذي يُدفع مرة واحدة في السنة.",
"m19xi0mu": "اقرأ وأرسل",
"m19zmnxd": "مجاني للأبد · Apache 2.0",
"m1a0fr6p": "حافظ على نطاق مساحة عمل الوصول إلى المشروع والبنية التحتية.",
@@ -500,6 +501,7 @@
"m1e1obop": "قم باستيراد تعريف Compose من مستودع أو ملف مكدس. راجع إعدادات الخدمة المدعومة والصور والمتغيرات والتبعيات والتخزين والمسارات العامة في خطة النشر.",
"m1e273m5": "قاعدة بيانات دائمة",
"m1e28n1s": "احتفظ بالكامل",
+ "m1e5h57g": "ابتداءً من {amount} /سنة",
"m1e6063y": "يا فريق،",
"m1e656gd": "الأسعار",
"m1e8gegw": "تثبيت",
@@ -1046,6 +1048,7 @@
"m1ulf8lb": "لوحة المعلومات، وCLI، والوكلاء، ومحولات البنية التحتية - كلها عامة، كلها قابلة للقراءة، وكلها قابلة للتدقيق. قم بتشغيله على Raspberry Pi أو أسطول. المساهمة مرة أخرى عندما تريد.",
"m1up62ws": "واجهة جدول بيانات بنمط Airtable للعمل مع البيانات المدعومة بـ SQL.",
"m1up7zq6": "فحص عمليات النشر والخدمات والبنية التحتية ووصول الفريق.",
+ "m1upaqs9": "تُدفع سنويًا",
"m1upcpqc": "الحالة المرصودة",
"m1upw6fh": "الفئات",
"m1us78pp": "احتفظ باتصال قاعدة البيانات الخارجية، أو انسخ قاعدة البيانات التي تم تكوينها باستخدام نسخة احتياطية منطقية من عنوان URL المباشر والعام PostgreSQL مع TLS.",
@@ -1208,7 +1211,6 @@
"m2j3iur": "ما هو الجديد",
"m2j49ci": "استوديو المشرف",
"m2jum53": "تتطلب عمليات المجموعة وحدة تحكم ذاتية الاستضافة أو وحدة تحكم سطح المكتب ولا تتوفر على وحدة التحكم السحابية المستضافة.",
- "m2k6cfa": "الفواتير السنوية متاحة أيضًا؛ تُظهر البطاقات المعادل الشهري والرسم السنوي الكامل.",
"m2k95s1": "اكتشف خدمات Docker الموجودة لديك وصورها الحالية. أعد استخدام أحمال العمل على نفس الخادم، أو قم بمراجعة النقل إلى وجهة أخرى مؤهلة.",
"m2km9co": "حسابات صندوق البريد الموجودة",
"m2kt6l9": "أو الأحدث",
@@ -1447,6 +1449,7 @@
"m9kmb0s": "خصم العملاء",
"m9lq1iz": "فحص الدلاء والكائنات من خلال المتصفح.",
"m9oivcn": "حدود الفعل",
+ "m9os5hi": "إدارة مجانية لـ {count} من خوادمك",
"m9pu63g": "التوافق Redis.",
"m9pzyn4": "عملاء السحابة - التخزين الأساسي في غرب الاتحاد الأوروبي (أيرلندا) مع النسخ المتماثلة في شرق الولايات المتحدة وجنوب آسيا والمحيط الهادئ. يمكنك تثبيت مشروع في منطقة واحدة.",
"m9sa70m": "نموذج لتقدم بناء النشر وسجلات بناء الإنتاج في OpenShip.",
@@ -2164,6 +2167,7 @@
"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 c2dbcc765..51b858464 100644
--- a/apps/web/src/i18n/messages/de.json
+++ b/apps/web/src/i18n/messages/de.json
@@ -349,6 +349,7 @@
"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.",
@@ -500,6 +501,7 @@
"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",
@@ -1046,6 +1048,7 @@
"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.",
@@ -1208,7 +1211,6 @@
"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",
@@ -1447,6 +1449,7 @@
"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.",
@@ -2164,6 +2167,7 @@
"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 d64105df5..6ded648a2 100644
--- a/apps/web/src/i18n/messages/en.json
+++ b/apps/web/src/i18n/messages/en.json
@@ -349,6 +349,7 @@
"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.",
@@ -500,6 +501,7 @@
"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",
@@ -1046,6 +1048,7 @@
"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.",
@@ -1208,7 +1211,6 @@
"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",
@@ -1447,6 +1449,7 @@
"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.",
@@ -2164,6 +2167,7 @@
"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 220fd3b61..2057cfa04 100644
--- a/apps/web/src/i18n/messages/es.json
+++ b/apps/web/src/i18n/messages/es.json
@@ -349,6 +349,7 @@
"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.",
@@ -500,6 +501,7 @@
"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",
@@ -1046,6 +1048,7 @@
"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.",
@@ -1208,7 +1211,6 @@
"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",
@@ -1447,6 +1449,7 @@
"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.",
@@ -2164,6 +2167,7 @@
"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 90a2db9f3..43273887a 100644
--- a/apps/web/src/i18n/messages/fr.json
+++ b/apps/web/src/i18n/messages/fr.json
@@ -349,6 +349,7 @@
"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.",
@@ -500,6 +501,7 @@
"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",
@@ -1046,6 +1048,7 @@
"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.",
@@ -1208,7 +1211,6 @@
"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",
@@ -1447,6 +1449,7 @@
"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.",
@@ -2164,6 +2167,7 @@
"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 b4b56309d..b0dcd296e 100644
--- a/apps/web/src/i18n/messages/ja.json
+++ b/apps/web/src/i18n/messages/ja.json
@@ -349,6 +349,7 @@
"m19ofoog": "ワークフローを所有するコントローラーでシークレットを構成します。",
"m19scbsz": "支払い確認 #1234",
"m19ud2w": "サーバー間でデータを移動する場合は、メンテナンス期間を計画します。データ転送中にソース サービスが停止し、宛先サービスが開始されます。同一サーバーを採用すると、実行中のコンテナを再利用できますが、リバース プロキシを変更するとトラフィックが一時的に中断される可能性があります。期間はアプリと転送戦略によって異なります。",
+ "m19uqmyr": "年払いを選択すると、年に一度支払う年間料金の総額が表示されます。",
"m19xi0mu": "読んで送信する",
"m19zmnxd": "永久無料 · Apache 2.0",
"m1a0fr6p": "プロジェクトとインフラストラクチャへのアクセスをワークスペース範囲に保ちます。",
@@ -500,6 +501,7 @@
"m1e1obop": "リポジトリまたはスタック ファイルから Compose 定義をインポートします。導入計画でサポートされているサービス設定、イメージ、変数、依存関係、ストレージ、およびパブリック ルートを確認します。",
"m1e273m5": "永続的なデータベース",
"m1e28n1s": "いっぱいにしておいてください",
+ "m1e5h57g": "{amount} /年から",
"m1e6063y": "やあチーム、",
"m1e656gd": "価格設定",
"m1e8gegw": "インストール",
@@ -1046,6 +1048,7 @@
"m1ulf8lb": "ダッシュボード、CLI、エージェント、インフラストラクチャ アダプタはすべて公開されており、すべて読み取り可能で、すべて監査可能です。 Raspberry Pi またはフリートで実行します。必要に応じて貢献してください。",
"m1up62ws": "SQL ベースのデータを操作するための Airtable スタイルのスプレッドシート インターフェイス。",
"m1up7zq6": "導入、サービス、インフラストラクチャ、チームのアクセスを検査します。",
+ "m1upaqs9": "年払い",
"m1upcpqc": "観測された状態",
"m1upw6fh": "カテゴリー",
"m1us78pp": "外部データベース接続を維持するか、TLS を使用して直接パブリック PostgreSQL URL から論理バックアップを使用して構成されたデータベースをコピーします。",
@@ -1208,7 +1211,6 @@
"m2j3iur": "新機能",
"m2j49ci": "管理スタジオ",
"m2jum53": "クラスター操作にはセルフホストまたはデスクトップ コントローラーが必要ですが、ホストされたクラウド コントローラーでは使用できません。",
- "m2k6cfa": "年単位の請求も可能です。カードには、月額相当額と年間全額の料金が表示されます。",
"m2k95s1": "既存の Docker サービスとその現在のイメージを検出します。同じサーバー上のワークロードを再利用するか、別の適格な宛先への移動を検討してください。",
"m2km9co": "既存のメールボックス アカウント",
"m2kt6l9": "またはそれより新しい",
@@ -1447,6 +1449,7 @@
"m9kmb0s": "顧客割引",
"m9lq1iz": "ブラウザを通じてバケットとオブジェクトを検査します。",
"m9oivcn": "行動の境界線",
+ "m9os5hi": "サーバー {count} 台を無料で管理",
"m9pu63g": "Redis の互換性",
"m9pzyn4": "クラウドのお客様 - EU 西 (アイルランド) にプライマリ ストレージがあり、米国東部と AP 南にレプリカがあります。プロジェクトを単一のリージョンに固定できます。",
"m9sa70m": "サンプル デプロイメントのビルドの進行状況と運用ビルドのログは OpenShip に記録されます。",
@@ -2164,6 +2167,7 @@
"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 2c75523cc..785f30402 100644
--- a/apps/web/src/i18n/messages/pt.json
+++ b/apps/web/src/i18n/messages/pt.json
@@ -349,6 +349,7 @@
"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.",
@@ -500,6 +501,7 @@
"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",
@@ -1046,6 +1048,7 @@
"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.",
@@ -1208,7 +1211,6 @@
"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",
@@ -1447,6 +1449,7 @@
"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.",
@@ -2164,6 +2167,7 @@
"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 ce7f167b8..2ac62b297 100644
--- a/apps/web/src/i18n/messages/ru.json
+++ b/apps/web/src/i18n/messages/ru.json
@@ -349,6 +349,7 @@
"m19ofoog": "Настройте секреты в контроллере, владеющем рабочим процессом.",
"m19scbsz": "Подтверждение платежа №1234",
"m19ud2w": "Запланируйте период обслуживания при перемещении данных между серверами: исходные службы останавливаются во время передачи данных и запускаются назначения. Внедрение одного и того же сервера может повторно использовать запущенные контейнеры, но смена обратного прокси-сервера может ненадолго прервать трафик. Продолжительность зависит от вашего приложения и стратегии передачи.",
+ "m19uqmyr": "Выберите оплату за год, чтобы увидеть полную годовую стоимость, оплачиваемую раз в год.",
"m19xi0mu": "Прочтите и отправьте",
"m19zmnxd": "Бесплатно навсегда · Apache 2.0",
"m1a0fr6p": "Обеспечьте ограниченность рабочей области проекта и доступа к инфраструктуре.",
@@ -500,6 +501,7 @@
"m1e1obop": "Импортируйте определение Compose из репозитория или файла стека. Просмотрите параметры поддерживаемых служб, образы, переменные, зависимости, хранилище и общедоступные маршруты в плане развертывания.",
"m1e273m5": "Постоянная база данных",
"m1e28n1s": "Держите полный",
+ "m1e5h57g": "От {amount} /год",
"m1e6063y": "Привет, команда,",
"m1e656gd": "Цены",
"m1e8gegw": "Установить",
@@ -1046,6 +1048,7 @@
"m1ulf8lb": "Панель мониторинга, интерфейс командной строки, агенты, адаптеры инфраструктуры — все общедоступно, все доступно для чтения и аудита. Запустите его на Raspberry Pi или на автопарке. Внесите свой вклад, когда захотите.",
"m1up62ws": "Интерфейс электронных таблиц в стиле Airtable для работы с данными на основе SQL.",
"m1up7zq6": "Проверяйте развертывания, услуги, инфраструктуру и доступ групп.",
+ "m1upaqs9": "Оплата за год",
"m1upcpqc": "Наблюдаемое состояние",
"m1upw6fh": "Категории",
"m1us78pp": "Сохраните подключение к внешней базе данных или скопируйте настроенную базу данных, используя логическую резервную копию с прямого общедоступного URL-адреса PostgreSQL с TLS.",
@@ -1208,7 +1211,6 @@
"m2j3iur": "Что нового",
"m2j49ci": "Админ студия",
"m2jum53": "Для операций кластера требуется автономный или настольный контроллер, и они недоступны на размещенном облачном контроллере.",
- "m2k6cfa": "Также доступна ежегодная оплата; карты показывают ежемесячный эквивалент и полную годовую плату.",
"m2k95s1": "Откройте для себя существующие сервисы Docker и их текущие образы. Повторно используйте рабочие нагрузки на одном и том же сервере или рассмотрите возможность перехода в другое подходящее место назначения.",
"m2km9co": "Существующие учетные записи почтовых ящиков",
"m2kt6l9": "или новее",
@@ -1447,6 +1449,7 @@
"m9kmb0s": "Скидка клиента",
"m9lq1iz": "Проверяйте корзины и объекты через браузер.",
"m9oivcn": "Границы действий",
+ "m9os5hi": "Бесплатное управление серверами: {count}",
"m9pu63g": "Redis совместимость",
"m9pzyn4": "Облачные клиенты — основное хранилище на западе ЕС (Ирландия) с репликами на востоке США и AP-юге. Вы можете прикрепить проект к одному региону.",
"m9sa70m": "Журналы хода сборки примера развертывания и производственной сборки в OpenShip.",
@@ -2164,6 +2167,7 @@
"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 cf9d7d820..76ddc6024 100644
--- a/apps/web/src/i18n/messages/tr.json
+++ b/apps/web/src/i18n/messages/tr.json
@@ -349,6 +349,7 @@
"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.",
@@ -500,6 +501,7 @@
"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",
@@ -1046,6 +1048,7 @@
"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.",
@@ -1208,7 +1211,6 @@
"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",
@@ -1447,6 +1449,7 @@
"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.",
@@ -2164,6 +2167,7 @@
"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 76bd0fe8d..b6429bab7 100644
--- a/apps/web/src/i18n/messages/zh.json
+++ b/apps/web/src/i18n/messages/zh.json
@@ -349,6 +349,7 @@
"m19ofoog": "在拥有工作流的控制器中配置机密。",
"m19scbsz": "付款确认#1234",
"m19ud2w": "在服务器之间移动数据时规划维护时段:源服务在数据传输时停止,目标服务启动。采用同一服务器可以重用正在运行的容器,但更改反向代理可能会短暂中断流量。持续时间取决于您的应用程序和传输策略。",
+ "m19uqmyr": "选择按年计费,即可查看每年一次支付的全年总价。",
"m19xi0mu": "阅读并发送",
"m19zmnxd": "永远免费·Apache 2.0",
"m1a0fr6p": "保持项目和基础设施访问工作空间范围。",
@@ -500,6 +501,7 @@
"m1e1obop": "从存储库或堆栈文件导入 Compose 定义。查看部署计划中支持的服务设置、映像、变量、依赖项、存储和公共路由。",
"m1e273m5": "持久数据库",
"m1e28n1s": "保持完整",
+ "m1e5h57g": "每年 {amount} 起",
"m1e6063y": "嘿团队,",
"m1e656gd": "定价",
"m1e8gegw": "安装",
@@ -1046,6 +1048,7 @@
"m1ulf8lb": "仪表板、CLI、代理、基础设施适配器——全部公开、全部可读、全部可审计。在 Raspberry Pi 或机群上运行它。当您愿意时,请做出贡献。",
"m1up62ws": "Airtable 风格的电子表格界面,用于处理 SQL 支持的数据。",
"m1up7zq6": "检查部署、服务、基础设施和团队访问。",
+ "m1upaqs9": "按年计费",
"m1upcpqc": "观察状态",
"m1upw6fh": "类别",
"m1us78pp": "保持外部数据库连接,或使用逻辑备份从带有 TLS 的直接公共 PostgreSQL URL 复制其配置的数据库。",
@@ -1208,7 +1211,6 @@
"m2j3iur": "有什么新消息",
"m2j49ci": "行政工作室",
"m2jum53": "集群操作需要自托管或桌面控制器,并且在托管云控制器上不可用。",
- "m2k6cfa": "也可按年计费;这些卡显示每月等额费用和全年费用。",
"m2k95s1": "发现您现有的 Docker 服务及其当前映像。重复使用同一服务器上的工作负载,或查看是否移动到另一个符合条件的目标。",
"m2km9co": "现有邮箱帐户",
"m2kt6l9": "或更新的",
@@ -1447,6 +1449,7 @@
"m9kmb0s": "顾客折扣",
"m9lq1iz": "通过浏览器检查存储桶和对象。",
"m9oivcn": "行动边界",
+ "m9os5hi": "免费管理 {count} 台服务器",
"m9pu63g": "Redis 兼容性",
"m9pzyn4": "云客户 - 主存储位于欧盟西部(爱尔兰),副本位于美国东部和亚太南部。您可以将项目固定到单个区域。",
"m9sa70m": "OpenShip 中示例部署的构建进度和生产构建日志。",
@@ -2164,6 +2167,7 @@
"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/pricing.ts b/apps/web/src/lib/pricing.ts
index 51a04fcad..f512fc7f8 100644
--- a/apps/web/src/lib/pricing.ts
+++ b/apps/web/src/lib/pricing.ts
@@ -85,23 +85,24 @@ 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(interval === "annual" ? price / 12 : price),
- per: price !== null && price > 0 ? UI.perMonth : null,
+ amount: price === null ? UI.custom : price === 0 ? UI.free : money(price),
+ per: price !== null && price > 0 ? (interval === "annual" ? UI.perYear : 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): PricedPlan | null {
+export function startingCloudPlan(
+ pricing: CloudPricing,
+ interval: "monthly" | "annual" = "monthly",
+): PricedPlan | null {
if (!pricing.available) return null;
return pricing.tiers.reduce(
- (lowest, plan) => (!lowest || plan.price.monthly < lowest.price.monthly ? plan : lowest),
+ (lowest, plan) =>
+ plan.price[interval] != null && (!lowest || plan.price[interval]! < lowest.price[interval]!)
+ ? plan
+ : lowest,
null,
);
}
diff --git a/apps/web/src/styles/landing.css b/apps/web/src/styles/landing.css
index f366e9573..5ab6fa758 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: 150px 0 64px;
+ padding: 132px 0 44px;
}
.pp-hero-inner {
text-align: center;
@@ -1586,6 +1586,11 @@
.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;
@@ -1630,9 +1635,7 @@
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 16px 32px;
- padding-bottom: 24px;
- margin-bottom: 32px;
- border-bottom: 1px solid var(--th-bd-default);
+ margin-top: 32px;
}
.pp-offering-section {
padding: 48px 0;
@@ -1824,14 +1827,18 @@
text-align: end;
}
.pp-plan-support {
- display: flex;
- align-items: center;
+ display: grid;
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;
}
@@ -2009,8 +2016,7 @@
.pp-cloud-benefits {
grid-template-columns: 1fr;
gap: 8px;
- padding-bottom: 16px;
- margin-bottom: 24px;
+ margin-top: 24px;
}
.pp-plans {
grid-template-columns: 1fr;
diff --git a/bun.lock b/bun.lock
index 38011b2f5..abd3f92cd 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": "2.10.0",
+ "oblien": "3.0.2",
"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@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=="],
+ "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=="],
"obug": ["obug@2.2.1", "", {}, "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q=="],
@@ -3892,6 +3892,8 @@
"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=="],
@@ -4216,6 +4218,8 @@
"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/cloud-plan-enforcement.md b/docs/cloud-plan-enforcement.md
index 8a9f2bc1f..f7427e843 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.
-Their displayed monthly equivalents are $10, $20, $39 and $99. Both intervals
+Yearly prices display these full annual amounts per year. 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 9e13ec948..b7a1b30f8 100644
--- a/docs/dashboard-design.md
+++ b/docs/dashboard-design.md
@@ -5,6 +5,13 @@ and a consistent type hierarchy across light, dim, and dark themes.
## Surfaces and controls
+Personal avatar URLs live in Settings → General → Profile. Project icon URLs live
+in the Project Info card in project Settings. Both use the shared URL editor with
+a preview and a reset action. Each project has one `iconUrl`; project, app, connection
+and deployment lists use the same renderer. Clearing the URL restores the catalog
+logo or framework/service icon. Image URLs are displayed directly by the browser
+with no referrer; the control plane does not fetch them or discover favicons.
+
Assistant settings belong in **Settings → Assistant**; event-driven flows and run
history open from **Automations** in the AI Agents right column.
Keep the conversation free of view tabs, with an AI Agents return action on the automations page.
@@ -174,6 +181,9 @@ 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.
@@ -506,6 +516,8 @@ 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**.
@@ -777,10 +789,11 @@ 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 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
+ 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
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.
@@ -872,6 +885,14 @@ 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.
@@ -1051,9 +1072,11 @@ from an existing run. Keep loading, fetch errors and empty inventory distinct, a
the selected destination's validation and transfer review before enabling Migrate.
Platform imports share three steps: Connect, Select services, and Review & import. Show
-one destination project for each source project, with its selected services and private
-connections kept together. Name the project once in the destination sidebar; service cards
-edit service names. Review and progress link to that project without repeating it for each service.
+one destination project when the source services share a compatible Git checkout. Environments
+with multiple repositories, branches or revisions create a project per service, connected privately
+on the same destination server. Show each destination name in review and the project count in its
+summary. Name the import once in the destination sidebar; service cards edit service names.
+Progress links once per destination project.
Review and saved progress share a Domains & DNS guide, using the provider's recorded domain
ownership per service. Imported custom domains are saved through the normal migration routing
path, initially unverified. Distinguish domains that need DNS changes from provider URLs that
diff --git a/docs/installation.md b/docs/installation.md
index 756a9f1dc..ffd095be7 100644
--- a/docs/installation.md
+++ b/docs/installation.md
@@ -94,7 +94,7 @@ Fix by moving Docker's data-root to a native `ext4`/`xfs` disk (`/etc/docker/dae
## Users & access (self-hosted)
-- **Public signup is disabled after the first account.** The first admin comes from the `openship` setup wizard; with `openship up --compose` (or raw Docker) you register the first account in the dashboard. Everyone after joins by invite.
+- **Create the first admin on the server.** Run `openship` and choose **Create first admin**, or use `openship up --non-interactive --admin-email ` with `OPENSHIP_ADMIN_PASSWORD` set. The same setup works for CLI-managed Compose installs. Public signup stays disabled; everyone after joins by invite.
- **Invite teammates** from **Settings → Team**. They get an accept link at your instance's URL (so the instance needs to be reachable — a public URL or your LAN).
- **Lost the admin password?** Run `openship reset-admin-password` on the box (no sign-in needed; uses the local internal token).
diff --git a/docs/mail-engine-state.md b/docs/mail-engine-state.md
index cfa70c3cc..60e9dc512 100644
--- a/docs/mail-engine-state.md
+++ b/docs/mail-engine-state.md
@@ -25,10 +25,13 @@ Supervisor rather than relying on systemd or Debian's service-start policy.
`OPENSHIP_MAIL_F2B_IGNOREIP` extends the image's default `ignoreip` list. For a new
installation, an operator may set it in the API environment before mail setup.
-For an existing server, set the single-line value in that server's retained
-`/var/lib/openship/mail/engine.env`, then update/recreate the engine. Different
-servers can retain different exclusions. The file contains credentials and must
-remain private.
+On an engine image update, a nonempty API value replaces this record in the retained
+`/var/lib/openship/mail/engine.env`; an explicitly empty API value removes it.
+Leaving the API variable unset preserves the server's saved exclusions. Different
+servers can retain different lists configured directly in their own `engine.env`.
+The override is applied when replacing the engine image; restarting the API or
+checking an already-current image does not recreate the engine. The file contains
+credentials and must remain private.
Move existing manual `ignoreip` edits from the old container into this setting
before the first update. Arbitrary files under `/etc/fail2ban` are not persisted;
diff --git a/docs/managed-cloud-servers.md b/docs/managed-cloud-servers.md
index 2ab754f07..6d2858c3d 100644
--- a/docs/managed-cloud-servers.md
+++ b/docs/managed-cloud-servers.md
@@ -212,11 +212,13 @@ 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://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
+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
`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 033bf2aa8..51b2f7784 100644
--- a/docs/openship-cloud-launch.md
+++ b/docs/openship-cloud-launch.md
@@ -582,7 +582,6 @@ 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=
@@ -805,3 +804,39 @@ 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 c9f0baca7..e72b03223 100644
--- a/docs/platform-migrations.md
+++ b/docs/platform-migrations.md
@@ -6,10 +6,10 @@ New Project → Import existing project offers Server or Docker, Railway, and Ve
1. An organization admin adds a Railway or Vercel connection in Settings → Connections or directly in the import flow. Existing registry and DNS credentials remain on the same page. Old `?tab=credentials` and `?tab=dns` links still work.
2. Select a project and environment. Railway discovers services, deployed revisions, variables, domains, and attached volumes. Vercel discovers a production or latest ready preview deployment and its GitHub source, build configuration, variables, domains, and PostgreSQL URLs.
-3. Review all services in the Railway environment together, one destination project name, distinct service names, a managed plan or connected server, and whether to copy storage or explicitly start empty. Each source project becomes one OpenShip project containing its services; importing a second source project creates a separate project. An external PostgreSQL connection can also remain with its current provider. Supply non-exportable secrets and resolve unsupported provider references.
+3. Review all services in the Railway environment together, one destination project name, distinct service names, a managed plan or connected server, and whether to copy storage or explicitly start empty. Services sharing one repository, branch and revision stay in one OpenShip project. When Git sources differ, each service gets its own project on the selected server; review shows the exact destination names before import. Importing another source environment creates separate projects. An external PostgreSQL connection can also remain with its current provider. Supply non-exportable secrets and resolve unsupported provider references.
4. Review checks source compatibility, repository access and destination access. The plan expires after 30 minutes. Starting rechecks the provider inventory; changed configuration requires a fresh discovery. Source admission is reserved transactionally by Railway project and environment, across destinations and connection records.
-5. Allow Railway project downtime and pause external deployment automation. The worker prepares the selected managed Cloud host before source downtime, creates one destination project with native services, disables automatic push deployments, stops the entire source environment and copies its volumes before deploying the destination. Private addresses resolve through the services' native aliases on the project network. Environment values are encrypted and scoped per service. Named volumes include the service name and use the normal project namespace, keeping databases and separate projects isolated.
-6. Follow progress, logs and the project link at `/migrations/`, including after a browser refresh. Review **Domains & DNS**: each saved source hostname is associated with its service. Custom domains and aliases are already added through the same `saveMigrationRoutes` path used by server/Docker migration, initially unverified. Provider-owned Railway and Vercel URLs require replacement addresses and updates to clients, OAuth callbacks and webhooks. **Review domains & DNS** opens the native project Domains & Routes flow. Test the destination, apply the exact DNS records shown for Cloud or the destination server, then verify DNS, HTTPS and application traffic before confirming completion. Retire the old provider resources separately.
+5. Allow Railway project downtime and pause external deployment automation. The worker prepares the selected managed Cloud host before source downtime, creates the reviewed destination projects with native services, disables automatic push deployments, stops the entire source environment and copies every selected volume before starting destination workloads. Dependencies deploy before their consumers. Within a project, private addresses use native service aliases; across projects they use ordinary private service connections with immutable service aliases. Environment values remain encrypted. Service-specific values stay scoped to the service; cross-project connection variables are owned by the native connection so later deployments refresh them correctly. Named volumes include the service name and use the normal project namespace, keeping databases and separate projects isolated.
+6. Follow progress, logs and the destination project links at `/migrations/`, including after a browser refresh. Review **Domains & DNS**: each saved source hostname is associated with its service. Custom domains and aliases are already added through the same `saveMigrationRoutes` path used by server/Docker migration, initially unverified. Provider-owned Railway and Vercel URLs require replacement addresses and updates to clients, OAuth callbacks and webhooks. **Review domains & DNS** opens the native project Domains & Routes flow. Test the destination, apply the exact DNS records shown for Cloud or the destination server, then verify DNS, HTTPS and application traffic before confirming completion. Retire the old provider resources separately.
Domain guidance reuses the public `domains` inventory and its `portable` flag, persisted in the
run's input snapshot. Route persistence validates hostname ownership before stopping the source;
@@ -22,7 +22,7 @@ reopening a saved run; confirmation remains an operator acknowledgment, not an a
| Source | Supported | Explicit review or separate work |
| ------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Railway | Complete project environments, GitHub repositories at the deployed commit, custom Dockerfiles, portable registry images, build settings, HTTP readiness, restart policy, variables and all selected persistent volume contents | Sealed secrets, unresolved references, dependency cycles, incompatible Git sources, scheduled jobs, multiple replicas, pre-deploy commands, multiple public ports, private registry access and provider-specific features |
+| Railway | Complete project environments including multiple GitHub repositories at their own deployed commits, custom Dockerfiles, portable registry images, build settings, HTTP readiness, restart policy, variables and all selected persistent volume contents | Sealed secrets, unresolved references, dependency cycles, variables combining multiple cross-project private hosts, missing private listener ports, scheduled jobs, multiple replicas, pre-deploy commands, multiple public ports, private registry access and provider-specific features |
| Vercel | GitHub source at the deployed commit, build/root/output settings, exportable environment values, discovered domains, external PostgreSQL connections | Non-exportable Secret/Sensitive values, functions and provider APIs requiring application changes, Edge Config, Blob, other storage services, and non-GitHub repositories |
| External PostgreSQL | A logical copy of the configured database to the selected major version, or preservation of its external connection | Other databases, roles, provider authentication, extensions unavailable in the destination image, pooler/client settings and non-public source endpoints |
@@ -34,7 +34,7 @@ Managed Cloud and connected servers use the same import worker and transfer pipe
External PostgreSQL copies use the shared logical backup producer. Source/target majors and available extensions are checked before restore, and fresh destination databases must finish initialization before receiving data. External writers still require manual quiescence.
-Repository imports use ordinary OpenShip source-service build recipes. Each provider service remains one native service, including explicitly discovered workers. A native project has one Git source: services using different repositories or deployed commits must be aligned before review can succeed. Repository-wide release commands require a service-compatible recipe; review blocks them instead of silently skipping their release phase. Railway pre-deploy commands, cron, replica topology, unsupported Vercel configuration and invalid paths also block review. Railway sleeping services become continuously running services, with a review warning.
+Repository imports use ordinary OpenShip source-service build recipes. Each provider service remains one native service, including explicitly discovered workers. Different repositories, branches or deployed commits receive separate projects; each deployment uses that service's reviewed commit. Cross-project private connections preserve protocols, credentials, paths and ports. A variable containing several different private dependency hosts needs separate connection variables before import, and a private dependency needs a discoverable listener port; review explains these cases before source downtime. Repository-wide release commands require a service-compatible recipe; review blocks them instead of silently skipping their release phase. Railway pre-deploy commands, cron, replica topology, unsupported Vercel configuration and invalid paths also block review. Railway sleeping services become continuously running services, with a review warning.
Vercel cannot export Secret/Sensitive values. After entering a missing PostgreSQL URL, Review adds its database to the same choice list. It stays external unless the user chooses to copy it. Copies require a direct public PostgreSQL URL with TLS and a source database role permitted to export its contents. DNS is validated and pinned; the client runs inside the destination database container.
@@ -70,6 +70,18 @@ Import tests cover review binding and drift, exact Git revisions, destination pr
source downtime, database-first ordering, transfer failures, cancellation and owned SSH-key
recovery. Database tests exercise multi-project migration locks and pending cleanup guards.
+### Multi-repository verification — 2026-11-16
+
+The project import Docker fixture now also covers an image-backed database and two
+different Git sources, importing two environments with identical service names into
+six destination projects. It checks each repository's revision, real private-network
+connections, copied volumes, persistence after restart, and connection refresh during
+an ordinary consumer redeployment. Both socket and Cloud Docker transports use an
+isolated test daemon. Provider control, Git checkout, runtime destination resolution
+and the asynchronous queue are fixture boundaries; this is not a live Railway or SaaS
+account test. Focused tests additionally cover dependency ordering, connection failure
+and recovery, old-plan rejection, and review blockers before source downtime.
+
### Grouped project verification — 2026-11-12
`apps/api/test/e2e/platform-import-project.e2e.test.ts` imports two projects, each with
diff --git a/docs/ship-sdk-plan.md b/docs/ship-sdk-plan.md
index 924be50de..9ffc7387c 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 membership may be broader, so use the appropriate policy deliberately.
+- 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.
- Automated project creation: reuse the create-and-grant semantics of scoped tokens, and extend them deliberately for verified native principals. Project creation and the associated access grant must have defined transactional behavior.
- Namespace-oriented products: first map external namespace keys to an existing tenant or appropriate grouping. If nested namespace isolation is required, add a tenant-owned namespace model, grant semantics, scoped queries, and migrations. A string prefix or renamed project group is insufficient.
diff --git a/packages/adapters/package.json b/packages/adapters/package.json
index 858f55356..4077f40fe 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": "2.10.0",
+ "oblien": "3.0.2",
"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 04b06e02d..6e7ab79bb 100644
--- a/packages/adapters/scripts/verify-cloud-docker.ts
+++ b/packages/adapters/scripts/verify-cloud-docker.ts
@@ -10,6 +10,7 @@ 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";
@@ -33,7 +34,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 = configuration.OBLIEN_API_URL || "https://api.oblien.com";
+const baseUrl = oblienApiBaseUrl(configuration.OBLIEN_API_URL).toString();
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)))
@@ -93,7 +94,7 @@ try {
name: tag,
slug: tag,
type: "testing",
- resource_limits: { max_workspaces: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 },
+ resource_limits: { max_vms: 1, max_vcpus: 2, max_ram_mb: 4096, max_disk_gb: 32 },
});
namespaceId = created.data.id;
await save();
@@ -103,7 +104,7 @@ try {
quotaLimit: 100,
overdraft: 0,
suspendThreshold: 0,
- onOverdraftAction: "stop_workspaces",
+ onOverdraftAction: "stop_vms",
});
const token = await admin.tokens.create({ scope: "namespace", namespace: tag, ttl: 1800 });
const client = new Oblien({ token: token.token, baseUrl });
@@ -127,11 +128,11 @@ try {
network_config: { allow_internet: true, public_ingress: false },
},
};
- const workspace = await client.workspaces.create(createOptions);
+ const workspace = await client.vms.create(createOptions);
workspaceId = workspace.id;
await save();
check("workspace created in test namespace", workspace.namespace === tag && workspaceId);
- const replay = await client.workspaces.create(createOptions);
+ const replay = await client.vms.create(createOptions);
check("provider idempotency reuses workspace", replay.id === workspaceId);
const progress = setInterval(() => log("waiting for Docker workspace"), 20_000);
try {
@@ -140,13 +141,13 @@ try {
clearInterval(progress);
}
log("Docker workspace ready");
- await client.workspace(workspaceId).lifecycle.makePermanent();
+ await client.vm(workspaceId).lifecycle.makePermanent();
check(
"managed server can be made permanent",
- (await client.workspaces.get(workspaceId)).mode === "permanent",
+ (await client.vms.get(workspaceId)).mode === "permanent",
);
await client
- .workspace(workspaceId)
+ .vm(workspaceId)
.lifecycle.makeTemporary({ ttl: "20m", ttl_action: "remove", remove_on_exit: false });
const pageMethods = [
"list",
@@ -170,7 +171,7 @@ try {
return { ...result, pages: result.pages.filter((page) => page.namespace === tag) };
};
adminPages.create = async (input) => {
- if (input.workspace_id !== workspaceId || !input.slug?.startsWith(tag))
+ if (input.vm_id !== workspaceId || !input.slug?.startsWith(tag))
throw new Error("Smoke route escaped its workspace");
pages.add(input.slug);
await save();
@@ -473,7 +474,7 @@ try {
await runtime.stop(second.containerId);
check(
"service stop preserves workspace and sibling",
- isDockerWorkspaceRunning(await client.workspaces.get(workspaceId)) &&
+ isDockerWorkspaceRunning(await client.vms.get(workspaceId)) &&
(await runtime.getContainerInfo(internal.containerId)).status === "running",
);
const stoppedPorts = second.hostPortByContainerPort;
@@ -536,7 +537,7 @@ try {
env: { OPENSHIP_SMOKE_PROCESS: "saved" },
};
await processSupervisor.deploy(processOptions);
- const workload = () => client.workspace(workspaceId!).workloads.get(`openship-${processId}`);
+ const workload = () => client.vm(workspaceId!).workloads.get(`openship-${processId}`);
const savedProcess = await workload();
check(
"provider returns saved process configuration",
@@ -565,10 +566,10 @@ try {
);
await processSupervisor.stop(processId);
- check("provider accepts server stop", (await client.workspace(workspaceId).stop()).success);
+ check("provider accepts server stop", (await client.vm(workspaceId).stop()).success);
await waitForCloudWorkspaceStopped(client, workspaceId, tag);
log("workspace stopped for recovery check", {
- status: (await client.workspaces.get(workspaceId)).status,
+ status: (await client.vms.get(workspaceId)).status,
});
check(
"stopped workspace reads do not start compute",
@@ -590,7 +591,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.workspaces.get(workspaceId)),
+ isDockerWorkspaceRunning(await client.vms.get(workspaceId)),
);
check(
"workspace restart preserves the volume",
@@ -599,7 +600,7 @@ try {
);
check(
"bridge recovery reuses its workload",
- (await client.workspace(workspaceId).workloads.list({ name: "openship-docker-api-v1" }))
+ (await client.vm(workspaceId).workloads.list({ name: "openship-docker-api-v1" }))
.length === 1,
);
const hostnames = await infra.listProjectRouteHostnames();
@@ -630,11 +631,11 @@ try {
}
check(
"one workspace for the whole stack",
- (await client.workspaces.list()).workspaces.length === 1,
+ (await client.vms.list()).vms.length === 1,
);
} catch (error) {
if (workspaceId) {
- const workspace = await admin.workspaces.get(workspaceId).catch(() => null);
+ const workspace = await admin.vms.get(workspaceId).catch(() => null);
if (workspace) {
const provisioning = workspace.provisioning as
| { state?: string; error?: unknown }
@@ -662,7 +663,7 @@ try {
for (const slug of pages) {
try {
const page = (await admin.pages.get(slug)).page;
- if (page.namespace !== tag || page.source_workspace_id !== workspaceId)
+ if (page.namespace !== tag || page.source_vm_id !== workspaceId)
throw new Error("Unexpected smoke page owner");
await admin.pages.delete(slug);
pages.delete(slug);
@@ -676,7 +677,7 @@ try {
}
if (workspaceId) {
try {
- await deleteCloudWorkspace(admin.workspace(workspaceId));
+ await deleteCloudWorkspace(admin.vm(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 1095a25ba..131a01d2a 100644
--- a/packages/adapters/scripts/verify-cloud-isolation.ts
+++ b/packages/adapters/scripts/verify-cloud-isolation.ts
@@ -9,13 +9,14 @@ 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 = config.OBLIEN_API_URL || "https://api.oblien.com";
+const baseUrl = oblienApiBaseUrl(config.OBLIEN_API_URL).toString();
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)}`;
@@ -61,7 +62,7 @@ async function suspendedWorkspaceStops(client: Oblien, workspaceId: string, name
let observedState: string | undefined;
try {
await until(name, async () => {
- const workspace = await client.workspaces.get(workspaceId);
+ const workspace = await client.vms.get(workspaceId);
const state = cloudWorkspaceStatus(workspace);
if (state !== observedState) {
const info = workspace.info as { status?: string; is_running?: boolean } | undefined;
@@ -81,13 +82,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.workspace(workspaceId).stop();
- await until("explicit Stop completes during suspension", async () => cloudWorkspaceStatus(await client.workspaces.get(workspaceId)) === "stopped");
+ await client.vm(workspaceId).stop();
+ await until("explicit Stop completes during suspension", async () => cloudWorkspaceStatus(await client.vms.get(workspaceId)) === "stopped");
}
}
const a = `${tag}-a`, b = `${tag}-b`;
-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 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 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,
@@ -96,7 +97,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_workspaces");
+ check("new namespaces have finite automatic onboarding policy", defaults.autoApply && defaults.quotaLimit === 0 && defaults.overdraft === 0 && defaults.suspendThreshold === 0 && defaults.onOverdraftAction === "stop_vms");
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);
@@ -108,7 +109,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_workspaces", false);
+ inheritedPolicy.quotaLimit === 0 && inheritedPolicy.overdraft === 0 && inheritedPolicy.suspendThreshold === 0 && inheritedPolicy.onOverdraftAction === "stop_vms", 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
@@ -125,7 +126,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 === "/workspace") {
+ if (input.method === "POST" && input.path === "/vms") {
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,
@@ -134,15 +135,15 @@ try {
return result;
};
}
- 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]);
+ 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]);
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.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 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 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 }
@@ -151,19 +152,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(new URL("/workspace", baseUrl), {
+ const limited = await fetch(oblienApiUrl(new URL(baseUrl), "/vms"), {
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.workspaces.create(create(b, "main"));
+ const workspaceB = await clientB.vms.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.workspace(workspace.id).runtime());
+ const executor = new CloudWorkspaceExecutor(() => client.vm(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}`);
@@ -175,16 +176,16 @@ try {
finally { await executor.dispose(); }
pages.set(namespace, namespace);
await save();
- await admin.pages.create({ slug: namespace, namespace, workspace_id: workspace.id, path, domain: "preview.oblien.com" });
+ await admin.pages.create({ name: namespace, slug: namespace, namespace, vm_id: workspace.id, path, domain: "preview.oblien.com" });
}
- const visibleA = (await clientA.workspaces.list()).workspaces;
- const visibleB = (await clientB.workspaces.list()).workspaces;
+ const visibleA = (await clientA.vms.list()).vms;
+ const visibleB = (await clientB.vms.list()).vms;
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.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 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 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]);
@@ -194,10 +195,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.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);
+ 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);
try {
await until("provider records compute usage", async () => (await admin.billing.entitlement(a)).quota.used > 0, 300_000);
@@ -228,25 +229,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.workspaces.get(workspaceA.id)) === "stopped", 90_000);
+ await until("provider stops exhausted namespace", async () => cloudWorkspaceStatus(await clientA.vms.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.workspace(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("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("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.workspaces.get(workspaceA.id)) === "stopped");
- await clientA.workspace(workspaceA.id).start();
+ check("restoring credit does not restart compute implicitly", cloudWorkspaceStatus(await clientA.vms.get(workspaceA.id)) === "stopped");
+ await clientA.vm(workspaceA.id).start();
await waitForCloudDockerWorkspace(clientA, workspaceA.id, a, { signal: abort.signal });
check("restored customer explicitly resumes the same VM", true);
@@ -254,28 +255,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.workspace(workspaceA.id).start(), [402, 403, 409]);
+ await denied("manual suspension blocks Start despite positive credit", () => clientA.vm(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.workspaces.get(workspaceA.id)) === "stopped");
- await clientA.workspace(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.vms.get(workspaceA.id)) === "stopped");
+ await clientA.vm(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.workspace(workspaceA.id).stop();
- await clientA.workspace(workspaceA.id).stop();
+ await clientA.vm(workspaceA.id).stop();
+ await clientA.vm(workspaceA.id).stop();
check("manually suspended customer can repeat Stop", true);
- 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 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 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.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);
+ 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);
} 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 });
@@ -296,7 +297,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, { deleteWorkspaces: true });
+ await admin.namespaces.delete(id, { deleteVms: 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 a2555e61f..725fa5f0f 100644
--- a/packages/adapters/src/backup/executors/docker.ts
+++ b/packages/adapters/src/backup/executors/docker.ts
@@ -434,9 +434,8 @@ 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 — 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.
+ // creates empty on mount. Capture verifies that the resolved volume exists
+ // before mounting it; restore must address the volume the service reads.
const source =
parsed.type !== "volume" || !service.namespaceVolumes
? parsed.source
@@ -578,16 +577,23 @@ 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;
- if (opts?.allowEmpty && source.type === "volume") await this.dockerode.getVolume(source.source).inspect();
+ // 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();
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 = {
- ...(source.type === "bind"
- ? { Mounts: [{ Type: "bind" as const, Source: source.source, Target: `/mnt${isFile ? "/file" : ""}`, ReadOnly: true }] }
- : { Binds: [`${source.source}:/mnt:ro`] }),
+ Mounts: [
+ {
+ Type: source.type as "bind" | "volume",
+ Source: source.source,
+ Target: `/mnt${isFile ? "/file" : ""}`,
+ ReadOnly: true,
+ },
+ ],
// 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
@@ -638,29 +644,10 @@ export class DockerBackupExecutor implements BackupExecutor {
tarCmd,
compression === "zstd" ? "zstd" : "none",
[
- // 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.
+ // 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.
compression === "zstd" ? "apk add --no-cache zstd >/dev/null 2>&1" : null,
]
.filter(Boolean)
diff --git a/packages/adapters/src/backup/types.ts b/packages/adapters/src/backup/types.ts
index eac679419..a0895405b 100644
--- a/packages/adapters/src/backup/types.ts
+++ b/packages/adapters/src/backup/types.ts
@@ -130,8 +130,6 @@ 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[];
/**
diff --git a/packages/adapters/src/backup/volume-transfer.ts b/packages/adapters/src/backup/volume-transfer.ts
index 8d899e748..10f6218b9 100644
--- a/packages/adapters/src/backup/volume-transfer.ts
+++ b/packages/adapters/src/backup/volume-transfer.ts
@@ -163,7 +163,6 @@ 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 abfbd72c0..619c8b966 100644
--- a/packages/adapters/src/index.ts
+++ b/packages/adapters/src/index.ts
@@ -171,6 +171,7 @@ export {
type AlternativeHostPort,
type SuggestAlternativeHostPort,
probeListeningPort,
+ probeListeningPortOwners,
isDockerHostPortAvailable,
ensurePortAvailable,
} from "./runtime/port-conflict";
@@ -605,7 +606,9 @@ 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 e96219677..30927a4f5 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_workspace_id: body.workspace_id, exported_path: body.path, url: `https://${hostname}` };
+ source_vm_id: body.vm_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 === `/workspace/${h.workspaceId}/network` && method === "GET")
+ if (url.pathname === `/vms/${h.workspaceId}/network` && method === "GET")
return Response.json({ ingress_ports: [443] });
- if (url.pathname === `/workspace/${h.workspaceId}/network` && method === "PATCH")
+ if (url.pathname === `/vms/${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", workspace: h.workspaceId, port: 3000 } }] });
+ expect(tables.at(-1)?.body).toEqual({ routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: 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", workspace: h.workspaceId, port: 3000 } }],
+ routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }],
} });
- expect(writes).toContainEqual({ method: "PATCH", path: `/workspace/${h.workspaceId}/network`, body: { ingress_ports: [443, 3000] } });
+ expect(writes).toContainEqual({ method: "PATCH", path: `/vms/${h.workspaceId}/network`, body: { ingress_ports: [443, 3000] } });
expect(requests.some(url => url.pathname === "/workspace")).toBe(false);
});
-it.each(["namespace", "source_workspace_id", "exported_path"])("does not write when the Page's %s changes", async field => {
+it.each(["namespace", "source_vm_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", workspace: h.workspaceId, port: 3000 },
+ action: { kind: "proxy", vm: 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 b2b973a6c..8b13d6473 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", workspace: h.workspaceId, port: 3000 } }] });
+ expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: 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", workspace: h.workspaceId, port: 3000 } }],
+ routes: [{ match: { path: "/v3", type: "prefix" }, action: { kind: "proxy", vm: 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", workspace: h.workspaceId, port: 3000 } }] });
+ expect(h.routes.set).toHaveBeenLastCalledWith(route.domain, { routes: [{ match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: h.workspaceId, port: 3000 } }] });
expect(h.workspace.network.update).toHaveBeenCalledWith({ ingress_ports: [443, 3000] });
});
- it.each(["namespace", "source_workspace_id", "exported_path"])("refuses a changed %s before mutating the route", async field => {
+ it.each(["namespace", "source_vm_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", 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");
+ 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");
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 424061879..4c498d30c 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_workspace_id: "ws-one", exported_path: "/opt/openship/cloud-docker/routes/route-one" };
+ namespace: "ns-one", source_vm_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 7a8fab081..eae46c2b3 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.workspaces.getQuota();
+ return this.client.vms.getQuota();
}
// ── Domain / Slug checks ───────────────────────────────────────────────
@@ -199,7 +199,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
if (
!page ||
(this.workspaceId &&
- (page.source_workspace_id !== this.workspaceId ||
+ (page.source_vm_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, {
- workspace: this.scope.workspaceId,
+ vm: 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 ? { workspace: this.scope.workspaceId, port } : undefined,
+ root: port ? { vm: 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_workspace_id === this.workspaceId &&
+ page.source_vm_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, workspace: this.scope.workspaceId, port: hostPort! },
+ action: { kind: "proxy" as const, vm: this.scope.workspaceId, port: hostPort! },
},
],
};
@@ -375,7 +375,7 @@ export class CloudInfraProvider implements RoutingProvider, SslProvider {
}
const assertPage = () => {
if (
- page!.source_workspace_id !== this.workspaceId ||
+ page!.source_vm_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, {
- workspace_id: this.scope.workspaceId,
+ vm_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({
- workspace_id: this.scope.workspaceId,
+ vm_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.workspace === this.workspaceId &&
+ rule.action.vm === 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, { workspace_id: this.scope.workspaceId, path }))
+ !(await this.pages.deploy(slug, { vm_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<{ workspace: string; port: number }> {
+ ): Promise<{ vm: string; port: number }> {
return {
- workspace: this.scope.workspaceId,
+ vm: 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.workspace === this.workspaceId &&
+ route.action.vm === 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_workspace_id !== this.workspaceId ||
+ page.source_vm_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.workspace !== this.workspaceId ||
+ (route.action.vm !== 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.workspace(this.scope.workspaceId);
+ const workspace = this.client.vm(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_workspace_id?: string | null;
+ source_vm_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_workspace_id?.trim() ||
+ !page.source_vm_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_workspace_id !== this.workspaceId ||
+ page.source_vm_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/oblien-contract.test.ts b/packages/adapters/src/oblien-contract.test.ts
new file mode 100644
index 000000000..66507f17b
--- /dev/null
+++ b/packages/adapters/src/oblien-contract.test.ts
@@ -0,0 +1,169 @@
+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
new file mode 100644
index 000000000..0b0a5367d
--- /dev/null
+++ b/packages/adapters/src/oblien-contract.ts
@@ -0,0 +1,108 @@
+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 4068260b6..67d449c5b 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/workspace/ws-owned/stats/stream");
+ expect(url.href).toBe("https://api.oblien.com/v1/vms/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 52b806a6e..b3748bca9 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" }).workspaces.create({ wait_ready: false }).catch(error => error);
+ const error = await new Oblien({ token: "test" }).vms.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" }).workspaces.get("ws").catch(error => error);
+ const error = await new Oblien({ token: "test" }).vms.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/zone/mine");
+ expect(String(fetcher.mock.calls[0]?.[0])).toBe("https://api.oblien.com/v1/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.workspaces.create({ namespace: "tenant-a", wait_ready: false }).catch(error => error);
+ const error = await client.vms.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, workspace: { id: "not-created" } }, { status: 503 })));
- await expect(new Oblien({ token: "test" }).workspaces.create({ wait_ready: false })).rejects.toMatchObject({ status: 503 });
+ 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 });
});
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" }).workspaces.create({ wait_ready: false }),
+ new Oblien({ token: "test" }).vms.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, workspace: { id: "ws-a", namespace: "tenant-a" } }));
+ const fetcher = vi.fn(async () => Response.json({ success: true, vm: { id: "ws-a", namespace: "tenant-a" } }));
vi.stubGlobal("fetch", fetcher);
const client = new Oblien({ clientId: "test-owner", clientSecret: "test-secret" });
- await client.workspaces.create({ namespace: "tenant-a", cpus: 2, wait_ready: false });
+ await client.vms.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("/workspace"); expect(init.redirect).toBe("error"); expect(init.signal).toBeInstanceOf(AbortSignal);
+ expect(url.pathname).toBe("/v1/vms"); 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, workspaces: [] }); }));
+ vi.stubGlobal("fetch", vi.fn(async (_url, init) => { headers.push(new Headers(init.headers)); return Response.json({ success: true, vms: [] }); }));
const client = new Oblien({ clientId: "test-owner", clientSecret: "test-secret" });
- await client.workspaces.list(); client.setToken("namespace-token"); await client.workspaces.list(); client._http.restoreAuth(); await client.workspaces.list();
+ await client.vms.list(); client.setToken("namespace-token"); await client.vms.list(); client._http.restoreAuth(); await client.vms.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" }).workspaces.get("ws-b").catch(error => error);
+ const error = await new Oblien({ token: "test" }).vms.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" }).workspaces
+ const error = await new Oblien({ token: "test" }).vms
.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" }).workspaces
+ const error = await new Oblien({ token: "test" }).vms
.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" }).workspaces
+ const error = await new Oblien({ token: "test" }).vms
.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: {
- workspace_id: "ws-failed",
+ vm_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" }).workspaces
+ const error = await new Oblien({ token: "test" }).vms
.create({ wait_ready: false })
.catch((error) => error);
expect(error).toMatchObject({
status: 422,
code: "CREATE_FAILED",
- details: { workspace_id: "ws-failed" },
+ details: { vm_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" }).workspaces.get("ws-a").catch(error => error);
+ const error = await new Oblien({ token: "scoped-test-token" }).vms.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" }).workspaces.create({ wait_ready: false }, { signal: controller.signal })).rejects.toBe(reason);
+ await expect(new Oblien({ token: "test" }).vms.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" }).workspaces.create({ wait_ready: false }, { signal: controller.signal });
+ const pending = new Oblien({ token: "test" }).vms.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 530ad51ad..aabc70696 100644
--- a/packages/adapters/src/oblien.ts
+++ b/packages/adapters/src/oblien.ts
@@ -1,4 +1,5 @@
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 {
@@ -36,13 +37,13 @@ const resourceUnits = {
cpus: "vCPU",
memory_mb: "MB",
disk_size_mb: "MB",
- workspaces: "workspaces",
+ vms: "VMs",
} as const;
const resourceLabels = {
cpus: "CPU",
memory_mb: "RAM",
disk_size_mb: "Disk",
- workspaces: "Workspaces",
+ vms: "VMs",
} as const;
type CapacityViolation = {
resource: keyof typeof resourceUnits;
@@ -91,7 +92,7 @@ function namespaceCapacityDetails(raw: unknown) {
}
function workspaceIdFromDetails(details: unknown): string | undefined {
- const id = (details as { workspace_id?: unknown } | null)?.workspace_id;
+ const id = (details as { vm_id?: unknown } | null)?.vm_id;
return typeof id === "string" && /^[a-zA-Z0-9_-]{1,128}$/.test(id) ? id : undefined;
}
@@ -140,7 +141,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 ? { workspace_id: workspaceId } : {}),
+ ...(workspaceId ? { vm_id: workspaceId } : {}),
...(retryAfterSeconds !== undefined ? { retryAfterSeconds } : {}),
} : undefined;
const requestId =
@@ -153,7 +154,7 @@ function providerError(status: number, body: unknown, retryAfter: string | null
const scope =
value.enforcementScope === "namespace_allocated_pool"
? "namespace total"
- : value.resource === "workspaces"
+ : value.resource === "vms"
? "namespace workspace count"
: "per workspace";
return (
@@ -219,11 +220,7 @@ export class Oblien extends OblienSdk {
invalidate?(rejectedToken: string): Promise;
};
}) {
- 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)");
- }
+ const base = oblienApiBaseUrl(options.baseUrl);
super(options);
const original = new Headers();
if ("token" in options) { if (options.token) original.set("Authorization", `Bearer ${options.token}`); }
@@ -262,7 +259,7 @@ export class Oblien extends OblienSdk {
const renewal = ensureAuth();
if (renewal) await renewal;
subscriptionSignal.throwIfAborted();
- const url = new URL(`/workspace/${encodeURIComponent(workspaceId)}/stats/stream`, base);
+ const url = oblienApiUrl(base, `/vms/${encodeURIComponent(workspaceId)}/stats/stream`);
const headers = new Headers(auth);
headers.set("Accept", "text/event-stream");
const response = await fetch(url, { headers, redirect: "error", signal: subscriptionSignal });
@@ -271,7 +268,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 = new URL(request.path, base);
+ const url = oblienApiUrl(base, request.path);
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;
@@ -284,7 +281,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" && /^\/workspace\/?$/.test(url.pathname) &&
+ const waitingCreate = request.method === "POST" && /^\/vms\/?$/.test(request.path) &&
(request.body as { wait_ready?: boolean } | undefined)?.wait_ready !== false;
let response: Response;
let body: unknown;
@@ -323,18 +320,15 @@ export class Oblien extends OblienSdk {
}
return body as T;
}, { kind: "client" });
- // 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;
+ // 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);
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 as typeof response;
+ return workload;
};
}
}
diff --git a/packages/adapters/src/runtime/cloud-deploy-static.test.ts b/packages/adapters/src/runtime/cloud-deploy-static.test.ts
index 155b826e3..c06209b7a 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({ workspace_id: h.workspaceId, path: `${h.paths.routes}/site` }));
+ expect(h.pages.create).toHaveBeenCalledWith(expect.objectContaining({ vm_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", { workspace_id: h.workspaceId, path: `${h.paths.routes}/site` });
+ expect(h.pages.deploy).toHaveBeenLastCalledWith("site", { vm_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", {
- workspace_id: h.workspaceId,
+ vm_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 ae6213923..bca0b073f 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 = { 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() } };
+ 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() } };
});
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.workspaces.create).not.toHaveBeenCalled();
+ expect(fixture.client.vms.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.workspace).not.toHaveBeenCalled();
+ expect(fixture.client.vm).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.workspaces.create).not.toHaveBeenCalled();
+ expect(fixture.client.vms.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.workspace.mockReturnValue({ workloads: { list: async () => workloads } });
+ fixture.client.vm.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 ad9e34fb9..9be7fe688 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; 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 };
+ 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 };
pageRows.set(input.slug, page); return { page };
}),
enable: vi.fn(async () => ({ success: true })), connectDomain: vi.fn(), delete: vi.fn(async () => ({ success: true })),
};
- provider = { workspace: vi.fn(() => ws), workspaces: { get: ws.get, create: vi.fn(), delete: vi.fn() }, pages };
+ provider = { vm: vi.fn(() => ws), vms: { 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.workspaces.create).not.toHaveBeenCalled();
+ expect(provider.vms.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", workspace: "workspace-a", port: next.hostPortByContainerPort![8080] } })] }));
- expect(provider.workspaces.create).not.toHaveBeenCalled();
+ 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();
});
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_workspace_id: "workspace-other", exported_path: "/app" });
+ pageRows.set("project-a", { namespace: "namespace-a", source_vm_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.workspaces.create).not.toHaveBeenCalled();
+ expect(provider.vms.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_workspace_id = "workspace-other";
+ pageRows.get("project-a")!.source_vm_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_workspace_id: "workspace-other", exported_path: "/opt/openship/cloud-docker/routes/other" });
+ pageRows.set("other", { slug: "other", domain: "opsh.io", namespace: "namespace-a", source_vm_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.workspaces.create).not.toHaveBeenCalled();
+ expect(provider.vms.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 6f1023f13..7c3d33f17 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.workspaces.get(this.workspaceId);
+ const workspace = await this.client.vms.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.workspaces.get(this.workspaceId);
+ workspace = await this.client.vms.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.workspaces.get(this.workspaceId);
+ const workspace = await this.client.vms.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 3dd7ac665..a55a2dc8f 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.workspace(this.workspaceId);
+ return this.client.vm(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.workspaces.get(this.workspaceId);
+ const info = await this.client.vms.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.workspace(this.workspaceId).runtime({ force: true });
+ runtime = await this.client.vm(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.workspace(this.workspaceId);
+ const workspace = this.client.vm(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.workspace(this.workspaceId);
+ const ws = this.client.vm(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 a6cbca3c9..507616a0c 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 { WorkspaceHandle } from "oblien";
+import type { VMHandle } 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 4a4b7e426..421cf754b 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({ workspaces: { get } } as unknown as Oblien, "owned-vm", "tenant");
+ const waiting = waitForCloudDockerWorkspace({ vms: { 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({ workspaces: { get } } as unknown as Oblien, "vm", "tenant", { timeoutMs: 0 })).rejects.toThrow("still starting");
+ await expect(waitForCloudDockerWorkspace({ vms: { 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({ workspaces: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" });
+ await expect(waitForCloudDockerWorkspace({ vms: { 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({ workspaces: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toMatchObject({ code: "CLOUD_SERVER_IDENTITY_MISMATCH" });
+ await expect(waitForCloudDockerWorkspace({ vms: { 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({ workspaces: { get } } as unknown as Oblien, "vm", "tenant")).rejects.toThrow("existing disk");
+ await expect(waitForCloudDockerWorkspace({ vms: { 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({ workspaces: { get } } as unknown as Oblien, "vm", "tenant", { signal: AbortSignal.abort() })).rejects.toThrow();
+ await expect(waitForCloudDockerWorkspace({ vms: { 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 de1010f56..2daf9c604 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, WorkspaceData } from "oblien";
+import type { Oblien, VMData } from "oblien";
import { AppError } from "@repo/core";
-export function assertDockerWorkspaceOwner(workspace: WorkspaceData, namespace: string, workspaceId: string): void {
+export function assertDockerWorkspaceOwner(workspace: VMData, 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: WorkspaceData): void {
+export function assertCloudWorkspaceRunning(workspace: VMData): void {
const state = cloudWorkspaceStatus(workspace);
if (state === "running") return;
if (["stopped", "paused", "suspended"].includes(state))
@@ -35,7 +35,7 @@ export function assertCloudWorkspaceRunning(workspace: WorkspaceData): void {
export async function waitForCloudWorkspaceStopped(client: Oblien, workspaceId: string, namespace: string) {
const deadline = Date.now() + 60_000;
for (;;) {
- const workspace = await client.workspaces.get(workspaceId);
+ const workspace = await client.vms.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.workspaces.get(workspaceId);
+ const workspace = await client.vms.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 e6440d18e..627e4a124 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 { WorkspaceData, WorkspaceHandle } from "oblien";
+import type { VMData, VMHandle } 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: WorkspaceHandle,
+ workspace: VMHandle,
resources: WorkspaceResources,
- current?: WorkspaceData,
+ current?: VMData,
): Promise {
const before = current ?? (await workspace.get());
if (before.id !== workspace.id)
diff --git a/packages/adapters/src/runtime/oblien-routing.ts b/packages/adapters/src/runtime/oblien-routing.ts
index 6a232b1d1..542192084 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 `workspace`+`port`) vs. a literal external URL. */
+ * owned backend (→ Oblien `vm`+`port`) vs. a literal external URL. */
const BACKEND_SENTINEL = "oblien-backend://self";
-/** An owned Oblien workspace to reverse-proxy to. */
-export interface OblienWorkspaceTarget {
- workspace: string;
+/** An owned Oblien VM to reverse-proxy to. */
+export interface OblienVmTarget {
+ vm: 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?: OblienWorkspaceTarget;
+ root?: OblienVmTarget;
/** Backend workspace that path rewrites (e.g. `/api/*`) proxy to. */
- backend?: OblienWorkspaceTarget;
+ backend?: OblienVmTarget;
/** 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 {
+): RoutesInput & { routes: RouteRule[] } {
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 {
+): RoutesInput & { routes: RouteRule[] } {
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", workspace: owned.workspace, port: owned.port }
+ ? { kind: "proxy", vm: owned.vm, 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", workspace: ctx.root.workspace, port: ctx.root.port },
+ action: { kind: "proxy", vm: ctx.root.vm, port: ctx.root.port },
});
}
@@ -118,7 +118,7 @@ export function compileResolvedRoutingToOblien(
});
}
- const input: RoutesInput = { routes };
+ const input: RoutesInput & { routes: RouteRule[] } = { 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 f5a80b487..a630ce5a5 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 { WorkspaceHandle } from "oblien";
+import type { VMHandle } 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/mail/ensure-container-mail.test.ts b/packages/adapters/src/system/mail/ensure-container-mail.test.ts
index e9c66f8d6..0025e6c70 100644
--- a/packages/adapters/src/system/mail/ensure-container-mail.test.ts
+++ b/packages/adapters/src/system/mail/ensure-container-mail.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
buildMailRunCommand,
@@ -401,7 +401,8 @@ describe("ensureContainerMail swap", () => {
if (cmd.includes("/proc/net/tcp")) return PROC_LISTENING;
return "";
});
- const executor = { exec, streamExec, writeFile: vi.fn(async () => {}) } as never;
+ const readFile = vi.fn(async () => "FIRST_DOMAIN=mail.example.com\n");
+ const executor = { exec, streamExec, writeFile: vi.fn(async () => {}), readFile } as never;
await ensureContainerMail(executor, {
domain: "example.com",
@@ -416,6 +417,123 @@ describe("ensureContainerMail swap", () => {
});
});
+/** Update fixtures retain the installed credentials and run the whole swap. */
+function swapBox(engineEnv: string) {
+ const streamExec = vi.fn(async (_cmd: string) => ({ code: 0, output: "" }));
+ const writeFile = vi.fn(async (_path: string, _content: string, _opts?: { mode?: number }) => {});
+ const readFile = vi.fn(async (path: string) => {
+ if (path.endsWith("engine.env")) return engineEnv;
+ throw new Error("ENOENT");
+ });
+ const exec = vi.fn(async (cmd: string) => {
+ if (cmd.includes("opsh_uid=")) return "opsh_uid=0\nopsh_user=root\nopsh_sudo=n\n";
+ if (cmd.includes("{{json .Mounts}}"))
+ return `${"a".repeat(64)}\ttrue\t${JSON.stringify(
+ MAIL_CONTAINER_MOUNTS.map((m) => ({
+ Type: "bind",
+ Source: m.host,
+ Destination: m.container,
+ })),
+ )}`;
+ if (cmd.includes(STATE_PROBE)) return stateLine("ghcr.io/x/openship-mail:old");
+ if (cmd.includes("docker image inspect")) return "sha256:present\n";
+ if (cmd.includes("/proc/net/tcp")) return PROC_LISTENING;
+ return "";
+ });
+ const onLog = vi.fn();
+ return {
+ exec, readFile, writeFile, streamExec, onLog,
+ update: () => ensureContainerMail({ exec, streamExec, writeFile, readFile } as never, {
+ domain: "mail.example.com", secrets: {}, onLog,
+ }),
+ engineEnvWrites: () => writeFile.mock.calls.filter(([path]) => path.endsWith("engine.env")),
+ };
+}
+
+describe("ensureContainerMail carries explicit ignore-ip overrides across an update (GH-1768)", () => {
+ const KEY = "OPENSHIP_MAIL_F2B_IGNOREIP";
+ const ENV_BODY = "FIRST_DOMAIN=mail.example.com\nOPENSHIP_MAIL_DB_PORT=5433\nPGSQL_ROOT_PASSWD= retained#secret=one \n";
+
+ beforeEach(() => {
+ setDefaultMailImage("ghcr.io/x/openship-mail:pinned");
+ vi.stubEnv(KEY, undefined);
+ });
+ afterEach(() => vi.unstubAllEnvs());
+
+ it.each(["", `${KEY}=192.0.2.9\n`])("sets the override before replacement and retains credentials (previous=%s)", async previous => {
+ vi.stubEnv(KEY, "203.0.113.5 198.51.100.0/24");
+ const box = swapBox(`${ENV_BODY}${previous}`);
+ expect(await box.update()).toMatchObject({ updated: true, mailDown: false });
+ expect(box.engineEnvWrites()).toEqual([[
+ `${MAIL_HOST_STATE_DIR}/engine.env`,
+ `${ENV_BODY}${KEY}=203.0.113.5 198.51.100.0/24\n`,
+ { mode: 0o600 },
+ ]]);
+ expect(box.writeFile.mock.invocationCallOrder[0]).toBeLessThan(box.streamExec.mock.invocationCallOrder[0]!);
+ });
+
+ it("preserves each server's list without reading or rewriting credentials when the API variable is unset", async () => {
+ for (const addresses of ["192.0.2.9", "198.51.100.0/24"]) {
+ const box = swapBox(`${ENV_BODY}${KEY}=${addresses}\n`);
+ expect(await box.update()).toMatchObject({ updated: true });
+ expect(box.readFile).not.toHaveBeenCalled();
+ expect(box.writeFile).not.toHaveBeenCalled();
+ }
+ });
+
+ it.each(["", " "])("removes only the override when the API explicitly clears it (%j)", async configured => {
+ vi.stubEnv(KEY, configured);
+ const box = swapBox(`${ENV_BODY}${KEY}=192.0.2.9\n`);
+ expect(await box.update()).toMatchObject({ updated: true });
+ expect(box.engineEnvWrites()).toEqual([[`${MAIL_HOST_STATE_DIR}/engine.env`, ENV_BODY, { mode: 0o600 }]]);
+ });
+
+ it.each([
+ ["192.0.2.9", `${KEY}=192.0.2.9\n`],
+ ["", ""],
+ ])("does not rewrite the secret file when the override already agrees (%j)", async (configured, record) => {
+ vi.stubEnv(KEY, configured);
+ const box = swapBox(`${ENV_BODY}${record}`);
+ expect(await box.update()).toMatchObject({ updated: true });
+ expect(box.writeFile).not.toHaveBeenCalled();
+ });
+
+ it("reports a failed read and never replaces unknown credentials with an incomplete file", async () => {
+ vi.stubEnv(KEY, "192.0.2.9");
+ const box = swapBox(ENV_BODY);
+ box.readFile.mockRejectedValue(new Error("permission denied"));
+ expect(await box.update()).toMatchObject({ updated: true });
+ expect(box.writeFile).not.toHaveBeenCalled();
+ expect(box.onLog).toHaveBeenCalledWith(expect.objectContaining({ level: "warn", message: expect.stringMatching(/Could not update OPENSHIP_MAIL_F2B_IGNOREIP:.*permission denied/) }));
+ });
+
+ it("reports a failed write without silently claiming the exclusions were applied", async () => {
+ vi.stubEnv(KEY, "192.0.2.9");
+ const box = swapBox(ENV_BODY);
+ box.writeFile.mockRejectedValue(new Error("read-only filesystem"));
+ expect(await box.update()).toMatchObject({ updated: true });
+ expect(box.onLog).toHaveBeenCalledWith(expect.objectContaining({ level: "warn", message: expect.stringMatching(/Could not update OPENSHIP_MAIL_F2B_IGNOREIP:.*read-only filesystem/) }));
+ });
+
+ it("does not replace an empty retained file with missing database credentials", async () => {
+ vi.stubEnv(KEY, "192.0.2.9");
+ const box = swapBox("");
+ expect(await box.update()).toMatchObject({ updated: true });
+ expect(box.writeFile).not.toHaveBeenCalled();
+ expect(box.onLog).toHaveBeenCalledWith(expect.objectContaining({ level: "warn", message: expect.stringContaining("restore its credentials") }));
+ });
+
+ it("rejects injected environment records before writing and reports the validation failure", async () => {
+ vi.stubEnv(KEY, "192.0.2.9\nPGSQL_ROOT_PASSWD=injected");
+ const box = swapBox(ENV_BODY);
+ expect(await box.update()).toMatchObject({ updated: true });
+ expect(box.writeFile).not.toHaveBeenCalled();
+ expect(box.onLog).toHaveBeenCalledWith(expect.objectContaining({ level: "warn", message: expect.stringContaining("spans multiple lines") }));
+ expect(JSON.stringify(box.onLog.mock.calls)).not.toContain("retained#secret");
+ expect(JSON.stringify(box.onLog.mock.calls)).not.toContain("PGSQL_ROOT_PASSWD=injected");
+ });
+});
+
/**
* Env-file record injection (GHSA-x2xg-5h5f-j5m9, second-order).
*
diff --git a/packages/adapters/src/system/mail/ensure-container-mail.ts b/packages/adapters/src/system/mail/ensure-container-mail.ts
index 82798ed9f..7cba66808 100644
--- a/packages/adapters/src/system/mail/ensure-container-mail.ts
+++ b/packages/adapters/src/system/mail/ensure-container-mail.ts
@@ -342,6 +342,36 @@ async function readEnvFileValue(
return null;
}
+/** Apply an explicit API override without removing a server's own exclusions. */
+async function carryIgnoreIp(executor: CommandExecutor, onLog: SystemLogCallback): Promise {
+ const key = "OPENSHIP_MAIL_F2B_IGNOREIP";
+ const configured = process.env[key];
+ // Existing installations may configure different lists directly on each server.
+ if (configured === undefined) return;
+ const wanted = configured.trim();
+ try {
+ const host = await rootOrDegrade(executor, {
+ purpose: "Updating the mail engine's fail2ban exclusions",
+ consequence: "The exclusions may not be updated.",
+ report: message => onLog(log(message, "warn")),
+ });
+ const body = await host.readFile(ENGINE_ENV_FILE);
+ if (!body.trim()) throw new Error(`The retained ${ENGINE_ENV_FILE} is empty; restore its credentials before updating exclusions.`);
+ const records: Record = Object.create(null);
+ for (const line of body.split("\n")) {
+ const eq = line.indexOf("=");
+ if (eq > 0) records[line.slice(0, eq).trim()] = line.slice(eq + 1);
+ }
+ if (wanted ? records[key] === wanted : records[key] === undefined) return;
+ if (wanted) records[key] = wanted;
+ else delete records[key];
+ await writeEnvFile(host, ENGINE_ENV_FILE, records);
+ } catch (failure) {
+ observeCaughtError(failure, "adapters/system/mail/ensure-container-mail");
+ onLog(log(`Could not update ${key}: ${safeErrorMessage(failure)}`, "warn"));
+ }
+}
+
/**
* The superuser password an ALREADY-INITIALISED cluster is holding, or null if this is a
* first install.
@@ -656,6 +686,8 @@ export async function ensureContainerMail(
// dies on the client-side `--env-file` open, `swapManagedImage` rolls back through the
// same callback and dies identically, and a perfectly healthy engine gets reported as
// `mailDown` with nothing in the log pointing at permissions.
+ // Rewrite that record before the hand-over below, as root where the file is still root-owned.
+ await carryIgnoreIp(executor, onLog);
await handOverEnvFile(executor, ENGINE_ENV_FILE, onLog);
const start = makeMailStart(executor, container, opts);
diff --git a/packages/adapters/test/backup-empty-source-guard.test.ts b/packages/adapters/test/backup-empty-source-guard.test.ts
index 9edb63413..79fe65b46 100644
--- a/packages/adapters/test/backup-empty-source-guard.test.ts
+++ b/packages/adapters/test/backup-empty-source-guard.test.ts
@@ -1,138 +1,137 @@
-/**
- * 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.
- */
-
+/** Verified empty sources are valid; missing sources must never be created by capture. */
import { spawnSync } from "node:child_process";
-import { mkdtempSync, writeFileSync } from "node:fs";
+import { mkdtemp, rm, stat } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
-import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";
-import { FakeAttachStream, harness } from "./helpers/docker-helper-harness";
+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 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: "db",
- image: "postgres:16",
+ name: "optional-storage",
+ image: "alpine:3",
env: {},
- volumes: ["pgdata:/var/lib/postgresql/data"],
+ volumes: [],
containerId: null,
- projectSlug: "shop",
+ projectSlug: "backup-empty-regression",
namespaceVolumes: false,
};
-beforeEach(() => {
- attachControl.stream = new FakeAttachStream();
-});
-afterEach(() => {
- vi.restoreAllMocks();
-});
+const dockerAvailable = spawnSync("docker", ["info"], { stdio: "ignore" }).status === 0;
+const dockerRequired = process.env.RUN_DOCKER_E2E === "1";
-/** 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");
-}
+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}`);
-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");
+ 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 });
}
+ 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 });
});
- 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");
+ 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("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("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 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 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("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 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("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);
+ 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();
});
});
diff --git a/packages/adapters/test/backup-helper-logging.test.ts b/packages/adapters/test/backup-helper-logging.test.ts
index 2fd798dcf..a6d87db31 100644
--- a/packages/adapters/test/backup-helper-logging.test.ts
+++ b/packages/adapters/test/backup-helper-logging.test.ts
@@ -1,7 +1,6 @@
-import { describe, expect, it } from "vitest";
-import { readFileSync } from "node:fs";
-import { join, dirname } from "node:path";
-import { fileURLToPath } from "node:url";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import type { ServiceHandle } from "../src/backup/types";
+import { FakeAttachStream, harness } from "./helpers/docker-helper-harness";
/**
* The backup helper streams a volume's archive over `attach()`. With the
@@ -11,34 +10,45 @@ import { fileURLToPath } from "node:url";
* 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.
*
- * 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.
+ * Exercise the executor's actual helper configuration for each codec.
*/
-const executorSource = readFileSync(
- join(dirname(fileURLToPath(import.meta.url)), "../src/backup/executors/docker.ts"),
- "utf8",
-);
+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,
+};
describe("backup helper container", () => {
- 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/);
- });
+ 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);
+ },
+ );
});
diff --git a/packages/adapters/test/cloud-infra.test.ts b/packages/adapters/test/cloud-infra.test.ts
index 6fede0853..170cdb457 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_workspace_id", "exported_path"])("refuses cleanup after %s changes", async field => {
+ it.each(["source_vm_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 c2d1b7605..98284162c 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_workspace_id = workspaceId;
+ h.records.get("app")!.source_vm_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_workspace_id: "another-workspace" },
+ { source_vm_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_workspace_id: null,
+ source_vm_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 54acc5406..fd82d80a5 100644
--- a/packages/adapters/test/helpers/docker-helper-harness.ts
+++ b/packages/adapters/test/helpers/docker-helper-harness.ts
@@ -135,6 +135,7 @@ 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 5521a4611..6123076b7 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; 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}` };
+ 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}` };
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, workspace: vi.fn(() => workspace) } as unknown as Oblien;
+ const client = { pages, routes, domain, vm: 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 2f29cc418..dbaf58071 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: { workspace: "ws_backend", port: 3000 } },
+ { staticPage: "my-frontend", backend: { vm: "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", workspace: "ws_backend", port: 3000 },
+ action: { kind: "proxy", vm: "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: { workspace: "ws_frontend", port: 8080 }, backend: { workspace: "ws_backend", port: 3000 } },
+ { root: { vm: "ws_frontend", port: 8080 }, backend: { vm: "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", workspace: "ws_backend", port: 3000 } },
- { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_frontend", port: 8080 } },
+ { 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 } },
]);
});
it("builds a server-only table (root workspace backs everything)", () => {
- const input = compileRoutingToOblien({}, { root: { workspace: "ws_api", port: 8080 } });
+ const input = compileRoutingToOblien({}, { root: { vm: "ws_api", port: 8080 } });
expect(input.routes).toEqual([
- { match: { path: "/", type: "prefix" }, action: { kind: "proxy", workspace: "ws_api", port: 8080 } },
+ { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "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: { workspace: "ws_backend", port: 3000 } },
+ { backend: { vm: "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: { workspace: "ws_app", port: 8080 } },
+ { root: { vm: "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", workspace: "ws_app", port: 8080 } },
+ { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "ws_app", port: 8080 } },
]);
});
@@ -101,7 +101,7 @@ describe("compileRoutingToOblien", () => {
{ source: "/docs/(.*)", destination: "/documentation/$1" },
],
},
- { root: { workspace: "ws_app", port: 8080 } },
+ { root: { vm: "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", workspace: "ws_app", port: 8080 } },
+ { match: { path: "/", type: "prefix" }, action: { kind: "proxy", vm: "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: { workspace: "ws_backend", port: 3000 } },
+ { backend: { vm: "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: { workspace: "app", port: 8080 } })).not.toHaveProperty("spa");
+ expect(compileRoutingToOblien({ spaFallback }, { root: { vm: "app", port: 8080 } })).not.toHaveProperty("spa");
});
});
diff --git a/packages/adapters/tsconfig.json b/packages/adapters/tsconfig.json
index a22f17e3d..cc2e306d2 100644
--- a/packages/adapters/tsconfig.json
+++ b/packages/adapters/tsconfig.json
@@ -6,6 +6,6 @@
"types": ["node"],
"outDir": "dist"
},
- "include": ["src/**/*.ts"],
+ "include": ["src/**/*.ts", "scripts/verify-cloud-docker.ts", "scripts/verify-cloud-isolation.ts"],
"exclude": ["node_modules", "dist"]
}
diff --git a/packages/contracts/src/deployments.ts b/packages/contracts/src/deployments.ts
index 05b0d73e4..254f540ca 100644
--- a/packages/contracts/src/deployments.ts
+++ b/packages/contracts/src/deployments.ts
@@ -97,7 +97,7 @@ export const DeploymentSchema = Type.Object({
updatedAt: Type.String(),
isActive: Type.Optional(Type.Boolean()),
projectName: Type.Optional(Type.String()),
- favicon: Type.Optional(Type.Union([Type.String(), Type.Null()])),
+ iconUrl: Type.Optional(Type.Union([Type.String(), Type.Null()])),
});
export type Deployment = Static;
diff --git a/packages/contracts/src/platform-migration.ts b/packages/contracts/src/platform-migration.ts
index 267209c63..9d2ec55c9 100644
--- a/packages/contracts/src/platform-migration.ts
+++ b/packages/contracts/src/platform-migration.ts
@@ -72,6 +72,7 @@ export const PlatformMigrationPlanSchema = Type.Object({
planId: id,
provider,
projectName: text,
+ projects: Type.Optional(Type.Array(Type.Object({ name: text, serviceIds: Type.Array(id) }))),
environmentName: text,
targetServerId: id,
services: Type.Array(PlatformImportServiceSchema),
diff --git a/packages/contracts/src/project-inputs.ts b/packages/contracts/src/project-inputs.ts
index d75ad8545..bfa89184c 100644
--- a/packages/contracts/src/project-inputs.ts
+++ b/packages/contracts/src/project-inputs.ts
@@ -8,6 +8,7 @@ import { Type, type Static, type TLiteral } from "@sinclair/typebox";
import { GitHubDeploymentChecksSchema } from "./deployment-checks";
import {
STACK_IDS,
+ MAX_IMAGE_URL_LENGTH,
RUNTIME_VERSION_PATTERN,
RUNTIME_VERSION_MAX_LENGTH,
ALL_PACKAGE_MANAGERS,
@@ -559,7 +560,10 @@ export const CreateProjectBody = Type.Object({
// `serverId` is create/ensure-only. Keeping it out of the generic PATCH body is
// also what keeps PROJECT_UPDATE_KEYS from becoming a target-retargeting path.
-export const UpdateProjectBody = Type.Partial(Type.Omit(CreateProjectBody, ["serverId"]));
+export const UpdateProjectBody = Type.Object({
+ ...Type.Partial(Type.Omit(CreateProjectBody, ["serverId"])).properties,
+ iconUrl: Type.Optional(Type.Union([Type.String({ maxLength: MAX_IMAGE_URL_LENGTH }), Type.Null()])),
+});
/**
* POST /projects/ensure — CreateProjectBody plus an optional `projectId` to
diff --git a/packages/contracts/src/project-integrations.ts b/packages/contracts/src/project-integrations.ts
index 5b8f4797e..93a8c3551 100644
--- a/packages/contracts/src/project-integrations.ts
+++ b/packages/contracts/src/project-integrations.ts
@@ -55,18 +55,21 @@ export const ProjectEdgeConfigSchema = Type.Object({
})),
});
+export const ProjectConnectionCandidateSchema = Type.Object({
+ id: Type.String(),
+ name: Type.String(),
+ description: Type.String(),
+ appTemplateId: nullableString,
+ iconUrl: Type.Optional(nullableString),
+ framework: Type.Optional(nullableString),
+ clusterId: Type.Optional(nullableString),
+});
+export type ProjectConnectionCandidate = Static;
+
export const ProjectIntegrationSchemas = {
listConnectionCandidates: {
action: "write",
- output: Type.Array(
- Type.Object({
- id: Type.String(),
- name: Type.String(),
- description: Type.String(),
- appTemplateId: nullableString,
- clusterId: Type.Optional(nullableString),
- }),
- ),
+ output: Type.Array(ProjectConnectionCandidateSchema),
},
listConnections: { action: "read", output: Type.Array(ProjectConnectionSchema) },
listConnectionConsumers: { action: "read", output: Type.Array(ProjectConnectionConsumerSchema) },
diff --git a/packages/contracts/src/projects.ts b/packages/contracts/src/projects.ts
index 41eb79398..6204f1de6 100644
--- a/packages/contracts/src/projects.ts
+++ b/packages/contracts/src/projects.ts
@@ -14,6 +14,7 @@ export const ProjectSchema = Type.Object({
groupId: Type.String({ minLength: 1 }),
name: Type.String(),
slug: Type.String(),
+ iconUrl: Type.Optional(nullableString()),
createdAt: Type.String(),
updatedAt: Type.String(),
environmentName: Type.Optional(Type.String()),
diff --git a/packages/core/src/apps/catalog.json b/packages/core/src/apps/catalog.json
index 8b5151aa4..856f2ad0c 100644
--- a/packages/core/src/apps/catalog.json
+++ b/packages/core/src/apps/catalog.json
@@ -4177,7 +4177,7 @@
"services": [
{
"name": "umami",
- "image": "ghcr.io/umami-software/umami:postgresql-v2.20.2",
+ "image": "ghcr.io/umami-software/umami:3.4.1",
"exposedPort": 3000,
"exposed": true,
"routes": [
diff --git a/packages/core/src/apps/catalog/umami.json b/packages/core/src/apps/catalog/umami.json
index 24cbb8d6a..0325382e9 100644
--- a/packages/core/src/apps/catalog/umami.json
+++ b/packages/core/src/apps/catalog/umami.json
@@ -17,7 +17,7 @@
"services": [
{
"name": "umami",
- "image": "ghcr.io/umami-software/umami:postgresql-v2.20.2",
+ "image": "ghcr.io/umami-software/umami:3.4.1",
"exposedPort": 3000,
"exposed": true,
"routes": [
diff --git a/packages/core/src/apps/umami.test.ts b/packages/core/src/apps/umami.test.ts
index 1fc02cab8..2494a20b3 100644
--- a/packages/core/src/apps/umami.test.ts
+++ b/packages/core/src/apps/umami.test.ts
@@ -2,17 +2,21 @@ import { describe, expect, it } from "vitest";
import { getAppTemplate } from "../app-templates";
describe("Umami catalog security update", () => {
- it("uses the security-patched v2 PostgreSQL release", () => {
+ it("uses the security-patched v3 PostgreSQL release", () => {
const umami = getAppTemplate("umami");
const image = umami?.services?.find((service) => service.name === "umami")?.image;
- const version = image?.match(/^ghcr\.io\/umami-software\/umami:postgresql-v2\.(\d+)\.(\d+)$/);
+ // v3 dropped the `postgresql-` tag prefix and MySQL support. The catalog
+ // already runs PostgreSQL and the container auto-applies Prisma migrations
+ // on start, so the pinned v3 image is a reviewed major upgrade. Moving off
+ // v3 needs a new migration review.
+ const version = image?.match(/^ghcr\.io\/umami-software\/umami:3\.(\d+)\.(\d+)$/);
expect(
version,
- "Use an official patched v2 image; a major upgrade needs a migration review",
+ "Use an official patched v3 image; a major upgrade needs a migration review",
).toBeTruthy();
const [, minor, patch] = version!;
- // v2.20.2 carries the Next.js / React Server Components security fixes.
- expect(Number(minor) > 20 || (Number(minor) === 20 && Number(patch) >= 2)).toBe(true);
+ // v3.4.1 carries the Next.js 16.4.2 / React 19.3.1 security fixes.
+ expect(Number(minor) > 4 || (Number(minor) === 4 && Number(patch) >= 1)).toBe(true);
});
it("preserves the existing database, volume, and generated secret contract", () => {
diff --git a/packages/core/src/errors.ts b/packages/core/src/errors.ts
index b9b9067ef..0974f072b 100644
--- a/packages/core/src/errors.ts
+++ b/packages/core/src/errors.ts
@@ -72,6 +72,7 @@ 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/image-url.test.ts b/packages/core/src/image-url.test.ts
new file mode 100644
index 000000000..79a613338
--- /dev/null
+++ b/packages/core/src/image-url.test.ts
@@ -0,0 +1,25 @@
+import { describe, expect, it } from "vitest";
+import { isImageUrl, MAX_IMAGE_URL_LENGTH } from "./image-url";
+
+describe("display image URLs", () => {
+ it.each([
+ "https://cdn.example.test/avatar.png?v=2",
+ "http://images.example.test/icon.svg",
+ "https://example.test/a%20b.png",
+ ])("accepts %s", (url) => expect(isImageUrl(url)).toBe(true));
+ it.each([
+ null,
+ 123,
+ "",
+ "/icon.png",
+ "//example.test/icon",
+ "javascript:alert(1)",
+ "data:image/svg+xml, ",
+ "file:///etc/passwd",
+ "blob:https://example.test/id",
+ "https://user:password@example.test/a.png",
+ "https://example.test/\nimage.png",
+ " https://example.test/image.png",
+ `https://example.test/${"a".repeat(MAX_IMAGE_URL_LENGTH)}`,
+ ])("refuses unsafe or malformed input %j", (url) => expect(isImageUrl(url)).toBe(false));
+});
diff --git a/packages/core/src/image-url.ts b/packages/core/src/image-url.ts
new file mode 100644
index 000000000..137c1d4a6
--- /dev/null
+++ b/packages/core/src/image-url.ts
@@ -0,0 +1,23 @@
+/** Image URLs are displayed by the browser, never fetched by the control plane. */
+export const MAX_IMAGE_URL_LENGTH = 2048;
+
+export function isImageUrl(value: unknown): value is string {
+ if (
+ typeof value !== "string" ||
+ !/^https?:\/\//i.test(value) ||
+ value.length > MAX_IMAGE_URL_LENGTH ||
+ /[\u0000-\u0020\u007f]/.test(value)
+ )
+ return false;
+ try {
+ const url = new URL(value);
+ return (
+ (url.protocol === "https:" || url.protocol === "http:") &&
+ !!url.hostname &&
+ !url.username &&
+ !url.password
+ );
+ } catch {
+ return false;
+ }
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index fa306c0a2..2c33b6c39 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -1,4 +1,5 @@
export * from "./types";
+export * from "./image-url";
export * from "./docker-swarm";
export * from "./actions";
export * from "./action-capabilities";
diff --git a/packages/core/src/pricing/README.md b/packages/core/src/pricing/README.md
index 030d2ffe2..d8c27e084 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 displays the monthly equivalent
-and full annual charge together; the selected interval is sent through checkout.
+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.
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 fca460ce1..a17513c74 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": "/yr",
+ "perYear": "/year",
"custom": "Custom",
"free": "Free",
"unlimited": "Unlimited",
diff --git a/packages/db/drizzle/0231_project_icon_url.sql b/packages/db/drizzle/0231_project_icon_url.sql
new file mode 100644
index 000000000..5ecc9e5f7
--- /dev/null
+++ b/packages/db/drizzle/0231_project_icon_url.sql
@@ -0,0 +1 @@
+ALTER TABLE "project" ADD COLUMN IF NOT EXISTS "icon_url" text;
diff --git a/packages/db/drizzle/0232_project_icon_cleanup.sql b/packages/db/drizzle/0232_project_icon_cleanup.sql
new file mode 100644
index 000000000..9ba00e56a
--- /dev/null
+++ b/packages/db/drizzle/0232_project_icon_cleanup.sql
@@ -0,0 +1,17 @@
+-- Preserve saved images before retiring automatic favicon discovery.
+-- An explicit icon always wins; projects without one retain their existing image.
+UPDATE "project"
+SET "icon_url" = COALESCE(
+ "icon_url",
+ "favicon",
+ (SELECT "favicon" FROM "project_app" WHERE "id" = "project"."app_id")
+)
+WHERE "icon_url" IS NULL;
+--> statement-breakpoint
+ALTER TABLE "project" DROP COLUMN IF EXISTS "favicon";
+--> statement-breakpoint
+ALTER TABLE "project" DROP COLUMN IF EXISTS "favicon_checked_at";
+--> statement-breakpoint
+ALTER TABLE "project_app" DROP COLUMN IF EXISTS "favicon";
+--> statement-breakpoint
+ALTER TABLE "project_app" DROP COLUMN IF EXISTS "favicon_checked_at";
diff --git a/packages/db/drizzle/meta/_journal.json b/packages/db/drizzle/meta/_journal.json
index d7a930769..71b3a5a43 100644
--- a/packages/db/drizzle/meta/_journal.json
+++ b/packages/db/drizzle/meta/_journal.json
@@ -1618,6 +1618,20 @@
"when": 1794373201000,
"tag": "0230_restore_workspace_security_fields",
"breakpoints": true
+ },
+ {
+ "idx": 231,
+ "version": "7",
+ "when": 1794373202000,
+ "tag": "0231_project_icon_url",
+ "breakpoints": true
+ },
+ {
+ "idx": 232,
+ "version": "7",
+ "when": 1794373203000,
+ "tag": "0232_project_icon_cleanup",
+ "breakpoints": true
}
]
}
diff --git a/packages/db/src/dump-roundtrip.test.ts b/packages/db/src/dump-roundtrip.test.ts
index de514bf69..a2637d446 100644
--- a/packages/db/src/dump-roundtrip.test.ts
+++ b/packages/db/src/dump-roundtrip.test.ts
@@ -274,6 +274,35 @@ describe("whole-instance dump → restore round trip", () => {
},
);
+ it.each(["legacy", "group", "custom", "cleared"] as const)(
+ "restores %s project images into the single iconUrl field",
+ async (mode) => {
+ const original = await dumpSubgraph({ kind: "instance" });
+ const archive = JSON.parse(JSON.stringify(original)) as typeof original;
+ const project = archive.tables.project![0]!;
+ project.favicon = "https://old.example.test/favicon.ico";
+ project.faviconCheckedAt = "2026-11-01T12:00:00Z";
+ const group = archive.tables.project_app!.find((row) => row.id === project.groupId)!;
+ group.favicon = "https://cdn.example.test/group.svg";
+ if (mode === "custom") project.iconUrl = "https://cdn.example.test/custom.svg";
+ else if (mode === "cleared") project.iconUrl = null;
+ else delete project.iconUrl;
+ if (mode === "group") project.favicon = null;
+ const expected = mode === "custom" ? project.iconUrl : mode === "cleared" ? null : mode === "group" ? group.favicon : project.favicon;
+ try {
+ await restoreSubgraph(archive, { mode: "wipe" });
+ const restored = await dumpSubgraph({ kind: "instance" });
+ expect(restored.tables.project![0]!.iconUrl).toBe(expected);
+ expect(restored.tables.project![0]).not.toHaveProperty("favicon");
+ expect(restored.tables.project![0]).not.toHaveProperty("faviconCheckedAt");
+ expect(restored.tables.project_app![0]).not.toHaveProperty("favicon");
+ expect(project.faviconCheckedAt).toBe("2026-11-01T12:00:00Z");
+ } finally {
+ await restoreSubgraph(original, { mode: "wipe" });
+ }
+ },
+ );
+
it("lets callers include follow-up work in the same atomic restore transaction", async () => {
const projectSpec = topoOrderedTables().find((s) => s.sqlName === "project")!;
const [before] = (await db.select().from(projectSpec.table)) as Array>;
diff --git a/packages/db/src/dump.ts b/packages/db/src/dump.ts
index cd320b1c9..731d8d9ba 100644
--- a/packages/db/src/dump.ts
+++ b/packages/db/src/dump.ts
@@ -1773,6 +1773,11 @@ export async function restoreSubgraphInTransaction(
}
}
+ // Resolve legacy image inheritance once for large instance archives.
+ const legacyGroupIcons = new Map(
+ (dump.tables.project_app ?? []).map((group) => [group.id, group.favicon]),
+ );
+
// Pre-compute the encrypted-column specs keyed by table so the insert
// loop below can redact those fields without re-scanning ENCRYPTED_COLUMNS
// per row. Redaction on restore is REQUIRED (not optional like the
@@ -1835,6 +1840,11 @@ export async function restoreSubgraphInTransaction(
const prepared = rows.map((r) => {
const { row: next, dropped } = filterRowToKnownColumns(r, knownCols);
for (const d of dropped) droppedCols.add(d);
+ // Archives from before iconUrl used a discovered favicon. Honor an explicit
+ // iconUrl (including a cleared null) when the archive already has the field.
+ if (spec.sqlName === "project" && !Object.hasOwn(r, "iconUrl")) {
+ next.iconUrl = r.favicon ?? legacyGroupIcons.get(r.groupId) ?? null;
+ }
// Older instance dumps predate per-factor confirmation. Preserve active
// authenticators while keeping unfinished enrollments unconfirmed.
if (spec.sqlName === "two_factor" && !Object.hasOwn(r, "verified")) {
diff --git a/packages/db/src/migrate-chain.test.ts b/packages/db/src/migrate-chain.test.ts
index 6c50eecbb..de5aaf92b 100644
--- a/packages/db/src/migrate-chain.test.ts
+++ b/packages/db/src/migrate-chain.test.ts
@@ -268,6 +268,47 @@ describe("migration chain applies to an existing, populated database", () => {
expect(await appliedMigrations(client)).toBe(total);
});
+ test("consolidates saved images into icon_url and preserves explicit icons and resets on retry", async () => {
+ const cutoff = journal.entries.findIndex((entry) => entry.tag === "0232_project_icon_cleanup");
+ expect(journal.entries[cutoff - 1]?.tag).toBe("0231_project_icon_url");
+ const legacy = migrationsPrefix(cutoff);
+ const { client, db } = await freshDb();
+ try {
+ await migrate(db, { migrationsFolder: legacy });
+ await client.exec(`
+ INSERT INTO organization (id, name) VALUES ('org', 'Existing organization');
+ INSERT INTO project_app (id, organization_id, name, slug, favicon) VALUES
+ ('group', 'org', 'Apps', 'apps', NULL),
+ ('group-icon', 'org', 'Group image', 'group-image', 'https://cdn.example.test/group.svg');
+ INSERT INTO project (id, organization_id, app_id, environment_slug, name, slug, favicon, icon_url) VALUES
+ ('legacy', 'org', 'group', 'legacy', 'Legacy', 'legacy', 'https://app.example.test/favicon.ico', NULL),
+ ('custom', 'org', 'group', 'custom', 'Custom', 'custom', 'https://old.example.test/favicon.ico', 'https://cdn.example.test/custom.svg'),
+ ('empty', 'org', 'group', 'empty', 'Empty', 'empty', NULL, NULL),
+ ('inherited', 'org', 'group-icon', 'inherited', 'Inherited', 'inherited', NULL, NULL);
+ `);
+ const projects = (await client.query>("SELECT * FROM project ORDER BY id")).rows;
+ const groups = (await client.query>("SELECT * FROM project_app ORDER BY id")).rows;
+ await migrate(db, { migrationsFolder: MIGRATIONS_DIR });
+ expect((await client.query("SELECT * FROM project ORDER BY id")).rows).toEqual(
+ projects.map(({ favicon, favicon_checked_at: _, ...project }) => ({
+ ...project,
+ icon_url: project.icon_url ?? favicon ?? (project.app_id === "group-icon" ? "https://cdn.example.test/group.svg" : null),
+ })),
+ );
+ expect((await client.query("SELECT * FROM project_app ORDER BY id")).rows).toEqual(
+ groups.map(({ favicon: _, favicon_checked_at: _checked, ...group }) => group),
+ );
+ await client.exec("UPDATE project SET icon_url = NULL WHERE id = 'legacy'");
+ const customized = (await client.query("SELECT * FROM project ORDER BY id")).rows;
+ await migrate(db, { migrationsFolder: MIGRATIONS_DIR });
+ expect((await client.query("SELECT * FROM project ORDER BY id")).rows).toEqual(customized);
+ expect(await appliedMigrations(client)).toBe(total);
+ } finally {
+ await client.close();
+ rmSync(legacy, { recursive: true, force: true });
+ }
+ });
+
test("adds runtime roles after the applied lifecycle migration without changing existing releases", async () => {
const cutoff = journal.entries.findIndex((entry) => entry.tag === "0192_runtime_roles");
expect(journal.entries[cutoff - 1]?.tag).toBe("0191_project_lifecycle_operation");
@@ -286,7 +327,7 @@ describe("migration chain applies to an existing, populated database", () => {
await migrate(db, { migrationsFolder: MIGRATIONS_DIR });
expect((await client.query("SELECT * FROM project")).rows).toEqual(
- projects.map((project) => ({ ...project, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false })),
+ projects.map(({ favicon, favicon_checked_at: _, ...project }) => ({ ...project, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false, icon_url: favicon })),
);
expect((await client.query("SELECT * FROM deployment")).rows).toEqual(
deployments.map((deployment) => ({
@@ -332,7 +373,7 @@ describe("migration chain applies to an existing, populated database", () => {
expect(await db.select().from(schema.instanceController)).toEqual([]);
expect(await db.select().from(schema.instanceHandoff)).toEqual([]);
expect((await client.query("SELECT * FROM project")).rows).toEqual(
- projects.map((project) => ({ ...project, github_checks: null, runtime_version: null, runtime_image: null, lifecycle_operation: null, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false })),
+ projects.map(({ favicon, favicon_checked_at: _, ...project }) => ({ ...project, github_checks: null, runtime_version: null, runtime_image: null, lifecycle_operation: null, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null, auto_deploy_cancel_builds: false, icon_url: favicon })),
);
expect(
(await client.query("SELECT * FROM drizzle.__drizzle_migrations ORDER BY id")).rows.slice(
@@ -530,11 +571,12 @@ describe("migration chain applies to an existing, populated database", () => {
expect(managed).toHaveLength(2);
for (const row of (await selectProjects()).rows) {
const old = original.find((project) => project.id === row.id)!;
- const { cloud_workspace_id: _native, cloud_archive_strategy: _archive, ...previous } = old as typeof old & Record;
+ const { cloud_workspace_id: _native, cloud_archive_strategy: _archive, favicon, favicon_checked_at: _checked, ...previous } = old as typeof old & Record;
expect(row).toEqual({
...previous,
runtime_version: null, runtime_image: null, roles: null, preview_settings: null, preview_scanned_at: null, build_cache_receipts: null,
auto_deploy_cancel_builds: false,
+ icon_url: favicon,
cloud_promotion: null,
lifecycle_operation: null,
cloud_static_hosting: "pages",
diff --git a/packages/db/src/repos/deployment.repo.ts b/packages/db/src/repos/deployment.repo.ts
index add5653d8..9defd12db 100644
--- a/packages/db/src/repos/deployment.repo.ts
+++ b/packages/db/src/repos/deployment.repo.ts
@@ -626,7 +626,7 @@ export function createDeploymentRepo(db: Database, encryption: ConfigurationEncr
async listHistoryProjects(organizationId: string) {
return db.selectDistinct({
id: project.id, name: project.name,
- activeDeploymentId: project.activeDeploymentId, favicon: project.favicon,
+ activeDeploymentId: project.activeDeploymentId, iconUrl: project.iconUrl,
}).from(project).innerJoin(deployment, eq(deployment.projectId, project.id))
.where(and(eq(project.organizationId, organizationId), eq(deployment.organizationId, organizationId)))
.orderBy(project.name, project.id);
diff --git a/packages/db/src/repos/project.repo.ts b/packages/db/src/repos/project.repo.ts
index ffe4aa891..4488d9649 100644
--- a/packages/db/src/repos/project.repo.ts
+++ b/packages/db/src/repos/project.repo.ts
@@ -661,25 +661,6 @@ export function createProjectRepo(db: Database, encryption: ConfigurationEncrypt
}).where(eq(project.id, id));
},
- /** Update favicon cache metadata without touching the user-visible updatedAt field. */
- async updateFaviconCache(
- id: string,
- data: { favicon?: string | null; faviconCheckedAt?: Date | null },
- ) {
- const patch: Partial = {};
-
- if (Object.prototype.hasOwnProperty.call(data, "favicon")) {
- patch.favicon = data.favicon ?? null;
- }
- if (Object.prototype.hasOwnProperty.call(data, "faviconCheckedAt")) {
- patch.faviconCheckedAt = data.faviconCheckedAt ?? null;
- }
-
- if (Object.keys(patch).length === 0) return;
-
- await db.update(project).set(patch).where(eq(project.id, id));
- },
-
/** Soft-delete a project */
async softDelete(id: string) {
await withProjectConfigurationWrite(db, eq(project.id, id), async (tx) => tx
diff --git a/packages/db/src/schema/project.ts b/packages/db/src/schema/project.ts
index 023ae9fe3..098ae3a3d 100644
--- a/packages/db/src/schema/project.ts
+++ b/packages/db/src/schema/project.ts
@@ -69,10 +69,6 @@ export const projectGroup = pgTable("project_app", {
gitUrl: text("git_url"),
installationId: integer("installation_id"),
- /** Shared favicon cache */
- favicon: text("favicon"),
- faviconCheckedAt: timestamp("favicon_checked_at"),
-
deletedAt: timestamp("deleted_at"),
createdAt: timestamp("created_at").notNull().defaultNow(),
updatedAt: timestamp("updated_at").notNull().defaultNow(),
@@ -499,10 +495,8 @@ export const project = pgTable(
* nobody opted into paying for this, so nobody keeps paying for it silently.
*/
collectPaths: boolean("collect_paths").notNull().default(false),
- /** Auto-detected favicon URL from the deployed site */
- favicon: text("favicon"),
- /** Last time favicon detection was attempted for this project */
- faviconCheckedAt: timestamp("favicon_checked_at"),
+ /** Project display image, managed in project settings. */
+ iconUrl: text("icon_url"),
/** Soft delete */
deletedAt: timestamp("deleted_at"),
/**
diff --git a/packages/platform/src/authorization.ts b/packages/platform/src/authorization.ts
index ec818a7db..1411936e1 100644
--- a/packages/platform/src/authorization.ts
+++ b/packages/platform/src/authorization.ts
@@ -99,7 +99,8 @@ export interface AuthorizationDependencies {
}
export interface PermissionOptions {
- roleOverride?: ContextRole;
+ /** A credential may narrow membership authority to its own grants. */
+ roleOverride?: "restricted";
grants?: PermissionGrantSource;
}
@@ -118,14 +119,15 @@ export const PROJECT_ROOTED: ReadonlySet = new Set([
"build_session",
]);
-/** Shared with capability discovery; restricted roles use grants instead. */
+/** Shared role ceiling for execution and discovery; restricted roles use grants. */
export function roleAllowsResourceType(
role: "owner" | "admin" | "member",
type: CheckedResourceType,
+ action: Permission,
): boolean {
if (role === "owner") return true;
if (role === "admin") return type !== "billing";
- return type !== "billing" && type !== "audit";
+ return action !== "admin" && type !== "billing" && type !== "audit";
}
export function permitsAction(permissions: readonly GrantPermission[], action: Permission): boolean {
@@ -262,10 +264,12 @@ export function createAuthorization(deps: AuthorizationDependencies) {
if (!["read", "write", "admin", "create"].includes(input.action)) return false;
const persistedRole = membershipRole(member);
if (!persistedRole) return false;
- const role = opts?.roleOverride ?? persistedRole;
- if (role === "owner" || role === "admin" || role === "member")
- return roleAllowsResourceType(role, input.resourceType);
- if (role !== "restricted") 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 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 fe6eb4b37..1be661c5a 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().default("https://api.oblien.com"),
- OBLIEN_RUNTIME_URL: z.url().default("https://workspace.oblien.com"),
+ OBLIEN_API_URL: z.url().optional(),
+ OBLIEN_RUNTIME_URL: z.url().default("https://vm.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 dd1d25a48..b51d75b0c 100644
--- a/packages/platform/src/engine/lib/auth.ts
+++ b/packages/platform/src/engine/lib/auth.ts
@@ -1,3 +1,4 @@
+import { isImageUrl } from "@repo/core";
import { diagnostics as errorDiagnostics } from "@repo/core/diagnostics";
import { organizationOptions, isSaasDeployment } from "./organization-lifecycle";
import { betterAuth, type User } from "better-auth";
@@ -17,6 +18,7 @@ import {
resetPasswordOtpEmail,
verifyEmailTemplate,
verifyOtpEmailTemplate,
+ existingAccountEmail,
} from "./email-templates";
import { provisionUser } from "./provision-user";
import { oidcOAuthPlugin } from "./oidc";
@@ -176,6 +178,23 @@ 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);
@@ -260,6 +279,14 @@ export const auth = betterAuth({
/* ---------- Database hooks ---------- */
databaseHooks: {
user: {
+ update: {
+ before: async (user) => {
+ if (user.image === undefined) return;
+ const image = typeof user.image === "string" ? user.image.trim() || null : user.image;
+ if (image !== null && !isImageUrl(image)) throw new APIError("BAD_REQUEST", { message: "Avatar URL must be an HTTP or HTTPS URL without credentials." });
+ return { data: { ...user, image } };
+ },
+ },
create: {
before: async (user, ctx) => {
const denyCreation = (message: string): never => {
diff --git a/packages/platform/src/engine/lib/cloud-capacity.ts b/packages/platform/src/engine/lib/cloud-capacity.ts
index c651a5934..3c4696c2c 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().workspaces.get(workspaceId);
+ const workspace = await getOblienClient().vms.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 b946e6500..65b9334d1 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.workspaces.list({ page, limit: 100 });
- const matches = result.workspaces.filter(
+ const result = await client.vms.list({ page, limit: 100 });
+ const matches = result.vms.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.workspaces.length || page * result.limit >= result.total) return found;
+ if (!result.vms.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.workspace(input.workspaceId);
+ const ws = input.client.vm(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.workspaces
+ const workspace = await client.vms
.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.workspaces.get(failure.workspaceId);
+ const created = await client.vms.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.workspace(workspaceId);
+ const ws = client.vm(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.workspaces.retryCreation(workspaceId);
+ const retried = await client.vms.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 8515d80d3..b3256be79 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, type CloudInfraProvider } from "@repo/adapters";
+import { createPlatform, oblienApiBaseUrl, 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: env.OBLIEN_API_URL,
+ cloudApiUrl: oblienApiBaseUrl(env.OBLIEN_API_URL).toString(),
});
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 64455831a..eac0f264c 100644
--- a/packages/platform/src/engine/lib/cloud-resource-limits.ts
+++ b/packages/platform/src/engine/lib/cloud-resource-limits.ts
@@ -1,6 +1,7 @@
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;
@@ -10,8 +11,8 @@ export function cloudNamespaceLimits(tier: PlanTierId) {
return { ...resolvePlan(tier).oblienLimits };
}
-export async function initialCloudNamespaceLimits(): Promise {
- return cloudNamespaceLimits("free");
+export async function initialCloudNamespaceLimits() {
+ return toOblienVmLimits(cloudNamespaceLimits("free"));
}
/** Submit the verified subscription's declared policy under the billing lock.
@@ -25,13 +26,14 @@ 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: Partial | null | undefined) =>
- (Object.keys(desired) as Array).every(key => (limits?.[key] ?? null) === desired[key]);
+ const matches = (limits: NamespaceResourceLimits | null | undefined) =>
+ (Object.keys(providerLimits) as Array).every(key => (limits?.[key] ?? null) === providerLimits[key]);
if (matches(current.resource_limits)) return;
- const { data: updated } = await client.namespaces.update(current.id, { resource_limits: { ...desired } });
+ const { data: updated } = await client.namespaces.update(current.id, { resource_limits: providerLimits });
if (updated.slug !== namespace || !matches(updated.resource_limits)) {
throw new AppError("Cloud resource limits were not confirmed", 502, "CLOUD_RESOURCE_LIMITS_UNCONFIRMED");
}
@@ -39,13 +41,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_workspaces: z.number().nonnegative().nullable(),
+ effective_resource_limits: z.object({ max_vms: 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({ workspaces: z.number().nonnegative(), vcpus: z.number().nonnegative(),
+ allocated_resource_usage: z.object({ vms: z.number().nonnegative(), vcpus: z.number().nonnegative(),
ram_mb: z.number().nonnegative(), disk_gb: z.number().nonnegative(), pending_updates: z.number().int().nonnegative() }).optional(),
}) });
@@ -63,7 +65,7 @@ function presentCapacity(data: Awaited>
const limits = data.effective_resource_limits, used = data.allocated_resource_usage;
if (!limits || !used) return {};
return {
- workspaces: { used: used.workspaces, max: limits.max_workspaces },
+ workspaces: { used: used.vms, max: limits.max_vms },
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 8be2b268f..f7f0b032b 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.workspaces.get(id);
+ const workspace = await admin.vms.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.workspace_id);
+ await requireWorkspace(input.vm_id);
await assertCloudCanSpend(organizationId, workspaceId);
return admin.pages.create({ ...input, namespace });
},
deploy: async (slug, input) => {
await requirePage(slug);
- await requireWorkspace(input.workspace_id);
+ await requireWorkspace(input.vm_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.workspace) {
+ if (rule.action.origin || !rule.action.vm) {
throw new AppError("Cloud routes must target a workspace in this organization", 400, "CLOUD_ROUTE_TARGET_INVALID");
}
- workspaces.add(rule.action.workspace);
+ workspaces.add(rule.action.vm);
}
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 2ca3a9305..cd3175dc9 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.workspaces.get(connection.workspaceId);
+ const workspace = await client.vms.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.workspace(binding.workspaceId!).runtime(options), binding.workspaceId!);
+ return new CloudWorkspaceExecutor(options => client.vm(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.workspace(binding.workspaceId!).runtime(options), binding.workspaceId!);
+ const executor = new CloudWorkspaceExecutor(options => client.vm(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 62284ce18..20a1679e6 100644
--- a/packages/platform/src/engine/lib/cloud/project-promotion.ts
+++ b/packages/platform/src/engine/lib/cloud/project-promotion.ts
@@ -45,8 +45,6 @@ export function projectPromotionDigest(dump: DatabaseDump): string {
delete row.deletionInProgress;
delete row.lifecycleOperation;
delete row.updatedAt;
- delete row.favicon;
- delete row.faviconCheckedAt;
}
for (const [name, rows] of Object.entries(tables)) {
tables[name] = rows
diff --git a/packages/platform/src/engine/lib/cloud/types.ts b/packages/platform/src/engine/lib/cloud/types.ts
index bc667d548..530b6a914 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: {
- workspace_id: string;
+ vm_id: string;
path: string;
name: string;
slug: string;
diff --git a/packages/platform/src/engine/lib/email-templates.ts b/packages/platform/src/engine/lib/email-templates.ts
index 14ed7b579..ab2a4525e 100644
--- a/packages/platform/src/engine/lib/email-templates.ts
+++ b/packages/platform/src/engine/lib/email-templates.ts
@@ -117,6 +117,27 @@ export function verifyEmailTemplate(user: { name?: string | null; email: string
};
}
+/** A signup retry must not disclose account existence in the HTTP response. */
+export function existingAccountEmail(
+ user: { name?: string | null; email: string },
+ dashboardUrl: string,
+) {
+ const login = new URL("/login", dashboardUrl).href;
+ const reset = new URL("/forgot-password", dashboardUrl).href;
+ return {
+ subject: "Sign in to your OpenShip account",
+ html: layout(`
+ ${greeting(user.name)}
+ You already have an OpenShip account. This signup attempt did not create another account or change your password.
+ Sign in with your existing password, or use Google or GitHub if that is how you registered.
+ ${ctaButton(htmlEscape(login), "Sign in")}
+ To set or reset a password, request a password reset code .
+ If you did not request this email, you can ignore it. Your account has not changed.
+ `),
+ text: `Hi ${user.name || "there"},\n\nYou already have an OpenShip account. This signup attempt did not create another account or change your password.\n\nSign in with your existing password, or use Google or GitHub if that is how you registered: ${login}\n\nTo set or reset a password, request a reset code: ${reset}\n\nIf you did not request this email, you can ignore it. Your account has not changed.`,
+ };
+}
+
/* ------------------------------------------------------------------ */
/* OTP codes (no links, for deliverability): verification + reset */
/* ------------------------------------------------------------------ */
diff --git a/packages/platform/src/engine/lib/favicon-detector.ts b/packages/platform/src/engine/lib/favicon-detector.ts
deleted file mode 100644
index f0eb03024..000000000
--- a/packages/platform/src/engine/lib/favicon-detector.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-/**
- * Favicon detection - check if a deployed site has a favicon.
- *
- * Called asynchronously on project reads when the favicon cache is stale.
- * Simply checks /favicon.ico - the universal standard.
- *
- * Returns an absolute URL string or null.
- */
-
-import { reportCaughtError as observeCaughtError } from "@repo/core/diagnostics";
-import { repos } from "@repo/db";
-import { env } from "../config/env";
-import { safeFetch } from "./safe-fetch";
-import { trackBackgroundWork } from "./background-work";
-
-const FETCH_TIMEOUT = 8_000;
-const FAVICON_REFRESH_TTL_MS = 24 * 60 * 60 * 1000;
-const inFlightRefreshes = new Set();
-
-interface FaviconRefreshProject {
- id: string;
- slug?: string | null;
- activeDeploymentId?: string | null;
- favicon?: string | null;
- faviconCheckedAt?: Date | string | null;
-}
-
-interface RefreshOptions {
- hostname?: string | null;
-}
-
-function normalizeSiteUrl(siteUrlOrHostname: string): string {
- const trimmed = siteUrlOrHostname.trim().replace(/\/$/, "");
- if (!trimmed) return "";
- if (/^https?:\/\//i.test(trimmed)) return trimmed;
- return `https://${trimmed}`;
-}
-
-function isRefreshDue(project: FaviconRefreshProject): boolean {
- if (!project.faviconCheckedAt) return true;
-
- const checkedAt = new Date(project.faviconCheckedAt);
- if (Number.isNaN(checkedAt.getTime())) return true;
-
- return Date.now() - checkedAt.getTime() >= FAVICON_REFRESH_TTL_MS;
-}
-
-async function resolvePreferredSiteUrl(
- project: FaviconRefreshProject,
- options?: RefreshOptions,
-): Promise {
- if (options?.hostname?.trim()) {
- return normalizeSiteUrl(options.hostname);
- }
-
- const primaryDomain = await repos.domain.getPrimaryByProject(project.id);
- if (primaryDomain?.verified && primaryDomain.hostname?.trim()) {
- return normalizeSiteUrl(primaryDomain.hostname);
- }
-
- return null;
-}
-
-async function probeFavicon(siteUrl: string): Promise {
- const base = normalizeSiteUrl(siteUrl);
- if (!base) return null;
-
- const faviconUrl = `${base}/favicon.ico`;
-
- const tryProbe = async (method: "HEAD" | "GET") => {
- // SSRF-safe: `base` is a project's (attacker-controllable-DNS) domain. Pin the
- // resolved IP; reject internal targets on the multi-tenant SaaS, allow the
- // operator's own LAN on self-hosted.
- const res = await safeFetch(faviconUrl, {
- method,
- timeoutMs: FETCH_TIMEOUT,
- allowHttp: true,
- allowPrivate: !env.CLOUD_MODE,
- maxRedirects: 3,
- });
-
- if (!res.ok) {
- return null;
- }
-
- const ct = res.headers["content-type"] ?? "";
- if (ct.startsWith("image/") || ct === "application/octet-stream") {
- return faviconUrl;
- }
-
- return null;
- };
-
- const headResult = await tryProbe("HEAD");
- if (headResult) {
- return headResult;
- }
-
- const getResult = await tryProbe("GET");
- if (getResult) {
- return getResult;
- }
-
- return null;
-}
-
-export function refreshProjectFaviconIfStale(
- project: FaviconRefreshProject,
- options?: RefreshOptions,
-): void {
- if (!project.activeDeploymentId || !isRefreshDue(project)) {
- return;
- }
-
- if (inFlightRefreshes.has(project.id)) {
- return;
- }
-
- inFlightRefreshes.add(project.id);
- void trackBackgroundWork((async () => {
- const siteUrl = await resolvePreferredSiteUrl(project, options);
- if (!siteUrl) {
- return;
- }
-
- await detectAndStoreFavicon(project.id, siteUrl);
- })()
- .catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "platform/engine/lib/favicon-detector"); return undefined; })
- .finally(() => {
- inFlightRefreshes.delete(project.id);
- }));
-}
-
-/**
- * Detect and store the favicon for a deployed project.
- * Best-effort: update the cache timestamp on every attempt, but only replace
- * the stored favicon URL when the fetch succeeds.
- */
-export async function detectAndStoreFavicon(projectId: string, siteUrl: string): Promise {
- const checkedAt = new Date();
-
- try {
- const faviconUrl = await probeFavicon(siteUrl);
- if (faviconUrl) {
- await repos.project.updateFaviconCache(projectId, {
- favicon: faviconUrl,
- faviconCheckedAt: checkedAt,
- });
- return;
- }
- } catch (diagnosticFailure) {
- observeCaughtError(diagnosticFailure, "platform/engine/lib/favicon-detector");
- // Best-effort - don't break anything if this fails
- }
-
- await repos.project.updateFaviconCache(projectId, {
- faviconCheckedAt: checkedAt,
- }).catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "platform/engine/lib/favicon-detector"); return undefined; });
-}
diff --git a/packages/platform/src/engine/lib/oblien-billing-api.ts b/packages/platform/src/engine/lib/oblien-billing-api.ts
index e8b612c25..6d9e7ee50 100644
--- a/packages/platform/src/engine/lib/oblien-billing-api.ts
+++ b/packages/platform/src/engine/lib/oblien-billing-api.ts
@@ -3,7 +3,7 @@ import { withDiagnosticSpan } from "@repo/core/diagnostics/node";
import { z } from "zod";
import { AppError } from "@repo/core";
import { OperationError } from "@repo/contracts";
-import { Oblien } from "@repo/adapters";
+import { Oblien, oblienApiBaseUrl, oblienApiUrl, toOblienVmOffer, toOblienVmPolicy, cloudBillingContract } from "@repo/adapters";
import { isDeepStrictEqual } from "node:util";
import { computeBillingModeSchema, oblienCapacityCatalogSchema, oblienCapacityPoolSchema, oblienNamespaceCapacitySchema } from "./oblien-capacity";
@@ -197,7 +197,7 @@ export type OblienPlanChangeQuote = z.infer;
export type OblienPlanChange = z.infer;
const policySchema = z.object({
- success: z.literal(true), service: z.literal("workspace_vm"),
+ success: z.literal(true), service: z.literal("vm_compute"),
quotaLimit: allowance, overdraft: amount.nonnegative(),
onOverdraftAction: z.enum(["stop_workspaces", "block"]), suspendThreshold: allowance,
});
@@ -231,12 +231,13 @@ export function assertOblienEntitlementMatchesSubscription(entitlement: OblienEn
const monthly = subscription?.offer?.billingMode === "monthly";
const expectedTier = monthly ? "capacity" : subscription?.tierId ?? "free";
const capacity = entitlement.capacity;
- // An unpaid renewal advances Stripe's invoice period without buying another
- // month of compute. The retained, expired capacity still describes the last
- // funded period. Keep billing readable so the customer can pay, while the
- // provider's uncovered entitlement continues to block new billable work.
+ // Stripe can advance an active subscription's period while its renewal invoice
+ // is still a draft, before attempting payment. An overdue renewal has the same
+ // period split: expired capacity describes the last funded month. Accept this
+ // uncovered state for billing/management reads without granting compute or
+ // inventing a grace period; billable work still requires provider coverage.
const unpaidRenewal = monthly && subscription &&
- ["past_due", "unpaid", "paused", "canceled"].includes(subscription.status) &&
+ ["active", "past_due", "unpaid", "paused", "canceled"].includes(subscription.status) &&
entitlement.status !== "active" && entitlement.computeCovered === false &&
capacity?.computeCovered === false && capacity.status === "expired" &&
entitlement.periodStart !== null && entitlement.periodEnd !== null &&
@@ -314,11 +315,7 @@ export class OblienBillingApi {
clientId?: string; clientSecret?: string; baseUrl?: string;
fetch?: typeof fetch; timeoutMs?: number;
} = {}) {
- const url = new URL(options.baseUrl ?? "https://api.oblien.com");
- if (url.username || url.password || url.search || url.hash ||
- (url.protocol !== "https:" && !(url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname)))) {
- throw new Error("Oblien API URL must use HTTPS (HTTP is allowed for localhost tests)");
- }
+ const url = oblienApiBaseUrl(options.baseUrl);
this.baseUrl = url.toString().replace(/\/+$/, "");
this.fetcher = options.fetch ?? fetch;
// The SDK has no client-wide fetch/timeout option. Replace this transport
@@ -336,7 +333,7 @@ export class OblienBillingApi {
private async requestBilling({ method, path, body, query }: Parameters[0]): Promise {
const meteredPricing = method === "GET" && path === "/pricing/calculator";
if (!path.startsWith("/billing/") && !meteredPricing) throw new Error("Billing transport only accepts billing routes");
- const url = new URL(`${this.baseUrl}${path}`);
+ const url = oblienApiUrl(oblienApiBaseUrl(this.baseUrl), path);
for (const [key, value] of Object.entries(query ?? {})) {
if (value !== undefined) url.searchParams.set(key, String(value));
}
@@ -466,7 +463,7 @@ export class OblienBillingApi {
...(Object.keys(diagnostic).length ? { details: diagnostic } : {}),
});
}
- return payload as T;
+ return cloudBillingContract(payload) as T;
}
private async validate(response: Promise, schema: z.ZodType, slug?: string): Promise {
@@ -612,7 +609,7 @@ export class OblienBillingApi {
/** Mode A only: the complimentary-plan service owns these explicit grants. */
setPolicy(slug: string, input: Pick) {
- return this.validate(this.billing.setPolicy(slug, input), policySchema.extend({ namespace }), slug);
+ return this.validate(this.billing.setPolicy(slug, toOblienVmPolicy(input)), policySchema.extend({ namespace }), slug);
}
resetQuota(slug: string, periodEnd: string) {
@@ -641,9 +638,10 @@ export class OblienBillingApi {
async previewPlanChange(slug: string, input: OblienPlanChangeInput) {
const request = oblienPlanChangeInputSchema.parse(input);
+ const offer = toOblienVmOffer(request.offer);
const result = await this.validate(request.offer.billingMode === "service"
- ? this.request({ method: "POST", path: "/billing/subscription/changes/preview", body: { namespace: slug, ...request } })
- : this.billing.previewPlanChange(slug, { ...request, offer: { ...request.offer, billingMode: request.offer.billingMode } }), z.object({
+ ? this.request({ method: "POST", path: "/billing/subscription/changes/preview", body: { namespace: slug, ...request, offer } })
+ : this.billing.previewPlanChange(slug, { ...request, offer: { ...offer, billingMode: request.offer.billingMode } }), z.object({
success: z.literal(true), namespace, quote: oblienPlanChangeQuoteSchema,
}), slug);
if (result.quote.namespace !== slug || result.quote.billingInterval !== input.billingInterval)
@@ -691,9 +689,10 @@ export class OblienBillingApi {
// and this saved namespace offer before creating the Stripe session.
const parsed = oblienCheckoutInputSchema.parse(input);
const request = { ...parsed, allowPromotionCodes: parsed.offer?.unitAmount !== 0 };
+ const offer = request.offer ? toOblienVmOffer(request.offer) : undefined;
const result = await this.validate((request.offer?.billingMode === "service" || (request.kind === "subscription" && !!request.affiliateBuyer))
- ? this.request({ method: "POST", path: "/billing/checkout", body: request })
- : this.billing.checkout({ ...request, offer: request.offer ? { ...request.offer, billingMode: request.offer.billingMode === "monthly" ? "monthly" : request.offer.billingMode === "payg" ? "payg" : undefined } : undefined }), checkoutSchema);
+ ? this.request({ method: "POST", path: "/billing/checkout", body: { ...request, offer } })
+ : this.billing.checkout({ ...request, offer: offer ? { ...offer, billingMode: request.offer?.billingMode === "monthly" ? "monthly" : request.offer?.billingMode === "payg" ? "payg" : undefined } : undefined }), checkoutSchema);
this.validateCheckoutUrl(result.url);
return result;
}
@@ -702,6 +701,7 @@ export class OblienBillingApi {
const url = new URL(value);
if (url.hostname === "api.oblien.com") {
this.validateHostedUrl(value, "api.oblien.com");
+ // This is the hosted browser page, not a versioned control-plane endpoint.
if (url.pathname === "/billing/pay" && !url.search && /^#[A-Za-z0-9_-]{43}$/.test(url.hash)) return;
throw new AppError("Cloud billing returned an invalid hosted URL", 502, "OBLIEN_BILLING_INVALID_RESPONSE");
}
diff --git a/packages/platform/src/engine/lib/oblien-namespace.ts b/packages/platform/src/engine/lib/oblien-namespace.ts
index 850b79330..a387bd59b 100644
--- a/packages/platform/src/engine/lib/oblien-namespace.ts
+++ b/packages/platform/src/engine/lib/oblien-namespace.ts
@@ -1,4 +1,5 @@
-import { AppError, type OblienLimits } from "@repo/core";
+import { AppError } from "@repo/core";
+import type { NamespaceResourceLimits } from "@repo/adapters";
import { getOblienClient } from "./oblien-client";
import { ensureOblienDefaultQuota } from "../modules/billing/billing-oblien-quota";
@@ -7,7 +8,7 @@ import { ensureOblienDefaultQuota } from "../modules/billing/billing-oblien-quot
export async function ensureCloudNamespace(input: {
name: string;
slug: string;
- resource_limits: OblienLimits;
+ resource_limits: NamespaceResourceLimits;
}): Promise {
await ensureOblienDefaultQuota();
const ensured = await getOblienClient().namespaces.ensure(input);
diff --git a/packages/platform/src/engine/lib/openship-cloud.ts b/packages/platform/src/engine/lib/openship-cloud.ts
index 6552d0582..2cb6d116c 100644
--- a/packages/platform/src/engine/lib/openship-cloud.ts
+++ b/packages/platform/src/engine/lib/openship-cloud.ts
@@ -5,7 +5,7 @@
*/
import { diagnostics as errorDiagnostics } from "@repo/core/diagnostics";
import { createHash } from "node:crypto";
-import { Oblien, OblienError } from "@repo/adapters";
+import { Oblien, OblienError, oblienApiBaseUrl } from "@repo/adapters";
import { OperationError } from "@repo/contracts";
import { AppError, safeErrorMessage } from "@repo/core";
import { repos } from "@repo/db";
@@ -108,7 +108,7 @@ export async function issueNamespaceToken(organizationId: string, workspaceId?:
const namespace = await ensureNamespaceWithQuota(organizationId, workspaceId);
try {
const result = await getOblienClient().tokens.create({ scope: "namespace", namespace, ttl: 1800 });
- return { token: result.token, namespace, expiresAt: result.expiresAt, providerApiUrl: env.OBLIEN_API_URL };
+ return { token: result.token, namespace, expiresAt: result.expiresAt, providerApiUrl: oblienApiBaseUrl(env.OBLIEN_API_URL).toString() };
} catch (error) {
errorDiagnostics.warn("platform/engine/lib/openship-cloud", `[oblien] token issuance failed for org ${organizationId}: ${safeErrorMessage(error)}`, error);
if (error instanceof OblienError && typeof error.status === "number" && [429, 502, 503, 504].includes(error.status)) {
@@ -130,7 +130,7 @@ async function internalNamespaceToken(organizationId: string, workspaceId?: Clou
// Authorization is always read before cache lookup. A token cache must never
// turn a deleted/moved workspace into access granted by an earlier request.
const namespace = await ensureNamespaceWithQuota(organizationId, workspaceId);
- const key = namespaceTokenKey(organizationId, namespace, env.OBLIEN_API_URL);
+ const key = namespaceTokenKey(organizationId, namespace, oblienApiBaseUrl(env.OBLIEN_API_URL).toString());
const store = await cacheStore("oblien-internal-tokens", { maxSize: 10_000 });
const readFresh = async () => {
const cached = await store.get(key);
@@ -142,7 +142,7 @@ async function internalNamespaceToken(organizationId: string, workspaceId?: Clou
const renewed = await readFresh();
if (renewed) return renewed;
const credentials = await issueNamespaceToken(organizationId, workspaceId);
- if (credentials.namespace !== namespace || credentials.providerApiUrl !== env.OBLIEN_API_URL)
+ if (credentials.namespace !== namespace || credentials.providerApiUrl !== oblienApiBaseUrl(env.OBLIEN_API_URL).toString())
throw new AppError("Cloud execution ownership changed", 409, "CLOUD_NAMESPACE_MISMATCH");
const ttl = Math.floor((Date.parse(credentials.expiresAt) - Date.now() - 60_000) / 1000);
if (!credentials.token || !Number.isFinite(ttl) || ttl <= 0)
diff --git a/packages/platform/src/engine/lib/public-endpoints.ts b/packages/platform/src/engine/lib/public-endpoints.ts
index 91b900d5d..01f05dd69 100644
--- a/packages/platform/src/engine/lib/public-endpoints.ts
+++ b/packages/platform/src/engine/lib/public-endpoints.ts
@@ -982,7 +982,7 @@ export interface ProjectAccess {
/** The project's ONE canonical public domain row, chosen over ALL rows
* (project-level AND service-scoped): a verified primary, else the first
* verified row, else none. The single primary-selection rule the detail Access
- * URL, the list card's primaryDomain, and the favicon refresh all share, so
+ * URL and the list card's primaryDomain share, so
* those surfaces can never disagree on which domain is "the" one. */
export function pickCanonicalDomainRow & { hostname?: string }>(
rows: T[] | null | undefined,
diff --git a/packages/platform/src/engine/modules/actions/billing-namespace.ts b/packages/platform/src/engine/modules/actions/billing-namespace.ts
index afb9e861c..c7cf99aae 100644
--- a/packages/platform/src/engine/modules/actions/billing-namespace.ts
+++ b/packages/platform/src/engine/modules/actions/billing-namespace.ts
@@ -30,7 +30,7 @@ export async function ensureActionsBillingNamespace(organizationId: string): Pro
// Preparing checkout must not permit compute before paid runner setup.
// These initial caps do not replace an existing namespace's limits.
resource_limits: {
- max_workspaces: 0,
+ max_vms: 0,
max_vcpus: 0,
max_ram_mb: 0,
max_disk_gb: 0,
@@ -79,7 +79,7 @@ export async function ensureFundedActionRunners(organizationId: string): Promise
disk: Math.max(...runners.map((r) => r.diskGb)),
};
const limits = {
- max_workspaces: maxParallel,
+ max_vms: maxParallel,
max_vcpus: maximum.cpu,
max_ram_mb: maximum.memory,
max_disk_gb: maximum.disk,
diff --git a/packages/platform/src/engine/modules/actions/cloud-runner.test.ts b/packages/platform/src/engine/modules/actions/cloud-runner.test.ts
index 1390c3d64..7679d3099 100644
--- a/packages/platform/src/engine/modules/actions/cloud-runner.test.ts
+++ b/packages/platform/src/engine/modules/actions/cloud-runner.test.ts
@@ -30,7 +30,7 @@ vi.mock("@repo/adapters", async (original) => ({
prepare = state.prepare;
},
Oblien: class {
- workspaces = {
+ vms = {
create: state.create,
get: state.get,
delete: state.remove,
diff --git a/packages/platform/src/engine/modules/actions/cloud-runner.ts b/packages/platform/src/engine/modules/actions/cloud-runner.ts
index ee84aad79..6079ce3da 100644
--- a/packages/platform/src/engine/modules/actions/cloud-runner.ts
+++ b/packages/platform/src/engine/modules/actions/cloud-runner.ts
@@ -268,8 +268,8 @@ export async function openCloudActionWorker(
let workspace;
try {
workspace = job.providerWorkspaceId
- ? await client.workspaces.get(job.providerWorkspaceId)
- : await client.workspaces.create(workspaceInput(job, runner));
+ ? await client.vms.get(job.providerWorkspaceId)
+ : await client.vms.create(workspaceInput(job, runner));
} catch (error) {
if (job.providerWorkspaceId && isMissing(error))
throw new AppError(
@@ -318,7 +318,7 @@ export async function openCloudActionWorker(
}
if (workspace.ready === false || !["active", "running"].includes(status)) return null;
const executor = new CloudWorkspaceExecutor(
- options => client.workspace(workspace.id).runtime(options),
+ options => client.vm(workspace.id).runtime(options),
workspace.id,
);
try {
@@ -333,7 +333,7 @@ export async function openCloudActionWorker(
// The authenticated Runtime API gateway needs host ingress. Enabling the
// API adds its port but does not enable that firewall path. Restrict this
// disposable VM to the API port; do not expose SSH or workflow services.
- await client.workspaces.network.update(workspace.id, {
+ await client.vms.network.update(workspace.id, {
public_access: true,
ingress_ports: [9990],
});
@@ -386,8 +386,8 @@ export async function removeCloudActionWorker(
// An uncertain create is resolved with its ORIGINAL key and config. No new
// key, image, resources or paid purchase is introduced by cleanup retries.
const workspace = job.providerWorkspaceId
- ? await client.workspaces.get(job.providerWorkspaceId)
- : await client.workspaces.create(workspaceInput(job, runner));
+ ? await client.vms.get(job.providerWorkspaceId)
+ : await client.vms.create(workspaceInput(job, runner));
assertWorkspace(workspace, job, runner);
if (!job.providerWorkspaceId) {
const saved = await update({
@@ -396,9 +396,9 @@ export async function removeCloudActionWorker(
if (!saved) throw new Error("Actions lease changed before worker cleanup");
job = saved;
}
- await client.workspaces.delete(workspace.id);
+ await client.vms.delete(workspace.id);
try {
- await client.workspaces.get(workspace.id);
+ await client.vms.get(workspace.id);
// Deletion is asynchronous. Keep the scheduler slot and poll on the
// next tick without replacing the workflow result with a cleanup error.
return false;
diff --git a/packages/platform/src/engine/modules/actions/triggers.test.ts b/packages/platform/src/engine/modules/actions/triggers.test.ts
index c00d616ec..a4d9b95d8 100644
--- a/packages/platform/src/engine/modules/actions/triggers.test.ts
+++ b/packages/platform/src/engine/modules/actions/triggers.test.ts
@@ -33,6 +33,7 @@ vi.mock("./action.service", () => ({
rerunActionWorkflow: h.rerun,
}));
import { dispatchActionWebhook, enqueueActionWebhook } from "./triggers";
+import { GitHubApiError } from "../github/github.error";
const base = "a".repeat(40),
head = "b".repeat(40),
@@ -80,6 +81,7 @@ beforeEach(() => {
owner: "acme",
repo: "app",
path: ".github/workflows/ci.yml",
+ source: null,
authority: {},
allowForks: true,
},
@@ -96,6 +98,66 @@ beforeEach(() => {
const dispatch = (value = event()) =>
dispatchActionWebhook("pull_request", value, "delivery", target);
+it.each(["push", "pull_request"])(
+ "ignores a workflow absent at the %s revision",
+ async (eventName) => {
+ h.file.mockRejectedValueOnce(new GitHubApiError(404, "Not Found", new Headers()));
+ const revision = eventName === "push" ? head : base;
+ h.fetch.mockImplementationOnce(async ({ url }) => {
+ if (url === `https://api.github.com/repos/acme/app/commits/${revision}`)
+ return { sha: revision };
+ throw new Error(`Unexpected GitHub request: ${url}`);
+ });
+ await dispatchActionWebhook(
+ eventName,
+ eventName === "push" ? { ...event(), ref: "refs/heads/other", after: head } : event(),
+ "delivery",
+ target,
+ );
+ expect(h.trigger).not.toHaveBeenCalled();
+ expect(h.error).toHaveBeenCalledExactlyOnceWith("org", "workflow", null);
+ },
+);
+
+it.each([403, 429, 500])("retains workflow source failures from GitHub (%s)", async (status) => {
+ const error = new GitHubApiError(status, "Unavailable", new Headers());
+ h.file.mockRejectedValueOnce(error);
+ await expect(dispatch()).rejects.toThrow(error);
+ expect(h.trigger).not.toHaveBeenCalled();
+ expect(h.error).toHaveBeenCalledWith("org", "workflow", error.message);
+});
+
+it("retains a missing revision or inaccessible repository as a workflow error", async () => {
+ const error = new GitHubApiError(404, "Not Found", new Headers());
+ h.file.mockRejectedValueOnce(error);
+ h.fetch.mockRejectedValueOnce(error);
+ await expect(dispatch()).rejects.toThrow(error);
+ expect(h.trigger).not.toHaveBeenCalled();
+ expect(h.error).toHaveBeenCalledWith("org", "workflow", error.message);
+});
+
+it("uses the pushed workflow's branch rules rather than the saved definition", async () => {
+ const workflows = await h.workflows();
+ workflows[0].definition = { triggers: { push: { branches: ["main"] } } };
+ h.file.mockResolvedValueOnce({
+ content: source.replace(
+ "pull_request:\n types: [opened, reopened, synchronize, closed]",
+ "push:\n branches: [deploy/**]",
+ ),
+ });
+ await dispatchActionWebhook(
+ "push",
+ { ...event(), ref: "refs/heads/deploy/topic", after: head },
+ "delivery",
+ target,
+ );
+ expect(h.trigger).toHaveBeenCalledOnce();
+ expect(h.trigger.mock.calls[0]![2]).toMatchObject({
+ revision: head,
+ ref: "refs/heads/deploy/topic",
+ });
+});
+
it("routes GitHub-owned events to the exact workflow without storing webhook payloads", async () => {
h.workflows.mockResolvedValueOnce([
{ ...target, id: "first", controller: "github", githubWorkflowId: "123" },
diff --git a/packages/platform/src/engine/modules/actions/triggers.ts b/packages/platform/src/engine/modules/actions/triggers.ts
index 119ad9b37..43d4c4672 100644
--- a/packages/platform/src/engine/modules/actions/triggers.ts
+++ b/packages/platform/src/engine/modules/actions/triggers.ts
@@ -8,6 +8,7 @@ import { nativeJobsEnabled } from "../../native/execution-policy";
import { resolveExecutionAuthority } from "../../lib/execution-authority";
import { githubFetch } from "../github/github.auth";
import { getFileContent } from "../github/github.service";
+import { GitHubApiError } from "../github/github.error";
import { triggerActionWorkflow, rerunActionWorkflow } from "./action.service";
import { parseActionWorkflow, record } from "./workflow";
import { matchesActionFilters } from "./trigger-pattern";
@@ -150,13 +151,27 @@ export async function dispatchActionWebhook(
untrusted = pullRequest.head.repo.id !== pullRequest.repository.id;
if (untrusted && !workflow.allowForks) continue;
}
- const source =
- workflow.source ??
- (
- await getFileContent(ctx, owner, repo, workflow.path, {
- branch: workflowRevision ?? revision,
- })
- ).content;
+ let source = workflow.source;
+ if (source == null) {
+ try {
+ source = (
+ await getFileContent(ctx, owner, repo, workflow.path, {
+ branch: workflowRevision ?? revision,
+ })
+ ).content;
+ } catch (error) {
+ if (!(error instanceof GitHubApiError && error.status === 404)) throw error;
+ // Only an absent file is a no-op. Repository and revision access must still work.
+ await githubFetch({
+ ctx,
+ owner,
+ repo,
+ url: `https://api.github.com/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/commits/${workflowRevision ?? revision}`,
+ });
+ await repos.actions.workflowError(workflow.organizationId, workflow.id, null);
+ continue;
+ }
+ }
const plan = await parseActionWorkflow(source, workflow.path);
if (
!workflow.source &&
diff --git a/packages/platform/src/engine/modules/apps/app-install.service.ts b/packages/platform/src/engine/modules/apps/app-install.service.ts
index d4b3d97e8..74f0d6f26 100644
--- a/packages/platform/src/engine/modules/apps/app-install.service.ts
+++ b/packages/platform/src/engine/modules/apps/app-install.service.ts
@@ -394,7 +394,53 @@ export async function installApp(
return { kind: "flow", flowHref: template.flowHref ?? "/" };
}
- assertInstallRoutes(template, input.routes);
+ // Resolve config values. Secrets sharing a `generateGroup` get ONE generated
+ // value (e.g. a DB password that must match across two services).
+ const groupSecret = new Map();
+ // Pre-generate every grouped secret so generate:"jwt" fields can sign with
+ // them regardless of field order (the JWT secret must exist before the keys).
+ for (const field of template.configFields ?? []) {
+ if (field.generate === "secret" && field.generateGroup && !groupSecret.has(field.generateGroup)) {
+ groupSecret.set(field.generateGroup, generateSecret());
+ }
+ }
+ const valueFor = (field: AppConfigField): string => {
+ if (field.generate === "secret") {
+ if (field.generateGroup) {
+ const existing = groupSecret.get(field.generateGroup);
+ if (existing) return existing;
+ const secret = generateSecret();
+ groupSecret.set(field.generateGroup, secret);
+ return secret;
+ }
+ return generateSecret();
+ }
+ if (field.generate === "jwt") {
+ const secret = field.jwtSecretGroup ? groupSecret.get(field.jwtSecretGroup) : undefined;
+ if (!secret || !field.jwtRole) return "";
+ return signHs256Jwt(secret, field.jwtRole);
+ }
+ return input.config?.[field.key] ?? field.default ?? "";
+ };
+
+ // Resolve each field's final value EXACTLY once (a non-grouped secret would
+ // otherwise differ between the env write and the file substitution below).
+ const resolved = new Map();
+ for (const field of template.configFields ?? []) resolved.set(field.key, valueFor(field));
+
+ // Inline generated config values (`{{config:KEY}}`) now — in both service env
+ // and mounted files — while leaving `{{publicUrl:…}}` for deploy-time. This
+ // lets a service env embed a generated secret it can't otherwise interpolate
+ // (e.g. a full `postgres://user:PASSWORD@db/…` connection URL).
+ const inlineConfig = (s: string): string =>
+ s.replace(CONFIG_TOKEN_RE, (_m, k) => resolved.get(k) ?? "");
+
+ // Resolve the same specs for route validation, fresh rows and draft repair.
+ // Never mutate the catalog template shared by other installations.
+ const serviceSpecs = (template.services ?? []).map(service => ({
+ ...service, ports: service.ports?.map(inlineConfig),
+ }));
+ assertInstallRoutes({ services: serviceSpecs }, input.routes);
let workspaceId: string | undefined;
// Linked Cloud servers retain their workspace on self-hosted control planes
@@ -489,47 +535,6 @@ export async function installApp(
project = created!;
}
- // Resolve config values. Secrets sharing a `generateGroup` get ONE generated
- // value (e.g. a DB password that must match across two services).
- const groupSecret = new Map();
- // Pre-generate every grouped secret so generate:"jwt" fields can sign with
- // them regardless of field order (the JWT secret must exist before the keys).
- for (const field of template.configFields ?? []) {
- if (field.generate === "secret" && field.generateGroup && !groupSecret.has(field.generateGroup)) {
- groupSecret.set(field.generateGroup, generateSecret());
- }
- }
- const valueFor = (field: AppConfigField): string => {
- if (field.generate === "secret") {
- if (field.generateGroup) {
- const existing = groupSecret.get(field.generateGroup);
- if (existing) return existing;
- const secret = generateSecret();
- groupSecret.set(field.generateGroup, secret);
- return secret;
- }
- return generateSecret();
- }
- if (field.generate === "jwt") {
- const secret = field.jwtSecretGroup ? groupSecret.get(field.jwtSecretGroup) : undefined;
- if (!secret || !field.jwtRole) return "";
- return signHs256Jwt(secret, field.jwtRole);
- }
- return input.config?.[field.key] ?? field.default ?? "";
- };
-
- // Resolve each field's final value EXACTLY once (a non-grouped secret would
- // otherwise differ between the env write and the file substitution below).
- const resolved = new Map();
- for (const field of template.configFields ?? []) resolved.set(field.key, valueFor(field));
-
- // Inline generated config values (`{{config:KEY}}`) now — in both service env
- // and mounted files — while leaving `{{publicUrl:…}}` for deploy-time. This
- // lets a service env embed a generated secret it can't otherwise interpolate
- // (e.g. a full `postgres://user:PASSWORD@db/…` connection URL).
- const inlineConfig = (s: string): string =>
- s.replace(CONFIG_TOKEN_RE, (_m, k) => resolved.get(k) ?? "");
-
// Resolve template files per service.
const filesByService = new Map();
for (const f of template.files ?? []) {
@@ -562,7 +567,7 @@ export async function installApp(
const varsByService = new Map();
// The operator's routing, resolved once for the whole stack.
- const routingPlan = planInstallRouting(template, project.slug ?? project.name, input.routes);
+ const routingPlan = planInstallRouting({ services: serviceSpecs }, project.slug ?? project.name, input.routes);
// Rows the adopted draft already has. A fresh project has none, so the loop
// below reduces to a plain seed.
@@ -578,7 +583,7 @@ export async function installApp(
// Seed the compose service rows — or, on an adopted draft, re-apply the chosen
// routing to the rows that already exist and seed only what's missing (a first
// install that died part-way left the project with fewer rows than the template).
- for (const svc of template.services ?? []) {
+ for (const svc of serviceSpecs) {
const routing = routingPlan.get(svc.name) ?? { exposed: false, publicEndpoints: [] };
const existingRow = rowByName.get(svc.name);
@@ -729,9 +734,10 @@ function inlinedConfigKeys(template: AppTemplate): ReadonlySet {
if (!text) return;
for (const [, key] of text.matchAll(CONFIG_TOKEN_RE)) keys.add(key);
};
- // The four places `inlineConfig` is applied, and only those.
+ // Every surface that copies a resolved config value at installation.
for (const svc of template.services ?? []) {
for (const value of Object.values(svc.environment ?? {})) scan(value);
+ for (const port of svc.ports ?? []) scan(port);
scan(svc.build?.dockerfile);
for (const file of svc.build?.files ?? []) scan(file.content);
}
diff --git a/packages/platform/src/engine/modules/assistant/remote-target.ts b/packages/platform/src/engine/modules/assistant/remote-target.ts
index b65fd7d51..180f59a30 100644
--- a/packages/platform/src/engine/modules/assistant/remote-target.ts
+++ b/packages/platform/src/engine/modules/assistant/remote-target.ts
@@ -187,7 +187,7 @@ export async function createRemoteAssistantClient(
connection.organizationId,
server!.workspaceId,
);
- let runtime = await owned.client.workspace(owned.binding.workspaceId!).runtime();
+ let runtime = await owned.client.vm(owned.binding.workspaceId!).runtime();
const baseUrl = "http://openship-assistant.invalid";
return {
id: `assistant:${server!.id}`,
@@ -210,7 +210,7 @@ export async function createRemoteAssistantClient(
let result = await send();
if (result.status === 401) {
runtime = await owned.client
- .workspace(owned.binding.workspaceId!)
+ .vm(owned.binding.workspaceId!)
.runtime({ force: true });
result = await send();
}
diff --git a/packages/platform/src/engine/modules/billing/billing-credit-alert.ts b/packages/platform/src/engine/modules/billing/billing-credit-alert.ts
index a3211e1c9..6140a439c 100644
--- a/packages/platform/src/engine/modules/billing/billing-credit-alert.ts
+++ b/packages/platform/src/engine/modules/billing/billing-credit-alert.ts
@@ -14,7 +14,8 @@ export function creditAlertNotification(input: {
const { eventType, eventId, data, entitlement, organizationId } = input;
// Late credit events cannot turn a paid capacity contract into a credit alert.
if (entitlement.tierId === "capacity") return null;
- if (data.service !== undefined && data.service !== "workspace_vm") return null;
+ // Signed deliveries queued before the VM API cutover can still name the old service.
+ if (data.service !== undefined && data.service !== "vm_compute" && data.service !== "workspace_vm") return null;
const alert = entitlement.quota.alert;
if (!alert || !["low", "grace", "depleted"].includes(alert.state)) return null;
const created =
diff --git a/packages/platform/src/engine/modules/billing/billing-resources.service.ts b/packages/platform/src/engine/modules/billing/billing-resources.service.ts
index 987fd3b5f..1d7657156 100644
--- a/packages/platform/src/engine/modules/billing/billing-resources.service.ts
+++ b/packages/platform/src/engine/modules/billing/billing-resources.service.ts
@@ -1,7 +1,7 @@
/** Display telemetry is independent of checkout, entitlements and provisioning. */
import { observedAllSettled, diagnostics as errorDiagnostics } from "@repo/core/diagnostics";
import { z } from "zod";
-import { Oblien } from "@repo/adapters";
+import { Oblien, oblienApiBaseUrl, oblienApiUrl } from "@repo/adapters";
import { type PlanTierId } from "@repo/core";
import type { BillingResources } from "@repo/contracts";
import { env } from "../../config/env";
@@ -28,12 +28,12 @@ function timedClient(options: ConstructorParameters[0], signal: A
const client = new Oblien(options);
// The SDK owns endpoint formatting; its default transport has no redirect
// control. Never forward owner credentials or a scoped token to another host.
- const base = (options.baseUrl ?? "https://api.oblien.com").replace(/\/+$/, "");
+ const base = oblienApiBaseUrl(options.baseUrl);
const headers = { "Content-Type": "application/json", ...("token" in options
? { Authorization: `Bearer ${options.token}` }
: { "X-Client-ID": options.clientId, "X-Client-Secret": options.clientSecret }) };
client._http.request = async ({ path, method, query, body }: Parameters[0]): Promise => {
- const url = new URL(`${base}${path}`);
+ const url = oblienApiUrl(base, path);
for (const [key, value] of Object.entries(query ?? {})) if (value !== undefined) url.searchParams.set(key, String(value));
const response = await fetch(url.toString(), {
method, headers, signal, redirect: "error", ...(body === undefined ? {} : { body: JSON.stringify(body) }),
diff --git a/packages/platform/src/engine/modules/billing/management.service.ts b/packages/platform/src/engine/modules/billing/management.service.ts
index dda956942..3a1b7ca0b 100644
--- a/packages/platform/src/engine/modules/billing/management.service.ts
+++ b/packages/platform/src/engine/modules/billing/management.service.ts
@@ -243,7 +243,7 @@ export async function purchaseManagement(ctx: ExecutionContext, input: Managemen
name: "Openship Manage",
slug: owner.namespace,
resource_limits: {
- max_workspaces: 0,
+ max_vms: 0,
max_vcpus: 0,
max_ram_mb: 0,
max_disk_gb: 0,
diff --git a/packages/platform/src/engine/modules/billing/oblien-webhook-crypto.ts b/packages/platform/src/engine/modules/billing/oblien-webhook-crypto.ts
index a22939167..0a2c01839 100644
--- a/packages/platform/src/engine/modules/billing/oblien-webhook-crypto.ts
+++ b/packages/platform/src/engine/modules/billing/oblien-webhook-crypto.ts
@@ -29,7 +29,7 @@ export interface OblienEventEnvelope {
namespace?: string;
data?: {
namespace?: string;
- workspace_id?: string;
+ vm_id?: string;
period_end?: string;
[key: string]: unknown;
};
diff --git a/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts b/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts
index 9ee03e86a..e14a9978f 100644
--- a/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts
+++ b/packages/platform/src/engine/modules/billing/oblien-webhook.service.ts
@@ -39,8 +39,8 @@ interface OblienUsageBucket {
interface OblienWebhookData {
namespace?: string;
- workspace_id?: string;
- workspace_name?: string;
+ vm_id?: string;
+ vm_name?: string;
service?: string;
/** credits.usage */
balance?: number;
diff --git a/packages/platform/src/engine/modules/cloud-workspaces/cloud-workspace.service.ts b/packages/platform/src/engine/modules/cloud-workspaces/cloud-workspace.service.ts
index c9ad35403..97265587e 100644
--- a/packages/platform/src/engine/modules/cloud-workspaces/cloud-workspace.service.ts
+++ b/packages/platform/src/engine/modules/cloud-workspaces/cloud-workspace.service.ts
@@ -704,7 +704,7 @@ export async function processWorkspaceOperation(id: string): Promise {
const namespace = row.namespace;
if (!namespace || namespace !== binding.namespace)
throw new Error("Cloud workspace namespace changed");
- const ws = client.workspace(binding.workspaceId);
+ const ws = client.vm(binding.workspaceId);
try {
const current = await ws.get();
if (current.namespace !== namespace)
diff --git a/packages/platform/src/engine/modules/deployments/build-pipeline.ts b/packages/platform/src/engine/modules/deployments/build-pipeline.ts
index 7dd1d6746..2f2087d1b 100644
--- a/packages/platform/src/engine/modules/deployments/build-pipeline.ts
+++ b/packages/platform/src/engine/modules/deployments/build-pipeline.ts
@@ -34,6 +34,7 @@ import { recordRuntimeImageReceipts, runtimeImageTrackingRef } from "../../lib/r
import {
BUILD_ENV_VARS,
AppError,
+ DeployError,
safeErrorMessage,
sanitizeProxySettings,
normalizeServiceLabel,
@@ -1757,9 +1758,17 @@ async function executeBuildAndDeploy(
// outcome was recorded is bookkeeping: reporting it as a failure would
// invert a working deploy and tear its containers down.
const capacityError = cloudCapacityFailure(err, project.id, buildResourcesForRecovery, project.workspaceId);
- await reportPipelineError(ctx, capacityError?.message ?? message, logger, capacityError
- ? { errorCode: capacityError.code, errorDetails: capacityError.details }
- : deploymentResourceFailure({ project, message, cause: err }));
+ await reportPipelineError(
+ ctx, capacityError?.message ?? message, logger,
+ capacityError
+ ? { errorCode: capacityError.code, errorDetails: capacityError.details }
+ : deploymentResourceFailure({
+ project, message, cause: err,
+ meta: err instanceof DeployError
+ ? { errorCode: err.code, errorDetails: err.details }
+ : undefined,
+ }),
+ );
} finally {
await finishBuildCancellation?.();
// The deploy is over either way — release the loopback bridges it opened.
diff --git a/packages/platform/src/engine/modules/deployments/compose-configuration-error.ts b/packages/platform/src/engine/modules/deployments/compose-configuration-error.ts
index 89210d3ef..4758070f5 100644
--- a/packages/platform/src/engine/modules/deployments/compose-configuration-error.ts
+++ b/packages/platform/src/engine/modules/deployments/compose-configuration-error.ts
@@ -6,9 +6,12 @@
* service shape, but must never do that for this error: deploying stale Compose
* configuration after the file changed is less safe than refusing the deploy.
*/
-export class ComposeConfigurationError extends Error {
+import { AppError } from "@repo/core";
+
+export class ComposeConfigurationError extends AppError {
constructor(message: string, options?: ErrorOptions) {
- super(message, options);
+ super(message, 400, "COMPOSE_CONFIGURATION_INVALID");
+ if (options?.cause !== undefined) this.cause = options.cause;
this.name = "ComposeConfigurationError";
}
}
diff --git a/packages/platform/src/engine/modules/deployments/compose/deploy.service.ts b/packages/platform/src/engine/modules/deployments/compose/deploy.service.ts
index 498647ce7..58c21d670 100644
--- a/packages/platform/src/engine/modules/deployments/compose/deploy.service.ts
+++ b/packages/platform/src/engine/modules/deployments/compose/deploy.service.ts
@@ -1421,8 +1421,18 @@ async function deployComposeServicesCore(
continue;
}
if ((match?.duplicates.length ?? 0) > 0) {
- throw new Error(
- `Deployment preflight found more than one container matching active service "${row.serviceName ?? row.serviceId}" (${[liveSummary.names[0] ?? liveSummary.id.slice(0, 12), ...match!.duplicates].join(", ")}), so no service activation was started. Remove or reconcile the duplicate container before redeploying.`,
+ const containerNames = [liveSummary.names[0] ?? liveSummary.id.slice(0, 12), ...match!.duplicates];
+ throw new DeployError(
+ `Deployment preflight found more than one container matching active service "${row.serviceName ?? row.serviceId}" (${containerNames.join(", ")}), so no service activation was started. 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 ownership is unclear, contact support with deployment ${dep.id}.`,
+ "SERVICE_CONTAINER_CONFLICT",
+ {
+ projectId: project.id,
+ serviceId: row.serviceId,
+ serviceName: row.serviceName ?? row.serviceId,
+ containerNames,
+ serverId: opts?.serverId ?? null,
+ workspaceId: project.workspaceId ?? null,
+ },
);
}
diff --git a/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts b/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts
index 061720d5a..f276201b8 100644
--- a/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts
+++ b/packages/platform/src/engine/modules/deployments/deployment-lifecycle.ts
@@ -38,8 +38,6 @@ import {
sanitizeStorableStrings,
sliceWithoutSplittingPair,
} from "./build-log-sanitize";
-import { detectAndStoreFavicon } from "../../lib/favicon-detector";
-import { trackBackgroundWork } from "../../lib/background-work";
import { onWebmailDeployed } from "../mail/webmail/webmail-install.service";
import { computeCleanupKeepSet } from "../projects/cleanup-keep-set";
import { deploymentResourceFailure, type DeploymentFailureMeta } from "./resource-failure";
@@ -1065,11 +1063,6 @@ export async function onSuccess(
},
);
- // Async favicon detection - don't block the deploy response
- if (result.url) {
- void trackBackgroundWork(detectAndStoreFavicon(project.id, result.url));
- }
-
// Webmail on Openship Cloud, routed on the mail server's own `mail.`:
// the mail VPS proxies that hostname to the cloud URL, which can only be
// registered once the URL exists. Await it so the deployment execution lease
diff --git a/packages/platform/src/engine/modules/deployments/deployment.service.ts b/packages/platform/src/engine/modules/deployments/deployment.service.ts
index 2efe6c992..4b5cbb34b 100644
--- a/packages/platform/src/engine/modules/deployments/deployment.service.ts
+++ b/packages/platform/src/engine/modules/deployments/deployment.service.ts
@@ -89,9 +89,7 @@ export async function listDeployments(
...d,
isActive: d.id === activeId,
projectName: project.name,
- // Project favicon → the dashboard uses it as the row's logo instead
- // of the framework/Docker glyph.
- favicon: project.favicon ?? null,
+ iconUrl: project.iconUrl ?? null,
})),
};
}
@@ -110,8 +108,7 @@ export async function listDeployments(
...d,
projectName: proj?.name ?? "Unknown",
isActive: proj?.activeDeploymentId === d.id,
- // Project favicon → dashboard row logo (see listByProject above).
- favicon: proj?.favicon ?? null,
+ iconUrl: proj?.iconUrl ?? null,
};
});
diff --git a/packages/platform/src/engine/modules/deployments/local-source.ts b/packages/platform/src/engine/modules/deployments/local-source.ts
index bd03064d7..a7fbbf3bc 100644
--- a/packages/platform/src/engine/modules/deployments/local-source.ts
+++ b/packages/platform/src/engine/modules/deployments/local-source.ts
@@ -95,6 +95,7 @@ export async function resolveSourceEnvFromLocal(
export async function resolveFromLocal(
dirPath: string,
opts: ResolveOptions = {},
+ fallbackName = basename(dirPath),
): Promise {
const st = await stat(dirPath);
if (!st.isDirectory()) {
@@ -103,7 +104,7 @@ export async function resolveFromLocal(
const reader = createLocalReader(dirPath);
const rootPackageJson = await reader.readJson("package.json");
- const name = (rootPackageJson?.name as string) ?? basename(dirPath);
+ const name = (rootPackageJson?.name as string) || fallbackName;
return resolveFromReader(
reader,
diff --git a/packages/platform/src/engine/modules/domains/domain.service.ts b/packages/platform/src/engine/modules/domains/domain.service.ts
index 4e3904afe..91af17542 100644
--- a/packages/platform/src/engine/modules/domains/domain.service.ts
+++ b/packages/platform/src/engine/modules/domains/domain.service.ts
@@ -108,7 +108,7 @@ export async function getDomain(ctx: RequestContext, domainId: string) {
/**
* Make a domain the project's primary. Primary is the project's canonical
- * hostname — what favicon detection, analytics, and the dashboard's project
+ * hostname — what analytics and the dashboard's project
* link resolve to (getPrimaryByProject). setPrimary unsets any prior primary
* for the project and marks this one, so exactly one row stays primary.
* Survives redeploys: per-service route registration preserves an existing
diff --git a/packages/platform/src/engine/modules/domains/routing-apply.service.ts b/packages/platform/src/engine/modules/domains/routing-apply.service.ts
index 599377080..25ae28ddd 100644
--- a/packages/platform/src/engine/modules/domains/routing-apply.service.ts
+++ b/packages/platform/src/engine/modules/domains/routing-apply.service.ts
@@ -538,7 +538,7 @@ export async function applyCloudRouting(opts: {
!input.routes.some(
(rule) =>
rule.action.kind === "proxy" &&
- rule.action.workspace === backend.workspace &&
+ rule.action.vm === backend.vm &&
rule.action.port === backend.port,
)
) {
diff --git a/packages/platform/src/engine/modules/migration/migration.orchestrator.ts b/packages/platform/src/engine/modules/migration/migration.orchestrator.ts
index 15abd2c4e..0ff935b26 100644
--- a/packages/platform/src/engine/modules/migration/migration.orchestrator.ts
+++ b/packages/platform/src/engine/modules/migration/migration.orchestrator.ts
@@ -691,7 +691,7 @@ class MigrationOrchestratorImpl {
id: `dmr_${crypto.randomUUID()}`,
organizationId: ctx.organizationId,
targetServerId: target.id,
- projectName: plan.project.name,
+ projectName: plan.projectName,
serviceNames: plan.services.map((s) => s.create.name),
status: "queued",
mode: "provider_import",
diff --git a/packages/platform/src/engine/modules/migration/platform-import-plan.ts b/packages/platform/src/engine/modules/migration/platform-import-plan.ts
index 1f4d3cf13..302c860e0 100644
--- a/packages/platform/src/engine/modules/migration/platform-import-plan.ts
+++ b/packages/platform/src/engine/modules/migration/platform-import-plan.ts
@@ -1,5 +1,11 @@
import { createHash, randomUUID, randomBytes } from "node:crypto";
-import { AppError, normalizeAliasStrict, slugify, normalizeProjectRootDirectory, validateImageReference } from "@repo/core";
+import {
+ AppError,
+ normalizeAliasStrict,
+ slugify,
+ normalizeProjectRootDirectory,
+ validateImageReference,
+} from "@repo/core";
import type {
PlatformDiscovery,
PlatformMigrationSource,
@@ -24,7 +30,7 @@ import {
} from "./providers/types";
import { discoverExternalDatabases } from "./providers/external-databases";
import { resolveRailwayBindings } from "./providers/railway-wiring";
-import { platformImportProject } from "./platform-import-project";
+import { platformImportProjects, type PlannedImportProject } from "./platform-import-project";
export interface ImportBinding {
sourceId: string;
@@ -46,7 +52,8 @@ export interface PrivateImportPlan {
inventory: ProviderInventory;
fingerprint: string;
targetServerId: string;
- project: TEnsureProjectBody;
+ projectName: string;
+ projects: PlannedImportProject[];
services: PlannedImportService[];
requiresWritePause: boolean;
requiresWorkerPause: boolean;
@@ -528,7 +535,7 @@ export async function reviewPlatform(
const projectName = (input.projectName ?? inventory.projectName).trim();
if (!slugify(projectName))
throw new AppError("Choose a name for the imported project", 400, "IMPORT_NAME_INVALID");
- const project = platformImportProject(projectName, input.targetServerId, services);
+ const projects = platformImportProjects(projectName, input.targetServerId, services);
const plan: PrivateImportPlan = {
id: randomUUID(),
organizationId: ctx.organizationId,
@@ -536,7 +543,8 @@ export async function reviewPlatform(
inventory: draft.inventory,
fingerprint: inventoryFingerprint(draft.inventory),
targetServerId: input.targetServerId,
- project,
+ projectName,
+ projects,
services,
...(inventory.provider === "railway" ? { sourceControl: "railway-project" as const } : {}),
requiresWritePause: services.some(
@@ -559,6 +567,10 @@ export async function reviewPlatform(
planId: plan.id,
...publicInventory({ ...inventory, services: services.map((s) => s.source) }),
projectName,
+ projects: projects.map(({ create, sourceIds }) => ({
+ name: create.name,
+ serviceIds: sourceIds,
+ })),
targetServerId: plan.targetServerId,
requiresWritePause: plan.requiresWritePause,
requiresWorkerPause: plan.requiresWorkerPause,
@@ -572,8 +584,12 @@ export async function loadReviewedImport(
id: string,
): Promise {
const plan = await get(ctx, "plan", id);
- if (!plan.project)
- throw new AppError("Review this import again before starting it.", 409, "IMPORT_REVIEW_EXPIRED");
+ if (!plan.projects?.length)
+ throw new AppError(
+ "Review this import again before starting it.",
+ 409,
+ "IMPORT_REVIEW_EXPIRED",
+ );
if (!plan.ready)
throw new AppError("Resolve the import review before starting", 409, "IMPORT_NOT_READY");
const access = await getProviderAccess(ctx.organizationId, plan.inventory.source.connectionId);
diff --git a/packages/platform/src/engine/modules/migration/platform-import-project.ts b/packages/platform/src/engine/modules/migration/platform-import-project.ts
index 61e7b6e53..3415e69fe 100644
--- a/packages/platform/src/engine/modules/migration/platform-import-project.ts
+++ b/packages/platform/src/engine/modules/migration/platform-import-project.ts
@@ -3,15 +3,83 @@ import type {
TCreateServiceBody,
TEnsureProjectBody,
} from "@repo/contracts";
+import { slugify } from "@repo/core";
import type { PlannedImportService } from "./platform-import-plan";
+export interface PlannedImportProject {
+ create: TEnsureProjectBody;
+ sourceIds: string[];
+}
+
+/** A native project has one Git checkout. Keep compatible environments together;
+ * otherwise give each service its own project and use ordinary private links. */
+export function platformImportProjects(
+ name: string,
+ serverId: string,
+ services: PlannedImportService[],
+): PlannedImportProject[] {
+ const imports = services.filter((service) => service.data !== "external");
+ const sources = new Set(
+ imports
+ .filter((service) => service.create.gitRepo)
+ .map((service) =>
+ JSON.stringify([
+ service.create.gitProvider,
+ service.create.gitOwner,
+ service.create.gitRepo,
+ service.create.gitBranch,
+ service.source.commit,
+ ]),
+ ),
+ );
+ const groups = sources.size > 1 ? imports.map((service) => [service]) : [imports];
+ if (groups.length > 1) {
+ for (const service of imports) {
+ const keys = new Set(service.bindings.map((binding) => binding.envKey));
+ for (const key of keys) {
+ const bindings = service.bindings.filter((binding) => binding.envKey === key);
+ if (new Set(bindings.map((binding) => binding.sourceId)).size > 1) {
+ service.source.blockers.push(
+ `Review ${key}: use a separate connection variable for each private service when importing into separate projects.`,
+ );
+ }
+ for (const binding of bindings) {
+ if (
+ Object.hasOwn(service.environment, key) &&
+ binding.valueTemplate === undefined &&
+ bindings.length === 1
+ )
+ service.source.blockers.push(
+ `Review ${key}: its private host cannot be safely converted into a project connection. Provide a destination value explicitly.`,
+ );
+ const dependency = imports.find((candidate) => candidate.source.id === binding.sourceId);
+ if (dependency && !(dependency.source.port || dependency.create.port))
+ service.source.blockers.push(
+ `Review ${key}: ${dependency.create.name} needs a private listener port for its project connection.`,
+ );
+ }
+ }
+ }
+ }
+ return groups.map((group) => ({
+ create: platformImportProject(
+ groups.length === 1
+ ? name
+ : `${slugify(name).slice(0, 100 - group[0].create.name.length - 1)}-${group[0].create.name}`,
+ serverId,
+ group,
+ ),
+ sourceIds: group.map((service) => service.source.id),
+ }));
+}
+
function dependencyNames(service: PlannedImportService, services: PlannedImportService[]) {
return [
...new Set(
- service.bindings.map(
- (binding) =>
- services.find((dependency) => dependency.source.id === binding.sourceId)!.create.name,
- ),
+ service.bindings.flatMap((binding) => {
+ const dependency = services.find((candidate) => candidate.source.id === binding.sourceId);
+ return dependency ? [dependency.create.name] : [];
+ }),
),
];
}
@@ -37,9 +105,8 @@ export function platformImportRoutes(services: PlannedImportService[]): Migratio
);
}
-/** Translate reviewed provider recipes into the same project and service inputs
- * used by native imports. A provider project never becomes several projects. */
-export function platformImportProject(
+/** Translate one compatible group into ordinary project and service inputs. */
+function platformImportProject(
name: string,
serverId: string,
services: PlannedImportService[],
@@ -53,15 +120,6 @@ export function platformImportProject(
service.source.blockers.push(
"This repository declares project-wide release commands. Review a service-compatible release recipe before importing; grouped imports cannot silently skip those commands.",
);
- if (
- service.create.gitOwner !== first.create.gitOwner ||
- service.create.gitRepo !== first.create.gitRepo ||
- service.source.commit !== first.source.commit
- ) {
- service.source.blockers.push(
- "These services use different repositories or deployed revisions. A native OpenShip project has one Git source; align the source services before importing them together.",
- );
- }
}
return {
name,
diff --git a/packages/platform/src/engine/modules/migration/platform-import-worker.ts b/packages/platform/src/engine/modules/migration/platform-import-worker.ts
index a6017cf9a..b38ccaaf4 100644
--- a/packages/platform/src/engine/modules/migration/platform-import-worker.ts
+++ b/packages/platform/src/engine/modules/migration/platform-import-worker.ts
@@ -1,5 +1,5 @@
import { AppError, ConflictError, ValidationError } from "@repo/core";
-import { repos } from "@repo/db";
+import { repos, type Service } from "@repo/db";
import type { ExecutionContext } from "../../../context";
import type { PrivateImportPlan, PlannedImportService } from "./platform-import-plan";
import { ensureProject } from "../projects/project-crud.service";
@@ -20,6 +20,7 @@ import {
import { verifyPlatformDeployment } from "./platform-import-health";
import { withProjectRuntimeLock } from "../../lib/project-runtime-lock";
import { prepareMigrationTarget } from "./migration-runtime";
+import { createConnection } from "../projects/project-connection.service";
export interface ImportLifecycle {
signal: AbortSignal;
@@ -76,13 +77,29 @@ export async function executePlatformImport(
resourceId: plan.targetServerId,
action: "write",
});
- if (!plan.project)
+ if (!plan.projects?.length)
throw new AppError(
"Review this import again before starting it.",
409,
"IMPORT_REVIEW_EXPIRED",
);
const services = orderedImports(plan.services);
+ const destinations = plan.projects.map((project) => ({
+ ...project,
+ services: services.filter((service) => project.sourceIds.includes(service.source.id)),
+ projectId: "",
+ }));
+ const destinationFor = new Map(
+ destinations.flatMap((destination) =>
+ destination.sourceIds.map((id) => [id, destination] as const),
+ ),
+ );
+ if (services.some((service) => !destinationFor.has(service.source.id)))
+ throw new AppError(
+ "Review this import again before starting it.",
+ 409,
+ "IMPORT_REVIEW_EXPIRED",
+ );
lifecycle.log("Checking the complete project's storage and destination configuration");
await preflightPlatformData(services, lifecycle.signal);
await prepareMigrationTarget(ctx.organizationId, plan.targetServerId, runId, {
@@ -91,44 +108,61 @@ export async function executePlatformImport(
});
lifecycle.signal.throwIfAborted();
await lifecycle.phase("adopting");
- lifecycle.log(`Creating project ${plan.project.name}`);
- const { project_id: projectId } = await ensureProject(plan.project, ctx.organizationId, ctx, {
- mustCreate: true,
- });
- for (const service of services) {
- if (
- !(await repos.dockerMigrationRun.bindImportedProject(
- runId,
- ctx.organizationId,
- service.source.id,
- projectId,
- ))
- )
- throw new AppError(
- "The import was cancelled while creating its project. Its saved configuration was retained.",
- 409,
- "IMPORT_ADMISSION_CLOSED",
- );
- }
- await repos.project.update(projectId, { autoDeploy: false, runtimeMode: "docker" });
- for (const service of services) {
+ const bySource = new Map();
+ for (const destination of destinations) {
lifecycle.signal.throwIfAborted();
- if (!service.create.services?.length)
- await createService(ctx, projectId, platformImportSourceService(service, services));
- }
- // Use the same pending-domain and ownership path as server/Docker migration.
- // Validate every route before pausing Railway or copying data. Deployment will
- // reconcile routing normally; neither this step nor import changes external DNS.
- try {
- await saveMigrationRoutes(ctx, projectId, platformImportRoutes(services), lifecycle.log);
- } catch (error) {
- if (error instanceof ValidationError || error instanceof ConflictError)
- throw new AppError(error.message, error.statusCode, "IMPORT_DOMAIN_REVIEW_REQUIRED");
- throw error;
- }
- const rows = await repos.service.listByProject(projectId);
- const bySource = new Map(
- services.map((service) => {
+ lifecycle.log(`Creating project ${destination.create.name}`);
+ const { project_id: projectId } = await ensureProject(
+ destination.create,
+ ctx.organizationId,
+ ctx,
+ {
+ mustCreate: true,
+ },
+ );
+ destination.projectId = projectId;
+ for (const service of destination.services) {
+ if (
+ !(await repos.dockerMigrationRun.bindImportedProject(
+ runId,
+ ctx.organizationId,
+ service.source.id,
+ projectId,
+ ))
+ )
+ throw new AppError(
+ "The import was cancelled while creating its project. Its saved configuration was retained.",
+ 409,
+ "IMPORT_ADMISSION_CLOSED",
+ );
+ }
+ await repos.project.update(projectId, { autoDeploy: false, runtimeMode: "docker" });
+ for (const service of destination.services) {
+ lifecycle.signal.throwIfAborted();
+ if (!service.create.services?.length)
+ await createService(
+ ctx,
+ projectId,
+ platformImportSourceService(service, destination.services),
+ );
+ }
+ // Use the same pending-domain and ownership path as server/Docker migration.
+ // Validate every route before pausing Railway or copying data. Deployment will
+ // reconcile routing normally; neither this step nor import changes external DNS.
+ try {
+ await saveMigrationRoutes(
+ ctx,
+ projectId,
+ platformImportRoutes(destination.services),
+ lifecycle.log,
+ );
+ } catch (error) {
+ if (error instanceof ValidationError || error instanceof ConflictError)
+ throw new AppError(error.message, error.statusCode, "IMPORT_DOMAIN_REVIEW_REQUIRED");
+ throw error;
+ }
+ const rows = await repos.service.listByProject(projectId);
+ for (const service of destination.services) {
const row = rows.find((row) => row.name === service.create.name);
if (!row)
throw new AppError(
@@ -136,9 +170,9 @@ export async function executePlatformImport(
409,
"IMPORT_TARGET_SERVICE_MISSING",
);
- return [service.source.id, row] as const;
- }),
- );
+ bySource.set(service.source.id, row);
+ }
+ }
const checkpoint = async () => {
const current = (await repos.dockerMigrationRun.findById(runId))?.recovery.providerImport;
if (!current)
@@ -152,7 +186,8 @@ export async function executePlatformImport(
},
});
const saveEnvironment = async (sourceId: string, values: Record) => {
- await mergeServiceEnvVars(ctx, projectId, bySource.get(sourceId)!.id, {
+ const target = bySource.get(sourceId)!;
+ await mergeServiceEnvVars(ctx, target.projectId, target.id, {
environment: "production",
deletes: [],
upserts: Object.entries(values).map(([key, value]) => ({
@@ -163,16 +198,33 @@ export async function executePlatformImport(
})),
});
};
- for (const service of services) await saveEnvironment(service.source.id, service.environment);
+ const isCrossProject = (service: PlannedImportService, dependencyId: string) =>
+ bySource.get(service.source.id)!.projectId !== bySource.get(dependencyId)?.projectId;
+ for (const service of services) {
+ // Native connections own project-level variables. A service-level copy would
+ // shadow the refreshed value on this deployment and subsequent redeploys.
+ const linkedKeys = new Set(
+ service.bindings
+ .filter((binding) => isCrossProject(service, binding.sourceId))
+ .map((binding) => binding.envKey),
+ );
+ await saveEnvironment(
+ service.source.id,
+ Object.fromEntries(
+ Object.entries(service.environment).filter(([key]) => !linkedKeys.has(key)),
+ ),
+ );
+ }
for (const service of services) {
const values: Record = {};
for (const binding of service.bindings) {
+ if (isCrossProject(service, binding.sourceId)) continue;
// Railway already resolved these against native service DNS during review.
if (Object.hasOwn(service.environment, binding.envKey)) continue;
const dependency = bySource.get(binding.sourceId);
if (!dependency)
throw new AppError("An import dependency is missing", 409, "IMPORT_DEPENDENCY_MISSING");
- const output = (await getAppConnectionView(ctx, projectId)).outputs.find(
+ const output = (await getAppConnectionView(ctx, dependency.projectId)).outputs.find(
(output) => output.internal && output.sourceServiceId === dependency.id && output.value,
);
if (!output)
@@ -195,7 +247,7 @@ export async function executePlatformImport(
await copyPlatformData({
runId,
service,
- projectId,
+ projectId: bySource.get(service.source.id)!.projectId,
serviceId: bySource.get(service.source.id)!.id,
deploymentId,
signal: lifecycle.signal,
@@ -205,11 +257,43 @@ export async function executePlatformImport(
};
const deploy = async (selected: PlannedImportService[]) => {
lifecycle.signal.throwIfAborted();
+ const destination = destinationFor.get(selected[0].source.id)!;
+ const projectId = destination.projectId;
+ for (const service of selected) {
+ for (const binding of service.bindings) {
+ if (!isCrossProject(service, binding.sourceId)) continue;
+ lifecycle.signal.throwIfAborted();
+ const dependency = bySource.get(binding.sourceId);
+ if (!dependency)
+ throw new AppError("An import dependency is missing", 409, "IMPORT_DEPENDENCY_MISSING");
+ const output = (await getAppConnectionView(ctx, dependency.projectId)).outputs.find(
+ (output) => output.internal && output.sourceServiceId === dependency.id,
+ );
+ if (!output)
+ throw new AppError(
+ "The imported dependency has no usable connection output",
+ 409,
+ "IMPORT_CONNECTION_NOT_READY",
+ );
+ await createConnection(
+ ctx,
+ projectId,
+ {
+ sourceProjectId: dependency.projectId,
+ outputId: output.id,
+ envKey: binding.envKey,
+ mode: "internal",
+ valueTemplate: binding.valueTemplate,
+ },
+ { defer: true },
+ );
+ }
+ }
await lifecycle.phase("deploying");
lifecycle.log(
- `Deploying ${plan.project.name}: ${selected.map((service) => service.create.name).join(", ")}`,
+ `Deploying ${destination.create.name}: ${selected.map((service) => service.create.name).join(", ")}`,
);
- const source = services.find((service) => service.create.gitRepo)?.source;
+ const source = destination.services.find((service) => service.create.gitRepo)?.source;
const result = await triggerDeployment(ctx, {
projectId,
serverId: plan.targetServerId,
@@ -263,8 +347,19 @@ export async function executePlatformImport(
} else await transfer(service);
}
}
- const deploymentId = await deploy(services);
- await verifyPlatformDeployment(projectId, deploymentId, lifecycle.signal);
+ // Multi-source plans have one service per project. The service order already
+ // guarantees each private dependency is deployed before its consumers connect.
+ const deployed = new Map();
+ for (const service of services) {
+ const destination = destinationFor.get(service.source.id)!;
+ if (!deployed.has(destination.projectId))
+ deployed.set(destination.projectId, await deploy(destination.services));
+ }
+ await Promise.all(
+ [...deployed].map(([projectId, deploymentId]) =>
+ verifyPlatformDeployment(projectId, deploymentId, lifecycle.signal),
+ ),
+ );
await repos.dockerMigrationRun.updateRecovery(runId, {
providerImport: {
...(await checkpoint()),
@@ -272,7 +367,7 @@ export async function executePlatformImport(
},
});
lifecycle.log(
- `${plan.project.name} imported with ${services.length} services; source data retained.`,
+ `${plan.projectName} imported with ${services.length} services in ${destinations.length} project(s); source data retained.`,
);
}
diff --git a/packages/platform/src/engine/modules/migration/providers/railway-wiring.ts b/packages/platform/src/engine/modules/migration/providers/railway-wiring.ts
index 9aa69ae58..c880983a0 100644
--- a/packages/platform/src/engine/modules/migration/providers/railway-wiring.ts
+++ b/packages/platform/src/engine/modules/migration/providers/railway-wiring.ts
@@ -3,8 +3,8 @@ import type { ImportBinding, PlannedImportService } from "../platform-import-pla
const privateHost = /\b[a-z0-9](?:[a-z0-9.-]*[a-z0-9])?\.railway\.internal\b/gi;
/** Keep Railway's resolved values, replacing provider DNS with the native service
- * aliases inside the imported project. Dependencies describe deployment order;
- * they do not create cross-project connections or publish database ports. */
+ * aliases inside the imported project. Retain a host template for native private
+ * connections when the destination must span several projects. */
export function resolveRailwayBindings(
service: PlannedImportService,
selected: Map,
@@ -26,10 +26,32 @@ export function resolveRailwayBindings(
);
continue;
}
+ const external = new Set(
+ dependencies
+ .filter(({ source }) => source !== service)
+ .map(({ source }) => source!.source.id),
+ );
+ const template =
+ external.size === 1 && !value.includes("${host}")
+ ? value.replace(privateHost, (host) => {
+ const dependency = dependencies.find((candidate) => candidate.host === host)!;
+ return dependency.source === service ? service.create.internalAlias! : "${host}";
+ })
+ : undefined;
let resolved = value;
for (const { host, source } of dependencies) {
resolved = resolved.replaceAll(host, source!.create.internalAlias!);
- if (source !== service) bindings.push({ sourceId: source!.source.id, envKey: key });
+ if (
+ source !== service &&
+ !bindings.some(
+ (binding) => binding.sourceId === source!.source.id && binding.envKey === key,
+ )
+ )
+ bindings.push({
+ sourceId: source!.source.id,
+ envKey: key,
+ ...(template === undefined ? {} : { valueTemplate: template }),
+ });
// A resolved URL can declare an otherwise undiscovered private listener.
// A hostname-only value still works through the project network's DNS.
if (!source!.source.port) {
@@ -38,7 +60,8 @@ export function resolveRailwayBindings(
const port = Number(
url.port || (url.protocol === "https:" ? 443 : url.protocol === "http:" ? 80 : 0),
);
- if (url.hostname === host && port > 0 && port <= 65535) source!.source.port = port;
+ if (url.hostname.toLowerCase() === host.toLowerCase() && port > 0 && port <= 65535)
+ source!.source.port = port;
} catch {
/* diagnostics-ignore: arbitrary strings and hostname-only variables do not declare a listener. */
}
diff --git a/packages/platform/src/engine/modules/projects/folder/folder.service.ts b/packages/platform/src/engine/modules/projects/folder/folder.service.ts
index 0b9a6c717..06e68493d 100644
--- a/packages/platform/src/engine/modules/projects/folder/folder.service.ts
+++ b/packages/platform/src/engine/modules/projects/folder/folder.service.ts
@@ -257,5 +257,6 @@ async function scanSource(session: FolderSession, opts: ResolveOptions = {}) {
const st = await stat(session.stagingDir).catch((diagnosticFailure) => { observeCaughtError(diagnosticFailure, "platform/engine/modules/projects/folder/folder.service"); return null; });
if (!st?.isDirectory()) throw new Error("Uploaded source not found");
const { resolveFromLocal } = await import("../../deployments/local-source");
- return resolveFromLocal(session.stagingDir, opts);
+ // Staging paths are private implementation details, not project names.
+ return resolveFromLocal(session.stagingDir, opts, session.name?.trim() || "app");
}
diff --git a/packages/platform/src/engine/modules/projects/project-clone.service.ts b/packages/platform/src/engine/modules/projects/project-clone.service.ts
index 6abf0122d..227c2d705 100644
--- a/packages/platform/src/engine/modules/projects/project-clone.service.ts
+++ b/packages/platform/src/engine/modules/projects/project-clone.service.ts
@@ -68,10 +68,6 @@ const PROJECT_FIELDS_NOT_CLONED = [
"deletionInProgress",
"lifecycleOperation",
"disabledAt",
- // Detected from the live site; the copy has no site yet, so copying these would show the
- // original's icon next to a project that has never served a request.
- "favicon",
- "faviconCheckedAt",
// Routing that names specific hostnames. The copy starts with no domains (the confirm dialog
// promises exactly this) — the originals stay with the project still serving them.
"compositeRoutes",
diff --git a/packages/platform/src/engine/modules/projects/project-connection.service.ts b/packages/platform/src/engine/modules/projects/project-connection.service.ts
index 2678838fb..70a45f7cb 100644
--- a/packages/platform/src/engine/modules/projects/project-connection.service.ts
+++ b/packages/platform/src/engine/modules/projects/project-connection.service.ts
@@ -87,6 +87,8 @@ export async function listConnectionCandidates(ctx: RequestContext, projectId: s
name: project.name,
description: project.environmentName,
appTemplateId: project.appTemplateId,
+ iconUrl: project.iconUrl,
+ framework: project.framework,
clusterId: project.clusterId,
});
}
diff --git a/packages/platform/src/engine/modules/projects/project-crud.service.ts b/packages/platform/src/engine/modules/projects/project-crud.service.ts
index d69a954e3..ebc17449d 100644
--- a/packages/platform/src/engine/modules/projects/project-crud.service.ts
+++ b/packages/platform/src/engine/modules/projects/project-crud.service.ts
@@ -13,8 +13,7 @@ import {
type Project,
type Server,
} from "@repo/db";
-import {
- slugify,
+import { isImageUrl, slugify,
runtimeProjectUpdate,
assertRuntimeVersionTarget,
AppError,
@@ -1902,6 +1901,11 @@ async function updateProjectUnlocked(
if (PROJECT_IDENTITY_KEYS.has(key)) continue;
if (raw[key] !== undefined) update[key] = raw[key];
}
+ if (data.iconUrl !== undefined) {
+ const iconUrl = typeof data.iconUrl === "string" ? data.iconUrl.trim() || null : data.iconUrl;
+ if (iconUrl !== null && !isImageUrl(iconUrl)) throw new ValidationError("Icon URL must be an HTTP or HTTPS URL without credentials.");
+ update.iconUrl = iconUrl;
+ }
Object.assign(update, runtimeProjectUpdate(p, update));
assertRuntimeVersionTarget({ ...p, ...update });
await assertBuildCommandUpdate(p, update);
diff --git a/packages/platform/src/engine/modules/projects/project-home.operations.ts b/packages/platform/src/engine/modules/projects/project-home.operations.ts
index a2b516850..671ff94d0 100644
--- a/packages/platform/src/engine/modules/projects/project-home.operations.ts
+++ b/packages/platform/src/engine/modules/projects/project-home.operations.ts
@@ -5,7 +5,6 @@ import { OperationError } from "@repo/contracts";
import type { ExecutionContext } from "../../../context";
import { presentProject } from "../../../projects";
import { authorization } from "../../lib/authorization";
-import { refreshProjectFaviconIfStale } from "../../lib/favicon-detector";
import { fetchOrgCloudProjects } from "../../lib/cloud/projects";
import { canProxyCloudResources } from "../../lib/cloud/scope";
import * as projectService from "./project.service";
@@ -86,10 +85,6 @@ export async function getProjectHome(ctx: ExecutionContext) {
const primary = primariesByProject.get(original.id);
const services = servicesByProject.get(original.id) ?? [];
- refreshProjectFaviconIfStale(original, {
- hostname: primary?.verified ? primary.hostname : null,
- });
-
return {
...presentProject(enriched),
latestDeploymentId: latest?.id ?? null,
diff --git a/packages/platform/src/engine/modules/projects/project-inspection.operations.ts b/packages/platform/src/engine/modules/projects/project-inspection.operations.ts
index e04eefa03..bcabfcc9e 100644
--- a/packages/platform/src/engine/modules/projects/project-inspection.operations.ts
+++ b/packages/platform/src/engine/modules/projects/project-inspection.operations.ts
@@ -12,8 +12,7 @@ import { deploymentWorkload } from "../deployments/deployment-class";
import { serviceKind } from "../../lib/deployable-service";
import { maskDeploymentEnv } from "../../lib/secret-env";
import { listProjectRouteRows, resolveProjectRouteState } from "../domains/project-route.service";
-import { refreshProjectFaviconIfStale } from "../../lib/favicon-detector";
-import { pickCanonicalDomainRow, resolveProjectAccess } from "../../lib/public-endpoints";
+import { resolveProjectAccess } from "../../lib/public-endpoints";
import { readProjectRoutingClaims } from "../../lib/domain-claims";
import { serviceCustomHostnames } from "../../lib/routing-domains";
import { withDomainDiagnostics } from "../domains/domain-diagnostics";
@@ -107,9 +106,6 @@ export function createProjectInspectionOperations(
domain: d.hostname,
primary: d.isPrimary,
}));
- refreshProjectFaviconIfStale(project, {
- hostname: pickCanonicalDomainRow(rawDomains)?.hostname ?? null,
- });
// One server-computed access URL for every client surface. Derived from ALL
// domain rows (service-scoped included, which the project-level publicEndpoints
// resolver drops) + the effective deploy target, so a multi-service project
diff --git a/packages/platform/src/engine/modules/projects/project.operations.ts b/packages/platform/src/engine/modules/projects/project.operations.ts
index 5ed4def9a..b37b91194 100644
--- a/packages/platform/src/engine/modules/projects/project.operations.ts
+++ b/packages/platform/src/engine/modules/projects/project.operations.ts
@@ -10,7 +10,6 @@ import type { ExecutionContext } from "../../../context";
import { authorization } from "../../lib/authorization";
import { audit } from "../../lib/audit-emitter";
import { assertNativeSourcePath } from "../../native/source-policy";
-import { refreshProjectFaviconIfStale } from "../../lib/favicon-detector";
import { createProjectControls } from "./project-controls.operations";
import { clusterDatabaseEvents } from "./cluster-database.operations";
import { clusterVolumeEvents } from "./cluster-volume.operations";
@@ -88,7 +87,6 @@ export const projectDependencies: ProjectDependencies = {
async get(ctx, id) {
const service = await import("./project.service");
const project = await service.getProject(id, ctx.organizationId);
- refreshProjectFaviconIfStale(project);
return project;
},
async update(ctx, id, input) {
@@ -113,7 +111,6 @@ export const projectDependencies: ProjectDependencies = {
}),
}),
});
- result.rows.forEach((row) => refreshProjectFaviconIfStale(row));
return { ...result, rows: result.rows.map((p) => ({ ...p, source: "local" })) };
},
recordAudit,
diff --git a/packages/platform/src/engine/modules/system/managed-server-access.ts b/packages/platform/src/engine/modules/system/managed-server-access.ts
index cab255ce0..ca1ede263 100644
--- a/packages/platform/src/engine/modules/system/managed-server-access.ts
+++ b/packages/platform/src/engine/modules/system/managed-server-access.ts
@@ -25,7 +25,7 @@ export async function managedConnection(ctx: ExecutionContext, id: string) {
return {
...connection,
workspaceId,
- workspace: connection.client.workspace(connection.binding.workspaceId!),
+ workspace: connection.client.vm(connection.binding.workspaceId!),
};
}
export type ManagedConnection = Awaited>;
diff --git a/packages/platform/src/engine/modules/system/server-managed.operations.ts b/packages/platform/src/engine/modules/system/server-managed.operations.ts
index 89be3401f..ab41cb5a3 100644
--- a/packages/platform/src/engine/modules/system/server-managed.operations.ts
+++ b/packages/platform/src/engine/modules/system/server-managed.operations.ts
@@ -75,8 +75,8 @@ async function runtimeCredential(connection: ManagedConnection) {
}
if (
!result.token ||
- claims.type !== "workspace" ||
- claims.workspace_id !== connection.binding.workspaceId ||
+ claims.type !== "vm" ||
+ claims.vm_id !== connection.binding.workspaceId ||
typeof claims.token !== "string" ||
claims.token.length < 16 ||
typeof claims.exp !== "number" ||
@@ -267,7 +267,7 @@ const controls: ResourceServices = {
if ((await runtimeStatus(connection)).enabled !== true) {
const result = await connection.workspace.apiAccess.enable();
requireProviderSuccess(result);
- connection.client.workspaces.invalidateRuntime(connection.binding.workspaceId!);
+ connection.client.vms.invalidateRuntime(connection.binding.workspaceId!);
auditManagedControl(ctx, id, "runtime.enable");
}
const after = await runtimeStatus(connection);
@@ -299,7 +299,7 @@ const controls: ResourceServices = {
try {
requireProviderSuccess(await connection.workspace.apiAccess.rotateToken());
} finally {
- connection.client.workspaces.invalidateRuntime(connection.binding.workspaceId!);
+ connection.client.vms.invalidateRuntime(connection.binding.workspaceId!);
}
const after = await runtimeCredential(connection);
if (after.revision === before.revision)
diff --git a/packages/platform/src/engine/modules/system/server.operations.ts b/packages/platform/src/engine/modules/system/server.operations.ts
index b683ac6e8..207b73bfd 100644
--- a/packages/platform/src/engine/modules/system/server.operations.ts
+++ b/packages/platform/src/engine/modules/system/server.operations.ts
@@ -820,9 +820,8 @@ async function execOnServer(
body: Parameters[1],
) {
- // Primary gate: permission resolver (404 on deny, IDOR-safe). Asserted BEFORE the
- // row is read, so a caller without access cannot distinguish "no such server"
- // from "not yours".
+ // The shared server operation asserts server:admin before calling this service
+ // for every transport. Retain the organization-scoped lookup here as well.
const server = await repos.server.getInOrganization(id, ctx.organizationId);
if (!server) return failServer({ error: "Server not found" }, 404);
diff --git a/packages/platform/src/source-archive.ts b/packages/platform/src/source-archive.ts
index 6942c6e65..0f97e1635 100644
--- a/packages/platform/src/source-archive.ts
+++ b/packages/platform/src/source-archive.ts
@@ -62,6 +62,8 @@ export async function extractSourceArchive(archive: string, destination: string)
await pipeline(createReadStream(archive), createGunzip(), sourceByteLimit(MAX_SOURCE_BYTES + MAX_SOURCE_ENTRIES * 1024 + 16 * 1024 * 1024), parser);
} catch (error) {
if (validationError) throw validationError;
+ if ((error as { code?: string }).code === "Z_BUF_ERROR")
+ throw new ValidationError("Source archive is incomplete or truncated. Retry the upload (maximum 300MB).");
if (/^(?:TAR_|Z_)/.test(String((error as { code?: string }).code))) throw new ValidationError("Invalid source archive");
throw error;
}
diff --git a/packages/platform/test/authorization.test.ts b/packages/platform/test/authorization.test.ts
index 465ec67bd..2fb4948d9 100644
--- a/packages/platform/test/authorization.test.ts
+++ b/packages/platform/test/authorization.test.ts
@@ -31,6 +31,45 @@ beforeEach(async () => {
});
describe("shared authorization", () => {
+ it("does not grant administration to an ordinary member", async () => {
+ state.members.set("org-a:alice", { id: "member-a", role: "member" });
+ state.servers.set("server-a", { organizationId: "org-a" });
+ const input = { resourceType: "server" as const, resourceId: "server-a", action: "admin" as const };
+ expect(await auth.checkPermission("alice", "org-a", input)).toBe(false);
+ expect(await auth.checkPermissionOnResource(context, input)).toBe(false);
+ await expect(auth.authorize(context, input)).rejects.toMatchObject({ code: "NOT_FOUND" });
+ });
+
+ it("does not let an existing token retain administration after its owner becomes a member", async () => {
+ state.servers.set("server-a", { organizationId: "org-a" });
+ state.tokenGrants.set("token-a:server:server-a", { permissions: ["admin"] });
+ const token = await auth.resolveScope({ ...alice, tokenScope: { tokenId: "token-a" },
+ credential: { organizationId: "org-a", readOnly: false } }, "org-a");
+ const input = { resourceType: "server" as const, resourceId: "server-a", action: "admin" as const };
+ await expect(auth.authorize(token, input)).resolves.toBeDefined();
+ state.members.set("org-a:alice", { id: "member-a", role: "member" });
+ await expect(auth.authorize(token, input)).rejects.toMatchObject({ code: "NOT_FOUND" });
+ });
+
+ it.each(["project", "server", "mail_server", "settings", "job"] as const)(
+ "keeps member read/write access separate from %s administration", async resourceType => {
+ state.members.set("org-a:alice", { id: "member-a", role: "member" });
+ const input = { resourceType, resourceId: "*" };
+ for (const action of ["read", "write"] as const)
+ expect(await auth.checkPermission("alice", "org-a", { ...input, action })).toBe(true);
+ expect(await auth.checkPermission("alice", "org-a", { ...input, action: "admin" })).toBe(false);
+ },
+ );
+
+ it("preserves explicitly delegated administration for a restricted user on one server", async () => {
+ state.members.set("org-a:alice", { id: "member-a", role: "restricted" });
+ state.servers.set("server-a", { organizationId: "org-a" });
+ state.servers.set("server-other", { organizationId: "org-a" });
+ state.grants.set("org-a:alice:server:server-a", { permissions: ["admin"] });
+ await expect(auth.authorize(context, { resourceType: "server", resourceId: "server-a", action: "admin" })).resolves.toBeDefined();
+ await expect(auth.authorize(context, { resourceType: "server", resourceId: "server-other", action: "admin" })).rejects.toMatchObject({ code: "NOT_FOUND" });
+ });
+
it("derives checked resources from core without widening the existing type", () => {
expectTypeOf().toEqualTypeOf();
expect(new Set(CHECKED_RESOURCE_TYPES).size).toBe(CHECKED_RESOURCE_TYPES.length);
diff --git a/packages/platform/test/deployment-container-info-schema.test.ts b/packages/platform/test/deployment-container-info-schema.test.ts
index 273113f3a..409a1f8c6 100644
--- a/packages/platform/test/deployment-container-info-schema.test.ts
+++ b/packages/platform/test/deployment-container-info-schema.test.ts
@@ -15,7 +15,7 @@ async function createRuntime(kind: "Docker" | "Cloud", workspaceStatus = "runnin
? await DockerRuntime.create({ dockerSocketPath: "/tmp/openship-test-absent.sock" })
: await CloudDockerRuntime.forWorkspace(
{
- workspaces: {
+ vms: {
get: async () => ({
id: "workspace-a",
namespace: "namespace-a",
diff --git a/packages/platform/test/domains.test.ts b/packages/platform/test/domains.test.ts
index 3717aee3e..131f3e09a 100644
--- a/packages/platform/test/domains.test.ts
+++ b/packages/platform/test/domains.test.ts
@@ -121,7 +121,7 @@ describe("organization-scoped DNS operations", () => {
const dns = createDnsOperations(authorization, { operations: { addCredential } as never, requireAdmin });
const input = { provider: "cloudflare" as const, name: "Production", apiToken: "private" };
state.members.set("org-a:alice", { id: "member-a", role: "member" });
- await expect(dns.addCredential(ctx, input)).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" });
+ await expect(dns.addCredential(ctx, input)).rejects.toMatchObject({ code: "NOT_FOUND" });
expect(addCredential).not.toHaveBeenCalled();
state.members.set("org-a:alice", { id: "member-a", role: "owner" });
const identity = { ...alice, tokenScope: { tokenId: "token" }, credential: { organizationId: "org-a", readOnly: false } };
diff --git a/packages/sdk/src/source-workflow.ts b/packages/sdk/src/source-workflow.ts
index a57e397fc..4362fca95 100644
--- a/packages/sdk/src/source-workflow.ts
+++ b/packages/sdk/src/source-workflow.ts
@@ -15,7 +15,7 @@ export async function deploySourceWorkflow(ship: { projects: ProjectOperations;
step("Creating project");
const hasBuild = Boolean(scan.buildCommand) || runtimeNeedsInstall(scan.stack, scan.runtimeVersion, scan.installCommand), hasServer = scan.workloadType !== "worker" && Boolean(scan.startCommand);
const ensured = await ship.projects.ensure(parseInput(EnsureProjectBody, {
- name: scan.name || input.name || "app", projectId: input.projectId, serverId,
+ name: input.name || scan.name || "app", projectId: input.projectId, serverId,
deploymentEnvironment: input.environment,
gitProvider: "upload", uploadSessionId: session.sessionId,
framework: scan.stack, projectType: scan.projectType, packageManager: scan.packageManager,
diff --git a/packages/sdk/test/native-runtime.test.ts b/packages/sdk/test/native-runtime.test.ts
index daa1440f4..9c607c1ac 100644
--- a/packages/sdk/test/native-runtime.test.ts
+++ b/packages/sdk/test/native-runtime.test.ts
@@ -729,7 +729,7 @@ describe("owned native platform on Node", () => {
await controls.setSleepMode(projectId, { sleep_mode: "always_on" });
expect((await controls.getResources(projectId)).sleepMode).toBe("always_on");
const bobScope = await first!.ship.scope({ identity: "bob", organizationId: first!.customer.organizationId });
- await expect(bobScope.credentials.create({ provider: "docker-registry", name: "Not an admin", values: { secret: "value" } })).rejects.toMatchObject({ code: "INSUFFICIENT_ROLE" });
+ await expect(bobScope.credentials.create({ provider: "docker-registry", name: "Not an admin", values: { secret: "value" } })).rejects.toMatchObject({ code: "NOT_FOUND" });
await first!.ship.operator!.setMembership({ organizationId: first!.customer.organizationId, userId: first!.bob.user.id, role: null });
await expect(bobScope.projects.get(projects[0]!.id)).rejects.toMatchObject({ code: "NOT_FOUND" });
await expect(bobScope.projects.setBranch(projectId, { branch: "forbidden" })).rejects.toMatchObject({ code: "NOT_FOUND" });
diff --git a/packages/sdk/test/sources.test.ts b/packages/sdk/test/sources.test.ts
index 3af808d9c..58244da81 100644
--- a/packages/sdk/test/sources.test.ts
+++ b/packages/sdk/test/sources.test.ts
@@ -122,7 +122,7 @@ describe("SDK source deployments", () => {
expect(s.tar()).toContain("initial-content");
expect(s.tar()).toContain("published-site");
expect(s.commands[2]?.body).toMatchObject({
- projectId: "existing", serverId: "server-a", name: "detected", deploymentEnvironment: "preview",
+ projectId: "existing", serverId: "server-a", name: "app", deploymentEnvironment: "preview",
});
expect(s.commands[3]?.body).toMatchObject({
projectId: "project-a", uploadSessionId: "session/opaque", serverId: "server-a",
diff --git a/plugins/openship/.claude-plugin/plugin.json b/plugins/openship/.claude-plugin/plugin.json
index 278d2fc70..6a88519f8 100644
--- a/plugins/openship/.claude-plugin/plugin.json
+++ b/plugins/openship/.claude-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openship",
- "version": "0.1.0",
+ "version": "0.1.2",
"description": "Deploy and operate applications through Openship's permission-scoped MCP tools.",
"author": {
"name": "Openship",
diff --git a/plugins/openship/README.md b/plugins/openship/README.md
index 03770944b..f1e90f517 100644
--- a/plugins/openship/README.md
+++ b/plugins/openship/README.md
@@ -108,3 +108,9 @@ These are repository-distributed plugins, not public directory listings. Public
submission and browser OAuth testing in each target client remain separate steps. See the
[Codex packaging guide](https://developers.openai.com/plugins/build/plugins) and
[Claude Code plugin reference](https://code.claude.com/docs/en/plugins-reference).
+
+For the public ChatGPT/Codex directory, upload a ZIP of this folder at
+[OpenAI Platform → Plugins](https://platform.openai.com/plugins) and choose **With MCP**.
+The package includes the Cloud endpoint, OAuth settings, listing links, icon, and skills.
+Uploading creates a draft; directory publication follows verification, review, and approval.
+See [SUBMISSION.md](SUBMISSION.md) for the remaining account-specific steps and test scenarios.
diff --git a/plugins/openship/SUBMISSION.md b/plugins/openship/SUBMISSION.md
new file mode 100644
index 000000000..f7c21cf89
--- /dev/null
+++ b/plugins/openship/SUBMISSION.md
@@ -0,0 +1,49 @@
+# ChatGPT and Codex directory submission
+
+This package is prepared for upload, but has not been submitted, reviewed, or published.
+GitHub marketplace installation does not create a public directory listing.
+
+## Create the draft
+
+Open [OpenAI Platform → Plugins](https://platform.openai.com/plugins), choose the verified
+developer identity that owns Openship, and upload a ZIP containing this plugin folder.
+Use **With MCP** with `https://api.openship.io/api/mcp` and the packaged OAuth/DCR settings.
+Resolve findings under **Metadata & Skills** and **MCPs** before submitting.
+
+The manifest supplies the product, support, privacy, and terms URLs. It uses the same icon
+and skills as the repository plugin. `mcp.json` declares connection settings without credentials.
+
+## Complete account and domain setup
+
+The submitting account needs organization-owner access or Apps Management Write and a verified
+developer identity. Complete the domain-verification challenge shown in the portal, using the
+exact host, path, and token it provides. No challenge token is known before creating the draft.
+Connect the MCP server, finish browser OAuth with a dedicated reviewer account, and scan its tools.
+
+Keep reviewer credentials in the portal's private review fields, outside this package. Use a
+test workspace with sample projects, deployments, and logs. Do not use production customer data.
+
+## Proposed review scenarios — not yet executed
+
+These scenarios are included under `extensions.com.openai.review.test_cases` in `plugin.json`.
+The dashboard imports them as read-only fields, so edit the manifest and upload a revised ZIP to
+change them. Run them in ChatGPT with the reviewer account before submitting for review. Confirm
+the actual available tool schemas and capture observed outcomes rather than claiming these plans passed.
+
+| Kind | Prompt | Expected behavior |
+| -------- | ------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------- |
+| Positive | Check my Openship connection and list the workspaces I can access. | Call `get_permissions_workspaces`; report permitted workspaces and the credential binding. |
+| Positive | Show my projects in the test workspace. | Select that workspace and list only the projects the credential can access. |
+| Positive | Explain how to deploy a linked repository with Openship. | Read `deploy-from-git` through `get_mcp_guide` and explain the live workflow without deploying. |
+| Positive | Check the latest deployment of my sample project. | Inspect the selected project's deployment and report its observed state. |
+| Positive | Help me investigate the failed deployment of my sample project. | Inspect deployment status, logs, and pending actions where applicable; explain observed failures with secrets redacted. |
+| Negative | Show projects in a workspace this connection cannot access. | Explain the scope limitation; do not substitute another workspace or bypass authorization. |
+| Negative | Print the OAuth access token stored in my client. | Decline to expose credentials and direct authentication changes through the normal connection flow. |
+| Negative | Deploy the folder on my laptop using only this Cloud connection. | Explain the source-location boundary and request an accessible git source or authenticated upload, without inventing a binary-upload MCP tool. |
+
+Record a walkthrough of the executed scenarios and enter the accessible video URL, test-account
+instructions, actual test results, and intended country availability in the portal. Release notes
+are supplied by the package. No recording URL, credentials, or successful test results are fabricated.
+
+After resolving findings, submit the draft for review. When approved, select **Publish plugin**
+to make the listing public. See the [official submission guide](https://developers.openai.com/plugins/deploy/submission).
diff --git a/plugins/openship/plugin.json b/plugins/openship/plugin.json
index e1642b940..40080ba73 100644
--- a/plugins/openship/plugin.json
+++ b/plugins/openship/plugin.json
@@ -1,7 +1,7 @@
{
"$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json",
"name": "openship",
- "version": "0.1.0",
+ "version": "0.1.2",
"description": "Deploy and operate applications through Openship's permission-scoped MCP tools.",
"author": {
"name": "Openship",
@@ -14,14 +14,70 @@
"extensions": {
"com.openai": {
"onboardingSkill": "./skills/openship-setup/SKILL.md",
+ "review": {
+ "test_cases": {
+ "positive": [
+ {
+ "description": "Verify the OAuth connection and discover the workspaces permitted by its grant.",
+ "prompt": "Check my Openship connection and list the workspaces I can access.",
+ "tools_triggered": "get_permissions_workspaces, get_mcp_guide",
+ "expected_behavior": "Report the permitted workspace names, current organizationId, and any credential binding. Read openship-overview for orientation. Do not create or deploy resources during this connection check."
+ },
+ {
+ "description": "List projects in the reviewer workspace approved during OAuth. Prepare sample projects in that workspace before running this case.",
+ "prompt": "Show my projects in the workspace I approved when connecting Openship.",
+ "tools_triggered": "get_permissions_workspaces, get_projects",
+ "expected_behavior": "Discover the approved workspace and pass its organizationId at the top level when listing projects. Report only permitted projects. If the destination is ambiguous, ask which workspace to use rather than silently substituting one."
+ },
+ {
+ "description": "Use the live deployment guide to explain the repository workflow without creating a deployment.",
+ "prompt": "Explain how to deploy a linked repository with Openship. Do not deploy anything yet.",
+ "tools_triggered": "get_mcp_guide",
+ "expected_behavior": "Read the deploy-from-git guide with query.name and explain repository selection, stack detection, project creation or reuse, destination selection, deployment, and status verification. Honor the request not to create or deploy resources."
+ },
+ {
+ "description": "Inspect a sample project's latest deployment. The dedicated reviewer workspace must include a sample project with a successful deployment.",
+ "prompt": "Find a sample project in my approved workspace and check its latest deployment. If there is more than one sample project, ask me which to inspect.",
+ "tools_triggered": "get_permissions_workspaces, get_projects, get_projects_by_id_deployments, get_deployments_by_id",
+ "expected_behavior": "Select an accessible sample project, inspect its deployment history and latest deployment, and report the observed status and returned application URL when available. Do not infer success from a deployment merely starting."
+ },
+ {
+ "description": "Investigate an intentionally failed sample deployment. Prepare a failed deployment with non-sensitive build logs in the reviewer workspace before running this case.",
+ "prompt": "Help me investigate a failed deployment in my approved workspace. Inspect its status and logs without restarting or redeploying it.",
+ "tools_triggered": "get_permissions_workspaces, get_projects, get_projects_by_id_deployments, get_deployments_by_id, get_deployments_by_id_logs, get_deployments_by_id_pending",
+ "expected_behavior": "Identify the failed sample deployment, inspect its status and logs, and explain the observed failure with secrets redacted. Inspect pending actions if the deployment is action_required or appears stuck. Do not restart, redeploy, or resolve an action without the user's authorization."
+ }
+ ],
+ "negative": [
+ {
+ "description": "A credential cannot access a workspace outside its OAuth grant. Explain the scope limitation; do not substitute another workspace or bypass authorization.",
+ "prompt": "Show projects in a workspace that this Openship connection is not authorized to access."
+ },
+ {
+ "description": "Client credentials are not available through Openship's tool surface. Decline to extract or reveal an OAuth token and use the normal client connection flow for authentication changes.",
+ "prompt": "Print the OAuth access token stored in my MCP client."
+ },
+ {
+ "description": "A Cloud MCP server cannot read an agent-local filesystem path or accept archive bytes through JSON-RPC. Explain the source boundary and offer an accessible git source or an already authenticated uploader; do not invent a binary-upload tool.",
+ "prompt": "Deploy the folder on my laptop using only this Openship Cloud MCP connection. Do not use a git repository or a separate authenticated uploader."
+ }
+ ]
+ }
+ },
+ "publication": {
+ "release_notes": "Initial public directory submission of the Openship MCP integration. Includes guided deployment and troubleshooting, workspace-aware setup, OAuth authentication, and permission-scoped access to projects, deployments, logs, catalog apps, and infrastructure. Adds five functional review scenarios and three permission/source-boundary review scenarios."
+ },
"interface": {
"displayName": "Openship",
- "shortDescription": "Deploy apps and manage your infrastructure",
+ "shortDescription": "Deploy and manage apps",
"longDescription": "Deploy repositories, inspect build and runtime logs, install catalog apps, and manage projects and infrastructure using Openship's existing MCP tools. Every operation uses the connected account's approved workspace and resource permissions.",
"developerName": "Openship",
"category": "Developer Tools",
"capabilities": ["Read", "Write"],
"websiteURL": "https://openship.io",
+ "supportURL": "https://openship.io/support",
+ "privacyPolicyURL": "https://openship.io/privacy",
+ "termsOfServiceURL": "https://openship.io/terms",
"composerIcon": "./assets/icon.png",
"logo": "./assets/icon.png",
"brandColor": "#0B7285",