All files / src/features/authentication sign-in.server.ts

97.05% Statements 33/34
94.11% Branches 16/17
100% Functions 4/4
97.05% Lines 33/34

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                                                        1x                       1x                 48x       48x 1536x   48x                         49x 49x 1x 1x   48x 1x 1x     47x   47x 47x 47x       4x 4x         4x       43x 43x                               31x         31x 10x 10x     21x 21x 21x 20x   1x 1x       1x    
// Signing in with an emailed code: the logic behind the server functions in
// functions.ts, with its dependencies passed in so Workers tests can drive it
// (spec: openspec/changes/add-email-sign-in/specs/authentication/spec.md).
import type { AlertReason, FieldReason } from '#/lib/reasons'
import type { Locale } from '#/paraglide/runtime.js'
import type { Auth } from '#/server/auth/auth'
import type { LimitRule } from '#/server/platform/limits.server'
import { EmailError, type SendEmail } from '#/server/email/email'
import type { Logger } from '#/server/log/log'
import { signInCodeEmail } from './sign-in-email'
import type { UserRepository } from './user.repository.server'
 
export interface SignInDeps {
  auth: Auth
  sendEmail: SendEmail
  log: Logger
  /** Counts a request against a key; see platform/limits.server.ts. */
  consumeLimit: (key: string, rule: LimitRule) => Promise<{ allowed: boolean }>
  clientIp: string
  /** The language the request resolved to: for new accounts and their email. */
  requestLocale: Locale
  /** The app's origin, for the logo in the email. */
  appUrl: string
  users: UserRepository
  now: () => Date
}
 
/** Each code request sends an email; Resend's free plan allows 100 a day. */
export const CODE_REQUEST_LIMITS = {
  perIp: { windowSeconds: 60, max: 3 },
  perEmail: { windowSeconds: 60 * 60, max: 5 },
} as const satisfies Record<string, LimitRule>
 
export type RequestCodeResult =
  { ok: true } | { ok: false; reason: AlertReason }
 
export type VerifyCodeResult =
  | { ok: true; locale: Locale }
  | { ok: false; reason: FieldReason | AlertReason }
 
const EMAIL_REASONS = {
  quota: 'email_quota',
  rate_limited: 'email_busy',
  rejected: 'email_failed',
  unavailable: 'email_failed',
} as const satisfies Record<EmailError['failure'], AlertReason>
 
/** A key without the address in it: the table keeps no email addresses. */
async function emailKey(email: string): Promise<string> {
  const digest = await crypto.subtle.digest(
    'SHA-256',
    new TextEncoder().encode(email),
  )
  const hex = [...new Uint8Array(digest)]
    .map((b) => b.toString(16).padStart(2, '0'))
    .join('')
  return `otp-email:${hex}`
}
 
/**
 * `email` is already validated and normalised (schemas.ts). `chosenLocale`
 * is the language the user chose on the sign-in page in this tab, if any:
 * the email is in it, not in the account's stored language.
 */
export async function requestCode(
  deps: SignInDeps,
  email: string,
  chosenLocale?: Locale,
): Promise<RequestCodeResult> {
  const { perIp, perEmail } = CODE_REQUEST_LIMITS
  if (!(await deps.consumeLimit(`otp-ip:${deps.clientIp}`, perIp)).allowed) {
    deps.log.warn('authentication.limit_reached', { limit: 'ip' })
    return { ok: false, reason: 'limit_reached' }
  }
  if (!(await deps.consumeLimit(await emailKey(email), perEmail)).allowed) {
    deps.log.warn('authentication.limit_reached', { limit: 'email' })
    return { ok: false, reason: 'limit_reached' }
  }
 
  const code = await deps.auth.createSignInCode(email)
  const locale =
    chosenLocale ?? (await deps.auth.findLocale(email)) ?? deps.requestLocale
  try {
    await deps.sendEmail(
      signInCodeEmail({ to: email, code, locale, appUrl: deps.appUrl }),
    )
  } catch (error) {
    Eif (error instanceof EmailError) {
      deps.log.error(
        'authentication.code_email_failed',
        { failure: error.failure },
        error,
      )
      return { ok: false, reason: EMAIL_REASONS[error.failure] }
    }
    throw error
  }
  deps.log.info('authentication.code_requested', { locale })
  return { ok: true }
}
 
/**
 * Signs in, creating the account for a new address. A language the user
 * chose on the sign-in page (`chosenLocale`) becomes the account's language,
 * also for an existing account; without a choice the stored one stays
 * (spec: "Choosing the language before sign-in"). Returns the account's
 * language, which the caller stores in the language cookie.
 */
export async function verifyCode(
  deps: SignInDeps,
  email: string,
  code: string,
  chosenLocale?: Locale,
): Promise<VerifyCodeResult> {
  const result = await deps.auth.signInWithCode(
    email,
    code,
    chosenLocale ?? deps.requestLocale,
  )
  if (!result.ok) {
    deps.log.info('authentication.sign_in_refused', { reason: result.failure })
    return { ok: false, reason: result.failure }
  }
  // The user id is on the line through the log context.
  deps.log.info('authentication.signed_in')
  const { id, locale } = result.user
  if (chosenLocale === undefined || chosenLocale === locale) {
    return { ok: true, locale }
  }
  await deps.users.setLocale(id, chosenLocale, deps.now())
  deps.log.info('authentication.locale_changed', {
    locale: chosenLocale,
    source: 'sign_in',
  })
  return { ok: true, locale: chosenLocale }
}