import { eq } from 'drizzle-orm'; import { db } from 'officerdb/db'; import { browserPairings } from './schema'; /** The caller's pairing salt, or null when they have never paired. */ export async function getPairingSalt(userId: number): Promise { const [row] = await db.select({ salt: browserPairings.salt }).from(browserPairings).where(eq(browserPairings.userId, userId)); return row?.salt ?? null; } /** * Store a salt for this account, replacing any previous one. * * Upsert rather than insert-or-check: the unique index is what guarantees one pairing per account, and * doing it in a single statement means a regenerate cannot race itself into two rows. */ export async function setPairingSalt(userId: number, salt: string): Promise { await db .insert(browserPairings) .values({ userId, salt }) .onConflictDoUpdate({ target: browserPairings.userId, set: { salt } }); } /** Forget the pairing. The old token stops resolving as soon as the sidecar is told. */ export async function clearPairing(userId: number): Promise { await db.delete(browserPairings).where(eq(browserPairings.userId, userId)); } /** Every pairing, for the sidecar to rebuild its token map on start. */ export async function allPairings(): Promise<{ userId: number; salt: string }[]> { return db.select({ userId: browserPairings.userId, salt: browserPairings.salt }).from(browserPairings); }