UNPKG

2.52 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.JWTService = exports.jsonwebtoken = void 0;
4const js_lib_1 = require("@naturalcycles/js-lib");
5const jsonwebtoken = require("jsonwebtoken");
6exports.jsonwebtoken = jsonwebtoken;
7const joi_shared_schemas_1 = require("../validation/joi/joi.shared.schemas");
8const joi_validation_util_1 = require("../validation/joi/joi.validation.util");
9// todo: define JWTError and list possible options
10/**
11 * Wraps popular `jsonwebtoken` library.
12 * You should create one instance of JWTService for each pair of private/public key.
13 *
14 * Generate key pair like this:
15 * openssl ecparam -name secp256k1 -genkey -noout -out key.pem
16 * openssl ec -in key.pem -pubout > key.pub.pem
17 */
18class JWTService {
19 constructor(cfg) {
20 this.cfg = cfg;
21 }
22 sign(payload, schema, opt = {}) {
23 (0, js_lib_1._assert)(this.cfg.privateKey, 'JWTService: privateKey is required to be able to verify, but not provided');
24 if (schema) {
25 (0, joi_validation_util_1.validate)(payload, schema);
26 }
27 return jsonwebtoken.sign(payload, this.cfg.privateKey, {
28 algorithm: this.cfg.algorithm,
29 noTimestamp: true,
30 ...this.cfg.signOptions,
31 ...opt,
32 });
33 }
34 verify(token, schema, opt = {}) {
35 (0, js_lib_1._assert)(this.cfg.publicKey, 'JWTService: publicKey is required to be able to verify, but not provided');
36 try {
37 const data = jsonwebtoken.verify(token, this.cfg.publicKey, {
38 algorithms: [this.cfg.algorithm],
39 ...this.cfg.verifyOptions,
40 ...opt,
41 });
42 if (schema) {
43 (0, joi_validation_util_1.validate)(data, schema);
44 }
45 return data;
46 }
47 catch (err) {
48 if (this.cfg.errorData) {
49 (0, js_lib_1._typeCast)(err);
50 (0, js_lib_1._errorDataAppend)(err, {
51 ...this.cfg.errorData,
52 });
53 }
54 throw err;
55 }
56 }
57 decode(token, schema) {
58 const data = jsonwebtoken.decode(token, {
59 complete: true,
60 });
61 (0, js_lib_1._assert)(data, 'invalid token, decoded value is null', {
62 ...this.cfg.errorData,
63 });
64 (0, joi_validation_util_1.validate)(data.payload, schema || joi_shared_schemas_1.anyObjectSchema);
65 return data;
66 }
67}
68exports.JWTService = JWTService;