├── .browserslistrc ├── .github ├── FUNDING.yml ├── stale.yml └── workflows │ └── npm-publish.yml ├── .gitignore ├── .npmignore ├── CODE_OF_CONDUCT.md ├── LICENSE ├── README.md ├── SECURITY.md ├── babel.config.js ├── index.js ├── jest.config.js ├── package-lock.json ├── package.json ├── src ├── common.js ├── useLogin.js ├── useLogin.test.js └── useRegistration.js └── webpack.config.js /.browserslistrc: -------------------------------------------------------------------------------- 1 | edge >= 18 2 | firefox >= 60 3 | chrome >= 67 4 | safari >= 13 5 | opera >= 54 6 | -------------------------------------------------------------------------------- /.github/FUNDING.yml: -------------------------------------------------------------------------------- 1 | github: Spomky 2 | patreon: FlorentMorselli 3 | -------------------------------------------------------------------------------- /.github/stale.yml: -------------------------------------------------------------------------------- 1 | daysUntilStale: 60 2 | daysUntilClose: 7 3 | staleLabel: wontfix 4 | markComment: > 5 | This issue has been automatically marked as stale because it has not had 6 | recent activity. It will be closed if no further activity occurs. Thank you 7 | for your contributions. 8 | closeComment: false 9 | -------------------------------------------------------------------------------- /.github/workflows/npm-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created 2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages 3 | 4 | name: Node.js Package 5 | 6 | on: 7 | release: 8 | types: [created] 9 | 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | - uses: actions/setup-node@v1 16 | with: 17 | node-version: 12 18 | - run: npm ci 19 | - run: npm test 20 | 21 | publish-npm: 22 | needs: build 23 | runs-on: ubuntu-latest 24 | steps: 25 | - uses: actions/checkout@v2 26 | - uses: actions/setup-node@v1 27 | with: 28 | node-version: 12 29 | registry-url: https://registry.npmjs.org/ 30 | - run: npm ci 31 | - run: npm run build 32 | - run: npm publish 33 | env: 34 | NODE_AUTH_TOKEN: ${{secrets.npm_token}} 35 | 36 | publish-gpr: 37 | needs: build 38 | runs-on: ubuntu-latest 39 | steps: 40 | - uses: actions/checkout@v2 41 | - uses: actions/setup-node@v1 42 | with: 43 | node-version: 12 44 | registry-url: https://npm.pkg.github.com/ 45 | - run: npm ci 46 | - run: npm run build 47 | - run: npm publish 48 | env: 49 | NODE_AUTH_TOKEN: ${{secrets.GITHUB_TOKEN}} 50 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | dist 3 | node_modules 4 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | # Created by .ignore support plugin (hsz.mobi) 2 | .idea 3 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. 6 | 7 | ## Our Standards 8 | 9 | Examples of behavior that contributes to creating a positive environment include: 10 | 11 | * Using welcoming and inclusive language 12 | * Being respectful of differing viewpoints and experiences 13 | * Gracefully accepting constructive criticism 14 | * Focusing on what is best for the community 15 | * Showing empathy towards other community members 16 | 17 | Examples of unacceptable behavior by participants include: 18 | 19 | * The use of sexualized language or imagery and unwelcome sexual attention or advances 20 | * Trolling, insulting/derogatory comments, and personal or political attacks 21 | * Public or private harassment 22 | * Publishing others' private information, such as a physical or electronic address, without explicit permission 23 | * Other conduct which could reasonably be considered inappropriate in a professional setting 24 | 25 | ## Our Responsibilities 26 | 27 | Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. 28 | 29 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. 30 | 31 | ## Scope 32 | 33 | This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. 34 | 35 | ## Enforcement 36 | 37 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at contact@spomky-labs.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. 38 | 39 | Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. 40 | 41 | ## Attribution 42 | 43 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] 44 | 45 | [homepage]: http://contributor-covenant.org 46 | [version]: http://contributor-covenant.org/version/1/4/ 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | The MIT License (MIT) 2 | 3 | Copyright (c) 2014-2019 Spomky-Labs 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Webauthn Helper 2 | =============== 3 | 4 | This package contains helper functions to handle Webauthn registration and authentication. 5 | It is primarily designed to be used with the Web-Auth Framework from Spomky-Labs. 6 | 7 | ---- 8 | 9 |

:warning::warning::warning:

10 | 11 | **This library is now deprecated and not maintained anymore. 12 | We highly recommend you to use the new [SimpleWebAuthn Project]([https://github.com/web-token/jwt-framework](https://github.com/MasterKale/SimpleWebAuthn)) as it offers lots of nice features and is fully compatible with the specification.** 13 | 14 |

:warning::warning::warning:

15 | 16 | 17 | # Installation 18 | 19 | With Yarn: 20 | 21 | ```sh 22 | yarn add @web-auth/webauthn-helper 23 | ``` 24 | # Usage 25 | 26 | ## Registration 27 | 28 | ```js 29 | // Import the tool(s) ou need 30 | import {useRegistration} from '@web-auth/webauthn-helper'; 31 | 32 | // We want to register new authenticators 33 | const register = useRegistration({ 34 | actionUrl: '/api/register', 35 | optionsUrl: '/api/register/options' 36 | }); 37 | 38 | register({ 39 | username: 'FOO4', 40 | displayName: 'baR' 41 | }) 42 | .then((response)=> console.log('Registration success')) 43 | .catch((error)=> console.log('Registration failure')) 44 | ; 45 | ``` 46 | 47 | ## Authentication 48 | 49 | ```js 50 | import {useLogin} from '@web-auth/webauthn-helper'; 51 | 52 | const login = useLogin({ 53 | actionUrl: '/api/login', 54 | optionsUrl: '/api/login/options' 55 | }); 56 | 57 | login({ 58 | username: 'FOO4' 59 | }) 60 | .then((response)=> console.log('Login success')) 61 | .catch((error)=> console.log('Login failure')) 62 | ; 63 | ``` 64 | 65 | ## Additional Header Parameters 66 | 67 | For both `useLogin` and `useRegistration` methods, you can add custom header parameters. 68 | 69 | ```js 70 | import {useLogin} from '@web-auth/webauthn-helper'; 71 | 72 | const login = useLogin({ 73 | loginUrl: '/api/login', 74 | actionHeader: { 75 | 'X-TOKEN': 'Secured-TOKEN!!!' 76 | }, 77 | loginOptions: '/api/login/options', 78 | optionsHeader: { 79 | 'X-TOKEN': 'Secured-TOKEN!!!', 80 | 'X-OTHER-PARAM': '1,2,3,4' 81 | } 82 | }); 83 | ``` 84 | 85 | 86 | # Support 87 | 88 | I bring solutions to your problems and answer your questions. 89 | 90 | If you really love that project, and the work I have done or if you want I prioritize your issues, then you can help me out for a couple of :beers: or more! 91 | 92 | [Become a sponsor](https://github.com/sponsors/Spomky) 93 | 94 | Or 95 | 96 | [![Become a Patreon](https://c5.patreon.com/external/logo/become_a_patron_button.png)](https://www.patreon.com/FlorentMorselli) 97 | 98 | # Contributing 99 | 100 | Requests for new features, bug fixed and all other ideas to make this framework useful are welcome. 101 | If you feel comfortable writing code, you could try to fix [opened issues where help is wanted](https://github.com/web-auth/webauthn-framework/issues?q=label%3A%22help+wanted%22) or [those that are easy to fix](https://github.com/web-auth/webauthn-framework/labels/easy-pick). 102 | 103 | Do not forget to [follow these best practices](.github/CONTRIBUTING.md). 104 | 105 | **If you think you have found a security issue, DO NOT open an issue**. [You MUST submit your issue here](https://gitter.im/Spomky/). 106 | 107 | # Licence 108 | 109 | This software is release under [MIT licence](LICENSE). 110 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | # Security Policy 2 | 3 | ## Supported Versions 4 | 5 | | Version | Supported | 6 | | ------- | ------------------ | 7 | | 0.0.x | :white_check_mark: | 8 | 9 | ## Reporting a Vulnerability 10 | 11 | If you think you have found a security issue, DO NOT open an issue. You MUST submit your issue at https://gitter.im/Spomky/. 12 | -------------------------------------------------------------------------------- /babel.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | presets: [ 3 | [ 4 | '@babel/preset-env', 5 | { 6 | targets: { 7 | node: 'current', 8 | }, 9 | }, 10 | ], 11 | ], 12 | }; 13 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import useLogin from "./src/useLogin"; 2 | import useRegistration from "./src/useRegistration"; 3 | 4 | export {useLogin, useRegistration}; 5 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | // For a detailed explanation regarding each configuration property, visit: 2 | // https://jestjs.io/docs/en/configuration.html 3 | 4 | module.exports = { 5 | // All imported modules in your tests should be mocked automatically 6 | // automock: false, 7 | 8 | // Stop running tests after `n` failures 9 | // bail: 0, 10 | 11 | // The directory where Jest should store its cached dependency information 12 | // cacheDirectory: "/tmp/jest_rs", 13 | 14 | // Automatically clear mock calls and instances between every test 15 | clearMocks: true, 16 | 17 | // Indicates whether the coverage information should be collected while executing the test 18 | // collectCoverage: false, 19 | 20 | // An array of glob patterns indicating a set of files for which coverage information should be collected 21 | // collectCoverageFrom: undefined, 22 | 23 | // The directory where Jest should output its coverage files 24 | // coverageDirectory: undefined, 25 | 26 | // An array of regexp pattern strings used to skip coverage collection 27 | // coveragePathIgnorePatterns: [ 28 | // "/node_modules/" 29 | // ], 30 | 31 | // Indicates which provider should be used to instrument code for coverage 32 | coverageProvider: "v8", 33 | 34 | // A list of reporter names that Jest uses when writing coverage reports 35 | // coverageReporters: [ 36 | // "json", 37 | // "text", 38 | // "lcov", 39 | // "clover" 40 | // ], 41 | 42 | // An object that configures minimum threshold enforcement for coverage results 43 | // coverageThreshold: undefined, 44 | 45 | // A path to a custom dependency extractor 46 | // dependencyExtractor: undefined, 47 | 48 | // Make calling deprecated APIs throw helpful error messages 49 | // errorOnDeprecated: false, 50 | 51 | // Force coverage collection from ignored files using an array of glob patterns 52 | // forceCoverageMatch: [], 53 | 54 | // A path to a module which exports an async function that is triggered once before all test suites 55 | // globalSetup: undefined, 56 | 57 | // A path to a module which exports an async function that is triggered once after all test suites 58 | // globalTeardown: undefined, 59 | 60 | // A set of global variables that need to be available in all test environments 61 | // globals: {}, 62 | 63 | // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers. 64 | // maxWorkers: "50%", 65 | 66 | // An array of directory names to be searched recursively up from the requiring module's location 67 | // moduleDirectories: [ 68 | // "node_modules" 69 | // ], 70 | 71 | // An array of file extensions your modules use 72 | // moduleFileExtensions: [ 73 | // "js", 74 | // "json", 75 | // "jsx", 76 | // "ts", 77 | // "tsx", 78 | // "node" 79 | // ], 80 | 81 | // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module 82 | // moduleNameMapper: {}, 83 | 84 | // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader 85 | // modulePathIgnorePatterns: [], 86 | 87 | // Activates notifications for test results 88 | // notify: false, 89 | 90 | // An enum that specifies notification mode. Requires { notify: true } 91 | // notifyMode: "failure-change", 92 | 93 | // A preset that is used as a base for Jest's configuration 94 | // preset: undefined, 95 | 96 | // Run tests from one or more projects 97 | // projects: undefined, 98 | 99 | // Use this configuration option to add custom reporters to Jest 100 | // reporters: undefined, 101 | 102 | // Automatically reset mock state between every test 103 | // resetMocks: false, 104 | 105 | // Reset the module registry before running each individual test 106 | // resetModules: false, 107 | 108 | // A path to a custom resolver 109 | // resolver: undefined, 110 | 111 | // Automatically restore mock state between every test 112 | // restoreMocks: false, 113 | 114 | // The root directory that Jest should scan for tests and modules within 115 | // rootDir: undefined, 116 | 117 | // A list of paths to directories that Jest should use to search for files in 118 | // roots: [ 119 | // "" 120 | // ], 121 | 122 | // Allows you to use a custom runner instead of Jest's default test runner 123 | // runner: "jest-runner", 124 | 125 | // The paths to modules that run some code to configure or set up the testing environment before each test 126 | // setupFiles: [], 127 | 128 | // A list of paths to modules that run some code to configure or set up the testing framework before each test 129 | // setupFilesAfterEnv: [], 130 | 131 | // The number of seconds after which a test is considered as slow and reported as such in the results. 132 | // slowTestThreshold: 5, 133 | 134 | // A list of paths to snapshot serializer modules Jest should use for snapshot testing 135 | // snapshotSerializers: [], 136 | 137 | // The test environment that will be used for testing 138 | // testEnvironment: "jest-environment-jsdom", 139 | 140 | // Options that will be passed to the testEnvironment 141 | // testEnvironmentOptions: {}, 142 | 143 | // Adds a location field to test results 144 | // testLocationInResults: false, 145 | 146 | // The glob patterns Jest uses to detect test files 147 | // testMatch: [ 148 | // "**/__tests__/**/*.[jt]s?(x)", 149 | // "**/?(*.)+(spec|test).[tj]s?(x)" 150 | // ], 151 | 152 | // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped 153 | // testPathIgnorePatterns: [ 154 | // "/node_modules/" 155 | // ], 156 | 157 | // The regexp pattern or array of patterns that Jest uses to detect test files 158 | // testRegex: [], 159 | 160 | // This option allows the use of a custom results processor 161 | // testResultsProcessor: undefined, 162 | 163 | // This option allows use of a custom test runner 164 | // testRunner: "jasmine2", 165 | 166 | // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href 167 | // testURL: "http://localhost", 168 | 169 | // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout" 170 | // timers: "real", 171 | 172 | // A map from regular expressions to paths to transformers 173 | // transform: undefined, 174 | 175 | // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation 176 | // transformIgnorePatterns: [ 177 | // "/node_modules/" 178 | // ], 179 | 180 | // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them 181 | // unmockedModulePathPatterns: undefined, 182 | 183 | // Indicates whether each individual test should be reported during the run 184 | // verbose: undefined, 185 | 186 | // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode 187 | // watchPathIgnorePatterns: [], 188 | 189 | // Whether to use watchman for file crawling 190 | // watchman: true, 191 | }; 192 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@web-auth/webauthn-helper", 3 | "version": "0.0.13", 4 | "description": "JS functions to ease the use of the Spomky-Labs library and Symfony bundle", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "jest", 8 | "build": "webpack --mode=production", 9 | "watch": "webpack --watch --mode=development" 10 | }, 11 | "repository": { 12 | "type": "git", 13 | "url": "git+https://github.com/web-auth/webauthn-helper.git" 14 | }, 15 | "keywords": [ 16 | "webauthn" 17 | ], 18 | "author": "Spomky", 19 | "license": "MIT", 20 | "bugs": { 21 | "url": "https://github.com/web-auth/webauthn-helper/issues" 22 | }, 23 | "homepage": "https://github.com/web-auth/webauthn-helper", 24 | "devDependencies": { 25 | "@babel/core": "^7.10.5", 26 | "@babel/preset-env": "^7.10.4", 27 | "@types/jest": "^26.0.7", 28 | "babel-jest": "^26.2.1", 29 | "babel-loader": "^8.1.0", 30 | "core-js": "^3.6.5", 31 | "jest": "^26.2.1", 32 | "webpack": "^4.44.1", 33 | "webpack-cli": "^3.3.12" 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /src/common.js: -------------------------------------------------------------------------------- 1 | // Predefined fetch function 2 | export const fetchEndpoint = (data, url, header) => { 3 | return fetch( 4 | url, 5 | { 6 | method: 'POST', 7 | credentials: 'same-origin', 8 | redirect: 'error', 9 | headers: { 10 | 'Content-Type': 'application/json', 11 | 'Accept': 'application/json', 12 | ...header 13 | }, 14 | body: JSON.stringify(data), 15 | } 16 | ); 17 | } 18 | 19 | // Decodes a Base64Url string 20 | const base64UrlDecode = (input) => { 21 | input = input 22 | .replace(/-/g, '+') 23 | .replace(/_/g, '/'); 24 | 25 | const pad = input.length % 4; 26 | if (pad) { 27 | if (pad === 1) { 28 | throw new Error('InvalidLengthError: Input base64url string is the wrong length to determine padding'); 29 | } 30 | input += new Array(5-pad).join('='); 31 | } 32 | 33 | return window.atob(input); 34 | }; 35 | 36 | // Converts an array of bytes into a Base64Url string 37 | const arrayToBase64String = (a) => btoa(String.fromCharCode(...a)); 38 | 39 | // Prepares the public key options object returned by the Webauthn Framework 40 | export const preparePublicKeyOptions = publicKey => { 41 | //Convert challenge from Base64Url string to Uint8Array 42 | publicKey.challenge = Uint8Array.from( 43 | base64UrlDecode(publicKey.challenge), 44 | c => c.charCodeAt(0) 45 | ); 46 | 47 | //Convert the user ID from Base64 string to Uint8Array 48 | if (publicKey.user !== undefined) { 49 | publicKey.user = { 50 | ...publicKey.user, 51 | id: Uint8Array.from( 52 | window.atob(publicKey.user.id), 53 | c => c.charCodeAt(0) 54 | ), 55 | }; 56 | } 57 | 58 | //If excludeCredentials is defined, we convert all IDs to Uint8Array 59 | if (publicKey.excludeCredentials !== undefined) { 60 | publicKey.excludeCredentials = publicKey.excludeCredentials.map( 61 | data => { 62 | return { 63 | ...data, 64 | id: Uint8Array.from( 65 | base64UrlDecode(data.id), 66 | c => c.charCodeAt(0) 67 | ), 68 | }; 69 | } 70 | ); 71 | } 72 | 73 | if (publicKey.allowCredentials !== undefined) { 74 | publicKey.allowCredentials = publicKey.allowCredentials.map( 75 | data => { 76 | return { 77 | ...data, 78 | id: Uint8Array.from( 79 | base64UrlDecode(data.id), 80 | c => c.charCodeAt(0) 81 | ), 82 | }; 83 | } 84 | ); 85 | } 86 | 87 | return publicKey; 88 | }; 89 | 90 | // Prepares the public key credentials object returned by the authenticator 91 | export const preparePublicKeyCredentials = data => { 92 | const publicKeyCredential = { 93 | id: data.id, 94 | type: data.type, 95 | rawId: arrayToBase64String(new Uint8Array(data.rawId)), 96 | response: { 97 | clientDataJSON: arrayToBase64String( 98 | new Uint8Array(data.response.clientDataJSON) 99 | ), 100 | }, 101 | }; 102 | 103 | if (data.response.attestationObject !== undefined) { 104 | publicKeyCredential.response.attestationObject = arrayToBase64String( 105 | new Uint8Array(data.response.attestationObject) 106 | ); 107 | } 108 | 109 | if (data.response.authenticatorData !== undefined) { 110 | publicKeyCredential.response.authenticatorData = arrayToBase64String( 111 | new Uint8Array(data.response.authenticatorData) 112 | ); 113 | } 114 | 115 | if (data.response.signature !== undefined) { 116 | publicKeyCredential.response.signature = arrayToBase64String( 117 | new Uint8Array(data.response.signature) 118 | ); 119 | } 120 | 121 | if (data.response.userHandle !== undefined) { 122 | publicKeyCredential.response.userHandle = arrayToBase64String( 123 | new Uint8Array(data.response.userHandle) 124 | ); 125 | } 126 | 127 | return publicKeyCredential; 128 | }; 129 | -------------------------------------------------------------------------------- /src/useLogin.js: -------------------------------------------------------------------------------- 1 | import { 2 | fetchEndpoint, 3 | preparePublicKeyCredentials, 4 | preparePublicKeyOptions, 5 | } from './common'; 6 | 7 | const useLogin = ({actionUrl = '/login', actionHeader = {}, optionsUrl = '/login/options', optionsHeader = {}}) => { 8 | return async (data) => { 9 | const optionsResponse = await fetchEndpoint(data, optionsUrl, optionsHeader); 10 | const json = await optionsResponse.json(); 11 | const publicKey = preparePublicKeyOptions(json); 12 | const credentials = await navigator.credentials.get({publicKey}); 13 | const publicKeyCredential = preparePublicKeyCredentials(credentials); 14 | const actionResponse = await fetchEndpoint(publicKeyCredential, actionUrl, actionHeader); 15 | if (! actionResponse.ok) { 16 | throw actionResponse; 17 | } 18 | const responseBody = await actionResponse.text(); 19 | 20 | return responseBody !== '' ? JSON.parse(responseBody) : responseBody; 21 | }; 22 | }; 23 | 24 | export default useLogin; 25 | -------------------------------------------------------------------------------- /src/useLogin.test.js: -------------------------------------------------------------------------------- 1 | import useLogin from "./useLogin"; 2 | 3 | describe('Login', () => { 4 | global.navigator.credentials = { 5 | get: jest.fn(() => Promise.resolve({ 6 | "rawId": "AZD7huwZVx7aW1efRa6Uq3JTQNorj3qA9yrLINXEcgvCQYtWiSQa1eOIVrXfCmip6MzP8KaITOvRLjy3TUHO7/c", 7 | "id": "AZD7huwZVx7aW1efRa6Uq3JTQNorj3qA9yrLINXEcgvCQYtWiSQa1eOIVrXfCmip6MzP8KaITOvRLjy3TUHO7/c", 8 | "response": { 9 | "clientDataJSON": "eyJ0eXBlIjoid2ViYXV0aG4uY3JlYXRlIiwiY2hhbGxlbmdlIjoiVGY2NWJTNkQ1dGVtaDJCd3ZwdHFnQlBiMjVpWkRSeGp3QzVhbnM5MUlJSkRyY3JPcG5XVEs0TFZnRmplVVY0R0RNZTQ0dzhTSTVOc1pzc0lYVFV2RGciLCJvcmlnaW4iOiJodHRwczpcL1wvd2ViYXV0aG4ub3JnIiwiYW5kcm9pZFBhY2thZ2VOYW1lIjoiY29tLm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 15 | global.fetch = jest.fn(() => { 16 | return Promise.resolve({ 17 | ok: true, 18 | text: () => Promise.resolve('{"status":"ok","errorMessage":""}'), 19 | json: () => Promise.resolve({ 20 | "status":"ok", 21 | "errorMessage":"", 22 | "rp":{ 23 | "name":"Webauthn Demo", 24 | "id":"webauthn.spomky-labs.com" 25 | }, 26 | "pubKeyCredParams":[ 27 | {"type":"public-key","alg":-8}, 28 | {"type":"public-key","alg":-7}, 29 | {"type":"public-key","alg":-43}, 30 | {"type":"public-key","alg":-35}, 31 | {"type":"public-key","alg":-36}, 32 | {"type":"public-key","alg":-257}, 33 | {"type":"public-key","alg":-258}, 34 | {"type":"public-key","alg":-259}, 35 | {"type":"public-key","alg":-37}, 36 | {"type":"public-key","alg":-38}, 37 | {"type":"public-key","alg":-39} 38 | ], 39 | "challenge":"KhWQ12Gltp92RModoTPgDqpgXCvR73JXKozijHIfwHE", 40 | "attestation":"direct", 41 | "user":{ 42 | "name":"hw1BfGxhRSKwTOAIx39K", 43 | "id":"NzExYmI2ZTItYmU3My00YTcyLWE1MDUtYTQzYWE3ZTUyYzgw", 44 | "displayName":"Leona Grayson" 45 | }, 46 | "authenticatorSelection":{ 47 | "requireResidentKey":false, 48 | "userVerification":"preferred" 49 | }, 50 | "timeout":60000 51 | }), 52 | }) 53 | } 54 | ); 55 | 56 | beforeEach(() => { 57 | fetch.mockClear(); 58 | }); 59 | const login = useLogin({ 60 | actionUrl: '/login', 61 | optionsUrl: '/login/options' 62 | }); 63 | 64 | it('should log me in when the assertion is valid', () => { 65 | expect(login({username: 'foo'})).resolves.toEqual({"status":"ok","errorMessage":""}) 66 | }) 67 | }); 68 | -------------------------------------------------------------------------------- /src/useRegistration.js: -------------------------------------------------------------------------------- 1 | import { 2 | fetchEndpoint, 3 | preparePublicKeyCredentials, 4 | preparePublicKeyOptions, 5 | } from './common'; 6 | 7 | const useRegistration = ({actionUrl = '/register', actionHeader = {}, optionsUrl = '/register/options', optionsHeader = {}}) => { 8 | return async (data) => { 9 | const optionsResponse = await fetchEndpoint(data, optionsUrl, optionsHeader); 10 | const json = await optionsResponse.json(); 11 | const publicKey = preparePublicKeyOptions(json); 12 | const credentials = await navigator.credentials.create({publicKey}); 13 | const publicKeyCredential = preparePublicKeyCredentials(credentials); 14 | const actionResponse = await fetchEndpoint(publicKeyCredential, actionUrl, actionHeader); 15 | if (! actionResponse.ok) { 16 | throw actionResponse; 17 | } 18 | const responseBody = await actionResponse.text(); 19 | 20 | return responseBody !== '' ? JSON.parse(responseBody) : responseBody; 21 | }; 22 | }; 23 | 24 | export default useRegistration; 25 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require('path'); 2 | 3 | module.exports = { 4 | entry: './index.js', 5 | output: { 6 | path: path.resolve(__dirname, 'dist'), 7 | filename: 'webauthn.js' 8 | }, 9 | module: { 10 | rules: [ 11 | { 12 | test: /\.js$/, 13 | exclude: /node_modules/, 14 | use: { 15 | loader: 'babel-loader', 16 | options: { 17 | presets: [ 18 | [ 19 | '@babel/preset-env', 20 | { 21 | useBuiltIns: 'usage', 22 | corejs: 3 23 | } 24 | ] 25 | ] 26 | } 27 | } 28 | } 29 | ] 30 | } 31 | }; 32 | --------------------------------------------------------------------------------