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 Category | Current Status | Risk | GitHub Issue |
|---|---|---|---|---|
| M1 | Improper Credential Usage | HIGH — idToken extracted from WebView localStorage via injected JS; no refresh token mechanism | Critical | See #565, raise dedicated issue |
| M2 | Inadequate Supply Chain Security | MEDIUM — pnpm audit in CI via security-scan.yml; 80+ direct dependencies | Medium | Compliance issue |
| M3 | Insecure Authentication/Authorisation | MEDIUM — relies on Cognito idToken; no token rotation | High | Dedicated issue |
| M4 | Insufficient Input/Output Validation | LOW — tRPC + Zod on backend validates inputs | Low | — |
| M5 | Insecure Communication | HIGH — no certificate pinning; MITM possible for medical data | Critical | Dedicated issue |
| M6 | Inadequate Privacy Controls | MEDIUM — no data residency enforcement (UK vs AU) | High | Dedicated issue |
| M7 | Insufficient Binary Protections | RESOLVED — jailbreak/root detection via expo-device; warning shown on compromised devices | Low | #630 |
| M8 | Security Misconfiguration | RESOLVED — CSP meta tag injected into WebView; originWhitelist restricts navigation | Low | #630 |
| M9 | Insecure Data Storage | RESOLVED — MMKV encrypted with AES-256; key stored in device Keychain/Keystore via expo-secure-store | Low | #634 |
| M10 | Insufficient Cryptography | LOW — TLS enforced by AWS Lambda URL | Low | — |
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:
- Read all of
localStorageand post it to the native layer - Override
localStorage.setItemto intercept Cognito idToken writes - 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
injectedJavaScriptruns in the WebView's page context — a compromised page can read the token before it is posted- Token is transmitted via
postMessagewhich 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
// 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:
- Key generation: A cryptographically random 32-byte hex string generated via
crypto.getRandomValues()(polyfilled byreact-native-get-random-values) - Key storage: Persisted in
expo-secure-storeunder the aliasppp_mmkv_encryption_key- iOS: Stored in the Keychain with
kSecAttrAccessibleAfterFirstUnlock - Android: Stored in EncryptedSharedPreferences backed by Android Keystore
- iOS: Stored in the Keychain with
- Key lifecycle: Generated once on first app launch; persisted across app updates
- Key rotation: Supported via
rotateEncryptionKey(storage)— callsstorage.recrypt(newKey)atomically then persists the new key
Data stored in MMKV:
session-storage— Zustand store containingaccessToken(Cognito idToken) anduserobjecthospital-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:
- If
user.countryCodeis"UK"→https://api-uk.professionalperformanceportfolio.com/trpc - If
user.countryCodeis"AU"→https://api-au.professionalperformanceportfolio.com/trpc - Fallback → build-time
TRPC_URLfrom 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
| Measure | Status | Implementation | PR/Issue |
|---|---|---|---|
| Encryption in transit (HTTPS/TLS 1.2+) | Done | AWS Lambda Function URL enforces HTTPS | — |
| Encryption at rest on device (AES-256) | Done | MMKV encrypted with device-bound key via expo-secure-store | #634 |
| Encryption key stored in hardware-backed storage | Done | iOS Keychain / Android Keystore | #634 |
| Key rotation support | Done | rotateEncryptionKey() in lib/utils/encryption-key.ts | #634 |
Article 32(1)(b) — Ongoing confidentiality, integrity, availability, and resilience
| Measure | Status | Implementation | PR/Issue |
|---|---|---|---|
| Access logging for sensitive operations | Done | Audit log service records TOKEN_ACCESS, HEALTHKIT_READ, etc. in encrypted MMKV | #653 |
| Data residency routing (UK endpoint for UK users) | Done | lib/services/data-residency.ts resolves regional tRPC URL from user.countryCode | #653 |
| Jailbreak / root detection | Done | expo-device warning on compromised devices | #630 |
| Content Security Policy (WebView) | Done | CSP meta tag injection; origin whitelist | #630 |
| Certificate pinning | Pending | Configured 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
| Measure | Status | Implementation | PR/Issue |
|---|---|---|---|
| Proactive token refresh | Done | Refresh scheduled 5 min before expiry; exponential backoff | — |
| Automatic 401 retry | Done | tRPC proxy client retries after refresh | — |
| Session persistence across app restarts | Done | Zustand + MMKV encrypted persist | — |
Article 32(1)(d) — Regular testing, assessing, and evaluating effectiveness
| Measure | Status | Implementation | PR/Issue |
|---|---|---|---|
| Weekly security scan (CI) | Done | security-scan.yml — npm audit, Semgrep, TruffleHog, Gitleaks | — |
| OWASP Mobile Top 10 mapping | Done | This document (see above) | — |
| Audit log available for export/review | Done | getAuditLog() in lib/services/audit-log.ts | #653 |
Article 17 — Right to erasure
| Measure | Status | Implementation | PR/Issue |
|---|---|---|---|
sessionStore.clear() on account deletion | Done | lib/services/account-erasure.ts | #653 |
Full MMKV wipe (storage.clearAll()) | Done | Clears all encrypted local data | #653 |
| Encryption key deletion from SecureStore | Done | Makes residual on-disk data unrecoverable | #653 |
| Health consent state reset | Done | healthConsentStore.resetConsent() | #653 |
| Token refresh timers cancelled | Done | clearTokenRefreshState() | #653 |
WebView accountDeleted message handler | Done | app/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 Type | Trigger | Metadata |
|---|---|---|
TOKEN_ACCESS | Reserved for explicit sensitive data access | — |
TOKEN_REFRESH | Successful token refresh | — |
TOKEN_REFRESH_FAILED | All refresh retries exhausted | { attempts } |
HEALTHKIT_PERMISSION_GRANTED | HealthKit init succeeds | { dataTypes } |
HEALTHKIT_PERMISSION_DENIED | HealthKit init fails | { error } |
SESSION_CLEAR | Logout or token failure | { reason } |
ACCOUNT_DELETION | User requests account deletion | { initiatedBy, scope } |
DATA_RESIDENCY_RESOLVED | Login 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
| Requirement | Status | Implementing Issue/PR |
|---|---|---|
| Privacy policy authored covering all personal data collected by the mobile app | Pending | #759 (Part 1) |
| Privacy policy link accessible from app Settings screen | Pending | #761 (Part 2) |
| Privacy policy link accessible from login / onboarding screen | Pending | #761 (Part 2) |
| Policy describes types of personal information collected (CPD, surgical logbook, wellness, HealthKit, location) | Pending | #759 (Part 1) |
| Policy describes purposes of collection | Pending | #759 (Part 1) |
| Policy describes how individuals can access and correct their information | Pending | #759 (Part 1) |
| Policy describes how complaints can be made | Pending | #759 (Part 1) |
| Policy describes overseas disclosure (if any) | Pending | #759 (Part 1) |
APP 5 — Notification of the collection of personal information
| Requirement | Status | Implementing Issue/PR |
|---|---|---|
| HealthKit data collection disclosure screen shown at first launch | Pending | #762 (Part 3) |
| Disclosure specifies which HealthKit data types are collected | Pending | #762 (Part 3) |
| Disclosure explains purpose of HealthKit data collection | Pending | #762 (Part 3) |
| User can decline HealthKit access without loss of core functionality | Pending | #762 (Part 3) |
| Privacy collection statement shown before location permission request | Pending | #763 (Part 4) |
| Location collection statement explains hospital proximity purpose | Pending | #763 (Part 4) |
| User can decline location access without loss of core functionality | Pending | #763 (Part 4) |
APP 8 — Cross-border disclosure of personal information
| Requirement | Status | Implementing Issue/PR |
|---|---|---|
| Australian users routed to ap-southeast-2 (Sydney) tRPC endpoint | Pending | #764 (Part 5) |
| User region determined at authentication / profile level | Pending | #764 (Part 5) |
| No AU personal data transits through non-AU regions | Pending | #764 (Part 5) |
| Database for AU users hosted in ap-southeast-2 | Pending | #764 (Part 5) |
APP 11 — Security of personal information
| Requirement | Status | Notes |
|---|---|---|
| Encryption in transit — all API calls over HTTPS/TLS 1.2+ | Done | AWS Lambda Function URL enforces HTTPS |
| Encryption at rest (server) — PostgreSQL storage encrypted | Done | AWS RDS encryption at rest enabled |
| Encryption at rest (device) — MMKV encrypted on mobile | Done | MMKV AES-256 encrypted with device-bound key via expo-secure-store (#634) |
| Authentication — AWS Cognito OAuth 2.0 with MFA support | Done | Cognito User Pool with hosted UI |
| Secrets management — no credentials in source code | Done | AWS Secrets Manager at mb/embrace/<env>/ppp/pg |
| No PII in application logs — server-side logging sanitised | Done | tRPC error handler strips user data; Lambda logs contain only request metadata |
| Access control — role-based permissions on backend | Done | tRPC middleware checks user role and ownership |
| Certificate pinning — prevent MITM on mobile | Pending | No SSL pinning configured; see Critical Security Issues section above |
| Jailbreak / root detection — detect compromised devices | Done | expo-device isRootedExperimentalAsync + warning UI (#630) |
| Session security — token expiry and refresh | Partial | Cognito idToken has expiry but no automatic refresh flow on mobile |
| Data destruction — secure deletion when no longer needed | Done | performAccountErasure() 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
| Event | Current Behaviour |
|---|---|
| Login | Cognito 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 |
| Logout | WebView localStorage/sessionStorage/cookies cleared; MMKV token nulled |
| Background task with expired token | tRPC 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:
expo-deviceexperimental root detection — checks for su binary, Superuser.apk, Magisk (Android), Cydia/Sileo artefacts (iOS)- Device type check — flags
DeviceType.UNKNOWNas 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 messageslib/hooks/useDeviceIntegrity.ts— React hook with session cachingapp/_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:
| Directive | Value | Rationale |
|---|---|---|
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.com | Allow 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.net | Allow 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 configurationlib/components/WebView.tsx— applies whitelist and CSP to shared WebViewapp/index.tsx— applies whitelist and CSP to login WebView