Skip to content

Feature/update user profile - #69

Closed
MohamadBakawi wants to merge 24 commits into
mhmdfarhat-mhmdali-amirfrom
feature/update_user_profile
Closed

Feature/update user profile#69
MohamadBakawi wants to merge 24 commits into
mhmdfarhat-mhmdali-amirfrom
feature/update_user_profile

Conversation

@MohamadBakawi

@MohamadBakawi MohamadBakawi commented Jul 5, 2026

Copy link
Copy Markdown
Collaborator

feat: Implemented Add Project Endpoint. http://localhost:3001/projects (POST)
feat: Implemented Update Project Endpoint. http://localhost:3001/projects/PROJECT-ID (PATCH)
bug: Restored test functionality and repaired spec files broken by different branch.

Keep an eye out for LLM edits to the spec files, folks.

Summary by CodeRabbit

  • New Features

    • Added profile editing for authenticated users.
    • Login now supports redirecting to a return URL after sign-in.
    • Signup now sends users to the login page after account creation and verification steps.
  • Bug Fixes

    • Improved magic-link sign-in reliability and invalid-link handling.
    • Tightened sign-in checks so users must verify their email first.
    • Expanded profile data support with additional website/social fields.

chrisshaddad and others added 24 commits June 20, 2026 22:41
chore: added corresponding test auth2e2-spec
chore: added corresponding test auth2e2-spec
bug:fixed multiple bugs in login and signup pages
chore: convert auth.controller.spec.ts from duplicated controller into proper Jest test structure

fix: update magic-link/auth proxy flow to stop relying on sessionId and treat apiRes.ok as success when backend sets cookies.
@coderabbitai

coderabbitai Bot commented Jul 5, 2026

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

This PR adds a PATCH /auth/profile endpoint with a new updateProfileRequestSchema contract, refactors AuthService (password verification, login confirmation gating, magic-link flow typing, and a rewritten updateProfile method), tightens signup validation, and updates web login/signup pages, useAuth, and the proxy to support magic-link redirect handling.

Changes

Auth backend and profile update

Layer / File(s) Summary
Profile update and user response contracts
packages/contracts/src/users/update-profile.request.ts, packages/contracts/src/users/index.ts, packages/contracts/src/users/user.response.ts
Adds updateProfileRequestSchema/UpdateProfileRequest, re-exports it, and adds linkedinUrl, personalWebsiteUrl, organizationWebsiteUrl fields to user response schemas.
Controller and service updateProfile endpoint
apps/api/src/auth/auth.controller.ts, apps/api/src/auth/auth.service.ts, apps/api/src/auth/auth.controller.spec.ts
Adds a PATCH /auth/profile handler validating with the new schema, delegates to a rewritten AuthService.updateProfile enforcing slug uniqueness and updating developer/hiring profiles, and updates controller test wiring for the mocked AuthService.
Login, signup, and magic-link typing/validation
apps/api/src/auth/auth.controller.ts, apps/api/src/auth/auth.service.ts
Explicitly types AuthResponse return types, removes @Res from signup, uses timingSafeEqual for password verification, requires email confirmation before login, and reworks magic-link request/verify flow with typed roles and link invalidation.
Signup request validation refinement
packages/contracts/src/auth/signup.request.ts
Moves required-field checks for profile fields into superRefine with trimmed-length validation instead of base min(1) constraints.

Estimated code review effort: 4 (Complex) | ~60 minutes

Web login/signup UI and magic-link redirect

Layer / File(s) Summary
useAuth updateProfile hook
apps/web/hooks/use-auth.ts
Adds an updateProfile function that PATCHes /auth/profile and revalidates user data.
Login page redirect-aware LoginForm
apps/web/app/login/page.tsx
Extracts a Suspense-wrapped LoginForm component that redirects to a safe redirect query path or falls back to /dashboard.
Signup page controlled field and redirect
apps/web/app/signup/page.tsx
Wires organizationType via Controller, and changes post-signup navigation to show a toast and redirect to /login.
Proxy magic-link verification redirect
apps/web/proxy.ts
Converts proxy to async and adds an /auth/verify branch calling the backend to verify magic-link tokens, set a session cookie, and redirect.
Password input cleanup
apps/web/components/password-input.tsx
Reorganizes imports and removes tabIndex={-1} from the visibility toggle button.

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

Sequence Diagram(s)

sequenceDiagram
  participant Browser
  participant Proxy as Next.js Proxy
  participant API as Auth API
  participant DB as Database

  Browser->>Proxy: GET /auth/verify?token=...
  Proxy->>API: POST /auth/magic-link/verify {token}
  API->>DB: Validate token, mark used, confirm email
  DB-->>API: sessionId
  API-->>Proxy: {sessionId}
  Proxy-->>Browser: Set session cookie, redirect /dashboard
Loading
sequenceDiagram
  participant User
  participant ProfileForm as Web Client
  participant Hook as useAuth.updateProfile
  participant API as AuthController
  participant Service as AuthService

  User->>ProfileForm: Submit updated profile
  ProfileForm->>Hook: updateProfile(data)
  Hook->>API: PATCH /auth/profile
  API->>Service: updateProfile(userId, body)
  Service->>Service: Validate publicSlug uniqueness
  Service-->>API: UserResponse
  API-->>Hook: UserResponse
  Hook->>Hook: mutate() to refresh /auth/me
  Hook-->>ProfileForm: Updated user
Loading

Possibly related PRs

  • chrisshaddad/bootcamp-starter#64: Both PRs implement the PATCH /auth/profile endpoint end-to-end, including AuthController.updateProfile, AuthService.updateProfile, and the UpdateProfileRequest schema.
  • chrisshaddad/bootcamp-starter#50: Both PRs modify AuthController/AuthService signatures and behavior around verifyMagicLink and typed session/response handling.
  • chrisshaddad/bootcamp-starter#53: Both PRs modify apps/web/app/login/page.tsx and apps/web/app/signup/page.tsx to adjust post-submit routing/behavior for login and signup.

Suggested reviewers: AmzBG

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description is off-template and discusses project endpoints instead of the user-profile changes in this PR. Add the required sections: Description, issue or ticket link, Steps to QA, and Screenshots if relevant, and summarize the actual changes in this PR.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and matches the main change: updating the user profile flow.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/update_user_profile
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch feature/update_user_profile

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 3

Caution

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

⚠️ Outside diff range comments (1)
apps/api/src/auth/auth.service.ts (1)

29-44: 🔒 Security & Privacy | 🟠 Major | 🏗️ Heavy lift

Remove password auth from the auth flow. signup still hashes data.password, login still checks passwordHash via verifyPassword, and /auth/login remains exposed. This is still password-based auth, which conflicts with the magic-link-only requirement; remove the password path or update the guideline.

🤖 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 `@apps/api/src/auth/auth.service.ts` around lines 29 - 44, Remove the remaining
password-based auth path in auth.service.ts: the verifyPassword helper and any
login/signup logic that hashes or checks data.password/passwordHash should be
eliminated or bypassed so auth is magic-link-only. Update the AuthService
methods that still call verifyPassword or store password-derived hashes, and
ensure the /auth/login flow no longer accepts or validates passwords.

Source: Coding guidelines

🧹 Nitpick comments (6)
packages/contracts/src/auth/signup.request.ts (1)

13-14: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Add format validation for publicSlug.

publicSlug is only checked for non-empty/non-whitespace content; there's no charset/format constraint (e.g., lowercase alphanumeric + hyphens). Since this value becomes part of a public profile URL (see developerProfile.publicSlug usage in auth.controller.ts), unrestricted input could produce malformed URLs or slugs containing spaces/special characters.

💡 Suggested fix
-    displayName: z.string().trim().optional(),
-    publicSlug: z.string().trim().optional(),
+    displayName: z.string().trim().optional(),
+    publicSlug: z
+      .string()
+      .trim()
+      .regex(/^[a-z0-9-]+$/, 'Public slug can only contain lowercase letters, numbers, and hyphens')
+      .optional(),

Also applies to: 30-36

🤖 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 `@packages/contracts/src/auth/signup.request.ts` around lines 13 - 14, Add
format validation for publicSlug in the signup request schema so it is not only
trimmed and optional but also restricted to a safe slug charset. Update the zod
definition in signup.request.ts to enforce a lowercase alphanumeric plus hyphen
pattern (and reject spaces/special characters), and make sure any shared
validation used around developerProfile.publicSlug or auth.controller.ts stays
consistent with that constraint.
apps/api/src/auth/auth.controller.ts (1)

160-168: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Add an explicit return type for consistency.

Sibling handlers (verifyMagicLink, signup, login) declare Promise<AuthResponse> / getCurrentUser declares UserResponse. updateProfile returns authService.updateProfile(...) which is typed Promise<UserResponse>; annotating it makes the controller contract explicit and guards against service drift.

♻️ Annotate return type
   `@Patch`('profile')
   `@HttpCode`(HttpStatus.OK)
   async updateProfile(
     `@CurrentUser`() user: UserResponse,
     `@Body`(new ZodValidationPipe(updateProfileRequestSchema))
     body: UpdateProfileRequest,
-  ) {
+  ): Promise<UserResponse> {
     return this.authService.updateProfile(user.id, body);
   }
🤖 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 `@apps/api/src/auth/auth.controller.ts` around lines 160 - 168, The
updateProfile handler in AuthController is missing an explicit return type,
unlike the sibling controller methods. Add a Promise<UserResponse> return
annotation to updateProfile so the controller contract matches
authService.updateProfile and stays consistent with verifyMagicLink, signup,
login, and getCurrentUser.
packages/contracts/src/users/update-profile.request.ts (2)

1-1: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

File naming deviates from the contracts convention.

Guidelines name contract files <resource>-<operation>.{request,response}.ts (e.g. user-create.request.ts). This file inverts that to <operation>-<resource>; user-update-profile.request.ts (or profile-update.request.ts) would match. Optional, but keeps the folder consistent.

As per coding guidelines: "Name files as <resource>-<operation>.{request,response}.ts (e.g., user-create.request.ts, user-list.response.ts)."

🤖 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 `@packages/contracts/src/users/update-profile.request.ts` at line 1, The
contract file name is using the operation-before-resource pattern, which
deviates from the established `<resource>-<operation>.{request,response}.ts`
convention. Rename the request contract file to match the contracts naming
scheme, using the relevant symbol/module for the profile update request (for
example, the update-profile request contract) so it follows the same pattern as
other contract files in this package.

Source: Coding guidelines


17-34: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Empty-string URL values will be persisted verbatim.

z.string().url().or(z.literal('')).nullable().optional() accepts a valid URL, '', null, and undefined. The downstream AuthService.updateProfile writes data.linkedinUrl/personalWebsiteUrl/profilePictureUrl/organizationWebsiteUrl straight into Prisma, so a '' clears intent but is stored as an empty string rather than null. Consider normalizing empty strings to null (e.g. .transform((v) => v === '' ? null : v)) so the "clear a URL" path yields consistent null storage.

🤖 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 `@packages/contracts/src/users/update-profile.request.ts` around lines 17 - 34,
The URL fields in the update-profile schema currently accept empty strings but
pass them through unchanged, so profile updates can store '' instead of a
cleared value. Update the validators in update-profile.request.ts for
profilePictureUrl, linkedinUrl, personalWebsiteUrl, and any similar URL fields
to normalize empty-string input to null before it reaches
AuthService.updateProfile and Prisma, while preserving valid URLs and undefined.
Use the existing zod chain on these fields and add a transform/normalization
step so the service consistently stores null when a user clears a URL.
apps/api/src/auth/auth.service.ts (1)

363-372: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Slug uniqueness check is racy; rely on the DB constraint too.

The findUnique check followed by update is a TOCTOU window — two concurrent requests can both pass the check. Ensure publicSlug has a unique constraint and handle the resulting Prisma unique-violation (P2002) by mapping it to ConflictException, so the guard degrades safely under concurrency.

🤖 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 `@apps/api/src/auth/auth.service.ts` around lines 363 - 372, The `AuthService`
slug validation is still race-prone because the `findUnique` check before the
update can be bypassed by concurrent requests. Keep the existing `publicSlug`
precheck in `AuthService`, but also rely on the database unique constraint for
`DeveloperProfile.publicSlug` and handle Prisma’s P2002 unique-violation around
the update path by translating it to `ConflictException`. Make sure the fix is
applied in the `auth.service.ts` flow that updates developer profiles so the
slug guard remains safe under concurrency.
apps/web/app/login/page.tsx (1)

29-41: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Redirect-path sanitization duplicated with signup page.

This exact logic (validating redirect query param against ///leading-slash) matches the onSubmit in apps/web/app/signup/page.tsx. Consider extracting a shared getSafeRedirectPath(searchParams, fallback) helper to avoid divergence.

🤖 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 `@apps/web/app/login/page.tsx` around lines 29 - 41, The redirect-path
validation in LoginPage’s onSubmit duplicates the same sanitization used in
SignupPage, so extract it into a shared helper like
getSafeRedirectPath(searchParams, fallback) and reuse it in both places. Move
the rawRedirect/startsWith checks into that helper, keep the existing fallback
behavior (e.g. /dashboard), and update LoginPage and SignupPage to call the
shared utility so the logic stays consistent.
🤖 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 `@apps/web/app/login/page.tsx`:
- Line 65: The login form in the login page has a stray bare JSX text node
(`code Code`) rendering between the email and password fields. Remove this
accidental literal from the page component and verify the JSX in the login form
only contains the intended inputs and labels, using the login page component
structure to locate it.

In `@apps/web/proxy.ts`:
- Around line 40-57: The magic-link verification flow in proxy.ts is reading
sessionId from the JSON body, but verifyMagicLink only returns user data and
sets SESSION_COOKIE_NAME via response headers. Update the success path to read
the session cookie from the backend response headers (Set-Cookie) instead of
apiRes.json(), and use that value in the if (sessionId) branch so the redirect
and cookie handling work correctly.
- Around line 33-38: The magic-link verification fetch in verify should not be
allowed to hang indefinitely. Update the request in proxy.ts to use the shared
API helper if it is available in this runtime so timeout and error handling stay
consistent; otherwise add an explicit timeout/abort around the existing fetch in
the magic-link verification path. Keep the fix localized to the verify flow and
the apiRes request.

---

Outside diff comments:
In `@apps/api/src/auth/auth.service.ts`:
- Around line 29-44: Remove the remaining password-based auth path in
auth.service.ts: the verifyPassword helper and any login/signup logic that
hashes or checks data.password/passwordHash should be eliminated or bypassed so
auth is magic-link-only. Update the AuthService methods that still call
verifyPassword or store password-derived hashes, and ensure the /auth/login flow
no longer accepts or validates passwords.

---

Nitpick comments:
In `@apps/api/src/auth/auth.controller.ts`:
- Around line 160-168: The updateProfile handler in AuthController is missing an
explicit return type, unlike the sibling controller methods. Add a
Promise<UserResponse> return annotation to updateProfile so the controller
contract matches authService.updateProfile and stays consistent with
verifyMagicLink, signup, login, and getCurrentUser.

In `@apps/api/src/auth/auth.service.ts`:
- Around line 363-372: The `AuthService` slug validation is still race-prone
because the `findUnique` check before the update can be bypassed by concurrent
requests. Keep the existing `publicSlug` precheck in `AuthService`, but also
rely on the database unique constraint for `DeveloperProfile.publicSlug` and
handle Prisma’s P2002 unique-violation around the update path by translating it
to `ConflictException`. Make sure the fix is applied in the `auth.service.ts`
flow that updates developer profiles so the slug guard remains safe under
concurrency.

In `@apps/web/app/login/page.tsx`:
- Around line 29-41: The redirect-path validation in LoginPage’s onSubmit
duplicates the same sanitization used in SignupPage, so extract it into a shared
helper like getSafeRedirectPath(searchParams, fallback) and reuse it in both
places. Move the rawRedirect/startsWith checks into that helper, keep the
existing fallback behavior (e.g. /dashboard), and update LoginPage and
SignupPage to call the shared utility so the logic stays consistent.

In `@packages/contracts/src/auth/signup.request.ts`:
- Around line 13-14: Add format validation for publicSlug in the signup request
schema so it is not only trimmed and optional but also restricted to a safe slug
charset. Update the zod definition in signup.request.ts to enforce a lowercase
alphanumeric plus hyphen pattern (and reject spaces/special characters), and
make sure any shared validation used around developerProfile.publicSlug or
auth.controller.ts stays consistent with that constraint.

In `@packages/contracts/src/users/update-profile.request.ts`:
- Line 1: The contract file name is using the operation-before-resource pattern,
which deviates from the established
`<resource>-<operation>.{request,response}.ts` convention. Rename the request
contract file to match the contracts naming scheme, using the relevant
symbol/module for the profile update request (for example, the update-profile
request contract) so it follows the same pattern as other contract files in this
package.
- Around line 17-34: The URL fields in the update-profile schema currently
accept empty strings but pass them through unchanged, so profile updates can
store '' instead of a cleared value. Update the validators in
update-profile.request.ts for profilePictureUrl, linkedinUrl,
personalWebsiteUrl, and any similar URL fields to normalize empty-string input
to null before it reaches AuthService.updateProfile and Prisma, while preserving
valid URLs and undefined. Use the existing zod chain on these fields and add a
transform/normalization step so the service consistently stores null when a user
clears a URL.
🪄 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: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 986321a5-99e6-4537-b3fd-477b230d7d19

📥 Commits

Reviewing files that changed from the base of the PR and between 8111b68 and de152c2.

📒 Files selected for processing (13)
  • apps/api/src/auth/auth.controller.spec.ts
  • apps/api/src/auth/auth.controller.ts
  • apps/api/src/auth/auth.service.ts
  • apps/web/app/login/page.tsx
  • apps/web/app/signup/page.tsx
  • apps/web/components/password-input.tsx
  • apps/web/hooks/use-auth.ts
  • apps/web/proxy.ts
  • ls.md
  • packages/contracts/src/auth/signup.request.ts
  • packages/contracts/src/users/index.ts
  • packages/contracts/src/users/update-profile.request.ts
  • packages/contracts/src/users/user.response.ts
💤 Files with no reviewable changes (1)
  • apps/web/components/password-input.tsx

<p className="text-sm text-destructive">{errors.email.message}</p>
)}
</div>
code Code

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🎯 Functional Correctness | 🔴 Critical | ⚡ Quick win

Stray literal text renders in the UI.

code Code appears as a bare JSX text node between the email and password fields and will render visibly in the login form. This looks like an accidental copy/paste or LLM artifact.

🐛 Proposed fix
       </div>
-      code Code
       <div className="space-y-2">
📝 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
code Code
🤖 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 `@apps/web/app/login/page.tsx` at line 65, The login form in the login page has
a stray bare JSX text node (`code Code`) rendering between the email and
password fields. Remove this accidental literal from the page component and
verify the JSX in the login form only contains the intended inputs and labels,
using the login page component structure to locate it.

Comment thread apps/web/proxy.ts
Comment on lines +33 to +38
// Make the POST request exactly like Postman does
const apiRes = await fetch(`${apiUrl}/auth/magic-link/verify`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token }),
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n## apps/web/proxy.ts\n'
ast-grep outline apps/web/proxy.ts --view expanded || true

printf '\n## apps/web/lib/api.ts\n'
ast-grep outline apps/web/lib/api.ts --view expanded || true

printf '\n## search for proxy/middleware usage of lib/api.ts\n'
rg -n --hidden --glob 'apps/web/**/*.{ts,tsx}' 'lib/api|ApiError|AbortController|timeout|fetch\(' apps/web || true

printf '\n## show relevant lines from apps/web/proxy.ts\n'
nl -ba apps/web/proxy.ts | sed -n '1,220p'

printf '\n## show relevant lines from apps/web/lib/api.ts\n'
nl -ba apps/web/lib/api.ts | sed -n '1,260p'

Repository: chrisshaddad/bootcamp-starter

Length of output: 2633


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n## apps/web/proxy.ts\n'
sed -n '1,220p' apps/web/proxy.ts

printf '\n## apps/web/lib/api.ts\n'
sed -n '1,220p' apps/web/lib/api.ts

Repository: chrisshaddad/bootcamp-starter

Length of output: 5298


Add a timeout to the magic-link verification request
This can block /auth/verify indefinitely if the backend stalls. If the shared API helper works in this runtime, use it here too for consistent error handling.

🤖 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 `@apps/web/proxy.ts` around lines 33 - 38, The magic-link verification fetch in
verify should not be allowed to hang indefinitely. Update the request in
proxy.ts to use the shared API helper if it is available in this runtime so
timeout and error handling stay consistent; otherwise add an explicit
timeout/abort around the existing fetch in the magic-link verification path.
Keep the fix localized to the verify flow and the apiRes request.

Source: Coding guidelines

Comment thread apps/web/proxy.ts
Comment on lines +40 to +57
if (apiRes.ok) {
const data = await apiRes.json();
const sessionId = data.sessionId || data.data?.sessionId;

if (sessionId) {
// Success! Set the session cookie and redirect to dashboard
const response = NextResponse.redirect(
new URL(DEFAULT_AUTHENTICATED_ROUTE, request.url),
);
response.cookies.set(SESSION_COOKIE_NAME, sessionId, {
path: '/',
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
});
return response;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🗄️ Data Integrity & Integration | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🌐 Web query:

Does Node.js / undici fetch expose multiple Set-Cookie headers via headers.getSetCookie()?

💡 Result:

Yes, the getSetCookie() method in the Node.js/undici fetch implementation is specifically designed to expose multiple Set-Cookie headers as an array of strings [1][2]. This method was introduced to address the limitation where the standard Headers.get() method would incorrectly combine multiple Set-Cookie headers into a single, comma-separated string, which is invalid for cookie values [1][3]. getSetCookie() correctly returns an array containing all individual Set-Cookie header values found in the response [2]. It is important to note the following: * Standard compliance: This behavior is compliant with the Fetch Standard, which mandates that Set-Cookie headers cannot be combined [4]. * Implementation note: If you are using interceptors or specific custom dispatchers, you may occasionally encounter issues where headers are incorrectly concatenated; however, these are typically considered bugs within the undici library that have been addressed in later versions [5][6]. * Redirection: If a response is redirected, fetch may not expose Set-Cookie headers from intermediate responses unless the request is set to redirect: 'manual' [7]. * Comparison to node-fetch: Unlike the older node-fetch library, which required a non-standard Headers.raw() method to access these headers, modern Node.js fetch (via undici) provides the standard getSetCookie() method [8].

Citations:


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n## proxy.ts\n'
git ls-files 'apps/web/proxy.ts' 'apps/api/src/auth/auth.controller.ts'

printf '\n## outline: apps/web/proxy.ts\n'
ast-grep outline apps/web/proxy.ts --view expanded || true

printf '\n## outline: apps/api/src/auth/auth.controller.ts\n'
ast-grep outline apps/api/src/auth/auth.controller.ts --view expanded || true

printf '\n## relevant snippets\n'
sed -n '1,220p' apps/web/proxy.ts
printf '\n--- auth.controller.ts ---\n'
sed -n '1,260p' apps/api/src/auth/auth.controller.ts

Repository: chrisshaddad/bootcamp-starter

Length of output: 9410


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n## auth contract and session cookie usage\n'
rg -n --no-heading 'type AuthResponse|interface AuthResponse|sessionId|SESSION_COOKIE_NAME|setCookie|getSetCookie|set-cookie' apps packages -g '!**/node_modules/**'

printf '\n## auth package files\n'
git ls-files 'packages/**' 'apps/api/src/auth/**' 'apps/web/**' | sed -n '1,200p'

printf '\n## contract definitions\n'
sed -n '1,220p' packages/contracts/src/auth.ts 2>/dev/null || true
sed -n '1,220p' packages/contracts/src/index.ts 2>/dev/null || true

Repository: chrisshaddad/bootcamp-starter

Length of output: 9507


🏁 Script executed:

#!/bin/bash
set -euo pipefail

sed -n '1,200p' packages/contracts/src/auth/auth.response.ts

Repository: chrisshaddad/bootcamp-starter

Length of output: 481


Read the session cookie from the backend response, not the JSON body.
apps/api/src/auth/auth.controller.ts::verifyMagicLink returns only { user } and sets SESSION_COOKIE_NAME via Set-Cookie, so data.sessionId / data.data?.sessionId will always be undefined here. That makes the if (sessionId) branch unreachable and every successful magic-link verification redirect to invalid_magic_link. Parse the cookie from the backend response headers instead.

🤖 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 `@apps/web/proxy.ts` around lines 40 - 57, The magic-link verification flow in
proxy.ts is reading sessionId from the JSON body, but verifyMagicLink only
returns user data and sets SESSION_COOKIE_NAME via response headers. Update the
success path to read the session cookie from the backend response headers
(Set-Cookie) instead of apiRes.json(), and use that value in the if (sessionId)
branch so the redirect and cookie handling work correctly.

@MohamadBakawi
MohamadBakawi deleted the feature/update_user_profile branch July 12, 2026 11:17
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