Skip to content

The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.

8.7 KB
Raw Blame
// Sign-in hand-back for the Linedesk app (iOS, Android; apps/mobile). Google refuses sign-ins in an app's web view and
// Apple wants its own sheet, so in the app a provider sign-in runs in the system browser (ASWebAuthenticationSession,
// Chrome Custom Tabs). That browser has its own cookies: its new session is not the app's. It is handed back like an
// OAuth code with PKCE (RFC 7636), tied to a provider sign-in made in that same flow:
// 1. The app makes a random verifier and opens `/app-sign-in?provider=…&challenge=<SHA-256 of it>` in the browser.
//    The page posts the challenge to `/app-sign-in/start`, which keeps it with the time in a signed, httpOnly cookie
//    of that browser (15 minutes), then goes to the provider.
// 2. Back from the provider, the page asks the person to confirm (continue only if they just tapped Sign in in the
//    app on this phone); only then does it ask `/app-sign-in/code`. A code is given only for a session the provider sign-in made after step 1's start
//    (an older session of that browser never counts), once per start: one use, 2 minutes, stored hashed with the user,
//    the challenge and the browser's session. The page sends it to the app on the server's own https address
//    (`/app-sign-in/back?code=…`), which only the real app can receive (universal link / verified app link, app-links.ts).
// 3. The app's web view redeems it with the verifier (`/app-sign-in/redeem`): only the app that started the sign-in
//    knows the verifier. The browser's session must still exist (a password reset or "sign out everywhere" in between
//    ends the hand-back too) and is ended then; the web view's own older session too. The new session is made by
//    Better Auth's adapter, so every session hook runs: a disabled account is refused (instance-admin.ts, session
//    create before: ACCOUNT_DISABLED), the audit log gets method `app`, the host is kept (host-sessions.ts).
// Every endpoint checks the request's origin like Better Auth's own sign-in endpoints (formCsrfMiddleware), so another
// site's form can neither start nor redeem (security review of #1997, H1, H2, L1, L2).
import { randomBytes } from 'node:crypto'
import { session as sessions, verification } from '@linedesk/db'
import type { BetterAuthPlugin } from 'better-auth'
import { APIError, createAuthEndpoint, formCsrfMiddleware, sessionMiddleware } from 'better-auth/api'
import { setSessionCookie } from 'better-auth/cookies'
import { and, eq, gt } from 'drizzle-orm'
import { z } from 'zod'
import { type Start, START_TTL_S, sessionFitsStart, sha256, verifierFits } from './app-sign-in-pkce.ts'
import { db } from './db.ts'

/** A code lasts 2 minutes: the app redeems it at once. */
const CODE_TTL_MS = 2 * 60 * 1000
const IDENTIFIER_PREFIX = 'app-sign-in:'
const START_COOKIE = 'app_sign_in'

export const APP_SIGN_IN_START_PATH = '/app-sign-in/start'
export const APP_SIGN_IN_CODE_PATH = '/app-sign-in/code'
export const APP_SIGN_IN_REDEEM_PATH = '/app-sign-in/redeem'

/** 32 random bytes in base64url (43 characters), the form of a verifier, a challenge and a code. */
const token43 = z.string().regex(/^[A-Za-z0-9_-]{43}$/)

/** The verification row of a code: only its hash is stored. */
const identifierOf = (code: string) => `${IDENTIFIER_PREFIX}${sha256(code)}`

type Stored = { userId: string; challenge: string; browserSessionId: string }

function readStart(value: string | null): Start | null {
  if (!value) return null
  try {
    const start = JSON.parse(value) as Partial<Start>
    return typeof start.challenge === 'string' && typeof start.at === 'number'
      ? { challenge: start.challenge, at: start.at }
      : null
  } catch {
    return null
  }
}

/**
 * Takes a code: deletes its row and returns what it held, in one statement, so two requests with the same code never
 * both get it. Null for an unknown, used or expired code.
 */
async function takeCode(code: string, now = new Date()): Promise<Stored | null> {
  const [row] = await db
    .delete(verification)
    .where(and(eq(verification.identifier, identifierOf(code)), gt(verification.expiresAt, now)))
    .returning({ value: verification.value })
  if (!row) return null
  try {
    const stored = JSON.parse(row.value) as Partial<Stored>
    return typeof stored.userId === 'string' &&
      typeof stored.challenge === 'string' &&
      typeof stored.browserSessionId === 'string'
      ? { userId: stored.userId, challenge: stored.challenge, browserSessionId: stored.browserSessionId }
      : null
  } catch {
    return null
  }
}

/**
 * The browser's session the code came from, if it still exists (not signed out, reset or revoked since): its token,
 * so it can be ended through Better Auth and its hooks.
 */
async function browserSessionToken(id: string, userId: string): Promise<string | null> {
  const [row] = await db
    .select({ token: sessions.token })
    .from(sessions)
    .where(and(eq(sessions.id, id), eq(sessions.userId, userId), gt(sessions.expiresAt, new Date())))
  return row?.token ?? null
}

// i18n-ignore: never shown; the web app says it in the reader's words for the code (auth.redirect.appSignInRefused).
const refused = () => new APIError('UNAUTHORIZED', { code: 'APP_SIGN_IN_REFUSED', message: 'Sign in again.' })

export const appSignIn = () =>
  ({
    id: 'app-sign-in',
    endpoints: {
      appSignInStart: createAuthEndpoint(
        APP_SIGN_IN_START_PATH,
        { method: 'POST', body: z.object({ challenge: token43 }), use: [formCsrfMiddleware] },
        async ctx => {
          const cookie = ctx.context.createAuthCookie(START_COOKIE, { maxAge: START_TTL_S })
          const start: Start = { challenge: ctx.body.challenge, at: Date.now() }
          await ctx.setSignedCookie(cookie.name, JSON.stringify(start), ctx.context.secret, cookie.attributes)
          return ctx.json({ ok: true })
        },
      ),
      appSignInCode: createAuthEndpoint(
        APP_SIGN_IN_CODE_PATH,
        { method: 'POST', use: [formCsrfMiddleware, sessionMiddleware] },
        async ctx => {
          const { session } = ctx.context.session
          const cookie = ctx.context.createAuthCookie(START_COOKIE)
          const start = readStart((await ctx.getSignedCookie(cookie.name, ctx.context.secret)) || null)
          // One code per start.
          ctx.setCookie(cookie.name, '', { ...cookie.attributes, maxAge: 0 })
          // An admin signed in as someone hands nobody that person's sign-in.
          if ((session as { impersonatedBy?: string | null }).impersonatedBy) throw refused()
          if (!start || !sessionFitsStart(new Date(session.createdAt), start)) throw refused()
          const code = randomBytes(32).toString('base64url')
          const stored: Stored = { userId: session.userId, challenge: start.challenge, browserSessionId: session.id }
          await ctx.context.internalAdapter.createVerificationValue({
            identifier: identifierOf(code),
            value: JSON.stringify(stored),
            expiresAt: new Date(Date.now() + CODE_TTL_MS),
          })
          return ctx.json({ code })
        },
      ),
      appSignInRedeem: createAuthEndpoint(
        APP_SIGN_IN_REDEEM_PATH,
        { method: 'POST', body: z.object({ code: token43, verifier: token43 }), use: [formCsrfMiddleware] },
        async ctx => {
          // Taken before the verifier is checked: a wrong verifier spends the code, so it cannot be guessed at.
          const stored = await takeCode(ctx.body.code)
          if (!stored || !verifierFits(ctx.body.verifier, stored.challenge)) throw refused()
          const browserToken = await browserSessionToken(stored.browserSessionId, stored.userId)
          if (!browserToken) throw refused()
          await ctx.context.internalAdapter.deleteSession(browserToken)
          const user = await ctx.context.internalAdapter.findUserById(stored.userId)
          if (!user) throw refused()
          // The web view's own older session (another account, or a stale one) goes with the new sign-in.
          const old = await ctx.getSignedCookie(ctx.context.authCookies.sessionToken.name, ctx.context.secret)
          if (old) await ctx.context.internalAdapter.deleteSession(old).catch(() => {})
          const session = await ctx.context.internalAdapter.createSession(user.id)
          if (!session) throw refused()
          await setSessionCookie(ctx, { session, user })
          return ctx.json({ ok: true })
        },
      ),
    },
    // Codes and challenges are 32 random bytes; this only keeps the endpoints from being hammered (per address).
    rateLimit: [
      { pathMatcher: path => path === APP_SIGN_IN_START_PATH, window: 60, max: 30 },
      { pathMatcher: path => path === APP_SIGN_IN_CODE_PATH, window: 60, max: 30 },
      { pathMatcher: path => path === APP_SIGN_IN_REDEEM_PATH, window: 60, max: 30 },
    ],
  }) satisfies BetterAuthPlugin