Files
resolutionflow/frontend/src/pages/AcceptInvitePage.tsx
Michael Chihlas 39e85c9770 feat(auth): add /accept-invite page + lookup endpoint
Adds the invitee-side flow for self-serve signup Phase 2 (Task 36):

Backend
- Public GET /accounts/invites/{code}/lookup returns
  {account_name, inviter_name, invited_email, role} for a valid invite,
  404 invite_invalid_or_expired_or_revoked otherwise (collapses unknown /
  expired / revoked / used into one anti-enumeration response). Mounted
  in a new account_invite_lookup endpoints module on the public route
  list, uses get_admin_db (BYPASSRLS) since the caller has no tenant.
- OAuthCallbackPayload gains optional account_invite_code + invited_email.
  _sign_in_or_register honors them: a new OAuth user with a valid invite
  joins the invited account (no personal account, no Pro trial), the
  invite is marked used, and OAuth-profile-email vs invite-email mismatch
  raises invite_email_mismatch (matching the email+password register
  contract).

Frontend
- New public route /accept-invite -> AcceptInvitePage. Reads ?code=,
  calls inviteApi.lookupAccountInvite, renders "Join {account} on
  ResolutionFlow" with the invited email locked (rendered as a div, not
  an input), three sign-in options (set password, Google, Microsoft),
  and a clear "ask {inviter} to resend" + mailto: fallback for invalid
  codes.
- OAuth state for invitees is base64url(JSON({csrf, accountInviteCode,
  invitedEmail})). OAuthCallbackPage decodes both shapes, forwards the
  invite fields to the backend, and surfaces invite_email_mismatch /
  invite_invalid_or_expired_or_revoked errors with friendly text.
  Successful invite-OAuth lands on /?welcome=teammate (suppresses the
  welcome wizard for invitees per spec).
- UserCreate type + invite/auth API clients extended for the new fields.

Tests
- Backend: invite lookup happy path + four invalid-state collapse, OAuth
  callback links invite when supplied + rejects on email mismatch.
- Frontend Vitest: AcceptInvitePage renders account name + locked email
  + accept buttons; resend message + mailto on invalid code.

All 43 backend auth/account/invite/email-verification tests green;
frontend Vitest 120/120 green; tsc -b clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 21:34:22 -04:00

372 lines
14 KiB
TypeScript

import { useEffect, useMemo, useState } from 'react'
import { Link, useLocation, useNavigate } from 'react-router-dom'
import { inviteApi, type AccountInviteLookup } from '@/api/invite'
import { useAuthStore } from '@/store/authStore'
import { useAppConfig } from '@/hooks/useAppConfig'
import { BrandLogo } from '@/components/common/BrandLogo'
import { PasswordInput } from '@/components/common/PasswordInput'
import { PageMeta } from '@/components/common/PageMeta'
import { buildOAuthAuthorizeUrl } from './RegisterPage'
import { cn } from '@/lib/utils'
import { encodeOAuthState } from '@/lib/oauthState'
function randomCsrf(): string {
const buf = new Uint8Array(16)
if (typeof crypto !== 'undefined' && crypto.getRandomValues) {
crypto.getRandomValues(buf)
} else {
for (let i = 0; i < buf.length; i++) buf[i] = Math.floor(Math.random() * 256)
}
return Array.from(buf, (b) => b.toString(16).padStart(2, '0')).join('')
}
type LookupState =
| { status: 'loading' }
| { status: 'ok'; data: AccountInviteLookup }
| { status: 'invalid' }
| { status: 'missing-code' }
export function AcceptInvitePage() {
const navigate = useNavigate()
const location = useLocation()
const { register, isLoading, error, clearError } = useAuthStore()
const appConfig = useAppConfig()
const code = useMemo(() => {
const search = new URLSearchParams(location.search)
return (search.get('code') || '').trim()
}, [location.search])
const [lookup, setLookup] = useState<LookupState>(
code ? { status: 'loading' } : { status: 'missing-code' },
)
const [name, setName] = useState('')
const [password, setPassword] = useState('')
const [confirmPassword, setConfirmPassword] = useState('')
const [localError, setLocalError] = useState('')
useEffect(() => {
if (!code) {
setLookup({ status: 'missing-code' })
return
}
let cancelled = false
setLookup({ status: 'loading' })
void (async () => {
try {
const data = await inviteApi.lookupAccountInvite(code)
if (cancelled) return
setLookup({ status: 'ok', data })
} catch {
if (cancelled) return
// Any error — 404, 410, network — collapses to the same "ask the
// inviter to resend" UX. Anti-enumeration is enforced server-side.
setLookup({ status: 'invalid' })
}
})()
return () => {
cancelled = true
}
}, [code])
const googleAvailable = appConfig.oauth_providers.includes('google')
const microsoftAvailable = appConfig.oauth_providers.includes('microsoft')
const handleOAuth = (provider: 'google' | 'microsoft') => {
if (lookup.status !== 'ok') return
const csrf = randomCsrf()
try {
sessionStorage.setItem('rf-oauth-state', csrf)
} catch {
// ignore — non-fatal
}
const stateValue = encodeOAuthState({
csrf,
accountInviteCode: code,
invitedEmail: lookup.data.invited_email,
})
const url = buildOAuthAuthorizeUrl(provider, stateValue)
window.location.href = url
}
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setLocalError('')
clearError()
if (lookup.status !== 'ok') return
if (!name || !password) {
setLocalError('Please fill in all fields')
return
}
if (password !== confirmPassword) {
setLocalError('Passwords do not match')
return
}
if (password.length < 10) {
setLocalError('Password must be at least 10 characters')
return
}
try {
await register({
email: lookup.data.invited_email,
password,
name,
account_invite_code: code,
})
// Invitees skip the welcome wizard — they're joining an existing shop.
// The `?welcome=teammate` marker is decoded by the dashboard in Task 41
// to surface the "Welcome to {account_name}" toast and pre-checked
// checklist items.
navigate('/?welcome=teammate', { replace: true })
} catch {
// Error is set in the store
}
}
return (
<>
<PageMeta
title="Join your team on ResolutionFlow"
description="Accept an invite to join an existing ResolutionFlow account"
/>
<div className="flex min-h-screen items-center justify-center bg-black px-4">
<div className="pointer-events-none fixed inset-0 bg-[radial-gradient(circle_at_50%_0%,rgba(100,100,120,0.03),transparent_50%)]" />
<div className="relative w-full max-w-md space-y-6">
<div className="text-center">
<div className="mb-4 flex justify-center sm:mb-6">
<BrandLogo size="lg" />
</div>
<h1 className="text-3xl font-bold font-heading text-foreground tracking-tight">
ResolutionFlow
</h1>
</div>
{lookup.status === 'loading' && (
<div className="bg-card border border-border rounded-xl p-6 text-center">
<p className="text-sm text-muted-foreground">Loading invite</p>
</div>
)}
{(lookup.status === 'invalid' || lookup.status === 'missing-code') && (
<div className="bg-card border border-border rounded-xl p-6 space-y-3">
<h2 className="text-lg font-semibold text-foreground">
This invite is no longer valid
</h2>
<p className="text-sm text-muted-foreground">
{lookup.status === 'missing-code'
? 'The invite link is missing its code.'
: 'This invite has expired, been used, or been revoked.'}{' '}
Ask the person who invited you to resend it.
</p>
<a
href="mailto:?subject=Please%20resend%20my%20ResolutionFlow%20invite&body=Hi%2C%20could%20you%20resend%20my%20ResolutionFlow%20invite%3F%20The%20link%20I%20got%20is%20no%20longer%20valid.%20Thanks!"
className={cn(
'inline-block rounded-xl px-4 py-2 text-sm font-semibold btn-press',
'bg-primary text-white hover:brightness-110',
)}
>
Email your inviter
</a>
<p className="text-xs text-muted-foreground">
Already have an account?{' '}
<Link to="/login" className="font-medium text-foreground hover:underline">
Sign in
</Link>
</p>
</div>
)}
{lookup.status === 'ok' && (
<>
<div className="text-center">
<p className="text-base font-medium text-foreground">
Join <span className="font-semibold">{lookup.data.account_name}</span> on
ResolutionFlow
</p>
<p className="mt-1 text-sm text-muted-foreground">
{lookup.data.inviter_name} invited you as {lookup.data.role}.
</p>
</div>
<div className="bg-card border border-border rounded-xl p-6 space-y-4">
{(error || localError) && (
<div className="rounded-xl border border-red-400/20 bg-red-400/10 p-3 text-sm text-red-400">
{localError || error}
</div>
)}
<div>
<p className="block text-sm font-medium text-foreground">
Joining as
</p>
<p
className={cn(
'mt-1 block w-full rounded-xl border border-border bg-card px-3 py-2',
'text-foreground',
)}
data-testid="invited-email"
>
{lookup.data.invited_email}
</p>
<p className="mt-1 text-xs text-muted-foreground">
The invite is locked to this email address.
</p>
</div>
{(googleAvailable || microsoftAvailable) && (
<div className="space-y-3">
{googleAvailable && (
<button
type="button"
onClick={() => handleOAuth('google')}
data-testid="oauth-google"
className={cn(
'w-full rounded-xl px-4 py-2.5 text-sm font-semibold btn-press',
'bg-card border border-border text-foreground hover:bg-foreground/5',
'focus:outline-hidden focus:ring-2 focus:ring-primary/30',
'transition-all',
)}
>
Continue with Google
</button>
)}
{microsoftAvailable && (
<button
type="button"
onClick={() => handleOAuth('microsoft')}
data-testid="oauth-microsoft"
className={cn(
'w-full rounded-xl px-4 py-2.5 text-sm font-semibold btn-press',
'bg-card border border-border text-foreground hover:bg-foreground/5',
'focus:outline-hidden focus:ring-2 focus:ring-primary/30',
'transition-all',
)}
>
Continue with Microsoft
</button>
)}
<div className="relative my-2">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-border" />
</div>
<div className="relative flex justify-center text-xs uppercase tracking-wider">
<span className="bg-card px-2 text-muted-foreground">
or set a password
</span>
</div>
</div>
</div>
)}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label
htmlFor="name"
className="block text-sm font-medium text-foreground"
>
Full name
</label>
<input
id="name"
name="name"
type="text"
autoComplete="name"
required
value={name}
onChange={(e) => setName(e.target.value)}
className={cn(
'mt-1 block w-full rounded-xl border border-border bg-card px-3 py-2',
'text-foreground placeholder:text-muted-foreground',
'focus:border-primary focus:outline-hidden focus:ring-1 focus:ring-primary/20',
)}
placeholder="Jane Doe"
/>
</div>
<div>
<label
htmlFor="password"
className="block text-sm font-medium text-foreground"
>
Password
</label>
<PasswordInput
id="password"
name="password"
autoComplete="new-password"
required
value={password}
onChange={(e) => setPassword(e.target.value)}
className={cn(
'mt-1 block w-full rounded-xl border border-border bg-card px-3 py-2',
'text-foreground placeholder:text-muted-foreground',
'focus:border-primary focus:outline-hidden focus:ring-1 focus:ring-primary/20',
)}
placeholder="••••••••••"
/>
<p className="mt-1 text-xs text-muted-foreground">
Must be at least 10 characters
</p>
</div>
<div>
<label
htmlFor="confirmPassword"
className="block text-sm font-medium text-foreground"
>
Confirm password
</label>
<PasswordInput
id="confirmPassword"
name="confirmPassword"
autoComplete="new-password"
required
value={confirmPassword}
onChange={(e) => setConfirmPassword(e.target.value)}
className={cn(
'mt-1 block w-full rounded-xl border border-border bg-card px-3 py-2',
'text-foreground placeholder:text-muted-foreground',
'focus:border-primary focus:outline-hidden focus:ring-1 focus:ring-primary/20',
)}
placeholder="••••••••••"
/>
</div>
<button
type="submit"
data-testid="accept-submit"
disabled={isLoading}
className={cn(
'w-full rounded-xl px-4 py-2.5 text-sm font-semibold btn-press',
'bg-primary text-white hover:brightness-110',
'focus:outline-hidden focus:ring-2 focus:ring-primary/30 focus:ring-offset-2 focus:ring-offset-black',
'disabled:cursor-not-allowed disabled:opacity-50',
'transition-all',
)}
>
{isLoading ? 'Joining…' : `Join ${lookup.data.account_name}`}
</button>
</form>
</div>
</>
)}
<p className="text-center text-sm text-muted-foreground">
Already have an account?{' '}
<Link to="/login" className="font-medium text-foreground hover:underline">
Sign in
</Link>
</p>
</div>
</div>
</>
)
}
export default AcceptInvitePage