fix(apps.create): clone via HTTPS+bot-PAT; activate bot users on creation

Coolify was failing all Gitea clones with "Permission denied (publickey)"
because the helper container's SSH hits git.vibnai.com:22 (Ubuntu host
sshd, which doesn't know Gitea keys), while Gitea's builtin SSH is on
host port 22222 (not publicly reachable).

Rather than fight the SSH topology, switch every Vibn-provisioned app
to clone over HTTPS with the workspace bot's PAT embedded in the URL.
The PAT is already stored encrypted per workspace and scoped to that
org, so this gives equivalent isolation with zero SSH dependency.

Changes:
- lib/naming.ts: add giteaHttpsUrl() + redactGiteaHttpsUrl(); mark
  giteaSshUrl() as deprecated-for-deploys with a comment.
- lib/coolify.ts: extend CreatePublicAppOpts with install/build/start
  commands, base_directory, dockerfile_location, docker_compose_location,
  manual_webhook_secret_gitea so it's at parity with the SSH variant.
- app/api/mcp/route.ts:
  - apps.create now uses createPublicApp(giteaHttpsUrl(...)) and pulls
    the bot PAT via getWorkspaceBotCredentials(). No more private-
    deploy-key path for new apps.
  - apps.update adds git_commit_sha + docker_compose_location to the
    whitelist.
  - New apps.rewire_git tool: re-points an app's git_repository at the
    canonical HTTPS+PAT URL. Unblocks older apps stuck on SSH URLs
    and provides a path for PAT rotation without rebuilding the app.
- lib/gitea.ts: createUser() now issues an immediate PATCH to set
  active: true. Gitea's admin-create endpoint creates users as inactive
  by default, and inactive users fail permission checks even though
  they're org members. GiteaUser gains optional `active` field.
- scripts/activate-workspace-bots.ts: idempotent backfill that flips
  active=true for any existing workspace bot that was created before
  this fix. Safe to re-run.
- AI_CAPABILITIES.md: document apps.rewire_git; clarify apps.create
  uses HTTPS+PAT (no SSH).

Already unblocked in prod for the mark workspace:
- vibn-bot-mark activated.
- twenty-crm's git_repository PATCHed to HTTPS+PAT form; git clone
  now succeeds (remaining unrelated error: docker-compose file path).

Made-with: Cursor
This commit is contained in:
2026-04-23 12:21:00 -07:00
parent 3192e0f7b9
commit fcd5d03894
5 changed files with 244 additions and 12 deletions

View File

@@ -31,7 +31,7 @@ import {
upsertApplicationEnv,
deleteApplicationEnv,
// Phase 4 ── create/update/delete + domains + databases + services
createPrivateDeployKeyApp,
createPublicApp,
updateApplication,
deleteApplication,
setApplicationDomains,
@@ -49,7 +49,7 @@ import {
import { query } from '@/lib/db-postgres';
import { getRepo } from '@/lib/gitea';
import {
giteaSshUrl,
giteaHttpsUrl,
isDomainUnderWorkspace,
slugify,
toDomainsString,
@@ -85,6 +85,7 @@ export async function GET() {
'apps.get',
'apps.create',
'apps.update',
'apps.rewire_git',
'apps.delete',
'apps.deploy',
'apps.deployments',
@@ -171,6 +172,8 @@ export async function POST(request: Request) {
return await toolAppsCreate(principal, params);
case 'apps.update':
return await toolAppsUpdate(principal, params);
case 'apps.rewire_git':
return await toolAppsRewireGit(principal, params);
case 'apps.delete':
return await toolAppsDelete(principal, params);
case 'apps.domains.list':
@@ -449,9 +452,21 @@ async function toolAppsEnvsDelete(principal: Principal, params: Record<string, a
async function toolAppsCreate(principal: Principal, params: Record<string, any>) {
const ws = principal.workspace;
if (!ws.coolify_project_uuid || !ws.coolify_private_key_uuid || !ws.gitea_org) {
if (!ws.coolify_project_uuid || !ws.gitea_org) {
return NextResponse.json(
{ error: 'Workspace not fully provisioned (need Coolify project + deploy key + Gitea org)' },
{ error: 'Workspace not fully provisioned (need Coolify project + Gitea org)' },
{ status: 503 }
);
}
// We clone via HTTPS with the workspace's bot PAT (NOT SSH) — Gitea's
// builtin SSH is on an internal-only port and port 22 hits the host's
// OpenSSH, so SSH clones fail. HTTPS+PAT works in all topologies and
// the PAT is scoped to the org via team membership.
const botCreds = getWorkspaceBotCredentials(ws);
if (!botCreds) {
return NextResponse.json(
{ error: 'Workspace Gitea bot credentials unavailable — re-run provisioning' },
{ status: 503 }
);
}
@@ -484,13 +499,12 @@ async function toolAppsCreate(principal: Principal, params: Record<string, any>)
);
}
const created = await createPrivateDeployKeyApp({
const created = await createPublicApp({
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),
gitRepository: giteaHttpsUrl(repoOrg, repoName, botCreds.username, botCreds.token),
gitBranch: String(params.branch ?? repo.default_branch ?? 'main'),
portsExposes: String(params.ports ?? '3000'),
buildPack: (params.buildPack as any) ?? 'nixpacks',
@@ -499,6 +513,13 @@ async function toolAppsCreate(principal: Principal, params: Record<string, any>)
isAutoDeployEnabled: true,
isForceHttpsEnabled: true,
instantDeploy: false,
dockerComposeLocation: params.dockerComposeLocation
? String(params.dockerComposeLocation)
: undefined,
dockerfileLocation: params.dockerfileLocation
? String(params.dockerfileLocation)
: undefined,
baseDirectory: params.baseDirectory ? String(params.baseDirectory) : undefined,
});
// Attach envs
@@ -543,9 +564,9 @@ async function toolAppsUpdate(principal: Principal, params: Record<string, any>)
await getApplicationInProject(appUuid, projectUuid);
const allowed = new Set([
'name', 'description', 'git_branch', 'build_pack', 'ports_exposes',
'name', 'description', 'git_branch', 'git_commit_sha', 'build_pack', 'ports_exposes',
'install_command', 'build_command', 'start_command',
'base_directory', 'dockerfile_location',
'base_directory', 'dockerfile_location', 'docker_compose_location',
'is_auto_deploy_enabled', 'is_force_https_enabled', 'static_image',
]);
const patch: Record<string, unknown> = {};
@@ -559,6 +580,70 @@ async function toolAppsUpdate(principal: Principal, params: Record<string, any>)
return NextResponse.json({ result: { ok: true, uuid: appUuid } });
}
/**
* Re-point an app's git_repository at the workspace's canonical
* HTTPS+PAT clone URL. Useful to recover older apps that were created
* with SSH URLs (which don't work on this Gitea topology), or to
* rotate the bot PAT embedded in the URL after a credential cycle.
* The repo name is inferred from the current URL unless `repo` is
* passed explicitly (in `owner/name` form).
*/
async function toolAppsRewireGit(principal: Principal, params: Record<string, any>) {
const projectUuid = requireCoolifyProject(principal);
if (projectUuid instanceof NextResponse) return projectUuid;
const appUuid = String(params.uuid ?? params.appUuid ?? '').trim();
if (!appUuid) return NextResponse.json({ error: 'Param "uuid" is required' }, { status: 400 });
const ws = principal.workspace;
const botCreds = getWorkspaceBotCredentials(ws);
if (!botCreds) {
return NextResponse.json(
{ error: 'Workspace Gitea bot credentials unavailable — re-run provisioning' },
{ status: 503 }
);
}
const app = await getApplicationInProject(appUuid, projectUuid);
let repoOrg: string;
let repoName: string;
if (params.repo) {
const parts = String(params.repo).replace(/\.git$/, '').split('/');
if (parts.length !== 2) {
return NextResponse.json({ error: 'Param "repo" must be "owner/name"' }, { status: 400 });
}
[repoOrg, repoName] = parts;
} else {
const m = (app.git_repository ?? '').match(
/(?:git@[^:]+:|https?:\/\/(?:[^/]+@)?[^/]+\/)([^/]+)\/([^/.]+)(?:\.git)?$/
);
if (!m) {
return NextResponse.json(
{ error: 'Could not infer repo from current git_repository; pass repo="owner/name"' },
{ status: 400 }
);
}
[, repoOrg, repoName] = m;
}
if (repoOrg !== ws.gitea_org) {
return NextResponse.json(
{ error: `Repo owner ${repoOrg} is not this workspace's org ${ws.gitea_org}` },
{ status: 403 }
);
}
const newUrl = giteaHttpsUrl(repoOrg, repoName, botCreds.username, botCreds.token);
await updateApplication(appUuid, { git_repository: newUrl });
return NextResponse.json({
result: {
ok: true,
uuid: appUuid,
repo: `${repoOrg}/${repoName}`,
gitUrlScheme: 'https+pat',
},
});
}
async function toolAppsDelete(principal: Principal, params: Record<string, any>) {
const projectUuid = requireCoolifyProject(principal);
if (projectUuid instanceof NextResponse) return projectUuid;