Skip to content

Commit

Permalink
feat: add node-2fa library (#347)
Browse files Browse the repository at this point in the history
  • Loading branch information
ChrisPdgn authored Sep 27, 2022
1 parent c1b60ae commit 8dfea01
Show file tree
Hide file tree
Showing 13 changed files with 2,060 additions and 39 deletions.
5 changes: 4 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@ RUN yarn && \

RUN if [ -z "$BUILDING_SERVICE" ] ; then npx lerna run build ; \
elif [ "$BUILDING_SERVICE" = "conduit" ] ; then npx lerna run build --scope=@conduitplatform/admin \
--scope=@conduitplatform/commons --scope=@conduitplatform/core --scope=@conduitplatform/hermes; \
--scope=@conduitplatform/commons --scope=@conduitplatform/core --scope=@conduitplatform/hermes \
--scope=@conduitplatform/node-2fa; \
elif [ "$BUILDING_SERVICE" = "modules/router" ] ; then npx lerna run build --scope=@conduitplatform/router \
--scope=@conduitplatform/hermes; \
elif [ "$BUILDING_SERVICE" = "modules/authentication" ] ; then npx lerna run build --scope=@conduitplatform/authentication \
--scope=@conduitplatform/node-2fa; \
else cd /app/$BUILDING_SERVICE && yarn build && cd /app ; fi

RUN yarn cache clean && npx lerna clean -y && rm -rf node_modules
1 change: 1 addition & 0 deletions libraries/node-2fa/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
src/
13 changes: 13 additions & 0 deletions libraries/node-2fa/README.mdx
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
# Conduit node-2fa

This is a library used for 2-Factor Authentication through QRs.
It uses notp which implements TOTP (RFC 6238) (the Authenticator standard), which is based on HOTP (RFC 4226)
to provide codes that are exactly compatible with all other Authenticator apps and services that use them.

Original Repo: https://github.com/jeremyscalpello/node-2fa

## Features ✔️

- Secret generation
- Token generation
- Token verification
38 changes: 38 additions & 0 deletions libraries/node-2fa/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
{
"contributors": [
"Jeremy Scalpello <jeremy@scalpello.info>",
"Alistair Smith <hey@alistair.cloud>"
],
"homepage": "https://github.com/jeremyscalpello/node-2fa#readme",
"name": "@conduitplatform/node-2fa",
"version": "1.0.0",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"engines": {
"node": ">=14"
},
"scripts": {
"prepublish": "npm run build",
"build": "rimraf dist && tsc",
"publish": "npm publish"
},
"author": "",
"license": "ISC",
"dependencies": {
"@types/notp": "^2.0.2",
"notp": "^2.0.3",
"thirty-two": "^1.0.2",
"tslib": "^2.4.0"
},
"devDependencies": {
"@types/jest": "^29.0.3",
"@types/node": "^18.7.18",
"@typescript-eslint/eslint-plugin": "^5.38.0",
"@typescript-eslint/parser": "^5.38.0",
"eslint": "^8.23.1",
"jest": "^29.0.3",
"prettier": "^2.7.1",
"ts-jest": "^29.0.1",
"typescript": "^4.8.3"
}
}
8 changes: 8 additions & 0 deletions libraries/node-2fa/src/env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
declare module 'thirty-two' {
const _default: {
encode: (plain: string | Buffer) => Buffer;
decode: (encoded: string | Buffer) => Buffer;
};

export = _default;
}
52 changes: 52 additions & 0 deletions libraries/node-2fa/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import notp from 'notp';
import crypto from 'crypto';
import b32 from 'thirty-two';
import { Options } from './interfaces';

export function generateSecret(options?: Options) {
const config = {
name: encodeURIComponent(options?.name ?? 'App'),
account: encodeURIComponent(options?.account ? `:${options.account}` : ''),
} as const;

const bin = crypto.randomBytes(20);
const base32 = b32.encode(bin).toString('utf8').replace(/=/g, '');

const secret = base32
.toLowerCase()
.replace(/(\w{4})/g, '$1 ')
.trim()
.split(' ')
.join('')
.toUpperCase();

const query = `?secret=${secret}&issuer=${config.name}`;
const encodedQuery = query.replace('?', '%3F').replace('&', '%26');
const uri = `otpauth://totp/${config.name}${config.account}`;

return {
secret,
uri: `${uri}${query}`,
qr: `https://chart.googleapis.com/chart?chs=166x166&chld=L|0&cht=qr&chl=${uri}${encodedQuery}`,
};
}

export function generateToken(secret: string) {
if (!secret || !secret.length) return null;
const unformatted = secret.replace(/\W+/g, '').toUpperCase();
const bin = b32.decode(unformatted);

return { token: notp.totp.gen(bin) };
}

export function verifyToken(secret: string, token?: string, window = 4) {
if (!token || !token.length) return null;

const unformatted = secret.replace(/\W+/g, '').toUpperCase();
const bin = b32.decode(unformatted);

return notp.totp.verify(token.replace(/\W+/g, ''), bin, {
window,
time: 30,
});
}
4 changes: 4 additions & 0 deletions libraries/node-2fa/src/interfaces.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface Options {
name: string;
account: string;
}
67 changes: 67 additions & 0 deletions libraries/node-2fa/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ES6" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true /* Generates corresponding '.d.ts' file. */,
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true /* Generates corresponding '.map' file. */,
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist"
/* Redirect output structure to the directory. */,
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
"removeComments": true /* Do not emit comments to output. */,
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
"strictPropertyInitialization": false /* Enable strict checking of property initialization in classes. */,
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */

/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */

/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */

/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

/* Experimental Options */
"experimentalDecorators": true /* Enables experimental support for ES7 decorators. */,
"emitDecoratorMetadata": true /* Enables experimental support for emitting type metadata for decorators. */,

/* Advanced Options */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
1 change: 1 addition & 0 deletions modules/authentication/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ FROM conduit-builder:latest
WORKDIR /app

COPY --from=conduit-base:latest /app/modules/authentication /app/modules/authentication
COPY --from=conduit-base:latest /app/libraries/node-2fa /app/libraries/node-2fa

RUN apk update && \
apk add --no-cache --virtual .gyp python3 make g++ && \
Expand Down
2 changes: 1 addition & 1 deletion modules/authentication/src/TwoFactorAuth.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import * as twoFactor from 'node-2fa';
import * as twoFactor from '@conduitplatform/node-2fa';
import ConduitGrpcSdk, { ConfigController, GrpcError } from '@conduitplatform/grpc-sdk';
import { status } from '@grpc/grpc-js';
import { AccessToken, RefreshToken, Token, TwoFactorSecret, User } from './models';
Expand Down
9 changes: 4 additions & 5 deletions modules/authentication/src/handlers/local.ts
Original file line number Diff line number Diff line change
Expand Up @@ -717,8 +717,8 @@ export class LocalHandlers implements IAuthenticationStrategy {
throw new GrpcError(status.NOT_FOUND, 'Verification unsuccessful');

const verification = TwoFactorAuth.verifyToken(secret.secret, code, 1);
if (isNil(verification))
throw new GrpcError(status.UNAUTHENTICATED, 'Verification unsuccessful');
if (isNil(verification) || verification.delta !== 0)
throw new GrpcError(status.INVALID_ARGUMENT, 'Provided code is invalid');
} else {
throw new GrpcError(status.FAILED_PRECONDITION, '2FA method not specified');
}
Expand Down Expand Up @@ -976,10 +976,9 @@ export class LocalHandlers implements IAuthenticationStrategy {
if (isNil(secret)) throw new GrpcError(status.NOT_FOUND, 'Verification unsuccessful');

const verification = TwoFactorAuth.verifyToken(secret.secret, code, 1);
if (isNil(verification)) {
throw new GrpcError(status.UNAUTHENTICATED, 'Verification unsuccessful');
if (isNil(verification) || verification.delta !== 0) {
throw new GrpcError(status.INVALID_ARGUMENT, 'Provided code is invalid');
}

await User.getInstance().findByIdAndUpdate(context.user._id, {
hasTwoFA: true,
});
Expand Down
1 change: 1 addition & 0 deletions packages/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ WORKDIR /app

COPY --from=conduit-base:latest /app/packages /app/packages
COPY --from=conduit-base:latest /app/libraries/hermes /app/libraries/hermes
COPY --from=conduit-base:latest /app/libraries/node-2fa /app/libraries/node-2fa

RUN yarn install --production --pure-lockfile --non-interactive && yarn cache clean

Expand Down
Loading

0 comments on commit 8dfea01

Please sign in to comment.