Phase 4: AI-driven app/database/auth lifecycle

Workspace-owned deploy infra so AI agents can create and destroy
Coolify resources without ever touching the root admin token.

  vibn_workspaces
    + coolify_server_uuid, coolify_destination_uuid
    + coolify_environment_name (default "production")
    + coolify_private_key_uuid, gitea_bot_ssh_key_id

  ensureWorkspaceProvisioned
    + generates an ed25519 keypair per workspace
    + pushes pubkey to the Gitea bot user (read/write scoped by team)
    + registers privkey in Coolify as a reusable deploy key

  New endpoints under /api/workspaces/[slug]/
    apps/                POST (private-deploy-key from Gitea repo)
    apps/[uuid]          PATCH, DELETE?confirm=<name>
    apps/[uuid]/domains  GET, PATCH (policy: *.{ws}.vibnai.com only)
    databases/           GET, POST (8 types incl. postgres, clickhouse, dragonfly)
    databases/[uuid]     GET, PATCH, DELETE?confirm=<name>
    auth/                GET, POST (Pocketbase, Authentik, Keycloak, Pocket-ID, Logto, Supertokens)
    auth/[uuid]          DELETE?confirm=<name>

  MCP (/api/mcp) gains 15 new tools that mirror the REST surface and
  enforce the same workspace tenancy + delete-confirm guard.

  Safety: destructive ops require ?confirm=<exact-resource-name>; volumes
  are kept by default (pass delete_volumes=true to drop).

Made-with: Cursor
This commit is contained in:
2026-04-21 12:04:59 -07:00
parent b51fb6da21
commit 0797717bc1
14 changed files with 2274 additions and 118 deletions

View File

@@ -2,30 +2,48 @@
* Coolify API client for Vibn project provisioning.
*
* Used server-side only. Credentials from env vars:
* COOLIFY_URL — e.g. http://34.19.250.135:8000
* COOLIFY_API_TOKEN — admin bearer token
* COOLIFY_URL — e.g. https://coolify.vibnai.com
* COOLIFY_API_TOKEN — admin bearer token
* COOLIFY_DEFAULT_SERVER_UUID — which Coolify server workspaces deploy to
* COOLIFY_DEFAULT_DESTINATION_UUID — Docker destination on that server
*/
const COOLIFY_URL = process.env.COOLIFY_URL ?? 'http://34.19.250.135:8000';
const COOLIFY_URL = process.env.COOLIFY_URL ?? 'https://coolify.vibnai.com';
const COOLIFY_API_TOKEN = process.env.COOLIFY_API_TOKEN ?? '';
const COOLIFY_DEFAULT_SERVER_UUID =
process.env.COOLIFY_DEFAULT_SERVER_UUID ?? 'jws4g4cgssss4cw48s488woc';
const COOLIFY_DEFAULT_DESTINATION_UUID =
process.env.COOLIFY_DEFAULT_DESTINATION_UUID ?? 'zkogkggkw0wg40gccks80oo0';
export interface CoolifyProject {
uuid: string;
name: string;
description?: string;
environments?: Array<{ id: number; uuid: string; name: string; project_id: number }>;
}
/** All database flavors Coolify v4 can provision. */
export type CoolifyDatabaseType =
| 'postgresql'
| 'mysql'
| 'mariadb'
| 'mongodb'
| 'redis'
| 'keydb'
| 'dragonfly'
| 'clickhouse';
export interface CoolifyDatabase {
uuid: string;
name: string;
type: string;
type?: string;
status: string;
internal_db_url?: string;
external_db_url?: string;
/** When true, Coolify publishes a host port for remote connections */
is_public?: boolean;
/** Host port mapped to 5432 inside the container */
public_port?: number;
project_uuid?: string;
environment?: { project_uuid?: string; project?: { uuid?: string } };
}
export interface CoolifyApplication {
@@ -33,11 +51,11 @@ export interface CoolifyApplication {
name: string;
status: string;
fqdn?: string;
domains?: string;
git_repository?: string;
git_branch?: string;
project_uuid?: string;
environment_name?: string;
/** Coolify sometimes nests these under an `environment` object */
environment?: { project_uuid?: string; project?: { uuid?: string } };
}
@@ -52,6 +70,29 @@ export interface CoolifyEnvVar {
is_shown_once?: boolean;
}
export interface CoolifyPrivateKey {
uuid: string;
name: string;
description?: string;
fingerprint?: string;
}
export interface CoolifyServer {
uuid: string;
name: string;
ip: string;
is_reachable?: boolean;
settings?: { wildcard_domain?: string | null };
}
export interface CoolifyDeployment {
uuid: string;
status: string;
created_at?: string;
finished_at?: string;
commit?: string;
}
async function coolifyFetch(path: string, options: RequestInit = {}) {
const url = `${COOLIFY_URL}/api/v1${path}`;
const res = await fetch(url, {
@@ -67,7 +108,6 @@ async function coolifyFetch(path: string, options: RequestInit = {}) {
const text = await res.text();
throw new Error(`Coolify API error ${res.status} on ${path}: ${text}`);
}
if (res.status === 204) return null;
return res.json();
}
@@ -96,82 +136,331 @@ export async function deleteProject(uuid: string): Promise<void> {
}
// ──────────────────────────────────────────────────
// Databases
// Servers
// ──────────────────────────────────────────────────
type DBType = 'postgresql' | 'mysql' | 'mariadb' | 'redis' | 'mongodb' | 'keydb';
export async function listServers(): Promise<CoolifyServer[]> {
return coolifyFetch('/servers');
}
export async function createDatabase(opts: {
projectUuid: string;
// ──────────────────────────────────────────────────
// Private keys (SSH deploy keys)
// ──────────────────────────────────────────────────
export async function listPrivateKeys(): Promise<CoolifyPrivateKey[]> {
return coolifyFetch('/security/keys');
}
export async function createPrivateKey(opts: {
name: string;
type: DBType;
serverUuid?: string;
environmentName?: string;
}): Promise<CoolifyDatabase> {
const { projectUuid, name, type, serverUuid = '0', environmentName = 'production' } = opts;
return coolifyFetch(`/databases`, {
privateKeyPem: string;
description?: string;
}): Promise<CoolifyPrivateKey> {
return coolifyFetch('/security/keys', {
method: 'POST',
body: JSON.stringify({
project_uuid: projectUuid,
name,
type,
server_uuid: serverUuid,
environment_name: environmentName,
name: opts.name,
private_key: opts.privateKeyPem,
description: opts.description ?? '',
}),
});
}
export async function deletePrivateKey(uuid: string): Promise<void> {
await coolifyFetch(`/security/keys/${uuid}`, { method: 'DELETE' });
}
// ──────────────────────────────────────────────────
// Databases (all 8 types)
// ──────────────────────────────────────────────────
/** Shared context used by every database-create call. */
export interface CoolifyDbCreateContext {
projectUuid: string;
serverUuid?: string;
environmentName?: string;
destinationUuid?: string;
instantDeploy?: boolean;
}
export interface CreateDatabaseOpts extends CoolifyDbCreateContext {
type: CoolifyDatabaseType;
name: string;
description?: string;
image?: string;
isPublic?: boolean;
publicPort?: number;
/** Type-specific credentials / config */
credentials?: Record<string, unknown>;
/** Resource limits */
limits?: { memory?: string; cpus?: string };
}
/**
* Create a database of the requested type. Dispatches to the right
* POST /databases/{type} endpoint and packs the right credential
* fields for each flavor.
*/
export async function createDatabase(opts: CreateDatabaseOpts): Promise<{ uuid: string }> {
const {
type, name,
projectUuid,
serverUuid = COOLIFY_DEFAULT_SERVER_UUID,
environmentName = 'production',
destinationUuid = COOLIFY_DEFAULT_DESTINATION_UUID,
instantDeploy = true,
description,
image,
isPublic,
publicPort,
credentials = {},
limits = {},
} = opts;
const common: Record<string, unknown> = {
project_uuid: projectUuid,
server_uuid: serverUuid,
environment_name: environmentName,
destination_uuid: destinationUuid,
name,
description,
image,
is_public: isPublic,
public_port: publicPort,
instant_deploy: instantDeploy,
limits_memory: limits.memory,
limits_cpus: limits.cpus,
};
return coolifyFetch(`/databases/${type}`, {
method: 'POST',
body: JSON.stringify(stripUndefined({ ...common, ...credentials })),
});
}
export async function listDatabases(): Promise<CoolifyDatabase[]> {
return coolifyFetch('/databases');
}
export async function getDatabase(uuid: string): Promise<CoolifyDatabase> {
return coolifyFetch(`/databases/${uuid}`);
}
export async function deleteDatabase(uuid: string): Promise<void> {
await coolifyFetch(`/databases/${uuid}`, { method: 'DELETE' });
export async function updateDatabase(uuid: string, patch: Record<string, unknown>): Promise<{ uuid: string }> {
return coolifyFetch(`/databases/${uuid}`, {
method: 'PATCH',
body: JSON.stringify(stripUndefined(patch)),
});
}
export async function deleteDatabase(
uuid: string,
opts: {
deleteConfigurations?: boolean;
deleteVolumes?: boolean;
dockerCleanup?: boolean;
deleteConnectedNetworks?: boolean;
} = {}
): Promise<void> {
const q = new URLSearchParams();
if (opts.deleteConfigurations !== undefined) q.set('delete_configurations', String(opts.deleteConfigurations));
if (opts.deleteVolumes !== undefined) q.set('delete_volumes', String(opts.deleteVolumes));
if (opts.dockerCleanup !== undefined) q.set('docker_cleanup', String(opts.dockerCleanup));
if (opts.deleteConnectedNetworks !== undefined) q.set('delete_connected_networks', String(opts.deleteConnectedNetworks));
const qs = q.toString();
await coolifyFetch(`/databases/${uuid}${qs ? '?' + qs : ''}`, { method: 'DELETE' });
}
export async function startDatabase(uuid: string): Promise<void> {
await coolifyFetch(`/databases/${uuid}/start`, { method: 'POST' });
}
export async function stopDatabase(uuid: string): Promise<void> {
await coolifyFetch(`/databases/${uuid}/stop`, { method: 'POST' });
}
export async function restartDatabase(uuid: string): Promise<void> {
await coolifyFetch(`/databases/${uuid}/restart`, { method: 'POST' });
}
// ──────────────────────────────────────────────────
// Applications
// ──────────────────────────────────────────────────
export async function createApplication(opts: {
export type CoolifyBuildPack = 'nixpacks' | 'static' | 'dockerfile' | 'dockercompose';
export interface CreatePrivateDeployKeyAppOpts {
projectUuid: string;
name: string;
gitRepo: string; // e.g. "https://git.vibnai.com/mark/taskmaster.git"
privateKeyUuid: string;
gitRepository: string; // SSH URL: git@git.vibnai.com:vibn-mark/repo.git
gitBranch?: string;
portsExposes: string; // "3000"
serverUuid?: string;
environmentName?: string;
buildPack?: string; // nixpacks, static, dockerfile
ports?: string; // e.g. "3000"
}): Promise<CoolifyApplication> {
const {
projectUuid, name, gitRepo,
gitBranch = 'main',
serverUuid = process.env.COOLIFY_SERVER_UUID ?? 'jws4g4cgssss4cw48s488woc',
environmentName = 'production',
buildPack = 'nixpacks',
ports = '3000',
} = opts;
destinationUuid?: string;
buildPack?: CoolifyBuildPack;
name?: string;
description?: string;
domains?: string; // comma-separated FQDNs
isAutoDeployEnabled?: boolean;
isForceHttpsEnabled?: boolean;
instantDeploy?: boolean;
installCommand?: string;
buildCommand?: string;
startCommand?: string;
baseDirectory?: string;
dockerfileLocation?: string;
manualWebhookSecretGitea?: string;
}
return coolifyFetch(`/applications`, {
export async function createPrivateDeployKeyApp(
opts: CreatePrivateDeployKeyAppOpts
): Promise<{ uuid: string }> {
const body = stripUndefined({
project_uuid: opts.projectUuid,
server_uuid: opts.serverUuid ?? COOLIFY_DEFAULT_SERVER_UUID,
environment_name: opts.environmentName ?? 'production',
destination_uuid: opts.destinationUuid ?? COOLIFY_DEFAULT_DESTINATION_UUID,
private_key_uuid: opts.privateKeyUuid,
git_repository: opts.gitRepository,
git_branch: opts.gitBranch ?? 'main',
build_pack: opts.buildPack ?? 'nixpacks',
ports_exposes: opts.portsExposes,
name: opts.name,
description: opts.description,
domains: opts.domains,
is_auto_deploy_enabled: opts.isAutoDeployEnabled ?? true,
is_force_https_enabled: opts.isForceHttpsEnabled ?? true,
instant_deploy: opts.instantDeploy ?? true,
install_command: opts.installCommand,
build_command: opts.buildCommand,
start_command: opts.startCommand,
base_directory: opts.baseDirectory,
dockerfile_location: opts.dockerfileLocation,
manual_webhook_secret_gitea: opts.manualWebhookSecretGitea,
});
return coolifyFetch('/applications/private-deploy-key', {
method: 'POST',
body: JSON.stringify({
project_uuid: projectUuid,
name,
git_repository: gitRepo,
git_branch: gitBranch,
server_uuid: serverUuid,
environment_name: environmentName,
build_pack: buildPack,
ports_exposes: ports,
}),
body: JSON.stringify(body),
});
}
/**
* Create a Coolify service for one app inside a Turborepo monorepo.
* Build command uses `turbo run build --filter` to target just that app.
*/
export interface CreatePublicAppOpts {
projectUuid: string;
gitRepository: string; // https URL
gitBranch?: string;
portsExposes: string;
serverUuid?: string;
environmentName?: string;
destinationUuid?: string;
buildPack?: CoolifyBuildPack;
name?: string;
description?: string;
domains?: string;
isAutoDeployEnabled?: boolean;
isForceHttpsEnabled?: boolean;
instantDeploy?: boolean;
}
export async function createPublicApp(opts: CreatePublicAppOpts): Promise<{ uuid: string }> {
const body = stripUndefined({
project_uuid: opts.projectUuid,
server_uuid: opts.serverUuid ?? COOLIFY_DEFAULT_SERVER_UUID,
environment_name: opts.environmentName ?? 'production',
destination_uuid: opts.destinationUuid ?? COOLIFY_DEFAULT_DESTINATION_UUID,
git_repository: opts.gitRepository,
git_branch: opts.gitBranch ?? 'main',
build_pack: opts.buildPack ?? 'nixpacks',
ports_exposes: opts.portsExposes,
name: opts.name,
description: opts.description,
domains: opts.domains,
is_auto_deploy_enabled: opts.isAutoDeployEnabled ?? true,
is_force_https_enabled: opts.isForceHttpsEnabled ?? true,
instant_deploy: opts.instantDeploy ?? true,
});
return coolifyFetch('/applications/public', {
method: 'POST',
body: JSON.stringify(body),
});
}
export async function updateApplication(
uuid: string,
patch: Record<string, unknown>
): Promise<{ uuid: string }> {
return coolifyFetch(`/applications/${uuid}`, {
method: 'PATCH',
body: JSON.stringify(stripUndefined(patch)),
});
}
export async function setApplicationDomains(
uuid: string,
domains: string[],
opts: { forceOverride?: boolean } = {}
): Promise<{ uuid: string }> {
return updateApplication(uuid, {
domains: domains.join(','),
force_domain_override: opts.forceOverride ?? true,
is_force_https_enabled: true,
});
}
export async function deleteApplication(
uuid: string,
opts: {
deleteConfigurations?: boolean;
deleteVolumes?: boolean;
dockerCleanup?: boolean;
deleteConnectedNetworks?: boolean;
} = {}
): Promise<void> {
const q = new URLSearchParams();
if (opts.deleteConfigurations !== undefined) q.set('delete_configurations', String(opts.deleteConfigurations));
if (opts.deleteVolumes !== undefined) q.set('delete_volumes', String(opts.deleteVolumes));
if (opts.dockerCleanup !== undefined) q.set('docker_cleanup', String(opts.dockerCleanup));
if (opts.deleteConnectedNetworks !== undefined) q.set('delete_connected_networks', String(opts.deleteConnectedNetworks));
const qs = q.toString();
await coolifyFetch(`/applications/${uuid}${qs ? '?' + qs : ''}`, { method: 'DELETE' });
}
export async function listApplications(): Promise<CoolifyApplication[]> {
return coolifyFetch('/applications');
}
export async function deployApplication(uuid: string): Promise<{ deployment_uuid: string }> {
return coolifyFetch(`/applications/${uuid}/deploy`, { method: 'POST' });
}
export async function getApplication(uuid: string): Promise<CoolifyApplication> {
return coolifyFetch(`/applications/${uuid}`);
}
export async function startApplication(uuid: string): Promise<void> {
await coolifyFetch(`/applications/${uuid}/start`, { method: 'POST' });
}
export async function stopApplication(uuid: string): Promise<void> {
await coolifyFetch(`/applications/${uuid}/stop`, { method: 'POST' });
}
export async function restartApplication(uuid: string): Promise<void> {
await coolifyFetch(`/applications/${uuid}/restart`, { method: 'POST' });
}
export async function getDeploymentLogs(deploymentUuid: string): Promise<{ logs: string }> {
return coolifyFetch(`/deployments/${deploymentUuid}/logs`);
}
export async function listApplicationDeployments(uuid: string): Promise<CoolifyDeployment[]> {
return coolifyFetch(`/applications/${uuid}/deployments`);
}
// ──────────────────────────────────────────────────
// Legacy monorepo helper (still used by older flows)
// ──────────────────────────────────────────────────
export async function createMonorepoAppService(opts: {
projectUuid: string;
appName: string;
@@ -185,10 +474,9 @@ export async function createMonorepoAppService(opts: {
projectUuid, appName, gitRepo,
gitBranch = 'main',
domain,
serverUuid = process.env.COOLIFY_SERVER_UUID ?? 'jws4g4cgssss4cw48s488woc',
serverUuid = COOLIFY_DEFAULT_SERVER_UUID,
environmentName = 'production',
} = opts;
return coolifyFetch(`/applications`, {
method: 'POST',
body: JSON.stringify({
@@ -207,32 +495,6 @@ export async function createMonorepoAppService(opts: {
});
}
export async function listApplications(): Promise<CoolifyApplication[]> {
return coolifyFetch('/applications');
}
export async function deployApplication(uuid: string): Promise<{ deployment_uuid: string }> {
return coolifyFetch(`/applications/${uuid}/deploy`, { method: 'POST' });
}
export async function getApplication(uuid: string): Promise<CoolifyApplication> {
return coolifyFetch(`/applications/${uuid}`);
}
export async function getDeploymentLogs(deploymentUuid: string): Promise<{ logs: string }> {
return coolifyFetch(`/deployments/${deploymentUuid}/logs`);
}
export async function listApplicationDeployments(uuid: string): Promise<Array<{
uuid: string;
status: string;
created_at?: string;
finished_at?: string;
commit?: string;
}>> {
return coolifyFetch(`/applications/${uuid}/deployments`);
}
// ──────────────────────────────────────────────────
// Environment variables
// ──────────────────────────────────────────────────
@@ -245,8 +507,6 @@ export async function upsertApplicationEnv(
uuid: string,
env: CoolifyEnvVar & { is_preview?: boolean }
): Promise<CoolifyEnvVar> {
// Coolify accepts PATCH for updates and POST for creates. We try
// PATCH first (idempotent upsert on key), fall back to POST.
try {
return await coolifyFetch(`/applications/${uuid}/envs`, {
method: 'PATCH',
@@ -271,27 +531,82 @@ export async function deleteApplicationEnv(uuid: string, key: string): Promise<v
}
// ──────────────────────────────────────────────────
// Tenant helpers
// Services (raw Coolify service resources)
// ──────────────────────────────────────────────────
/**
* Return the Coolify project UUID an application belongs to, working
* around Coolify v4 sometimes nesting it under `environment`.
*/
export function projectUuidOf(app: CoolifyApplication): string | null {
export interface CoolifyService {
uuid: string;
name: string;
status?: string;
project_uuid?: string;
environment?: { project_uuid?: string; project?: { uuid?: string } };
}
export async function listServices(): Promise<CoolifyService[]> {
return coolifyFetch('/services');
}
export async function getService(uuid: string): Promise<CoolifyService> {
return coolifyFetch(`/services/${uuid}`);
}
export async function createService(opts: {
projectUuid: string;
type: string; // e.g. "pocketbase", "authentik", "zitadel"
name: string;
description?: string;
serverUuid?: string;
environmentName?: string;
destinationUuid?: string;
instantDeploy?: boolean;
}): Promise<{ uuid: string }> {
const body = stripUndefined({
project_uuid: opts.projectUuid,
server_uuid: opts.serverUuid ?? COOLIFY_DEFAULT_SERVER_UUID,
environment_name: opts.environmentName ?? 'production',
destination_uuid: opts.destinationUuid ?? COOLIFY_DEFAULT_DESTINATION_UUID,
type: opts.type,
name: opts.name,
description: opts.description,
instant_deploy: opts.instantDeploy ?? true,
});
return coolifyFetch('/services', { method: 'POST', body: JSON.stringify(body) });
}
export async function deleteService(
uuid: string,
opts: {
deleteConfigurations?: boolean;
deleteVolumes?: boolean;
dockerCleanup?: boolean;
deleteConnectedNetworks?: boolean;
} = {}
): Promise<void> {
const q = new URLSearchParams();
if (opts.deleteConfigurations !== undefined) q.set('delete_configurations', String(opts.deleteConfigurations));
if (opts.deleteVolumes !== undefined) q.set('delete_volumes', String(opts.deleteVolumes));
if (opts.dockerCleanup !== undefined) q.set('docker_cleanup', String(opts.dockerCleanup));
if (opts.deleteConnectedNetworks !== undefined) q.set('delete_connected_networks', String(opts.deleteConnectedNetworks));
const qs = q.toString();
await coolifyFetch(`/services/${uuid}${qs ? '?' + qs : ''}`, { method: 'DELETE' });
}
// ──────────────────────────────────────────────────
// Tenant helpers — every endpoint that returns an app/db/service runs
// through one of these so cross-project access is impossible.
// ──────────────────────────────────────────────────
export function projectUuidOf(
resource: CoolifyApplication | CoolifyDatabase | CoolifyService
): string | null {
return (
app.project_uuid ??
app.environment?.project_uuid ??
app.environment?.project?.uuid ??
resource.project_uuid ??
resource.environment?.project_uuid ??
resource.environment?.project?.uuid ??
null
);
}
/**
* Fetch an application AND verify it lives in the expected Coolify
* project. Throws a `TenantError` when the app is cross-tenant so
* callers can translate to HTTP 403.
*/
export class TenantError extends Error {
status = 403 as const;
}
@@ -310,10 +625,65 @@ export async function getApplicationInProject(
return app;
}
/** List applications that belong to the given Coolify project. */
export async function getDatabaseInProject(
dbUuid: string,
expectedProjectUuid: string
): Promise<CoolifyDatabase> {
const db = await getDatabase(dbUuid);
const actualProject = projectUuidOf(db);
if (!actualProject || actualProject !== expectedProjectUuid) {
throw new TenantError(
`Database ${dbUuid} does not belong to project ${expectedProjectUuid}`
);
}
return db;
}
export async function getServiceInProject(
serviceUuid: string,
expectedProjectUuid: string
): Promise<CoolifyService> {
const svc = await getService(serviceUuid);
const actualProject = projectUuidOf(svc);
if (!actualProject || actualProject !== expectedProjectUuid) {
throw new TenantError(
`Service ${serviceUuid} does not belong to project ${expectedProjectUuid}`
);
}
return svc;
}
export async function listApplicationsInProject(
projectUuid: string
): Promise<CoolifyApplication[]> {
const all = await listApplications();
return all.filter(a => projectUuidOf(a) === projectUuid);
}
export async function listDatabasesInProject(
projectUuid: string
): Promise<CoolifyDatabase[]> {
const all = await listDatabases();
return all.filter(d => projectUuidOf(d) === projectUuid);
}
export async function listServicesInProject(
projectUuid: string
): Promise<CoolifyService[]> {
const all = await listServices();
return all.filter(s => projectUuidOf(s) === projectUuid);
}
// ──────────────────────────────────────────────────
// util
// ──────────────────────────────────────────────────
function stripUndefined<T extends Record<string, unknown>>(obj: T): Partial<T> {
const out: Partial<T> = {};
for (const [k, v] of Object.entries(obj)) {
if (v !== undefined) (out as Record<string, unknown>)[k] = v;
}
return out;
}
export { COOLIFY_DEFAULT_SERVER_UUID, COOLIFY_DEFAULT_DESTINATION_UUID };

View File

@@ -334,6 +334,54 @@ export async function ensureOrgTeamMembership(opts: {
return team;
}
// ──────────────────────────────────────────────────
// Admin: SSH keys on a user (for Coolify deploy-key flow)
// ──────────────────────────────────────────────────
export interface GiteaSshKey {
id: number;
key: string;
title: string;
fingerprint?: string;
read_only?: boolean;
}
/**
* Register an SSH public key under a target user via the admin API.
* The resulting key gives anyone holding the matching private key the
* same repo-read access as the user (bounded by that user's team
* memberships — for bots, usually read/write on one org only).
*/
export async function adminAddUserSshKey(opts: {
username: string;
title: string;
key: string; // OpenSSH-format public key, e.g. "ssh-ed25519 AAAAC3... comment"
readOnly?: boolean;
}): Promise<GiteaSshKey> {
return giteaFetch(`/admin/users/${opts.username}/keys`, {
method: 'POST',
body: JSON.stringify({
title: opts.title,
key: opts.key,
read_only: opts.readOnly ?? false,
}),
});
}
/**
* List SSH keys for a user (admin view).
*/
export async function adminListUserSshKeys(username: string): Promise<GiteaSshKey[]> {
return giteaFetch(`/users/${username}/keys`);
}
/**
* Delete an SSH key by id (owned by a user). Used when rotating keys.
*/
export async function adminDeleteUserSshKey(keyId: number): Promise<void> {
await giteaFetch(`/admin/users/keys/${keyId}`, { method: 'DELETE' });
}
/**
* Get an existing repo.
*/

69
lib/naming.ts Normal file
View File

@@ -0,0 +1,69 @@
/**
* Canonical name + domain derivation for workspace-scoped resources.
*
* AI-generated Coolify apps live under a single subdomain namespace
* per workspace:
*
* https://{app-slug}.{workspace-slug}.vibnai.com
*
* e.g. `api.mark.vibnai.com` for the `api` app in workspace `mark`.
*
* The DNS record `*.vibnai.com` (or its subdomain) must resolve to
* the Coolify server. Traefik picks up the Host header and Coolify's
* per-app ACME handshake provisions a Let's Encrypt cert per FQDN.
*/
const VIBN_BASE_DOMAIN = process.env.VIBN_BASE_DOMAIN ?? 'vibnai.com';
const SLUG_STRIP = /[^a-z0-9-]+/g;
/** Lowercase, dash-sanitize a free-form name into a DNS-safe slug. */
export function slugify(name: string): string {
return name
.toLowerCase()
.replace(/[_\s]+/g, '-')
.replace(SLUG_STRIP, '')
.replace(/-+/g, '-')
.replace(/^-+|-+$/g, '')
.slice(0, 40) || 'app';
}
/**
* The default public FQDN for an app inside a workspace, given the
* workspace's slug (e.g. `mark`) and an app slug (e.g. `my-api`).
*
* workspaceAppFqdn('mark', 'my-api') === 'my-api.mark.vibnai.com'
*/
export function workspaceAppFqdn(workspaceSlug: string, appSlug: string): string {
return `${appSlug}.${workspaceSlug}.${VIBN_BASE_DOMAIN}`;
}
/** `https://{fqdn}` — what Coolify's `domains` field expects. */
export function toDomainsString(fqdns: string[]): string {
return fqdns.map(f => (f.startsWith('http') ? f : `https://${f}`)).join(',');
}
/** Parse a Coolify `domains` CSV back into bare FQDNs. */
export function parseDomainsString(domains: string | null | undefined): string[] {
if (!domains) return [];
return domains
.split(/[,\s]+/)
.map(d => d.trim())
.filter(Boolean)
.map(d => d.replace(/^https?:\/\//, '').replace(/\/+$/, ''));
}
/** Guard against cross-workspace or disallowed domains. */
export function isDomainUnderWorkspace(fqdn: string, workspaceSlug: string): boolean {
const f = fqdn.replace(/^https?:\/\//, '').toLowerCase();
return f === `${workspaceSlug}.${VIBN_BASE_DOMAIN}` || f.endsWith(`.${workspaceSlug}.${VIBN_BASE_DOMAIN}`);
}
/**
* Build a Gitea SSH clone URL for a repo in a workspace's org.
* Matches what Coolify's `private-deploy-key` flow expects.
*/
export function giteaSshUrl(org: string, repo: string, giteaHost = 'git.vibnai.com'): string {
return `git@${giteaHost}:${org}/${repo}.git`;
}
export { VIBN_BASE_DOMAIN };

80
lib/ssh-keys.ts Normal file
View File

@@ -0,0 +1,80 @@
/**
* ed25519 SSH keypair generation for per-workspace Coolify deploy keys.
*
* We generate once at provisioning time:
* - public key in OpenSSH format (for Gitea's SSH keys API)
* - private key in PKCS8 PEM (Coolify accepts this via /security/keys)
*
* Keys live in memory just long enough to be pushed to Gitea and Coolify;
* neither is ever persisted by Vibn directly (Coolify holds the private
* key, Gitea holds the public key). We keep the Coolify key uuid and the
* Gitea key id on vibn_workspaces so we can rotate them later.
*/
import { generateKeyPairSync, createPublicKey, type KeyObject } from 'crypto';
export interface Ed25519Keypair {
/** PKCS8 PEM — what Coolify's POST /security/keys wants. */
privateKeyPem: string;
/** OpenSSH public-key line: "ssh-ed25519 AAAA… <comment>" */
publicKeyOpenSsh: string;
/** SHA256 fingerprint string (without the trailing "=") */
fingerprint: string;
}
export function generateEd25519Keypair(comment = ''): Ed25519Keypair {
const { privateKey, publicKey } = generateKeyPairSync('ed25519', {
privateKeyEncoding: { type: 'pkcs8', format: 'pem' },
publicKeyEncoding: { type: 'spki', format: 'pem' },
});
const pubKeyObj = createPublicKey(publicKey);
const publicKeyOpenSsh = ed25519PublicKeyToOpenSsh(pubKeyObj, comment);
return {
privateKeyPem: privateKey,
publicKeyOpenSsh,
fingerprint: opensshFingerprint(publicKeyOpenSsh),
};
}
/**
* Convert a Node ed25519 public KeyObject into an OpenSSH-format line.
* Wire format for the base64 blob:
* uint32 len=11 | "ssh-ed25519" | uint32 len=32 | raw-pubkey-bytes
*/
function ed25519PublicKeyToOpenSsh(publicKey: KeyObject, comment: string): string {
const jwk = publicKey.export({ format: 'jwk' }) as { x?: string };
if (!jwk.x) {
throw new Error('public key has no jwk.x component — not ed25519?');
}
const rawKey = Buffer.from(jwk.x, 'base64url');
if (rawKey.length !== 32) {
throw new Error(`expected 32-byte ed25519 pubkey, got ${rawKey.length}`);
}
const keyTypeBytes = Buffer.from('ssh-ed25519');
const blob = Buffer.concat([
uint32BE(keyTypeBytes.length),
keyTypeBytes,
uint32BE(rawKey.length),
rawKey,
]).toString('base64');
const tail = comment ? ` ${comment}` : '';
return `ssh-ed25519 ${blob}${tail}`;
}
function uint32BE(n: number): Buffer {
const b = Buffer.alloc(4);
b.writeUInt32BE(n);
return b;
}
/**
* OpenSSH `ssh-keygen -lf`-style SHA256 fingerprint of a public key line.
*/
function opensshFingerprint(publicKeyLine: string): string {
const b64 = publicKeyLine.trim().split(/\s+/)[1];
if (!b64) return '';
const raw = Buffer.from(b64, 'base64');
const { createHash } = require('crypto') as typeof import('crypto');
const fp = createHash('sha256').update(raw).digest('base64');
return `SHA256:${fp.replace(/=+$/, '')}`;
}

View File

@@ -19,7 +19,12 @@
import { randomBytes } from 'crypto';
import { query, queryOne } from '@/lib/db-postgres';
import { createProject as createCoolifyProject } from '@/lib/coolify';
import {
createProject as createCoolifyProject,
createPrivateKey as createCoolifyPrivateKey,
COOLIFY_DEFAULT_SERVER_UUID,
COOLIFY_DEFAULT_DESTINATION_UUID,
} from '@/lib/coolify';
import {
createOrg,
getOrg,
@@ -29,8 +34,11 @@ import {
createAccessTokenFor,
ensureOrgTeamMembership,
adminEditUser,
adminAddUserSshKey,
adminListUserSshKeys,
} from '@/lib/gitea';
import { encryptSecret, decryptSecret } from '@/lib/auth/secret-box';
import { generateEd25519Keypair } from '@/lib/ssh-keys';
export interface VibnWorkspace {
id: string;
@@ -39,10 +47,15 @@ export interface VibnWorkspace {
owner_user_id: string;
coolify_project_uuid: string | null;
coolify_team_id: number | null;
coolify_server_uuid: string | null;
coolify_destination_uuid: string | null;
coolify_environment_name: string;
coolify_private_key_uuid: string | null;
gitea_org: string | null;
gitea_bot_username: string | null;
gitea_bot_user_id: number | null;
gitea_bot_token_encrypted: string | null;
gitea_bot_ssh_key_id: number | null;
provision_status: 'pending' | 'partial' | 'ready' | 'error';
provision_error: string | null;
created_at: Date;
@@ -183,11 +196,18 @@ export async function ensureWorkspaceProvisioned(workspace: VibnWorkspace): Prom
workspace.coolify_project_uuid &&
workspace.gitea_org &&
workspace.gitea_bot_username &&
workspace.gitea_bot_token_encrypted;
workspace.gitea_bot_token_encrypted &&
workspace.coolify_private_key_uuid &&
workspace.gitea_bot_ssh_key_id;
if (fullyProvisioned) return workspace;
let coolifyUuid = workspace.coolify_project_uuid;
let giteaOrg = workspace.gitea_org;
let coolifyServerUuid = workspace.coolify_server_uuid ?? COOLIFY_DEFAULT_SERVER_UUID;
let coolifyDestinationUuid =
workspace.coolify_destination_uuid ?? COOLIFY_DEFAULT_DESTINATION_UUID;
let coolifyPrivateKeyUuid = workspace.coolify_private_key_uuid;
let giteaBotSshKeyId = workspace.gitea_bot_ssh_key_id;
const errors: string[] = [];
// ── Coolify Project ────────────────────────────────────────────────
@@ -323,20 +343,83 @@ export async function ensureWorkspaceProvisioned(workspace: VibnWorkspace): Prom
}
}
const allReady = !!(coolifyUuid && giteaOrg && botUsername && botTokenEncrypted);
// ── Per-workspace SSH deploy keypair ──────────────────────────────
// Used by Coolify to clone private Gitea repos this workspace owns.
// We generate the keypair in-process, push the public key to Gitea
// (under the bot user so its team memberships scope repo access),
// and register the private key in Coolify. Neither key is ever
// persisted directly by Vibn — we only keep their ids.
if (botUsername && (!coolifyPrivateKeyUuid || !giteaBotSshKeyId)) {
try {
const comment = `vibn-${workspace.slug}@${botUsername}`;
const kp = generateEd25519Keypair(comment);
// Register public key on Gitea bot if not already present.
if (!giteaBotSshKeyId) {
// Protect against double-adding on re-provisioning by looking
// for an existing key with our canonical title first.
const title = `vibn-${workspace.slug}-coolify`;
let existingId: number | null = null;
try {
const keys = await adminListUserSshKeys(botUsername);
existingId = keys.find(k => k.title === title)?.id ?? null;
} catch {
/* list failure is non-fatal */
}
if (existingId) {
giteaBotSshKeyId = existingId;
} else {
const added = await adminAddUserSshKey({
username: botUsername,
title,
key: kp.publicKeyOpenSsh,
readOnly: false,
});
giteaBotSshKeyId = added.id;
}
}
// Register private key in Coolify if not already present.
if (!coolifyPrivateKeyUuid) {
const created = await createCoolifyPrivateKey({
name: `vibn-${workspace.slug}-gitea`,
description: `Workspace ${workspace.slug} Gitea deploy key (${kp.fingerprint})`,
privateKeyPem: kp.privateKeyPem,
});
coolifyPrivateKeyUuid = created.uuid;
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
errors.push(`ssh-key: ${msg}`);
console.error('[workspaces] SSH deploy-key provisioning failed', workspace.slug, msg);
}
}
const allReady = !!(
coolifyUuid &&
giteaOrg &&
botUsername &&
botTokenEncrypted &&
coolifyPrivateKeyUuid &&
giteaBotSshKeyId
);
const status: VibnWorkspace['provision_status'] =
allReady ? 'ready' : errors.length > 0 ? 'partial' : 'pending';
const updated = await query<VibnWorkspace>(
`UPDATE vibn_workspaces
SET coolify_project_uuid = COALESCE($2, coolify_project_uuid),
gitea_org = COALESCE($3, gitea_org),
gitea_bot_username = COALESCE($4, gitea_bot_username),
gitea_bot_user_id = COALESCE($5, gitea_bot_user_id),
gitea_bot_token_encrypted= COALESCE($6, gitea_bot_token_encrypted),
provision_status = $7,
provision_error = $8,
updated_at = now()
SET coolify_project_uuid = COALESCE($2, coolify_project_uuid),
gitea_org = COALESCE($3, gitea_org),
gitea_bot_username = COALESCE($4, gitea_bot_username),
gitea_bot_user_id = COALESCE($5, gitea_bot_user_id),
gitea_bot_token_encrypted = COALESCE($6, gitea_bot_token_encrypted),
coolify_server_uuid = COALESCE($7, coolify_server_uuid),
coolify_destination_uuid = COALESCE($8, coolify_destination_uuid),
coolify_private_key_uuid = COALESCE($9, coolify_private_key_uuid),
gitea_bot_ssh_key_id = COALESCE($10, gitea_bot_ssh_key_id),
provision_status = $11,
provision_error = $12,
updated_at = now()
WHERE id = $1
RETURNING *`,
[
@@ -346,6 +429,10 @@ export async function ensureWorkspaceProvisioned(workspace: VibnWorkspace): Prom
botUsername,
botUserId,
botTokenEncrypted,
coolifyServerUuid,
coolifyDestinationUuid,
coolifyPrivateKeyUuid,
giteaBotSshKeyId,
status,
errors.length ? errors.join('; ') : null,
]