Skip to content

[Infra] Schema rework - #640

Merged
Fermionic-Lyu merged 34 commits into
mainfrom
schema-rework
Dec 19, 2025
Merged

Fermionic-Lyu merged 34 commits into
mainfrom
schema-rework

Conversation

@Fermionic-Lyu

@Fermionic-Lyu Fermionic-Lyu commented Dec 13, 2025 •

Copy link
Copy Markdown
Member

Summary

Reworked schema to the following standard:

  • system
    • migrations
    • secrets
    • audit_logs
    • mcp_usage
  • auth
    • users (remove name, add is_super_admin, is_anonymous, metadata, profile column)
    • user_providers
    • configs
    • oauth_configs
    • email_otps
  • ai
    • configs
    • usage
  • storage
    • objects
    • buckets
  • functions
    • definitions
    • invocations (future)
    • usage (future)
  • realtime
    • channels
    • messages

Updated docs, templates accordingly, but there could be missing places. If you find anything outdated, let me know!

How did you test this change?

Tested locally and on cloud, all versions migrated successfully without losing user data, and all previous foreign key relation to users.id will be migrated to auth.users.id.

Summary by CodeRabbit

  • New Features

    • View and update richer user profiles (profile + metadata) and receive full current-session user data; new profile endpoints.
    • Expanded OAuth providers: Instagram, TikTok, Apple, X, Spotify.
    • Data grid: customizable selection column with avatar + name support.
    • Storage: new upload/download strategy endpoints.
  • Bug Fixes / Ops

    • Migration bootstrap step added; migrations now tracked under a system schema.
  • Documentation

    • Docs updated to a multi‑schema database architecture and revised auth model.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Dec 13, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Rehomes many public tables into new schemas (system, auth, ai, storage, functions), adds a bootstrap migration to move node-pg-migrate state, updates SQL/table references across backend services, adjusts types/frontend/UI/docs/OpenAPI for auth/profile changes, and adds profile GET/PATCH endpoints.

Changes

Cohort / File(s) Summary
Migration & bootstrap
backend/package.json, backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
Added migrate:bootstrap and wired migrate scripts to run it; bootstrap script migrates node-pg-migrate tracking table to system.migrations or creates the system schema for fresh installs.
Schema rework migration
backend/src/infra/database/migrations/018_schema-rework.sql
Creates schemas (system,auth,ai,storage,functions), moves/renames many tables, adds JSONB profile/metadata, new flags, RLS/policies, triggers, functions, FK updates and data migration steps.
Database core & metadata
backend/src/infra/database/database.manager.ts, backend/src/services/database/database-advance.service.ts, backend/src/services/database/database-table.service.ts, backend/src/types/database.ts, backend/src/utils/validations.ts
Removed init transaction; include underscore-prefixed tables in listings; simplified raw-SQL sanitization (removed mode branching and underscore guard); added cross-schema FK awareness and type metadata (udt_name, foreign_schema).
Auth backend: services, types & routes
backend/src/services/auth/*.ts, backend/src/api/routes/auth/*.ts, backend/src/types/auth.ts, backend/src/utils/seed.ts
Migrated auth tables to auth.*, replaced name with profile/metadata, added is_project_admin/is_anonymous, updated SQL across services, added profile GET/PATCH endpoints and admin seeding into auth.users.
AI, functions & usage services
backend/src/services/ai/*.ts, backend/src/services/functions/function.service.ts, backend/src/services/usage/usage.service.ts, functions/*, zeabur/template.yml
Replaced legacy tables with ai.configs/ai.usage, functions.definitions; updated joins and queries to new schema-qualified names; adjusted function/worker docs to functions.definitions and system.secrets.
Storage, secrets & audit
backend/src/services/storage/storage.service.ts, backend/src/services/secrets/secret.service.ts, backend/src/services/logs/audit.service.ts, backend/tests/*
Migrated _storage/_storage_buckets → storage.objects/storage.buckets, _secrets → system.secrets, _audit_logs → system.audit_logs; added upload/download strategy APIs and timing-safe secret comparison.
Frontend DB surface & UI changes
frontend/src/features/database/constants.ts, frontend/src/features/database/hooks/useTables.ts, frontend/src/features/database/services/table.service.ts, frontend/src/lib/hooks/useMetadata.ts, frontend/src/features/visualizer/*, frontend/src/features/database/templates/*, frontend/src/features/database/components/*, frontend/src/features/database/pages/*
Introduced AUTH_USERS_TABLE and authUsersSchema, removed prior system-guards and filters for users/system tables, special-cased auth.users across FK popovers, link modal, visualizer and templates; metadata hook now includes users.
Frontend DataGrid & users UI types
frontend/src/components/datagrid/DataGrid.tsx, frontend/src/components/datagrid/datagridTypes.tsx, frontend/src/components/datagrid/index.ts, frontend/src/features/auth/components/UsersDataGrid.tsx
Added selectable cell API (SelectionCellProps, renderSelectionCell, selectionColumnWidth), extended DataGridProps, updated ConvertedValue union (added Record<string, unknown> and string[]), and added a custom UserSelectionCell in UsersDataGrid.
OpenAPI, shared-schemas & API surface
openapi/*.yaml, shared-schemas/src/auth.schema.ts, shared-schemas/src/auth-api.schema.ts, shared-schemas/package.json
Added profileSchema, changed UserResponse to use profile/metadata and providers, expanded OAuth provider enum, added profile PATCH/GET endpoints, and bumped shared-schemas version.
Docs, examples & configs
docs/*, examples/*, eslint.config.js, backend/src/api/routes/docs/index.routes.ts
Updated docs/examples to reflect multi-schema layout (auth.*, system.*), restructured changelog, added ESLint ignore for bootstrap scripts, and re-enabled auth-components-nextjs docs mapping.
Misc: auth app, broadcasts, seeds, tests, utils
auth/src/*, auth/package.json, auth/tsconfig.json, backend/src/api/routes/auth/oauth.routes.ts, shared-schemas/*, backend/src/utils/utils.ts, backend/src/utils/cookies.ts, backend/src/server.ts, backend/src/utils/environment.ts
Adjusted broadcast user type to shared UserSchema, SignIn/SignUp redirect now use String(profile?.name), cookie helpers changed to accept req and use req.secure, removed isProduction/isDevelopment helpers, removed shared-schemas dep in auth package.json and added TS path alias, and other minor util/type updates.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

  • Extra attention:
    • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js — connection lifecycle, rename/move logic, and exit-code handling.
    • 018_schema-rework.sql — ordering of moves, FK/policy correctness, destructive operations, and data migration steps.
    • Auth service/types/routes (backend/src/services/auth/auth.service.ts, backend/src/types/auth.ts, backend/src/api/routes/auth/*.ts) — profile/metadata mapping, transactional flows, and new endpoints.
    • Cross-schema FK handling in database-table.service.ts and corresponding frontend special-cases (FK popovers, LinkRecordModal, Visualizer).
    • Cookie API changes (backend/src/utils/cookies.ts) and server gating changes (backend/src/server.ts) — ensure callers updated and security flags correct.
    • OpenAPI/shared-schemas vs backend responses — ensure runtime types and API docs remain consistent.

Possibly related PRs

Suggested reviewers

  • jwfing
  • tonychang04

Poem

🐇 I hopped through schemas late and bright,

I nudged the migrations into place at night,
Moved secrets, users, functions to new homes so neat,
Wrapped profiles in JSON, made FK crossings meet,
A tiny bootstrap drumbeat — migrations march in light.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 47.83% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title '[Infra] Schema rework' clearly and directly describes the primary change—a comprehensive rework of the database schema architecture into namespaced groups.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch schema-rework

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (12)
frontend/src/features/database/components/ForeignKeyPopover.tsx (1)

266-266: Fix typo in user-facing error message.

The error message has a typo and grammatical issue.

Apply this diff:

-                            rightText = 'Columntype not match';
+                            rightText = 'Column types do not match';
backend/tests/manual/test-rawsql-modes.sh (2)

72-118: Test summary text contradicts the strict-mode test behavior for auth.users.
Strict mode Test 6 expects SELECT COUNT(*) FROM auth.users to pass, but the summary line says “Blocks ALL operations on auth.users table”. Update the summary line to match the tests (or change Test 6 expectation).

Suggested diff:

-echo "  - ❌ Blocks ALL operations on auth.users table"
+echo "  - ❌ Blocks write/DDL operations on auth.users table"

Also applies to: 123-186


7-9: Hard-coded bearer token in repo is a security footgun (even for manual tests).
Please move TOKEN to an env var (with a safe default) to avoid accidental reuse/leakage.

Suggested diff:

-TOKEN="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
+TOKEN="${TOKEN:-}"
+if [ -z "$TOKEN" ]; then
+  echo "Missing TOKEN env var" >&2
+  exit 1
+fi
backend/src/services/secrets/secret.service.ts (2)

159-204: updateSecret can generate invalid SQL when input has no updatable fields.
If updates.length === 0, this becomes SET (syntax error). Add an early return (or throw a validation error) before issuing the query.

Suggested diff:

   async updateSecret(id: string, input: UpdateSecretInput): Promise<boolean> {
     try {
       const updates: string[] = [];
       const values: (string | boolean | Date | null)[] = [];
       let paramCount = 1;
@@
       if (input.expiresAt !== undefined) {
         updates.push(`expires_at = $${paramCount++}`);
         values.push(input.expiresAt);
       }
+
+      if (updates.length === 0) {
+        return false;
+      }
@@
       values.push(id);

209-241: Use constant-time comparison for API key verification.
The checkSecretByKey method compares secrets using === (line 228), which leaks timing information. Replace with crypto.timingSafeEqual(Buffer.from(decryptedValue), Buffer.from(value)) to prevent timing attacks, especially critical since this method verifies API keys via verifyApiKey (lines 359-364).

backend/src/services/usage/usage.service.ts (1)

96-147: Fix precision loss in usage statistics for large database/storage sizes.

The queries for pg_database_size(), COUNT(*), and SUM(size) can return PostgreSQL BIGINT values exceeding JavaScript's safe integer range (2^53-1). Using parseInt() on these values silently loses precision for databases or storage exceeding ~9 petabytes.

Change database_size_bytes and storage_size_bytes to string fields in the UsageStats interface to preserve precision:

export interface UsageStats {
  mcp_usage_count: number;
-  database_size_bytes: number;
-  storage_size_bytes: number;
+  database_size_bytes: string;
+  storage_size_bytes: string;
   ai_usage_by_model: AIUsageByModel[];
}

       return {
         mcp_usage_count: parseInt(mcpResult.rows[0]?.count || '0'),
-        database_size_bytes: parseInt(dbSizeResult.rows[0]?.size || '0'),
-        storage_size_bytes: parseInt(storageResult.rows[0]?.total_size || '0'),
+        database_size_bytes: String(dbSizeResult.rows[0]?.size ?? '0'),
+        storage_size_bytes: String(storageResult.rows[0]?.total_size ?? '0'),

Note: Verify token sum fields (total_input_tokens, total_output_tokens) in AIUsageByModel and ai-config.service.ts also don't exceed safe range, as they use SUM() on INT columns without explicit casting.

frontend/src/components/datagrid/DataGrid.tsx (1)

119-142: Inconsistent key usage between cell and header selection logic.

The renderCell function uses keyGetter(row) (lines 102-108), but renderHeaderCell uses row.id directly (lines 120, 133, 136). This inconsistency could cause bugs when a custom rowKeyGetter is provided that returns a different value than row.id.

Apply this diff to use keyGetter consistently:

         renderHeaderCell: () => {
-          const selectedCount = data.filter((row) => selectedRows.has(String(row.id))).length;
+          const selectedCount = data.filter((row) => selectedRows.has(keyGetter(row))).length;
           const totalCount = data.length;
           const isAllSelected = totalCount > 0 && selectedCount === totalCount;
           const isPartiallySelected = selectedCount > 0 && selectedCount < totalCount;

           return (
             <Checkbox
               checked={isAllSelected}
               indeterminate={isPartiallySelected}
               onChange={(checked) => {
                 const newSelectedRows = new Set(selectedRows);
                 if (checked) {
                   // Select all
-                  data.forEach((row) => newSelectedRows.add(String(row.id)));
+                  data.forEach((row) => newSelectedRows.add(keyGetter(row)));
                 } else {
                   // Unselect all
-                  data.forEach((row) => newSelectedRows.delete(String(row.id)));
+                  data.forEach((row) => newSelectedRows.delete(keyGetter(row)));
                 }
                 onSelectedRowsChange(newSelectedRows);
               }}
             />
           );
         },
backend/src/api/routes/auth/oauth.routes.ts (2)

344-350: Potential issue with String() on undefined metadata.

When result?.user?.metadata?.name is undefined or null, String() will produce the literal string "undefined" or "null", which may confuse client applications expecting an empty string or missing parameter.

Consider using nullish coalescing or conditional assignment:

-    params.set('name', String(result?.user?.metadata?.name));
+    params.set('name', result?.user?.metadata?.name ?? '');

Alternatively, only set the parameter when a name exists:

if (result?.user?.metadata?.name) {
  params.set('name', result.user.metadata.name);
}

416-422: Same issue with String() casting.

This has the same potential issue as the shared callback above—String(undefined) produces "undefined".

Apply the same fix pattern:

-      params.set('name', String(result?.user?.metadata?.name));
+      params.set('name', result?.user?.metadata?.name ?? '');
backend/src/utils/seed.ts (1)

64-105: Fix misleading “enabled (cloud environment)” log + consider atomic seed insert.

  • Line 95 sets require_email_verification to isCloudEnvironment(), but Line 104 always logs “enabled (cloud environment)”, which will be incorrect in local runs.
  • The SELECT COUNT(*) (Line 70) + INSERT (Line 85) is race-prone; prefer a single atomic INSERT ... SELECT ... WHERE NOT EXISTS (or INSERT ... ON CONFLICT (...) DO NOTHING with an explicit conflict target) if you want exactly one config row.
docs/core-concepts/database/sdk.mdx (1)

341-375: Update auth-hook example: user.name likely no longer exists after schema rework.

If the SDK user mirrors auth.users changes, Line 368 should not use user.name; it should read from metadata (and confirm whether user.email is still directly available).

claude-plugin/skills/insforge-schema-patterns/SKILL.md (1)

183-193: Query expansion may reference incorrect columns.

The query examples use author:user_id(nickname, avatar_url), but according to the migration, auth.users no longer has nickname or avatar_url as direct columns. These fields are now stored in the metadata JSONB column.

Consider updating the examples to reflect the new schema structure:

-  .select('*, author:user_id(nickname, avatar_url)')
+  .select('*, author:user_id(id, metadata)')

Then extract name and avatar_url from metadata in the application code.

🧹 Nitpick comments (12)
frontend/src/features/database/pages/SQLEditorPage.tsx (1)

302-308: Use a schema-qualified (and valid) example in the placeholder

Given the schema rework, products is likely not a guaranteed table name, and from should be FROM for readability. Consider updating the placeholder to a schema-qualified table that exists post-migration (or a neutral query).

-              placeholder="SELECT * from products LIMIT 10;"
+              placeholder="SELECT * FROM auth.users LIMIT 10;"
frontend/src/features/database/hooks/useTables.ts (1)

112-127: Watch for parallel-fetch burst + verify authz for auth.users schema fetch.
Now that users is included, please ensure tableService.getTableSchema() cannot leak restricted schema details to unauthorized users, and consider avoiding potentially large fan-out query storms when tables grows.

A concrete improvement (keeps useTables() API unchanged) is to make enabled=false truly “on demand” by not fetching tables at all:

 export function useAllTableSchemas(enabled = true) {
-  const { tables, isLoadingTables } = useTables();
+  const { data: tables = [], isLoading: isLoadingTables } = useQuery({
+    queryKey: ['tables'],
+    queryFn: () => tableService.listTables(),
+    staleTime: 2 * 60 * 1000,
+    enabled,
+  });

   const { allSchemas, isLoadingSchemas } = useQueries({
     queries: enabled
       ? tables.map((tableName) => ({
           queryKey: ['tables', tableName, 'schema'],
           queryFn: () => tableService.getTableSchema(tableName),
           staleTime: 2 * 60 * 1000,
         }))
       : [],
     combine: (results) => ({
       allSchemas: results.filter((r) => r.data).map((r) => r.data as GetTableSchemaResponse),
       isLoadingSchemas: results.some((r) => r.isLoading),
     }),
   });

Separately, if tables can be large, consider a single backend endpoint to fetch all schemas in one call (or server-side batching) to avoid N parallel requests.

frontend/src/features/database/components/ForeignKeyPopover.tsx (1)

20-24: Hardcoded schema creates maintenance risk.

The hardcoded authUsersSchema bypasses dynamic schema fetching and will become stale if the actual auth.users table schema changes. Consider documenting why this workaround exists and adding a TODO to fetch the real schema once the backend supports cross-schema queries, or ensure this is kept in sync with the actual table definition.

Additionally, add an explicit type annotation for better type safety:

+type TableSchema = { columns: ColumnSchema[] };
+
 // Special auth.users table schema (only id column available for FK)
 const AUTH_USERS_TABLE = 'auth.users';
-const authUsersSchema = {
+const authUsersSchema: TableSchema = {
   columns: [{ columnName: 'id', type: 'uuid', isUnique: true, isNullable: false }],
 };
frontend/src/features/database/components/ForeignKeyCell.tsx (1)

56-56: Empty string passed to useRecords when disabled.

Passing an empty string to useRecords when isAuthUsers is true works because of the enabled check in the hook, but this is fragile. If the hook implementation changes, this could cause unintended API calls.

Consider using a more explicit pattern:

-  const recordsHook = useRecords(isAuthUsers ? '' : foreignKey.table);
+  const recordsHook = useRecords(foreignKey.table);

Then rely solely on the enabled parameter in useRecordByForeignKey (line 80) which already handles the !isAuthUsers condition.

backend/src/services/usage/usage.service.ts (1)

54-69: recordMCPUsage table rename is fine; consider BIGINT return types in pg.
created_at is OK, but usage counters/sizes elsewhere can exceed JS safe integer—worth aligning now while touching this service.

frontend/src/features/database/templates/ai-chatbot.ts (1)

229-270: Consider aligning conversations.user_id nullability with RLS policies.
DDL allows user_id NULL, but RLS policies effectively require user_id = auth.uid() for select/insert/update/delete—so NULL rows would be unusable. Either make user_id NOT NULL or explicitly support anonymous flows in policies.

frontend/src/features/auth/components/UsersDataGrid.tsx (1)

205-218: Consider validating avatar URL before rendering.

The avatarUrl from user metadata is rendered directly in an <img> tag. While React 19 blocks javascript: URLs, consider adding basic URL validation (e.g., ensuring it starts with https://) to prevent rendering potentially malformed URLs.

   const metadata = row.metadata as Record<string, unknown> | null;
-  const avatarUrl = metadata?.avatar_url as string | undefined;
+  const rawAvatarUrl = metadata?.avatar_url as string | undefined;
+  const avatarUrl = rawAvatarUrl?.startsWith('https://') ? rawAvatarUrl : undefined;
   const name = metadata?.name as string | undefined;
backend/src/services/functions/function.service.ts (1)

44-52: Good migration to functions.definitions, but wrap multi-step writes in a DB transaction.

createFunction() (Line 127+) and updateFunction() (Line 185+) do multiple UPDATEs; without BEGIN/COMMIT, partial updates are possible on error.

Also applies to: 89-98, 114-146, 178-246, 264-270, 289-295

frontend/src/features/visualizer/components/SchemaVisualizer.tsx (1)

249-257: Keep backward-compat for FK targets: accept both users and auth.users.

If referenceTable can still be 'users' from older schema snapshots, this change will stop routing edges to the auth node. Suggested tweak:

- column.foreignKey.referenceTable === 'auth.users' &&
+ (column.foreignKey.referenceTable === 'auth.users' || column.foreignKey.referenceTable === 'users') &&
  column.foreignKey.referenceColumn === 'id'

Also applies to: 281-285

backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js (1)

32-70: Consider adding transaction wrapper for atomicity.

While the current approach works, wrapping the schema creation and table move operations in a transaction would ensure atomicity. If the rename fails after setting the schema, the system could be left in an inconsistent state.

Apply this diff to add transaction safety:

     try {
+      await client.query('BEGIN');
+
       // Check if old _migrations table exists in public schema
       const oldTableExists = await client.query(`
         SELECT EXISTS (
           SELECT 1 FROM information_schema.tables
           WHERE table_schema = 'public' AND table_name = '_migrations'
         ) as exists
       `);

       // Check if new system.migrations table already exists
       const newTableExists = await client.query(`
         SELECT EXISTS (
           SELECT 1 FROM information_schema.tables
           WHERE table_schema = 'system' AND table_name = 'migrations'
         ) as exists
       `);

       if (oldTableExists.rows[0].exists && !newTableExists.rows[0].exists) {
         console.log('Bootstrap: Moving _migrations table to system.migrations...');

         // Create system schema if it doesn't exist
         await client.query('CREATE SCHEMA IF NOT EXISTS system');

         // Move the table
         await client.query('ALTER TABLE public._migrations SET SCHEMA system');
         await client.query('ALTER TABLE system._migrations RENAME TO migrations');

         console.log('Bootstrap: Successfully moved _migrations to system.migrations');
+        await client.query('COMMIT');
       } else if (newTableExists.rows[0].exists) {
         // Already migrated, nothing to do
         console.log('Bootstrap: system.migrations already exists, skipping');
+        await client.query('COMMIT');
       } else if (!oldTableExists.rows[0].exists && !newTableExists.rows[0].exists) {
         // Fresh install - node-pg-migrate will create the table
         console.log('Bootstrap: No existing migrations table, fresh install');
+        await client.query('COMMIT');
       }
     } finally {
       client.release();
     }
   } catch (error) {
+    try {
+      await client.query('ROLLBACK');
+    } catch (rollbackError) {
+      // Ignore rollback errors
+    }
     console.error('Bootstrap migration failed:', error.message);
     process.exit(1);
   } finally {
claude-plugin/skills/insforge-schema-patterns/SKILL.md (1)

47-57: Query simplification removes user profile expansion.

The .select() calls without arguments will return only the follows table columns. If consumers need user details (nickname, avatar_url), they'll need a separate query or should use .select('*, follower:follower_id(id, metadata)') syntax.

This is fine as a simplified example, but consider adding a comment or advanced example showing how to expand the auth.users metadata in the query.

backend/src/infra/database/migrations/018_schema-rework.sql (1)

1-4: Consider adding rollback documentation or procedure.

This migration performs significant schema changes including data migrations. While a full DOWN migration would be complex, consider documenting:

  1. The backup procedure before running this migration
  2. Manual rollback steps if needed
  3. Any data that would be lost on rollback (e.g., the consolidated metadata)

This is especially important for production deployments.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dc75938 and 9fd3efe.

📒 Files selected for processing (65)
  • backend/package.json (1 hunks)
  • backend/src/api/routes/auth/oauth.routes.ts (2 hunks)
  • backend/src/infra/database/database.manager.ts (0 hunks)
  • backend/src/infra/database/migrations/018_schema-rework.sql (1 hunks)
  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js (1 hunks)
  • backend/src/services/ai/ai-config.service.ts (5 hunks)
  • backend/src/services/ai/ai-usage.service.ts (6 hunks)
  • backend/src/services/auth/auth-config.service.ts (4 hunks)
  • backend/src/services/auth/auth-otp.service.ts (6 hunks)
  • backend/src/services/auth/auth.service.ts (25 hunks)
  • backend/src/services/auth/oauth-config.service.ts (11 hunks)
  • backend/src/services/database/database-advance.service.ts (1 hunks)
  • backend/src/services/database/database-table.service.ts (4 hunks)
  • backend/src/services/functions/function.service.ts (7 hunks)
  • backend/src/services/logs/audit.service.ts (5 hunks)
  • backend/src/services/secrets/secret.service.ts (12 hunks)
  • backend/src/services/storage/storage.service.ts (18 hunks)
  • backend/src/services/usage/usage.service.ts (5 hunks)
  • backend/src/types/auth.ts (1 hunks)
  • backend/src/types/database.ts (1 hunks)
  • backend/src/types/profile.ts (0 hunks)
  • backend/src/types/storage.ts (1 hunks)
  • backend/src/utils/seed.ts (2 hunks)
  • backend/src/utils/validations.ts (0 hunks)
  • backend/tests/local/test-secrets.sh (1 hunks)
  • backend/tests/manual/test-rawsql-modes.sh (4 hunks)
  • claude-plugin/skills/insforge-schema-patterns/SKILL.md (5 hunks)
  • docs/core-concepts/authentication/architecture.mdx (4 hunks)
  • docs/core-concepts/database/architecture.mdx (1 hunks)
  • docs/core-concepts/database/sdk.mdx (6 hunks)
  • docs/core-concepts/functions/sdk.mdx (0 hunks)
  • docs/core-concepts/storage/sdk.mdx (4 hunks)
  • docs/partnership.mdx (1 hunks)
  • eslint.config.js (1 hunks)
  • examples/response-examples.md (1 hunks)
  • frontend/src/components/datagrid/DataGrid.tsx (5 hunks)
  • frontend/src/components/datagrid/datagridTypes.tsx (1 hunks)
  • frontend/src/components/datagrid/index.ts (1 hunks)
  • frontend/src/features/auth/components/UsersDataGrid.tsx (5 hunks)
  • frontend/src/features/database/components/DatabaseDataGrid.tsx (0 hunks)
  • frontend/src/features/database/components/ForeignKeyCell.tsx (5 hunks)
  • frontend/src/features/database/components/ForeignKeyPopover.tsx (2 hunks)
  • frontend/src/features/database/constants.ts (1 hunks)
  • frontend/src/features/database/hooks/useTables.ts (1 hunks)
  • frontend/src/features/database/pages/IndexesPage.tsx (0 hunks)
  • frontend/src/features/database/pages/PoliciesPage.tsx (0 hunks)
  • frontend/src/features/database/pages/SQLEditorPage.tsx (1 hunks)
  • frontend/src/features/database/pages/TriggersPage.tsx (0 hunks)
  • frontend/src/features/database/services/table.service.ts (1 hunks)
  • frontend/src/features/database/templates/ai-chatbot.ts (6 hunks)
  • frontend/src/features/database/templates/ecommerce-platform.ts (2 hunks)
  • frontend/src/features/database/templates/instagram-clone.ts (8 hunks)
  • frontend/src/features/database/templates/notion-clone.ts (8 hunks)
  • frontend/src/features/database/templates/reddit-clone.ts (10 hunks)
  • frontend/src/features/visualizer/components/SchemaVisualizer.tsx (2 hunks)
  • frontend/src/lib/hooks/useMetadata.ts (1 hunks)
  • functions/server.ts (2 hunks)
  • functions/worker-template.js (1 hunks)
  • openapi/auth.yaml (1 hunks)
  • openapi/logs.yaml (0 hunks)
  • openapi/metadata.yaml (0 hunks)
  • openapi/records.yaml (12 hunks)
  • openapi/tables.yaml (1 hunks)
  • shared-schemas/src/auth.schema.ts (1 hunks)
  • zeabur/template.yml (3 hunks)
💤 Files with no reviewable changes (10)
  • backend/src/infra/database/database.manager.ts
  • backend/src/utils/validations.ts
  • docs/core-concepts/functions/sdk.mdx
  • openapi/metadata.yaml
  • openapi/logs.yaml
  • frontend/src/features/database/pages/TriggersPage.tsx
  • frontend/src/features/database/components/DatabaseDataGrid.tsx
  • frontend/src/features/database/pages/IndexesPage.tsx
  • frontend/src/features/database/pages/PoliciesPage.tsx
  • backend/src/types/profile.ts
🧰 Additional context used
📓 Path-based instructions (18)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • frontend/src/features/database/pages/SQLEditorPage.tsx
  • backend/src/services/auth/auth-config.service.ts
  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/services/database/database-advance.service.ts
  • frontend/src/features/visualizer/components/SchemaVisualizer.tsx
  • functions/server.ts
  • backend/src/services/ai/ai-usage.service.ts
  • frontend/src/features/database/templates/ecommerce-platform.ts
  • frontend/src/features/database/constants.ts
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/components/datagrid/index.ts
  • frontend/src/features/database/services/table.service.ts
  • frontend/src/features/database/templates/notion-clone.ts
  • backend/src/types/storage.ts
  • backend/src/services/logs/audit.service.ts
  • backend/src/services/auth/auth-otp.service.ts
  • frontend/src/lib/hooks/useMetadata.ts
  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
  • shared-schemas/src/auth.schema.ts
  • frontend/src/features/database/templates/ai-chatbot.ts
  • backend/src/services/functions/function.service.ts
  • backend/src/types/database.ts
  • frontend/src/features/database/templates/instagram-clone.ts
  • backend/src/services/ai/ai-config.service.ts
  • backend/src/services/database/database-table.service.ts
  • frontend/src/components/datagrid/datagridTypes.tsx
  • frontend/src/features/database/templates/reddit-clone.ts
  • eslint.config.js
  • functions/worker-template.js
  • backend/src/services/secrets/secret.service.ts
  • backend/src/services/usage/usage.service.ts
  • backend/src/utils/seed.ts
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/services/auth/auth.service.ts
  • frontend/src/features/database/hooks/useTables.ts
  • backend/src/services/auth/oauth-config.service.ts
  • backend/src/services/storage/storage.service.ts
  • backend/src/types/auth.ts
frontend/src/**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

frontend/src/**/*.{tsx,jsx}: Use functional components with hooks exclusively in React
Implement proper TypeScript interfaces for all props in React components
Use React Hook Form for form handling in frontend
Follow component composition patterns in React
Implement proper loading and error states in React components
Keep components focused and single-purpose in React
Use Radix UI primitives for accessibility in frontend
Use appropriate loading skeletons for data fetching in frontend
Display clear error messages with actionable feedback in frontend
Implement proper form validation with inline errors in frontend
Use consistent icon set from lucide-react
Optimize React component re-renders

Files:

  • frontend/src/features/database/pages/SQLEditorPage.tsx
  • frontend/src/features/visualizer/components/SchemaVisualizer.tsx
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/components/datagrid/datagridTypes.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
frontend/src/**/*.{tsx,jsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

frontend/src/**/*.{tsx,jsx,ts}: Use TanStack Query for server state management in frontend
Use lazy loading for code splitting
Optimize bundle size with proper imports

Files:

  • frontend/src/features/database/pages/SQLEditorPage.tsx
  • frontend/src/features/visualizer/components/SchemaVisualizer.tsx
  • frontend/src/features/database/templates/ecommerce-platform.ts
  • frontend/src/features/database/constants.ts
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/components/datagrid/index.ts
  • frontend/src/features/database/services/table.service.ts
  • frontend/src/features/database/templates/notion-clone.ts
  • frontend/src/lib/hooks/useMetadata.ts
  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/templates/ai-chatbot.ts
  • frontend/src/features/database/templates/instagram-clone.ts
  • frontend/src/components/datagrid/datagridTypes.tsx
  • frontend/src/features/database/templates/reddit-clone.ts
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/features/database/hooks/useTables.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • frontend/src/features/database/pages/SQLEditorPage.tsx
  • backend/src/services/auth/auth-config.service.ts
  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/services/database/database-advance.service.ts
  • frontend/src/features/visualizer/components/SchemaVisualizer.tsx
  • functions/server.ts
  • backend/src/services/ai/ai-usage.service.ts
  • frontend/src/features/database/templates/ecommerce-platform.ts
  • frontend/src/features/database/constants.ts
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/components/datagrid/index.ts
  • frontend/src/features/database/services/table.service.ts
  • frontend/src/features/database/templates/notion-clone.ts
  • backend/src/types/storage.ts
  • backend/src/services/logs/audit.service.ts
  • backend/src/services/auth/auth-otp.service.ts
  • frontend/src/lib/hooks/useMetadata.ts
  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • shared-schemas/src/auth.schema.ts
  • frontend/src/features/database/templates/ai-chatbot.ts
  • backend/src/services/functions/function.service.ts
  • backend/src/types/database.ts
  • frontend/src/features/database/templates/instagram-clone.ts
  • backend/src/services/ai/ai-config.service.ts
  • backend/src/services/database/database-table.service.ts
  • frontend/src/components/datagrid/datagridTypes.tsx
  • frontend/src/features/database/templates/reddit-clone.ts
  • backend/src/services/secrets/secret.service.ts
  • backend/src/services/usage/usage.service.ts
  • backend/src/utils/seed.ts
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/services/auth/auth.service.ts
  • frontend/src/features/database/hooks/useTables.ts
  • backend/src/services/auth/oauth-config.service.ts
  • backend/src/services/storage/storage.service.ts
  • backend/src/types/auth.ts
frontend/src/**/*.{tsx,jsx,css}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Maintain consistent color scheme using CSS variables

Files:

  • frontend/src/features/database/pages/SQLEditorPage.tsx
  • frontend/src/features/visualizer/components/SchemaVisualizer.tsx
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/components/datagrid/datagridTypes.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • frontend/src/features/database/pages/SQLEditorPage.tsx
  • backend/src/services/auth/auth-config.service.ts
  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/services/database/database-advance.service.ts
  • frontend/src/features/visualizer/components/SchemaVisualizer.tsx
  • backend/src/services/ai/ai-usage.service.ts
  • frontend/src/features/database/templates/ecommerce-platform.ts
  • frontend/src/features/database/constants.ts
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/components/datagrid/index.ts
  • frontend/src/features/database/services/table.service.ts
  • frontend/src/features/database/templates/notion-clone.ts
  • backend/src/types/storage.ts
  • backend/src/services/logs/audit.service.ts
  • backend/src/services/auth/auth-otp.service.ts
  • frontend/src/lib/hooks/useMetadata.ts
  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
  • frontend/src/features/database/templates/ai-chatbot.ts
  • backend/src/services/functions/function.service.ts
  • backend/src/types/database.ts
  • frontend/src/features/database/templates/instagram-clone.ts
  • backend/src/services/ai/ai-config.service.ts
  • backend/src/services/database/database-table.service.ts
  • frontend/src/components/datagrid/datagridTypes.tsx
  • frontend/src/features/database/templates/reddit-clone.ts
  • backend/src/services/secrets/secret.service.ts
  • backend/src/services/usage/usage.service.ts
  • backend/src/utils/seed.ts
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/services/auth/auth.service.ts
  • frontend/src/features/database/hooks/useTables.ts
  • backend/src/services/auth/oauth-config.service.ts
  • backend/src/services/storage/storage.service.ts
  • backend/src/types/auth.ts
{backend/src/{api,controllers},frontend/src/**}/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src/{api,controllers},frontend/src/**}/*.{ts,tsx,js,jsx}: Validate all user inputs
Use pagination for large data sets

Files:

  • frontend/src/features/database/pages/SQLEditorPage.tsx
  • frontend/src/features/visualizer/components/SchemaVisualizer.tsx
  • frontend/src/features/database/templates/ecommerce-platform.ts
  • frontend/src/features/database/constants.ts
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/components/datagrid/index.ts
  • frontend/src/features/database/services/table.service.ts
  • frontend/src/features/database/templates/notion-clone.ts
  • frontend/src/lib/hooks/useMetadata.ts
  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/templates/ai-chatbot.ts
  • frontend/src/features/database/templates/instagram-clone.ts
  • frontend/src/components/datagrid/datagridTypes.tsx
  • frontend/src/features/database/templates/reddit-clone.ts
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/features/database/hooks/useTables.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • frontend/src/features/database/pages/SQLEditorPage.tsx
  • backend/src/services/auth/auth-config.service.ts
  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/services/database/database-advance.service.ts
  • frontend/src/features/visualizer/components/SchemaVisualizer.tsx
  • backend/src/services/ai/ai-usage.service.ts
  • frontend/src/features/database/templates/ecommerce-platform.ts
  • frontend/src/features/database/constants.ts
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/components/datagrid/index.ts
  • frontend/src/features/database/services/table.service.ts
  • frontend/src/features/database/templates/notion-clone.ts
  • backend/src/types/storage.ts
  • backend/src/services/logs/audit.service.ts
  • backend/src/services/auth/auth-otp.service.ts
  • frontend/src/lib/hooks/useMetadata.ts
  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
  • frontend/src/features/database/templates/ai-chatbot.ts
  • backend/src/services/functions/function.service.ts
  • backend/src/types/database.ts
  • frontend/src/features/database/templates/instagram-clone.ts
  • backend/src/services/ai/ai-config.service.ts
  • backend/src/services/database/database-table.service.ts
  • frontend/src/components/datagrid/datagridTypes.tsx
  • frontend/src/features/database/templates/reddit-clone.ts
  • backend/src/services/secrets/secret.service.ts
  • backend/src/services/usage/usage.service.ts
  • backend/src/utils/seed.ts
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/services/auth/auth.service.ts
  • frontend/src/features/database/hooks/useTables.ts
  • backend/src/services/auth/oauth-config.service.ts
  • backend/src/services/storage/storage.service.ts
  • backend/src/types/auth.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/services/auth/auth-config.service.ts
  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/services/database/database-advance.service.ts
  • backend/src/services/ai/ai-usage.service.ts
  • backend/src/types/storage.ts
  • backend/src/services/logs/audit.service.ts
  • backend/src/services/auth/auth-otp.service.ts
  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
  • backend/src/services/functions/function.service.ts
  • backend/src/types/database.ts
  • backend/src/services/ai/ai-config.service.ts
  • backend/src/services/database/database-table.service.ts
  • backend/src/services/secrets/secret.service.ts
  • backend/src/services/usage/usage.service.ts
  • backend/src/utils/seed.ts
  • backend/src/services/auth/auth.service.ts
  • backend/src/services/auth/oauth-config.service.ts
  • backend/src/services/storage/storage.service.ts
  • backend/src/types/auth.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/services/auth/auth-config.service.ts
  • backend/src/api/routes/auth/oauth.routes.ts
  • backend/src/services/database/database-advance.service.ts
  • backend/src/services/ai/ai-usage.service.ts
  • backend/src/types/storage.ts
  • backend/src/services/logs/audit.service.ts
  • backend/src/services/auth/auth-otp.service.ts
  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
  • shared-schemas/src/auth.schema.ts
  • backend/src/services/functions/function.service.ts
  • backend/src/types/database.ts
  • backend/src/services/ai/ai-config.service.ts
  • backend/src/services/database/database-table.service.ts
  • backend/src/services/secrets/secret.service.ts
  • backend/src/services/usage/usage.service.ts
  • backend/src/utils/seed.ts
  • backend/src/services/auth/auth.service.ts
  • backend/src/services/auth/oauth-config.service.ts
  • backend/src/services/storage/storage.service.ts
  • backend/src/types/auth.ts
backend/src/**/*.service.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Name service files in camelCase with .service.ts suffix (e.g., auth.service.ts)

Files:

  • backend/src/services/auth/auth-config.service.ts
  • backend/src/services/database/database-advance.service.ts
  • backend/src/services/ai/ai-usage.service.ts
  • backend/src/services/logs/audit.service.ts
  • backend/src/services/auth/auth-otp.service.ts
  • backend/src/services/functions/function.service.ts
  • backend/src/services/ai/ai-config.service.ts
  • backend/src/services/database/database-table.service.ts
  • backend/src/services/secrets/secret.service.ts
  • backend/src/services/usage/usage.service.ts
  • backend/src/services/auth/auth.service.ts
  • backend/src/services/auth/oauth-config.service.ts
  • backend/src/services/storage/storage.service.ts
backend/src/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/api/**/*.{ts,js}: Implement proper middleware for authentication and error handling
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
backend/src/{controllers,api}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Return consistent API responses using utility functions

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
backend/src/{api,core,controllers}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper authentication and authorization

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
{backend/src/api,openapi}/**/*.{ts,yaml,yml,json}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Document all API endpoints with clear descriptions

Files:

  • backend/src/api/routes/auth/oauth.routes.ts
  • openapi/tables.yaml
  • openapi/auth.yaml
  • openapi/records.yaml
frontend/src/**/*.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Name hook files with 'use' prefix in PascalCase (e.g., useAuth.ts)

Files:

  • frontend/src/features/database/templates/ecommerce-platform.ts
  • frontend/src/features/database/constants.ts
  • frontend/src/components/datagrid/index.ts
  • frontend/src/features/database/services/table.service.ts
  • frontend/src/features/database/templates/notion-clone.ts
  • frontend/src/lib/hooks/useMetadata.ts
  • frontend/src/features/database/templates/ai-chatbot.ts
  • frontend/src/features/database/templates/instagram-clone.ts
  • frontend/src/features/database/templates/reddit-clone.ts
  • frontend/src/features/database/hooks/useTables.ts
frontend/src/components/**/*.tsx

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Name component files in PascalCase (e.g., DataGrid.tsx)

Files:

  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/components/datagrid/datagridTypes.tsx
{**/README.md,**/examples/**/*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Include examples for common use cases

Files:

  • examples/response-examples.md
🧠 Learnings (17)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/**/*.{ts,js} : Use prepared statements for SQL queries

Applied to files:

  • frontend/src/features/database/pages/SQLEditorPage.tsx
  • backend/src/services/database/database-advance.service.ts
  • functions/server.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Avoid snake_case except in SQL queries and external APIs

Applied to files:

  • frontend/src/features/database/pages/SQLEditorPage.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/**/*.service.ts : Name service files in camelCase with .service.ts suffix (e.g., auth.service.ts)

Applied to files:

  • backend/src/services/auth/auth-config.service.ts
  • backend/src/services/functions/function.service.ts
  • backend/src/services/auth/auth.service.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/**/*.{ts,js} : Sanitize data before database operations

Applied to files:

  • backend/src/services/database/database-advance.service.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/**/*.{ts,js} : Implement proper database transaction handling

Applied to files:

  • backend/src/services/database/database-advance.service.ts
  • backend/src/services/functions/function.service.ts
📚 Learning: 2025-11-14T18:47:06.676Z
Learnt from: Fermionic-Lyu
Repo: InsForge/InsForge PR: 585
File: frontend/src/features/database/page/FunctionsPage.tsx:57-83
Timestamp: 2025-11-14T18:47:06.676Z
Learning: In the InsForge codebase, there are two distinct types of functions: (1) database functions (SQL stored procedures/functions in PostgreSQL) which are part of the database schema and emit DATA_UPDATE events with resource type DATABASE, handled in frontend/src/features/database/page/FunctionsPage.tsx; (2) edge/serverless functions which emit DATA_UPDATE events with resource type FUNCTIONS, handled in frontend/src/features/functions/page/FunctionsPage.tsx. These are separate concepts with different resource types.

Applied to files:

  • functions/server.ts
  • frontend/src/features/database/constants.ts
  • docs/core-concepts/database/architecture.mdx
  • backend/src/services/functions/function.service.ts
  • docs/core-concepts/database/sdk.mdx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/**/*.{ts,js} : Implement proper database indexing

Applied to files:

  • frontend/src/features/database/templates/ecommerce-platform.ts
  • frontend/src/features/database/templates/instagram-clone.ts
  • frontend/src/features/database/templates/reddit-clone.ts
  • frontend/src/features/database/hooks/useTables.ts
📚 Learning: 2025-11-20T00:54:00.807Z
Learnt from: HMaan0
Repo: InsForge/InsForge PR: 607
File: frontend/src/components/datagrid/index.ts:1-23
Timestamp: 2025-11-20T00:54:00.807Z
Learning: In react-data-grid v7.0.0-beta.47, the type for cell click handler arguments is named `CellClickArgs`. This was renamed to `CellMouseArgs` in later beta releases (after beta.47). When reviewing barrel exports or type re-exports from react-data-grid, verify the specific version being used before suggesting type name changes.

Applied to files:

  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/components/datagrid/index.ts
  • frontend/src/features/auth/components/UsersDataGrid.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/components/**/*.tsx : Name component files in PascalCase (e.g., DataGrid.tsx)

Applied to files:

  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/components/datagrid/index.ts
  • frontend/src/features/auth/components/UsersDataGrid.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.ts : Name hook files with 'use' prefix in PascalCase (e.g., useAuth.ts)

Applied to files:

  • frontend/src/lib/hooks/useMetadata.ts
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/database/hooks/useTables.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to **/{src,lib}/**/?(database-|*-)utils.ts : Name utility files in kebab-case or camelCase with .ts suffix (e.g., database-utils.ts)

Applied to files:

  • backend/src/services/functions/function.service.ts
📚 Learning: 2025-11-04T05:18:26.126Z
Learnt from: Fermionic-Lyu
Repo: InsForge/InsForge PR: 553
File: docs/changelog.mdx:6-35
Timestamp: 2025-11-04T05:18:26.126Z
Learning: The InsForge JavaScript SDK repository is named "insforge-sdk-js" and is located at https://github.com/insforge/insforge-sdk-js

Applied to files:

  • docs/core-concepts/storage/sdk.mdx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx} : Use consistent icon set from lucide-react

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx} : Use functional components with hooks exclusively in React

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx} : Use React Hook Form for form handling in frontend

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx,ts} : Use TanStack Query for server state management in frontend

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/services/auth/auth.service.ts
🧬 Code graph analysis (6)
frontend/src/components/datagrid/DataGrid.tsx (4)
frontend/src/components/datagrid/index.ts (1)
  • SelectionCellProps (6-6)
frontend/src/components/datagrid/datagridTypes.tsx (2)
  • DataGridRowType (53-53)
  • DataGridRow (44-46)
frontend/src/components/index.ts (1)
  • Checkbox (12-12)
frontend/src/components/Checkbox.tsx (1)
  • Checkbox (16-59)
frontend/src/features/database/services/table.service.ts (1)
frontend/src/lib/api/client.ts (1)
  • apiClient (163-163)
backend/src/services/logs/audit.service.ts (1)
backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js (1)
  • pool (29-29)
backend/src/utils/seed.ts (1)
backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js (1)
  • client (32-32)
frontend/src/features/database/components/ForeignKeyCell.tsx (3)
frontend/src/features/database/hooks/useTables.ts (1)
  • useTables (10-105)
frontend/src/features/database/hooks/useRecords.ts (1)
  • useRecords (6-139)
frontend/src/features/auth/services/user.service.ts (1)
  • getUser (40-42)
frontend/src/features/database/hooks/useTables.ts (2)
frontend/src/features/database/services/table.service.ts (1)
  • tableService (55-55)
frontend/src/features/database/index.ts (1)
  • tableService (10-10)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: E2E Tests
  • GitHub Check: CI Pre-merge Check

Comment thread frontend/src/lib/hooks/useMetadata.ts Resolved
Comment thread openapi/auth.yaml Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (2)
backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js (2)

51-60: Wrap the move/rename DDL in a transaction to avoid partial state.
If anything fails between SET SCHEMA and RENAME, you can end up with system._migrations lingering (or other partial outcomes).

       if (oldTableExists.rows[0].exists && !newTableExists.rows[0].exists) {
         console.log('Bootstrap: Moving _migrations table to system.migrations...');

         // Create system schema if it doesn't exist
         await client.query('CREATE SCHEMA IF NOT EXISTS system');

-        // Move the table
-        await client.query('ALTER TABLE public._migrations SET SCHEMA system');
-        await client.query('ALTER TABLE system._migrations RENAME TO migrations');
+        await client.query('BEGIN');
+        try {
+          // Move the table
+          await client.query('ALTER TABLE public._migrations SET SCHEMA system');
+          await client.query('ALTER TABLE system._migrations RENAME TO migrations');
+          await client.query('COMMIT');
+        } catch (error) {
+          await client.query('ROLLBACK');
+          throw error;
+        }

         console.log('Bootstrap: Successfully moved _migrations to system.migrations');
       } else if (newTableExists.rows[0].exists) {

82-82: Handle the returned Promise explicitly at top-level (cleaner failure semantics).

-bootstrapMigrations();
+bootstrapMigrations().catch((error) => {
+  const message = error instanceof Error ? error.message : String(error);
+  console.error('Bootstrap migration failed:', message);
+  process.exitCode = 1;
+});
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9fd3efe and 88660cc.

📒 Files selected for processing (1)
  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: CI Pre-merge Check
  • GitHub Check: E2E Tests
🔇 Additional comments (1)
backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js (1)

16-19: Fix process.exit() calls and add transaction safety for DDL operations.

The script calls process.exit(1) in catch blocks (lines 82), which prevents the finally block from executing pool cleanup. Replace with explicit error handling: set process.exitCode = 1 and return, or restructure to ensure await pool.end() executes.

Also wrap the migration move/rename operations (the ALTER TABLE and RENAME TO DDL statements) in a transaction to ensure atomicity—this makes the migration idempotent and easier to rollback if needed.

Confirm that the backend runtime supports ESM ("type": "module" in package.json) and that the pg package's default import works with your Node version and invocation method (whether called via node, tsx, or another loader).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (1)
backend/src/infra/database/migrations/018_schema-rework.sql (1)

185-209: RLS policy is “public can view all rows”; rely less on future-proofing via column GRANTs.
USING (true) on auth.users (Line 200-203) means any role with SELECT privilege can read all rows. Today column-level GRANT limits exposed columns (Line 189-193), but if future migrations grant more columns, the RLS policy won’t protect row visibility.

Safer patterns:

  • Serve public profile reads via a dedicated view (exposing only id/metadata/created_at) with its own policy, and keep auth.users RLS stricter; or
  • Keep policy but explicitly scope allowed rows (if you have a concept like “public profiles enabled”), rather than unconditional true.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 88660cc and 60fb38e.

📒 Files selected for processing (2)
  • backend/src/infra/database/migrations/018_schema-rework.sql (1 hunks)
  • backend/src/services/database/database-table.service.ts (5 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • backend/src/services/database/database-table.service.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/services/database/database-table.service.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/services/database/database-table.service.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • backend/src/services/database/database-table.service.ts
backend/src/**/*.service.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Name service files in camelCase with .service.ts suffix (e.g., auth.service.ts)

Files:

  • backend/src/services/database/database-table.service.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/services/database/database-table.service.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/services/database/database-table.service.ts
🧠 Learnings (1)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/**/*.{ts,js} : Implement proper database indexing

Applied to files:

  • backend/src/services/database/database-table.service.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: build-and-push
  • GitHub Check: E2E Tests
  • GitHub Check: CI Pre-merge Check
🔇 Additional comments (5)
backend/src/services/database/database-table.service.ts (5)

232-238: LGTM!

The trigger function reference correctly uses the schema-qualified name system.update_updated_at(), aligning with the schema rework that moves system utilities to the system schema.


651-658: LGTM!

The quoteTableReference method correctly handles the cross-schema reference for auth.users by properly quoting both schema and table components separately ("auth"."users"). The explicit allowlist approach is secure and prevents arbitrary cross-schema references.


691-701: LGTM!

The constraint naming correctly sanitizes auth.users to auth_users to avoid dots in PostgreSQL constraint names, which improves compatibility and avoids potential issues with constraint manipulation. The quoteTableReference usage ensures proper cross-schema FK references.


704-728: LGTM!

The addition of foreign_schema to the FK constraints query is essential for properly identifying cross-schema references. The query correctly uses parameterized input and efficiently retrieves all necessary FK metadata in a single database round trip.


734-747: Type safety for ForeignKeyRow is properly maintained.

The ForeignKeyRow interface in backend/src/types/database.ts includes the foreign_schema property (line 105), confirming that the cross-schema reference logic at lines 735-739 is type-safe. The schema-aware table name prefixing correctly handles both public and non-public schemas without type concerns.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

♻️ Duplicate comments (1)
frontend/src/features/database/components/ForeignKeyCell.tsx (1)

21-59: TanStack Query key doesn’t align with invalidation (stale cache risk)

Per useUsers invalidation (invalidateQueries({ queryKey: ['users'] })), queryKey: ['user', searchValue] won’t be invalidated and can go stale.

Suggested diff:

 const { data: authUserData, error: authUserError } = useQuery({
-  queryKey: ['user', searchValue],
+  queryKey: ['users', searchValue],
   queryFn: () => getUser(searchValue),
   enabled: isAuthUsers && open && !!value,
 });
🧹 Nitpick comments (2)
frontend/src/features/database/components/LinkRecordModal.tsx (1)

50-77: Auth users integration is pragmatic; consider an explicit adapter instead of unknown casts

users as unknown as DatabaseRecord[] works but is brittle if the users API shape diverges from authUsersSchema/DataGrid expectations. Consider mapping to a DatabaseRecord explicitly (at least ensuring id and displayed columns exist).

Also applies to: 88-110

frontend/src/features/auth/components/UsersDataGrid.tsx (1)

241-241: Consider extracting magic number to a named constant.

The selectionColumnWidth is hardcoded to 180. While this appears intentional for the users grid layout, extracting it to a named constant would improve maintainability and make the intent clearer.

Apply this diff:

+// Selection column width to accommodate checkbox + avatar + name
+const SELECTION_COLUMN_WIDTH = 180;
+
 // Specialized DataGrid for users
 export function UsersDataGrid(props: UsersDataGridProps) {
   const columns = useMemo(() => createUsersColumns(), []);

   return (
     <DataGrid<UserDataGridRow>
       {...props}
       columns={columns}
       showSelection={true}
       showPagination={true}
       showTypeBadge={false}
-      selectionColumnWidth={180}
+      selectionColumnWidth={SELECTION_COLUMN_WIDTH}
       renderSelectionCell={UserSelectionCell}
     />
   );
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e3aa1b0 and e4d714c.

📒 Files selected for processing (5)
  • frontend/src/features/auth/components/UsersDataGrid.tsx (5 hunks)
  • frontend/src/features/database/components/ForeignKeyCell.tsx (5 hunks)
  • frontend/src/features/database/components/ForeignKeyPopover.tsx (2 hunks)
  • frontend/src/features/database/components/LinkRecordModal.tsx (2 hunks)
  • frontend/src/features/database/constants.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/features/database/constants.ts
🧰 Additional context used
📓 Path-based instructions (8)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
frontend/src/**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

frontend/src/**/*.{tsx,jsx}: Use functional components with hooks exclusively in React
Implement proper TypeScript interfaces for all props in React components
Use React Hook Form for form handling in frontend
Follow component composition patterns in React
Implement proper loading and error states in React components
Keep components focused and single-purpose in React
Use Radix UI primitives for accessibility in frontend
Use appropriate loading skeletons for data fetching in frontend
Display clear error messages with actionable feedback in frontend
Implement proper form validation with inline errors in frontend
Use consistent icon set from lucide-react
Optimize React component re-renders

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
frontend/src/**/*.{tsx,jsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

frontend/src/**/*.{tsx,jsx,ts}: Use TanStack Query for server state management in frontend
Use lazy loading for code splitting
Optimize bundle size with proper imports

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
frontend/src/**/*.{tsx,jsx,css}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Maintain consistent color scheme using CSS variables

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
{backend/src/{api,controllers},frontend/src/**}/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src/{api,controllers},frontend/src/**}/*.{ts,tsx,js,jsx}: Validate all user inputs
Use pagination for large data sets

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
🧠 Learnings (9)
📚 Learning: 2025-11-20T00:54:00.807Z
Learnt from: HMaan0
Repo: InsForge/InsForge PR: 607
File: frontend/src/components/datagrid/index.ts:1-23
Timestamp: 2025-11-20T00:54:00.807Z
Learning: In react-data-grid v7.0.0-beta.47, the type for cell click handler arguments is named `CellClickArgs`. This was renamed to `CellMouseArgs` in later beta releases (after beta.47). When reviewing barrel exports or type re-exports from react-data-grid, verify the specific version being used before suggesting type name changes.

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}} : Use Zod schemas for request/response validation in backend

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx} : Use consistent icon set from lucide-react

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx} : Use functional components with hooks exclusively in React

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx} : Use React Hook Form for form handling in frontend

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx,ts} : Use TanStack Query for server state management in frontend

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.ts : Name hook files with 'use' prefix in PascalCase (e.g., useAuth.ts)

Applied to files:

  • frontend/src/features/database/components/LinkRecordModal.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/{api,controllers},frontend/src/**}/*.{ts,tsx,js,jsx} : Use pagination for large data sets

Applied to files:

  • frontend/src/features/database/components/LinkRecordModal.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/components/**/*.tsx : Name component files in PascalCase (e.g., DataGrid.tsx)

Applied to files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
🧬 Code graph analysis (3)
frontend/src/features/database/components/ForeignKeyPopover.tsx (1)
frontend/src/features/database/constants.ts (1)
  • AUTH_USERS_TABLE (5-5)
frontend/src/features/database/components/LinkRecordModal.tsx (4)
frontend/src/features/database/constants.ts (2)
  • AUTH_USERS_TABLE (5-5)
  • authUsersSchema (8-18)
frontend/src/features/database/hooks/useRecords.ts (1)
  • useRecords (6-139)
frontend/src/features/auth/hooks/useUsers.ts (1)
  • useUsers (11-95)
frontend/src/components/datagrid/datagridTypes.tsx (1)
  • DatabaseRecord (37-39)
frontend/src/features/auth/components/UsersDataGrid.tsx (6)
frontend/src/components/datagrid/index.ts (3)
  • RenderCellProps (10-10)
  • DataGridProps (6-6)
  • SelectionCellProps (6-6)
frontend/src/features/auth/components/index.ts (1)
  • UsersDataGridProps (5-5)
frontend/src/components/datagrid/DataGrid.tsx (2)
  • DataGridProps (28-53)
  • SelectionCellProps (20-25)
frontend/src/components/Checkbox.tsx (1)
  • Checkbox (16-59)
frontend/src/lib/contexts/AuthContext.tsx (1)
  • User (6-12)
frontend/src/lib/utils/utils.ts (1)
  • cn (19-21)
🔇 Additional comments (2)
frontend/src/features/database/components/ForeignKeyCell.tsx (1)

38-75: Auth users special-casing + navigation looks consistent

The isAuthUsers split (schema + data source) and “Open Users” navigation path are clear and keep the non-auth flow intact.

Also applies to: 168-184

frontend/src/features/auth/components/UsersDataGrid.tsx (1)

101-126: No action needed. The providers field is explicitly defined in UserSchema (as z.array(z.string()).optional() in auth.schema.ts line 39) and is properly typed as string[] | undefined. The component's defensive checks on line 104 (if (!providers || !Array.isArray(providers) || !providers.length)) correctly handle all cases: undefined, null, non-array, and empty array. The implementation is type-safe and robust.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
backend/src/api/routes/auth/index.routes.ts (2)

221-233: Consider performance impact of additional database query.

The handler now fetches the full user object from the database on every request. If this endpoint is called frequently (e.g., on page loads or token refresh), this could impact performance.

Consider:

  • Enriching req.user during token verification to include the full user object
  • Implementing a caching strategy for user data
  • Monitoring query performance metrics for this endpoint

Based on coding guidelines emphasizing performance monitoring and the need to align with the new schema structure, this change trades performance for data freshness and schema consistency.


290-290: Inconsistent error message wording.

Line 229 uses "User not found" while this line uses "User does not exist" for similar scenarios. Consider using consistent wording across the codebase.

Apply this diff for consistency:

-        throw new AppError('User does not exist', 404, ERROR_CODES.NOT_FOUND);
+        throw new AppError('User not found', 404, ERROR_CODES.NOT_FOUND);
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e4d714c and 4808462.

📒 Files selected for processing (5)
  • backend/src/api/routes/auth/index.routes.ts (2 hunks)
  • backend/src/api/routes/email/index.routes.ts (1 hunks)
  • openapi/email.yaml (2 hunks)
  • shared-schemas/src/auth-api.schema.ts (1 hunks)
  • shared-schemas/src/email-api.schema.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • shared-schemas/src/email-api.schema.ts
  • backend/src/api/routes/email/index.routes.ts
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • shared-schemas/src/email-api.schema.ts
  • backend/src/api/routes/email/index.routes.ts
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/api/routes/auth/index.routes.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • shared-schemas/src/email-api.schema.ts
  • backend/src/api/routes/email/index.routes.ts
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/api/routes/auth/index.routes.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/api/routes/email/index.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
backend/src/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/api/**/*.{ts,js}: Implement proper middleware for authentication and error handling
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/email/index.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
backend/src/{controllers,api}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Return consistent API responses using utility functions

Files:

  • backend/src/api/routes/email/index.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/api/routes/email/index.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
backend/src/{api,core,controllers}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper authentication and authorization

Files:

  • backend/src/api/routes/email/index.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/api/routes/email/index.routes.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend/src/api,openapi}/**/*.{ts,yaml,yml,json}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Document all API endpoints with clear descriptions

Files:

  • backend/src/api/routes/email/index.routes.ts
  • openapi/email.yaml
  • backend/src/api/routes/auth/index.routes.ts
🧠 Learnings (4)
📚 Learning: 2025-12-12T22:31:18.410Z
Learnt from: tonychang04
Repo: InsForge/InsForge PR: 639
File: backend/src/api/routes/email/index.routes.ts:28-28
Timestamp: 2025-12-12T22:31:18.410Z
Learning: In the InsForge codebase, new API endpoints intentionally return empty objects `{}` for forward compatibility, allowing fields to be added later without breaking existing clients. The shared-schemas package defines corresponding empty object schemas (e.g., SendEmailResponse) for this purpose.

Applied to files:

  • shared-schemas/src/email-api.schema.ts
  • backend/src/api/routes/email/index.routes.ts
  • openapi/email.yaml
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}} : Use Zod schemas for request/response validation in backend

Applied to files:

  • shared-schemas/src/email-api.schema.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement proper middleware for authentication and error handling

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
🧬 Code graph analysis (3)
backend/src/api/routes/email/index.routes.ts (1)
backend/src/utils/response.ts (1)
  • successResponse (22-24)
shared-schemas/src/auth-api.schema.ts (1)
shared-schemas/src/auth.schema.ts (1)
  • userSchema (35-43)
backend/src/api/routes/auth/index.routes.ts (3)
backend/src/api/middlewares/auth.ts (1)
  • AuthRequest (7-16)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
shared-schemas/src/auth-api.schema.ts (1)
  • GetCurrentSessionResponse (326-326)
🔇 Additional comments (4)
shared-schemas/src/auth-api.schema.ts (1)

178-178: LGTM! Good consolidation to shared schema.

Using the shared userSchema instead of an inline definition ensures consistency across API responses and reduces duplication.

backend/src/api/routes/email/index.routes.ts (1)

28-28: LGTM! Response updated for forward compatibility.

The change from { success: true } to an empty object {} aligns with the codebase pattern for forward compatibility. This allows fields to be added later without breaking existing clients.

Based on learnings, this is an intentional design choice consistent with the shared-schemas package and OpenAPI specification.

openapi/email.yaml (1)

28-28: LGTM! SendEmailResponse schema properly defined.

The introduction of the SendEmailResponse schema as an empty object with clear documentation about forward compatibility is well-executed. This aligns with both the backend implementation and the shared schemas.

Based on learnings, this design allows for future extensibility without breaking existing API clients.

Also applies to: 132-135

shared-schemas/src/email-api.schema.ts (1)

23-30: LGTM! Response schema properly defined with clear documentation.

The sendEmailResponseSchema and SendEmailResponse type are correctly defined using Zod with clear documentation explaining the forward compatibility intent. The schema is properly exported from the shared-schemas package index via the barrel export in index.ts, ensuring it's available to consumers.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
backend/src/services/auth/auth.service.ts (2)

238-263: Email templates still read name from metadata, ignoring new profile field

In all email flows (sendVerificationEmailWithCode/Link, sendResetPasswordEmailWithCode/Link), userName is derived from dbUser.metadata?.name || 'User', but:

  • New registrations/OAuth users store names in profile, not metadata.
  • Migration 018 also populates profile (not metadata) with name.

Result: greetings for new users will almost always fall back to 'User'.

Recommend preferring profile with a metadata fallback, e.g.:

-    const userName = dbUser.metadata?.name || 'User';
+    const profile = (dbUser.profile as { name?: string } | null) || null;
+    const metadata = (dbUser.metadata as { name?: string } | null) || null;
+    const userName = profile?.name || metadata?.name || 'User';

Apply the same pattern in all four email helper methods.

Also applies to: 270-298, 436-461, 468-496


980-1004: Core user queries don’t select profile and search still targets metadata.name

Issues:

  1. getUserByEmail, getUserById, and listUsers SELECT:

    • Don’t include u.profile, yet transformUserRecordToSchema returns profile: dbUser.profile.
    • So profile in all responses from login/register/listUsers/current-session will be undefined.
  2. listUsers search/count still filter on metadata->>'name', but:

    • Migration 018 and new writes store names under profile->>'name'.

This breaks name-based search for new users and leaves profile missing from main user responses.

-- getUserByEmail
       SELECT
         u.id,
         u.email,
+        u.profile,
         u.metadata,
         u.email_verified,
         u.is_project_admin,
         u.is_anonymous,
@@
-- getUserById
       SELECT
         u.id,
         u.email,
+        u.profile,
         u.metadata,
         u.email_verified,
         u.is_project_admin,
         u.is_anonymous,
@@
-- listUsers main query
       SELECT
         u.id,
         u.email,
-        u.metadata,
+        u.profile,
+        u.metadata,
@@
-      query += ` AND (u.email LIKE $1 OR u.metadata->>'name' LIKE $2)`;
+      query +=
+        ` AND (u.email LIKE $1 OR COALESCE(u.profile->>'name', u.metadata->>'name') LIKE $2)`;
@@
-    let countQuery =
-      'SELECT COUNT(*) as count FROM auth.users WHERE is_project_admin = false AND is_anonymous = false';
+    let countQuery =
+      'SELECT COUNT(*) as count FROM auth.users WHERE is_project_admin = false AND is_anonymous = false';
@@
-      countQuery += ` AND (email LIKE $1 OR metadata->>'name' LIKE $2)`;
+      countQuery +=
+        ` AND (email LIKE $1 OR COALESCE(profile->>'name', metadata->>'name') LIKE $2)`;
@@
   private transformUserRecordToSchema(dbUser: UserRecord): UserSchema {
@@
-    return {
+    return {
       id: dbUser.id,
       email: dbUser.email,
       emailVerified: dbUser.email_verified,
       createdAt: dbUser.created_at,
       updatedAt: dbUser.updated_at,
-      providers: providers,
-      profile: dbUser.profile,
-      metadata: dbUser.metadata,
+      providers,
+      profile: dbUser.profile ?? null,
+      metadata: dbUser.metadata ?? null,
     };

Also applies to: 1010-1034, 1070-1123

♻️ Duplicate comments (2)
backend/src/infra/database/migrations/018_schema-rework.sql (2)

94-150: Dynamic FK rewrite still assumes single-column foreign keys

The FK rewrite loop only tracks a single kcu.column_name and recreates FOREIGN KEY (%I) REFERENCES auth.users(id). Any composite FK referencing public.users will be dropped and recreated incorrectly (or not at all).

Consider either:

  • Explicitly supporting only single-column FKs: group by constraint, ensure COUNT(*) = 1, and RAISE EXCEPTION if not; or
  • Fully supporting composite FKs by aggregating columns with string_agg(quote_ident(kcu.column_name), ', ' ORDER BY kcu.ordinal_position) per constraint, and using that list when rebuilding the FK.
-    SELECT
-      tc.table_schema,
-      tc.table_name,
-      tc.constraint_name,
-      kcu.column_name,
+    SELECT
+      tc.table_schema,
+      tc.table_name,
+      tc.constraint_name,
+      string_agg(quote_ident(kcu.column_name), ', ' ORDER BY kcu.ordinal_position) AS column_names,
       rc.delete_rule,
       rc.update_rule
    ...
-      'ALTER TABLE %I.%I ADD CONSTRAINT %I FOREIGN KEY (%I) REFERENCES auth.users(id) ON DELETE %s ON UPDATE %s',
+      'ALTER TABLE %I.%I ADD CONSTRAINT %I FOREIGN KEY (%s) REFERENCES auth.users(id) ON DELETE %s ON UPDATE %s',
       fk_record.table_schema,
       fk_record.table_name,
       fk_record.constraint_name,
-      fk_record.column_name,
+      fk_record.column_names,
       fk_record.delete_rule,
       fk_record.update_rule

368-432: Event triggers can fail on duplicate project_admin_policy creation

Both system.create_default_policies and system.create_policies_after_rls unconditionally CREATE POLICY "project_admin_policy"; if the same table is processed multiple times, or the policy already exists, the DDL will error and abort.

Guard policy creation, e.g.:

  • Check pg_policies for (schemaname, tablename, policyname = 'project_admin_policy') before creating, or
  • Wrap CREATE POLICY in a BEGIN ... EXCEPTION WHEN duplicate_object THEN NULL; END block.

Apply the same safeguard in both functions.

-    IF has_rls THEN
-      EXECUTE format('CREATE POLICY "project_admin_policy" ON %s FOR ALL TO project_admin USING (true) WITH CHECK (true)', obj.object_identity);
-    END IF;
+    IF has_rls AND NOT EXISTS (
+      SELECT 1 FROM pg_policies
+      WHERE schemaname = table_schema
+        AND tablename = table_name
+        AND policyname = 'project_admin_policy'
+    ) THEN
+      EXECUTE format(
+        'CREATE POLICY "project_admin_policy" ON %s FOR ALL TO project_admin USING (true) WITH CHECK (true)',
+        obj.object_identity
+      );
+    END IF;
🧹 Nitpick comments (1)
backend/src/services/auth/auth.service.ts (1)

1184-1193: Consider preventing deletion of admin/anonymous system users

deleteUsers currently deletes any IDs provided:

DELETE FROM auth.users WHERE id IN (...)

Given new is_project_admin/is_anonymous flags, you may want to guard against accidentally deleting system/admin/anonymous accounts (or handle them separately).

-      `DELETE FROM auth.users WHERE id IN (${placeholders})`,
+      `DELETE FROM auth.users
+       WHERE id IN (${placeholders})
+         AND is_project_admin = false
+         AND is_anonymous = false`,
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 4808462 and c91b03b.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (7)
  • backend/src/api/routes/auth/index.routes.ts (5 hunks)
  • backend/src/infra/database/migrations/018_schema-rework.sql (1 hunks)
  • backend/src/services/auth/auth.service.ts (25 hunks)
  • backend/src/types/auth.ts (1 hunks)
  • shared-schemas/package.json (1 hunks)
  • shared-schemas/src/auth-api.schema.ts (4 hunks)
  • shared-schemas/src/auth.schema.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • shared-schemas/src/auth.schema.ts
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/types/auth.ts
  • backend/src/services/auth/auth.service.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • shared-schemas/src/auth.schema.ts
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/types/auth.ts
  • backend/src/services/auth/auth.service.ts
  • backend/src/api/routes/auth/index.routes.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • shared-schemas/src/auth.schema.ts
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/types/auth.ts
  • backend/src/services/auth/auth.service.ts
  • backend/src/api/routes/auth/index.routes.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/types/auth.ts
  • backend/src/services/auth/auth.service.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/types/auth.ts
  • backend/src/services/auth/auth.service.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/types/auth.ts
  • backend/src/services/auth/auth.service.ts
  • backend/src/api/routes/auth/index.routes.ts
backend/src/**/*.service.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Name service files in camelCase with .service.ts suffix (e.g., auth.service.ts)

Files:

  • backend/src/services/auth/auth.service.ts
backend/src/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/api/**/*.{ts,js}: Implement proper middleware for authentication and error handling
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/auth/index.routes.ts
backend/src/{controllers,api}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Return consistent API responses using utility functions

Files:

  • backend/src/api/routes/auth/index.routes.ts
backend/src/{api,core,controllers}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper authentication and authorization

Files:

  • backend/src/api/routes/auth/index.routes.ts
{backend/src/api,openapi}/**/*.{ts,yaml,yml,json}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Document all API endpoints with clear descriptions

Files:

  • backend/src/api/routes/auth/index.routes.ts
🧠 Learnings (4)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}} : Use Zod schemas for request/response validation in backend

Applied to files:

  • shared-schemas/src/auth-api.schema.ts
📚 Learning: 2025-12-12T22:31:18.410Z
Learnt from: tonychang04
Repo: InsForge/InsForge PR: 639
File: backend/src/api/routes/email/index.routes.ts:28-28
Timestamp: 2025-12-12T22:31:18.410Z
Learning: In the InsForge codebase, new API endpoints intentionally return empty objects `{}` for forward compatibility, allowing fields to be added later without breaking existing clients. The shared-schemas package defines corresponding empty object schemas (e.g., SendEmailResponse) for this purpose.

Applied to files:

  • shared-schemas/src/auth-api.schema.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/services/auth/auth.service.ts
  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement proper middleware for authentication and error handling

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
🧬 Code graph analysis (3)
shared-schemas/src/auth-api.schema.ts (1)
shared-schemas/src/auth.schema.ts (2)
  • userSchema (35-44)
  • userIdSchema (12-12)
backend/src/services/auth/auth.service.ts (1)
backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js (2)
  • client (32-32)
  • pool (29-29)
backend/src/api/routes/auth/index.routes.ts (6)
backend/src/infra/security/token.manager.ts (1)
  • verifyToken (85-96)
backend/src/api/middlewares/auth.ts (2)
  • verifyToken (156-199)
  • AuthRequest (7-16)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
shared-schemas/src/auth-api.schema.ts (3)
  • updateProfileRequestSchema (70-72)
  • GetProfileResponse (343-343)
  • GetCurrentSessionResponse (342-342)
backend/src/utils/response.ts (1)
  • successResponse (22-24)
shared-schemas/src/auth.schema.ts (1)
  • userIdSchema (12-12)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: E2E Tests
  • GitHub Check: CI Pre-merge Check
🔇 Additional comments (12)
backend/src/infra/database/migrations/018_schema-rework.sql (3)

68-93: Profile migration logic looks consistent with new model

Adding profile/metadata and populating profile from public.users and fallback auth.users.name (with guards for empty profiles) avoids clobbering existing metadata and matches the new “profile vs metadata” semantics.


298-360: Shared system.update_updated_at trigger consolidation looks good

Centralizing updated_at handling into system.update_updated_at() and rewiring the triggers on system/auth/functions/realtime tables simplifies maintenance and avoids duplicated trigger functions.


188-212: RLS + GRANT configuration for auth.users requires manual verification

The proposed configuration (GRANT USAGE on schema, column-level SELECT/UPDATE restrictions, and row-level policies) follows a reasonable separation of concerns, but verification is needed:

  • Confirm auth.uid() function exists in migration 013 and works as expected
  • Validate that the row-level policy conditions correctly enforce self-update restrictions
  • Confirm intentionality of public column access (id, profile, created_at)
shared-schemas/package.json (1)

3-3: Version bump is straightforward

Incrementing @insforge/shared-schemas to 1.1.29 is consistent with the added auth/profile schema changes elsewhere in the PR.

backend/src/types/auth.ts (1)

3-15: UserRecord shape matches new auth.users structure

Adding profile, metadata, is_project_admin, and is_anonymous to UserRecord aligns with the new auth.users table and downstream UserSchema transformation.

shared-schemas/src/auth.schema.ts (1)

32-44: Public user schema aligns with new profile/metadata model

Exposing providers?, profile, and metadata while omitting internal flags (is_project_admin, is_anonymous) gives a clean public shape that matches what AuthService intends to return.

shared-schemas/src/auth-api.schema.ts (1)

67-72: Profile request/response schemas are consistent with backend contracts

  • updateProfileRequestSchema wraps profile in a top-level profile object, matching AuthService.updateProfile(userId, profile).
  • getCurrentSessionResponseSchema now returns full userSchema, aligning with getUserSchemaById.
  • getProfileResponseSchema/GetProfileResponse mirror { id, profile } from the service.

Also applies to: 184-194, 315-343

backend/src/api/routes/auth/index.routes.ts (3)

73-103: PATCH /profiles/current wiring looks correct

Auth, body validation via updateProfileRequestSchema, and delegation to authService.updateProfile all line up with the new GetProfileResponse type. Error handling is consistent with other routes.


330-347: GET /users/:userId admin endpoint matches new naming and error semantics

Path param rename to userId, direct validation using userIdSchema, and 404 'User does not exist' are sensible; response mirrors UserSchema from getUserSchemaById.


273-297: GET /sessions/current now requires a user record in auth.users; anonymous and admin tokens will receive 401

The endpoint will reject any token without a corresponding auth.users row. Anonymous tokens (role: 'anon', ID: 12345678-1234-5678-90ab-cdef12345678) and admin tokens (role: 'project_admin', ID: project-admin-with-api-key) both pass through the verifyToken middleware but lack database user records, so they will receive a 'User not found' 401 error. Confirm this behavior is intentional.

backend/src/services/auth/auth.service.ts (2)

112-187: Profile population for password/OAuth/admin users is coherent

  • register now writes profile JSON from the optional name argument.
  • createThirdPartyUser stores { name, avatar_url } in profile and propagates avatar into user_providers.provider_data.
  • Admin login paths return a UserSchema with profile: { name: 'Administrator' } and metadata: null.

All of these align with the new auth.users columns and exported UserSchema.

Also applies to: 773-806, 822-830, 595-622, 627-653


1136-1179: The review comment is incorrect; updateProfile works as written.

The pg library (v8.16.3) automatically serializes plain JavaScript objects to JSON when passed as parameters for json/jsonb columns. Passing a plain object to $1::jsonb works correctly without explicit JSON.stringify(). The web search confirms: "pg will call JSON.stringify on the outbound object" automatically during parameter binding.

The code pattern appears consistently throughout the service (lines 136, 803, 1165) and requires no changes.

Likely an incorrect or invalid review comment.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (2)
frontend/src/features/auth/components/UsersDataGrid.tsx (2)

191-199: Avoid trusting row.profile shape via as casts; add a small guard or stronger typing.

Right now row.profile is force-cast and fields are then asserted as strings:

const profile = row.profile as Record<string, unknown> | null;
const avatarUrl = profile?.avatar_url as string | undefined;
const name = profile?.name as string | undefined;

If the backend type for profile ever diverges (e.g., profile is null, a primitive, or has non-string fields), TypeScript will not help you catch it, and you may end up passing unexpected values into the UI.

Consider either:

  • Tightening the UserSchema/UserDataGridRow typing so profile is a proper { avatar_url?: string; name?: string } | null, or
  • Adding a tiny runtime guard that checks typeof profile === 'object' and typeof (profile as any).avatar_url === 'string' / name === 'string' before using those values, falling back to undefined otherwise.

This keeps the grid more robust to schema drift without much extra code.


201-228: Handle avatar load failures and memoize UserSelectionCell to reduce re-renders.

Two improvements here (same as previously noted):

  1. Avatar error handling
    If avatarUrl is invalid, the <img> will show a broken icon. Track an avatarError state and fall back to the placeholder when loading fails.

  2. Memoization
    UserSelectionCell renders for every row; wrapping it in memo avoids unnecessary re-renders when props are stable.

You can do this within this component block:

-const UserSelectionCell = ({
-  row,
-  isSelected,
-  onToggle,
-  tabIndex,
-}: SelectionCellProps<UserDataGridRow>) => {
-  const profile = row.profile as Record<string, unknown> | null;
-  const avatarUrl = profile?.avatar_url as string | undefined;
-  const name = profile?.name as string | undefined;
+const UserSelectionCell = memo(({
+  row,
+  isSelected,
+  onToggle,
+  tabIndex,
+}: SelectionCellProps<UserDataGridRow>) => {
+  const profile = row.profile as Record<string, unknown> | null;
+  const avatarUrl = profile?.avatar_url as string | undefined;
+  const name = profile?.name as string | undefined;
+  const [avatarError, setAvatarError] = useState(false);
@@
-      <div className="flex items-center gap-2 min-w-0 flex-1">
-        {avatarUrl ? (
+      <div className="flex items-center gap-2 min-w-0 flex-1">
+        {avatarUrl && !avatarError ? (
           <img
             src={avatarUrl}
             alt={name || 'User avatar'}
             className="w-6 h-6 rounded-full object-cover flex-shrink-0"
+            onError={() => setAvatarError(true)}
           />
@@
-    </div>
-  );
-};
+    </div>
+  );
+});
+
+UserSelectionCell.displayName = 'UserSelectionCell';

And update the React import accordingly (exact form depends on your preferred style), for example:

import { useMemo, useState, memo } from 'react';

This gives a clean fallback for broken avatars and a small performance win on large tables.

🧹 Nitpick comments (2)
backend/src/services/auth/auth.service.ts (1)

684-757: Consider wrapping OAuth operations in transactions for consistency.

The OAuth login and linking flows perform multiple database operations (updating timestamps, linking providers, setting email_verified) without an explicit transaction wrapper. While the operations are largely idempotent and low-risk, wrapping them in transactions would ensure atomicity.

Example for the existing-provider path (lines 692-701):

     if (account) {
       // Found existing OAuth user, update last login time
+      const client = await pool.connect();
+      try {
+        await client.query('BEGIN');
+
-      await pool.query(
+        await client.query(
           'UPDATE auth.user_providers SET updated_at = CURRENT_TIMESTAMP WHERE provider = $1 AND provider_account_id = $2',
           [provider, providerId]
         );

         // Update email_verified to true if not already verified (OAuth login means email is trusted)
-        await pool.query(
+        await client.query(
           'UPDATE auth.users SET email_verified = true WHERE id = $1 AND email_verified = false',
           [account.user_id]
         );
+
+        await client.query('COMMIT');
+      } catch (error) {
+        await client.query('ROLLBACK');
+        throw error;
+      } finally {
+        client.release();
+      }

       const dbUser = await this.getUserById(account.user_id);

Similar pattern could be applied to lines 726-741 for the email-matching path.

frontend/src/features/auth/components/UsersDataGrid.tsx (1)

101-126: ProvidersCellRenderer behavior is sound; consider tiny key/title refinements.

Logic for handling empty providers, deduping via new Set, and showing a +N badge looks correct and matches the new schema shape.

Two small, optional tweaks:

  • Use uniqueProviders.join(', ') in the title so the tooltip matches the visible set.
  • Use key={provider} instead of key={index} for slightly more stable React keys (providers appear to be unique identifiers).

These are minor polish; current code is functionally fine.

Also applies to: 150-156

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c91b03b and 67b624f.

📒 Files selected for processing (3)
  • backend/src/api/routes/auth/oauth.routes.ts (2 hunks)
  • backend/src/services/auth/auth.service.ts (25 hunks)
  • frontend/src/features/auth/components/UsersDataGrid.tsx (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/api/routes/auth/oauth.routes.ts
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/services/auth/auth.service.ts
frontend/src/**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

frontend/src/**/*.{tsx,jsx}: Use functional components with hooks exclusively in React
Implement proper TypeScript interfaces for all props in React components
Use React Hook Form for form handling in frontend
Follow component composition patterns in React
Implement proper loading and error states in React components
Keep components focused and single-purpose in React
Use Radix UI primitives for accessibility in frontend
Use appropriate loading skeletons for data fetching in frontend
Display clear error messages with actionable feedback in frontend
Implement proper form validation with inline errors in frontend
Use consistent icon set from lucide-react
Optimize React component re-renders

Files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
frontend/src/**/*.{tsx,jsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

frontend/src/**/*.{tsx,jsx,ts}: Use TanStack Query for server state management in frontend
Use lazy loading for code splitting
Optimize bundle size with proper imports

Files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/services/auth/auth.service.ts
frontend/src/**/*.{tsx,jsx,css}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Maintain consistent color scheme using CSS variables

Files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/services/auth/auth.service.ts
{backend/src/{api,controllers},frontend/src/**}/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src/{api,controllers},frontend/src/**}/*.{ts,tsx,js,jsx}: Validate all user inputs
Use pagination for large data sets

Files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/services/auth/auth.service.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/services/auth/auth.service.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/services/auth/auth.service.ts
backend/src/**/*.service.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Name service files in camelCase with .service.ts suffix (e.g., auth.service.ts)

Files:

  • backend/src/services/auth/auth.service.ts
🧠 Learnings (5)
📚 Learning: 2025-11-20T00:54:00.807Z
Learnt from: HMaan0
Repo: InsForge/InsForge PR: 607
File: frontend/src/components/datagrid/index.ts:1-23
Timestamp: 2025-11-20T00:54:00.807Z
Learning: In react-data-grid v7.0.0-beta.47, the type for cell click handler arguments is named `CellClickArgs`. This was renamed to `CellMouseArgs` in later beta releases (after beta.47). When reviewing barrel exports or type re-exports from react-data-grid, verify the specific version being used before suggesting type name changes.

Applied to files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/components/**/*.tsx : Name component files in PascalCase (e.g., DataGrid.tsx)

Applied to files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx} : Implement proper loading and error states in React components

Applied to files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx} : Use consistent icon set from lucide-react

Applied to files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/services/auth/auth.service.ts
🧬 Code graph analysis (1)
backend/src/services/auth/auth.service.ts (1)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: build-and-push
  • GitHub Check: CI Pre-merge Check
  • GitHub Check: E2E Tests
🔇 Additional comments (7)
backend/src/services/auth/auth.service.ts (5)

133-138: LGTM! Profile creation migrated correctly.

The register method correctly creates the JSONB profile structure for the new auth.users schema. The conditional logic ensures profile is populated with name when provided, falling back to an empty object.


259-260: LGTM! Safe profile access for email personalization.

The optional chaining (dbUser.profile?.name) with fallback to 'User' is the correct pattern for accessing the JSONB profile structure. This prevents runtime errors and provides good user experience in email templates.

Also applies to: 294-295, 457-458, 492-493


1072-1126: LGTM! User listing with proper schema filtering.

The listUsers method correctly:

  • Uses schema-qualified table names (auth.users, auth.user_providers)
  • Filters out admin and anonymous users using new schema flags
  • Implements search using JSONB extraction (profile->>'name')
  • Uses parameterized queries with proper dynamic parameter indexing
  • Aggregates providers using STRING_AGG

980-1067: LGTM! Helper methods updated for new schema.

The getUserByEmail, getUserById, and transformUserRecordToSchema methods correctly handle the new schema structure:

  • Select new JSONB fields (profile, metadata) and boolean flags (is_project_admin, is_anonymous)
  • Use schema-qualified table names
  • PostgreSQL's pg driver automatically parses JSONB to JavaScript objects
  • Provider aggregation pattern is appropriate

1139-1182: LGTM! Profile management methods implemented correctly with proper API validation.

The new getProfileById and updateProfile methods properly support the profile-centric user schema:

  • getProfileById returns only public profile data (id and profile)
  • updateProfile uses PostgreSQL's JSONB merge operator (||) with COALESCE to safely handle null profiles
  • Proper error handling and parameterized queries

The API layer validates profile structure using the Zod schema updateProfileRequestSchema before calling updateProfile, with comprehensive error handling for invalid input.

frontend/src/features/auth/components/UsersDataGrid.tsx (2)

2-11: New imports for selection cell UI are correct and aligned with conventions.

User from lucide-react, Checkbox, and SelectionCellProps are all used below and match the new custom selection cell design; no issues here, and using lucide-react keeps the icon set consistent.

Based on learnings, lucide-react is the preferred icon set in this repo.


185-188: Encapsulating selection column config in UsersDataGrid is good; verify call sites.

Omitting 'selectionColumnWidth' | 'renderSelectionCell' from UsersDataGridProps and hard-wiring selectionColumnWidth={180} and renderSelectionCell={UserSelectionCell} makes the selection UX consistent and prevents external overrides.

Just confirm no existing UsersDataGrid consumers relied on customizing these props; TypeScript should already flag such usages if they exist.

Also applies to: 241-242

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (2)
auth/src/pages/SignUpPage.tsx (1)

32-34: Log the error object for better debugging.

The catch block logs a message but not the actual error object, which contains valuable debugging information such as stack traces.

Apply this diff to include the error in the log:

-          } catch {
-            console.error('Failed to redirect to final URL');
+          } catch (error) {
+            console.error('Failed to redirect to final URL:', error);
           }
shared-schemas/src/auth-api.schema.ts (1)

68-73: Consider using profileSchema for update validation.

The updateProfileRequestSchema uses z.record(z.unknown()) which accepts any object, while the profileSchema defines specific fields (name, avatar_url) with validation (e.g., URL format for avatar_url). This means invalid avatar URLs would be accepted on update but potentially rejected or malformed on read.

Consider using a partial profile schema for consistency:

 export const updateProfileRequestSchema = z.object({
-  profile: z.record(z.unknown()),
+  profile: profileSchema.partial(),
 });

This maintains extensibility via .passthrough() while validating known fields.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 67b624f and 2b1afcd.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (6)
  • auth/src/lib/broadcastService.ts (2 hunks)
  • auth/src/pages/SignInPage.tsx (1 hunks)
  • auth/src/pages/SignUpPage.tsx (1 hunks)
  • shared-schemas/package.json (1 hunks)
  • shared-schemas/src/auth-api.schema.ts (5 hunks)
  • shared-schemas/src/auth.schema.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • shared-schemas/package.json
🧰 Additional context used
📓 Path-based instructions (3)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • auth/src/pages/SignInPage.tsx
  • auth/src/pages/SignUpPage.tsx
  • auth/src/lib/broadcastService.ts
  • shared-schemas/src/auth-api.schema.ts
  • shared-schemas/src/auth.schema.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • auth/src/pages/SignInPage.tsx
  • auth/src/pages/SignUpPage.tsx
  • auth/src/lib/broadcastService.ts
  • shared-schemas/src/auth-api.schema.ts
  • shared-schemas/src/auth.schema.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • shared-schemas/src/auth-api.schema.ts
  • shared-schemas/src/auth.schema.ts
🧠 Learnings (3)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.ts : Name hook files with 'use' prefix in PascalCase (e.g., useAuth.ts)

Applied to files:

  • auth/src/pages/SignInPage.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}} : Use Zod schemas for request/response validation in backend

Applied to files:

  • shared-schemas/src/auth-api.schema.ts
  • shared-schemas/src/auth.schema.ts
📚 Learning: 2025-12-12T22:31:18.410Z
Learnt from: tonychang04
Repo: InsForge/InsForge PR: 639
File: backend/src/api/routes/email/index.routes.ts:28-28
Timestamp: 2025-12-12T22:31:18.410Z
Learning: In the InsForge codebase, new API endpoints intentionally return empty objects `{}` for forward compatibility, allowing fields to be added later without breaking existing clients. The shared-schemas package defines corresponding empty object schemas (e.g., SendEmailResponse) for this purpose.

Applied to files:

  • shared-schemas/src/auth-api.schema.ts
🧬 Code graph analysis (2)
auth/src/lib/broadcastService.ts (1)
shared-schemas/src/auth.schema.ts (1)
  • UserSchema (133-133)
shared-schemas/src/auth-api.schema.ts (1)
shared-schemas/src/auth.schema.ts (3)
  • userSchema (47-56)
  • userIdSchema (12-12)
  • profileSchema (32-38)
🪛 GitHub Actions: Lint and Format Check
auth/src/lib/broadcastService.ts

[error] 1-1: Cannot find module '@insforge/shared-schemas' or its corresponding type declarations.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: E2E Tests
  • GitHub Check: CI Pre-merge Check
🔇 Additional comments (6)
auth/src/lib/broadcastService.ts (2)

13-13: Type migration to UserSchema looks good.

Using the shared UserSchema type ensures consistency across the codebase. Note that consumers of BroadcastEvent will need to access user name via user.profile?.name instead of the previous user.name.


1-2: No module resolution issue exists. The @insforge/shared-schemas dependency is properly declared in auth/package.json (version ^1.1.23), the package is correctly configured with exports pointing to its built types, and the pnpm workspace setup is correct. UserSchema is properly exported from the shared-schemas package and should resolve without issues.

Likely an incorrect or invalid review comment.

shared-schemas/src/auth.schema.ts (2)

28-38: Schema design with .passthrough() is appropriate for extensibility.

The profileSchema correctly uses .passthrough() to allow custom profile fields beyond name and avatar_url. The snake_case documentation and eslint-disable comment are properly placed. This aligns well with the PR objective of supporting flexible user metadata.


44-56: User schema migration looks correct.

The restructuring from flat name/identities/providerType to providers/profile/metadata properly supports the new auth.users table structure. The use of .nullable() for profile and metadata correctly represents PostgreSQL NULL values, while .optional() for providers allows the field to be omitted in API responses.

shared-schemas/src/auth-api.schema.ts (2)

189-195: Profile response schema design is appropriate.

The getProfileResponseSchema correctly exposes only id and profile, keeping sensitive user data (email, metadata) private. This is a good privacy-conscious design for public profile endpoints.


185-195: Verify if role field should be included in the session response.

The getCurrentSessionResponseSchema uses userSchema, which does not include a role field. However, there are no usages of user.role in the codebase, so the claim about a breaking change cannot be verified. If the session response should include the user's role for authorization purposes, that's a valid schema design consideration—but it's separate from the breaking change concern. Consider whether role should be added to userSchema or the session response based on API requirements.

Comment thread auth/src/pages/SignInPage.tsx Resolved
Comment thread auth/src/pages/SignUpPage.tsx Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2b1afcd and 0e75399.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (2)
  • auth/package.json (0 hunks)
  • auth/tsconfig.json (1 hunks)
💤 Files with no reviewable changes (1)
  • auth/package.json
🧰 Additional context used
🧠 Learnings (5)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}} : Use Zod schemas for request/response validation in backend

Applied to files:

  • auth/tsconfig.json
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.ts : Name hook files with 'use' prefix in PascalCase (e.g., useAuth.ts)

Applied to files:

  • auth/tsconfig.json
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • auth/tsconfig.json
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/**/*.service.ts : Name service files in camelCase with .service.ts suffix (e.g., auth.service.ts)

Applied to files:

  • auth/tsconfig.json
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Use ES modules (import/export syntax)

Applied to files:

  • auth/tsconfig.json
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: lint-and-format
  • GitHub Check: E2E Tests
  • GitHub Check: CI Pre-merge Check

Comment thread auth/tsconfig.json Resolved
@tonychang04

Copy link
Copy Markdown
Member

upgrade from old proj 1.0.0 -> 1.3.0

EXISTS public.reload_postgrest_schema();
DROP FUNCTION IF EXISTS public.update_updated_at_column();
DROP FUNCTION IF EXISTS realtime.update_updated_at();
;
error: cannot drop function uid() because other objects depend on it

Rolling back attempted migration ...
error: cannot drop function uid() because other objects depend on it
at /app/node_modules/pg/lib/client.js:545:17
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Object.query (file:///app/node_modules/node-pg-migrate/dist/bundle/index.js:3499:14)
at async runner (file:///app/node_modules/node-pg-migrate/dist/bundle/index.js:3806:9) {
length: 278,
severity: 'ERROR',
code: '2BP01',
detail: 'policy Enable insert for authenticated users on table scores depends on function uid()',
hint: 'Use DROP ... CASCADE to drop the dependent objects too.',
position: undefined,
internalPosition: undefined,
internalQuery: undefined,
where: undefined,
schema: undefined,
table: undefined,
column: undefined,
dataType: undefined,
constraint: undefined,
file: 'dependency.c',
line: '1196',
routine: 'reportDependentObjects'
}

project creation failed with

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

♻️ Duplicate comments (1)
backend/src/infra/database/migrations/018_schema-rework.sql (1)

94-150: Dynamic FK rewrite only handles single-column FKs; composite FKs will be corrupted.

The loop captures a single column_name (line 108) and recreates the FK with only that column (line 136-143). For multi-column foreign keys referencing public.users, the loop iterates once per column, dropping and recreating the constraint multiple times with different single columns each time, resulting in a corrupted FK that references only the last column processed.

At minimum:

  • Filter to single-column FKs only by grouping by constraint and asserting COUNT(*) = 1, otherwise RAISE EXCEPTION to prevent silent corruption.
  • Better: fully support composite FKs by aggregating columns via string_agg(quote_ident(kcu.column_name), ', ' ORDER BY kcu.ordinal_position) grouped by constraint, then use the aggregated column list when building the ALTER TABLE ... ADD CONSTRAINT ... FOREIGN KEY (...) statement.
 DO $$
 DECLARE
   fk_record RECORD;
   drop_sql TEXT;
   create_sql TEXT;
 BEGIN
   -- Find all foreign keys that reference public.users
   FOR fk_record IN
     SELECT
       tc.table_schema,
       tc.table_name,
       tc.constraint_name,
-      kcu.column_name,
+      string_agg(quote_ident(kcu.column_name), ', ' ORDER BY kcu.ordinal_position) AS column_names,
       rc.delete_rule,
       rc.update_rule
     FROM information_schema.table_constraints tc
     JOIN information_schema.key_column_usage kcu
       ON tc.constraint_name = kcu.constraint_name
       AND tc.table_schema = kcu.table_schema
     JOIN information_schema.referential_constraints rc
       ON tc.constraint_name = rc.constraint_name
       AND tc.table_schema = rc.constraint_schema
     JOIN information_schema.constraint_column_usage ccu
       ON rc.unique_constraint_name = ccu.constraint_name
       AND rc.unique_constraint_schema = ccu.constraint_schema
     WHERE tc.constraint_type = 'FOREIGN KEY'
       AND ccu.table_schema = 'public'
       AND ccu.table_name = 'users'
+    GROUP BY tc.table_schema, tc.table_name, tc.constraint_name, rc.delete_rule, rc.update_rule
   LOOP
     -- Drop the old foreign key
     drop_sql := format(
       'ALTER TABLE %I.%I DROP CONSTRAINT IF EXISTS %I',
       fk_record.table_schema,
       fk_record.table_name,
       fk_record.constraint_name
     );
     EXECUTE drop_sql;

     -- Recreate with reference to auth.users
     create_sql := format(
-      'ALTER TABLE %I.%I ADD CONSTRAINT %I FOREIGN KEY (%I) REFERENCES auth.users(id) ON DELETE %s ON UPDATE %s',
+      'ALTER TABLE %I.%I ADD CONSTRAINT %I FOREIGN KEY (%s) REFERENCES auth.users(id) ON DELETE %s ON UPDATE %s',
       fk_record.table_schema,
       fk_record.table_name,
       fk_record.constraint_name,
-      fk_record.column_name,
+      fk_record.column_names,
       fk_record.delete_rule,
       fk_record.update_rule
     );
     EXECUTE create_sql;

     RAISE NOTICE 'Updated FK constraint % on %.% to reference auth.users',
       fk_record.constraint_name, fk_record.table_schema, fk_record.table_name;
   END LOOP;
 END $$;
🧹 Nitpick comments (2)
backend/src/infra/database/migrations/018_schema-rework.sql (2)

77-92: Profile updates overwrite instead of merge (defensive coding).

Lines 77-85 and 88-92 both use SET profile = ..., which overwrites any existing profile data. While profile is newly added at line 71, the IF NOT EXISTS clause means if the column already exists (partial re-run, or backported migration), existing profile keys would be lost.

Consider merging instead of replacing:

 UPDATE auth.users AS au
-SET profile = jsonb_strip_nulls(jsonb_build_object(
+SET profile = COALESCE(au.profile, '{}'::jsonb) || jsonb_strip_nulls(jsonb_build_object(
   'name', COALESCE(pu.nickname, au.name),
   'avatar_url', pu.avatar_url,
   'bio', pu.bio,
   'birthday', pu.birthday
 ))
 FROM public.users AS pu
 WHERE au.id = pu.id;

 UPDATE auth.users
-SET profile = jsonb_build_object('name', name)
+SET profile = COALESCE(profile, '{}'::jsonb) || jsonb_build_object('name', name)
 WHERE name IS NOT NULL
   AND (profile IS NULL OR profile = '{}'::jsonb)
   AND id NOT IN (SELECT id FROM public.users);

372-423: Event trigger policy creation may fail on duplicate policy edge cases.

Both functions unconditionally execute CREATE POLICY "project_admin_policy" (lines 391, 419). If that specific policy already exists (e.g., manually created, or multiple DDL commands affect the same table in one event), the CREATE will fail and abort the DDL.

The guard at lines 414-418 only checks if ANY policies exist, not whether project_admin_policy specifically exists. If a different policy exists but project_admin_policy doesn't, this block won't execute, which is correct. However, if project_admin_policy already exists, line 419 will still fail.

Guard the policy creation to handle duplicates:

     IF has_rls THEN
-      EXECUTE format('CREATE POLICY "project_admin_policy" ON %s FOR ALL TO project_admin USING (true) WITH CHECK (true)', obj.object_identity);
+      IF NOT EXISTS (
+        SELECT 1 FROM pg_policies 
+        WHERE schemaname = table_schema 
+          AND tablename = table_name 
+          AND policyname = 'project_admin_policy'
+      ) THEN
+        EXECUTE format('CREATE POLICY "project_admin_policy" ON %s FOR ALL TO project_admin USING (true) WITH CHECK (true)', obj.object_identity);
+      END IF;
     END IF;
   END LOOP;
 END;
 $$ LANGUAGE plpgsql;

 CREATE OR REPLACE FUNCTION system.create_policies_after_rls()
 RETURNS event_trigger AS $$
 DECLARE
   obj record;
   table_schema text;
   table_name text;
 BEGIN
   FOR obj IN SELECT * FROM pg_event_trigger_ddl_commands() WHERE command_tag = 'ALTER TABLE'
   LOOP
     SELECT INTO table_schema, table_name
       split_part(obj.object_identity, '.', 1),
       trim(both '"' from split_part(obj.object_identity, '.', 2));
     IF EXISTS (
       SELECT 1 FROM pg_tables
       WHERE schemaname = table_schema
         AND tablename = table_name
         AND rowsecurity = true
     ) AND NOT EXISTS (
       SELECT 1 FROM pg_policies
       WHERE schemaname = table_schema
         AND tablename = table_name
+        AND policyname = 'project_admin_policy'
     ) THEN
       EXECUTE format('CREATE POLICY "project_admin_policy" ON %s FOR ALL TO project_admin USING (true) WITH CHECK (true)', obj.object_identity);
     END IF;
   END LOOP;
 END;
 $$ LANGUAGE plpgsql;

Alternatively, wrap the CREATE POLICY in a DO $$ BEGIN ... EXCEPTION WHEN duplicate_object THEN NULL; END $$; block.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0e75399 and e303594.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (3)
  • backend/src/infra/database/migrations/018_schema-rework.sql (1 hunks)
  • backend/src/utils/seed.ts (2 hunks)
  • functions/server.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend/src/utils/seed.ts
  • functions/server.ts
🔇 Additional comments (1)
backend/src/infra/database/migrations/018_schema-rework.sql (1)

188-211: LGTM! Auth schema access controls are well-designed.

The combination of schema-level USAGE grant, column-level SELECT/UPDATE grants, and RLS policies provides defense-in-depth:

  • Column grants limit visible columns to public profile data (id, profile, created_at)
  • RLS SELECT policy allows viewing all profiles
  • RLS UPDATE policy restricts modifications to own profile only (id = auth.uid())
  • UPDATE column grant limits modifications to profile field only

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (5)
frontend/src/features/database/components/ForeignKeyPopover.tsx (1)

73-91: Potential duplicate auth.users entry and schema drift risk.

The availableTables array prepends AUTH_USERS_TABLE without checking if tables already contains it, which could result in a duplicate entry. Additionally, the hardcoded referenceTableSchema at lines 87-90 only includes id, while authUsersSchema in constants.ts defines additional columns (email, emailVerified, etc.). Consider:

  1. Deduplicating with a Set or filter check
  2. Importing and reusing authUsersSchema from constants.ts instead of hardcoding
-import { AUTH_USERS_TABLE } from '../constants';
+import { AUTH_USERS_TABLE, authUsersSchema } from '../constants';

-const availableTables = [
-  AUTH_USERS_TABLE,
-  ...tables.filter((tableName) => mode === 'create' || tableName !== editTableName),
-];
+const availableTables = Array.from(
+  new Set([
+    AUTH_USERS_TABLE,
+    ...tables.filter((tableName) => mode === 'create' || tableName !== editTableName),
+  ])
+);

-const referenceTableSchema = isAuthUsers
-  ? {
-      columns: [{ columnName: 'id', type: 'uuid', isUnique: true, isNullable: false }],
-    }
-  : fetchedTableSchema;
+const referenceTableSchema = isAuthUsers
+  ? { columns: authUsersSchema.columns.filter((c) => c.isUnique) }
+  : fetchedTableSchema;
frontend/src/features/auth/components/UsersDataGrid.tsx (1)

200-202: Consider adding runtime type guards for profile access.

The type assertions assume profile has avatar_url and name as strings. If the profile structure differs at runtime, this could lead to unexpected behavior.

-  const profile = row.profile as Record<string, unknown> | null;
-  const avatarUrl = profile?.avatar_url as string | undefined;
-  const name = profile?.name as string | undefined;
+  const profile = row.profile;
+  const avatarUrl =
+    profile &&
+    typeof profile === 'object' &&
+    'avatar_url' in profile &&
+    typeof (profile as Record<string, unknown>).avatar_url === 'string'
+      ? (profile as Record<string, unknown>).avatar_url as string
+      : undefined;
+  const name =
+    profile &&
+    typeof profile === 'object' &&
+    'name' in profile &&
+    typeof (profile as Record<string, unknown>).name === 'string'
+      ? (profile as Record<string, unknown>).name as string
+      : undefined;
frontend/src/features/database/components/ForeignKeyCell.tsx (1)

55-59: Query key misalignment may cause stale cache after user mutations.

The query key ['user', searchValue] won't be invalidated when useUsers mutations invalidate ['users']. This can result in stale data being displayed after user updates elsewhere in the application.

Consider aligning the query key namespace:

   const { data: authUserData, error: authUserError } = useQuery({
-    queryKey: ['user', searchValue],
+    queryKey: ['users', 'single', searchValue],
     queryFn: () => getUser(searchValue),
     enabled: isAuthUsers && open && !!value,
   });

Alternatively, ensure user mutations also invalidate this specific query pattern.

backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js (1)

24-27: Use process.exitCode instead of process.exit(1) for consistency.

Line 26 still calls process.exit(1), which was flagged in a previous review. Although the pool hasn't been created yet, using process.exitCode = 1; return; maintains consistency with the error handling at lines 82-83 and allows the outer .catch() handler at lines 89-93 to execute.

Apply this diff:

   if (!connectionString) {
     console.error('DATABASE_URL environment variable is not set');
-    process.exit(1);
+    process.exitCode = 1;
+    return;
   }
openapi/auth.yaml (1)

1191-1193: Document the metadata object structure.

The metadata field still uses additionalProperties: true without documenting its expected structure. As noted in previous reviews, the backend populates it with {name, avatar_url} for OAuth users and {name} for email-registered users.

Document the structure by adding properties for name (string) and avatar_url (string, optional/nullable), and keep additionalProperties: true if arbitrary extra keys must be supported.

Apply this diff:

         metadata:
           type: object
           additionalProperties: true
+          properties:
+            name:
+              type: string
+            avatar_url:
+              type: string
+              nullable: true
🧹 Nitpick comments (2)
backend/src/services/secrets/secret.service.ts (1)

186-188: Good optimization: early exit when no updates provided.

This prevents unnecessary database queries when updateSecret is called with an empty input object, improving efficiency without changing the semantic behavior (both paths return false for no rows affected).

Consider logging a debug message when this early exit is taken to aid troubleshooting:

 if (updates.length === 0) {
+  logger.debug('No updates provided for secret', { id });
   return false;
 }
openapi/auth.yaml (1)

1207-1224: Consider clarifying that profile properties are optional.

The ProfileResponse.profile schema shows name and avatar_url as example properties under additionalProperties: true. While the parent profile field is nullable, it's not explicitly clear whether these specific properties are required when profile is non-null.

Consider adding a description to clarify:

         profile:
           type: object
           nullable: true
           additionalProperties: true
-          description: User profile data (can contain custom fields)
+          description: User profile data (can contain custom fields). Common fields like name and avatar_url are optional.
           properties:
             name:
               type: string
             avatar_url:
               type: string
               format: uri
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e303594 and 5af4951.

📒 Files selected for processing (12)
  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js (1 hunks)
  • backend/src/services/secrets/secret.service.ts (13 hunks)
  • claude-plugin/skills/insforge-schema-patterns/SKILL.md (6 hunks)
  • docs/core-concepts/database/sdk.mdx (7 hunks)
  • frontend/src/components/datagrid/DataGrid.tsx (6 hunks)
  • frontend/src/components/datagrid/datagridTypes.tsx (1 hunks)
  • frontend/src/features/auth/components/UsersDataGrid.tsx (5 hunks)
  • frontend/src/features/database/components/ForeignKeyCell.tsx (4 hunks)
  • frontend/src/features/database/components/ForeignKeyPopover.tsx (3 hunks)
  • frontend/src/features/database/components/LinkRecordModal.tsx (4 hunks)
  • frontend/src/features/database/components/RecordFormField.tsx (1 hunks)
  • openapi/auth.yaml (10 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • frontend/src/components/datagrid/datagridTypes.tsx
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/services/secrets/secret.service.ts
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/features/database/components/RecordFormField.tsx
  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
  • frontend/src/features/database/components/ForeignKeyCell.tsx
frontend/src/**/*.{tsx,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

frontend/src/**/*.{tsx,jsx}: Use functional components with hooks exclusively in React
Implement proper TypeScript interfaces for all props in React components
Use React Hook Form for form handling in frontend
Follow component composition patterns in React
Implement proper loading and error states in React components
Keep components focused and single-purpose in React
Use Radix UI primitives for accessibility in frontend
Use appropriate loading skeletons for data fetching in frontend
Display clear error messages with actionable feedback in frontend
Implement proper form validation with inline errors in frontend
Use consistent icon set from lucide-react
Optimize React component re-renders

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/features/database/components/RecordFormField.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
frontend/src/**/*.{tsx,jsx,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

frontend/src/**/*.{tsx,jsx,ts}: Use TanStack Query for server state management in frontend
Use lazy loading for code splitting
Optimize bundle size with proper imports

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/features/database/components/RecordFormField.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/services/secrets/secret.service.ts
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/features/database/components/RecordFormField.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
frontend/src/**/*.{tsx,jsx,css}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Maintain consistent color scheme using CSS variables

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/features/database/components/RecordFormField.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/services/secrets/secret.service.ts
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/features/database/components/RecordFormField.tsx
  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
  • frontend/src/features/database/components/ForeignKeyCell.tsx
{backend/src/{api,controllers},frontend/src/**}/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src/{api,controllers},frontend/src/**}/*.{ts,tsx,js,jsx}: Validate all user inputs
Use pagination for large data sets

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/features/database/components/RecordFormField.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • frontend/src/features/database/components/ForeignKeyPopover.tsx
  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • backend/src/services/secrets/secret.service.ts
  • frontend/src/components/datagrid/DataGrid.tsx
  • frontend/src/features/database/components/RecordFormField.tsx
  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
  • frontend/src/features/database/components/ForeignKeyCell.tsx
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/services/secrets/secret.service.ts
  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/services/secrets/secret.service.ts
  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
backend/src/**/*.service.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Name service files in camelCase with .service.ts suffix (e.g., auth.service.ts)

Files:

  • backend/src/services/secrets/secret.service.ts
frontend/src/components/**/*.tsx

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Name component files in PascalCase (e.g., DataGrid.tsx)

Files:

  • frontend/src/components/datagrid/DataGrid.tsx
{backend/src/api,openapi}/**/*.{ts,yaml,yml,json}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Document all API endpoints with clear descriptions

Files:

  • openapi/auth.yaml
🧠 Learnings (12)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/{api,controllers},frontend/src/**}/*.{ts,tsx,js,jsx} : Use pagination for large data sets

Applied to files:

  • frontend/src/features/database/components/LinkRecordModal.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.ts : Name hook files with 'use' prefix in PascalCase (e.g., useAuth.ts)

Applied to files:

  • frontend/src/features/database/components/LinkRecordModal.tsx
📚 Learning: 2025-11-20T00:54:00.807Z
Learnt from: HMaan0
Repo: InsForge/InsForge PR: 607
File: frontend/src/components/datagrid/index.ts:1-23
Timestamp: 2025-11-20T00:54:00.807Z
Learning: In react-data-grid v7.0.0-beta.47, the type for cell click handler arguments is named `CellClickArgs`. This was renamed to `CellMouseArgs` in later beta releases (after beta.47). When reviewing barrel exports or type re-exports from react-data-grid, verify the specific version being used before suggesting type name changes.

Applied to files:

  • frontend/src/features/database/components/LinkRecordModal.tsx
  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/components/datagrid/DataGrid.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/components/**/*.tsx : Name component files in PascalCase (e.g., DataGrid.tsx)

Applied to files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/components/datagrid/DataGrid.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx} : Implement proper loading and error states in React components

Applied to files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx} : Use consistent icon set from lucide-react

Applied to files:

  • frontend/src/features/auth/components/UsersDataGrid.tsx
  • frontend/src/features/database/components/ForeignKeyCell.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/**/*.{ts,js} : Implement proper database transaction handling

Applied to files:

  • backend/src/infra/database/migrations/bootstrap/bootstrap-migrations.js
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}} : Use Zod schemas for request/response validation in backend

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx} : Use functional components with hooks exclusively in React

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx} : Use React Hook Form for form handling in frontend

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to frontend/src/**/*.{tsx,jsx,ts} : Use TanStack Query for server state management in frontend

Applied to files:

  • frontend/src/features/database/components/ForeignKeyCell.tsx
📚 Learning: 2025-11-14T18:47:06.676Z
Learnt from: Fermionic-Lyu
Repo: InsForge/InsForge PR: 585
File: frontend/src/features/database/page/FunctionsPage.tsx:57-83
Timestamp: 2025-11-14T18:47:06.676Z
Learning: In the InsForge codebase, there are two distinct types of functions: (1) database functions (SQL stored procedures/functions in PostgreSQL) which are part of the database schema and emit DATA_UPDATE events with resource type DATABASE, handled in frontend/src/features/database/page/FunctionsPage.tsx; (2) edge/serverless functions which emit DATA_UPDATE events with resource type FUNCTIONS, handled in frontend/src/features/functions/page/FunctionsPage.tsx. These are separate concepts with different resource types.

Applied to files:

  • docs/core-concepts/database/sdk.mdx
🧬 Code graph analysis (4)
frontend/src/features/database/components/ForeignKeyPopover.tsx (1)
frontend/src/features/database/constants.ts (1)
  • AUTH_USERS_TABLE (5-5)
frontend/src/features/database/components/LinkRecordModal.tsx (4)
frontend/src/features/database/constants.ts (2)
  • AUTH_USERS_TABLE (5-5)
  • authUsersSchema (8-18)
frontend/src/features/database/hooks/useRecords.ts (1)
  • useRecords (6-139)
frontend/src/features/auth/hooks/useUsers.ts (1)
  • useUsers (11-95)
frontend/src/components/datagrid/datagridTypes.tsx (2)
  • DatabaseRecord (36-38)
  • ConvertedValue (13-19)
frontend/src/components/datagrid/DataGrid.tsx (1)
frontend/src/components/datagrid/datagridTypes.tsx (1)
  • DataGridRow (43-45)
frontend/src/features/database/components/ForeignKeyCell.tsx (3)
frontend/src/features/database/hooks/useTables.ts (1)
  • useTables (10-105)
frontend/src/features/database/constants.ts (2)
  • AUTH_USERS_TABLE (5-5)
  • authUsersSchema (8-18)
frontend/src/features/database/hooks/useRecords.ts (1)
  • useRecords (6-139)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: CI Pre-merge Check
  • GitHub Check: E2E Tests
🔇 Additional comments (26)
docs/core-concepts/database/sdk.mdx (2)

38-39: LGTM! Improved documentation with neutral examples.

The shift from users to posts in SDK examples is a good practice. Using a neutral domain table avoids confusion with the actual auth.users system table and makes the documentation more universally applicable.

Also applies to: 45-48, 59-59, 95-97, 115-115, 199-206, 212-212, 221-222


368-368: Correctly reflects the schema migration.

The change from user.name to user.profile?.name accurately documents the new user schema where the name field has been moved into the profile JSONB column. The optional chaining is appropriate for safely accessing nested properties in a potentially null JSONB field.

backend/src/services/secrets/secret.service.ts (4)

62-66: Schema migration to system.secrets looks correct.

The INSERT query correctly migrates to the new system.secrets schema while maintaining parameterized queries for SQL injection safety.


82-147: Retrieval methods correctly migrated to system.secrets.

All SELECT and UPDATE queries in getSecretById, getSecretByKey, and listSecrets have been properly updated to reference system.secrets while preserving the original logic for active secret checks, expiration validation, and last-used tracking.


232-237: Excellent security improvement: constant-time comparison.

Replacing direct string comparison with crypto.timingSafeEqual prevents timing attacks during secret verification. The implementation correctly checks buffer lengths before calling timingSafeEqual (which requires equal-length buffers), following security best practices.


259-314: Deletion, rotation, and cleanup methods correctly migrated.

All SQL queries in deleteSecret, rotateSecret, and cleanupExpiredSecrets have been properly updated to system.secrets. Transaction handling in rotateSecret is correct with proper BEGIN/COMMIT/ROLLBACK and client release in the finally block.

Also applies to: 341-345

frontend/src/features/database/components/ForeignKeyPopover.tsx (1)

265-265: LGTM!

The grammar correction from "Columntype not match" to "Column types mismatch" improves user-facing text clarity.

frontend/src/features/database/components/ForeignKeyCell.tsx (2)

68-74: LGTM!

Good approach using authUsersSchema from constants instead of hardcoding. The conditional schema resolution between auth.users and fetched schemas is clean.


168-183: LGTM!

The navigation logic cleanly handles both auth.users (navigating to /dashboard/users) and regular tables (using the provided onJumpToTable callback). The button label adapts appropriately.

frontend/src/features/database/components/LinkRecordModal.tsx (3)

52-65: LGTM!

The conditional hook setup properly disables recordsHook for auth.users and configures useUsers with appropriate gating. The search query is correctly passed only when isAuthUsers is true.


88-108: LGTM!

The ?? operator at line 104 correctly handles the case when pagination.total is 0, addressing the previous review concern about falsy value handling.


165-175: LGTM!

The renderCellValue helper properly handles JSON type values by stringifying objects before passing to formatValueForDisplay, preventing [object Object] display issues.

frontend/src/components/datagrid/DataGrid.tsx (3)

19-25: LGTM!

The SelectionCellProps interface is well-designed with appropriate generic typing. Exposing row, isSelected, onToggle, and tabIndex provides the necessary context for custom selection cell implementations.


92-118: LGTM!

The selection column implementation is clean:

  • Width configuration respects selectionColumnWidth with a sensible default
  • maxWidth becomes undefined when custom renderer is provided, enabling resizing
  • The handleToggle callback properly manages Set operations with string conversion
  • Falls back to default Checkbox when no custom renderer is provided

119-143: LGTM!

The header cell correctly uses keyGetter(row) for consistent row identity when counting selections and toggling all rows. This aligns with the row-level selection logic.

frontend/src/features/auth/components/UsersDataGrid.tsx (3)

104-129: LGTM!

The ProvidersCellRenderer properly handles edge cases:

  • Checks for null/undefined, non-array, and empty array
  • Deduplicates providers before display
  • Shows a maximum of 2 badges with an overflow indicator
  • Tooltip shows all providers

208-213: LGTM!

Using Avatar with AvatarFallback is a good improvement over a plain img tag. The AvatarFallback handles broken/missing avatar URLs gracefully by showing the User icon, eliminating the need for explicit onError handling.


239-240: LGTM!

The selectionColumnWidth of 180 appropriately accommodates the avatar + name display in the custom selection cell.

frontend/src/features/database/components/RecordFormField.tsx (1)

495-503: Remove this review comment—the type cast removal is correct.

The as JSON cast was unnecessary and potentially misleading. result.value is already properly typed as ConvertedValue by the ValueConversionResult type, which accepts all values that jsonSchema.parse() produces: null, parsed objects, and arrays. All of these are valid ConvertedValue types. Removing the incorrect cast improves type safety rather than reducing it.

Likely an incorrect or invalid review comment.

claude-plugin/skills/insforge-schema-patterns/SKILL.md (4)

18-19: LGTM!

Foreign key references correctly updated from users(id) to auth.users(id) across all patterns, aligning with the schema rework.

Also applies to: 83-83, 146-146, 215-215


47-57: LGTM!

Query patterns simplified by removing nested relation expansions, which aligns with the new profile structure in auth.users.


181-196: LGTM!

Query patterns correctly updated to reference author:user_id(id, profile) and include clear documentation on accessing profile fields from the JSONB column.


37-37: No action required. The migration is working as designed.

The 018_schema-rework.sql migration intentionally drops public.uid() with CASCADE (lines 214-219) as a breaking change to force migration to the new auth.uid() function. The migration explicitly documents this design decision in its comments and includes fallback RLS policies using auth.uid() on the new auth.users table (lines 203-211). Any RLS policies on user-created tables that depend on public.uid() must be recreated using auth.uid() instead—this is the expected behavior, not a bug.

The SKILL.md documentation file shows recommended RLS patterns and is not the source of the migration issue. The error about the "scores" table policy is expected and reflects user-created schemas that must be updated to use auth.uid() following the migration.

Likely an incorrect or invalid review comment.

openapi/auth.yaml (3)

29-29: LGTM!

OAuth provider enumerations consistently expanded across all endpoints and schemas to include instagram, tiktok, apple, x, and spotify.

Also applies to: 915-915, 956-956, 989-989, 1038-1038, 1070-1070, 1143-1143, 1234-1234


63-126: LGTM!

New profile endpoints are well-structured: authenticated PATCH for updating current user's profile and public GET for retrieving profiles by ID. Security model is appropriate.


1196-1199: LGTM!

Simplified providers field from array of objects to array of strings, making the response structure cleaner.

@Fermionic-Lyu
Fermionic-Lyu requested a review from jwfing December 16, 2025 21:19
tonychang04 and others added 3 commits December 17, 2025 13:29
* ✨Introduced apis to refresh tokens

* Test new method

* Renamed config

* Resolve comments

* Resolve comments #2

* Fixed a bug

* Remove unused code

* Refresh token mechanism ready to review

* Introduce csrf token

* Introduce csrf token #2

* Extract csrf token logic from cookies

* Switch to store csrf token into cookies

* Enabled nextjs docs

* Enabled in docs map

* Enabled in instructions

* Fixed wrong instruction in docs

* Reverted changes in auth & updated versions

* Reverted changes #2

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
backend/src/services/database/database-table.service.ts (2)

286-386: Fix test/code mismatch and add error handling for unrecognized types.

The convertSqlTypeToColumnType function silently returns a truncated string for unknown types (sqlType.slice(0, 8)), but the test expects only 5 characters. Additionally, there is no error handling or logging when encountering unrecognized USER-DEFINED types (e.g., pgvector extensions).

Update the default case to either:

  • Throw an error for unrecognized types with a clear message
  • Log a warning when truncation occurs
  • Fix the test expectation to match the code (or adjust the slice length)

This prevents silent data loss and improves debuggability when extensions or custom types are encountered.


115-257: Document deployment sequence for version upgrades to ensure migration 018 completes before application startup.

The createTable method depends on system.update_updated_at() function, which is created in migration 018_schema-rework.sql. The bootstrap process correctly creates the system schema before migrations execute, and node-pg-migrate wraps each migration in a transaction for safety. However, the 1.0.0 → 1.3.0 upgrade involves significant schema restructuring (moving tables between schemas, renaming underscore-prefixed tables). Add deployment documentation clarifying:

  1. Bootstrap script must complete and migrate the _migrations table before migration 018 runs
  2. Migration 018 must complete fully before application code calls createTable()
  3. Existing deployments upgrading from 1.0.0 should not create new tables during the migration window

The transactional safety is handled automatically, but the sequencing must be enforced at the deployment level.

♻️ Duplicate comments (1)
backend/src/services/database/database-table.service.ts (1)

656-663: Make cross-schema reference handling extensible.

The quoteTableReference method is hardcoded to only handle auth.users. As noted in previous review, this approach doesn't scale as the multi-schema architecture expands (storage, functions, etc.).

The previous review suggested using a whitelist or pattern-based approach. Consider implementing one of these solutions:

  • Maintain a class-level Set/array of allowed cross-schema references
  • Use pattern matching for any schema reference (schema.table format)
  • Make the allowed list configurable via constructor or config service

This refactor should be prioritized to avoid repeated modifications as new schemas are added.

🧹 Nitpick comments (5)
docs/introduction.mdx (1)

35-45: Consider using distinct icons for Edge Functions and Realtime.

Both "Edge Functions" (line 35) and "Realtime" (line 43) use icon="bolt". Consider using a different icon for Realtime (e.g., radio, signal, or arrows-rotate) to visually distinguish the features.

docs/changelog.mdx (1)

150-150: Inconsistent GitHub organization casing.

Based on learnings, the SDK repository URL should use lowercase: https://github.com/insforge/insforge-sdk-js. While GitHub URLs are case-insensitive, consistent casing improves professionalism.

-  [GitHub](https://github.com/InsForge/InsForge-sdk-js) · [Database SDK →](/core-concepts/database/sdk)
+  [GitHub](https://github.com/insforge/insforge-sdk-js) · [Database SDK →](/core-concepts/database/sdk)
backend/src/services/database/database-table.service.ts (3)

687-707: Consolidate cross-schema reference logic.

The FK constraint generation has special handling for auth.users in both constraint naming (lines 696-698) and SQL generation (lines 703, 705). This logic is duplicated and tightly coupled to the hardcoded quoteTableReference method.

Consider consolidating the cross-schema handling:

  • Extract constraint naming logic into a helper method that consistently handles cross-schema references
  • Ensure the constraint naming and SQL generation use the same source of truth for cross-schema tables
  • This will make the code easier to maintain when additional cross-schema references are added

Apply this pattern to reduce duplication:

+ private getConstraintSafeName(tableRef: string): string {
+   // Convert "auth.users" to "auth_users" for constraint naming
+   return tableRef.replace('.', '_');
+ }
+
  private generateFkeyConstraintStatement(
    col: { columnName: string; foreignKey?: ForeignKeySchema },
    include_source_column: boolean = true
  ) {
    if (!col.foreignKey) {
      return '';
    }
    const fk = col.foreignKey;
-   // Use "auth_users" in constraint name for auth.users references
-   const safeTableName = fk.referenceTable === 'auth.users' ? 'auth_users' : fk.referenceTable;
+   const safeTableName = this.getConstraintSafeName(fk.referenceTable);
    const constraintName = `fk_${col.columnName}_${safeTableName}_${fk.referenceColumn}`;

709-754: LGTM! Cross-schema FK retrieval looks correct.

The foreign key constraint retrieval now properly handles cross-schema references by:

  • Retrieving foreign_schema from information_schema (line 715)
  • Constructing schema-qualified table names for non-public schemas (lines 740-744)
  • Maintaining backward compatibility with public schema tables

The logic correctly follows PostgreSQL conventions where public schema can be implicit.

Minor suggestion: add defensive null checking for foreign_schema:

  const referenceTable =
-   fk.foreign_schema !== 'public'
+   fk.foreign_schema && fk.foreign_schema !== 'public'
      ? `${fk.foreign_schema}.${fk.foreign_table}`
      : fk.foreign_table;

232-238: Add defensive error handling for trigger creation with informative messaging.

The system.update_updated_at() function is correctly created in migration 018 before any production tables are created. However, the trigger creation at line 232-238 lacks explicit error handling. If migration 018 fails or doesn't execute, users will encounter a cryptic PostgreSQL error instead of a clear message about missing dependencies.

Consider wrapping the trigger creation in a try-catch block:

try {
  await client.query(`
    CREATE TRIGGER ${this.quoteIdentifier(table_name + '_update_timestamp')}
    BEFORE UPDATE ON ${this.quoteIdentifier(table_name)}
    FOR EACH ROW EXECUTE FUNCTION system.update_updated_at();
  `);
} catch (error) {
  if (error instanceof Error && error.message.includes('function')) {
    throw new AppError(
      'Database initialization incomplete',
      500,
      ERROR_CODES.DATABASE_ERROR,
      'Required trigger function missing. Ensure all migrations have executed successfully.'
    );
  }
  throw error;
}
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0da262c and 9e23084.

⛔ Files ignored due to path filters (3)
  • docs/favicon.png is excluded by !**/*.png
  • docs/favicon.svg is excluded by !**/*.svg
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (18)
  • backend/src/api/routes/docs/index.routes.ts (1 hunks)
  • backend/src/services/database/database-table.service.ts (7 hunks)
  • backend/src/types/database.ts (2 hunks)
  • backend/src/utils/utils.ts (1 hunks)
  • docs/changelog.mdx (1 hunks)
  • docs/core-concepts/ai/architecture.mdx (1 hunks)
  • docs/core-concepts/authentication/architecture.mdx (5 hunks)
  • docs/core-concepts/authentication/ui-components/nextjs.mdx (1 hunks)
  • docs/core-concepts/database/architecture.mdx (2 hunks)
  • docs/core-concepts/email/architecture.mdx (1 hunks)
  • docs/core-concepts/functions/architecture.mdx (1 hunks)
  • docs/core-concepts/realtime/architecture.mdx (1 hunks)
  • docs/core-concepts/storage/architecture.mdx (1 hunks)
  • docs/docs.json (1 hunks)
  • docs/insforge-instructions-sdk.md (1 hunks)
  • docs/introduction.mdx (2 hunks)
  • docs/quickstart.mdx (1 hunks)
  • shared-schemas/src/docs.schema.ts (2 hunks)
✅ Files skipped from review due to trivial changes (5)
  • docs/core-concepts/functions/architecture.mdx
  • docs/core-concepts/realtime/architecture.mdx
  • docs/core-concepts/email/architecture.mdx
  • docs/core-concepts/storage/architecture.mdx
  • docs/core-concepts/ai/architecture.mdx
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend/src/types/database.ts
  • docs/core-concepts/authentication/architecture.mdx
🧰 Additional context used
📓 Path-based instructions (12)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • backend/src/utils/utils.ts
  • backend/src/api/routes/docs/index.routes.ts
  • backend/src/services/database/database-table.service.ts
  • shared-schemas/src/docs.schema.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/utils/utils.ts
  • backend/src/api/routes/docs/index.routes.ts
  • backend/src/services/database/database-table.service.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/utils/utils.ts
  • backend/src/api/routes/docs/index.routes.ts
  • backend/src/services/database/database-table.service.ts
  • shared-schemas/src/docs.schema.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • backend/src/utils/utils.ts
  • backend/src/api/routes/docs/index.routes.ts
  • backend/src/services/database/database-table.service.ts
  • shared-schemas/src/docs.schema.ts
**/{src,lib}/**/?(database-|*-)utils.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Name utility files in kebab-case or camelCase with .ts suffix (e.g., database-utils.ts)

Files:

  • backend/src/utils/utils.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/utils/utils.ts
  • backend/src/api/routes/docs/index.routes.ts
  • backend/src/services/database/database-table.service.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/utils/utils.ts
  • backend/src/api/routes/docs/index.routes.ts
  • backend/src/services/database/database-table.service.ts
backend/src/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/api/**/*.{ts,js}: Implement proper middleware for authentication and error handling
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/docs/index.routes.ts
backend/src/{controllers,api}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Return consistent API responses using utility functions

Files:

  • backend/src/api/routes/docs/index.routes.ts
backend/src/{api,core,controllers}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper authentication and authorization

Files:

  • backend/src/api/routes/docs/index.routes.ts
{backend/src/api,openapi}/**/*.{ts,yaml,yml,json}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Document all API endpoints with clear descriptions

Files:

  • backend/src/api/routes/docs/index.routes.ts
backend/src/**/*.service.ts

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Name service files in camelCase with .service.ts suffix (e.g., auth.service.ts)

Files:

  • backend/src/services/database/database-table.service.ts
🧠 Learnings (11)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to **/{src,lib}/**/?(database-|*-)utils.ts : Name utility files in kebab-case or camelCase with .ts suffix (e.g., database-utils.ts)

Applied to files:

  • backend/src/utils/utils.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Avoid snake_case except in SQL queries and external APIs

Applied to files:

  • backend/src/utils/utils.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/api,openapi}/**/*.{ts,yaml,yml,json} : Document all API endpoints with clear descriptions

Applied to files:

  • backend/src/api/routes/docs/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to **/*.{ts,tsx,js,jsx} : Include JSDoc comments for complex functions

Applied to files:

  • backend/src/api/routes/docs/index.routes.ts
📚 Learning: 2025-11-14T18:47:06.676Z
Learnt from: Fermionic-Lyu
Repo: InsForge/InsForge PR: 585
File: frontend/src/features/database/page/FunctionsPage.tsx:57-83
Timestamp: 2025-11-14T18:47:06.676Z
Learning: In the InsForge codebase, there are two distinct types of functions: (1) database functions (SQL stored procedures/functions in PostgreSQL) which are part of the database schema and emit DATA_UPDATE events with resource type DATABASE, handled in frontend/src/features/database/page/FunctionsPage.tsx; (2) edge/serverless functions which emit DATA_UPDATE events with resource type FUNCTIONS, handled in frontend/src/features/functions/page/FunctionsPage.tsx. These are separate concepts with different resource types.

Applied to files:

  • docs/core-concepts/database/architecture.mdx
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/**/*.{ts,js} : Implement proper database indexing

Applied to files:

  • backend/src/services/database/database-table.service.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/**/*.{ts,js} : Implement proper database transaction handling

Applied to files:

  • backend/src/services/database/database-table.service.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/**/*.{ts,js} : Use prepared statements for SQL queries

Applied to files:

  • backend/src/services/database/database-table.service.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • docs/insforge-instructions-sdk.md
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement proper middleware for authentication and error handling

Applied to files:

  • docs/insforge-instructions-sdk.md
📚 Learning: 2025-11-04T05:18:26.126Z
Learnt from: Fermionic-Lyu
Repo: InsForge/InsForge PR: 553
File: docs/changelog.mdx:6-35
Timestamp: 2025-11-04T05:18:26.126Z
Learning: The InsForge JavaScript SDK repository is named "insforge-sdk-js" and is located at https://github.com/insforge/insforge-sdk-js

Applied to files:

  • docs/core-concepts/authentication/ui-components/nextjs.mdx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: build-and-push
  • GitHub Check: E2E Tests
  • GitHub Check: CI Pre-merge Check
🔇 Additional comments (7)
docs/docs.json (2)

18-19: LGTM! Standard SEO meta tags added.

The addition of the Google Search Console verification tag and the properly formatted og:site_name are standard SEO practices for documentation sites.


26-26: The favicon.png file exists in the repository at /docs/favicon.png and will load correctly. No issues to address.

docs/insforge-instructions-sdk.md (1)

58-58: LGTM! Documentation type addition is consistent.

The new "auth-components-nextjs" documentation type is properly added and aligns with the corresponding changes in the backend route and schema definition.

shared-schemas/src/docs.schema.ts (1)

11-11: LGTM! Schema definition is properly updated.

The new 'auth-components-nextjs' enum value and its description are correctly added to the Zod schema. The change maintains type safety and is consistent with the backend route implementation.

Also applies to: 22-22

backend/src/api/routes/docs/index.routes.ts (1)

22-22: Documentation file exists and mapping is correct.

The mapping for 'auth-components-nextjs' correctly references the existing documentation file at docs/core-concepts/authentication/ui-components/nextjs.mdx. The change is ready for deployment.

docs/core-concepts/database/architecture.mdx (1)

116-178: Documentation accurately reflects the new multi-schema architecture.

The schema organization and table listings match the PR objectives. All six schemas (auth, storage, ai, functions, realtime, system) are documented with their respective tables, and the access model is clearly explained. The note at line 176-178 appropriately clarifies that only public schema tables are exposed via PostgREST.

docs/changelog.mdx (1)

6-158: Changelog restructuring looks good.

The migration from accordion sections to standalone Update blocks with labels and tags improves readability and consistency. Documentation links are properly included for each feature announcement.

Comment thread backend/src/utils/utils.ts Resolved
Comment thread docs/insforge-instructions-sdk.md Resolved
Comment thread docs/quickstart.mdx Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
backend/src/utils/seed.ts (1)

40-40: Consider parameterizing admin profile.

The admin profile is hardcoded as { name: 'Administrator' }. While acceptable for the default admin user, consider making this configurable via environment variables (e.g., ADMIN_NAME) for flexibility across deployments.

📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 787141d and 3201f92.

📒 Files selected for processing (1)
  • backend/src/utils/seed.ts (5 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • backend/src/utils/seed.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/utils/seed.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/utils/seed.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • backend/src/utils/seed.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/utils/seed.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/utils/seed.ts
🧠 Learnings (2)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/utils/seed.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/**/*.{ts,js} : Use async/await for asynchronous operations in backend code

Applied to files:

  • backend/src/utils/seed.ts
🧬 Code graph analysis (1)
backend/src/utils/seed.ts (2)
backend/src/infra/database/database.manager.ts (1)
  • DatabaseManager (10-172)
backend/src/utils/constants.ts (1)
  • ADMIN_ID (1-1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: E2E Tests
  • GitHub Check: CI Pre-merge Check
🔇 Additional comments (3)
backend/src/utils/seed.ts (3)

265-266: Admin seeding integration looks correct.

The placement of seedAdminUser before API key initialization is appropriate, ensuring the admin user exists early in the startup sequence.


1-1: Use bcryptjs 3.0.3 to ensure you're on the latest stable version.

bcryptjs 3.0.2 itself has no known security vulnerabilities and is safe for password hashing. However, upgrading to 3.0.3 is recommended as a minor version bump with improvements.


20-23: The review comment's premise is incorrect based on the actual startup sequence. ADMIN_EMAIL and ADMIN_PASSWORD are enforced as required environment variables by the AuthService constructor (backend/src/services/auth/auth.service.ts, lines 70-75), which throws an error if either is missing. This occurs during route initialization (line 171 in server.ts), which happens before seedBackend() is called (line 259).

If credentials are not configured, the application fails at startup with a clear error message—it does not continue to seedBackend where silent skipping occurs. The fallback defaults in seed.ts (lines 259-260) are unreachable in the credential-missing scenario.

No actionable changes are needed; the credential validation is already enforced at startup.

Likely an incorrect or invalid review comment.

Comment thread backend/src/utils/seed.ts Resolved
Comment thread backend/src/utils/seed.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

♻️ Duplicate comments (1)
backend/src/infra/database/migrations/018_schema-rework.sql (1)

217-219: Critical: CASCADE drop of public.uid() causes migration failures (confirmed by user reports).

This issue was previously flagged and has now been confirmed in PR comments: tonychang04 reported migration failure when upgrading from 1.0.0 → 1.3.0 with error "cannot drop function uid() because other objects depend on it" (policy on table scores depends on uid()).

The recommended fix from previous review remains valid: instead of dropping these functions, create backward-compatible proxy functions that delegate to the new auth.* equivalents.

🧹 Nitpick comments (1)
backend/src/infra/database/migrations/018_schema-rework.sql (1)

71-72: Consider potential table locking on large installations.

Adding columns with DEFAULT values requires PostgreSQL to rewrite the entire table, which can cause extended locks on large auth.users tables during migration.

For production deployments with many users, consider a two-step approach: add columns as nullable first, then backfill and add defaults separately.

-ALTER TABLE auth.users ADD COLUMN IF NOT EXISTS profile JSONB DEFAULT '{}'::jsonb;
-ALTER TABLE auth.users ADD COLUMN IF NOT EXISTS metadata JSONB DEFAULT '{}'::jsonb;
+-- Add columns without DEFAULT to avoid table rewrite
+ALTER TABLE auth.users ADD COLUMN IF NOT EXISTS profile JSONB;
+ALTER TABLE auth.users ADD COLUMN IF NOT EXISTS metadata JSONB;
+
+-- Backfill with default values
+UPDATE auth.users SET profile = '{}'::jsonb WHERE profile IS NULL;
+UPDATE auth.users SET metadata = '{}'::jsonb WHERE metadata IS NULL;
+
+-- Add defaults for future inserts
+ALTER TABLE auth.users ALTER COLUMN profile SET DEFAULT '{}'::jsonb;
+ALTER TABLE auth.users ALTER COLUMN metadata SET DEFAULT '{}'::jsonb;
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cd54dca and b62e881.

📒 Files selected for processing (1)
  • backend/src/infra/database/migrations/018_schema-rework.sql (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: build-and-push
  • GitHub Check: E2E Tests
  • GitHub Check: CI Pre-merge Check

* Removed isProduction & isDevelopment

* Use req.secure to decide

* Added isCloud back

* Finalize changes

* Restore rate limit

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
backend/src/api/routes/auth/index.routes.ts (1)

106-127: Consider adding rate limiting to prevent abuse.

This public endpoint allows fetching user profiles by ID without authentication. While the past review noted this concern and was marked as addressed, rate limiting is still not applied. This could allow:

  • User enumeration attacks (probing valid user IDs)
  • DoS through excessive requests

Consider adding a rate limiter similar to sendEmailOTPLimiter to this endpoint.

🔎 Example implementation

Define a rate limiter in your rate-limiters middleware file:

export const publicProfileLimiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15 minutes
  max: 100, // limit each IP to 100 requests per windowMs
  message: 'Too many profile requests, please try again later'
});

Then apply it to the route:

 // GET /api/auth/profiles/:userId - Get user profile by ID (public endpoint)
-router.get('/profiles/:userId', async (req: Request, res: Response, next: NextFunction) => {
+router.get('/profiles/:userId', publicProfileLimiter, async (req: Request, res: Response, next: NextFunction) => {
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b62e881 and d5fc613.

📒 Files selected for processing (5)
  • backend/src/api/routes/auth/index.routes.ts (11 hunks)
  • backend/src/api/routes/auth/oauth.routes.ts (3 hunks)
  • backend/src/server.ts (2 hunks)
  • backend/src/utils/cookies.ts (3 hunks)
  • backend/src/utils/environment.ts (0 hunks)
💤 Files with no reviewable changes (1)
  • backend/src/utils/environment.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/api/routes/auth/oauth.routes.ts
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx,js,jsx}: Use TypeScript for all code files
Prefer descriptive, unabbreviated variable and function names
Follow consistent file naming: kebab-case for files, PascalCase for components
Use ES modules (import/export syntax)
Implement proper error handling with try-catch blocks
Add appropriate logging for debugging
Use camelCase for variables, parameters, properties, and functions
Use UPPER_CASE for constants and Enum members
Avoid snake_case except in SQL queries and external APIs
Use single quotes for strings
Include semicolons at the end of statements
Use arrow functions for callbacks and inline functions
Prefer const over let, avoid var
Use template literals for string interpolation
Maintain consistent indentation (2 spaces)
Format code with Prettier configuration
Include JSDoc comments for complex functions

Files:

  • backend/src/server.ts
  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
backend/src/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/**/*.{ts,js}: Use async/await for asynchronous operations in backend code
Implement proper database transaction handling
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper database indexing

Files:

  • backend/src/server.ts
  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend/src/**/*.{ts,js},shared-schemas/**/*.{ts,js}}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use Zod schemas for request/response validation in backend

Files:

  • backend/src/server.ts
  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use PascalCase for React components and TypeScript types/interfaces

Files:

  • backend/src/server.ts
  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend,frontend}/src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use environment variables for configuration

Files:

  • backend/src/server.ts
  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

{backend/src,frontend/src}/**/*.{ts,tsx,js,jsx}: Implement proper caching strategies
Monitor and log performance metrics

Files:

  • backend/src/server.ts
  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
backend/src/api/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

backend/src/api/**/*.{ts,js}: Implement proper middleware for authentication and error handling
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints

Files:

  • backend/src/api/routes/auth/index.routes.ts
backend/src/{controllers,api}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Return consistent API responses using utility functions

Files:

  • backend/src/api/routes/auth/index.routes.ts
backend/src/{api,core,controllers}/**/*.{ts,js}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Implement proper authentication and authorization

Files:

  • backend/src/api/routes/auth/index.routes.ts
{backend/src/api,openapi}/**/*.{ts,yaml,yml,json}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Document all API endpoints with clear descriptions

Files:

  • backend/src/api/routes/auth/index.routes.ts
🧠 Learnings (6)
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement rate limiting for API endpoints

Applied to files:

  • backend/src/server.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Implement proper middleware for authentication and error handling

Applied to files:

  • backend/src/server.ts
  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend,frontend}/src/**/*.{ts,tsx,js,jsx} : Use environment variables for configuration

Applied to files:

  • backend/src/server.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/{api,core,controllers}/**/*.{ts,js} : Implement proper authentication and authorization

Applied to files:

  • backend/src/utils/cookies.ts
  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to backend/src/api/**/*.{ts,js} : Follow RESTful conventions for API endpoints

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
📚 Learning: 2025-12-01T06:28:41.515Z
Learnt from: CR
Repo: InsForge/InsForge PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-12-01T06:28:41.515Z
Learning: Applies to {backend/src/api,openapi}/**/*.{ts,yaml,yml,json} : Document all API endpoints with clear descriptions

Applied to files:

  • backend/src/api/routes/auth/index.routes.ts
🧬 Code graph analysis (1)
backend/src/api/routes/auth/index.routes.ts (7)
backend/src/infra/security/token.manager.ts (1)
  • verifyToken (137-148)
backend/src/api/middlewares/auth.ts (2)
  • verifyToken (156-199)
  • AuthRequest (7-16)
backend/src/api/middlewares/error.ts (1)
  • AppError (7-17)
shared-schemas/src/auth-api.schema.ts (3)
  • updateProfileRequestSchema (71-73)
  • GetProfileResponse (358-358)
  • GetCurrentSessionResponse (357-357)
backend/src/utils/response.ts (1)
  • successResponse (22-24)
shared-schemas/src/auth.schema.ts (1)
  • userIdSchema (12-12)
backend/src/utils/cookies.ts (3)
  • setAuthCookie (13-21)
  • REFRESH_TOKEN_COOKIE_NAME (6-6)
  • clearAuthCookie (27-34)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: CI Pre-merge Check
  • GitHub Check: E2E Tests
🔇 Additional comments (5)
backend/src/server.ts (1)

80-80: LGTM: Rate limiting now applied in all environments.

Removing the production-only gating ensures rate limiting is consistently tested across all environments. The limit of 1000 requests per 15 minutes is generous enough for development workflows while providing protection in production.

backend/src/api/routes/auth/index.routes.ts (3)

75-104: LGTM! Profile update endpoint is well-implemented.

The endpoint correctly:

  • Protects the route with verifyToken middleware
  • Validates the request body using Zod schema
  • Handles authentication errors appropriately
  • Returns properly typed responses

190-190: LGTM! Cookie function calls updated consistently.

All calls to setAuthCookie and clearAuthCookie have been correctly updated to pass the req parameter, matching the new function signatures in cookies.ts.

Also applies to: 226-226, 260-260, 274-274, 284-284, 292-292, 591-591


361-381: LGTM! Session endpoint now fetches fresh user data.

The endpoint correctly fetches the current user from the database rather than relying solely on the JWT payload. This ensures:

  • Fresh user data (profile, metadata, role changes)
  • Detection of deleted users (404 handling)
  • Consistency with the new schema structure
backend/src/utils/cookies.ts (1)

13-21: The change to use req.secure is secure and correct. Trust proxy is already properly configured in the application at backend/src/server.ts:64 with app.set('trust proxy', true);, ensuring req.secure will accurately reflect HTTPS status when the app runs behind a reverse proxy. No additional verification or configuration needed.

Likely an incorrect or invalid review comment.

Comment thread backend/src/server.ts
Comment on lines +230 to 233
} else {
const authAppUrl = process.env.AUTH_APP_URL || 'http://localhost:7132';
logger.info('Auth app not built, proxying to development server', { authAppUrl });
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical: Missing proxy setup for auth app development server.

The else block logs that it's "proxying to development server" but doesn't actually set up any proxy middleware. The authAppUrl variable is read but never used. When the auth app is not built, requests to /auth will fall through to the 404 handler, breaking the development workflow.

🔎 Add proxy middleware to forward requests to the development server:

Install http-proxy-middleware if not already available:

import { createProxyMiddleware } from 'http-proxy-middleware';

Then apply this diff:

 } else {
   const authAppUrl = process.env.AUTH_APP_URL || 'http://localhost:7132';
   logger.info('Auth app not built, proxying to development server', { authAppUrl });
+  app.use(
+    '/auth',
+    createProxyMiddleware({
+      target: authAppUrl,
+      changeOrigin: true,
+      ws: true,
+    })
+  );
 }

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In backend/src/server.ts around lines 230 to 233, the else branch logs proxying
to the auth dev server but never configures a proxy; add an import for
createProxyMiddleware at the top of the file and instantiate middleware that
forwards requests matching the /auth path to authAppUrl (use
process.env.AUTH_APP_URL || 'http://localhost:7132') with changeOrigin: true and
appropriate path rewriting if needed, then mount that middleware on the Express
app so /auth requests are forwarded to the development server instead of falling
through to the 404 handler.

@tonychang04 tonychang04 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Amazing work! tested e2e multiple times new proj + couple proj upgrades. Only some minor edge cases(regarding user being dropped and it) but this is unavoidable.

We can slowly build on top of this to make this better!

ex: letting agent able to select and understand the schema: maybe add it to instructions.md(which will later become AGENT.md)
so it can query an debug better

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants