Skip to main content
3Nsofts logo3Nsofts
Security & Compliance

Copy Sensitive Text on macOS Without Clearing the Next Copy

Build an AppKit clipboard helper with ConcealedType, guarded expiry and honest limits for clipboard managers, app termination and cross-device copying.

By Ehsan Azish · 3NSOFTS··6 min read

Copying a password to the general pasteboard makes it available to other processes that can read that pasteboard. A confidential marker and a delayed clear can reduce accidental retention. Neither makes copying a secret private.

This guide is for a native Mac app with an explicit Copy secret action. The goal is to mark that write, expire it after roughly a minute, and preserve anything the user copies afterward.

Two-step clipboard handling diagram showing a confidential marker and a change-count check before clearing.

The card shows the minimal idea. The implementation below writes one item with both representations and handles write failure. The confidential marker is a community convention. Supporting managers choose whether to mask or omit the entry. Apple documents the pasteboard APIs separately. Marker convention · Apple NSPasteboard

Contents

Choose the threat model

This is useful for reducing exposure in clipboard history, accidental later pastes, and visible previews. It cannot defend against a process reading the value immediately after the copy. It also cannot erase a copy already stored by another app.

Keep secrets in the Keychain until the user requests them. Offer copying as a deliberate action, show a short expiry message, and avoid automatically copying a value when a window opens. Use a non-secret fixture during development. Never include the actual clipboard value in diagnostics.

An expiry is a product policy. Sixty seconds gives a user time to switch apps, but you should adjust that interval after testing your own workflow.

Write and expire one item

This complete helper targets a native macOS app using AppKit. Keep its instance alive for the application session. Call it from a main-actor UI action. It supports one outstanding secret copy per instance.

import AppKit

@MainActor
final class SensitiveClipboard {
    enum CopyError: Error {
        case representationFailed
        case writeFailed
    }

    private var expiry: Task<Void, Never>?
    private var ownedChangeCount: Int?

    func copy(_ value: String) throws {
        let item = NSPasteboardItem()
        let concealed = NSPasteboard.PasteboardType(
            "org.nspasteboard.ConcealedType"
        )
        guard item.setString(value, forType: .string),
              item.setData(Data(), forType: concealed) else {
            throw CopyError.representationFailed
        }

        expiry?.cancel()
        let board = NSPasteboard.general
        board.clearContents()
        guard board.writeObjects([item]) else {
            ownedChangeCount = nil
            throw CopyError.writeFailed
        }
        ownedChangeCount = board.changeCount

        expiry = Task { @MainActor [weak self] in
            do {
                try await Task.sleep(nanoseconds: 60_000_000_000)
            } catch {
                return
            }
            self?.clearIfCurrent()
        }
    }

    func clearIfCurrent() {
        expiry?.cancel()
        expiry = nil
        guard let count = ownedChangeCount else { return }
        ownedChangeCount = nil

        let board = NSPasteboard.general
        guard board.changeCount == count else { return }
        board.clearContents()
    }
}

The timer captures the helper weakly and does not retain the secret string. The pasteboard item itself necessarily contains the secret. This code makes no memory-zeroization guarantee for Swift strings or framework copies.

On a second copy, the helper cancels its old task and records the new write. When expiry runs, it compares the current count with the saved count. If another copy changed ownership, it leaves the current pasteboard alone. The main actor serializes this app's actions, but another process can still write between the comparison and clear. NSPasteboard provides no atomic compare-and-clear operation. Treat the check as a practical guard with a small cross-process race window. Apple changeCount

Understand the two representations

The item has exactly two representations.

  • String holds the value that a text field will paste.
  • ConcealedType holds empty data. Its presence signals confidential content to participating clipboard tools. It carries no password, encryption key, or authorization rule.

Avoid adding an unmarked HTML or rich-text copy elsewhere in the same write. A manager might handle those independently. This example does not write TransientType because a minute-long copy is a different policy from briefly commandeering the clipboard for an automated text insertion. NSPasteboard marker definitions

The helper replaces the existing pasteboard contents. It intentionally does not save and restore the user's previous content, which would create another retained copy and might restore something the user no longer expects.

What can still go wrong

The app quits or crashes. An in-process task stops running. During an orderly termination you may call clearIfCurrent() from the app's main-actor termination handling. A force quit, crash, logout, or power loss can skip that cleanup.

The Mac sleeps. The callback may run later than the displayed interval. Say “clears after about a minute while the app is running.” A timer does not create a pasteboard-level expiry.

A manager keeps a history. Confirm how each supported manager handles the marker. Do not infer behavior from its name or from one version's results.

Universal Clipboard is enabled. This helper does not request a local-only write and makes no promise about cross-device propagation. If local-only copying is required, review AppKit's prepareForNewContents(with:) and ContentsOptions.currentHostOnly, then test with Handoff enabled on the actual devices. ConcealedType alone is insufficient. Apple pasteboard preparation · Apple currentHostOnly

A write fails after clearing. The previous clipboard is already gone. Surface failure to the user and avoid claiming the secret was copied.

Test the user-visible behavior

  • Copy a harmless fixture, paste it in a plain-text field, and confirm both advertised types exist.
  • Let expiry run and confirm the fixture is gone.
  • Copy ordinary text before expiry and confirm that text survives.
  • Copy secret fixture A, then B. Confirm A's canceled timer cannot prematurely clear B.
  • Try normal quit, force quit, sleep, and relaunch. Record the limitations in the UI copy.
  • Repeat with the clipboard managers and Handoff configuration you support.
  • Confirm logs, analytics, screenshots, and crash attachments contain no secret values.

For the stored credential behind that Copy button, continue with consistent Keychain queries. For selected files and exported secrets, see security-scoped bookmarks. The fourth article covers signing and offline release checks.

References

Expanded from Ehsan's original clipboard post.

Authoritative References