Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[discuss] Asymmetric authentication #812

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
30 changes: 30 additions & 0 deletions packages/asymmetric/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# @accounts/password
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

need to change that


[![npm](https://img.shields.io/npm/v/@accounts/password.svg?maxAge=2592000)](https://www.npmjs.com/package/@accounts/password)
![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)

## Install

```
yarn add @accounts/password
```

## Usage

```js
import { AccountsServer } from '@accounts/server';
import { AccountsPassword } from '@accounts/password';

export const accountsPassword = new AccountsPassword({
// options
});

const accountsServer = new AccountsServer(
{
// options
},
{
password: accountsPassword,
}
);
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`AccountsAsymmetric throws error when the user is not found by public key 1`] = `[Error: User not found]`;

exports[`AccountsAsymmetric throws error when the verification process fails 1`] = `[Error: Failed to verify signature]`;
183 changes: 183 additions & 0 deletions packages/asymmetric/__tests__/accounts-asymmetric.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
import * as crypto from 'crypto';

import { PublicKeyType } from '../src/types';
import { AccountsAsymmetric } from '../src';

describe('AccountsAsymmetric', () => {
it('should update the public key', async () => {
const { publicKey } = crypto.generateKeyPairSync('ec', {
namedCurve: 'sect239k1',
});
const publicKeyStr = publicKey.export({ type: 'spki', format: 'der' }).toString('base64');

const service = new AccountsAsymmetric();

const setService = jest.fn(() => Promise.resolve(null));
service.setStore({ setService } as any);

const publicKeyParams: PublicKeyType = {
key: publicKeyStr,
encoding: 'base64',
format: 'pem',
type: 'spki',
};

const res = await service.updatePublicKey('123', publicKeyParams);

expect(res).toBeTruthy();
expect(setService).toHaveBeenCalledWith('123', service.serviceName, {
id: publicKeyStr,
...publicKeyParams,
});
});

it('throws error when the user is not found by public key', async () => {
const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
namedCurve: 'sect239k1',
});
const payload = 'some data to sign';

const sign = crypto.createSign('sha512');
sign.write(payload);
sign.end();
const signature = sign.sign(privateKey, 'hex');

const publicKeyStr = publicKey.export({ type: 'spki', format: 'der' }).toString('base64');

const service = new AccountsAsymmetric();

const findUserByServiceId = jest.fn(() => Promise.resolve(null));
service.setStore({ findUserByServiceId } as any);

await expect(
service.authenticate({
signature,
payload,
publicKey: publicKeyStr,
signatureAlgorithm: 'sha512',
signatureFormat: 'hex',
})
).rejects.toMatchSnapshot();
});

it('throws error when the verification process fails', async () => {
const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
namedCurve: 'sect239k1',
});
const payload = 'some data to sign';

const sign = crypto.createSign('sha512');
sign.write(payload);
sign.end();
const signature = sign.sign(privateKey, 'hex');

const publicKeyStr = publicKey.export({ type: 'spki', format: 'der' }).toString('base64');

const service = new AccountsAsymmetric();

const publicKeyParams: PublicKeyType = {
key: publicKeyStr,
encoding: 'base64',
format: 'pem',
type: 'spki',
};

const user = {
id: '123',
services: {
[service.serviceName]: publicKeyParams,
},
};
const findUserByServiceId = jest.fn(() => Promise.resolve(user));
service.setStore({ findUserByServiceId } as any);

await expect(
service.authenticate({
signature,
payload,
publicKey: publicKeyStr,
signatureAlgorithm: 'sha512',
signatureFormat: 'hex',
})
).rejects.toMatchSnapshot();
});

it('should return null when signature is invalid', async () => {
const { publicKey } = crypto.generateKeyPairSync('ec', {
namedCurve: 'sect239k1',
});
const payload = 'some data to sign';

const publicKeyStr = publicKey.export({ type: 'spki', format: 'der' }).toString('base64');

const service = new AccountsAsymmetric();

const publicKeyParams: PublicKeyType = {
key: publicKeyStr,
encoding: 'base64',
format: 'der',
type: 'spki',
};

const user = {
id: '123',
services: {
[service.serviceName]: publicKeyParams,
},
};
const findUserByServiceId = jest.fn(() => Promise.resolve(user));
service.setStore({ findUserByServiceId } as any);

const userFromService = await service.authenticate({
signature: 'some signature',
payload,
publicKey: publicKeyStr,
signatureAlgorithm: 'sha512',
signatureFormat: 'hex',
});

expect(userFromService).toBeNull();
});

it('should return user when verification is successful', async () => {
const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
namedCurve: 'sect239k1',
});
const payload = 'some data to sign';

const sign = crypto.createSign('sha512');
sign.write(payload);
sign.end();
const signature = sign.sign(privateKey, 'hex');

const publicKeyStr = publicKey.export({ type: 'spki', format: 'der' }).toString('base64');

const service = new AccountsAsymmetric();

const publicKeyParams: PublicKeyType = {
key: publicKeyStr,
encoding: 'base64',
format: 'der',
type: 'spki',
};

const user = {
id: '123',
services: {
[service.serviceName]: publicKeyParams,
},
};
const findUserByServiceId = jest.fn(() => Promise.resolve(user));
service.setStore({ findUserByServiceId } as any);

const userFromService = await service.authenticate({
signature,
payload,
publicKey: publicKeyStr,
signatureAlgorithm: 'sha512',
signatureFormat: 'hex',
});

expect(userFromService).toEqual(user);
});
});
33 changes: 33 additions & 0 deletions packages/asymmetric/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
{
"name": "@accounts/asymmetric",
"version": "0.19.0",
"license": "MIT",
"main": "lib/index.js",
"typings": "lib/index.d.ts",
"scripts": {
"clean": "rimraf lib",
"start": "tsc --watch",
"precompile": "yarn clean",
"compile": "tsc",
"prepublishOnly": "yarn compile",
"testonly": "jest",
"coverage": "jest --coverage"
},
"jest": {
"testEnvironment": "node",
"preset": "ts-jest"
},
"dependencies": {
"@accounts/types": "^0.19.0",
"tslib": "1.10.0"
},
"devDependencies": {
"@types/jest": "24.0.18",
"@types/node": "12.7.4",
"jest": "24.9.0",
"rimraf": "3.0.0"
},
"peerDependencies": {
"@accounts/server": "^0.19.0"
}
}
69 changes: 69 additions & 0 deletions packages/asymmetric/src/accounts-asymmetric.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { AuthenticationService, DatabaseInterface } from '@accounts/types';
import { AccountsServer } from '@accounts/server';
import * as crypto from 'crypto';

import { AsymmetricLoginType, PublicKeyType, ErrorMessages } from './types';
import { errors } from './errors';

export interface AccountsAsymmetricOptions {
errors?: ErrorMessages;
}

const defaultOptions = {
errors,
};

export default class AccountsAsymmetric implements AuthenticationService {
public serviceName = 'asymmetric';
public server!: AccountsServer;
private db!: DatabaseInterface;
private options: AccountsAsymmetricOptions & typeof defaultOptions;

constructor(options: AccountsAsymmetricOptions = {}) {
this.options = { ...defaultOptions, ...options };
}

public setStore(store: DatabaseInterface) {
this.db = store;
}

public async updatePublicKey(
userId: string,
{ key, ...params }: PublicKeyType
): Promise<boolean> {
try {
await this.db.setService(userId, this.serviceName, { id: key, key, ...params });
return true;
} catch (e) {
return false;
}
}

public async authenticate(params: AsymmetricLoginType): Promise<any> {
const user = await this.db.findUserByServiceId(this.serviceName, params.publicKey);

if (!user) {
throw new Error(this.options.errors.userNotFound);
}

try {
const verify = crypto.createVerify(params.signatureAlgorithm);
verify.write(params.payload);
verify.end();

const publicKeyParams: PublicKeyType = (user.services as any)[this.serviceName];

const publicKey = crypto.createPublicKey({
key: Buffer.from(publicKeyParams.key, publicKeyParams.encoding),
format: publicKeyParams.format,
type: publicKeyParams.type,
});

const isVerified = verify.verify(publicKey, params.signature, params.signatureFormat);

return isVerified ? user : null;
} catch (e) {
throw new Error(this.options.errors.verificationFailed);
}
}
}
6 changes: 6 additions & 0 deletions packages/asymmetric/src/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { ErrorMessages } from './types';

export const errors: ErrorMessages = {
userNotFound: 'User not found',
verificationFailed: 'Failed to verify signature',
};
5 changes: 5 additions & 0 deletions packages/asymmetric/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import AccountsAsymmetric from './accounts-asymmetric';
export * from './types';

export default AccountsAsymmetric;
export { AccountsAsymmetric };
7 changes: 7 additions & 0 deletions packages/asymmetric/src/types/asymmetric-login-type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export interface AsymmetricLoginType {
publicKey: string;
signature: string;
signatureAlgorithm: 'sha256' | 'sha512';
signatureFormat: 'hex' | 'base64';
payload: string;
}
4 changes: 4 additions & 0 deletions packages/asymmetric/src/types/error-messages.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
export interface ErrorMessages {
userNotFound: string;
verificationFailed: string;
}
3 changes: 3 additions & 0 deletions packages/asymmetric/src/types/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from './asymmetric-login-type';
export * from './public-key-type';
export * from './error-messages';
6 changes: 6 additions & 0 deletions packages/asymmetric/src/types/public-key-type.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export interface PublicKeyType {
key: string;
encoding: 'utf8' | 'base64' | 'hex';
format: 'pem' | 'der';
type: 'pkcs1' | 'spki';
}
9 changes: 9 additions & 0 deletions packages/asymmetric/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"extends": "../../tsconfig",
"compilerOptions": {
"rootDir": "./src",
"outDir": "./lib",
"importHelpers": true
},
"exclude": ["node_modules", "__tests__", "lib"]
}