App icon indicating copy to clipboard operation
App copied to clipboard

[$175] [Sentry: APP-P53] NotAllowedError: Failed to execute 'writeText' on 'Clipboard' (unhandled rejection)

Open melvin-bot[bot] opened this issue 2 weeks ago • 24 comments

Sentry

https://expensify.sentry.io/issues/APP-P53

Impact

  • 1 user, 1 event since first seen: 2026-11-12 17:41 UTC
  • Platform: web, Edge on Windows, standalone
  • Release: 9.5.36
  • Route: /workspaces/:policyID/connections/two-factor-auth
  • View: Dynamic_Settings_TwoFactorAuth_Root
  • Mechanism: unhandled rejection (onunhandledrejection)

Error

NotAllowedError: Failed to execute 'writeText' on 'Clipboard': Document is not focused.

Top first-party frames

src/libs/Clipboard/index.ts:139 — setString
DynamicTwoFactorAuthPage.tsx:165 — onPress
PressableWithDelayToggle.tsx:107 — updatePressState

Root cause

The browser legitimately rejects clipboard writes when the document is unfocused. Our clipboard wrapper delegates to a dependency that neither returns nor catches the navigator.clipboard.writeText() Promise, allowing the rejection to escape unhandled.

The 2FA handler also marks recovery codes as copied and announces “Copied” without confirming the write succeeded.

Suggested fix

Handle clipboard write failures centrally and expose success/failure to callers. Only mark recovery codes as copied and announce success after a successful write; otherwise allow retry without claiming success.

A synchronous try/catch around the existing wrapper will not catch this asynchronous rejection.

Add tests verifying rejected clipboard writes are handled and do not trigger success feedback.

Existing issues

No matching tracking issue found in Expensify/App or Expensify/Expensify. App#93837 discusses clipboard rejection in comments but tracks a different error.

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @FitseTLT

melvin-bot[bot] avatar Nov 13 '26 18:11 melvin-bot[bot]

Triggered auto assignment to Contributor-plus team member for initial proposal review - @FitseTLT (External)

melvin-bot[bot] avatar Nov 13 '26 18:11 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022121304566909824244

melvin-bot[bot] avatar Nov 13 '26 18:11 melvin-bot[bot]

Proposal

What is the root cause of that problem?

  1. Unhandled Asynchronous Promise in Clipboard.setString and Clipboard.setHtml:

    • In src/libs/Clipboard/index.ts:138-140:
      const setString: SetString = (text) => {
          Clipboard.setString(text);
      };
      
      setString delegates to @react-native-clipboard/clipboard's web implementation, which calls navigator.clipboard.writeText(text) without awaiting, catching, or returning the promise.
    • When the document is unfocused (or clipboard permission is refused by the browser), navigator.clipboard.writeText(text) rejects with a NotAllowedError. Because there is no .catch() handler attached to the promise and the wrapper does not return the promise to the caller, the rejection escapes as an unhandled promise rejection (window.onunhandledrejection), causing the Sentry error.
    • Similarly, in src/libs/Clipboard/index.ts:125-131, setHtml calls navigator.clipboard.write([...]) without a .catch() handler, allowing the same NotAllowedError to escape unhandled.
  2. Premature Success Feedback in DynamicTwoFactorAuthPage & PressableWithDelayToggle:

What changes do you think we should make in order to solve the problem?

  1. Centralize Clipboard Write Error Handling & Return Status in src/libs/Clipboard/index.ts:

    • In src/libs/Clipboard/types.ts, update SetString and SetHtml to return Promise<boolean>.
    • In src/libs/Clipboard/index.ts:
      • In setString, use async/await around navigator.clipboard.writeText(text):
        • If navigator?.clipboard?.writeText succeeds, return true.
        • If navigator.clipboard.writeText rejects (e.g. NotAllowedError), catch the error, log a warning with Log.warn, and attempt the existing fallback setHTMLSync('', text) (using document.execCommand('copy')). If fallback succeeds, return true; otherwise return false.
      • In setHtml, wrap navigator.clipboard.write([...]) in a try/catch: if it rejects, catch the error, log a warning, and fall back to setHTMLSync(html, text).
    • In src/libs/Clipboard/index.native.ts, wrap Clipboard.setString(text) in a try/catch and return Promise.resolve(true) on success and Promise.resolve(false) on failure.
  2. Only Announce and Mark Copied on Success in DynamicTwoFactorAuthPage.tsx:

  3. Update PressableWithDelayToggle.tsx to Respect onPress Return Value:

    • In src/components/Pressable/PressableWithDelayToggle.tsx:102-108, update updatePressState:
      • If onPress returns a Promise, await it (or chain .then(success => ...)): only call temporarilyDisableInteractions() if the result is not false.
      • If onPress returns synchronous false, do not call temporarilyDisableInteractions().
      • If onPress returns void / undefined, call temporarilyDisableInteractions() as before to maintain backward compatibility with existing synchronous buttons.
  4. Add Unit & UI Tests:

    • In tests/unit/ClipboardTest.ts:
      • Verify that when navigator.clipboard.writeText rejects with NotAllowedError, Clipboard.setString catches the error, attempts fallback, and resolves to false without triggering an unhandled rejection.
    • In tests/ui/DynamicTwoFactorAuthPageTest.tsx:
      • Add a test verifying that when Clipboard.setString fails, setCodesAreCopied is not called, and the status announcement is not triggered.

What alternative solutions did you explore? (Optional)

  • Wrapping Clipboard.setString in a synchronous try/catch inside DynamicTwoFactorAuthPage.tsx: Rejected because navigator.clipboard.writeText returns a Promise that rejects asynchronously in a later event loop tick; a synchronous try/catch will not catch the rejection.
  • Using only document.execCommand('copy') on web: Rejected because document.execCommand is deprecated and the modern asynchronous Clipboard API is the preferred web standard.

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374

kevinjosh10 avatar Nov 13 '26 18:11 kevinjosh10

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 13 '26 18:11 melvin-bot[bot]

Proposal

What is the root cause of that problem?

The code supports the issue’s diagnosis, with one additional problem: the copy button displays “Copied” before the clipboard operation succeeds.

The web clipboard dependency discards the Promise returned by navigator.clipboard.writeText(). Consequently, the browser’s focus-related rejection escapes unhandled. Meanwhile, the recovery-code handler immediately records the codes as copied and announces success.

Code evidence

Confidence: Medium. The current code explains the reported rejection and premature success feedback. The production event and release-specific behavior were not independently reproduced; why the document lost focus remains unknown.

What changes do you think we should make in order to solve the problem?

  1. Handle browser clipboard writes centrally in App, observing the actual browser Promise and returning a non-rejecting success/failure result. Merely awaiting the existing dependency is insufficient.
  2. Preserve the legacy copy fallback, checking its result and cleaning up temporary elements even on failure.
  3. Make the recovery-code control success-aware: show and announce “Copied,” and record acknowledgement, only after success. Separate pending/disabled state from successful checked state.
  4. On failure, provide retryable failure feedback without logging recovery codes. Preserve the independent Download flow and any previous successful acknowledgement.
  5. Keep existing callers compatible and explicitly account for native clipboard APIs that do not confirm completion.
Regression coverage

Test delayed success, rejected writes—including the reported focus error—synchronous exceptions, fallback failure, and successful retry. Verify there is no unhandled rejection or premature copied state, announcement, checkmark, or acknowledgement. Exercise the real pressable behavior rather than mocking away its immediate state transition.

What alternative solutions did you explore? (Optional)

  • Synchronous try/catch or awaiting the current wrapper: cannot catch a Promise already discarded by the dependency.
  • Only delaying the page’s announcement: leaves the button’s independent “Copied” feedback incorrect.
  • Forcing focus: does not address other legitimate clipboard failures.

Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106888) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.


view run

MelvinBot avatar Nov 13 '26 18:11 MelvinBot

Proposal

Please re-state the problem that we are trying to solve in this issue.

On web (such as Edge standalone on /workspaces/:policyID/connections/two-factor-auth), clicking Copy codes on the 2FA recovery codes step when the document lacks focus causes navigator.clipboard.writeText() to reject with NotAllowedError: Failed to execute 'writeText' on 'Clipboard': Document is not focused., escaping as an unhandled Promise rejection (onunhandledrejection). At the same time, both PressableWithDelayToggle and DynamicTwoFactorAuthPage unconditionally report success—displaying Copied!, announcing "Copied!" to screen readers, setting codesAreCopied: true in Onyx (unlocking the Verify step without copied codes), and throttling retries for 1800ms—even though nothing was written to the clipboard.

What is the root cause of that problem?

  1. Unhandled Promise rejection in src/libs/Clipboard/index.ts:

    • src/libs/Clipboard/index.ts:138-140 delegates setString to @react-native-clipboard/clipboard (v1.16.3), whose web implementation calls navigator.clipboard.writeText(text) without returning or .catch()ing the Promise, and only falls back to document.execCommand('copy') when navigator.clipboard itself is undefined—never when writeText() rejects due to focus or permission restrictions.
    • src/libs/Clipboard/index.ts:125-131 (setHtml) likewise invokes navigator.clipboard.write([...]) without returning or catching its Promise, and canSetHtml (lines 26-30) returns a nested closure () => (...args) => ... that is always truthy even when navigator.clipboard?.write or ClipboardItem is unavailable.
    • Existing setHTMLSync (lines 34-100) cannot be reused as-is for plain-text fallback because: (a) it appends node to document.body (line 49) before the early if (selection === null) return; (lines 53-55) and without try / finally, leaking DOM nodes containing sensitive text on early exit or selection errors; (b) it ignores the boolean return value of document.execCommand('copy') (line 81), which returns false without throwing when user activation has expired after an async rejection; and (c) it unconditionally writes e.clipboardData?.setData('text/html', html) (line 46), so passing html = '' writes an empty 'text/html' payload that pastes blank into rich-text editors.
  2. Unconditional pre-completion success UI in PressableWithDelayToggle and DynamicTwoFactorAuthPage:

    • In src/components/Pressable/PressableWithDelayToggle.tsx:102-108, updatePressState calls temporarilyDisableInteractions() before onPress?.(). Flipping isActive to false immediately switches the label to textChecked ("Copied!"), icon to Checkmark, and accessibilityLabel to checkedAccessibilityLabel (lines 110-126, 163-168) while blocking retries for 1800ms, regardless of async completion or failure.
    • In src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:208-213, onPress synchronously calls setCodesAreCopied() (which sets codesAreCopied: true and twoFactorAuthSetupInProgress: true in ONYXKEYS.ACCOUNT, satisfying TwoFactorAuthWrapper's VERIFY gate) and announceStatus(translate('common.copied')) without awaiting confirmation that the clipboard write succeeded.

What changes do you think we should make in order to solve the problem?

  1. Centralize non-rejecting clipboard writes with a leak-safe fallback in src/libs/Clipboard/:

    • In src/libs/Clipboard/types.ts, update SetString to (text: string) => Promise<boolean>, SetHtml to (html: string, text: string) => Promise<boolean>, and CanSetHtml to () => boolean.
    • In src/libs/Clipboard/index.ts:
      • Fix canSetHtml to return Boolean((navigator?.clipboard?.write && typeof ClipboardItem !== 'undefined') || Browser.getBrowser() === CONST.BROWSER.SAFARI).
      • Replace setHTMLSync with copyWithExecCommand(text: string, html?: string): boolean that checks document.body and window?.getSelection() before appending the temporary <span>, only sets 'text/html' when html !== undefined (preserving rich-text paste compatibility for plain-text fallbacks), checks both document.execCommand('copy') and copy-event clipboardData population, and restores selection + calls node.remove() inside a finally block.
      • Implement setString directly against navigator?.clipboard?.writeText(text) inside async / try / catch: return true when writeText resolves; on rejection or missing writeText, attempt copyWithExecCommand(text), log sanitized error metadata (error.name / error.message via Log.warn—never logging text, which holds 2FA recovery codes, TOTP secrets, or card CVVs) only if the fallback also fails, and resolve to boolean. Apply the same try / catch + copyWithExecCommand(text, html) fallback to setHtml.
    • In src/libs/Clipboard/index.native.ts, wrap Clipboard.setString(text) in try / catch returning Promise.resolve(true) / Promise.resolve(false) (accounting for React Native's synchronous fire-and-forget bridge) and return Promise.resolve(false) from setHtml.
  2. Decouple in-flight press protection from checked success state in PressableWithDelayToggle.tsx:

    • In src/components/Pressable/PressableWithDelayToggle.tsx, widen onPress via Omit<PressableProps, 'onPress'> to accept boolean | void | Promise<boolean | void>.
    • Track in-flight async presses with a synchronous isPendingRef (plus isPending state for styles.cursorDefault and isMountedRef for unmount safety) so neither nested PressableWithoutFeedback bubbling (lines 143, 196) nor rapid clicks can fire duplicate onPress calls while a Promise is pending, while keeping isActive === true (no premature "Copied!" text, checkmark, or checked accessibility label).
    • Call temporarilyDisableInteractions() only when onPress returns synchronously !== false or resolves to !== false; if it returns false, resolves to false, or rejects, catch internally and reset isPending immediately so the user can retry without waiting 1800ms.
    • In src/components/CopyTextToClipboard.tsx:41-43, return Clipboard.setString(urlToCopy || text || '') from copyToClipboard so it (alongside DynamicVerifyPage and TwoFactorAuthSecretDisplay) also withholds "Copied!" on failed writes.
  3. Gate recovery-code acknowledgement & surface retryable error feedback in DynamicTwoFactorAuthPage.tsx:

    • In src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:208-213, make onPress async (guarded by isMountedRef so late resolutions after quitAndNavigateBack cannot re-dirty ONYXKEYS.ACCOUNT):
      onPress={async () => {
          setError('');
          const didCopy = await Clipboard.setString(account?.recoveryCodes ?? '');
          if (!isMountedRef.current) {
              return false;
          }
          if (!didCopy) {
              setError(translate('twoFactorAuth.errorCopyCodes'));
              return false;
          }
          setCodesAreCopied();
          announceStatus(translate('common.copied'));
          return true;
      }}
      
    • On failure, setCodesAreCopied() and announceStatus(translate('common.copied')) are not called (preserving any prior codesAreCopied: true from an earlier Copy or Download without resetting it, and leaving the independent Download flow intact), while the existing <FormHelpMessage isError message={error} /> (lines 240-246) displays and assertively announces twoFactorAuth.errorCopyCodes (src/languages/*.ts).
  4. Add regression tests:

    • tests/unit/ClipboardTest.ts: test web Clipboard.setString / setHtml for resolved writes, NotAllowedError unfocused-document rejections (no unhandled rejection, DOM <span> cleaned up, secret text never logged, resolves false when fallback fails and true with 'text/plain'-only when fallback succeeds), and synchronous exceptions.
    • tests/ui/DynamicTwoFactorAuthPageTest.tsx: exercise the real PressableWithDelayToggle button (CONST.SENTRY_LABEL.TWO_FACTOR_AUTH.COPY_CODES) for pending writes (no premature "Copied!" or setCodesAreCopied), rejected writes (shows error, keeps "Copy codes" active for immediate retry, preserves pre-existing codesAreCopied), and successful retry.

What alternative solutions did you explore? (Optional)

  • Calling existing setHTMLSync('', text) as the setString fallback: Rejected because setHTMLSync writes an empty 'text/html' clipboard item that causes rich-text editors to paste blank, ignores document.execCommand('copy')'s boolean result, and can leak the temporary DOM node on early exit.
  • Delaying temporarilyDisableInteractions() in PressableWithDelayToggle without an in-flight ref guard: Rejected because isActive remains true while navigator.clipboard.writeText() is pending, allowing rapid clicks or nested pressable events to trigger concurrent onPress executions.

cocvn157 avatar Nov 14 '26 03:11 cocvn157

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~014898525b9c53fc32

Proposal

Please re-state the problem that we are trying to solve in this issue.

When copying recovery codes on Web while the document is not focused, navigator.clipboard.writeText rejects with NotAllowedError: Document is not focused. Because Clipboard.setString does not catch or return the browser Promise, an unhandled rejection Sentry error is thrown. Simultaneously, the copy button and 2FA handler immediately show "Copied!" and announce success despite the clipboard write failing.

What is the root cause of that problem?

  1. Unhandled asynchronous promise in Clipboard.setString and Clipboard.setHtml (src/libs/Clipboard/index.ts:125-140): setString delegates to @react-native-clipboard/clipboard's Web implementation, which calls navigator.clipboard.writeText(text) without returning or catching the Promise. When the document is unfocused or clipboard permissions are denied, the rejection escapes as an unhandled promise rejection (window.onunhandledrejection). Similarly, setHtml calls navigator.clipboard.write(...) without catching rejections.
  2. Premature success state in PressableWithDelayToggle.tsx:102-108: updatePressState immediately triggers temporarilyDisableInteractions(), flipping isActive to false and displaying textChecked ("Copied!") regardless of whether the clipboard operation succeeds or is still pending.
  3. Unchecked success in DynamicTwoFactorAuthPage.tsx:208-213: The onPress callback executes setCodesAreCopied() and announceStatus(translate('common.copied')) synchronously without confirming that the clipboard write succeeded.

What changes do you think we should make in order to solve the problem?

  1. Centralize clipboard error handling & return boolean success in src/libs/Clipboard/index.ts:

    • In src/libs/Clipboard/types.ts: Update SetString and SetHtml signatures to return Promise<boolean>.
    • In src/libs/Clipboard/index.ts:
      • In setString:
        • If navigator?.clipboard?.writeText is available, wrap the call in a try/catch. If it resolves, return true.
        • If it rejects (e.g. NotAllowedError), catch the error, log a warning via Log.warn, and attempt legacy fallback using document.execCommand('copy') with text/plain only (using a clean temporary <span> element cleaned up in a finally block). Return true if fallback succeeds, false otherwise. (Do not call setHTMLSync for plain text, as that creates an empty text/html item that corrupts paste in external rich text editors).
      • In setHtml: Wrap navigator.clipboard.write(...) in a try/catch. If it rejects, log a warning and fall back to setHTMLSync(html, text).
    • In src/libs/Clipboard/index.native.ts: Wrap Clipboard.setString(text) in a try/catch and return Promise.resolve(true).
  2. Make PressableWithDelayToggle.tsx async-aware and gate checked state on success:

    • Widen onPress prop to accept boolean | void | Promise<boolean | void>.
    • Introduce an isPending state / ref so that rapid clicks while a Promise is in flight are ignored without prematurely flipping to textChecked ("Copied!").
    • Call temporarilyDisableInteractions() only if onPress resolves to !== false. If it returns or resolves to false, reset isPending immediately so the user can retry without waiting the 1800ms throttle.
  3. Gate recovery codes confirmation in DynamicTwoFactorAuthPage.tsx:208-213:

    • Make onPress async.
    • const success = await Clipboard.setString(account?.recoveryCodes ?? '');
    • If !success, display setError(translate('twoFactorAuth.errorCopyCodes')) and return false.
    • Only call setCodesAreCopied() and announceStatus(translate('common.copied')) when success === true.
  4. Automated tests:

    • tests/unit/ClipboardTest.ts: Test Web Clipboard.setString resolving, rejecting with NotAllowedError (asserting no unhandled rejection and correct fallback behavior), and returning boolean.
    • tests/ui/DynamicTwoFactorAuthPageTest.tsx: Test that a rejected clipboard write keeps the button active for immediate retry, does not announce "Copied", does not set codesAreCopied, and displays the error message.

What alternative solutions did you explore? (Optional)

  • Falling back to setHTMLSync('', text) for setString: Rejected because setHTMLSync writes an empty text/html MIME type into the system pasteboard, which causes rich-text editors (Slack, Google Docs) to paste empty text.
  • Wrapping with a synchronous try/catch: Rejected because navigator.clipboard.writeText() is asynchronous and a synchronous try/catch does not intercept unhandled Promise rejections.

RajGahoi avatar Nov 14 '26 12:11 RajGahoi

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 14 '26 12:11 melvin-bot[bot]

📣 @RS-ITACHI! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 14 '26 15:11 melvin-bot[bot]

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 14 '26 15:11 melvin-bot[bot]

Proposal

What is the root cause of that problem?

The web clipboard wrapper delegates to @react-native-clipboard/clipboard. Its version 1.16.3 web setter calls navigator.clipboard.writeText() without returning or catching the promise. When the browser rejects an unfocused document's write, that rejection escapes unhandled. App's HTML copy path also discards a browser write promise.

Success feedback happens before either write completes. PressableWithDelayToggle switches to its checked state before calling the handler. The recovery-code handler immediately records the codes as copied and announces success. Both places need to wait for the result.

What changes do you think we should make in order to solve the problem?

  • Have the shared web setters observe the actual browser promise and return Promise<boolean>. Catch synchronous exceptions and asynchronous rejections centrally, including calls whose results are ignored. Make canSetHtml return a boolean capability check.
  • Reuse the existing span and copy-event fallback, checking execCommand('copy')'s result. Remove the temporary node and restore selection in finally. Preserve Safari's whitespace behavior, HTML/plain text clipboard data, mention normalization and composer selection. Plain text copies must omit an empty HTML representation. Apply the existing FullStory mask before putting clipboard contents in the temporary node.
  • Let PressableWithDelayToggle accept boolean or asynchronous results through an Omit override of onPress. A pending ref prevents duplicate and nested presses. Show checked feedback only after success; allow immediate retry after false, a throw or a rejection. Keep synchronous successful handlers immediate and handle StrictMode effect replay correctly.
  • Await copying on the recovery-code page before acknowledgement or announcement. On failure, display the existing localized error. Ignore results after unmount, blur/refocus or replacement of the recovery codes. Preserve previous successful acknowledgement and the independent Download flow.
  • Return the clipboard result from CopyTextToClipboard, and adapt the three menu callbacks whose return types otherwise become incompatible. On native, report whether the synchronous bridge call succeeded; that does not confirm later OS clipboard persistence.

Local verification passed 95 Jest tests across nine suites, followed by 39 focused tests after the privacy mask change. Seven checks passed in an actual Chrome clipboard harness, including clipboard readback, fallback cleanup and controlled denial. TypeScript, lint, React Compiler, formatting and spelling checks passed; the staged standards review reported no violations.

A controlled local before/after recording exercises the real 2FA page with test recovery codes, stubbed server responses and an injected clipboard denial. The original build acknowledges the failed copy and emits an unhandled rejection. The patched build keeps failure retryable and confirms a subsequent copy through native clipboard readback. The exact production focus-loss condition remains unconfirmed. Safari's fallback branch was exercised in Chromium; actual Safari and iOS/Android device checks remain outstanding.

What alternative solutions did you explore? (Optional)

A synchronous catch around the existing dependency cannot observe the promise it discards. Updating only the page leaves the pressable's premature checkmark and accessible success label. Forcing browser focus would still leave other legitimate clipboard denials unhandled.

https://github.com/user-attachments/assets/b621e0e8-21e9-4097-a4df-f5546860ae10

MannA-001 avatar Nov 15 '26 09:11 MannA-001

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01e25967395e54eb3f

Proposal

Please re-state the problem that we are trying to solve in this issue.

On Web (e.g., Edge on Windows at /workspaces/:policyID/connections/two-factor-auth), pressing Copy codes on the 2FA recovery codes step when the document is unfocused causes navigator.clipboard.writeText() to reject with NotAllowedError: Failed to execute 'writeText' on 'Clipboard': Document is not focused., escaping as an unhandled Promise rejection (onunhandledrejection). At the same time, the button and page immediately mark the recovery codes as copied (setCodesAreCopied()) and display/announce "Copied" even though the clipboard write failed.

What is the root cause of that problem?

  1. Unhandled Promise rejection in src/libs/Clipboard/index.ts:
    • In src/libs/Clipboard/index.ts:144-146, setString delegates directly to @react-native-clipboard/clipboard (Clipboard.setString(text)), whose web implementation invokes navigator.clipboard.writeText(text) without returning or catching the resulting Promise. When the document lacks focus, the browser rejects that Promise with NotAllowedError, escaping as an unhandled rejection.
    • Similarly, setHtml (src/libs/Clipboard/index.ts:131-137) calls navigator.clipboard.write([...]) without catching rejections.
  2. Unconditional success state in DynamicTwoFactorAuthPage.tsx (src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:207-212):
    • onPress synchronously calls Clipboard.setString(account?.recoveryCodes ?? '') and immediately runs setError(''), setCodesAreCopied(), and announceStatus(translate('common.copied')) without confirming whether the clipboard write succeeded.
  3. Premature "Copied" toggle in PressableWithDelayToggle.tsx (src/components/Pressable/PressableWithDelayToggle.tsx:101-107):
    • updatePressState calls temporarilyDisableInteractions() synchronously before onPress?.() resolves. That immediately flips isActive to false, rendering textChecked={translate('common.copied')}, the checkmark icon, and accessibilityLabelChecked—and throttling retries—even when the clipboard write fails.

What changes do you think we should make in order to solve the problem?

  1. Handle web clipboard writes centrally and return Promise<boolean> (src/libs/Clipboard/types.ts, src/libs/Clipboard/index.ts, src/libs/Clipboard/index.native.ts):

    • Update SetString in src/libs/Clipboard/types.ts to (text: string) => Promise<boolean>.
    • In src/libs/Clipboard/index.ts, implement setString using navigator.clipboard?.writeText(text) when available, catching any rejection (including NotAllowedError) and falling back to a synchronous document.execCommand('copy') helper that cleans up its temporary <textarea> in a finally block and returns true/false without ever throwing or leaving an unhandled rejection:
      function setStringSync(text: string): boolean {
          if (typeof document === 'undefined' || !document.body) {
              return false;
          }
          const node = document.createElement('textarea');
          node.value = text;
          node.setAttribute('readonly', '');
          node.style.all = 'unset';
          node.style.opacity = '0';
          node.style.position = 'absolute';
          node.style.left = '-9999px';
          document.body.appendChild(node);
          node.select();
          try {
              return document.execCommand('copy');
          } catch {
              return false;
          } finally {
              document.body.removeChild(node);
          }
      }
      
      const setString: SetString = async (text) => {
          if (typeof navigator !== 'undefined' && navigator.clipboard?.writeText) {
              try {
                  await navigator.clipboard.writeText(text);
                  return true;
              } catch {
                  return setStringSync(text);
              }
          }
          return setStringSync(text);
      };
      
    • Also attach .catch(() => setHTMLSync(html, text)) to navigator.clipboard.write(...) in setHtml (src/libs/Clipboard/index.ts:131-137) so HTML copies cannot trigger unhandled rejections when unfocused.
    • In src/libs/Clipboard/index.native.ts, return Promise.resolve(true) after Clipboard.setString(text).
  2. Make PressableWithDelayToggle respect async onPress success/failure (src/components/Pressable/PressableWithDelayToggle.tsx):

    • Allow onPress on PressableWithDelayToggleProps to return void | boolean | Promise<void | boolean>.
    • Guard in-flight async calls with an isPendingRef ref and only call temporarilyDisableInteractions() (which switches the button to the checked "Copied" state) when result !== false:
      const updatePressState = () => {
          if (!isActive || isPendingRef.current) {
              return;
          }
          const result = onPress?.();
          if (result instanceof Promise) {
              isPendingRef.current = true;
              result
                  .then((didSucceed) => {
                      if (didSucceed !== false) {
                          temporarilyDisableInteractions();
                      }
                  })
                  .catch(() => {})
                  .finally(() => {
                      isPendingRef.current = false;
                  });
              return;
          }
          if (result !== false) {
              temporarilyDisableInteractions();
          }
      };
      
  3. Gate 2FA recovery code acknowledgement and announcement on clipboard success (src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:207-212):

    • Update the Copy codes onPress handler to await Clipboard.setString(account?.recoveryCodes ?? '') and return false without calling setCodesAreCopied() or announcing "Copied" if the write fails:
      onPress={async () => {
          const didCopy = await Clipboard.setString(account?.recoveryCodes ?? '');
          if (!didCopy) {
              return false;
          }
          setError('');
          setCodesAreCopied();
          announceStatus(translate('common.copied'));
          return true;
      }}
      
  4. Add unit/UI tests:

    • Add unit tests in tests/unit/ClipboardTest.ts verifying that when navigator.clipboard.writeText rejects with NotAllowedError and fallback copy fails, Clipboard.setString resolves to false with no unhandled rejection.
    • Add UI tests in tests/ui/DynamicTwoFactorAuthPageTest.tsx verifying that a rejected clipboard write does not call setCodesAreCopied, does not announce "Copied", and does not toggle the button to "Copied", while a subsequent retry succeeds.

What alternative solutions did you explore? (Optional)

  • Wrapping Clipboard.setString in a synchronous try/catch inside DynamicTwoFactorAuthPage: Rejected because navigator.clipboard.writeText rejects asynchronously on a microtask; synchronous try/catch cannot catch it, and @react-native-clipboard/clipboard discards the underlying Promise.
  • Only updating DynamicTwoFactorAuthPage without updating PressableWithDelayToggle: Rejected because PressableWithDelayToggle toggles its own label and accessibility state to "Copied" before onPress completes.

U-ITACHII avatar Nov 15 '26 10:11 U-ITACHII

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 15 '26 10:11 melvin-bot[bot]

Proposal

Proposal

Please re-state the problem that we are trying to solve in this issue.

On Web (e.g. Edge/Chrome on Windows at /workspaces/:policyID/connections/two-factor-auth), clicking Copy codes when the document is not focused causes navigator.clipboard.writeText() to asynchronously reject with NotAllowedError: Failed to execute 'writeText' on 'Clipboard': Document is not focused..

Because the clipboard wrapper does not catch or return the Promise from writeText, this rejection escapes into the microtask queue and triggers window.onunhandledrejection (Sentry APP-P53). Additionally, the UI prematurely announces "Copied" and marks recovery codes as copied even if the clipboard write failed.

What is the root cause of that problem?

  1. Unhandled Asynchronous Promise in Clipboard.setString and Clipboard.setHtml: In src/libs/Clipboard/index.ts:138-140:

    const setString: SetString = (text) => {
        Clipboard.setString(text);
    };
    

    Our web wrapper delegates to @react-native-clipboard/clipboard. On web, @react-native-clipboard/clipboard calls navigator.clipboard.writeText(text) but neither returns the Promise nor attaches a .catch() handler. When the browser rejects the operation (e.g. Document is not focused, permission denied, or cross-origin iframe restriction), the floating Promise rejects in the microtask queue, which any synchronous try/catch wrapper in caller code cannot catch.

    Similarly, in setHtml (lines 125–132), navigator.clipboard.write([...]) returns a Promise without a .catch(), leaving another unhandled rejection path.

  2. Premature Success Feedback in PressableWithDelayToggle and DynamicTwoFactorAuthPage: In src/components/Pressable/PressableWithDelayToggle.tsx:102-108:

    const updatePressState = () => {
        if (!isActive) {
            return;
        }
        temporarilyDisableInteractions();
        onPress?.();
    };
    

    temporarilyDisableInteractions() is invoked immediately upon click, prematurely flipping the button to "Copied" and displaying the checkmark icon regardless of whether the underlying write succeeded.

    In src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:146-151:

    onPress={() => {
        Clipboard.setString(account?.recoveryCodes ?? '');
        setError('');
        setCodesAreCopied();
        announceStatus(translate('common.copied'));
    }}
    

    The 2FA screen synchronously clears errors, marks codes as copied (setCodesAreCopied()), and triggers screen reader announcement without awaiting clipboard confirmation.

What changes do you think we should make in order to solve the problem?

  1. Centralize Clipboard Write Error Handling and Return a Promise<boolean>:

    • In src/libs/Clipboard/types.ts:
      type SetString = (text: string) => Promise<boolean>;
      type SetHtml = (html: string, text: string) => Promise<boolean>;
      
    • In src/libs/Clipboard/index.ts: Directly handle navigator.clipboard.writeText with try / catch and add a fallback to document.execCommand('copy') (matching the existing setHTMLSync approach already used in this file for Safari):
      function copyTextSync(text: string): boolean {
          const node = document.createElement('textarea');
          node.value = text;
          node.style.all = 'unset';
          node.style.position = 'fixed';
          node.style.opacity = '0';
          document.body.appendChild(node);
          node.focus();
          node.select();
          try {
              return document.execCommand('copy');
          } catch {
              return false;
          } finally {
              document.body.removeChild(node);
          }
      }
      
      const setString: SetString = async (text: string): Promise<boolean> => {
          if (navigator?.clipboard?.writeText) {
              try {
                  await navigator.clipboard.writeText(text);
                  return true;
              } catch (error) {
                  Log.warn('[Clipboard] Failed to write text via navigator.clipboard.writeText, attempting sync fallback', {error});
                  return copyTextSync(text);
              }
          }
          return copyTextSync(text);
      };
      
      In setHtml (lines 125–132), catch rejection on navigator.clipboard.write and fall back to setHTMLSync:
      try {
          await navigator.clipboard.write([
              new ClipboardItem({
                  /* eslint-disable @typescript-eslint/naming-convention */
                  'text/html': new Blob([htmlNonClosingTags], {type: 'text/html'}),
                  'text/plain': new Blob([text], {type: 'text/plain'}),
              }),
          ]);
          return true;
      } catch (error) {
          Log.warn('[Clipboard] Failed to write HTML via navigator.clipboard.write, falling back to sync copy', {error});
          setHTMLSync(html, text);
          return true;
      }
      
    • In src/libs/Clipboard/index.native.ts: Update setString to return Promise.resolve(true):
      const setString: SetString = (text) => {
          Clipboard.setString(text);
          return Promise.resolve(true);
      };
      
  2. Make PressableWithDelayToggle Await onPress Before Switching to "Copied": In src/components/Pressable/PressableWithDelayToggle.tsx: Allow onPress to return Promise<boolean | void> | void. In updatePressState:

    const updatePressState = async () => {
        if (!isActive) {
            return;
        }
        const result = onPress?.();
        if (result instanceof Promise) {
            const success = await result;
            if (success === false) {
                return;
            }
        }
        temporarilyDisableInteractions();
    };
    

    Benefit: Existing callers returning void continue to work with zero breaking changes. Callers that return a Promise can signal failure by resolving false, which leaves the button active and immediately clickable for retry.

  3. Gate 2FA Success State on Clipboard Confirmation: In src/pages/settings/Security/TwoFactorAuth/DynamicTwoFactorAuthPage.tsx:146-151:

    onPress={async () => {
        const success = await Clipboard.setString(account?.recoveryCodes ?? '');
        if (!success) {
            return false;
        }
        setError('');
        setCodesAreCopied();
        announceStatus(translate('common.copied'));
        return true;
    }}
    

What alternative solutions did you explore? (Optional)

  • Synchronous try/catch wrapping Clipboard.setString at caller sites: Rejected because navigator.clipboard.writeText rejects asynchronously in the microtask queue; a synchronous try/catch block does not intercept the rejection.
  • window.addEventListener('unhandledrejection') global suppression: Rejected because masking unhandled rejections globally hides legitimate errors and does not provide proper retry UX to users.

Test Plan

  1. Unit tests (tests/unit/libs/ClipboardTest.ts):
    • Verify Clipboard.setString succeeds and returns true when navigator.clipboard.writeText resolves.
    • Mock navigator.clipboard.writeText rejecting with new DOMException('Document is not focused.', 'NotAllowedError'):
      • Verify no unhandled promise rejection is thrown.
      • Verify fallback to copyTextSync is executed.
      • Verify Clipboard.setString returns false if copyTextSync also fails.
    • Verify Clipboard.setHtml handles rejection from navigator.clipboard.write and falls back to setHTMLSync.
  2. Component & Integration tests:
    • In PressableWithDelayToggle, verify that an onPress returning Promise.resolve(false) does not enter the disabled/checked state and keeps the button interactive.
    • In DynamicTwoFactorAuthPage, simulate a failed clipboard write: verify setCodesAreCopied is not called, "Copied" announcement is not made, and the button does not display "Copied".
    • Simulate a successful write: verify setCodesAreCopied is called, "Copied" announcement is made, and the button displays "Copied" with the checkmark.

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0105126232377c4c5c

ayolyn avatar Nov 15 '26 22:11 ayolyn

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 15 '26 22:11 melvin-bot[bot]

@FitseTLT can you please review the proposals?

mountiny avatar Nov 16 '26 03:11 mountiny

Proposal

What is the root cause of that problem?

On web, Clipboard.setString hands the text to @react-native-clipboard/clipboard (L135-L140). The package's web setString calls navigator.clipboard.writeText() and drops the promise (v1.16.3 L22-L33), so when the browser refuses the write, nothing handles it. This started with #29119, which moved web setString from react-native-web's synchronous execCommand copy to this package.

The 2FA page then marks the codes as copied and announces "Copied" without knowing the result (L203-L213). PressableWithDelayToggle also switches to "Copied!" before it calls onPress (L102-L108).

I reproduced the exact error on staging 9.5.39-2 (Chromium, 1440px and 390px). The event came from the Xero connect flow on Connections; I opened the same Dynamic_Settings_TwoFactorAuth_Root screen from Settings > Security, because Connections isn't available on my test workspace.

  • With the window unfocused (document.hasFocus() is false), a click event on Copy codes gives an unhandled NotAllowedError: Failed to execute 'writeText' on 'Clipboard': Document is not focused. The button still shows "Copied!", account.codesAreCopied becomes true, and the clipboard keeps its old content.
  • A real pointer click focuses the document first, so it copies normally (the clipboard then holds the codes). The event needs a click that reaches the button while the window isn't focused, such as an assistive-tech or scripted click. A retry with a normal click works.

What changes do you think we should make in order to solve the problem?

  1. Web setString: call navigator.clipboard.writeText() ourselves and return Promise<boolean>. It resolves true on success. On rejection it logs with Log.hmmm (without the text) and resolves false, so it never rejects, like handleSearchError in Search.ts. Browsers without the async API keep the package call. Native resolves true.
  2. DynamicTwoFactorAuthPage: call setCodesAreCopied() and announce "Copied" only when it resolves true, and return the result.
  3. PressableWithDelayToggle: when onPress returns a promise, switch to the checked state only if it resolves true; everything else works as today. ContextMenuItem already notes this idea (L94). On failure the button stays "Copy codes", so the user can click again.
  4. Once setString returns a promise, no-misused-promises flags the 3 ContextMenuItem callers that return it from a one-line arrow (Share code, workspace share, referral; checked with lint). They get a block body, with no behaviour change.

I don't add an execCommand fallback (most of the earlier proposals do). On staging, with the document unfocused, every fallback I tried returned false and left the clipboard unchanged: setHTMLSync('', text), a span holding the text, and the package's textarea. With focus, setHTMLSync('', text) returns true but copies nothing, because the span is empty and the copy event never reaches its listener. So a fallback can't copy here, and it could report a false success.

Tests: ClipboardWebTest runs the package's real web code with writeText rejecting with the measured error, and DynamicTwoFactorAuthPageTest gets two cases.

  • On main, 3 fail, and jest reports the same "Document is not focused." rejection.
  • With the change, both pass (14/14), and all 11 clipboard/copy suites pass (92/92).
  • Lint and oxfmt are clean.

What alternative solutions did you explore? (Optional)

  • Patching the package to return the promise: our wrapper would still need to handle it, so doing it in the wrapper is smaller.
  • setHtml (clipboard.write) has the same pattern. Draft #106742 already adds a catch there that falls back to setString; with this change, that fallback resolves false instead of raising this same error. If #106742 doesn't land first, I can give setHtml the same handling.

vulinh1704 avatar Nov 16 '26 04:11 vulinh1704

@FitseTLT can you please review the proposals?

Okay

FitseTLT avatar Nov 16 '26 13:11 FitseTLT

@MelvinBot draft the pr

FitseTLT avatar Nov 17 '26 15:11 FitseTLT

🤖 Web test steps verification results: ❌ fail

Blocked on dev NewDot web: the existing session displays a blank page. No recovery-code behavior could be verified.

Blank app page preventing recovery-code verification
Step Status
Recovery-code Copy success, failure/retry, and pending-write behaviorBoth snapshots returned zero nodes. Browser verification was blocked; no product regression was established.
Blank app page preventing recovery-code verification
❌

Created draft PR: Handle clipboard failures before acknowledging recovery codes, assigned to FitseTLT.

48 focused tests passed, alongside lint and typechecking. Full-suite, Storybook, and tooling limitations are documented in the draft.


view run · no recording available

MelvinBot avatar Nov 17 '26 16:11 MelvinBot