demo key

node v10.23.0
version: 13.0.2
An endpoint that returns the active demo API key from the Ably homepage so that online coding tools can use the SDK with a zero setup. The demo key is restricted to message frequency and expires approximately every four hours. In addition to the API limitations the endpoint maintains a list of know hosts for added level of precaution.
var curl = require("curl")
Load the CURL library which allows us to GET the homepage, and mitigate CORS restrictions
// example: 1WChTA.PPl-SQ:am3EBXSy0NXQd9uc function matchApiKey(text) { const re = /[^\.]{6}\.[^\:]{6}:[^\"\'\s]{16}/; const array = `${text || ""}`.match(re) || [null]; return array[0]; }
matchApiKey() A helper function that will grab the demo API KEY, from the homepage content.
function allowOrigin (origin) { const text = `${origin}`.trim().toLowerCase(); const allowed = [ "localhost", "cdpn", "codepen", "fliptopbox", "ably", "codesandbox" ].join("|"); const re = new RegExp(`(${allowed})`, "i"); return re.test(text) ? text : null; }
allowOrigin() - a helper that validates the orign is known
exports.endpoint = function(request, response) { const { origin } = request.headers; const allow = allowOrigin(origin); if(!allow) return response.end(); const headers = { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': allow, 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS' }; curl.get("", {}, (e,a,html) => { const key = matchApiKey(html); let payload = { key, origin, ts: new Date().valueOf() }; payload = JSON.stringify(payload); response.writeHead(200, headers); response.end(payload); }); }
Export the endpoint that will use CURL to GET the homepage. The script plucks out the demo API key, sets the headers to allow "origins" that are contained list of known hosts, and responds to them with a JSON payload that contains the origin and the demo key.
Usage: To test this endpoint you need to open a console on a site in the `known` list, and use this console command
//> fetch("").then(s => s.json()).then(console.log)
The expexted reply for a know host:
//> {"key":"abcdef.ABCDEF:012345678abc", "origin":""}
... or CORS Access-Control-Allow-Origin error

no comments

    sign in to comment