Skip to content
Draft
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
32 changes: 32 additions & 0 deletions .github/workflows/test-worker-bridge.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
name: PAYNEX Worker bridge regression tests

on:
push:
branches: [feat/appdeploy-worker-bridge]
paths:
- "worker/**"
- "docs/appdeploy-worker-bridge.md"
- ".github/workflows/test-worker-bridge.yml"
pull_request:
branches: [main]
paths:
- "worker/**"
- "docs/appdeploy-worker-bridge.md"
- ".github/workflows/test-worker-bridge.yml"

jobs:
worker-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
- name: Check Worker syntax
run: node --check worker/src/index.js
- name: Install Worker dependencies
working-directory: worker
run: npm install
- name: Run Worker tests
working-directory: worker
run: npm test
50 changes: 50 additions & 0 deletions docs/appdeploy-worker-bridge.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# AppDeploy ↔ PAYNEX Worker bridge

## Source of truth

The Cloudflare Worker and D1 remain authoritative for merchants, API keys, payment links, transactions, refunds, provider events and entitlements. AppDeploy owns the web session and presentation layer only. AppDeploy application records may store a Worker merchant ID mapping and an encrypted copy of the one-time-issued merchant API key for server-side proxy calls; they must never become a second payment ledger.

## Existing Worker contract used by the bridge

- `GET /health` — connectivity/readiness check.
- `POST /api/admin/merchants` — creates a pending D1 merchant.
- `GET /api/admin/merchants?status=pending|active|suspended` — admin merchant listing.
- `POST /api/admin/merchants/:id/approve` — activates the D1 merchant and returns its initial API key once.
- `POST /api/admin/merchants/:id/issue-key` — issues a dedicated bridge API key for an already-active merchant without revoking any existing merchant keys.
- `POST /api/admin/merchants/:id/suspend` and `/reactivate` — D1 merchant lifecycle.
- Merchant-scoped `GET /api/v1/summary` and `GET /api/v1/transactions` — authenticated using the D1-issued merchant API key.

All `/api/admin/*` calls require `x-admin-token` and the Worker secret `ADMIN_API_TOKEN`. The AppDeploy backend must hold the same value as encrypted secret `PAYNEX_WORKER_ADMIN_TOKEN`. Never expose it to frontend code.

## AppDeploy bridge routes

The AppDeploy backend exposes a narrow allowlisted proxy; the browser never receives the Worker admin token or merchant API key.

- Admin: `GET /api/admin/worker/status` checks Worker health and verifies that the configured admin token is accepted; `GET /api/admin/worker/merchants` reads pending, active and suspended D1 merchant records.
- Merchant: `GET /api/merchant/worker/payment-links`, `POST /api/merchant/worker/payment-links`, and `POST /api/merchant/worker/payment-links/:id/disable` proxy link management with the merchant's server-held API key.
- Merchant UPI profile: `POST /api/merchant/worker/upi` updates the active merchant's UPI ID using the Worker endpoint. Personal UPI is not a commercial PSP substitute; the Worker explicitly keeps UPI Intent transactions pending.
- Public checkout: `GET /api/public/pay/:id` and `POST /api/public/pay/:id/initiate` proxy the existing Worker public checkout endpoints. The AppDeploy public checkout uses a client-generated idempotency key and only displays `PENDING` after UPI intent initiation.
- Access control: admin suspend/reactivate first synchronizes the linked Worker merchant status; AppDeploy local access is updated only after Worker confirms the change.

The AppDeploy public checkout is an alternate presentation route. Existing GitHub Pages checkout URLs and direct Worker endpoints are unchanged.

## Secret setup

1. Generate a high-entropy random token (at least 32 random bytes).
2. Set it as the Cloudflare Worker secret `ADMIN_API_TOKEN`.
3. Enter the exact same value in AppDeploy's secure secret-entry form as `PAYNEX_WORKER_ADMIN_TOKEN`.
4. Generate a separate 32-byte random encryption key and store it only as AppDeploy secret `PAYNEX_BRIDGE_ENCRYPTION_KEY`.
5. Never paste either value into chat, source control, frontend code, logs or screenshots.

## Safety rules

- Do not change existing checkout, UPI intent, webhook, idempotency or transaction state behavior.
- App approval is not PSP approval. Worker merchant activation only permits the existing merchant API; it does not enable bank/PSP verification.
- No API key is returned to the admin browser. The bridge encrypts a dedicated Worker-issued key at rest and offers the merchant a one-time reveal, while retaining only the encrypted value for server-side proxying. Existing merchant API keys are preserved.
- AppDeploy user ID ↔ Worker merchant ID mapping is explicit and created only by a successful server-side admin action.
- Worker failures leave the AppDeploy application unapproved and retryable; retries must reconcile against the Worker merchant list by exact email before creating another merchant.
- Only Worker-verified transactions can activate subscriptions. Screenshots, UPI app returns and client callbacks remain non-authoritative.

## Verification

Run `cd worker && npm test`. These regression tests assert the existing Worker admin-auth boundary, merchant provisioning/approval endpoints, pending checkout policy and signed-provider verification guard remain present.
13 changes: 13 additions & 0 deletions worker/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -409,6 +409,19 @@ export default {
.bind(makeId(), merchantId, "merchant." + action, merchantId).run();
return json({ merchant_id: merchantId, status: nextStatus, ...(issuedKey ? { api_key: issuedKey, warning: "Copy this key now. It cannot be shown again." } : {}) }, 200, origin);
}
const issueKeyMatch = url.pathname.match(new RegExp("^/api/admin/merchants/([0-9a-f-]{36})/issue-key$", "i"));
if (request.method === "POST" && issueKeyMatch) {
const merchantId = issueKeyMatch[1];
const merchant = await env.DB.prepare("SELECT id,status FROM merchants WHERE id=?").bind(merchantId).first();
if (!merchant || merchant.status !== "active") return json({ error: "Only active merchants can receive a replacement API key" }, 409, origin);
const issuedKey = "pn_live_" + Array.from(crypto.getRandomValues(new Uint8Array(32)), b => b.toString(16).padStart(2, "0")).join("");
const keyId = makeId();
await env.DB.batch([
env.DB.prepare("INSERT INTO api_keys (id,merchant_id,key_hash,label) VALUES (?,?,?,'AppDeploy bridge key')").bind(keyId, merchantId, await sha256(issuedKey)),
env.DB.prepare("INSERT INTO audit_logs (id,merchant_id,actor,action,resource_type,resource_id,metadata_json) VALUES (?,?,'admin','merchant.api_key.issued_for_bridge','api_key',?,?)").bind(makeId(), merchantId, keyId, JSON.stringify({ source: "appdeploy_bridge", existing_keys_preserved: true }))
]);
return json({ merchant_id: merchantId, id: keyId, api_key: issuedKey, warning: "Copy this key now. It cannot be shown again." }, 201, origin);
}
if (request.method === "GET" && url.pathname === "/api/admin/refunds") {
const status=url.searchParams.get("status") || "requested";
if(!["requested","approved_waiting_provider","rejected","settled"].includes(status)) return json({error:"Invalid refund status"},400,origin);
Expand Down
31 changes: 31 additions & 0 deletions worker/test/appdeploy-bridge-contract.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';

const source = readFileSync(new URL('../src/index.js', import.meta.url), 'utf8');

test('admin endpoints remain behind the Worker admin token boundary', () => {
assert.ok(source.includes('if (url.pathname.startsWith("/api/admin/"))'));
assert.ok(source.includes('if (!env.ADMIN_API_TOKEN) return json({ error: "Admin access is not configured" }, 503, origin);'));
assert.ok(source.includes('if (!await authenticateAdmin(request, env)) return json({ error: "Unauthorised" }, 401, origin);'));
});

test('Worker exposes the D1 merchant lifecycle and recoverable API-key rotation', () => {
assert.ok(source.includes('url.pathname === "/api/admin/merchants"'));
assert.ok(source.includes('approve|suspend|reactivate'));
assert.ok(source.includes('issue-key'));
assert.ok(source.includes('AppDeploy bridge key'));
assert.ok(source.includes('Initial admin-approved key'));
});

test('checkout remains pending until an authorised provider confirms settlement', () => {
assert.ok(source.includes('status: "pending"'));
assert.ok(source.includes('Opening a UPI app or returning from it does not confirm payment.'));
assert.ok(source.includes('Transaction is not eligible for verification'));
});

test('UPI partner verification remains signed and amount/currency checked', () => {
assert.ok(source.includes('verifyHmacSha256Hex(secret,rawBody,signature)'));
assert.ok(source.includes('tx.amount_minor!==payment.amount_minor || tx.currency!==payment.currency'));
assert.ok(source.includes("status='verified'"));
});
Loading