oneie 2.0.3 → 2.0.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CLAUDE.md +220 -29
  2. package/LICENSE.md +84 -0
  3. package/README.md +489 -931
  4. package/folders.yaml +78 -17
  5. package/one/.obsidian/workspace.json +6 -6
  6. package/one/events/CASCADE-2-BACKEND-AGNOSTIC.md +412 -0
  7. package/one/events/FEATURE-2-4-COMPLETE.md +302 -0
  8. package/one/events/FEATURE_2_3_COMPLETE.md +575 -0
  9. package/one/events/GROUPS-MIGRATION.md +625 -0
  10. package/one/events/INSTALL-TESTS.md +293 -0
  11. package/one/events/INTEGRATION-ARCHITECTURE.md +561 -0
  12. package/one/events/INTEGRATION-CHECKLIST.md +1234 -0
  13. package/one/events/INTEGRATION-ORCHESTRATION.md +2623 -0
  14. package/one/events/INTEGRATION-SUMMARY.md +653 -0
  15. package/one/events/MIGRATION-REPORT.md +435 -0
  16. package/one/events/MIGRATION.md +69 -0
  17. package/one/events/README-archived.md +519 -0
  18. package/one/events/TEST-SUMMARY.md +393 -0
  19. package/one/events/TESTS-QUICK-REF.md +262 -0
  20. package/one/groups/groups.md +543 -0
  21. package/one/knowledge/CLOUDFLARE_ENV_SETUP.md +49 -0
  22. package/one/knowledge/architecture-any-backend.md +1366 -0
  23. package/one/knowledge/docs/flow.md +0 -0
  24. package/one/knowledge/ontology-documentation.md +18 -18
  25. package/one/knowledge/ontology.md +154 -143
  26. package/one/knowledge/ontology.md.backup +2822 -0
  27. package/one/knowledge/ontology.yaml +87 -87
  28. package/one/knowledge/provider-creation-guide.md +1064 -0
  29. package/one/knowledge/todo.md +251 -0
  30. package/one/license.md +84 -0
  31. package/one/things/CHECKLIST.md +356 -0
  32. package/one/things/ONE.md +510 -0
  33. package/one/things/{cli.md → cli/cli.md} +27 -4
  34. package/one/things/features/2-1-dataprovider-interface.md +2358 -0
  35. package/one/things/features/2-2-config-system.md +3075 -0
  36. package/one/things/features/2-3-effectts-services.md +1498 -0
  37. package/one/things/features/2-4-react-hooks.md +2120 -0
  38. package/one/things/features/2-5-auth-migration.md +2046 -0
  39. package/one/things/features/2-6-dashboard-migration.md +1985 -0
  40. package/one/things/features/2-7-alternative-providers.md +2505 -0
  41. package/one/things/features/2-7-implementation-report.md +680 -0
  42. package/one/things/features/2-cli.md +39 -39
  43. package/one/things/features/2-design.md +1738 -0
  44. package/one/things/features/2-tests.md +520 -0
  45. package/one/things/features/AUTH_HOOKS_IMPLEMENTATION.md +521 -0
  46. package/one/things/features/DECOUPLING.md +272 -0
  47. package/one/things/features/DEPLOYMENT.md +452 -0
  48. package/one/things/features/IMPLEMENTATION_SUMMARY.md +316 -0
  49. package/one/things/features/dataprovider-interface/1-tests.md +1522 -0
  50. package/one/things/features/improve.md +843 -0
  51. package/one/things/features/remove-convex-deps.md +45 -0
  52. package/one/things/features/top-features.md +79 -0
  53. package/one/things/ideas/2-backend-agnostic-frontend.md +384 -0
  54. package/one/things/plans/2-backend-agnostic-frontend.md +543 -0
  55. package/one/things/plans/3-groups.md +502 -0
  56. package/one/things/plans/backend-agnostic-frontend.md +323 -0
  57. package/one/things/plans/deploy-to-cloudflare.md +581 -0
  58. package/one/things/plans/organizations-to-groups.md +705 -0
  59. package/one/things/plans/release.md +432 -0
  60. package/one/things/products/ontology.md +1 -1
  61. package/one/things/system.md +600 -0
  62. package/one/things/tests/2-1-dataprovider-interface.md +1144 -0
  63. package/one/things/tests/2-1-test-analysis.md +496 -0
  64. package/one/things/vision/elegant-interface.md +214 -0
  65. package/package.json +1 -1
  66. package/one/organisation/organisation.md +0 -438
  67. package/one/repomix-output.md +0 -92634
  68. /package/one/{things → connections}/agentkit.md +0 -0
  69. /package/one/{things → connections}/copilotkit.md +0 -0
  70. /package/one/{organisation → groups}/one.md +0 -0
  71. /package/one/{organisation → groups}/revenue.md +0 -0
  72. /package/one/{organisation → groups}/strategy.md +0 -0
  73. /package/one/{organisation → groups}/vision.md +0 -0
  74. /package/one/things/{cli-code.md → cli/cli-code.md} +0 -0
  75. /package/one/things/{cli-compiler-code.md → cli/cli-compiler-code.md} +0 -0
@@ -0,0 +1,2046 @@
1
+ # Feature 2-5: Auth Component Migration to DataProvider
2
+
3
+ **Feature ID:** `feature_2_5_auth_migration`
4
+ **Plan:** `plan_2_backend_agnostic_frontend`
5
+ **Owner:** Frontend Specialist
6
+ **Status:** ✅ **COMPLETE SPECIFICATION** - Ready for Implementation
7
+ **Priority:** **P0 (CRITICAL)** - All 50+ auth tests MUST pass
8
+ **Effort:** 1 week (5-8 days)
9
+ **Risk Level:** **HIGHEST** - Authentication is critical infrastructure
10
+ **Dependencies:** Feature 2-1 (DataProvider), Feature 2-4 (React Hooks)
11
+
12
+ ---
13
+
14
+ ## Executive Summary
15
+
16
+ This feature migrates **6 critical authentication components** from direct Better Auth + Convex integration to backend-agnostic DataProvider hooks. This is the **HIGHEST RISK** feature in Plan 2 because:
17
+
18
+ 1. Authentication affects 100% of users
19
+ 2. 50+ existing tests MUST continue passing
20
+ 3. Security cannot be compromised
21
+ 4. Session management must work identically
22
+ 5. Zero downtime deployment required
23
+
24
+ **Success Criteria:** All 50+ auth tests pass with ZERO functionality regression.
25
+
26
+ **Migration Strategy:** Incremental component-by-component with test validation after EACH component (<5 tests fail = immediate rollback).
27
+
28
+ ---
29
+
30
+ ## 1. Components to Migrate (6 Total)
31
+
32
+ ### Component Matrix
33
+
34
+ | # | Component | Current API | New Hook | Lines | Risk | Test File |
35
+ |---|-----------|-------------|----------|-------|------|-----------|
36
+ | 1 | **SimpleSignInForm** | `authClient.signIn.email()` | `useLogin()` | 163 | **HIGH** | `email-password.test.ts` |
37
+ | 2 | **SimpleSignUpForm** | `authClient.signUp.email()` | `useSignup()` | 157 | **HIGH** | `email-password.test.ts` |
38
+ | 3 | **MagicLinkAuth** | `convex.mutation(api.auth.signInWithMagicLink)` | `useMagicLinkAuth()` | 151 | **MEDIUM** | `magic-link.test.ts` |
39
+ | 4 | **TwoFactorSettings** | Multiple `convex.mutation(api.auth.*)` | `use2FA()` | 293 | **HIGH** | `auth.test.ts` |
40
+ | 5 | **VerifyEmailForm** | `convex.mutation(api.auth.verifyEmail)` | `useVerifyEmail()` | 134 | **LOW** | `auth.test.ts` |
41
+ | 6 | **ForgotPasswordForm** | `fetch("/api/auth/forgot-password")` | `usePasswordReset()` | 144 | **MEDIUM** | `password-reset.test.ts` |
42
+ | 7 | **ResetPasswordForm** | `fetch("/api/auth/reset-password")` | `usePasswordResetComplete()` | 206 | **MEDIUM** | `password-reset.test.ts` |
43
+
44
+ **Total:** 1,248 lines of code to migrate
45
+ **Estimated Effort:** 8-12 hours of careful migration + testing
46
+
47
+ ---
48
+
49
+ ## 2. Complete BEFORE/AFTER Code
50
+
51
+ ### 2.1 SimpleSignInForm Migration
52
+
53
+ **BEFORE (Current - 163 lines):**
54
+
55
+ ```typescript
56
+ // frontend/src/components/auth/SimpleSignInForm.tsx (BEFORE)
57
+ import { useState } from "react"
58
+ import { Button } from "@/components/ui/button"
59
+ import { Input } from "@/components/ui/input"
60
+ import { Label } from "@/components/ui/label"
61
+ import { authClient } from "@/lib/auth-client" // ❌ REMOVE
62
+ import { toast } from "sonner"
63
+ import { AuthCard } from "./AuthCard"
64
+ import { SocialLoginButtons } from "./SocialLoginButtons"
65
+
66
+ export function SimpleSignInForm() {
67
+ const [email, setEmail] = useState("")
68
+ const [password, setPassword] = useState("")
69
+ const [loading, setLoading] = useState(false) // ❌ Manual state management
70
+
71
+ const handleSubmit = async (e: React.FormEvent) => {
72
+ e.preventDefault()
73
+ setLoading(true) // ❌ Manual loading state
74
+
75
+ try {
76
+ // ❌ Direct authClient call
77
+ const result = await authClient.signIn.email({
78
+ email,
79
+ password,
80
+ })
81
+
82
+ if (result.error) {
83
+ const errorMessage = result.error.message || "Unable to sign in"
84
+ let title = "Unable to sign in"
85
+ let description = `Error: ${errorMessage}. Please check your credentials and try again.`
86
+
87
+ // ❌ String-based error handling (brittle)
88
+ if (errorMessage.toLowerCase().includes("not found") || errorMessage.toLowerCase().includes("no user")) {
89
+ title = "Account not found"
90
+ description = "No account exists with this email. Please sign up first."
91
+ } else if (errorMessage.toLowerCase().includes("password") || errorMessage.toLowerCase().includes("incorrect")) {
92
+ title = "Incorrect password"
93
+ description = "The password you entered is incorrect."
94
+ }
95
+ // ... more string-based error checks
96
+
97
+ toast.error(title, { description })
98
+ setLoading(false) // ❌ Manual state reset
99
+ return
100
+ }
101
+
102
+ toast.success("Welcome back!", {
103
+ description: "Successfully signed in. Redirecting to your dashboard..."
104
+ })
105
+
106
+ setTimeout(() => {
107
+ window.location.href = "/account"
108
+ }, 1000)
109
+ } catch (err: any) {
110
+ // ❌ Generic error handling
111
+ toast.error("Sign in error", {
112
+ description: `Error: ${err.message}. Please try again later.`
113
+ })
114
+ setLoading(false) // ❌ Manual state reset
115
+ }
116
+ }
117
+
118
+ return (
119
+ <AuthCard title="Welcome Back" description="Sign in to your account">
120
+ <form onSubmit={handleSubmit} className="space-y-4">
121
+ <div className="space-y-2">
122
+ <Label htmlFor="email">Email</Label>
123
+ <Input
124
+ id="email"
125
+ type="email"
126
+ placeholder="your@email.com"
127
+ value={email}
128
+ onChange={(e) => setEmail(e.target.value)}
129
+ required
130
+ />
131
+ </div>
132
+
133
+ <div className="space-y-2">
134
+ <div className="flex items-center justify-between">
135
+ <Label htmlFor="password">Password</Label>
136
+ <a href="/account/forgot-password" className="text-xs text-primary hover:underline">
137
+ Forgot password?
138
+ </a>
139
+ </div>
140
+ <Input
141
+ id="password"
142
+ type="password"
143
+ placeholder="••••••••"
144
+ value={password}
145
+ onChange={(e) => setPassword(e.target.value)}
146
+ required
147
+ />
148
+ </div>
149
+
150
+ <Button type="submit" className="w-full" disabled={loading}>
151
+ {loading ? "Signing in..." : "Sign In"}
152
+ </Button>
153
+
154
+ <div className="relative my-4">
155
+ <div className="absolute inset-0 flex items-center">
156
+ <span className="w-full border-t" />
157
+ </div>
158
+ <div className="relative flex justify-center text-xs uppercase">
159
+ <span className="bg-background px-2 text-muted-foreground">Or</span>
160
+ </div>
161
+ </div>
162
+
163
+ <Button variant="outline" className="w-full" asChild>
164
+ <a href="/account/magic-link">Sign in with magic link</a>
165
+ </Button>
166
+ </form>
167
+ </AuthCard>
168
+ )
169
+ }
170
+ ```
171
+
172
+ **AFTER (Migrated - 120 lines, cleaner):**
173
+
174
+ ```typescript
175
+ // frontend/src/components/auth/SimpleSignInForm.tsx (AFTER)
176
+ import { useState } from "react"
177
+ import { Button } from "@/components/ui/button"
178
+ import { Input } from "@/components/ui/input"
179
+ import { Label } from "@/components/ui/label"
180
+ import { useLogin } from "@/providers/hooks" // ✅ DataProvider hook
181
+ import { toast } from "sonner"
182
+ import { AuthCard } from "./AuthCard"
183
+ import { SocialLoginButtons } from "./SocialLoginButtons"
184
+
185
+ export function SimpleSignInForm() {
186
+ const [email, setEmail] = useState("")
187
+ const [password, setPassword] = useState("")
188
+ const { mutate: login, loading, error } = useLogin() // ✅ Hook manages state
189
+
190
+ const handleSubmit = async (e: React.FormEvent) => {
191
+ e.preventDefault()
192
+
193
+ try {
194
+ const result = await login({ email, password }) // ✅ Simple hook call
195
+
196
+ if (result.success) {
197
+ toast.success("Welcome back!", {
198
+ description: "Successfully signed in. Redirecting to your dashboard..."
199
+ })
200
+
201
+ setTimeout(() => {
202
+ window.location.href = "/account"
203
+ }, 1000)
204
+ }
205
+ } catch (err: any) {
206
+ // ✅ Typed error handling
207
+ let title = "Unable to sign in"
208
+ let description = err.message || "Please check your credentials and try again."
209
+
210
+ // ✅ Type-safe error checking
211
+ if (err._tag === "UserNotFound") {
212
+ title = "Account not found"
213
+ description = "No account exists with this email. Please sign up first."
214
+ } else if (err._tag === "InvalidCredentials") {
215
+ title = "Incorrect password"
216
+ description = "The password you entered is incorrect. Try again or use 'Forgot password'."
217
+ } else if (err._tag === "NetworkError") {
218
+ title = "Network error"
219
+ description = "Unable to connect to the server. Check your internet connection."
220
+ } else if (err._tag === "EmailNotVerified") {
221
+ title = "Email not verified"
222
+ description = "Please verify your email address before signing in."
223
+ } else if (err._tag === "TwoFactorRequired") {
224
+ title = "2FA required"
225
+ description = "Please enter your two-factor authentication code."
226
+ // Redirect to 2FA page
227
+ window.location.href = `/account/signin/2fa?email=${encodeURIComponent(email)}`
228
+ return
229
+ }
230
+
231
+ toast.error(title, { description })
232
+ }
233
+ }
234
+
235
+ return (
236
+ <AuthCard title="Welcome Back" description="Sign in to your account">
237
+ <SocialLoginButtons mode="signin" />
238
+
239
+ <form onSubmit={handleSubmit} className="space-y-4">
240
+ <div className="space-y-2">
241
+ <Label htmlFor="email">Email</Label>
242
+ <Input
243
+ id="email"
244
+ type="email"
245
+ placeholder="your@email.com"
246
+ value={email}
247
+ onChange={(e) => setEmail(e.target.value)}
248
+ required
249
+ />
250
+ </div>
251
+
252
+ <div className="space-y-2">
253
+ <div className="flex items-center justify-between">
254
+ <Label htmlFor="password">Password</Label>
255
+ <a href="/account/forgot-password" className="text-xs text-primary hover:underline">
256
+ Forgot password?
257
+ </a>
258
+ </div>
259
+ <Input
260
+ id="password"
261
+ type="password"
262
+ placeholder="••••••••"
263
+ value={password}
264
+ onChange={(e) => setPassword(e.target.value)}
265
+ required
266
+ />
267
+ </div>
268
+
269
+ <Button type="submit" className="w-full" disabled={loading}>
270
+ {loading ? "Signing in..." : "Sign In"}
271
+ </Button>
272
+
273
+ <div className="relative my-4">
274
+ <div className="absolute inset-0 flex items-center">
275
+ <span className="w-full border-t" />
276
+ </div>
277
+ <div className="relative flex justify-center text-xs uppercase">
278
+ <span className="bg-background px-2 text-muted-foreground">Or</span>
279
+ </div>
280
+ </div>
281
+
282
+ <Button variant="outline" className="w-full" asChild>
283
+ <a href="/account/magic-link">Sign in with magic link</a>
284
+ </Button>
285
+ </form>
286
+ </AuthCard>
287
+ )
288
+ }
289
+ ```
290
+
291
+ **Key Changes:**
292
+ - ❌ Removed `authClient` import
293
+ - ✅ Added `useLogin()` hook import
294
+ - ❌ Removed manual `loading` state
295
+ - ✅ Hook manages `loading`, `error` state
296
+ - ❌ Removed string-based error detection
297
+ - ✅ Type-safe `_tag` error checking
298
+ - 🔥 **43 fewer lines** (163 → 120)
299
+ - 🎯 **Better error handling** with typed errors
300
+ - ⚡ **Cleaner code** with hook pattern
301
+
302
+ ---
303
+
304
+ ### 2.2 SimpleSignUpForm Migration
305
+
306
+ **BEFORE (Current - 157 lines):**
307
+
308
+ ```typescript
309
+ // frontend/src/components/auth/SimpleSignUpForm.tsx (BEFORE)
310
+ import { useState } from "react"
311
+ import { Button } from "@/components/ui/button"
312
+ import { Input } from "@/components/ui/input"
313
+ import { Label } from "@/components/ui/label"
314
+ import { authClient } from "@/lib/auth-client" // ❌ REMOVE
315
+ import { toast } from "sonner"
316
+ import { AuthCard } from "./AuthCard"
317
+ import { SocialLoginButtons } from "./SocialLoginButtons"
318
+ import { PasswordStrengthIndicator } from "./PasswordStrengthIndicator"
319
+
320
+ export function SimpleSignUpForm() {
321
+ const [email, setEmail] = useState("")
322
+ const [password, setPassword] = useState("")
323
+ const [name, setName] = useState("")
324
+ const [loading, setLoading] = useState(false) // ❌ Manual state
325
+
326
+ const handleSubmit = async (e: React.FormEvent) => {
327
+ e.preventDefault()
328
+ setLoading(true) // ❌ Manual loading
329
+
330
+ try {
331
+ // ❌ Direct authClient call
332
+ const result = await authClient.signUp.email({
333
+ email,
334
+ password,
335
+ name,
336
+ })
337
+
338
+ if (result.error) {
339
+ const errorMessage = result.error.message || "Unable to create account"
340
+ let title = "Unable to create account"
341
+ let description = `Error: ${errorMessage}. Please verify your information and try again.`
342
+
343
+ // ❌ String-based error detection
344
+ if (errorMessage.toLowerCase().includes("already exists")) {
345
+ title = "Email already registered"
346
+ description = "This email is already in use. Please sign in instead."
347
+ } else if (errorMessage.toLowerCase().includes("password")) {
348
+ title = "Invalid password"
349
+ description = "Password must be at least 8 characters long."
350
+ }
351
+
352
+ toast.error(title, { description })
353
+ setLoading(false) // ❌ Manual state reset
354
+ return
355
+ }
356
+
357
+ toast.success("Account created successfully!", {
358
+ description: `Welcome ${name}! Redirecting to your dashboard...`
359
+ })
360
+
361
+ setTimeout(() => {
362
+ window.location.href = "/account"
363
+ }, 1000)
364
+ } catch (err: any) {
365
+ toast.error("Sign up error", {
366
+ description: `Error: ${err.message}. Please try again later.`
367
+ })
368
+ setLoading(false) // ❌ Manual state reset
369
+ }
370
+ }
371
+
372
+ return (
373
+ <AuthCard title="Create Account" description="Sign up to get started">
374
+ <SocialLoginButtons mode="signup" />
375
+
376
+ <form onSubmit={handleSubmit} className="space-y-4">
377
+ <div className="space-y-2">
378
+ <Label htmlFor="name">Name</Label>
379
+ <Input
380
+ id="name"
381
+ type="text"
382
+ placeholder="Your name"
383
+ value={name}
384
+ onChange={(e) => setName(e.target.value)}
385
+ />
386
+ </div>
387
+
388
+ <div className="space-y-2">
389
+ <Label htmlFor="email">Email</Label>
390
+ <Input
391
+ id="email"
392
+ type="email"
393
+ placeholder="your@email.com"
394
+ value={email}
395
+ onChange={(e) => setEmail(e.target.value)}
396
+ required
397
+ />
398
+ </div>
399
+
400
+ <div className="space-y-2">
401
+ <Label htmlFor="password">Password</Label>
402
+ <Input
403
+ id="password"
404
+ type="password"
405
+ placeholder="••••••••"
406
+ value={password}
407
+ onChange={(e) => setPassword(e.target.value)}
408
+ required
409
+ minLength={8}
410
+ />
411
+ <PasswordStrengthIndicator password={password} />
412
+ </div>
413
+
414
+ <Button type="submit" className="w-full" disabled={loading}>
415
+ {loading ? "Signing up..." : "Sign Up"}
416
+ </Button>
417
+ </form>
418
+ </AuthCard>
419
+ )
420
+ }
421
+ ```
422
+
423
+ **AFTER (Migrated - 115 lines):**
424
+
425
+ ```typescript
426
+ // frontend/src/components/auth/SimpleSignUpForm.tsx (AFTER)
427
+ import { useState } from "react"
428
+ import { Button } from "@/components/ui/button"
429
+ import { Input } from "@/components/ui/input"
430
+ import { Label } from "@/components/ui/label"
431
+ import { useSignup } from "@/providers/hooks" // ✅ DataProvider hook
432
+ import { toast } from "sonner"
433
+ import { AuthCard } from "./AuthCard"
434
+ import { SocialLoginButtons } from "./SocialLoginButtons"
435
+ import { PasswordStrengthIndicator } from "./PasswordStrengthIndicator"
436
+
437
+ export function SimpleSignUpForm() {
438
+ const [email, setEmail] = useState("")
439
+ const [password, setPassword] = useState("")
440
+ const [name, setName] = useState("")
441
+ const { mutate: signup, loading, error } = useSignup() // ✅ Hook manages state
442
+
443
+ const handleSubmit = async (e: React.FormEvent) => {
444
+ e.preventDefault()
445
+
446
+ try {
447
+ const result = await signup({ email, password, name }) // ✅ Simple call
448
+
449
+ if (result.success) {
450
+ toast.success("Account created successfully!", {
451
+ description: `Welcome ${name}! Redirecting to your dashboard...`
452
+ })
453
+
454
+ setTimeout(() => {
455
+ window.location.href = "/account"
456
+ }, 1000)
457
+ }
458
+ } catch (err: any) {
459
+ let title = "Unable to create account"
460
+ let description = err.message || "Please verify your information and try again."
461
+
462
+ // ✅ Typed error handling
463
+ if (err._tag === "EmailAlreadyExists") {
464
+ title = "Email already registered"
465
+ description = "This email is already in use. Please sign in or use a different email."
466
+ } else if (err._tag === "WeakPassword") {
467
+ title = "Password too weak"
468
+ description = "Password must be at least 8 characters with letters and numbers."
469
+ } else if (err._tag === "NetworkError") {
470
+ title = "Network error"
471
+ description = "Unable to connect to the server. Check your internet connection."
472
+ }
473
+
474
+ toast.error(title, { description })
475
+ }
476
+ }
477
+
478
+ return (
479
+ <AuthCard title="Create Account" description="Sign up to get started">
480
+ <SocialLoginButtons mode="signup" />
481
+
482
+ <form onSubmit={handleSubmit} className="space-y-4">
483
+ <div className="space-y-2">
484
+ <Label htmlFor="name">Name</Label>
485
+ <Input
486
+ id="name"
487
+ type="text"
488
+ placeholder="Your name"
489
+ value={name}
490
+ onChange={(e) => setName(e.target.value)}
491
+ />
492
+ </div>
493
+
494
+ <div className="space-y-2">
495
+ <Label htmlFor="email">Email</Label>
496
+ <Input
497
+ id="email"
498
+ type="email"
499
+ placeholder="your@email.com"
500
+ value={email}
501
+ onChange={(e) => setEmail(e.target.value)}
502
+ required
503
+ />
504
+ </div>
505
+
506
+ <div className="space-y-2">
507
+ <Label htmlFor="password">Password</Label>
508
+ <Input
509
+ id="password"
510
+ type="password"
511
+ placeholder="••••••••"
512
+ value={password}
513
+ onChange={(e) => setPassword(e.target.value)}
514
+ required
515
+ minLength={8}
516
+ />
517
+ <PasswordStrengthIndicator password={password} />
518
+ </div>
519
+
520
+ <Button type="submit" className="w-full" disabled={loading}>
521
+ {loading ? "Signing up..." : "Sign Up"}
522
+ </Button>
523
+ </form>
524
+ </AuthCard>
525
+ )
526
+ }
527
+ ```
528
+
529
+ **Key Changes:**
530
+ - 🔥 **42 fewer lines** (157 → 115)
531
+ - ✅ Cleaner error handling with typed errors
532
+ - ✅ Password strength indicator preserved
533
+ - ✅ Same UX, better code
534
+
535
+ ---
536
+
537
+ ### 2.3 MagicLinkAuth Migration
538
+
539
+ **BEFORE (Current - 151 lines):**
540
+
541
+ ```typescript
542
+ // frontend/src/components/auth/MagicLinkAuth.tsx (BEFORE)
543
+ import { useState, useEffect } from "react"
544
+ import { Button } from "@/components/ui/button"
545
+ import { toast } from "sonner"
546
+ import { AuthCard } from "./AuthCard"
547
+ import { CheckCircle2, Mail } from "lucide-react"
548
+ import { Alert, AlertDescription } from "@/components/ui/alert"
549
+ import { ConvexHttpClient } from "convex/browser" // ❌ REMOVE
550
+ import { api } from "../../../convex/_generated/api" // ❌ REMOVE
551
+
552
+ const convex = new ConvexHttpClient( // ❌ REMOVE
553
+ import.meta.env.PUBLIC_CONVEX_URL || import.meta.env.NEXT_PUBLIC_CONVEX_URL
554
+ )
555
+
556
+ interface MagicLinkAuthProps {
557
+ token: string
558
+ }
559
+
560
+ export function MagicLinkAuth({ token }: MagicLinkAuthProps) {
561
+ const [loading, setLoading] = useState(false) // ❌ Manual state
562
+ const [authSuccess, setAuthSuccess] = useState(false)
563
+ const [tokenValid, setTokenValid] = useState(true)
564
+ const [authenticating, setAuthenticating] = useState(true)
565
+
566
+ useEffect(() => {
567
+ const authenticateWithMagicLink = async () => {
568
+ if (!token) {
569
+ setTokenValid(false)
570
+ setAuthenticating(false)
571
+ toast.error("No magic link token", {
572
+ description: "This link is missing a token."
573
+ })
574
+ return
575
+ }
576
+
577
+ setLoading(true)
578
+ try {
579
+ // ❌ Direct Convex mutation call
580
+ const result = await convex.mutation(api.auth.signInWithMagicLink, { token })
581
+
582
+ if (result?.token) {
583
+ // ❌ Manual cookie setting via API
584
+ const response = await fetch("/api/auth/set-cookie", {
585
+ method: "POST",
586
+ headers: { "Content-Type": "application/json" },
587
+ body: JSON.stringify({ token: result.token }),
588
+ })
589
+
590
+ if (response.ok) {
591
+ setAuthSuccess(true)
592
+ toast.success("Signed in successfully!", {
593
+ description: "Redirecting to your dashboard..."
594
+ })
595
+
596
+ setTimeout(() => {
597
+ window.location.href = "/account"
598
+ }, 1500)
599
+ } else {
600
+ throw new Error("Failed to set authentication cookie")
601
+ }
602
+ }
603
+ } catch (err: any) {
604
+ setTokenValid(false)
605
+ toast.error("Authentication failed", {
606
+ description: err.message || "Invalid or expired link"
607
+ })
608
+ } finally {
609
+ setLoading(false)
610
+ setAuthenticating(false)
611
+ }
612
+ }
613
+
614
+ authenticateWithMagicLink()
615
+ }, [token])
616
+
617
+ // ... render logic (unchanged)
618
+ }
619
+ ```
620
+
621
+ **AFTER (Migrated - 105 lines):**
622
+
623
+ ```typescript
624
+ // frontend/src/components/auth/MagicLinkAuth.tsx (AFTER)
625
+ import { useState, useEffect } from "react"
626
+ import { Button } from "@/components/ui/button"
627
+ import { toast } from "sonner"
628
+ import { AuthCard } from "./AuthCard"
629
+ import { CheckCircle2, Mail } from "lucide-react"
630
+ import { Alert, AlertDescription } from "@/components/ui/alert"
631
+ import { useMagicLinkAuth } from "@/providers/hooks" // ✅ DataProvider hook
632
+
633
+ interface MagicLinkAuthProps {
634
+ token: string
635
+ }
636
+
637
+ export function MagicLinkAuth({ token }: MagicLinkAuthProps) {
638
+ const { mutate: authenticate, loading, error } = useMagicLinkAuth() // ✅ Hook
639
+ const [authSuccess, setAuthSuccess] = useState(false)
640
+ const [tokenValid, setTokenValid] = useState(true)
641
+
642
+ useEffect(() => {
643
+ const authenticateWithToken = async () => {
644
+ if (!token) {
645
+ setTokenValid(false)
646
+ toast.error("No magic link token", {
647
+ description: "This link is missing a token."
648
+ })
649
+ return
650
+ }
651
+
652
+ try {
653
+ const result = await authenticate({ token }) // ✅ Simple hook call
654
+
655
+ if (result.success) {
656
+ setAuthSuccess(true)
657
+ toast.success("Signed in successfully!", {
658
+ description: "Redirecting to your dashboard..."
659
+ })
660
+
661
+ setTimeout(() => {
662
+ window.location.href = "/account"
663
+ }, 1500)
664
+ }
665
+ } catch (err: any) {
666
+ setTokenValid(false)
667
+
668
+ let title = "Authentication failed"
669
+ let description = err.message
670
+
671
+ // ✅ Typed error handling
672
+ if (err._tag === "InvalidToken" || err._tag === "TokenExpired") {
673
+ title = "Invalid or expired link"
674
+ description = "This magic link has expired or is invalid. Magic links expire after 15 minutes."
675
+ }
676
+
677
+ toast.error(title, { description })
678
+ }
679
+ }
680
+
681
+ authenticateWithToken()
682
+ }, [token])
683
+
684
+ if (loading) {
685
+ return (
686
+ <AuthCard
687
+ title="Signing you in"
688
+ description="Please wait while we authenticate your magic link"
689
+ >
690
+ <div className="flex justify-center py-8">
691
+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
692
+ </div>
693
+ </AuthCard>
694
+ )
695
+ }
696
+
697
+ if (!tokenValid) {
698
+ return (
699
+ <AuthCard
700
+ title="Authentication failed"
701
+ description="This magic link is no longer valid"
702
+ >
703
+ <Alert variant="destructive">
704
+ <Mail className="h-4 w-4" />
705
+ <AlertDescription>
706
+ This magic link has expired or is invalid. Magic links expire after 15 minutes.
707
+ </AlertDescription>
708
+ </Alert>
709
+
710
+ <Button variant="outline" className="w-full" asChild>
711
+ <a href="/account/magic-link">Request new magic link</a>
712
+ </Button>
713
+ </AuthCard>
714
+ )
715
+ }
716
+
717
+ if (authSuccess) {
718
+ return (
719
+ <AuthCard
720
+ title="Signed in successfully!"
721
+ description="Redirecting to your dashboard"
722
+ >
723
+ <Alert className="border-green-500/50 bg-green-500/10">
724
+ <CheckCircle2 className="h-4 w-4 text-green-500" />
725
+ <AlertDescription>
726
+ You've been successfully signed in with your magic link.
727
+ </AlertDescription>
728
+ </Alert>
729
+
730
+ <Button className="w-full" asChild>
731
+ <a href="/account">Go to dashboard</a>
732
+ </Button>
733
+ </AuthCard>
734
+ )
735
+ }
736
+
737
+ return null
738
+ }
739
+ ```
740
+
741
+ **Key Changes:**
742
+ - ❌ Removed ConvexHttpClient import
743
+ - ❌ Removed api import
744
+ - ✅ Added `useMagicLinkAuth()` hook
745
+ - 🔥 **46 fewer lines** (151 → 105)
746
+ - ✅ Automatic cookie management (hook handles it)
747
+ - ✅ Cleaner error handling
748
+
749
+ ---
750
+
751
+ ### 2.4 TwoFactorSettings Migration
752
+
753
+ **BEFORE (Current - 293 lines):**
754
+
755
+ ```typescript
756
+ // frontend/src/components/auth/TwoFactorSettings.tsx (BEFORE)
757
+ import { useState, useEffect } from "react"
758
+ import { Button } from "@/components/ui/button"
759
+ import { Input } from "@/components/ui/input"
760
+ import { Label } from "@/components/ui/label"
761
+ import { toast } from "sonner"
762
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
763
+ import { Alert, AlertDescription } from "@/components/ui/alert"
764
+ import { Shield, Key, Copy, CheckCircle2 } from "lucide-react"
765
+ import { ConvexHttpClient } from "convex/browser" // ❌ REMOVE
766
+ import { api } from "../../../convex/_generated/api" // ❌ REMOVE
767
+ import * as OTPAuth from "otpauth"
768
+ import QRCode from "qrcode"
769
+
770
+ const convex = new ConvexHttpClient( // ❌ REMOVE
771
+ import.meta.env.PUBLIC_CONVEX_URL || import.meta.env.NEXT_PUBLIC_CONVEX_URL
772
+ )
773
+
774
+ export function TwoFactorSettings() {
775
+ const [loading, setLoading] = useState(false) // ❌ Manual state
776
+ const [status, setStatus] = useState<{ enabled: boolean; hasSetup: boolean }>({ enabled: false, hasSetup: false })
777
+ const [showSetup, setShowSetup] = useState(false)
778
+ const [secret, setSecret] = useState("")
779
+ const [backupCodes, setBackupCodes] = useState<string[]>([])
780
+ const [qrCodeUrl, setQrCodeUrl] = useState("")
781
+ const [verificationCode, setVerificationCode] = useState("")
782
+ const [disablePassword, setDisablePassword] = useState("")
783
+
784
+ useEffect(() => {
785
+ loadStatus()
786
+ }, [])
787
+
788
+ const loadStatus = async () => {
789
+ try {
790
+ // ❌ Manual token extraction from cookies
791
+ const token = document.cookie.split('; ').find(row => row.startsWith('auth_token='))?.split('=')[1]
792
+ if (!token) return
793
+
794
+ // ❌ Direct Convex query
795
+ const result = await convex.query(api.auth.get2FAStatus, { token })
796
+ setStatus(result)
797
+ } catch (err) {
798
+ console.error("Failed to load 2FA status:", err)
799
+ }
800
+ }
801
+
802
+ const handleSetup = async () => {
803
+ setLoading(true) // ❌ Manual state
804
+ try {
805
+ const token = document.cookie.split('; ').find(row => row.startsWith('auth_token='))?.split('=')[1]
806
+ if (!token) {
807
+ toast.error("Not authenticated")
808
+ return
809
+ }
810
+
811
+ // ❌ Direct Convex mutation
812
+ const result = await convex.mutation(api.auth.setup2FA, { token })
813
+ setSecret(result.secret)
814
+ setBackupCodes(result.backupCodes)
815
+
816
+ // Generate TOTP URI
817
+ const totp = new OTPAuth.TOTP({
818
+ issuer: "ONE",
819
+ label: "user@one.ie",
820
+ algorithm: "SHA1",
821
+ digits: 6,
822
+ period: 30,
823
+ secret: OTPAuth.Secret.fromBase32(result.secret.toUpperCase().padEnd(32, 'A')),
824
+ })
825
+
826
+ const uri = totp.toString()
827
+ const qrUrl = await QRCode.toDataURL(uri)
828
+ setQrCodeUrl(qrUrl)
829
+ setShowSetup(true)
830
+
831
+ toast.success("2FA setup initiated", {
832
+ description: "Scan the QR code with your authenticator app"
833
+ })
834
+ } catch (err: any) {
835
+ toast.error("Setup failed", {
836
+ description: err.message || "Failed to setup 2FA"
837
+ })
838
+ } finally {
839
+ setLoading(false) // ❌ Manual state
840
+ }
841
+ }
842
+
843
+ const handleVerify = async () => {
844
+ setLoading(true)
845
+ try {
846
+ const token = document.cookie.split('; ').find(row => row.startsWith('auth_token='))?.split('=')[1]
847
+ if (!token) {
848
+ toast.error("Not authenticated")
849
+ return
850
+ }
851
+
852
+ // Client-side TOTP verification
853
+ const totp = new OTPAuth.TOTP({
854
+ issuer: "ONE",
855
+ label: "user@one.ie",
856
+ algorithm: "SHA1",
857
+ digits: 6,
858
+ period: 30,
859
+ secret: OTPAuth.Secret.fromBase32(secret.toUpperCase().padEnd(32, 'A')),
860
+ })
861
+
862
+ const delta = totp.validate({ token: verificationCode, window: 1 })
863
+ if (delta === null) {
864
+ toast.error("Invalid code", {
865
+ description: "The verification code is incorrect. Please try again."
866
+ })
867
+ setLoading(false)
868
+ return
869
+ }
870
+
871
+ // ❌ Direct Convex mutation
872
+ await convex.mutation(api.auth.verify2FA, { token })
873
+
874
+ toast.success("2FA enabled!", {
875
+ description: "Two-factor authentication has been enabled for your account"
876
+ })
877
+
878
+ setShowSetup(false)
879
+ loadStatus()
880
+ } catch (err: any) {
881
+ toast.error("Verification failed", {
882
+ description: err.message || "Failed to verify code"
883
+ })
884
+ } finally {
885
+ setLoading(false)
886
+ }
887
+ }
888
+
889
+ const handleDisable = async () => {
890
+ setLoading(true)
891
+ try {
892
+ const token = document.cookie.split('; ').find(row => row.startsWith('auth_token='))?.split('=')[1]
893
+ if (!token) {
894
+ toast.error("Not authenticated")
895
+ return
896
+ }
897
+
898
+ // ❌ Direct Convex mutation
899
+ await convex.mutation(api.auth.disable2FA, { token, password: disablePassword })
900
+
901
+ toast.success("2FA disabled", {
902
+ description: "Two-factor authentication has been disabled"
903
+ })
904
+
905
+ setDisablePassword("")
906
+ loadStatus()
907
+ } catch (err: any) {
908
+ toast.error("Failed to disable 2FA", {
909
+ description: err.message || "Incorrect password"
910
+ })
911
+ } finally {
912
+ setLoading(false)
913
+ }
914
+ }
915
+
916
+ const copyToClipboard = (text: string) => {
917
+ navigator.clipboard.writeText(text)
918
+ toast.success("Copied to clipboard")
919
+ }
920
+
921
+ // ... rest of component (render logic - 150+ lines unchanged)
922
+ }
923
+ ```
924
+
925
+ **AFTER (Migrated - 210 lines):**
926
+
927
+ ```typescript
928
+ // frontend/src/components/auth/TwoFactorSettings.tsx (AFTER)
929
+ import { useState, useEffect } from "react"
930
+ import { Button } from "@/components/ui/button"
931
+ import { Input } from "@/components/ui/input"
932
+ import { Label } from "@/components/ui/label"
933
+ import { toast } from "sonner"
934
+ import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
935
+ import { Alert, AlertDescription } from "@/components/ui/alert"
936
+ import { Shield, Key, Copy, CheckCircle2 } from "lucide-react"
937
+ import { use2FA } from "@/providers/hooks" // ✅ DataProvider hook
938
+ import * as OTPAuth from "otpauth"
939
+ import QRCode from "qrcode"
940
+
941
+ export function TwoFactorSettings() {
942
+ const { getStatus, setup, verify, disable, loading, error } = use2FA() // ✅ Hook
943
+ const [status, setStatus] = useState<{ enabled: boolean; hasSetup: boolean }>({ enabled: false, hasSetup: false })
944
+ const [showSetup, setShowSetup] = useState(false)
945
+ const [secret, setSecret] = useState("")
946
+ const [backupCodes, setBackupCodes] = useState<string[]>([])
947
+ const [qrCodeUrl, setQrCodeUrl] = useState("")
948
+ const [verificationCode, setVerificationCode] = useState("")
949
+ const [disablePassword, setDisablePassword] = useState("")
950
+
951
+ useEffect(() => {
952
+ loadStatus()
953
+ }, [])
954
+
955
+ const loadStatus = async () => {
956
+ try {
957
+ const result = await getStatus() // ✅ Simple hook call (no token needed)
958
+ setStatus(result)
959
+ } catch (err) {
960
+ console.error("Failed to load 2FA status:", err)
961
+ }
962
+ }
963
+
964
+ const handleSetup = async () => {
965
+ try {
966
+ const result = await setup() // ✅ Simple hook call
967
+ setSecret(result.secret)
968
+ setBackupCodes(result.backupCodes)
969
+
970
+ // Generate TOTP URI (unchanged)
971
+ const totp = new OTPAuth.TOTP({
972
+ issuer: "ONE",
973
+ label: "user@one.ie",
974
+ algorithm: "SHA1",
975
+ digits: 6,
976
+ period: 30,
977
+ secret: OTPAuth.Secret.fromBase32(result.secret.toUpperCase().padEnd(32, 'A')),
978
+ })
979
+
980
+ const uri = totp.toString()
981
+ const qrUrl = await QRCode.toDataURL(uri)
982
+ setQrCodeUrl(qrUrl)
983
+ setShowSetup(true)
984
+
985
+ toast.success("2FA setup initiated", {
986
+ description: "Scan the QR code with your authenticator app"
987
+ })
988
+ } catch (err: any) {
989
+ toast.error("Setup failed", {
990
+ description: err.message || "Failed to setup 2FA"
991
+ })
992
+ }
993
+ }
994
+
995
+ const handleVerify = async () => {
996
+ try {
997
+ // Client-side TOTP verification (unchanged)
998
+ const totp = new OTPAuth.TOTP({
999
+ issuer: "ONE",
1000
+ label: "user@one.ie",
1001
+ algorithm: "SHA1",
1002
+ digits: 6,
1003
+ period: 30,
1004
+ secret: OTPAuth.Secret.fromBase32(secret.toUpperCase().padEnd(32, 'A')),
1005
+ })
1006
+
1007
+ const delta = totp.validate({ token: verificationCode, window: 1 })
1008
+ if (delta === null) {
1009
+ toast.error("Invalid code", {
1010
+ description: "The verification code is incorrect. Please try again."
1011
+ })
1012
+ return
1013
+ }
1014
+
1015
+ await verify(verificationCode) // ✅ Simple hook call
1016
+
1017
+ toast.success("2FA enabled!", {
1018
+ description: "Two-factor authentication has been enabled for your account"
1019
+ })
1020
+
1021
+ setShowSetup(false)
1022
+ loadStatus()
1023
+ } catch (err: any) {
1024
+ toast.error("Verification failed", {
1025
+ description: err.message || "Failed to verify code"
1026
+ })
1027
+ }
1028
+ }
1029
+
1030
+ const handleDisable = async () => {
1031
+ try {
1032
+ await disable(disablePassword) // ✅ Simple hook call
1033
+
1034
+ toast.success("2FA disabled", {
1035
+ description: "Two-factor authentication has been disabled"
1036
+ })
1037
+
1038
+ setDisablePassword("")
1039
+ loadStatus()
1040
+ } catch (err: any) {
1041
+ toast.error("Failed to disable 2FA", {
1042
+ description: err.message || "Incorrect password"
1043
+ })
1044
+ }
1045
+ }
1046
+
1047
+ const copyToClipboard = (text: string) => {
1048
+ navigator.clipboard.writeText(text)
1049
+ toast.success("Copied to clipboard")
1050
+ }
1051
+
1052
+ // ... render logic (unchanged - 100+ lines)
1053
+ }
1054
+ ```
1055
+
1056
+ **Key Changes:**
1057
+ - ❌ Removed ConvexHttpClient
1058
+ - ❌ Removed manual token extraction
1059
+ - ✅ Added `use2FA()` hook with all operations
1060
+ - 🔥 **83 fewer lines** (293 → 210)
1061
+ - ✅ Automatic authentication (hook handles tokens)
1062
+ - ✅ Same functionality, cleaner code
1063
+
1064
+ ---
1065
+
1066
+ ### 2.5 VerifyEmailForm Migration
1067
+
1068
+ **BEFORE (Current - 134 lines):**
1069
+
1070
+ ```typescript
1071
+ // frontend/src/components/auth/VerifyEmailForm.tsx (BEFORE)
1072
+ import { useState, useEffect } from "react"
1073
+ import { Button } from "@/components/ui/button"
1074
+ import { toast } from "sonner"
1075
+ import { AuthCard } from "./AuthCard"
1076
+ import { CheckCircle2, Mail } from "lucide-react"
1077
+ import { Alert, AlertDescription } from "@/components/ui/alert"
1078
+ import { ConvexHttpClient } from "convex/browser" // ❌ REMOVE
1079
+ import { api } from "../../../convex/_generated/api" // ❌ REMOVE
1080
+
1081
+ const convex = new ConvexHttpClient( // ❌ REMOVE
1082
+ import.meta.env.PUBLIC_CONVEX_URL || import.meta.env.NEXT_PUBLIC_CONVEX_URL
1083
+ )
1084
+
1085
+ interface VerifyEmailFormProps {
1086
+ token: string
1087
+ }
1088
+
1089
+ export function VerifyEmailForm({ token }: VerifyEmailFormProps) {
1090
+ const [loading, setLoading] = useState(false) // ❌ Manual state
1091
+ const [verifySuccess, setVerifySuccess] = useState(false)
1092
+ const [tokenValid, setTokenValid] = useState(true)
1093
+ const [verifying, setVerifying] = useState(true)
1094
+
1095
+ useEffect(() => {
1096
+ const verifyToken = async () => {
1097
+ if (!token) {
1098
+ setTokenValid(false)
1099
+ setVerifying(false)
1100
+ toast.error("No verification token", {
1101
+ description: "This verification link is missing a token."
1102
+ })
1103
+ return
1104
+ }
1105
+
1106
+ setLoading(true)
1107
+ try {
1108
+ // ❌ Direct Convex mutation
1109
+ const result = await convex.mutation(api.auth.verifyEmail, { token })
1110
+
1111
+ if (result?.success) {
1112
+ setVerifySuccess(true)
1113
+ toast.success("Email verified successfully!", {
1114
+ description: "Your email has been verified. You can now access all features."
1115
+ })
1116
+ }
1117
+ } catch (err: any) {
1118
+ setTokenValid(false)
1119
+ toast.error("Verification failed", {
1120
+ description: err.message || "Invalid or expired link"
1121
+ })
1122
+ } finally {
1123
+ setLoading(false)
1124
+ setVerifying(false)
1125
+ }
1126
+ }
1127
+
1128
+ verifyToken()
1129
+ }, [token])
1130
+
1131
+ // ... render logic (unchanged)
1132
+ }
1133
+ ```
1134
+
1135
+ **AFTER (Migrated - 95 lines):**
1136
+
1137
+ ```typescript
1138
+ // frontend/src/components/auth/VerifyEmailForm.tsx (AFTER)
1139
+ import { useState, useEffect } from "react"
1140
+ import { Button } from "@/components/ui/button"
1141
+ import { toast } from "sonner"
1142
+ import { AuthCard } from "./AuthCard"
1143
+ import { CheckCircle2, Mail } from "lucide-react"
1144
+ import { Alert, AlertDescription } from "@/components/ui/alert"
1145
+ import { useVerifyEmail } from "@/providers/hooks" // ✅ DataProvider hook
1146
+
1147
+ interface VerifyEmailFormProps {
1148
+ token: string
1149
+ }
1150
+
1151
+ export function VerifyEmailForm({ token }: VerifyEmailFormProps) {
1152
+ const { mutate: verify, loading, error } = useVerifyEmail() // ✅ Hook
1153
+ const [verifySuccess, setVerifySuccess] = useState(false)
1154
+ const [tokenValid, setTokenValid] = useState(true)
1155
+
1156
+ useEffect(() => {
1157
+ const verifyToken = async () => {
1158
+ if (!token) {
1159
+ setTokenValid(false)
1160
+ toast.error("No verification token", {
1161
+ description: "This verification link is missing a token."
1162
+ })
1163
+ return
1164
+ }
1165
+
1166
+ try {
1167
+ const result = await verify({ token }) // ✅ Simple hook call
1168
+
1169
+ if (result.success) {
1170
+ setVerifySuccess(true)
1171
+ toast.success("Email verified successfully!", {
1172
+ description: "Your email has been verified. You can now access all features."
1173
+ })
1174
+ }
1175
+ } catch (err: any) {
1176
+ setTokenValid(false)
1177
+
1178
+ let title = "Verification failed"
1179
+ let description = err.message
1180
+
1181
+ // ✅ Typed error handling
1182
+ if (err._tag === "InvalidToken" || err._tag === "TokenExpired") {
1183
+ title = "Invalid or expired link"
1184
+ description = "This verification link has expired or is invalid."
1185
+ }
1186
+
1187
+ toast.error(title, { description })
1188
+ }
1189
+ }
1190
+
1191
+ verifyToken()
1192
+ }, [token])
1193
+
1194
+ if (loading) {
1195
+ return (
1196
+ <AuthCard
1197
+ title="Verifying your email"
1198
+ description="Please wait while we verify your email address"
1199
+ >
1200
+ <div className="flex justify-center py-8">
1201
+ <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
1202
+ </div>
1203
+ </AuthCard>
1204
+ )
1205
+ }
1206
+
1207
+ if (!tokenValid) {
1208
+ return (
1209
+ <AuthCard
1210
+ title="Verification failed"
1211
+ description="This verification link is no longer valid"
1212
+ >
1213
+ <Alert variant="destructive">
1214
+ <Mail className="h-4 w-4" />
1215
+ <AlertDescription>
1216
+ This verification link has expired or is invalid. If you need a new verification email, please contact support.
1217
+ </AlertDescription>
1218
+ </Alert>
1219
+
1220
+ <Button variant="outline" className="w-full" asChild>
1221
+ <a href="/account">Go to dashboard</a>
1222
+ </Button>
1223
+ </AuthCard>
1224
+ )
1225
+ }
1226
+
1227
+ if (verifySuccess) {
1228
+ return (
1229
+ <AuthCard
1230
+ title="Email verified!"
1231
+ description="Your email has been successfully verified"
1232
+ >
1233
+ <Alert className="border-green-500/50 bg-green-500/10">
1234
+ <CheckCircle2 className="h-4 w-4 text-green-500" />
1235
+ <AlertDescription>
1236
+ Your email has been successfully verified. You can now access all features.
1237
+ </AlertDescription>
1238
+ </Alert>
1239
+
1240
+ <Button className="w-full" asChild>
1241
+ <a href="/account">Go to dashboard</a>
1242
+ </Button>
1243
+ </AuthCard>
1244
+ )
1245
+ }
1246
+
1247
+ return null
1248
+ }
1249
+ ```
1250
+
1251
+ **Key Changes:**
1252
+ - 🔥 **39 fewer lines** (134 → 95)
1253
+ - ✅ Simple hook-based verification
1254
+ - ✅ Automatic verification on mount
1255
+
1256
+ ---
1257
+
1258
+ ### 2.6 ForgotPasswordForm Migration
1259
+
1260
+ **BEFORE (Current - 144 lines):**
1261
+
1262
+ ```typescript
1263
+ // frontend/src/components/auth/ForgotPasswordForm.tsx (BEFORE)
1264
+ import { useState } from "react"
1265
+ import { Button } from "@/components/ui/button"
1266
+ import { Input } from "@/components/ui/input"
1267
+ import { Label } from "@/components/ui/label"
1268
+ import { toast } from "sonner"
1269
+ import { AuthCard } from "./AuthCard"
1270
+ import { AlertCircle, CheckCircle2 } from "lucide-react"
1271
+ import { Alert, AlertDescription } from "@/components/ui/alert"
1272
+
1273
+ export function ForgotPasswordForm() {
1274
+ const [email, setEmail] = useState("")
1275
+ const [loading, setLoading] = useState(false) // ❌ Manual state
1276
+ const [emailSent, setEmailSent] = useState(false)
1277
+
1278
+ const handleSubmit = async (e: React.FormEvent) => {
1279
+ e.preventDefault()
1280
+ setLoading(true) // ❌ Manual loading
1281
+
1282
+ try {
1283
+ // ❌ Direct fetch call
1284
+ const response = await fetch("/api/auth/forgot-password", {
1285
+ method: "POST",
1286
+ headers: { "Content-Type": "application/json" },
1287
+ body: JSON.stringify({ email }),
1288
+ })
1289
+
1290
+ const data = await response.json()
1291
+
1292
+ if (!response.ok) {
1293
+ const errorMessage = data.error || "Unable to send reset email"
1294
+ // ... string-based error handling
1295
+ toast.error("Unable to send reset email", {
1296
+ description: errorMessage
1297
+ })
1298
+ setLoading(false) // ❌ Manual state
1299
+ return
1300
+ }
1301
+
1302
+ setEmailSent(true)
1303
+ toast.success("Reset email sent!", {
1304
+ description: "Check your inbox for password reset instructions."
1305
+ })
1306
+ setLoading(false)
1307
+ } catch (err: any) {
1308
+ toast.error("Request failed", {
1309
+ description: `Error: ${err.message}. Please try again later.`
1310
+ })
1311
+ setLoading(false) // ❌ Manual state
1312
+ }
1313
+ }
1314
+
1315
+ // ... render logic (unchanged)
1316
+ }
1317
+ ```
1318
+
1319
+ **AFTER (Migrated - 105 lines):**
1320
+
1321
+ ```typescript
1322
+ // frontend/src/components/auth/ForgotPasswordForm.tsx (AFTER)
1323
+ import { useState } from "react"
1324
+ import { Button } from "@/components/ui/button"
1325
+ import { Input } from "@/components/ui/input"
1326
+ import { Label } from "@/components/ui/label"
1327
+ import { toast } from "sonner"
1328
+ import { AuthCard } from "./AuthCard"
1329
+ import { AlertCircle, CheckCircle2 } from "lucide-react"
1330
+ import { Alert, AlertDescription } from "@/components/ui/alert"
1331
+ import { usePasswordReset } from "@/providers/hooks" // ✅ DataProvider hook
1332
+
1333
+ export function ForgotPasswordForm() {
1334
+ const [email, setEmail] = useState("")
1335
+ const { mutate: requestReset, loading, error } = usePasswordReset() // ✅ Hook
1336
+ const [emailSent, setEmailSent] = useState(false)
1337
+
1338
+ const handleSubmit = async (e: React.FormEvent) => {
1339
+ e.preventDefault()
1340
+
1341
+ try {
1342
+ await requestReset({ email }) // ✅ Simple hook call
1343
+
1344
+ setEmailSent(true)
1345
+ toast.success("Reset email sent!", {
1346
+ description: "Check your inbox for password reset instructions."
1347
+ })
1348
+ } catch (err: any) {
1349
+ let title = "Unable to send reset email"
1350
+ let description = err.message || "Please try again."
1351
+
1352
+ // ✅ Typed error handling
1353
+ if (err._tag === "UserNotFound") {
1354
+ title = "Email not found"
1355
+ description = "No account exists with this email address."
1356
+ } else if (err._tag === "RateLimitExceeded") {
1357
+ title = "Too many requests"
1358
+ description = "Please wait a few minutes and try again."
1359
+ } else if (err._tag === "NetworkError") {
1360
+ title = "Network error"
1361
+ description = "Unable to connect to the server."
1362
+ }
1363
+
1364
+ toast.error(title, { description })
1365
+ }
1366
+ }
1367
+
1368
+ if (emailSent) {
1369
+ return (
1370
+ <AuthCard
1371
+ title="Check your email"
1372
+ description="We've sent password reset instructions"
1373
+ >
1374
+ <Alert className="border-green-500/50 bg-green-500/10">
1375
+ <CheckCircle2 className="h-4 w-4 text-green-500" />
1376
+ <AlertDescription>
1377
+ If an account exists with <strong>{email}</strong>, you will receive an email.
1378
+ </AlertDescription>
1379
+ </Alert>
1380
+
1381
+ <Button
1382
+ variant="outline"
1383
+ className="w-full"
1384
+ onClick={() => {
1385
+ setEmailSent(false)
1386
+ setEmail("")
1387
+ }}
1388
+ >
1389
+ Try another email
1390
+ </Button>
1391
+ </AuthCard>
1392
+ )
1393
+ }
1394
+
1395
+ return (
1396
+ <AuthCard title="Forgot your password?" description="Enter your email to receive reset instructions">
1397
+ <Alert>
1398
+ <AlertCircle className="h-4 w-4" />
1399
+ <AlertDescription>
1400
+ We'll send you an email with instructions to reset your password.
1401
+ </AlertDescription>
1402
+ </Alert>
1403
+
1404
+ <form onSubmit={handleSubmit} className="space-y-4">
1405
+ <div className="space-y-2">
1406
+ <Label htmlFor="email">Email</Label>
1407
+ <Input
1408
+ id="email"
1409
+ type="email"
1410
+ placeholder="your@email.com"
1411
+ value={email}
1412
+ onChange={(e) => setEmail(e.target.value)}
1413
+ required
1414
+ />
1415
+ </div>
1416
+
1417
+ <Button type="submit" className="w-full" disabled={loading}>
1418
+ {loading ? "Sending..." : "Send reset email"}
1419
+ </Button>
1420
+ </form>
1421
+ </AuthCard>
1422
+ )
1423
+ }
1424
+ ```
1425
+
1426
+ **Key Changes:**
1427
+ - 🔥 **39 fewer lines** (144 → 105)
1428
+ - ❌ Removed fetch call
1429
+ - ✅ Added hook-based request
1430
+
1431
+ ---
1432
+
1433
+ ### 2.7 ResetPasswordForm Migration
1434
+
1435
+ **AFTER (Complete):**
1436
+
1437
+ ```typescript
1438
+ // frontend/src/components/auth/ResetPasswordForm.tsx (AFTER)
1439
+ import { useState, useEffect } from "react"
1440
+ import { Button } from "@/components/ui/button"
1441
+ import { Input } from "@/components/ui/input"
1442
+ import { Label } from "@/components/ui/label"
1443
+ import { toast } from "sonner"
1444
+ import { AuthCard } from "./AuthCard"
1445
+ import { PasswordStrengthIndicator } from "./PasswordStrengthIndicator"
1446
+ import { CheckCircle2 } from "lucide-react"
1447
+ import { Alert, AlertDescription } from "@/components/ui/alert"
1448
+ import { usePasswordResetComplete } from "@/providers/hooks" // ✅ Hook
1449
+
1450
+ interface ResetPasswordFormProps {
1451
+ token: string
1452
+ }
1453
+
1454
+ export function ResetPasswordForm({ token }: ResetPasswordFormProps) {
1455
+ const [password, setPassword] = useState("")
1456
+ const [confirmPassword, setConfirmPassword] = useState("")
1457
+ const { mutate: resetPassword, loading, error } = usePasswordResetComplete() // ✅ Hook
1458
+ const [resetSuccess, setResetSuccess] = useState(false)
1459
+ const [tokenValid, setTokenValid] = useState(true)
1460
+
1461
+ useEffect(() => {
1462
+ // Token validation can be done on mount if needed
1463
+ if (!token) {
1464
+ setTokenValid(false)
1465
+ toast.error("Invalid or expired token", {
1466
+ description: "This password reset link is invalid or has expired."
1467
+ })
1468
+ }
1469
+ }, [token])
1470
+
1471
+ const handleSubmit = async (e: React.FormEvent) => {
1472
+ e.preventDefault()
1473
+
1474
+ if (password !== confirmPassword) {
1475
+ toast.error("Passwords don't match", {
1476
+ description: "Please make sure both password fields match."
1477
+ })
1478
+ return
1479
+ }
1480
+
1481
+ if (password.length < 8) {
1482
+ toast.error("Password too short", {
1483
+ description: "Password must be at least 8 characters long."
1484
+ })
1485
+ return
1486
+ }
1487
+
1488
+ try {
1489
+ await resetPassword({ token, newPassword: password }) // ✅ Simple hook call
1490
+
1491
+ setResetSuccess(true)
1492
+ toast.success("Password reset successful!", {
1493
+ description: "Your password has been updated. Redirecting to sign in..."
1494
+ })
1495
+
1496
+ setTimeout(() => {
1497
+ window.location.href = "/account/signin"
1498
+ }, 2000)
1499
+ } catch (err: any) {
1500
+ let title = "Unable to reset password"
1501
+ let description = err.message || "Please try again."
1502
+
1503
+ // ✅ Typed error handling
1504
+ if (err._tag === "InvalidToken" || err._tag === "TokenExpired") {
1505
+ title = "Invalid or expired token"
1506
+ description = "This password reset link is invalid or has expired. Please request a new one."
1507
+ setTokenValid(false)
1508
+ } else if (err._tag === "WeakPassword") {
1509
+ title = "Invalid password"
1510
+ description = "Password must be at least 8 characters with letters and numbers."
1511
+ } else if (err._tag === "NetworkError") {
1512
+ title = "Network error"
1513
+ description = "Unable to connect to the server."
1514
+ }
1515
+
1516
+ toast.error(title, { description })
1517
+ }
1518
+ }
1519
+
1520
+ // ... render logic (similar to BEFORE)
1521
+ }
1522
+ ```
1523
+
1524
+ ---
1525
+
1526
+ ## 3. Implementation Procedure (60 Steps)
1527
+
1528
+ ### Phase 1: Pre-Migration Setup (Steps 1-12)
1529
+
1530
+ **Step 1: Audit Current Implementation**
1531
+ ```bash
1532
+ cd /Users/toc/Server/ONE/frontend
1533
+
1534
+ # Count lines
1535
+ wc -l src/components/auth/*.tsx
1536
+
1537
+ # Find dependencies
1538
+ grep -r "authClient" src/components/auth/
1539
+ grep -r "ConvexHttpClient" src/components/auth/
1540
+ grep -r "import.*convex" src/components/auth/
1541
+ ```
1542
+
1543
+ **Expected Output:**
1544
+ ```
1545
+ 163 SimpleSignInForm.tsx
1546
+ 157 SimpleSignUpForm.tsx
1547
+ 151 MagicLinkAuth.tsx
1548
+ 293 TwoFactorSettings.tsx
1549
+ 134 VerifyEmailForm.tsx
1550
+ 144 ForgotPasswordForm.tsx
1551
+ 206 ResetPasswordForm.tsx
1552
+ ```
1553
+
1554
+ **Step 2: Run Baseline Tests**
1555
+ ```bash
1556
+ # Save baseline results
1557
+ bun test test/auth > baseline-auth-tests.txt 2>&1
1558
+
1559
+ # Count passing tests
1560
+ grep -c "PASS" baseline-auth-tests.txt
1561
+ ```
1562
+
1563
+ **Expected:** 50+ passing tests
1564
+
1565
+ **Step 3: Create Migration Branch**
1566
+ ```bash
1567
+ git checkout -b feature/auth-migration-2-5
1568
+ git push -u origin feature/auth-migration-2-5
1569
+ ```
1570
+
1571
+ **Step 4: Create Rollback Tags**
1572
+ ```bash
1573
+ # Tag before any changes
1574
+ git tag rollback-pre-auth-migration
1575
+ git push --tags
1576
+ ```
1577
+
1578
+ **Step 5: Verify Dependencies**
1579
+ ```bash
1580
+ # Check DataProvider exists
1581
+ test -f src/providers/DataProvider.ts || echo "ERROR: DataProvider missing"
1582
+
1583
+ # Check hooks exist
1584
+ test -f src/providers/hooks/index.ts || echo "ERROR: hooks missing"
1585
+
1586
+ # Check ConvexAuthProvider exists
1587
+ grep -q "ConvexAuthProvider" src/providers/ConvexProvider.ts || echo "ERROR: Provider missing"
1588
+ ```
1589
+
1590
+ **Step 6-12: Create Auth Hook Infrastructure**
1591
+
1592
+ See full hook implementations in Appendix A.
1593
+
1594
+ ---
1595
+
1596
+ ### Phase 2: SimpleSignInForm Migration (Steps 13-17)
1597
+
1598
+ **Step 13: Backup Current File**
1599
+ ```bash
1600
+ cp src/components/auth/SimpleSignInForm.tsx src/components/auth/SimpleSignInForm.tsx.backup
1601
+ ```
1602
+
1603
+ **Step 14: Migrate SimpleSignInForm**
1604
+
1605
+ Apply BEFORE → AFTER changes shown in section 2.1 above.
1606
+
1607
+ **Step 15: Test SimpleSignInForm**
1608
+ ```bash
1609
+ # Run login tests only
1610
+ bun test test/auth/email-password.test.ts -t "login"
1611
+
1612
+ # Manual testing checklist:
1613
+ # 1. Login with valid credentials succeeds ✓
1614
+ # 2. Login with invalid credentials shows error ✓
1615
+ # 3. Login with non-existent email shows error ✓
1616
+ # 4. Loading state displays correctly ✓
1617
+ # 5. Success redirects to /account ✓
1618
+ # 6. Session persists after refresh ✓
1619
+ ```
1620
+
1621
+ **Quality Gate:** ALL login tests must pass. If >5 tests fail → ROLLBACK.
1622
+
1623
+ **Step 16: Compare Results**
1624
+ ```bash
1625
+ bun test test/auth > step16-results.txt 2>&1
1626
+ diff baseline-auth-tests.txt step16-results.txt
1627
+ ```
1628
+
1629
+ **Step 17: Commit SimpleSignInForm**
1630
+ ```bash
1631
+ git add src/components/auth/SimpleSignInForm.tsx
1632
+ git add src/providers/hooks/auth.ts
1633
+ git commit -m "feat(auth): migrate SimpleSignInForm to DataProvider
1634
+
1635
+ - Replace authClient.signIn.email() with useLogin() hook
1636
+ - Improve error handling with typed errors (_tag pattern)
1637
+ - Reduce code from 163 to 120 lines
1638
+ - Preserve all existing functionality
1639
+ - All login tests passing
1640
+
1641
+ TESTS: bun test test/auth/email-password.test.ts
1642
+ BREAKING: None
1643
+ "
1644
+ git tag rollback-post-signin-migration
1645
+ git push --tags
1646
+ ```
1647
+
1648
+ ---
1649
+
1650
+ ### Phase 3: SimpleSignUpForm Migration (Steps 18-22)
1651
+
1652
+ **Step 18: Backup**
1653
+ ```bash
1654
+ cp src/components/auth/SimpleSignUpForm.tsx src/components/auth/SimpleSignUpForm.tsx.backup
1655
+ ```
1656
+
1657
+ **Step 19: Migrate**
1658
+
1659
+ Apply BEFORE → AFTER changes from section 2.2.
1660
+
1661
+ **Step 20: Test**
1662
+ ```bash
1663
+ bun test test/auth/email-password.test.ts -t "signup"
1664
+ bun test test/auth
1665
+
1666
+ # Manual tests:
1667
+ # 1. Signup with new email succeeds ✓
1668
+ # 2. Signup with existing email shows error ✓
1669
+ # 3. Weak password shows error ✓
1670
+ # 4. Password strength indicator works ✓
1671
+ # 5. Success creates user + org membership ✓
1672
+ ```
1673
+
1674
+ **Step 21: Compare**
1675
+ ```bash
1676
+ bun test test/auth > step21-results.txt 2>&1
1677
+ diff baseline-auth-tests.txt step21-results.txt
1678
+ ```
1679
+
1680
+ **Step 22: Commit**
1681
+ ```bash
1682
+ git add src/components/auth/SimpleSignUpForm.tsx
1683
+ git commit -m "feat(auth): migrate SimpleSignUpForm to DataProvider
1684
+
1685
+ - Replace authClient.signUp.email() with useSignup() hook
1686
+ - Reduce code from 157 to 115 lines
1687
+ - Preserve password strength indicator
1688
+ - All signup tests passing
1689
+
1690
+ TESTS: bun test test/auth/email-password.test.ts
1691
+ "
1692
+ git tag rollback-post-signup-migration
1693
+ git push --tags
1694
+ ```
1695
+
1696
+ ---
1697
+
1698
+ ### Phase 4: MagicLinkAuth Migration (Steps 23-27)
1699
+
1700
+ **Step 23-27:** Follow same pattern as Phase 2-3.
1701
+
1702
+ **Quality Gate:** All magic link tests must pass.
1703
+
1704
+ ---
1705
+
1706
+ ### Phase 5: TwoFactorSettings Migration (Steps 28-32)
1707
+
1708
+ **Step 28-32:** Follow same pattern. This is the most complex component.
1709
+
1710
+ **Quality Gate:** All 2FA tests must pass (TOTP generation, QR codes, backup codes).
1711
+
1712
+ ---
1713
+
1714
+ ### Phase 6: VerifyEmailForm Migration (Steps 33-37)
1715
+
1716
+ **Step 33-37:** Follow same pattern.
1717
+
1718
+ **Quality Gate:** Email verification tests must pass.
1719
+
1720
+ ---
1721
+
1722
+ ### Phase 7: Password Reset Forms (Steps 38-45)
1723
+
1724
+ Migrate both ForgotPasswordForm and ResetPasswordForm.
1725
+
1726
+ **Quality Gate:** All password reset tests must pass.
1727
+
1728
+ ---
1729
+
1730
+ ### Phase 8: Final Validation (Steps 46-60)
1731
+
1732
+ **Step 46: Remove Direct Imports**
1733
+ ```bash
1734
+ # Find remaining direct imports
1735
+ grep -r "authClient" src/components/auth/
1736
+ grep -r "ConvexHttpClient" src/components/auth/
1737
+ grep -r "api\.auth" src/components/auth/
1738
+
1739
+ # Should return NO results
1740
+ ```
1741
+
1742
+ **Step 47: TypeScript Check**
1743
+ ```bash
1744
+ bunx astro check
1745
+
1746
+ # Expected: 0 errors
1747
+ ```
1748
+
1749
+ **Step 48: Full Test Suite**
1750
+ ```bash
1751
+ bun test test/auth > final-auth-tests.txt 2>&1
1752
+
1753
+ # Compare to baseline
1754
+ diff baseline-auth-tests.txt final-auth-tests.txt
1755
+
1756
+ # Count passing
1757
+ grep -c "PASS" final-auth-tests.txt
1758
+ ```
1759
+
1760
+ **Expected:** 50+ tests passing, same as baseline.
1761
+
1762
+ **Step 49: Performance Testing**
1763
+ ```bash
1764
+ # Measure login time
1765
+ time curl -X POST http://localhost:4321/api/auth/signin \
1766
+ -H "Content-Type: application/json" \
1767
+ -d '{"email":"test@example.com","password":"password123"}'
1768
+
1769
+ # Should complete in <2 seconds
1770
+ ```
1771
+
1772
+ **Step 50-60:** Documentation, cleanup, final review.
1773
+
1774
+ ---
1775
+
1776
+ ## 4. Rollback Plan
1777
+
1778
+ ### Level 1: Single Component Rollback
1779
+
1780
+ ```bash
1781
+ # Example: Rollback SimpleSignInForm
1782
+ git reset --hard rollback-pre-signin-migration
1783
+
1784
+ # Restore backup
1785
+ cp src/components/auth/SimpleSignInForm.tsx.backup src/components/auth/SimpleSignInForm.tsx
1786
+
1787
+ # Verify tests pass
1788
+ bun test test/auth/email-password.test.ts
1789
+ ```
1790
+
1791
+ **Time:** <5 minutes
1792
+
1793
+ ### Level 2: Full Feature Rollback
1794
+
1795
+ ```bash
1796
+ # Rollback to pre-migration state
1797
+ git reset --hard rollback-pre-auth-migration
1798
+
1799
+ # Verify all tests pass
1800
+ bun test test/auth
1801
+ diff baseline-auth-tests.txt current-tests.txt
1802
+ ```
1803
+
1804
+ **Time:** <10 minutes
1805
+
1806
+ ### Level 3: Feature Flag Rollback
1807
+
1808
+ Create environment variable to toggle between old and new:
1809
+
1810
+ ```bash
1811
+ # .env.local
1812
+ USE_NEW_AUTH_HOOKS=false # Use old authClient
1813
+ USE_NEW_AUTH_HOOKS=true # Use new DataProvider (default)
1814
+ ```
1815
+
1816
+ **Time:** <2 minutes (just change env var and restart)
1817
+
1818
+ ---
1819
+
1820
+ ## 5. Testing Strategy
1821
+
1822
+ ### Test Execution After Each Component
1823
+
1824
+ ```bash
1825
+ # Pattern:
1826
+ bun test test/auth/[specific-test].test.ts
1827
+ bun test test/auth # Full suite
1828
+
1829
+ # If >5 tests fail:
1830
+ # 1. Review errors
1831
+ # 2. Check DataProvider implementation
1832
+ # 3. Rollback to previous tag
1833
+ # 4. Investigate and fix
1834
+ # 5. Retry
1835
+ ```
1836
+
1837
+ ### Critical Test Cases (50+)
1838
+
1839
+ **Email/Password (20 tests):**
1840
+ - ✅ Login with valid credentials
1841
+ - ✅ Login with invalid password
1842
+ - ✅ Login with non-existent email
1843
+ - ✅ Signup with new email
1844
+ - ✅ Signup with existing email
1845
+ - ✅ Password strength validation
1846
+ - ✅ Session persistence
1847
+ - ✅ Logout functionality
1848
+
1849
+ **OAuth (10 tests):**
1850
+ - ✅ GitHub OAuth flow
1851
+ - ✅ Google OAuth flow
1852
+ - ✅ Account linking
1853
+ - ✅ OAuth error handling
1854
+
1855
+ **Magic Links (8 tests):**
1856
+ - ✅ Request magic link
1857
+ - ✅ Authenticate with valid token
1858
+ - ✅ Expired token (>15 min)
1859
+ - ✅ Used token (single-use)
1860
+ - ✅ Invalid token
1861
+
1862
+ **Password Reset (8 tests):**
1863
+ - ✅ Request reset
1864
+ - ✅ Reset with valid token
1865
+ - ✅ Expired token (>1 hour)
1866
+ - ✅ New password works
1867
+
1868
+ **Email Verification (4 tests):**
1869
+ - ✅ Verify with valid token
1870
+ - ✅ Expired token
1871
+ - ✅ Already verified
1872
+
1873
+ **2FA (8 tests):**
1874
+ - ✅ Enable 2FA
1875
+ - ✅ QR code generation
1876
+ - ✅ Backup codes
1877
+ - ✅ TOTP verification
1878
+ - ✅ Disable 2FA
1879
+
1880
+ ---
1881
+
1882
+ ## 6. Quality Gates
1883
+
1884
+ ### Mandatory Gates (MUST PASS)
1885
+
1886
+ 1. **All 50+ auth tests pass** ✅
1887
+ 2. **No direct Convex imports** ✅
1888
+ 3. **TypeScript compiles (0 errors)** ✅
1889
+ 4. **Performance within 10% baseline** ✅
1890
+ 5. **Zero functionality regression** ✅
1891
+
1892
+ ### Quality Metrics
1893
+
1894
+ - Code reduction: **~250 fewer lines** (1,248 → ~1,000)
1895
+ - Type safety: **100% typed errors** (no string checking)
1896
+ - Maintainability: **Cleaner hook-based code**
1897
+ - Testability: **Easier to mock providers**
1898
+
1899
+ ---
1900
+
1901
+ ## 7. Success Criteria
1902
+
1903
+ ✅ **All 50+ tests passing**
1904
+ ✅ **No direct authClient or Convex imports**
1905
+ ✅ **TypeScript clean (0 errors)**
1906
+ ✅ **Performance maintained**
1907
+ ✅ **Documentation updated**
1908
+ ✅ **Rollback plan tested**
1909
+
1910
+ **Sign-Off Requirements:**
1911
+ 1. Frontend Specialist approval
1912
+ 2. Quality Agent validation
1913
+ 3. All tests green
1914
+ 4. Performance benchmarks met
1915
+ 5. Code review complete
1916
+
1917
+ ---
1918
+
1919
+ ## Appendix A: Complete Hook Implementations
1920
+
1921
+ ### useLogin Hook
1922
+
1923
+ ```typescript
1924
+ // frontend/src/providers/hooks/auth.ts
1925
+ import { useState } from "react";
1926
+ import { useDataProvider } from "../DataProviderContext";
1927
+ import type { AuthResult, LoginArgs } from "../types";
1928
+
1929
+ export function useLogin() {
1930
+ const provider = useDataProvider();
1931
+ const [loading, setLoading] = useState(false);
1932
+ const [error, setError] = useState<Error | null>(null);
1933
+
1934
+ const mutate = async (args: LoginArgs): Promise<AuthResult> => {
1935
+ setLoading(true);
1936
+ setError(null);
1937
+
1938
+ try {
1939
+ const result = await provider.auth.login(args);
1940
+ setLoading(false);
1941
+ return result;
1942
+ } catch (err) {
1943
+ const error = err instanceof Error ? err : new Error(String(err));
1944
+ setError(error);
1945
+ setLoading(false);
1946
+ throw error;
1947
+ }
1948
+ };
1949
+
1950
+ return { mutate, loading, error };
1951
+ }
1952
+ ```
1953
+
1954
+ ### use2FA Hook
1955
+
1956
+ ```typescript
1957
+ export function use2FA() {
1958
+ const provider = useDataProvider();
1959
+ const [loading, setLoading] = useState(false);
1960
+ const [error, setError] = useState<Error | null>(null);
1961
+
1962
+ const getStatus = async (): Promise<{ enabled: boolean; hasSetup: boolean }> => {
1963
+ try {
1964
+ return await provider.auth.get2FAStatus();
1965
+ } catch (err) {
1966
+ throw err instanceof Error ? err : new Error(String(err));
1967
+ }
1968
+ };
1969
+
1970
+ const setup = async (): Promise<{ secret: string; backupCodes: string[] }> => {
1971
+ setLoading(true);
1972
+ setError(null);
1973
+
1974
+ try {
1975
+ const result = await provider.auth.setup2FA();
1976
+ setLoading(false);
1977
+ return result;
1978
+ } catch (err) {
1979
+ const error = err instanceof Error ? err : new Error(String(err));
1980
+ setError(error);
1981
+ setLoading(false);
1982
+ throw error;
1983
+ }
1984
+ };
1985
+
1986
+ const verify = async (code: string): Promise<void> => {
1987
+ setLoading(true);
1988
+ setError(null);
1989
+
1990
+ try {
1991
+ await provider.auth.verify2FA({ code });
1992
+ setLoading(false);
1993
+ } catch (err) {
1994
+ const error = err instanceof Error ? err : new Error(String(err));
1995
+ setError(error);
1996
+ setLoading(false);
1997
+ throw error;
1998
+ }
1999
+ };
2000
+
2001
+ const disable = async (password: string): Promise<void> => {
2002
+ setLoading(true);
2003
+ setError(null);
2004
+
2005
+ try {
2006
+ await provider.auth.disable2FA({ password });
2007
+ setLoading(false);
2008
+ } catch (err) {
2009
+ const error = err instanceof Error ? err : new Error(String(err));
2010
+ setError(error);
2011
+ setLoading(false);
2012
+ throw error;
2013
+ }
2014
+ };
2015
+
2016
+ return { getStatus, setup, verify, disable, loading, error };
2017
+ }
2018
+ ```
2019
+
2020
+ ---
2021
+
2022
+ ## Appendix B: Error Types
2023
+
2024
+ ```typescript
2025
+ // frontend/src/providers/types/auth-errors.ts
2026
+ export type AuthError =
2027
+ | { _tag: "InvalidCredentials"; message: string; suggestion: string }
2028
+ | { _tag: "UserNotFound"; message: string; suggestion: string }
2029
+ | { _tag: "EmailAlreadyExists"; message: string; suggestion: string }
2030
+ | { _tag: "WeakPassword"; message: string; suggestion: string }
2031
+ | { _tag: "InvalidToken"; message: string; suggestion: string }
2032
+ | { _tag: "TokenExpired"; message: string; suggestion: string }
2033
+ | { _tag: "NetworkError"; message: string; suggestion: string }
2034
+ | { _tag: "RateLimitExceeded"; message: string; suggestion: string }
2035
+ | { _tag: "EmailNotVerified"; message: string; suggestion: string }
2036
+ | { _tag: "TwoFactorRequired"; message: string; suggestion: string }
2037
+ | { _tag: "Invalid2FACode"; message: string; suggestion: string };
2038
+ ```
2039
+
2040
+ ---
2041
+
2042
+ **Total Specification Length:** 950+ lines
2043
+ **Status:** ✅ COMPLETE - Ready for Implementation
2044
+ **Next:** Wait for Feature 2-1 and 2-4 completion, then execute migration
2045
+
2046
+ **Critical Reminder:** ALL 50+ auth tests MUST pass. <5 failures = continue. >5 failures = STOP and ROLLBACK immediately.