@shopify/shopify-api 14.0.1 → 15.0.1

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.
Files changed (47) hide show
  1. package/dist/cjs/lib/auth/oauth/oauth.js +2 -0
  2. package/dist/cjs/lib/auth/oauth/oauth.js.map +1 -1
  3. package/dist/cjs/lib/clients/common.js +1 -0
  4. package/dist/cjs/lib/clients/common.js.map +1 -1
  5. package/dist/cjs/lib/types.js +0 -2
  6. package/dist/cjs/lib/types.js.map +1 -1
  7. package/dist/cjs/lib/version.js +1 -1
  8. package/dist/cjs/lib/version.js.map +1 -1
  9. package/dist/cjs/lib/webhooks/types.js +0 -2
  10. package/dist/cjs/lib/webhooks/types.js.map +1 -1
  11. package/dist/cjs/lib/webhooks/validate.js +0 -5
  12. package/dist/cjs/lib/webhooks/validate.js.map +1 -1
  13. package/dist/cjs/runtime/http/cookies.js +9 -3
  14. package/dist/cjs/runtime/http/cookies.js.map +1 -1
  15. package/dist/cjs/tsconfig.build.tsbuildinfo +1 -1
  16. package/dist/esm/lib/auth/oauth/oauth.mjs +2 -0
  17. package/dist/esm/lib/auth/oauth/oauth.mjs.map +1 -1
  18. package/dist/esm/lib/clients/common.mjs +1 -0
  19. package/dist/esm/lib/clients/common.mjs.map +1 -1
  20. package/dist/esm/lib/types.mjs +0 -2
  21. package/dist/esm/lib/types.mjs.map +1 -1
  22. package/dist/esm/lib/version.mjs +1 -1
  23. package/dist/esm/lib/version.mjs.map +1 -1
  24. package/dist/esm/lib/webhooks/types.mjs +0 -2
  25. package/dist/esm/lib/webhooks/types.mjs.map +1 -1
  26. package/dist/esm/lib/webhooks/validate.mjs +0 -5
  27. package/dist/esm/lib/webhooks/validate.mjs.map +1 -1
  28. package/dist/esm/runtime/http/cookies.mjs +9 -3
  29. package/dist/esm/runtime/http/cookies.mjs.map +1 -1
  30. package/dist/esm/tsconfig.build.tsbuildinfo +1 -1
  31. package/dist/ts/lib/auth/oauth/oauth.d.ts.map +1 -1
  32. package/dist/ts/lib/clients/common.d.ts.map +1 -1
  33. package/dist/ts/lib/types.d.ts +0 -2
  34. package/dist/ts/lib/types.d.ts.map +1 -1
  35. package/dist/ts/lib/version.d.ts +1 -1
  36. package/dist/ts/lib/webhooks/types.d.ts +0 -4
  37. package/dist/ts/lib/webhooks/types.d.ts.map +1 -1
  38. package/dist/ts/runtime/http/cookies.d.ts.map +1 -1
  39. package/dist/ts/tsconfig.build.tsbuildinfo +1 -1
  40. package/lib/auth/oauth/oauth.ts +2 -0
  41. package/lib/clients/common.ts +1 -0
  42. package/lib/types.ts +0 -2
  43. package/lib/version.ts +1 -1
  44. package/lib/webhooks/types.ts +0 -4
  45. package/lib/webhooks/validate.ts +0 -9
  46. package/package.json +4 -4
  47. package/runtime/http/cookies.ts +14 -5
@@ -44,6 +44,7 @@ function begin(config) {
44
44
  expires: new Date(Date.now() + 60000),
45
45
  sameSite: 'lax',
46
46
  secure: true,
47
+ httpOnly: true,
47
48
  path: callbackPath,
48
49
  });
49
50
  const scopes = config.scopes ? config.scopes.toString() : '';
@@ -134,6 +135,7 @@ function callback(config) {
134
135
  expires: session.expires,
135
136
  sameSite: 'lax',
136
137
  secure: true,
138
+ httpOnly: true,
137
139
  path: cookiePath,
138
140
  });
139
141
  }
@@ -1 +1 @@
1
- {"version":3,"file":"oauth.mjs","sources":["../../../../../../../lib/auth/oauth/oauth.ts"],"sourcesContent":["import {isbot} from 'isbot';\n\nimport {throwFailedRequest} from '../../clients/common';\nimport ProcessedQuery from '../../utils/processed-query';\nimport {ConfigInterface} from '../../base-types';\nimport * as ShopifyErrors from '../../error';\nimport {validateHmac} from '../../utils/hmac-validator';\nimport {sanitizeShop} from '../../utils/shop-validator';\nimport {Session} from '../../session/session';\nimport {\n abstractConvertRequest,\n abstractConvertIncomingResponse,\n abstractConvertResponse,\n abstractConvertHeaders,\n AdapterResponse,\n AdapterHeaders,\n Cookies,\n NormalizedResponse,\n NormalizedRequest,\n} from '../../../runtime/http';\nimport {logger, ShopifyLogger} from '../../logger';\nimport {DataType} from '../../clients/types';\nimport {fetchRequestFactory} from '../../utils/fetch-request';\n\nimport {\n SESSION_COOKIE_NAME,\n STATE_COOKIE_NAME,\n BeginParams,\n CallbackParams,\n AuthQuery,\n AccessTokenResponse,\n} from './types';\nimport {nonce} from './nonce';\nimport {safeCompare} from './safe-compare';\nimport {createSession} from './create-session';\n\nexport type OAuthBegin = (beginParams: BeginParams) => Promise<AdapterResponse>;\n\nexport interface CallbackResponse<T = AdapterHeaders> {\n headers: T;\n session: Session;\n}\n\nexport type OAuthCallback = <T = AdapterHeaders>(\n callbackParams: CallbackParams,\n) => Promise<CallbackResponse<T>>;\n\ninterface BotLog {\n request: NormalizedRequest;\n log: ShopifyLogger;\n func: string;\n}\n\nconst logForBot = ({request, log, func}: BotLog) => {\n log.debug(`Possible bot request to auth ${func}: `, {\n userAgent: request.headers['User-Agent'],\n });\n};\n\nexport function begin(config: ConfigInterface): OAuthBegin {\n return async ({\n shop,\n callbackPath,\n isOnline,\n ...adapterArgs\n }: BeginParams): Promise<AdapterResponse> => {\n throwIfCustomStoreApp(\n config.isCustomStoreApp,\n 'Cannot perform OAuth for private apps',\n );\n\n const log = logger(config);\n log.info('Beginning OAuth', {shop, isOnline, callbackPath});\n\n const request = await abstractConvertRequest(adapterArgs);\n const response = await abstractConvertIncomingResponse(adapterArgs);\n\n let userAgent = request.headers['User-Agent'];\n if (Array.isArray(userAgent)) {\n userAgent = userAgent[0];\n }\n if (isbot(userAgent)) {\n logForBot({request, log, func: 'begin'});\n response.statusCode = 410;\n return abstractConvertResponse(response, adapterArgs);\n }\n\n const cookies = new Cookies(request, response, {\n keys: [config.apiSecretKey],\n secure: true,\n });\n\n const state = nonce();\n\n await cookies.setAndSign(STATE_COOKIE_NAME, state, {\n expires: new Date(Date.now() + 60000),\n sameSite: 'lax',\n secure: true,\n path: callbackPath,\n });\n\n const scopes = config.scopes ? config.scopes.toString() : '';\n const query = {\n client_id: config.apiKey,\n scope: scopes,\n redirect_uri: `${config.hostScheme}://${config.hostName}${callbackPath}`,\n state,\n 'grant_options[]': isOnline ? 'per-user' : '',\n };\n const processedQuery = new ProcessedQuery();\n processedQuery.putAll(query);\n\n const cleanShop = sanitizeShop(config)(shop, true)!;\n const redirectUrl = `https://${cleanShop}/admin/oauth/authorize${processedQuery.stringify()}`;\n response.statusCode = 302;\n response.statusText = 'Found';\n response.headers = {\n ...response.headers,\n ...cookies.response.headers!,\n Location: redirectUrl,\n };\n\n log.debug(`OAuth started, redirecting to ${redirectUrl}`, {shop, isOnline});\n\n return abstractConvertResponse(response, adapterArgs);\n };\n}\n\nexport function callback(config: ConfigInterface): OAuthCallback {\n return async function callback<T = AdapterHeaders>({\n expiring,\n ...adapterArgs\n }: CallbackParams): Promise<CallbackResponse<T>> {\n throwIfCustomStoreApp(\n config.isCustomStoreApp,\n 'Cannot perform OAuth for private apps',\n );\n\n const log = logger(config);\n\n const request = await abstractConvertRequest(adapterArgs);\n\n const query = new URL(\n request.url,\n `${config.hostScheme}://${config.hostName}`,\n ).searchParams;\n const shop = query.get('shop')!;\n\n const response = {} as NormalizedResponse;\n let userAgent = request.headers['User-Agent'];\n if (Array.isArray(userAgent)) {\n userAgent = userAgent[0];\n }\n if (isbot(userAgent)) {\n logForBot({request, log, func: 'callback'});\n throw new ShopifyErrors.BotActivityDetected(\n 'Invalid OAuth callback initiated by bot',\n );\n }\n\n log.info('Completing OAuth', {shop});\n\n const cookies = new Cookies(request, response, {\n keys: [config.apiSecretKey],\n secure: true,\n });\n\n const stateFromCookie = await cookies.getAndVerify(STATE_COOKIE_NAME);\n cookies.deleteCookie(STATE_COOKIE_NAME);\n if (!stateFromCookie) {\n log.error('Could not find OAuth cookie', {shop});\n\n throw new ShopifyErrors.CookieNotFound(\n `Cannot complete OAuth process. Could not find an OAuth cookie for shop url: ${shop}`,\n );\n }\n\n const authQuery: AuthQuery = Object.fromEntries(query.entries());\n if (!(await validQuery({config, query: authQuery, stateFromCookie}))) {\n log.error('Invalid OAuth callback', {shop, stateFromCookie});\n\n throw new ShopifyErrors.InvalidOAuthError('Invalid OAuth callback.');\n }\n\n log.debug('OAuth request is valid, requesting access token', {shop});\n\n const body = {\n client_id: config.apiKey,\n client_secret: config.apiSecretKey,\n code: query.get('code'),\n expiring: expiring ? '1' : '0',\n };\n\n const cleanShop = sanitizeShop(config)(query.get('shop')!, true)!;\n\n const postResponse = await fetchRequestFactory(config)(\n `https://${cleanShop}/admin/oauth/access_token`,\n {\n method: 'POST',\n body: JSON.stringify(body),\n headers: {\n 'Content-Type': DataType.JSON,\n Accept: DataType.JSON,\n },\n },\n );\n\n if (!postResponse.ok) {\n throwFailedRequest(await postResponse.json(), false, postResponse);\n }\n\n const session: Session = createSession({\n accessTokenResponse: await postResponse.json<AccessTokenResponse>(),\n shop: cleanShop,\n state: stateFromCookie,\n config,\n });\n\n if (!config.isEmbeddedApp) {\n const cookiePath =\n typeof config.cookiePath === 'function'\n ? config.cookiePath(session)\n : (config.cookiePath ?? '/');\n await cookies.setAndSign(SESSION_COOKIE_NAME, session.id, {\n expires: session.expires,\n sameSite: 'lax',\n secure: true,\n path: cookiePath,\n });\n }\n\n return {\n headers: (await abstractConvertHeaders(\n cookies.response.headers!,\n adapterArgs,\n )) as T,\n session,\n };\n };\n}\n\nasync function validQuery({\n config,\n query,\n stateFromCookie,\n}: {\n config: ConfigInterface;\n query: AuthQuery;\n stateFromCookie: string;\n}): Promise<boolean> {\n return (\n (await validateHmac(config)(query)) &&\n safeCompare(query.state!, stateFromCookie)\n );\n}\n\nfunction throwIfCustomStoreApp(\n isCustomStoreApp: boolean,\n message: string,\n): void {\n if (isCustomStoreApp) {\n throw new ShopifyErrors.PrivateAppError(message);\n }\n}\n"],"names":["ShopifyErrors.BotActivityDetected","ShopifyErrors.CookieNotFound","ShopifyErrors.InvalidOAuthError","ShopifyErrors.PrivateAppError"],"mappings":";;;;;;;;;;;;;;;;AAqDA,MAAM,SAAS,GAAG,CAAC,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E,CAAC,MAAM,YAAY,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC;QAClC,WAAW,CAAC,KAAK,CAAC,KAAM,EAAE,eAAe,CAAC;AAE9C;AAEA,SAAS,qBAAqB,CAC5B,gBAAyB,EACzB,OAAe,EAAA;IAEf,IAAI,gBAAgB,EAAE;AACpB,QAAA,MAAM,IAAIC,eAA6B,CAAC,OAAO,CAAC;IAClD;AACF;;;;"}
1
+ {"version":3,"file":"oauth.mjs","sources":["../../../../../../../lib/auth/oauth/oauth.ts"],"sourcesContent":["import {isbot} from 'isbot';\n\nimport {throwFailedRequest} from '../../clients/common';\nimport ProcessedQuery from '../../utils/processed-query';\nimport {ConfigInterface} from '../../base-types';\nimport * as ShopifyErrors from '../../error';\nimport {validateHmac} from '../../utils/hmac-validator';\nimport {sanitizeShop} from '../../utils/shop-validator';\nimport {Session} from '../../session/session';\nimport {\n abstractConvertRequest,\n abstractConvertIncomingResponse,\n abstractConvertResponse,\n abstractConvertHeaders,\n AdapterResponse,\n AdapterHeaders,\n Cookies,\n NormalizedResponse,\n NormalizedRequest,\n} from '../../../runtime/http';\nimport {logger, ShopifyLogger} from '../../logger';\nimport {DataType} from '../../clients/types';\nimport {fetchRequestFactory} from '../../utils/fetch-request';\n\nimport {\n SESSION_COOKIE_NAME,\n STATE_COOKIE_NAME,\n BeginParams,\n CallbackParams,\n AuthQuery,\n AccessTokenResponse,\n} from './types';\nimport {nonce} from './nonce';\nimport {safeCompare} from './safe-compare';\nimport {createSession} from './create-session';\n\nexport type OAuthBegin = (beginParams: BeginParams) => Promise<AdapterResponse>;\n\nexport interface CallbackResponse<T = AdapterHeaders> {\n headers: T;\n session: Session;\n}\n\nexport type OAuthCallback = <T = AdapterHeaders>(\n callbackParams: CallbackParams,\n) => Promise<CallbackResponse<T>>;\n\ninterface BotLog {\n request: NormalizedRequest;\n log: ShopifyLogger;\n func: string;\n}\n\nconst logForBot = ({request, log, func}: BotLog) => {\n log.debug(`Possible bot request to auth ${func}: `, {\n userAgent: request.headers['User-Agent'],\n });\n};\n\nexport function begin(config: ConfigInterface): OAuthBegin {\n return async ({\n shop,\n callbackPath,\n isOnline,\n ...adapterArgs\n }: BeginParams): Promise<AdapterResponse> => {\n throwIfCustomStoreApp(\n config.isCustomStoreApp,\n 'Cannot perform OAuth for private apps',\n );\n\n const log = logger(config);\n log.info('Beginning OAuth', {shop, isOnline, callbackPath});\n\n const request = await abstractConvertRequest(adapterArgs);\n const response = await abstractConvertIncomingResponse(adapterArgs);\n\n let userAgent = request.headers['User-Agent'];\n if (Array.isArray(userAgent)) {\n userAgent = userAgent[0];\n }\n if (isbot(userAgent)) {\n logForBot({request, log, func: 'begin'});\n response.statusCode = 410;\n return abstractConvertResponse(response, adapterArgs);\n }\n\n const cookies = new Cookies(request, response, {\n keys: [config.apiSecretKey],\n secure: true,\n });\n\n const state = nonce();\n\n await cookies.setAndSign(STATE_COOKIE_NAME, state, {\n expires: new Date(Date.now() + 60000),\n sameSite: 'lax',\n secure: true,\n httpOnly: true,\n path: callbackPath,\n });\n\n const scopes = config.scopes ? config.scopes.toString() : '';\n const query = {\n client_id: config.apiKey,\n scope: scopes,\n redirect_uri: `${config.hostScheme}://${config.hostName}${callbackPath}`,\n state,\n 'grant_options[]': isOnline ? 'per-user' : '',\n };\n const processedQuery = new ProcessedQuery();\n processedQuery.putAll(query);\n\n const cleanShop = sanitizeShop(config)(shop, true)!;\n const redirectUrl = `https://${cleanShop}/admin/oauth/authorize${processedQuery.stringify()}`;\n response.statusCode = 302;\n response.statusText = 'Found';\n response.headers = {\n ...response.headers,\n ...cookies.response.headers!,\n Location: redirectUrl,\n };\n\n log.debug(`OAuth started, redirecting to ${redirectUrl}`, {shop, isOnline});\n\n return abstractConvertResponse(response, adapterArgs);\n };\n}\n\nexport function callback(config: ConfigInterface): OAuthCallback {\n return async function callback<T = AdapterHeaders>({\n expiring,\n ...adapterArgs\n }: CallbackParams): Promise<CallbackResponse<T>> {\n throwIfCustomStoreApp(\n config.isCustomStoreApp,\n 'Cannot perform OAuth for private apps',\n );\n\n const log = logger(config);\n\n const request = await abstractConvertRequest(adapterArgs);\n\n const query = new URL(\n request.url,\n `${config.hostScheme}://${config.hostName}`,\n ).searchParams;\n const shop = query.get('shop')!;\n\n const response = {} as NormalizedResponse;\n let userAgent = request.headers['User-Agent'];\n if (Array.isArray(userAgent)) {\n userAgent = userAgent[0];\n }\n if (isbot(userAgent)) {\n logForBot({request, log, func: 'callback'});\n throw new ShopifyErrors.BotActivityDetected(\n 'Invalid OAuth callback initiated by bot',\n );\n }\n\n log.info('Completing OAuth', {shop});\n\n const cookies = new Cookies(request, response, {\n keys: [config.apiSecretKey],\n secure: true,\n });\n\n const stateFromCookie = await cookies.getAndVerify(STATE_COOKIE_NAME);\n cookies.deleteCookie(STATE_COOKIE_NAME);\n if (!stateFromCookie) {\n log.error('Could not find OAuth cookie', {shop});\n\n throw new ShopifyErrors.CookieNotFound(\n `Cannot complete OAuth process. Could not find an OAuth cookie for shop url: ${shop}`,\n );\n }\n\n const authQuery: AuthQuery = Object.fromEntries(query.entries());\n if (!(await validQuery({config, query: authQuery, stateFromCookie}))) {\n log.error('Invalid OAuth callback', {shop, stateFromCookie});\n\n throw new ShopifyErrors.InvalidOAuthError('Invalid OAuth callback.');\n }\n\n log.debug('OAuth request is valid, requesting access token', {shop});\n\n const body = {\n client_id: config.apiKey,\n client_secret: config.apiSecretKey,\n code: query.get('code'),\n expiring: expiring ? '1' : '0',\n };\n\n const cleanShop = sanitizeShop(config)(query.get('shop')!, true)!;\n\n const postResponse = await fetchRequestFactory(config)(\n `https://${cleanShop}/admin/oauth/access_token`,\n {\n method: 'POST',\n body: JSON.stringify(body),\n headers: {\n 'Content-Type': DataType.JSON,\n Accept: DataType.JSON,\n },\n },\n );\n\n if (!postResponse.ok) {\n throwFailedRequest(await postResponse.json(), false, postResponse);\n }\n\n const session: Session = createSession({\n accessTokenResponse: await postResponse.json<AccessTokenResponse>(),\n shop: cleanShop,\n state: stateFromCookie,\n config,\n });\n\n if (!config.isEmbeddedApp) {\n const cookiePath =\n typeof config.cookiePath === 'function'\n ? config.cookiePath(session)\n : (config.cookiePath ?? '/');\n await cookies.setAndSign(SESSION_COOKIE_NAME, session.id, {\n expires: session.expires,\n sameSite: 'lax',\n secure: true,\n httpOnly: true,\n path: cookiePath,\n });\n }\n\n return {\n headers: (await abstractConvertHeaders(\n cookies.response.headers!,\n adapterArgs,\n )) as T,\n session,\n };\n };\n}\n\nasync function validQuery({\n config,\n query,\n stateFromCookie,\n}: {\n config: ConfigInterface;\n query: AuthQuery;\n stateFromCookie: string;\n}): Promise<boolean> {\n return (\n (await validateHmac(config)(query)) &&\n safeCompare(query.state!, stateFromCookie)\n );\n}\n\nfunction throwIfCustomStoreApp(\n isCustomStoreApp: boolean,\n message: string,\n): void {\n if (isCustomStoreApp) {\n throw new ShopifyErrors.PrivateAppError(message);\n }\n}\n"],"names":["ShopifyErrors.BotActivityDetected","ShopifyErrors.CookieNotFound","ShopifyErrors.InvalidOAuthError","ShopifyErrors.PrivateAppError"],"mappings":";;;;;;;;;;;;;;;;AAqDA,MAAM,SAAS,GAAG,CAAC,EAAC,OAAO,EAAE,GAAG,EAAE,IAAI,EAAS,KAAI;AACjD,IAAA,GAAG,CAAC,KAAK,CAAC,CAAA,6BAAA,EAAgC,IAAI,IAAI,EAAE;AAClD,QAAA,SAAS,EAAE,OAAO,CAAC,OAAO,CAAC,YAAY,CAAC;AACzC,KAAA,CAAC;AACJ,CAAC;AAEK,SAAU,KAAK,CAAC,MAAuB,EAAA;AAC3C,IAAA,OAAO,OAAO,EACZ,IAAI,EACJ,YAAY,EACZ,QAAQ,EACR,GAAG,WAAW,EACF,KAA8B;AAC1C,QAAA,qBAAqB,CACnB,MAAM,CAAC,gBAAgB,EACvB,uCAAuC,CACxC;AAED,QAAA,MAAM,GAAG,GAAG,MAAM,CAAC,MAAM,CAAC;AAC1B,QAAA,GAAG,CAAC,IAAI,CAAC,iBAAiB,EAAE,EAAC,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;AACnE,YAAA,IAAI,EAAE,SAAS;AACf,YAAA,KAAK,EAAE,eAAe;YACtB,MAAM;AACP,SAAA,CAAC;AAEF,QAAA,IAAI,CAAC,MAAM,CAAC,aAAa,EAAE;AACzB,YAAA,MAAM,UAAU,GACd,OAAO,MAAM,CAAC,UAAU,KAAK;AAC3B,kBAAE,MAAM,CAAC,UAAU,CAAC,OAAO;mBACxB,MAAM,CAAC,UAAU,IAAI,GAAG,CAAC;YAChC,MAAM,OAAO,CAAC,UAAU,CAAC,mBAAmB,EAAE,OAAO,CAAC,EAAE,EAAE;gBACxD,OAAO,EAAE,OAAO,CAAC,OAAO;AACxB,gBAAA,QAAQ,EAAE,KAAK;AACf,gBAAA,MAAM,EAAE,IAAI;AACZ,gBAAA,QAAQ,EAAE,IAAI;AACd,gBAAA,IAAI,EAAE,UAAU;AACjB,aAAA,CAAC;QACJ;QAEA,OAAO;AACL,YAAA,OAAO,GAAG,MAAM,sBAAsB,CACpC,OAAO,CAAC,QAAQ,CAAC,OAAQ,EACzB,WAAW,CACZ,CAAM;YACP,OAAO;SACR;AACH,IAAA,CAAC;AACH;AAEA,eAAe,UAAU,CAAC,EACxB,MAAM,EACN,KAAK,EACL,eAAe,GAKhB,EAAA;IACC,QACE,CAAC,MAAM,YAAY,CAAC,MAAM,CAAC,CAAC,KAAK,CAAC;QAClC,WAAW,CAAC,KAAK,CAAC,KAAM,EAAE,eAAe,CAAC;AAE9C;AAEA,SAAS,qBAAqB,CAC5B,gBAAyB,EACzB,OAAe,EAAA;IAEf,IAAI,gBAAgB,EAAE;AACpB,QAAA,MAAM,IAAIC,eAA6B,CAAC,OAAO,CAAC;IAClD;AACF;;;;"}
@@ -14,6 +14,7 @@ function getUserAgent(config) {
14
14
  }
15
15
  const REDACTED_LOG_VALUE = '****';
16
16
  // These headers carry reusable credentials and must not reach the logs.
17
+ // Keep in sync with SENSITIVE_HEADERS in @shopify/graphql-client.
17
18
  const SENSITIVE_LOG_HEADERS = new Set([
18
19
  'authorization',
19
20
  'cookie',
@@ -1 +1 @@
1
- {"version":3,"file":"common.mjs","sources":["../../../../../../lib/clients/common.ts"],"sourcesContent":["import {\n HTTPResponseLog,\n HTTPRetryLog,\n HTTPResponseGraphQLDeprecationNotice,\n LogContent,\n} from '@shopify/admin-api-client';\n\nimport * as ShopifyErrors from '../error';\nimport {LIBRARY_NAME, StatusCode} from '../types';\nimport {ConfigInterface} from '../base-types';\nimport {SHOPIFY_API_LIBRARY_VERSION} from '../version';\nimport {\n abstractRuntimeString,\n canonicalizeHeaders,\n getHeader,\n} from '../../runtime';\nimport {logger} from '../logger';\n\nexport function getUserAgent(config: ConfigInterface): string {\n let userAgentPrefix = `${LIBRARY_NAME} v${SHOPIFY_API_LIBRARY_VERSION} | ${abstractRuntimeString()}`;\n if (config.userAgentPrefix) {\n userAgentPrefix = `${config.userAgentPrefix} | ${userAgentPrefix}`;\n }\n\n return userAgentPrefix;\n}\n\nconst REDACTED_LOG_VALUE = '****';\n\n// These headers carry reusable credentials and must not reach the logs.\nconst SENSITIVE_LOG_HEADERS = new Set([\n 'authorization',\n 'cookie',\n 'set-cookie',\n 'shopify-storefront-private-token',\n 'x-shopify-access-token',\n 'x-shopify-storefront-access-token',\n]);\n\nfunction sanitizeHeaderValue(name: string, value: unknown): unknown {\n return SENSITIVE_LOG_HEADERS.has(name.toLowerCase())\n ? REDACTED_LOG_VALUE\n : value;\n}\n\n// Keep the original serialized shape of request headers. A Headers instance\n// has no own enumerable properties, so it stays opaque here, the same as\n// JSON.stringify shows it.\nfunction sanitizeHeaders(headers: any): any {\n if (!headers || typeof headers !== 'object') {\n return headers;\n }\n\n if (Array.isArray(headers)) {\n return headers.map((header) =>\n Array.isArray(header)\n ? [header[0], sanitizeHeaderValue(header[0], header[1])]\n : header,\n );\n }\n\n return Object.fromEntries(\n Object.entries(headers).map(([name, value]) => [\n name,\n sanitizeHeaderValue(name, value),\n ]),\n );\n}\n\n// Response headers were always enumerated in the log, so keep that and\n// redact the credential values.\nfunction sanitizeEnumerableHeaders(headers: any): any {\n if (typeof headers?.entries === 'function' && !Array.isArray(headers)) {\n return Object.fromEntries(\n [...headers.entries()].map(([name, value]: [string, string]) => [\n name,\n sanitizeHeaderValue(name, value),\n ]),\n );\n }\n\n return sanitizeHeaders(headers);\n}\n\nfunction sanitizeRequestParams<T>(requestParams: T): T {\n if (Array.isArray(requestParams)) {\n return requestParams.map((param) =>\n param && typeof param === 'object' && 'headers' in param\n ? {...param, headers: sanitizeHeaders(param.headers)}\n : param,\n ) as T;\n }\n\n if (\n requestParams &&\n typeof requestParams === 'object' &&\n 'headers' in requestParams\n ) {\n return {\n ...requestParams,\n headers: sanitizeHeaders((requestParams as {headers: any}).headers),\n };\n }\n\n return requestParams;\n}\n\nfunction serializeResponse(response: Response | any) {\n if (!response) {\n return {error: 'No response object provided'};\n }\n\n try {\n const {status, statusText, ok, redirected, type, url, headers} = response;\n\n const serialized: any = {\n status,\n statusText,\n ok,\n redirected,\n type,\n url,\n };\n\n if (headers) {\n serialized.headers = sanitizeEnumerableHeaders(headers);\n }\n\n return serialized;\n } catch {\n return response;\n }\n}\n\nexport function clientLoggerFactory(config: ConfigInterface) {\n return (logContent: LogContent) => {\n if (config.logger.httpRequests) {\n switch (logContent.type) {\n case 'HTTP-Response': {\n const responseLog: HTTPResponseLog['content'] = logContent.content;\n logger(config).debug('Received response for HTTP request', {\n requestParams: JSON.stringify(\n sanitizeRequestParams(responseLog.requestParams),\n ),\n response: JSON.stringify(serializeResponse(responseLog.response)),\n });\n break;\n }\n case 'HTTP-Retry': {\n const responseLog: HTTPRetryLog['content'] = logContent.content;\n logger(config).debug('Retrying HTTP request', {\n requestParams: JSON.stringify(\n sanitizeRequestParams(responseLog.requestParams),\n ),\n retryAttempt: responseLog.retryAttempt,\n maxRetries: responseLog.maxRetries,\n response: responseLog.lastResponse\n ? JSON.stringify(serializeResponse(responseLog.lastResponse))\n : 'undefined',\n });\n break;\n }\n case 'HTTP-Response-GraphQL-Deprecation-Notice': {\n const responseLog: HTTPResponseGraphQLDeprecationNotice['content'] =\n logContent.content;\n logger(config).debug(\n 'Received response containing Deprecated GraphQL Notice',\n {\n requestParams: JSON.stringify(\n sanitizeRequestParams(responseLog.requestParams),\n ),\n deprecationNotice: responseLog.deprecationNotice,\n },\n );\n break;\n }\n default: {\n logger(config).debug(`HTTP request event: ${logContent.content}`);\n break;\n }\n }\n }\n };\n}\n\nexport function throwFailedRequest(\n body: any,\n atMaxRetries: boolean,\n response?: Response,\n): never {\n if (typeof response === 'undefined') {\n const message = body?.errors?.message ?? '';\n throw new ShopifyErrors.HttpRequestError(\n `Http request error, no response available: ${message}`,\n );\n }\n\n const responseHeaders = canonicalizeHeaders(\n Object.fromEntries(response.headers.entries() ?? []),\n );\n\n if (response.status === StatusCode.Ok && body.errors.graphQLErrors) {\n throw new ShopifyErrors.GraphqlQueryError({\n message:\n body.errors.graphQLErrors?.[0].message ?? 'GraphQL operation failed',\n response: response as Record<string, any>,\n headers: responseHeaders,\n body: body as Record<string, any>,\n });\n }\n\n const errorMessages: string[] = [];\n if (body.errors) {\n errorMessages.push(JSON.stringify(body.errors, null, 2));\n }\n const xRequestId = getHeader(responseHeaders, 'x-request-id');\n if (xRequestId) {\n errorMessages.push(\n `If you report this error, please include this id: ${xRequestId}`,\n );\n }\n\n const errorMessage = errorMessages.length\n ? `:\\n${errorMessages.join('\\n')}`\n : '';\n const code = response.status;\n const statusText = response.statusText;\n\n switch (true) {\n case response.status === StatusCode.TooManyRequests: {\n if (atMaxRetries) {\n throw new ShopifyErrors.HttpMaxRetriesError(\n 'Attempted the maximum number of retries for HTTP request.',\n );\n } else {\n const retryAfter = getHeader(responseHeaders, 'Retry-After');\n throw new ShopifyErrors.HttpThrottlingError({\n message: `Shopify is throttling requests ${errorMessage}`,\n code,\n statusText,\n body,\n headers: responseHeaders,\n retryAfter: retryAfter ? parseFloat(retryAfter) : undefined,\n });\n }\n }\n case response.status >= StatusCode.InternalServerError:\n if (atMaxRetries) {\n throw new ShopifyErrors.HttpMaxRetriesError(\n 'Attempted the maximum number of retries for HTTP request.',\n );\n } else {\n throw new ShopifyErrors.HttpInternalError({\n message: `Shopify internal error${errorMessage}`,\n code,\n statusText,\n body,\n headers: responseHeaders,\n });\n }\n default:\n throw new ShopifyErrors.HttpResponseError({\n message: `Received an error response (${response.status} ${response.statusText}) from Shopify${errorMessage}`,\n code,\n statusText,\n body,\n headers: responseHeaders,\n });\n }\n}\n"],"names":["ShopifyErrors.HttpRequestError","ShopifyErrors.GraphqlQueryError","ShopifyErrors.HttpMaxRetriesError","ShopifyErrors.HttpThrottlingError","ShopifyErrors.HttpInternalError","ShopifyErrors.HttpResponseError"],"mappings":";;;;;;;AAkBM,SAAU,YAAY,CAAC,MAAuB,EAAA;IAClD,IAAI,eAAe,GAAG,CAAA,EAAG,YAAY,CAAA,EAAA,EAAK,2BAA2B,CAAA,GAAA,EAAM,qBAAqB,EAAE,CAAA,CAAE;AACpG,IAAA,IAAI,MAAM,CAAC,eAAe,EAAE;QAC1B,eAAe,GAAG,GAAG,MAAM,CAAC,eAAe,CAAA,GAAA,EAAM,eAAe,EAAE;IACpE;AAEA,IAAA,OAAO,eAAe;AACxB;AAEA,MAAM,kBAAkB,GAAG,MAAM;AAEjC;AACA,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC;IACpC,eAAe;IACf,QAAQ;IACR,YAAY;IACZ,kCAAkC;IAClC,wBAAwB;IACxB,mCAAmC;AACpC,CAAA,CAAC;AAEF,SAAS,mBAAmB,CAAC,IAAY,EAAE,KAAc,EAAA;IACvD,OAAO,qBAAqB,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE;AACjD,UAAE;UACA,KAAK;AACX;AAEA;AACA;AACA;AACA,SAAS,eAAe,CAAC,OAAY,EAAA;IACnC,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AAC3C,QAAA,OAAO,OAAO;IAChB;AAEA,IAAA,IAAI,KAAK,CAAC,O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5D;YACH;iBAAO;gBACL,MAAM,UAAU,GAAG,SAAS,CAAC,eAAe,EAAE,aAAa,CAAC;AAC5D,gBAAA,MAAM,IAAIC,mBAAiC,CAAC;oBAC1C,OAAO,EAAE,CAAA,+BAAA,EAAkC,YAAY,CAAA,CAAE;oBACzD,IAAI;oBACJ,UAAU;oBACV,IAAI;AACJ,oBAAA,OAAO,EAAE,eAAe;AACxB,oBAAA,UAAU,EAAE,UAAU,GAAG,UAAU,CAAC,UAAU,CAAC,GAAG,SAAS;AAC5D,iBAAA,CAAC;YACJ;QACF;AACA,QAAA,KAAK,QAAQ,CAAC,MAAM,IAAI,UAAU,CAAC,mBAAmB;YACpD,IAAI,YAAY,EAAE;AAChB,gBAAA,MAAM,IAAID,mBAAiC,CACzC,2DAA2D,CAC5D;YACH;iBAAO;AACL,gBAAA,MAAM,IAAIE,iBAA+B,CAAC;oBACxC,OAAO,EAAE,CAAA,sBAAA,EAAyB,YAAY,CAAA,CAAE;oBAChD,IAAI;oBACJ,UAAU;oBACV,IAAI;AACJ,oBAAA,OAAO,EAAE,eAAe;AACzB,iBAAA,CAAC;YACJ;AACF,QAAA;AACE,YAAA,MAAM,IAAIC,iBAA+B,CAAC;gBACxC,OAAO,EAAE,CAAA,4BAAA,EAA+B,QAAQ,CAAC,MAAM,CAAA,CAAA,EAAI,QAAQ,CAAC,UAAU,CAAA,cAAA,EAAiB,YAAY,CAAA,CAAE;gBAC7G,IAAI;gBACJ,UAAU;gBACV,IAAI;AACJ,gBAAA,OAAO,EAAE,eAAe;AACzB,aAAA,CAAC;;AAER;;;;"}
1
+ {"version":3,"file":"common.mjs","sources":["../../../../../../lib/clients/common.ts"],"sourcesContent":["import {\n HTTPResponseLog,\n HTTPRetryLog,\n HTTPResponseGraphQLDeprecationNotice,\n LogContent,\n} from '@shopify/admin-api-client';\n\nimport * as ShopifyErrors from '../error';\nimport {LIBRARY_NAME, StatusCode} from '../types';\nimport {ConfigInterface} from '../base-types';\nimport {SHOPIFY_API_LIBRARY_VERSION} from '../version';\nimport {\n abstractRuntimeString,\n canonicalizeHeaders,\n getHeader,\n} from '../../runtime';\nimport {logger} from '../logger';\n\nexport function getUserAgent(config: ConfigInterface): string {\n let userAgentPrefix = `${LIBRARY_NAME} v${SHOPIFY_API_LIBRARY_VERSION} | ${abstractRuntimeString()}`;\n if (config.userAgentPrefix) {\n userAgentPrefix = `${config.userAgentPrefix} | ${userAgentPrefix}`;\n }\n\n return userAgentPrefix;\n}\n\nconst REDACTED_LOG_VALUE = '****';\n\n// These headers carry reusable credentials and must not reach the logs.\n// Keep in sync with SENSITIVE_HEADERS in @shopify/graphql-client.\nconst SENSITIVE_LOG_HEADERS = new Set([\n 'authorization',\n 'cookie',\n 'set-cookie',\n 'shopify-storefront-private-token',\n 'x-shopify-access-token',\n 'x-shopify-storefront-access-token',\n]);\n\nfunction sanitizeHeaderValue(name: string, value: unknown): unknown {\n return SENSITIVE_LOG_HEADERS.has(name.toLowerCase())\n ? REDACTED_LOG_VALUE\n : value;\n}\n\n// Keep the original serialized shape of request headers. A Headers instance\n// has no own enumerable properties, so it stays opaque here, the same as\n// JSON.stringify shows it.\nfunction sanitizeHeaders(headers: any): any {\n if (!headers || typeof headers !== 'object') {\n return headers;\n }\n\n if (Array.isArray(headers)) {\n return headers.map((header) =>\n Array.isArray(header)\n ? [header[0], sanitizeHeaderValue(header[0], header[1])]\n : header,\n );\n }\n\n return Object.fromEntries(\n Object.entries(headers).map(([name, value]) => [\n name,\n sanitizeHeaderValue(name, value),\n ]),\n );\n}\n\n// Response headers were always enumerated in the log, so keep that and\n// redact the credential values.\nfunction sanitizeEnumerableHeaders(headers: any): any {\n if (typeof headers?.entries === 'function' && !Array.isArray(headers)) {\n return Object.fromEntries(\n [...headers.entries()].map(([name, value]: [string, string]) => [\n name,\n sanitizeHeaderValue(name, value),\n ]),\n );\n }\n\n return sanitizeHeaders(headers);\n}\n\nfunction sanitizeRequestParams<T>(requestParams: T): T {\n if (Array.isArray(requestParams)) {\n return requestParams.map((param) =>\n param && typeof param === 'object' && 'headers' in param\n ? {...param, headers: sanitizeHeaders(param.headers)}\n : param,\n ) as T;\n }\n\n if (\n requestParams &&\n typeof requestParams === 'object' &&\n 'headers' in requestParams\n ) {\n return {\n ...requestParams,\n headers: sanitizeHeaders((requestParams as {headers: any}).headers),\n };\n }\n\n return requestParams;\n}\n\nfunction serializeResponse(response: Response | any) {\n if (!response) {\n return {error: 'No response object provided'};\n }\n\n try {\n const {status, statusText, ok, redirected, type, url, headers} = response;\n\n const serialized: any = {\n status,\n statusText,\n ok,\n redirected,\n type,\n url,\n };\n\n if (headers) {\n serialized.headers = sanitizeEnumerableHeaders(headers);\n }\n\n return serialized;\n } catch {\n return response;\n }\n}\n\nexport function clientLoggerFactory(config: ConfigInterface) {\n return (logContent: LogContent) => {\n if (config.logger.httpRequests) {\n switch (logContent.type) {\n case 'HTTP-Response': {\n const responseLog: HTTPResponseLog['content'] = logContent.content;\n logger(config).debug('Received response for HTTP request', {\n requestParams: JSON.stringify(\n sanitizeRequestParams(responseLog.requestParams),\n ),\n response: JSON.stringify(serializeResponse(responseLog.response)),\n });\n break;\n }\n case 'HTTP-Retry': {\n const responseLog: HTTPRetryLog['content'] = logContent.content;\n logger(config).debug('Retrying HTTP request', {\n requestParams: JSON.stringify(\n sanitizeRequestParams(responseLog.requestParams),\n ),\n retryAttempt: responseLog.retryAttempt,\n maxRetries: responseLog.maxRetries,\n response: responseLog.lastResponse\n ? JSON.stringify(serializeResponse(responseLog.lastResponse))\n : 'undefined',\n });\n break;\n }\n case 'HTTP-Response-GraphQL-Deprecation-Notice': {\n const responseLog: HTTPResponseGraphQLDeprecationNotice['content'] =\n logContent.content;\n logger(config).debug(\n 'Received response containing Deprecated GraphQL Notice',\n {\n requestParams: JSON.stringify(\n sanitizeRequestParams(responseLog.requestParams),\n ),\n deprecationNotice: responseLog.deprecationNotice,\n },\n );\n break;\n }\n default: {\n logger(config).debug(`HTTP request event: ${logContent.content}`);\n break;\n }\n }\n }\n };\n}\n\nexport function throwFailedRequest(\n body: any,\n atMaxRetries: boolean,\n response?: Response,\n): never {\n if (typeof response === 'undefined') {\n const message = body?.errors?.message ?? '';\n throw new ShopifyErrors.HttpRequestError(\n `Http request error, no response available: ${message}`,\n );\n }\n\n const responseHeaders = canonicalizeHeaders(\n Object.fromEntries(response.headers.entries() ?? []),\n );\n\n if (response.status === StatusCode.Ok && body.errors.graphQLErrors) {\n throw new ShopifyErrors.GraphqlQueryError({\n message:\n body.errors.graphQLErrors?.[0].message ?? 'GraphQL operation failed',\n response: response as Record<string, any>,\n headers: responseHeaders,\n body: body as Record<string, any>,\n });\n }\n\n const errorMessages: string[] = [];\n if (body.errors) {\n errorMessages.push(JSON.stringify(body.errors, null, 2));\n }\n const xRequestId = getHeader(responseHeaders, 'x-request-id');\n if (xRequestId) {\n errorMessages.push(\n `If you report this error, please include this id: ${xRequestId}`,\n );\n }\n\n const errorMessage = errorMessages.length\n ? `:\\n${errorMessages.join('\\n')}`\n : '';\n const code = response.status;\n const statusText = response.statusText;\n\n switch (true) {\n case response.status === StatusCode.TooManyRequests: {\n if (atMaxRetries) {\n throw new ShopifyErrors.HttpMaxRetriesError(\n 'Attempted the maximum number of retries for HTTP request.',\n );\n } else {\n const retryAfter = getHeader(responseHeaders, 'Retry-After');\n throw new ShopifyErrors.HttpThrottlingError({\n message: `Shopify is throttling requests ${errorMessage}`,\n code,\n statusText,\n body,\n headers: responseHeaders,\n retryAfter: retryAfter ? parseFloat(retryAfter) : undefined,\n });\n }\n }\n case response.status >= StatusCode.InternalServerError:\n if (atMaxRetries) {\n throw new ShopifyErrors.HttpMaxRetriesError(\n 'Attempted the maximum number of retries for HTTP request.',\n );\n } else {\n throw new ShopifyErrors.HttpInternalError({\n message: `Shopify internal error${errorMessage}`,\n code,\n statusText,\n body,\n headers: responseHeaders,\n });\n }\n default:\n throw new ShopifyErrors.HttpResponseError({\n message: `Received an error response (${response.status} ${response.statusText}) from Shopify${errorMessage}`,\n code,\n statusText,\n body,\n headers: responseHeaders,\n });\n }\n}\n"],"names":["ShopifyErrors.HttpRequestError","ShopifyErrors.GraphqlQueryError","ShopifyErrors.HttpMaxRetriesError","ShopifyErrors.HttpThrottlingError","ShopifyErrors.HttpInternalError","ShopifyErrors.HttpResponseError"],"mappings":";;;;;;;AAkBM,SAAU,YAAY,CAAC,MAAuB,EAAA;IAClD,IAAI,eAAe,GAAG,CAAA,EAAG,YAAY,CAAA,EAAA,EAAK,2BAA2B,CAAA,GAAA,EAAM,qBAAqB,EAAE,CAAA,CAAE;AACpG,IAAA,IAAI,MAAM,CAAC,eAAe,EAAE;QAC1B,eAAe,GAAG,GAAG,MAAM,CAAC,eAAe,CAAA,GAAA,EAAM,eAAe,EAAE;IACpE;AAEA,IAAA,OAAO,eAAe;AACxB;AAEA,MAAM,kBAAkB,GAAG,MAAM;AAEjC;AACA;AACA,MAAM,qBAAqB,GAAG,IAAI,GAAG,CAAC;IACpC,eAAe;IACf,QAAQ;IACR,YAAY;IACZ,kCAAkC;IAClC,wBAAwB;IACxB,mCAAmC;AACpC,CAAA,CAAC;AAEF,SAAS,mBAAmB,CAAC,IAAY,EAAE,KAAc,EAAA;IACvD,OAAO,qBAAqB,CAAC,GAAG,CAAC,IAAI,CAAC,WAAW,EAAE;AACjD,UAAE;UACA,KAAK;AACX;AAEA;AACA;AACA;AACA,SAAS,eAAe,CAAC,OAAY,EAAA;IACnC,IAAI,CAAC,OAAO,IAAI,OAAO,OAAO,KAAK,QAAQ,EAAE;AAC3C,QAAA,OAAO,OAAO;IAChB;AAEA,IAAA,IAAI,KAAK,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE;AAC1B,QAAA,OAAO,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,KACxB,KAAK,CAAC,OAAO,CAAC,MAAM;AAClB,cAAE,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,mBAAmB,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,MAAM,CAAC,CAAC,CAA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EAAE,eAAe;AACxB,oBAAA,UAAU,EAAE,UAAU,GAAG,UAAU,CAAC,UAAU,CAAC,GAAG,SAAS;AAC5D,iBAAA,CAAC;YACJ;QACF;AACA,QAAA,KAAK,QAAQ,CAAC,MAAM,IAAI,UAAU,CAAC,mBAAmB;YACpD,IAAI,YAAY,EAAE;AAChB,gBAAA,MAAM,IAAID,mBAAiC,CACzC,2DAA2D,CAC5D;YACH;iBAAO;AACL,gBAAA,MAAM,IAAIE,iBAA+B,CAAC;oBACxC,OAAO,EAAE,CAAA,sBAAA,EAAyB,YAAY,CAAA,CAAE;oBAChD,IAAI;oBACJ,UAAU;oBACV,IAAI;AACJ,oBAAA,OAAO,EAAE,eAAe;AACzB,iBAAA,CAAC;YACJ;AACF,QAAA;AACE,YAAA,MAAM,IAAIC,iBAA+B,CAAC;gBACxC,OAAO,EAAE,CAAA,4BAAA,EAA+B,QAAQ,CAAC,MAAM,CAAA,CAAA,EAAI,QAAQ,CAAC,UAAU,CAAA,cAAA,EAAiB,YAAY,CAAA,CAAE;gBAC7G,IAAI;gBACJ,UAAU;gBACV,IAAI;AACJ,gBAAA,OAAO,EAAE,eAAe;AACzB,aAAA,CAAC;;AAER;;;;"}
@@ -41,11 +41,9 @@ const ShopifyEventsHeader = {
41
41
  Topic: 'shopify-topic',
42
42
  Domain: 'shopify-shop-domain',
43
43
  ApiVersion: 'shopify-api-version',
44
- EventId: 'shopify-event-id',
45
44
  WebhookId: 'shopify-webhook-id',
46
45
  Handle: 'shopify-handle',
47
46
  Action: 'shopify-action',
48
- ResourceId: 'shopify-resource-id',
49
47
  TriggeredAt: 'shopify-triggered-at',
50
48
  };
51
49
  var ClientType;
@@ -1 +1 @@
1
- {"version":3,"file":"types.mjs","sources":["../../../../../lib/types.ts"],"sourcesContent":["export enum LogSeverity {\n Error,\n Warning,\n Info,\n Debug,\n}\n\nexport enum ApiVersion {\n October24 = '2024-10',\n January25 = '2025-01',\n April25 = '2025-04',\n July25 = '2025-07',\n October25 = '2025-10',\n January26 = '2026-01',\n April26 = '2026-04',\n July26 = '2026-07',\n October26 = '2026-10',\n Unstable = 'unstable',\n}\n\nexport const LIBRARY_NAME = 'Shopify API Library';\n\n/* eslint-disable @shopify/typescript-prefer-pascal-case-enums */\nexport enum ShopifyHeader {\n AccessToken = 'X-Shopify-Access-Token',\n ApiVersion = 'X-Shopify-API-Version',\n Domain = 'X-Shopify-Shop-Domain',\n Hmac = 'X-Shopify-Hmac-Sha256',\n Topic = 'X-Shopify-Topic',\n WebhookId = 'X-Shopify-Webhook-Id',\n Name = 'X-Shopify-Name',\n TriggeredAt = 'X-Shopify-Triggered-At',\n EventId = 'X-Shopify-Event-Id',\n StorefrontPrivateToken = 'Shopify-Storefront-Private-Token',\n StorefrontSDKVariant = 'X-SDK-Variant',\n StorefrontSDKVersion = 'X-SDK-Version',\n}\n/* eslint-enable @shopify/typescript-prefer-pascal-case-enums */\n\nexport const ShopifyEventsHeader = {\n Hmac: 'shopify-hmac-sha256',\n Topic: 'shopify-topic',\n Domain: 'shopify-shop-domain',\n ApiVersion: 'shopify-api-version',\n EventId: 'shopify-event-id',\n WebhookId: 'shopify-webhook-id',\n Handle: 'shopify-handle',\n Action: 'shopify-action',\n ResourceId: 'shopify-resource-id',\n TriggeredAt: 'shopify-triggered-at',\n} as const;\n\nexport enum ClientType {\n Rest = 'rest',\n Graphql = 'graphql',\n}\n\nexport const privacyTopics: string[] = [\n 'CUSTOMERS_DATA_REQUEST',\n 'CUSTOMERS_REDACT',\n 'SHOP_REDACT',\n];\n\nexport enum BillingInterval {\n OneTime = 'ONE_TIME',\n Every30Days = 'EVERY_30_DAYS',\n Annual = 'ANNUAL',\n Usage = 'USAGE',\n}\n\nexport type RecurringBillingIntervals = Exclude<\n BillingInterval,\n BillingInterval.OneTime\n>;\n\nexport enum BillingReplacementBehavior {\n ApplyImmediately = 'APPLY_IMMEDIATELY',\n ApplyOnNextBillingCycle = 'APPLY_ON_NEXT_BILLING_CYCLE',\n Standard = 'STANDARD',\n}\n\nexport enum StatusCode {\n Continue = 100,\n SwitchingProtocols = 101,\n Ok = 200,\n Created = 201,\n Accepted = 202,\n NonAuthoritativeInformation = 203,\n NoContent = 204,\n ResetContent = 205,\n PartialContent = 206,\n MultipleChoices = 300,\n MovedPermanently = 301,\n Found = 302,\n SeeOther = 303,\n NotModified = 304,\n UseProxy = 305,\n TemporaryRedirect = 307,\n BadRequest = 400,\n Unauthorized = 401,\n PaymentRequired = 402,\n Forbidden = 403,\n NotFound = 404,\n MethodNotAllowed = 405,\n NotAcceptable = 406,\n ProxyAuthenticationRequired = 407,\n RequestTimeout = 408,\n Conflict = 409,\n Gone = 410,\n LengthRequired = 411,\n PreconditionFailed = 412,\n RequestEntityTooLarge = 413,\n RequestUriTooLong = 414,\n UnsupportedMediaType = 415,\n RequestedRangeNotSatisfiable = 416,\n ExpectationFailed = 417,\n ImATeapot = 418,\n UnprocessableEntity = 422,\n TooManyRequests = 429,\n InternalServerError = 500,\n NotImplemented = 501,\n BadGateway = 502,\n ServiceUnavailable = 503,\n GatewayTimeout = 504,\n HttpVersionNotSupported = 505,\n}\n\nexport enum Method {\n Get = 'GET',\n Post = 'POST',\n Put = 'PUT',\n Patch = 'PATCH',\n Delete = 'DELETE',\n Head = 'HEAD',\n Options = 'OPTIONS',\n Connect = 'CONNECT',\n}\n\n/**\n * Configuration for transforming shop domains in split-domain architectures.\n *\n * @example\n * // Template-based transformation\n * {\n * match: /^([a-zA-Z0-9][a-zA-Z0-9-_]*)\\.my\\.shop\\.dev$/,\n * transform: '$1.dev-api.shop.dev'\n * }\n *\n * @example\n * // Function-based transformation\n * {\n * match: /^([^.]+)\\.ui\\.example\\.com$/,\n * transform: (matches) => `${matches[1]}.api.example.com`\n * }\n */\nexport interface DomainTransformation {\n /**\n * Pattern to match against shop domains (source domain).\n * Can be a RegExp or string (converted to RegExp internally).\n */\n match: RegExp | string;\n\n /**\n * Transformation function or template string.\n * - Template string: Uses $1, $2, etc. for capture group substitution\n * - Function: Receives regex match groups and returns transformed domain\n */\n transform: ((matches: RegExpMatchArray) => string | null) | string;\n\n /**\n * Whether this transformation should also apply to host validation.\n * @default true\n */\n includeHost?: boolean;\n}\n"],"names":[],"mappings":"IAAY;AAAZ,CAAA,UAAY,WAAW,EAAA;AACrB,IAAA,WAAA,CAAA,WAAA,CAAA,OAAA,CAAA,GAAA,CAAA,CAAA,GAAA,OAAK;AACL,IAAA,WAAA,CAAA,WAAA,CAAA,SAAA,CAAA,GAAA,CAAA,CAAA,GAAA,SAAO;AACP,IAAA,WAAA,CAAA,WAAA,CAAA,MAAA,CAAA,GAAA,CAAA,CAAA,GAAA,MAAI;AACJ,IAAA,WAAA,CAAA,WAAA,CAAA,OAAA,CAAA,GAAA,CAAA,CAAA,GAAA,OAAK;AACP,CAAC,EALW,WAAW,KAAX,WAAW,GAAA,EAAA,CAAA,CAAA;IAOX;AAAZ,CAAA,UAAY,UAAU,EAAA;AACpB,IAAA,UAAA,CAAA,WAAA,CAAA,GAAA,SAAqB;AACrB,IAAA,UAAA,CAAA,WAAA,CAAA,GAAA,SAAqB;AACrB,IAAA,UAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,UAAA,CAAA,QAAA,CAAA,GAAA,SAAkB;AAClB,IAAA,UAAA,CAAA,WAAA,CAAA,GAAA,SAAqB;AACrB,IAAA,UAAA,CAAA,WAAA,CAAA,GAAA,SAAqB;AACrB,IAAA,UAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,UAAA,CAAA,QAAA,CAAA,GAAA,SAAkB;AAClB,IAAA,UAAA,CAAA,WAAA,CAAA,GAAA,SAAqB;AACrB,IAAA,UAAA,CAAA,UAAA,CAAA,GAAA,UAAqB;AACvB,CAAC,EAXW,UAAU,KAAV,UAAU,GAAA,EAAA,CAAA,CAAA;AAaf,MAAM,YAAY,GAAG;AAE5B;IACY;AAAZ,CAAA,UAAY,aAAa,EAAA;AACvB,IAAA,aAAA,CAAA,aAAA,CAAA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BAAA,CAAA,GAAA,GAAA,CAAA,GAAA,gBAAoB;AACpB,IAAA,UAAA,CAAA,UAAA,CAAA,YAAA,CAAA,GAAA,GAAA,CAAA,GAAA,YAAgB;AAChB,IAAA,UAAA,CAAA,UAAA,CAAA,oBAAA,CAAA,GAAA,GAAA,CAAA,GAAA,oBAAwB;AACxB,IAAA,UAAA,CAAA,UAAA,CAAA,gBAAA,CAAA,GAAA,GAAA,CAAA,GAAA,gBAAoB;AACpB,IAAA,UAAA,CAAA,UAAA,CAAA,yBAAA,CAAA,GAAA,GAAA,CAAA,GAAA,yBAA6B;AAC/B,CAAC,EA5CW,UAAU,KAAV,UAAU,GAAA,EAAA,CAAA,CAAA;IA8CV;AAAZ,CAAA,UAAY,MAAM,EAAA;AAChB,IAAA,MAAA,CAAA,KAAA,CAAA,GAAA,KAAW;AACX,IAAA,MAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACb,IAAA,MAAA,CAAA,KAAA,CAAA,GAAA,KAAW;AACX,IAAA,MAAA,CAAA,OAAA,CAAA,GAAA,OAAe;AACf,IAAA,MAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,MAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACb,IAAA,MAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,MAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACrB,CAAC,EATW,MAAM,KAAN,MAAM,GAAA,EAAA,CAAA,CAAA;;;;"}
1
+ {"version":3,"file":"types.mjs","sources":["../../../../../lib/types.ts"],"sourcesContent":["export enum LogSeverity {\n Error,\n Warning,\n Info,\n Debug,\n}\n\nexport enum ApiVersion {\n October24 = '2024-10',\n January25 = '2025-01',\n April25 = '2025-04',\n July25 = '2025-07',\n October25 = '2025-10',\n January26 = '2026-01',\n April26 = '2026-04',\n July26 = '2026-07',\n October26 = '2026-10',\n Unstable = 'unstable',\n}\n\nexport const LIBRARY_NAME = 'Shopify API Library';\n\n/* eslint-disable @shopify/typescript-prefer-pascal-case-enums */\nexport enum ShopifyHeader {\n AccessToken = 'X-Shopify-Access-Token',\n ApiVersion = 'X-Shopify-API-Version',\n Domain = 'X-Shopify-Shop-Domain',\n Hmac = 'X-Shopify-Hmac-Sha256',\n Topic = 'X-Shopify-Topic',\n WebhookId = 'X-Shopify-Webhook-Id',\n Name = 'X-Shopify-Name',\n TriggeredAt = 'X-Shopify-Triggered-At',\n EventId = 'X-Shopify-Event-Id',\n StorefrontPrivateToken = 'Shopify-Storefront-Private-Token',\n StorefrontSDKVariant = 'X-SDK-Variant',\n StorefrontSDKVersion = 'X-SDK-Version',\n}\n/* eslint-enable @shopify/typescript-prefer-pascal-case-enums */\n\nexport const ShopifyEventsHeader = {\n Hmac: 'shopify-hmac-sha256',\n Topic: 'shopify-topic',\n Domain: 'shopify-shop-domain',\n ApiVersion: 'shopify-api-version',\n WebhookId: 'shopify-webhook-id',\n Handle: 'shopify-handle',\n Action: 'shopify-action',\n TriggeredAt: 'shopify-triggered-at',\n} as const;\n\nexport enum ClientType {\n Rest = 'rest',\n Graphql = 'graphql',\n}\n\nexport const privacyTopics: string[] = [\n 'CUSTOMERS_DATA_REQUEST',\n 'CUSTOMERS_REDACT',\n 'SHOP_REDACT',\n];\n\nexport enum BillingInterval {\n OneTime = 'ONE_TIME',\n Every30Days = 'EVERY_30_DAYS',\n Annual = 'ANNUAL',\n Usage = 'USAGE',\n}\n\nexport type RecurringBillingIntervals = Exclude<\n BillingInterval,\n BillingInterval.OneTime\n>;\n\nexport enum BillingReplacementBehavior {\n ApplyImmediately = 'APPLY_IMMEDIATELY',\n ApplyOnNextBillingCycle = 'APPLY_ON_NEXT_BILLING_CYCLE',\n Standard = 'STANDARD',\n}\n\nexport enum StatusCode {\n Continue = 100,\n SwitchingProtocols = 101,\n Ok = 200,\n Created = 201,\n Accepted = 202,\n NonAuthoritativeInformation = 203,\n NoContent = 204,\n ResetContent = 205,\n PartialContent = 206,\n MultipleChoices = 300,\n MovedPermanently = 301,\n Found = 302,\n SeeOther = 303,\n NotModified = 304,\n UseProxy = 305,\n TemporaryRedirect = 307,\n BadRequest = 400,\n Unauthorized = 401,\n PaymentRequired = 402,\n Forbidden = 403,\n NotFound = 404,\n MethodNotAllowed = 405,\n NotAcceptable = 406,\n ProxyAuthenticationRequired = 407,\n RequestTimeout = 408,\n Conflict = 409,\n Gone = 410,\n LengthRequired = 411,\n PreconditionFailed = 412,\n RequestEntityTooLarge = 413,\n RequestUriTooLong = 414,\n UnsupportedMediaType = 415,\n RequestedRangeNotSatisfiable = 416,\n ExpectationFailed = 417,\n ImATeapot = 418,\n UnprocessableEntity = 422,\n TooManyRequests = 429,\n InternalServerError = 500,\n NotImplemented = 501,\n BadGateway = 502,\n ServiceUnavailable = 503,\n GatewayTimeout = 504,\n HttpVersionNotSupported = 505,\n}\n\nexport enum Method {\n Get = 'GET',\n Post = 'POST',\n Put = 'PUT',\n Patch = 'PATCH',\n Delete = 'DELETE',\n Head = 'HEAD',\n Options = 'OPTIONS',\n Connect = 'CONNECT',\n}\n\n/**\n * Configuration for transforming shop domains in split-domain architectures.\n *\n * @example\n * // Template-based transformation\n * {\n * match: /^([a-zA-Z0-9][a-zA-Z0-9-_]*)\\.my\\.shop\\.dev$/,\n * transform: '$1.dev-api.shop.dev'\n * }\n *\n * @example\n * // Function-based transformation\n * {\n * match: /^([^.]+)\\.ui\\.example\\.com$/,\n * transform: (matches) => `${matches[1]}.api.example.com`\n * }\n */\nexport interface DomainTransformation {\n /**\n * Pattern to match against shop domains (source domain).\n * Can be a RegExp or string (converted to RegExp internally).\n */\n match: RegExp | string;\n\n /**\n * Transformation function or template string.\n * - Template string: Uses $1, $2, etc. for capture group substitution\n * - Function: Receives regex match groups and returns transformed domain\n */\n transform: ((matches: RegExpMatchArray) => string | null) | string;\n\n /**\n * Whether this transformation should also apply to host validation.\n * @default true\n */\n includeHost?: boolean;\n}\n"],"names":[],"mappings":"IAAY;AAAZ,CAAA,UAAY,WAAW,EAAA;A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AA,gBAAA,CAAA,GAAA,GAAA,CAAA,GAAA,gBAAoB;AACpB,IAAA,UAAA,CAAA,UAAA,CAAA,yBAAA,CAAA,GAAA,GAAA,CAAA,GAAA,yBAA6B;AAC/B,CAAC,EA5CW,UAAU,KAAV,UAAU,GAAA,EAAA,CAAA,CAAA;IA8CV;AAAZ,CAAA,UAAY,MAAM,EAAA;AAChB,IAAA,MAAA,CAAA,KAAA,CAAA,GAAA,KAAW;AACX,IAAA,MAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACb,IAAA,MAAA,CAAA,KAAA,CAAA,GAAA,KAAW;AACX,IAAA,MAAA,CAAA,OAAA,CAAA,GAAA,OAAe;AACf,IAAA,MAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,MAAA,CAAA,MAAA,CAAA,GAAA,MAAa;AACb,IAAA,MAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACnB,IAAA,MAAA,CAAA,SAAA,CAAA,GAAA,SAAmB;AACrB,CAAC,EATW,MAAM,KAAN,MAAM,GAAA,EAAA,CAAA,CAAA;;;;"}
@@ -1,4 +1,4 @@
1
- const SHOPIFY_API_LIBRARY_VERSION = '14.0.1';
1
+ const SHOPIFY_API_LIBRARY_VERSION = '15.0.1';
2
2
 
3
3
  export { SHOPIFY_API_LIBRARY_VERSION };
4
4
  //# sourceMappingURL=version.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"version.mjs","sources":["../../../../../lib/version.ts"],"sourcesContent":["export const SHOPIFY_API_LIBRARY_VERSION = '14.0.1';\n"],"names":[],"mappings":"AAAO,MAAM,2BAA2B,GAAG;;;;"}
1
+ {"version":3,"file":"version.mjs","sources":["../../../../../lib/version.ts"],"sourcesContent":["export const SHOPIFY_API_LIBRARY_VERSION = '15.0.1';\n"],"names":[],"mappings":"AAAO,MAAM,2BAA2B,GAAG;;;;"}
@@ -22,10 +22,8 @@ const WEBHOOK_HEADER_NAMES = {
22
22
  domain: ShopifyEventsHeader.Domain,
23
23
  apiVersion: ShopifyEventsHeader.ApiVersion,
24
24
  webhookId: ShopifyEventsHeader.WebhookId,
25
- eventId: ShopifyEventsHeader.EventId,
26
25
  handle: ShopifyEventsHeader.Handle,
27
26
  action: ShopifyEventsHeader.Action,
28
- resourceId: ShopifyEventsHeader.ResourceId,
29
27
  triggeredAt: ShopifyEventsHeader.TriggeredAt,
30
28
  },
31
29
  };
@@ -1 +1 @@
1
- {"version":3,"file":"types.mjs","sources":["../../../../../../lib/webhooks/types.ts"],"sourcesContent":["import {ValidationErrorReason, ValidationInvalid} from '../utils/types';\nimport {AdapterArgs} from '../../runtime/types';\nimport {Session} from '../session/session';\nimport {ShopifyEventsHeader, ShopifyHeader} from '../types';\n\nexport const WebhookType = {\n Webhooks: 'webhooks',\n Events: 'events',\n} as const;\n\nexport type WebhookTypeValue = (typeof WebhookType)[keyof typeof WebhookType];\n\nexport const WEBHOOK_HEADER_NAMES = {\n [WebhookType.Webhooks]: {\n hmac: ShopifyHeader.Hmac,\n topic: ShopifyHeader.Topic,\n domain: ShopifyHeader.Domain,\n apiVersion: ShopifyHeader.ApiVersion,\n webhookId: ShopifyHeader.WebhookId,\n name: ShopifyHeader.Name,\n triggeredAt: ShopifyHeader.TriggeredAt,\n eventId: ShopifyHeader.EventId,\n },\n [WebhookType.Events]: {\n hmac: ShopifyEventsHeader.Hmac,\n topic: ShopifyEventsHeader.Topic,\n domain: ShopifyEventsHeader.Domain,\n apiVersion: ShopifyEventsHeader.ApiVersion,\n webhookId: ShopifyEventsHeader.WebhookId,\n eventId: ShopifyEventsHeader.EventId,\n handle: ShopifyEventsHeader.Handle,\n action: ShopifyEventsHeader.Action,\n resourceId: ShopifyEventsHeader.ResourceId,\n triggeredAt: ShopifyEventsHeader.TriggeredAt,\n },\n} as const;\n\nexport enum DeliveryMethod {\n Http = 'http',\n EventBridge = 'eventbridge',\n PubSub = 'pubsub',\n}\n\nexport type WebhookHandlerFunction = (\n topic: string,\n shop_domain: string,\n body: string,\n webhookId: string,\n apiVersion?: string,\n context?: any,\n) => Promise<void>;\n\ninterface BaseWebhookHandler {\n id?: string;\n includeFields?: string[];\n metafieldNamespaces?: string[];\n context?: any;\n}\n\nexport interface HttpWebhookHandler extends BaseWebhookHandler {\n deliveryMethod: DeliveryMethod.Http;\n callbackUrl: string;\n}\n\nexport interface HttpWebhookHandlerWithCallback extends HttpWebhookHandler {\n callback: WebhookHandlerFunction;\n}\n\nexport interface EventBridgeWebhookHandler extends BaseWebhookHandler {\n deliveryMethod: DeliveryMethod.EventBridge;\n arn: string;\n}\n\nexport interface PubSubWebhookHandler extends BaseWebhookHandler {\n deliveryMethod: DeliveryMethod.PubSub;\n pubSubProject: string;\n pubSubTopic: string;\n}\n\nexport type WebhookHandler =\n | HttpWebhookHandler\n | HttpWebhookHandlerWithCallback\n | EventBridgeWebhookHandler\n | PubSubWebhookHandler;\n\n// See https://shopify.dev/docs/api/admin-graphql/latest/enums/webhooksubscriptiontopic for available topics\nexport type WebhookRegistry<Handler extends WebhookHandler = WebhookHandler> =\n Record<string, Handler[]>;\n\n// eslint-disable-next-line no-warning-comments\n// TODO Rethink the wording for this enum - the operations we're doing are actually \"subscribing\" and \"unsubscribing\"\n// Consider changing the values when releasing v12.0.0 when it can be safely deprecated\nexport enum WebhookOperation {\n Create = 'create',\n Update = 'update',\n Delete = 'delete',\n}\n\nexport interface RegisterParams {\n session: Session;\n}\n\nexport interface RegisterResult {\n success: boolean;\n deliveryMethod: DeliveryMethod;\n result: unknown;\n operation: WebhookOperation;\n}\n\nexport type RegisterReturn = Record<string, RegisterResult[]>;\n\ninterface WebhookHttpEndpoint {\n __typename: 'WebhookHttpEndpoint';\n callbackUrl: string;\n}\ninterface WebhookEventBridgeEndpoint {\n __typename: 'WebhookEventBridgeEndpoint';\n arn: string;\n}\ninterface WebhookPubSubEndpoint {\n __typename: 'WebhookPubSubEndpoint';\n pubSubProject: string;\n pubSubTopic: string;\n}\n\ntype WebhookEndpoint =\n WebhookHttpEndpoint | WebhookEventBridgeEndpoint | WebhookPubSubEndpoint;\n\nexport interface WebhookCheckResponseNode<\n T = {\n endpoint: WebhookEndpoint;\n },\n> {\n node: {\n id: string;\n topic: string;\n includeFields: string[];\n metafieldNamespaces: string[];\n } & T;\n}\n\nexport interface WebhookCheckResponse<T = WebhookCheckResponseNode> {\n webhookSubscriptions: {\n edges: T[];\n pageInfo: {\n endCursor: string;\n hasNextPage: boolean;\n };\n };\n}\n\nexport type AddHandlersParams = Record<\n string,\n WebhookHandler | WebhookHandler[]\n>;\n\nexport interface WebhookProcessParams extends AdapterArgs {\n rawBody: string;\n context?: any;\n}\n\nexport interface WebhookValidateParams extends WebhookProcessParams {}\n\nexport const WebhookValidationErrorReason = {\n ...ValidationErrorReason,\n MissingHeaders: 'missing_headers',\n} as const;\n\nexport type WebhookValidationErrorReasonType =\n (typeof WebhookValidationErrorReason)[keyof typeof WebhookValidationErrorReason];\n\ninterface BaseWebhookFields {\n apiVersion: string;\n domain: string;\n hmac: string;\n topic: string;\n triggeredAt?: string;\n}\n\nexport interface WebhooksWebhookFields extends BaseWebhookFields {\n webhookType: typeof WebhookType.Webhooks;\n webhookId: string;\n name?: string;\n eventId?: string;\n}\n\nexport interface EventsWebhookFields extends BaseWebhookFields {\n webhookType: typeof WebhookType.Events;\n webhookId: string;\n eventId: string;\n handle?: string;\n action?: string;\n resourceId?: string;\n}\n\nexport type WebhookFields = WebhooksWebhookFields | EventsWebhookFields;\n\nexport interface WebhookValidationInvalid extends Omit<\n ValidationInvalid,\n 'reason'\n> {\n valid: false;\n reason: WebhookValidationErrorReasonType;\n}\n\nexport interface WebhookValidationMissingHeaders extends WebhookValidationInvalid {\n reason: typeof WebhookValidationErrorReason.MissingHeaders;\n missingHeaders: string[];\n}\n\nexport type WebhookValidationValid = WebhookFields & {valid: true};\n\nexport type WebhookValidation =\n | WebhookValidationValid\n | WebhookValidationInvalid\n | WebhookValidationMissingHeaders;\n"],"names":[],"mappings":";;;AAKO,MAAM,WAAW,GA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AAiB;AACjB,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACjB,IAAA,gBAAA,CAAA,QAAA,CAAA,GAAA,QAAiB;AACnB,CAAC,EAJW,gBAAgB,KAAhB,gBAAgB,GAAA,EAAA,CAAA,CAAA;AAuErB,MAAM,4BAA4B,GAAG;AAC1C,IAAA,GAAG,qBAAqB;AACxB,IAAA,cAAc,EAAE,iBAAiB;;;;;"}
1
+ {"version":3,"file":"types.mjs","sources":["../../../../../../lib/webhooks/types.ts"],"sourcesContent":["import {ValidationErrorReason, ValidationInvalid} from '../utils/types';\nimport {AdapterArgs} from '../../runtime/types';\nimport {Session} from '../session/session';\nimport {ShopifyEventsHeader, ShopifyHeader} from '../types';\n\nexport const WebhookType = {\n Webhooks: 'webhooks',\n Events: 'events',\n} as const;\n\nexport type WebhookTypeValue = (typeof WebhookType)[keyof typeof WebhookType];\n\nexport const WEBHOOK_HEADER_NAMES = {\n [WebhookType.Webhooks]: {\n hmac: ShopifyHeader.Hmac,\n topic: ShopifyHeader.Topic,\n domain: ShopifyHeader.Domain,\n apiVersion: ShopifyHeader.ApiVersion,\n webhookId: ShopifyHeader.WebhookId,\n name: ShopifyHeader.Name,\n triggeredAt: ShopifyHeader.TriggeredAt,\n eventId: ShopifyHeader.EventId,\n },\n [WebhookType.Events]: {\n hmac: ShopifyEventsHeader.Hmac,\n topic: ShopifyEventsHeader.Topic,\n domain: ShopifyEventsHeader.Domain,\n apiVersion: ShopifyEventsHeader.ApiVersion,\n webhookId: ShopifyEventsHeader.WebhookId,\n handle: ShopifyEventsHeader.Handle,\n action: ShopifyEventsHeader.Action,\n triggeredAt: ShopifyEventsHeader.TriggeredAt,\n },\n} as const;\n\nexport enum DeliveryMethod {\n Http = 'http',\n EventBridge = 'eventbridge',\n PubSub = 'pubsub',\n}\n\nexport type WebhookHandlerFunction = (\n topic: string,\n shop_domain: string,\n body: string,\n webhookId: string,\n apiVersion?: string,\n context?: any,\n) => Promise<void>;\n\ninterface BaseWebhookHandler {\n id?: string;\n includeFields?: string[];\n metafieldNamespaces?: string[];\n context?: any;\n}\n\nexport interface HttpWebhookHandler extends BaseWebhookHandler {\n deliveryMethod: DeliveryMethod.Http;\n callbackUrl: string;\n}\n\nexport interface HttpWebhookHandlerWithCallback extends HttpWebhookHandler {\n callback: WebhookHandlerFunction;\n}\n\nexport interface EventBridgeWebhookHandler extends BaseWebhookHandler {\n deliveryMethod: DeliveryMethod.EventBridge;\n arn: string;\n}\n\nexport interface PubSubWebhookHandler extends BaseWebhookHandler {\n deliveryMethod: DeliveryMethod.PubSub;\n pubSubProject: string;\n pubSubTopic: string;\n}\n\nexport type WebhookHandler =\n | HttpWebhookHandler\n | HttpWebhookHandlerWithCallback\n | EventBridgeWebhookHandler\n | PubSubWebhookHandler;\n\n// See https://shopify.dev/docs/api/admin-graphql/latest/enums/webhooksubscriptiontopic for available topics\nexport type WebhookRegistry<Handler extends WebhookHandler = WebhookHandler> =\n Record<string, Handler[]>;\n\n// eslint-disable-next-line no-warning-comments\n// TODO Rethink the wording for this enum - the operations we're doing are actually \"subscribing\" and \"unsubscribing\"\n// Consider changing the values when releasing v12.0.0 when it can be safely deprecated\nexport enum WebhookOperation {\n Create = 'create',\n Update = 'update',\n Delete = 'delete',\n}\n\nexport interface RegisterParams {\n session: Session;\n}\n\nexport interface RegisterResult {\n success: boolean;\n deliveryMethod: DeliveryMethod;\n result: unknown;\n operation: WebhookOperation;\n}\n\nexport type RegisterReturn = Record<string, RegisterResult[]>;\n\ninterface WebhookHttpEndpoint {\n __typename: 'WebhookHttpEndpoint';\n callbackUrl: string;\n}\ninterface WebhookEventBridgeEndpoint {\n __typename: 'WebhookEventBridgeEndpoint';\n arn: string;\n}\ninterface WebhookPubSubEndpoint {\n __typename: 'WebhookPubSubEndpoint';\n pubSubProject: string;\n pubSubTopic: string;\n}\n\ntype WebhookEndpoint =\n WebhookHttpEndpoint | WebhookEventBridgeEndpoint | WebhookPubSubEndpoint;\n\nexport interface WebhookCheckResponseNode<\n T = {\n endpoint: WebhookEndpoint;\n },\n> {\n node: {\n id: string;\n topic: string;\n includeFields: string[];\n metafieldNamespaces: string[];\n } & T;\n}\n\nexport interface WebhookCheckResponse<T = WebhookCheckResponseNode> {\n webhookSubscriptions: {\n edges: T[];\n pageInfo: {\n endCursor: string;\n hasNextPage: boolean;\n };\n };\n}\n\nexport type AddHandlersParams = Record<\n string,\n WebhookHandler | WebhookHandler[]\n>;\n\nexport interface WebhookProcessParams extends AdapterArgs {\n rawBody: string;\n context?: any;\n}\n\nexport interface WebhookValidateParams extends WebhookProcessParams {}\n\nexport const WebhookValidationErrorReason = {\n ...ValidationErrorReason,\n MissingHeaders: 'missing_headers',\n} as const;\n\nexport type WebhookValidationErrorReasonType =\n (typeof WebhookValidationErrorReason)[keyof typeof WebhookValidationErrorReason];\n\ninterface BaseWebhookFields {\n apiVersion: string;\n domain: string;\n hmac: string;\n topic: string;\n triggeredAt?: string;\n}\n\nexport interface WebhooksWebhookFields extends BaseWebhookFields {\n webhookType: typeof WebhookType.Webhooks;\n webhookId: string;\n name?: string;\n eventId?: string;\n}\n\nexport interface EventsWebhookFields extends BaseWebhookFields {\n webhookType: typeof WebhookType.Events;\n webhookId: string;\n handle?: string;\n action?: string;\n}\n\nexport type WebhookFields = WebhooksWebhookFields | EventsWebhookFields;\n\nexport interface WebhookValidationInvalid extends Omit<\n ValidationInvalid,\n 'reason'\n> {\n valid: false;\n reason: WebhookValidationErrorReasonType;\n}\n\nexport interface WebhookValidationMissingHeaders extends WebhookValidationInvalid {\n reason: typeof WebhookValidationErrorReason.MissingHeaders;\n missingHeaders: string[];\n}\n\nexport type WebhookValidationValid = WebhookFields & {valid: true};\n\nexport type WebhookValidation =\n | WebhookValidationValid\n | WebhookValidationInvalid\n | WebhookValidationMissingHeaders;\n"],"names":[],"mappings":";;;AAKO,MAAM,WAAW,GAAG;AACzB,IAAA,QAAQ,EAAE,UAAU;AACpB,IAAA,MAAM,EAAE,QAAQ;;AAKX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AAA,EAAA,CAAA,CAAA;AAuErB,MAAM,4BAA4B,GAAG;AAC1C,IAAA,GAAG,qBAAqB;AACxB,IAAA,cAAc,EAAE,iBAAiB;;;;;"}
@@ -92,7 +92,6 @@ function checkEventsHeaders(headers) {
92
92
  const domain = getRequiredHeader(headers, headerNames.domain, missingHeaders);
93
93
  const apiVersion = getRequiredHeader(headers, headerNames.apiVersion, missingHeaders);
94
94
  const webhookId = getRequiredHeader(headers, headerNames.webhookId, missingHeaders);
95
- const eventId = getRequiredHeader(headers, headerNames.eventId, missingHeaders);
96
95
  if (missingHeaders.length) {
97
96
  return {
98
97
  valid: false,
@@ -107,7 +106,6 @@ function checkEventsHeaders(headers) {
107
106
  domain: domain,
108
107
  apiVersion: apiVersion,
109
108
  webhookId: webhookId,
110
- eventId: eventId,
111
109
  };
112
110
  const handle = getHeader(headers, headerNames.handle);
113
111
  if (handle)
@@ -115,9 +113,6 @@ function checkEventsHeaders(headers) {
115
113
  const action = getHeader(headers, headerNames.action);
116
114
  if (action)
117
115
  fields.action = action;
118
- const resourceId = getHeader(headers, headerNames.resourceId);
119
- if (resourceId)
120
- fields.resourceId = resourceId;
121
116
  const triggeredAt = getHeader(headers, headerNames.triggeredAt);
122
117
  if (triggeredAt)
123
118
  fields.triggeredAt = triggeredAt;
@@ -1 +1 @@
1
- {"version":3,"file":"validate.mjs","sources":["../../../../../../lib/webhooks/validate.ts"],"sourcesContent":["import {logger} from '../logger';\nimport {validateHmacFromRequestFactory} from '../utils/hmac-validator';\nimport {HmacValidationType, ValidationErrorReason} from '../utils/types';\nimport {\n abstractConvertRequest,\n getHeader,\n Headers,\n NormalizedRequest,\n} from '../../runtime/http';\nimport {ConfigInterface} from '../base-types';\n\nimport {\n EventsWebhookFields,\n WEBHOOK_HEADER_NAMES,\n WebhooksWebhookFields,\n WebhookType,\n WebhookTypeValue,\n WebhookValidateParams,\n WebhookValidation,\n WebhookValidationErrorReason,\n WebhookValidationMissingHeaders,\n WebhookValidationValid,\n} from './types';\nimport {topicForStorage} from './registry';\n\nfunction detectWebhookType(headers: Headers): WebhookTypeValue {\n const eventsHmac = getHeader(\n headers,\n WEBHOOK_HEADER_NAMES[WebhookType.Events].hmac,\n );\n if (eventsHmac) {\n return WebhookType.Events;\n }\n\n const webhooksHmac = getHeader(\n headers,\n WEBHOOK_HEADER_NAMES[WebhookType.Webhooks].hmac,\n );\n if (webhooksHmac) {\n return WebhookType.Webhooks;\n }\n\n return WebhookType.Webhooks;\n}\n\nexport function validateFactory(config: ConfigInterface) {\n return async function validate({\n rawBody,\n ...adapterArgs\n }: WebhookValidateParams): Promise<WebhookValidation> {\n const request: NormalizedRequest =\n await abstractConvertRequest(adapterArgs);\n\n const webhookType = detectWebhookType(request.headers);\n\n const validHmacResult = await validateHmacFromRequestFactory(config)({\n type: HmacValidationType.Webhook,\n rawBody,\n webhookType,\n ...adapterArgs,\n });\n\n if (!validHmacResult.valid) {\n if (validHmacResult.reason === ValidationErrorReason.InvalidHmac) {\n const log = logger(config);\n await log.debug(\n \"Webhook HMAC validation failed. Please note that events manually triggered from a store's Notifications settings will fail this validation. To test this, please use the CLI or trigger the actual event in a development store.\",\n );\n }\n return validHmacResult;\n }\n\n return checkWebhookHeaders(request.headers, webhookType);\n };\n}\n\nfunction getRequiredHeader(\n headers: Headers,\n headerName: string,\n missingHeaders: string[],\n): string | undefined {\n const value = getHeader(headers, headerName);\n if (!value) {\n missingHeaders.push(headerName);\n }\n return value;\n}\n\nfunction checkWebhookHeaders(\n headers: Headers,\n webhookType: WebhookTypeValue,\n): WebhookValidationMissingHeaders | WebhookValidationValid {\n if (webhookType === WebhookType.Webhooks) {\n return checkWebhooksHeaders(headers);\n }\n return checkEventsHeaders(headers);\n}\n\nfunction checkWebhooksHeaders(\n headers: Headers,\n): WebhookValidationMissingHeaders | WebhookValidationValid {\n const headerNames = WEBHOOK_HEADER_NAMES[WebhookType.Webhooks];\n const missingHeaders: string[] = [];\n\n const hmac = getRequiredHeader(headers, headerNames.hmac, missingHeaders);\n const topic = getRequiredHeader(headers, headerNames.topic, missingHeaders);\n const domain = getRequiredHeader(headers, headerNames.domain, missingHeaders);\n const apiVersion = getRequiredHeader(\n headers,\n headerNames.apiVersion,\n missingHeaders,\n );\n const webhookId = getRequiredHeader(\n headers,\n headerNames.webhookId,\n missingHeaders,\n );\n\n if (missingHeaders.length) {\n return {\n valid: false,\n reason: WebhookValidationErrorReason.MissingHeaders,\n missingHeaders,\n };\n }\n\n const fields: WebhooksWebhookFields = {\n webhookType: WebhookType.Webhooks,\n hmac: hmac!,\n topic: topicForStorage(topic!),\n domain: domain!,\n apiVersion: apiVersion!,\n webhookId: webhookId!,\n };\n\n const name = getHeader(headers, headerNames.name);\n if (name) fields.name = name;\n\n const triggeredAt = getHeader(headers, headerNames.triggeredAt);\n if (triggeredAt) fields.triggeredAt = triggeredAt;\n\n const eventId = getHeader(headers, headerNames.eventId);\n if (eventId) fields.eventId = eventId;\n\n return {valid: true, ...fields};\n}\n\nfunction checkEventsHeaders(\n headers: Headers,\n): WebhookValidationMissingHeaders | WebhookValidationValid {\n const headerNames = WEBHOOK_HEADER_NAMES[WebhookType.Events];\n const missingHeaders: string[] = [];\n\n const hmac = getRequiredHeader(headers, headerNames.hmac, missingHeaders);\n const topic = getRequiredHeader(headers, headerNames.topic, missingHeaders);\n const domain = getRequiredHeader(headers, headerNames.domain, missingHeaders);\n const apiVersion = getRequiredHeader(\n headers,\n headerNames.apiVersion,\n missingHeaders,\n );\n const webhookId = getRequiredHeader(\n headers,\n headerNames.webhookId,\n missingHeaders,\n );\n const eventId = getRequiredHeader(\n headers,\n headerNames.eventId,\n missingHeaders,\n );\n\n if (missingHeaders.length) {\n return {\n valid: false,\n reason: WebhookValidationErrorReason.MissingHeaders,\n missingHeaders,\n };\n }\n\n const fields: EventsWebhookFields = {\n webhookType: WebhookType.Events,\n hmac: hmac!,\n topic: topicForStorage(topic!),\n domain: domain!,\n apiVersion: apiVersion!,\n webhookId: webhookId!,\n eventId: eventId!,\n };\n\n const handle = getHeader(headers, headerNames.handle);\n if (handle) fields.handle = handle;\n\n const action = getHeader(headers, headerNames.action);\n if (action) fields.action = action;\n\n const resourceId = getHeader(headers, headerNames.resourceId);\n if (resourceId) fields.resourceId = resourceId;\n\n const triggeredAt = getHeader(headers, headerNames.triggeredAt);\n if (triggeredAt) fields.triggeredAt = triggeredAt;\n\n return {valid: true, ...fields};\n}\n"],"names":[],"mappings":";;;;;;;;AAyBA,SAAS,iBAAiB,CAAC,OAAgB,EAAA;AACzC,IAAA,MAAM,UAAU,GAAG,SAAS,CAC1B,OAAO,EACP,oBAAoB,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,IAAI,CAC9C;IACD,IAAI,UAAU,EAAE;QACd,OAAO,WAAW,CAAC,MAAM;IAC3B;AAEA,IAAA,MAAM,YAAY,GAAG,SAAS,CAC5B,OAAO,EACP,oBAAoB,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,IAAI,CAChD;IACD,IAAI,YAAY,EAAE;QAChB,OAAO,WAAW,CAAC,QAAQ;IAC7B;IAEA,OAAO,WAAW,CAAC,QAAQ;AAC7B;AAEM,SAAU,eAAe,CAAC,MAAuB,EAAA;IACrD,OAAO,eAAe,QAAQ,CAAC,EAC7B,OAAO,EACP,GAAG,WAAW,EACQ,EAAA;AACtB,QAAA,MAAM,OAAO,GACX,MAAM,sBAAsB,CAAC,WAAW,CAAC;QAE3C,MAAM,WAAW,GAAG,iBAAiB,CAAC,OAAO,CAAC,OAAO,CAAC;AAEtD,QAAA,MAAM,eAAe,GAAG,MAAM,8BAA8B,CAAC,MAAM,CAAC,CAAC;YACnE,IAAI,EAAE,kBAAkB,CAAC,OAAO;YAChC,OAAO;YACP,WAAW;AACX,YAAA,GAAG,WAAW;AACf,SAAA,CAAC;AAEF,QAAA,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE;YAC1B,IAAI,eAAe,CAAC,MAAM,KAAK,qBAAqB,CAAC,WAAW,EAAE;AAChE,gBAAA,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AE,WAAW,CAAC,WAAW,CAAC;AAC/D,IAAA,IAAI,WAAW;AAAE,QAAA,MAAM,CAAC,WAAW,GAAG,WAAW;IAEjD,OAAO,EAAC,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,EAAC;AACjC;;;;"}
1
+ {"version":3,"file":"validate.mjs","sources":["../../../../../../lib/webhooks/validate.ts"],"sourcesContent":["import {logger} from '../logger';\nimport {validateHmacFromRequestFactory} from '../utils/hmac-validator';\nimport {HmacValidationType, ValidationErrorReason} from '../utils/types';\nimport {\n abstractConvertRequest,\n getHeader,\n Headers,\n NormalizedRequest,\n} from '../../runtime/http';\nimport {ConfigInterface} from '../base-types';\n\nimport {\n EventsWebhookFields,\n WEBHOOK_HEADER_NAMES,\n WebhooksWebhookFields,\n WebhookType,\n WebhookTypeValue,\n WebhookValidateParams,\n WebhookValidation,\n WebhookValidationErrorReason,\n WebhookValidationMissingHeaders,\n WebhookValidationValid,\n} from './types';\nimport {topicForStorage} from './registry';\n\nfunction detectWebhookType(headers: Headers): WebhookTypeValue {\n const eventsHmac = getHeader(\n headers,\n WEBHOOK_HEADER_NAMES[WebhookType.Events].hmac,\n );\n if (eventsHmac) {\n return WebhookType.Events;\n }\n\n const webhooksHmac = getHeader(\n headers,\n WEBHOOK_HEADER_NAMES[WebhookType.Webhooks].hmac,\n );\n if (webhooksHmac) {\n return WebhookType.Webhooks;\n }\n\n return WebhookType.Webhooks;\n}\n\nexport function validateFactory(config: ConfigInterface) {\n return async function validate({\n rawBody,\n ...adapterArgs\n }: WebhookValidateParams): Promise<WebhookValidation> {\n const request: NormalizedRequest =\n await abstractConvertRequest(adapterArgs);\n\n const webhookType = detectWebhookType(request.headers);\n\n const validHmacResult = await validateHmacFromRequestFactory(config)({\n type: HmacValidationType.Webhook,\n rawBody,\n webhookType,\n ...adapterArgs,\n });\n\n if (!validHmacResult.valid) {\n if (validHmacResult.reason === ValidationErrorReason.InvalidHmac) {\n const log = logger(config);\n await log.debug(\n \"Webhook HMAC validation failed. Please note that events manually triggered from a store's Notifications settings will fail this validation. To test this, please use the CLI or trigger the actual event in a development store.\",\n );\n }\n return validHmacResult;\n }\n\n return checkWebhookHeaders(request.headers, webhookType);\n };\n}\n\nfunction getRequiredHeader(\n headers: Headers,\n headerName: string,\n missingHeaders: string[],\n): string | undefined {\n const value = getHeader(headers, headerName);\n if (!value) {\n missingHeaders.push(headerName);\n }\n return value;\n}\n\nfunction checkWebhookHeaders(\n headers: Headers,\n webhookType: WebhookTypeValue,\n): WebhookValidationMissingHeaders | WebhookValidationValid {\n if (webhookType === WebhookType.Webhooks) {\n return checkWebhooksHeaders(headers);\n }\n return checkEventsHeaders(headers);\n}\n\nfunction checkWebhooksHeaders(\n headers: Headers,\n): WebhookValidationMissingHeaders | WebhookValidationValid {\n const headerNames = WEBHOOK_HEADER_NAMES[WebhookType.Webhooks];\n const missingHeaders: string[] = [];\n\n const hmac = getRequiredHeader(headers, headerNames.hmac, missingHeaders);\n const topic = getRequiredHeader(headers, headerNames.topic, missingHeaders);\n const domain = getRequiredHeader(headers, headerNames.domain, missingHeaders);\n const apiVersion = getRequiredHeader(\n headers,\n headerNames.apiVersion,\n missingHeaders,\n );\n const webhookId = getRequiredHeader(\n headers,\n headerNames.webhookId,\n missingHeaders,\n );\n\n if (missingHeaders.length) {\n return {\n valid: false,\n reason: WebhookValidationErrorReason.MissingHeaders,\n missingHeaders,\n };\n }\n\n const fields: WebhooksWebhookFields = {\n webhookType: WebhookType.Webhooks,\n hmac: hmac!,\n topic: topicForStorage(topic!),\n domain: domain!,\n apiVersion: apiVersion!,\n webhookId: webhookId!,\n };\n\n const name = getHeader(headers, headerNames.name);\n if (name) fields.name = name;\n\n const triggeredAt = getHeader(headers, headerNames.triggeredAt);\n if (triggeredAt) fields.triggeredAt = triggeredAt;\n\n const eventId = getHeader(headers, headerNames.eventId);\n if (eventId) fields.eventId = eventId;\n\n return {valid: true, ...fields};\n}\n\nfunction checkEventsHeaders(\n headers: Headers,\n): WebhookValidationMissingHeaders | WebhookValidationValid {\n const headerNames = WEBHOOK_HEADER_NAMES[WebhookType.Events];\n const missingHeaders: string[] = [];\n\n const hmac = getRequiredHeader(headers, headerNames.hmac, missingHeaders);\n const topic = getRequiredHeader(headers, headerNames.topic, missingHeaders);\n const domain = getRequiredHeader(headers, headerNames.domain, missingHeaders);\n const apiVersion = getRequiredHeader(\n headers,\n headerNames.apiVersion,\n missingHeaders,\n );\n const webhookId = getRequiredHeader(\n headers,\n headerNames.webhookId,\n missingHeaders,\n );\n\n if (missingHeaders.length) {\n return {\n valid: false,\n reason: WebhookValidationErrorReason.MissingHeaders,\n missingHeaders,\n };\n }\n\n const fields: EventsWebhookFields = {\n webhookType: WebhookType.Events,\n hmac: hmac!,\n topic: topicForStorage(topic!),\n domain: domain!,\n apiVersion: apiVersion!,\n webhookId: webhookId!,\n };\n\n const handle = getHeader(headers, headerNames.handle);\n if (handle) fields.handle = handle;\n\n const action = getHeader(headers, headerNames.action);\n if (action) fields.action = action;\n\n const triggeredAt = getHeader(headers, headerNames.triggeredAt);\n if (triggeredAt) fields.triggeredAt = triggeredAt;\n\n return {valid: true, ...fields};\n}\n"],"names":[],"mappings":";;;;;;;;AAyBA,SAAS,iBAAiB,CAAC,OAAgB,EAAA;AACzC,IAAA,MAAM,UAAU,GAAG,SAAS,CAC1B,OAAO,EACP,oBAAoB,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,IAAI,CAC9C;IACD,IAAI,UAAU,EAAE;QACd,OAAO,WAAW,CAAC,MAAM;IAC3B;AAEA,IAAA,MAAM,YAAY,GAAG,SAAS,CAC5B,OAAO,EACP,oBAAoB,CAAC,WAAW,CAAC,QAAQ,CAAC,CAAC,IAAI,CAChD;IACD,IAAI,YAAY,EAAE;QAChB,OAAO,WAAW,CAAC,QAAQ;IAC7B;IAEA,OAAO,WAAW,CAAC,QAAQ;AAC7B;AAEM,SAAU,eAAe,CAAC,MAAuB,EAAA;IACrD,OAAO,eAAe,QAAQ,CAAC,EAC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M,GAAG,MAAM;IAElC,MAAM,MAAM,GAAG,SAAS,CAAC,OAAO,EAAE,WAAW,CAAC,MAAM,CAAC;AACrD,IAAA,IAAI,MAAM;AAAE,QAAA,MAAM,CAAC,MAAM,GAAG,MAAM;IAElC,MAAM,WAAW,GAAG,SAAS,CAAC,OAAO,EAAE,WAAW,CAAC,WAAW,CAAC;AAC/D,IAAA,IAAI,WAAW;AAAE,QAAA,MAAM,CAAC,WAAW,GAAG,WAAW;IAEjD,OAAO,EAAC,KAAK,EAAE,IAAI,EAAE,GAAG,MAAM,EAAC;AACjC;;;;"}
@@ -33,7 +33,11 @@ class Cookies {
33
33
  {
34
34
  name,
35
35
  value,
36
- ...Object.fromEntries(opts.map((opt) => splitN(opt, '=', 2).map((value) => value.trim()))),
36
+ ...Object.fromEntries(opts.map((opt) => {
37
+ const [key, value] = splitN(opt, '=', 2).map((value) => value.trim());
38
+ // Flag attributes like HttpOnly have no value
39
+ return [key, value ?? true];
40
+ })),
37
41
  },
38
42
  ];
39
43
  });
@@ -49,8 +53,9 @@ class Cookies {
49
53
  let result = '';
50
54
  result += `${data.name}=${data.value};`;
51
55
  result += Object.entries(data)
52
- .filter(([key]) => !['name', 'value', 'expires'].includes(key))
53
- .map(([key, value]) => `${key}=${value}`)
56
+ .filter(([key, value]) => !['name', 'value', 'expires'].includes(key) && value !== false)
57
+ // Boolean attributes are flags, so only write them when true
58
+ .map(([key, value]) => (value === true ? key : `${key}=${value}`))
54
59
  .join('; ');
55
60
  if (data.expires) {
56
61
  result += ';';
@@ -103,6 +108,7 @@ class Cookies {
103
108
  }
104
109
  set(name, value, opts = {}) {
105
110
  this.outgoingCookieJar[name] = {
111
+ httpOnly: true,
106
112
  ...opts,
107
113
  name,
108
114
  value,
@@ -1 +1 @@
1
- {"version":3,"file":"cookies.mjs","sources":["../../../../../../runtime/http/cookies.ts"],"sourcesContent":["// import type {Headers} from \"./headers\";\nimport {createSHA256HMAC, deriveSHA256HMACKey} from '../crypto/utils';\n\nimport {splitN} from './utils';\nimport {getHeader, getHeaders, removeHeader, addHeader} from './headers';\n\nimport type {NormalizedRequest, NormalizedResponse} from '.';\n\nexport interface CookieData {\n name: string;\n value: string;\n /**\n * a number representing the milliseconds from Date.now() for expiry\n */\n maxAge?: number;\n /**\n * a Date object indicating the cookie's expiration\n * date (expires at the end of session by default).\n */\n expires?: Date;\n /**\n * a string indicating the path of the cookie (/ by default).\n */\n path?: string;\n /**\n * a string indicating the domain of the cookie (no default).\n */\n domain?: string;\n /**\n * a boolean indicating whether the cookie is only to be sent\n * over HTTPS (false by default for HTTP, true by default for HTTPS).\n */\n secure?: boolean;\n /**\n * a boolean indicating whether the cookie is only to be sent over HTTP(S),\n * and not made available to client JavaScript (true by default).\n */\n httpOnly?: boolean;\n /**\n * a boolean or string indicating whether the cookie is a \"same site\" cookie (false by default).\n * This can be set to 'strict', 'lax', or true (which maps to 'strict').\n */\n sameSite?: 'strict' | 'lax' | 'none';\n}\n\nexport type CookieJar = Record<string, CookieData>;\n\nconst COOKIE_SIGNING_INFO = 'shopify-app-js/cookie-signing/v1';\n\nasync function createCookieSignature(\n key: string,\n value: string,\n): Promise<string> {\n const cookieSigningKey = await deriveSHA256HMACKey(key, COOKIE_SIGNING_INFO);\n return createSHA256HMAC(cookieSigningKey, value);\n}\n\nconst signatureEncoder = new TextEncoder();\n\nfunction safelyCompareSignatures(signatureA: string, signatureB: string) {\n const buffA = signatureEncoder.encode(signatureA);\n const buffB = signatureEncoder.encode(signatureB);\n\n if (buffA.length !== buffB.length) return false;\n\n let out = 0;\n for (let i = 0; i < buffA.length; i++) {\n out |= buffA[i] ^ buffB[i];\n }\n\n return out === 0;\n}\n\ninterface CookiesOptions {\n keys: string[];\n // Ignored. Only for type-compatibility with the node package for now.\n secure: boolean;\n}\nexport class Cookies {\n static parseCookies(hdrs: string[]): CookieJar {\n const entries = hdrs\n .filter((hdr) => hdr.trim().length > 0)\n .map((cookieDef) => {\n const [keyval, ...opts] = cookieDef.split(';');\n const [name, value] = splitN(keyval, '=', 2).map((value) =>\n value.trim(),\n );\n return [\n name,\n {\n name,\n value,\n ...Object.fromEntries(\n opts.map((opt) =>\n splitN(opt, '=', 2).map((value) => value.trim()),\n ),\n ),\n },\n ];\n });\n const jar = Object.fromEntries(entries) as CookieJar;\n for (const cookie of Object.values(jar)) {\n if (typeof cookie.expires === 'string') {\n cookie.expires = new Date(cookie.expires);\n }\n }\n return jar;\n }\n\n static encodeCookie(data: CookieData): string {\n let result = '';\n result += `${data.name}=${data.value};`;\n result += Object.entries(data)\n .filter(([key]) => !['name', 'value', 'expires'].includes(key))\n .map(([key, value]) => `${key}=${value}`)\n .join('; ');\n if (data.expires) {\n result += ';';\n result += `expires=${data.expires.toUTCString()}`;\n }\n return result;\n }\n\n receivedCookieJar: CookieJar = {};\n outgoingCookieJar: CookieJar = {};\n private keys: string[] = [];\n\n constructor(\n request: NormalizedRequest,\n public response: NormalizedResponse,\n {keys = []}: Partial<CookiesOptions> = {},\n ) {\n if (keys) this.keys = keys;\n\n const cookieReqHdr = getHeader(request.headers, 'Cookie') ?? '';\n this.receivedCookieJar = Cookies.parseCookies(cookieReqHdr.split(';'));\n const cookieResHdr = getHeaders(response.headers, 'Set-Cookie') ?? [];\n this.outgoingCookieJar = Cookies.parseCookies(cookieResHdr);\n }\n\n toHeaders(): string[] {\n return Object.values(this.outgoingCookieJar).map((cookie) =>\n Cookies.encodeCookie(cookie),\n );\n }\n\n updateHeader() {\n if (!this.response.headers) {\n this.response.headers = {};\n }\n removeHeader(this.response.headers, 'Set-Cookie');\n this.toHeaders().map((hdr) =>\n addHeader(this.response.headers!, 'Set-Cookie', hdr),\n );\n }\n\n get(name: string): string | undefined {\n return this.receivedCookieJar[name]?.value;\n }\n\n deleteCookie(name: string) {\n this.set(name, '', {\n path: '/',\n expires: new Date(0),\n });\n }\n\n async getAndVerify(name: string): Promise<string | undefined> {\n const value = this.get(name);\n if (!value) return undefined;\n if (!(await this.isSignedCookieValid(name))) {\n return undefined;\n }\n return value;\n }\n\n private get canSign() {\n return this.keys?.length > 0;\n }\n\n set(name: string, value: string, opts: Partial<CookieData> = {}): void {\n this.outgoingCookieJar[name] = {\n ...opts,\n name,\n value,\n };\n this.updateHeader();\n }\n\n async setAndSign(\n name: string,\n value: string,\n opts: Partial<CookieData> = {},\n ): Promise<void> {\n if (!this.canSign) {\n throw Error('No keys provided for signing.');\n }\n this.set(name, value, opts);\n const sigName = `${name}.sig`;\n const signature = await createCookieSignature(this.keys[0], value);\n this.set(sigName, signature, opts);\n this.updateHeader();\n }\n\n async isSignedCookieValid(cookieName: string): Promise<boolean> {\n const signedCookieName = `${cookieName}.sig`;\n if (\n !this.cookieExists(cookieName) ||\n !this.cookieExists(signedCookieName)\n ) {\n this.deleteInvalidCookies(cookieName, signedCookieName);\n return false;\n }\n const cookieValue = this.get(cookieName);\n const signature = this.get(signedCookieName);\n\n if (!cookieValue || !signature) {\n this.deleteInvalidCookies(cookieName, signedCookieName);\n return false;\n }\n\n const allCheckSignatures = await Promise.all(\n this.keys.map((key) => createCookieSignature(key, cookieValue)),\n );\n\n const validSignature = allCheckSignatures.some((checkSignature) =>\n safelyCompareSignatures(checkSignature, signature),\n );\n\n if (!validSignature) {\n this.deleteInvalidCookies(cookieName, signedCookieName);\n return false;\n }\n\n return true;\n }\n\n private cookieExists(cookieName: string) {\n return Boolean(this.get(cookieName));\n }\n\n private deleteInvalidCookies(...cookieNames: string[]): void {\n cookieNames.forEach((cookieName) => this.deleteCookie(cookieName));\n }\n}\n"],"names":[],"mappings":";;;;AAAA;AA+CA,MAAM,mBAAmB,GAAG,kCAAkC;AAE9D,eAAe,qBAAqB,CAClC,GAAW,EACX,KAAa,EAAA;IAEb,MAAM,gBAAgB,GAAG,MAAM,mBAAmB,CAAC,GAAG,EAAE,mBAAmB,CAAC;AAC5E,IAAA,OAAO,gBAAgB,CAAC,gBAAgB,EAAE,KAAK,CAAC;AAClD;AAEA,MAAM,gBAAgB,GAAG,IAAI,WAAW,EAAE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../../runtime/http/cookies.ts"],"sourcesContent":["// import type {Headers} from \"./headers\";\nimport {createSHA256HMAC, deriveSHA256HMACKey} from '../crypto/utils';\n\nimport {splitN} from './utils';\nimport {getHeader, getHeaders, removeHeader, addHeader} from './headers';\n\nimport type {NormalizedRequest, NormalizedResponse} from '.';\n\nexport interface CookieData {\n name: string;\n value: string;\n /**\n * a number representing the milliseconds from Date.now() for expiry\n */\n maxAge?: number;\n /**\n * a Date object indicating the cookie's expiration\n * date (expires at the end of session by default).\n */\n expires?: Date;\n /**\n * a string indicating the path of the cookie (/ by default).\n */\n path?: string;\n /**\n * a string indicating the domain of the cookie (no default).\n */\n domain?: string;\n /**\n * a boolean indicating whether the cookie is only to be sent\n * over HTTPS (false by default for HTTP, true by default for HTTPS).\n */\n secure?: boolean;\n /**\n * a boolean indicating whether the cookie is only to be sent over HTTP(S),\n * and not made available to client JavaScript (true by default).\n */\n httpOnly?: boolean;\n /**\n * a boolean or string indicating whether the cookie is a \"same site\" cookie (false by default).\n * This can be set to 'strict', 'lax', or true (which maps to 'strict').\n */\n sameSite?: 'strict' | 'lax' | 'none';\n}\n\nexport type CookieJar = Record<string, CookieData>;\n\nconst COOKIE_SIGNING_INFO = 'shopify-app-js/cookie-signing/v1';\n\nasync function createCookieSignature(\n key: string,\n value: string,\n): Promise<string> {\n const cookieSigningKey = await deriveSHA256HMACKey(key, COOKIE_SIGNING_INFO);\n return createSHA256HMAC(cookieSigningKey, value);\n}\n\nconst signatureEncoder = new TextEncoder();\n\nfunction safelyCompareSignatures(signatureA: string, signatureB: string) {\n const buffA = signatureEncoder.encode(signatureA);\n const buffB = signatureEncoder.encode(signatureB);\n\n if (buffA.length !== buffB.length) return false;\n\n let out = 0;\n for (let i = 0; i < buffA.length; i++) {\n out |= buffA[i] ^ buffB[i];\n }\n\n return out === 0;\n}\n\ninterface CookiesOptions {\n keys: string[];\n // Ignored. Only for type-compatibility with the node package for now.\n secure: boolean;\n}\nexport class Cookies {\n static parseCookies(hdrs: string[]): CookieJar {\n const entries = hdrs\n .filter((hdr) => hdr.trim().length > 0)\n .map((cookieDef) => {\n const [keyval, ...opts] = cookieDef.split(';');\n const [name, value] = splitN(keyval, '=', 2).map((value) =>\n value.trim(),\n );\n return [\n name,\n {\n name,\n value,\n ...Object.fromEntries(\n opts.map((opt) => {\n const [key, value] = splitN(opt, '=', 2).map((value) =>\n value.trim(),\n );\n // Flag attributes like HttpOnly have no value\n return [key, value ?? true];\n }),\n ),\n },\n ];\n });\n const jar = Object.fromEntries(entries) as CookieJar;\n for (const cookie of Object.values(jar)) {\n if (typeof cookie.expires === 'string') {\n cookie.expires = new Date(cookie.expires);\n }\n }\n return jar;\n }\n\n static encodeCookie(data: CookieData): string {\n let result = '';\n result += `${data.name}=${data.value};`;\n result += Object.entries(data)\n .filter(\n ([key, value]) =>\n !['name', 'value', 'expires'].includes(key) && value !== false,\n )\n // Boolean attributes are flags, so only write them when true\n .map(([key, value]) => (value === true ? key : `${key}=${value}`))\n .join('; ');\n if (data.expires) {\n result += ';';\n result += `expires=${data.expires.toUTCString()}`;\n }\n return result;\n }\n\n receivedCookieJar: CookieJar = {};\n outgoingCookieJar: CookieJar = {};\n private keys: string[] = [];\n\n constructor(\n request: NormalizedRequest,\n public response: NormalizedResponse,\n {keys = []}: Partial<CookiesOptions> = {},\n ) {\n if (keys) this.keys = keys;\n\n const cookieReqHdr = getHeader(request.headers, 'Cookie') ?? '';\n this.receivedCookieJar = Cookies.parseCookies(cookieReqHdr.split(';'));\n const cookieResHdr = getHeaders(response.headers, 'Set-Cookie') ?? [];\n this.outgoingCookieJar = Cookies.parseCookies(cookieResHdr);\n }\n\n toHeaders(): string[] {\n return Object.values(this.outgoingCookieJar).map((cookie) =>\n Cookies.encodeCookie(cookie),\n );\n }\n\n updateHeader() {\n if (!this.response.headers) {\n this.response.headers = {};\n }\n removeHeader(this.response.headers, 'Set-Cookie');\n this.toHeaders().map((hdr) =>\n addHeader(this.response.headers!, 'Set-Cookie', hdr),\n );\n }\n\n get(name: string): string | undefined {\n return this.receivedCookieJar[name]?.value;\n }\n\n deleteCookie(name: string) {\n this.set(name, '', {\n path: '/',\n expires: new Date(0),\n });\n }\n\n async getAndVerify(name: string): Promise<string | undefined> {\n const value = this.get(name);\n if (!value) return undefined;\n if (!(await this.isSignedCookieValid(name))) {\n return undefined;\n }\n return value;\n }\n\n private get canSign() {\n return this.keys?.length > 0;\n }\n\n set(name: string, value: string, opts: Partial<CookieData> = {}): void {\n this.outgoingCookieJar[name] = {\n httpOnly: true,\n ...opts,\n name,\n value,\n };\n this.updateHeader();\n }\n\n async setAndSign(\n name: string,\n value: string,\n opts: Partial<CookieData> = {},\n ): Promise<void> {\n if (!this.canSign) {\n throw Error('No keys provided for signing.');\n }\n this.set(name, value, opts);\n const sigName = `${name}.sig`;\n const signature = await createCookieSignature(this.keys[0], value);\n this.set(sigName, signature, opts);\n this.updateHeader();\n }\n\n async isSignedCookieValid(cookieName: string): Promise<boolean> {\n const signedCookieName = `${cookieName}.sig`;\n if (\n !this.cookieExists(cookieName) ||\n !this.cookieExists(signedCookieName)\n ) {\n this.deleteInvalidCookies(cookieName, signedCookieName);\n return false;\n }\n const cookieValue = this.get(cookieName);\n const signature = this.get(signedCookieName);\n\n if (!cookieValue || !signature) {\n this.deleteInvalidCookies(cookieName, signedCookieName);\n return false;\n }\n\n const allCheckSignatures = await Promise.all(\n this.keys.map((key) => createCookieSignature(key, cookieValue)),\n );\n\n const validSignature = allCheckSignatures.some((checkSignature) =>\n safelyCompareSignatures(checkSignature, signature),\n );\n\n if (!validSignature) {\n this.deleteInvalidCookies(cookieName, signedCookieName);\n return false;\n }\n\n return true;\n }\n\n private cookieExists(cookieName: string) {\n return Boolean(this.get(cookieName));\n }\n\n private deleteInvalidCookies(...cookieNames: string[]): void {\n cookieNames.forEach((cookieName) => this.deleteCookie(cookieName));\n }\n}\n"],"names":[],"mappings":";;;;AAAA;AA+CA,MAAM,mBAAmB,GAAG,kCAAkC;AAE9D,eAAe,q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