'use strict'; var crypto = require('crypto'); var PromiseA = require('bluebird'); var OpErr = PromiseA.OperationalError; var makeB64UrlSafe = require('./common').makeB64UrlSafe; function retrieveOtp(codeStore, codeId) { return codeStore.get(codeId).then(function (code) { if (!code) { return null; } var expires = (new Date(code.expires)).valueOf(); if (!expires || Date.now() > expires) { return codeStore.destroy(codeId).then(function () { return null; }); } return code; }); } function validateOtp(codeStore, codeId, token) { if (!codeId) { return PromiseA.reject(new Error("Must provide authcode ID")); } if (!token) { return PromiseA.reject(new Error("Must provide authcode code")); } return codeStore.get(codeId).then(function (code) { if (!code) { throw new OpErr('authcode specified does not exist or has expired'); } return PromiseA.resolve().then(function () { var attemptsLeft = 3 - (code.attempts && code.attempts.length || 0); if (attemptsLeft <= 0) { throw new OpErr('you have tried to authorize this code too many times'); } if (code.code !== token) { throw new OpErr('you have entered the code incorrectly. '+attemptsLeft+' attempts remaining'); } // TODO: maybe impose a rate limit, although going fast doesn't help you break the // system when you can only try 3 times total. }).then(function () { return codeStore.destroy(codeId).then(function () { return code; }); }, function (err) { code.attempts = code.attempts || []; code.attempts.unshift(new Date()); return codeStore.upsert(codeId, code).then(function () { return PromiseA.reject(err); }, function () { return PromiseA.reject(err); }); }); }); } function getOrCreate(store, username) { return store.IssuerOauth3OrgAccounts.get(username).then(function (account) { if (account) { return account; } account = { username: username, accountId: makeB64UrlSafe(crypto.randomBytes(32).toString('base64')), }; return store.IssuerOauth3OrgAccounts.create(username, account).then(function () { // TODO: put sort sort of email notification to the server managers? return account; }); }); } function getPrivKey(store, experienceId) { return store.IssuerOauth3OrgPrivateKeys.get(experienceId).then(function (jwk) { if (jwk) { return jwk; } var keyPair = require('elliptic').ec('p256').genKeyPair(); jwk = { kty: 'EC', crv: 'P-256', alg: 'ES256', kid: experienceId, x: makeB64UrlSafe(keyPair.getPublic().getX().toArrayLike(Buffer).toString('base64')), y: makeB64UrlSafe(keyPair.getPublic().getY().toArrayLike(Buffer).toString('base64')), d: makeB64UrlSafe(keyPair.getPrivate().toArrayLike(Buffer).toString('base64')), }; return store.IssuerOauth3OrgPrivateKeys.upsert(experienceId, jwk).then(function () { return jwk; }); }); } function timespan(duration, max) { var timestamp = Math.floor(Date.now() / 1000); if (!duration) { return; } if (typeof duration === 'string') { duration = Math.floor(require('ms')(duration) / 1000) || 0; } if (typeof duration !== 'number') { return 0; } // Handle the case where the user gave us a timestamp instead of duration for the expiration. // Also make the maximum explicitly defined expiration as one year. if (duration > 31557600) { if (duration > timestamp) { return duration - timestamp; } else { return 31557600; } } if (max && timestamp+duration > max) { return max - timestamp; } return duration; } function createOtp(store, params) { return PromiseA.resolve().then(function () { if (!params || !params.username) { throw new OpErr("must provide the email address as 'username' in the body"); } if ((params.username_type && 'email' !== params.username_type) || !/@/.test(params.username)) { throw new OpErr("only email one-time login codes are supported at this time"); } params.username_type = 'email'; var codeStore = store.IssuerOauth3OrgCodes; var codeId = crypto.createHash('sha256').update(params.username_type+':'+params.username).digest('base64'); codeId = makeB64UrlSafe(codeId); return retrieveOtp(codeStore, codeId).then(function (code) { if (code) { return code; } var token = ''; while (!/^\d{4}-\d{4}-\d{4}$/.test(token)) { // Most of the number we can generate this was start with 1 (and no matter what can't // start with 0), so we don't use the very first digit. Also basically all of the // numbers are too big to accurately store in JS floats, so we limit the trailing 0's. token = (parseInt(crypto.randomBytes(8).toString('hex'), 16)).toString() .replace(/0+$/, '0').replace(/\d(\d{4})(\d{4})(\d{4}).*/, '$1-$2-$3'); } code = { id: codeId, code: token, expires: new Date(Date.now() + 20*60*1000), node: { type: params.username_type, node: params.username } }; return codeStore.upsert(codeId, code).then(function (){ return code; }); }); }); } function create(app) { var restful = {}; restful.sendOtp = function (req, res) { var params = req.body; var promise = req.getSiteStore().then(function (store) { return createOtp(store, params).then(function (code) { var emailParams = { to: params.username, from: 'login@daplie.com', replyTo: 'hello@daplie.com', subject: "Use " + code.code + " as your Login Code", text: "Your login code is:\n\n" + code.code + "\n\nThis email address was used to request to add your Hello ID to a device." + "\nIf you did not make the request you can safely ignore this message." }; emailParams['h:Reply-To'] = emailParams.replyTo; return req.getSiteCapability('email@daplie.com').then(function (mailer) { return mailer.sendMailAsync(emailParams).then(function () { return { code_id: code.id, expires: code.expires, created: new Date(parseInt(code.createdAt, 10) || code.createdAt), }; }); }); }); }); app.handlePromise(req, res, promise, '[issuer@oauth3.org] send one-time-password'); }; restful.createToken = function (req, res) { var store; var promise = req.getSiteStore().then(function (_store) { store = _store; if (!req.body || !req.body.grant_type) { throw new OpErr("missing 'grant_type' from the body"); } if (req.body.grant_type === 'password') { return restful.createToken.password(req); } if (req.body.grant_type === 'issuer_token') { return restful.createToken.issuerToken(req); } if (req.body.grant_type === 'refresh_token') { return restful.createToken.refreshToken(req); } throw new OpErr("unknown or un-implemented grant_type '"+req.body.grant_type+"'"); }).then(function (token_info) { token_info.iss = req.experienceId; if (!token_info.aud) { throw new OpErr("missing required token field 'aud'"); } if (!token_info.azp) { throw new OpErr("missing required token field 'azp'"); } if (token_info.iss === token_info.azp) { // We don't have normal grants for the issuer, so we don't need to look the // azpSub or the grants up in the database. token_info.azpSub = token_info.sub; token_info.scope = ''; return token_info; } var search = {}; ['sub', 'azp', 'azpSub'].forEach(function (key) { if (token_info[key]) { search[key] = token_info[key]; } }); return store.IssuerOauth3OrgGrants.find(search).then(function (grants) { if (!grants.length) { throw new OpErr("'"+token_info.azp+"' not given any grants from '"+(token_info.sub || token_info.azpSub)+"'"); } if (grants.length > 1) { throw new Error("unexpected resource collision: too many relevant grants"); } var grant = grants[0]; Object.keys(grant).forEach(function (key) { token_info[key] = grant[key]; }); return token_info; }); }).then(function (token_info) { return getPrivKey(store, req.experienceId).then(function (jwk) { var pem = require('jwk-to-pem')(jwk, { private: true }); var payload = { // standard iss: token_info.iss, // https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.1 aud: token_info.aud, // https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.3 azp: token_info.azp, sub: token_info.azpSub, // https://tools.ietf.org/html/draft-ietf-oauth-json-web-token-32#section-4.1.2 // extended scp: token_info.scope, }; var opts = { algorithm: jwk.alg, header: { kid: jwk.kid } }; var accessOpts = {}; // We set `expiresIn` like this to make it possible to send `null` and `exp` to have // no expiration while still having a default of 1 day. if (req.body.hasOwnProperty('exp')) { accessOpts.expiresIn = timespan(req.body.exp, token_info.exp); } else { accessOpts.expiresIn = timespan('1h', token_info.exp); } var refreshOpts = {}; refreshOpts.expiresIn = timespan(req.body.refresh_exp, token_info.exp); var jwt = require('jsonwebtoken'); var result = {}; result.scope = token_info.scope; result.access_token = jwt.sign(payload, pem, Object.assign(accessOpts, opts)); if (req.body.refresh_token) { if (token_info.refresh_token) { result.refresh_token = token_info.refresh_token; } else { result.refresh_token = jwt.sign(payload, pem, Object.assign(refreshOpts, opts)); } } return result; }); }); app.handlePromise(req, res, promise, '[issuer@oauth3.org] create tokens'); }; restful.createToken.password = function (req) { var params = req.body; if (!params || !params.username) { return PromiseA.reject(PromiseA.OperationalError("must provide the email address as 'username' in the body")); } if ((params.username_type && 'email' !== params.username_type) || !/@/.test(params.username)) { return PromiseA.reject(PromiseA.OperationalError("only email one-time login codes are supported at this time")); } params.username_type = 'email'; if (!params.password) { return PromiseA.reject(new OpErr("request missing 'password'")); } var codeId = crypto.createHash('sha256').update(params.username_type+':'+params.username).digest('base64'); codeId = makeB64UrlSafe(codeId); return req.getSiteStore().then(function (store) { return validateOtp(store.IssuerOauth3OrgCodes, codeId, params.password) .then(function () { return getOrCreate(store, params.username); }).then(function (account) { var contactClaimId = crypto.createHash('sha256').update(account.accountId+':'+params.username_type+':'+params.username).digest('base64'); return req.Models.IssuerOauth3OrgContactNodes.get(contactClaimId).then(function (contactClaim) { var now = Date.now(); if (!contactClaim) { contactClaim = { id: contactClaimId }; } if (!contactClaim.verifiedAt) { contactClaim.verifiedAt = now; } contactClaim.lastVerifiedAt = now; console.log('contactClaim'); console.log(contactClaim); return req.Models.IssuerOauth3OrgContactNodes.upsert(contactClaim).then(function () { return { sub: account.accountId, aud: req.params.aud || req.body.aud || req.experienceId, azp: req.params.azp || req.body.azp || req.body.client_id || req.body.client_uri || req.experienceId, }; }); }); }); }); }; restful.createToken.issuerToken = function (req) { return require('./common').checkIssuerToken(req, req.params.sub || req.body.sub).then(function (sub) { return { sub: sub, aud: req.params.aud || req.body.aud || req.experienceId, azp: req.params.azp || req.body.azp || req.body.client_id || req.body.client_uri, exp: req.oauth3.token.exp, }; }); }; restful.createToken.refreshToken = function (req) { return PromiseA.resolve().then(function () { if (!req.body.refresh_token) { throw new OpErr("missing refresh token"); } return req.oauth3.verifyAsync(req.body.refresh_token).then(function (token) { return { sub: token.sub, aud: token.aud, azp: token.azp, exp: token.exp, refresh_token: req.body.refresh_token, }; }); }); }; restful.getProfile = function (req, res) { var promise = req.Models.IssuerOauth3OrgAccounts.get(req.oauth3.accountIdx).then(function (result) { if (!result) { result = { id: undefined }; } result.id = undefined; return result; }); app.handlePromise(req, res, promise, '[issuer@oauth3.org] get profile'); }; restful.setProfile = function (req, res) { console.log('req.oauth3'); console.log(req.oauth3); var body = req.body; var promise = req.Models.IssuerOauth3OrgAccounts.find({ accountId: req.oauth3.ppid }).then(function (results) { var result = results[0]; var changed = false; console.log('get gotten'); console.log(results); if (!result) { throw new OpErr("account could not be found"); /*result = { accountId: req.oauth3.accountIdx, displayName: '', firstName: '', lastName: '', avatarUrl: '' };*/ } // TODO schema for validation [ 'firstName', 'lastName', 'avatarUrl', 'displayName' ].forEach(function (key) { if ('string' === typeof body[key] && -1 === [ 'null', 'undefined' ].indexOf(body[key])) { if (result[key] !== body[key]) { result[key] = body[key]; changed = true; } } }); if (changed) { return req.Models.IssuerOauth3OrgAccounts.upsert(result).then(function () { console.log('update updated'); return result; }); } return result; }).then(function (result) { result.id = undefined; }); app.handlePromise(req, res, promise, '[issuer@oauth3.org] set profile'); }; restful.listContactNodes = function (req, res) { }; restful.claimContact = function (req, res) { var type = req.body.type; var node = req.body.node; var promise = createOtp(req.Models, { username_type: type, username: node }).then(function (code) { var emailParams = { to: node, from: 'login@daplie.com', replyTo: 'hello@daplie.com', subject: "Verify your email address: " + code.code, text: "Your verification code is:\n\n" + code.code + "\n\nThis email address was requested to be used with Hello ID." + "\nIf you did not make the request you can safely ignore this message." }; emailParams['h:Reply-To'] = emailParams.replyTo; return req.getSiteCapability('email@daplie.com').then(function (mailer) { return mailer.sendMailAsync(emailParams).then(function () { return { code_id: code.id, expires: code.expires, created: new Date(parseInt(code.createdAt, 10) || code.createdAt), }; }); }); }); app.handlePromise(req, res, promise, '[issuer@oauth3.org] claim contact'); }; restful.verifyContact = function (req, res) { var codeId = req.params.id; var challenge = req.body.challenge || req.body.token || req.body.code; var store = req.Models; var promise = validateOtp(store.IssuerOauth3OrgCodes, codeId, challenge).then(function (code) { if (!code.node || !code.node.type || !code.node.node) { throw new OpErr("code didn't have contact node and type information"); } var contactClaimId = crypto.createHash('sha256').update(req.oauth3.accountIdx+':'+code.node.type+':'+code.node.node).digest('base64'); return req.Models.IssuerOauth3OrgContactNodes.get(contactClaimId).then(function (contactClaim) { var now = Date.now(); if (!contactClaim) { contactClaim = { id: contactClaimId }; } if (!contactClaim.verifiedAt) { contactClaim.verifiedAt = now; } contactClaim.lastVerifiedAt = now; return req.Models.IssuerOauth3OrgContactNodes.upsert(contactClaim).then(function () { return { success: true }; }); }); }); app.handlePromise(req, res, promise, '[issuer@oauth3.org] verify contact'); }; return { restful: restful, }; } module.exports.create = create;