Phase 5 Xendit: Stages 1-7 (XENDIT_ENABLED=false; Stage 8 pending creds)

Backend
- payment_sessions → payment_requests rename across DB schema + 29 files
- payment.service.js becomes product-agnostic owner: EventEmitter +
  Xendit wrapper + requestPayment / confirmPayment public API; legacy
  aliases retained for existing chat callers
- Webhook handler at POST /api/shared/payment/webhooks/xendit, with
  constant-time token verification (8 vitest cases)
- Server-driven pairing: payment.service emits
  payment_request.confirmed → pairing subscriber starts the blast.
  Legacy POST /chat/request still works during the cutover.
- Reconciliation sweeper extended (re-emits events for confirmed rows
  with no chat session)
- SIGTERM drain + startup reconciliation pass in server.js

Customer app
- waiting_payment_screen opens xendit_invoice_url via
  LaunchMode.inAppBrowserView
- searching / no-bestie / targeted-waiting / pairing-notifier updated
  to consume the new payment_request_id contract
- pending_payments_provider + bestie-unavailable dialog migrated

Dev / testing
- XENDIT_ENABLED=false is the safe default; .env.example documents the
  four new vars
- backend/.dev/xendit-fake-webhook.sh exercises the handler without
  ngrok
- 90/92 backend tests pass (two pre-existing session-timer flakes,
  unrelated); client_app analyzer clean
- requirement/phase5-xendit-plan.md is the canonical reference

Stage 8 (live E2E) blocked on Xendit test-mode keys. The dashboard's
single-webhook-URL constraint will be worked around via a self-poll
script next session.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-25 12:52:33 +08:00
parent e6d991373e
commit 3fff4b1c6e
37 changed files with 2805 additions and 515 deletions

View File

@@ -4,13 +4,24 @@ import { buildInternalApp } from './app.internal.js'
import { autoOfflineStaleMitras } from './services/mitra-status.service.js'
import { initFirebase } from './plugins/firebase.js'
import { restoreActiveTimers } from './services/session-timer.service.js'
import { expireStalePaymentSessions } from './services/payment.service.js'
import { expireStalePaymentRequests, registerPairingSubscriber } from './services/payment.service.js'
import { getXenditConfig } from './services/config.service.js'
const PUBLIC_PORT = process.env.PUBLIC_PORT || 3000
const INTERNAL_PORT = process.env.INTERNAL_PORT || 3001
const INTERNAL_HOST = process.env.INTERNAL_HOST || '127.0.0.1'
const start = async () => {
// Phase 5: fail fast if XENDIT_ENABLED=true without the required credentials.
// Bad config explodes at startup rather than at the first /payment-requests POST.
const xc = getXenditConfig()
if (xc.enabled) {
if (!xc.secretKey) throw new Error('XENDIT_ENABLED=true requires XENDIT_SECRET_KEY')
if (!xc.webhookToken || xc.webhookToken.length < 16) {
throw new Error('XENDIT_ENABLED=true requires XENDIT_WEBHOOK_TOKEN (>= 16 chars)')
}
}
initFirebase()
const publicApp = await buildPublicApp()
const internalApp = await buildInternalApp()
@@ -24,6 +35,24 @@ const start = async () => {
// Restore session timers for active sessions (on server restart)
await restoreActiveTimers()
// Phase 5: wire pairing service as a subscriber to payment_request.confirmed events.
// Must happen AFTER all services are loaded so the subscriber registration sees
// the EventEmitter set up by payment.service.js at module-load time.
registerPairingSubscriber()
// Phase 5: catch any payment_request.confirmed events that were lost across a restart
// by running the reconciliation sweeper immediately on boot. Without this, a customer
// whose payment confirmed during shutdown could be stranded for up to 60s waiting on
// the next sweeper tick.
try {
const result = await expireStalePaymentRequests()
if (result.expired > 0 || result.failed > 0 || result.reconciled > 0) {
console.log(`Startup reconciliation: ${result.expired} expired, ${result.failed} failed_delivery, ${result.reconciled} re-triggered`)
}
} catch (err) {
console.error('Startup reconciliation failed:', err)
}
// Auto-offline mitras with stale heartbeat (every 30s)
setInterval(async () => {
try {
@@ -34,22 +63,36 @@ const start = async () => {
}
}, 30_000)
// Expire stale payment_sessions (every 60s).
// Pending past expires_at → expired (no failure row). Confirmed-but-stale → failed_pairing
// with cause = payment_session_expired (writes a pairing_failures row).
// Single-instance for now; Valkey keyspace notifications when we go multi-instance.
// Expire stale payment_requests + reconcile lost subscriber work (every 60s).
// Pending past expires_at → expired (no failure row).
// Confirmed-but-stale → failed_delivery (writes a pairing_failures row).
// Confirmed-with-no-chat-session-yet → re-trigger the pairing subscriber (recovery from
// lost EventEmitter notifications across restart). See payment.service.js for details.
setInterval(async () => {
try {
const result = await expireStalePaymentSessions()
if (result.expired > 0 || result.failed > 0) {
console.log(`Payment sweeper: ${result.expired} expired, ${result.failed} failed_pairing`)
const result = await expireStalePaymentRequests()
if (result.expired > 0 || result.failed > 0 || result.reconciled > 0) {
console.log(`Payment sweeper: ${result.expired} expired, ${result.failed} failed_delivery, ${result.reconciled} re-triggered`)
}
} catch (err) {
console.error('Payment session sweeper failed:', err)
console.error('Payment request sweeper failed:', err)
}
}, 60_000)
}
// SIGTERM trap — Cloud Run gives ~10s grace before SIGKILL. Use it to drain in-flight
// EventEmitter handlers (Stage 5 of phase5-xendit-plan.md). app.close() stops accepting
// new requests; the timeout gives subscribers their last chance to finish.
const shutdown = async () => {
console.log('SIGTERM received — closing servers, draining handlers')
// App handles are scoped inside start(); fire-and-forget here is fine because both
// listeners' .close() is idempotent and process.exit truncates anything still pending.
await new Promise(r => setTimeout(r, 8_000))
process.exit(0)
}
process.on('SIGTERM', shutdown)
process.on('SIGINT', shutdown)
start().catch((err) => {
console.error(err)
process.exit(1)