diff --git a/e2e/whatsapp-auth.spec.js b/e2e/whatsapp-auth.spec.js index 6668a92..41c5acc 100644 --- a/e2e/whatsapp-auth.spec.js +++ b/e2e/whatsapp-auth.spec.js @@ -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(); @@ -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(); + }); }); diff --git a/lib/handlers/auth.js b/lib/handlers/auth.js index dda5564..9155604 100644 --- a/lib/handlers/auth.js +++ b/lib/handlers/auth.js @@ -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, @@ -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, diff --git a/lib/handlers/pages.js b/lib/handlers/pages.js index 5c9978b..73837cf 100644 --- a/lib/handlers/pages.js +++ b/lib/handlers/pages.js @@ -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() diff --git a/lib/services/whatsapp-auth.js b/lib/services/whatsapp-auth.js index 4a344e3..bdb70af 100644 --- a/lib/services/whatsapp-auth.js +++ b/lib/services/whatsapp-auth.js @@ -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'; @@ -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) diff --git a/lib/views/pages.js b/lib/views/pages.js index 24c0d6a..144cd0b 100644 --- a/lib/views/pages.js +++ b/lib/views/pages.js @@ -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.' @@ -471,7 +474,7 @@ function devPersonaPicker() { `; } -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`I confirm I am 21 or older and agree to the Terms and Community Guidelines.`; let tgMethod; @@ -517,8 +520,9 @@ export function renderSignin({ next = '/me', error = '', oidc = false, devLogin
-
-