diff --git a/.github/workflows/deploy-production.yml b/.github/workflows/deploy-production.yml
index 90247066..37089f91 100644
--- a/.github/workflows/deploy-production.yml
+++ b/.github/workflows/deploy-production.yml
@@ -198,6 +198,10 @@ jobs:
fi
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+ - name: Apply isolated sandbox API key migration
+ run: npx wrangler d1 execute paynex-db --remote --file=./migrations/0030_limited_sandbox_api_keys.sql
+ env:
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
- name: Verify production schema before Worker rollout
run: |
set -euo pipefail
@@ -205,6 +209,7 @@ jobs:
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='table' AND name='sandbox_api_keys'" --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
npx wrangler d1 execute paynex-db --remote --command "SELECT name FROM pragma_table_info('transactions') WHERE name IN ('base_amount_minor','unique_paise_offset_minor') ORDER BY name" --json
diff --git a/.github/workflows/deploy-v2-staging.yml b/.github/workflows/deploy-v2-staging.yml
index 696514e7..f476b396 100644
--- a/.github/workflows/deploy-v2-staging.yml
+++ b/.github/workflows/deploy-v2-staging.yml
@@ -2,7 +2,7 @@ name: Deploy PAYNEX V2 staging (integration branch)
on:
push:
- branches: [integration/paynex-v2-auth-safe-20261130, feat/direct-upi-merchant-confirmation-engine-20261130, feat/oxigendev-limited-merchant-access]
+ branches: [integration/paynex-v2-auth-safe-20261130, feat/direct-upi-merchant-confirmation-engine-20261130, feat/oxigendev-limited-merchant-access, feat/limited-sandbox-api-keys]
paths:
- "worker/**"
- "dashboard/**"
@@ -98,6 +98,10 @@ 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 isolated sandbox API key migration
+ run: npx wrangler d1 execute paynex-v2-staging --remote --file=./migrations/0030_limited_sandbox_api_keys.sql --env staging
+ env:
+ CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
- name: Deploy staging Worker only
run: npx wrangler deploy --env staging
env:
diff --git a/dashboard/index.html b/dashboard/index.html
index 39575eec..c8262395 100644
--- a/dashboard/index.html
+++ b/dashboard/index.html
@@ -109,6 +109,12 @@
Support email
Save draft
Sandbox payment simulator Choose a payment rail and a simulated outcome. These records are test-only and never change live transactions or orders.
UPI QR UPI Intent Card Net Banking Wallet Pending Simulate success Simulate failure Create test checkout
@@ -828,8 +834,24 @@
Payment mode onboarding · A / B / C
$("limitedStoreName").value=store.display_name||profile.merchant?.business_name||"";
$("limitedStoreDescription").value=store.description||"";
$("limitedStoreEmail").value=store.support_email||profile.merchant?.email||"";
+ await loadLimitedApiKeys();
await loadLimitedSandbox();
}
+ async function loadLimitedApiKeys(){
+ try{const data=await api("/api/v1/limited/api-keys");const rows=data.api_keys||[];
+ $("limitedApiKeyRows").innerHTML=rows.length?rows.map(k=>'
'+esc(k.label)+' Created '+esc(k.created_at)+' · Last used '+esc(k.last_used_at||"Never")+'
Revoke ').join(""):'
No active sandbox keys.
';
+ $("limitedApiKeyRows").querySelectorAll("[data-revoke-sandbox-key]").forEach(b=>b.addEventListener("click",async()=>{if(!confirm("Revoke this sandbox key? Integrations using it will stop working."))return;b.disabled=true;try{await api("/api/v1/limited/api-keys/"+encodeURIComponent(b.dataset.revokeSandboxKey)+"/revoke",{method:"POST"});await loadLimitedApiKeys();}catch(e){error("limitedApiKeyError",e.message);b.disabled=false;}}));
+ }catch(e){error("limitedApiKeyError",e.message)}
+ }
+ async function createLimitedSandboxKey(){
+ const button=$("createLimitedSandboxKey");button.disabled=true;$("limitedApiKeyError").textContent="";$("limitedSandboxKeyResult").classList.add("hidden");
+ try{const data=await api("/api/v1/limited/api-keys",{method:"POST",body:JSON.stringify({label:$("limitedApiKeyLabel").value.trim()||"LocalProof sandbox"})});
+ $("limitedSandboxKeyResult").innerHTML='
Copy this key now — it will not be shown again. '+esc(data.api_key)+'Copy key
Sandbox only · Live access: disabled ';
+ $("limitedSandboxKeyResult").classList.remove("hidden");
+ $("copyLimitedSandboxKey").addEventListener("click",async()=>{try{await navigator.clipboard.writeText(data.api_key);$("copyLimitedSandboxKey").textContent="Copied";}catch{$("copyLimitedSandboxKey").textContent="Select and copy";}});
+ $("limitedApiKeyLabel").value="";await loadLimitedApiKeys();
+ }catch(e){error("limitedApiKeyError",e.message)}finally{button.disabled=false;}
+ }
async function loadLimitedSandbox(){
try{const data=await api("/api/v1/limited/sandbox-checkouts");const rows=data.checkouts||[];
$("sandboxRows").innerHTML=rows.length?rows.map(x=>'
'+esc(x.merchant_reference)+' ₹'+(Number(x.amount_minor)/100).toFixed(2)+' · '+esc(x.payment_method)+' · '+esc(x.environment)+'
'+esc(x.simulated_outcome)+' ').join(""):'
No sandbox checkouts yet.
';
@@ -870,6 +892,7 @@
Payment mode onboarding · A / B / C
error("loginError","Could not verify your PAYNEX session. Please refresh and try again.");
}
}
+ $("createLimitedSandboxKey").addEventListener("click",createLimitedSandboxKey);
void loadAuthCapabilities();
$("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);
diff --git a/worker/migrations/0030_limited_sandbox_api_keys.sql b/worker/migrations/0030_limited_sandbox_api_keys.sql
new file mode 100644
index 00000000..fdea2c8a
--- /dev/null
+++ b/worker/migrations/0030_limited_sandbox_api_keys.sql
@@ -0,0 +1,12 @@
+-- Sandbox credentials are isolated from live api_keys and cannot authorise live collection.
+CREATE TABLE IF NOT EXISTS sandbox_api_keys (
+ id TEXT PRIMARY KEY,
+ merchant_id TEXT NOT NULL REFERENCES merchants(id) ON DELETE CASCADE,
+ key_hash TEXT NOT NULL UNIQUE,
+ label TEXT NOT NULL DEFAULT 'LocalProof sandbox',
+ last_used_at TEXT,
+ revoked_at TEXT,
+ created_at TEXT NOT NULL DEFAULT (datetime('now'))
+);
+CREATE INDEX IF NOT EXISTS idx_sandbox_api_keys_merchant_active
+ ON sandbox_api_keys(merchant_id, revoked_at, created_at DESC);
diff --git a/worker/src/index.js b/worker/src/index.js
index 3cb9eaad..a93a39bb 100644
--- a/worker/src/index.js
+++ b/worker/src/index.js
@@ -143,6 +143,16 @@ async function authenticateLimitedMerchant(request, env) {
return await env.DB.prepare("SELECT m.id,m.business_name,m.email,m.currency,m.status FROM merchants m JOIN merchant_limited_access a ON a.merchant_id=m.id WHERE lower(m.email)=? AND a.revoked_at IS NULL AND m.status<>'suspended' ORDER BY a.granted_at DESC LIMIT 1").bind(email).first();
} catch { return null; }
}
+async function authenticateSandboxApiKey(request, env) {
+ let key=request.headers.get("x-api-key")||request.headers.get("authorization")||"";
+ if(key.toLowerCase().startsWith("bearer ")) key=key.slice(7);
+ if(!key.startsWith("pn_test_")) return null;
+ const keyHash=await sha256(key);
+ const row=await env.DB.prepare("SELECT k.id AS key_id,k.merchant_id,m.business_name,m.email FROM sandbox_api_keys k JOIN merchants m ON m.id=k.merchant_id JOIN merchant_limited_access a ON a.merchant_id=m.id WHERE k.key_hash=? AND k.revoked_at IS NULL AND a.revoked_at IS NULL AND m.status<>'suspended'").bind(keyHash).first();
+ if(!row)return null;
+ await env.DB.prepare("UPDATE sandbox_api_keys SET last_used_at=datetime('now') WHERE id=?").bind(row.key_id).run();
+ return row;
+}
async function authenticate(request, env) {
let key = request.headers.get("x-api-key") || request.headers.get("authorization") || "";
if (key.toLowerCase().startsWith("bearer ")) key = key.slice(7);
@@ -743,9 +753,54 @@ export default {
).bind(applicant.email).all();
return json({ applications: rows.results || [] }, 200, origin);
}
+ if (url.pathname === "/api/v1/sandbox/me" && request.method === "GET") {
+ const sandboxMerchant=await authenticateSandboxApiKey(request,env);
+ if(!sandboxMerchant)return json({error:"A valid, active pn_test_ sandbox key is required"},401,origin);
+ return json({environment:"sandbox",merchant:{id:sandboxMerchant.merchant_id,business_name:sandboxMerchant.business_name},capabilities:{simulated_checkout:true,live_collection:false,live_transactions:false,ledger_posting:false}},200,origin);
+ }
+ if (url.pathname === "/api/v1/sandbox/checkouts" && request.method === "POST") {
+ const sandboxMerchant=await authenticateSandboxApiKey(request,env);
+ if(!sandboxMerchant)return json({error:"A valid, active pn_test_ sandbox key is required"},401,origin);
+ const sandboxBody=await request.json().catch(()=>({}));
+ const reference=String(sandboxBody.merchant_reference||"").trim().slice(0,100);
+ const amount=Number(sandboxBody.amount_minor);
+ const method=String(sandboxBody.payment_method||"");
+ const outcome=String(sandboxBody.simulated_outcome||"pending");
+ if(!reference||!Number.isSafeInteger(amount)||amount<1||amount>100000000||!["upi_qr","upi_intent","card","netbanking","wallet"].includes(method)||!["pending","success_simulated","failed_simulated"].includes(outcome))return json({error:"Invalid sandbox checkout payload"},400,origin);
+ const id=makeId();
+ try {
+ await env.DB.prepare("INSERT INTO merchant_sandbox_checkouts (id,merchant_id,merchant_reference,amount_minor,payment_method,simulated_outcome) VALUES (?,?,?,?,?,?)").bind(id,sandboxMerchant.merchant_id,reference,amount,method,outcome).run();
+ } catch { return json({error:"Sandbox reference already exists or could not be saved"},409,origin); }
+ await env.DB.prepare("INSERT INTO audit_logs (id,merchant_id,actor,action,resource_type,resource_id,metadata_json) VALUES (?,?,'sandbox_api','sandbox.checkout.created','sandbox_checkout',?,?)").bind(makeId(),sandboxMerchant.merchant_id,id,JSON.stringify({payment_method:method,outcome,environment:"sandbox"})).run();
+ return json({id,merchant_reference:reference,amount_minor:amount,currency:"INR",payment_method:method,simulated_outcome:outcome,environment:"sandbox",money_moved:false,live_transaction_created:false},201,origin);
+ }
if (url.pathname.startsWith("/api/v1/limited/")) {
const merchant = await authenticateLimitedMerchant(request,env);
if (!merchant) return json({error:"A verified account with an active limited-access grant is required"},401,origin);
+ if (request.method === "GET" && url.pathname === "/api/v1/limited/api-keys") {
+ const rows = await env.DB.prepare("SELECT id,label,last_used_at,created_at FROM sandbox_api_keys WHERE merchant_id=? AND revoked_at IS NULL ORDER BY created_at DESC LIMIT 25").bind(merchant.id).all();
+ return json({environment:"sandbox",api_keys:rows.results||[],prefix:"pn_test_",live_access:false},200,origin);
+ }
+ if (request.method === "POST" && url.pathname === "/api/v1/limited/api-keys") {
+ const keyBody=await request.json().catch(()=>({}));
+ const label=String(keyBody.label||"LocalProof sandbox").trim().slice(0,80) || "LocalProof sandbox";
+ const count=await env.DB.prepare("SELECT COUNT(*) AS total FROM sandbox_api_keys WHERE merchant_id=? AND revoked_at IS NULL").bind(merchant.id).first();
+ if(Number(count?.total||0)>=5) return json({error:"Maximum 5 active sandbox keys. Revoke an unused key first."},409,origin);
+ const bytes=crypto.getRandomValues(new Uint8Array(32));
+ const key="pn_test_"+btoa(String.fromCharCode(...bytes)).replaceAll("+","-").replaceAll("/","_").replaceAll("=","");
+ const id=makeId();
+ await env.DB.prepare("INSERT INTO sandbox_api_keys (id,merchant_id,key_hash,label) VALUES (?,?,?,?)").bind(id,merchant.id,await sha256(key),label).run();
+ await env.DB.prepare("INSERT INTO audit_logs (id,merchant_id,actor,action,resource_type,resource_id,metadata_json) VALUES (?,?,'merchant','sandbox.api_key.created','sandbox_api_key',?,?)").bind(makeId(),merchant.id,id,JSON.stringify({label,prefix:"pn_test_"})).run();
+ return json({id,api_key:key,prefix:"pn_test_",environment:"sandbox",shown_once:true,live_access:false},201,origin);
+ }
+ const sandboxKeyRevoke=url.pathname.match(new RegExp("^/api/v1/limited/api-keys/([A-Za-z0-9-]+)/revoke$"));
+ if (request.method === "POST" && sandboxKeyRevoke) {
+ const keyId=sandboxKeyRevoke[1];
+ const result=await env.DB.prepare("UPDATE sandbox_api_keys SET revoked_at=datetime('now') WHERE id=? AND merchant_id=? AND revoked_at IS NULL").bind(keyId,merchant.id).run();
+ if(!result.meta?.changes) return json({error:"Active sandbox API key not found"},404,origin);
+ await env.DB.prepare("INSERT INTO audit_logs (id,merchant_id,actor,action,resource_type,resource_id) VALUES (?,?,'merchant','sandbox.api_key.revoked','sandbox_api_key',?)").bind(makeId(),merchant.id,keyId).run();
+ return json({revoked:true,id:keyId},200,origin);
+ }
if (request.method === "GET" && url.pathname === "/api/v1/limited/profile") {
const workspace = await env.DB.prepare("SELECT display_name,description,support_email,updated_at FROM merchant_limited_workspace WHERE merchant_id=?").bind(merchant.id).first();
const sandbox = await env.DB.prepare("SELECT id,merchant_reference,amount_minor,currency,payment_method,simulated_outcome,created_at FROM merchant_sandbox_checkouts WHERE merchant_id=? ORDER BY created_at DESC LIMIT 20").bind(merchant.id).all();
diff --git a/worker/test/limited-sandbox-api-keys.test.js b/worker/test/limited-sandbox-api-keys.test.js
new file mode 100644
index 00000000..b4393b3f
--- /dev/null
+++ b/worker/test/limited-sandbox-api-keys.test.js
@@ -0,0 +1,39 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+
+const migration = await readFile(new URL("../migrations/0030_limited_sandbox_api_keys.sql", import.meta.url), "utf8");
+const worker = await readFile(new URL("../src/index.js", import.meta.url), "utf8");
+const dashboard = await readFile(new URL("../../dashboard/index.html", import.meta.url), "utf8");
+
+test("sandbox keys are stored separately and cannot be mistaken for live API keys", () => {
+ assert.match(migration, /CREATE TABLE IF NOT EXISTS sandbox_api_keys/);
+ assert.match(migration, /key_hash TEXT NOT NULL UNIQUE/);
+ assert.match(migration, /revoked_at TEXT/);
+ assert.doesNotMatch(migration, /INSERT\s+INTO\s+api_keys/i);
+});
+
+test("limited merchant API key routes require the limited-access gate", () => {
+ const gate = worker.indexOf('if (url.pathname.startsWith("/api/v1/limited/"))');
+ const route = worker.indexOf('url.pathname === "/api/v1/limited/api-keys"', gate);
+ assert.ok(gate >= 0 && route > gate);
+ assert.match(worker, /pn_test_/);
+ assert.match(worker, /sandbox_api_keys/);
+ assert.match(worker, /A verified account with an active limited-access grant is required/);
+ assert.ok(worker.includes("const keyBody=await request.json()"));
+});
+
+test("sandbox key auth remains confined to limited merchant routes", () => {
+ assert.match(worker, /FROM sandbox_api_keys k JOIN merchants m/);
+ assert.match(worker, /UPDATE sandbox_api_keys SET last_used_at/);
+ assert.ok(worker.includes("const sandboxBody=await request.json()"));
+ assert.match(worker, /\/api\/v1\/sandbox\/me/);
+ assert.match(worker, /\/api\/v1\/sandbox\/checkouts/);
+ assert.match(worker, /FROM api_keys k JOIN merchants m/);
+});
+
+test("limited workspace provides sandbox key create, revoke and one-time reveal UI", () => {
+ for (const marker of ["limitedApiKeys","createLimitedSandboxKey","limitedSandboxKeyResult","/api/v1/limited/api-keys"]) {
+ assert.ok(dashboard.includes(marker), "missing " + marker);
+ }
+});