Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(dashboard): preserve numbers and secure exports
Yudhi Armyndharis65579f7af2ce
diff --git a/dashboard/src/pages/NumberChecker.test.ts b/dashboard/src/pages/NumberChecker.test.tsindex 6fb06cf48..aa9fa5a94 100644--- a/dashboard/src/pages/NumberChecker.test.ts+++ b/dashboard/src/pages/NumberChecker.test.ts@@ -10,6 +10,7 @@ let rtl: RTL;let NumberChecker: typeof import('./NumberChecker.tsx').NumberChecker;let ToastProvider: typeof import('../components/Toast.tsx').ToastProvider;let MemoryRouter: typeof import('react-router-dom').MemoryRouter;+let RoleProvider: typeof import('../components/RoleProvider.tsx').RoleProvider;let defaultFetch: typeof fetch;function jsonResponse(data: unknown, status = 200): Response {@@ -29,13 +30,18 @@ function createTestQueryClient() {});}-function renderComponent() {+function renderComponent(role = 'operator') {+ sessionStorage.setItem('openwa_user_role', role);const queryClient = createTestQueryClient();return rtl.render(createElement(QueryClientProvider,{ client: queryClient },- createElement(ToastProvider, null, createElement(MemoryRouter, null, createElement(NumberChecker))),+ createElement(+ RoleProvider,+ null,+ createElement(ToastProvider, null, createElement(MemoryRouter, null, createElement(NumberChecker))),+ ),),);}@@ -61,12 +67,14 @@ before(async () => {rtl = await import('@testing-library/react');({ MemoryRouter } = await import('react-router-dom'));({ ToastProvider } = await import('../components/Toast.tsx'));+ ({ RoleProvider } = await import('../components/RoleProvider.tsx'));({ NumberChecker } = await import('./NumberChecker.tsx'));});afterEach(() => {rtl.cleanup();globalThis.fetch = defaultFetch;+ sessionStorage.clear();});test('NumberChecker: renders single check form and tabs', () => {@@ -83,7 +91,118 @@ test('NumberChecker: switches to bulk / batch tab when clicked', () => {assert.ok(headings.length >= 1);});-test('NumberChecker: a rejected lookup is recorded as failed with error status, not as unregistered', async () => {+for (const [raw, autoPrefix, expected] of [+ ['+65 8123 4567', true, '6581234567'],+ ['0065 8123 4567', true, '6581234567'],+ ['09876543210', false, '09876543210'],+ ['9109876543210', false, '9109876543210'],+ ['9876543210', true, '919876543210'],+ ['09876543210', true, '919876543210'],+] as const) {+ test(`NumberChecker: checks ${raw} as ${expected} with auto-prefix ${autoPrefix}`, async () => {+ const lookups: string[] = [];+ globalThis.fetch = ((input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes('/contacts/check/')) {+ const number = url.split('/contacts/check/')[1];+ lookups.push(number);+ return Promise.resolve(jsonResponse({ number, exists: false, whatsappId: null }));+ }+ return defaultFetch(input);+ }) as typeof fetch;++ const { container } = renderComponent();+ await rtl.screen.findByRole('option', { name: /Primary Session/ });+ if (!autoPrefix) rtl.fireEvent.click(rtl.screen.getByRole('checkbox'));+ rtl.fireEvent.change(rtl.screen.getByPlaceholderText(/9876543210/), { target: { value: raw } });+ if (raw.startsWith('+') || raw.startsWith('00')) {+ assert.ok(!container.querySelector('.nc-format-preview')?.textContent?.includes('auto-prefixed'));+ }+ rtl.fireEvent.click(rtl.screen.getByRole('button', { name: 'Check' }));+ await rtl.screen.findByText('Not Registered', { selector: '.nc-status-badge' });+ assert.deepEqual(lookups, [expected]);+ });+}++test('NumberChecker: bulk parsing deduplicates explicit international numbers without adding +91', async () => {+ const lookups: string[] = [];+ globalThis.fetch = ((input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes('/contacts/check/')) {+ const number = url.split('/contacts/check/')[1];+ lookups.push(number);+ return Promise.resolve(jsonResponse({ number, exists: false, whatsappId: null }));+ }+ return defaultFetch(input);+ }) as typeof fetch;++ renderComponent();+ rtl.fireEvent.click(rtl.screen.getByRole('button', { name: /Bulk/i }));+ await rtl.screen.findByRole('option', { name: /Primary Session/ });+ rtl.fireEvent.change(rtl.screen.getByPlaceholderText(/9612345678/i), {+ target: { value: '+65 8123 4567\n0065 8123 4567' },+ });+ assert.match(rtl.screen.getByText(/ten-digit/).textContent ?? '', /0 ten-digit/);+ rtl.fireEvent.click(rtl.screen.getByRole('button', { name: /Start Batch Check/i }));+ await rtl.screen.findByText('+6581234567');+ assert.deepEqual(lookups, ['6581234567']);+});++test('NumberChecker: viewers cannot start single or bulk lookups, including with Enter', async () => {+ const lookups: string[] = [];+ globalThis.fetch = ((input: RequestInfo | URL) => {+ const url = String(input);+ if (url.includes('/contacts/check/')) {+ lookups.push(url);+ return Promise.resolve(jsonResponse({ number: '919876543210', exists: false, whatsappId: null }));+ }+ return defaultFetch(input);+ }) as typeof fetch;++ renderComponent('viewer');+ await rtl.screen.findByRole('option', { name: /Primary Session/ });+ const input = rtl.screen.getByPlaceholderText(/9876543210/);+ rtl.fireEvent.change(input, { target: { value: '9876543210' } });+ assert.equal((rtl.screen.getByRole('button', { name: 'Check' }) as HTMLButtonElement).disabled, true);+ await rtl.act(async () => rtl.fireEvent.keyDown(input, { key: 'Enter' }));+ rtl.fireEvent.click(rtl.screen.getByRole('button', { name: /Bulk/i }));+ rtl.fireEvent.change(rtl.screen.getByPlaceholderText(/9612345678/i), { target: { value: '9876543210' } });+ assert.equal((rtl.screen.getByRole('button', { name: /Start Batch Check/i }) as HTMLButtonElement).disabled, true);+ assert.deepEqual(lookups, []);+});++test('NumberChecker: CSV export neutralizes error formulas and releases its object URL', async t => {+ const downloads: Blob[] = [];+ t.mock.method(URL, 'createObjectURL', (blob: Blob) => {+ downloads.push(blob);+ return 'blob:number-checker-csv';+ });+ const revoke = t.mock.method(URL, 'revokeObjectURL');+ t.mock.method(HTMLAnchorElement.prototype, 'click', () => {});+ globalThis.fetch = ((input: RequestInfo | URL) => {+ if (String(input).includes('/contacts/check/')) {+ return Promise.resolve(jsonResponse({ message: '=HYPERLINK("https://example.com","lookup")' }, 500));+ }+ return defaultFetch(input);+ }) as typeof fetch;++ renderComponent();+ rtl.fireEvent.click(rtl.screen.getByRole('button', { name: /Bulk/i }));+ await rtl.screen.findByRole('option', { name: /Primary Session/ });+ rtl.fireEvent.change(rtl.screen.getByPlaceholderText(/9612345678/i), { target: { value: '919999999999' } });+ rtl.fireEvent.click(rtl.screen.getByRole('button', { name: /Start Batch Check/i }));+ await rtl.screen.findByText('Failed', { selector: '.nc-status-badge' });+ rtl.fireEvent.click(rtl.screen.getByRole('button', { name: /Export Results/i }));++ assert.equal(downloads.length, 1);+ assert.ok((await downloads[0].text()).includes(`"'=HYPERLINK(""https://example.com"",""lookup"")"`));+ assert.equal(revoke.mock.callCount(), 1);+ assert.deepEqual(revoke.mock.calls[0].arguments, ['blob:number-checker-csv']);+ assert.equal(document.querySelector('a[download]'), null);+});++test('NumberChecker: a rejected lookup is recorded as failed with error status, not as unregistered', async t => {+ t.mock.method(HTMLAnchorElement.prototype, 'click', () => {});const recordedDownloads: Blob[] = [];const realCreateObjectURL = URL.createObjectURL;URL.createObjectURL = (blob: Blob) => {@@ -144,8 +263,8 @@ test('NumberChecker: a rejected lookup is recorded as failed with error status,assert.equal(recordedDownloads.length, 1);const csvContent = await recordedDownloads[0].text();- assert.ok(csvContent.includes('"919999999999","Error","","Rate limit exceeded (HTTP 429)"'));- assert.ok(!csvContent.includes('"919999999999","No"'));+ assert.ok(csvContent.includes('919999999999,Error,,Rate limit exceeded (HTTP 429),'));+ assert.ok(!csvContent.includes('919999999999,No,'));} finally {URL.createObjectURL = realCreateObjectURL;}diff --git a/dashboard/src/pages/NumberChecker.tsx b/dashboard/src/pages/NumberChecker.tsxindex c5c534f79..864db7771 100644--- a/dashboard/src/pages/NumberChecker.tsx+++ b/dashboard/src/pages/NumberChecker.tsx@@ -21,6 +21,8 @@ import { useDocumentTitle } from '../hooks/useDocumentTitle';import { useSessionsQuery } from '../hooks/queries';import { contactApi, type CheckNumberResponse } from '../services/api';import { useToast } from '../hooks/useToast';+import { useRole } from '../hooks/useRole';+import { escapeCsvCell } from '../utils/csv';import './NumberChecker.css';export type CheckStatus = 'registered' | 'unregistered' | 'failed';@@ -36,6 +38,7 @@ export function NumberChecker() {useDocumentTitle('Number Checker - OpenWA');const navigate = useNavigate();const toast = useToast();+ const { canWrite } = useRole();const { data: sessions = [], isLoading: loadingSessions } = useSessionsQuery();const readySessions = useMemo(@@ -79,20 +82,21 @@ export function NumberChecker() {const formatNumberForCheck = useCallback((raw: string, applyPrefix = autoPrefix91) => {let digits = raw.replace(/[^0-9]/g, '');+ const isInternational = raw.trim().startsWith('+') || digits.startsWith('00');// 1. If international dial exit code 00 is present (e.g. 009196...), strip '00'if (digits.startsWith('00') && digits.length >= 12) {digits = digits.substring(2);}// 2. If user entered +91 with domestic trunk 0 (e.g. +91 096... -> 13 digits), strip trunk 0- if (digits.length === 13 && digits.startsWith('910')) {+ if (applyPrefix && digits.length === 13 && digits.startsWith('910')) {digits = '91' + digits.substring(3);}// 3. If domestic 11 digits starting with 0 (e.g. 096xxxxxxxx), strip leading 0- if (digits.length === 11 && digits.startsWith('0')) {+ if (applyPrefix && !isInternational && digits.length === 11 && digits.startsWith('0')) {digits = digits.substring(1);}// 4. If exactly 10 digits and autoPrefix is true: impose India country code (+91)- if (applyPrefix && digits.length === 10) {+ if (applyPrefix && !isInternational && digits.length === 10) {return '91' + digits;}// 5. If 12 digits (already has country code, e.g. 91xxxxxxxxxx) or any other format: keep as-is@@ -121,11 +125,12 @@ export function NumberChecker() {for (const raw of lines) {let d = raw.replace(/[^0-9]/g, '');+ const isInternational = raw.startsWith('+') || d.startsWith('00');if (d.startsWith('00') && d.length >= 12) d = d.substring(2);- if (d.length === 13 && d.startsWith('910')) d = '91' + d.substring(3);- if (d.length === 11 && d.startsWith('0')) d = d.substring(1);+ if (autoPrefix91 && d.length === 13 && d.startsWith('910')) d = '91' + d.substring(3);+ if (autoPrefix91 && !isInternational && d.length === 11 && d.startsWith('0')) d = d.substring(1);- if (d.length === 10) {+ if (!isInternational && d.length === 10) {tenDigitsCount++;} else if (d.length === 12) {twelveDigitsCount++;@@ -150,6 +155,7 @@ export function NumberChecker() {// Perform single checkconst handleSingleCheck = async () => {+ if (!canWrite || isCheckingSingle) return;const formatted = formatNumberForCheck(phoneNumber);if (!formatted) {toast.error('Please enter a phone number to check.');@@ -199,6 +205,7 @@ export function NumberChecker() {// Perform batch checkconst handleStartBatch = async () => {+ if (!canWrite || isCheckingBatch) return;const numbers = batchParsedStats.list;if (numbers.length === 0) {@@ -282,8 +289,7 @@ export function NumberChecker() {const rows = batchResults.map(r => {const hasWa = r.status === 'failed' ? 'Error' : r.exists ? 'Yes' : 'No';- const errorText = (r.error || '').replace(/"/g, '""');- return `"${r.number}","${hasWa}","${r.whatsappId || ''}","${errorText}","${r.timestamp}"`;+ return [r.number, hasWa, r.whatsappId, r.error, r.timestamp].map(escapeCsvCell).join(',');}).join('\n');const blob = new Blob([header + rows], { type: 'text/csv;charset=utf-8;' });@@ -294,6 +300,7 @@ export function NumberChecker() {document.body.appendChild(link);link.click();document.body.removeChild(link);+ URL.revokeObjectURL(url);};const registeredCount = batchResults.filter(r => r.status === 'registered').length;@@ -389,7 +396,7 @@ export function NumberChecker() {<buttonclassName="nc-btn nc-btn-primary"onClick={handleSingleCheck}- disabled={isCheckingSingle || !phoneNumber.trim() || readySessions.length === 0}+ disabled={!canWrite || isCheckingSingle || !phoneNumber.trim() || readySessions.length === 0}>{isCheckingSingle ? <Loader2 size={18} className="animate-spin" /> : <Search size={18} />}{isCheckingSingle ? 'Checking...' : 'Check'}@@ -411,7 +418,8 @@ export function NumberChecker() {{phoneNumber.trim() && (<div className="nc-format-preview">- {phoneNumber.replace(/[^0-9]/g, '').length === 10 && autoPrefix91 ? (+ {phoneNumber.replace(/[^0-9]/g, '').length === 10 &&+ singleFormattedNumber === '91' + phoneNumber.replace(/[^0-9]/g, '') ? (<span className="nc-format-pill highlight">Will check as: <strong>+{singleFormattedNumber}</strong> (10 digits → auto-prefixed with91)@@ -695,7 +703,7 @@ export function NumberChecker() {<buttonclassName="nc-btn nc-btn-primary"onClick={handleStartBatch}- disabled={!batchInput.trim() || readySessions.length === 0}+ disabled={!canWrite || !batchInput.trim() || readySessions.length === 0}><UserCheck size={18} /> Start Batch Check</button>