71 lines
2.6 KiB
JavaScript
71 lines
2.6 KiB
JavaScript
|
|
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
|
|
|
|
var crypto = _interopDefault(require('isomorphic-webcrypto'));
|
|
var algos = require('jose-algorithms');
|
|
var jwkLite = require('jwk-lite');
|
|
var b64uLite = require('b64u-lite');
|
|
var str2buf = require('str2buf');
|
|
|
|
function decode(token) {
|
|
if ( token === void 0 ) token = '';
|
|
|
|
var parts = token.split('.');
|
|
if (parts.length !== 3)
|
|
{ throw new Error('token must have 3 parts'); }
|
|
return {
|
|
header: JSON.parse(b64uLite.fromBase64Url(parts[0])),
|
|
payload: b64uLite.fromBase64Url(parts[1]),
|
|
signedContent: str2buf.toUint8Array(parts[0] + '.' + parts[1]),
|
|
signature: str2buf.toUint8Array(b64uLite.toBinaryString(parts[2]))
|
|
};
|
|
}
|
|
|
|
function sign(payload, key, header) {
|
|
if ( header === void 0 ) header = {};
|
|
|
|
var alg = header.alg;
|
|
return new Promise(function (resolve) {
|
|
header.alg = (alg = alg || key.alg);
|
|
if (!algos[alg])
|
|
{ throw new Error(("alg must be one of " + (Object.keys(algos)))); }
|
|
resolve(b64uLite.toBase64Url(JSON.stringify(header)) + '.' + b64uLite.toBase64Url(payload));
|
|
}).then(function (payloadString) {
|
|
var buffer = str2buf.toUint8Array(payloadString);
|
|
return jwkLite.importKey(key, {
|
|
alg: alg
|
|
}).then(function (signingKey) {
|
|
var algo = Object.assign({}, algos[alg]);
|
|
delete algo.namedCurve;
|
|
return crypto.subtle.sign(algo, signingKey, buffer);
|
|
}).then(function (signature) { return payloadString + '.' + b64uLite.fromBinaryString(str2buf.fromBuffer(signature)); });
|
|
});
|
|
}
|
|
|
|
function verify(token, key, ref) {
|
|
if ( ref === void 0 ) ref = {};
|
|
var algorithms = ref.algorithms;
|
|
|
|
algorithms = algorithms || Object.keys(algos);
|
|
return new Promise(function (resolve) {
|
|
resolve(decode(token));
|
|
}).then(function (jws) {
|
|
if (algorithms && !algorithms.includes(jws.header.alg))
|
|
{ throw new Error(("alg must be one of " + algorithms)); }
|
|
if (!algos[jws.header.alg])
|
|
{ throw new Error(("alg must be one of " + (Object.keys(algos)))); }
|
|
return jwkLite.importKey(key, {
|
|
alg: jws.header.alg
|
|
}).then(function (verifyingKey) { return crypto.subtle.verify(algos[jws.header.alg], verifyingKey, jws.signature, jws.signedContent); }).then(function (result) {
|
|
if (!result)
|
|
{ throw new Error('invalid token signature'); }
|
|
return jws.payload;
|
|
});
|
|
});
|
|
}
|
|
|
|
exports.decode = decode;
|
|
exports.sign = sign;
|
|
exports.verify = verify;
|
|
//# sourceMappingURL=jws-lite.js.map
|