index.js

"use strict";
/** @module OAuthServer **/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.TYPE = void 0;
var pkce_1 = require("./pkce");
Object.defineProperty(exports, "TYPE", { enumerable: true, get: function () { return pkce_1.TYPE; } });
var oauth2_server_1 = __importStar(require("oauth2-server"));
/**
 * @typedef {Function} ExpressMiddleware
 * @memberof module:OAuthServer
 *
 * @param {ExpressRequest} req The request object
 * @param {ExpressResponse} res The response object
 * @param {NextFunction} next The next function
 * The message of the error. (If the status is >= 500, the message will always be "Internal Server Error")
 * @return {Promise<void>}
 */
/**
 * @typedef {Object} ErrorObject
 * @memberof module:OAuthServer
 *
 * @property {number=} status The error's status code
 * @property {string=} message The error's message
 */
/**
 * @typedef {Function} CustomErrorResponse
 * @memberof module:OAuthServer
 *
 * @param {ExpressResponse} res The response object that you can use to send the response to the client.
 * @param {number} status The status of the error.
 * @param {string} message
 * The message of the error. (If the status is >= 500, the message will always be "Internal Server Error")
 * @param {ErrorObject} _error
 * If the status is >= 500, you can use the error object to check the Server Error
 * @return {void}
 */
/**
 * @typedef {Object} ContinueMiddleware Specify which action should be sent to responder.
 * @memberof module:OAuthServer
 *
 * @property {boolean=} token If true, at the end the action will be sent to the responder. (Default: false)
 * @property {boolean=} authorize If true, at the end the action will be sent to the responder. (Default: false)
 */
/**
 * @typedef {Object} OAuthServerOptions This class extends the ServerOptions class.
 * @memberof module:OAuthServer
 *
 * @property {ContinueMiddleware=} continueMiddleware
 * Specify which action should be sent to responder.
 * @property {ServerOptions.model} model The model for the oauth2server.
 * @property {number} accessTokenLifetime The expire time in seconds
 */
/**
 * @typedef {Object} AuthenticateOptions The OAuth2Server's AuthenticateOptions
 * @memberof module:OAuthServer
 *
 * @property {Array<string>=} scope
 * The scope(s) to authenticate.
 * @property {boolean=} addAcceptedScopesHeader
 * Set the X-Accepted-OAuth-Scopes HTTP header on response objects.
 * @property {boolean=} addAuthorizedScopesHeader
 * Set the X-OAuth-Scopes HTTP header on response objects.
 * @property {boolean=} allowBearerTokensInQueryString
 * Allow clients to pass bearer tokens in the query string of a request.
 */
/**
 * @typedef {Object} AuthorizeOptions The OAuth2Server's AuthorizeOptions
 * @memberof module:OAuthServer
 *
 * @property {{}=} authenticateHandler
 * The authenticate handler
 * @property {boolean=} allowEmptyState
 * Allow clients to specify an empty state
 * @property {number=} authorizationCodeLifetime
 * Lifetime of generated authorization codes in seconds (default = 5 minutes).
 */
/**
 * @typedef {Object} TokenOptions The OAuth2Server's TokenOptions
 * @memberof module:OAuthServer
 *
 * @property {number=} accessTokenLifetime
 * Lifetime of generated access tokens in seconds (default = 1 hour)
 * @property {number=} refreshTokenLifetime
 * Lifetime of generated refresh tokens in seconds (default = 2 weeks)
 * @property {boolean=} allowExtendedTokenAttributes
 * Allow extended attributes to be set on the returned token
 * @property {{}=} requireClientAuthentication
 * Require a client secret. Defaults to true for all grant types.
 * @property {boolean=} alwaysIssueNewRefreshToken
 * Always revoke the used refresh token and issue a new one for the refresh_token grant.
 * @property {Object.<string, AbstractGrantType>=} extendedGrantTypes
 * Additional supported grant types.
 */
/**
 * @class
 * @classdesc
 * The OAuthServer class. This wrapper also implements the PKCE support,
 * to use it, check the interface [AuthorizationCode]{@link AuthorizationCode}
 * @param {OAuthServerOptions} options
 * @param {CustomErrorResponse=} customErrorResponse
 * If you want to handle the errors for yourself, use this function
 * @memberof module:OAuthServer
 */
var OAuthServer = /** @class */ (function () {
    // eslint-disable-next-line require-jsdoc
    function OAuthServer(options, customErrorResponse) {
        if (!(options === null || options === void 0 ? void 0 : options.model)) {
            throw new oauth2_server_1.InvalidArgumentError('Missing parameter: "model"');
        }
        var continueMiddleware = options.continueMiddleware, opts = __rest(options, ["continueMiddleware"]);
        this.continueMiddleware = continueMiddleware
            ? {
                token: continueMiddleware.token,
                authorize: continueMiddleware.authorize
            }
            : undefined;
        this.server = new oauth2_server_1.default(opts);
        this.customErrorResponse = customErrorResponse;
    }
    /**
     *
     * @param {AuthorizeOptions=} options The OAuth2Server's AuthorizeOptions
     * @return {ExpressMiddleware}
     */
    OAuthServer.prototype.authorize = function (options) {
        var _this = this;
        return function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
            var request, response, code, error_1;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 2, , 3]);
                        request = new oauth2_server_1.Request(req);
                        response = new oauth2_server_1.Response(res);
                        return [4 /*yield*/, this.server.authorize(request, response, options)];
                    case 1:
                        code = _b.sent();
                        res.locals.oauth = { code: code };
                        if ((_a = this.continueMiddleware) === null || _a === void 0 ? void 0 : _a.authorize) {
                            return [2 /*return*/, next()];
                        }
                        this.handleExpressResponse(res, response);
                        return [3 /*break*/, 3];
                    case 2:
                        error_1 = _b.sent();
                        this.handleError(error_1, res);
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        }); };
    };
    /**
     *
     * @param {AuthenticateOptions=} options The OAuth2Server's AuthenticateOptions
     * @return {ExpressMiddleware}
     */
    OAuthServer.prototype.authenticate = function (options) {
        var _this = this;
        return function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
            var request, response, token, error_2;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        _a.trys.push([0, 2, , 3]);
                        request = new oauth2_server_1.Request(req);
                        response = new oauth2_server_1.Response(res);
                        return [4 /*yield*/, this.server.authenticate(request, response, options)];
                    case 1:
                        token = _a.sent();
                        res.locals.oauth = { token: token };
                        next();
                        return [3 /*break*/, 3];
                    case 2:
                        error_2 = _a.sent();
                        this.handleError(error_2, res);
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        }); };
    };
    /**
     *
     * @param {TokenOptions=} options The OAuth2Server's TokenOptions
     * @return {ExpressMiddleware}
     */
    OAuthServer.prototype.token = function (options) {
        var _this = this;
        return function (req, res, next) { return __awaiter(_this, void 0, void 0, function () {
            var request, response, token, error_3;
            var _a;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        _b.trys.push([0, 2, , 3]);
                        request = new oauth2_server_1.Request(req);
                        response = new oauth2_server_1.Response(res);
                        return [4 /*yield*/, this.server.token(request, response, options)];
                    case 1:
                        token = _b.sent();
                        res.locals.oauth = { token: token };
                        if ((_a = this.continueMiddleware) === null || _a === void 0 ? void 0 : _a.token) {
                            return [2 /*return*/, next()];
                        }
                        this.handleExpressResponse(res, response);
                        return [3 /*break*/, 3];
                    case 2:
                        error_3 = _b.sent();
                        this.handleError(error_3, res);
                        return [3 /*break*/, 3];
                    case 3: return [2 /*return*/];
                }
            });
        }); };
    };
    // eslint-disable-next-line require-jsdoc
    OAuthServer.prototype.handleExpressResponse = function (res, response) {
        var _a, _b;
        if (response.status === 302 && ((_a = response === null || response === void 0 ? void 0 : response.headers) === null || _a === void 0 ? void 0 : _a.location)) {
            var _c = response.headers, location_1 = _c.location, headers = __rest(_c, ["location"]);
            res.set(headers);
            res.redirect(location_1);
        }
        else {
            res.set(response.headers);
            res.status((_b = response === null || response === void 0 ? void 0 : response.status) !== null && _b !== void 0 ? _b : 200).send(response.body);
        }
    };
    // eslint-disable-next-line require-jsdoc
    OAuthServer.prototype.handleError = function (error, res) {
        var _a, _b;
        var errorNames = [
            'unsupported_response_type',
            'unsupported_grant_type',
            'unauthorized_request',
            'unauthorized_client',
            'insufficient_scope',
            'invalid_argument',
            'invalid_request',
            'invalid_client',
            'invalid_grant',
            'invalid_scope',
            'invalid_token',
            'access_denied',
            'server_error'
        ];
        var INTERNAL_MESSAGE = 'Internal Server Error';
        var INTERNAL_STATUS = 500;
        var message = INTERNAL_MESSAGE;
        var status = INTERNAL_STATUS;
        if (errorNames.includes(error === null || error === void 0 ? void 0 : error.name)) {
            message = (_a = error === null || error === void 0 ? void 0 : error.message) !== null && _a !== void 0 ? _a : message;
            status = (_b = error === null || error === void 0 ? void 0 : error.code) !== null && _b !== void 0 ? _b : status;
        }
        if (this.customErrorResponse) {
            return this.customErrorResponse(res, status >= 500 ? INTERNAL_STATUS : status, status >= 500 ? INTERNAL_MESSAGE : message, {
                status: error === null || error === void 0 ? void 0 : error.code,
                message: error === null || error === void 0 ? void 0 : error.message
            });
        }
        res.status(status >= 500 ? INTERNAL_STATUS : status).json({
            success: false,
            message: status >= 500 ? INTERNAL_MESSAGE : message
        });
    };
    return OAuthServer;
}());
exports.default = OAuthServer;
//# sourceMappingURL=index.js.map