@simplewebauthn/browser 11.0.0 → 12.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/README.md +34 -24
  2. package/dist/bundle/index.es5.umd.min.js +2 -2
  3. package/dist/bundle/index.umd.min.js +2 -2
  4. package/esm/helpers/base64URLStringToBuffer.d.ts +9 -0
  5. package/esm/helpers/base64URLStringToBuffer.d.ts.map +1 -0
  6. package/esm/helpers/base64URLStringToBuffer.js +29 -0
  7. package/esm/helpers/browserSupportsWebAuthn.d.ts +8 -0
  8. package/esm/helpers/browserSupportsWebAuthn.d.ts.map +1 -0
  9. package/esm/helpers/browserSupportsWebAuthn.js +11 -0
  10. package/esm/helpers/browserSupportsWebAuthnAutofill.d.ts +9 -0
  11. package/esm/helpers/browserSupportsWebAuthnAutofill.d.ts.map +1 -0
  12. package/esm/helpers/browserSupportsWebAuthnAutofill.js +26 -0
  13. package/esm/helpers/bufferToBase64URLString.d.ts +8 -0
  14. package/esm/helpers/bufferToBase64URLString.d.ts.map +1 -0
  15. package/esm/helpers/bufferToBase64URLString.js +15 -0
  16. package/esm/helpers/identifyAuthenticationError.d.ts +9 -0
  17. package/esm/helpers/identifyAuthenticationError.d.ts.map +1 -0
  18. package/esm/helpers/identifyAuthenticationError.js +61 -0
  19. package/esm/helpers/identifyRegistrationError.d.ts +9 -0
  20. package/esm/helpers/identifyRegistrationError.d.ts.map +1 -0
  21. package/esm/helpers/identifyRegistrationError.js +126 -0
  22. package/esm/helpers/isValidDomain.d.ts +10 -0
  23. package/esm/helpers/isValidDomain.d.ts.map +1 -0
  24. package/esm/helpers/isValidDomain.js +14 -0
  25. package/esm/helpers/platformAuthenticatorIsAvailable.d.ts +8 -0
  26. package/esm/helpers/platformAuthenticatorIsAvailable.d.ts.map +1 -0
  27. package/esm/helpers/platformAuthenticatorIsAvailable.js +13 -0
  28. package/{dist/types → esm}/helpers/toAuthenticatorAttachment.d.ts +4 -0
  29. package/esm/helpers/toAuthenticatorAttachment.d.ts.map +1 -0
  30. package/esm/helpers/toAuthenticatorAttachment.js +13 -0
  31. package/esm/helpers/toPublicKeyCredentialDescriptor.d.ts +3 -0
  32. package/esm/helpers/toPublicKeyCredentialDescriptor.d.ts.map +1 -0
  33. package/esm/helpers/toPublicKeyCredentialDescriptor.js +14 -0
  34. package/esm/helpers/webAuthnAbortService.d.ts +14 -0
  35. package/esm/helpers/webAuthnAbortService.d.ts.map +1 -0
  36. package/esm/helpers/webAuthnAbortService.js +45 -0
  37. package/{dist/types → esm}/helpers/webAuthnError.d.ts +18 -0
  38. package/esm/helpers/webAuthnError.d.ts.map +1 -0
  39. package/esm/helpers/webAuthnError.js +31 -0
  40. package/esm/index.d.ts +16 -0
  41. package/esm/index.d.ts.map +1 -0
  42. package/{dist/types/index.d.ts → esm/index.js} +13 -10
  43. package/esm/methods/startAuthentication.d.ts +15 -0
  44. package/esm/methods/startAuthentication.d.ts.map +1 -0
  45. package/esm/methods/startAuthentication.js +89 -0
  46. package/esm/methods/startRegistration.d.ts +13 -0
  47. package/esm/methods/startRegistration.d.ts.map +1 -0
  48. package/esm/methods/startRegistration.js +115 -0
  49. package/esm/package.json +3 -0
  50. package/package.json +25 -29
  51. package/script/helpers/base64URLStringToBuffer.d.ts +9 -0
  52. package/script/helpers/base64URLStringToBuffer.d.ts.map +1 -0
  53. package/script/helpers/base64URLStringToBuffer.js +32 -0
  54. package/script/helpers/browserSupportsWebAuthn.d.ts +8 -0
  55. package/script/helpers/browserSupportsWebAuthn.d.ts.map +1 -0
  56. package/script/helpers/browserSupportsWebAuthn.js +15 -0
  57. package/script/helpers/browserSupportsWebAuthnAutofill.d.ts +9 -0
  58. package/script/helpers/browserSupportsWebAuthnAutofill.d.ts.map +1 -0
  59. package/script/helpers/browserSupportsWebAuthnAutofill.js +30 -0
  60. package/script/helpers/bufferToBase64URLString.d.ts +8 -0
  61. package/script/helpers/bufferToBase64URLString.d.ts.map +1 -0
  62. package/script/helpers/bufferToBase64URLString.js +18 -0
  63. package/script/helpers/identifyAuthenticationError.d.ts +9 -0
  64. package/script/helpers/identifyAuthenticationError.d.ts.map +1 -0
  65. package/script/helpers/identifyAuthenticationError.js +64 -0
  66. package/script/helpers/identifyRegistrationError.d.ts +9 -0
  67. package/script/helpers/identifyRegistrationError.d.ts.map +1 -0
  68. package/script/helpers/identifyRegistrationError.js +129 -0
  69. package/script/helpers/isValidDomain.d.ts +10 -0
  70. package/script/helpers/isValidDomain.d.ts.map +1 -0
  71. package/script/helpers/isValidDomain.js +17 -0
  72. package/script/helpers/platformAuthenticatorIsAvailable.d.ts +8 -0
  73. package/script/helpers/platformAuthenticatorIsAvailable.d.ts.map +1 -0
  74. package/script/helpers/platformAuthenticatorIsAvailable.js +16 -0
  75. package/script/helpers/toAuthenticatorAttachment.d.ts +6 -0
  76. package/script/helpers/toAuthenticatorAttachment.d.ts.map +1 -0
  77. package/script/helpers/toAuthenticatorAttachment.js +16 -0
  78. package/script/helpers/toPublicKeyCredentialDescriptor.d.ts +3 -0
  79. package/script/helpers/toPublicKeyCredentialDescriptor.d.ts.map +1 -0
  80. package/script/helpers/toPublicKeyCredentialDescriptor.js +17 -0
  81. package/script/helpers/webAuthnAbortService.d.ts +14 -0
  82. package/script/helpers/webAuthnAbortService.d.ts.map +1 -0
  83. package/script/helpers/webAuthnAbortService.js +48 -0
  84. package/script/helpers/webAuthnError.d.ts +28 -0
  85. package/script/helpers/webAuthnError.d.ts.map +1 -0
  86. package/script/helpers/webAuthnError.js +35 -0
  87. package/script/index.d.ts +16 -0
  88. package/script/index.d.ts.map +1 -0
  89. package/script/index.js +25 -0
  90. package/script/methods/startAuthentication.d.ts +15 -0
  91. package/script/methods/startAuthentication.d.ts.map +1 -0
  92. package/script/methods/startAuthentication.js +92 -0
  93. package/script/methods/startRegistration.d.ts +13 -0
  94. package/script/methods/startRegistration.d.ts.map +1 -0
  95. package/script/methods/startRegistration.js +118 -0
  96. package/script/package.json +3 -0
  97. package/dist/bundle/index.js +0 -398
  98. package/dist/types/helpers/base64URLStringToBuffer.d.ts +0 -1
  99. package/dist/types/helpers/browserSupportsWebAuthn.d.ts +0 -1
  100. package/dist/types/helpers/browserSupportsWebAuthnAutofill.d.ts +0 -1
  101. package/dist/types/helpers/bufferToBase64URLString.d.ts +0 -1
  102. package/dist/types/helpers/identifyAuthenticationError.d.ts +0 -5
  103. package/dist/types/helpers/identifyRegistrationError.d.ts +0 -5
  104. package/dist/types/helpers/isValidDomain.d.ts +0 -1
  105. package/dist/types/helpers/platformAuthenticatorIsAvailable.d.ts +0 -1
  106. package/dist/types/helpers/toPublicKeyCredentialDescriptor.d.ts +0 -2
  107. package/dist/types/helpers/webAuthnAbortService.d.ts +0 -7
  108. package/dist/types/methods/startAuthentication.d.ts +0 -7
  109. package/dist/types/methods/startRegistration.d.ts +0 -6
  110. package/jest-environment.js +0 -29
@@ -0,0 +1,15 @@
1
+ import { AuthenticationResponseJSON, PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/types';
2
+ export type StartAuthenticationOpts = {
3
+ optionsJSON: PublicKeyCredentialRequestOptionsJSON;
4
+ useBrowserAutofill?: boolean;
5
+ verifyBrowserAutofillInput?: boolean;
6
+ };
7
+ /**
8
+ * Begin authenticator "login" via WebAuthn assertion
9
+ *
10
+ * @param optionsJSON Output from **@simplewebauthn/server**'s `generateAuthenticationOptions()`
11
+ * @param useBrowserAutofill (Optional) Initialize conditional UI to enable logging in via browser autofill prompts. Defaults to `false`.
12
+ * @param verifyBrowserAutofillInput (Optional) Ensure a suitable `<input>` element is present when `useBrowserAutofill` is `true`. Defaults to `true`.
13
+ */
14
+ export declare function startAuthentication(options: StartAuthenticationOpts): Promise<AuthenticationResponseJSON>;
15
+ //# sourceMappingURL=startAuthentication.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"startAuthentication.d.ts","sourceRoot":"","sources":["../../src/methods/startAuthentication.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,0BAA0B,EAC1B,qCAAqC,EACtC,MAAM,uBAAuB,CAAC;AAW/B,MAAM,MAAM,uBAAuB,GAAG;IACpC,WAAW,EAAE,qCAAqC,CAAC;IACnD,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,0BAA0B,CAAC,EAAE,OAAO,CAAC;CACtC,CAAC;AAEF;;;;;;GAMG;AACH,wBAAsB,mBAAmB,CACvC,OAAO,EAAE,uBAAuB,GAC/B,OAAO,CAAC,0BAA0B,CAAC,CAkGrC"}
@@ -0,0 +1,92 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.startAuthentication = startAuthentication;
4
+ const bufferToBase64URLString_js_1 = require("../helpers/bufferToBase64URLString.js");
5
+ const base64URLStringToBuffer_js_1 = require("../helpers/base64URLStringToBuffer.js");
6
+ const browserSupportsWebAuthn_js_1 = require("../helpers/browserSupportsWebAuthn.js");
7
+ const browserSupportsWebAuthnAutofill_js_1 = require("../helpers/browserSupportsWebAuthnAutofill.js");
8
+ const toPublicKeyCredentialDescriptor_js_1 = require("../helpers/toPublicKeyCredentialDescriptor.js");
9
+ const identifyAuthenticationError_js_1 = require("../helpers/identifyAuthenticationError.js");
10
+ const webAuthnAbortService_js_1 = require("../helpers/webAuthnAbortService.js");
11
+ const toAuthenticatorAttachment_js_1 = require("../helpers/toAuthenticatorAttachment.js");
12
+ /**
13
+ * Begin authenticator "login" via WebAuthn assertion
14
+ *
15
+ * @param optionsJSON Output from **@simplewebauthn/server**'s `generateAuthenticationOptions()`
16
+ * @param useBrowserAutofill (Optional) Initialize conditional UI to enable logging in via browser autofill prompts. Defaults to `false`.
17
+ * @param verifyBrowserAutofillInput (Optional) Ensure a suitable `<input>` element is present when `useBrowserAutofill` is `true`. Defaults to `true`.
18
+ */
19
+ async function startAuthentication(options) {
20
+ const { optionsJSON, useBrowserAutofill = false, verifyBrowserAutofillInput = true, } = options;
21
+ if (!(0, browserSupportsWebAuthn_js_1.browserSupportsWebAuthn)()) {
22
+ throw new Error('WebAuthn is not supported in this browser');
23
+ }
24
+ // We need to avoid passing empty array to avoid blocking retrieval
25
+ // of public key
26
+ let allowCredentials;
27
+ if (optionsJSON.allowCredentials?.length !== 0) {
28
+ allowCredentials = optionsJSON.allowCredentials?.map(toPublicKeyCredentialDescriptor_js_1.toPublicKeyCredentialDescriptor);
29
+ }
30
+ // We need to convert some values to Uint8Arrays before passing the credentials to the navigator
31
+ const publicKey = {
32
+ ...optionsJSON,
33
+ challenge: (0, base64URLStringToBuffer_js_1.base64URLStringToBuffer)(optionsJSON.challenge),
34
+ allowCredentials,
35
+ };
36
+ // Prepare options for `.get()`
37
+ const getOptions = {};
38
+ /**
39
+ * Set up the page to prompt the user to select a credential for authentication via the browser's
40
+ * input autofill mechanism.
41
+ */
42
+ if (useBrowserAutofill) {
43
+ if (!(await (0, browserSupportsWebAuthnAutofill_js_1.browserSupportsWebAuthnAutofill)())) {
44
+ throw Error('Browser does not support WebAuthn autofill');
45
+ }
46
+ // Check for an <input> with "webauthn" in its `autocomplete` attribute
47
+ const eligibleInputs = document.querySelectorAll("input[autocomplete$='webauthn']");
48
+ // WebAuthn autofill requires at least one valid input
49
+ if (eligibleInputs.length < 1 && verifyBrowserAutofillInput) {
50
+ throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');
51
+ }
52
+ // `CredentialMediationRequirement` doesn't know about "conditional" yet as of
53
+ // typescript@4.6.3
54
+ getOptions.mediation = 'conditional';
55
+ // Conditional UI requires an empty allow list
56
+ publicKey.allowCredentials = [];
57
+ }
58
+ // Finalize options
59
+ getOptions.publicKey = publicKey;
60
+ // Set up the ability to cancel this request if the user attempts another
61
+ getOptions.signal = webAuthnAbortService_js_1.WebAuthnAbortService.createNewAbortSignal();
62
+ // Wait for the user to complete assertion
63
+ let credential;
64
+ try {
65
+ credential = (await navigator.credentials.get(getOptions));
66
+ }
67
+ catch (err) {
68
+ throw (0, identifyAuthenticationError_js_1.identifyAuthenticationError)({ error: err, options: getOptions });
69
+ }
70
+ if (!credential) {
71
+ throw new Error('Authentication was not completed');
72
+ }
73
+ const { id, rawId, response, type } = credential;
74
+ let userHandle = undefined;
75
+ if (response.userHandle) {
76
+ userHandle = (0, bufferToBase64URLString_js_1.bufferToBase64URLString)(response.userHandle);
77
+ }
78
+ // Convert values to base64 to make it easier to send back to the server
79
+ return {
80
+ id,
81
+ rawId: (0, bufferToBase64URLString_js_1.bufferToBase64URLString)(rawId),
82
+ response: {
83
+ authenticatorData: (0, bufferToBase64URLString_js_1.bufferToBase64URLString)(response.authenticatorData),
84
+ clientDataJSON: (0, bufferToBase64URLString_js_1.bufferToBase64URLString)(response.clientDataJSON),
85
+ signature: (0, bufferToBase64URLString_js_1.bufferToBase64URLString)(response.signature),
86
+ userHandle,
87
+ },
88
+ type,
89
+ clientExtensionResults: credential.getClientExtensionResults(),
90
+ authenticatorAttachment: (0, toAuthenticatorAttachment_js_1.toAuthenticatorAttachment)(credential.authenticatorAttachment),
91
+ };
92
+ }
@@ -0,0 +1,13 @@
1
+ import { PublicKeyCredentialCreationOptionsJSON, RegistrationResponseJSON } from '@simplewebauthn/types';
2
+ export type StartRegistrationOpts = {
3
+ optionsJSON: PublicKeyCredentialCreationOptionsJSON;
4
+ useAutoRegister?: boolean;
5
+ };
6
+ /**
7
+ * Begin authenticator "registration" via WebAuthn attestation
8
+ *
9
+ * @param optionsJSON Output from **@simplewebauthn/server**'s `generateRegistrationOptions()`
10
+ * @param useAutoRegister (Optional) Try to silently create a passkey with the password manager that the user just signed in with. Defaults to `false`.
11
+ */
12
+ export declare function startRegistration(options: StartRegistrationOpts): Promise<RegistrationResponseJSON>;
13
+ //# sourceMappingURL=startRegistration.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"startRegistration.d.ts","sourceRoot":"","sources":["../../src/methods/startRegistration.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,sCAAsC,EAEtC,wBAAwB,EACzB,MAAM,uBAAuB,CAAC;AAU/B,MAAM,MAAM,qBAAqB,GAAG;IAClC,WAAW,EAAE,sCAAsC,CAAC;IACpD,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B,CAAC;AAEF;;;;;GAKG;AACH,wBAAsB,iBAAiB,CACrC,OAAO,EAAE,qBAAqB,GAC7B,OAAO,CAAC,wBAAwB,CAAC,CA6GnC"}
@@ -0,0 +1,118 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.startRegistration = startRegistration;
4
+ const bufferToBase64URLString_js_1 = require("../helpers/bufferToBase64URLString.js");
5
+ const base64URLStringToBuffer_js_1 = require("../helpers/base64URLStringToBuffer.js");
6
+ const browserSupportsWebAuthn_js_1 = require("../helpers/browserSupportsWebAuthn.js");
7
+ const toPublicKeyCredentialDescriptor_js_1 = require("../helpers/toPublicKeyCredentialDescriptor.js");
8
+ const identifyRegistrationError_js_1 = require("../helpers/identifyRegistrationError.js");
9
+ const webAuthnAbortService_js_1 = require("../helpers/webAuthnAbortService.js");
10
+ const toAuthenticatorAttachment_js_1 = require("../helpers/toAuthenticatorAttachment.js");
11
+ /**
12
+ * Begin authenticator "registration" via WebAuthn attestation
13
+ *
14
+ * @param optionsJSON Output from **@simplewebauthn/server**'s `generateRegistrationOptions()`
15
+ * @param useAutoRegister (Optional) Try to silently create a passkey with the password manager that the user just signed in with. Defaults to `false`.
16
+ */
17
+ async function startRegistration(options) {
18
+ const { optionsJSON, useAutoRegister = false } = options;
19
+ if (!(0, browserSupportsWebAuthn_js_1.browserSupportsWebAuthn)()) {
20
+ throw new Error('WebAuthn is not supported in this browser');
21
+ }
22
+ // We need to convert some values to Uint8Arrays before passing the credentials to the navigator
23
+ const publicKey = {
24
+ ...optionsJSON,
25
+ challenge: (0, base64URLStringToBuffer_js_1.base64URLStringToBuffer)(optionsJSON.challenge),
26
+ user: {
27
+ ...optionsJSON.user,
28
+ id: (0, base64URLStringToBuffer_js_1.base64URLStringToBuffer)(optionsJSON.user.id),
29
+ },
30
+ excludeCredentials: optionsJSON.excludeCredentials?.map(toPublicKeyCredentialDescriptor_js_1.toPublicKeyCredentialDescriptor),
31
+ };
32
+ // Prepare options for `.create()`
33
+ const createOptions = {};
34
+ /**
35
+ * Try to use conditional create to register a passkey for the user with the password manager
36
+ * the user just used to authenticate with. The user won't be shown any prominent UI by the
37
+ * browser.
38
+ */
39
+ if (useAutoRegister) {
40
+ // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024
41
+ createOptions.mediation = 'conditional';
42
+ }
43
+ // Finalize options
44
+ createOptions.publicKey = publicKey;
45
+ // Set up the ability to cancel this request if the user attempts another
46
+ createOptions.signal = webAuthnAbortService_js_1.WebAuthnAbortService.createNewAbortSignal();
47
+ // Wait for the user to complete attestation
48
+ let credential;
49
+ try {
50
+ credential = (await navigator.credentials.create(createOptions));
51
+ }
52
+ catch (err) {
53
+ throw (0, identifyRegistrationError_js_1.identifyRegistrationError)({ error: err, options: createOptions });
54
+ }
55
+ if (!credential) {
56
+ throw new Error('Registration was not completed');
57
+ }
58
+ const { id, rawId, response, type } = credential;
59
+ // Continue to play it safe with `getTransports()` for now, even when L3 types say it's required
60
+ let transports = undefined;
61
+ if (typeof response.getTransports === 'function') {
62
+ transports = response.getTransports();
63
+ }
64
+ // L3 says this is required, but browser and webview support are still not guaranteed.
65
+ let responsePublicKeyAlgorithm = undefined;
66
+ if (typeof response.getPublicKeyAlgorithm === 'function') {
67
+ try {
68
+ responsePublicKeyAlgorithm = response.getPublicKeyAlgorithm();
69
+ }
70
+ catch (error) {
71
+ warnOnBrokenImplementation('getPublicKeyAlgorithm()', error);
72
+ }
73
+ }
74
+ let responsePublicKey = undefined;
75
+ if (typeof response.getPublicKey === 'function') {
76
+ try {
77
+ const _publicKey = response.getPublicKey();
78
+ if (_publicKey !== null) {
79
+ responsePublicKey = (0, bufferToBase64URLString_js_1.bufferToBase64URLString)(_publicKey);
80
+ }
81
+ }
82
+ catch (error) {
83
+ warnOnBrokenImplementation('getPublicKey()', error);
84
+ }
85
+ }
86
+ // L3 says this is required, but browser and webview support are still not guaranteed.
87
+ let responseAuthenticatorData;
88
+ if (typeof response.getAuthenticatorData === 'function') {
89
+ try {
90
+ responseAuthenticatorData = (0, bufferToBase64URLString_js_1.bufferToBase64URLString)(response.getAuthenticatorData());
91
+ }
92
+ catch (error) {
93
+ warnOnBrokenImplementation('getAuthenticatorData()', error);
94
+ }
95
+ }
96
+ return {
97
+ id,
98
+ rawId: (0, bufferToBase64URLString_js_1.bufferToBase64URLString)(rawId),
99
+ response: {
100
+ attestationObject: (0, bufferToBase64URLString_js_1.bufferToBase64URLString)(response.attestationObject),
101
+ clientDataJSON: (0, bufferToBase64URLString_js_1.bufferToBase64URLString)(response.clientDataJSON),
102
+ transports,
103
+ publicKeyAlgorithm: responsePublicKeyAlgorithm,
104
+ publicKey: responsePublicKey,
105
+ authenticatorData: responseAuthenticatorData,
106
+ },
107
+ type,
108
+ clientExtensionResults: credential.getClientExtensionResults(),
109
+ authenticatorAttachment: (0, toAuthenticatorAttachment_js_1.toAuthenticatorAttachment)(credential.authenticatorAttachment),
110
+ };
111
+ }
112
+ /**
113
+ * Visibly warn when we detect an issue related to a passkey provider intercepting WebAuthn API
114
+ * calls
115
+ */
116
+ function warnOnBrokenImplementation(methodName, cause) {
117
+ console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${methodName}. You should report this error to them.\n`, cause);
118
+ }
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
@@ -1,398 +0,0 @@
1
- /* [@simplewebauthn/browser@11.0.0] */
2
- function bufferToBase64URLString(buffer) {
3
- const bytes = new Uint8Array(buffer);
4
- let str = '';
5
- for (const charCode of bytes) {
6
- str += String.fromCharCode(charCode);
7
- }
8
- const base64String = btoa(str);
9
- return base64String.replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, '');
10
- }
11
-
12
- function base64URLStringToBuffer(base64URLString) {
13
- const base64 = base64URLString.replace(/-/g, '+').replace(/_/g, '/');
14
- const padLength = (4 - (base64.length % 4)) % 4;
15
- const padded = base64.padEnd(base64.length + padLength, '=');
16
- const binary = atob(padded);
17
- const buffer = new ArrayBuffer(binary.length);
18
- const bytes = new Uint8Array(buffer);
19
- for (let i = 0; i < binary.length; i++) {
20
- bytes[i] = binary.charCodeAt(i);
21
- }
22
- return buffer;
23
- }
24
-
25
- function browserSupportsWebAuthn() {
26
- return (window?.PublicKeyCredential !== undefined &&
27
- typeof window.PublicKeyCredential === 'function');
28
- }
29
-
30
- function toPublicKeyCredentialDescriptor(descriptor) {
31
- const { id } = descriptor;
32
- return {
33
- ...descriptor,
34
- id: base64URLStringToBuffer(id),
35
- transports: descriptor.transports,
36
- };
37
- }
38
-
39
- function isValidDomain(hostname) {
40
- return (hostname === 'localhost' ||
41
- /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(hostname));
42
- }
43
-
44
- class WebAuthnError extends Error {
45
- constructor({ message, code, cause, name, }) {
46
- super(message, { cause });
47
- this.name = name ?? cause.name;
48
- this.code = code;
49
- }
50
- }
51
-
52
- function identifyRegistrationError({ error, options, }) {
53
- const { publicKey } = options;
54
- if (!publicKey) {
55
- throw Error('options was missing required publicKey property');
56
- }
57
- if (error.name === 'AbortError') {
58
- if (options.signal instanceof AbortSignal) {
59
- return new WebAuthnError({
60
- message: 'Registration ceremony was sent an abort signal',
61
- code: 'ERROR_CEREMONY_ABORTED',
62
- cause: error,
63
- });
64
- }
65
- }
66
- else if (error.name === 'ConstraintError') {
67
- if (publicKey.authenticatorSelection?.requireResidentKey === true) {
68
- return new WebAuthnError({
69
- message: 'Discoverable credentials were required but no available authenticator supported it',
70
- code: 'ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT',
71
- cause: error,
72
- });
73
- }
74
- else if (options.mediation === 'conditional' &&
75
- publicKey.authenticatorSelection?.userVerification === 'required') {
76
- return new WebAuthnError({
77
- message: 'User verification was required during automatic registration but it could not be performed',
78
- code: 'ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE',
79
- cause: error,
80
- });
81
- }
82
- else if (publicKey.authenticatorSelection?.userVerification === 'required') {
83
- return new WebAuthnError({
84
- message: 'User verification was required but no available authenticator supported it',
85
- code: 'ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT',
86
- cause: error,
87
- });
88
- }
89
- }
90
- else if (error.name === 'InvalidStateError') {
91
- return new WebAuthnError({
92
- message: 'The authenticator was previously registered',
93
- code: 'ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED',
94
- cause: error,
95
- });
96
- }
97
- else if (error.name === 'NotAllowedError') {
98
- return new WebAuthnError({
99
- message: error.message,
100
- code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
101
- cause: error,
102
- });
103
- }
104
- else if (error.name === 'NotSupportedError') {
105
- const validPubKeyCredParams = publicKey.pubKeyCredParams.filter((param) => param.type === 'public-key');
106
- if (validPubKeyCredParams.length === 0) {
107
- return new WebAuthnError({
108
- message: 'No entry in pubKeyCredParams was of type "public-key"',
109
- code: 'ERROR_MALFORMED_PUBKEYCREDPARAMS',
110
- cause: error,
111
- });
112
- }
113
- return new WebAuthnError({
114
- message: 'No available authenticator supported any of the specified pubKeyCredParams algorithms',
115
- code: 'ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG',
116
- cause: error,
117
- });
118
- }
119
- else if (error.name === 'SecurityError') {
120
- const effectiveDomain = window.location.hostname;
121
- if (!isValidDomain(effectiveDomain)) {
122
- return new WebAuthnError({
123
- message: `${window.location.hostname} is an invalid domain`,
124
- code: 'ERROR_INVALID_DOMAIN',
125
- cause: error,
126
- });
127
- }
128
- else if (publicKey.rp.id !== effectiveDomain) {
129
- return new WebAuthnError({
130
- message: `The RP ID "${publicKey.rp.id}" is invalid for this domain`,
131
- code: 'ERROR_INVALID_RP_ID',
132
- cause: error,
133
- });
134
- }
135
- }
136
- else if (error.name === 'TypeError') {
137
- if (publicKey.user.id.byteLength < 1 || publicKey.user.id.byteLength > 64) {
138
- return new WebAuthnError({
139
- message: 'User ID was not between 1 and 64 characters',
140
- code: 'ERROR_INVALID_USER_ID_LENGTH',
141
- cause: error,
142
- });
143
- }
144
- }
145
- else if (error.name === 'UnknownError') {
146
- return new WebAuthnError({
147
- message: 'The authenticator was unable to process the specified options, or could not create a new credential',
148
- code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',
149
- cause: error,
150
- });
151
- }
152
- return error;
153
- }
154
-
155
- class BaseWebAuthnAbortService {
156
- createNewAbortSignal() {
157
- if (this.controller) {
158
- const abortError = new Error('Cancelling existing WebAuthn API call for new one');
159
- abortError.name = 'AbortError';
160
- this.controller.abort(abortError);
161
- }
162
- const newController = new AbortController();
163
- this.controller = newController;
164
- return newController.signal;
165
- }
166
- cancelCeremony() {
167
- if (this.controller) {
168
- const abortError = new Error('Manually cancelling existing WebAuthn API call');
169
- abortError.name = 'AbortError';
170
- this.controller.abort(abortError);
171
- this.controller = undefined;
172
- }
173
- }
174
- }
175
- const WebAuthnAbortService = new BaseWebAuthnAbortService();
176
-
177
- const attachments = ['cross-platform', 'platform'];
178
- function toAuthenticatorAttachment(attachment) {
179
- if (!attachment) {
180
- return;
181
- }
182
- if (attachments.indexOf(attachment) < 0) {
183
- return;
184
- }
185
- return attachment;
186
- }
187
-
188
- async function startRegistration(options) {
189
- const { optionsJSON, useAutoRegister = false } = options;
190
- if (!browserSupportsWebAuthn()) {
191
- throw new Error('WebAuthn is not supported in this browser');
192
- }
193
- const publicKey = {
194
- ...optionsJSON,
195
- challenge: base64URLStringToBuffer(optionsJSON.challenge),
196
- user: {
197
- ...optionsJSON.user,
198
- id: base64URLStringToBuffer(optionsJSON.user.id),
199
- },
200
- excludeCredentials: optionsJSON.excludeCredentials?.map(toPublicKeyCredentialDescriptor),
201
- };
202
- const createOptions = {};
203
- if (useAutoRegister) {
204
- createOptions.mediation = 'conditional';
205
- }
206
- createOptions.publicKey = publicKey;
207
- createOptions.signal = WebAuthnAbortService.createNewAbortSignal();
208
- let credential;
209
- try {
210
- credential = (await navigator.credentials.create(createOptions));
211
- }
212
- catch (err) {
213
- throw identifyRegistrationError({ error: err, options: createOptions });
214
- }
215
- if (!credential) {
216
- throw new Error('Registration was not completed');
217
- }
218
- const { id, rawId, response, type } = credential;
219
- let transports = undefined;
220
- if (typeof response.getTransports === 'function') {
221
- transports = response.getTransports();
222
- }
223
- let responsePublicKeyAlgorithm = undefined;
224
- if (typeof response.getPublicKeyAlgorithm === 'function') {
225
- try {
226
- responsePublicKeyAlgorithm = response.getPublicKeyAlgorithm();
227
- }
228
- catch (error) {
229
- warnOnBrokenImplementation('getPublicKeyAlgorithm()', error);
230
- }
231
- }
232
- let responsePublicKey = undefined;
233
- if (typeof response.getPublicKey === 'function') {
234
- try {
235
- const _publicKey = response.getPublicKey();
236
- if (_publicKey !== null) {
237
- responsePublicKey = bufferToBase64URLString(_publicKey);
238
- }
239
- }
240
- catch (error) {
241
- warnOnBrokenImplementation('getPublicKey()', error);
242
- }
243
- }
244
- let responseAuthenticatorData;
245
- if (typeof response.getAuthenticatorData === 'function') {
246
- try {
247
- responseAuthenticatorData = bufferToBase64URLString(response.getAuthenticatorData());
248
- }
249
- catch (error) {
250
- warnOnBrokenImplementation('getAuthenticatorData()', error);
251
- }
252
- }
253
- return {
254
- id,
255
- rawId: bufferToBase64URLString(rawId),
256
- response: {
257
- attestationObject: bufferToBase64URLString(response.attestationObject),
258
- clientDataJSON: bufferToBase64URLString(response.clientDataJSON),
259
- transports,
260
- publicKeyAlgorithm: responsePublicKeyAlgorithm,
261
- publicKey: responsePublicKey,
262
- authenticatorData: responseAuthenticatorData,
263
- },
264
- type,
265
- clientExtensionResults: credential.getClientExtensionResults(),
266
- authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),
267
- };
268
- }
269
- function warnOnBrokenImplementation(methodName, cause) {
270
- console.warn(`The browser extension that intercepted this WebAuthn API call incorrectly implemented ${methodName}. You should report this error to them.\n`, cause);
271
- }
272
-
273
- function browserSupportsWebAuthnAutofill() {
274
- if (!browserSupportsWebAuthn()) {
275
- return new Promise((resolve) => resolve(false));
276
- }
277
- const globalPublicKeyCredential = window
278
- .PublicKeyCredential;
279
- if (globalPublicKeyCredential.isConditionalMediationAvailable === undefined) {
280
- return new Promise((resolve) => resolve(false));
281
- }
282
- return globalPublicKeyCredential.isConditionalMediationAvailable();
283
- }
284
-
285
- function identifyAuthenticationError({ error, options, }) {
286
- const { publicKey } = options;
287
- if (!publicKey) {
288
- throw Error('options was missing required publicKey property');
289
- }
290
- if (error.name === 'AbortError') {
291
- if (options.signal instanceof AbortSignal) {
292
- return new WebAuthnError({
293
- message: 'Authentication ceremony was sent an abort signal',
294
- code: 'ERROR_CEREMONY_ABORTED',
295
- cause: error,
296
- });
297
- }
298
- }
299
- else if (error.name === 'NotAllowedError') {
300
- return new WebAuthnError({
301
- message: error.message,
302
- code: 'ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY',
303
- cause: error,
304
- });
305
- }
306
- else if (error.name === 'SecurityError') {
307
- const effectiveDomain = window.location.hostname;
308
- if (!isValidDomain(effectiveDomain)) {
309
- return new WebAuthnError({
310
- message: `${window.location.hostname} is an invalid domain`,
311
- code: 'ERROR_INVALID_DOMAIN',
312
- cause: error,
313
- });
314
- }
315
- else if (publicKey.rpId !== effectiveDomain) {
316
- return new WebAuthnError({
317
- message: `The RP ID "${publicKey.rpId}" is invalid for this domain`,
318
- code: 'ERROR_INVALID_RP_ID',
319
- cause: error,
320
- });
321
- }
322
- }
323
- else if (error.name === 'UnknownError') {
324
- return new WebAuthnError({
325
- message: 'The authenticator was unable to process the specified options, or could not create a new assertion signature',
326
- code: 'ERROR_AUTHENTICATOR_GENERAL_ERROR',
327
- cause: error,
328
- });
329
- }
330
- return error;
331
- }
332
-
333
- async function startAuthentication(options) {
334
- const { optionsJSON, useBrowserAutofill = false, verifyBrowserAutofillInput = true, } = options;
335
- if (!browserSupportsWebAuthn()) {
336
- throw new Error('WebAuthn is not supported in this browser');
337
- }
338
- let allowCredentials;
339
- if (optionsJSON.allowCredentials?.length !== 0) {
340
- allowCredentials = optionsJSON.allowCredentials?.map(toPublicKeyCredentialDescriptor);
341
- }
342
- const publicKey = {
343
- ...optionsJSON,
344
- challenge: base64URLStringToBuffer(optionsJSON.challenge),
345
- allowCredentials,
346
- };
347
- const getOptions = {};
348
- if (useBrowserAutofill) {
349
- if (!(await browserSupportsWebAuthnAutofill())) {
350
- throw Error('Browser does not support WebAuthn autofill');
351
- }
352
- const eligibleInputs = document.querySelectorAll("input[autocomplete$='webauthn']");
353
- if (eligibleInputs.length < 1 && verifyBrowserAutofillInput) {
354
- throw Error('No <input> with "webauthn" as the only or last value in its `autocomplete` attribute was detected');
355
- }
356
- getOptions.mediation = 'conditional';
357
- publicKey.allowCredentials = [];
358
- }
359
- getOptions.publicKey = publicKey;
360
- getOptions.signal = WebAuthnAbortService.createNewAbortSignal();
361
- let credential;
362
- try {
363
- credential = (await navigator.credentials.get(getOptions));
364
- }
365
- catch (err) {
366
- throw identifyAuthenticationError({ error: err, options: getOptions });
367
- }
368
- if (!credential) {
369
- throw new Error('Authentication was not completed');
370
- }
371
- const { id, rawId, response, type } = credential;
372
- let userHandle = undefined;
373
- if (response.userHandle) {
374
- userHandle = bufferToBase64URLString(response.userHandle);
375
- }
376
- return {
377
- id,
378
- rawId: bufferToBase64URLString(rawId),
379
- response: {
380
- authenticatorData: bufferToBase64URLString(response.authenticatorData),
381
- clientDataJSON: bufferToBase64URLString(response.clientDataJSON),
382
- signature: bufferToBase64URLString(response.signature),
383
- userHandle,
384
- },
385
- type,
386
- clientExtensionResults: credential.getClientExtensionResults(),
387
- authenticatorAttachment: toAuthenticatorAttachment(credential.authenticatorAttachment),
388
- };
389
- }
390
-
391
- function platformAuthenticatorIsAvailable() {
392
- if (!browserSupportsWebAuthn()) {
393
- return new Promise((resolve) => resolve(false));
394
- }
395
- return PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
396
- }
397
-
398
- export { WebAuthnAbortService, WebAuthnError, base64URLStringToBuffer, browserSupportsWebAuthn, browserSupportsWebAuthnAutofill, bufferToBase64URLString, platformAuthenticatorIsAvailable, startAuthentication, startRegistration };
@@ -1 +0,0 @@
1
- export declare function base64URLStringToBuffer(base64URLString: string): ArrayBuffer;
@@ -1 +0,0 @@
1
- export declare function browserSupportsWebAuthn(): boolean;
@@ -1 +0,0 @@
1
- export declare function browserSupportsWebAuthnAutofill(): Promise<boolean>;
@@ -1 +0,0 @@
1
- export declare function bufferToBase64URLString(buffer: ArrayBuffer): string;
@@ -1,5 +0,0 @@
1
- import { WebAuthnError } from './webAuthnError';
2
- export declare function identifyAuthenticationError({ error, options, }: {
3
- error: Error;
4
- options: CredentialRequestOptions;
5
- }): WebAuthnError | Error;
@@ -1,5 +0,0 @@
1
- import { WebAuthnError } from './webAuthnError';
2
- export declare function identifyRegistrationError({ error, options, }: {
3
- error: Error;
4
- options: CredentialCreationOptions;
5
- }): WebAuthnError | Error;