Skip to content

🔒 Remove deprecated document.execCommand from useCopyToClipboard - #520

Open
is0692vs wants to merge 1 commit into
mainfrom
security/remove-exec-command-17996083711857532255
Open

🔒 Remove deprecated document.execCommand from useCopyToClipboard#520
is0692vs wants to merge 1 commit into
mainfrom
security/remove-exec-command-17996083711857532255

Conversation

@is0692vs

@is0692vs is0692vs commented Aug 1, 2026

Copy link
Copy Markdown
Contributor

🎯 What: The useCopyToClipboard hook previously included a fallback mechanism using document.execCommand("copy") for older browsers that do not support the modern navigator.clipboard API. This fallback has been completely removed. The hook now exclusively relies on navigator.clipboard.writeText.

⚠️ Risk: The document.execCommand API is deprecated and known to have security implications and inconsistencies across different browsers. Retaining this deprecated API could introduce potential vulnerabilities or unhandled edge cases, especially since it requires manipulating hidden DOM elements (<textarea>) which could be exploited or cause styling/layout issues.

🛡️ Solution: Removed the document.execCommand fallback logic and the associated DOM manipulation from useCopyToClipboard.ts. The hook now safely catches errors if navigator.clipboard.writeText fails or if the API is entirely unavailable, logging the error securely without triggering any legacy copy operations. The corresponding test suites (useCopyToClipboard.test.ts and ShareButtons.test.tsx) have been updated to reflect the new behavior and remove all document.execCommand mocks.


PR created automatically by Jules for task 17996083711857532255 started by @is0692vs

Greptile Summary

useCopyToClipboard から非推奨の document.execCommand("copy") と一時的な DOM 操作を削除し、Clipboard API のみに統一する変更です。

  • コピー成功時のフィードバック処理は維持されています。
  • Clipboard API が利用できない場合や書き込みに失敗した場合は、エラーを記録して成功状態にしません。
  • フックおよび ShareButtons のテストが新しい失敗時の挙動に合わせて更新されています。

Confidence Score: 5/5

意図されたブラウザー互換性の縮小を除き、マージを妨げる問題は確認できず、安全にマージできると考えます。

非推奨のコピー処理と関連する DOM 操作は一貫して削除され、成功時の状態更新と Clipboard API の失敗時・未提供時のエラー処理が対応するテストでカバーされています。

Important Files Changed

Filename Overview
src/hooks/useCopyToClipboard.ts 非推奨の DOM ベースのコピー処理を削除し、Clipboard API の成功・失敗処理に一本化しています。
src/hooks/tests/useCopyToClipboard.test.ts フォールバック関連テストを削除し、Clipboard API の失敗および未提供時のログ出力を検証しています。
src/components/ShareButtons.test.tsx ShareButtons の統合テストを Clipboard API のみを使用する新しい契約に合わせて更新しています。

Reviews (1): Last reviewed commit: "refactor: remove document.execCommand fa..." | Re-trigger Greptile

Context used:

Co-authored-by: is0692vs <135803462+is0692vs@users.noreply.github.com>
@vercel

vercel Bot commented Aug 1, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
github-user-summary Ignored Ignored Aug 1, 2026 4:32am

@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@gemini-code-assist

Copy link
Copy Markdown

Caution

The consumer version of Gemini Code Assist on GitHub has been sunset. All code review activity has officially ceased.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@is0692vs, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 53 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: af2347f0-8fb0-45b7-a464-0d90b660f497

📥 Commits

Reviewing files that changed from the base of the PR and between e914034 and 3cfce0e.

📒 Files selected for processing (3)
  • src/components/ShareButtons.test.tsx
  • src/hooks/__tests__/useCopyToClipboard.test.ts
  • src/hooks/useCopyToClipboard.ts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@dosubot

dosubot Bot commented Aug 1, 2026

Copy link
Copy Markdown

📄 Knowledge review

Dosu skipped reviewing this PR because your organization has used its 200 included credits for the month. Your usage will reset on 2026-09-01. To have Dosu review this PR before then, ask your organization admin to upgrade to a pro account.


Leave Feedback Ask Dosu about github-user-summary Add Dosu to your team

@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Remove deprecated document.execCommand fallback from useCopyToClipboard

✨ Enhancement 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Remove legacy document.execCommand copy fallback and hidden textarea DOM manipulation.
• Rely only on navigator.clipboard.writeText; log errors when unavailable or failing.
• Update ShareButtons and hook tests to reflect clipboard-only behavior.
Diagram

graph TD
  SB["ShareButtons"] --> Hook["useCopyToClipboard"] --> Clip["navigator.clipboard.writeText"]
  Hook --> Log["logger.error"]
  Clip -."rejects".-> Log
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Keep execCommand behind an opt-in flag
  • ➕ Preserves compatibility for legacy/embedded browsers
  • ➕ Allows gradual rollout with telemetry on failure rates
  • ➖ Still retains deprecated API and DOM injection path
  • ➖ Increases code paths and testing burden
2. Use a vetted copy-to-clipboard library
  • ➕ Offloads edge-case handling and browser quirks to maintained dependency
  • ➕ Potentially better UX across more environments
  • ➖ Adds dependency surface area and audit requirements
  • ➖ May reintroduce execCommand or DOM-based fallbacks indirectly
3. Provide manual-copy UX on failure (no fallback copy)
  • ➕ Avoids deprecated APIs entirely while still helping users succeed
  • ➕ Clearer behavior in restricted contexts (permissions/iframes)
  • ➖ More UI work (modal/selectable text) and product decisions
  • ➖ Still won’t auto-copy in constrained environments

Recommendation: The PR’s approach (clipboard-only + error logging) is the best default for security hardening and deterministic behavior. If legacy support is still required for a specific audience, consider an explicit opt-in flag or a manual-copy UI instead of reintroducing execCommand implicitly.

Files changed (3) +17 / -267

Refactor (1) +2 / -36
useCopyToClipboard.tsRemove deprecated execCommand fallback; log clipboard failures +2/-36

Remove deprecated execCommand fallback; log clipboard failures

• Eliminates the textarea/execCommand('copy') fallback path entirely and removes multi-error aggregation for fallback failures. The hook now only attempts navigator.clipboard.writeText, logging errors on rejection or when the Clipboard API is unavailable.

src/hooks/useCopyToClipboard.ts

Tests (2) +15 / -231
ShareButtons.test.tsxRemove execCommand fallback expectations from ShareButtons tests +8/-144

Remove execCommand fallback expectations from ShareButtons tests

• Deletes tests that validated document.execCommand-based fallback behavior and DOM textarea manipulation. Updates failure-path assertions to expect a single logged error and no 'Copied!' feedback when clipboard copying fails or is unavailable.

src/components/ShareButtons.test.tsx

useCopyToClipboard.test.tsAlign useCopyToClipboard tests to clipboard-only behavior +7/-87

Align useCopyToClipboard tests to clipboard-only behavior

• Removes execCommand mocking/setup and deletes fallback-oriented test cases. Simplifies error assertions to a single logger.error call when writeText rejects, and verifies error logging when navigator.clipboard is missing.

src/hooks/tests/useCopyToClipboard.test.ts

@codecov

codecov Bot commented Aug 1, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 30 rules

Grey Divider


Remediation recommended

1. Stale copied feedback 🐞 Bug ≡ Correctness
Description
When copyToClipboard fails (clipboard missing or writeText rejects), useCopyToClipboard only logs
and never clears any existing copied state/timer, so UI may still show “Copied!” from a previous
success even though the latest attempt failed (until the old timeout expires). This becomes more
likely now that the execCommand fallback has been removed, increasing the number of failure-path
executions.
Code

src/hooks/useCopyToClipboard.ts[R26-30]

+        logger.error("Failed to copy", err);
      }
    } else {
-      clipboardError = new Error("Clipboard API not available");
-    }
-
-    // Fallback for older browsers
-    const textArea = document.createElement("textarea");
-    textArea.value = text;
-    textArea.style.position = "fixed";
-    textArea.style.left = "-9999px";
-    textArea.style.top = "0";
-    textArea.setAttribute("readonly", "");
-    document.body.appendChild(textArea);
-
-    let successful = false;
-    let fallbackError: unknown = null;
-
-    try {
-      textArea.select();
-      successful = document.execCommand("copy");
-      if (!successful) {
-        fallbackError = new Error("document.execCommand('copy') failed");
-      }
-    } catch (err) {
-      successful = false;
-      fallbackError = err;
-    } finally {
-      document.body.removeChild(textArea);
-    }
-
-    if (successful) {
-      showCopiedFeedback();
-    } else {
-      logger.error("Failed to copy", clipboardError, fallbackError);
+      logger.error("Failed to copy", new Error("Clipboard API not available"));
    }
Evidence
showCopiedFeedback is the only code path that updates copied and manages the timer; the failure
paths just log and exit, leaving any previously-true copied value intact until its existing timer
fires.

src/hooks/useCopyToClipboard.ts[14-31]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`useCopyToClipboard` sets `copied=true` only on success, but on failure it only logs and does not clear `copied` or cancel any existing timer. If a previous successful copy set `copied=true` and the user clicks again within the timeout, a failure can leave the UI incorrectly displaying “Copied!” for the remainder of the prior timer.

## Issue Context
Now that the legacy execCommand fallback is removed, failures are more common (e.g., missing Clipboard API / permission issues), so the stale-success feedback is more visible.

## Fix Focus Areas
- src/hooks/useCopyToClipboard.ts[14-31]

## Suggested fix
- In both failure branches (the `catch` and the `else`), clear any existing timeout and set `copied` to `false` (e.g., via a small helper like `clearCopiedFeedback()` that mirrors the timer cleanup used in `showCopiedFeedback`).
- Optionally, have `copyToClipboard` return a boolean (`true` on success, `false` on failure) to make it harder for callers to assume success when `await` resolves.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

Comment on lines +26 to 30
logger.error("Failed to copy", err);
}
} else {
clipboardError = new Error("Clipboard API not available");
}

// Fallback for older browsers
const textArea = document.createElement("textarea");
textArea.value = text;
textArea.style.position = "fixed";
textArea.style.left = "-9999px";
textArea.style.top = "0";
textArea.setAttribute("readonly", "");
document.body.appendChild(textArea);

let successful = false;
let fallbackError: unknown = null;

try {
textArea.select();
successful = document.execCommand("copy");
if (!successful) {
fallbackError = new Error("document.execCommand('copy') failed");
}
} catch (err) {
successful = false;
fallbackError = err;
} finally {
document.body.removeChild(textArea);
}

if (successful) {
showCopiedFeedback();
} else {
logger.error("Failed to copy", clipboardError, fallbackError);
logger.error("Failed to copy", new Error("Clipboard API not available"));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remediation recommended

1. Stale copied feedback 🐞 Bug ≡ Correctness

When copyToClipboard fails (clipboard missing or writeText rejects), useCopyToClipboard only logs
and never clears any existing copied state/timer, so UI may still show “Copied!” from a previous
success even though the latest attempt failed (until the old timeout expires). This becomes more
likely now that the execCommand fallback has been removed, increasing the number of failure-path
executions.
Agent Prompt
## Issue description
`useCopyToClipboard` sets `copied=true` only on success, but on failure it only logs and does not clear `copied` or cancel any existing timer. If a previous successful copy set `copied=true` and the user clicks again within the timeout, a failure can leave the UI incorrectly displaying “Copied!” for the remainder of the prior timer.

## Issue Context
Now that the legacy execCommand fallback is removed, failures are more common (e.g., missing Clipboard API / permission issues), so the stale-success feedback is more visible.

## Fix Focus Areas
- src/hooks/useCopyToClipboard.ts[14-31]

## Suggested fix
- In both failure branches (the `catch` and the `else`), clear any existing timeout and set `copied` to `false` (e.g., via a small helper like `clearCopiedFeedback()` that mirrors the timer cleanup used in `showCopiedFeedback`).
- Optionally, have `copyToClipboard` return a boolean (`true` on success, `false` on failure) to make it harder for callers to assume success when `await` resolves.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant