package com.cottondb.android.platformimport android.content.ClipDataimport android.content.ClipDescriptionimport android.content.ClipboardManagerimport android.content.Contextimport android.os.PersistableBundleimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Jobimport kotlinx.coroutines.delayimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.launchimport java.util.UUID/** The time-to-clear is attempted only while this process and its scope remain alive. */enumclassSensitiveClipboardExpiry {BestEffortWhileProcessRuns,NotScheduled,}/** A clipboard operation failed, but never carries platform text that could contain a copied value. */enumclassSensitiveClipboardIssue {CopyFailed,ClearFailed,ExpirySchedulingFailed,}/** * Copies a credential without retaining it outside Android's clipboard service. * * Android has no expiry date on a ClipData item. [copy] schedules a best-effort clear, * and [clear] only removes a clip whose opaque label still belongs to this instance. */interfaceSensitiveClipboard {fun copy(value: CharSequence): SensitiveClipboardExpiryfun clear()}/** A cancellable task used solely to make expiry deterministic in tests. */funinterfaceClipboardExpiryCancellation {fun cancel()}funinterfaceClipboardExpiryScheduler {fun schedule(delayMillis: Long, task: () -> Unit): ClipboardExpiryCancellation}/** The process scope owns the best-effort expiry: it deliberately does not survive a process death. */classCoroutineClipboardExpiryScheduler(privateval scope: CoroutineScope,) : ClipboardExpiryScheduler {overridefun schedule(delayMillis: Long, task: () -> Unit): ClipboardExpiryCancellation {val job: Job = scope.launch { delay(delayMillis) task() }returnClipboardExpiryCancellation(job::cancel) }}/** * Only clip metadata is read back. In particular, an expiry never reads or compares the secret. */interfaceSensitiveClipboardPlatform {fun writeSensitive(labelToken: String, value: CharSequence)fun currentLabel(): CharSequence?fun clear()}/** Android's global clipboard boundary. */classAndroidClipboardPlatform(context: Context) : SensitiveClipboardPlatform {privateval clipboard = context.getSystemService(ClipboardManager::class.java)overridefun writeSensitive(labelToken: String, value: CharSequence) {val clip = ClipData.newPlainText(labelToken, value)// Description extras are API 24; the sensitive marker is understood by Android 13 (API 33)+. clip.description.extras = PersistableBundle().apply { putBoolean(ClipDescription.EXTRA_IS_SENSITIVE, true) } clipboard.setPrimaryClip(clip) }overridefun currentLabel(): CharSequence? = clipboard.primaryClipDescription?.labeloverridefun clear() {// clearPrimaryClip was introduced in API 28, the application's minimum SDK. clipboard.clearPrimaryClip() }}/** * Uses a random label to identify one copy operation. The token does not encode the copied * value, and is held only until that copy is cleared or superseded. */classAndroidSensitiveClipboard(privateval platform: SensitiveClipboardPlatform,privateval scheduler: ClipboardExpiryScheduler,privateval expiryMillis: Long = DEFAULT_EXPIRY_MILLIS,privateval nextLabelToken: () -> String = { UUID.randomUUID().toString() },) : SensitiveClipboard {privateval lock = Any()privatevar activeLabelToken: String? = nullprivatevar pendingExpiry: ClipboardExpiryCancellation? = nullprivateval _issue = MutableStateFlow<SensitiveClipboardIssue?>(null)/** Transient failure state for retry affordances. It neither contains nor retains a copied value. */val issue: StateFlow<SensitiveClipboardIssue?> = _issue.asStateFlow() constructor(context: Context, scope: CoroutineScope) : this( platform = AndroidClipboardPlatform(context.applicationContext), scheduler = CoroutineClipboardExpiryScheduler(scope), )init { require(expiryMillis > 0) { "Sensitive clipboard expiry must be positive." } }overridefun copy(value: CharSequence): SensitiveClipboardExpiry = synchronized(lock) {val labelToken = nextLabelToken()try { platform.writeSensitive(labelToken, value) } catch (_: Throwable) {// Leave the previous token and timer intact: the failed write has not superseded it. _issue.value = SensitiveClipboardIssue.CopyFailedthrowIllegalStateException("The password could not be copied.") } pendingExpiry?.cancel() pendingExpiry = null activeLabelToken = labelToken _issue.value = nulltry { pendingExpiry = scheduler.schedule(expiryMillis) { clearIfStillOurs(labelToken) }SensitiveClipboardExpiry.BestEffortWhileProcessRuns } catch (_: Throwable) {// The copy succeeded but has no process timer. Keep its token for an explicit clear. _issue.value = SensitiveClipboardIssue.ExpirySchedulingFailedSensitiveClipboardExpiry.NotScheduled } }overridefun clear(): Unit = synchronized(lock) { activeLabelToken?.let(::clearIfStillOurs)Unit }privatefun clearIfStillOurs(labelToken: String) {try { synchronized(lock) {if (activeLabelToken != labelToken) returntry {// This is a best-effort identity check: another process can replace the clip after the// read and before clearPrimaryClip(), because Android provides no compare-and-clear.val label = platform.currentLabel()if (label == null) {// Background clipboard access may be denied. Keep ownership for a// foreground retry rather than claiming the value was cleared. _issue.value = SensitiveClipboardIssue.ClearFailedreturn }if (label.contentEquals(labelToken)) { platform.clear() } } catch (_: Throwable) {// Retain the token and pending timer so a later explicit clear can retry safely. _issue.value = SensitiveClipboardIssue.ClearFailedreturn } activeLabelToken = null pendingExpiry?.cancel() pendingExpiry = null _issue.value = null } } catch (_: Throwable) {// A scheduler callback must not fail the process scope's supervisor. _issue.value = SensitiveClipboardIssue.ClearFailed } }companionobject {constval DEFAULT_EXPIRY_MILLIS: Long = 60_000 }}