Manage errors and translations in nodejs - node.js

My nodejs application uses a basic REST communication style to allow an HTML web ui to pass commands.
For instance:
http://address/api/config/cmd1
http://address/api/config/cmd2
http://address/api/network/cmd3
...
In return, my web ui gets a JSON result of the form:
{
"success": true
}
or
{
"success": false,
"errorMsg": "Wrong parameter blabla"
}
My problem is, I now need to translate error messages on client-side (in many languages), and the english "errorMsg" is too variadic and too long to be a translation key.
So I need something like an "errorCode" (an integer, probably) and I'm searching for a strategy into my nodejs application to manage error codes. I don't really know what is usually done for that, considering I usually use throw new Error("message") to return the message directly to the web ui.
I don't know if it's better to make a list of uniq error codes for all my REST API of a contextual error list for every subset of this API.
UPDATE: finally, I opted for a string error id. For instance, "wrong argument for this command" becomes "WrongArgument" and will be used to identify the error on GUI side and thus, perform the localization process. And finally, I don't need to make the error id uniq.

Using a custom Error class in the back-end with error identifier will allow the front-end to directly use its translation module, without modifications.
From your Server, one can process the standard error by creating a custom class, throw the class, catch it in your controller and send to the front-end the response with correct http status and error id.
The reasons are:
1 - Front-end code maintanability.
2 - Keeping errors systems data on back-end logs because they might be sensitive. It should not be return to the client side.
I agree with naming identifier code instead of using a code number. This because it s hard to pre-define a range for each error type (SQL, API, Authentication...). And it s harder when the error may be found in different service.
Scope: In the front-end service, i define a scope when calling the server, so that if there is need for a global error to be more specific, it is there. The scope is just a string with the name of the page where the ressources is used, also found in JSON lang files.
If 'ld like to check this code out and give comments, it will be great:
'https://codepen.io/Aymer-El/pen/OJoRVgZ'
Also leaving place for a debug message in the response may help front-end devs. Tho, this is optional.

Related

How to integrate twilio sms verification into my Node.js application

As I am integrating Twilio into my website. It is first of all not working. My code is this
and app crashes. my userController where I am implementing the code is here
I am not getting what I want. This is what I am getting on my front UI
You see the error because you didn't supply a to parameter. This probably happens when the first function argument of sendSms() is null or undefined.
You call sendSms(User.newphone) which is probably the mistake as you call the property of what I assume is a class but instead you should try sendSms(user.newphone) or sendSms(newphone).
Tip: Don't use the same variable name to avoid this in the future.

Authorize.net Error when adding new paymentProfile - code: E00114, Invalid OTS Token

we're trying to add a new customerPaymentProfile for an existing customerProfile. we're patterning our code on the github sample provided
https://github.com/AuthorizeNet/sample-code-node/blob/master/CustomerProfiles/create-customer-payment-profile.js
the only difference is that, we don't pass CC details to our servers. instead, we pass opaqueData from frontend. on Initial customerProfile creation(with a single payment profile) it works w/c is good. but if we try to add a new paymentProfile(using a new opaqueData) we get the error code: E00114, Invalid OTS Token.
the official documentation regarding error code doesn't say much
And it seems like there's a few different cases, where it throws this error code
Using Accept.js
https://community.developer.authorize.net/t5/Integration-and-Testing/E00114-Invalid-OTS-Token/td-p/58879
https://community.developer.authorize.net/t5/Integration-and-Testing/E00114-Invalid-OTS-Token/td-p/59314
Our Case(node.js SDK)
https://community.developer.authorize.net/t5/Integration-and-Testing/Error-while-adding-new-paymentProfile-quot-code-quot-quot-E00114/td-p/69872
Others
https://community.developer.authorize.net/t5/Integration-and-Testing/Intermittent-Invalid-OTS-Token-Errors-E00114/td-p/57509
https://community.developer.authorize.net/t5/Integration-and-Testing/E00114-Invalid-OTS-Token-error-generates-while-creating-ARB/td-p/68685
We also tried to delay the transaction at least 7 seconds, before using the opaqueData maybe to allow their systems to sync as suggested here to receive the same error message.
Anyone ever encountered something like this before?
Any form of help would be highly appreciated.
We were doing something wrong, by doing trial and error(via API) to determine if a customer exists or not. hence hitting api once or twice resulting to an invalid token (error on 2nd call)
So we tried to create a customerProfile, w/ customerPaymentProfile & this will throw error if customerProfile already exist(if its a duplicate email). Whats good here, is that customerProfileId comes with the error payload.
We though of using customerProfileId from error payload, to create a new payment profile for the customer, giving us some edge by reducing one DB call on our system.
The issue with our strategy though, is that opaqueData will expire, when we use it to create customerProfile(w/ payment profile) even though the request failed.
So resolution is to save customer info in our system, and check if it's a returning customer or not. If it is, then get customerProfileId from db, and create new customerPaymentProfile on authorize.net
One could also create customerProfile first, w/o the customerPaymentProfile. if this transaction fails, then at least you haven't used the opaqueData yet and you get the customerProfileId w/o doing any query on your db. So when you try to create a new customerPaymentProfile, you won't get error code E00114 since opaqueData isn't used yet.
lessons learned the hard way for us, but hopefully it helps someone.

Debugging Groovy in Jira Scriptrunner inline editor

I'm a programmer who is just getting started working with groovy in Jira in order to automate some tasks.
I'm trying to write a custom listener script using the inline editor in Jira, but haven't gotten past trying to get a Hello World program to work.
I don't know if the script is running, and can't see any output, and I really need some help with figuring out how to debug the script, preferably through outputs to some kind of console (or even just by reading the Jira logs if necessary), just so that I can actually start trying to learn how to use this tool.
I'm working with the information HERE as a general guideline to start learning to work with the inline editor.
For a little more context, you can see another related question that I asked HERE.
I've set the debug level to DEBUG for the event which I'm attaching the listener, as shown in this screenshot, based on the information found HERE:
Here is a screenshot of the inline editor I'm working in in JIRA. In this screenshot, I'm just trying to output 'Hello', and have just clicked the 'Preview' button:
As you can see, in the 'Result' tab at the bottom of the screen, there is nothing of interest. The 'Logs' tab is also empty, and the 'Timing' tab just says 'Elapsed: 0 ms CPU time: 0 ms', so it seems like nothing if happening.
If I check the log on the server (in the file catalina.2017-10-13.txt), I see the following output:
13-Oct-2017 07:01:50.942 WARNING [http-nio-8080-exec-6] com.sun.jersey.spi.container.servlet.WebComponent.filterFormParameters A servlet request, to the URI http://somevmserver:8080/rest/scriptrunner-jira/latest/listeners/com.onresolve.scriptrunner.canned.jira.workflow.listeners.CustomListener/params, contains form parameters in the request body but the request body has been consumed by the servlet or a servlet filter accessing the request parameters. Only resource methods using #FormParam will work as expected. Resource methods consuming the request body by other means will not work as expected.
13-Oct-2017 07:02:26.740 WARNING [http-nio-8080-exec-12] com.sun.jersey.spi.container.servlet.WebComponent.filterFormParameters A servlet request, to the URI http://somevmserver:8080/rest/scriptrunner/latest/canned/com.onresolve.scriptrunner.canned.common.StaticCompilationChecker, contains form parameters in the request body but the request body has been consumed by the servlet or a servlet filter accessing the request parameters. Only resource methods using #FormParam will work as expected. Resource methods consuming the request body by other means will not work as expected.
13-Oct-2017 07:02:26.974 WARNING [http-nio-8080-exec-1] com.sun.jersey.spi.container.servlet.WebComponent.filterFormParameters A servlet request, to the URI http://somevmserver:8080/rest/scriptrunner-jira/latest/listeners/com.onresolve.scriptrunner.canned.jira.workflow.listeners.CustomListener/preview, contains form parameters in the request body but the request body has been consumed by the servlet or a servlet filter accessing the request parameters. Only resource methods using #FormParam will work as expected. Resource methods consuming the request body by other means will not work as expected.
This output doesn't mean a whole lot to me, but it seems apparent that it's being populated as a result of trying to preview the script.
I'm not getting any errors in the inline editor, and it's really simple code, so I don't think it's that.
The only other information I can include that I think is pertinent is that this is a test instance of Jira cloned from our production environment, and its base URL is still set to the URL of the prod environment. Not sure if that has any bearing, but I'm not really a Jira admin, just the programmer tasked with doing this, so I don't want to go fiddling around where I don't need to.
Thanks!
When using scriptrunner within jira, you'll need to import the logger to use the debugger or to output to the console. This can be done with the following:
// Enable debugger
import org.apache.log4j.Logger
import org.apache.log4j.Level
def log = Logger.getLogger("com.acme.CreateSubtask")
log.setLevel(Level.DEBUG)
And then, you'll be able to see the logged information using log.debug "hello"
To see your debug message "Hello" in the log, you must update a issue in your selected project. The Result, Logs and Timing Tabs at the bottom are useless in this view. Just trigger the Listener with a issue update in your selected project and search your debug message in the atlassian-jira.log file.
Hint: To view the Log in the browser you can use this jira app https://marketplace.atlassian.com/plugins/com.cps.lastLog/server/overview

Application Insights response code 400 Bad request

when trying to call application insights api service with this url it gave me 400 Bad request
https://api.applicationinsights.io/beta/apps/appID/events/pageViews?timespan=P30D&$filter=contains(pageView/url,'valid-url')&$count=true
appID and valid-url is set correctly and i delete them in this question to make it more easy to read
Is there any issue in using $filter=contains ???
the easiest way to verify this stuff is to use the api explorer, and the demo app:
https://dev.applicationinsights.io/apiexplorer/events
this url shows that startswith works fine:
https://dev.applicationinsights.io/apiexplorer/events?appId=DEMO_APP&apiKey=DEMO_KEY&eventType=pageViews&timespan=P30D&$filter=startswith(pageView%2Furl%2C'http%3A%2F%2Faiconnect')
if you "need" something like contains, you can use $search (which looks across most fields, though, and has its own AND/OR text search logic)
https://dev.applicationinsights.io/apiexplorer/events?appId=DEMO_APP&apiKey=DEMO_KEY&eventType=pageViews&timespan=P30D&$search=%22Customers%2FCreate%22

Rails 4 path traversal possible?

The app I'm working on has a controller that issues templates to the front end (single page app). It's very basic, and simply consists of
#path = params[:path]
render template: "templates/#{#path}", layout: nil
Here my concern however is the direct use of the users input. Everything about this to me feels like it can be attacked with something as simple as path traversal. The route for this is
get "/templates/:path.html" => "templates#file", constraints: { path: /.+/ }, defaults: { format: 'html' }
I've tried multiple things to attempt a path traversal attack, such as
request /templates/path/to/../somewhere/else.html
request /templates?path=/path/to/../../something.rb
request /templates/index.html?path=/path/to/../../config/something.html
request /templates/path/../../../file.html
Fortunately, I haven't had any success with this. The requests that just start with /templates and don't specify anything after it, don't match the route thanks to the constraint so that is good.
It seems as though when that route is matched, rails doesn't allow you to override the path parameter through a url parameter, so I don't seem to be able to inject it there.
The ones that interest are the first and last examples above, where rails seems to internally be changing the requested URL before invoking the routes file. When I request /templates/path/to/../somewhere/else.html, my console output shows a request for /templates/path/somewhere/else.html. When I make a request for /templates/path/../../../file.html, the log shows a request for /file.html.
Am I missing something somewhere that will leave the app open to security issues, or is this just rails being sensible and protecting itself for me?
UPDATE
I've done some more digging, and if I try doing some URL encoding then I can cause the server to simply not respond at all. If I request /templates/%2e%2e%2f%2e%2e%2f%2e%2e%2ffresult.html then I just get an empty response with a connection: close header.
I assume that the parameter parser higher up in the rack is checking all urls for this type of attack? Regardless, my original question still stands. Am I missing something here?

Resources