diff --git a/.dockerignore b/.dockerignore index 12bb6fe..d265653 100644 --- a/.dockerignore +++ b/.dockerignore @@ -8,3 +8,9 @@ README.md .env.local .env context +infrasity_ref +.recordings +.screenshots +.taste-skill +.agent +.agents diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..c30bae1 --- /dev/null +++ b/.env.example @@ -0,0 +1,29 @@ +# Example environment variables for AppForge +# Copy this file to .env.local and populate the secrets. +# Never commit real keys to git. + +# 21st.dev Component Registry API Key +API_KEY_21ST=your-21st-dev-key + +# InsForge / Supabase +NEXT_PUBLIC_INSFORGE_URL=https://your-project.supabase.co +NEXT_PUBLIC_INSFORGE_ANON_KEY=your-anon-key +SUPABASE_SERVICE_ROLE_KEY=your-service-role-key + +# AI Copilot Keys +GROQ_API_KEY=your-groq-api-key +GEMINI_API_KEY=your-gemini-api-key + +# Upstash Redis +UPSTASH_REDIS_REST_URL=https://your-upstash.upstash.io +UPSTASH_REDIS_REST_TOKEN=your-upstash-token + +# Clerk Authentication & Redirect Settings +NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY=your-clerk-publishable-key +CLERK_SECRET_KEY=your-clerk-secret-key +NEXT_PUBLIC_CLERK_SIGN_IN_URL=/sign-in +NEXT_PUBLIC_CLERK_SIGN_UP_URL=/sign-up +NEXT_PUBLIC_CLERK_SIGN_IN_FALLBACK_REDIRECT_URL=/apps +NEXT_PUBLIC_CLERK_SIGN_UP_FALLBACK_REDIRECT_URL=/apps +NEXT_PUBLIC_CLERK_AFTER_SIGN_IN_URL=/apps +NEXT_PUBLIC_CLERK_AFTER_SIGN_UP_URL=/apps diff --git a/.github/workflows/production.yml b/.github/workflows/production.yml index 8ef04d5..3525206 100644 --- a/.github/workflows/production.yml +++ b/.github/workflows/production.yml @@ -2,9 +2,7 @@ name: AppForge Enterprise CI/CD Pipeline on: push: - branches: [ "master", "main" ] pull_request: - branches: [ "master", "main" ] jobs: # Job 1: Linting and Code Integrity Verification @@ -15,10 +13,10 @@ jobs: - name: Checkout Codebase uses: actions/checkout@v4 - - name: Setup Node.js 20 + - name: Setup Node.js 22 uses: actions/setup-node@v4 with: - node-version: '20' + node-version: '22' cache: 'npm' - name: Install Dependencies @@ -30,11 +28,70 @@ jobs: - name: ESLint Code Quality Scan run: npm run lint - # Job 2: Build Verification & Dockerization + # Job 2A: Unit Test Suite (Pure Logic, AST, Proxy Payload & Component Tests) + unit-tests: + name: Unit Tests (Pure Logic, AST, Proxy Payload & Components) + runs-on: ubuntu-latest + needs: lint-and-typecheck + steps: + - name: Checkout Codebase + uses: actions/checkout@v4 + + - name: Setup Node.js 22 + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: 'npm' + + - name: Install Dependencies + run: npm ci --legacy-peer-deps + + - name: Run Vitest Unit Tests + run: npm run test:unit + + # Job 2B: Database Integration Test Suite (Multi-Tenant Isolation & RLS Verification) + database-tests: + name: Database Tests (Multi-Tenant Isolation & RLS Verification) + runs-on: ubuntu-latest + needs: lint-and-typecheck + steps: + - name: Checkout Codebase + uses: actions/checkout@v4 + + - name: Setup Node.js 22 + uses: actions/setup-node@v4 + with: + node-version: '22' + cache: 'npm' + + - name: Install Dependencies + run: npm ci --legacy-peer-deps + + - name: Check Required Test Database Secrets + run: | + if [ -z "${{ secrets.TEST_SUPABASE_URL }}" ] || [ -z "${{ secrets.TEST_SUPABASE_ANON_KEY }}" ] || [ -z "${{ secrets.TEST_SUPABASE_SERVICE_ROLE_KEY }}" ]; then + echo "::error::CRITICAL: Dedicated test database secrets (TEST_SUPABASE_URL, TEST_SUPABASE_ANON_KEY, TEST_SUPABASE_SERVICE_ROLE_KEY) are missing in GitHub repository secrets! Testing against production database (upljqampxcmhqjszatrp) is strictly forbidden." + exit 1 + fi + + - name: Run Vitest Database Tests + env: + NEXT_PUBLIC_INSFORGE_URL: ${{ secrets.TEST_SUPABASE_URL }} + NEXT_PUBLIC_INSFORGE_ANON_KEY: ${{ secrets.TEST_SUPABASE_ANON_KEY }} + SUPABASE_SERVICE_ROLE_KEY: ${{ secrets.TEST_SUPABASE_SERVICE_ROLE_KEY }} + TEST_SUPABASE_URL: ${{ secrets.TEST_SUPABASE_URL }} + TEST_SUPABASE_ANON_KEY: ${{ secrets.TEST_SUPABASE_ANON_KEY }} + TEST_SUPABASE_SERVICE_ROLE_KEY: ${{ secrets.TEST_SUPABASE_SERVICE_ROLE_KEY }} + TEST_DATABASE_URL: ${{ secrets.TEST_DATABASE_URL }} + CLERK_SECRET_KEY: ${{ secrets.CLERK_SECRET_KEY }} + NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: ${{ secrets.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY }} + run: npm run test:db + + # Job 3: Build Verification & Dockerization build-and-containerize: name: Docker Multi-Stage Build runs-on: ubuntu-latest - needs: lint-and-typecheck # Only build if the code is syntactically perfect! + needs: [unit-tests, database-tests] steps: - name: Checkout Codebase uses: actions/checkout@v4 @@ -47,7 +104,7 @@ jobs: with: context: . file: ./Dockerfile - push: false # Set to true later when mapping to AWS ECR or Docker Hub + push: false load: true tags: appforge:latest cache-from: type=gha diff --git a/.gitignore b/.gitignore index 2035bcc..307e875 100644 --- a/.gitignore +++ b/.gitignore @@ -32,6 +32,8 @@ yarn-error.log* # env files (can opt-in for committing if needed) .env* +.env.local +!.env.example # vercel .vercel @@ -48,8 +50,16 @@ agent-skills agent_skills claude.md agents.md +# Screenshots & Visual Audits +.screenshots/ +public/audit-screenshots/ +.taste-skill/ CLAUDE.md AGENTS.md .agents/ .agent/ + +# References +infrasity_ref/ + diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000..3ed628d --- /dev/null +++ b/DESIGN.md @@ -0,0 +1,122 @@ +# AppForge Design System Specification (DESIGN.md) + +This document establishes the official design tokens and visual principles for AppForge, tailored for high-craft, restrained software UI (Linear / Vercel / Stripe caliber). + +--- + +## 1. Direction & Aesthetic Identity + +- **Visual Direction**: Soft lavender atmospheric field, frosted light surfaces with multi-stop backdrop blur, a single large sculpted glass ribbon behind the top-right viewport, and a disciplined violet/indigo accent ramp. +- **Core Principle**: Restraint over decoration. Optical alignment, typographic rhythm, 1px rgba hairline borders, two-layer ambient+diffuse soft shadows, and zero visual clutter. +- **Rules**: + - No eyebrow pills or kickers. + - No emoji in chrome or data. + - No nested bordered boxes ("card inside a card"). Every panel is a single coherent frosted surface. + - No hardcoded hex values or raw Tailwind arbitrary colors in components. + - Max body line width capped at 60ch. + - All icons from Lucide only with consistent 1.5px/1.75px stroke. + +--- + +## 2. Typographic Scale & Rhythm + +### Font Families +- **Display & Sans**: Inter / Geist Sans (`--font-sans`, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif) +- **Code & Numbers**: JetBrains Mono / SF Mono / Geist Mono (`--font-mono`, monospace) + +### Hierarchy +| Role | Size / Clamp | Weight | Line Height | Tracking | Purpose | +|------|--------------|--------|-------------|----------|---------| +| **Display Headline** | `clamp(48px, 6vw, 76px)` | 700 | 1.02 | `-0.035em` | Hero landing title | +| **Hero Subtitle** | `17px–18px` | 400 | 1.6 | `-0.01em` | Explanatory copy (max 60ch) | +| **Section Headings** | `20px` | 600 | 1.3 | `-0.02em` | Major structural sections | +| **Panel Headers / Tabs** | `14px–15px` | 500 / 600 | 1.4 | `-0.01em` | Top nav, segmented controls | +| **Small Caps / Meta** | `12px` | 600 | 1.2 | `0.06em` | Small caps section tags | +| **Data & Code** | `13px` | 400 / 500 | 1.6 | `0em` | Code lines, table rows, JSON | + +*Floor rule: Nothing rendered below 12px.* + +--- + +## 3. Color Tokens + +### 3.1 Neutral Scale (Slate Ramp) +| Token | Light Theme | Dark Theme | Purpose | +|-------|-------------|------------|---------| +| `--bg-canvas` | `#EEF0FA` → `#F5F6FD` | `#0B0D17` → `#0E1122` | Cohesive lavender wash | +| `--surface-frosted` | `rgba(255, 255, 255, 0.76)` | `rgba(20, 24, 40, 0.72)` | Frosted glass cards | +| `--surface-subtle` | `rgba(255, 255, 255, 0.50)` | `rgba(255, 255, 255, 0.04)` | Inactive pills, inner wells | +| `--border-hairline` | `rgba(148, 163, 184, 0.22)` | `rgba(255, 255, 255, 0.08)` | 1px card/divider borders | +| `--border-frosted` | `rgba(255, 255, 255, 0.85)` | `rgba(255, 255, 255, 0.12)` | Outer card edge reflection | +| `--text-primary` | `#0F172A` (Slate 900) | `#F8FAFC` (Slate 50) | Headline, labels (contrast > 12:1) | +| `--text-muted` | `#475569` (Slate 600) | `#94A3B8` (Slate 400) | Body copy (WCAG AA pass: ≥ 5.5:1) | +| `--text-faint` | `#64748B` (Slate 500) | `#64748B` (Slate 500) | Line numbers, subtle hints | + +### 3.2 Accent Ramp (Single Violet / Indigo System) +| Token | Hex | Role | +|-------|-----|------| +| `--accent-50` | `#EEF2FF` | Soft tinted pill background | +| `--accent-100` | `#E0E7FF` | Hover states on ghost buttons | +| `--accent-200` | `#C7D2FE` | Tinted borders & badges | +| `--accent-400` | `#818CF8` | Dark mode highlights | +| `--accent-500` | `#6366F1` | Gradient start point | +| `--accent-600` | `#4F46E5` | Active accents, gradient midpoint | +| `--accent-700` | `#4338CA` | Gradient endpoint, hover primary | + +### 3.3 Semantic Accents +- **Success**: Running status `#16A34A` (dot) on `rgba(22, 163, 74, 0.10)` +- **Idle / Info**: Idle status `#6366F1` (dot) on `rgba(99, 102, 241, 0.10)` + +--- + +## 4. Radii Scale + +| Token | Value | Applied To | +|-------|-------|------------| +| `--radius-sm` | `10px` | Small buttons, status badges, copy button | +| `--radius-md` | `14px` | Metric cards, table wrappers, tabs | +| `--radius-lg` | `20px` | Primary outer demo panels | +| `--radius-xl` | `28px` | Floating top bar pill | +| `--radius-full`| `9999px` | Segmented control active pill, avatars, dots | + +--- + +## 5. Shadow Elevation (Two-Layer Soft System) + +No harsh, saturated drop shadows. Elevation is rendered via two-step ambient + diffuse layers: + +```css +/* Ambient: tight grounding shadow */ +/* Diffuse: wide, low-opacity atmospheric bloom */ +--shadow-frosted: 0 2px 6px -1px rgba(15, 23, 42, 0.04), 0 20px 48px -12px rgba(99, 102, 241, 0.08); +--shadow-pill: 0 1px 3px rgba(15, 23, 42, 0.06), 0 6px 16px -2px rgba(15, 23, 42, 0.04); +--shadow-hover: 0 4px 12px -2px rgba(15, 23, 42, 0.08), 0 24px 56px -12px rgba(99, 102, 241, 0.12); +``` + +--- + +## 6. Spacing & Container System + +- **Base Unit**: `4px` +- **8-Step Scale**: + - `step-1`: `4px` (`0.25rem`) + - `step-2`: `8px` (`0.5rem`) + - `step-3`: `12px` (`0.75rem`) + - `step-4`: `16px` (`1rem`) + - `step-5`: `24px` (`1.5rem`) + - `step-6`: `32px` (`2rem`) + - `step-7`: `48px` (`3rem`) + - `step-8`: `64px` (`4rem`) +- **Content Container**: `max-w-[1200px] mx-auto w-full px-6` (centered, full-width viewport canvas, zero sidebar). +- **Above-the-Fold Constraint**: At 1440×900, both demo panels sit fully above the 900px fold. At 1280×800, both panels sit mostly above the 800px fold. + +--- + +## 7. Motion & Interaction + +- **Headline Entrance**: Fade and rise (`opacity: 0 -> 1`, `translateY: 12px -> 0px`) over 350ms, ease-out (`cubic-bezier(0.16, 1, 0.3, 1)`). +- **Code Lines Reveal**: Staggered reveal at ~30ms per line (`delay: index * 0.03s`). +- **Rendered Panel Resolution**: Resolves gently after code begins (~250ms delay, 400ms duration). +- **CTA Interaction**: Primary button arrow shifts `+2px` right on hover (`translate-x-0.5`). +- **Reduced Motion**: All animations wrapped in `@media (prefers-reduced-motion: reduce)` with instantaneous fallback. + diff --git a/EVALS.md b/EVALS.md new file mode 100644 index 0000000..36dca35 --- /dev/null +++ b/EVALS.md @@ -0,0 +1,221 @@ +# AppForge Generation Evaluation Harness Report + +**Evaluation Timestamp:** 2026-11-18T00:15:12Z +**Current Prompt Version:** `v1.2.1-backend` (dynamic reflection from `lib/copilot-prompt.ts`) +**Reproduction Command:** `node scripts/run-evals.mjs` +**Resumption Command (for 120b after quota reset):** `node scripts/run-evals.mjs 120b-only` + +> [!NOTE] +> **Schema & Prompt Version Notice (`v1.2.1-backend`):** `PROMPT_VERSION` is set to `v1.2.1-backend` for the interview-hardening branch. It reflects strict per-component schemas with native AST types (`Header`, `Statistic`, `DataTable`, `Card`, `Grid`, `ButtonAction`) without landing-redesign UI extensions (such as status/icon columns or gradient variants). Historical evaluation benchmarks recorded below predate this version and are not directly comparable to `v1.3.0` or `v1.4.0`. No new LLM evals have been run under `v1.2.1-backend`. + +--- + +## 1. System & Test Environment + +* **Operating System:** Windows 11 (`win32 10.0.26300 x64`) +* **Processor:** AMD Ryzen 7 6800H with Radeon Graphics (8 Cores, 16 Threads) +* **Runtime:** Node.js `v24.15.0` +* **Benchmark Suite:** 100 domain-specific prompts across 5 categories (`evals/benchmark-prompts.json`): + * Forms (`form-01` to `form-20`) + * Dashboards (`dash-01` to `dash-20`) + * CRUD Interfaces (`crud-01` to `crud-20`) + * System Settings (`sett-01` to `sett-20`) + * Analytics & Telemetry (`anal-01` to `anal-20`) +* **AST Validation Engine:** Per-component Zod validator (`lib/validation.ts`) enforcing `Header`, `Statistic`, `DataTable`, `Card`, `Grid`, and `ButtonAction` schemas with safe fallback node integration (`registry/components/InvalidNodeFallback.tsx`). + +--- + +## 2. Independent Model Evaluation Records + +> [!IMPORTANT] +> **Non-Comparative Data Notice:** The datasets below must NOT be compared side-by-side. Groq 120b was evaluated using strict per-component Zod schemas (`lib/validation.ts`), whereas Groq 20b was evaluated under an obsolete type-only string check (`commit 975e62a~1`). Because raw completions were not preserved in full, 20b cannot be back-scored. Each model's results are presented strictly as independent historical artifacts. + +### 2.1 Groq (`openai/gpt-oss-120b`) — Per-Component Zod Schema Suite +* **Validation Standard:** Strict per-component Zod schemas (`HeaderSchema`, `StatisticSchema`, `DataTableSchema`, `CardSchema`, `GridSchema`, `ButtonActionSchema`). +* **Total Prompts Attempted:** 67 (interrupted by sliding-window rate limits at `sett-07`) +* **Completed Prompts (Excluding 429 Rate Limits):** 59 prompts +* **Full Layout Pass Rate (Excluding 429s):** **81.4%** (48 pass / 59 completed) +* **Full Layout Pass Rate (Raw with 429s as Fail):** **71.6%** (48 pass / 67 attempted) +* **Node Validity Rate:** **92.8%** (141 valid / 152 total component nodes evaluated across non-429 prompts) +* **Latency (TTFT & Duration):** Marked **INVALID** per evaluation protocol (exponential retry backoff sleep inflated attempt timers). + +### 2.2 Groq (`openai/gpt-oss-20b`) — Legacy Unvalidated Run (Old Type-Only Check) +* **Validation Standard:** Legacy type-only string check (`z.object({ type: z.string() })` prior to `commit 975e62a`). +* **Total Prompts Evaluated:** 100 prompts +* **Reported Node Validity %:** **87.7% (old type-only check)** — Not evaluated against component schemas. +* **Reported Full Layout Pass %:** **68.0%** (68/100) — Historical unvalidated metric. +* **Latency Profile:** First Render p50: 1,620 ms | p95: 2,917 ms; Full Layout p50: 1,956 ms | p95: 3,341 ms; Avg Tokens: 1,749. + +### 2.3 Gemini (`gemini-2.5-flash`) — Free Tier Quota Aborted Run +* **Validation Standard:** Evaluated with default dynamic thinking budget. +* **Total Prompts Attempted:** 100 (Hard quota cut off after prompt 1; 99 rejected with 429 quota exhaustion). +* **Completed Valid Layouts:** 1 (`dash-04`: 2 valid nodes, 100% node validity, 1.0% pass rate). +* **Latency Profile:** Marked **INVALID** due to quota delays and artificial hold time. + +--- + +## 3. Exact Metric Definitions + +### Node Validity % +A generated layout produces an array of AST component nodes: `[node_1, node_2, ..., node_k]`. +Each node is evaluated individually through `validateComponentNode(node)` from `lib/validation.ts`. +A node is considered **Valid** if and only if: +1. `node` is a non-null object containing a registered `type` property in `{"Header", "Statistic", "DataTable", "Card", "Grid", "ButtonAction"}`. +2. `node` strictly satisfies its component-specific Zod schema via `schema.safeParse(node).success === true`: + * `HeaderSchema`: Requires valid string `title`, optional `subtitle`, and `size` strictly in `["sm", "md", "lg"]`. + * `StatisticSchema`: Requires numeric/string `value`, valid `label` or `title`, and optional `trend` strictly adhering to trend union schemas (`up | down | neutral` or `{ value, label, direction, sentiment }`). + * `DataTableSchema`: Requires structured `columns` (`string` or `{ key, label, type, align }`) and `data` or `rows` records. + * `ButtonActionSchema`: Requires `label` and `variant` strictly in `["default", "outline", "secondary", "ghost"]`. + * `CardSchema` / `GridSchema`: Recursively validates that all child `content`, `footer`, or `items` are themselves valid component nodes. + +$$\text{Node Validity \%} = \left(\frac{\sum \text{Valid Component Nodes}}{\sum \text{Total Evaluated Component Nodes}}\right) \times 100$$ + +> [!NOTE] +> **Refusal Node Contribution:** Prompts that result in a plain text refusal (such as `form-02` and `form-03`) emit 0 AST component nodes. They contribute exactly **0 valid nodes and 0 total nodes** to the aggregate node validity fraction. Refusals do not dilute or inflate the node validity percentage of parsed component nodes, but count strictly as failures for Full Layout Pass %. + +### Full Layout Pass % +A benchmark prompt achieves a **Full Layout Pass** if and only if all three of the following criteria are met: +1. **Valid Non-Empty Array:** The response parses into a valid JSON array containing at least one component (`Array.isArray(ast) && ast.length > 0`). +2. **100% Component Validity:** Every single component node in the array passes `validateComponentNode(node).valid === true` (0 schema violations across all nodes in the tree). +3. **Architectural Root Requirement:** The top-level layout contains at least one `Header` component (`node.type === "Header"`), satisfying the top-level page contract. + +$$\text{Full Layout Pass \%} = \left(\frac{\text{Count of Prompts Passing All 3 Layout Criteria}}{\text{Total Prompts in Benchmark Suite}}\right) \times 100$$ + +--- + +## 4. Discrepancy Analysis (120b Intermediate vs. Final Frozen Results) + +Between the intermediate chat update and the committed dataset, the reported 120b metrics adjusted from (70.1% layout pass, 1,118 ms TTFT) to (71.6% layout pass, 5,326 ms TTFT). The underlying data was never overwritten; `git log` and array diffs confirm 0 entries in the original 67-prompt record changed. The differences arose from: + +1. **Prompt 66 (`sett-06`) Completion:** + * In the intermediate turn, an uncommitted slice of 65 completed items was calculated while prompt 66 was in-flight: 47 full passes out of 65 gave `47 / 67 = 70.1%` layout pass, and `138 / 149 = 92.6%` node validity. + * When prompt 66 finished, it produced 3 valid nodes and passed full layout, bringing the final 67-prompt total to `48 / 67 = 71.6%` layout pass and `141 / 152 = 92.8%` node validity. +2. **Latency Calculation Methodology:** + * The intermediate `1,118 ms` value was an unverified manual reference taken from `form-03`'s individual TTFT (`1,117 ms`), rather than an array percentile. + * When `scripts/run-evals.mjs` ran the mathematical percentile calculation `percentile(ttfts, 0.5)` on all 57 successful responses, it produced `5,326 ms`. + * However, because the original script did not reset timing across retries, prompts that hit Groq's sliding TPM/TPD rate limits accumulated AI SDK's exponential backoff sleep into their elapsed time (e.g. `92,384 ms` on `sett-02`). As a result, the 120b latency figures are marked **INVALID** to prevent reporting distorted performance. + +--- + +## 5. Resumability Protocol & Retry Handling + +[`scripts/run-evals.mjs`](file:///d:/Projects/appforge/scripts/run-evals.mjs) now enforces strict resumability: +* **Recorded Result Protection:** Any prompt with a recorded result is immediately skipped. Prompts resulting in model refusals (such as safety refusals on `form-02` and `form-03`) are preserved as valid data points and never overwritten. +* **Targeted Rate-Limit Retries:** Only prompts explicitly flagged as `rateLimited: true` or `status: "rate_limited"` are evaluated during retry passes. +* **Separation of Latency and Backoff:** Timing starts strictly at the execution of the successful attempt (`attemptStart = performance.now()`). Time spent waiting on HTTP 429 `retry-after` windows is tracked separately in `rateLimitWaitMs`. +* **Resuming Remaining 120b Prompts:** + ```bash + node scripts/run-evals.mjs 120b-only + ``` + *(Paused: No further evals will be executed until a separate eval account is configured.)* + +--- + +## 6. Groq 120b Per-Prompt Breakdown & Refusal Investigation + +### Recomputed Metrics (Excluding Rate-Limited Prompts) +* **Total Evaluated Entries:** 67 +* **Completed (Non-Rate-Limited):** 59 prompts +* **Status Distribution:** + * **Pass:** 48 prompts + * **Fail:** 9 prompts (`form-04`, `form-05`, `form-07`, `form-09`, `form-11`, `form-12`, `form-13`, `form-15`, `sett-02`) + * **Refusal:** 2 prompts (`form-02`, `form-03`) — counted as failures + * **Rate Limited (429):** 8 prompts (`dash-18`, `crud-19`, `crud-20`, `sett-01`, `sett-03`, `sett-04`, `sett-05`, `sett-07`) — excluded from recomputation +* **Full-Layout Pass % (Excluding Rate-Limited):** + $$\text{Full Layout Pass \%} = \frac{48 \text{ passes}}{59 \text{ non-rate-limited prompts}} = 81.36\% \text{ (vs. } \frac{48}{67} = 71.64\% \text{ raw)}$$ +* **Node Validity % (Excluding Rate-Limited):** + $$\text{Node Validity \%} = \frac{141 \text{ valid nodes}}{152 \text{ evaluated nodes}} = 92.76\%$$ + *(126 valid / 126 in passes + 15 valid / 26 in fails + 0 / 0 in refusals + 0 / 0 in rate-limited)* + +### Performance Across All 5 Prompt Categories + +| Category | Suite Total | Evaluated | Completed (Non-429) | Rate-Limited (429) | Full Layout Passes | Fails / Refusals | Pass % (Completed) | Pass % (Evaluated) | Node Validity % | +| :--- | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | :---: | +| **Forms** | 20 | 20 | 20 | 0 | 10 | 10 (8 fail, 2 refusal) | **50.0%** (10/20) | **50.0%** (10/20) | **82.0%** (41/50) | +| **Dashboards** | 20 | 20 | 19 | 1 | 19 | 0 | **100.0%** (19/19) | **95.0%** (19/20) | **100.0%** (48/48) | +| **CRUD Interfaces** | 20 | 20 | 18 | 2 | 18 | 0 | **100.0%** (18/18) | **90.0%** (18/20) | **100.0%** (46/46) | +| **System Settings** | 20 | 7 | 2 | 5 | 1 | 1 | **50.0%** (1/2) | **14.3%** (1/7) | **75.0%** (6/8) | +| **Analytics & Telemetry** | 20 | 0 | 0 | 0 | 0 | 0 | *N/A (unattempted)* | *N/A (unattempted)* | *N/A* | +| **Total / Overall** | **100** | **67** | **59** | **8** | **48** | **11** | **81.4%** (48/59) | **71.6%** (48/67) | **92.8%** (141/152) | + +### Refusal Investigation (`form-02` & `form-03`) +* **Prompt `form-02`:** + * **Input:** `"Build a customer feedback and NPS survey form with rating scale and text comments"` + * **Recorded Refusal Output:** `"I’m sorry, but I can’t help with that...."` + * **Root Cause (Hypothesis, untested):** Suspected false-positive safety classifier trigger on customer feedback / PII collection within the model's system boundary. +* **Prompt `form-03`:** + * **Input:** `"Create a multi-tier SaaS checkout billing form with credit card fields and tax address"` + * **Recorded Refusal Output:** `"I’m sorry, but I can’t fulfill that request...."` + * **Root Cause (Hypothesis, untested):** Suspected trigger on PCI-DSS / financial payment data guardrails caused by the phrase `"credit card fields"`. *(Note: The 1,117 ms TTFT of this single refusal was previously mistakenly cited as the overall 120b median).* + +### Complete 67-Prompt Status Table + +| Index | Prompt ID | Category | Status | Valid Nodes | Total Nodes | Node Pass % | Full Layout Pass | +| :---: | :--- | :--- | :---: | :---: | :---: | :---: | :---: | +| 1 | `form-01` | forms | **pass** | 3 | 3 | 100.0% | true | +| 2 | `form-02` | forms | **refusal** | 0 | 0 | 0.0% | false | +| 3 | `form-03` | forms | **refusal** | 0 | 0 | 0.0% | false | +| 4 | `form-04` | forms | **fail** | 1 | 2 | 50.0% | false | +| 5 | `form-05` | forms | **fail** | 2 | 3 | 66.7% | false | +| 6 | `form-06` | forms | **pass** | 3 | 3 | 100.0% | true | +| 7 | `form-07` | forms | **fail** | 2 | 4 | 50.0% | false | +| 8 | `form-08` | forms | **pass** | 3 | 3 | 100.0% | true | +| 9 | `form-09` | forms | **fail** | 2 | 3 | 66.7% | false | +| 10 | `form-10` | forms | **pass** | 5 | 5 | 100.0% | true | +| 11 | `form-11` | forms | **fail** | 2 | 3 | 66.7% | false | +| 12 | `form-12` | forms | **fail** | 1 | 2 | 50.0% | false | +| 13 | `form-13` | forms | **fail** | 1 | 2 | 50.0% | false | +| 14 | `form-14` | forms | **pass** | 2 | 2 | 100.0% | true | +| 15 | `form-15` | forms | **fail** | 1 | 2 | 50.0% | false | +| 16 | `form-16` | forms | **pass** | 3 | 3 | 100.0% | true | +| 17 | `form-17` | forms | **pass** | 2 | 2 | 100.0% | true | +| 18 | `form-18` | forms | **pass** | 2 | 2 | 100.0% | true | +| 19 | `form-19` | forms | **pass** | 3 | 3 | 100.0% | true | +| 20 | `form-20` | forms | **pass** | 3 | 3 | 100.0% | true | +| 21 | `dash-01` | dashboards | **pass** | 3 | 3 | 100.0% | true | +| 22 | `dash-02` | dashboards | **pass** | 2 | 2 | 100.0% | true | +| 23 | `dash-03` | dashboards | **pass** | 4 | 4 | 100.0% | true | +| 24 | `dash-04` | dashboards | **pass** | 2 | 2 | 100.0% | true | +| 25 | `dash-05` | dashboards | **pass** | 3 | 3 | 100.0% | true | +| 26 | `dash-06` | dashboards | **pass** | 2 | 2 | 100.0% | true | +| 27 | `dash-07` | dashboards | **pass** | 2 | 2 | 100.0% | true | +| 28 | `dash-08` | dashboards | **pass** | 2 | 2 | 100.0% | true | +| 29 | `dash-09` | dashboards | **pass** | 3 | 3 | 100.0% | true | +| 30 | `dash-10` | dashboards | **pass** | 2 | 2 | 100.0% | true | +| 31 | `dash-11` | dashboards | **pass** | 3 | 3 | 100.0% | true | +| 32 | `dash-12` | dashboards | **pass** | 3 | 3 | 100.0% | true | +| 33 | `dash-13` | dashboards | **pass** | 2 | 2 | 100.0% | true | +| 34 | `dash-14` | dashboards | **pass** | 2 | 2 | 100.0% | true | +| 35 | `dash-15` | dashboards | **pass** | 3 | 3 | 100.0% | true | +| 36 | `dash-16` | dashboards | **pass** | 2 | 2 | 100.0% | true | +| 37 | `dash-17` | dashboards | **pass** | 3 | 3 | 100.0% | true | +| 38 | `dash-18` | dashboards | **rate_limited** | 0 | 0 | 0.0% | false | +| 39 | `dash-19` | dashboards | **pass** | 3 | 3 | 100.0% | true | +| 40 | `dash-20` | dashboards | **pass** | 2 | 2 | 100.0% | true | +| 41 | `crud-01` | crud | **pass** | 2 | 2 | 100.0% | true | +| 42 | `crud-02` | crud | **pass** | 3 | 3 | 100.0% | true | +| 43 | `crud-03` | crud | **pass** | 3 | 3 | 100.0% | true | +| 44 | `crud-04` | crud | **pass** | 3 | 3 | 100.0% | true | +| 45 | `crud-05` | crud | **pass** | 2 | 2 | 100.0% | true | +| 46 | `crud-06` | crud | **pass** | 2 | 2 | 100.0% | true | +| 47 | `crud-07` | crud | **pass** | 3 | 3 | 100.0% | true | +| 48 | `crud-08` | crud | **pass** | 2 | 2 | 100.0% | true | +| 49 | `crud-09` | crud | **pass** | 3 | 3 | 100.0% | true | +| 50 | `crud-10` | crud | **pass** | 3 | 3 | 100.0% | true | +| 51 | `crud-11` | crud | **pass** | 3 | 3 | 100.0% | true | +| 52 | `crud-12` | crud | **pass** | 3 | 3 | 100.0% | true | +| 53 | `crud-13` | crud | **pass** | 2 | 2 | 100.0% | true | +| 54 | `crud-14` | crud | **pass** | 3 | 3 | 100.0% | true | +| 55 | `crud-15` | crud | **pass** | 2 | 2 | 100.0% | true | +| 56 | `crud-16` | crud | **pass** | 2 | 2 | 100.0% | true | +| 57 | `crud-17` | crud | **pass** | 3 | 3 | 100.0% | true | +| 58 | `crud-18` | crud | **pass** | 2 | 2 | 100.0% | true | +| 59 | `crud-19` | crud | **rate_limited** | 0 | 0 | 0.0% | false | +| 60 | `crud-20` | crud | **rate_limited** | 0 | 0 | 0.0% | false | +| 61 | `sett-01` | settings | **rate_limited** | 0 | 0 | 0.0% | false | +| 62 | `sett-02` | settings | **fail** | 3 | 5 | 60.0% | false | +| 63 | `sett-03` | settings | **rate_limited** | 0 | 0 | 0.0% | false | +| 64 | `sett-04` | settings | **rate_limited** | 0 | 0 | 0.0% | false | +| 65 | `sett-05` | settings | **rate_limited** | 0 | 0 | 0.0% | false | +| 66 | `sett-06` | settings | **pass** | 3 | 3 | 100.0% | true | +| 67 | `sett-07` | settings | **rate_limited** | 0 | 0 | 0.0% | false | diff --git a/README.md b/README.md index 4c865fe..1bfcf07 100644 --- a/README.md +++ b/README.md @@ -11,7 +11,6 @@ AppForge interprets natural language prompts via large language models, compiles ![Supabase](https://img.shields.io/badge/Supabase-Database-3ECF8E) ![Clerk](https://img.shields.io/badge/Clerk-Auth-6C47FF) ![Upstash Redis](https://img.shields.io/badge/Upstash_Redis-Cache-FF3E00) -![Upstash Kafka](https://img.shields.io/badge/Upstash_Kafka-Queue-231F20) ![Groq](https://img.shields.io/badge/Groq-LPU_Inference-F36E0B) --- @@ -51,7 +50,6 @@ Traditional web applications require developers to hardcode layouts, map databas - **Prompt-to-Software Copilot:** The `CopilotPanel` routes raw user requests to an AI LLM, instantly returning a structured JSON DOM. - **Serverless Semantic Caching:** Prevents hallucination overhead and massive LLM generation latencies by instantly serving repeated prompts via Upstash Redis. - **Dynamic Postgres Sync Engine:** AppForge intercepts the generated UI AST and dynamically executes runtime DDL (`CREATE TABLE/ALTER`) on a Supabase database instance to provision identical backend architecture on the fly. -- **Background Event Brokerage:** Every publish action instantly fires asynchronous fire-and-forget payloads into Upstash Kafka for decoupled business intelligence analytics. - **Production-grade Global Edge Routing:** Clerk auth middleware secures the entire platform across 300+ Edge nodes, dynamically locking out unauthenticated bots from modifying global states. - **Smart Quota Sandboxing:** Guests natively experience the system instantly up to a localized maximum ceiling before being seamlessly captured into the Authentication funnel. @@ -67,7 +65,7 @@ Traditional web applications require developers to hardcode layouts, map databas ## Architecture -At a high level, AppForge operates within a hybrid SSR (Server-Side Rendered) matrix leveraging the Next.js Edge runtime, Supabase Data proxies, and an Event-Driven architecture cluster. +At a high level, AppForge operates within a hybrid SSR (Server-Side Rendered) matrix leveraging the Next.js Edge runtime, Supabase Data proxies, and an Upstash semantic cache layer. ```text ┌──────────────────────┐ @@ -81,19 +79,18 @@ At a high level, AppForge operates within a hybrid SSR (Server-Side Rendered) ma │ Next.js App Router │ │ (Server Actions & API)│ │ + Clerk Middleware │ - └────┬──────┬──────┬───┘ - Event Pub │ │ Cache│ Auth / RPC - ┌────────────┘ │ └────────────┐ - ▼ ▼ ▼ -┌──────────────────┐ ┌────────────────┐ ┌───────────────────┐ -│ Upstash Kafka │ │ Upstash Redis │ │ Supabase Postgres │ -│ (Topic Streams) │ │ (Semantic Mem) │ │ (Schema + Apps) │ -└──────────────────┘ └────────┬───────┘ └───────────────────┘ - │ - ┌─────────┴────────┐ - │ LLM Providers │ - │ (Groq / Gemini) │ - └──────────────────┘ + └────┬──────────────┬──┘ + │ Cache │ Auth / RPC + ▼ ▼ + ┌────────────────┐ ┌───────────────────┐ + │ Upstash Redis │ │ Supabase Postgres │ + │ (Semantic Mem) │ │ (Schema + Apps) │ + └────────┬───────┘ └───────────────────┘ + │ + ┌─────────┴────────┐ + │ LLM Providers │ + │ (Groq / Gemini) │ + └──────────────────┘ ``` --- @@ -112,11 +109,6 @@ At a high level, AppForge operates within a hybrid SSR (Server-Side Rendered) ma - **Dependencies:** `@supabase/ssr`, `lib/insforge-server`. - **Important Implementation Details:** Uses `execute_app_ddl` via Supabase RPC to securely execute runtime data-definition languages while shielding the central registry tables from malicious DROPs or mutations. -### Analytics Decoupler (`lib/event-queue.ts`) -- **Responsibility:** Fire-and-forget payload drops triggered upon structural commits. -- **Dependencies:** `@upstash/kafka`. -- **Failure Modes:** Deliberate "Try/Catch with Empty Throw." Downstream Kafka anomalies will never break the primary HTTP transaction loop on the user facing client. - --- ## Repository Structure @@ -156,7 +148,6 @@ appforge/ | **Backend** | Next.js App Router | Edge-capable API runtime. | | **Database** | Supabase (PostgreSQL) | Stores central application JSON configurations and handles Dynamic App instances. | | **Authentication** | Clerk B2B | Provides JWT-mediated state control natively wired directly into Next.js middleware. | -| **Queue** | Upstash Kafka | Low-latency serverless event brokering for analytical webhooks. | | **Cache/RateLimit**| Upstash Redis | Hard prevents API exhaustion and speeds up identical query latencies globally. | | **Generative AI** | AI SDK Core | Standardized multi-model fallback streaming execution (Groq, Gemini). | | **Observability** | Sentry | Full cycle Next.js Error Monitoring locally and globally. | @@ -248,11 +239,7 @@ Authentication is natively enforced using **Clerk**. | `GEMINI_API_KEY_2` | Optional | `AIza...` | Tier 2 failover key ensuring zero-downtime structural capacity. | | `UPSTASH_REDIS_REST_URL` | Yes | `https://xx.upstash.io` | Connection URL for REST API Serverless KV fetching. | | `UPSTASH_REDIS_REST_TOKEN` | Yes | `AXXX...` | Security token allowing API validation to the DB cache tier. | -| `UPSTASH_KAFKA_REST_URL` | Yes | `https://xx.upstash.io` | Connection URL serving background telemetry logic. | -| `UPSTASH_KAFKA_REST_USERNAME` | Yes | `default` | Security cluster identifier verifying event payloads. | -| `UPSTASH_KAFKA_REST_PASSWORD` | Yes | `XXXX...` | Security hash authorizing push topics. | | `NEXT_PUBLIC_SENTRY_DSN` | Optional | `https://xx@sentry.io/xx`| Application telemetry monitoring pipeline sink configurations | -| `ADMIN_BYPASS_KEY` | Optional | `super_secret_string` | Testing parameter to circumnavigate explicit production server checks. | *(All secrets are kept secure within `.env.local` locally and mapped securely out into the Vercel variables GUI in prod.)* @@ -363,6 +350,7 @@ The enterprise pipeline heavily restricts branches. It is comprised strictly of --- ## Known Limitations / TODO +- **Security & Database Access Model**: Server-only DB access with app-level ownership checks; RLS blocks anonymous key access only. Native Clerk Third-Party Auth (JWKS token validation) is not configured in Supabase PostgREST. All database queries and mutations from authenticated users execute server-side in Next.js Server Actions and Route Handlers using the Supabase Service Role key (`SUPABASE_SERVICE_ROLE_KEY`), with tenant isolation verified by Clerk `auth()` (`eq('user_id', userId)`). Postgres Row-Level Security (RLS) is active strictly to block anonymous key access (`anon`), restricting public reads solely to published applications (`published_config IS NOT NULL`). Direct authenticated PostgREST calls with Clerk JWTs return `PGRST301` without Supabase Dashboard JWKS configuration. - **TODO / Verify (React Testing Layer):** There is currently no active e2e testing interface. Adding `Playwright` to strictly verify DOM layout alignment output from generic JSON structures would guarantee a vastly more secure build layer. - **TODO / Verify:** AI Provider Failover Logic is extremely simplistic. Migrating to a complex load-balancer tracking API quota exhaustions heavily per key natively rather than sequential cascading fallbacks. - **Functional Limitation (Publishing):** Guests cannot natively host simulated domains in full isolation. They require immediate `auth.protect()` transitions. diff --git a/actions/apps.ts b/actions/apps.ts index 778f6ac..31b8b26 100644 --- a/actions/apps.ts +++ b/actions/apps.ts @@ -3,46 +3,134 @@ import { createInsforgeServer } from "@/lib/insforge-server"; import { redirect } from "next/navigation"; import { auth } from "@clerk/nextjs/server"; -import { cookies } from "next/headers"; -import { EventPublisher } from "@/lib/event-queue"; +import { syncAppSchema } from "@/actions/schema"; +import { normalizeConfigFieldNames } from "@/lib/config-normalizer"; +import { isSandboxAppId } from "@/lib/sandbox"; /** - * Checks Clerk for a real user session. - * If none exists, checks for a secure ADMIN bypass cookie. + * Resolves the authenticated user ID. + * The development bypass is strictly opt-in via DEV_AUTH_BYPASS=true and is hard-blocked in production. */ +function isDevAuthBypassEnabled(): boolean { + return process.env.NODE_ENV !== "production" && process.env.DEV_AUTH_BYPASS === "true"; +} + async function getAuthOrBypass() { + if (isDevAuthBypassEnabled()) { + return { userId: "dev-bypass-user", isBypass: true }; + } + const { userId } = await auth(); if (userId) return { userId, isBypass: false }; - const cookieStore = await cookies(); - const adminCookie = cookieStore.get("APPFORGE_ADMIN_BYPASS")?.value; - if (adminCookie && process.env.ADMIN_BYPASS_KEY && adminCookie === process.env.ADMIN_BYPASS_KEY) { - return { userId: "admin-bypass-user", isBypass: true }; - } - - if (process.env.NODE_ENV === "development") { - return { userId: "dev-bypass-user", isBypass: true }; - } - return { userId: null, isBypass: false }; } export async function getUserApps() { - const supabase = await createInsforgeServer(); const { userId, isBypass } = await getAuthOrBypass(); if (isBypass) { return [ - { id: "mock-1", name: "Internal CRM (Admin Mock)", updated_at: new Date().toISOString(), status: "Published" }, - { id: "mock-2", name: "Inventory Tracker (Admin Mock)", updated_at: new Date(Date.now() - 3600000).toISOString(), status: "Draft" }, + { + id: "mock-1", + name: "Customer Success Portal", + updated_at: new Date(Date.now() - 3600000).toISOString(), // 1 hour ago + status: "Published", + config: { + app: "Customer Success Portal", + pages: [ + { + components: [ + { + type: "Header", + title: "Customer Success & Operations", + subtitle: "Active enterprise accounts, health scores, and critical churn alerts.", + size: "lg", + }, + { + type: "Grid", + columns: 3, + gap: 4, + items: [ + { type: "Statistic", label: "Net Retention", value: "114%", trend: "up", trendValue: "+3.2%" }, + { type: "Statistic", label: "Accounts at Risk", value: "2", trend: "down", trendValue: "-1" }, + { type: "Statistic", label: "Expansion ARR", value: "$42,800" }, + ], + }, + { + type: "DataTable", + entity: "accounts", + columns: [ + { key: "company", label: "Account Name", type: "text" }, + { key: "mrr", label: "ARR ($)", type: "number" }, + { key: "health", label: "Health", type: "badge" }, + ], + data: [ + { id: "1", company: "Acme Logistics", mrr: 18200, health: "Good" }, + { id: "2", company: "Vanguard Tech", mrr: 29500, health: "Review" }, + { id: "3", company: "Helix Biotech", mrr: 12400, health: "Good" }, + ], + }, + ], + }, + ], + }, + }, + { + id: "mock-2", + name: "Global Fleet Logistics", + updated_at: new Date(Date.now() - 86400000).toISOString(), // 1 day ago + status: "Draft", + config: { + app: "Global Fleet Logistics", + pages: [ + { + components: [ + { + type: "Header", + title: "Fleet Operations Telemetry", + subtitle: "Real-time dispatch, route schedules, and equipment alerts.", + size: "lg", + }, + { + type: "Grid", + columns: 3, + gap: 4, + items: [ + { + type: "Card", + title: "Western Depot", + subtitle: "24 vehicles online · 0 critical alerts", + footer: [{ type: "ButtonAction", label: "Inspect depot", variant: "outline" }], + }, + { + type: "Card", + title: "Eastern Corridor", + subtitle: "18 vehicles online · 1 scheduled repair", + footer: [{ type: "ButtonAction", label: "Inspect corridor", variant: "outline" }], + }, + { + type: "Card", + title: "Central Hub", + subtitle: "42 vehicles online · nominal status", + footer: [{ type: "ButtonAction", label: "Inspect hub", variant: "outline" }], + }, + ], + }, + ], + }, + ], + }, + }, ]; } if (!userId) throw new Error("Unauthorized"); + const supabase = await createInsforgeServer(); const { data, error } = await supabase .from("apps") - .select("id, name, updated_at, published_config") + .select("id, name, updated_at, published_config, config") .eq("user_id", userId) .order("updated_at", { ascending: false }); @@ -57,25 +145,29 @@ export async function getUserApps() { })); } -export async function createApp() { +export async function createApp(prompt?: string) { const supabase = await createInsforgeServer(); const { userId, isBypass } = await getAuthOrBypass(); + const querySuffix = prompt ? `?prompt=${encodeURIComponent(prompt)}` : ""; + if (isBypass) { - redirect("/builder/mock-new-id"); + redirect(`/builder/mock-new-id${querySuffix}`); } // Gracefully bounce unauthenticated 'Create New App' clicks to the sandbox if (!userId) { - redirect("/builder/template-blank"); + redirect(`/builder/template-blank${querySuffix}`); } + const appName = prompt ? prompt.trim().slice(0, 36) : "Untitled App"; + const { data, error } = await supabase .from("apps") .insert({ user_id: userId, - name: "Untitled App", - config: { app: "Untitled App", pages: [] }, + name: appName, + config: { app: appName, pages: [] }, }) .select("id") .single(); @@ -85,7 +177,7 @@ export async function createApp() { throw new Error("Failed to create app"); } - redirect(`/builder/${data.id}`); + redirect(`/builder/${data.id}${querySuffix}`); } export async function createAppFromTemplate(templateId: string) { @@ -99,7 +191,7 @@ export async function createAppFromTemplate(templateId: string) { // Determine template initial configuration // eslint-disable-next-line @typescript-eslint/no-explicit-any let initialConfig: any = { "app": `New ${templateId} App`, "pages": [] }; - + if (templateId === "directory") { initialConfig = { "app": "Employee Directory", @@ -107,14 +199,18 @@ export async function createAppFromTemplate(templateId: string) { "pages": [{ "components": [ { "type": "Header", "title": "Employee Directory", "subtitle": "Search and manage personnel globally.", "size": "lg" }, - { "type": "Grid", "columns": 3, "gap": 4, "items": [ + { + "type": "Grid", "columns": 3, "gap": 4, "items": [ { "type": "Statistic", "label": "Total Employees", "value": "142", "trend": "up", "trendValue": "+12%" }, { "type": "Statistic", "label": "Departments", "value": "8" }, { "type": "Statistic", "label": "Open Roles", "value": "24", "trend": "up", "trendValue": "+4" } - ]}, - { "type": "Card", "title": "Directory Database", "content": [ + ] + }, + { + "type": "Card", "title": "Directory Database", "content": [ { "type": "DataTable", "entity": "employees", "columns": ["name", "role", "department", "email"] } - ]} + ] + } ] }] }; @@ -125,12 +221,14 @@ export async function createAppFromTemplate(templateId: string) { "pages": [{ "components": [ { "type": "Header", "title": "Sales Analytics CRM", "subtitle": "Q3 Performance Metrics and Pipeline", "size": "lg" }, - { "type": "Grid", "columns": 4, "gap": 4, "items": [ + { + "type": "Grid", "columns": 4, "gap": 4, "items": [ { "type": "Statistic", "label": "Total Pipeline", "value": "$1.2M", "trend": "up", "trendValue": "+18%" }, { "type": "Statistic", "label": "Active Leads", "value": "84", "trend": "down", "trendValue": "-5%" }, { "type": "Statistic", "label": "Conversion Rate", "value": "12.5%", "trend": "up", "trendValue": "+2.1%" }, { "type": "Statistic", "label": "Closed Won", "value": "42 Deals" } - ]}, + ] + }, { "type": "Header", "title": "Recent Opportunities", "size": "md" }, { "type": "DataTable", "entity": "leads", "columns": ["company", "contact", "value", "status"] } ] @@ -149,17 +247,31 @@ export async function createAppFromTemplate(templateId: string) { .single(); if (error) { - console.error("[createTemplate] failed:", error); + console.error("[createAppFromTemplate] failed:", error); throw new Error("Failed to create app from template"); } + // Trigger schema synchronization for template entities so tables are provisioned immediately + if (initialConfig.entities) { + const syncRes = await syncAppSchema(data.id, initialConfig.entities, userId); + if (!syncRes.success) { + console.warn("Schema Sync Warning in createAppFromTemplate:", syncRes.message); + } + } + // Redirecting the user to the builder with a flag so the UI can seed the template redirect(`/builder/${data.id}?template=${templateId}`); } -import { syncAppSchema } from "@/actions/schema"; - export async function saveAppConfig(appId: string, configStr: string) { + if (isSandboxAppId(appId)) { + return { + success: false, + error: "Sandbox demo and template applications cannot be modified in the database.", + status: 400, + }; + } + const supabase = await createInsforgeServer(); const { userId, isBypass } = await getAuthOrBypass(); @@ -181,9 +293,9 @@ export async function saveAppConfig(appId: string, configStr: string) { if (!userId) throw new Error("Unauthorized"); - let rawConfig = {}; + let rawConfig: any = {}; try { - rawConfig = JSON.parse(configStr); + rawConfig = normalizeConfigFieldNames(JSON.parse(configStr)); } catch { return { success: false, @@ -192,11 +304,12 @@ export async function saveAppConfig(appId: string, configStr: string) { } // Save the configuration to the apps table - const { error: saveError } = await supabase + const { data: updatedRows, error: saveError } = await supabase .from("apps") .update({ config: rawConfig, updated_at: new Date().toISOString() }) .eq("id", appId) - .eq("user_id", userId); + .eq("user_id", userId) + .select("id"); if (saveError) { return { @@ -205,6 +318,14 @@ export async function saveAppConfig(appId: string, configStr: string) { }; } + if (!updatedRows || updatedRows.length === 0) { + return { + success: false, + error: "App not found or not owned by user", + status: 404, + }; + } + // Trigger schema synchronization if entities exist if ((rawConfig as Record).entities) { const syncRes = await syncAppSchema( @@ -214,7 +335,10 @@ export async function saveAppConfig(appId: string, configStr: string) { ); if (!syncRes.success) { console.warn("Schema Sync Warning:", syncRes.message); - // We purposefully do not throw an error here to prevent blocking the UI save success entirely + return { + success: false, + error: syncRes.message, + }; } } @@ -222,6 +346,14 @@ export async function saveAppConfig(appId: string, configStr: string) { } export async function publishAppConfig(appId: string, configStr: string) { + if (isSandboxAppId(appId)) { + return { + success: false, + error: "Sandbox demo and template applications cannot be published to the database.", + status: 400, + }; + } + const supabase = await createInsforgeServer(); const { userId, isBypass } = await getAuthOrBypass(); @@ -235,76 +367,118 @@ export async function publishAppConfig(appId: string, configStr: string) { if (!userId) throw new Error("Unauthorized"); - let rawConfig = {}; + let rawConfig: any = {}; try { - rawConfig = JSON.parse(configStr); + rawConfig = normalizeConfigFieldNames(JSON.parse(configStr)); } catch { return { success: false, error: "Invalid json format." }; } - const { error } = await supabase + const { data: updatedRows, error } = await supabase .from("apps") .update({ published_config: rawConfig, config: rawConfig }) .eq("id", appId) - .eq("user_id", userId); + .eq("user_id", userId) + .select("id, config"); if (error) { return { success: false, error: `Failed to publish app: ${error.message}` }; } - // Asynchronously fire a Kafka event to our decoupled queue tracking 'app_published' events. - // This operation handles its own errors silently to prevent failing the UI interaction if analytics goes down. - EventPublisher.publish("appforge-events", "app_published", { - app_id: appId, - user_id: userId, - config_size: configStr.length, - timestamp: new Date().toISOString(), - }); + if (!updatedRows || updatedRows.length === 0) { + return { + success: false, + error: "App not found or not owned by user", + status: 404, + }; + } + + // Trigger schema synchronization if entities exist (ensures tables exist if user publishes without saving first) + const targetEntities = + (rawConfig as Record).entities || + (updatedRows[0]?.config as Record)?.entities; + + if (targetEntities) { + const syncRes = await syncAppSchema(appId, targetEntities, userId); + if (!syncRes.success) { + console.warn("Schema Sync Warning in publishAppConfig:", syncRes.message); + return { + success: false, + error: syncRes.message, + }; + } + } return { success: true }; } export async function deleteApp(appId: string) { + if (isSandboxAppId(appId)) { + const err = new Error("Sandbox demo and template applications cannot be deleted."); + (err as unknown as { status: number }).status = 400; + throw err; + } + const supabase = await createInsforgeServer(); const { userId, isBypass } = await getAuthOrBypass(); if (isBypass) return { success: true }; if (!userId) throw new Error("Unauthorized"); - const { error } = await supabase + const { data: deletedRows, error } = await supabase .from("apps") .delete() .eq("id", appId) - .eq("user_id", userId); + .eq("user_id", userId) + .select("id"); if (error) { - throw new Error("Failed to delete app."); + throw new Error(`Failed to delete app: ${error.message}`); + } + + if (!deletedRows || deletedRows.length === 0) { + const err = new Error("App not found or not owned by user"); + (err as unknown as { status: number }).status = 404; + throw err; } return { success: true }; } export async function renameApp(appId: string, newName: string) { + if (isSandboxAppId(appId)) { + const err = new Error("Sandbox demo and template applications cannot be renamed."); + (err as unknown as { status: number }).status = 400; + throw err; + } + const supabase = await createInsforgeServer(); const { userId, isBypass } = await getAuthOrBypass(); if (isBypass) return { success: true }; if (!userId) throw new Error("Unauthorized"); - const { error } = await supabase + const { data: updatedRows, error } = await supabase .from("apps") .update({ name: newName }) .eq("id", appId) - .eq("user_id", userId); + .eq("user_id", userId) + .select("id"); if (error) { - throw new Error("Failed to rename app."); + throw new Error(`Failed to rename app: ${error.message}`); + } + + if (!updatedRows || updatedRows.length === 0) { + const err = new Error("App not found or not owned by user"); + (err as unknown as { status: number }).status = 404; + throw err; } return { success: true }; } export async function getAppConfig(appId: string) { - if (appId.startsWith("template-") || appId.startsWith("mock-")) return null; - + if (isSandboxAppId(appId)) return null; + const supabase = await createInsforgeServer(); const { userId, isBypass } = await getAuthOrBypass(); diff --git a/actions/schema.ts b/actions/schema.ts index 1b602bc..2385543 100644 --- a/actions/schema.ts +++ b/actions/schema.ts @@ -1,62 +1,152 @@ "use server"; -//acts as a parser for the app config and generates the ddl commands for the app +// Acts as a parser for the app config and generates DDL commands for the app import { createInsforgeServer } from "@/lib/insforge-server"; +import { authorizeAppAccess } from "@/lib/app-access"; +import { isSandboxAppId } from "@/lib/sandbox"; + +// Whitelist of valid PostgreSQL column types for runtime entities +const COLUMN_TYPE_WHITELIST: Record = { + string: "TEXT", + text: "TEXT", + number: "NUMERIC", + numeric: "NUMERIC", + boolean: "BOOLEAN", + date: "TIMESTAMPTZ", + timestamptz: "TIMESTAMPTZ", +}; + +// Postgres limit 63 - 41 prefix chars ("app__") = 22 max entity chars +const ENTITY_MAX_LENGTH = 22; +const COLUMN_MAX_LENGTH = 63; +const ENTITY_IDENTIFIER_RE = /^[a-zA-Z0-9_]{1,22}$/; +const COLUMN_IDENTIFIER_RE = /^[a-zA-Z0-9_]{1,63}$/; export async function syncAppSchema(appId: string, entities: unknown, userId: string | null) { + if (isSandboxAppId(appId)) { + return { + success: false, + message: "Sandbox demo and template schemas cannot be synchronized to the database.", + }; + } + const supabase = await createInsforgeServer(); // If there's no Clerk userId (e.g. guest mode) if (!userId) { - // DEV BYPASS FALLBACK ( for dev mode only) - if (process.env.NODE_ENV === "development") { + // Explicit opt-in dev bypass (never active in production) + if (process.env.NODE_ENV !== "production" && process.env.DEV_AUTH_BYPASS === "true") { console.log("[DEV BYPASS] Mocking Schema Extraction for:", appId); return { success: true, message: "Mock schema generated successfully." }; } return { success: false, message: "Unauthorized" }; } + if (!entities || typeof entities !== "object") { return { success: false, message: "No entities defined in config." }; } - const cleanAppId = appId.replace(/-/g, '_'); - const ddlCommands = []; - for (const [entityName, fields] of Object.entries(entities)) { + // Enforce 22-char entity name length limit to prevent silent truncation & collision + if (entityName.length > ENTITY_MAX_LENGTH) { + return { + success: false, + message: `Entity name "${entityName}" exceeds maximum length of ${ENTITY_MAX_LENGTH} characters.`, + }; + } + // Sanitize entity name const validEntityName = entityName.replace(/[^a-zA-Z0-9_]/g, '').toLowerCase(); - if (!validEntityName) continue; - - const tableName = `app_${cleanAppId}_${validEntityName}`; - - // Default columns - const columns = [ - `id UUID PRIMARY KEY DEFAULT gen_random_uuid()`, - `created_at TIMESTAMPTZ DEFAULT NOW()` - ]; - - // Map JSON types to Postgres types - for (const [fieldName, fieldType] of Object.entries(fields as Record)) { - const validFieldName = fieldName.replace(/[^a-zA-Z0-9_]/g, '').toLowerCase(); - if (!validFieldName || validFieldName === 'id' || validFieldName === 'created_at') continue; - - let pgType = "TEXT"; - if (fieldType === "number") pgType = "NUMERIC"; - if (fieldType === "boolean") pgType = "BOOLEAN"; - if (fieldType === "date") pgType = "TIMESTAMPTZ"; - - columns.push(`${validFieldName} ${pgType}`); + if (!validEntityName || !ENTITY_IDENTIFIER_RE.test(validEntityName)) { + return { + success: false, + message: `Invalid entity name "${entityName}". Must be alphanumeric/underscore only.`, + }; } - const ddl = `CREATE TABLE IF NOT EXISTS ${tableName} (${columns.join(', ')});`; - ddlCommands.push(ddl); - } + // Verify ownership and write authorization before executing structural DDL. + // skipEntityCheck is explicitly used here because the entity table is about to be created/synced. + const authResult = await authorizeAppAccess(appId, validEntityName, "write", { skipEntityCheck: true }); + if (authResult.error) { + const status = authResult.error.status; + return { + success: false, + message: status === 401 ? "Unauthorized" : "App not found or not owned by user", + }; + } + + // Process fields with strict identifier validation and type whitelisting + const sanitizedFields: Record = {}; + const seenColNames = new Map(); + + if (fields && typeof fields === "object") { + for (const [fieldName, rawType] of Object.entries(fields as Record)) { + if (fieldName.length > COLUMN_MAX_LENGTH) { + return { + success: false, + message: `Column name "${fieldName}" exceeds maximum length of ${COLUMN_MAX_LENGTH} characters.`, + }; + } + + const cleanFieldName = String(fieldName).replace(/[^a-zA-Z0-9_]/g, '').toLowerCase(); + if (!cleanFieldName || !COLUMN_IDENTIFIER_RE.test(cleanFieldName)) { + return { + success: false, + message: `Invalid column name "${fieldName}". Must be alphanumeric/underscore only.`, + }; + } + if (cleanFieldName === 'id' || cleanFieldName === 'created_at') continue; + + // Check for duplicate column collisions (e.g. firstName and first_name) + const prevField = seenColNames.get(cleanFieldName); + if (prevField && prevField !== fieldName) { + return { + success: false, + message: `Duplicate column collision: "${fieldName}" and "${prevField}" collapse to the same column "${cleanFieldName}".`, + }; + } + seenColNames.set(cleanFieldName, fieldName); + + const stringType = typeof rawType === "string" ? rawType.toLowerCase() : ""; + const pgType = COLUMN_TYPE_WHITELIST[stringType]; + if (!pgType) { + return { + success: false, + message: `Invalid or unknown type "${rawType}" for field "${fieldName}". Allowed types are string, number, boolean, date.`, + }; + } + + sanitizedFields[cleanFieldName] = pgType; + } + } + + // Execute structured RPC call: execute_app_ddl(app_id, entity_name, fields) + // No raw query string, no string concatenation, no string blacklists + const { error: ddlError } = await supabase.rpc('execute_app_ddl', { + app_id: appId, + entity_name: validEntityName, + fields: sanitizedFields, + }); + + if (ddlError) { + console.error("[syncAppSchema] Failed DDL execution:", ddlError); + return { success: false, message: ddlError.message }; + } + + // Upsert a row in app_schemas after successful DDL using consistent validEntityName + const { error: upsertError } = await supabase + .from("app_schemas") + .upsert( + { + app_id: appId, + table_name: validEntityName, + schema_definition: sanitizedFields, + }, + { onConflict: "app_id,table_name" } + ); - // Execute each generated DDL statement using our custom RPC function - for (const query of ddlCommands) { - const { error } = await supabase.rpc('execute_app_ddl', { app_id: appId, query }); - if (error) { - console.error("[syncAppSchema] Failed DDL execution:", error); - return { success: false, message: `Failed to create tables: ${error.message}` }; + if (upsertError) { + console.error("[syncAppSchema] Failed to upsert app_schemas:", upsertError); + return { success: false, message: `Failed to record schema definition: ${upsertError.message}` }; } } diff --git a/app/api/copilot/route.ts b/app/api/copilot/route.ts index 3a39e51..601f5b5 100644 --- a/app/api/copilot/route.ts +++ b/app/api/copilot/route.ts @@ -1,46 +1,76 @@ import { NextResponse } from "next/server"; +import { auth } from "@clerk/nextjs/server"; -export const runtime = "edge"; export const dynamic = "force-dynamic"; export const maxDuration = 60; -import { rateLimit } from "@/lib/rate-limit"; -import { streamText } from "ai"; -import { groq } from "@ai-sdk/groq"; + +import { rateLimit, checkGuestCopilotLimit, resolveClientIp } from "@/lib/rate-limit"; +import { createGroq } from "@ai-sdk/groq"; import { createGoogleGenerativeAI } from "@ai-sdk/google"; import { Redis } from "@upstash/redis"; - -const redisClient = (process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN) - ? new Redis({ url: process.env.UPSTASH_REDIS_REST_URL, token: process.env.UPSTASH_REDIS_REST_TOKEN }) +import { normalizePromptForCache } from "@/lib/validation"; +import { createCopilotStream, CopilotProvider } from "@/lib/copilot-pipeline"; +import { COPILOT_SYSTEM_PROMPT } from "@/lib/copilot-prompt"; + +const redisClient = + process.env.UPSTASH_REDIS_REST_URL && process.env.UPSTASH_REDIS_REST_TOKEN + ? new Redis({ + url: process.env.UPSTASH_REDIS_REST_URL, + token: process.env.UPSTASH_REDIS_REST_TOKEN, + }) : null; -const SYSTEM_PROMPT = `Return ONLY a valid JSON array matching this schema structure. No markdown wrappers. -Types: -- Header: {type:"Header",title:string,subtitle?:string,size?:"sm"|"md"|"lg"} -- ButtonAction: {type:"ButtonAction",label:string,variant?:"default"|"outline"|"secondary"|"ghost",icon?:"arrow-right"|"save"|"play"|"plus"|"search"} -- Card: {type:"Card",title:string,subtitle?:string,content:any[],footer?:any[]} -- Grid: {type:"Grid",columns?:1|2|3|4,gap?:number,items:any[]} -- Statistic: {type:"Statistic",label:string,value:string,trend?:"up"|"down"|"neutral",trendValue?:string} -- DataTable: {type:"DataTable",columns:string[],data:Record[]} -Rules: Compose recursively. Omit markdown backticks.`; - export async function POST(req: Request) { try { - // 1. Resolve Client Origin - const ip = req.headers.get("x-forwarded-for") ?? "127.0.0.1"; - - // 2. Validate against sliding window threshold (10 req / 10s) - const { success, limit, remaining, reset } = await rateLimit.limit(ip); - + // 1. Resolve Client Origin strictly via x-real-ip only. If absent, map to shared "unknown" bucket. + // Never trust client-controlled headers like x-forwarded-for or cf-connecting-ip. + const clientIp = resolveClientIp(req); + + // 2. Resolve Authenticated User + let userId: string | null = null; + try { + const authRes = await auth(); + userId = authRes?.userId ?? null; + } catch { + userId = null; + } + + // 3. For logged-out users, enforce per-IP limit + global daily cap to prevent LLM quota draining + if (!userId) { + const guestCheck = await checkGuestCopilotLimit(clientIp); + if (!guestCheck.success) { + return NextResponse.json( + { + error: "Please sign in to keep generating with Copilot.", + code: "AUTH_REQUIRED", + reason: guestCheck.reason, + }, + { + status: 429, + headers: { + "X-RateLimit-Limit": guestCheck.limit.toString(), + "X-RateLimit-Remaining": guestCheck.remaining.toString(), + "X-RateLimit-Reset": guestCheck.reset.toString(), + }, + } + ); + } + } + + // 4. Validate against sliding window threshold (per user or per IP) + const rateLimitKey = userId ? `user:${userId}` : `guest_ip:${clientIp}`; + const { success, limit, remaining, reset } = await rateLimit.limit(rateLimitKey); + if (!success) { return NextResponse.json( { error: "Too many AI generation requests. Please slow down and try again shortly." }, - { + { status: 429, headers: { "X-RateLimit-Limit": limit.toString(), "X-RateLimit-Remaining": remaining.toString(), - "X-RateLimit-Reset": reset.toString() - } + "X-RateLimit-Reset": reset.toString(), + }, } ); } @@ -52,125 +82,90 @@ export async function POST(req: Request) { return NextResponse.json({ error: "Missing prompt" }, { status: 400 }); } - // --- Enterprise Upstash Cache Lookup --- + // --- Normalized Upstash Cache Lookup --- + const normalizedKey = `copilot_cache:${normalizePromptForCache(prompt)}`; + if (redisClient) { - const cacheKey = `copilot_cache:${prompt.trim().toLowerCase()}`; try { - const cachedResponse = await redisClient.get(cacheKey); + const cachedResponse = await redisClient.get(normalizedKey); if (cachedResponse) { - console.log(`[Copilot Cache] HIT for prompt: "${prompt}"`); + console.log(`[Copilot Cache] HIT for normalized prompt: "${normalizedKey}"`); const stream = new ReadableStream({ start(controller) { - const textOutput = typeof cachedResponse === "string" ? cachedResponse : JSON.stringify(cachedResponse); + const textOutput = + typeof cachedResponse === "string" + ? cachedResponse + : JSON.stringify(cachedResponse); controller.enqueue(new TextEncoder().encode(textOutput)); controller.close(); - } + }, + }); + return new Response(stream, { + headers: { "Content-Type": "text/plain; charset=utf-8" }, }); - return new Response(stream, { headers: { "Content-Type": "text/plain; charset=utf-8" } }); } } catch (err) { console.error("[Copilot Cache Error] Failed to read from Redis:", err); } } - // 4. Initialize Multi-Provider Fallback (Groq Primary -> Gemini Backups) + // 4. Build Provider List: Groq as Primary, Gemini as Fallback + const providers: CopilotProvider[] = []; + + // Primary: Groq LPU + const rawGroqKey = process.env.GROQ_API_KEY || ""; + const cleanGroqKey = rawGroqKey.trim().replace(/^["']|["']$/g, ""); + if (cleanGroqKey) { + const groqProvider = createGroq({ apiKey: cleanGroqKey }); + const groqModelName = process.env.GROQ_MODEL || "openai/gpt-oss-120b"; + providers.push({ + name: `Groq (${groqModelName})`, + model: groqProvider(groqModelName), + }); + } + + // Fallback: Gemini Providers const geminiKeys = [ process.env.GEMINI_API_KEY, process.env.GEMINI_API_KEY_2, process.env.GEMINI_API_KEY_3, - ].filter(Boolean) as string[]; - - const models: import("ai").LanguageModel[] = []; - - // Attempt Groq first if key exists (Lightning Fast Free Tier) - if (process.env.GROQ_API_KEY) { - models.push(groq("llama-3.3-70b-versatile")); - } - - // Append Gemini backups by explicitly building the provider with specific keys - for (const key of geminiKeys) { - const googleProvider = createGoogleGenerativeAI({ apiKey: key }); - models.push(googleProvider("gemini-2.5-flash")); + ] + .map((k) => (k || "").trim().replace(/^["']|["']$/g, "")) + .filter(Boolean); + + for (let i = 0; i < geminiKeys.length; i++) { + const googleProvider = createGoogleGenerativeAI({ apiKey: geminiKeys[i] }); + providers.push({ + name: `Gemini (gemini-2.5-flash key ${i + 1})`, + model: googleProvider("gemini-2.5-flash"), + }); } - if (models.length === 0) { + if (providers.length === 0) { return NextResponse.json({ error: "No AI API Keys are configured." }, { status: 500 }); } - // 5. Custom stream multiplexer for Native Failover - const streamFallback = new ReadableStream({ - async start(controller) { - let lastError = null; - - for (const activeModel of models) { - try { - const responseResult = streamText({ - model: activeModel, - system: SYSTEM_PROMPT, - prompt: prompt, - temperature: 0.1, - }); - - // Extract the raw byte stream returned by the AI SDK - const reader = responseResult.toTextStreamResponse().body?.getReader(); - if (!reader) { - lastError = new Error("Failed to extract reader from stream."); - continue; - } - - // Await the first stream chunk! - // Vercel AI SDK throws underlying API HTTP errors here (like 429 Quota Exceeded) - const firstChunk = await reader.read(); - if (firstChunk.done) { - lastError = new Error("Stream closed instantly with no data."); - continue; - } - - // Connection is alive and generating data. Forward the first chunk! - controller.enqueue(firstChunk.value); - - let streamTextAccumulator = ""; - const decoder = new TextDecoder("utf-8"); - streamTextAccumulator += decoder.decode(firstChunk.value, { stream: true }); - - // Forward the rest of the stream transparently - while (true) { - const { done, value } = await reader.read(); - if (done) break; - - controller.enqueue(value); - streamTextAccumulator += decoder.decode(value, { stream: true }); - } - - // Optionally push the finalized AST to the Redis cache - if (redisClient && streamTextAccumulator.trim()) { - const cacheKey = `copilot_cache:${prompt.trim().toLowerCase()}`; - await redisClient.set(cacheKey, streamTextAccumulator, { ex: 604800 }).catch(console.error); - } - - controller.close(); - return; // Successfully streamed! Break out of the fallback loop forever - - } catch (err) { - console.warn(`[Copilot Failover] Model failed, actively shifting to backup...`, (err as Error).message); - lastError = err; - continue; // Move to next model - } + // 5. Execute Multi-Provider Pipeline (Groq Primary -> Gemini Fallback; Failover ONLY before first chunk) + const stream = createCopilotStream({ + prompt, + providers, + systemPrompt: COPILOT_SYSTEM_PROMPT, + temperature: 0.1, + onCacheSet: async (key, val) => { + if (redisClient) { + // 7-day TTL (604,800 seconds) + await redisClient.set(key, val, { ex: 604800 }).catch(console.error); } - - // If all configured activeModels failed - controller.error(lastError || new Error("All backup AI models failed on this payload.")); - } + }, }); - return new Response(streamFallback, { + return new Response(stream, { status: 200, - headers: { + headers: { "Content-Type": "text/plain; charset=utf-8", - "Cache-Control": "no-cache" + "Cache-Control": "no-cache", }, }); - } catch (error: unknown) { console.error("[Copilot API Error]", error); return NextResponse.json({ error: (error as Error).message }, { status: 500 }); diff --git a/app/api/health/route.ts b/app/api/health/route.ts index 0f1c0ed..42114fa 100644 --- a/app/api/health/route.ts +++ b/app/api/health/route.ts @@ -1,15 +1,24 @@ -import { createInsforgeServer } from "@/lib/insforge-server"; import { NextResponse } from "next/server"; export const dynamic = "force-dynamic"; -// Status-only database check used by the keep-alive workflow. -// Returns no row data. +// Status-only database and backend check used by keep-alive workflows. +// Verifies Supabase platform reachability using the anon public key +// without depending on any application data tables (apps, app_schemas, dynamic tables). export async function GET() { try { - const supabase = await createInsforgeServer(); - const { error } = await supabase.from("apps").select("id").limit(1); - if (error) { + const supabaseUrl = process.env.NEXT_PUBLIC_INSFORGE_URL; + const anonKey = process.env.NEXT_PUBLIC_INSFORGE_ANON_KEY; + if (!supabaseUrl || !anonKey) { + return NextResponse.json({ ok: false, error: "Missing config" }, { status: 503 }); + } + + const res = await fetch(`${supabaseUrl}/auth/v1/health`, { + headers: { apikey: anonKey }, + signal: AbortSignal.timeout(5000), + }); + + if (!res.ok) { return NextResponse.json({ ok: false }, { status: 503 }); } return NextResponse.json({ ok: true }); diff --git a/app/api/proxy/[appId]/[entity]/route.ts b/app/api/proxy/[appId]/[entity]/route.ts index c1f8e1c..5ca1b6d 100644 --- a/app/api/proxy/[appId]/[entity]/route.ts +++ b/app/api/proxy/[appId]/[entity]/route.ts @@ -1,40 +1,184 @@ import { createInsforgeServer } from "@/lib/insforge-server"; +import { authorizeAppAccess } from "@/lib/app-access"; +import { normalizePayload, getClientIp } from "@/lib/proxy-helpers"; import { NextResponse } from "next/server"; -export async function GET(request: Request, { params }: { params: Promise<{ appId: string, entity: string }> }) { +type RouteParams = { + params: Promise<{ appId: string; entity: string }>; +}; + +export async function GET(request: Request, { params }: RouteParams) { const { appId, entity } = await params; + + const authResult = await authorizeAppAccess(appId, entity, "read", { + clientIp: getClientIp(request), + }); + if (authResult.error) return authResult.error; + + const { tableName, schemaDefinition } = authResult; const supabase = await createInsforgeServer(); - - const cleanAppId = appId.replace(/-/g, '_'); - const validEntityName = entity.replace(/[^a-zA-Z0-9_]/g, '').toLowerCase(); - const tableName = `app_${cleanAppId}_${validEntityName}`; - if (process.env.NODE_ENV === "development") { - // DEV BYPASS FALLBACK - return NextResponse.json([{ id: "mock-record-1", name: "Mock Row", _table: tableName }]); + const url = new URL(request.url); + const limit = Math.min(Math.max(1, parseInt(url.searchParams.get("limit") || "100", 10)), 1000); + const rawOrderBy = url.searchParams.get("order") || "created_at"; + const orderBy = rawOrderBy.replace(/[^a-zA-Z0-9_]/g, "").toLowerCase() || "created_at"; + const ascending = url.searchParams.get("ascending") === "true"; + + // Validate order column against schema definition to prevent database errors + if (orderBy !== "created_at" && orderBy !== "id") { + const allowedColumns = new Set(["id", "created_at"]); + if (schemaDefinition && typeof schemaDefinition === "object") { + for (const field of Object.keys(schemaDefinition)) { + const clean = field.replace(/[^a-zA-Z0-9_]/g, "").toLowerCase(); + if (clean) allowedColumns.add(clean); + } + } + if (!allowedColumns.has(orderBy)) { + return NextResponse.json( + { error: `Order field '${rawOrderBy}' does not exist in schema for entity '${entity}'` }, + { status: 400 } + ); + } } - const { data, error } = await supabase.from(tableName).select("*"); - if (error) return NextResponse.json({ error: error.message }, { status: 400 }); + const { data, error } = await supabase + .from(tableName) + .select("*") + .order(orderBy, { ascending }) + .limit(limit); + + if (error) { + // If entity is registered in app_schemas but physical table does not exist in Postgres + if ( + error.code === "42P01" || + error.code === "PGRST205" || + error.message?.includes("does not exist") || + error.message?.includes("schema cache") + ) { + return NextResponse.json( + { error: `Entity table '${entity}' is registered in schema but physical table does not exist` }, + { status: 503 } + ); + } + return NextResponse.json({ error: error.message }, { status: 400 }); + } return NextResponse.json(data); } -export async function POST(request: Request, { params }: { params: Promise<{ appId: string, entity: string }> }) { +export async function POST(request: Request, { params }: RouteParams) { const { appId, entity } = await params; - const body = await request.json(); - const supabase = await createInsforgeServer(); - - const cleanAppId = appId.replace(/-/g, '_'); - const validEntityName = entity.replace(/[^a-zA-Z0-9_]/g, '').toLowerCase(); - const tableName = `app_${cleanAppId}_${validEntityName}`; - if (process.env.NODE_ENV === "development") { - return NextResponse.json({ id: "mock-record-2", ...body, _table: tableName }, { status: 201 }); + const authResult = await authorizeAppAccess(appId, entity, "write"); + if (authResult.error) return authResult.error; + + const { tableName, schemaDefinition } = authResult; + let body: unknown; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const normResult = normalizePayload(body, schemaDefinition, entity, "insert"); + if (!normResult.success) { + return NextResponse.json({ error: normResult.error }, { status: 400 }); } - const { data, error } = await supabase.from(tableName).insert(body).select().single(); - if (error) return NextResponse.json({ error: error.message }, { status: 400 }); + const supabase = await createInsforgeServer(); + const { data, error } = await supabase.from(tableName).insert(normResult.data).select().single(); + + if (error) { + return NextResponse.json({ error: error.message }, { status: 400 }); + } return NextResponse.json(data, { status: 201 }); } + +export async function PUT(request: Request, { params }: RouteParams) { + const { appId, entity } = await params; + + const authResult = await authorizeAppAccess(appId, entity, "write"); + if (authResult.error) return authResult.error; + + const { tableName, schemaDefinition } = authResult; + let body: unknown; + try { + body = await request.json(); + } catch { + return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 }); + } + + const normResult = normalizePayload(body, schemaDefinition, entity, "update"); + if (!normResult.success) { + return NextResponse.json({ error: normResult.error }, { status: 400 }); + } + + const normalizedBody = (Array.isArray(normResult.data) ? normResult.data[0] : normResult.data) || {}; + const url = new URL(request.url); + const id = url.searchParams.get("id") || (normalizedBody.id as string | undefined); + if (!id) { + return NextResponse.json({ error: "Missing record id to update" }, { status: 400 }); + } + + // Remove primary key and created_at from update payload to prevent reassigning primary key column or creation timestamp + const { id: _unusedId, created_at: _unusedCreatedAt, ...updateFields } = normalizedBody; + + const supabase = await createInsforgeServer(); + const { data, error } = await supabase + .from(tableName) + .update(updateFields) + .eq("id", id) + .select() + .single(); + + if (error) { + return NextResponse.json({ error: error.message }, { status: 400 }); + } + + return NextResponse.json(data); +} + +export async function PATCH(request: Request, { params }: RouteParams) { + return PUT(request, { params }); +} + +export async function DELETE(request: Request, { params }: RouteParams) { + const { appId, entity } = await params; + + const authResult = await authorizeAppAccess(appId, entity, "write"); + if (authResult.error) return authResult.error; + + const { tableName, schemaDefinition } = authResult; + const url = new URL(request.url); + let id = url.searchParams.get("id"); + + // Allow id to be supplied in JSON request body for DELETE + if (!id) { + try { + const body = await request.json(); + const normResult = normalizePayload(body, schemaDefinition, entity, "delete"); + if (normResult.success) { + const normBody = (Array.isArray(normResult.data) ? normResult.data[0] : normResult.data) || {}; + if (normBody.id) { + id = String(normBody.id); + } + } + } catch { + // Body is optional on DELETE + } + } + + if (!id) { + return NextResponse.json({ error: "Missing record id to delete" }, { status: 400 }); + } + + const supabase = await createInsforgeServer(); + const { error } = await supabase.from(tableName).delete().eq("id", id); + + if (error) { + return NextResponse.json({ error: error.message }, { status: 400 }); + } + + return NextResponse.json({ success: true }); +} diff --git a/app/api/sentry-test/route.ts b/app/api/sentry-test/route.ts index 98995b4..65b9544 100644 --- a/app/api/sentry-test/route.ts +++ b/app/api/sentry-test/route.ts @@ -2,6 +2,10 @@ import { NextResponse } from "next/server"; import * as Sentry from "@sentry/nextjs"; export async function GET() { + if (process.env.NODE_ENV === "production") { + return NextResponse.json({ error: "Not found" }, { status: 404 }); + } + try { throw new Error("🚀 AppForge Global Error Test [Sentry Observability Pipeline Verified]"); } catch (err) { diff --git a/app/api/webhooks/kafka/route.ts b/app/api/webhooks/kafka/route.ts deleted file mode 100644 index 198e518..0000000 --- a/app/api/webhooks/kafka/route.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { NextRequest, NextResponse } from "next/server"; - -// To protect this route, Upstash Kafka allows you to configure a custom HTTP header -// (e.g. Authorization: Bearer ) which you can verify here. -// For MVP, we simply ingest the raw stringified Kafka event payload. -export async function POST(req: NextRequest) { - try { - const rawPayload = await req.json(); - - // Upstash Kafka Webhook payloads typically have `{ message: { value: "..." } }` - // but the exact signature can vary based on your Upstash Dashboard configuration. - - console.log("[Kafka Consumer] Received Decoupled Event:", rawPayload); - - // TODO: Connect to Admin Database and update analytics based on rawPayload.type - // Example: if (rawPayload.type === 'app_published') { incrementPublishCount() } - - return NextResponse.json({ success: true, processed: true }, { status: 200 }); - } catch (error: unknown) { - console.error("[Kafka Consumer] Failed to process webhook event:", error); - return NextResponse.json({ success: false, error: (error as Error).message }, { status: 500 }); - } -} diff --git a/app/apps/[appId]/page.tsx b/app/apps/[appId]/page.tsx index 3d24d17..8a21958 100644 --- a/app/apps/[appId]/page.tsx +++ b/app/apps/[appId]/page.tsx @@ -1,19 +1,20 @@ import { createInsforgeServer } from "@/lib/insforge-server"; import { RenderNode } from "@/registry"; +import { AppRuntimeProvider } from "@/registry/context"; import { notFound } from "next/navigation"; import { Navbar } from "@/components/layout/Navbar"; import { Footer } from "@/components/layout/Footer"; +import { auth } from "@clerk/nextjs/server"; export default async function LiveAppPage({ params }: { params: Promise<{ appId: string }> }) { const { appId } = await params; - const supabase = await createInsforgeServer(); - const { data: { user } } = await supabase.auth.getUser(); + const { userId } = await auth(); // Fetch the latest published configuration directly let rawConfig: unknown = null; - if (process.env.NODE_ENV === "development" && !user) { - // DEV BYPASS: Fake published state + if (process.env.NODE_ENV !== "production" && process.env.DEV_AUTH_BYPASS === "true" && !userId) { + // DEV BYPASS: Explicit opt-in fake published state for previewing without auth rawConfig = { app: "Published App Simulation", pages: [ @@ -27,6 +28,7 @@ export default async function LiveAppPage({ params }: { params: Promise<{ appId: }; } else { // Secure Database Read + const supabase = await createInsforgeServer(); const { data: appData, error } = await supabase .from("apps") .select("published_config") @@ -44,17 +46,19 @@ export default async function LiveAppPage({ params }: { params: Promise<{ appId:
-
- +
+ Live Environment
{/* Live Execution Loop via Registry Engine */} -
- {(rawConfig as { pages?: { components: unknown[] }[] })?.pages?.[0]?.components?.map((comp: unknown, i: number) => ( - - ))} -
+ +
+ {(rawConfig as { pages?: { components: unknown[] }[] })?.pages?.[0]?.components?.map((comp: unknown, i: number) => ( + + ))} +
+