diff --git a/e2e/auth-audit.spec.js b/e2e/auth-audit.spec.js new file mode 100644 index 0000000..83dfcb1 --- /dev/null +++ b/e2e/auth-audit.spec.js @@ -0,0 +1,86 @@ +// e2e/auth-audit.spec.js - Playwright E2E for Telegram multi-account & WhatsApp production signin audit. +import { test, expect } from '@playwright/test'; +import { expectAccessible, expectNoHorizontalOverflow, screenshot } from './helpers.js'; +import fs from 'node:fs'; +import path from 'node:path'; + +const ARTIFACT_DIR = process.env.ARTIFACT_DIR || path.join(process.cwd(), 'test-results', 'evidence'); +fs.mkdirSync(ARTIFACT_DIR, { recursive: true }); + +test.describe('NIGHTLIFEZ Sign-in Multi-Account & Production Verification', () => { + test('Clean browser session: consent checkboxes unchecked, no premature OTP step, Telegram switch guidance', async ({ browser }, testInfo) => { + // 1. Fresh, completely clean browser context with no stored cookies + const context = await browser.newContext(); + const page = await context.newPage(); + await page.setViewportSize({ width: 1280, height: 800 }); + + await page.goto('/signin'); + await expect(page.getByRole('heading', { level: 1 })).toContainText('Continue to NIGHTLIFEZ'); + + // 2. Invariant: On clean session, OTP verification panel is strictly hidden + const otpCard = page.locator('[data-wa-otp-card]'); + if (await otpCard.count() > 0) { + await expect(otpCard).toBeHidden(); + } + + // Invariant: Dummy phone +91 98****1234 is NEVER displayed + const bodyText = await page.textContent('body'); + expect(bodyText).not.toContain('+91 98****1234'); + + // 3. Switch to Telegram tab + const tgTab = page.locator('[data-auth-tab="telegram"]'); + await tgTab.click(); + await expect(page.locator('[data-auth-panel="telegram"]')).toBeVisible(); + + // 4. Invariant: Age confirmation is unchecked for fresh visitor + const ageCheckbox = page.locator('[data-age-confirm]'); + if (await ageCheckbox.count() > 0) { + expect(await ageCheckbox.isChecked()).toBe(false); + } + + // 5. Invariant: Telegram Switch Account guidance is visible and helpful + const switchTip = page.locator('[data-tg-switch-tip]'); + await expect(switchTip).toBeVisible(); + await expect(switchTip).toContainText('Signing in with a different Telegram account?'); + await expect(switchTip).toContainText('Incognito or Private window'); + await expect(switchTip).toContainText('web.telegram.org'); + + await expectAccessible(page, { exclude: ['iframe'] }); + await expectNoHorizontalOverflow(page); + + await page.screenshot({ path: path.join(ARTIFACT_DIR, 'clean-session-telegram-signin.png'), fullPage: true }); + await context.close(); + }); + + test('Direct navigation to /signin?step=otp without active challenge safely defaults to phone step', async ({ browser }, testInfo) => { + const context = await browser.newContext(); + const page = await context.newPage(); + + await page.goto('/signin?step=otp'); + // OTP card must be hidden because no active challenge was issued + const otpCard = page.locator('[data-wa-otp-card]'); + if (await otpCard.count() > 0) { + await expect(otpCard).toBeHidden(); + } + + const bodyText = await page.textContent('body'); + expect(bodyText).not.toContain('+91 98****1234'); + + await context.close(); + }); + + test('Mobile (375px): Telegram switch tip and auth layout are fully responsive', async ({ browser }, testInfo) => { + const context = await browser.newContext(); + const page = await context.newPage(); + await page.setViewportSize({ width: 375, height: 667 }); + + await page.goto('/signin'); + await page.locator('[data-auth-tab="telegram"]').click(); + + await expect(page.locator('[data-tg-switch-tip]')).toBeVisible(); + await expectNoHorizontalOverflow(page); + + await page.screenshot({ path: path.join(ARTIFACT_DIR, 'mobile-375px-telegram-switch-tip.png'), fullPage: true }); + await context.close(); + }); +}); diff --git a/e2e/env.js b/e2e/env.js index c182e8a..aeb7455 100644 --- a/e2e/env.js +++ b/e2e/env.js @@ -22,6 +22,7 @@ export const serverEnv = { PORT: String(E2E_PORT), DATABASE_URL: E2E_DATABASE_URL, DEV_LOGIN: 'true', + TELEGRAM_BOT_USERNAME: 'Nightlifez_bot', SESSION_SECRET: 'e2e-only-session-secret-0123456789abcdef', PUBLIC_SITE_URL: E2E_BASE, IS_PREVIEW: 'true', diff --git a/lib/handlers/auth.js b/lib/handlers/auth.js index 9155604..1a91e4c 100644 --- a/lib/handlers/auth.js +++ b/lib/handlers/auth.js @@ -470,7 +470,8 @@ export async function requestWhatsAppOtpHandler({ req, res, ip }) { phoneMasked: result.phoneMasked, phone: body.phone, next: nextUrl, - promoOptIn: body.promotionalOptIn + promoOptIn: body.promotionalOptIn, + createdAt: Date.now() }), { maxAge: 600, secure, path: '/' })); return redirect(res, `/signin?step=otp&next=${encodeURIComponent(nextUrl)}`); } diff --git a/lib/handlers/pages.js b/lib/handlers/pages.js index 73837cf..5f13576 100644 --- a/lib/handlers/pages.js +++ b/lib/handlers/pages.js @@ -1,9 +1,10 @@ // lib/handlers/pages.js - Public, CDN-cacheable server-rendered pages + sitemap/robots. -import { sendHtml, sendText, sendJson, redirect, HttpError, PUBLIC_CACHE } from '../http.js'; +import { sendHtml, sendText, sendJson, redirect, HttpError, PUBLIC_CACHE, parseCookies, serializeCookie, appendHeader } from '../http.js'; import { getSessionUser } from '../session.js'; import { siteUrl, isProductionRuntime } from '../config.js'; import { devLoginEnabled, previewReviewerEnabled } from '../dev-personas.js'; import { oidcConfigured } from '../telegram/auth.js'; +import { isWhatsAppAvailable } from '../services/whatsapp-auth.js'; import { listPublicEvents, getPublicEventBySlug, listSitemapEvents, socialProof, listVisibleMedia, listTiers, CATEGORY_LABELS, CITIES @@ -129,6 +130,28 @@ export async function memberPage({ req, res, pathname, query }) { return sendHtml(res, 200, html, { cache: 'no-store' }); } + // --- Parse temporary challenge cookies & check stale state --- + const cookies = parseCookies(req.headers.cookie || ''); + let waStepCookie = null; + try { + if (cookies.sm_wa_step) { + waStepCookie = JSON.parse(cookies.sm_wa_step); + } + } catch { + waStepCookie = null; + } + + // Clear stale challenge cookies (>10 minutes) + const isStale = waStepCookie?.createdAt && (Date.now() - waStepCookie.createdAt > 10 * 60 * 1000); + if (isStale) { + const secure = Boolean(process.env.VERCEL) || req.headers['x-forwarded-proto'] === 'https'; + appendHeader(res, 'Set-Cookie', serializeCookie('sm_wa_step', '', { maxAge: 0, secure, path: '/' })); + waStepCookie = null; + } + + const whatsappAvailable = isWhatsAppAvailable(); + const hasActiveChallenge = Boolean(waStepCookie?.challengeId); + // --- 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)); @@ -143,8 +166,7 @@ export async function memberPage({ req, res, pathname, query }) { if (errorVal && /^[a-z0-9_-]{1,64}$/i.test(errorVal)) { safeParams.set('error', errorVal); } - const stepVal = query.get('step'); - if (stepVal === 'otp') { + if (query.get('step') === 'otp' && hasActiveChallenge && whatsappAvailable) { safeParams.set('step', 'otp'); } const cleanUrl = safeParams.size > 0 ? `/signin?${safeParams.toString()}` : '/signin'; @@ -155,10 +177,13 @@ export async function memberPage({ req, res, pathname, query }) { res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin'); + const isOtpStep = query.get('step') === 'otp' && hasActiveChallenge && whatsappAvailable; 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', + step: isOtpStep ? 'otp' : 'phone', + maskedPhone: isOtpStep ? waStepCookie?.phoneMasked : null, + whatsappAvailable, oidc: oidcConfigured(), devLogin: devLoginEnabled(), previewReviewer: previewReviewerEnabled() diff --git a/lib/services/whatsapp-auth.js b/lib/services/whatsapp-auth.js index bdb70af..4405e6f 100644 --- a/lib/services/whatsapp-auth.js +++ b/lib/services/whatsapp-auth.js @@ -9,6 +9,19 @@ import { getWhatsAppConfig, getWhatsAppProvider } from './whatsapp-provider.js'; import { recordConsent } from './communication-consent.js'; import { logger } from '../logger.js'; +/** + * Checks whether WhatsApp messaging is configured and operational on this deployment. + * Fails closed in production / Vercel if live credentials are not present. + */ +export function isWhatsAppAvailable() { + 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'); + return Boolean(cfg.isLive || isMockAllowed); +} + /** * Request an authentication OTP delivered over WhatsApp. */ @@ -20,12 +33,7 @@ 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) { + if (!isWhatsAppAvailable()) { throw new HttpError( 503, 'whatsapp_unavailable', diff --git a/lib/views/pages.js b/lib/views/pages.js index 144cd0b..68eafa6 100644 --- a/lib/views/pages.js +++ b/lib/views/pages.js @@ -474,7 +474,16 @@ function devPersonaPicker() { `; } -export function renderSignin({ next = '/me', error = '', step = 'phone', oidc = false, devLogin = false, previewReviewer = false } = {}) { +export function renderSignin({ + next = '/me', + error = '', + step = 'phone', + maskedPhone = null, + whatsappAvailable = false, + 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; @@ -514,12 +523,19 @@ export function renderSignin({ next = '/me', error = '', step = 'phone', oidc = ` : ''}
- - + +
-
+
+ ${!whatsappAvailable ? html` + ` : html`
-
+
`}
-