Skip to content

fix(validation): correct Zod email schema and centralize authentication validation - #370

Open
KrutagyaKaneria wants to merge 4 commits into
vishnukothakapu:mainfrom
KrutagyaKaneria:fix/auth-zod-validation-schema
Open

fix(validation): correct Zod email schema and centralize authentication validation#370
KrutagyaKaneria wants to merge 4 commits into
vishnukothakapu:mainfrom
KrutagyaKaneria:fix/auth-zod-validation-schema

Conversation

@KrutagyaKaneria

@KrutagyaKaneria KrutagyaKaneria commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

📌 Summary

This PR fixes an invalid Zod validation schema that could cause runtime crashes and centralizes authentication validation to ensure consistent behavior across the application.

✨ Changes Made

  • Replaced the invalid z.email() API with z.string().email() in lib/validations/auth.ts.
  • Extended the shared authentication schema with password validation matching the project's existing requirements.
  • Refactored the registration API to use the shared Zod validation schema instead of inline validation.
  • Updated the registration page to follow the same validation rules for consistent client-side behavior.
  • Added unit tests covering email and password validation scenarios.

🛠️ Bug Fixes

  • Prevents runtime TypeError: z.email is not a function.
  • Removes duplicated validation logic.
  • Establishes a single source of truth for authentication validation.
  • Ensures consistent validation between frontend and backend.

🧪 Tests Added

  • Valid email
  • Invalid email
  • Empty email
  • Valid password
  • Password below minimum length
  • Missing required fields

✅ Acceptance Criteria

  • Replaced z.email() with z.string().email().
  • Email validation works correctly.
  • Password validation added to the shared schema.
  • Registration API uses the shared schema.
  • Client-side validation matches the shared schema.
  • Added lib/validations/auth.test.ts.
  • Added validation tests.
  • Existing tests continue to pass.
  • npm test passes successfully.

Closes #365

#GSSoC
#ECSoC26

This PR is submitted as part of GirlScript Summer of Code (GSSoC) 2026.

Kindly review and consider approving it if it aligns with the project's testing and API quality standards. Thank you for your time and feedback!

Summary by CodeRabbit

  • New Features

    • Added clearer, shared password-validation feedback during registration.
    • Registration now returns field-specific feedback for invalid email inputs.
  • Bug Fixes

    • Improved alignment between registration form validation and account-creation rules.
    • Restricted accepted password special characters to the supported set.
  • Tests

    • Added test coverage for validation outcomes (valid/invalid email), password requirements, and missing required fields.

@vercel

vercel Bot commented Jul 9, 2026

Copy link
Copy Markdown

@KrutagyaKaneria is attempting to deploy a commit to the vishnukothakapu's projects Team on Vercel.

A member of the Team first needs to authorize it.

@coderabbitai

coderabbitai Bot commented Jul 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 080d3445-e860-4cca-a30a-591eae974f4f

📥 Commits

Reviewing files that changed from the base of the PR and between 16596ea and f9fd5a1.

📒 Files selected for processing (1)
  • lib/validations/auth.ts

📝 Walkthrough

Walkthrough

Registration now uses shared Zod email and password validation across the API and page. The API persists and sends verification data using the validated email, while unit tests cover schema and password-helper behavior.

Changes

Authentication validation

Layer / File(s) Summary
Shared validation rules and tests
lib/validations/auth.ts, lib/validations/auth.test.ts
The signup schema validates email and password requirements, getPasswordError exposes matching client-side messages, and tests cover valid, invalid, and missing fields.
Registration API validation
app/api/auth/register/route.ts
Registration uses the shared schema and passes the validated email to user creation, verification-token creation, and verification email sending.
Registration page integration
app/register/page.tsx
The page imports the shared password error helper instead of defining a local implementation.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Client
  participant RegistrationAPI
  participant ValidationSchema
  participant Prisma
  participant EmailService
  Client->>RegistrationAPI: Submit email and password
  RegistrationAPI->>ValidationSchema: Validate registration fields
  ValidationSchema-->>RegistrationAPI: Return validated data
  RegistrationAPI->>Prisma: Create user and verification token
  RegistrationAPI->>EmailService: Send verification email
Loading

Possibly related PRs

Suggested labels: bug, type:bug, ECSoC26-L1, ECSoC26

Suggested reviewers: vishnukothakapu

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: fixing Zod email validation and centralizing auth validation.
Linked Issues check ✅ Passed The PR addresses the issue goals by correcting the email schema, centralizing validation, syncing client/server rules, and adding tests.
Out of Scope Changes check ✅ Passed The changes stay focused on authentication validation and tests, with no clear unrelated or extraneous code added.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 Biome (2.5.3)
lib/validations/auth.ts

File contains syntax errors that prevent linting: Line 55: Expected a semicolon or an implicit semicolon after a statement, but found none

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

lib/validations/auth.ts

Parsing error: ';' expected.


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.

❤️ Share

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

@vishnukothakapu

Copy link
Copy Markdown
Owner

Hi @KrutagyaKaneria, please resolve conflicts

@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

Caution

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

⚠️ Outside diff range comments (1)
app/api/auth/register/route.ts (1)

35-48: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Handle name validation errors if using the full signupSchema.

If you update registerSchema to validate the name field as well, ensure that you provide the name to safeParse and handle its potential validation errors.

♻️ Proposed fix
-        const result = registerSchema.safeParse({ email, password });
+        const result = registerSchema.safeParse({ name, email, password });
         if (!result.success) {
             const fieldErrors = result.error.flatten().fieldErrors;
+            if (fieldErrors.name) {
+                return NextResponse.json(
+                    { error: fieldErrors.name[0] },
+                    { status: 400 },
+                );
+            }
             if (fieldErrors.email) {
                 return NextResponse.json(
                     { error: "Invalid email address" },
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/api/auth/register/route.ts` around lines 35 - 48, Update the registration
validation around registerSchema.safeParse to include the name input when
registerSchema validates it, then handle fieldErrors.name explicitly with the
appropriate 400 response. Preserve the existing email and password validation
responses for their respective errors.
🧹 Nitpick comments (1)
app/register/page.tsx (1)

142-149: 🎯 Functional Correctness | 🔵 Trivial | 💤 Low value

Consider adding HTML5 minLength validation to the name input.

To better align the client-side validation with the shared signupSchema (which requires at least 2 characters for the name), consider adding minLength={2} to this input.

♻️ Proposed fix
                             <Input
                                 name="name"
                                 placeholder="Full name"
                                 autoComplete="name"
                                 required
+                                minLength={2}
                                 className="pl-10 transition-colors"
                             />
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/register/page.tsx` around lines 142 - 149, Update the name Input in the
registration form to include HTML5 minLength validation of 2 characters,
matching the shared signupSchema requirement while preserving the existing
required and other input properties.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@app/api/auth/register/route.ts`:
- Around line 86-92: Update the sendVerificationEmail error handler in the
registration route to stop logging result.data.email in plaintext. Remove the
email from the console.error call, while preserving the non-blocking
registration behavior and existing failure message.
- Line 12: Update registerSchema to use signupSchema directly instead of picking
only email and password, so registration validates name alongside the other
shared signup fields and remains aligned with frontend validation.

---

Outside diff comments:
In `@app/api/auth/register/route.ts`:
- Around line 35-48: Update the registration validation around
registerSchema.safeParse to include the name input when registerSchema validates
it, then handle fieldErrors.name explicitly with the appropriate 400 response.
Preserve the existing email and password validation responses for their
respective errors.

---

Nitpick comments:
In `@app/register/page.tsx`:
- Around line 142-149: Update the name Input in the registration form to include
HTML5 minLength validation of 2 characters, matching the shared signupSchema
requirement while preserving the existing required and other input properties.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: bae5133a-4595-4b30-8fdb-dac5e55c1fff

📥 Commits

Reviewing files that changed from the base of the PR and between 8c6fb67 and 16596ea.

📒 Files selected for processing (4)
  • app/api/auth/register/route.ts
  • app/register/page.tsx
  • lib/validations/auth.test.ts
  • lib/validations/auth.ts

const REGISTER_LIMIT = 5;
const REGISTER_WINDOW_MS = 60 * 60 * 1000;

const registerSchema = signupSchema.pick({ email: true, password: true });

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.

🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Validate the name field to maintain consistency with the shared schema.

By picking only email and password, the API bypasses the name validation defined in signupSchema (which requires at least 2 characters). This means the API could accept registrations with an empty name even though the frontend enforces it.

Consider using signupSchema directly to validate all fields, ensuring the API and frontend rules remain perfectly aligned.

♻️ Proposed fix
-const registerSchema = signupSchema.pick({ email: true, password: true });
+const registerSchema = signupSchema;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const registerSchema = signupSchema.pick({ email: true, password: true });
const registerSchema = signupSchema;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/api/auth/register/route.ts` at line 12, Update registerSchema to use
signupSchema directly instead of picking only email and password, so
registration validates name alongside the other shared signup fields and remains
aligned with frontend validation.

Comment on lines 86 to 92
// Send verification email — non-blocking in dev if SMTP not configured
try {
await sendVerificationEmail(normalizedEmail, token);
await sendVerificationEmail(result.data.email, token);
} catch {
// Email sending failure should not block registration
console.error("Failed to send verification email to", normalizedEmail);
console.error("Failed to send verification email to", result.data.email);
}

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.

🔒 Security & Privacy | 🟠 Major | ⚡ Quick win

Avoid logging sensitive user data (PII).

Logging the user's email address in plain text creates a privacy risk and violates best practices for log management. Consider masking the email or removing it entirely from the log message, as the sendVerificationEmail function already logs relevant error details.

🛡️ Proposed fix
         // Send verification email — non-blocking in dev if SMTP not configured
         try {
             await sendVerificationEmail(result.data.email, token);
         } catch {
             // Email sending failure should not block registration
-            console.error("Failed to send verification email to", result.data.email);
+            console.error("Failed to send verification email");
         }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Send verification email — non-blocking in dev if SMTP not configured
try {
await sendVerificationEmail(normalizedEmail, token);
await sendVerificationEmail(result.data.email, token);
} catch {
// Email sending failure should not block registration
console.error("Failed to send verification email to", normalizedEmail);
console.error("Failed to send verification email to", result.data.email);
}
// Send verification email — non-blocking in dev if SMTP not configured
try {
await sendVerificationEmail(result.data.email, token);
} catch {
// Email sending failure should not block registration
console.error("Failed to send verification email");
}
🧰 Tools
🪛 ast-grep (0.44.1)

[warning] 90-90: Avoid logging sensitive data
Context: console.error("Failed to send verification email to", result.data.email)
Note: [CWE-532] Insertion of Sensitive Information into Log File.

(log-sensitive-data-typescript)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@app/api/auth/register/route.ts` around lines 86 - 92, Update the
sendVerificationEmail error handler in the registration route to stop logging
result.data.email in plaintext. Remove the email from the console.error call,
while preserving the non-blocking registration behavior and existing failure
message.

Source: Linters/SAST tools

@vercel

vercel Bot commented Jul 20, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
linkid Error Error Jul 20, 2026 4:39am

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.

[BUG] Fix Invalid Zod Email Validation Schema to Prevent Runtime Crashes

2 participants