@oneblink/apps-react 13.5.1-beta.1 → 13.5.1-beta.3

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.
@@ -249,9 +249,12 @@ declare function getUserFriendlyName(): string | undefined;
249
249
  * }
250
250
  * ```
251
251
  *
252
+ * @param mfaAuthenticatorAppSetup
253
+ * @param authenticatorAppDisplayName Name shown in the authenticator app. When
254
+ * omitted, the product name is used. Console sign-in omits this.
252
255
  * @returns
253
256
  */
254
- declare function generateMfaAuthenticatorAppQrCodeUrl(mfaAuthenticatorAppSetup: Awaited<ReturnType<typeof setupMfaAuthenticatorApp>>): string | undefined;
257
+ declare function generateMfaAuthenticatorAppQrCodeUrl(mfaAuthenticatorAppSetup: Awaited<ReturnType<typeof setupMfaAuthenticatorApp>>, authenticatorAppDisplayName?: string): string | undefined;
255
258
  declare function getMfaSettings(abortSignal?: AbortSignal): Promise<MfaSettings>;
256
259
  declare function updateUserPhoneNumber(phoneNumber: string): Promise<{
257
260
  isPhoneNumberVerified: boolean;
@@ -369,13 +369,23 @@ function getUserFriendlyName() {
369
369
  * }
370
370
  * ```
371
371
  *
372
+ * @param mfaAuthenticatorAppSetup
373
+ * @param authenticatorAppDisplayName Name shown in the authenticator app. When
374
+ * omitted, the product name is used. Console sign-in omits this.
372
375
  * @returns
373
376
  */
374
- function generateMfaAuthenticatorAppQrCodeUrl(mfaAuthenticatorAppSetup) {
377
+ function generateMfaAuthenticatorAppQrCodeUrl(mfaAuthenticatorAppSetup, authenticatorAppDisplayName) {
375
378
  const profile = getUserProfile();
376
379
  if (!profile || !mfaAuthenticatorAppSetup) {
377
380
  return;
378
381
  }
382
+ const displayName = authenticatorAppDisplayName === null || authenticatorAppDisplayName === void 0 ? void 0 : authenticatorAppDisplayName.trim();
383
+ if (displayName) {
384
+ const issuer = encodeURIComponent(displayName);
385
+ return `otpauth://totp/${issuer}:${profile.email}?secret=${mfaAuthenticatorAppSetup.secretCode}&issuer=${issuer}`;
386
+ }
387
+ // Console MFA keeps the product name, including the unencoded space in
388
+ // "OneBlink LcS". App users pass authenticatorAppDisplayName instead.
379
389
  return `otpauth://totp/${tenants.current.productShortName}:${profile.email}?secret=${mfaAuthenticatorAppSetup.secretCode}&issuer=${tenants.current.productShortName}`;
380
390
  }
381
391
  async function getMfaSettings(abortSignal) {
@@ -1 +1 @@
1
- {"version":3,"file":"cognito.js","sourceRoot":"","sources":["../../../src/apps/services/cognito.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAEtC,OAAO,gBAAgB,EAAE,EACvB,oBAAoB,GAKrB,MAAM,oBAAoB,CAAA;AAE3B,OAAO,KAAK,cAAc,MAAM,oBAAoB,CAAA;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,CAAA;AAEhD,OAAO,EAAa,WAAW,EAAE,MAAM,SAAS,CAAA;AAChD,OAAO,OAAO,MAAM,YAAY,CAAA;AAChC,OAAO,iBAAiB,MAAM,4BAA4B,CAAA;AAU1D,MAAM,WAAW,GAAG,YAAY,CAAA;AAEhC,IAAI,gBAAgB,GAA4B,IAAI,CAAA;AAEpD,SAAS,IAAI,CAAC,kBAAsC;IAClD,OAAO,CAAC,GAAG,CAAC,2CAA2C,EAAE,kBAAkB,CAAC,CAAA;IAE5E,gBAAgB,GAAG,IAAI,gBAAgB,CAAC;QACtC,QAAQ,EAAE,kBAAkB,CAAC,aAAa;QAC1C,MAAM,EAAE,kBAAkB,CAAC,MAAM;QACjC,WAAW,EAAE,kBAAkB,CAAC,WAAW;QAC3C,WAAW,EAAE,kBAAkB,CAAC,WAAW;QAC3C,SAAS,EAAE,kBAAkB,CAAC,SAAS;KACxC,CAAC,CAAA;AACJ,CAAC;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,SAAS,oBAAoB,CAAC,QAAuB;IACnD,IAAI,CAAC,gBAAgB,EAAE,CAAC;QACtB,MAAM,IAAI,KAAK,CACb,mHA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CAAA;IACH,CAAC;IAED,OAAO,MAAM,gBAAgB,CAAC,wBAAwB,CAAC,OAAO,CAAC,CAAA;AACjE,CAAC;AAED,OAAO,EACL,IAAI,EACJ,oBAAoB,EACpB,qBAAqB,EACrB,aAAa,EACb,oBAAoB,EACpB,cAAc,EACd,cAAc,EACd,cAAc,EACd,MAAM,EACN,UAAU,EACV,iBAAiB,EACjB,cAAc,EACd,mBAAmB,EACnB,cAAc,EACd,qBAAqB,EACrB,qBAAqB,EACrB,qBAAqB,EACrB,gBAAgB,EAChB,qBAAqB,EACrB,WAAW,EACX,wBAAwB,EACxB,oCAAoC,EACpC,oBAAoB,GACrB,CAAA","sourcesContent":["import { jwtDecode } from 'jwt-decode'\n\nimport AWSCognitoClient, {\n DEFAULT_MFA_SETTINGS,\n LoginAttemptResponse,\n LoggedInMfaMethod,\n MfaMethod,\n MfaSettings,\n} from './AWSCognitoClient'\n\nimport * as offlineService from '../offline-service'\nimport { userService } from '@oneblink/sdk-core'\nimport { MiscTypes } from '@oneblink/types'\nimport { HTTPError, postRequest } from './fetch'\nimport tenants from '../tenants'\nimport OneBlinkAppsError from './errors/oneBlinkAppsError'\n\ninterface CognitoServiceData {\n oAuthClientId: string\n loginDomain: string\n region: string\n redirectUri: string\n logoutUri: string\n}\n\nconst CONTINUE_TO = 'continueTo'\n\nlet awsCognitoClient: null | AWSCognitoClient = null\n\nfunction init(cognitoServiceData: CognitoServiceData) {\n console.log('Initiating CognitoIdentityServiceProvider', cognitoServiceData)\n\n awsCognitoClient = new AWSCognitoClient({\n clientId: cognitoServiceData.oAuthClientId,\n region: cognitoServiceData.region,\n loginDomain: cognitoServiceData.loginDomain,\n redirectUri: cognitoServiceData.redirectUri,\n logoutUri: cognitoServiceData.logoutUri,\n })\n}\n\n/**\n * Register a listener function that will be call when authentication tokens are\n * updated or removed.\n *\n * #### Example\n *\n * ```js\n * const listener = async () => {\n * // Check if the user is logged in still\n * const isLoggedIn = authService.isLoggedIn()\n * }\n * const deregister = await authService.registerAuthListener(listener)\n *\n * // When no longer needed, remember to deregister the listener\n * deregister()\n * ```\n *\n * @param listener\n * @returns\n */\nfunction registerAuthListener(listener: () => unknown): () => void {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to register a listener.',\n )\n }\n return awsCognitoClient.registerListener(listener)\n}\n\n/**\n * Create a session for a user by entering a username and password. If the user\n * requires a password reset, the \"resetPasswordCallback\" property will be\n * returned. This function should be called with the new password once entered\n * by the user. If the user requires an MFA token, the \"mfa\" property will be\n * returned. Its \"codeCallback\" should be called with the one-time token. The\n * functions returned are recursive and the result from each of them is the same\n * result from the loginUsernamePassword() function. Each time the response\n * includes a callback, you will need to begin the process again until all\n * callbacks are handled.\n *\n * #### Example\n *\n * ```js\n * async function handleLoginAttemptResponse({\n * resetPasswordCallback,\n * mfa,\n * }) {\n * // \"resetPasswordCallback\" will be undefined if a password reset was not required.\n * if (resetPasswordCallback) {\n * // Prompt the user to enter a new password\n * const newPassword = prompt(\n * 'The password you entered was only temporary, and must be reset for security purposes. Please enter your new password below to continue.',\n * )\n * const resetPasswordResponse =\n * await resetPasswordCallback(newPassword)\n * return await handleLoginAttemptResponse(resetPasswordResponse)\n * }\n *\n * // \"mfa\" will be undefined if MFA is not setup.\n * if (mfa) {\n * // Prompt the user to enter an MFA code\n * const code = prompt(\n * mfa.method === 'email'\n * ? 'Please enter the one-time code sent to your email.'\n * : 'Please enter a one-time code from your MFA app.',\n * )\n * const mfaCodeResponse = await mfa.codeCallback(code)\n * return await handleLoginAttemptResponse(mfaCodeResponse)\n * }\n * }\n *\n * const username = 'user@email.io'\n * const password = 'P@$5w0rd'\n *\n * const loginAttemptResponse = await authService.loginUsernamePassword(\n * username,\n * password,\n * )\n *\n * await handleLoginAttemptResponse(loginAttemptResponse)\n * ```\n *\n * @param username\n * @param password\n * @returns\n */\nasync function loginUsernamePassword(username: string, password: string) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to login.',\n )\n }\n console.log('Attempting sign using username', username)\n return awsCognitoClient.loginUsernamePassword(\n username.toLowerCase(),\n password,\n )\n}\n\n/**\n * Redirect the user to the login screen. Passing an `identityProvider` is\n * optionally, it will allow users to skip the login page and be directed\n * straight to that providers login page\n *\n * #### Example\n *\n * ```js\n * // OPtionally pass a\n * const identityProvider = 'Google'\n * await authService.loginHostedUI(identityProvider)\n * // User will be redirected to login page or promise will resolve\n * ```\n *\n * @param identityProviderName\n * @returns\n */\nasync function loginHostedUI(identityProviderName?: string): Promise<void> {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to login.',\n )\n }\n const continueTo = `${window.location.pathname}${window.location.search}`\n localStorage.setItem(CONTINUE_TO, continueTo)\n\n return awsCognitoClient.loginHostedUI(identityProviderName)\n}\n\n/**\n * This function should be called when the user is redirected back to your app\n * after a login attempt. It will use the query string add the redirect URL to\n * create a session for the current user. It will return a URL as a `string`\n * that should be redirected to within your app.\n *\n * #### Example\n *\n * ```js\n * try {\n * const continueTo = await authService.handleAuthentication()\n * // Redirect the user back to where they were before attempting to login\n * window.location.href = continueTo\n * } catch (error) {\n * // handle failed login attempts here.\n * }\n * ```\n *\n * @returns\n */\nasync function handleAuthentication(): Promise<string> {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to handle authentication in URL.',\n )\n }\n\n const continueTo = localStorage.getItem(CONTINUE_TO) || '/'\n if (isLoggedIn()) {\n console.log('Already authenticated, redirecting to:', continueTo)\n } else {\n await awsCognitoClient.handleAuthentication()\n }\n\n localStorage.removeItem(CONTINUE_TO)\n\n return continueTo\n}\n\n/**\n * Allow the currently logged in user to change their password by passing their\n * existing password and a new password.\n *\n * #### Example\n *\n * ```js\n * const currentPassword = 'P@$5w0rd'\n * const newPassword = 'P@$5w0rD'\n * await authService.changePassword(currentPassword, newPassword)\n * ```\n *\n * @param existingPassword\n * @param newPassword\n * @returns\n */\nasync function changePassword(existingPassword: string, newPassword: string) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to change passwords.',\n )\n }\n\n return await awsCognitoClient.changePassword(existingPassword, newPassword)\n}\n\n/**\n * Allow a user to start the forgot password process. The user will be emailed a\n * temporary code that must be passed with a new password to the function\n * returned.\n *\n * #### Example\n *\n * ```js\n * const username = 'user@email.io'\n * const finishForgotPassword = await authService.forgotPassword(username)\n *\n * // Prompt the user to enter the code and a new password\n * const code = prompt(\n * 'You have been emailed a verification code, please enter it here.',\n * )\n * const newPassword = prompt('Please enter a new password to continue.')\n * await finishForgotPassword(code, newPassword)\n * ```\n *\n * @param username\n * @param formsAppId Used to give the resulting email sent to the user\n * associated forms app branding and sending address\n * @returns\n */\nasync function forgotPassword(\n username: string,\n /**\n * Used to give the resulting email sent to the user associated forms app\n * branding and sending address\n */\n formsAppId?: number,\n): Promise<(code: string, password: string) => Promise<void>> {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before starting the forgot password process.',\n )\n }\n\n try {\n const url = `${tenants.current.apiOrigin}/authentication/reset-password`\n await postRequest(url, {\n username,\n formsAppId,\n })\n } catch (err) {\n const error = err as HTTPError\n switch (error.status) {\n case 400: {\n throw new OneBlinkAppsError(error.message, {\n title: 'Invalid Request',\n httpStatusCode: error.status,\n })\n }\n default: {\n throw new OneBlinkAppsError(\n 'An unknown error has occurred. Please contact support if the problem persists.',\n {\n originalError: error,\n httpStatusCode: error.status,\n },\n )\n }\n }\n }\n\n return async (code, password) => {\n await awsCognitoClient?.confirmForgotPassword({\n username,\n code,\n password,\n })\n }\n}\n\n/**\n * Redirect the user to the logout screen to clear the users session on the\n * hosted login page. User will then be redirected to `/logout`. After being\n * redirected back to the application, the `logout()` function should be called\n * to clear the session data from browser storage.\n *\n * #### Example\n *\n * ```js\n * authService.logoutHostedUI()\n * ```\n */\nfunction logoutHostedUI(): void {\n if (awsCognitoClient) {\n awsCognitoClient.logoutHostedUI()\n }\n}\n\nasync function logout() {\n if (awsCognitoClient) {\n await awsCognitoClient.logout()\n }\n}\n\n/**\n * Check if the user is currently logged in\n *\n * #### Example\n *\n * ```js\n * const isLoggedIn = authService.isLoggedIn()\n * // handle user being logged in or not\n * ```\n *\n * @returns\n */\nfunction isLoggedIn(): boolean {\n return !!(awsCognitoClient && awsCognitoClient._getRefreshToken())\n}\n\nasync function getCognitoIdToken(): Promise<string | undefined> {\n if (!awsCognitoClient) {\n return\n }\n\n if (offlineService.isOffline()) {\n return awsCognitoClient._getIdToken()\n }\n\n return await awsCognitoClient.getIdToken()\n}\n\n/**\n * Get current users profile based on there Id Token payload. This will return\n * `null` if the the current user is not logged in.\n *\n * #### Example\n *\n * ```js\n * const profile = authService.getUserProfile()\n * if (profile) {\n * // Use profile here\n * }\n * ```\n *\n * @returns\n */\nfunction getUserProfile(): MiscTypes.UserProfile | null {\n if (!awsCognitoClient) {\n return null\n }\n const idToken = awsCognitoClient._getIdToken()\n if (!idToken) {\n return null\n }\n\n const jwtToken = jwtDecode(idToken)\n return userService.parseUserProfile(jwtToken) || null\n}\n\nexport function getUsername(): string | undefined {\n const profile = getUserProfile()\n if (!profile) {\n return undefined\n }\n\n return profile.username\n}\n\n/**\n * A friendly `string` that represents the current user. Uses first name, last\n * name, full name and username. This will return `null` the current user is not\n * logged in.\n *\n * #### Example\n *\n * ```js\n * const name = authService.getUserFriendlyName()\n * if (name) {\n * // Display current user's name\n * }\n * ```\n *\n * @returns\n */\nfunction getUserFriendlyName(): string | undefined {\n const profile = getUserProfile()\n if (!profile) {\n return\n }\n\n return userService.getUserFriendlyName(profile)\n}\n\n/**\n * Generate a QR code link to display to a user after they have initiated\n * authenticator app MFA setup.\n *\n * #### Example\n *\n * ```js\n * const mfaAuthenticatorAppSetupQrCodeUrl =\n * mfaService.generateMfaAuthenticatorAppQrCodeUrl()\n * if (mfaAuthenticatorAppSetupQrCodeUrl) {\n * // use mfaAuthenticatorAppSetupQrCodeUrl to display QR code to user\n * }\n * ```\n *\n * @returns\n */\nfunction generateMfaAuthenticatorAppQrCodeUrl(\n mfaAuthenticatorAppSetup: Awaited<\n ReturnType<typeof setupMfaAuthenticatorApp>\n >,\n): string | undefined {\n const profile = getUserProfile()\n if (!profile || !mfaAuthenticatorAppSetup) {\n return\n }\n\n return `otpauth://totp/${tenants.current.productShortName}:${profile.email}?secret=${mfaAuthenticatorAppSetup.secretCode}&issuer=${tenants.current.productShortName}`\n}\n\nasync function getMfaSettings(abortSignal?: AbortSignal) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before checking MFA settings.',\n )\n }\n\n return await awsCognitoClient.getMfaSettings(abortSignal)\n}\n\nasync function updateUserPhoneNumber(phoneNumber: string) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before updating the user phone number.',\n )\n }\n\n return await awsCognitoClient.updateUserPhoneNumber(phoneNumber)\n}\n\nasync function removeUserPhoneNumber() {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before removing the user phone number.',\n )\n }\n\n return await awsCognitoClient.removeUserPhoneNumber()\n}\n\nasync function verifyUserPhoneNumber(code: string) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before verifying the user phone number.',\n )\n }\n\n return await awsCognitoClient.verifyUserPhoneNumber(code)\n}\n\nasync function setupSmsMfa(options?: { preferred?: boolean }) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to setup SMS MFA.',\n )\n }\n\n return await awsCognitoClient.setupSmsMfa(options)\n}\n\nasync function disableMfaMethod(method: MfaMethod) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to disable an MFA method.',\n )\n }\n\n return await awsCognitoClient.disableMfaMethod(method)\n}\n\nasync function setPreferredMfaMethod(method: MfaMethod) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to set the preferred MFA method.',\n )\n }\n\n return await awsCognitoClient.setPreferredMfaMethod(method)\n}\n\n/**\n * Setup authenticator app MFA for the current user. The result will include a\n * callback that should be called with the valid TOTP from an authenticator\n * app.\n *\n * #### Example\n *\n * ```js\n * const { secretCode, mfaCodeCallback } =\n * await mfaService.setupMfaAuthenticatorApp()\n * // Prompt the user to enter an MFA code\n * const code = prompt(\n * `Please enter a one-time code from your MFA app after creating a new entry with secret: ${secretCode}.`,\n * )\n * await mfaCodeCallback(code)\n * ```\n *\n * @returns\n */\nasync function setupMfaAuthenticatorApp(options?: { preferred?: boolean }) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to setup authenticator app MFA.',\n )\n }\n\n return await awsCognitoClient.setupMfaAuthenticatorApp(options)\n}\n\nexport {\n init,\n registerAuthListener,\n loginUsernamePassword,\n loginHostedUI,\n handleAuthentication,\n changePassword,\n forgotPassword,\n logoutHostedUI,\n logout,\n isLoggedIn,\n getCognitoIdToken,\n getUserProfile,\n getUserFriendlyName,\n getMfaSettings,\n updateUserPhoneNumber,\n removeUserPhoneNumber,\n verifyUserPhoneNumber,\n disableMfaMethod,\n setPreferredMfaMethod,\n setupSmsMfa,\n setupMfaAuthenticatorApp,\n generateMfaAuthenticatorAppQrCodeUrl,\n DEFAULT_MFA_SETTINGS,\n}\nexport type { LoginAttemptResponse, LoggedInMfaMethod, MfaMethod, MfaSettings }\n"]}
1
+ {"version":3,"file":"cognito.js","sourceRoot":"","sources":["../../../src/apps/services/cognito.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,SAAS,EAAE,MAAM,YAAY,CAAA;AAEtC,OAAO,gBAAgB,EAAE,EACvB,oBAAoB,GAKrB,MAAM,oBAAoB,CAAA;AAE3B,OAAO,KAAK,cAAc,MAAM,oBAAoB,CAAA;AACpD,OAAO,EAAE,WAAW,EAAE,MAAM,oBAAoB,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c,EACd,cAAc,EACd,cAAc,EACd,MAAM,EACN,UAAU,EACV,iBAAiB,EACjB,cAAc,EACd,mBAAmB,EACnB,cAAc,EACd,qBAAqB,EACrB,qBAAqB,EACrB,qBAAqB,EACrB,gBAAgB,EAChB,qBAAqB,EACrB,WAAW,EACX,wBAAwB,EACxB,oCAAoC,EACpC,oBAAoB,GACrB,CAAA","sourcesContent":["import { jwtDecode } from 'jwt-decode'\n\nimport AWSCognitoClient, {\n DEFAULT_MFA_SETTINGS,\n LoginAttemptResponse,\n LoggedInMfaMethod,\n MfaMethod,\n MfaSettings,\n} from './AWSCognitoClient'\n\nimport * as offlineService from '../offline-service'\nimport { userService } from '@oneblink/sdk-core'\nimport { MiscTypes } from '@oneblink/types'\nimport { HTTPError, postRequest } from './fetch'\nimport tenants from '../tenants'\nimport OneBlinkAppsError from './errors/oneBlinkAppsError'\n\ninterface CognitoServiceData {\n oAuthClientId: string\n loginDomain: string\n region: string\n redirectUri: string\n logoutUri: string\n}\n\nconst CONTINUE_TO = 'continueTo'\n\nlet awsCognitoClient: null | AWSCognitoClient = null\n\nfunction init(cognitoServiceData: CognitoServiceData) {\n console.log('Initiating CognitoIdentityServiceProvider', cognitoServiceData)\n\n awsCognitoClient = new AWSCognitoClient({\n clientId: cognitoServiceData.oAuthClientId,\n region: cognitoServiceData.region,\n loginDomain: cognitoServiceData.loginDomain,\n redirectUri: cognitoServiceData.redirectUri,\n logoutUri: cognitoServiceData.logoutUri,\n })\n}\n\n/**\n * Register a listener function that will be call when authentication tokens are\n * updated or removed.\n *\n * #### Example\n *\n * ```js\n * const listener = async () => {\n * // Check if the user is logged in still\n * const isLoggedIn = authService.isLoggedIn()\n * }\n * const deregister = await authService.registerAuthListener(listener)\n *\n * // When no longer needed, remember to deregister the listener\n * deregister()\n * ```\n *\n * @param listener\n * @returns\n */\nfunction registerAuthListener(listener: () => unknown): () => void {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to register a listener.',\n )\n }\n return awsCognitoClient.registerListener(listener)\n}\n\n/**\n * Create a session for a user by entering a username and password. If the user\n * requires a password reset, the \"resetPasswordCallback\" property will be\n * returned. This function should be called with the new password once entered\n * by the user. If the user requires an MFA token, the \"mfa\" property will be\n * returned. Its \"codeCallback\" should be called with the one-time token. The\n * functions returned are recursive and the result from each of them is the same\n * result from the loginUsernamePassword() function. Each time the response\n * includes a callback, you will need to begin the process again until all\n * callbacks are handled.\n *\n * #### Example\n *\n * ```js\n * async function handleLoginAttemptResponse({\n * resetPasswordCallback,\n * mfa,\n * }) {\n * // \"resetPasswordCallback\" will be undefined if a password reset was not required.\n * if (resetPasswordCallback) {\n * // Prompt the user to enter a new password\n * const newPassword = prompt(\n * 'The password you entered was only temporary, and must be reset for security purposes. Please enter your new password below to continue.',\n * )\n * const resetPasswordResponse =\n * await resetPasswordCallback(newPassword)\n * return await handleLoginAttemptResponse(resetPasswordResponse)\n * }\n *\n * // \"mfa\" will be undefined if MFA is not setup.\n * if (mfa) {\n * // Prompt the user to enter an MFA code\n * const code = prompt(\n * mfa.method === 'email'\n * ? 'Please enter the one-time code sent to your email.'\n * : 'Please enter a one-time code from your MFA app.',\n * )\n * const mfaCodeResponse = await mfa.codeCallback(code)\n * return await handleLoginAttemptResponse(mfaCodeResponse)\n * }\n * }\n *\n * const username = 'user@email.io'\n * const password = 'P@$5w0rd'\n *\n * const loginAttemptResponse = await authService.loginUsernamePassword(\n * username,\n * password,\n * )\n *\n * await handleLoginAttemptResponse(loginAttemptResponse)\n * ```\n *\n * @param username\n * @param password\n * @returns\n */\nasync function loginUsernamePassword(username: string, password: string) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to login.',\n )\n }\n console.log('Attempting sign using username', username)\n return awsCognitoClient.loginUsernamePassword(\n username.toLowerCase(),\n password,\n )\n}\n\n/**\n * Redirect the user to the login screen. Passing an `identityProvider` is\n * optionally, it will allow users to skip the login page and be directed\n * straight to that providers login page\n *\n * #### Example\n *\n * ```js\n * // OPtionally pass a\n * const identityProvider = 'Google'\n * await authService.loginHostedUI(identityProvider)\n * // User will be redirected to login page or promise will resolve\n * ```\n *\n * @param identityProviderName\n * @returns\n */\nasync function loginHostedUI(identityProviderName?: string): Promise<void> {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to login.',\n )\n }\n const continueTo = `${window.location.pathname}${window.location.search}`\n localStorage.setItem(CONTINUE_TO, continueTo)\n\n return awsCognitoClient.loginHostedUI(identityProviderName)\n}\n\n/**\n * This function should be called when the user is redirected back to your app\n * after a login attempt. It will use the query string add the redirect URL to\n * create a session for the current user. It will return a URL as a `string`\n * that should be redirected to within your app.\n *\n * #### Example\n *\n * ```js\n * try {\n * const continueTo = await authService.handleAuthentication()\n * // Redirect the user back to where they were before attempting to login\n * window.location.href = continueTo\n * } catch (error) {\n * // handle failed login attempts here.\n * }\n * ```\n *\n * @returns\n */\nasync function handleAuthentication(): Promise<string> {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to handle authentication in URL.',\n )\n }\n\n const continueTo = localStorage.getItem(CONTINUE_TO) || '/'\n if (isLoggedIn()) {\n console.log('Already authenticated, redirecting to:', continueTo)\n } else {\n await awsCognitoClient.handleAuthentication()\n }\n\n localStorage.removeItem(CONTINUE_TO)\n\n return continueTo\n}\n\n/**\n * Allow the currently logged in user to change their password by passing their\n * existing password and a new password.\n *\n * #### Example\n *\n * ```js\n * const currentPassword = 'P@$5w0rd'\n * const newPassword = 'P@$5w0rD'\n * await authService.changePassword(currentPassword, newPassword)\n * ```\n *\n * @param existingPassword\n * @param newPassword\n * @returns\n */\nasync function changePassword(existingPassword: string, newPassword: string) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to change passwords.',\n )\n }\n\n return await awsCognitoClient.changePassword(existingPassword, newPassword)\n}\n\n/**\n * Allow a user to start the forgot password process. The user will be emailed a\n * temporary code that must be passed with a new password to the function\n * returned.\n *\n * #### Example\n *\n * ```js\n * const username = 'user@email.io'\n * const finishForgotPassword = await authService.forgotPassword(username)\n *\n * // Prompt the user to enter the code and a new password\n * const code = prompt(\n * 'You have been emailed a verification code, please enter it here.',\n * )\n * const newPassword = prompt('Please enter a new password to continue.')\n * await finishForgotPassword(code, newPassword)\n * ```\n *\n * @param username\n * @param formsAppId Used to give the resulting email sent to the user\n * associated forms app branding and sending address\n * @returns\n */\nasync function forgotPassword(\n username: string,\n /**\n * Used to give the resulting email sent to the user associated forms app\n * branding and sending address\n */\n formsAppId?: number,\n): Promise<(code: string, password: string) => Promise<void>> {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before starting the forgot password process.',\n )\n }\n\n try {\n const url = `${tenants.current.apiOrigin}/authentication/reset-password`\n await postRequest(url, {\n username,\n formsAppId,\n })\n } catch (err) {\n const error = err as HTTPError\n switch (error.status) {\n case 400: {\n throw new OneBlinkAppsError(error.message, {\n title: 'Invalid Request',\n httpStatusCode: error.status,\n })\n }\n default: {\n throw new OneBlinkAppsError(\n 'An unknown error has occurred. Please contact support if the problem persists.',\n {\n originalError: error,\n httpStatusCode: error.status,\n },\n )\n }\n }\n }\n\n return async (code, password) => {\n await awsCognitoClient?.confirmForgotPassword({\n username,\n code,\n password,\n })\n }\n}\n\n/**\n * Redirect the user to the logout screen to clear the users session on the\n * hosted login page. User will then be redirected to `/logout`. After being\n * redirected back to the application, the `logout()` function should be called\n * to clear the session data from browser storage.\n *\n * #### Example\n *\n * ```js\n * authService.logoutHostedUI()\n * ```\n */\nfunction logoutHostedUI(): void {\n if (awsCognitoClient) {\n awsCognitoClient.logoutHostedUI()\n }\n}\n\nasync function logout() {\n if (awsCognitoClient) {\n await awsCognitoClient.logout()\n }\n}\n\n/**\n * Check if the user is currently logged in\n *\n * #### Example\n *\n * ```js\n * const isLoggedIn = authService.isLoggedIn()\n * // handle user being logged in or not\n * ```\n *\n * @returns\n */\nfunction isLoggedIn(): boolean {\n return !!(awsCognitoClient && awsCognitoClient._getRefreshToken())\n}\n\nasync function getCognitoIdToken(): Promise<string | undefined> {\n if (!awsCognitoClient) {\n return\n }\n\n if (offlineService.isOffline()) {\n return awsCognitoClient._getIdToken()\n }\n\n return await awsCognitoClient.getIdToken()\n}\n\n/**\n * Get current users profile based on there Id Token payload. This will return\n * `null` if the the current user is not logged in.\n *\n * #### Example\n *\n * ```js\n * const profile = authService.getUserProfile()\n * if (profile) {\n * // Use profile here\n * }\n * ```\n *\n * @returns\n */\nfunction getUserProfile(): MiscTypes.UserProfile | null {\n if (!awsCognitoClient) {\n return null\n }\n const idToken = awsCognitoClient._getIdToken()\n if (!idToken) {\n return null\n }\n\n const jwtToken = jwtDecode(idToken)\n return userService.parseUserProfile(jwtToken) || null\n}\n\nexport function getUsername(): string | undefined {\n const profile = getUserProfile()\n if (!profile) {\n return undefined\n }\n\n return profile.username\n}\n\n/**\n * A friendly `string` that represents the current user. Uses first name, last\n * name, full name and username. This will return `null` the current user is not\n * logged in.\n *\n * #### Example\n *\n * ```js\n * const name = authService.getUserFriendlyName()\n * if (name) {\n * // Display current user's name\n * }\n * ```\n *\n * @returns\n */\nfunction getUserFriendlyName(): string | undefined {\n const profile = getUserProfile()\n if (!profile) {\n return\n }\n\n return userService.getUserFriendlyName(profile)\n}\n\n/**\n * Generate a QR code link to display to a user after they have initiated\n * authenticator app MFA setup.\n *\n * #### Example\n *\n * ```js\n * const mfaAuthenticatorAppSetupQrCodeUrl =\n * mfaService.generateMfaAuthenticatorAppQrCodeUrl()\n * if (mfaAuthenticatorAppSetupQrCodeUrl) {\n * // use mfaAuthenticatorAppSetupQrCodeUrl to display QR code to user\n * }\n * ```\n *\n * @param mfaAuthenticatorAppSetup\n * @param authenticatorAppDisplayName Name shown in the authenticator app. When\n * omitted, the product name is used. Console sign-in omits this.\n * @returns\n */\nfunction generateMfaAuthenticatorAppQrCodeUrl(\n mfaAuthenticatorAppSetup: Awaited<\n ReturnType<typeof setupMfaAuthenticatorApp>\n >,\n authenticatorAppDisplayName?: string,\n): string | undefined {\n const profile = getUserProfile()\n if (!profile || !mfaAuthenticatorAppSetup) {\n return\n }\n\n const displayName = authenticatorAppDisplayName?.trim()\n if (displayName) {\n const issuer = encodeURIComponent(displayName)\n return `otpauth://totp/${issuer}:${profile.email}?secret=${mfaAuthenticatorAppSetup.secretCode}&issuer=${issuer}`\n }\n\n // Console MFA keeps the product name, including the unencoded space in\n // \"OneBlink LcS\". App users pass authenticatorAppDisplayName instead.\n return `otpauth://totp/${tenants.current.productShortName}:${profile.email}?secret=${mfaAuthenticatorAppSetup.secretCode}&issuer=${tenants.current.productShortName}`\n}\n\nasync function getMfaSettings(abortSignal?: AbortSignal) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before checking MFA settings.',\n )\n }\n\n return await awsCognitoClient.getMfaSettings(abortSignal)\n}\n\nasync function updateUserPhoneNumber(phoneNumber: string) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before updating the user phone number.',\n )\n }\n\n return await awsCognitoClient.updateUserPhoneNumber(phoneNumber)\n}\n\nasync function removeUserPhoneNumber() {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before removing the user phone number.',\n )\n }\n\n return await awsCognitoClient.removeUserPhoneNumber()\n}\n\nasync function verifyUserPhoneNumber(code: string) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before verifying the user phone number.',\n )\n }\n\n return await awsCognitoClient.verifyUserPhoneNumber(code)\n}\n\nasync function setupSmsMfa(options?: { preferred?: boolean }) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to setup SMS MFA.',\n )\n }\n\n return await awsCognitoClient.setupSmsMfa(options)\n}\n\nasync function disableMfaMethod(method: MfaMethod) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to disable an MFA method.',\n )\n }\n\n return await awsCognitoClient.disableMfaMethod(method)\n}\n\nasync function setPreferredMfaMethod(method: MfaMethod) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to set the preferred MFA method.',\n )\n }\n\n return await awsCognitoClient.setPreferredMfaMethod(method)\n}\n\n/**\n * Setup authenticator app MFA for the current user. The result will include a\n * callback that should be called with the valid TOTP from an authenticator\n * app.\n *\n * #### Example\n *\n * ```js\n * const { secretCode, mfaCodeCallback } =\n * await mfaService.setupMfaAuthenticatorApp()\n * // Prompt the user to enter an MFA code\n * const code = prompt(\n * `Please enter a one-time code from your MFA app after creating a new entry with secret: ${secretCode}.`,\n * )\n * await mfaCodeCallback(code)\n * ```\n *\n * @returns\n */\nasync function setupMfaAuthenticatorApp(options?: { preferred?: boolean }) {\n if (!awsCognitoClient) {\n throw new Error(\n '\"authService\" has not been initiated. You must call the init() function before attempting to setup authenticator app MFA.',\n )\n }\n\n return await awsCognitoClient.setupMfaAuthenticatorApp(options)\n}\n\nexport {\n init,\n registerAuthListener,\n loginUsernamePassword,\n loginHostedUI,\n handleAuthentication,\n changePassword,\n forgotPassword,\n logoutHostedUI,\n logout,\n isLoggedIn,\n getCognitoIdToken,\n getUserProfile,\n getUserFriendlyName,\n getMfaSettings,\n updateUserPhoneNumber,\n removeUserPhoneNumber,\n verifyUserPhoneNumber,\n disableMfaMethod,\n setPreferredMfaMethod,\n setupSmsMfa,\n setupMfaAuthenticatorApp,\n generateMfaAuthenticatorAppQrCodeUrl,\n DEFAULT_MFA_SETTINGS,\n}\nexport type { LoginAttemptResponse, LoggedInMfaMethod, MfaMethod, MfaSettings }\n"]}
@@ -8,14 +8,14 @@ import useMfa from '../../hooks/useMfa';
8
8
  import { CopyToClipBoardIconButton } from '../CopyToClipboardIconButton';
9
9
  import InputField from '../InputField';
10
10
  function MfaAuthenticatorAppDialog() {
11
- const { mfaAuthenticatorAppSetup, cancelMfaAuthenticatorAppSetup, completeMfaAuthenticatorAppSetup, } = useMfa();
11
+ const { mfaAuthenticatorAppSetup, cancelMfaAuthenticatorAppSetup, completeMfaAuthenticatorAppSetup, authenticatorAppDisplayName, } = useMfa();
12
12
  const [code, setState] = React.useState('');
13
13
  const [isShowingSecretCode, showSecretCode, hideSecretCode] = useBooleanState(false);
14
14
  const qrcodeValue = React.useMemo(() => {
15
15
  if (mfaAuthenticatorAppSetup) {
16
- return mfaService.generateMfaAuthenticatorAppQrCodeUrl(mfaAuthenticatorAppSetup);
16
+ return mfaService.generateMfaAuthenticatorAppQrCodeUrl(mfaAuthenticatorAppSetup, authenticatorAppDisplayName);
17
17
  }
18
- }, [mfaAuthenticatorAppSetup]);
18
+ }, [authenticatorAppDisplayName, mfaAuthenticatorAppSetup]);
19
19
  const [isSaving, startSaving, stopSaving] = useBooleanState(false);
20
20
  const handleSubmit = React.useCallback(async (event) => {
21
21
  event.preventDefault();
@@ -38,7 +38,9 @@ function MfaAuthenticatorAppDialog() {
38
38
  startSaving,
39
39
  stopSaving,
40
40
  ]);
41
- return (_jsx(React.Fragment, { children: _jsx(Dialog, { open: !!mfaAuthenticatorAppSetup, onClose: cancelMfaAuthenticatorAppSetup, title: "Complete MFA Setup", children: _jsxs("form", { onSubmit: handleSubmit, children: [_jsx(DialogTitle, { children: "Authenticator App Setup" }), _jsxs(DialogContent, { dividers: true, children: [_jsxs(Typography, { variant: "body2", component: "p", sx: { mb: 2 }, children: ["Authenticator apps like", ' ', _jsx(Link, { href: "https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2", target: "_blank", rel: "noopener noreferrer", children: "Google Authenticator" }), ' ', "and", ' ', _jsx(Link, { href: "https://www.microsoft.com/en-us/security/mobile-authenticator-app", target: "_blank", rel: "noopener noreferrer", children: "Microsoft Authenticator" }), ' ', "generate one-time passwords that are used as a second factor to verify your identity when prompted during sign-in."] }), _jsx(Typography, { variant: "subtitle2", gutterBottom: true, children: "Scan the QR code" }), _jsx(Typography, { variant: "body2", sx: { mb: 2 }, children: "Use an authenticator app or browser extension to scan the QR code below." }), _jsx(Box, { marginBottom: 2, children: _jsxs(Grid, { container: true, spacing: 2, alignItems: "center", children: [_jsx(Grid, { children: _jsx(Box, { border: 1, padding: 2, borderRadius: 1, borderColor: "divider", display: "inline-block", lineHeight: 0, children: _jsx(QRCodeSVG, { value: qrcodeValue || '' }) }) }), _jsx(Grid, { size: { xs: 'grow' }, children: _jsxs(Typography, { variant: "caption", color: "text.secondary", children: ["Having trouble scanning the QR code?", ' ', _jsx(Link, { type: "button", onClick: showSecretCode, component: "button", children: "Click here" }), ' ', "to display the setup key which can be manually entered in your authenticator app."] }) })] }) }), _jsx(Collapse, { in: isShowingSecretCode, children: _jsx(Box, { marginBottom: 2, children: _jsx(InputField, { label: "Setup Key", value: (mfaAuthenticatorAppSetup === null || mfaAuthenticatorAppSetup === void 0 ? void 0 : mfaAuthenticatorAppSetup.secretCode) || '', variant: "filled", focused: false, sx: {
41
+ return (_jsx(React.Fragment, { children: _jsx(Dialog, { open: !!mfaAuthenticatorAppSetup, onClose: cancelMfaAuthenticatorAppSetup, title: "Complete MFA Setup", children: _jsxs("form", { onSubmit: handleSubmit, children: [_jsx(DialogTitle, { children: "Authenticator App Setup" }), _jsxs(DialogContent, { dividers: true, children: [_jsxs(Typography, { variant: "body2", component: "p", sx: { mb: 2 }, children: ["Authenticator apps like", ' ', _jsx(Link, { href: "https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2", target: "_blank", rel: "noopener noreferrer", children: "Google Authenticator" }), ' ', "and", ' ', _jsx(Link, { href: "https://www.microsoft.com/en-us/security/mobile-authenticator-app", target: "_blank", rel: "noopener noreferrer", children: "Microsoft Authenticator" }), ' ', "generate one-time passwords that are used as a second factor to verify your identity when prompted during sign-in."] }), _jsx(Typography, { variant: "subtitle2", gutterBottom: true, children: "Scan the QR code" }), _jsxs(Typography, { variant: "body2", sx: { mb: 2 }, children: ["Use an authenticator app or browser extension to scan the QR code below.", authenticatorAppDisplayName
42
+ ? ` This account will appear as "${authenticatorAppDisplayName}".`
43
+ : ''] }), _jsx(Box, { marginBottom: 2, children: _jsxs(Grid, { container: true, spacing: 2, alignItems: "center", children: [_jsx(Grid, { children: _jsx(Box, { border: 1, padding: 2, borderRadius: 1, borderColor: "divider", display: "inline-block", lineHeight: 0, children: _jsx(QRCodeSVG, { value: qrcodeValue || '' }) }) }), _jsx(Grid, { size: { xs: 'grow' }, children: _jsxs(Typography, { variant: "caption", color: "text.secondary", children: ["Having trouble scanning the QR code?", ' ', _jsx(Link, { type: "button", onClick: showSecretCode, component: "button", children: "Click here" }), ' ', "to display the setup key which can be manually entered in your authenticator app."] }) })] }) }), _jsx(Collapse, { in: isShowingSecretCode, children: _jsx(Box, { marginBottom: 2, children: _jsx(InputField, { label: "Setup Key", value: (mfaAuthenticatorAppSetup === null || mfaAuthenticatorAppSetup === void 0 ? void 0 : mfaAuthenticatorAppSetup.secretCode) || '', variant: "filled", focused: false, sx: {
42
44
  input: {
43
45
  cursor: 'default !important',
44
46
  },
@@ -1 +1 @@
1
- {"version":3,"file":"MfaAuthenticatorAppDialog.js","sourceRoot":"","sources":["../../../src/components/mfa/MfaAuthenticatorAppDialog.tsx"],"names":[],"mappings":";AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAA;AACxC,OAAO,EACL,GAAG,EACH,QAAQ,EACR,MAAM,EACN,IAAI,EACJ,IAAI,EACJ,UAAU,EACV,aAAa,EACb,aAAa,EACb,MAAM,EACN,WAAW,GACZ,MAAM,eAAe,CAAA;AACtB,OAAO,EAAE,UAAU,EAAE,MAAM,YAAY,CAAA;AACvC,OAAO,eAAe,MAAM,6BAA6B,CAAA;AACzD,OAAO,MAAM,MAAM,oBAAoB,CAAA;AACvC,OAAO,EAAE,yBAAyB,EAAE,MAAM,8BAA8B,CAAA;AACxE,OAAO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AC,KAAK,CAAA;oCACnC,QAAQ,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,CAAA;gCAC1B,CAAC,EACD,QAAQ,EAAE,QAAQ,kBACL,4BAA4B,GACzC,IACY,EAChB,MAAC,aAAa,eACZ,KAAC,MAAM,IACL,IAAI,EAAC,QAAQ,EACb,OAAO,EAAE,8BAA8B,EACvC,QAAQ,EAAE,QAAQ,uBAGX,EACT,KAAC,MAAM,IACL,IAAI,EAAC,QAAQ,EACb,OAAO,EAAC,WAAW,EACnB,KAAK,EAAC,SAAS,EACf,QAAQ,EAAE,CAAC,IAAI,IAAI,QAAQ,qBAGpB,IACK,IACX,GACA,GACM,CAClB,CAAA;AACH,CAAC;AAED;;;;;;;GAOG;AACH,eAAe,KAAK,CAAC,IAAI,CAAC,yBAAyB,CAAC,CAAA","sourcesContent":["import * as React from 'react'\nimport { QRCodeSVG } from 'qrcode.react'\nimport {\n Box,\n Collapse,\n Dialog,\n Grid,\n Link,\n Typography,\n DialogContent,\n DialogActions,\n Button,\n DialogTitle,\n} from '@mui/material'\nimport { mfaService } from '../../apps'\nimport useBooleanState from '../../hooks/useBooleanState'\nimport useMfa from '../../hooks/useMfa'\nimport { CopyToClipBoardIconButton } from '../CopyToClipboardIconButton'\nimport InputField from '../InputField'\n\nfunction MfaAuthenticatorAppDialog() {\n const {\n mfaAuthenticatorAppSetup,\n cancelMfaAuthenticatorAppSetup,\n completeMfaAuthenticatorAppSetup,\n } = useMfa()\n\n const [code, setState] = React.useState('')\n const [isShowingSecretCode, showSecretCode, hideSecretCode] =\n useBooleanState(false)\n\n const qrcodeValue = React.useMemo(() => {\n if (mfaAuthenticatorAppSetup) {\n return mfaService.generateMfaAuthenticatorAppQrCodeUrl(\n mfaAuthenticatorAppSetup,\n )\n }\n }, [mfaAuthenticatorAppSetup])\n\n const [isSaving, startSaving, stopSaving] = useBooleanState(false)\n const handleSubmit = React.useCallback(\n async (event: React.SubmitEvent<HTMLFormElement>) => {\n event.preventDefault()\n\n if (!code || !mfaAuthenticatorAppSetup || isSaving) {\n return\n }\n\n startSaving()\n try {\n await mfaAuthenticatorAppSetup.mfaCodeCallback(code)\n await completeMfaAuthenticatorAppSetup()\n } finally {\n stopSaving()\n }\n },\n [\n code,\n completeMfaAuthenticatorAppSetup,\n isSaving,\n mfaAuthenticatorAppSetup,\n startSaving,\n stopSaving,\n ],\n )\n\n return (\n <React.Fragment>\n <Dialog\n open={!!mfaAuthenticatorAppSetup}\n onClose={cancelMfaAuthenticatorAppSetup}\n title=\"Complete MFA Setup\"\n >\n <form onSubmit={handleSubmit}>\n <DialogTitle>Authenticator App Setup</DialogTitle>\n <DialogContent dividers>\n <Typography variant=\"body2\" component=\"p\" sx={{ mb: 2 }}>\n Authenticator apps like{' '}\n <Link\n href=\"https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n Google Authenticator\n </Link>{' '}\n and{' '}\n <Link\n href=\"https://www.microsoft.com/en-us/security/mobile-authenticator-app\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n Microsoft Authenticator\n </Link>{' '}\n generate one-time passwords that are used as a second factor to\n verify your identity when prompted during sign-in.\n </Typography>\n <Typography variant=\"subtitle2\" gutterBottom>\n Scan the QR code\n </Typography>\n <Typography variant=\"body2\" sx={{ mb: 2 }}>\n Use an authenticator app or browser extension to scan the QR code\n below.\n </Typography>\n\n <Box marginBottom={2}>\n <Grid container spacing={2} alignItems=\"center\">\n <Grid>\n <Box\n border={1}\n padding={2}\n borderRadius={1}\n borderColor=\"divider\"\n display=\"inline-block\"\n lineHeight={0}\n >\n <QRCodeSVG value={qrcodeValue || ''} />\n </Box>\n </Grid>\n <Grid size={{ xs: 'grow' }}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n Having trouble scanning the QR code?{' '}\n <Link\n type=\"button\"\n onClick={showSecretCode}\n component=\"button\"\n >\n Click here\n </Link>{' '}\n to display the setup key which can be manually entered in\n your authenticator app.\n </Typography>\n </Grid>\n </Grid>\n </Box>\n\n <Collapse in={isShowingSecretCode}>\n <Box marginBottom={2}>\n <InputField\n label=\"Setup Key\"\n value={mfaAuthenticatorAppSetup?.secretCode || ''}\n variant=\"filled\"\n focused={false}\n sx={{\n input: {\n cursor: 'default !important',\n },\n }}\n fullWidth\n slotProps={{\n input: {\n readOnly: true,\n endAdornment: (\n <CopyToClipBoardIconButton\n text={mfaAuthenticatorAppSetup?.secretCode || ''}\n />\n ),\n },\n }}\n helperText={\n <>\n <Link\n type=\"button\"\n onClick={hideSecretCode}\n component=\"button\"\n >\n Click here\n </Link>{' '}\n to hide the setup key\n </>\n }\n />\n </Box>\n </Collapse>\n\n <Typography variant=\"subtitle2\" gutterBottom>\n Verify App\n </Typography>\n <Typography variant=\"body2\" sx={{ mb: 2 }}>\n Enter the 6-digit code found in your authenticator app.\n </Typography>\n\n <InputField\n autoFocus\n margin=\"none\"\n name=\"code\"\n label=\"Code\"\n fullWidth\n placeholder=\"XXXXXX\"\n variant=\"outlined\"\n value={code}\n onChange={(event) => {\n const newValue = event.target.value\n setState(() => newValue)\n }}\n disabled={isSaving}\n data-cypress=\"mfa-authenticator-app-code\"\n />\n </DialogContent>\n <DialogActions>\n <Button\n type=\"button\"\n onClick={cancelMfaAuthenticatorAppSetup}\n disabled={isSaving}\n >\n Cancel\n </Button>\n <Button\n type=\"submit\"\n variant=\"contained\"\n color=\"primary\"\n disabled={!code || isSaving}\n >\n Save\n </Button>\n </DialogActions>\n </form>\n </Dialog>\n </React.Fragment>\n )\n}\n\n/**\n * React Component that guides users through authenticator app MFA setup,\n * including QR code scanning and verification code entry. Typically rendered by\n * `<MultiFactorAuthentication />` within an\n * `<MfaProvider />` tree.\n *\n * @returns\n */\nexport default React.memo(MfaAuthenticatorAppDialog)\n"]}
1
+ {"version":3,"file":"MfaAuthenticatorAppDialog.js","sourceRoot":"","sources":["../../../src/components/mfa/MfaAuthenticatorAppDialog.tsx"],"names":[],"mappings":";AAA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,IAAI,IACH,IAAI,EAAC,QAAQ,EACb,OAAO,EAAE,cAAc,EACvB,SAAS,EAAC,QAAQ,2BAGb,EAAC,GAAG,6BAEV,GAEL,GACE,GACG,EAEX,KAAC,UAAU,IAAC,OAAO,EAAC,WAAW,EAAC,YAAY,iCAE/B,EACb,KAAC,UAAU,IAAC,OAAO,EAAC,OAAO,EAAC,EAAE,EAAE,EAAE,EAAE,EAAE,CAAC,EAAE,wEAE5B,EAEb,KAAC,UAAU,IACT,SAAS,QACT,MAAM,EAAC,MAAM,EACb,IAAI,EAAC,MAAM,EACX,KAAK,EAAC,MAAM,EACZ,SAAS,QACT,WAAW,EAAC,QAAQ,EACpB,OAAO,EAAC,UAAU,EAClB,KAAK,EAAE,IAAI,EACX,QAAQ,EAAE,CAAC,KAAK,EAAE,EAAE;oCAClB,MAAM,QAAQ,GAAG,KAAK,CAAC,MAAM,CAAC,KAAK,CAAA;oCACnC,QAAQ,CAAC,GAAG,EAAE,CAAC,QAAQ,CAAC,CAAA;gCAC1B,CAAC,EACD,QAAQ,EAAE,QAAQ,kBACL,4BAA4B,GACzC,IACY,EAChB,MAAC,aAAa,eACZ,KAAC,MAAM,IACL,IAAI,EAAC,QAAQ,EACb,OAAO,EAAE,8BAA8B,EACvC,QAAQ,EAAE,QAAQ,uBAGX,EACT,KAAC,MAAM,IACL,IAAI,EAAC,QAAQ,EACb,OAAO,EAAC,WAAW,EACnB,KAAK,EAAC,SAAS,EACf,QAAQ,EAAE,CAAC,IAAI,IAAI,QAAQ,qBAGpB,IACK,IACX,GACA,GACM,CAClB,CAAA;AACH,CAAC;AAED;;;;;;;GAOG;AACH,eAAe,KAAK,CAAC,IAAI,CAAC,yBAAyB,CAAC,CAAA","sourcesContent":["import * as React from 'react'\nimport { QRCodeSVG } from 'qrcode.react'\nimport {\n Box,\n Collapse,\n Dialog,\n Grid,\n Link,\n Typography,\n DialogContent,\n DialogActions,\n Button,\n DialogTitle,\n} from '@mui/material'\nimport { mfaService } from '../../apps'\nimport useBooleanState from '../../hooks/useBooleanState'\nimport useMfa from '../../hooks/useMfa'\nimport { CopyToClipBoardIconButton } from '../CopyToClipboardIconButton'\nimport InputField from '../InputField'\n\nfunction MfaAuthenticatorAppDialog() {\n const {\n mfaAuthenticatorAppSetup,\n cancelMfaAuthenticatorAppSetup,\n completeMfaAuthenticatorAppSetup,\n authenticatorAppDisplayName,\n } = useMfa()\n\n const [code, setState] = React.useState('')\n const [isShowingSecretCode, showSecretCode, hideSecretCode] =\n useBooleanState(false)\n\n const qrcodeValue = React.useMemo(() => {\n if (mfaAuthenticatorAppSetup) {\n return mfaService.generateMfaAuthenticatorAppQrCodeUrl(\n mfaAuthenticatorAppSetup,\n authenticatorAppDisplayName,\n )\n }\n }, [authenticatorAppDisplayName, mfaAuthenticatorAppSetup])\n\n const [isSaving, startSaving, stopSaving] = useBooleanState(false)\n const handleSubmit = React.useCallback(\n async (event: React.SubmitEvent<HTMLFormElement>) => {\n event.preventDefault()\n\n if (!code || !mfaAuthenticatorAppSetup || isSaving) {\n return\n }\n\n startSaving()\n try {\n await mfaAuthenticatorAppSetup.mfaCodeCallback(code)\n await completeMfaAuthenticatorAppSetup()\n } finally {\n stopSaving()\n }\n },\n [\n code,\n completeMfaAuthenticatorAppSetup,\n isSaving,\n mfaAuthenticatorAppSetup,\n startSaving,\n stopSaving,\n ],\n )\n\n return (\n <React.Fragment>\n <Dialog\n open={!!mfaAuthenticatorAppSetup}\n onClose={cancelMfaAuthenticatorAppSetup}\n title=\"Complete MFA Setup\"\n >\n <form onSubmit={handleSubmit}>\n <DialogTitle>Authenticator App Setup</DialogTitle>\n <DialogContent dividers>\n <Typography variant=\"body2\" component=\"p\" sx={{ mb: 2 }}>\n Authenticator apps like{' '}\n <Link\n href=\"https://play.google.com/store/apps/details?id=com.google.android.apps.authenticator2\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n Google Authenticator\n </Link>{' '}\n and{' '}\n <Link\n href=\"https://www.microsoft.com/en-us/security/mobile-authenticator-app\"\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n >\n Microsoft Authenticator\n </Link>{' '}\n generate one-time passwords that are used as a second factor to\n verify your identity when prompted during sign-in.\n </Typography>\n <Typography variant=\"subtitle2\" gutterBottom>\n Scan the QR code\n </Typography>\n <Typography variant=\"body2\" sx={{ mb: 2 }}>\n Use an authenticator app or browser extension to scan the QR code\n below.\n {authenticatorAppDisplayName\n ? ` This account will appear as \"${authenticatorAppDisplayName}\".`\n : ''}\n </Typography>\n\n <Box marginBottom={2}>\n <Grid container spacing={2} alignItems=\"center\">\n <Grid>\n <Box\n border={1}\n padding={2}\n borderRadius={1}\n borderColor=\"divider\"\n display=\"inline-block\"\n lineHeight={0}\n >\n <QRCodeSVG value={qrcodeValue || ''} />\n </Box>\n </Grid>\n <Grid size={{ xs: 'grow' }}>\n <Typography variant=\"caption\" color=\"text.secondary\">\n Having trouble scanning the QR code?{' '}\n <Link\n type=\"button\"\n onClick={showSecretCode}\n component=\"button\"\n >\n Click here\n </Link>{' '}\n to display the setup key which can be manually entered in\n your authenticator app.\n </Typography>\n </Grid>\n </Grid>\n </Box>\n\n <Collapse in={isShowingSecretCode}>\n <Box marginBottom={2}>\n <InputField\n label=\"Setup Key\"\n value={mfaAuthenticatorAppSetup?.secretCode || ''}\n variant=\"filled\"\n focused={false}\n sx={{\n input: {\n cursor: 'default !important',\n },\n }}\n fullWidth\n slotProps={{\n input: {\n readOnly: true,\n endAdornment: (\n <CopyToClipBoardIconButton\n text={mfaAuthenticatorAppSetup?.secretCode || ''}\n />\n ),\n },\n }}\n helperText={\n <>\n <Link\n type=\"button\"\n onClick={hideSecretCode}\n component=\"button\"\n >\n Click here\n </Link>{' '}\n to hide the setup key\n </>\n }\n />\n </Box>\n </Collapse>\n\n <Typography variant=\"subtitle2\" gutterBottom>\n Verify App\n </Typography>\n <Typography variant=\"body2\" sx={{ mb: 2 }}>\n Enter the 6-digit code found in your authenticator app.\n </Typography>\n\n <InputField\n autoFocus\n margin=\"none\"\n name=\"code\"\n label=\"Code\"\n fullWidth\n placeholder=\"XXXXXX\"\n variant=\"outlined\"\n value={code}\n onChange={(event) => {\n const newValue = event.target.value\n setState(() => newValue)\n }}\n disabled={isSaving}\n data-cypress=\"mfa-authenticator-app-code\"\n />\n </DialogContent>\n <DialogActions>\n <Button\n type=\"button\"\n onClick={cancelMfaAuthenticatorAppSetup}\n disabled={isSaving}\n >\n Cancel\n </Button>\n <Button\n type=\"submit\"\n variant=\"contained\"\n color=\"primary\"\n disabled={!code || isSaving}\n >\n Save\n </Button>\n </DialogActions>\n </form>\n </Dialog>\n </React.Fragment>\n )\n}\n\n/**\n * React Component that guides users through authenticator app MFA setup,\n * including QR code scanning and verification code entry. Typically rendered by\n * `<MultiFactorAuthentication />` within an\n * `<MfaProvider />` tree.\n *\n * @returns\n */\nexport default React.memo(MfaAuthenticatorAppDialog)\n"]}
@@ -171,7 +171,9 @@ function AutocompleteDropdown({ id, label, value, placeholder, required, disable
171
171
  export default React.memo(AutocompleteDropdown);
172
172
  function highlightLabel(text, phrase) {
173
173
  if (phrase) {
174
- text = text.replace(new RegExp('(' +
174
+ text = text.replace(
175
+ // eslint-disable-next-line security/detect-non-literal-regexp -- special characters in the phrase are escaped
176
+ new RegExp('(' +
175
177
  phrase.replace(/[`~!@#$%^&*()_|+\-=?;:'",.<>{}[\]\\/]/gi, (char) => `\\${char}`) +
176
178
  ')', 'gi'), '<b>$1</b>');
177
179
  }
@@ -1 +1 @@
1
- {"version":3,"file":"AutocompleteDropdown.js","sourceRoot":"","sources":["../../../src/components/renderer/AutocompleteDropdown.tsx"],"names":[],"mappings":";AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAA;AAEnC,OAAO,eAAe,MAAM,6BAA6B,CAAA;AAEzD,OAAO,EAAE,yBAAyB,EAAE,MAAM,mCAAmC,CAA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K,CAAC,IAAI,CAAC,oBAAoB,CAAgC,CAAA;AAE9E,SAAS,cAAc,CAAC,IAAY,EAAE,MAAc;IAClD,IAAI,MAAM,EAAE,CAAC;QACX,IAAI,GAAG,IAAI,CAAC,OAAO,CACjB,IAAI,MAAM,CACR,GAAG;YACD,MAAM,CAAC,OAAO,CACZ,yCAAyC,EACzC,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,IAAI,EAAE,CAC9B;YACD,GAAG,EACL,IAAI,CACL,EACD,WAAW,CACZ,CAAA;IACH,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC","sourcesContent":["import * as React from 'react'\nimport clsx from 'clsx'\nimport { Sentry } from '../../apps'\n\nimport useBooleanState from '../../hooks/useBooleanState'\nimport { IsDirtyProps } from '../../types/form'\nimport { LookupNotificationContext } from '../../hooks/useLookupNotification'\nimport MaterialIcon from '../MaterialIcon'\nimport FormElementValidationMessage from './FormElementValidationMessage'\n\ntype AutocompleteOption<T> = {\n label: string\n value: string\n data?: T\n}\n\ntype Props<T> = {\n id: string\n label: string\n value: unknown | undefined\n placeholder: string | undefined\n required: boolean | undefined\n disabled: boolean | undefined\n isLoading?: boolean\n hasError?: boolean\n validationMessage: string | undefined\n displayValidationMessage: boolean\n searchDebounceMs: number\n searchMinCharacters: number\n onChangeValue: (\n newValue: string | undefined,\n data?: T,\n ) => Promise<void> | void\n onChangeLabel: (newLabel: string) => void\n onSearch: (\n label: string,\n abortSignal: AbortSignal,\n ) => Promise<AutocompleteOption<T>[]>\n 'aria-describedby'?: string\n branding?: React.ReactNode\n autoComplete?: string\n hideEndAdornment?: boolean\n} & IsDirtyProps\n\nfunction AutocompleteDropdown<T>({\n id,\n label,\n value,\n placeholder,\n required,\n disabled,\n validationMessage,\n displayValidationMessage,\n searchDebounceMs,\n searchMinCharacters,\n isLoading,\n hasError,\n onChangeValue,\n onChangeLabel,\n onSearch,\n isDirty,\n setIsDirty,\n branding,\n autoComplete,\n hideEndAdornment,\n ...props\n}: Props<T>) {\n const optionsContainerElement = React.useRef<HTMLDivElement>(null)\n const [currentFocusedOptionIndex, setCurrentFocusedOptionIndex] =\n React.useState(0)\n const [options, setOptions] = React.useState<AutocompleteOption<T>[]>([])\n const [error, setError] = React.useState<Error | null>(null)\n const [isFetchingOptions, setIsFetchingOptions] = React.useState(false)\n const [isOpen, onOpen, onClose] = useBooleanState(false)\n\n const onSelectOption = React.useCallback(\n (option: AutocompleteOption<T>) => {\n onChangeLabel(option.label)\n onChangeValue(option.value, option.data)\n onClose()\n },\n [onChangeLabel, onChangeValue, onClose],\n )\n\n const handleClickOption = React.useCallback(\n (\n event: React.MouseEvent<HTMLAnchorElement, MouseEvent>,\n option: AutocompleteOption<T>,\n ) => {\n console.log('Selected element option in autocomplete', option)\n\n event.preventDefault()\n event.stopPropagation()\n\n onSelectOption(option)\n },\n [onSelectOption],\n )\n\n const onFocus = React.useCallback(() => {\n setCurrentFocusedOptionIndex(0)\n onOpen()\n }, [onOpen])\n\n // When moving away from the input, if this is no value remove\n // the label to show the user they have not selected a value\n const handleBlur = React.useCallback(\n (inputOption: { label: string; value: unknown | undefined }) => {\n setIsDirty()\n setError(null)\n onClose()\n\n if (Array.isArray(options)) {\n // If there is a label that resembles an option, set that option to be the new value.\n // UNLESS it was the previously selected label. Else, clear the label and the value.\n if (inputOption.label) {\n const lowerCase = inputOption.label.toLowerCase()\n const option = options.find(\n (option) => option.label.toLowerCase() === lowerCase,\n )\n if (option) {\n // If the new option is not equal to the option that is currently selected,\n // we want to update to the new option to ensure that it gets changed.\n if (inputOption.value !== option.value) {\n console.log('Setting value after blurring away from autocomplete')\n onSelectOption(option)\n }\n return\n }\n }\n\n console.log('Removing label after blurring away from autocomplete')\n onChangeValue(undefined)\n onChangeLabel('')\n }\n },\n [\n onChangeLabel,\n onChangeValue,\n onClose,\n onSelectOption,\n options,\n setIsDirty,\n ],\n )\n\n const onKeyDown = React.useCallback<\n React.KeyboardEventHandler<HTMLInputElement>\n >(\n (event) => {\n if (!options) {\n return\n }\n const enterPressed = event.keyCode === 13\n const upArrowPressed = event.keyCode === 38\n const downArrowPressed = event.keyCode === 40\n if (!upArrowPressed && !downArrowPressed && !enterPressed) {\n return\n }\n\n event.preventDefault()\n\n const previousFocusedOptionIndex = currentFocusedOptionIndex\n let nextFocusedOptionIndex = currentFocusedOptionIndex\n if (upArrowPressed) {\n nextFocusedOptionIndex = Math.max(0, currentFocusedOptionIndex - 1)\n } else if (downArrowPressed) {\n nextFocusedOptionIndex = Math.min(\n options.length - 1,\n currentFocusedOptionIndex + 1,\n )\n } else if (enterPressed) {\n const option = options[nextFocusedOptionIndex]\n if (option) {\n onSelectOption(option)\n }\n }\n\n // If the index has changed, need to ensure the active option is visible\n if (\n previousFocusedOptionIndex !== nextFocusedOptionIndex &&\n optionsContainerElement.current\n ) {\n const activeStepElement = optionsContainerElement.current.querySelector(\n `.ob-autocomplete__drop-down-item-${nextFocusedOptionIndex}`,\n )\n if (activeStepElement) {\n activeStepElement.scrollIntoView({\n behavior: 'smooth',\n block: 'nearest',\n inline: 'start',\n })\n }\n setCurrentFocusedOptionIndex(nextFocusedOptionIndex)\n }\n },\n [currentFocusedOptionIndex, options, onSelectOption],\n )\n\n const handleChangeLabel = React.useCallback<\n React.ChangeEventHandler<HTMLInputElement>\n >(\n (e) => {\n const newLabel = e.target.value\n onOpen()\n setCurrentFocusedOptionIndex(0)\n\n onChangeLabel(newLabel)\n },\n [onChangeLabel, onOpen],\n )\n\n React.useEffect(() => {\n setError(null)\n\n if (!isOpen || label.length < searchMinCharacters) {\n setIsFetchingOptions(false)\n return\n }\n\n setIsFetchingOptions(true)\n\n let ignore = false\n const abortController = new AbortController()\n\n const timeoutId = setTimeout(async () => {\n let newOptions: AutocompleteOption<T>[] = []\n let newError = null\n\n try {\n newOptions = await onSearch(label, abortController.signal)\n } catch (error) {\n // Cancelling will throw an error.\n if (!abortController.signal.aborted) {\n console.warn('Error while fetching autocomplete options', error)\n Sentry.captureException(error)\n newError = error as Error\n }\n }\n if (!ignore) {\n setError(newError)\n setOptions(newOptions)\n setIsFetchingOptions(false)\n }\n }, searchDebounceMs)\n\n return () => {\n ignore = true\n clearTimeout(timeoutId)\n abortController.abort()\n }\n }, [isOpen, label, onSearch, searchDebounceMs, searchMinCharacters])\n\n React.useEffect(() => {\n //If there is no value set, we want to clear the label\n //This is to satisfy lookups that return undefined.\n if (!value) {\n onChangeLabel('')\n }\n }, [onChangeLabel, value])\n const { isLookingUp } = React.useContext(LookupNotificationContext)\n\n const isShowingLoading = isFetchingOptions || !!isLoading\n const isShowingValid = !isShowingLoading && value !== undefined\n const isShowingError = !isShowingLoading && !isLookingUp && !!hasError\n\n return (\n <>\n <div\n className={clsx('dropdown', {\n 'is-active': isOpen && Array.isArray(options),\n })}\n >\n <div className=\"field\">\n <div\n className={clsx(\n 'cypress-autocomplete-field-control control is-expanded',\n {\n 'is-loading': isShowingLoading,\n 'has-icons-right': isShowingValid || isShowingError,\n },\n )}\n >\n <input\n type=\"text\"\n placeholder={placeholder}\n id={id}\n autoComplete={autoComplete ?? 'off'}\n className=\"cypress-autocomplete-control input ob-input\"\n required={required}\n value={label}\n disabled={disabled}\n onFocus={onFocus}\n onBlur={() => handleBlur({ label, value })}\n onKeyDown={onKeyDown}\n onChange={handleChangeLabel}\n aria-describedby={props['aria-describedby']}\n aria-required={required}\n />\n {!hideEndAdornment && (\n <>\n {isShowingValid && (\n <span className=\" ob-input-icon icon is-small is-right\">\n <MaterialIcon className=\"is-size-5 has-text-success\">\n check\n </MaterialIcon>\n </span>\n )}\n {isShowingError && (\n <span className=\" ob-input-icon icon is-small is-right\">\n <MaterialIcon className=\"is-size-5 has-text-danger\">\n error\n </MaterialIcon>\n </span>\n )}\n </>\n )}\n </div>\n </div>\n\n <div className=\"dropdown-menu\">\n <div\n ref={optionsContainerElement}\n className=\"ob-autocomplete__dropdown-content dropdown-content cypress-autocomplete-dropdown-content\"\n >\n {error ? (\n <a className=\"dropdown-item cypress-autocomplete-error ob-autocomplete__drop-down-item-error\">\n <span className=\"has-text-danger\">{error.message}</span>\n </a>\n ) : label.length < searchMinCharacters ? (\n <a className=\"dropdown-item cypress-max-characters ob-autocomplete__drop-down-item-max-characters\">\n <i>\n Enter at least {searchMinCharacters} character(s) to search\n </i>\n </a>\n ) : isShowingLoading ? (\n <a className=\"dropdown-item cypress-searching-options ob-autocomplete__drop-down-item-searching\">\n <i>Searching...</i>\n </a>\n ) : options && options.length ? (\n options.map((option, index) => (\n <a\n key={option.value}\n className={clsx(\n `dropdown-item cypress-autocomplete-dropdown-item ob-autocomplete__drop-down-item-${index}`,\n {\n 'is-active': currentFocusedOptionIndex === index,\n },\n )}\n onMouseDown={(e) => handleClickOption(e, option)}\n // eslint-disable-next-line react/no-danger\n dangerouslySetInnerHTML={{\n __html: highlightLabel(option.label, label),\n }}\n />\n ))\n ) : (\n <a className=\"dropdown-item cypress-no-matches-found ob-autocomplete__drop-down-item-no-matches\">\n <i>No matches found</i>\n </a>\n )}\n {branding}\n </div>\n </div>\n </div>\n\n {(isDirty || displayValidationMessage) &&\n !!validationMessage &&\n !isShowingLoading && (\n <FormElementValidationMessage message={validationMessage} />\n )}\n </>\n )\n}\n\nexport default React.memo(AutocompleteDropdown) as typeof AutocompleteDropdown\n\nfunction highlightLabel(text: string, phrase: string) {\n if (phrase) {\n text = text.replace(\n new RegExp(\n '(' +\n phrase.replace(\n /[`~!@#$%^&*()_|+\\-=?;:'\",.<>{}[\\]\\\\/]/gi,\n (char: string) => `\\\\${char}`,\n ) +\n ')',\n 'gi',\n ),\n '<b>$1</b>',\n )\n }\n\n return text\n}\n"]}
1
+ {"version":3,"file":"AutocompleteDropdown.js","sourceRoot":"","sources":["../../../src/components/renderer/AutocompleteDropdown.tsx"],"names":[],"mappings":";AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAA;AACvB,OAAO,EAAE,MAAM,EAAE,MAAM,YAAY,CAAA;AAEnC,OAAO,e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,OAAO,EAAE,iBAAiB,GAAI,CAC7D,IACF,CACJ,CAAA;AACH,CAAC;AAED,eAAe,KAAK,CAAC,IAAI,CAAC,oBAAoB,CAAgC,CAAA;AAE9E,SAAS,cAAc,CAAC,IAAY,EAAE,MAAc;IAClD,IAAI,MAAM,EAAE,CAAC;QACX,IAAI,GAAG,IAAI,CAAC,OAAO;QACjB,8GAA8G;QAC9G,IAAI,MAAM,CACR,GAAG;YACD,MAAM,CAAC,OAAO,CACZ,yCAAyC,EACzC,CAAC,IAAY,EAAE,EAAE,CAAC,KAAK,IAAI,EAAE,CAC9B;YACD,GAAG,EACL,IAAI,CACL,EACD,WAAW,CACZ,CAAA;IACH,CAAC;IAED,OAAO,IAAI,CAAA;AACb,CAAC","sourcesContent":["import * as React from 'react'\nimport clsx from 'clsx'\nimport { Sentry } from '../../apps'\n\nimport useBooleanState from '../../hooks/useBooleanState'\nimport { IsDirtyProps } from '../../types/form'\nimport { LookupNotificationContext } from '../../hooks/useLookupNotification'\nimport MaterialIcon from '../MaterialIcon'\nimport FormElementValidationMessage from './FormElementValidationMessage'\n\ntype AutocompleteOption<T> = {\n label: string\n value: string\n data?: T\n}\n\ntype Props<T> = {\n id: string\n label: string\n value: unknown | undefined\n placeholder: string | undefined\n required: boolean | undefined\n disabled: boolean | undefined\n isLoading?: boolean\n hasError?: boolean\n validationMessage: string | undefined\n displayValidationMessage: boolean\n searchDebounceMs: number\n searchMinCharacters: number\n onChangeValue: (\n newValue: string | undefined,\n data?: T,\n ) => Promise<void> | void\n onChangeLabel: (newLabel: string) => void\n onSearch: (\n label: string,\n abortSignal: AbortSignal,\n ) => Promise<AutocompleteOption<T>[]>\n 'aria-describedby'?: string\n branding?: React.ReactNode\n autoComplete?: string\n hideEndAdornment?: boolean\n} & IsDirtyProps\n\nfunction AutocompleteDropdown<T>({\n id,\n label,\n value,\n placeholder,\n required,\n disabled,\n validationMessage,\n displayValidationMessage,\n searchDebounceMs,\n searchMinCharacters,\n isLoading,\n hasError,\n onChangeValue,\n onChangeLabel,\n onSearch,\n isDirty,\n setIsDirty,\n branding,\n autoComplete,\n hideEndAdornment,\n ...props\n}: Props<T>) {\n const optionsContainerElement = React.useRef<HTMLDivElement>(null)\n const [currentFocusedOptionIndex, setCurrentFocusedOptionIndex] =\n React.useState(0)\n const [options, setOptions] = React.useState<AutocompleteOption<T>[]>([])\n const [error, setError] = React.useState<Error | null>(null)\n const [isFetchingOptions, setIsFetchingOptions] = React.useState(false)\n const [isOpen, onOpen, onClose] = useBooleanState(false)\n\n const onSelectOption = React.useCallback(\n (option: AutocompleteOption<T>) => {\n onChangeLabel(option.label)\n onChangeValue(option.value, option.data)\n onClose()\n },\n [onChangeLabel, onChangeValue, onClose],\n )\n\n const handleClickOption = React.useCallback(\n (\n event: React.MouseEvent<HTMLAnchorElement, MouseEvent>,\n option: AutocompleteOption<T>,\n ) => {\n console.log('Selected element option in autocomplete', option)\n\n event.preventDefault()\n event.stopPropagation()\n\n onSelectOption(option)\n },\n [onSelectOption],\n )\n\n const onFocus = React.useCallback(() => {\n setCurrentFocusedOptionIndex(0)\n onOpen()\n }, [onOpen])\n\n // When moving away from the input, if this is no value remove\n // the label to show the user they have not selected a value\n const handleBlur = React.useCallback(\n (inputOption: { label: string; value: unknown | undefined }) => {\n setIsDirty()\n setError(null)\n onClose()\n\n if (Array.isArray(options)) {\n // If there is a label that resembles an option, set that option to be the new value.\n // UNLESS it was the previously selected label. Else, clear the label and the value.\n if (inputOption.label) {\n const lowerCase = inputOption.label.toLowerCase()\n const option = options.find(\n (option) => option.label.toLowerCase() === lowerCase,\n )\n if (option) {\n // If the new option is not equal to the option that is currently selected,\n // we want to update to the new option to ensure that it gets changed.\n if (inputOption.value !== option.value) {\n console.log('Setting value after blurring away from autocomplete')\n onSelectOption(option)\n }\n return\n }\n }\n\n console.log('Removing label after blurring away from autocomplete')\n onChangeValue(undefined)\n onChangeLabel('')\n }\n },\n [\n onChangeLabel,\n onChangeValue,\n onClose,\n onSelectOption,\n options,\n setIsDirty,\n ],\n )\n\n const onKeyDown = React.useCallback<\n React.KeyboardEventHandler<HTMLInputElement>\n >(\n (event) => {\n if (!options) {\n return\n }\n const enterPressed = event.keyCode === 13\n const upArrowPressed = event.keyCode === 38\n const downArrowPressed = event.keyCode === 40\n if (!upArrowPressed && !downArrowPressed && !enterPressed) {\n return\n }\n\n event.preventDefault()\n\n const previousFocusedOptionIndex = currentFocusedOptionIndex\n let nextFocusedOptionIndex = currentFocusedOptionIndex\n if (upArrowPressed) {\n nextFocusedOptionIndex = Math.max(0, currentFocusedOptionIndex - 1)\n } else if (downArrowPressed) {\n nextFocusedOptionIndex = Math.min(\n options.length - 1,\n currentFocusedOptionIndex + 1,\n )\n } else if (enterPressed) {\n const option = options[nextFocusedOptionIndex]\n if (option) {\n onSelectOption(option)\n }\n }\n\n // If the index has changed, need to ensure the active option is visible\n if (\n previousFocusedOptionIndex !== nextFocusedOptionIndex &&\n optionsContainerElement.current\n ) {\n const activeStepElement = optionsContainerElement.current.querySelector(\n `.ob-autocomplete__drop-down-item-${nextFocusedOptionIndex}`,\n )\n if (activeStepElement) {\n activeStepElement.scrollIntoView({\n behavior: 'smooth',\n block: 'nearest',\n inline: 'start',\n })\n }\n setCurrentFocusedOptionIndex(nextFocusedOptionIndex)\n }\n },\n [currentFocusedOptionIndex, options, onSelectOption],\n )\n\n const handleChangeLabel = React.useCallback<\n React.ChangeEventHandler<HTMLInputElement>\n >(\n (e) => {\n const newLabel = e.target.value\n onOpen()\n setCurrentFocusedOptionIndex(0)\n\n onChangeLabel(newLabel)\n },\n [onChangeLabel, onOpen],\n )\n\n React.useEffect(() => {\n setError(null)\n\n if (!isOpen || label.length < searchMinCharacters) {\n setIsFetchingOptions(false)\n return\n }\n\n setIsFetchingOptions(true)\n\n let ignore = false\n const abortController = new AbortController()\n\n const timeoutId = setTimeout(async () => {\n let newOptions: AutocompleteOption<T>[] = []\n let newError = null\n\n try {\n newOptions = await onSearch(label, abortController.signal)\n } catch (error) {\n // Cancelling will throw an error.\n if (!abortController.signal.aborted) {\n console.warn('Error while fetching autocomplete options', error)\n Sentry.captureException(error)\n newError = error as Error\n }\n }\n if (!ignore) {\n setError(newError)\n setOptions(newOptions)\n setIsFetchingOptions(false)\n }\n }, searchDebounceMs)\n\n return () => {\n ignore = true\n clearTimeout(timeoutId)\n abortController.abort()\n }\n }, [isOpen, label, onSearch, searchDebounceMs, searchMinCharacters])\n\n React.useEffect(() => {\n //If there is no value set, we want to clear the label\n //This is to satisfy lookups that return undefined.\n if (!value) {\n onChangeLabel('')\n }\n }, [onChangeLabel, value])\n const { isLookingUp } = React.useContext(LookupNotificationContext)\n\n const isShowingLoading = isFetchingOptions || !!isLoading\n const isShowingValid = !isShowingLoading && value !== undefined\n const isShowingError = !isShowingLoading && !isLookingUp && !!hasError\n\n return (\n <>\n <div\n className={clsx('dropdown', {\n 'is-active': isOpen && Array.isArray(options),\n })}\n >\n <div className=\"field\">\n <div\n className={clsx(\n 'cypress-autocomplete-field-control control is-expanded',\n {\n 'is-loading': isShowingLoading,\n 'has-icons-right': isShowingValid || isShowingError,\n },\n )}\n >\n <input\n type=\"text\"\n placeholder={placeholder}\n id={id}\n autoComplete={autoComplete ?? 'off'}\n className=\"cypress-autocomplete-control input ob-input\"\n required={required}\n value={label}\n disabled={disabled}\n onFocus={onFocus}\n onBlur={() => handleBlur({ label, value })}\n onKeyDown={onKeyDown}\n onChange={handleChangeLabel}\n aria-describedby={props['aria-describedby']}\n aria-required={required}\n />\n {!hideEndAdornment && (\n <>\n {isShowingValid && (\n <span className=\" ob-input-icon icon is-small is-right\">\n <MaterialIcon className=\"is-size-5 has-text-success\">\n check\n </MaterialIcon>\n </span>\n )}\n {isShowingError && (\n <span className=\" ob-input-icon icon is-small is-right\">\n <MaterialIcon className=\"is-size-5 has-text-danger\">\n error\n </MaterialIcon>\n </span>\n )}\n </>\n )}\n </div>\n </div>\n\n <div className=\"dropdown-menu\">\n <div\n ref={optionsContainerElement}\n className=\"ob-autocomplete__dropdown-content dropdown-content cypress-autocomplete-dropdown-content\"\n >\n {error ? (\n <a className=\"dropdown-item cypress-autocomplete-error ob-autocomplete__drop-down-item-error\">\n <span className=\"has-text-danger\">{error.message}</span>\n </a>\n ) : label.length < searchMinCharacters ? (\n <a className=\"dropdown-item cypress-max-characters ob-autocomplete__drop-down-item-max-characters\">\n <i>\n Enter at least {searchMinCharacters} character(s) to search\n </i>\n </a>\n ) : isShowingLoading ? (\n <a className=\"dropdown-item cypress-searching-options ob-autocomplete__drop-down-item-searching\">\n <i>Searching...</i>\n </a>\n ) : options && options.length ? (\n options.map((option, index) => (\n <a\n key={option.value}\n className={clsx(\n `dropdown-item cypress-autocomplete-dropdown-item ob-autocomplete__drop-down-item-${index}`,\n {\n 'is-active': currentFocusedOptionIndex === index,\n },\n )}\n onMouseDown={(e) => handleClickOption(e, option)}\n // eslint-disable-next-line react/no-danger\n dangerouslySetInnerHTML={{\n __html: highlightLabel(option.label, label),\n }}\n />\n ))\n ) : (\n <a className=\"dropdown-item cypress-no-matches-found ob-autocomplete__drop-down-item-no-matches\">\n <i>No matches found</i>\n </a>\n )}\n {branding}\n </div>\n </div>\n </div>\n\n {(isDirty || displayValidationMessage) &&\n !!validationMessage &&\n !isShowingLoading && (\n <FormElementValidationMessage message={validationMessage} />\n )}\n </>\n )\n}\n\nexport default React.memo(AutocompleteDropdown) as typeof AutocompleteDropdown\n\nfunction highlightLabel(text: string, phrase: string) {\n if (phrase) {\n text = text.replace(\n // eslint-disable-next-line security/detect-non-literal-regexp -- special characters in the phrase are escaped\n new RegExp(\n '(' +\n phrase.replace(\n /[`~!@#$%^&*()_|+\\-=?;:'\",.<>{}[\\]\\\\/]/gi,\n (char: string) => `\\\\${char}`,\n ) +\n ')',\n 'gi',\n ),\n '<b>$1</b>',\n )\n }\n\n return text\n}\n"]}
@@ -66,6 +66,7 @@ function FormElementRepeatableSet({ formId, element, readOnly, childrenReadOnly,
66
66
  },
67
67
  sectionState: (currentSectionState) => {
68
68
  return ((currentSectionState === null || currentSectionState === void 0 ? void 0 : currentSectionState.map((section) => {
69
+ // eslint-disable-next-line security/detect-non-literal-regexp -- element name comes from the form definition
69
70
  const idPrefixPattern = new RegExp(`(.+)?${element.name}_entry-(.+)_(.+)`);
70
71
  const entryIdPrefixMatches = section.id.match(idPrefixPattern);
71
72
  if (entryIdPrefixMatches) {
@@ -104,6 +105,7 @@ function FormElementRepeatableSet({ formId, element, readOnly, childrenReadOnly,
104
105
  },
105
106
  sectionState: (currentSectionState) => {
106
107
  return ((currentSectionState === null || currentSectionState === void 0 ? void 0 : currentSectionState.reduce((state, section) => {
108
+ // eslint-disable-next-line security/detect-non-literal-regexp -- element name comes from the form definition
107
109
  const idPrefixPattern = new RegExp(`(.+)?${element.name}_entry-(\\d+)`);
108
110
  const entryIdPrefixMatches = entryIdPrefix.match(idPrefixPattern);
109
111
  if (!section.id.startsWith(entryIdPrefix) &&
@@ -113,6 +115,7 @@ function FormElementRepeatableSet({ formId, element, readOnly, childrenReadOnly,
113
115
  if (section.id.startsWith(parentElementPath)) {
114
116
  // Match pattern: {elementName}_entry-{index}_
115
117
  // also yields a prefix and suffix for any match found
118
+ // eslint-disable-next-line security/detect-non-literal-regexp -- element name comes from the form definition
116
119
  const idPrefixWithFullIdPattern = new RegExp(`(.+)?${element.name}_entry-(\\d+)_(.+)`);
117
120
  const match = section.id.match(idPrefixWithFullIdPattern);
118
121
  if (match) {
@@ -1 +1 @@
1
- {"version":3,"file":"FormElementRepeatableSet.js","sourceRoot":"","sources":["../../src/form-elements/FormElementRepeatableSet.tsx"],"names":[],"mappings":";AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAA;AAEvB,OAAO,eAAe,MAAM,0BAA0B,CAAA;AACtD,OAAO,mBAAmB,EAAE,EAC1B,sBAAsB,EACtB,6BAA6B,GAC9B,MAAM,mCAAmC,CAAA;AAC1C,OAAO,oBAAoB,MAAM,6CAA6C,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EAAC,MAAM,YACpB,KAAC,YAAY,iCAA8B,GACtC,EACN,CAAC,CAAC,OAAO,CAAC,mBAAmB,IAAI,CAChC,yBAAO,OAAO,CAAC,mBAAmB,GAAQ,CAC3C,IACM,CACV,CAAA;AACH,CAAC","sourcesContent":["import * as React from 'react'\nimport clsx from 'clsx'\nimport { FormTypes, SubmissionTypes } from '@oneblink/types'\nimport useBooleanState from '../hooks/useBooleanState'\nimport generateDefaultData, {\n ENTRY_ID_PROPERTY_NAME,\n generateNewRepeatableSetEntry,\n} from '../services/generate-default-data'\nimport OneBlinkFormElements from '../components/renderer/OneBlinkFormElements'\nimport Modal from '../components/renderer/Modal'\nimport FormElementLabelContainer from '../components/renderer/FormElementLabelContainer'\nimport useValidationClass from '../hooks/useValidationClass'\nimport {\n ExecutedLookups,\n FormElementConditionallyShown,\n FormElementLookupHandler,\n FormElementsConditionallyShown,\n FormElementsValidation,\n FormElementValidation,\n NestedFormElementValueChangeHandler,\n IsDirtyProps,\n UpdateFormElementsHandler,\n SectionState,\n} from '../types/form'\nimport useFormElementRepeatableSetEntries from '../hooks/useFormElementRepeatableSetEntries'\nimport useElementAriaDescribedby from '../hooks/useElementAriaDescribedby'\nimport MaterialIcon from '../components/MaterialIcon'\nimport ElementDOMId from '../utils/elementDOMIds'\nimport { Collapse } from '@mui/material'\nimport FormElementValidationMessage from '../components/renderer/FormElementValidationMessage'\n\ntype Props = {\n formId: number\n id: string\n isEven: boolean\n element: FormTypes.RepeatableSetElement\n /**\n * Whether this set’s own controls (add/remove entries) are locked. The set\n * itself must be listed in `editableFormElementIds` to add or remove entries;\n * a nested field being listed is not enough.\n */\n readOnly: boolean\n /**\n * Lock to apply to fields inside each entry. True when the whole form is\n * read-only, a parent is read-only, or this element’s definition has\n * `readOnly: true`.\n */\n childrenReadOnly: boolean\n value: Array<SubmissionTypes.S3SubmissionData['submission']> | undefined\n onChange: NestedFormElementValueChangeHandler<\n SubmissionTypes.S3SubmissionData['submission'][]\n >\n onLookup: FormElementLookupHandler\n formElementConditionallyShown: FormElementConditionallyShown | undefined\n formElementValidation: FormElementValidation | undefined\n displayValidationMessage: boolean\n onUpdateFormElements: UpdateFormElementsHandler\n sectionState: SectionState\n} & IsDirtyProps\n\nconst RepeatableSetIndexContext = React.createContext<number>(0)\n\nfunction RepeatableSetEntryProvider({\n index,\n isAnimated,\n element,\n idPrefix,\n onRemove,\n children,\n}: {\n isAnimated: boolean\n index: number\n element: FormTypes.RepeatableSetElement\n idPrefix?: string\n onRemove: (\n index: number,\n element: FormTypes.RepeatableSetElement,\n idPrefix?: string,\n ) => void\n children: (renderProps: { onRemove: () => void }) => React.ReactNode\n}) {\n const [isExpanded, setIsExpanded] = React.useState(true)\n\n const handleRemove = React.useCallback(() => {\n if (isAnimated) {\n setIsExpanded(false)\n } else {\n onRemove(index, element, idPrefix)\n }\n }, [index, isAnimated, onRemove, element, idPrefix])\n\n const node = (\n <RepeatableSetIndexContext.Provider value={index}>\n {children({\n onRemove: handleRemove,\n })}\n </RepeatableSetIndexContext.Provider>\n )\n\n if (!isAnimated) {\n return node\n }\n\n return (\n <Collapse\n in={isExpanded}\n appear\n onExited={() => {\n onRemove(index, element, idPrefix)\n }}\n classes={{\n root: 'ob-repeatable-set__collapsible',\n wrapper: 'ob-repeatable-set__collapsible-wrapper',\n wrapperInner: 'ob-repeatable-set__collapsible-wrapper-inner',\n }}\n >\n {node}\n </Collapse>\n )\n}\n\nexport function useRepeatableSetIndexText(text: string) {\n const index = React.useContext(RepeatableSetIndexContext)\n return React.useMemo(\n () => text.replace('{INDEX}', (index + 1).toString()),\n [index, text],\n )\n}\n\nfunction FormElementRepeatableSet({\n formId,\n element,\n readOnly,\n childrenReadOnly,\n value,\n formElementValidation,\n id,\n isEven,\n displayValidationMessage,\n formElementConditionallyShown,\n onChange,\n onLookup,\n onUpdateFormElements,\n isDirty,\n setIsDirty,\n sectionState,\n}: Props) {\n const entries = React.useMemo(\n () => (Array.isArray(value) ? value : []),\n [value],\n )\n\n const handleAddEntry = React.useCallback(\n (index: number) => {\n onChange(element, {\n value: (existingEntries) => {\n const newEntries = [...(existingEntries || [])]\n const entry = generateDefaultData(\n element.elements,\n generateNewRepeatableSetEntry(),\n )\n\n newEntries.splice(index, 0, entry)\n return newEntries\n },\n executedLookups: (existingExecutedLookups) => {\n if (\n existingExecutedLookups !== undefined &&\n !Array.isArray(existingExecutedLookups)\n ) {\n return []\n }\n\n const newExistingExecutedLookups = [\n ...((existingExecutedLookups as ExecutedLookups[]) ??\n Array.from(Array(entries.length))),\n ]\n newExistingExecutedLookups.push({})\n return newExistingExecutedLookups\n },\n sectionState: (currentSectionState) => {\n return (\n currentSectionState?.map((section) => {\n const idPrefixPattern = new RegExp(\n `(.+)?${element.name}_entry-(.+)_(.+)`,\n )\n const entryIdPrefixMatches = section.id.match(idPrefixPattern)\n\n if (entryIdPrefixMatches) {\n const startOfId = entryIdPrefixMatches[1]\n const entryIndex = parseInt(entryIdPrefixMatches[2])\n const restOfId = entryIdPrefixMatches[3]\n\n if (entryIndex >= index) {\n const newEntryIndex = entryIndex + 1\n return {\n ...section,\n id: `${startOfId ? startOfId : ''}${element.name}_entry-${newEntryIndex}_${restOfId}`,\n }\n }\n }\n\n return section\n }, []) || []\n )\n },\n })\n setIsDirty()\n },\n [element, onChange, setIsDirty, entries.length],\n )\n\n const handleRemoveEntry = React.useCallback(\n (\n index: number,\n element: FormTypes.RepeatableSetElement,\n idPrefix?: string,\n ) => {\n const entryIdPrefix = idPrefix || ''\n\n onChange(element, {\n value: (existingEntries) => {\n const newEntries = [...(existingEntries || [])]\n newEntries.splice(index, 1)\n return newEntries\n },\n executedLookups: (existingExecutedLookups) => {\n if (!Array.isArray(existingExecutedLookups)) {\n return []\n }\n const newExistingExecutedLookups = [...existingExecutedLookups]\n\n newExistingExecutedLookups.splice(index, 1)\n return newExistingExecutedLookups\n },\n sectionState: (currentSectionState) => {\n return (\n currentSectionState?.reduce(\n (\n state: {\n id: string\n state: 'COLLAPSED' | 'EXPANDED'\n }[],\n section,\n ) => {\n const idPrefixPattern = new RegExp(\n `(.+)?${element.name}_entry-(\\\\d+)`,\n )\n const entryIdPrefixMatches =\n entryIdPrefix.match(idPrefixPattern)\n if (\n !section.id.startsWith(entryIdPrefix) &&\n entryIdPrefixMatches\n ) {\n const parentElementPath =\n entryIdPrefixMatches[1] || `${element.name}_entry`\n // only update nested sections where the parent path matches the entry that was removed\n if (section.id.startsWith(parentElementPath)) {\n // Match pattern: {elementName}_entry-{index}_\n // also yields a prefix and suffix for any match found\n const idPrefixWithFullIdPattern = new RegExp(\n `(.+)?${element.name}_entry-(\\\\d+)_(.+)`,\n )\n const match = section.id.match(idPrefixWithFullIdPattern)\n\n if (match) {\n const oldEntryIndex = parseInt(match[2], 10)\n if (oldEntryIndex > index) {\n const prefix = match[1]\n const restOfId = match[3]\n const newEntryIndex = oldEntryIndex - 1\n state.push({\n ...section,\n id: `${prefix ? prefix : ''}${element.name}_entry-${newEntryIndex}_${restOfId}`,\n })\n return state\n }\n }\n }\n\n state.push(section)\n }\n\n return state\n },\n [],\n ) || []\n )\n },\n })\n setIsDirty()\n },\n [onChange, setIsDirty],\n )\n\n const handleNestedChange = React.useCallback(\n (\n index: number,\n nestedElement: FormTypes.FormElement,\n {\n value,\n executedLookups,\n sectionState,\n isDerivedChange,\n }: Parameters<NestedFormElementValueChangeHandler>[1],\n idPrefix?: string,\n ) => {\n if (nestedElement.type === 'section') {\n // trigger onChange to update sectionState\n onChange(\n {\n ...nestedElement,\n id: idPrefix ? `${idPrefix}${nestedElement.id}` : nestedElement.id,\n },\n { executedLookups: undefined, sectionState },\n )\n }\n if (!('name' in nestedElement)) {\n return\n }\n onChange(element, {\n value: (existingEntries) => {\n const newEntries = (existingEntries || []).map((entry, i) => {\n if (i === index) {\n return {\n ...entry,\n [nestedElement.name]:\n typeof value === 'function'\n ? value(entry[nestedElement.name])\n : value,\n }\n } else {\n return entry\n }\n })\n return newEntries\n },\n executedLookups: (existingExecutedLookups) => {\n const elementExecutedLookups = existingExecutedLookups ?? []\n if (!Array.isArray(elementExecutedLookups)) {\n return elementExecutedLookups\n }\n const newExecutedLookups = elementExecutedLookups.map(\n (executedLookup, i) => {\n if (i === index) {\n const updatedExecutedLookups =\n typeof executedLookups === 'function'\n ? executedLookups(executedLookup?.[nestedElement.name])\n : executedLookups\n return {\n ...executedLookup,\n [nestedElement.name]: updatedExecutedLookups,\n }\n }\n return executedLookup\n },\n )\n return newExecutedLookups\n },\n sectionState,\n isDerivedChange,\n })\n },\n [element, onChange],\n )\n\n const { minSetEntries, maxSetEntries } =\n useFormElementRepeatableSetEntries(element)\n\n const repeatableSetValidation = React.useMemo(\n () =>\n !formElementValidation ||\n typeof formElementValidation === 'string' ||\n formElementValidation.type !== 'repeatableSet'\n ? undefined\n : formElementValidation,\n [formElementValidation],\n )\n\n const repeatableSetEntriesConditionallyShown =\n formElementConditionallyShown &&\n formElementConditionallyShown.type === 'repeatableSet'\n ? formElementConditionallyShown.entries\n : {}\n\n const { validationClassName } = useValidationClass({\n formElementsValid: !repeatableSetValidation,\n displayInvalidClassName: isDirty || displayValidationMessage,\n validClassName: 'ob-repeatable-set-element__valid',\n invalidClassName: 'ob-repeatable-set-element__invalid',\n })\n\n const ariaDescribedby = useElementAriaDescribedby(id, element)\n\n const showAddButton = React.useMemo(\n () => maxSetEntries === undefined || entries.length < maxSetEntries,\n [maxSetEntries, entries.length],\n )\n\n const repeatableSetContainerClass = React.useMemo(() => {\n const prefix = 'ob-repeatable-set-container-layout__'\n switch (element.layout) {\n case 'MULTIPLE_ADD_BUTTONS':\n return prefix + 'multiple-add-buttons'\n default:\n return 'single-add-button'\n }\n }, [element.layout])\n\n return (\n <div\n className={clsx('cypress-repeatable-set-element', validationClassName)}\n aria-labelledby={`${id}-label`}\n aria-describedby={ariaDescribedby}\n role=\"region\"\n >\n {/* */}\n <FormElementLabelContainer\n className={clsx(\n 'ob-repeatable-set',\n isEven ? 'even' : 'odd',\n repeatableSetContainerClass,\n )}\n element={element}\n id={id}\n required={!!minSetEntries && minSetEntries > 0}\n associateLabelWithInput={false}\n >\n {element.layout === 'MULTIPLE_ADD_BUTTONS' && showAddButton && (\n <AddButton\n onAdd={() => handleAddEntry(0)}\n element={element}\n readOnly={readOnly}\n classes={['ob-button-repeatable-set-layout__multiple-add-buttons']}\n id={id}\n />\n )}\n {entries.map((entry, index) => {\n return (\n <RepeatableSetEntry\n key={entry[ENTRY_ID_PROPERTY_NAME] as string}\n formId={formId}\n index={index}\n id={id}\n isEven={isEven}\n entry={entry}\n element={element}\n readOnly={readOnly}\n childrenReadOnly={childrenReadOnly}\n showAddButton={\n element.layout === 'MULTIPLE_ADD_BUTTONS' && showAddButton\n }\n onChange={handleNestedChange}\n onLookup={onLookup}\n onAdd={handleAddEntry}\n onRemove={handleRemoveEntry}\n formElementsConditionallyShown={\n repeatableSetEntriesConditionallyShown[index.toString()]\n }\n formElementsValidation={\n repeatableSetValidation &&\n repeatableSetValidation.entries[index.toString()]\n }\n displayValidationMessages={displayValidationMessage}\n onUpdateFormElements={onUpdateFormElements}\n sectionState={sectionState}\n />\n )\n })}\n {(!element.layout || element.layout === 'SINGLE_ADD_BUTTON') &&\n showAddButton && (\n <AddButton\n onAdd={() => handleAddEntry(entries.length)}\n element={element}\n readOnly={readOnly}\n id={id}\n />\n )}\n {(isDirty || displayValidationMessage) &&\n !!repeatableSetValidation &&\n !!repeatableSetValidation.set && (\n <FormElementValidationMessage\n message={repeatableSetValidation.set}\n />\n )}\n </FormElementLabelContainer>\n </div>\n )\n}\n\nexport default React.memo(FormElementRepeatableSet)\n\ntype RepeatableSetEntryProps = {\n formId: number\n id: string\n index: number\n isEven: boolean\n entry: SubmissionTypes.S3SubmissionData['submission']\n element: FormTypes.RepeatableSetElement\n /**\n * Whether this entry’s add/remove controls are locked. See\n * `FormElementRepeatableSet` `readOnly`.\n */\n readOnly: boolean\n /**\n * Lock to apply to fields in this entry. See `FormElementRepeatableSet`\n * `childrenReadOnly`.\n */\n childrenReadOnly: boolean\n formElementsConditionallyShown: FormElementsConditionallyShown | undefined\n formElementsValidation: FormElementsValidation | undefined\n displayValidationMessages: boolean\n showAddButton: boolean\n onChange: (\n index: number,\n formElement: FormTypes.FormElement,\n {\n value,\n executedLookups,\n }: Parameters<NestedFormElementValueChangeHandler>[1],\n idPrefix?: string,\n ) => void\n onLookup: FormElementLookupHandler\n onAdd: (index: number) => unknown\n onRemove: (\n index: number,\n element: FormTypes.RepeatableSetElement,\n idPrefix?: string,\n ) => unknown\n onUpdateFormElements: UpdateFormElementsHandler\n sectionState: SectionState\n}\n\nconst RepeatableSetEntry = React.memo<RepeatableSetEntryProps>(\n function RepeatableSetEntry({\n formId,\n id,\n index,\n isEven,\n entry,\n element,\n readOnly,\n childrenReadOnly,\n formElementsConditionallyShown,\n displayValidationMessages,\n formElementsValidation,\n onChange,\n onLookup,\n onAdd,\n onRemove,\n onUpdateFormElements,\n showAddButton,\n sectionState,\n }: RepeatableSetEntryProps) {\n const [isConfirmingRemove, confirmRemove, cancelRemove] =\n useBooleanState(false)\n const elementDOMId = React.useMemo(() => new ElementDOMId(id), [id])\n\n const handleChange: NestedFormElementValueChangeHandler = React.useCallback(\n (\n nestedElement,\n { value, executedLookups, sectionState, isDerivedChange },\n idPrefix,\n ) => {\n onChange(\n index,\n nestedElement,\n {\n value,\n executedLookups,\n sectionState,\n isDerivedChange,\n },\n idPrefix,\n )\n },\n [index, onChange],\n )\n\n const handleLookup = React.useCallback<FormElementLookupHandler>(\n (mergeLookupResults, options) => {\n onLookup((currentFormSubmission) => {\n let newEntry = {}\n const entries = currentFormSubmission.submission[\n element.name\n ] as Array<SubmissionTypes.S3SubmissionData['submission']>\n const existingExecutedLookups = (currentFormSubmission\n .executedLookups?.[element.name] ??\n Array.from(Array(entries.length))) as ExecutedLookups[]\n const repeatableSetExecutedLookups = Array.isArray(\n existingExecutedLookups,\n )\n ? [...existingExecutedLookups]\n : existingExecutedLookups\n // if the repeatable set is prefilled or has minimum entries then executed lookups exists,\n // but is an empty array\n if (\n Array.isArray(repeatableSetExecutedLookups) &&\n !repeatableSetExecutedLookups[index]\n ) {\n repeatableSetExecutedLookups[index] = {}\n }\n let newExecutedLookups: ExecutedLookups = {}\n const elements = currentFormSubmission.elements.map((formElement) => {\n if (\n formElement.type === 'repeatableSet' &&\n formElement.name === element.name\n ) {\n const { elements, submission, executedLookups } =\n mergeLookupResults({\n elements: formElement.elements,\n submission: entries[index],\n lastElementUpdated: currentFormSubmission.lastElementUpdated,\n executedLookups: repeatableSetExecutedLookups[index] ?? {},\n sectionState: currentFormSubmission.sectionState,\n })\n newEntry = submission\n newExecutedLookups = executedLookups as ExecutedLookups\n return {\n ...formElement,\n elements,\n }\n }\n return formElement\n })\n\n const submission = {\n ...currentFormSubmission.submission,\n [element.name]: entries.map((entry, i) => {\n if (i === index) {\n return newEntry\n }\n return entry\n }),\n }\n\n let updatedExecutedLookups = currentFormSubmission.executedLookups\n if (Array.isArray(repeatableSetExecutedLookups)) {\n updatedExecutedLookups = {\n ...currentFormSubmission.executedLookups,\n [element.name]: repeatableSetExecutedLookups.map((entry, i) => {\n if (i == index) {\n return newExecutedLookups\n }\n return entry\n }),\n }\n }\n\n return {\n elements,\n submission,\n executedLookups: updatedExecutedLookups,\n }\n }, options)\n },\n [element.name, index, onLookup],\n )\n\n const { validationClassName } = useValidationClass({\n formElementsValid: !formElementsValidation,\n displayInvalidClassName: displayValidationMessages,\n validClassName: 'ob-repeatable-set__valid',\n invalidClassName: 'ob-repeatable-set__invalid',\n })\n\n const handleUpdateNestedFormElements =\n React.useCallback<UpdateFormElementsHandler>(\n (setter) => {\n onUpdateFormElements((formElements) => {\n return formElements.map((formElement) => {\n if (\n formElement.id === element.id &&\n formElement.type === 'repeatableSet'\n ) {\n return {\n ...formElement,\n elements: setter(formElement.elements),\n }\n }\n return formElement\n })\n })\n },\n [element.id, onUpdateFormElements],\n )\n\n const idPrefix = elementDOMId.repeatableSetEntryDOMIdPrefix(\n index.toString(),\n )\n\n return (\n <RepeatableSetEntryProvider\n index={index}\n element={element}\n idPrefix={idPrefix}\n onRemove={onRemove}\n isAnimated={element.layout === 'MULTIPLE_ADD_BUTTONS'}\n >\n {({ onRemove }) => (\n <>\n <Modal\n isOpen={isConfirmingRemove}\n className=\"cypress-repeatable-set-prompt\"\n titleClassName=\"cypress-repeatable-set-remove-entry-header\"\n title={element.removeSetEntryLabel || 'Remove Entry'}\n actions={\n <>\n <button\n type=\"button\"\n className=\"button ob-button is-light cypress-cancel-repeatable-set\"\n onClick={cancelRemove}\n >\n Cancel\n </button>\n <button\n type=\"button\"\n className=\"button ob-button is-primary cypress-confirm-repeatable-set\"\n onClick={() => {\n cancelRemove()\n onRemove()\n }}\n autoFocus\n >\n Yes\n </button>\n </>\n }\n >\n Are you sure you want to remove this entry?\n </Modal>\n\n <div\n className={clsx(\n 'ob-repeatable-set__container cypress-repeatable-set-container',\n validationClassName,\n )}\n >\n {(!element.layout || element.layout === 'SINGLE_ADD_BUTTON') && (\n <RemoveButton\n onConfirmRemove={confirmRemove}\n element={element}\n readOnly={readOnly}\n className=\"ob-repeatable-set__button-remove-top\"\n index={index}\n />\n )}\n\n <OneBlinkFormElements\n formId={formId}\n idPrefix={idPrefix}\n isEven={isEven}\n formElementsValidation={formElementsValidation}\n displayValidationMessages={displayValidationMessages}\n elements={element.elements}\n onChange={handleChange}\n onLookup={handleLookup}\n model={entry}\n parentElement={element}\n readOnly={childrenReadOnly}\n formElementsConditionallyShown={formElementsConditionallyShown}\n onUpdateFormElements={handleUpdateNestedFormElements}\n sectionState={sectionState}\n />\n {element.layout === 'MULTIPLE_ADD_BUTTONS' && (\n <RemoveButton\n onConfirmRemove={confirmRemove}\n element={element}\n readOnly={readOnly}\n index={index}\n className=\"ob-repeatable-set__button-remove-bottom\"\n />\n )}\n </div>\n {showAddButton && (\n <AddButton\n onAdd={() => onAdd(index + 1)}\n element={element}\n readOnly={readOnly}\n classes={[\n 'ob-button-repeatable-set-layout__multiple-add-buttons',\n ]}\n />\n )}\n </>\n )}\n </RepeatableSetEntryProvider>\n )\n },\n)\n\nfunction AddButton({\n id,\n onAdd,\n element,\n readOnly,\n classes,\n}: {\n id?: string\n onAdd: () => void\n element: FormTypes.RepeatableSetElement\n readOnly: boolean\n isPrimary?: boolean\n classes?: string[]\n}) {\n return (\n <button\n type=\"button\"\n className={clsx(\n 'button ob-button ob-button__add cypress-add-repeatable-set is-primary',\n classes,\n )}\n onClick={onAdd}\n disabled={readOnly}\n aria-label={element.addSetEntryLabel ? undefined : 'Add Entry'}\n id={id}\n >\n <span className=\"icon\">\n <MaterialIcon>add</MaterialIcon>\n </span>\n {!!element.addSetEntryLabel && <span>{element.addSetEntryLabel}</span>}\n </button>\n )\n}\n\nfunction RemoveButton({\n onConfirmRemove,\n element,\n readOnly,\n className,\n index,\n}: {\n onConfirmRemove: () => void\n element: FormTypes.RepeatableSetElement\n readOnly: boolean\n className?: string\n index: number\n}) {\n return (\n <button\n type=\"button\"\n className={clsx(\n 'button ob-button ob-button_remove is-light cypress-remove-repeatable-set-entry',\n className,\n )}\n onClick={onConfirmRemove}\n disabled={readOnly}\n aria-label={`${element.removeSetEntryLabel ?? 'Remove Entry'} ${index + 1}`}\n >\n <span className=\"icon\">\n <MaterialIcon>delete_outline</MaterialIcon>\n </span>\n {!!element.removeSetEntryLabel && (\n <span>{element.removeSetEntryLabel}</span>\n )}\n </button>\n )\n}\n"]}
1
+ {"version":3,"file":"FormElementRepeatableSet.js","sourceRoot":"","sources":["../../src/form-elements/FormElementRepeatableSet.tsx"],"names":[],"mappings":";AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,IAAI,MAAM,MAAM,CAAA;AAEvB,OAAO,eAAe,MAAM,0BAA0B,CAAA;AACtD,OAAO,mBAAmB,EAAE,EAC1B,sBAAsB,EACtB,6BAA6B,GAC9B,MAAM,mCAAmC,CAAA;AAC1C,OAAO,oBAAoB,MAAM,6CAA6C,CAAA;AAC9E,OAAO,KAAK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,EAAE,aAE3E,eAAM,SAAS,EAAC,MAAM,YACpB,KAAC,YAAY,iCAA8B,GACtC,EACN,CAAC,CAAC,OAAO,CAAC,mBAAmB,IAAI,CAChC,yBAAO,OAAO,CAAC,mBAAmB,GAAQ,CAC3C,IACM,CACV,CAAA;AACH,CAAC","sourcesContent":["import * as React from 'react'\nimport clsx from 'clsx'\nimport { FormTypes, SubmissionTypes } from '@oneblink/types'\nimport useBooleanState from '../hooks/useBooleanState'\nimport generateDefaultData, {\n ENTRY_ID_PROPERTY_NAME,\n generateNewRepeatableSetEntry,\n} from '../services/generate-default-data'\nimport OneBlinkFormElements from '../components/renderer/OneBlinkFormElements'\nimport Modal from '../components/renderer/Modal'\nimport FormElementLabelContainer from '../components/renderer/FormElementLabelContainer'\nimport useValidationClass from '../hooks/useValidationClass'\nimport {\n ExecutedLookups,\n FormElementConditionallyShown,\n FormElementLookupHandler,\n FormElementsConditionallyShown,\n FormElementsValidation,\n FormElementValidation,\n NestedFormElementValueChangeHandler,\n IsDirtyProps,\n UpdateFormElementsHandler,\n SectionState,\n} from '../types/form'\nimport useFormElementRepeatableSetEntries from '../hooks/useFormElementRepeatableSetEntries'\nimport useElementAriaDescribedby from '../hooks/useElementAriaDescribedby'\nimport MaterialIcon from '../components/MaterialIcon'\nimport ElementDOMId from '../utils/elementDOMIds'\nimport { Collapse } from '@mui/material'\nimport FormElementValidationMessage from '../components/renderer/FormElementValidationMessage'\n\ntype Props = {\n formId: number\n id: string\n isEven: boolean\n element: FormTypes.RepeatableSetElement\n /**\n * Whether this set’s own controls (add/remove entries) are locked. The set\n * itself must be listed in `editableFormElementIds` to add or remove entries;\n * a nested field being listed is not enough.\n */\n readOnly: boolean\n /**\n * Lock to apply to fields inside each entry. True when the whole form is\n * read-only, a parent is read-only, or this element’s definition has\n * `readOnly: true`.\n */\n childrenReadOnly: boolean\n value: Array<SubmissionTypes.S3SubmissionData['submission']> | undefined\n onChange: NestedFormElementValueChangeHandler<\n SubmissionTypes.S3SubmissionData['submission'][]\n >\n onLookup: FormElementLookupHandler\n formElementConditionallyShown: FormElementConditionallyShown | undefined\n formElementValidation: FormElementValidation | undefined\n displayValidationMessage: boolean\n onUpdateFormElements: UpdateFormElementsHandler\n sectionState: SectionState\n} & IsDirtyProps\n\nconst RepeatableSetIndexContext = React.createContext<number>(0)\n\nfunction RepeatableSetEntryProvider({\n index,\n isAnimated,\n element,\n idPrefix,\n onRemove,\n children,\n}: {\n isAnimated: boolean\n index: number\n element: FormTypes.RepeatableSetElement\n idPrefix?: string\n onRemove: (\n index: number,\n element: FormTypes.RepeatableSetElement,\n idPrefix?: string,\n ) => void\n children: (renderProps: { onRemove: () => void }) => React.ReactNode\n}) {\n const [isExpanded, setIsExpanded] = React.useState(true)\n\n const handleRemove = React.useCallback(() => {\n if (isAnimated) {\n setIsExpanded(false)\n } else {\n onRemove(index, element, idPrefix)\n }\n }, [index, isAnimated, onRemove, element, idPrefix])\n\n const node = (\n <RepeatableSetIndexContext.Provider value={index}>\n {children({\n onRemove: handleRemove,\n })}\n </RepeatableSetIndexContext.Provider>\n )\n\n if (!isAnimated) {\n return node\n }\n\n return (\n <Collapse\n in={isExpanded}\n appear\n onExited={() => {\n onRemove(index, element, idPrefix)\n }}\n classes={{\n root: 'ob-repeatable-set__collapsible',\n wrapper: 'ob-repeatable-set__collapsible-wrapper',\n wrapperInner: 'ob-repeatable-set__collapsible-wrapper-inner',\n }}\n >\n {node}\n </Collapse>\n )\n}\n\nexport function useRepeatableSetIndexText(text: string) {\n const index = React.useContext(RepeatableSetIndexContext)\n return React.useMemo(\n () => text.replace('{INDEX}', (index + 1).toString()),\n [index, text],\n )\n}\n\nfunction FormElementRepeatableSet({\n formId,\n element,\n readOnly,\n childrenReadOnly,\n value,\n formElementValidation,\n id,\n isEven,\n displayValidationMessage,\n formElementConditionallyShown,\n onChange,\n onLookup,\n onUpdateFormElements,\n isDirty,\n setIsDirty,\n sectionState,\n}: Props) {\n const entries = React.useMemo(\n () => (Array.isArray(value) ? value : []),\n [value],\n )\n\n const handleAddEntry = React.useCallback(\n (index: number) => {\n onChange(element, {\n value: (existingEntries) => {\n const newEntries = [...(existingEntries || [])]\n const entry = generateDefaultData(\n element.elements,\n generateNewRepeatableSetEntry(),\n )\n\n newEntries.splice(index, 0, entry)\n return newEntries\n },\n executedLookups: (existingExecutedLookups) => {\n if (\n existingExecutedLookups !== undefined &&\n !Array.isArray(existingExecutedLookups)\n ) {\n return []\n }\n\n const newExistingExecutedLookups = [\n ...((existingExecutedLookups as ExecutedLookups[]) ??\n Array.from(Array(entries.length))),\n ]\n newExistingExecutedLookups.push({})\n return newExistingExecutedLookups\n },\n sectionState: (currentSectionState) => {\n return (\n currentSectionState?.map((section) => {\n // eslint-disable-next-line security/detect-non-literal-regexp -- element name comes from the form definition\n const idPrefixPattern = new RegExp(\n `(.+)?${element.name}_entry-(.+)_(.+)`,\n )\n const entryIdPrefixMatches = section.id.match(idPrefixPattern)\n\n if (entryIdPrefixMatches) {\n const startOfId = entryIdPrefixMatches[1]\n const entryIndex = parseInt(entryIdPrefixMatches[2])\n const restOfId = entryIdPrefixMatches[3]\n\n if (entryIndex >= index) {\n const newEntryIndex = entryIndex + 1\n return {\n ...section,\n id: `${startOfId ? startOfId : ''}${element.name}_entry-${newEntryIndex}_${restOfId}`,\n }\n }\n }\n\n return section\n }, []) || []\n )\n },\n })\n setIsDirty()\n },\n [element, onChange, setIsDirty, entries.length],\n )\n\n const handleRemoveEntry = React.useCallback(\n (\n index: number,\n element: FormTypes.RepeatableSetElement,\n idPrefix?: string,\n ) => {\n const entryIdPrefix = idPrefix || ''\n\n onChange(element, {\n value: (existingEntries) => {\n const newEntries = [...(existingEntries || [])]\n newEntries.splice(index, 1)\n return newEntries\n },\n executedLookups: (existingExecutedLookups) => {\n if (!Array.isArray(existingExecutedLookups)) {\n return []\n }\n const newExistingExecutedLookups = [...existingExecutedLookups]\n\n newExistingExecutedLookups.splice(index, 1)\n return newExistingExecutedLookups\n },\n sectionState: (currentSectionState) => {\n return (\n currentSectionState?.reduce(\n (\n state: {\n id: string\n state: 'COLLAPSED' | 'EXPANDED'\n }[],\n section,\n ) => {\n // eslint-disable-next-line security/detect-non-literal-regexp -- element name comes from the form definition\n const idPrefixPattern = new RegExp(\n `(.+)?${element.name}_entry-(\\\\d+)`,\n )\n const entryIdPrefixMatches =\n entryIdPrefix.match(idPrefixPattern)\n if (\n !section.id.startsWith(entryIdPrefix) &&\n entryIdPrefixMatches\n ) {\n const parentElementPath =\n entryIdPrefixMatches[1] || `${element.name}_entry`\n // only update nested sections where the parent path matches the entry that was removed\n if (section.id.startsWith(parentElementPath)) {\n // Match pattern: {elementName}_entry-{index}_\n // also yields a prefix and suffix for any match found\n // eslint-disable-next-line security/detect-non-literal-regexp -- element name comes from the form definition\n const idPrefixWithFullIdPattern = new RegExp(\n `(.+)?${element.name}_entry-(\\\\d+)_(.+)`,\n )\n const match = section.id.match(idPrefixWithFullIdPattern)\n\n if (match) {\n const oldEntryIndex = parseInt(match[2], 10)\n if (oldEntryIndex > index) {\n const prefix = match[1]\n const restOfId = match[3]\n const newEntryIndex = oldEntryIndex - 1\n state.push({\n ...section,\n id: `${prefix ? prefix : ''}${element.name}_entry-${newEntryIndex}_${restOfId}`,\n })\n return state\n }\n }\n }\n\n state.push(section)\n }\n\n return state\n },\n [],\n ) || []\n )\n },\n })\n setIsDirty()\n },\n [onChange, setIsDirty],\n )\n\n const handleNestedChange = React.useCallback(\n (\n index: number,\n nestedElement: FormTypes.FormElement,\n {\n value,\n executedLookups,\n sectionState,\n isDerivedChange,\n }: Parameters<NestedFormElementValueChangeHandler>[1],\n idPrefix?: string,\n ) => {\n if (nestedElement.type === 'section') {\n // trigger onChange to update sectionState\n onChange(\n {\n ...nestedElement,\n id: idPrefix ? `${idPrefix}${nestedElement.id}` : nestedElement.id,\n },\n { executedLookups: undefined, sectionState },\n )\n }\n if (!('name' in nestedElement)) {\n return\n }\n onChange(element, {\n value: (existingEntries) => {\n const newEntries = (existingEntries || []).map((entry, i) => {\n if (i === index) {\n return {\n ...entry,\n [nestedElement.name]:\n typeof value === 'function'\n ? value(entry[nestedElement.name])\n : value,\n }\n } else {\n return entry\n }\n })\n return newEntries\n },\n executedLookups: (existingExecutedLookups) => {\n const elementExecutedLookups = existingExecutedLookups ?? []\n if (!Array.isArray(elementExecutedLookups)) {\n return elementExecutedLookups\n }\n const newExecutedLookups = elementExecutedLookups.map(\n (executedLookup, i) => {\n if (i === index) {\n const updatedExecutedLookups =\n typeof executedLookups === 'function'\n ? executedLookups(executedLookup?.[nestedElement.name])\n : executedLookups\n return {\n ...executedLookup,\n [nestedElement.name]: updatedExecutedLookups,\n }\n }\n return executedLookup\n },\n )\n return newExecutedLookups\n },\n sectionState,\n isDerivedChange,\n })\n },\n [element, onChange],\n )\n\n const { minSetEntries, maxSetEntries } =\n useFormElementRepeatableSetEntries(element)\n\n const repeatableSetValidation = React.useMemo(\n () =>\n !formElementValidation ||\n typeof formElementValidation === 'string' ||\n formElementValidation.type !== 'repeatableSet'\n ? undefined\n : formElementValidation,\n [formElementValidation],\n )\n\n const repeatableSetEntriesConditionallyShown =\n formElementConditionallyShown &&\n formElementConditionallyShown.type === 'repeatableSet'\n ? formElementConditionallyShown.entries\n : {}\n\n const { validationClassName } = useValidationClass({\n formElementsValid: !repeatableSetValidation,\n displayInvalidClassName: isDirty || displayValidationMessage,\n validClassName: 'ob-repeatable-set-element__valid',\n invalidClassName: 'ob-repeatable-set-element__invalid',\n })\n\n const ariaDescribedby = useElementAriaDescribedby(id, element)\n\n const showAddButton = React.useMemo(\n () => maxSetEntries === undefined || entries.length < maxSetEntries,\n [maxSetEntries, entries.length],\n )\n\n const repeatableSetContainerClass = React.useMemo(() => {\n const prefix = 'ob-repeatable-set-container-layout__'\n switch (element.layout) {\n case 'MULTIPLE_ADD_BUTTONS':\n return prefix + 'multiple-add-buttons'\n default:\n return 'single-add-button'\n }\n }, [element.layout])\n\n return (\n <div\n className={clsx('cypress-repeatable-set-element', validationClassName)}\n aria-labelledby={`${id}-label`}\n aria-describedby={ariaDescribedby}\n role=\"region\"\n >\n {/* */}\n <FormElementLabelContainer\n className={clsx(\n 'ob-repeatable-set',\n isEven ? 'even' : 'odd',\n repeatableSetContainerClass,\n )}\n element={element}\n id={id}\n required={!!minSetEntries && minSetEntries > 0}\n associateLabelWithInput={false}\n >\n {element.layout === 'MULTIPLE_ADD_BUTTONS' && showAddButton && (\n <AddButton\n onAdd={() => handleAddEntry(0)}\n element={element}\n readOnly={readOnly}\n classes={['ob-button-repeatable-set-layout__multiple-add-buttons']}\n id={id}\n />\n )}\n {entries.map((entry, index) => {\n return (\n <RepeatableSetEntry\n key={entry[ENTRY_ID_PROPERTY_NAME] as string}\n formId={formId}\n index={index}\n id={id}\n isEven={isEven}\n entry={entry}\n element={element}\n readOnly={readOnly}\n childrenReadOnly={childrenReadOnly}\n showAddButton={\n element.layout === 'MULTIPLE_ADD_BUTTONS' && showAddButton\n }\n onChange={handleNestedChange}\n onLookup={onLookup}\n onAdd={handleAddEntry}\n onRemove={handleRemoveEntry}\n formElementsConditionallyShown={\n repeatableSetEntriesConditionallyShown[index.toString()]\n }\n formElementsValidation={\n repeatableSetValidation &&\n repeatableSetValidation.entries[index.toString()]\n }\n displayValidationMessages={displayValidationMessage}\n onUpdateFormElements={onUpdateFormElements}\n sectionState={sectionState}\n />\n )\n })}\n {(!element.layout || element.layout === 'SINGLE_ADD_BUTTON') &&\n showAddButton && (\n <AddButton\n onAdd={() => handleAddEntry(entries.length)}\n element={element}\n readOnly={readOnly}\n id={id}\n />\n )}\n {(isDirty || displayValidationMessage) &&\n !!repeatableSetValidation &&\n !!repeatableSetValidation.set && (\n <FormElementValidationMessage\n message={repeatableSetValidation.set}\n />\n )}\n </FormElementLabelContainer>\n </div>\n )\n}\n\nexport default React.memo(FormElementRepeatableSet)\n\ntype RepeatableSetEntryProps = {\n formId: number\n id: string\n index: number\n isEven: boolean\n entry: SubmissionTypes.S3SubmissionData['submission']\n element: FormTypes.RepeatableSetElement\n /**\n * Whether this entry’s add/remove controls are locked. See\n * `FormElementRepeatableSet` `readOnly`.\n */\n readOnly: boolean\n /**\n * Lock to apply to fields in this entry. See `FormElementRepeatableSet`\n * `childrenReadOnly`.\n */\n childrenReadOnly: boolean\n formElementsConditionallyShown: FormElementsConditionallyShown | undefined\n formElementsValidation: FormElementsValidation | undefined\n displayValidationMessages: boolean\n showAddButton: boolean\n onChange: (\n index: number,\n formElement: FormTypes.FormElement,\n {\n value,\n executedLookups,\n }: Parameters<NestedFormElementValueChangeHandler>[1],\n idPrefix?: string,\n ) => void\n onLookup: FormElementLookupHandler\n onAdd: (index: number) => unknown\n onRemove: (\n index: number,\n element: FormTypes.RepeatableSetElement,\n idPrefix?: string,\n ) => unknown\n onUpdateFormElements: UpdateFormElementsHandler\n sectionState: SectionState\n}\n\nconst RepeatableSetEntry = React.memo<RepeatableSetEntryProps>(\n function RepeatableSetEntry({\n formId,\n id,\n index,\n isEven,\n entry,\n element,\n readOnly,\n childrenReadOnly,\n formElementsConditionallyShown,\n displayValidationMessages,\n formElementsValidation,\n onChange,\n onLookup,\n onAdd,\n onRemove,\n onUpdateFormElements,\n showAddButton,\n sectionState,\n }: RepeatableSetEntryProps) {\n const [isConfirmingRemove, confirmRemove, cancelRemove] =\n useBooleanState(false)\n const elementDOMId = React.useMemo(() => new ElementDOMId(id), [id])\n\n const handleChange: NestedFormElementValueChangeHandler = React.useCallback(\n (\n nestedElement,\n { value, executedLookups, sectionState, isDerivedChange },\n idPrefix,\n ) => {\n onChange(\n index,\n nestedElement,\n {\n value,\n executedLookups,\n sectionState,\n isDerivedChange,\n },\n idPrefix,\n )\n },\n [index, onChange],\n )\n\n const handleLookup = React.useCallback<FormElementLookupHandler>(\n (mergeLookupResults, options) => {\n onLookup((currentFormSubmission) => {\n let newEntry = {}\n const entries = currentFormSubmission.submission[\n element.name\n ] as Array<SubmissionTypes.S3SubmissionData['submission']>\n const existingExecutedLookups = (currentFormSubmission\n .executedLookups?.[element.name] ??\n Array.from(Array(entries.length))) as ExecutedLookups[]\n const repeatableSetExecutedLookups = Array.isArray(\n existingExecutedLookups,\n )\n ? [...existingExecutedLookups]\n : existingExecutedLookups\n // if the repeatable set is prefilled or has minimum entries then executed lookups exists,\n // but is an empty array\n if (\n Array.isArray(repeatableSetExecutedLookups) &&\n !repeatableSetExecutedLookups[index]\n ) {\n repeatableSetExecutedLookups[index] = {}\n }\n let newExecutedLookups: ExecutedLookups = {}\n const elements = currentFormSubmission.elements.map((formElement) => {\n if (\n formElement.type === 'repeatableSet' &&\n formElement.name === element.name\n ) {\n const { elements, submission, executedLookups } =\n mergeLookupResults({\n elements: formElement.elements,\n submission: entries[index],\n lastElementUpdated: currentFormSubmission.lastElementUpdated,\n executedLookups: repeatableSetExecutedLookups[index] ?? {},\n sectionState: currentFormSubmission.sectionState,\n })\n newEntry = submission\n newExecutedLookups = executedLookups as ExecutedLookups\n return {\n ...formElement,\n elements,\n }\n }\n return formElement\n })\n\n const submission = {\n ...currentFormSubmission.submission,\n [element.name]: entries.map((entry, i) => {\n if (i === index) {\n return newEntry\n }\n return entry\n }),\n }\n\n let updatedExecutedLookups = currentFormSubmission.executedLookups\n if (Array.isArray(repeatableSetExecutedLookups)) {\n updatedExecutedLookups = {\n ...currentFormSubmission.executedLookups,\n [element.name]: repeatableSetExecutedLookups.map((entry, i) => {\n if (i == index) {\n return newExecutedLookups\n }\n return entry\n }),\n }\n }\n\n return {\n elements,\n submission,\n executedLookups: updatedExecutedLookups,\n }\n }, options)\n },\n [element.name, index, onLookup],\n )\n\n const { validationClassName } = useValidationClass({\n formElementsValid: !formElementsValidation,\n displayInvalidClassName: displayValidationMessages,\n validClassName: 'ob-repeatable-set__valid',\n invalidClassName: 'ob-repeatable-set__invalid',\n })\n\n const handleUpdateNestedFormElements =\n React.useCallback<UpdateFormElementsHandler>(\n (setter) => {\n onUpdateFormElements((formElements) => {\n return formElements.map((formElement) => {\n if (\n formElement.id === element.id &&\n formElement.type === 'repeatableSet'\n ) {\n return {\n ...formElement,\n elements: setter(formElement.elements),\n }\n }\n return formElement\n })\n })\n },\n [element.id, onUpdateFormElements],\n )\n\n const idPrefix = elementDOMId.repeatableSetEntryDOMIdPrefix(\n index.toString(),\n )\n\n return (\n <RepeatableSetEntryProvider\n index={index}\n element={element}\n idPrefix={idPrefix}\n onRemove={onRemove}\n isAnimated={element.layout === 'MULTIPLE_ADD_BUTTONS'}\n >\n {({ onRemove }) => (\n <>\n <Modal\n isOpen={isConfirmingRemove}\n className=\"cypress-repeatable-set-prompt\"\n titleClassName=\"cypress-repeatable-set-remove-entry-header\"\n title={element.removeSetEntryLabel || 'Remove Entry'}\n actions={\n <>\n <button\n type=\"button\"\n className=\"button ob-button is-light cypress-cancel-repeatable-set\"\n onClick={cancelRemove}\n >\n Cancel\n </button>\n <button\n type=\"button\"\n className=\"button ob-button is-primary cypress-confirm-repeatable-set\"\n onClick={() => {\n cancelRemove()\n onRemove()\n }}\n autoFocus\n >\n Yes\n </button>\n </>\n }\n >\n Are you sure you want to remove this entry?\n </Modal>\n\n <div\n className={clsx(\n 'ob-repeatable-set__container cypress-repeatable-set-container',\n validationClassName,\n )}\n >\n {(!element.layout || element.layout === 'SINGLE_ADD_BUTTON') && (\n <RemoveButton\n onConfirmRemove={confirmRemove}\n element={element}\n readOnly={readOnly}\n className=\"ob-repeatable-set__button-remove-top\"\n index={index}\n />\n )}\n\n <OneBlinkFormElements\n formId={formId}\n idPrefix={idPrefix}\n isEven={isEven}\n formElementsValidation={formElementsValidation}\n displayValidationMessages={displayValidationMessages}\n elements={element.elements}\n onChange={handleChange}\n onLookup={handleLookup}\n model={entry}\n parentElement={element}\n readOnly={childrenReadOnly}\n formElementsConditionallyShown={formElementsConditionallyShown}\n onUpdateFormElements={handleUpdateNestedFormElements}\n sectionState={sectionState}\n />\n {element.layout === 'MULTIPLE_ADD_BUTTONS' && (\n <RemoveButton\n onConfirmRemove={confirmRemove}\n element={element}\n readOnly={readOnly}\n index={index}\n className=\"ob-repeatable-set__button-remove-bottom\"\n />\n )}\n </div>\n {showAddButton && (\n <AddButton\n onAdd={() => onAdd(index + 1)}\n element={element}\n readOnly={readOnly}\n classes={[\n 'ob-button-repeatable-set-layout__multiple-add-buttons',\n ]}\n />\n )}\n </>\n )}\n </RepeatableSetEntryProvider>\n )\n },\n)\n\nfunction AddButton({\n id,\n onAdd,\n element,\n readOnly,\n classes,\n}: {\n id?: string\n onAdd: () => void\n element: FormTypes.RepeatableSetElement\n readOnly: boolean\n isPrimary?: boolean\n classes?: string[]\n}) {\n return (\n <button\n type=\"button\"\n className={clsx(\n 'button ob-button ob-button__add cypress-add-repeatable-set is-primary',\n classes,\n )}\n onClick={onAdd}\n disabled={readOnly}\n aria-label={element.addSetEntryLabel ? undefined : 'Add Entry'}\n id={id}\n >\n <span className=\"icon\">\n <MaterialIcon>add</MaterialIcon>\n </span>\n {!!element.addSetEntryLabel && <span>{element.addSetEntryLabel}</span>}\n </button>\n )\n}\n\nfunction RemoveButton({\n onConfirmRemove,\n element,\n readOnly,\n className,\n index,\n}: {\n onConfirmRemove: () => void\n element: FormTypes.RepeatableSetElement\n readOnly: boolean\n className?: string\n index: number\n}) {\n return (\n <button\n type=\"button\"\n className={clsx(\n 'button ob-button ob-button_remove is-light cypress-remove-repeatable-set-entry',\n className,\n )}\n onClick={onConfirmRemove}\n disabled={readOnly}\n aria-label={`${element.removeSetEntryLabel ?? 'Remove Entry'} ${index + 1}`}\n >\n <span className=\"icon\">\n <MaterialIcon>delete_outline</MaterialIcon>\n </span>\n {!!element.removeSetEntryLabel && (\n <span>{element.removeSetEntryLabel}</span>\n )}\n </button>\n )\n}\n"]}
@@ -20,6 +20,7 @@ type MfaState = {
20
20
  isRemovePhoneNumberDialogOpen: boolean;
21
21
  };
22
22
  export declare const MfaContext: React.Context<MfaState & {
23
+ authenticatorAppDisplayName?: string;
23
24
  beginMfaSetup: (mfaMethod: mfaService.MfaMethod) => Promise<void>;
24
25
  openMfaSetupMethodDialog: () => void;
25
26
  closeMfaSetupMethodDialog: () => void;
@@ -93,11 +94,18 @@ export declare const MfaContext: React.Context<MfaState & {
93
94
  * @returns
94
95
  * @group Components
95
96
  */
96
- export declare function MfaProvider({ children, isExternalIdentityProviderUser, }: {
97
+ export declare function MfaProvider({ children, isExternalIdentityProviderUser, authenticatorAppDisplayName, }: {
97
98
  children: React.ReactNode;
98
99
  isExternalIdentityProviderUser: boolean;
100
+ /**
101
+ * Name shown in authenticator apps when a user sets up an authenticator.
102
+ * When omitted, the product name is used. Console sign-in omits this so it
103
+ * continues to show the product name.
104
+ */
105
+ authenticatorAppDisplayName?: string;
99
106
  }): import("react/jsx-runtime").JSX.Element;
100
107
  export default function useMfa(): MfaState & {
108
+ authenticatorAppDisplayName?: string;
101
109
  beginMfaSetup: (mfaMethod: mfaService.MfaMethod) => Promise<void>;
102
110
  openMfaSetupMethodDialog: () => void;
103
111
  closeMfaSetupMethodDialog: () => void;
@@ -13,6 +13,7 @@ export const MfaContext = React.createContext({
13
13
  isSettingPreferredMfaMethod: false,
14
14
  isPhoneNumberDialogOpen: false,
15
15
  isRemovePhoneNumberDialogOpen: false,
16
+ authenticatorAppDisplayName: undefined,
16
17
  beginMfaSetup: async () => { },
17
18
  openMfaSetupMethodDialog: () => { },
18
19
  closeMfaSetupMethodDialog: () => { },
@@ -130,7 +131,7 @@ function setPreferredMfaMethodInSettings(mfaSettings, mfaMethod) {
130
131
  * @returns
131
132
  * @group Components
132
133
  */
133
- export function MfaProvider({ children, isExternalIdentityProviderUser, }) {
134
+ export function MfaProvider({ children, isExternalIdentityProviderUser, authenticatorAppDisplayName, }) {
134
135
  const [state, setState] = React.useState({
135
136
  isExternalIdentityProviderUser,
136
137
  isLoading: !isExternalIdentityProviderUser,
@@ -478,6 +479,7 @@ export function MfaProvider({ children, isExternalIdentityProviderUser, }) {
478
479
  const value = React.useMemo(() => {
479
480
  return {
480
481
  ...state,
482
+ authenticatorAppDisplayName,
481
483
  clearMfaSetupError,
482
484
  loadMfa,
483
485
  beginMfaSetup,
@@ -519,6 +521,7 @@ export function MfaProvider({ children, isExternalIdentityProviderUser, }) {
519
521
  completeMfaAuthenticatorAppSetup,
520
522
  cancelDisablingMfa,
521
523
  completeDisablingMfa,
524
+ authenticatorAppDisplayName,
522
525
  ]);
523
526
  return _jsx(MfaContext.Provider, { value: value, children: children });
524
527
  }
@@ -1 +1 @@
1
- {"version":3,"file":"useMfa.js","sourceRoot":"","sources":["../../src/hooks/useMfa.tsx"],"names":[],"mappings":";AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpC,OAAO,iBAAiB,MAAM,qBAAqB,CAAA;AAwBnD,MAAM,CAAC,MAAM,UAAU,GAAG,KAAK,CAAC,aAAa,CAsB3C;IACA,8BAA8B,EAAE,KAAK;IACrC,SAAS,EAAE,IAAI;IACf,YAAY,EAAE,KAAK;IACnB,WAAW,EAAE,UAAU,CAAC,oBAAoB;IAC5C,kBAAkB,EAAE,KAAK;IACzB,cAAc,EAAE,KAAK;IACrB,uBAAuB,EAAE,KAAK;IAC9B,2BAA2B,EAAE,KAAK;IAClC,uBAAuB,EAAE,KAAK;IAC9B,6BAA6B,EAAE,KAAK;IACpC,aAAa,EAAE,KAAK,IAAI,EAAE,GAAE,CAAC;IAC7B,wBAAwB,EAAE,GAAG,EAAE,GAAE,CAAC;IAClC,yBAAyB,EAAE,GAAG,EAAE,GAAE,CAAC;IACnC,uBAAuB,EAAE,GAAG,EAAE,GAAE,CAAC;IACjC,qBAAqB,EAAE,KAAK,IAAI,EAAE,GAAE,CAAC;IACrC,qBAAqB,EAAE,GAAG,EAAE,GAAE,CAAC;IAC/B,sBAAsB,EAAE,GAAG,EAAE,GAAE,CAAC;IAChC,eAAe,EAAE,KAAK,IAAI,EAAE,GAAE,CAAC;IAC/B,iBAAiB,EAAE,KAAK,IAAI,EAAE,GAAE,CAAC;IACjC,wBAAwB,EA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AgB;QAChB,8BAA8B;QAC9B,gCAAgC;QAChC,kBAAkB;QAClB,oBAAoB;KACrB,CAAC,CAAA;IAEF,OAAO,KAAC,UAAU,CAAC,QAAQ,IAAC,KAAK,EAAE,KAAK,YAAG,QAAQ,GAAuB,CAAA;AAC5E,CAAC;AAED,MAAM,CAAC,OAAO,UAAU,MAAM;IAC5B,OAAO,KAAK,CAAC,UAAU,CAAC,UAAU,CAAC,CAAA;AACrC,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,MAAM,UAAU,0BAA0B,CACxC,cAAoD;IAEpD,MAAM,EACJ,SAAS,EACT,YAAY,EACZ,WAAW,EACX,OAAO,EACP,8BAA8B,GAC/B,GAAG,MAAM,EAAE,CAAA;IAEZ,OAAO,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE;QACxB,MAAM,WAAW,GAAG,UAAU,CAAC,aAAa,CAAC,cAAc,CAAC,CAAA;QAC5D,MAAM,cAAc,GAAG,WAAW,IAAI,CAAC,8BAA8B,CAAA;QACrE,MAAM,gBAAgB,GAAG,UAAU,CAAC,uBAAuB,CACzD,cAAc,EACd,WAAW,CACZ,CAAA;QACD,MAAM,gBAAgB,GACpB,cAAc,IAAI,CAAC,SAAS,IAAI,CAAC,YAAY,IAAI,CAAC,gBAAgB,CAAA;QAEpE,OAAO;YACL,gBAAgB;YAChB,SAAS,EAAE,cAAc,IAAI,SAAS;YACtC,YAAY,EAAE,cAAc,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS;YACvD,UAAU,EAAE,OAAO;SACpB,CAAA;IACH,CAAC,EAAE;QACD,cAAc;QACd,8BAA8B;QAC9B,WAAW;QACX,SAAS;QACT,YAAY;QACZ,OAAO;KACR,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import * as React from 'react'\nimport { mfaService } from '../apps'\nimport useLoadDataEffect from './useLoadDataEffect'\nimport { MiscTypes } from '@oneblink/types'\n\ntype MfaState = {\n isExternalIdentityProviderUser: boolean\n isLoading: boolean\n isMfaEnabled: boolean\n mfaSettings: mfaService.MfaSettings\n isSetupSuccessOpen: boolean\n loadingError?: Error\n isSettingUpMfa: boolean\n settingUpMfaMethod?: mfaService.MfaMethod\n isSetupMethodDialogOpen: boolean\n disablingMfaMethod?: mfaService.MfaMethod\n isSettingPreferredMfaMethod: boolean\n setupError?: Error\n mfaAuthenticatorAppSetup?: Awaited<\n ReturnType<typeof mfaService.setupMfaAuthenticatorApp>\n >\n isPhoneNumberDialogOpen: boolean\n phoneVerificationCodeSentAt?: number\n isRemovePhoneNumberDialogOpen: boolean\n}\n\nexport const MfaContext = React.createContext<\n MfaState & {\n beginMfaSetup: (mfaMethod: mfaService.MfaMethod) => Promise<void>\n openMfaSetupMethodDialog: () => void\n closeMfaSetupMethodDialog: () => void\n beginDisablingMfaMethod: (mfaMethod: mfaService.MfaMethod) => void\n setPreferredMfaMethod: (mfaMethod: mfaService.MfaMethod) => Promise<void>\n openPhoneNumberDialog: () => void\n closePhoneNumberDialog: () => void\n savePhoneNumber: (phoneNumber: string) => Promise<void>\n verifyPhoneNumber: (code: string) => Promise<void>\n beginRemovingPhoneNumber: () => void\n cancelRemovingPhoneNumber: () => void\n completeRemovingPhoneNumber: () => Promise<void>\n hideSetupSuccess: () => void\n cancelMfaAuthenticatorAppSetup: () => void\n completeMfaAuthenticatorAppSetup: () => Promise<void>\n cancelDisablingMfa: () => void\n completeDisablingMfa: () => Promise<void>\n clearMfaSetupError: () => void\n loadMfa: () => void\n }\n>({\n isExternalIdentityProviderUser: false,\n isLoading: true,\n isMfaEnabled: false,\n mfaSettings: mfaService.DEFAULT_MFA_SETTINGS,\n isSetupSuccessOpen: false,\n isSettingUpMfa: false,\n isSetupMethodDialogOpen: false,\n isSettingPreferredMfaMethod: false,\n isPhoneNumberDialogOpen: false,\n isRemovePhoneNumberDialogOpen: false,\n beginMfaSetup: async () => {},\n openMfaSetupMethodDialog: () => {},\n closeMfaSetupMethodDialog: () => {},\n beginDisablingMfaMethod: () => {},\n setPreferredMfaMethod: async () => {},\n openPhoneNumberDialog: () => {},\n closePhoneNumberDialog: () => {},\n savePhoneNumber: async () => {},\n verifyPhoneNumber: async () => {},\n beginRemovingPhoneNumber: () => {},\n cancelRemovingPhoneNumber: () => {},\n completeRemovingPhoneNumber: async () => {},\n hideSetupSuccess: () => {},\n cancelMfaAuthenticatorAppSetup: () => {},\n completeMfaAuthenticatorAppSetup: async () => {},\n cancelDisablingMfa: () => {},\n completeDisablingMfa: async () => {},\n clearMfaSetupError: () => {},\n loadMfa: () => {},\n})\n\nfunction getIsMfaEnabled(mfaSettings: mfaService.MfaSettings) {\n return mfaSettings.authenticator.enabled || mfaSettings.sms.enabled\n}\n\nfunction hasPreferredMfaMethod(mfaSettings: mfaService.MfaSettings) {\n return (\n (mfaSettings.authenticator.enabled &&\n mfaSettings.authenticator.preferred) ||\n (mfaSettings.sms.enabled && mfaSettings.sms.preferred)\n )\n}\n\nfunction enableSmsMfaInSettings(\n mfaSettings: mfaService.MfaSettings,\n smsPreferred: boolean,\n): mfaService.MfaSettings {\n return {\n ...mfaSettings,\n sms: {\n ...mfaSettings.sms,\n enabled: true,\n preferred: smsPreferred,\n },\n }\n}\n\nfunction enableAuthenticatorMfaInSettings(\n mfaSettings: mfaService.MfaSettings,\n authenticatorPreferred: boolean,\n): mfaService.MfaSettings {\n return {\n ...mfaSettings,\n authenticator: {\n enabled: true,\n preferred: authenticatorPreferred,\n },\n sms: {\n ...mfaSettings.sms,\n preferred: authenticatorPreferred ? false : mfaSettings.sms.preferred,\n },\n }\n}\n\nfunction setPreferredMfaMethodInSettings(\n mfaSettings: mfaService.MfaSettings,\n mfaMethod: mfaService.MfaMethod,\n): mfaService.MfaSettings {\n return {\n ...mfaSettings,\n authenticator: {\n ...mfaSettings.authenticator,\n preferred: mfaMethod === 'authenticator',\n },\n sms: {\n ...mfaSettings.sms,\n preferred: mfaMethod === 'sms',\n },\n }\n}\n\n/**\n * React Component that provides the context for the\n * `useUserMeetsMfaRequirement()` hook and `<MultiFactorAuthentication />`\n * component, to be used by components further down your component tree. **It\n * should only be included in your component tree once and ideally at the root\n * of the application.**\n *\n * #### Example\n *\n * ```js\n * import * as React from 'react'\n * import {\n * MfaProvider,\n * useUserMeetsMfaRequirement,\n * } from '@oneblink/apps-react'\n *\n * function Component({ teamMemberMfaRequirement }) {\n * const { mfaSetupRequired, isLoading, loadingError, refreshMfa } =\n * useUserMeetsMfaRequirement(teamMemberMfaRequirement)\n *\n * if (isLoading) {\n * return <Loading />\n * }\n *\n * if (loadingError) {\n * return <Error onRetry={refreshMfa} />\n * }\n *\n * if (mfaSetupRequired) {\n * return <ConfigureMfa />\n * }\n *\n * return <Application />\n * }\n *\n * function App({ teamMemberMfaRequirement }) {\n * return (\n * <MfaProvider isExternalIdentityProviderUser={false}>\n * <Component teamMemberMfaRequirement={teamMemberMfaRequirement} />\n * </MfaProvider>\n * )\n * }\n *\n * const root = document.getElementById('root')\n * if (root) {\n * ReactDOM.render(<App teamMemberMfaRequirement={mfaRequirement} />, root)\n * }\n * ```\n *\n * @param props\n * @returns\n * @group Components\n */\nexport function MfaProvider({\n children,\n isExternalIdentityProviderUser,\n}: {\n children: React.ReactNode\n isExternalIdentityProviderUser: boolean\n}) {\n const [state, setState] = React.useState<MfaState>({\n isExternalIdentityProviderUser,\n isLoading: !isExternalIdentityProviderUser,\n isMfaEnabled: false,\n mfaSettings: mfaService.DEFAULT_MFA_SETTINGS,\n isSetupSuccessOpen: false,\n isSettingUpMfa: false,\n isSetupMethodDialogOpen: false,\n isSettingPreferredMfaMethod: false,\n isPhoneNumberDialogOpen: false,\n isRemovePhoneNumberDialogOpen: false,\n })\n\n const handleLoadMfa = React.useCallback(\n async (abortSignal: AbortSignal) => {\n if (isExternalIdentityProviderUser) {\n return\n }\n\n setState((currentState) => ({\n ...currentState,\n isLoading: true,\n isMfaEnabled: false,\n mfaSettings: mfaService.DEFAULT_MFA_SETTINGS,\n loadingError: undefined,\n }))\n try {\n const mfaSettings = await mfaService.getMfaSettings(abortSignal)\n if (!abortSignal.aborted) {\n setState((currentState) => ({\n ...currentState,\n isLoading: false,\n mfaSettings,\n isMfaEnabled: getIsMfaEnabled(mfaSettings),\n }))\n }\n } catch (error) {\n if (abortSignal.aborted) {\n return\n }\n\n setState((currentState) => ({\n ...currentState,\n isLoading: false,\n loadingError: error as Error,\n }))\n }\n },\n [isExternalIdentityProviderUser],\n )\n\n const loadMfa = useLoadDataEffect(handleLoadMfa)\n\n const clearMfaSetupError = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n setupError: undefined,\n }))\n }, [])\n\n const openMfaSetupMethodDialog = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isSetupMethodDialogOpen: true,\n }))\n }, [])\n\n const closeMfaSetupMethodDialog = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isSetupMethodDialogOpen: false,\n }))\n }, [])\n\n const hideSetupSuccess = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isSetupSuccessOpen: false,\n }))\n }, [])\n\n const cancelMfaAuthenticatorAppSetup = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n mfaAuthenticatorAppSetup: undefined,\n settingUpMfaMethod: undefined,\n }))\n }, [])\n\n const completeMfaAuthenticatorAppSetup = React.useCallback(async () => {\n setState((currentState) => {\n const authenticatorPreferred = !hasPreferredMfaMethod(\n currentState.mfaSettings,\n )\n const mfaSettings = enableAuthenticatorMfaInSettings(\n currentState.mfaSettings,\n authenticatorPreferred,\n )\n\n return {\n ...currentState,\n isSetupSuccessOpen: true,\n isMfaEnabled: getIsMfaEnabled(mfaSettings),\n mfaSettings,\n mfaAuthenticatorAppSetup: undefined,\n settingUpMfaMethod: undefined,\n }\n })\n }, [])\n\n const openPhoneNumberDialog = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isPhoneNumberDialogOpen: true,\n phoneVerificationCodeSentAt: undefined,\n setupError: undefined,\n }))\n }, [])\n\n const closePhoneNumberDialog = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isPhoneNumberDialogOpen: false,\n phoneVerificationCodeSentAt: undefined,\n }))\n }, [])\n\n const setupSmsMfaMethod = React.useCallback(async () => {\n let smsPreferred = false\n\n setState((currentState) => {\n smsPreferred = !hasPreferredMfaMethod(currentState.mfaSettings)\n return currentState\n })\n\n await mfaService.setupSmsMfa({\n preferred: smsPreferred,\n })\n\n setState((currentState) => {\n const mfaSettings = enableSmsMfaInSettings(\n currentState.mfaSettings,\n smsPreferred,\n )\n\n return {\n ...currentState,\n isSetupSuccessOpen: true,\n isSettingUpMfa: false,\n settingUpMfaMethod: undefined,\n isMfaEnabled: getIsMfaEnabled(mfaSettings),\n mfaSettings,\n }\n })\n }, [])\n\n const savePhoneNumber = React.useCallback(\n async (phoneNumber: string) => {\n setState((currentState) => ({\n ...currentState,\n setupError: undefined,\n }))\n\n try {\n const { isPhoneNumberVerified } =\n await mfaService.updateUserPhoneNumber(phoneNumber)\n\n if (!isPhoneNumberVerified) {\n setState((currentState) => ({\n ...currentState,\n phoneVerificationCodeSentAt: Date.now(),\n mfaSettings: {\n ...currentState.mfaSettings,\n sms: {\n ...currentState.mfaSettings.sms,\n phoneNumber,\n isPhoneNumberVerified: false,\n },\n },\n }))\n return\n }\n setState((currentState) => ({\n ...currentState,\n mfaSettings: {\n ...currentState.mfaSettings,\n sms: {\n ...currentState.mfaSettings.sms,\n phoneNumber,\n isPhoneNumberVerified,\n },\n },\n isPhoneNumberDialogOpen: false,\n phoneVerificationCodeSentAt: undefined,\n }))\n await setupSmsMfaMethod()\n } catch (error) {\n setState((currentState) => ({\n ...currentState,\n setupError: error as Error,\n }))\n }\n },\n [setupSmsMfaMethod],\n )\n\n const verifyPhoneNumber = React.useCallback(\n async (code: string) => {\n setState((currentState) => ({\n ...currentState,\n setupError: undefined,\n }))\n\n try {\n await mfaService.verifyUserPhoneNumber(code)\n\n setState((currentState) => ({\n ...currentState,\n mfaSettings: {\n ...currentState.mfaSettings,\n sms: {\n ...currentState.mfaSettings.sms,\n isPhoneNumberVerified: true,\n },\n },\n isPhoneNumberDialogOpen: false,\n phoneVerificationCodeSentAt: undefined,\n }))\n await setupSmsMfaMethod()\n } catch (error) {\n setState((currentState) => ({\n ...currentState,\n setupError: error as Error,\n }))\n }\n },\n [setupSmsMfaMethod],\n )\n\n const beginRemovingPhoneNumber = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isRemovePhoneNumberDialogOpen: true,\n setupError: undefined,\n }))\n }, [])\n\n const cancelRemovingPhoneNumber = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isRemovePhoneNumberDialogOpen: false,\n }))\n }, [])\n\n const completeRemovingPhoneNumber = React.useCallback(async () => {\n setState((currentState) => ({\n ...currentState,\n setupError: undefined,\n }))\n\n try {\n await mfaService.removeUserPhoneNumber()\n setState((currentState) => ({\n ...currentState,\n isRemovePhoneNumberDialogOpen: false,\n mfaSettings: {\n ...currentState.mfaSettings,\n sms: {\n ...currentState.mfaSettings.sms,\n phoneNumber: undefined,\n isPhoneNumberVerified: false,\n },\n },\n }))\n } catch (error) {\n setState((currentState) => ({\n ...currentState,\n setupError: error as Error,\n }))\n }\n }, [])\n\n const beginMfaSetup = React.useCallback(\n async (mfaMethod: mfaService.MfaMethod) => {\n setState((currentState) => ({\n ...currentState,\n isSettingUpMfa: true,\n settingUpMfaMethod: mfaMethod,\n mfaAuthenticatorAppSetup: undefined,\n setupError: undefined,\n }))\n\n try {\n let mfaSettings = mfaService.DEFAULT_MFA_SETTINGS\n\n setState((currentState) => {\n mfaSettings = currentState.mfaSettings\n return currentState\n })\n\n if (mfaMethod === 'sms') {\n if (\n !mfaSettings.sms.phoneNumber ||\n !mfaSettings.sms.isPhoneNumberVerified\n ) {\n setState((currentState) => ({\n ...currentState,\n isSettingUpMfa: false,\n settingUpMfaMethod: undefined,\n isSetupMethodDialogOpen: false,\n isPhoneNumberDialogOpen: true,\n }))\n return\n }\n\n await setupSmsMfaMethod()\n setState((currentState) => ({\n ...currentState,\n isSetupMethodDialogOpen: false,\n }))\n return\n }\n\n const hasPreferredMethod = hasPreferredMfaMethod(mfaSettings)\n const newMfaAuthenticatorAppSetup =\n await mfaService.setupMfaAuthenticatorApp({\n preferred: !hasPreferredMethod,\n })\n setState((currentState) => ({\n ...currentState,\n isSettingUpMfa: false,\n isSetupMethodDialogOpen: false,\n mfaAuthenticatorAppSetup: newMfaAuthenticatorAppSetup,\n }))\n } catch (error) {\n setState((currentState) => ({\n ...currentState,\n isSettingUpMfa: false,\n settingUpMfaMethod: undefined,\n setupError: error as Error,\n }))\n }\n },\n [setupSmsMfaMethod],\n )\n\n const disablingMfaMethodRef = React.useRef<mfaService.MfaMethod | undefined>(\n undefined,\n )\n\n const beginDisablingMfaMethod = React.useCallback(\n (mfaMethod: mfaService.MfaMethod) => {\n disablingMfaMethodRef.current = mfaMethod\n setState((currentState) => ({\n ...currentState,\n disablingMfaMethod: mfaMethod,\n }))\n },\n [],\n )\n\n const cancelDisablingMfa = React.useCallback(() => {\n disablingMfaMethodRef.current = undefined\n setState((currentState) => ({\n ...currentState,\n disablingMfaMethod: undefined,\n }))\n }, [])\n\n const completeDisablingMfa = React.useCallback(async () => {\n const disablingMfaMethod = disablingMfaMethodRef.current\n if (!disablingMfaMethod) {\n return\n }\n\n await mfaService.disableMfaMethod(disablingMfaMethod)\n const mfaSettings = await mfaService.getMfaSettings()\n disablingMfaMethodRef.current = undefined\n setState((currentState) => ({\n ...currentState,\n disablingMfaMethod: undefined,\n mfaSettings,\n isMfaEnabled: getIsMfaEnabled(mfaSettings),\n }))\n }, [])\n\n const setPreferredMfaMethod = React.useCallback(\n async (mfaMethod: mfaService.MfaMethod) => {\n setState((currentState) => ({\n ...currentState,\n isSettingPreferredMfaMethod: true,\n setupError: undefined,\n }))\n\n try {\n await mfaService.setPreferredMfaMethod(mfaMethod)\n setState((currentState) => ({\n ...currentState,\n isSettingPreferredMfaMethod: false,\n mfaSettings: setPreferredMfaMethodInSettings(\n currentState.mfaSettings,\n mfaMethod,\n ),\n }))\n } catch (error) {\n setState((currentState) => ({\n ...currentState,\n isSettingPreferredMfaMethod: false,\n setupError: error as Error,\n }))\n }\n },\n [],\n )\n\n const value = React.useMemo(() => {\n return {\n ...state,\n clearMfaSetupError,\n loadMfa,\n beginMfaSetup,\n openMfaSetupMethodDialog,\n closeMfaSetupMethodDialog,\n beginDisablingMfaMethod,\n setPreferredMfaMethod,\n openPhoneNumberDialog,\n closePhoneNumberDialog,\n savePhoneNumber,\n verifyPhoneNumber,\n beginRemovingPhoneNumber,\n cancelRemovingPhoneNumber,\n completeRemovingPhoneNumber,\n hideSetupSuccess,\n cancelMfaAuthenticatorAppSetup,\n completeMfaAuthenticatorAppSetup,\n cancelDisablingMfa,\n completeDisablingMfa,\n }\n }, [\n state,\n clearMfaSetupError,\n loadMfa,\n beginMfaSetup,\n openMfaSetupMethodDialog,\n closeMfaSetupMethodDialog,\n beginDisablingMfaMethod,\n setPreferredMfaMethod,\n openPhoneNumberDialog,\n closePhoneNumberDialog,\n savePhoneNumber,\n verifyPhoneNumber,\n beginRemovingPhoneNumber,\n cancelRemovingPhoneNumber,\n completeRemovingPhoneNumber,\n hideSetupSuccess,\n cancelMfaAuthenticatorAppSetup,\n completeMfaAuthenticatorAppSetup,\n cancelDisablingMfa,\n completeDisablingMfa,\n ])\n\n return <MfaContext.Provider value={value}>{children}</MfaContext.Provider>\n}\n\nexport default function useMfa() {\n return React.useContext(MfaContext)\n}\n\n/**\n * React hook to determine whether the logged in user must set up MFA before\n * accessing your application. Reads MFA settings from the `<MfaProvider />`\n * context. Will throw an Error if used outside of `<MfaProvider />`.\n *\n * Users signed in via an external identity provider are not required to set up\n * MFA.\n *\n * #### Example\n *\n * ```js\n * import { MfaProvider, useUserMeetsMfaRequirement } from '@oneblink/apps-react'\n *\n * function Component({ teamMemberMfaRequirement }) {\n * const { mfaSetupRequired, isLoading, loadingError, refreshMfa } =\n * useUserMeetsMfaRequirement(teamMemberMfaRequirement)\n *\n * if (isLoading) {\n * return <Loading />\n * }\n *\n * if (loadingError) {\n * return <Error onRetry={refreshMfa} />\n * }\n *\n * if (mfaSetupRequired) {\n * return <ConfigureMfa />\n * }\n *\n * return <Application />\n * }\n * ```\n *\n * @param mfaRequirement - The MFA requirement to enforce, e.g. from your\n * organisation or app settings.\n * @returns Whether MFA setup is required, along with loading state from the MFA\n * provider.\n * @group Hooks\n */\nexport function useUserMeetsMfaRequirement(\n mfaRequirement: MiscTypes.MfaRequirement | undefined,\n) {\n const {\n isLoading,\n loadingError,\n mfaSettings,\n loadMfa,\n isExternalIdentityProviderUser,\n } = useMfa()\n\n return React.useMemo(() => {\n const mfaRequired = mfaService.isMfaRequired(mfaRequirement)\n const shouldCheckMfa = mfaRequired && !isExternalIdentityProviderUser\n const meetsRequirement = mfaService.userMeetsMfaRequirement(\n mfaRequirement,\n mfaSettings,\n )\n const mfaSetupRequired =\n shouldCheckMfa && !isLoading && !loadingError && !meetsRequirement\n\n return {\n mfaSetupRequired,\n isLoading: shouldCheckMfa && isLoading,\n loadingError: shouldCheckMfa ? loadingError : undefined,\n refreshMfa: loadMfa,\n }\n }, [\n mfaRequirement,\n isExternalIdentityProviderUser,\n mfaSettings,\n isLoading,\n loadingError,\n loadMfa,\n ])\n}\n"]}
1
+ {"version":3,"file":"useMfa.js","sourceRoot":"","sources":["../../src/hooks/useMfa.tsx"],"names":[],"mappings":";AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAAE,UAAU,EAAE,MAAM,SAAS,CAAA;AACpC,OAAO,iBAAiB,MAAM,qBAAqB,CAAA;AAwBnD,MAAM,CAAC,MAAM,UAAU,GAAG,KAAK,CAAC,aAAa,CAuB3C;IACA,8BAA8B,EAAE,KAAK;IACrC,SAAS,EAAE,IAAI;IACf,YAAY,EAAE,KAAK;IACnB,WAAW,EAAE,UAAU,CAAC,oBAAoB;IAC5C,kBAAkB,EAAE,K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cAAc,CAAC,CAAA;QAC5D,MAAM,cAAc,GAAG,WAAW,IAAI,CAAC,8BAA8B,CAAA;QACrE,MAAM,gBAAgB,GAAG,UAAU,CAAC,uBAAuB,CACzD,cAAc,EACd,WAAW,CACZ,CAAA;QACD,MAAM,gBAAgB,GACpB,cAAc,IAAI,CAAC,SAAS,IAAI,CAAC,YAAY,IAAI,CAAC,gBAAgB,CAAA;QAEpE,OAAO;YACL,gBAAgB;YAChB,SAAS,EAAE,cAAc,IAAI,SAAS;YACtC,YAAY,EAAE,cAAc,CAAC,CAAC,CAAC,YAAY,CAAC,CAAC,CAAC,SAAS;YACvD,UAAU,EAAE,OAAO;SACpB,CAAA;IACH,CAAC,EAAE;QACD,cAAc;QACd,8BAA8B;QAC9B,WAAW;QACX,SAAS;QACT,YAAY;QACZ,OAAO;KACR,CAAC,CAAA;AACJ,CAAC","sourcesContent":["import * as React from 'react'\nimport { mfaService } from '../apps'\nimport useLoadDataEffect from './useLoadDataEffect'\nimport { MiscTypes } from '@oneblink/types'\n\ntype MfaState = {\n isExternalIdentityProviderUser: boolean\n isLoading: boolean\n isMfaEnabled: boolean\n mfaSettings: mfaService.MfaSettings\n isSetupSuccessOpen: boolean\n loadingError?: Error\n isSettingUpMfa: boolean\n settingUpMfaMethod?: mfaService.MfaMethod\n isSetupMethodDialogOpen: boolean\n disablingMfaMethod?: mfaService.MfaMethod\n isSettingPreferredMfaMethod: boolean\n setupError?: Error\n mfaAuthenticatorAppSetup?: Awaited<\n ReturnType<typeof mfaService.setupMfaAuthenticatorApp>\n >\n isPhoneNumberDialogOpen: boolean\n phoneVerificationCodeSentAt?: number\n isRemovePhoneNumberDialogOpen: boolean\n}\n\nexport const MfaContext = React.createContext<\n MfaState & {\n authenticatorAppDisplayName?: string\n beginMfaSetup: (mfaMethod: mfaService.MfaMethod) => Promise<void>\n openMfaSetupMethodDialog: () => void\n closeMfaSetupMethodDialog: () => void\n beginDisablingMfaMethod: (mfaMethod: mfaService.MfaMethod) => void\n setPreferredMfaMethod: (mfaMethod: mfaService.MfaMethod) => Promise<void>\n openPhoneNumberDialog: () => void\n closePhoneNumberDialog: () => void\n savePhoneNumber: (phoneNumber: string) => Promise<void>\n verifyPhoneNumber: (code: string) => Promise<void>\n beginRemovingPhoneNumber: () => void\n cancelRemovingPhoneNumber: () => void\n completeRemovingPhoneNumber: () => Promise<void>\n hideSetupSuccess: () => void\n cancelMfaAuthenticatorAppSetup: () => void\n completeMfaAuthenticatorAppSetup: () => Promise<void>\n cancelDisablingMfa: () => void\n completeDisablingMfa: () => Promise<void>\n clearMfaSetupError: () => void\n loadMfa: () => void\n }\n>({\n isExternalIdentityProviderUser: false,\n isLoading: true,\n isMfaEnabled: false,\n mfaSettings: mfaService.DEFAULT_MFA_SETTINGS,\n isSetupSuccessOpen: false,\n isSettingUpMfa: false,\n isSetupMethodDialogOpen: false,\n isSettingPreferredMfaMethod: false,\n isPhoneNumberDialogOpen: false,\n isRemovePhoneNumberDialogOpen: false,\n authenticatorAppDisplayName: undefined,\n beginMfaSetup: async () => {},\n openMfaSetupMethodDialog: () => {},\n closeMfaSetupMethodDialog: () => {},\n beginDisablingMfaMethod: () => {},\n setPreferredMfaMethod: async () => {},\n openPhoneNumberDialog: () => {},\n closePhoneNumberDialog: () => {},\n savePhoneNumber: async () => {},\n verifyPhoneNumber: async () => {},\n beginRemovingPhoneNumber: () => {},\n cancelRemovingPhoneNumber: () => {},\n completeRemovingPhoneNumber: async () => {},\n hideSetupSuccess: () => {},\n cancelMfaAuthenticatorAppSetup: () => {},\n completeMfaAuthenticatorAppSetup: async () => {},\n cancelDisablingMfa: () => {},\n completeDisablingMfa: async () => {},\n clearMfaSetupError: () => {},\n loadMfa: () => {},\n})\n\nfunction getIsMfaEnabled(mfaSettings: mfaService.MfaSettings) {\n return mfaSettings.authenticator.enabled || mfaSettings.sms.enabled\n}\n\nfunction hasPreferredMfaMethod(mfaSettings: mfaService.MfaSettings) {\n return (\n (mfaSettings.authenticator.enabled &&\n mfaSettings.authenticator.preferred) ||\n (mfaSettings.sms.enabled && mfaSettings.sms.preferred)\n )\n}\n\nfunction enableSmsMfaInSettings(\n mfaSettings: mfaService.MfaSettings,\n smsPreferred: boolean,\n): mfaService.MfaSettings {\n return {\n ...mfaSettings,\n sms: {\n ...mfaSettings.sms,\n enabled: true,\n preferred: smsPreferred,\n },\n }\n}\n\nfunction enableAuthenticatorMfaInSettings(\n mfaSettings: mfaService.MfaSettings,\n authenticatorPreferred: boolean,\n): mfaService.MfaSettings {\n return {\n ...mfaSettings,\n authenticator: {\n enabled: true,\n preferred: authenticatorPreferred,\n },\n sms: {\n ...mfaSettings.sms,\n preferred: authenticatorPreferred ? false : mfaSettings.sms.preferred,\n },\n }\n}\n\nfunction setPreferredMfaMethodInSettings(\n mfaSettings: mfaService.MfaSettings,\n mfaMethod: mfaService.MfaMethod,\n): mfaService.MfaSettings {\n return {\n ...mfaSettings,\n authenticator: {\n ...mfaSettings.authenticator,\n preferred: mfaMethod === 'authenticator',\n },\n sms: {\n ...mfaSettings.sms,\n preferred: mfaMethod === 'sms',\n },\n }\n}\n\n/**\n * React Component that provides the context for the\n * `useUserMeetsMfaRequirement()` hook and `<MultiFactorAuthentication />`\n * component, to be used by components further down your component tree. **It\n * should only be included in your component tree once and ideally at the root\n * of the application.**\n *\n * #### Example\n *\n * ```js\n * import * as React from 'react'\n * import {\n * MfaProvider,\n * useUserMeetsMfaRequirement,\n * } from '@oneblink/apps-react'\n *\n * function Component({ teamMemberMfaRequirement }) {\n * const { mfaSetupRequired, isLoading, loadingError, refreshMfa } =\n * useUserMeetsMfaRequirement(teamMemberMfaRequirement)\n *\n * if (isLoading) {\n * return <Loading />\n * }\n *\n * if (loadingError) {\n * return <Error onRetry={refreshMfa} />\n * }\n *\n * if (mfaSetupRequired) {\n * return <ConfigureMfa />\n * }\n *\n * return <Application />\n * }\n *\n * function App({ teamMemberMfaRequirement }) {\n * return (\n * <MfaProvider isExternalIdentityProviderUser={false}>\n * <Component teamMemberMfaRequirement={teamMemberMfaRequirement} />\n * </MfaProvider>\n * )\n * }\n *\n * const root = document.getElementById('root')\n * if (root) {\n * ReactDOM.render(<App teamMemberMfaRequirement={mfaRequirement} />, root)\n * }\n * ```\n *\n * @param props\n * @returns\n * @group Components\n */\nexport function MfaProvider({\n children,\n isExternalIdentityProviderUser,\n authenticatorAppDisplayName,\n}: {\n children: React.ReactNode\n isExternalIdentityProviderUser: boolean\n /**\n * Name shown in authenticator apps when a user sets up an authenticator.\n * When omitted, the product name is used. Console sign-in omits this so it\n * continues to show the product name.\n */\n authenticatorAppDisplayName?: string\n}) {\n const [state, setState] = React.useState<MfaState>({\n isExternalIdentityProviderUser,\n isLoading: !isExternalIdentityProviderUser,\n isMfaEnabled: false,\n mfaSettings: mfaService.DEFAULT_MFA_SETTINGS,\n isSetupSuccessOpen: false,\n isSettingUpMfa: false,\n isSetupMethodDialogOpen: false,\n isSettingPreferredMfaMethod: false,\n isPhoneNumberDialogOpen: false,\n isRemovePhoneNumberDialogOpen: false,\n })\n\n const handleLoadMfa = React.useCallback(\n async (abortSignal: AbortSignal) => {\n if (isExternalIdentityProviderUser) {\n return\n }\n\n setState((currentState) => ({\n ...currentState,\n isLoading: true,\n isMfaEnabled: false,\n mfaSettings: mfaService.DEFAULT_MFA_SETTINGS,\n loadingError: undefined,\n }))\n try {\n const mfaSettings = await mfaService.getMfaSettings(abortSignal)\n if (!abortSignal.aborted) {\n setState((currentState) => ({\n ...currentState,\n isLoading: false,\n mfaSettings,\n isMfaEnabled: getIsMfaEnabled(mfaSettings),\n }))\n }\n } catch (error) {\n if (abortSignal.aborted) {\n return\n }\n\n setState((currentState) => ({\n ...currentState,\n isLoading: false,\n loadingError: error as Error,\n }))\n }\n },\n [isExternalIdentityProviderUser],\n )\n\n const loadMfa = useLoadDataEffect(handleLoadMfa)\n\n const clearMfaSetupError = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n setupError: undefined,\n }))\n }, [])\n\n const openMfaSetupMethodDialog = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isSetupMethodDialogOpen: true,\n }))\n }, [])\n\n const closeMfaSetupMethodDialog = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isSetupMethodDialogOpen: false,\n }))\n }, [])\n\n const hideSetupSuccess = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isSetupSuccessOpen: false,\n }))\n }, [])\n\n const cancelMfaAuthenticatorAppSetup = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n mfaAuthenticatorAppSetup: undefined,\n settingUpMfaMethod: undefined,\n }))\n }, [])\n\n const completeMfaAuthenticatorAppSetup = React.useCallback(async () => {\n setState((currentState) => {\n const authenticatorPreferred = !hasPreferredMfaMethod(\n currentState.mfaSettings,\n )\n const mfaSettings = enableAuthenticatorMfaInSettings(\n currentState.mfaSettings,\n authenticatorPreferred,\n )\n\n return {\n ...currentState,\n isSetupSuccessOpen: true,\n isMfaEnabled: getIsMfaEnabled(mfaSettings),\n mfaSettings,\n mfaAuthenticatorAppSetup: undefined,\n settingUpMfaMethod: undefined,\n }\n })\n }, [])\n\n const openPhoneNumberDialog = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isPhoneNumberDialogOpen: true,\n phoneVerificationCodeSentAt: undefined,\n setupError: undefined,\n }))\n }, [])\n\n const closePhoneNumberDialog = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isPhoneNumberDialogOpen: false,\n phoneVerificationCodeSentAt: undefined,\n }))\n }, [])\n\n const setupSmsMfaMethod = React.useCallback(async () => {\n let smsPreferred = false\n\n setState((currentState) => {\n smsPreferred = !hasPreferredMfaMethod(currentState.mfaSettings)\n return currentState\n })\n\n await mfaService.setupSmsMfa({\n preferred: smsPreferred,\n })\n\n setState((currentState) => {\n const mfaSettings = enableSmsMfaInSettings(\n currentState.mfaSettings,\n smsPreferred,\n )\n\n return {\n ...currentState,\n isSetupSuccessOpen: true,\n isSettingUpMfa: false,\n settingUpMfaMethod: undefined,\n isMfaEnabled: getIsMfaEnabled(mfaSettings),\n mfaSettings,\n }\n })\n }, [])\n\n const savePhoneNumber = React.useCallback(\n async (phoneNumber: string) => {\n setState((currentState) => ({\n ...currentState,\n setupError: undefined,\n }))\n\n try {\n const { isPhoneNumberVerified } =\n await mfaService.updateUserPhoneNumber(phoneNumber)\n\n if (!isPhoneNumberVerified) {\n setState((currentState) => ({\n ...currentState,\n phoneVerificationCodeSentAt: Date.now(),\n mfaSettings: {\n ...currentState.mfaSettings,\n sms: {\n ...currentState.mfaSettings.sms,\n phoneNumber,\n isPhoneNumberVerified: false,\n },\n },\n }))\n return\n }\n setState((currentState) => ({\n ...currentState,\n mfaSettings: {\n ...currentState.mfaSettings,\n sms: {\n ...currentState.mfaSettings.sms,\n phoneNumber,\n isPhoneNumberVerified,\n },\n },\n isPhoneNumberDialogOpen: false,\n phoneVerificationCodeSentAt: undefined,\n }))\n await setupSmsMfaMethod()\n } catch (error) {\n setState((currentState) => ({\n ...currentState,\n setupError: error as Error,\n }))\n }\n },\n [setupSmsMfaMethod],\n )\n\n const verifyPhoneNumber = React.useCallback(\n async (code: string) => {\n setState((currentState) => ({\n ...currentState,\n setupError: undefined,\n }))\n\n try {\n await mfaService.verifyUserPhoneNumber(code)\n\n setState((currentState) => ({\n ...currentState,\n mfaSettings: {\n ...currentState.mfaSettings,\n sms: {\n ...currentState.mfaSettings.sms,\n isPhoneNumberVerified: true,\n },\n },\n isPhoneNumberDialogOpen: false,\n phoneVerificationCodeSentAt: undefined,\n }))\n await setupSmsMfaMethod()\n } catch (error) {\n setState((currentState) => ({\n ...currentState,\n setupError: error as Error,\n }))\n }\n },\n [setupSmsMfaMethod],\n )\n\n const beginRemovingPhoneNumber = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isRemovePhoneNumberDialogOpen: true,\n setupError: undefined,\n }))\n }, [])\n\n const cancelRemovingPhoneNumber = React.useCallback(() => {\n setState((currentState) => ({\n ...currentState,\n isRemovePhoneNumberDialogOpen: false,\n }))\n }, [])\n\n const completeRemovingPhoneNumber = React.useCallback(async () => {\n setState((currentState) => ({\n ...currentState,\n setupError: undefined,\n }))\n\n try {\n await mfaService.removeUserPhoneNumber()\n setState((currentState) => ({\n ...currentState,\n isRemovePhoneNumberDialogOpen: false,\n mfaSettings: {\n ...currentState.mfaSettings,\n sms: {\n ...currentState.mfaSettings.sms,\n phoneNumber: undefined,\n isPhoneNumberVerified: false,\n },\n },\n }))\n } catch (error) {\n setState((currentState) => ({\n ...currentState,\n setupError: error as Error,\n }))\n }\n }, [])\n\n const beginMfaSetup = React.useCallback(\n async (mfaMethod: mfaService.MfaMethod) => {\n setState((currentState) => ({\n ...currentState,\n isSettingUpMfa: true,\n settingUpMfaMethod: mfaMethod,\n mfaAuthenticatorAppSetup: undefined,\n setupError: undefined,\n }))\n\n try {\n let mfaSettings = mfaService.DEFAULT_MFA_SETTINGS\n\n setState((currentState) => {\n mfaSettings = currentState.mfaSettings\n return currentState\n })\n\n if (mfaMethod === 'sms') {\n if (\n !mfaSettings.sms.phoneNumber ||\n !mfaSettings.sms.isPhoneNumberVerified\n ) {\n setState((currentState) => ({\n ...currentState,\n isSettingUpMfa: false,\n settingUpMfaMethod: undefined,\n isSetupMethodDialogOpen: false,\n isPhoneNumberDialogOpen: true,\n }))\n return\n }\n\n await setupSmsMfaMethod()\n setState((currentState) => ({\n ...currentState,\n isSetupMethodDialogOpen: false,\n }))\n return\n }\n\n const hasPreferredMethod = hasPreferredMfaMethod(mfaSettings)\n const newMfaAuthenticatorAppSetup =\n await mfaService.setupMfaAuthenticatorApp({\n preferred: !hasPreferredMethod,\n })\n setState((currentState) => ({\n ...currentState,\n isSettingUpMfa: false,\n isSetupMethodDialogOpen: false,\n mfaAuthenticatorAppSetup: newMfaAuthenticatorAppSetup,\n }))\n } catch (error) {\n setState((currentState) => ({\n ...currentState,\n isSettingUpMfa: false,\n settingUpMfaMethod: undefined,\n setupError: error as Error,\n }))\n }\n },\n [setupSmsMfaMethod],\n )\n\n const disablingMfaMethodRef = React.useRef<mfaService.MfaMethod | undefined>(\n undefined,\n )\n\n const beginDisablingMfaMethod = React.useCallback(\n (mfaMethod: mfaService.MfaMethod) => {\n disablingMfaMethodRef.current = mfaMethod\n setState((currentState) => ({\n ...currentState,\n disablingMfaMethod: mfaMethod,\n }))\n },\n [],\n )\n\n const cancelDisablingMfa = React.useCallback(() => {\n disablingMfaMethodRef.current = undefined\n setState((currentState) => ({\n ...currentState,\n disablingMfaMethod: undefined,\n }))\n }, [])\n\n const completeDisablingMfa = React.useCallback(async () => {\n const disablingMfaMethod = disablingMfaMethodRef.current\n if (!disablingMfaMethod) {\n return\n }\n\n await mfaService.disableMfaMethod(disablingMfaMethod)\n const mfaSettings = await mfaService.getMfaSettings()\n disablingMfaMethodRef.current = undefined\n setState((currentState) => ({\n ...currentState,\n disablingMfaMethod: undefined,\n mfaSettings,\n isMfaEnabled: getIsMfaEnabled(mfaSettings),\n }))\n }, [])\n\n const setPreferredMfaMethod = React.useCallback(\n async (mfaMethod: mfaService.MfaMethod) => {\n setState((currentState) => ({\n ...currentState,\n isSettingPreferredMfaMethod: true,\n setupError: undefined,\n }))\n\n try {\n await mfaService.setPreferredMfaMethod(mfaMethod)\n setState((currentState) => ({\n ...currentState,\n isSettingPreferredMfaMethod: false,\n mfaSettings: setPreferredMfaMethodInSettings(\n currentState.mfaSettings,\n mfaMethod,\n ),\n }))\n } catch (error) {\n setState((currentState) => ({\n ...currentState,\n isSettingPreferredMfaMethod: false,\n setupError: error as Error,\n }))\n }\n },\n [],\n )\n\n const value = React.useMemo(() => {\n return {\n ...state,\n authenticatorAppDisplayName,\n clearMfaSetupError,\n loadMfa,\n beginMfaSetup,\n openMfaSetupMethodDialog,\n closeMfaSetupMethodDialog,\n beginDisablingMfaMethod,\n setPreferredMfaMethod,\n openPhoneNumberDialog,\n closePhoneNumberDialog,\n savePhoneNumber,\n verifyPhoneNumber,\n beginRemovingPhoneNumber,\n cancelRemovingPhoneNumber,\n completeRemovingPhoneNumber,\n hideSetupSuccess,\n cancelMfaAuthenticatorAppSetup,\n completeMfaAuthenticatorAppSetup,\n cancelDisablingMfa,\n completeDisablingMfa,\n }\n }, [\n state,\n clearMfaSetupError,\n loadMfa,\n beginMfaSetup,\n openMfaSetupMethodDialog,\n closeMfaSetupMethodDialog,\n beginDisablingMfaMethod,\n setPreferredMfaMethod,\n openPhoneNumberDialog,\n closePhoneNumberDialog,\n savePhoneNumber,\n verifyPhoneNumber,\n beginRemovingPhoneNumber,\n cancelRemovingPhoneNumber,\n completeRemovingPhoneNumber,\n hideSetupSuccess,\n cancelMfaAuthenticatorAppSetup,\n completeMfaAuthenticatorAppSetup,\n cancelDisablingMfa,\n completeDisablingMfa,\n authenticatorAppDisplayName,\n ])\n\n return <MfaContext.Provider value={value}>{children}</MfaContext.Provider>\n}\n\nexport default function useMfa() {\n return React.useContext(MfaContext)\n}\n\n/**\n * React hook to determine whether the logged in user must set up MFA before\n * accessing your application. Reads MFA settings from the `<MfaProvider />`\n * context. Will throw an Error if used outside of `<MfaProvider />`.\n *\n * Users signed in via an external identity provider are not required to set up\n * MFA.\n *\n * #### Example\n *\n * ```js\n * import { MfaProvider, useUserMeetsMfaRequirement } from '@oneblink/apps-react'\n *\n * function Component({ teamMemberMfaRequirement }) {\n * const { mfaSetupRequired, isLoading, loadingError, refreshMfa } =\n * useUserMeetsMfaRequirement(teamMemberMfaRequirement)\n *\n * if (isLoading) {\n * return <Loading />\n * }\n *\n * if (loadingError) {\n * return <Error onRetry={refreshMfa} />\n * }\n *\n * if (mfaSetupRequired) {\n * return <ConfigureMfa />\n * }\n *\n * return <Application />\n * }\n * ```\n *\n * @param mfaRequirement - The MFA requirement to enforce, e.g. from your\n * organisation or app settings.\n * @returns Whether MFA setup is required, along with loading state from the MFA\n * provider.\n * @group Hooks\n */\nexport function useUserMeetsMfaRequirement(\n mfaRequirement: MiscTypes.MfaRequirement | undefined,\n) {\n const {\n isLoading,\n loadingError,\n mfaSettings,\n loadMfa,\n isExternalIdentityProviderUser,\n } = useMfa()\n\n return React.useMemo(() => {\n const mfaRequired = mfaService.isMfaRequired(mfaRequirement)\n const shouldCheckMfa = mfaRequired && !isExternalIdentityProviderUser\n const meetsRequirement = mfaService.userMeetsMfaRequirement(\n mfaRequirement,\n mfaSettings,\n )\n const mfaSetupRequired =\n shouldCheckMfa && !isLoading && !loadingError && !meetsRequirement\n\n return {\n mfaSetupRequired,\n isLoading: shouldCheckMfa && isLoading,\n loadingError: shouldCheckMfa ? loadingError : undefined,\n refreshMfa: loadMfa,\n }\n }, [\n mfaRequirement,\n isExternalIdentityProviderUser,\n mfaSettings,\n isLoading,\n loadingError,\n loadMfa,\n ])\n}\n"]}
@@ -9,7 +9,9 @@ export default function useSignUp({ formsAppId, username, firstName, lastName, o
9
9
  const usernameValidation = React.useMemo(() => {
10
10
  // regex source: https://www.w3resource.com/javascript/form/email-validation.php#:~:text=To%20get%20a%20valid%20email,%5D%2B)*%24%2F.
11
11
  return {
12
- isInvalid: !username.match(/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),
12
+ isInvalid: !username.match(
13
+ // eslint-disable-next-line security/detect-unsafe-regex -- the "." separator prevents catastrophic backtracking in the repeated group
14
+ /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/),
13
15
  };
14
16
  }, [username]);
15
17
  const [{ isSigningUp, signUpError, signUpComplete }, setSignUpState] = React.useState({
@@ -1 +1 @@
1
- {"version":3,"file":"useSignUp.js","sourceRoot":"","sources":["../../src/hooks/useSignUp.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAE7C;;;;GAIG;AACH,MAAM,CAAC,OAAO,UAAU,SAAS,CAAC,E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C,CAAA;YAEF,cAAc,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;gBAChC,GAAG,YAAY;gBACf,WAAW,EAAE,KAAK;gBAClB,cAAc,EAAE,IAAI;aACrB,CAAC,CAAC,CAAA;YACH,SAAS,aAAT,SAAS,uBAAT,SAAS,EAAI,CAAA;QACf,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,MAAM,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAA;YAC9B,cAAc,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;gBAChC,GAAG,YAAY;gBACf,WAAW,EAAE,KAAK;gBAClB,WAAW,EAAE,KAAc;aAC5B,CAAC,CAAC,CAAA;YACH,OAAO,aAAP,OAAO,uBAAP,OAAO,EAAI,CAAA;QACb,CAAC;IACH,CAAC,EAAE;QACD,SAAS;QACT,UAAU;QACV,QAAQ;QACR,OAAO;QACP,SAAS;QACT,QAAQ;QACR,kBAAkB,CAAC,SAAS;KAC7B,CAAC,CAAA;IAEF,OAAO;QACL,qBAAqB;QACrB,gBAAgB;QAChB,WAAW;QACX,WAAW;QACX,cAAc;QACd,kBAAkB;KACnB,CAAA;AACH,CAAC","sourcesContent":["import * as React from 'react'\nimport { authService, Sentry } from '../apps'\n\n/**\n * @param options\n * @returns\n * @group Hooks\n */\nexport default function useSignUp({\n formsAppId,\n username,\n firstName,\n lastName,\n onSuccess,\n onError,\n}: {\n formsAppId: number\n username: string\n firstName?: string\n lastName?: string\n onSuccess?: () => void\n onError?: () => void\n}) {\n const usernameValidation = React.useMemo(() => {\n // regex source: https://www.w3resource.com/javascript/form/email-validation.php#:~:text=To%20get%20a%20valid%20email,%5D%2B)*%24%2F.\n return {\n isInvalid: !username.match(\n /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$/,\n ),\n }\n }, [username])\n\n const [{ isSigningUp, signUpError, signUpComplete }, setSignUpState] =\n React.useState<{\n isSigningUp: boolean\n signUpError: Error | null\n signUpComplete: boolean\n }>({\n isSigningUp: false,\n signUpError: null,\n signUpComplete: false,\n })\n\n const clearSignUpError = React.useCallback(\n () =>\n setSignUpState((current) => ({\n ...current,\n signUpError: null,\n })),\n [],\n )\n\n const signUpWithUserDetails = React.useCallback(async () => {\n if (usernameValidation.isInvalid) {\n setSignUpState((current) => ({\n ...current,\n signUpError: new Error('Please enter a valid email address'),\n }))\n return\n }\n\n setSignUpState((currentState) => ({\n ...currentState,\n isSigningUp: true,\n signUpError: null,\n }))\n\n try {\n await authService.signUp({\n formsAppId,\n email: username,\n firstName,\n lastName,\n })\n\n setSignUpState((currentState) => ({\n ...currentState,\n isSigningUp: false,\n signUpComplete: true,\n }))\n onSuccess?.()\n } catch (error) {\n Sentry.captureException(error)\n setSignUpState((currentState) => ({\n ...currentState,\n isSigningUp: false,\n signUpError: error as Error,\n }))\n onError?.()\n }\n }, [\n firstName,\n formsAppId,\n lastName,\n onError,\n onSuccess,\n username,\n usernameValidation.isInvalid,\n ])\n\n return {\n signUpWithUserDetails,\n clearSignUpError,\n isSigningUp,\n signUpError,\n signUpComplete,\n usernameValidation,\n }\n}\n"]}
1
+ {"version":3,"file":"useSignUp.js","sourceRoot":"","sources":["../../src/hooks/useSignUp.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,KAAK,MAAM,OAAO,CAAA;AAC9B,OAAO,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAE7C;;;;GAIG;AACH,MAAM,CAAC,OAAO,UAAU,SAAS,CAAC,EAChC,UAAU,EACV,QAAQ,EACR,SAAS,EACT,QAAQ,EACR,SAAS,EACT,OAAO,GAQR;IACC,MAAM,kBAAkB,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE;QAC5C,qIAAqI;QACrI,OAAO;YACL,SAAS,EAAE,CAAC,QAAQ,CAAC,KAAK;YACxB,sIAAsI;YACtI,sEAAsE,CACvE;SACF,CAAA;I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,CAAC;YACf,MAAM,CAAC,gBAAgB,CAAC,KAAK,CAAC,CAAA;YAC9B,cAAc,CAAC,CAAC,YAAY,EAAE,EAAE,CAAC,CAAC;gBAChC,GAAG,YAAY;gBACf,WAAW,EAAE,KAAK;gBAClB,WAAW,EAAE,KAAc;aAC5B,CAAC,CAAC,CAAA;YACH,OAAO,aAAP,OAAO,uBAAP,OAAO,EAAI,CAAA;QACb,CAAC;IACH,CAAC,EAAE;QACD,SAAS;QACT,UAAU;QACV,QAAQ;QACR,OAAO;QACP,SAAS;QACT,QAAQ;QACR,kBAAkB,CAAC,SAAS;KAC7B,CAAC,CAAA;IAEF,OAAO;QACL,qBAAqB;QACrB,gBAAgB;QAChB,WAAW;QACX,WAAW;QACX,cAAc;QACd,kBAAkB;KACnB,CAAA;AACH,CAAC","sourcesContent":["import * as React from 'react'\nimport { authService, Sentry } from '../apps'\n\n/**\n * @param options\n * @returns\n * @group Hooks\n */\nexport default function useSignUp({\n formsAppId,\n username,\n firstName,\n lastName,\n onSuccess,\n onError,\n}: {\n formsAppId: number\n username: string\n firstName?: string\n lastName?: string\n onSuccess?: () => void\n onError?: () => void\n}) {\n const usernameValidation = React.useMemo(() => {\n // regex source: https://www.w3resource.com/javascript/form/email-validation.php#:~:text=To%20get%20a%20valid%20email,%5D%2B)*%24%2F.\n return {\n isInvalid: !username.match(\n // eslint-disable-next-line security/detect-unsafe-regex -- the \".\" separator prevents catastrophic backtracking in the repeated group\n /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$/,\n ),\n }\n }, [username])\n\n const [{ isSigningUp, signUpError, signUpComplete }, setSignUpState] =\n React.useState<{\n isSigningUp: boolean\n signUpError: Error | null\n signUpComplete: boolean\n }>({\n isSigningUp: false,\n signUpError: null,\n signUpComplete: false,\n })\n\n const clearSignUpError = React.useCallback(\n () =>\n setSignUpState((current) => ({\n ...current,\n signUpError: null,\n })),\n [],\n )\n\n const signUpWithUserDetails = React.useCallback(async () => {\n if (usernameValidation.isInvalid) {\n setSignUpState((current) => ({\n ...current,\n signUpError: new Error('Please enter a valid email address'),\n }))\n return\n }\n\n setSignUpState((currentState) => ({\n ...currentState,\n isSigningUp: true,\n signUpError: null,\n }))\n\n try {\n await authService.signUp({\n formsAppId,\n email: username,\n firstName,\n lastName,\n })\n\n setSignUpState((currentState) => ({\n ...currentState,\n isSigningUp: false,\n signUpComplete: true,\n }))\n onSuccess?.()\n } catch (error) {\n Sentry.captureException(error)\n setSignUpState((currentState) => ({\n ...currentState,\n isSigningUp: false,\n signUpError: error as Error,\n }))\n onError?.()\n }\n }, [\n firstName,\n formsAppId,\n lastName,\n onError,\n onSuccess,\n username,\n usernameValidation.isInvalid,\n ])\n\n return {\n signUpWithUserDetails,\n clearSignUpError,\n isSigningUp,\n signUpError,\n signUpComplete,\n usernameValidation,\n }\n}\n"]}
@@ -302,6 +302,7 @@ export const validators = {
302
302
  }
303
303
  let pattern = options.pattern;
304
304
  if (isString(pattern)) {
305
+ // eslint-disable-next-line security/detect-non-literal-regexp -- pattern is configured on the form definition
305
306
  pattern = new RegExp(options.pattern, options.flags);
306
307
  }
307
308
  const match = pattern.exec(value);
@@ -1 +1 @@
1
- {"version":3,"file":"validate-dot-js.js","sourceRoot":"","sources":["../../../src/services/form-validation/validate-dot-js.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,cAAc,MAAM,iBAAiB,CAAA;AAEjD,MAAM,mBAAmB,GAAG,OAAO,CAAA;AACnC,MAAM,aAAa,GAAG,mBAAmB,CAAA;AAEzC;;;;;;GAMG;AACH,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;AACnD,CAAC;AAED;;;;;GAKG;AACH,SAAS,UAAU,CAAC,KAAc;IAChC,OAAO,OAAO,KAAK,KAAK,UAAU,CAAA;AACpC,CAAC;AAED;;;;;;G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,GAAG,CAAA,OAAO,aAAP,OAAO,uBAAP,OAAO,CAAE,OAAO,KAAI,sBAAsB,CAAA;QAC1D,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YACrB,OAAO,CAAC,OAAO,CAAC,CAAA;QAClB,CAAC;QACD,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YACpC,OAAO,CAAC,OAAO,CAAC,CAAA;QAClB,CAAC;QAED,OAAO,EAAE,CAAA;IACX,CAAC;CACF,CAAA","sourcesContent":["import * as EmailValidator from 'email-validator'\n\nconst EMPTY_STRING_REGEXP = /^\\s*$/\nconst FORMAT_REGEXP = /(%?)%\\{([^}]+)\\}/g\n\n/**\n * Checks if the value is a number. This function does not consider NaN a number\n * like many other `isNumber` functions do.\n *\n * @param value\n * @returns\n */\nfunction isNumber(value: unknown): value is number {\n return typeof value === 'number' && !isNaN(value)\n}\n\n/**\n * Returns false if the object is not a function\n *\n * @param value\n * @returns\n */\nfunction isFunction(value: unknown) {\n return typeof value === 'function'\n}\n\n/**\n * A simple check to verify that the value is an integer. Uses `isNumber` and a\n * simple modulo check.\n *\n * @param value\n * @returns\n */\nfunction isInteger(value: unknown): value is number {\n return isNumber(value) && value % 1 === 0\n}\n\n/**\n * Uses the `Object` function to check if the given argument is an object.\n *\n * @param obj\n * @returns\n */\nfunction isObject(obj: unknown): obj is object {\n return obj === Object(obj)\n}\n\n/**\n * Simply checks if the object is an instance of a date\n *\n * @param obj\n * @returns\n */\nfunction isDate(obj: unknown): obj is Date {\n return obj instanceof Date\n}\n\n/**\n * Returns false if the object is `null` of `undefined`\n *\n * @param obj\n * @returns\n */\nfunction isDefined(obj: unknown) {\n return obj !== null && obj !== undefined\n}\n\nexport function isEmpty(value: unknown) {\n // Null and undefined are empty\n if (!isDefined(value)) {\n return true\n }\n\n // functions are non empty\n if (isFunction(value)) {\n return false\n }\n\n // Whitespace only strings are empty\n if (isString(value)) {\n return EMPTY_STRING_REGEXP.test(value)\n }\n\n // For arrays we use the length property\n if (isArray(value)) {\n return value.length === 0\n }\n\n // Dates have no attributes but aren't empty\n if (isDate(value)) {\n return false\n }\n\n // If we find at least one property we consider it non empty\n if (isObject(value)) {\n for (const _attr in value) {\n return false\n }\n return true\n }\n\n return false\n}\n\n/**\n * Formats the specified strings with the given values like so:\n *\n * format('Foo: %{foo}', { foo: 'bar' }) // \"Foo bar\"\n *\n * If you want to write %{...} without having it replaced simply prefix it with\n * % like this `Foo: %%{foo}` and it will be returned as `\"Foo: %{foo}\"`\n *\n * @param str\n * @param vals\n * @returns\n */\nfunction formatValidationMessage(\n str: string,\n vals: Record<string, unknown>,\n): string {\n if (!isString(str)) {\n return str\n }\n return str.replace(FORMAT_REGEXP, function (m0, m1, m2) {\n if (m1 === '%') {\n return '%{' + m2 + '}'\n } else {\n return String(vals[m2])\n }\n })\n}\n\nfunction isString(value: unknown) {\n return typeof value === 'string'\n}\n\nfunction isArray(value: unknown) {\n return Array.isArray(value)\n}\n\nexport const validators = {\n /**\n * Presence validates that the value isn't empty\n *\n * @param value\n * @param options\n * @returns\n */\n presence(\n value: unknown,\n options?: { allowEmpty?: boolean; message?: string },\n ): string[] {\n if (options?.allowEmpty ? !isDefined(value) : isEmpty(value)) {\n return [options?.message || \"can't be blank\"]\n }\n\n return []\n },\n\n length(\n value: unknown,\n options?: {\n message?: string\n is?: number\n minimum?: number\n maximum?: number\n tooShort?: string\n tooLong?: string\n wrongLength?: string\n },\n ): string[] {\n // Empty values are allowed\n if (!isDefined(value)) {\n return []\n }\n\n const length = (value as { length?: unknown } | string | Array<unknown>)\n ?.length\n const { message, is, minimum, maximum, tooShort, tooLong, wrongLength } =\n options || {}\n\n if (!isNumber(length)) {\n return [message || 'has an incorrect length']\n }\n\n // Is checks\n if (isNumber(is) && length !== is) {\n const err =\n message ||\n wrongLength ||\n 'is the wrong length (should be %{count} characters)'\n return [formatValidationMessage(err, { count: is })]\n }\n\n const errors: string[] = []\n if (isNumber(minimum) && length < minimum) {\n const err = tooShort || 'is too short (minimum is %{count} characters)'\n errors.push(formatValidationMessage(err, { count: minimum }))\n }\n\n if (isNumber(maximum) && length > maximum) {\n const err = tooLong || 'is too long (maximum is %{count} characters)'\n errors.push(formatValidationMessage(err, { count: maximum }))\n }\n\n if (errors.length > 0) {\n return message ? [message] : errors\n }\n\n return []\n },\n numericality(\n value: unknown,\n options?: {\n message?: string\n notValid?: string\n onlyInteger?: boolean\n notInteger?: string\n greaterThan?: number\n notGreaterThan?: string\n greaterThanOrEqualTo?: number\n notGreaterThanOrEqualTo?: string\n lessThanOrEqualTo?: number\n notLessThanOrEqualTo?: string\n equalTo?: number\n notEqualTo?: string\n lessThan?: number\n notLessThan?: string\n divisibleBy?: number\n notDivisibleBy?: string\n odd?: boolean\n notOdd?: string\n even?: boolean\n notEven?: string\n },\n ): string[] {\n // Empty values are fine\n if (!isDefined(value)) {\n return []\n }\n\n // If it's not a number we shouldn't continue since it will compare it.\n if (!isNumber(value)) {\n return [options?.message || options?.notValid || 'is not a number']\n }\n\n // Same logic as above, sort of. Don't bother with comparisons if this\n // doesn't pass.\n if (options?.onlyInteger && !isInteger(value)) {\n return [options?.message || options?.notInteger || 'must be an integer']\n }\n\n const checks = [\n {\n name: 'greater than',\n message: options?.notGreaterThan,\n predicateValue: options?.greaterThan,\n predicate(predicateValue: number) {\n return value > predicateValue\n },\n },\n {\n name: 'greater than or equal to',\n message: options?.notGreaterThanOrEqualTo,\n predicateValue: options?.greaterThanOrEqualTo,\n predicate(predicateValue: number) {\n return value >= predicateValue\n },\n },\n {\n name: 'equal to',\n message: options?.notEqualTo,\n predicateValue: options?.equalTo,\n predicate(predicateValue: number) {\n return value === predicateValue\n },\n },\n {\n name: 'less than',\n message: options?.notLessThan,\n predicateValue: options?.lessThan,\n predicate(predicateValue: number) {\n return value < predicateValue\n },\n },\n {\n name: 'less than or equal to',\n message: options?.notLessThanOrEqualTo,\n predicateValue: options?.lessThanOrEqualTo,\n predicate(predicateValue: number) {\n return value <= predicateValue\n },\n },\n {\n name: 'divisible by',\n message: options?.notDivisibleBy,\n predicateValue: options?.divisibleBy,\n predicate(predicateValue: number) {\n return value % predicateValue === 0\n },\n },\n ]\n\n const errors: string[] = []\n\n for (const check of checks) {\n if (\n isNumber(check.predicateValue) &&\n !check.predicate(check.predicateValue)\n ) {\n // This picks the default message if specified\n // For example the greaterThan check uses the message from\n // this.notGreaterThan so we capitalize the name and prepend \"not\"\n const msg = check.message || 'must be %{type} %{count}'\n\n errors.push(\n formatValidationMessage(msg, {\n count: check.predicateValue,\n type: check.name,\n }),\n )\n }\n }\n\n if (options?.odd && value % 2 !== 1) {\n errors.push(options.notOdd || 'must be odd')\n }\n if (options?.even && value % 2 !== 0) {\n errors.push(options.notEven || 'must be even')\n }\n\n if (errors.length) {\n return options?.message ? [options.message] : errors\n }\n\n return []\n },\n\n datetime(\n value: unknown,\n {\n format,\n ...options\n }: {\n format: (date: Date) => string\n earliest?: string\n latest?: string\n tooEarly?: string\n tooLate?: string\n dateOnly?: boolean\n notValid?: string\n message?: string\n },\n ): string[] {\n // Empty values are fine\n if (!isDefined(value)) {\n return []\n }\n\n let num = value\n if (isString(value)) {\n num = Date.parse(value)\n }\n\n // 86400000 is the number of milliseconds in a day, this is used to remove\n // the time from the date\n if (\n !isNumber(num) ||\n isNaN(num) ||\n (options.dateOnly && num % 86400000 !== 0)\n ) {\n const err = options.notValid || options.message || 'must be a valid date'\n return [formatValidationMessage(err, { value })]\n }\n\n const errors = []\n\n const earliest = options.earliest ? Date.parse(options.earliest) : NaN\n if (!isNaN(earliest) && num < earliest) {\n const err =\n options.tooEarly || options.message || 'must be no earlier than %{date}'\n errors.push(\n formatValidationMessage(err, {\n value: format(new Date(num)),\n date: format(new Date(earliest)),\n }),\n )\n }\n\n const latest = options.latest ? Date.parse(options.latest) : NaN\n if (!isNaN(latest) && num > latest) {\n const err =\n options.tooLate || options.message || 'must be no later than %{date}'\n errors.push(\n formatValidationMessage(err, {\n date: format(new Date(latest)),\n value: format(new Date(num)),\n }),\n )\n }\n\n return errors\n },\n\n regexValidation(\n value: unknown,\n options:\n | {\n pattern: RegExp | string\n message?: string\n flags?: string\n }\n | RegExp\n | string,\n ): string[] {\n if (isString(options) || options instanceof RegExp) {\n options = { pattern: options }\n }\n\n const message = options.message || 'is invalid'\n\n // Empty values are allowed\n if (!isDefined(value)) {\n return []\n }\n if (!isString(value)) {\n return [message]\n }\n\n let pattern = options.pattern\n if (isString(pattern)) {\n pattern = new RegExp(options.pattern, options.flags)\n }\n const match = pattern.exec(value)\n if (!match || match[0].length != value.length) {\n return [message]\n }\n\n return []\n },\n\n email(value: unknown, options?: { message?: string }): string[] {\n // Empty values are fine\n if (!isDefined(value)) {\n return []\n }\n\n const message = options?.message || 'is not a valid email'\n if (!isString(value)) {\n return [message]\n }\n if (!EmailValidator.validate(value)) {\n return [message]\n }\n\n return []\n },\n}\n"]}
1
+ {"version":3,"file":"validate-dot-js.js","sourceRoot":"","sources":["../../../src/services/form-validation/validate-dot-js.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,cAAc,MAAM,iBAAiB,CAAA;AAEjD,MAAM,mBAAmB,GAAG,OAAO,CAAA;AACnC,MAAM,aAAa,GAAG,mBAAmB,CAAA;AAEzC;;;;;;GAMG;AACH,SAAS,QAAQ,CAAC,KAAc;IAC9B,OAAO,OAAO,KAAK,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;AACnD,CAAC;AAED;;;;;GAKG;AACH,SAAS,UAAU,CAAC,KAAc;IAChC,OAAO,OAAO,KAAK,KAAK,UAAU,CAAA;AACpC,CAAC;AAED;;;;;;GAMG;AACH,SAAS,SAAS,CAAC,KAAc;IAC/B,OAAO,QAAQ,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,KAAK,CAAC,CAAA;AAC3C,CAAC;AAED;;;;;GAKG;AACH,SAAS,QAAQ,CAAC,GAAY;IAC5B,OAAO,GAAG,KAAK,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ACD,IAAI,CAAC,cAAc,CAAC,QAAQ,CAAC,KAAK,CAAC,EAAE,CAAC;YACpC,OAAO,CAAC,OAAO,CAAC,CAAA;QAClB,CAAC;QAED,OAAO,EAAE,CAAA;IACX,CAAC;CACF,CAAA","sourcesContent":["import * as EmailValidator from 'email-validator'\n\nconst EMPTY_STRING_REGEXP = /^\\s*$/\nconst FORMAT_REGEXP = /(%?)%\\{([^}]+)\\}/g\n\n/**\n * Checks if the value is a number. This function does not consider NaN a number\n * like many other `isNumber` functions do.\n *\n * @param value\n * @returns\n */\nfunction isNumber(value: unknown): value is number {\n return typeof value === 'number' && !isNaN(value)\n}\n\n/**\n * Returns false if the object is not a function\n *\n * @param value\n * @returns\n */\nfunction isFunction(value: unknown) {\n return typeof value === 'function'\n}\n\n/**\n * A simple check to verify that the value is an integer. Uses `isNumber` and a\n * simple modulo check.\n *\n * @param value\n * @returns\n */\nfunction isInteger(value: unknown): value is number {\n return isNumber(value) && value % 1 === 0\n}\n\n/**\n * Uses the `Object` function to check if the given argument is an object.\n *\n * @param obj\n * @returns\n */\nfunction isObject(obj: unknown): obj is object {\n return obj === Object(obj)\n}\n\n/**\n * Simply checks if the object is an instance of a date\n *\n * @param obj\n * @returns\n */\nfunction isDate(obj: unknown): obj is Date {\n return obj instanceof Date\n}\n\n/**\n * Returns false if the object is `null` of `undefined`\n *\n * @param obj\n * @returns\n */\nfunction isDefined(obj: unknown) {\n return obj !== null && obj !== undefined\n}\n\nexport function isEmpty(value: unknown) {\n // Null and undefined are empty\n if (!isDefined(value)) {\n return true\n }\n\n // functions are non empty\n if (isFunction(value)) {\n return false\n }\n\n // Whitespace only strings are empty\n if (isString(value)) {\n return EMPTY_STRING_REGEXP.test(value)\n }\n\n // For arrays we use the length property\n if (isArray(value)) {\n return value.length === 0\n }\n\n // Dates have no attributes but aren't empty\n if (isDate(value)) {\n return false\n }\n\n // If we find at least one property we consider it non empty\n if (isObject(value)) {\n for (const _attr in value) {\n return false\n }\n return true\n }\n\n return false\n}\n\n/**\n * Formats the specified strings with the given values like so:\n *\n * format('Foo: %{foo}', { foo: 'bar' }) // \"Foo bar\"\n *\n * If you want to write %{...} without having it replaced simply prefix it with\n * % like this `Foo: %%{foo}` and it will be returned as `\"Foo: %{foo}\"`\n *\n * @param str\n * @param vals\n * @returns\n */\nfunction formatValidationMessage(\n str: string,\n vals: Record<string, unknown>,\n): string {\n if (!isString(str)) {\n return str\n }\n return str.replace(FORMAT_REGEXP, function (m0, m1, m2) {\n if (m1 === '%') {\n return '%{' + m2 + '}'\n } else {\n return String(vals[m2])\n }\n })\n}\n\nfunction isString(value: unknown) {\n return typeof value === 'string'\n}\n\nfunction isArray(value: unknown) {\n return Array.isArray(value)\n}\n\nexport const validators = {\n /**\n * Presence validates that the value isn't empty\n *\n * @param value\n * @param options\n * @returns\n */\n presence(\n value: unknown,\n options?: { allowEmpty?: boolean; message?: string },\n ): string[] {\n if (options?.allowEmpty ? !isDefined(value) : isEmpty(value)) {\n return [options?.message || \"can't be blank\"]\n }\n\n return []\n },\n\n length(\n value: unknown,\n options?: {\n message?: string\n is?: number\n minimum?: number\n maximum?: number\n tooShort?: string\n tooLong?: string\n wrongLength?: string\n },\n ): string[] {\n // Empty values are allowed\n if (!isDefined(value)) {\n return []\n }\n\n const length = (value as { length?: unknown } | string | Array<unknown>)\n ?.length\n const { message, is, minimum, maximum, tooShort, tooLong, wrongLength } =\n options || {}\n\n if (!isNumber(length)) {\n return [message || 'has an incorrect length']\n }\n\n // Is checks\n if (isNumber(is) && length !== is) {\n const err =\n message ||\n wrongLength ||\n 'is the wrong length (should be %{count} characters)'\n return [formatValidationMessage(err, { count: is })]\n }\n\n const errors: string[] = []\n if (isNumber(minimum) && length < minimum) {\n const err = tooShort || 'is too short (minimum is %{count} characters)'\n errors.push(formatValidationMessage(err, { count: minimum }))\n }\n\n if (isNumber(maximum) && length > maximum) {\n const err = tooLong || 'is too long (maximum is %{count} characters)'\n errors.push(formatValidationMessage(err, { count: maximum }))\n }\n\n if (errors.length > 0) {\n return message ? [message] : errors\n }\n\n return []\n },\n numericality(\n value: unknown,\n options?: {\n message?: string\n notValid?: string\n onlyInteger?: boolean\n notInteger?: string\n greaterThan?: number\n notGreaterThan?: string\n greaterThanOrEqualTo?: number\n notGreaterThanOrEqualTo?: string\n lessThanOrEqualTo?: number\n notLessThanOrEqualTo?: string\n equalTo?: number\n notEqualTo?: string\n lessThan?: number\n notLessThan?: string\n divisibleBy?: number\n notDivisibleBy?: string\n odd?: boolean\n notOdd?: string\n even?: boolean\n notEven?: string\n },\n ): string[] {\n // Empty values are fine\n if (!isDefined(value)) {\n return []\n }\n\n // If it's not a number we shouldn't continue since it will compare it.\n if (!isNumber(value)) {\n return [options?.message || options?.notValid || 'is not a number']\n }\n\n // Same logic as above, sort of. Don't bother with comparisons if this\n // doesn't pass.\n if (options?.onlyInteger && !isInteger(value)) {\n return [options?.message || options?.notInteger || 'must be an integer']\n }\n\n const checks = [\n {\n name: 'greater than',\n message: options?.notGreaterThan,\n predicateValue: options?.greaterThan,\n predicate(predicateValue: number) {\n return value > predicateValue\n },\n },\n {\n name: 'greater than or equal to',\n message: options?.notGreaterThanOrEqualTo,\n predicateValue: options?.greaterThanOrEqualTo,\n predicate(predicateValue: number) {\n return value >= predicateValue\n },\n },\n {\n name: 'equal to',\n message: options?.notEqualTo,\n predicateValue: options?.equalTo,\n predicate(predicateValue: number) {\n return value === predicateValue\n },\n },\n {\n name: 'less than',\n message: options?.notLessThan,\n predicateValue: options?.lessThan,\n predicate(predicateValue: number) {\n return value < predicateValue\n },\n },\n {\n name: 'less than or equal to',\n message: options?.notLessThanOrEqualTo,\n predicateValue: options?.lessThanOrEqualTo,\n predicate(predicateValue: number) {\n return value <= predicateValue\n },\n },\n {\n name: 'divisible by',\n message: options?.notDivisibleBy,\n predicateValue: options?.divisibleBy,\n predicate(predicateValue: number) {\n return value % predicateValue === 0\n },\n },\n ]\n\n const errors: string[] = []\n\n for (const check of checks) {\n if (\n isNumber(check.predicateValue) &&\n !check.predicate(check.predicateValue)\n ) {\n // This picks the default message if specified\n // For example the greaterThan check uses the message from\n // this.notGreaterThan so we capitalize the name and prepend \"not\"\n const msg = check.message || 'must be %{type} %{count}'\n\n errors.push(\n formatValidationMessage(msg, {\n count: check.predicateValue,\n type: check.name,\n }),\n )\n }\n }\n\n if (options?.odd && value % 2 !== 1) {\n errors.push(options.notOdd || 'must be odd')\n }\n if (options?.even && value % 2 !== 0) {\n errors.push(options.notEven || 'must be even')\n }\n\n if (errors.length) {\n return options?.message ? [options.message] : errors\n }\n\n return []\n },\n\n datetime(\n value: unknown,\n {\n format,\n ...options\n }: {\n format: (date: Date) => string\n earliest?: string\n latest?: string\n tooEarly?: string\n tooLate?: string\n dateOnly?: boolean\n notValid?: string\n message?: string\n },\n ): string[] {\n // Empty values are fine\n if (!isDefined(value)) {\n return []\n }\n\n let num = value\n if (isString(value)) {\n num = Date.parse(value)\n }\n\n // 86400000 is the number of milliseconds in a day, this is used to remove\n // the time from the date\n if (\n !isNumber(num) ||\n isNaN(num) ||\n (options.dateOnly && num % 86400000 !== 0)\n ) {\n const err = options.notValid || options.message || 'must be a valid date'\n return [formatValidationMessage(err, { value })]\n }\n\n const errors = []\n\n const earliest = options.earliest ? Date.parse(options.earliest) : NaN\n if (!isNaN(earliest) && num < earliest) {\n const err =\n options.tooEarly || options.message || 'must be no earlier than %{date}'\n errors.push(\n formatValidationMessage(err, {\n value: format(new Date(num)),\n date: format(new Date(earliest)),\n }),\n )\n }\n\n const latest = options.latest ? Date.parse(options.latest) : NaN\n if (!isNaN(latest) && num > latest) {\n const err =\n options.tooLate || options.message || 'must be no later than %{date}'\n errors.push(\n formatValidationMessage(err, {\n date: format(new Date(latest)),\n value: format(new Date(num)),\n }),\n )\n }\n\n return errors\n },\n\n regexValidation(\n value: unknown,\n options:\n | {\n pattern: RegExp | string\n message?: string\n flags?: string\n }\n | RegExp\n | string,\n ): string[] {\n if (isString(options) || options instanceof RegExp) {\n options = { pattern: options }\n }\n\n const message = options.message || 'is invalid'\n\n // Empty values are allowed\n if (!isDefined(value)) {\n return []\n }\n if (!isString(value)) {\n return [message]\n }\n\n let pattern = options.pattern\n if (isString(pattern)) {\n // eslint-disable-next-line security/detect-non-literal-regexp -- pattern is configured on the form definition\n pattern = new RegExp(options.pattern, options.flags)\n }\n const match = pattern.exec(value)\n if (!match || match[0].length != value.length) {\n return [message]\n }\n\n return []\n },\n\n email(value: unknown, options?: { message?: string }): string[] {\n // Empty values are fine\n if (!isDefined(value)) {\n return []\n }\n\n const message = options?.message || 'is not a valid email'\n if (!isString(value)) {\n return [message]\n }\n if (!EmailValidator.validate(value)) {\n return [message]\n }\n\n return []\n },\n}\n"]}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@oneblink/apps-react",
3
3
  "description": "Helper functions for OneBlink apps in ReactJS.",
4
- "version": "13.5.1-beta.1",
4
+ "version": "13.5.1-beta.3",
5
5
  "author": "OneBlink <developers@oneblink.io> (https://oneblink.io)",
6
6
  "bugs": {
7
7
  "url": "https://github.com/oneblink/apps-react/issues"
@@ -12,7 +12,7 @@
12
12
  "@emotion/react": "^11.14.0",
13
13
  "@emotion/styled": "^11.14.1",
14
14
  "@nylas/react": "^3.1.2",
15
- "@oneblink/sdk-core": "^10.2.0-beta.1",
15
+ "@oneblink/sdk-core": "^10.2.1-beta.1",
16
16
  "@oneblink/storage": "^9.0.0-beta.4",
17
17
  "@react-google-maps/api": "^2.20.8",
18
18
  "@react-input/mask": "^2.0.4",
@@ -55,7 +55,6 @@
55
55
  "@eslint/compat": "^2.0.2",
56
56
  "@eslint/eslintrc": "^3.3.3",
57
57
  "@eslint/js": "^9.39.2",
58
- "@microsoft/eslint-plugin-sdl": "^1.1.0",
59
58
  "@mui/material": "^7.3.7",
60
59
  "@mui/x-date-pickers": "^8.27.0",
61
60
  "@oneblink/release-cli": "^5.2.2",
@@ -82,7 +81,9 @@
82
81
  "eslint": "^9.39.2",
83
82
  "eslint-config-prettier": "^10.1.8",
84
83
  "eslint-plugin-prettier": "^5.5.5",
84
+ "eslint-plugin-react": "^7.37.5",
85
85
  "eslint-plugin-react-hooks": "^7.0.1",
86
+ "eslint-plugin-security": "^4.2.1",
86
87
  "fixpack": "^4.0.0",
87
88
  "globals": "^17.3.0",
88
89
  "jsdom": "^28.0.0",