POS Çift Harcama Önleme: TOTP ve Idempotency
Kasada dönen barkodların, idempotent API uç noktalarının ve fraud önleme katmanlarının mimarisini keşfedin.
Türkçe özet: Bu makale loyalisa ekibi tarafından hazırlanmıştır. Aşağıdaki içerik İngilizce teknik kaynağın Türkçe yerelleştirilmiş özetidir; ayrıntılı teknik bölümler orijinal yapıyı korur.
POS Çift Harcama Önleme: TOTP ve Idempotency
Loyalisa dijital sadakat platformu, özel kahve dükkanları ve çok şubeli kafe zincirleri için tasarlanmıştır. Dijital damga kartları, Apple/Google Wallet entegrasyonu ve fraud-proof barkodlar ile müşteri elde tutmayı ölçülebilir şekilde artırır.
High-Performance POS Gateways: Bulletproof Transaction Integrity
In high-volume hospitality environments like busy coffee roasteries, speed is everything. During peak morning rushes, checkout latency must remain under 300 milliseconds. Even minor delays in applying loyalty stamps or redeeming free items can backup a physical queue, causing frustration for both baristas and customers.
However, high speed cannot compromise security. In loyalty systems, two primary exploit vectors must be strictly mitigated:
- Double-Spend Attacks: Attempting to scan a single digital reward barcode multiple times in parallel, or sharing a screenshot of a high-value free V60 reward card with multiple users.
- Replay Latency / Packet Loss: Network disruptions at the POS terminal causing a stamp transaction to be retried multiple times, risking duplicate stamps.
At Loyalisa, we solved this by implementing an architectural-grade transaction integrity engine based on Time-Based One-Time Passwords (TOTP) and Strict Idempotency Keys. Here is a detailed look at how we enforce security without slowing down checkout throughput. To test this checkout pipeline yourself, check out our interactive Live Demo.
1. Preventing Screengrab Sharing with Rotational TOTP Barcodes
To eliminate the risk of screenshot sharing or barcode recycling, Loyalisa does not display static customer IDs in its digital wallet barcodes. Instead, the frontend PWA and native Apple Wallet passes utilize a cryptographically secure, rotating transaction token.
This token is generated using the standard RFC 6238 Time-Based One-Time Password (TOTP) algorithm, customized for low-latency barcode rendering.
How the Token is Generated & Verified:
- Shared Secret: During registration, each customer is assigned a cryptographically random 256-bit secret key (K), stored securely in our central PostgreSQL database and on the client's local keychain (using Isar on mobile/PWA).
- Time Step ($T$): The system rotates the barcode every 30 seconds (T_X = 30).
- HMAC Calculation: The client hashes the current time window counter (C = ⌊ Epoch Time / 30 ⌋) against the shared secret (K) using the HMAC-SHA256 algorithm:
HMAC-Value = HMAC-SHA256(K, C)
- Token Truncation: The system truncates the resulting hash to a 10-digit numeric value, prepending the client’s tenant ID. This combined value is rendered as a dynamic Aztec or PDF417 barcode.
When a barista scans the barcode, the POS gateway immediately decomposes the scanned token:
interface ScannedBarcode {
customerId: string;
totpToken: string;
}
function verifyBarcodeScan(
scanned: ScannedBarcode,
clientSecret: string,
clockDriftBuffer: number = 1 // Allow 1 time-step drift (+/- 30s)
): boolean {
const currentTime = Math.floor(Date.now() / 1000);
const currentStep = Math.floor(currentTime / 30);
// Check current step and surrounding buffer to accommodate network latency
for (let i = -clockDriftBuffer; i <= clockDriftBuffer; i++) {
const calculatedToken = generateTOTP(clientSecret, currentStep + i);
if (calculatedToken === scanned.totpToken) {
return true;
}
}
return false;
}If a customer captures a screenshot of their barcode and sends it to a friend, the screengrab becomes completely invalid within 30 seconds, neutralizing the screenshot exploit vector.
2. Eliminating Transaction Regressions with Idempotency Keys
When POS terminals operate in areas with unstable Wi-Fi, connection drops frequently occur midway through processing a stamp. If a barista taps the stamp button, and the connection drops during the HTTP transit, the terminal will automatically retry the request.
Without strict idempotency controls, this retry would result in applying two stamps for a single coffee purchase.
To prevent this, every transaction in the Loyalisa ecosystem requires a unique, client-generated Idempotency Key (UUID v4) sent in the custom X-Idempotency-Key HTTP header.
Backend Idempotency Pipeline:
- The Request: The POS scans the card and sends:
POST /v1/transactions
X-Idempotency-Key: c9a5a3a7-e85d-4f1c-9de6-419df256d0a7
Content-Type: application/json
{
"customerId": "usr_9918a",
"stampsToApply": 1
}- The Redis Distributed Lock: The server instantly attempts to acquire a short-lived lock (e.g., 5 seconds) on the idempotency key:
- Command:
SETNX lock:idempotency:c9a5a3a7... 1 EX 5 - If the lock is not acquired, the backend returns
409 Conflict, preventing parallel race conditions.
- Lookup Cache: The server queries our Redis/Flatfile key-value store to see if this idempotency key already exists.
- Case A (Exists): The request has already been completed. The server immediately bypasses the database and returns the exact identical HTTP response payload and headers stored from the first request.
- Case B (New): The server processes the stamp in a transaction, stores the final result in PostgreSQL, caches the result in Redis with an 86400-second (24-hour) TTL, and releases the temporary lock.
3. Gateway Architecture Performance Benchmarks
Our Elysia framework server, operating with a pool of optimized database connections, guarantees reliable execution under massive retail pressure. Here are our actual performance metrics for POS transaction evaluations:
| Scenario | Cache / Lock State | Target Latency | DB Impact | Result |
|---|---|---|---|---|
| Initial Scan | Cache Miss / Acquire Lock | 45ms | 1 Read, 1 Write | Stamps applied, cached, returned |
| Duplicate Retry (within 1s) | Locked | 12ms | 0 DB Queries | 409 Conflict returned |
| Replay Request (within 24h) | Cache Hit (Redis) | 8ms | 0 DB Queries | Original response payload returned |
| Offline Recovery | Local Queue / SQLite Cache | < 1ms | 0 DB Queries | Queued in isolate buffer |
By wrapping every customer scan in a rotating TOTP token and enforcing strict transaction-level idempotency headers, Loyalisa guarantees a zero-drift ledger system. Café owners get a 100% accurate loyalty log, and baristas get a reliable checkout tool that never lags during the morning peak.