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 =
` : ''}
- Continue with WhatsApp
- Continue with Telegram
+ Continue with WhatsApp
+ Continue with Telegram
-
+
+ ${!whatsappAvailable ? html`
+
+
📱
+
WhatsApp sign-in is temporarily unavailable
+
WhatsApp OTP delivery is currently offline or unconfigured on this deployment. Please sign in with Telegram for instant, passwordless access to your digital passes, secret venues, and bookings.
+
Continue with Telegram
+
` : html`
+
`}
-
+
${tgMethod}
+
+
+
+ Telegram automatically detects the active Telegram session in this browser. To sign in with a different Telegram account:
+
+
+ Open an Incognito or Private window to log in with a different Telegram phone number.
+ Or sign out of Telegram Web at web.telegram.org .
+ ${bot ? html`Or open our bot @${bot} directly in the Telegram app on your phone and tap “Open NIGHTLIFEZ”. ` : ''}
+
+
${bot ? html`
Using Telegram on your phone? Open our bot and tap “Open NIGHTLIFEZ”.
` : ''}
diff --git a/public/css/site.css b/public/css/site.css
index fe5137f..839b93f 100644
--- a/public/css/site.css
+++ b/public/css/site.css
@@ -356,6 +356,24 @@ select:focus, input:focus, textarea:focus { outline: 2px solid var(--accent); ou
.country-code-pill { display: flex; align-items: center; justify-content: center; background: var(--surface-2); border: 1px solid var(--line-light); border-radius: var(--radius-sm); padding: 0 14px; font-weight: 600; font-size: .95rem; color: var(--ink); }
.phone-input { flex: 1; font-size: 1.05rem; }
+/* Ensure HTML hidden attribute is strictly respected regardless of author display properties */
+[hidden] { display: none !important; }
+.otp-box[hidden], .auth-panel[hidden], [data-wa-step][hidden] { display: none !important; }
+
+.wa-unavailable-card {
+ background: var(--surface);
+ border: 1px solid var(--line);
+ border-radius: var(--radius);
+ padding: 32px 24px;
+ text-align: center;
+ display: grid;
+ gap: 16px;
+ box-shadow: var(--shadow);
+}
+.wa-unavailable-icon { font-size: 2.2rem; margin: 0 auto 4px; }
+.wa-unavailable-title { font-size: 1.15rem; font-weight: 700; color: var(--ink); margin: 0; }
+.wa-unavailable-desc { font-size: .92rem; color: var(--ink-2); line-height: 1.5; margin: 0; max-width: 42ch; margin-inline: auto; }
+
.otp-box { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 24px; display: grid; gap: 16px; }
.otp-hint { font-size: .88rem; color: var(--muted); margin: 0 0 8px; line-height: 1.4; }
#otp-input {
@@ -396,6 +414,28 @@ select:focus, input:focus, textarea:focus { outline: 2px solid var(--accent); ou
.tg-widget { min-height: 48px; }
.tg-widget[aria-disabled="true"] { opacity: .45; pointer-events: none; }
+.tg-switch-tip {
+ margin-top: 18px;
+ padding: 16px 18px;
+ border-radius: var(--radius-sm);
+ background: rgba(0, 217, 255, 0.05);
+ border: 1px solid rgba(0, 217, 255, 0.25);
+ font-size: .88rem;
+ line-height: 1.5;
+ color: var(--ink-2);
+}
+.tg-switch-tip-header {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ color: var(--ink);
+ font-size: .92rem;
+ margin-bottom: 6px;
+}
+.tg-switch-desc { margin: 0 0 8px; font-size: .88rem; }
+.tg-switch-steps { margin: 0 0 0 18px; padding: 0; }
+.tg-switch-steps li { margin-bottom: 6px; }
+.tg-switch-steps a { color: var(--neon-cyan); text-decoration: underline; }
.signin-why { margin-top: 28px; padding: 20px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius-sm); }
.signin-why-title { font-size: 1.02rem; margin: 0 0 12px; color: var(--ink); }
.signin-why-list { list-style: none; padding: 0; margin: 0; display: grid; gap: 10px; font-size: .88rem; color: var(--ink-2); }
diff --git a/public/js/site.js b/public/js/site.js
index 43ed86d..bc0e34b 100644
--- a/public/js/site.js
+++ b/public/js/site.js
@@ -239,6 +239,14 @@
});
}
+ /* Shortcut to switch to Telegram tab from unavailable card */
+ $$('[data-switch-to-telegram]').forEach(function (btn) {
+ btn.addEventListener('click', function () {
+ var tgTab = $('[data-auth-tab="telegram"]');
+ if (tgTab) tgTab.click();
+ });
+ });
+
/* WhatsApp OTP Authentication on /signin */
var waPhoneForm = $('[data-wa-phone-form]');
var waOtpCard = $('[data-wa-otp-card]');
@@ -440,11 +448,26 @@
changePhoneBtn.addEventListener('click', function () {
stopSmsOtpListener();
if (countdownTimer) clearInterval(countdownTimer);
+ currentChallengeId = null;
+ currentPhone = null;
+ try {
+ var isHttps = location.protocol === 'https:';
+ document.cookie = 'sm_wa_step=; path=/; max-age=0; samesite=lax' + (isHttps ? '; secure' : '');
+ } catch (e) { /* ignore */ }
waOtpCard.hidden = true;
var phoneStep = $('[data-wa-step="phone"]');
if (phoneStep) phoneStep.hidden = false;
var phoneInput = $('#wa-phone');
- if (phoneInput) phoneInput.focus();
+ if (phoneInput) {
+ phoneInput.value = '';
+ phoneInput.focus();
+ }
+ var maskedEl = $('[data-wa-masked-phone]');
+ if (maskedEl) maskedEl.textContent = '';
+ var otpInput = $('#otp-input');
+ if (otpInput) otpInput.value = '';
+ signinMsg.className = 'form-msg';
+ signinMsg.textContent = '';
});
}
@@ -528,6 +551,16 @@
s.setAttribute('data-request-access', 'write');
s.setAttribute('data-auth-url', callbackUrl);
widget.appendChild(s);
+
+ try {
+ var obs = new MutationObserver(function () {
+ var ifr = widget.querySelector('iframe');
+ if (ifr && !ifr.getAttribute('title')) {
+ ifr.setAttribute('title', 'Log in with Telegram');
+ }
+ });
+ obs.observe(widget, { childList: true, subtree: true });
+ } catch (e) { /* ignore */ }
}
/* Local test personas (the server returns 404 unless persona sign-in is enabled on this machine). */
diff --git a/test/helpers.js b/test/helpers.js
index 5eb0b38..7cd68e9 100644
--- a/test/helpers.js
+++ b/test/helpers.js
@@ -5,7 +5,7 @@ export const BOT_TOKEN = '123456789:TEST_ONLY_token_abcdefghijklmnopqrstuvwxyz';
Object.assign(process.env, {
SKIP_DOTENV: 'true',
- DATABASE_URL: process.env.TEST_DATABASE_URL || 'postgres://postgres@localhost:54329/sm_test',
+ DATABASE_URL: process.env.TEST_DATABASE_URL || process.env.DATABASE_URL || 'postgres://localhost:5432/sm_test',
SESSION_SECRET: 'test-session-secret-0123456789-abcdefghij',
CRON_SECRET: 'test-cron-secret-0123456789',
TELEGRAM_BOT_TOKEN: BOT_TOKEN,
diff --git a/test/multi-account-telegram-and-whatsapp-audit.test.js b/test/multi-account-telegram-and-whatsapp-audit.test.js
new file mode 100644
index 0000000..9b22cc4
--- /dev/null
+++ b/test/multi-account-telegram-and-whatsapp-audit.test.js
@@ -0,0 +1,294 @@
+// test/multi-account-telegram-and-whatsapp-audit.test.js - Multi-Account Telegram Login + WhatsApp Production Login Audit Tests.
+import { test, before, after } from 'node:test';
+import assert from 'node:assert/strict';
+import crypto from 'node:crypto';
+import { resetDb, startServer, stopServer, Client, makeWidgetData, db, BOT_TOKEN } from './helpers.js';
+
+before(async () => {
+ await resetDb();
+ await startServer();
+});
+after(stopServer);
+
+function buildCallbackQuery(widgetData, state, next) {
+ const params = new URLSearchParams();
+ if (state !== undefined) params.set('state', state);
+ if (next !== undefined) params.set('next', next);
+ for (const [k, v] of Object.entries(widgetData)) {
+ params.set(k, String(v));
+ }
+ return params.toString();
+}
+
+/* ========================================================================== */
+/* OBJECTIVE A: Telegram Multi-Account Support & Isolation */
+/* ========================================================================== */
+
+test('Telegram multi-account: accepts authentication from any valid Telegram account', async () => {
+ // Test Account 1: User 70001 (Alice)
+ const client1 = new Client();
+ const state1 = crypto.randomBytes(16).toString('hex');
+ client1.cookies.sm_tg_state = state1;
+
+ const widgetAlice = makeWidgetData({ id: 70001, first_name: 'Alice', username: 'alice_telegram' });
+ const qs1 = buildCallbackQuery(widgetAlice, state1, '/me');
+ const res1 = await client1.get(`/auth/telegram/widget-callback?${qs1}`);
+
+ assert.equal(res1.status, 302);
+ assert.equal(res1.headers.get('location'), '/me');
+
+ const me1 = await client1.get('/api/me');
+ assert.equal(me1.status, 200);
+ assert.equal(me1.json.user.alias, 'Alice');
+
+ // Verify database record for Account 1
+ const u1 = await db.one('SELECT id, telegram_user_id, alias FROM users WHERE telegram_user_id = 70001');
+ assert.equal(u1.telegram_user_id, 70001);
+ assert.equal(u1.alias, 'Alice');
+
+ // Test Account 2: User 70002 (Bob)
+ const client2 = new Client();
+ const state2 = crypto.randomBytes(16).toString('hex');
+ client2.cookies.sm_tg_state = state2;
+
+ const widgetBob = makeWidgetData({ id: 70002, first_name: 'Bob', username: 'bob_telegram' });
+ const qs2 = buildCallbackQuery(widgetBob, state2, '/me');
+ const res2 = await client2.get(`/auth/telegram/widget-callback?${qs2}`);
+
+ assert.equal(res2.status, 302);
+ assert.equal(res2.headers.get('location'), '/me');
+
+ const me2 = await client2.get('/api/me');
+ assert.equal(me2.status, 200);
+ assert.equal(me2.json.user.alias, 'Bob');
+
+ // Verify database record for Account 2
+ const u2 = await db.one('SELECT id, telegram_user_id, alias FROM users WHERE telegram_user_id = 70002');
+ assert.equal(u2.telegram_user_id, 70002);
+ assert.equal(u2.alias, 'Bob');
+
+ // Verify accounts are distinct and isolated in database
+ assert.notEqual(u1.id, u2.id);
+ const count = await db.one('SELECT count(*)::int as c FROM users WHERE telegram_user_id IN (70001, 70002)');
+ assert.equal(count.c, 2);
+});
+
+test('Telegram identity: identity is bound strictly to Telegram verified numeric ID, not browser username', async () => {
+ const client = new Client();
+ const state = crypto.randomBytes(16).toString('hex');
+ client.cookies.sm_tg_state = state;
+
+ // Sign in with verified numeric ID 70003, username 'charlie_smith'
+ const widget1 = makeWidgetData({ id: 70003, first_name: 'Charlie', username: 'charlie_smith' });
+ await client.get(`/auth/telegram/widget-callback?${buildCallbackQuery(widget1, state, '/me')}`);
+
+ const userBefore = await db.one('SELECT id, telegram_user_id, alias FROM users WHERE telegram_user_id = 70003');
+ assert.equal(userBefore.telegram_user_id, 70003);
+
+ // Subsequent login with same numeric ID but changed username/first_name updates profile, preserves user ID
+ const clientFollowup = new Client();
+ const stateFollowup = crypto.randomBytes(16).toString('hex');
+ clientFollowup.cookies.sm_tg_state = stateFollowup;
+
+ const widgetUpdated = makeWidgetData({ id: 70003, first_name: 'Charlie Smith Updated', username: 'new_username' });
+ await clientFollowup.get(`/auth/telegram/widget-callback?${buildCallbackQuery(widgetUpdated, stateFollowup, '/me')}`);
+
+ const userAfter = await db.one('SELECT id, telegram_user_id, alias FROM users WHERE telegram_user_id = 70003');
+ assert.equal(userAfter.id, userBefore.id, 'User record ID must match across logins with same Telegram ID');
+ assert.equal(userAfter.alias, 'Charlie Smith Updated');
+});
+
+test('Telegram isolation: a different Telegram account cannot access another user NIGHTLIFEZ account', async () => {
+ // Alice (70010) creates booking or access
+ const clientAlice = new Client();
+ const stateA = crypto.randomBytes(16).toString('hex');
+ clientAlice.cookies.sm_tg_state = stateA;
+ const widgetA = makeWidgetData({ id: 70010, first_name: 'Alice_Isolated' });
+ await clientAlice.get(`/auth/telegram/widget-callback?${buildCallbackQuery(widgetA, stateA, '/me')}`);
+
+ const uAlice = await db.one('SELECT id, telegram_user_id FROM users WHERE telegram_user_id = 70010');
+
+ // Eve (70011) attempts access
+ const clientEve = new Client();
+ const stateE = crypto.randomBytes(16).toString('hex');
+ clientEve.cookies.sm_tg_state = stateE;
+ const widgetE = makeWidgetData({ id: 70011, first_name: 'Eve_Attacker' });
+ await clientEve.get(`/auth/telegram/widget-callback?${buildCallbackQuery(widgetE, stateE, '/me')}`);
+
+ const uEve = await db.one('SELECT id, telegram_user_id FROM users WHERE telegram_user_id = 70011');
+
+ assert.notEqual(uEve.id, uAlice.id);
+ assert.equal(uEve.telegram_user_id, 70011);
+ assert.equal(uAlice.telegram_user_id, 70010);
+});
+
+test('Telegram tampering: forged or mismatched Telegram ID breaks HMAC and fails authentication', async () => {
+ const client = new Client();
+ const state = crypto.randomBytes(16).toString('hex');
+ client.cookies.sm_tg_state = state;
+
+ // Attacker signs payload for 70020, but tampers URL to say id=70021
+ const widget = makeWidgetData({ id: 70020, first_name: 'Attacker' });
+ widget.id = 70021; // Tampered!
+
+ const res = await client.get(`/auth/telegram/widget-callback?${buildCallbackQuery(widget, state, '/me')}`);
+ assert.equal(res.status, 302);
+ assert.equal(res.headers.get('location'), '/signin?error=invalid_telegram_auth&next=%2Fme');
+
+ // Verify no session was issued
+ assert.ok(!res.headers.getSetCookie().some((h) => h.startsWith('sm_session=')));
+});
+
+test('Telegram UI: signin page renders switch-account guidance on Telegram tab', async () => {
+ const client = new Client();
+ const res = await client.get('/signin');
+ assert.equal(res.status, 200);
+
+ // Invariant: Clear account-switching guidance present
+ assert.match(res.text, /data-tg-switch-tip/);
+ assert.match(res.text, /Signing in with a different Telegram account\?/);
+ assert.match(res.text, /Incognito or Private window/);
+ assert.match(res.text, /web\.telegram\.org/);
+ assert.match(res.text, /Open our bot/);
+
+ // Invariant: Pradeep or any hardcoded founder ID is never embedded in template
+ assert.doesNotMatch(res.text, /Log in as Pradeep/i);
+ assert.doesNotMatch(res.text, /data-hardcoded-user/i);
+});
+
+/* ========================================================================== */
+/* OBJECTIVE B: WhatsApp Fail-Closed & Unavailable State */
+/* ========================================================================== */
+
+test('WhatsApp production fail-closed: missing Meta credentials cause HTTP 503 and clear unavailable error', async () => {
+ const client = new Client();
+
+ // In simulated production environment (VERCEL=1, VERCEL_ENV=production), unconfigured WhatsApp fails closed
+ const prevVercel = process.env.VERCEL;
+ const prevVercelEnv = process.env.VERCEL_ENV;
+ process.env.VERCEL = '1';
+ process.env.VERCEL_ENV = 'production';
+ try {
+ const res = await client.post('/api/auth/whatsapp/otp', {
+ phone: '+919876543210',
+ promotionalOptIn: false
+ });
+ assert.equal(res.status, 503);
+ assert.equal(res.json.ok, false);
+ assert.equal(res.json.error, 'whatsapp_unavailable');
+ assert.match(res.json.message, /WhatsApp sign-in is currently unavailable/);
+ } finally {
+ if (prevVercel !== undefined) process.env.VERCEL = prevVercel;
+ else delete process.env.VERCEL;
+ if (prevVercelEnv !== undefined) process.env.VERCEL_ENV = prevVercelEnv;
+ else delete process.env.VERCEL_ENV;
+ }
+});
+
+test('WhatsApp unavailable UI: renders clear unavailable card and hides phone form when WhatsApp is offline', async () => {
+ const client = new Client();
+
+ const prevVercel = process.env.VERCEL;
+ const prevVercelEnv = process.env.VERCEL_ENV;
+ process.env.VERCEL = '1';
+ process.env.VERCEL_ENV = 'production';
+ try {
+ const res = await client.get('/signin');
+ assert.equal(res.status, 200);
+
+ // When WhatsApp is unavailable, the unavailable card is rendered
+ assert.match(res.text, /data-wa-unavailable/);
+ assert.match(res.text, /WhatsApp sign-in is temporarily unavailable/);
+ assert.match(res.text, /data-switch-to-telegram/);
+
+ // And phone form is NOT rendered on the WhatsApp panel
+ assert.doesNotMatch(res.text, /data-wa-phone-form/);
+
+ // Telegram tab is active by default
+ assert.match(res.text, /data-auth-tab="telegram"/);
+ assert.match(res.text, /class="auth-tab-btn active"[^>]*data-auth-tab="telegram"/);
+ } finally {
+ if (prevVercel !== undefined) process.env.VERCEL = prevVercel;
+ else delete process.env.VERCEL;
+ if (prevVercelEnv !== undefined) process.env.VERCEL_ENV = prevVercelEnv;
+ else delete process.env.VERCEL_ENV;
+ }
+});
+
+test('WhatsApp bypass prevention: verify endpoint rejects missing challenge and invalid codes', async () => {
+ const client = new Client();
+
+ // Missing challenge ID
+ const r1 = await client.post('/api/auth/whatsapp/verify', {
+ phone: '+919876543210',
+ code: '123456'
+ });
+ assert.equal(r1.status, 400);
+
+ // Non-existent challenge ID
+ const r2 = await client.post('/api/auth/whatsapp/verify', {
+ challengeId: crypto.randomUUID(),
+ phone: '+919876543210',
+ code: '123456'
+ });
+ assert.equal(r2.status, 400);
+});
+
+/* ========================================================================== */
+/* OBJECTIVE C: Consent & Stale UI State Guardrails */
+/* ========================================================================== */
+
+test('Consent: fresh visitor signin page has age and promotional checkboxes unchecked', async () => {
+ const client = new Client();
+ const res = await client.get('/signin');
+ assert.equal(res.status, 200);
+
+ // Age confirm must never have checked attribute in HTML
+ assert.match(res.text, /data-age-confirm/);
+ assert.doesNotMatch(res.text, /data-age-confirm[^>]*checked/);
+});
+
+test('Stale UI state: direct GET /signin?step=otp without active challenge cookie safely defaults to phone step', async () => {
+ const client = new Client(); // Fresh visitor, no cookies
+
+ const res = await client.get('/signin?step=otp');
+ assert.equal(res.status, 200);
+
+ // Invariant: Dummy phone +91 98****1234 is NEVER rendered
+ assert.doesNotMatch(res.text, /\+91 98\*\*\*\*1234/);
+
+ // Invariant: OTP panel is not active/unhidden for random visitor
+ if (res.text.includes('data-wa-otp-card')) {
+ assert.match(res.text, /data-wa-otp-card[^>]*hidden/);
+ }
+});
+
+test('Stale cookie: expired sm_wa_step cookie is cleared and defaults to phone step', async () => {
+ const client = new Client();
+ // Set expired challenge cookie (> 15 minutes old)
+ client.cookies.sm_wa_step = JSON.stringify({
+ challengeId: crypto.randomUUID(),
+ phoneMasked: '+91 98****9999',
+ phone: '+919876549999',
+ createdAt: Date.now() - 15 * 60 * 1000
+ });
+
+ const res = await client.get('/signin?step=otp');
+ assert.equal(res.status, 200);
+
+ // Invariant: Cookie is cleared with max-age=0
+ const setCookies = res.headers.getSetCookie();
+ const cleared = setCookies.find((c) => c.startsWith('sm_wa_step='));
+ assert.ok(cleared, 'Expired sm_wa_step cookie must be cleared');
+ assert.match(cleared, /max-age=0/i);
+});
+
+test('CSS Invariant: [hidden] attribute strictly enforces display: none !important', async () => {
+ const client = new Client();
+ const res = await client.get('/css/site.css');
+ assert.equal(res.status, 200);
+
+ // Verify CSS contains !important on hidden attribute
+ assert.match(res.text, /\[hidden\]\s*\{\s*display:\s*none\s*!important/);
+ assert.match(res.text, /\.otp-box\[hidden\]/);
+});