ubiquitous-invention/apps/web/server/lib/identity.ts

80 lines
2.6 KiB
TypeScript
Raw Normal View History

feat(identity): schema + helpers + read-only profile UI (Task 1, part 1/2) First half of Task-multi-email-identity. Lays down everything except the NextAuth callback wiring, which is gated on a research subagent finishing its survey of OAuth provider behavior for the email_verified claim across GitHub, Google, and Authentik. Schema (packages/database): * New user_email_identities table colocated with `users` in users.ts. Columns: id, user_id (FK), email (lowercased), verified_at, source, created_at, last_used_at. * Indexes: user_id, email, unique(user_id, email), and a PARTIAL unique index on email WHERE verified_at IS NOT NULL — a verified email resolves to exactly one users row globally, while unverified rows (none today; placeholder for the manual-verification follow-up) do not share the constraint. * Drizzle relation: users.emailIdentities -> userEmailIdentities, and the inverse one(users) relation. * Migration 0005 generated by db:generate, augmented with a backfill INSERT that seeds one source='primary' identity per existing users row using created_at as verified_at. Migration applied to dev DB; existing admin@tasks.dev user verified as 1:1 mapped. Server (apps/web/server): * apps/web/server/lib/identity.ts exports two pure read helpers: - userOwnsEmail(userId, email): boolean used by the (upcoming) invite-accept procedure to verify the human controls the invited address under any of their linked identities. - findUserIdByVerifiedEmail(email): the replacement for the old ensureUserIdByEmail lookup. Will be called from auth.ts once the OAuth research subagent returns. * apps/web/server/routers/identity.ts exposes identity.listMine — a protected procedure returning the caller's identities ordered by verifiedAt desc. Cross-user identity surface is intentionally NOT exposed here; that lives behind the workspace-scoped autocomplete in Task 3 with its own tenancy fence. UI (apps/web/app): * New route /[workspaceSlug]/settings/profile renders a read-only "Linked emails" section with per-identity row (email, source badge, verified state, last-used relative time) plus a hint that explains how to add another email (sign in via that email's OAuth provider). * Empty / loading / error states all handled. The "no identities" branch should never fire post-backfill but renders a friendly message instead of throwing. What's NOT in this commit: * auth.ts changes (ensureUserIdByEmail -> ensureUserIdByVerifiedEmail, OAuth callback identity upsert, cross-user conflict rejection). Waiting on subagent research to land the callback wiring correctly on the first try across all three providers. * Vitest tests. The pure helpers are 10-line query shims and the behavior-relevant assertion is the auth callback path — easier to write meaningful tests once that lands. All three CI gates green: pnpm lint (14 pre-existing warnings, unchanged), pnpm type-check (6/6 packages), pnpm test (14/14 existing tests across @tasks/shared, @tasks/database, @tasks/ai). Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-02 11:07:50 -04:00
import { and, eq, isNotNull } from "drizzle-orm";
import { userEmailIdentities } from "@tasks/database/schema";
import { db } from "@tasks/database";
/**
* Identity helpers built on top of the `user_email_identities` table.
*
* Why this module exists: invite acceptance (and any future feature that
* binds an action to "the human who owns this email address") needs to
* answer the question *"does this `users.id` actually control this email?"*
* without leaking the wrong answer when the user signed in via a different
* provider than the invite was sent to.
*
* The answer is: *yes* iff the user has a row in `user_email_identities`
* with the lowercased email and `verified_at IS NOT NULL`. Both the
* `source='primary'` mirror of `users.email` and any OAuth-claimed or
* manually-verified identity counts.
*/
/**
* Returns `true` iff the given user owns the given (lowercased) email
* as a verified identity. Case-insensitive callers may pass any case
* and this function normalizes.
*
* This is the single source of truth for "is this email under this
* user's control?" invite acceptance, profile-bound API access, and
* any future per-email permission check should funnel through here.
*/
export async function userOwnsEmail(
userId: string,
email: string,
): Promise<boolean> {
const emailLower = email.trim().toLowerCase();
if (!userId || !emailLower) return false;
const rows = await db
.select({ id: userEmailIdentities.id })
.from(userEmailIdentities)
.where(
and(
eq(userEmailIdentities.userId, userId),
eq(userEmailIdentities.email, emailLower),
isNotNull(userEmailIdentities.verifiedAt),
),
)
.limit(1);
return rows.length > 0;
}
/**
* Look up the `users.id` that owns a verified email, or `null` if no
* verified identity matches. Used by the sign-in callback to resolve
* an OAuth provider's email claim to the canonical user replacing
* the old `ensureUserIdByEmail` lookup against `users.email`.
*
* Note: this only returns matches where `verified_at IS NOT NULL`.
* The (future) "pending manual verification" rows from
* `Task-manual-email-verification` are correctly invisible here.
*/
export async function findUserIdByVerifiedEmail(
email: string,
): Promise<string | null> {
const emailLower = email.trim().toLowerCase();
if (!emailLower) return null;
const rows = await db
.select({ userId: userEmailIdentities.userId })
.from(userEmailIdentities)
.where(
and(
eq(userEmailIdentities.email, emailLower),
isNotNull(userEmailIdentities.verifiedAt),
),
)
.limit(1);
return rows[0]?.userId ?? null;
}