@agnostack/next-shopify 1.13.7-alpha.2 → 1.13.7-beta.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 (60) hide show
  1. package/CHANGELOG.md +36 -20
  2. package/dist/lib/handlers/api/graph.d.ts.map +1 -1
  3. package/dist/lib/handlers/api/graph.js +84 -79
  4. package/dist/lib/handlers/api/graph.js.map +1 -1
  5. package/dist/lib/handlers/api/proxy.d.ts.map +1 -1
  6. package/dist/lib/handlers/api/proxy.js +115 -161
  7. package/dist/lib/handlers/api/proxy.js.map +1 -1
  8. package/dist/lib/handlers/api/rest.d.ts.map +1 -1
  9. package/dist/lib/handlers/api/rest.js +70 -65
  10. package/dist/lib/handlers/api/rest.js.map +1 -1
  11. package/dist/lib/index.d.ts +1 -1
  12. package/dist/lib/index.d.ts.map +1 -1
  13. package/dist/lib/index.js +5 -4
  14. package/dist/lib/index.js.map +1 -1
  15. package/dist/lib/utils/headers.d.ts +1 -1
  16. package/dist/lib/utils/headers.js +2 -2
  17. package/dist/lib/utils/headers.js.map +1 -1
  18. package/dist/lib/utils/index.d.ts +1 -0
  19. package/dist/lib/utils/index.js +1 -0
  20. package/dist/lib/utils/index.js.map +1 -1
  21. package/dist/lib/utils/session.d.ts.map +1 -1
  22. package/dist/lib/utils/session.js +2 -2
  23. package/dist/lib/utils/session.js.map +1 -1
  24. package/dist/lib/utils/verification.d.ts +2 -0
  25. package/dist/lib/utils/verification.d.ts.map +1 -0
  26. package/dist/lib/utils/verification.js +69 -0
  27. package/dist/lib/utils/verification.js.map +1 -0
  28. package/dist/react/hooks/index.d.ts +2 -0
  29. package/dist/react/hooks/index.d.ts.map +1 -0
  30. package/dist/react/hooks/index.js +5 -0
  31. package/dist/react/hooks/index.js.map +1 -0
  32. package/dist/react/hooks/useVerification.d.ts +9 -0
  33. package/dist/react/hooks/useVerification.d.ts.map +1 -0
  34. package/dist/react/hooks/useVerification.js +63 -0
  35. package/dist/react/hooks/useVerification.js.map +1 -0
  36. package/dist/react/index.d.ts +2 -0
  37. package/dist/react/index.d.ts.map +1 -0
  38. package/dist/react/index.js +5 -0
  39. package/dist/react/index.js.map +1 -0
  40. package/dist/react/types.d.ts +1 -0
  41. package/dist/react/types.d.ts.map +1 -0
  42. package/dist/react/types.js +1 -0
  43. package/dist/react/types.js.map +1 -0
  44. package/dist/shared/datetime.d.ts +96 -0
  45. package/dist/shared/datetime.d.ts.map +1 -0
  46. package/dist/shared/datetime.js +285 -0
  47. package/dist/shared/datetime.js.map +1 -0
  48. package/dist/shared/display.d.ts +88 -23
  49. package/dist/shared/display.d.ts.map +1 -1
  50. package/dist/shared/display.js +409 -104
  51. package/dist/shared/display.js.map +1 -1
  52. package/dist/shared/index.d.ts +1 -0
  53. package/dist/shared/index.d.ts.map +1 -1
  54. package/dist/shared/index.js +1 -0
  55. package/dist/shared/index.js.map +1 -1
  56. package/dist/shared/shopify.d.ts +0 -6
  57. package/dist/shared/shopify.d.ts.map +1 -1
  58. package/dist/shared/shopify.js +1 -28
  59. package/dist/shared/shopify.js.map +1 -1
  60. package/package.json +6 -1
package/CHANGELOG.md CHANGED
@@ -1,16 +1,19 @@
1
- ## [1.13.7-alpha.2](https://github.com/agnostack/next-shopify/compare/v1.13.7-alpha.1...v1.13.7-alpha.2) (2023-12-01)
1
+ ## [1.13.7-beta.1](https://github.com/agnostack/next-shopify/compare/v1.13.6...v1.13.7-beta.1) (2023-12-01)
2
2
 
3
3
 
4
4
  ### Bug Fixes
5
5
 
6
- * wip ([6f3d3f5](https://github.com/agnostack/next-shopify/commit/6f3d3f515831fce0f30e6a34b3603ad89114ae38))
7
-
8
- ## [1.13.7-alpha.1](https://github.com/agnostack/next-shopify/compare/v1.13.6...v1.13.7-alpha.1) (2023-12-01)
9
-
10
-
11
- ### Bug Fixes
12
-
13
- * wip ([d3d121f](https://github.com/agnostack/next-shopify/commit/d3d121f402b46648cad0b1767a5ddd03de8d9dd7))
6
+ * added react export and useVerification ([7131369](https://github.com/agnostack/next-shopify/commit/71313698da5b30b94a0b28fa9a0d6e595e16c5bd))
7
+ * reverted pubblic-key vs api-key ([b3b40ac](https://github.com/agnostack/next-shopify/commit/b3b40ace673090d321635e011818ea130b7ddd3c))
8
+ * wip ([088e2f8](https://github.com/agnostack/next-shopify/commit/088e2f84ecb27dc435f1d9a7e1a53eb955fc6fd6))
9
+ * wip ([b0eb414](https://github.com/agnostack/next-shopify/commit/b0eb414b9a3c3d02aaef66b72569dba6c1bdccb0))
10
+ * wip ([cd8d260](https://github.com/agnostack/next-shopify/commit/cd8d260f40672cc066da5695c7a72a790f71d4a1))
11
+ * wip ([f8d453a](https://github.com/agnostack/next-shopify/commit/f8d453a850ead76d6d2c536fe1f8f472f380c1c6))
12
+ * wip ([82e20e8](https://github.com/agnostack/next-shopify/commit/82e20e8e9878ac7f9424ff990e8959c3cbe66e9d))
13
+ * wip ([ecd3625](https://github.com/agnostack/next-shopify/commit/ecd36257e4cde1bbdea48b895934e82ecedf0612))
14
+ * wip ([825f688](https://github.com/agnostack/next-shopify/commit/825f688f614be631c13a70e1c652c45f742408ed))
15
+ * wip ([a66af1e](https://github.com/agnostack/next-shopify/commit/a66af1e574e9e1cc08b2718c4a49f46caf42db9f))
16
+ * wip ([ab11674](https://github.com/agnostack/next-shopify/commit/ab116749073075133350e46d272b5475bb6e9d1b))
14
17
 
15
18
  ## [1.13.6](https://github.com/agnostack/next-shopify/compare/v1.13.5...v1.13.6) (2023-12-01)
16
19
 
@@ -18,12 +21,6 @@
18
21
  ### Bug Fixes
19
22
 
20
23
  * wip ([a0e6d9b](https://github.com/agnostack/next-shopify/commit/a0e6d9b293964314160a9eb8f13d7992c7116af8))
21
-
22
- ## [1.13.6-alpha.1](https://github.com/agnostack/next-shopify/compare/v1.13.5...v1.13.6-alpha.1) (2023-12-01)
23
-
24
-
25
- ### Bug Fixes
26
-
27
24
  * wip ([a0e6d9b](https://github.com/agnostack/next-shopify/commit/a0e6d9b293964314160a9eb8f13d7992c7116af8))
28
25
 
29
26
  ## [1.13.5](https://github.com/agnostack/next-shopify/compare/v1.13.4...v1.13.5) (2023-11-30)
@@ -31,21 +28,40 @@
31
28
 
32
29
  ### Bug Fixes
33
30
 
34
- * wip ([d0e3583](https://github.com/agnostack/next-shopify/commit/d0e35831a73f4c8ffc0a8f073a25bf37f6877502))
35
- * wip ([6bc1e78](https://github.com/agnostack/next-shopify/commit/6bc1e78c764fde2673669c80ad525f733f413d7f))
31
+ * added react export and useVerification ([7131369](https://github.com/agnostack/next-shopify/commit/71313698da5b30b94a0b28fa9a0d6e595e16c5bd))
32
+ * wip ([088e2f8](https://github.com/agnostack/next-shopify/commit/088e2f84ecb27dc435f1d9a7e1a53eb955fc6fd6))
33
+ * wip ([b0eb414](https://github.com/agnostack/next-shopify/commit/b0eb414b9a3c3d02aaef66b72569dba6c1bdccb0))
34
+ * wip ([cd8d260](https://github.com/agnostack/next-shopify/commit/cd8d260f40672cc066da5695c7a72a790f71d4a1))
35
+ * wip ([f8d453a](https://github.com/agnostack/next-shopify/commit/f8d453a850ead76d6d2c536fe1f8f472f380c1c6))
36
+ * wip ([82e20e8](https://github.com/agnostack/next-shopify/commit/82e20e8e9878ac7f9424ff990e8959c3cbe66e9d))
37
+ * wip ([ecd3625](https://github.com/agnostack/next-shopify/commit/ecd36257e4cde1bbdea48b895934e82ecedf0612))
38
+ * wip ([825f688](https://github.com/agnostack/next-shopify/commit/825f688f614be631c13a70e1c652c45f742408ed))
39
+ * wip ([a66af1e](https://github.com/agnostack/next-shopify/commit/a66af1e574e9e1cc08b2718c4a49f46caf42db9f))
40
+ * wip ([ab11674](https://github.com/agnostack/next-shopify/commit/ab116749073075133350e46d272b5475bb6e9d1b))
36
41
 
37
- ## [1.13.5-alpha.2](https://github.com/agnostack/next-shopify/compare/v1.13.5-alpha.1...v1.13.5-alpha.2) (2023-11-30)
42
+ ## [1.13.6-beta.1](https://github.com/agnostack/next-shopify/compare/v1.13.5-beta.7...v1.13.5-beta.8) (2023-11-30)
38
43
 
39
44
 
40
45
  ### Bug Fixes
41
46
 
42
- * wip ([d0e3583](https://github.com/agnostack/next-shopify/commit/d0e35831a73f4c8ffc0a8f073a25bf37f6877502))
47
+ * wip ([b0eb414](https://github.com/agnostack/next-shopify/commit/b0eb414b9a3c3d02aaef66b72569dba6c1bdccb0))
48
+ * wip ([cd8d260](https://github.com/agnostack/next-shopify/commit/cd8d260f40672cc066da5695c7a72a790f71d4a1))
49
+ * wip ([f8d453a](https://github.com/agnostack/next-shopify/commit/f8d453a850ead76d6d2c536fe1f8f472f380c1c6))
50
+ * wip ([82e20e8](https://github.com/agnostack/next-shopify/commit/82e20e8e9878ac7f9424ff990e8959c3cbe66e9d))
51
+ * wip ([ecd3625](https://github.com/agnostack/next-shopify/commit/ecd36257e4cde1bbdea48b895934e82ecedf0612))
52
+ * wip ([825f688](https://github.com/agnostack/next-shopify/commit/825f688f614be631c13a70e1c652c45f742408ed))
53
+ * wip ([a66af1e](https://github.com/agnostack/next-shopify/commit/a66af1e574e9e1cc08b2718c4a49f46caf42db9f))
54
+ * added react export and useVerification ([7131369](https://github.com/agnostack/next-shopify/commit/71313698da5b30b94a0b28fa9a0d6e595e16c5bd))
55
+ * wip ([ab11674](https://github.com/agnostack/next-shopify/commit/ab116749073075133350e46d272b5475bb6e9d1b))
43
56
 
44
- ## [1.13.5-alpha.1](https://github.com/agnostack/next-shopify/compare/v1.13.4...v1.13.5-alpha.1) (2023-11-30)
57
+ ## [1.13.5](https://github.com/agnostack/next-shopify/compare/v1.13.4...v1.13.5) (2023-11-30)
45
58
 
46
59
 
47
60
  ### Bug Fixes
48
61
 
62
+ * wip ([d0e3583](https://github.com/agnostack/next-shopify/commit/d0e35831a73f4c8ffc0a8f073a25bf37f6877502))
63
+ * wip ([6bc1e78](https://github.com/agnostack/next-shopify/commit/6bc1e78c764fde2673669c80ad525f733f413d7f))
64
+ * wip ([d0e3583](https://github.com/agnostack/next-shopify/commit/d0e35831a73f4c8ffc0a8f073a25bf37f6877502))
49
65
  * wip ([6bc1e78](https://github.com/agnostack/next-shopify/commit/6bc1e78c764fde2673669c80ad525f733f413d7f))
50
66
 
51
67
  ## [1.13.4](https://github.com/agnostack/next-shopify/compare/v1.13.3...v1.13.4) (2023-11-29)
@@ -1 +1 @@
1
- {"version":3,"file":"graph.d.ts","sourceRoot":"","sources":["../../../../src/lib/handlers/api/graph.js"],"names":[],"mappings":"AAkBO,yGA0GN"}
1
+ {"version":3,"file":"graph.d.ts","sourceRoot":"","sources":["../../../../src/lib/handlers/api/graph.js"],"names":[],"mappings":"AAmBO,yGAiHN"}
@@ -5,89 +5,94 @@ const tslib_1 = require("tslib");
5
5
  const shopify_api_1 = require("@shopify/shopify-api");
6
6
  const utils_1 = require("../../utils");
7
7
  const shared_1 = require("../../../shared");
8
- const handleGraph = (serverRuntimeConfig) => (req, res, params) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
9
- var _a, _b;
10
- const { body = '{}' } = req, _c = req.query, _d = _c === void 0 ? {} : _c, { shop, apiVersion } = _d, _query = tslib_1.__rest(_d, ["shop", "apiVersion"]);
11
- const _e = params !== null && params !== void 0 ? params : JSON.parse(body), { isOnline, query: graphQuery, variables: graphVariables, transform = (_data) => _data } = _e, graphParams = tslib_1.__rest(_e, ["isOnline", "query", "variables", "transform"]);
12
- let query = _query;
13
- if ((0, shared_1.isType)(query, 'string')) {
14
- query = (0, shared_1.querystringToObject)(query);
15
- }
16
- if ((0, shared_1.stringEmpty)(shop) || (0, shared_1.stringEmpty)(graphQuery)) {
17
- return res.status(400).json({ message: 'Invalid arguments' });
18
- }
19
- let statusCode;
20
- let response;
21
- let headers = {};
22
- let message = 'Error handling query call';
23
- try {
24
- const { getVerifiedClients } = yield (0, utils_1.getShopifyHelpers)(serverRuntimeConfig, { shop });
25
- const { Graphql } = yield getVerifiedClients({ req, res, shop, apiVersion, isOnline });
26
- response = yield Graphql.query(Object.assign(Object.assign({ data: graphVariables ? {
27
- query: graphQuery,
28
- variables: graphVariables,
29
- } : graphQuery }, (0, shared_1.objectNotEmpty)(query) && { query }), graphParams));
30
- statusCode = 200;
31
- }
32
- catch (error) {
33
- statusCode = 500;
34
- // TODO: clean up to share between rest and graph (pr at least keep in sync)
35
- switch (true) {
36
- case error instanceof shared_1.ShopifyAuthenticationError: {
37
- console.error(`${message}. Authentication Error.`, error);
38
- const errorResponse = (0, utils_1.getAuthErrorResponse)(serverRuntimeConfig, { error, shop });
39
- statusCode = errorResponse.statusCode;
40
- message = errorResponse.message;
41
- // HMMMM, should this be:
42
- // message = `${message}. Authentication Error - ${errroResponse.message}.`
43
- headers = errorResponse.headers;
44
- break;
45
- }
46
- case error instanceof shopify_api_1.BillingError: {
47
- // HMMMM, should this be:
48
- // message = `${message}. Billing Error - ${error.message}.`
49
- console.error(`${message}. Billing Error - ${error.message}.`, error.errorData);
50
- statusCode = 402;
51
- if (error === null || error === void 0 ? void 0 : error.message) {
52
- message = error.message;
8
+ const handleGraph = (serverRuntimeConfig) => {
9
+ const _getVerifiedBody = (0, utils_1.getVerifiedBody)(serverRuntimeConfig);
10
+ return (req, res, params) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
11
+ var _a, _b, _c;
12
+ const [requestBody, processResponse] = yield _getVerifiedBody(req, res);
13
+ const _d = (_a = req.query) !== null && _a !== void 0 ? _a : {}, { shop, apiVersion } = _d, _query = tslib_1.__rest(_d, ["shop", "apiVersion"]);
14
+ const _e = params !== null && params !== void 0 ? params : requestBody, { isOnline, query: graphQuery, variables: graphVariables, transform = (_data) => _data } = _e, graphParams = tslib_1.__rest(_e, ["isOnline", "query", "variables", "transform"]);
15
+ let query = _query;
16
+ if ((0, shared_1.isType)(query, 'string')) {
17
+ query = (0, shared_1.querystringToObject)(query);
18
+ }
19
+ if ((0, shared_1.stringEmpty)(shop) || (0, shared_1.stringEmpty)(graphQuery)) {
20
+ return res.status(400).json({ message: 'Invalid arguments' });
21
+ }
22
+ let statusCode;
23
+ let response;
24
+ let headers = {};
25
+ let message = 'Error handling query call';
26
+ try {
27
+ const { getVerifiedClients } = yield (0, utils_1.getShopifyHelpers)(serverRuntimeConfig, { shop });
28
+ const { Graphql } = yield getVerifiedClients({ req, res, shop, apiVersion, isOnline });
29
+ response = yield Graphql.query(Object.assign(Object.assign({ data: graphVariables ? {
30
+ query: graphQuery,
31
+ variables: graphVariables,
32
+ } : graphQuery }, (0, shared_1.objectNotEmpty)(query) && { query }), graphParams))
33
+ .then(processResponse);
34
+ statusCode = 200;
35
+ }
36
+ catch (error) {
37
+ statusCode = 500;
38
+ // TODO: clean up to share between rest and graph (pr at least keep in sync)
39
+ switch (true) {
40
+ case error instanceof shared_1.ShopifyAuthenticationError: {
41
+ console.error(`${message}. Authentication Error.`, error);
42
+ const errorResponse = (0, utils_1.getAuthErrorResponse)(serverRuntimeConfig, { error, shop });
43
+ statusCode = errorResponse.statusCode;
44
+ message = errorResponse.message;
45
+ // HMMMM, should this be:
46
+ // message = `${message}. Authentication Error - ${errroResponse.message}.`
47
+ headers = errorResponse.headers;
48
+ break;
49
+ }
50
+ case error instanceof shopify_api_1.BillingError: {
51
+ // HMMMM, should this be:
52
+ // message = `${message}. Billing Error - ${error.message}.`
53
+ console.error(`${message}. Billing Error - ${error.message}.`, error.errorData);
54
+ statusCode = 402;
55
+ if (error === null || error === void 0 ? void 0 : error.message) {
56
+ message = error.message;
57
+ }
58
+ break;
59
+ }
60
+ case error instanceof shopify_api_1.GraphqlQueryError: {
61
+ const errorMessages = (0, shared_1.ensureArray)((_b = error.response) === null || _b === void 0 ? void 0 : _b.errors).map(({ message }) => (0, shared_1.ensureString)(message));
62
+ console.error(`${message}. ${errorMessages.join('. ')}.`);
63
+ // HMMMM, should this be:
64
+ // message = `${message}. ${errorMessages.join('. ')}.`
65
+ // TODO: why are these not sending back different error codes?
66
+ break;
67
+ }
68
+ default: {
69
+ console.error(`${message}. HandleGraph Error - ${error.message}.`);
70
+ break;
53
71
  }
54
- break;
55
- }
56
- case error instanceof shopify_api_1.GraphqlQueryError: {
57
- const errorMessages = (0, shared_1.ensureArray)((_a = error.response) === null || _a === void 0 ? void 0 : _a.errors).map(({ message }) => (0, shared_1.ensureString)(message));
58
- console.error(`${message}. ${errorMessages.join('. ')}.`);
59
- // HMMMM, should this be:
60
- // message = `${message}. ${errorMessages.join('. ')}.`
61
- // TODO: why are these not sending back different error codes?
62
- break;
63
72
  }
64
- default: {
65
- console.error(`${message}. HandleGraph Error - ${error.message}.`);
66
- break;
73
+ }
74
+ Object.entries(headers).forEach(([key, value]) => {
75
+ res.setHeader(key, value);
76
+ });
77
+ if (!(response === null || response === void 0 ? void 0 : response.body)) {
78
+ return res.status(statusCode).json({ message });
79
+ }
80
+ try {
81
+ const responseBody = (_c = response.body.data) !== null && _c !== void 0 ? _c : response.body;
82
+ const [_responseData] = Object.values((0, shared_1.ensureObject)(responseBody));
83
+ const _f = (0, shared_1.ensureObject)(_responseData), { userErrors } = _f, responseData = tslib_1.__rest(_f, ["userErrors"]);
84
+ if ((0, shared_1.arrayNotEmpty)(userErrors)) {
85
+ const errorMessages = (0, shared_1.ensureArray)(userErrors).map(({ message }) => (0, shared_1.ensureString)(message));
86
+ return res.status(500).json({ message: `${message}. ${errorMessages.join('. ')}.` });
67
87
  }
88
+ // NOTE: sending in both to transform in case someone needs the userErrors
89
+ return res.status(statusCode).json(transform(responseData, responseBody));
68
90
  }
69
- }
70
- Object.entries(headers).forEach(([key, value]) => {
71
- res.setHeader(key, value);
72
- });
73
- if (!(response === null || response === void 0 ? void 0 : response.body)) {
74
- return res.status(statusCode).json({ message });
75
- }
76
- try {
77
- const responseBody = (_b = response.body.data) !== null && _b !== void 0 ? _b : response.body;
78
- const [_responseData] = Object.values((0, shared_1.ensureObject)(responseBody));
79
- const _f = (0, shared_1.ensureObject)(_responseData), { userErrors } = _f, responseData = tslib_1.__rest(_f, ["userErrors"]);
80
- if ((0, shared_1.arrayNotEmpty)(userErrors)) {
81
- const errorMessages = (0, shared_1.ensureArray)(userErrors).map(({ message }) => (0, shared_1.ensureString)(message));
82
- return res.status(500).json({ message: `${message}. ${errorMessages.join('. ')}.` });
91
+ catch (error) {
92
+ console.error(`${message}. Transformation Error.`, error);
93
+ return res.status(500).json({ message });
83
94
  }
84
- // NOTE: sending in both to transform in case someone needs the userErrors
85
- return res.status(statusCode).json(transform(responseData, responseBody));
86
- }
87
- catch (error) {
88
- console.error(`${message}. Transformation Error.`, error);
89
- return res.status(500).json({ message });
90
- }
91
- });
95
+ });
96
+ };
92
97
  exports.handleGraph = handleGraph;
93
98
  //# sourceMappingURL=graph.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"graph.js","sourceRoot":"","sources":["../../../../src/lib/handlers/api/graph.js"],"names":[],"mappings":";;;;AAAA,sDAAsE;AAEtE,uCAGoB;AACpB,4CAUwB;AAEjB,MAAM,WAAW,GAAG,CAAC,mBAAmB,EAAE,EAAE,CAAC,CAAO,GAAG,EAAE,GAAG,EAAE,MAAM,EAAE,EAAE;;IAC7E,MAAM,EAAE,IAAI,GAAG,IAAI,KAAkD,GAAG,EAAnD,KAAgD,GAAG,MAAR,EAA3C,qBAAyC,EAAE,KAAA,EAA3C,EAAS,IAAI,EAAE,UAAU,OAAkB,EAAb,MAAM,sBAA7B,sBAA+B,CAAa,CAAA;IACxE,MAAM,KAMF,MAAM,aAAN,MAAM,cAAN,MAAM,GAAI,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,EANxB,EACJ,QAAQ,EACR,KAAK,EAAE,UAAU,EACjB,SAAS,EAAE,cAAc,EACzB,SAAS,GAAG,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,OAEA,EADzB,WAAW,sBALV,+CAML,CAA6B,CAAA;IAE9B,IAAI,KAAK,GAAG,MAAM,CAAA;IAClB,IAAI,IAAA,eAAM,EAAC,KAAK,EAAE,QAAQ,CAAC,EAAE;QAC3B,KAAK,GAAG,IAAA,4BAAmB,EAAC,KAAK,CAAC,CAAA;KACnC;IAED,IAAI,IAAA,oBAAW,EA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AAI,mCAAI,QAAQ,CAAC,IAAI,CAAA;YAExD,MAAM,CAAC,aAAa,CAAC,GAAG,MAAM,CAAC,MAAM,CAAC,IAAA,qBAAY,EAAC,YAAY,CAAC,CAAC,CAAA;YACjE,MAAM,KAAkC,IAAA,qBAAY,EAAC,aAAa,CAAC,EAA7D,EAAE,UAAU,OAAiD,EAA5C,YAAY,sBAA7B,cAA+B,CAA8B,CAAA;YAEnE,IAAI,IAAA,sBAAa,EAAC,UAAU,CAAC,EAAE;gBAC7B,MAAM,aAAa,GAAG,IAAA,oBAAW,EAAC,UAAU,CAAC,CAAC,GAAG,CAAC,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE,CAAC,IAAA,qBAAY,EAAC,OAAO,CAAC,CAAC,CAAA;gBACzF,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,GAAG,OAAO,KAAK,aAAa,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,CAAC,CAAA;aACrF;YAED,0EAA0E;YAC1E,OAAO,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,YAAY,EAAE,YAAY,CAAC,CAAC,CAAA;SAC1E;QAAC,OAAO,KAAK,EAAE;YACd,OAAO,CAAC,KAAK,CAAC,GAAG,OAAO,yBAAyB,EAAE,KAAK,CAAC,CAAA;YACzD,OAAO,GAAG,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,IAAI,CAAC,EAAE,OAAO,EAAE,CAAC,CAAA;SACzC;IACH,CAAC,CAAA,CAAA;AACH,CAAC,CAAA;AAjHY,QAAA,WAAW,eAiHvB"}
@@ -1 +1 @@
1
- {"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../../../../src/lib/handlers/api/proxy.js"],"names":[],"mappings":"AAsCO,sHAqQN"}
1
+ {"version":3,"file":"proxy.d.ts","sourceRoot":"","sources":["../../../../src/lib/handlers/api/proxy.js"],"names":[],"mappings":"AAmCO,sHAwLN"}
@@ -5,7 +5,6 @@ const tslib_1 = require("tslib");
5
5
  /* eslint-disable @typescript-eslint/no-unused-vars */
6
6
  const nextjs_cors_1 = tslib_1.__importDefault(require("nextjs-cors"));
7
7
  const http_proxy_1 = tslib_1.__importDefault(require("http-proxy"));
8
- const raw_body_1 = tslib_1.__importDefault(require("raw-body"));
9
8
  const node_http_proxy_json_1 = tslib_1.__importDefault(require("node-http-proxy-json"));
10
9
  const utils_1 = require("../../utils");
11
10
  const shared_1 = require("../../../shared");
@@ -14,176 +13,131 @@ const verifyAppProxySignature = (signature, verifiable, hmacSecret) => {
14
13
  const hmac = (0, utils_1.generateHMAC)((0, shared_1.objectToSortedString)(verifiable), hmacSecret);
15
14
  return (0, utils_1.compareHashes)(signature, hmac);
16
15
  };
17
- const handleProxy = (serverRuntimeConfig, config) => (req, res, params) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
18
- var _a, _b;
16
+ const handleProxy = (serverRuntimeConfig, config) => {
19
17
  const { generateReplacements } = config !== null && config !== void 0 ? config : {};
20
- const { keyPairs, API_PATHS, APP_CONFIG, APP_BASE_URL, TARGET_SAFELIST, ORIGIN_SAFELIST, } = serverRuntimeConfig;
21
- const _c = (_a = req.headers) !== null && _a !== void 0 ? _a : {}, { origin, 'x-forwarded-for': _forwardFor, 'x-forwarded-proto': _forwardProto, 'x-forwarded-host': forwardHost, 'x-proxy-origin': proxyOrigin } = _c, proxyableHeaders = tslib_1.__rest(_c, ["origin", 'x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host', 'x-proxy-origin']);
22
- const { 'x-public-key': apiKey, 'x-ephemeral-key': ephemeralPublicKey, 'x-authorization-timestamp': customAuthTimestamp, 'x-authorization': customAuth, 'x-extension-session': sessionToken, 'x-extension-point': extensionPoint, 'x-shop-domain': shopDomainHeader, 'x-shopify-shop-domain': shopifyShopDomainHeader, 'x-shopify-shop': shopHeader = shopifyShopDomainHeader !== null && shopifyShopDomainHeader !== void 0 ? shopifyShopDomainHeader : shopDomainHeader, 'x-shopify-app-id': shopifyAppId, 'x-app-id': appId = shopifyAppId,
23
- // 'x-shopify-app-installation-id': shopifyAppInstallationId,
24
- // 'x-app-installation-id': appInstallationId = shopifyAppInstallationId, // TODO: pass along installationId??
25
- // TODO: pass along providerSetId??
26
- } = proxyableHeaders;
27
- const verificationHeaders = {
28
- 'x-public-key': apiKey,
29
- 'x-ephemeral-key': ephemeralPublicKey,
30
- 'x-authorization-timestamp': customAuthTimestamp,
31
- 'x-authorization': customAuth,
32
- };
33
- let targetPath;
34
- try {
35
- const [authProtocol, authSignature] = (0, shared_1.ensureString)(customAuth).split(' ');
36
- const isVerifiable = (apiKey &&
37
- ephemeralPublicKey &&
38
- customAuthTimestamp &&
39
- authSignature &&
40
- (keyPairs === null || keyPairs === void 0 ? void 0 : keyPairs.shared) &&
41
- (authProtocol === 'HMAC-SHA256'));
42
- let verificationKeys;
43
- // NOTE raw request body is required for shopify's validation
44
- const _rawBody = yield (0, raw_body_1.default)(req);
45
- const rawBody = _rawBody.toString();
46
- const parsedBody = JSON.parse(rawBody || '{}'); // NOTE: parsedBody should be encrypted when isVerifiable
47
- let decryptedBody = parsedBody;
48
- // NOTE: GET requests are not always sending along origin
49
- if ((0, shared_1.stringEmpty)(origin)) {
50
- req.headers = Object.assign(Object.assign({}, req.headers), { origin: proxyOrigin || forwardHost });
51
- }
52
- const _d = (_b = req.query) !== null && _b !== void 0 ? _b : {}, { signature, proxyEncoded } = _d, verifiable = tslib_1.__rest(_d, ["signature", "proxyEncoded"]);
53
- const { shop: _shop, host, timestamp, path_prefix } = verifiable;
54
- const shop = _shop || shopHeader;
55
- yield (0, nextjs_cors_1.default)(req, res, {
56
- methods: ['PUT', 'PATCH', 'POST', 'DELETE'],
57
- origin: (origin, callback) => {
58
- const isSafelisted = (0, shared_1.matchHostname)(origin, [
59
- ...ORIGIN_SAFELIST,
60
- 'cdn.shopify.com' // NOTE: this is the domain for checkout UI extensions
61
- ]);
62
- if (isSafelisted) {
63
- return callback(null, true);
64
- }
65
- return callback(new Error('Invalid CORS origin'));
66
- },
67
- optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
68
- });
69
- const { target: targetParam } = params !== null && params !== void 0 ? params : {};
70
- // eslint-disable-next-line max-len
71
- const _targetUrl = ((0, shared_1.stringEmpty)(targetParam) || targetParam.startsWith('http')) ? targetParam : `${APP_BASE_URL}/${(0, shared_1.removeLeadingSlash)(targetParam)}`;
72
- const { origin: target, hostname, pathname, search } = (0, shared_1.stringNotEmpty)(_targetUrl) ? new URL(_targetUrl) : {};
73
- targetPath = [pathname, search].filter(shared_1.stringNotEmpty).join('');
74
- const safelistedTarget = (0, shared_1.matchHostname)(hostname, Object.assign({ [new URL(APP_BASE_URL).hostname]: {
75
- // HMMM: can we generate our own session token (or use the current one) so as to not have to tell handleGraph/Rest to behave as offline?
76
- // headers: {
77
- // Authorization: 'Bearer {{setting.zendesk.token}}',
78
- // },
79
- params: {
80
- shop,
81
- host,
82
- },
83
- } }, TARGET_SAFELIST));
84
- if ((0, shared_1.stringEmpty)(targetPath) || (safelistedTarget == undefined)) {
85
- return res.status(407).json({ message: 'Unproxyable target' });
86
- }
87
- if (!shop || !host || !extensionPoint || !signature || !proxyEncoded) {
88
- return res.status(400).json({ message: 'Invalid or missing headers', extensionPoint });
89
- }
90
- const isShopifyOriginOrRelative = (0, shared_1.stringNotEmpty)((0, shared_1.ensureString)(path_prefix).startsWith('http')
91
- ? (0, shared_1.sanitizeShop)(new URL(path_prefix).hostname)
92
- : path_prefix);
93
- // TODO: once Shopify fixes CORS issue when origin is cdn.shopify.com, update this!
94
- if (!verifyAppProxySignature(signature, verifiable, isShopifyOriginOrRelative ? APP_CONFIG.apiSecretKey : timestamp)) {
95
- return res.status(403).json({ message: 'Invalid signature' });
96
- }
97
- // TODO: clean up targetParam.startsWith??
98
- if (!targetParam.startsWith(API_PATHS[shared_1.API_ROUTE_NAMES.SESSION_TOKEN])) {
99
- const _getVerifiedSessionData = (0, utils_1.getVerifiedSessionData)(serverRuntimeConfig);
100
- if (!_getVerifiedSessionData(sessionToken, { shop, host }).catch((_error) => {
101
- if (_error instanceof shared_1.ShopifySessionInvalidError) {
102
- return res.status(403).json({ message: _error.message });
103
- }
104
- throw _error;
105
- })) {
106
- return res.status(403).json({ message: 'Unverified signature' });
18
+ const { API_PATHS, APP_CONFIG, APP_BASE_URL, TARGET_SAFELIST, ORIGIN_SAFELIST, } = serverRuntimeConfig;
19
+ const _getVerifiedBody = (0, utils_1.getVerifiedBody)(serverRuntimeConfig);
20
+ return (req, res, params) => tslib_1.__awaiter(void 0, void 0, void 0, function* () {
21
+ var _a, _b;
22
+ const _c = (_a = req.headers) !== null && _a !== void 0 ? _a : {}, { origin, 'x-forwarded-for': _forwardFor, 'x-forwarded-proto': _forwardProto, 'x-forwarded-host': forwardHost, 'x-proxy-origin': proxyOrigin } = _c, _headers = tslib_1.__rest(_c, ["origin", 'x-forwarded-for', 'x-forwarded-proto', 'x-forwarded-host', 'x-proxy-origin']);
23
+ const { 'x-extension-session': sessionToken, 'x-extension-point': extensionPoint, 'x-shop-domain': shopDomainHeader, 'x-shopify-shop-domain': shopifyShopDomainHeader, 'x-shopify-shop': shopHeader = shopifyShopDomainHeader !== null && shopifyShopDomainHeader !== void 0 ? shopifyShopDomainHeader : shopDomainHeader, 'x-shopify-app-id': shopifyAppId, 'x-app-id': appId = shopifyAppId,
24
+ // 'x-shopify-app-installation-id': shopifyAppInstallationId,
25
+ // 'x-app-installation-id': appInstallationId = shopifyAppInstallationId, // TODO: pass along installationId??
26
+ // TODO: pass along providerSetId???
27
+ } = _headers;
28
+ let targetPath;
29
+ try {
30
+ // NOTE: GET requests are not always sending along origin
31
+ if ((0, shared_1.stringEmpty)(origin)) {
32
+ req.headers = Object.assign(Object.assign({}, req.headers), { origin: proxyOrigin || forwardHost });
107
33
  }
108
- }
109
- const { headers: targetHeaders, params: targetParams } = (0, shared_1.ensureObject)(safelistedTarget);
110
- if ((0, shared_1.objectNotEmpty)(targetParams)) {
111
- targetPath = (0, shared_1.appendQuery)(targetPath, new URLSearchParams(targetParams).toString());
112
- }
113
- if (!apiKey || (apiKey !== keyPairs.shared.publicKey)) {
114
- return res.status(401).json({ message: 'Invalid or missing public key' });
115
- }
116
- // TEMP!!! remove isVerifiable check once webwidget moved to react
117
- if (isVerifiable) {
118
- if (!ephemeralPublicKey ||
119
- !customAuthTimestamp ||
120
- !authSignature ||
121
- (authProtocol !== 'HMAC-SHA256')) {
122
- return res.status(401).json({ message: 'Invalid or missing authorization' });
123
- }
124
- verificationKeys = yield shared_1.subtle.getVerificationKeys({
125
- publicKey: ephemeralPublicKey,
126
- privateKey: keyPairs.shared.privateKey,
34
+ const _d = (_b = req.query) !== null && _b !== void 0 ? _b : {}, { signature, proxyEncoded } = _d, verifiable = tslib_1.__rest(_d, ["signature", "proxyEncoded"]);
35
+ const { shop: _shop, host, timestamp, path_prefix } = verifiable;
36
+ const shop = _shop || shopHeader;
37
+ yield (0, nextjs_cors_1.default)(req, res, {
38
+ methods: ['PUT', 'PATCH', 'POST', 'DELETE'],
39
+ origin: (origin, callback) => {
40
+ const isSafelisted = (0, shared_1.matchHostname)(origin, [
41
+ ...ORIGIN_SAFELIST,
42
+ 'cdn.shopify.com' // NOTE: this is the domain for checkout UI extensions
43
+ ]);
44
+ if (isSafelisted) {
45
+ return callback(null, true);
46
+ }
47
+ return callback(new Error('Invalid CORS origin'));
48
+ },
49
+ optionsSuccessStatus: 200, // some legacy browsers (IE11, various SmartTVs) choke on 204
127
50
  });
128
- if (!verificationKeys) {
129
- return res.status(412).json({ message: 'Invalid or missing verification' });
51
+ const { target: targetParam } = params !== null && params !== void 0 ? params : {};
52
+ // eslint-disable-next-line max-len
53
+ const _targetUrl = ((0, shared_1.stringEmpty)(targetParam) || targetParam.startsWith('http')) ? targetParam : `${APP_BASE_URL}/${(0, shared_1.removeLeadingSlash)(targetParam)}`;
54
+ const { origin: target, hostname, pathname, search } = (0, shared_1.stringNotEmpty)(_targetUrl) ? new URL(_targetUrl) : {};
55
+ targetPath = [pathname, search].filter(shared_1.stringNotEmpty).join('');
56
+ const safelistedTarget = (0, shared_1.matchHostname)(hostname, Object.assign({ [new URL(APP_BASE_URL).hostname]: {
57
+ // HMMM: can we generate our own session token (or use the current one) so as to not have to tell handleGraph/Rest to behave as offline?
58
+ // headers: {
59
+ // Authorization: 'Bearer {{setting.zendesk.token}}',
60
+ // },
61
+ params: {
62
+ shop,
63
+ host,
64
+ },
65
+ } }, TARGET_SAFELIST));
66
+ if ((0, shared_1.stringEmpty)(targetPath) || (safelistedTarget == undefined)) {
67
+ return res.status(407).json({ message: 'Unproxyable target' });
130
68
  }
131
- const verificationPayload = (0, shared_1.objectToSortedString)(Object.assign({ method: (0, shared_1.getRequestMethod)(rawBody, req.method), timestamp: customAuthTimestamp, body: parsedBody }, (0, shared_1.normalizeURIParts)(targetPath)));
132
- const isValid = yield shared_1.subtle.verifyHMAC(verificationPayload, verificationKeys.derivedHMACKey, authSignature);
133
- if (!isValid) {
134
- return res.status(412).json({ message: 'Invalid or missing verification' });
69
+ if (!shop || !host || !extensionPoint || !signature || !proxyEncoded) {
70
+ return res.status(400).json({ message: 'Invalid or missing headers', extensionPoint });
135
71
  }
136
- if (rawBody) {
137
- const decryptedMessage = yield shared_1.subtle.decryptMessage(parsedBody, verificationKeys.derivedSecretKey);
138
- decryptedBody = JSON.parse(decryptedMessage !== null && decryptedMessage !== void 0 ? decryptedMessage : '{}');
72
+ const isShopifyOriginOrRelative = (0, shared_1.stringNotEmpty)((0, shared_1.ensureString)(path_prefix).startsWith('http')
73
+ ? (0, shared_1.sanitizeShop)(new URL(path_prefix).hostname)
74
+ : path_prefix);
75
+ // TODO: once Shopify fixes CORS issue when origin is cdn.shopify.com, update this!
76
+ if (!verifyAppProxySignature(signature, verifiable, isShopifyOriginOrRelative ? APP_CONFIG.apiSecretKey : timestamp)) {
77
+ return res.status(403).json({ message: 'Invalid signature' });
139
78
  }
140
- }
141
- const _prepareHeaders = (0, utils_1.prepareHeaders)(serverRuntimeConfig);
142
- const headers = yield _prepareHeaders({
143
- generateReplacements,
144
- shop,
145
- appId,
146
- headers: Object.assign(Object.assign(Object.assign({}, !isVerifiable && Object.assign({}, verificationHeaders)), proxyableHeaders), targetHeaders),
147
- });
148
- const proxy = http_proxy_1.default.createProxy();
149
- return new Promise((resolve, reject) => {
150
- req.url = targetPath;
151
- if (headers) {
152
- req.headers = headers;
153
- }
154
- proxy.on('proxyReq', (proxyReq, proxyReqRequest, proxyReqResponse, options) => {
155
- if ((0, shared_1.objectNotEmpty)(decryptedBody)) {
156
- const bodyData = JSON.stringify(decryptedBody);
157
- proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
158
- proxyReq.write(bodyData);
79
+ // TODO: clean up targetParam.startsWith??
80
+ if (!targetParam.startsWith(API_PATHS[shared_1.API_ROUTE_NAMES.SESSION_TOKEN])) {
81
+ const _getVerifiedSessionData = (0, utils_1.getVerifiedSessionData)(serverRuntimeConfig);
82
+ if (!_getVerifiedSessionData(sessionToken, { shop, host }).catch((_error) => {
83
+ if (_error instanceof shared_1.ShopifySessionInvalidError) {
84
+ return res.status(403).json({ message: _error.message });
85
+ }
86
+ throw _error;
87
+ })) {
88
+ return res.status(403).json({ message: 'Unverified signature' });
159
89
  }
90
+ }
91
+ const { headers: targetHeaders, params: targetParams } = (0, shared_1.ensureObject)(safelistedTarget);
92
+ if ((0, shared_1.objectNotEmpty)(targetParams)) {
93
+ targetPath = (0, shared_1.appendQuery)(targetPath, new URLSearchParams(targetParams).toString());
94
+ }
95
+ const [requestBody, processResponse] = yield _getVerifiedBody(req, res, targetPath);
96
+ console.log(`>>> > handleProxy > requestBody, processResponse:`, requestBody, processResponse);
97
+ const _prepareHeaders = (0, utils_1.prepareHeaders)(serverRuntimeConfig);
98
+ const headers = yield _prepareHeaders({
99
+ generateReplacements,
100
+ shop,
101
+ appId,
102
+ headers: Object.assign(Object.assign({}, _headers), targetHeaders),
160
103
  });
161
- proxy.on('proxyRes', function (proxyRes, proxyResRequest, proxyResResponse) {
162
- (0, node_http_proxy_json_1.default)(proxyResResponse, proxyRes, function (proxyResBody) {
163
- if (!proxyResBody || !isVerifiable || !verificationKeys) {
164
- return proxyResBody;
104
+ const proxy = http_proxy_1.default.createProxy();
105
+ return new Promise((resolve, reject) => {
106
+ req.url = targetPath;
107
+ if (headers) {
108
+ req.headers = headers;
109
+ }
110
+ proxy.on('proxyReq', (proxyReq, proxyReqRequest, proxyReqResponse, options) => {
111
+ if ((0, shared_1.objectNotEmpty)(requestBody)) {
112
+ const bodyData = JSON.stringify(requestBody);
113
+ proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
114
+ proxyReq.write(bodyData);
165
115
  }
166
- return shared_1.subtle.encryptMessage(JSON.stringify(proxyResBody), verificationKeys.derivedSecretKey);
116
+ });
117
+ proxy.on('proxyRes', function (proxyRes, proxyResRequest, proxyResResponse) {
118
+ (0, node_http_proxy_json_1.default)(proxyResResponse, proxyRes, function (proxyResBody) {
119
+ return processResponse(proxyResBody);
120
+ });
121
+ });
122
+ proxy.once('error', (error) => {
123
+ console.error('Proxy error', error);
124
+ reject(error);
125
+ });
126
+ proxy.web(req, res, {
127
+ target,
128
+ timeout: PROXY_TIMEOUT,
129
+ proxyTimeout: PROXY_TIMEOUT,
130
+ followRedirects: false,
131
+ changeOrigin: true,
132
+ secure: true,
167
133
  });
168
134
  });
169
- proxy.once('error', (error) => {
170
- console.error('Proxy error', error);
171
- reject(error);
172
- });
173
- proxy.web(req, res, {
174
- target,
175
- timeout: PROXY_TIMEOUT,
176
- proxyTimeout: PROXY_TIMEOUT,
177
- followRedirects: false,
178
- changeOrigin: true,
179
- secure: true,
180
- });
181
- });
182
- }
183
- catch (error) {
184
- console.error(`Error handling proxy request for '${targetPath}'`, error);
185
- return res.status(200).json({ message: (error === null || error === void 0 ? void 0 : error.message) || 'Error handling proxy request', targetPath });
186
- }
187
- });
135
+ }
136
+ catch (error) {
137
+ console.error(`Error handling proxy request for '${targetPath}'`, error);
138
+ return res.status(200).json({ message: (error === null || error === void 0 ? void 0 : error.message) || 'Error handling proxy request', targetPath });
139
+ }
140
+ });
141
+ };
188
142
  exports.handleProxy = handleProxy;
189
143
  //# sourceMappingURL=proxy.js.map