feat(ai-access): per-workspace Gitea bot + tenant-safe Coolify proxy + MCP
Ship Phases 1–3 of the multi-tenant AI access plan so an AI agent can
act on a Vibn workspace with one bearer token and zero admin reach.
Phase 1 — Gitea bot per workspace
- Add gitea_bot_username / gitea_bot_user_id / gitea_bot_token_encrypted
columns to vibn_workspaces (migrate route).
- New lib/auth/secret-box.ts (AES-256-GCM, VIBN_SECRETS_KEY) for PAT at rest.
- Extend lib/gitea.ts with createUser, createAccessTokenFor (Sudo PAT),
createOrgTeam, addOrgTeamMember, ensureOrgTeamMembership.
- ensureWorkspaceProvisioned now mints a vibn-bot-<slug> user, adds it to
a Writers team (write perms only) on the workspace's org, and stores
its PAT encrypted.
- GET /api/workspaces/[slug]/gitea-credentials returns a workspace-scoped
bot PAT + clone URL template; session or vibn_sk_ bearer auth.
Phase 2 — Tenant-safe Coolify proxy + real MCP
- lib/coolify.ts: projectUuidOf, listApplicationsInProject,
getApplicationInProject, TenantError, env CRUD, deployments list.
- Workspace-scoped REST endpoints (all filtered by coolify_project_uuid):
GET/POST /api/workspaces/[slug]/apps/[uuid](/deploy|/envs|/deployments),
GET /api/workspaces/[slug]/deployments/[deploymentUuid]/logs.
- Full rewrite of /api/mcp off legacy Firebase onto Postgres vibn_sk_
keys, exposing workspace.describe, gitea.credentials, projects.*,
apps.* (list/get/deploy/deployments, envs.list/upsert/delete).
Phase 3 — Settings UI AI bundle
- GET /api/workspaces/[slug]/bootstrap.sh: curl|sh installer that writes
.cursor/rules, .cursor/mcp.json and appends VIBN_* to .env.local.
Embeds the caller's vibn_sk_ token when invoked with bearer auth.
- WorkspaceKeysPanel: single AiAccessBundleCard with system-prompt block,
one-line bootstrap, Reveal-bot-PAT button, collapsible manual-setup
fallback. Minted-key modal also shows the bootstrap one-liner.
Ops prerequisites:
- Set VIBN_SECRETS_KEY (>=16 chars) on the frontend.
- Run /api/admin/migrate to add the three bot columns.
- GITEA_API_TOKEN must be a site-admin token (needed for admin/users
+ Sudo PAT mint); otherwise provision_status lands on 'partial'.
Made-with: Cursor
This commit is contained in:
@@ -17,9 +17,19 @@
|
||||
* Coolify exposes team creation.
|
||||
*/
|
||||
|
||||
import { randomBytes } from 'crypto';
|
||||
import { query, queryOne } from '@/lib/db-postgres';
|
||||
import { createProject as createCoolifyProject } from '@/lib/coolify';
|
||||
import { createOrg, getOrg, getUser, addOrgOwner } from '@/lib/gitea';
|
||||
import {
|
||||
createOrg,
|
||||
getOrg,
|
||||
getUser,
|
||||
addOrgOwner,
|
||||
createUser,
|
||||
createAccessTokenFor,
|
||||
ensureOrgTeamMembership,
|
||||
} from '@/lib/gitea';
|
||||
import { encryptSecret, decryptSecret } from '@/lib/auth/secret-box';
|
||||
|
||||
export interface VibnWorkspace {
|
||||
id: string;
|
||||
@@ -29,6 +39,9 @@ export interface VibnWorkspace {
|
||||
coolify_project_uuid: string | null;
|
||||
coolify_team_id: number | null;
|
||||
gitea_org: string | null;
|
||||
gitea_bot_username: string | null;
|
||||
gitea_bot_user_id: number | null;
|
||||
gitea_bot_token_encrypted: string | null;
|
||||
provision_status: 'pending' | 'partial' | 'ready' | 'error';
|
||||
provision_error: string | null;
|
||||
created_at: Date;
|
||||
@@ -64,6 +77,16 @@ export function giteaOrgNameFor(slug: string): string {
|
||||
return `vibn-${slug}`;
|
||||
}
|
||||
|
||||
/** Gitea username we mint for each workspace's bot account. */
|
||||
export function giteaBotUsernameFor(slug: string): string {
|
||||
return `vibn-bot-${slug}`;
|
||||
}
|
||||
|
||||
/** Placeholder-looking email so Gitea accepts the user; never delivered to. */
|
||||
export function giteaBotEmailFor(slug: string): string {
|
||||
return `bot+${slug}@vibnai.invalid`;
|
||||
}
|
||||
|
||||
// ──────────────────────────────────────────────────
|
||||
// CRUD
|
||||
// ──────────────────────────────────────────────────
|
||||
@@ -219,24 +242,114 @@ export async function ensureWorkspaceProvisioned(workspace: VibnWorkspace): Prom
|
||||
}
|
||||
}
|
||||
|
||||
// ── Per-workspace Gitea bot user + PAT ─────────────────────────────
|
||||
// Gives AI agents a credential that is scoped exclusively to this
|
||||
// workspace's org. The bot has no other org memberships, so even a
|
||||
// leaked PAT cannot reach other tenants' repos.
|
||||
let botUsername = workspace.gitea_bot_username;
|
||||
let botUserId = workspace.gitea_bot_user_id;
|
||||
let botTokenEncrypted = workspace.gitea_bot_token_encrypted;
|
||||
|
||||
if (giteaOrg && (!botUsername || !botTokenEncrypted)) {
|
||||
try {
|
||||
const wantBot = giteaBotUsernameFor(workspace.slug);
|
||||
|
||||
// 1. Ensure the bot user exists.
|
||||
let existingBot = await getUser(wantBot);
|
||||
if (!existingBot) {
|
||||
const created = await createUser({
|
||||
username: wantBot,
|
||||
email: giteaBotEmailFor(workspace.slug),
|
||||
// Password is never used (only the PAT is), but Gitea requires one.
|
||||
password: `bot-${randomBytes(24).toString('base64url')}`,
|
||||
fullName: `Vibn bot (${workspace.slug})`,
|
||||
});
|
||||
existingBot = { id: created.id, login: created.login };
|
||||
}
|
||||
botUsername = existingBot.login;
|
||||
botUserId = existingBot.id;
|
||||
|
||||
// 2. Add the bot to the org's Writers team (scoped permissions).
|
||||
await ensureOrgTeamMembership({
|
||||
org: giteaOrg,
|
||||
teamName: 'Writers',
|
||||
permission: 'write',
|
||||
username: botUsername,
|
||||
});
|
||||
|
||||
// 3. Mint a PAT for the bot. Gitea shows the plaintext exactly
|
||||
// once, so if we already stored an encrypted copy we skip.
|
||||
if (!botTokenEncrypted) {
|
||||
const pat = await createAccessTokenFor({
|
||||
username: botUsername,
|
||||
name: `vibn-${workspace.slug}-${Date.now().toString(36)}`,
|
||||
scopes: ['write:repository', 'write:issue', 'write:user'],
|
||||
});
|
||||
botTokenEncrypted = encryptSecret(pat.sha1);
|
||||
}
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
errors.push(`gitea-bot: ${msg}`);
|
||||
console.error('[workspaces] Gitea bot provisioning failed', workspace.slug, msg);
|
||||
}
|
||||
}
|
||||
|
||||
const allReady = !!(coolifyUuid && giteaOrg && botUsername && botTokenEncrypted);
|
||||
const status: VibnWorkspace['provision_status'] =
|
||||
coolifyUuid && giteaOrg ? 'ready' : errors.length > 0 ? 'partial' : 'pending';
|
||||
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),
|
||||
provision_status = $4,
|
||||
provision_error = $5,
|
||||
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),
|
||||
provision_status = $7,
|
||||
provision_error = $8,
|
||||
updated_at = now()
|
||||
WHERE id = $1
|
||||
RETURNING *`,
|
||||
[workspace.id, coolifyUuid, giteaOrg, status, errors.length ? errors.join('; ') : null]
|
||||
[
|
||||
workspace.id,
|
||||
coolifyUuid,
|
||||
giteaOrg,
|
||||
botUsername,
|
||||
botUserId,
|
||||
botTokenEncrypted,
|
||||
status,
|
||||
errors.length ? errors.join('; ') : null,
|
||||
]
|
||||
);
|
||||
|
||||
return updated[0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt and return the bot credentials for a workspace. Call this
|
||||
* from endpoints that need to hand the AI a usable git clone URL.
|
||||
* Returns null when the workspace has not been fully provisioned.
|
||||
*/
|
||||
export function getWorkspaceBotCredentials(workspace: VibnWorkspace): {
|
||||
username: string;
|
||||
token: string;
|
||||
org: string;
|
||||
} | null {
|
||||
if (!workspace.gitea_bot_username || !workspace.gitea_bot_token_encrypted || !workspace.gitea_org) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return {
|
||||
username: workspace.gitea_bot_username,
|
||||
token: decryptSecret(workspace.gitea_bot_token_encrypted),
|
||||
org: workspace.gitea_org,
|
||||
};
|
||||
} catch (err) {
|
||||
console.error('[workspaces] Failed to decrypt bot token for', workspace.slug, err);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience: get-or-create + provision in one call. Used by the
|
||||
* project-create flow so the first project in a fresh account always
|
||||
|
||||
Reference in New Issue
Block a user