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