<recommended_plugins>
Here is a list of plugins that are available but not installed. If the user's query would benefit from one of these plugins, use the request_plugin_install tool to suggest that they install it. Pass the parenthesized ID as plugin_id. For example, suggest the Google Drive plugin if the query could possibly be better answered with access to Google Drive.
Paths (web): use alias ~/ for src imports (e.g., import { x } from "~/utils/x").
NEVER USE DYNAMIC IMPORTS. ALWAYS IMPORT ON THE TOP
Rules
Prefer to use trpc alway unless asked otherwise
Testing Guidelines
Web testing is configured with Vitest in apps/web; add tests when changes impact logic, APIs, or behavior.
Prefer targeted suites first: pnpm test:web:unit, pnpm test:web:trpc, pnpm test:web:api; use pnpm test:web for default non-integration coverage.
Test file conventions: *.unit.test.ts, *.trpc.test.ts, *.api.test.ts, *.integration.test.ts.
Integration tests require infra and env (RUN_INTEGRATION=true with Postgres/Redis available). Root commands pnpm test:web:all and pnpm test:web:integration:full auto-manage infra lifecycle.
Use pnpm test:infra:up / pnpm test:infra:down when running targeted integration commands manually.
pnpm test:web:integration:full and test:integration:prepare run Prisma migrations (prisma migrate deploy); never run these unless the user explicitly asks.
Test defaults are cloud mode (NEXT_PUBLIC_IS_CLOUD=true); keep new tests compatible with cloud behavior unless the task says otherwise.
I’ll check the self-hosted authentication and signup guards in this repository so the answer matches this version’s actual behavior.
Assistant
Yes. In the current self-hosted version, anyone who can reach the instance can create an account through /signup using any configured authentication provider.
There’s no signup allowlist or “disable registration” setting. New self-hosted users are automatically activated—not waitlisted. However, self-hosting supports only one team, so new accounts don’t create separate isolated teams.
If your instance is internet-accessible, restrict access at the reverse proxy/VPN level or add an invite-only signup guard.
User
i don't want this. only first user should able to sign up. after that only invited users can sign up. should not allow any random user to signup. can you work on plan for that?
Assistant
I’ll trace account creation, team invitations, and the signup/login routes, then turn that into an implementation plan with the important race-condition and OAuth considerations covered.
Assistant
The key finding is that hiding /signup is not sufficient: NextAuth can create a new user from the normal /login flow too. The restriction must live at the adapter/account-creation boundary, and the current invite acceptance flow also needs email ownership checks because an inviteId alone can presently expose and accept an invite.
Assistant
The implementation plan is ready.
Core policy:
The first user on a fresh self-hosted installation may register and becomes the initial administrator.
After that, existing users may always sign in.
New users may register only when a pending invitation matches their verified email address.
Enforcement happens server-side for every authentication provider—not merely by hiding /signup.
Invite lookup and acceptance will require the signed-in email to match the invited email.
Atomic database operations will prevent two concurrent requests from both becoming the “first user.”
The UI will remove public signup prompts after bootstrap and show a clear “Invitation required” response.
Tests will cover email and OAuth paths, invitation misuse, stale invitations, and concurrency.
No migration should be necessary; the existing User and TeamInvite records contain the required state. I would avoid making /signup itself the security boundary because new accounts can currently also originate through /login.
User
expand the plan in detail, not sure what youre going to do. it's not clear
Assistant
I’ll make the plan concrete at the code level: exact enforcement points, route behavior, invite validation, concurrency handling, tests, and what remains unchanged for cloud deployments.
Assistant
Desired behavior
For self-hosted installations:
If the database has no users, one person may register.
That first user follows the existing onboarding flow and becomes administrator of the first team they create.
Once the first user exists, unknown users cannot register.
Existing users can always sign in.
A new user can register only if TeamInvite contains an invitation for the email address proven by their authentication provider.
Knowing or guessing an inviteId is insufficient—the authenticated email must match.
Cloud-hosted behavior remains unchanged.
Authentication flow
mermaid
flowchart TD
A["Authentication callback"] --> B{"Cloud deployment?"}
B -->|"Yes"| C["Keep current behavior"]
B -->|"No"| D{"Existing user/account?"}
D -->|"Yes"| E["Allow sign-in"]
D -->|"No"| F{"Any users exist?"}
F -->|"No"| G["Atomically create first user"]
F -->|"Yes"| H{"Pending invite matches verified email?"}
H -->|"Yes"| I["Create invited user"]
H -->|"No"| J["Reject: invitation required"]
The important part is that this decision happens on the server when NextAuth attempts to create the user. /signup is only presentation; it will not be trusted as the security boundary.
1. Central registration policy
I’ll add a small server-side helper, likely near auth.ts, responsible for answering:
Is this cloud or self-hosted?
Does this authentication attempt belong to an existing user?
Is the database empty?
Does a pending invitation match this email?
Should user creation be allowed?
Email addresses will be trimmed and normalized to lowercase for new records. Existing invitations with mixed-case addresses will still match case-insensitively.
The helper will return an explicit result such as:
existing-user
first-user
invited-user
invite-required
User
seems to completely useless, why do we need it?
there's a reason this flow exist, inviteId is enough, then if use signs with anyother method with different email then it won't work. do not change this
7. i don't even understand why this is needed
Assistant
You’re right that items 4 and 7 are not required for the security boundary; I’ll remove them. On item 5, I want to flag one concrete mismatch between the intended flow and the current implementation before revising the plan.
Assistant
You’re right about items 4 and 7. I added unnecessary UX and normalization work that wasn’t required for your request. Both are removed.
One clarification on item 5: currently, signing in with a different email does work if the user has the inviteId. The invitation queries by ID alone at invitiation.ts:20, and acceptance also queries only by ID at invitiation.ts:47. However, since you explicitly want that bearer-link flow preserved, I will not change it.
Revised plan
1. Decide whether NextAuth may create the user
For self-hosted only:
If the authenticating account already exists, allow sign-in.
If there are no users, allow this account to become the first user.
If users already exist, look for a TeamInvite matching the provider-supplied email.
If a matching invitation exists, allow account creation.
Otherwise, reject account creation.
Cloud mode remains unchanged.
The invitation is only checked here to authorize creating the account. I will not change how inviteId is subsequently used to join the team.
2. Reject uninvited users early
Add a NextAuth signIn callback:
Email provider: do not send an OTP to an uninvited new email.
Google/GitHub: reject an uninvited new account during the callback.
Existing accounts continue normally.
This is an early check for efficiency. It will not be the authoritative security boundary.
3. Enforce the rule during database user creation
Override the Prisma authentication adapter’s createUser operation.
For self-hosted account creation, it will:
Start a database transaction.
Lock self-hosted registration using a PostgreSQL advisory lock.
Check whether a user already exists.
If none exists, insert the first user.
Otherwise, require a matching TeamInvite.email.
Insert the invited user or reject the request.
Commit and release the lock.
The lock prevents this race:
Two people register simultaneously.
Both initially see an empty database.
Without locking, both could become the first user.
User
make the changes and tests
Assistant
I’ll implement the narrowed backend-only policy and targeted tests. I’ll leave the login/signup UI and the existing inviteId acceptance flow untouched, as agreed.
Assistant
I’ve narrowed the implementation to two enforcement layers: an early NextAuth eligibility check and an atomic adapter-level creation check. The latter is the real security boundary and handles simultaneous first-user attempts.
Assistant
The code and unit tests are in place. Dependency tooling was not initialized in this worktree, so the formatter restored the locked workspace dependencies; I’m now running only the targeted auth unit test, not a build or migration-backed suite.
Assistant
The targeted tests and lint pass. A type-check exposed that this fresh worktree’s Prisma client had not been generated, plus two type annotations needed in the new adapter wrapper. I’m generating the client only (no schema change or migration) so I can verify the production types accurately.
Assistant
The enforcement now preserves the existing invite-link flow while blocking account creation unless the database is empty or the authentication email already has an invite. I’m doing the final targeted verification, including confirming the database lock is acquired before checking for the first user.
Assistant
Implemented the self-hosted signup restriction.
Changes in auth.ts:
First user can register without an invitation.
Existing users can always sign in.
Subsequent new users require a matching TeamInvite.email.
Uninvited users are rejected early by NextAuth and again during database creation.
PostgreSQL advisory locking prevents two simultaneous registrations from both becoming the first user.
Cloud registration behavior is unchanged.
Login, signup, and inviteId acceptance flows were not modified.
Tests in auth.unit.test.ts cover first user, existing users, invited users, uninvited users, missing emails, atomic locking, and cloud behavior.
That keeps the rules testable and prevents slightly different policy logic from spreading across pages and callbacks.
2. Early rejection in NextAuth
I’ll add a signIn callback in auth.ts.
This is the early, user-friendly check:
Existing users are allowed.
The first prospective user is allowed.
Invited email addresses are allowed.
Other new users are redirected back with an InviteRequired error.
A new provider account without an email address is denied because its invitation cannot be verified.
For email authentication, this check also prevents sending an OTP to an obviously ineligible address. For OAuth, it prevents most random accounts from progressing past the provider callback.
This callback improves UX, but it will not be the final security control because two requests could pass the check simultaneously.
3. Authoritative, concurrency-safe enforcement
I’ll wrap the existing PrismaAdapter and override its createUser operation.
Inside createUser, self-hosted registration will run in one database transaction:
Acquire a PostgreSQL transaction-scoped advisory lock dedicated to registration.
Check whether a user already exists.
If no user exists, permit creation of the first user.
Otherwise, search for a pending invite matching the normalized email.
Create the user only if the invite exists.
Commit, releasing the lock.
The advisory lock matters because a simple user.count() === 0 check has a race:
Alice checks and sees zero users.
Bob checks at the same time and also sees zero users.
Both become “first” users.
Serializing the check and insert means the second request sees the first committed user and must have an invitation.
No schema migration is needed for this approach.
The invitation will not be deleted during account creation. It will be consumed when the authenticated user explicitly accepts it and becomes a team member.
4. Signup and login pages
I’ll update:
signup/page.tsx
login/page.tsx
login-page.tsx
Self-hosted behavior will be:
Before the first account exists, /signup displays “Create administrator account.”
After the first account exists, /signup redirects to /login.
The public “Create new account” link disappears after bootstrap.
/login continues showing configured authentication providers because existing users still need them.
An unknown user who authenticates receives a clear message: “This instance is invite-only. Ask an administrator to invite your email address.”
The page will not reveal whether any arbitrary email has a pending invitation.
Invite links will continue through /join-team?inviteId=..., which preserves the invite ID across authentication.
Cloud mode will keep the existing signup link and account-creation behavior.
5. Secure the invitation flow
The existing invitation router has a security issue independent of public signup: when an inviteId is supplied, invite lookup and acceptance do not currently require the logged-in email to match the invited email.
I’ll update invitiation.ts so every operation uses both:
The invitation ID.
The authenticated user’s email address.
That applies to:
getUserInvites
getInvite
acceptTeamInvite
Someone signed in as attacker@example.com will not be able to inspect or accept an invitation intended for person@example.com, even if they possess its URL.
6. Atomic invitation acceptance
Accepting an invite will become a single transaction:
Find the invite by ID and authenticated email.
Verify the user is not already a member.
Create the TeamUser membership with the invited role.
Delete the invitation.
Commit both changes together.
This prevents partial results such as membership being created while the invitation remains reusable.
The API will return controlled errors for:
Cancelled or already-consumed invites.
An invite belonging to another email.
A user already belonging to the team.
Duplicate concurrent acceptance attempts.
The UI should use a generic “Invitation is invalid or no longer available” message so it does not disclose invitation details.
7. Normalize invitations when created
I’ll update TeamService.createTeamInvite in team-service.ts to store new invitation emails in normalized lowercase form.
Checks for existing users and existing invitations will use the same normalized value. Matching will remain case-insensitive so invitations created before this change continue to work.
No invitation expiry will be introduced in this work. Invitations will remain valid until accepted or cancelled, matching the current data model.
8. Tests
I’ll add focused tests covering:
Registration policy
Cloud mode preserves current open-registration behavior.
A fresh self-hosted database permits the first user.
A self-hosted database with an existing user rejects an unknown email.
A matching invitation permits a new user.
Email matching is case-insensitive.
An invitation for a different email does not permit registration.
Existing users can sign in without an outstanding invitation.
New accounts without an email are rejected.
Authentication entry points
/signup is available before bootstrap.
/signup redirects after bootstrap.
Random registration is denied even when attempted through /login.
Email OTP requests for unknown users are rejected.
OAuth creation for unknown users is rejected.
Invite-required errors render correctly.
Concurrency
Two simultaneous first-user creation attempts result in exactly one user.
The losing request is denied unless its email is invited.
Invitations
An invited user can view and accept their invite.
A different authenticated user cannot view or accept it.
Acceptance creates membership and removes the invite.
A consumed or cancelled invite cannot be reused.
Concurrent acceptance does not create duplicate membership.
Unit tests can run without infrastructure. Database concurrency tests should be added as integration tests, but repository instructions prevent me from running migration-backed integration commands unless you explicitly authorize that later.
9. Documentation
I’ll update the self-hosting documentation to explain:
The first registered account bootstraps the installation.