diff --git a/apps/api/src/__tests__/routes/clientInvites.test.ts b/apps/api/src/__tests__/routes/clientInvites.test.ts index 17bfc08..5ffcefb 100644 --- a/apps/api/src/__tests__/routes/clientInvites.test.ts +++ b/apps/api/src/__tests__/routes/clientInvites.test.ts @@ -62,19 +62,23 @@ describe("Client Invites Endpoints", () => { { headers: { Authorization: `Bearer ${user.accessToken}` } } ); - const acceptInvite = (user: TestUserData, token: string) => - client["client-invites"].accept[":token"].$post( - { param: { token } }, - { headers: { Authorization: `Bearer ${user.accessToken}` } } - ); + const getSetupInvite = (token: string) => + client["client-invites"].setup[":token"].$get({ + param: { token }, + }); - // ─── Helper: insert a client_invite row directly via admin ────────────────── + const completeSetupInvite = (token: string, password: string) => + client["client-invites"].setup[":token"].$post({ + param: { token }, + json: { password }, + }); const insertClientInvite = async (opts: { tabloId: string; invitedEmail: string; invitedBy: string; token: string; + inviteType?: string; isPending?: boolean; expiresAt?: string; }) => { @@ -87,6 +91,7 @@ describe("Client Invites Endpoints", () => { invited_email: opts.invitedEmail, invited_by: opts.invitedBy, invite_token: opts.token, + invite_type: opts.inviteType ?? "setup", is_pending: opts.isPending ?? true, expires_at: expiresAt, }) @@ -97,11 +102,9 @@ describe("Client Invites Endpoints", () => { return data.id as number; }; - // ─── Cleanup helper ────────────────────────────────────────────────────────── - const cleanupInvitesByEmail = async (email: string) => { await supabaseAdmin.from("client_invites").delete().eq("invited_email", email); - // Also clean up any client user that may have been created + const { data: usersData } = await supabaseAdmin.auth.admin.listUsers(); // biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime const users = usersData as any; @@ -113,50 +116,118 @@ describe("Client Invites Endpoints", () => { } }; + const createClientAccount = async ( + email: string, + input?: { onboarded?: boolean; password?: string } + ) => { + const password = input?.password ?? "client_password_123"; + const { data: authData, error: authError } = await supabaseAdmin.auth.admin.createUser({ + email, + password, + email_confirm: true, + user_metadata: { role: "client" }, + }); + + if (authError || !authData?.user) { + throw new Error(`Failed to create client account: ${authError?.message}`); + } + + const updates: Record = { is_client: true }; + if (input?.onboarded) { + updates.client_onboarded_at = new Date().toISOString(); + } + + const { error: profileError } = await supabaseAdmin + .from("profiles") + .update(updates) + .eq("id", authData.user.id); + + if (profileError) { + throw new Error(`Failed to update client profile: ${profileError.message}`); + } + + return authData.user; + }; + // ════════════════════════════════════════════════════════════════════════════ // POST /:tabloId — Create client invite // ════════════════════════════════════════════════════════════════════════════ describe("POST /client-invites/:tabloId", () => { const testEmail = "test_client_invite_new@example.com"; + const existingClientEmail = "test_existing_client_invite@example.com"; beforeEach(async () => { await cleanupInvitesByEmail(testEmail); + await cleanupInvitesByEmail(existingClientEmail); }); - it("should create a client invite for a valid email (admin)", async () => { + it("creates a setup token for a first-time client invite", async () => { const res = await postInvite(ownerUser, adminTabloId, testEmail); expect(res.status).toBe(200); const data = await res.json(); expect(data.success).toBe(true); + expect(data.inviteMode).toBe("setup"); - // Verify row was inserted const { data: invite } = await supabaseAdmin .from("client_invites") - .select("id, invited_email, is_pending") + .select("id, invited_email, is_pending, invite_token, invite_type") .eq("tablo_id", adminTabloId) .eq("invited_email", testEmail) .single(); expect(invite).toBeDefined(); expect(invite?.is_pending).toBe(true); + expect(invite?.invite_token).toBeTruthy(); + expect(invite?.invite_type).toBe("setup"); + expect(mockSendMail).toHaveBeenCalledTimes(1); + expect(mockSendMail.mock.calls[0]?.[0]?.html).toContain("/set-password?token="); }); - it("should reject temporary users before admin check", async () => { - // tempUser is NOT admin of adminTabloId (owner user owns it) + it("sends an access notification for an already-onboarded client", async () => { + await createClientAccount(existingClientEmail, { onboarded: true }); + + const res = await postInvite(ownerUser, adminTabloId, existingClientEmail); + + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.success).toBe(true); + expect(data.inviteMode).toBe("notification"); + + const { data: invite } = await supabaseAdmin + .from("client_invites") + .select("id") + .eq("tablo_id", adminTabloId) + .eq("invited_email", existingClientEmail) + .maybeSingle(); + + expect(invite).toBeNull(); + expect(mockSendMail).toHaveBeenCalledTimes(1); + expect(mockSendMail.mock.calls[0]?.[0]?.html).toContain(`/tablo/${adminTabloId}`); + }); + + it("rejects emails already used by a main-app account", async () => { + const res = await postInvite(ownerUser, adminTabloId, ownerUser.email); + + expect(res.status).toBe(409); + const data = await res.json(); + expect(data.error).toContain("already belongs"); + }); + + it("rejects temporary users before admin check", async () => { const res = await postInvite(tempUser, adminTabloId, testEmail); expect(res.status).toBe(401); }); - it("should return 400 for an invalid email", async () => { + it("returns 400 for an invalid email", async () => { const res = await postInvite(ownerUser, adminTabloId, "not-an-email"); expect(res.status).toBe(400); const data = await res.json(); expect(data.error).toContain("valid email"); }); - it("should return 400 for a missing email", async () => { + it("returns 400 for a missing email", async () => { const res = client["client-invites"][":tabloId"].$post( { param: { tabloId: adminTabloId }, json: {} }, { headers: { Authorization: `Bearer ${ownerUser.accessToken}` } } @@ -164,7 +235,7 @@ describe("Client Invites Endpoints", () => { expect((await res).status).toBe(400); }); - it("should return 401 for unauthenticated requests", async () => { + it("returns 401 for unauthenticated requests", async () => { const res = await client["client-invites"][":tabloId"].$post({ param: { tabloId: adminTabloId }, json: { email: testEmail }, @@ -174,54 +245,50 @@ describe("Client Invites Endpoints", () => { }); // ════════════════════════════════════════════════════════════════════════════ - // POST /accept/:token — Accept a client invite + // GET/POST /setup/:token — Validate and complete a client setup invite // ════════════════════════════════════════════════════════════════════════════ - describe("POST /client-invites/accept/:token", () => { - it("should accept an invite and return tabloId", async () => { - const token = `test_accept_valid_${Date.now()}`; + describe("GET/POST /client-invites/setup/:token", () => { + const setupEmail = "test_client_setup@example.com"; - // Insert invite for the owner user's email + beforeEach(async () => { + await cleanupInvitesByEmail(setupEmail); + }); + + it("returns invite metadata for a valid pending setup token", async () => { + const token = `test_setup_valid_${Date.now()}`; await insertClientInvite({ tabloId: adminTabloId, - invitedEmail: ownerUser.email, + invitedEmail: setupEmail, invitedBy: ownerUser.userId, token, }); try { - const res = await acceptInvite(ownerUser, token); + const res = await getSetupInvite(token); expect(res.status).toBe(200); const data = await res.json(); - expect(data.success).toBe(true); + expect(data.email).toBe(setupEmail); expect(data.tabloId).toBe(adminTabloId); - - // Verify invite is now not pending - const { data: invite } = await supabaseAdmin - .from("client_invites") - .select("is_pending") - .eq("invite_token", token) - .single(); - expect(invite?.is_pending).toBe(false); } finally { await supabaseAdmin.from("client_invites").delete().eq("invite_token", token); } }); - it("should return 410 for an expired invite", async () => { + it("returns 410 for an expired invite", async () => { const token = `test_expired_${Date.now()}`; - const pastDate = new Date(Date.now() - 1000).toISOString(); // already expired + const pastDate = new Date(Date.now() - 1000).toISOString(); await insertClientInvite({ tabloId: adminTabloId, - invitedEmail: ownerUser.email, + invitedEmail: setupEmail, invitedBy: ownerUser.userId, token, expiresAt: pastDate, }); try { - const res = await acceptInvite(ownerUser, token); + const res = await getSetupInvite(token); expect(res.status).toBe(410); const data = await res.json(); expect(data.error).toContain("expired"); @@ -230,35 +297,50 @@ describe("Client Invites Endpoints", () => { } }); - it("should return 403 when email does not match the authenticated user", async () => { - const token = `test_email_mismatch_${Date.now()}`; - - // Invite is for tempUser's email but we authenticate as ownerUser + it("completes password setup once and rejects reuse", async () => { + const token = `test_setup_complete_${Date.now()}`; + await createClientAccount(setupEmail); await insertClientInvite({ tabloId: adminTabloId, - invitedEmail: tempUser.email, + invitedEmail: setupEmail, invitedBy: ownerUser.userId, token, }); try { - const res = await acceptInvite(ownerUser, token); // wrong user - expect(res.status).toBe(403); + const res = await completeSetupInvite(token, "new_password_123"); + expect(res.status).toBe(200); + const data = await res.json(); + expect(data.success).toBe(true); + expect(data.email).toBe(setupEmail); + expect(data.tabloId).toBe(adminTabloId); + + const reused = await completeSetupInvite(token, "new_password_456"); + expect(reused.status).toBe(404); } finally { await supabaseAdmin.from("client_invites").delete().eq("invite_token", token); } }); - it("should return 404 for a non-existent token", async () => { - const res = await acceptInvite(ownerUser, "nonexistent_token_xyz"); + it("returns 404 for a non-existent token", async () => { + const res = await getSetupInvite("nonexistent_token_xyz"); expect(res.status).toBe(404); }); - it("should return 401 for unauthenticated requests", async () => { - const res = await client["client-invites"].accept[":token"].$post({ - param: { token: "some_token" }, + it("marks cancelled pending setup tokens unusable", async () => { + const token = `test_setup_cancelled_${Date.now()}`; + const inviteId = await insertClientInvite({ + tabloId: adminTabloId, + invitedEmail: setupEmail, + invitedBy: ownerUser.userId, + token, }); - expect(res.status).toBe(401); + + const cancelRes = await deleteInvite(ownerUser, adminTabloId, inviteId); + expect(cancelRes.status).toBe(200); + + const res = await getSetupInvite(token); + expect(res.status).toBe(404); }); }); @@ -280,7 +362,7 @@ describe("Client Invites Endpoints", () => { }); }); - it("should return pending invites for an admin", async () => { + it("returns pending invites for an admin", async () => { const res = await getPending(ownerUser, adminTabloId); expect(res.status).toBe(200); const data = await res.json(); @@ -292,12 +374,12 @@ describe("Client Invites Endpoints", () => { expect(found.is_pending).toBe(true); }); - it("should return 401 for a temporary user before admin check", async () => { + it("returns 401 for a temporary user before admin check", async () => { const res = await getPending(tempUser, adminTabloId); expect(res.status).toBe(401); }); - it("should return 401 for unauthenticated requests", async () => { + it("returns 401 for unauthenticated requests", async () => { const res = await client["client-invites"][":tabloId"].pending.$get({ param: { tabloId: adminTabloId }, }); @@ -316,8 +398,7 @@ describe("Client Invites Endpoints", () => { await cleanupInvitesByEmail(cancelEmail); }); - it("should cancel a pending invite and revoke client access", async () => { - // First create a client user and tablo_access entry via the API + it("cancels a pending invite and revokes client access", async () => { const token = `test_cancel_${Date.now()}`; const inviteId = await insertClientInvite({ tabloId: adminTabloId, @@ -326,14 +407,11 @@ describe("Client Invites Endpoints", () => { token, }); - // Create a mock profile to revoke (uses admin client to simulate client user existing) - // We'll skip verifying the user's actual auth account since we just need to test cancellation const res = await deleteInvite(ownerUser, adminTabloId, inviteId); expect(res.status).toBe(200); const data = await res.json(); expect(data.success).toBe(true); - // Verify invite is now not pending const { data: invite } = await supabaseAdmin .from("client_invites") .select("is_pending") @@ -342,7 +420,7 @@ describe("Client Invites Endpoints", () => { expect(invite?.is_pending).toBe(false); }); - it("should return 401 for a temporary user before admin check", async () => { + it("returns 401 for a temporary user before admin check", async () => { const token = `test_cancel_nonadmin_${Date.now()}`; const inviteId = await insertClientInvite({ tabloId: adminTabloId, @@ -355,19 +433,19 @@ describe("Client Invites Endpoints", () => { expect(res.status).toBe(401); }); - it("should return 404 for a non-existent invite", async () => { + it("returns 404 for a non-existent invite", async () => { const res = await deleteInvite(ownerUser, adminTabloId, 999999); expect(res.status).toBe(404); }); - it("should return 400 for an already-cancelled invite", async () => { + it("returns 400 for an already-cancelled invite", async () => { const token = `test_cancel_already_${Date.now()}`; const inviteId = await insertClientInvite({ tabloId: adminTabloId, invitedEmail: cancelEmail, invitedBy: ownerUser.userId, token, - isPending: false, // already cancelled + isPending: false, }); const res = await deleteInvite(ownerUser, adminTabloId, inviteId); @@ -376,7 +454,7 @@ describe("Client Invites Endpoints", () => { expect(data.error).toContain("pending"); }); - it("should return 401 for unauthenticated requests", async () => { + it("returns 401 for unauthenticated requests", async () => { const res = await client["client-invites"][":tabloId"][":inviteId"].$delete({ param: { tabloId: adminTabloId, inviteId: "1" }, }); diff --git a/apps/api/src/helpers/helpers.ts b/apps/api/src/helpers/helpers.ts index f559288..99a3acb 100644 --- a/apps/api/src/helpers/helpers.ts +++ b/apps/api/src/helpers/helpers.ts @@ -364,67 +364,193 @@ export const createInvitedUser = async ( return { success: true, userId: newUser.user.id }; }; -/** - * Creates or finds a client user, marks them as is_client, and grants tablo access. - */ -export async function createClientUser( - supabase: SupabaseClient, - recipientEmail: string, - tabloId: string, - grantedBy: string -): Promise<{ success: boolean; error?: string; userId?: string }> { - // Check if user already exists - const { data: existingUsersData } = await supabase.auth.admin.listUsers(); +type ClientAccount = { + email: string; + is_client: boolean; + client_onboarded_at: string | null; + userId: string; +}; + +type ClientAccountResult = + | { success: true; account: ClientAccount; wasCreated: boolean } + | { success: false; error: string }; + +const getAuthUserByEmail = async (supabase: SupabaseClient, email: string) => { + const { data: existingUsersData, error } = await supabase.auth.admin.listUsers(); + if (error) { + return { user: null, error: error.message }; + } + // biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime const existingUsers = existingUsersData as any; const existingUser = existingUsers?.users?.find( // biome-ignore lint/suspicious/noExplicitAny: admin user type - (u: any) => u.email?.toLowerCase() === recipientEmail.toLowerCase() + (u: any) => u.email?.toLowerCase() === email.toLowerCase() ); - let userId: string; + return { user: existingUser ?? null, error: null }; +}; - if (existingUser) { - userId = existingUser.id; - // Mark as client if not already - await supabase - .from("profiles") - .update({ is_client: true }) - .eq("id", userId) - .eq("is_client", false); - } else { - // Create new auth user (no password — magic link only) - const { data: authData, error: authError } = await supabase.auth.admin.createUser({ - email: recipientEmail, - email_confirm: true, - user_metadata: { role: "client" }, - }); - if (authError || !authData?.user) { - return { success: false, error: authError?.message ?? "Failed to create user" }; - } - userId = authData.user.id; - await supabase.from("profiles").update({ is_client: true }).eq("id", userId); +export async function hasCompletedClientOnboarding( + supabase: SupabaseClient, + userId: string +): Promise<{ completed: boolean; error?: string }> { + const { data: profile, error } = await supabase + .from("profiles") + .select("client_onboarded_at") + .eq("id", userId) + .maybeSingle(); + + if (error) { + return { completed: false, error: error.message }; } - // Grant tablo access if not already granted - const { data: existingAccess } = await supabase + return { completed: !!profile?.client_onboarded_at }; +} + +export async function findOrCreateClientAccount( + supabase: SupabaseClient, + recipientEmail: string +): Promise { + const normalizedEmail = recipientEmail.trim().toLowerCase(); + const { user: existingUser, error: lookupError } = await getAuthUserByEmail(supabase, normalizedEmail); + + if (lookupError) { + return { success: false, error: lookupError }; + } + + if (existingUser) { + const { data: existingProfile, error: profileError } = await supabase + .from("profiles") + .select("email, is_client, client_onboarded_at") + .eq("id", existingUser.id) + .maybeSingle(); + + if (profileError) { + return { success: false, error: profileError.message }; + } + + if (!existingProfile) { + return { success: false, error: "Client profile not found" }; + } + + if (!existingProfile.is_client) { + return { + success: false, + error: "This email already belongs to a main app account", + }; + } + + return { + success: true, + wasCreated: false, + account: { + email: existingProfile.email ?? normalizedEmail, + is_client: existingProfile.is_client, + client_onboarded_at: existingProfile.client_onboarded_at, + userId: existingUser.id, + }, + }; + } + + const { data: authData, error: authError } = await supabase.auth.admin.createUser({ + email: normalizedEmail, + email_confirm: true, + user_metadata: { role: "client" }, + }); + + if (authError || !authData?.user) { + return { success: false, error: authError?.message ?? "Failed to create client user" }; + } + + const { error: updateProfileError } = await supabase + .from("profiles") + .update({ is_client: true, client_onboarded_at: null }) + .eq("id", authData.user.id); + + if (updateProfileError) { + return { success: false, error: updateProfileError.message }; + } + + return { + success: true, + wasCreated: true, + account: { + email: normalizedEmail, + is_client: true, + client_onboarded_at: null, + userId: authData.user.id, + }, + }; +} + +export async function ensureClientTabloAccess( + supabase: SupabaseClient, + tabloId: string, + userId: string, + grantedBy: string +): Promise<{ success: boolean; error?: string }> { + const { data: existingAccess, error: accessError } = await supabase .from("tablo_access") .select("id, is_active") .eq("tablo_id", tabloId) .eq("user_id", userId) - .single(); + .maybeSingle(); + + if (accessError) { + return { success: false, error: accessError.message }; + } if (!existingAccess) { - await supabase.from("tablo_access").insert({ + const { error: insertError } = await supabase.from("tablo_access").insert({ tablo_id: tabloId, user_id: userId, granted_by: grantedBy, is_admin: false, is_active: true, }); - } else if (!existingAccess.is_active) { - await supabase.from("tablo_access").update({ is_active: true }).eq("id", existingAccess.id); + if (insertError) { + return { success: false, error: insertError.message }; + } + return { success: true }; } - return { success: true, userId }; + if (!existingAccess.is_active) { + const { error: updateError } = await supabase + .from("tablo_access") + .update({ is_active: true }) + .eq("id", existingAccess.id); + if (updateError) { + return { success: false, error: updateError.message }; + } + } + + return { success: true }; +} + +export async function createClientSetupInvite( + supabase: SupabaseClient, + input: { + tabloId: string; + invitedEmail: string; + invitedBy: string; + token: string; + expiresAt: string; + } +): Promise<{ success: boolean; error?: string }> { + const { error } = await supabase.from("client_invites").insert({ + tablo_id: input.tabloId, + invited_email: input.invitedEmail, + invited_by: input.invitedBy, + invite_token: input.token, + invite_type: "setup", + is_pending: true, + expires_at: input.expiresAt, + }); + + if (error) { + return { success: false, error: error.message }; + } + + return { success: true }; } diff --git a/apps/api/src/routers/clientInvites.ts b/apps/api/src/routers/clientInvites.ts index f14f977..d42da4c 100644 --- a/apps/api/src/routers/clientInvites.ts +++ b/apps/api/src/routers/clientInvites.ts @@ -1,19 +1,97 @@ import { Hono } from "hono"; import { createFactory } from "hono/factory"; -import { checkTabloAdmin, createClientUser } from "../helpers/helpers.js"; +import { + checkTabloAdmin, + createClientSetupInvite, + ensureClientTabloAccess, + findOrCreateClientAccount, +} from "../helpers/helpers.js"; import { generateToken } from "../helpers/token.js"; import { MiddlewareManager } from "../middlewares/middleware.js"; -import type { AuthEnv } from "../types/app.types.js"; +import type { AuthEnv, BaseEnv } from "../types/app.types.js"; -const factory = createFactory(); +const authFactory = createFactory(); +const publicFactory = createFactory(); const CLIENT_INVITE_EXPIRY_HOURS = 72; +const getClientsUrl = () => process.env.CLIENTS_URL || "https://clients.xtablo.com"; + +const isValidEmail = (value: string) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value); + +const findInviteByToken = async (token: string, supabase: BaseEnv["Variables"]["supabase"]) => + supabase + .from("client_invites") + .select( + "id, tablo_id, invited_email, invited_by, invite_type, is_pending, expires_at, used_at, cancelled_at, setup_completed_at" + ) + .eq("invite_token", token) + .maybeSingle(); + +const validateSetupInvite = async (token: string, supabase: BaseEnv["Variables"]["supabase"]) => { + const { data: invite, error } = await findInviteByToken(token, supabase); + + if (error) { + return { status: 500 as const, body: { error: error.message } }; + } + + if (!invite || invite.invite_type !== "setup" || !invite.is_pending) { + return { status: 404 as const, body: { error: "Invite not found or already used" } }; + } + + if (invite.cancelled_at || invite.used_at || invite.setup_completed_at) { + return { status: 404 as const, body: { error: "Invite not found or already used" } }; + } + + if (invite.expires_at && new Date(invite.expires_at) < new Date()) { + return { status: 410 as const, body: { error: "This invite has expired" } }; + } + + return { status: 200 as const, invite }; +}; + +const sendSetupEmail = async ( + transporter: BaseEnv["Variables"]["transporter"], + input: { email: string; setupUrl: string } +) => { + await transporter.sendMail({ + from: "Xtablo ", + to: input.email, + subject: "Configurez votre accès client Xtablo", + html: ` +

Vous avez été invité sur Xtablo

+

Bonjour,

+

Créez votre mot de passe via le lien ci-dessous pour accéder à votre espace client :

+

Configurer mon mot de passe

+

Ce lien expire dans ${CLIENT_INVITE_EXPIRY_HOURS} heures et ne peut être utilisé qu'une seule fois.

+ `, + }); +}; + +const sendAccessNotificationEmail = async ( + transporter: BaseEnv["Variables"]["transporter"], + input: { email: string; tabloUrl: string } +) => { + await transporter.sendMail({ + from: "Xtablo ", + to: input.email, + subject: "Vous avez maintenant accès à un nouveau tablo", + html: ` +

Vous avez maintenant accès à un tablo

+

Bonjour,

+

Votre accès a été ajouté. Utilisez le lien ci-dessous pour ouvrir directement le tablo :

+

Ouvrir le tablo

+

Si vous n'êtes pas connecté, vous serez redirigé vers la page de connexion.

+ `, + }); +}; + /** POST /:tabloId — Create a client invite (admin only) */ const createClientInvite = (middlewareManager: ReturnType) => - factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { + authFactory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const user = c.get("user"); const supabase = c.get("supabase"); + const transporter = c.get("transporter"); const tabloId = c.req.param("tabloId"); const body = await c.req.json(); @@ -21,14 +99,42 @@ const createClientInvite = (middlewareManager: ReturnType", - to: rawEmail, - subject: "Vous avez été invité sur Xtablo", - html: ` -

Vous avez été invité à collaborer sur un tablo

-

Bonjour,

-

Cliquez sur le lien ci-dessous pour accéder à votre espace client :

-

Accéder à mon espace

-

Ce lien expire dans ${CLIENT_INVITE_EXPIRY_HOURS} heures.

- `, - }); - } catch (emailError) { - console.error("Failed to send client invite email:", emailError); - } + try { + await sendSetupEmail(transporter, { + email: rawEmail, + setupUrl: `${clientsUrl}/set-password?token=${encodeURIComponent(token)}`, + }); + } catch (emailError) { + console.error("Failed to send client setup email:", emailError); } - return c.json({ success: true }); + return c.json({ success: true, inviteMode: "setup" as const }); }); -/** POST /accept/:token — Accept a client invite */ -const acceptClientInvite = (_middlewareManager: ReturnType) => - factory.createHandlers(async (c) => { - const user = c.get("user"); +/** GET /setup/:token — Validate a setup invite token */ +const getSetupInvite = () => + publicFactory.createHandlers(async (c) => { const supabase = c.get("supabase"); const token = c.req.param("token"); - const { data: invite, error: inviteError } = await supabase + const validation = await validateSetupInvite(token, supabase); + if (validation.status !== 200) { + return c.json(validation.body, validation.status); + } + + return c.json({ + email: validation.invite.invited_email, + tabloId: validation.invite.tablo_id, + }); + }); + +/** POST /setup/:token — Complete one-time password setup */ +const completeSetupInvite = () => + publicFactory.createHandlers(async (c) => { + const supabase = c.get("supabase"); + const token = c.req.param("token"); + const body = await c.req.json(); + const password = String(body.password || ""); + + if (password.length < 8) { + return c.json({ error: "Password must be at least 8 characters long" }, 400); + } + + const validation = await validateSetupInvite(token, supabase); + if (validation.status !== 200) { + return c.json(validation.body, validation.status); + } + + const invite = validation.invite; + const { data: usersData, error: listUsersError } = await supabase.auth.admin.listUsers(); + if (listUsersError) { + return c.json({ error: listUsersError.message }, 500); + } + + // biome-ignore lint/suspicious/noExplicitAny: admin.listUsers returns typed data at runtime + const users = usersData as any; + // biome-ignore lint/suspicious/noExplicitAny: admin user type + const clientUser = users?.users?.find((candidate: any) => { + return candidate.email?.toLowerCase() === invite.invited_email?.toLowerCase(); + }); + + if (!clientUser?.id) { + return c.json({ error: "Client account not found" }, 404); + } + + const { error: updateUserError } = await supabase.auth.admin.updateUserById(clientUser.id, { + password, + }); + if (updateUserError) { + return c.json({ error: updateUserError.message }, 500); + } + + const completedAt = new Date().toISOString(); + + const { error: updateProfileError } = await supabase + .from("profiles") + .update({ client_onboarded_at: completedAt, is_client: true }) + .eq("id", clientUser.id); + if (updateProfileError) { + return c.json({ error: updateProfileError.message }, 500); + } + + const { error: consumeInviteError } = await supabase .from("client_invites") - .select("id, tablo_id, invited_email, invited_by, is_pending, expires_at") - .eq("invite_token", token) - .maybeSingle(); - - if (inviteError) { - return c.json({ error: inviteError.message }, 500); + .update({ + is_pending: false, + used_at: completedAt, + setup_completed_at: completedAt, + }) + .eq("id", invite.id) + .eq("is_pending", true); + if (consumeInviteError) { + return c.json({ error: consumeInviteError.message }, 500); } - if (!invite || !invite.is_pending) { - return c.json({ error: "Invite not found or already used" }, 404); - } - - // Check expiration - if (invite.expires_at && new Date(invite.expires_at) < new Date()) { - return c.json({ error: "This invite has expired" }, 410); - } - - // Email must match the authenticated user - if (invite.invited_email?.toLowerCase() !== user.email?.toLowerCase()) { - return c.json({ error: "This invite was not issued to your account" }, 403); - } - - // Mark invite as accepted - await supabase.from("client_invites").update({ is_pending: false }).eq("id", invite.id); - - // Ensure tablo access is active - const { data: existingAccess } = await supabase - .from("tablo_access") - .select("id, is_active") - .eq("tablo_id", invite.tablo_id) - .eq("user_id", user.id) - .maybeSingle(); - - if (!existingAccess) { - await supabase.from("tablo_access").insert({ - tablo_id: invite.tablo_id, - user_id: user.id, - granted_by: invite.invited_by, - is_admin: false, - is_active: true, - }); - } else if (!existingAccess.is_active) { - await supabase.from("tablo_access").update({ is_active: true }).eq("id", existingAccess.id); - } - - return c.json({ success: true, tabloId: invite.tablo_id }); + return c.json({ + success: true, + email: invite.invited_email, + tabloId: invite.tablo_id, + }); }); /** GET /:tabloId/pending — List pending client invites (admin only) */ const getPendingClientInvites = ( middlewareManager: ReturnType ) => - factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { + authFactory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const supabase = c.get("supabase"); const tabloId = c.req.param("tabloId"); const { data: invites, error } = await supabase .from("client_invites") - .select("id, invited_email, expires_at, is_pending, created_at") + .select("id, invited_email, expires_at, is_pending, created_at, invite_type") .eq("tablo_id", tabloId) + .eq("invite_type", "setup") .eq("is_pending", true) .order("created_at", { ascending: false }); @@ -169,7 +282,7 @@ const getPendingClientInvites = ( /** DELETE /:tabloId/:inviteId — Cancel a client invite (admin only) */ const cancelClientInvite = (middlewareManager: ReturnType) => - factory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { + authFactory.createHandlers(middlewareManager.regularUserCheck, checkTabloAdmin, async (c) => { const supabase = c.get("supabase"); const tabloId = c.req.param("tabloId"); const inviteId = Number(c.req.param("inviteId")); @@ -180,7 +293,7 @@ const cancelClientInvite = (middlewareManager: ReturnType { const middlewareManager = MiddlewareManager.getInstance(); router.post("/:tabloId", ...createClientInvite(middlewareManager)); - router.post("/accept/:token", ...acceptClientInvite(middlewareManager)); router.get("/:tabloId/pending", ...getPendingClientInvites(middlewareManager)); router.delete("/:tabloId/:inviteId", ...cancelClientInvite(middlewareManager)); return router; }; + +export const getPublicClientInvitesRouter = () => { + const router = new Hono(); + + router.get("/setup/:token", ...getSetupInvite()); + router.post("/setup/:token", ...completeSetupInvite()); + + return router; +}; diff --git a/apps/api/src/routers/maybeAuthRouter.ts b/apps/api/src/routers/maybeAuthRouter.ts index 7da5c8e..b01a6c5 100644 --- a/apps/api/src/routers/maybeAuthRouter.ts +++ b/apps/api/src/routers/maybeAuthRouter.ts @@ -1,6 +1,7 @@ import { Hono } from "hono"; import { MiddlewareManager } from "../middlewares/middleware.js"; import type { MaybeAuthEnv } from "../types/app.types.js"; +import { getPublicClientInvitesRouter } from "./clientInvites.js"; import { getBookingRouter } from "./invite.js"; export const getMaybeAuthenticatedRouter = () => { @@ -11,6 +12,7 @@ export const getMaybeAuthenticatedRouter = () => { maybeAuthenticated.use(middlewareManager.maybeAuthenticated); maybeAuthenticated.route("/book", getBookingRouter()); + maybeAuthenticated.route("/client-invites", getPublicClientInvitesRouter()); return maybeAuthenticated; }; diff --git a/apps/clients/package.json b/apps/clients/package.json index 68c5563..699fa82 100644 --- a/apps/clients/package.json +++ b/apps/clients/package.json @@ -39,6 +39,7 @@ }, "dependencies": { "@tanstack/react-query": "^5.69.0", + "@xtablo/auth-ui": "workspace:*", "@xtablo/shared": "workspace:*", "@xtablo/shared-types": "workspace:*", "@xtablo/tablo-views": "workspace:*", diff --git a/apps/clients/src/components/ClientAuthGate.tsx b/apps/clients/src/components/ClientAuthGate.tsx new file mode 100644 index 0000000..4c75eda --- /dev/null +++ b/apps/clients/src/components/ClientAuthGate.tsx @@ -0,0 +1,56 @@ +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { useEffect, useState } from "react"; +import { Navigate, Outlet, useLocation } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +export function ClientAuthGate() { + const { session } = useSession(); + const location = useLocation(); + const [isCheckingSession, setIsCheckingSession] = useState(true); + const [hasSession, setHasSession] = useState(false); + + useEffect(() => { + let isMounted = true; + + if (session) { + setHasSession(true); + setIsCheckingSession(false); + return () => { + isMounted = false; + }; + } + + supabase.auth + .getSession() + .then(({ data }) => { + if (!isMounted) return; + setHasSession(Boolean(data.session)); + }) + .finally(() => { + if (isMounted) { + setIsCheckingSession(false); + } + }); + + return () => { + isMounted = false; + }; + }, [session]); + + if (session || hasSession) { + return ; + } + + if (isCheckingSession) { + return ( +
+
+
+ ); + } + + const redirectUrl = `${location.pathname}${location.search}${location.hash}`; + localStorage.setItem("clients.redirectUrl", redirectUrl); + + return ; +} diff --git a/apps/clients/src/components/ClientLayout.test.tsx b/apps/clients/src/components/ClientLayout.test.tsx index 17c3972..709a0c0 100644 --- a/apps/clients/src/components/ClientLayout.test.tsx +++ b/apps/clients/src/components/ClientLayout.test.tsx @@ -1,4 +1,6 @@ +import { screen } from "@testing-library/react"; import { describe, expect, it } from "vitest"; +import AppRoutes from "../routes"; import { renderWithProviders } from "../test/testHelpers"; import { ClientLayout } from "./ClientLayout"; @@ -20,4 +22,14 @@ describe("ClientLayout", () => { expect(main).toHaveClass("max-w-7xl"); expect(main).toHaveClass("mx-auto"); }); + + it("redirects unauthenticated client routes to the login page", async () => { + renderWithProviders(, { + route: "/tablo/tablo-1", + testUser: undefined, + }); + + expect(await screen.findByTestId("auth-card-shell")).toBeInTheDocument(); + expect(await screen.findByRole("button", { name: "Connexion" })).toBeInTheDocument(); + }); }); diff --git a/apps/clients/src/components/ClientLayout.tsx b/apps/clients/src/components/ClientLayout.tsx index 16609cf..5ef32f4 100644 --- a/apps/clients/src/components/ClientLayout.tsx +++ b/apps/clients/src/components/ClientLayout.tsx @@ -14,19 +14,7 @@ function getInitials(email: string): string { export function ClientLayout() { const { session } = useSession(); - - if (!session) { - return ( -
-
-

Accès non autorisé

-

- Veuillez utiliser le lien reçu dans votre email pour accéder à cette page. -

-
-
- ); - } + if (!session) return null; const email = session.user.email ?? ""; const initials = email ? getInitials(email) : "?"; diff --git a/apps/clients/src/i18n.test.ts b/apps/clients/src/i18n.test.ts index e7747d7..7ca4e6c 100644 --- a/apps/clients/src/i18n.test.ts +++ b/apps/clients/src/i18n.test.ts @@ -2,11 +2,13 @@ import i18n from "i18next"; import { initReactI18next } from "react-i18next"; import bookingEn from "./locales/en/booking.json"; import bookingFr from "./locales/fr/booking.json"; +import authEn from "../../main/src/locales/en/auth.json"; import chatEn from "../../main/src/locales/en/chat.json"; import commonEn from "../../main/src/locales/en/common.json"; import componentsEn from "../../main/src/locales/en/components.json"; import pagesEn from "../../main/src/locales/en/pages.json"; import tabloEn from "../../main/src/locales/en/tablo.json"; +import authFr from "../../main/src/locales/fr/auth.json"; import chatFr from "../../main/src/locales/fr/chat.json"; import commonFr from "../../main/src/locales/fr/common.json"; import componentsFr from "../../main/src/locales/fr/components.json"; @@ -16,6 +18,7 @@ import tabloFr from "../../main/src/locales/fr/tablo.json"; i18n.use(initReactI18next).init({ resources: { fr: { + auth: authFr, booking: bookingFr, chat: chatFr, common: commonFr, @@ -24,6 +27,7 @@ i18n.use(initReactI18next).init({ tablo: tabloFr, }, en: { + auth: authEn, booking: bookingEn, chat: chatEn, common: commonEn, diff --git a/apps/clients/src/i18n.ts b/apps/clients/src/i18n.ts index 5612ccd..92423b4 100644 --- a/apps/clients/src/i18n.ts +++ b/apps/clients/src/i18n.ts @@ -4,11 +4,13 @@ import { initReactI18next } from "react-i18next"; import bookingEn from "./locales/en/booking.json"; // Import translation files import bookingFr from "./locales/fr/booking.json"; +import authEn from "../../main/src/locales/en/auth.json"; import chatEn from "../../main/src/locales/en/chat.json"; import commonEn from "../../main/src/locales/en/common.json"; import componentsEn from "../../main/src/locales/en/components.json"; import pagesEn from "../../main/src/locales/en/pages.json"; import tabloEn from "../../main/src/locales/en/tablo.json"; +import authFr from "../../main/src/locales/fr/auth.json"; import chatFr from "../../main/src/locales/fr/chat.json"; import commonFr from "../../main/src/locales/fr/common.json"; import componentsFr from "../../main/src/locales/fr/components.json"; @@ -21,6 +23,7 @@ i18n .init({ resources: { fr: { + auth: authFr, booking: bookingFr, chat: chatFr, common: commonFr, @@ -29,6 +32,7 @@ i18n tablo: tabloFr, }, en: { + auth: authEn, booking: bookingEn, chat: chatEn, common: commonEn, diff --git a/apps/clients/src/pages/AuthCallback.tsx b/apps/clients/src/pages/AuthCallback.tsx index b34427b..806d3cb 100644 --- a/apps/clients/src/pages/AuthCallback.tsx +++ b/apps/clients/src/pages/AuthCallback.tsx @@ -1,66 +1,5 @@ -import { useSession } from "@xtablo/shared/contexts/SessionContext"; -import { useEffect, useRef, useState } from "react"; -import { useNavigate, useSearchParams } from "react-router-dom"; +import { Navigate } from "react-router-dom"; export function AuthCallback() { - const [searchParams] = useSearchParams(); - const token = searchParams.get("token"); - const { session } = useSession(); - const navigate = useNavigate(); - const [error, setError] = useState(null); - const hasAccepted = useRef(false); - - useEffect(() => { - if (!session || !token || hasAccepted.current) { - return; - } - - hasAccepted.current = true; - - const apiUrl = import.meta.env.VITE_API_URL as string; - - fetch(`${apiUrl}/api/v1/client-invites/accept/${token}`, { - method: "POST", - headers: { - Authorization: `Bearer ${session.access_token}`, - "Content-Type": "application/json", - }, - }) - .then(async (res) => { - if (!res.ok) { - const body = await res.json().catch(() => ({})); - throw new Error((body as { message?: string }).message ?? "Erreur lors de l'acceptation de l'invitation"); - } - return res.json() as Promise<{ tabloId: string }>; - }) - .then((data) => { - navigate(`/tablo/${data.tabloId}`, { replace: true }); - }) - .catch((err: unknown) => { - console.error("Accept invite error:", err); - setError( - "Une erreur est survenue lors de l'acceptation de l'invitation. Veuillez contacter la personne qui vous a invité." - ); - }); - }, [session, token, navigate]); - - if (error) { - return ( -
-
-

Erreur

-

{error}

-
-
- ); - } - - return ( -
-
-
-

Authentification en cours...

-
-
- ); + return ; } diff --git a/apps/clients/src/pages/LoginPage.test.tsx b/apps/clients/src/pages/LoginPage.test.tsx new file mode 100644 index 0000000..425eac6 --- /dev/null +++ b/apps/clients/src/pages/LoginPage.test.tsx @@ -0,0 +1,62 @@ +import { fireEvent, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { renderWithProviders } from "../test/testHelpers"; +import { LoginPage } from "./LoginPage"; + +const { mockSignInWithPassword, mockNavigate } = vi.hoisted(() => ({ + mockSignInWithPassword: vi.fn(), + mockNavigate: vi.fn(), +})); + +vi.mock("../lib/supabase", () => ({ + supabase: { + auth: { + signInWithPassword: mockSignInWithPassword, + }, + }, +})); + +vi.mock("react-router-dom", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useNavigate: () => mockNavigate, + }; +}); + +describe("LoginPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + localStorage.clear(); + mockSignInWithPassword.mockResolvedValue({ + data: { user: { email_confirmed_at: new Date().toISOString() } }, + error: null, + }); + }); + + it("renders the shared auth shell and form", () => { + renderWithProviders(, { testUser: undefined }); + + expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument(); + expect(screen.getByLabelText("Email")).toBeInTheDocument(); + expect(screen.getByLabelText("Mot de passe")).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Connexion" })).toBeInTheDocument(); + }); + + it("submits email/password login and resumes the stored redirect", async () => { + localStorage.setItem("clients.redirectUrl", "/tablo/tablo-42"); + renderWithProviders(, { testUser: undefined }); + + fireEvent.change(screen.getByLabelText("Email"), { target: { value: "client@example.com" } }); + fireEvent.change(screen.getByLabelText("Mot de passe"), { target: { value: "password123" } }); + fireEvent.click(screen.getByRole("button", { name: "Connexion" })); + + await waitFor(() => { + expect(mockSignInWithPassword).toHaveBeenCalledWith({ + email: "client@example.com", + password: "password123", + }); + expect(mockNavigate).toHaveBeenCalledWith("/tablo/tablo-42"); + }); + }); +}); diff --git a/apps/clients/src/pages/LoginPage.tsx b/apps/clients/src/pages/LoginPage.tsx new file mode 100644 index 0000000..f38f582 --- /dev/null +++ b/apps/clients/src/pages/LoginPage.tsx @@ -0,0 +1,102 @@ +import { AuthCardShell, AuthEmailPasswordForm, AuthInfoBanner } from "@xtablo/auth-ui"; +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Link, useNavigate } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +export function LoginPage() { + const { t } = useTranslation(["auth", "common"]); + const { session } = useSession(); + const navigate = useNavigate(); + const [email, setEmail] = useState(""); + const [password, setPassword] = useState(""); + const [isPending, setIsPending] = useState(false); + const [error, setError] = useState(null); + + if (session) { + const redirectUrl = localStorage.getItem("clients.redirectUrl"); + if (redirectUrl) { + localStorage.removeItem("clients.redirectUrl"); + navigate(redirectUrl); + } else { + navigate("/"); + } + } + + const onSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + setIsPending(true); + setError(null); + + const { error: signInError } = await supabase.auth.signInWithPassword({ + email, + password, + }); + + if (signInError) { + setError(signInError.message); + setIsPending(false); + return; + } + + const redirectUrl = localStorage.getItem("clients.redirectUrl"); + if (redirectUrl) { + localStorage.removeItem("clients.redirectUrl"); + navigate(redirectUrl); + } else { + navigate("/"); + } + }; + + return ( + + + + + {t("auth:common.backHome")} + + } + showThemeToggle + > +
+ {error ? : null} + + + + {t("auth:login.forgotPassword")} + +
+ } + /> +
+ + ); +} diff --git a/apps/clients/src/pages/ResetPasswordPage.test.tsx b/apps/clients/src/pages/ResetPasswordPage.test.tsx new file mode 100644 index 0000000..18a4657 --- /dev/null +++ b/apps/clients/src/pages/ResetPasswordPage.test.tsx @@ -0,0 +1,42 @@ +import { fireEvent, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { renderWithProviders } from "../test/testHelpers"; +import { ResetPasswordPage } from "./ResetPasswordPage"; + +const { mockResetPasswordForEmail } = vi.hoisted(() => ({ + mockResetPasswordForEmail: vi.fn(), +})); + +vi.mock("../lib/supabase", () => ({ + supabase: { + auth: { + resetPasswordForEmail: mockResetPasswordForEmail, + }, + }, +})); + +describe("ResetPasswordPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + mockResetPasswordForEmail.mockResolvedValue({ error: null }); + }); + + it("renders the shared auth shell", () => { + renderWithProviders(, { testUser: undefined }); + + expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument(); + expect(screen.getByLabelText("Email")).toBeInTheDocument(); + }); + + it("submits a password reset email", async () => { + renderWithProviders(, { testUser: undefined }); + + fireEvent.change(screen.getByLabelText("Email"), { target: { value: "client@example.com" } }); + fireEvent.click(screen.getByRole("button", { name: "Envoyer le lien de réinitialisation" })); + + await waitFor(() => { + expect(mockResetPasswordForEmail).toHaveBeenCalled(); + expect(screen.getByText(/vérifiez votre boîte mail/i)).toBeInTheDocument(); + }); + }); +}); diff --git a/apps/clients/src/pages/ResetPasswordPage.tsx b/apps/clients/src/pages/ResetPasswordPage.tsx new file mode 100644 index 0000000..85d591e --- /dev/null +++ b/apps/clients/src/pages/ResetPasswordPage.tsx @@ -0,0 +1,71 @@ +import { AuthCardShell, AuthInfoBanner } from "@xtablo/auth-ui"; +import { Button } from "@xtablo/ui/components/button"; +import { Input } from "@xtablo/ui/components/input"; +import { Label } from "@xtablo/ui/components/label"; +import { useState } from "react"; +import { useTranslation } from "react-i18next"; +import { Link } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +export function ResetPasswordPage() { + const { t } = useTranslation(["auth", "common"]); + const [email, setEmail] = useState(""); + const [error, setError] = useState(null); + const [isPending, setIsPending] = useState(false); + const [isSubmitted, setIsSubmitted] = useState(false); + + const onSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + setIsPending(true); + setError(null); + + const { error: resetError } = await supabase.auth.resetPasswordForEmail(email, { + redirectTo: `${window.location.origin}/set-password`, + }); + + if (resetError) { + setError(resetError.message); + setIsPending(false); + return; + } + + setIsSubmitted(true); + setIsPending(false); + }; + + return ( + +
+ {error ? : null} + {isSubmitted ? ( +
+ + + + +
+ ) : ( +
+
+ + setEmail(event.target.value)} + placeholder={t("auth:resetPassword.emailPlaceholder")} + required + disabled={isPending} + /> +
+ + +
+ )} +
+
+ ); +} diff --git a/apps/clients/src/pages/SetPasswordPage.test.tsx b/apps/clients/src/pages/SetPasswordPage.test.tsx new file mode 100644 index 0000000..1cce2ee --- /dev/null +++ b/apps/clients/src/pages/SetPasswordPage.test.tsx @@ -0,0 +1,91 @@ +import { fireEvent, screen, waitFor } from "@testing-library/react"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { renderWithProviders } from "../test/testHelpers"; +import { SetPasswordPage } from "./SetPasswordPage"; + +const { mockSignInWithPassword, mockUpdateUser, mockNavigate } = vi.hoisted(() => ({ + mockSignInWithPassword: vi.fn(), + mockUpdateUser: vi.fn(), + mockNavigate: vi.fn(), +})); + +vi.mock("../lib/supabase", () => ({ + supabase: { + auth: { + signInWithPassword: mockSignInWithPassword, + updateUser: mockUpdateUser, + }, + }, +})); + +vi.mock("react-router-dom", async (importOriginal) => { + const actual = await importOriginal(); + return { + ...actual, + useNavigate: () => mockNavigate, + }; +}); + +describe("SetPasswordPage", () => { + beforeEach(() => { + vi.clearAllMocks(); + vi.stubGlobal("fetch", vi.fn()); + mockSignInWithPassword.mockResolvedValue({ data: {}, error: null }); + mockUpdateUser.mockResolvedValue({ data: {}, error: null }); + }); + + it("renders an invalid-token state when invite validation fails", async () => { + vi.mocked(fetch).mockResolvedValueOnce( + new Response(JSON.stringify({ error: "Invite not found or already used" }), { status: 404 }) + ); + + renderWithProviders(, { + route: "/set-password?token=bad-token", + path: "/set-password", + testUser: undefined, + }); + + await waitFor(() => { + expect(screen.getByText(/lien invalide/i)).toBeInTheDocument(); + }); + }); + + it("submits invite-based password setup once", async () => { + vi.mocked(fetch) + .mockResolvedValueOnce( + new Response(JSON.stringify({ email: "client@example.com", tabloId: "tablo-1" }), { + status: 200, + }) + ) + .mockResolvedValueOnce( + new Response(JSON.stringify({ success: true, email: "client@example.com", tabloId: "tablo-1" }), { + status: 200, + }) + ); + + renderWithProviders(, { + route: "/set-password?token=good-token", + path: "/set-password", + testUser: undefined, + }); + + await waitFor(() => { + expect(screen.getByLabelText("Mot de passe")).toBeInTheDocument(); + }); + + fireEvent.change(screen.getByLabelText("Mot de passe"), { target: { value: "password123" } }); + fireEvent.change(screen.getByLabelText("Confirmer le mot de passe"), { + target: { value: "password123" }, + }); + fireEvent.click(screen.getByRole("button", { name: "Définir mon mot de passe" })); + + await waitFor(() => { + expect(fetch).toHaveBeenCalledTimes(2); + expect(mockSignInWithPassword).toHaveBeenCalledWith({ + email: "client@example.com", + password: "password123", + }); + expect(mockNavigate).toHaveBeenCalledWith("/tablo/tablo-1"); + }); + }); +}); diff --git a/apps/clients/src/pages/SetPasswordPage.tsx b/apps/clients/src/pages/SetPasswordPage.tsx new file mode 100644 index 0000000..f775c4b --- /dev/null +++ b/apps/clients/src/pages/SetPasswordPage.tsx @@ -0,0 +1,205 @@ +import { AuthCardShell, AuthInfoBanner } from "@xtablo/auth-ui"; +import { useSession } from "@xtablo/shared/contexts/SessionContext"; +import { Button } from "@xtablo/ui/components/button"; +import { Input } from "@xtablo/ui/components/input"; +import { Label } from "@xtablo/ui/components/label"; +import { useEffect, useMemo, useState } from "react"; +import { useTranslation } from "react-i18next"; +import { useNavigate, useSearchParams } from "react-router-dom"; +import { supabase } from "../lib/supabase"; + +type InviteDetails = { + email: string; + tabloId: string; +}; + +type InviteState = "loading" | "ready" | "invalid"; + +function getApiUrl() { + return import.meta.env.VITE_API_URL ?? ""; +} + +async function parseError(response: Response) { + const body = (await response.json().catch(() => ({}))) as { error?: string; message?: string }; + return body.error ?? body.message ?? "Une erreur est survenue."; +} + +export function SetPasswordPage() { + const { t } = useTranslation("auth"); + const { session } = useSession(); + const navigate = useNavigate(); + const [searchParams] = useSearchParams(); + const token = searchParams.get("token"); + const [inviteState, setInviteState] = useState(token ? "loading" : "ready"); + const [inviteDetails, setInviteDetails] = useState(null); + const [password, setPassword] = useState(""); + const [confirmPassword, setConfirmPassword] = useState(""); + const [error, setError] = useState(null); + const [isPending, setIsPending] = useState(false); + + const isInviteFlow = Boolean(token); + const description = useMemo( + () => + isInviteFlow + ? "Définissez votre mot de passe pour accéder à votre espace client." + : t("updatePassword.description"), + [isInviteFlow, t] + ); + + useEffect(() => { + if (!token) { + return; + } + + let isMounted = true; + + fetch(`${getApiUrl()}/api/v1/client-invites/setup/${token}`) + .then(async (response) => { + if (!response.ok) { + throw new Error(await parseError(response)); + } + + return (await response.json()) as InviteDetails; + }) + .then((details) => { + if (!isMounted) return; + setInviteDetails(details); + setInviteState("ready"); + }) + .catch((err: unknown) => { + if (!isMounted) return; + setError(err instanceof Error ? err.message : "Lien invalide"); + setInviteState("invalid"); + }); + + return () => { + isMounted = false; + }; + }, [token]); + + const onSubmit = async (event: React.FormEvent) => { + event.preventDefault(); + setError(null); + + if (password.length < 8) { + setError(t("signup.errors.passwordLength")); + return; + } + + if (password !== confirmPassword) { + setError(t("signup.errors.passwordMatch")); + return; + } + + setIsPending(true); + + try { + if (token && inviteDetails) { + const response = await fetch(`${getApiUrl()}/api/v1/client-invites/setup/${token}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify({ password }), + }); + + if (!response.ok) { + throw new Error(await parseError(response)); + } + + const result = (await response.json()) as InviteDetails & { success: boolean }; + const { error: signInError } = await supabase.auth.signInWithPassword({ + email: result.email, + password, + }); + + if (signInError) { + throw signInError; + } + + navigate(`/tablo/${result.tabloId}`); + return; + } + + const { error: updateError } = await supabase.auth.updateUser({ password }); + if (updateError) { + throw updateError; + } + + navigate("/login"); + } catch (err) { + setError(err instanceof Error ? err.message : "Une erreur est survenue."); + } finally { + setIsPending(false); + } + }; + + if (inviteState === "loading") { + return ( + +
+
+
+ + ); + } + + if (inviteState === "invalid") { + return ( + + + + ); + } + + const shouldShowRecoveryHint = !isInviteFlow && !session; + + return ( + +
+ {error ? : null} + {shouldShowRecoveryHint ? ( + + ) : null} + +
+
+ + setPassword(event.target.value)} + required + disabled={isPending} + /> +
+ +
+ + setConfirmPassword(event.target.value)} + required + disabled={isPending} + /> +
+ + +
+
+
+ ); +} diff --git a/apps/clients/src/routes.tsx b/apps/clients/src/routes.tsx index 57a23ce..e10531f 100644 --- a/apps/clients/src/routes.tsx +++ b/apps/clients/src/routes.tsx @@ -1,16 +1,25 @@ import { Route, Routes } from "react-router-dom"; +import { ClientAuthGate } from "./components/ClientAuthGate"; import { ClientLayout } from "./components/ClientLayout"; import { AuthCallback } from "./pages/AuthCallback"; import { ClientTabloListPage } from "./pages/ClientTabloListPage"; import { ClientTabloPage } from "./pages/ClientTabloPage"; +import { LoginPage } from "./pages/LoginPage"; +import { ResetPasswordPage } from "./pages/ResetPasswordPage"; +import { SetPasswordPage } from "./pages/SetPasswordPage"; export default function AppRoutes() { return ( + } /> + } /> + } /> } /> - }> - } /> - } /> + }> + }> + } /> + } /> + ); diff --git a/apps/clients/src/test/testHelpers.tsx b/apps/clients/src/test/testHelpers.tsx index ede64d8..ac7b2ab 100644 --- a/apps/clients/src/test/testHelpers.tsx +++ b/apps/clients/src/test/testHelpers.tsx @@ -23,12 +23,18 @@ interface RenderWithProvidersOptions { route?: string; path?: string; language?: string; + testUser?: typeof defaultUser | undefined; } export const renderWithProviders = ( ui: React.ReactNode, - { route = "/", path, language = "fr" }: RenderWithProvidersOptions = {} + options: RenderWithProvidersOptions = {} ): RenderResult & { user: ReturnType } => { + const { route = "/", path, language = "fr" } = options; + const testUser = Object.prototype.hasOwnProperty.call(options, "testUser") + ? options.testUser + : defaultUser; + testI18n.changeLanguage(language); const testQueryClient = new QueryClient({ @@ -55,7 +61,7 @@ export const renderWithProviders = ( - {content} + {content} diff --git a/apps/clients/tsconfig.json b/apps/clients/tsconfig.json index f2fa327..2431c00 100644 --- a/apps/clients/tsconfig.json +++ b/apps/clients/tsconfig.json @@ -18,6 +18,8 @@ "noFallthroughCasesInSwitch": true, "baseUrl": ".", "paths": { + "@xtablo/auth-ui": ["../../packages/auth-ui/src"], + "@xtablo/auth-ui/*": ["../../packages/auth-ui/src/*"], "@xtablo/ui": ["../../packages/ui/src"], "@xtablo/ui/*": ["../../packages/ui/src/*"], "@xtablo/shared": ["../../packages/shared/src"], diff --git a/apps/clients/tsconfig.tsbuildinfo b/apps/clients/tsconfig.tsbuildinfo index 1df4210..6ab4cf9 100644 --- a/apps/clients/tsconfig.tsbuildinfo +++ b/apps/clients/tsconfig.tsbuildinfo @@ -1 +1 @@ -{"root":["./src/app.tsx","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file +{"root":["./src/app.tsx","./src/i18n.test.ts","./src/i18n.ts","./src/main.tsx","./src/maincss.test.ts","./src/routes.tsx","./src/setuptests.ts","./src/components/clientauthgate.tsx","./src/components/clientlayout.test.tsx","./src/components/clientlayout.tsx","./src/lib/supabase.ts","./src/pages/authcallback.tsx","./src/pages/clienttablolistpage.tsx","./src/pages/clienttablopage.test.tsx","./src/pages/clienttablopage.tsx","./src/pages/loginpage.test.tsx","./src/pages/loginpage.tsx","./src/pages/resetpasswordpage.test.tsx","./src/pages/resetpasswordpage.tsx","./src/pages/setpasswordpage.test.tsx","./src/pages/setpasswordpage.tsx","./src/test/testhelpers.test.tsx","./src/test/testhelpers.tsx"],"version":"5.9.3"} \ No newline at end of file diff --git a/apps/main/package.json b/apps/main/package.json index 18574d9..97bdeda 100644 --- a/apps/main/package.json +++ b/apps/main/package.json @@ -100,6 +100,7 @@ "@types/react-router-dom": "^5.3.3", "@typescript/native-preview": "7.0.0-dev.20251010.1", "@xtablo/chat-ui": "workspace:*", + "@xtablo/auth-ui": "workspace:*", "@xtablo/shared": "workspace:*", "@xtablo/shared-types": "workspace:*", "@xtablo/tablo-views": "workspace:*", diff --git a/apps/main/src/components/ProtectedRoute.test.tsx b/apps/main/src/components/ProtectedRoute.test.tsx index 19143ed..c7e6375 100644 --- a/apps/main/src/components/ProtectedRoute.test.tsx +++ b/apps/main/src/components/ProtectedRoute.test.tsx @@ -85,6 +85,7 @@ describe("ProtectedRoute", () => { last_name: "User", is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none" as const, created_at: new Date().toISOString(), diff --git a/apps/main/src/components/SubscriptionCard.test.tsx b/apps/main/src/components/SubscriptionCard.test.tsx index f065c5b..7eebb0e 100644 --- a/apps/main/src/components/SubscriptionCard.test.tsx +++ b/apps/main/src/components/SubscriptionCard.test.tsx @@ -40,6 +40,7 @@ const baseUser: User = { avatar_url: null, is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none", created_at: new Date().toISOString(), diff --git a/apps/main/src/components/UpgradePanel.test.tsx b/apps/main/src/components/UpgradePanel.test.tsx index 3b00d34..b82f2a7 100644 --- a/apps/main/src/components/UpgradePanel.test.tsx +++ b/apps/main/src/components/UpgradePanel.test.tsx @@ -36,6 +36,7 @@ const baseUser: User = { avatar_url: null, is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none", created_at: new Date().toISOString(), diff --git a/apps/main/src/contexts/UpgradeBlockContext.test.tsx b/apps/main/src/contexts/UpgradeBlockContext.test.tsx index f4b29f7..cedf044 100644 --- a/apps/main/src/contexts/UpgradeBlockContext.test.tsx +++ b/apps/main/src/contexts/UpgradeBlockContext.test.tsx @@ -23,6 +23,7 @@ const baseUser: User = { avatar_url: null, is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none", created_at: new Date().toISOString(), diff --git a/apps/main/src/hooks/client_invites.ts b/apps/main/src/hooks/client_invites.ts index 3c6125e..71c6e5a 100644 --- a/apps/main/src/hooks/client_invites.ts +++ b/apps/main/src/hooks/client_invites.ts @@ -10,6 +10,11 @@ type PendingClientInvite = { created_at: string; }; +type CreateClientInviteResponse = { + success: true; + inviteMode: "notification" | "setup"; +}; + export const usePendingClientInvites = (tabloId: string) => { const api = useAuthedApi(); const { session } = useSession(); @@ -32,17 +37,23 @@ export const useCreateClientInvite = () => { return useMutation({ mutationFn: async ({ tabloId, email }: { tabloId: string; email: string }) => { - const { data } = await api.post(`/api/v1/client-invites/${tabloId}`, { - email, - }); + const { data } = await api.post( + `/api/v1/client-invites/${tabloId}`, + { + email, + } + ); return data; }, - onSuccess: (_data, { tabloId }) => { + onSuccess: (data, { tabloId }) => { queryClient.invalidateQueries({ queryKey: ["client-invites", tabloId] }); toast.add( { - title: "Lien magique envoyé", - description: "L'invitation client a été envoyée avec succès", + title: data.inviteMode === "setup" ? "Invitation client envoyée" : "Accès client accordé", + description: + data.inviteMode === "setup" + ? "Un email de configuration du mot de passe a été envoyé au client." + : "Le client a été informé de son nouvel accès et pourra se connecter à son espace.", type: "success", }, { timeout: 3000 } diff --git a/apps/main/src/pages/login.test.tsx b/apps/main/src/pages/login.test.tsx index a3c0361..b39deef 100644 --- a/apps/main/src/pages/login.test.tsx +++ b/apps/main/src/pages/login.test.tsx @@ -34,6 +34,7 @@ describe("LoginPage", () => { it("renders all form elements", () => { renderWithProviders(); + expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument(); expect(screen.getByLabelText(/email/i)).toBeInTheDocument(); expect(screen.getByLabelText(/password/i)).toBeInTheDocument(); expect(screen.getByRole("button", { name: /log in/i })).toBeInTheDocument(); diff --git a/apps/main/src/pages/login.tsx b/apps/main/src/pages/login.tsx index 41ca566..c6e3eaa 100644 --- a/apps/main/src/pages/login.tsx +++ b/apps/main/src/pages/login.tsx @@ -1,10 +1,5 @@ import { LoginWithGoogle } from "@ui/components/BrandButtons/LoginWithGoogle"; -import { useTheme } from "@xtablo/shared/contexts/ThemeContext"; -import { Button } from "@xtablo/ui/components/button"; -import { FieldError } from "@xtablo/ui/components/field"; -import { Input } from "@xtablo/ui/components/input"; -import { Label } from "@xtablo/ui/components/label"; -import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react"; +import { AuthCardShell, AuthEmailPasswordForm } from "@xtablo/auth-ui"; import { useRef, useState } from "react"; import { useTranslation } from "react-i18next"; import { Link, useSearchParams } from "react-router-dom"; @@ -60,32 +55,6 @@ export function LoginPage() { setIsHovered(false); }; - // Theme - const { theme, setTheme } = useTheme(); - - const toggleTheme = () => { - if (theme === "light") { - setTheme("dark"); - } else if (theme === "dark") { - setTheme("system"); - } else { - setTheme("light"); - } - }; - - const getThemeIcon = () => { - switch (theme) { - case "light": - return ; - case "dark": - return ; - case "system": - return ; - default: - return ; - } - }; - const onSubmit = (e: React.FormEvent) => { e.preventDefault(); login({ @@ -95,168 +64,100 @@ export function LoginPage() { }; return ( -
- -
e.stopPropagation()} - > - {/* Glow effect behind the card */} -
- -
} + topLeft={ + -
- - - - - {t("auth:common.backHome")} - - - {/* Theme Toggle */} - -
- - {/* Xtablo Icon */} -
- Xtablo + - Xtablo -
+ + {t("auth:common.backHome")} + + } + showThemeToggle + wrapperClassName="transition-transform duration-200 ease-out will-change-transform" + wrapperStyle={{ transform }} + onWrapperMouseMove={handleMouseMove} + onWrapperMouseLeave={handleMouseLeave} + isHovered={isHovered} + > +
+ + {t("auth:login.newExperienceLink")} + +
-

- {t("auth:login.title")} -

- -
- - {t("auth:login.newExperienceLink")} - -
- -
-
-
- - setFormData({ ...formData, email: e.target.value })} - required - placeholder={t("auth:login.emailPlaceholder")} - /> - {errors?.email && } -
- -
- - setFormData({ ...formData, password: e.target.value })} - required - placeholder={t("auth:login.passwordPlaceholder")} - /> - {errors?.password && } -
- -
- - {t("auth:login.forgotPassword")} - -
- - -
- -
-
-
-
-
- - {t("auth:common.orContinue")} - -
-
- - - -

- {t("auth:login.noAccount")}{" "} +

+ setFormData({ ...formData, email })} + onPasswordChange={(password: string) => setFormData({ ...formData, password })} + onSubmit={onSubmit} + submitLabel={isPending ? t("auth:common.connecting") : t("auth:login.loginButton")} + emailLabel={`${t("common:labels.email")} *`} + passwordLabel={`${t("common:labels.password")} *`} + emailPlaceholder={t("auth:login.emailPlaceholder")} + passwordPlaceholder={t("auth:login.passwordPlaceholder")} + emailError={errors?.email} + passwordError={errors?.password} + extraContent={ +
- {t("auth:login.signupLink")} + {t("auth:login.forgotPassword")} -

+
+ } + /> + +
+
+
+
+
+ + {t("auth:common.orContinue")} +
+ + + +

+ {t("auth:login.noAccount")}{" "} + + {t("auth:login.signupLink")} + +

-
+ ); } diff --git a/apps/main/src/pages/reset-password.test.tsx b/apps/main/src/pages/reset-password.test.tsx index beddf74..1e07af5 100644 --- a/apps/main/src/pages/reset-password.test.tsx +++ b/apps/main/src/pages/reset-password.test.tsx @@ -16,6 +16,7 @@ describe("ResetPasswordPage", () => { it("renders form with email input", () => { renderWithProviders(); + expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument(); expect(screen.getByText(/forgot your password/i)).toBeInTheDocument(); expect(screen.getByLabelText(/email/i)).toBeInTheDocument(); expect(screen.getByRole("button", { name: /send reset link/i })).toBeInTheDocument(); diff --git a/apps/main/src/pages/reset-password.tsx b/apps/main/src/pages/reset-password.tsx index 9633d68..acc4a75 100644 --- a/apps/main/src/pages/reset-password.tsx +++ b/apps/main/src/pages/reset-password.tsx @@ -1,13 +1,13 @@ +import { AuthCardShell, AuthInfoBanner } from "@xtablo/auth-ui"; import { toast } from "@xtablo/shared"; import { Button } from "@xtablo/ui/components/button"; import { Input } from "@xtablo/ui/components/input"; import { Label } from "@xtablo/ui/components/label"; import { Text } from "@xtablo/ui/components/typography"; -import { AlertCircle, CheckCircle2, Loader2Icon, MailIcon } from "lucide-react"; +import { CheckCircle2, Loader2Icon, MailIcon } from "lucide-react"; import { useState } from "react"; import { useTranslation } from "react-i18next"; import { Link, useNavigate } from "react-router-dom"; -import { twMerge } from "tailwind-merge"; import { supabase } from "../lib/supabase"; export function ResetPasswordPage() { @@ -49,113 +49,83 @@ export function ResetPasswordPage() { if (isSubmitted) { return ( -
navigate("/login")} + {t("resetPassword.checkInbox", { email })}} + onBackdropClick={() => navigate("/login")} > -
e.stopPropagation()} - > -
-
-
- -
+
+
+
+
-
-

{t("resetPassword.emailSent")}

- - {t("resetPassword.checkInbox", { email })} - -
-
-
- - - {t("resetPassword.emailInstructions")} - -
-
- - -
+ + + + + +
-
+ ); } return ( -
navigate("/login")} + {t("resetPassword.description")}} + onBackdropClick={() => navigate("/login")} > -
e.stopPropagation()} - > -
-
-

{t("resetPassword.title")}

- {t("resetPassword.description")} +
+ {error ? : null} + +
+
+ + setEmail(e.target.value)} + placeholder={t("resetPassword.emailPlaceholder")} + required + disabled={isPending} + className="transition-opacity disabled:opacity-50" + />
- {error && ( -
-
- - {error} -
-
- )} + +
-
-
- - setEmail(e.target.value)} - placeholder={t("resetPassword.emailPlaceholder")} - required - disabled={isPending} - className="transition-opacity disabled:opacity-50" - /> -
- - -
- -

- - {t("resetPassword.backToLogin")} - -

+
+
+ + + {t("resetPassword.emailInstructions")} + +
+ +

+ + {t("resetPassword.backToLogin")} + +

-
+ ); } diff --git a/apps/main/src/pages/tablo-details.layout.test.tsx b/apps/main/src/pages/tablo-details.layout.test.tsx index e30a059..ec1ace7 100644 --- a/apps/main/src/pages/tablo-details.layout.test.tsx +++ b/apps/main/src/pages/tablo-details.layout.test.tsx @@ -406,7 +406,7 @@ describe("TabloDetailsPage overview layout", () => { expect(screen.getByRole("button", { name: "Modifier la mise en page" })).toBeInTheDocument(); }); - it("uses the standard email invite UI in the share dialog", async () => { + it("uses the client password invite UI in the share dialog", async () => { const user = userEvent.setup(); renderWithProviders(, { @@ -416,9 +416,10 @@ describe("TabloDetailsPage overview layout", () => { await user.click(screen.getByRole("button", { name: "Inviter" })); - expect(screen.getByText("Inviter un utilisateur")).toBeInTheDocument(); - expect(screen.getByPlaceholderText("Email de l'utilisateur à inviter")).toBeInTheDocument(); - expect(screen.queryByText("Accès client")).not.toBeInTheDocument(); - expect(screen.queryByRole("button", { name: "Envoyer le lien" })).not.toBeInTheDocument(); + expect(screen.getByText("Accès client")).toBeInTheDocument(); + expect(screen.getByPlaceholderText("Email du client")).toBeInTheDocument(); + expect(screen.getByText(/définir son mot de passe/i)).toBeInTheDocument(); + expect(screen.getByRole("button", { name: "Envoyer l'invitation" })).toBeInTheDocument(); + expect(screen.queryByText("Inviter un utilisateur")).not.toBeInTheDocument(); }); }); diff --git a/apps/main/src/pages/tablo-details.tsx b/apps/main/src/pages/tablo-details.tsx index 4816bb3..a6db9de 100644 --- a/apps/main/src/pages/tablo-details.tsx +++ b/apps/main/src/pages/tablo-details.tsx @@ -86,8 +86,7 @@ const TAB_SECTIONS: TabSection[] = [ "roadmap", ]; -// Temporary rollback until the client portal invite flow is ready to be used again. -const USE_CLIENT_MAGIC_LINK_INVITES = false; +const USE_CLIENT_PASSWORD_INVITES = true; // ─── Page ───────────────────────────────────────────────────────────────────── @@ -564,12 +563,13 @@ export const TabloDetailsPage = () => { {/* Separator */}
- {USE_CLIENT_MAGIC_LINK_INVITES ? ( + {USE_CLIENT_PASSWORD_INVITES ? ( <>

Accès client

- Invitez des clients externes via un lien magique + Le client recevra un email pour définir son mot de passe ou, s'il a déjà + un compte, une notification d'accès directe à ce tablo.

@@ -598,7 +598,7 @@ export const TabloDetailsPage = () => { }} disabled={!isEmailValid(clientInviteEmail)} > - Envoyer le lien + Envoyer l'invitation )}
diff --git a/apps/main/src/providers/UserStoreProvider.test.tsx b/apps/main/src/providers/UserStoreProvider.test.tsx index 7f7e908..84b9bb2 100644 --- a/apps/main/src/providers/UserStoreProvider.test.tsx +++ b/apps/main/src/providers/UserStoreProvider.test.tsx @@ -63,6 +63,7 @@ describe("TestUserStoreProvider", () => { first_name: null, is_temporary: false, is_client: false, + client_onboarded_at: null, last_name: null, short_user_id: "short-id", last_signed_in: null, diff --git a/apps/main/src/utils/testHelpers.tsx b/apps/main/src/utils/testHelpers.tsx index f370ba2..c3a4cab 100644 --- a/apps/main/src/utils/testHelpers.tsx +++ b/apps/main/src/utils/testHelpers.tsx @@ -19,6 +19,7 @@ const defaultUser = { avatar_url: "https://example.com/avatar.jpg", is_temporary: false, is_client: false, + client_onboarded_at: null, last_signed_in: null, plan: "none" as const, created_at: new Date().toISOString(), diff --git a/apps/main/tsconfig.app.json b/apps/main/tsconfig.app.json index b633f54..5b1c16f 100644 --- a/apps/main/tsconfig.app.json +++ b/apps/main/tsconfig.app.json @@ -27,6 +27,8 @@ "paths": { "*": ["./*"], "@ui/*": ["./src/*"], + "@xtablo/auth-ui": ["../../packages/auth-ui/src"], + "@xtablo/auth-ui/*": ["../../packages/auth-ui/src/*"], "@xtablo/ui/*": ["../../packages/ui/src/*"] } }, diff --git a/docs/superpowers/plans/2026-04-18-client-password-invite-flow.md b/docs/superpowers/plans/2026-04-18-client-password-invite-flow.md new file mode 100644 index 0000000..733f66e --- /dev/null +++ b/docs/superpowers/plans/2026-04-18-client-password-invite-flow.md @@ -0,0 +1,626 @@ +# Client Password Invite Flow Implementation Plan + +> **For agentic workers:** REQUIRED: Use superpowers:subagent-driven-development (if subagents available) or superpowers:executing-plans to implement this plan. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Replace the client magic-link callback flow with one-time password setup plus normal email/password login in `apps/clients`, while keeping client users restricted to the client portal. + +**Architecture:** Keep Supabase Auth as the identity provider, but move invite lifecycle decisions into the API. The backend creates or reuses one client account per email, then branches between an onboarding email with a one-time setup token and an access-notification email for already-onboarded clients. On the frontend, extract the main login visual shell into a shared auth UI surface, add client login/set-password/reset routes, and redirect protected client routes through login with destination resume. + +**Tech Stack:** Hono API, Supabase Auth, React 19, React Router, TanStack Query, Tailwind CSS v4, pnpm workspaces, Vitest. + +**Spec:** `docs/superpowers/specs/2026-04-18-client-password-invite-flow-design.md` + +--- + +## File Structure + +### New files + +**Database** +- `supabase/migrations/20260418110000_client_password_invites.sql` — replaces callback-oriented invite semantics with setup-token lifecycle fields and client-only auth metadata + +**Shared auth UI** +- `packages/auth-ui/package.json` — shared auth UI package manifest if no existing package is a clean fit +- `packages/auth-ui/tsconfig.json` — package tsconfig +- `packages/auth-ui/src/index.ts` — barrel exports +- `packages/auth-ui/src/AuthCardShell.tsx` — shared auth page background, card shell, logo, theme toggle, and content slot +- `packages/auth-ui/src/AuthEmailPasswordForm.tsx` — shared email/password form layout with error and loading states +- `packages/auth-ui/src/AuthInfoBanner.tsx` — shared inline success/error/info banner component used by login/reset/setup screens + +**Client auth pages** +- `apps/clients/src/pages/LoginPage.tsx` — client login screen using shared auth UI +- `apps/clients/src/pages/ResetPasswordPage.tsx` — client forgot-password page +- `apps/clients/src/pages/SetPasswordPage.tsx` — one-time invite setup screen +- `apps/clients/src/pages/LoginPage.test.tsx` +- `apps/clients/src/pages/ResetPasswordPage.test.tsx` +- `apps/clients/src/pages/SetPasswordPage.test.tsx` +- `apps/clients/src/components/ClientAuthGate.tsx` — preserves intended route and redirects unauthenticated users to login + +**API tests** +- No brand-new top-level test files required if the current route tests remain focused; extend: + - `apps/api/src/__tests__/routes/clientInvites.test.ts` + - `apps/api/src/__tests__/middlewares/middlewares.test.ts` + +### Modified files + +**API** +- `apps/api/src/routers/clientInvites.ts` — replace callback accept flow with setup-token create/validate/complete flow plus access-notification branch +- `apps/api/src/helpers/helpers.ts` — split current `createClientUser()` into clearer helpers for create/reuse account, detect onboarding state, and grant tablo access +- `apps/api/src/routers/index.ts` or the file that mounts `clientInvites` — ensure new routes are exposed +- `apps/api/src/middlewares/middleware.ts` — keep client users blocked from regular main-app routes; tighten behavior if needed +- `apps/api/src/__tests__/routes/clientInvites.test.ts` — cover onboarding vs notification, token validation, single use, cancellation, and app-boundary expectations +- `apps/api/src/__tests__/middlewares/middlewares.test.ts` — keep client-only users rejected by main-app middleware + +**Shared types** +- `packages/shared-types/src/database.types.ts` — add migration-driven type updates for `client_invites` and any new client auth columns + +**Main app frontend** +- `apps/main/src/pages/tablo-details.tsx` — update invite dialog submit flow and text for password-setup onboarding / access notification messaging +- `apps/main/src/pages/tablo-details.layout.test.tsx` — cover active magic-link invite UI copy and success states after the backend contract change +- `apps/main/src/pages/login.tsx` — consume shared auth shell/form pieces after extraction +- `apps/main/src/pages/reset-password.tsx` — consume shared auth shell/form pieces after extraction +- `apps/main/src/hooks/client_invites.ts` — adapt to the updated invite response shape if needed +- `apps/main/src/hooks/auth.ts` — optionally extract reusable login/reset behavior or keep app-specific logic while sharing visuals +- `apps/main/src/pages/login.test.tsx` +- `apps/main/src/pages/reset-password.test.tsx` + +**Client app frontend** +- `apps/clients/src/routes.tsx` — add `/login`, `/reset-password`, `/set-password`, and redirect handling; remove `/auth/callback` from primary flow +- `apps/clients/src/components/ClientLayout.tsx` — stop rendering dead-end unauthorized state and rely on auth gate redirect behavior +- `apps/clients/src/lib/supabase.ts` — no behavioral change expected, but verify redirect URLs and auth persistence assumptions +- `apps/clients/src/i18n.ts` — add auth namespaces reused from main or from shared locale files +- `apps/clients/src/main.tsx` — ensure new pages have needed providers +- `apps/clients/src/pages/AuthCallback.tsx` — remove or reduce to a temporary compatibility shim +- `apps/clients/src/pages/ClientTabloPage.tsx` +- `apps/clients/src/pages/ClientTabloListPage.tsx` +- `apps/clients/src/components/ClientLayout.test.tsx` +- `apps/clients/src/pages/ClientTabloPage.test.tsx` + +--- + +## Chunk 1: Database And API Invite Lifecycle + +### Task 1: Replace callback invite semantics with setup-token lifecycle + +**Files:** +- Create: `supabase/migrations/20260418110000_client_password_invites.sql` +- Modify: `packages/shared-types/src/database.types.ts` +- Test: `apps/api/src/__tests__/routes/clientInvites.test.ts` + +- [ ] **Step 1: Write the failing API test cases for the new lifecycle** + +Add or replace route tests in `apps/api/src/__tests__/routes/clientInvites.test.ts` for: + +```ts +it("creates a setup token for a first-time client invite", async () => {}); +it("does not create a setup token for an already-onboarded client", async () => {}); +it("rejects reused setup tokens", async () => {}); +it("rejects expired setup tokens", async () => {}); +it("marks cancelled pending setup tokens unusable", async () => {}); +``` + +Model the first-time case so it asserts: +- `client_invites.is_pending === true` +- a setup token exists +- `sendMail` is called with a setup URL targeting `clients.xtablo.com` + +Model the onboarded case so it asserts: +- no new setup token row is created +- `sendMail` is called with a direct `/tablo/:tabloId` URL + +- [ ] **Step 2: Run the targeted API tests to verify failure** + +Run: + +```bash +pnpm --filter @xtablo/api test -- clientInvites.test.ts +``` + +Expected: +- FAIL because the current router still creates magic-link callback invites and still exposes `/accept/:token` + +- [ ] **Step 3: Write the migration** + +In `supabase/migrations/20260418110000_client_password_invites.sql`, evolve `client_invites` for setup-token lifecycle. Prefer modifying the existing table shape over creating a second invite table. + +The migration should include the minimal schema required for: + +```sql +ALTER TABLE public.client_invites + ADD COLUMN IF NOT EXISTS invite_type text NOT NULL DEFAULT 'setup', + ADD COLUMN IF NOT EXISTS used_at timestamptz, + ADD COLUMN IF NOT EXISTS cancelled_at timestamptz, + ADD COLUMN IF NOT EXISTS setup_completed_at timestamptz; + +-- If the old callback flow uses invite_token generically, keep the column +-- but redefine its meaning as the setup token for setup invites. + +CREATE INDEX IF NOT EXISTS idx_client_invites_email_tablo_pending + ON public.client_invites (invited_email, tablo_id, is_pending); +``` + +Also add any client-account marker needed to distinguish: +- invited client users who have not completed password setup +- onboarded client users who already have password login + +Keep the schema minimal. Avoid adding fields that can be derived from auth state unless tests require them. + +- [ ] **Step 4: Update generated database types** + +Update `packages/shared-types/src/database.types.ts` to reflect the migration: +- new `client_invites` columns +- any added client-profile/account lifecycle columns + +Use the repo’s current type-generation practice if available; otherwise make the minimal manual edit and note it in the commit message. + +- [ ] **Step 5: Refactor helper boundaries before touching the router** + +In `apps/api/src/helpers/helpers.ts`, split the current client invite helper behavior into smaller pieces with one responsibility each: + +```ts +export async function findOrCreateClientAccount(...) {} +export async function ensureClientTabloAccess(...) {} +export async function hasCompletedClientOnboarding(...) {} +export async function createClientSetupInvite(...) {} +``` + +Do not keep all onboarding, auth-user creation, and tablo-access behavior fused into one large helper. + +- [ ] **Step 6: Replace callback endpoints with setup-token endpoints** + +In `apps/api/src/routers/clientInvites.ts`, change the route surface to: + +```ts +POST /client-invites/:tabloId +GET /client-invites/setup/:token +POST /client-invites/setup/:token +GET /client-invites/:tabloId/pending +DELETE /client-invites/:tabloId/:inviteId +``` + +Behavior: +- `POST /:tabloId` + - create/reuse client account + - ensure tablo access + - if account is not onboarded: create pending setup token + send setup email + - if account is onboarded: skip setup token + send access notification email to `/tablo/:tabloId` +- `GET /setup/:token` + - return token metadata for `SetPasswordPage` + - reject missing / expired / cancelled / already-used tokens +- `POST /setup/:token` + - validate token again + - set password for the client auth user + - mark invite consumed immediately + - return success payload for the frontend + +Remove callback-style `accept/:token` logic from the primary flow. + +- [ ] **Step 7: Keep `apps/main` protected from client-only users** + +In `apps/api/src/middlewares/middleware.ts`, verify that `regularUserCheck` or equivalent main-app guard rejects `is_client` users cleanly. If the current behavior is already correct, only tighten the tests and leave code untouched. + +Add or update targeted test coverage in `apps/api/src/__tests__/middlewares/middlewares.test.ts`: + +```ts +it("returns 401 for client-only users on main-app protected routes", async () => {}); +``` + +- [ ] **Step 8: Run API verification** + +Run: + +```bash +pnpm --filter @xtablo/api test -- clientInvites.test.ts middlewares.test.ts +pnpm --filter @xtablo/api typecheck +``` + +Expected: +- PASS for invite lifecycle and middleware protection coverage + +- [ ] **Step 9: Commit** + +```bash +git add supabase/migrations/20260418110000_client_password_invites.sql \ + packages/shared-types/src/database.types.ts \ + apps/api/src/helpers/helpers.ts \ + apps/api/src/routers/clientInvites.ts \ + apps/api/src/__tests__/routes/clientInvites.test.ts \ + apps/api/src/__tests__/middlewares/middlewares.test.ts \ + apps/api/src/middlewares/middleware.ts +git commit -m "feat(api): add client password setup invite flow" +``` + +--- + +## Chunk 2: Shared Auth UI Extraction + +### Task 2: Extract the main login visual shell into a shared package + +**Files:** +- Create: `packages/auth-ui/package.json` +- Create: `packages/auth-ui/tsconfig.json` +- Create: `packages/auth-ui/src/index.ts` +- Create: `packages/auth-ui/src/AuthCardShell.tsx` +- Create: `packages/auth-ui/src/AuthEmailPasswordForm.tsx` +- Create: `packages/auth-ui/src/AuthInfoBanner.tsx` +- Modify: `apps/main/src/pages/login.tsx` +- Modify: `apps/main/src/pages/reset-password.tsx` +- Test: `apps/main/src/pages/login.test.tsx` +- Test: `apps/main/src/pages/reset-password.test.tsx` + +- [ ] **Step 1: Write failing rendering tests around the shared auth shell contract** + +Before extracting, add or update tests that pin the current main auth page structure at the right level: + +```ts +it("renders the main login page through a reusable auth shell", async () => {}); +it("renders the reset-password page through the shared auth shell", async () => {}); +``` + +Assert only stable behavior: +- heading renders +- email/password fields render +- forgot-password link renders +- shared shell wrapper test id or landmark renders + +Do not snapshot the entire page. + +- [ ] **Step 2: Run the main auth tests to verify current coverage gap** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/pages/login.test.tsx src/pages/reset-password.test.tsx --mode dev +``` + +Expected: +- FAIL or insufficient coverage for the extraction seam + +- [ ] **Step 3: Extract presentation-only auth UI** + +Create `packages/auth-ui` and move only visual/auth-form composition into it. + +Recommended split: + +```tsx +// AuthCardShell.tsx +export function AuthCardShell(props: { + title: string; + children: React.ReactNode; + backHomeHref?: string; + footer?: React.ReactNode; +}) {} + +// AuthEmailPasswordForm.tsx +export function AuthEmailPasswordForm(props: { + email: string; + password: string; + onEmailChange: (value: string) => void; + onPasswordChange: (value: string) => void; + onSubmit: (e: React.FormEvent) => void; + isPending?: boolean; + emailError?: string; + passwordError?: string; + submitLabel: string; + forgotPasswordHref?: string; +}) {} +``` + +Keep: +- theme toggle +- background +- card framing +- logo block +- stable form spacing and typography + +Out of scope for the shared package: +- actual Supabase mutations +- route-specific navigation +- Google login wiring +- signup flow behavior + +- [ ] **Step 4: Refactor main login and reset pages onto the shared auth UI** + +Update: +- `apps/main/src/pages/login.tsx` +- `apps/main/src/pages/reset-password.tsx` + +Keep existing behavior intact while removing duplicated layout markup. + +- [ ] **Step 5: Run verification for main auth pages** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/pages/login.test.tsx src/pages/reset-password.test.tsx --mode dev +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/auth-ui typecheck +``` + +Expected: +- PASS with no behavior regression in main auth pages + +- [ ] **Step 6: Commit** + +```bash +git add packages/auth-ui \ + apps/main/src/pages/login.tsx \ + apps/main/src/pages/reset-password.tsx \ + apps/main/src/pages/login.test.tsx \ + apps/main/src/pages/reset-password.test.tsx +git commit -m "refactor(auth): extract shared auth ui" +``` + +--- + +## Chunk 3: Client Portal Auth Routes And Redirect Flow + +### Task 3: Add client login, reset-password, set-password, and redirect memory + +**Files:** +- Create: `apps/clients/src/components/ClientAuthGate.tsx` +- Create: `apps/clients/src/pages/LoginPage.tsx` +- Create: `apps/clients/src/pages/ResetPasswordPage.tsx` +- Create: `apps/clients/src/pages/SetPasswordPage.tsx` +- Modify: `apps/clients/src/routes.tsx` +- Modify: `apps/clients/src/components/ClientLayout.tsx` +- Modify: `apps/clients/src/pages/AuthCallback.tsx` +- Modify: `apps/clients/src/i18n.ts` +- Test: `apps/clients/src/pages/LoginPage.test.tsx` +- Test: `apps/clients/src/pages/ResetPasswordPage.test.tsx` +- Test: `apps/clients/src/pages/SetPasswordPage.test.tsx` +- Test: `apps/clients/src/components/ClientLayout.test.tsx` +- Test: `apps/clients/src/pages/ClientTabloPage.test.tsx` + +- [ ] **Step 1: Write failing client auth route tests** + +Add coverage for the new expected client behavior: + +```ts +it("redirects unauthenticated /tablo/:tabloId requests to /login and resumes after login", async () => {}); +it("renders the client login page with shared auth ui", async () => {}); +it("submits forgot-password from the client login flow", async () => {}); +it("renders an invalid-token state on the set-password page", async () => {}); +it("submits password setup once and rejects token reuse", async () => {}); +``` + +Prefer route-level tests with mocked Supabase/API behavior over isolated unit tests. + +- [ ] **Step 2: Run the client auth tests to verify failure** + +Run: + +```bash +pnpm --filter @xtablo/clients exec vitest run \ + src/components/ClientLayout.test.tsx \ + src/pages/ClientTabloPage.test.tsx \ + src/pages/LoginPage.test.tsx \ + src/pages/ResetPasswordPage.test.tsx \ + src/pages/SetPasswordPage.test.tsx \ + --mode dev +``` + +Expected: +- FAIL because `/login`, `/reset-password`, and `/set-password` do not exist and protected client routes do not redirect correctly + +- [ ] **Step 3: Add a client auth gate with redirect memory** + +Create `apps/clients/src/components/ClientAuthGate.tsx` with behavior like: + +```tsx +export function ClientAuthGate({ children }: { children: React.ReactNode }) { + // if no session: + // store current pathname + search in localStorage + // navigate("/login") + // else render children +} +``` + +Use a client-specific storage key such as: + +```ts +const CLIENT_REDIRECT_KEY = "clients.redirectUrl"; +``` + +Do not reuse the main app’s generic redirect key unless the semantics are already isolated per app. + +- [ ] **Step 4: Build the client login and reset pages on top of shared auth UI** + +Implement: +- `apps/clients/src/pages/LoginPage.tsx` +- `apps/clients/src/pages/ResetPasswordPage.tsx` + +Behavior: +- login via `supabase.auth.signInWithPassword` +- forgot-password via `supabase.auth.resetPasswordForEmail` +- no signup affordance +- successful login resumes `clients.redirectUrl` if present, otherwise `/` + +- [ ] **Step 5: Build the one-time set-password page** + +Implement `apps/clients/src/pages/SetPasswordPage.tsx`: +- read the token from the URL +- call `GET /api/v1/client-invites/setup/:token` on mount +- render clear invalid / expired / used states +- submit new password to `POST /api/v1/client-invites/setup/:token` +- after success, sign in the user and navigate to the granted destination + +If the API returns enough information to sign the user in directly, use it. If not, perform a normal `signInWithPassword` after successful setup using the freshly set password. + +- [ ] **Step 6: Update client routes and remove callback-first flow** + +In `apps/clients/src/routes.tsx`, move to: + +```tsx +} /> +} /> +} /> +}> + } /> + } /> + +``` + +Reduce `AuthCallback.tsx` to: +- temporary compatibility notice, or +- redirect to `/login` + +Do not leave it as the primary entry path. + +- [ ] **Step 7: Update client translations and copy** + +In `apps/clients/src/i18n.ts`, reuse the main auth namespace if practical. If not, add the minimal client auth keys needed without duplicating the entire namespace unnecessarily. + +Required copy states: +- login +- forgot password +- set password +- invalid token +- expired token +- already-used token +- access granted / password set success + +- [ ] **Step 8: Run client verification** + +Run: + +```bash +pnpm --filter @xtablo/clients exec vitest run \ + src/components/ClientLayout.test.tsx \ + src/pages/ClientTabloPage.test.tsx \ + src/pages/LoginPage.test.tsx \ + src/pages/ResetPasswordPage.test.tsx \ + src/pages/SetPasswordPage.test.tsx \ + --mode dev +pnpm --filter @xtablo/clients typecheck +``` + +Expected: +- PASS for login, reset-password, set-password, and redirect-resume flow + +- [ ] **Step 9: Commit** + +```bash +git add apps/clients/src/routes.tsx \ + apps/clients/src/components/ClientAuthGate.tsx \ + apps/clients/src/components/ClientLayout.tsx \ + apps/clients/src/pages/LoginPage.tsx \ + apps/clients/src/pages/ResetPasswordPage.tsx \ + apps/clients/src/pages/SetPasswordPage.tsx \ + apps/clients/src/pages/AuthCallback.tsx \ + apps/clients/src/i18n.ts \ + apps/clients/src/pages/LoginPage.test.tsx \ + apps/clients/src/pages/ResetPasswordPage.test.tsx \ + apps/clients/src/pages/SetPasswordPage.test.tsx \ + apps/clients/src/components/ClientLayout.test.tsx \ + apps/clients/src/pages/ClientTabloPage.test.tsx +git commit -m "feat(clients): add password auth onboarding flow" +``` + +--- + +## Chunk 4: Main Invite UI And Full Verification + +### Task 4: Update main-app invite UX to match the new backend contract + +**Files:** +- Modify: `apps/main/src/pages/tablo-details.tsx` +- Modify: `apps/main/src/hooks/client_invites.ts` +- Modify: `apps/main/src/pages/tablo-details.layout.test.tsx` + +- [ ] **Step 1: Write failing main invite flow tests** + +Extend `apps/main/src/pages/tablo-details.layout.test.tsx` with cases like: + +```ts +it("shows password-setup onboarding messaging for first-time client invites", async () => {}); +it("shows access-notification messaging for already-onboarded client invites", async () => {}); +``` + +Assert only the user-facing contract: +- client invite UI is visible +- email field submits +- success state reflects either setup email sent or access notification sent + +- [ ] **Step 2: Run the targeted main invite tests** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run src/pages/tablo-details.layout.test.tsx --mode dev +``` + +Expected: +- FAIL because current UI still assumes the callback-style invite flow + +- [ ] **Step 3: Update the main invite hook contract** + +In `apps/main/src/hooks/client_invites.ts`, align the mutation response typing with the new API payload, for example: + +```ts +type ClientInviteResponse = { + success: true; + inviteMode: "setup" | "notification"; +}; +``` + +Avoid frontend logic that infers email mode from copy alone. + +- [ ] **Step 4: Update share-dialog copy and success handling** + +In `apps/main/src/pages/tablo-details.tsx`, keep the client invite UI active, but change the submission/success states to match the new flow: +- first-time invite: explain that the client will receive a password-setup email +- existing client: explain that the client will receive a direct access notification + +Do not reintroduce the old standard-email collaborator invite UI for this flow. + +- [ ] **Step 5: Run focused frontend verification** + +Run: + +```bash +pnpm --filter @xtablo/main exec vitest run \ + src/pages/tablo-details.layout.test.tsx \ + src/pages/login.test.tsx \ + src/pages/reset-password.test.tsx \ + --mode dev +pnpm --filter @xtablo/main typecheck +``` + +Expected: +- PASS for share dialog copy, login page extraction, and reset page extraction + +- [ ] **Step 6: Run cross-app final verification** + +Run: + +```bash +pnpm --filter @xtablo/api test -- clientInvites.test.ts middlewares.test.ts +pnpm --filter @xtablo/api typecheck +pnpm --filter @xtablo/auth-ui typecheck +pnpm --filter @xtablo/main typecheck +pnpm --filter @xtablo/clients typecheck +pnpm --filter @xtablo/main exec vitest run src/pages/tablo-details.layout.test.tsx src/pages/login.test.tsx src/pages/reset-password.test.tsx --mode dev +pnpm --filter @xtablo/clients exec vitest run src/components/ClientLayout.test.tsx src/pages/ClientTabloPage.test.tsx src/pages/LoginPage.test.tsx src/pages/ResetPasswordPage.test.tsx src/pages/SetPasswordPage.test.tsx --mode dev +``` + +If the API tests require local Supabase migrations first, run the repo-standard migration command before rerunning tests and record that in the implementation notes. + +- [ ] **Step 7: Commit** + +```bash +git add apps/main/src/pages/tablo-details.tsx \ + apps/main/src/hooks/client_invites.ts \ + apps/main/src/pages/tablo-details.layout.test.tsx +git commit -m "feat(main): update client invite onboarding messaging" +``` + +--- + +## Completion Notes + +- Keep commits small and aligned with the chunks above. +- Do not reintroduce permanent bearer links. +- Do not allow client-only users through `apps/main` guards, even if they authenticate successfully. +- Do not preserve `AuthCallback` as a hidden second primary flow; either remove it or make it an explicit compatibility dead-end. +- Prefer reusing the existing main auth translations where possible, but avoid coupling `apps/clients` directly to `apps/main` internals if extraction into a shared package is cleaner. diff --git a/packages/auth-ui/package.json b/packages/auth-ui/package.json new file mode 100644 index 0000000..7569c83 --- /dev/null +++ b/packages/auth-ui/package.json @@ -0,0 +1,32 @@ +{ + "name": "@xtablo/auth-ui", + "version": "0.0.0", + "private": true, + "type": "module", + "main": "./src/index.ts", + "types": "./src/index.ts", + "exports": { + ".": "./src/index.ts" + }, + "scripts": { + "typecheck": "tsc --noEmit", + "lint": "biome check .", + "lint:fix": "biome check --write .", + "format": "biome format --write ." + }, + "dependencies": { + "@xtablo/shared": "workspace:*", + "@xtablo/ui": "workspace:*", + "lucide-react": "^0.460.0", + "react": "19.0.0", + "react-dom": "19.0.0", + "tailwind-merge": "^3.0.2" + }, + "devDependencies": { + "@biomejs/biome": "2.2.5", + "@types/react": "19.0.10", + "@types/react-dom": "19.0.4", + "typescript": "^5.7.0", + "vite": "^6.2.2" + } +} diff --git a/packages/auth-ui/src/AuthCardShell.tsx b/packages/auth-ui/src/AuthCardShell.tsx new file mode 100644 index 0000000..3baca34 --- /dev/null +++ b/packages/auth-ui/src/AuthCardShell.tsx @@ -0,0 +1,125 @@ +import { useTheme } from "@xtablo/shared/contexts/ThemeContext"; +import { Button } from "@xtablo/ui/components/button"; +import { MonitorIcon, MoonIcon, SunIcon } from "lucide-react"; +import type { CSSProperties, MouseEventHandler, ReactNode } from "react"; +import { twMerge } from "tailwind-merge"; + +type AuthCardShellProps = { + title: string; + description?: ReactNode; + children: ReactNode; + background?: ReactNode; + topLeft?: ReactNode; + showThemeToggle?: boolean; + onBackdropClick?: () => void; + wrapperClassName?: string; + wrapperStyle?: CSSProperties; + onWrapperMouseMove?: MouseEventHandler; + onWrapperMouseLeave?: () => void; + isHovered?: boolean; + cardClassName?: string; +}; + +export function AuthCardShell({ + title, + description, + children, + background, + topLeft, + showThemeToggle = false, + onBackdropClick, + wrapperClassName, + wrapperStyle, + onWrapperMouseMove, + onWrapperMouseLeave, + isHovered = false, + cardClassName, +}: AuthCardShellProps) { + const { theme, setTheme } = useTheme(); + + const toggleTheme = () => { + if (theme === "light") { + setTheme("dark"); + } else if (theme === "dark") { + setTheme("system"); + } else { + setTheme("light"); + } + }; + + const themeIcon = + theme === "light" ? ( + + ) : theme === "dark" ? ( + + ) : ( + + ); + + return ( +
+ {background} + +
event.stopPropagation()} + > +
+ +
+ {topLeft || showThemeToggle ? ( +
+
{topLeft}
+ {showThemeToggle ? ( + + ) : null} +
+ ) : null} + +
+ Xtablo + Xtablo +
+ +
+

{title}

+ {description ?
{description}
: null} +
+ + {children} +
+
+
+ ); +} diff --git a/packages/auth-ui/src/AuthEmailPasswordForm.tsx b/packages/auth-ui/src/AuthEmailPasswordForm.tsx new file mode 100644 index 0000000..b97c1be --- /dev/null +++ b/packages/auth-ui/src/AuthEmailPasswordForm.tsx @@ -0,0 +1,83 @@ +import { Button } from "@xtablo/ui/components/button"; +import { FieldError } from "@xtablo/ui/components/field"; +import { Input } from "@xtablo/ui/components/input"; +import { Label } from "@xtablo/ui/components/label"; +import type { ReactNode } from "react"; + +type AuthEmailPasswordFormProps = { + email: string; + password: string; + onEmailChange: (value: string) => void; + onPasswordChange: (value: string) => void; + onSubmit: (event: React.FormEvent) => void; + submitLabel: string; + emailLabel: string; + passwordLabel: string; + emailPlaceholder: string; + passwordPlaceholder: string; + emailError?: string; + passwordError?: string; + isPending?: boolean; + footer?: ReactNode; + extraContent?: ReactNode; +}; + +export function AuthEmailPasswordForm({ + email, + password, + onEmailChange, + onPasswordChange, + onSubmit, + submitLabel, + emailLabel, + passwordLabel, + emailPlaceholder, + passwordPlaceholder, + emailError, + passwordError, + isPending = false, + footer, + extraContent, +}: AuthEmailPasswordFormProps) { + return ( +
+
+ + onEmailChange(event.target.value)} + required + placeholder={emailPlaceholder} + disabled={isPending} + /> + {emailError ? : null} +
+ +
+ + onPasswordChange(event.target.value)} + required + placeholder={passwordPlaceholder} + disabled={isPending} + /> + {passwordError ? : null} +
+ + {extraContent} + + + + {footer} +
+ ); +} diff --git a/packages/auth-ui/src/AuthInfoBanner.tsx b/packages/auth-ui/src/AuthInfoBanner.tsx new file mode 100644 index 0000000..a5554d2 --- /dev/null +++ b/packages/auth-ui/src/AuthInfoBanner.tsx @@ -0,0 +1,33 @@ +import { AlertCircle, CheckCircle2, InfoIcon } from "lucide-react"; +import { twMerge } from "tailwind-merge"; + +type AuthInfoBannerProps = { + message: string; + variant: "error" | "info" | "success"; +}; + +const variantStyles: Record = { + error: "bg-red-50 text-red-800 border-red-200 dark:bg-red-950/20 dark:text-red-200 dark:border-red-800", + info: "bg-blue-50 text-blue-800 border-blue-200 dark:bg-blue-950/20 dark:text-blue-200 dark:border-blue-800", + success: + "bg-green-50 text-green-800 border-green-200 dark:bg-green-950/20 dark:text-green-200 dark:border-green-800", +}; + +const variantIcon = { + error: AlertCircle, + info: InfoIcon, + success: CheckCircle2, +} satisfies Record; + +export function AuthInfoBanner({ message, variant }: AuthInfoBannerProps) { + const Icon = variantIcon[variant]; + + return ( +
+
+ +

{message}

+
+
+ ); +} diff --git a/packages/auth-ui/src/index.ts b/packages/auth-ui/src/index.ts new file mode 100644 index 0000000..5c6d6f3 --- /dev/null +++ b/packages/auth-ui/src/index.ts @@ -0,0 +1,3 @@ +export { AuthCardShell } from "./AuthCardShell"; +export { AuthEmailPasswordForm } from "./AuthEmailPasswordForm"; +export { AuthInfoBanner } from "./AuthInfoBanner"; diff --git a/packages/auth-ui/tsconfig.json b/packages/auth-ui/tsconfig.json new file mode 100644 index 0000000..4976ebd --- /dev/null +++ b/packages/auth-ui/tsconfig.json @@ -0,0 +1,27 @@ +{ + "compilerOptions": { + "target": "ES2020", + "useDefineForClassFields": true, + "lib": ["ES2020", "DOM", "DOM.Iterable"], + "module": "ESNext", + "skipLibCheck": true, + "moduleResolution": "bundler", + "allowImportingTsExtensions": true, + "resolveJsonModule": true, + "isolatedModules": true, + "noEmit": true, + "jsx": "react-jsx", + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noFallthroughCasesInSwitch": true, + "baseUrl": ".", + "paths": { + "@xtablo/ui": ["../ui/src"], + "@xtablo/ui/*": ["../ui/src/*"], + "@xtablo/shared": ["../shared/src"], + "@xtablo/shared/*": ["../shared/src/*"] + } + }, + "include": ["src", "src/vite-env.d.ts"] +} diff --git a/packages/shared-types/src/database.types.ts b/packages/shared-types/src/database.types.ts index 3ab03a5..66b30a0 100644 --- a/packages/shared-types/src/database.types.ts +++ b/packages/shared-types/src/database.types.ts @@ -83,31 +83,43 @@ export type Database = { created_at: string; expires_at: string; id: number; + invite_type: string; invited_by: string; invited_email: string; invite_token: string; is_pending: boolean; + cancelled_at: string | null; + setup_completed_at: string | null; tablo_id: string; + used_at: string | null; }; Insert: { created_at?: string; expires_at?: string; id?: number; + invite_type?: string; invited_by: string; invited_email: string; invite_token: string; is_pending?: boolean; + cancelled_at?: string | null; + setup_completed_at?: string | null; tablo_id: string; + used_at?: string | null; }; Update: { created_at?: string; expires_at?: string; id?: number; + invite_type?: string; invited_by?: string; invited_email?: string; invite_token?: string; is_pending?: boolean; + cancelled_at?: string | null; + setup_completed_at?: string | null; tablo_id?: string; + used_at?: string | null; }; Relationships: [ { @@ -429,6 +441,7 @@ export type Database = { profiles: { Row: { avatar_url: string | null; + client_onboarded_at: string | null; created_at: string | null; email: string | null; first_name: string | null; @@ -443,6 +456,7 @@ export type Database = { }; Insert: { avatar_url?: string | null; + client_onboarded_at?: string | null; created_at?: string | null; email?: string | null; first_name?: string | null; @@ -457,6 +471,7 @@ export type Database = { }; Update: { avatar_url?: string | null; + client_onboarded_at?: string | null; created_at?: string | null; email?: string | null; first_name?: string | null; diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e797dbd..240d4f4 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -145,6 +145,9 @@ importers: '@tanstack/react-query': specifier: ^5.69.0 version: 5.90.5(react@19.0.0) + '@xtablo/auth-ui': + specifier: workspace:* + version: link:../../packages/auth-ui '@xtablo/chat-ui': specifier: workspace:* version: link:../../packages/chat-ui @@ -405,6 +408,9 @@ importers: '@typescript/native-preview': specifier: 7.0.0-dev.20251010.1 version: 7.0.0-dev.20251010.1 + '@xtablo/auth-ui': + specifier: workspace:* + version: link:../../packages/auth-ui '@xtablo/chat-ui': specifier: workspace:* version: link:../../packages/chat-ui @@ -629,6 +635,43 @@ importers: specifier: ^4.24.3 version: 4.44.0(@cloudflare/workers-types@4.20260411.1) + packages/auth-ui: + dependencies: + '@xtablo/shared': + specifier: workspace:* + version: link:../shared + '@xtablo/ui': + specifier: workspace:* + version: link:../ui + lucide-react: + specifier: ^0.460.0 + version: 0.460.0(react@19.0.0) + react: + specifier: 19.0.0 + version: 19.0.0 + react-dom: + specifier: 19.0.0 + version: 19.0.0(react@19.0.0) + tailwind-merge: + specifier: ^3.0.2 + version: 3.3.1 + devDependencies: + '@biomejs/biome': + specifier: 2.2.5 + version: 2.2.5 + '@types/react': + specifier: 19.0.10 + version: 19.0.10 + '@types/react-dom': + specifier: 19.0.4 + version: 19.0.4(@types/react@19.0.10) + typescript: + specifier: ^5.7.0 + version: 5.9.3 + vite: + specifier: ^6.2.2 + version: 6.4.1(@types/node@22.18.12)(jiti@2.6.1)(lightningcss@1.30.2)(terser@5.46.1)(tsx@4.20.6) + packages/chat-ui: dependencies: '@xtablo/shared': diff --git a/supabase/migrations/20260418110000_client_password_invites.sql b/supabase/migrations/20260418110000_client_password_invites.sql new file mode 100644 index 0000000..0746c80 --- /dev/null +++ b/supabase/migrations/20260418110000_client_password_invites.sql @@ -0,0 +1,27 @@ +ALTER TABLE public.profiles + ADD COLUMN IF NOT EXISTS client_onboarded_at timestamptz; + +COMMENT ON COLUMN public.profiles.client_onboarded_at IS + 'Timestamp when a client portal user completed their one-time password setup.'; + +ALTER TABLE public.client_invites + ADD COLUMN IF NOT EXISTS invite_type text NOT NULL DEFAULT 'setup', + ADD COLUMN IF NOT EXISTS used_at timestamptz, + ADD COLUMN IF NOT EXISTS cancelled_at timestamptz, + ADD COLUMN IF NOT EXISTS setup_completed_at timestamptz; + +COMMENT ON COLUMN public.client_invites.invite_type IS + 'Invite lifecycle type. setup = first-time password onboarding token.'; +COMMENT ON COLUMN public.client_invites.used_at IS + 'Timestamp when the setup token was consumed.'; +COMMENT ON COLUMN public.client_invites.cancelled_at IS + 'Timestamp when a pending setup invite was cancelled.'; +COMMENT ON COLUMN public.client_invites.setup_completed_at IS + 'Timestamp when password setup completed successfully.'; + +CREATE UNIQUE INDEX IF NOT EXISTS idx_client_invites_pending_setup_email_tablo + ON public.client_invites (tablo_id, invited_email) + WHERE is_pending = true AND invite_type = 'setup'; + +CREATE INDEX IF NOT EXISTS idx_client_invites_token_pending + ON public.client_invites (invite_token, is_pending);