Skip to content

Feat: add email-auth related endpoints. - #511

Merged
jwfing merged 13 commits into
feat-email-servicefrom
feat/email_auth
Oct 27, 2025
Merged

jwfing merged 13 commits into
feat-email-servicefrom
feat/email_auth

Conversation

@jwfing

@jwfing jwfing commented Oct 22, 2025 •

Copy link
Copy Markdown
Member

Summary

add email auth endpoints, include:

  • /api/auth/request-email-verification
  • /api/auth/verify-email
  • /api/auth/request-one-time-password
  • /api/auth/verify-one-time-password

How did you test this change?

  • for unit test:
    cd backend && npm test -- email.test.ts

  • for functionality test:
    local test with cloud backend.

Summary by CodeRabbit

  • New Features

    • Email verification and one-time-password (OTP) flows with request and verify endpoints that return sessions on success.
    • Cloud-backed email delivery service with templated messages and signed requests.
    • Per-email and per-IP rate limits plus cooldowns to prevent rapid/repeated requests.
    • Numeric verification codes and OTPs now support 4–8 characters.
  • Database

    • Storage for verification/OTP codes and expiration timestamps with indexed lookups.
  • Tests

    • Comprehensive unit tests for email delivery, token signing, error handling, and cooldown middleware.
  • Chores

    • Typed application config and utility for generating numeric codes.

@coderabbitai

coderabbitai Bot commented Oct 22, 2025 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Adds DB migration and implements email verification and passwordless OTP: config, EmailService, numeric code generator, AuthService methods, API routes + OpenAPI/shared schemas, rate-limit middleware, and unit tests.

Changes

Cohort / File(s) Summary
Database Migration
backend/migrations/015_add-verification-codes.sql
Adds verify_email_code, reset_password_code, otp_code (VARCHAR, nullable, UNIQUE), corresponding *_expires_at TIMESTAMPTZ columns, CHECK length constraints (4–8), partial indexes for non-NULL codes, and commented rollback steps.
Configuration
backend/src/app.config.ts
New AppConfig interface and exported config populated from environment variables (app, database, cloud settings).
Utilities
backend/src/utils/uuid.ts
Adds generateNumericCode(length: number): string using crypto.randomInt(); existing UUID generator retained.
Email Service
backend/src/core/email/email.ts, backend/src/core/email/index.ts
New EmailService singleton and EmailTemplate type; sendWithTemplate() signs a JWT, posts to cloud email API, maps HTTP errors to AppError, logs, and adds wrappers: sendVerificationEmail, sendPasswordResetEmail, sendOTPRequestEmail. Re-exported from index.
Auth Service
backend/src/core/auth/auth.ts
Adds requestEmailVerification, verifyEmail, requestOneTimePassword, verifyOneTimePassword with numeric-code generation, retry-on-unique-conflict logic, DB updates to store/clear codes and expirations, email sending, and session issuance.
API Routes
backend/src/api/routes/auth.ts
Adds POST endpoints: /request-email-verification, /verify-email, /request-one-time-password, /verify-one-time-password; uses shared schemas, applies rate-limit middleware, calls AuthService, returns messages or session (user + accessToken).
Rate Limit Middleware
backend/src/api/middleware/rate-limit.ts
New per-IP express-rate-limiters and a per-email cooldown map/middleware; exports emailVerificationLimiter, otpRequestLimiter, verificationAttemptLimiter.
Request Schemas
shared-schemas/src/auth-api.schema.ts
Adds Zod schemas: requestEmailVerificationSchema, requestOneTimePasswordSchema, verifyEmailRequestSchema, verifyOneTimePasswordRequestSchema (email + 4–8 char code/otp).
OpenAPI
openapi/auth.yaml
Documents four new endpoints, request bodies, and responses (messages and verify endpoints returning user + accessToken), with appropriate error responses.
Tests
backend/tests/unit/email.test.ts, backend/tests/unit/rate-limit.test.ts
New Vitest suites for EmailService (JWT, HTTP request, error mapping, wrappers, singleton) and perEmailCooldown middleware (cooldown semantics, case-insensitivity, messages).
Docker Compose
docker-compose.yml
Adds CLOUD_API_HOST environment variable to the insforge service.

Sequence Diagram(s)

sequenceDiagram
    participant C as Client
    participant API as Auth API
    participant Auth as AuthService
    participant DB as Database
    participant Email as EmailService
    participant Cloud as Cloud Email API

    Note over C,Cloud: Request email verification
    C->>API: POST /api/auth/request-email-verification { email }
    API->>Auth: requestEmailVerification(email)
    Auth->>DB: SELECT account WHERE email
    DB-->>Auth: account
    Auth->>Auth: generateNumericCode()
    Auth->>DB: UPDATE account SET verify_email_code, expires_at
    DB-->>Auth: OK
    Auth->>Email: sendVerificationEmail(email, name, code)
    Email->>Email: generateSignToken()
    Email->>Cloud: POST /send { email, template, signedToken }
    Cloud-->>Email: 200 OK
    Email-->>Auth: OK
    Auth-->>API: { message }
    API-->>C: 200 { message }
Loading
sequenceDiagram
    participant C as Client
    participant API as Auth API
    participant Auth as AuthService
    participant DB as Database

    Note over C,DB: Verify code and create session
    C->>API: POST /api/auth/verify-email { email, verificationCode }
    API->>Auth: verifyEmail(email, verificationCode)
    Auth->>DB: SELECT account WHERE email
    DB-->>Auth: account (code, expires_at)
    Auth->>Auth: validate code & expiry
    Auth->>DB: UPDATE account SET email_verified=true, clear codes
    DB-->>Auth: OK
    Auth->>Auth: create session (accessToken)
    Auth-->>API: { user, accessToken }
    API-->>C: 200 { user, accessToken }
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested reviewers

  • tonychang04
  • Fermionic-Lyu

Poem

🐇 I nibble bytes and stitch a token bright,
Codes that hop to inboxes by night.
OTP and verify in a nimble stride,
Sessions sprout where proofs collide.
From this rabbit: hops, cheer, and byte-sized delight.

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title "Feat: add email-auth related endpoints." directly describes the primary user-facing change in this pull request, which is the addition of four new authentication endpoints (/request-email-verification, /verify-email, /request-one-time-password, /verify-one-time-password). While the changeset includes substantial supporting infrastructure such as database migrations, service implementations, middleware, configuration, schemas, and tests, these components exist to enable the endpoint functionality. The title appropriately focuses on the main deliverable rather than attempting to enumerate all technical details, which aligns with the guidance that titles need not cover every detail of the changeset. The phrasing is clear, specific, and concise.

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

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 8

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

16-27: Harden generateNumericCode: enforce integer range and align with DB constraints.

  • Add integer guard and max length (DB allows up to 8; schemas use 4–6). Prevents accidental huge loops and DB truncation.
  • Minor: prefer named imports and a join-based build for clarity.

Apply:

-import crypto from 'crypto';
+import { randomInt } from 'crypto';
@@
-export function generateNumericCode(length: number): string {
-  if (length <= 0) {
-    throw new Error('Length must be greater than 0');
-  }
-
-  let code = '';
-  for (let i = 0; i < length; i++) {
-    code += crypto.randomInt(0, 10).toString();
-  }
-
-  return code;
-}
+export function generateNumericCode(length: number): string {
+  // Enforce integer and reasonable bounds; DB migration currently allows up to 8 chars.
+  if (!Number.isInteger(length) || length < 1 || length > 8) {
+    throw new RangeError('length must be an integer between 1 and 8');
+  }
+  return Array.from({ length }, () => randomInt(0, 10).toString()).join('');
+}

If the product standardizes on 6-digit codes, we can tighten the upper bound to 6. Confirm intended code length across the stack.

backend/src/app.config.ts (1)

1-54: Style: use 2-space indentation and run Prettier.

File uses 4 spaces; repo guideline specifies 2. Re-run formatter to keep diffs minimal in future.

As per coding guidelines.

backend/migrations/015_add-verification-codes.sql (2)

5-11: Redundant/inefficient indexing strategy.

  • Column-level UNIQUE already creates a unique btree index. The extra partial indexes (non-unique) duplicate work and bloat writes.
  • Either:
    • Keep column UNIQUE and drop the partial indexes, or
    • Drop column UNIQUE and create UNIQUE INDEX ... WHERE code IS NOT NULL per column.

Suggested up-migration approach:

-ADD COLUMN verify_email_code VARCHAR(8) UNIQUE,
-ADD COLUMN reset_password_code VARCHAR(8) UNIQUE,
-ADD COLUMN otp_code VARCHAR(8) UNIQUE,
+ADD COLUMN verify_email_code VARCHAR(8),
+ADD COLUMN reset_password_code VARCHAR(8),
+ADD COLUMN otp_code VARCHAR(8),
@@
-CREATE INDEX IF NOT EXISTS idx_accounts_verify_email_code ON _accounts(verify_email_code) WHERE verify_email_code IS NOT NULL;
-CREATE INDEX IF NOT EXISTS idx_accounts_reset_password_code ON _accounts(reset_password_code) WHERE reset_password_code IS NOT NULL;
-CREATE INDEX IF NOT EXISTS idx_accounts_otp_code ON _accounts(otp_code) WHERE otp_code IS NOT NULL;
+CREATE UNIQUE INDEX IF NOT EXISTS idx_accounts_verify_email_code
+  ON _accounts(verify_email_code) WHERE verify_email_code IS NOT NULL;
+CREATE UNIQUE INDEX IF NOT EXISTS idx_accounts_reset_password_code
+  ON _accounts(reset_password_code) WHERE reset_password_code IS NOT NULL;
+CREATE UNIQUE INDEX IF NOT EXISTS idx_accounts_otp_code
+  ON _accounts(otp_code) WHERE otp_code IS NOT NULL;

This preserves uniqueness only when set and removes duplicate indexes. As per best practices.

Also applies to: 32-35


13-30: Align code length with API validation (4–6 vs 4–8).

Schemas validate 4–6, migration allows up to 8. Recommend aligning to a single limit to avoid confusion and future drift.

If standard is 6-digit codes, change checks to <= 6 here and cap generator accordingly.

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

66-92: Unify code-length constraints and export shared constants.

Export shared constants (UPPER_CASE) to prevent drift across schemas, DB, and code generator.

Apply:

+export const OTP_CODE_MIN = 4;
+export const OTP_CODE_MAX = 6;
+export const VERIFICATION_CODE_MIN = 4;
+export const VERIFICATION_CODE_MAX = 6;
@@
-export const verifyOneTimePasswordRequestSchema = z.object({
-  email: emailSchema,
-  otp: z.string().min(4).max(6),
-});
+export const verifyOneTimePasswordRequestSchema = z.object({
+  email: emailSchema,
+  otp: z.string().min(OTP_CODE_MIN).max(OTP_CODE_MAX),
+});
@@
-export const verifyEmailRequestSchema = z.object({
-  email: emailSchema,
-  verificationCode: z.string().min(4).max(6),
-});
+export const verifyEmailRequestSchema = z.object({
+  email: emailSchema,
+  verificationCode: z.string().min(VERIFICATION_CODE_MIN).max(VERIFICATION_CODE_MAX),
+});

Comments list paths as /api/auth/request-..., but routes currently register under /auth/request-... inside the auth router, yielding /api/auth/auth/.... Decide on one and sync comments and OpenAPI.
As per coding guidelines.

backend/src/api/routes/auth.ts (1)

427-443: Deduplicate validation boilerplate with a reusable validateBody(schema) middleware.

Current pattern repeats safeParse and AppError creation. Introduce a small validator to reduce noise and mistakes.

Example helper:

// api/middleware/validate.ts
export const validateBody = <T extends z.ZodTypeAny>(schema: T) =>
  (req: Request, _res: Response, next: NextFunction) => {
    const r = schema.safeParse(req.body);
    if (!r.success) {
      return next(new AppError(
        r.error.issues.map(e => `${e.path.join('.')}: ${e.message}`).join(', '),
        400,
        ERROR_CODES.INVALID_INPUT
      ));
    }
    // attach parsed
    (req as any).validated = r.data;
    next();
  };

Then:

-router.post('/verify-email', async (req, res, next) => {
+router.post('/verify-email', validateBody(verifyEmailRequestSchema), async (req, res, next) => {
-  const validationResult = verifyEmailRequestSchema.safeParse(req.body);
-  if (!validationResult.success) { ... }
-  const { email, verificationCode } = validationResult.data;
+  const { email, verificationCode } = (req as any).validated;

Same for OTP endpoints. As per coding guidelines.

Also applies to: 445-461

backend/tests/unit/email.test.ts (2)

51-53: Avoid resetting process.env wholesale in tests.

Reassigning process.env can leak across suites. Prefer saving/restoring only keys you mutate or resetting the mocked config object.

Apply:

-  afterEach(() => {
-    process.env = oldEnv;
-  });
+  afterEach(() => {
+    vi.restoreAllMocks();
+  });

190-199: Strengthen invalid-template assertion for exact message.

Current toThrow('Invalid template type') relies on substring match. Assert full message to lock API contract.

-      ).rejects.toThrow('Invalid template type');
+      ).rejects.toThrow(
+        "Invalid template type: invalid-template. Must be 'email-verification' or 'reset-password' or 'request-otp'"
+      );
backend/src/core/auth/auth.ts (3)

35-37: Remove unused import.

config is imported but not used.

-import { config } from '@/app.config';

223-265: Code collision handling is brittle; increase entropy/retries and store proper expirations.

  • Only 1 retry (max 7 digits) risks unique constraint collisions.
  • Expires stored as Date.now() number; DB likely expects a datetime string.
-    let verificationCode = generateNumericCode(6);
-    let codeLength = 6;
-    const maxRetries = 1; // Allow up to 1 retry (6, 7 digit codes)
+    let verificationCode = generateNumericCode(6);
+    let codeLength = 6;
+    const maxRetries = 3; // up to 9 digits
     let retries = 0;
@@
-          .run(verificationCode, Date.now() + 3600000, email);
+          .run(verificationCode, new Date(Date.now() + 3600000).toISOString(), email);
@@
-          logger.warn(`Verification code conflict, retrying with ${codeLength} digits`, { email, attempt: retries + 1 });
+          logger.warn(`Verification code conflict, retrying with ${codeLength} digits`, { email, attempt: retries + 1 });

Also consider dropping global UNIQUE constraints on codes in favor of per-user uniqueness.


296-339: Same as email verification: increase OTP entropy/retries and store ISO timestamps.

Mirror the verification changes for OTP generation.

-    let verificationCode = generateNumericCode(6);
+    let verificationCode = generateNumericCode(6);
     let codeLength = 6;
-    const maxRetries = 1; // Allow up to 1 retry (6, 7 digit codes)
+    const maxRetries = 3; // Allow up to 3 retries (6..9 digits)
@@
-          .run(verificationCode, Date.now() + 3600000, email);
+          .run(verificationCode, new Date(Date.now() + 3600000).toISOString(), email);
openapi/auth.yaml (2)

419-477: Status codes: use 400/422 for invalid/expired codes, not 401.

401 implies missing/invalid authentication, not bad user input.

-        '401':
-          description: Verification code expired or invalid
+        '422':
+          description: Verification code expired or invalid

Apply similarly to OTP verify response.


478-569: Align all four endpoints with shared schemas and add 429.

Reference shared request/response schemas and document 429 rate limiting (already handled in email service).

-            schema:
-              type: object
-              required:
-                - email
-              properties:
-                email:
-                  type: string
-                  format: email
-                  example: [email protected]
+            schema:
+              $ref: '#/components/schemas/RequestEmailVerification'
@@
-        '400':
-          description: Invalid request
+        '400':
+          description: Invalid request
+        '429':
+          description: Too many requests

Also add corresponding component schemas or refs to shared-schemas if you bundle them here.

backend/src/core/email/email.ts (1)

151-176: Map 429 to a distinct rate-limit error code.

Currently uses INTERNAL_ERROR; prefer a specific code to help clients react.

-            ERROR_CODES.INTERNAL_ERROR
+            ERROR_CODES.RATE_LIMITED
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a49adb7 and c0483c9.

📒 Files selected for processing (10)
  • backend/migrations/015_add-verification-codes.sql (1 hunks)
  • backend/src/api/routes/auth.ts (2 hunks)
  • backend/src/app.config.ts (1 hunks)
  • backend/src/core/auth/auth.ts (2 hunks)
  • backend/src/core/email/email.ts (1 hunks)
  • backend/src/core/email/index.ts (1 hunks)
  • backend/src/utils/uuid.ts (1 hunks)
  • backend/tests/unit/email.test.ts (1 hunks)
  • openapi/auth.yaml (1 hunks)
  • shared-schemas/src/auth-api.schema.ts (1 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/email/index.ts
  • backend/src/utils/uuid.ts
  • backend/src/core/email/email.ts
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/app.config.ts
  • backend/tests/unit/email.test.ts
  • backend/src/core/auth/auth.ts
  • backend/src/api/routes/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/email/index.ts
  • backend/src/utils/uuid.ts
  • backend/src/core/email/email.ts
  • backend/src/app.config.ts
  • backend/src/core/auth/auth.ts
  • backend/src/api/routes/auth.ts
backend/src/{controllers,core}/**/*.ts

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

Implement proper database transaction handling

Files:

  • backend/src/core/email/index.ts
  • backend/src/core/email/email.ts
  • backend/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/email/index.ts
  • backend/src/utils/uuid.ts
  • backend/src/core/email/email.ts
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/app.config.ts
  • backend/tests/unit/email.test.ts
  • backend/src/core/auth/auth.ts
  • 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/core/email/index.ts
  • backend/src/utils/uuid.ts
  • backend/src/core/email/email.ts
  • shared-schemas/src/auth-api.schema.ts
  • backend/src/app.config.ts
  • backend/tests/unit/email.test.ts
  • backend/src/core/auth/auth.ts
  • backend/src/api/routes/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 (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:

  • backend/src/api/routes/auth.ts
🧬 Code graph analysis (5)
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)
shared-schemas/src/auth-api.schema.ts (1)
shared-schemas/src/auth.schema.ts (1)
  • emailSchema (14-14)
backend/tests/unit/email.test.ts (2)
backend/src/app.config.ts (1)
  • config (30-54)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/core/auth/auth.ts (4)
backend/src/utils/uuid.ts (1)
  • generateNumericCode (16-27)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/core/email/email.ts (1)
  • EmailService (16-240)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (213-213)
backend/src/api/routes/auth.ts (3)
shared-schemas/src/auth-api.schema.ts (5)
  • requestEmailVerificationSchema (69-71)
  • requestOneTimePasswordSchema (76-78)
  • verifyEmailRequestSchema (89-92)
  • CreateSessionResponse (213-213)
  • verifyOneTimePasswordRequestSchema (83-86)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/utils/response.ts (1)
  • successResponse (22-24)
🔇 Additional comments (5)
backend/src/core/email/index.ts (1)

1-1: LGTM — concise re-export.

Keeps consumers on a stable import path. No issues.

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

427-443: Service-side checks: constant-time compare, bounded attempts, and code invalidation.

Ensure AuthService.verifyEmail/verifyOneTimePassword:

  • Compare codes in constant time,
  • Enforce expiry and attempt counters with lockouts,
  • Invalidate codes on success and optionally on too many failures,
  • Are wrapped in DB transactions.

Would you like a follow-up patch against core/auth/auth.ts adding these guards and unit tests?

Also applies to: 445-461


16-19: Imports OK.

Schemas are correctly imported and used by new handlers.


401-404: Good anti-enumeration messaging.

Neutral success messages avoid leaking account existence. Keep this pattern.

Also applies to: 419-422

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

222-265: User enumeration risk from 'User not found' in request flows.

Routes should always return 200 with generic message for requestEmailVerification/requestOneTimePassword, regardless of user existence.

Do the route handlers map 'User not found' to a generic 200 response? If not, I can propose a small wrapper.

Also applies to: 296-339

Comment thread backend/src/api/routes/auth.ts Resolved
Comment thread backend/src/app.config.ts Resolved
Comment on lines +270 to +294
async verifyEmail(email: string, verificationCode: string): Promise<CreateSessionResponse> {
// Implementation for verifying email
const dbUser = await this.db.prepare('SELECT * FROM _accounts WHERE email = ?').get(email);
if (!dbUser) {
throw new Error('User not found');
}
// ignore expiration for now
if (dbUser.verify_email_code !== verificationCode) {
throw new Error('Invalid verification code');
}

await this.db
.prepare('UPDATE _accounts SET email_verified = true, verify_email_code = NULL, verify_email_code_expires_at = NULL WHERE email = ?')
.run(email);

dbUser.email_verified = true;
const user = this.dbUserToApiUser(dbUser);
const accessToken = this.generateToken({
sub: dbUser.id,
email: dbUser.email,
role: 'authenticated',
});

return { user, accessToken };
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Do not ignore expiration when verifying email.

Accepting expired codes weakens security and enables replay.

-    // ignore expiration for now
-    if (dbUser.verify_email_code !== verificationCode) {
+    const now = Date.now();
+    const expiresAt = dbUser.verify_email_code_expires_at
+      ? new Date(dbUser.verify_email_code_expires_at).getTime()
+      : 0;
+    if (dbUser.verify_email_code !== verificationCode) {
       throw new Error('Invalid verification code');
     }
+    if (!expiresAt || expiresAt < now) {
+      throw new Error('Verification code expired');
+    }
🤖 Prompt for AI Agents
In backend/src/core/auth/auth.ts around lines 270 to 294, the current
verifyEmail implementation ignores verify_email_code_expires_at; update it to
check the stored expiration against the current time and reject expired codes.
After loading dbUser, parse dbUser.verify_email_code_expires_at into a
Date/number (or treat as UNIX epoch depending on schema) and if the expiration
is missing or now >= expiration, throw an Error('Verification code expired');
only proceed to validate the code and update email_verified when the code is not
expired; keep clearing the code and expiration in the UPDATE when successful.

Comment thread backend/src/core/auth/auth.ts Resolved
Comment thread backend/src/core/email/email.ts Resolved
Comment thread openapi/auth.yaml Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (1)
backend/src/api/routes/auth.ts (1)

390-465: Add rate limiting middleware to email/OTP endpoints.

These authentication endpoints lack rate limiting, enabling enumeration attacks, brute-force attempts, and email flooding. As per coding guidelines.

Apply rate limiting middleware:

+import { emailAuthLimiter } from '@/api/middleware/rate-limit.js';
+
-router.post('/request-email-verification', async (req: Request, res: Response, next: NextFunction) => {
+router.post(
+  '/request-email-verification',
+  emailAuthLimiter,
+  async (req: Request, res: Response, next: NextFunction) => {

Repeat for the other three endpoints. Implement emailAuthLimiter with:

  • 10–15 minute sliding window
  • Key: ${req.ip}:${normalizedEmail}
  • Log threshold violations to AuditService

Additionally, ensure AuthService enforces per-email cooldowns and limits outstanding codes.

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

467-485: Remove commented-out password reset placeholders.

Leaving commented-out code reduces maintainability. If these features are planned, track them in an issue or TODO comment instead.

Apply this diff:

-// router.post('/auth/request-password-reset', async (req: Request, res: Response, next: NextFunction) => {
-//   try {
-//     const { email } = req.body;
-//     await authService.requestPasswordReset(email);
-//     successResponse(res, { message: 'Password reset email sent if the email is registered' });
-//   } catch (error) {
-//     next(error);
-//   }
-// });
-
-// router.post('/auth/reset-password', async (req: Request, res: Response, next: NextFunction) => {
-//   try {
-//     const { token, newPassword } = req.body;
-//     await authService.resetPassword(token, newPassword);
-//     successResponse(res, { message: 'Password has been reset successfully' });
-//   } catch (error) {
-//     next(error);
-//   }
-// });
-
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c0483c9 and cbae1be.

📒 Files selected for processing (2)
  • backend/src/api/routes/auth.ts (2 hunks)
  • openapi/auth.yaml (1 hunks)
🧰 Additional context used
📓 Path-based instructions (6)
openapi/**/*.{yml,yaml,json}

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

Document all API endpoints with clear OpenAPI documentation

Files:

  • openapi/auth.yaml
**/*.{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/api/routes/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/api/routes/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
**/*.{tsx,ts}

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

React components and TypeScript types/interfaces must use PascalCase

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.ts
🧠 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:

  • backend/src/api/routes/auth.ts
🧬 Code graph analysis (1)
backend/src/api/routes/auth.ts (3)
shared-schemas/src/auth-api.schema.ts (5)
  • requestEmailVerificationSchema (69-71)
  • requestOneTimePasswordSchema (76-78)
  • verifyEmailRequestSchema (89-92)
  • CreateSessionResponse (213-213)
  • verifyOneTimePasswordRequestSchema (83-86)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/utils/response.ts (1)
  • successResponse (22-24)
🪛 GitHub Actions: Lint and Format Check
backend/src/api/routes/auth.ts

[error] 391-391: prettier/prettier: Formatting issue detected. Replace '/request-email-verification', with a newline-wrapped version of the string (as per Prettier's rule).

🪛 GitHub Check: lint-and-format
backend/src/api/routes/auth.ts

[failure] 400-400:
Replace ···· with ······


[failure] 399-399:
Insert ··


[failure] 398-398:
Insert ··


[failure] 397-397:
Insert ··


[failure] 396-396:
Insert ··


[failure] 395-395:
Insert ··


[failure] 394-394:
Insert ··


[failure] 393-393:
Replace ···· with ······


[failure] 392-392:
Insert ··


[failure] 391-391:
Replace '/request-email-verification', with ⏎··'/request-email-verification',⏎·

🔇 Additional comments (2)
backend/src/api/routes/auth.ts (1)

390-465: LGTM: Consistent validation and error handling.

All four endpoints follow the established patterns for request validation (Zod safeParse), error handling (try-catch with next), and response formatting (successResponse helper).

openapi/auth.yaml (1)

386-569: LGTM: Comprehensive OpenAPI documentation.

All four new endpoints are well-documented with clear descriptions, complete schemas, appropriate tags, and error responses. The structure is consistent with existing endpoints.

Comment thread backend/src/api/routes/auth.ts Resolved
Comment thread openapi/auth.yaml Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (4)
backend/src/api/routes/auth.ts (1)

390-474: Critical: Add rate limiting to prevent abuse and enumeration attacks.

All four email/OTP endpoints lack rate limiting middleware, despite this being flagged in a previous review. This is a critical security gap that enables:

  • Email enumeration attacks
  • Abuse of email sending (costs/spam)
  • Brute force attacks on verification codes

Implement per-IP and per-email rate limiting with appropriate windows (e.g., 10-15 minutes).

Apply rate limiting middleware to all four endpoints:

+import { emailAuthLimiter } from '@/api/middleware/rate-limit.js';
...
 router.post(
   '/request-email-verification',
+  emailAuthLimiter,
   async (req: Request, res: Response, next: NextFunction) => {
...
 router.post(
   '/request-one-time-password',
+  emailAuthLimiter,
   async (req: Request, res: Response, next: NextFunction) => {
...
-router.post('/verify-email', async (req: Request, res: Response, next: NextFunction) => {
+router.post('/verify-email', emailAuthLimiter, async (req: Request, res: Response, next: NextFunction) => {
...
 router.post(
   '/verify-one-time-password',
+  emailAuthLimiter,
   async (req: Request, res: Response, next: NextFunction) => {

As per coding guidelines.

backend/src/core/auth/auth.ts (2)

274-300: Critical: Expiration checking still ignored for email verification.

Line 280 explicitly states "ignore expiration for now", allowing expired verification codes to be accepted indefinitely. This is a security vulnerability that was flagged in a previous review but remains unfixed.

Apply this fix to validate expiration:

   const dbUser = await this.db.prepare('SELECT * FROM _accounts WHERE email = ?').get(email);
   if (!dbUser) {
     throw new Error('User not found');
   }
-  // ignore expiration for now
+  const now = Date.now();
+  const expiresAt = dbUser.verify_email_code_expires_at
+    ? new Date(dbUser.verify_email_code_expires_at).getTime()
+    : 0;
   if (dbUser.verify_email_code !== verificationCode) {
     throw new Error('Invalid verification code');
   }
+  if (!expiresAt || expiresAt < now) {
+    throw new Error('Verification code expired');
+  }

350-376: Critical: Wrong database field and expiration still ignored.

Two critical bugs remain unfixed from previous review:

  1. Line 357: Wrong field name - Compares dbUser.otp (doesn't exist) instead of dbUser.otp_code. This will cause all OTP verifications to fail.
  2. Line 356: Expiration ignored - Allows expired OTPs to be accepted indefinitely.

Apply this fix:

   const dbUser = await this.db.prepare('SELECT * FROM _accounts WHERE email = ?').get(email);
   if (!dbUser) {
     throw new Error('User not found');
   }
-  // ignore expiration for now
-  if (dbUser.otp !== otp) {
+  const now = Date.now();
+  const expiresAt = dbUser.otp_code_expires_at
+    ? new Date(dbUser.otp_code_expires_at).getTime()
+    : 0;
+  if (dbUser.otp_code !== otp) {
     throw new Error('Invalid one-time password');
   }
+  if (!expiresAt || expiresAt < now) {
+    throw new Error('One-time password expired');
+  }
backend/src/core/email/email.ts (1)

102-106: Major: Email addresses logged without masking (PII exposure).

Full email addresses are still being logged, exposing PII. This was flagged in a previous review but remains unfixed. Email addresses should be masked or hashed before logging.

Implement email masking:

+    const maskEmail = (email: string) => {
+      const [local, domain] = email.split('@');
+      if (!local || !domain) return email;
+      return `${local[0]}***${local[local.length - 1]}@${domain}`;
+    };
+    const maskedEmail = maskEmail(email);
+
     logger.info('Sending email via cloud backend', {
-      email,
+      email: maskedEmail,
       template,
       url,
     });

Also apply to lines 126-129, 143-149, and 185-188.

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

476-494: Commented-out password reset endpoints.

These placeholder endpoints suggest planned future functionality for password reset flows.

Would you like me to open an issue to track the implementation of password reset endpoints?

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

221-269: Consider adding per-email cooldown in addition to API rate limiting.

While the retry logic handles unique constraint conflicts well, the service layer doesn't enforce a cooldown period between requests for the same email. This could allow rapid code regeneration even within rate limits.

Consider checking the last code generation timestamp and rejecting requests within a cooldown window (e.g., 60 seconds).

Example:

 async requestEmailVerification(email: string): Promise<void> {
   const dbUser = await this.db.prepare('SELECT * FROM _accounts WHERE email = ?').get(email);
   if (!dbUser) {
     throw new Error('User not found');
   }
+
+  // Check cooldown (e.g., 60 seconds between requests)
+  if (dbUser.verify_email_code_expires_at) {
+    const lastRequestTime = dbUser.verify_email_code_expires_at - 3600000; // subtract 1 hour to get creation time
+    const cooldownPeriod = 60000; // 60 seconds
+    if (Date.now() - lastRequestTime < cooldownPeriod) {
+      throw new Error('Please wait before requesting a new code');
+    }
+  }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between cbae1be and c834b5d.

📒 Files selected for processing (4)
  • backend/src/api/routes/auth.ts (2 hunks)
  • backend/src/core/auth/auth.ts (2 hunks)
  • backend/src/core/email/email.ts (1 hunks)
  • backend/tests/unit/email.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/tests/unit/email.test.ts
🧰 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/src/core/auth/auth.ts
  • backend/src/core/email/email.ts
  • backend/src/api/routes/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.ts
  • backend/src/core/email/email.ts
  • backend/src/api/routes/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.ts
  • backend/src/core/email/email.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.ts
  • backend/src/core/email/email.ts
  • 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/core/auth/auth.ts
  • backend/src/core/email/email.ts
  • backend/src/api/routes/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
🧠 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:

  • backend/src/api/routes/auth.ts
🧬 Code graph analysis (3)
backend/src/core/auth/auth.ts (4)
backend/src/utils/uuid.ts (1)
  • generateNumericCode (16-27)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/core/email/email.ts (1)
  • EmailService (16-236)
shared-schemas/src/auth-api.schema.ts (1)
  • CreateSessionResponse (213-213)
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/api/routes/auth.ts (3)
shared-schemas/src/auth-api.schema.ts (5)
  • requestEmailVerificationSchema (69-71)
  • requestOneTimePasswordSchema (76-78)
  • verifyEmailRequestSchema (89-92)
  • CreateSessionResponse (213-213)
  • verifyOneTimePasswordRequestSchema (83-86)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/utils/response.ts (1)
  • successResponse (22-24)
⏰ 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 (12)
backend/src/api/routes/auth.ts (4)

16-19: LGTM: Schema imports are correct.

The new schema imports align with the endpoint validation requirements and match the shared-schemas package structure.


395-402: LGTM: Validation pattern is consistent.

The Zod schema validation with comprehensive error mapping follows the established pattern in this file and aligns with coding guidelines.


404-406: LGTM: Anti-enumeration response prevents user discovery.

The response message correctly avoids revealing whether the email exists, which is good security practice to prevent email enumeration attacks.


446-448: LGTM: Verification endpoints correctly return session info.

The verification endpoints appropriately return CreateSessionResponse with user and access token upon successful verification, enabling immediate authentication.

backend/src/core/auth/auth.ts (2)

34-35: LGTM: Required imports added.

The imports for generateNumericCode and EmailService are correctly added to support the new email authentication functionality.


302-348: LGTM: OTP request implementation mirrors email verification.

The implementation correctly follows the same pattern as requestEmailVerification with appropriate field names for OTP codes and uses the correct EmailService method.

backend/src/core/email/email.ts (6)

1-11: LGTM: Imports and type definition are clean.

The EmailTemplate type properly constrains valid template values, and imports are appropriate for the service functionality.


16-29: LGTM: Singleton pattern correctly implemented.

The singleton pattern is appropriate for a stateless service class and correctly prevents direct instantiation.


35-62: LGTM: Token generation follows security best practices.

The sign token correctly:

  • Validates required configuration
  • Uses short-lived expiration (10 minutes)
  • Throws appropriate errors for missing config

83-98: LGTM: Input validation is thorough.

The method properly validates all required parameters and constrains template values to the allowed set with clear error messages.


137-176: LGTM: Error handling is comprehensive and well-structured.

The error handling properly:

  • Distinguishes between different HTTP status codes
  • Provides specific, actionable error messages
  • Maps to appropriate ERROR_CODES
  • Includes timeout protection (10 seconds)

199-236: LGTM: Wrapper methods provide clean API.

The convenience wrappers (sendVerificationEmail, sendPasswordResetEmail, sendOTPRequestEmail) provide a clean, type-safe API for common email operations while delegating to the core sendWithTemplate method.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

♻️ Duplicate comments (2)
backend/src/core/auth/auth.ts (2)

274-300: Do not ignore expiration when verifying email.

Accepting expired codes weakens security and enables replay attacks. The code currently ignores the verify_email_code_expires_at field.

Apply this diff to check expiration:

+    const now = Date.now();
+    const expiresAt = dbUser.verify_email_code_expires_at;
     // ignore expiration for now
     if (dbUser.verify_email_code !== verificationCode) {
       throw new Error('Invalid verification code');
     }
+    if (!expiresAt || expiresAt < now) {
+      throw new Error('Verification code expired');
+    }

350-376: Do not ignore expiration when verifying OTP.

The code correctly uses dbUser.otp_code (past issue with field name has been fixed), but still ignores otp_code_expires_at. Accepting expired OTPs is a security risk.

Apply this diff to check expiration:

+    const now = Date.now();
+    const expiresAt = dbUser.otp_code_expires_at;
     // ignore expiration for now
     if (dbUser.otp_code !== otp) {
       throw new Error('Invalid one-time password');
     }
+    if (!expiresAt || expiresAt < now) {
+      throw new Error('One-time password expired');
+    }
🧹 Nitpick comments (1)
backend/src/core/email/email.ts (1)

92-98: Consider deriving allowed templates from the EmailTemplate type.

The hardcoded list of templates in the error message could drift from the EmailTemplate type definition. Consider deriving the allowed values programmatically or referencing the type in a comment.

For example:

+      const allowedTemplates: EmailTemplate[] = ['email-verification', 'reset-password', 'request-otp'];
-      if (!['email-verification', 'reset-password', 'request-otp'].includes(template)) {
+      if (!allowedTemplates.includes(template)) {
         throw new AppError(
-          `Invalid template type: ${template}. Must be 'email-verification' or 'reset-password' or 'request-otp'`,
+          `Invalid template type: ${template}. Must be one of: ${allowedTemplates.join(', ')}`,
           400,
           ERROR_CODES.INVALID_INPUT
         );
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c834b5d and d8e6336.

📒 Files selected for processing (3)
  • backend/src/core/auth/auth.ts (2 hunks)
  • backend/src/core/email/email.ts (1 hunks)
  • shared-schemas/src/auth-api.schema.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • shared-schemas/src/auth-api.schema.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{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/email/email.ts
  • backend/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/email/email.ts
  • backend/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/email/email.ts
  • backend/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/email/email.ts
  • backend/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/email/email.ts
  • backend/src/core/auth/auth.ts
🧬 Code graph analysis (2)
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 (3)
backend/src/utils/uuid.ts (1)
  • generateNumericCode (16-27)
backend/src/utils/logger.ts (1)
  • logger (6-29)
backend/src/core/email/email.ts (1)
  • EmailService (16-229)
🔇 Additional comments (4)
backend/src/core/email/email.ts (4)

35-62: LGTM!

The JWT token generation logic correctly validates configuration and produces short-lived tokens appropriate for API authentication.


100-129: LGTM!

The HTTP request is properly configured with authentication, timeout, and response validation. Logging is PII-safe.


130-189: LGTM! PII logging concern from past review has been addressed.

The error handling comprehensively maps HTTP errors to appropriate AppError codes with helpful messages. Logging throughout this section is PII-safe and does not include email addresses.


198-228: LGTM!

The wrapper methods provide a clean, type-safe API for each email template type.

Comment thread backend/src/core/auth/auth.ts Resolved
Comment thread backend/src/core/auth/auth.ts Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

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

487-505: Note: Commented password reset endpoints have incorrect path prefix.

When these endpoints are enabled, remove the /auth prefix from the paths (lines 487, 497) to match the pattern of other endpoints in this file. The router is already mounted at /api/auth, so these should be /request-password-reset and /reset-password.

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d8e6336 and ab915ed.

📒 Files selected for processing (3)
  • backend/src/api/middleware/rate-limit.ts (1 hunks)
  • backend/src/api/routes/auth.ts (2 hunks)
  • backend/tests/unit/rate-limit.test.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{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/rate-limit.test.ts
  • backend/src/api/routes/auth.ts
  • backend/src/api/middleware/rate-limit.ts
**/*.{tsx,ts}

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

React components and TypeScript types/interfaces must use PascalCase

Files:

  • backend/tests/unit/rate-limit.test.ts
  • backend/src/api/routes/auth.ts
  • backend/src/api/middleware/rate-limit.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/rate-limit.test.ts
  • backend/src/api/routes/auth.ts
  • backend/src/api/middleware/rate-limit.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/api/routes/auth.ts
  • backend/src/api/middleware/rate-limit.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
  • backend/src/api/middleware/rate-limit.ts
🧠 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/routes/auth.ts
  • backend/src/api/middleware/rate-limit.ts
🧬 Code graph analysis (3)
backend/tests/unit/rate-limit.test.ts (2)
backend/src/api/middleware/rate-limit.ts (1)
  • perEmailCooldown (103-130)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/api/routes/auth.ts (4)
backend/src/api/middleware/rate-limit.ts (3)
  • emailVerificationLimiter (136-139)
  • otpRequestLimiter (145-148)
  • verificationAttemptLimiter (154-154)
shared-schemas/src/auth-api.schema.ts (5)
  • requestEmailVerificationSchema (69-71)
  • requestOneTimePasswordSchema (76-78)
  • verifyEmailRequestSchema (89-92)
  • CreateSessionResponse (213-213)
  • verifyOneTimePasswordRequestSchema (83-86)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/utils/response.ts (1)
  • successResponse (22-24)
backend/src/api/middleware/rate-limit.ts (1)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
🔇 Additional comments (7)
backend/src/api/middleware/rate-limit.ts (2)

32-95: Rate limiter configurations are well-designed.

The skip configurations are intentionally different:

  • Request limiters (email verification, OTP) count all requests to prevent enumeration
  • Verification attempt limiter only counts failures to prevent brute-force code guessing while allowing legitimate retries

This provides layered protection against both enumeration and brute-force attacks.


132-154: LGTM! Clean composable rate limiter exports.

The combined middleware arrays provide the right balance of protection while maintaining usability. The verification attempt limiter correctly omits per-email cooldown to allow legitimate retries.

backend/tests/unit/rate-limit.test.ts (1)

1-154: Excellent test coverage for perEmailCooldown middleware.

The test suite comprehensively covers:

  • Happy path (first request)
  • Cooldown enforcement (blocking subsequent requests)
  • Cooldown expiration (allowing requests after timeout)
  • Case-insensitive email handling
  • Independent cooldowns per email
  • Missing email passthrough
  • Accurate remaining time calculation
  • Custom cooldown durations

The use of unique emails per test and proper async/await for timing tests demonstrates good testing practices.

backend/src/api/routes/auth.ts (4)

395-417: LGTM! Email verification endpoint is well-protected.

The endpoint correctly implements:

  • Combined rate limiting (per-IP + per-email cooldown)
  • Input validation with Zod schema
  • Generic response message to prevent user enumeration
  • Proper error handling

419-440: LGTM! OTP request endpoint follows secure patterns.

Consistent with the email verification endpoint, properly implementing rate limiting, validation, and enumeration-resistant responses.


442-462: LGTM! Email verification endpoint correctly creates sessions.

The endpoint:

  • Uses verification attempt rate limiting (per-IP only, allowing legitimate retries per email)
  • Validates both email and verification code
  • Returns session information upon successful verification
  • Maintains proper error handling

464-485: LGTM! OTP verification endpoint mirrors email verification.

Consistent implementation with proper rate limiting, validation, and session creation. The symmetry with the email verification endpoint makes the API predictable and maintainable.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

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

488-506: Consider removing commented-out password reset endpoints.

If these endpoints are planned for future implementation, consider tracking them in an issue rather than keeping commented code in the codebase. This improves code clarity and maintainability.

Would you like me to open an issue to track the password reset feature implementation?

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e53a9dc and 64b5865.

📒 Files selected for processing (2)
  • backend/src/api/middleware/rate-limit.ts (1 hunks)
  • backend/src/api/routes/auth.ts (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/api/middleware/rate-limit.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{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/api/routes/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/api/routes/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
**/*.{tsx,ts}

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

React components and TypeScript types/interfaces must use PascalCase

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.ts
🧠 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/routes/auth.ts
🧬 Code graph analysis (1)
backend/src/api/routes/auth.ts (4)
backend/src/api/middleware/rate-limit.ts (3)
  • emailVerificationLimiter (139-142)
  • otpRequestLimiter (148-151)
  • verificationAttemptLimiter (157-157)
shared-schemas/src/auth-api.schema.ts (5)
  • requestEmailVerificationSchema (69-71)
  • requestOneTimePasswordSchema (76-78)
  • verifyEmailRequestSchema (89-92)
  • CreateSessionResponse (213-213)
  • verifyOneTimePasswordRequestSchema (83-86)
backend/src/api/middleware/error.ts (1)
  • AppError (7-17)
backend/src/utils/response.ts (1)
  • successResponse (22-24)
🔇 Additional comments (5)
backend/src/api/routes/auth.ts (5)

9-13: LGTM! Rate limiters and validation schemas properly imported.

The new imports align with the coding guidelines and are correctly used in the endpoints below. Rate limiting middleware addresses security concerns for authentication endpoints.

Also applies to: 21-24


395-417: LGTM! Email verification request endpoint properly secured.

The endpoint correctly applies rate limiting, validates input, and returns a sanitized message that prevents user enumeration. The implementation follows existing patterns and security best practices.


419-440: LGTM! OTP request endpoint mirrors the email verification pattern.

Proper rate limiting, input validation, and sanitized responses are in place. The consistent implementation across authentication endpoints improves maintainability.


442-463: LGTM! Email verification endpoint correctly implements passwordless authentication.

The endpoint returns session information (user + accessToken) upon successful verification, which is the correct behavior for passwordless login flows. Rate limiting protects against brute-force attacks on verification codes.


465-486: LGTM! OTP verification endpoint completes the passwordless authentication flow.

The implementation is consistent with the email verification endpoint and properly returns session information for authenticated users.

@Fermionic-Lyu Fermionic-Lyu left a comment •

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Open to discussion here:

How about a new table called _email_otp with columns email, scope, code, expired_at, ... and other necessary columns?
In this case this feature is decoupled with the _account table. Scope can be verify_email, login, reset_password,... and so on. We can have a (email, scope) co-costraint to ensure uniqueness.
I am suggesting this because I think it's good to make it more centralized, and endpoints can be simplified to /send-otp and /verify-otp, just pass in different scope for different uses.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 0

♻️ Duplicate comments (1)
backend/migrations/015_add-verification-codes.sql (1)

37-55: Remove commented rollback statements or convert migration to JavaScript format.

This is a continuation of the critical issue flagged in the previous review. The commented-out rollback statements (lines 37–55) should not exist in .sql migration files used by node-pg-migrate. The tool treats .sql files as up-only migrations and executes all SQL in a single pass during npm run migrate:up. While currently commented out, these lines:

  • Violate best practices for migration file structure
  • Clutter the file and create confusion for future maintainers
  • Risk accidental execution if uncommented
  • Have no functional purpose in a .sql file

Recommended fix: Remove lines 37–55 entirely. If downgrade support is needed for this schema change, convert the entire migration to a JavaScript module that exports up(pg) and down(pg) functions.

🧹 Nitpick comments (1)
docker-compose.yml (1)

88-93: Consider adding an inline comment for clarity (optional).

While the placement and naming are consistent with existing configuration, adding a brief comment explaining the purpose of CLOUD_API_HOST could improve developer ergonomics, especially given its role in cloud-backed email functionality.

      # Multi-tenant Cloud Configuration
      - DEPLOYMENT_ID=${DEPLOYMENT_ID:-}
      - PROJECT_ID=${PROJECT_ID:-}
      - APP_KEY=${APP_KEY:-}
      - ACCESS_API_KEY=${ACCESS_API_KEY:-}
+     # Cloud API host for email service and other cloud-backed operations
      - CLOUD_API_HOST=${CLOUD_API_HOST:-}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c81baae and a117ed2.

📒 Files selected for processing (3)
  • backend/migrations/015_add-verification-codes.sql (1 hunks)
  • backend/src/core/auth/auth.ts (2 hunks)
  • docker-compose.yml (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • backend/src/core/auth/auth.ts
🔇 Additional comments (2)
docker-compose.yml (1)

93-93: Verify backend consumes CLOUD_API_HOST from environment.

The environment variable is appropriately placed in the Multi-tenant Cloud Configuration section and follows the established pattern for optional configuration variables. However, ensure that the backend properly reads and uses this variable from the app configuration module.

Run the following script to verify that the backend imports and uses CLOUD_API_HOST:

backend/migrations/015_add-verification-codes.sql (1)

1-36: Schema design looks solid for the email verification and OTP flows.

The migration properly adds the necessary infrastructure:

  • Code columns (VARCHAR(8) UNIQUE) with CHECK constraints enforce length validation (4–8 characters when non-NULL)
  • UNIQUE constraints prevent code reuse across users, supporting security requirements
  • Nullable columns align with optional/temporary verification workflows
  • TIMESTAMP WITH TIME ZONE for expiration timestamps allows proper time-based validation
  • Partial indexes on non-NULL code values are efficient for sparse data

Once the rollback comment block is removed, this migration is ready.

@jwfing

jwfing commented Oct 24, 2025

Copy link
Copy Markdown
Member Author

This is a good question. I previously considered putting the verification code in a separate table, but ultimately decided to keep it within the account table.
For example, with email verification, email_verified is within the account table, so it might be better to keep the verification_code there. The OTP code is the same as the password, so putting them together might be better. I'm currently keeping all auth verification-related attributes together, which seems to make sense. Of course, if the attribute isn't related to auth, it's better to keep it in a separate table.

@Fermionic-Lyu
Fermionic-Lyu changed the base branch from main to feat-email-service October 27, 2025 18:40

@Fermionic-Lyu Fermionic-Lyu left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Let's merge this into a transition branch first and I will further develop the frontend

@jwfing
jwfing merged commit fe5c8f2 into feat-email-service Oct 27, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants