u2finterface.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. import {Component} from 'react';
  2. import * as Sentry from '@sentry/react';
  3. import * as cbor from 'cbor-web';
  4. import {base64urlToBuffer, bufferToBase64url} from 'sentry/components/u2f/webAuthnHelper';
  5. import {t, tct} from 'sentry/locale';
  6. import ConfigStore from 'sentry/stores/configStore';
  7. import {ChallengeData, Organization} from 'sentry/types';
  8. import withOrganization from 'sentry/utils/withOrganization';
  9. type TapParams = {
  10. challenge: string;
  11. response: string;
  12. isSuperuserModal?: boolean;
  13. superuserAccessCategory?: string;
  14. superuserReason?: string;
  15. };
  16. type Props = {
  17. challengeData: ChallengeData;
  18. flowMode: string;
  19. onTap: ({
  20. response,
  21. challenge,
  22. isSuperuserModal,
  23. superuserAccessCategory,
  24. superuserReason,
  25. }: TapParams) => Promise<void>;
  26. organization: Organization;
  27. silentIfUnsupported: boolean;
  28. style?: React.CSSProperties;
  29. };
  30. type State = {
  31. challengeElement: HTMLInputElement | null;
  32. deviceFailure: string | null;
  33. failCount: number;
  34. formElement: HTMLFormElement | null;
  35. hasBeenTapped: boolean;
  36. isSafari: boolean;
  37. isSupported: boolean | null;
  38. responseElement: HTMLInputElement | null;
  39. };
  40. class U2fInterface extends Component<Props, State> {
  41. state: State = {
  42. isSupported: null,
  43. formElement: null,
  44. challengeElement: null,
  45. hasBeenTapped: false,
  46. deviceFailure: null,
  47. responseElement: null,
  48. isSafari: false,
  49. failCount: 0,
  50. };
  51. componentDidMount() {
  52. const supported = !!window.PublicKeyCredential;
  53. // eslint-disable-next-line react/no-did-mount-set-state
  54. this.setState({isSupported: supported});
  55. const isSafari =
  56. navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome');
  57. if (isSafari) {
  58. // eslint-disable-next-line react/no-did-mount-set-state
  59. this.setState({
  60. deviceFailure: 'safari: requires interaction',
  61. isSafari,
  62. hasBeenTapped: false,
  63. });
  64. }
  65. if (supported && !isSafari) {
  66. this.invokeU2fFlow();
  67. }
  68. }
  69. getU2FResponse(data) {
  70. if (!data.response) {
  71. return JSON.stringify(data);
  72. }
  73. if (this.props.flowMode === 'sign') {
  74. const authenticatorData = {
  75. keyHandle: data.id,
  76. clientData: bufferToBase64url(data.response.clientDataJSON),
  77. signatureData: bufferToBase64url(data.response.signature),
  78. authenticatorData: bufferToBase64url(data.response.authenticatorData),
  79. };
  80. return JSON.stringify(authenticatorData);
  81. }
  82. if (this.props.flowMode === 'enroll') {
  83. const authenticatorData = {
  84. id: data.id,
  85. rawId: bufferToBase64url(data.rawId),
  86. response: {
  87. attestationObject: bufferToBase64url(data.response.attestationObject),
  88. clientDataJSON: bufferToBase64url(data.response.clientDataJSON),
  89. },
  90. type: bufferToBase64url(data.type),
  91. };
  92. return JSON.stringify(authenticatorData);
  93. }
  94. throw new Error(`Unsupported flow mode '${this.props.flowMode}'`);
  95. }
  96. submitU2fResponse(promise) {
  97. promise
  98. .then(data => {
  99. this.setState(
  100. {
  101. hasBeenTapped: true,
  102. },
  103. () => {
  104. const u2fResponse = this.getU2FResponse(data);
  105. const challenge = JSON.stringify(this.props.challengeData);
  106. if (this.state.responseElement) {
  107. // eslint-disable-next-line react/no-direct-mutation-state
  108. this.state.responseElement.value = u2fResponse;
  109. }
  110. if (!this.props.onTap) {
  111. this.state.formElement?.submit();
  112. return;
  113. }
  114. this.props
  115. .onTap({
  116. response: u2fResponse,
  117. challenge,
  118. })
  119. .catch(() => {
  120. // This is kind of gross but I want to limit the amount of changes to this component
  121. this.setState({
  122. deviceFailure: 'UNKNOWN_ERROR',
  123. hasBeenTapped: false,
  124. });
  125. });
  126. }
  127. );
  128. })
  129. .catch(err => {
  130. let failure = 'DEVICE_ERROR';
  131. // in some rare cases there is no metadata on the error which
  132. // causes this to blow up badly.
  133. if (err.metaData) {
  134. if (err.metaData.type === 'DEVICE_INELIGIBLE') {
  135. if (this.props.flowMode === 'enroll') {
  136. failure = 'DUPLICATE_DEVICE';
  137. } else {
  138. failure = 'UNKNOWN_DEVICE';
  139. }
  140. } else if (err.metaData.type === 'BAD_REQUEST') {
  141. failure = 'BAD_APPID';
  142. }
  143. }
  144. // we want to know what is happening here. There are some indicators
  145. // that users are getting errors that should not happen through the
  146. // regular u2f flow.
  147. Sentry.captureException(err);
  148. this.setState({
  149. deviceFailure: failure,
  150. hasBeenTapped: false,
  151. failCount: this.state.failCount + 1,
  152. });
  153. });
  154. }
  155. webAuthnSignIn(publicKeyCredentialRequestOptions) {
  156. const promise = navigator.credentials.get({
  157. publicKey: publicKeyCredentialRequestOptions,
  158. });
  159. this.submitU2fResponse(promise);
  160. }
  161. webAuthnRegister(publicKey) {
  162. const promise = navigator.credentials.create({
  163. publicKey,
  164. });
  165. this.submitU2fResponse(promise);
  166. }
  167. invokeU2fFlow() {
  168. if (this.props.flowMode === 'sign') {
  169. const challengeArray = base64urlToBuffer(
  170. this.props.challengeData.webAuthnAuthenticationData
  171. );
  172. const challenge = cbor.decodeFirst(challengeArray);
  173. challenge
  174. .then(data => {
  175. this.webAuthnSignIn(data);
  176. })
  177. .catch(err => {
  178. const failure = 'DEVICE_ERROR';
  179. Sentry.captureException(err);
  180. this.setState({
  181. deviceFailure: failure,
  182. hasBeenTapped: false,
  183. });
  184. });
  185. } else if (this.props.flowMode === 'enroll') {
  186. const challengeArray = base64urlToBuffer(
  187. this.props.challengeData.webAuthnRegisterData
  188. );
  189. const challenge = cbor.decodeFirst(challengeArray);
  190. // challenge contains a PublicKeyCredentialRequestOptions object for webauthn registration
  191. challenge
  192. .then(data => {
  193. this.webAuthnRegister(data.publicKey);
  194. })
  195. .catch(err => {
  196. const failure = 'DEVICE_ERROR';
  197. Sentry.captureException(err);
  198. this.setState({
  199. deviceFailure: failure,
  200. hasBeenTapped: false,
  201. });
  202. });
  203. } else {
  204. throw new Error(`Unsupported flow mode '${this.props.flowMode}'`);
  205. }
  206. }
  207. onTryAgain = () => {
  208. this.setState(
  209. {hasBeenTapped: false, deviceFailure: null},
  210. () => void this.invokeU2fFlow()
  211. );
  212. };
  213. bindChallengeElement: React.RefCallback<HTMLInputElement> = ref => {
  214. this.setState({
  215. challengeElement: ref,
  216. formElement: ref && ref.form,
  217. });
  218. if (ref) {
  219. ref.value = JSON.stringify(this.props.challengeData);
  220. }
  221. };
  222. bindResponseElement: React.RefCallback<HTMLInputElement> = ref =>
  223. this.setState({responseElement: ref});
  224. renderUnsupported() {
  225. return this.props.silentIfUnsupported ? null : (
  226. <div className="u2f-box">
  227. <div className="inner">
  228. <p className="error">
  229. {t(
  230. `
  231. Unfortunately your browser does not support U2F. You need to use
  232. a different two-factor method or switch to a browser that supports
  233. it (Google Chrome or Microsoft Edge).`
  234. )}
  235. </p>
  236. </div>
  237. </div>
  238. );
  239. }
  240. get canTryAgain() {
  241. return this.state.deviceFailure !== 'BAD_APPID';
  242. }
  243. renderSafariWebAuthn = () => {
  244. return (
  245. <a onClick={this.onTryAgain} className="btn btn-primary">
  246. {this.props.flowMode === 'enroll'
  247. ? t('Enroll with WebAuthn')
  248. : t('Sign in with WebAuthn')}
  249. </a>
  250. );
  251. };
  252. renderFailure = () => {
  253. const {deviceFailure} = this.state;
  254. const supportMail = ConfigStore.get('supportEmail');
  255. const support = supportMail ? (
  256. <a href={'mailto:' + supportMail}>{supportMail}</a>
  257. ) : (
  258. <span>{t('Support')}</span>
  259. );
  260. if (this.state.isSafari && this.state.failCount === 0) {
  261. return this.renderSafariWebAuthn();
  262. }
  263. return (
  264. <div className="failure-message">
  265. <div>
  266. <strong>{t('Error: ')}</strong>{' '}
  267. {
  268. {
  269. UNKNOWN_ERROR: t('There was an unknown problem, please try again'),
  270. DEVICE_ERROR: t('Your U2F device reported an error.'),
  271. DUPLICATE_DEVICE: t('This device is already registered with Sentry.'),
  272. UNKNOWN_DEVICE: t('The device you used for sign-in is unknown.'),
  273. BAD_APPID: tct(
  274. `[p1:The Sentry server administrator modified the device
  275. registrations.] [p2:You need to remove and re-add the device to continue using
  276. your U2F device. Use a different sign-in method or contact [support] for
  277. assistance.]`,
  278. {
  279. p1: <p />,
  280. p2: <p />,
  281. support,
  282. }
  283. ),
  284. }[deviceFailure || '']
  285. }
  286. </div>
  287. {this.canTryAgain && (
  288. <div style={{marginTop: 18}}>
  289. <a onClick={this.onTryAgain} className="btn btn-primary">
  290. {t('Try Again')}
  291. </a>
  292. </div>
  293. )}
  294. </div>
  295. );
  296. };
  297. renderBody() {
  298. return this.state.deviceFailure ? this.renderFailure() : this.props.children;
  299. }
  300. renderPrompt() {
  301. const {style} = this.props;
  302. return (
  303. <div
  304. style={style}
  305. className={
  306. 'u2f-box' +
  307. (this.state.hasBeenTapped ? ' tapped' : '') +
  308. (this.state.deviceFailure
  309. ? this.state.failCount === 0 && this.state.isSafari
  310. ? ' loading-dots'
  311. : ' device-failure'
  312. : '')
  313. }
  314. >
  315. <div className="device-animation-frame">
  316. <div className="device-failed" />
  317. <div className="device-animation" />
  318. <div className="loading-dots">
  319. <span className="dot" />
  320. <span className="dot" />
  321. <span className="dot" />
  322. </div>
  323. </div>
  324. <input type="hidden" name="challenge" ref={this.bindChallengeElement} />
  325. <input type="hidden" name="response" ref={this.bindResponseElement} />
  326. <div className="inner">{this.renderBody()}</div>
  327. </div>
  328. );
  329. }
  330. render() {
  331. const {isSupported} = this.state;
  332. // if we are still waiting for the browser to tell us if we can do u2f this
  333. // will be null.
  334. if (isSupported === null) {
  335. return null;
  336. }
  337. if (!isSupported) {
  338. return this.renderUnsupported();
  339. }
  340. return this.renderPrompt();
  341. }
  342. }
  343. export default withOrganization(U2fInterface);