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`
`; } else if (bot) { - method = html`Telegram sign-in is not configured yet on this deployment.
On production, attendees and hosts sign in with one tap through Telegram. Telegram handles 21+ identity verification, instant ticket delivery, and secret group invites with no passwords and no stored phone numbers.
- ${previewReviewer ? html` -Preview Testing Mode
-Sign in as a synthetic reviewer to test event booking, ticket issuance, and secret venue disclosure in this isolated preview environment.
- -${SIGNIN_ERRORS[error]}
` : ''} - ${method} - ${bot ? html`Using Telegram on your phone? Open our bot and tap “Open NIGHTLIFEZ”.
` : ''} -Preview Testing Mode
+Sign in as a synthetic reviewer to test event booking, ticket issuance, and secret venue disclosure in this isolated preview environment.
+ +Using Telegram on your phone? Open our bot and tap “Open NIGHTLIFEZ”.
` : ''} +Loading host announcements…
Loading login methods and communication settings…
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 = 'Target opted-in NIGHTLIFEZ members using official Meta Cloud API WhatsApp templates.
' + + 'Every WhatsApp campaign button embeds full UTM tracking parameters to measure registrations and ticket passes.
' + + 'Core Decision Rules:
' + + '“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!”
' + + 'No promotion campaigns have been created for this event yet.
'; + } else { + h += 'Loading delivery logs…
' + + '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 = '| Recipient | City | Status | Provider Msg ID | Cost | Dispatched |
|---|---|---|---|---|---|
| ' + 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)) + ' | ' + + '
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 = 'Link both WhatsApp and Telegram to access your tickets and receive operational updates across either service.
' + + 'Manage how and where NIGHTLIFEZ sends you notifications.
' + + '