Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

oauth2-pkce

Package Overview
Dependencies
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

oauth2-pkce - npm Package Compare versions

Comparing version 1.1.1 to 1.1.2

errors.d.ts

4

errors.js

@@ -54,6 +54,6 @@ export class ErrorOAuth2 {

};
export function toErrorObject(rawError) {
export const toErrorObject = (rawError) => {
const errorClass = RAW_ERROR_TO_ERROR_CLASS_MAP[rawError];
return errorClass ? new errorClass() : new ErrorUnknown(rawError);
}
};
export class ErrorWWWAuthenticate {

@@ -60,0 +60,0 @@ constructor() {

@@ -12,3 +12,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

const PKCE_CHARSET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~';
export function parseWwwAuthenticateHeader(header) {
export const parseWwwAuthenticateHeader = (header) => {
const headerMap = header

@@ -29,4 +29,4 @@ .slice('Bearer '.length)

};
}
function base64urlEncode(value) {
};
const base64urlEncode = (value) => {
let base64 = btoa(value);

@@ -37,4 +37,4 @@ base64 = base64.replace(/\+/g, '-');

return base64;
}
export function extractParamFromUrl(param, url) {
};
export const extractParamFromUrl = (param, url) => {
let queryString = url.split('?');

@@ -52,28 +52,25 @@ if (queryString.length < 2) {

}
}
export function objectToQueryString(dict) {
return Object.entries(dict).map(([key, val]) => `${key}=${encodeURIComponent(val)}`).join('&');
}
export function generatePKCECodeChallengeAndVerifier() {
return __awaiter(this, void 0, void 0, function* () {
const output = new Uint32Array(RECOMMENDED_CODE_VERIFIER_LENGTH);
crypto.getRandomValues(output);
const codeVerifier = base64urlEncode(Array
.from(output)
.map((num) => PKCE_CHARSET[num % PKCE_CHARSET.length])
.join(''));
const buffer = yield crypto
.subtle
.digest('SHA-256', (new TextEncoder()).encode(codeVerifier));
const hash = new Uint8Array(buffer);
let binary = '';
const hashLength = hash.byteLength;
for (let i = 0; i < hashLength; i++) {
binary += String.fromCharCode(hash[i]);
}
const codeChallenge = base64urlEncode(binary);
return { codeChallenge, codeVerifier };
});
}
export function generateRandomState(lengthOfState) {
return undefined;
};
export const objectToQueryString = (dict) => Object.entries(dict).map(([key, val]) => `${key}=${encodeURIComponent(val)}`).join('&');
export const generatePKCECodeChallengeAndVerifier = () => __awaiter(void 0, void 0, void 0, function* () {
const output = new Uint32Array(RECOMMENDED_CODE_VERIFIER_LENGTH);
crypto.getRandomValues(output);
const codeVerifier = base64urlEncode(Array
.from(output)
.map((num) => PKCE_CHARSET[num % PKCE_CHARSET.length])
.join(''));
const buffer = yield crypto
.subtle
.digest('SHA-256', (new TextEncoder()).encode(codeVerifier));
const hash = new Uint8Array(buffer);
let binary = '';
const hashLength = hash.byteLength;
for (let i = 0; i < hashLength; i++) {
binary += String.fromCharCode(hash[i]);
}
const codeChallenge = base64urlEncode(binary);
return { codeChallenge, codeVerifier };
});
export const generateRandomState = (lengthOfState) => {
const output = new Uint32Array(lengthOfState);

@@ -85,2 +82,2 @@ crypto.getRandomValues(output);

.join('');
}
};

@@ -89,3 +89,3 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

}
return { accessToken: accessToken, scopes, refreshToken };
return { accessToken, scopes, refreshToken };
});

@@ -114,2 +114,65 @@ }

}
makeRetryFetchFunction(fetchFunc) {
return (input, ...rest) => __awaiter(this, void 0, void 0, function* () {
const response = yield fetchFunc(input, ...rest);
if (response.status === 401) {
const authenticateHeader = response.headers.get(HEADER_WWW_AUTHENTICATE.toLowerCase());
if (authenticateHeader) {
const error = parseWwwAuthenticateHeader(authenticateHeader).error;
if (error === 'invalid_token') {
yield this.exchangeRefreshTokenForAccessToken();
input = yield this.requestInterceptor(input);
return fetchFunc(input, ...rest);
}
}
}
return response;
});
}
decorateFetchWithInterceptors(fetchFunc) {
return (input, ...rest) => __awaiter(this, void 0, void 0, function* () {
if (typeof input === 'string') {
input = new Request(input);
}
input = yield this.requestInterceptor(input);
const response = yield fetchFunc(input, ...rest);
return this.responseInterceptor(response);
});
}
requestInterceptor(request) {
return __awaiter(this, void 0, void 0, function* () {
const tokenContext = yield this.getAccessToken();
request.headers.set(HEADER_AUTHORIZATION, `Bearer ${tokenContext.accessToken}`);
return request;
});
}
responseInterceptor(response) {
return __awaiter(this, void 0, void 0, function* () {
if (response.status !== 401) {
return response;
}
const authenticateHeader = response.headers.get(HEADER_WWW_AUTHENTICATE.toLowerCase());
if (authenticateHeader) {
const error = parseWwwAuthenticateHeader(authenticateHeader).error;
if (error === 'invalid_grant' && this.config.onInvalidGrant) {
yield this.config.onInvalidGrant();
}
if (error === 'invalid_token' && this.config.onInvalidToken) {
yield this.config.onInvalidToken();
}
throw toErrorObject(error);
}
return response;
});
}
getGrantedScopes() {
return this.state.scopes;
}
isAuthorized() {
return !!this.state.accessToken;
}
isAccessTokenExpired() {
const { accessTokenExpiry } = this.state;
return Boolean(accessTokenExpiry && (new Date()) >= (new Date(accessTokenExpiry)));
}
fetchAccessTokenUsingCode() {

@@ -177,3 +240,3 @@ return __awaiter(this, void 0, void 0, function* () {

this.state.accessToken = accessToken;
this.state.accessTokenExpiry = (new Date(Date.now() + (parseInt(expiresIn) * 1000)))
this.state.accessTokenExpiry = (new Date(Date.now() + (parseInt(expiresIn, 10) * 1000)))
.toString();

@@ -189,65 +252,2 @@ if (refreshToken) {

}
makeRetryFetchFunction(fetchFunc) {
return (input, ...rest) => __awaiter(this, void 0, void 0, function* () {
const response = yield fetchFunc(input, ...rest);
if (response.status === 401) {
const authenticateHeader = response.headers.get(HEADER_WWW_AUTHENTICATE.toLowerCase());
if (authenticateHeader) {
const error = parseWwwAuthenticateHeader(authenticateHeader).error;
if (error === 'invalid_token') {
yield this.exchangeRefreshTokenForAccessToken();
input = yield this.requestInterceptor(input);
return fetchFunc(input, ...rest);
}
}
}
return response;
});
}
decorateFetchWithInterceptors(fetchFunc) {
return (input, ...rest) => __awaiter(this, void 0, void 0, function* () {
if (typeof input === 'string') {
input = new Request(input);
}
input = yield this.requestInterceptor(input);
const response = yield fetchFunc(input, ...rest);
return this.responseInterceptor(response);
});
}
requestInterceptor(request) {
return __awaiter(this, void 0, void 0, function* () {
const tokenContext = yield this.getAccessToken();
request.headers.set(HEADER_AUTHORIZATION, `Bearer ${tokenContext.accessToken}`);
return request;
});
}
responseInterceptor(response) {
return __awaiter(this, void 0, void 0, function* () {
if (response.status !== 401) {
return response;
}
const authenticateHeader = response.headers.get(HEADER_WWW_AUTHENTICATE.toLowerCase());
if (authenticateHeader) {
const error = parseWwwAuthenticateHeader(authenticateHeader).error;
if (error === 'invalid_grant' && this.config.onInvalidGrant) {
yield this.config.onInvalidGrant();
}
if (error === 'invalid_token' && this.config.onInvalidToken) {
yield this.config.onInvalidToken();
}
throw toErrorObject(error);
}
return response;
});
}
getGrantedScopes() {
return this.state.scopes;
}
isAuthorized() {
return !!this.state.accessToken;
}
isAccessTokenExpired() {
const { accessTokenExpiry } = this.state;
return Boolean(accessTokenExpiry && (new Date()) >= (new Date(accessTokenExpiry)));
}
recoverState() {

@@ -254,0 +254,0 @@ this.state = JSON.parse(localStorage.getItem(LOCALSTORAGE_STATE) || '{}');

@@ -7,4 +7,3 @@ (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.OAuth2Pkce = f()}})(function(){var define,module,exports;return (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){

});
exports.toErrorObject = toErrorObject;
exports.ErrorWWWAuthenticate = exports.RAW_ERROR_TO_ERROR_CLASS_MAP = exports.ErrorUnsupportedGrantType = exports.ErrorInvalidGrant = exports.ErrorInvalidClient = exports.ErrorAccessTokenResponse = exports.ErrorTemporarilyUnavailable = exports.ErrorServerError = exports.ErrorUnsupportedResponseType = exports.ErrorAccessDenied = exports.ErrorUnauthorizedClient = exports.ErrorAuthenticationGrant = exports.ErrorInvalidToken = exports.ErrorInvalidRequest = exports.ErrorInvalidScope = exports.ErrorInvalidReturnedStateParam = exports.ErrorNoAuthCode = exports.ErrorNoAccessToken = exports.ErrorUnknown = exports.ErrorOAuth2 = void 0;
exports.toErrorObject = exports.RAW_ERROR_TO_ERROR_CLASS_MAP = exports.ErrorWWWAuthenticate = exports.ErrorUnsupportedResponseType = exports.ErrorUnsupportedGrantType = exports.ErrorUnknown = exports.ErrorUnauthorizedClient = exports.ErrorTemporarilyUnavailable = exports.ErrorServerError = exports.ErrorOAuth2 = exports.ErrorNoAuthCode = exports.ErrorNoAccessToken = exports.ErrorInvalidToken = exports.ErrorInvalidScope = exports.ErrorInvalidReturnedStateParam = exports.ErrorInvalidRequest = exports.ErrorInvalidGrant = exports.ErrorInvalidClient = exports.ErrorAuthenticationGrant = exports.ErrorAccessTokenResponse = exports.ErrorAccessDenied = void 0;

@@ -103,7 +102,9 @@ class ErrorOAuth2 {}

function toErrorObject(rawError) {
const toErrorObject = rawError => {
const errorClass = RAW_ERROR_TO_ERROR_CLASS_MAP[rawError];
return errorClass ? new errorClass() : new ErrorUnknown(rawError);
}
};
exports.toErrorObject = toErrorObject;
class ErrorWWWAuthenticate {

@@ -125,8 +126,3 @@ constructor() {

});
exports.parseWwwAuthenticateHeader = parseWwwAuthenticateHeader;
exports.extractParamFromUrl = extractParamFromUrl;
exports.objectToQueryString = objectToQueryString;
exports.generatePKCECodeChallengeAndVerifier = generatePKCECodeChallengeAndVerifier;
exports.generateRandomState = generateRandomState;
exports.RECOMMENDED_CODE_VERIFIER_LENGTH = void 0;
exports.parseWwwAuthenticateHeader = exports.objectToQueryString = exports.generateRandomState = exports.generatePKCECodeChallengeAndVerifier = exports.extractParamFromUrl = exports.RECOMMENDED_CODE_VERIFIER_LENGTH = void 0;

@@ -169,3 +165,3 @@ var __awaiter = void 0 && (void 0).__awaiter || function (thisArg, _arguments, P, generator) {

function parseWwwAuthenticateHeader(header) {
const parseWwwAuthenticateHeader = header => {
const headerMap = header.slice('Bearer '.length).replace(/"/g, '').split(',').map(pair => {

@@ -183,5 +179,7 @@ const [key, value] = pair.trim().split('=');

};
}
};
function base64urlEncode(value) {
exports.parseWwwAuthenticateHeader = parseWwwAuthenticateHeader;
const base64urlEncode = value => {
let base64 = btoa(value);

@@ -192,5 +190,5 @@ base64 = base64.replace(/\+/g, '-');

return base64;
}
};
function extractParamFromUrl(param, url) {
const extractParamFromUrl = (param, url) => {
let queryString = url.split('?');

@@ -212,36 +210,42 @@

}
}
function objectToQueryString(dict) {
return Object.entries(dict).map(([key, val]) => `${key}=${encodeURIComponent(val)}`).join('&');
}
return undefined;
};
function generatePKCECodeChallengeAndVerifier() {
return __awaiter(this, void 0, void 0, function* () {
const output = new Uint32Array(RECOMMENDED_CODE_VERIFIER_LENGTH);
crypto.getRandomValues(output);
const codeVerifier = base64urlEncode(Array.from(output).map(num => PKCE_CHARSET[num % PKCE_CHARSET.length]).join(''));
const buffer = yield crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier));
const hash = new Uint8Array(buffer);
let binary = '';
const hashLength = hash.byteLength;
exports.extractParamFromUrl = extractParamFromUrl;
for (let i = 0; i < hashLength; i++) {
binary += String.fromCharCode(hash[i]);
}
const objectToQueryString = dict => Object.entries(dict).map(([key, val]) => `${key}=${encodeURIComponent(val)}`).join('&');
const codeChallenge = base64urlEncode(binary);
return {
codeChallenge,
codeVerifier
};
});
}
exports.objectToQueryString = objectToQueryString;
function generateRandomState(lengthOfState) {
const generatePKCECodeChallengeAndVerifier = () => __awaiter(void 0, void 0, void 0, function* () {
const output = new Uint32Array(RECOMMENDED_CODE_VERIFIER_LENGTH);
crypto.getRandomValues(output);
const codeVerifier = base64urlEncode(Array.from(output).map(num => PKCE_CHARSET[num % PKCE_CHARSET.length]).join(''));
const buffer = yield crypto.subtle.digest('SHA-256', new TextEncoder().encode(codeVerifier));
const hash = new Uint8Array(buffer);
let binary = '';
const hashLength = hash.byteLength;
for (let i = 0; i < hashLength; i++) {
binary += String.fromCharCode(hash[i]);
}
const codeChallenge = base64urlEncode(binary);
return {
codeChallenge,
codeVerifier
};
});
exports.generatePKCECodeChallengeAndVerifier = generatePKCECodeChallengeAndVerifier;
const generateRandomState = lengthOfState => {
const output = new Uint32Array(lengthOfState);
crypto.getRandomValues(output);
return Array.from(output).map(num => PKCE_CHARSET[num % PKCE_CHARSET.length]).join('');
}
};
exports.generateRandomState = generateRandomState;
},{}],3:[function(require,module,exports){

@@ -257,3 +261,3 @@ "use strict";

};
exports.OAuth2AuthCodePkceClient = exports.RECOMMENDED_STATE_LENGTH = void 0;
exports.RECOMMENDED_STATE_LENGTH = exports.OAuth2AuthCodePkceClient = void 0;

@@ -413,3 +417,3 @@ var _errors = require("./errors");

return {
accessToken: accessToken,
accessToken,
scopes,

@@ -446,2 +450,85 @@ refreshToken

makeRetryFetchFunction(fetchFunc) {
return (input, ...rest) => __awaiter(this, void 0, void 0, function* () {
const response = yield fetchFunc(input, ...rest);
if (response.status === 401) {
const authenticateHeader = response.headers.get(HEADER_WWW_AUTHENTICATE.toLowerCase());
if (authenticateHeader) {
const error = (0, _helpers.parseWwwAuthenticateHeader)(authenticateHeader).error;
if (error === 'invalid_token') {
yield this.exchangeRefreshTokenForAccessToken();
input = yield this.requestInterceptor(input);
return fetchFunc(input, ...rest);
}
}
}
return response;
});
}
decorateFetchWithInterceptors(fetchFunc) {
return (input, ...rest) => __awaiter(this, void 0, void 0, function* () {
if (typeof input === 'string') {
input = new Request(input);
}
input = yield this.requestInterceptor(input);
const response = yield fetchFunc(input, ...rest);
return this.responseInterceptor(response);
});
}
requestInterceptor(request) {
return __awaiter(this, void 0, void 0, function* () {
const tokenContext = yield this.getAccessToken();
request.headers.set(HEADER_AUTHORIZATION, `Bearer ${tokenContext.accessToken}`);
return request;
});
}
responseInterceptor(response) {
return __awaiter(this, void 0, void 0, function* () {
if (response.status !== 401) {
return response;
}
const authenticateHeader = response.headers.get(HEADER_WWW_AUTHENTICATE.toLowerCase());
if (authenticateHeader) {
const error = (0, _helpers.parseWwwAuthenticateHeader)(authenticateHeader).error;
if (error === 'invalid_grant' && this.config.onInvalidGrant) {
yield this.config.onInvalidGrant();
}
if (error === 'invalid_token' && this.config.onInvalidToken) {
yield this.config.onInvalidToken();
}
throw (0, _errors.toErrorObject)(error);
}
return response;
});
}
getGrantedScopes() {
return this.state.scopes;
}
isAuthorized() {
return !!this.state.accessToken;
}
isAccessTokenExpired() {
const {
accessTokenExpiry
} = this.state;
return Boolean(accessTokenExpiry && new Date() >= new Date(accessTokenExpiry));
}
fetchAccessTokenUsingCode() {

@@ -536,3 +623,3 @@ return __awaiter(this, void 0, void 0, function* () {

this.state.accessToken = accessToken;
this.state.accessTokenExpiry = new Date(Date.now() + parseInt(expiresIn) * 1000).toString();
this.state.accessTokenExpiry = new Date(Date.now() + parseInt(expiresIn, 10) * 1000).toString();

@@ -554,85 +641,2 @@ if (refreshToken) {

makeRetryFetchFunction(fetchFunc) {
return (input, ...rest) => __awaiter(this, void 0, void 0, function* () {
const response = yield fetchFunc(input, ...rest);
if (response.status === 401) {
const authenticateHeader = response.headers.get(HEADER_WWW_AUTHENTICATE.toLowerCase());
if (authenticateHeader) {
const error = (0, _helpers.parseWwwAuthenticateHeader)(authenticateHeader).error;
if (error === 'invalid_token') {
yield this.exchangeRefreshTokenForAccessToken();
input = yield this.requestInterceptor(input);
return fetchFunc(input, ...rest);
}
}
}
return response;
});
}
decorateFetchWithInterceptors(fetchFunc) {
return (input, ...rest) => __awaiter(this, void 0, void 0, function* () {
if (typeof input === 'string') {
input = new Request(input);
}
input = yield this.requestInterceptor(input);
const response = yield fetchFunc(input, ...rest);
return this.responseInterceptor(response);
});
}
requestInterceptor(request) {
return __awaiter(this, void 0, void 0, function* () {
const tokenContext = yield this.getAccessToken();
request.headers.set(HEADER_AUTHORIZATION, `Bearer ${tokenContext.accessToken}`);
return request;
});
}
responseInterceptor(response) {
return __awaiter(this, void 0, void 0, function* () {
if (response.status !== 401) {
return response;
}
const authenticateHeader = response.headers.get(HEADER_WWW_AUTHENTICATE.toLowerCase());
if (authenticateHeader) {
const error = (0, _helpers.parseWwwAuthenticateHeader)(authenticateHeader).error;
if (error === 'invalid_grant' && this.config.onInvalidGrant) {
yield this.config.onInvalidGrant();
}
if (error === 'invalid_token' && this.config.onInvalidToken) {
yield this.config.onInvalidToken();
}
throw (0, _errors.toErrorObject)(error);
}
return response;
});
}
getGrantedScopes() {
return this.state.scopes;
}
isAuthorized() {
return !!this.state.accessToken;
}
isAccessTokenExpired() {
const {
accessTokenExpiry
} = this.state;
return Boolean(accessTokenExpiry && new Date() >= new Date(accessTokenExpiry));
}
recoverState() {

@@ -639,0 +643,0 @@ this.state = JSON.parse(localStorage.getItem(LOCALSTORAGE_STATE) || '{}');

{
"name": "oauth2-pkce",
"version": "1.1.1",
"version": "1.1.2",
"description": "An OAuth 2.0 client library for the Authorization Code flow with PKCE",
"main": "index.js",
"types": "index.d.ts",
"files": ["*.js", "*.d.ts"],
"repository": {

@@ -21,3 +22,4 @@ "type": "git",

"oauth2",
"pkce"
"pkce",
"authorization grant"
],

@@ -24,0 +26,0 @@ "author": "Tim-Christian Mundt",

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc