-
-
Notifications
You must be signed in to change notification settings - Fork 141
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
ozsay
wants to merge
6
commits into
accounts-js:master
Choose a base branch
from
ozsay:asymmetric-authentication
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 3 commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
23d2297
work
ozsay af5992d
Merge branch 'master' of github.com:accounts-js/accounts into asymmet…
ozsay 5b1d308
more work
ozsay 43296b4
fixes
ozsay 0b6fae7
Merge branch 'master' of github.com:accounts-js/accounts into asymmet…
ozsay 68183d7
make it work on node lts
ozsay File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
# @accounts/password | ||
|
||
[![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, | ||
} | ||
); | ||
``` |
5 changes: 5 additions & 0 deletions
5
packages/asymmetric/__tests__/__snapshots__/accounts-asymmetric.ts.snap
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]`; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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', | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
export interface ErrorMessages { | ||
userNotFound: string; | ||
verificationFailed: string; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"] | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
need to change that