/** * Server-side helpers for the DeviceToken Prisma model (Phase 08 #65). * * The Web Push register-device endpoint upserts on the unique * `token` column, the push-worker job filters by `revokedAt IS NULL` * for fan-out, and the cron prune script revokes rows older than 90d. * * Keeping these functions narrow and prisma-shape-only lets unit tests * inject a stub client without pulling in `@prisma/client` at all. */ import { getDbClient, type DbClient } from "./client.server.js"; export type DevicePlatform = "web"; export type PushProvider = "webpush"; const DEVICE_PLATFORMS = new Set(["web"]); const PUSH_PROVIDERS = new Set(["webpush"]); export function parseDevicePlatform(value: unknown): DevicePlatform | null { return typeof value === "string" && DEVICE_PLATFORMS.has(value as DevicePlatform) ? (value as DevicePlatform) : null; } export function parsePushProvider(value: unknown): PushProvider | null { return typeof value === "string" && PUSH_PROVIDERS.has(value as PushProvider) ? (value as PushProvider) : null; } /** Default provider for a given platform when the client omits it. */ export function defaultPushProviderFor(platform: DevicePlatform): PushProvider { void platform; return "webpush"; } export type DeviceTokenRecord = { id: string; createdAt: Date; updatedAt: Date; userId: string; tenantId: string | null; platform: string; token: string; pushProvider: string; appVersion: string | null; lastSeenAt: Date; revokedAt: Date | null; }; export type DeviceTokenClient = { deviceToken: { upsert(args: { where: { token: string; userId: string }; create: { userId: string; tenantId: string | null; platform: DevicePlatform; token: string; pushProvider: PushProvider; appVersion?: string | null; }; update: { tenantId: string | null; platform: DevicePlatform; pushProvider: PushProvider; appVersion?: string | null; lastSeenAt: Date; revokedAt: null; }; }): Promise; update(args: { where: { token: string; userId: string; tenantId: string | null }; data: { revokedAt: Date }; }): Promise; updateMany(args: { where: { userId: string; revokedAt: null }; data: { revokedAt: Date }; }): Promise<{ count: number }>; findMany(args: { where: { userId?: string; tenantId?: string; revokedAt?: null }; orderBy?: { createdAt: "desc" | "asc" }; take?: number; }): Promise; findUnique(args: { where: { token: string } }): Promise; }; }; export type RegisterDeviceTokenInput = { userId: string; tenantId: string | null; platform: DevicePlatform; token: string; pushProvider?: PushProvider; appVersion?: string | null; }; /** * Idempotent upsert keyed by `token`. Re-registration of the same token * (typical on app cold-start) just bumps `lastSeenAt` and clears any * prior `revokedAt`. */ export async function registerDeviceToken( input: RegisterDeviceTokenInput, client: DeviceTokenClient = getDbClient() as unknown as DeviceTokenClient, ): Promise { const provider = input.pushProvider ?? defaultPushProviderFor(input.platform); const now = new Date(); return client.deviceToken.upsert({ // Keep the globally unique token bound to its authenticated owner. If the // same token already belongs to another user, the filtered update cannot // match and the create path fails closed on the unique constraint. where: { token: input.token, userId: input.userId }, create: { userId: input.userId, tenantId: input.tenantId, platform: input.platform, token: input.token, pushProvider: provider, appVersion: input.appVersion ?? null, }, update: { tenantId: input.tenantId, platform: input.platform, pushProvider: provider, appVersion: input.appVersion ?? null, lastSeenAt: now, revokedAt: null, }, }); } /** * Mark a single token revoked. Called when the push provider responds * with `Unregistered` / `InvalidRegistration` so the next fan-out pass * skips this token. */ export async function revokeDeviceToken( input: { token: string; userId: string; tenantId: string | null }, client: DeviceTokenClient = getDbClient() as unknown as DeviceTokenClient, ): Promise { try { return await client.deviceToken.update({ where: { token: input.token, userId: input.userId, tenantId: input.tenantId, }, data: { revokedAt: new Date() }, }); } catch { return null; } } /** Revoke all active tokens for a user (logout / password-change hook). */ export async function revokeDeviceTokensForUser( userId: string, client: DeviceTokenClient = getDbClient() as unknown as DeviceTokenClient, ): Promise { const { count } = await client.deviceToken.updateMany({ where: { userId, revokedAt: null }, data: { revokedAt: new Date() }, }); return count; } /** * List active tokens for fan-out. Scoped by user (always required) plus * optional tenant. Returns at most `take` tokens, newest first. */ export async function listActiveDeviceTokens( args: { userId: string; tenantId?: string; take?: number }, client: DeviceTokenClient = getDbClient() as unknown as DeviceTokenClient, ): Promise { return client.deviceToken.findMany({ where: { userId: args.userId, ...(args.tenantId ? { tenantId: args.tenantId } : {}), revokedAt: null, }, orderBy: { createdAt: "desc" }, take: args.take ?? 100, }); } export async function findDeviceTokenByToken( token: string, client: DeviceTokenClient = getDbClient() as unknown as DeviceTokenClient, ): Promise { return client.deviceToken.findUnique({ where: { token } }); } // Re-export DbClient so call-sites in the API / worker can keep their // type assertion narrow without needing an extra import path. export type { DbClient };