All files / apps / api/src / server / auth repository.ts

100% Statements 24/24
100% Branches 8/8
100% Functions 11/11
100% Lines 23/23

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228                                                              74x                               74x                   56x   56x         4x           4x                           46x                             46x                     45x                     45x                 45x                           3x                   5x 5x           5x             2x                       7x                                         8x 8x 8x   4x         4x                 4x                
import type { UserRole, UserStatus } from '@chattra/shared'
import { and, desc, eq, isNull, lt, sql } from 'drizzle-orm'
import type { DrizzleD1Database } from 'drizzle-orm/d1'
import {
  allowedDomains,
  conversationMembers,
  conversations,
  sessions,
  users,
  workspaces,
} from '../../db/schema'
 
// Sign-in, the token check and sessions (design 4.1, 4.2, 3.1). Times are integer ms.
 
export interface ActorRow {
  userId: string
  workspaceId: string
  role: UserRole
  status: UserStatus
  tokensValidAfter: number
  sessionId: string | null
  sessionEndedAt: number | null
  sessionLastSeenAt: number | null
}
 
/** The token check's one D1 read: the person by Firebase uid, and the session of this sign-in. */
export async function findActor(
  db: DrizzleD1Database,
  firebaseUid: string,
  authTimeMs: number,
): Promise<ActorRow | undefined> {
  const [row] = await db
    .select({
      userId: users.id,
      workspaceId: users.workspaceId,
      role: users.role,
      status: users.status,
      tokensValidAfter: users.tokensValidAfter,
      sessionId: sessions.id,
      sessionEndedAt: sessions.endedAt,
      sessionLastSeenAt: sessions.lastSeenAt,
    })
    .from(users)
    .leftJoin(sessions, and(eq(sessions.userId, users.id), eq(sessions.authTime, authTimeMs)))
    .where(eq(users.firebaseUid, firebaseUid))
    .limit(1)
 
  return row
}
 
export type UserRow = typeof users.$inferSelect
 
/** A person is keyed by Google's sub, never the email (design 4.1). */
export async function findUserByGoogleSub(
  db: DrizzleD1Database,
  googleSub: string,
): Promise<UserRow | undefined> {
  const [row] = await db.select().from(users).where(eq(users.googleSub, googleSub)).limit(1)
 
  return row
}
 
/** Whether a person already holds this email, compared as its unique index does: ignoring case. */
export async function isEmailTaken(db: DrizzleD1Database, email: string): Promise<boolean> {
  const [row] = await db
    .select({ id: users.id })
    .from(users)
    .where(sql`lower(${users.email}) = lower(${email})`)
    .limit(1)
 
  return row !== undefined
}
 
export interface SignInTarget {
  workspaceId: string
  ownerId: string | null
  generalId: string | null
}
 
/** The workspace that allows this domain (compared case-insensitively), with its owner and #general. */
export async function findSignInTarget(
  db: DrizzleD1Database,
  domain: string,
): Promise<SignInTarget | undefined> {
  const [row] = await db
    .select({
      workspaceId: allowedDomains.workspaceId,
      ownerId: workspaces.ownerId,
      generalId: conversations.id,
    })
    .from(allowedDomains)
    .innerJoin(workspaces, eq(workspaces.id, allowedDomains.workspaceId))
    .leftJoin(
      conversations,
      and(eq(conversations.workspaceId, workspaces.id), eq(conversations.isGeneral, 1)),
    )
    .where(sql`lower(${allowedDomains.domain}) = lower(${domain})`)
    .limit(1)
 
  return row
}
 
export type NewUser = typeof users.$inferInsert
export type NewSession = typeof sessions.$inferInsert
 
/** First sign-in: the person, ownership, #general and the session in one batch (design 3.1). */
export async function createPerson(
  db: DrizzleD1Database,
  { user, session, generalId }: { user: NewUser; session: NewSession; generalId: string | null },
): Promise<void> {
  const joinGeneral = generalId
    ? [
        db.insert(conversationMembers).values({
          conversationId: generalId,
          userId: user.id,
          joinedAt: user.createdAt,
        }),
      ]
    : []
  // Only while the workspace has no owner, so a second OWNER_EMAIL row can never take it over.
  const claimOwnership =
    user.role === 'owner'
      ? [
          db
            .update(workspaces)
            .set({ ownerId: user.id })
            .where(and(eq(workspaces.id, user.workspaceId), isNull(workspaces.ownerId))),
        ]
      : []
 
  await db.batch([
    db.insert(users).values(user),
    ...claimOwnership,
    ...joinGeneral,
    db.insert(sessions).values(session),
  ])
}
 
/** A returning sign-in: relink the Firebase uid (an account can be recreated) and stamp the time. */
export async function updateSignIn(
  db: DrizzleD1Database,
  userId: string,
  { firebaseUid, at }: { firebaseUid: string; at: number },
): Promise<void> {
  await db.update(users).set({ firebaseUid, lastSignInAt: at }).where(eq(users.id, userId))
}
 
export type SessionRow = typeof sessions.$inferSelect
 
/** Adds the session of one sign-in, or returns the one already there for (user, auth_time). */
export async function upsertSession(
  db: DrizzleD1Database,
  session: NewSession,
): Promise<SessionRow | undefined> {
  await db.insert(sessions).values(session).onConflictDoNothing()
  const [row] = await db
    .select()
    .from(sessions)
    .where(and(eq(sessions.userId, session.userId), eq(sessions.authTime, session.authTime)))
    .limit(1)
 
  return row
}
 
export async function touchSession(
  db: DrizzleD1Database,
  { userId, sessionId, at }: { userId: string; sessionId: string; at: number },
): Promise<void> {
  await db
    .update(sessions)
    .set({ lastSeenAt: at })
    .where(and(eq(sessions.id, sessionId), eq(sessions.userId, userId)))
}
 
/** One page of a person's open sessions, newest first; UUIDv7 ids sort by creation time. */
export async function listOpenSessions(
  db: DrizzleD1Database,
  userId: string,
  { limit, cursor }: { limit: number; cursor?: string },
): Promise<SessionRow[]> {
  return db
    .select()
    .from(sessions)
    .where(
      and(
        eq(sessions.userId, userId),
        isNull(sessions.endedAt),
        cursor ? lt(sessions.id, cursor) : undefined,
      ),
    )
    .orderBy(desc(sessions.id))
    .limit(limit)
}
 
/** Ends one of this person's sessions. False when the id is not theirs (or does not exist). */
export async function endSession(
  db: DrizzleD1Database,
  userId: string,
  sessionId: string,
  at: number,
): Promise<boolean> {
  const owned = and(eq(sessions.id, sessionId), eq(sessions.userId, userId))
  const [row] = await db.select({ id: sessions.id }).from(sessions).where(owned).limit(1)
  if (!row) return false
 
  await db
    .update(sessions)
    .set({ endedAt: at })
    .where(and(owned, isNull(sessions.endedAt)))
 
  return true
}
 
/** Sign out everywhere: the token cut-off and every open session, in one batch (design 4.2). */
export async function endAllSessions(
  db: DrizzleD1Database,
  userId: string,
  { at, validAfter }: { at: number; validAfter: number },
): Promise<void> {
  await db.batch([
    db.update(users).set({ tokensValidAfter: validAfter }).where(eq(users.id, userId)),
    db
      .update(sessions)
      .set({ endedAt: at })
      .where(and(eq(sessions.userId, userId), isNull(sessions.endedAt))),
  ])
}