Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .github/workflows/deploy-production.yml
Original file line number Diff line number Diff line change
Expand Up @@ -198,13 +198,18 @@ 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
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='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
Expand Down
6 changes: 5 additions & 1 deletion .github/workflows/deploy-v2-staging.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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/**"
Expand Down Expand Up @@ -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:
Expand Down
23 changes: 23 additions & 0 deletions dashboard/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,12 @@
<label for="limitedStoreEmail">Support email</label><input class="field" id="limitedStoreEmail" type="email" maxlength="254" style="width:100%">
<button class="btn primary" id="saveLimitedStore" type="button">Save draft</button><div class="error" id="limitedStoreError"></div>
</div>
<div class="card section" id="limitedApiKeys">
<h3>Sandbox API keys</h3><p>Create a <code>pn_test_</code> key for LocalProof and development integrations. It is isolated from live credentials and cannot initiate live collection.</p>
<div class="filters"><input class="field" id="limitedApiKeyLabel" maxlength="80" placeholder="Key label (e.g. LocalProof Android)"><button class="btn primary" id="createLimitedSandboxKey" type="button">Generate sandbox key</button></div>
<div class="notice">The full key is shown only once. Copy it now and store it securely. Never paste it into public code or screenshots.</div>
<div id="limitedSandboxKeyResult" class="hidden"></div><div class="error" id="limitedApiKeyError"></div><div id="limitedApiKeyRows" style="margin-top:12px"></div>
</div>
<div class="card section"><h3>Sandbox payment simulator</h3><p>Choose a payment rail and a simulated outcome. These records are test-only and never change live transactions or orders.</p>
<div class="filters"><input class="field" id="sandboxReference" placeholder="Test reference e.g. OXI-TEST-001"><input class="field" id="sandboxAmount" type="number" min="0.01" step="0.01" placeholder="Amount (₹)"></div>
<div class="filters" style="margin-top:9px"><select class="field" id="sandboxMethod"><option value="upi_qr">UPI QR</option><option value="upi_intent">UPI Intent</option><option value="card">Card</option><option value="netbanking">Net Banking</option><option value="wallet">Wallet</option></select><select class="field" id="sandboxOutcome"><option value="pending">Pending</option><option value="success_simulated">Simulate success</option><option value="failed_simulated">Simulate failure</option></select><button class="btn primary" id="createSandboxCheckout" type="button">Create test checkout</button></div>
Expand Down Expand Up @@ -828,8 +834,24 @@ <h3 style="margin-top:0">Payment mode onboarding · A / B / C</h3>
$("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=>'<div class="currency-row"><div><strong>'+esc(k.label)+'</strong><br><small class="muted">Created '+esc(k.created_at)+' · Last used '+esc(k.last_used_at||"Never")+'</small></div><button class="btn" data-revoke-sandbox-key="'+esc(k.id)+'">Revoke</button></div>').join(""):'<div class="empty">No active sandbox keys.</div>';
$("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='<strong>Copy this key now — it will not be shown again.</strong><div class="currency-row"><code style="overflow-wrap:anywhere">'+esc(data.api_key)+'</code><button class="btn" id="copyLimitedSandboxKey" type="button">Copy key</button></div><small class="muted">Sandbox only · Live access: disabled</small>';
$("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=>'<div class="currency-row"><div><strong>'+esc(x.merchant_reference)+'</strong><br><small class="muted">₹'+(Number(x.amount_minor)/100).toFixed(2)+' · '+esc(x.payment_method)+' · '+esc(x.environment)+'</small></div><span class="status pending">'+esc(x.simulated_outcome)+'</span></div>').join(""):'<div class="empty">No sandbox checkouts yet.</div>';
Expand Down Expand Up @@ -870,6 +892,7 @@ <h3 style="margin-top:0">Payment mode onboarding · A / B / C</h3>
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);
Expand Down
12 changes: 12 additions & 0 deletions worker/migrations/0030_limited_sandbox_api_keys.sql
Original file line number Diff line number Diff line change
@@ -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);
55 changes: 55 additions & 0 deletions worker/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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();
Expand Down
39 changes: 39 additions & 0 deletions worker/test/limited-sandbox-api-keys.test.js
Original file line number Diff line number Diff line change
@@ -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);
}
});
Loading