feat: add client password invite flow

This commit is contained in:
Arthur Belleville 2026-04-18 11:09:04 +02:00
parent c2ad27c8c7
commit f02c36dbb7
No known key found for this signature in database
46 changed files with 2419 additions and 591 deletions

View file

@ -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<string, unknown> = { 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" },
});

View file

@ -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<ClientAccountResult> {
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 };
}

View file

@ -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<AuthEnv>();
const authFactory = createFactory<AuthEnv>();
const publicFactory = createFactory<BaseEnv>();
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 <noreply@xtablo.com>",
to: input.email,
subject: "Configurez votre accès client Xtablo",
html: `
<h2>Vous avez é invité sur Xtablo</h2>
<p>Bonjour,</p>
<p>Créez votre mot de passe via le lien ci-dessous pour accéder à votre espace client :</p>
<p><a href="${input.setupUrl}">Configurer mon mot de passe</a></p>
<p>Ce lien expire dans ${CLIENT_INVITE_EXPIRY_HOURS} heures et ne peut être utilisé qu'une seule fois.</p>
`,
});
};
const sendAccessNotificationEmail = async (
transporter: BaseEnv["Variables"]["transporter"],
input: { email: string; tabloUrl: string }
) => {
await transporter.sendMail({
from: "Xtablo <noreply@xtablo.com>",
to: input.email,
subject: "Vous avez maintenant accès à un nouveau tablo",
html: `
<h2>Vous avez maintenant accès à un tablo</h2>
<p>Bonjour,</p>
<p>Votre accès a é ajouté. Utilisez le lien ci-dessous pour ouvrir directement le tablo :</p>
<p><a href="${input.tabloUrl}">Ouvrir le tablo</a></p>
<p>Si vous n'êtes pas connecté, vous serez redirigé vers la page de connexion.</p>
`,
});
};
/** POST /:tabloId — Create a client invite (admin only) */
const createClientInvite = (middlewareManager: ReturnType<typeof MiddlewareManager.getInstance>) =>
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<typeof MiddlewareManag
.trim()
.toLowerCase();
if (!rawEmail || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(rawEmail)) {
if (!rawEmail || !isValidEmail(rawEmail)) {
return c.json({ error: "A valid email is required" }, 400);
}
// Create / find the client user and grant tablo access
const result = await createClientUser(supabase, rawEmail, tabloId, user.id);
if (!result.success || !result.userId) {
return c.json({ error: result.error ?? "Failed to create client user" }, 500);
const accountResult = await findOrCreateClientAccount(supabase, rawEmail);
if ("error" in accountResult) {
const errorMessage = accountResult.error;
if (errorMessage.includes("already belongs")) {
return c.json({ error: errorMessage }, 409);
}
return c.json({ error: errorMessage }, 500);
}
const accessResult = await ensureClientTabloAccess(
supabase,
tabloId,
accountResult.account.userId,
user.id
);
if (!accessResult.success) {
return c.json({ error: accessResult.error ?? "Failed to grant client access" }, 500);
}
const clientsUrl = getClientsUrl();
if (accountResult.account.client_onboarded_at) {
try {
await sendAccessNotificationEmail(transporter, {
email: rawEmail,
tabloUrl: `${clientsUrl}/tablo/${tabloId}`,
});
} catch (emailError) {
console.error("Failed to send client access notification email:", emailError);
}
return c.json({ success: true, inviteMode: "notification" as const });
}
const token = generateToken();
@ -36,127 +142,134 @@ const createClientInvite = (middlewareManager: ReturnType<typeof MiddlewareManag
Date.now() + CLIENT_INVITE_EXPIRY_HOURS * 60 * 60 * 1000
).toISOString();
const { error: insertError } = await supabase.from("client_invites").insert({
tablo_id: tabloId,
invited_email: rawEmail,
invited_by: user.id,
invite_token: token,
is_pending: true,
expires_at: expiresAt,
const inviteResult = await createClientSetupInvite(supabase, {
tabloId,
invitedEmail: rawEmail,
invitedBy: user.id,
token,
expiresAt,
});
if (insertError) {
if (insertError.code === "23505") {
if (!inviteResult.success) {
if (inviteResult.error?.includes("idx_client_invites_pending_setup_email_tablo")) {
return c.json({ error: "A pending invite already exists for this email and tablo" }, 409);
}
return c.json({ error: insertError.message }, 500);
return c.json({ error: inviteResult.error ?? "Failed to create setup invite" }, 500);
}
// Generate a Supabase magic link that redirects to the client portal callback
const clientsUrl = process.env.CLIENTS_URL || "https://clients.xtablo.com";
const redirectTo = `${clientsUrl}/auth/callback?token=${encodeURIComponent(token)}`;
const { data: linkData, error: magicLinkError } = await supabase.auth.admin.generateLink({
type: "magiclink",
email: rawEmail,
options: { redirectTo },
});
if (magicLinkError) {
console.error("Failed to generate magic link:", magicLinkError);
// Non-fatal: invite record is already created
} else if (linkData?.properties?.action_link) {
const transporter = c.get("transporter");
try {
await transporter.sendMail({
from: "Xtablo <noreply@xtablo.com>",
to: rawEmail,
subject: "Vous avez été invité sur Xtablo",
html: `
<h2>Vous avez é invité à collaborer sur un tablo</h2>
<p>Bonjour,</p>
<p>Cliquez sur le lien ci-dessous pour accéder à votre espace client :</p>
<p><a href="${linkData.properties.action_link}">Accéder à mon espace</a></p>
<p>Ce lien expire dans ${CLIENT_INVITE_EXPIRY_HOURS} heures.</p>
`,
});
} 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<typeof MiddlewareManager.getInstance>) =>
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<typeof MiddlewareManager.getInstance>
) =>
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<typeof MiddlewareManager.getInstance>) =>
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<typeof MiddlewareManag
const { data: invite, error: inviteError } = await supabase
.from("client_invites")
.select("id, invited_email, is_pending")
.select("id, invited_email, is_pending, invite_type")
.eq("id", inviteId)
.eq("tablo_id", tabloId)
.maybeSingle();
@ -197,10 +310,10 @@ const cancelClientInvite = (middlewareManager: ReturnType<typeof MiddlewareManag
return c.json({ error: "Invite is no longer pending" }, 400);
}
// Mark invite as cancelled
const cancelledAt = new Date().toISOString();
const { error: cancelError } = await supabase
.from("client_invites")
.update({ is_pending: false })
.update({ is_pending: false, cancelled_at: cancelledAt })
.eq("id", inviteId)
.eq("tablo_id", tabloId);
@ -208,7 +321,6 @@ const cancelClientInvite = (middlewareManager: ReturnType<typeof MiddlewareManag
return c.json({ error: cancelError.message }, 500);
}
// Revoke tablo access for the client user
if (invite.invited_email) {
const { data: clientProfile } = await supabase
.from("profiles")
@ -233,9 +345,17 @@ export const getClientInvitesRouter = () => {
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<BaseEnv>();
router.get("/setup/:token", ...getSetupInvite());
router.post("/setup/:token", ...completeSetupInvite());
return router;
};

View file

@ -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;
};

View file

@ -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:*",

View file

@ -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 <Outlet />;
}
if (isCheckingSession) {
return (
<div className="flex min-h-screen items-center justify-center bg-background">
<div className="h-8 w-8 animate-spin rounded-full border-b-2 border-primary" />
</div>
);
}
const redirectUrl = `${location.pathname}${location.search}${location.hash}`;
localStorage.setItem("clients.redirectUrl", redirectUrl);
return <Navigate to="/login" replace />;
}

View file

@ -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(<AppRoutes />, {
route: "/tablo/tablo-1",
testUser: undefined,
});
expect(await screen.findByTestId("auth-card-shell")).toBeInTheDocument();
expect(await screen.findByRole("button", { name: "Connexion" })).toBeInTheDocument();
});
});

View file

@ -14,19 +14,7 @@ function getInitials(email: string): string {
export function ClientLayout() {
const { session } = useSession();
if (!session) {
return (
<div className="min-h-screen flex items-center justify-center bg-background">
<div className="text-center space-y-3">
<p className="text-lg font-medium text-foreground">Accès non autorisé</p>
<p className="text-sm text-muted-foreground">
Veuillez utiliser le lien reçu dans votre email pour accéder à cette page.
</p>
</div>
</div>
);
}
if (!session) return null;
const email = session.user.email ?? "";
const initials = email ? getInitials(email) : "?";

View file

@ -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,

View file

@ -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,

View file

@ -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<string | null>(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 (
<div className="min-h-screen flex items-center justify-center bg-background">
<div className="text-center space-y-3 max-w-md px-4">
<p className="text-lg font-medium text-destructive">Erreur</p>
<p className="text-sm text-muted-foreground">{error}</p>
</div>
</div>
);
}
return (
<div className="min-h-screen flex items-center justify-center bg-background">
<div className="text-center space-y-3">
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto" />
<p className="text-sm text-muted-foreground">Authentification en cours...</p>
</div>
</div>
);
return <Navigate to="/login" replace />;
}

View file

@ -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<typeof import("react-router-dom")>();
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(<LoginPage />, { 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(<LoginPage />, { 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");
});
});
});

View file

@ -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<string | null>(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<HTMLFormElement>) => {
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 (
<AuthCardShell
title={t("auth:login.title")}
topLeft={
<a
href="https://www.xtablo.com"
className="inline-flex items-center text-sm text-muted-foreground transition-colors hover:text-foreground"
>
<svg className="mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 19l-7-7 7-7"
/>
</svg>
{t("auth:common.backHome")}
</a>
}
showThemeToggle
>
<div className="space-y-6">
{error ? <AuthInfoBanner message={error} variant="error" /> : null}
<AuthEmailPasswordForm
email={email}
password={password}
onEmailChange={setEmail}
onPasswordChange={setPassword}
onSubmit={onSubmit}
submitLabel="Connexion"
emailLabel={t("common:labels.email")}
passwordLabel={t("common:labels.password")}
emailPlaceholder={t("auth:login.emailPlaceholder")}
passwordPlaceholder={t("auth:login.passwordPlaceholder")}
isPending={isPending}
extraContent={
<div className="flex items-center justify-end">
<Link
to="/reset-password"
className="text-sm text-[#804EEC] transition-colors hover:text-[#6f3fd4]"
>
{t("auth:login.forgotPassword")}
</Link>
</div>
}
/>
</div>
</AuthCardShell>
);
}

View file

@ -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(<ResetPasswordPage />, { testUser: undefined });
expect(screen.getByTestId("auth-card-shell")).toBeInTheDocument();
expect(screen.getByLabelText("Email")).toBeInTheDocument();
});
it("submits a password reset email", async () => {
renderWithProviders(<ResetPasswordPage />, { 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();
});
});
});

View file

@ -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<string | null>(null);
const [isPending, setIsPending] = useState(false);
const [isSubmitted, setIsSubmitted] = useState(false);
const onSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
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 (
<AuthCardShell title={t("auth:resetPassword.title")} description={t("auth:resetPassword.description")}>
<div className="space-y-6">
{error ? <AuthInfoBanner message={error} variant="error" /> : null}
{isSubmitted ? (
<div className="space-y-4">
<AuthInfoBanner message="Vérifiez votre boîte mail pour continuer." variant="success" />
<Link className="block" to="/login">
<Button className="w-full">Retour à la connexion</Button>
</Link>
</div>
) : (
<form className="space-y-4" onSubmit={onSubmit}>
<div className="space-y-2">
<Label htmlFor="email">{t("common:labels.email")}</Label>
<Input
id="email"
name="email"
type="email"
value={email}
onChange={(event) => setEmail(event.target.value)}
placeholder={t("auth:resetPassword.emailPlaceholder")}
required
disabled={isPending}
/>
</div>
<Button className="w-full" type="submit" disabled={isPending}>
{t("auth:resetPassword.submit")}
</Button>
</form>
)}
</div>
</AuthCardShell>
);
}

View file

@ -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<typeof import("react-router-dom")>();
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(<SetPasswordPage />, {
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(<SetPasswordPage />, {
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");
});
});
});

View file

@ -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<InviteState>(token ? "loading" : "ready");
const [inviteDetails, setInviteDetails] = useState<InviteDetails | null>(null);
const [password, setPassword] = useState("");
const [confirmPassword, setConfirmPassword] = useState("");
const [error, setError] = useState<string | null>(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<HTMLFormElement>) => {
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 (
<AuthCardShell title="Définir votre mot de passe" description={description}>
<div className="flex justify-center py-8">
<div className="h-8 w-8 animate-spin rounded-full border-b-2 border-primary" />
</div>
</AuthCardShell>
);
}
if (inviteState === "invalid") {
return (
<AuthCardShell title="Lien invalide" description="Ce lien ne peut plus être utilisé.">
<AuthInfoBanner message={error ?? "Lien invalide"} variant="error" />
</AuthCardShell>
);
}
const shouldShowRecoveryHint = !isInviteFlow && !session;
return (
<AuthCardShell
title={isInviteFlow ? "Définir votre mot de passe" : t("updatePassword.title")}
description={description}
>
<div className="space-y-6">
{error ? <AuthInfoBanner message={error} variant="error" /> : null}
{shouldShowRecoveryHint ? (
<AuthInfoBanner
message="Utilisez le lien reçu par email pour définir ou réinitialiser votre mot de passe."
variant="info"
/>
) : null}
<form className="space-y-4" onSubmit={onSubmit}>
<div className="space-y-2">
<Label htmlFor="password">Mot de passe</Label>
<Input
id="password"
name="password"
type="password"
value={password}
onChange={(event) => setPassword(event.target.value)}
required
disabled={isPending}
/>
</div>
<div className="space-y-2">
<Label htmlFor="confirmPassword">Confirmer le mot de passe</Label>
<Input
id="confirmPassword"
name="confirmPassword"
type="password"
value={confirmPassword}
onChange={(event) => setConfirmPassword(event.target.value)}
required
disabled={isPending}
/>
</div>
<Button className="w-full" type="submit" disabled={isPending}>
Définir mon mot de passe
</Button>
</form>
</div>
</AuthCardShell>
);
}

View file

@ -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 (
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route path="/reset-password" element={<ResetPasswordPage />} />
<Route path="/set-password" element={<SetPasswordPage />} />
<Route path="/auth/callback" element={<AuthCallback />} />
<Route element={<ClientLayout />}>
<Route path="/tablo/:tabloId" element={<ClientTabloPage />} />
<Route path="/" element={<ClientTabloListPage />} />
<Route element={<ClientAuthGate />}>
<Route element={<ClientLayout />}>
<Route path="/tablo/:tabloId" element={<ClientTabloPage />} />
<Route path="/" element={<ClientTabloListPage />} />
</Route>
</Route>
</Routes>
);

View file

@ -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<typeof userEvent.setup> } => {
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 = (
<MemoryRouter initialEntries={[route]}>
<ThemeProvider>
<QueryClientProvider client={testQueryClient}>
<SessionTestProvider testUser={defaultUser}>{content}</SessionTestProvider>
<SessionTestProvider testUser={testUser}>{content}</SessionTestProvider>
</QueryClientProvider>
</ThemeProvider>
</MemoryRouter>

View file

@ -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"],

View file

@ -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"}
{"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"}

View file

@ -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:*",

View file

@ -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(),

View file

@ -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(),

View file

@ -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(),

View file

@ -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(),

View file

@ -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<PendingClientInvite>(`/api/v1/client-invites/${tabloId}`, {
email,
});
const { data } = await api.post<CreateClientInviteResponse>(
`/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 }

View file

@ -34,6 +34,7 @@ describe("LoginPage", () => {
it("renders all form elements", () => {
renderWithProviders(<LoginPage />);
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();

View file

@ -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 <SunIcon className="w-5 h-5" />;
case "dark":
return <MoonIcon className="w-5 h-5" />;
case "system":
return <MonitorIcon className="w-5 h-5" />;
default:
return <SunIcon className="w-5 h-5" />;
}
};
const onSubmit = (e: React.FormEvent) => {
e.preventDefault();
login({
@ -95,168 +64,100 @@ export function LoginPage() {
};
return (
<div className="min-h-screen flex items-center justify-center bg-linear-to-br from-primary/10 via-background to-secondary/5 animate-gradient-x bg-size-[400%_400%] relative overflow-hidden px-4 py-8 sm:px-6">
<AnimatedBackground />
<div
ref={cardRef}
className={twMerge(
"w-full max-w-lg rounded-2xl relative",
"transition-transform duration-200 ease-out will-change-transform"
)}
style={{ transform }}
onMouseMove={handleMouseMove}
onMouseLeave={handleMouseLeave}
onClick={(e) => e.stopPropagation()}
>
{/* Glow effect behind the card */}
<div className="absolute inset-0 rounded-2xl bg-linear-to-br from-primary/10 via-primary/5 to-secondary/10 blur-xl -z-10"></div>
<div
className={twMerge(
"relative w-full h-full p-5 sm:p-8 bg-card/80 backdrop-blur-md rounded-2xl border border-border z-10 transition-shadow duration-200",
isHovered
? "shadow-[0_15px_35px_rgba(0,0,0,0.15)] dark:shadow-[0_15px_35px_rgba(0,0,0,0.3)]"
: "shadow-xl shadow-black/10 dark:shadow-black/25"
)}
<AuthCardShell
title={t("auth:login.title")}
background={<AnimatedBackground />}
topLeft={
<a
href="https://www.xtablo.com"
className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<div className="mb-6 flex items-center justify-between">
<a
href="https://www.xtablo.com"
className="inline-flex items-center text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 19l-7-7 7-7"
/>
</svg>
{t("auth:common.backHome")}
</a>
{/* Theme Toggle */}
<Button
variant="ghost"
size="icon"
onClick={toggleTheme}
className="text-muted-foreground hover:text-foreground p-2"
aria-label={t("auth:common.themeToggle", { theme })}
>
{getThemeIcon()}
</Button>
</div>
{/* Xtablo Icon */}
<div className="flex justify-center mb-6">
<img
src="/logo_dark.png"
alt="Xtablo"
className="w-16 h-16 object-contain block dark:hidden"
<svg className="mr-2 h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M15 19l-7-7 7-7"
/>
<img
src="/logo_white.png"
alt="Xtablo"
className="w-16 h-16 object-contain hidden dark:block"
/>
</div>
</svg>
{t("auth:common.backHome")}
</a>
}
showThemeToggle
wrapperClassName="transition-transform duration-200 ease-out will-change-transform"
wrapperStyle={{ transform }}
onWrapperMouseMove={handleMouseMove}
onWrapperMouseLeave={handleMouseLeave}
isHovered={isHovered}
>
<div className="mb-6 text-center">
<Link
to="/login-v2"
className="inline-flex items-center text-sm text-[#804EEC] hover:text-[#6f3fd4] font-medium transition-colors"
>
{t("auth:login.newExperienceLink")}
</Link>
</div>
<h1 className="text-2xl sm:text-3xl font-bold text-foreground mb-6 sm:mb-8 text-center">
{t("auth:login.title")}
</h1>
<div className="mb-6 text-center">
<Link
to="/login-v2"
className="inline-flex items-center text-sm text-[#804EEC] hover:text-[#6f3fd4] font-medium transition-colors"
>
{t("auth:login.newExperienceLink")}
</Link>
</div>
<div className="space-y-4 flex flex-col items-center">
<form className="space-y-4 w-full max-w-md mx-auto" onSubmit={onSubmit}>
<div className="space-y-2">
<Label htmlFor="email">
{t("common:labels.email")} <span className="text-red-500">*</span>
</Label>
<Input
id="email"
name="email"
type="email"
value={formData.email}
onChange={(e) => setFormData({ ...formData, email: e.target.value })}
required
placeholder={t("auth:login.emailPlaceholder")}
/>
{errors?.email && <FieldError errors={[{ message: errors.email }]} />}
</div>
<div className="space-y-2">
<Label htmlFor="password">
{t("common:labels.password")} <span className="text-red-500">*</span>
</Label>
<Input
id="password"
name="password"
type="password"
value={formData.password}
onChange={(e) => setFormData({ ...formData, password: e.target.value })}
required
placeholder={t("auth:login.passwordPlaceholder")}
/>
{errors?.password && <FieldError errors={[{ message: errors.password }]} />}
</div>
<div className="flex items-center justify-end">
<Link
to="/reset-password"
className="text-sm text-purple-600 hover:text-purple-500 dark:text-purple-400 dark:hover:text-purple-300 transition-colors"
>
{t("auth:login.forgotPassword")}
</Link>
</div>
<Button className="w-full" type="submit">
{isPending ? t("auth:common.connecting") : t("auth:login.loginButton")}
</Button>
</form>
<div className="relative my-6">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-border"></div>
</div>
<div className="relative flex justify-center text-sm">
<span
className={twMerge(
"px-4 py-1 bg-background",
"text-muted-foreground",
"text-sm font-medium",
"rounded-full",
"relative z-10",
"before:absolute before:w-[100px] before:h-px before:bg-border before:left-[-110px] before:top-1/2",
"after:absolute after:w-[100px] after:h-px after:bg-border after:right-[-110px] after:top-1/2"
)}
>
{t("auth:common.orContinue")}
</span>
</div>
</div>
<LoginWithGoogle />
<p className="text-center text-sm text-muted-foreground">
{t("auth:login.noAccount")}{" "}
<div className="space-y-4 flex flex-col items-center">
<AuthEmailPasswordForm
email={formData.email}
password={formData.password}
onEmailChange={(email: string) => 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={
<div className="flex items-center justify-end">
<Link
to="/signup"
className="text-foreground hover:text-foreground/80 font-medium text-sm px-2 py-1 rounded hover:bg-muted transition-colors"
to="/reset-password"
className="text-sm text-purple-600 hover:text-purple-500 dark:text-purple-400 dark:hover:text-purple-300 transition-colors"
>
{t("auth:login.signupLink")}
{t("auth:login.forgotPassword")}
</Link>
</p>
</div>
}
/>
<div className="relative my-6">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-border"></div>
</div>
<div className="relative flex justify-center text-sm">
<span
className={twMerge(
"px-4 py-1 bg-background",
"text-muted-foreground",
"text-sm font-medium",
"rounded-full",
"relative z-10",
"before:absolute before:w-[100px] before:h-px before:bg-border before:left-[-110px] before:top-1/2",
"after:absolute after:w-[100px] after:h-px after:bg-border after:right-[-110px] after:top-1/2"
)}
>
{t("auth:common.orContinue")}
</span>
</div>
</div>
<LoginWithGoogle />
<p className="text-center text-sm text-muted-foreground">
{t("auth:login.noAccount")}{" "}
<Link
to="/signup"
className="text-foreground hover:text-foreground/80 font-medium text-sm px-2 py-1 rounded hover:bg-muted transition-colors"
>
{t("auth:login.signupLink")}
</Link>
</p>
</div>
</div>
</AuthCardShell>
);
}

View file

@ -16,6 +16,7 @@ describe("ResetPasswordPage", () => {
it("renders form with email input", () => {
renderWithProviders(<ResetPasswordPage />);
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();

View file

@ -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 (
<div
className="min-h-screen flex items-center justify-center bg-linear-to-br from-primary/10 via-background to-secondary/5"
onClick={() => navigate("/login")}
<AuthCardShell
title={t("resetPassword.emailSent")}
description={<Text>{t("resetPassword.checkInbox", { email })}</Text>}
onBackdropClick={() => navigate("/login")}
>
<div
className={twMerge(
"w-full max-w-lg p-8 bg-card/80 backdrop-blur-lg rounded-2xl",
"border border-border",
"shadow-xl"
)}
onClick={(e) => e.stopPropagation()}
>
<div className="text-center space-y-6">
<div className="flex justify-center">
<div className="rounded-full bg-green-100 dark:bg-green-900/20 p-3">
<CheckCircle2 className="w-12 h-12 text-green-600 dark:text-green-400" />
</div>
<div className="space-y-6 text-center">
<div className="flex justify-center">
<div className="rounded-full bg-green-100 dark:bg-green-900/20 p-3">
<CheckCircle2 className="w-12 h-12 text-green-600 dark:text-green-400" />
</div>
<div className="space-y-2">
<h1 className="text-3xl font-bold text-foreground">{t("resetPassword.emailSent")}</h1>
<Text className="text-muted-foreground">
{t("resetPassword.checkInbox", { email })}
</Text>
</div>
<div className="bg-blue-50 dark:bg-blue-950/20 border border-blue-200 dark:border-blue-800 rounded-lg p-4">
<div className="flex gap-3">
<MailIcon className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
<Text className="text-sm text-blue-800 dark:text-blue-200 text-left">
{t("resetPassword.emailInstructions")}
</Text>
</div>
</div>
<Link to="/login" className="block">
<Button className="mt-4">{t("resetPassword.backToLogin")}</Button>
</Link>
</div>
<AuthInfoBanner message={t("resetPassword.emailInstructions")} variant="info" />
<Link to="/login" className="block">
<Button className="mt-4">{t("resetPassword.backToLogin")}</Button>
</Link>
</div>
</div>
</AuthCardShell>
);
}
return (
<div
className="min-h-screen flex items-center justify-center bg-linear-to-br from-primary/10 via-background to-secondary/5"
onClick={() => navigate("/login")}
<AuthCardShell
title={t("resetPassword.title")}
description={<Text>{t("resetPassword.description")}</Text>}
onBackdropClick={() => navigate("/login")}
>
<div
className={twMerge(
"w-full max-w-lg p-8 bg-card/80 backdrop-blur-lg rounded-2xl",
"border border-border",
"shadow-xl"
)}
onClick={(e) => e.stopPropagation()}
>
<div className="space-y-6">
<div className="text-center">
<h1 className="text-3xl font-bold text-foreground mb-2">{t("resetPassword.title")}</h1>
<Text className="text-muted-foreground">{t("resetPassword.description")}</Text>
<div className="space-y-6">
{error ? <AuthInfoBanner message={error} variant="error" /> : null}
<form className="space-y-4" onSubmit={onSubmit}>
<div className="space-y-2">
<Label htmlFor="email">{t("resetPassword.emailLabel")}</Label>
<Input
id="email"
name="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder={t("resetPassword.emailPlaceholder")}
required
disabled={isPending}
className="transition-opacity disabled:opacity-50"
/>
</div>
{error && (
<div className="bg-red-50 dark:bg-red-950/20 border border-red-200 dark:border-red-800 rounded-lg p-4">
<div className="flex gap-3">
<AlertCircle className="w-5 h-5 text-red-600 dark:text-red-400 flex-shrink-0" />
<Text className="text-sm text-red-800 dark:text-red-200">{error}</Text>
</div>
</div>
)}
<Button className="w-full" type="submit" disabled={isPending}>
{isPending ? (
<>
<Loader2Icon className="w-4 h-4 mr-2 animate-spin" />
{t("resetPassword.sending")}
</>
) : (
t("resetPassword.submit")
)}
</Button>
</form>
<form className="space-y-4" onSubmit={onSubmit}>
<div className="space-y-2">
<Label htmlFor="email">{t("resetPassword.emailLabel")}</Label>
<Input
id="email"
name="email"
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
placeholder={t("resetPassword.emailPlaceholder")}
required
disabled={isPending}
className="transition-opacity disabled:opacity-50"
/>
</div>
<Button className="w-full" type="submit" disabled={isPending}>
{isPending ? (
<>
<Loader2Icon className="w-4 h-4 mr-2 animate-spin" />
{t("resetPassword.sending")}
</>
) : (
t("resetPassword.submit")
)}
</Button>
</form>
<p className="text-center text-sm text-muted-foreground">
<Link
to="/login"
className="text-foreground hover:text-foreground/80 font-medium transition-colors"
>
{t("resetPassword.backToLogin")}
</Link>
</p>
<div className="rounded-lg border border-blue-200 bg-blue-50 p-4 dark:border-blue-800 dark:bg-blue-950/20">
<div className="flex gap-3">
<MailIcon className="w-5 h-5 text-blue-600 dark:text-blue-400 flex-shrink-0 mt-0.5" />
<Text className="text-sm text-blue-800 dark:text-blue-200">
{t("resetPassword.emailInstructions")}
</Text>
</div>
</div>
<p className="text-center text-sm text-muted-foreground">
<Link
to="/login"
className="text-foreground hover:text-foreground/80 font-medium transition-colors"
>
{t("resetPassword.backToLogin")}
</Link>
</p>
</div>
</div>
</AuthCardShell>
);
}

View file

@ -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(<TabloDetailsPage />, {
@ -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();
});
});

View file

@ -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 */}
<div className="border-t border-border pt-4">
{USE_CLIENT_MAGIC_LINK_INVITES ? (
{USE_CLIENT_PASSWORD_INVITES ? (
<>
<div className="mb-3">
<h4 className="text-sm font-semibold text-foreground">Accès client</h4>
<p className="text-xs text-muted-foreground">
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.
</p>
</div>
@ -598,7 +598,7 @@ export const TabloDetailsPage = () => {
}}
disabled={!isEmailValid(clientInviteEmail)}
>
Envoyer le lien
Envoyer l'invitation
</Button>
)}
</div>

View file

@ -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,

View file

@ -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(),

View file

@ -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/*"]
}
},

View file

@ -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 repos 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 apps 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
<Route path="/login" element={<LoginPage />} />
<Route path="/reset-password" element={<ResetPasswordPage />} />
<Route path="/set-password" element={<SetPasswordPage />} />
<Route element={<ClientLayout />}>
<Route path="/tablo/:tabloId" element={<ClientAuthGate><ClientTabloPage /></ClientAuthGate>} />
<Route path="/" element={<ClientAuthGate><ClientTabloListPage /></ClientAuthGate>} />
</Route>
```
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.

View file

@ -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"
}
}

View file

@ -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<HTMLDivElement>;
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" ? (
<SunIcon className="h-5 w-5" />
) : theme === "dark" ? (
<MoonIcon className="h-5 w-5" />
) : (
<MonitorIcon className="h-5 w-5" />
);
return (
<div
className="min-h-screen flex items-center justify-center bg-linear-to-br from-primary/10 via-background to-secondary/5 relative overflow-hidden px-4 py-8 sm:px-6"
onClick={onBackdropClick}
>
{background}
<div
className={twMerge("w-full max-w-lg rounded-2xl relative", wrapperClassName)}
style={wrapperStyle}
onMouseMove={onWrapperMouseMove}
onMouseLeave={onWrapperMouseLeave}
onClick={(event) => event.stopPropagation()}
>
<div className="absolute inset-0 rounded-2xl bg-linear-to-br from-primary/10 via-primary/5 to-secondary/10 blur-xl -z-10" />
<div
data-testid="auth-card-shell"
className={twMerge(
"relative w-full h-full p-5 sm:p-8 bg-card/80 backdrop-blur-md rounded-2xl border border-border z-10 transition-shadow duration-200",
isHovered
? "shadow-[0_15px_35px_rgba(0,0,0,0.15)] dark:shadow-[0_15px_35px_rgba(0,0,0,0.3)]"
: "shadow-xl shadow-black/10 dark:shadow-black/25",
cardClassName
)}
>
{topLeft || showThemeToggle ? (
<div className="mb-6 flex items-center justify-between">
<div>{topLeft}</div>
{showThemeToggle ? (
<Button
variant="ghost"
size="icon"
onClick={toggleTheme}
className="text-muted-foreground hover:text-foreground p-2"
aria-label={`change theme (${theme})`}
>
{themeIcon}
</Button>
) : null}
</div>
) : null}
<div className="mb-6 flex justify-center">
<img
src="/logo_dark.png"
alt="Xtablo"
className="w-16 h-16 object-contain block dark:hidden"
/>
<img
src="/logo_white.png"
alt="Xtablo"
className="w-16 h-16 object-contain hidden dark:block"
/>
</div>
<div className="space-y-2 text-center mb-6">
<h1 className="text-2xl sm:text-3xl font-bold text-foreground">{title}</h1>
{description ? <div className="text-muted-foreground">{description}</div> : null}
</div>
{children}
</div>
</div>
</div>
);
}

View file

@ -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<HTMLFormElement>) => 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 (
<form className="space-y-4 w-full max-w-md mx-auto" onSubmit={onSubmit}>
<div className="space-y-2">
<Label htmlFor="email">{emailLabel}</Label>
<Input
id="email"
name="email"
type="email"
value={email}
onChange={(event) => onEmailChange(event.target.value)}
required
placeholder={emailPlaceholder}
disabled={isPending}
/>
{emailError ? <FieldError errors={[{ message: emailError }]} /> : null}
</div>
<div className="space-y-2">
<Label htmlFor="password">{passwordLabel}</Label>
<Input
id="password"
name="password"
type="password"
value={password}
onChange={(event) => onPasswordChange(event.target.value)}
required
placeholder={passwordPlaceholder}
disabled={isPending}
/>
{passwordError ? <FieldError errors={[{ message: passwordError }]} /> : null}
</div>
{extraContent}
<Button className="w-full" type="submit" disabled={isPending}>
{submitLabel}
</Button>
{footer}
</form>
);
}

View file

@ -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<AuthInfoBannerProps["variant"], string> = {
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<AuthInfoBannerProps["variant"], typeof AlertCircle>;
export function AuthInfoBanner({ message, variant }: AuthInfoBannerProps) {
const Icon = variantIcon[variant];
return (
<div className={twMerge("rounded-lg border p-4", variantStyles[variant])}>
<div className="flex gap-3">
<Icon className="mt-0.5 h-5 w-5 shrink-0" />
<p className="text-sm">{message}</p>
</div>
</div>
);
}

View file

@ -0,0 +1,3 @@
export { AuthCardShell } from "./AuthCardShell";
export { AuthEmailPasswordForm } from "./AuthEmailPasswordForm";
export { AuthInfoBanner } from "./AuthInfoBanner";

View file

@ -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"]
}

View file

@ -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;

View file

@ -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':

View file

@ -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);