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

@@ -0,0 +1,114 @@
/**
* GET /api/workspaces/[slug]/apps/[uuid]/domains — list current domains
* PATCH /api/workspaces/[slug]/apps/[uuid]/domains — replace domain set
*
* Body: { domains: string[] } — each must end with .{workspace}.vibnai.com.
* We enforce workspace-subdomain policy here to prevent AI-driven
* hijacking of other workspaces' subdomains.
*/
import { NextResponse } from 'next/server';
import { requireWorkspacePrincipal } from '@/lib/auth/workspace-auth';
import {
getApplicationInProject,
setApplicationDomains,
TenantError,
} from '@/lib/coolify';
import {
isDomainUnderWorkspace,
parseDomainsString,
workspaceAppFqdn,
slugify,
} from '@/lib/naming';
export async function GET(
request: Request,
{ params }: { params: Promise<{ slug: string; uuid: string }> }
) {
const { slug, uuid } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (!ws.coolify_project_uuid) {
return NextResponse.json({ error: 'Workspace has no Coolify project yet' }, { status: 503 });
}
try {
const app = await getApplicationInProject(uuid, ws.coolify_project_uuid);
return NextResponse.json({
uuid: app.uuid,
name: app.name,
domains: parseDomainsString(app.domains ?? app.fqdn ?? ''),
workspaceDomainSuffix: `${ws.slug}.vibnai.com`,
});
} catch (err) {
if (err instanceof TenantError) {
return NextResponse.json({ error: err.message }, { status: 403 });
}
return NextResponse.json({ error: 'App not found' }, { status: 404 });
}
}
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ slug: string; uuid: string }> }
) {
const { slug, uuid } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (!ws.coolify_project_uuid) {
return NextResponse.json({ error: 'Workspace has no Coolify project yet' }, { status: 503 });
}
let app;
try {
app = await getApplicationInProject(uuid, ws.coolify_project_uuid);
} catch (err) {
if (err instanceof TenantError) {
return NextResponse.json({ error: err.message }, { status: 403 });
}
return NextResponse.json({ error: 'App not found' }, { status: 404 });
}
let body: { domains?: string[] } = {};
try {
body = await request.json();
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
const raw = Array.isArray(body.domains) ? body.domains : [];
if (raw.length === 0) {
return NextResponse.json({ error: '`domains` must be a non-empty array' }, { status: 400 });
}
// Normalize + policy-check.
const normalized: string[] = [];
for (const d of raw) {
if (typeof d !== 'string' || !d.trim()) continue;
const clean = d.replace(/^https?:\/\//, '').replace(/\/+$/, '').toLowerCase();
if (!isDomainUnderWorkspace(clean, ws.slug)) {
return NextResponse.json(
{
error: `Domain ${clean} is not allowed; must end with .${ws.slug}.vibnai.com`,
hint: `Use ${workspaceAppFqdn(ws.slug, slugify(app.name))}`,
},
{ status: 403 }
);
}
normalized.push(clean);
}
try {
await setApplicationDomains(uuid, normalized, { forceOverride: true });
return NextResponse.json({ ok: true, uuid, domains: normalized });
} catch (err) {
return NextResponse.json(
{ error: 'Coolify domain update failed', details: err instanceof Error ? err.message : String(err) },
{ status: 502 }
);
}
}

View File

@@ -1,13 +1,23 @@
/**
* GET /api/workspaces/[slug]/apps/[uuid]
* GET /api/workspaces/[slug]/apps/[uuid] — app details
* PATCH /api/workspaces/[slug]/apps/[uuid] — update fields (name/branch/build config)
* DELETE /api/workspaces/[slug]/apps/[uuid]?confirm=<name>
* — destroy app. Volumes kept by default.
*
* Single Coolify app details. Verifies the app's project uuid matches
* the workspace's before returning anything.
* All verify the app's project uuid matches the workspace's before
* acting. DELETE additionally requires `?confirm=<exact-resource-name>`
* to prevent AI-driven accidents.
*/
import { NextResponse } from 'next/server';
import { requireWorkspacePrincipal } from '@/lib/auth/workspace-auth';
import { getApplicationInProject, projectUuidOf, TenantError } from '@/lib/coolify';
import {
getApplicationInProject,
projectUuidOf,
TenantError,
updateApplication,
deleteApplication,
} from '@/lib/coolify';
export async function GET(
request: Request,
@@ -29,6 +39,7 @@ export async function GET(
name: app.name,
status: app.status,
fqdn: app.fqdn ?? null,
domains: app.domains ?? null,
gitRepository: app.git_repository ?? null,
gitBranch: app.git_branch ?? null,
projectUuid: projectUuidOf(app),
@@ -43,3 +54,128 @@ export async function GET(
);
}
}
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ slug: string; uuid: string }> }
) {
const { slug, uuid } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (!ws.coolify_project_uuid) {
return NextResponse.json({ error: 'Workspace has no Coolify project yet' }, { status: 503 });
}
// Verify tenancy first (400-style fail fast on cross-tenant access).
try {
await getApplicationInProject(uuid, ws.coolify_project_uuid);
} catch (err) {
if (err instanceof TenantError) {
return NextResponse.json({ error: err.message }, { status: 403 });
}
return NextResponse.json({ error: 'App not found' }, { status: 404 });
}
let body: Record<string, unknown> = {};
try {
body = await request.json();
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
// Whitelist which Coolify fields we expose to AI-level callers.
// Domains are managed via the dedicated /domains subroute.
const allowed = new Set([
'name',
'description',
'git_branch',
'build_pack',
'ports_exposes',
'install_command',
'build_command',
'start_command',
'base_directory',
'dockerfile_location',
'is_auto_deploy_enabled',
'is_force_https_enabled',
'static_image',
]);
const patch: Record<string, unknown> = {};
for (const [k, v] of Object.entries(body)) {
if (allowed.has(k) && v !== undefined) patch[k] = v;
}
if (Object.keys(patch).length === 0) {
return NextResponse.json({ error: 'No updatable fields in body' }, { status: 400 });
}
try {
await updateApplication(uuid, patch);
return NextResponse.json({ ok: true, uuid });
} catch (err) {
return NextResponse.json(
{ error: 'Coolify update failed', details: err instanceof Error ? err.message : String(err) },
{ status: 502 }
);
}
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ slug: string; uuid: string }> }
) {
const { slug, uuid } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (!ws.coolify_project_uuid) {
return NextResponse.json({ error: 'Workspace has no Coolify project yet' }, { status: 503 });
}
// Resolve the app and verify tenancy.
let app;
try {
app = await getApplicationInProject(uuid, ws.coolify_project_uuid);
} catch (err) {
if (err instanceof TenantError) {
return NextResponse.json({ error: err.message }, { status: 403 });
}
return NextResponse.json({ error: 'App not found' }, { status: 404 });
}
// Require `?confirm=<exact app name>` to prevent accidental destroys.
const url = new URL(request.url);
const confirm = url.searchParams.get('confirm');
if (confirm !== app.name) {
return NextResponse.json(
{
error: 'Confirmation required',
hint: `Pass ?confirm=${app.name} to delete this app`,
},
{ status: 409 }
);
}
// Default: preserve volumes (user data). Caller can opt in.
const deleteVolumes = url.searchParams.get('delete_volumes') === 'true';
const deleteConfigurations = url.searchParams.get('delete_configurations') !== 'false';
const deleteConnectedNetworks = url.searchParams.get('delete_connected_networks') !== 'false';
const dockerCleanup = url.searchParams.get('docker_cleanup') !== 'false';
try {
await deleteApplication(uuid, {
deleteConfigurations,
deleteVolumes,
deleteConnectedNetworks,
dockerCleanup,
});
return NextResponse.json({ ok: true, deleted: { uuid, name: app.name, volumesKept: !deleteVolumes } });
} catch (err) {
return NextResponse.json(
{ error: 'Coolify delete failed', details: err instanceof Error ? err.message : String(err) },
{ status: 502 }
);
}
}

View File

@@ -1,15 +1,43 @@
/**
* GET /api/workspaces/[slug]/apps — list Coolify apps in this workspace
* GET /api/workspaces/[slug]/apps — list Coolify apps in this workspace
* POST /api/workspaces/[slug]/apps — create a new app from a Gitea repo
*
* Auth: session OR `Bearer vibn_sk_...`. The workspace's
* `coolify_project_uuid` acts as the tenant boundary — any app whose
* Coolify project uuid doesn't match is filtered out even if the
* token issuer accidentally had wider reach.
*
* POST body:
* {
* repo: string, // "my-api" or "{org}/my-api"
* branch?: string, // default: "main"
* name?: string, // default: derived from repo
* ports?: string, // default: "3000"
* buildPack?: "nixpacks"|"static"|"dockerfile"|"dockercompose"
* domain?: string, // default: {app}.{workspace}.vibnai.com
* envs?: Record<string,string>
* instantDeploy?: boolean, // default: true
* }
*/
import { NextResponse } from 'next/server';
import { requireWorkspacePrincipal } from '@/lib/auth/workspace-auth';
import { listApplicationsInProject, projectUuidOf } from '@/lib/coolify';
import {
listApplicationsInProject,
projectUuidOf,
createPrivateDeployKeyApp,
upsertApplicationEnv,
getApplication,
deployApplication,
} from '@/lib/coolify';
import {
slugify,
workspaceAppFqdn,
toDomainsString,
isDomainUnderWorkspace,
giteaSshUrl,
} from '@/lib/naming';
import { getRepo } from '@/lib/gitea';
export async function GET(
request: Request,
@@ -36,6 +64,7 @@ export async function GET(
name: a.name,
status: a.status,
fqdn: a.fqdn ?? null,
domains: a.domains ?? null,
gitRepository: a.git_repository ?? null,
gitBranch: a.git_branch ?? null,
projectUuid: projectUuidOf(a),
@@ -48,3 +77,156 @@ export async function GET(
);
}
}
export async function POST(
request: Request,
{ params }: { params: Promise<{ slug: string }> }
) {
const { slug } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (
!ws.coolify_project_uuid ||
!ws.coolify_private_key_uuid ||
!ws.gitea_org
) {
return NextResponse.json(
{ error: 'Workspace not fully provisioned (need Coolify project + deploy key + Gitea org)' },
{ status: 503 }
);
}
type Body = {
repo?: string;
branch?: string;
name?: string;
ports?: string;
buildPack?: 'nixpacks' | 'static' | 'dockerfile' | 'dockercompose';
domain?: string;
envs?: Record<string, string>;
instantDeploy?: boolean;
description?: string;
baseDirectory?: string;
installCommand?: string;
buildCommand?: string;
startCommand?: string;
dockerfileLocation?: string;
};
let body: Body = {};
try {
body = (await request.json()) as Body;
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
if (!body.repo || typeof body.repo !== 'string') {
return NextResponse.json({ error: 'Missing "repo" field' }, { status: 400 });
}
// Accept either "repo-name" (assumed in workspace org) or "org/repo".
const parts = body.repo.replace(/\.git$/, '').split('/');
const repoOrg = parts.length === 2 ? parts[0] : ws.gitea_org;
const repoName = parts.length === 2 ? parts[1] : parts[0];
if (repoOrg !== ws.gitea_org) {
return NextResponse.json(
{ error: `Repo owner ${repoOrg} is not this workspace's org ${ws.gitea_org}` },
{ status: 403 }
);
}
if (!/^[a-zA-Z0-9._-]+$/.test(repoName)) {
return NextResponse.json({ error: 'Invalid repo name' }, { status: 400 });
}
// Verify the repo actually exists in Gitea (fail fast).
const repo = await getRepo(repoOrg, repoName);
if (!repo) {
return NextResponse.json(
{ error: `Repo ${repoOrg}/${repoName} not found in Gitea` },
{ status: 404 }
);
}
const appName = slugify(body.name ?? repoName);
const fqdn = body.domain
? body.domain.replace(/^https?:\/\//, '')
: workspaceAppFqdn(ws.slug, appName);
if (!isDomainUnderWorkspace(fqdn, ws.slug)) {
return NextResponse.json(
{ error: `Domain ${fqdn} must end with .${ws.slug}.vibnai.com` },
{ status: 403 }
);
}
try {
const created = await createPrivateDeployKeyApp({
projectUuid: ws.coolify_project_uuid,
serverUuid: ws.coolify_server_uuid ?? undefined,
environmentName: ws.coolify_environment_name,
destinationUuid: ws.coolify_destination_uuid ?? undefined,
privateKeyUuid: ws.coolify_private_key_uuid,
gitRepository: giteaSshUrl(repoOrg, repoName),
gitBranch: body.branch ?? repo.default_branch ?? 'main',
portsExposes: body.ports ?? '3000',
buildPack: body.buildPack ?? 'nixpacks',
name: appName,
description: body.description ?? `AI-created from ${repoOrg}/${repoName}`,
domains: toDomainsString([fqdn]),
isAutoDeployEnabled: true,
isForceHttpsEnabled: true,
// We defer the first deploy until envs are attached so they
// show up in the initial build.
instantDeploy: false,
baseDirectory: body.baseDirectory,
installCommand: body.installCommand,
buildCommand: body.buildCommand,
startCommand: body.startCommand,
dockerfileLocation: body.dockerfileLocation,
});
// Attach env vars (best-effort — don't fail the whole create on one bad key).
if (body.envs && typeof body.envs === 'object') {
for (const [key, value] of Object.entries(body.envs)) {
if (!/^[A-Z_][A-Z0-9_]*$/i.test(key)) continue;
try {
await upsertApplicationEnv(created.uuid, { key, value });
} catch (e) {
console.warn('[apps.POST] upsert env failed', key, e);
}
}
}
// Now kick off the first deploy (unless the caller opted out).
let deploymentUuid: string | null = null;
if (body.instantDeploy !== false) {
try {
const dep = await deployApplication(created.uuid);
deploymentUuid = dep.deployment_uuid ?? null;
} catch (e) {
console.warn('[apps.POST] initial deploy failed', e);
}
}
// Return a hydrated object (status / urls) for the UI.
const app = await getApplication(created.uuid);
return NextResponse.json(
{
uuid: app.uuid,
name: app.name,
status: app.status,
domain: fqdn,
url: `https://${fqdn}`,
gitRepository: app.git_repository ?? null,
gitBranch: app.git_branch ?? null,
deploymentUuid,
},
{ status: 201 }
);
} catch (err) {
return NextResponse.json(
{ error: 'Coolify create failed', details: err instanceof Error ? err.message : String(err) },
{ status: 502 }
);
}
}

View File

@@ -0,0 +1,92 @@
/**
* GET /api/workspaces/[slug]/auth/[uuid] — provider details
* DELETE /api/workspaces/[slug]/auth/[uuid]?confirm=<name>
* Volumes KEPT by default (don't blow away user accounts).
*/
import { NextResponse } from 'next/server';
import { requireWorkspacePrincipal } from '@/lib/auth/workspace-auth';
import {
getServiceInProject,
deleteService,
projectUuidOf,
TenantError,
} from '@/lib/coolify';
export async function GET(
request: Request,
{ params }: { params: Promise<{ slug: string; uuid: string }> }
) {
const { slug, uuid } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (!ws.coolify_project_uuid) {
return NextResponse.json({ error: 'Workspace has no Coolify project yet' }, { status: 503 });
}
try {
const svc = await getServiceInProject(uuid, ws.coolify_project_uuid);
return NextResponse.json({
uuid: svc.uuid,
name: svc.name,
status: svc.status ?? null,
projectUuid: projectUuidOf(svc),
});
} catch (err) {
if (err instanceof TenantError) return NextResponse.json({ error: err.message }, { status: 403 });
return NextResponse.json({ error: 'Provider not found' }, { status: 404 });
}
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ slug: string; uuid: string }> }
) {
const { slug, uuid } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (!ws.coolify_project_uuid) {
return NextResponse.json({ error: 'Workspace has no Coolify project yet' }, { status: 503 });
}
let svc;
try {
svc = await getServiceInProject(uuid, ws.coolify_project_uuid);
} catch (err) {
if (err instanceof TenantError) return NextResponse.json({ error: err.message }, { status: 403 });
return NextResponse.json({ error: 'Provider not found' }, { status: 404 });
}
const url = new URL(request.url);
const confirm = url.searchParams.get('confirm');
if (confirm !== svc.name) {
return NextResponse.json(
{ error: 'Confirmation required', hint: `Pass ?confirm=${svc.name}` },
{ status: 409 }
);
}
const deleteVolumes = url.searchParams.get('delete_volumes') === 'true';
try {
await deleteService(uuid, {
deleteConfigurations: true,
deleteVolumes,
deleteConnectedNetworks: true,
dockerCleanup: true,
});
return NextResponse.json({
ok: true,
deleted: { uuid, name: svc.name, volumesKept: !deleteVolumes },
});
} catch (err) {
return NextResponse.json(
{ error: 'Coolify delete failed', details: err instanceof Error ? err.message : String(err) },
{ status: 502 }
);
}
}

View File

@@ -0,0 +1,174 @@
/**
* Workspace authentication providers.
*
* GET /api/workspaces/[slug]/auth — list auth-provider services
* POST /api/workspaces/[slug]/auth — provision one of the vetted providers
*
* AI-callers can only create providers from an allowlist — we deliberately
* skip the rest of Coolify's ~300 one-click templates so this endpoint
* stays focused on "auth for my app". The allowlist:
*
* pocketbase — lightweight (SQLite-backed) auth + data
* authentik — feature-rich self-hosted IDP
* keycloak — industry-standard OIDC/SAML
* keycloak-with-postgres
* pocket-id — passkey-first OIDC
* pocket-id-with-postgresql
* logto — dev-first IDP
* supertokens-with-postgresql — session/auth backend
*
* (Zitadel is not on Coolify's service catalog — callers that ask for
* it get a descriptive 400 so the AI knows to pick a supported one.)
*
* POST body:
* { provider: "pocketbase", name?: "auth" }
*/
import { NextResponse } from 'next/server';
import { requireWorkspacePrincipal } from '@/lib/auth/workspace-auth';
import {
listServicesInProject,
createService,
getService,
projectUuidOf,
} from '@/lib/coolify';
import { slugify } from '@/lib/naming';
/**
* Vetted auth-provider service ids. Keys are what callers pass as
* `provider`; values are the Coolify service-template slugs.
*/
const AUTH_PROVIDERS: Record<string, string> = {
pocketbase: 'pocketbase',
authentik: 'authentik',
keycloak: 'keycloak',
'keycloak-with-postgres': 'keycloak-with-postgres',
'pocket-id': 'pocket-id',
'pocket-id-with-postgresql': 'pocket-id-with-postgresql',
logto: 'logto',
'supertokens-with-postgresql': 'supertokens-with-postgresql',
};
/** Anything in this set is Coolify-supported but not an auth provider (used for filtering the list view). */
const AUTH_PROVIDER_SLUGS = new Set(Object.values(AUTH_PROVIDERS));
export async function GET(
request: Request,
{ params }: { params: Promise<{ slug: string }> }
) {
const { slug } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (!ws.coolify_project_uuid) {
return NextResponse.json(
{ error: 'Workspace has no Coolify project yet', providers: [] },
{ status: 503 }
);
}
try {
const all = await listServicesInProject(ws.coolify_project_uuid);
// Coolify returns all services — we narrow to ones whose name
// contains an auth-provider slug. We also return the full list so
// callers can see non-auth services without a separate endpoint.
return NextResponse.json({
workspace: { slug: ws.slug, coolifyProjectUuid: ws.coolify_project_uuid },
providers: all
.filter(s => AUTH_PROVIDER_SLUGS.has(deriveTypeFromName(s.name)))
.map(s => ({
uuid: s.uuid,
name: s.name,
status: s.status ?? null,
provider: deriveTypeFromName(s.name),
projectUuid: projectUuidOf(s),
})),
allowedProviders: Object.keys(AUTH_PROVIDERS),
});
} catch (err) {
return NextResponse.json(
{ error: 'Coolify request failed', details: err instanceof Error ? err.message : String(err) },
{ status: 502 }
);
}
}
export async function POST(
request: Request,
{ params }: { params: Promise<{ slug: string }> }
) {
const { slug } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (!ws.coolify_project_uuid) {
return NextResponse.json({ error: 'Workspace has no Coolify project yet' }, { status: 503 });
}
let body: { provider?: string; name?: string; description?: string; instantDeploy?: boolean } = {};
try {
body = await request.json();
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
const providerKey = (body.provider ?? '').toLowerCase().trim();
const coolifyType = AUTH_PROVIDERS[providerKey];
if (!coolifyType) {
return NextResponse.json(
{
error: `Unsupported provider "${providerKey}". Allowed: ${Object.keys(AUTH_PROVIDERS).join(', ')}`,
hint: 'Zitadel is not on Coolify v4 service catalog — use keycloak or authentik instead.',
},
{ status: 400 }
);
}
const name = slugify(body.name ?? providerKey);
try {
const created = await createService({
projectUuid: ws.coolify_project_uuid,
type: coolifyType,
name,
description: body.description ?? `AI-provisioned ${providerKey} for ${ws.slug}`,
serverUuid: ws.coolify_server_uuid ?? undefined,
environmentName: ws.coolify_environment_name,
destinationUuid: ws.coolify_destination_uuid ?? undefined,
instantDeploy: body.instantDeploy ?? true,
});
const svc = await getService(created.uuid);
return NextResponse.json(
{
uuid: svc.uuid,
name: svc.name,
provider: providerKey,
status: svc.status ?? null,
},
{ status: 201 }
);
} catch (err) {
return NextResponse.json(
{ error: 'Coolify create failed', details: err instanceof Error ? err.message : String(err) },
{ status: 502 }
);
}
}
/**
* Coolify names services "{type}-{random-suffix}" when auto-named. We
* recover the provider slug by stripping the trailing `-\w+` if any
* and matching against our allowlist. Falls back to empty string.
*/
function deriveTypeFromName(name: string): string {
const candidates = Object.values(AUTH_PROVIDERS).sort((a, b) => b.length - a.length);
for (const slug of candidates) {
if (name === slug || name.startsWith(`${slug}-`) || name.startsWith(`${slug}_`)) {
return slug;
}
}
return '';
}

View File

@@ -0,0 +1,158 @@
/**
* GET /api/workspaces/[slug]/databases/[uuid] — database details (incl. URLs)
* PATCH /api/workspaces/[slug]/databases/[uuid] — update fields
* DELETE /api/workspaces/[slug]/databases/[uuid]?confirm=<name>
* Volumes KEPT by default (data). Pass &delete_volumes=true to drop.
*/
import { NextResponse } from 'next/server';
import { requireWorkspacePrincipal } from '@/lib/auth/workspace-auth';
import {
getDatabaseInProject,
updateDatabase,
deleteDatabase,
projectUuidOf,
TenantError,
} from '@/lib/coolify';
export async function GET(
request: Request,
{ params }: { params: Promise<{ slug: string; uuid: string }> }
) {
const { slug, uuid } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (!ws.coolify_project_uuid) {
return NextResponse.json({ error: 'Workspace has no Coolify project yet' }, { status: 503 });
}
try {
const db = await getDatabaseInProject(uuid, ws.coolify_project_uuid);
return NextResponse.json({
uuid: db.uuid,
name: db.name,
type: db.type ?? null,
status: db.status,
isPublic: db.is_public ?? false,
publicPort: db.public_port ?? null,
internalUrl: db.internal_db_url ?? null,
externalUrl: db.external_db_url ?? null,
projectUuid: projectUuidOf(db),
});
} catch (err) {
if (err instanceof TenantError) return NextResponse.json({ error: err.message }, { status: 403 });
return NextResponse.json({ error: 'Database not found' }, { status: 404 });
}
}
export async function PATCH(
request: Request,
{ params }: { params: Promise<{ slug: string; uuid: string }> }
) {
const { slug, uuid } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (!ws.coolify_project_uuid) {
return NextResponse.json({ error: 'Workspace has no Coolify project yet' }, { status: 503 });
}
try {
await getDatabaseInProject(uuid, ws.coolify_project_uuid);
} catch (err) {
if (err instanceof TenantError) return NextResponse.json({ error: err.message }, { status: 403 });
return NextResponse.json({ error: 'Database not found' }, { status: 404 });
}
let body: Record<string, unknown> = {};
try {
body = await request.json();
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
const allowed = new Set([
'name',
'description',
'is_public',
'public_port',
'image',
'limits_memory',
'limits_cpus',
]);
const patch: Record<string, unknown> = {};
for (const [k, v] of Object.entries(body)) {
if (allowed.has(k) && v !== undefined) patch[k] = v;
}
if (Object.keys(patch).length === 0) {
return NextResponse.json({ error: 'No updatable fields in body' }, { status: 400 });
}
try {
await updateDatabase(uuid, patch);
return NextResponse.json({ ok: true, uuid });
} catch (err) {
return NextResponse.json(
{ error: 'Coolify update failed', details: err instanceof Error ? err.message : String(err) },
{ status: 502 }
);
}
}
export async function DELETE(
request: Request,
{ params }: { params: Promise<{ slug: string; uuid: string }> }
) {
const { slug, uuid } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (!ws.coolify_project_uuid) {
return NextResponse.json({ error: 'Workspace has no Coolify project yet' }, { status: 503 });
}
let db;
try {
db = await getDatabaseInProject(uuid, ws.coolify_project_uuid);
} catch (err) {
if (err instanceof TenantError) return NextResponse.json({ error: err.message }, { status: 403 });
return NextResponse.json({ error: 'Database not found' }, { status: 404 });
}
const url = new URL(request.url);
const confirm = url.searchParams.get('confirm');
if (confirm !== db.name) {
return NextResponse.json(
{ error: 'Confirmation required', hint: `Pass ?confirm=${db.name}` },
{ status: 409 }
);
}
// Default: preserve volumes (it's a database — user data lives there).
const deleteVolumes = url.searchParams.get('delete_volumes') === 'true';
const deleteConfigurations = url.searchParams.get('delete_configurations') !== 'false';
const deleteConnectedNetworks = url.searchParams.get('delete_connected_networks') !== 'false';
const dockerCleanup = url.searchParams.get('docker_cleanup') !== 'false';
try {
await deleteDatabase(uuid, {
deleteConfigurations,
deleteVolumes,
deleteConnectedNetworks,
dockerCleanup,
});
return NextResponse.json({
ok: true,
deleted: { uuid, name: db.name, volumesKept: !deleteVolumes },
});
} catch (err) {
return NextResponse.json(
{ error: 'Coolify delete failed', details: err instanceof Error ? err.message : String(err) },
{ status: 502 }
);
}
}

View File

@@ -0,0 +1,161 @@
/**
* GET /api/workspaces/[slug]/databases — list databases in this workspace
* POST /api/workspaces/[slug]/databases — provision a new database
*
* Supported `type` values (all that Coolify v4 can deploy):
* postgresql | mysql | mariadb | mongodb | redis | keydb | dragonfly | clickhouse
*
* POST body:
* {
* type: "postgresql",
* name?: "my-db",
* isPublic?: true, // expose a host port for remote clients
* publicPort?: 5433,
* image?: "postgres:16",
* credentials?: { ... } // type-specific (e.g. postgres_user)
* limits?: { memory?: "1G", cpus?: "1" },
* }
*
* Tenancy: every returned record is filtered to the workspace's own
* Coolify project UUID.
*/
import { NextResponse } from 'next/server';
import { requireWorkspacePrincipal } from '@/lib/auth/workspace-auth';
import {
listDatabasesInProject,
createDatabase,
getDatabase,
projectUuidOf,
type CoolifyDatabaseType,
} from '@/lib/coolify';
import { slugify } from '@/lib/naming';
const SUPPORTED_TYPES: readonly CoolifyDatabaseType[] = [
'postgresql',
'mysql',
'mariadb',
'mongodb',
'redis',
'keydb',
'dragonfly',
'clickhouse',
];
export async function GET(
request: Request,
{ params }: { params: Promise<{ slug: string }> }
) {
const { slug } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (!ws.coolify_project_uuid) {
return NextResponse.json(
{ error: 'Workspace has no Coolify project yet', databases: [] },
{ status: 503 }
);
}
try {
const dbs = await listDatabasesInProject(ws.coolify_project_uuid);
return NextResponse.json({
workspace: { slug: ws.slug, coolifyProjectUuid: ws.coolify_project_uuid },
databases: dbs.map(d => ({
uuid: d.uuid,
name: d.name,
type: d.type ?? null,
status: d.status,
isPublic: d.is_public ?? false,
publicPort: d.public_port ?? null,
projectUuid: projectUuidOf(d),
})),
});
} catch (err) {
return NextResponse.json(
{ error: 'Coolify request failed', details: err instanceof Error ? err.message : String(err) },
{ status: 502 }
);
}
}
export async function POST(
request: Request,
{ params }: { params: Promise<{ slug: string }> }
) {
const { slug } = await params;
const principal = await requireWorkspacePrincipal(request, { targetSlug: slug });
if (principal instanceof NextResponse) return principal;
const ws = principal.workspace;
if (!ws.coolify_project_uuid) {
return NextResponse.json({ error: 'Workspace has no Coolify project yet' }, { status: 503 });
}
type Body = {
type?: string;
name?: string;
description?: string;
isPublic?: boolean;
publicPort?: number;
image?: string;
credentials?: Record<string, unknown>;
limits?: { memory?: string; cpus?: string };
instantDeploy?: boolean;
};
let body: Body = {};
try {
body = (await request.json()) as Body;
} catch {
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 });
}
const type = body.type as CoolifyDatabaseType | undefined;
if (!type || !SUPPORTED_TYPES.includes(type)) {
return NextResponse.json(
{ error: `\`type\` must be one of: ${SUPPORTED_TYPES.join(', ')}` },
{ status: 400 }
);
}
const name = slugify(body.name ?? `${type}-${Date.now().toString(36)}`);
try {
const created = await createDatabase({
type,
name,
description: body.description,
projectUuid: ws.coolify_project_uuid,
serverUuid: ws.coolify_server_uuid ?? undefined,
environmentName: ws.coolify_environment_name,
destinationUuid: ws.coolify_destination_uuid ?? undefined,
isPublic: body.isPublic,
publicPort: body.publicPort,
image: body.image,
credentials: body.credentials,
limits: body.limits,
instantDeploy: body.instantDeploy ?? true,
});
const db = await getDatabase(created.uuid);
return NextResponse.json(
{
uuid: db.uuid,
name: db.name,
type: db.type ?? type,
status: db.status,
isPublic: db.is_public ?? false,
publicPort: db.public_port ?? null,
internalUrl: db.internal_db_url ?? null,
externalUrl: db.external_db_url ?? null,
},
{ status: 201 }
);
} catch (err) {
return NextResponse.json(
{ error: 'Coolify create failed', details: err instanceof Error ? err.message : String(err) },
{ status: 502 }
);
}
}