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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .githooks/pre-push
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
#!/bin/sh
set -eu
pnpm security:scan
11 changes: 11 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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:
Expand Down
7 changes: 6 additions & 1 deletion apps/api/next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
2 changes: 2 additions & 0 deletions apps/api/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
33 changes: 33 additions & 0 deletions apps/api/src/app/api/v1/payments/[paymentId]/receipt/route.ts
Original file line number Diff line number Diff line change
@@ -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",
},
});
});
3 changes: 3 additions & 0 deletions apps/api/src/app/api/v1/security/pin/reset/route.ts
Original file line number Diff line number Diff line change
@@ -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);
4 changes: 4 additions & 0 deletions apps/api/src/app/api/v1/security/pin/route.ts
Original file line number Diff line number Diff line change
@@ -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);
17 changes: 3 additions & 14 deletions apps/api/src/shared/auth/index.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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,
Expand All @@ -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;
}
28 changes: 27 additions & 1 deletion apps/api/src/shared/infrastructure/email.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,15 @@
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";

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),
Expand All @@ -18,6 +23,13 @@ export async function sendEmail(payload: Record<string, unknown>) {
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: {
Expand All @@ -30,7 +42,21 @@ export async function sendEmail(payload: Record<string, unknown>) {
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"),
},
],
},
],
}),
Expand Down
31 changes: 31 additions & 0 deletions apps/api/src/shared/infrastructure/email/queue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { enqueue, type Connection } from "@quickpay/database";
export async function queueUserEmail(
c: Pick<Connection, "query">,
userId: string,
subject: string,
text: string,
key: string,
extra: Record<string, unknown> = {},
) {
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 }),
);
}
}
49 changes: 49 additions & 0 deletions apps/api/src/shared/infrastructure/email/template.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const escape = (text: string) =>
text.replace(
/[&<>"']/g,
(c) =>
({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[
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) =>
`<p style="margin:0 0 18px;color:#51465f;font-size:16px;line-height:1.7;word-break:break-word;overflow-wrap:anywhere">${escape(line)}</p>`,
)
.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 `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head><body style="margin:0;background:#faf9ff;font-family:Arial,Helvetica,sans-serif"><div style="display:none;max-height:0;overflow:hidden">${escape(input.subject)}</div><table role="presentation" width="100%" cellspacing="0" cellpadding="0"><tr><td align="center" style="padding:32px 12px"><table role="presentation" width="600" cellspacing="0" cellpadding="0" style="width:100%;max-width:600px;border-collapse:separate;background:#fff;border:1px solid #e9e2f3;border-top:6px solid #6d28d9;border-radius:24px"><tr><td style="padding:36px 32px"><img src="cid:quickpay-logo" width="210" alt="Quick Pay" style="display:block;width:210px;max-width:100%;height:auto"><p style="color:#6d28d9;font-size:11px;letter-spacing:2px;font-weight:bold;margin:32px 0 12px">YOUR QUICK PAY ACCOUNT</p><h1 style="color:#2e1065;font-size:28px;line-height:1.3;margin:0 0 24px">${escape(input.subject)}</h1>${input.otp ? `<div style="background:#faf9ff;border:1px solid #e9e2f3;border-radius:16px;padding:22px;text-align:center;font-size:34px;font-weight:bold;letter-spacing:8px;color:#6d28d9;margin-bottom:24px">${escape(input.otp)}</div>` : ""}${paragraphs}${action ? `<p style="margin:28px 0"><a href="${escape(action.href)}" style="display:inline-block;background:#6d28d9;color:white;border-radius:12px;padding:15px 24px;font-weight:bold;text-decoration:none">${actionLabel}</a></p>` : ""}<hr style="border:0;border-top:1px solid #eeeaf4;margin:30px 0"><p style="font-weight:bold;color:#6d28d9;font-size:17px">Less paying. More living.</p><p style="font-size:12px;line-height:1.7;color:#71677e;margin-bottom:0">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.</p></td></tr></table><p style="color:#8d819a;font-size:11px">Quick Pay · Account and transaction notifications</p></td></tr></table></body></html>`;
}
2 changes: 2 additions & 0 deletions apps/api/src/shared/infrastructure/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } : {}),
}),
);
Expand Down
45 changes: 44 additions & 1 deletion apps/api/src/shared/infrastructure/openapi.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,13 @@ export function openapi() {
properties: Record<string, unknown>,
required = Object.keys(properties),
) => ({ type: "object", properties, required });
const withOptional = (
requiredProperties: Record<string, unknown>,
optionalProperties: Record<string, unknown>,
) => ({
...object(requiredProperties),
properties: { ...requiredProperties, ...optionalProperties },
});
const str = { type: "string" };
add(
"/wallet/capabilities",
Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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",
Expand Down
12 changes: 11 additions & 1 deletion apps/api/src/v1/modules/admin/routes/access.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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);
Expand Down Expand Up @@ -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." });
}
Loading
Loading