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

@jmondi/oauth2-server

Package Overview
Dependencies
Maintainers
1
Versions
108
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@jmondi/oauth2-server - npm Package Compare versions

Comparing version 3.0.1-alpha.8 to 3.0.1-alpha.9

115

dist/express.js

@@ -0,1 +1,4 @@

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
// src/exceptions/oauth.exception.ts

@@ -9,3 +12,19 @@ var HttpStatus = {

};
var ErrorType;
(function(ErrorType2) {
ErrorType2["InvalidRequest"] = "invalid_request";
ErrorType2["InvalidClient"] = "invalid_client";
ErrorType2["InvalidGrant"] = "invalid_grant";
ErrorType2["InvalidScope"] = "invalid_scope";
ErrorType2["UnauthorizedClient"] = "unauthorized_client";
ErrorType2["UnsupportedGrantType"] = "unsupported_grant_type";
ErrorType2["AccessDenied"] = "access_denied";
ErrorType2["InternalServerError"] = "server_error";
})(ErrorType || (ErrorType = {}));
var OAuthException = class extends Error {
error;
errorType;
errorDescription;
errorUri;
status;
constructor(error, errorType, errorDescription, errorUri, status = HttpStatus.BAD_REQUEST) {

@@ -22,6 +41,6 @@ super(errorDescription ? `${error}: ${errorDescription}` : error);

/**
* The request is missing a parameter so the server can’t proceed with the request. This
* may also be returned if the request includes an unsupported parameter or repeats a
* parameter.
*/
* The request is missing a parameter so the server can’t proceed with the request. This
* may also be returned if the request includes an unsupported parameter or repeats a
* parameter.
*/
static invalidParameter(parameter, errorDescription) {

@@ -31,22 +50,16 @@ let message = "The request is missing a required parameter, includes an invalid parameter value, ";

errorDescription = errorDescription ? errorDescription : `Check the \`${parameter}\` parameter`;
return new OAuthException(message, "invalid_request" /* InvalidRequest */, errorDescription);
return new OAuthException(message, ErrorType.InvalidRequest, errorDescription);
}
/**
* Client authentication failed, such as if the request contains an invalid client ID or
* secret. Send an HTTP 401 response in this case.
*/
* Client authentication failed, such as if the request contains an invalid client ID or
* secret. Send an HTTP 401 response in this case.
*/
static invalidClient(errorDescription) {
return new OAuthException(
"Client authentication failed",
"invalid_client" /* InvalidClient */,
errorDescription,
void 0,
HttpStatus.UNAUTHORIZED
);
return new OAuthException("Client authentication failed", ErrorType.InvalidClient, errorDescription, void 0, HttpStatus.UNAUTHORIZED);
}
/**
* The authorization code (or user’s password for the password grant type) is invalid or
* expired. This is also the error you would return if the redirect URL given in the
* authorization grant does not match the URL provided in this access token request.
*/
* The authorization code (or user’s password for the password grant type) is invalid or
* expired. This is also the error you would return if the redirect URL given in the
* authorization grant does not match the URL provided in this access token request.
*/
static invalidGrant(errorDescription) {

@@ -56,8 +69,8 @@ let message = "The provided authorization grant (e.g., authorization_code, client_credentials) or refresh token ";

message += "request, or was issued to another client";
return new OAuthException(message, "invalid_grant" /* InvalidGrant */, errorDescription);
return new OAuthException(message, ErrorType.InvalidGrant, errorDescription);
}
/**
* For access token requests that include a scope (password or client_credentials grants),
* this error indicates an invalid scope value in the request.
*/
* For access token requests that include a scope (password or client_credentials grants),
* this error indicates an invalid scope value in the request.
*/
static invalidScope(scope, redirectUri) {

@@ -69,42 +82,31 @@ const message = "The requested scope is invalid, unknown, or malformed";

}
return new OAuthException(message, "invalid_scope" /* InvalidScope */, hint, redirectUri);
return new OAuthException(message, ErrorType.InvalidScope, hint, redirectUri);
}
/**
* This client is not authorized to use the requested grant type. For example, if you
* restrict which applications can use the Implicit grant, you would return this error
* for the other apps.
*/
* This client is not authorized to use the requested grant type. For example, if you
* restrict which applications can use the Implicit grant, you would return this error
* for the other apps.
*/
static unauthorizedClient() {
return new OAuthException(`unauthorized client`, "unauthorized_client" /* UnauthorizedClient */);
return new OAuthException(`unauthorized client`, ErrorType.UnauthorizedClient);
}
/**
* If a grant type is requested that the authorization server doesn’t recognize, use
* this code. Note that unknown grant types also use this specific error code
* rather than using the invalid_request above.
*/
* If a grant type is requested that the authorization server doesn’t recognize, use
* this code. Note that unknown grant types also use this specific error code
* rather than using the invalid_request above.
*/
static unsupportedGrantType() {
return new OAuthException("unsupported grant_type", "unsupported_grant_type" /* UnsupportedGrantType */);
return new OAuthException("unsupported grant_type", ErrorType.UnsupportedGrantType);
}
static badRequest(message) {
return new OAuthException(message, "invalid_request" /* InvalidRequest */, void 0, void 0, HttpStatus.BAD_REQUEST);
return new OAuthException(message, ErrorType.InvalidRequest, void 0, void 0, HttpStatus.BAD_REQUEST);
}
static accessDenied(errorDescription) {
return new OAuthException(
"The resource owner or authorization server denied the request",
"access_denied" /* AccessDenied */,
errorDescription,
void 0,
HttpStatus.UNAUTHORIZED
);
return new OAuthException("The resource owner or authorization server denied the request", ErrorType.AccessDenied, errorDescription, void 0, HttpStatus.UNAUTHORIZED);
}
static internalServerError(errorDescription) {
return new OAuthException(
"Internal server error",
"server_error" /* InternalServerError */,
errorDescription,
void 0,
HttpStatus.INTERNAL_SERVER_ERROR
);
return new OAuthException("Internal server error", ErrorType.InternalServerError, errorDescription, void 0, HttpStatus.INTERNAL_SERVER_ERROR);
}
};
__name(OAuthException, "OAuthException");

@@ -131,2 +133,3 @@ // src/requests/request.ts

};
__name(OAuthRequest, "OAuthRequest");

@@ -138,3 +141,5 @@ // src/responses/response.ts

headers = {};
constructor(responseOptions = { headers: {} }) {
constructor(responseOptions = {
headers: {}
}) {
this.headers = {

@@ -145,3 +150,6 @@ ...responseOptions.headers

get(field) {
console.log({ headers: this.headers, field });
console.log({
headers: this.headers,
field
});
return "";

@@ -153,2 +161,3 @@ }

};
__name(OAuthResponse, "OAuthResponse");

@@ -159,5 +168,7 @@ // src/adapters/express.ts

}
__name(responseFromExpress, "responseFromExpress");
function requestFromExpress(req) {
return new OAuthRequest(req);
}
__name(requestFromExpress, "requestFromExpress");
function handleExpressResponse(expressResponse, oauthResponse) {

@@ -174,2 +185,3 @@ if (oauthResponse.status === 302) {

}
__name(handleExpressResponse, "handleExpressResponse");
function handleExpressError(e, res) {

@@ -186,2 +198,3 @@ if (e instanceof OAuthException) {

}
__name(handleExpressError, "handleExpressError");
export {

@@ -188,0 +201,0 @@ handleExpressError,

@@ -0,1 +1,4 @@

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
// src/exceptions/oauth.exception.ts

@@ -9,3 +12,19 @@ var HttpStatus = {

};
var ErrorType;
(function(ErrorType2) {
ErrorType2["InvalidRequest"] = "invalid_request";
ErrorType2["InvalidClient"] = "invalid_client";
ErrorType2["InvalidGrant"] = "invalid_grant";
ErrorType2["InvalidScope"] = "invalid_scope";
ErrorType2["UnauthorizedClient"] = "unauthorized_client";
ErrorType2["UnsupportedGrantType"] = "unsupported_grant_type";
ErrorType2["AccessDenied"] = "access_denied";
ErrorType2["InternalServerError"] = "server_error";
})(ErrorType || (ErrorType = {}));
var OAuthException = class extends Error {
error;
errorType;
errorDescription;
errorUri;
status;
constructor(error, errorType, errorDescription, errorUri, status = HttpStatus.BAD_REQUEST) {

@@ -22,6 +41,6 @@ super(errorDescription ? `${error}: ${errorDescription}` : error);

/**
* The request is missing a parameter so the server can’t proceed with the request. This
* may also be returned if the request includes an unsupported parameter or repeats a
* parameter.
*/
* The request is missing a parameter so the server can’t proceed with the request. This
* may also be returned if the request includes an unsupported parameter or repeats a
* parameter.
*/
static invalidParameter(parameter, errorDescription) {

@@ -31,22 +50,16 @@ let message = "The request is missing a required parameter, includes an invalid parameter value, ";

errorDescription = errorDescription ? errorDescription : `Check the \`${parameter}\` parameter`;
return new OAuthException(message, "invalid_request" /* InvalidRequest */, errorDescription);
return new OAuthException(message, ErrorType.InvalidRequest, errorDescription);
}
/**
* Client authentication failed, such as if the request contains an invalid client ID or
* secret. Send an HTTP 401 response in this case.
*/
* Client authentication failed, such as if the request contains an invalid client ID or
* secret. Send an HTTP 401 response in this case.
*/
static invalidClient(errorDescription) {
return new OAuthException(
"Client authentication failed",
"invalid_client" /* InvalidClient */,
errorDescription,
void 0,
HttpStatus.UNAUTHORIZED
);
return new OAuthException("Client authentication failed", ErrorType.InvalidClient, errorDescription, void 0, HttpStatus.UNAUTHORIZED);
}
/**
* The authorization code (or user’s password for the password grant type) is invalid or
* expired. This is also the error you would return if the redirect URL given in the
* authorization grant does not match the URL provided in this access token request.
*/
* The authorization code (or user’s password for the password grant type) is invalid or
* expired. This is also the error you would return if the redirect URL given in the
* authorization grant does not match the URL provided in this access token request.
*/
static invalidGrant(errorDescription) {

@@ -56,8 +69,8 @@ let message = "The provided authorization grant (e.g., authorization_code, client_credentials) or refresh token ";

message += "request, or was issued to another client";
return new OAuthException(message, "invalid_grant" /* InvalidGrant */, errorDescription);
return new OAuthException(message, ErrorType.InvalidGrant, errorDescription);
}
/**
* For access token requests that include a scope (password or client_credentials grants),
* this error indicates an invalid scope value in the request.
*/
* For access token requests that include a scope (password or client_credentials grants),
* this error indicates an invalid scope value in the request.
*/
static invalidScope(scope, redirectUri) {

@@ -69,42 +82,31 @@ const message = "The requested scope is invalid, unknown, or malformed";

}
return new OAuthException(message, "invalid_scope" /* InvalidScope */, hint, redirectUri);
return new OAuthException(message, ErrorType.InvalidScope, hint, redirectUri);
}
/**
* This client is not authorized to use the requested grant type. For example, if you
* restrict which applications can use the Implicit grant, you would return this error
* for the other apps.
*/
* This client is not authorized to use the requested grant type. For example, if you
* restrict which applications can use the Implicit grant, you would return this error
* for the other apps.
*/
static unauthorizedClient() {
return new OAuthException(`unauthorized client`, "unauthorized_client" /* UnauthorizedClient */);
return new OAuthException(`unauthorized client`, ErrorType.UnauthorizedClient);
}
/**
* If a grant type is requested that the authorization server doesn’t recognize, use
* this code. Note that unknown grant types also use this specific error code
* rather than using the invalid_request above.
*/
* If a grant type is requested that the authorization server doesn’t recognize, use
* this code. Note that unknown grant types also use this specific error code
* rather than using the invalid_request above.
*/
static unsupportedGrantType() {
return new OAuthException("unsupported grant_type", "unsupported_grant_type" /* UnsupportedGrantType */);
return new OAuthException("unsupported grant_type", ErrorType.UnsupportedGrantType);
}
static badRequest(message) {
return new OAuthException(message, "invalid_request" /* InvalidRequest */, void 0, void 0, HttpStatus.BAD_REQUEST);
return new OAuthException(message, ErrorType.InvalidRequest, void 0, void 0, HttpStatus.BAD_REQUEST);
}
static accessDenied(errorDescription) {
return new OAuthException(
"The resource owner or authorization server denied the request",
"access_denied" /* AccessDenied */,
errorDescription,
void 0,
HttpStatus.UNAUTHORIZED
);
return new OAuthException("The resource owner or authorization server denied the request", ErrorType.AccessDenied, errorDescription, void 0, HttpStatus.UNAUTHORIZED);
}
static internalServerError(errorDescription) {
return new OAuthException(
"Internal server error",
"server_error" /* InternalServerError */,
errorDescription,
void 0,
HttpStatus.INTERNAL_SERVER_ERROR
);
return new OAuthException("Internal server error", ErrorType.InternalServerError, errorDescription, void 0, HttpStatus.INTERNAL_SERVER_ERROR);
}
};
__name(OAuthException, "OAuthException");

@@ -131,2 +133,3 @@ // src/requests/request.ts

};
__name(OAuthRequest, "OAuthRequest");

@@ -138,3 +141,5 @@ // src/responses/response.ts

headers = {};
constructor(responseOptions = { headers: {} }) {
constructor(responseOptions = {
headers: {}
}) {
this.headers = {

@@ -145,3 +150,6 @@ ...responseOptions.headers

get(field) {
console.log({ headers: this.headers, field });
console.log({
headers: this.headers,
field
});
return "";

@@ -153,2 +161,3 @@ }

};
__name(OAuthResponse, "OAuthResponse");

@@ -161,2 +170,3 @@ // src/adapters/fastify.ts

}
__name(responseFromFastify, "responseFromFastify");
function requestFromFastify(req) {

@@ -169,2 +179,3 @@ return new OAuthRequest({

}
__name(requestFromFastify, "requestFromFastify");
function handleFastifyError(e, res) {

@@ -180,2 +191,3 @@ if (e instanceof OAuthException) {

}
__name(handleFastifyError, "handleFastifyError");
function handleFastifyReply(res, response) {

@@ -192,2 +204,3 @@ if (response.status === 302) {

}
__name(handleFastifyReply, "handleFastifyReply");
export {

@@ -194,0 +207,0 @@ handleFastifyError,

@@ -0,1 +1,4 @@

var __defProp = Object.defineProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
// src/exceptions/oauth.exception.ts

@@ -9,3 +12,4 @@ var HttpStatus = {

};
var ErrorType = /* @__PURE__ */ ((ErrorType2) => {
var ErrorType;
(function(ErrorType2) {
ErrorType2["InvalidRequest"] = "invalid_request";

@@ -19,5 +23,9 @@ ErrorType2["InvalidClient"] = "invalid_client";

ErrorType2["InternalServerError"] = "server_error";
return ErrorType2;
})(ErrorType || {});
})(ErrorType || (ErrorType = {}));
var OAuthException = class extends Error {
error;
errorType;
errorDescription;
errorUri;
status;
constructor(error, errorType, errorDescription, errorUri, status = HttpStatus.BAD_REQUEST) {

@@ -34,6 +42,6 @@ super(errorDescription ? `${error}: ${errorDescription}` : error);

/**
* The request is missing a parameter so the server can’t proceed with the request. This
* may also be returned if the request includes an unsupported parameter or repeats a
* parameter.
*/
* The request is missing a parameter so the server can’t proceed with the request. This
* may also be returned if the request includes an unsupported parameter or repeats a
* parameter.
*/
static invalidParameter(parameter, errorDescription) {

@@ -43,22 +51,16 @@ let message = "The request is missing a required parameter, includes an invalid parameter value, ";

errorDescription = errorDescription ? errorDescription : `Check the \`${parameter}\` parameter`;
return new OAuthException(message, "invalid_request" /* InvalidRequest */, errorDescription);
return new OAuthException(message, ErrorType.InvalidRequest, errorDescription);
}
/**
* Client authentication failed, such as if the request contains an invalid client ID or
* secret. Send an HTTP 401 response in this case.
*/
* Client authentication failed, such as if the request contains an invalid client ID or
* secret. Send an HTTP 401 response in this case.
*/
static invalidClient(errorDescription) {
return new OAuthException(
"Client authentication failed",
"invalid_client" /* InvalidClient */,
errorDescription,
void 0,
HttpStatus.UNAUTHORIZED
);
return new OAuthException("Client authentication failed", ErrorType.InvalidClient, errorDescription, void 0, HttpStatus.UNAUTHORIZED);
}
/**
* The authorization code (or user’s password for the password grant type) is invalid or
* expired. This is also the error you would return if the redirect URL given in the
* authorization grant does not match the URL provided in this access token request.
*/
* The authorization code (or user’s password for the password grant type) is invalid or
* expired. This is also the error you would return if the redirect URL given in the
* authorization grant does not match the URL provided in this access token request.
*/
static invalidGrant(errorDescription) {

@@ -68,8 +70,8 @@ let message = "The provided authorization grant (e.g., authorization_code, client_credentials) or refresh token ";

message += "request, or was issued to another client";
return new OAuthException(message, "invalid_grant" /* InvalidGrant */, errorDescription);
return new OAuthException(message, ErrorType.InvalidGrant, errorDescription);
}
/**
* For access token requests that include a scope (password or client_credentials grants),
* this error indicates an invalid scope value in the request.
*/
* For access token requests that include a scope (password or client_credentials grants),
* this error indicates an invalid scope value in the request.
*/
static invalidScope(scope, redirectUri) {

@@ -81,42 +83,31 @@ const message = "The requested scope is invalid, unknown, or malformed";

}
return new OAuthException(message, "invalid_scope" /* InvalidScope */, hint, redirectUri);
return new OAuthException(message, ErrorType.InvalidScope, hint, redirectUri);
}
/**
* This client is not authorized to use the requested grant type. For example, if you
* restrict which applications can use the Implicit grant, you would return this error
* for the other apps.
*/
* This client is not authorized to use the requested grant type. For example, if you
* restrict which applications can use the Implicit grant, you would return this error
* for the other apps.
*/
static unauthorizedClient() {
return new OAuthException(`unauthorized client`, "unauthorized_client" /* UnauthorizedClient */);
return new OAuthException(`unauthorized client`, ErrorType.UnauthorizedClient);
}
/**
* If a grant type is requested that the authorization server doesn’t recognize, use
* this code. Note that unknown grant types also use this specific error code
* rather than using the invalid_request above.
*/
* If a grant type is requested that the authorization server doesn’t recognize, use
* this code. Note that unknown grant types also use this specific error code
* rather than using the invalid_request above.
*/
static unsupportedGrantType() {
return new OAuthException("unsupported grant_type", "unsupported_grant_type" /* UnsupportedGrantType */);
return new OAuthException("unsupported grant_type", ErrorType.UnsupportedGrantType);
}
static badRequest(message) {
return new OAuthException(message, "invalid_request" /* InvalidRequest */, void 0, void 0, HttpStatus.BAD_REQUEST);
return new OAuthException(message, ErrorType.InvalidRequest, void 0, void 0, HttpStatus.BAD_REQUEST);
}
static accessDenied(errorDescription) {
return new OAuthException(
"The resource owner or authorization server denied the request",
"access_denied" /* AccessDenied */,
errorDescription,
void 0,
HttpStatus.UNAUTHORIZED
);
return new OAuthException("The resource owner or authorization server denied the request", ErrorType.AccessDenied, errorDescription, void 0, HttpStatus.UNAUTHORIZED);
}
static internalServerError(errorDescription) {
return new OAuthException(
"Internal server error",
"server_error" /* InternalServerError */,
errorDescription,
void 0,
HttpStatus.INTERNAL_SERVER_ERROR
);
return new OAuthException("Internal server error", ErrorType.InternalServerError, errorDescription, void 0, HttpStatus.INTERNAL_SERVER_ERROR);
}
};
__name(OAuthException, "OAuthException");

@@ -130,2 +121,3 @@ // src/code_verifiers/plain.verifier.ts

};
__name(PlainVerifier, "PlainVerifier");

@@ -141,2 +133,3 @@ // src/code_verifiers/S256.verifier.ts

}
__name(base64encode, "base64encode");
function base64decode(str) {

@@ -147,5 +140,7 @@ if (typeof str === "string")

}
__name(base64decode, "base64decode");
function base64urlencode(str) {
return base64encode(str).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, "");
}
__name(base64urlencode, "base64urlencode");

@@ -160,5 +155,15 @@ // src/code_verifiers/S256.verifier.ts

};
__name(S256Verifier, "S256Verifier");
// src/requests/authorization.request.ts
var AuthorizationRequest = class {
grantTypeId;
client;
user;
scopes;
isAuthorizationApproved;
redirectUri;
state;
codeChallenge;
codeChallengeMethod;
constructor(grantTypeId, client, redirectUri, user) {

@@ -169,2 +174,3 @@ this.grantTypeId = grantTypeId;

this.scopes = [];
this.scopes = [];
this.isAuthorizationApproved = false;

@@ -175,9 +181,4 @@ this.redirectUri = redirectUri ?? client.redirectUris[0];

}
scopes = [];
isAuthorizationApproved;
redirectUri;
state;
codeChallenge;
codeChallengeMethod;
};
__name(AuthorizationRequest, "AuthorizationRequest");

@@ -189,3 +190,5 @@ // src/responses/response.ts

headers = {};
constructor(responseOptions = { headers: {} }) {
constructor(responseOptions = {
headers: {}
}) {
this.headers = {

@@ -196,3 +199,6 @@ ...responseOptions.headers

get(field) {
console.log({ headers: this.headers, field });
console.log({
headers: this.headers,
field
});
return "";

@@ -204,2 +210,3 @@ }

};
__name(OAuthResponse, "OAuthResponse");

@@ -214,2 +221,3 @@ // src/responses/redirect.response.ts

};
__name(RedirectResponse, "RedirectResponse");

@@ -239,2 +247,3 @@ // src/utils/date_interval.ts

};
__name(DateInterval, "DateInterval");

@@ -248,8 +257,12 @@ // src/grants/abstract/abstract_authorized.grant.ts

}
__name(isClientConfidential, "isClientConfidential");
// src/responses/bearer_token.response.ts
var BearerTokenResponse = class extends OAuthResponse {
accessToken;
status;
constructor(accessToken, options) {
super(options);
this.accessToken = accessToken;
this.status = HttpStatus.OK;
this.set("pragma", "no-cache");

@@ -259,7 +272,7 @@ this.set("cache-control", "no-store");

}
status = HttpStatus.OK;
};
__name(BearerTokenResponse, "BearerTokenResponse");
// src/utils/array.ts
var arrayDiff = (arr1, arr2) => arr1.filter((x) => !arr2.includes(x));
var arrayDiff = /* @__PURE__ */ __name((arr1, arr2) => arr1.filter((x) => !arr2.includes(x)), "arrayDiff");

@@ -271,2 +284,3 @@ // src/utils/time.ts

}
__name(getSecondsUntil, "getSecondsUntil");
function roundToSeconds(ms2) {

@@ -277,5 +291,15 @@ if (ms2 instanceof Date)

}
__name(roundToSeconds, "roundToSeconds");
// src/grants/abstract/abstract.grant.ts
var AbstractGrant = class {
clientRepository;
tokenRepository;
scopeRepository;
jwt;
options;
authCodeRepository;
userRepository;
scopeDelimiterString;
supportedGrantTypes;
constructor(clientRepository, tokenRepository, scopeRepository, jwt2, options) {

@@ -287,13 +311,11 @@ this.clientRepository = clientRepository;

this.options = options;
this.scopeDelimiterString = " ";
this.supportedGrantTypes = [
"client_credentials",
"authorization_code",
"refresh_token",
"password",
"implicit"
];
}
authCodeRepository;
userRepository;
scopeDelimiterString = " ";
supportedGrantTypes = [
"client_credentials",
"authorization_code",
"refresh_token",
"password",
"implicit"
];
async makeBearerTokenResponse(client, accessToken, scopes = [], extraJwtFields = {}) {

@@ -334,5 +356,3 @@ const scope = scopes.map((scope2) => scope2.name).join(this.scopeDelimiterString);

iss: void 0,
// @see https://tools.ietf.org/html/rfc7519#section-4.1.1
aud: void 0,
// @see https://tools.ietf.org/html/rfc7519#section-4.1.3
// the contents of `jwtService.extraTokenFields()`

@@ -345,11 +365,6 @@ ...extraJwtFields,

sub: (_a = accessToken.user) == null ? void 0 : _a.id,
// @see https://tools.ietf.org/html/rfc7519#section-4.1.2
exp: roundToSeconds(accessToken.accessTokenExpiresAt.getTime()),
// @see https://tools.ietf.org/html/rfc7519#section-4.1.4
nbf: roundToSeconds(now) - this.options.notBeforeLeeway,
// @see https://tools.ietf.org/html/rfc7519#section-4.1.5
iat: roundToSeconds(now),
// @see https://tools.ietf.org/html/rfc7519#section-4.1.6
jti: accessToken.accessToken
// @see https://tools.ietf.org/html/rfc7519#section-4.1.7
});

@@ -381,3 +396,6 @@ }

clientSecret = clientSecret[0];
return [clientId, clientSecret];
return [
clientId,
clientSecret
];
}

@@ -387,11 +405,20 @@ getBasicAuthCredentials(request) {

if (!((_a = request.headers) == null ? void 0 : _a.hasOwnProperty("authorization"))) {
return [void 0, void 0];
return [
void 0,
void 0
];
}
const header = request.headers["authorization"];
if (!header || !header.startsWith("Basic ")) {
return [void 0, void 0];
return [
void 0,
void 0
];
}
const decoded = base64decode(header.substr(6, header.length));
if (!decoded.includes(":")) {
return [void 0, void 0];
return [
void 0,
void 0
];
}

@@ -408,6 +435,3 @@ return decoded.split(":");

const validScopes = await this.scopeRepository.getAllByIdentifiers(scopes);
const invalidScopes = arrayDiff(
scopes,
validScopes.map((scope) => scope.name)
);
const invalidScopes = arrayDiff(scopes, validScopes.map((scope) => scope.name));
if (invalidScopes.length > 0) {

@@ -481,2 +505,3 @@ throw OAuthException.invalidScope(invalidScopes.join(", "), redirectUri);

};
__name(AbstractGrant, "AbstractGrant");

@@ -510,6 +535,3 @@ // src/grants/abstract/abstract_authorized.grant.ts

if (!!parsed.fragment) {
throw OAuthException.invalidParameter(
"redirect_uri",
"Redirection endpoint must not contain url fragment based on RFC6749, section 3.1.2"
);
throw OAuthException.invalidParameter("redirect_uri", "Redirection endpoint must not contain url fragment based on RFC6749, section 3.1.2");
}

@@ -523,2 +545,3 @@ const redirectUriWithoutQuery = redirectUri.split("?")[0];

};
__name(AbstractAuthorizedGrant, "AbstractAuthorizedGrant");

@@ -529,2 +552,7 @@ // src/grants/auth_code.grant.ts

var AuthCodeGrant = class extends AbstractAuthorizedGrant {
authCodeRepository;
userRepository;
identifier;
authCodeTTL;
codeChallengeVerifiers;
constructor(authCodeRepository, userRepository, clientRepository, tokenRepository, scopeRepository, jwt2, options) {

@@ -534,9 +562,9 @@ super(clientRepository, tokenRepository, scopeRepository, jwt2, options);

this.userRepository = userRepository;
this.identifier = "authorization_code";
this.authCodeTTL = new DateInterval("15m");
this.codeChallengeVerifiers = {
plain: new PlainVerifier(),
S256: new S256Verifier()
};
}
identifier = "authorization_code";
authCodeTTL = new DateInterval("15m");
codeChallengeVerifiers = {
plain: new PlainVerifier(),
S256: new S256Verifier()
};
async respondToAccessTokenRequest(req, accessTokenTTL) {

@@ -556,8 +584,3 @@ var _a, _b;

try {
const finalizedScopes = await this.scopeRepository.finalize(
await this.validateScopes(validatedPayload.scopes ?? []),
this.identifier,
client,
userId
);
const finalizedScopes = await this.scopeRepository.finalize(await this.validateScopes(validatedPayload.scopes ?? []), this.identifier, client, userId);
finalizedScopes.forEach((scope) => scopes.push(scope));

@@ -579,6 +602,3 @@ } catch (_) {

if (!REGEXP_CODE_VERIFIER.test(codeVerifier)) {
throw OAuthException.invalidParameter(
"code_verifier",
"Code verifier must follow the specifications of RFC-7636"
);
throw OAuthException.invalidParameter("code_verifier", "Code verifier must follow the specifications of RFC-7636");
}

@@ -598,3 +618,6 @@ const codeChallengeMethod = validatedPayload.code_challenge_method;

await this.authCodeRepository.revoke(validatedPayload.auth_code_id);
const extraJwtFields = user ? await ((_b = (_a = this.jwt).extraTokenFields) == null ? void 0 : _b.call(_a, { user, client })) : void 0;
const extraJwtFields = user ? await ((_b = (_a = this.jwt).extraTokenFields) == null ? void 0 : _b.call(_a, {
user,
client
})) : void 0;
return await this.makeBearerTokenResponse(client, accessToken, scopes, extraJwtFields);

@@ -623,6 +646,3 @@ }

if (this.options.requiresPKCE && !codeChallenge) {
throw OAuthException.invalidParameter(
"code_challenge",
"The authorization server requires public clients to use PKCE RFC-7636"
);
throw OAuthException.invalidParameter("code_challenge", "The authorization server requires public clients to use PKCE RFC-7636");
}

@@ -654,11 +674,3 @@ if (codeChallenge) {

}
const authCode = await this.issueAuthCode(
this.authCodeTTL,
authorizationRequest.client,
authorizationRequest.user.id,
authorizationRequest.redirectUri,
authorizationRequest.codeChallenge,
authorizationRequest.codeChallengeMethod,
authorizationRequest.scopes
);
const authCode = await this.issueAuthCode(this.authCodeTTL, authorizationRequest.client, authorizationRequest.user.id, authorizationRequest.redirectUri, authorizationRequest.codeChallenge, authorizationRequest.codeChallengeMethod, authorizationRequest.scopes);
const payload = {

@@ -676,3 +688,5 @@ client_id: authCode.client.id,

const code = await this.encrypt(jsonPayload);
const params = { code };
const params = {
code
};
if (authorizationRequest.state)

@@ -733,2 +747,3 @@ params.state = authorizationRequest.state;

};
__name(AuthCodeGrant, "AuthCodeGrant");

@@ -745,6 +760,10 @@ // src/grants/client_credentials.grant.ts

const accessToken = await this.issueAccessToken(accessTokenTTL, client, user, validScopes);
const extraJwtFields = await ((_b = (_a = this.jwt).extraTokenFields) == null ? void 0 : _b.call(_a, { user, client }));
const extraJwtFields = await ((_b = (_a = this.jwt).extraTokenFields) == null ? void 0 : _b.call(_a, {
user,
client
}));
return await this.makeBearerTokenResponse(client, accessToken, validScopes, extraJwtFields);
}
};
__name(ClientCredentialsGrant, "ClientCredentialsGrant");

@@ -774,7 +793,3 @@ // src/grants/implicit.grant.ts

const redirectUri = this.getRedirectUri(request, client);
const scopes = await this.validateScopes(
this.getQueryStringParameter("scope", request, []),
// @see about this.defaultSCopes as third param
redirectUri
);
const scopes = await this.validateScopes(this.getQueryStringParameter("scope", request, []), redirectUri);
const state = this.getQueryStringParameter("state", request);

@@ -796,6 +811,3 @@ const authorizationRequest = new AuthorizationRequest(this.identifier, client, redirectUri);

if (!finalRedirectUri) {
throw OAuthException.invalidParameter(
"redirect_uri",
"Neither the request nor the client contain a valid refresh token"
);
throw OAuthException.invalidParameter("redirect_uri", "Neither the request nor the client contain a valid refresh token");
}

@@ -805,14 +817,4 @@ if (!authorizationRequest.isAuthorizationApproved) {

}
const finalizedScopes = await this.scopeRepository.finalize(
authorizationRequest.scopes,
this.identifier,
authorizationRequest.client,
authorizationRequest.user.id
);
const accessToken = await this.issueAccessToken(
this.accessTokenTTL,
authorizationRequest.client,
authorizationRequest.user,
finalizedScopes
);
const finalizedScopes = await this.scopeRepository.finalize(authorizationRequest.scopes, this.identifier, authorizationRequest.client, authorizationRequest.user.id);
const accessToken = await this.issueAccessToken(this.accessTokenTTL, authorizationRequest.client, authorizationRequest.user, finalizedScopes);
const extraFields = await ((_d = (_c = this.jwt).extraTokenFields) == null ? void 0 : _d.call(_c, {

@@ -822,8 +824,3 @@ user: authorizationRequest.user,

}));
const encryptedAccessToken = await this.encryptAccessToken(
authorizationRequest.client,
accessToken,
authorizationRequest.scopes,
extraFields ?? {}
);
const encryptedAccessToken = await this.encryptAccessToken(authorizationRequest.client, accessToken, authorizationRequest.scopes, extraFields ?? {});
const params = {

@@ -839,10 +836,13 @@ access_token: encryptedAccessToken,

};
__name(ImplicitGrant, "ImplicitGrant");
// src/grants/password.grant.ts
var PasswordGrant = class extends AbstractGrant {
userRepository;
identifier;
constructor(userRepository, clientRepository, tokenRepository, scopeRepository, jwt2, options) {
super(clientRepository, tokenRepository, scopeRepository, jwt2, options);
this.userRepository = userRepository;
this.identifier = "password";
}
identifier = "password";
async respondToAccessTokenRequest(req, accessTokenTTL) {

@@ -853,11 +853,9 @@ var _a, _b;

const user = await this.validateUser(req, client);
const finalizedScopes = await this.scopeRepository.finalize(
await this.validateScopes(bodyScopes),
this.identifier,
client,
user.id
);
const finalizedScopes = await this.scopeRepository.finalize(await this.validateScopes(bodyScopes), this.identifier, client, user.id);
let accessToken = await this.issueAccessToken(accessTokenTTL, client, user, finalizedScopes);
accessToken = await this.issueRefreshToken(accessToken, client);
const extraJwtFields = await ((_b = (_a = this.jwt).extraTokenFields) == null ? void 0 : _b.call(_a, { user, client }));
const extraJwtFields = await ((_b = (_a = this.jwt).extraTokenFields) == null ? void 0 : _b.call(_a, {
user,
client
}));
return await this.makeBearerTokenResponse(client, accessToken, finalizedScopes, extraJwtFields);

@@ -881,2 +879,3 @@ }

};
__name(PasswordGrant, "PasswordGrant");

@@ -891,9 +890,3 @@ // src/grants/refresh_token.grant.ts

const user = oldToken.user;
const scopes = await this.validateScopes(
this.getRequestParameter(
"scope",
req,
oldToken.scopes.map((s) => s.name)
)
);
const scopes = await this.validateScopes(this.getRequestParameter("scope", req, oldToken.scopes.map((s) => s.name)));
scopes.forEach((scope) => {

@@ -908,3 +901,6 @@ if (!oldToken.scopes.map((scope2) => scope2.name).includes(scope.name)) {

newToken = await this.issueRefreshToken(newToken, client);
const extraJwtFields = await ((_b = (_a = this.jwt).extraTokenFields) == null ? void 0 : _b.call(_a, { user, client }));
const extraJwtFields = await ((_b = (_a = this.jwt).extraTokenFields) == null ? void 0 : _b.call(_a, {
user,
client
}));
return await this.makeBearerTokenResponse(client, newToken, scopes, extraJwtFields);

@@ -962,2 +958,3 @@ }

};
__name(RefreshTokenGrant, "RefreshTokenGrant");

@@ -967,2 +964,3 @@ // src/utils/jwt.ts

var JwtService = class {
secretOrPrivateKey;
constructor(secretOrPrivateKey) {

@@ -972,4 +970,4 @@ this.secretOrPrivateKey = secretOrPrivateKey;

/**
* Asynchronously verify given token using a secret or a public key to get a decoded token
*/
* Asynchronously verify given token using a secret or a public key to get a decoded token
*/
verify(token, options = {}) {

@@ -986,4 +984,4 @@ return new Promise((resolve, reject) => {

/**
* Returns the decoded payload without verifying if the signature is valid.
*/
* Returns the decoded payload without verifying if the signature is valid.
*/
decode(encryptedData) {

@@ -993,4 +991,4 @@ return jwt.decode(encryptedData);

/**
* Sign the given payload into a JSON Web Token string
*/
* Sign the given payload into a JSON Web Token string
*/
sign(payload) {

@@ -1007,2 +1005,3 @@ return new Promise((resolve, reject) => {

};
__name(JwtService, "JwtService");

@@ -1019,2 +1018,10 @@ // src/options.ts

var AuthorizationServer = class {
clientRepository;
tokenRepository;
scopeRepository;
enabledGrantTypes;
grantTypeAccessTokenTTL;
availableGrants;
options;
jwt;
constructor(clientRepository, tokenRepository, scopeRepository, serviceOrString, options) {

@@ -1024,4 +1031,10 @@ this.clientRepository = clientRepository;

this.scopeRepository = scopeRepository;
this.enabledGrantTypes = {};
this.grantTypeAccessTokenTTL = {};
this.options = DEFAULT_AUTHORIZATION_SERVER_OPTIONS;
this.jwt = typeof serviceOrString === "string" ? new JwtService(serviceOrString) : this.jwt = serviceOrString;
this.options = { ...DEFAULT_AUTHORIZATION_SERVER_OPTIONS, ...options };
this.options = {
...DEFAULT_AUTHORIZATION_SERVER_OPTIONS,
...options
};
const grantProps = [

@@ -1040,7 +1053,2 @@ this.clientRepository,

}
enabledGrantTypes = {};
grantTypeAccessTokenTTL = {};
availableGrants;
options = DEFAULT_AUTHORIZATION_SERVER_OPTIONS;
jwt;
enableGrantTypes(...grants) {

@@ -1066,20 +1074,5 @@ for (const grant of grants) {

} else if (toEnable.grant === "authorization_code") {
grant = new AuthCodeGrant(
toEnable.authCodeRepository,
toEnable.userRepository,
this.clientRepository,
this.tokenRepository,
this.scopeRepository,
this.jwt,
this.options
);
grant = new AuthCodeGrant(toEnable.authCodeRepository, toEnable.userRepository, this.clientRepository, this.tokenRepository, this.scopeRepository, this.jwt, this.options);
} else if (toEnable.grant === "password") {
grant = new PasswordGrant(
toEnable.userRepository,
this.clientRepository,
this.tokenRepository,
this.scopeRepository,
this.jwt,
this.options
);
grant = new PasswordGrant(toEnable.userRepository, this.clientRepository, this.tokenRepository, this.scopeRepository, this.jwt, this.options);
}

@@ -1133,2 +1126,3 @@ if (!grant) {

};
__name(AuthorizationServer, "AuthorizationServer");

@@ -1155,2 +1149,3 @@ // src/requests/request.ts

};
__name(OAuthRequest, "OAuthRequest");

@@ -1162,2 +1157,3 @@ // src/utils/token.ts

}
__name(generateRandomToken, "generateRandomToken");
export {

@@ -1164,0 +1160,0 @@ AbstractAuthorizedGrant,

{
"version": "3.0.1-alpha.8",
"name": "@jmondi/oauth2-server",
"version": "3.0.1-alpha.9",
"packageManager": "pnpm@8.4.0",
"type": "module",
"author": "Jason Raimondi <jason@raimondi.us>",
"funding": "https://github.com/sponsors/jasonraimondi",
"license": "MIT",
"type": "module",
"exports": {

@@ -24,18 +26,2 @@ ".": {

},
"tsup": {
"entry": {
"index": "./src/index.ts",
"express": "./src/adapters/express.ts",
"fastify": "./src/adapters/fastify.ts"
},
"format": [
"cjs",
"esm"
],
"target": "node16",
"clean": true,
"dts": true,
"splitting": false,
"sourcemap": true
},
"files": [

@@ -71,2 +57,3 @@ "dist",

"dependencies": {
"@swc/core": "^1.3.62",
"jsonwebtoken": "^9.0.0",

@@ -76,2 +63,18 @@ "ms": "^2.1.3",

},
"tsup": {
"entry": {
"index": "./src/index.ts",
"express": "./src/adapters/express.ts",
"fastify": "./src/adapters/fastify.ts"
},
"format": [
"cjs",
"esm"
],
"target": "node16",
"clean": true,
"dts": true,
"splitting": false,
"sourcemap": true
},
"scripts": {

@@ -91,2 +94,5 @@ "clean": "rimraf dist",

},
"main": "./dist/index.js",
"module": "./dist/index.js",
"types": "./dist/index.d.ts",
"typesVersions": {

@@ -93,0 +99,0 @@ "*": {

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

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