feat: provision dedicated per-project Theia workspaces

- lib/coolify-workspace.ts: creates a Coolify docker-image app at
  {slug}.ide.vibnai.com for each project, patches in vibn-auth Traefik
  labels, sets env vars, and starts deployment
- create/route.ts: provisions Theia workspace after Gitea repo creation;
  stores theiaWorkspaceUrl + theiaAppUuid on the project record
- theia-auth/route.ts: for *.ide.vibnai.com hosts, verifies the
  authenticated user is the project owner (slug → fs_projects lookup)
- overview/page.tsx: Open IDE always links (dedicated URL or shared fallback)
- project-creation-modal.tsx: shows dedicated workspace URL in success screen

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
2026-02-19 13:14:21 -08:00
parent 4678928ee0
commit a22d5a0f18
5 changed files with 237 additions and 41 deletions

View File

@@ -4,6 +4,7 @@ import { authOptions } from '@/lib/auth/authOptions';
import { query } from '@/lib/db-postgres';
import { randomUUID } from 'crypto';
import { createRepo, createWebhook, GITEA_ADMIN_USER_EXPORT } from '@/lib/gitea';
import { provisionTheiaWorkspace } from '@/lib/coolify-workspace';
import type { ProjectPhaseData, ProjectPhaseScores } from '@/lib/types/project-artifacts';
const GITEA_ADMIN_USER = GITEA_ADMIN_USER_EXPORT;
@@ -90,7 +91,24 @@ export async function POST(request: Request) {
}
// ──────────────────────────────────────────────
// 3. Save project record
// 3. Provision dedicated Theia workspace
// ──────────────────────────────────────────────
let theiaWorkspaceUrl: string | null = null;
let theiaAppUuid: string | null = null;
let theiaError: string | null = null;
try {
const workspace = await provisionTheiaWorkspace(slug, projectId, giteaRepo);
theiaWorkspaceUrl = workspace.workspaceUrl;
theiaAppUuid = workspace.appUuid;
console.log(`[API] Theia workspace provisioned: ${theiaWorkspaceUrl}`);
} catch (err) {
theiaError = err instanceof Error ? err.message : String(err);
console.error('[API] Theia workspace provisioning failed (non-fatal):', theiaError);
}
// ──────────────────────────────────────────────
// 4. Save project record
// ──────────────────────────────────────────────
const projectData = {
id: projectId,
@@ -127,6 +145,10 @@ export async function POST(request: Request) {
giteaSshUrl,
giteaWebhookId,
giteaError,
// Theia workspace
theiaWorkspaceUrl,
theiaAppUuid,
theiaError,
// Context snapshot (kept fresh by webhooks)
contextSnapshot: null,
createdAt: now,
@@ -163,6 +185,8 @@ export async function POST(request: Request) {
? { repo: giteaRepo, repoUrl: giteaRepoUrl, cloneUrl: giteaCloneUrl, sshUrl: giteaSshUrl }
: null,
giteaError: giteaError ?? undefined,
theiaWorkspaceUrl,
theiaError: theiaError ?? undefined,
});
} catch (error) {
console.error('[POST /api/projects/create] Error:', error);

View File

@@ -1,17 +1,21 @@
/**
* GET /api/theia-auth
*
* Traefik ForwardAuth endpoint for theia.vibnai.com.
* Traefik ForwardAuth endpoint for Theia IDE domains.
*
* Traefik calls this URL for every request to the Theia IDE, forwarding
* the user's Cookie header via authRequestHeaders. We validate the
* NextAuth database session (strategy: "database") by looking up the
* session token directly in Postgres — avoiding Prisma / authOptions
* imports that cause build-time issues under --network host.
* Handles two cases:
* 1. theia.vibnai.com — shared IDE: any authenticated user may access
* 2. {slug}.ide.vibnai.com — per-project IDE: only the project owner may access
*
* Traefik calls this URL for every request to those Theia domains, forwarding
* the user's Cookie header via authRequestHeaders. We validate the NextAuth
* database session directly in Postgres (avoids Prisma / authOptions build-time
* issues under --network host).
*
* Returns:
* 200 — valid session, Traefik lets the request through
* 200 — valid session (and owner check passed), Traefik lets the request through
* 302 — no/expired session, redirect browser to Vibn login
* 403 — authenticated but not the project owner
*/
import { NextRequest, NextResponse } from 'next/server';
@@ -19,34 +23,33 @@ import { query } from '@/lib/db-postgres';
export const dynamic = 'force-dynamic';
const APP_URL = process.env.NEXTAUTH_URL ?? 'https://vibnai.com';
const APP_URL = process.env.NEXTAUTH_URL ?? 'https://vibnai.com';
const THEIA_URL = 'https://theia.vibnai.com';
const IDE_SUFFIX = '.ide.vibnai.com';
// NextAuth v4 uses these cookie names for database sessions
const SESSION_COOKIE_NAMES = [
'__Secure-next-auth.session-token', // HTTPS (production)
'next-auth.session-token', // HTTP fallback
'__Secure-next-auth.session-token',
'next-auth.session-token',
];
export async function GET(request: NextRequest) {
// Extract session token from cookies
// ── 1. Extract session token ──────────────────────────────────────────────
let sessionToken: string | null = null;
for (const name of SESSION_COOKIE_NAMES) {
const val = request.cookies.get(name)?.value;
if (val) { sessionToken = val; break; }
}
if (!sessionToken) {
return redirectToLogin(request);
}
if (!sessionToken) return redirectToLogin(request);
// Look up session in Postgres (NextAuth stores sessions in the "sessions" table)
// ── 2. Validate session in Postgres ──────────────────────────────────────
let userEmail: string | null = null;
let userName: string | null = null;
let userName: string | null = null;
let userId: string | null = null;
try {
const rows = await query<{ email: string; name: string }>(
`SELECT u.email, u.name
const rows = await query<{ email: string; name: string; user_id: string }>(
`SELECT u.email, u.name, s.user_id
FROM sessions s
JOIN users u ON u.id = s.user_id
WHERE s.session_token = $1
@@ -56,31 +59,57 @@ export async function GET(request: NextRequest) {
);
if (rows.length > 0) {
userEmail = rows[0].email;
userName = rows[0].name;
userName = rows[0].name;
userId = rows[0].user_id;
}
} catch (err) {
console.error('[theia-auth] DB error:', err);
return redirectToLogin(request);
}
if (!userEmail) {
return redirectToLogin(request);
if (!userEmail || !userId) return redirectToLogin(request);
// ── 3. Per-project ownership check for *.ide.vibnai.com ──────────────────
const forwardedHost = request.headers.get('x-forwarded-host') ?? '';
if (forwardedHost.endsWith(IDE_SUFFIX)) {
const slug = forwardedHost.slice(0, -IDE_SUFFIX.length);
try {
const rows = await query<{ user_id: string }>(
`SELECT user_id FROM fs_projects WHERE slug = $1 LIMIT 1`,
[slug],
);
if (rows.length === 0) {
// Unknown project slug — deny
return new NextResponse('Workspace not found', { status: 403 });
}
const ownerUserId = rows[0].user_id;
if (ownerUserId !== userId) {
// Authenticated but not the owner
return new NextResponse('Access denied — this workspace belongs to another user', { status: 403 });
}
} catch (err) {
console.error('[theia-auth] project ownership check error:', err);
return redirectToLogin(request);
}
}
// Session valid — pass user identity to Theia via response headers
// ── 4. Allow — pass user identity headers to Theia ───────────────────────
return new NextResponse(null, {
status: 200,
headers: {
'X-Auth-Email': userEmail,
'X-Auth-Name': userName ?? '',
'X-Auth-Name': userName ?? '',
},
});
}
function redirectToLogin(request: NextRequest): NextResponse {
// Traefik ForwardAuth sets X-Forwarded-Host to the auth service's host (vibnai.com),
// not the original request host (theia.vibnai.com). Use THEIA_URL directly as the
// destination so the user returns to Theia after logging in.
// Use THEIA_URL as the callbackUrl so the user lands back on Theia after login.
// (X-Forwarded-Host points to vibnai.com via Traefik, not the original Theia domain.)
const loginUrl = `${APP_URL}/auth?callbackUrl=${encodeURIComponent(THEIA_URL)}`;
return NextResponse.redirect(loginUrl, { status: 302 });
}