---
title: "Phone OTP sign-in"
description: "Passwordless phone login on Layer1 — Telegram Gateway first, WhatsApp Cloud AUTHENTICATION copy-code as fallback, virtual-email for phone-only accounts"
locale: "en"
---
# Phone OTP sign-in

> **Info**
> Use **Founder** / **Developer** tabs in the docs sidebar to filter this page. This is **phone possession**, not [Sign in with Telegram](/docs/features/authentication.md) and not [Ring Mailer](/docs/features/ring-mailer.md) email codes.

  The login field accepts **email or phone**. A phone starts `requestPhoneLoginCode`, stores a challenge, then `signIn('phone-otp')`. Delivery prefers **Telegram Gateway**. WhatsApp Cloud sends an **AUTHENTICATION** copy-code template only when Gateway is unset or cannot deliver, and only if the member did not opt out.

## Delivery comparison

| Situation | What the member gets | What you configure |
|-----------|----------------------|--------------------|
| Gateway token set and Telegram can deliver | Code inside Telegram | `TELEGRAM_GATEWAY_TOKEN` |
| Gateway fails (`fallbackNeeded`) and WhatsApp is configured, opt-out off | One WhatsApp AUTH template | WhatsApp Cloud trio below |
| Gateway not configured, WhatsApp is | WhatsApp only | Same WhatsApp trio |
| Member checked **Do not send codes via WhatsApp** | Gateway only, or a clear error | Client flag + checkbox |
| Neither rail | Error. Classical SMS is **not** wired | — |

| Previous / myth | Ring equivalent |
|-----------------|-----------------|
| SMS from a US long code as the WhatsApp rail | WhatsApp is Meta Cloud API. A carrier number can *become* the business sender; it does not replace the Graph send path |
| Free-form WhatsApp text (“your code is …”) | AUTHENTICATION template with copy-code button. Session text hits Meta error **131047** |
| Second login form | Same `EmailLoginForm` — `@` means email OTP, otherwise phone |
| Show `{digits}@your-domain` as the member’s email | Virtual mailbox for Auth.js uniqueness only. Profile offers **Link Email** |

### For founders

## Why phone login matters

Members in markets where Telegram is the default messenger can sign in without an inbox. If that number has no Telegram, WhatsApp is the second rail — one message, not both. Opt-out is a checkbox on the phone step, remembered in the browser.

A brand-new phone creates an account. The address stored for Auth.js is internal. The profile never presents it as “your email.” The member adds a real mailbox later with the Link Email dialog.

## Typical scenarios

  
  
  

  WhatsApp sends nothing until Meta marks the AUTHENTICATION copy-code template **Approved**. Name and language in env must match WhatsApp Manager exactly (`uk` is not `uk_UA`).

  `NEXT_PUBLIC_WHATSAPP_OTP_ENABLED=true` is inlined when the image is built. Setting it only on a running pod does not show the opt-out checkbox. Server send still requires the Cloud token, phone number ID, and template name.

### For developers

## Request and verify

```mermaid
sequenceDiagram
  participant UI as EmailLoginForm
  participant Act as requestPhoneLoginCode
  participant Del as sendPhoneOtp
  participant TG as TelegramGateway
  participant WA as WhatsAppCloud
  participant DB as phone_login_tokens
  UI->>Act: phone plus optional whatsappOptOut
  Act->>Del: sendPhoneOtp
  alt Gateway configured
    Del->>TG: checkSendAbility then send
    alt delivered
      Del-->>Act: channel telegram_gateway
    else fallbackNeeded and WhatsApp allowed
      Del->>WA: AUTH copy-code once
      Del-->>Act: channel whatsapp plus rawCode
    end
  else WhatsApp only
    Del->>WA: AUTH copy-code
    Del-->>Act: channel whatsapp plus rawCode
  end
  Act->>DB: insert challenge hash rawCode when WhatsApp
  UI->>UI: signIn phone-otp
```

| Piece | Path |
|-------|------|
| Login UI | `features/auth/components/email-login-form.tsx` |
| Client flag + opt-out storage | `features/auth/lib/phone-login-client.ts` — key `ring.phoneOtp.whatsappOptOut` |
| Request action | `app/_actions/auth-phone-actions.ts` — `requestPhoneLoginCode` |
| Profile verify | `app/_actions/phone-otp.ts` — `startPhoneOtp` / `confirmPhoneOtp`; panel `features/auth/components/phone-otp-panel.tsx` |
| Rail selector | `features/auth/services/phone-otp-delivery.ts` |
| Gateway client | `features/auth/services/telegram-gateway-otp.ts` |
| WhatsApp client | `features/auth/services/whatsapp-cloud-otp.ts` |
| Challenge store | `features/auth/services/phone-login-tokens.ts` |
| Auth.js | `auth.ts` Credentials id `phone-otp` |
| E.164 | `lib/phone/e164.ts` — `normalizeToE164` |
| Virtual mailbox | `lib/auth/virtual-email.ts` — digits `@` contact-email host, or `auth.virtualEmailDomain` |
| Code helpers | `lib/auth/email-tokens.ts` — `generateOTP`, `hmacOTP`, `verifyOTPTiming` |
| Schema | `data/migrations/047_phone_login_tokens.sql`, `049_phone_login_tokens_code_hash.sql` |

### Verify rules

| Rail | How the code is checked | Stored secret |
|------|-------------------------|---------------|
| `telegram_gateway` | `checkVerificationStatus` must return `code_valid` | `request_id` only |
| `whatsapp` | `hmacOTP(code, E.164)` compared with `verifyOTPTiming` | `code_hash` only. Raw code is never inserted |

Challenge TTL is **3 minutes**. Request cap is **5 / 15 minutes** per phone. Verify cap is **5** attempts. WhatsApp bumps attempts inside `verifyPhoneOtpCode`; `auth.ts` does not bump again for that channel. A WhatsApp send without `rawCode` is refused before insert.

Gateway-generated codes stay on Telegram’s API. Do not hash them into `code_hash`.

### WhatsApp send contract

`POST https://graph.facebook.com/{WHATSAPP_GRAPH_API_VERSION}/{WHATSAPP_CLOUD_PHONE_NUMBER_ID}/messages`

Template category AUTHENTICATION, button type copy code. The same 6-digit code is the body parameter and the URL button parameter (`sub_type: url`, `index: "0"`). Recipient `to` is E.164 digits **without** `+`. Default Graph version in code is `v21.0` when `WHATSAPP_GRAPH_API_VERSION` is unset. Default template language in code is `en_US` when `WHATSAPP_AUTH_TEMPLATE_LANG` is unset — set the env to the approved locale.

`request_id` prefers the Cloud message id (`wamid.…`, column `VARCHAR(255)`).

## Manual path

### Prerequisites

`AUTH_SECRET` (min 16 characters) or `OTP_HMAC_SECRET`. PostgreSQL with migrations `047` and `049` applied. Phone login does not use SMTP.

### Enable Telegram Gateway

Set `TELEGRAM_GATEWAY_TOKEN` (server only). Optional: `TELEGRAM_GATEWAY_SENDER_USERNAME`. `TELEGRAM_GATEWAY_CALLBACK_URL` is read if set; there is **no** `/api/auth/phone-otp/callback` route in this build — verify does not depend on it.

### Enable WhatsApp fallback

Create an AUTHENTICATION copy-code template in WhatsApp Manager (security recommendation on, expiration **3** minutes). After status **Approved**, set:

`WHATSAPP_CLOUD_TOKEN`, `WHATSAPP_CLOUD_PHONE_NUMBER_ID` (Cloud phone number ID, not the display number), `WHATSAPP_AUTH_TEMPLATE_NAME`, `WHATSAPP_AUTH_TEMPLATE_LANG`.

Bake `NEXT_PUBLIC_WHATSAPP_OTP_ENABLED=true` at **image build** so the opt-out checkbox renders.

### Smoke

With only Gateway: banner says Telegram. With Gateway unable to deliver and WhatsApp configured: one WhatsApp message, banner says WhatsApp. With opt-out: WhatsApp is not selected. Profile **Send code** uses the same `sendPhoneOtp` façade.

{`TELEGRAM_GATEWAY_TOKEN=
# TELEGRAM_GATEWAY_SENDER_USERNAME=
# TELEGRAM_GATEWAY_CALLBACK_URL=

WHATSAPP_CLOUD_TOKEN=
WHATSAPP_CLOUD_PHONE_NUMBER_ID=
WHATSAPP_AUTH_TEMPLATE_NAME=
WHATSAPP_AUTH_TEMPLATE_LANG=uk
# WHATSAPP_GRAPH_API_VERSION=v21.0
# Build-time only:
# NEXT_PUBLIC_WHATSAPP_OTP_ENABLED=true

# OTP_HMAC_SECRET=   # or AUTH_SECRET already set for Auth.js
`}

  `rawCode` exists only between WhatsApp send and `insertPhoneLoginToken`. Logs must not include the Graph body or the code.

## Frequently asked questions

### Impact

#### Does a successful Telegram send also text WhatsApp?

No. One request, one rail. WhatsApp runs only after Gateway is missing or returns `fallbackNeeded`, and only when the member has not opted out.

#### Will the profile show `380…@our-domain`?

No. That mailbox satisfies `users.email` uniqueness. Link Email replaces it with a real address. Ring Mailer must not send login mail to a virtual address.

### Migration

#### We only had email OTP

Leave phone env unset. The unified field still routes addresses that contain `@` to Ring Mailer.

#### Our `phone_login_tokens.request_id` is `VARCHAR(128)`

Apply `049_phone_login_tokens_code_hash.sql` before WhatsApp. Cloud message ids can exceed 128 characters. The migration also adds nullable `code_hash`.

### Ops

#### Graph error 132001 or 132000

**132001** — template name or language does not match an approved template. **132000** — parameter count does not match the template (body and button both need the code).

#### Graph error 131026

The number cannot receive WhatsApp. The send is treated as undeliverable. Do not retry in a loop.

#### Opt-out checkbox missing in production

`NEXT_PUBLIC_WHATSAPP_OTP_ENABLED` was not present at **build**. Rebuild the image. Runtime Secret alone does not rewrite the client bundle.

## Related documentation

  
- [features/authentication](/docs/features/authentication.md) — Prerequisite: Auth.js provider list, vitals gate, and Telegram Login versus phone OTP.

  
- [features/ring-mailer](/docs/features/ring-mailer.md) — Same-workflow: email OTP when the identifier contains @.

  
- [architecture/authentication](/docs/architecture/authentication.md) — Deep-dive: auth.ts versus auth.config.ts and the Credentials authorize path.

  
- [examples/authentication](/docs/examples/authentication.md) — Next-step: signIn patterns for the other Credentials providers.

  
- [api/authentication](/docs/api/authentication.md) — See-also: session endpoints — phone login still ends in an Auth.js JWT.

  
- [deployment/environment](/docs/deployment/environment.md) — Depends-on: where AUTH_SECRET and SMTP live beside these phone vars.
