From 14bab6e1c429b53df8918d50f190a8c9aa618651 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 12:29:12 +0530 Subject: [PATCH 1/2] Integrate LocalProof routes with current production Worker and admin archive changes --- worker/src/index.js | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/worker/src/index.js b/worker/src/index.js index 78d9a4d0..3cb9eaad 100644 --- a/worker/src/index.js +++ b/worker/src/index.js @@ -10,14 +10,15 @@ import { redactPublicConfig } from "./public-config.js"; import { buildMerchantCollectionJournal, isBalancedJournal } from "./ledger.js"; import { PROVIDER_ADAPTERS } from "./provider-adapters.js"; import { parseBankStatementCsv } from "./statement-csv.js"; +import { handleLocalProofRequest } from "./localproof.js"; import { getPhaseCapabilitySnapshot } from "./phase-gates.js"; const json = (data, status = 200, origin = "*") => new Response(JSON.stringify(data), { status, headers: { "content-type": "application/json; charset=utf-8", "access-control-allow-origin": origin, - "access-control-allow-methods": "GET,POST,OPTIONS", - "access-control-allow-headers": "content-type,authorization,x-api-key,idempotency-key", + "access-control-allow-methods": "GET,POST,DELETE,OPTIONS", + "access-control-allow-headers": "content-type,authorization,x-api-key,idempotency-key,x-localproof-device,x-localproof-timestamp,x-localproof-nonce,x-localproof-signature", "access-control-max-age": "600", "vary": "Origin", "cache-control": "no-store" @@ -560,8 +561,8 @@ export default { status: 204, headers: { "access-control-allow-origin": origin, - "access-control-allow-methods": "GET,POST,OPTIONS", - "access-control-allow-headers": "content-type,authorization,x-api-key,idempotency-key", + "access-control-allow-methods": "GET,POST,DELETE,OPTIONS", + "access-control-allow-headers": "content-type,authorization,x-api-key,idempotency-key,x-localproof-device,x-localproof-timestamp,x-localproof-nonce,x-localproof-signature", "access-control-max-age": "600", "vary": "Origin" } @@ -593,6 +594,10 @@ export default { }); } } + if (url.pathname.startsWith("/api/v1/localproof/")) { + const localProofResponse = await handleLocalProofRequest(request, env, origin, authenticate, json); + if (localProofResponse) return localProofResponse; + } if (request.method === "POST" && url.pathname === "/api/admin/key-login") { if (!sameOriginAdminRequest(request, url)) return json({ error: "A same-origin request is required." }, 403, origin); const configured = String(env.ADMIN_ACCESS_KEY || ""); From 9e434ac4a7faf51eeba23d66cfe452570253635e Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 12:31:06 +0530 Subject: [PATCH 2/2] feat: integrate LocalProof with current PAYNEX production main --- .github/workflows/deploy-pages.yml | 2 +- .github/workflows/deploy-production.yml | 17 ++- .github/workflows/deploy-worker.yml | 16 +++ .github/workflows/worker-tests.yml | 39 +++++- README.md | 2 +- android/README.md | 31 +++++ android/app/build.gradle.kts | 20 +++ android/app/src/main/AndroidManifest.xml | 15 +++ .../main/java/com/paynex/localproof/Api.kt | 57 +++++++++ .../com/paynex/localproof/DeviceCrypto.kt | 60 +++++++++ .../LocalProofNotificationListener.kt | 43 +++++++ .../com/paynex/localproof/MainActivity.kt | 59 +++++++++ .../java/com/paynex/localproof/SecretStore.kt | 42 +++++++ android/build.gradle.kts | 4 + android/gradle.properties | 3 + android/settings.gradle.kts | 4 + dashboard/index.html | 24 +++- docs/LOCALPROOF-STATUS.md | 70 +++++------ .../0028_localproof_device_observation.sql | 52 ++++++++ .../0029_localproof_observation_direction.sql | 5 + worker/schema.sql | 58 +++++++++ worker/src/localproof.js | 114 ++++++++++++++++++ worker/test/localproof.test.js | 110 +++++++++++++++++ 23 files changed, 804 insertions(+), 43 deletions(-) create mode 100644 android/README.md create mode 100644 android/app/build.gradle.kts create mode 100644 android/app/src/main/AndroidManifest.xml create mode 100644 android/app/src/main/java/com/paynex/localproof/Api.kt create mode 100644 android/app/src/main/java/com/paynex/localproof/DeviceCrypto.kt create mode 100644 android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt create mode 100644 android/app/src/main/java/com/paynex/localproof/MainActivity.kt create mode 100644 android/app/src/main/java/com/paynex/localproof/SecretStore.kt create mode 100644 android/build.gradle.kts create mode 100644 android/gradle.properties create mode 100644 android/settings.gradle.kts create mode 100644 worker/migrations/0028_localproof_device_observation.sql create mode 100644 worker/migrations/0029_localproof_observation_direction.sql create mode 100644 worker/src/localproof.js create mode 100644 worker/test/localproof.test.js diff --git a/.github/workflows/deploy-pages.yml b/.github/workflows/deploy-pages.yml index 7bea5d37..f80e1912 100644 --- a/.github/workflows/deploy-pages.yml +++ b/.github/workflows/deploy-pages.yml @@ -42,7 +42,7 @@ jobs: grep -q "paynex-api.sbn50088.workers.dev/dashboard" docs/dashboard/index.html grep -q "Test API health" docs/docs/index.html grep -q "menuToggle" docs/index.html - grep -q "no Android companion APK" docs/LOCALPROOF-STATUS.md + grep -q "Android companion source" docs/LOCALPROOF-STATUS.md node scripts/validate-pages.mjs - uses: actions/configure-pages@v5 with: diff --git a/.github/workflows/deploy-production.yml b/.github/workflows/deploy-production.yml index b09a6d94..90247066 100644 --- a/.github/workflows/deploy-production.yml +++ b/.github/workflows/deploy-production.yml @@ -46,6 +46,7 @@ jobs: run: | node --check src/index.js node --check src/auth.js + node --check src/localproof.js - name: Run complete Worker regression suite run: npm test - name: Verify required production secrets exist (names only) @@ -184,11 +185,25 @@ jobs: run: npx wrangler d1 execute paynex-db --remote --file=./migrations/0027_backfill_merchant_mode_onboarding.sql env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + - name: Apply LocalProof device observation schema (idempotent) + run: npx wrangler d1 execute paynex-db --remote --file=./migrations/0028_localproof_device_observation.sql + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + - name: Apply LocalProof observation direction migration (skip if already present) + run: | + if npx wrangler d1 execute paynex-db --remote --command "SELECT direction FROM localproof_observations LIMIT 0" --json >/dev/null 2>&1; then + echo "LocalProof direction column already exists." + else + npx wrangler d1 execute paynex-db --remote --file=./migrations/0029_localproof_observation_direction.sql + fi + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - name: Verify production schema before Worker rollout run: | set -euo pipefail - npx wrangler d1 execute paynex-db --remote --command "SELECT name FROM sqlite_master WHERE type='table' AND name IN ('gateway_applications','account','orders','payment_attempts','payment_routing_rules','reconciliation_batches','saas_invoices','ledger_accounts','ledger_journals','ledger_entries','merchant_review_records') ORDER BY name" --json + npx wrangler d1 execute paynex-db --remote --command "SELECT name FROM sqlite_master WHERE type='table' AND name IN ('gateway_applications','account','orders','payment_attempts','payment_routing_rules','reconciliation_batches','saas_invoices','ledger_accounts','ledger_journals','ledger_entries','merchant_review_records','localproof_devices','localproof_nonces','localproof_observations','localproof_audit_events') ORDER BY name" --json npx wrangler d1 execute paynex-db --remote --command "SELECT name FROM sqlite_master WHERE type='table' AND name='merchant_payment_confirmations'" --json + npx wrangler d1 execute paynex-db --remote --command "SELECT direction FROM localproof_observations LIMIT 0" --json npx wrangler d1 execute paynex-db --remote --command "SELECT name FROM sqlite_master WHERE type='table' AND name IN ('merchant_mode_onboarding','merchant_kyc_documents','merchant_limited_access','merchant_limited_workspace','merchant_sandbox_checkouts') ORDER BY name" --json npx wrangler d1 execute paynex-db --remote --command "SELECT name FROM sqlite_master WHERE type='index' AND name IN ('idx_merchant_payment_confirmations_order','idx_merchant_payment_confirmations_reference') ORDER BY name" --json npx wrangler d1 execute paynex-db --remote --command "SELECT name FROM pragma_table_info('merchants') WHERE name IN ('upi_account_type','upi_ownership_verified') ORDER BY name" --json diff --git a/.github/workflows/deploy-worker.yml b/.github/workflows/deploy-worker.yml index b244703c..930ee0ec 100644 --- a/.github/workflows/deploy-worker.yml +++ b/.github/workflows/deploy-worker.yml @@ -26,6 +26,7 @@ jobs: - name: Check Worker and onboarding script syntax run: | node --check worker/src/index.js + node --check worker/src/localproof.js node --check scripts/provision-merchant.mjs node --check scripts/approve-merchant.mjs - name: Install Worker dependencies @@ -94,6 +95,21 @@ jobs: run: npx wrangler d1 execute paynex-v2-staging --remote --file=./migrations/0027_backfill_merchant_mode_onboarding.sql --env staging env: CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + - name: Apply LocalProof device observation schema (idempotent) + working-directory: worker + run: npx wrangler d1 execute paynex-v2-staging --remote --file=./migrations/0028_localproof_device_observation.sql --env staging + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} + - name: Apply LocalProof observation direction migration (skip if already present) + working-directory: worker + run: | + if npx wrangler d1 execute paynex-v2-staging --remote --command "SELECT direction FROM localproof_observations LIMIT 0" --env staging --json >/dev/null 2>&1; then + echo "LocalProof direction column already exists." + else + npx wrangler d1 execute paynex-v2-staging --remote --file=./migrations/0029_localproof_observation_direction.sql --env staging + fi + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - name: Verify merchant attestation staging schema working-directory: worker run: | diff --git a/.github/workflows/worker-tests.yml b/.github/workflows/worker-tests.yml index 1332322a..0d0fd9ac 100644 --- a/.github/workflows/worker-tests.yml +++ b/.github/workflows/worker-tests.yml @@ -2,9 +2,9 @@ name: PAYNEX worker tests on: pull_request: - branches: [main, feat/hybrid-settlement-commission-ready-20261129, feat/phase3-unified-checkout-byok-20261129, integration/paynex-v2-auth-safe-20261130, feat/oxigendev-limited-merchant-access] + branches: [main, feat/hybrid-settlement-commission-ready-20261129, feat/phase3-unified-checkout-byok-20261129, integration/paynex-v2-auth-safe-20261130, feat/oxigendev-limited-merchant-access, feat/localproof-secure-device-observation] push: - branches: [main, feat/provider-contract-hardening, feat/better-auth-google-email, feat/phase3-unified-checkout-byok-20261129, integration/paynex-v2-auth-safe-20261130, feat/oxigendev-limited-merchant-access] + branches: [main, feat/provider-contract-hardening, feat/better-auth-google-email, feat/phase3-unified-checkout-byok-20261129, integration/paynex-v2-auth-safe-20261130, feat/oxigendev-limited-merchant-access, feat/localproof-secure-device-observation] jobs: worker-tests: @@ -23,5 +23,40 @@ jobs: run: | node --check src/index.js node --check src/auth.js + node --check src/localproof.js + - name: Validate LocalProof D1 migrations locally + run: | + npx wrangler d1 execute paynex-db --local --file=./migrations/0028_localproof_device_observation.sql + npx wrangler d1 execute paynex-db --local --file=./migrations/0029_localproof_observation_direction.sql + npx wrangler d1 execute paynex-db --local --command "SELECT direction FROM localproof_observations LIMIT 0" - name: Run worker tests run: npm test + + android-debug-apk: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "17" + - name: Install Android SDK packages + run: | + SDK_ROOT="${ANDROID_HOME:-$ANDROID_SDK_ROOT}" + SDKMANAGER="$(find "$SDK_ROOT/cmdline-tools" -type f -name sdkmanager | sort | tail -n 1)" + test -x "$SDKMANAGER" + yes | "$SDKMANAGER" --licenses >/dev/null + "$SDKMANAGER" "platforms;android-35" "build-tools;35.0.0" "platform-tools" + - name: Build LocalProof debug APK + uses: gradle/gradle-build-action@v3 + with: + gradle-version: "8.9" + build-root-directory: android + arguments: --no-daemon :app:assembleDebug + - name: Upload debug APK + uses: actions/upload-artifact@v4 + with: + name: paynex-localproof-debug-apk + path: android/app/build/outputs/apk/debug/app-debug.apk + if-no-files-found: error + retention-days: 14 diff --git a/README.md b/README.md index 5574ca4e..2984bc66 100644 --- a/README.md +++ b/README.md @@ -134,4 +134,4 @@ Then configure the Razorpay webhook secret. Until the migration and secret are c ## LocalProof Android companion — current status -The LocalProof notification-listener companion is **not implemented and no APK is available yet**. The implementation scope and safety gates are tracked in [docs/LOCALPROOF-STATUS.md](docs/LOCALPROOF-STATUS.md). A future Android notification observation may assist reconciliation only; it must never mark a transaction paid or activate a subscription. Only an authorised provider's authenticated server-side confirmation can do that. +LocalProof backend and initial Android companion source are implemented on the draft feature PR. The Android app uses an Android Keystore P-256 signing key, encrypted API-key storage, explicit notification-listener consent and local-only parsing of allowlisted UPI app notifications. The Worker stores signed device observations as **unverified reconciliation hints only**. No notification can mark a transaction paid, post a verified ledger entry or trigger fulfilment. The CI debug-APK build and physical Android 16 device validation must pass before rollout. See [docs/LOCALPROOF-STATUS.md](docs/LOCALPROOF-STATUS.md) for current release gates. \ No newline at end of file diff --git a/android/README.md b/android/README.md new file mode 100644 index 00000000..3741ea5a --- /dev/null +++ b/android/README.md @@ -0,0 +1,31 @@ +# PAYNEX LocalProof Android companion (early access) + +This is an opt-in notification observation companion, not a payment app or bank integration. + +## Build +- Android Studio with JDK 17 and Android SDK 35 +- Open the `android/` folder and build the `app` debug variant. +- The CI workflow builds a debug APK and stores it as a GitHub Actions artifact. + +## Pairing +1. Sign in to the PAYNEX merchant dashboard and create/use an active merchant API key. +2. Enter the Worker URL and API key in the app. +3. Add only the exact package names of UPI apps you choose to observe. +4. Tap Enroll this device. +5. Tap Enable notification access and explicitly enable PAYNEX LocalProof in Android Settings. +6. Keep the phone unlocked/online when notifications arrive. + +The P-256 private key is generated and held by Android Keystore; it is not exported. The server receives only the public key. The app signs timestamp + nonce + exact JSON request bytes. + +## Data minimisation +Notification text is processed locally only. The app uploads the source package, parser version, event ID, observation time and optional parsed amount/UTR. Full notification bodies, account numbers, contacts and inbox history are not uploaded. Configure an explicit package allowlist. The app does not read SMS inboxes. + +## Limits +- Notification formats vary by UPI app, bank and language; parsing is best-effort and requires real-device testing. +- Notifications may be delayed, absent, duplicated or spoofed. +- A LocalProof observation never marks an order/payment paid, posts a verified ledger journal, activates a subscription, or triggers fulfilment. +- This initial companion does not yet have a durable offline retry queue or in-app observation history. +- Do not use this as a substitute for checking the receiving bank/UPI app. + +## Privacy and control +Disable notification access in Android Settings to stop observation. Revoke the device in-app to invalidate its API identity. Clear app data/uninstalling the app removes local settings; server-side device revocation should be done first where possible. diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts new file mode 100644 index 00000000..b17d4b3f --- /dev/null +++ b/android/app/build.gradle.kts @@ -0,0 +1,20 @@ +plugins { + id("com.android.application") + id("org.jetbrains.kotlin.android") +} +android { + namespace = "com.paynex.localproof" + compileSdk = 35 + defaultConfig { + applicationId = "com.paynex.localproof" + minSdk = 26 + targetSdk = 35 + versionCode = 1 + versionName = "0.1.0" + } + compileOptions { + sourceCompatibility = JavaVersion.VERSION_17 + targetCompatibility = JavaVersion.VERSION_17 + } + kotlinOptions { jvmTarget = "17" } +} diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000..205f7c86 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,15 @@ + + + + + + + + + + + diff --git a/android/app/src/main/java/com/paynex/localproof/Api.kt b/android/app/src/main/java/com/paynex/localproof/Api.kt new file mode 100644 index 00000000..2c92edd1 --- /dev/null +++ b/android/app/src/main/java/com/paynex/localproof/Api.kt @@ -0,0 +1,57 @@ +package com.paynex.localproof + +import org.json.JSONObject +import java.net.HttpURLConnection +import java.net.URL +import java.util.UUID + +object Api { + private fun request(base: String, path: String, method: String, apiKey: String, body: String): String { + require(base.startsWith("https://",true)) { "HTTPS Worker URL required" } + val url=URL(base.trimEnd('/')+path) + val connection=(url.openConnection() as HttpURLConnection).apply { + requestMethod=method; connectTimeout=12000; readTimeout=12000 + setRequestProperty("Accept","application/json") + if(apiKey.isNotBlank()) setRequestProperty("Authorization","Bearer $apiKey") + if(method!="GET") { doOutput=true; setRequestProperty("Content-Type","application/json"); outputStream.use { it.write(body.toByteArray()) } } + } + val code=connection.responseCode + val stream=if(code in 200..299) connection.inputStream else connection.errorStream + val result=stream?.bufferedReader()?.use { it.readText() } ?: "" + connection.disconnect() + if(code !in 200..299) throw IllegalStateException("PAYNEX API HTTP $code: $result") + return result + } + fun enroll(base:String,apiKey:String):String { + val body=JSONObject().put("label",android.os.Build.MANUFACTURER+" "+android.os.Build.MODEL) + .put("public_key_jwk",DeviceCrypto.publicJwk()).toString() + return request(base,"/api/v1/localproof/devices","POST",apiKey,body) + } + fun send(base:String,deviceId:String,event:JSONObject) { + require(base.startsWith("https://",true)) { "HTTPS Worker URL required" } + val raw=event.toString() + val timestamp=System.currentTimeMillis().toString() + val nonce=Base64Url.randomNonce() + val signature=DeviceCrypto.sign("$timestamp.$nonce.$raw") + val connection=(URL(base.trimEnd('/')+"/api/v1/localproof/events").openConnection() as HttpURLConnection).apply { + requestMethod="POST"; connectTimeout=12000; readTimeout=12000; doOutput=true + setRequestProperty("Content-Type","application/json") + setRequestProperty("X-LocalProof-Device",deviceId) + setRequestProperty("X-LocalProof-Timestamp",timestamp) + setRequestProperty("X-LocalProof-Nonce",nonce) + setRequestProperty("X-LocalProof-Signature",signature) + outputStream.use { it.write(raw.toByteArray()) } + } + val code=connection.responseCode + val stream=if(code in 200..299) connection.inputStream else connection.errorStream + val result=stream?.bufferedReader()?.use { it.readText() } ?: "" + connection.disconnect() + if(code !in 200..299) throw IllegalStateException("Observation rejected: HTTP $code $result") + } +} +object Base64Url { + fun randomNonce():String { + val bytes=ByteArray(24); java.security.SecureRandom().nextBytes(bytes) + return android.util.Base64.encodeToString(bytes,android.util.Base64.URL_SAFE or android.util.Base64.NO_WRAP or android.util.Base64.NO_PADDING) + } +} diff --git a/android/app/src/main/java/com/paynex/localproof/DeviceCrypto.kt b/android/app/src/main/java/com/paynex/localproof/DeviceCrypto.kt new file mode 100644 index 00000000..1a0e1dca --- /dev/null +++ b/android/app/src/main/java/com/paynex/localproof/DeviceCrypto.kt @@ -0,0 +1,60 @@ +package com.paynex.localproof + +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import org.json.JSONObject +import java.math.BigInteger +import java.security.KeyPairGenerator +import java.security.KeyStore +import java.security.Signature +import java.security.interfaces.ECPublicKey + +object DeviceCrypto { + private const val ALIAS = "paynex-localproof-device-p256" + private fun b64(bytes: ByteArray) = Base64.encodeToString(bytes, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING) + private fun coordinate(value: BigInteger): ByteArray { + val raw = value.toByteArray() + val unsigned = if (raw.size == 33 && raw[0] == 0.toByte()) raw.copyOfRange(1, raw.size) else raw + return ByteArray(32).also { unsigned.copyInto(it, 32 - unsigned.size) } + } + fun publicJwk(): JSONObject { + val ks = KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + val existing = ks.getKey(ALIAS, null) + if (existing == null) { + val generator = KeyPairGenerator.getInstance(KeyProperties.KEY_ALGORITHM_EC, "AndroidKeyStore") + generator.initialize(KeyGenParameterSpec.Builder(ALIAS, KeyProperties.PURPOSE_SIGN or KeyProperties.PURPOSE_VERIFY) + .setAlgorithmParameterSpec(java.security.spec.ECGenParameterSpec("secp256r1")) + .setDigests(KeyProperties.DIGEST_SHA256) + .setUserAuthenticationRequired(false) + .build()) + generator.generateKeyPair() + } + val publicKey = ks.getCertificate(ALIAS).publicKey as ECPublicKey + return JSONObject().put("kty","EC").put("crv","P-256") + .put("x",b64(coordinate(publicKey.w.affineX))).put("y",b64(coordinate(publicKey.w.affineY))).put("ext",true) + } + private fun derToRaw(der: ByteArray): ByteArray { + var i = 0 + require(der[i++].toInt() == 0x30) + var sequenceLength = der[i++].toInt() and 0xff + if ((sequenceLength and 0x80) != 0) { val n=sequenceLength and 0x7f; sequenceLength=0; repeat(n) { sequenceLength=(sequenceLength shl 8) or (der[i++].toInt() and 0xff) } } + require(der[i++].toInt() == 0x02) + val rLen=der[i++].toInt() and 0xff; val r=der.copyOfRange(i,i+rLen); i+=rLen + require(der[i++].toInt() == 0x02) + val sLen=der[i++].toInt() and 0xff; val s=der.copyOfRange(i,i+sLen) + fun fixed(v: ByteArray): ByteArray { + val clean=if(v.size>32 && v[0]==0.toByte()) v.copyOfRange(1,v.size) else v + require(clean.size<=32) + return ByteArray(32).also { clean.copyInto(it,32-clean.size) } + } + return fixed(r)+fixed(s) + } + fun sign(message: String): String { + val ks=KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + val privateKey=ks.getKey(ALIAS,null) as java.security.PrivateKey + val signer=Signature.getInstance("SHA256withECDSA") + signer.initSign(privateKey); signer.update(message.toByteArray(Charsets.UTF_8)) + return b64(derToRaw(signer.sign())) + } +} diff --git a/android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt b/android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt new file mode 100644 index 00000000..fdfccc87 --- /dev/null +++ b/android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt @@ -0,0 +1,43 @@ +package com.paynex.localproof + +import android.service.notification.NotificationListenerService +import android.service.notification.StatusBarNotification +import org.json.JSONObject +import java.text.SimpleDateFormat +import java.util.Date +import java.util.Locale +import java.util.UUID + +class LocalProofNotificationListener : NotificationListenerService() { + override fun onNotificationPosted(sbn: StatusBarNotification?) { + if(sbn==null) return + val prefs=getSharedPreferences("localproof",MODE_PRIVATE) + if(!prefs.getBoolean("consent",false)) return + val deviceId=prefs.getString("device_id","").orEmpty() + val base=prefs.getString("base","").orEmpty() + val allow=prefs.getString("packages","").orEmpty().split(',').map{it.trim()}.filter{it.isNotBlank()}.toSet() + if(deviceId.isBlank()||base.isBlank()||sbn.packageName !in allow) return + val extras=sbn.notification.extras + // Notification text is read locally for parsing only; it is never placed in the request. + val localText=listOf( + extras.getCharSequence("android.title")?.toString().orEmpty(), + extras.getCharSequence("android.text")?.toString().orEmpty(), + extras.getCharSequence("android.bigText")?.toString().orEmpty() + ).joinToString(" ").take(3000) + val amountRegex=Regex("(?i)(?:INR|Rs\\.?|₹)\\s*([0-9,]+(?:\\.[0-9]{1,2})?)") + val amount=amountRegex.find(localText)?.groupValues?.getOrNull(1)?.replace(",","")?.toBigDecimalOrNull() + val utr=Regex("(?i)\\b(?:UTR|RRN|UPI REF(?:ERENCE)?|REF(?:ERENCE)? NO)\\s*[:#-]?\\s*([A-Z0-9]{8,22})\\b").find(localText)?.groupValues?.getOrNull(1) + if(amount==null && utr==null) return + val hasCredit=Regex("(?i)\\b(credited|received|deposited|credit to|added to)\\b").containsMatchIn(localText) + val hasDebit=Regex("(?i)\\b(debited|sent|paid|withdrawn|spent|debit from)\\b").containsMatchIn(localText) + val direction=if(hasCredit && !hasDebit) "credit" else if(hasDebit && !hasCredit) "debit" else "unknown" + val minor=amount?.multiply(java.math.BigDecimal(100))?.toLong() + val observed=SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX",Locale.US).format(Date(sbn.postTime)) + val event=JSONObject().put("event_uuid",UUID.randomUUID().toString()) + .put("source_package",sbn.packageName).put("parser_version","android-0.1.0") + .put("currency","INR").put("direction",direction).put("observed_at",observed) + if(minor!=null && minor>0) event.put("amount_minor",minor) + if(!utr.isNullOrBlank()) event.put("utr",utr) + Thread { try { Api.send(base,deviceId,event) } catch (_:Exception) { /* No silent paid-state action; user can inspect API/device state. */ } }.start() + } +} diff --git a/android/app/src/main/java/com/paynex/localproof/MainActivity.kt b/android/app/src/main/java/com/paynex/localproof/MainActivity.kt new file mode 100644 index 00000000..d2f51197 --- /dev/null +++ b/android/app/src/main/java/com/paynex/localproof/MainActivity.kt @@ -0,0 +1,59 @@ +package com.paynex.localproof + +import android.app.Activity +import android.content.Intent +import android.os.Bundle +import android.provider.Settings +import android.widget.CheckBox +import android.widget.Button +import android.widget.EditText +import android.widget.LinearLayout +import android.widget.TextView +import android.widget.Toast +import org.json.JSONObject + +class MainActivity : Activity() { + private lateinit var base: EditText + private lateinit var key: EditText + private lateinit var packages: EditText + private lateinit var device: EditText + private lateinit var status: TextView + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + val prefs=getSharedPreferences("localproof",MODE_PRIVATE) + val root=LinearLayout(this).apply { orientation=LinearLayout.VERTICAL; setPadding(32,32,32,32) } + fun field(hint:String,value:String="",secret:Boolean=false)=EditText(this).apply { this.hint=hint; setText(value); if(secret) inputType=android.text.InputType.TYPE_CLASS_TEXT or android.text.InputType.TYPE_TEXT_VARIATION_PASSWORD } + root.addView(TextView(this).apply { text="PAYNEX LocalProof\nDevice observation only — not bank verification"; textSize=20f }) + base=field("PAYNEX Worker URL",prefs.getString("base","https://paynex-api.sbn50088.workers.dev")!!) + key=field("Merchant API key (encrypted with Android Keystore)",SecretStore.decrypt(prefs.getString("api_key_enc","")),true) + packages=field("Allowed UPI app package names, comma-separated",prefs.getString("packages","")!!) + device=field("Enrolled device ID",prefs.getString("device_id","")!!) + listOf(base,key,packages,device).forEach { root.addView(it) } + status=TextView(this).apply { text="Notification access reads only the app notifications you explicitly allow. Parsing happens locally; only amount/reference metadata, app package, parser version and observation time may be sent. This is NOT bank verification and never marks payments paid."; textSize=14f } + root.addView(status) + val consent=CheckBox(this).apply { + text="I understand the data collection described above and explicitly consent to enable notification observation." + isChecked=prefs.getBoolean("consent",false) + } + root.addView(consent) + root.addView(Button(this).apply { text="Save settings"; setOnClickListener { save(); toast("Settings saved locally") } }) + root.addView(Button(this).apply { text="Enroll this device"; setOnClickListener { save(); Thread { try { val response=JSONObject(Api.enroll(base.text.toString(),key.text.toString())); runOnUiThread { device.setText(response.getString("device_id")); save(); status.text="Device enrolled. Keep the private key on this phone."; } } catch(e:Exception) { runOnUiThread { status.text=e.message; } } }.start() } }) + root.addView(Button(this).apply { text="Enable notification access"; setOnClickListener { + if(!consent.isChecked) { status.text="Please read and accept the disclosure first."; return@setOnClickListener } + prefs.edit().putBoolean("consent",true).apply() + startActivity(Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)) + } }) + root.addView(Button(this).apply { text="Disconnect (revoke device)"; setOnClickListener { prefs.edit().putBoolean("consent",false).apply(); save(); Thread { try { require(base.text.toString().startsWith("https://",true)) { "Use an HTTPS PAYNEX Worker URL" }; val url=java.net.URL(base.text.toString().trimEnd('/')+"/api/v1/localproof/devices/"+device.text.toString()); val c=url.openConnection() as java.net.HttpURLConnection; c.requestMethod="DELETE"; c.setRequestProperty("Authorization","Bearer "+key.text); val code=c.responseCode; runOnUiThread { status.text=if(code in 200..299) "Device revoked. You can disable notification access in Android Settings." else "Revoke failed: HTTP $code"; }; } catch(e:Exception){runOnUiThread{status.text=e.message}} }.start() } }) + setContentView(root) + } + private fun save() { + val worker=base.text.toString().trim() + getSharedPreferences("localproof",MODE_PRIVATE).edit() + .putString("base",worker) + .putString("api_key_enc",SecretStore.encrypt(key.text.toString())) + .remove("api_key") + .putString("packages",packages.text.toString()) + .putString("device_id",device.text.toString().trim()).apply() + } + private fun toast(value:String)=Toast.makeText(this,value,Toast.LENGTH_LONG).show() +} diff --git a/android/app/src/main/java/com/paynex/localproof/SecretStore.kt b/android/app/src/main/java/com/paynex/localproof/SecretStore.kt new file mode 100644 index 00000000..0f893cf9 --- /dev/null +++ b/android/app/src/main/java/com/paynex/localproof/SecretStore.kt @@ -0,0 +1,42 @@ +package com.paynex.localproof + +import android.security.keystore.KeyGenParameterSpec +import android.security.keystore.KeyProperties +import android.util.Base64 +import java.security.KeyStore +import javax.crypto.Cipher +import javax.crypto.KeyGenerator +import javax.crypto.SecretKey +import javax.crypto.spec.GCMParameterSpec + +object SecretStore { + private const val ALIAS = "paynex-localproof-settings-aes" + private fun key(): SecretKey { + val store=KeyStore.getInstance("AndroidKeyStore").apply { load(null) } + (store.getKey(ALIAS,null) as? SecretKey)?.let { return it } + val generator=KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES,"AndroidKeyStore") + generator.init(KeyGenParameterSpec.Builder(ALIAS,KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT) + .setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setRandomizedEncryptionRequired(true) + .build()) + return generator.generateKey() + } + fun encrypt(value:String):String { + if(value.isEmpty()) return "" + val cipher=Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.ENCRYPT_MODE,key()) + val encrypted=cipher.doFinal(value.toByteArray(Charsets.UTF_8)) + return Base64.encodeToString(cipher.iv+encrypted,Base64.NO_WRAP) + } + fun decrypt(value:String?):String { + if(value.isNullOrEmpty()) return "" + return try { + val packed=Base64.decode(value,Base64.NO_WRAP) + require(packed.size>12) + val cipher=Cipher.getInstance("AES/GCM/NoPadding") + cipher.init(Cipher.DECRYPT_MODE,key(),GCMParameterSpec(128,packed.copyOfRange(0,12))) + String(cipher.doFinal(packed.copyOfRange(12,packed.size)),Charsets.UTF_8) + } catch (_:Exception) { "" } + } +} diff --git a/android/build.gradle.kts b/android/build.gradle.kts new file mode 100644 index 00000000..c7ad7549 --- /dev/null +++ b/android/build.gradle.kts @@ -0,0 +1,4 @@ +plugins { + id("com.android.application") version "8.7.3" apply false + id("org.jetbrains.kotlin.android") version "2.0.21" apply false +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100644 index 00000000..459e0db2 --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8 +android.useAndroidX=true +kotlin.code.style=official diff --git a/android/settings.gradle.kts b/android/settings.gradle.kts new file mode 100644 index 00000000..a2ab70a8 --- /dev/null +++ b/android/settings.gradle.kts @@ -0,0 +1,4 @@ +pluginManagement { repositories { google(); mavenCentral(); gradlePluginPortal() } } +dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS); repositories { google(); mavenCentral() } } +rootProject.name = "PAYNEX-LocalProof" +include(":app") diff --git a/dashboard/index.html b/dashboard/index.html index d67e74b8..39575eec 100644 --- a/dashboard/index.html +++ b/dashboard/index.html @@ -167,6 +167,7 @@

Payment mode onboarding · A / B / C

↻Subscriptions ◇PAYNEX V2 Payments ⚡V2 Power Suite + ⌁LocalProof devices ⌁Reports & analytics ⚙Settings & security ↗Webhooks @@ -354,6 +355,16 @@

Payment mode onboarding · A / B / C

These invoices are separate software/service fees. They do not reduce your customer payment settlement. If an invoice is open, use the payment instructions provided separately by PAYNEX support; status changes only after the admin verifies the external payment reference.
Connect to load invoices.
+
+

LocalProof · Device observations

+

Connect the optional Android companion using an active merchant API key. Notifications are parsed locally and arrive here as unverified reconciliation hints only. They never mark payments paid or trigger fulfilment.

+
+
Paired devices
Load devices to view pairing status.
+
Recent device observations
No device observations loaded.
+
+
Trust boundary

A phone notification is not bank-to-server evidence. Verify the credit in your receiving bank/UPI app or through an authorised provider before fulfilling any order.

+
+

Financial analytics

Date range follows filters above
@@ -383,6 +394,15 @@

Payment mode onboarding · A / B / C

if(!res.ok) throw new Error(data.error||("Request failed ("+res.status+")")); return data; } + async function loadLocalProof(){ + error("localProofError",""); + try{ + const [devices,events]=await Promise.all([api("/api/v1/localproof/devices"),api("/api/v1/localproof/events?limit=30")]); + $("localProofDevices").innerHTML=(devices.devices||[]).length?(devices.devices||[]).map(d=>'
'+esc(d.label||"Android device")+'
'+esc(d.id)+' · '+esc(d.last_seen_at||"Not seen yet")+'
'+esc(d.status)+''+(d.status==="active"?' ':'')+'
').join(""):'
No paired devices. Enroll from the LocalProof Android app.
'; + $("localProofObservations").innerHTML=(events.observations||[]).length?(events.observations||[]).map(o=>'
'+esc(o.source_package)+'
'+esc(o.observed_at)+' · '+(o.amount_minor==null?"Amount unavailable":money(o.amount_minor,o.currency))+' · '+esc(o.direction||"unknown")+'
OBSERVED · UNVERIFIED
').join(""):'
No notification observations received yet.
'; + $("localProofDevices").querySelectorAll("[data-localproof-revoke]").forEach(button=>button.addEventListener("click",async()=>{if(!confirm("Revoke this device? It will no longer be able to submit observations."))return;button.disabled=true;try{await api("/api/v1/localproof/devices/"+encodeURIComponent(button.dataset.localproofRevoke),{method:"DELETE"});await loadLocalProof()}catch(e){error("localProofError",e.message);button.disabled=false}})); + }catch(e){error("localProofError",e.message)} + } function error(el,msg){$(el).textContent=msg;$(el).style.display=msg?"block":"none"} async function load(){ error("appError",""); @@ -854,6 +874,8 @@

Payment mode onboarding · A / B / C

$("openFullOnboarding").addEventListener("click",async()=>{$("limitedWorkspace").classList.add("hidden");$("onboarding").classList.remove("hidden");await loadMyApplications();await loadModeOnboarding();}); $("saveLimitedStore").addEventListener("click",saveLimitedStore);$("createSandboxCheckout").addEventListener("click",createSandboxCheckout);$("limitedLogout").addEventListener("click",async()=>{try{await fetch("/api/auth/sign-out",{method:"POST",credentials:"same-origin"})}catch{}$("limitedWorkspace").classList.add("hidden");$("login").classList.remove("hidden")}); $("saveModeOnboarding").addEventListener("click",saveModeOnboarding); $("uploadKycEvidence")?.addEventListener("click",uploadKycEvidence); $("gatewayApplicationForm").addEventListener("submit",submitGatewayApplication);$("refreshApplications").addEventListener("click",loadMyApplications);$("onboardingLogout").addEventListener("click",async()=>{try{await fetch("/api/auth/sign-out",{method:"POST",credentials:"same-origin"})}catch{}$("onboarding").classList.add("hidden");$("login").classList.remove("hidden")}); + $("refreshLocalProof").addEventListener("click",loadLocalProof); + document.querySelector('[data-merchant-nav="merchantLocalProof"]')?.addEventListener("click",loadLocalProof); $("powerRefresh").addEventListener("click",refreshPowerSuite); $("powerRefreshLedger").addEventListener("click",refreshPowerSuite); $("powerCreateOrder").addEventListener("click",createPowerOrder); @@ -939,7 +961,7 @@

Payment mode onboarding · A / B / C

document.getElementById("merchantSideSignOut")?.addEventListener("click",()=>document.getElementById("logout")?.click()); document.getElementById("merchantBackToDashboard")?.addEventListener("click",()=>{document.getElementById("onboarding")?.classList.add("hidden");app.classList.remove("hidden")}); document.getElementById("merchantThemeToggle")?.addEventListener("click",()=>{const light=document.body.dataset.merchantTheme!=="light";document.body.dataset.merchantTheme=light?"light":"dark";document.getElementById("merchantThemeToggle").textContent=light?"☾ Dark":"☼ Light"}); - const ids=["merchantOverview","merchantTransactions","merchantLinks","merchantCustomers","merchantSubscriptions","merchantSettings","merchantWebhooks","merchantAudit","merchantReports"]; + const ids=["merchantOverview","merchantTransactions","merchantLinks","merchantCustomers","merchantSubscriptions","merchantSettings","merchantWebhooks","merchantAudit","merchantReports","merchantLocalProof"]; const targets=ids.map(id=>document.getElementById(id)).filter(Boolean); if("IntersectionObserver" in window){const io=new IntersectionObserver(entries=>{const visible=entries.filter(e=>e.isIntersecting).sort((a,b)=>b.intersectionRatio-a.intersectionRatio)[0];if(visible){const anchor=document.querySelector('[data-merchant-nav="'+visible.target.id+'"]');if(anchor){document.querySelectorAll("[data-merchant-nav]").forEach(x=>x.classList.toggle("active",x===anchor))}}},{rootMargin:"-15% 0px -70% 0px",threshold:[0,.1,.35]});targets.forEach(el=>io.observe(el))} })(); diff --git a/docs/LOCALPROOF-STATUS.md b/docs/LOCALPROOF-STATUS.md index 97bdb4b3..3b7b3ec5 100644 --- a/docs/LOCALPROOF-STATUS.md +++ b/docs/LOCALPROOF-STATUS.md @@ -1,52 +1,48 @@ # PAYNEX LocalProof — implementation status and safe rollout -**Status: specification only; no Android companion APK is currently included in this repository.** +**Status: backend and initial Android companion source implemented on a feature branch; CI APK build and physical-device validation are pending. No production release has been made.** -This document prevents a device-notification prototype from being mistaken for a bank-verified payment integration. +## Implemented on the feature branch -## What exists today +- Merchant-authenticated device enrollment, listing and revocation. +- Public-only P-256 JWK registration; the Android private signing key is generated and retained by Android Keystore. +- ECDSA signed event requests over `timestamp.nonce.raw_request_body`, with five-minute request freshness, one-time per-device nonce storage, event UUID uniqueness and revoked-device checks. +- Strict payload allowlist; full notification body/text is never sent. The server stores only parsed amount, currency, source package, parser version, observed time, untrusted parsed direction (credit/debit/unknown), UTR hash and canonical payload hash. +- Merchant dashboard panel to list paired devices, view recent observations and revoke a device. +- Android companion with explicit consent checkbox, package allowlist, local-only notification parsing, HTTPS-only Worker URL, encrypted API-key storage using Android Keystore and revoke control. +- Idempotent D1 migration 0028 and schema snapshot; staging/production workflow wiring and Android debug-APK CI workflow. +- Initial Worker route tests and syntax checks. -- The Worker has a provider-neutral verification contract and fail-closed payment state mapping. -- The Worker keeps UPI-intent transactions pending until an authorised provider verifies the payment. -- A signed UPI-partner webhook contract exists, but it is disabled until an authorised partner and its secret are configured. -- Paytm server-side initiation, checksum validation, status lookup and scheduled reconciliation code exist, but Paytm is disabled by default and requires approved merchant onboarding and production credentials. -- No LocalProof Android source, Android build configuration, device-registration endpoint or device-event ingestion endpoint is present in this repository. +## Trust and payment authority boundary -## LocalProof must not become a payment-verification authority +Every device observation is returned as `OBSERVED_UNVERIFIED`. It is not bank confirmation. The feature must never set payment/order status to paid, post a verified ledger journal, emit `payment.succeeded`, activate subscriptions, or trigger fulfilment. Notifications may be delayed, missing, duplicated, modified or spoofed. Only an authorised provider's authenticated server-to-server webhook or status API can establish provider-verified payment. -Android notification or SMS content is an observation from a device, not an authenticated bank-to-server payment confirmation. Notifications can be delayed, missing, duplicated, modified by apps, or generated from untrusted sources. Android 13+ notification access also requires explicit user-granted notification-listener access; the app must disclose this clearly and process the minimum necessary information. +## Android privacy and operation -A future LocalProof client may be used only as a **reconciliation-assistance signal**: +- Notification-listener permission is requested only after the user checks an explicit disclosure/consent checkbox and opens Android Settings. +- The user must manually allowlist exact app package names. No SMS inbox permission is requested. +- Notification text is parsed locally and discarded; only allowlisted structured metadata is uploaded. +- The private signing key is non-exportable in Android Keystore. The merchant API key is encrypted at rest with an Android Keystore AES-GCM key. +- Revoke the device in the app/dashboard to invalidate its server identity. Disable notification access in Android Settings to stop the OS listener as well. +- Notification formats vary by bank, UPI app, language and OS version; unsupported formats are ignored. +- The first companion version has no durable offline retry queue; failed network submissions are not guaranteed to be delivered later. -- Store a device-observed event separately from a payment-provider event. -- Never transition a transaction to `verified` from a notification, SMS, screenshot, UTR entered by a customer, or UPI app return. -- Never activate subscriptions or deliver paid entitlements from device-observed evidence alone. -- Require explicit merchant device pairing, revocable credentials, short-lived request authentication, timestamp/replay checks, event deduplication and merchant-scoped access. -- Minimise data: parse only the minimum fields needed on-device; do not upload notification bodies, contact lists, inbox history or unrelated app content. -- Provide a clear disconnect/revoke action and an audit trail. -- Keep device-observed status visibly distinct from provider-confirmed status. +## Remaining release gates -## Required implementation sequence +- [ ] GitHub Actions Worker suite and Android debug APK build both pass on the current PR head. +- [ ] Physical-device tests on the user's Android 16 device, including permission, pairing, signature, notification parsing, revocation and network loss. +- [ ] Adversarial integration tests for replay, stale signature, revoked device, cross-merchant access and no payment-state mutation. +- [ ] APK artifact reviewed and privately installed; no release signing key committed. +- [ ] Production migration/Worker rollout separately approved and guarded. -1. Build an Android 16 companion app with an explicit disclosure and user-controlled notification-listener permission. Support multiple UPI/bank apps without assuming their notification formats are stable. -2. Add an operator-controlled device-pairing flow. Do not put merchant API keys or admin tokens in the APK. -3. Add a dedicated device-event API and D1 tables for paired devices, event IDs, timestamps, observed fields and audit records. Authenticate each device independently and scope every record to one merchant. -4. Add replay protection, rate limits, revocation, clock-skew handling, schema validation and tests for forged, duplicated, stale and cross-merchant events. -5. Display device observations only in a separate reconciliation panel. They must not alter the payment state or trigger fulfilment. -6. Build and test a debug APK in CI, then distribute it privately for device testing. A release APK requires a protected signing key; never commit that key to GitHub. -7. Keep authoritative payment verification on an approved provider's signed webhook and/or authenticated status API. +## API -## Release acceptance criteria - -- [ ] Android 16 install and permission flows tested on a physical device. -- [ ] Multiple UPI/bank notification formats tested, with unsupported formats safely ignored. -- [ ] No notification or SMS content is uploaded wholesale. -- [ ] Device pairing, revocation and merchant isolation tested. -- [ ] Duplicate/replayed/stale/forged event tests pass. -- [ ] Device events cannot mark payments verified or activate subscriptions. -- [ ] APK signing and release artifact handling reviewed. -- [ ] Separate provider-side payment verification has passed sandbox and production onboarding gates. +- `POST /api/v1/localproof/devices` — merchant API key/session authenticated enrollment. +- `GET /api/v1/localproof/devices` — merchant-scoped device list. +- `DELETE /api/v1/localproof/devices/{deviceId}` — merchant-scoped revocation. +- `POST /api/v1/localproof/events` — signed device observation ingestion. +- `GET /api/v1/localproof/events` — merchant-scoped observations. ## Current user-facing truth -PAYNEX has no LocalProof APK available yet. A successful GitHub Pages or Worker deployment does not mean an Android APK has been built, notification access has been tested, or real UPI payments can be verified. Real payments must remain pending unless an authorised provider confirms them server-to-server. +This feature is not yet deployed to the live Worker. The Android source is on a draft PR; the APK is not available until the CI artifact build passes. It is not a payment gateway or a bank feed. Real payment verification continues to require an authorised provider's server-side confirmation. diff --git a/worker/migrations/0028_localproof_device_observation.sql b/worker/migrations/0028_localproof_device_observation.sql new file mode 100644 index 00000000..902f6a00 --- /dev/null +++ b/worker/migrations/0028_localproof_device_observation.sql @@ -0,0 +1,52 @@ +-- LocalProof stores only signed, minimised Android notification observations. +-- Device events are reconciliation hints and never authoritative payment confirmations. +CREATE TABLE IF NOT EXISTS localproof_devices ( + id TEXT PRIMARY KEY, + merchant_id TEXT NOT NULL REFERENCES merchants(id) ON DELETE CASCADE, + label TEXT NOT NULL DEFAULT 'Android device', + public_key_jwk TEXT NOT NULL, + key_thumbprint TEXT NOT NULL UNIQUE, + status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','active','revoked')), + enrolled_at TEXT, + last_seen_at TEXT, + revoked_at TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE TABLE IF NOT EXISTS localproof_nonces ( + device_id TEXT NOT NULL REFERENCES localproof_devices(id) ON DELETE CASCADE, + nonce_hash TEXT NOT NULL, + expires_at INTEGER NOT NULL, + used_at TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY(device_id,nonce_hash) +); +CREATE TABLE IF NOT EXISTS localproof_observations ( + id TEXT PRIMARY KEY, + merchant_id TEXT NOT NULL REFERENCES merchants(id) ON DELETE CASCADE, + device_id TEXT NOT NULL REFERENCES localproof_devices(id) ON DELETE CASCADE, + event_uuid TEXT NOT NULL, + source TEXT NOT NULL CHECK(source='android_notification_observation'), + source_package TEXT NOT NULL, + parser_version TEXT NOT NULL, + amount_minor INTEGER CHECK(amount_minor IS NULL OR amount_minor > 0), + currency TEXT NOT NULL DEFAULT 'INR' CHECK(currency='INR'), + observed_at TEXT NOT NULL, + utr_hash TEXT, + canonical_payload_hash TEXT NOT NULL, + match_state TEXT NOT NULL DEFAULT 'unmatched' CHECK(match_state IN ('unmatched','possible_match','awaiting_bank_confirmation','ignored')), + matched_transaction_id TEXT REFERENCES transactions(id), + received_at TEXT NOT NULL DEFAULT (datetime('now')), + UNIQUE(device_id,event_uuid) +); +CREATE TABLE IF NOT EXISTS localproof_audit_events ( + id TEXT PRIMARY KEY, + merchant_id TEXT NOT NULL REFERENCES merchants(id) ON DELETE CASCADE, + device_id TEXT REFERENCES localproof_devices(id) ON DELETE SET NULL, + action TEXT NOT NULL CHECK(action IN ('device_enrolled','device_revoked','observation_received','observation_rejected','observation_matched')), + resource_id TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_localproof_devices_merchant_status ON localproof_devices(merchant_id,status); +CREATE INDEX IF NOT EXISTS idx_localproof_observations_merchant_received ON localproof_observations(merchant_id,received_at); +CREATE INDEX IF NOT EXISTS idx_localproof_nonces_expiry ON localproof_nonces(expires_at); diff --git a/worker/migrations/0029_localproof_observation_direction.sql b/worker/migrations/0029_localproof_observation_direction.sql new file mode 100644 index 00000000..8922dbd1 --- /dev/null +++ b/worker/migrations/0029_localproof_observation_direction.sql @@ -0,0 +1,5 @@ +-- Preserve whether the notification parser observed a credit, debit or ambiguous direction. +-- Direction remains untrusted device metadata and never authorises payment state transitions. +ALTER TABLE localproof_observations +ADD COLUMN direction TEXT NOT NULL DEFAULT 'unknown' +CHECK(direction IN ('credit','debit','unknown')); diff --git a/worker/schema.sql b/worker/schema.sql index 686f4581..86ca5f4f 100644 --- a/worker/schema.sql +++ b/worker/schema.sql @@ -334,3 +334,61 @@ CREATE TABLE IF NOT EXISTS merchant_provider_connections ( ); CREATE INDEX IF NOT EXISTS idx_provider_connections_merchant ON merchant_provider_connections(merchant_id,status); + + +-- LocalProof device observation schema (kept aligned with migration 0028). +-- LocalProof stores only signed, minimised Android notification observations. +-- Device events are reconciliation hints and never authoritative payment confirmations. +CREATE TABLE IF NOT EXISTS localproof_devices ( + id TEXT PRIMARY KEY, + merchant_id TEXT NOT NULL REFERENCES merchants(id) ON DELETE CASCADE, + label TEXT NOT NULL DEFAULT 'Android device', + public_key_jwk TEXT NOT NULL, + key_thumbprint TEXT NOT NULL UNIQUE, + status TEXT NOT NULL DEFAULT 'pending' CHECK(status IN ('pending','active','revoked')), + enrolled_at TEXT, + last_seen_at TEXT, + revoked_at TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE TABLE IF NOT EXISTS localproof_nonces ( + device_id TEXT NOT NULL REFERENCES localproof_devices(id) ON DELETE CASCADE, + nonce_hash TEXT NOT NULL, + expires_at INTEGER NOT NULL, + used_at TEXT, + created_at TEXT NOT NULL DEFAULT (datetime('now')), + PRIMARY KEY(device_id,nonce_hash) +); +CREATE TABLE IF NOT EXISTS localproof_observations ( + id TEXT PRIMARY KEY, + merchant_id TEXT NOT NULL REFERENCES merchants(id) ON DELETE CASCADE, + device_id TEXT NOT NULL REFERENCES localproof_devices(id) ON DELETE CASCADE, + event_uuid TEXT NOT NULL, + source TEXT NOT NULL CHECK(source='android_notification_observation'), + source_package TEXT NOT NULL, + parser_version TEXT NOT NULL, + amount_minor INTEGER CHECK(amount_minor IS NULL OR amount_minor > 0), + direction TEXT NOT NULL DEFAULT 'unknown' CHECK(direction IN ('credit','debit','unknown')), + currency TEXT NOT NULL DEFAULT 'INR' CHECK(currency='INR'), + observed_at TEXT NOT NULL, + utr_hash TEXT, + canonical_payload_hash TEXT NOT NULL, + match_state TEXT NOT NULL DEFAULT 'unmatched' CHECK(match_state IN ('unmatched','possible_match','awaiting_bank_confirmation','ignored')), + matched_transaction_id TEXT REFERENCES transactions(id), + received_at TEXT NOT NULL DEFAULT (datetime('now')), + UNIQUE(device_id,event_uuid) +); +CREATE TABLE IF NOT EXISTS localproof_audit_events ( + id TEXT PRIMARY KEY, + merchant_id TEXT NOT NULL REFERENCES merchants(id) ON DELETE CASCADE, + device_id TEXT REFERENCES localproof_devices(id) ON DELETE SET NULL, + action TEXT NOT NULL CHECK(action IN ('device_enrolled','device_revoked','observation_received','observation_rejected','observation_matched')), + resource_id TEXT, + metadata_json TEXT NOT NULL DEFAULT '{}', + created_at TEXT NOT NULL DEFAULT (datetime('now')) +); +CREATE INDEX IF NOT EXISTS idx_localproof_devices_merchant_status ON localproof_devices(merchant_id,status); +CREATE INDEX IF NOT EXISTS idx_localproof_observations_merchant_received ON localproof_observations(merchant_id,received_at); +CREATE INDEX IF NOT EXISTS idx_localproof_nonces_expiry ON localproof_nonces(expires_at); + +-- Existing installations add direction with migration 0029_localproof_observation_direction.sql. diff --git a/worker/src/localproof.js b/worker/src/localproof.js new file mode 100644 index 00000000..21e54ae1 --- /dev/null +++ b/worker/src/localproof.js @@ -0,0 +1,114 @@ +// LocalProof server contract: signed device observations are reconciliation hints only. +const MAX_EVENT_BYTES = 8192; +const CLOCK_SKEW_MS = 300000; +const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; +const B64URL_RE = /^[A-Za-z0-9_-]+$/; +const PACKAGE_RE = /^[A-Za-z0-9_]+(?:\.[A-Za-z0-9_]+){1,5}$/; +const sha256 = async value => { + const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value)); + return [...new Uint8Array(bytes)].map(b => b.toString(16).padStart(2,"0")).join(""); +}; +const decode64 = value => { + if (typeof value !== "string" || !B64URL_RE.test(value)) throw new Error("Invalid base64url"); + const raw = atob(value.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat((4-value.length%4)%4)); + return Uint8Array.from(raw,c=>c.charCodeAt(0)); +}; +const text = (v,n) => String(v ?? "").trim().slice(0,n); +async function parseRequest(request) { + const raw = await request.text(); + if (new TextEncoder().encode(raw).length > MAX_EVENT_BYTES) throw new Error("Request exceeds 8 KB"); + let body; try { body=JSON.parse(raw); } catch { throw new Error("Invalid JSON"); } + if (!body || typeof body !== "object" || Array.isArray(body)) throw new Error("JSON object required"); + return {raw,body}; +} +function publicJwk(jwk) { + if (!jwk || jwk.kty!=="EC" || jwk.crv!=="P-256" || typeof jwk.x!=="string" || typeof jwk.y!=="string" || jwk.d || jwk.x.length!==43 || jwk.y.length!==43) throw new Error("Public P-256 JWK required"); + decode64(jwk.x); decode64(jwk.y); + return {kty:"EC",crv:"P-256",x:jwk.x,y:jwk.y,ext:true}; +} +async function verify(jwk,message,signature) { + const key=await crypto.subtle.importKey("jwk",jwk,{name:"ECDSA",namedCurve:"P-256"},false,["verify"]); + return crypto.subtle.verify({name:"ECDSA",hash:"SHA-256"},key,decode64(signature),new TextEncoder().encode(message)); +} +export async function handleLocalProofRequest(request,env,origin,authenticate,json) { + const url=new URL(request.url), path=url.pathname; + const devices=path==="/api/v1/localproof/devices", events=path==="/api/v1/localproof/events"; + const revoke=path.match(/^\/api\/v1\/localproof\/devices\/([0-9a-f-]{36})$/i); + if (!devices && !events && !revoke) return null; + const respond=(data,status)=>json(data,status,origin); + if (request.method==="POST" && events) { + let raw,body; try {({raw,body}=await parseRequest(request));} catch(e){return respond({error:e.message},400);} + const id=text(request.headers.get("x-localproof-device"),64), ts=Number(request.headers.get("x-localproof-timestamp")); + const nonce=text(request.headers.get("x-localproof-nonce"),128), sig=text(request.headers.get("x-localproof-signature"),256); + if(!UUID_RE.test(id)||!Number.isSafeInteger(ts)||Math.abs(Date.now()-ts)>CLOCK_SKEW_MS||nonce.length<16||!B64URL_RE.test(nonce)||!sig) return respond({error:"Invalid device authentication"},401); + const device=await env.DB.prepare("SELECT id,merchant_id,public_key_jwk,status FROM localproof_devices WHERE id=?").bind(id).first(); + if(!device||device.status!=="active") return respond({error:"Device is not active"},401); + let valid=false; try{valid=await verify(JSON.parse(device.public_key_jwk),ts+"."+nonce+"."+raw,sig);}catch{} + if(!valid) return respond({error:"Invalid device signature"},401); + const allowed=["event_uuid","source_package","parser_version","amount_minor","currency","observed_at","utr","direction"]; + if(Object.keys(body).some(k=>!allowed.includes(k))) return respond({error:"Only minimised parsed fields are accepted; notification text is prohibited"},400); + const event=text(body.event_uuid,64), pkg=text(body.source_package,180), parser=text(body.parser_version,40), observed=text(body.observed_at,40); + const amount=body.amount_minor==null?null:Number(body.amount_minor), currency=text(body.currency||"INR",3).toUpperCase(), direction=text(body.direction||"unknown",12); + const utr=text(body.utr,80).replace(/\s+/g,"").toUpperCase(); + const observedMs=Date.parse(observed); + if(!UUID_RE.test(event)||!PACKAGE_RE.test(pkg)||!/^[A-Za-z0-9._-]{1,32}$/.test(parser)||!Number.isFinite(observedMs)||observedMs>Date.now()+5*60*1000||observedMs10000000000))||currency!=="INR"||!["credit","debit","unknown"].includes(direction)||(utr&&!/^[A-Z0-9]{6,80}$/.test(utr))) return respond({error:"Invalid observation fields"},400); + const now=Math.floor(Date.now()/1000), nonceHash=await sha256(nonce), payloadHash=await sha256(raw), utrHash=utr?await sha256(utr):null; + try { + const batchResult = await env.DB.batch([ + env.DB.prepare("DELETE FROM localproof_nonces WHERE expires_at < ?").bind(now), + env.DB.prepare("INSERT INTO localproof_nonces (device_id,nonce_hash,expires_at,used_at) VALUES (?,?,?,datetime('now'))").bind(id,nonceHash,now+600), + env.DB.prepare("INSERT INTO localproof_observations (id,merchant_id,device_id,event_uuid,source,source_package,parser_version,amount_minor,currency,observed_at,utr_hash,canonical_payload_hash,direction,match_state) SELECT ?,merchant_id,id,?,'android_notification_observation',?,?,?,?,?,?,?,?, 'unmatched' FROM localproof_devices WHERE id=? AND status='active'").bind(crypto.randomUUID(),event,pkg,parser,amount,currency,observed,utrHash,payloadHash,direction,id), + env.DB.prepare("UPDATE localproof_devices SET last_seen_at=datetime('now') WHERE id=? AND status='active'").bind(id), + env.DB.prepare("INSERT INTO localproof_audit_events (id,merchant_id,device_id,action,resource_id,metadata_json) SELECT ?,merchant_id,device_id,'observation_received',?,? FROM localproof_observations WHERE device_id=? AND event_uuid=?").bind(crypto.randomUUID(),event,JSON.stringify({amount_present:amount!==null,reference_present:Boolean(utrHash),source_package:pkg}),id,event) + ]); + if (Number(batchResult?.[2]?.meta?.changes || 0) === 0) return respond({error:"Device was revoked before the observation could be stored"},401); + } catch { + const duplicate=await env.DB.prepare("SELECT id FROM localproof_observations WHERE device_id=? AND event_uuid=?").bind(id,event).first(); + return respond({error:duplicate?"Duplicate observation event":"Replay, duplicate nonce or storage conflict",duplicate:Boolean(duplicate)},409); + } + return respond({accepted:true,observation_id:event,state:"OBSERVED_UNVERIFIED",bank_verified:false,payment_marked_paid:false,fulfilment_triggered:false},202); + } + const merchantId=await authenticate(request,env); + if(!merchantId) return respond({error:"Unauthorised"},401); + if(request.method==="POST"&&devices){ + let body;try{body=await request.json();}catch{return respond({error:"Invalid JSON"},400);} + let jwk;try{jwk=publicJwk(body.public_key_jwk);}catch(e){return respond({error:e.message},400);} + const label=text(body.label||"Android device",80), thumb=await sha256(JSON.stringify({crv:jwk.crv,kty:jwk.kty,x:jwk.x,y:jwk.y})); + const existing=await env.DB.prepare("SELECT id,merchant_id,status FROM localproof_devices WHERE key_thumbprint=?").bind(thumb).first(); + if(existing){ + if(existing.merchant_id!==merchantId) return respond({error:"This device key is already bound to another merchant; it cannot be transferred"},409); + if(existing.status==="revoked"){ + const results=await env.DB.batch([ + env.DB.prepare("UPDATE localproof_devices SET label=?,status='active',enrolled_at=datetime('now'),last_seen_at=NULL,revoked_at=NULL WHERE id=? AND merchant_id=? AND status='revoked'").bind(label,existing.id,merchantId), + env.DB.prepare("INSERT INTO localproof_audit_events (id,merchant_id,device_id,action,resource_id,metadata_json) SELECT ?,?,?, 'device_enrolled',?,? WHERE EXISTS (SELECT 1 FROM localproof_devices WHERE id=? AND merchant_id=? AND status='active')").bind(crypto.randomUUID(),merchantId,existing.id,existing.id,JSON.stringify({label,algorithm:"ECDSA_P256_SHA256",reactivated:true}),existing.id,merchantId) + ]); + if(Number(results?.[0]?.meta?.changes||0)!==1) return respond({error:"Device could not be reactivated; refresh and retry"},409); + }else if(existing.status!=="active"){ + return respond({error:"This device is pending review"},409); + } + return respond({device_id:existing.id,status:"active",reactivated:existing.status==="revoked",algorithm:"ECDSA_P256_SHA256",signing_message:"timestamp.nonce.raw_request_body",notification_content_uploaded:false},200); + } + const id=crypto.randomUUID(); + try{await env.DB.batch([ + env.DB.prepare("INSERT INTO localproof_devices (id,merchant_id,label,public_key_jwk,key_thumbprint,status,enrolled_at) VALUES (?,?,?,?,?,'active',datetime('now'))").bind(id,merchantId,label,JSON.stringify(jwk),thumb), + env.DB.prepare("INSERT INTO localproof_audit_events (id,merchant_id,device_id,action,resource_id,metadata_json) VALUES (?,?,?,'device_enrolled',?,?)").bind(crypto.randomUUID(),merchantId,id,id,JSON.stringify({label,algorithm:"ECDSA_P256_SHA256"})) + ]);}catch{return respond({error:"Device key already enrolled or could not be stored"},409);} + return respond({device_id:id,status:"active",algorithm:"ECDSA_P256_SHA256",signing_message:"timestamp.nonce.raw_request_body",notification_content_uploaded:false},201); + } + if(request.method==="GET"&&devices){ + const rows=await env.DB.prepare("SELECT id,label,status,enrolled_at,last_seen_at,revoked_at,created_at FROM localproof_devices WHERE merchant_id=? ORDER BY created_at DESC LIMIT 50").bind(merchantId).all(); + return respond({devices:rows.results||[]},200); + } + if(request.method==="DELETE"&&revoke){ + const id=revoke[1]; + const result=await env.DB.prepare("UPDATE localproof_devices SET status='revoked',revoked_at=datetime('now') WHERE id=? AND merchant_id=? AND status='active'").bind(id,merchantId).run(); + if(Number(result.meta?.changes||0)) await env.DB.prepare("INSERT INTO localproof_audit_events (id,merchant_id,device_id,action,resource_id,metadata_json) VALUES (?,?,?,'device_revoked',?,'{}')").bind(crypto.randomUUID(),merchantId,id,id).run(); + return respond({revoked:Number(result.meta?.changes||0)>0,device_id:id},Number(result.meta?.changes||0)>0?200:404); + } + if(request.method==="GET"&&events){ + const limit=Math.min(100,Math.max(1,Number(url.searchParams.get("limit")||50))); + const rows=await env.DB.prepare("SELECT id,event_uuid,device_id,source_package,parser_version,amount_minor,currency,direction,observed_at,utr_hash,match_state,received_at FROM localproof_observations WHERE merchant_id=? ORDER BY received_at DESC LIMIT ?").bind(merchantId,limit).all(); + return respond({observations:rows.results||[],verification_authority:"reconciliation_assistance_only"},200); + } + return respond({error:"Method not allowed"},405); +} diff --git a/worker/test/localproof.test.js b/worker/test/localproof.test.js new file mode 100644 index 00000000..feb576c6 --- /dev/null +++ b/worker/test/localproof.test.js @@ -0,0 +1,110 @@ +import test from "node:test"; +import assert from "node:assert/strict"; +import { handleLocalProofRequest } from "../src/localproof.js"; + +const json = (body,status=200) => new Response(JSON.stringify(body),{status}); + +test("LocalProof handler ignores unrelated routes", async () => { + const request = new Request("https://paynex.example/api/v1/orders"); + const result = await handleLocalProofRequest(request, {}, "*", async()=>null, json); + assert.equal(result,null); +}); + +test("LocalProof rejects oversized event payload before database access", async () => { + const request = new Request("https://paynex.example/api/v1/localproof/events",{ + method:"POST", + headers:{"content-type":"application/json"}, + body:JSON.stringify({payload:"x".repeat(9000)}) + }); + const result = await handleLocalProofRequest(request, {}, "*", async()=>null, json); + assert.equal(result.status,400); + assert.match((await result.json()).error,/8 KB/); +}); + +test("LocalProof rejects malformed JSON without accessing merchant credentials", async () => { + const request = new Request("https://paynex.example/api/v1/localproof/events",{ + method:"POST",headers:{"content-type":"application/json"},body:"{not-json" + }); + const result = await handleLocalProofRequest(request, {}, "*", async()=>null, json); + assert.equal(result.status,400); + assert.match((await result.json()).error,/JSON/); +}); + +test("LocalProof merchant routes require an authenticated active merchant", async () => { + const request = new Request("https://paynex.example/api/v1/localproof/devices"); + let authCalls=0; + const result = await handleLocalProofRequest(request, {}, "*", async()=>{authCalls++;return null;}, json); + assert.equal(authCalls,1); + assert.equal(result.status,401); +}); + +test("valid signed LocalProof event is observation-only and cannot change payment state", async () => { + const pair = await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},true,["sign","verify"]); + const jwk = await crypto.subtle.exportKey("jwk",pair.publicKey); + const deviceId = "123e4567-e89b-42d3-a456-426614174000"; + const body = JSON.stringify({ + event_uuid:"123e4567-e89b-42d3-a456-426614174001", + source_package:"com.example.upi", + parser_version:"android-0.1.0", + amount_minor:12345, + currency:"INR", + direction:"credit", + observed_at:new Date().toISOString(), + utr:"ABCD12345678" + }); + const timestamp=String(Date.now()), nonce="0123456789abcdef0123456789abcdef"; + const message=timestamp+"."+nonce+"."+body; + const signature=await crypto.subtle.sign({name:"ECDSA",hash:"SHA-256"},pair.privateKey,new TextEncoder().encode(message)); + const b64url=Buffer.from(signature).toString("base64url"); + const statements=[]; + const db={ + prepare(sql){return {sql,args:[],bind(...args){this.args=args;return this;},async first(){return sql.includes("FROM localproof_devices")?{id:deviceId,merchant_id:"merchant-A",public_key_jwk:JSON.stringify(jwk),status:"active"}:null;}};}, + async batch(items){statements.push(...items);return [{meta:{changes:0}},{meta:{changes:1}},{meta:{changes:1}},{meta:{changes:1}},{meta:{changes:1}}];} + }; + const request=new Request("https://paynex.example/api/v1/localproof/events",{ + method:"POST", + headers:{ + "content-type":"application/json", + "x-localproof-device":deviceId, + "x-localproof-timestamp":timestamp, + "x-localproof-nonce":nonce, + "x-localproof-signature":b64url + }, + body + }); + const result=await handleLocalProofRequest(request,{DB:db},"*",async()=>null,json); + assert.equal(result.status,202); + const data=await result.json(); + assert.equal(data.state,"OBSERVED_UNVERIFIED"); + assert.equal(data.bank_verified,false); + assert.equal(data.payment_marked_paid,false); + assert.equal(data.fulfilment_triggered,false); + assert.equal(statements.some(x=>/UPDATE\\s+(payment_attempts|orders|transactions)|INSERT\\s+INTO\\s+ledger/i.test(x.sql)),false); +}); + +test("LocalProof rejects an invalid device signature without writing an observation", async () => { + const pair=await crypto.subtle.generateKey({name:"ECDSA",namedCurve:"P-256"},true,["sign","verify"]); + const jwk=await crypto.subtle.exportKey("jwk",pair.publicKey); + const deviceId="123e4567-e89b-42d3-a456-426614174000"; + const body=JSON.stringify({event_uuid:"123e4567-e89b-42d3-a456-426614174002",source_package:"com.example.upi",parser_version:"1",amount_minor:100,currency:"INR",direction:"credit",observed_at:new Date().toISOString()}); + let writes=0; + const db={prepare(sql){return {bind(){return this;},async first(){return {id:deviceId,merchant_id:"merchant-A",public_key_jwk:JSON.stringify(jwk),status:"active"};}};},async batch(){writes++;return [];}}; + const request=new Request("https://paynex.example/api/v1/localproof/events",{method:"POST",headers:{ + "x-localproof-device":deviceId,"x-localproof-timestamp":String(Date.now()), + "x-localproof-nonce":"0123456789abcdef0123456789abcdef", + "x-localproof-signature":Buffer.alloc(64).toString("base64url") + },body}); + const result=await handleLocalProofRequest(request,{DB:db},"*",async()=>null,json); + assert.equal(result.status,401); + assert.equal(writes,0); +}); + +test("LocalProof event reads remain scoped to the authenticated merchant", async () => { + let boundMerchant=null; + const db={prepare(){return {bind(id,limit){boundMerchant=id;return this;},async all(){return {results:[]};}};}}; + const request=new Request("https://paynex.example/api/v1/localproof/events?limit=20"); + const result=await handleLocalProofRequest(request,{DB:db},"*",async()=> "merchant-A",json); + assert.equal(result.status,200); + assert.equal(boundMerchant,"merchant-A"); + assert.deepEqual((await result.json()).observations,[]); +});