Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions lib/lib-auth/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
src/typings/
14 changes: 14 additions & 0 deletions lib/lib-auth/.eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"extends": "../../.eslintrc",
"parserOptions": {
"project": "tsconfig.json"
},
"rules": {
"@typescript-eslint/no-unsafe-assignment": "off",
"@typescript-eslint/no-unsafe-return": "off",
"@typescript-eslint/no-unsafe-call": "off",
"@typescript-eslint/no-unsafe-argument": "off",
"@typescript-eslint/no-unsafe-member-access": "off",
"@typescript-eslint/no-explicit-any": "off"
}
}
8 changes: 8 additions & 0 deletions lib/lib-auth/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/node_modules/
/build/
/coverage/
/docs/
*.tsbuildinfo
*.tgz
*.log
package-lock.json
21 changes: 21 additions & 0 deletions lib/lib-auth/LICENSE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) [2023] [Topcoder]

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
3 changes: 3 additions & 0 deletions lib/lib-auth/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# @topcoder-framework/lib-auth

TODO
42 changes: 42 additions & 0 deletions lib/lib-auth/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"name": "@topcoder-framework/lib-auth",
"version": "0.20.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "scripty",
"build:es": "scripty",
"build:app": "scripty",
"build:include:deps": "scripty",
"clean": "scripty",
"lint": "scripty",
"format": "scripty"
},
"scripty": {
"path": "../../scripts/packages",
"windowsPath": "../../scripts-win/packages"
},
"author": "Rakib Ansary <rakibansary@topcoder.com>",
"license": "ISC",
"volta": {
"node": "18.14.1",
"typescript": "4.9.3",
"npm": "9.1.2"
},
"dependencies": {
"@grpc/grpc-js": "^1.8.0",
"@types/jsonwebtoken": "^9.0.2",
"axios": "^1.4.0",
"jsonwebtoken": "^9.0.1",
"jwks-rsa": "^3.0.1",
"lodash": "^4.17.21"
},
"devDependencies": {
"@types/express": "^4.17.17",
"express": "^4.18.2"
},
"files": [
"dist-*"
],
"gitHead": "8c19fdcd36bcccc5e952aa909e4a30caf2943340"
}
46 changes: 46 additions & 0 deletions lib/lib-auth/src/common/JwksHelper.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { Jwt } from "jsonwebtoken";
import JwksRSA, { JwksClient, SigningKey } from "jwks-rsa";
import _ from "lodash";
import { UnauthorizedError } from "src/errors/UnauthorizedError";
import { hasIss } from "./Validators";

const jwksClients: { [iss: string]: JwksClient } = {};

const getJwksClient = (
token: Jwt,
cacheTime: number,
validIssuers?: string[]
): JwksClient => {
if (!hasIss(token.payload)) {
throw new UnauthorizedError("");
}
if (validIssuers && !_.includes(validIssuers, token.payload.iss)) {
throw new UnauthorizedError("Invalid token issuer.");
}
const iss = token.payload.iss;
if (!jwksClients[iss]) {
jwksClients[iss] = JwksRSA({
cache: true,
cacheMaxEntries: 5,
cacheMaxAge: cacheTime * 36e5,
jwksUri: token.payload.iss + ".well-known/jwks.json",
});
}
return jwksClients[iss];
};

export const getRSAKey = async (
token: Jwt,
cacheTime: number,
validIssuers?: string[]
) => {
const kid = token.header.kid;
const jwksClient = getJwksClient(token, cacheTime, validIssuers);
let key: SigningKey;
try {
key = await jwksClient.getSigningKey(kid);
} catch {
throw new UnauthorizedError("");
}
return key.getPublicKey();
};
24 changes: 24 additions & 0 deletions lib/lib-auth/src/common/TokenGetter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { Request } from "express";
import { AuthMethod, TokenGetter } from "src/interfaces";

export const getDefaultTokenGetter = (method: AuthMethod): TokenGetter => {
switch (method) {
case "Bearer":
return bearerTokenGetter;
default:
throw new Error("");
}
};

const bearerTokenGetter = (req: Request): string | undefined => {
if (req.headers && req.headers.authorization) {
const parts = req.headers.authorization.split(" ");
if (parts.length == 2) {
const scheme = parts[0];
const credentials = parts[1];
if (/^Bearer$/i.test(scheme)) {
return credentials;
}
}
}
};
124 changes: 124 additions & 0 deletions lib/lib-auth/src/common/Validators.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import { JwtPayload } from "jsonwebtoken";
import _ from "lodash";
import {
Algorithm,
AuthMethod,
AuthMethods,
HSA,
RSA,
TokenGetter,
} from "src/interfaces";
import { getDefaultTokenGetter } from "./TokenGetter";

export const isValidAuthMethod = (method: unknown): method is AuthMethod =>
_.isString(method) && method in AuthMethods;

export const isValidAlgorithm = (algorithm: unknown): algorithm is Algorithm =>
_.includes(["HS256", "HS384", "HS512", "RS256", "RS384", "RS512"], algorithm);

export const isValidAlgorithms = (
algorithms: unknown[]
): algorithms is Algorithm[] => _.every(algorithms, isValidAlgorithm);

export const isHSA = (algorithm: unknown): algorithm is HSA =>
_.includes(["HS256", "HS384", "HS512"], algorithm);

export const isRSA = (algorithm: unknown): algorithm is RSA =>
_.includes(["RS256", "RS384", "RS512"], algorithm);

export const hasIss = (
payload: string | JwtPayload
): payload is JwtPayload & { iss: string } => {
return typeof payload === "object" && payload.iss !== undefined;
};

export const validateAndGetAlgorithms = (
algorithms?: unknown[]
): Algorithm[] => {
if (algorithms === undefined) {
return ["HS256", "RS256"];
}
if (_.isEmpty(algorithms)) {
throw new RangeError("");
}
if (!isValidAlgorithms(algorithms)) {
throw new RangeError("");
}
return algorithms;
};

export const validateAndGetMethod = (method?: unknown): AuthMethod => {
if (method === undefined) {
return "Bearer";
}
if (isValidAuthMethod(method)) {
return method;
} else {
throw new RangeError("");
}
};

export const validateAndGetTokenGetter = (
method: AuthMethod,
getToken?: unknown
): TokenGetter => {
if (getToken === undefined) {
return getDefaultTokenGetter(method);
}
if (typeof getToken === "function") {
return getToken as TokenGetter;
} else {
throw new RangeError("");
}
};

export const validateAndGetCacheTime = (cacheTime?: unknown): number => {
if (cacheTime === undefined) {
return 24;
}
if (_.isNumber(cacheTime)) {
return cacheTime;
} else {
throw new RangeError("");
}
};

export const validateAndGetRequestProperty = (
requestProperty?: unknown
): string => {
if (requestProperty === undefined) {
return "authUser";
}
if (_.isString(requestProperty)) {
return requestProperty;
} else {
throw new RangeError("");
}
};

export const validateAndGetIssuers = (issuer: unknown): string[] => {
if (issuer === undefined) {
throw new RangeError("");
} else if (_.isString(issuer)) {
return [issuer];
} else if (
_.isArray(issuer) &&
!_.isEmpty(issuer) &&
_.every(issuer, (iss) => _.isString(iss))
) {
return issuer as string[];
} else {
throw new RangeError("");
}
};

export const validateAndGetTokenKey = (tokenKey?: unknown): string => {
if (tokenKey === undefined) {
return "token";
}
if (_.isString(tokenKey)) {
return tokenKey;
} else {
throw new RangeError("");
}
};
95 changes: 95 additions & 0 deletions lib/lib-auth/src/common/Verifiers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { Jwt, JwtPayload, Secret, verify } from "jsonwebtoken";
import _ from "lodash";
import { UnauthorizedError } from "src/errors/UnauthorizedError";
import { Algorithm, AuthProperty, Permissions } from "src/interfaces";
import { getRSAKey } from "./JwksHelper";

export const validatePermissions = (
auth: AuthProperty,
permissions: Permissions
) => {
if (auth.isMachine) {
if (permissions.allowedScopes) {
if (
_.some(permissions.allowedScopes, (scope) =>
_.includes(auth.scopes, scope)
)
) {
return true;
}
} else {
return true;
}
} else {
if (permissions.allowedRoles) {
if (
_.some(permissions.allowedRoles, (role) => _.includes(auth.roles, role))
) {
return true;
}
} else {
return true;
}
}
throw new UnauthorizedError("");
};

export const verifyHSAToken = (
token: string,
algorithms: Algorithm[],
audience?: string | RegExp | (string | RegExp)[],
secret?: Secret
) => {
if (secret === undefined) {
throw new UnauthorizedError("");
}
try {
verify(token, secret, {
audience,
algorithms,
});
} catch {
throw new UnauthorizedError("");
}
};

export const verifyRSAToken = async (
token: string,
decodedToken: Jwt,
cacheTime: number,
algorithms: Algorithm[],
validIsuers: string[],
audience?: string | RegExp | (string | RegExp)[]
) => {
const key = await getRSAKey(decodedToken, cacheTime, validIsuers);
try {
verify(token, key, {
audience,
algorithms,
});
} catch {
throw new UnauthorizedError("");
}
};

export const buildRequestProperty = (
token: JwtPayload,
claimScope: string
): AuthProperty => {
const payload: AuthProperty = {
userId: token[claimScope + "/userId"],
handle: token[claimScope + "/handle"],
roles: token[claimScope + "/roles"],
email: token.email ?? token[claimScope + "/email"],
isMachine: token.gty === "client-credentials",
};
if (payload.isMachine) {
const scopes = token[claimScope + "/scope"];
if (typeof scopes === "string") {
payload.scopes = scopes.split(" ");
} else if (_.isArray(scopes)) {
payload.scopes = scopes;
}
}
return payload;
};
4 changes: 4 additions & 0 deletions lib/lib-auth/src/common/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export * from "./JwksHelper";
export * from "./TokenGetter";
export * from "./Validators";
export * from "./Verifiers";
Loading