Repository navigation
[Feat] Add Email Auth Service - #532
Conversation
WalkthroughAdds email OTP and singleton auth configuration persistence, EmailService for cloud templates, OTP creation/verification and rate-limiting, password-policy utilities, backend API and migrations for email flows, OpenAPI/shared-schema updates, frontend config UI/hooks/services, and related tests. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant Frontend
participant Backend
participant RateLimiter
participant DB
participant EmailSvc
participant CloudAPI
User->>Frontend: Request verification (email)
Frontend->>Backend: POST /auth/email/send-verification-code
Backend->>RateLimiter: check IP & per-email cooldown
alt blocked
RateLimiter-->>Backend: 429 RATE_LIMITED
Backend-->>Frontend: 429
else allowed
Backend->>DB: upsert _email_otps (hash, expiry)
DB-->>Backend: OTP row
Backend->>EmailSvc: sendWithTemplate(template, vars)
EmailSvc->>CloudAPI: POST /email/v1/{project}/send-with-template (signed)
CloudAPI-->>EmailSvc: 200
EmailSvc-->>Backend: success
Backend-->>Frontend: 202 Accepted
end
User->>Frontend: Submit OTP
Frontend->>Backend: POST /auth/verify-email {email, otp}
Backend->>RateLimiter: check verify attempts (counts failures)
Backend->>DB: SELECT FOR UPDATE _email_otps -> validate, increment attempts or mark consumed
alt valid
DB-->>Backend: consumed
Backend->>DB: create session / mark user verified
Backend-->>Frontend: 200 {session, accessToken}
else invalid/expired
DB-->>Backend: failure
Backend-->>Frontend: 400/401
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Areas to focus on:
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)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 23
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
backend/src/core/auth/auth.ts (3)
228-235: Use AppError(401) for invalid credentialsStandardize errors for auth failures.
- if (!dbUser || !dbUser.password) { - throw new Error('Invalid credentials'); - } + if (!dbUser || !dbUser.password) { + throw new AppError('Invalid credentials', 401, ERROR_CODES.AUTH_UNAUTHORIZED); + } @@ - if (!validPassword) { - throw new Error('Invalid credentials'); - } + if (!validPassword) { + throw new AppError('Invalid credentials', 401, ERROR_CODES.AUTH_UNAUTHORIZED); + }
161-167: Return a 409 AppError on duplicate registrationThe constant name in your suggestion is incorrect. Use
ERROR_CODES.ALREADY_EXISTSinstead ofERROR_CODES.CONFLICT(which doesn't exist in the codebase). This pattern is already used inbackend/src/core/auth/oauth.config.tsfor similar duplicate checks.if (existingUser) { - throw new Error('User already exists'); + throw new AppError('User already exists', 409, ERROR_CODES.ALREADY_EXISTS); }
160-220: Fix error handling inconsistency: use AppError with proper error code for duplicate emailThe
CreateUserResponsetype correctly includesrequiresEmailVerificationas an optional boolean, andINVALID_INPUTerror code exists. However, at line 169, the duplicate email check throws a plainError('User already exists')instead of following the established pattern of throwingAppErrorwith a proper error code (should useAUTH_EMAIL_EXISTS). This creates inconsistency with the rest of the function and other routes that useAppErrorwithERROR_CODES.The
CONFLICTandRATE_LIMITEDerror codes referenced in the review do not exist in theERROR_CODESenum—consider usingALREADY_EXISTSfor conflict scenarios andTOO_MANY_REQUESTSfor rate-limit cases if needed elsewhere.
🧹 Nitpick comments (28)
frontend/src/features/auth/components/AddOAuthDialog.tsx (1)
58-59: Unify wording: “Add Provider”Title now says “Add Provider” but CTA still says “Add OAuth”. Suggest aligning CTA.
Apply:
- Add OAuth + Add ProviderAlso applies to: 99-104
shared-schemas/src/auth-api.schema.ts (3)
75-79: Tighten OTP format if numericIf OTPs are numeric (common), enforce a fixed-length digit regex; improves validation symmetry with backend.
-export const verifyEmailRequestSchema = z.object({ - email: emailSchema, - verificationCode: z.string().min(4).max(8), -}); +const OTP_CODE_REGEX = /^\d{6}$/; +export const verifyEmailRequestSchema = z.object({ + email: emailSchema, + verificationCode: z.string().regex(OTP_CODE_REGEX, 'Invalid code'), +}); @@ -export const resetPasswordRequestSchema = z.object({ - email: emailSchema, - newPassword: passwordSchema, - verificationCode: z.string().min(4).max(8), -}); +export const resetPasswordRequestSchema = z.object({ + email: emailSchema, + newPassword: passwordSchema, + verificationCode: z.string().regex(OTP_CODE_REGEX, 'Invalid code'), +});If alphanumeric/variable-length is intended, ignore this.
Also applies to: 90-94
241-248: Standardize exported type names (drop “Schema” suffix)Other request types use “…Request”. These two include “…RequestSchema”; align for consistency.
-export type ResendVerificationEmailRequestSchema = z.infer< - typeof resendVerificationEmailRequestSchema ->; -export type VerifyEmailRequestSchema = z.infer<typeof verifyEmailRequestSchema>; +export type ResendVerificationEmailRequest = z.infer< + typeof resendVerificationEmailRequestSchema +>; +export type VerifyEmailRequest = z.infer<typeof verifyEmailRequestSchema>;
67-73: Naming in comments vs schema namesComment says “Request email verification,” schema is “resend…”. Minor but could confuse API docs. Consider aligning wording.
Also applies to: 83-86
backend/src/api/routes/auth.ts (1)
482-503: Consider harmonizing response status codes.The
/verify-emailendpoint returns 200 on success, while related endpoints like/resend-verification-emailreturn 202. Inconsistent status codes could potentially leak information about whether an account exists. Consider using 200 for both, or documenting why they differ.frontend/src/features/auth/components/EmailConfigDialog.tsx (4)
31-41: Surface validation errors to users.Form uses zodResolver but UI never shows field errors (e.g., passwordMinLength out of range). Render formState.errors and inline messages near inputs.
75-89: Add error state and retry.Loading UI exists; error from useEmailConfig is ignored. Show an error message with a Retry button (calls refetch).
As per coding guidelines
132-139: Clamp and sanitize numeric input.Use RHF validate to enforce 4–128 and coerce NaN to a safe value before submit; also show helper/error text.
As per coding guidelines
147-209: Normalize checkbox change handlers.If Checkbox mirrors Radix, prefer onCheckedChange(boolean) for consistency; otherwise keep as is. Ensure it passes boolean, not event.
backend/src/api/middleware/rate-limiters.ts (3)
15-27: Clear the cleanup interval on shutdown/tests.Keep a handle to setInterval and clear it on process exit signals to prevent leaks/flaky tests.
- setInterval( + const cooldownCleanup = setInterval( () => { @@ - 5 * 60 * 1000 + 5 * 60 * 1000 ); +process.on('SIGINT', () => clearInterval(cooldownCleanup)); +process.on('SIGTERM', () => clearInterval(cooldownCleanup));
116-119: Type the middleware arrays.Export typed arrays to ensure only RequestHandler items are used.
-import { Request, Response, NextFunction } from 'express'; +import { Request, Response, NextFunction, type RequestHandler } from 'express'; @@ -export const sendEmailOTPLimiter = [ +export const sendEmailOTPLimiter: RequestHandler[] = [ sendEmailOTPRateLimiter, perEmailCooldown(60000), // 60 second cooldown per email ]; @@ -export const verifyOTPLimiter = [verifyOTPRateLimiter]; +export const verifyOTPLimiter: RequestHandler[] = [verifyOTPRateLimiter];
41-47: Prefer next(new AppError(...)) in handler.Throwing inside handler can bypass some middlewares; call next(err) to integrate with error pipeline.
- handler: (_req: Request, _res: Response) => { - throw new AppError( + handler: (_req: Request, _res: Response, next: NextFunction) => { + next(new AppError( 'Too many send email verification requests from this IP. Please try again in 15 minutes.', 429, ERROR_CODES.TOO_MANY_REQUESTS - ); + )); },Apply similarly to verifyOTPRateLimiter.
backend/tests/unit/email.test.ts (2)
173-185: Brittle message matching in toThrow.Use regex/contains to avoid hard-coding full messages from AppError.
-await expect( - emailService.sendWithTemplate('', 'John', '123456', 'email-verification') -).rejects.toThrow('Missing required parameters'); +await expect( + emailService.sendWithTemplate('', 'John', '123456', 'email-verification') +).rejects.toThrow(/Missing required parameters/);Apply similarly to other toThrow assertions.
50-52: Avoid mutating process.env in tests unless needed.afterEach resets process.env without preceding mutations; remove to reduce side effects.
frontend/src/features/auth/components/ConfigurationTab.tsx (2)
40-56: deleteConfig mutate is async; try/catch here won’t catch errors.useMutation.mutate returns void; onError is handled in the hook. Remove try/catch or switch to mutateAsync and await it for local error handling.
- if (shouldDelete) { - try { - deleteConfig(providerId); - } catch (error) { - console.error(`Failed to delete ${providerId} OAuth:`, error); - } - } + if (shouldDelete) { + deleteConfig(providerId); + }Or:
- const { ..., deleteConfig, ... } = useOAuthConfig(); + const { ..., deleteConfigAsync, ... } = useOAuthConfig(); // expose mutateAsync @@ - try { - deleteConfig(providerId); - } catch (error) { - console.error(...) - } + await deleteConfigAsync(providerId);
170-231: Rendering only configured providers is fine; consider empty-state hint.When hasAuthMethods is true but some providers disabled, grid hides them. Optional: show “Add Provider” card tiles for disabled ones to improve discoverability.
backend/src/core/auth/auth.config.ts (2)
5-5: Verify logger export style.File imports logger as default; ensure utils/logger exports default to avoid runtime undefined.
30-69: Return consistent errors with details.Consider attaching nextActions to AppError for operator guidance (e.g., “Run migrate:up” if table missing).
backend/src/utils/utils.ts (2)
9-31: Improve password requirements message for clarity and grammarMake the message explicit (“be … and include …”), add an “and” before the last item, and end with a period.
-export function getPasswordRequirementsMessage(config: EmailAuthConfigSchema): string { - const requirements: string[] = []; - - requirements.push(`at least ${config.passwordMinLength} characters long`); - - if (config.requireNumber) { - requirements.push('at least one number'); - } - - if (config.requireLowercase) { - requirements.push('at least one lowercase letter'); - } - - if (config.requireUppercase) { - requirements.push('at least one uppercase letter'); - } - - if (config.requireSpecialChar) { - requirements.push('at least one special character'); - } - - return `Password must contain ${requirements.join(', ')}`; -} +export function getPasswordRequirementsMessage(config: EmailAuthConfigSchema): string { + const parts: string[] = []; + parts.push(`be at least ${config.passwordMinLength} characters long`); + if (config.requireNumber) parts.push('include at least one number'); + if (config.requireLowercase) parts.push('include at least one lowercase letter'); + if (config.requireUppercase) parts.push('include at least one uppercase letter'); + if (config.requireSpecialChar) parts.push('include at least one special character'); + + const last = parts.pop(); + const list = last ? (parts.length ? `${parts.join(', ')} and ${last}` : last) : ''; + return `Password must ${list}.`; +}
33-79: Harden SQL type mapping; avoid truncation fallback and handle parameterized typesCurrent fallback
sqlType.slice(0, 5)is unsafe (e.g., 'varchar(255)' -> 'varch'). Normalize by stripping size/precision and return a ColumnType for unknowns instead of a string union.-export const convertSqlTypeToColumnType = (sqlType: string): ColumnType | string => { - switch (sqlType.toLowerCase()) { +export const convertSqlTypeToColumnType = (sqlType: string): ColumnType => { + const t = sqlType.toLowerCase().replace(/\(.*\)/, '').trim(); + switch (t) { case 'uuid': return ColumnType.UUID; - case 'timestamptz': - case 'timestamp with time zone': + case 'timestamptz': + case 'timestamp with time zone': + case 'timestamp': + case 'timestamp without time zone': return ColumnType.DATETIME; case 'date': return ColumnType.DATE; - case 'integer': + case 'integer': case 'bigint': case 'smallint': case 'int': case 'int2': case 'int4': + case 'int8': case 'serial': case 'serial2': case 'serial4': case 'serial8': case 'smallserial': case 'bigserial': return ColumnType.INTEGER; case 'double precision': case 'real': - case 'numeric': + case 'numeric': case 'float': case 'float4': case 'float8': case 'decimal': return ColumnType.FLOAT; case 'boolean': case 'bool': return ColumnType.BOOLEAN; case 'json': case 'jsonb': case 'array': return ColumnType.JSON; case 'text': - case 'varchar': + case 'varchar': case 'char': case 'character varying': case 'character': return ColumnType.STRING; default: - return sqlType.slice(0, 5); + return ColumnType.STRING; } };openapi/auth.yaml (4)
386-419: Use consistent error semantics and include 429 for rate limitingReturn 400 for invalid/expired codes; reserve 401 for auth. Add 429 responses matching service behavior.
responses: '200': description: Verification email sent (if email exists) @@ - '400': - description: Invalid request + '400': + description: Invalid request + '429': + description: Too many requests
419-477: Align verify-email errors and add 429Match service: invalid/expired -> 400; include 429.
responses: '200': description: Email verified successfully, session created @@ - '400': - description: Invalid verification code - '401': - description: Verification code expired or invalid + '400': + description: Invalid or expired verification code + '429': + description: Too many requests
478-510: Add 429 for OTP request endpointDocument rate limiting behavior.
responses: '200': description: OTP sent (if email exists) @@ - '400': - description: Invalid request + '400': + description: Invalid request + '429': + description: Too many requests
511-569: Align verify-one-time-password errors and add 429Use 400 for invalid/expired and document 429.
responses: '200': description: OTP verified successfully, session created @@ - '400': - description: Invalid OTP - '401': - description: OTP expired or invalid + '400': + description: Invalid or expired OTP + '429': + description: Too many requestsbackend/src/core/email/email.ts (2)
136-143: Reduce logging of remote response bodies
error.response.datacan contain PII. Log status + message only.- logger.error('Failed to send email via cloud backend', { - projectId: config.cloud.projectId, - template, - status, - message, - error: error.response?.data, - }); + logger.error('Failed to send email via cloud backend', { + projectId: config.cloud.projectId, + template, + status, + message, + });
151-157: Use a specific rate-limit error codeMap 429 to a dedicated error code (e.g., RATE_LIMITED) for clearer handling across clients.
- } else if (status === 429) { - throw new AppError( - 'Email rate limit exceeded. Free plans are limited to 3000 emails per month.', - status, - ERROR_CODES.INTERNAL_ERROR - ); + } else if (status === 429) { + throw new AppError( + 'Email rate limit exceeded. Free plans are limited to 3000 emails per month.', + status, + ERROR_CODES.RATE_LIMITED + );Please confirm
ERROR_CODES.RATE_LIMITEDexists; if not, add it.backend/src/core/auth/auth.ts (2)
205-214: Registration should not hard-fail if email send failsOptional: catch send errors, log, and still return requiresEmailVerification=true so the client can request a resend.
- if (emailAuthConfig.requireEmailVerification) { - await this.sendVerificationEmail(email); - - return { - user, - accessToken: null, - requiresEmailVerification: true, - }; - } + if (emailAuthConfig.requireEmailVerification) { + try { + await this.sendVerificationEmail(email); + } catch (e) { + logger.warn('Verification email send failed during register', { email }); + } + return { user, accessToken: null, requiresEmailVerification: true }; + }
22-27: Import style consistency (with/without .js extensions)Mixed usage of extensionless and
.jsimports in TS can be brittle under different module resolvers. Standardize across the repo (prefer one approach).Also applies to: 41-41
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (38)
backend/migrations/015_create-auth-config-and-email-otp-tables.sql(1 hunks)backend/src/api/middleware/rate-limiters.ts(1 hunks)backend/src/api/routes/auth.oauth.ts(4 hunks)backend/src/api/routes/auth.ts(2 hunks)backend/src/app.config.ts(1 hunks)backend/src/core/auth/auth.config.ts(1 hunks)backend/src/core/auth/auth.otp.ts(1 hunks)backend/src/core/auth/auth.ts(7 hunks)backend/src/core/database/table.ts(1 hunks)backend/src/core/email/email.ts(1 hunks)backend/src/core/email/index.ts(1 hunks)backend/src/utils/helpers.ts(0 hunks)backend/src/utils/seed.ts(1 hunks)backend/src/utils/utils.ts(1 hunks)backend/src/utils/uuid.ts(0 hunks)backend/src/utils/validations.ts(1 hunks)backend/tests/unit/email.test.ts(1 hunks)backend/tests/unit/rate-limit.test.ts(1 hunks)backend/tests/unit/uuid.test.ts(1 hunks)docker-compose.yml(1 hunks)frontend/src/components/layout/AppSidebar.tsx(1 hunks)frontend/src/features/auth/components/AddOAuthDialog.tsx(1 hunks)frontend/src/features/auth/components/AuthMethodTab.tsx(0 hunks)frontend/src/features/auth/components/ConfigurationTab.tsx(1 hunks)frontend/src/features/auth/components/EmailConfigDialog.tsx(1 hunks)frontend/src/features/auth/components/UserFormDialog.tsx(1 hunks)frontend/src/features/auth/components/UsersDataGrid.tsx(1 hunks)frontend/src/features/auth/helpers.tsx(1 hunks)frontend/src/features/auth/hooks/useEmailConfig.ts(1 hunks)frontend/src/features/auth/hooks/useOAuthConfig.ts(2 hunks)frontend/src/features/auth/page/AuthenticationPage.tsx(4 hunks)frontend/src/features/auth/services/email-config.service.ts(1 hunks)frontend/src/features/auth/services/oauth-config.service.ts(2 hunks)frontend/src/features/login/page/LoginPage.tsx(2 hunks)frontend/src/lib/utils/validation-schemas.ts(1 hunks)openapi/auth.yaml(1 hunks)shared-schemas/src/auth-api.schema.ts(6 hunks)shared-schemas/src/auth.schema.ts(3 hunks)
💤 Files with no reviewable changes (3)
- backend/src/utils/uuid.ts
- backend/src/utils/helpers.ts
- frontend/src/features/auth/components/AuthMethodTab.tsx
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
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 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions
Files:
frontend/src/features/auth/services/oauth-config.service.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxbackend/src/utils/seed.tsfrontend/src/features/auth/hooks/useEmailConfig.tsfrontend/src/features/auth/services/email-config.service.tsbackend/src/app.config.tsfrontend/src/features/login/page/LoginPage.tsxbackend/src/api/routes/auth.oauth.tsfrontend/src/features/auth/components/EmailConfigDialog.tsxbackend/src/api/routes/auth.tsfrontend/src/features/auth/page/AuthenticationPage.tsxbackend/tests/unit/email.test.tsfrontend/src/features/auth/components/UserFormDialog.tsxfrontend/src/lib/utils/validation-schemas.tsbackend/src/core/email/index.tsbackend/src/core/auth/auth.config.tsbackend/src/core/auth/auth.otp.tsbackend/src/core/database/table.tsfrontend/src/features/auth/helpers.tsxshared-schemas/src/auth.schema.tsfrontend/src/components/layout/AppSidebar.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxbackend/tests/unit/rate-limit.test.tsbackend/tests/unit/uuid.test.tsbackend/src/utils/utils.tsbackend/src/api/middleware/rate-limiters.tsbackend/src/core/email/email.tsbackend/src/core/auth/auth.tsfrontend/src/features/auth/components/ConfigurationTab.tsxfrontend/src/features/auth/hooks/useOAuthConfig.tsbackend/src/utils/validations.tsshared-schemas/src/auth-api.schema.ts
frontend/src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders
Files:
frontend/src/features/auth/services/oauth-config.service.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/hooks/useEmailConfig.tsfrontend/src/features/auth/services/email-config.service.tsfrontend/src/features/login/page/LoginPage.tsxfrontend/src/features/auth/components/EmailConfigDialog.tsxfrontend/src/features/auth/page/AuthenticationPage.tsxfrontend/src/features/auth/components/UserFormDialog.tsxfrontend/src/lib/utils/validation-schemas.tsfrontend/src/features/auth/helpers.tsxfrontend/src/components/layout/AppSidebar.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/components/ConfigurationTab.tsxfrontend/src/features/auth/hooks/useOAuthConfig.ts
frontend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{ts,tsx}: Use TanStack Query for server state management
Use React Hook Form for form handling with Zod validation
Optimize bundle size with proper imports
Files:
frontend/src/features/auth/services/oauth-config.service.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/auth/hooks/useEmailConfig.tsfrontend/src/features/auth/services/email-config.service.tsfrontend/src/features/login/page/LoginPage.tsxfrontend/src/features/auth/components/EmailConfigDialog.tsxfrontend/src/features/auth/page/AuthenticationPage.tsxfrontend/src/features/auth/components/UserFormDialog.tsxfrontend/src/lib/utils/validation-schemas.tsfrontend/src/features/auth/helpers.tsxfrontend/src/components/layout/AppSidebar.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/components/ConfigurationTab.tsxfrontend/src/features/auth/hooks/useOAuthConfig.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
frontend/src/features/auth/services/oauth-config.service.tsfrontend/src/features/auth/components/AddOAuthDialog.tsxbackend/src/utils/seed.tsfrontend/src/features/auth/hooks/useEmailConfig.tsfrontend/src/features/auth/services/email-config.service.tsbackend/src/app.config.tsfrontend/src/features/login/page/LoginPage.tsxbackend/src/api/routes/auth.oauth.tsfrontend/src/features/auth/components/EmailConfigDialog.tsxbackend/src/api/routes/auth.tsfrontend/src/features/auth/page/AuthenticationPage.tsxbackend/tests/unit/email.test.tsfrontend/src/features/auth/components/UserFormDialog.tsxfrontend/src/lib/utils/validation-schemas.tsbackend/src/core/email/index.tsbackend/src/core/auth/auth.config.tsbackend/src/core/auth/auth.otp.tsbackend/src/core/database/table.tsfrontend/src/features/auth/helpers.tsxshared-schemas/src/auth.schema.tsfrontend/src/components/layout/AppSidebar.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxbackend/tests/unit/rate-limit.test.tsbackend/tests/unit/uuid.test.tsbackend/src/utils/utils.tsbackend/src/api/middleware/rate-limiters.tsbackend/src/core/email/email.tsbackend/src/core/auth/auth.tsfrontend/src/features/auth/components/ConfigurationTab.tsxfrontend/src/features/auth/hooks/useOAuthConfig.tsbackend/src/utils/validations.tsshared-schemas/src/auth-api.schema.ts
**/[a-z][a-zA-Z0-9]*.service.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Service files must be named camelCase.service.ts (e.g., auth.service.ts)
Files:
frontend/src/features/auth/services/oauth-config.service.tsfrontend/src/features/auth/services/email-config.service.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
frontend/src/features/auth/services/oauth-config.service.tsbackend/src/utils/seed.tsfrontend/src/features/auth/hooks/useEmailConfig.tsfrontend/src/features/auth/services/email-config.service.tsbackend/src/app.config.tsbackend/src/api/routes/auth.oauth.tsbackend/src/api/routes/auth.tsbackend/tests/unit/email.test.tsfrontend/src/lib/utils/validation-schemas.tsbackend/src/core/email/index.tsbackend/src/core/auth/auth.config.tsbackend/src/core/auth/auth.otp.tsbackend/src/core/database/table.tsshared-schemas/src/auth.schema.tsbackend/tests/unit/rate-limit.test.tsbackend/tests/unit/uuid.test.tsbackend/src/utils/utils.tsbackend/src/api/middleware/rate-limiters.tsbackend/src/core/email/email.tsbackend/src/core/auth/auth.tsfrontend/src/features/auth/hooks/useOAuthConfig.tsbackend/src/utils/validations.tsshared-schemas/src/auth-api.schema.ts
frontend/src/**/*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.tsx: Implement TypeScript interfaces/types for all component props
Follow component composition patterns; keep components focused and single-purpose
Implement proper loading and error states in UI
Use a consistent icon set from lucide-react
Files:
frontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/login/page/LoginPage.tsxfrontend/src/features/auth/components/EmailConfigDialog.tsxfrontend/src/features/auth/page/AuthenticationPage.tsxfrontend/src/features/auth/components/UserFormDialog.tsxfrontend/src/features/auth/helpers.tsxfrontend/src/components/layout/AppSidebar.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/components/ConfigurationTab.tsx
frontend/src/**/[A-Z]*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Component files must use PascalCase filenames (e.g., DataGrid.tsx)
Files:
frontend/src/features/auth/components/AddOAuthDialog.tsxfrontend/src/features/login/page/LoginPage.tsxfrontend/src/features/auth/components/EmailConfigDialog.tsxfrontend/src/features/auth/page/AuthenticationPage.tsxfrontend/src/features/auth/components/UserFormDialog.tsxfrontend/src/components/layout/AppSidebar.tsxfrontend/src/features/auth/components/UsersDataGrid.tsxfrontend/src/features/auth/components/ConfigurationTab.tsx
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/utils/seed.tsbackend/src/app.config.tsbackend/src/api/routes/auth.oauth.tsbackend/src/api/routes/auth.tsbackend/src/core/email/index.tsbackend/src/core/auth/auth.config.tsbackend/src/core/auth/auth.otp.tsbackend/src/core/database/table.tsbackend/src/utils/utils.tsbackend/src/api/middleware/rate-limiters.tsbackend/src/core/email/email.tsbackend/src/core/auth/auth.tsbackend/src/utils/validations.ts
frontend/src/**/use[A-Z]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Hook files must be named usePascalCase.ts (e.g., useAuth.ts)
Files:
frontend/src/features/auth/hooks/useEmailConfig.tsfrontend/src/features/auth/hooks/useOAuthConfig.ts
backend/src/api/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints
Files:
backend/src/api/routes/auth.oauth.tsbackend/src/api/routes/auth.tsbackend/src/api/middleware/rate-limiters.ts
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/email/index.tsbackend/src/core/auth/auth.config.tsbackend/src/core/auth/auth.otp.tsbackend/src/core/database/table.tsbackend/src/core/email/email.tsbackend/src/core/auth/auth.ts
openapi/**/*.{yml,yaml,json}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Document all API endpoints with clear OpenAPI documentation
Files:
openapi/auth.yaml
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement rate limiting for API endpoints
Applied to files:
backend/src/api/middleware/rate-limiters.ts
🧬 Code graph analysis (18)
frontend/src/features/auth/services/oauth-config.service.ts (1)
frontend/src/lib/api/client.ts (1)
apiClient(163-163)
frontend/src/features/auth/hooks/useEmailConfig.ts (4)
frontend/src/lib/hooks/useToast.tsx (1)
useToast(223-229)shared-schemas/src/auth.schema.ts (1)
EmailAuthConfigSchema(121-121)frontend/src/features/auth/services/email-config.service.ts (1)
emailConfigService(19-19)shared-schemas/src/auth-api.schema.ts (1)
UpdateEmailAuthConfigRequest(241-241)
frontend/src/features/auth/services/email-config.service.ts (3)
shared-schemas/src/auth.schema.ts (1)
EmailAuthConfigSchema(121-121)frontend/src/lib/api/client.ts (1)
apiClient(163-163)shared-schemas/src/auth-api.schema.ts (1)
UpdateEmailAuthConfigRequest(241-241)
frontend/src/features/login/page/LoginPage.tsx (1)
frontend/src/lib/utils/validation-schemas.ts (2)
LoginForm(123-123)loginFormSchema(118-121)
frontend/src/features/auth/components/EmailConfigDialog.tsx (4)
frontend/src/features/auth/hooks/useEmailConfig.ts (1)
useEmailConfig(6-48)shared-schemas/src/auth-api.schema.ts (2)
UpdateEmailAuthConfigRequest(241-241)updateEmailAuthConfigRequestSchema(204-208)frontend/src/features/auth/services/email-config.service.ts (1)
updateConfig(11-16)frontend/src/lib/utils/utils.ts (1)
isInsForgeCloudProject(158-160)
backend/src/api/routes/auth.ts (5)
backend/src/core/auth/auth.config.ts (1)
AuthConfigService(8-209)backend/src/core/logs/audit.ts (1)
AuditService(8-255)shared-schemas/src/auth-api.schema.ts (7)
GetEmailAuthConfigResponse(258-258)updateEmailAuthConfigRequestSchema(204-208)resendVerificationEmailRequestSchema(70-72)verifyEmailRequestSchema(75-78)CreateSessionResponse(251-251)sendResetPasswordEmailRequestSchema(83-85)resetPasswordRequestSchema(90-94)backend/src/utils/response.ts (1)
successResponse(22-24)backend/src/api/middleware/rate-limiters.ts (2)
sendEmailOTPLimiter(116-119)verifyOTPLimiter(125-125)
frontend/src/features/auth/page/AuthenticationPage.tsx (2)
frontend/src/features/auth/components/UsersTab.tsx (1)
UsersTab(14-120)frontend/src/features/auth/components/ConfigurationTab.tsx (1)
ConfigurationTab(20-263)
backend/tests/unit/email.test.ts (3)
backend/src/core/email/email.ts (1)
EmailService(16-219)backend/src/app.config.ts (1)
config(30-54)backend/src/api/middleware/error.ts (1)
AppError(7-17)
backend/src/core/auth/auth.config.ts (5)
backend/src/utils/logger.ts (1)
logger(6-29)backend/src/core/database/manager.ts (1)
DatabaseManager(10-254)shared-schemas/src/auth.schema.ts (1)
EmailAuthConfigSchema(121-121)backend/src/api/middleware/error.ts (1)
AppError(7-17)shared-schemas/src/auth-api.schema.ts (1)
UpdateEmailAuthConfigRequest(241-241)
backend/src/core/auth/auth.otp.ts (4)
backend/src/utils/logger.ts (1)
logger(6-29)backend/src/core/database/manager.ts (1)
DatabaseManager(10-254)backend/src/utils/utils.ts (1)
generateNumericCode(94-105)backend/src/api/middleware/error.ts (1)
AppError(7-17)
backend/tests/unit/rate-limit.test.ts (2)
backend/src/api/middleware/rate-limiters.ts (1)
perEmailCooldown(83-110)backend/src/api/middleware/error.ts (1)
AppError(7-17)
backend/src/utils/utils.ts (1)
shared-schemas/src/auth.schema.ts (1)
EmailAuthConfigSchema(121-121)
backend/src/api/middleware/rate-limiters.ts (1)
backend/src/api/middleware/error.ts (1)
AppError(7-17)
backend/src/core/email/email.ts (3)
backend/src/app.config.ts (1)
config(30-54)backend/src/api/middleware/error.ts (1)
AppError(7-17)backend/src/utils/logger.ts (1)
logger(6-29)
backend/src/core/auth/auth.ts (7)
backend/src/core/auth/auth.config.ts (1)
AuthConfigService(8-209)backend/src/utils/validations.ts (1)
validatePassword(15-42)backend/src/api/middleware/error.ts (1)
AppError(7-17)backend/src/utils/utils.ts (1)
getPasswordRequirementsMessage(9-31)backend/src/core/auth/auth.otp.ts (1)
AuthOTPService(39-221)backend/src/core/email/email.ts (1)
EmailService(16-219)backend/src/core/database/manager.ts (1)
DatabaseManager(10-254)
frontend/src/features/auth/components/ConfigurationTab.tsx (8)
frontend/src/features/auth/helpers.tsx (2)
OAuthProviderInfo(15-21)oauthProviders(23-66)frontend/src/lib/hooks/useConfirm.ts (1)
useConfirm(11-55)frontend/src/features/auth/hooks/useOAuthConfig.ts (1)
useOAuthConfig(13-133)frontend/src/features/auth/components/OAuthEmptyState.tsx (1)
OAuthEmptyState(3-15)frontend/src/features/auth/components/EmailConfigDialog.tsx (1)
EmailConfigDialog(28-239)frontend/src/features/auth/components/OAuthConfigDialog.tsx (1)
OAuthConfigDialog(39-321)frontend/src/features/auth/components/AddOAuthDialog.tsx (1)
AddOAuthDialog(22-109)frontend/src/components/ConfirmDialog.tsx (1)
ConfirmDialog(25-96)
backend/src/utils/validations.ts (1)
shared-schemas/src/auth.schema.ts (1)
EmailAuthConfigSchema(121-121)
shared-schemas/src/auth-api.schema.ts (1)
shared-schemas/src/auth.schema.ts (3)
emailSchema(14-14)passwordSchema(16-16)emailAuthConfigSchema(86-96)
🔇 Additional comments (32)
frontend/src/features/auth/components/UsersDataGrid.tsx (1)
164-171: Field verification confirmed—emailVerifiedexists inUserSchemaand is properly typed.The
emailVerifiedfield is defined asz.boolean()inshared-schemas/src/auth.schema.tsand is consistently used throughout the codebase (backend auth logic sets it fromemail_verified, and the new column correctly renders it with the boolean renderer). The implementation is correct.backend/src/utils/seed.ts (1)
6-6: The import path refactor is complete and correct.Verification confirms:
- New file
backend/src/core/auth/oauth.config.tsexists and exportsOAuthConfigService- Old
oauth.jsfile has been removed- All backend files that use
OAuthConfigServicehave been successfully migrated to the new path:
backend/src/utils/seed.ts(line 6)backend/src/api/routes/auth.oauth.ts(line 3)backend/src/core/auth/auth.ts(line 22)- The
getInstance()method is present and properly implemented- No remaining references to the old path exist
The change at line 6 is consistent with the broader refactor and poses no risk.
frontend/src/features/login/page/LoginPage.tsx (1)
27-27: Type rename implemented correctly.The rename from
LoginFormDatatoLoginFormis consistently applied across imports and type annotations with no functional changes.Also applies to: 36-36, 44-44
frontend/src/lib/utils/validation-schemas.ts (1)
123-123: Type rename implemented correctly.The rename from
LoginFormDatatoLoginFormfollows TypeScript conventions and maintains proper type inference from the schema.frontend/src/components/layout/AppSidebar.tsx (1)
42-42: Label tweak LGTMSingular “Authentication” reads better and aligns with recent UI. No routing/logic impact.
shared-schemas/src/auth-api.schema.ts (2)
105-107: Response changes look goodNullable accessToken + optional requiresEmailVerification aligns with verification-required flows.
204-214: Email auth config schemas: solidUpdate request omits id/timestamps; GET reuses base schema. Good reuse.
docker-compose.yml (1)
93-93: CLOUD_API_HOST addition verified—no issues foundAll backend usages (app.config.ts, utils/cloud-token.ts, core/ai/client.ts, core/auth/auth.ts) consistently reference the env var with identical fallback to
https://api.insforge.dev. Variable name is spelled correctly across all 11 occurrences. Docker-compose syntax is correct.backend/src/app.config.ts (1)
1-2: No action required—current code is appropriate.The
backend/tsconfig.jsonhas"esModuleInterop": true, so the condition stated in the review comment ("if tsconfig lacks esModuleInterop") is not met. The current default import pattern is valid and correctly follows TypeScript conventions for this configuration. Whileimport 'dotenv/config'would also work, it is an optional optimization rather than a necessary fix.frontend/src/features/auth/components/UserFormDialog.tsx (1)
14-14: LGTM! Centralized validation schema.Moving
emailSchemato the shared schemas package promotes consistency across frontend and backend validation.frontend/src/features/auth/hooks/useOAuthConfig.ts (2)
38-41: LGTM! Improved query enablement logic.The tightened enablement conditions prevent unnecessary API calls by ensuring:
- A provider is selected
- The configs list has loaded
- The provider exists in the loaded configs
This defensive approach reduces errors and improves performance.
10-10: Service reorganization verified successfully.The renamed service module exists at the correct location and is properly imported. No references to the old service path remain in the codebase. The hook correctly uses the new
oauthConfigServiceexport, and the enhanced query enablement logic defensively prevents unnecessary API calls.frontend/src/features/auth/helpers.tsx (1)
10-13: LGTM! Type-safe tab identifiers.The
AuthTabenum provides type safety for tab navigation, replacing string literals with a centralized definition.backend/src/core/email/index.ts (1)
1-1: Verification passed. BothEmailServiceandEmailTemplateare properly exported fromemail.tsand correctly re-exported through the barrel file.backend/src/core/database/table.ts (1)
24-24: Import path change verified.The function
convertSqlTypeToColumnTypeis correctly exported from@/utils/utils.tsat line 33. The import consolidation is complete and valid.backend/tests/unit/uuid.test.ts (1)
2-2: Consolidation verified as complete and correct.The
generateUUIDfunction was successfully moved tobackend/src/utils/utils.ts, the olduuid.tsmodule was removed, and the test import was correctly updated. No other test files reference the old path, and the function exists at the new location. The change is valid.frontend/src/features/auth/services/oauth-config.service.ts (1)
19-19: Backend routes match the updated frontend paths—no issues found.The verification confirms that the endpoint paths in the frontend service align correctly with the backend routes. The apiClient prepends
/apivia itsAPI_BASEconstant, so calls to/auth/oauth/${provider}/configresolve to/api/auth/oauth/:provider/config, which matches the backend routes for GET, PUT, and DELETE operations.backend/src/api/routes/auth.oauth.ts (2)
3-3: LGTM - Clean refactoring.The import path update aligns with the new OAuth configuration service structure.
55-57: LGTM - Consistent route restructuring.The route path changes from
/configs/:providerto/:provider/configimprove REST API consistency by placing provider-specific config under the provider namespace.Also applies to: 140-142, 201-203
shared-schemas/src/auth.schema.ts (2)
85-96: LGTM - Well-structured configuration schema.The
emailAuthConfigSchemaproperly models configurable authentication requirements with appropriate constraints (e.g.,passwordMinLengthbounded between 4 and 128).
16-16: Dynamic password validation is properly implemented in all password-handling flows.Verification confirms that password validation using
emailAuthConfigsettings is correctly implemented across all three critical flows:
- Registration (backend/src/core/auth/auth.ts, line 173)
- Password change (backend/src/core/auth/auth.ts, line 364)
- Password reset (backend/src/core/auth/auth.ts, line ~365)
Each flow retrieves the dynamic config, validates the password against all requirements (passwordMinLength, requireNumber, requireLowercase, requireUppercase, requireSpecialChar), and returns appropriate error messages. The schema change from constrained to plain
z.string()is properly compensated by runtime validation.frontend/src/features/auth/services/email-config.service.ts (1)
1-19: LGTM - Clean service implementation.The service follows established patterns and properly encapsulates email authentication configuration operations.
frontend/src/features/auth/hooks/useEmailConfig.ts (1)
1-48: LGTM - Proper react-query implementation.The hook correctly implements query and mutation patterns with appropriate error handling and cache invalidation.
backend/migrations/015_create-auth-config-and-email-otp-tables.sql (2)
7-28: LGTM - Well-designed OTP table.The
_email_otpstable properly handles OTP storage with:
- Unique constraint on (email, purpose) to prevent duplicate active OTPs
- Proper indexes for query performance
- Tracking of attempts and consumption
30-69: LGTM - Proper singleton pattern implementation.The
_auth_configstable correctly implements a singleton pattern using a unique index on a constant expression. The CHECK constraint ensures password_min_length stays within reasonable bounds (4-128).frontend/src/features/auth/page/AuthenticationPage.tsx (1)
8-8: LGTM - Type-safe refactor.Replacing string literals with the
AuthTabenum improves type safety and makes the code more maintainable. The rename from "Auth Methods" to "Configuration" better reflects the unified configuration UI.Also applies to: 13-13, 18-18, 49-49, 55-56, 88-88, 139-139, 147-147
backend/src/api/routes/auth.ts (5)
3-3: LGTM - Proper service initialization.The new imports and service instances are correctly initialized following the singleton pattern.
Also applies to: 10-10, 36-36
42-90: LGTM - Secure admin configuration endpoints.The email auth configuration endpoints properly:
- Restrict access to admins only
- Validate input using Zod schemas
- Log configuration changes via audit service
- Handle errors appropriately
445-480: LGTM - Good user enumeration prevention.The endpoint properly prevents user enumeration by:
- Silently catching errors (lines 462-468)
- Always returning 202 Accepted with a generic message
- Still applying rate limiting to prevent abuse
505-540: LGTM - Consistent security pattern.The password reset email endpoint follows the same secure pattern as the verification email endpoint, preventing user enumeration while maintaining rate limiting.
542-566: LGTM - Secure password reset flow.The reset password endpoint properly:
- Applies rate limiting
- Validates input via Zod schema
- Delegates to AuthService for OTP verification and password update
- Returns appropriate success message
frontend/src/features/auth/components/EmailConfigDialog.tsx (1)
92-118: Confirm Cloud-only toggle is intentional.Email verification switch is gated by isInsForgeCloudProject(). If self‑hosted users need this, remove the gate or document it.
There was a problem hiding this comment.
Actionable comments posted: 10
♻️ Duplicate comments (1)
backend/src/core/auth/auth.otp.ts (1)
7-7: Fix logger import to use named export
loggeris exported as a named symbol from@/utils/logger.js. Default-importing it leavesloggerundefined at runtime, so every call tologger.info/errorwill throw. Please switch to the named import.-import logger from '@/utils/logger.js'; +import { logger } from '@/utils/logger.js';
🧹 Nitpick comments (2)
shared-schemas/src/auth-api.schema.ts (2)
74-86: Strengthen OTP validation bounds.The
otpfield accepts any string withmin(1), but per the comments and backend implementation, it should be either a 6-digit code or a 64-character hex token.Apply this diff to add basic length constraints:
export const verifyEmailRequestSchema = z .object({ email: emailSchema.optional(), - otp: z.string().min(1), + otp: z.string().min(6).max(64), }) .refine((data) => data.email || data.otp, { message: 'Either email or otp must be provided', });
95-108: Strengthen OTP validation bounds.Same issue as
verifyEmailRequestSchema– theotpfield should enforce min/max length constraints.Apply this diff:
export const resetPasswordRequestSchema = z .object({ email: emailSchema.optional(), newPassword: passwordSchema, - otp: z.string().min(1), + otp: z.string().min(6).max(64), }) .refine((data) => data.email || data.otp, { message: 'Either email or otp must be provided', });
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (9)
backend/migrations/015_create-auth-config-and-email-otp-tables.sql(1 hunks)backend/src/api/routes/auth.ts(2 hunks)backend/src/core/auth/auth.otp.ts(1 hunks)backend/src/core/auth/auth.ts(6 hunks)backend/src/core/email/email.ts(1 hunks)backend/src/utils/utils.ts(1 hunks)backend/tests/unit/email.test.ts(1 hunks)backend/tests/unit/helpers.test.ts(1 hunks)shared-schemas/src/auth-api.schema.ts(6 hunks)
✅ Files skipped from review due to trivial changes (1)
- backend/tests/unit/helpers.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- backend/migrations/015_create-auth-config-and-email-otp-tables.sql
🧰 Additional context used
📓 Path-based instructions (6)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
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 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions
Files:
backend/tests/unit/email.test.tsbackend/src/core/email/email.tsbackend/src/utils/utils.tsbackend/src/api/routes/auth.tsshared-schemas/src/auth-api.schema.tsbackend/src/core/auth/auth.tsbackend/src/core/auth/auth.otp.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
backend/tests/unit/email.test.tsbackend/src/core/email/email.tsbackend/src/utils/utils.tsbackend/src/api/routes/auth.tsshared-schemas/src/auth-api.schema.tsbackend/src/core/auth/auth.tsbackend/src/core/auth/auth.otp.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/tests/unit/email.test.tsbackend/src/core/email/email.tsbackend/src/utils/utils.tsbackend/src/api/routes/auth.tsshared-schemas/src/auth-api.schema.tsbackend/src/core/auth/auth.tsbackend/src/core/auth/auth.otp.ts
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/core/email/email.tsbackend/src/utils/utils.tsbackend/src/api/routes/auth.tsbackend/src/core/auth/auth.tsbackend/src/core/auth/auth.otp.ts
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/email/email.tsbackend/src/core/auth/auth.tsbackend/src/core/auth/auth.otp.ts
backend/src/api/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints
Files:
backend/src/api/routes/auth.ts
🧠 Learnings (9)
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to tests/**/*.{test,spec}.{ts,tsx} : Implement integration tests for API endpoints
Applied to files:
backend/tests/unit/email.test.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to tests/**/*.{test,spec}.{ts,tsx} : Mock external dependencies appropriately in tests
Applied to files:
backend/tests/unit/email.test.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/**/*.{ts,tsx} : Return consistent API responses using utility functions
Applied to files:
backend/src/utils/utils.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement authentication and error-handling middleware
Applied to files:
backend/src/api/routes/auth.tsbackend/src/core/auth/auth.tsbackend/src/core/auth/auth.otp.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement rate limiting for API endpoints
Applied to files:
backend/src/api/routes/auth.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Follow RESTful conventions for API endpoints
Applied to files:
backend/src/api/routes/auth.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/**/*.{ts,tsx} : Use Zod schemas for request/response validation
Applied to files:
shared-schemas/src/auth-api.schema.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/{controllers,core}/**/*.ts : Implement proper database transaction handling
Applied to files:
backend/src/core/auth/auth.tsbackend/src/core/auth/auth.otp.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to **/*.{ts,tsx} : Implement proper error handling with try-catch blocks and logging where appropriate
Applied to files:
backend/src/core/auth/auth.otp.ts
🧬 Code graph analysis (7)
backend/tests/unit/email.test.ts (3)
backend/src/core/email/email.ts (1)
EmailService(20-201)backend/src/app.config.ts (1)
config(30-54)backend/src/api/middleware/error.ts (1)
AppError(7-17)
backend/src/core/email/email.ts (3)
backend/src/app.config.ts (1)
config(30-54)backend/src/api/middleware/error.ts (1)
AppError(7-17)backend/src/utils/logger.ts (1)
logger(6-29)
backend/src/utils/utils.ts (1)
shared-schemas/src/auth.schema.ts (1)
EmailAuthConfigSchema(121-121)
backend/src/api/routes/auth.ts (7)
backend/src/core/auth/auth.ts (1)
AuthService(50-1877)backend/src/core/auth/auth.config.ts (1)
AuthConfigService(8-214)backend/src/core/logs/audit.ts (1)
AuditService(8-255)backend/src/api/middleware/auth.ts (2)
verifyAdmin(71-116)AuthRequest(8-17)shared-schemas/src/auth-api.schema.ts (7)
GetEmailAuthConfigResponse(270-270)updateEmailAuthConfigRequestSchema(218-222)resendVerificationEmailRequestSchema(70-72)verifyEmailRequestSchema(79-86)CreateSessionResponse(263-263)sendResetPasswordEmailRequestSchema(91-93)resetPasswordRequestSchema(100-108)backend/src/utils/response.ts (1)
successResponse(22-24)backend/src/api/middleware/rate-limiters.ts (2)
sendEmailOTPLimiter(118-121)verifyOTPLimiter(127-127)
shared-schemas/src/auth-api.schema.ts (1)
shared-schemas/src/auth.schema.ts (4)
emailSchema(14-14)passwordSchema(16-16)userSchema(33-48)emailAuthConfigSchema(86-96)
backend/src/core/auth/auth.ts (8)
backend/src/api/middleware/error.ts (1)
AppError(7-17)shared-schemas/src/auth-api.schema.ts (3)
CreateUserResponse(262-262)CreateSessionResponse(263-263)CreateAdminSessionResponse(264-264)backend/src/core/auth/auth.config.ts (1)
AuthConfigService(8-214)backend/src/utils/validations.ts (1)
validatePassword(15-42)backend/src/utils/utils.ts (1)
getPasswordRequirementsMessage(9-31)backend/src/core/auth/auth.otp.ts (1)
AuthOTPService(59-388)backend/src/core/email/email.ts (1)
EmailService(20-201)backend/src/core/database/manager.ts (1)
DatabaseManager(10-254)
backend/src/core/auth/auth.otp.ts (4)
backend/src/utils/logger.ts (1)
logger(6-29)backend/src/core/database/manager.ts (1)
DatabaseManager(10-254)backend/src/utils/utils.ts (2)
generateNumericCode(94-102)generateSecureToken(112-114)backend/src/api/middleware/error.ts (1)
AppError(7-17)
🔇 Additional comments (7)
backend/src/core/email/email.ts (1)
4-4: ****The review comment is based on incorrect assumptions about the logger module. The file
backend/src/utils/logger.tsexports the logger object in both forms:
- Named export:
export const logger = ...- Default export:
export default logger;This means both import styles work correctly:
import logger from '@/utils/logger'✓ (uses the default export)import { logger } from '@/utils/logger'✓ (uses the named export)The claim that "default-importing returns
undefined" is incorrect. All 30 files across the codebase using the default import form are working correctly. The module intentionally supports both import styles, so no changes are required.Likely an incorrect or invalid review comment.
shared-schemas/src/auth-api.schema.ts (2)
117-121: LGTM!The schema changes correctly model the new registration flow where email verification may be required before returning user data and access tokens.
218-227: LGTM!Email auth configuration schemas follow the established pattern used for OAuth configs in this file.
backend/src/core/auth/auth.ts (4)
207-219: Verify intentional omission of user object.When email verification is required, the response includes only
accessToken: nullandrequiresEmailVerification: true, but omits theuserobject. The schema permits this (user is optional), but it means the frontend cannot display user info until after verification completes.Confirm this is intentional. If the user should be returned (without a token) so the UI can show "verification email sent to [email]", then adjust:
if (emailAuthConfig.requireEmailVerification) { try { await this.sendVerificationEmailWithLink(email); } catch (error) { logger.warn('Verification email send failed during register', { error }); } return { + user, accessToken: null, requiresEmailVerification: true, }; }
230-263: LGTM!Login properly validates credentials and enforces email verification when required, with clear error messaging.
175-198: LGTM!Registration now uses proper transaction handling with BEGIN/COMMIT/ROLLBACK and correctly handles unique constraint violations, addressing earlier review feedback.
165-171: LGTM!Password validation properly uses shared utilities and provides clear, user-friendly error messages.
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 (1)
backend/src/core/auth/auth.ts (1)
1-1885: CRITICAL: Do not merge without testing given the bugs found.The PR objectives state you "did not test the change and indicated intent to ship without testing." This review found 2 critical bugs that will cause runtime failures:
- Line 5 in auth.config.ts: Logger import will be
undefined, causing crashes- Lines 206-220 in auth.config.ts: UPDATE without WHERE clause will corrupt all config rows
Additionally, 4 major issues with inconsistent error handling (generic
Errorinstead ofAppError) remain unfixed despite past review comments.Required before merge:
- Fix both critical bugs
- Write integration tests covering:
- Email verification flow (code and link)
- Password reset flow (code and link)
- Email config CRUD operations
- Concurrent config updates (test the FOR UPDATE lock)
- Rate limiting behavior
- User enumeration prevention
- Test error paths (invalid OTP, expired token, etc.)
- Verify email templates render correctly
These flows are authentication-critical and cannot be deployed untested.
♻️ Duplicate comments (6)
backend/src/core/auth/auth.config.ts (2)
5-5: Fix logger import (named vs default).
loggeris exported as a named export from@/utils/logger.js, but line 5 uses a default import. This will beundefinedat runtime and cause crashes.Apply this diff:
-import logger from '@/utils/logger.js'; +import { logger } from '@/utils/logger.js';Based on learnings
149-239: UPDATE without WHERE updates all rows—add WHERE id = $N.Lines 206-220 execute an UPDATE with no WHERE clause, which will modify every row in
_auth_configsif multiple rows exist. Past review comments flagged this but it remains unfixed.Fix by capturing the id from line 155 and adding a WHERE clause:
// Ensure config exists and lock row to prevent concurrent modifications const existingResult = await client.query('SELECT id FROM _auth_configs LIMIT 1 FOR UPDATE'); + let configId: string; if (!existingResult.rows.length) { // Create default config if it doesn't exist, reusing the same client for transactional consistency - await this.createDefaultConfig(client); + const defaultConfig = await this.createDefaultConfig(client); + configId = defaultConfig.id; + } else { + configId = existingResult.rows[0].id; } // ... build updates ... + // Add updated_at to updates updates.push('updated_at = NOW()'); const result = await client.query( `UPDATE _auth_configs SET ${updates.join(', ')} + WHERE id = $${paramCount} RETURNING id, require_email_verification as "requireEmailVerification", @@ created_at as "createdAt", updated_at as "updatedAt"`, - values + [...values, configId] );backend/src/core/auth/auth.ts (4)
329-379: Use AppError for consistent error handling.Line 359 throws a generic
Errorinstead ofAppError, breaking error-handling consistency. Past review comments flagged this but it remains unfixed.Apply this diff:
if (result.rows.length === 0) { - throw new Error('User not found'); + throw new AppError('User not found', 404, ERROR_CODES.NOT_FOUND); }
386-432: Use AppError for consistent error handling.Line 412 throws a generic
Errorinstead ofAppError. This was flagged in past reviews but remains unfixed.Apply this diff:
if (result.rows.length === 0) { - throw new Error('User not found'); + throw new AppError('User not found', 404, ERROR_CODES.NOT_FOUND); }
499-560: Use AppError for consistent error handling.Line 546 throws a generic
Errorinstead ofAppError. Past review comments flagged this for consistency.Apply this diff:
if (result.rows.length === 0) { - throw new Error('User not found'); + throw new AppError('User not found', 404, ERROR_CODES.NOT_FOUND); }Note: The password validation at lines 504-515 before OTP verification is good design—it allows users to retry with a valid password without consuming the OTP.
567-623: Use AppError for consistent error handling.Line 609 throws a generic
Errorinstead ofAppError. This was flagged in previous reviews.Apply this diff:
if (result.rows.length === 0) { - throw new Error('User not found'); + throw new AppError('User not found', 404, ERROR_CODES.NOT_FOUND); }
🧹 Nitpick comments (1)
openapi/auth.yaml (1)
534-698: Document OTP field constraints in request schemas.The
otpfield in/verify-email(line 559-562) and/reset-password(line 679-682) should document expected formats more clearly:
- For numeric codes: exactly 6 digits (
pattern: '^[0-9]{6}$')- For link tokens: 64-character hex string (
minLength: 64, maxLength: 64, pattern: '^[a-f0-9]{64}$')Consider adding JSON schema validation to make the dual-path behavior explicit:
otp: type: string - description: Either a 6-digit numeric code or a 64-character hex token from magic link + description: Either a 6-digit numeric code or a 64-character hex token from magic link + oneOf: + - pattern: '^[0-9]{6}$' + description: 6-digit numeric code + - pattern: '^[a-f0-9]{64}$' + description: 64-character hex token from magic link example: "123456"
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (4)
backend/src/api/routes/auth.ts(2 hunks)backend/src/core/auth/auth.config.ts(1 hunks)backend/src/core/auth/auth.ts(6 hunks)openapi/auth.yaml(14 hunks)
🧰 Additional context used
📓 Path-based instructions (7)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
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 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions
Files:
backend/src/core/auth/auth.config.tsbackend/src/api/routes/auth.tsbackend/src/core/auth/auth.ts
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/core/auth/auth.config.tsbackend/src/api/routes/auth.tsbackend/src/core/auth/auth.ts
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/auth/auth.config.tsbackend/src/core/auth/auth.ts
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
backend/src/core/auth/auth.config.tsbackend/src/api/routes/auth.tsbackend/src/core/auth/auth.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/core/auth/auth.config.tsbackend/src/api/routes/auth.tsbackend/src/core/auth/auth.ts
backend/src/api/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints
Files:
backend/src/api/routes/auth.ts
openapi/**/*.{yml,yaml,json}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Document all API endpoints with clear OpenAPI documentation
Files:
openapi/auth.yaml
🧠 Learnings (6)
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement authentication and error-handling middleware
Applied to files:
backend/src/core/auth/auth.config.tsbackend/src/api/routes/auth.tsopenapi/auth.yamlbackend/src/core/auth/auth.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/{controllers,core}/**/*.ts : Implement proper database transaction handling
Applied to files:
backend/src/core/auth/auth.config.tsbackend/src/core/auth/auth.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/**/*.{ts,tsx} : Use prepared statements for SQL queries
Applied to files:
backend/src/core/auth/auth.config.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to **/*.{ts,tsx} : Implement proper error handling with try-catch blocks and logging where appropriate
Applied to files:
backend/src/core/auth/auth.config.tsbackend/src/core/auth/auth.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement rate limiting for API endpoints
Applied to files:
backend/src/api/routes/auth.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Follow RESTful conventions for API endpoints
Applied to files:
backend/src/api/routes/auth.ts
🧬 Code graph analysis (3)
backend/src/core/auth/auth.config.ts (5)
backend/src/utils/logger.ts (1)
logger(6-29)backend/src/core/database/manager.ts (1)
DatabaseManager(10-254)shared-schemas/src/auth.schema.ts (1)
EmailAuthConfigSchema(121-121)backend/src/api/middleware/error.ts (1)
AppError(7-17)shared-schemas/src/auth-api.schema.ts (1)
UpdateEmailAuthConfigRequest(255-255)
backend/src/api/routes/auth.ts (8)
backend/src/core/auth/auth.ts (1)
AuthService(50-1885)backend/src/core/auth/auth.config.ts (1)
AuthConfigService(8-240)backend/src/core/logs/audit.ts (1)
AuditService(8-255)backend/src/api/middleware/auth.ts (2)
verifyAdmin(71-116)AuthRequest(8-17)shared-schemas/src/auth-api.schema.ts (7)
GetEmailAuthConfigResponse(270-270)updateEmailAuthConfigRequestSchema(218-222)resendVerificationEmailRequestSchema(70-72)verifyEmailRequestSchema(79-86)CreateSessionResponse(263-263)sendResetPasswordEmailRequestSchema(91-93)resetPasswordRequestSchema(100-108)backend/src/api/middleware/error.ts (1)
AppError(7-17)backend/src/utils/response.ts (1)
successResponse(22-24)backend/src/api/middleware/rate-limiters.ts (2)
sendEmailOTPLimiter(118-121)verifyOTPLimiter(127-127)
backend/src/core/auth/auth.ts (9)
backend/src/api/middleware/error.ts (1)
AppError(7-17)backend/src/core/auth/auth.config.ts (1)
AuthConfigService(8-240)backend/src/utils/validations.ts (1)
validatePassword(15-42)backend/src/utils/utils.ts (1)
getPasswordRequirementsMessage(9-31)backend/src/core/auth/auth.otp.ts (1)
AuthOTPService(59-388)backend/src/core/email/email.ts (1)
EmailService(20-201)backend/src/core/email/index.ts (1)
EmailService(1-1)backend/src/utils/environment.ts (1)
getApiBaseUrl(39-41)backend/src/core/database/manager.ts (1)
DatabaseManager(10-254)
⏰ 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). (1)
- GitHub Check: E2E Tests
🔇 Additional comments (8)
backend/src/api/routes/auth.ts (2)
445-509: LGTM! Proper anti-enumeration and rate limiting.The email verification endpoints correctly implement:
- Rate limiting via
sendEmailOTPLimiter- 202 responses with generic messages to prevent user enumeration
- Comments documenting the anti-enumeration behavior at service layer
511-647: LGTM! OTP verification and password reset properly implemented.The implementation correctly:
- Rate-limits verification attempts with
verifyOTPLimiter- Supports both numeric code and magic link flows
- Returns session tokens after email verification
- Uses consistent error handling throughout
backend/src/core/auth/auth.config.ts (1)
76-143: LGTM! Race-safe default config creation.The idempotent INSERT with
ON CONFLICT ... DO NOTHINGproperly handles concurrent cold starts. When a conflict occurs, the existing row is re-read and returned. Transaction support viaexternalClientis correctly implemented.openapi/auth.yaml (1)
8-116: LGTM! Email config schema matches backend.The email authentication configuration endpoints and schemas correctly align with the backend
EmailAuthConfigSchema. Properties include all required fields with correct types and constraints (passwordMinLength: 4-128, all boolean flags).backend/src/core/auth/auth.ts (4)
207-219: Consider surfacing verification email send failures.Lines 209-213 catch and log email send failures during registration but still return success with
requiresEmailVerification: true. If the email delivery fails, users will be stranded—unable to verify and unable to log in.Options:
- Rollback registration if email fails (strict): Ensures consistency but couples user creation to external email service availability.
- Return a warning flag (pragmatic): Keep
accessToken: nullbut add{ emailSendFailed: true }so the frontend can show a "resend verification" option immediately.- Current behavior (lenient): Acceptable if you have a separate "resend verification email" flow that users can trigger manually.
Which approach aligns with your product requirements? If email delivery is unreliable, option 2 or 3 is safer.
269-323: LGTM! Anti-enumeration protection correctly implemented.Both verification email methods silently succeed when the user doesn't exist, preventing account enumeration attacks. The logging at lines 274 and 303 provides observability without leaking information to callers.
438-492: LGTM! Password reset flows prevent user enumeration.Both password reset email methods correctly return silently when a user doesn't exist, preventing account enumeration. The internal logging provides observability without exposing user existence to external callers.
628-685: LGTM! Admin authentication uses consistent error handling.Lines 631 and 683 correctly use
AppErrorwithAUTH_UNAUTHORIZEDcode for invalid admin credentials and failed token verification. This provides consistent error handling across the authentication surface.
| await auditService.log({ | ||
| actor: req.user?.email || 'api-key', | ||
| action: 'UPDATE_EMAIL_AUTH_CONFIG', | ||
| module: 'AUTH', | ||
| details: { | ||
| updatedFields: Object.keys(input), | ||
| }, | ||
| ip_address: req.ip, | ||
| }); |
There was a problem hiding this comment.
Avoid logging PII; use user ID as audit actor.
Line 76 logs req.user?.email which is PII. Per privacy best practices, log req.user?.id instead so audit trails don't contain sensitive user information.
Apply this diff:
await auditService.log({
- actor: req.user?.email || 'api-key',
+ actor: req.user?.id || 'api-key',
action: 'UPDATE_EMAIL_AUTH_CONFIG',
module: 'AUTH',
details: {
updatedFields: Object.keys(input),
},
ip_address: req.ip,
});🤖 Prompt for AI Agents
In backend/src/api/routes/auth.ts around lines 75-83, the audit log currently
uses req.user?.email which is PII; change it to use req.user?.id (or another
non-PII identifier) as the actor. Replace actor: req.user?.email || 'api-key'
with actor: req.user?.id || 'api-key', ensuring the value is converted to a
string if necessary to match the auditService schema.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
backend/migrations/015_create-auth-config-and-email-otp-tables.sql (1)
62-97: Fix the ON CONFLICT target.
ON CONFLICT ON CONSTRAINT idx_auth_configs_singletonwill raiseERROR: there is no unique or exclusion constraint matching the ON CONFLICT specificationbecauseidx_auth_configs_singletonis created as a unique index, not a named unique constraint. Either add an explicitALTER TABLE ... ADD CONSTRAINT ... UNIQUEand reference that constraint name, or dropON CONSTRAINTand useON CONFLICT DO NOTHINGso the insert stays idempotent. Without this fix the migration fails as soon as it runs. (stackoverflow.com)
♻️ Duplicate comments (1)
backend/src/core/auth/auth.ts (1)
334-377: Return structured errors instead of throwing raw Error.
throw new Error('User not found')bubbles up as a 500 and leaks stack traces. Use the existingAppError('User not found', 404, ERROR_CODES.NOT_FOUND)so clients receive the correct status/code and the middleware can format the response consistently. Apply the same fix to the other verification/reset paths that still throw plainError. (stackoverflow.com)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
backend/migrations/015_create-auth-config-and-email-otp-tables.sql(1 hunks)backend/src/core/auth/auth.config.ts(1 hunks)backend/src/core/auth/auth.ts(6 hunks)frontend/src/features/auth/components/EmailConfigDialog.tsx(1 hunks)shared-schemas/src/auth.schema.ts(3 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
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 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions
Files:
frontend/src/features/auth/components/EmailConfigDialog.tsxbackend/src/core/auth/auth.config.tsshared-schemas/src/auth.schema.tsbackend/src/core/auth/auth.ts
frontend/src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders
Files:
frontend/src/features/auth/components/EmailConfigDialog.tsx
frontend/src/**/*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.tsx: Implement TypeScript interfaces/types for all component props
Follow component composition patterns; keep components focused and single-purpose
Implement proper loading and error states in UI
Use a consistent icon set from lucide-react
Files:
frontend/src/features/auth/components/EmailConfigDialog.tsx
frontend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{ts,tsx}: Use TanStack Query for server state management
Use React Hook Form for form handling with Zod validation
Optimize bundle size with proper imports
Files:
frontend/src/features/auth/components/EmailConfigDialog.tsx
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
frontend/src/features/auth/components/EmailConfigDialog.tsxbackend/src/core/auth/auth.config.tsshared-schemas/src/auth.schema.tsbackend/src/core/auth/auth.ts
frontend/src/**/[A-Z]*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Component files must use PascalCase filenames (e.g., DataGrid.tsx)
Files:
frontend/src/features/auth/components/EmailConfigDialog.tsx
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/core/auth/auth.config.tsbackend/src/core/auth/auth.ts
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/auth/auth.config.tsbackend/src/core/auth/auth.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/core/auth/auth.config.tsshared-schemas/src/auth.schema.tsbackend/src/core/auth/auth.ts
🧠 Learnings (6)
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to frontend/src/**/*.{ts,tsx} : Use React Hook Form for form handling with Zod validation
Applied to files:
frontend/src/features/auth/components/EmailConfigDialog.tsx
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement authentication and error-handling middleware
Applied to files:
backend/src/core/auth/auth.config.tsbackend/src/core/auth/auth.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/{controllers,core}/**/*.ts : Implement proper database transaction handling
Applied to files:
backend/src/core/auth/auth.config.tsbackend/src/core/auth/auth.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/**/*.{ts,tsx} : Use prepared statements for SQL queries
Applied to files:
backend/src/core/auth/auth.config.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to **/*.{ts,tsx} : Implement proper error handling with try-catch blocks and logging where appropriate
Applied to files:
backend/src/core/auth/auth.config.tsbackend/src/core/auth/auth.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/**/*.{ts,tsx} : Use Zod schemas for request/response validation
Applied to files:
shared-schemas/src/auth.schema.ts
🧬 Code graph analysis (3)
frontend/src/features/auth/components/EmailConfigDialog.tsx (4)
frontend/src/features/auth/hooks/useEmailConfig.ts (1)
useEmailConfig(6-48)shared-schemas/src/auth-api.schema.ts (2)
UpdateEmailAuthConfigRequest(255-255)updateEmailAuthConfigRequestSchema(218-222)frontend/src/features/auth/services/email-config.service.ts (1)
updateConfig(11-16)frontend/src/lib/utils/utils.ts (1)
isInsForgeCloudProject(158-160)
backend/src/core/auth/auth.config.ts (5)
backend/src/utils/logger.ts (1)
logger(6-29)backend/src/core/database/manager.ts (1)
DatabaseManager(10-254)shared-schemas/src/auth.schema.ts (1)
EmailAuthConfigSchema(129-129)backend/src/api/middleware/error.ts (1)
AppError(7-17)shared-schemas/src/auth-api.schema.ts (1)
UpdateEmailAuthConfigRequest(255-255)
backend/src/core/auth/auth.ts (9)
backend/src/api/middleware/error.ts (1)
AppError(7-17)backend/src/core/auth/auth.config.ts (1)
AuthConfigService(8-260)backend/src/utils/validations.ts (1)
validatePassword(15-42)backend/src/utils/utils.ts (1)
getPasswordRequirementsMessage(9-31)backend/src/utils/logger.ts (1)
logger(6-29)backend/src/core/auth/auth.otp.ts (1)
AuthOTPService(59-388)backend/src/core/email/email.ts (1)
EmailService(20-201)backend/src/utils/environment.ts (1)
getApiBaseUrl(39-41)backend/src/core/database/manager.ts (1)
DatabaseManager(10-254)
⏰ 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: build-and-push
- GitHub Check: E2E Tests
| import logger from '@/utils/logger.js'; | ||
| import type { EmailAuthConfigSchema, UpdateEmailAuthConfigRequest } from '@insforge/shared-schemas'; | ||
|
|
||
| export class AuthConfigService { | ||
| private static instance: AuthConfigService; | ||
| private pool: Pool | null = null; | ||
|
|
||
| private constructor() { | ||
| logger.info('AuthConfigService initialized'); | ||
| } | ||
|
|
||
| public static getInstance(): AuthConfigService { | ||
| if (!AuthConfigService.instance) { | ||
| AuthConfigService.instance = new AuthConfigService(); | ||
| } | ||
| return AuthConfigService.instance; | ||
| } | ||
|
|
||
| private getPool(): Pool { | ||
| if (!this.pool) { | ||
| this.pool = DatabaseManager.getInstance().getPool(); | ||
| } | ||
| return this.pool; | ||
| } | ||
|
|
||
| /** | ||
| * Get email authentication configuration | ||
| * Returns the singleton configuration row | ||
| */ | ||
| async getEmailConfig(): Promise<EmailAuthConfigSchema> { | ||
| const client = await this.getPool().connect(); | ||
| try { | ||
| const result = await client.query( | ||
| `SELECT | ||
| id, | ||
| require_email_verification as "requireEmailVerification", | ||
| password_min_length as "passwordMinLength", | ||
| require_number as "requireNumber", | ||
| require_lowercase as "requireLowercase", | ||
| require_uppercase as "requireUppercase", | ||
| require_special_char as "requireSpecialChar", | ||
| verify_email_url as "verifyEmailUrl", | ||
| reset_password_url as "resetPasswordUrl", | ||
| created_at as "createdAt", | ||
| updated_at as "updatedAt" | ||
| FROM _auth_configs | ||
| LIMIT 1` | ||
| ); | ||
|
|
||
| // If no config exists, create default and return it | ||
| if (!result.rows.length) { | ||
| logger.warn('No auth config found, creating default configuration'); | ||
| return await this.createDefaultConfig(); | ||
| } | ||
|
|
||
| return result.rows[0]; | ||
| } catch (error) { | ||
| logger.error('Failed to get auth config', { error }); | ||
| throw new AppError( | ||
| 'Failed to get email authentication configuration', | ||
| 500, | ||
| ERROR_CODES.INTERNAL_ERROR | ||
| ); | ||
| } finally { | ||
| client.release(); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Create default authentication configuration (idempotent and race-safe) | ||
| * Uses UPSERT to handle concurrent cold starts gracefully | ||
| * @param externalClient - Optional client to use (for transaction support) | ||
| */ | ||
| private async createDefaultConfig(externalClient?: PoolClient): Promise<EmailAuthConfigSchema> { | ||
| const client = externalClient || (await this.getPool().connect()); | ||
| const shouldReleaseClient = !externalClient; | ||
|
|
||
| try { | ||
| // Use ON CONFLICT DO NOTHING to make insert idempotent | ||
| // The singleton constraint (idx_auth_configs_singleton) prevents duplicates | ||
| const result = await client.query( | ||
| `INSERT INTO _auth_configs ( | ||
| require_email_verification, | ||
| password_min_length, | ||
| require_number, | ||
| require_lowercase, | ||
| require_uppercase, | ||
| require_special_char, | ||
| verify_email_url, | ||
| reset_password_url | ||
| ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8) | ||
| ON CONFLICT ON CONSTRAINT idx_auth_configs_singleton DO NOTHING | ||
| RETURNING | ||
| id, | ||
| require_email_verification as "requireEmailVerification", | ||
| password_min_length as "passwordMinLength", | ||
| require_number as "requireNumber", | ||
| require_lowercase as "requireLowercase", | ||
| require_uppercase as "requireUppercase", | ||
| require_special_char as "requireSpecialChar", | ||
| verify_email_url as "verifyEmailUrl", | ||
| reset_password_url as "resetPasswordUrl", | ||
| created_at as "createdAt", | ||
| updated_at as "updatedAt"`, | ||
| [false, 6, false, false, false, false, null, null] | ||
| ); | ||
|
|
||
| // If insert was skipped due to conflict (concurrent insert won the race), | ||
| // read the existing row that was created by the other request | ||
| if (result.rows.length === 0) { | ||
| logger.info( | ||
| 'Default auth config already exists (concurrent creation), reading existing row' | ||
| ); | ||
| const existingResult = await client.query( | ||
| `SELECT | ||
| id, | ||
| require_email_verification as "requireEmailVerification", | ||
| password_min_length as "passwordMinLength", | ||
| require_number as "requireNumber", | ||
| require_lowercase as "requireLowercase", | ||
| require_uppercase as "requireUppercase", | ||
| require_special_char as "requireSpecialChar", | ||
| verify_email_url as "verifyEmailUrl", | ||
| reset_password_url as "resetPasswordUrl", | ||
| created_at as "createdAt", | ||
| updated_at as "updatedAt" | ||
| FROM _auth_configs | ||
| LIMIT 1` | ||
| ); | ||
| return existingResult.rows[0]; | ||
| } | ||
|
|
||
| logger.info('Default auth config created'); | ||
| return result.rows[0]; | ||
| } catch (error) { | ||
| logger.error('Failed to create default auth config', { error }); | ||
| throw new AppError( | ||
| 'Failed to create default authentication configuration', | ||
| 500, | ||
| ERROR_CODES.INTERNAL_ERROR | ||
| ); | ||
| } finally { | ||
| if (shouldReleaseClient) { | ||
| client.release(); |
There was a problem hiding this comment.
Correct logger import and ON CONFLICT usage.
Two blockers here:
import logger from '@/utils/logger.js';pulls a default export, butloggeris exported as a named constant. At runtime this evaluates toundefined, so every log call throws. Switch toimport { logger } from '@/utils/logger.js';.ON CONFLICT ON CONSTRAINT idx_auth_configs_singletonmirrors the migration bug: the index is not a constraint, so inserts throwERROR: ... no unique or exclusion constraint matching .... Either reference a real unique constraint or fall back toON CONFLICT DO NOTHING.
Please fix both before merging. (stackoverflow.com)
🤖 Prompt for AI Agents
In backend/src/core/auth/auth.config.ts around lines 5 to 148, the file imports
logger as a default and uses an ON CONFLICT clause that references a
non-constraint index; update the import to use the named export (import { logger
} from '@/utils/logger.js') so logger is defined at runtime, and change the
INSERT upsert clause to use a valid ON CONFLICT form (e.g. ON CONFLICT DO
NOTHING) or reference a real unique constraint name if one exists; ensure any
other logger usages in the file remain compatible and keep the INSERT parameter
ordering the same when switching the ON CONFLICT form.
| // Check if user exists | ||
| const dbUser = await this.db.prepare('SELECT * FROM _accounts WHERE email = ?').get(email); | ||
| if (!dbUser) { | ||
| // Silently succeed to prevent user enumeration | ||
| logger.info('Verification email requested for non-existent user', { email }); | ||
| return; | ||
| } | ||
|
|
||
| // Create numeric OTP code using the OTP service | ||
| const otpService = AuthOTPService.getInstance(); | ||
| const { code } = await otpService.createEmailOTP( | ||
| email, | ||
| EmailOTPPurpose.VERIFY_EMAIL, | ||
| EmailOTPType.NUMERIC_CODE | ||
| ); | ||
|
|
||
| // Send email with verification code | ||
| const emailService = EmailService.getInstance(); | ||
| await emailService.sendWithTemplate(email, dbUser.name || 'User', 'email-verification-code', { | ||
| token: code, | ||
| }); | ||
| } | ||
|
|
||
| /** | ||
| * Send verification email with magic link | ||
| * Creates a long cryptographic token and sends it via email as a clickable link | ||
| * The link contains only the token (no email) for better privacy and security | ||
| */ | ||
| async sendVerificationEmailWithLink(email: string): Promise<void> { | ||
| // Check if user exists | ||
| const dbUser = await this.db.prepare('SELECT * FROM _accounts WHERE email = ?').get(email); | ||
| if (!dbUser) { | ||
| // Silently succeed to prevent user enumeration | ||
| logger.info('Verification email requested for non-existent user', { email }); | ||
| return; | ||
| } |
There was a problem hiding this comment.
Stop logging raw email addresses for missing accounts.
logger.info('... non-existent user', { email }) writes attacker-controlled email strings into logs whenever someone probes the API. Beyond leaking PII, this reproduces the log-forging weakness that motivated CVE-2020-4072; an attacker can inject newline/escape sequences to poison log analysis. Drop the email from the message (or sanitize it) and rely on internal correlation IDs instead. (wiz.io)
Also applies to: 443-478
There was a problem hiding this comment.
Actionable comments posted: 0
♻️ Duplicate comments (2)
openapi/auth.yaml (2)
585-588: OTP field missing 6-digit pattern constraint to align with backend and shared-schemas.The
otpfields in bothverify-emailandreset-passwordendpoints lack a schema constraint despite the descriptions stating "6-digit numeric code." This was flagged in previous reviews and should be fixed to ensure spec/implementation consistency and enable client-side validation.Add a
patternconstraint to enforce the 6-digit format:otp: type: string description: Either a 6-digit numeric code or a 64-character hex token from magic link + pattern: '^[0-9]{6}$|^[a-f0-9]{64}$' example: "123456"Alternatively, if magic links use different endpoints, consider separate fields or an anyOf schema to represent both formats precisely.
Also applies to: 707-710
602-605: Missing 429 (Rate Limit) response; error code alignment needed.Both
verify-emailandreset-passwordendpoints currently define 400 and 401 responses but lack documentation for rate-limit scenarios. Previous reviews flagged that the backend returns 429 for too many OTP attempts. Add this response and clarify the 400/401 distinction:
- 400: Invalid verification code or token
- 429: Too many failed attempts; rate limit exceeded
- 401: Consider removing; the backend does not use 401 for auth errors in these flows
Apply this diff to both endpoints:
'400': description: Invalid verification code or token - '401': - description: Verification code/token expired or invalid + '429': + description: Too many failed attempts, please try again laterAlso applies to: 722-725
🧹 Nitpick comments (1)
openapi/auth.yaml (1)
351-380: Inconsistent response format:/api/auth/sessions/currentreturns inline object instead ofUserResponseschema.This endpoint returns an inline user object with only
id,role, while all other authenticated user endpoints (login, register, admin login, etc.) referenceUserResponseschema. If the "basic info from JWT" is intentional and scoped, document this clearly; otherwise, align withUserResponsefor consistency.user: - type: object - properties: - id: - type: string - format: uuid - email: - type: string - format: email - role: - type: string - enum: [authenticated, project_admin] + $ref: '#/components/schemas/UserResponse'Verify with the backend team whether this endpoint intentionally returns a subset of user fields or if it should return the full
UserResponse.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
backend/src/core/auth/auth.config.ts(1 hunks)openapi/auth.yaml(14 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- backend/src/core/auth/auth.config.ts
🧰 Additional context used
📓 Path-based instructions (1)
openapi/**/*.{yml,yaml,json}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Document all API endpoints with clear OpenAPI documentation
Files:
openapi/auth.yaml
🧠 Learnings (1)
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement authentication and error-handling middleware
Applied to files:
openapi/auth.yaml
⏰ 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). (1)
- GitHub Check: E2E Tests
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
backend/src/core/auth/auth.ts (1)
276-307: Remove email address from “user not found” logsLogging
backend/src/api/routes/auth.ts (1)
74-86: PII in audit log actorWe still record
req.user?.emailas the actor, which leaks PII into the audit trail. Please switch to a non-sensitive identifier likereq.user?.id(same as noted earlier).
📜 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 (10)
backend/migrations/015_create-auth-config-and-email-otp-tables.sql(1 hunks)backend/src/api/routes/auth.ts(2 hunks)backend/src/core/auth/auth.config.ts(1 hunks)backend/src/core/auth/auth.otp.ts(1 hunks)backend/src/core/auth/auth.ts(6 hunks)frontend/src/features/auth/components/EmailConfigDialog.tsx(1 hunks)openapi/auth.yaml(14 hunks)shared-schemas/package.json(1 hunks)shared-schemas/src/auth-api.schema.ts(5 hunks)shared-schemas/src/auth.schema.ts(3 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
- backend/src/core/auth/auth.config.ts
- backend/migrations/015_create-auth-config-and-email-otp-tables.sql
- backend/src/core/auth/auth.otp.ts
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
**/*.{ts,tsx}: Use TypeScript for all code files
Use ES modules (import/export syntax)
Prefer descriptive, unabbreviated variable and function names
Implement proper error handling with try-catch blocks and logging where appropriate
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 2-space indentation
Format code with the repository Prettier configuration
Variables, parameters, properties, and functions must use camelCase
Constants and enum members must use UPPER_CASE
Include JSDoc comments for complex functions
Files:
frontend/src/features/auth/components/EmailConfigDialog.tsxbackend/src/api/routes/auth.tsshared-schemas/src/auth.schema.tsshared-schemas/src/auth-api.schema.tsbackend/src/core/auth/auth.ts
frontend/src/**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{tsx,ts}: Use functional React components with hooks exclusively
Use Radix UI primitives for accessibility
Optimize React component re-renders
Files:
frontend/src/features/auth/components/EmailConfigDialog.tsx
frontend/src/**/*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.tsx: Implement TypeScript interfaces/types for all component props
Follow component composition patterns; keep components focused and single-purpose
Implement proper loading and error states in UI
Use a consistent icon set from lucide-react
Files:
frontend/src/features/auth/components/EmailConfigDialog.tsx
frontend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
frontend/src/**/*.{ts,tsx}: Use TanStack Query for server state management
Use React Hook Form for form handling with Zod validation
Optimize bundle size with proper imports
Files:
frontend/src/features/auth/components/EmailConfigDialog.tsx
**/*.{tsx,ts}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
React components and TypeScript types/interfaces must use PascalCase
Files:
frontend/src/features/auth/components/EmailConfigDialog.tsxbackend/src/api/routes/auth.tsshared-schemas/src/auth.schema.tsshared-schemas/src/auth-api.schema.tsbackend/src/core/auth/auth.ts
frontend/src/**/[A-Z]*.tsx
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Component files must use PascalCase filenames (e.g., DataGrid.tsx)
Files:
frontend/src/features/auth/components/EmailConfigDialog.tsx
backend/src/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/**/*.{ts,tsx}: Use async/await for asynchronous operations in the backend
Use Zod schemas for request/response validation
Return consistent API responses using utility functions
Validate all user inputs
Sanitize data before database operations
Use prepared statements for SQL queries
Implement proper caching strategies (server-side)
Files:
backend/src/api/routes/auth.tsbackend/src/core/auth/auth.ts
backend/src/api/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
backend/src/api/**/*.ts: Implement authentication and error-handling middleware
Follow RESTful conventions for API endpoints
Implement rate limiting for API endpoints
Files:
backend/src/api/routes/auth.ts
**/[a-z][a-z0-9-]*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Utility files should use kebab-case or camelCase (kebab-case validated here)
Files:
backend/src/api/routes/auth.tsshared-schemas/src/auth.schema.tsshared-schemas/src/auth-api.schema.tsbackend/src/core/auth/auth.ts
openapi/**/*.{yml,yaml,json}
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Document all API endpoints with clear OpenAPI documentation
Files:
openapi/auth.yaml
backend/src/{controllers,core}/**/*.ts
📄 CodeRabbit inference engine (.github/copilot-instructions.md)
Implement proper database transaction handling
Files:
backend/src/core/auth/auth.ts
🧠 Learnings (7)
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to frontend/src/**/*.{ts,tsx} : Use React Hook Form for form handling with Zod validation
Applied to files:
frontend/src/features/auth/components/EmailConfigDialog.tsx
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement authentication and error-handling middleware
Applied to files:
backend/src/api/routes/auth.tsopenapi/auth.yamlbackend/src/core/auth/auth.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Implement rate limiting for API endpoints
Applied to files:
backend/src/api/routes/auth.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/api/**/*.ts : Follow RESTful conventions for API endpoints
Applied to files:
backend/src/api/routes/auth.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/**/*.{ts,tsx} : Use Zod schemas for request/response validation
Applied to files:
shared-schemas/src/auth.schema.tsshared-schemas/src/auth-api.schema.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to backend/src/{controllers,core}/**/*.ts : Implement proper database transaction handling
Applied to files:
backend/src/core/auth/auth.ts
📚 Learning: 2025-10-15T18:18:47.519Z
Learnt from: CR
PR: InsForge/InsForge#0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-10-15T18:18:47.519Z
Learning: Applies to **/*.{ts,tsx} : Implement proper error handling with try-catch blocks and logging where appropriate
Applied to files:
backend/src/core/auth/auth.ts
🧬 Code graph analysis (4)
frontend/src/features/auth/components/EmailConfigDialog.tsx (4)
frontend/src/features/auth/hooks/useEmailConfig.ts (1)
useEmailConfig(6-48)shared-schemas/src/auth-api.schema.ts (2)
UpdateEmailAuthConfigRequest(277-277)updateEmailAuthConfigRequestSchema(240-244)frontend/src/features/auth/services/email-config.service.ts (1)
updateConfig(11-16)frontend/src/lib/utils/utils.ts (1)
isInsForgeCloudProject(158-160)
backend/src/api/routes/auth.ts (8)
backend/src/core/auth/auth.ts (1)
AuthService(52-1913)backend/src/core/auth/auth.config.ts (1)
AuthConfigService(8-260)backend/src/core/logs/audit.ts (1)
AuditService(8-255)backend/src/api/middleware/auth.ts (2)
verifyAdmin(71-116)AuthRequest(8-17)shared-schemas/src/auth-api.schema.ts (8)
GetEmailAuthConfigResponse(294-294)updateEmailAuthConfigRequestSchema(240-244)sendVerificationEmailRequestSchema(70-72)verifyEmailRequestSchema(79-86)VerifyEmailResponse(286-286)sendResetPasswordEmailRequestSchema(91-93)resetPasswordRequestSchema(100-108)ResetPasswordResponse(287-287)backend/src/api/middleware/error.ts (1)
AppError(7-17)backend/src/utils/response.ts (1)
successResponse(22-24)backend/src/api/middleware/rate-limiters.ts (2)
sendEmailOTPLimiter(118-121)verifyOTPLimiter(127-127)
shared-schemas/src/auth-api.schema.ts (1)
shared-schemas/src/auth.schema.ts (4)
emailSchema(14-14)passwordSchema(16-16)userSchema(33-48)emailAuthConfigSchema(86-104)
backend/src/core/auth/auth.ts (8)
backend/src/api/middleware/error.ts (1)
AppError(7-17)shared-schemas/src/auth-api.schema.ts (4)
CreateUserResponse(284-284)VerifyEmailResponse(286-286)ResetPasswordResponse(287-287)CreateAdminSessionResponse(288-288)backend/src/core/auth/auth.config.ts (1)
AuthConfigService(8-260)backend/src/utils/validations.ts (1)
validatePassword(15-42)backend/src/utils/utils.ts (1)
getPasswordRequirementsMessage(9-31)backend/src/core/auth/auth.otp.ts (1)
AuthOTPService(59-388)backend/src/core/email/email.ts (1)
EmailService(20-201)backend/src/core/database/manager.ts (1)
DatabaseManager(10-254)
⏰ 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). (1)
- GitHub Check: E2E Tests
|
|
||
| // If no config exists, create default and return it | ||
| if (!result.rows.length) { | ||
| logger.warn('No auth config found, creating default configuration'); |
There was a problem hiding this comment.
do we still need default config since default is included in the db layer
https://github.com/InsForge/InsForge/pull/532/files#diff-713449bf01e60da3a8bb29e0d0a0849af827bcc4163549c8571b974bb7ae4430R63-R79
There was a problem hiding this comment.
I was thinking the same thing, but Claude code and code rabbit keeps adding this safe net
|
LGTM, i believe major cases should all be covered, we should have comprehensive tests along with oss page/auth components |
Summary
How did you test this change?
Tested both locally and on cloud. Email works, password requirement works. But full verify-email flow and reset-password flow need the new OSS auth page from Leo's branch.
Summary by CodeRabbit
New Features
Improvements