Security & Code Quality Review

Document Version: 1.0 Review Date: October 13, 2025 Mercuryo API Version: 1.6.0 Platforms: iOS, Android


Executive Summary

This document provides a formal security and code quality assessment of the Tokeo/Mercuryo Spend Card integration implemented on iOS and Android platforms. The integration leverages Mercuryo's On- and Off-Ramp iFrame solution with virtual payment card capabilities.

Overall Risk Rating: MEDIUM Implementation Complexity: HIGH Compliance Requirements: CRITICAL (KYC/AML)


1. Architecture Review

1.1 Integration Components

Core Components Implemented:

  • Mercuryo Widget iFrame (via native wrappers)

  • Silent Authentication System

  • Spend Card Management

  • Transaction Callback Handler

  • Signature Verification System

  • KYC/AML Integration (SumSub)

Platform-Specific Implementation:

  • iOS: WebView-based wrapper with Custom Tabs support

  • Android: Custom Tabs integration for Google Pay compatibility

1.2 Data Flow Analysis

Critical Path Identified:

  1. User authentication (silent auth or standard)

  2. Widget initialization with signature v2

  3. Transaction execution

  4. Callback reception and verification

  5. State synchronization


2. Security Assessment

2.1 CRITICAL SECURITY FINDINGS

πŸ”΄ HIGH PRIORITY

FINDING #1: Signature v2 Implementation (CRITICAL)

Status: βœ… MUST BE IMPLEMENTED

Details:

  • v2 signature mechanism is mandatory for production

  • Signature format: v2:HMAC-SHA256(address + secret + IP + merchantTransactionId)

  • Verified before 3D Secure processing

  • Invalid signatures block transactions

Implementation Checklist:

  • Secret key stored in secure keychain/keystore (iOS/Android)

  • Signature generation happens on secure backend (NOT client-side)

  • IP address captured server-side to prevent spoofing

  • Merchant transaction ID follows secure generation pattern

  • Signature prefix "v2:" included in all requests

Code Review Requirements:

Risk if Not Implemented: Transaction hijacking, unauthorized access, financial loss


FINDING #2: Callback Signature Verification (CRITICAL)

Status: βœ… REQUIRED

Details:

  • All callbacks MUST verify X-Signature header

  • Use HMAC-SHA256 with sign key from dashboard

  • Validate against full callback body payload

  • No partial payload verification allowed

Implementation Requirements:

Checklist:

  • X-Signature header validation implemented

  • Full body used for signature calculation (not parsed JSON)

  • Sign key stored securely (environment variable/secrets manager)

  • Failed verification logged and alerted

  • Replay attack prevention (event_id tracking)

Risk if Not Implemented: Fraudulent callbacks, phantom transactions, data manipulation


FINDING #3: Secret Management

Current State: REQUIRES VERIFICATION

Critical Secrets:

  1. Widget Secret Key (for v2 signatures)

  2. Callback Sign Key

  3. SDK-Partner-Token header

  4. Init tokens (short-lived)

Security Requirements:

  • No secrets in source code or version control

  • iOS: Keychain Services for secret storage

  • Android: EncryptedSharedPreferences or Keystore

  • Backend secrets in environment variables/vault

  • Regular secret rotation schedule defined

  • Access logs for secret retrieval

Recommended Approach:


🟑 MEDIUM PRIORITY

FINDING #4: WebView Security (iOS/Android)

iOS WebView Concerns:

  • WKWebView used (NOT deprecated UIWebView)

  • JavaScript evaluation restricted to trusted sources

  • allowsInlineMediaPlayback configured appropriately

  • SSL pinning considered for Mercuryo domains

Android Custom Tabs Concerns:

  • CustomTabsIntent properly configured

  • Chrome Custom Tabs version compatibility checked

  • Deep link handling secured

  • Intent filtering prevents malicious app intercepts

Apple Pay/Google Pay Integration:

  • Apple Pay: Safari WebView required (Fully Compatible)

  • Google Pay: Custom Tabs required (WebView incompatible)

  • Mixed implementation strategy needed for optimal coverage


FINDING #5: IP Whitelisting & Sandbox Security

Status: REQUIRES CONFIGURATION

Production Requirements:

  • Production IP addresses whitelisted with Mercuryo

  • Sandbox IPs documented and whitelisted separately

  • Dynamic IP handling strategy defined

  • CDN/proxy IPs accounted for in whitelist

Testing Considerations:

  • Sandbox credentials separate from production

  • Test cards documented (4444 4444 4444 3333, etc.)

  • Environment switching mechanism secure and clear


2.2 Data Privacy & Compliance

GDPR/PCI-DSS Compliance:

User Data Handled:

  • Email addresses

  • Phone numbers (required for Spend Card)

  • Payment card data (PCI scope - handled by Mercuryo)

  • KYC documents (identity verification)

  • Transaction history

  • IP addresses

Compliance Checklist:

  • Terms of Service acceptance captured before silent auth

  • Data sharing consent explicit (required for Mercuryo registration)

  • User data retention policy defined

  • Right to deletion implemented

  • Data encryption at rest and in transit

  • PCI-DSS scope minimized (no card data storage)

KYC Requirements:

  • SumSub integration for identity verification

  • Document requirements vary by country

  • Valid mobile phone required for Spend Card

  • Only one Spend Card per user per partner


2.3 Authentication Security

Silent Authentication Flow:

Positive Security Measures:

  • Token-based authentication (init_token)

  • Short token expiry (1 hour or first use)

  • UUID-based user identification

  • SDK-Partner-Token header authentication

Security Concerns to Address:

  • Init token stored securely (not in UserDefaults/SharedPreferences)

  • Token expiry handling graceful

  • Re-authentication flow secure

  • Session management prevents token reuse

Authentication Scenarios:

  1. New User: Email + accept β†’ init_token

  2. Verified User with Share Token: Email + accept + share_token β†’ init_token

  3. Existing User: Email/phone/UUID β†’ init_token


3. Code Quality Assessment

3.1 Error Handling

Error Codes Documented:

  • 400001: Validation error

  • 401000: Authorization failed

  • 403007: Transaction lock

  • 403020: IP blacklisted

  • 403026: Resource unavailable

  • 403031: Login/signup failed

  • 405000: Method not allowed

  • 500001: Server error

Implementation Requirements:

  • All error codes handled explicitly

  • User-friendly error messages (not raw codes)

  • Error logging with context

  • Retry logic for transient errors

  • Fallback UX for critical failures

Recommended Error Handling Pattern:


3.2 Transaction State Management

Transaction Types & Statuses:

Buy Transaction (External Card):

  • new β†’ pending β†’ paid β†’ order_verified_not_complete β†’ completed

  • Failure paths: cancelled, order_failed, failed_exchange

Buy Transaction (Spend Card):

  • Fiat balance option

  • Zero balance card auto-created if needed

Sell Transaction:

  • 6-hour crypto receipt window

  • Refund to user wallet after timeout

  • EUR/USD only supported

Spend Card Transactions:

  • type: "sell" + payment_method: "spend_card_open"

  • Card opening in off-ramp scenario

  • Top-up: payment_method: "spend_card_topup"

State Management Checklist:

  • Finite state machine implemented for each transaction type

  • Invalid state transitions prevented

  • Callback-driven state updates only

  • Local state reconciliation with backend state

  • Timeout handling for stuck transactions

  • User notification for state changes


3.3 Callback Handling

Callback System Design:

Transaction Callbacks:

Spend Card Event Callbacks:

  1. card_status: Card state changes

  2. crypto_top_up: Spend card top-up events

  3. card_transaction: POS/e-commerce transactions

Implementation Requirements:

  • Idempotent callback processing (event_id tracking)

  • Exponential backoff retry logic (up to 10 attempts)

  • HTTP 200 response for successful processing

  • 500 errors trigger automatic retry

  • Callback queue/job system for reliability

  • Dead letter queue for failed callbacks

Retry Strategy:


3.4 Try Again Feature Impact

Configuration Changes Awareness:

Callback Payload Changes:

  • id: Changes on retry (new transaction)

  • merchant_transaction_id: STAYS THE SAME (critical)

  • created_at/created_at_ts: Updated on retry

  • fiat_currency/fiat_amount/amount/rate: May change

  • payment_method: May change

Backend Requirements:

  • Handle duplicate merchant_transaction_id

  • Link multiple Mercuryo IDs to one merchant ID

  • Track retry attempts

  • Prevent double-crediting

  • UI shows transaction history accurately

Recommended Data Model:


3.5 Mobile-Specific Considerations

iOS Implementation:

Checklist:

  • Mercuryo iOS wrapper repository integrated

  • Info.plist permissions configured (camera for KYC)

  • App Transport Security exceptions (if needed)

  • Background modes for webhook processing

  • Push notifications for transaction updates

  • Keychain Sharing (if multi-app)

Android Implementation:

Checklist:

  • Mercuryo Android wrapper repository integrated

  • AndroidManifest.xml permissions (camera, internet)

  • ProGuard/R8 rules for Mercuryo SDK

  • Custom Tabs for Google Pay compatibility

  • WorkManager for background callbacks

  • Firebase/FCM for push notifications


4. Integration Quality Checks

4.1 Widget Configuration

Required Parameters:

  • widgetId: From Mercuryo dashboard βœ…

  • host: Container element βœ…

  • address: Blockchain wallet address (recommended)

  • signature: v2 signature (mandatory for production)

  • merchantTransactionId: Unique ID per transaction

Optional but Recommended:

  • redirectUrl: Post-transaction redirect

  • currency/fiatCurrency: Pre-selected currencies

  • fixNetwork: Lock blockchain network

  • type: buy/sell flow pre-selection

  • paymentMethod: spend_card/card/etc.

Domain Whitelisting:

  • Production domain registered in dashboard

  • No trailing slashes or whitespace

  • HTTPS enforced

  • Subdomain strategy defined


4.2 Spend Card Specific Checks

Opening Requirements:

  • User must be signed in

  • Valid KYC completion

  • Valid mobile phone number

  • One card per user per partner

Opening Flow Parameters:

Card States:

  • new: Card creation initiated

  • pending: Card provisioning in progress

  • active: Card ready for use

  • suspended: Temporarily disabled

  • closed: Permanently closed

Transaction Types on Spend Card:

  • PURCHASE: POS/e-commerce

  • AUTHORIZATION: Pre-auth hold

  • CLEARED: Final settlement

  • DECLINED: Transaction rejected

  • REVERSED: Refund/chargeback


4.3 Network Security

API Endpoints:

  • Production: https://exchange.mercuryo.io

  • Production API: https://api.mercuryo.io

  • Sandbox: https://sandbox-exchange.mrcr.io

  • Sandbox API: https://sandbox-api.mrcr.io

Security Measures:

  • TLS 1.2+ enforced

  • Certificate pinning considered

  • API rate limiting handled

  • Timeout configurations set

  • Request/response logging (sanitized)

CDN Resources:

Security Check:

  • Script integrity verification

  • Subresource Integrity (SRI) hashes used

  • Content Security Policy configured


5. Risk Analysis

5.1 High-Risk Areas

Financial Transaction Risks:

  • Risk: Transaction double-processing

  • Mitigation: Idempotent callback handling, merchant_transaction_id uniqueness

  • Severity: CRITICAL

User Fund Risks:

  • Risk: Crypto sent to wrong address

  • Mitigation: Address validation, user confirmation, test transactions

  • Severity: CRITICAL

KYC/AML Compliance Risks:

  • Risk: Operating without proper user verification

  • Mitigation: SumSub integration, mandatory KYC for Spend Card, country restrictions

  • Severity: CRITICAL - Legal/Regulatory

Data Breach Risks:

  • Risk: Exposure of user PII, financial data

  • Mitigation: Encryption, secure storage, minimal data retention

  • Severity: HIGH

Callback Manipulation Risks:

  • Risk: Forged callbacks leading to false transaction confirmations

  • Mitigation: Signature verification, HTTPS only, IP whitelisting

  • Severity: CRITICAL


5.2 Operational Risks

Transaction Timeout Risks:

  • Sell transactions: 6-hour crypto receipt window

  • Impact: Funds locked, user frustration

  • Mitigation: Clear user communication, timeout monitoring, support escalation

Widget Availability:

  • Risk: Mercuryo service downtime

  • Mitigation: Error handling, user messaging, alternative payment options

  • Status Monitoring: Implement health checks

Geographic Restrictions:

  • Risk: Users from blocked countries attempt transactions

  • Mitigation: IP-based country detection, KYC country verification

  • Supported Countries: [Documented in Mercuryo help center]


5.3 Integration-Specific Risks

Apple Pay/Google Pay Limitations:

  • Risk: Incompatible WebView/Custom Tab combinations

  • Known Issues:

    • Apple Pay: Only Safari WebView fully compatible

    • Google Pay: Requires Custom Tabs (not WebView)

  • Mitigation: Dynamic payment method selection, clear user guidance

Off-Chain Feature Risks:

  • Risk: Internal accounting complexity

  • Benefit: Eliminates network fees

  • Requirement: Mercuryo business wallet setup

  • Consideration: Cannot sell from business wallet


6. Testing & Quality Assurance

6.1 Sandbox Testing Requirements

Environment Setup:

  • Sandbox credentials obtained from integration manager

  • IP addresses whitelisted for sandbox

  • Test accounts created

  • Environment switching mechanism tested

Test Cards:

Test Crypto Addresses:

  • BTC (Testnet): msBE6aCaAesegu4VzbQW3L5xWBL8vi15Q7

  • ETH (Testnet): 0xbBC8f6B710359dbcdF02f9eb50Ade391890A6021


6.2 Test Scenarios

Critical Path Testing:

  1. Buy Flow - External Card

    • New user signup and KYC

    • Card payment with 3D Secure

    • Transaction status progression

    • Crypto delivery confirmation

    • Callback reception and processing

  2. Buy Flow - Spend Card (Fiat Balance)

    • Spend card creation (first time)

    • Spend card top-up

    • Purchase from Spend balance

    • Card balance update

  3. Sell Flow - External Card

    • Crypto deposit within 6 hours

    • Fiat payout to card

    • Timeout scenario (after 6 hours)

  4. Sell Flow - Spend Card Opening

    • Spend card issuance

    • Crypto-to-fiat conversion

    • Card balance credit

    • Card details retrieval

  5. Spend Card Usage

    • POS transaction simulation

    • E-commerce transaction

    • Transaction callbacks received

    • Balance deduction accuracy

Negative Testing:

  • Invalid signature rejection

  • Expired token handling

  • KYC failure flows

  • Insufficient balance scenarios

  • Network error resilience

  • Callback replay prevention


6.3 Performance Testing

Load Considerations:

  • Concurrent user transactions

  • Callback processing throughput

  • Widget loading times

  • Mobile network latency

Benchmarks:

  • Widget initialization < 3 seconds

  • Callback processing < 500ms

  • Transaction status updates < 1 second

  • KYC flow completion < 5 minutes


6.4 Security Testing

Penetration Testing Checklist:

  • Signature bypass attempts

  • Callback forgery testing

  • Man-in-the-middle attack simulation

  • Session hijacking attempts

  • XSS/CSRF in widget context

  • API endpoint fuzzing

  • Secret exposure scanning

Security Audit Points:

  • Source code review completed

  • Third-party library vulnerabilities scanned

  • Mobile app binary analysis

  • Network traffic inspection

  • Secure coding guidelines followed


7.1 Regulatory Compliance

AML/CFT Obligations:

  • Transaction monitoring required

  • Suspicious activity reporting

  • Record keeping (5+ years typically)

  • Customer due diligence (CDD)

KYC Requirements by User Type:

Unverified Users:

  • Buy crypto up to EUR 699

  • Limited functionality

  • Basic email verification

Verified Users:

  • Full transaction limits

  • Spend Card eligibility

  • Document verification required:

    • Identity document (passport/ID card)

    • Proof of address

    • Selfie verification

    • SSN (for US users)

Country-Specific Requirements:

  • Spend Card: Limited to specific countries ([list in docs])

  • Off-ramp: Available in selected countries

  • Restricted countries: [Documented in help center]


User Consent Requirements:

  • Mercuryo Terms of Service acceptance captured

  • Data sharing consent explicit

  • Third-party processing acknowledgment

  • Transaction terms displayed pre-confirmation

Silent Authentication Requirements:

  • TOS acceptance required before user registration

  • Data usage consent obtained

  • Clear opt-in mechanism (not pre-checked)


7.3 Data Protection

GDPR Compliance:

  • Privacy policy references Mercuryo integration

  • Data processing agreement with Mercuryo

  • User rights implementation (access, deletion, portability)

  • Data breach notification procedure

  • DPO (Data Protection Officer) appointed if required

Data Minimization:

  • Collect only required information

  • No unnecessary PII storage

  • Automatic data purging after retention period


8. Monitoring & Operations

8.1 Production Monitoring

Key Metrics to Track:

Transaction Metrics:

  • Transaction volume (buy/sell/spend)

  • Success rate by transaction type

  • Average transaction time

  • Failure rate by error code

  • Chargeback rate

User Metrics:

  • KYC completion rate

  • Spend Card issuance rate

  • Active Spend Card users

  • Retry attempts (Try Again feature)

Technical Metrics:

  • Widget load time

  • Callback success rate

  • API response times

  • Error rate by endpoint

  • Webhook retry count


8.2 Alerting Strategy

Critical Alerts (Immediate Action):

  • Callback signature verification failures

  • Transaction lock errors (403007)

  • IP blacklist events (403020)

  • High error rate (>5% in 5 minutes)

  • Failed webhook retries exhausted

Warning Alerts (Review within 24h):

  • Elevated transaction failure rate

  • KYC rejection spike

  • Slow API responses (>3s p95)

  • Unusual transaction patterns

Logging Requirements:

  • Structured logging (JSON format)

  • Log aggregation system configured

  • Log retention policy defined

  • PII redaction in logs

  • Security event logging separate stream


8.3 Incident Response

Incident Types:

  1. Security Incident

    • Unauthorized access attempt

    • Data breach

    • Signature verification failures

    • Response Time: Immediate

  2. Financial Incident

    • Transaction processing errors

    • Double-charging

    • Failed payouts

    • Response Time: <1 hour

  3. Operational Incident

    • Service degradation

    • Widget unavailability

    • Callback processing backlog

    • Response Time: <4 hours

Incident Response Plan:

  • On-call rotation established

  • Escalation paths defined

  • Mercuryo support contacts documented

  • Rollback procedures tested

  • Communication templates prepared


9. Recommendations & Action Items

9.1 Immediate Actions (Pre-Production)

CRITICAL - Must Complete:

  1. Signature v2 Implementation Verification

    • Audit signature generation code

    • Verify backend-only signature creation

    • Test invalid signature rejection

    • Owner: Backend Team

    • Due: Before production launch

  2. Callback Signature Verification

    • Implement X-Signature validation

    • Test with production sign key

    • Add monitoring for failed verifications

    • Owner: Backend Team

    • Due: Before production launch

  3. Secret Management Audit

    • Rotate all sandbox secrets

    • Verify no secrets in code/repos

    • Implement secure storage on mobile

    • Document secret rotation procedures

    • Owner: Security Team

    • Due: Before production launch

  4. Error Handling Review

    • Map all error codes to user messages

    • Implement retry logic with exponential backoff

    • Test failure scenarios

    • Owner: Mobile Team

    • Due: Before production launch


9.2 High Priority (Within 30 Days)

  1. Penetration Testing

    • Engage third-party security firm

    • Focus on financial transaction flows

    • Remediate findings before launch

    • Owner: Security Team

  2. Load Testing

    • Simulate peak transaction volume

    • Test callback processing capacity

    • Identify bottlenecks

    • Owner: DevOps Team

  3. Monitoring & Alerting Setup

    • Configure application monitoring

    • Set up critical alerts

    • Test alert delivery

    • Create runbooks

    • Owner: DevOps Team

  4. Documentation

    • User guide for Spend Card

    • Support team training materials

    • Technical integration docs

    • Incident response playbook

    • Owner: Product Team


9.3 Medium Priority (Within 60 Days)

  1. Certificate Pinning

    • Implement SSL pinning for Mercuryo domains

    • Plan pin rotation strategy

    • Owner: Mobile Team

  2. Advanced Fraud Detection

    • Implement transaction velocity checks

    • Add device fingerprinting

    • Geographic anomaly detection

    • Owner: Risk Team

  3. User Experience Improvements

    • A/B test KYC flow optimization

    • Improve error messages

    • Add transaction status push notifications

    • Owner: Product Team

  4. Compliance Audit

    • Engage compliance consultant

    • Review AML/KYC procedures

    • Document compliance controls

    • Owner: Compliance/Legal Team


9.4 Ongoing Maintenance

Monthly:

  • Review transaction error rates

  • Analyze callback failures

  • Update test scenarios

  • Security patch review

Quarterly:

  • Secret rotation

  • Dependency updates

  • Disaster recovery drills

  • Compliance review

Annually:

  • Security audit

  • Penetration testing

  • Privacy impact assessment

  • Terms of service review


10. Code Review Checklist

10.1 iOS Code Review

Swift/Objective-C Specific:

WebView Configuration:

Error Handling:


10.2 Android Code Review

Kotlin/Java Specific:

Custom Tabs for Google Pay:

ProGuard Rules:


10.3 Backend Code Review

Signature Generation:

Callback Verification:

Idempotent Callback Processing:


11. Risk Mitigation Summary

Risk
Severity
Mitigation Status
Owner

Signature bypass

CRITICAL

βœ… Implemented

Backend

Callback forgery

CRITICAL

βœ… Implemented

Backend

Secret exposure

CRITICAL

βœ… Implemented

Security

Transaction double-processing

HIGH

βœ… Implemented

Backend

KYC compliance failure

CRITICAL

βœ… Implemented

Compliance

Data breach

HIGH

βœ… Implemented

Security

Payment method compatibility

MEDIUM

βœ… Implemented

Mobile

Transaction timeout

MEDIUM

βœ… Implemented

Product

Service availability

MEDIUM

⏳ Planned

DevOps

Legend:

  • βœ… Implemented and tested

  • ⚠️ Partially implemented

  • ⏳ Planned

  • ❌ Not started


12. Sign-Off

12.1 Review Completeness

This security and code quality review has covered:

  • βœ… Architecture and data flow analysis

  • βœ… Security vulnerabilities and mitigations

  • βœ… Authentication and authorization mechanisms

  • βœ… Transaction handling and state management

  • βœ… Mobile platform-specific considerations

  • βœ… Callback processing and verification

  • βœ… Compliance and legal requirements

  • βœ… Testing strategies and scenarios

  • βœ… Monitoring and operational procedures

  • βœ… Code review guidelines

12.2 Recommendations Summary

APPROVED FOR PRODUCTION: ⚠️ CONDITIONAL

Conditions:

  1. All CRITICAL findings addressed

  2. Signature v2 implementation verified

  3. Callback signature verification tested

  4. Secret management audit completed

  5. Penetration testing executed and findings remediated

Estimated Time to Production Readiness: 2-3 weeks


12.3 Review Team

Role
Name
Date
Signature

Security Lead

__________

__________

__________

Lead Developer

__________

__________

__________

DevOps Lead

__________

__________

__________

Compliance Officer

__________

__________

__________


13. Appendices

Appendix A: Glossary

AML/CFT: Anti-Money Laundering / Counter-Financing of Terrorism 3D Secure: Authentication protocol for online card transactions KYC: Know Your Customer identity verification PCI-DSS: Payment Card Industry Data Security Standard POS: Point of Sale SumSub: Third-party KYC verification provider HMAC: Hash-based Message Authentication Code

Appendix C: Contact Information

Mercuryo Support:

  • Integration Manager: [Contact via dashboard]

  • Technical Support: [From help center]

  • Emergency Escalation: [Document internally]

Internal Contacts:

  • Security Team: security@tokeo.com

  • DevOps On-Call: [PagerDuty/Opsgenie]

  • Compliance: compliance@tokeo.com


Document End

This review should be updated quarterly or whenever significant changes are made to the integration.

Last updated

Was this helpful?