From 9ffc3eeeceae900db47b197d4f6dfdce64348f7c Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:23:25 +0530 Subject: [PATCH 01/71] feat(localproof): add signed device observation API --- worker/src/localproof.js | 96 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 96 insertions(+) create mode 100644 worker/src/localproof.js diff --git a/worker/src/localproof.js b/worker/src/localproof.js new file mode 100644 index 00000000..c24f2333 --- /dev/null +++ b/worker/src/localproof.js @@ -0,0 +1,96 @@ +// 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 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"]; + 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(); + const utr=text(body.utr,80).replace(/\s+/g,"").toUpperCase(); + if(!UUID_RE.test(event)||!pkg||!parser||!Number.isFinite(Date.parse(observed))||(amount!==null&&(!Number.isSafeInteger(amount)||amount<1||amount>10000000000))||currency!=="INR"||(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 { + 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,match_state) VALUES (?,?,?,?,'android_notification_observation',?,?,?,?,?,?,?,'unmatched')").bind(crypto.randomUUID(),device.merchant_id,id,event,pkg,parser,amount,currency,observed,utrHash,payloadHash), + 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) VALUES (?,?,?,'observation_received',?,?)").bind(crypto.randomUUID(),device.merchant_id,id,event,JSON.stringify({amount_present:amount!==null,reference_present:Boolean(utrHash),source_package:pkg})) + ]); + } 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})), 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,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); +} From cde4b59baf0c6c509af94170c1eed2c2bcc46b40 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:23:32 +0530 Subject: [PATCH 02/71] feat(localproof): wire authenticated device routes --- worker/src/index.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/worker/src/index.js b/worker/src/index.js index 02b550e8..544135ad 100644 --- a/worker/src/index.js +++ b/worker/src/index.js @@ -10,6 +10,7 @@ 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, @@ -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 c3e7ed9f1ac3dbaec01b0b9a52d3749b096bd9c9 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:24:02 +0530 Subject: [PATCH 03/71] feat(localproof): add idempotent device observation schema --- .../0028_localproof_device_observation.sql | 52 +++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 worker/migrations/0028_localproof_device_observation.sql 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); From 6ce41b042e9bc685852a3f902e3720b3ffe74406 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:24:22 +0530 Subject: [PATCH 04/71] feat(localproof): wire schema and deployment checks --- worker/schema.sql | 55 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/worker/schema.sql b/worker/schema.sql index 686f4581..54612e34 100644 --- a/worker/schema.sql +++ b/worker/schema.sql @@ -334,3 +334,58 @@ 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), + 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); From 3c3ff5bc8a9499cf5a603723b59295fdae084c99 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:24:24 +0530 Subject: [PATCH 05/71] feat(localproof): wire schema and deployment checks --- .github/workflows/deploy-production.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-production.yml b/.github/workflows/deploy-production.yml index b09a6d94..047c8878 100644 --- a/.github/workflows/deploy-production.yml +++ b/.github/workflows/deploy-production.yml @@ -184,7 +184,7 @@ 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: Verify production schema before Worker rollout + - name: Apply LocalProof device observation schema (idempotent)\n run: npx wrangler d1 execute paynex-db --remote --file=./migrations/0028_localproof_device_observation.sql\n env:\n CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}\n - 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 From 0a4cde6aefe4fa22c2e97b059544bdc88a5582ff Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:24:26 +0530 Subject: [PATCH 06/71] feat(localproof): wire schema and deployment checks --- .github/workflows/deploy-worker.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/deploy-worker.yml b/.github/workflows/deploy-worker.yml index b244703c..6198fb68 100644 --- a/.github/workflows/deploy-worker.yml +++ b/.github/workflows/deploy-worker.yml @@ -94,7 +94,7 @@ 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: Verify merchant attestation staging schema + - name: Apply LocalProof device observation schema (idempotent)\n working-directory: worker\n run: npx wrangler d1 execute paynex-v2-staging --remote --file=./migrations/0028_localproof_device_observation.sql --env staging\n env:\n CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}\n - name: Verify merchant attestation staging schema working-directory: worker run: | set -euo pipefail From 1be7834d19b1f42d29756a3407c387835a2a7e77 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:24:28 +0530 Subject: [PATCH 07/71] feat(localproof): wire schema and deployment checks --- docs/LOCALPROOF-STATUS.md | 66 +++++++++++++++------------------------ 1 file changed, 26 insertions(+), 40 deletions(-) diff --git a/docs/LOCALPROOF-STATUS.md b/docs/LOCALPROOF-STATUS.md index 97bdb4b3..a2ae1bf0 100644 --- a/docs/LOCALPROOF-STATUS.md +++ b/docs/LOCALPROOF-STATUS.md @@ -1,52 +1,38 @@ # PAYNEX LocalProof — implementation status and safe rollout -**Status: specification only; no Android companion APK is currently included in this repository.** +**Backend implementation in review; Android companion app/APK is not yet implemented.** -This document prevents a device-notification prototype from being mistaken for a bank-verified payment integration. +## Implemented on feature branch -## What exists today +- Merchant-authenticated device enrollment stores a public-only P-256 JWK. The private key must remain on the Android device. +- Device events require ECDSA signatures over `timestamp.nonce.raw_request_body`, a five-minute clock window, per-device nonce uniqueness, event UUID uniqueness, and active-device status. +- Merchant-scoped device listing and revocation. +- Event ingestion accepts only parsed metadata (source package, parser version, amount, currency, observed timestamp, optional UTR); raw notification text is rejected. +- UTRs and full payloads are hashed before persistence. The event endpoint returns `OBSERVED_UNVERIFIED`, `bank_verified:false`, `payment_marked_paid:false`, and `fulfilment_triggered:false`. +- D1 migration `0028_localproof_device_observation.sql` is idempotent and adds indexes for merchant/status, observation chronology and nonce expiry. -- 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. +## Security and authority boundary -## LocalProof must not become a payment-verification authority +Android notification/SMS content is a device observation, not authenticated bank-to-server confirmation. Notifications may be delayed, missing, duplicated, modified or spoofed. LocalProof must never set a payment to paid, transition an order, post a verified ledger entry, activate a subscription or trigger fulfilment. -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. +The Android app must request notification-listener access only after clear disclosure and explicit user action. Parse the minimum fields locally; never upload full notification bodies, inbox history, contacts or unrelated app content. Keep device credentials out of the APK; use a hardware-backed Android Keystore key where supported and provide revoke/disconnect controls. -A future LocalProof client may be used only as a **reconciliation-assistance signal**: +## Not yet implemented / required before real-device rollout -- 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. +- Android project, notification-listener UI and Android Keystore P-256 key generation/signing. +- Pairing UI to call the merchant-authenticated enrollment API. +- Android event queue, retry/backoff and event delivery. +- Physical-device tests across supported UPI/bank notification formats and Android 16. +- CI debug APK build and private artifact distribution. +- End-to-end tests for cross-merchant isolation, replay, stale signatures, revoked devices, duplicate event IDs and proof that no payment/order/ledger/fulfilment state changes. +- Production migration and Worker deployment after PR review and explicit release approval. -## Required implementation sequence +## API contract (feature branch) -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. +- `POST /api/v1/localproof/devices` — merchant-authenticated public-key enrollment. +- `GET /api/v1/localproof/devices` — merchant's device list. +- `DELETE /api/v1/localproof/devices/{deviceId}` — revoke own device. +- `POST /api/v1/localproof/events` — signed device event; device-authenticated. +- `GET /api/v1/localproof/events` — merchant's observations. -## 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. - -## 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. +Do not describe LocalProof as a bank integration or payment verification gateway. Authoritative payment verification remains an approved provider's signed webhook or authenticated server-side status API. From 8b7e5e391105ae540f5a659b5aa0b583f4883300 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:24:40 +0530 Subject: [PATCH 08/71] test(localproof): cover route isolation and invalid payloads --- worker/test/localproof.test.js | 39 ++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 worker/test/localproof.test.js diff --git a/worker/test/localproof.test.js b/worker/test/localproof.test.js new file mode 100644 index 00000000..a42ac40a --- /dev/null +++ b/worker/test/localproof.test.js @@ -0,0 +1,39 @@ +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); +}); From 359a7df61ec85f8a04bb82c6b9abd0c7df3fe105 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:25:04 +0530 Subject: [PATCH 09/71] ci(localproof): validate module and schema during release --- .github/workflows/deploy-production.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/deploy-production.yml b/.github/workflows/deploy-production.yml index 047c8878..f818e271 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) @@ -187,7 +188,7 @@ jobs: - name: Apply LocalProof device observation schema (idempotent)\n run: npx wrangler d1 execute paynex-db --remote --file=./migrations/0028_localproof_device_observation.sql\n env:\n CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}\n - 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 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 From 6cb4f2c5289f640364b4569ad2be0849d97d60ba Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:25:06 +0530 Subject: [PATCH 10/71] ci(localproof): syntax check device routes in staging --- .github/workflows/deploy-worker.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/deploy-worker.yml b/.github/workflows/deploy-worker.yml index 6198fb68..dfa72655 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 From 1fb6fa47e08a78707c043acf5bd555e100133462 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:25:20 +0530 Subject: [PATCH 11/71] ci(localproof): run worker tests for LocalProof branch --- .github/workflows/worker-tests.yml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.github/workflows/worker-tests.yml b/.github/workflows/worker-tests.yml index 1332322a..b111c83b 100644 --- a/.github/workflows/worker-tests.yml +++ b/.github/workflows/worker-tests.yml @@ -2,7 +2,7 @@ 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] @@ -23,5 +23,6 @@ jobs: run: | node --check src/index.js node --check src/auth.js + node --check src/localproof.js - name: Run worker tests run: npm test From 72c48a9cadfddbab8fbe50ac54d58f861236d63e Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:26:20 +0530 Subject: [PATCH 12/71] fix(localproof): enforce active device at observation commit --- worker/src/localproof.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/worker/src/localproof.js b/worker/src/localproof.js index c24f2333..01b958ce 100644 --- a/worker/src/localproof.js +++ b/worker/src/localproof.js @@ -55,9 +55,9 @@ export async function handleLocalProofRequest(request,env,origin,authenticate,js 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,match_state) VALUES (?,?,?,?,'android_notification_observation',?,?,?,?,?,?,?,'unmatched')").bind(crypto.randomUUID(),device.merchant_id,id,event,pkg,parser,amount,currency,observed,utrHash,payloadHash), + 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,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,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) VALUES (?,?,?,'observation_received',?,?)").bind(crypto.randomUUID(),device.merchant_id,id,event,JSON.stringify({amount_present:amount!==null,reference_present:Boolean(utrHash),source_package:pkg})) + 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) ]); } catch { const duplicate=await env.DB.prepare("SELECT id FROM localproof_observations WHERE device_id=? AND event_uuid=?").bind(id,event).first(); From f66d4842ccf723fe1c34035f26dcfdb7f5acf08f Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:42:38 +0530 Subject: [PATCH 13/71] feat(localproof-android): add opt-in Keystore companion --- android/settings.gradle.kts | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 android/settings.gradle.kts 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") From 77a43e21ad00c22aa01123b517da6d6b7a3b31bf Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:42:40 +0530 Subject: [PATCH 14/71] feat(localproof-android): add opt-in Keystore companion --- android/build.gradle.kts | 4 ++++ 1 file changed, 4 insertions(+) create mode 100644 android/build.gradle.kts 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 +} From ac69fa18949e647e16288d966bd1d7139a521998 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:42:42 +0530 Subject: [PATCH 15/71] feat(localproof-android): add opt-in Keystore companion --- android/gradle.properties | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 android/gradle.properties 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 From 31bd9833cec15c9e752395c25fa87c76cf139ae7 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:42:44 +0530 Subject: [PATCH 16/71] feat(localproof-android): add opt-in Keystore companion --- android/app/build.gradle.kts | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) create mode 100644 android/app/build.gradle.kts 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" } +} From ac24ec225e5986feae6c6e40b6690b13bceccba6 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:42:46 +0530 Subject: [PATCH 17/71] feat(localproof-android): add opt-in Keystore companion --- android/app/src/main/AndroidManifest.xml | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 android/app/src/main/AndroidManifest.xml 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 @@ + + + + + + + + + + + From 443800d58624aac2b557ab696f7e2ff599c17282 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:42:48 +0530 Subject: [PATCH 18/71] feat(localproof-android): add opt-in Keystore companion --- .../com/paynex/localproof/DeviceCrypto.kt | 60 +++++++++++++++++++ 1 file changed, 60 insertions(+) create mode 100644 android/app/src/main/java/com/paynex/localproof/DeviceCrypto.kt 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..cc92c1b3 --- /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())) + } +} From 3d2753202696b36dace1f6fb2d3451833b8e0fdf Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:42:51 +0530 Subject: [PATCH 19/71] feat(localproof-android): add opt-in Keystore companion --- .../main/java/com/paynex/localproof/Api.kt | 55 +++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 android/app/src/main/java/com/paynex/localproof/Api.kt 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..a11996f5 --- /dev/null +++ b/android/app/src/main/java/com/paynex/localproof/Api.kt @@ -0,0 +1,55 @@ +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 { + 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) { + 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) + } +} From 36278638cbdd76dd1022cf18e4018925ac6f0c2f Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:42:53 +0530 Subject: [PATCH 20/71] feat(localproof-android): add opt-in Keystore companion --- .../com/paynex/localproof/MainActivity.kt | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 android/app/src/main/java/com/paynex/localproof/MainActivity.kt 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..cc25b010 --- /dev/null +++ b/android/app/src/main/java/com/paynex/localproof/MainActivity.kt @@ -0,0 +1,41 @@ +package com.paynex.localproof + +import android.app.Activity +import android.content.Intent +import android.os.Bundle +import android.provider.Settings +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 (stored on this device)",prefs.getString("api_key","")!!,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="No notification content is uploaded. Only parsed amount/reference metadata is sent."; textSize=14f } + root.addView(status) + 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 { startActivity(Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)) } }) + root.addView(Button(this).apply { text="Disconnect (revoke device)"; setOnClickListener { save(); Thread { try { 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() { getSharedPreferences("localproof",MODE_PRIVATE).edit().putString("base",base.text.toString().trim()).putString("api_key",key.text.toString()).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() +} From 02f63466e10baa6fbd7db1583b05beb36abb36ba Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:42:56 +0530 Subject: [PATCH 21/71] feat(localproof-android): add opt-in Keystore companion --- .../LocalProofNotificationListener.kt | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) create mode 100644 android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt 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..01199c72 --- /dev/null +++ b/android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt @@ -0,0 +1,39 @@ +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) + 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 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("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() + } +} From efe93fc62ee66c6c0196d5fe5e130146ef98646a Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:42:58 +0530 Subject: [PATCH 22/71] feat(localproof-android): add opt-in Keystore companion --- android/README.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 android/README.md 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. From f7865f2f1fc075602585bef4545e39fe9b8c6db7 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:43:35 +0530 Subject: [PATCH 23/71] fix(localproof): permit secure device API CORS headers --- worker/src/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/worker/src/index.js b/worker/src/index.js index 544135ad..bb3c5c9d 100644 --- a/worker/src/index.js +++ b/worker/src/index.js @@ -17,8 +17,8 @@ const json = (data, status = 200, origin = "*") => new Response(JSON.stringify(d 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" From 34f15610ec7b121700852ce34715b62d05869feb Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:43:50 +0530 Subject: [PATCH 24/71] security(localproof): encrypt saved API key with Android Keystore --- .../java/com/paynex/localproof/SecretStore.kt | 42 +++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 android/app/src/main/java/com/paynex/localproof/SecretStore.kt 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) { "" } + } +} From 4da0f8ab64b44d09154a7c11ca03edc02397815d Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:44:05 +0530 Subject: [PATCH 25/71] security(localproof): protect merchant API key and require HTTPS --- .../main/java/com/paynex/localproof/MainActivity.kt | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/android/app/src/main/java/com/paynex/localproof/MainActivity.kt b/android/app/src/main/java/com/paynex/localproof/MainActivity.kt index cc25b010..3853ddfa 100644 --- a/android/app/src/main/java/com/paynex/localproof/MainActivity.kt +++ b/android/app/src/main/java/com/paynex/localproof/MainActivity.kt @@ -24,7 +24,7 @@ class MainActivity : Activity() { 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 (stored on this device)",prefs.getString("api_key","")!!,true) + 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) } @@ -36,6 +36,15 @@ class MainActivity : Activity() { root.addView(Button(this).apply { text="Disconnect (revoke device)"; setOnClickListener { save(); Thread { try { 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() { getSharedPreferences("localproof",MODE_PRIVATE).edit().putString("base",base.text.toString().trim()).putString("api_key",key.text.toString()).putString("packages",packages.text.toString()).putString("device_id",device.text.toString().trim()).apply() } + private fun save() { + val worker=base.text.toString().trim() + require(worker.startsWith("https://",true)) { "Use an HTTPS PAYNEX Worker URL" } + 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() } From ce4a40f50cffbf72ef70dcf1ba036df2aa01dc6d Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:44:19 +0530 Subject: [PATCH 26/71] ci(localproof): build Android debug APK on pull requests --- .github/workflows/localproof-android.yml | 40 ++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 .github/workflows/localproof-android.yml diff --git a/.github/workflows/localproof-android.yml b/.github/workflows/localproof-android.yml new file mode 100644 index 00000000..a139fef9 --- /dev/null +++ b/.github/workflows/localproof-android.yml @@ -0,0 +1,40 @@ +name: PAYNEX LocalProof Android build + +on: + pull_request: + branches: [main] + paths: + - "android/**" + - ".github/workflows/localproof-android.yml" + push: + branches: [feat/localproof-secure-device-observation] + paths: + - "android/**" + - ".github/workflows/localproof-android.yml" + +permissions: + contents: read + +jobs: + android-debug-apk: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "17" + - uses: android-actions/setup-android@v3 + - name: Build 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 From 1313dbed4693fdef8796fefb0529fbc4f15f097b Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:44:24 +0530 Subject: [PATCH 27/71] ci(localproof): run regression tests on feature branch pushes From 14205ae6b6d1abb80336473681cf60d5f4f81e6e Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:44:35 +0530 Subject: [PATCH 28/71] ci(localproof): enable push validation for LocalProof branch From 513c79327afe2b355bfd291d8210dc27a674c49a Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:44:47 +0530 Subject: [PATCH 29/71] ci(localproof): enable feature branch push checks --- .github/workflows/worker-tests.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/worker-tests.yml b/.github/workflows/worker-tests.yml index b111c83b..d896d3a8 100644 --- a/.github/workflows/worker-tests.yml +++ b/.github/workflows/worker-tests.yml @@ -4,7 +4,7 @@ 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, 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: From 8107c9c17be1a7ecaf2172442c1433bc18b09be7 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:45:28 +0530 Subject: [PATCH 30/71] fix(ci): correct LocalProof migration workflow YAML --- .github/workflows/deploy-production.yml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/workflows/deploy-production.yml b/.github/workflows/deploy-production.yml index f818e271..3833d302 100644 --- a/.github/workflows/deploy-production.yml +++ b/.github/workflows/deploy-production.yml @@ -185,7 +185,11 @@ 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)\n run: npx wrangler d1 execute paynex-db --remote --file=./migrations/0028_localproof_device_observation.sql\n env:\n CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}\n - name: Verify production schema before Worker rollout + - 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: 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','localproof_devices','localproof_nonces','localproof_observations','localproof_audit_events') ORDER BY name" --json From 52e0936f8c9579398eba491cc11cb518d112b8f9 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:45:31 +0530 Subject: [PATCH 31/71] fix(ci): correct LocalProof migration workflow YAML --- .github/workflows/deploy-worker.yml | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/workflows/deploy-worker.yml b/.github/workflows/deploy-worker.yml index dfa72655..d4e8ed81 100644 --- a/.github/workflows/deploy-worker.yml +++ b/.github/workflows/deploy-worker.yml @@ -95,7 +95,12 @@ 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)\n working-directory: worker\n run: npx wrangler d1 execute paynex-v2-staging --remote --file=./migrations/0028_localproof_device_observation.sql --env staging\n env:\n CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}\n - name: Verify merchant attestation staging schema + - 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: Verify merchant attestation staging schema working-directory: worker run: | set -euo pipefail From 378dd1ad817e9efc5089e26163ba4bcb26ca0bc9 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:45:46 +0530 Subject: [PATCH 32/71] fix(localproof): allow CORS preflight for device revocation and signed events --- worker/src/index.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/worker/src/index.js b/worker/src/index.js index bb3c5c9d..199e54c8 100644 --- a/worker/src/index.js +++ b/worker/src/index.js @@ -561,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" } From fa537ae2ad0661133d36ce074420ced98a60cf4b Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:46:17 +0530 Subject: [PATCH 33/71] fix(localproof): validate package metadata and revocation race --- worker/src/localproof.js | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/worker/src/localproof.js b/worker/src/localproof.js index 01b958ce..b4d546f3 100644 --- a/worker/src/localproof.js +++ b/worker/src/localproof.js @@ -3,6 +3,7 @@ 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(""); @@ -49,16 +50,18 @@ export async function handleLocalProofRequest(request,env,origin,authenticate,js 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(); const utr=text(body.utr,80).replace(/\s+/g,"").toUpperCase(); - if(!UUID_RE.test(event)||!pkg||!parser||!Number.isFinite(Date.parse(observed))||(amount!==null&&(!Number.isSafeInteger(amount)||amount<1||amount>10000000000))||currency!=="INR"||(utr&&!/^[A-Z0-9]{6,80}$/.test(utr))) return respond({error:"Invalid observation fields"},400); + 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"||(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 { - await env.DB.batch([ + 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,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,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); From ec02a1559cf7a13911c7a6315d70562815647487 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:46:34 +0530 Subject: [PATCH 34/71] privacy(localproof): require explicit notification observation consent --- .../java/com/paynex/localproof/MainActivity.kt | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/android/app/src/main/java/com/paynex/localproof/MainActivity.kt b/android/app/src/main/java/com/paynex/localproof/MainActivity.kt index 3853ddfa..661b2ade 100644 --- a/android/app/src/main/java/com/paynex/localproof/MainActivity.kt +++ b/android/app/src/main/java/com/paynex/localproof/MainActivity.kt @@ -4,6 +4,7 @@ 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 @@ -28,11 +29,20 @@ class MainActivity : Activity() { 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="No notification content is uploaded. Only parsed amount/reference metadata is sent."; textSize=14f } + 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 { startActivity(Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)) } }) + 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 { save(); Thread { try { 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) } From 7be7e361cb60d122736df37adc062cf90f8a3d01 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:46:43 +0530 Subject: [PATCH 35/71] privacy(localproof): enforce consent before notification parsing --- .../java/com/paynex/localproof/LocalProofNotificationListener.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt b/android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt index 01199c72..7456fc15 100644 --- a/android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt +++ b/android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt @@ -12,6 +12,7 @@ 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() From a40f0c40628bafc6d2bf44105f3471e5ff624203 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:46:51 +0530 Subject: [PATCH 36/71] privacy(localproof): stop local capture before device revocation --- android/app/src/main/java/com/paynex/localproof/MainActivity.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/app/src/main/java/com/paynex/localproof/MainActivity.kt b/android/app/src/main/java/com/paynex/localproof/MainActivity.kt index 661b2ade..a8399637 100644 --- a/android/app/src/main/java/com/paynex/localproof/MainActivity.kt +++ b/android/app/src/main/java/com/paynex/localproof/MainActivity.kt @@ -43,7 +43,7 @@ class MainActivity : Activity() { prefs.edit().putBoolean("consent",true).apply() startActivity(Intent(Settings.ACTION_NOTIFICATION_LISTENER_SETTINGS)) } }) - root.addView(Button(this).apply { text="Disconnect (revoke device)"; setOnClickListener { save(); Thread { try { 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() } }) + root.addView(Button(this).apply { text="Disconnect (revoke device)"; setOnClickListener { prefs.edit().putBoolean("consent",false).apply(); save(); Thread { try { 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() { From 4a697df3bdd483a43ca1bb4385a52a14f521cf32 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:47:54 +0530 Subject: [PATCH 37/71] feat(localproof): add merchant device and observation panel --- dashboard/index.html | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/dashboard/index.html b/dashboard/index.html index d67e74b8..27d6b00a 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))+'
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); From 2384101cd25c41fe8f905063c4dd21c8a548ca8e Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:48:18 +0530 Subject: [PATCH 38/71] docs(localproof): update implementation and release status --- docs/LOCALPROOF-STATUS.md | 61 ++++++++++++++++++++++----------------- 1 file changed, 35 insertions(+), 26 deletions(-) diff --git a/docs/LOCALPROOF-STATUS.md b/docs/LOCALPROOF-STATUS.md index a2ae1bf0..5f4ade11 100644 --- a/docs/LOCALPROOF-STATUS.md +++ b/docs/LOCALPROOF-STATUS.md @@ -1,38 +1,47 @@ # PAYNEX LocalProof — implementation status and safe rollout -**Backend implementation in review; Android companion app/APK is not yet implemented.** +**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.** -## Implemented on feature branch +## Implemented on the feature branch -- Merchant-authenticated device enrollment stores a public-only P-256 JWK. The private key must remain on the Android device. -- Device events require ECDSA signatures over `timestamp.nonce.raw_request_body`, a five-minute clock window, per-device nonce uniqueness, event UUID uniqueness, and active-device status. -- Merchant-scoped device listing and revocation. -- Event ingestion accepts only parsed metadata (source package, parser version, amount, currency, observed timestamp, optional UTR); raw notification text is rejected. -- UTRs and full payloads are hashed before persistence. The event endpoint returns `OBSERVED_UNVERIFIED`, `bank_verified:false`, `payment_marked_paid:false`, and `fulfilment_triggered:false`. -- D1 migration `0028_localproof_device_observation.sql` is idempotent and adds indexes for merchant/status, observation chronology and nonce expiry. +- 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, 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. -## Security and authority boundary +## Trust and payment authority boundary -Android notification/SMS content is a device observation, not authenticated bank-to-server confirmation. Notifications may be delayed, missing, duplicated, modified or spoofed. LocalProof must never set a payment to paid, transition an order, post a verified ledger entry, activate a subscription or trigger fulfilment. +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. -The Android app must request notification-listener access only after clear disclosure and explicit user action. Parse the minimum fields locally; never upload full notification bodies, inbox history, contacts or unrelated app content. Keep device credentials out of the APK; use a hardware-backed Android Keystore key where supported and provide revoke/disconnect controls. +## Android privacy and operation -## Not yet implemented / required before real-device rollout +- 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. -- Android project, notification-listener UI and Android Keystore P-256 key generation/signing. -- Pairing UI to call the merchant-authenticated enrollment API. -- Android event queue, retry/backoff and event delivery. -- Physical-device tests across supported UPI/bank notification formats and Android 16. -- CI debug APK build and private artifact distribution. -- End-to-end tests for cross-merchant isolation, replay, stale signatures, revoked devices, duplicate event IDs and proof that no payment/order/ledger/fulfilment state changes. -- Production migration and Worker deployment after PR review and explicit release approval. +## Remaining release gates -## API contract (feature branch) +- [ ] 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. -- `POST /api/v1/localproof/devices` — merchant-authenticated public-key enrollment. -- `GET /api/v1/localproof/devices` — merchant's device list. -- `DELETE /api/v1/localproof/devices/{deviceId}` — revoke own device. -- `POST /api/v1/localproof/events` — signed device event; device-authenticated. -- `GET /api/v1/localproof/events` — merchant's observations. +## API -Do not describe LocalProof as a bank integration or payment verification gateway. Authoritative payment verification remains an approved provider's signed webhook or authenticated server-side status API. +- `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 + +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. From dacb60a24870b78714c136858b5ecf9426537e75 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:48:20 +0530 Subject: [PATCH 39/71] docs(localproof): update README implementation status --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 From 96f9f00bad335a5a1cfa456e1799bff63919a29d Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:48:47 +0530 Subject: [PATCH 40/71] test(localproof): prove signed observations cannot mutate payment state --- worker/test/localproof.test.js | 43 ++++++++++++++++++++++++++++++++++ 1 file changed, 43 insertions(+) diff --git a/worker/test/localproof.test.js b/worker/test/localproof.test.js index a42ac40a..d73d445c 100644 --- a/worker/test/localproof.test.js +++ b/worker/test/localproof.test.js @@ -37,3 +37,46 @@ test("LocalProof merchant routes require an authenticated active merchant", asyn 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", + 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); +}); From 6a58227fbe2c893ee4f0832c06a86554802d10bb Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:49:10 +0530 Subject: [PATCH 41/71] fix(android): validate HTTPS before network actions --- .../app/src/main/java/com/paynex/localproof/MainActivity.kt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/android/app/src/main/java/com/paynex/localproof/MainActivity.kt b/android/app/src/main/java/com/paynex/localproof/MainActivity.kt index a8399637..d2f51197 100644 --- a/android/app/src/main/java/com/paynex/localproof/MainActivity.kt +++ b/android/app/src/main/java/com/paynex/localproof/MainActivity.kt @@ -43,12 +43,11 @@ class MainActivity : Activity() { 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 { 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() } }) + 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() - require(worker.startsWith("https://",true)) { "Use an HTTPS PAYNEX Worker URL" } getSharedPreferences("localproof",MODE_PRIVATE).edit() .putString("base",worker) .putString("api_key_enc",SecretStore.encrypt(key.text.toString())) From 1c6a22e660eae18e0a03f4db2e8cccc6f51c64b8 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:49:12 +0530 Subject: [PATCH 42/71] security(android): enforce HTTPS for LocalProof API requests --- android/app/src/main/java/com/paynex/localproof/Api.kt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/android/app/src/main/java/com/paynex/localproof/Api.kt b/android/app/src/main/java/com/paynex/localproof/Api.kt index a11996f5..2c92edd1 100644 --- a/android/app/src/main/java/com/paynex/localproof/Api.kt +++ b/android/app/src/main/java/com/paynex/localproof/Api.kt @@ -7,6 +7,7 @@ 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 @@ -27,6 +28,7 @@ object Api { 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() From dc5e0c5b74e67afe806d9f9ceb8e8cb9a1e4e9df Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:49:57 +0530 Subject: [PATCH 43/71] fix(ci): install supported Android SDK packages directly --- .github/workflows/localproof-android.yml | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/.github/workflows/localproof-android.yml b/.github/workflows/localproof-android.yml index a139fef9..141abd1b 100644 --- a/.github/workflows/localproof-android.yml +++ b/.github/workflows/localproof-android.yml @@ -24,7 +24,10 @@ jobs: with: distribution: temurin java-version: "17" - - uses: android-actions/setup-android@v3 + - name: Install Android SDK packages + run: | + yes | sdkmanager --licenses >/dev/null + sdkmanager "platforms;android-35" "build-tools;35.0.0" "platform-tools" - name: Build debug APK uses: gradle/gradle-build-action@v3 with: From 2f540accee880e0940f1177eeb355010a0b8f066 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:50:17 +0530 Subject: [PATCH 44/71] ci(localproof): add Android APK build to PR regression workflow --- .github/workflows/worker-tests.yml | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/.github/workflows/worker-tests.yml b/.github/workflows/worker-tests.yml index d896d3a8..8a27ff60 100644 --- a/.github/workflows/worker-tests.yml +++ b/.github/workflows/worker-tests.yml @@ -26,3 +26,29 @@ jobs: node --check src/localproof.js - 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: | + 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 From ee1fc54107d7f4ed9f0db1efed7aae41d2e8d639 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:50:54 +0530 Subject: [PATCH 45/71] feat(localproof): record parsed credit or debit direction --- worker/migrations/0029_localproof_observation_direction.sql | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 worker/migrations/0029_localproof_observation_direction.sql 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')); From 51cfc88dda7d01235078ed05e6129ae459398601 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:51:06 +0530 Subject: [PATCH 46/71] feat(localproof): retain parsed transaction direction as untrusted metadata --- worker/src/localproof.js | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/worker/src/localproof.js b/worker/src/localproof.js index b4d546f3..415e0242 100644 --- a/worker/src/localproof.js +++ b/worker/src/localproof.js @@ -45,19 +45,19 @@ export async function handleLocalProofRequest(request,env,origin,authenticate,js 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"]; + 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(); + 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"||(utr&&!/^[A-Z0-9]{6,80}$/.test(utr))) return respond({error:"Invalid observation fields"},400); + 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,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,id), + 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) ]); @@ -92,7 +92,7 @@ export async function handleLocalProofRequest(request,env,origin,authenticate,js } 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,observed_at,utr_hash,match_state,received_at FROM localproof_observations WHERE merchant_id=? ORDER BY received_at DESC LIMIT ?").bind(merchantId,limit).all(); + 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); From ab4b84f7a48cebda22c565fcf5aab2435354b7ca Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:51:28 +0530 Subject: [PATCH 47/71] feat(localproof): include direction in fresh LocalProof schema --- worker/migrations/0028_localproof_device_observation.sql | 1 + 1 file changed, 1 insertion(+) diff --git a/worker/migrations/0028_localproof_device_observation.sql b/worker/migrations/0028_localproof_device_observation.sql index 902f6a00..6900d709 100644 --- a/worker/migrations/0028_localproof_device_observation.sql +++ b/worker/migrations/0028_localproof_device_observation.sql @@ -29,6 +29,7 @@ CREATE TABLE IF NOT EXISTS localproof_observations ( 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, From b182f003115f946e1edd3ac36534066c8f074a27 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:51:30 +0530 Subject: [PATCH 48/71] chore(db): align LocalProof schema snapshot with direction field --- worker/schema.sql | 3 +++ 1 file changed, 3 insertions(+) diff --git a/worker/schema.sql b/worker/schema.sql index 54612e34..86ca5f4f 100644 --- a/worker/schema.sql +++ b/worker/schema.sql @@ -368,6 +368,7 @@ CREATE TABLE IF NOT EXISTS localproof_observations ( 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, @@ -389,3 +390,5 @@ CREATE TABLE IF NOT EXISTS localproof_audit_events ( 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. From 365ef591ef510e66e3d16da41dd67ad16e86bc4d Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:51:33 +0530 Subject: [PATCH 49/71] ci(db): apply LocalProof direction migration in production release --- .github/workflows/deploy-production.yml | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.github/workflows/deploy-production.yml b/.github/workflows/deploy-production.yml index 3833d302..df5350c1 100644 --- a/.github/workflows/deploy-production.yml +++ b/.github/workflows/deploy-production.yml @@ -189,6 +189,10 @@ jobs: 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 + run: npx wrangler d1 execute paynex-db --remote --file=./migrations/0029_localproof_observation_direction.sql + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - name: Verify production schema before Worker rollout run: | set -euo pipefail From 9f0ba432a11f2be26db219617ec5986237994699 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:51:35 +0530 Subject: [PATCH 50/71] ci(db): apply LocalProof direction migration in staging --- .github/workflows/deploy-worker.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/deploy-worker.yml b/.github/workflows/deploy-worker.yml index d4e8ed81..6d504352 100644 --- a/.github/workflows/deploy-worker.yml +++ b/.github/workflows/deploy-worker.yml @@ -100,6 +100,11 @@ jobs: 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 + working-directory: worker + run: npx wrangler d1 execute paynex-v2-staging --remote --file=./migrations/0029_localproof_observation_direction.sql --env staging + env: + CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }} - name: Verify merchant attestation staging schema working-directory: worker run: | From 1ba24e686187cd1dc528892145f495ec6eaee5b3 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:51:48 +0530 Subject: [PATCH 51/71] feat(android): label notification observation direction --- .../com/paynex/localproof/LocalProofNotificationListener.kt | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt b/android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt index 7456fc15..fdfccc87 100644 --- a/android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt +++ b/android/app/src/main/java/com/paynex/localproof/LocalProofNotificationListener.kt @@ -28,11 +28,14 @@ class LocalProofNotificationListener : NotificationListenerService() { 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("observed_at",observed) + .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() From f1f2019ec80c290c7ee490ef13ab2fe1fb311673 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:51:50 +0530 Subject: [PATCH 52/71] feat(localproof): show parsed direction in merchant observations --- dashboard/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dashboard/index.html b/dashboard/index.html index 27d6b00a..d9cafd63 100644 --- a/dashboard/index.html +++ b/dashboard/index.html @@ -399,7 +399,7 @@

Payment mode onboarding · A / B / C

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))+'
OBSERVED · UNVERIFIED
').join(""):'
No notification observations received yet.
'; + $("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)} } From 8377f9b39aec56379714a858feb2edd3ca037f7b Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:51:53 +0530 Subject: [PATCH 53/71] test(localproof): include direction in signed observation contract --- worker/test/localproof.test.js | 1 + 1 file changed, 1 insertion(+) diff --git a/worker/test/localproof.test.js b/worker/test/localproof.test.js index d73d445c..0d5087cd 100644 --- a/worker/test/localproof.test.js +++ b/worker/test/localproof.test.js @@ -48,6 +48,7 @@ test("valid signed LocalProof event is observation-only and cannot change paymen parser_version:"android-0.1.0", amount_minor:12345, currency:"INR", + direction:"credit", observed_at:new Date().toISOString(), utr:"ABCD12345678" }); From 9d0de9ebaf620f0ba03cd2fb8c55206a04752354 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:52:18 +0530 Subject: [PATCH 54/71] fix(ci): resolve Android sdkmanager from installed SDK root --- .github/workflows/worker-tests.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/worker-tests.yml b/.github/workflows/worker-tests.yml index 8a27ff60..f512415f 100644 --- a/.github/workflows/worker-tests.yml +++ b/.github/workflows/worker-tests.yml @@ -37,8 +37,11 @@ jobs: java-version: "17" - name: Install Android SDK packages run: | - yes | sdkmanager --licenses >/dev/null - sdkmanager "platforms;android-35" "build-tools;35.0.0" "platform-tools" + 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: From edbaf0d70dab6eb1b063287b81377be89bf01559 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:52:49 +0530 Subject: [PATCH 55/71] fix(ci): resolve SDK manager in standalone Android workflow From 4713fcfc256f62fb742e458c0a2ccb7765c7e463 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:52:59 +0530 Subject: [PATCH 56/71] fix(ci): resolve Android SDK manager from runner installation --- .github/workflows/localproof-android.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/localproof-android.yml b/.github/workflows/localproof-android.yml index 141abd1b..14bf4194 100644 --- a/.github/workflows/localproof-android.yml +++ b/.github/workflows/localproof-android.yml @@ -26,8 +26,11 @@ jobs: java-version: "17" - name: Install Android SDK packages run: | - yes | sdkmanager --licenses >/dev/null - sdkmanager "platforms;android-35" "build-tools;35.0.0" "platform-tools" + 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 debug APK uses: gradle/gradle-build-action@v3 with: From cc8d18630c7d8a7940e44221078a05f8fc539bdc Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:53:34 +0530 Subject: [PATCH 57/71] fix(dashboard): include LocalProof in merchant navigation tracking --- dashboard/index.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dashboard/index.html b/dashboard/index.html index d9cafd63..39575eec 100644 --- a/dashboard/index.html +++ b/dashboard/index.html @@ -961,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))} })(); From 26321e819dca4c46aed4a4e835d9d8d1fbfb8c77 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:54:30 +0530 Subject: [PATCH 58/71] ci(localproof): use shared worker PR workflow for APK build --- .github/workflows/localproof-android.yml | 46 ------------------------ 1 file changed, 46 deletions(-) delete mode 100644 .github/workflows/localproof-android.yml diff --git a/.github/workflows/localproof-android.yml b/.github/workflows/localproof-android.yml deleted file mode 100644 index 14bf4194..00000000 --- a/.github/workflows/localproof-android.yml +++ /dev/null @@ -1,46 +0,0 @@ -name: PAYNEX LocalProof Android build - -on: - pull_request: - branches: [main] - paths: - - "android/**" - - ".github/workflows/localproof-android.yml" - push: - branches: [feat/localproof-secure-device-observation] - paths: - - "android/**" - - ".github/workflows/localproof-android.yml" - -permissions: - contents: read - -jobs: - 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 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 From d87886fcf249052093ff9c33312e76219dbb05a3 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:54:56 +0530 Subject: [PATCH 59/71] fix(android): clarify DER signature length bitmask --- android/app/src/main/java/com/paynex/localproof/DeviceCrypto.kt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/app/src/main/java/com/paynex/localproof/DeviceCrypto.kt b/android/app/src/main/java/com/paynex/localproof/DeviceCrypto.kt index cc92c1b3..1a0e1dca 100644 --- a/android/app/src/main/java/com/paynex/localproof/DeviceCrypto.kt +++ b/android/app/src/main/java/com/paynex/localproof/DeviceCrypto.kt @@ -38,7 +38,7 @@ object DeviceCrypto { 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) } } + 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) From 8dc702945f2eea2d151492a275cba516f0ed2379 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:55:25 +0530 Subject: [PATCH 60/71] ci(pages): align LocalProof documentation validation --- .github/workflows/deploy-pages.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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: From 4886b5446ad694691c15718c19fbd860de8a2160 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:56:28 +0530 Subject: [PATCH 61/71] docs(localproof): document direction metadata and offline queue limitation --- docs/LOCALPROOF-STATUS.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/LOCALPROOF-STATUS.md b/docs/LOCALPROOF-STATUS.md index 5f4ade11..3b7b3ec5 100644 --- a/docs/LOCALPROOF-STATUS.md +++ b/docs/LOCALPROOF-STATUS.md @@ -7,7 +7,7 @@ - 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, UTR hash and canonical payload hash. +- 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. @@ -25,6 +25,7 @@ Every device observation is returned as `OBSERVED_UNVERIFIED`. It is not bank co - 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. ## Remaining release gates From 186f7ab6b749b925ce3e4191c923299fd79eef1c Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:56:39 +0530 Subject: [PATCH 62/71] ci(db): verify LocalProof direction schema before production Worker rollout --- .github/workflows/deploy-production.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/deploy-production.yml b/.github/workflows/deploy-production.yml index df5350c1..6d2953f2 100644 --- a/.github/workflows/deploy-production.yml +++ b/.github/workflows/deploy-production.yml @@ -198,6 +198,7 @@ jobs: 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','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 From a89de13f3c54801519ff0e087e729b8c174c88a6 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:56:41 +0530 Subject: [PATCH 63/71] ci(db): verify LocalProof direction schema in staging From dedf6cc718c0970826303758c0dfe3ea89c56e8b Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:57:50 +0530 Subject: [PATCH 64/71] test(localproof): cover forged signatures and merchant isolation --- worker/test/localproof.test.js | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/worker/test/localproof.test.js b/worker/test/localproof.test.js index 0d5087cd..feb576c6 100644 --- a/worker/test/localproof.test.js +++ b/worker/test/localproof.test.js @@ -81,3 +81,30 @@ test("valid signed LocalProof event is observation-only and cannot change paymen 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,[]); +}); From 9a6a7d5090fc9ad13282ce9482b82e71a0c32de3 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:58:38 +0530 Subject: [PATCH 65/71] ci(db): validate LocalProof D1 migrations in worker PR checks --- .github/workflows/worker-tests.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/.github/workflows/worker-tests.yml b/.github/workflows/worker-tests.yml index f512415f..0d0fd9ac 100644 --- a/.github/workflows/worker-tests.yml +++ b/.github/workflows/worker-tests.yml @@ -24,6 +24,11 @@ jobs: 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 From 8eb37be49f41cc92eb81bc671d832954ab986514 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 09:59:40 +0530 Subject: [PATCH 66/71] fix(db): keep direction addition isolated in migration 0029 --- worker/migrations/0028_localproof_device_observation.sql | 1 - 1 file changed, 1 deletion(-) diff --git a/worker/migrations/0028_localproof_device_observation.sql b/worker/migrations/0028_localproof_device_observation.sql index 6900d709..902f6a00 100644 --- a/worker/migrations/0028_localproof_device_observation.sql +++ b/worker/migrations/0028_localproof_device_observation.sql @@ -29,7 +29,6 @@ CREATE TABLE IF NOT EXISTS localproof_observations ( 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, From a1f0d30f8f101c6d2bfce2e0c04a727727458c6e Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 10:01:11 +0530 Subject: [PATCH 67/71] fix(release): make LocalProof direction migration rerun-safe --- .github/workflows/deploy-production.yml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy-production.yml b/.github/workflows/deploy-production.yml index 6d2953f2..90247066 100644 --- a/.github/workflows/deploy-production.yml +++ b/.github/workflows/deploy-production.yml @@ -189,8 +189,13 @@ jobs: 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 - run: npx wrangler d1 execute paynex-db --remote --file=./migrations/0029_localproof_observation_direction.sql + - 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 From cbe054b922e2a20cfcaa41dcc6cea08abf278286 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 10:01:13 +0530 Subject: [PATCH 68/71] fix(staging): make LocalProof direction migration rerun-safe --- .github/workflows/deploy-worker.yml | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/.github/workflows/deploy-worker.yml b/.github/workflows/deploy-worker.yml index 6d504352..930ee0ec 100644 --- a/.github/workflows/deploy-worker.yml +++ b/.github/workflows/deploy-worker.yml @@ -100,9 +100,14 @@ jobs: 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 + - name: Apply LocalProof observation direction migration (skip if already present) working-directory: worker - run: npx wrangler d1 execute paynex-v2-staging --remote --file=./migrations/0029_localproof_observation_direction.sql --env staging + 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 From 4d88f2082a1dc60f53164e60ab4d2151afb4133c Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 10:01:50 +0530 Subject: [PATCH 69/71] fix(localproof): support safe same-merchant device re-enrollment --- worker/src/localproof.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/worker/src/localproof.js b/worker/src/localproof.js index 415e0242..21e54ae1 100644 --- a/worker/src/localproof.js +++ b/worker/src/localproof.js @@ -73,7 +73,22 @@ export async function handleLocalProofRequest(request,env,origin,authenticate,js 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})), id=crypto.randomUUID(); + 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"})) From 512c53c02b3aefb5c9fe44a83fd70638068f5fe8 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 10:03:05 +0530 Subject: [PATCH 70/71] fix(ci): validate fresh LocalProof schema without reapplying additive migration --- .github/workflows/worker-tests.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/worker-tests.yml b/.github/workflows/worker-tests.yml index 0d0fd9ac..993defbd 100644 --- a/.github/workflows/worker-tests.yml +++ b/.github/workflows/worker-tests.yml @@ -27,7 +27,6 @@ jobs: - 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 From b09ab154f43ceedebd6ccdaefd63542d675e0971 Mon Sep 17 00:00:00 2001 From: PDFly-source Date: Tue, 1 Dec 2026 10:43:32 +0530 Subject: [PATCH 71/71] fix(ci): apply additive LocalProof direction migration in local schema validation --- .github/workflows/worker-tests.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/worker-tests.yml b/.github/workflows/worker-tests.yml index 993defbd..0d0fd9ac 100644 --- a/.github/workflows/worker-tests.yml +++ b/.github/workflows/worker-tests.yml @@ -27,6 +27,7 @@ jobs: - 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