Bridge to Ngrok tunnels
Recently I decided to use Ngrok while developing a new application locally. It consisted of a webhook which is meant to be called from the auth provider which in this case is Auth0. So to make the local server endpoint easily accessible to Auth0's servers, I used Ngrok. Ngrok is great but it's free version I found didn't make it possible to keep Auth0 pointed at the webhook without updating parts of code.
Auth0 Rules code which calls webhook via Ngrok |
Since it's the first time I've used it, along with the fact that I didn't use/need any other paid plan features, I wrote an NPM package for my need. The additional code via ngrok-dns plugs into the ngrok npm package which is officially supported by ngrok. Specifically ngrok-dns is provided to ngrok's onLogEvent option.
Code example using ngrok-dns vs without |
Per ngrok's options documentation, the onLogEvent option should be a function that returns stdout messages from the ngrok process.
onLogEvent: data => {}, // returns stdout messages from ngrok process
Thus ngrok-dns acts as middleware in that it performs actions with the ngrok process output (set's a Cloudflare DNS record using Cloudflare's API) while passing that output through to any other onLogEvent middleware that might be needed. Further if any errors happen, like missing API keys, ngrok-dns should not have any unwanted effects. The expected output looks like this...
The currently implemented DNS code was written using Cloudflare's REST API which is pretty straight forward. And although I first looked at the cloudflare npm package, I ran into some issues using it, and since I was only using a single endpoint, it was just as easy to use Axios to make the appropriate GET, PATCH, and POST calls and to handle authentication using user api tokens.
Three env vars are used to authenticate and determine which zone you want the TXT record to be added to.
CLOUDFLARE_TOKEN
CLOUDFLARE_ZONE_ID
TXT
If the dns TXT record doesn't exist for the zone, it will be created. If it does exist, it will be updated. In detail, the TXT record will be set with a name equal to the TXT
env var you set, and a value equal to the secure tunnel address that the ngrok binary spits out. So in our example as given herein the associated TXT record in cloudflare would be as is shown here in Cloudflare's dashboard:
Making out Auth0 code from the beginning work by resolving to the correct ngrok development tunnel. As well I can now call the static endpoint ngrok-project1.june07.com from any other remote locations as long as DNS resolution is possible.
Should be simple to add code for different DNS providers using their API's.
Hopefully I'm not the only one who has used ngrok and who would also like to have the added convenience the ngrok-dns npm package provides.