Files
vibn-frontend/app/[workspace]/settings/page.tsx
Mark Henderson acb63a2a5a 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
2026-04-20 17:17:12 -07:00

286 lines
9.4 KiB
TypeScript

"use client";
import { useState, useEffect } from 'react';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { auth } from '@/lib/firebase/config';
import { toast } from 'sonner';
import { Settings, User, Bell, Shield, Trash2 } from 'lucide-react';
import { useParams, useRouter } from 'next/navigation';
import { WorkspaceKeysPanel } from '@/components/workspace/WorkspaceKeysPanel';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog";
interface WorkspaceSettings {
name: string;
description: string;
createdAt: any;
}
export default function SettingsPage() {
const params = useParams();
const router = useRouter();
const workspace = params.workspace as string;
const [settings, setSettings] = useState<WorkspaceSettings | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [displayName, setDisplayName] = useState('');
const [email, setEmail] = useState('');
useEffect(() => {
loadSettings();
loadUserProfile();
}, []);
const loadSettings = async () => {
try {
const user = auth.currentUser;
if (!user) return;
const token = await user.getIdToken();
const response = await fetch(`/api/workspace/${workspace}/settings`, {
headers: {
'Authorization': `Bearer ${token}`,
},
});
if (response.ok) {
const data = await response.json();
setSettings(data);
}
} catch (error) {
console.error('Error loading settings:', error);
} finally {
setLoading(false);
}
};
const loadUserProfile = () => {
const user = auth.currentUser;
if (user) {
setDisplayName(user.displayName || '');
setEmail(user.email || '');
}
};
const handleSaveProfile = async () => {
setSaving(true);
try {
const user = auth.currentUser;
if (!user) {
toast.error('Please sign in');
return;
}
// Update profile logic would go here
toast.success('Profile updated successfully');
} catch (error) {
console.error('Error saving profile:', error);
toast.error('Failed to update profile');
} finally {
setSaving(false);
}
};
return (
<div className="flex h-full flex-col overflow-auto">
<div className="flex-1 p-8 space-y-8 max-w-4xl">
{/* Header */}
<div>
<h1 className="text-4xl font-bold mb-2">Settings</h1>
<p className="text-muted-foreground text-lg">
Manage your workspace and account preferences
</p>
</div>
{/* Profile Settings */}
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<User className="h-5 w-5" />
<CardTitle>Profile</CardTitle>
</div>
<CardDescription>Update your personal information</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="displayName">Display Name</Label>
<Input
id="displayName"
value={displayName}
onChange={(e) => setDisplayName(e.target.value)}
placeholder="Your display name"
/>
</div>
<div className="space-y-2">
<Label htmlFor="email">Email</Label>
<Input
id="email"
type="email"
value={email}
disabled
className="opacity-60 cursor-not-allowed"
/>
<p className="text-xs text-muted-foreground">
Email cannot be changed directly. Contact support if needed.
</p>
</div>
<Button onClick={handleSaveProfile} disabled={saving}>
{saving ? 'Saving...' : 'Save Changes'}
</Button>
</CardContent>
</Card>
{/* Workspace Settings */}
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Settings className="h-5 w-5" />
<CardTitle>Workspace</CardTitle>
</div>
<CardDescription>Configure workspace settings</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label>Workspace Name</Label>
<Input
value={workspace}
disabled
className="opacity-60 cursor-not-allowed"
/>
<p className="text-xs text-muted-foreground">
Workspace identifier cannot be changed after creation
</p>
</div>
{settings?.createdAt && (
<div className="space-y-2">
<Label>Created</Label>
<p className="text-sm">
{new Date(settings.createdAt._seconds * 1000).toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
})}
</p>
</div>
)}
</CardContent>
</Card>
{/* Workspace tenancy + AI access keys */}
<WorkspaceKeysPanel workspaceSlug={workspace} />
{/* Notifications */}
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Bell className="h-5 w-5" />
<CardTitle>Notifications</CardTitle>
</div>
<CardDescription>Manage your notification preferences</CardDescription>
</CardHeader>
<CardContent>
<div className="space-y-4">
<div className="flex items-center justify-between">
<div>
<p className="font-medium">Email Notifications</p>
<p className="text-sm text-muted-foreground">Receive updates via email</p>
</div>
<Button variant="outline" disabled>
Coming Soon
</Button>
</div>
<div className="flex items-center justify-between">
<div>
<p className="font-medium">Session Summaries</p>
<p className="text-sm text-muted-foreground">Daily AI session summaries</p>
</div>
<Button variant="outline" disabled>
Coming Soon
</Button>
</div>
</div>
</CardContent>
</Card>
{/* Security */}
<Card>
<CardHeader>
<div className="flex items-center gap-2">
<Shield className="h-5 w-5" />
<CardTitle>Security</CardTitle>
</div>
<CardDescription>Manage your account security</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="flex items-center justify-between">
<div>
<p className="font-medium">Change Password</p>
<p className="text-sm text-muted-foreground">Update your account password</p>
</div>
<Button variant="outline" disabled>
Coming Soon
</Button>
</div>
<div className="flex items-center justify-between">
<div>
<p className="font-medium">Two-Factor Authentication</p>
<p className="text-sm text-muted-foreground">Add an extra layer of security</p>
</div>
<Button variant="outline" disabled>
Coming Soon
</Button>
</div>
</CardContent>
</Card>
{/* Danger Zone */}
<Card className="border-red-500/50">
<CardHeader>
<div className="flex items-center gap-2">
<Trash2 className="h-5 w-5 text-red-500" />
<CardTitle className="text-red-500">Danger Zone</CardTitle>
</div>
<CardDescription>Irreversible and destructive actions</CardDescription>
</CardHeader>
<CardContent>
<AlertDialog>
<AlertDialogTrigger asChild>
<Button variant="destructive" disabled>
Delete Workspace
</Button>
</AlertDialogTrigger>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
<AlertDialogDescription>
This action cannot be undone. This will permanently delete your workspace and all associated data.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction className="bg-red-600 hover:bg-red-700">
Delete Workspace
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</CardContent>
</Card>
</div>
</div>
);
}