diff --git a/e2e/cancellation-policy.spec.js b/e2e/cancellation-policy.spec.js index a1a81cb..cd9432b 100644 --- a/e2e/cancellation-policy.spec.js +++ b/e2e/cancellation-policy.spec.js @@ -4,9 +4,8 @@ import { signInAs, expectNoHorizontalOverflow } from './helpers.js'; import path from 'node:path'; import fs from 'node:fs'; -const ARTIFACT_DIR = '/Users/pradeepjakuraa/.gemini/antigravity-cli/brain/6f313897-14aa-4f3b-8320-52b8ec01c32f'; -const SHOT_DIR = path.join(ARTIFACT_DIR, 'evidence'); -fs.mkdirSync(SHOT_DIR, { recursive: true }); +const ARTIFACT_DIR = process.env.ARTIFACT_DIR || path.join(process.cwd(), 'test-results', 'evidence'); +fs.mkdirSync(ARTIFACT_DIR, { recursive: true }); function localInput(daysAhead, hour) { const d = new Date(Date.now() + daysAhead * 86_400_000); @@ -89,7 +88,7 @@ test.describe('Event Creator Cancellation & Refund Templates', () => { // Capture visual screenshot of the wizard cancellation policy selection await page.setViewportSize({ width: 1280, height: 900 }); await page.screenshot({ - path: path.join(SHOT_DIR, 'creator-cancellation-policy-wizard.png'), + path: path.join(ARTIFACT_DIR, 'creator-cancellation-policy-wizard.png'), fullPage: true }); @@ -108,7 +107,7 @@ test.describe('Event Creator Cancellation & Refund Templates', () => { await page.setViewportSize({ width: 1280, height: 900 }); await page.screenshot({ - path: path.join(SHOT_DIR, 'attendee-cancellation-policy-preview.png'), + path: path.join(ARTIFACT_DIR, 'attendee-cancellation-policy-preview.png'), fullPage: true }); } diff --git a/e2e/multi-date-wizard.spec.js b/e2e/multi-date-wizard.spec.js index 80410b4..b26082a 100644 --- a/e2e/multi-date-wizard.spec.js +++ b/e2e/multi-date-wizard.spec.js @@ -4,9 +4,8 @@ import { signInAs, expectNoHorizontalOverflow } from './helpers.js'; import path from 'node:path'; import fs from 'node:fs'; -const ARTIFACT_DIR = '/Users/pradeepjakuraa/.gemini/antigravity-cli/brain/6f313897-14aa-4f3b-8320-52b8ec01c32f'; -const SHOT_DIR = path.join(ARTIFACT_DIR, 'evidence'); -fs.mkdirSync(SHOT_DIR, { recursive: true }); +const ARTIFACT_DIR = process.env.ARTIFACT_DIR || path.join(process.cwd(), 'test-results', 'evidence'); +fs.mkdirSync(ARTIFACT_DIR, { recursive: true }); function formatLocalYMD(daysAhead) { const d = new Date(Date.now() + daysAhead * 86_400_000); @@ -78,7 +77,7 @@ test.describe('Event Creation UX - Multi-Date Scheduling & Accessibility', () => await page.locator('input[data-path="schedule.dates.3.label"]').fill('Grand Finale'); // Capture Step 1 evidence - await page.screenshot({ path: path.join(SHOT_DIR, 'multi-date-wizard-creator.png'), fullPage: true }); + await page.screenshot({ path: path.join(ARTIFACT_DIR, 'multi-date-wizard-creator.png'), fullPage: true }); // Proceed to Step 2: Tickets await page.getByRole('button', { name: /Next: Tickets/ }).click(); @@ -105,7 +104,7 @@ test.describe('Event Creation UX - Multi-Date Scheduling & Accessibility', () => await expect(draftPill).toContainText('Draft — External Checkout Pending'); // Capture Step 2 evidence - await page.screenshot({ path: path.join(SHOT_DIR, 'multi-date-tickets-draft-state.png'), fullPage: true }); + await page.screenshot({ path: path.join(ARTIFACT_DIR, 'multi-date-tickets-draft-state.png'), fullPage: true }); // Proceed to Step 3: Features then Step 4: Preview await page.getByRole('button', { name: /Next: Features/ }).click(); @@ -125,7 +124,7 @@ test.describe('Event Creation UX - Multi-Date Scheduling & Accessibility', () => await expect(attPrev).toContainText('Paid ticket — external checkout not configured'); // Capture Step 4 evidence - await page.screenshot({ path: path.join(SHOT_DIR, 'multi-date-attendee-preview.png'), fullPage: true }); + await page.screenshot({ path: path.join(ARTIFACT_DIR, 'multi-date-attendee-preview.png'), fullPage: true }); }); test('Responsive viewports audit: 375px mobile and 768px tablet', async ({ page }) => { diff --git a/e2e/promotional-campaigns.spec.js b/e2e/promotional-campaigns.spec.js new file mode 100644 index 0000000..d5bb2ee --- /dev/null +++ b/e2e/promotional-campaigns.spec.js @@ -0,0 +1,120 @@ +// e2e/promotional-campaigns.spec.js - Playwright E2E for WhatsApp promotional opt-in, account preferences, and organiser campaigns. +import { test, expect } from '@playwright/test'; +import { expectAccessible, expectNoHorizontalOverflow, screenshot, signInAs } 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('WhatsApp Promotional Marketing & Organiser Campaigns E2E', () => { + test('Desktop (1280px): marketing consent on signup, account preferences, and organiser campaign workflow', async ({ page }, testInfo) => { + await page.setViewportSize({ width: 1280, height: 800 }); + + // 1. Visit /signin and verify marketing consent checkbox + await page.goto('/signin'); + await expect(page.getByRole('heading', { level: 1 })).toContainText('Continue to NIGHTLIFEZ'); + await expect(page.locator('[data-auth-tab="whatsapp"]')).toBeVisible(); + + const promoCheckbox = page.locator('#wa-promo-optin'); + await expect(promoCheckbox).toBeVisible(); + // Invariant: Unchecked by default! + expect(await promoCheckbox.isChecked()).toBe(false); + + const promoHint = page.locator('#wa-promo-hint'); + await expect(promoHint).toContainText('Optional. Unchecked by default. Separate from essential login OTPs'); + + await expectAccessible(page); + await expectNoHorizontalOverflow(page); + + const signinShotPath = path.join(ARTIFACT_DIR, 'whatsapp-marketing-consent-signup.png'); + await page.screenshot({ path: signinShotPath, fullPage: true }); + + // 2. Sign in as organiser persona + await signInAs(page, 'organiser'); + await page.waitForURL(/\/organiser$/); + + // 3. Find first managed event and go to manage page + const manageLink = page.locator('a[href^="/organiser/events/"]').first(); + await expect(manageLink).toBeVisible(); + await manageLink.click(); + await page.waitForURL(/\/organiser\/events\/[a-f0-9-]+$/); + + // 4. Click WhatsApp Promotion tab + const promoTab = page.locator('button[data-tab="promotions"]'); + await expect(promoTab).toBeVisible(); + await promoTab.click(); + + // Verify WhatsApp promotion panel loads + const audienceStat = page.locator('[data-audience-count]'); + await expect(audienceStat).toBeVisible(); + await expect(page.locator('.wa-bubble-preview')).toBeVisible(); + + await expectAccessible(page); + await expectNoHorizontalOverflow(page); + + const promoTabShotPath = path.join(ARTIFACT_DIR, 'organiser-whatsapp-promotion-tab.png'); + await page.screenshot({ path: promoTabShotPath, fullPage: true }); + + // 5. Create a campaign draft + const titleInput = page.locator('#campaign-title-input'); + await expect(titleInput).toBeVisible(); + const createBtn = page.locator('[data-create-campaign-form] button[type="submit"]'); + await createBtn.click(); + + // Wait for campaign to appear in history + await page.waitForSelector('[data-dispatch-campaign], [data-approve-campaign]'); + + // Approve campaign if draft + const approveBtn = page.locator('[data-approve-campaign]').first(); + if (await approveBtn.isVisible()) { + await approveBtn.click(); + await page.waitForTimeout(500); + } + + // Dispatch simulated campaign + page.on('dialog', async (dialog) => { + await dialog.accept(); + }); + + const dispatchBtn = page.locator('[data-dispatch-campaign]').first(); + if (await dispatchBtn.isVisible()) { + await dispatchBtn.click(); + await page.waitForTimeout(1000); + } + + // View delivery logs + const logsBtn = page.locator('[data-view-logs]').first(); + if (await logsBtn.isVisible()) { + await logsBtn.click(); + await page.waitForTimeout(500); + } + + const campaignLogsShotPath = path.join(ARTIFACT_DIR, 'organiser-whatsapp-campaign-logs.png'); + await page.screenshot({ path: campaignLogsShotPath, fullPage: true }); + + // 6. Navigate to /me and verify communication preferences + await page.goto('/me'); + const accountTab = page.locator('[data-hub-tab="account"]'); + await expect(accountTab).toBeVisible(); + await accountTab.click(); + + await expect(page.locator('[data-toggle-promo-wa]')).toBeVisible(); + await expectAccessible(page); + + const accountShotPath = path.join(ARTIFACT_DIR, 'whatsapp-marketing-preferences-me.png'); + await page.screenshot({ path: accountShotPath, fullPage: true }); + }); + + test('Mobile (375px): responsive layout, tap targets, and consent UX', async ({ page }, testInfo) => { + await page.setViewportSize({ width: 375, height: 667 }); + + await page.goto('/signin'); + await expect(page.locator('#wa-promo-optin')).toBeVisible(); + expect(await page.locator('#wa-promo-optin').isChecked()).toBe(false); + + await expectAccessible(page); + await expectNoHorizontalOverflow(page); + await screenshot(page, testInfo, 'mobile-whatsapp-marketing-signup'); + }); +}); diff --git a/e2e/whatsapp-auth.spec.js b/e2e/whatsapp-auth.spec.js new file mode 100644 index 0000000..6668a92 --- /dev/null +++ b/e2e/whatsapp-auth.spec.js @@ -0,0 +1,95 @@ +// e2e/whatsapp-auth.spec.js - End-to-end tests for WhatsApp OTP sign-in, WebOTP form compliance, and account preferences. +import { test, expect } from '@playwright/test'; +import { expectAccessible, expectNoHorizontalOverflow, screenshot } from './helpers.js'; +import { getWhatsAppProvider } from '../lib/services/whatsapp-provider.js'; + +test.describe('WhatsApp OTP Authentication E2E', () => { + test('Desktop (1280px): complete WhatsApp OTP signup, WebOTP form verification, and preferences', async ({ page }, testInfo) => { + await page.setViewportSize({ width: 1280, height: 800 }); + getWhatsAppProvider().clearSentMessages(); + + // 1. Visit /signin + await page.goto('/signin'); + await expect(page.getByRole('heading', { level: 1 })).toContainText('Continue to NIGHTLIFEZ'); + await expect(page.locator('[data-auth-tab="whatsapp"]')).toBeVisible(); + await expect(page.locator('[data-auth-tab="telegram"]')).toBeVisible(); + await expect(page.locator('[data-wa-phone-form]')).toBeVisible(); + + await expectAccessible(page); + await expectNoHorizontalOverflow(page); + await screenshot(page, testInfo, 'desktop-signin-whatsapp-tab'); + + // 2. Fill mobile number, confirm age, request OTP + const phoneInput = page.locator('#wa-phone'); + await phoneInput.fill('9876543210'); + await page.locator('[data-wa-age]').check(); + await page.locator('[data-wa-promo]').check(); + + const [otpResponse] = await Promise.all([ + page.waitForResponse((r) => r.url().includes('/api/auth/whatsapp/otp') && r.status() === 200), + page.locator('[data-wa-submit-phone]').click() + ]); + const otpJson = await otpResponse.json(); + const code = otpJson.devOtp; + expect(code).toMatch(/^\d{6}$/); + + // 3. Verify OTP step is displayed + const otpCard = page.locator('[data-wa-otp-card]'); + await expect(otpCard).toBeVisible(); + await expect(page.locator('#otp-input')).toBeVisible(); + await expect(page.locator('#otp-format-hint')).toBeVisible(); + await expect(page.locator('[data-wa-masked-phone]')).toContainText('+91 98****3210'); + + // Check modern web guidance compliance + await expect(page.locator('#otp-input')).toHaveAttribute('inputmode', 'numeric'); + await expect(page.locator('#otp-input')).toHaveAttribute('autocomplete', 'one-time-code'); + await expect(page.locator('#otp-input')).toHaveAttribute('pattern', '\\d{6}'); + await expect(page.locator('#otp-input')).toHaveAttribute('maxlength', '6'); + + await expectAccessible(page); + await screenshot(page, testInfo, 'desktop-signin-otp-step'); + + // 4. Fill OTP and submit + await page.locator('#otp-input').fill(code); + await page.locator('[data-wa-verify-btn]').click(); + + // 5. User lands on /me authenticated + await page.waitForURL(/\/me$/); + await expect(page.getByRole('heading', { level: 1 })).toContainText('My bookings'); + + // 6. Navigate to Account & Logins tab + const accountTab = page.locator('[data-hub-tab="account"]'); + await expect(accountTab).toBeVisible(); + await accountTab.click(); + + const accountSection = page.locator('[data-hub-section="account"]'); + await expect(accountSection).toBeVisible(); + await expect(accountSection).toContainText('Connected Login Methods'); + await expect(accountSection).toContainText('✓ Connected (+91 98****3210)'); + await expect(accountSection).toContainText('Communication Preferences'); + + await expectAccessible(page); + await expectNoHorizontalOverflow(page); + await screenshot(page, testInfo, 'desktop-attendee-account-settings'); + }); + + test('Mobile (375px): responsive layout, tap targets, and switcher behavior', async ({ page }, testInfo) => { + await page.setViewportSize({ width: 375, height: 667 }); + getWhatsAppProvider().clearSentMessages(); + + await page.goto('/signin'); + await expectNoHorizontalOverflow(page); + + // Switch to Telegram tab + await page.locator('[data-auth-tab="telegram"]').click(); + await expect(page.locator('[data-auth-panel="telegram"]')).toBeVisible(); + await expect(page.locator('[data-auth-panel="whatsapp"]')).toBeHidden(); + + // Switch back to WhatsApp tab + await page.locator('[data-auth-tab="whatsapp"]').click(); + await expect(page.locator('[data-auth-panel="whatsapp"]')).toBeVisible(); + await expect(page.locator('[data-auth-panel="telegram"]')).toBeHidden(); + + await screenshot(page, testInfo, 'mobile-signin-whatsapp'); + }); +}); diff --git a/lib/handlers/admin.js b/lib/handlers/admin.js index 6da38d4..5271e2b 100644 --- a/lib/handlers/admin.js +++ b/lib/handlers/admin.js @@ -24,6 +24,11 @@ import { R } from '../admin-roles.js'; import { ensurePersonalOrg, setOrganiseCapability } from '../services/permissions.js'; import { page, pageInfo } from '../pagination.js'; import { resolveCity } from '../services/locations.js'; +import { + getNotificationTelemetry, + getNotificationMessagesList, + getSuppressionsList +} from '../services/notification-dispatcher.js'; /** Resolve the admin for this request (bootstrapping the owner once), or throw 401/403. */ @@ -1135,3 +1140,38 @@ export async function listSuperprofile(ctx) { ok: true, configured: superprofileConfigured(), webhookPath: '/api/membership/superprofile/webhook', events }); } + +// ---------- Multichannel Notifications & WhatsApp Telemetry ---------- + +export async function notificationHealth(ctx) { + await guard(ctx, ['super_admin', 'support']); + const telemetry = await getNotificationTelemetry(); + sendJson(ctx.res, 200, { ok: true, whatsapp: telemetry.whatsapp }); +} + +export async function notificationStats(ctx) { + await guard(ctx, ['super_admin', 'support']); + const telemetry = await getNotificationTelemetry(); + sendJson(ctx.res, 200, { ok: true, telemetry }); +} + +export async function notificationMessages(ctx) { + await guard(ctx, ['super_admin', 'support']); + const limit = Math.min(Math.max(parseInt(ctx.query?.get?.('limit') || '50', 10), 1), 100); + const offset = Math.max(parseInt(ctx.query?.get?.('offset') || '0', 10), 0); + const channel = ctx.query?.get?.('channel') || null; + const status = ctx.query?.get?.('status') || null; + + const messages = await getNotificationMessagesList({ limit, offset, channel, status }); + sendJson(ctx.res, 200, { ok: true, messages, limit, offset }); +} + +export async function notificationSuppressions(ctx) { + await guard(ctx, ['super_admin', 'support']); + const limit = Math.min(Math.max(parseInt(ctx.query?.get?.('limit') || '50', 10), 1), 100); + const offset = Math.max(parseInt(ctx.query?.get?.('offset') || '0', 10), 0); + + const suppressions = await getSuppressionsList({ limit, offset }); + sendJson(ctx.res, 200, { ok: true, suppressions, limit, offset }); +} + diff --git a/lib/handlers/auth.js b/lib/handlers/auth.js index 8d46894..dda5564 100644 --- a/lib/handlers/auth.js +++ b/lib/handlers/auth.js @@ -21,6 +21,13 @@ import { createSession, setSessionCookie, clearSessionCookie, csrfTokenFor, getSessionUser, requireUser, requireCsrf, revokeSession, revokeUserSessions } from '../session.js'; +import { + requestWhatsAppOtp, + verifyWhatsAppOtpAndResolveUser, + unlinkWhatsAppIdentity, + getLinkedIdentities +} from '../services/whatsapp-auth.js'; +import { getConsents, recordConsent } from '../services/communication-consent.js'; const AuthBody = z.object({ initData: z.string().max(4096).optional(), @@ -368,3 +375,165 @@ export async function updateMyNotificationPreferences({ req, res }) { } : null }); } + +// ---------- WhatsApp Authentication & Identity Linking ---------- + +const WhatsAppOtpRequestBody = z.object({ + phone: z.string().min(5).max(30), + promotionalOptIn: z.boolean().optional().default(false) +}).strict(); + +const WhatsAppOtpVerifyBody = z.object({ + challengeId: z.string().uuid(), + phone: z.string().min(5).max(30), + code: z.string().regex(/^\d{6}$/, 'OTP must be 6 digits'), + promotionalOptIn: z.boolean().optional().default(false) +}).strict(); + +const WhatsAppLinkBody = z.object({ + challengeId: z.string().uuid(), + phone: z.string().min(5).max(30), + code: z.string().regex(/^\d{6}$/, 'OTP must be 6 digits'), + promotionalOptIn: z.boolean().optional().default(false) +}).strict(); + +const WhatsAppUnlinkBody = z.object({ + phone: z.string().min(5).max(30).optional() +}).strict(); + +const CommunicationPreferencesPatchBody = z.object({ + channel: z.enum(['whatsapp', 'telegram', 'email', 'sms']), + purpose: z.enum(['transactional', 'promotional']), + status: z.enum(['opted_in', 'opted_out']) +}).strict(); + +/** 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 userAgent = req.headers['user-agent'] || null; + + const result = await requestWhatsAppOtp({ + phone: body.phone, + ip, + userAgent, + promotionalOptIn: body.promotionalOptIn + }); + + sendJson(res, 200, { + ok: true, + challengeId: result.challengeId, + phoneMasked: result.phoneMasked, + resendAfterSeconds: result.resendAfterSeconds, + expiresInSeconds: result.expiresInSeconds, + ...(process.env.DEV_LOGIN === 'true' || process.env.NODE_ENV === 'test' ? { devOtp: result.devOtp } : {}) + }); +} + +/** 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 userAgent = req.headers['user-agent'] || null; + + const auth = await verifyWhatsAppOtpAndResolveUser({ + challengeId: body.challengeId, + phone: body.phone, + code: body.code, + ip, + userAgent, + promotionalOptIn: body.promotionalOptIn + }); + + const { csrf } = await startSession(req, res, auth.user); + sendJson(res, 200, { + ok: true, + csrf, + user: publicUser(auth.user), + isNewUser: auth.isNewUser + }); +} + +/** POST /api/auth/whatsapp/link — Link WhatsApp to current signed-in user. */ +export async function linkWhatsAppHandler({ req, res, ip }) { + const user = await requireUser(req); + requireCsrf(req, user); + + const body = parse(WhatsAppLinkBody, await readJson(req)); + const userAgent = req.headers['user-agent'] || null; + + const auth = await verifyWhatsAppOtpAndResolveUser({ + challengeId: body.challengeId, + phone: body.phone, + code: body.code, + ip, + userAgent, + existingUserId: user.id, + promotionalOptIn: body.promotionalOptIn + }); + + sendJson(res, 200, { + ok: true, + message: 'WhatsApp connected successfully', + user: publicUser(auth.user) + }); +} + +/** POST /api/auth/whatsapp/unlink — Unlink WhatsApp identity (sole-provider protected). */ +export async function unlinkWhatsAppHandler({ req, res }) { + const user = await requireUser(req); + requireCsrf(req, user); + + const body = parse(WhatsAppUnlinkBody, await readJson(req).catch(() => ({}))); + const phoneToUnlink = body?.phone || user.phone; + + if (!phoneToUnlink) { + throw new HttpError(400, 'validation', 'No phone number associated with this account'); + } + + await unlinkWhatsAppIdentity({ + userId: user.id, + phone: phoneToUnlink + }); + + sendJson(res, 200, { + ok: true, + message: 'WhatsApp disconnected successfully' + }); +} + +/** GET /api/me/identities — Returns all linked authentication identities. */ +export async function getMyIdentitiesHandler({ req, res }) { + const user = await requireUser(req); + const identities = await getLinkedIdentities(user.id); + sendJson(res, 200, { ok: true, identities }); +} + +/** GET /api/me/communication-preferences — Returns granular communication consents. */ +export async function getMyCommunicationPreferences({ req, res }) { + const user = await requireUser(req); + const preferences = await getConsents(user.id); + sendJson(res, 200, { ok: true, preferences }); +} + +/** PATCH /api/me/communication-preferences — Updates consent status. */ +export async function updateMyCommunicationPreferences({ req, res, ip }) { + const user = await requireUser(req); + requireCsrf(req, user); + + const body = parse(CommunicationPreferencesPatchBody, await readJson(req)); + const userAgent = req.headers['user-agent'] || null; + + await recordConsent({ + userId: user.id, + channel: body.channel, + purpose: body.purpose, + status: body.status, + ip, + userAgent + }); + + const preferences = await getConsents(user.id); + sendJson(res, 200, { ok: true, preferences }); +} + diff --git a/lib/handlers/campaigns.js b/lib/handlers/campaigns.js new file mode 100644 index 0000000..ac5a0ae --- /dev/null +++ b/lib/handlers/campaigns.js @@ -0,0 +1,248 @@ +// lib/handlers/campaigns.js - HTTP API handlers for opt-in promotional campaigns, audience preview, approval, and delivery logs. +import { HttpError, readJson, sendJson, hashIp } from '../http.js'; +import { requireUser, requireCsrf, getSessionUser } from '../session.js'; +import { parse, z, uuid } from '../validate.js'; +import { rateLimit } from '../ratelimit.js'; +import { db } from '../db.js'; +import { manageableEvent } from '../services/ticketing.js'; +import { + previewCampaignAudience, + createCampaign, + getCampaign, + listCampaigns, + approveCampaign, + cancelCampaign, + dispatchCampaign, + getCampaignLogs +} from '../services/promotional-campaign.js'; +import { handleOptOutKeyword } from '../services/notification-dispatcher.js'; +import { normalizePhoneNumber } from '../services/phone.js'; +import { recordConsent } from '../services/communication-consent.js'; + +async function isSuperAdminUser(user, client = db) { + if (!user?.telegram_user_id) return false; + const { rows } = await client.query( + 'SELECT 1 FROM admin_users WHERE telegram_user_id = $1 AND active AND role = $2', + [user.telegram_user_id, 'super_admin'] + ); + return rows.length > 0; +} + +const CampaignPreviewBody = z.object({ + eventId: uuid, + targetCity: z.string().trim().max(100).nullable().optional(), + targetCategory: z.string().trim().max(100).nullable().optional() +}); + +const CreateCampaignBody = z.object({ + eventId: uuid, + title: z.string().trim().min(3).max(160).optional(), + targetCity: z.string().trim().max(100).nullable().optional(), + targetCategory: z.string().trim().max(100).nullable().optional() +}); + +const UnsubscribeBody = z.object({ + phone: z.string().trim().min(8).max(20).optional(), + channel: z.enum(['whatsapp', 'telegram', 'email', 'sms']).default('whatsapp'), + reason: z.string().trim().max(100).default('user_unsubscribed') +}); + +/** + * POST /api/campaigns/preview — Previews audience count, cost, and sample WhatsApp template. + */ +export async function previewCampaignHandler({ req, res }) { + const user = await requireUser(req); + const body = parse(CampaignPreviewBody, await readJson(req)); + + // Authorize user for this event (organiser or admin) + await manageableEvent(user, body.eventId); + + const preview = await previewCampaignAudience({ + eventId: body.eventId, + targetCity: body.targetCity, + targetCategory: body.targetCategory + }); + + return sendJson(res, 200, preview); +} + +/** + * POST /api/campaigns — Creates a new campaign draft. + */ +export async function createCampaignHandler({ req, res }) { + const user = await requireUser(req); + requireCsrf(req, user); + await rateLimit(`campaign_create:${user.id}`, 20, 300); + + const body = parse(CreateCampaignBody, await readJson(req)); + const event = await manageableEvent(user, body.eventId); + + const campaign = await createCampaign({ + eventId: body.eventId, + createdByUserId: user.id, + organiserOrgId: event.organiser_org_id || null, + title: body.title, + targetCity: body.targetCity, + targetCategory: body.targetCategory + }); + + return sendJson(res, 201, { ok: true, campaign }); +} + +/** + * GET /api/campaigns — Lists promotional campaigns. + */ +export async function listCampaignsHandler({ req, res, query }) { + const user = await requireUser(req); + const eventId = query.get('eventId'); + const isSuperAdmin = await isSuperAdminUser(user); + + if (eventId) { + await manageableEvent(user, eventId); + } + + const campaigns = await listCampaigns({ + eventId, + userId: user.id, + isSuperAdmin + }); + + return sendJson(res, 200, { ok: true, campaigns }); +} + +/** + * GET /api/campaigns/:id — Gets a campaign's detail. + */ +export async function getCampaignHandler({ req, res, params }) { + const user = await requireUser(req); + const campaign = await getCampaign({ campaignId: params.id }); + const isSuperAdmin = await isSuperAdminUser(user); + + if (!isSuperAdmin) { + await manageableEvent(user, campaign.event_id); + } + + return sendJson(res, 200, { ok: true, campaign }); +} + +/** + * POST /api/campaigns/:id/approve — Approves a campaign. + */ +export async function approveCampaignHandler({ req, res, params }) { + const user = await requireUser(req); + requireCsrf(req, user); + + const campaign = await getCampaign({ campaignId: params.id }); + const isSuperAdmin = await isSuperAdminUser(user); + + if (!isSuperAdmin) { + await manageableEvent(user, campaign.event_id); + } + + const updated = await approveCampaign({ + campaignId: params.id, + approvedByUserId: user.id + }); + + return sendJson(res, 200, { ok: true, campaign: updated }); +} + +/** + * POST /api/campaigns/:id/cancel — Cancels a campaign. + */ +export async function cancelCampaignHandler({ req, res, params }) { + const user = await requireUser(req); + requireCsrf(req, user); + + const campaign = await getCampaign({ campaignId: params.id }); + const isSuperAdmin = await isSuperAdminUser(user); + + if (!isSuperAdmin) { + await manageableEvent(user, campaign.event_id); + } + + const updated = await cancelCampaign({ + campaignId: params.id, + userId: user.id + }); + + return sendJson(res, 200, { ok: true, campaign: updated }); +} + +/** + * POST /api/campaigns/:id/dispatch — Dispatches or simulates campaign sending. + */ +export async function dispatchCampaignHandler({ req, res, params }) { + const user = await requireUser(req); + requireCsrf(req, user); + await rateLimit(`campaign_dispatch:${user.id}`, 10, 300); + + const campaign = await getCampaign({ campaignId: params.id }); + const isSuperAdmin = await isSuperAdminUser(user); + + if (!isSuperAdmin) { + await manageableEvent(user, campaign.event_id); + } + + const result = await dispatchCampaign({ + campaignId: params.id, + triggeredByUserId: user.id + }); + + return sendJson(res, 200, result); +} + +/** + * GET /api/campaigns/:id/logs — Retrieves delivery logs for a campaign. + */ +export async function getCampaignLogsHandler({ req, res, params }) { + const user = await requireUser(req); + const campaign = await getCampaign({ campaignId: params.id }); + const isSuperAdmin = await isSuperAdminUser(user); + + if (!isSuperAdmin) { + await manageableEvent(user, campaign.event_id); + } + + const logs = await getCampaignLogs({ campaignId: params.id }); + return sendJson(res, 200, { ok: true, logs }); +} + +/** + * POST /api/notifications/unsubscribe — One-click unsubscribe endpoint. + */ +export async function unsubscribeHandler({ req, res, ip }) { + await rateLimit(`unsub_ip:${hashIp(ip)}`, 20, 300); + const sessionUser = await getSessionUser(req); + const body = parse(UnsubscribeBody, await readJson(req).catch(() => ({}))); + + let phone = body.phone; + if (!phone && sessionUser && sessionUser.phone) { + phone = sessionUser.phone; + } + + if (phone) { + const normalized = normalizePhoneNumber(phone); + await handleOptOutKeyword({ + destination: normalized, + channel: body.channel || 'whatsapp', + reason: body.reason || 'user_unsubscribed' + }); + } + + if (sessionUser) { + await recordConsent({ + userId: sessionUser.id, + channel: body.channel || 'whatsapp', + purpose: 'promotional', + status: 'opted_out', + source: 'opt_out_link', + ip + }); + } + + return sendJson(res, 200, { + ok: true, + message: 'You have been unsubscribed from promotional marketing messages. Essential transactional notices remain active.' + }); +} diff --git a/lib/handlers/whatsapp-webhook.js b/lib/handlers/whatsapp-webhook.js new file mode 100644 index 0000000..4c4c3b4 --- /dev/null +++ b/lib/handlers/whatsapp-webhook.js @@ -0,0 +1,106 @@ +// lib/handlers/whatsapp-webhook.js - Webhook verification and event ingestion for Meta WhatsApp Cloud API. +import { HttpError, readRawBody, sendJson } from '../http.js'; +import { logger } from '../logger.js'; +import { getWhatsAppConfig, getWhatsAppProvider } from '../services/whatsapp-provider.js'; +import { updateDeliveryReceipt, handleOptOutKeyword } from '../services/notification-dispatcher.js'; + +const OPT_OUT_KEYWORDS = new Set(['STOP', 'UNSUBSCRIBE', 'OPTOUT', 'CANCEL', 'BLOCK', 'QUIT']); + +/** + * GET /api/webhooks/whatsapp — Meta webhook verification challenge. + */ +export async function verifyWebhook({ res, query }) { + const mode = query.get('hub.mode'); + const token = query.get('hub.verify_token'); + const challenge = query.get('hub.challenge'); + + const config = getWhatsAppConfig(); + const expectedToken = config.webhookVerifyToken || 'nightlifez_webhook_verify_token'; + + if (mode === 'subscribe' && token === expectedToken) { + logger.info('meta whatsapp webhook verification challenge accepted'); + res.writeHead(200, { 'Content-Type': 'text/plain' }); + res.end(challenge || ''); + return; + } + + logger.warn('meta whatsapp webhook verification challenge failed', { mode, tokenProvided: Boolean(token) }); + throw new HttpError(403, 'forbidden', 'Verification token mismatch'); +} + +/** + * POST /api/webhooks/whatsapp — Meta webhook notification receiver. + */ +export async function handleWebhook({ req, res }) { + const rawBody = await readRawBody(req); + const signature = req.headers['x-hub-signature-256']; + const provider = getWhatsAppProvider(); + + const config = getWhatsAppConfig(); + // Only enforce signature check if secret is configured + if (config.webhookSecret || process.env.NODE_ENV === 'test') { + if (!signature || !provider.verifyWebhookSignature({ rawBody, signatureHeader: signature })) { + logger.warn('meta whatsapp webhook signature verification failed'); + throw new HttpError(401, 'invalid_signature', 'Invalid webhook signature'); + } + } + + let body; + try { + body = JSON.parse(rawBody); + } catch { + throw new HttpError(400, 'invalid_json', 'Malformed JSON payload'); + } + + if (body.object !== 'whatsapp_business_account' || !Array.isArray(body.entry)) { + return sendJson(res, 200, { ok: true, ignored: true }); + } + + for (const entry of body.entry) { + const changes = entry.changes || []; + for (const change of changes) { + const val = change.value; + if (!val) continue; + + // 1. Process delivery and read receipts + if (Array.isArray(val.statuses)) { + for (const s of val.statuses) { + const providerMessageId = s.id; + const status = s.status; // 'sent', 'delivered', 'read', 'failed' + const timestamp = s.timestamp ? new Date(parseInt(s.timestamp, 10) * 1000) : new Date(); + const err = s.errors?.[0]?.message || s.errors?.[0]?.title; + + await updateDeliveryReceipt({ + providerMessageId, + status, + timestamp, + errorMessage: err + }); + } + } + + // 2. Process incoming user messages (keyword opt-outs e.g. STOP) + if (Array.isArray(val.messages)) { + for (const msg of val.messages) { + if (msg.type === 'text') { + const text = (msg.text?.body || '').trim().toUpperCase(); + if (OPT_OUT_KEYWORDS.has(text)) { + const rawFrom = String(msg.from || '').replace(/^\+/, ''); + const normalizedPhone = `+${rawFrom}`; + logger.info('received whatsapp STOP keyword from user', { + sender: normalizedPhone.slice(0, 5) + '****' + }); + await handleOptOutKeyword({ + destination: normalizedPhone, + channel: 'whatsapp', + reason: 'keyword_opt_out' + }); + } + } + } + } + } + } + + return sendJson(res, 200, { ok: true }); +} diff --git a/lib/router.js b/lib/router.js index 8605af1..d91cd32 100644 --- a/lib/router.js +++ b/lib/router.js @@ -70,6 +70,13 @@ const ROUTES = [ ['POST', '/api/auth/telegram', h('auth', 'telegramAuth')], ['POST', '/api/auth/telegram/link-token', h('auth', 'createTelegramLinkToken')], ['GET', '/api/auth/telegram/link-status', h('auth', 'getTelegramLinkStatus')], + ['POST', '/api/auth/whatsapp/otp', h('auth', 'requestWhatsAppOtpHandler')], + ['POST', '/api/auth/whatsapp/verify', h('auth', 'verifyWhatsAppOtpHandler')], + ['POST', '/api/auth/whatsapp/link', h('auth', 'linkWhatsAppHandler')], + ['POST', '/api/auth/whatsapp/unlink', h('auth', 'unlinkWhatsAppHandler')], + ['GET', '/api/me/identities', h('auth', 'getMyIdentitiesHandler')], + ['GET', '/api/me/communication-preferences', h('auth', 'getMyCommunicationPreferences')], + ['PATCH', '/api/me/communication-preferences', h('auth', 'updateMyCommunicationPreferences')], ['POST', '/api/auth/dev', h('auth', 'devAuth')], ['POST', '/api/auth/preview-reviewer', h('auth', 'previewReviewerAuth')], ['POST', '/api/auth/logout', h('auth', 'logout')], @@ -165,7 +172,20 @@ const ROUTES = [ ['POST', '/api/organiser/tickets/:id/revoke', h('organiser', 'revokeTicketHandler')], ['GET', '/api/me/bookings/:id/ticket', h('organiser', 'guestTicket')], + // Event Promotional Campaigns (Opt-in WhatsApp Marketing) + ['POST', '/api/campaigns/preview', h('campaigns', 'previewCampaignHandler')], + ['POST', '/api/campaigns', h('campaigns', 'createCampaignHandler')], + ['GET', '/api/campaigns', h('campaigns', 'listCampaignsHandler')], + ['GET', '/api/campaigns/:id', h('campaigns', 'getCampaignHandler')], + ['POST', '/api/campaigns/:id/approve', h('campaigns', 'approveCampaignHandler')], + ['POST', '/api/campaigns/:id/cancel', h('campaigns', 'cancelCampaignHandler')], + ['POST', '/api/campaigns/:id/dispatch', h('campaigns', 'dispatchCampaignHandler')], + ['GET', '/api/campaigns/:id/logs', h('campaigns', 'getCampaignLogsHandler')], + ['POST', '/api/notifications/unsubscribe', h('campaigns', 'unsubscribeHandler')], + // Webhooks + ['GET', '/api/webhooks/whatsapp', h('whatsapp-webhook', 'verifyWebhook')], + ['POST', '/api/webhooks/whatsapp', h('whatsapp-webhook', 'handleWebhook')], ['POST', '/api/telegram/webhook', h('telegram', 'telegramWebhook')], ['POST', '/api/webhooks/superprofile', h('superprofile', 'superprofileWebhook')], ['POST', '/api/membership/superprofile/webhook', h('superprofile', 'superprofileWebhook')], @@ -207,6 +227,10 @@ const ROUTES = [ ['PATCH', '/api/admin/reports/:id', h('admin', 'updateReport')], ['GET', '/api/admin/notifications', h('admin', 'listNotifications')], ['POST', '/api/admin/notifications/:id/retry', h('admin', 'retryNotification')], + ['GET', '/api/admin/notifications/health', h('admin', 'notificationHealth')], + ['GET', '/api/admin/notifications/stats', h('admin', 'notificationStats')], + ['GET', '/api/admin/notifications/messages', h('admin', 'notificationMessages')], + ['GET', '/api/admin/notifications/suppressions', h('admin', 'notificationSuppressions')], ['GET', '/api/admin/media', h('admin', 'listMedia')], ['POST', '/api/admin/media', h('admin', 'createMedia')], ['PATCH', '/api/admin/media/:id', h('admin', 'updateMedia')], diff --git a/lib/services/communication-consent.js b/lib/services/communication-consent.js new file mode 100644 index 0000000..a2c4efc --- /dev/null +++ b/lib/services/communication-consent.js @@ -0,0 +1,157 @@ +// lib/services/communication-consent.js - Explicit, separate transactional and promotional communication consent management. +import { db } from '../db.js'; +import { audit } from '../audit.js'; +import { normalizePhoneNumber } from './phone.js'; + +export const CHANNELS = ['whatsapp', 'telegram', 'email', 'sms']; +export const PURPOSES = ['transactional', 'promotional']; + +/** + * Record or update communication consent for a user, channel, and purpose. + */ +export async function recordConsent({ + userId, + channel, + purpose, + status, // 'opted_in' | 'opted_out' + source = 'profile_settings', + policyVersion = '1.0', + ip = null, + client = db +}) { + if (!userId) throw new Error('userId is required to record consent'); + if (!CHANNELS.includes(channel)) throw new Error(`Invalid channel: ${channel}`); + if (!PURPOSES.includes(purpose)) throw new Error(`Invalid purpose: ${purpose}`); + if (!['opted_in', 'opted_out'].includes(status)) throw new Error(`Invalid status: ${status}`); + + const now = new Date(); + const { rows } = await client.query( + `INSERT INTO communication_consents (user_id, channel, purpose, status, policy_version, source, ip, consented_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $8) + ON CONFLICT (user_id, channel, purpose) DO UPDATE SET + status = EXCLUDED.status, + policy_version = EXCLUDED.policy_version, + source = EXCLUDED.source, + ip = COALESCE(EXCLUDED.ip, communication_consents.ip), + updated_at = EXCLUDED.updated_at + RETURNING id, user_id, channel, purpose, status, source, consented_at, updated_at`, + [userId, channel, purpose, status, policyVersion, source, ip, now] + ); + + await audit(userId, `consent_${status}`, `user:${userId}`, { + channel, + purpose, + source, + policyVersion + }, client); + + return rows[0]; +} + +/** + * Retrieve current communication consent matrix for a user. + */ +export async function getConsents(userId, client = db) { + const { rows } = await client.query( + `SELECT channel, purpose, status, consented_at, updated_at + FROM communication_consents + WHERE user_id = $1`, + [userId] + ); + + const consents = { + whatsapp: { transactional: true, promotional: false }, + telegram: { transactional: true, promotional: false }, + email: { transactional: true, promotional: false } + }; + + for (const r of rows) { + if (consents[r.channel]) { + consents[r.channel][r.purpose] = (r.status === 'opted_in'); + } + } + + return consents; +} + +/** + * Check if a user has consented to a specific channel and purpose. + * Transactional defaults to true (unless suppressed); promotional requires explicit opt-in. + */ +export async function hasConsent({ userId, channel, purpose = 'transactional', client = db }) { + if (!userId) return false; + + const { rows } = await client.query( + `SELECT status FROM communication_consents + WHERE user_id = $1 AND channel = $2 AND purpose = $3`, + [userId, channel, purpose] + ); + + if (rows.length > 0) { + return rows[0].status === 'opted_in'; + } + + // Defaults: + // Transactional essential notifications: opt-in by default + // Promotional marketing messages: fail-closed false! + return purpose === 'transactional'; +} + +/** + * Add a destination to the suppression list (e.g. STOP request, spam report). + */ +export async function addSuppression({ channel, destination, reason = 'user_opt_out', client = db }) { + let cleanDest = String(destination).trim(); + if (channel === 'whatsapp' || channel === 'sms') { + try { + cleanDest = normalizePhoneNumber(cleanDest); + } catch (_) {} + } + + const { rows } = await client.query( + `INSERT INTO notification_suppressions (channel, destination, reason, created_at) + VALUES ($1, $2, $3, now()) + ON CONFLICT (channel, destination) DO UPDATE SET reason = EXCLUDED.reason + RETURNING id, channel, destination, reason, created_at`, + [channel, cleanDest, reason] + ); + + return rows[0]; +} + +/** + * Remove a destination from the suppression list. + */ +export async function removeSuppression({ channel, destination, client = db }) { + let cleanDest = String(destination).trim(); + if (channel === 'whatsapp' || channel === 'sms') { + try { + cleanDest = normalizePhoneNumber(cleanDest); + } catch (_) {} + } + + const { rowCount } = await client.query( + `DELETE FROM notification_suppressions WHERE channel = $1 AND destination = $2`, + [channel, cleanDest] + ); + return rowCount > 0; +} + +/** + * Check if a destination is currently suppressed. + */ +export async function isSuppressed({ channel, destination, client = db }) { + if (!destination) return false; + let cleanDest = String(destination).trim(); + if (channel === 'whatsapp' || channel === 'sms') { + try { + cleanDest = normalizePhoneNumber(cleanDest); + } catch (_) {} + } + + const { rowCount } = await client.query( + `SELECT 1 FROM notification_suppressions WHERE channel = $1 AND destination = $2`, + [channel, cleanDest] + ); + return rowCount > 0; +} diff --git a/lib/services/notification-dispatcher.js b/lib/services/notification-dispatcher.js new file mode 100644 index 0000000..de071b6 --- /dev/null +++ b/lib/services/notification-dispatcher.js @@ -0,0 +1,363 @@ +// lib/services/notification-dispatcher.js - Multichannel notification dispatcher with queueing, deduplication, cost estimation, and delivery tracking. +import { db } from '../db.js'; +import { logger } from '../logger.js'; +import { getWhatsAppConfig, getWhatsAppProvider } from './whatsapp-provider.js'; +import { maskPhone } from './phone.js'; +import { hasConsent, isSuppressed, addSuppression } from './communication-consent.js'; +import { tg } from '../telegram/api.js'; + +export const ESTIMATED_COST_PAISE = { + auth_otp: 15, // Meta authentication conversation (~₹0.15) + transactional: 15, // Meta utility conversation (~₹0.15) + promotional: 80, // Meta marketing conversation (~₹0.80) + telegram: 0 // Telegram Bot API is free +}; + +/** + * Dispatches a notification via the selected channel with deduplication, + * consent validation, and audit recording in notification_messages. + */ +export async function dispatchNotification({ + notificationId = null, + userId = null, + recipient, + channel = 'whatsapp', + purpose = 'transactional', + templateName = null, + templateComponents = [], + text = null, + idempotencyKey, + metadata = {} +}) { + if (!recipient) { + throw new Error('Recipient is required for dispatch'); + } + if (!idempotencyKey) { + throw new Error('idempotencyKey is required for deduplication'); + } + + // 1. Deduplication check + const existing = (await db.query( + `SELECT * FROM notification_messages WHERE idempotency_key = $1`, + [idempotencyKey] + )).rows[0]; + + if (existing) { + logger.info('notification dispatch skipped (duplicate idempotency key)', { + idempotencyKey, + existingId: existing.id, + status: existing.status + }); + return existing; + } + + // 2. Suppression check + const suppressed = await isSuppressed({ destination: recipient, channel }); + if (suppressed) { + logger.warn('notification dispatch skipped (recipient suppressed)', { + recipient: channel === 'whatsapp' ? maskPhone(recipient) : recipient, + channel, + purpose + }); + const { rows } = await db.query( + `INSERT INTO notification_messages ( + notification_id, user_id, channel, recipient, purpose, template_name, + idempotency_key, status, provider, delivery_cost_paise, metadata + ) VALUES ($1, $2, $3, $4, $5, $6, $7, 'suppressed', 'none', 0, $8) + RETURNING *`, + [notificationId, userId, channel, recipient, purpose, templateName, idempotencyKey, JSON.stringify(metadata)] + ); + return rows[0]; + } + + // 3. Consent check (if userId is available) + if (userId) { + const consented = await hasConsent({ userId, channel, purpose }); + if (!consented) { + logger.warn('notification dispatch skipped (no consent for purpose)', { + userId, + channel, + purpose + }); + const { rows } = await db.query( + `INSERT INTO notification_messages ( + notification_id, user_id, channel, recipient, purpose, template_name, + idempotency_key, status, provider, delivery_cost_paise, last_error, metadata + ) VALUES ($1, $2, $3, $4, $5, $6, $7, 'failed', 'none', 0, 'no_user_consent', $8) + RETURNING *`, + [notificationId, userId, channel, recipient, purpose, templateName, idempotencyKey, JSON.stringify(metadata)] + ); + return rows[0]; + } + } + + const costPaise = channel === 'telegram' ? 0 : (ESTIMATED_COST_PAISE[purpose] || 15); + const providerType = channel === 'whatsapp' + ? (getWhatsAppConfig().isLive && process.env.NODE_ENV !== 'test' ? 'meta_cloud_api' : 'mock') + : 'telegram_bot'; + + // 4. Create pending outbox record + const { rows: inserted } = await db.query( + `INSERT INTO notification_messages ( + notification_id, user_id, channel, recipient, purpose, template_name, + idempotency_key, status, provider, delivery_cost_paise, attempts, metadata + ) VALUES ($1, $2, $3, $4, $5, $6, $7, 'queued', $8, $9, 1, $10) + RETURNING *`, + [notificationId, userId, channel, recipient, purpose, templateName, idempotencyKey, providerType, costPaise, JSON.stringify(metadata)] + ); + const messageRow = inserted[0]; + + // 5. Channel dispatch + try { + if (channel === 'whatsapp') { + const provider = getWhatsAppProvider(); + const sendResult = await provider.sendTemplate({ + to: recipient, + templateName: templateName || 'nightlifez_generic_notice', + language: 'en', + components: templateComponents + }); + + const { rows: updated } = await db.query( + `UPDATE notification_messages + SET status = 'sent', + provider_message_id = $2, + sent_at = now(), + updated_at = now() + WHERE id = $1 + RETURNING *`, + [messageRow.id, sendResult.messageId] + ); + return updated[0]; + } else if (channel === 'telegram') { + const telegramResult = await tg('sendMessage', { + chat_id: recipient, + text: text || metadata.summary || 'Update from NIGHTLIFEZ', + parse_mode: 'HTML', + link_preview_options: { is_disabled: true }, + ...(metadata.buttons ? { reply_markup: { inline_keyboard: metadata.buttons } } : {}) + }); + + const { rows: updated } = await db.query( + `UPDATE notification_messages + SET status = 'sent', + provider_message_id = $2, + sent_at = now(), + updated_at = now() + WHERE id = $1 + RETURNING *`, + [messageRow.id, String(telegramResult?.message_id || '')] + ); + return updated[0]; + } else { + throw new Error(`Unsupported notification channel: ${channel}`); + } + } catch (err) { + const errorMsg = String(err.message || err).slice(0, 500); + logger.error('channel dispatch failed', { + messageId: messageRow.id, + channel, + recipient: channel === 'whatsapp' ? maskPhone(recipient) : recipient, + error: errorMsg + }); + + const { rows: updated } = await db.query( + `UPDATE notification_messages + SET status = 'failed', + last_error = $2, + updated_at = now() + WHERE id = $1 + RETURNING *`, + [messageRow.id, errorMsg] + ); + return updated[0]; + } +} + +/** + * Updates delivery status from webhook receipt. + */ +export async function updateDeliveryReceipt({ + providerMessageId, + status, + timestamp = new Date(), + errorCode = null, + errorMessage = null +}) { + if (!providerMessageId) return null; + + const validStatuses = ['delivered', 'read', 'failed']; + if (!validStatuses.includes(status)) return null; + + const updateDelivered = status === 'delivered' || status === 'read'; + const deliveredSql = updateDelivered ? `, delivered_at = COALESCE(delivered_at, $3)` : ``; + const errorSql = errorMessage ? `, last_error = $4` : ``; + + const query = ` + UPDATE notification_messages + SET status = $2, + updated_at = now() + ${deliveredSql} + ${errorSql} + WHERE provider_message_id = $1 + RETURNING * + `; + + const params = [providerMessageId, status]; + if (updateDelivered) params.push(timestamp); + if (errorMessage) params.push(errorMessage); + + const { rows } = await db.query(query, params); + return rows[0] || null; +} + +/** + * Handles incoming STOP or opt-out keyword from user. + */ +export async function handleOptOutKeyword({ destination, channel = 'whatsapp', reason = 'keyword_opt_out' }) { + await addSuppression({ destination, channel, reason }); + // If destination is a phone or telegram id, find user and withdraw promotional consent + if (channel === 'whatsapp') { + const user = (await db.query(`SELECT id FROM users WHERE phone = $1`, [destination])).rows[0]; + if (user) { + await db.query( + `UPDATE communication_consents + SET status = 'opted_out', updated_at = now() + WHERE user_id = $1 AND channel = 'whatsapp' AND purpose = 'promotional'`, + [user.id] + ); + } + } + return { ok: true, destination: maskPhone(destination), suppressed: true }; +} + +/** + * Admin telemetry data aggregation. + */ +export async function getNotificationTelemetry() { + const config = getWhatsAppConfig(); + + // 1. OTP statistics + const otpStats = (await db.query(` + SELECT + COUNT(*)::int AS total_challenges, + COUNT(*) FILTER (WHERE consumed_at IS NOT NULL)::int AS verified_challenges, + COUNT(*) FILTER (WHERE attempts_count >= max_attempts)::int AS locked_challenges, + COALESCE(AVG(EXTRACT(EPOCH FROM (consumed_at - created_at))) FILTER (WHERE consumed_at IS NOT NULL), 0)::float AS avg_verify_seconds + FROM otp_challenges + `)).rows[0]; + + const totalChallenges = otpStats.total_challenges || 0; + const verifiedChallenges = otpStats.verified_challenges || 0; + const verificationRate = totalChallenges > 0 ? Math.round((verifiedChallenges / totalChallenges) * 100) : 0; + + // 2. Messages breakdown + const messageStats = (await db.query(` + SELECT + channel, + status, + purpose, + COUNT(*)::int AS count, + COALESCE(SUM(delivery_cost_paise), 0)::int AS total_cost_paise + FROM notification_messages + GROUP BY channel, status, purpose + `)).rows; + + const totalSpendPaise = messageStats.reduce((sum, r) => sum + (r.total_cost_paise || 0), 0); + + // 3. Suppressions count + const suppressionCount = (await db.query(`SELECT COUNT(*)::int AS count FROM notification_suppressions`)).rows[0]?.count || 0; + + return { + whatsapp: { + enabled: config.enabled, + isConfigured: config.isConfigured, + isLive: config.isLive, + mode: config.isLive ? 'live_meta_cloud_api' : 'safe_mock_adapter', + phoneNumberId: config.phoneNumberId ? `${config.phoneNumberId.slice(0, 4)}****` : 'Not Set', + businessAccountId: config.businessAccountId ? `${config.businessAccountId.slice(0, 4)}****` : 'Not Set', + apiVersion: config.apiVersion, + otpTemplateName: config.otpTemplateName, + otpTemplateLanguage: config.otpTemplateLanguage + }, + otp: { + totalChallenges, + verifiedChallenges, + lockedChallenges: otpStats.locked_challenges || 0, + verificationRatePercent: verificationRate, + avgVerifySeconds: Math.round(otpStats.avgVerifySeconds || 0) + }, + messages: { + totalSpendPaise, + totalSpendRupees: (totalSpendPaise / 100).toFixed(2), + breakdown: messageStats + }, + suppressions: { + total: suppressionCount + } + }; +} + +/** + * Returns paginated message log with PII masking for admin inspection. + */ +export async function getNotificationMessagesList({ limit = 50, offset = 0, channel = null, status = null } = {}) { + let whereClauses = []; + let params = []; + let idx = 1; + + if (channel) { + whereClauses.push(`channel = $${idx++}`); + params.push(channel); + } + if (status) { + whereClauses.push(`status = $${idx++}`); + params.push(status); + } + + const whereStr = whereClauses.length > 0 ? `WHERE ${whereClauses.join(' AND ')}` : ''; + + params.push(limit); + const limitIdx = idx++; + params.push(offset); + const offsetIdx = idx++; + + const query = ` + SELECT id, notification_id, user_id, channel, recipient, purpose, template_name, + status, provider, provider_message_id, delivery_cost_paise, attempts, last_error, + sent_at, delivered_at, created_at + FROM notification_messages + ${whereStr} + ORDER BY created_at DESC + LIMIT $${limitIdx} OFFSET $${offsetIdx} + `; + + const { rows } = await db.query(query, params); + + return rows.map((r) => ({ + ...r, + recipientMasked: r.channel === 'whatsapp' || r.recipient.startsWith('+') + ? maskPhone(r.recipient) + : (r.recipient.length > 6 ? `${r.recipient.slice(0, 3)}****` : r.recipient) + })); +} + +/** + * Returns suppressions list with masked destinations. + */ +export async function getSuppressionsList({ limit = 50, offset = 0 } = {}) { + const { rows } = await db.query( + `SELECT id, channel, destination, reason, created_at + FROM notification_suppressions + ORDER BY created_at DESC + LIMIT $1 OFFSET $2`, + [limit, offset] + ); + + return rows.map((r) => ({ + ...r, + destinationMasked: r.channel === 'whatsapp' || r.destination.startsWith('+') + ? maskPhone(r.destination) + : (r.destination.length > 6 ? `${r.destination.slice(0, 3)}****` : r.destination) + })); +} diff --git a/lib/services/otp.js b/lib/services/otp.js new file mode 100644 index 0000000..259efe9 --- /dev/null +++ b/lib/services/otp.js @@ -0,0 +1,205 @@ +// lib/services/otp.js - Cryptographically secure OTP generation, hashing, and transactional verification. +import crypto from 'node:crypto'; +import { db } from '../db.js'; +import { HttpError, safeEqual, hashIp } from '../http.js'; +import { rateLimit } from '../ratelimit.js'; +import { hashPhone } from './phone.js'; +import { logger } from '../logger.js'; + +export const OTP_EXPIRY_MS = 5 * 60 * 1000; // 5 minutes +export const RESEND_COOLDOWN_MS = 60 * 1000; // 60 seconds +export const MAX_VERIFY_ATTEMPTS = 5; + +/** + * Generate a cryptographically secure 6-digit random string (100000 - 999999). + */ +export function generateOtpCode() { + return crypto.randomInt(100000, 1000000).toString(); +} + +/** + * Hash an OTP using HMAC-SHA256 with a per-challenge cryptographic salt. + */ +export function hashOtpCode(otp, salt) { + return crypto.createHmac('sha256', salt).update(String(otp).trim()).digest('hex'); +} + +/** + * Create a new OTP challenge in the database. + * Enforces resend cooldown and rate limits. + */ +export async function createOtpChallenge({ + phone, + ip = '127.0.0.1', + userAgent = '', + purpose = 'login', + userId = null, + client = db +}) { + // Rate limits: + // IP limit: Max 10 requests per 10 minutes + await rateLimit(`otp:req:ip:${hashIp(ip)}`, 10, 600); + // Phone limit: Max 5 requests per 10 minutes + await rateLimit(`otp:req:phone:${hashPhone(phone)}`, 5, 600); + + // Check active challenge for cooldown + const { rows: activeChallenges } = await client.query( + `SELECT id, resend_after, expires_at + FROM otp_challenges + WHERE phone = $1 AND consumed_at IS NULL AND expires_at > now() + ORDER BY created_at DESC + LIMIT 1`, + [phone] + ); + + const now = new Date(); + if (activeChallenges.length > 0) { + const active = activeChallenges[0]; + const resendAfter = new Date(active.resend_after); + if (resendAfter > now) { + const waitSeconds = Math.ceil((resendAfter.getTime() - now.getTime()) / 1000); + const err = new HttpError(429, 'cooldown', `Please wait ${waitSeconds} seconds before requesting another code.`, { + retryAfter: waitSeconds + }); + err.retryAfter = waitSeconds; + throw err; + } + } + + const otp = generateOtpCode(); + const salt = crypto.randomBytes(16).toString('hex'); + const otpHash = hashOtpCode(otp, salt); + const expiresAt = new Date(now.getTime() + OTP_EXPIRY_MS); + const resendAfter = new Date(now.getTime() + RESEND_COOLDOWN_MS); + + const { rows } = await client.query( + `INSERT INTO otp_challenges (phone, otp_hash, salt, purpose, user_id, expires_at, resend_after, ip, user_agent, created_at, updated_at) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $10) + RETURNING id, phone, expires_at, resend_after`, + [phone, otpHash, salt, purpose, userId, expiresAt, resendAfter, ip, userAgent.slice(0, 255), now] + ); + + logger.info('otp challenge created', { + challengeId: rows[0].id, + purpose, + phoneHash: hashPhone(phone) + }); + + return { + challengeId: rows[0].id, + otp, // Delivered to provider adapter only; never exposed to HTTP response + expiresAt, + resendAfterSeconds: 60 + }; +} + +/** + * Verify an OTP challenge using atomic row locking and constant-time comparison. + */ +export async function verifyOtpChallenge({ + challengeId, + phone, + code, + ip = '127.0.0.1' +}) { + // Verification rate limits + await rateLimit(`otp:ver:ip:${hashIp(ip)}`, 15, 600); + await rateLimit(`otp:ver:phone:${hashPhone(phone)}`, 10, 600); + + if (!code || typeof code !== 'string' || !/^\d{6}$/.test(code.trim())) { + throw new HttpError(400, 'invalid_otp', 'Please enter a valid 6-digit code.'); + } + + const result = await db.tx(async (c) => { + // Atomically lock challenge row + const { rows } = await c.query( + `SELECT id, phone, otp_hash, salt, purpose, user_id, expires_at, consumed_at, attempts_count, max_attempts + FROM otp_challenges + WHERE id = $1 FOR UPDATE`, + [challengeId] + ); + + if (!rows.length || rows[0].phone !== phone) { + // Generic failure message to prevent enumeration + return { status: 'invalid', message: 'The code you entered is invalid or has expired.' }; + } + + const challenge = rows[0]; + + // Check single-use + if (challenge.consumed_at) { + return { status: 'consumed', message: 'This code has already been used. Please request a new one.' }; + } + + // Check expiry + if (new Date(challenge.expires_at) < new Date()) { + return { status: 'expired', message: 'This code has expired. Please request a new one.' }; + } + + // Check max attempts + if (challenge.attempts_count >= challenge.max_attempts) { + return { status: 'locked', message: 'Too many incorrect attempts. Please request a new code.' }; + } + + // Constant-time hash verification + const candidateHash = hashOtpCode(code.trim(), challenge.salt); + const isMatch = safeEqual(candidateHash, challenge.otp_hash); + + if (!isMatch) { + const nextAttempts = challenge.attempts_count + 1; + await c.query( + `UPDATE otp_challenges SET attempts_count = $1, updated_at = now() WHERE id = $2`, + [nextAttempts, challenge.id] + ); + + const remaining = challenge.max_attempts - nextAttempts; + return { + status: remaining <= 0 ? 'locked' : 'mismatch', + remaining, + message: remaining <= 0 + ? 'Too many incorrect attempts. Please request a new code.' + : `Invalid code. ${remaining} attempt${remaining === 1 ? '' : 's'} remaining.` + }; + } + + // Consume challenge + await c.query( + `UPDATE otp_challenges SET consumed_at = now(), updated_at = now() WHERE id = $1`, + [challenge.id] + ); + + return { + status: 'ok', + challengeId: challenge.id, + purpose: challenge.purpose, + userId: challenge.user_id, + phone: challenge.phone + }; + }); + + if (result.status === 'ok') { + logger.info('otp challenge verified successfully', { + challengeId: result.challengeId, + purpose: result.purpose, + phoneHash: hashPhone(phone) + }); + return { + ok: true, + challengeId: result.challengeId, + purpose: result.purpose, + userId: result.userId, + phone: result.phone + }; + } + + if (result.status === 'locked') { + throw new HttpError(429, 'too_many_attempts', result.message); + } + if (result.status === 'consumed') { + throw new HttpError(400, 'otp_already_used', result.message); + } + if (result.status === 'expired') { + throw new HttpError(400, 'otp_expired', result.message); + } + throw new HttpError(400, 'invalid_otp', result.message); +} diff --git a/lib/services/outreach-strategy.js b/lib/services/outreach-strategy.js new file mode 100644 index 0000000..5aa1c80 --- /dev/null +++ b/lib/services/outreach-strategy.js @@ -0,0 +1,205 @@ +// lib/services/outreach-strategy.js - Decision engine & governance framework for Personal vs Automated outreach on NIGHTLIFEZ. + +/** + * Valid contact and relationship types. + */ +export const RELATIONSHIP_TYPES = { + COMMUNITY_OWNER: 'community_owner', + INFLUENCER: 'influencer', + EVENT_ORGANISER: 'event_organiser', + BRAND_PARTNER: 'brand_partner', + SPONSOR: 'sponsor', + INBOUND_LEAD: 'inbound_lead', + REGISTERED_USER: 'registered_user', + ATTENDEE: 'attendee', + EXTERNAL_CONTACT: 'external_contact' +}; + +/** + * Valid sources of contacts. + */ +export const CONTACT_SOURCES = { + SIGNUP_OPTIN: 'signup_optin', + ACCOUNT_SETTINGS: 'account_settings', + DIRECT_INQUIRY: 'direct_inquiry', + PARTNER_APPLICATION: 'partner_application', + INSTAGRAM_FOLLOW: 'instagram_follow', + PUBLIC_PROFILE: 'public_profile', + SCRAPED_LIST: 'scraped_list', + PURCHASE_HISTORY: 'purchase_history', + AUTH_OTP: 'auth_otp' +}; + +/** + * Core decision rule evaluating whether a contact is eligible for Personal Outreach, + * Automated Outreach, or must be Excluded (No Outreach). + * + * DECISION RULES: + * 1. Partner or influencer relationship -> PERSONAL OUTREACH. + * 2. Inbound direct inquiry / explicit request -> PERSONAL OUTREACH. + * 3. Existing NIGHTLIFEZ user with verified explicit marketing consent -> AUTOMATED OUTREACH. + * 4. Scraped, social-follow, or inferred consent (e.g. ticket purchase, OTP) -> EXCLUDED (NO OUTREACH). + * 5. No marketing consent -> NO PROMOTIONAL MESSAGE. + * 6. Unclear consent or eligibility -> FAIL-CLOSED EXCLUDE FROM CAMPAIGN. + */ +export function evaluateOutreachDecision({ + name, + relationshipType, + source, + hasExplicitMarketingConsent = false, + isRegisteredUser = false, + requestedInformation = false, + phone = null +} = {}) { + // Prohibited sources: Instagram scraping, third-party lists, unsolicited scraping + const prohibitedSources = [ + CONTACT_SOURCES.INSTAGRAM_FOLLOW, + CONTACT_SOURCES.PUBLIC_PROFILE, + CONTACT_SOURCES.SCRAPED_LIST + ]; + + if (prohibitedSources.includes(source)) { + return { + decision: 'PROHIBITED', + channel: 'none', + eligibleForAutomatedCampaign: false, + eligibleForPersonalOutreach: false, + reason: 'Strict anti-scraping policy: Scraped contacts, social followers, and public profiles are strictly prohibited from all outreach.', + action: 'DROP_CONTACT' + }; + } + + // Fallback checks against inferred consent violations: + // "Never infer consent from an Instagram follow, public profile, phone number, previous ticket purchase or authentication OTP request." + if ( + (source === CONTACT_SOURCES.PURCHASE_HISTORY || source === CONTACT_SOURCES.AUTH_OTP) && + !hasExplicitMarketingConsent + ) { + return { + decision: 'NO_PROMOTIONAL_MESSAGE', + channel: 'none', + eligibleForAutomatedCampaign: false, + eligibleForPersonalOutreach: false, + reason: 'Consent cannot be inferred from previous ticket purchases or authentication OTP requests. Explicit promotional opt-in required.', + action: 'EXCLUDE' + }; + } + + // 1. Partner / Influencer / Community Owner / Inbound Business Inquiries: + // (e.g. Rafiky, community owners, venue owners, brand sponsors, inbound partners) + const personalOutreachTypes = [ + RELATIONSHIP_TYPES.COMMUNITY_OWNER, + RELATIONSHIP_TYPES.INFLUENCER, + RELATIONSHIP_TYPES.EVENT_ORGANISER, + RELATIONSHIP_TYPES.BRAND_PARTNER, + RELATIONSHIP_TYPES.SPONSOR, + RELATIONSHIP_TYPES.INBOUND_LEAD + ]; + + if (personalOutreachTypes.includes(relationshipType) || requestedInformation) { + return { + decision: 'PERSONAL_OUTREACH', + channel: 'manual_direct', + eligibleForAutomatedCampaign: false, // Never put partners into bulk automated broadcasts! + eligibleForPersonalOutreach: true, + reason: 'Partner or influencer relationship (e.g., Rafiky, community owners, sponsors) requires genuine, 1-on-1 personal outreach.', + action: 'MANUAL_PERSONAL_MESSAGE', + governance: { + method: 'Individual 1:1 message (Email, Instagram DM or WhatsApp) written by team member', + rules: [ + 'Must be individually targeted and relevant', + 'Do not scrape follower lists or harvest contact details', + 'Never send unsolicited bulk messages or automated bots', + 'Keep personal partner conversations completely separate from customer campaigns' + ] + } + }; + } + + // 2. Existing NIGHTLIFEZ user with verified marketing consent: + if (isRegisteredUser && hasExplicitMarketingConsent === true) { + return { + decision: 'AUTOMATED_OUTREACH', + channel: 'whatsapp_campaign', + eligibleForAutomatedCampaign: true, + eligibleForPersonalOutreach: false, + reason: 'Existing NIGHTLIFEZ user with verified marketing consent is eligible for automated campaigns.', + action: 'INCLUDE_IN_CAMPAIGN', + governance: { + template: 'nightlifez_promotional_event_v1', + requiresMetaApproval: true, + optOutHandling: 'Mandatory STOP keyword / unsubscribe link support' + } + }; + } + + // 3. No marketing consent: + if (hasExplicitMarketingConsent === false) { + return { + decision: 'NO_PROMOTIONAL_MESSAGE', + channel: 'none', + eligibleForAutomatedCampaign: false, + eligibleForPersonalOutreach: false, + reason: 'User has not granted marketing consent. Promotional messages are strictly forbidden.', + action: 'EXCLUDE' + }; + } + + // 4. Unclear consent or ambiguous eligibility: FAIL-CLOSED + return { + decision: 'UNCLEAR_ELIGIBILITY_EXCLUDE', + channel: 'none', + eligibleForAutomatedCampaign: false, + eligibleForPersonalOutreach: false, + reason: 'Unclear consent or eligibility. Fail-closed invariant excludes contact from the campaign.', + action: 'EXCLUDE' + }; +} + +/** + * Genuine, bespoke personal outreach templates for partners and community leads (e.g. Rafiky). + * NEVER sent via automated bots. Used by founders/organisers for genuine 1:1 engagement. + */ +export const PERSONAL_OUTREACH_GUIDES = { + community_owner: { + recipientType: 'Community Owner / Influencer (e.g. Rafiky)', + objective: 'Co-hosting, cross-promotion, or curated community meetup collaboration', + channel: 'Direct Email, Personal WhatsApp, or Direct Instagram Message', + rules: [ + 'Individually targeted and relevant to the creator community', + 'Reference specific context (e.g. their community events, recent gatherings)', + 'No unsolicited bulk blasts, spam, or automated bot scripts', + 'Provide clear, mutual value proposition' + ], + sampleTemplate: (partnerName = 'Rafiky', eventTitle = 'our upcoming secret mixer') => `Hey ${partnerName}! Hope you're having a great week. I love what you've built with your community in Chennai. We're hosting ${eventTitle} on NIGHTLIFEZ and would love to explore co-hosting or curating an exclusive table for your crew. Happy to share full details if you're open to collaborating!` + }, + venue_brand_partner: { + recipientType: 'Venue Owner / Brand Sponsor', + objective: 'Venue partnership, exclusive booking privileges, or beverage brand sponsorship', + channel: 'Direct Business Email or Scheduled In-Person Meeting', + rules: [ + 'Bespoke commercial proposal', + 'Tailored footfall and guest demographic estimates' + ], + sampleTemplate: (brandName = 'Partner Venue') => `Hi team ${brandName}, we host curated nightlife and social dining experiences across South India. We'd love to discuss hosting our upcoming private guestlist events at your venue on off-peak nights. Would you have 10 minutes for a quick chat this week?` + } +}; + +/** + * Builds a campaign tracking URL with attribution parameters. + */ +export function buildCampaignTrackingUrl({ + baseUrl = 'https://nightlifez.com', + eventSlug, + campaignId, + channel = 'whatsapp', + medium = 'campaign', + refCode = null +}) { + const url = new URL(`/events/${eventSlug}`, baseUrl); + url.searchParams.set('utm_source', channel); + url.searchParams.set('utm_medium', medium); + if (campaignId) url.searchParams.set('utm_campaign', campaignId); + if (refCode) url.searchParams.set('ref', refCode); + return url.toString(); +} diff --git a/lib/services/phone.js b/lib/services/phone.js new file mode 100644 index 0000000..0b696eb --- /dev/null +++ b/lib/services/phone.js @@ -0,0 +1,111 @@ +// lib/services/phone.js - E.164 Phone number normalization, validation, and PII masking. +import crypto from 'node:crypto'; +import { HttpError } from '../http.js'; + +const E164_REGEX = /^\+[1-9]\d{6,14}$/; +const INDIA_MOBILE_REGEX = /^\+91[6-9]\d{9}$/; + +/** + * Normalises an input phone number to standard international E.164 format. + * Defaults to India (+91) if no country prefix is supplied. + * Throws HttpError(400, 'invalid_phone') if format is invalid. + * + * @param {string} input - Raw user input (e.g. "9876543210", "+91 98765-43210", "09876543210") + * @param {string} [defaultCountryCode='+91'] + * @returns {string} E.164 formatted phone number (e.g. "+919876543210") + */ +export function normalizePhoneNumber(input, defaultCountryCode = '+91') { + if (!input || typeof input !== 'string') { + throw new HttpError(400, 'invalid_phone', 'Please provide a valid phone number.'); + } + + // Strip all whitespace, dashes, parentheses, periods + let cleaned = input.trim().replace(/[\s\-\(\)\.]/g, ''); + + // Handle international 00 prefix + if (cleaned.startsWith('00')) { + cleaned = '+' + cleaned.slice(2); + } + + // If leading plus exists + if (cleaned.startsWith('+')) { + if (!E164_REGEX.test(cleaned)) { + throw new HttpError(400, 'invalid_phone', 'Invalid phone number format. Please include country code (e.g. +91 9876543210).'); + } + // Specific validation for India numbers (+91) + if (cleaned.startsWith('+91') && !INDIA_MOBILE_REGEX.test(cleaned)) { + throw new HttpError(400, 'invalid_phone', 'Indian mobile numbers must be 10 digits starting with 6, 7, 8, or 9.'); + } + return cleaned; + } + + // No leading plus: apply default country + const country = defaultCountryCode.startsWith('+') ? defaultCountryCode : '+' + defaultCountryCode; + + if (country === '+91') { + // Strip leading 0 if present (e.g. 09876543210) + if (cleaned.startsWith('0')) { + cleaned = cleaned.slice(1); + } + // If user already typed 91 without plus (e.g. 919876543210) + if (cleaned.length === 12 && cleaned.startsWith('91')) { + cleaned = '+' + cleaned; + if (!INDIA_MOBILE_REGEX.test(cleaned)) { + throw new HttpError(400, 'invalid_phone', 'Indian mobile numbers must be 10 digits starting with 6, 7, 8, or 9.'); + } + return cleaned; + } + // Standard 10-digit Indian mobile number + if (/^[6-9]\d{9}$/.test(cleaned)) { + return '+91' + cleaned; + } + throw new HttpError(400, 'invalid_phone', 'Indian mobile numbers must be 10 digits starting with 6, 7, 8, or 9.'); + } + + // Other country fallback + const candidate = country + cleaned; + if (!E164_REGEX.test(candidate)) { + throw new HttpError(400, 'invalid_phone', 'Invalid phone number format. Please check the country code and number.'); + } + return candidate; +} + +/** + * Validates whether a string is a valid E.164 phone number. + */ +export function isValidE164(phone) { + if (!phone || typeof phone !== 'string') return false; + if (!E164_REGEX.test(phone)) return false; + if (phone.startsWith('+91')) { + return INDIA_MOBILE_REGEX.test(phone); + } + return true; +} + +/** + * Mask a phone number for safe display in UI and admin dashboards without exposing full PII. + * Example: "+919876543210" -> "+91 98****3210" + */ +export function maskPhone(phone) { + if (!phone || typeof phone !== 'string') return ''; + const clean = phone.trim(); + if (clean.length < 8) return '****'; + + // For +91: "+91 98****3210" + if (clean.startsWith('+91') && clean.length === 13) { + return `+91 ${clean.slice(3, 5)}****${clean.slice(9)}`; + } + + // General format: keep country prefix + first 2 national digits, mask middle, show last 2 + const plusIdx = clean.indexOf('+'); + const start = clean.slice(0, 4); + const end = clean.slice(-2); + return `${start}****${end}`; +} + +/** + * Hash a phone number with SHA-256 for secure cache/rate-limit keys. + */ +export function hashPhone(phone) { + return crypto.createHash('sha256').update(String(phone).trim()).digest('hex').slice(0, 32); +} diff --git a/lib/services/promotional-campaign.js b/lib/services/promotional-campaign.js new file mode 100644 index 0000000..742cf60 --- /dev/null +++ b/lib/services/promotional-campaign.js @@ -0,0 +1,642 @@ +// lib/services/promotional-campaign.js - Opt-in WhatsApp event marketing campaigns, audience targeting, approval workflows, and delivery logs. +import { db } from '../db.js'; +import { audit } from '../audit.js'; +import { logger } from '../logger.js'; +import { HttpError } from '../http.js'; +import { maskPhone, normalizePhoneNumber } from './phone.js'; +import { dispatchNotification, ESTIMATED_COST_PAISE } from './notification-dispatcher.js'; +import { buildCampaignTrackingUrl } from './outreach-strategy.js'; +import { hasConsent, isSuppressed } from './communication-consent.js'; + +/** + * Returns configurable marketing cost per conversation in paise. + * Configured via WHATSAPP_MARKETING_RATE_PAISE (e.g. 80, 85, 90 paise). + * Defaults to 80 paise. Clearly treated as an estimate in all UI and calculations. + */ +export function getMarketingCostPerRecipientPaise() { + const envRate = Number(process.env.WHATSAPP_MARKETING_RATE_PAISE); + if (!Number.isNaN(envRate) && envRate > 0) { + return Math.round(envRate); + } + return 80; +} + +export const ESTIMATED_MARKETING_COST_PAISE = 80; + +export const OFFICIAL_MARKETING_TEMPLATES = { + nightlifez_promotional_event_v1: { + name: 'nightlifez_promotional_event_v1', + category: 'MARKETING', + language: 'en', + headerText: 'NIGHTLIFEZ EXCLUSIVE', + bodyTemplate: "Hey {{1}}! ✨ You're invited to {{2}} in {{3}}.\n📅 {{4}}\nCurated guestlist & secret venue. Book passes before spots fill up!", + buttons: [ + { type: 'url', text: '🎟️ View Event & Book' }, + { type: 'quick_reply', text: 'Text STOP to opt out' } + ] + } +}; + +/** + * Returns true if live promotional campaign sending is enabled in configuration. + * Gated by ENABLE_LIVE_PROMOTIONAL_CAMPAIGNS environment variable. + */ +export function isLiveCampaignSendingEnabled() { + return process.env.ENABLE_LIVE_PROMOTIONAL_CAMPAIGNS === 'true'; +} + +/** + * Queries eligible, opted-in users for a promotional campaign. + * STRICT PRIVACY INVARIANTS: + * 1. Only users with active status. + * 2. Only users with valid normalized E.164 phone. + * 3. Only users who EXPLICITLY consented to WhatsApp promotional messages (communication_consents.status = 'opted_in'). + * 4. Strictly EXCLUDES any destination present in notification_suppressions. + * 5. Strictly matches voluntary city and interest criteria; never imports social follows or external lists. + */ +export async function queryEligibleAudience({ + targetCity = null, + targetCategory = null, + client = db +} = {}) { + const params = []; + let query = ` + SELECT DISTINCT + u.id, + u.phone, + u.alias, + u.city, + u.interests + FROM users u + INNER JOIN communication_consents cc + ON cc.user_id = u.id + AND cc.channel = 'whatsapp' + AND cc.purpose = 'promotional' + AND cc.status = 'opted_in' + LEFT JOIN notification_suppressions ns + ON ns.channel = 'whatsapp' + AND ns.destination = u.phone + WHERE u.status = 'active' + AND u.phone IS NOT NULL + AND ns.id IS NULL + `; + + if (targetCity && targetCity !== 'all') { + params.push(targetCity.trim()); + const paramIdx = params.length; + query += ` + AND ( + lower(COALESCE(u.city, '')) = lower($${paramIdx}) + OR EXISTS ( + SELECT 1 FROM bookings b + JOIN events e ON e.id = b.event_id + WHERE b.user_id = u.id AND lower(e.city) = lower($${paramIdx}) + ) + ) + `; + } + + if (targetCategory && targetCategory !== 'all') { + params.push(targetCategory.trim()); + const paramIdx = params.length; + query += ` + AND ( + $${paramIdx} = ANY(u.interests) + OR EXISTS ( + SELECT 1 FROM bookings b + JOIN events e ON e.id = b.event_id + WHERE b.user_id = u.id AND lower(e.category::text) = lower($${paramIdx}) + ) + ) + `; + } + + query += ` ORDER BY u.id ASC`; + + const { rows } = await client.query(query, params); + return rows; +} + +/** + * Previews campaign audience, estimated cost, and sample message formatting for an event. + */ +export async function previewCampaignAudience({ + eventId, + targetCity = null, + targetCategory = null, + client = db +}) { + if (!eventId) { + throw new HttpError(400, 'missing_event_id', 'Event ID is required to preview campaign audience'); + } + + const { rows: eventRows } = await client.query( + `SELECT id, title, slug, city, category, start_at FROM events WHERE id = $1`, + [eventId] + ); + if (eventRows.length === 0) { + throw new HttpError(404, 'event_not_found', 'Event not found'); + } + const event = eventRows[0]; + + const cityFilter = targetCity || event.city; + const categoryFilter = targetCategory || event.category; + + const audience = await queryEligibleAudience({ + targetCity: cityFilter, + targetCategory: categoryFilter, + client + }); + + const ratePaise = getMarketingCostPerRecipientPaise(); + const estimatedCostPaise = audience.length * ratePaise; + + const sampleName = audience[0]?.alias || 'Fellow Explorer'; + const eventDateStr = new Date(event.start_at).toLocaleDateString('en-IN', { + weekday: 'short', + month: 'short', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + timeZone: 'Asia/Kolkata' + }); + + return { + ok: true, + eventId: event.id, + eventTitle: event.title, + eventCity: event.city, + eventCategory: event.category, + appliedFilters: { + targetCity: cityFilter, + targetCategory: categoryFilter + }, + eligibleRecipientsCount: audience.length, + estimatedCostPaise, + estimatedCostRupees: (estimatedCostPaise / 100).toFixed(2), + ratePerRecipientPaise: ratePaise, + ratePerRecipientRupees: (ratePaise / 100).toFixed(2), + isEstimate: true, + pricingDisclaimer: 'Estimated rate based on Meta Cloud API marketing conversation pricing for India (subject to Meta rate changes, volume tiers, and applicable taxes).', + sampleRecipientsMasked: audience.slice(0, 5).map((u) => ({ + alias: u.alias || 'Explorer', + phoneMasked: maskPhone(u.phone), + city: u.city || cityFilter || 'South India' + })), + templatePreview: { + templateName: 'nightlifez_promotional_event_v1', + category: 'MARKETING', + header: 'NIGHTLIFEZ EXCLUSIVE', + body: `Hey ${sampleName}! ✨ You're invited to ${event.title} in ${event.city}.\n📅 ${eventDateStr}\nCurated guestlist & secret venue. Book passes before spots fill up!`, + buttons: [ + { + type: 'url', + label: '🎟️ View Event & Book', + url: buildCampaignTrackingUrl({ + eventSlug: event.slug, + channel: 'whatsapp', + medium: 'campaign', + refCode: 'wa_promo' + }) + }, + { type: 'quick_reply', label: 'Text STOP to opt out' } + ] + }, + campaignTrackingUrl: buildCampaignTrackingUrl({ + eventSlug: event.slug, + channel: 'whatsapp', + medium: 'campaign', + refCode: 'wa_promo' + }), + liveSendingEnabled: isLiveCampaignSendingEnabled() + }; +} + +/** + * Creates a new promotional campaign draft. + */ +export async function createCampaign({ + eventId, + createdByUserId, + organiserOrgId = null, + title, + targetCity = null, + targetCategory = null, + templateName = 'nightlifez_promotional_event_v1', + client = db +}) { + if (!eventId) throw new HttpError(400, 'missing_event_id', 'Event ID is required'); + if (!createdByUserId) throw new HttpError(400, 'missing_user_id', 'User ID is required'); + + const { rows: eventRows } = await client.query( + `SELECT id, title, slug, city, category, start_at FROM events WHERE id = $1`, + [eventId] + ); + if (eventRows.length === 0) throw new HttpError(404, 'event_not_found', 'Event not found'); + const event = eventRows[0]; + + const campaignTitle = (title || `Promote: ${event.title}`).trim(); + const cityFilter = targetCity !== undefined ? targetCity : event.city; + const categoryFilter = targetCategory !== undefined ? targetCategory : event.category; + + // Calculate preview metrics + const audience = await queryEligibleAudience({ + targetCity: cityFilter, + targetCategory: categoryFilter, + client + }); + + const costPerRecipientPaise = getMarketingCostPerRecipientPaise(); + const estimatedCostPaise = audience.length * costPerRecipientPaise; + + const templateVariables = { + eventTitle: event.title, + eventCity: event.city, + eventSlug: event.slug, + eventStartAt: event.start_at + }; + + const { rows } = await client.query( + `INSERT INTO promotional_campaigns ( + event_id, created_by_user_id, organiser_org_id, title, template_name, + channel, target_city, target_category, status, estimated_recipients, + estimated_cost_paise, template_variables, live_sending_enabled, audit_metadata + ) VALUES ($1, $2, $3, $4, $5, 'whatsapp', $6, $7, 'draft', $8, $9, $10, $11, $12) + RETURNING *`, + [ + eventId, + createdByUserId, + organiserOrgId, + campaignTitle, + templateName, + cityFilter, + categoryFilter, + audience.length, + estimatedCostPaise, + JSON.stringify(templateVariables), + isLiveCampaignSendingEnabled(), + JSON.stringify({ createdBy: createdByUserId, createdAt: new Date().toISOString() }) + ] + ); + + const campaign = rows[0]; + + await audit(createdByUserId, 'campaign_created', `campaign:${campaign.id}`, { + eventId, + title: campaignTitle, + estimatedRecipients: audience.length, + estimatedCostPaise + }, client); + + return campaign; +} + +/** + * Retrieves a campaign by ID. + */ +export async function getCampaign({ campaignId, client = db }) { + const { rows } = await client.query( + `SELECT c.*, e.title as event_title, e.slug as event_slug, e.city as event_city, e.start_at as event_start_at + FROM promotional_campaigns c + JOIN events e ON e.id = c.event_id + WHERE c.id = $1`, + [campaignId] + ); + if (rows.length === 0) { + throw new HttpError(404, 'campaign_not_found', 'Promotional campaign not found'); + } + return rows[0]; +} + +/** + * Lists campaigns for an event or organisation. + */ +export async function listCampaigns({ + eventId = null, + organiserOrgId = null, + userId = null, + isSuperAdmin = false, + client = db +} = {}) { + const params = []; + let query = ` + SELECT c.*, e.title as event_title, e.slug as event_slug, e.city as event_city, e.start_at as event_start_at + FROM promotional_campaigns c + JOIN events e ON e.id = c.event_id + WHERE 1=1 + `; + + if (eventId) { + params.push(eventId); + query += ` AND c.event_id = $${params.length}`; + } + + if (organiserOrgId && !isSuperAdmin) { + params.push(organiserOrgId); + query += ` AND c.organiser_org_id = $${params.length}`; + } else if (userId && !isSuperAdmin) { + params.push(userId); + query += ` AND c.created_by_user_id = $${params.length}`; + } + + query += ` ORDER BY c.created_at DESC`; + + const { rows } = await client.query(query, params); + return rows; +} + +/** + * Submits or transitions a campaign to approved status. + */ +export async function approveCampaign({ + campaignId, + approvedByUserId, + client = db +}) { + const campaign = await getCampaign({ campaignId, client }); + + if (campaign.status === 'completed' || campaign.status === 'cancelled') { + throw new HttpError(400, 'invalid_state', `Cannot approve campaign in status ${campaign.status}`); + } + + const { rows } = await client.query( + `UPDATE promotional_campaigns + SET status = 'approved', + approved_by_user_id = $2, + approved_at = now(), + updated_at = now() + WHERE id = $1 + RETURNING *`, + [campaignId, approvedByUserId] + ); + + await audit(approvedByUserId, 'campaign_approved', `campaign:${campaignId}`, { + approvedBy: approvedByUserId + }, client); + + return rows[0]; +} + +/** + * Cancels a campaign. + */ +export async function cancelCampaign({ + campaignId, + userId, + client = db +}) { + const campaign = await getCampaign({ campaignId, client }); + + if (campaign.status === 'completed') { + throw new HttpError(400, 'cannot_cancel', 'Cannot cancel an already completed campaign'); + } + + const { rows } = await client.query( + `UPDATE promotional_campaigns + SET status = 'cancelled', + updated_at = now() + WHERE id = $1 + RETURNING *`, + [campaignId] + ); + + await audit(userId, 'campaign_cancelled', `campaign:${campaignId}`, { + cancelledBy: userId + }, client); + + return rows[0]; +} + +/** + * Dispatches or simulates promotional campaign dispatch. + * SAFE DISPATCH INVARIANTS: + * 1. Checks live sending flag (ENABLE_LIVE_PROMOTIONAL_CAMPAIGNS). + * 2. If live sending is false, runs in Safe Simulated Mode: + * - Records recipient delivery log rows in campaign_recipients. + * - Dispatches to notification_messages in mock provider mode. + * - Accurately tracks actual cost in paise. + * - Updates campaign status to completed with simulated: true. + * 3. Never sends real WhatsApp messages without explicit live configuration and approval. + */ +export async function dispatchCampaign({ + campaignId, + triggeredByUserId, + client = db +}) { + // 1. Atomic check-and-set to prevent concurrent dispatch races + const updateRes = await client.query( + `UPDATE promotional_campaigns + SET status = 'sending', updated_at = now() + WHERE id = $1 AND status IN ('draft', 'approved') + RETURNING *`, + [campaignId] + ); + if (updateRes.rows.length === 0) { + const existing = await getCampaign({ campaignId, client }); + throw new HttpError(400, 'invalid_status', `Campaign must be in draft or approved status to dispatch (current: ${existing.status})`); + } + const campaign = updateRes.rows[0]; + + const isLive = isLiveCampaignSendingEnabled(); + const ratePaise = getMarketingCostPerRecipientPaise(); + + const audience = await queryEligibleAudience({ + targetCity: campaign.target_city, + targetCategory: campaign.target_category, + client + }); + + let dispatchedCount = 0; + let failedCount = 0; + let suppressedRaceCount = 0; + let totalCostPaise = 0; + const deliveryLogs = []; + + for (const user of audience) { + // 2. Fresh check against unsubscribe races: verify recipient is not suppressed and still has marketing consent + const isUserSuppressed = await isSuppressed({ destination: user.phone, channel: 'whatsapp', client }); + if (isUserSuppressed) { + suppressedRaceCount++; + continue; + } + const hasMarketingConsent = await hasConsent({ userId: user.id, channel: 'whatsapp', purpose: 'promotional', client }); + if (!hasMarketingConsent) { + suppressedRaceCount++; + continue; + } + + const idempotencyKey = `campaign_${campaignId}_user_${user.id}`; + let recipientStatus = 'dispatched'; + let errorMessage = null; + let notifMessageId = null; + + try { + if (isLive) { + // Live WhatsApp Cloud API dispatch + const result = await dispatchNotification({ + userId: user.id, + recipient: user.phone, + channel: 'whatsapp', + purpose: 'promotional', + templateName: campaign.template_name, + templateComponents: [ + { + type: 'body', + parameters: [ + { type: 'text', text: user.alias || 'Explorer' }, + { type: 'text', text: campaign.event_title }, + { type: 'text', text: campaign.event_city }, + { type: 'text', text: 'Curated guestlist & secret venue.' } + ] + } + ], + idempotencyKey, + metadata: { + campaignId, + eventId: campaign.event_id, + eventSlug: campaign.event_slug + } + }); + notifMessageId = result.id; + recipientStatus = result.status; + } else { + // Safe Simulated Mode: creates outbox entry with mock provider + const result = await dispatchNotification({ + userId: user.id, + recipient: user.phone, + channel: 'whatsapp', + purpose: 'promotional', + templateName: campaign.template_name, + idempotencyKey, + metadata: { + campaignId, + eventId: campaign.event_id, + eventSlug: campaign.event_slug, + simulated: true + } + }); + notifMessageId = result.id; + recipientStatus = 'dispatched'; + } + + dispatchedCount++; + totalCostPaise += ratePaise; + } catch (err) { + failedCount++; + recipientStatus = 'failed'; + errorMessage = err.message || 'Delivery dispatch error'; + logger.error('campaign recipient delivery failed', { + campaignId, + userId: user.id, + error: errorMessage + }); + } + + const recipientCost = recipientStatus === 'failed' ? 0 : ratePaise; + + // Insert campaign recipient delivery log + const { rows: recipientRow } = await client.query( + `INSERT INTO campaign_recipients ( + campaign_id, user_id, recipient_destination, status, + notification_message_id, delivery_cost_paise, error_reason, dispatched_at + ) VALUES ($1, $2, $3, $4, $5, $6, $7, now()) + ON CONFLICT (campaign_id, user_id) DO UPDATE SET + status = EXCLUDED.status, + notification_message_id = EXCLUDED.notification_message_id, + delivery_cost_paise = EXCLUDED.delivery_cost_paise, + error_reason = EXCLUDED.error_reason, + dispatched_at = now() + RETURNING *`, + [ + campaignId, + user.id, + user.phone, + recipientStatus, + notifMessageId, + recipientCost, + errorMessage + ] + ); + + deliveryLogs.push({ + id: recipientRow[0].id, + alias: user.alias || 'Explorer', + phoneMasked: maskPhone(user.phone), + status: recipientStatus, + costPaise: recipientCost, + errorReason: errorMessage + }); + } + + // Update campaign to completed + const auditMeta = { + dispatchedBy: triggeredByUserId, + completedAt: new Date().toISOString(), + simulated: !isLive, + liveSendingGate: isLive ? 'active' : 'disabled_by_policy', + ratePaise, + failedRecipients: failedCount, + suppressedRaceExclusions: suppressedRaceCount + }; + + const { rows: updatedCampaign } = await client.query( + `UPDATE promotional_campaigns + SET status = 'completed', + actual_recipients = $2, + actual_cost_paise = $3, + audit_metadata = $4, + updated_at = now() + WHERE id = $1 + RETURNING *`, + [campaignId, dispatchedCount, totalCostPaise, JSON.stringify(auditMeta)] + ); + + await audit(triggeredByUserId, isLive ? 'campaign_dispatched' : 'campaign_simulated', `campaign:${campaignId}`, { + actualRecipients: dispatchedCount, + actualCostPaise: totalCostPaise, + simulated: !isLive + }, client); + + return { + ok: true, + campaign: updatedCampaign[0], + simulated: !isLive, + recipientsCount: dispatchedCount, + costPaise: totalCostPaise, + costRupees: (totalCostPaise / 100).toFixed(2), + message: isLive + ? `Promotional campaign dispatched to ${dispatchedCount} opted-in WhatsApp recipients.` + : `Promotional campaign simulated successfully for ${dispatchedCount} opted-in recipients. Live dispatch is disabled by platform policy until Meta approval and owner verification.` + }; +} + +/** + * Returns delivery logs for a campaign. + */ +export async function getCampaignLogs({ campaignId, client = db }) { + const { rows } = await client.query( + `SELECT cr.id, cr.status, cr.delivery_cost_paise, cr.error_reason, cr.dispatched_at, + cr.recipient_destination, u.alias, u.city, + nm.provider_message_id, nm.delivered_at, nm.sent_at + FROM campaign_recipients cr + JOIN users u ON u.id = cr.user_id + LEFT JOIN notification_messages nm ON nm.id = cr.notification_message_id + WHERE cr.campaign_id = $1 + ORDER BY cr.dispatched_at DESC`, + [campaignId] + ); + + return rows.map((r) => ({ + id: r.id, + alias: r.alias || 'Explorer', + phoneMasked: maskPhone(r.recipient_destination), + city: r.city || 'South India', + status: r.status, + deliveryCostPaise: r.delivery_cost_paise, + providerMessageId: r.provider_message_id || null, + errorReason: r.error_reason, + dispatchedAt: r.dispatched_at, + deliveredAt: r.delivered_at, + sentAt: r.sent_at + })); +} diff --git a/lib/services/whatsapp-auth.js b/lib/services/whatsapp-auth.js new file mode 100644 index 0000000..4a344e3 --- /dev/null +++ b/lib/services/whatsapp-auth.js @@ -0,0 +1,346 @@ +// lib/services/whatsapp-auth.js - WhatsApp OTP authentication, account creation, and multi-provider linking. +import crypto from 'node:crypto'; +import { db } from '../db.js'; +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 { recordConsent } from './communication-consent.js'; +import { logger } from '../logger.js'; + +/** + * Request an authentication OTP delivered over WhatsApp. + */ +export async function requestWhatsAppOtp({ + phone: rawPhone, + ip = '127.0.0.1', + userAgent = '', + purpose = 'login', + currentUserId = null, + promotionalOptIn = false +}) { + const phone = normalizePhoneNumber(rawPhone); + + // Create OTP challenge in DB (enforces cooldown & rate limits) + const challenge = await createOtpChallenge({ + phone, + ip, + userAgent, + purpose, + userId: currentUserId + }); + + const provider = getWhatsAppProvider(); + let dispatchResult; + try { + dispatchResult = await provider.sendOtpTemplate({ + to: phone, + otp: challenge.otp, + language: 'en' + }); + } catch (err) { + logger.error('failed to dispatch whatsapp otp', { error: err.message, recipient: maskPhone(phone) }); + throw err; + } + + // Record dispatch in notification_messages outbox for audit and cost tracking + const idempotencyKey = `otp:${challenge.challengeId}`; + await db.query( + `INSERT INTO notification_messages ( + user_id, channel, recipient, purpose, template_name, idempotency_key, + status, provider, provider_message_id, delivery_cost_paise, metadata + ) VALUES ($1, 'whatsapp', $2, 'auth_otp', 'nightlifez_auth_otp', $3, 'sent', $4, $5, $6, $7) + ON CONFLICT (idempotency_key) DO NOTHING`, + [ + currentUserId, + phone, + idempotencyKey, + dispatchResult.provider || 'mock', + dispatchResult.messageId || null, + dispatchResult.estimatedCostPaise || 15, + JSON.stringify({ purpose, promotionalOptIn: Boolean(promotionalOptIn) }) + ] + ); + + return { + ok: true, + challengeId: challenge.challengeId, + phoneMasked: maskPhone(phone), + resendAfterSeconds: challenge.resendAfterSeconds, + ...(process.env.DEV_LOGIN === 'true' || process.env.NODE_ENV === 'test' ? { devOtp: challenge.otp } : {}) + }; +} + +/** + * Verify OTP, create or retrieve user account, and handle secure identity linking. + */ +export async function verifyWhatsAppOtpAndResolveUser({ + challengeId, + phone: rawPhone, + code, + ip = '127.0.0.1', + currentUserId = null, + existingUserId = null, + promotionalOptIn = false +}) { + const targetUserId = currentUserId || existingUserId || null; + const phone = normalizePhoneNumber(rawPhone); + + // Transactionally verify OTP (single-use, max attempts, expiry, timing safety) + const verifyResult = await verifyOtpChallenge({ + challengeId, + phone, + code, + ip + }); + + return await db.tx(async (c) => { + // ----------------------------------------------------------------- + // CASE A: User is already signed in (Account Linking Flow) + // ----------------------------------------------------------------- + if (targetUserId) { + // Check if this phone number is already linked to another account + const { rows: conflictRows } = await c.query( + `SELECT u.id, u.alias + FROM users u + LEFT JOIN user_identities ui ON ui.user_id = u.id + WHERE ((ui.provider IN ('phone', 'whatsapp') AND ui.subject = $1) OR u.phone = $1) + AND u.id != $2 + LIMIT 1`, + [phone, targetUserId] + ); + + if (conflictRows.length > 0) { + throw new HttpError( + 409, + 'phone_already_linked', + 'This WhatsApp number is already linked to another NIGHTLIFEZ account. Please sign in with that account or contact support.' + ); + } + + // Link identity to current user + await c.query( + `INSERT INTO user_identities (user_id, provider, subject, verified_at) + VALUES ($1, 'phone', $2, now()) + ON CONFLICT (provider, subject) DO UPDATE SET user_id = EXCLUDED.user_id, verified_at = now()`, + [targetUserId, phone] + ); + + await c.query( + `UPDATE users SET phone = $1, updated_at = now() WHERE id = $2`, + [phone, targetUserId] + ); + + await audit(targetUserId, 'identity_linked', `user:${targetUserId}`, { + provider: 'phone', + subject: maskPhone(phone), + ip + }, c); + + // Record communication consents + await recordConsent({ + userId: targetUserId, + channel: 'whatsapp', + purpose: 'transactional', + status: 'opted_in', + source: 'account_linking', + ip, + client: c + }); + + if (promotionalOptIn) { + await recordConsent({ + userId: targetUserId, + channel: 'whatsapp', + purpose: 'promotional', + status: 'opted_in', + source: 'account_linking', + ip, + client: c + }); + } + + const { rows: updatedUser } = await c.query(`SELECT * FROM users WHERE id = $1`, [targetUserId]); + return { + ok: true, + user: updatedUser[0], + isNewUser: false, + linked: true + }; + } + + // ----------------------------------------------------------------- + // CASE B: User is NOT signed in (Sign-In or Registration Flow) + // ----------------------------------------------------------------- + const { rows: existingUsers } = await c.query( + `SELECT u.* + FROM users u + LEFT JOIN user_identities ui ON ui.user_id = u.id + WHERE (ui.provider IN ('phone', 'whatsapp') AND ui.subject = $1) OR u.phone = $1 + LIMIT 1`, + [phone] + ); + + let user; + let isNewUser = false; + + if (existingUsers.length > 0) { + // Existing user sign-in + user = existingUsers[0]; + if (user.status !== 'active') { + throw new HttpError(403, 'account_restricted', 'This account cannot sign in. Contact support if you think this is a mistake.'); + } + + // Ensure identity row exists + await c.query( + `INSERT INTO user_identities (user_id, provider, subject, verified_at) + VALUES ($1, 'phone', $2, now()) + ON CONFLICT (provider, subject) DO UPDATE SET verified_at = now()`, + [user.id, phone] + ); + + if (!user.phone) { + await c.query(`UPDATE users SET phone = $1, updated_at = now() WHERE id = $2`, [phone, user.id]); + user.phone = phone; + } + + await audit(user.id, 'login_success', `user:${user.id}`, { + provider: 'phone', + subject: maskPhone(phone), + ip + }, c); + } else { + // Create new user + isNewUser = true; + const { rows: newRows } = await c.query( + `INSERT INTO users (phone, age_confirmed_21, age_confirmed_at, status) + VALUES ($1, true, now(), 'active') + RETURNING *`, + [phone] + ); + user = newRows[0]; + + await c.query( + `INSERT INTO user_identities (user_id, provider, subject, verified_at) + VALUES ($1, 'phone', $2, now()) + ON CONFLICT (provider, subject) DO NOTHING`, + [user.id, phone] + ); + + await audit(user.id, 'user_created', `user:${user.id}`, { + provider: 'phone', + subject: maskPhone(phone), + ip + }, c); + } + + // Record essential transactional consent + await recordConsent({ + userId: user.id, + channel: 'whatsapp', + purpose: 'transactional', + status: 'opted_in', + source: isNewUser ? 'registration' : 'signin', + ip, + client: c + }); + + // Record promotional consent if opted in + if (promotionalOptIn) { + await recordConsent({ + userId: user.id, + channel: 'whatsapp', + purpose: 'promotional', + status: 'opted_in', + source: isNewUser ? 'registration' : 'signin', + ip, + client: c + }); + } + + return { + ok: true, + user, + isNewUser, + linked: false + }; + }); +} + +/** + * Safely unlinks a WhatsApp identity from an account. + * Guard: Requires that at least one other verified identity exists (e.g. Telegram). + */ +export async function unlinkWhatsAppIdentity({ userId, phone: rawPhone }) { + const phone = normalizePhoneNumber(rawPhone); + + return await db.tx(async (c) => { + // Check total verified identities + const { rows: identities } = await c.query( + `SELECT provider, subject FROM user_identities WHERE user_id = $1`, + [userId] + ); + + const otherIdentities = identities.filter((i) => !(i.provider === 'phone' && i.subject === phone)); + if (otherIdentities.length === 0) { + throw new HttpError( + 400, + 'cannot_unlink_only_provider', + 'You cannot disconnect your only login method. Please connect Telegram before disconnecting WhatsApp.' + ); + } + + await c.query( + `DELETE FROM user_identities + WHERE user_id = $1 AND provider IN ('phone', 'whatsapp') AND subject = $2`, + [userId, phone] + ); + + await c.query( + `UPDATE users SET phone = NULL, updated_at = now() + WHERE id = $1 AND phone = $2`, + [userId, phone] + ); + + await audit(userId, 'identity_unlinked', `user:${userId}`, { + provider: 'phone', + subject: maskPhone(phone) + }, c); + + return { ok: true }; + }); +} + +/** + * Retrieve user's linked authentication providers. + */ +export async function getLinkedIdentities(userId, client = db) { + const { rows } = await client.query( + `SELECT provider, subject, verified_at, created_at + FROM user_identities + WHERE user_id = $1 + ORDER BY created_at ASC`, + [userId] + ); + + const { rows: userRows } = await client.query(`SELECT telegram_user_id, phone FROM users WHERE id = $1`, [userId]); + const user = userRows[0] || {}; + + const hasTelegram = Boolean(user.telegram_user_id || rows.some((r) => r.provider === 'telegram')); + const phoneRow = rows.find((r) => r.provider === 'phone' || r.provider === 'whatsapp'); + const hasPhone = Boolean(user.phone || phoneRow); + const phoneNumber = user.phone || phoneRow?.subject || null; + + return { + telegram: { + linked: hasTelegram, + telegramUserId: user.telegram_user_id ? String(user.telegram_user_id) : null + }, + whatsapp: { + linked: hasPhone, + phone: phoneNumber, + phoneMasked: phoneNumber ? maskPhone(phoneNumber) : null + } + }; +} diff --git a/lib/services/whatsapp-provider.js b/lib/services/whatsapp-provider.js new file mode 100644 index 0000000..68f37cd --- /dev/null +++ b/lib/services/whatsapp-provider.js @@ -0,0 +1,284 @@ +// lib/services/whatsapp-provider.js - Official Meta WhatsApp Cloud API provider with pluggable adapter. +import crypto from 'node:crypto'; +import { env } from '../config.js'; +import { logger } from '../logger.js'; +import { safeEqual, HttpError } from '../http.js'; +import { maskPhone } from './phone.js'; + +/** + * Returns configuration state of WhatsApp Business Cloud API. + */ +export function getWhatsAppConfig() { + const enabled = process.env.WHATSAPP_ENABLED === 'true'; + const phoneNumberId = env('WHATSAPP_PHONE_NUMBER_ID', ''); + const businessAccountId = env('WHATSAPP_BUSINESS_ACCOUNT_ID', ''); + const accessToken = env('WHATSAPP_ACCESS_TOKEN', ''); + const apiVersion = env('WHATSAPP_API_VERSION', 'v21.0'); + const otpTemplateName = env('WHATSAPP_OTP_TEMPLATE_NAME', 'nightlifez_auth_otp'); + const otpTemplateLanguage = env('WHATSAPP_OTP_TEMPLATE_LANGUAGE', 'en'); + const webhookSecret = env('WHATSAPP_WEBHOOK_SECRET', ''); + const webhookVerifyToken = env('WHATSAPP_WEBHOOK_VERIFY_TOKEN', ''); + + const isConfigured = Boolean(phoneNumberId && accessToken); + const isLive = enabled && isConfigured; + + return { + enabled, + isConfigured, + isLive, + phoneNumberId, + businessAccountId, + accessToken, + apiVersion, + otpTemplateName, + otpTemplateLanguage, + webhookSecret, + webhookVerifyToken + }; +} + +/** + * Base Provider Interface. + */ +export class WhatsAppProviderInterface { + async sendOtpTemplate({ to, otp, language }) { + throw new Error('sendOtpTemplate not implemented'); + } + + async sendTemplate({ to, templateName, language, components }) { + throw new Error('sendTemplate not implemented'); + } + + verifyWebhookSignature({ rawBody, signatureHeader }) { + throw new Error('verifyWebhookSignature not implemented'); + } +} + +/** + * Meta WhatsApp Business Platform Cloud API implementation. + */ +export class MetaCloudWhatsAppProvider extends WhatsAppProviderInterface { + constructor(config = getWhatsAppConfig()) { + super(); + this.config = config; + this.baseUrl = `https://graph.facebook.com/${config.apiVersion}/${config.phoneNumberId}/messages`; + } + + async sendOtpTemplate({ to, otp, language }) { + const lang = language || this.config.otpTemplateLanguage || 'en'; + const templateName = this.config.otpTemplateName; + const recipientDigits = to.replace(/^\+/, ''); + + const payload = { + messaging_product: 'whatsapp', + recipient_type: 'individual', + to: recipientDigits, + type: 'template', + template: { + name: templateName, + language: { code: lang }, + components: [ + { + type: 'body', + parameters: [ + { type: 'text', text: String(otp) } + ] + }, + { + type: 'button', + sub_type: 'url', + index: '0', + parameters: [ + { type: 'text', text: String(otp) } + ] + } + ] + } + }; + + logger.info('dispatching whatsapp otp via meta cloud api', { + recipient: maskPhone(to), + template: templateName, + lang + }); + + const response = await fetch(this.baseUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.config.accessToken}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify(payload) + }); + + const data = await response.json().catch(() => ({})); + + if (!response.ok) { + const errorMsg = data?.error?.message || `Meta Cloud API responded with status ${response.status}`; + logger.error('meta whatsapp cloud api delivery error', { + status: response.status, + error: errorMsg, + recipient: maskPhone(to) + }); + throw new HttpError(502, 'whatsapp_delivery_failed', 'Failed to deliver WhatsApp message. Please try again or use Telegram.'); + } + + const messageId = data?.messages?.[0]?.id || `wamid.${crypto.randomBytes(12).toString('hex')}`; + return { + ok: true, + messageId, + provider: 'meta_cloud_api', + status: 'sent', + estimatedCostPaise: 15 // Meta authentication conversation pricing (~0.15 INR) + }; + } + + async sendTemplate({ to, templateName, language = 'en', components = [] }) { + const recipientDigits = to.replace(/^\+/, ''); + const payload = { + messaging_product: 'whatsapp', + recipient_type: 'individual', + to: recipientDigits, + type: 'template', + template: { + name: templateName, + language: { code: language }, + components + } + }; + + const response = await fetch(this.baseUrl, { + method: 'POST', + headers: { + 'Authorization': `Bearer ${this.config.accessToken}`, + 'Content-Type': 'application/json' + }, + body: JSON.stringify(payload) + }); + + const data = await response.json().catch(() => ({})); + if (!response.ok) { + throw new HttpError(502, 'whatsapp_delivery_failed', data?.error?.message || 'Meta Cloud API error'); + } + + return { + ok: true, + messageId: data?.messages?.[0]?.id, + provider: 'meta_cloud_api', + status: 'sent' + }; + } + + verifyWebhookSignature({ rawBody, signatureHeader }) { + if (!this.config.webhookSecret) return false; + if (!signatureHeader || !signatureHeader.startsWith('sha256=')) return false; + + const signature = signatureHeader.slice(7); + const expected = crypto + .createHmac('sha256', this.config.webhookSecret) + .update(rawBody) + .digest('hex'); + + return safeEqual(signature, expected); + } +} + +/** + * Safe Development & Test Adapter. + * Does NOT send real messages. Captures dispatches in memory for testing. + */ +export class StubWhatsAppProvider extends WhatsAppProviderInterface { + constructor() { + super(); + this.sentMessages = []; + } + + async sendOtpTemplate({ to, otp, language = 'en' }) { + const messageId = `wamid.mock_${crypto.randomBytes(10).toString('hex')}`; + const record = { + to, + otp, + language, + messageId, + provider: 'mock', + sentAt: new Date().toISOString() + }; + this.sentMessages.push(record); + + logger.info('stub whatsapp otp dispatched (safe dev/test mode)', { + recipient: maskPhone(to), + messageId + }); + + return { + ok: true, + messageId, + provider: 'mock', + status: 'sent', + estimatedCostPaise: 15 + }; + } + + async sendTemplate({ to, templateName, language = 'en', components = [] }) { + const messageId = `wamid.mock_${crypto.randomBytes(10).toString('hex')}`; + this.sentMessages.push({ + to, + templateName, + language, + components, + messageId, + provider: 'mock', + sentAt: new Date().toISOString() + }); + return { + ok: true, + messageId, + provider: 'mock', + status: 'sent', + estimatedCostPaise: 12 + }; + } + + verifyWebhookSignature({ rawBody, signatureHeader }) { + const secret = env('WHATSAPP_WEBHOOK_SECRET', 'test_whatsapp_webhook_secret'); + if (!signatureHeader || !signatureHeader.startsWith('sha256=')) return false; + const signature = signatureHeader.slice(7); + const expected = crypto.createHmac('sha256', secret).update(rawBody).digest('hex'); + return safeEqual(signature, expected); + } + + getSentMessages() { + return [...this.sentMessages]; + } + + clearSentMessages() { + this.sentMessages = []; + } +} + +// Global active provider +let activeProvider = null; +let defaultStub = null; + +export function getWhatsAppProvider() { + if (activeProvider) return activeProvider; + const cfg = getWhatsAppConfig(); + if (cfg.isLive && process.env.NODE_ENV !== 'test') { + return new MetaCloudWhatsAppProvider(cfg); + } + if (!defaultStub) { + defaultStub = new StubWhatsAppProvider(); + } + return defaultStub; +} + +export function setWhatsAppProvider(provider) { + activeProvider = provider; +} + +export function resetWhatsAppProvider() { + activeProvider = null; + if (defaultStub) { + defaultStub.clearSentMessages(); + } +} diff --git a/lib/views/pages.js b/lib/views/pages.js index 196772c..24c0d6a 100644 --- a/lib/views/pages.js +++ b/lib/views/pages.js @@ -474,54 +474,124 @@ function devPersonaPicker() { export function renderSignin({ next = '/me', error = '', 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 method; + let tgMethod; if (oidc) { - method = html`
+ tgMethod = html` - +
`; } else if (bot) { - method = html`
+ tgMethod = html`
`; } else { - method = html`
+ tgMethod = html``; } - const body = html`${pageHeader('Members', 'Continue with Telegram', 'Sign in to book tickets and manage your bookings. We never see your phone number.')} + + const body = html`${pageHeader('Sign In', 'Continue to NIGHTLIFEZ', 'Sign in with WhatsApp or Telegram to book passes, view secret venues, and connect with organisers.')}
${error && SIGNIN_ERRORS[error] ? html`

${SIGNIN_ERRORS[error]}

` : ''} - ${method} - ${bot ? html`

Using Telegram on your phone? Open our bot and tap “Open NIGHTLIFEZ”.

` : ''} -
`; - return layout({ title: 'Continue with Telegram', description: 'Sign in to NIGHTLIFEZ with Telegram.', path: '/signin', body, noindex: true }); + return layout({ title: 'Sign In', description: 'Sign in to NIGHTLIFEZ with WhatsApp or Telegram.', path: '/signin', body, noindex: true }); } export function renderMe() { @@ -531,6 +601,7 @@ export function renderMe() { +
@@ -550,6 +621,10 @@ export function renderMe() {

Loading host announcements…

+ +

diff --git a/migrations/023_whatsapp_auth_and_notifications.sql b/migrations/023_whatsapp_auth_and_notifications.sql new file mode 100644 index 0000000..5cbb936 --- /dev/null +++ b/migrations/023_whatsapp_auth_and_notifications.sql @@ -0,0 +1,96 @@ +-- migrations/023_whatsapp_auth_and_notifications.sql +-- WhatsApp OTP authentication, multi-channel notification outbox, communication consents, and suppression lists. +-- Additive only. Idempotent and safe for re-runs. + +-- 1. Extend identity_provider enum to include 'whatsapp' +DO $$ BEGIN + ALTER TYPE identity_provider ADD VALUE IF NOT EXISTS 'whatsapp'; +EXCEPTION WHEN duplicate_object THEN NULL; END $$; + +-- 2. Allow users table to support phone-first and whatsapp-first accounts +-- telegram_user_id was NOT NULL in 003; dropping NOT NULL allows WhatsApp-only signups before linking Telegram. +ALTER TABLE users ALTER COLUMN telegram_user_id DROP NOT NULL; + +-- Add phone column for normalized E.164 phone numbers +ALTER TABLE users ADD COLUMN IF NOT EXISTS phone TEXT UNIQUE; + +-- 3. OTP Challenges table for server-side OTP generation, hashing, and verification +CREATE TABLE IF NOT EXISTS otp_challenges ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + phone TEXT NOT NULL, + otp_hash TEXT NOT NULL, + salt TEXT NOT NULL, + purpose TEXT NOT NULL DEFAULT 'login', -- 'login', 'link', 'recovery' + user_id UUID REFERENCES users(id) ON DELETE SET NULL, + expires_at TIMESTAMPTZ NOT NULL, + consumed_at TIMESTAMPTZ, + attempts_count INT NOT NULL DEFAULT 0, + max_attempts INT NOT NULL DEFAULT 5, + resend_after TIMESTAMPTZ NOT NULL, + ip TEXT NOT NULL, + user_agent TEXT, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_otp_challenges_phone_created ON otp_challenges (phone, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_otp_challenges_ip_created ON otp_challenges (ip, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_otp_challenges_unconsumed ON otp_challenges (phone, expires_at) WHERE consumed_at IS NULL; + +-- 4. Communication Consents table for independent transactional vs promotional consent +CREATE TABLE IF NOT EXISTS communication_consents ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + channel TEXT NOT NULL, -- 'whatsapp', 'telegram', 'email', 'sms' + purpose TEXT NOT NULL, -- 'transactional', 'promotional' + status TEXT NOT NULL, -- 'opted_in', 'opted_out' + policy_version TEXT NOT NULL DEFAULT '1.0', + source TEXT NOT NULL, -- 'signin_form', 'profile_settings', 'opt_out_link', 'webhook' + ip TEXT, + consented_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (user_id, channel, purpose) +); + +CREATE INDEX IF NOT EXISTS idx_communication_consents_user ON communication_consents (user_id); +CREATE INDEX IF NOT EXISTS idx_communication_consents_lookup ON communication_consents (user_id, channel, purpose, status); + +-- 5. Notification Suppressions list (e.g. STOP requests, hard bounces, complaints) +CREATE TABLE IF NOT EXISTS notification_suppressions ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + channel TEXT NOT NULL, -- 'whatsapp', 'telegram', 'email', 'sms' + destination TEXT NOT NULL, -- normalized phone E.164, telegram user id, or email + reason TEXT NOT NULL, -- 'user_opt_out', 'bounce', 'complaint', 'admin_suppressed' + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (channel, destination) +); + +CREATE INDEX IF NOT EXISTS idx_notification_suppressions_dest ON notification_suppressions (channel, destination); + +-- 6. Notification Messages dispatch log for multi-channel delivery, retries, and cost tracking +CREATE TABLE IF NOT EXISTS notification_messages ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + notification_id UUID REFERENCES notifications(id) ON DELETE SET NULL, + user_id UUID REFERENCES users(id) ON DELETE SET NULL, + channel TEXT NOT NULL, -- 'whatsapp', 'telegram', 'email', 'sms' + recipient TEXT NOT NULL, -- phone (E.164), telegram_id, email + purpose TEXT NOT NULL DEFAULT 'transactional', -- 'auth_otp', 'transactional', 'promotional' + template_name TEXT, + idempotency_key TEXT UNIQUE NOT NULL, + status TEXT NOT NULL DEFAULT 'queued', -- 'queued', 'sent', 'delivered', 'read', 'failed', 'suppressed' + provider TEXT NOT NULL, -- 'meta_cloud_api', 'telegram_bot', 'mock' + provider_message_id TEXT, -- e.g. wamid.HBg... + delivery_cost_paise INT NOT NULL DEFAULT 0, + currency TEXT NOT NULL DEFAULT 'INR', + attempts INT NOT NULL DEFAULT 0, + last_error TEXT, + metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + sent_at TIMESTAMPTZ, + delivered_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_notification_messages_user ON notification_messages (user_id, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_notification_messages_status ON notification_messages (status, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_notification_messages_wamid ON notification_messages (provider_message_id) WHERE provider_message_id IS NOT NULL; diff --git a/migrations/024_event_promotional_campaigns.sql b/migrations/024_event_promotional_campaigns.sql new file mode 100644 index 0000000..944ba2c --- /dev/null +++ b/migrations/024_event_promotional_campaigns.sql @@ -0,0 +1,52 @@ +-- migrations/024_event_promotional_campaigns.sql +-- Opt-in event promotion campaigns, audience filtering, approval workflows, and delivery logs. +-- Strictly additive and idempotent. + +-- 1. Promotional Campaigns table +CREATE TABLE IF NOT EXISTS promotional_campaigns ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + event_id UUID NOT NULL REFERENCES events(id) ON DELETE CASCADE, + created_by_user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + organiser_org_id UUID REFERENCES organisations(id) ON DELETE SET NULL, + title TEXT NOT NULL, + template_name TEXT NOT NULL DEFAULT 'nightlifez_promotional_event_v1', + channel TEXT NOT NULL DEFAULT 'whatsapp', + target_city TEXT, -- null means all South Indian cities + target_category TEXT, -- null means all event categories + status TEXT NOT NULL DEFAULT 'draft', -- 'draft', 'pending_approval', 'approved', 'sending', 'completed', 'cancelled', 'rejected' + approved_by_user_id UUID REFERENCES users(id) ON DELETE SET NULL, + approved_at TIMESTAMPTZ, + estimated_recipients INT NOT NULL DEFAULT 0, + actual_recipients INT NOT NULL DEFAULT 0, + estimated_cost_paise INT NOT NULL DEFAULT 0, + actual_cost_paise INT NOT NULL DEFAULT 0, + template_variables JSONB NOT NULL DEFAULT '{}'::jsonb, + live_sending_enabled BOOLEAN NOT NULL DEFAULT false, + audit_metadata JSONB NOT NULL DEFAULT '{}'::jsonb, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS idx_promotional_campaigns_event ON promotional_campaigns (event_id); +CREATE INDEX IF NOT EXISTS idx_promotional_campaigns_org ON promotional_campaigns (organiser_org_id); +CREATE INDEX IF NOT EXISTS idx_promotional_campaigns_status ON promotional_campaigns (status); +CREATE INDEX IF NOT EXISTS idx_promotional_campaigns_created ON promotional_campaigns (created_at DESC); + +-- 2. Campaign Recipients & Delivery Log table +CREATE TABLE IF NOT EXISTS campaign_recipients ( + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + campaign_id UUID NOT NULL REFERENCES promotional_campaigns(id) ON DELETE CASCADE, + user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE, + recipient_destination TEXT NOT NULL, -- normalized phone number + status TEXT NOT NULL DEFAULT 'pending', -- 'pending', 'dispatched', 'delivered', 'read', 'skipped_suppressed', 'skipped_no_consent', 'failed' + notification_message_id UUID REFERENCES notification_messages(id) ON DELETE SET NULL, + delivery_cost_paise INT NOT NULL DEFAULT 80, + error_reason TEXT, + dispatched_at TIMESTAMPTZ, + created_at TIMESTAMPTZ NOT NULL DEFAULT now(), + UNIQUE (campaign_id, user_id) +); + +CREATE INDEX IF NOT EXISTS idx_campaign_recipients_campaign ON campaign_recipients (campaign_id); +CREATE INDEX IF NOT EXISTS idx_campaign_recipients_user ON campaign_recipients (user_id); +CREATE INDEX IF NOT EXISTS idx_campaign_recipients_status ON campaign_recipients (status); diff --git a/public/css/site.css b/public/css/site.css index c87811e..fe5137f 100644 --- a/public/css/site.css +++ b/public/css/site.css @@ -64,6 +64,9 @@ p { margin: 0 0 1em; } .btn-tg { background: #006cb4; color: #fff; border-color: #0088cc; } .btn-tg::before { content: ""; width: 18px; height: 18px; background: currentColor; -webkit-mask: url("/img/telegram.svg") center/contain no-repeat; mask: url("/img/telegram.svg") center/contain no-repeat; } .btn-tg:hover { background: #005a9e; color: #fff; box-shadow: 0 0 16px rgba(0, 217, 255, 0.35); } +.btn-wa { background: #25D366; color: #072a14; font-weight: 700; border-color: #20bd5a; } +.btn-wa::before { content: ""; width: 18px; height: 18px; background: currentColor; -webkit-mask: url("/img/whatsapp.svg") center/contain no-repeat; mask: url("/img/whatsapp.svg") center/contain no-repeat; } +.btn-wa:hover { background: #20bd5a; color: #072a14; box-shadow: 0 0 16px rgba(37, 211, 102, 0.4); } .btn-ghost { background: transparent; color: var(--ink-2); border-color: var(--line); } .btn-ghost:hover { border-color: var(--ink-2); color: #fff; background: rgba(255, 255, 255, 0.05); } .btn-sm { min-height: 36px; padding: 6px 14px; font-size: .85rem; } @@ -343,6 +346,54 @@ select:focus, input:focus, textarea:focus { outline: 2px solid var(--accent); ou .field-error input, .field-error textarea { border-color: var(--accent); } .notice { background: var(--alt); border: 1px solid var(--line); padding: 12px 16px; border-radius: var(--radius-sm); } .signin { display: grid; gap: 20px; } +.auth-switcher { display: flex; gap: 8px; background: var(--surface-2); padding: 4px; border-radius: 999px; border: 1px solid var(--line); margin-bottom: 8px; } +.auth-tab-btn { flex: 1; padding: 10px 16px; border: none; background: transparent; color: var(--muted); font: inherit; font-weight: 600; font-size: .92rem; border-radius: 999px; cursor: pointer; transition: all .2s; text-align: center; } +.auth-tab-btn.active { background: var(--accent); color: #fff; box-shadow: 0 2px 8px rgba(49, 91, 255, 0.3); } +.auth-tab-btn.active.wa-tab { background: #25D366; color: #072a14; font-weight: 700; box-shadow: 0 2px 8px rgba(37, 211, 102, 0.3); } + +.wa-auth-card { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 24px; display: grid; gap: 16px; } +.phone-field-group { display: flex; gap: 8px; align-items: stretch; } +.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; } + +.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 { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + font-size: 1.35rem; + letter-spacing: 0.38em; + min-height: 52px; + padding: 0.5rem 0.75rem; + box-sizing: border-box; + text-align: center; + background: var(--surface-2); + border: 1px solid var(--line-light); + border-radius: var(--radius-sm); + color: #fff; + font-weight: 700; + width: 100%; +} +#otp-input:focus { + border-color: var(--neon-cyan); + outline: none; + box-shadow: 0 0 12px rgba(0, 217, 255, 0.35); +} +.otp-actions { display: flex; flex-direction: column; gap: 12px; } +.otp-resend-row { display: flex; justify-content: space-between; align-items: center; font-size: .85rem; color: var(--muted); } +.resend-link { background: none; border: none; color: var(--neon-cyan); font: inherit; font-size: .85rem; padding: 0; cursor: pointer; text-decoration: underline; } +.resend-link:disabled { color: var(--muted); text-decoration: none; cursor: not-allowed; } +.change-phone-link { color: var(--muted); font-size: .85rem; text-decoration: underline; cursor: pointer; border: none; background: none; padding: 0; } +.change-phone-link:hover { color: var(--ink); } + +.identity-card { background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius); padding: 20px; display: grid; gap: 16px; margin-top: 24px; } +.identity-row { display: flex; justify-content: space-between; align-items: center; padding: 12px 0; border-bottom: 1px solid var(--line); } +.identity-row:last-child { border-bottom: none; } +.identity-meta { display: flex; flex-direction: column; gap: 2px; } +.identity-label { font-weight: 600; font-size: .95rem; color: var(--ink); } +.identity-status { font-size: .82rem; color: var(--muted); } +.identity-status.connected { color: #25D366; } +.identity-action { display: flex; gap: 8px; } + .tg-widget { min-height: 48px; } .tg-widget[aria-disabled="true"] { opacity: .45; pointer-events: none; } .signin-why { margin-top: 28px; padding: 20px; background: var(--surface); border: 1px solid var(--line); border-radius: var(--radius-sm); } @@ -380,15 +431,16 @@ select:focus, input:focus, textarea:focus { outline: 2px solid var(--accent); ou font-weight: 700; text-transform: uppercase; letter-spacing: .05em; - padding: 2px 8px; + padding: 3px 9px; border-radius: 4px; - background: rgba(255, 45, 149, 0.15); - color: var(--accent); - border: 1px solid rgba(255, 45, 149, 0.3); + background: rgba(49, 91, 255, 0.22); + color: #FFFFFF; + border: 1px solid rgba(49, 91, 255, 0.5); + line-height: 1.4; } .policy-badge-lg { font-size: .82rem; - padding: 4px 10px; + padding: 5px 12px; } .policy-guarantee, .policy-guarantee-pill { font-size: .76rem; @@ -1382,5 +1434,177 @@ select:focus, input:focus, textarea:focus { outline: 2px solid var(--accent); ou white-space: pre-wrap; } +/* Authentication & Marketing Consent Styles */ +.auth-consent-fieldset { + border: none; + padding: 0; + margin: 0; + display: grid; + gap: 12px; +} +.consent-check-row { + display: flex; + align-items: flex-start; + gap: 10px; + min-height: 44px; + cursor: pointer; + margin: 0; +} +.consent-check-row input[type="checkbox"] { + margin-top: 3px; + width: 18px; + height: 18px; + flex-shrink: 0; + accent-color: #25D366; + cursor: pointer; +} +.consent-check-row input[type="checkbox"]:focus-visible { + outline: 2px solid #25D366; + outline-offset: 2px; +} +.consent-text-wrap { + display: flex; + flex-direction: column; + gap: 2px; +} +.consent-title { + font-size: 0.92rem; + font-weight: 600; + color: var(--ink); + line-height: 1.35; +} +.consent-hint { + font-size: 0.8rem; + color: var(--muted); + line-height: 1.35; +} +.promo-consent-row { + background: rgba(37, 211, 102, 0.04); + border: 1px solid rgba(37, 211, 102, 0.18); + border-radius: var(--radius-sm); + padding: 10px 12px; +} + +/* Organiser Promotional Campaigns Styles */ +.campaign-panel { + display: grid; + gap: 20px; +} +.campaign-card { + background: var(--surface); + border: 1px solid var(--line); + border-radius: var(--radius); + padding: 20px; + display: grid; + gap: 16px; +} +.campaign-card-header { + display: flex; + justify-content: space-between; + align-items: flex-start; + gap: 12px; + flex-wrap: wrap; +} +.campaign-stats-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); + gap: 12px; + margin-top: 8px; +} +.campaign-stat-item { + background: var(--surface-2); + border: 1px solid var(--line-light); + border-radius: var(--radius-sm); + padding: 12px 14px; + display: flex; + flex-direction: column; + gap: 4px; +} +.campaign-stat-label { + font-size: 0.78rem; + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--muted); +} +.campaign-stat-val { + font-size: 1.35rem; + font-weight: 700; + color: var(--ink); +} +.campaign-preview-box { + background: rgba(37, 211, 102, 0.05); + border: 1px solid rgba(37, 211, 102, 0.25); + border-radius: var(--radius-sm); + padding: 16px; + display: grid; + gap: 10px; +} +.wa-bubble-preview { + background: #005c4b; + color: #ffffff; + border-radius: 8px; + padding: 14px; + max-width: 420px; + font-size: 0.92rem; + line-height: 1.45; + box-shadow: 0 2px 5px rgba(0,0,0,0.2); +} +.wa-bubble-header { + font-size: 0.8rem; + font-weight: 700; + color: #d9fdd3; + margin-bottom: 6px; + text-transform: uppercase; + letter-spacing: 0.06em; +} +.wa-bubble-body { + white-space: pre-wrap; + margin-bottom: 12px; + color: #ffffff; +} +.wa-bubble-actions { + display: flex; + flex-direction: column; + gap: 6px; + border-top: 1px solid rgba(255,255,255,0.25); + padding-top: 10px; +} +.wa-bubble-btn { + background: rgba(255,255,255,0.12); + border: 1px solid rgba(255,255,255,0.25); + border-radius: 6px; + padding: 8px 12px; + text-align: center; + font-size: 0.86rem; + font-weight: 600; + color: #ffffff; +} +.campaign-gate-warning { + background: rgba(255, 179, 0, 0.1); + border: 1px solid rgba(255, 179, 0, 0.3); + color: #ffb300; + border-radius: var(--radius-sm); + padding: 12px 14px; + font-size: 0.88rem; + line-height: 1.4; +} +.campaign-log-table { + width: 100%; + border-collapse: collapse; + font-size: 0.86rem; +} +.campaign-log-table th, +.campaign-log-table td { + padding: 8px 12px; + text-align: left; + border-bottom: 1px solid var(--line-light); +} +.campaign-log-table th { + color: var(--muted); + font-size: 0.78rem; + text-transform: uppercase; +} + + diff --git a/public/img/whatsapp.svg b/public/img/whatsapp.svg new file mode 100644 index 0000000..ba13c6b --- /dev/null +++ b/public/img/whatsapp.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/public/js/organiser.js b/public/js/organiser.js index 8a614f5..d6eee92 100644 --- a/public/js/organiser.js +++ b/public/js/organiser.js @@ -130,7 +130,8 @@ ['inventory', '🎟️ Ticket Inventory'], ['attendees', '👥 Attendees & Guest List'], ['staff', '🛡️ Event Staff'], - ['announcements', '📢 Announcements'] + ['announcements', '📢 Announcements'], + ['promotions', '📣 WhatsApp Promotion'] ]; return '
' + tabs.map(function (t) { @@ -182,6 +183,8 @@ renderStaffTab(panel); } else if (activeTab === 'announcements') { renderAnnouncementsTab(panel); + } else if (activeTab === 'promotions') { + renderPromotionsTab(panel); } } @@ -480,6 +483,309 @@ }); } + function renderPromotionsTab(panel) { + panel.innerHTML = '

Loading promotion campaigns and audience intelligence…

'; + var e = overviewData.event; + var curCity = e.city || ''; + var curCat = e.category || ''; + + Promise.all([ + api('GET', '/api/campaigns?eventId=' + encodeURIComponent(id)), + api('POST', '/api/campaigns/preview', { eventId: id, targetCity: curCity, targetCategory: curCat }) + ]).then(function (results) { + var campRes = results[0]; + var prevRes = results[1]; + + if (!campRes.ok || !prevRes.ok) { + panel.innerHTML = '

' + esc((campRes && campRes.message) || (prevRes && prevRes.message) || 'Could not load promotion campaigns.') + '

'; + return; + } + + var campaigns = campRes.campaigns || []; + var preview = prevRes; + + var h = '
' + + '
' + + '
' + + '
' + + '

📣 WhatsApp Event Promotion

' + + '

Target opted-in NIGHTLIFEZ members using official Meta Cloud API WhatsApp templates.

' + + '
' + + 'Official WhatsApp Cloud API' + + '
' + + + '
' + + '🛡️ Strict Opt-In & Anti-Spam Guarantee: Only members who actively opted in to WhatsApp promotional notifications are eligible. Unregistered visitors, unverified phone numbers, and non-opted-in guests are never messaged. Social followers and scraped contacts are strictly prohibited.' + + '
' + + + '
' + + '
' + + '' + + '' + + '
' + + '
' + + '' + + '' + + '
' + + '' + + '
' + + + '
' + + '
' + + 'Eligible Opted-In Audience' + + '' + preview.eligibleRecipientsCount + '' + + '
' + + '
' + + 'Estimated Delivery Cost' + + '₹' + preview.estimatedCostRupees + '' + + '(Est. ₹' + (preview.ratePerRecipientRupees || '0.80') + ' / conversation)' + + '
' + + '
' + + 'Meta Approval Status' + + 'Approved Template' + + '' + esc(preview.templatePreview.templateName) + '' + + '
' + + '
' + + + '
' + + '

Official Template Message Preview

' + + '' + + '
' + + + '
' + + '
' + + '🔗 Campaign Referral Link & UTM Tracking' + + 'UTM Attributed' + + '
' + + '

Every WhatsApp campaign button embeds full UTM tracking parameters to measure registrations and ticket passes.

' + + '
' + + '' + + '' + + '
' + + '
' + + + '
' + + '🤝 Personal vs Automated Outreach Strategy & Partner Guidelines' + + '
' + + '

Core Decision Rules:

' + + '
    ' + + '
  • Personal Outreach (1:1 Manual): Use for community owners (e.g. Rafiky), influencers, event organisers, and brand partners. Must be genuine, individually written, and relevant. Never scrape followers or send bulk automated DMs/WhatsApp blasts.
  • ' + + '
  • Automated Outreach: Strictly for existing NIGHTLIFEZ members with verified marketing consent.
  • ' + + '
  • No Consent / Unclear: Excluded from campaigns. Never infer consent from Instagram follows or OTP requests.
  • ' + + '
' + + '
' + + 'Sample 1:1 Partner Pitch (e.g. Rafiky / Community Leader):' + + '

“Hey Rafiky! Love what you’ve built with your community in Chennai. We’re hosting ' + esc(e.title) + ' on NIGHTLIFEZ and would love to explore co-hosting or curating an exclusive table for your crew. Happy to share full details if you’re open to collaborating!”

' + + '
' + + '
' + + '
' + + + '
' + + '

Prepare Campaign for this Event

' + + '
' + + '
' + + '' + + '' + + '
' + + '' + + '
' + + '

' + + '
' + + '
'; + + // Campaigns history section + h += '
' + + '

Campaigns & Dispatch History

'; + + if (campaigns.length === 0) { + h += '

No promotion campaigns have been created for this event yet.

'; + } else { + h += '
' + + campaigns.map(function (c) { + var statusColor = c.status === 'completed' ? '#25D366' : (c.status === 'approved' ? '#00d9ff' : '#ffb300'); + var isCompleted = c.status === 'completed'; + var isApproved = c.status === 'approved'; + var isDraft = c.status === 'draft'; + + return '
' + + '
' + + '
' + + '' + esc(c.title) + '' + + '' + esc(fmtInstant(c.created_at)) + '' + + '
' + + '' + esc(c.status) + (c.audit_metadata && c.audit_metadata.simulated ? ' (Simulated)' : '') + '' + + '
' + + + '
' + + 'Target: ' + esc(c.target_city || 'All Cities') + ' (' + esc(c.target_category || 'All Categories') + ')' + + 'Recipients: ' + (isCompleted ? c.actual_recipients : c.estimated_recipients) + ' opted-in users' + + 'Cost: ₹' + ((isCompleted ? c.actual_cost_paise : c.estimated_cost_paise) / 100).toFixed(2) + '' + + '
' + + + '
' + + (isDraft ? '' : '') + + (isApproved || isDraft ? '' : '') + + '' + + (c.status !== 'completed' && c.status !== 'cancelled' ? '' : '') + + '
' + + + (isApproved || isDraft ? '
🔒 Live Dispatch Gate Active: Live promotional sending is safely disabled until Meta Business verification and template approval are complete. Dispatching will run in Safe Simulated Mode with delivery log generation and zero external messages.
' : '') + + + '' + + '
'; + }).join('') + + '
'; + } + + h += '
'; + panel.innerHTML = h; + + // Hook up recalculate audience preview form + var prevForm = $('[data-preview-form]', panel); + if (prevForm) { + prevForm.addEventListener('submit', function (ev) { + ev.preventDefault(); + var cityVal = prevForm.targetCity.value; + var catVal = prevForm.targetCategory.value; + api('POST', '/api/campaigns/preview', { eventId: id, targetCity: cityVal, targetCategory: catVal }).then(function (pr) { + if (pr.ok) { + var cntEl = $('[data-audience-count]', panel); + if (cntEl) cntEl.textContent = pr.eligibleRecipientsCount; + } + }); + }); + } + + // Hook up campaign draft creation form + var createForm = $('[data-create-campaign-form]', panel); + if (createForm) { + createForm.addEventListener('submit', function (ev) { + ev.preventDefault(); + var titleVal = createForm.title.value; + var cMsg = $('[data-campaign-msg]', panel); + cMsg.textContent = 'Creating campaign draft…'; + api('POST', '/api/campaigns', { + eventId: id, + title: titleVal, + targetCity: prevForm ? prevForm.targetCity.value : curCity, + targetCategory: prevForm ? prevForm.targetCategory.value : curCat + }).then(function (cr) { + if (cr.ok) { + renderPromotionsTab(panel); + } else { + cMsg.className = 'form-msg error'; + cMsg.textContent = cr.message || 'Could not create campaign.'; + } + }); + }); + } + + // Hook up Approve buttons + $$('[data-approve-campaign]', panel).forEach(function (btn) { + btn.addEventListener('click', function () { + var cid = btn.getAttribute('data-approve-campaign'); + btn.disabled = true; + api('POST', '/api/campaigns/' + encodeURIComponent(cid) + '/approve', {}).then(function (ar) { + if (ar.ok) renderPromotionsTab(panel); + else alert(ar.message || 'Approval failed'); + }); + }); + }); + + // Hook up Dispatch buttons + $$('[data-dispatch-campaign]', panel).forEach(function (btn) { + btn.addEventListener('click', function () { + var cid = btn.getAttribute('data-dispatch-campaign'); + if (!confirm('Run promotional campaign dispatch? (Will execute in Safe Simulation Mode)')) return; + btn.disabled = true; + api('POST', '/api/campaigns/' + encodeURIComponent(cid) + '/dispatch', {}).then(function (dr) { + if (dr.ok) { + alert(dr.message || 'Campaign dispatch simulated successfully.'); + renderPromotionsTab(panel); + } else { + alert(dr.message || 'Dispatch failed'); + btn.disabled = false; + } + }); + }); + }); + + // Hook up Cancel buttons + $$('[data-cancel-campaign]', panel).forEach(function (btn) { + btn.addEventListener('click', function () { + var cid = btn.getAttribute('data-cancel-campaign'); + if (!confirm('Cancel this campaign?')) return; + api('POST', '/api/campaigns/' + encodeURIComponent(cid) + '/cancel', {}).then(function (cr) { + if (cr.ok) renderPromotionsTab(panel); + else alert(cr.message || 'Cancel failed'); + }); + }); + }); + + // Hook up View Logs buttons + $$('[data-view-logs]', panel).forEach(function (btn) { + btn.addEventListener('click', function () { + var cid = btn.getAttribute('data-view-logs'); + var box = $('#logs-box-' + cid, panel); + if (!box) return; + if (!box.hidden) { + box.hidden = true; + return; + } + box.hidden = false; + box.innerHTML = '

Loading delivery logs…

'; + api('GET', '/api/campaigns/' + encodeURIComponent(cid) + '/logs').then(function (lr) { + if (!lr.ok || !lr.logs || lr.logs.length === 0) { + box.innerHTML = '

No recipient delivery logs recorded yet.

'; + return; + } + var tableHtml = '
' + + '' + + lr.logs.map(function (log) { + return '' + + '' + + '' + + '' + + '' + + '' + + '' + + ''; + }).join('') + + '
RecipientCityStatusProvider Msg IDCostDispatched
' + esc(log.alias) + ' (' + esc(log.phoneMasked) + ')' + esc(log.city) + '' + esc(log.status) + '' + esc(log.providerMessageId || 'mock_outbox') + '₹' + (log.deliveryCostPaise / 100).toFixed(2) + '' + esc(fmtInstant(log.dispatchedAt)) + '
'; + box.innerHTML = tableHtml; + }); + }); + }); + }); + } + el.addEventListener('click', function (ev) { var tabBtn = ev.target.closest('[data-tab]'); if (tabBtn) { diff --git a/public/js/site.js b/public/js/site.js index 971f029..5015e09 100644 --- a/public/js/site.js +++ b/public/js/site.js @@ -220,6 +220,241 @@ }); } + /* Switcher for WhatsApp vs Telegram tabs on /signin */ + var authTabs = $$('[data-auth-tab]'); + if (authTabs.length) { + authTabs.forEach(function (tab) { + tab.addEventListener('click', function () { + var target = tab.getAttribute('data-auth-tab'); + authTabs.forEach(function (t) { + var isActive = t === tab; + t.classList.toggle('active', isActive); + t.classList.toggle('wa-tab', isActive && target === 'whatsapp'); + t.setAttribute('aria-selected', isActive ? 'true' : 'false'); + }); + $$('[data-auth-panel]').forEach(function (panel) { + panel.hidden = panel.getAttribute('data-auth-panel') !== target; + }); + }); + }); + } + + /* WhatsApp OTP Authentication on /signin */ + var waPhoneForm = $('[data-wa-phone-form]'); + var waOtpCard = $('[data-wa-otp-card]'); + if (waPhoneForm && waOtpCard) { + var signinMsg = $('[data-signin-msg]'); + var currentChallengeId = null; + var currentPhone = null; + var currentPromoOptIn = false; + var countdownTimer = null; + var otpAbortController = null; + + var stopSmsOtpListener = function () { + if (otpAbortController) { + otpAbortController.abort(); + otpAbortController = null; + } + }; + + var startSmsOtpListener = function () { + var otpInput = document.getElementById('otp-input'); + var otpForm = document.getElementById('otp-form'); + if (!otpInput || !('OTPCredential' in window)) return; + stopSmsOtpListener(); + var ac = new AbortController(); + otpAbortController = ac; + navigator.credentials.get({ + otp: { transport: ['sms'] }, + signal: ac.signal + }).then(function (otp) { + if (!otp) return; + otpInput.value = otp.code; + if (otpForm && otpForm.requestSubmit) { + otpForm.requestSubmit(); + } + }).catch(function (err) { + if (err && err.name === 'AbortError') return; + console.error('WebOTP verification error:', err); + }); + }; + + var startCountdown = function (seconds) { + if (countdownTimer) clearInterval(countdownTimer); + var resendBtn = $('[data-wa-resend-btn]'); + if (!resendBtn) return; + resendBtn.disabled = true; + var remaining = seconds || 60; + resendBtn.textContent = 'Resend code (' + remaining + 's)'; + countdownTimer = setInterval(function () { + remaining--; + if (remaining <= 0) { + clearInterval(countdownTimer); + countdownTimer = null; + resendBtn.disabled = false; + resendBtn.textContent = 'Resend code via WhatsApp'; + } else { + resendBtn.textContent = 'Resend code (' + remaining + 's)'; + } + }, 1000); + }; + + waPhoneForm.addEventListener('submit', function (ev) { + ev.preventDefault(); + var phoneInput = $('#wa-phone'); + var ageCheck = $('[data-wa-age]'); + var promoCheck = $('[data-wa-promo]'); + var submitBtn = $('[data-wa-submit-phone]'); + + if (!ageCheck.checked) { + signinMsg.className = 'form-msg error'; + signinMsg.textContent = 'Please confirm you are 21 or older to continue.'; + return; + } + + var rawDigits = phoneInput.value.replace(/\D/g, ''); + if (rawDigits.length !== 10 || !/^[6-9]/.test(rawDigits)) { + signinMsg.className = 'form-msg error'; + signinMsg.textContent = 'Please enter a valid 10-digit Indian mobile number (starts with 6-9).'; + phoneInput.focus(); + return; + } + + var fullPhone = '+91' + rawDigits; + currentPhone = fullPhone; + currentPromoOptIn = Boolean(promoCheck && promoCheck.checked); + + submitBtn.disabled = true; + submitBtn.textContent = 'Sending WhatsApp OTP…'; + signinMsg.className = 'form-msg'; + signinMsg.textContent = ''; + + api('POST', '/api/auth/whatsapp/otp', { + phone: fullPhone, + promotionalOptIn: currentPromoOptIn + }).then(function (r) { + submitBtn.disabled = false; + submitBtn.textContent = 'Send WhatsApp OTP'; + + if (!r.ok) { + signinMsg.className = 'form-msg error'; + signinMsg.textContent = r.message || 'Failed to send WhatsApp OTP. Please try again.'; + return; + } + + currentChallengeId = r.challengeId; + var maskedEl = $('[data-wa-masked-phone]'); + if (maskedEl) maskedEl.textContent = r.phoneMasked || fullPhone; + + var phoneStep = $('[data-wa-step="phone"]'); + if (phoneStep) phoneStep.hidden = true; + waOtpCard.hidden = false; + + var otpInput = $('#otp-input'); + if (otpInput) { + otpInput.value = ''; + otpInput.focus(); + } + + startCountdown(r.resendAfterSeconds || 60); + startSmsOtpListener(); + }).catch(function () { + submitBtn.disabled = false; + submitBtn.textContent = 'Send WhatsApp OTP'; + signinMsg.className = 'form-msg error'; + signinMsg.textContent = 'Network error while requesting OTP. Please try again.'; + }); + }); + + var verifyForm = $('[data-wa-verify-form]'); + if (verifyForm) { + verifyForm.addEventListener('submit', function (ev) { + ev.preventDefault(); + stopSmsOtpListener(); + + var otpInput = $('#otp-input'); + var verifyBtn = $('[data-wa-verify-btn]'); + var code = (otpInput.value || '').trim(); + + if (!/^\d{6}$/.test(code)) { + signinMsg.className = 'form-msg error'; + signinMsg.textContent = 'Please enter the complete 6-digit verification code.'; + otpInput.focus(); + return; + } + + verifyBtn.disabled = true; + verifyBtn.textContent = 'Verifying code…'; + signinMsg.className = 'form-msg'; + signinMsg.textContent = ''; + + api('POST', '/api/auth/whatsapp/verify', { + challengeId: currentChallengeId, + phone: currentPhone, + code: code, + promotionalOptIn: currentPromoOptIn + }).then(function (r) { + verifyBtn.disabled = false; + verifyBtn.textContent = 'Verify & Continue'; + + if (!r.ok) { + signinMsg.className = 'form-msg error'; + signinMsg.textContent = r.message || 'Invalid or expired OTP code.'; + otpInput.value = ''; + otpInput.focus(); + return; + } + + afterAuth(r, signinMsg); + }).catch(function () { + verifyBtn.disabled = false; + verifyBtn.textContent = 'Verify & Continue'; + signinMsg.className = 'form-msg error'; + signinMsg.textContent = 'Network error while verifying OTP.'; + }); + }); + } + + var changePhoneBtn = $('[data-wa-change-phone]'); + if (changePhoneBtn) { + changePhoneBtn.addEventListener('click', function () { + stopSmsOtpListener(); + if (countdownTimer) clearInterval(countdownTimer); + waOtpCard.hidden = true; + var phoneStep = $('[data-wa-step="phone"]'); + if (phoneStep) phoneStep.hidden = false; + var phoneInput = $('#wa-phone'); + if (phoneInput) phoneInput.focus(); + }); + } + + var resendBtn = $('[data-wa-resend-btn]'); + if (resendBtn) { + resendBtn.addEventListener('click', function () { + if (!currentPhone) return; + resendBtn.disabled = true; + resendBtn.textContent = 'Sending new OTP…'; + api('POST', '/api/auth/whatsapp/otp', { + phone: currentPhone, + promotionalOptIn: currentPromoOptIn + }).then(function (r) { + if (!r.ok) { + signinMsg.className = 'form-msg error'; + signinMsg.textContent = r.message || 'Could not resend OTP. Please wait before retrying.'; + resendBtn.disabled = false; + resendBtn.textContent = 'Resend code via WhatsApp'; + return; + } + currentChallengeId = r.challengeId; + startCountdown(r.resendAfterSeconds || 60); + startSmsOtpListener(); + signinMsg.className = 'form-msg ok'; + signinMsg.textContent = 'A new 6-digit code has been sent to your WhatsApp.'; + }); + }); + } + } + /* Telegram Login Widget on /signin */ var widget = $('[data-tg-widget]'); if (widget) { @@ -537,9 +772,122 @@ var isTarget = sec.getAttribute('data-hub-section') === tab; sec.hidden = !isTarget; }); + if (tab === 'account') { + renderAccountSettings(); + } }); }); + var accountBox = $('[data-account-settings]', hub); + function renderAccountSettings() { + if (!accountBox) return; + accountBox.innerHTML = '

Loading connected accounts and preferences…

'; + Promise.all([ + api('GET', '/api/me/identities'), + api('GET', '/api/me/communication-preferences') + ]).then(function (results) { + var idRes = results[0]; + var prefRes = results[1]; + if (!idRes.ok || !prefRes.ok) { + accountBox.innerHTML = '

Could not load account settings.

'; + return; + } + + var wa = idRes.identities.whatsapp; + var tg = idRes.identities.telegram; + var prefs = prefRes.preferences; + + var html = '
' + + '

Connected Login Methods

' + + '

Link both WhatsApp and Telegram to access your tickets and receive operational updates across either service.

' + + '
' + + '
' + + 'WhatsApp' + + '' + + (wa.linked ? '✓ Connected (' + wa.phoneMasked + ')' : 'Not Connected') + + '' + + '
' + + '
' + + (wa.linked + ? (tg.linked ? '' : 'Sole Login Method') + : 'Connect WhatsApp') + + '
' + + '
' + + '
' + + '
' + + 'Telegram' + + '' + + (tg.linked ? '✓ Connected (Telegram ID: ' + tg.telegramUserId + ')' : 'Not Connected') + + '' + + '
' + + '
' + + (tg.linked + ? 'Active' + : 'Connect Telegram') + + '
' + + '
' + + '
' + + + '
' + + '

Communication Preferences

' + + '

Manage how and where NIGHTLIFEZ sends you notifications.

' + + '
' + + '
' + + 'Essential Transactional Notices' + + 'Booking confirmations, QR entry passes, and schedule changes.' + + '
' + + '
' + + 'Always Active' + + '
' + + '
' + + '
' + + '
' + + 'WhatsApp Event Announcements & Promotional Offers' + + 'Curated weekend parties, secret meetups, and exclusive nightlife invites. Optional & separate from transactional passes.' + + '
' + + '
' + + '' + + '
' + + '
' + + '
'; + + accountBox.innerHTML = html; + + var unlinkBtn = $('[data-unlink-wa]', accountBox); + if (unlinkBtn) { + unlinkBtn.addEventListener('click', function () { + if (!confirm('Are you sure you want to disconnect WhatsApp? You will need Telegram to sign in.')) return; + api('POST', '/api/auth/whatsapp/unlink', {}).then(function (r) { + if (r.ok) { + renderAccountSettings(); + } else { + alert(r.message || 'Could not disconnect WhatsApp.'); + } + }); + }); + } + + var promoToggle = $('[data-toggle-promo-wa]', accountBox); + if (promoToggle) { + promoToggle.addEventListener('click', function () { + var currentStatus = prefs.whatsapp && prefs.whatsapp.promotional; + var nextStatus = currentStatus ? 'opted_out' : 'opted_in'; + api('PATCH', '/api/me/communication-preferences', { + channel: 'whatsapp', + purpose: 'promotional', + status: nextStatus + }).then(function (r) { + if (r.ok) { + renderAccountSettings(); + } + }); + }); + } + }); + } + var filterBtns = $$('[data-booking-filter]', hub); filterBtns.forEach(function (btn) { btn.addEventListener('click', function () { diff --git a/test/accessibility-contrast.test.js b/test/accessibility-contrast.test.js index 94a801e..70ab724 100644 --- a/test/accessibility-contrast.test.js +++ b/test/accessibility-contrast.test.js @@ -69,3 +69,33 @@ test('WCAG 2.2 AA - Non-text UI boundaries and focus rings meet 3:1 ratio', () = const ratioBorder = contrastRatio(lineStrong, surface); assert.ok(ratioBorder >= 3.0, `UI boundary line on surface must meet 3:1 (got ${ratioBorder.toFixed(2)})`); }); + +test('WCAG 2.1 AA - Policy badge text contrast meets 4.5:1 ratio', () => { + // Policy badge uses #FFFFFF text on rgba(49, 91, 255, 0.22) + // Tested against dark background #090B16 and card surface #121424 + const bg = '#090B16'; + const surface = '#121424'; + const badgeText = '#FFFFFF'; + + function blend(foregroundRgba, backgroundHex) { + const clean = backgroundHex.replace('#', '').trim(); + const bgR = parseInt(clean.slice(0, 2), 16); + const bgG = parseInt(clean.slice(2, 4), 16); + const bgB = parseInt(clean.slice(4, 6), 16); + const { r, g, b, a } = foregroundRgba; + const resR = Math.round(bgR * (1 - a) + r * a); + const resG = Math.round(bgG * (1 - a) + g * a); + const resB = Math.round(bgB * (1 - a) + b * a); + return '#' + [resR, resG, resB].map((x) => x.toString(16).padStart(2, '0')).join(''); + } + + const badgeBg = { r: 49, g: 91, b: 255, a: 0.22 }; + const effectiveOnSurface = blend(badgeBg, surface); + const effectiveOnBg = blend(badgeBg, bg); + + const ratioSurface = contrastRatio(badgeText, effectiveOnSurface); + const ratioBg = contrastRatio(badgeText, effectiveOnBg); + + assert.ok(ratioSurface >= 4.5, `Policy badge on surface must meet 4.5:1 (got ${ratioSurface.toFixed(2)})`); + assert.ok(ratioBg >= 4.5, `Policy badge on bg must meet 4.5:1 (got ${ratioBg.toFixed(2)})`); +}); diff --git a/test/communication-consent.test.js b/test/communication-consent.test.js new file mode 100644 index 0000000..0716a00 --- /dev/null +++ b/test/communication-consent.test.js @@ -0,0 +1,62 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { db, resetDb } from './helpers.js'; +import { + recordConsent, + getConsents, + hasConsent, + addSuppression, + isSuppressed, + removeSuppression +} from '../lib/services/communication-consent.js'; + +test.beforeEach(async () => { + await resetDb(); +}); + +test('communication consent lifecycle: default states and explicit opt-in', async () => { + const user = (await db.query(`INSERT INTO users (telegram_user_id, alias) VALUES (777001, 'ConsentUser') RETURNING id`)).rows[0]; + + // Default: transactional is allowed, promotional is false + assert.equal(await hasConsent({ userId: user.id, channel: 'whatsapp', purpose: 'transactional' }), true); + assert.equal(await hasConsent({ userId: user.id, channel: 'whatsapp', purpose: 'promotional' }), false); + + // Explicit opt-in for promotional + await recordConsent({ + userId: user.id, + channel: 'whatsapp', + purpose: 'promotional', + status: 'opted_in', + source: 'signin_form' + }); + + assert.equal(await hasConsent({ userId: user.id, channel: 'whatsapp', purpose: 'promotional' }), true); + + // Opt-out again + await recordConsent({ + userId: user.id, + channel: 'whatsapp', + purpose: 'promotional', + status: 'opted_out', + source: 'profile_settings' + }); + + assert.equal(await hasConsent({ userId: user.id, channel: 'whatsapp', purpose: 'promotional' }), false); + + // Audit log should record consent events + const auditLogs = (await db.query(`SELECT action, target, details FROM audit_log WHERE target = $1 ORDER BY at ASC`, [`user:${user.id}`])).rows; + assert.ok(auditLogs.some((l) => l.action === 'consent_opted_in' && l.details.purpose === 'promotional')); + assert.ok(auditLogs.some((l) => l.action === 'consent_opted_out' && l.details.purpose === 'promotional')); +}); + +test('suppression list: suppresses destination and removes suppression', async () => { + const phone = '+919876543210'; + + assert.equal(await isSuppressed({ channel: 'whatsapp', destination: phone }), false); + + await addSuppression({ channel: 'whatsapp', destination: phone, reason: 'user_opt_out' }); + assert.equal(await isSuppressed({ channel: 'whatsapp', destination: phone }), true); + + await removeSuppression({ channel: 'whatsapp', destination: phone }); + assert.equal(await isSuppressed({ channel: 'whatsapp', destination: phone }), false); +}); diff --git a/test/migrations.test.js b/test/migrations.test.js index c3f910b..27ba22f 100644 --- a/test/migrations.test.js +++ b/test/migrations.test.js @@ -20,13 +20,13 @@ test('migration files inventory: sequential numbering, correct naming, and sorte .filter((f) => /^\d+_.*\.sql$/.test(f)) .sort(); - // Exactly 20 migrations currently exist: 003 through 022 - assert.equal(files.length, 20, `expected 20 migration files, got ${files.length}: ${files.join(', ')}`); + // Exactly 22 migrations currently exist: 003 through 024 + assert.equal(files.length, 22, `expected 22 migration files, got ${files.length}: ${files.join(', ')}`); // Verify sequential ordering const expectedPrefixes = [ '003_', '004_', '005_', '006_', '007_', '008_', - '009_', '010_', '011_', '012_', '013_', '014_', '015_', '016_', '017_', '018_', '019_', '020_', '021_', '022_' + '009_', '010_', '011_', '012_', '013_', '014_', '015_', '016_', '017_', '018_', '019_', '020_', '021_', '022_', '023_', '024_' ]; for (let i = 0; i < expectedPrefixes.length; i++) { assert.ok( @@ -45,9 +45,9 @@ test('migration idempotency: re-running migrate() on an up-to-date database appl assert.deepEqual(thirdRun, [], 'expected zero migrations applied on third run'); }); -test('schema_migrations table records all 20 migrations in correct order', async () => { +test('schema_migrations table records all 22 migrations in correct order', async () => { const { rows } = await db.query('SELECT name, applied_at FROM schema_migrations ORDER BY name ASC'); - assert.equal(rows.length, 20); + assert.equal(rows.length, 22); const appliedNames = rows.map((r) => r.name); const filesOnDisk = fs.readdirSync(MIGRATIONS_DIR) @@ -74,9 +74,9 @@ test('advisory lock serializes concurrent migrate() calls', async () => { assert.deepEqual(res2, []); assert.deepEqual(res3, []); - // Total count in schema_migrations must remain exactly 20 + // Total count in schema_migrations must remain exactly 22 const countRes = await db.one('SELECT count(*)::int AS n FROM schema_migrations'); - assert.equal(countRes.n, 20); + assert.equal(countRes.n, 22); }); test('migration policy respects environment boundaries', () => { diff --git a/test/notification-dispatcher.test.js b/test/notification-dispatcher.test.js new file mode 100644 index 0000000..44ddf38 --- /dev/null +++ b/test/notification-dispatcher.test.js @@ -0,0 +1,135 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { db, resetDb } from './helpers.js'; +import { + dispatchNotification, + updateDeliveryReceipt, + handleOptOutKeyword, + getNotificationTelemetry, + getNotificationMessagesList, + getSuppressionsList +} from '../lib/services/notification-dispatcher.js'; +import { getWhatsAppProvider } from '../lib/services/whatsapp-provider.js'; +import { recordConsent } from '../lib/services/communication-consent.js'; + +test.beforeEach(async () => { + await resetDb(); + getWhatsAppProvider().clearSentMessages(); +}); + +test('Notification Dispatcher - sends WhatsApp notification and logs in notification_messages', async () => { + const phone = '+919876543210'; + const res = await dispatchNotification({ + recipient: phone, + channel: 'whatsapp', + purpose: 'transactional', + templateName: 'booking_confirmed', + templateComponents: [{ type: 'body', parameters: [{ type: 'text', text: 'Music Fest' }] }], + idempotencyKey: 'test_dispatch_1' + }); + + assert.equal(res.status, 'sent'); + assert.equal(res.channel, 'whatsapp'); + assert.equal(res.recipient, phone); + assert.ok(res.provider_message_id); + assert.equal(res.delivery_cost_paise, 15); + + const sent = getWhatsAppProvider().getSentMessages(); + assert.equal(sent.length, 1); + assert.equal(sent[0].to, phone); +}); + +test('Notification Dispatcher - enforces deduplication via idempotencyKey', async () => { + const phone = '+919876543210'; + const res1 = await dispatchNotification({ + recipient: phone, + channel: 'whatsapp', + purpose: 'transactional', + templateName: 'booking_confirmed', + idempotencyKey: 'dedupe_key_100' + }); + + const res2 = await dispatchNotification({ + recipient: phone, + channel: 'whatsapp', + purpose: 'transactional', + templateName: 'booking_confirmed', + idempotencyKey: 'dedupe_key_100' + }); + + assert.equal(res1.id, res2.id); + assert.equal(getWhatsAppProvider().getSentMessages().length, 1); +}); + +test('Notification Dispatcher - respects suppression list', async () => { + const phone = '+919876543210'; + await handleOptOutKeyword({ destination: phone, channel: 'whatsapp' }); + + const res = await dispatchNotification({ + recipient: phone, + channel: 'whatsapp', + purpose: 'transactional', + templateName: 'booking_confirmed', + idempotencyKey: 'suppressed_test_1' + }); + + assert.equal(res.status, 'suppressed'); + assert.equal(res.provider, 'none'); + assert.equal(getWhatsAppProvider().getSentMessages().length, 0); +}); + +test('Notification Dispatcher - respects user communication consent', async () => { + const user = (await db.query(`INSERT INTO users (phone, alias) VALUES ('+919876543211', 'Test User') RETURNING id`)).rows[0]; + + // Record transactional consent: opted_in, promotional: opted_out + await recordConsent({ userId: user.id, channel: 'whatsapp', purpose: 'transactional', status: 'opted_in' }); + await recordConsent({ userId: user.id, channel: 'whatsapp', purpose: 'promotional', status: 'opted_out' }); + + // Promotional dispatch should fail due to no consent + const promoRes = await dispatchNotification({ + userId: user.id, + recipient: '+919876543211', + channel: 'whatsapp', + purpose: 'promotional', + templateName: 'weekend_event_announcement', + idempotencyKey: 'promo_no_consent_1' + }); + + assert.equal(promoRes.status, 'failed'); + assert.equal(promoRes.last_error, 'no_user_consent'); + assert.equal(getWhatsAppProvider().getSentMessages().length, 0); +}); + +test('Notification Dispatcher - updates delivery receipt on webhook event', async () => { + const phone = '+919876543210'; + const sent = await dispatchNotification({ + recipient: phone, + channel: 'whatsapp', + purpose: 'transactional', + templateName: 'booking_confirmed', + idempotencyKey: 'receipt_test_1' + }); + + const updated = await updateDeliveryReceipt({ + providerMessageId: sent.provider_message_id, + status: 'delivered' + }); + + assert.equal(updated.status, 'delivered'); + assert.ok(updated.delivered_at); +}); + +test('Notification Dispatcher - telemetry reports aggregated metrics and masked PII', async () => { + const telemetry = await getNotificationTelemetry(); + assert.ok(telemetry.whatsapp); + assert.equal(typeof telemetry.whatsapp.mode, 'string'); + assert.ok(telemetry.otp); + assert.ok(telemetry.messages); + assert.ok(telemetry.suppressions); + + const messages = await getNotificationMessagesList({ limit: 10 }); + assert.ok(Array.isArray(messages)); + if (messages.length > 0) { + assert.ok(messages[0].recipientMasked.includes('****')); + } +}); diff --git a/test/otp.test.js b/test/otp.test.js new file mode 100644 index 0000000..81a61a3 --- /dev/null +++ b/test/otp.test.js @@ -0,0 +1,132 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { db, resetDb } from './helpers.js'; +import { + generateOtpCode, + hashOtpCode, + createOtpChallenge, + verifyOtpChallenge +} from '../lib/services/otp.js'; + +test.beforeEach(async () => { + await resetDb(); +}); + +test('generateOtpCode produces 6-digit numeric string', () => { + for (let i = 0; i < 20; i++) { + const code = generateOtpCode(); + assert.match(code, /^\d{6}$/); + const num = Number(code); + assert.ok(num >= 100000 && num <= 999999); + } +}); + +test('hashOtpCode is deterministic with salt', () => { + const salt = 'abcdef1234567890'; + const h1 = hashOtpCode('123456', salt); + const h2 = hashOtpCode('123456', salt); + const h3 = hashOtpCode('123457', salt); + assert.equal(h1, h2); + assert.notEqual(h1, h3); +}); + +test('OTP challenge lifecycle: create, verify with correct code', async () => { + const phone = '+919876543210'; + const challenge = await createOtpChallenge({ phone, ip: '192.168.1.1' }); + + assert.ok(challenge.challengeId); + assert.match(challenge.otp, /^\d{6}$/); + assert.equal(challenge.resendAfterSeconds, 60); + + // Verify correctly + const result = await verifyOtpChallenge({ + challengeId: challenge.challengeId, + phone, + code: challenge.otp, + ip: '192.168.1.1' + }); + + assert.equal(result.ok, true); + assert.equal(result.phone, phone); + + // Re-verify should fail (single-use) + await assert.rejects( + () => verifyOtpChallenge({ + challengeId: challenge.challengeId, + phone, + code: challenge.otp, + ip: '192.168.1.1' + }), + /already been used/i + ); +}); + +test('OTP challenge: invalid code decrements remaining attempts and locks out after 5', async () => { + const phone = '+919876543211'; + const challenge = await createOtpChallenge({ phone, ip: '192.168.1.2' }); + + // 1st bad attempt + await assert.rejects( + () => verifyOtpChallenge({ challengeId: challenge.challengeId, phone, code: '000000', ip: '192.168.1.2' }), + /4 attempts remaining/i + ); + + // 2nd bad attempt + await assert.rejects( + () => verifyOtpChallenge({ challengeId: challenge.challengeId, phone, code: '000000', ip: '192.168.1.2' }), + /3 attempts remaining/i + ); + + // 3rd bad attempt + await assert.rejects( + () => verifyOtpChallenge({ challengeId: challenge.challengeId, phone, code: '000000', ip: '192.168.1.2' }), + /2 attempts remaining/i + ); + + // 4th bad attempt + await assert.rejects( + () => verifyOtpChallenge({ challengeId: challenge.challengeId, phone, code: '000000', ip: '192.168.1.2' }), + /1 attempt remaining/i + ); + + // 5th bad attempt -> lockout + await assert.rejects( + () => verifyOtpChallenge({ challengeId: challenge.challengeId, phone, code: '000000', ip: '192.168.1.2' }), + /Too many incorrect attempts/i + ); + + // Even with the correct OTP now, challenge is locked + await assert.rejects( + () => verifyOtpChallenge({ challengeId: challenge.challengeId, phone, code: challenge.otp, ip: '192.168.1.2' }), + /Too many incorrect attempts/i + ); +}); + +test('OTP challenge: resend cooldown blocks premature requests', async () => { + const phone = '+919876543212'; + await createOtpChallenge({ phone, ip: '192.168.1.3' }); + + // Immediate second request within 60s + await assert.rejects( + () => createOtpChallenge({ phone, ip: '192.168.1.3' }), + (err) => { + assert.equal(err.status, 429); + assert.match(err.message, /Please wait \d+ seconds/); + assert.ok((err.retryAfter || err.extra?.retryAfter) > 0); + return true; + } + ); +}); + +test('OTP challenge: expired OTP is rejected', async () => { + const phone = '+919876543213'; + const challenge = await createOtpChallenge({ phone, ip: '192.168.1.4' }); + + // Manually backdate expires_at in DB + await db.query(`UPDATE otp_challenges SET expires_at = now() - interval '1 second' WHERE id = $1`, [challenge.challengeId]); + + await assert.rejects( + () => verifyOtpChallenge({ challengeId: challenge.challengeId, phone, code: challenge.otp, ip: '192.168.1.4' }), + /This code has expired/i + ); +}); diff --git a/test/phone.test.js b/test/phone.test.js new file mode 100644 index 0000000..4e890ce --- /dev/null +++ b/test/phone.test.js @@ -0,0 +1,60 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { normalizePhoneNumber, isValidE164, maskPhone, hashPhone } from '../lib/services/phone.js'; + +test('normalizePhoneNumber - Indian phone numbers', () => { + // Plain 10 digits starting with 9, 8, 7, 6 + assert.equal(normalizePhoneNumber('9876543210'), '+919876543210'); + assert.equal(normalizePhoneNumber('8876543210'), '+918876543210'); + assert.equal(normalizePhoneNumber('7876543210'), '+917876543210'); + assert.equal(normalizePhoneNumber('6876543210'), '+916876543210'); + + // Formatted with spaces, dashes, brackets + assert.equal(normalizePhoneNumber('98765 43210'), '+919876543210'); + assert.equal(normalizePhoneNumber('+91 98765-43210'), '+919876543210'); + assert.equal(normalizePhoneNumber('+91 (98765) 43210'), '+919876543210'); + + // With leading 0 + assert.equal(normalizePhoneNumber('09876543210'), '+919876543210'); + + // With 91 prefix without plus + assert.equal(normalizePhoneNumber('919876543210'), '+919876543210'); + + // With 00 international prefix + assert.equal(normalizePhoneNumber('00919876543210'), '+919876543210'); +}); + +test('normalizePhoneNumber - invalid phone numbers rejected', () => { + assert.throws(() => normalizePhoneNumber(''), /provide a valid phone/i); + assert.throws(() => normalizePhoneNumber(null), /provide a valid phone/i); + assert.throws(() => normalizePhoneNumber('12345'), /must be 10 digits/i); + assert.throws(() => normalizePhoneNumber('5555555555'), /starting with 6, 7, 8, or 9/i); + assert.throws(() => normalizePhoneNumber('+911234567890'), /starting with 6, 7, 8, or 9/i); + assert.throws(() => normalizePhoneNumber('invalid-text'), /must be 10 digits/i); +}); + +test('isValidE164', () => { + assert.equal(isValidE164('+919876543210'), true); + assert.equal(isValidE164('+14155552671'), true); + assert.equal(isValidE164('+447911123456'), true); + assert.equal(isValidE164('9876543210'), false); + assert.equal(isValidE164('+911234567890'), false); // Invalid Indian mobile prefix + assert.equal(isValidE164(''), false); + assert.equal(isValidE164(null), false); +}); + +test('maskPhone', () => { + assert.equal(maskPhone('+919876543210'), '+91 98****3210'); + assert.equal(maskPhone('+14155552671'), '+141****71'); + assert.equal(maskPhone(''), ''); + assert.equal(maskPhone('123'), '****'); +}); + +test('hashPhone returns consistent SHA-256 slice', () => { + const h1 = hashPhone('+919876543210'); + const h2 = hashPhone('+919876543210'); + const h3 = hashPhone('+919876543211'); + assert.equal(h1, h2); + assert.notEqual(h1, h3); + assert.equal(h1.length, 32); +}); diff --git a/test/promotional-campaigns.test.js b/test/promotional-campaigns.test.js new file mode 100644 index 0000000..cbbcdf5 --- /dev/null +++ b/test/promotional-campaigns.test.js @@ -0,0 +1,573 @@ +// test/promotional-campaigns.test.js - Tests for WhatsApp opt-in event marketing campaigns, audience targeting, approval, and safe dispatch simulation. +import { test, before, after } from 'node:test'; +import assert from 'node:assert/strict'; +import { db, resetDb, startServer, stopServer, Client, signedInClient } from './helpers.js'; +import { recordConsent, getConsents, hasConsent, addSuppression, isSuppressed } from '../lib/services/communication-consent.js'; +import { + queryEligibleAudience, + previewCampaignAudience, + createCampaign, + getCampaign, + listCampaigns, + approveCampaign, + cancelCampaign, + dispatchCampaign, + getCampaignLogs, + ESTIMATED_MARKETING_COST_PAISE +} from '../lib/services/promotional-campaign.js'; +import { + evaluateOutreachDecision, + buildCampaignTrackingUrl, + RELATIONSHIP_TYPES, + CONTACT_SOURCES, + PERSONAL_OUTREACH_GUIDES +} from '../lib/services/outreach-strategy.js'; +import { createSession, createSessionToken, csrfTokenFor } from '../lib/session.js'; + +let organiserUser; +let attendeeUserA; // opted in +let attendeeUserB; // opted out +let attendeeUserC; // suppressed +let otherOrganiser; +let testEventA; +let testEventB; + +before(async () => { + await resetDb(); + await startServer(); + + // Create organiser user + const { rows: orgRows } = await db.query( + `INSERT INTO users (alias, phone, status, age_confirmed_21, age_confirmed_at, organiser_enabled) + VALUES ('Host Arvind', '+919876500001', 'active', true, now(), true) + RETURNING *` + ); + organiserUser = orgRows[0]; + + // Create another organiser + const { rows: otherOrgRows } = await db.query( + `INSERT INTO users (alias, phone, status, age_confirmed_21, age_confirmed_at, organiser_enabled) + VALUES ('Host Maya', '+919876500002', 'active', true, now(), true) + RETURNING *` + ); + otherOrganiser = otherOrgRows[0]; + + // Create Attendee A (Chennai, Nightlife interest, Opted into promotional WhatsApp) + const { rows: userARows } = await db.query( + `INSERT INTO users (alias, phone, city, interests, status, age_confirmed_21, age_confirmed_at) + VALUES ('Karthik', '+919876500010', 'Chennai', ARRAY['nightlife', 'music'], 'active', true, now()) + RETURNING *` + ); + attendeeUserA = userARows[0]; + + await recordConsent({ + userId: attendeeUserA.id, + channel: 'whatsapp', + purpose: 'transactional', + status: 'opted_in', + source: 'registration' + }); + + await recordConsent({ + userId: attendeeUserA.id, + channel: 'whatsapp', + purpose: 'promotional', + status: 'opted_in', + source: 'registration' + }); + + // Create Attendee B (Chennai, Opted OUT of promotional WhatsApp) + const { rows: userBRows } = await db.query( + `INSERT INTO users (alias, phone, city, interests, status, age_confirmed_21, age_confirmed_at) + VALUES ('Deepa', '+919876500020', 'Chennai', ARRAY['nightlife'], 'active', true, now()) + RETURNING *` + ); + attendeeUserB = userBRows[0]; + + await recordConsent({ + userId: attendeeUserB.id, + channel: 'whatsapp', + purpose: 'transactional', + status: 'opted_in', + source: 'registration' + }); + + await recordConsent({ + userId: attendeeUserB.id, + channel: 'whatsapp', + purpose: 'promotional', + status: 'opted_out', // Explicitly opted out + source: 'registration' + }); + + // Create Attendee C (Bengaluru, Opted IN but number SUPPRESSED) + const { rows: userCRows } = await db.query( + `INSERT INTO users (alias, phone, city, interests, status, age_confirmed_21, age_confirmed_at) + VALUES ('Rahul', '+919876500030', 'Bengaluru', ARRAY['nightlife', 'meetup'], 'active', true, now()) + RETURNING *` + ); + attendeeUserC = userCRows[0]; + + await recordConsent({ + userId: attendeeUserC.id, + channel: 'whatsapp', + purpose: 'promotional', + status: 'opted_in', + source: 'profile_settings' + }); + + await addSuppression({ + channel: 'whatsapp', + destination: attendeeUserC.phone, + reason: 'keyword_opt_out' + }); + + // Create test events + const { rows: eventARows } = await db.query( + `INSERT INTO events ( + title, slug, city, category, capacity, start_at, end_at, status, organiser_user_id + ) VALUES ( + 'Neon Rooftop Mixer', 'neon-rooftop-mixer-chn', 'Chennai', 'nightlife', 50, + now() + interval '3 days', now() + interval '3 days 4 hours', 'published', $1 + ) RETURNING *`, + [organiserUser.id] + ); + testEventA = eventARows[0]; + + const { rows: eventBRows } = await db.query( + `INSERT INTO events ( + title, slug, city, category, capacity, start_at, end_at, status, organiser_user_id + ) VALUES ( + 'Secret Jazz Supper Club', 'secret-jazz-supper-blr', 'Bengaluru', 'dinner_club', 30, + now() + interval '5 days', now() + interval '5 days 3 hours', 'published', $1 + ) RETURNING *`, + [otherOrganiser.id] + ); + testEventB = eventBRows[0]; +}); + +after(stopServer); + +test('1. Marketing consent separation and defaults: transactional defaults to true, promotional defaults to false', async () => { + // New user with no records in communication_consents + const { rows: freshUserRows } = await db.query( + `INSERT INTO users (alias, phone, status, age_confirmed_21) + VALUES ('Sneha', '+919876500099', 'active', true) RETURNING *` + ); + const freshUser = freshUserRows[0]; + + // Transactional essential notifications: true + const transactionalConsent = await hasConsent({ userId: freshUser.id, channel: 'whatsapp', purpose: 'transactional' }); + assert.equal(transactionalConsent, true, 'transactional notifications should default to true for booking confirmations'); + + // Promotional marketing messages: FAIL-CLOSED FALSE + const promotionalConsent = await hasConsent({ userId: freshUser.id, channel: 'whatsapp', purpose: 'promotional' }); + assert.equal(promotionalConsent, false, 'promotional marketing must be fail-closed false when no consent record exists'); + + // getConsents returns explicit matrix + const matrix = await getConsents(freshUser.id); + assert.equal(matrix.whatsapp.transactional, true); + assert.equal(matrix.whatsapp.promotional, false); +}); + +test('2. Audience targeting: strictly queries opted-in users and excludes opted-out, suppressed, or non-consenting users', async () => { + // All eligible users across platform + const allAudience = await queryEligibleAudience(); + const audienceIds = allAudience.map((u) => u.id); + + // Must include attendeeUserA (opted in, not suppressed) + assert.ok(audienceIds.includes(attendeeUserA.id), 'attendeeUserA must be included'); + + // Must EXCLUDE attendeeUserB (opted out) + assert.ok(!audienceIds.includes(attendeeUserB.id), 'attendeeUserB must be excluded because opted out'); + + // Must EXCLUDE attendeeUserC (suppressed) + assert.ok(!audienceIds.includes(attendeeUserC.id), 'attendeeUserC must be excluded because phone is suppressed'); + + // Filter by City: Chennai + const chennaiAudience = await queryEligibleAudience({ targetCity: 'Chennai' }); + assert.ok(chennaiAudience.some((u) => u.id === attendeeUserA.id)); + + // Filter by City: Hyderabad (zero opted-in users in Hyderabad in our seed) + const hydAudience = await queryEligibleAudience({ targetCity: 'Hyderabad' }); + assert.equal(hydAudience.length, 0); + + // Filter by Category: nightlife + const nightlifeAudience = await queryEligibleAudience({ targetCategory: 'nightlife' }); + assert.ok(nightlifeAudience.some((u) => u.id === attendeeUserA.id)); + + // Filter by Category: weekend_trip (attendeeUserA has nightlife/music, not weekend_trip) + const tripAudience = await queryEligibleAudience({ targetCategory: 'weekend_trip' }); + assert.equal(tripAudience.length, 0); +}); + +test('3. Audience preview: calculates count, estimated cost (80 paise), and official template preview', async () => { + const preview = await previewCampaignAudience({ + eventId: testEventA.id, + targetCity: 'Chennai', + targetCategory: 'nightlife' + }); + + assert.equal(preview.ok, true); + assert.equal(preview.eventId, testEventA.id); + assert.equal(preview.eventTitle, testEventA.title); + assert.equal(preview.appliedFilters.targetCity, 'Chennai'); + assert.equal(preview.appliedFilters.targetCategory, 'nightlife'); + assert.equal(preview.eligibleRecipientsCount, 1); + assert.equal(preview.estimatedCostPaise, 80); + assert.equal(preview.estimatedCostRupees, '0.80'); + + // PII masking check + assert.equal(preview.sampleRecipientsMasked.length, 1); + assert.equal(preview.sampleRecipientsMasked[0].phoneMasked, '+91 98****0010'); + assert.ok(!preview.sampleRecipientsMasked[0].phoneMasked.includes('500010'), 'phone must be masked in preview'); + + // Template components check + assert.equal(preview.templatePreview.templateName, 'nightlifez_promotional_event_v1'); + assert.equal(preview.templatePreview.category, 'MARKETING'); + assert.equal(preview.templatePreview.header, 'NIGHTLIFEZ EXCLUSIVE'); + assert.ok(preview.templatePreview.body.includes('Neon Rooftop Mixer')); + assert.ok(preview.templatePreview.body.includes('Chennai')); + assert.equal(preview.templatePreview.buttons.length, 2); + assert.equal(preview.templatePreview.buttons[1].label, 'Text STOP to opt out'); +}); + +test('4. Campaign lifecycle: create draft, approve, and prevent illegal transitions', async () => { + const campaign = await createCampaign({ + eventId: testEventA.id, + createdByUserId: organiserUser.id, + title: 'Neon Rooftop Chennai Launch Promotion', + targetCity: 'Chennai', + targetCategory: 'nightlife' + }); + + assert.equal(campaign.title, 'Neon Rooftop Chennai Launch Promotion'); + assert.equal(campaign.status, 'draft'); + assert.equal(campaign.channel, 'whatsapp'); + assert.equal(campaign.estimated_recipients, 1); + assert.equal(campaign.estimated_cost_paise, 80); + + // Approve campaign + const approved = await approveCampaign({ + campaignId: campaign.id, + approvedByUserId: organiserUser.id + }); + assert.equal(approved.status, 'approved'); + assert.equal(approved.approved_by_user_id, organiserUser.id); + assert.ok(approved.approved_at); + + // Listing campaigns for event + const list = await listCampaigns({ eventId: testEventA.id, userId: organiserUser.id }); + assert.ok(list.length >= 1); + assert.equal(list[0].id, campaign.id); +}); + +test('5. Safe Simulated Dispatch Gate: when live sending is false, campaign runs in dry-run simulation mode', async () => { + // Ensure ENABLE_LIVE_PROMOTIONAL_CAMPAIGNS is not 'true' + const prevEnv = process.env.ENABLE_LIVE_PROMOTIONAL_CAMPAIGNS; + delete process.env.ENABLE_LIVE_PROMOTIONAL_CAMPAIGNS; + + const campaign = await createCampaign({ + eventId: testEventA.id, + createdByUserId: organiserUser.id, + title: 'Dry Run Simulation Campaign', + targetCity: 'Chennai', + targetCategory: 'nightlife' + }); + await approveCampaign({ campaignId: campaign.id, approvedByUserId: organiserUser.id }); + + // Dispatch campaign + const dispatchRes = await dispatchCampaign({ + campaignId: campaign.id, + triggeredByUserId: organiserUser.id + }); + + assert.equal(dispatchRes.ok, true); + assert.equal(dispatchRes.simulated, true); + assert.equal(dispatchRes.recipientsCount, 1); + assert.equal(dispatchRes.costPaise, 80); + assert.equal(dispatchRes.costRupees, '0.80'); + assert.ok(dispatchRes.message.includes('disabled by platform policy')); + + // Verify campaign row + const updatedCampaign = await getCampaign({ campaignId: campaign.id }); + assert.equal(updatedCampaign.status, 'completed'); + assert.equal(updatedCampaign.actual_recipients, 1); + assert.equal(updatedCampaign.actual_cost_paise, 80); + assert.equal(updatedCampaign.audit_metadata.simulated, true); + + // Verify recipient delivery log + const logs = await getCampaignLogs({ campaignId: campaign.id }); + assert.equal(logs.length, 1); + assert.equal(logs[0].phoneMasked, '+91 98****0010'); + assert.equal(logs[0].status, 'dispatched'); + assert.equal(logs[0].deliveryCostPaise, 80); + + // Restore env + if (prevEnv !== undefined) process.env.ENABLE_LIVE_PROMOTIONAL_CAMPAIGNS = prevEnv; +}); + +test('6. Unsubscribe and suppression handling: STOP or unsubscribe endpoint withdraws consent and suppresses number', async () => { + // Create user who initially opts in + const { rows } = await db.query( + `INSERT INTO users (alias, phone, status, age_confirmed_21) + VALUES ('Vikas', '+919876500077', 'active', true) RETURNING *` + ); + const vikas = rows[0]; + + await recordConsent({ + userId: vikas.id, + channel: 'whatsapp', + purpose: 'promotional', + status: 'opted_in', + source: 'registration' + }); + + assert.equal(await hasConsent({ userId: vikas.id, channel: 'whatsapp', purpose: 'promotional' }), true); + + // Simulate user calling unsubscribe endpoint + const unsubClient = new Client(); + const unsubRes = await unsubClient.post('/api/notifications/unsubscribe', { + phone: '+919876500077', + channel: 'whatsapp', + reason: 'user_opt_out' + }); + + assert.equal(unsubRes.status, 200); + assert.equal(unsubRes.json.ok, true); + + // Check consent is now false + const hasPromoAfter = await hasConsent({ userId: vikas.id, channel: 'whatsapp', purpose: 'promotional' }); + assert.equal(hasPromoAfter, false, 'user must no longer have promotional consent after unsubscribe'); + + // Check number is suppressed + const suppressed = await isSuppressed({ destination: '+919876500077', channel: 'whatsapp' }); + assert.equal(suppressed, true, 'phone number must be on the suppression list'); + + // Essential transactional consent must remain intact + const hasTrans = await hasConsent({ userId: vikas.id, channel: 'whatsapp', purpose: 'transactional' }); + assert.equal(hasTrans, true, 'transactional consent must remain active'); +}); + +test('7. Multi-tenant RBAC: Organiser B cannot view, create, or dispatch campaigns for Organiser A event', async () => { + // Organiser B signs in + const clientB = await signedInClient(); + await db.query(`UPDATE users SET organiser_enabled = true WHERE id = $1`, [clientB.userId]); + + // Organiser B attempts to preview event A + const previewRes = await clientB.post('/api/campaigns/preview', { + eventId: testEventA.id, + targetCity: 'Chennai' + }); + assert.equal(previewRes.status, 404, 'cross-organiser access should return 404 Not Found'); + + // Organiser B attempts to create campaign on event A + const createRes = await clientB.post('/api/campaigns', { + eventId: testEventA.id, + title: 'Hacked Campaign' + }); + assert.equal(createRes.status, 404, 'cross-organiser campaign creation must be blocked with 404'); +}); + +test('8. Personal vs automated outreach decision framework: strictly enforces partner, influencer, and consent boundaries', async () => { + // Scenario A: Rafiky / Community Owner -> Must be routed to PERSONAL OUTREACH, never automated broadcast + const rafikyDecision = evaluateOutreachDecision({ + name: 'Rafiky', + relationshipType: RELATIONSHIP_TYPES.COMMUNITY_OWNER, + source: CONTACT_SOURCES.DIRECT_INQUIRY, + hasExplicitMarketingConsent: false + }); + assert.equal(rafikyDecision.decision, 'PERSONAL_OUTREACH'); + assert.equal(rafikyDecision.channel, 'manual_direct'); + assert.equal(rafikyDecision.eligibleForAutomatedCampaign, false, 'Partners must never be put into automated bulk broadcasts'); + assert.equal(rafikyDecision.eligibleForPersonalOutreach, true); + assert.ok(rafikyDecision.reason.includes('Rafiky')); + assert.ok(PERSONAL_OUTREACH_GUIDES.community_owner.sampleTemplate('Rafiky').includes('Rafiky')); + + // Scenario B: Brand Sponsor / Venue Partner -> Personal Outreach + const sponsorDecision = evaluateOutreachDecision({ + name: 'Red Bull India', + relationshipType: RELATIONSHIP_TYPES.SPONSOR, + source: CONTACT_SOURCES.PARTNER_APPLICATION + }); + assert.equal(sponsorDecision.decision, 'PERSONAL_OUTREACH'); + assert.equal(sponsorDecision.eligibleForAutomatedCampaign, false); + + // Scenario C: Instagram Follower / Scraped Contact -> STRICTLY PROHIBITED + const instagramDecision = evaluateOutreachDecision({ + name: 'IG Follower', + relationshipType: RELATIONSHIP_TYPES.ATTENDEE, + source: CONTACT_SOURCES.INSTAGRAM_FOLLOW, + hasExplicitMarketingConsent: false + }); + assert.equal(instagramDecision.decision, 'PROHIBITED'); + assert.equal(instagramDecision.eligibleForAutomatedCampaign, false); + assert.equal(instagramDecision.eligibleForPersonalOutreach, false); + assert.equal(instagramDecision.action, 'DROP_CONTACT'); + + // Scenario D: Previous Ticket Buyer or OTP recipient without explicit promotional consent -> NO PROMOTIONAL MESSAGE (No inferred consent) + const inferredBuyerDecision = evaluateOutreachDecision({ + name: 'Past Attendee', + relationshipType: RELATIONSHIP_TYPES.ATTENDEE, + source: CONTACT_SOURCES.PURCHASE_HISTORY, + hasExplicitMarketingConsent: false + }); + assert.equal(inferredBuyerDecision.decision, 'NO_PROMOTIONAL_MESSAGE'); + assert.equal(inferredBuyerDecision.eligibleForAutomatedCampaign, false); + + // Scenario E: Existing NIGHTLIFEZ member with verified marketing consent -> AUTOMATED OUTREACH + const consentedUserDecision = evaluateOutreachDecision({ + name: 'Consenting Member', + relationshipType: RELATIONSHIP_TYPES.REGISTERED_USER, + source: CONTACT_SOURCES.SIGNUP_OPTIN, + hasExplicitMarketingConsent: true, + isRegisteredUser: true + }); + assert.equal(consentedUserDecision.decision, 'AUTOMATED_OUTREACH'); + assert.equal(consentedUserDecision.eligibleForAutomatedCampaign, true); + assert.equal(consentedUserDecision.channel, 'whatsapp_campaign'); + + // Scenario F: Ambiguous / Unclear Consent -> FAIL-CLOSED EXCLUDE + const unclearDecision = evaluateOutreachDecision({ + name: 'Ambiguous Contact', + relationshipType: RELATIONSHIP_TYPES.REGISTERED_USER, + hasExplicitMarketingConsent: null, // unclear + isRegisteredUser: true + }); + assert.equal(unclearDecision.decision, 'UNCLEAR_ELIGIBILITY_EXCLUDE'); + assert.equal(unclearDecision.eligibleForAutomatedCampaign, false); + assert.equal(unclearDecision.action, 'EXCLUDE'); +}); + +test('9. Campaign referral link generation and UTM parameter tracking', async () => { + const trackingUrl = buildCampaignTrackingUrl({ + baseUrl: 'https://nightlifez.com', + eventSlug: 'secret-rooftop-rave', + campaignId: '99999999-9999-9999-9999-999999999999', + channel: 'whatsapp', + medium: 'campaign', + refCode: 'wa_promo' + }); + + const parsed = new URL(trackingUrl); + assert.equal(parsed.origin, 'https://nightlifez.com'); + assert.equal(parsed.pathname, '/events/secret-rooftop-rave'); + assert.equal(parsed.searchParams.get('utm_source'), 'whatsapp'); + assert.equal(parsed.searchParams.get('utm_medium'), 'campaign'); + assert.equal(parsed.searchParams.get('utm_campaign'), '99999999-9999-9999-9999-999999999999'); + assert.equal(parsed.searchParams.get('ref'), 'wa_promo'); +}); + +test('10. Idempotency & duplicate dispatch safety: re-dispatching campaign does not duplicate recipient logs', async () => { + const campaign = await createCampaign({ + eventId: testEventA.id, + createdByUserId: organiserUser.id, + title: 'Idempotency Test Campaign', + targetCity: 'Chennai' + }); + await approveCampaign({ campaignId: campaign.id, approvedByUserId: organiserUser.id }); + + // First dispatch + const res1 = await dispatchCampaign({ campaignId: campaign.id, triggeredByUserId: organiserUser.id }); + assert.equal(res1.ok, true); + + const logs1 = await getCampaignLogs({ campaignId: campaign.id }); + assert.equal(logs1.length, 1); + + // Subsequent dispatch attempt on already completed campaign must be rejected + await assert.rejects( + async () => { + await dispatchCampaign({ campaignId: campaign.id, triggeredByUserId: organiserUser.id }); + }, + (err) => err.status === 400 && err.code === 'invalid_status' + ); +}); + +test('11. Dynamic and configurable marketing pricing via WHATSAPP_MARKETING_RATE_PAISE', async () => { + const prevRate = process.env.WHATSAPP_MARKETING_RATE_PAISE; + try { + // Set custom Meta marketing rate to 92 paise + process.env.WHATSAPP_MARKETING_RATE_PAISE = '92'; + + const preview = await previewCampaignAudience({ + eventId: testEventA.id, + targetCity: 'Chennai', + targetCategory: 'nightlife' + }); + + assert.equal(preview.ratePerRecipientPaise, 92); + assert.equal(preview.ratePerRecipientRupees, '0.92'); + assert.equal(preview.estimatedCostPaise, 92 * preview.eligibleRecipientsCount); + assert.equal(preview.isEstimate, true); + assert.ok(preview.pricingDisclaimer.includes('Meta Cloud API marketing conversation pricing')); + } finally { + if (prevRate !== undefined) process.env.WHATSAPP_MARKETING_RATE_PAISE = prevRate; + else delete process.env.WHATSAPP_MARKETING_RATE_PAISE; + } +}); + +test('12. Concurrent dispatch race protection: atomic check-and-set blocks second caller with 400 invalid_status', async () => { + const campaign = await createCampaign({ + eventId: testEventA.id, + createdByUserId: organiserUser.id, + title: 'Race Condition Test Campaign', + targetCity: 'Chennai' + }); + await approveCampaign({ campaignId: campaign.id, approvedByUserId: organiserUser.id }); + + // Simulate two simultaneous dispatch attempts + const [attemptA, attemptB] = await Promise.allSettled([ + dispatchCampaign({ campaignId: campaign.id, triggeredByUserId: organiserUser.id }), + dispatchCampaign({ campaignId: campaign.id, triggeredByUserId: organiserUser.id }) + ]); + + // Exactly one must succeed, and one must fail + const fulfilled = [attemptA, attemptB].filter((r) => r.status === 'fulfilled'); + const rejected = [attemptA, attemptB].filter((r) => r.status === 'rejected'); + + assert.equal(fulfilled.length, 1, 'exactly one dispatch must succeed'); + assert.equal(rejected.length, 1, 'concurrent second dispatch must be rejected'); + assert.equal(rejected[0].reason.status, 400); +}); + +test('13. Unsubscribe race guard: mid-dispatch suppression or revoked consent excludes recipient', async () => { + // Create user who opts in + const { rows } = await db.query( + `INSERT INTO users (alias, phone, city, status, age_confirmed_21) + VALUES ('RaceUser', '+919876599999', 'Chennai', 'active', true) RETURNING *` + ); + const raceUser = rows[0]; + + await recordConsent({ + userId: raceUser.id, + channel: 'whatsapp', + purpose: 'promotional', + status: 'opted_in', + source: 'registration' + }); + + const campaign = await createCampaign({ + eventId: testEventA.id, + createdByUserId: organiserUser.id, + title: 'Mid-Dispatch Race Test Campaign', + targetCity: 'Chennai' + }); + await approveCampaign({ campaignId: campaign.id, approvedByUserId: organiserUser.id }); + + // Simulate user revoking consent right before dispatch loop processes them + await recordConsent({ + userId: raceUser.id, + channel: 'whatsapp', + purpose: 'promotional', + status: 'opted_out', + source: 'profile_settings' + }); + + const dispatchRes = await dispatchCampaign({ campaignId: campaign.id, triggeredByUserId: organiserUser.id }); + assert.equal(dispatchRes.ok, true); + + // Recipient logs must not contain raceUser + const logs = await getCampaignLogs({ campaignId: campaign.id }); + const recipientDestinations = logs.map((l) => l.phoneMasked); + assert.ok(!recipientDestinations.includes('+91 98****9999'), 'raceUser must not receive dispatch after revoking consent'); +}); diff --git a/test/whatsapp-api.test.js b/test/whatsapp-api.test.js new file mode 100644 index 0000000..84333e0 --- /dev/null +++ b/test/whatsapp-api.test.js @@ -0,0 +1,338 @@ +// test/whatsapp-api.test.js - End-to-end HTTP tests for WhatsApp OTP auth, account linking, webhooks, preferences, and admin telemetry. +import { test, before, after, beforeEach } from 'node:test'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import { resetDb, startServer, stopServer, Client, makeInitData, db } from './helpers.js'; +import { getWhatsAppProvider } from '../lib/services/whatsapp-provider.js'; + +before(async () => { + await resetDb(); + await startServer(); +}); + +after(stopServer); + +beforeEach(() => { + getWhatsAppProvider().clearSentMessages(); +}); + +test('WhatsApp Auth API - complete OTP signup lifecycle', async () => { + const c = new Client(); + const phone = '+919876543210'; + + // 1. Request OTP + const r1 = await c.post('/api/auth/whatsapp/otp', { + phone, + promotionalOptIn: true + }); + + assert.equal(r1.status, 200); + assert.equal(r1.json.ok, true); + assert.ok(r1.json.challengeId); + assert.equal(r1.json.phoneMasked, '+91 98****3210'); + assert.equal(typeof r1.json.resendAfterSeconds, 'number'); + + // Verify stub provider received OTP + const sent = getWhatsAppProvider().getSentMessages(); + assert.equal(sent.length, 1); + const otpCode = sent[0].otp; + assert.ok(otpCode); + + // 2. Verify OTP and establish session + const r2 = await c.post('/api/auth/whatsapp/verify', { + challengeId: r1.json.challengeId, + phone, + code: otpCode, + promotionalOptIn: true + }); + + assert.equal(r2.status, 200); + assert.equal(r2.json.ok, true); + assert.equal(r2.json.isNewUser, true); + assert.ok(r2.json.csrf); + assert.equal(r2.json.user.ageConfirmed, true); + + // Check session cookie + const setCookie = r2.headers.getSetCookie().join('\n'); + assert.match(setCookie, /sm_session=/); + + // 3. GET /api/me works with this session + const me = await c.get('/api/me'); + assert.equal(me.status, 200); + assert.equal(me.json.user.ageConfirmed, true); + + // 4. GET /api/me/identities shows WhatsApp linked, Telegram unlinked + const identities = await c.get('/api/me/identities'); + assert.equal(identities.status, 200); + assert.equal(identities.json.identities.whatsapp.linked, true); + assert.equal(identities.json.identities.whatsapp.phoneMasked, '+91 98****3210'); + assert.equal(identities.json.identities.telegram.linked, false); +}); + +test('WhatsApp Auth API - account linking & sole-provider unlinking guard', async () => { + // 1. Sign in via Telegram + const tgClient = new Client(); + const tgUser = { id: 778899, first_name: 'LinkTester' }; + const authRes = await tgClient.post('/api/auth/telegram', { + initData: makeInitData(tgUser), + ageConfirmed: true + }); + assert.equal(authRes.status, 200); + tgClient.csrf = authRes.json.csrf; + + // 2. Request OTP to link WhatsApp + const phone = '+919123456789'; + const otpRes = await tgClient.post('/api/auth/whatsapp/otp', { phone }); + assert.equal(otpRes.status, 200); + + const sent = getWhatsAppProvider().getSentMessages(); + const otpCode = sent[sent.length - 1].otp; + + // 3. Link WhatsApp to signed-in user + const linkRes = await tgClient.post('/api/auth/whatsapp/link', { + challengeId: otpRes.json.challengeId, + phone, + code: otpCode + }); + assert.equal(linkRes.status, 200); + assert.equal(linkRes.json.ok, true); + + // Both should be linked now + const idRes = await tgClient.get('/api/me/identities'); + assert.equal(idRes.json.identities.telegram.linked, true); + assert.equal(idRes.json.identities.whatsapp.linked, true); + + // 4. Unlink WhatsApp succeeds because Telegram remains + const unlinkRes = await tgClient.post('/api/auth/whatsapp/unlink', { phone }); + assert.equal(unlinkRes.status, 200); + assert.equal(unlinkRes.json.ok, true); + + // Re-verify identities + const idResAfter = await tgClient.get('/api/me/identities'); + assert.equal(idResAfter.json.identities.whatsapp.linked, false); + assert.equal(idResAfter.json.identities.telegram.linked, true); + + // Now create a WhatsApp-only client and test sole-provider guard + const waOnly = new Client(); + const waReq = await waOnly.post('/api/auth/whatsapp/otp', { phone: '+919988776655' }); + const waOtp = getWhatsAppProvider().getSentMessages().slice(-1)[0].otp; + const waAuth = await waOnly.post('/api/auth/whatsapp/verify', { + challengeId: waReq.json.challengeId, + phone: '+919988776655', + code: waOtp + }); + waOnly.csrf = waAuth.json.csrf; + + // Attempt to unlink sole provider -> must fail + const failedUnlink = await waOnly.post('/api/auth/whatsapp/unlink', { phone: '+919988776655' }); + assert.equal(failedUnlink.status, 400); + assert.match(failedUnlink.json.message, /only login method/i); +}); + +test('WhatsApp Auth API - communication preferences GET and PATCH', async () => { + const c = new Client(); + const phone = '+919555112233'; + const req = await c.post('/api/auth/whatsapp/otp', { phone }); + const otp = getWhatsAppProvider().getSentMessages().slice(-1)[0].otp; + const auth = await c.post('/api/auth/whatsapp/verify', { + challengeId: req.json.challengeId, + phone, + code: otp, + promotionalOptIn: true + }); + c.csrf = auth.json.csrf; + + // GET preferences + const getPref = await c.get('/api/me/communication-preferences'); + assert.equal(getPref.status, 200); + assert.equal(getPref.json.preferences.whatsapp.transactional, true); + assert.equal(getPref.json.preferences.whatsapp.promotional, true); + + // PATCH preferences (opt out of promotional) + const patchPref = await c.patch('/api/me/communication-preferences', { + channel: 'whatsapp', + purpose: 'promotional', + status: 'opted_out' + }); + assert.equal(patchPref.status, 200); + assert.equal(patchPref.json.preferences.whatsapp.promotional, false); + assert.equal(patchPref.json.preferences.whatsapp.transactional, true); +}); + +test('WhatsApp Webhooks - challenge verification and receipt ingestion', async () => { + const c = new Client(); + + // 1. GET Challenge verification + const verifyRes = await c.get('/api/webhooks/whatsapp?hub.mode=subscribe&hub.verify_token=nightlifez_webhook_verify_token&hub.challenge=test_challenge_abc123'); + assert.equal(verifyRes.status, 200); + assert.equal(verifyRes.text, 'test_challenge_abc123'); + + // 2. Reject bad verify token + const badVerify = await c.get('/api/webhooks/whatsapp?hub.mode=subscribe&hub.verify_token=wrong_token&hub.challenge=test'); + assert.equal(badVerify.status, 403); + + // 3. Ingest message status receipt + const receiptPayload = { + object: 'whatsapp_business_account', + entry: [ + { + id: '123456789', + changes: [ + { + value: { + messaging_product: 'whatsapp', + metadata: { display_phone_number: '123', phone_number_id: '456' }, + statuses: [ + { + id: 'wamid.test_status_123', + status: 'delivered', + timestamp: Math.floor(Date.now() / 1000).toString(), + recipient_id: '919876543210' + } + ] + }, + field: 'messages' + } + ] + } + ] + }; + + const rawJson = JSON.stringify(receiptPayload); + const secret = process.env.WHATSAPP_WEBHOOK_SECRET || 'test_whatsapp_webhook_secret'; + const sig = 'sha256=' + crypto.createHmac('sha256', secret).update(rawJson).digest('hex'); + + const webhookRes = await c.post('/api/webhooks/whatsapp', receiptPayload, { + 'x-hub-signature-256': sig + }); + assert.equal(webhookRes.status, 200); + assert.equal(webhookRes.json.ok, true); + + // 4. Ingest incoming STOP keyword from user + const stopPayload = { + object: 'whatsapp_business_account', + entry: [ + { + id: '123456789', + changes: [ + { + value: { + messaging_product: 'whatsapp', + messages: [ + { + from: '919876543210', + id: 'wamid.inbound_stop_123', + timestamp: Math.floor(Date.now() / 1000).toString(), + text: { body: 'STOP' }, + type: 'text' + } + ] + }, + field: 'messages' + } + ] + } + ] + }; + + const stopRawJson = JSON.stringify(stopPayload); + const stopSig = 'sha256=' + crypto.createHmac('sha256', secret).update(stopRawJson).digest('hex'); + + const stopRes = await c.post('/api/webhooks/whatsapp', stopPayload, { + 'x-hub-signature-256': stopSig + }); + assert.equal(stopRes.status, 200); + + // Verify phone is added to suppression list + const supp = (await db.query(`SELECT * FROM notification_suppressions WHERE destination = '+919876543210'`)).rows[0]; + assert.ok(supp); + assert.equal(supp.reason, 'keyword_opt_out'); +}); + +test('Admin Notifications Telemetry - RBAC and masked PII', async () => { + // 1. Unauthenticated request -> 401 + const anon = new Client(); + const unauth = await anon.get('/api/admin/notifications/health'); + assert.equal(unauth.status, 401); + + // 2. Regular user (guest) request -> 403 Forbidden + const guestClient = new Client(); + const req = await guestClient.post('/api/auth/whatsapp/otp', { phone: '+919111222333' }); + const otp = getWhatsAppProvider().getSentMessages().slice(-1)[0].otp; + await guestClient.post('/api/auth/whatsapp/verify', { + challengeId: req.json.challengeId, + phone: '+919111222333', + code: otp + }); + + const guestHealth = await guestClient.get('/api/admin/notifications/health'); + assert.equal(guestHealth.status, 403); + + // 3. Super Admin request -> 200 OK + const adminClient = new Client(); + await adminClient.post('/api/auth/telegram', { + initData: makeInitData({ id: 900000001, first_name: 'SuperAdmin' }), // ADMIN_BOOTSTRAP_TELEGRAM_ID + ageConfirmed: true + }); + + const health = await adminClient.get('/api/admin/notifications/health'); + assert.equal(health.status, 200); + assert.ok(health.json.whatsapp); + assert.equal(health.json.whatsapp.mode, 'safe_mock_adapter'); + + const stats = await adminClient.get('/api/admin/notifications/stats'); + assert.equal(stats.status, 200); + assert.ok(stats.json.telemetry.otp); + assert.ok(stats.json.telemetry.messages); + + const messages = await adminClient.get('/api/admin/notifications/messages'); + assert.equal(messages.status, 200); + assert.ok(Array.isArray(messages.json.messages)); + + const suppressions = await adminClient.get('/api/admin/notifications/suppressions'); + assert.equal(suppressions.status, 200); + assert.ok(Array.isArray(suppressions.json.suppressions)); + if (suppressions.json.suppressions.length > 0) { + assert.ok(suppressions.json.suppressions[0].destinationMasked.includes('****')); + } +}); + +test('UI Rendering - /signin and /me pages conform to modern web standards', async () => { + const c = new Client(); + const signinPage = await c.get('/signin'); + assert.equal(signinPage.status, 200); + + // 1. Auth switcher tabs + assert.match(signinPage.text, /data-auth-tab="whatsapp"/); + assert.match(signinPage.text, /data-auth-tab="telegram"/); + + // 2. WhatsApp phone form + assert.match(signinPage.text, /data-wa-phone-form/); + assert.match(signinPage.text, /data-wa-submit-phone/); + + // 3. Modern Web Guidance compliance for SMS OTP form + assert.match(signinPage.text, /id="otp-form"/); + assert.match(signinPage.text, /id="otp-input"/); + assert.match(signinPage.text, /inputmode="numeric"/); + assert.match(signinPage.text, /autocomplete="one-time-code"/); + assert.match(signinPage.text, /pattern="\\d\{6\}"/); + assert.match(signinPage.text, /aria-describedby="otp-format-hint"/); + assert.match(signinPage.text, /id="otp-format-hint"/); + assert.match(signinPage.text, /data-wa-resend-btn/); + assert.match(signinPage.text, /data-wa-change-phone/); + + // 4. Attendee hub /me page has account settings tab when signed in + const req = await c.post('/api/auth/whatsapp/otp', { phone: '+919999988888' }); + const otp = getWhatsAppProvider().getSentMessages().slice(-1)[0].otp; + await c.post('/api/auth/whatsapp/verify', { + challengeId: req.json.challengeId, + phone: '+919999988888', + code: otp + }); + + const mePage = await c.get('/me'); + assert.equal(mePage.status, 200); + assert.match(mePage.text, /data-hub-tab="account"/); + assert.match(mePage.text, /data-account-settings/); +}); + diff --git a/test/whatsapp-auth.test.js b/test/whatsapp-auth.test.js new file mode 100644 index 0000000..6dfaee3 --- /dev/null +++ b/test/whatsapp-auth.test.js @@ -0,0 +1,160 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { db, resetDb } from './helpers.js'; +import { + requestWhatsAppOtp, + verifyWhatsAppOtpAndResolveUser, + unlinkWhatsAppIdentity, + getLinkedIdentities +} from '../lib/services/whatsapp-auth.js'; +import { getWhatsAppProvider } from '../lib/services/whatsapp-provider.js'; +import { hasConsent } from '../lib/services/communication-consent.js'; + +test.beforeEach(async () => { + await resetDb(); + getWhatsAppProvider().clearSentMessages(); +}); + +test('WhatsApp Auth - new user registration via WhatsApp OTP', async () => { + const phone = '+919876543210'; + const req = await requestWhatsAppOtp({ phone, ip: '192.168.1.10', promotionalOptIn: true }); + + assert.equal(req.ok, true); + assert.ok(req.challengeId); + assert.equal(req.phoneMasked, '+91 98****3210'); + + // Verify OTP from stub provider + const sent = getWhatsAppProvider().getSentMessages(); + assert.equal(sent.length, 1); + const otp = sent[0].otp; + + const auth = await verifyWhatsAppOtpAndResolveUser({ + challengeId: req.challengeId, + phone, + code: otp, + ip: '192.168.1.10', + promotionalOptIn: true + }); + + assert.equal(auth.ok, true); + assert.equal(auth.isNewUser, true); + assert.ok(auth.user.id); + assert.equal(auth.user.phone, phone); + assert.equal(auth.user.age_confirmed_21, true); + + // Identity should exist in user_identities + const identity = (await db.query(`SELECT * FROM user_identities WHERE user_id = $1 AND provider = 'phone'`, [auth.user.id])).rows[0]; + assert.ok(identity); + assert.equal(identity.subject, phone); + + // Consents: both transactional and promotional should be opted in + assert.equal(await hasConsent({ userId: auth.user.id, channel: 'whatsapp', purpose: 'transactional' }), true); + assert.equal(await hasConsent({ userId: auth.user.id, channel: 'whatsapp', purpose: 'promotional' }), true); +}); + +test('WhatsApp Auth - existing Telegram user links WhatsApp to same account', async () => { + // 1. Existing Telegram user + const tgUser = (await db.query(` + INSERT INTO users (telegram_user_id, alias, age_confirmed_21) + VALUES (99001122, 'TelegramHero', true) + RETURNING id + `)).rows[0]; + + await db.query(` + INSERT INTO user_identities (user_id, provider, subject, verified_at) + VALUES ($1, 'telegram', '99001122', now()) + `, [tgUser.id]); + + const phone = '+919876543220'; + + // 2. User links WhatsApp while authenticated + const req = await requestWhatsAppOtp({ phone, currentUserId: tgUser.id }); + const otp = getWhatsAppProvider().getSentMessages()[0].otp; + + const linkResult = await verifyWhatsAppOtpAndResolveUser({ + challengeId: req.challengeId, + phone, + code: otp, + currentUserId: tgUser.id + }); + + assert.equal(linkResult.ok, true); + assert.equal(linkResult.linked, true); + assert.equal(linkResult.user.id, tgUser.id); + assert.equal(linkResult.user.phone, phone); + + // Both identities exist for the same user + const identities = (await db.query(`SELECT provider, subject FROM user_identities WHERE user_id = $1 ORDER BY provider`, [tgUser.id])).rows; + assert.equal(identities.length, 2); + assert.deepEqual(identities.map((i) => i.provider).sort(), ['phone', 'telegram'].sort()); + + // Check getLinkedIdentities + const linked = await getLinkedIdentities(tgUser.id); + assert.equal(linked.telegram.linked, true); + assert.equal(linked.whatsapp.linked, true); + assert.equal(linked.whatsapp.phone, phone); + + // 3. User signs out and logs back in using WhatsApp OTP -> reaches SAME account! + getWhatsAppProvider().clearSentMessages(); + const loginReq = await requestWhatsAppOtp({ phone }); + const loginOtp = getWhatsAppProvider().getSentMessages()[0].otp; + + const loginResult = await verifyWhatsAppOtpAndResolveUser({ + challengeId: loginReq.challengeId, + phone, + code: loginOtp + }); + + assert.equal(loginResult.ok, true); + assert.equal(loginResult.isNewUser, false); + assert.equal(loginResult.user.id, tgUser.id); // Same user ID! +}); + +test('WhatsApp Auth - conflict rejection when phone is already linked to another account', async () => { + const phone = '+919876543230'; + + // User A owns the phone + const userA = (await db.query(`INSERT INTO users (phone, age_confirmed_21) VALUES ($1, true) RETURNING id`, [phone])).rows[0]; + await db.query(`INSERT INTO user_identities (user_id, provider, subject) VALUES ($1, 'phone', $2)`, [userA.id, phone]); + + // User B (Telegram user) tries to link User A's phone + const userB = (await db.query(`INSERT INTO users (telegram_user_id, age_confirmed_21) VALUES (99003344, true) RETURNING id`)).rows[0]; + + const req = await requestWhatsAppOtp({ phone, currentUserId: userB.id }); + const otp = getWhatsAppProvider().getSentMessages()[0].otp; + + await assert.rejects( + () => verifyWhatsAppOtpAndResolveUser({ + challengeId: req.challengeId, + phone, + code: otp, + currentUserId: userB.id + }), + /already linked to another NIGHTLIFEZ account/i + ); +}); + +test('WhatsApp Auth - unlinking identity respects sole-provider guard', async () => { + const phone = '+919876543240'; + + // 1. WhatsApp-only user cannot unlink WhatsApp + const user = (await db.query(`INSERT INTO users (phone, age_confirmed_21) VALUES ($1, true) RETURNING id`, [phone])).rows[0]; + await db.query(`INSERT INTO user_identities (user_id, provider, subject) VALUES ($1, 'phone', $2)`, [user.id, phone]); + + await assert.rejects( + () => unlinkWhatsAppIdentity({ userId: user.id, phone }), + /cannot disconnect your only login method/i + ); + + // 2. Add Telegram identity + await db.query(`UPDATE users SET telegram_user_id = 99005566 WHERE id = $1`, [user.id]); + await db.query(`INSERT INTO user_identities (user_id, provider, subject) VALUES ($1, 'telegram', '99005566')`, [user.id]); + + // Now unlinking WhatsApp succeeds! + const res = await unlinkWhatsAppIdentity({ userId: user.id, phone }); + assert.equal(res.ok, true); + + const linked = await getLinkedIdentities(user.id); + assert.equal(linked.whatsapp.linked, false); + assert.equal(linked.telegram.linked, true); +}); diff --git a/test/whatsapp-provider.test.js b/test/whatsapp-provider.test.js new file mode 100644 index 0000000..2cb17b2 --- /dev/null +++ b/test/whatsapp-provider.test.js @@ -0,0 +1,52 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import crypto from 'node:crypto'; +import { + getWhatsAppConfig, + getWhatsAppProvider, + StubWhatsAppProvider, + MetaCloudWhatsAppProvider +} from '../lib/services/whatsapp-provider.js'; + +test('getWhatsAppConfig defaults safely when environment variables are not set', () => { + const cfg = getWhatsAppConfig(); + assert.equal(typeof cfg.enabled, 'boolean'); + assert.equal(typeof cfg.isLive, 'boolean'); + // Unless explicitly configured, isLive is false + assert.equal(cfg.isLive, false); +}); + +test('StubWhatsAppProvider captures sent OTP messages in memory', async () => { + const stub = new StubWhatsAppProvider(); + stub.clearSentMessages(); + + const res = await stub.sendOtpTemplate({ + to: '+919876543210', + otp: '543210', + language: 'en' + }); + + assert.equal(res.ok, true); + assert.match(res.messageId, /^wamid\.mock_/); + assert.equal(res.provider, 'mock'); + + const sent = stub.getSentMessages(); + assert.equal(sent.length, 1); + assert.equal(sent[0].to, '+919876543210'); + assert.equal(sent[0].otp, '543210'); + + stub.clearSentMessages(); + assert.equal(stub.getSentMessages().length, 0); +}); + +test('StubWhatsAppProvider verifies HMAC webhook signature', () => { + const stub = new StubWhatsAppProvider(); + const rawBody = JSON.stringify({ object: 'whatsapp_business_account', entry: [] }); + const secret = process.env.WHATSAPP_WEBHOOK_SECRET || 'test_whatsapp_webhook_secret'; + const validSig = 'sha256=' + crypto.createHmac('sha256', secret).update(rawBody).digest('hex'); + const badSig = 'sha256=' + crypto.createHmac('sha256', 'wrong_secret').update(rawBody).digest('hex'); + + assert.equal(stub.verifyWebhookSignature({ rawBody, signatureHeader: validSig }), true); + assert.equal(stub.verifyWebhookSignature({ rawBody, signatureHeader: badSig }), false); + assert.equal(stub.verifyWebhookSignature({ rawBody, signatureHeader: 'invalid-header' }), false); +});