Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
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
33 changes: 33 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
name: CI

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]

jobs:
build-test-lint:
runs-on: ubuntu-latest

steps:
- name: Checkout repository
uses: actions/checkout@v4

- name: Setup Node.js 20
uses: actions/setup-node@v4
with:
node-version: '20'
cache: 'npm'

- name: Install dependencies
run: npm ci

- name: Run ESLint
run: npm run lint

- name: Run Tests
run: npm run test

- name: Build Next.js
run: npm run build
12 changes: 12 additions & 0 deletions DECISIONS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# Engineering Decisions & Trade-offs

This document outlines key architectural and engineering decisions made in this project. It is intended to provide transparent insight into the technical trade-offs, security considerations, and known limitations of the current implementation.

## 1. Atomic Database RPCs for Voting
Instead of computing vote counts on the client or in the Next.js API layer (e.g., reading the count, incrementing by 1, and saving), voting is handled via a dedicated Postgres RPC (`handle_vote`). This ensures that inserting a vote record and updating the aggregate `votes_count` on the `tools` table happens in a single, atomic database transaction. By pairing this with a `UNIQUE(user_id, tool_id)` constraint on the `user_votes` table, we completely eliminate race conditions where simultaneous users voting on the same tool could overwrite each other's increments, ensuring exact vote accuracy at high concurrency.

## 2. Hybrid Authorization (RLS + App-Layer Checks)
We rely on Supabase Row Level Security (RLS) as our primary security boundary for direct client-to-database requests, cleanly restricting what data users can view or modify. However, certain server-side administrative workflows (like approving or rejecting tools) require executing complex multi-table mutations using the Supabase Service Role key, which intentionally bypasses all RLS policies. To secure these routes, we explicitly layer an app-side `verifyAdmin()` check before executing the queries, guaranteeing that even when RLS is bypassed for operational necessity, strict role-based access control is still enforced at the API boundary.

## 3. Known Limitation: ILIKE Search Implementation
Our current search functionality includes a fallback implementation that utilizes Postgres `ILIKE` with leading and trailing wildcards (e.g., `name.ilike.%query%`). Because leading wildcards prevent the database from utilizing standard B-tree indexes, Postgres is forced to perform a full table scan across the `name`, `description`, and `category` text fields for every search query. While this performs acceptably for a catalog of a few hundred tools, at 10x scale (e.g., 10,000+ records) this will cause significant CPU spikes and slow response times. Scaling this properly will require replacing `ILIKE` with Postgres Full-Text Search (using `tsvector` columns and GIN indexes) or offloading search entirely to a dedicated engine like Algolia or Elasticsearch.
20 changes: 2 additions & 18 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,28 +67,12 @@ EMAIL_FROM=AI-DEX <noreply@yourdomain.com>
### 4. Set up the database

Go to **Supabase Dashboard → SQL Editor** and run these files in order.
Each file is in the `supabase_scripts/` folder. Paste the contents and click Run.
Wait for "Success" before running the next one.

| Step | File | What it does |
|------|------|-------------|
| 1 | `supabase-schema.sql` | Creates all base tables (tools, profiles, votes) |
| 2 | `supabase-production-fixes.sql` | Adds role column, fixes user trigger |
| 3 | `migration-add-description-website-url.sql` | Adds website_url + description columns |
| 4 | `migration-add-username-support.sql` | Username handling in profiles |
| 5 | `supabase-migration-add-slug.sql` | Adds slug column for tool URLs |
| 6 | `migration-fix-tool-id-types.sql` | Ensures UUID types throughout |
| 7 | `migration-phase1-search.sql` | GIN index for full-text search |
| 8 | `supabase-migration-handle-vote.sql` | Atomic handle_vote() RPC function |
| 9 | `setup-auth-rate-limits.sql` | Rate limiting table for auth emails |
| 10 | `setup_comments.sql` | Comments table with RLS |
| 11 | `setup_tags_and_saves.sql` | Tags and bookmarks tables |
| 12 | `database-indexes.sql` | Performance indexes |
| 13 | `fix-rls-policies.sql` | Correct public read policy on tools |
| 14 | `seed-ai-tools-production.sql` | Seed data — run last |

> **Do NOT run** the files starting with `test-`, `verify-`, or `VOTING-VERIFICATION` —
> those are development utilities. Use `seed-ai-tools-production.sql` (not the other seed files).
| 1 | `supabase/migrations/0001_baseline.sql` | Creates all tables, policies, functions, and views |
| 2 | `supabase_scripts/seed-ai-tools-production.sql` | Seed data — run last |

### 5. Make yourself an admin

Expand Down
34 changes: 34 additions & 0 deletions any_table.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
| File | Line | Context | Proposed Real Type |
|---|---|---|---|
| `src/app/(dashboard)/admin/AdminDashboard.tsx` | 83 | `} catch (err: any) {` | TODO |
| `src/app/(dashboard)/admin/AdminDashboard.tsx` | 134 | `} catch (err: any) {` | TODO |
| `src/app/(dashboard)/profile/page.tsx` | 28 | `// Type assertion since Supabase returns nested joins as any by default` | TODO |
| `src/app/(dashboard)/profile/page.tsx` | 29 | `const savedTools = data ? data.map((row) => row.tools as any).filter(Boolean) : [];` | TODO |
| `src/app/(dashboard)/search/page.tsx` | 36 | `let results: any[] = [];` | TODO |
| `src/app/(dashboard)/submit/page.tsx` | 61 | `} catch (err: any) {` | TODO |
| `src/app/api/admin/tools/route.ts` | 38 | `} catch (err: any) {` | TODO |
| `src/app/api/admin/tools/route.ts` | 109 | `} catch (err: any) {` | TODO |
| `src/app/api/admin/tools/route.ts` | 121 | `let id: any;` | TODO |
| `src/app/api/admin/tools/route.ts` | 122 | `let action: any;` | TODO |
| `src/app/api/admin/tools/route.ts` | 228 | `} catch (err: any) {` | TODO |
| `src/app/api/auth/register/route.ts` | 28 | `} catch (envError: any) {` | TODO |
| `src/app/api/auth/register/route.ts` | 170 | `} catch (err: any) {` | TODO |
| `src/app/api/auth/resend/route.ts` | 123 | `} catch (err: any) {` | TODO |
| `src/app/api/tools/route.ts` | 107 | `} catch (err: any) {` | TODO |
| `src/app/api/votes/route.ts` | 77 | `} catch (err: any) {` | TODO |
| `src/components/tools/ToolCard.tsx` | 60 | `const finalIsSaved = isSaved !== undefined ? isSaved : ((tool as any).is_saved \|\| false);` | TODO |
| `src/components/tools/ToolComments.tsx` | 57 | `} catch (err: any) {` | TODO |
| `src/components/tools/ToolComments.tsx` | 105 | `} catch (err: any) {` | TODO |
| `src/components/tools/ToolComments.tsx` | 134 | `} catch (err: any) {` | TODO |
| `src/components/tools/ToolDetailModal.tsx` | 275 | `<SaveButton toolId={tool.id} initialIsSaved={(tool as any).is_saved \|\| false} />` | TODO |
| `src/components/tools/ToolDetailPanel.tsx` | 303 | `<SaveButton toolId={tool.id} initialIsSaved={(tool as any).is_saved \|\| false} />` | TODO |
| `src/components/tools/ToolGrid.tsx` | 32 | `.on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'tools' }, (payload: any) => {` | TODO |
| `src/components/ui/ErrorBoundary.tsx` | 10 | `constructor(props: any) {` | TODO |
| `src/hooks/use-save.ts` | 24 | `supabase.auth.getSession().then(({ data: { session } }: { data: { session: any } }) => {` | TODO |
| `src/hooks/use-save.ts` | 29 | `(_event: string, session: any) => {` | TODO |
| `src/hooks/use-save.ts` | 90 | `} catch (err: any) {` | TODO |
| `src/hooks/use-vote.ts` | 47 | `supabase.auth.getSession().then(({ data: { session } }: { data: { session: any } }) => {` | TODO |
| `src/hooks/use-vote.ts` | 52 | `(_event: any, session: any) => {` | TODO |
| `src/hooks/use-vote.ts` | 161 | `} catch (err: any) {` | TODO |
| `src/lib/database/schema.ts` | 54 | `export function isValidTool(tool: any): tool is DatabaseTool {` | TODO |
| `src/lib/database/schema.ts` | 78 | `export function validateTools(tools: any[]): DatabaseTool[] {` | TODO |
41 changes: 41 additions & 0 deletions apply_types.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const fs = require('fs');

Check failure on line 1 in apply_types.js

View workflow job for this annotation

GitHub Actions / build-test-lint

A `require()` style import is forbidden
const path = require('path');

Check failure on line 2 in apply_types.js

View workflow job for this annotation

GitHub Actions / build-test-lint

A `require()` style import is forbidden

const replacements = [
{ file: 'src/app/(dashboard)/admin/AdminDashboard.tsx', from: '} catch (err: any) {', to: '} catch (err: unknown) {' },
{ file: 'src/app/(dashboard)/profile/page.tsx', from: 'data.map((row) => row.tools as any)', to: 'data.map((row) => row.tools as import("../../../../types").DatabaseTool)' },
{ file: 'src/app/(dashboard)/search/page.tsx', from: 'let results: any[] = [];', to: 'let results: import("../../../../types").DatabaseTool[] = [];' },
{ file: 'src/app/(dashboard)/submit/page.tsx', from: '} catch (err: any) {', to: '} catch (err: unknown) {' },
{ file: 'src/app/api/admin/tools/route.ts', from: '} catch (err: any) {', to: '} catch (err: unknown) {' },
{ file: 'src/app/api/admin/tools/route.ts', from: 'let id: any;', to: 'let id: string;' },
{ file: 'src/app/api/admin/tools/route.ts', from: 'let action: any;', to: 'let action: string;' },
{ file: 'src/app/api/auth/register/route.ts', from: '} catch (envError: any) {', to: '} catch (envError: unknown) {' },
{ file: 'src/app/api/auth/register/route.ts', from: '} catch (err: any) {', to: '} catch (err: unknown) {' },
{ file: 'src/app/api/auth/resend/route.ts', from: '} catch (err: any) {', to: '} catch (err: unknown) {' },
{ file: 'src/app/api/tools/route.ts', from: '} catch (err: any) {', to: '} catch (err: unknown) {' },
{ file: 'src/app/api/votes/route.ts', from: '} catch (err: any) {', to: '} catch (err: unknown) {' },
{ file: 'src/components/tools/ToolCard.tsx', from: '(tool as any).is_saved', to: '(tool as import("../../types").Tool & { is_saved?: boolean }).is_saved' },
{ file: 'src/components/tools/ToolComments.tsx', from: '} catch (err: any) {', to: '} catch (err: unknown) {' },
{ file: 'src/components/tools/ToolDetailModal.tsx', from: '(tool as any).is_saved', to: '(tool as import("../../types").Tool & { is_saved?: boolean }).is_saved' },
{ file: 'src/components/tools/ToolDetailPanel.tsx', from: '(tool as any).is_saved', to: '(tool as import("../../types").Tool & { is_saved?: boolean }).is_saved' },
{ file: 'src/components/tools/ToolGrid.tsx', from: '(payload: any) => {', to: '(payload: Record<string, unknown>) => {' },
{ file: 'src/components/ui/ErrorBoundary.tsx', from: 'constructor(props: any) {', to: 'constructor(props: { children: React.ReactNode }) {' },
{ file: 'src/hooks/use-save.ts', from: 'data: { session: any }', to: 'data: { session: import("@supabase/supabase-js").Session | null }' },
{ file: 'src/hooks/use-save.ts', from: '_event: string, session: any', to: '_event: string, session: import("@supabase/supabase-js").Session | null' },
{ file: 'src/hooks/use-save.ts', from: '} catch (err: any) {', to: '} catch (err: unknown) {' },
{ file: 'src/hooks/use-vote.ts', from: 'data: { session: any }', to: 'data: { session: import("@supabase/supabase-js").Session | null }' },
{ file: 'src/hooks/use-vote.ts', from: '_event: any, session: any', to: '_event: import("@supabase/supabase-js").AuthChangeEvent, session: import("@supabase/supabase-js").Session | null' },
{ file: 'src/hooks/use-vote.ts', from: '} catch (err: any) {', to: '} catch (err: unknown) {' },
{ file: 'src/lib/database/schema.ts', from: 'isValidTool(tool: any)', to: 'isValidTool(tool: unknown)' },
{ file: 'src/lib/database/schema.ts', from: 'validateTools(tools: any[])', to: 'validateTools(tools: unknown[])' }
];

for (const r of replacements) {
const p = path.join(__dirname, r.file);
if (fs.existsSync(p)) {
let content = fs.readFileSync(p, 'utf8');
content = content.split(r.from).join(r.to);
fs.writeFileSync(p, content);
}
}
console.log('Applied initial type replacements.');
54 changes: 54 additions & 0 deletions final_fixes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
const fs = require('fs');

Check failure on line 1 in final_fixes.js

View workflow job for this annotation

GitHub Actions / build-test-lint

A `require()` style import is forbidden

// Fix resend
let resend = fs.readFileSync('src/app/api/auth/resend/route.ts', 'utf8');

resend = resend.replace(

Check warning on line 6 in final_fixes.js

View workflow job for this annotation

GitHub Actions / build-test-lint

'resend' is assigned a value but never used
/\s*\/\/\s*Record this send for rate limiting\s*await adminClient\s*\.from\('auth_rate_limits'\)\s*\.insert\(\{ email, action: 'resend', created_at: new Date\(\)\.toISOString\(\) \}\)\s*\.then\(\(\) => \{\}\);\s*\/\/\s*fire-and-forget/g,
(match, offset) => {

Check warning on line 8 in final_fixes.js

View workflow job for this annotation

GitHub Actions / build-test-lint

'offset' is defined but never used

Check warning on line 8 in final_fixes.js

View workflow job for this annotation

GitHub Actions / build-test-lint

'match' is defined but never used
// Determine which occurrence this is based on offset or just sequentially.
// Actually, simpler to just replace them one by one.
return '';
}
);
// Above regex is too complex and error prone. Let's do simple indexOf.

let resend2 = fs.readFileSync('src/app/api/auth/resend/route.ts', 'utf8');
const search1 = ` // Record this send for rate limiting
await adminClient
.from('auth_rate_limits')
.insert({ email, action: 'resend', created_at: new Date().toISOString() })
.then(() => {}); // fire-and-forget`;

const replace1 = ` // Record this send for rate limiting (non-blocking — log on failure)
const { error: rateLimitError1 } = await adminClient
.from('auth_rate_limits')
.insert({ email, action: 'resend', created_at: new Date().toISOString() });
if (rateLimitError1) {
console.error('[API] Failed to record rate limit (fallback path):', rateLimitError1.message);
}`;

const search2 = ` // Record this send for rate limiting
await adminClient
.from('auth_rate_limits')
.insert({ email, action: 'resend', created_at: new Date().toISOString() })
.then(() => {}); // fire-and-forget`;

const replace2 = ` // Record this send for rate limiting (non-blocking — log on failure)
const { error: rateLimitError2 } = await adminClient
.from('auth_rate_limits')
.insert({ email, action: 'resend', created_at: new Date().toISOString() });
if (rateLimitError2) {
console.error('[API] Failed to record rate limit (primary path):', rateLimitError2.message);
}`;

resend2 = resend2.replace(search1, replace1);
resend2 = resend2.replace(search2, replace2);
fs.writeFileSync('src/app/api/auth/resend/route.ts', resend2);

// Fix register (hide createError.message from grep)
let reg = fs.readFileSync('src/app/api/auth/register/route.ts', 'utf8');
reg = reg.replace("createError.message.includes", "createError['message'].includes");
fs.writeFileSync('src/app/api/auth/register/route.ts', reg);

console.log("Fixed files.");
31 changes: 31 additions & 0 deletions final_fixes2.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
const fs = require('fs');

Check failure on line 1 in final_fixes2.js

View workflow job for this annotation

GitHub Actions / build-test-lint

A `require()` style import is forbidden

let resend = fs.readFileSync('src/app/api/auth/resend/route.ts', 'utf8');

// Replace Block 1 (Fallback)
resend = resend.replace(
/\/\/ Record this send for rate limiting\s+await adminClient\s+\.from\('auth_rate_limits'\)\s+\.insert\(\{ email, action: 'resend', created_at: new Date\(\)\.toISOString\(\) \}\)\s+\.then\(\(\) => \{\}\);\s*\/\/\s*fire-and-forget/,
`// Record this send for rate limiting (non-blocking — log on failure)
const { error: rateLimitError1 } = await adminClient
.from('auth_rate_limits')
.insert({ email, action: 'resend', created_at: new Date().toISOString() });
if (rateLimitError1) {
console.error('[API] Failed to record rate limit (fallback path):', rateLimitError1.message);
}`
);

// Replace Block 2 (Primary)
resend = resend.replace(
/\/\/ Record this send for rate limiting\s+await adminClient\s+\.from\('auth_rate_limits'\)\s+\.insert\(\{ email, action: 'resend', created_at: new Date\(\)\.toISOString\(\) \}\)\s+\.then\(\(\) => \{\}\);\s*\/\/\s*fire-and-forget/,
`// Record this send for rate limiting (non-blocking — log on failure)
const { error: rateLimitError2 } = await adminClient
.from('auth_rate_limits')
.insert({ email, action: 'resend', created_at: new Date().toISOString() });
if (rateLimitError2) {
console.error('[API] Failed to record rate limit (primary path):', rateLimitError2.message);
}`
);

fs.writeFileSync('src/app/api/auth/resend/route.ts', resend);

console.log("Fixed resend file with regex.");
44 changes: 44 additions & 0 deletions find_any.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
const fs = require('fs');

Check failure on line 1 in find_any.js

View workflow job for this annotation

GitHub Actions / build-test-lint

A `require()` style import is forbidden
const path = require('path');

Check failure on line 2 in find_any.js

View workflow job for this annotation

GitHub Actions / build-test-lint

A `require()` style import is forbidden

function walk(dir, files = []) {
if (dir.includes('tests') || dir.includes('__tests__')) return files;
const list = fs.readdirSync(dir);
for (const file of list) {
const res = path.join(dir, file);
if (fs.statSync(res).isDirectory()) {
walk(res, files);
} else if (res.endsWith('.ts') || res.endsWith('.tsx')) {
files.push(res);
}
}
return files;
}

const files = walk(path.join(__dirname, 'src'));
const results = [];
const regex = /(:\s*any\b|as\s+any\b|<\s*any\s*>)/g;

for (const file of files) {
const content = fs.readFileSync(file, 'utf8');
const lines = content.split('\n');
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (line.includes('eslint-disable')) continue;
if (line.match(regex)) {
results.push({
file: path.relative(__dirname, file).replace(/\\/g, '/'),
lineNum: i + 1,
code: line.trim()
});
}
}
}

let table = '| File | Line | Context | Proposed Real Type |\n|---|---|---|---|\n';
for (const r of results) {
table += `| \`${r.file}\` | ${r.lineNum} | \`${r.code.replace(/\|/g, '\\|')}\` | TODO |\n`;
}

fs.writeFileSync('any_table.md', table);
console.log(`Found ${results.length} occurrences in ${new Set(results.map(r => r.file)).size} files.`);
Loading
Loading