From 85f0a37d5bdd4ce3c10c51c2efb476c4a08f767a Mon Sep 17 00:00:00 2001 From: Thunpisit Amnuaikiatloet Date: Sun, 25 Oct 2026 14:23:21 +0700 Subject: [PATCH] fix(shop): require proof of access to view or pay an order by number MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The customer order page looked orders up by number alone whenever no ?email= was given, and order numbers are sequential — so anyone could walk KHP-2026-00001, 00002, … and read every buyer's name, email, phone and shipping address. Any signed-in account, customers included, could do the same. The return-request action and pay-by-orderNumber had the same gap. Access now needs one of: staff (admin+), the owning account (user id, or a verified email matching the order), the order's email (receipt links and /lookup), or the browser that placed the order — checkout/ start sets an HMAC-signed cookie (keyed by BETTER_AUTH_SECRET) so a guest returning from the payment page still lands on their order. Refusals are the same 404 as a missing order. Ported from bactrack-website 70d37f5, with a generic cookie name and a verified-email requirement on the account-email path. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 4c86687e892c2506ec09ae0f39fd921cc6648d62) --- src/lib/server/shop/order-access.test.ts | 169 ++++++++++++++++++ src/lib/server/shop/order-access.ts | 110 ++++++++++++ .../order/[orderNumber]/+page.server.ts | Bin 7764 -> 8078 bytes .../[locale]/order/[orderNumber]/+page.svelte | 4 +- src/routes/api/shop/checkout/pay/+server.ts | 39 +++- src/routes/api/shop/checkout/start/+server.ts | 6 + .../api/shop/payment-recovery.node.test.ts | 17 +- 7 files changed, 329 insertions(+), 16 deletions(-) create mode 100644 src/lib/server/shop/order-access.test.ts create mode 100644 src/lib/server/shop/order-access.ts diff --git a/src/lib/server/shop/order-access.test.ts b/src/lib/server/shop/order-access.test.ts new file mode 100644 index 00000000..83a6df3a --- /dev/null +++ b/src/lib/server/shop/order-access.test.ts @@ -0,0 +1,169 @@ +/** + * v4.5.1 — order pages were readable by anyone holding a (sequential) + * order number. These pin who may see an order, and that the three + * routes which look orders up BY NUMBER all go through canViewOrder. + */ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; +import type { Cookies } from "@sveltejs/kit"; +import type { AuthUser, UserRole } from "$lib/server/auth/types"; +import { + ORDER_ACCESS_COOKIE, + browserPlacedOrder, + canViewOrder, + grantOrderAccess, +} from "./order-access"; + +const SECRET = "test-secret-at-least-32-characters-long"; + +function jar(initial: Record = {}): Cookies { + const store = new Map(Object.entries(initial)); + return { + get: (name: string) => store.get(name), + getAll: () => [...store].map(([name, value]) => ({ name, value })), + set: (name: string, value: string) => void store.set(name, value), + delete: (name: string) => void store.delete(name), + serialize: () => "", + } as unknown as Cookies; +} + +function user(role: UserRole, over: Partial = {}): AuthUser { + return { + id: "u_1", + name: "U", + email: "someone@example.com", + emailVerified: true, + image: null, + role, + createdAt: "", + updatedAt: "", + ...over, + }; +} + +const order = { + orderNumber: "KP-2026-00001", + email: "Buyer@Example.com", + userId: null as string | null, +}; + +const view = (over: Partial[0]> = {}) => + canViewOrder({ + order, + user: null, + email: null, + cookies: jar(), + secret: SECRET, + ...over, + }); + +describe("canViewOrder", () => { + it("refuses an anonymous visitor holding only the number", async () => { + expect(await view()).toBe(false); + }); + + it("refuses any signed-in non-owner, customer or editor", async () => { + expect(await view({ user: user("customer") })).toBe(false); + expect(await view({ user: user("editor") })).toBe(false); + }); + + it("allows staff (admin+)", async () => { + expect(await view({ user: user("admin") })).toBe(true); + expect(await view({ user: user("super_admin") })).toBe(true); + }); + + it("allows the owning account by user id", async () => { + expect( + await view({ + order: { ...order, userId: "u_1" }, + user: user("customer"), + }), + ).toBe(true); + }); + + it("allows a VERIFIED account whose email matches, not an unverified one", async () => { + const email = "buyer@example.com"; + expect(await view({ user: user("customer", { email }) })).toBe(true); + expect( + await view({ user: user("customer", { email, emailVerified: false }) }), + ).toBe(false); + }); + + it("allows the order's email, case- and space-insensitively", async () => { + expect(await view({ email: " buyer@EXAMPLE.com " })).toBe(true); + expect(await view({ email: "other@example.com" })).toBe(false); + expect(await view({ email: "" })).toBe(false); + }); + + it("allows the browser that placed the order", async () => { + const cookies = jar(); + await grantOrderAccess(cookies, SECRET, order.orderNumber); + expect(await view({ cookies })).toBe(true); + }); +}); + +describe("order-access cookie", () => { + it("cannot be minted without the secret", async () => { + const forged = jar({ [ORDER_ACCESS_COOKIE]: `${order.orderNumber}.AAAA` }); + expect(await browserPlacedOrder(forged, SECRET, order.orderNumber)).toBe( + false, + ); + }); + + it("does not carry over to another order number", async () => { + const cookies = jar(); + await grantOrderAccess(cookies, SECRET, "KP-2026-00001"); + expect(await browserPlacedOrder(cookies, SECRET, "KP-2026-00002")).toBe( + false, + ); + }); + + it("is refused under a different secret (rotation invalidates it)", async () => { + const cookies = jar(); + await grantOrderAccess(cookies, SECRET, order.orderNumber); + expect( + await browserPlacedOrder(cookies, `${SECRET}-rotated`, order.orderNumber), + ).toBe(false); + }); + + it("keeps at most 10 orders, newest first, without duplicates", async () => { + const cookies = jar(); + for (let i = 1; i <= 12; i++) { + await grantOrderAccess(cookies, SECRET, `KP-2026-${i}`); + } + await grantOrderAccess(cookies, SECRET, "KP-2026-12"); + const entries = cookies.get(ORDER_ACCESS_COOKIE)!.split(","); + expect(entries).toHaveLength(10); + expect(entries[0].startsWith("KP-2026-12.")).toBe(true); + expect(await browserPlacedOrder(cookies, SECRET, "KP-2026-1")).toBe(false); + }); + + it("grants nothing when no secret is configured", async () => { + const cookies = jar(); + await grantOrderAccess(cookies, undefined, order.orderNumber); + expect(cookies.get(ORDER_ACCESS_COOKIE)).toBeUndefined(); + expect(await view({ cookies, secret: undefined })).toBe(false); + }); +}); + +describe("routes that look an order up by number", () => { + const read = (p: string) => + readFileSync(new URL(`../../../routes/${p}`, import.meta.url), "utf8"); + + it("the order page load and return action both check access", () => { + const src = read("(www)/[locale]/order/[orderNumber]/+page.server.ts"); + expect(src.match(/canViewOrder\(/g)).toHaveLength(2); + // The old shape: signed-in → no email filter, anonymous → optional one. + expect(src).not.toMatch(/locals\.user \? undefined/); + }); + + it("paying by order number checks access", () => { + const src = read("api/shop/checkout/pay/+server.ts"); + expect(src).toMatch(/canViewOrder\(/); + }); + + it("checkout/start grants the placing browser access", () => { + const src = read("api/shop/checkout/start/+server.ts"); + expect(src).toMatch(/grantOrderAccess\(cookies, env\.BETTER_AUTH_SECRET/); + }); +}); diff --git a/src/lib/server/shop/order-access.ts b/src/lib/server/shop/order-access.ts new file mode 100644 index 00000000..803635ed --- /dev/null +++ b/src/lib/server/shop/order-access.ts @@ -0,0 +1,110 @@ +/** + * Who may see a customer order (#security, v4.5.1). + * + * Order numbers are sequential (KP-2026-00001, …00002), so holding one + * proves nothing — and the order page shows the buyer's email, phone + * and shipping address. Access needs ONE of: + * + * 1. Staff (admin+), who manage orders anyway. + * 2. A signed-in customer who owns the order — by user id, or by a + * VERIFIED account email equal to the order's email. + * 3. The order's email, as the receipt links (`?email=`) and the + * /lookup form provide — Shopify's guest-lookup model. + * 4. This browser placed the order: checkout/start sets a signed + * cookie naming it, so a guest returning from the payment page + * lands on their own order without retyping their email. The HMAC + * (keyed by BETTER_AUTH_SECRET) stops anyone minting the cookie + * for an order number they guessed. + * + * Callers answer "no" with the same 404 as a missing order, so a + * refusal never confirms that an order number exists. + */ +import type { Cookies } from "@sveltejs/kit"; +import { hasRole } from "$lib/server/auth/permissions"; +import type { AuthUser } from "$lib/server/auth/types"; + +export const ORDER_ACCESS_COOKIE = "khaopad_order_access"; +const MAX_ORDERS = 10; +const MAX_AGE_SECONDS = 60 * 60 * 24 * 90; + +async function sign(secret: string, orderNumber: string): Promise { + const key = await crypto.subtle.importKey( + "raw", + new TextEncoder().encode(secret), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"], + ); + const mac = await crypto.subtle.sign( + "HMAC", + key, + new TextEncoder().encode(`order-access:${orderNumber}`), + ); + // 128 bits of the MAC is ample for a cookie-sized proof. + return btoa(String.fromCharCode(...new Uint8Array(mac).slice(0, 16))) + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); +} + +function readEntries(cookies: Cookies): string[] { + return (cookies.get(ORDER_ACCESS_COOKIE) ?? "").split(",").filter(Boolean); +} + +/** Remember that this browser placed `orderNumber`. */ +export async function grantOrderAccess( + cookies: Cookies, + secret: string | undefined, + orderNumber: string, +): Promise { + if (!secret) return; + const entry = `${orderNumber}.${await sign(secret, orderNumber)}`; + const kept = readEntries(cookies).filter( + (e) => !e.startsWith(`${orderNumber}.`), + ); + cookies.set( + ORDER_ACCESS_COOKIE, + [entry, ...kept].slice(0, MAX_ORDERS).join(","), + { + path: "/", + httpOnly: true, + secure: true, + // Lax, not Strict: the payment provider's redirect back to the order + // page is a cross-site top-level GET and must carry the cookie. + sameSite: "lax", + maxAge: MAX_AGE_SECONDS, + }, + ); +} + +/** Did this browser place `orderNumber`? Verified, never trusted. */ +export async function browserPlacedOrder( + cookies: Cookies, + secret: string | undefined, + orderNumber: string, +): Promise { + if (!secret) return false; + const expected = `${orderNumber}.${await sign(secret, orderNumber)}`; + return readEntries(cookies).some((e) => e === expected); +} + +const norm = (s: string | null | undefined) => (s ?? "").trim().toLowerCase(); + +export async function canViewOrder(input: { + order: { orderNumber: string; email: string; userId: string | null }; + user: AuthUser | null | undefined; + /** An email the requester presented (`?email=`, a form field). */ + email: string | null | undefined; + cookies: Cookies; + secret: string | undefined; +}): Promise { + const { order, user, email, cookies, secret } = input; + const orderEmail = norm(order.email); + if (user && hasRole(user, "admin")) return true; + if (user && order.userId && order.userId === user.id) return true; + if (user?.emailVerified && orderEmail && norm(user.email) === orderEmail) { + return true; + } + if (orderEmail && norm(email) === orderEmail) return true; + return browserPlacedOrder(cookies, secret, order.orderNumber); +} diff --git a/src/routes/(www)/[locale]/order/[orderNumber]/+page.server.ts b/src/routes/(www)/[locale]/order/[orderNumber]/+page.server.ts index ab282db8d2787ecf673b5719b7536c49428f0923..266d83056f0ba94dd055e7efae54daec88ae95e7 100644 GIT binary patch delta 866 zcmaiyPiqrF7{&?ORC*A^gHRQoir8I^yA`8{tx{8o^rTQzuVu1%(+r*6i8DLNp$+lm zMG$5E7G8vW3D4ritN1;1X4X_KTIVvn|DWHy^ZDNEjW?UqR+^I5P)3l3;3ERhaaHhc ztVxYX#d;uzu~a=$H(8Y%jGED%=vJ6O7p&iJEa5te0YQ#)p6?+wx{w*EM&)#ss~VIs zE)Z<^`+fsbAr?|b`(_w=%XV;$x=N1iWLwJ$35wUw>B#dwHd&WcxV{9$ zF)HZ9i^+WiOvs#Iw4aYIfpTf~2Kf5o9a!E&m8QXzMRPs0l}mZSnTXJ`;`>H30j_;h z%`%#zxz+@;CCIqe?m4}b$ky{d0($`~-i5=%$_m(+@!}8e;J}Aa725^*V}+^&LZ(dU z$Qkp1-$??aMERh;yft^HQtorob5m2Qs7Ng2DB5gyI_>S<)=p<@_i6j#cDqw$O~TL) z3*qONFBh+!0w%Nfi}mwo8mRisJ}iH%{p+27qdd-O?UP84vBIt8@3gRgamRkfITwBk fI|7B>)BjN|n1?;W1uaC$9bb2U?cVHP9e8p%q)y<}sitI0X~;Mx z=LEu;!&v31@jL{_ZDlmhXaY@?AUAb<#n76ON(gyM%7QYf1{f)cZYcMJ5IFZ_Cm2dA zGepLsJuv3X4_hk&C#iDfE1AsWl-%ue^s#hcyv||i+$;M>Xew&kbH&~K%VMRmSNvXV z%y#O<{d&82`mkI)EPTGIgI5r8!q|lDk%neK|2Tqhi=)&uS`ie8gcSIFI z_n&U7wAkwKruv9Bf|XX$Tlz9JOY^JK%eBW^1@}H4*ur~?mEgq%nlqY4WVhb(ZdS diff --git a/src/routes/(www)/[locale]/order/[orderNumber]/+page.svelte b/src/routes/(www)/[locale]/order/[orderNumber]/+page.svelte index 354c2c3c..ac27b37f 100644 --- a/src/routes/(www)/[locale]/order/[orderNumber]/+page.svelte +++ b/src/routes/(www)/[locale]/order/[orderNumber]/+page.svelte @@ -95,7 +95,9 @@ const res = await fetch('/api/shop/checkout/pay', { method: 'POST', headers: { 'content-type': 'application/json' }, - body: JSON.stringify({ orderNumber: order.orderNumber }), + // The email proves access for a guest who arrived via the + // receipt link rather than the browser that checked out. + body: JSON.stringify({ orderNumber: order.orderNumber, email: order.email }), }); const body = (await res.json()) as { ok: boolean; diff --git a/src/routes/api/shop/checkout/pay/+server.ts b/src/routes/api/shop/checkout/pay/+server.ts index d18b43bc..4d8d8a15 100644 --- a/src/routes/api/shop/checkout/pay/+server.ts +++ b/src/routes/api/shop/checkout/pay/+server.ts @@ -1,7 +1,7 @@ /** * POST /api/shop/checkout/pay — create a payment charge for a pending order. * - * Body: { orderId?: string, orderNumber?: string, + * Body: { orderId?: string, orderNumber?: string, email?: string, * method?: "promptpay" | "card" } * Returns (hosted link): { ok, providerChargeId, paymentUrl, extra } * Returns (in-page QR): { ok, providerChargeId, orderNumber, @@ -16,13 +16,14 @@ * who abandoned the Beam page only holds the order NUMBER (it's in * their URL and receipt email), never the internal id. * - * ACCEPTED RISK: an order number is a weak secret, so anyone holding it - * can mint a payment link for that order. The blast radius is bounded: - * the endpoint refuses any order not in `pending` status, the response - * carries the payment URL and nothing else (no items, no email, no - * address), and the minted link can only pay the order's OWN stored - * total into the merchant's account — worst case, someone pays your - * bill. + * ACCESS (v4.5.1): an order number is sequential, so paying BY NUMBER + * needs the same proof as viewing the order (order-access.ts) — the + * browser that placed it, the owning account, staff, or `email`. It + * used to be an "accepted risk" that anyone could mint a link; the + * real cost was that minting re-points the order's stored charge id, + * so a stranger could disrupt a customer mid-payment. Refusals are the + * same 404 as a missing order. `orderId` (an unguessable nanoid from + * checkout/start) needs no further proof. */ import { error, json } from "@sveltejs/kit"; import { drizzle } from "drizzle-orm/d1"; @@ -34,6 +35,7 @@ import { resolveProviderForRequest, } from "$plugins/shop/beam-config.server"; import { requireSameOrigin } from "$lib/server/http/same-origin"; +import { canViewOrder } from "$lib/server/shop/order-access"; import { cookieName } from "$lib/paraglide/runtime"; import { DEFAULT_LOCALE, localePath, toLocale } from "$lib/i18n"; import type { RequestHandler } from "./$types"; @@ -43,6 +45,7 @@ export const POST: RequestHandler = async ({ platform, url, cookies, + locals, }) => { // Checkout creates orders and initiates charges — the highest-value // state change in the app, and it had no provenance check at all @@ -55,6 +58,8 @@ export const POST: RequestHandler = async ({ const body = (await request.json().catch(() => null)) as { orderId?: string; orderNumber?: string; + /** With `orderNumber`: proves access the way ?email= does. */ + email?: string; method?: string; } | null; if (!body?.orderId && !body?.orderNumber) { @@ -65,7 +70,23 @@ export const POST: RequestHandler = async ({ const order = body.orderId ? await orderSvc.getOrder(body.orderId) : await orderSvc.getOrderByNumber(body.orderNumber!); - if (!order) throw error(404, "Order not found"); + // An orderId is an unguessable nanoid handed out by checkout/start; an + // order NUMBER is sequential, so paying by number needs the same proof + // as viewing the order (v4.5.1) — otherwise anyone could re-point a + // stranger's pending order at a new charge. + if ( + !order || + (!body.orderId && + !(await canViewOrder({ + order, + user: locals.user, + email: body.email, + cookies, + secret: env.BETTER_AUTH_SECRET, + }))) + ) { + throw error(404, "Order not found"); + } if (order.status !== "pending") { return json( { diff --git a/src/routes/api/shop/checkout/start/+server.ts b/src/routes/api/shop/checkout/start/+server.ts index 376052a2..c145bad3 100644 --- a/src/routes/api/shop/checkout/start/+server.ts +++ b/src/routes/api/shop/checkout/start/+server.ts @@ -37,6 +37,7 @@ import type { OrderAddress } from "$plugins/shop/order-service"; import { track, buildEventContext } from "$lib/server/analytics/track"; import { dispatchEvent } from "$lib/server/webhooks"; import { requireSameOrigin } from "$lib/server/http/same-origin"; +import { grantOrderAccess } from "$lib/server/shop/order-access"; import type { RequestHandler } from "./$types"; /** KV key recording when the reservation sweep last ran. */ @@ -412,6 +413,11 @@ export const POST: RequestHandler = async ({ } } + // Lets this browser open its own order page after paying — the + // payment provider returns the customer to /order/ with no + // email in the URL (order-access.ts). + await grantOrderAccess(cookies, env.BETTER_AUTH_SECRET, orderNumber); + return json({ ok: true, orderId, diff --git a/src/routes/api/shop/payment-recovery.node.test.ts b/src/routes/api/shop/payment-recovery.node.test.ts index 0b03638b..e795d6a9 100644 --- a/src/routes/api/shop/payment-recovery.node.test.ts +++ b/src/routes/api/shop/payment-recovery.node.test.ts @@ -86,14 +86,19 @@ describe("pay-by-orderNumber (#157)", () => { expect(paySrc).toContain("ORDER_NOT_PENDING"); }); - it("documents the accepted weak-secret risk", () => { - expect(paySrc).toContain("ACCEPTED RISK"); - expect(paySrc).toContain("worst case"); + it("no longer accepts the weak-secret risk: paying by number needs access (v4.5.1)", () => { + expect(paySrc).not.toContain("ACCEPTED RISK"); + expect(paySrc).toMatch(/!body\.orderId &&\s*!\(await canViewOrder\(/); }); it("responses stay minimal — no items, email, or address fields", () => { // The json() responses may carry the payment URL / QR and charge id, - // nothing else about the order. + // nothing else about the order. Scoped to the json(...) bodies: the + // REQUEST may carry an email as proof of access (v4.5.1). + const responses = [...paySrc.matchAll(/json\(\s*\{[\s\S]*?\}\s*[,)]/g)] + .map((m) => m[0]) + .join("\n"); + expect(responses).toContain("paymentUrl"); for (const forbidden of [ "items:", "email:", @@ -101,7 +106,7 @@ describe("pay-by-orderNumber (#157)", () => { "billingAddress", "totalSatang:", ]) { - expect(paySrc, forbidden).not.toContain(forbidden); + expect(responses, forbidden).not.toContain(forbidden); } }); @@ -144,7 +149,7 @@ describe("order page arrival states (#157)", () => { it("retry button POSTs the orderNumber to /checkout/pay", () => { expect(orderPageSrc).toContain("'/api/shop/checkout/pay'"); expect(orderPageSrc).toContain( - "JSON.stringify({ orderNumber: order.orderNumber })", + "JSON.stringify({ orderNumber: order.orderNumber, email: order.email })", ); });