Repository navigation
[Infra] Schema rework - #640
Conversation
WalkthroughRehomes 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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
There was a problem hiding this comment.
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 forauth.users.
Strict mode Test 6 expectsSELECT COUNT(*) FROM auth.usersto 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 moveTOKENto 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 +fibackend/src/services/secrets/secret.service.ts (2)
159-204:updateSecretcan generate invalid SQL wheninputhas no updatable fields.
Ifupdates.length === 0, this becomesSET(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.
ThecheckSecretByKeymethod compares secrets using===(line 228), which leaks timing information. Replace withcrypto.timingSafeEqual(Buffer.from(decryptedValue), Buffer.from(value))to prevent timing attacks, especially critical since this method verifies API keys viaverifyApiKey(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(*), andSUM(size)can return PostgreSQLBIGINTvalues exceeding JavaScript's safe integer range (2^53-1). UsingparseInt()on these values silently loses precision for databases or storage exceeding ~9 petabytes.Change
database_size_bytesandstorage_size_bytesto string fields in theUsageStatsinterface 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) inAIUsageByModelandai-config.service.tsalso don't exceed safe range, as they useSUM()onINTcolumns without explicit casting.frontend/src/components/datagrid/DataGrid.tsx (1)
119-142: Inconsistent key usage between cell and header selection logic.The
renderCellfunction useskeyGetter(row)(lines 102-108), butrenderHeaderCellusesrow.iddirectly (lines 120, 133, 136). This inconsistency could cause bugs when a customrowKeyGetteris provided that returns a different value thanrow.id.Apply this diff to use
keyGetterconsistently: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 withString()on undefined metadata.When
result?.user?.metadata?.nameisundefinedornull,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 withString()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_verificationtoisCloudEnvironment(), 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 atomicINSERT ... SELECT ... WHERE NOT EXISTS(orINSERT ... ON CONFLICT (...) DO NOTHINGwith 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.namelikely no longer exists after schema rework.If the SDK user mirrors
auth.userschanges, Line 368 should not useuser.name; it should read from metadata (and confirm whetheruser.emailis 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.usersno longer hasnicknameoravatar_urlas direct columns. These fields are now stored in themetadataJSONB 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
nameandavatar_urlfrommetadatain 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 placeholderGiven the schema rework,
productsis likely not a guaranteed table name, andfromshould beFROMfor 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 forauth.usersschema fetch.
Now thatusersis included, please ensuretableService.getTableSchema()cannot leak restricted schema details to unauthorized users, and consider avoiding potentially large fan-out query storms whentablesgrows.A concrete improvement (keeps
useTables()API unchanged) is to makeenabled=falsetruly “on demand” by not fetchingtablesat 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
tablescan 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
authUsersSchemabypasses dynamic schema fetching and will become stale if the actualauth.userstable 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
useRecordswhenisAuthUsersis true works because of theenabledcheck 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
enabledparameter inuseRecordByForeignKey(line 80) which already handles the!isAuthUserscondition.backend/src/services/usage/usage.service.ts (1)
54-69:recordMCPUsagetable rename is fine; consider BIGINT return types in pg.
created_atis 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 aligningconversations.user_idnullability with RLS policies.
DDL allowsuser_idNULL, but RLS policies effectively requireuser_id = auth.uid()for select/insert/update/delete—so NULL rows would be unusable. Either makeuser_idNOT NULLor explicitly support anonymous flows in policies.frontend/src/features/auth/components/UsersDataGrid.tsx (1)
205-218: Consider validating avatar URL before rendering.The
avatarUrlfrom user metadata is rendered directly in an<img>tag. While React 19 blocksjavascript:URLs, consider adding basic URL validation (e.g., ensuring it starts withhttps://) 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 tofunctions.definitions, but wrap multi-step writes in a DB transaction.
createFunction()(Line 127+) andupdateFunction()(Line 185+) do multiple UPDATEs; withoutBEGIN/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 bothusersandauth.users.If
referenceTablecan 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 thefollowstable 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.usersmetadata 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
DOWNmigration would be complex, consider documenting:
- The backup procedure before running this migration
- Manual rollback steps if needed
- 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
📒 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.tsxbackend/src/services/auth/auth-config.service.tsbackend/src/api/routes/auth/oauth.routes.tsbackend/src/services/database/database-advance.service.tsfrontend/src/features/visualizer/components/SchemaVisualizer.tsxfunctions/server.tsbackend/src/services/ai/ai-usage.service.tsfrontend/src/features/database/templates/ecommerce-platform.tsfrontend/src/features/database/constants.tsfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/components/datagrid/index.tsfrontend/src/features/database/services/table.service.tsfrontend/src/features/database/templates/notion-clone.tsbackend/src/types/storage.tsbackend/src/services/logs/audit.service.tsbackend/src/services/auth/auth-otp.service.tsfrontend/src/lib/hooks/useMetadata.tsfrontend/src/features/database/components/ForeignKeyPopover.tsxbackend/src/infra/database/migrations/bootstrap/bootstrap-migrations.jsshared-schemas/src/auth.schema.tsfrontend/src/features/database/templates/ai-chatbot.tsbackend/src/services/functions/function.service.tsbackend/src/types/database.tsfrontend/src/features/database/templates/instagram-clone.tsbackend/src/services/ai/ai-config.service.tsbackend/src/services/database/database-table.service.tsfrontend/src/components/datagrid/datagridTypes.tsxfrontend/src/features/database/templates/reddit-clone.tseslint.config.jsfunctions/worker-template.jsbackend/src/services/secrets/secret.service.tsbackend/src/services/usage/usage.service.tsbackend/src/utils/seed.tsfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxbackend/src/services/auth/auth.service.tsfrontend/src/features/database/hooks/useTables.tsbackend/src/services/auth/oauth-config.service.tsbackend/src/services/storage/storage.service.tsbackend/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.tsxfrontend/src/features/visualizer/components/SchemaVisualizer.tsxfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/features/database/components/ForeignKeyPopover.tsxfrontend/src/components/datagrid/datagridTypes.tsxfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/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.tsxfrontend/src/features/visualizer/components/SchemaVisualizer.tsxfrontend/src/features/database/templates/ecommerce-platform.tsfrontend/src/features/database/constants.tsfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/components/datagrid/index.tsfrontend/src/features/database/services/table.service.tsfrontend/src/features/database/templates/notion-clone.tsfrontend/src/lib/hooks/useMetadata.tsfrontend/src/features/database/components/ForeignKeyPopover.tsxfrontend/src/features/database/templates/ai-chatbot.tsfrontend/src/features/database/templates/instagram-clone.tsfrontend/src/components/datagrid/datagridTypes.tsxfrontend/src/features/database/templates/reddit-clone.tsfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/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.tsxbackend/src/services/auth/auth-config.service.tsbackend/src/api/routes/auth/oauth.routes.tsbackend/src/services/database/database-advance.service.tsfrontend/src/features/visualizer/components/SchemaVisualizer.tsxfunctions/server.tsbackend/src/services/ai/ai-usage.service.tsfrontend/src/features/database/templates/ecommerce-platform.tsfrontend/src/features/database/constants.tsfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/components/datagrid/index.tsfrontend/src/features/database/services/table.service.tsfrontend/src/features/database/templates/notion-clone.tsbackend/src/types/storage.tsbackend/src/services/logs/audit.service.tsbackend/src/services/auth/auth-otp.service.tsfrontend/src/lib/hooks/useMetadata.tsfrontend/src/features/database/components/ForeignKeyPopover.tsxshared-schemas/src/auth.schema.tsfrontend/src/features/database/templates/ai-chatbot.tsbackend/src/services/functions/function.service.tsbackend/src/types/database.tsfrontend/src/features/database/templates/instagram-clone.tsbackend/src/services/ai/ai-config.service.tsbackend/src/services/database/database-table.service.tsfrontend/src/components/datagrid/datagridTypes.tsxfrontend/src/features/database/templates/reddit-clone.tsbackend/src/services/secrets/secret.service.tsbackend/src/services/usage/usage.service.tsbackend/src/utils/seed.tsfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxbackend/src/services/auth/auth.service.tsfrontend/src/features/database/hooks/useTables.tsbackend/src/services/auth/oauth-config.service.tsbackend/src/services/storage/storage.service.tsbackend/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.tsxfrontend/src/features/visualizer/components/SchemaVisualizer.tsxfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/features/database/components/ForeignKeyPopover.tsxfrontend/src/components/datagrid/datagridTypes.tsxfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/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.tsxbackend/src/services/auth/auth-config.service.tsbackend/src/api/routes/auth/oauth.routes.tsbackend/src/services/database/database-advance.service.tsfrontend/src/features/visualizer/components/SchemaVisualizer.tsxbackend/src/services/ai/ai-usage.service.tsfrontend/src/features/database/templates/ecommerce-platform.tsfrontend/src/features/database/constants.tsfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/components/datagrid/index.tsfrontend/src/features/database/services/table.service.tsfrontend/src/features/database/templates/notion-clone.tsbackend/src/types/storage.tsbackend/src/services/logs/audit.service.tsbackend/src/services/auth/auth-otp.service.tsfrontend/src/lib/hooks/useMetadata.tsfrontend/src/features/database/components/ForeignKeyPopover.tsxbackend/src/infra/database/migrations/bootstrap/bootstrap-migrations.jsfrontend/src/features/database/templates/ai-chatbot.tsbackend/src/services/functions/function.service.tsbackend/src/types/database.tsfrontend/src/features/database/templates/instagram-clone.tsbackend/src/services/ai/ai-config.service.tsbackend/src/services/database/database-table.service.tsfrontend/src/components/datagrid/datagridTypes.tsxfrontend/src/features/database/templates/reddit-clone.tsbackend/src/services/secrets/secret.service.tsbackend/src/services/usage/usage.service.tsbackend/src/utils/seed.tsfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxbackend/src/services/auth/auth.service.tsfrontend/src/features/database/hooks/useTables.tsbackend/src/services/auth/oauth-config.service.tsbackend/src/services/storage/storage.service.tsbackend/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.tsxfrontend/src/features/visualizer/components/SchemaVisualizer.tsxfrontend/src/features/database/templates/ecommerce-platform.tsfrontend/src/features/database/constants.tsfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/components/datagrid/index.tsfrontend/src/features/database/services/table.service.tsfrontend/src/features/database/templates/notion-clone.tsfrontend/src/lib/hooks/useMetadata.tsfrontend/src/features/database/components/ForeignKeyPopover.tsxfrontend/src/features/database/templates/ai-chatbot.tsfrontend/src/features/database/templates/instagram-clone.tsfrontend/src/components/datagrid/datagridTypes.tsxfrontend/src/features/database/templates/reddit-clone.tsfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/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.tsxbackend/src/services/auth/auth-config.service.tsbackend/src/api/routes/auth/oauth.routes.tsbackend/src/services/database/database-advance.service.tsfrontend/src/features/visualizer/components/SchemaVisualizer.tsxbackend/src/services/ai/ai-usage.service.tsfrontend/src/features/database/templates/ecommerce-platform.tsfrontend/src/features/database/constants.tsfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/components/datagrid/index.tsfrontend/src/features/database/services/table.service.tsfrontend/src/features/database/templates/notion-clone.tsbackend/src/types/storage.tsbackend/src/services/logs/audit.service.tsbackend/src/services/auth/auth-otp.service.tsfrontend/src/lib/hooks/useMetadata.tsfrontend/src/features/database/components/ForeignKeyPopover.tsxbackend/src/infra/database/migrations/bootstrap/bootstrap-migrations.jsfrontend/src/features/database/templates/ai-chatbot.tsbackend/src/services/functions/function.service.tsbackend/src/types/database.tsfrontend/src/features/database/templates/instagram-clone.tsbackend/src/services/ai/ai-config.service.tsbackend/src/services/database/database-table.service.tsfrontend/src/components/datagrid/datagridTypes.tsxfrontend/src/features/database/templates/reddit-clone.tsbackend/src/services/secrets/secret.service.tsbackend/src/services/usage/usage.service.tsbackend/src/utils/seed.tsfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxbackend/src/services/auth/auth.service.tsfrontend/src/features/database/hooks/useTables.tsbackend/src/services/auth/oauth-config.service.tsbackend/src/services/storage/storage.service.tsbackend/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.tsbackend/src/api/routes/auth/oauth.routes.tsbackend/src/services/database/database-advance.service.tsbackend/src/services/ai/ai-usage.service.tsbackend/src/types/storage.tsbackend/src/services/logs/audit.service.tsbackend/src/services/auth/auth-otp.service.tsbackend/src/infra/database/migrations/bootstrap/bootstrap-migrations.jsbackend/src/services/functions/function.service.tsbackend/src/types/database.tsbackend/src/services/ai/ai-config.service.tsbackend/src/services/database/database-table.service.tsbackend/src/services/secrets/secret.service.tsbackend/src/services/usage/usage.service.tsbackend/src/utils/seed.tsbackend/src/services/auth/auth.service.tsbackend/src/services/auth/oauth-config.service.tsbackend/src/services/storage/storage.service.tsbackend/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.tsbackend/src/api/routes/auth/oauth.routes.tsbackend/src/services/database/database-advance.service.tsbackend/src/services/ai/ai-usage.service.tsbackend/src/types/storage.tsbackend/src/services/logs/audit.service.tsbackend/src/services/auth/auth-otp.service.tsbackend/src/infra/database/migrations/bootstrap/bootstrap-migrations.jsshared-schemas/src/auth.schema.tsbackend/src/services/functions/function.service.tsbackend/src/types/database.tsbackend/src/services/ai/ai-config.service.tsbackend/src/services/database/database-table.service.tsbackend/src/services/secrets/secret.service.tsbackend/src/services/usage/usage.service.tsbackend/src/utils/seed.tsbackend/src/services/auth/auth.service.tsbackend/src/services/auth/oauth-config.service.tsbackend/src/services/storage/storage.service.tsbackend/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.tsbackend/src/services/database/database-advance.service.tsbackend/src/services/ai/ai-usage.service.tsbackend/src/services/logs/audit.service.tsbackend/src/services/auth/auth-otp.service.tsbackend/src/services/functions/function.service.tsbackend/src/services/ai/ai-config.service.tsbackend/src/services/database/database-table.service.tsbackend/src/services/secrets/secret.service.tsbackend/src/services/usage/usage.service.tsbackend/src/services/auth/auth.service.tsbackend/src/services/auth/oauth-config.service.tsbackend/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.tsopenapi/tables.yamlopenapi/auth.yamlopenapi/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.tsfrontend/src/features/database/constants.tsfrontend/src/components/datagrid/index.tsfrontend/src/features/database/services/table.service.tsfrontend/src/features/database/templates/notion-clone.tsfrontend/src/lib/hooks/useMetadata.tsfrontend/src/features/database/templates/ai-chatbot.tsfrontend/src/features/database/templates/instagram-clone.tsfrontend/src/features/database/templates/reddit-clone.tsfrontend/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.tsxfrontend/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.tsxbackend/src/services/database/database-advance.service.tsfunctions/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.tsbackend/src/services/functions/function.service.tsbackend/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.tsbackend/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.tsfrontend/src/features/database/constants.tsdocs/core-concepts/database/architecture.mdxbackend/src/services/functions/function.service.tsdocs/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.tsfrontend/src/features/database/templates/instagram-clone.tsfrontend/src/features/database/templates/reddit-clone.tsfrontend/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.tsxfrontend/src/components/datagrid/index.tsfrontend/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.tsxfrontend/src/components/datagrid/index.tsfrontend/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.tsfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/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.tsxfrontend/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
There was a problem hiding this comment.
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 betweenSET SCHEMAandRENAME, you can end up withsystem._migrationslingering (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
📒 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: setprocess.exitCode = 1and return, or restructure to ensureawait 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 thepgpackage's default import works with your Node version and invocation method (whether called vianode,tsx, or another loader).
There was a problem hiding this comment.
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)onauth.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 keepauth.usersRLS 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
📒 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 thesystemschema.
651-658: LGTM!The
quoteTableReferencemethod correctly handles the cross-schema reference forauth.usersby 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.userstoauth_usersto avoid dots in PostgreSQL constraint names, which improves compatibility and avoids potential issues with constraint manipulation. ThequoteTableReferenceusage ensures proper cross-schema FK references.
704-728: LGTM!The addition of
foreign_schemato 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 forForeignKeyRowis properly maintained.The
ForeignKeyRowinterface inbackend/src/types/database.tsincludes theforeign_schemaproperty (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.
There was a problem hiding this comment.
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
useUsersinvalidation (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 ofunknowncasts
users as unknown as DatabaseRecord[]works but is brittle if the users API shape diverges fromauthUsersSchema/DataGrid expectations. Consider mapping to aDatabaseRecordexplicitly (at least ensuringidand 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
selectionColumnWidthis hardcoded to180. 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
📒 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.tsxfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/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.tsxfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/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.tsxfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/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.tsxfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/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.tsxfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/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.tsxfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/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.tsxfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/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.tsxfrontend/src/features/database/components/ForeignKeyCell.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/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.tsxfrontend/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.tsxfrontend/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 consistentThe
isAuthUserssplit (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. Theprovidersfield is explicitly defined inUserSchema(asz.array(z.string()).optional()in auth.schema.ts line 39) and is properly typed asstring[] | 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.
There was a problem hiding this comment.
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.userduring 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
📒 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.tsbackend/src/api/routes/email/index.routes.tsshared-schemas/src/auth-api.schema.tsbackend/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.tsbackend/src/api/routes/email/index.routes.tsshared-schemas/src/auth-api.schema.tsbackend/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.tsbackend/src/api/routes/email/index.routes.tsshared-schemas/src/auth-api.schema.tsbackend/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.tsbackend/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.tsbackend/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.tsbackend/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.tsbackend/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.tsbackend/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.tsbackend/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.tsopenapi/email.yamlbackend/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.tsbackend/src/api/routes/email/index.routes.tsopenapi/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
userSchemainstead 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
SendEmailResponseschema 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
sendEmailResponseSchemaandSendEmailResponsetype 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 inindex.ts, ensuring it's available to consumers.
There was a problem hiding this comment.
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 fieldIn all email flows (
sendVerificationEmailWithCode/Link,sendResetPasswordEmailWithCode/Link),userNameis derived fromdbUser.metadata?.name || 'User', but:
- New registrations/OAuth users store names in
profile, notmetadata.- Migration 018 also populates
profile(not metadata) withname.Result: greetings for new users will almost always fall back to
'User'.Recommend preferring
profilewith 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 selectprofileand search still targets metadata.nameIssues:
getUserByEmail,getUserById, andlistUsersSELECT:
- Don’t include
u.profile, yettransformUserRecordToSchemareturnsprofile: dbUser.profile.- So
profilein all responses from login/register/listUsers/current-session will beundefined.
listUserssearch/count still filter onmetadata->>'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 keysThe FK rewrite loop only tracks a single
kcu.column_nameand recreatesFOREIGN KEY (%I) REFERENCES auth.users(id). Any composite FK referencingpublic.userswill be dropped and recreated incorrectly (or not at all).Consider either:
- Explicitly supporting only single-column FKs: group by constraint, ensure
COUNT(*) = 1, andRAISE EXCEPTIONif 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 duplicateproject_admin_policycreationBoth
system.create_default_policiesandsystem.create_policies_after_rlsunconditionallyCREATE 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_policiesfor(schemaname, tablename, policyname = 'project_admin_policy')before creating, or- Wrap
CREATE POLICYin aBEGIN ... EXCEPTION WHEN duplicate_object THEN NULL; ENDblock.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
deleteUserscurrently deletes any IDs provided:DELETE FROM auth.users WHERE id IN (...)Given new
is_project_admin/is_anonymousflags, 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
⛔ Files ignored due to path filters (1)
package-lock.jsonis 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.tsshared-schemas/src/auth-api.schema.tsbackend/src/types/auth.tsbackend/src/services/auth/auth.service.tsbackend/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.tsshared-schemas/src/auth-api.schema.tsbackend/src/types/auth.tsbackend/src/services/auth/auth.service.tsbackend/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.tsshared-schemas/src/auth-api.schema.tsbackend/src/types/auth.tsbackend/src/services/auth/auth.service.tsbackend/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.tsbackend/src/services/auth/auth.service.tsbackend/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.tsbackend/src/services/auth/auth.service.tsbackend/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.tsbackend/src/services/auth/auth.service.tsbackend/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.tsbackend/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 modelAdding
profile/metadataand populatingprofilefrompublic.usersand fallbackauth.users.name(with guards for empty profiles) avoids clobbering existing metadata and matches the new “profile vs metadata” semantics.
298-360: Sharedsystem.update_updated_attrigger consolidation looks goodCentralizing
updated_athandling intosystem.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 forauth.usersrequires manual verificationThe 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 straightforwardIncrementing
@insforge/shared-schemasto1.1.29is 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 structureAdding
profile,metadata,is_project_admin, andis_anonymoustoUserRecordaligns with the newauth.userstable and downstreamUserSchematransformation.shared-schemas/src/auth.schema.ts (1)
32-44: Public user schema aligns with new profile/metadata modelExposing
providers?,profile, andmetadatawhile omitting internal flags (is_project_admin,is_anonymous) gives a clean public shape that matches whatAuthServiceintends to return.shared-schemas/src/auth-api.schema.ts (1)
67-72: Profile request/response schemas are consistent with backend contracts
updateProfileRequestSchemawraps profile in a top-levelprofileobject, matchingAuthService.updateProfile(userId, profile).getCurrentSessionResponseSchemanow returns fulluserSchema, aligning withgetUserSchemaById.getProfileResponseSchema/GetProfileResponsemirror{ 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 correctAuth, body validation via
updateProfileRequestSchema, and delegation toauthService.updateProfileall line up with the newGetProfileResponsetype. Error handling is consistent with other routes.
330-347: GET /users/:userId admin endpoint matches new naming and error semanticsPath param rename to
userId, direct validation usinguserIdSchema, and 404'User does not exist'are sensible; response mirrorsUserSchemafromgetUserSchemaById.
273-297: GET /sessions/current now requires a user record in auth.users; anonymous and admin tokens will receive 401The 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
registernow writesprofileJSON from the optionalnameargument.createThirdPartyUserstores{ name, avatar_url }inprofileand propagates avatar intouser_providers.provider_data.- Admin login paths return a
UserSchemawithprofile: { name: 'Administrator' }andmetadata: null.All of these align with the new
auth.userscolumns and exportedUserSchema.Also applies to: 773-806, 822-830, 595-622, 627-653
1136-1179: The review comment is incorrect;updateProfileworks as written.The
pglibrary (v8.16.3) automatically serializes plain JavaScript objects to JSON when passed as parameters forjson/jsonbcolumns. Passing a plain object to$1::jsonbworks correctly without explicitJSON.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.
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
frontend/src/features/auth/components/UsersDataGrid.tsx (2)
191-199: Avoid trustingrow.profileshape viaascasts; add a small guard or stronger typing.Right now
row.profileis 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
profileever diverges (e.g.,profileisnull, 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/UserDataGridRowtyping soprofileis a proper{ avatar_url?: string; name?: string } | null, or- Adding a tiny runtime guard that checks
typeof profile === 'object'andtypeof (profile as any).avatar_url === 'string'/name === 'string'before using those values, falling back toundefinedotherwise.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):
Avatar error handling
IfavatarUrlis invalid, the<img>will show a broken icon. Track anavatarErrorstate and fall back to the placeholder when loading fails.Memoization
UserSelectionCellrenders for every row; wrapping it inmemoavoids 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+Nbadge looks correct and matches the new schema shape.Two small, optional tweaks:
- Use
uniqueProviders.join(', ')in thetitleso the tooltip matches the visible set.- Use
key={provider}instead ofkey={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
📒 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.tsxbackend/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.tsxbackend/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.tsxbackend/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.tsxbackend/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
listUsersmethod 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, andtransformUserRecordToSchemamethods 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
pgdriver 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
getProfileByIdandupdateProfilemethods properly support the profile-centric user schema:
getProfileByIdreturns only public profile data (id and profile)updateProfileuses PostgreSQL's JSONB merge operator (||) withCOALESCEto safely handle null profiles- Proper error handling and parameterized queries
The API layer validates profile structure using the Zod schema
updateProfileRequestSchemabefore callingupdateProfile, 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.
Userfromlucide-react,Checkbox, andSelectionCellPropsare 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'fromUsersDataGridPropsand hard-wiringselectionColumnWidth={180}andrenderSelectionCell={UserSelectionCell}makes the selection UX consistent and prevents external overrides.Just confirm no existing
UsersDataGridconsumers relied on customizing these props; TypeScript should already flag such usages if they exist.Also applies to: 241-242
There was a problem hiding this comment.
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 usingprofileSchemafor update validation.The
updateProfileRequestSchemausesz.record(z.unknown())which accepts any object, while theprofileSchemadefines specific fields (name,avatar_url) with validation (e.g., URL format foravatar_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
⛔ Files ignored due to path filters (1)
package-lock.jsonis 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.tsxauth/src/pages/SignUpPage.tsxauth/src/lib/broadcastService.tsshared-schemas/src/auth-api.schema.tsshared-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.tsxauth/src/pages/SignUpPage.tsxauth/src/lib/broadcastService.tsshared-schemas/src/auth-api.schema.tsshared-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.tsshared-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.tsshared-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 toUserSchemalooks good.Using the shared
UserSchematype ensures consistency across the codebase. Note that consumers ofBroadcastEventwill need to access user name viauser.profile?.nameinstead of the previoususer.name.
1-2: No module resolution issue exists. The@insforge/shared-schemasdependency is properly declared inauth/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
profileSchemacorrectly uses.passthrough()to allow custom profile fields beyondnameandavatar_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/providerTypetoproviders/profile/metadataproperly supports the new auth.users table structure. The use of.nullable()forprofileandmetadatacorrectly represents PostgreSQL NULL values, while.optional()forprovidersallows 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
getProfileResponseSchemacorrectly exposes onlyidandprofile, keeping sensitive user data (email, metadata) private. This is a good privacy-conscious design for public profile endpoints.
185-195: Verify ifrolefield should be included in the session response.The
getCurrentSessionResponseSchemausesuserSchema, which does not include arolefield. However, there are no usages ofuser.rolein 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 touserSchemaor the session response based on API requirements.
There was a problem hiding this comment.
Actionable comments posted: 1
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
package-lock.jsonis 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
|
upgrade from old proj 1.0.0 -> 1.3.0 EXISTS public.reload_postgrest_schema();
project creation failed with |
There was a problem hiding this comment.
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 referencingpublic.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, otherwiseRAISE EXCEPTIONto 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 theALTER 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, theIF NOT EXISTSclause 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_policyspecifically exists. If a different policy exists butproject_admin_policydoesn't, this block won't execute, which is correct. However, ifproject_admin_policyalready 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
⛔ Files ignored due to path filters (1)
package-lock.jsonis 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
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (5)
frontend/src/features/database/components/ForeignKeyPopover.tsx (1)
73-91: Potential duplicateauth.usersentry and schema drift risk.The
availableTablesarray prependsAUTH_USERS_TABLEwithout checking iftablesalready contains it, which could result in a duplicate entry. Additionally, the hardcodedreferenceTableSchemaat lines 87-90 only includesid, whileauthUsersSchemainconstants.tsdefines additional columns (email, emailVerified, etc.). Consider:
- Deduplicating with a
Setor filter check- Importing and reusing
authUsersSchemafromconstants.tsinstead 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
profilehasavatar_urlandnameas 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 whenuseUsersmutations 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: Useprocess.exitCodeinstead ofprocess.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, usingprocess.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 themetadataobject structure.The
metadatafield still usesadditionalProperties: truewithout 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) andavatar_url(string, optional/nullable), and keepadditionalProperties: trueif 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
updateSecretis 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.profileschema showsnameandavatar_urlas example properties underadditionalProperties: true. While the parentprofilefield is nullable, it's not explicitly clear whether these specific properties are required whenprofileis 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
📒 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.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxbackend/src/services/secrets/secret.service.tsfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/features/database/components/RecordFormField.tsxbackend/src/infra/database/migrations/bootstrap/bootstrap-migrations.jsfrontend/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.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/features/database/components/RecordFormField.tsxfrontend/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.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/features/database/components/RecordFormField.tsxfrontend/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.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxbackend/src/services/secrets/secret.service.tsfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/features/database/components/RecordFormField.tsxfrontend/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.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/features/database/components/RecordFormField.tsxfrontend/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.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxbackend/src/services/secrets/secret.service.tsfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/features/database/components/RecordFormField.tsxbackend/src/infra/database/migrations/bootstrap/bootstrap-migrations.jsfrontend/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.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/features/database/components/RecordFormField.tsxfrontend/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.tsxfrontend/src/features/database/components/LinkRecordModal.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxbackend/src/services/secrets/secret.service.tsfrontend/src/components/datagrid/DataGrid.tsxfrontend/src/features/database/components/RecordFormField.tsxbackend/src/infra/database/migrations/bootstrap/bootstrap-migrations.jsfrontend/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.tsbackend/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.tsbackend/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.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/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.tsxfrontend/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.tsxfrontend/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
userstopostsin SDK examples is a good practice. Using a neutral domain table avoids confusion with the actualauth.userssystem 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.nametouser.profile?.nameaccurately documents the new user schema where thenamefield has been moved into theprofileJSONB 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.secretsschema 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, andlistSecretshave been properly updated to referencesystem.secretswhile 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.timingSafeEqualprevents timing attacks during secret verification. The implementation correctly checks buffer lengths before callingtimingSafeEqual(which requires equal-length buffers), following security best practices.
259-314: Deletion, rotation, and cleanup methods correctly migrated.All SQL queries in
deleteSecret,rotateSecret, andcleanupExpiredSecretshave been properly updated tosystem.secrets. Transaction handling inrotateSecretis 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
authUsersSchemafrom 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 providedonJumpToTablecallback). The button label adapts appropriately.frontend/src/features/database/components/LinkRecordModal.tsx (3)
52-65: LGTM!The conditional hook setup properly disables
recordsHookfor auth.users and configuresuseUserswith appropriate gating. The search query is correctly passed only whenisAuthUsersis true.
88-108: LGTM!The
??operator at line 104 correctly handles the case whenpagination.totalis0, addressing the previous review concern about falsy value handling.
165-175: LGTM!The
renderCellValuehelper properly handles JSON type values by stringifying objects before passing toformatValueForDisplay, preventing[object Object]display issues.frontend/src/components/datagrid/DataGrid.tsx (3)
19-25: LGTM!The
SelectionCellPropsinterface is well-designed with appropriate generic typing. Exposingrow,isSelected,onToggle, andtabIndexprovides the necessary context for custom selection cell implementations.
92-118: LGTM!The selection column implementation is clean:
- Width configuration respects
selectionColumnWidthwith a sensible defaultmaxWidthbecomes undefined when custom renderer is provided, enabling resizing- The
handleTogglecallback 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
ProvidersCellRendererproperly 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
AvatarwithAvatarFallbackis a good improvement over a plainimgtag. TheAvatarFallbackhandles broken/missing avatar URLs gracefully by showing the User icon, eliminating the need for explicitonErrorhandling.
239-240: LGTM!The
selectionColumnWidthof 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 JSONcast was unnecessary and potentially misleading.result.valueis already properly typed asConvertedValueby theValueConversionResulttype, which accepts all values thatjsonSchema.parse()produces:null, parsed objects, and arrays. All of these are validConvertedValuetypes. 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)toauth.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.sqlmigration intentionally dropspublic.uid()with CASCADE (lines 214-219) as a breaking change to force migration to the newauth.uid()function. The migration explicitly documents this design decision in its comments and includes fallback RLS policies usingauth.uid()on the newauth.userstable (lines 203-211). Any RLS policies on user-created tables that depend onpublic.uid()must be recreated usingauth.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
tiktok,apple,x, andspotify.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
providersfield from array of objects to array of strings, making the response structure cleaner.
we need to migrate the migration table
* ✨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
There was a problem hiding this comment.
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
convertSqlTypeToColumnTypefunction 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
createTablemethod depends onsystem.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:
- Bootstrap script must complete and migrate the
_migrationstable before migration 018 runs- Migration 018 must complete fully before application code calls
createTable()- 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
quoteTableReferencemethod is hardcoded to only handleauth.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, orarrows-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.usersin both constraint naming (lines 696-698) and SQL generation (lines 703, 705). This logic is duplicated and tightly coupled to the hardcodedquoteTableReferencemethod.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_schemafrom 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
⛔ Files ignored due to path filters (3)
docs/favicon.pngis excluded by!**/*.pngdocs/favicon.svgis excluded by!**/*.svgpackage-lock.jsonis 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.tsbackend/src/api/routes/docs/index.routes.tsbackend/src/services/database/database-table.service.tsshared-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.tsbackend/src/api/routes/docs/index.routes.tsbackend/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.tsbackend/src/api/routes/docs/index.routes.tsbackend/src/services/database/database-table.service.tsshared-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.tsbackend/src/api/routes/docs/index.routes.tsbackend/src/services/database/database-table.service.tsshared-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.tsbackend/src/api/routes/docs/index.routes.tsbackend/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.tsbackend/src/api/routes/docs/index.routes.tsbackend/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_nameare standard SEO practices for documentation sites.
26-26: The favicon.png file exists in the repository at/docs/favicon.pngand 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
publicschema tables are exposed via PostgREST.docs/changelog.mdx (1)
6-158: Changelog restructuring looks good.The migration from accordion sections to standalone
Updateblocks with labels and tags improves readability and consistency. Documentation links are properly included for each feature announcement.
There was a problem hiding this comment.
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
📒 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
seedAdminUserbefore 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.
allow query information scehma
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (1)
backend/src/infra/database/migrations/018_schema-rework.sql (1)
217-219: Critical: CASCADE drop ofpublic.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
scoresdepends onuid()).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.userstables 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
📒 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
There was a problem hiding this comment.
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
sendEmailOTPLimiterto 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
📒 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.tsbackend/src/utils/cookies.tsbackend/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.tsbackend/src/utils/cookies.tsbackend/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.tsbackend/src/utils/cookies.tsbackend/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.tsbackend/src/utils/cookies.tsbackend/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.tsbackend/src/utils/cookies.tsbackend/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.tsbackend/src/utils/cookies.tsbackend/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.tsbackend/src/utils/cookies.tsbackend/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.tsbackend/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
verifyTokenmiddleware- 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
setAuthCookieandclearAuthCookiehave been correctly updated to pass thereqparameter, matching the new function signatures incookies.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 usereq.secureis secure and correct. Trust proxy is already properly configured in the application atbackend/src/server.ts:64withapp.set('trust proxy', true);, ensuringreq.securewill 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.
| } else { | ||
| const authAppUrl = process.env.AUTH_APP_URL || 'http://localhost:7132'; | ||
| logger.info('Auth app not built, proxying to development server', { authAppUrl }); | ||
| } |
There was a problem hiding this comment.
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
left a comment
There was a problem hiding this comment.
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
Summary
Reworked schema to the following standard:
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
Bug Fixes / Ops
Documentation
✏️ Tip: You can customize this high-level summary in your review settings.