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
86 changes: 86 additions & 0 deletions e2e/auth-audit.spec.js
Original file line number Diff line number Diff line change
@@ -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();
});
});
1 change: 1 addition & 0 deletions e2e/env.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
3 changes: 2 additions & 1 deletion lib/handlers/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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)}`);
}
Expand Down
33 changes: 29 additions & 4 deletions lib/handlers/pages.js
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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));
Expand All @@ -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';
Expand All @@ -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()
Expand Down
20 changes: 14 additions & 6 deletions lib/services/whatsapp-auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand All @@ -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',
Expand Down
44 changes: 37 additions & 7 deletions lib/views/pages.js
Original file line number Diff line number Diff line change
Expand Up @@ -474,7 +474,16 @@ function devPersonaPicker() {
</section>`;
}

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`<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 @@ -514,12 +523,19 @@ export function renderSignin({ next = '/me', error = '', step = 'phone', oidc =
</div>` : ''}

<div class="auth-switcher" role="tablist" aria-label="Sign in method">
<button type="button" class="auth-tab-btn active wa-tab" role="tab" data-auth-tab="whatsapp" aria-selected="true">Continue with WhatsApp</button>
<button type="button" class="auth-tab-btn" role="tab" data-auth-tab="telegram" aria-selected="false">Continue with Telegram</button>
<button type="button" class="auth-tab-btn ${whatsappAvailable ? 'active wa-tab' : ''}" role="tab" data-auth-tab="whatsapp" aria-selected="${whatsappAvailable ? 'true' : 'false'}">Continue with WhatsApp</button>
<button type="button" class="auth-tab-btn ${!whatsappAvailable ? 'active' : ''}" role="tab" data-auth-tab="telegram" aria-selected="${!whatsappAvailable ? 'true' : 'false'}">Continue with Telegram</button>
</div>

<!-- WhatsApp Panel -->
<div class="auth-panel" data-auth-panel="whatsapp">
<div class="auth-panel" data-auth-panel="whatsapp" ${!whatsappAvailable ? 'hidden' : ''}>
${!whatsappAvailable ? html`
<div class="wa-unavailable-card" data-wa-unavailable>
<div class="wa-unavailable-icon" aria-hidden="true">📱</div>
<h3 class="wa-unavailable-title">WhatsApp sign-in is temporarily unavailable</h3>
<p class="wa-unavailable-desc">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.</p>
<button type="button" class="btn btn-tg btn-lg btn-block" data-switch-to-telegram>Continue with Telegram</button>
</div>` : html`
<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}">
Expand Down Expand Up @@ -554,7 +570,7 @@ export function renderSignin({ next = '/me', error = '', step = 'phone', oidc =
<div class="field">
<label for="otp-input">Verification code</label>
<p id="otp-format-hint" class="otp-hint">
Enter the 6-digit verification code sent to your WhatsApp on <strong data-wa-masked-phone>+91 98****1234</strong>.
Enter the 6-digit verification code sent to your WhatsApp on <strong data-wa-masked-phone>${maskedPhone || ''}</strong>.
</p>
<input
type="text"
Expand All @@ -576,12 +592,26 @@ export function renderSignin({ next = '/me', error = '', step = 'phone', oidc =
</div>
</div>
</form>
</div>
</div>`}
</div>

<!-- Telegram Panel -->
<div class="auth-panel" data-auth-panel="telegram" hidden>
<div class="auth-panel" data-auth-panel="telegram" ${whatsappAvailable ? 'hidden' : ''}>
${tgMethod}
<div class="tg-switch-tip" data-tg-switch-tip>
<div class="tg-switch-tip-header">
<span class="tg-switch-icon" aria-hidden="true">ℹ️</span>
<strong>Signing in with a different Telegram account?</strong>
</div>
<p class="tg-switch-desc">
Telegram automatically detects the active Telegram session in this browser. To sign in with a different Telegram account:
</p>
<ul class="tg-switch-steps">
<li>Open an <strong>Incognito or Private window</strong> to log in with a different Telegram phone number.</li>
<li>Or sign out of Telegram Web at <a href="https://web.telegram.org" target="_blank" rel="noopener">web.telegram.org</a>.</li>
${bot ? html`<li>Or open our bot <a href="https://t.me/${bot}?start=signin">@${bot}</a> directly in the Telegram app on your phone and tap “Open NIGHTLIFEZ”.</li>` : ''}
</ul>
</div>
${bot ? html`<p class="muted" style="margin-top: 14px;">Using Telegram on your phone? <a href="https://t.me/${bot}?start=signin">Open our bot</a> and tap “Open NIGHTLIFEZ”.</p>` : ''}
</div>

Expand Down
40 changes: 40 additions & 0 deletions public/css/site.css
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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); }
Expand Down
35 changes: 34 additions & 1 deletion public/js/site.js
Original file line number Diff line number Diff line change
Expand Up @@ -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]');
Expand Down Expand Up @@ -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 = '';
});
}

Expand Down Expand Up @@ -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). */
Expand Down
Loading
Loading