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(foundation): synchronize PostgreSQL schema, disable cleartext traffic and add schema parity test (#11, #13)

ArunGupta152648d5619369a3
diff --git a/apps/android-observer-app/app/src/main/AndroidManifest.xml b/apps/android-observer-app/app/src/main/AndroidManifest.xml
index 44af5a9..0abdd98 100644
--- a/apps/android-observer-app/app/src/main/AndroidManifest.xml
+++ b/apps/android-observer-app/app/src/main/AndroidManifest.xml
@@ -34,7 +34,8 @@
android:label="YOUPI SMS Gateway"
android:icon="@android:drawable/stat_notify_chat"
android:theme="@android:style/Theme.DeviceDefault.Light.NoActionBar"
- android:usesCleartextTraffic="true">
+ android:usesCleartextTraffic="false"
+ android:networkSecurityConfig="@xml/network_security_config">
<activity
android:name="com.youpi.observer.MainActivity"
diff --git a/apps/android-observer-app/app/src/main/res/xml/network_security_config.xml b/apps/android-observer-app/app/src/main/res/xml/network_security_config.xml
index 8a76775..60ce59c 100644
--- a/apps/android-observer-app/app/src/main/res/xml/network_security_config.xml
+++ b/apps/android-observer-app/app/src/main/res/xml/network_security_config.xml
@@ -1,9 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
- <base-config cleartextTrafficPermitted="true">
+ <!-- Invariant: Cleartext traffic is disabled by default app-wide. Only HTTPS is allowed. -->
+ <base-config cleartextTrafficPermitted="false">
<trust-anchors>
<certificates src="system" />
- <certificates src="user" />
</trust-anchors>
</base-config>
+ <!-- Development/emulator loopback domain config -->
+ <domain-config cleartextTrafficPermitted="true">
+ <domain includeSubdomains="true">10.0.2.2</domain>
+ <domain includeSubdomains="true">localhost</domain>
+ <domain includeSubdomains="true">127.0.0.1</domain>
+ </domain-config>
</network-security-config>
diff --git a/packages/db/src/__tests__/schema-parity.test.js b/packages/db/src/__tests__/schema-parity.test.js
new file mode 100644
index 0000000..0d434d9
--- /dev/null
+++ b/packages/db/src/__tests__/schema-parity.test.js
@@ -0,0 +1,135 @@
+import { test, describe } from 'node:test';
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { Database } from '../database.js';
+
+const __filename = fileURLToPath(import.meta.url);
+const __dirname = path.dirname(__filename);
+
+describe('Database Schema Parity & Integrity (Postgres vs SQLite) (#13)', () => {
+ const pgSchemaPath = path.join(__dirname, '..', 'schema.sql');
+ const sqliteSchemaPath = path.join(__dirname, '..', 'sqlite-schema.sql');
+
+ const pgSchema = fs.readFileSync(pgSchemaPath, 'utf8');
+ const sqliteSchema = fs.readFileSync(sqliteSchemaPath, 'utf8');
+
+ function extractTableNames(sql) {
+ const regex = /CREATE\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-zA-Z0-9_]+)/gi;
+ const tables = [];
+ let match;
+ while ((match = regex.exec(sql)) !== null) {
+ tables.push(match[1].toLowerCase());
+ }
+ return tables;
+ }
+
+ function extractIndexNames(sql) {
+ const regex = /CREATE\s+(?:UNIQUE\s+)?INDEX\s+(?:IF\s+NOT\s+EXISTS\s+)?([a-zA-Z0-9_]+)/gi;
+ const indexes = [];
+ let match;
+ while ((match = regex.exec(sql)) !== null) {
+ indexes.push(match[1].toLowerCase());
+ }
+ return indexes;
+ }
+
+ test('PostgreSQL and SQLite schemas define identical set of tables', () => {
+ const pgTables = extractTableNames(pgSchema);
+ const sqliteTables = extractTableNames(sqliteSchema);
+
+ assert.deepEqual(pgTables.sort(), sqliteTables.sort(), 'Tables in schema.sql and sqlite-schema.sql must match 1:1');
+ assert.ok(pgTables.length >= 10, 'Must have at least 10 core tables defined');
+ });
+
+ test('devices table is defined before payment_sessions in both schemas to prevent foreign key errors', () => {
+ const pgTables = extractTableNames(pgSchema);
+ const sqliteTables = extractTableNames(sqliteSchema);
+
+ const pgDevicesIdx = pgTables.indexOf('devices');
+ const pgSessionsIdx = pgTables.indexOf('payment_sessions');
+ assert.ok(pgDevicesIdx !== -1, 'devices table must exist in schema.sql');
+ assert.ok(pgSessionsIdx !== -1, 'payment_sessions table must exist in schema.sql');
+ assert.ok(pgDevicesIdx < pgSessionsIdx, 'devices must be declared before payment_sessions in schema.sql');
+
+ const sqliteDevicesIdx = sqliteTables.indexOf('devices');
+ const sqliteSessionsIdx = sqliteTables.indexOf('payment_sessions');
+ assert.ok(sqliteDevicesIdx < sqliteSessionsIdx, 'devices must be declared before payment_sessions in sqlite-schema.sql');
+ });
+
+ test('PostgreSQL and SQLite schemas define identical core indexes', () => {
+ const pgIndexes = extractIndexNames(pgSchema);
+ const sqliteIndexes = extractIndexNames(sqliteSchema);
+
+ const requiredIndexes = [
+ 'idx_single_active_vpa_per_merchant',
+ 'idx_customers_email',
+ 'idx_customers_mobile',
+ 'idx_customer_sessions_token',
+ 'idx_customer_sessions_customer',
+ 'idx_devices_customer',
+ 'idx_devices_fingerprint',
+ 'idx_devices_token',
+ 'idx_payment_sessions_active',
+ 'idx_payment_sessions_order',
+ 'idx_payment_sessions_device',
+ 'idx_single_active_session_per_order',
+ 'idx_one_slot_per_receiving_account',
+ 'idx_observations_match',
+ 'idx_observations_bank_ref',
+ 'idx_observations_fingerprint',
+ 'idx_observations_attributed_payment',
+ 'idx_webhook_deliveries_retry',
+ 'idx_support_tickets_merchant',
+ 'idx_support_tickets_customer',
+ 'idx_ticket_messages_ticket',
+ 'idx_audit_logs_merchant',
+ 'idx_audit_logs_entity',
+ 'idx_security_events_customer',
+ 'idx_security_events_session',
+ 'idx_security_events_type'
+ ];
+
+ for (const idx of requiredIndexes) {
+ assert.ok(pgIndexes.includes(idx), `schema.sql missing index: ${idx}`);
+ assert.ok(sqliteIndexes.includes(idx), `sqlite-schema.sql missing index: ${idx}`);
+ }
+ });
+
+ test('customers table has required security and fraud tracking columns in both schemas', () => {
+ const requiredCustomerCols = [
+ 'otp_attempts',
+ 'ban_reason',
+ 'banned_at',
+ 'unbanned_at',
+ 'last_device'
+ ];
+
+ for (const col of requiredCustomerCols) {
+ assert.ok(pgSchema.includes(col), `schema.sql customers table missing column: ${col}`);
+ assert.ok(sqliteSchema.includes(col), `sqlite-schema.sql customers table missing column: ${col}`);
+ }
+ });
+
+ test('sqlite-schema.sql executes cleanly and creates complete schema on fresh database', () => {
+ const db = new Database({ inMemory: true, autoMigrate: false });
+ try {
+ db.exec(sqliteSchema);
+ const tables = db.query("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%'");
+ const tableNames = tables.map(t => t.name);
+ assert.ok(tableNames.includes('merchants'));
+ assert.ok(tableNames.includes('payment_receiving_accounts'));
+ assert.ok(tableNames.includes('customers'));
+ assert.ok(tableNames.includes('devices'));
+ assert.ok(tableNames.includes('payment_sessions'));
+ assert.ok(tableNames.includes('payment_observations'));
+ assert.ok(tableNames.includes('webhook_deliveries'));
+ assert.ok(tableNames.includes('support_tickets'));
+ assert.ok(tableNames.includes('audit_logs'));
+ assert.ok(tableNames.includes('security_events'));
+ } finally {
+ db.close();
+ }
+ });
+});
diff --git a/packages/db/src/migrate.js b/packages/db/src/migrate.js
index 98a9c2a..d671f91 100644
--- a/packages/db/src/migrate.js
+++ b/packages/db/src/migrate.js
@@ -70,6 +70,11 @@ export function runMigrations(targetDb) {
try { db.exec("ALTER TABLE payment_sessions ADD COLUMN verification_level INTEGER DEFAULT 0;"); } catch {}
try { db.exec("ALTER TABLE payment_sessions ADD COLUMN verification_sources TEXT DEFAULT '[]';"); } catch {}
try { db.exec("ALTER TABLE payment_sessions ADD COLUMN verification_tag TEXT DEFAULT 'UNVERIFIED';"); } catch {}
+ try { db.exec("ALTER TABLE payment_sessions ADD COLUMN attempt_id TEXT;"); } catch {}
+ try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_single_active_session_per_order ON payment_sessions (merchant_id, order_id) WHERE status NOT IN ('FAILED', 'EXPIRED', 'CANCELLED');"); } catch {}
+ try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_one_slot_per_receiving_account ON payment_sessions (receiving_account_id) WHERE status IN ('ACTIVE', 'PROCESSING') AND receiving_account_id IS NOT NULL;"); } catch {}
+ try { db.exec("CREATE INDEX IF NOT EXISTS idx_payment_sessions_order ON payment_sessions (merchant_id, order_id, created_at);"); } catch {}
+ try { db.exec("CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_retry ON webhook_deliveries (is_successful, next_retry_at);"); } catch {}
try { db.exec("ALTER TABLE payment_receiving_accounts ADD COLUMN is_merchant_enabled INTEGER NOT NULL DEFAULT 1;"); } catch {}
try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_single_active_vpa_per_merchant ON payment_receiving_accounts (merchant_id) WHERE is_active = 1;"); } catch {}
try { db.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_customers_email ON customers (email);"); } catch {}
@@ -104,8 +109,10 @@ export function runMigrations(targetDb) {
`); } catch {}
try { db.exec("CREATE INDEX IF NOT EXISTS idx_devices_customer ON devices (customer_id);"); } catch {}
try { db.exec("CREATE INDEX IF NOT EXISTS idx_devices_fingerprint ON devices (fingerprint_hash);"); } catch {}
- try { db.exec("CREATE INDEX IF NOT EXISTS idx_devices_token ON devices (device_token);"); } catch {}
try { db.exec("CREATE INDEX IF NOT EXISTS idx_payment_sessions_device ON payment_sessions (device_id);"); } catch {}
+ try { db.exec("CREATE INDEX IF NOT EXISTS idx_observations_bank_ref ON payment_observations (bank_reference_number);"); } catch {}
+ try { db.exec("CREATE INDEX IF NOT EXISTS idx_observations_fingerprint ON payment_observations (fingerprint_hash);"); } catch {}
+ try { db.exec("CREATE INDEX IF NOT EXISTS idx_observations_attributed_payment ON payment_observations (attributed_payment_id);"); } catch {}
// Seed default merchant if empty
const merchantRepo = new MerchantRepository(db);
diff --git a/packages/db/src/schema.sql b/packages/db/src/schema.sql
index fa0a210..a9f38e3 100644
--- a/packages/db/src/schema.sql
+++ b/packages/db/src/schema.sql
@@ -42,8 +42,13 @@ CREATE TABLE IF NOT EXISTS customers (
password_hash VARCHAR(255),
otp_code VARCHAR(10),
otp_expires_at TIMESTAMPTZ,
+ otp_attempts INT NOT NULL DEFAULT 0,
is_phone_verified BOOLEAN DEFAULT false,
status VARCHAR(50) NOT NULL DEFAULT 'ACTIVE',
+ ban_reason TEXT,
+ banned_at TIMESTAMPTZ,
+ unbanned_at TIMESTAMPTZ,
+ last_device TEXT,
last_login_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
@@ -68,6 +73,28 @@ CREATE TABLE IF NOT EXISTS customer_sessions (
CREATE INDEX IF NOT EXISTS idx_customer_sessions_token ON customer_sessions (token, is_active);
CREATE INDEX IF NOT EXISTS idx_customer_sessions_customer ON customer_sessions (customer_id);
+-- 3c. Devices Table (Cryptographic Device Binding & Hardware Context Fingerprinting)
+CREATE TABLE IF NOT EXISTS devices (
+ id TEXT PRIMARY KEY,
+ customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,
+ public_key TEXT NOT NULL,
+ fingerprint_hash VARCHAR(64) NOT NULL,
+ user_agent TEXT,
+ platform VARCHAR(100),
+ browser VARCHAR(100),
+ timezone VARCHAR(100),
+ language VARCHAR(50),
+ screen_signature VARCHAR(100),
+ device_token VARCHAR(255) UNIQUE,
+ status VARCHAR(50) NOT NULL DEFAULT 'ACTIVE',
+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
+ last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
+);
+
+CREATE INDEX IF NOT EXISTS idx_devices_customer ON devices (customer_id);
+CREATE INDEX IF NOT EXISTS idx_devices_fingerprint ON devices (fingerprint_hash);
+CREATE INDEX IF NOT EXISTS idx_devices_token ON devices (device_token);
+
-- 4. Payment Sessions Table
CREATE TABLE IF NOT EXISTS payment_sessions (
id TEXT PRIMARY KEY,
@@ -75,6 +102,7 @@ CREATE TABLE IF NOT EXISTS payment_sessions (
customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,
receiving_account_id TEXT REFERENCES payment_receiving_accounts(id),
order_id VARCHAR(255) NOT NULL,
+ attempt_id TEXT,
amount_paise BIGINT NOT NULL CHECK (amount_paise > 0),
currency VARCHAR(3) NOT NULL DEFAULT 'INR',
method VARCHAR(50) NOT NULL DEFAULT 'UPI',
@@ -94,11 +122,18 @@ CREATE TABLE IF NOT EXISTS payment_sessions (
verification_tag VARCHAR(100) DEFAULT 'UNVERIFIED',
metadata TEXT NOT NULL DEFAULT '{}',
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
- updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
- CONSTRAINT uq_merchant_order UNIQUE (merchant_id, order_id)
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_payment_sessions_active ON payment_sessions (receiving_account_id, status);
+CREATE INDEX IF NOT EXISTS idx_payment_sessions_order ON payment_sessions (merchant_id, order_id, created_at);
+CREATE INDEX IF NOT EXISTS idx_payment_sessions_device ON payment_sessions (device_id);
+CREATE UNIQUE INDEX IF NOT EXISTS idx_single_active_session_per_order
+ ON payment_sessions (merchant_id, order_id)
+ WHERE status NOT IN ('FAILED', 'EXPIRED', 'CANCELLED');
+CREATE UNIQUE INDEX IF NOT EXISTS idx_one_slot_per_receiving_account
+ ON payment_sessions (receiving_account_id)
+ WHERE status IN ('ACTIVE', 'PROCESSING') AND receiving_account_id IS NOT NULL;
-- 5. Payment Observations Table
CREATE TABLE IF NOT EXISTS payment_observations (
@@ -118,6 +153,9 @@ CREATE TABLE IF NOT EXISTS payment_observations (
);
CREATE INDEX IF NOT EXISTS idx_observations_match ON payment_observations (receiving_account_id, amount_paise, attribution_status);
+CREATE INDEX IF NOT EXISTS idx_observations_bank_ref ON payment_observations (bank_reference_number);
+CREATE INDEX IF NOT EXISTS idx_observations_fingerprint ON payment_observations (fingerprint_hash);
+CREATE INDEX IF NOT EXISTS idx_observations_attributed_payment ON payment_observations (attributed_payment_id);
-- 6. Android Devices Table
CREATE TABLE IF NOT EXISTS android_devices (
@@ -148,6 +186,8 @@ CREATE TABLE IF NOT EXISTS webhook_deliveries (
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
+CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_retry ON webhook_deliveries (is_successful, next_retry_at);
+
-- 8. Support Tickets & Ticket Messages
CREATE TABLE IF NOT EXISTS support_tickets (
id TEXT PRIMARY KEY,
@@ -160,6 +200,9 @@ CREATE TABLE IF NOT EXISTS support_tickets (
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
+CREATE INDEX IF NOT EXISTS idx_support_tickets_merchant ON support_tickets (merchant_id);
+CREATE INDEX IF NOT EXISTS idx_support_tickets_customer ON support_tickets (customer_id);
+
CREATE TABLE IF NOT EXISTS ticket_messages (
id TEXT PRIMARY KEY,
ticket_id TEXT NOT NULL REFERENCES support_tickets(id) ON DELETE CASCADE,
@@ -170,6 +213,8 @@ CREATE TABLE IF NOT EXISTS ticket_messages (
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
+CREATE INDEX IF NOT EXISTS idx_ticket_messages_ticket ON ticket_messages (ticket_id);
+
-- 9. Audit Logs Table
CREATE TABLE IF NOT EXISTS audit_logs (
id TEXT PRIMARY KEY,
@@ -184,6 +229,9 @@ CREATE TABLE IF NOT EXISTS audit_logs (
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
+CREATE INDEX IF NOT EXISTS idx_audit_logs_merchant ON audit_logs (merchant_id);
+CREATE INDEX IF NOT EXISTS idx_audit_logs_entity ON audit_logs (entity_type, entity_id);
+
-- 10. Security Events Table
CREATE TABLE IF NOT EXISTS security_events (
id TEXT PRIMARY KEY,
@@ -205,26 +253,8 @@ CREATE TABLE IF NOT EXISTS security_events (
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
--- 11. Devices Table (Cryptographic Device Binding & Hardware Context Fingerprinting)
-CREATE TABLE IF NOT EXISTS devices (
- id TEXT PRIMARY KEY,
- customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,
- public_key TEXT NOT NULL,
- fingerprint_hash VARCHAR(64) NOT NULL,
- user_agent TEXT,
- platform VARCHAR(100),
- browser VARCHAR(100),
- timezone VARCHAR(100),
- language VARCHAR(50),
- screen_signature VARCHAR(100),
- device_token VARCHAR(255) UNIQUE,
- status VARCHAR(50) NOT NULL DEFAULT 'ACTIVE',
- created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
- last_seen_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
-);
+CREATE INDEX IF NOT EXISTS idx_security_events_customer ON security_events (customer_id);
+CREATE INDEX IF NOT EXISTS idx_security_events_session ON security_events (payment_session_id);
+CREATE INDEX IF NOT EXISTS idx_security_events_type ON security_events (event_type);
-CREATE INDEX IF NOT EXISTS idx_devices_customer ON devices (customer_id);
-CREATE INDEX IF NOT EXISTS idx_devices_fingerprint ON devices (fingerprint_hash);
-CREATE INDEX IF NOT EXISTS idx_devices_token ON devices (device_token);
-CREATE INDEX IF NOT EXISTS idx_payment_sessions_device ON payment_sessions (device_id);
diff --git a/packages/db/src/sqlite-schema.sql b/packages/db/src/sqlite-schema.sql
index 0243ce2..95220e8 100644
--- a/packages/db/src/sqlite-schema.sql
+++ b/packages/db/src/sqlite-schema.sql
@@ -43,6 +43,10 @@ CREATE TABLE IF NOT EXISTS customers (
otp_attempts INTEGER NOT NULL DEFAULT 0,
is_phone_verified INTEGER DEFAULT 0,
status TEXT NOT NULL DEFAULT 'ACTIVE',
+ ban_reason TEXT,
+ banned_at TEXT,
+ unbanned_at TEXT,
+ last_device TEXT,
last_login_at TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
@@ -67,6 +71,28 @@ CREATE TABLE IF NOT EXISTS customer_sessions (
CREATE INDEX IF NOT EXISTS idx_customer_sessions_token ON customer_sessions (token, is_active);
CREATE INDEX IF NOT EXISTS idx_customer_sessions_customer ON customer_sessions (customer_id);
+-- 3c. Devices Table (Cryptographic Device Binding & Hardware Context Fingerprinting)
+CREATE TABLE IF NOT EXISTS devices (
+ id TEXT PRIMARY KEY,
+ customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,
+ public_key TEXT NOT NULL,
+ fingerprint_hash TEXT NOT NULL,
+ user_agent TEXT,
+ platform TEXT,
+ browser TEXT,
+ timezone TEXT,
+ language TEXT,
+ screen_signature TEXT,
+ device_token TEXT UNIQUE,
+ status TEXT NOT NULL DEFAULT 'ACTIVE',
+ created_at TEXT NOT NULL DEFAULT (datetime('now')),
+ last_seen_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+
+CREATE INDEX IF NOT EXISTS idx_devices_customer ON devices (customer_id);
+CREATE INDEX IF NOT EXISTS idx_devices_fingerprint ON devices (fingerprint_hash);
+CREATE INDEX IF NOT EXISTS idx_devices_token ON devices (device_token);
+
-- 4. Payment Sessions Table
CREATE TABLE IF NOT EXISTS payment_sessions (
id TEXT PRIMARY KEY,
@@ -74,6 +100,7 @@ CREATE TABLE IF NOT EXISTS payment_sessions (
customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,
receiving_account_id TEXT REFERENCES payment_receiving_accounts(id),
order_id TEXT NOT NULL,
+ attempt_id TEXT,
amount_paise INTEGER NOT NULL CHECK (amount_paise > 0),
currency TEXT NOT NULL DEFAULT 'INR',
method TEXT NOT NULL DEFAULT 'UPI',
@@ -93,11 +120,17 @@ CREATE TABLE IF NOT EXISTS payment_sessions (
verification_tag TEXT DEFAULT 'UNVERIFIED',
metadata TEXT NOT NULL DEFAULT '{}',
created_at TEXT NOT NULL DEFAULT (datetime('now')),
- updated_at TEXT NOT NULL DEFAULT (datetime('now')),
- UNIQUE(merchant_id, order_id)
+ updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
CREATE INDEX IF NOT EXISTS idx_payment_sessions_active ON payment_sessions (receiving_account_id, status);
+CREATE INDEX IF NOT EXISTS idx_payment_sessions_order ON payment_sessions (merchant_id, order_id, created_at);
+CREATE INDEX IF NOT EXISTS idx_payment_sessions_device ON payment_sessions (device_id);
+-- At most one active/processing/queued/successful session per merchant order.
+-- Retrying a terminal (FAILED, EXPIRED, CANCELLED) order allows a new attempt with the true orderId.
+CREATE UNIQUE INDEX IF NOT EXISTS idx_single_active_session_per_order
+ ON payment_sessions (merchant_id, order_id)
+ WHERE status NOT IN ('FAILED', 'EXPIRED', 'CANCELLED');
-- Slot exclusivity is a database invariant, not an application convention: at most one
-- session per receiving account may occupy the slot (ACTIVE or PROCESSING) at any time.
-- Concurrent writers are rejected by the engine instead of relying on lock contention.
@@ -123,6 +156,9 @@ CREATE TABLE IF NOT EXISTS payment_observations (
);
CREATE INDEX IF NOT EXISTS idx_observations_match ON payment_observations (receiving_account_id, amount_paise, attribution_status);
+CREATE INDEX IF NOT EXISTS idx_observations_bank_ref ON payment_observations (bank_reference_number);
+CREATE INDEX IF NOT EXISTS idx_observations_fingerprint ON payment_observations (fingerprint_hash);
+CREATE INDEX IF NOT EXISTS idx_observations_attributed_payment ON payment_observations (attributed_payment_id);
-- 6. Android Devices Table
CREATE TABLE IF NOT EXISTS android_devices (
@@ -153,6 +189,8 @@ CREATE TABLE IF NOT EXISTS webhook_deliveries (
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
+CREATE INDEX IF NOT EXISTS idx_webhook_deliveries_retry ON webhook_deliveries (is_successful, next_retry_at);
+
-- 8. Support Tickets & Ticket Messages
CREATE TABLE IF NOT EXISTS support_tickets (
id TEXT PRIMARY KEY,
@@ -165,6 +203,9 @@ CREATE TABLE IF NOT EXISTS support_tickets (
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
);
+CREATE INDEX IF NOT EXISTS idx_support_tickets_merchant ON support_tickets (merchant_id);
+CREATE INDEX IF NOT EXISTS idx_support_tickets_customer ON support_tickets (customer_id);
+
CREATE TABLE IF NOT EXISTS ticket_messages (
id TEXT PRIMARY KEY,
ticket_id TEXT NOT NULL REFERENCES support_tickets(id) ON DELETE CASCADE,
@@ -175,6 +216,8 @@ CREATE TABLE IF NOT EXISTS ticket_messages (
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
+CREATE INDEX IF NOT EXISTS idx_ticket_messages_ticket ON ticket_messages (ticket_id);
+
-- 9. Audit Logs Table
CREATE TABLE IF NOT EXISTS audit_logs (
id TEXT PRIMARY KEY,
@@ -189,6 +232,9 @@ CREATE TABLE IF NOT EXISTS audit_logs (
created_at TEXT NOT NULL DEFAULT (datetime('now'))
);
+CREATE INDEX IF NOT EXISTS idx_audit_logs_merchant ON audit_logs (merchant_id);
+CREATE INDEX IF NOT EXISTS idx_audit_logs_entity ON audit_logs (entity_type, entity_id);
+
-- 10. Security Events Table (Forensic evidence for fraud, automatic and manual bans)
CREATE TABLE IF NOT EXISTS security_events (
id TEXT PRIMARY KEY,
@@ -214,27 +260,5 @@ CREATE INDEX IF NOT EXISTS idx_security_events_customer ON security_events (cust
CREATE INDEX IF NOT EXISTS idx_security_events_session ON security_events (payment_session_id);
CREATE INDEX IF NOT EXISTS idx_security_events_type ON security_events (event_type);
--- 11. Devices Table (Cryptographic Device Binding & Hardware Context Fingerprinting)
-CREATE TABLE IF NOT EXISTS devices (
- id TEXT PRIMARY KEY,
- customer_id TEXT REFERENCES customers(id) ON DELETE SET NULL,
- public_key TEXT NOT NULL,
- fingerprint_hash TEXT NOT NULL,
- user_agent TEXT,
- platform TEXT,
- browser TEXT,
- timezone TEXT,
- language TEXT,
- screen_signature TEXT,
- device_token TEXT UNIQUE,
- status TEXT NOT NULL DEFAULT 'ACTIVE',
- created_at TEXT NOT NULL DEFAULT (datetime('now')),
- last_seen_at TEXT NOT NULL DEFAULT (datetime('now'))
-);
-
-CREATE INDEX IF NOT EXISTS idx_devices_customer ON devices (customer_id);
-CREATE INDEX IF NOT EXISTS idx_devices_fingerprint ON devices (fingerprint_hash);
-CREATE INDEX IF NOT EXISTS idx_devices_token ON devices (device_token);
-CREATE INDEX IF NOT EXISTS idx_payment_sessions_device ON payment_sessions (device_id);
diff --git a/scripts/test-all.js b/scripts/test-all.js
index 7ba8d26..62a28b5 100644
--- a/scripts/test-all.js
+++ b/scripts/test-all.js
@@ -5,6 +5,7 @@ const testFiles = [
'packages/db/src/__tests__/customer-reset.test.js',
'packages/db/src/__tests__/auth-matrix.test.js',
'packages/db/src/__tests__/db.test.js',
+ 'packages/db/src/__tests__/schema-parity.test.js',
'packages/core/src/__tests__/core.test.js',
'packages/core/src/__tests__/queue-timing.test.js',
'packages/core/src/__tests__/webhook-engine.test.js',
@@ -31,6 +32,7 @@ const testFiles = [
'apps/payment-api/src/__tests__/whatsapp-berry-auth.test.js',
'apps/payment-api/src/__tests__/whitelabel-branding.test.js',
'apps/payment-api/src/__tests__/cod-parallel-timer-decoupling.test.js',
+ 'apps/payment-api/src/__tests__/gateway-hardening-invariants.test.js',
'scripts/chaos-concurrency.test.js',
'scripts/production-infrastructure.test.js'
];