feat(workspaces): per-account tenancy + AI access keys + Cursor integration

Adds logical multi-tenancy on top of Coolify + Gitea so every Vibn
account gets its own isolated tenant boundary, and exposes that
boundary to AI agents (Cursor, Claude Code, scripts) through
per-workspace bearer tokens.

Schema (additive, idempotent — run /api/admin/migrate once after deploy)
  - vibn_workspaces: slug, name, owner, coolify_project_uuid,
    coolify_team_id (reserved for when Coolify ships POST /teams),
    gitea_org, provision_status
  - vibn_workspace_members: room for multi-user workspaces later
  - vibn_workspace_api_keys: sha256-hashed bearer tokens
  - fs_projects.vibn_workspace_id: nullable FK linking projects
    to their workspace

Provisioning
  - On first sign-in, ensureWorkspaceForUser() inserts the row
    (no network calls — keeps signin fast).
  - On first project create, ensureWorkspaceProvisioned() lazily
    creates a Coolify Project (vibn-ws-{slug}) and a Gitea org
    (vibn-{slug}). Failures are recorded on the row, not thrown,
    and POST /api/workspaces/{slug}/provision retries.

Auth surface
  - lib/auth/workspace-auth.ts: requireWorkspacePrincipal() accepts
    either a NextAuth session or "Authorization: Bearer vibn_sk_...".
    The bearer key is hard-pinned to one workspace — it cannot
    reach any other tenant.
  - mintWorkspaceApiKey / listWorkspaceApiKeys / revokeWorkspaceApiKey

Routes
  - GET    /api/workspaces                         list
  - GET    /api/workspaces/[slug]                  details
  - POST   /api/workspaces/[slug]/provision        retry provisioning
  - GET    /api/workspaces/[slug]/keys             list keys
  - POST   /api/workspaces/[slug]/keys             mint key (token shown once)
  - DELETE /api/workspaces/[slug]/keys/[keyId]     revoke

UI
  - components/workspace/WorkspaceKeysPanel.tsx: identity card,
    keys CRUD with one-time secret reveal, and a "Connect Cursor"
    block with copy/download for:
      .cursor/rules/vibn-workspace.mdc — rule telling the agent
        about the API + workspace IDs + house rules
      ~/.cursor/mcp.json — MCP server registration with key
        embedded (server URL is /api/mcp; HTTP MCP route lands next)
      .env.local — VIBN_API_KEY + smoke-test curl
  - Slotted into existing /[workspace]/settings between Workspace
    and Notifications cards (no other layout changes).

projects/create
  - Resolves the user's workspace (creating + provisioning lazily).
  - Repos go under workspace.gitea_org (falls back to GITEA_ADMIN_USER
    for backwards compat).
  - Coolify services are created inside workspace.coolify_project_uuid
    (renamed {slug}-{appName} to stay unique within the namespace) —
    no more per-Vibn-project Coolify Project sprawl.
  - Stamps vibn_workspace_id on fs_projects.

lib/gitea
  - createOrg, getOrg, addOrgOwner, getUser
  - createRepo now routes /orgs/{owner}/repos when owner != admin

Also includes prior-turn auth hardening that was already in
authOptions.ts (CredentialsProvider for dev-local, isLocalNextAuth
cookie config) bundled in to keep the auth layer in one consistent
state.

.env.example
  - Documents GITEA_API_URL / GITEA_API_TOKEN / GITEA_ADMIN_USER /
    GITEA_WEBHOOK_SECRET and COOLIFY_URL / COOLIFY_API_TOKEN /
    COOLIFY_SERVER_UUID, with the canonical hostnames
    (git.vibnai.com, coolify.vibnai.com).

Post-deploy
  - Run once: curl -X POST https://vibnai.com/api/admin/migrate \\
      -H "x-admin-secret: \$ADMIN_MIGRATE_SECRET"
  - Existing users get a workspace row on next sign-in.
  - Existing fs_projects keep working (legacy gitea owner + their
    own per-project Coolify Projects); new projects use the
    workspace-scoped path.

Not in this commit (follow-ups)
  - Wiring requireWorkspacePrincipal into the rest of /api/projects/*
    so API keys can drive existing routes
  - HTTP MCP server at /api/mcp (the mcp.json snippet already
    points at the right URL — no client re-setup when it lands)
  - Backfill script to assign legacy fs_projects to a workspace

Made-with: Cursor
This commit is contained in:
2026-04-20 17:17:12 -07:00
parent ccc6cc1da5
commit acb63a2a5a
14 changed files with 1824 additions and 56 deletions

View File

@@ -1,14 +1,85 @@
import { NextAuthOptions } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import GoogleProvider from "next-auth/providers/google";
import { PrismaAdapter } from "@next-auth/prisma-adapter";
import { PrismaClient } from "@prisma/client";
import { query } from "@/lib/db-postgres";
import { ensureWorkspaceForUser } from "@/lib/workspaces";
const prisma = new PrismaClient();
const nextAuthUrl = (process.env.NEXTAUTH_URL ?? "").trim();
const isLocalNextAuth =
nextAuthUrl.startsWith("http://localhost") ||
nextAuthUrl.startsWith("http://127.0.0.1") ||
(process.env.NODE_ENV === "development" && !nextAuthUrl);
/** Set in .env.local (server + client): one email for local dev bypass. */
const devLocalEmail = (process.env.NEXT_PUBLIC_DEV_LOCAL_AUTH_EMAIL ?? "").trim();
const devLocalSecret = (process.env.DEV_LOCAL_AUTH_SECRET ?? "").trim();
const devLocalAuthEnabled =
process.env.NODE_ENV === "development" && devLocalEmail.length > 0;
function isLocalhostHost(host: string): boolean {
const h = host.split(":")[0]?.toLowerCase() ?? "";
return (
h === "localhost" ||
h === "127.0.0.1" ||
h === "[::1]" ||
h === "::1"
);
}
export const authOptions: NextAuthOptions = {
debug: process.env.NODE_ENV === "development",
adapter: PrismaAdapter(prisma),
providers: [
...(devLocalAuthEnabled
? [
CredentialsProvider({
id: "dev-local",
name: "Local dev",
credentials: {
password: { label: "Dev secret", type: "password" },
},
async authorize(credentials, req) {
const headers = (req as { headers?: Headers } | undefined)?.headers;
const host =
headers && typeof headers.get === "function"
? (headers.get("host") ?? "")
: "";
if (devLocalSecret) {
if ((credentials?.password ?? "") !== devLocalSecret) {
return null;
}
} else if (!isLocalhostHost(host)) {
return null;
}
const name =
(process.env.DEV_LOCAL_AUTH_NAME ?? "").trim() || "Local dev";
const user = await prisma.user.upsert({
where: { email: devLocalEmail },
create: {
email: devLocalEmail,
name,
emailVerified: new Date(),
},
update: { name },
});
return {
id: user.id,
email: user.email,
name: user.name,
image: user.image,
};
},
}),
]
: []),
GoogleProvider({
clientId: process.env.GOOGLE_CLIENT_ID || "",
clientSecret: process.env.GOOGLE_CLIENT_SECRET || "",
@@ -20,8 +91,8 @@ export const authOptions: NextAuthOptions = {
},
callbacks: {
async session({ session, user }) {
if (session.user) {
session.user.id = user.id;
if (session.user && "id" in user && user.id) {
(session.user as { id: string }).id = user.id;
}
return session;
},
@@ -42,16 +113,34 @@ export const authOptions: NextAuthOptions = {
`SELECT id FROM fs_users WHERE data->>'email' = $1 LIMIT 1`,
[user.email]
);
let fsUserId: string;
if (existing.length === 0) {
await query(
`INSERT INTO fs_users (id, user_id, data) VALUES (gen_random_uuid()::text, $1, $2::jsonb)`,
const inserted = await query<{ id: string }>(
`INSERT INTO fs_users (id, user_id, data)
VALUES (gen_random_uuid()::text, $1, $2::jsonb)
RETURNING id`,
[user.id, data]
);
fsUserId = inserted[0].id;
} else {
await query(
`UPDATE fs_users SET user_id = $1, data = data || $2::jsonb, updated_at = NOW() WHERE id = $3`,
[user.id, data, existing[0].id]
);
fsUserId = existing[0].id;
}
// Ensure a Vibn workspace exists for this user. We DO NOT
// provision Coolify/Gitea here — that happens lazily on first
// project create so signin stays fast and resilient to outages.
try {
await ensureWorkspaceForUser({
userId: fsUserId,
email: user.email,
displayName: user.name ?? null,
});
} catch (wsErr) {
console.error("[signIn] Failed to ensure workspace:", wsErr);
}
} catch (e) {
console.error("[signIn] Failed to upsert fs_user:", e);
@@ -66,13 +155,14 @@ export const authOptions: NextAuthOptions = {
secret: process.env.NEXTAUTH_SECRET,
cookies: {
sessionToken: {
name: `__Secure-next-auth.session-token`,
// __Secure- prefix requires Secure; localhost HTTP needs plain name + secure: false
name: isLocalNextAuth ? "next-auth.session-token" : "__Secure-next-auth.session-token",
options: {
httpOnly: true,
sameSite: "lax",
path: "/",
secure: true,
domain: ".vibnai.com", // share across all subdomains (theia.vibnai.com, etc.)
secure: !isLocalNextAuth,
...(isLocalNextAuth ? {} : { domain: ".vibnai.com" }),
},
},
},

247
lib/auth/workspace-auth.ts Normal file
View File

@@ -0,0 +1,247 @@
/**
* Workspace-scoped auth.
*
* Two principal types are accepted on `/api/...` routes:
* 1. NextAuth session (browser users) — `authSession()`
* 2. Per-workspace bearer API key (`Authorization: Bearer vibn_sk_...`)
*
* Either way we resolve a `WorkspacePrincipal` that is scoped to one
* workspace. Routes that touch Coolify/Gitea/Theia must call
* `requireWorkspacePrincipal()` and use `principal.workspace` to fetch
* the right Coolify Project / Gitea org.
*/
import { createHash, randomBytes } from 'crypto';
import { NextResponse } from 'next/server';
import { authSession } from '@/lib/auth/session-server';
import { query, queryOne } from '@/lib/db-postgres';
import {
type VibnWorkspace,
getWorkspaceById,
getWorkspaceBySlug,
getWorkspaceByOwner,
userHasWorkspaceAccess,
} from '@/lib/workspaces';
const KEY_PREFIX = 'vibn_sk_';
const KEY_RANDOM_BYTES = 32; // 256-bit secret
export interface WorkspacePrincipal {
/** "session" = browser user; "api_key" = automated/AI client */
source: 'session' | 'api_key';
workspace: VibnWorkspace;
/** fs_users.id of the human ultimately responsible for this request */
userId: string;
/** When source = "api_key", which key id was used */
apiKeyId?: string;
}
/**
* Resolve the workspace principal from either a NextAuth session or a
* `Bearer vibn_sk_...` token. Optional `targetSlug` enforces that the
* principal is for the requested workspace.
*
* Returns:
* - principal on success
* - NextResponse on failure (401 / 403) — return it directly from the route
*/
export async function requireWorkspacePrincipal(
request: Request,
opts: { targetSlug?: string; targetId?: string } = {},
): Promise<WorkspacePrincipal | NextResponse> {
const apiKey = extractApiKey(request);
if (apiKey) {
const principal = await resolveApiKey(apiKey);
if (!principal) {
return NextResponse.json({ error: 'Invalid or revoked API key' }, { status: 401 });
}
if (!matchesTarget(principal.workspace, opts)) {
return NextResponse.json({ error: 'API key not authorized for this workspace' }, { status: 403 });
}
return principal;
}
// Fall through to NextAuth session
const session = await authSession();
if (!session?.user?.email) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
}
const userRow = await queryOne<{ id: string }>(
`SELECT id FROM fs_users WHERE data->>'email' = $1 LIMIT 1`,
[session.user.email]
);
if (!userRow) {
return NextResponse.json({ error: 'No fs_users row for session' }, { status: 401 });
}
let workspace: VibnWorkspace | null = null;
if (opts.targetSlug) workspace = await getWorkspaceBySlug(opts.targetSlug);
else if (opts.targetId) workspace = await getWorkspaceById(opts.targetId);
else workspace = await getWorkspaceByOwner(userRow.id);
if (!workspace) {
return NextResponse.json({ error: 'Workspace not found' }, { status: 404 });
}
const ok = await userHasWorkspaceAccess(userRow.id, workspace.id);
if (!ok) {
return NextResponse.json({ error: 'Forbidden' }, { status: 403 });
}
return { source: 'session', workspace, userId: userRow.id };
}
function matchesTarget(
workspace: VibnWorkspace,
opts: { targetSlug?: string; targetId?: string }
): boolean {
if (opts.targetSlug && workspace.slug !== opts.targetSlug) return false;
if (opts.targetId && workspace.id !== opts.targetId) return false;
return true;
}
function extractApiKey(request: Request): string | null {
const auth = request.headers.get('authorization');
if (!auth) return null;
const m = /^Bearer\s+(.+)$/i.exec(auth.trim());
if (!m) return null;
const token = m[1].trim();
if (!token.startsWith(KEY_PREFIX)) return null;
return token;
}
async function resolveApiKey(token: string): Promise<WorkspacePrincipal | null> {
const hash = hashKey(token);
const row = await queryOne<{
id: string;
workspace_id: string;
created_by: string;
revoked_at: Date | null;
}>(
`SELECT id, workspace_id, created_by, revoked_at
FROM vibn_workspace_api_keys
WHERE key_hash = $1
LIMIT 1`,
[hash]
);
if (!row || row.revoked_at) return null;
const workspace = await getWorkspaceById(row.workspace_id);
if (!workspace) return null;
// Touch last_used_at without blocking
void query(
`UPDATE vibn_workspace_api_keys SET last_used_at = now() WHERE id = $1`,
[row.id]
).catch(() => undefined);
return {
source: 'api_key',
workspace,
userId: row.created_by,
apiKeyId: row.id,
};
}
// ──────────────────────────────────────────────────
// Key minting + hashing
// ──────────────────────────────────────────────────
export interface MintedApiKey {
id: string;
/** Full plaintext key — shown once at creation, never stored. */
token: string;
prefix: string;
workspace_id: string;
name: string;
created_at: Date;
}
export async function mintWorkspaceApiKey(opts: {
workspaceId: string;
name: string;
createdBy: string;
scopes?: string[];
}): Promise<MintedApiKey> {
const random = randomBytes(KEY_RANDOM_BYTES).toString('base64url');
const token = `${KEY_PREFIX}${random}`;
const hash = hashKey(token);
const prefix = token.slice(0, 12); // e.g. "vibn_sk_AbCd"
const inserted = await query<{ id: string; created_at: Date }>(
`INSERT INTO vibn_workspace_api_keys
(workspace_id, name, key_prefix, key_hash, scopes, created_by)
VALUES ($1, $2, $3, $4, $5::jsonb, $6)
RETURNING id, created_at`,
[
opts.workspaceId,
opts.name,
prefix,
hash,
JSON.stringify(opts.scopes ?? ['workspace:*']),
opts.createdBy,
]
);
return {
id: inserted[0].id,
token,
prefix,
workspace_id: opts.workspaceId,
name: opts.name,
created_at: inserted[0].created_at,
};
}
export async function listWorkspaceApiKeys(workspaceId: string): Promise<Array<{
id: string;
name: string;
prefix: string;
scopes: string[];
created_by: string;
last_used_at: Date | null;
revoked_at: Date | null;
created_at: Date;
}>> {
const rows = await query<{
id: string;
name: string;
key_prefix: string;
scopes: string[];
created_by: string;
last_used_at: Date | null;
revoked_at: Date | null;
created_at: Date;
}>(
`SELECT id, name, key_prefix, scopes, created_by, last_used_at, revoked_at, created_at
FROM vibn_workspace_api_keys
WHERE workspace_id = $1
ORDER BY created_at DESC`,
[workspaceId]
);
return rows.map(r => ({
id: r.id,
name: r.name,
prefix: r.key_prefix,
scopes: r.scopes,
created_by: r.created_by,
last_used_at: r.last_used_at,
revoked_at: r.revoked_at,
created_at: r.created_at,
}));
}
export async function revokeWorkspaceApiKey(workspaceId: string, keyId: string): Promise<boolean> {
const updated = await query<{ id: string }>(
`UPDATE vibn_workspace_api_keys
SET revoked_at = now()
WHERE id = $1 AND workspace_id = $2 AND revoked_at IS NULL
RETURNING id`,
[keyId, workspaceId]
);
return updated.length > 0;
}
function hashKey(token: string): string {
return createHash('sha256').update(token).digest('hex');
}

View File

@@ -54,7 +54,10 @@ async function giteaFetch(path: string, options: RequestInit = {}) {
}
/**
* Create a new repo under the admin user (or a specified owner).
* Create a new repo. By default creates under the admin user.
* Pass `owner` to create under a specific user OR org — when the owner
* is an org (or any user other than the token holder), Gitea requires
* the org-scoped endpoint `/orgs/{owner}/repos`.
*/
export async function createRepo(
name: string,
@@ -62,18 +65,86 @@ export async function createRepo(
): Promise<GiteaRepo> {
const { description = '', private: isPrivate = true, owner = GITEA_ADMIN_USER, auto_init = true } = opts;
return giteaFetch(`/user/repos`, {
const body = JSON.stringify({
name,
description,
private: isPrivate,
auto_init,
default_branch: 'main',
});
// Token-owner repos use /user/repos; everything else (orgs, other users)
// must go through /orgs/{owner}/repos.
const path = owner === GITEA_ADMIN_USER ? `/user/repos` : `/orgs/${owner}/repos`;
return giteaFetch(path, { method: 'POST', body });
}
// ──────────────────────────────────────────────────
// Organizations (per-workspace tenancy)
// ──────────────────────────────────────────────────
export interface GiteaOrg {
id: number;
username: string; // org name (Gitea uses "username" for orgs too)
full_name: string;
description?: string;
visibility: 'public' | 'private' | 'limited';
}
/**
* Create a Gitea organization. Requires the admin token to have
* permission to create orgs.
*/
export async function createOrg(opts: {
name: string;
fullName?: string;
description?: string;
visibility?: 'public' | 'private' | 'limited';
}): Promise<GiteaOrg> {
const { name, fullName = name, description = '', visibility = 'private' } = opts;
return giteaFetch(`/orgs`, {
method: 'POST',
body: JSON.stringify({
name,
username: name,
full_name: fullName,
description,
private: isPrivate,
auto_init,
default_branch: 'main',
visibility,
repo_admin_change_team_access: true,
}),
});
}
export async function getOrg(name: string): Promise<GiteaOrg | null> {
try {
return await giteaFetch(`/orgs/${name}`);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
if (msg.includes('404')) return null;
throw err;
}
}
/**
* Add a Gitea user to an org's "Owners" team (full access to the org).
* Falls back to the org's default team when "Owners" cannot be located.
*/
export async function addOrgOwner(orgName: string, username: string): Promise<void> {
const teams = (await giteaFetch(`/orgs/${orgName}/teams`)) as Array<{ id: number; name: string }>;
const owners = teams.find(t => t.name.toLowerCase() === 'owners') ?? teams[0];
if (!owners) throw new Error(`No teams found for org ${orgName}`);
await giteaFetch(`/teams/${owners.id}/members/${username}`, { method: 'PUT' });
}
export async function getUser(username: string): Promise<{ id: number; login: string } | null> {
try {
return await giteaFetch(`/users/${username}`);
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
if (msg.includes('404')) return null;
throw err;
}
}
/**
* Get an existing repo.
*/

270
lib/workspaces.ts Normal file
View File

@@ -0,0 +1,270 @@
/**
* Vibn workspaces — logical multi-tenancy on top of Coolify + Gitea.
*
* Each Vibn user gets one workspace. The workspace owns:
* - a Coolify Project UUID (the team/namespace boundary inside Coolify)
* - a Gitea org (which contains all repos for the workspace)
*
* All Vibn projects, apps, deployments, and AI access keys are
* scoped to a single workspace. Code that touches Coolify or Gitea
* MUST resolve a workspace first and use its IDs (never the legacy
* hardcoded admin user / project UUID).
*
* Coolify cannot create real Teams via its public API today — see
* Coolify changelog notes about scoping queries to current team and
* the lack of POST /teams. We treat one Coolify *Project* as our
* tenant boundary instead, and stamp `coolify_team_id` later if/when
* Coolify exposes team creation.
*/
import { query, queryOne } from '@/lib/db-postgres';
import { createProject as createCoolifyProject } from '@/lib/coolify';
import { createOrg, getOrg, getUser, addOrgOwner } from '@/lib/gitea';
export interface VibnWorkspace {
id: string;
slug: string;
name: string;
owner_user_id: string;
coolify_project_uuid: string | null;
coolify_team_id: number | null;
gitea_org: string | null;
provision_status: 'pending' | 'partial' | 'ready' | 'error';
provision_error: string | null;
created_at: Date;
updated_at: Date;
}
export interface VibnWorkspaceMember {
id: string;
workspace_id: string;
user_id: string;
role: 'owner' | 'admin' | 'member';
created_at: Date;
}
// ──────────────────────────────────────────────────
// Slug helpers
// ──────────────────────────────────────────────────
const SAFE_SLUG = /[^a-z0-9]+/g;
export function workspaceSlugFromEmail(email: string): string {
const local = email.split('@')[0]?.toLowerCase() ?? 'user';
return local.replace(SAFE_SLUG, '-').replace(/^-+|-+$/g, '') || 'user';
}
/** Coolify Project name we use for a workspace. Prefixed to avoid collisions. */
export function coolifyProjectNameFor(slug: string): string {
return `vibn-ws-${slug}`;
}
/** Gitea org name we use for a workspace. Same prefix for consistency. */
export function giteaOrgNameFor(slug: string): string {
return `vibn-${slug}`;
}
// ──────────────────────────────────────────────────
// CRUD
// ──────────────────────────────────────────────────
export async function getWorkspaceById(id: string): Promise<VibnWorkspace | null> {
return queryOne<VibnWorkspace>(`SELECT * FROM vibn_workspaces WHERE id = $1`, [id]);
}
export async function getWorkspaceBySlug(slug: string): Promise<VibnWorkspace | null> {
return queryOne<VibnWorkspace>(`SELECT * FROM vibn_workspaces WHERE slug = $1`, [slug]);
}
export async function getWorkspaceByOwner(userId: string): Promise<VibnWorkspace | null> {
return queryOne<VibnWorkspace>(
`SELECT * FROM vibn_workspaces WHERE owner_user_id = $1 ORDER BY created_at ASC LIMIT 1`,
[userId]
);
}
export async function listWorkspacesForUser(userId: string): Promise<VibnWorkspace[]> {
return query<VibnWorkspace>(
`SELECT w.* FROM vibn_workspaces w
LEFT JOIN vibn_workspace_members m ON m.workspace_id = w.id
WHERE w.owner_user_id = $1 OR m.user_id = $1
GROUP BY w.id
ORDER BY w.created_at ASC`,
[userId]
);
}
export async function userHasWorkspaceAccess(userId: string, workspaceId: string): Promise<boolean> {
const row = await queryOne<{ id: string }>(
`SELECT w.id FROM vibn_workspaces w
LEFT JOIN vibn_workspace_members m ON m.workspace_id = w.id AND m.user_id = $1
WHERE w.id = $2 AND (w.owner_user_id = $1 OR m.user_id = $1)
LIMIT 1`,
[userId, workspaceId]
);
return !!row;
}
// ──────────────────────────────────────────────────
// Get-or-create + provision
// ──────────────────────────────────────────────────
/**
* Idempotently ensures a workspace row exists for the user. Does NOT
* provision Coolify/Gitea — call ensureWorkspaceProvisioned() for that.
*
* Suitable to call from the NextAuth signIn callback (cheap, single insert).
*/
export async function ensureWorkspaceForUser(opts: {
userId: string;
email: string;
displayName?: string | null;
}): Promise<VibnWorkspace> {
const existing = await getWorkspaceByOwner(opts.userId);
if (existing) return existing;
const slug = await pickAvailableSlug(workspaceSlugFromEmail(opts.email));
const name = opts.displayName?.trim() || opts.email.split('@')[0];
const inserted = await query<VibnWorkspace>(
`INSERT INTO vibn_workspaces (slug, name, owner_user_id)
VALUES ($1, $2, $3)
RETURNING *`,
[slug, name, opts.userId]
);
const workspace = inserted[0];
await query(
`INSERT INTO vibn_workspace_members (workspace_id, user_id, role)
VALUES ($1, $2, 'owner')
ON CONFLICT (workspace_id, user_id) DO NOTHING`,
[workspace.id, opts.userId]
);
return workspace;
}
/**
* Provisions Coolify Project + Gitea org for a workspace if not yet done.
* Idempotent. Failures are recorded on the row but do not throw — callers
* can retry by calling again. Returns the up-to-date workspace row.
*/
export async function ensureWorkspaceProvisioned(workspace: VibnWorkspace): Promise<VibnWorkspace> {
if (workspace.provision_status === 'ready') return workspace;
let coolifyUuid = workspace.coolify_project_uuid;
let giteaOrg = workspace.gitea_org;
const errors: string[] = [];
// ── Coolify Project ────────────────────────────────────────────────
if (!coolifyUuid) {
try {
const project = await createCoolifyProject(
coolifyProjectNameFor(workspace.slug),
`Vibn workspace ${workspace.slug}`
);
coolifyUuid = project.uuid;
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
// Coolify returns 400/409 if the name collides — fall through; the
// workspace can still be patched manually with the right UUID.
errors.push(`coolify: ${msg}`);
console.error('[workspaces] Coolify provisioning failed', workspace.slug, msg);
}
}
// ── Gitea Org ──────────────────────────────────────────────────────
if (!giteaOrg) {
const wantOrg = giteaOrgNameFor(workspace.slug);
try {
const existingOrg = await getOrg(wantOrg);
if (existingOrg) {
giteaOrg = existingOrg.username;
} else {
const created = await createOrg({
name: wantOrg,
fullName: workspace.name,
description: `Vibn workspace for ${workspace.slug}`,
visibility: 'private',
});
giteaOrg = created.username;
}
} catch (err) {
const msg = err instanceof Error ? err.message : String(err);
errors.push(`gitea: ${msg}`);
console.error('[workspaces] Gitea org provisioning failed', workspace.slug, msg);
}
}
// ── Add the workspace owner to the Gitea org if they have a Gitea account.
// Best-effort: most Vibn users won't have a Gitea login, so a 404 is fine.
if (giteaOrg) {
try {
const ownerEmail = await queryOne<{ email: string }>(
`SELECT data->>'email' AS email FROM fs_users WHERE id = $1`,
[workspace.owner_user_id]
);
const candidateLogin = ownerEmail?.email
? workspaceSlugFromEmail(ownerEmail.email)
: null;
if (candidateLogin) {
const giteaUser = await getUser(candidateLogin);
if (giteaUser) {
await addOrgOwner(giteaOrg, giteaUser.login);
}
}
} catch (err) {
// Membership add is best-effort
console.warn('[workspaces] Skipping Gitea owner add', err);
}
}
const status: VibnWorkspace['provision_status'] =
coolifyUuid && giteaOrg ? '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()
WHERE id = $1
RETURNING *`,
[workspace.id, coolifyUuid, giteaOrg, status, errors.length ? errors.join('; ') : null]
);
return updated[0];
}
/**
* Convenience: get-or-create + provision in one call. Used by the
* project-create flow so the first project in a fresh account always
* has somewhere to land.
*/
export async function getOrCreateProvisionedWorkspace(opts: {
userId: string;
email: string;
displayName?: string | null;
}): Promise<VibnWorkspace> {
const ws = await ensureWorkspaceForUser(opts);
return ensureWorkspaceProvisioned(ws);
}
// ──────────────────────────────────────────────────
// Slug uniqueness
// ──────────────────────────────────────────────────
async function pickAvailableSlug(base: string): Promise<string> {
// Try base, then base-2, base-3, … up to base-99.
for (let i = 0; i < 100; i++) {
const candidate = i === 0 ? base : `${base}-${i + 1}`;
const existing = await queryOne<{ id: string }>(
`SELECT id FROM vibn_workspaces WHERE slug = $1 LIMIT 1`,
[candidate]
);
if (!existing) return candidate;
}
// Extremely unlikely fallback
return `${base}-${Date.now().toString(36)}`;
}