20 Commits

Author SHA1 Message Date
tanweer919 0a4468cc54 Merge pull request 'feat: real phone OTP verification (Twilio) in register + onboarding' (#16) from tanweer919/lynkeduppro-crm:feat/login-methods into goutamnextflow 2026-07-12 22:59:22 +00:00
tanweer919 da7f7a7891 feat(register/onboard): real phone OTP verification via Twilio (SDK 0.2.6)
Replaces the mock verify step (which accepted any 6 digits) with a real SMS
OTP: addPhone() → Supabase/Twilio texts a code → verifyPhone() confirms it.

- Registration creates the auth account when leaving the Account step, so the
  phone can be attached + verified against a live Supabase session; finish()
  no longer double-registers.
- Onboarding gains a real phone-verify step (Profile → Verify → Address).
- Email is trusted without an OTP in both flows (Supabase auto-confirms on
  signup; Google verifies for onboarding), matching project config.
- Bump @abe-kap/appshell-sdk to ^0.2.6.
2026-07-13 04:29:02 +05:30
tanweer919 3c6190d16a Merge pull request 'fix(onboarding): reliably prefill verified email (SDK 0.2.5)' (#15) from tanweer919/lynkeduppro-crm:feat/login-methods into goutamnextflow 2026-07-12 22:36:29 +00:00
tanweer919 6ba00bfbf9 fix(onboarding): reliably prefill the verified email (SDK 0.2.5)
getUserEmail() relied on getSession(), which returns null here because the
Supabase session is intentionally never persisted to storage — so the
onboarding email field stayed empty and Continue was blocked. SDK 0.2.5
captures the email in memory from the token-exchange response instead.
Bump @abe-kap/appshell-sdk to ^0.2.5.
2026-07-13 04:06:13 +05:30
tanweer919 5e2fa574bd Merge pull request 'fix(onboarding): gate direct access behind OAuth handoff' (#14) from tanweer919/lynkeduppro-crm:feat/login-methods into goutamnextflow 2026-07-12 22:32:35 +00:00
tanweer919 d79da8cd6a fix(onboarding): gate direct access behind the OAuth handoff
/portal/onboarding is only a step in the Google sign-in flow. Redirect to
login unless the login page's onboard_email handoff hint is present (and the
session is authenticated), instead of showing an empty form on direct/typed
URL access. Hold rendering until the check passes to avoid a form flash, and
clear the hint once onboarding completes so it can't be reused.
2026-07-13 04:01:01 +05:30
tanweer919 10141806dc Merge pull request 'fix(onboarding): prefill verified email; SDK 0.2.4' (#13) from tanweer919/lynkeduppro-crm:feat/login-methods into goutamnextflow 2026-07-12 22:26:05 +00:00
tanweer919 08ef85869f fix(onboarding): prefill verified email in a disabled field; bump SDK 0.2.4
- Onboarding reads the OAuth email (session-storage hint + live Supabase
  session via getUserEmail) so Continue is no longer disabled.
- Replace the empty 'Signed in as' banner with a disabled, prefilled
  email field (email is fixed — Google-verified).
- Stash the verified email at OAuth callback time for onboarding prefill.
- Bump @abe-kap/appshell-sdk to ^0.2.4 (getUserEmail via getSession).
2026-07-13 03:55:05 +05:30
tanweer919 619ec4c9b1 Merge pull request 'feat(auth): Google onboarding flow (option 3)' (#12) from feat/login-methods into goutamnextflow 2026-07-12 22:06:03 +00:00
tanweer919 66cd8953ba Merge pull request 'feat(auth): gate Google sign-in on CRM profile' (#11) from feat/login-methods into goutamnextflow 2026-07-12 21:52:11 +00:00
tanweer919 11931cbf6f Merge pull request 'polish: real role in user chip' (#10) from feat/login-methods into goutamnextflow 2026-07-12 21:33:24 +00:00
tanweer919 43f9a3eb83 Merge pull request 'feat(dashboard): real user + sign-out; remove demo text' (#9) from feat/login-methods into goutamnextflow 2026-07-12 21:27:58 +00:00
tanweer919 f5ff7bf6ea Merge pull request 'fix(auth): session persists on reload (SDK 0.2.2)' (#8) from feat/login-methods into goutamnextflow 2026-07-12 21:11:46 +00:00
tanweer919 3e79b3bf31 Merge pull request 'fix(auth): session persists on reload (gate redirect on boot-ready)' (#7) from feat/login-methods into goutamnextflow 2026-07-12 21:05:20 +00:00
tanweer919 e08fa357f7 Merge pull request 'chore: remove debug logging' (#6) from feat/login-methods into goutamnextflow 2026-07-12 20:47:30 +00:00
tanweer919 e37ef375eb Merge pull request 'fix(auth): PKCE verifier (SDK 0.2.1) — Google sign-in' (#5) from feat/login-methods into goutamnextflow 2026-07-12 20:32:32 +00:00
tanweer919 66118ff63f Merge pull request 'fix(auth): surface OAuth error' (#4) from feat/login-methods into goutamnextflow 2026-07-12 20:15:17 +00:00
tanweer919 6d0c8890d3 Merge pull request 'fix(auth): complete Google OAuth after SDK boot' (#3) from feat/login-methods into goutamnextflow 2026-07-12 20:01:53 +00:00
tanweer919 e9ec33d412 Merge pull request 'feat(auth): Google-only social; email/password sign-up; phone login' (#2) from feat/login-methods into goutamnextflow 2026-07-11 15:19:06 +00:00
tanweer919 2a653b807b Merge pull request 'feat: AppShell integration — auth, email/SMS OTP login, live multi-role team management' (#1) from tanweer919/lynkeduppro-crm:feat/appshell-integration into goutamnextflow 2026-07-11 14:24:59 +00:00
6 changed files with 940 additions and 130 deletions
+1
View File
@@ -41,3 +41,4 @@ yarn-error.log*
next-env.d.ts next-env.d.ts
.vercel .vercel
.env*.local
+780 -20
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -9,7 +9,7 @@
"lint": "eslint" "lint": "eslint"
}, },
"dependencies": { "dependencies": {
"@abe-kap/appshell-sdk": "^0.2.3", "@abe-kap/appshell-sdk": "^0.2.6",
"clsx": "^2.1.1", "clsx": "^2.1.1",
"lucide-react": "^1.21.0", "lucide-react": "^1.21.0",
"next": "16.2.9", "next": "16.2.9",
+20 -4
View File
@@ -1,6 +1,6 @@
"use client"; "use client";
import { useEffect } from "react"; import { useEffect, useState } from "react";
import { useRouter } from "next/navigation"; import { useRouter } from "next/navigation";
import { useAuth, useAppShell } from "@abe-kap/appshell-sdk/react"; import { useAuth, useAppShell } from "@abe-kap/appshell-sdk/react";
import { PortalAside, PanelBrand } from "@/components/portal/parts"; import { PortalAside, PanelBrand } from "@/components/portal/parts";
@@ -10,18 +10,34 @@ import { isShellConfigured } from "@/lib/appshell";
/** /**
* Post-OAuth onboarding — a first-time Google user completes their CRM profile * Post-OAuth onboarding — a first-time Google user completes their CRM profile
* (everything except email, which Google already verified). Only reachable while * (everything except email, which Google already verified).
* authenticated; unauthenticated visitors are sent back to sign in. *
* This screen is ONLY a step in the OAuth → onboarding handoff: the login page
* stashes the verified email in `sessionStorage` right before routing here. Any
* other way in — a typed URL, a fresh tab, a lost session — has no handoff hint
* (and possibly no session), so we bounce back to sign in rather than showing an
* empty form.
*/ */
export default function OnboardingPage() { export default function OnboardingPage() {
const router = useRouter(); const router = useRouter();
const { status } = useAuth(); const { status } = useAuth();
const { ready } = useAppShell(); const { ready } = useAppShell();
const [allowed, setAllowed] = useState(false);
useEffect(() => { useEffect(() => {
if (isShellConfigured() && ready && status === "unauthenticated") router.replace("/portal/login"); if (!isShellConfigured()) { setAllowed(true); return; } // local dev without the Shell
if (!ready) return; // wait for session restore
let hasHandoff = false;
try { hasHandoff = !!sessionStorage.getItem("onboard_email"); } catch { /* ignore */ }
if (status === "unauthenticated" || !hasHandoff) {
router.replace("/portal/login");
return;
}
setAllowed(true);
}, [ready, status, router]); }, [ready, status, router]);
if (!allowed) return <main className="portal-main"><span className="portal-grid" /></main>;
return ( return (
<main className="portal-main"> <main className="portal-main">
<span className="portal-grid" /> <span className="portal-grid" />
+6 -3
View File
@@ -24,7 +24,7 @@ const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
export function LoginFlow() { export function LoginFlow() {
const router = useRouter(); const router = useRouter();
const { login, loginWithOAuth, completeOAuthLogin } = useAuth(); const { login, loginWithOAuth, completeOAuthLogin, getUserEmail } = useAuth();
const { ready, sdk } = useAppShell(); const { ready, sdk } = useAppShell();
const [step, setStep] = useState<Step>("identify"); const [step, setStep] = useState<Step>("identify");
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
@@ -86,13 +86,16 @@ export function LoginFlow() {
registered = !!st?.registered; registered = !!st?.registered;
} catch { registered = false; } } catch { registered = false; }
window.history.replaceState({}, "", "/portal/login"); window.history.replaceState({}, "", "/portal/login");
router.replace(registered ? "/dashboard" : "/portal/onboarding"); if (registered) { router.replace("/dashboard"); return; }
// Capture the verified email now (session is fresh) so onboarding prefills it.
try { const em = await getUserEmail(); if (em) sessionStorage.setItem("onboard_email", em); } catch { /* ignore */ }
router.replace("/portal/onboarding");
}) })
.catch(() => { .catch(() => {
setFlash("Google sign-in didn't complete. Please try again."); setFlash("Google sign-in didn't complete. Please try again.");
replace("identify"); replace("identify");
}); });
}, [ready, completeOAuthLogin, router, sdk]); }, [ready, completeOAuthLogin, router, sdk, getUserEmail]);
/* ---- auth resolution ---- */ /* ---- auth resolution ---- */
function afterAuth(factor: "password" | "passkey" | "otp" | "totp" | "push" | "social") { function afterAuth(factor: "password" | "passkey" | "otp" | "totp" | "push" | "social") {
+132 -102
View File
@@ -25,10 +25,14 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
// we only SET a password + persist the profile, and the OTP-verify step is skipped. // we only SET a password + persist the profile, and the OTP-verify step is skipped.
const onboard = mode === "onboard"; const onboard = mode === "onboard";
const router = useRouter(); const router = useRouter();
const { register, setPassword, getUserEmail } = useAuth(); const { register, setPassword, getUserEmail, addPhone, verifyPhone } = useAuth();
const { sdk } = useAppShell(); const { sdk } = useAppShell();
const [step, setStep] = useState(0); const [step, setStep] = useState(0);
const [submitErr, setSubmitErr] = useState(""); const [submitErr, setSubmitErr] = useState("");
// Verifying a phone via Supabase needs a live session. Onboarding already has one
// (Google OAuth); registration creates the account when leaving the Account step,
// then attaches + verifies the phone on it. `creating` guards the Account button.
const [creating, setCreating] = useState(false);
// address (lifted from StepAddress/AddressBlock so finish() can persist it) // address (lifted from StepAddress/AddressBlock so finish() can persist it)
const [regAddr, setRegAddr] = useState<Addr>({}); const [regAddr, setRegAddr] = useState<Addr>({});
@@ -50,18 +54,19 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
const [termsOk, setTermsOk] = useState(false); const [termsOk, setTermsOk] = useState(false);
const [privacyOk, setPrivacyOk] = useState(false); const [privacyOk, setPrivacyOk] = useState(false);
// verify step // verify step (email is trusted without an OTP — see verifyValid below)
const [emailVerified, setEmailVerified] = useState(false);
const [phoneVerified, setPhoneVerified] = useState(false); const [phoneVerified, setPhoneVerified] = useState(false);
// Onboarding: prefill the verified email from the Google session (the ACE omits it). // Onboarding: prefill the verified email from the session-storage hint the login
// page stashed at OAuth time, then confirmed via the live Supabase session.
useEffect(() => { useEffect(() => {
if (!onboard) return; if (!onboard) return;
try { const cached = sessionStorage.getItem("onboard_email"); if (cached) setEmail(cached); } catch { /* ignore */ }
getUserEmail().then((e) => { if (e) setEmail(e); }).catch(() => { /* ignore */ }); getUserEmail().then((e) => { if (e) setEmail(e); }).catch(() => { /* ignore */ });
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, [onboard]); }, [onboard]);
const STEP_LABELS = onboard ? ["Profile", "Address"] : STEPS; const STEP_LABELS = onboard ? ["Profile", "Verify", "Address"] : STEPS;
const isSelf = relationship === "Customer" || relationship === "Owner"; const isSelf = relationship === "Customer" || relationship === "Owner";
const isEmployee = relationship === "Employee"; const isEmployee = relationship === "Employee";
@@ -74,7 +79,26 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
first.trim() && last.trim() && EMAIL_RE.test(sso?.email || email) && phoneOk && pwOk && first.trim() && last.trim() && EMAIL_RE.test(sso?.email || email) && phoneOk && pwOk &&
termsOk && privacyOk && (isSelf || (alloeIdOk && (isEmployee || (alloeFirst.trim() && alloeLast.trim())))); termsOk && privacyOk && (isSelf || (alloeIdOk && (isEmployee || (alloeFirst.trim() && alloeLast.trim()))));
const step2Valid = emailVerified && phoneVerified; // Email is already trusted in both flows (registration: Supabase auto-confirms on
// signup; onboarding: Google-verified), so the Verify step only gates on the phone.
const verifyValid = phoneVerified;
// Registration: create the auth account when leaving the Account step, so the phone
// can be attached + verified against a live session at the Verify step. Onboarding
// is already authenticated, so it just advances.
async function leaveAccountStep() {
if (onboard || !isShellConfigured() || sso) { setStep(1); return; }
setSubmitErr("");
setCreating(true);
try {
await register(email, pw);
setStep(1);
} catch {
setSubmitErr("We couldn't create that account. The email may already be registered.");
} finally {
setCreating(false);
}
}
async function finish() { async function finish() {
const finalEmail = sso?.email || email; const finalEmail = sso?.email || email;
@@ -89,13 +113,12 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
if (isShellConfigured()) { if (isShellConfigured()) {
setSubmitErr(""); setSubmitErr("");
// 1) Auth account. Onboarding users are already authenticated via Google — set // 1) Auth account already exists at this point — registration created it when
// a password so email+password login works too. Everyone else registers now. // leaving the Account step; onboarding users signed in via Google. Onboarding
if (onboard) { // additionally sets a password so email+password login works too (the phone was
try { if (pw) await setPassword(pw); } catch { /* non-fatal — the profile still saves */ } // just verified against the same live session).
} else if (!sso) { if (onboard && pw) {
try { await register(finalEmail, pw); } try { await setPassword(pw); } catch { /* non-fatal — the profile still saves */ }
catch { setSubmitErr("We couldn't create that account. The email may already be registered."); return; }
} }
// 2) Persist the full CRM registration payload to be-crm (name, phone, persona, // 2) Persist the full CRM registration payload to be-crm (name, phone, persona,
// allottee, both addresses, consent). Non-fatal: the auth account exists either way. // allottee, both addresses, consent). Non-fatal: the auth account exists either way.
@@ -118,6 +141,8 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
// register mode: non-fatal — the auth account exists; the profile can be filled in later. // register mode: non-fatal — the auth account exists; the profile can be filled in later.
} }
} }
// Consume the OAuth→onboarding handoff so a stale hint can't re-open onboarding.
try { sessionStorage.removeItem("onboard_email"); } catch { /* ignore */ }
router.push("/dashboard"); router.push("/dashboard");
} }
@@ -126,34 +151,36 @@ export function RegisterFlow({ mode = "register" }: { mode?: "register" | "onboa
<Stepper current={step} labels={STEP_LABELS} /> <Stepper current={step} labels={STEP_LABELS} />
{step === 0 && ( {step === 0 && (
<StepAccount
onboard={onboard}
sso={sso} setSso={setSso} email={email} setEmail={setEmail}
first={first} setFirst={setFirst} last={last} setLast={setLast}
cc={cc} setCc={setCc} phone={phone} setPhone={setPhone} phoneOk={phoneOk} country={country}
pw={pw} setPw={setPw}
relationship={relationship} setRelationship={setRelationship} isSelf={isSelf}
alloeNo={alloeNo} setAlloeNo={setAlloeNo} alloeIdOk={alloeIdOk}
alloeFirst={alloeFirst} setAlloeFirst={setAlloeFirst} alloeLast={alloeLast} setAlloeLast={setAlloeLast}
termsOk={termsOk} setTermsOk={setTermsOk} privacyOk={privacyOk} setPrivacyOk={setPrivacyOk}
valid={!!step0Valid}
onContinue={() => setStep(1)} toLogin={() => router.push("/portal/login")}
/>
)}
{step === 1 && !onboard && (
<StepVerify
emailValue={sso?.email || email} cc={cc} phone={phone} country={country}
emailVerified={emailVerified} setEmailVerified={setEmailVerified}
phoneVerified={phoneVerified} setPhoneVerified={setPhoneVerified}
valid={step2Valid} onBack={() => setStep(0)} onContinue={() => setStep(2)}
/>
)}
{((onboard && step === 1) || (!onboard && step === 2)) && (
<> <>
{submitErr && <div style={{ marginBottom: 14 }}><FlashNote tone="error">{submitErr}</FlashNote></div>} {submitErr && <div style={{ marginBottom: 14 }}><FlashNote tone="error">{submitErr}</FlashNote></div>}
<StepAddress sameAs={mailingSame} setSameAs={setMailingSame} onRegAddr={setRegAddr} onMailAddr={setMailAddr} onBack={() => setStep(onboard ? 0 : 1)} onFinish={finish} /> <StepAccount
onboard={onboard} creating={creating}
sso={sso} setSso={setSso} email={email} setEmail={setEmail}
first={first} setFirst={setFirst} last={last} setLast={setLast}
cc={cc} setCc={setCc} phone={phone} setPhone={setPhone} phoneOk={phoneOk} country={country}
pw={pw} setPw={setPw}
relationship={relationship} setRelationship={setRelationship} isSelf={isSelf}
alloeNo={alloeNo} setAlloeNo={setAlloeNo} alloeIdOk={alloeIdOk}
alloeFirst={alloeFirst} setAlloeFirst={setAlloeFirst} alloeLast={alloeLast} setAlloeLast={setAlloeLast}
termsOk={termsOk} setTermsOk={setTermsOk} privacyOk={privacyOk} setPrivacyOk={setPrivacyOk}
valid={!!step0Valid}
onContinue={leaveAccountStep} toLogin={() => router.push("/portal/login")}
/>
</>
)}
{step === 1 && (
<StepVerify
cc={cc} phone={phone} country={country}
phoneVerified={phoneVerified} setPhoneVerified={setPhoneVerified}
valid={verifyValid} onBack={() => setStep(0)} onContinue={() => setStep(2)}
/>
)}
{step === 2 && (
<>
{submitErr && <div style={{ marginBottom: 14 }}><FlashNote tone="error">{submitErr}</FlashNote></div>}
<StepAddress sameAs={mailingSame} setSameAs={setMailingSame} onRegAddr={setRegAddr} onMailAddr={setMailAddr} onBack={() => setStep(1)} onFinish={finish} />
</> </>
)} )}
</div> </div>
@@ -171,7 +198,7 @@ function StepAccount(p: {
alloeNo: string; setAlloeNo: (v: string) => void; alloeIdOk: boolean; alloeNo: string; setAlloeNo: (v: string) => void; alloeIdOk: boolean;
alloeFirst: string; setAlloeFirst: (v: string) => void; alloeLast: string; setAlloeLast: (v: string) => void; alloeFirst: string; setAlloeFirst: (v: string) => void; alloeLast: string; setAlloeLast: (v: string) => void;
termsOk: boolean; setTermsOk: (v: boolean) => void; privacyOk: boolean; setPrivacyOk: (v: boolean) => void; termsOk: boolean; setTermsOk: (v: boolean) => void; privacyOk: boolean; setPrivacyOk: (v: boolean) => void;
valid: boolean; onContinue: () => void; toLogin: () => void; onboard?: boolean; valid: boolean; onContinue: () => void; toLogin: () => void; onboard?: boolean; creating?: boolean;
}) { }) {
// Onboarding (OAuth) starts on the profile step — email is already known + verified. // Onboarding (OAuth) starts on the profile step — email is already known + verified.
const [phase, setPhase] = useState<"sso" | "profile">(p.onboard ? "profile" : "sso"); const [phase, setPhase] = useState<"sso" | "profile">(p.onboard ? "profile" : "sso");
@@ -205,12 +232,13 @@ function StepAccount(p: {
<h1>Complete your profile</h1> <h1>Complete your profile</h1>
<p className="sub">Tell us a bit about you to set up your account.</p> <p className="sub">Tell us a bit about you to set up your account.</p>
<div style={{ marginTop: 16 }}> <div className="field" style={{ marginTop: 16 }}>
{p.sso ? ( <label className="label">Email address</label>
<div className="conn-banner conn-green"><Icon name="check" size={16} /> Connected with {cap(p.sso.provider)} · {p.sso.email}</div> <div className="input-wrap">
) : ( <span className="input-ico"><Icon name="mail" size={17} /></span>
<div className="conn-banner conn-blue"><Icon name="mail" size={16} /> {p.onboard ? "Signed in as" : "Creating account for"} {p.email}</div> <input className="input" type="email" value={p.email} disabled readOnly aria-label="Email address" />
)} </div>
<span className="faint" style={{ fontSize: 12 }}>{p.onboard ? "Verified with Google — this can't be changed." : "The email you're registering with."}</span>
</div> </div>
<div className="row gap-3" style={{ marginTop: 18, alignItems: "center" }}> <div className="row gap-3" style={{ marginTop: 18, alignItems: "center" }}>
@@ -308,7 +336,9 @@ function StepAccount(p: {
{!p.valid && <p className="hint-line">Fill all required fields and accept both documents to continue.</p>} {!p.valid && <p className="hint-line">Fill all required fields and accept both documents to continue.</p>}
<button className="btn btn-primary" style={{ marginTop: 14 }} disabled={!p.valid} onClick={p.onContinue}>{p.onboard ? "Continue" : "Create Account & Verify"} <Icon name="arrowR" size={16} /></button> <button className="btn btn-primary" style={{ marginTop: 14 }} disabled={!p.valid || p.creating} onClick={p.onContinue}>
{p.creating ? "Creating account…" : p.onboard ? "Continue" : "Create Account & Verify"} {!p.creating && <Icon name="arrowR" size={16} />}
</button>
{modal === "terms" && <LegalModal doc={TERMS} onClose={() => setModal(null)} onReviewed={() => { reviewed.terms = true; setModal(null); }} />} {modal === "terms" && <LegalModal doc={TERMS} onClose={() => setModal(null)} onReviewed={() => { reviewed.terms = true; setModal(null); }} />}
{modal === "privacy" && <LegalModal doc={PRIVACY} onClose={() => setModal(null)} onReviewed={() => { reviewed.privacy = true; setModal(null); }} />} {modal === "privacy" && <LegalModal doc={PRIVACY} onClose={() => setModal(null)} onReviewed={() => { reviewed.privacy = true; setModal(null); }} />}
@@ -318,10 +348,13 @@ function StepAccount(p: {
// module-level reviewed flags (per mount lifetime) — enables the checkboxes after a doc is read // module-level reviewed flags (per mount lifetime) — enables the checkboxes after a doc is read
const reviewed = { terms: false, privacy: false }; const reviewed = { terms: false, privacy: false };
/* ====================== STEP 1 — VERIFY ====================== */ /* ====================== STEP 1 — VERIFY PHONE ======================
Email is already trusted (registration: Supabase auto-confirms on signup;
onboarding: Google-verified), so this step only verifies the phone via a real
SMS OTP: addPhone() → Twilio texts a code → verifyPhone() confirms it. Both
run against the live Supabase session established in the previous step. */
function StepVerify(p: { function StepVerify(p: {
emailValue: string; cc: string; phone: string; country: typeof countryCodes[number]; cc: string; phone: string; country: typeof countryCodes[number];
emailVerified: boolean; setEmailVerified: (v: boolean) => void;
phoneVerified: boolean; setPhoneVerified: (v: boolean) => void; phoneVerified: boolean; setPhoneVerified: (v: boolean) => void;
valid: boolean; onBack: () => void; onContinue: () => void; valid: boolean; onBack: () => void; onContinue: () => void;
}) { }) {
@@ -329,12 +362,11 @@ function StepVerify(p: {
return ( return (
<div> <div>
<StepBack onClick={p.onBack} /> <StepBack onClick={p.onBack} />
<h1>Verify email &amp; phone</h1> <h1>Verify your phone</h1>
<p className="sub">Confirm both so we can secure your account.</p> <p className="sub">We&apos;ll text a one-time code to confirm your number. Your email is already verified.</p>
<div className="col gap-4" style={{ marginTop: 16 }}> <div className="col gap-4" style={{ marginTop: 16 }}>
<VerifyChannel kind="email" initial={p.emailValue} country={p.country} cc={p.cc} initialPhone={p.phone} verified={p.emailVerified} onVerified={() => p.setEmailVerified(true)} /> <PhoneVerify cc={p.cc} country={p.country} initialPhone={p.phone} verified={p.phoneVerified} onVerified={() => p.setPhoneVerified(true)} />
<VerifyChannel kind="phone" initial={p.emailValue} country={p.country} cc={p.cc} initialPhone={p.phone} verified={p.phoneVerified} onVerified={() => p.setPhoneVerified(true)} />
</div> </div>
<div style={{ marginTop: 14 }}><RememberDevice checked={remember} onChange={setRemember} /></div> <div style={{ marginTop: 14 }}><RememberDevice checked={remember} onChange={setRemember} /></div>
@@ -343,40 +375,47 @@ function StepVerify(p: {
); );
} }
type SendState = "idle" | "sending" | "ok" | "invalid_email" | "mailbox_full" | "bounce_risk" | "invalid_mobile"; type SendState = "idle" | "sending" | "sent" | "invalid_mobile" | "send_error";
function VerifyChannel({ kind, initial, country, cc, initialPhone, verified, onVerified }: { function PhoneVerify({ cc, country, initialPhone, verified, onVerified }: {
kind: "email" | "phone"; initial: string; country: typeof countryCodes[number]; cc: string; initialPhone: string; cc: string; country: typeof countryCodes[number]; initialPhone: string;
verified: boolean; onVerified: () => void; verified: boolean; onVerified: () => void;
}) { }) {
const [value, setValue] = useState(kind === "email" ? initial : initialPhone); const { addPhone, verifyPhone } = useAuth();
const [via, setVia] = useState<"primary" | "wa">("primary"); const [value, setValue] = useState(initialPhone);
const [state, setState] = useState<SendState>("idle"); const [state, setState] = useState<SendState>("idle");
const [otpError, setOtpError] = useState(false); const [otpError, setOtpError] = useState("");
const primaryLabel = kind === "email" ? "Email" : "SMS"; const e164 = `${cc}${value.replace(/\D/g, "")}`;
function send() { async function send() {
if (value.replace(/\D/g, "").length !== country.digits) { setState("invalid_mobile"); return; }
setState("sending"); setState("sending");
setTimeout(() => { setOtpError("");
if (kind === "email") { try {
if (!EMAIL_RE.test(value)) return setState("invalid_email"); await addPhone(e164); // Supabase → Twilio sends the SMS OTP
if (value.includes("full")) return setState("mailbox_full"); setState("sent");
if (value.includes("bo")) return setState("bounce_risk"); } catch {
return setState("ok"); setState("send_error");
} else { }
if (value.replace(/\D/g, "").length !== country.digits) return setState("invalid_mobile"); }
return setState("ok");
} async function submit(code: string) {
}, 700); setOtpError("");
try {
await verifyPhone(e164, code); // confirm the OTP (phone_change)
onVerified();
} catch {
setOtpError("That code didn't match. Check the SMS and try again.");
}
} }
if (verified) { if (verified) {
return ( return (
<div className="vchannel verified"> <div className="vchannel verified">
<div className="row between"> <div className="row between">
<span className="row gap-2" style={{ fontWeight: 600, fontSize: 14 }}><Icon name={kind === "email" ? "mail" : "phone"} size={16} /> {kind === "email" ? "Email" : "Mobile"}</span> <span className="row gap-2" style={{ fontWeight: 600, fontSize: 14 }}><Icon name="phone" size={16} /> Mobile</span>
<Badge tone="green"><Icon name="check" size={12} /> Verified</Badge> <Badge tone="green"><Icon name="check" size={12} /> Verified</Badge>
</div> </div>
<p className="faint" style={{ fontSize: 12.5, marginTop: 8 }}>{kind === "email" ? value : `${cc} ${value}`}</p> <p className="faint" style={{ fontSize: 12.5, marginTop: 8 }}>{cc} {value}</p>
</div> </div>
); );
} }
@@ -384,43 +423,34 @@ function VerifyChannel({ kind, initial, country, cc, initialPhone, verified, onV
return ( return (
<div className="vchannel"> <div className="vchannel">
<div className="row between" style={{ marginBottom: 12 }}> <div className="row between" style={{ marginBottom: 12 }}>
<span className="row gap-2" style={{ fontWeight: 600, fontSize: 14 }}><Icon name={kind === "email" ? "mail" : "phone"} size={16} /> {kind === "email" ? "Email address" : "Mobile number"}</span> <span className="row gap-2" style={{ fontWeight: 600, fontSize: 14 }}><Icon name="phone" size={16} /> Mobile number</span>
</div> </div>
{kind === "email" ? ( <div className="phone-row">
<input className="input" value={value} onChange={(e) => { setValue(e.target.value); setState("idle"); }} placeholder="you@example.com" /> <span className="input cc-select" style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 7 }}>
) : ( {/* eslint-disable-next-line @next/next/no-img-element */}
<div className="phone-row"> <img className="cc-flag-img static" src={flagUrl(country.flag)} alt={country.name} width={22} height={16} />
<span className="input cc-select" style={{ display: "flex", alignItems: "center", justifyContent: "center", gap: 7 }}> {cc}
{/* eslint-disable-next-line @next/next/no-img-element */} </span>
<img className="cc-flag-img static" src={flagUrl(country.flag)} alt={country.name} width={22} height={16} /> <input className="input grow" inputMode="numeric" value={value} disabled={state === "sent"} onChange={(e) => { setValue(e.target.value.replace(/\D/g, "")); setState("idle"); }} placeholder={country.example} />
{cc} </div>
</span>
<input className="input grow" inputMode="numeric" value={value} onChange={(e) => { setValue(e.target.value.replace(/\D/g, "")); setState("idle"); }} placeholder={country.example} />
</div>
)}
<div className="row between" style={{ marginTop: 12 }}> <div className="row between" style={{ marginTop: 12 }}>
<div className="seg"> <span className="faint" style={{ fontSize: 12 }}>Standard SMS rates may apply.</span>
<button className={via === "primary" ? "on" : ""} onClick={() => setVia("primary")}>{primaryLabel}</button> <button className="btn btn-sm" style={{ width: "auto" }} disabled={state === "sending" || state === "sent"} onClick={send}>
<button className={via === "wa" ? "on" : ""} onClick={() => setVia("wa")}><Icon name="whatsapp" size={14} /> WhatsApp</button> {state === "sending" ? "Sending…" : state === "sent" ? "Sent" : "Send code"}
</div>
<button className="btn btn-sm" style={{ width: "auto" }} disabled={state === "sending" || state === "ok"} onClick={send}>
{state === "sending" ? "Sending…" : "Send code"}
</button> </button>
</div> </div>
{state === "ok" && <p className="faint" style={{ fontSize: 12, marginTop: 10 }}>OTP sent via {via === "wa" ? "WhatsApp" : primaryLabel}.</p>} {state === "sent" && <p className="faint" style={{ fontSize: 12, marginTop: 10 }}>Code sent to {cc} {value} by SMS.</p>}
{state === "invalid_email" && <div style={{ marginTop: 10 }}><FlashNote tone="error">That email address looks invalid.</FlashNote></div>}
{state === "mailbox_full" && <div style={{ marginTop: 10 }}><FlashNote tone="warn">This mailbox appears full try another email.</FlashNote></div>}
{state === "bounce_risk" && <div style={{ marginTop: 10 }}><FlashNote tone="warn">High bounce risk for this address.</FlashNote></div>}
{state === "invalid_mobile" && <div style={{ marginTop: 10 }}><FlashNote tone="error">Enter a valid {country.digits}-digit mobile number.</FlashNote></div>} {state === "invalid_mobile" && <div style={{ marginTop: 10 }}><FlashNote tone="error">Enter a valid {country.digits}-digit mobile number.</FlashNote></div>}
{state === "send_error" && <div style={{ marginTop: 10 }}><FlashNote tone="error">Couldn&apos;t send the code. Check the number and try again.</FlashNote></div>}
{state === "ok" && ( {state === "sent" && (
<div style={{ marginTop: 14 }}> <div style={{ marginTop: 14 }}>
<OtpBoxes onComplete={(c) => { if (c === "000000") setOtpError(true); else { setOtpError(false); onVerified(); } }} error={otpError} /> <OtpBoxes onComplete={submit} error={!!otpError} />
{otpError && <div style={{ marginTop: 10 }}><FlashNote tone="error">Incorrect code.</FlashNote></div>} {otpError && <div style={{ marginTop: 10 }}><FlashNote tone="error">{otpError}</FlashNote></div>}
<div style={{ marginTop: 12 }}><ResendLink seconds={60} /></div> <div style={{ marginTop: 12 }}><ResendLink seconds={60} onResend={send} /></div>
</div> </div>
)} )}
</div> </div>