Skip to content

A self-hosted UPI & COD payment gateway with zero per-transaction platform fees, universal JavaScript checkout integration, dynamic QR payments, WhatsApp OTP authentication, and automated payment verification.

JavaScript

fix(gmail-observer): paginate messages list with bounded lookback (closes #104)

ArunGupta152642c578ad6142
diff --git a/apps/gmail-observer/src/__tests__/gmail-poller-pagination.test.js b/apps/gmail-observer/src/__tests__/gmail-poller-pagination.test.js
new file mode 100644
index 0000000..f0f61e9
--- /dev/null
+++ b/apps/gmail-observer/src/__tests__/gmail-poller-pagination.test.js
@@ -0,0 +1,248 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { GmailPoller } from '../gmail-poller.js';
+
+function createTempDir(prefix = 'youpi-pages-') {
+ return fs.mkdtempSync(path.join(os.tmpdir(), prefix));
+}
+
+test('Issue #104: bounded pagination discovers alert on page two across multiple pages', async () => {
+ const dir = createTempDir();
+ const originalFetch = globalThis.fetch;
+ const submitted = [];
+ const pageTokens = [];
+
+ const poller = new GmailPoller({
+ receivingAccountId: 'synthetic-account',
+ storagePath: path.join(dir, 'ids.json'),
+ maxPagesPerCycle: 3
+ });
+ poller.getAccessToken = async () => 'synthetic-token';
+ poller.observerClient.submitObservation = async (data) => {
+ submitted.push(data.rawPayload.messageId);
+ return { accepted: true };
+ };
+
+ globalThis.fetch = async (input) => {
+ const url = new URL(input);
+ assert.equal(url.origin, 'https://gmail.googleapis.com');
+ if (url.pathname.endsWith('/messages')) {
+ const token = url.searchParams.get('pageToken');
+ pageTokens.push(token);
+ return Response.json(token
+ ? { messages: [{ id: 'alert-11' }] }
+ : {
+ messages: Array.from({ length: 10 }, (_, i) => ({ id: `alert-${i + 1}` })),
+ nextPageToken: 'page-two'
+ });
+ }
+ return Response.json({
+ internalDate: String(Date.now()),
+ payload: {
+ mimeType: 'text/plain',
+ headers: [
+ { name: 'From', value: '[email protected]' },
+ { name: 'Subject', value: 'Credit alert' }
+ ],
+ body: {
+ data: Buffer.from('Dear customer, Rs 150.00 credited to your account. UTR: 778899001122').toString('base64url')
+ }
+ }
+ });
+ };
+
+ try {
+ await poller.pollCycle();
+ await poller.pollCycle();
+ await poller.pollCycle();
+
+ assert.equal(pageTokens.includes('page-two'), true, 'Should fetch page 2 with pageToken=page-two');
+ assert.equal(submitted.length, 11, 'Should discover and submit all 11 messages');
+ assert.ok(submitted.includes('alert-11'), 'Should submit alert-11 from page 2');
+ } finally {
+ globalThis.fetch = originalFetch;
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test('Issue #104: downtime recovery discovers page two when page one was already processed on disk', async () => {
+ const dir = createTempDir();
+ const originalFetch = globalThis.fetch;
+ const storagePath = path.join(dir, 'ids.json');
+
+ // Pre-populate disk with first 10 alerts already processed before restart
+ const preProcessed = Array.from({ length: 10 }, (_, i) => `alert-${i + 1}`);
+ fs.writeFileSync(storagePath, JSON.stringify(preProcessed));
+
+ const poller = new GmailPoller({
+ receivingAccountId: 'synthetic-account',
+ storagePath,
+ maxPagesPerCycle: 3
+ });
+ poller.getAccessToken = async () => 'synthetic-token';
+ const submitted = [];
+ const pageTokens = [];
+
+ poller.observerClient.submitObservation = async (data) => {
+ submitted.push(data.rawPayload.messageId);
+ return { accepted: true };
+ };
+
+ globalThis.fetch = async (input) => {
+ const url = new URL(input);
+ assert.equal(url.origin, 'https://gmail.googleapis.com');
+ if (url.pathname.endsWith('/messages')) {
+ const token = url.searchParams.get('pageToken');
+ pageTokens.push(token);
+ return Response.json(token
+ ? { messages: [{ id: 'alert-11' }] }
+ : {
+ messages: Array.from({ length: 10 }, (_, i) => ({ id: `alert-${i + 1}` })),
+ nextPageToken: 'page-two'
+ });
+ }
+ return Response.json({
+ internalDate: String(Date.now()),
+ payload: {
+ mimeType: 'text/plain',
+ headers: [
+ { name: 'From', value: '[email protected]' },
+ { name: 'Subject', value: 'Credit alert' }
+ ],
+ body: {
+ data: Buffer.from('Dear customer, Rs 200.00 credited to your account. UTR: 889900112233').toString('base64url')
+ }
+ }
+ });
+ };
+
+ try {
+ await poller.pollCycle();
+
+ assert.equal(pageTokens.includes('page-two'), true, 'Should inspect page 2 on initial lookback');
+ assert.equal(submitted.length, 1, 'Should only submit the unseen alert-11');
+ assert.equal(submitted[0], 'alert-11');
+ } finally {
+ globalThis.fetch = originalFetch;
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test('Issue #104: idle polling does not re-fetch page two when top message and page one are unchanged', async () => {
+ const dir = createTempDir();
+ const originalFetch = globalThis.fetch;
+ let pageTwoFetchCount = 0;
+
+ const poller = new GmailPoller({
+ receivingAccountId: 'synthetic-account',
+ storagePath: path.join(dir, 'ids.json'),
+ maxPagesPerCycle: 3
+ });
+ poller.getAccessToken = async () => 'synthetic-token';
+ poller.observerClient.submitObservation = async () => ({ accepted: true });
+
+ globalThis.fetch = async (input) => {
+ const url = new URL(input);
+ if (url.pathname.endsWith('/messages')) {
+ const token = url.searchParams.get('pageToken');
+ if (token === 'page-two') pageTwoFetchCount++;
+ return Response.json(token
+ ? { messages: [{ id: 'alert-11' }] }
+ : {
+ messages: Array.from({ length: 10 }, (_, i) => ({ id: `alert-${i + 1}` })),
+ nextPageToken: 'page-two'
+ });
+ }
+ return Response.json({
+ internalDate: String(Date.now()),
+ payload: {
+ mimeType: 'text/plain',
+ headers: [{ name: 'From', value: '[email protected]' }, { name: 'Subject', value: 'Credit' }],
+ body: { data: Buffer.from('Rs 100.00 credited UTR: 112233445566').toString('base64url') }
+ }
+ });
+ };
+
+ try {
+ // Cycle 1: discovers alert-1..10 and alert-11 on page-two
+ await poller.pollCycle();
+ assert.equal(pageTwoFetchCount, 1);
+
+ // Cycle 2: everything is caught up, top message unchanged -> stops early on page 1
+ await poller.pollCycle();
+ assert.equal(pageTwoFetchCount, 1, 'Should not re-fetch page 2 when idle');
+
+ // Cycle 3: still idle
+ await poller.pollCycle();
+ assert.equal(pageTwoFetchCount, 1, 'Should not re-fetch page 2 on subsequent idle cycles');
+ } finally {
+ globalThis.fetch = originalFetch;
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
+test('Issue #104: multi-cycle catch-up respects maxPagesPerCycle budget', async () => {
+ const dir = createTempDir();
+ const originalFetch = globalThis.fetch;
+ const pageFetches = [];
+
+ const poller = new GmailPoller({
+ receivingAccountId: 'synthetic-account',
+ storagePath: path.join(dir, 'ids.json'),
+ maxPagesPerCycle: 2 // budget: only 2 pages per cycle
+ });
+ poller.getAccessToken = async () => 'synthetic-token';
+ poller.observerClient.submitObservation = async () => ({ accepted: true });
+
+ globalThis.fetch = async (input) => {
+ const url = new URL(input);
+ if (url.pathname.endsWith('/messages')) {
+ const token = url.searchParams.get('pageToken');
+ pageFetches.push(token);
+ if (!token) {
+ return Response.json({
+ messages: [{ id: 'p1-1' }],
+ nextPageToken: 'page-2'
+ });
+ }
+ if (token === 'page-2') {
+ return Response.json({
+ messages: [{ id: 'p2-1' }],
+ nextPageToken: 'page-3'
+ });
+ }
+ if (token === 'page-3') {
+ return Response.json({
+ messages: [{ id: 'p3-1' }]
+ });
+ }
+ }
+ return Response.json({
+ internalDate: String(Date.now()),
+ payload: {
+ mimeType: 'text/plain',
+ headers: [{ name: 'From', value: '[email protected]' }, { name: 'Subject', value: 'Credit' }],
+ body: { data: Buffer.from('Rs 100.00 credited UTR: 112233445566').toString('base64url') }
+ }
+ });
+ };
+
+ try {
+ // Cycle 1: fetches page 1 and page 2 (hitting maxPagesPerCycle = 2)
+ await poller.pollCycle();
+ assert.deepEqual(pageFetches, [null, 'page-2']);
+ assert.equal(poller.nextCatchUpPageToken, 'page-3');
+
+ // Cycle 2: continues catch-up to page 3
+ await poller.pollCycle();
+ assert.deepEqual(pageFetches, [null, 'page-2', 'page-3']);
+ assert.equal(poller.nextCatchUpPageToken, null, 'Catch-up finished');
+ } finally {
+ globalThis.fetch = originalFetch;
+ fs.rmSync(dir, { recursive: true, force: true });
+ }
+});
+
diff --git a/apps/gmail-observer/src/gmail-poller.js b/apps/gmail-observer/src/gmail-poller.js
index 13e2c95..b34659c 100644
--- a/apps/gmail-observer/src/gmail-poller.js
+++ b/apps/gmail-observer/src/gmail-poller.js
@@ -89,6 +89,12 @@ export class GmailPoller {
this.bootRetryTimer = null;
this.bootVersion = 0;
this.backoffDelayMs = 5000;
+
+ // Pagination & Lookback state (Issue #104)
+ this.maxPagesPerCycle = options.maxPagesPerCycle || Number(process.env.GMAIL_MAX_PAGES_PER_CYCLE || 5);
+ this.maxResultsPerPage = options.maxResultsPerPage || 10;
+ this.lastTopMessageId = null;
+ this.nextCatchUpPageToken = null;
}
clearBootRetryTimer() {
@@ -359,6 +365,7 @@ export class GmailPoller {
}
this.isRunning = false;
this._isPolling = false;
+ this.nextCatchUpPageToken = null;
this.lifecycleState = 'STOPPED';
console.log('[Gmail Observer] Poller stopped.');
}
@@ -374,51 +381,95 @@ export class GmailPoller {
// Strict bank transaction alert filter (read-only search)
const query = encodeURIComponent('from:(bank.in OR hdfcbank.net OR hdfcbank.com OR icicibank.com OR sbi.co.in OR axisbank.com OR kotak.com) OR (credit OR credited OR received OR upi OR deposit OR alert OR update)');
- const listRes = await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=10&q=${query}`, {
- headers: { 'Authorization': `Bearer ${accessToken}` },
- signal: AbortSignal.timeout(8000)
- });
- if (!listRes.ok) {
- if (listRes.status === 401) {
- this.cachedAccessToken = null;
+ let pageToken = this.nextCatchUpPageToken || null;
+ let pagesFetched = 0;
+ let hasMoreCatchUp = false;
+
+ while (pagesFetched < this.maxPagesPerCycle) {
+ if (!this.isRunning && this.lifecycleState === 'STOPPED') break;
+
+ let url = `https://gmail.googleapis.com/gmail/v1/users/me/messages?maxResults=${this.maxResultsPerPage}&q=${query}`;
+ if (pageToken) {
+ url += `&pageToken=${encodeURIComponent(pageToken)}`;
}
- return;
- }
+ pagesFetched++;
+
+ const listRes = await fetch(url, {
+ headers: { 'Authorization': `Bearer ${accessToken}` },
+ signal: AbortSignal.timeout(8000)
+ });
- const listData = await listRes.json();
- const messages = listData.messages || [];
-
- const unseenMessages = messages.filter(m => !this.processedMessageIds.has(m.id));
- if (unseenMessages.length > 0) {
- await Promise.allSettled(unseenMessages.map(async (m) => {
- try {
- const msgRes = await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${m.id}?format=full`, {
- headers: { 'Authorization': `Bearer ${accessToken}` },
- signal: AbortSignal.timeout(8000)
- });
- if (!msgRes.ok) return;
-
- const msgData = await msgRes.json();
- const headers = msgData.payload?.headers || [];
- const from = headers.find(h => h.name.toLowerCase() === 'from')?.value || '';
- const subject = headers.find(h => h.name.toLowerCase() === 'subject')?.value || '';
- const dateStr = headers.find(h => h.name.toLowerCase() === 'date')?.value || '';
- const body = extractBodyFromGmailPayload(msgData.payload) || msgData.snippet || '';
-
- await this.processEmail({
- id: m.id,
- messageId: m.id,
- subject,
- body,
- from,
- date: dateStr ? new Date(dateStr) : new Date(Number(msgData.internalDate || Date.now()))
- });
- } catch (msgErr) {
- console.warn(`[Gmail Observer] Error fetching message:`, redactSensitiveData(msgErr.message));
+ if (!listRes.ok) {
+ if (listRes.status === 401) {
+ this.cachedAccessToken = null;
+ }
+ if (listRes.status === 400 && pageToken) {
+ // Expired or invalid pageToken: reset catchUpPageToken
+ this.nextCatchUpPageToken = null;
}
- }));
+ break;
+ }
+
+ const listData = await listRes.json();
+ const messages = listData.messages || [];
+
+ // Track newest message on the first page
+ if (!pageToken && messages.length > 0) {
+ const currentTopId = messages[0].id;
+ const isSameTop = this.lastTopMessageId && this.lastTopMessageId === currentTopId;
+ const wasBootLookback = this.lastTopMessageId === null;
+ this.lastTopMessageId = currentTopId;
+
+ const unseenOnPage1 = messages.filter(m => !this.processedMessageIds.has(m.id));
+ // If top message hasn't changed, all messages on page 1 are seen, and not in boot lookback or ongoing catch-up, stop early
+ if (isSameTop && unseenOnPage1.length === 0 && !this.nextCatchUpPageToken && !wasBootLookback) {
+ break;
+ }
+ }
+
+ const unseenMessages = messages.filter(m => !this.processedMessageIds.has(m.id));
+ if (unseenMessages.length > 0) {
+ await Promise.allSettled(unseenMessages.map(async (m) => {
+ try {
+ const msgRes = await fetch(`https://gmail.googleapis.com/gmail/v1/users/me/messages/${m.id}?format=full`, {
+ headers: { 'Authorization': `Bearer ${accessToken}` },
+ signal: AbortSignal.timeout(8000)
+ });
+ if (!msgRes.ok) return;
+
+ const msgData = await msgRes.json();
+ const headers = msgData.payload?.headers || [];
+ const from = headers.find(h => h.name.toLowerCase() === 'from')?.value || '';
+ const subject = headers.find(h => h.name.toLowerCase() === 'subject')?.value || '';
+ const dateStr = headers.find(h => h.name.toLowerCase() === 'date')?.value || '';
+ const body = extractBodyFromGmailPayload(msgData.payload) || msgData.snippet || '';
+
+ await this.processEmail({
+ id: m.id,
+ messageId: m.id,
+ subject,
+ body,
+ from,
+ date: dateStr ? new Date(dateStr) : new Date(Number(msgData.internalDate || Date.now()))
+ });
+ } catch (msgErr) {
+ console.warn(`[Gmail Observer] Error fetching message:`, redactSensitiveData(msgErr.message));
+ }
+ }));
+ }
+
+ if (listData.nextPageToken) {
+ pageToken = listData.nextPageToken;
+ hasMoreCatchUp = true;
+ } else {
+ pageToken = null;
+ hasMoreCatchUp = false;
+ break;
+ }
}
+
+ this.nextCatchUpPageToken = hasMoreCatchUp ? pageToken : null;
} catch (err) {
console.warn('[Gmail Observer] pollCycle error:', redactSensitiveData(err.message));
} finally {
diff --git a/scripts/test-all.js b/scripts/test-all.js
index 65ccf0e..903ee8a 100644
--- a/scripts/test-all.js
+++ b/scripts/test-all.js
@@ -24,6 +24,7 @@ const testFiles = [
'apps/merchant-admin/src/__tests__/merchant-admin.test.js',
'apps/payment-help/src/__tests__/payment-help.test.js',
'apps/gmail-observer/src/__tests__/gmail-poller-stop-race.test.js',
+ 'apps/gmail-observer/src/__tests__/gmail-poller-pagination.test.js',
'apps/gmail-observer/src/__tests__/gmail-observer.test.js',
'apps/gmail-observer/src/__tests__/gmail-bank-alert-security.test.js',
'apps/gmail-observer/src/__tests__/gmail-poller-boot-lifecycle.test.js',