Skip to content

feat(auth) expose name and picture in useSession() user - #184

Merged
omegascorp merged 23 commits into
modelence:mainfrom
AtulYadav25:feat/expose-user-name-picture
Mar 10, 2026
Merged

omegascorp merged 23 commits into
modelence:mainfrom
AtulYadav25:feat/expose-user-name-picture

Conversation

@AtulYadav25

@AtulYadav25 AtulYadav25 commented Feb 11, 2026 •

Copy link
Copy Markdown
Contributor

This PR fixes the authentication flow by exposing name and picture fields on the user object returned from:

import { useSession } from 'modelence/client';

Previously, although OAuth providers (Google/GitHub) returned profile data such as name and avatar, these fields were not:

  • Stored in the database
  • Included in the UserInfo TypeScript type

As a result, accessing user.name or user.picture caused TypeScript errors.

This PR resolves that issue.

1. OAuth Providers (Google & GitHub)

  • Fetch name and avatar (picture / avatar_url) from provider APIs
  • Pass them into the authentication pipeline

I tried doing console log of users data fetched from the providers
Result
Screenshot (519)
Screenshot (520)

2. Database Schema Update

  • Added name and picture fields to user schema
  • On re-login, user profile data is updated if changed

3. Authentication Flow Update

  • authenticate now returns name and picture also
  • getOwnProfile includes profile fields of name and picture

4. Type Updates

Updated UserInfo type:

export type UserInfo = {
  id: string;
  handle: string;
  roles: string[];
  hasRole: (role: string) => boolean;
  requireRole: (role: string) => void;
  name?: string;
  picture?: string;
};

5. Client Session Update

  • Updated packages/modelence/src/client/session.ts
  • Extended Zod schema to validate name and picture optionally
  • useSession() now properly exposes them

6. auth-ui Update

  • Updated UserProfile component
  • Profile page now displays user avatar and name

Testing

  • Built package successfully using pnpm build
  • Packed locally using pnpm pack
  • Installed in test project
  • Verified:
    • Google login returns name and picture
    • GitHub login returns name and avatar_url
    • Data stored in MongoDB
    • useSession() includes required fields
    • Avatar and name render correctly in UI

Screenshot are attached: useSession() use returns the name and picture :
Screenshot (527)


Note

Medium Risk
Touches core authentication/signup/OAuth linking and introduces new DB fields and handle resolution logic, which could affect account creation/login behavior and uniqueness constraints if edge cases aren’t covered.

Overview
Modelence auth now persists and exposes user profile fields (firstName, lastName, avatarUrl) end-to-end: stored in _modelenceUsers, returned from authenticate/login, included in getOwnProfile, and surfaced in useSession()/client UserInfo.

OAuth (Google/GitHub) now extracts these fields from provider responses and backfills missing profile fields for existing users on login/auto-link, while new users get a unique handle via a new AuthConfig.generateHandle hook (with automatic conflict suffixing) or email-derived fallback.

Email/password signup is extended to accept optional profile fields + custom handle, runs a new AuthConfig.validateSignup hook, resolves unique handles via new auth/utils.ts, and a new updateProfile mutation/client API adds validated profile edits with optional validateProfileUpdate. Docs and @modelence/auth-ui UserProfile are updated to reflect/show these profile fields.

Written by Cursor Bugbot for commit 80c4ebd. This will update automatically on new commits. Configure here.

Comment thread packages/auth-ui/package.json Resolved
@AtulYadav25

Copy link
Copy Markdown
Contributor Author

@artahian @omegascorp Please Guide, how may i make it better?

@omegascorp omegascorp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you for the PR, I've added some comments, there are also some form the bot

emails: { address: string; verified: boolean }[];
authMethods: string[];
name?: string;
picture?: string;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

avatarUrl - is more common name for this

handle: string;
emails: { address: string; verified: boolean }[];
authMethods: string[];
name?: string;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I would suggest having firstName and lastName instead.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

For github we can just split for now (it might be wrong in some cases, but I don't see a better solution)

@AtulYadav25

Copy link
Copy Markdown
Contributor Author

@omegascorp @artahian

The documentation mentions that the User object contains these attributes, and I’ve updated the docs accordingly to show firstName, lastName, and avatarUrl in User object.
Screenshot (530)

I have a question regarding the handle field in the OAuth file.
oauth file
around line 95, the handle is currently set to the user’s email by default.

Do we need the handle field even when email already exists on the user object?

Alternatively, I think handle should represent something more user focus like:

GitHub username for GitHub OAuth
Full name from Google OAuth

I’d like to clarify the real role of handle before making next changes.

I reviewed the same for googleId and githubId field, they both aren't sent in user object as mentioned in documentation.

@artahian

Copy link
Copy Markdown
Contributor

@omegascorp @artahian
Do we need the handle field even when email already exists on the user object?

Alternatively, I think handle should represent something more user focus like:

GitHub username for GitHub OAuth Full name from Google OAuth

I’d like to clarify the real role of handle before making next changes.

Good question - and we've intentionally picked handle as the name for this field and not username so it can be more generic. Some apps/platforms (like Modelence Cloud itself) don't really need a "username" concept and it only works with emails. I think a username is mostly used for social apps, where you can see and interact with other users - e.g. Discord and even Spotify.

Ideally I'd like handle to remain flexible - so I'd suggest to add support for a custom callback where the user can define how to generate the handle for each user signup (and even better if it is smart enough to resolve conflicts on its own and automatically adding _2, _3`, etc as suffixes on collisions with existing handles.

I reviewed the same for googleId and githubId field, they both aren't sent in user object as mentioned in documentation.

@omegascorp I'm not sure about this part, deferring to you. But @AtulYadav25 what's the use case for having googleId and githubId sent to the frontend automatically? useSession is basically made for having your current user's basic fields readily available at all times. For anything more specific you can always have a custom method that fetches these on demand.

@omegascorp

Copy link
Copy Markdown
Collaborator

@AtulYadav25, the documentation is wrong there; the GitHub ID is stored in authMethods.github.id, we need to update the docs to reflect the real user object that is published

@AtulYadav25

Copy link
Copy Markdown
Contributor Author

@omegascorp
To make the authentication workflow cleaner and more consistent (and considering @artahian suggestions), I’ve few improvements.

While these are the current updates

  • I added firstName, lastName, and avatarUrl to the user schema.
  • For OAuth users, these fields are automatically populated from the provider.
  • For non-OAuth users (password users), there is currently no good way to set firstName and lastName or avatarUrl.

This can be an inconsistency in user data
OAuth users may have profile information.
Password users do not have an official way to set it.

Possible Improvements

  1. Add a generateHandle callback
    This would allow developers to customize how handles are generated during signup.

However, even with this, developers still wouldn’t have a clean way to:
Update handle
Set or update firstName, lastName, or avatarUrl later

That makes the framework feel a bit rigid.

  1. Introduce a handleUpdateProfile function in _system.user module mutation

This function would allow updating:
handle, firstName, lastName, avatarUrl

Also, we could update handleSignUpWithPassword to accept these handle, firstName, lastName, avatarUrl fields as OPTIONAL during user creation.

This:
Keep OAuth and password users consistent in terms of profile data
Allow profile updates in a clear and structured way

  1. Add validateSignUp callback in authConfig

Introduce a validateSignUp callback that runs during user creation. This allows developers to enforce custom validation rules without modifying the core authentication flow.

For example:

auth: {
  validateSignUp: ({ firstName, lastName, handle }) => {
    if (!firstName) {
      throw new Error("FirstName is required");
    }
  }
}

This callback would be executed inside handleSignUpWithPassword.


NEXT?

To move forward, I have two approaches:

Add only the generateHandle callback for now and keep the current structure otherwise unchanged.

OR
Introduce a proper handleUpdateProfile function and extend handleSignUpWithPassword to accept optional profile fields (firstName, lastName, avatarUrl, handle), along with adding the validateSignUp callback.

I’m open to suggestions if there’s a better way to do this or more improvements.

Comment thread packages/modelence/src/auth/profile.ts Resolved
…ser in object as RawUserData and case insensitive checks
@AtulYadav25

AtulYadav25 commented Feb 21, 2026 •

Copy link
Copy Markdown
Contributor Author

I’ve here completed the improvements that i comment, to make the authentication and profile system more consistent and flexible.

What I Added

1. Full Profile Support for All Users

  • Added firstName, lastName, and avatarUrl to the user schema.
  • OAuth users (Google & GitHub) automatically populate these fields.
  • Password users can now also set and update these fields properly.

2. updateProfile Mutation

  • Introduced a proper _system.user.updateProfile mutation.

  • Allows updating:

    • handle
    • firstName
    • lastName
    • avatarUrl
  • Returns a fully valid user object to keep session state consistent.

3. Extended signupWithPassword

  • Now accepts optional fields:

    • handle
    • firstName
    • lastName
    • avatarUrl
  • Keeps OAuth and password users aligned in terms of profile structure.

4. generateHandle Callback

  • Developers can now customize how handles are generated during signup.

5. validateSignUp Callback

  • Runs during user creation.
  • Allows developers to enforce custom rules without modifying core auth logic.

6. validateProfileUpdate Callback

  • Runs during profile updates.
  • Allows validation logic before saving changes.

Testing Done

I tested all flows locally:

  • ✅ Password signup with optional profile fields
  • ✅ OAuth login (Google & GitHub)
  • ✅ generateHandle customization
  • ✅ validateSignUp validation
  • ✅ validateProfileUpdate validation
  • ✅ updateProfile mutation
  • ✅ Session updates correctly without breaking auth flow
  • ✅ Profile updates reflect properly in useSession()

Everything is working as expected.

This PR has large changes in the auth layer, so I understand it needs careful review. I’m fully open to adjustments, suggestions, or improvements to refine this further before merging.

Please Let me know If you all like to proceed and thn I will update the documentations as well.

@omegascorp omegascorp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you, added some comments

lastName?: string;
};

type signUpArgs = {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Should be SignUpProps to match other types

import { AuthErrorProps, AuthSuccessProps, User } from '@/auth/types';
import { UpdateProfileArgs } from '@/methods/types';

type GenerateHandleInput = {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Should be GenerateHandleProps

*/
export type AuthConfig = {
// Optional pre-signup validation hook.
validateSignUp?: (props: signUpArgs) => void | Promise<void>;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Signup as a noun in other places with lowercase u, let's keep it consistent

Comment thread packages/modelence/src/auth/profile.ts Outdated
};
}

export async function handleUpdateProfile(_args: UpdateProfileArgs, { user }: Context) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

There should be no underscore before args here, also args should be renamed to props for consistancy

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Should I replace all occurrences of Args with Props ?

Here , export type Args = Record<string, unknown>; in file modelence/src/methods/types.ts

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

I would suggest replacing only the parts that are changed. Args is used in many places.

Comment thread packages/modelence/src/auth/signup.ts Outdated
import { resolveUniqueHandle } from './utils';

export async function handleSignupWithPassword(
args: Args,

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Let's rename this to props and set a proper type here

Comment thread packages/modelence/src/methods/types.ts Outdated

export type Args = Record<string, unknown>;

export type UpdateProfileArgs = {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Let's rename to UpdateProfileProps

password: string;
handle?: string;
avatarUrl?: string;
};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Duplicate SignupProps type defined in two files

Low Severity

A local SignupProps type in authConfig.ts is structurally identical to the exported SignupProps from methods/types.ts. The file already imports UpdateProfileProps from that same module, so SignupProps could be imported too. Having two separate definitions risks them silently diverging if one is updated without the other, causing the validateSignup hook's type to mismatch the actual data shape passed to it.

Additional Locations (1)

Fix in Cursor Fix in Web

Comment thread packages/modelence/src/auth/utils.ts Outdated
): Promise<string> {
if (rawHandle !== undefined && rawHandle !== null && String(rawHandle).trim() !== '') {
// Caller explicitly provided a handle – validate it.
const handle = validateHandle(String(rawHandle));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Handle not trimmed before validation in signup path

Low Severity

resolveUniqueHandle checks String(rawHandle).trim() !== '' to detect blank handles, but then passes the untrimmed value to validateHandle. In contrast, validateProfileFields trims handles before validation and storage. This means a handle like " abc " would be stored with whitespace during signup but trimmed to "abc" on profile update, causing inconsistent behavior across the two code paths.

Fix in Cursor Fix in Web

Comment thread packages/modelence/src/auth/profile.ts Outdated

await getAuthConfig().validateProfileUpdate?.(props);

const update = validateProfileFields(props);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Validation hook runs before sanitization in profile update

Medium Severity

The validateProfileUpdate hook is called with raw, untrimmed props before validateProfileFields sanitizes them. This means the hook validates data that differs from what's actually persisted. For example, firstName: ' ' passes the hook as a 3-character string, but validateProfileFields then trims it to ''. In contrast, signup.ts correctly calls validateSignup after validateProfileFields, so the hook sees the sanitized data there. This inconsistency can cause custom validation logic in the hook to be silently bypassed.

Additional Locations (1)

Fix in Cursor Fix in Web


// Derive handle from the email local-part (everything before '@').
const baseHandle = email.split('@')[0];
return findAvailableHandle(baseHandle);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Email-derived handles bypass minimum length validation

Medium Severity

When no handle is supplied, resolveUniqueHandle derives one from the email local part without calling validateHandle. This means short email prefixes (e.g., [email protected]) produce handles like 'ab' that violate the 3-character minimum enforced by validateHandle and validateProfileFields. Worse, those users would later be unable to keep their own auto-assigned handle during a profile update, since validateProfileFields would reject it as too short.

Fix in Cursor Fix in Web

@AtulYadav25

Copy link
Copy Markdown
Contributor Author

@omegascorp
Useful comments, Thanks. I'm learning and upgrading more. Now these updates look clean as you expected.
I also updated the documentation, keeping it as simple as possible.

Now documentation includes

  • updateProfile function exposure in Auth Overview docs.
  • validateSignup, validateProfileUpdate, generateHandle hook in hooks docs.
  • Google and GitHub missing fields (firstName, lastName, avatarUrl) added

*
* @returns An object containing only the validated, trimmed fields that were provided.
*/
export function validateProfileFields(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can we replace this via zod validation?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@AtulYadav25, could you check this comment?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@AtulYadav25, could you check this comment?

yes, I used zod and made this more clean in the latest commit 😅

@omegascorp

Copy link
Copy Markdown
Collaborator

@AtulYadav25 thank you, I've added one more comment

…es for auto filling of missing fields from providers, in oauth-common test file
profile = { ...profile, ...update } as typeof profile;
} catch (error) {
throw new Error('Failed to update profile.');
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Profile update catches and discards original database error

Medium Severity

The catch block around usersCollection.updateOne discards the original error and throws a generic 'Failed to update profile.' message. This hides critical diagnostic information — for example, if a TOCTOU race condition on handle uniqueness causes a MongoDB duplicate key error, the user sees a generic message instead of something actionable like "Handle already taken." It also makes server-side debugging of connection timeouts, validation failures, and other DB errors much harder.

Fix in Cursor Fix in Web

password,
handle,
...profileFields,
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

validateSignup receives raw handle unlike validated profile fields

Low Severity

The validateSignup hook receives handle as raw user input (untrimmed, unvalidated) while firstName, lastName, and avatarUrl are already validated and trimmed via validateProfileFields. A developer writing a validateSignup hook would see inconsistent data quality — trimmed profile fields but a raw handle with potential leading/trailing whitespace. The handle is only validated later by resolveUniqueHandle.

Fix in Cursor Fix in Web

…ds. Fix: Throw original error from profile.ts on profile update fail. Fix: Do not return undefined values from func in auth/client/index.ts
const generated = await authConfig.generateHandle({
email,
...profileFields,
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Extra props leaked to generateHandle callback in signup

Low Severity

The generateHandle callback in the signup flow receives { email, ...profileFields }, where profileFields can include avatarUrl (and other UpdateProfileProps fields) not present in GenerateHandleProps. The OAuth flow in oauth-common.ts correctly passes only { email, firstName, lastName }. A callback that iterates over all received props (e.g., using Object.values) would inadvertently incorporate avatarUrl into the handle.

Additional Locations (1)

Fix in Cursor Fix in Web

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

@AtulYadav25, could you check the cursor comments? This one is relevant.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@AtulYadav25, could you check the cursor comments? This one is relevant.

Yup, I did a fix on this, maybe it is not visible because you might be seeing some limited last commits.
Could you please check through this all commits
Screenshot (604)

For a quick review
What i made changes:

From this:

 const generated = await authConfig.generateHandle({
        email,
        ...profileFields,
      });

To this

const generated = await authConfig.generateHandle({
        email,
        firstName: profileFields.firstName,
        lastName: profileFields.lastName,
      });


suffix++;
}
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Handle suffix generation can exceed max length limit

Low Severity

findAvailableHandle appends _2, _3, etc. to a base handle without enforcing the 50-character max that validateHandle requires. A generateHandle hook returning a 48+ char handle that conflicts would produce a suffixed handle exceeding 50 chars. Similarly, the email-derived path (email.split('@')[0].padEnd(3, '_')) applies no max-length check at all — RFC 5321 allows local parts up to 64 characters. These oversized handles get stored in the DB but would fail validateProfileFields validation if the user later updates their profile.

Additional Locations (1)

Fix in Cursor Fix in Web

…: Handle suffix generation can exceed max length limit
Comment thread packages/modelence/src/auth/profile.ts Outdated
};
}

export async function handleUpdateProfile(props: UpdateProfileProps, { user }: Context) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Handler parameter type breaks mutation handler contract

Medium Severity

handleUpdateProfile declares its first parameter as UpdateProfileProps instead of Args, which is the type all other handlers use. The framework invokes every handler with handler(args, context) where args is Args (Record<string, unknown>). Every other handler in the codebase (handleSignupWithPassword, handleLoginWithPassword, getOwnProfile, handleLogout, etc.) correctly types its first parameter as Args and then narrows internally. This inconsistency gives a false sense of type safety — TypeScript treats the parameter values as string | undefined, but at runtime they are unknown — and may cause a type error when the function is assigned to the Mutations record under strict: true.

Additional Locations (1)

Fix in Cursor Fix in Web

await callMethod('_system.user.signupWithPassword', {
email,
password,
...(handle ? { handle } : {}),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Client signupWithPassword uses inconsistent check for handle

Low Severity

The handle field uses a truthiness check (handle ?) while firstName, lastName, and avatarUrl use !== undefined. This means passing handle: '' silently omits it and the server auto-generates a handle, whereas passing firstName: '' correctly sends the empty string to the server (which then validates it). The check for handle is inconsistent with the other fields in the same function.

Fix in Cursor Fix in Web

@omegascorp

Copy link
Copy Markdown
Collaborator

@AtulYadav25 could you check the bot's comments and resolve the conflict with main?

…ient signupWithPassword uses inconsistent check for handle
});
} else {
handle = await resolveUniqueHandle(undefined, userData.email);
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Config not cached; getAuthConfig() called twice for generateHandle

Low Severity

The new generateHandle integration calls getAuthConfig() twice — once to check existence and once to invoke — without caching the result. In the same PR, signup.ts properly caches it with const authConfig = getAuthConfig(). The inconsistency is a readability issue and, since getAuthConfig() returns a frozen snapshot that can be replaced by setAuthConfig, the two calls could theoretically return different objects if setAuthConfig is invoked between them by asynchronous scheduling.

Fix in Cursor Fix in Web

hasRole: (role: string) => boolean;
/** Throws an error if the user does not have the given role. */
requireRole: (role: string) => void;
firstName?: string;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

User interface missing new profile fields

Medium Severity

The User interface in types.ts is missing firstName, lastName, and avatarUrl optional fields. These fields were added to the DB schema, UserInfo, client types, and session schema, but not to the User document interface. Code across oauth-common.ts, login.ts, index.ts, and profile.ts accesses these fields on User-typed objects. This only compiles because User extends Document (MongoDB's permissive Record<string, any>), so all accesses silently resolve to any, eliminating type safety — typos like existingUser.fistName would go undetected.

Additional Locations (2)

Fix in Cursor Fix in Web

import { getAuthConfig } from '@/app/authConfig';

export async function getOwnProfile(_args: Args, { user }: Context) {
export async function getOwnProfile(props: Args, { user }: Context) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unused parameter renamed, drops unused-variable convention

Low Severity

getOwnProfile renamed its first parameter from _args to props but never reads it. The underscore prefix was a deliberate convention to signal an intentionally unused parameter. Removing the prefix makes it look like the parameter is meant to be used, losing that intent signal.

Fix in Cursor Fix in Web

@AtulYadav25

Copy link
Copy Markdown
Contributor Author

@omegascorp Conflicts with main have been resolved. Apologies for so delayed updates on PR..
The tests for the changes are all passed pnpm test. Please review and merge when convenient.

For resolving the conflicts,

  • I updated handleExistingProviderLogin to Add User firstName,lastName, avatarUrl if not exists in the user data when user login
  • Updated handleExistingEmailLogin same, profile fields to backfill from provider data if missing, (Case: User Already existed via email verification but now trying to login via OAuth Providers from the same email )
  • In handleNewUserSignup it automatically adds up the profile fields got from userData
  • Updated test file oauth-common.test.ts

.trim()
.max(opts.max, { message: `must be at most ${opts.max} characters` })
.transform((val) => (val === '' ? undefined : val))
.optional();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Transform converts empty strings to undefined, mismatching tests and intent

Medium Severity

The trimmedOptionalString schema includes .transform((val) => (val === '' ? undefined : val)) which converts empty strings to undefined. This contradicts the test expectations at lines 91–93 and 96–98, which expect { firstName: '' } to remain after validation. In production, this means updateProfile({ firstName: '' }) would pass { firstName: undefined } to MongoDB's $set, which stores null — creating inconsistency with backfill checks that use === undefined.

Additional Locations (1)

Fix in Cursor Fix in Web

.string()
.trim()
.min(opts.min ?? 1, { message: `must be at least ${opts.min ?? 1} characters` })
.max(opts.max, { message: `must be at most ${opts.max} characters` });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Handle empty-string error message doesn't match test expectations

Medium Severity

When handle is '' or whitespace-only, the trimmedNonEmptyString min-length check produces the error "handle: must be at least 3 characters" via the generic formatting in validateProfileFields. The tests expect the error message "handle cannot be empty.", which is not a substring of the actual error, causing test failures. The validator lacks a distinct empty-input error path.

Additional Locations (1)

Fix in Cursor Fix in Web


await authenticateUser(res, existingUser._id);
//Add User FirstName,LastName, AvatarURL if not exists
const update: Partial<OAuthUserData> = {};

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Overly broad type allows non-profile fields in $set

Low Severity

The update and profileUpdate variables are typed as Partial<OAuthUserData>, which includes id, email, emailVerified, and providerName — fields that must never be part of a user document $set operation. While the runtime code currently only assigns profile fields, this loose typing doesn't prevent accidental assignment of dangerous fields like email or providerName directly onto the user document. A narrower type like Partial<Pick<OAuthUserData, 'firstName' | 'lastName' | 'avatarUrl'>> would make the intent explicit and prevent misuse.

Additional Locations (1)

Fix in Cursor Fix in Web

Comment thread packages/modelence/src/auth/profile.ts Outdated
if (Object.keys(update).length > 0) {
try {
await usersCollection.updateOne({ _id: profile._id }, { $set: update });
profile = { ...profile, ...update } as typeof profile;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Empty string clearing produces undefined values in MongoDB $set

Medium Severity

When a user tries to clear a profile field by passing an empty string (e.g., updateProfile({ firstName: '' })), validateProfileFields transforms it to { firstName: undefined }. This object then passes the Object.keys(update).length > 0 check and gets sent to MongoDB as $set: { firstName: undefined }. With the MongoDB Node.js driver v6, undefined is serialized as BSON null, so the field ends up as null instead of being properly removed with $unset. The in-memory merge profile = { ...profile, ...update } also applies the undefined value, so the API response may diverge from the database state depending on BSON serialization settings.

Fix in Cursor Fix in Web

…et. Fix: Overly broad type allows non-profile fields in oauth-common.ts
}

suffix++;
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unbounded loop in handle suffix generation

Low Severity

findAvailableHandle uses a while (true) loop that increments a suffix and queries the database on each iteration with no upper bound. If many handles share the same base (e.g., via automated signups), this could issue a large number of sequential DB queries, degrading performance or effectively hanging the signup request. A maximum iteration limit with a fallback (or random suffix) would make this resilient.

Fix in Cursor Fix in Web

@cursor cursor 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.

Cursor Bugbot has reviewed your changes and found 1 potential issue.

Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the Cursor dashboard.


throw new Error(
`Could not generate a unique handle for base "${baseHandle}" after exhausting all attempts.`
);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Handle resolution performs many sequential DB queries

Low Severity

findAvailableHandle checks handle availability one candidate at a time via sequential findOne calls — up to 1 + 50 + 10 = 61 round trips in the worst case. This runs during user-facing signup (both OAuth and password). For popular base handles, this could add significant latency. A single batch query using $in to check multiple candidates at once would be much more efficient.

Fix in Cursor Fix in Web

@omegascorp

Copy link
Copy Markdown
Collaborator

Thank you @AtulYadav25, testing

@omegascorp omegascorp left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Thank you @AtulYadav25, appoved.

@omegascorp
omegascorp merged commit f163899 into modelence:main Mar 10, 2026
2 checks passed
@AtulYadav25

Copy link
Copy Markdown
Contributor Author

Thank you @AtulYadav25, appoved.

Thanks @omegascorp ! 🤝

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.

3 participants