diff --git a/.githooks/pre-push b/.githooks/pre-push new file mode 100755 index 0000000..88b9a89 --- /dev/null +++ b/.githooks/pre-push @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +pnpm security:scan diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index b02e4d9..2cc8e41 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -21,6 +21,8 @@ jobs: PAYMENT_MODE: disabled steps: - uses: actions/checkout@v4 + with: + fetch-depth: 0 - uses: pnpm/action-setup@v4 with: version: 11.19.0 @@ -29,6 +31,10 @@ jobs: node-version: 22 cache: pnpm - run: pnpm install --frozen-lockfile + - run: pnpm security:scan + env: + SECRET_SCAN_BASE: ${{ github.event.pull_request.base.sha || github.event.before }} + - run: pnpm audit --audit-level=moderate - run: pnpm setup:local - run: pnpm db:migrate - run: pnpm db:seed @@ -49,11 +55,16 @@ jobs: API_ORIGIN: http://localhost:3101 NEXT_PUBLIC_SITE_URL: http://localhost:3100 - run: pnpm exec playwright install --with-deps msedge + - run: pnpm qa:prepare + env: + TEST_DATABASE_URL: postgresql://quickpay:local-development-only@localhost:5432/quickpay_e2e_test - run: pnpm test:e2e env: E2E_BASE_URL: http://localhost:3100 E2E_SERVER_COMMAND: pnpm qa:serve E2E_REAL_AUTH: "true" + E2E_PROVIDER_FIXTURES: "true" + TEST_DATABASE_URL: postgresql://quickpay:local-development-only@localhost:5432/quickpay_e2e_test - uses: actions/upload-artifact@v4 if: always() with: diff --git a/apps/api/next.config.ts b/apps/api/next.config.ts index ca00df0..7cd792c 100644 --- a/apps/api/next.config.ts +++ b/apps/api/next.config.ts @@ -2,5 +2,10 @@ import type { NextConfig } from "next"; export default { distDir: process.env.NEXT_BUILD_DIR || ".next", transpilePackages: ["@quickpay/contracts", "@quickpay/database"], - serverExternalPackages: ["pg"], + serverExternalPackages: ["pg", "sharp"], + outputFileTracingIncludes: { + "/api/v1/payments/*/receipt": [ + "../../assets/brand/quick-pay-brand-pack-v1/website/header-light@2x.png", + ], + }, } satisfies NextConfig; diff --git a/apps/api/package.json b/apps/api/package.json index a9e58fa..e25b574 100644 --- a/apps/api/package.json +++ b/apps/api/package.json @@ -13,9 +13,11 @@ "better-auth": "1.7.16", "drizzle-orm": "0.45.4", "next": "16.4.5", + "pdf-lib": "^1.17.1", "pg": "8.23.1", "react": "19.3.1", "react-dom": "19.3.1", + "sharp": "^0.35.5", "zod": "4.6.7" }, "devDependencies": { diff --git a/apps/api/src/app/api/v1/payments/[paymentId]/receipt/route.ts b/apps/api/src/app/api/v1/payments/[paymentId]/receipt/route.ts new file mode 100644 index 0000000..2d3cd04 --- /dev/null +++ b/apps/api/src/app/api/v1/payments/[paymentId]/receipt/route.ts @@ -0,0 +1,33 @@ +import { endpoint } from "@quickpay/server/shared/infrastructure/http"; +import { identity } from "@quickpay/server/shared/auth"; +import { assert } from "@quickpay/server/shared/errors"; +import { + ownPayment, + publicTransaction, +} from "@quickpay/server/v1/modules/payments/repositories/payment.repository"; +import { renderReceipt } from "@quickpay/server/v1/modules/payments/services/receipt"; +export const GET = endpoint(async (req, ctx) => { + const session = await identity(req); + const { paymentId } = await ctx.params; + const format = new URL(req.url).searchParams.get("format") || "pdf"; + assert( + format === "pdf" || format === "png", + "INVALID_FORMAT", + "Choose PDF or PNG.", + ); + const payment = publicTransaction( + await ownPayment(paymentId, session.user.id), + ); + const bytes = await renderReceipt( + { ...payment, createdAt: payment.createdAt.toISOString() }, + format, + ); + return new Response(new Uint8Array(bytes).buffer, { + headers: { + "Content-Type": format === "pdf" ? "application/pdf" : "image/png", + "Content-Disposition": `attachment; filename="QuickPay-receipt-${payment.id}.${format}"`, + "Cache-Control": "private, no-store", + "X-Content-Type-Options": "nosniff", + }, + }); +}); diff --git a/apps/api/src/app/api/v1/security/pin/reset/route.ts b/apps/api/src/app/api/v1/security/pin/reset/route.ts new file mode 100644 index 0000000..cd4411c --- /dev/null +++ b/apps/api/src/app/api/v1/security/pin/reset/route.ts @@ -0,0 +1,3 @@ +import { endpoint } from "@quickpay/server/shared/infrastructure/http"; +import { pinReset } from "@quickpay/server/v1/modules/security/routes/pin"; +export const POST = endpoint(pinReset); diff --git a/apps/api/src/app/api/v1/security/pin/route.ts b/apps/api/src/app/api/v1/security/pin/route.ts new file mode 100644 index 0000000..f518630 --- /dev/null +++ b/apps/api/src/app/api/v1/security/pin/route.ts @@ -0,0 +1,4 @@ +import { endpoint } from "@quickpay/server/shared/infrastructure/http"; +import { pinSettings } from "@quickpay/server/v1/modules/security/routes/pin"; +export const GET = endpoint(pinSettings); +export const POST = endpoint(pinSettings); diff --git a/apps/api/src/shared/auth/index.ts b/apps/api/src/shared/auth/index.ts index f6f1562..1cc6f44 100644 --- a/apps/api/src/shared/auth/index.ts +++ b/apps/api/src/shared/auth/index.ts @@ -1,5 +1,5 @@ import { pool } from "@quickpay/database"; -import { verifyPassword } from "better-auth/crypto"; +import { verifyTransactionPin } from "../../v1/modules/security/services/pin"; import { auth } from "../../v1/modules/auth/auth"; import { assert } from "../errors"; import { rateLimit } from "../infrastructure/http"; @@ -40,7 +40,7 @@ export async function authorized(req: Request, permission: string) { ); return s; } -export async function authorizeMoney(req: Request, password: string) { +export async function authorizeMoney(req: Request, pin: string) { const s = await identity(req); assert( s.user.emailVerified, @@ -49,17 +49,6 @@ export async function authorizeMoney(req: Request, password: string) { 403, ); await rateLimit(`authorize:${s.user.id}`, 5); - const { - rows: [a], - } = await pool.query( - "SELECT password FROM auth_accounts WHERE user_id=$1 AND provider_id='credential'", - [s.user.id], - ); - assert( - a?.password && (await verifyPassword({ password, hash: a.password })), - "AUTHORIZATION_FAILED", - "Your password is incorrect.", - 403, - ); + await verifyTransactionPin(s.user.id, pin); return s; } diff --git a/apps/api/src/shared/infrastructure/email.ts b/apps/api/src/shared/infrastructure/email.ts index 772a91b..103585a 100644 --- a/apps/api/src/shared/infrastructure/email.ts +++ b/apps/api/src/shared/infrastructure/email.ts @@ -1,3 +1,7 @@ +import { readFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import { emailTemplate } from "./email/template"; +import { unseal } from "./security"; import { z } from "zod"; import { env } from "./env"; @@ -5,6 +9,7 @@ const emailJob = z.object({ to: z.email(), subject: z.string().min(1), text: z.string().min(1), + otpEncrypted: z.string().optional(), }); const acceptedMessage = z.object({ Messages: z.array(z.object({ Status: z.literal("success") })).length(1), @@ -18,6 +23,13 @@ export async function sendEmail(payload: Record) { throw new Error("Mailjet email delivery is not configured."); } const message = emailJob.parse(payload); + const otp = message.otpEncrypted ? unseal(message.otpEncrypted) : undefined; + const text = otp ? message.text.replaceAll("{{code}}", otp) : message.text; + const name = + "assets/brand/quick-pay-brand-pack-v1/website/header-light@2x.png"; + const logo = await readFile(resolve(process.cwd(), name)).catch(() => + readFile(resolve(process.cwd(), "../..", name)), + ); const response = await fetch("https://api.mailjet.com/v3.1/send", { method: "POST", headers: { @@ -30,7 +42,21 @@ export async function sendEmail(payload: Record) { From: { Email: e.MAILJET_FROM_EMAIL, Name: e.MAILJET_FROM_NAME }, To: [{ Email: message.to }], Subject: message.subject, - TextPart: message.text, + TextPart: text, + HTMLPart: emailTemplate({ + subject: message.subject, + text, + siteUrl: e.WEB_ORIGIN || "", + otp, + }), + InlinedAttachments: [ + { + ContentType: "image/png", + Filename: "quickpay-logo.png", + ContentID: "quickpay-logo", + Base64Content: logo.toString("base64"), + }, + ], }, ], }), diff --git a/apps/api/src/shared/infrastructure/email/queue.ts b/apps/api/src/shared/infrastructure/email/queue.ts new file mode 100644 index 0000000..8521fc1 --- /dev/null +++ b/apps/api/src/shared/infrastructure/email/queue.ts @@ -0,0 +1,31 @@ +import { enqueue, type Connection } from "@quickpay/database"; +export async function queueUserEmail( + c: Pick, + userId: string, + subject: string, + text: string, + key: string, + extra: Record = {}, +) { + const { + rows: [user], + } = await c.query("SELECT email FROM users WHERE id=$1", [userId]); + if (user) + await enqueue(c, "email", { to: user.email, subject, text, ...extra }, key); +} + +export async function queueSecurityEmail( + userId: string, + subject: string, + text: string, + key: string, +) { + const { pool } = await import("@quickpay/database"); + try { + await queueUserEmail(pool, userId, subject, text, key); + } catch { + console.error( + JSON.stringify({ event: "security_email_queue_failed", userId }), + ); + } +} diff --git a/apps/api/src/shared/infrastructure/email/template.ts b/apps/api/src/shared/infrastructure/email/template.ts new file mode 100644 index 0000000..e33b86a --- /dev/null +++ b/apps/api/src/shared/infrastructure/email/template.ts @@ -0,0 +1,49 @@ +const escape = (text: string) => + text.replace( + /[&<>"']/g, + (c) => + ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[ + c + ]!, + ); +export function emailTemplate(input: { + subject: string; + text: string; + siteUrl: string; + otp?: string; +}) { + let action: URL | undefined; + let actionSource = ""; + try { + const origin = new URL(input.siteUrl); + for (const value of input.text.match(/https?:\/\/[^\s<>]+/g) || []) { + const url = new URL(value); + if (url.origin === origin.origin && !url.username && !url.password) { + action = url; + actionSource = value; + break; + } + } + } catch { + /* A message remains readable without an action link. */ + } + const paragraphs = input.text + .split(/\n+/) + .map((line) => + actionSource ? line.replace(actionSource, "").trim() : line, + ) + .filter(Boolean) + .map( + (line) => + `

${escape(line)}

`, + ) + .join(""); + const actionLabel = /verify.*email/i.test(input.subject) + ? "Verify email address" + : /reset.*password/i.test(input.subject) + ? "Reset password" + : /transaction/i.test(input.subject) + ? "View transaction" + : "Open Quick Pay"; + return `
${escape(input.subject)}
Quick Pay

YOUR QUICK PAY ACCOUNT

${escape(input.subject)}

${input.otp ? `
${escape(input.otp)}
` : ""}${paragraphs}${action ? `

${actionLabel}

` : ""}

Less paying. More living.

Quick Pay will never ask you to reply with your password, transaction PIN, authenticator code or card details. If you did not request this activity, secure your account and contact support through the app.

Quick Pay · Account and transaction notifications

`; +} diff --git a/apps/api/src/shared/infrastructure/http.ts b/apps/api/src/shared/infrastructure/http.ts index 7dbf8e0..147a093 100644 --- a/apps/api/src/shared/infrastructure/http.ts +++ b/apps/api/src/shared/infrastructure/http.ts @@ -101,6 +101,8 @@ export function endpoint( correlationId, event: "request_failed", type: e instanceof Error ? e.name : "unknown", + path: new URL(req.url).pathname, + ...(known ? { code: e.code } : {}), ...(configuration ? { fields: e.fields } : {}), }), ); diff --git a/apps/api/src/shared/infrastructure/openapi.ts b/apps/api/src/shared/infrastructure/openapi.ts index 2b2b8eb..6a356c6 100644 --- a/apps/api/src/shared/infrastructure/openapi.ts +++ b/apps/api/src/shared/infrastructure/openapi.ts @@ -78,6 +78,13 @@ export function openapi() { properties: Record, required = Object.keys(properties), ) => ({ type: "object", properties, required }); + const withOptional = ( + requiredProperties: Record, + optionalProperties: Record, + ) => ({ + ...object(requiredProperties), + properties: { ...requiredProperties, ...optionalProperties }, + }); const str = { type: "string" }; add( "/wallet/capabilities", @@ -216,6 +223,42 @@ export function openapi() { object({ code: str }), true, ); + add( + "/security/pin", + "get", + "Read transaction PIN setup and lock status", + "Security", + ); + add( + "/security/pin", + "post", + "Set or change transaction PIN using current account credentials", + "Security", + withOptional( + { + password: { type: "string", writeOnly: true }, + newPin: { type: "string", pattern: "^[0-9]{6}$", writeOnly: true }, + confirmPin: { type: "string", writeOnly: true }, + }, + { currentPin: { type: "string", writeOnly: true } }, + ), + ); + add( + "/security/pin/reset", + "post", + "Request or confirm an email OTP transaction PIN reset", + "Security", + withOptional( + { + password: { type: "string", writeOnly: true }, + }, + { + code: { type: "string", writeOnly: true }, + newPin: { type: "string", writeOnly: true }, + confirmPin: { type: "string", writeOnly: true }, + }, + ), + ); add( "/wallet", "get", @@ -339,7 +382,7 @@ export function openapi() { "post", "Claim an eligible reward once", "Rewards", - object({ password: { type: "string", writeOnly: true } }), + object({ pin: { type: "string", pattern: "^[0-9]{6}$", writeOnly: true } }), ); add( "/gift-cards/products", diff --git a/apps/api/src/v1/modules/admin/routes/access.ts b/apps/api/src/v1/modules/admin/routes/access.ts index 9ae7a9e..9bc9937 100644 --- a/apps/api/src/v1/modules/admin/routes/access.ts +++ b/apps/api/src/v1/modules/admin/routes/access.ts @@ -1,3 +1,4 @@ +import { queueSecurityEmail } from "../../../../shared/infrastructure/email/queue"; import { z } from "zod"; import { pool } from "@quickpay/database"; import { identity } from "../../../../shared/auth"; @@ -23,7 +24,10 @@ export async function adminAccess(req: Request) { "SELECT 1 FROM admin_elevations WHERE session_id=$1 AND expires_at>now()", [s.session.id], ); - return json({ allowed: !!valid.rowCount, mfaEnabled: u.two_factor_enabled }); + return json({ + allowed: !!valid.rowCount && u.two_factor_enabled, + mfaEnabled: u.two_factor_enabled, + }); } export async function unlockAdmin(req: Request) { const s = await identity(req); @@ -55,5 +59,11 @@ export async function unlockAdmin(req: Request) { await audit(pool, s.user.id, "admin.unlocked", s.session.id, null, { expiresInMinutes: 15, }); + await queueSecurityEmail( + s.user.id, + "Admin tools unlocked", + "An authenticator check unlocked your Quick Pay admin tools for 15 minutes. If this was not you, secure your account immediately.", + `admin-unlock:${crypto.randomUUID()}`, + ); return json({ message: "Admin tools unlocked for 15 minutes." }); } diff --git a/apps/api/src/v1/modules/auth/auth.ts b/apps/api/src/v1/modules/auth/auth.ts index d9fbd4b..c5effd4 100644 --- a/apps/api/src/v1/modules/auth/auth.ts +++ b/apps/api/src/v1/modules/auth/auth.ts @@ -1,3 +1,4 @@ +import { queueSecurityEmail } from "../../../shared/infrastructure/email/queue"; import { betterAuth } from "better-auth"; import { drizzleAdapter } from "better-auth/adapters/drizzle"; import { bearer, twoFactor } from "better-auth/plugins"; @@ -20,6 +21,14 @@ function createAuth() { maxPasswordLength: 128, requireEmailVerification: true, revokeSessionsOnPasswordReset: true, + onPasswordReset: async ({ user }) => { + await queueSecurityEmail( + user.id, + "Your password was reset", + "Your Quick Pay login password was reset. If this was not you, secure your email and contact support immediately.", + `password-reset-alert:${crypto.randomUUID()}`, + ); + }, sendResetPassword: async ({ user, url }) => { await enqueue( pool, @@ -27,7 +36,7 @@ function createAuth() { { to: user.email, subject: "Reset your Quick Pay password", - text: `Reset your password: ${url}`, + text: `A password reset was requested for your Quick Pay account. Open the secure link below to choose a new password.\n${url}\nIf this was not you, you can ignore this email. Your password has not changed.`, }, `reset:${crypto.randomUUID()}`, ); @@ -43,7 +52,7 @@ function createAuth() { { to: user.email, subject: "Verify your Quick Pay email", - text: `Verify your email: ${url}`, + text: `Welcome to Quick Pay. Confirm your email address to finish setting up your account and keep your payments secure.\n${url}\nIf you did not create this account, you can ignore this email.`, }, `verify:${crypto.randomUUID()}`, ); diff --git a/apps/api/src/v1/modules/auth/routes/handler.ts b/apps/api/src/v1/modules/auth/routes/handler.ts index 51ed60d..3b3a665 100644 --- a/apps/api/src/v1/modules/auth/routes/handler.ts +++ b/apps/api/src/v1/modules/auth/routes/handler.ts @@ -1,3 +1,5 @@ +import { createHash } from "node:crypto"; +import { queueSecurityEmail } from "../../../../shared/infrastructure/email/queue"; import { z } from "zod"; import { pool } from "@quickpay/database"; import { POLICY_VERSION, signUpSchema, password } from "@quickpay/contracts"; @@ -88,13 +90,77 @@ export async function handleAuth(req: Request) { revokeOtherSessions: z.boolean().optional(), }), ); - return auth().handler( + const actor = path.endsWith("/change-password") + ? await auth().api.getSession({ headers: req.headers }) + : null; + const response = await auth().handler( new Request(req.url, { method: "POST", headers: req.headers, body: JSON.stringify(v), }), ); + if (response.ok && path.endsWith("/change-password")) { + if (actor) + await queueSecurityEmail( + actor.user.id, + "Your password changed", + "Your Quick Pay login password was changed. If this was not you, reset it immediately and contact support.", + `password-changed:${crypto.randomUUID()}`, + ); + } + return response; + } + const response = await auth().handler(req); + if (req.method === "POST" && response.ok) { + const result = await response + .clone() + .json() + .catch(() => null); + if ( + (path.endsWith("/sign-in/email") || + path.endsWith("/two-factor/verify-totp") || + path.endsWith("/two-factor/verify-backup-code")) && + result?.user?.id && + !result.twoFactorRedirect + ) { + const agent = req.headers.get("user-agent") || ""; + const device = /iPhone|iPad/i.test(agent) + ? "iPhone or iPad" + : /Android/i.test(agent) + ? "Android device" + : /Windows/i.test(agent) + ? "Windows device" + : /Macintosh|Mac OS/i.test(agent) + ? "Mac" + : /Linux/i.test(agent) + ? "Linux device" + : "Web or mobile client"; + const key = createHash("sha256") + .update(String(result.token || crypto.randomUUID())) + .digest("hex"); + await queueSecurityEmail( + result.user.id, + "New sign-in to Quick Pay", + `A new sign-in completed on ${new Date().toUTCString()}. +Device: ${device} +If this was not you, change your password and review your account security.`, + `login:${key}`, + ); + } + if ( + path.endsWith("/two-factor/verify-totp") || + path.endsWith("/two-factor/disable") + ) { + const session = await auth().api.getSession({ headers: req.headers }); + if (session) + await queueSecurityEmail( + session.user.id, + "Authenticator security update", + "An authenticator verification or settings change was completed on your account. If this was not you, contact support.", + `authenticator:${crypto.randomUUID()}`, + ); + } } - return auth().handler(req); + return response; } diff --git a/apps/api/src/v1/modules/billers/providers/vtpass.ts b/apps/api/src/v1/modules/billers/providers/vtpass.ts index 7cd6062..7c2c9fa 100644 --- a/apps/api/src/v1/modules/billers/providers/vtpass.ts +++ b/apps/api/src/v1/modules/billers/providers/vtpass.ts @@ -2,12 +2,27 @@ import { z } from "zod"; import { env } from "../../../../shared/infrastructure/env"; import { assert } from "../../../../shared/errors"; const envelope = z.object({ - code: z.string().optional(), - response_description: z.string().optional(), + code: z + .string() + .nullish() + .transform((value) => value ?? undefined), + response_description: z + .string() + .nullish() + .transform((value) => value ?? undefined), content: z.unknown().optional(), - requestId: z.string().optional(), - amount: z.union([z.string(), z.number()]).optional(), - purchased_code: z.string().optional(), + requestId: z + .string() + .nullish() + .transform((value) => value ?? undefined), + amount: z + .union([z.string(), z.number()]) + .nullish() + .transform((value) => value ?? undefined), + purchased_code: z + .string() + .nullish() + .transform((value) => value ?? undefined), }); export function vtpassConfigured() { const e = env(); diff --git a/apps/api/src/v1/modules/deposits/providers/paystack.ts b/apps/api/src/v1/modules/deposits/providers/paystack.ts index b730894..0a7c356 100644 --- a/apps/api/src/v1/modules/deposits/providers/paystack.ts +++ b/apps/api/src/v1/modules/deposits/providers/paystack.ts @@ -1,10 +1,17 @@ import { createHmac, timingSafeEqual } from "node:crypto"; import { z } from "zod"; import { env } from "../../../../shared/infrastructure/env"; -import { assert } from "../../../../shared/errors"; +import { assert, DomainError } from "../../../../shared/errors"; export function paystackConfigured() { return env().PAYMENT_MODE !== "disabled" && !!env().PAYSTACK_SECRET_KEY; } +export function withdrawalsConfigured() { + return ( + paystackConfigured() && + (env().PAYMENT_MODE === "sandbox" || + env().PAYSTACK_TRANSFERS_ENABLED === "true") + ); +} export async function paystack( path: string, schema: T, @@ -16,31 +23,94 @@ export async function paystack( "Adding money is not available yet. Please check back.", 503, ); - const r = await fetch(`https://api.paystack.co/${path}`, { - method: payload ? "POST" : "GET", - headers: { - Authorization: `Bearer ${env().PAYSTACK_SECRET_KEY}`, - "Content-Type": "application/json", - }, - body: payload ? JSON.stringify(payload) : undefined, - signal: AbortSignal.timeout(20000), + const accountLookup = path.startsWith("bank/resolve"), + bankList = path.startsWith("bank?"); + const unavailable = () => + new DomainError( + accountLookup + ? "BANK_LOOKUP_UNAVAILABLE" + : bankList + ? "BANK_LIST_UNAVAILABLE" + : "PAYMENT_PENDING", + accountLookup + ? "Account verification is temporarily unavailable. Please try again shortly. No transfer has been made." + : bankList + ? "We could not load the banks. Please try again shortly." + : "We could not confirm this request. Check its status before trying again.", + 503, + ); + // Bank reads can be retried safely. Money-moving requests reconcile uncertain outcomes instead. + let r: Response | undefined; + for ( + let attempt = 0; + attempt < (accountLookup || bankList ? 2 : 1); + attempt++ + ) { + try { + r = await fetch(`https://api.paystack.co/${path}`, { + method: payload ? "POST" : "GET", + headers: { + Authorization: `Bearer ${env().PAYSTACK_SECRET_KEY}`, + "Content-Type": "application/json", + }, + body: payload ? JSON.stringify(payload) : undefined, + signal: AbortSignal.timeout(accountLookup || bankList ? 10000 : 20000), + }); + if (r.ok || (r.status < 500 && ![408, 425, 429].includes(r.status))) + break; + } catch { + r = undefined; + } + } + if (!r) throw unavailable(); + if ( + !r.ok && + r.status >= 400 && + r.status < 500 && + ![408, 409, 425, 429].includes(r.status) + ) { + assert( + false, + accountLookup + ? [401, 403].includes(r.status) + ? "BANK_LOOKUP_UNAVAILABLE" + : "BANK_ACCOUNT_UNVERIFIED" + : bankList + ? "BANK_LIST_UNAVAILABLE" + : "PROVIDER_REJECTED", + accountLookup + ? "Paystack could not verify this account. Check the selected bank and ten-digit account number, or try again shortly. No transfer has been made." + : bankList + ? "We could not load the banks. Please try again shortly." + : "The payment provider could not accept this request. Please contact support if it continues.", + (accountLookup && [401, 403].includes(r.status)) || bankList ? 503 : 422, + ); + } + if (!r.ok) throw unavailable(); + const raw = await r.json().catch(() => { + throw unavailable(); }); - assert( - r.ok, - "PAYMENT_PENDING", - "We could not confirm this request. Check its status before trying again.", - 503, - ); const data = z - .object({ status: z.boolean(), data: z.unknown() }) - .parse(await r.json()); + .object({ status: z.boolean(), data: z.unknown().optional() }) + .safeParse(raw); + if (!data.success) throw unavailable(); assert( - data.status, - "PROVIDER_PENDING", - "We could not confirm this request yet.", - 503, + data.data.status, + accountLookup + ? "BANK_ACCOUNT_UNVERIFIED" + : bankList + ? "BANK_LIST_UNAVAILABLE" + : "PROVIDER_PENDING", + accountLookup + ? "Paystack could not verify this account. Check the selected bank and ten-digit account number, or try again shortly. No transfer has been made." + : bankList + ? "We could not load the banks. Please try again shortly." + : "We could not confirm this request yet.", + accountLookup ? 422 : 503, ); - return schema.parse(data.data); + const parsed = schema.safeParse(data.data.data); + if (!parsed.success) throw unavailable(); + return parsed.data; } export function validPaystackSignature( raw: string, @@ -67,3 +137,8 @@ export const verifiedTransferSchema = z.object({ currency: z.string(), recipient: z.object({ recipient_code: z.string() }), }); + +export const resolvedBankAccountSchema = z.object({ + account_number: z.string(), + account_name: z.string().trim().min(1), +}); diff --git a/apps/api/src/v1/modules/deposits/services/checkout.ts b/apps/api/src/v1/modules/deposits/services/checkout.ts new file mode 100644 index 0000000..303155a --- /dev/null +++ b/apps/api/src/v1/modules/deposits/services/checkout.ts @@ -0,0 +1,74 @@ +import { pool } from "@quickpay/database"; +import { z } from "zod"; +import { env } from "../../../../shared/infrastructure/env"; +import { assert } from "../../../../shared/errors"; +import { paystack } from "../providers/paystack"; +import type { PaymentRow } from "../../payments/repositories/payment.repository"; + +export async function prepareDepositCheckout(id: string) { + // A persisted lease works with pooled database connections and expires after a crash. + const token = crypto.randomUUID(); + const { + rows: [p], + } = await pool.query( + "UPDATE transactions SET details=details||jsonb_build_object('checkoutLeaseToken',$2::text,'checkoutLeaseUntil',now()+interval '60 seconds') WHERE id=$1 AND kind='deposit' AND status='processing' AND NOT(details ? 'checkoutUrl') AND (NOT(details ? 'checkoutLeaseUntil') OR (details->>'checkoutLeaseUntil')::timestamptz { + void pool + .query( + "UPDATE transactions SET details=jsonb_set(details,'{checkoutLeaseUntil}',to_jsonb(now()+interval '60 seconds')) WHERE id=$1 AND details->>'checkoutLeaseToken'=$2", + [id, token], + ) + .catch(() => {}); + }, 20000); + try { + const { + rows: [u], + } = await pool.query("SELECT email FROM users WHERE id=$1", [p.user_id]); + const data = await paystack( + "transaction/initialize", + z.object({ + authorization_url: z.url(), + access_code: z.string(), + reference: z.string(), + }), + { + email: u.email, + amount: p.amount, + currency: "NGN", + reference: p.reference, + callback_url: `${env().WEB_ORIGIN}/transactions/detail?id=${encodeURIComponent(p.id)}`, + metadata: { transactionId: p.id }, + }, + ); + const url = new URL(data.authorization_url); + assert( + data.reference === p.reference, + "REFERENCE_MISMATCH", + "This checkout needs a further check.", + 409, + ); + assert( + url.protocol === "https:" && + !url.username && + !url.password && + url.hostname === "checkout.paystack.com", + "CHECKOUT_INVALID", + "Checkout is not available yet.", + 503, + ); + // A webhook may already have confirmed the charge while initialization was in flight. + await pool.query( + "UPDATE transactions SET status=CASE WHEN status='processing' THEN 'awaiting_authorization' ELSE status END,details=details||$2::jsonb,updated_at=now() WHERE id=$1 AND kind='deposit'", + [id, JSON.stringify({ checkoutUrl: url.href })], + ); + } finally { + clearInterval(heartbeat); + await pool.query( + "UPDATE transactions SET details=details-'checkoutLeaseToken'-'checkoutLeaseUntil' WHERE id=$1 AND details->>'checkoutLeaseToken'=$2", + [id, token], + ); + } +} diff --git a/apps/api/src/v1/modules/payments/docs/payments.openapi.ts b/apps/api/src/v1/modules/payments/docs/payments.openapi.ts index 09597bb..ed37b0c 100644 --- a/apps/api/src/v1/modules/payments/docs/payments.openapi.ts +++ b/apps/api/src/v1/modules/payments/docs/payments.openapi.ts @@ -7,29 +7,26 @@ export const financialSchemas = { Money: money, Deposit: { type: "object", - required: ["amount"], - properties: { amount: money }, + required: ["amount", "pin"], + properties: { + amount: money, + pin: { type: "string", pattern: "^[0-9]{6}$", writeOnly: true }, + }, }, Withdrawal: { type: "object", - required: [ - "amount", - "bankCode", - "accountNumber", - "validationId", - "password", - ], + required: ["amount", "bankCode", "accountNumber", "validationId", "pin"], properties: { amount: money, bankCode: { type: "string" }, accountNumber: { type: "string", pattern: "^[0-9]{10}$" }, validationId: { type: "string", format: "uuid" }, - password: { type: "string", writeOnly: true }, + pin: { type: "string", pattern: "^[0-9]{6}$", writeOnly: true }, }, }, Payment: { type: "object", - required: ["amount", "serviceId", "beneficiary", "password"], + required: ["amount", "serviceId", "beneficiary", "pin"], properties: { amount: money, serviceId: { type: "string" }, @@ -40,7 +37,7 @@ export const financialSchemas = { description: "Nigerian mobile, normalized to +234", }, validationId: { type: "string", format: "uuid" }, - password: { type: "string", writeOnly: true }, + pin: { type: "string", pattern: "^[0-9]{6}$", writeOnly: true }, }, }, Transaction: { diff --git a/apps/api/src/v1/modules/payments/domain/payment-state.ts b/apps/api/src/v1/modules/payments/domain/payment-state.ts index e6bd190..8ac5335 100644 --- a/apps/api/src/v1/modules/payments/domain/payment-state.ts +++ b/apps/api/src/v1/modules/payments/domain/payment-state.ts @@ -9,9 +9,17 @@ const allowed: Record = { reversed: [], cancelled: [], }; -export function transition(from: PaymentState, to: PaymentState) { +export function transition( + from: PaymentState, + to: PaymentState, + kind?: string, +) { assert( - from === to || allowed[from]?.includes(to), + from === to || + allowed[from]?.includes(to) || + (kind === "deposit" && + to === "successful" && + ["failed", "cancelled"].includes(from)), "STATE_CONFLICT", "This payment needs a status check before it can change.", 409, diff --git a/apps/api/src/v1/modules/payments/jobs/process-payment.ts b/apps/api/src/v1/modules/payments/jobs/process-payment.ts index 29b541f..e43611a 100644 --- a/apps/api/src/v1/modules/payments/jobs/process-payment.ts +++ b/apps/api/src/v1/modules/payments/jobs/process-payment.ts @@ -7,11 +7,11 @@ import { } from "../../deposits/providers/paystack"; import { vtpass } from "../../billers/providers/vtpass"; import { unseal } from "../../../../shared/infrastructure/security"; -import { env } from "../../../../shared/infrastructure/env"; -import { assert } from "../../../../shared/errors"; +import { prepareDepositCheckout } from "../../deposits/services/checkout"; +import { assert, DomainError } from "../../../../shared/errors"; import { settlePayment } from "../services/settle-payment"; import type { PaymentRow } from "../repositories/payment.repository"; -import { parseNaira } from "@quickpay/contracts"; +import { phone, parseNaira } from "@quickpay/contracts"; export async function verifyPayment(p: PaymentRow) { if (p.kind === "deposit") { const data = await paystack( @@ -26,7 +26,7 @@ export async function verifyPayment(p: PaymentRow) { reference: data.reference, email: data.customer.email, }); - else if (["failed", "abandoned"].includes(data.status)) + else if (data.status === "failed") await settlePayment(p.id, { status: "failed", amount: String(data.amount), @@ -57,44 +57,117 @@ export async function verifyPayment(p: PaymentRow) { }); } else if (p.kind === "payment") { const data = await vtpass("requery", "POST", { request_id: p.reference }); - const content = z - .object({ - transactions: z.object({ - status: z.string(), - amount: z.union([z.string(), z.number()]), - unique_element: z.string().optional(), - phone: z.string().optional(), + const transactionSchema = z.object({ + status: z.string(), + amount: z.union([z.string(), z.number()]), + unique_element: z + .string() + .nullish() + .transform((value) => value ?? undefined), + phone: z + .string() + .nullish() + .transform((value) => value ?? undefined), + request_id: z + .string() + .nullish() + .transform((value) => value ?? undefined), + }); + const parsed = z + .union([ + z + .object({ transactions: transactionSchema }) + .transform((value) => value.transactions), + transactionSchema, + ]) + .safeParse(data.content); + if (!parsed.success) { + const description = data.response_description || ""; + const reason = + /(?:invalid|incorrect|missing).*(?:key|credential)|unauth|authenticat/i.test( + description, + ) + ? "authentication" + : /not.*(?:found|exist)|invalid.*request/i.test(description) + ? "reference-not-found" + : /process|pending|progress/i.test(description) + ? "pending" + : /balance|insufficient/i.test(description) + ? "provider-balance" + : "response-format"; + const knownFields = new Set([ + "transactions", + "transaction", + "status", + "amount", + "request_id", + "requestId", + "data", + "error", + "errors", + "message", + "response_description", + "code", + "content", + ]); + console.error( + JSON.stringify({ + event: "provider_verification_unconfirmed", + provider: "vtpass", + providerCode: /^\d{3}$/.test(data.code || "") ? data.code : "unknown", + reason, + responseFields: + data.content && typeof data.content === "object" + ? Object.keys(data.content).filter((key) => knownFields.has(key)) + : [], }), - }) - .parse(data.content); + ); + throw new DomainError( + "PROVIDER_PENDING", + "The payment provider has not returned enough information to confirm this transaction yet.", + 503, + ); + } + const content = parsed.data; + const reference = data.requestId || content.request_id; assert( - data.requestId === p.reference, + reference === p.reference && + (!data.requestId || data.requestId === p.reference) && + (!content.request_id || content.request_id === p.reference), "REFERENCE_MISMATCH", "This payment needs a further check.", 409, ); - const destination = - content.transactions.unique_element || content.transactions.phone; + const destination = content.unique_element || content.phone; + const storedPhone = ["airtime", "data"].includes(String(p.details.category)) + ? phone.safeParse(p.details.beneficiary) + : null; + const providerPhone = storedPhone?.success + ? phone.safeParse(destination) + : null; assert( - destination === p.details.beneficiary, + destination === p.details.beneficiary || + (storedPhone?.success && + providerPhone?.success && + storedPhone.data === providerPhone.data), "DESTINATION_MISMATCH", "This payment needs a further check.", 409, ); const status = - content.transactions.status === "delivered" + content.status === "delivered" ? "successful" - : content.transactions.status === "reversed" + : content.status === "reversed" ? "reversed" - : content.transactions.status === "failed" + : content.status === "failed" ? "failed" : null; if (status) await settlePayment(p.id, { status, - amount: parseNaira(String(content.transactions.amount)), + amount: parseNaira(String(content.amount)), currency: "NGN", - reference: data.requestId!, + reference, fulfillment: data.purchased_code, }); } @@ -105,44 +178,14 @@ export async function processPayment(id: string) { } = await pool.query("SELECT * FROM transactions WHERE id=$1", [ id, ]); - if (!p || p.status !== "processing") return; - if (p.details.initiationStarted) { - await verifyPayment(p); + if (!p) return; + if (p.kind === "deposit") { + await prepareDepositCheckout(id); return; } - if (p.kind === "deposit") { - const { - rows: [u], - } = await pool.query("SELECT email FROM users WHERE id=$1", [p.user_id]); - const data = await paystack( - "transaction/initialize", - z.object({ - authorization_url: z.url(), - access_code: z.string(), - reference: z.string(), - }), - { - email: u.email, - amount: p.amount, - currency: "NGN", - reference: p.reference, - callback_url: `${env().WEB_ORIGIN}/transactions/${p.id}`, - metadata: { transactionId: p.id }, - }, - ); - const url = new URL(data.authorization_url); - assert( - url.protocol === "https:" && - (url.hostname === "checkout.paystack.com" || - url.hostname.endsWith(".paystack.com")), - "CHECKOUT_INVALID", - "Checkout is not available yet.", - 503, - ); - await pool.query( - "UPDATE transactions SET status='awaiting_authorization',details=details||$2::jsonb,updated_at=now() WHERE id=$1", - [id, JSON.stringify({ checkoutUrl: data.authorization_url })], - ); + if (p.status !== "processing") return; + if (p.details.initiationStarted) { + await verifyPayment(p); return; } if (p.kind === "withdrawal") { @@ -172,21 +215,34 @@ export async function processPayment(id: string) { ], ); if (!claimed.rowCount) return; - await paystack( - "transfer", - z.object({ - reference: z.string(), - status: z.string(), - transfer_code: z.string(), - }), - { - source: "balance", + try { + await paystack( + "transfer", + z.object({ + reference: z.string(), + status: z.string(), + transfer_code: z.string(), + }), + { + source: "balance", + amount: p.amount, + recipient: recipient.recipient_code, + reason: "Quick Pay wallet withdrawal", + reference: p.reference, + }, + ); + } catch (error) { + if (!(error instanceof DomainError) || error.code !== "PROVIDER_REJECTED") + throw error; + await settlePayment(id, { + status: "failed", amount: p.amount, - recipient: recipient.recipient_code, - reason: "Quick Pay wallet withdrawal", + currency: p.currency, reference: p.reference, - }, - ); + recipient: recipient.recipient_code, + }); + return; + } } else if (p.kind === "payment") { const claimed = await pool.query( "UPDATE transactions SET details=details||'{\"initiationStarted\":true}'::jsonb WHERE id=$1 AND NOT(details ? 'initiationStarted') RETURNING id", diff --git a/apps/api/src/v1/modules/payments/repositories/payment.repository.ts b/apps/api/src/v1/modules/payments/repositories/payment.repository.ts index a4787f6..4db67df 100644 --- a/apps/api/src/v1/modules/payments/repositories/payment.repository.ts +++ b/apps/api/src/v1/modules/payments/repositories/payment.repository.ts @@ -36,6 +36,8 @@ export const publicTransaction = (r: PaymentRow) => ({ "providerRaw", "initiationStarted", "attemptedAt", + "checkoutLeaseToken", + "checkoutLeaseUntil", ].includes(k), ), ), diff --git a/apps/api/src/v1/modules/payments/routes/handler.ts b/apps/api/src/v1/modules/payments/routes/handler.ts index b824582..869d8f0 100644 --- a/apps/api/src/v1/modules/payments/routes/handler.ts +++ b/apps/api/src/v1/modules/payments/routes/handler.ts @@ -20,24 +20,52 @@ export async function listPayments(req: Request) { } export async function getPayment(req: Request, id: string) { const s = await identity(req); - return json({ - transaction: publicTransaction(await ownPayment(id, s.user.id)), - }); + const payment = await ownPayment(id, s.user.id); + if ( + payment.kind === "deposit" + ? ["failed", "cancelled"].includes(payment.status) || + (["processing", "awaiting_authorization"].includes(payment.status) && + !!payment.details.checkoutUrl) + : ["processing", "awaiting_authorization"].includes(payment.status) && + payment.details.initiationStarted + ) { + await enqueue( + pool, + "verify-provider", + { reference: payment.reference }, + `status:${payment.id}:${Math.floor(Date.now() / 30000)}`, + ); + } + if ( + payment.kind === "deposit" && + payment.status === "processing" && + !payment.details.checkoutUrl + ) + await enqueue( + pool, + "process-payment", + { id: payment.id }, + `checkout:${payment.id}:${Math.floor(Date.now() / 30000)}`, + ); + return json({ transaction: publicTransaction(payment) }); } export async function checkPayment(req: Request, id: string) { const s = await identity(req); await rateLimit(`check:${s.user.id}`, 10); const p = await ownPayment(id, s.user.id); + const preparingCheckout = + p.kind === "deposit" && p.status === "processing" && !p.details.checkoutUrl; await enqueue( pool, - "verify-provider", - { reference: p.reference }, + preparingCheckout ? "process-payment" : "verify-provider", + preparingCheckout ? { id: p.id } : { reference: p.reference }, `manual:${id}:${Math.floor(Date.now() / 60000)}`, ); return json( { - message: - "We are checking your payment. Please refresh its status shortly.", + message: preparingCheckout + ? "We are preparing your secure checkout. It will appear here when ready." + : "We are checking your payment. Its status will update here automatically.", }, 202, ); diff --git a/apps/api/src/v1/modules/payments/services/create-payment.ts b/apps/api/src/v1/modules/payments/services/create-payment.ts index 1589cb1..b8a3881 100644 --- a/apps/api/src/v1/modules/payments/services/create-payment.ts +++ b/apps/api/src/v1/modules/payments/services/create-payment.ts @@ -1,11 +1,13 @@ import { atomic, enqueue, pool } from "@quickpay/database"; +import { queueUserEmail } from "../../../../shared/infrastructure/email/queue"; +import { env } from "../../../../shared/infrastructure/env"; import { z } from "zod"; import { paymentSchema, withdrawalSchema, depositSchema, } from "@quickpay/contracts"; -import { authorizeMoney, identity } from "../../../../shared/auth"; +import { authorizeMoney } from "../../../../shared/auth"; import { body, json } from "../../../../shared/infrastructure/http"; import { hash, seal } from "../../../../shared/infrastructure/security"; import { assert } from "../../../../shared/errors"; @@ -21,9 +23,11 @@ import { vtReference, variationSchema, } from "../../billers/providers/vtpass"; -import { paystackConfigured } from "../../deposits/providers/paystack"; -import { env } from "../../../../shared/infrastructure/env"; -import { parseNaira, phone } from "@quickpay/contracts"; +import { + paystackConfigured, + withdrawalsConfigured, +} from "../../deposits/providers/paystack"; +import { parseNaira, phone, formatMoney } from "@quickpay/contracts"; import { walletLimits } from "../../wallets/domain/limits"; export async function createOperation( req: Request, @@ -36,10 +40,7 @@ export async function createOperation( : kind === "withdrawal" ? { ...withdrawalSchema.parse(raw), kind: "withdrawal" as const } : { ...depositSchema.parse(raw), kind: "deposit" as const }; - const s = - v.kind === "deposit" - ? await identity(req) - : await authorizeMoney(req, v.password); + const s = await authorizeMoney(req, v.pin); assert( s.user.emailVerified, "VERIFY_CONTACT", @@ -53,7 +54,9 @@ export async function createOperation( "Please submit this request with a valid reference.", ); const clean = Object.fromEntries( - Object.entries(v).filter(([k]) => k !== "password"), + Object.entries(v).filter( + ([k]) => !["password", "pin", "code", "otp"].includes(k), + ), ); const requestHash = hash({ kind, ...clean }); // Replay before provider reads so retries remain useful during provider outages. @@ -76,7 +79,7 @@ export async function createOperation( const reference = kind === "payment" ? vtReference() - : `qp_${crypto.randomUUID().replaceAll("-", "")}`; + : `qp-${crypto.randomUUID().replaceAll("-", "")}`; if (kind === "deposit") { assert( paystackConfigured(), @@ -125,6 +128,13 @@ export async function createOperation( const normalized = phone.parse(v.beneficiary); v.beneficiary = `0${normalized.slice(4)}`; } + if (!["airtime", "data"].includes(service.category)) + assert( + v.phone, + "PHONE_REQUIRED", + "Enter a valid contact phone number.", + 422, + ); Object.assign(details, { beneficiary: v.beneficiary, phone: v.phone ? `0${v.phone.slice(4)}` : undefined, @@ -184,7 +194,7 @@ export async function createOperation( } if (v.kind === "withdrawal") { assert( - paystackConfigured() && env().PAYSTACK_TRANSFERS_ENABLED === "true", + withdrawalsConfigured(), "WITHDRAWAL_UNAVAILABLE", "Bank withdrawals are not available yet.", 503, @@ -259,6 +269,14 @@ export async function createOperation( ]); } await enqueue(c, "process-payment", { id }, `process:${id}`); + await queueUserEmail( + c, + s.user.id, + "Transaction submitted", + `Your ${kind} of ${formatMoney(v.amount)} has been submitted. Reference: ${reference}. Status: processing. +${env().WEB_ORIGIN}/transactions/detail?id=${id}`, + `transaction-submitted:${id}`, + ); return r.rows[0]; }); return json({ transaction: publicTransaction(transaction) }, 202); diff --git a/apps/api/src/v1/modules/payments/services/receipt.ts b/apps/api/src/v1/modules/payments/services/receipt.ts new file mode 100644 index 0000000..1b38178 --- /dev/null +++ b/apps/api/src/v1/modules/payments/services/receipt.ts @@ -0,0 +1,108 @@ +import { readFile } from "node:fs/promises"; +import { resolve } from "node:path"; +import sharp from "sharp"; +import { PDFDocument } from "pdf-lib"; +import { formatMoney, type Transaction } from "@quickpay/contracts"; +const escape = (value: unknown) => + String(value).replace( + /[&<>"']/g, + (c) => + ({ + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'", + })[c]!, + ); +async function logo() { + const name = + "assets/brand/quick-pay-brand-pack-v1/website/header-light@2x.png"; + try { + return await readFile(resolve(process.cwd(), name)); + } catch { + return readFile(resolve(process.cwd(), "../..", name)); + } +} +export async function renderReceipt(t: Transaction, format: "pdf" | "png") { + const brand = await logo(); + const status = t.status.replaceAll("_", " "); + const color = + t.status === "successful" + ? "#166534" + : ["processing", "created", "awaiting_authorization"].includes(t.status) + ? "#92400e" + : "#991b1b"; + const rows = [ + ["Transaction type", t.kind], + ["Service", t.serviceId || "Wallet"], + ["Reference", t.reference], + [ + "Date · Africa/Lagos", + new Date(t.createdAt).toLocaleString("en-GB", { + timeZone: "Africa/Lagos", + dateStyle: "medium", + timeStyle: "short", + }), + ], + ...(t.details.beneficiary + ? [ + [ + "Recipient", + String(t.details.beneficiaryName || t.details.beneficiary), + ], + ] + : []), + ...(t.details.accountName + ? [ + [ + "Bank account", + `${t.details.accountName} · •••• ${t.details.accountLast4 || ""}`, + ], + ] + : []), + ["Amount", formatMoney(t.amount)], + ["Fee", formatMoney(t.fee)], + ["Total", formatMoney(BigInt(t.amount) + BigInt(t.fee))], + ]; + const lines = rows + .map(([label, value], index) => { + const y = 590 + index * 88; + const text = String(value).slice(0, 160); + const parts = text.match(/.{1,53}/g) || [""]; + return `${escape(label)}${parts + .slice(0, 2) + .map( + (part, i) => + `${escape(part)}`, + ) + .join( + "", + )}`; + }) + .join(""); + const svg = ` + + + + TRANSACTION RECEIPT + ${escape(formatMoney(BigInt(t.amount) + BigInt(t.fee)))} + ${escape(status.toUpperCase())} + ${lines} + Less paying. More living. + ${t.status === "successful" ? "Payment confirmed. Keep this receipt for your records." : "This receipt records the status shown above; it is not proof of a completed payment."} + Quick Pay · NGN · Reference above identifies this transaction.`; + const png = await sharp(Buffer.from(svg)).png().toBuffer(); + if (format === "png") return png; + const pdf = await PDFDocument.create(); + pdf.setTitle(`Quick Pay receipt · ${t.reference}`); + pdf.setAuthor("Quick Pay"); + const page = pdf.addPage([595.28, 841.89]); + page.drawImage(await pdf.embedPng(png), { + x: 0, + y: 0, + width: 595.28, + height: 841.89, + }); + return Buffer.from(await pdf.save()); +} diff --git a/apps/api/src/v1/modules/payments/services/settle-payment.ts b/apps/api/src/v1/modules/payments/services/settle-payment.ts index 47a8715..976493e 100644 --- a/apps/api/src/v1/modules/payments/services/settle-payment.ts +++ b/apps/api/src/v1/modules/payments/services/settle-payment.ts @@ -1,3 +1,6 @@ +import { formatMoney } from "@quickpay/contracts"; +import { env } from "../../../../shared/infrastructure/env"; +import { queueUserEmail } from "../../../../shared/infrastructure/email/queue"; import { atomic, enqueue } from "@quickpay/database"; import { assert } from "../../../../shared/errors"; import { postJournal, ensureWallet } from "../../ledger/services/post-journal"; @@ -48,7 +51,15 @@ export async function settlePayment(id: string, outcome: VerifiedOutcome) { "This transfer needs a further check.", 409, ); - transition(p.status, outcome.status); + // A late charge confirmation can follow a failed checkout attempt. Never downgrade + // confirmed deposits when an older failure response arrives out of order. + if ( + p.kind === "deposit" && + p.status === "successful" && + outcome.status === "failed" + ) + return false; + transition(p.status, outcome.status, p.kind); await ensureWallet(c, p.user_id); const amount = BigInt(p.amount), fee = BigInt(p.fee), @@ -150,6 +161,17 @@ export async function settlePayment(id: string, outcome: VerifiedOutcome) { ], ); await enqueue(c, "receipt", { id }, `receipt:${id}:${outcome.status}`); + await queueUserEmail( + c, + p.user_id, + `Transaction ${outcome.status}`, + `Your ${p.kind} of ${formatMoney(p.amount)} is ${outcome.status}. +Reference: ${p.reference} +Fee: ${formatMoney(p.fee)} +Open the app for your receipt and full details: +${env().WEB_ORIGIN}/transactions/detail?id=${id}`, + `transaction-email:${id}:${outcome.status}`, + ); return true; }); } diff --git a/apps/api/src/v1/modules/rewards/routes/handler.ts b/apps/api/src/v1/modules/rewards/routes/handler.ts index a24acae..6307834 100644 --- a/apps/api/src/v1/modules/rewards/routes/handler.ts +++ b/apps/api/src/v1/modules/rewards/routes/handler.ts @@ -1,5 +1,6 @@ import { atomic, pool } from "@quickpay/database"; import { ruleSummary, rewardRuleSchema } from "@quickpay/contracts"; +import { transactionPin } from "@quickpay/contracts"; import { z } from "zod"; import { identity, authorizeMoney } from "../../../../shared/auth"; import { json, body } from "../../../../shared/infrastructure/http"; @@ -56,8 +57,8 @@ export async function referrals(req: Request) { }); } export async function claimReward(req: Request, id: string) { - const v = await body(req, z.object({ password: z.string().min(1) })); - const s = await authorizeMoney(req, v.password); + const v = await body(req, z.object({ pin: transactionPin })); + const s = await authorizeMoney(req, v.pin); await atomic(async (c) => { const { rows: [r], diff --git a/apps/api/src/v1/modules/security/routes/pin.ts b/apps/api/src/v1/modules/security/routes/pin.ts new file mode 100644 index 0000000..0d84bec --- /dev/null +++ b/apps/api/src/v1/modules/security/routes/pin.ts @@ -0,0 +1,84 @@ +import { z } from "zod"; +import { newTransactionPin, transactionPin } from "@quickpay/contracts"; +import { pool } from "@quickpay/database"; +import { identity } from "../../../../shared/auth"; +import { assert } from "../../../../shared/errors"; +import { body, json, rateLimit } from "../../../../shared/infrastructure/http"; +import { + checkAccountPassword, + setTransactionPin, + requestPinReset, + resetTransactionPin, +} from "../services/pin"; +export async function pinSettings(req: Request) { + const s = await identity(req); + if (req.method === "GET") { + const { + rows: [row], + } = await pool.query( + "SELECT locked_until FROM transaction_pins WHERE user_id=$1", + [s.user.id], + ); + return json({ configured: !!row, lockedUntil: row?.locked_until || null }); + } + assert( + s.user.emailVerified, + "VERIFY_CONTACT", + "Verify your email before setting a transaction PIN.", + 403, + ); + await rateLimit(`pin-settings:${s.user.id}`, 5); + const value = await body( + req, + z + .object({ + password: z.string().min(1), + newPin: newTransactionPin, + confirmPin: z.string(), + currentPin: transactionPin.optional(), + }) + .refine((v) => v.newPin === v.confirmPin, { + path: ["confirmPin"], + message: "Your PINs do not match.", + }), + ); + await checkAccountPassword(s.user.id, value.password); + await setTransactionPin(s.user.id, value.newPin, value.currentPin); + return json({ message: "Your transaction PIN is ready." }); +} +export async function pinReset(req: Request) { + const s = await identity(req); + assert( + s.user.emailVerified, + "VERIFY_CONTACT", + "Verify your email before resetting your PIN.", + 403, + ); + await rateLimit(`pin-reset:${s.user.id}`, 5); + const value = await body( + req, + z + .object({ + password: z.string().min(1), + code: z + .string() + .regex(/^\d{6}$/, "Enter the six-digit code sent to your email.") + .optional(), + newPin: newTransactionPin.optional(), + confirmPin: z.string().optional(), + }) + .refine((v) => !v.code || (!!v.newPin && v.newPin === v.confirmPin), { + path: ["confirmPin"], + message: "Enter and confirm your new PIN.", + }), + ); + await checkAccountPassword(s.user.id, value.password); + if (!value.code) { + await requestPinReset(s.user.id); + return json({ + message: "A reset code has been sent to your verified email.", + }); + } + await resetTransactionPin(s.user.id, value.code, value.newPin!); + return json({ message: "Your transaction PIN has been reset." }); +} diff --git a/apps/api/src/v1/modules/security/services/pin.ts b/apps/api/src/v1/modules/security/services/pin.ts new file mode 100644 index 0000000..3efba5b --- /dev/null +++ b/apps/api/src/v1/modules/security/services/pin.ts @@ -0,0 +1,230 @@ +import { newTransactionPin } from "@quickpay/contracts"; +import { randomInt, createHmac, timingSafeEqual } from "node:crypto"; +import { atomic, pool, type Connection } from "@quickpay/database"; +import { hashPassword, verifyPassword } from "better-auth/crypto"; +import { assert } from "../../../../shared/errors"; +import { env } from "../../../../shared/infrastructure/env"; +import { seal } from "../../../../shared/infrastructure/security"; +import { queueUserEmail } from "../../../../shared/infrastructure/email/queue"; +type PinRow = { + pin_hash: string; + failed_attempts: number; + locked_until: Date | null; + updated_at: Date; +}; +const problem = (code: string, message: string) => ({ code, message }); +const pinSecret = (userId: string, pin: string) => + createHmac("sha256", env().BETTER_AUTH_SECRET) + .update(`transaction-pin:${userId}:${pin}`) + .digest("hex"); +async function check( + c: Pick, + userId: string, + pin: string, + row?: PinRow, +) { + if (!row) + return problem( + "PIN_REQUIRED", + "Set up your transaction PIN before continuing.", + ); + if (row.locked_until && row.locked_until.getTime() > Date.now()) + return problem( + "PIN_LOCKED", + "Your PIN is locked for 15 minutes. Wait or reset it in Security settings.", + ); + if ( + !(await verifyPassword({ + password: pinSecret(userId, pin), + hash: row.pin_hash, + })) + ) { + const attempts = row.locked_until ? 1 : row.failed_attempts + 1; + await c.query( + "UPDATE transaction_pins SET failed_attempts=$2,locked_until=CASE WHEN $2>=5 THEN now()+interval '15 minutes' ELSE NULL END WHERE user_id=$1", + [userId, attempts], + ); + if (attempts >= 5) + await queueUserEmail( + c, + userId, + "Transaction PIN locked", + "Five incorrect PIN attempts locked your transaction PIN for 15 minutes. If this was not you, reset your PIN in Security settings.", + `pin-locked:${userId}:${Date.now()}`, + ); + return attempts >= 5 + ? problem( + "PIN_LOCKED", + "Your PIN is locked for 15 minutes. Reset it in Security settings if needed.", + ) + : problem( + "PIN_INCORRECT", + "Your transaction PIN is incorrect. Please try again.", + ); + } + await c.query( + "UPDATE transaction_pins SET failed_attempts=0,locked_until=NULL WHERE user_id=$1", + [userId], + ); +} +function ensure(result: ReturnType | undefined) { + assert( + !result, + result?.code || "PIN_INCORRECT", + result?.message || "Check your PIN.", + 403, + ); +} +export async function verifyTransactionPin(userId: string, pin: string) { + const result = await atomic(async (c) => { + const { + rows: [row], + } = await c.query( + "SELECT * FROM transaction_pins WHERE user_id=$1 FOR UPDATE", + [userId], + ); + return check(c, userId, pin, row); + }); + ensure(result); +} +export async function checkAccountPassword(userId: string, password: string) { + const { + rows: [account], + } = await pool.query( + "SELECT password FROM auth_accounts WHERE user_id=$1 AND provider_id='credential'", + [userId], + ); + assert( + account?.password && + (await verifyPassword({ password, hash: account.password })), + "AUTHORIZATION_FAILED", + "Your current login password is incorrect. Please try again.", + 403, + ); +} +export async function setTransactionPin( + userId: string, + pin: string, + currentPin?: string, +) { + pin = newTransactionPin.parse(pin); + const hash = await hashPassword(pinSecret(userId, pin)); + const result = await atomic(async (c) => { + await c.query("SELECT pg_advisory_xact_lock(hashtextextended($1,13))", [ + userId, + ]); + const { + rows: [old], + } = await c.query( + "SELECT * FROM transaction_pins WHERE user_id=$1 FOR UPDATE", + [userId], + ); + if (old) { + const error = await check(c, userId, currentPin || "", old); + if (error) return error; + } + await c.query( + "INSERT INTO transaction_pins(user_id,pin_hash) VALUES($1,$2) ON CONFLICT(user_id) DO UPDATE SET pin_hash=$2,failed_attempts=0,locked_until=NULL,updated_at=now()", + [userId, hash], + ); + await queueUserEmail( + c, + userId, + old ? "Transaction PIN changed" : "Transaction PIN set", + `Your Quick Pay transaction PIN was ${old ? "changed" : "set up"}. Your PIN is required for deposits, transfers and payments. We will never include it in an email.`, + `pin-set:${crypto.randomUUID()}`, + ); + }); + ensure(result); +} +const otpHash = (userId: string, code: string) => + createHmac("sha256", env().BETTER_AUTH_SECRET) + .update(`pin-reset:${userId}:${code}`) + .digest("hex"); +export async function requestPinReset(userId: string) { + const code = String(randomInt(100000, 1000000)); + await atomic(async (c) => { + await c.query("SELECT pg_advisory_xact_lock(hashtextextended($1,14))", [ + userId, + ]); + const { + rows: [old], + } = await c.query( + "SELECT created_at FROM pin_reset_challenges WHERE user_id=$1", + [userId], + ); + assert( + !old || Date.now() - old.created_at.getTime() >= 60000, + "RATE_LIMIT", + "Wait a minute before requesting another code.", + 429, + ); + await c.query( + "INSERT INTO pin_reset_challenges(user_id,code_hash,expires_at) VALUES($1,$2,now()+interval '10 minutes') ON CONFLICT(user_id) DO UPDATE SET code_hash=$2,expires_at=now()+interval '10 minutes',attempts=0,created_at=now()", + [userId, otpHash(userId, code)], + ); + await queueUserEmail( + c, + userId, + "Reset your transaction PIN", + "Your PIN reset code is {{code}}. It expires in 10 minutes and can be used once. Never share this code.", + `pin-reset-code:${crypto.randomUUID()}`, + { otpEncrypted: seal(code) }, + ); + }); +} +export async function resetTransactionPin( + userId: string, + code: string, + pin: string, +) { + pin = newTransactionPin.parse(pin); + const hash = await hashPassword(pinSecret(userId, pin)); + const result = await atomic(async (c) => { + const { + rows: [challenge], + } = await c.query( + "SELECT * FROM pin_reset_challenges WHERE user_id=$1 FOR UPDATE", + [userId], + ); + if ( + !challenge || + challenge.expires_at.getTime() < Date.now() || + challenge.attempts >= 5 + ) + return problem( + "OTP_INVALID", + "This code expired or has too many attempts. Request a new code.", + ); + const expected = Buffer.from(otpHash(userId, code), "hex"), + actual = Buffer.from(challenge.code_hash, "hex"); + if ( + actual.length !== expected.length || + !timingSafeEqual(expected, actual) + ) { + await c.query( + "UPDATE pin_reset_challenges SET attempts=attempts+1 WHERE user_id=$1", + [userId], + ); + return problem( + "OTP_INVALID", + "That code is incorrect. Please try again.", + ); + } + await c.query( + "INSERT INTO transaction_pins(user_id,pin_hash) VALUES($1,$2) ON CONFLICT(user_id) DO UPDATE SET pin_hash=$2,failed_attempts=0,locked_until=NULL,updated_at=now()", + [userId, hash], + ); + await c.query("DELETE FROM pin_reset_challenges WHERE user_id=$1", [ + userId, + ]); + await queueUserEmail( + c, + userId, + "Transaction PIN reset", + "Your transaction PIN was reset. If this was not you, secure your account and contact Quick Pay support.", + `pin-reset:${crypto.randomUUID()}`, + ); + }); + ensure(result); +} diff --git a/apps/api/src/v1/modules/users/routes/beneficiaries.ts b/apps/api/src/v1/modules/users/routes/beneficiaries.ts index 0f9a709..cd7a131 100644 --- a/apps/api/src/v1/modules/users/routes/beneficiaries.ts +++ b/apps/api/src/v1/modules/users/routes/beneficiaries.ts @@ -1,3 +1,4 @@ +import { phone } from "@quickpay/contracts"; import { z } from "zod"; import { pool } from "@quickpay/database"; import { identity } from "../../../../shared/auth"; @@ -40,6 +41,17 @@ export async function beneficiaries(req: Request) { }), }), ); + const service = v.details.serviceId + ? ( + await pool.query("SELECT category FROM service_catalog WHERE id=$1", [ + v.details.serviceId, + ]) + ).rows[0] + : null; + if (v.kind === "phone" || ["airtime", "data"].includes(service?.category)) { + v.details.account = phone.parse(v.details.account); + v.kind = "phone"; + } const id = crypto.randomUUID(); await pool.query( "INSERT INTO beneficiaries(id,user_id,name,kind,details) VALUES($1,$2,$3,$4,$5)", diff --git a/apps/api/src/v1/modules/wallets/routes/capabilities.ts b/apps/api/src/v1/modules/wallets/routes/capabilities.ts index d2fa60f..321b00c 100644 --- a/apps/api/src/v1/modules/wallets/routes/capabilities.ts +++ b/apps/api/src/v1/modules/wallets/routes/capabilities.ts @@ -1,12 +1,14 @@ import { identity } from "../../../../shared/auth"; import { json } from "../../../../shared/infrastructure/http"; -import { env } from "../../../../shared/infrastructure/env"; -import { paystackConfigured } from "../../deposits/providers/paystack"; +import { + paystackConfigured, + withdrawalsConfigured, +} from "../../deposits/providers/paystack"; import { walletLimits } from "../domain/limits"; export async function walletCapabilities(req: Request) { await identity(req); const deposit = paystackConfigured(); - const withdrawal = deposit && env().PAYSTACK_TRANSFERS_ENABLED === "true"; + const withdrawal = withdrawalsConfigured(); return json({ currency: "NGN", deposit: { diff --git a/apps/api/src/v1/modules/withdrawals/routes/handler.ts b/apps/api/src/v1/modules/withdrawals/routes/handler.ts index c6bebc1..954d574 100644 --- a/apps/api/src/v1/modules/withdrawals/routes/handler.ts +++ b/apps/api/src/v1/modules/withdrawals/routes/handler.ts @@ -1,15 +1,30 @@ import { z } from "zod"; import { pool } from "@quickpay/database"; +import { assert } from "../../../../shared/errors"; import { identity } from "../../../../shared/auth"; import { body, json, rateLimit } from "../../../../shared/infrastructure/http"; import { hash } from "../../../../shared/infrastructure/security"; -import { paystack } from "../../deposits/providers/paystack"; +import { + paystack, + resolvedBankAccountSchema, +} from "../../deposits/providers/paystack"; export async function banks(req: Request) { await identity(req); - const banks = await paystack( - "bank?country=nigeria¤cy=NGN", - z.array(z.object({ name: z.string(), code: z.string() })), - ); + const banks: { name: string; code: string }[] = []; + const seen = new Set(); + for (let page = 1; page <= 20; page++) { + const entries = await paystack( + `bank?country=nigeria¤cy=NGN&perPage=100&page=${page}`, + z.array(z.object({ name: z.string(), code: z.string() })), + ); + const fresh = entries.filter((bank) => !seen.has(bank.code)); + for (const bank of fresh) { + banks.push(bank); + seen.add(bank.code); + } + if (entries.length < 100 || fresh.length === 0) break; + } + banks.sort((a, b) => a.name.localeCompare(b.name)); return json({ banks }); } export async function resolveBank(req: Request) { @@ -24,7 +39,13 @@ export async function resolveBank(req: Request) { ); const result = await paystack( `bank/resolve?account_number=${v.accountNumber}&bank_code=${v.bankCode}`, - z.object({ account_number: z.string(), account_name: z.string() }), + resolvedBankAccountSchema, + ); + assert( + result.account_number === v.accountNumber, + "ACCOUNT_MISMATCH", + "The bank returned a different account. Please verify your details again.", + 422, ); const id = crypto.randomUUID(); await pool.query( diff --git a/apps/mobile/package.json b/apps/mobile/package.json index dfcc166..8f9ca84 100644 --- a/apps/mobile/package.json +++ b/apps/mobile/package.json @@ -34,6 +34,7 @@ "expo-notifications": "~57.0.25", "expo-router": "~57.0.30", "expo-secure-store": "~57.0.4", + "expo-sharing": "~57.0.25", "expo-splash-screen": "~57.0.11", "expo-status-bar": "~57.0.1", "expo-system-ui": "57.0.4", @@ -46,6 +47,7 @@ "react-native": "0.86.3", "react-native-css-interop": "0.2.7", "react-native-gesture-handler": "~2.32.0", + "react-native-qrcode-svg": "^6.3.53", "react-native-reanimated": "4.5.1", "react-native-safe-area-context": "~5.7.0", "react-native-screens": "~4.26.0", diff --git a/apps/mobile/src/features/auth/components/sign-up-form/SignUpForm.tsx b/apps/mobile/src/features/auth/components/sign-up-form/SignUpForm.tsx index eaea254..ea52dd5 100644 --- a/apps/mobile/src/features/auth/components/sign-up-form/SignUpForm.tsx +++ b/apps/mobile/src/features/auth/components/sign-up-form/SignUpForm.tsx @@ -52,7 +52,7 @@ export function SignUpForm() { name="phoneNumber" label="Phone number" keyboardType="phone-pad" - placeholder="0801 234 5678" + placeholder="0803 123 4567" autoComplete="tel" textContentType="telephoneNumber" /> diff --git a/apps/mobile/src/features/beneficiaries/screens/BeneficiariesScreen.tsx b/apps/mobile/src/features/beneficiaries/screens/BeneficiariesScreen.tsx index 940f1d6..4a28d31 100644 --- a/apps/mobile/src/features/beneficiaries/screens/BeneficiariesScreen.tsx +++ b/apps/mobile/src/features/beneficiaries/screens/BeneficiariesScreen.tsx @@ -1,7 +1,7 @@ import { useState } from "react"; import { router, useLocalSearchParams } from "expo-router"; import { z } from "zod"; -import type { Beneficiary, Service } from "@quickpay/contracts"; +import { phone, type Beneficiary, type Service } from "@quickpay/contracts"; import { mutation } from "@quickpay/api-client"; import { api } from "../../../services/api"; import { useResource } from "../../../services/api/use-resource"; @@ -129,6 +129,8 @@ export function BeneficiariesScreen() { const service = catalog.data?.services.find( (s) => s.id === v.serviceId, ); + if (service && ["airtime", "data"].includes(service.category)) + v.account = phone.parse(v.account); await api( "/beneficiaries", mutation({ diff --git a/apps/mobile/src/features/bills/screens/BillsScreen.tsx b/apps/mobile/src/features/bills/screens/BillsScreen.tsx index f0f79bd..cd5842a 100644 --- a/apps/mobile/src/features/bills/screens/BillsScreen.tsx +++ b/apps/mobile/src/features/bills/screens/BillsScreen.tsx @@ -53,9 +53,13 @@ export function BillsScreen() { ); const form = useValidatedForm( z.object({ - beneficiary: z.string().trim().min(3, "Enter the recipient’s details."), + beneficiary: ["airtime", "data"].includes(category) + ? phone + : z.string().trim().min(3, "Enter the recipient’s details."), amount: z.string(), - phone: z.string(), + phone: ["airtime", "data"].includes(category) + ? z.union([z.literal(""), phone]) + : phone, }), { beneficiary: params.account || "", amount: "", phone: "" }, ); @@ -256,7 +260,7 @@ export function BillsScreen() { fee={service.fee} recipient={review.recipient} onClose={() => setReview(null)} - onConfirm={async (password) => { + onConfirm={async (pin) => { if (review.expires < Date.now()) throw new Error("Check the recipient again before paying."); const v = form.getValues(); @@ -273,7 +277,7 @@ export function BillsScreen() { ? { validationId: review.validationId } : {}), }, - password, + pin, ); form.reset(); router.replace(`/(customer)/transactions/${t.id}`); diff --git a/apps/mobile/src/features/referrals/screens/ReferralsScreen.tsx b/apps/mobile/src/features/referrals/screens/ReferralsScreen.tsx index e95483e..2a72300 100644 --- a/apps/mobile/src/features/referrals/screens/ReferralsScreen.tsx +++ b/apps/mobile/src/features/referrals/screens/ReferralsScreen.tsx @@ -11,7 +11,7 @@ import { siteUrl } from "../../../lib/config"; import { Screen } from "../../../components/layout/screen"; import { Button } from "../../../components/ui/button"; import { Card, Row } from "../../../components/ui/card/Card"; -import { PasswordInput } from "../../../components/ui/password-input"; +import { TransactionPinInput } from "../../security/components/TransactionPinInput"; import { Sheet } from "../../../components/ui/bottom-sheet/Sheet"; import { Notice, @@ -26,7 +26,7 @@ export function ReferralsScreen() { const referrals = useResource("/referrals"), rule = useResource<{ summary: string }>("/rewards/active-rule"); const [claim, setClaim] = useState(null), - [password, setPassword] = useState(""), + [pin, setPin] = useState(""), [busy, setBusy] = useState(false), [message, setMessage] = useState(""); return ( @@ -118,27 +118,22 @@ export function ReferralsScreen() { onClose={() => { if (!busy) { setClaim(null); - setPassword(""); + setPin(""); } }} > Claim your reward. - + ) : ( - - Set up two-step verification in Settings + + Set up your authenticator in Settings (use your existing login + password, then the app-generated code) )} diff --git a/apps/web/src/features/auth/components/sign-up-form/SignUpForm.tsx b/apps/web/src/features/auth/components/sign-up-form/SignUpForm.tsx index bce96a2..67c87ec 100644 --- a/apps/web/src/features/auth/components/sign-up-form/SignUpForm.tsx +++ b/apps/web/src/features/auth/components/sign-up-form/SignUpForm.tsx @@ -108,7 +108,7 @@ export function SignUpForm() { type="tel" inputMode="tel" autoComplete="tel" - placeholder="0801 234 5678" + placeholder="0803 123 4567" required error={errors.phoneNumber} /> diff --git a/apps/web/src/features/beneficiaries/BeneficiariesPage.tsx b/apps/web/src/features/beneficiaries/BeneficiariesPage.tsx index 75c569d..1c28417 100644 --- a/apps/web/src/features/beneficiaries/BeneficiariesPage.tsx +++ b/apps/web/src/features/beneficiaries/BeneficiariesPage.tsx @@ -3,7 +3,7 @@ import { useState } from "react"; import { toast } from "sonner"; import { Trash2 } from "lucide-react"; import { api, mutation } from "@quickpay/api-client"; -import type { Service } from "@quickpay/contracts"; +import { phone, type Service } from "@quickpay/contracts"; import { useApi } from "../../lib/use-api"; import { Field } from "../../components/ui/form-field"; import { inputClass } from "../../components/ui/password-input"; @@ -30,6 +30,18 @@ export function BeneficiariesPage() { v = Object.fromEntries(new FormData(form)); setBusy(true); try { + if ( + v.kind === "phone" || + ["airtime", "data"].includes( + catalog.data?.services.find((s) => s.id === v.serviceId)?.category || + "", + ) + ) { + const parsed = phone.safeParse(v.account); + if (!parsed.success) throw new Error(parsed.error.issues[0].message); + v.account = parsed.data; + v.kind = "phone"; + } await api( "/beneficiaries", mutation({ diff --git a/apps/web/src/features/bills/BillsPage.tsx b/apps/web/src/features/bills/BillsPage.tsx index ffc48ef..fbbe920 100644 --- a/apps/web/src/features/bills/BillsPage.tsx +++ b/apps/web/src/features/bills/BillsPage.tsx @@ -1,4 +1,5 @@ "use client"; +import { TransactionPinField } from "../security/TransactionPinField"; import { useState, useEffect } from "react"; import { useRouter } from "next/navigation"; import { @@ -13,6 +14,7 @@ import { import { api, mutation } from "@quickpay/api-client"; import { categories, + phone, parseNaira, formatMoney, type Service, @@ -20,7 +22,7 @@ import { } from "@quickpay/contracts"; import { useApi } from "../../lib/use-api"; import { Field } from "../../components/ui/form-field"; -import { PasswordInput, inputClass } from "../../components/ui/password-input"; +import { inputClass } from "../../components/ui/password-input"; import { Button } from "../../components/ui/button"; import { LoadingState, @@ -69,6 +71,7 @@ export function BillsPage({ [validation, setValidation] = useState<{ id: string; name: string }>(), [error, setError] = useState(""), [busy, setBusy] = useState(false), + [pinReady, setPinReady] = useState(false), [key, setKey] = useState(() => crypto.randomUUID()); useEffect(() => { if (!initialCategory) { @@ -116,6 +119,14 @@ export function BillsPage({ setError(""); setBusy(true); try { + if (["airtime", "data"].includes(service.category)) { + const parsed = phone.safeParse(data.beneficiary); + if (!parsed.success) throw new Error(parsed.error.issues[0].message); + } + if (data.phone) { + const parsed = phone.safeParse(data.phone); + if (!parsed.success) throw new Error(parsed.error.issues[0].message); + } if (step === 1) { parseNaira(data.amount); if (service.requiresValidation) { @@ -144,12 +155,14 @@ export function BillsPage({ ...(data.plan ? { plan: data.plan } : {}), ...(data.phone ? { phone: data.phone } : {}), validationId: validation?.id, - password: new FormData(e.currentTarget).get("password"), + pin: new FormData(e.currentTarget).get("pin"), }, key, ), ); - router.push(`/transactions/detail?id=${encodeURIComponent(r.transaction.id)}`); + router.push( + `/transactions/detail?id=${encodeURIComponent(r.transaction.id)}`, + ); } } catch (e) { setError(e instanceof Error ? e.message : "Please try again."); @@ -336,6 +349,11 @@ export function BillsPage({ ? "Smartcard number" : "Account or phone number" } + type={ + ["airtime", "data"].includes(service?.category || "") + ? "tel" + : "text" + } id="beneficiary" value={data.beneficiary} onChange={(e) => @@ -447,13 +465,7 @@ export function BillsPage({ ))} - +

Check the recipient carefully. Once confirmed, your payment may not be refundable. @@ -461,7 +473,10 @@ export function BillsPage({ )} {error && } - + + +

+ )} + + + + + ); +} diff --git a/apps/web/src/features/security/TransactionPinField.tsx b/apps/web/src/features/security/TransactionPinField.tsx new file mode 100644 index 0000000..37ecb80 --- /dev/null +++ b/apps/web/src/features/security/TransactionPinField.tsx @@ -0,0 +1,75 @@ +"use client"; +import { useEffect } from "react"; +import { useRouter } from "next/navigation"; +import { ShieldCheck } from "lucide-react"; +import { useApi } from "../../lib/use-api"; +import { PasswordInput } from "../../components/ui/password-input"; +export function TransactionPinField({ + onReady, +}: { + onReady?: (ready: boolean) => void; +}) { + const status = useApi<{ configured: boolean }>("/security/pin"), + router = useRouter(); + useEffect(() => { + onReady?.(!!status.data?.configured && !status.error); + }, [status.data?.configured, status.error, onReady]); + if (status.data && !status.data.configured) + return ( +
+ +

Set up your transaction PIN to continue

+

+ Protect your payments with a six-digit PIN. You’ll confirm your + current login password and choose a new PIN in Settings, then return + here. No payment has been submitted. +

+ +
+ ); + return ( +
+ +

+ Enter your six-digit payment PIN. It is different from your login + password and authenticator code. +

+ {status.error && ( +

+ {status.error}{" "} + +

+ )} +
+ ); +} diff --git a/apps/web/src/features/settings/SettingsPage.tsx b/apps/web/src/features/settings/SettingsPage.tsx index 9908dec..f52ba75 100644 --- a/apps/web/src/features/settings/SettingsPage.tsx +++ b/apps/web/src/features/settings/SettingsPage.tsx @@ -1,4 +1,6 @@ "use client"; +import QRCode from "react-qr-code"; +import { PinSettings } from "../security/PinSettings"; import { useState } from "react"; import { toast } from "sonner"; import { api, mutation } from "@quickpay/api-client"; @@ -37,7 +39,9 @@ export function SettingsPage() { toast.success( task === "email" ? "A verification link is on its way." - : "Your settings have been updated.", + : task === "mfa" + ? "Scan the QR code, then confirm the code generated by your authenticator." + : "Your settings have been updated.", ); await r.refresh(); return result; @@ -165,12 +169,16 @@ export function SettingsPage() { /> -
+ +

Two-step verification

{u.two_factor_enabled ? "Your authenticator adds an extra step when you sign in." - : "Protect your account with an authenticator app. Required for administrators."} + : "First enter your existing Quick Pay login password to authorize setup. Then scan the QR code in an authenticator app and enter its generated code. Do not choose a new password or a random code here. Required for administrators."}

{!u.two_factor_enabled && !setup && (
@@ -199,8 +207,13 @@ export function SettingsPage() { {setup && (

Add Quick Pay to your authenticator

+
+ +

- Choose “Enter setup key” in your app. Keep this key private. + Scan this QR code in Google Authenticator, Microsoft + Authenticator or a similar app, or choose “Enter setup key” in + your app. Keep this key private.

{new URL(setup.totpURI).searchParams.get("secret")} @@ -226,12 +239,13 @@ export function SettingsPage() { className="space-y-4" > diff --git a/apps/web/src/features/transactions/ReceiptMenu.tsx b/apps/web/src/features/transactions/ReceiptMenu.tsx new file mode 100644 index 0000000..ae2841d --- /dev/null +++ b/apps/web/src/features/transactions/ReceiptMenu.tsx @@ -0,0 +1,92 @@ +"use client"; +import { useState } from "react"; +import { SlidersHorizontal } from "lucide-react"; +import { toast } from "sonner"; +import { webConnection } from "@quickpay/api-client"; +export function ReceiptMenu({ id }: { id: string }) { + const [open, setOpen] = useState(false), + [busy, setBusy] = useState(false); + async function exportFile(format: "pdf" | "png", share: boolean) { + setOpen(false); + setBusy(true); + try { + const response = await webConnection.fetch( + `/api/v1/payments/${encodeURIComponent(id)}/receipt?format=${format}`, + { credentials: "include" }, + ); + if (!response.ok) + throw new Error( + "We could not generate your receipt. Please try again.", + ); + const blob = await response.blob(); + const file = new File([blob], `QuickPay-receipt-${id}.${format}`, { + type: blob.type, + }); + if (share && navigator.canShare?.({ files: [file] })) { + await navigator.share({ files: [file], title: "Quick Pay receipt" }); + } else { + const url = URL.createObjectURL(file), + link = document.createElement("a"); + link.href = url; + link.download = file.name; + document.body.append(link); + link.click(); + link.remove(); + setTimeout(() => URL.revokeObjectURL(url), 60000); + if (share) + toast.info( + "File sharing is unavailable in this browser. Your receipt was downloaded instead.", + ); + } + } catch (error) { + if (!(error instanceof Error && error.name === "AbortError")) + toast.error( + error instanceof Error ? error.message : "Please try again.", + ); + } finally { + setBusy(false); + } + } + return ( +
+ + {open && ( +
+ {( + [ + ["Download PDF", "pdf", false], + ["Download image", "png", false], + ["Share PDF", "pdf", true], + ["Share image", "png", true], + ] as const + ).map(([label, format, share]) => ( + + ))} +
+ )} +
+ ); +} diff --git a/apps/web/src/features/transactions/TransactionDetails.tsx b/apps/web/src/features/transactions/TransactionDetails.tsx index faa5a00..41e1df4 100644 --- a/apps/web/src/features/transactions/TransactionDetails.tsx +++ b/apps/web/src/features/transactions/TransactionDetails.tsx @@ -2,27 +2,44 @@ import { useEffect, useState } from "react"; import Link from "next/link"; import { toast } from "sonner"; -import { ArrowLeft, Printer, RefreshCw, ExternalLink } from "lucide-react"; +import { ArrowLeft, RefreshCw, ExternalLink } from "lucide-react"; import { api, mutation } from "@quickpay/api-client"; -import { formatMoney, type Transaction } from "@quickpay/contracts"; +import { + formatMoney, + isDepositPreparing, + paystackCheckoutUrl, + shouldRefreshTransaction, + type Transaction, +} from "@quickpay/contracts"; import { useApi } from "../../lib/use-api"; import { StatusBadge } from "../../components/ui/status-badge"; import { Button } from "../../components/ui/button"; import { LoadingState, ErrorState } from "../../components/feedback"; +import { ReceiptMenu } from "./ReceiptMenu"; export function TransactionDetails({ id }: { id: string }) { const { data, error, loading, refresh } = useApi<{ transaction: Transaction; }>(`/payments/${id}`); const [busy, setBusy] = useState(false); const t = data?.transaction; + const preparing = t ? isDepositPreparing(t) : false; useEffect(() => { - if (!t || !["processing", "awaiting_authorization"].includes(t.status)) - return; - const timer = setInterval(() => { - void refresh(); - }, 5000); - return () => clearInterval(timer); - }, [t?.status, refresh]); + if (!t || !shouldRefreshTransaction(t)) return; + const focus = () => { + if (document.visibilityState === "visible") void refresh(); + }; + const timer = setInterval( + () => { + if (document.visibilityState === "visible") void refresh(); + }, + preparing ? 2000 : 30000, + ); + document.addEventListener("visibilitychange", focus); + return () => { + clearInterval(timer); + document.removeEventListener("visibilitychange", focus); + }; + }, [t?.status, preparing, refresh]); async function check() { setBusy(true); try { @@ -39,9 +56,10 @@ export function TransactionDetails({ id }: { id: string }) { } } if (loading) return ; - if (error) return ; + if (error && !data) return ; if (!t) return null; const success = t.status === "successful"; + const checkout = paystackCheckoutUrl(t.details.checkoutUrl); return (

- {success ? "Payment receipt" : "Payment details"} + {preparing + ? "Preparing your checkout" + : success + ? "Payment receipt" + : t.kind === "deposit" && + checkout && + ["processing", "awaiting_authorization"].includes(t.status) + ? "Complete your deposit" + : "Payment details"}

- +
+ + +

{formatMoney(t.amount)} @@ -116,29 +145,37 @@ export function TransactionDetails({ id }: { id: string }) { aria-live="polite" className="my-5 rounded-xl bg-amber-50 p-4 text-sm text-amber-900" > - {t.status === "awaiting_authorization" - ? "Complete your checkout to add money." - : "We are checking your payment. Please check this transaction before trying again."} + {preparing + ? "We’re preparing your secure Paystack checkout. Your wallet is credited only after you complete payment. Checkout will appear here automatically." + : t.kind === "deposit" && checkout + ? "Complete your checkout to add money." + : "We are checking your payment. Please check this transaction before trying again."}

)}
- {!!t.details.checkoutUrl && t.status === "awaiting_authorization" && ( - - Open secure checkout - - )} - {success ? ( - - ) : ( + {checkout && + t.kind === "deposit" && + ["awaiting_authorization", "processing", "failed"].includes( + t.status, + ) && ( + + {t.status === "failed" + ? "Try secure checkout again" + : "Open secure checkout"}{" "} + + + )} + {shouldRefreshTransaction(t) && ( )} void; + disabled?: boolean; +}) { + const id = useId(), + root = useRef(null), + trigger = useRef(null); + const [open, setOpen] = useState(false), + [search, setSearch] = useState(""), + [active, setActive] = useState(0); + const filtered = banks.filter((b) => + b.name.toLowerCase().includes(search.trim().toLowerCase()), + ); + useEffect(() => { + const close = (e: PointerEvent) => { + if (!root.current?.contains(e.target as Node)) setOpen(false); + }; + document.addEventListener("pointerdown", close); + return () => document.removeEventListener("pointerdown", close); + }, []); + useEffect(() => { + if (open) + document + .getElementById(`${id}-option-${active}`) + ?.scrollIntoView({ block: "nearest" }); + }, [active, open, id]); + const choose = (code: string) => { + onChange(code); + setOpen(false); + trigger.current?.focus(); + }; + return ( +
+ + + {open && ( +
+
+ + { + setSearch(e.target.value); + setActive(0); + }} + onKeyDown={(e) => { + if (e.key === "Escape") { + e.preventDefault(); + setOpen(false); + trigger.current?.focus(); + } else if (e.key === "Tab") setOpen(false); + else if (e.key === "ArrowDown" || e.key === "ArrowUp") { + e.preventDefault(); + setActive((n) => + Math.max( + 0, + Math.min( + filtered.length - 1, + n + (e.key === "ArrowDown" ? 1 : -1), + ), + ), + ); + } else if (e.key === "Enter") { + e.preventDefault(); + if (filtered[active]) choose(filtered[active].code); + } + }} + className="min-h-11 w-full min-w-0 bg-transparent text-sm outline-none" + /> +
+
+ {filtered.map((b, i) => ( + + ))} + {!filtered.length && ( +

+ No matching banks. Try another name. +

+ )} +
+
+ )} +
+ ); +} diff --git a/apps/web/src/features/wallet/DepositPage.tsx b/apps/web/src/features/wallet/DepositPage.tsx index c9edfe5..cf597d6 100644 --- a/apps/web/src/features/wallet/DepositPage.tsx +++ b/apps/web/src/features/wallet/DepositPage.tsx @@ -1,4 +1,5 @@ "use client"; +import { TransactionPinField } from "../security/TransactionPinField"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { api, mutation } from "@quickpay/api-client"; @@ -8,6 +9,7 @@ import { Button } from "../../components/ui/button"; import { ErrorState } from "../../components/feedback"; export function DepositPage() { const [busy, setBusy] = useState(false), + [pinReady, setPinReady] = useState(false), [error, setError] = useState(""), [key] = useState(() => crypto.randomUUID()); const router = useRouter(); @@ -21,9 +23,14 @@ export function DepositPage() { ); const r = await api<{ transaction: Transaction }>( "/deposits", - mutation({ amount }, key), + mutation( + { amount, pin: new FormData(e.currentTarget).get("pin") }, + key, + ), + ); + router.push( + `/transactions/detail?id=${encodeURIComponent(r.transaction.id)}`, ); - router.push(`/transactions/detail?id=${encodeURIComponent(r.transaction.id)}`); } catch (e) { setError(e instanceof Error ? e.message : "Please try again."); } finally { @@ -52,8 +59,9 @@ export function DepositPage() { placeholder="5,000" />

Minimum ₦100. Maximum ₦1,000,000.

+ {error && } - diff --git a/apps/web/src/features/wallet/WithdrawalPage.tsx b/apps/web/src/features/wallet/WithdrawalPage.tsx index f68f798..b82b87f 100644 --- a/apps/web/src/features/wallet/WithdrawalPage.tsx +++ b/apps/web/src/features/wallet/WithdrawalPage.tsx @@ -1,10 +1,11 @@ "use client"; +import { TransactionPinField } from "../security/TransactionPinField"; import { useState } from "react"; import { useRouter } from "next/navigation"; import { api, mutation } from "@quickpay/api-client"; import { formatMoney, parseNaira, type Transaction } from "@quickpay/contracts"; import { Field } from "../../components/ui/form-field"; -import { PasswordInput, inputClass } from "../../components/ui/password-input"; +import { BankSelect } from "./BankSelect"; import { Button } from "../../components/ui/button"; import { ErrorState } from "../../components/feedback"; import { useApi } from "../../lib/use-api"; @@ -18,6 +19,7 @@ export function WithdrawalPage() { }), [validation, setValidation] = useState<{ id: string; name: string }>(), [review, setReview] = useState(false), + [pinReady, setPinReady] = useState(false), [busy, setBusy] = useState(false), [error, setError] = useState(""), [key] = useState(() => crypto.randomUUID()); @@ -30,6 +32,11 @@ export function WithdrawalPage() { setBusy(true); setError(""); try { + if (!data.bankCode) + throw new Error("Choose a bank before checking the account."); + const amount = BigInt(parseNaira(data.amount)); + if (amount < 10000n || amount > 100000000n) + throw new Error("Withdraw between ₦100 and ₦1,000,000."); const v = await api<{ id: string; name: string }>( "/banks/resolve", mutation({ @@ -37,7 +44,6 @@ export function WithdrawalPage() { accountNumber: data.accountNumber, }), ); - parseNaira(data.amount); setValidation(v); setReview(true); } catch (e) { @@ -62,12 +68,14 @@ export function WithdrawalPage() { ...data, amount: parseNaira(data.amount), validationId: validation?.id, - password: new FormData(e.currentTarget).get("password"), + pin: new FormData(e.currentTarget).get("pin"), }, key, ), ); - router.push(`/transactions/detail?id=${encodeURIComponent(r.transaction.id)}`); + router.push( + `/transactions/detail?id=${encodeURIComponent(r.transaction.id)}`, + ); } catch (e) { setError(e instanceof Error ? e.message : "Please try again."); } finally { @@ -83,33 +91,19 @@ export function WithdrawalPage() { Check the account name before you confirm. Money is reserved while your transfer is being processed.

- {banks.error && } + {banks.error && ( + + )}
-
- - -
+ change("bankCode", value)} + disabled={busy || !banks.data?.banks.length} + /> change("accountNumber", e.target.value)} inputMode="numeric" pattern="[0-9]{10}" + maxLength={10} required />
- + )} {error && } - `, + }), + ); + await page.getByRole("link", { name: "Open secure checkout" }).click(); + await expect( + page.getByRole("heading", { name: "Provider checkout fixture" }), + ).toBeVisible(); + // Reproduce an old failure while the customer is away at checkout. + await db.query("UPDATE transactions SET status='failed' WHERE id=$1", [ + depositId, + ]); + await page + .getByRole("button", { name: "Complete checkout", exact: true }) + .click(); + await expect(page).toHaveURL( + new RegExp(`transactions/detail.*${depositId}`), + ); + await settled(depositId); + expect( + ( + await db.query( + "SELECT balance FROM ledger_accounts WHERE user_id=$1 AND bucket='available'", + [user.id], + ) + ).rows[0].balance, + ).toBe("100000"); + await request.post(`http://127.0.0.1:3190/__qa/checkout/${reference}`); + expect( + ( + await db.query( + "SELECT count(*)::int AS count FROM journals WHERE reference=$1", + [`deposit:${depositId}`], + ) + ).rows[0].count, + ).toBe(1); + await page.getByRole("button", { name: "Receipt options" }).click(); + const download = page.waitForEvent("download"); + await page + .getByRole("menuitem", { name: "Download PDF", exact: true }) + .click(); + const pdf = await download; + expect( + (await readFile((await pdf.path())!)).subarray(0, 4).toString(), + ).toBe("%PDF"); + + await page.goto("/withdraw"); + await page.getByRole("combobox", { name: "Bank", exact: true }).click(); + await page.getByRole("searchbox", { name: "Search banks" }).fill("QA Test"); + await expect( + page.getByRole("option", { name: "Another QA Bank" }), + ).toHaveCount(0); + await page + .getByRole("option", { name: "QA Test Bank", exact: true }) + .click(); + await page.getByLabel("Account number").fill("1234567890"); + await page.getByLabel("Amount (₦)").fill("250"); + await page + .getByRole("button", { name: "Check account and review" }) + .click(); + await expect( + page.getByText("QA BANK CUSTOMER", { exact: true }), + ).toBeVisible(); + expect( + ( + await db.query( + "SELECT 1 FROM transactions WHERE user_id=$1 AND kind='withdrawal'", + [user.id], + ) + ).rowCount, + ).toBe(0); + expect( + (await (await request.get("http://127.0.0.1:3190/__qa/stats")).json()) + .bankResolves, + ).toBe(2); + await page.getByLabel("Transaction PIN", { exact: true }).fill(pin); + await page.getByRole("button", { name: "Confirm withdrawal" }).click(); + await expect(page).toHaveURL(/transactions\/detail/); + const withdrawalId = new URL(page.url()).searchParams.get("id")!; + await settled(withdrawalId); + + await db.query( + "INSERT INTO service_catalog(id,name,category,provider,min,max,enabled) VALUES('qa-mtn','QA MTN airtime','airtime','vtpass',5000,10000000,true) ON CONFLICT(id) DO UPDATE SET enabled=true", + ); + await page.goto("/airtime"); + await page.getByRole("button", { name: /QA MTN airtime/ }).click(); + await page.getByLabel("Nigerian phone number").fill("08031234567"); + await page.getByLabel("Amount (₦)").fill("100"); + await page.getByRole("button", { name: "Review payment" }).click(); + await page.getByLabel("Transaction PIN", { exact: true }).fill(pin); + await page.getByRole("button", { name: "Confirm and pay" }).click(); + await expect(page).toHaveURL(/transactions\/detail/); + await settled(new URL(page.url()).searchParams.get("id")!); + const balances = ( + await db.query( + "SELECT bucket,balance FROM ledger_accounts WHERE user_id=$1 AND bucket IN ('available','reserved')", + [user.id], + ) + ).rows; + expect( + Object.fromEntries(balances.map((row) => [row.bucket, row.balance])), + ).toEqual({ available: "65000", reserved: "0" }); + await page.goto("/settings#transaction-pin"); + await page + .getByRole("button", { name: "Forgot your transaction PIN?" }) + .click(); + await page + .getByLabel("Current login password", { exact: true }) + .fill(password); + await page + .getByRole("button", { name: "Email me a reset code", exact: true }) + .click(); + let resetMail: + | { subject: string; text: string; branded: boolean } + | undefined; + await expect + .poll(async () => { + const mail = (await ( + await request.get("http://127.0.0.1:3190/__qa/mail") + ).json()) as { subject: string; text: string; branded: boolean }[]; + resetMail = mail.find( + (item: { + to?: string; + subject: string; + text: string; + branded: boolean; + }) => + item.to === email && item.subject === "Reset your transaction PIN", + ); + return !!resetMail; + }) + .toBe(true); + expect(resetMail!.branded).toBe(true); + const code = resetMail!.text.match(/\b\d{6}\b/)![0]; + await page.getByLabel("Code sent to your verified email").fill(code); + await page + .getByLabel("New transaction PIN", { exact: true }) + .fill("684207"); + await page + .getByLabel("Confirm transaction PIN", { exact: true }) + .fill("684207"); + await page + .getByRole("button", { name: "Reset transaction PIN", exact: true }) + .click(); + await expect( + page + .getByRole("status") + .filter({ hasText: "Your transaction PIN has been reset." }), + ).toBeVisible(); + await page + .getByLabel("Current login password", { exact: true }) + .fill(password); + await page + .getByLabel("Current transaction PIN", { exact: true }) + .fill("684207"); + await page.getByLabel("New transaction PIN", { exact: true }).fill(pin); + await page.getByLabel("Confirm transaction PIN", { exact: true }).fill(pin); + await page + .getByRole("button", { name: "Change transaction PIN", exact: true }) + .click(); + await expect( + page + .getByRole("status") + .filter({ hasText: "Your transaction PIN is ready." }), + ).toBeVisible(); + const emails = (await ( + await request.get("http://127.0.0.1:3190/__qa/mail") + ).json()) as { to: string; subject: string; branded: boolean }[]; + expect( + emails.some( + (item) => + item.to === email && item.subject === "New sign-in to Quick Pay", + ), + ).toBe(true); + expect( + emails.some( + (item) => + item.to === email && item.subject === "Transaction successful", + ), + ).toBe(true); + expect(emails.every((item) => item.branded)).toBe(true); + expect(errors).toEqual([]); + } finally { + await db.end(); + } +}); diff --git a/tests/browser/quickpay.spec.ts b/tests/browser/quickpay.spec.ts index c89ab9d..af1dc1e 100644 --- a/tests/browser/quickpay.spec.ts +++ b/tests/browser/quickpay.spec.ts @@ -77,7 +77,7 @@ const transaction = { reference: "browser-illustration", createdAt: new Date().toISOString(), serviceId: "mtn", - details: { beneficiary: "08012345678" }, + details: { beneficiary: "08031234567" }, }; // UI fixtures exist only in the browser test harness, never in the runtime adapters. async function fixture( @@ -95,27 +95,29 @@ async function fixture( const custom = extra(path, req.method(), body); const data = custom ?? - (path === "/health" - ? { status: "ok" } - : path === "/admin/access" - ? { allowed: true, mfaEnabled: true } - : path === "/auth/get-session" - ? session - : path === "/profile" - ? { user: { name: "Browser Test", email_verified: true } } - : path === "/wallet" - ? { - available: "2500000", - reserved: "0", - rewards: "0", - reward_debt: "0", - currency: "NGN", - } - : path.startsWith("/payments/") - ? { transaction } - : path === "/payments" - ? { transactions: [] } - : {}); + (path === "/security/pin" + ? { configured: true } + : path === "/health" + ? { status: "ok" } + : path === "/admin/access" + ? { allowed: true, mfaEnabled: true } + : path === "/auth/get-session" + ? session + : path === "/profile" + ? { user: { name: "Browser Test", email_verified: true } } + : path === "/wallet" + ? { + available: "2500000", + reserved: "0", + rewards: "0", + reward_debt: "0", + currency: "NGN", + } + : path.startsWith("/payments/") + ? { transaction } + : path === "/payments" + ? { transactions: [] } + : {}); await route.fulfill({ status: 200, contentType: "application/json", @@ -285,7 +287,7 @@ test("signup password buttons, confirmation and unchecked terms validate", async await expect(page.getByRole("checkbox")).not.toBeChecked(); await page.getByLabel("Full name", { exact: true }).fill("Browser Test"); await page.getByLabel("Email address").fill("browser@example.com"); - await page.getByLabel("Nigerian phone number").fill("08012345678"); + await page.getByLabel("Nigerian phone number").fill("08031234567"); await page.locator("#password").fill("StrongPassword123!"); await page.locator("#confirmPassword").fill("DifferentPassword123!"); await page @@ -352,13 +354,11 @@ test("bill wizard reviews beneficiary, fee and total then shows pending state", }); await page.goto("/airtime"); await page.getByRole("button", { name: /MTN airtime/ }).click(); - await page.getByLabel("Nigerian phone number").fill("08012345678"); + await page.getByLabel("Nigerian phone number").fill("08031234567"); await page.getByLabel("Amount (₦)").fill("1000"); await page.getByRole("button", { name: "Review payment" }).click(); await expect(page.getByText("₦1,000.00").first()).toBeVisible(); - await page - .getByLabel("Confirm with your password", { exact: true }) - .fill("StrongPassword123!"); + await page.getByLabel("Transaction PIN", { exact: true }).fill("572904"); await page.getByRole("button", { name: "Confirm and pay" }).click(); await expect(page).toHaveURL(/\/transactions\//); await expect(page.getByText("processing", { exact: true })).toBeVisible(); @@ -370,7 +370,12 @@ test("withdrawal validates bank details before authorization and reservation", a let submitted: Record | undefined; await fixture(page, (path, method, body) => { if (path === "/banks") - return { banks: [{ name: "Browser test bank", code: "999" }] }; + return { + banks: [ + { name: "Browser test bank", code: "999" }, + { name: "Another bank", code: "888" }, + ], + }; if (path === "/banks/resolve") return { id: "22222222-2222-4222-8222-222222222222", @@ -382,14 +387,26 @@ test("withdrawal validates bank details before authorization and reservation", a } }); await page.goto("/withdraw"); - await page.getByLabel("Bank", { exact: true }).selectOption("999"); + await expect( + page.getByRole("searchbox", { name: "Search banks" }), + ).toHaveCount(0); + await page.getByRole("combobox", { name: "Bank", exact: true }).click(); + await page.getByRole("searchbox", { name: "Search banks" }).fill("Browser"); + await expect( + page.getByRole("option", { name: "Browser test bank" }), + ).toBeVisible(); + await expect(page.getByRole("option", { name: "Another bank" })).toHaveCount( + 0, + ); + await page.getByRole("option", { name: "Browser test bank" }).click(); + await expect( + page.getByRole("searchbox", { name: "Search banks" }), + ).toHaveCount(0); await page.getByLabel("Account number").fill("1234567890"); await page.getByLabel("Amount (₦)").fill("1000"); await page.getByRole("button", { name: "Check account and review" }).click(); await expect(page.getByText("BROWSER TEST", { exact: true })).toBeVisible(); - await page - .getByLabel("Confirm with your password", { exact: true }) - .fill("StrongPassword123!"); + await page.getByLabel("Transaction PIN", { exact: true }).fill("572904"); await page.getByRole("button", { name: "Confirm withdrawal" }).click(); await expect(page).toHaveURL(/transactions/); expect(submitted?.validationId).toBe("22222222-2222-4222-8222-222222222222"); @@ -457,3 +474,229 @@ test("unauthenticated API and unavailable provider operations fail closed", asyn }); expect(webhook.status()).toBe(401); }); + +test("transaction status refreshes quietly after thirty seconds and receipts download as files", async ({ + page, +}) => { + await page.clock.install(); + let completed = false; + await fixture(page, (path) => + path === `/payments/${transaction.id}` + ? { + transaction: { + ...transaction, + status: completed ? "successful" : "processing", + }, + } + : undefined, + ); + await page.route("**/receipt?format=pdf", (route) => + route.fulfill({ + contentType: "application/pdf", + body: Buffer.from("%PDF-1.7\nReceipt fixture"), + }), + ); + await page.goto(`/transactions/detail?id=${transaction.id}`); + await expect( + page.getByText(transaction.reference, { exact: true }), + ).toBeVisible(); + const original = await page + .getByText(transaction.reference, { exact: true }) + .elementHandle(); + completed = true; + await page.clock.runFor(30000); + await expect(page.getByText("successful", { exact: true })).toBeVisible(); + expect(await original!.evaluate((node) => node.isConnected)).toBe(true); + await page.getByRole("button", { name: "Receipt options" }).click(); + const download = page.waitForEvent("download"); + await page + .getByRole("menuitem", { name: "Download PDF", exact: true }) + .click(); + expect((await download).suggestedFilename()).toBe( + `QuickPay-receipt-${transaction.id}.pdf`, + ); +}); + +test("missing PIN explains setup before navigating and resumes deposit after saving", async ({ + page, +}) => { + let configured = false; + await fixture(page, (path, method, body) => { + if (path === "/security/pin") { + if (method === "POST") { + expect(body).toMatchObject({ + password: "StrongPassword123!", + newPin: "572904", + confirmPin: "572904", + }); + configured = true; + return { message: "Your transaction PIN is ready." }; + } + return { configured }; + } + if (path === "/wallet/capabilities") + return { + deposits: true, + withdrawals: true, + depositMethods: ["card"], + minimumDeposit: "10000", + maximumDeposit: "100000000", + withdrawalFee: "0", + }; + }); + await page.goto("/deposit"); + await expect(page).toHaveURL(/\/deposit\/?$/); + await expect( + page.getByText("Set up your transaction PIN to continue", { exact: true }), + ).toBeVisible(); + await expect( + page.getByRole("button", { name: "Continue to checkout", exact: true }), + ).toBeDisabled(); + await page + .getByRole("button", { name: "Set up PIN and continue", exact: true }) + .click(); + await expect(page).toHaveURL( + /settings\/?\?setup=pin&returnTo=.*#transaction-pin/, + ); + await expect( + page.getByRole("status").filter({ + hasText: "Set up your PIN below to continue with your payment.", + }), + ).toBeVisible(); + await page + .getByLabel("Current login password", { exact: true }) + .fill("StrongPassword123!"); + await page.getByLabel("New transaction PIN", { exact: true }).fill("572904"); + await page + .getByLabel("Confirm transaction PIN", { exact: true }) + .fill("572904"); + await page + .getByRole("button", { name: "Set transaction PIN", exact: true }) + .click(); + await expect(page).toHaveURL(/\/deposit\/?$/); + await expect( + page.getByLabel("Transaction PIN", { exact: true }), + ).toBeEditable(); +}); + +test("authenticator setup explains existing password and displays a local QR code", async ({ + page, +}) => { + await fixture(page, (path) => { + if (path === "/auth/two-factor/enable") + return { + totpURI: + "otpauth://totp/Quick%20Pay:browser?secret=JBSWY3DPEHPK3PXP&issuer=Quick%20Pay", + backupCodes: ["backup-one", "backup-two"], + }; + }); + await page.goto("/settings#authenticator"); + await expect( + page.getByText(/First enter your existing Quick Pay login password/), + ).toBeVisible(); + await page + .getByLabel("Existing login password", { exact: true }) + .fill("StrongPassword123!"); + await page + .getByRole("button", { name: "Set up authenticator", exact: true }) + .click(); + await expect(page.locator("#authenticator svg")).toBeVisible(); + await expect( + page.getByLabel("Six-digit code generated by your authenticator"), + ).toBeVisible(); + await expect( + page.getByText("JBSWY3DPEHPK3PXP", { exact: true }), + ).toBeVisible(); + await page.screenshot({ + path: "/tmp/quickpay-security-settings.png", + fullPage: true, + }); +}); + +test("deposit prepares checkout before offering payment status checks and refreshes without replacing the page", async ({ + page, +}) => { + await page.clock.install(); + let stage = "preparing"; + const deposit = { ...transaction, kind: "deposit", serviceId: null }; + await fixture(page, (path) => + path === `/payments/${transaction.id}` + ? { + transaction: { + ...deposit, + status: + stage === "completed" + ? "successful" + : stage === "ready" + ? "awaiting_authorization" + : "processing", + details: + stage === "preparing" + ? {} + : { + checkoutUrl: "https://checkout.paystack.com/local-checkout", + }, + }, + } + : undefined, + ); + await page.goto(`/transactions/detail?id=${transaction.id}`); + await expect( + page.getByRole("heading", { name: "Preparing your checkout" }), + ).toBeVisible(); + await expect( + page.getByRole("button", { name: "Check your payment", exact: true }), + ).toHaveCount(0); + const original = await page + .getByText(transaction.reference, { exact: true }) + .elementHandle(); + stage = "ready"; + await page.clock.runFor(2000); + await expect( + page.getByRole("link", { name: "Open secure checkout" }), + ).toHaveAttribute("href", "https://checkout.paystack.com/local-checkout"); + await expect( + page.getByRole("heading", { name: "Complete your deposit" }), + ).toBeVisible(); + stage = "completed"; + await page.clock.runFor(30000); + await expect(page.getByText("successful", { exact: true })).toBeVisible(); + expect(await original!.evaluate((node) => node.isConnected)).toBe(true); +}); + +test("bank picker filters in its open dropdown and supports keyboard selection without submitting", async ({ + page, +}) => { + let lookups = 0; + await fixture(page, (path) => { + if (path === "/banks") + return { + banks: [ + { code: "999", name: "OPay bank" }, + { code: "888", name: "Another bank" }, + ], + }; + if (path === "/banks/resolve") { + lookups++; + return {}; + } + }); + await page.goto("/withdraw"); + await page.getByRole("combobox", { name: "Bank", exact: true }).click(); + const search = page.getByRole("searchbox", { name: "Search banks" }); + await search.fill("no bank has this name"); + await expect( + page.getByText("No matching banks. Try another name."), + ).toBeVisible(); + await search.fill("opay"); + await expect(page.getByRole("option", { name: "OPay bank" })).toBeVisible(); + await expect(page.getByRole("option", { name: "Another bank" })).toHaveCount( + 0, + ); + await search.press("ArrowDown"); + await search.press("Enter"); + await expect( + page.getByRole("combobox", { name: "Bank", exact: true }), + ).toHaveText("OPay bank"); + expect(lookups).toBe(0); +}); diff --git a/tests/browser/reliability.spec.ts b/tests/browser/reliability.spec.ts index 6e599b8..c759626 100644 --- a/tests/browser/reliability.spec.ts +++ b/tests/browser/reliability.spec.ts @@ -49,7 +49,7 @@ test("signup focuses invalid input and shows server field errors beside the corr await expect(page.locator("#name")).toHaveAttribute("aria-invalid", "true"); await page.getByLabel("Full name", { exact: true }).fill("Account Test"); await page.getByLabel("Email address").fill("account@example.com"); - await page.getByLabel("Nigerian phone number").fill("08012345678"); + await page.getByLabel("Nigerian phone number").fill("08031234567"); await page.locator("#password").fill("StrongPassword123!"); await page.locator("#confirmPassword").fill("StrongPassword123!"); await page.getByRole("checkbox").check(); diff --git a/tests/configuration.test.ts b/tests/configuration.test.ts index 70bf982..2fe4778 100644 --- a/tests/configuration.test.ts +++ b/tests/configuration.test.ts @@ -76,15 +76,21 @@ it("enables configured sandbox providers and keeps VTpass on the matching enviro vi.stubEnv("VTPASS_PUBLIC_KEY", "sandbox-fixture"); vi.stubEnv("VTPASS_ENV", "sandbox"); const { env } = await import("../apps/api/src/shared/infrastructure/env"); - const { paystackConfigured } = + const { paystackConfigured, withdrawalsConfigured } = await import("../apps/api/src/v1/modules/deposits/providers/paystack"); const { vtpassConfigured } = await import("../apps/api/src/v1/modules/billers/providers/vtpass"); expect(paystackConfigured()).toBe(true); expect(vtpassConfigured()).toBe(true); + expect(withdrawalsConfigured()).toBe(true); env().VTPASS_ENV = "live"; expect(vtpassConfigured()).toBe(false); expect(paystackConfigured()).toBe(true); + env().PAYMENT_MODE = "live"; + env().PAYSTACK_TRANSFERS_ENABLED = "false"; + expect(withdrawalsConfigured()).toBe(false); + env().PAYSTACK_TRANSFERS_ENABLED = "true"; + expect(withdrawalsConfigured()).toBe(true); env().PAYMENT_MODE = "disabled"; expect(paystackConfigured()).toBe(false); expect(vtpassConfigured()).toBe(false); diff --git a/tests/dependency-security.test.ts b/tests/dependency-security.test.ts new file mode 100644 index 0000000..6fd6bc1 --- /dev/null +++ b/tests/dependency-security.test.ts @@ -0,0 +1,20 @@ +import { createRequire } from "node:module"; +import { expect, it } from "vitest"; +const mobile = createRequire( + new URL("../apps/mobile/package.json", import.meta.url), +); +const router = createRequire(mobile.resolve("expo-router/package.json")); +it("keeps Expo Router query parsing compatible with the patched URI decoder", () => { + const query = router("query-string"); + expect( + query.parse("name=Quick%20Pay¤cy=%E2%82%A6&next=%2Fwallet"), + ).toEqual( + expect.objectContaining({ + name: "Quick Pay", + currency: "₦", + next: "/wallet", + }), + ); + expect(() => query.parse("bad=%E0%A4%A&value=%25%ZZ")).not.toThrow(); + expect(query.stringify({ next: "/wallet" })).toBe("next=%2Fwallet"); +}); diff --git a/tests/financial.test.ts b/tests/financial.test.ts index ef40021..d1bcf8a 100644 --- a/tests/financial.test.ts +++ b/tests/financial.test.ts @@ -25,8 +25,21 @@ import { parseNaira, signUpSchema, phone, + newTransactionPin, type RewardRule, } from "@quickpay/contracts"; +import { + setTransactionPin, + verifyTransactionPin, + requestPinReset, + resetTransactionPin, +} from "../apps/api/src/v1/modules/security/services/pin"; +import { pinSettings } from "../apps/api/src/v1/modules/security/routes/pin"; +import { prepareDepositCheckout } from "../apps/api/src/v1/modules/deposits/services/checkout"; +import { getPayment } from "../apps/api/src/v1/modules/payments/routes/handler"; +import { resolveBank } from "../apps/api/src/v1/modules/withdrawals/routes/handler"; +import { publicTransaction } from "../apps/api/src/v1/modules/payments/repositories/payment.repository"; +import { createOperation } from "../apps/api/src/v1/modules/payments/services/create-payment"; import { verifyAdminEmail } from "../apps/api/src/v1/modules/admin/services/verify-email"; import { auth } from "../apps/api/src/v1/modules/auth/auth"; import { authorized } from "../apps/api/src/shared/auth"; @@ -142,6 +155,8 @@ beforeAll(async () => { await user(ids.referrer); await user(ids.user, ids.referrer); await user(ids.other); + for (const id of [ids.user, ids.other, ids.referrer]) + await setTransactionPin(id, "572904"); }); afterAll(() => pool.end()); @@ -529,7 +544,7 @@ describe("native client extensions", () => { }); describe("exact money and request contracts", () => { it("normalizes Nigerian phones and preserves exact kobo", () => { - expect(phone.parse("0801 234 5678")).toBe("+2348012345678"); + expect(phone.parse("0803 123 4567")).toBe("+2348031234567"); expect(parseNaira("99999999.99")).toBe("9999999999"); expect(() => parseNaira("1.001")).toThrow(); }); @@ -537,7 +552,7 @@ describe("exact money and request contracts", () => { const base = { name: "Test User", email: "test@example.com", - phoneNumber: "08012345678", + phoneNumber: "08031234567", password: testPassword, confirmPassword: "different", terms: false, @@ -692,7 +707,9 @@ describe("immutable, concurrent financial records", () => { vi.fn().mockRejectedValue(new DOMException("Timed out", "TimeoutError")), ); try { - await expect(processPayment(p.id)).rejects.toThrow("Timed out"); + await expect(processPayment(p.id)).rejects.toMatchObject({ + code: "PAYMENT_PENDING", + }); } finally { vi.unstubAllGlobals(); config.PAYMENT_MODE = previousMode; @@ -1229,7 +1246,7 @@ describe("account lifecycle and ledger enforcement", () => { authorization: `Bearer ${login.token}`, "content-type": "application/json", }, - body: JSON.stringify({ password: testPassword }), + body: JSON.stringify({ pin: "572904" }), }); const before = await balance(ids.referrer); await claimReward(request(), r.id); @@ -1343,3 +1360,504 @@ describe("gift-card review and settlement", () => { expect(await balance(seller)).toBe(BigInt(q.amount)); }); }); + +describe("transaction PIN security", () => { + it("persists failed attempts, locks, and resets only with a single-use verified email code", async () => { + const id = crypto.randomUUID(); + await user(id); + await expect(verifyTransactionPin(id, "572904")).rejects.toMatchObject({ + code: "PIN_REQUIRED", + }); + await setTransactionPin(id, "572904"); + expect( + ( + await pool.query( + "SELECT pin_hash FROM transaction_pins WHERE user_id=$1", + [id], + ) + ).rows[0].pin_hash, + ).not.toBe("572904"); + for (let i = 0; i < 5; i++) + await expect(verifyTransactionPin(id, "111111")).rejects.toMatchObject({ + code: i === 4 ? "PIN_LOCKED" : "PIN_INCORRECT", + }); + expect( + ( + await pool.query( + "SELECT failed_attempts FROM transaction_pins WHERE user_id=$1", + [id], + ) + ).rows[0].failed_attempts, + ).toBe(5); + await expect(verifyTransactionPin(id, "572904")).rejects.toMatchObject({ + code: "PIN_LOCKED", + }); + await requestPinReset(id); + const job = ( + await pool.query( + "SELECT payload FROM jobs WHERE type='email' AND payload->>'to'=$1 AND payload->>'subject'='Reset your transaction PIN' ORDER BY created_at DESC LIMIT 1", + [`${id}@quickpay.test`], + ) + ).rows[0].payload; + expect(job.text).toContain("{{code}}"); + const code = unseal(job.otpEncrypted); + const wrong = String((Number(code) + 1) % 1000000).padStart(6, "0"); + await expect( + resetTransactionPin(id, wrong, "684207"), + ).rejects.toMatchObject({ code: "OTP_INVALID" }); + expect( + ( + await pool.query( + "SELECT attempts FROM pin_reset_challenges WHERE user_id=$1", + [id], + ) + ).rows[0].attempts, + ).toBe(1); + await resetTransactionPin(id, code, "684207"); + await verifyTransactionPin(id, "684207"); + await expect(resetTransactionPin(id, code, "906248")).rejects.toMatchObject( + { code: "OTP_INVALID" }, + ); + await expect(verifyTransactionPin(id, "572904")).rejects.toMatchObject({ + code: "PIN_INCORRECT", + }); + }); + it("requires the separate PIN for deposits, withdrawals and payments before any provider submission", async () => { + const id = crypto.randomUUID(); + await user(id); + await setTransactionPin(id, "572904"); + const login = await auth().api.signInEmail({ + body: { email: `${id}@quickpay.test`, password: testPassword }, + headers: new Headers({ "x-forwarded-for": "127.0.0.9" }), + }); + const variants = [ + ["deposit", { amount: "10000" }], + [ + "withdrawal", + { + amount: "10000", + bankCode: "999", + accountNumber: "1234567890", + validationId: crypto.randomUUID(), + }, + ], + [ + "payment", + { amount: "10000", serviceId: "mtn", beneficiary: "08031234567" }, + ], + ] as const; + for (const [kind, fields] of variants) { + const req = new Request(`http://localhost:3001/api/v1/${kind}`, { + method: "POST", + headers: { + Authorization: `Bearer ${login.token}`, + "Content-Type": "application/json", + "Idempotency-Key": crypto.randomUUID(), + }, + body: JSON.stringify({ ...fields, pin: "111111" }), + }); + await expect(createOperation(req, kind)).rejects.toMatchObject({ + code: "PIN_INCORRECT", + }); + } + expect( + ( + await pool.query( + "SELECT count(*)::int AS count FROM transactions WHERE user_id=$1", + [id], + ) + ).rows[0].count, + ).toBe(0); + }); +}); + +describe("PIN settings and account security alerts", () => { + it("rejects weak PINs and requires both the login password and old PIN for a change", async () => { + for (const value of ["111111", "123456", "987654", "1234", "abcdef"]) + expect(newTransactionPin.safeParse(value).success).toBe(false); + const id = crypto.randomUUID(); + await user(id); + const login = await auth().api.signInEmail({ + body: { email: `${id}@quickpay.test`, password: testPassword }, + headers: new Headers({ "x-forwarded-for": "127.0.0.12" }), + }); + const req = (value?: unknown) => + new Request("http://localhost:3001/api/v1/security/pin", { + method: value ? "POST" : "GET", + headers: { + Authorization: `Bearer ${login.token}`, + "Content-Type": "application/json", + }, + ...(value ? { body: JSON.stringify(value) } : {}), + }); + expect(await (await pinSettings(req())).json()).toEqual({ + configured: false, + lockedUntil: null, + }); + await expect( + pinSettings( + req({ + password: "wrong-password", + newPin: "572904", + confirmPin: "572904", + }), + ), + ).rejects.toMatchObject({ code: "AUTHORIZATION_FAILED" }); + await pinSettings( + req({ password: testPassword, newPin: "572904", confirmPin: "572904" }), + ); + expect(await (await pinSettings(req())).json()).toEqual({ + configured: true, + lockedUntil: null, + }); + await expect( + pinSettings( + req({ + password: testPassword, + currentPin: "684207", + newPin: "906248", + confirmPin: "906248", + }), + ), + ).rejects.toMatchObject({ code: "PIN_INCORRECT" }); + await pinSettings( + req({ + password: testPassword, + currentPin: "572904", + newPin: "906248", + confirmPin: "906248", + }), + ); + await verifyTransactionPin(id, "906248"); + const jobs = ( + await pool.query( + "SELECT payload FROM jobs WHERE type='email' AND payload->>'to'=$1", + [`${id}@quickpay.test`], + ) + ).rows; + expect(jobs.map((j) => j.payload.subject)).toEqual( + expect.arrayContaining([ + "Transaction PIN set", + "Transaction PIN changed", + ]), + ); + expect(JSON.stringify(jobs)).not.toMatch(/572904|906248|StrongPassword123/); + }); + it("queues branded-delivery jobs for successful login and password change without exposing credentials", async () => { + const id = crypto.randomUUID(); + await user(id); + const headers = { + "content-type": "application/json", + "expo-origin": "quickpay-dev://", + "x-real-ip": "127.0.0.13", + "x-forwarded-for": "127.0.0.13", + "user-agent": "QuickPay Android", + }; + const response = await handleAuth( + new Request("http://localhost:3001/api/v1/auth/sign-in/email", { + method: "POST", + headers, + body: JSON.stringify({ + email: `${id}@quickpay.test`, + password: testPassword, + }), + }), + ); + expect(response.status).toBe(200); + const login = await response.json(); + const changed = await handleAuth( + new Request("http://localhost:3001/api/v1/auth/change-password", { + method: "POST", + headers: { ...headers, Authorization: `Bearer ${login.token}` }, + body: JSON.stringify({ + currentPassword: testPassword, + newPassword: "NewPassword456!", + revokeOtherSessions: true, + }), + }), + ); + expect(changed.status).toBe(200); + const jobs = ( + await pool.query( + "SELECT payload FROM jobs WHERE type='email' AND payload->>'to'=$1", + [`${id}@quickpay.test`], + ) + ).rows; + expect(jobs.map((j) => j.payload.subject)).toEqual( + expect.arrayContaining([ + "New sign-in to Quick Pay", + "Your password changed", + ]), + ); + expect(JSON.stringify(jobs)).not.toContain(login.token); + expect(JSON.stringify(jobs)).not.toMatch( + /StrongPassword123|NewPassword456/, + ); + }); +}); + +describe("deposit checkout recovery", () => { + it("accepts a late verified deposit success after a failed attempt, credits once, and ignores stale failure responses", async () => { + for (const state of ["failed", "cancelled"]) { + const p = await payment("deposit", "10000", ids.user, state); + const before = await balance(ids.user); + const confirmed = { + status: "successful" as const, + amount: p.amount, + currency: "NGN", + reference: p.reference, + email: `${ids.user}@quickpay.test`, + }; + await expect( + settlePayment(p.id, { ...confirmed, amount: "9999" }), + ).rejects.toMatchObject({ code: "VERIFICATION_MISMATCH" }); + await expect( + settlePayment(p.id, { ...confirmed, email: "other@example.test" }), + ).rejects.toMatchObject({ code: "DESTINATION_MISMATCH" }); + await Promise.all([ + settlePayment(p.id, confirmed), + settlePayment(p.id, confirmed), + ]); + expect(await balance(ids.user)).toBe(before + 10000n); + expect( + await settlePayment(p.id, { ...confirmed, status: "failed" }), + ).toBe(false); + expect( + ( + await pool.query("SELECT status FROM transactions WHERE id=$1", [ + p.id, + ]) + ).rows[0].status, + ).toBe("successful"); + expect( + ( + await pool.query("SELECT 1 FROM journals WHERE reference=$1", [ + `deposit:${p.id}`, + ]) + ).rowCount, + ).toBe(1); + } + const withdrawal = await payment( + "withdrawal", + "10000", + ids.user, + "failed", + { recipientCode: "expected-recipient" }, + ); + await expect( + settlePayment(withdrawal.id, { + status: "successful", + amount: withdrawal.amount, + currency: "NGN", + reference: withdrawal.reference, + recipient: "expected-recipient", + }), + ).rejects.toMatchObject({ code: "STATE_CONFLICT" }); + }); + it("serializes checkout preparation, preserves a charge confirmed during initialization, and uses the static return URL", async () => { + const p = await payment("deposit"); + const config = env(), + originalMode = config.PAYMENT_MODE, + originalKey = config.PAYSTACK_SECRET_KEY; + config.PAYMENT_MODE = "sandbox"; + config.PAYSTACK_SECRET_KEY = "sk_test_checkout_fixture"; + let finish!: () => void; + const gate = new Promise((resolve) => { + finish = resolve; + }); + const before = await balance(ids.user); + const fetcher = vi.fn(async (_url: string, init?: RequestInit) => { + const body = JSON.parse(String(init?.body)); + expect(body.reference).toBe(p.reference); + expect(body.callback_url).toBe( + `${config.WEB_ORIGIN}/transactions/detail?id=${p.id}`, + ); + await gate; + await settlePayment(p.id, { + status: "successful", + amount: p.amount, + currency: "NGN", + reference: p.reference, + email: `${ids.user}@quickpay.test`, + }); + return Response.json({ + status: true, + data: { + authorization_url: "https://checkout.paystack.com/local-checkout", + access_code: "private-code", + reference: p.reference, + }, + }); + }); + vi.stubGlobal("fetch", fetcher); + try { + const first = prepareDepositCheckout(p.id); + await vi.waitFor(() => expect(fetcher).toHaveBeenCalledTimes(1)); + await prepareDepositCheckout(p.id); + expect(fetcher).toHaveBeenCalledTimes(1); + finish(); + await first; + const stored = ( + await pool.query("SELECT * FROM transactions WHERE id=$1", [ + p.id, + ]) + ).rows[0]; + expect(stored.status).toBe("successful"); + expect(stored.details.checkoutUrl).toBe( + "https://checkout.paystack.com/local-checkout", + ); + expect(stored.details).not.toHaveProperty("checkoutLeaseToken"); + expect(stored.details).not.toHaveProperty("checkoutLeaseUntil"); + expect(JSON.stringify(publicTransaction(stored))).not.toContain( + "private-code", + ); + expect(await balance(ids.user)).toBe(before + 10000n); + } finally { + finish(); + vi.unstubAllGlobals(); + config.PAYMENT_MODE = originalMode; + config.PAYSTACK_SECRET_KEY = originalKey; + } + }); + it("releases an interrupted checkout lease and retries with the same reference without falsely failing the deposit", async () => { + const p = await payment("deposit"); + const config = env(), + originalMode = config.PAYMENT_MODE, + originalKey = config.PAYSTACK_SECRET_KEY; + config.PAYMENT_MODE = "sandbox"; + config.PAYSTACK_SECRET_KEY = "sk_test_checkout_fixture"; + const before = await balance(ids.user); + const fetcher = vi.fn().mockRejectedValueOnce(new TypeError("Interrupted")); + vi.stubGlobal("fetch", fetcher); + try { + await expect(prepareDepositCheckout(p.id)).rejects.toMatchObject({ + code: "PAYMENT_PENDING", + }); + let stored = ( + await pool.query("SELECT * FROM transactions WHERE id=$1", [ + p.id, + ]) + ).rows[0]; + expect(stored.status).toBe("processing"); + expect(stored.details).not.toHaveProperty("checkoutLeaseToken"); + fetcher.mockResolvedValue( + Response.json({ + status: true, + data: { + authorization_url: "https://checkout.paystack.com/retry", + access_code: "private", + reference: p.reference, + }, + }), + ); + await prepareDepositCheckout(p.id); + stored = ( + await pool.query("SELECT * FROM transactions WHERE id=$1", [ + p.id, + ]) + ).rows[0]; + expect(stored.status).toBe("awaiting_authorization"); + expect(await balance(ids.user)).toBe(before); + expect( + fetcher.mock.calls.map( + (call) => JSON.parse(String(call[1]?.body)).reference, + ), + ).toEqual([p.reference, p.reference]); + } finally { + vi.unstubAllGlobals(); + config.PAYMENT_MODE = originalMode; + config.PAYSTACK_SECRET_KEY = originalKey; + } + }); + it("prepares checkout instead of verifying an uninitialized deposit when its page is opened", async () => { + const id = crypto.randomUUID(); + await user(id); + const login = await auth().api.signInEmail({ + body: { email: `${id}@quickpay.test`, password: testPassword }, + headers: new Headers({ "x-forwarded-for": "127.0.0.17" }), + }); + const p = await payment("deposit", "10000", id); + const req = new Request(`http://localhost:3001/api/v1/payments/${p.id}`, { + headers: { Authorization: `Bearer ${login.token}` }, + }); + await getPayment(req, p.id); + const first = ( + await pool.query( + "SELECT type FROM jobs WHERE payload->>'id'=$1 OR payload->>'reference'=$2", + [p.id, p.reference], + ) + ).rows; + expect(first.map((row) => row.type)).toEqual(["process-payment"]); + await pool.query( + "UPDATE transactions SET status='awaiting_authorization',details=jsonb_build_object('checkoutUrl','https://checkout.paystack.com/ready') WHERE id=$1", + [p.id], + ); + await getPayment(req, p.id); + expect( + ( + await pool.query( + "SELECT 1 FROM jobs WHERE type='verify-provider' AND payload->>'reference'=$1", + [p.reference], + ) + ).rowCount, + ).toBe(1); + }); + it("bank account review never creates a withdrawal and returns an account-specific error on rejection", async () => { + const id = crypto.randomUUID(); + await user(id); + const login = await auth().api.signInEmail({ + body: { email: `${id}@quickpay.test`, password: testPassword }, + headers: new Headers({ "x-forwarded-for": "127.0.0.18" }), + }); + const config = env(), + originalMode = config.PAYMENT_MODE, + originalKey = config.PAYSTACK_SECRET_KEY; + config.PAYMENT_MODE = "sandbox"; + config.PAYSTACK_SECRET_KEY = "sk_test_checkout_fixture"; + const fetcher = vi + .fn() + .mockResolvedValueOnce(Response.json({ status: false })) + .mockResolvedValueOnce( + Response.json({ + status: true, + data: { + account_number: "1234567890", + account_name: "VERIFIED RECIPIENT", + }, + }), + ); + vi.stubGlobal("fetch", fetcher); + const req = () => + new Request("http://localhost:3001/api/v1/banks/resolve", { + method: "POST", + headers: { + Authorization: `Bearer ${login.token}`, + "content-type": "application/json", + }, + body: JSON.stringify({ + bankCode: "999992", + accountNumber: "1234567890", + }), + }); + try { + await expect(resolveBank(req())).rejects.toMatchObject({ + code: "BANK_ACCOUNT_UNVERIFIED", + }); + expect(await (await resolveBank(req())).json()).toMatchObject({ + name: "VERIFIED RECIPIENT", + }); + expect( + (await pool.query("SELECT 1 FROM transactions WHERE user_id=$1", [id])) + .rowCount, + ).toBe(0); + expect(await balance(id)).toBe(0n); + expect( + fetcher.mock.calls.every((call) => call[1]?.method === "GET"), + ).toBe(true); + } finally { + vi.unstubAllGlobals(); + config.PAYMENT_MODE = originalMode; + config.PAYSTACK_SECRET_KEY = originalKey; + } + }); +}); diff --git a/tests/job-error.test.ts b/tests/job-error.test.ts new file mode 100644 index 0000000..0325df3 --- /dev/null +++ b/tests/job-error.test.ts @@ -0,0 +1,47 @@ +import { expect, it } from "vitest"; +import { paymentSchema } from "@quickpay/contracts"; +import { jobError } from "../apps/worker/src/job-error"; +import { DomainError } from "../apps/api/src/shared/errors"; +it("records validation field paths without customer values or raw provider messages", () => { + const parsed = paymentSchema.safeParse({ + serviceId: "mtn", + beneficiary: "private-account-value", + amount: null, + pin: "private-secret", + }); + expect(parsed.success).toBe(false); + if (parsed.success) throw new Error("Expected invalid test input"); + const diagnostic = jobError(parsed.error); + expect(diagnostic.code).toBe("ZodError"); + expect(diagnostic.issues).toContainEqual({ + path: "amount", + code: "invalid_type", + }); + expect(JSON.stringify(diagnostic)).not.toMatch( + /private-account-value|private-secret/, + ); + expect( + jobError(new DomainError("PAYMENT_PENDING", "private provider response")), + ).toEqual({ code: "PAYMENT_PENDING" }); +}); + +it("preserves useful field paths through provider response alternatives", async () => { + const { variationSchema } = + await import("../apps/api/src/v1/modules/billers/providers/vtpass"); + const parsed = variationSchema.safeParse({ + variations: [ + { + variation_code: "fixture", + name: "Private data", + variation_amount: null, + }, + ], + }); + if (parsed.success) throw new Error("Expected invalid test input"); + const diagnostic = jobError(parsed.error); + expect(diagnostic.issues).toContainEqual({ + path: "variations.0.variation_amount", + code: "invalid_type", + }); + expect(JSON.stringify(diagnostic)).not.toContain("Private data"); +}); diff --git a/tests/mailjet.test.ts b/tests/mailjet.test.ts index 5c7aeb2..7708dcf 100644 --- a/tests/mailjet.test.ts +++ b/tests/mailjet.test.ts @@ -4,6 +4,8 @@ const config = vi.hoisted(() => ({ MAILJET_SECRET_KEY: "test-secret-key", MAILJET_FROM_EMAIL: "sender@example.com", MAILJET_FROM_NAME: "Quick Pay", + WEB_ORIGIN: "https://example.com", + DATA_ENCRYPTION_KEY: "a".repeat(64), })); vi.mock("../apps/api/src/shared/infrastructure/env", () => ({ env: () => config, @@ -41,12 +43,20 @@ describe("Mailjet email delivery", () => { expect(init?.signal).toBeDefined(); expect(JSON.parse(String(init?.body))).toEqual({ Messages: [ - { + expect.objectContaining({ From: { Email: "sender@example.com", Name: "Quick Pay" }, To: [{ Email: job.to }], Subject: job.subject, TextPart: job.text, - }, + HTMLPart: expect.stringContaining("cid:quickpay-logo"), + InlinedAttachments: [ + expect.objectContaining({ + ContentID: "quickpay-logo", + ContentType: "image/png", + Base64Content: expect.any(String), + }), + ], + }), ], }); }); @@ -79,3 +89,48 @@ describe("Mailjet email delivery", () => { await expect(sendEmail(job)).rejects.toThrow("Network timeout"); }); }); + +describe("branded email security", () => { + it("escapes message content and permits action buttons only for the app origin", async () => { + const { emailTemplate } = + await import("../apps/api/src/shared/infrastructure/email/template"); + const html = emailTemplate({ + subject: '', + text: " https://attacker.example/verify", + siteUrl: "https://example.com", + }); + expect(html).not.toContain("