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
169 changes: 169 additions & 0 deletions src/lib/server/shop/order-access.test.ts
Original file line number Diff line number Diff line change
@@ -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<string, string> = {}): 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> = {}): 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<Parameters<typeof canViewOrder>[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/);
});
});
110 changes: 110 additions & 0 deletions src/lib/server/shop/order-access.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
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<void> {
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<boolean> {
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<boolean> {
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);
}
Binary file modified src/routes/(www)/[locale]/order/[orderNumber]/+page.server.ts
Binary file not shown.
4 changes: 3 additions & 1 deletion src/routes/(www)/[locale]/order/[orderNumber]/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
39 changes: 30 additions & 9 deletions src/routes/api/shop/checkout/pay/+server.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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";
Expand All @@ -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";
Expand All @@ -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
Expand 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) {
Expand All @@ -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(
{
Expand Down
6 changes: 6 additions & 0 deletions src/routes/api/shop/checkout/start/+server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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. */
Expand Down Expand Up @@ -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/<number> with no
// email in the URL (order-access.ts).
await grantOrderAccess(cookies, env.BETTER_AUTH_SECRET, orderNumber);

return json({
ok: true,
orderId,
Expand Down
Loading
Loading