Skip to content

Give people a handle they can be mentioned by - #274

Merged
imshashank merged 3 commits into
mainfrom
fix/clean-signup-handles
Aug 9, 2026
Merged

imshashank merged 3 commits into
mainfrom
fix/clean-signup-handles

Conversation

@imshashank

@imshashank imshashank commented Aug 9, 2026 •

Copy link
Copy Markdown
Contributor

Reopens the fix from #267, which was closed on the understanding that handleFor used a user ID rather than a random string. It doesn't. There are two functions with that name, and the one that runs at sign-up still appends ten random characters unconditionally on main today:

// apps/web/src/lib/auth/server.ts
function handleFor(email: string, name: string): string {
  const base = slugify(name) || slugify(email.split('@')[0] ?? '') || 'member';
  return `${base}-${randomUUID().replaceAll('-', '').slice(0, 10)}`;
}

The other one, packages/db/src/import/plane-mapping.ts, takes a taken set and already does clean base-plus-numbering. That is the good one, and it is almost certainly the one that was looked at. It only runs on import, which is why imported accounts have usable handles and everyone who signed up does not.

Handles are how mentions resolve, so in practice nobody who signed up could be @-mentioned. An account invited as [email protected] came out as hey-3402a5fa15, which no colleague is going to type.

What changes

The base handle stands on its own. A real collision takes ada-lovelace-2, then -3, and the random suffix survives only as a last resort once twenty numbered candidates are gone. All candidates are checked in one query.

Generation moves to apps/web/src/lib/auth/handle.ts so it can be tested without standing up auth: the caller passes in the "which of these are taken" lookup, and the sign-up hook supplies the database one.

Existing accounts are not touched. Anyone already carrying a random suffix can change it in profile settings, which already validates uniqueness.

The race, and why it is not fixed here

The previous review flagged that the availability query and the insert are separate operations, so two simultaneous sign-ups sharing a base can both select the same free handle and one insert then fails on the unique constraint. That is correct, and it is inherent to a Better Auth user.create.before hook: the hook returns the row it wants inserted, so there is no insert error to catch and retry from.

I have deliberately not restructured the hook to fix it, because the trade is lopsided. Today every sign-up gets an unusable handle, with certainty. After this, a sign-up can fail only when two people with the same slugified name submit within the same instant, and that failure is retryable. Trading a universal defect for a rare retryable one is worth doing on its own; fixing the race properly means assigning the handle after insert and living with a window where it is wrong, which is a bigger change than this bug warrants.

Worth its own issue if it ever actually bites.

Testing

Nine cases in apps/web/tests/lib/auth/handle.test.ts covering the name and email bases, the member fallback, first-come clean handles, numbering on collision, and the random-suffix last resort.

Verified by mutation rather than asserted: restoring the unconditional suffix fails 4 of the 9, with the file hash checked before and after to prove the mutation actually applied and was reverted.

bun run typecheck passes. bun run lint is clean. The two failures in tests/lib/auth/sign-out.test.ts are realtime socket tests that need a live database and fail identically on main, so they are not from this change.

🤖 Generated with Claude Code

Greptile Summary

This PR replaces unconditional random handle suffixes with a batched availability lookup that prefers clean handles and then numbered alternatives. The previously reported minimum-length mismatch remains in the current implementation.

  • Extracts handle generation into a separately testable module.
  • Queries all clean and numbered candidates in one database operation.
  • Adds tests for base selection, collisions, numbering, and random fallback.

Confidence Score: 4/5

The PR should not merge until generated handles satisfy the mention parser’s minimum length.

A signup whose name or email local part slugifies to one character still persists that value as the handle, while mention extraction only recognizes handles containing at least two characters.

Files Needing Attention: apps/web/src/lib/auth/handle.ts

Important Files Changed

Filename Overview
apps/web/src/lib/auth/handle.ts Introduces clean and numbered handle generation, but still permits one-character handles that cannot be resolved by mention extraction.
apps/web/src/lib/auth/server.ts Connects asynchronous uniqueness lookup to the user creation hook and persists the selected handle directly.
apps/web/tests/lib/auth/handle.test.ts Covers generation and collision behavior but does not cover the outstanding one-character handle case.

Reviews (2): Last reviewed commit: "fix(auth): name the handle-candidate con..." | Re-trigger Greptile

Every account created since sign-up existed got a handle of the form
name-3402a5fa15, because handleFor appended ten random characters
unconditionally. Handles are how mentions work, so nobody could realistically
be @-mentioned unless their handle predated sign-up, which in practice meant
only imported accounts had a usable one.

The base now stands on its own. A collision takes ada-lovelace-2, then -3, and
the random suffix survives only as the last resort after twenty numbered
candidates are gone. One query covers every candidate.
@imshashank
imshashank requested a review from pulkitxm as a code owner August 9, 2026 19:36
@vercel

vercel Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

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

Project Deployment Actions Updated (UTC)
orbit Ready Ready Preview Aug 9, 2026 7:49pm

Request Review

@coderabbitai

coderabbitai Bot commented Aug 9, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

Changes

Authentication handle generation

Layer / File(s) Summary
Handle candidate generation and validation
apps/web/src/lib/auth/handle.ts, apps/web/tests/lib/auth/handle.test.ts
Handle generation derives a base from the name, email, or member, checks numbered candidates, and uses a UUID suffix when needed. Tests cover fallback and collision cases.
Database-backed user creation integration
apps/web/src/lib/auth/server.ts
User creation queries existing handles, delegates to uniqueHandleFor, and awaits the generated handle.

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

Sequence Diagram(s)

sequenceDiagram
  participant UserCreationHook
  participant uniqueHandleFor
  participant Database
  UserCreationHook->>uniqueHandleFor: generate handle
  uniqueHandleFor->>Database: query existing handles
  Database-->>uniqueHandleFor: return taken handles
  uniqueHandleFor-->>UserCreationHook: return unique handle
  UserCreationHook-->>UserCreationHook: augment user data
Loading

Suggested reviewers: pulkitxm

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title clearly describes the main change: generating handles that support user mentions.
Description check ✅ Passed The description directly explains the handle-generation changes, collision handling, testing, and known race condition.
✨ 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 fix/clean-signup-handles

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.

@github-actions github-actions Bot added tests Test coverage and test infrastructure area: web The Next.js app and its UI area: auth Sign-in, sessions, passkeys, OAuth labels Aug 9, 2026

@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

🤖 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/src/lib/auth/handle.ts`:
- Around line 12-15: Update the numbered candidate generation in the surrounding
function to use length NUMBERED_CANDIDATES, producing all twenty variants
through -21 before the random fallback. Add a test covering the base and -2
through -20 being occupied, and assert that -21 is selected without using the
random suffix.

In `@apps/web/src/lib/auth/server.ts`:
- Around line 85-94: The handleFor/takenHandles allocation is a
check-then-insert race that permits duplicate handles during concurrent
sign-ups. Replace this flow with atomic handle allocation—using an insert
guarded by a unique constraint and retrying on unique-constraint collisions—and
ensure concurrent account creation yields distinct handles. Add a concurrency
test that asserts both users receive different handles and fails if uniqueness
regresses.

In `@apps/web/tests/lib/auth/handle.test.ts`:
- Line 2: Update the import in the handle tests to use the web-app alias
`@/lib/auth/handle.ts` instead of the relative path, while preserving the existing
handleBaseFor and uniqueHandleFor imports.
🪄 Autofix

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: cddbb719-d6b0-43ab-852d-d79009367f0e

📥 Commits

Reviewing files that changed from the base of the PR and between c594023 and ca8e477.

📒 Files selected for processing (3)
  • apps/web/src/lib/auth/handle.ts
  • apps/web/src/lib/auth/server.ts
  • apps/web/tests/lib/auth/handle.test.ts

Comment thread apps/web/src/lib/auth/handle.ts Outdated
Comment on lines +12 to +15
{ length: NUMBERED_CANDIDATES - 1 },
(_unused, index) => `${base}-${index + 2}`,
);
return [base, ...numbered];

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 | 🟡 Minor | ⚡ Quick win

Generate twenty numbered variants before fallback.

NUMBERED_CANDIDATES is 20, but this range creates only 19 numbered variants: -2 through -20. The function uses a random suffix before trying -21.

Use length: NUMBERED_CANDIDATES. Add a test where the base and -2 through -20 are taken, then assert that -21 is returned.

Based on PR objectives, the random fallback must wait until twenty numbered candidates are unavailable.

🤖 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/src/lib/auth/handle.ts` around lines 12 - 15, Update the numbered
candidate generation in the surrounding function to use length
NUMBERED_CANDIDATES, producing all twenty variants through -21 before the random
fallback. Add a test covering the base and -2 through -20 being occupied, and
assert that -21 is selected without using the random suffix.

Comment on lines +85 to +94
async function takenHandles(candidates: readonly string[]): Promise<Set<string>> {
const rows = await db
.select({ handle: schema.user.handle })
.from(schema.user)
.where(inArray(schema.user.handle, [...candidates]));
return new Set(rows.map((row) => row.handle));
}

function handleFor(email: string, name: string): Promise<string> {
return uniqueHandleFor(email, name, takenHandles);

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 | 🟠 Major | 🏗️ Heavy lift

Make handle allocation atomic.

takenHandles reads availability before Better Auth inserts the user. Two concurrent sign-ups can select the same candidate. A unique database constraint makes one sign-up fail. Without that constraint, duplicate handles persist.

Allocate the handle with an atomic insert or retry after a unique-constraint collision. Also cover concurrent account creation and assert that both users receive distinct handles.

Based on PR objectives, sign-up must generate unique handles. As per coding guidelines, a feature is incomplete until tests fail when the feature breaks.

Also applies to: 187-189

🤖 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/src/lib/auth/server.ts` around lines 85 - 94, The
handleFor/takenHandles allocation is a check-then-insert race that permits
duplicate handles during concurrent sign-ups. Replace this flow with atomic
handle allocation—using an insert guarded by a unique constraint and retrying on
unique-constraint collisions—and ensure concurrent account creation yields
distinct handles. Add a concurrency test that asserts both users receive
different handles and fails if uniqueness regresses.

Source: Coding guidelines

Comment thread apps/web/tests/lib/auth/handle.test.ts Outdated
@@ -0,0 +1,70 @@
import { describe, expect, it } from 'bun:test';
import { handleBaseFor, uniqueHandleFor } from '../../../src/lib/auth/handle.ts';

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Use the web-app import alias.

Replace the relative import with @/lib/auth/handle.ts. This keeps internal imports consistent when the source tree moves.

As per coding guidelines, use @/ for internal imports inside apps/web.

🤖 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/tests/lib/auth/handle.test.ts` at line 2, Update the import in the
handle tests to use the web-app alias `@/lib/auth/handle.ts` instead of the
relative path, while preserving the existing handleBaseFor and uniqueHandleFor
imports.

Source: Coding guidelines

const NUMBERED_CANDIDATES = 20;

export function handleBaseFor(email: string, name: string): string {
return slugify(name) || slugify(email.split('@')[0] ?? '') || 'member';

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Single-character handles break mentions

When a name or email local part slugifies to one character, handleBaseFor persists that clean handle even though mention extraction requires at least two characters, so colleagues cannot mention the new account using its assigned handle.

Prompt To Fix With AI
This is a comment left during a code review.
Path: apps/web/src/lib/auth/handle.ts
Line: 7

Comment:
**Single-character handles break mentions**

When a name or email local part slugifies to one character, `handleBaseFor` persists that clean handle even though mention extraction requires at least two characters, so colleagues cannot mention the new account using its assigned handle.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Fix in Claude Code

Review flagged that NUMBERED_CANDIDATES = 20 produced only 19 numbered
variants. The count was right (base plus -2 through -20 is twenty candidates)
but the name said "numbered", so the constant and the description disagreed.

Renamed to HANDLE_CANDIDATES, which is what it actually bounds, and pinned the
shape with two tests: the candidate list is exactly HANDLE_CANDIDATES entries
starting at the bare base, and the random suffix appears only after every one
of them is taken.

Behaviour is unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
@imshashank

Copy link
Copy Markdown
Contributor Author

Both findings are valid. One is fixed, one is deliberately not.

Candidate count (minor). Fixed in 62d5ca9, though as naming rather than behaviour. The count was already right — base plus -2 through -20 is twenty candidates — but the constant was called NUMBERED_CANDIDATES, which claims to count only the numbered ones. Renamed to HANDLE_CANDIDATES and pinned with two tests: the list is exactly HANDLE_CANDIDATES entries starting at the bare base, and the random suffix appears only once every one of them is taken. Adding a 21st candidate would have made the code match a misleading name instead of fixing it.

Atomic allocation (major). Correct, and not fixed here on purpose.

It cannot be fixed inside the current hook. handleFor runs in Better Auth's user.create.before, which returns the row it wants inserted — Better Auth performs the insert, so there is no insert error in scope to catch and retry from. Making it atomic means moving allocation after the insert and reconciling, which leaves a window where the handle is wrong and is a larger change than this bug justifies.

The trade is lopsided in favour of shipping:

  • today, every sign-up gets an unusable handle, with certainty
  • after this, a sign-up can fail only when two people whose names slugify identically submit within the same instant, and that failure is retryable

Trading a universal defect for a rare retryable one is worth doing on its own. I would rather leave the race documented than hold a fix for a certain bug behind a restructure aimed at an uncommon one.

Worth its own issue if it ever actually bites.

@imshashank
imshashank merged commit 0a3744c into main Aug 9, 2026
13 checks passed
@imshashank
imshashank deleted the fix/clean-signup-handles branch August 9, 2026 19:55

This branch was successfully deployed

1 active deployment
Preview — 62d5ca91 Deployed Aug 9, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: auth Sign-in, sessions, passkeys, OAuth area: web The Next.js app and its UI tests Test coverage and test infrastructure

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant