Skip to content

Commit 4cd44e2

Browse files
fix(commerce-server): respect product listing channels in storefronts (#1532)
* fix(commerce-server): respect product listing channels in storefronts * update
1 parent 8f69cfd commit 4cd44e2

8 files changed

Lines changed: 135 additions & 15 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
"@godaddy/gd-commerce-server": patch
3+
---
4+
5+
Filter storefront product lists and product details by the server-configured Commerce channel. Active products unavailable on that channel no longer appear in lists or resolve through direct product links. Search, category filters, and explicit product IDs retain the channel filter; browser query parameters cannot override it.
6+
7+
Document stale-channel empty results and upstream channel lookup costs. Product browsing filters do not check channel eligibility for SKU lookup or cart writes; hosts must enforce any required restrictions on those operations.

‎packages/commerce-server/README.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,16 @@ Hosts with their own configuration service can implement `CommerceConfiguration`
5050

5151
The HTTP checkout route accepts an existing `draftOrderId` or a direct `skuId`; Commerce resolves catalog prices. It rejects `lineItemData`. For non-catalog charges such as fixed-price deposits, calculate the amount on the server and call `createCheckoutSession(params, configuration)` directly. Never forward browser-supplied prices to this trusted helper. Server callers can also use `getOrderStatus(orderId, configuration)` without an HTTP loopback.
5252

53+
### Product channel visibility
54+
55+
`GET /products` and `GET /products/:id` use the channel from the server configuration and request only `ACTIVE` products. Search, category filters, and explicit product IDs retain that channel filter. Product-detail requests for products unavailable on that channel return 404. Browser query parameters cannot select a different channel. Products configured for all channels remain available when the configured channel is active and registered to the store.
56+
57+
If a configured `GODADDY_CHANNEL_ID` is inactive or is not registered to the configured store, the Catalog API returns an empty product list and product-detail requests return 404. These are successful empty results from the Catalog API, not configuration errors. When an expected catalog is empty, verify that the channel is active and registered to `GODADDY_STORE_ID`, then check product status and channel assignments. A missing `GODADDY_CHANNEL_ID` is different: the default configuration reader rejects it with 503 `not_configured`.
58+
59+
The Catalog API resolves active store channels through the paginated `/v1/commerce/channels` endpoint when evaluating a channel filter. Those lookups are not currently cached by the Catalog API, so channel-filtered catalog requests can add upstream calls and latency.
60+
61+
These checks control product browsing. `GET /skus/:id`, cart creation (`POST /cart`), and item addition (`POST /cart/:id/items`) forward SKU IDs without this package checking whether their products are available on the configured channel. A 404 from product details does not establish that a SKU lookup or cart write will be rejected. Hosts that require channel-based restrictions on these operations must enforce them before forwarding the SKU IDs; browsing filters are not an authorization boundary.
62+
5363
## Checkout return destinations
5464

5565
Configure `checkoutReturnUrls` on the router using trusted deployment settings. Both lists contain complete absolute HTTPS URLs; scheme, origin, port, path, and configured query parameters must match. Success URLs may add a single `orderId` query parameter. Additional query parameters, fragments, credentials, relative URLs, and unlisted destinations are rejected. Configure separate cancel and success destinations as shown above; do not derive the allowlist from request headers or request bodies.

‎packages/commerce-server/src/configuration-integration.test.ts‎

Lines changed: 93 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,26 +10,30 @@ afterEach((): void => {
1010
vi.restoreAllMocks();
1111
});
1212

13-
it('serves variant product details without querying SKUGroup.status', async (): Promise<void> => {
13+
it('serves variant product details only on the configured channel without querying SKUGroup.status', async (): Promise<void> => {
1414
const upstream = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
1515
const { query, variables } = JSON.parse(String(init?.body)) as {
1616
query: string;
17-
variables: { id: string; attributeValues: string[] };
17+
variables: { id: string; attributeValues: string[]; channelId?: string };
1818
};
1919
if (/^\s+status\s*$/m.test(query)) {
2020
return Response.json({ errors: [{ message: 'Cannot query field "status" on type "SKUGroup".' }] });
2121
}
2222
expect(query).toContain(
23-
'activeSkuGroups: skuGroups(id: { in: [$id] }, status: { eq: "ACTIVE" }, first: 1)',
23+
'activeSkuGroups: skuGroups(id: { in: [$id] }, channelId: { eq: $channelId }, status: { eq: "ACTIVE" }, first: 1)',
2424
);
25-
expect(['shirt', 'archived-shirt']).toContain(variables.id);
25+
expect(['shirt', 'other-shirt', 'archived-shirt']).toContain(variables.id);
26+
const appliesChannelFilter = /channelId:\s*\{\s*eq:\s*\$channelId\s*\}/.test(query);
27+
const productChannel = variables.id === 'other-shirt' ? 'channel-2' : 'channel-1';
28+
const visible =
29+
variables.id !== 'archived-shirt' && (!appliesChannelFilter || variables.channelId === productChannel);
2630
const skus = [
2731
{ id: 'shirt-red', label: 'Red shirt' },
2832
{ id: 'shirt-blue', label: 'Blue shirt' },
2933
];
3034
return Response.json({
3135
data: {
32-
activeSkuGroups: { edges: variables.id === 'shirt' ? [{ node: { id: 'shirt' } }] : [] },
36+
activeSkuGroups: { edges: visible ? [{ node: { id: variables.id } }] : [] },
3337
skuGroup: {
3438
id: variables.id,
3539
label: 'Shirt',
@@ -101,7 +105,90 @@ it('serves variant product details without querying SKUGroup.status', async ():
101105
code: 'not_found',
102106
requestId: expect.any(String),
103107
});
104-
expect(upstream).toHaveBeenCalledTimes(3);
108+
const otherChannel = await clientFetch(`${url.replace('/shirt', '/other-shirt')}?channelId=channel-2`);
109+
expect(otherChannel.status).toBe(404);
110+
expect(await otherChannel.json()).toEqual({
111+
error: 'Product not found',
112+
code: 'not_found',
113+
requestId: expect.any(String),
114+
});
115+
expect(upstream).toHaveBeenCalledTimes(4);
116+
} finally {
117+
await new Promise<void>((resolve, reject) =>
118+
server.close((error) => (error ? reject(error) : resolve())),
119+
);
120+
}
121+
});
122+
123+
it('filters product lists by the current server channel with every catalog filter', async (): Promise<void> => {
124+
const environment = {
125+
GODADDY_OAUTH_CLIENT_ID: 'client-1',
126+
GODADDY_OAUTH_CLIENT_SECRET: 'secret-1',
127+
GODADDY_STORE_ID: 'store-1',
128+
GODADDY_CHANNEL_ID: 'channel-1',
129+
GODADDY_CURRENCY_CODE: 'USD',
130+
};
131+
const products = [
132+
{ id: 'shirt', channelId: 'channel-1' },
133+
{ id: 'other-shirt', channelId: 'channel-2' },
134+
{ id: 'all-channels-shirt', channelId: null },
135+
];
136+
const upstream = vi.fn(async (_input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
137+
const { query, variables } = JSON.parse(String(init?.body)) as {
138+
query: string;
139+
variables: { channelId?: string };
140+
};
141+
// Catalog products without custom channel assignments remain available on all channels.
142+
const appliesChannelFilter = /channelId:\s*\{\s*eq:\s*\$channelId\s*\}/.test(query);
143+
const visible = products.filter(
144+
(product) =>
145+
!appliesChannelFilter || product.channelId === null || product.channelId === variables.channelId,
146+
);
147+
return Response.json({ data: { skuGroups: { edges: visible.map(({ id }) => ({ node: { id } })) } } });
148+
});
149+
vi.stubGlobal('fetch', upstream);
150+
const app = express();
151+
app.use(
152+
'/api/commerce',
153+
createCommerceRouter({ configuration: createRuntimeCommerceConfiguration({ environment }) }),
154+
);
155+
const server = app.listen(0, '127.0.0.1');
156+
await once(server, 'listening');
157+
try {
158+
const address = server.address();
159+
if (!address || typeof address === 'string') throw new Error('Expected a listening TCP server');
160+
const url = `http://127.0.0.1:${address.port}/api/commerce/products`;
161+
const cases = [
162+
['', { first: 24 }],
163+
['?first=12&after=page-2', { first: 12, after: 'page-2' }],
164+
['?searchQuery=shirt', { first: 24, label: { contains: 'shirt' } }],
165+
[
166+
'?productIds=shirt&productIds=other-shirt&productIds=all-channels-shirt&searchQuery=ignored',
167+
{ first: 24, id: { in: ['shirt', 'other-shirt', 'all-channels-shirt'] } },
168+
],
169+
[
170+
'?categoryIds=clothing&categoryIds=sale&searchQuery=ignored',
171+
{ first: 24, listId: { in: ['clothing', 'sale'] } },
172+
],
173+
['?channelId=channel-2', { first: 24 }],
174+
] as const;
175+
for (const [search, filters] of cases) {
176+
const response = await clientFetch(`${url}${search}`);
177+
expect(response.status).toBe(200);
178+
expect(await response.json()).toEqual({
179+
skuGroups: { edges: [{ node: { id: 'shirt' } }, { node: { id: 'all-channels-shirt' } }] },
180+
});
181+
const request = JSON.parse(String(upstream.mock.lastCall?.[1]?.body));
182+
expect(request.variables).toEqual({ ...filters, channelId: 'channel-1' });
183+
expect(request.query).toContain('$channelId: String!');
184+
}
185+
environment.GODADDY_CHANNEL_ID = 'channel-2';
186+
const rebound = await clientFetch(url);
187+
expect(rebound.status).toBe(200);
188+
expect(await rebound.json()).toEqual({
189+
skuGroups: { edges: [{ node: { id: 'other-shirt' } }, { node: { id: 'all-channels-shirt' } }] },
190+
});
191+
expect(upstream).toHaveBeenCalledTimes(cases.length + 1);
105192
} finally {
106193
await new Promise<void>((resolve, reject) =>
107194
server.close((error) => (error ? reject(error) : resolve())),

‎packages/commerce-server/src/lib/commerce/catalog-subgraph.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,7 @@ export interface LabelFilter {
127127
}
128128

129129
export interface SkuGroupsVariables {
130+
channelId: string;
130131
first?: number | null;
131132
after?: string | null;
132133
id?: StringInFilter;
@@ -135,6 +136,7 @@ export interface SkuGroupsVariables {
135136
}
136137

137138
export interface SkuGroupVariables {
139+
channelId: string;
138140
id: string;
139141
first?: number | null;
140142
/** Attribute value `name` fields — the catalog API's `has` filter matches by `name`, not `id`. */
@@ -158,6 +160,7 @@ export interface SkuResult {
158160
}
159161

160162
export interface ProductGridVariablesInput {
163+
channelId: string;
161164
first?: number | null;
162165
after?: string | null;
163166
productIds?: readonly string[];
@@ -166,6 +169,7 @@ export interface ProductGridVariablesInput {
166169
}
167170

168171
export interface ProductDetailsVariablesInput {
172+
channelId: string;
169173
productId: string;
170174
/** Attribute value `name` fields, not `id`. */
171175
selectedAttributeValues?: readonly string[];
@@ -204,6 +208,7 @@ export function buildSkuGroupsVariables(input: ProductGridVariablesInput): SkuGr
204208
const hasExplicitFilters = productIds.length > 0 || categoryIds.length > 0;
205209

206210
return {
211+
channelId: input.channelId,
207212
...(input.first !== undefined && { first: input.first }),
208213
...(input.after && { after: input.after }),
209214
...(productIds.length > 0 && { id: { in: [...productIds] } }),
@@ -213,13 +218,15 @@ export function buildSkuGroupsVariables(input: ProductGridVariablesInput): SkuGr
213218
}
214219

215220
export function buildSkuGroupVariables({
221+
channelId,
216222
productId,
217223
selectedAttributeValues,
218224
skuGroupFirst,
219225
}: ProductDetailsVariablesInput): SkuGroupVariables {
220226
const attributeValues = selectedAttributeValues ? [...selectedAttributeValues] : [];
221227

222228
return {
229+
channelId,
223230
id: productId,
224231
attributeValues,
225232
...(!attributeValues.length && { first: skuGroupFirst ?? 50 }),

‎packages/commerce-server/src/router.test.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -106,15 +106,17 @@ describe('Commerce scoped routes', () => {
106106
res as unknown as Response,
107107
);
108108
expect(gqlRequest).toHaveBeenCalledWith(
109-
expect.objectContaining({ variables: { id: 'product', attributeValues: ['red', 'large'] } }),
109+
expect.objectContaining({
110+
variables: { channelId: 'channel-1', id: 'product', attributeValues: ['red', 'large'] },
111+
}),
110112
);
111113
const query: string = vi.mocked(gqlRequest).mock.calls[0]?.[0].query ?? '';
112114
expect(query).toContain('prices(first: 10)');
113115
expect(query).toContain('inventoryCounts');
114116
expect(query).toContain('attributeValues(first: 50) {');
115117
expect(query).toContain('pageInfo { hasNextPage }');
116118
expect(query).toContain(
117-
'activeSkuGroups: skuGroups(id: { in: [$id] }, status: { eq: "ACTIVE" }, first: 1)',
119+
'activeSkuGroups: skuGroups(id: { in: [$id] }, channelId: { eq: $channelId }, status: { eq: "ACTIVE" }, first: 1)',
118120
);
119121
expect(query).toMatch(/skuGroup\(id: \$id\) \{\s+id\s+name/);
120122
expect(query).not.toMatch(/^\s+status\s*$/m);

‎packages/commerce-server/src/server/api/commerce/products/GET.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
* the catalog subgraph directly so the browser never sees `X-Store-ID` /
77
* `X-Client-ID` and the server can layer caching, abuse protection, or
88
* per-tenant filtering later without touching the client.
9+
* Only ACTIVE products available on the server-configured channel are returned.
910
*
1011
* Query params (all optional):
1112
* first - page size (number)
@@ -32,8 +33,9 @@ import { gqlRequest, storefrontHeaders } from '@/lib/commerce/gql';
3233
// Cards use group pricing/media and SKU identity/inventory for quick-add.
3334
// Nested SKU price money fields would exceed the catalog API's depth limit of 10.
3435
const skuGroupsQuery = `
35-
query SkuGroups($first: Int, $after: String, $id: SKUGroupIdsFilter, $listId: ListIdFilter, $label: LabelFilter) {
36+
query SkuGroups($channelId: String!, $first: Int, $after: String, $id: SKUGroupIdsFilter, $listId: ListIdFilter, $label: LabelFilter) {
3637
skuGroups(
38+
channelId: { eq: $channelId }
3739
first: $first
3840
after: $after
3941
id: $id
@@ -134,9 +136,10 @@ function asNumber(value: unknown): number | undefined {
134136
async function listProducts(req: Request, res: Response): Promise<void> {
135137
const config: CommerceConfig = readCommerceConfigForResponse(res);
136138
assertCommerceCartScope(req, config);
137-
const { storeId, clientId, apiBaseUrl } = config;
139+
const { storeId, channelId, clientId, apiBaseUrl } = config;
138140

139141
const variables = buildSkuGroupsVariables({
142+
channelId,
140143
first: asNumber(req.query.first) ?? 24,
141144
after: typeof req.query.after === 'string' ? req.query.after : undefined,
142145
searchQuery: typeof req.query.searchQuery === 'string' ? req.query.searchQuery : undefined,

‎packages/commerce-server/src/server/api/commerce/products/[id]/GET.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,8 @@
22
* GET /api/commerce/products/:id
33
*
44
* Proxy for the catalog `skuGroup` query — single-product (PDP) detail.
5-
* Only ACTIVE groups appear on a product page, matching the catalog list.
5+
* Only ACTIVE groups available on the configured channel appear on a product
6+
* page, matching the catalog list.
67
* Re-call this route after the user picks attribute values to narrow the
78
* SKU set (pass `?attributeValues=red&attributeValues=large`). Use the
89
* `getSingleMatchedSku` helper returns the selected SKU, including price,
@@ -33,8 +34,8 @@ import { gqlRequest, storefrontHeaders } from '@/lib/commerce/gql';
3334
type ProductDetailsResult = SkuGroupResult & { activeSkuGroups?: SkuGroupsResult['skuGroups'] };
3435

3536
const skuGroupQuery = `
36-
query SkuGroup($id: String!, $first: Int, $attributeValues: [String!] = []) {
37-
activeSkuGroups: skuGroups(id: { in: [$id] }, status: { eq: "ACTIVE" }, first: 1) {
37+
query SkuGroup($channelId: String!, $id: String!, $first: Int, $attributeValues: [String!] = []) {
38+
activeSkuGroups: skuGroups(id: { in: [$id] }, channelId: { eq: $channelId }, status: { eq: "ACTIVE" }, first: 1) {
3839
edges { node { id } }
3940
}
4041
skuGroup(id: $id) {
@@ -139,9 +140,10 @@ async function readProduct(req: Request, res: Response): Promise<void> {
139140

140141
const config: CommerceConfig = readCommerceConfigForResponse(res);
141142
assertCommerceCartScope(req, config);
142-
const { storeId, clientId, apiBaseUrl } = config;
143+
const { storeId, channelId, clientId, apiBaseUrl } = config;
143144

144145
const variables = buildSkuGroupVariables({
146+
channelId,
145147
productId,
146148
selectedAttributeValues: asStringArray(req.query.attributeValues),
147149
skuGroupFirst: asNumber(req.query.skuGroupFirst),

‎packages/commerce-storefront/docs/server-api.md‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ Server implementations can use GoDaddy Commerce APIs or their existing integrati
3131

3232
`/checkout` is required only when checkout is enabled. `/discounts` is needed if the host uses `applyDiscount`. The standard catalog/detail/cart flow uses the other routes. All product/cart IDs in request paths are encoded.
3333

34-
The companion `@godaddy/gd-commerce-server` returns 404 from product details when the group is missing or excluded by the catalog's ACTIVE filter, including direct links to inactive products.
34+
The companion `@godaddy/gd-commerce-server` filters `GET /products` to ACTIVE groups available on the server-configured channel. It returns 404 from `GET /products/:id` when the group is missing, inactive, or unavailable on that channel, including direct product links. Browser callers cannot override the configured channel. This browsing filter does not check product-channel eligibility for `GET /skus/:id`, cart creation, or item addition by SKU ID; hosts must enforce any required restrictions on those operations. See the [server package's channel visibility notes][server-channel-visibility] for stale-channel troubleshooting and upstream lookup costs.
35+
36+
[server-channel-visibility]: ../../commerce-server/README.md#product-channel-visibility
3537

3638
## Configuration
3739

0 commit comments

Comments
 (0)