telebit-relay.js/lib/extensions.js

155 lines
5.9 KiB
JavaScript
Raw Normal View History

2018-06-06 09:18:13 +00:00
/*
curl -s --user 'api:YOUR_API_KEY' \
https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages \
-F from='Excited User <mailgun@YOUR_DOMAIN_NAME>' \
-F to=YOU@YOUR_DOMAIN_NAME \
-F to=bar@example.com \
-F subject='Hello' \
-F text='Testing some Mailgun awesomeness!'
*/
2018-06-08 08:23:05 +00:00
var fs = require('fs');
2018-06-06 10:58:01 +00:00
var _auths = module.exports._auths = {};
2018-06-06 09:18:13 +00:00
module.exports.authenticate = function (opts) {
2018-06-06 10:58:01 +00:00
console.log("It's auth'n time!");
2018-06-06 09:18:13 +00:00
var util = require('util');
var requestAsync = util.promisify(require('request'));
var state = opts.state;
var jwtoken = opts.auth;
2018-06-06 10:58:01 +00:00
var auth;
2018-06-06 09:18:13 +00:00
var mailer = {
user: 'wizard@telebit.cloud'
, secret: 'fbbf21d73c9d2f480bd0e71f5f18494e'
};
var crypto = require('crypto');
2018-06-06 10:58:01 +00:00
console.log('[DEBUG] ext auth', jwtoken);
auth = jwtoken;
if ('object' === typeof auth && /^.+@.+\..+$/.test(auth.subject)) {
console.log('parsed');
var id = crypto.randomBytes(12).toString('hex');
//var id = crypto.randomBytes(16).toString('base64').replace(/\+/g,'-').replace(/\//g,'_').replace(/=/g,'');
2018-06-06 10:58:01 +00:00
console.log("[DEBUG] gonna send email");
return requestAsync({
url: 'https://api.mailgun.net/v3/telebit.cloud/messages'
, method: 'POST'
, auth: { user: 'api', pass: 'key-70ef48178081df19783ecfbe6fed5e9a' }
, formData: {
from: 'Telebit Wizard <wizard@telebit.cloud>'
, to: auth.subject
2018-06-08 08:23:05 +00:00
, subject: 'Confirm New Device Connection'
, text: "You tried connecting with '" + auth.hostname + "' for the first time. Confirm to continue connecting:\n"
+ '\n'
+ ' https://www.telebit.cloud/login/?magic=' + id + '\n'
+ '\n'
2018-06-06 10:58:01 +00:00
+ "(" + auth.os_arch + " " + auth.os_platform + " " + auth.os_release + ")\n"
2018-06-08 08:23:05 +00:00
+ '\n'
, html: "You tried connecting with '" + auth.hostname + "' for the first time. Confirm to continue connecting:<br>"
+ '<br>'
+ '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <a href="https://www.telebit.cloud/login/?magic=' + id + '">Confirm Device</a><br>'
2018-06-09 20:46:08 +00:00
+ '<br>'
+ '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; <small>or copy and paste this link:<br>https://www.telebit.cloud/login/?magic=' + id + '</small><br>'
2018-06-08 08:23:05 +00:00
+ '<br>'
+ "(" + auth.os_arch + " " + auth.os_platform + " " + auth.os_release + ")<br>"
+ '<br>'
2018-06-06 10:58:01 +00:00
}
}).then(function (resp) {
console.log("[DEBUG] email was sent, or so they say");
console.log(resp.body);
2018-06-08 08:23:05 +00:00
fs.writeFile(path.join(__dirname, 'emails', auth.subject), JSON.stringify(auth), function (err) {
if (err) {
console.error('[ERROR] in writing auth details');
console.error(err);
}
});
2018-06-06 10:58:01 +00:00
return new state.Promise(function (resolve, reject) {
// TODO use global interval whenever the number of active links is high
var t = setTimeout(function () {
console.log("[Magic Link] Timeout for '" + auth.subject + "'");
2018-06-06 10:58:01 +00:00
delete _auths[id];
var err = new Error("Login Failure: Magic Link was not clicked within 5 minutes");
err.code = 'E_LOGIN_TIMEOUT';
reject();
2018-06-09 20:46:08 +00:00
}, 2 * 60 * 60 * 1000);
2018-06-06 09:18:13 +00:00
2018-06-06 10:58:01 +00:00
function authorize() {
console.log("mighty auth'n ranger!");
clearTimeout(t);
delete _auths[id];
var hri = require('human-readable-ids').hri;
var hrname = hri.random() + '.telebit.cloud';
var jwt = require('jsonwebtoken');
var tokenData = {
domains: [ hrname ]
, ports: [ 1024 + Math.round(Math.random() * 6300) ]
, aud: 'telebit.cloud'
, iss: Math.round(Date.now() / 1000)
, id: id
, hostname: auth.hostname
2018-06-06 09:18:13 +00:00
};
2018-06-06 10:58:01 +00:00
tokenData.jwt = jwt.sign(tokenData, state.secret);
resolve(tokenData);
2018-06-08 08:25:06 +00:00
fs.writeFile(path.join(__dirname, 'emails', auth.subject + '.data'), JSON.stringify(tokenData), function (err) {
if (err) {
console.error('[ERROR] in writing token details');
console.error(err);
}
});
2018-06-06 10:58:01 +00:00
return tokenData;
}
_auths[id] = {
dt: Date.now()
, resolve: authorize
, reject: reject
};
2018-06-06 09:18:13 +00:00
});
2018-06-06 10:58:01 +00:00
});
2018-06-06 09:18:13 +00:00
}
2018-06-06 10:58:01 +00:00
console.log("just trying a normal token...");
2018-06-06 09:18:13 +00:00
try {
decoded = jwt.decode(jwtoken, { complete: true });
} catch(e) {
decoded = null;
}
return state.defaults.authenticate(opts.auth);
};
2018-06-07 05:26:15 +00:00
//var loaded = false;
var path = require('path');
2018-06-06 10:58:01 +00:00
var express = require('express');
var app = express();
2018-06-07 05:26:15 +00:00
app.use('/', express.static(path.join(__dirname, 'extensions/admin')));
2018-06-06 10:58:01 +00:00
app.use('/login', function (req, res) {
var tokenData;
var magic = req.query.magic;
if (_auths[magic]) {
tokenData = _auths[magic].resolve();
2018-06-08 08:23:05 +00:00
res.send('<!DOCTYPE html><html>'
+ '<head><meta http-equiv="refresh" content="5;url='
+ 'https://' + tokenData.domains.join(',') + '/?serviceport=' + tokenData.ports.join(',')
+ '" /></head>'
+ '<body>'
+ '<h1>Give us about 30 seconds...</h1>'
2018-06-09 20:46:08 +00:00
+ 'We\'re initializing our connection, redirecting you to your device at <a href="https://' + tokenData.domains[0] + '">'
2018-06-08 08:23:05 +00:00
+ tokenData.domains[0]
2018-06-09 20:46:08 +00:00
+ '</a>, which will then take a few seconds to initialize as it gets your https certificates for peer-to-peer, end-to-end encryption'
2018-06-08 08:23:05 +00:00
+ '<br>'
+ '<br>'
+ '<small><pre><code>' + JSON.stringify(tokenData, null, 2) + '</code></pre></small>'
+ '</body></html>'
);
2018-06-06 10:58:01 +00:00
} else {
res.send("<h1>Invalid Magic Link</h1>"
+ "<pre><code>'" + magic + "' isn't a valid link.\nLinks are only good for 5 minutes, so act fast.\n"
+ "(" + new Date(1000*((_auths[magic]||{}).dt||0)).toISOString() + ")</code></pre>\n"
);
}
});
module.exports.webadmin = function (state, req, res) {
2018-06-07 05:26:15 +00:00
//if (!loaded) { loaded = true; app.use('/', state.defaults.webadmin); }
2018-06-06 10:58:01 +00:00
console.log('[DEBUG] extensions webadmin');
app(req, res);
};