SystemsAuthentication flow

Add a new site or app

Checklist for wiring a new Ziteox site into Ziteox Account sign-in.

Add a new site or app

How to connect a new first-party site or tool to Ziteox Account (auth.ziteox.com), the same way Admin and Client do it.

Copy from ziteox-client for a normal product site (no staff / forced two-step). Copy from ziteox-admin only when the site needs staff and fresh two-step rules like Admin.

Checklist

1. Pick a client id

  • Lowercase string, stable forever (e.g. partner, rail).
  • Becomes core.apps.key and the handoff client_id.
  • Account looks up the site secret as ZITEOX_SITE_SECRET_<CLIENT_ID> (uppercased) via siteSecretEnvKey in packages/auth — e.g. partner → ZITEOX_SITE_SECRET_PARTNER.

2. Register the app in core.apps

Add a migration under ziteox-admin/supabase/migrations/ that inserts (or updates) the row. Secrets stay in env, never in SQL.

insert into core.apps (
  key,
  label,
  allowed_origins,
  callback_urls,
  require_staff,
  require_second_factor,
  max_second_factor_age_seconds
) values (
  'partner',
  'Ziteox Partner',
  array['https://partner.ziteox.com']::text[],
  array['https://partner.ziteox.com/auth/handoff']::text[],
  false,  -- staff gate
  false,  -- require two-step at handoff
  null    -- or e.g. 43200 for 12h freshness
)
on conflict (key) do update set
  allowed_origins = excluded.allowed_origins,
  callback_urls = excluded.callback_urls,
  require_staff = excluded.require_staff,
  require_second_factor = excluded.require_second_factor,
  max_second_factor_age_seconds = excluded.max_second_factor_age_seconds;
ColumnTypical product siteAdmin-like site
callback_urlshttps://<host>/auth/handoffsame pattern
require_stafffalsetrue
require_second_factorfalsetrue
max_second_factor_age_secondsnull43200 (12h)

See Site registration and secrets for how Account reads these columns.

3. Generate and set the site secret

  1. Generate a strong random value (32+ random bytes, hex or base64).
  2. On Account (Cloudflare Worker): set ZITEOX_SITE_SECRET_<APP> (uppercase client id).
  3. On the new site: set ZITEOX_SITE_SECRET to the same value.
  4. Never commit, log, or paste the value into docs or tickets.

4. Add site routes and helpers

Copy and rename from ziteox-client (simplest template):

Copy fromRole
ziteox-client/src/app/auth/start/route.tsStart handoff: state + PKCE verifier cookie → redirect to Account /handoff
ziteox-client/src/app/auth/handoff/route.tsCallback: check state, exchange code, setSession, redirect to return_to
ziteox-client/src/app/auth/signout/route.tsPOST local sign-out; GET only redirects (no sign-out)
ziteox-client/src/lib/auth-handoff.tsCookie helpers, build*HandoffStartUrl, redirect URI, return_to sanitize
ziteox-client/src/lib/client-middleware-auth.tsSession-optional paths (/sign-in, /auth/*) and redirect decisions
ziteox-client/src/lib/ziteox-auth/session-cookie.tsHost-only session cookie name + secure flag
ziteox-client/src/app/sign-in/page.tsx“Sign in with Ziteox Account” → /auth/start?return_to=…

Wire middleware the same way: middleware.ts → updateSession, and teach session refresh to use your cookie options. Keep /auth/start, /auth/handoff, and /auth/signout reachable without a session.

Replace every hardcoded "client" / client origin helper with your client id and site origin helper from @ziteox/auth.

Start route skeleton (matches client/admin):

// app/auth/start/route.ts
import { NextResponse, type NextRequest } from "next/server";
import { getAuthAppOrigin } from "@ziteox/auth";
import { generateState, generateVerifier } from "@ziteox/auth/handoff";
// import your HANDOFF_COOKIE, cookie write opts, build*StartUrl, sanitizeReturnTo

export async function GET(request: NextRequest) {
  const returnTo = sanitizeReturnTo(
    request.nextUrl.searchParams.get("return_to") ??
      request.nextUrl.searchParams.get("returnTo")
  );
  const state = generateState();
  const verifier = generateVerifier();
  const location = await buildHandoffStartUrl({
    authOrigin: getAuthAppOrigin(),
    state,
    verifier,
    returnTo,
  });
  const response = NextResponse.redirect(location, 303);
  response.cookies.set(
    HANDOFF_COOKIE,
    JSON.stringify({ state, verifier, returnTo }),
    handoffCookieWriteOptions()
  );
  return response;
}

Sign-out route skeleton (POST only signs out; GET must not):

// app/auth/signout/route.ts
export async function GET(request: NextRequest) {
  return NextResponse.redirect(new URL("/sign-in", request.url), 303);
}

export async function POST(request: NextRequest) {
  const response = NextResponse.redirect(new URL("/sign-in", request.url), 303);
  // createClientForResponse → signOut({ scope: "local" })
  // clear handoff cookie
  return response;
}

Handoff callback is longer (token exchange, draft-user checks, optional org cookie). Copy the client file and change client_id, secret env, and redirect URI helpers — do not invent a shorter exchange.

Host-only cookie, no domain attribute. Pattern used today:

SiteCookie name
Adminsb-zx-admin-auth-token
Clientsb-zx-client-auth-token
New sitesb-zx-<app>-auth-token

Distinct names matter on localhost, where several apps can share a host and would otherwise fight over one Supabase session cookie.

6. Sign-in and sign-out UI

  • Sign in: link or button to /auth/start?return_to=<current path> (path only, same origin).
  • Sign out: HTML form method="post" action="/auth/signout". Never a prefetched GET link to a logout URL.

7. Local development fixture

For local Account with ZITEOX_SITE_REGISTRY=local:

  1. Add the site to localHandoffSitesFromEnv() in packages/auth/src/handoff/registry.ts (today only admin and client are built from ADMIN_APP_URL / CLIENT_APP_URL).
  2. Prefer a site origin helper in packages/auth/src/sites.ts (Partner already has getPartnerSiteOrigin).
  3. Add a localhost / *.localhost origin to DEV_ORIGINS in safe-return-to.ts if needed.
  4. Give the site a fixed local port (Admin 3000, Client 3001, Account 3002) and matching *_APP_URL / AUTH_APP_URL names.
  5. Use matching dummy ZITEOX_SITE_SECRET_<APP> (Account) and ZITEOX_SITE_SECRET (site).

Details: Security rules and local development.

8. Account-side code that still lists sites

Secret lookup is generic (ZITEOX_SITE_SECRET_${clientId.toUpperCase()}). You still need to touch explicit lists / labels when adding an app:

LocationWhat to update
packages/auth/src/handoff/registry.tsHandoffClientId, productionHandoffSites(), localHandoffSitesFromEnv()
packages/auth/src/sites.tsOrigin helper + env names for the new host
packages/auth/src/safe-return-to.tsProd / dev origin allowlists when used
packages/auth/src/audit.tsZiteoxPortal if you record portal-specific auth events
ziteox-auth/src/app/handoff/actions.tsportalForClient, appLabel; org binding today runs only when clientId === "client"
ziteox-auth/src/lib/app-connections.tsOptional display-name override (else uses core.apps.label / key)
ziteox-auth/src/app/handoff/page.tsxMetadata / UI copy that assumes Admin vs Client

Production registration itself comes from core.apps via SupabaseSiteRegistry — the migration is the source of truth there. The lists above matter for types, local fixtures, labels, and special handoff behavior.

9. Test checklist

  • Sign in from a deep page; after handoff you land on that path
  • Wrong state → failure page; no session
  • Expired or reused code → failure; code is single-use (~60s TTL)
  • Sign out of the new site (scope: "local"); Admin / Client / Account stay signed in
  • Staff / two-step: if require_staff or require_second_factor is set, wrong account or missing / stale 2FA is rejected
  • Unregistered redirect_uri or wrong site secret → no tokens

10. Deploy order

  1. Apply the DB migration (core.apps row)
  2. Set secrets on Account and on the new site (ZITEOX_SITE_SECRET_<APP> + ZITEOX_SITE_SECRET)
  3. Redeploy Account if you changed Account code or need new Worker secrets picked up
  4. Deploy the new site