@porulle/adapter-shopify 0.87.0 → 0.88.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,40 +1,3 @@
1
1
  # @porulle/adapter-shopify
2
2
 
3
3
  Shopify ingress channel connector for Porulle.
4
-
5
- ## Catalog push and re-authorisation
6
-
7
- Catalog push requires the `write_products` OAuth scope. The adapter advertises
8
- `capabilities.pushCatalog: true`, but effective push access is resolved per
9
- store from `credentials.grantedScopes` recorded during OAuth (`completeAuth`).
10
-
11
- Stores connected before `write_products` was added to `REQUIRED_SCOPES` hold
12
- tokens without that scope. When push is attempted, the adapter returns
13
- `SHOPIFY_WRITE_PRODUCTS_SCOPE_MISSING` with `retriable: false` and a link to
14
- Porulle's OAuth start route (when `appUrl` is configured).
15
-
16
- Operators can recover without disconnecting the store:
17
-
18
- 1. Start Shopify OAuth again for the same store (`/api/channels/oauth/shopify/start` in a Porulle app with this adapter configured).
19
- 2. Approve the updated scope list, which now includes `write_products`.
20
- 3. Retry the catalog push job.
21
-
22
- Use `shopifyReauthorizeUrl(options, params)` to build the authorize URL outside
23
- the push error path, or `shopifyPushCatalogEnabled(store)` to check scope
24
- coverage before enqueueing work.
25
-
26
- ## Product images
27
-
28
- `pushCatalog` writes `item.images` to the product's images through the Admin
29
- REST API (`/products/{id}/images.json`). Roles `primary`, `gallery` and
30
- `thumbnail` are written as images; `video` and `document` fail the item with
31
- `SHOPIFY_IMAGE_ROLE_UNSUPPORTED`. The `primary` image is written first and
32
- takes position 1, the rest follow `sortOrder`; `alt` and `variantExternalIds`
33
- map to the image's `alt` and `variant_ids`.
34
-
35
- Each item outcome carries `images[]` with the Shopify image id as
36
- `externalId`. Persist it and send it back as `image.externalId` on the next
37
- push so the adapter updates that image in place. Without an id the adapter
38
- falls back to matching the uploaded file name against the CDN path Shopify
39
- keeps (`boot.jpg` matches `boot.jpg` and `boot_a1b2c3.jpg`); a file name that
40
- matches nothing creates a new image. Dry runs do not touch images.
package/dist/graphql.js CHANGED
@@ -95,7 +95,9 @@ export async function shopifyGraphql(target, query, variables, schema) {
95
95
  if (errors.length > 0) {
96
96
  const message = errors.map((error) => error.message ?? "unknown error").join("; ");
97
97
  const denied = errors.some((error) => error.extensions?.code === "ACCESS_DENIED");
98
- return Err({ code: denied ? "SHOPIFY_ACCESS_DENIED" : "SHOPIFY_GRAPHQL_ERROR", message: `Shopify GraphQL error: ${message}`, retriable: false });
98
+ const customerDataBlocked = denied && (/not approved to access the Order object/i.test(message) || /protected[- ]customer[- ]data/i.test(message));
99
+ const code = customerDataBlocked ? "SHOPIFY_CUSTOMER_DATA_NOT_ALLOWED" : denied ? "SHOPIFY_ACCESS_DENIED" : "SHOPIFY_GRAPHQL_ERROR";
100
+ return Err({ code, message: `Shopify GraphQL error: ${message}`, retriable: false });
99
101
  }
100
102
  const data = schema.safeParse(envelope?.data);
101
103
  if (!data.success) {
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
- import type { ChannelConnector } from "@porulle/core";
1
+ import type { ChannelConnector, ChannelConnectorError, Result } from "@porulle/core";
2
2
  export { SHOPIFY_API_VERSION } from "./graphql.js";
3
3
  export { CATALOG_ITEMS_QUERY, CATALOG_PAGE_QUERY, VARIANTS_PAGE_QUERY } from "./catalog.js";
4
4
  export { INVENTORY_ITEM_VARIANT_QUERY } from "./webhooks.js";
5
- export { REQUIRED_SCOPES, normalizeShopDomain, parseShopifyCredentials } from "./oauth.js";
5
+ export { REQUIRED_SCOPES, exchangeIdToken, mintClientCredentials, missingScopes, normalizeShopDomain, parseShopifyCredentials, validShopDomain, verifyShopifyIdToken } from "./oauth.js";
6
6
  export type { ShopifyCredentials } from "./oauth.js";
7
7
  export interface ShopifyConnectorOptions {
8
8
  clientId: string;
@@ -34,5 +34,29 @@ export declare const ORDER_FULFILLMENT_LINES_QUERY = "query PorulleOrderFulfillm
34
34
  export declare const RETURN_REASON_QUERY = "query PorulleReturnReasons($handles: [String!]) {\n returnReasonDefinitions(first: 2, handles: $handles) { nodes { id handle } }\n}";
35
35
  export declare const RETURN_REQUEST_MUTATION = "mutation PorulleReturnRequest($input: ReturnRequestInput!) {\n returnRequest(input: $input) { return { id } userErrors { code message } }\n}";
36
36
  export declare const ORDER_BY_SOURCE_QUERY = "query PorulleOrderBySource($query: String!) {\n orders(first: 1, query: $query) { nodes { legacyResourceId } }\n}";
37
+ /**
38
+ * Every topic this connector acts on (see `decodeShopifyWebhook`), in Shopify's header spelling, less
39
+ * the compliance topics: those are app configuration only, and Shopify's `WebhookSubscriptionTopic`
40
+ * has no value for them. An app whose configuration declares its subscriptions (`shopify.app.toml`)
41
+ * lists exactly these; an app that cannot carry ours is subscribed with {@link subscribeShopifyWebhooks}.
42
+ */
43
+ export declare const SHOPIFY_WEBHOOK_TOPICS: readonly ["products/create", "products/update", "products/delete", "inventory_levels/update", "orders/fulfilled", "orders/partially_fulfilled", "orders/cancelled", "refunds/create", "returns/approve", "returns/decline", "returns/close", "returns/cancel", "app/uninstalled"];
44
+ export declare const WEBHOOK_SUBSCRIPTIONS_QUERY = "query PorulleWebhookSubscriptions($uri: String!) {\n webhookSubscriptions(first: 100, uri: $uri) { nodes { topic } }\n}";
45
+ export declare const WEBHOOK_SUBSCRIPTION_CREATE_MUTATION = "mutation PorulleWebhookSubscriptionCreate($topic: WebhookSubscriptionTopic!, $webhookSubscription: WebhookSubscriptionInput!) {\n webhookSubscriptionCreate(topic: $topic, webhookSubscription: $webhookSubscription) { webhookSubscription { id } userErrors { field message } }\n}";
46
+ /**
47
+ * Subscribes the app that holds `accessToken` to every {@link SHOPIFY_WEBHOOK_TOPICS} topic on this
48
+ * store, delivered to `uri`, creating only the subscriptions missing — so connecting again does not
49
+ * double the deliveries. For an app whose configuration does not carry our subscriptions: a merchant's
50
+ * own Dev Dashboard app, connected with the client credentials grant. Deliveries are signed with that
51
+ * app's client secret.
52
+ */
53
+ export declare function subscribeShopifyWebhooks(params: {
54
+ origin: string;
55
+ accessToken: string;
56
+ uri: string;
57
+ fetchImpl?: typeof fetch;
58
+ }): Promise<Result<{
59
+ created: number;
60
+ }, ChannelConnectorError>>;
37
61
  export declare const ORDER_STATUS_QUERY = "query PorulleOrderStatus($id: ID!) {\n order(id: $id) { cancelledAt displayFinancialStatus displayFulfillmentStatus }\n}";
38
62
  export declare function shopifyConnector(options: ShopifyConnectorOptions): ChannelConnector;
package/dist/index.js CHANGED
@@ -2,13 +2,13 @@ import { createHmac, timingSafeEqual } from "node:crypto";
2
2
  import { CHANNEL_CANCEL_REFUSED, CHANNEL_OUT_OF_STOCK, defineChannelConnector, Err, Ok } from "@porulle/core";
3
3
  import { z } from "zod";
4
4
  import { readCatalogItems, readCatalogPage } from "./catalog.js";
5
- import { decodeShopifyWebhook } from "./webhooks.js";
5
+ import { decodeReadsTheStore, decodeShopifyWebhook, isComplianceTopic, minimizeShopifyWebhookPayload } from "./webhooks.js";
6
6
  import { shopifyGid, shopifyGraphql } from "./graphql.js";
7
7
  import { REQUIRED_SCOPES, buildAuthorizeUrl, exchangeCallback, normalizeShopDomain, parseShopifyCredentials, refreshIfExpiring, validShopDomain, } from "./oauth.js";
8
8
  export { SHOPIFY_API_VERSION } from "./graphql.js";
9
9
  export { CATALOG_ITEMS_QUERY, CATALOG_PAGE_QUERY, VARIANTS_PAGE_QUERY } from "./catalog.js";
10
10
  export { INVENTORY_ITEM_VARIANT_QUERY } from "./webhooks.js";
11
- export { REQUIRED_SCOPES, normalizeShopDomain, parseShopifyCredentials } from "./oauth.js";
11
+ export { REQUIRED_SCOPES, exchangeIdToken, mintClientCredentials, missingScopes, normalizeShopDomain, parseShopifyCredentials, validShopDomain, verifyShopifyIdToken } from "./oauth.js";
12
12
  export const INVENTORY_QUERY = `query PorulleInventoryPage($after: String) {
13
13
  productVariants(first: 250, after: $after, sortKey: ID) { pageInfo { hasNextPage endCursor } nodes { legacyResourceId inventoryQuantity } }
14
14
  }`;
@@ -51,6 +51,74 @@ export const RETURN_REQUEST_MUTATION = `mutation PorulleReturnRequest($input: Re
51
51
  export const ORDER_BY_SOURCE_QUERY = `query PorulleOrderBySource($query: String!) {
52
52
  orders(first: 1, query: $query) { nodes { legacyResourceId } }
53
53
  }`;
54
+ /**
55
+ * Every topic this connector acts on (see `decodeShopifyWebhook`), in Shopify's header spelling, less
56
+ * the compliance topics: those are app configuration only, and Shopify's `WebhookSubscriptionTopic`
57
+ * has no value for them. An app whose configuration declares its subscriptions (`shopify.app.toml`)
58
+ * lists exactly these; an app that cannot carry ours is subscribed with {@link subscribeShopifyWebhooks}.
59
+ */
60
+ export const SHOPIFY_WEBHOOK_TOPICS = [
61
+ "products/create",
62
+ "products/update",
63
+ "products/delete",
64
+ "inventory_levels/update",
65
+ "orders/fulfilled",
66
+ "orders/partially_fulfilled",
67
+ "orders/cancelled",
68
+ "refunds/create",
69
+ "returns/approve",
70
+ "returns/decline",
71
+ "returns/close",
72
+ "returns/cancel",
73
+ "app/uninstalled",
74
+ ];
75
+ export const WEBHOOK_SUBSCRIPTIONS_QUERY = `query PorulleWebhookSubscriptions($uri: String!) {
76
+ webhookSubscriptions(first: 100, uri: $uri) { nodes { topic } }
77
+ }`;
78
+ export const WEBHOOK_SUBSCRIPTION_CREATE_MUTATION = `mutation PorulleWebhookSubscriptionCreate($topic: WebhookSubscriptionTopic!, $webhookSubscription: WebhookSubscriptionInput!) {
79
+ webhookSubscriptionCreate(topic: $topic, webhookSubscription: $webhookSubscription) { webhookSubscription { id } userErrors { field message } }
80
+ }`;
81
+ const webhookSubscriptionsSchema = z.object({ webhookSubscriptions: z.object({ nodes: z.array(z.object({ topic: z.string() })) }) });
82
+ const webhookSubscriptionCreateSchema = z.object({
83
+ webhookSubscriptionCreate: z.object({
84
+ webhookSubscription: z.object({ id: z.string() }).nullable(),
85
+ userErrors: z.array(z.object({ field: z.array(z.string()).nullable(), message: z.string() })),
86
+ }),
87
+ });
88
+ /** `inventory_levels/update` → `INVENTORY_LEVELS_UPDATE`: the header spelling and the enum name of one topic. */
89
+ function webhookTopicEnum(topic) {
90
+ return topic.replaceAll("/", "_").toUpperCase();
91
+ }
92
+ /**
93
+ * Subscribes the app that holds `accessToken` to every {@link SHOPIFY_WEBHOOK_TOPICS} topic on this
94
+ * store, delivered to `uri`, creating only the subscriptions missing — so connecting again does not
95
+ * double the deliveries. For an app whose configuration does not carry our subscriptions: a merchant's
96
+ * own Dev Dashboard app, connected with the client credentials grant. Deliveries are signed with that
97
+ * app's client secret.
98
+ */
99
+ export async function subscribeShopifyWebhooks(params) {
100
+ const target = { fetchImpl: params.fetchImpl ?? fetch, origin: params.origin, accessToken: params.accessToken };
101
+ const existing = await shopifyGraphql(target, WEBHOOK_SUBSCRIPTIONS_QUERY, { uri: params.uri }, webhookSubscriptionsSchema);
102
+ if (!existing.ok)
103
+ return existing;
104
+ const held = new Set(existing.value.webhookSubscriptions.nodes.map((node) => node.topic));
105
+ let created = 0;
106
+ for (const topic of SHOPIFY_WEBHOOK_TOPICS.map(webhookTopicEnum).filter((name) => !held.has(name))) {
107
+ const answer = await shopifyGraphql(target, WEBHOOK_SUBSCRIPTION_CREATE_MUTATION, { topic, webhookSubscription: { uri: params.uri } }, webhookSubscriptionCreateSchema);
108
+ if (!answer.ok)
109
+ return answer;
110
+ const { webhookSubscription, userErrors } = answer.value.webhookSubscriptionCreate;
111
+ if (userErrors.length > 0 || !webhookSubscription) {
112
+ const detail = userErrors.map((error) => error.message).join("; ") || "no subscription returned";
113
+ const code = userErrors.some((error) => /protected[- ]customer[- ]data/i.test(error.message))
114
+ ? "SHOPIFY_CUSTOMER_DATA_NOT_ALLOWED"
115
+ : "SHOPIFY_WEBHOOK_SUBSCRIPTION_REFUSED";
116
+ return Err({ code, message: `Shopify refused the ${topic} subscription: ${detail}.`, retriable: false });
117
+ }
118
+ created += 1;
119
+ }
120
+ return Ok({ created });
121
+ }
54
122
  export const ORDER_STATUS_QUERY = `query PorulleOrderStatus($id: ID!) {
55
123
  order(id: $id) { cancelledAt displayFinancialStatus displayFulfillmentStatus }
56
124
  }`;
@@ -244,7 +312,6 @@ export function shopifyConnector(options) {
244
312
  const already = existing.value.orders.nodes[0];
245
313
  if (already)
246
314
  return Ok({ remoteOrderId: already.legacyResourceId });
247
- const [firstName, ...rest] = slice.customer.name.trim().split(/\s+/);
248
315
  const address = slice.customer.shippingAddress;
249
316
  // Shopify takes a province as its CODE. A region the shopper typed as a name is kept for the
250
317
  // courier on the second address line rather than sent where Shopify would reject it.
@@ -262,6 +329,11 @@ export function shopifyConnector(options) {
262
329
  countryCode: address.countryCode,
263
330
  ...(address.phone ? { phone: address.phone } : {}),
264
331
  };
332
+ // No `customer.toUpsert`: measured on live Shopify (2026-11-24), `orderCreate` with
333
+ // `customer.toUpsert` for an email that already exists as a customer fails with ACCESS_DENIED
334
+ // ("Required access: `write_customers` access scope to update an existing customer with
335
+ // `customer.toUpsert`"). Passing `email` and `shippingAddress` alone creates orders for new,
336
+ // existing and repeat emails, and the brand's admin shows name, email, phone and address.
265
337
  const created = await shopifyGraphql(shop, ORDER_CREATE_MUTATION, {
266
338
  order: {
267
339
  sourceName: SOURCE_NAME,
@@ -269,7 +341,6 @@ export function shopifyConnector(options) {
269
341
  currency: slice.currency,
270
342
  email: slice.customer.email,
271
343
  financialStatus: "PAID",
272
- customer: { toUpsert: { email: slice.customer.email, firstName: firstName ?? "", lastName: rest.join(" ") } },
273
344
  shippingAddress,
274
345
  lineItems: slice.lines.map((line) => ({
275
346
  variantId: shopifyGid("ProductVariant", line.externalVariantId),
@@ -395,11 +466,26 @@ export function shopifyConnector(options) {
395
466
  catch {
396
467
  return Err({ code: "INVALID_APP_WEBHOOK", message: "Shopify webhook body must be valid JSON.", retriable: false });
397
468
  }
469
+ // The HMAC proves which app sent this, not which shop: the shop is a header. The compliance topics
470
+ // also name their shop inside the signed body, and a sender holding the app's secret could pair
471
+ // any body with any header, so the two must agree before anything is erased on either's say.
472
+ if (isComplianceTopic(topic)) {
473
+ const named = typeof data === "object" && data !== null && "shop_domain" in data && typeof data.shop_domain === "string" ? data.shop_domain.toLowerCase() : undefined;
474
+ if (named !== shopDomain)
475
+ return Err({ code: "INVALID_APP_WEBHOOK", message: "The shop in the webhook body does not match the shop in its headers.", retriable: false });
476
+ }
477
+ // An uninstall names its shop in the body too (`myshopify_domain`), where it carries it. The same pairing
478
+ // argument holds: it takes a store's grant away, so a body for one shop must not ride a header for another.
479
+ if (topic === "app/uninstalled" && typeof data === "object" && data !== null && "myshopify_domain" in data && typeof data.myshopify_domain === "string" && data.myshopify_domain.toLowerCase() !== shopDomain) {
480
+ return Err({ code: "INVALID_APP_WEBHOOK", message: "The shop in the webhook body does not match the shop in its headers.", retriable: false });
481
+ }
398
482
  return Ok({ id, topic, shopDomain, data });
399
483
  },
400
484
  async decodeWebhook(store, event) {
401
485
  return decodeShopifyWebhook(target(store), event);
402
486
  },
487
+ decodeWebhookNeedsCredentials: (event) => decodeReadsTheStore(event.type),
488
+ minimizeWebhookPayload: minimizeShopifyWebhookPayload,
403
489
  async refundExecute() {
404
490
  return Err({ code: "NOT_IMPLEMENTED", message: "Refunds are issued by the platform, not executed in the Shopify store." });
405
491
  },
package/dist/oauth.d.ts CHANGED
@@ -1,25 +1,50 @@
1
1
  import type { ChannelConnectorError, Result } from "@porulle/core";
2
2
  /**
3
- * Shopify's OAuth for a standalone (non-embedded) app: the authorization code grant, asking for an
4
- * EXPIRING offline token. Shopify requires expiring offline tokens of every new public app calling the
5
- * GraphQL Admin API: a one-hour access token and a 90-day refresh token that rotates on every refresh.
6
- * https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens
3
+ * Shopify's two grants an app connects a store with.
4
+ *
5
+ * - The authorization code grant, for an app the merchant installs from us (public or custom
6
+ * distribution), asking for an EXPIRING offline token: Shopify requires them of every new public
7
+ * app calling the GraphQL Admin API — a one-hour access token and a 90-day refresh token that
8
+ * rotates on every refresh.
9
+ * https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens
10
+ * - The client credentials grant, for an app that belongs to the SAME Shopify organization as the
11
+ * store: a merchant's own Dev Dashboard app, whose client id and secret the merchant hands over.
12
+ * The token lives 24 hours and there is no refresh token; a new one is minted with the same client
13
+ * id and secret. Shopify refuses it with `shop_not_permitted` across organizations.
14
+ * https://shopify.dev/docs/apps/build/authentication-authorization/client-credentials-grant
15
+ * - The token exchange grant, for an app Shopify installs itself (managed installation) and loads
16
+ * inside the admin: App Bridge hands the page a one-minute ID token, and the app trades it for the
17
+ * same expiring offline token. Shopify keeps ONE current offline token per app and store, so a
18
+ * successful exchange retires the refresh tokens an earlier grant of that app issued.
19
+ * https://shopify.dev/docs/apps/build/authentication-authorization/implement-token-exchange
7
20
  */
8
21
  /**
9
- * The scopes the connector's live paths need, and nothing else.
22
+ * The scopes the connector's live paths need, and nothing else. Nothing about a product is ever
23
+ * pushed to a merchant's Shopify — only orders reach it — so there is no `write_products` here.
10
24
  *
11
- * - `read_products`, `write_products`: the catalogue import, and the Loom metafield write-back.
25
+ * - `read_products`: the catalogue import.
12
26
  * - `read_inventory`: variant stock and the inventory item behind a stock webhook.
13
27
  * - `write_orders`: a paid platform order is created in the store (`orderCreate`). A write scope
14
28
  * includes its read scope, which `orders/fulfilled` and `orders/cancelled` need.
15
29
  * - `read_returns`, `write_returns`: a shopper's return is asked of the store (`returnRequest`) and
16
30
  * its `returns/*` webhooks say how the store answered.
17
31
  */
18
- export declare const REQUIRED_SCOPES: readonly ["read_products", "write_products", "read_inventory", "write_orders", "read_returns", "write_returns"];
32
+ export declare const REQUIRED_SCOPES: readonly ["read_products", "read_inventory", "write_orders", "read_returns", "write_returns"];
19
33
  /** Refresh this long before Shopify's stated expiry, so a call never starts on a token about to lapse. */
20
34
  export declare const ACCESS_TOKEN_REFRESH_MARGIN_MS: number;
21
35
  /** What the store row holds. Read back with {@link parseShopifyCredentials}; never cast. */
22
36
  export interface ShopifyCredentials {
37
+ /**
38
+ * The client id of the app that issued this grant. A token renews only with the app that issued
39
+ * it, and which app that is cannot be inferred from the shop: it is stored with the grant. Absent on
40
+ * a grant stored before this field existed, which the next renewal fills in.
41
+ */
42
+ clientId?: string;
43
+ /**
44
+ * How the token was granted. `client_credentials` has no refresh token: it is renewed by minting
45
+ * again with the app's client id and secret. Absent: the authorization code grant.
46
+ */
47
+ grant?: "client_credentials";
23
48
  accessToken: string;
24
49
  /** Absent for a non-expiring token (an admin-created custom app); such a token is never refreshed. */
25
50
  refreshToken?: string;
@@ -54,9 +79,57 @@ export declare function exchangeCallback(params: {
54
79
  requiredScopes: readonly string[];
55
80
  now: number;
56
81
  }): Promise<Result<ShopifyCredentials, ChannelConnectorError>>;
82
+ /**
83
+ * Check an ID token the way Shopify documents: HS256 over `header.payload` under the client secret
84
+ * (compared in constant time), `exp` in the future, `nbf` in the past, `aud` equal to the client id,
85
+ * and the hostnames of `iss` and `dest` equal and a `*.myshopify.com` shop. Returns the shop the
86
+ * token was issued for and the staff member (`sub`). Every failure is `SHOPIFY_ID_TOKEN_INVALID`:
87
+ * the caller's answer is the same (a fresh token fixes it), and the cause is not the caller's to learn.
88
+ * https://shopify.dev/docs/apps/build/authentication-authorization/id-tokens
89
+ */
90
+ export declare function verifyShopifyIdToken(params: {
91
+ token: string;
92
+ clientId: string;
93
+ clientSecret: string;
94
+ now: number;
95
+ }): Result<{
96
+ shop: string;
97
+ userId: string;
98
+ }, ChannelConnectorError>;
99
+ /**
100
+ * Trade a verified ID token for an expiring offline token (the token exchange grant). Shopify answers
101
+ * a stale or invalid ID token with 400, a routine condition a fresh token fixes: it is
102
+ * `SHOPIFY_ID_TOKEN_INVALID` here, not a refusal of the app. Scopes the store did not grant are refused
103
+ * exactly as the code grant refuses them.
104
+ */
105
+ export declare function exchangeIdToken(params: {
106
+ fetchImpl: typeof fetch;
107
+ origin: string;
108
+ clientId: string;
109
+ clientSecret: string;
110
+ idToken: string;
111
+ requiredScopes: readonly string[];
112
+ now: number;
113
+ }): Promise<Result<ShopifyCredentials, ChannelConnectorError>>;
114
+ /**
115
+ * A token from the client credentials grant: the app's own client id and secret, no code and no
116
+ * scope (Shopify ignores one). The token carries the scopes the store granted the app's installation.
117
+ * A refusal names its cause: `SHOPIFY_SHOP_NOT_PERMITTED` (another organization's app),
118
+ * `SHOPIFY_APP_NOT_INSTALLED`, or `SHOPIFY_REAUTHORIZATION_REQUIRED` for a client id or secret
119
+ * Shopify does not accept.
120
+ */
121
+ export declare function mintClientCredentials(params: {
122
+ fetchImpl: typeof fetch;
123
+ origin: string;
124
+ clientId: string;
125
+ clientSecret: string;
126
+ now: number;
127
+ }): Promise<Result<ShopifyCredentials, ChannelConnectorError>>;
57
128
  /**
58
129
  * New credentials when the access token is within the refresh margin of expiry, `null` when the
59
- * current ones are good. A refresh token Shopify refuses means the merchant must reconnect.
130
+ * current ones are good. A client-credentials token is minted again; an authorization-code token is
131
+ * refreshed with its refresh token, and a refresh token Shopify refuses means the merchant must
132
+ * reconnect.
60
133
  */
61
134
  export declare function refreshIfExpiring(params: {
62
135
  fetchImpl: typeof fetch;
package/dist/oauth.js CHANGED
@@ -2,25 +2,41 @@ import { createHmac, timingSafeEqual } from "node:crypto";
2
2
  import { Err, Ok } from "@porulle/core";
3
3
  import { z } from "zod";
4
4
  /**
5
- * Shopify's OAuth for a standalone (non-embedded) app: the authorization code grant, asking for an
6
- * EXPIRING offline token. Shopify requires expiring offline tokens of every new public app calling the
7
- * GraphQL Admin API: a one-hour access token and a 90-day refresh token that rotates on every refresh.
8
- * https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens
5
+ * Shopify's two grants an app connects a store with.
6
+ *
7
+ * - The authorization code grant, for an app the merchant installs from us (public or custom
8
+ * distribution), asking for an EXPIRING offline token: Shopify requires them of every new public
9
+ * app calling the GraphQL Admin API — a one-hour access token and a 90-day refresh token that
10
+ * rotates on every refresh.
11
+ * https://shopify.dev/docs/apps/build/authentication-authorization/access-tokens
12
+ * - The client credentials grant, for an app that belongs to the SAME Shopify organization as the
13
+ * store: a merchant's own Dev Dashboard app, whose client id and secret the merchant hands over.
14
+ * The token lives 24 hours and there is no refresh token; a new one is minted with the same client
15
+ * id and secret. Shopify refuses it with `shop_not_permitted` across organizations.
16
+ * https://shopify.dev/docs/apps/build/authentication-authorization/client-credentials-grant
17
+ * - The token exchange grant, for an app Shopify installs itself (managed installation) and loads
18
+ * inside the admin: App Bridge hands the page a one-minute ID token, and the app trades it for the
19
+ * same expiring offline token. Shopify keeps ONE current offline token per app and store, so a
20
+ * successful exchange retires the refresh tokens an earlier grant of that app issued.
21
+ * https://shopify.dev/docs/apps/build/authentication-authorization/implement-token-exchange
9
22
  */
10
23
  /**
11
- * The scopes the connector's live paths need, and nothing else.
24
+ * The scopes the connector's live paths need, and nothing else. Nothing about a product is ever
25
+ * pushed to a merchant's Shopify — only orders reach it — so there is no `write_products` here.
12
26
  *
13
- * - `read_products`, `write_products`: the catalogue import, and the Loom metafield write-back.
27
+ * - `read_products`: the catalogue import.
14
28
  * - `read_inventory`: variant stock and the inventory item behind a stock webhook.
15
29
  * - `write_orders`: a paid platform order is created in the store (`orderCreate`). A write scope
16
30
  * includes its read scope, which `orders/fulfilled` and `orders/cancelled` need.
17
31
  * - `read_returns`, `write_returns`: a shopper's return is asked of the store (`returnRequest`) and
18
32
  * its `returns/*` webhooks say how the store answered.
19
33
  */
20
- export const REQUIRED_SCOPES = ["read_products", "write_products", "read_inventory", "write_orders", "read_returns", "write_returns"];
34
+ export const REQUIRED_SCOPES = ["read_products", "read_inventory", "write_orders", "read_returns", "write_returns"];
21
35
  /** Refresh this long before Shopify's stated expiry, so a call never starts on a token about to lapse. */
22
36
  export const ACCESS_TOKEN_REFRESH_MARGIN_MS = 5 * 60 * 1000;
23
37
  const credentialsSchema = z.object({
38
+ clientId: z.string().min(1).optional(),
39
+ grant: z.literal("client_credentials").optional(),
24
40
  accessToken: z.string().min(1),
25
41
  refreshToken: z.string().min(1).optional(),
26
42
  accessTokenExpiresAt: z.string().optional(),
@@ -31,9 +47,11 @@ export function parseShopifyCredentials(value) {
31
47
  const parsed = credentialsSchema.safeParse(value);
32
48
  if (!parsed.success)
33
49
  return undefined;
34
- const { refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt, ...rest } = parsed.data;
50
+ const { clientId, grant, refreshToken, accessTokenExpiresAt, refreshTokenExpiresAt, ...rest } = parsed.data;
35
51
  return {
36
52
  ...rest,
53
+ ...(clientId !== undefined ? { clientId } : {}),
54
+ ...(grant !== undefined ? { grant } : {}),
37
55
  ...(refreshToken !== undefined ? { refreshToken } : {}),
38
56
  ...(accessTokenExpiresAt !== undefined ? { accessTokenExpiresAt } : {}),
39
57
  ...(refreshTokenExpiresAt !== undefined ? { refreshTokenExpiresAt } : {}),
@@ -86,8 +104,9 @@ export function missingScopes(granted, required) {
86
104
  const have = new Set(granted);
87
105
  return required.filter((scope) => !have.has(scope) && !(scope.startsWith("read_") && have.has(`write_${scope.slice(5)}`)));
88
106
  }
89
- function credentialsFrom(body, now) {
107
+ function credentialsFrom(body, now, clientId) {
90
108
  return {
109
+ clientId,
91
110
  accessToken: body.access_token,
92
111
  grantedScopes: body.scope.split(",").map((scope) => scope.trim()).filter(Boolean),
93
112
  ...(body.refresh_token !== undefined ? { refreshToken: body.refresh_token } : {}),
@@ -95,7 +114,26 @@ function credentialsFrom(body, now) {
95
114
  ...(body.refresh_token_expires_in !== undefined ? { refreshTokenExpiresAt: new Date(now + body.refresh_token_expires_in * 1000).toISOString() } : {}),
96
115
  };
97
116
  }
98
- async function postTokenEndpoint(fetchImpl, origin, form) {
117
+ /**
118
+ * Why the token endpoint refused a grant, from the body Shopify answered with. Live Shopify
119
+ * (measured 2026-11-24) answers 400 JSON (`invalid_request`, `application_cannot_be_found`,
120
+ * `app_not_installed`) and `shop_not_permitted` for cross-org client credentials; the refusal name is
121
+ * matched wherever it appears rather than parsed from one assumed shape.
122
+ */
123
+ function tokenRefusal(status, body) {
124
+ if (body.includes("shop_not_permitted")) {
125
+ return { code: "SHOPIFY_SHOP_NOT_PERMITTED", message: "Shopify refused the client credentials grant for this store: the app and the store are in different Shopify organizations.", retriable: false };
126
+ }
127
+ if (body.includes("app_not_installed")) {
128
+ return { code: "SHOPIFY_APP_NOT_INSTALLED", message: "Shopify says the app is not installed on this store.", retriable: false };
129
+ }
130
+ return { code: "SHOPIFY_REAUTHORIZATION_REQUIRED", message: `Shopify refused the grant (${status}); the store must be reconnected.`, retriable: false };
131
+ }
132
+ /**
133
+ * `badRequest` is what a 400 means to this grant when it is not the generic refusal: for the token
134
+ * exchange it is a stale or invalid ID token, which a fresh one fixes.
135
+ */
136
+ async function postTokenEndpoint(fetchImpl, origin, form, badRequest) {
99
137
  let response;
100
138
  try {
101
139
  response = await fetchImpl(`${origin}/admin/oauth/access_token`, {
@@ -108,8 +146,13 @@ async function postTokenEndpoint(fetchImpl, origin, form) {
108
146
  catch (error) {
109
147
  return oauthError("SHOPIFY_TOKEN_REQUEST_FAILED", error instanceof Error ? error.message : "Shopify token request failed.", true);
110
148
  }
149
+ if (response.status === 400 && badRequest !== undefined)
150
+ return Err(badRequest);
111
151
  if (response.status === 400 || response.status === 401) {
112
- return oauthError("SHOPIFY_REAUTHORIZATION_REQUIRED", `Shopify refused the grant (${response.status}); the store must be reconnected.`);
152
+ return Err(tokenRefusal(response.status, await response.text().catch(() => "")));
153
+ }
154
+ if (response.status === 404) {
155
+ return oauthError("SHOPIFY_SHOP_NOT_FOUND", "Shopify has no store at that address.");
113
156
  }
114
157
  if (!response.ok)
115
158
  return oauthError("SHOPIFY_TOKEN_REQUEST_FAILED", `Shopify token request failed (${response.status}).`, response.status >= 500);
@@ -137,7 +180,7 @@ export async function exchangeCallback(params) {
137
180
  const token = await postTokenEndpoint(params.fetchImpl, params.origin, { client_id: params.clientId, client_secret: params.clientSecret, code, expiring: "1" });
138
181
  if (!token.ok)
139
182
  return token;
140
- const credentials = credentialsFrom(token.value, params.now);
183
+ const credentials = credentialsFrom(token.value, params.now, params.clientId);
141
184
  // Merchants can untick scopes on the grant screen; a token missing one fails later in a way that
142
185
  // looks like a product problem, so it is refused here, where the cause is still nameable.
143
186
  const missing = missingScopes(credentials.grantedScopes, params.requiredScopes);
@@ -145,9 +188,117 @@ export async function exchangeCallback(params) {
145
188
  return oauthError("SHOPIFY_SCOPES_NOT_GRANTED", `The store did not grant: ${missing.join(", ")}.`);
146
189
  return Ok(credentials);
147
190
  }
191
+ /** Shopify's ID tokens are signed with this; anything else (`none`, RS256) is refused before it is read. */
192
+ const ID_TOKEN_ALGORITHM = "HS256";
193
+ /** How far a token's `nbf` may sit in the future before it is refused: clocks differ by seconds. */
194
+ const ID_TOKEN_SKEW_MS = 10_000;
195
+ const idTokenHeaderSchema = z.object({ alg: z.string() });
196
+ const idTokenPayloadSchema = z.object({
197
+ iss: z.string(),
198
+ dest: z.string(),
199
+ aud: z.string(),
200
+ sub: z.string(),
201
+ exp: z.number(),
202
+ nbf: z.number(),
203
+ });
204
+ const ID_TOKEN_INVALID = { code: "SHOPIFY_ID_TOKEN_INVALID", message: "The Shopify ID token is invalid or expired.", retriable: false };
205
+ function jwtPart(encoded) {
206
+ try {
207
+ return JSON.parse(Buffer.from(encoded, "base64url").toString("utf8"));
208
+ }
209
+ catch {
210
+ return undefined;
211
+ }
212
+ }
213
+ function hostOf(url) {
214
+ try {
215
+ return new URL(url).hostname.toLowerCase();
216
+ }
217
+ catch {
218
+ return undefined;
219
+ }
220
+ }
221
+ /**
222
+ * Check an ID token the way Shopify documents: HS256 over `header.payload` under the client secret
223
+ * (compared in constant time), `exp` in the future, `nbf` in the past, `aud` equal to the client id,
224
+ * and the hostnames of `iss` and `dest` equal and a `*.myshopify.com` shop. Returns the shop the
225
+ * token was issued for and the staff member (`sub`). Every failure is `SHOPIFY_ID_TOKEN_INVALID`:
226
+ * the caller's answer is the same (a fresh token fixes it), and the cause is not the caller's to learn.
227
+ * https://shopify.dev/docs/apps/build/authentication-authorization/id-tokens
228
+ */
229
+ export function verifyShopifyIdToken(params) {
230
+ const parts = params.token.split(".");
231
+ const [encodedHeader, encodedPayload, encodedSignature] = parts;
232
+ if (parts.length !== 3 || !encodedHeader || !encodedPayload || !encodedSignature)
233
+ return Err(ID_TOKEN_INVALID);
234
+ const header = idTokenHeaderSchema.safeParse(jwtPart(encodedHeader));
235
+ if (!header.success || header.data.alg !== ID_TOKEN_ALGORITHM)
236
+ return Err(ID_TOKEN_INVALID);
237
+ const expected = createHmac("sha256", params.clientSecret).update(`${encodedHeader}.${encodedPayload}`).digest();
238
+ const actual = Buffer.from(encodedSignature, "base64url");
239
+ if (actual.length !== expected.length || !timingSafeEqual(actual, expected))
240
+ return Err(ID_TOKEN_INVALID);
241
+ const payload = idTokenPayloadSchema.safeParse(jwtPart(encodedPayload));
242
+ if (!payload.success)
243
+ return Err(ID_TOKEN_INVALID);
244
+ const claims = payload.data;
245
+ const issuerHost = hostOf(claims.iss);
246
+ const destHost = hostOf(claims.dest);
247
+ if (claims.exp * 1000 <= params.now
248
+ || claims.nbf * 1000 > params.now + ID_TOKEN_SKEW_MS
249
+ || claims.aud !== params.clientId
250
+ || issuerHost === undefined
251
+ || issuerHost !== destHost
252
+ || !validShopDomain(destHost))
253
+ return Err(ID_TOKEN_INVALID);
254
+ return Ok({ shop: destHost, userId: claims.sub });
255
+ }
256
+ /**
257
+ * Trade a verified ID token for an expiring offline token (the token exchange grant). Shopify answers
258
+ * a stale or invalid ID token with 400, a routine condition a fresh token fixes: it is
259
+ * `SHOPIFY_ID_TOKEN_INVALID` here, not a refusal of the app. Scopes the store did not grant are refused
260
+ * exactly as the code grant refuses them.
261
+ */
262
+ export async function exchangeIdToken(params) {
263
+ const token = await postTokenEndpoint(params.fetchImpl, params.origin, {
264
+ client_id: params.clientId,
265
+ client_secret: params.clientSecret,
266
+ grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
267
+ subject_token: params.idToken,
268
+ subject_token_type: "urn:ietf:params:oauth:token-type:id_token",
269
+ requested_token_type: "urn:shopify:params:oauth:token-type:offline-access-token",
270
+ expiring: "1",
271
+ }, ID_TOKEN_INVALID);
272
+ if (!token.ok)
273
+ return token;
274
+ const credentials = credentialsFrom(token.value, params.now, params.clientId);
275
+ const missing = missingScopes(credentials.grantedScopes, params.requiredScopes);
276
+ if (missing.length > 0)
277
+ return oauthError("SHOPIFY_SCOPES_NOT_GRANTED", `The store did not grant: ${missing.join(", ")}.`);
278
+ return Ok(credentials);
279
+ }
280
+ /**
281
+ * A token from the client credentials grant: the app's own client id and secret, no code and no
282
+ * scope (Shopify ignores one). The token carries the scopes the store granted the app's installation.
283
+ * A refusal names its cause: `SHOPIFY_SHOP_NOT_PERMITTED` (another organization's app),
284
+ * `SHOPIFY_APP_NOT_INSTALLED`, or `SHOPIFY_REAUTHORIZATION_REQUIRED` for a client id or secret
285
+ * Shopify does not accept.
286
+ */
287
+ export async function mintClientCredentials(params) {
288
+ const token = await postTokenEndpoint(params.fetchImpl, params.origin, {
289
+ grant_type: "client_credentials",
290
+ client_id: params.clientId,
291
+ client_secret: params.clientSecret,
292
+ });
293
+ if (!token.ok)
294
+ return token;
295
+ return Ok({ grant: "client_credentials", ...credentialsFrom(token.value, params.now, params.clientId) });
296
+ }
148
297
  /**
149
298
  * New credentials when the access token is within the refresh margin of expiry, `null` when the
150
- * current ones are good. A refresh token Shopify refuses means the merchant must reconnect.
299
+ * current ones are good. A client-credentials token is minted again; an authorization-code token is
300
+ * refreshed with its refresh token, and a refresh token Shopify refuses means the merchant must
301
+ * reconnect.
151
302
  */
152
303
  export async function refreshIfExpiring(params) {
153
304
  const { credentials } = params;
@@ -158,6 +309,8 @@ export async function refreshIfExpiring(params) {
158
309
  if (Number.isFinite(expiresAt) && expiresAt - params.now > ACCESS_TOKEN_REFRESH_MARGIN_MS)
159
310
  return Ok(null);
160
311
  }
312
+ if (credentials.grant === "client_credentials")
313
+ return mintClientCredentials(params);
161
314
  if (credentials.refreshToken === undefined)
162
315
  return oauthError("SHOPIFY_REAUTHORIZATION_REQUIRED", "The store's access token expired and no refresh token is held; the store must be reconnected.");
163
316
  const token = await postTokenEndpoint(params.fetchImpl, params.origin, {
@@ -168,7 +321,7 @@ export async function refreshIfExpiring(params) {
168
321
  });
169
322
  if (!token.ok)
170
323
  return token;
171
- const refreshed = credentialsFrom(token.value, params.now);
324
+ const refreshed = credentialsFrom(token.value, params.now, params.clientId);
172
325
  // A refresh answer may omit the scope list; the grant did not change, so keep the one we hold.
173
326
  return Ok(refreshed.grantedScopes.length > 0 ? refreshed : { ...refreshed, grantedScopes: credentials.grantedScopes });
174
327
  }