Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 35 additions & 1 deletion e2e/whatsapp-auth.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,11 @@ test.describe('WhatsApp OTP Authentication E2E', () => {
await screenshot(page, testInfo, 'desktop-signin-whatsapp-tab');

// 2. Fill mobile number, confirm age, request OTP
// Use unique phone with 98 prefix and 3210 suffix so masking matches +91 98****3210 without cooldown collision
const middle = String(Math.floor(1000 + Math.random() * 9000));
const testPhone = `98${middle}3210`;
const phoneInput = page.locator('#wa-phone');
await phoneInput.fill('9876543210');
await phoneInput.fill(testPhone);
await page.locator('[data-wa-age]').check();
await page.locator('[data-wa-promo]').check();

Expand Down Expand Up @@ -92,4 +95,35 @@ test.describe('WhatsApp OTP Authentication E2E', () => {

await screenshot(page, testInfo, 'mobile-signin-whatsapp');
});

test('Native HTML form submission with JavaScript disabled: verifies explicit POST semantics and zero URL leakage', async ({ browser }, testInfo) => {
const context = await browser.newContext({ javaScriptEnabled: false });
const page = await context.newPage();
getWhatsAppProvider().clearSentMessages();

await page.goto('/signin');
const form = page.locator('[data-wa-phone-form]');
await expect(form).toHaveAttribute('method', 'POST');
await expect(form).toHaveAttribute('action', '/api/auth/whatsapp/otp');

const testPhone = `97${String(Math.floor(10000000 + Math.random() * 90000000))}`;
await page.locator('#wa-phone').fill(testPhone);
await page.locator('[data-wa-age]').check();

// Submit form natively
await page.locator('[data-wa-submit-phone]').click();
await page.waitForLoadState('networkidle');

// Invariant: Phone number MUST NOT be in current page URL
const currentUrl = page.url();
expect(currentUrl).not.toContain(testPhone);
expect(currentUrl).not.toContain('phone=');
expect(currentUrl).not.toContain('ageConfirmed=');
expect(currentUrl).toMatch(/\/signin\?step=otp/);

// Verify OTP card is shown
await expect(page.locator('[data-wa-otp-card]')).toBeVisible();

await context.close();
});
});
135 changes: 119 additions & 16 deletions lib/handlers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -410,15 +410,70 @@ const CommunicationPreferencesPatchBody = z.object({
/** POST /api/auth/whatsapp/otp — Request WhatsApp OTP. */
export async function requestWhatsAppOtpHandler({ req, res, ip }) {
await rateLimit(`wa_otp_ip:${hashIp(ip)}`, 10, 300);
const body = parse(WhatsAppOtpRequestBody, await readJson(req));

const ct = req.headers['content-type'] || '';
const isFormUrlEncoded = ct.includes('application/x-www-form-urlencoded');
const isHtmlAccept = (req.headers['accept'] || '').includes('text/html') && !ct.includes('application/json');

let rawBody;
let nextUrl = '/me';
if (isFormUrlEncoded) {
const form = await readForm(req);
nextUrl = safeNext(form.next);
const promoOptIn = form.promotionalOptIn === 'on' || form.promotionalOptIn === 'true' || form.promotionalOptIn === true;
rawBody = {
phone: form.phone ? String(form.phone).trim() : '',
promotionalOptIn: promoOptIn
};
if (form.ageConfirmed !== 'on' && form.ageConfirmed !== 'true' && form.ageConfirmed !== true) {
if (isHtmlAccept) {
return redirect(res, `/signin?error=age&next=${encodeURIComponent(nextUrl)}`);
}
throw new HttpError(400, 'age_required', 'Please confirm you are 21 or older');
}
} else {
rawBody = await readJson(req);
}

let body;
try {
body = parse(WhatsAppOtpRequestBody, rawBody);
} catch (err) {
if (isHtmlAccept) {
return redirect(res, `/signin?error=invalid_phone&next=${encodeURIComponent(nextUrl)}`);
}
throw err;
}

const userAgent = req.headers['user-agent'] || null;

const result = await requestWhatsAppOtp({
phone: body.phone,
ip,
userAgent,
promotionalOptIn: body.promotionalOptIn
});
let result;
try {
result = await requestWhatsAppOtp({
phone: body.phone,
ip,
userAgent,
promotionalOptIn: body.promotionalOptIn
});
} catch (err) {
if (isHtmlAccept) {
const errCode = err.code === 'whatsapp_unavailable' ? 'whatsapp_unavailable' : (err.code || 'failed');
return redirect(res, `/signin?error=${encodeURIComponent(errCode)}&next=${encodeURIComponent(nextUrl)}`);
}
throw err;
}

if (isHtmlAccept) {
const secure = Boolean(process.env.VERCEL) || req.headers['x-forwarded-proto'] === 'https';
appendHeader(res, 'Set-Cookie', serializeCookie('sm_wa_step', JSON.stringify({
challengeId: result.challengeId,
phoneMasked: result.phoneMasked,
phone: body.phone,
next: nextUrl,
promoOptIn: body.promotionalOptIn
}), { maxAge: 600, secure, path: '/' }));
return redirect(res, `/signin?step=otp&next=${encodeURIComponent(nextUrl)}`);
}

sendJson(res, 200, {
ok: true,
Expand All @@ -433,19 +488,67 @@ export async function requestWhatsAppOtpHandler({ req, res, ip }) {
/** POST /api/auth/whatsapp/verify — Verify OTP & start session. */
export async function verifyWhatsAppOtpHandler({ req, res, ip }) {
await rateLimit(`wa_verify_ip:${hashIp(ip)}`, 25, 300);
const body = parse(WhatsAppOtpVerifyBody, await readJson(req));

const ct = req.headers['content-type'] || '';
const isFormUrlEncoded = ct.includes('application/x-www-form-urlencoded');
const isHtmlAccept = (req.headers['accept'] || '').includes('text/html') && !ct.includes('application/json');

let rawBody;
let nextUrl = '/me';
if (isFormUrlEncoded) {
const form = await readForm(req);
nextUrl = safeNext(form.next);
const cookies = parseCookies(req.headers.cookie || '');
let cookieStep = null;
try { cookieStep = JSON.parse(cookies['sm_wa_step'] || '{}'); } catch {}

rawBody = {
challengeId: form.challengeId || cookieStep?.challengeId,
phone: form.phone || cookieStep?.phone,
code: form.otp || form.code,
promotionalOptIn: form.promotionalOptIn === 'on' || form.promotionalOptIn === 'true' || Boolean(cookieStep?.promoOptIn)
};
} else {
rawBody = await readJson(req);
}

let body;
try {
body = parse(WhatsAppOtpVerifyBody, rawBody);
} catch (err) {
if (isHtmlAccept) {
return redirect(res, `/signin?step=otp&error=invalid_otp&next=${encodeURIComponent(nextUrl)}`);
}
throw err;
}

const userAgent = req.headers['user-agent'] || null;

const auth = await verifyWhatsAppOtpAndResolveUser({
challengeId: body.challengeId,
phone: body.phone,
code: body.code,
ip,
userAgent,
promotionalOptIn: body.promotionalOptIn
});
let auth;
try {
auth = await verifyWhatsAppOtpAndResolveUser({
challengeId: body.challengeId,
phone: body.phone,
code: body.code,
ip,
userAgent,
promotionalOptIn: body.promotionalOptIn
});
} catch (err) {
if (isHtmlAccept) {
return redirect(res, `/signin?step=otp&error=invalid_otp&next=${encodeURIComponent(nextUrl)}`);
}
throw err;
}

const { csrf } = await startSession(req, res, auth.user);

if (isHtmlAccept) {
const secure = Boolean(process.env.VERCEL) || req.headers['x-forwarded-proto'] === 'https';
appendHeader(res, 'Set-Cookie', serializeCookie('sm_wa_step', '', { maxAge: 0, secure, path: '/' }));
return redirect(res, nextUrl);
}

sendJson(res, 200, {
ok: true,
csrf,
Expand Down
28 changes: 28 additions & 0 deletions lib/handlers/pages.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,9 +128,37 @@ export async function memberPage({ req, res, pathname, query }) {
const html = P.renderMe();
return sendHtml(res, 200, html, { cache: 'no-store' });
}

// --- Defense-in-depth URL privacy: detect and remove sensitive query parameters ---
const SENSITIVE_QUERY_PARAMS = ['phone', 'ageConfirmed', 'promotionalOptIn', 'otp', 'code', 'token', 'secret'];
const hasSensitiveParam = SENSITIVE_QUERY_PARAMS.some((k) => query.has(k));

if (hasSensitiveParam) {
const safeParams = new URLSearchParams();
const nextVal = query.get('next');
if (nextVal && /^\/(?![\/\\])[\w\-./?=&#%]*$/.test(nextVal)) {
safeParams.set('next', nextVal);
}
const errorVal = query.get('error');
if (errorVal && /^[a-z0-9_-]{1,64}$/i.test(errorVal)) {
safeParams.set('error', errorVal);
}
const stepVal = query.get('step');
if (stepVal === 'otp') {
safeParams.set('step', 'otp');
}
const cleanUrl = safeParams.size > 0 ? `/signin?${safeParams.toString()}` : '/signin';
res.setHeader('Cache-Control', 'no-store');
res.setHeader('Referrer-Policy', 'no-referrer');
return redirect(res, cleanUrl);
}

res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');

const html = P.renderSignin({
next: /^\/(?![\/\\])[\w\-./?=&#%]*$/.test(query.get('next') || '') ? query.get('next') : '/me',
error: query.get('error') || '',
step: query.get('step') === 'otp' ? 'otp' : 'phone',
oidc: oidcConfigured(),
devLogin: devLoginEnabled(),
previewReviewer: previewReviewerEnabled()
Expand Down
15 changes: 14 additions & 1 deletion lib/services/whatsapp-auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { HttpError } from '../http.js';
import { audit } from '../audit.js';
import { normalizePhoneNumber, maskPhone } from './phone.js';
import { createOtpChallenge, verifyOtpChallenge } from './otp.js';
import { getWhatsAppProvider } from './whatsapp-provider.js';
import { getWhatsAppConfig, getWhatsAppProvider } from './whatsapp-provider.js';
import { recordConsent } from './communication-consent.js';
import { logger } from '../logger.js';

Expand All @@ -20,6 +20,19 @@ export async function requestWhatsAppOtp({
currentUserId = null,
promotionalOptIn = false
}) {
const cfg = getWhatsAppConfig();
const isDeployedOrProd = Boolean(process.env.VERCEL) ||
process.env.NODE_ENV === 'production' ||
process.env.VERCEL_ENV === 'production';
const isMockAllowed = !isDeployedOrProd && (process.env.NODE_ENV === 'test' || Boolean(process.env.TEST_DATABASE_URL) || process.env.DEV_LOGIN === 'true');
if (!cfg.isLive && !isMockAllowed) {
throw new HttpError(
503,
'whatsapp_unavailable',
'WhatsApp sign-in is currently unavailable. Please sign in with Telegram or try again later.'
);
}

const phone = normalizePhoneNumber(rawPhone);

// Create OTP challenge in DB (enforces cooldown & rate limits)
Expand Down
17 changes: 11 additions & 6 deletions lib/views/pages.js
Original file line number Diff line number Diff line change
Expand Up @@ -452,8 +452,11 @@ export function renderContact() {

const SIGNIN_ERRORS = {
age: 'Please confirm you are 21 or older to continue.',
invalid_phone: 'Please enter a valid 10-digit Indian mobile number (starts with 6-9).',
invalid_otp: 'The verification code you entered is invalid or has expired.',
whatsapp_unavailable: 'WhatsApp sign-in is currently unavailable on this deployment. Please sign in with Telegram or try again later.',
expired: 'That sign-in attempt expired. Please try again.',
failed: 'Telegram sign-in could not be completed. Please try again.',
failed: 'Sign-in could not be completed. Please try again.',
not_configured: 'Telegram sign-in is not configured yet on this deployment.',
invalid_telegram_auth: 'Telegram sign-in could not be verified. Please try again.',
replay: 'This sign-in link was already used. Please try again.'
Expand All @@ -471,7 +474,7 @@ function devPersonaPicker() {
</section>`;
}

export function renderSignin({ next = '/me', error = '', oidc = false, devLogin = false, previewReviewer = false } = {}) {
export function renderSignin({ next = '/me', error = '', step = 'phone', oidc = false, devLogin = false, previewReviewer = false } = {}) {
const bot = botUsername();
const ageLabel = html`<span>I confirm I am 21 or older and agree to the <a href="/terms">Terms</a> and <a href="/community-guidelines">Community Guidelines</a>.</span>`;
let tgMethod;
Expand Down Expand Up @@ -517,8 +520,9 @@ export function renderSignin({ next = '/me', error = '', oidc = false, devLogin

<!-- WhatsApp Panel -->
<div class="auth-panel" data-auth-panel="whatsapp">
<div data-wa-step="phone">
<form class="wa-auth-card" data-wa-phone-form>
<div data-wa-step="phone" ${step === 'otp' ? 'hidden' : ''}>
<form class="wa-auth-card" method="POST" action="/api/auth/whatsapp/otp" data-wa-phone-form>
<input type="hidden" name="next" value="${next}">
<div class="field">
<label for="wa-phone">Enter your WhatsApp mobile number</label>
<div class="phone-field-group">
Expand All @@ -544,8 +548,9 @@ export function renderSignin({ next = '/me', error = '', oidc = false, devLogin
</form>
</div>

<div data-wa-step="otp" class="otp-box" data-wa-otp-card hidden>
<form id="otp-form" method="POST" data-wa-verify-form>
<div data-wa-step="otp" class="otp-box" data-wa-otp-card ${step === 'otp' ? '' : 'hidden'}>
<form id="otp-form" method="POST" action="/api/auth/whatsapp/verify" data-wa-verify-form>
<input type="hidden" name="next" value="${next}">
<div class="field">
<label for="otp-input">Verification code</label>
<p id="otp-format-hint" class="otp-hint">
Expand Down
20 changes: 20 additions & 0 deletions public/js/site.js
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,26 @@
var waPhoneForm = $('[data-wa-phone-form]');
var waOtpCard = $('[data-wa-otp-card]');
if (waPhoneForm && waOtpCard) {
// Defense-in-depth: scrub any legacy sensitive query parameters from browser address bar
try {
if (window.history && window.history.replaceState && location.search) {
var currentParams = new URLSearchParams(location.search);
var sensitiveKeys = ['phone', 'ageConfirmed', 'promotionalOptIn', 'otp', 'code'];
var hasSensitive = false;
sensitiveKeys.forEach(function (k) {
if (currentParams.has(k)) {
currentParams.delete(k);
hasSensitive = true;
}
});
if (hasSensitive) {
var cleanSearch = currentParams.toString();
var cleanUrl = location.pathname + (cleanSearch ? '?' + cleanSearch : '') + location.hash;
window.history.replaceState(null, document.title, cleanUrl);
}
}
} catch (e) { /* ignore */ }

var signinMsg = $('[data-signin-msg]');
var currentChallengeId = null;
var currentPhone = null;
Expand Down
Loading
Loading