xtablo-source/docs/superpowers/plans/2026-04-18-client-password-invite-flow.md
2026-04-18 11:09:04 +02:00

23 KiB
Raw Blame History

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:

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:

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:

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:

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:

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:

it("returns 401 for client-only users on main-app protected routes", async () => {});
  • Step 8: Run API verification

Run:

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

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:

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:

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:

// 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:

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

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:

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:

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:

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:

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:

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

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

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:

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:

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:

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:

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:

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
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.