Skip to content

PPP Mobile App — Security ​

Security Posture Summary ​

The PPP mobile app handles sensitive UK and Australian medical data including:

  • CPD activity records
  • Surgical logbook entries (procedures, outcomes)
  • Wellness questionnaire responses
  • Apple HealthKit clinical records
  • Location data (hospital proximity)
  • Cognito authentication tokens

This document maps the current security posture against the OWASP Mobile Top 10 (2024) and medical data compliance requirements.


OWASP Mobile Top 10 Mapping ​

#OWASP CategoryCurrent StatusRiskGitHub Issue
M1Improper Credential UsageHIGH — idToken extracted from WebView localStorage via injected JS; no refresh token mechanismCriticalSee #565, raise dedicated issue
M2Inadequate Supply Chain SecurityMEDIUM — pnpm audit in CI via security-scan.yml; 80+ direct dependenciesMediumCompliance issue
M3Insecure Authentication/AuthorisationMEDIUM — relies on Cognito idToken; no token rotationHighDedicated issue
M4Insufficient Input/Output ValidationLOW — tRPC + Zod on backend validates inputsLow—
M5Insecure CommunicationHIGH — no certificate pinning; MITM possible for medical dataCriticalDedicated issue
M6Inadequate Privacy ControlsMEDIUM — no data residency enforcement (UK vs AU)HighDedicated issue
M7Insufficient Binary ProtectionsRESOLVED — jailbreak/root detection via expo-device; warning shown on compromised devicesLow#630
M8Security MisconfigurationRESOLVED — CSP meta tag injected into WebView; originWhitelist restricts navigationLow#630
M9Insecure Data StorageRESOLVED — MMKV encrypted with AES-256; key stored in device Keychain/Keystore via expo-secure-storeLow#634
M10Insufficient CryptographyLOW — TLS enforced by AWS Lambda URLLow—

Critical Security Issues ​

1. WebView Token Extraction (M1 — Critical) ​

File: app/index.tsx:97–166

The current authentication mechanism injects JavaScript into the WebView to:

  1. Read all of localStorage and post it to the native layer
  2. Override localStorage.setItem to intercept Cognito idToken writes
  3. Listen for URL changes via MutationObserver

Risks:

  • Any XSS vulnerability in the loaded web page could intercept the token extraction
  • The injected script has full access to all localStorage including non-token data
  • injectedJavaScript runs in the WebView's page context — a compromised page can read the token before it is posted
  • Token is transmitted via postMessage which can be intercepted if multiple WebViews exist

Tracked as: GitHub Issue #565 (existing), plus a new dedicated issue for better-auth cookie session migration.

Recommendation: Migrate to better-auth which supports native mobile cookie sessions, eliminating the need for localStorage scraping.

2. No Certificate Pinning (M5 — Critical) ​

The trpcClient.ts uses a plain httpBatchLink to the TRPC_URL. There is no certificate pinning.

Risk: A MITM attacker on a compromised network (e.g. hospital WiFi) could intercept or modify medical data. This is a significant risk for clinical staff working in hospital environments.

Recommendation: Implement certificate pinning using react-native-ssl-pinning or OkHttp pinning for Android.

3. No Refresh Token Mechanism (M1 — High) ​

sessionStore stores only accessToken. There is no refresh token flow. When the Cognito idToken expires:

  • The user must re-authenticate through the WebView
  • No automatic token refresh occurs in the background
  • Background tasks will fail silently when the token expires

Risk: Clinicians may lose in-progress data if the token expires mid-session.


MMKV Storage Security ​

Files: lib/utils/storage.ts, lib/utils/encryption-key.ts

typescript
// encryption-key.ts — retrieves or generates a 32-byte AES-256 key
const encryptionKey = getOrCreateEncryptionKey();

// storage.ts — MMKV encrypted at rest
export const storage = new MMKV({
  id: 'ppp-encrypted-storage',
  encryptionKey,
});

MMKV is configured with AES-256 encryption. The encryption key is managed by encryption-key.ts:

  1. Key generation: A cryptographically random 32-byte hex string generated via crypto.getRandomValues() (polyfilled by react-native-get-random-values)
  2. Key storage: Persisted in expo-secure-store under the alias ppp_mmkv_encryption_key
    • iOS: Stored in the Keychain with kSecAttrAccessibleAfterFirstUnlock
    • Android: Stored in EncryptedSharedPreferences backed by Android Keystore
  3. Key lifecycle: Generated once on first app launch; persisted across app updates
  4. Key rotation: Supported via rotateEncryptionKey(storage) — calls storage.recrypt(newKey) atomically then persists the new key

Data stored in MMKV:

  • session-storage — Zustand store containing accessToken (Cognito idToken) and user object
  • hospital-notification-history — Hospital IDs with notification dates

iOS encryption behaviour: With an encryptionKey provided, MMKV encrypts data using AES-256 on both iOS and Android. Without a key, neither platform encrypts the MMKV data file — the iOS Keychain is only used for the key itself, not the data.

Android security: The encryption key is protected by Android Keystore hardware backing, making it inaccessible even on rooted devices (hardware-backed keys cannot be extracted). The MMKV data file is AES-256 encrypted and useless without the key.


Data Residency Routing ​

Status: Implemented (#653)

File: lib/services/data-residency.ts

The tRPC client dynamically resolves the API endpoint URL based on the authenticated user's region (user.countryCode). This ensures UK users' data is routed to the UK endpoint and AU users' data stays within Australian infrastructure.

Resolution order:

  1. If user.countryCode is "UK" → https://api-uk.professionalperformanceportfolio.com/trpc
  2. If user.countryCode is "AU" → https://api-au.professionalperformanceportfolio.com/trpc
  3. Fallback → build-time TRPC_URL from EAS environment variables

Audit: A DATA_RESIDENCY_RESOLVED event is logged on every login with the resolved region and endpoint (no PII).

Note: Regional endpoint URLs are defaults that must be configured via EAS build-time environment variables (TRPC_URL_UK, TRPC_URL_AU) for each deployment environment. Backend infrastructure for multi-region routing is tracked separately.


GDPR / AU Privacy Act Compliance ​

GDPR Article 32 (UK users) ​

Required technical measures to ensure the security of processing personal data.

Article 32(1)(a) — Pseudonymisation and encryption of personal data ​

MeasureStatusImplementationPR/Issue
Encryption in transit (HTTPS/TLS 1.2+)DoneAWS Lambda Function URL enforces HTTPS—
Encryption at rest on device (AES-256)DoneMMKV encrypted with device-bound key via expo-secure-store#634
Encryption key stored in hardware-backed storageDoneiOS Keychain / Android Keystore#634
Key rotation supportDonerotateEncryptionKey() in lib/utils/encryption-key.ts#634

Article 32(1)(b) — Ongoing confidentiality, integrity, availability, and resilience ​

MeasureStatusImplementationPR/Issue
Access logging for sensitive operationsDoneAudit log service records TOKEN_ACCESS, HEALTHKIT_READ, etc. in encrypted MMKV#653
Data residency routing (UK endpoint for UK users)Donelib/services/data-residency.ts resolves regional tRPC URL from user.countryCode#653
Jailbreak / root detectionDoneexpo-device warning on compromised devices#630
Content Security Policy (WebView)DoneCSP meta tag injection; origin whitelist#630
Certificate pinningPendingConfigured in build plugin but not enforced in docs—

Article 32(1)(c) — Ability to restore availability and access to personal data in a timely manner ​

MeasureStatusImplementationPR/Issue
Proactive token refreshDoneRefresh scheduled 5 min before expiry; exponential backoff—
Automatic 401 retryDonetRPC proxy client retries after refresh—
Session persistence across app restartsDoneZustand + MMKV encrypted persist—

Article 32(1)(d) — Regular testing, assessing, and evaluating effectiveness ​

MeasureStatusImplementationPR/Issue
Weekly security scan (CI)Donesecurity-scan.yml — npm audit, Semgrep, TruffleHog, Gitleaks—
OWASP Mobile Top 10 mappingDoneThis document (see above)—
Audit log available for export/reviewDonegetAuditLog() in lib/services/audit-log.ts#653

Article 17 — Right to erasure ​

MeasureStatusImplementationPR/Issue
sessionStore.clear() on account deletionDonelib/services/account-erasure.ts#653
Full MMKV wipe (storage.clearAll())DoneClears all encrypted local data#653
Encryption key deletion from SecureStoreDoneMakes residual on-disk data unrecoverable#653
Health consent state resetDonehealthConsentStore.resetConsent()#653
Token refresh timers cancelledDoneclearTokenRefreshState()#653
WebView accountDeleted message handlerDoneapp/index.tsx listens for deletion event from web app#653

Audit Event Types ​

The following events are recorded by lib/services/audit-log.ts:

Event TypeTriggerMetadata
TOKEN_ACCESSReserved for explicit sensitive data access—
TOKEN_REFRESHSuccessful token refresh—
TOKEN_REFRESH_FAILEDAll refresh retries exhausted{ attempts }
HEALTHKIT_PERMISSION_GRANTEDHealthKit init succeeds{ dataTypes }
HEALTHKIT_PERMISSION_DENIEDHealthKit init fails{ error }
SESSION_CLEARLogout or token failure{ reason }
ACCOUNT_DELETIONUser requests account deletion{ initiatedBy, scope }
DATA_RESIDENCY_RESOLVEDLogin with region resolution{ region, endpoint }

Storage: Circular buffer of max 500 entries in encrypted MMKV. No PII is logged.

DPO Sign-Off — Pre-Production Checklist ​

The following items must be verified by the Data Protection Officer before the mobile app is released to UK users:

  • [ ] All Article 32 measures above are marked "Done"
  • [ ] Certificate pinning is enforced on production builds
  • [ ] Data residency endpoint URLs are configured for UK production
  • [ ] Privacy policy is accessible from login and settings screens
  • [ ] HealthKit data collection disclosure is shown at first launch
  • [ ] Account deletion flow has been end-to-end tested (web → mobile wipe)
  • [ ] Audit log retention and export procedures are documented
  • [ ] Penetration test report reviewed (no critical/high findings open)
  • [ ] DPO has signed off on this document (date: **____**)

Australian Privacy Act 1988 — Compliance Checklist ​

The following checklist maps each relevant Australian Privacy Principle (APP) to the implementing issue or PR from the parent initiative (#654). This gives auditors a single reference point for the current compliance posture.

APP 1 — Open and transparent management of personal information ​

RequirementStatusImplementing Issue/PR
Privacy policy authored covering all personal data collected by the mobile appPending#759 (Part 1)
Privacy policy link accessible from app Settings screenPending#761 (Part 2)
Privacy policy link accessible from login / onboarding screenPending#761 (Part 2)
Policy describes types of personal information collected (CPD, surgical logbook, wellness, HealthKit, location)Pending#759 (Part 1)
Policy describes purposes of collectionPending#759 (Part 1)
Policy describes how individuals can access and correct their informationPending#759 (Part 1)
Policy describes how complaints can be madePending#759 (Part 1)
Policy describes overseas disclosure (if any)Pending#759 (Part 1)

APP 5 — Notification of the collection of personal information ​

RequirementStatusImplementing Issue/PR
HealthKit data collection disclosure screen shown at first launchPending#762 (Part 3)
Disclosure specifies which HealthKit data types are collectedPending#762 (Part 3)
Disclosure explains purpose of HealthKit data collectionPending#762 (Part 3)
User can decline HealthKit access without loss of core functionalityPending#762 (Part 3)
Privacy collection statement shown before location permission requestPending#763 (Part 4)
Location collection statement explains hospital proximity purposePending#763 (Part 4)
User can decline location access without loss of core functionalityPending#763 (Part 4)

APP 8 — Cross-border disclosure of personal information ​

RequirementStatusImplementing Issue/PR
Australian users routed to ap-southeast-2 (Sydney) tRPC endpointPending#764 (Part 5)
User region determined at authentication / profile levelPending#764 (Part 5)
No AU personal data transits through non-AU regionsPending#764 (Part 5)
Database for AU users hosted in ap-southeast-2Pending#764 (Part 5)

APP 11 — Security of personal information ​

RequirementStatusNotes
Encryption in transit — all API calls over HTTPS/TLS 1.2+DoneAWS Lambda Function URL enforces HTTPS
Encryption at rest (server) — PostgreSQL storage encryptedDoneAWS RDS encryption at rest enabled
Encryption at rest (device) — MMKV encrypted on mobileDoneMMKV AES-256 encrypted with device-bound key via expo-secure-store (#634)
Authentication — AWS Cognito OAuth 2.0 with MFA supportDoneCognito User Pool with hosted UI
Secrets management — no credentials in source codeDoneAWS Secrets Manager at mb/embrace/<env>/ppp/pg
No PII in application logs — server-side logging sanitisedDonetRPC error handler strips user data; Lambda logs contain only request metadata
Access control — role-based permissions on backendDonetRPC middleware checks user role and ownership
Certificate pinning — prevent MITM on mobilePendingNo SSL pinning configured; see Critical Security Issues section above
Jailbreak / root detection — detect compromised devicesDoneexpo-device isRootedExperimentalAsync + warning UI (#630)
Session security — token expiry and refreshPartialCognito idToken has expiry but no automatic refresh flow on mobile
Data destruction — secure deletion when no longer neededDoneperformAccountErasure() wipes MMKV + deletes encryption key (#653)

Parent initiative: #654 — mobile: implement Australian Privacy Act compliance Dependencies: Parts 1-5 (#759, #761, #762, #763, #764) must be merged before this checklist can be fully marked as complete.


Token Lifecycle ​

EventCurrent Behaviour
LoginCognito idToken extracted from WebView localStorage and stored in MMKV
App resume (token valid)MMKV provides token; tRPC works
App resume (token expired)tRPC calls fail with 401; no automatic recovery
LogoutWebView localStorage/sessionStorage/cookies cleared; MMKV token nulled
Background task with expired tokentRPC calls throw; task returns Failed silently

Jailbreak / Root Detection ​

Status: Implemented (#630)

Jailbreak (iOS) and root (Android) detection is performed at app launch using expo-device.isRootedExperimentalAsync(). The detection runs once per app session and the result is cached.

Detection checks:

  1. expo-device experimental root detection — checks for su binary, Superuser.apk, Magisk (Android), Cydia/Sileo artefacts (iOS)
  2. Device type check — flags DeviceType.UNKNOWN as a possible emulator

On detection:

  • A non-dismissable-style alert warns the user that their device appears compromised
  • The warning explains the risk to medical data (CPD, surgical logbook, wellness)
  • Restricted features (planned/future work — not currently enforced at runtime): HealthKit sync, background location, offline caching

Files:

  • lib/services/device-integrity.ts — detection logic and warning messages
  • lib/hooks/useDeviceIntegrity.ts — React hook with session caching
  • app/_layout.tsx — alert display on compromised device detection

Limitations: Sophisticated root-hiding tools (Magisk Hide, Shadow) can bypass these checks. The detection provides a reasonable baseline but is not tamper-proof.


Content Security Policy ​

Status: Implemented (#630)

A Content Security Policy is injected into every WebView page load via a <meta> tag using injectedJavaScriptBeforeContentLoaded. This ensures the CSP is active before any page scripts execute.

Key directives:

DirectiveValueRationale
default-src'self' https://<web-host>Restrict default resource loading to our domain
script-src'self' 'unsafe-inline' https://<web-host>Allow injected JS (required by RN WebView); unsafe-eval is blocked
style-src'self' 'unsafe-inline' https://<web-host> https://fonts.googleapis.comAllow dynamic styles (MUI) and Google Fonts
img-src'self' https://<web-host> https://*.blob.core.windows.net data: blob:Allow Azure Blob Storage images and inline data URIs
connect-src'self' https://<web-host> https://<api-host> https://*.blob.core.windows.netAllow API and Azure storage connections
frame-src'none'No iframes allowed
object-src'none'No plugins (Flash, Java)

Origin whitelist: The WebView originWhitelist prop restricts navigation to HTTPS origins matching our known domains (app, API, SSO providers). This prevents the WebView from navigating to arbitrary URLs.

Files:

  • lib/utils/webview-security.ts — CSP and whitelist configuration
  • lib/components/WebView.tsx — applies whitelist and CSP to shared WebView
  • app/index.tsx — applies whitelist and CSP to login WebView

Internal documentation — org members only