Skip to content

fix(invite): accept-link session bug + force password setup on join - #127

Merged
gkhngyk merged 1 commit into
mainfrom
fix/invite-accept-session
May 30, 2026
Merged

gkhngyk merged 1 commit into
mainfrom
fix/invite-accept-session

Conversation

@gkhngyk

@gkhngyk gkhngyk commented May 30, 2026

Copy link
Copy Markdown
Contributor

What

Clicking an invite mail used to bounce the user to /sign-up, then to /sign-in with credentials that didn't work. Two stacked bugs.

Bug A — session never established on /invite/<token>

The invite mail's redirect_to pointed straight at our /invite/<token> page. After Supabase verified the magic-link token, it appended ?code=<session-code> to that URL and redirected the user there. But our /invite/[token]/page.tsx is a server component — supabase.auth.getUser() returns null because the ?code= hadn't been exchanged for a cookie session yet. The if (!user) branch fired and ejected the user to /sign-up?invite=....

On /sign-up, the form called supabase.auth.signUp({ email, password }) on an email that already existed (created by inviteUserByEmail). Supabase returned a soft success without actually changing credentials, and the form pushed the user to /sign-in?verified=pending. The password they typed didn't match anything in the DB.

Bug B — invited users have no password to sign back in with

inviteUserByEmail creates an auth.users row with no encrypted_password. Even if Bug A hadn't existed, the user would land on the accept card with a single 'Join' button, accept, get into the dashboard once via the magic-link session — then never be able to sign back in. They have nothing to type at the sign-in form.

Why

This is the canonical broken-invite-flow that every customer's first invited teammate would have hit. The team-invite UI itself works (the mail goes out via Resend) so it looks healthy from the inviter's side — the breakage is entirely downstream, on the invitee's first click.

Scope

  • team.ts: the invite link in inviteMember is now

    ${appUrl}/auth/callback?next=${encodeURIComponent(`/invite/${token}`)}
    

    /auth/callback already calls exchangeCodeForSession and forwards to next. So by the time the user lands on /invite/<token> they have a cookie session and the !user branch never fires.

  • AcceptInvitationCard: the single 'Join' button is now a small form — Full name (optional), Password + Confirm Password (required, min 8 chars). On submit it does

    await supabase.auth.updateUser({ password, data: { full_name } });
    await acceptInvitation(token);
    

    Order matters: if updateUser fails we never flip the invitation to 'accepted' — the user can retry the link instead of landing in a half-joined state.

Test plan

  1. Delete any prior auth.users / invitations for the test email
  2. From the dashboard team page, invite the test email
  3. Open the mail (delivered via Resend), click 'Accept the invite'
  4. Land on /invite/<token> directly (no detour through /sign-up)
  5. Set full name + password, click 'Accept and join'
  6. Land in /dashboard as a member of the inviter's org
  7. Sign out → sign back in with the password just set → succeeds

Out of scope

  • The /sign-up?invite=... fallback path in /invite/[token]/page.tsx (line ~32). With the redirect fix this path shouldn't fire for normal invite clicks; if someone lands on /invite/<token> directly without a session it's still the same old broken redirect. Out of scope here, easy follow-up if anyone hits it.
  • 'Delete user from team' doesn't clean up auth.users — separate concern, separate fix.

…ive, prompt for password

Symptom: clicking an invite mail bounced the user to /sign-up, then to
/sign-in with credentials that didn't work. Two stacked bugs:

1. The invite mail's redirect_to pointed straight at /invite/<token>.
   Supabase appends ?code=<session-code> to that URL after verifying the
   magic link, but our /invite page is a server component that calls
   supabase.auth.getUser() with no code-exchange step in between. It saw
   no session, fell into its 'if (!user)' branch, and ejected the user
   to /sign-up. The /sign-up form then called signUp() on an email that
   already existed (the invite created the auth row), got a soft success
   without actually setting credentials, and pushed the user to /sign-in
   where their typed password didn't match anything.

2. inviteUserByEmail creates an auth.users row with no password. Even
   when the session is good, the user has nothing to sign back in with
   later. The accept card just had a 'Join' button — no password setup.

Fix:
- team.ts: invite mail's redirect_to is now /auth/callback?next=/invite/<token>.
  /auth/callback already calls exchangeCodeForSession and forwards to
  next, so by the time the user lands on the invite page they have a
  cookie session and the !user branch never fires.
- AcceptInvitationCard: turned the single button into a small form —
  full name (optional), password + confirm (required, min 8). On submit
  it updateUser({ password, full_name }) before calling acceptInvitation,
  so the moment the invite flips to 'accepted' the credentials are good.
@gkhngyk
gkhngyk merged commit 4678a64 into main May 30, 2026
3 checks passed
gkhngyk added a commit that referenced this pull request May 30, 2026
…ash-flow, not PKCE (#129)

* fix(invite): use verifyOtp via /auth/confirm — invite mails ship hash-flow tokens, not PKCE codes

The /auth/callback hop added in #127 only works for PKCE OAuth flows
where the browser holds the code verifier. Admin-initiated invite
emails (supabase.auth.admin.inviteUserByEmail) have no PKCE verifier
on the recipient's browser — Supabase's verify endpoint returns the
session as URL hash params (#access_token=...&refresh_token=...) which
server components can't read. /auth/callback sees no ?code=, redirects
to /sign-in?error=auth_callback_failed, and the user falls into the
old broken /sign-up dance again.

Canonical fix is the OTP-token-hash flow Supabase documents for SSR:

- New /auth/confirm route handler reads ?token_hash + ?type + ?redirect_to,
  calls supabase.auth.verifyOtp({ type, token_hash }), and 302s to the
  destination once the session cookie is set server-side. Works for
  every Supabase email type (invite, signup, recovery, magiclink,
  email_change) — the type comes from the template, not from us.
- team.ts inviteLink is now plain ${appUrl}/invite/<token> again. The
  auth hop is no longer in the redirect; it's in the email template's
  link itself.

Required ops step (manual, not in code): the Supabase project's Auth →
Email Templates → 'Invite user' template needs the link changed from
{{ .ConfirmationURL }} to:

  {{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=invite&redirect_to={{ .RedirectTo }}

Same swap recommended for signup / recovery / magiclink templates so
every email auth flow goes through the same SSR-friendly path. Until
that's done the invite link still hits the old default URL and the
fix doesn't take effect.

* fix(invite): use {{ .RedirectTo }}-based template prefix so a single template covers dev + prod

Previous attempt put /auth/confirm under {{ .SiteURL }} in the email
template. Supabase's Site URL is one project-wide value (production
https://app.ansvisor.com here), so the same template can't drive
both prod testing and a localhost dev loop — the link always points
at prod regardless of NEXT_PUBLIC_APP_URL.

Switch the redirectTo we pass to inviteUserByEmail to be the full
/auth/confirm URL with our next path baked in:

  ${appUrl}/auth/confirm?next=/invite/<token>

Template now uses {{ .RedirectTo }} as the prefix and only appends
the OTP params:

  {{ .RedirectTo }}&token_hash={{ .TokenHash }}&type=invite

Because appUrl resolves to whichever NEXT_PUBLIC_APP_URL is in the
current environment, the link goes to localhost in dev and prod in
prod — without changing Supabase project settings between the two.
gkhngyk added a commit that referenced this pull request May 30, 2026
…ntl rewrite was 404ing (#130)

* fix(invite): use verifyOtp via /auth/confirm — invite mails ship hash-flow tokens, not PKCE codes

The /auth/callback hop added in #127 only works for PKCE OAuth flows
where the browser holds the code verifier. Admin-initiated invite
emails (supabase.auth.admin.inviteUserByEmail) have no PKCE verifier
on the recipient's browser — Supabase's verify endpoint returns the
session as URL hash params (#access_token=...&refresh_token=...) which
server components can't read. /auth/callback sees no ?code=, redirects
to /sign-in?error=auth_callback_failed, and the user falls into the
old broken /sign-up dance again.

Canonical fix is the OTP-token-hash flow Supabase documents for SSR:

- New /auth/confirm route handler reads ?token_hash + ?type + ?redirect_to,
  calls supabase.auth.verifyOtp({ type, token_hash }), and 302s to the
  destination once the session cookie is set server-side. Works for
  every Supabase email type (invite, signup, recovery, magiclink,
  email_change) — the type comes from the template, not from us.
- team.ts inviteLink is now plain ${appUrl}/invite/<token> again. The
  auth hop is no longer in the redirect; it's in the email template's
  link itself.

Required ops step (manual, not in code): the Supabase project's Auth →
Email Templates → 'Invite user' template needs the link changed from
{{ .ConfirmationURL }} to:

  {{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=invite&redirect_to={{ .RedirectTo }}

Same swap recommended for signup / recovery / magiclink templates so
every email auth flow goes through the same SSR-friendly path. Until
that's done the invite link still hits the old default URL and the
fix doesn't take effect.

* fix(invite): use {{ .RedirectTo }}-based template prefix so a single template covers dev + prod

Previous attempt put /auth/confirm under {{ .SiteURL }} in the email
template. Supabase's Site URL is one project-wide value (production
https://app.ansvisor.com here), so the same template can't drive
both prod testing and a localhost dev loop — the link always points
at prod regardless of NEXT_PUBLIC_APP_URL.

Switch the redirectTo we pass to inviteUserByEmail to be the full
/auth/confirm URL with our next path baked in:

  ${appUrl}/auth/confirm?next=/invite/<token>

Template now uses {{ .RedirectTo }} as the prefix and only appends
the OTP params:

  {{ .RedirectTo }}&token_hash={{ .TokenHash }}&type=invite

Because appUrl resolves to whichever NEXT_PUBLIC_APP_URL is in the
current environment, the link goes to localhost in dev and prod in
prod — without changing Supabase project settings between the two.

* fix(invite): mirror /auth/confirm under [locale]/(marketing) so next-intl can resolve it

PR #129 added /auth/confirm at the root app directory only. next-intl
middleware rewrites every /auth/* request to /[locale]/auth/*, and the
deployed bundle had no matching file under [locale]/auth/confirm — so
the request landed on the framework 404 page.

The existing /auth/callback works because there's already a
[locale]/(marketing)/auth/callback/route.ts that the rewrite resolves
to. Add the equivalent mirror for confirm so the same routing rules
have a destination.

Verified via response headers — /auth/callback shows
`x-matched-path: /[locale]/auth/callback`, /auth/confirm before this
change matched /404 with x-vercel-cache HIT. Keeping the root
/auth/confirm/route.ts around to stay consistent with the callback
sibling pattern; it's never hit but matches the existing convention.
gkhngyk added a commit that referenced this pull request May 31, 2026
Bundles the in-product Agent epic (#120, #121), the BYOK rollout on
cloud, the MCP toolkit expansion (#109, #110, #116, #117, #118), the
insights performance fix (#114), and the invite-accept flow rebuild
(#127, #129, #130) into a tagged release.

See CHANGELOG.md for the full notes.
gkhngyk added a commit that referenced this pull request May 31, 2026
Bundles the in-product Agent epic (#120, #121), the BYOK rollout on
cloud, the MCP toolkit expansion (#109, #110, #116, #117, #118), the
insights performance fix (#114), and the invite-accept flow rebuild
(#127, #129, #130) into a tagged release.

See CHANGELOG.md for the full notes.

This branch was successfully deployed

1 active deployment
Preview — 51c10ffd Deployed May 30, 2026 by vercel[bot]
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.

1 participant