Skip to content
Open
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
5 changes: 5 additions & 0 deletions .changeset/order-poll-public-fields.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@dashcommerce/core": patch
---

Stop `GET /orders/by-draft` from returning the full stored order (#68). The route is public and its draft id travels in the thank-you URL, so the `ready` response now carries only what the thank-you page renders: order id, number, status, currency, total, a masked customer email, and each item's id, name, quantity and total. Addresses, Stripe ids, IP address, user agent, coupon codes, notes, metadata and vendor data are no longer exposed. The receipt line on the thank-you page now shows the masked email (`j***@example.com`).
68 changes: 60 additions & 8 deletions packages/core/src/routes/orders-public.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,9 @@
* - Returns `{ status: "failed" }` if the draft snapshot is gone and
* no order was created (Stripe webhook never arrived / PI failed).
*
* We don't leak arbitrary orders — access is keyed on `orderDraftId`
* which only the session that created the PI knows.
* Access is keyed on `orderDraftId`, but that id travels in the
* thank-you URL, so treat it as public: the "ready" response is reduced
* to the fields the thank-you page renders (see toPublicOrder).
*
* Why a query string instead of `/orders/by-draft/:id`? emdash's
* PluginRouteRegistry does an exact-string lookup on the route key — it
Expand Down Expand Up @@ -43,6 +44,59 @@ function json(body: unknown, status = 200): Response {
});
}

/**
* What the public thank-you poll is allowed to return.
*
* The route is unauthenticated: anyone holding the draft id (it sits in
* the thank-you URL, browser history and Referer headers) can call it.
* So the response carries only what the thank-you page renders: no
* addresses, Stripe ids, IP, user agent, metadata or vendor splits.
* The email is masked; the full address is in the receipt email.
*/
export interface PublicOrderSummary {
id: string;
orderNumber: string;
status: Order["status"];
customerEmail: string;
currency: Order["currency"];
total: Order["total"];
}

export interface PublicOrderItem {
id: string;
name: string;
quantity: number;
total: OrderItem["total"];
}

/** "jane.doe@example.com" → "j***@example.com". */
export function maskEmail(email: string | undefined): string {
if (!email) return "";
const at = email.lastIndexOf("@");
if (at <= 0) return "***";
return `${email[0]}***${email.slice(at)}`;
}

export function toPublicOrder(order: Order): PublicOrderSummary {
return {
id: order.id,
orderNumber: order.orderNumber,
status: order.status,
customerEmail: maskEmail(order.customerEmail),
currency: order.currency,
total: order.total,
};
}

export function toPublicOrderItem(item: OrderItem): PublicOrderItem {
return {
id: item.id,
name: item.name,
quantity: item.quantity,
total: item.total,
};
}

function parseDraftId(req: Request): string | null {
const url = new URL(req.url);
// Preferred: ?id=xxx (what the thank-you island sends).
Expand All @@ -54,7 +108,7 @@ function parseDraftId(req: Request): string | null {
// helper robust for tests / future matchers.
const parts = url.pathname.split("/").filter(Boolean);
const idx = parts.lastIndexOf("by-draft");
return idx === -1 ? null : parts[idx + 1] ?? null;
return idx === -1 ? null : (parts[idx + 1] ?? null);
}

export const ordersPublicRoutes = {
Expand All @@ -73,9 +127,7 @@ export const ordersPublicRoutes = {
limit: 200,
});
const match = recent.items.find((r) => {
const meta = (r.data as Order).metadata as
| { orderDraftId?: string }
| undefined;
const meta = (r.data as Order).metadata as { orderDraftId?: string } | undefined;
return meta?.orderDraftId === orderDraftId;
});
if (match) {
Expand All @@ -85,8 +137,8 @@ export const ordersPublicRoutes = {
where: { orderId: order.id },
limit: 200,
})
).items.map((r) => orderItemFromStorage(r.id, r.data as OrderItem));
return json({ status: "ready", order, items });
).items.map((r) => toPublicOrderItem(orderItemFromStorage(r.id, r.data as OrderItem)));
return json({ status: "ready", order: toPublicOrder(order), items });
}

// No order yet — is the draft snapshot still around?
Expand Down
163 changes: 163 additions & 0 deletions packages/core/test/orders-public.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,163 @@
import { describe, expect, it } from "bun:test";
import type { PluginContext, RouteContext } from "emdash";
import { maskEmail, ordersPublicRoutes } from "../src/routes/orders-public";

/**
* Regression tests for issue #68: the public /orders/by-draft poll must
* not return the full stored order (addresses, Stripe ids, IP, metadata).
*/

const DRAFT = "draft_abc123";

const storedOrder = {
orderNumber: "000042",
status: "processing",
paymentStatus: "paid",
customerId: "cus_internal_1",
customerEmail: "jane.doe@example.com",
currency: "USD",
billingAddress: { line1: "1 Secret St", city: "El Paso", postalCode: "79901" },
shippingAddress: { line1: "1 Secret St", city: "El Paso", postalCode: "79901" },
subtotal: { currency: "USD", amount: 2000 },
discountTotal: { currency: "USD", amount: 0 },
shippingTotal: { currency: "USD", amount: 0 },
taxTotal: { currency: "USD", amount: 0 },
total: { currency: "USD", amount: 2000 },
paidTotal: { currency: "USD", amount: 2000 },
refundedTotal: { currency: "USD", amount: 0 },
taxLines: [],
couponCodes: ["SECRET50"],
stripePaymentIntentId: "pi_secret",
stripeCustomerId: "cus_stripe_secret",
stripeChargeId: "ch_secret",
metadata: { orderDraftId: DRAFT, cartId: "cart_secret" },
ipAddress: "203.0.113.7",
userAgent: "SecretBrowser/1.0",
customerNote: "leave at back door",
createdAt: "2026-11-14T00:00:00.000Z",
updatedAt: "2026-11-14T00:00:00.000Z",
};

const storedItem = {
orderId: "ord_1",
productId: "prod_1",
sku: "SKU-1",
name: "Dossier No. 7",
quantity: 1,
unitPrice: { currency: "USD", amount: 2000 },
lineSubtotal: { currency: "USD", amount: 2000 },
discountAmount: { currency: "USD", amount: 0 },
taxAmount: { currency: "USD", amount: 0 },
total: { currency: "USD", amount: 2000 },
isDigital: true,
vendorId: "vendor_secret",
};

function ctxWithOrder(): PluginContext {
return {
storage: {
orders: {
query: async () => ({
items: [{ id: "ord_1", data: storedOrder }],
cursor: null,
hasMore: false,
}),
},
order_items: {
query: async () => ({
items: [{ id: "item_1", data: storedItem }],
cursor: null,
hasMore: false,
}),
},
},
kv: { get: async () => null },
} as unknown as PluginContext;
}

async function poll(ctx: PluginContext) {
const req = new Request(
`http://localhost/_emdash/api/plugins/dashcommerce/orders/by-draft?id=${DRAFT}`,
);
const res = await ordersPublicRoutes["orders/by-draft"].handler(
{ request: req } as RouteContext,
ctx,
);
return (await res.json()) as {
status: string;
order: Record<string, unknown>;
items: Record<string, unknown>[];
};
}

describe("GET /orders/by-draft (issue #68)", () => {
it("returns only the thank-you page fields", async () => {
const body = await poll(ctxWithOrder());
expect(body.status).toBe("ready");
expect(body.order).toEqual({
id: "ord_1",
orderNumber: "000042",
status: "processing",
customerEmail: "j***@example.com",
currency: "USD",
total: { currency: "USD", amount: 2000 },
});
expect(body.items).toEqual([
{
id: "item_1",
name: "Dossier No. 7",
quantity: 1,
total: { currency: "USD", amount: 2000 },
},
]);
});

it("leaks none of the sensitive stored values", async () => {
const raw = JSON.stringify(await poll(ctxWithOrder()));
for (const secret of [
"Secret St",
"pi_secret",
"cus_stripe_secret",
"ch_secret",
"cus_internal_1",
"203.0.113.7",
"SecretBrowser",
"cart_secret",
DRAFT,
"SECRET50",
"back door",
"vendor_secret",
"jane.doe",
]) {
expect(raw).not.toContain(secret);
}
});

it("still reports pending and failed states", async () => {
const empty = {
query: async () => ({ items: [], cursor: null, hasMore: false }),
};
const pending = {
storage: { orders: empty, order_items: empty },
kv: { get: async () => ({ snapshot: true }) },
} as unknown as PluginContext;
expect((await poll(pending)).status).toBe("pending");

const failed = {
storage: { orders: empty, order_items: empty },
kv: { get: async () => null },
} as unknown as PluginContext;
expect((await poll(failed)).status).toBe("failed");
});
});

describe("maskEmail", () => {
it("masks the local part", () => {
expect(maskEmail("jane.doe@example.com")).toBe("j***@example.com");
expect(maskEmail("a@b.co")).toBe("a***@b.co");
});
it("handles missing or malformed input", () => {
expect(maskEmail(undefined)).toBe("");
expect(maskEmail("not-an-email")).toBe("***");
});
});