Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
51 commits
Select commit Hold shift + click to select a range
44d7cf3
Update AiGeminiModel.js
Sivadheeraj5356 Nov 6, 2026
9b9d2b0
Enhance ConvexClientProvider with auth and error handling
Sivadheeraj5356 Nov 6, 2026
efec0be
Add workspace view state management to Provider
Sivadheeraj5356 Nov 6, 2026
492ecfb
Require authenticated user for AI chat API
Sivadheeraj5356 Nov 6, 2026
001796a
Add authentication check in POST request handler
Sivadheeraj5356 Nov 6, 2026
d6c2cb4
Modify body styles in globals.css
Sivadheeraj5356 Nov 6, 2026
fc5eca4
Replace Geist font with Sora font in layout
Sivadheeraj5356 Nov 6, 2026
219ec41
Update loadWorkspaces to remove userId filter
Sivadheeraj5356 Nov 6, 2026
2d9478d
Refactor Workspace component for mobile tab support
Sivadheeraj5356 Nov 6, 2026
660e501
Refactor ChatView component with new features
Sivadheeraj5356 Nov 6, 2026
030f361
Refactor CodeView component with new features
Sivadheeraj5356 Nov 6, 2026
f759f75
Refactor Header component for improved functionality
Sivadheeraj5356 Nov 6, 2026
6184866
Refactor Hero component layout and styles
Sivadheeraj5356 Nov 6, 2026
7e2b481
Remove deploy action and update preview height
Sivadheeraj5356 Nov 6, 2026
c752a61
Refactor Google sign-in logic in SignInDialog
Sivadheeraj5356 Nov 6, 2026
1a81e12
Refactor GetAllWorkspace to remove userId
Sivadheeraj5356 Nov 6, 2026
a9085ef
Add WorkspaceViewContext for shared view state
Sivadheeraj5356 Nov 6, 2026
4a1de14
Create WorkspaceViewContext for shared view state
Sivadheeraj5356 Nov 6, 2026
0db04e8
Add Google OIDC configuration for authentication
Sivadheeraj5356 Nov 6, 2026
25ce647
Add authentication utility functions for user identity
Sivadheeraj5356 Nov 6, 2026
37b9b4a
Add build plan parser and line stripper functions
Sivadheeraj5356 Nov 6, 2026
f0aa3a7
Add Convex client and authentication handling
Sivadheeraj5356 Nov 6, 2026
3a71d87
Add Convex configuration functions
Sivadheeraj5356 Nov 6, 2026
93ece57
Add mergeFiles function to combine file entries
Sivadheeraj5356 Nov 6, 2026
459be04
Create model-label.js for Gemini 3.5 Flash
Sivadheeraj5356 Nov 6, 2026
da74009
Implement server-side Google ID token verification
Sivadheeraj5356 Nov 6, 2026
0aa0b83
Add session management functions for ID tokens
Sivadheeraj5356 Nov 6, 2026
8136950
Add tests for unauthenticated API route access
Sivadheeraj5356 Nov 6, 2026
c4e53d4
Delete lib/__tests__/tests__/__api-routes-auth.test.js
Sivadheeraj5356 Nov 6, 2026
3247694
Add tests for unauthenticated AI route access
Sivadheeraj5356 Nov 6, 2026
f432b2e
Add tests for convex config functions
Sivadheeraj5356 Nov 6, 2026
2969c95
Add tests for mergeFiles function
Sivadheeraj5356 Nov 6, 2026
01fc239
Add tests for server authentication functions
Sivadheeraj5356 Nov 6, 2026
adb19c3
Add unit tests for session management functions
Sivadheeraj5356 Nov 6, 2026
fbbeb6a
Add tests for LookUp component defaults and behavior
Sivadheeraj5356 Nov 6, 2026
477b322
Add fixture-client.jsx for workspace component testing
Sivadheeraj5356 Nov 6, 2026
4b29982
Add FixtureWorkspacePage with notFound handling
Sivadheeraj5356 Nov 6, 2026
ea7be92
Add fixture-client for workspace component testing
Sivadheeraj5356 Nov 6, 2026
c463c99
Add FixtureWorkspacePage component with notFound handling
Sivadheeraj5356 Nov 6, 2026
2425d52
Add CI workflow for testing and building project
Sivadheeraj5356 Nov 6, 2026
d4b70d2
Add authorization tests for Convex backend
Sivadheeraj5356 Nov 6, 2026
22ad835
Add fixture-gate script for conditional route inclusion
Sivadheeraj5356 Nov 6, 2026
0a125e8
Add Vitest configuration file
Sivadheeraj5356 Nov 6, 2026
412496e
Add indexes to users and workspace tables
Sivadheeraj5356 Nov 6, 2026
cfaab31
Refactor user creation and retrieval logic
Sivadheeraj5356 Nov 6, 2026
1a4e8be
Refactor workspace mutations and queries for user validation
Sivadheeraj5356 Nov 6, 2026
a3ce577
Update sign-in headings and agreement text
Sivadheeraj5356 Nov 6, 2026
f4cb6b3
Update README with authentication and access control details
Sivadheeraj5356 Nov 6, 2026
335ef65
Add test and prebuild scripts to package.json
Sivadheeraj5356 Nov 6, 2026
01b3550
Update package-lock.json
Sivadheeraj5356 Nov 6, 2026
4a3f19d
Delete context/context/WorkspaceViewContext.jsx
Sivadheeraj5356 Nov 6, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
test-and-build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm test
- name: Build (placeholder env; real values come from Vercel)
run: npm run build
env:
NEXT_PUBLIC_CONVEX_URL: https://placeholder.convex.cloud
NEXT_PUBLIC_GOOGLE_AUTH_KEY: placeholder-client-id
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,39 @@ data/LookUp.jsx default Sandpack files and dependencies
Push to Vercel and set `NEXT_PUBLIC_CONVEX_URL`, `NEXT_PUBLIC_GOOGLE_AUTH_KEY`, `GEMINI_API_KEY` and `GEMINI_MODEL` in the project's environment variables, then run `npx convex deploy` so the production Convex deployment has the current functions. Add the deployed domain to the OAuth client's authorized origins too.

`vercel.json` raises the timeout on `/api/gen-ai-code` to 60 seconds. Generating a full project usually takes 25 to 45 seconds, so that ceiling is real: very elaborate prompts can hit it. Trimming `CODE_GEN_PROMPT` in `data/Prompt.jsx` is the cheapest way to speed things up, since it currently asks for a header, navbar, footer, dashboard, routing and a dark mode toggle on every single generation.

## Authentication and access control

Sign-in uses Google's OIDC credential flow: the client receives a Google ID
token (a signed JWT), and both the Convex backend and the paid Next.js API
routes verify that token server-side. There is no client-side session state
that the backend trusts.

- `convex/auth.config.js` registers Google as the OIDC provider (issuer
`https://accounts.google.com`, audience = the OAuth web client ID). It ships
with the current client ID as a default; export `GOOGLE_CLIENT_ID` before
`npx convex deploy` if the OAuth client ever rotates.
- Every Convex function in `convex/users.js` and `convex/workspace.js`
requires the verified identity (`ctx.auth.getUserIdentity()`) and enforces
workspace ownership. Clients never send an email or user id for themselves.
- `/api/ai-chat` and `/api/gen-ai-code` require `Authorization: Bearer <id
token>` and verify it locally against Google's public JWKS (signature,
issuer, audience, expiry, per Google's production guidance) before any
model call (`lib/server-auth.js`), so anonymous traffic cannot spend the
Gemini quota. No cookies are used, so there is no CSRF surface.
- The client session (`lib/session.js`) is the ID token plus its claims. The
old unsigned `localStorage["user"]` profile is deleted on load and on
sign-in. ID tokens expire after about an hour; when a session expires the
user signs in again.

Deploying these changes requires both halves: `npx convex deploy` (pushes
`auth.config.js` and the guarded functions) and the Vercel redeploy of the
Next app. Deploying only one breaks sign-in: the new client no longer sends
the `email`/`userId` arguments the old backend functions required.

Tests: `npm test` covers token handling (`lib/__tests__/session.test.js`),
Google token verification failures (`lib/__tests__/server-auth.test.js`), the
anonymous-request gate on both AI routes
(`lib/__tests__/api-routes-auth.test.js`), and the full backend authorization
contract (anonymous rejected everywhere, cross-user read/write/list blocked,
owner allowed) in `convex-tests/authz.test.js` via `convex-test`.
86 changes: 75 additions & 11 deletions app/(main)/workspace/[id]/page.jsx
Original file line number Diff line number Diff line change
@@ -1,20 +1,84 @@
import React from 'react'
"use client"
import React, { useContext, useState } from 'react'
import Link from 'next/link'
import ChatView from '@/components/custom/ChatView'
import CodeView from '@/components/custom/CodeView'
import { WorkspaceViewContext } from '@/context/WorkspaceViewContext'
import { UserDetailsContext } from '@/context/UserDetailContext'
import { useSidebar } from '@/components/ui/sidebar'
const Workspace = () => {
import { House, SquarePen } from 'lucide-react'

const MOBILE_TABS = [
{ key: 'chat', label: 'Chat' },
{ key: 'code', label: 'Code' },
{ key: 'preview', label: 'Preview' },
]

// v0-style three-zone workspace (desktop): a slim global rail (real routes
// only), the conversation column, and the workbench. Mobile keeps the
// approved 3-way pill switcher and stacked panes. The Code/Preview state
// lives in WorkspaceViewContext so the workbench toolbar switch and the
// mobile switcher drive the same panes.
const Workspace = ({ initialMobilePane = 'chat' }) => {
const [mobilePane, setMobilePane] = useState(initialMobilePane)
const { workspaceView: codeTab, setWorkspaceView: setCodeTab } = useContext(WorkspaceViewContext)
const { userDetails } = useContext(UserDetailsContext)
const { toggleSidebar } = useSidebar()

const select = (key) => {
if (key === 'chat') {
setMobilePane('chat')
} else {
setMobilePane('ide')
setCodeTab(key)
}
}
const activeKey = mobilePane === 'chat' ? 'chat' : codeTab

return (
<div className='px-7 mt-2 max-h-screen'>
<div className='grid grid-cols-1 md:grid-cols-3 gap-6'>
<div className='flex gap-5'>
<ChatView />
</div>
<div className='col-span-2'>
<CodeView />
</div>
<div className='flex h-full min-h-0 flex-col'>
<div className='md:hidden flex justify-center mb-2 shrink-0 px-3 pt-2'>
<div className='flex items-center bg-[#101314] p-1 gap-1 rounded-lg border border-[#2A3130]' role='tablist' aria-label='Workspace view'>
{MOBILE_TABS.map((t) => (
<button key={t.key} type='button' role='tab' aria-selected={activeKey === t.key}
onClick={() => select(t.key)}
className={`text-[13px] px-4 py-1.5 rounded-md transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#7FB39D] ${activeKey === t.key ? 'text-[#7FB39D] bg-[#5F8F7B]/25' : 'text-[#9AA4A1] hover:text-[#EDE8DC]'}`}>
{t.label}
</button>
))}
</div>
</div>
<div className='flex min-h-0 flex-1'>
{/* Global rail: real destinations only. Desktop only. */}
<nav aria-label='Workspace navigation'
className='hidden md:flex w-[52px] shrink-0 flex-col items-center gap-1 border-r border-[#232928] py-3'>
<Link href='/' aria-label='Home'
className='flex h-9 w-9 items-center justify-center rounded-lg text-[#9AA4A1] transition-colors hover:bg-[#1B2120] hover:text-[#EDE8DC] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#7FB39D]'>
<House className='h-[18px] w-[18px]' />
</Link>
<Link href='/' aria-label='New workspace'
className='flex h-9 w-9 items-center justify-center rounded-lg text-[#9AA4A1] transition-colors hover:bg-[#1B2120] hover:text-[#EDE8DC] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#7FB39D]'>
<SquarePen className='h-[18px] w-[18px]' />
</Link>
<div className='flex-1' />
<button type='button' onClick={toggleSidebar} aria-label='Account and history'
className='flex h-8 w-8 items-center justify-center rounded-full bg-[#5F8F7B]/25 text-[11px] font-semibold text-[#7FB39D] transition-colors hover:bg-[#5F8F7B]/40 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#7FB39D]'>
{(userDetails?.name ?? '?').trim().charAt(0).toUpperCase()}
</button>
</nav>

{/* Conversation column */}
<div className={`min-h-0 w-full md:w-[368px] md:shrink-0 md:border-r md:border-[#232928] ${mobilePane === 'chat' ? 'flex' : 'hidden'} md:flex`}>
<ChatView />
</div>

{/* Workbench */}
<div className={`min-h-0 min-w-0 flex-1 ${mobilePane === 'ide' ? '' : 'hidden'} md:block`}>
<CodeView activeTab={codeTab} setActiveTab={setCodeTab} />
</div>
</div>
</div>
)
}

export default Workspace
export default Workspace
32 changes: 26 additions & 6 deletions app/ConvexClientProvider.jsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,30 @@
"use client";

import { ConvexProvider, ConvexReactClient } from "convex/react";
import { ReactNode } from "react";

const convex = new ConvexReactClient(process.env.NEXT_PUBLIC_CONVEX_URL);
import { ConvexProvider } from "convex/react";
import { useEffect } from "react";
import { convexClient, applyStoredAuth } from "@/lib/convex-client";

// When the backend is not configured, fail visibly and keep generation
// disabled: no provider, no data hooks, an explicit state instead of a
// build-time crash or a runtime failure on a placeholder URL.
export function ConvexClientProvider({ children }) {
return <ConvexProvider client={convex}>{children}</ConvexProvider>;
}
useEffect(() => {
// Pick up a stored Google ID token (returning visitor) so Convex function
// calls are authenticated from the first render.
applyStoredAuth();
}, []);

if (!convexClient) {
return (
<div role="alert" className="flex min-h-screen flex-col items-center justify-center gap-2 p-8 text-center">
<h1 className="text-xl font-semibold">Configuration unavailable</h1>
<p className="max-w-md text-sm opacity-80">
NEXT_PUBLIC_CONVEX_URL is not set, so this deployment cannot reach its
backend. Sign-in, workspaces and code generation are disabled until it
is configured.
</p>
</div>
);
}
return <ConvexProvider client={convexClient}>{children}</ConvexProvider>;
}
61 changes: 36 additions & 25 deletions app/Provider.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,54 +7,63 @@ import { UserDetailsContext } from '@/context/UserDetailContext'
import { useState } from 'react'
import { GoogleOAuthProvider } from '@react-oauth/google'
import { useConvex } from 'convex/react'
import { loadSession, clearSession } from '@/lib/session'
import { applyStoredAuth } from '@/lib/convex-client'
import { api } from '@/convex/_generated/api'
import { SidebarProvider } from '@/components/ui/sidebar'
import AppSidebar from '@/components/custom/AppSidebar'
import { ActionContext } from '@/context/ActionContext'
import { WorkspaceViewContext } from '@/context/WorkspaceViewContext'
import { usePathname, useRouter } from 'next/navigation'

const Provider = ({children}) => {
const [messages, setMessages] = useState()
const [userDetails, setUserDetails] = useState()
const [action, setAction] = useState()
const [workspaceView, setWorkspaceView] = useState('code')
const router = useRouter()
const pathname = usePathname()
// Fixture preview routes render their own self-contained chrome.
const isFixtureRoute = pathname?.startsWith('/fixture-workspace')
const convex = useConvex()
useEffect(() => {
const isAuthenticated = async () => {
try {
const storedUser = localStorage.getItem('user')
const session = loadSession()

if (!storedUser) {
if (pathname !== '/') {
if (!session) {
// Drop any legacy unsigned session too: a forged "user" key must
// never count as signed in.
clearSession()
if (!isFixtureRoute && pathname !== '/') {
router.push('/')
}
return
}

const parsedUser = JSON.parse(storedUser)
const convexUser = await convex.query(api.users.GetUser, {
email: parsedUser.email
})
// Register the stored Google ID token so the GetUser call below is
// authenticated; the backend resolves the account from the verified
// identity, never from client-supplied data.
applyStoredAuth()

if (!convexUser) {
// The stored session points at a user that no longer exists in this
// Convex deployment. Keeping it would leave the app signed in with no
// usable id, so drop it and let the user sign in again.
console.warn('Stored session is no longer valid, signing out:', parsedUser.email)
localStorage.removeItem('user')
setUserDetails(undefined)
return
let convexUser
try {
convexUser = await convex.query(api.users.GetUser, {})
} catch (firstErr) {
// Token propagation after setAuth can lag one round trip; retry once.
await new Promise((resolve) => setTimeout(resolve, 700))
convexUser = await convex.query(api.users.GetUser, {})
}

const userWithId = {
...parsedUser,
setUserDetails({
name: session.name,
email: session.email,
picture: session.picture,
_id: convexUser._id
}
localStorage.setItem('user', JSON.stringify(userWithId))
setUserDetails(userWithId)
})
} catch (error) {
console.error("Error in isAuthenticated:", error)
clearSession()
}
}

Expand All @@ -67,6 +76,7 @@ const Provider = ({children}) => {
<UserDetailsContext.Provider value={{userDetails, setUserDetails}}>
<ContextMessages.Provider value={{messages, setMessages}}>
<ActionContext.Provider value={{action, setAction}}>
<WorkspaceViewContext.Provider value={{workspaceView, setWorkspaceView}}>
<ThemeProvider
attribute="class"
defaultTheme="dark"
Expand All @@ -75,16 +85,17 @@ const Provider = ({children}) => {
>
<div className="max-h-screen w-full">
<SidebarProvider defaultOpen={false}>
<div className='absolute'>
{!isFixtureRoute && <div className='absolute'>
<AppSidebar />
</div>
</div>}
<div className='relative flex min-h-svh w-full min-w-0 flex-1 flex-col'>
<Header />
<main className='w-full flex-1'>{children}</main>
{!isFixtureRoute && <Header />}
<main className='h-full w-full min-h-0 flex-1'>{children}</main>
</div>
</SidebarProvider>
</div>
</ThemeProvider>
</WorkspaceViewContext.Provider>
</ActionContext.Provider>
</ContextMessages.Provider>
</UserDetailsContext.Provider>
Expand All @@ -93,4 +104,4 @@ const Provider = ({children}) => {
)
}

export default Provider
export default Provider
8 changes: 8 additions & 0 deletions app/api/ai-chat/route.jsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,13 @@
import { createChatSession, describeAiError } from "@/configs/AiGeminiModel"
import { requireApiUser, AuthError } from "@/lib/server-auth"
import { NextResponse } from "next/server"

export async function POST(req) {
try {
// Authentication happens before any model call so anonymous traffic
// cannot spend the server's Gemini quota.
await requireApiUser(req)

const { prompt } = await req.json()

if (!prompt) {
Expand All @@ -15,6 +20,9 @@ export async function POST(req) {

return NextResponse.json({ result: AiResponse })
} catch (error) {
if (error instanceof AuthError) {
return NextResponse.json({ error: error.message }, { status: error.status })
}
const { status, message } = describeAiError(error)
console.error(`[api/ai-chat] ${status}: ${message}`)
return NextResponse.json({ error: message }, { status })
Expand Down
8 changes: 8 additions & 0 deletions app/api/gen-ai-code/route.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { createCodeSession, describeAiError } from "@/configs/AiGeminiModel"
import { requireApiUser, AuthError } from "@/lib/server-auth"
import { NextResponse } from "next/server"

// The model is asked for raw JSON, but it sometimes wraps it in a markdown
Expand All @@ -21,6 +22,10 @@ function parseJsonResponse(text) {

export async function POST(req) {
try {
// Authentication happens before any model call so anonymous traffic
// cannot spend the server's Gemini quota.
await requireApiUser(req)

const { prompt } = await req.json()

if (!prompt) {
Expand Down Expand Up @@ -51,6 +56,9 @@ export async function POST(req) {

return NextResponse.json(parsed)
} catch (e) {
if (e instanceof AuthError) {
return NextResponse.json({ error: e.message }, { status: e.status })
}
const { status, message } = describeAiError(e)
console.error(`[api/gen-ai-code] ${status}: ${message}`)
return NextResponse.json({ error: message }, { status })
Expand Down
Loading
Loading