Repository navigation
Give people a handle they can be mentioned by - #274
Conversation
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.
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
📝 WalkthroughWalkthroughChangesAuthentication handle generation
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
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 Files selected for processing (3)
apps/web/src/lib/auth/handle.tsapps/web/src/lib/auth/server.tsapps/web/tests/lib/auth/handle.test.ts
| { length: NUMBERED_CANDIDATES - 1 }, | ||
| (_unused, index) => `${base}-${index + 2}`, | ||
| ); | ||
| return [base, ...numbered]; |
There was a problem hiding this comment.
🎯 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.
| 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); |
There was a problem hiding this comment.
🗄️ 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
| @@ -0,0 +1,70 @@ | |||
| import { describe, expect, it } from 'bun:test'; | |||
| import { handleBaseFor, uniqueHandleFor } from '../../../src/lib/auth/handle.ts'; | |||
There was a problem hiding this comment.
📐 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'; |
There was a problem hiding this 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.
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.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]>
|
Both findings are valid. One is fixed, one is deliberately not. Candidate count (minor). Fixed in Atomic allocation (major). Correct, and not fixed here on purpose. It cannot be fixed inside the current hook. The trade is lopsided in favour of shipping:
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. |
Reopens the fix from #267, which was closed on the understanding that
handleForused 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 onmaintoday:The other one,
packages/db/src/import/plane-mapping.ts, takes atakenset 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 ashey-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.tsso 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.beforehook: 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.tscovering the name and email bases, thememberfallback, 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 typecheckpasses.bun run lintis clean. The two failures intests/lib/auth/sign-out.test.tsare realtime socket tests that need a live database and fail identically onmain, 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.
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
Reviews (2): Last reviewed commit: "fix(auth): name the handle-candidate con..." | Re-trigger Greptile