UNPKG

eve-sso

Version:
95 lines (94 loc) 3.5 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); const node_fetch_1 = __importDefault(require("node-fetch")); const form_urlencoded_1 = __importDefault(require("form-urlencoded")); const jsonwebtoken_1 = __importDefault(require("jsonwebtoken")); const jwks_rsa_1 = __importDefault(require("jwks-rsa")); const { name, version, homepage } = require('../package'); const ENDPOINT = 'https://login.eveonline.com'; class SingleSignOn { clientId; callbackUri; endpoint; host; userAgent; #authorization; #jwks; constructor(clientId, secretKey, callbackUri, { endpoint, userAgent, } = {}) { this.clientId = clientId; this.callbackUri = callbackUri; this.#authorization = Buffer.from(`${clientId}:${secretKey}`).toString('base64'); this.endpoint = endpoint ?? ENDPOINT; this.host = new URL(this.endpoint).hostname; this.userAgent = userAgent ?? `${name}@${version} - nodejs@${process.version} - ${homepage}`; this.#jwks = (0, jwks_rsa_1.default)({ jwksUri: `${this.endpoint}/oauth/jwks`, requestHeaders: { 'User-Agent': this.userAgent } }); } getRedirectUrl(state, scopes) { let scope = ''; if (scopes) { if (Array.isArray(scopes)) { scope = scopes.join(' '); } else { scope = scopes; } } const search = new URLSearchParams({ response_type: 'code', redirect_uri: this.callbackUri, client_id: this.clientId, scope, state }); return `${this.endpoint}/v2/oauth/authorize?${search.toString()}`; } async getAccessToken(code, isRefreshToken = false) { const payload = !isRefreshToken ? { grant_type: 'authorization_code', code } : { grant_type: 'refresh_token', refresh_token: code, }; const response = await (0, node_fetch_1.default)(`${this.endpoint}/v2/oauth/token`, { method: 'POST', body: (0, form_urlencoded_1.default)(payload), headers: { Host: this.host, Authorization: `Basic ${this.#authorization}`, 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': this.userAgent, } }); if (!response.ok) { throw new Error(`Got status code ${response.status}`); } const data = await response.json(); data.decoded_access_token = await new Promise((resolve, reject) => { jsonwebtoken_1.default.verify(data.access_token, this.getKey.bind(this), { issuer: [this.endpoint, this.host] }, (err, decoded) => { if (err) return reject(err); resolve(decoded); }); }); return data; } getKey(header, callback) { this.#jwks.getSigningKey(header.kid, (err, key) => { if (err) return callback(err); callback(null, key.getPublicKey()); }); } } exports.default = SingleSignOn;