5894c92dd4ba
chore: seed dev lane baseline from main Phase 7b state — full working tree at v2.1.7
- time
- 2026-06-02 23:53 UTC · 5 months ago
- machine
- koh2
- agent
- claude-opus-4-8
- session
- phase 8-12 sync autofill codex integrations
- parent
- none, the first save
↓ peach-android-5894c92d.tar.gzatlas at this save
files changed110 files
.kohignore+37 −0app/build.gradle+112 −0app/proguard-rules.pro+1 −0app/src/main/AndroidManifest.xml+108 −0app/src/main/java/com/peachpasswords/MainActivity.kt+43 −0app/src/main/java/com/peachpasswords/PeachApplication.kt+7 −0app/src/main/java/com/peachpasswords/autofill/PeachAutofillService.kt+22 −0app/src/main/java/com/peachpasswords/di/VaultModule.kt+17 −0app/src/main/java/com/peachpasswords/haptics/PeachHaptics.kt+56 −0app/src/main/java/com/peachpasswords/license/LicenseRepository.kt+125 −0app/src/main/java/com/peachpasswords/license/ProFeature.kt+11 −0app/src/main/java/com/peachpasswords/passkeys/PeachCredentialProviderService.kt+42 −0app/src/main/java/com/peachpasswords/qs/PeachTileService.kt+9 −0app/src/main/java/com/peachpasswords/shared/DomainUtils.kt+22 −0app/src/main/java/com/peachpasswords/sync/ChirpIdentity.kt+67 −0app/src/main/java/com/peachpasswords/sync/ChirpPairing.kt+633 −0app/src/main/java/com/peachpasswords/sync/ChirpPayload.kt+109 −0app/src/main/java/com/peachpasswords/sync/ChirpSyncTransport.kt+254 −0app/src/main/java/com/peachpasswords/sync/ChirpTypes.kt+22 −0app/src/main/java/com/peachpasswords/sync/Ggwave.kt+41 −0app/src/main/java/com/peachpasswords/sync/NoiseNK.kt+224 −0app/src/main/java/com/peachpasswords/sync/NoiseXX.kt+254 −0app/src/main/java/com/peachpasswords/sync/PairedDevice.kt+17 −0app/src/main/java/com/peachpasswords/sync/PairingProgress.kt+19 −0app/src/main/java/com/peachpasswords/sync/SASDerivation.kt+12 −0app/src/main/java/com/peachpasswords/sync/SyncIdentity.kt+89 −0app/src/main/java/com/peachpasswords/sync/SyncStatus.kt+9 −0app/src/main/java/com/peachpasswords/ui/PeachAppNavHost.kt+99 −0app/src/main/java/com/peachpasswords/ui/PeachNav.kt+39 −0app/src/main/java/com/peachpasswords/ui/components/CharEnterText.kt+76 −0app/src/main/java/com/peachpasswords/ui/components/FaviconInitials.kt+74 −0app/src/main/java/com/peachpasswords/ui/components/LockRuneString.kt+70 −0app/src/main/java/com/peachpasswords/ui/components/PeachMark.kt+53 −0app/src/main/java/com/peachpasswords/ui/components/TOTPRing.kt+47 −0app/src/main/java/com/peachpasswords/ui/lock/BiometricUnlockActivity.kt+11 −0app/src/main/java/com/peachpasswords/ui/lock/Biometrics.kt+40 −0app/src/main/java/com/peachpasswords/ui/lock/LockScreen.kt+245 −0app/src/main/java/com/peachpasswords/ui/lock/LockViewModel.kt+71 −0app/src/main/java/com/peachpasswords/ui/screens/PlaceholderScreens.kt+120 −0app/src/main/java/com/peachpasswords/ui/settings/CardIcon.kt+78 −0app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+509 −0app/src/main/java/com/peachpasswords/ui/settings/SettingsScreen.kt+386 −0app/src/main/java/com/peachpasswords/ui/settings/SettingsStack.kt+56 −0app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+50 −0app/src/main/java/com/peachpasswords/ui/theme/AccentColors.kt+20 −0app/src/main/java/com/peachpasswords/ui/theme/PeachColors.kt+37 −0app/src/main/java/com/peachpasswords/ui/theme/PeachColorsLight.kt+26 −0app/src/main/java/com/peachpasswords/ui/theme/PeachMotion.kt+27 −0app/src/main/java/com/peachpasswords/ui/theme/PeachRadius.kt+18 −0app/src/main/java/com/peachpasswords/ui/theme/PeachStackColors.kt+39 −0app/src/main/java/com/peachpasswords/ui/theme/PeachTheme.kt+92 −0app/src/main/java/com/peachpasswords/ui/theme/PeachType.kt+29 −0app/src/main/java/com/peachpasswords/ui/theme/ShellBackground.kt+64 −0app/src/main/java/com/peachpasswords/ui/vault/EntryDetailScreen.kt+238 −0app/src/main/java/com/peachpasswords/ui/vault/EntryDetailViewModel.kt+75 −0app/src/main/java/com/peachpasswords/ui/vault/EntryEditScreen.kt+267 −0app/src/main/java/com/peachpasswords/ui/vault/EntryEditViewModel.kt+131 −0app/src/main/java/com/peachpasswords/ui/vault/VaultListScreen.kt+343 −0app/src/main/java/com/peachpasswords/ui/vault/VaultListViewModel.kt+105 −0app/src/main/java/com/peachpasswords/vault/Canary.kt+14 −0app/src/main/java/com/peachpasswords/vault/PasskeyData.kt+24 −0app/src/main/java/com/peachpasswords/vault/PasswordGenerator.kt+45 −0app/src/main/java/com/peachpasswords/vault/RecoveryWordList.kt+2053 −0app/src/main/java/com/peachpasswords/vault/RecoveryWords.kt+87 −0app/src/main/java/com/peachpasswords/vault/SavedIdentity.kt+12 −0app/src/main/java/com/peachpasswords/vault/TOTPGenerator.kt+92 −0app/src/main/java/com/peachpasswords/vault/VaultCrypto.kt+95 −0app/src/main/java/com/peachpasswords/vault/VaultEntry.kt+67 −0app/src/main/java/com/peachpasswords/vault/VaultHealth.kt+102 −0app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+347 −0app/src/main/java/com/peachpasswords/vault/VaultSettings.kt+28 −0app/src/main/java/com/peachpasswords/vault/VaultSnapshot.kt+13 −0app/src/main/java/com/peachpasswords/vault/VaultStore.kt+114 −0app/src/main/java/com/peachpasswords/widget/PeachWidgets.kt+43 −0app/src/main/res/drawable/ic_launcher_background.xml+4 −0app/src/main/res/drawable/ic_launcher_foreground.xml+15 −0app/src/main/res/drawable/ic_launcher_monochrome.xml+5 −0app/src/main/res/font/cormorant_garamond_light.ttfbinaryapp/src/main/res/font/cormorant_garamond_light_italic.ttfbinaryapp/src/main/res/font/cormorant_garamond_regular.ttfbinaryapp/src/main/res/font/cormorant_garamond_regular_italic.ttfbinaryapp/src/main/res/font/ibm_plex_mono_light.ttfbinaryapp/src/main/res/font/ibm_plex_mono_light_italic.ttfbinaryapp/src/main/res/font/ibm_plex_mono_regular.ttfbinaryapp/src/main/res/font/inter_regular.ttfbinaryapp/src/main/res/font/inter_variable.ttfbinaryapp/src/main/res/font/peachscript_regular.otfbinaryapp/src/main/res/mipmap-anydpi-v26/ic_launcher.xml+6 −0app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml+6 −0app/src/main/res/values-night/colors.xml+24 −0app/src/main/res/values/colors.xml+83 −0app/src/main/res/values/strings.xml+8 −0app/src/main/res/values/styles.xml+16 −0app/src/main/res/xml/autofill_service_config.xml+3 −0app/src/main/res/xml/credential_provider_config.xml+6 −0app/src/main/res/xml/peach_medium_widget_info.xml+10 −0app/src/main/res/xml/peach_small_widget_info.xml+10 −0app/src/main/res/xml/shortcuts.xml+36 −0app/src/test/java/com/peachpasswords/sync/ChirpPairingTest.kt+226 −0app/src/test/java/com/peachpasswords/sync/ChirpSyncTransportTest.kt+99 −0app/src/test/java/com/peachpasswords/vault/PasswordGeneratorTest.kt+36 −0app/src/test/java/com/peachpasswords/vault/TOTPGeneratorTest.kt+33 −0app/src/test/java/com/peachpasswords/vault/VaultRepositoryTest.kt+142 −0build.gradle+8 −0gradle.properties+7 −0gradle/wrapper/gradle-wrapper-shared.jarbinarygradle/wrapper/gradle-wrapper.jarbinarygradle/wrapper/gradle-wrapper.properties+7 −0gradlew+22 −0settings.gradle+20 −0.kohignore+37 −0
@@ -0,0 +1,37 @@1+# .kohignore2+# Generated by koh init. Edit to fit the project.3+#4+# Patterns are matched against repo-relative paths. Suffix `/` restricts5+# to directories. Leading `/` anchors to the repo root. A pattern like6+# `*.log` matches any file with that extension anywhere in the tree.7+#8+# koh already ignores .koh/, .git/, and .kohconfig automatically.9+10+# Build output11+.gradle/12+.kotlin/13+zig-out/14+.zig-cache/15+zig-cache/16+target/17+build/18+app/build/19+dist/20+out/21+22+# Local environment23+local.properties24+25+# Dependencies26+node_modules/27+28+# OS noise29+.DS_Store30+Thumbs.db31+32+# Logs33+*.log34+35+# Koh artifacts36+*.bundle37+*.koh.offerapp/build.gradle+112 −0
@@ -0,0 +1,112 @@1+plugins {2+ id "com.android.application"3+ id "org.jetbrains.kotlin.android"4+ id "org.jetbrains.kotlin.plugin.compose"5+ id "org.jetbrains.kotlin.plugin.parcelize"6+ id "org.jetbrains.kotlin.plugin.serialization"7+ id "kotlin-kapt"8+ id "com.google.dagger.hilt.android"9+}10+11+android {12+ namespace "com.peachpasswords"13+ compileSdk 3514+15+ defaultConfig {16+ applicationId "com.peachpasswords"17+ minSdk 2618+ targetSdk 3519+ versionCode 20100720+ versionName "2.1.7"21+22+ testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"23+ vectorDrawables {24+ useSupportLibrary true25+ }26+ }27+28+ buildTypes {29+ debug {30+ applicationIdSuffix ".debug"31+ versionNameSuffix "-debug"32+ debuggable true33+ }34+ release {35+ minifyEnabled false36+ proguardFiles getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro"37+ }38+ }39+40+ compileOptions {41+ sourceCompatibility JavaVersion.VERSION_1742+ targetCompatibility JavaVersion.VERSION_1743+ }44+45+ kotlinOptions {46+ jvmTarget = "17"47+ }48+49+ buildFeatures {50+ compose true51+ buildConfig true52+ }53+54+ composeOptions {55+ kotlinCompilerExtensionVersion "1.5.15"56+ }57+58+ packaging {59+ resources {60+ excludes += [61+ "/META-INF/{AL2.0,LGPL2.1}",62+ "META-INF/DEPENDENCIES",63+ "META-INF/LICENSE*",64+ "META-INF/NOTICE*",65+ ]66+ }67+ }68+}69+70+dependencies {71+ implementation platform("androidx.compose:compose-bom:2024.06.00")72+ androidTestImplementation platform("androidx.compose:compose-bom:2024.06.00")73+74+ implementation "androidx.activity:activity-compose:1.9.2"75+ implementation "androidx.biometric:biometric:1.1.0"76+ implementation "androidx.core:core-splashscreen:1.0.1"77+ implementation "androidx.appcompat:appcompat:1.7.0"78+ implementation "androidx.credentials:credentials:1.5.0"79+ implementation "androidx.credentials:credentials-play-services-auth:1.5.0"80+ implementation "androidx.glance:glance-appwidget:1.1.0"81+ implementation "androidx.glance:glance-material3:1.1.0"82+ implementation "androidx.hilt:hilt-navigation-compose:1.2.0"83+ implementation "androidx.lifecycle:lifecycle-runtime-compose:2.8.4"84+ implementation "androidx.lifecycle:lifecycle-viewmodel-compose:2.8.4"85+ implementation "androidx.navigation:navigation-compose:2.8.0"86+ implementation "androidx.security:security-crypto:1.1.0-alpha06"87+ implementation "androidx.compose.material3:material3"88+ implementation "androidx.compose.ui:ui"89+ implementation "androidx.compose.ui:ui-tooling-preview"90+ implementation "androidx.compose.foundation:foundation"91+ implementation "androidx.compose.material:material-icons-extended"92+ implementation "androidx.core:core-ktx:1.13.1"93+ implementation "com.google.android.material:material:1.12.0"94+95+ implementation "com.google.crypto.tink:tink-android:1.13.0"96+ implementation "com.google.dagger:hilt-android:2.51.1"97+ kapt "com.google.dagger:hilt-compiler:2.51.1"98+ implementation "com.google.zxing:core:3.5.3"99+ implementation "com.squareup.okhttp3:okhttp:4.12.0"100+ implementation "org.bouncycastle:bcprov-jdk18on:1.78.1"101+ implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:1.8.1"102+ implementation "org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.1"103+104+ debugImplementation "androidx.compose.ui:ui-tooling"105+ debugImplementation "androidx.compose.ui:ui-test-manifest"106+107+ androidTestImplementation "androidx.test.ext:junit:1.2.1"108+ androidTestImplementation "androidx.test.espresso:espresso-core:3.6.1"109+ androidTestImplementation "androidx.compose.ui:ui-test-junit4"110+111+ testImplementation "junit:junit:4.13.2"112+}app/src/main/AndroidManifest.xml+108 −0
@@ -0,0 +1,108 @@1+<?xml version="1.0" encoding="utf-8"?>2+<manifest xmlns:android="http://schemas.android.com/apk/res/android"3+ xmlns:tools="http://schemas.android.com/tools">4+5+ <uses-permission android:name="android.permission.INTERNET" />6+ <uses-permission android:name="android.permission.VIBRATE" />7+ <uses-permission android:name="android.permission.USE_BIOMETRIC" />8+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />9+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />10+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />11+12+ <application13+ android:name=".PeachApplication"14+ android:allowBackup="false"15+ android:fullBackupContent="false"16+ android:icon="@mipmap/ic_launcher"17+ android:label="@string/app_name"18+ android:roundIcon="@mipmap/ic_launcher_round"19+ android:supportsRtl="true"20+ android:theme="@style/Theme.Peach.Splash">21+22+ <activity23+ android:name=".MainActivity"24+ android:exported="true"25+ android:launchMode="singleTask"26+ android:screenOrientation="unspecified"27+ android:enableOnBackInvokedCallback="true"28+ android:theme="@style/Theme.Peach">29+ <intent-filter>30+ <action android:name="android.intent.action.MAIN" />31+ <category android:name="android.intent.category.LAUNCHER" />32+ </intent-filter>33+ <intent-filter>34+ <action android:name="android.intent.action.VIEW" />35+ <category android:name="android.intent.category.DEFAULT" />36+ <category android:name="android.intent.category.BROWSABLE" />37+ <data android:scheme="peach" />38+ </intent-filter>39+ <meta-data40+ android:name="android.app.shortcuts"41+ android:resource="@xml/shortcuts" />42+ </activity>43+44+ <activity45+ android:name=".ui.lock.BiometricUnlockActivity"46+ android:exported="false"47+ android:theme="@style/Theme.Peach" />48+49+ <service50+ android:name=".autofill.PeachAutofillService"51+ android:permission="android.permission.BIND_AUTOFILL_SERVICE"52+ android:exported="true"53+ android:label="@string/autofill_service_label"54+ android:settingsActivity=".MainActivity">55+ <intent-filter>56+ <action android:name="android.service.autofill.AutofillService" />57+ </intent-filter>58+ <meta-data59+ android:name="android.autofill"60+ android:resource="@xml/autofill_service_config" />61+ </service>62+63+ <service64+ android:name=".passkeys.PeachCredentialProviderService"65+ android:permission="android.permission.BIND_CREDENTIAL_PROVIDER_SERVICE"66+ android:exported="true"67+ tools:targetApi="34">68+ <intent-filter>69+ <action android:name="android.service.credentials.CredentialProviderService" />70+ </intent-filter>71+ <meta-data72+ android:name="android.credentials.provider"73+ android:resource="@xml/credential_provider_config" />74+ </service>75+76+ <service77+ android:name=".qs.PeachTileService"78+ android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"79+ android:exported="true">80+ <intent-filter>81+ <action android:name="android.service.quicksettings.action.QS_TILE" />82+ </intent-filter>83+ </service>84+85+ <receiver86+ android:name=".widget.PeachSmallWidgetReceiver"87+ android:exported="true">88+ <intent-filter>89+ <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />90+ </intent-filter>91+ <meta-data92+ android:name="android.appwidget.provider"93+ android:resource="@xml/peach_small_widget_info" />94+ </receiver>95+96+ <receiver97+ android:name=".widget.PeachMediumWidgetReceiver"98+ android:exported="true">99+ <intent-filter>100+ <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />101+ </intent-filter>102+ <meta-data103+ android:name="android.appwidget.provider"104+ android:resource="@xml/peach_medium_widget_info" />105+ </receiver>106+107+ </application>108+</manifest>app/src/main/java/com/peachpasswords/MainActivity.kt+43 −0
@@ -0,0 +1,43 @@1+package com.peachpasswords2+3+import android.graphics.Color as AndroidColor4+import android.graphics.drawable.ColorDrawable5+import android.os.Bundle6+import android.view.WindowManager7+import androidx.activity.compose.setContent8+import androidx.activity.enableEdgeToEdge9+import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen10+import androidx.fragment.app.FragmentActivity11+import dagger.hilt.android.AndroidEntryPoint12+import com.peachpasswords.ui.PeachAppNavHost13+import com.peachpasswords.ui.theme.PeachTheme14+15+// FragmentActivity (not ComponentActivity) so androidx BiometricPrompt can attach.16+@AndroidEntryPoint17+class MainActivity : FragmentActivity() {18+ override fun onCreate(savedInstanceState: Bundle?) {19+ installSplashScreen()20+ super.onCreate(savedInstanceState)21+22+ // Match the splash/window fill to --bg so launch never flashes white.23+ window.setBackgroundDrawable(ColorDrawable(AndroidColor.parseColor("#0C0A06")))24+25+ enableEdgeToEdge()26+27+ // Block screenshots / recents thumbnails of the vault in release builds.28+ if (!BuildConfig.DEBUG) {29+ window.setFlags(30+ WindowManager.LayoutParams.FLAG_SECURE,31+ WindowManager.LayoutParams.FLAG_SECURE,32+ )33+ }34+35+ setContent {36+ // Theme/accent are wired to persisted settings in a later phase; the37+ // shell uses the dark default until SettingsViewModel lands.38+ PeachTheme {39+ PeachAppNavHost()40+ }41+ }42+ }43+}app/src/main/java/com/peachpasswords/PeachApplication.kt+7 −0
@@ -0,0 +1,7 @@1+package com.peachpasswords2+3+import android.app.Application4+import dagger.hilt.android.HiltAndroidApp5+6+@HiltAndroidApp7+class PeachApplication : Application()app/src/main/java/com/peachpasswords/autofill/PeachAutofillService.kt+22 −0
@@ -0,0 +1,22 @@1+package com.peachpasswords.autofill2+3+import android.os.CancellationSignal4+import android.service.autofill.AutofillService5+import android.service.autofill.FillCallback6+import android.service.autofill.FillRequest7+import android.service.autofill.SaveCallback8+import android.service.autofill.SaveRequest9+10+class PeachAutofillService : AutofillService() {11+ override fun onFillRequest(12+ request: FillRequest,13+ cancellationSignal: CancellationSignal,14+ callback: FillCallback,15+ ) {16+ // Scaffold: the real dataset wiring comes later.17+ }18+19+ override fun onSaveRequest(request: SaveRequest, callback: SaveCallback) {20+ // Scaffold: save flow is wired in a later phase.21+ }22+}app/src/main/java/com/peachpasswords/di/VaultModule.kt+17 −0
@@ -0,0 +1,17 @@1+package com.peachpasswords.di2+3+import com.peachpasswords.vault.VaultStorage4+import com.peachpasswords.vault.VaultStore5+import dagger.Binds6+import dagger.Module7+import dagger.hilt.InstallIn8+import dagger.hilt.components.SingletonComponent9+import javax.inject.Singleton10+11+@Module12+@InstallIn(SingletonComponent::class)13+abstract class VaultModule {14+ @Binds15+ @Singleton16+ abstract fun bindVaultStorage(impl: VaultStore): VaultStorage17+}app/src/main/java/com/peachpasswords/haptics/PeachHaptics.kt+56 −0
@@ -0,0 +1,56 @@1+package com.peachpasswords.haptics2+3+import android.content.Context4+import android.os.Build5+import android.os.VibrationEffect6+import android.os.Vibrator7+import android.os.VibratorManager8+import android.view.HapticFeedbackConstants9+import android.view.View10+11+object PeachHaptics {12+ fun onUnlock(view: View) = view.performHapticFeedback(HapticFeedbackConstants.CONFIRM)13+ fun onEntryTap(view: View) = view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)14+ fun onCopy(view: View) = view.performHapticFeedback(HapticFeedbackConstants.CLOCK_TICK)15+ fun onSheetOpen(view: View) = view.performHapticFeedback(HapticFeedbackConstants.CONTEXT_CLICK)16+ fun onSheetClose(view: View) = view.performHapticFeedback(HapticFeedbackConstants.GESTURE_END)17+ fun onError(view: View) = view.performHapticFeedback(HapticFeedbackConstants.REJECT)18+ fun onButton(view: View) = view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)19+ fun onCardFocus(view: View) = view.performHapticFeedback(HapticFeedbackConstants.VIRTUAL_KEY)20+21+ fun onLongPress(context: Context) = vibrate(context, 20L, 180)22+ fun onSwipeCopy(context: Context) = vibrate(context, 15L, 150)23+24+ fun onPairingComplete(context: Context) {25+ val vibrator = getVibrator(context) ?: return26+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {27+ vibrator.vibrate(28+ VibrationEffect.createWaveform(29+ longArrayOf(0, 30, 60, 50),30+ intArrayOf(0, 180, 0, 120),31+ -1,32+ )33+ )34+ }35+ }36+37+ private fun vibrate(context: Context, duration: Long, amplitude: Int) {38+ val vibrator = getVibrator(context) ?: return39+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {40+ vibrator.vibrate(VibrationEffect.createOneShot(duration, amplitude))41+ } else {42+ @Suppress("DEPRECATION")43+ vibrator.vibrate(duration)44+ }45+ }46+47+ private fun getVibrator(context: Context): Vibrator? {48+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {49+ val manager = context.getSystemService(VibratorManager::class.java)50+ manager?.defaultVibrator51+ } else {52+ @Suppress("DEPRECATION")53+ context.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator54+ }55+ }56+}app/src/main/java/com/peachpasswords/license/LicenseRepository.kt+125 −0
@@ -0,0 +1,125 @@1+package com.peachpasswords.license2+3+import android.content.Context4+import androidx.security.crypto.EncryptedSharedPreferences5+import androidx.security.crypto.MasterKey6+import java.math.BigInteger7+import java.security.KeyFactory8+import java.security.Signature9+import java.security.spec.X509EncodedKeySpec10+11+class LicenseRepository(context: Context) {12+ companion object {13+ private const val PUBLIC_KEY_HEX =14+ "c7dc52d2c484696cf8566dbe6cfe69025d114cb47f6cf53c25088ecfd539bdfa"15+16+ private const val PREFS_FILE = "peach_license_prefs"17+ private const val KEY_LICENSE = "peach_license"18+ private const val KEY_PRO_CELEBRATED = "peach_pro_celebrated"19+20+ private const val BASE58_ALPHABET =21+ "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"22+23+ const val PAYLOAD_SIZE = 1224+ const val SIGNATURE_SIZE = 6425+ const val TOTAL_SIZE = 7626+27+ const val PRODUCT_TAG = 0x01.toByte()28+ const val PLAN_TAG = 0x01.toByte()29+ const val VERSION_TAG = 0x01.toByte()30+ }31+32+ private val masterKey = MasterKey.Builder(context)33+ .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)34+ .build()35+36+ private val prefs = EncryptedSharedPreferences.create(37+ context,38+ PREFS_FILE,39+ masterKey,40+ EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,41+ EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,42+ )43+44+ fun storeLicense(key: String) {45+ prefs.edit().putString(KEY_LICENSE, key).apply()46+ prefs.edit().remove(KEY_PRO_CELEBRATED).apply()47+ }48+49+ fun getLicenseKey(): String? = prefs.getString(KEY_LICENSE, null)50+51+ fun clearLicense() = prefs.edit().remove(KEY_LICENSE).apply()52+53+ fun isProCelebrated(): Boolean = prefs.getBoolean(KEY_PRO_CELEBRATED, false)54+55+ fun markProCelebrated() = prefs.edit().putBoolean(KEY_PRO_CELEBRATED, true).apply()56+57+ fun isProActive(): Boolean = getLicenseKey()?.let(::validateLicense) == true58+59+ fun hasFeature(feature: ProFeature): Boolean = isProActive()60+61+ fun validateLicense(licenseKey: String): Boolean {62+ return try {63+ val decoded = decodeLicenseKey(licenseKey) ?: return false64+ if (decoded.size != TOTAL_SIZE) return false65+ val payload = decoded.copyOfRange(0, PAYLOAD_SIZE)66+ val signature = decoded.copyOfRange(PAYLOAD_SIZE, TOTAL_SIZE)67+ if (payload[0] != PRODUCT_TAG) return false68+ if (payload[1] != PLAN_TAG) return false69+ if (payload[2] != VERSION_TAG) return false70+ verifySignature(payload, signature)71+ } catch (_: Exception) {72+ false73+ }74+ }75+76+ private fun decodeLicenseKey(key: String): ByteArray? {77+ if (!key.startsWith("PPK-")) return null78+ val encoded = key.removePrefix("PPK-").replace("-", "")79+ return base58Decode(encoded)80+ }81+82+ private fun base58Decode(input: String): ByteArray? {83+ return try {84+ var n = BigInteger.ZERO85+ for (char in input) {86+ val index = BASE58_ALPHABET.indexOf(char)87+ if (index < 0) return null88+ n = n.multiply(BigInteger.valueOf(58)).add(BigInteger.valueOf(index.toLong()))89+ }90+ val bytes = n.toByteArray()91+ if (bytes.isNotEmpty() && bytes[0] == 0.toByte()) bytes.copyOfRange(1, bytes.size) else bytes92+ } catch (_: Exception) {93+ null94+ }95+ }96+97+ private fun verifySignature(payload: ByteArray, signature: ByteArray): Boolean {98+ return try {99+ val publicKeyBytes = hexToBytes(PUBLIC_KEY_HEX)100+ val keyFactory = KeyFactory.getInstance("Ed25519")101+ val derPrefix = byteArrayOf(102+ 0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65,103+ 0x70, 0x03, 0x21, 0x00,104+ )105+ val encoded = derPrefix + publicKeyBytes106+ val publicKey = keyFactory.generatePublic(X509EncodedKeySpec(encoded))107+ val sig = Signature.getInstance("Ed25519")108+ sig.initVerify(publicKey)109+ sig.update(payload)110+ sig.verify(signature)111+ } catch (_: Exception) {112+ false113+ }114+ }115+116+ private fun hexToBytes(hex: String): ByteArray {117+ val len = hex.length118+ val data = ByteArray(len / 2)119+ for (i in 0 until len step 2) {120+ data[i / 2] = ((Character.digit(hex[i], 16) shl 4) +121+ Character.digit(hex[i + 1], 16)).toByte()122+ }123+ return data124+ }125+}app/src/main/java/com/peachpasswords/license/ProFeature.kt+11 −0
@@ -0,0 +1,11 @@1+package com.peachpasswords.license2+3+sealed class ProFeature(val key: String) {4+ data object Sync : ProFeature("sync")5+ data object Passkeys : ProFeature("passkeys")6+ data object AdvancedHealth : ProFeature("advanced_health")7+ data object IosApp : ProFeature("ios_app")8+ data object Codex : ProFeature("codex")9+ data object CanaryEntry : ProFeature("canary_entry")10+ data object DuressVault : ProFeature("duress_vault")11+}app/src/main/java/com/peachpasswords/passkeys/PeachCredentialProviderService.kt+42 −0
@@ -0,0 +1,42 @@1+package com.peachpasswords.passkeys2+3+import android.os.Build4+import android.os.CancellationSignal5+import androidx.credentials.provider.BeginCreateCredentialRequest6+import androidx.credentials.provider.BeginCreateCredentialResponse7+import androidx.credentials.provider.BeginGetCredentialRequest8+import androidx.credentials.provider.BeginGetCredentialResponse9+import androidx.credentials.provider.CredentialProviderService10+import androidx.credentials.provider.ProviderClearCredentialStateRequest11+import android.os.OutcomeReceiver12+import androidx.credentials.exceptions.ClearCredentialException13+import androidx.credentials.exceptions.CreateCredentialException14+import androidx.credentials.exceptions.GetCredentialException15+import androidx.annotation.RequiresApi16+17+@RequiresApi(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)18+class PeachCredentialProviderService : CredentialProviderService() {19+ override fun onBeginGetCredentialRequest(20+ request: BeginGetCredentialRequest,21+ cancellationSignal: CancellationSignal,22+ callback: OutcomeReceiver<BeginGetCredentialResponse, GetCredentialException>,23+ ) {24+ // Scaffold: real passkey entries are added in the passkeys phase.25+ }26+27+ override fun onBeginCreateCredentialRequest(28+ request: BeginCreateCredentialRequest,29+ cancellationSignal: CancellationSignal,30+ callback: OutcomeReceiver<BeginCreateCredentialResponse, CreateCredentialException>,31+ ) {32+ // Scaffold: credential creation flow comes later.33+ }34+35+ override fun onClearCredentialStateRequest(36+ request: ProviderClearCredentialStateRequest,37+ cancellationSignal: CancellationSignal,38+ callback: OutcomeReceiver<Void?, ClearCredentialException>,39+ ) {40+ // Scaffold: no-op.41+ }42+}app/src/main/java/com/peachpasswords/qs/PeachTileService.kt+9 −0
@@ -0,0 +1,9 @@1+package com.peachpasswords.qs2+3+import android.service.quicksettings.TileService4+5+class PeachTileService : TileService() {6+ override fun onClick() {7+ super.onClick()8+ }9+}app/src/main/java/com/peachpasswords/shared/DomainUtils.kt+22 −0
@@ -0,0 +1,22 @@1+package com.peachpasswords.shared2+3+import okhttp3.internal.publicsuffix.PublicSuffixDatabase4+5+fun extractDomain(url: String): String? {6+ return try {7+ val normalized = if (url.startsWith("http")) url else "https://$url"8+ val host = java.net.URL(normalized).host.lowercase()9+ PublicSuffixDatabase.get().getEffectiveTldPlusOne(host)10+ } catch (_: Exception) {11+ null12+ }13+}14+15+fun getDisplayDomain(url: String): String {16+ return try {17+ val normalized = if (url.startsWith("http")) url else "https://$url"18+ java.net.URL(normalized).host19+ } catch (_: Exception) {20+ url21+ }22+}app/src/main/java/com/peachpasswords/sync/ChirpIdentity.kt+67 −0
@@ -0,0 +1,67 @@1+package com.peachpasswords.sync2+3+import android.content.Context4+import java.util.UUID5+6+private const val DEVICE_ID_KEY = "peach_chirp_device_id"7+private const val DEVICE_NAME_KEY = "peach_chirp_device_name"8+private const val PREFS_FILE = "peach_chirp_identity"9+10+data class LocalChirpIdentity(11+ val deviceId: String,12+ val deviceName: String,13+ val deviceType: DeviceType,14+ val longTermPublicKeyHex: String,15+ val signingPublicKeyHex: String,16+ val wsPort: Int? = null,17+)18+19+fun getOrCreateDeviceId(context: Context): String {20+ val prefs = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)21+ val current = prefs.getString(DEVICE_ID_KEY, null)22+ if (!current.isNullOrEmpty()) return current23+ val fresh = UUID.randomUUID().toString()24+ prefs.edit().putString(DEVICE_ID_KEY, fresh).apply()25+ return fresh26+}27+28+fun getDeviceName(context: Context): String {29+ val prefs = context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)30+ return prefs.getString(DEVICE_NAME_KEY, null).orEmpty().ifBlank { defaultDeviceName() }31+}32+33+fun setDeviceName(context: Context, name: String) {34+ val trimmed = name.trim()35+ require(trimmed.isNotEmpty()) { "device name must not be empty" }36+ require(trimmed.length <= 64) { "device name must be 64 chars or fewer" }37+ context.getSharedPreferences(PREFS_FILE, Context.MODE_PRIVATE)38+ .edit()39+ .putString(DEVICE_NAME_KEY, trimmed)40+ .apply()41+}42+43+fun buildLocalIdentity(context: Context, masterKey: ByteArray): LocalChirpIdentity {44+ val deviceId = getOrCreateDeviceId(context)45+ val deviceName = getDeviceName(context)46+ val kp = deriveSyncIdentityKeypair(masterKey, deviceId)47+ val signing = deriveSyncSigningKeypair(masterKey, deviceId)48+ return LocalChirpIdentity(49+ deviceId = deviceId,50+ deviceName = deviceName,51+ deviceType = extensionDeviceType(),52+ longTermPublicKeyHex = pubkeyToHex(kp.publicKey),53+ signingPublicKeyHex = pubkeyToHex(signing.publicKeyRaw),54+ )55+}56+57+fun deriveLocalSyncKeypair(masterKey: ByteArray, deviceId: String): SyncIdentityKeypair {58+ return deriveSyncIdentityKeypair(masterKey, deviceId)59+}60+61+private fun defaultDeviceName(): String {62+ return "Android"63+}64+65+private fun extensionDeviceType(): DeviceType {66+ return DeviceType.ANDROID67+}app/src/main/java/com/peachpasswords/sync/ChirpPairing.kt+633 −0
@@ -0,0 +1,633 @@1+package com.peachpasswords.sync2+3+import kotlinx.coroutines.async4+import kotlinx.coroutines.coroutineScope5+import kotlinx.coroutines.cancelAndJoin6+import kotlinx.coroutines.delay7+import kotlinx.coroutines.isActive8+import kotlinx.coroutines.withTimeoutOrNull9+import java.security.SecureRandom10+import java.util.concurrent.atomic.AtomicBoolean11+import org.bouncycastle.crypto.params.X25519PrivateKeyParameters12+13+const val CHIRP_PAIRING_PORT: Int = 4914214+15+interface PairingTransport {16+ suspend fun send(msg: ByteArray)17+ suspend fun receive(): ByteArray18+ suspend fun close()19+}20+21+data class PairingEndpoint(22+ val ip: String,23+ val port: Int,24+)25+26+data class PairingServer(27+ val transport: PairingTransport,28+ val peerIp: String,29+)30+31+data class PairingHandshakeResult(32+ val device: PairedDevice,33+ val sas: String,34+)35+36+enum class PairingRole {37+ INITIATOR,38+ RESPONDER,39+}40+41+interface ChirpPairingDeps {42+ suspend fun fetchLocalIdentity(): LocalChirpIdentity43+ suspend fun completePairing(paired: PairedDevice)44+ suspend fun confirmSAS(sas: String): Boolean45+ suspend fun cacheLastKnownIp(pubkeyHex: String, ip: String)46+ suspend fun getLocalSubnet(): String?47+ suspend fun openPairingTransport(endpoint: PairingEndpoint): PairingTransport48+ suspend fun openPairingServer(): PairingServer49+ suspend fun openAudio(): AudioIO50+ val chirpTimeoutMs: Long51+ fun onProgress(progress: PairingProgress)52+}53+54+class ChirpPairingFailure(55+ val phase: PairingPhase,56+ message: String,57+) : Error(message)58+59+interface AudioIO {60+ val sampleRate: Int61+ suspend fun play(waveform: FloatArray)62+ suspend fun pullSamples(): FloatArray63+ suspend fun close()64+}65+66+interface PairingKeyPair {67+ val publicKey: ByteArray68+ val secretKey: ByteArray69+}70+71+private data class PairingX25519KeyPair(72+ override val publicKey: ByteArray,73+ override val secretKey: ByteArray,74+) : PairingKeyPair75+76+data class PairingAttempt(77+ val ephemeralPrivateKey: ByteArray,78+ val ephemeralPublicKey: ByteArray,79+ val sessionNonce: ByteArray,80+ val outgoingPayload: ChirpPayload,81+)82+83+fun createPairingAttempt(deviceType: Byte): PairingAttempt {84+ val kp = generatePairingKeyPair()85+ val nonce = ByteArray(16)86+ secureRandom().nextBytes(nonce)87+ return PairingAttempt(88+ ephemeralPrivateKey = kp.secretKey,89+ ephemeralPublicKey = kp.publicKey,90+ sessionNonce = nonce,91+ outgoingPayload = ChirpPayload(92+ version = CHIRP_PROTOCOL_VERSION,93+ deviceType = deviceType,94+ ephemeralPublicKey = kp.publicKey,95+ sessionNonce = nonce,96+ ),97+ )98+}99+100+data class ChirpExchangeResult(101+ val remoteChirp: ChirpPayload,102+)103+104+data class ChirpExchangeOptions(105+ val attempt: PairingAttempt,106+ val timeoutMs: Long = DEFAULT_CHIRP_TIMEOUT_MS,107+ val onDiscard: ((ChirpDecodeError.Kind) -> Unit)? = null,108+ val onChirpPlayed: ((Int) -> Unit)? = null,109+)110+111+enum class ChirpExchangeErrorKind {112+ TIMEOUT,113+ VERSION_MISMATCH,114+ MIC_DENIED,115+ AUDIO_UNAVAILABLE,116+}117+118+class ChirpExchangeError(119+ val kind: ChirpExchangeErrorKind,120+ message: String? = null,121+) : Error(message ?: kind.name.lowercase())122+123+private const val CHIRP_LOOP_INTERVAL_MS = 4_000L124+private const val DEFAULT_CHIRP_TIMEOUT_MS = 90_000L125+private const val LISTEN_FRAME_SAMPLES = 4096126+127+fun generatePairingKeyPair(): PairingKeyPair {128+ val priv = X25519PrivateKeyParameters(secureRandom())129+ return PairingX25519KeyPair(130+ publicKey = priv.generatePublicKey().encoded,131+ secretKey = priv.encoded,132+ )133+}134+135+private fun secureRandom(): SecureRandom = SecureRandom()136+137+private fun sameBytes(a: ByteArray, b: ByteArray): Boolean {138+ if (a.size != b.size) return false139+ for (i in a.indices) {140+ if (a[i] != b[i]) return false141+ }142+ return true143+}144+145+/**146+ * Run the two-chirp exchange against a provided audio interface.147+ *148+ * This is a direct port of the browser coordinator logic. The codec and149+ * audio bridge are injectable so the protocol can be unit-tested before the150+ * Android-native ggwave bridge lands.151+ */152+suspend fun runChirpExchange(153+ io: AudioIO,154+ opts: ChirpExchangeOptions,155+ codecFactory: ChirpCodecFactory = ::createChirpCodec,156+): ChirpExchangeResult {157+ return coroutineScope {158+ val codec = codecFactory(159+ ChirpCodecOptions(160+ sampleRate = io.sampleRate,161+ protocol = GgwaveProtocol.ULTRASOUND_FASTEST,162+ volumePercent = 10,163+ ),164+ )165+ val ourBytes = encodeChirpPayload(opts.attempt.outgoingPayload)166+ val ourWaveform = codec.encode(ourBytes)167+168+ val deadline = System.currentTimeMillis() + opts.timeoutMs169+ val stopped = AtomicBoolean(false)170+171+ val playLoop = async {172+ var playCount = 0173+ while (isActive && !stopped.get() && System.currentTimeMillis() < deadline) {174+ try {175+ io.play(ourWaveform)176+ playCount++177+ opts.onChirpPlayed?.invoke(playCount)178+ } catch (_: Throwable) {179+ // Play failures are non-fatal; keep listening.180+ }181+ if (stopped.get()) break182+ val remaining = deadline - System.currentTimeMillis()183+ val wait = minOf(CHIRP_LOOP_INTERVAL_MS, maxOf(0L, remaining))184+ if (wait <= 0L) break185+ delay(wait)186+ }187+ }188+189+ try {190+ while (System.currentTimeMillis() < deadline && !stopped.get()) {191+ val samples = io.pullSamples()192+ if (samples.isEmpty()) {193+ delay(50)194+ continue195+ }196+197+ val decoded = codec.decode(samples)198+ if (decoded == null) continue199+ if (decoded.size != CHIRP_PAYLOAD_LENGTH) {200+ opts.onDiscard?.invoke(ChirpDecodeError.Kind.LENGTH)201+ continue202+ }203+204+ try {205+ val payload = decodeChirpPayload(decoded)206+ if (sameBytes(payload.ephemeralPublicKey, opts.attempt.ephemeralPublicKey)) {207+ continue208+ }209+ if (payload.version != CHIRP_PROTOCOL_VERSION) {210+ throw ChirpExchangeError(ChirpExchangeErrorKind.VERSION_MISMATCH)211+ }212+ stopped.set(true)213+ return@coroutineScope ChirpExchangeResult(remoteChirp = payload)214+ } catch (err: ChirpExchangeError) {215+ throw err216+ } catch (err: ChirpDecodeError) {217+ if (err.kind == ChirpDecodeError.Kind.VERSION) {218+ throw ChirpExchangeError(ChirpExchangeErrorKind.VERSION_MISMATCH)219+ }220+ opts.onDiscard?.invoke(err.kind)221+ continue222+ }223+ }224+ throw ChirpExchangeError(ChirpExchangeErrorKind.TIMEOUT)225+ } finally {226+ stopped.set(true)227+ codec.free()228+ playLoop.cancelAndJoin()229+ try {230+ io.close()231+ } catch (_: Throwable) {232+ // ignore233+ }234+ }235+ }236+}237+238+suspend fun openAndroidAudioIO(): AudioIO {239+ throw ChirpExchangeError(240+ ChirpExchangeErrorKind.AUDIO_UNAVAILABLE,241+ "Android audio bridge is not yet implemented",242+ )243+}244+245+suspend fun runChirpPairing(246+ deps: ChirpPairingDeps,247+ role: PairingRole = PairingRole.RESPONDER,248+ codecFactory: ChirpCodecFactory = ::createChirpCodec,249+): PairedDevice {250+ deps.onProgress(PairingProgress(phase = PairingPhase.IDLE))251+252+ val localIdentity = deps.fetchLocalIdentity()253+254+ if (role == PairingRole.RESPONDER && localIdentity.deviceType != DeviceType.EXTENSION) {255+ throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, "responder requires extension identity")256+ }257+ if (role == PairingRole.INITIATOR && localIdentity.deviceType == DeviceType.EXTENSION) {258+ throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, "initiator requires non-extension identity")259+ }260+261+ deps.onProgress(PairingProgress(phase = PairingPhase.LISTENING))262+263+ val deviceTypeByte = when (localIdentity.deviceType) {264+ DeviceType.ANDROID -> deviceTypeToByte(DeviceType.ANDROID)265+ DeviceType.IOS -> deviceTypeToByte(DeviceType.IOS)266+ DeviceType.DESKTOP -> deviceTypeToByte(DeviceType.DESKTOP)267+ DeviceType.EXTENSION -> deviceTypeToByte(DeviceType.EXTENSION)268+ }269+ val attempt = createPairingAttempt(deviceTypeByte)270+271+ val remoteChirpPublicKey: ByteArray272+ try {273+ val audio = deps.openAudio()274+ val result = runChirpExchange(275+ io = audio,276+ opts = ChirpExchangeOptions(277+ attempt = attempt,278+ timeoutMs = deps.chirpTimeoutMs,279+ ),280+ codecFactory = codecFactory,281+ )282+ remoteChirpPublicKey = result.remoteChirp.ephemeralPublicKey283+ } catch (err: ChirpExchangeError) {284+ val phase = when (err.kind) {285+ ChirpExchangeErrorKind.TIMEOUT -> PairingPhase.TIMEOUT286+ ChirpExchangeErrorKind.VERSION_MISMATCH -> PairingPhase.VERSION_MISMATCH287+ ChirpExchangeErrorKind.MIC_DENIED -> PairingPhase.MIC_DENIED288+ ChirpExchangeErrorKind.AUDIO_UNAVAILABLE -> PairingPhase.HANDSHAKE_FAILED289+ }290+ deps.onProgress(PairingProgress(phase = phase, errorMessage = err.message))291+ throw ChirpPairingFailure(phase, err.message ?: phase.wireValue)292+ }293+294+ deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE))295+296+ if (role == PairingRole.RESPONDER) {297+ return runResponderHandshake(deps, attempt, localIdentity)298+ }299+ return runInitiatorHandshake(deps, remoteChirpPublicKey, localIdentity)300+}301+302+private suspend fun runResponderHandshake(303+ deps: ChirpPairingDeps,304+ attempt: PairingAttempt,305+ localIdentity: LocalChirpIdentity,306+): PairedDevice {307+ val subnet = deps.getLocalSubnet()308+ if (subnet.isNullOrBlank()) {309+ deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = "no_subnet"))310+ throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, "could not determine local subnet")311+ }312+313+ val peerEndpoint = firstResponsivePeer(deps, subnet, CHIRP_PAIRING_PORT)314+ if (peerEndpoint == null) {315+ deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = "peer_not_found"))316+ throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, "could not reach paired peer on subnet")317+ }318+319+ val transport = deps.openPairingTransport(peerEndpoint)320+ val result = try {321+ runPairingResponder(322+ ourEphemeralPrivateKey = attempt.ephemeralPrivateKey,323+ ourEphemeralPublicKey = attempt.ephemeralPublicKey,324+ ourIdentity = localIdentity,325+ transport = transport,326+ )327+ } catch (err: Throwable) {328+ try {329+ transport.close()330+ } catch (_: Throwable) {331+ // ignore332+ }333+ deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = err.message))334+ throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, err.message ?: "handshake failed")335+ }336+ transport.close()337+338+ val paired = gateOnSAS(deps, result)339+ deps.completePairing(paired)340+ deps.cacheLastKnownIp(paired.longTermPublicKeyHex.orEmpty(), peerEndpoint.ip)341+ deps.onProgress(PairingProgress(phase = PairingPhase.PAIRED, peerDeviceName = paired.deviceName))342+ return paired343+}344+345+private suspend fun gateOnSAS(346+ deps: ChirpPairingDeps,347+ result: PairingHandshakeResult,348+): PairedDevice {349+ val confirmed = try {350+ deps.confirmSAS(result.sas)351+ } catch (err: Throwable) {352+ deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = err.message))353+ throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, err.message ?: "handshake failed")354+ }355+ if (!confirmed) {356+ deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = "sas_rejected"))357+ throw ChirpPairingFailure(358+ PairingPhase.HANDSHAKE_FAILED,359+ "pairing rejected - the verification codes did not match",360+ )361+ }362+ return result.device363+}364+365+private suspend fun runInitiatorHandshake(366+ deps: ChirpPairingDeps,367+ remoteChirpPublicKey: ByteArray,368+ localIdentity: LocalChirpIdentity,369+): PairedDevice {370+ val server = try {371+ deps.openPairingServer()372+ } catch (err: Throwable) {373+ deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = err.message))374+ throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, err.message ?: "handshake failed")375+ }376+377+ val result = try {378+ runPairingInitiator(remoteChirpPublicKey, localIdentity, server.transport)379+ } catch (err: Throwable) {380+ try {381+ server.transport.close()382+ } catch (_: Throwable) {383+ // ignore384+ }385+ deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = err.message))386+ throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, err.message ?: "handshake failed")387+ }388+ server.transport.close()389+390+ val paired = gateOnSAS(deps, result)391+ deps.completePairing(paired)392+ deps.cacheLastKnownIp(paired.longTermPublicKeyHex.orEmpty(), server.peerIp)393+ deps.onProgress(PairingProgress(phase = PairingPhase.PAIRED, peerDeviceName = paired.deviceName))394+ return paired395+}396+397+private suspend fun firstResponsivePeer(398+ deps: ChirpPairingDeps,399+ subnet: String,400+ port: Int,401+): PairingEndpoint? {402+ val probeTimeoutMs = 250L403+ val batch = 16404+ for (start in 1..254 step batch) {405+ val end = minOf(start + batch - 1, 254)406+ val ips = (start..end).map { "$subnet.$it" }407+ val results = coroutineScope {408+ ips.map { ip ->409+ async {410+ try {411+ val transport = withTimeoutOrNull(probeTimeoutMs) {412+ deps.openPairingTransport(PairingEndpoint(ip = ip, port = port))413+ }414+ if (transport != null) {415+ transport.close()416+ PairingEndpoint(ip = ip, port = port)417+ } else {418+ null419+ }420+ } catch (_: Throwable) {421+ null422+ }423+ }424+ }.mapNotNull { it.await() }425+ }426+ val hit = results.firstOrNull()427+ if (hit != null) return hit428+ }429+ return null430+}431+432+private suspend fun runPairingInitiator(433+ remoteEphemeralPublicKey: ByteArray,434+ ourIdentity: LocalChirpIdentity,435+ transport: PairingTransport,436+): PairingHandshakeResult {437+ val session = noiseNKInitiator(438+ remoteEphemeralPublicKey,439+ transport::send,440+ transport::receive,441+ )442+443+ transport.send(444+ session.encrypt(445+ encodePairingFrame(446+ PairingFrame(447+ type = "PAIR_IDENTITY",448+ deviceId = ourIdentity.deviceId,449+ deviceName = ourIdentity.deviceName,450+ deviceType = ourIdentity.deviceType,451+ longTermPublicKeyHex = ourIdentity.longTermPublicKeyHex,452+ signingPublicKeyHex = ourIdentity.signingPublicKeyHex,453+ wsPort = ourIdentity.wsPort,454+ ),455+ ),456+ ),457+ )458+459+ val theirCipher = transport.receive()460+ val theirPlain = session.decrypt(theirCipher)461+ val theirFrame = decodePairingFrame(theirPlain)462+ return PairingHandshakeResult(463+ device = frameToPairedDevice(theirFrame),464+ sas = SASDerivation.derive(session.handshakeHash),465+ )466+}467+468+private suspend fun runPairingResponder(469+ ourEphemeralPrivateKey: ByteArray,470+ ourEphemeralPublicKey: ByteArray,471+ ourIdentity: LocalChirpIdentity,472+ transport: PairingTransport,473+): PairingHandshakeResult {474+ val session = noiseNKResponder(475+ ourEphemeralPrivateKey,476+ ourEphemeralPublicKey,477+ transport::send,478+ transport::receive,479+ )480+481+ val theirCipher = transport.receive()482+ val theirPlain = session.decrypt(theirCipher)483+ val theirFrame = decodePairingFrame(theirPlain)484+485+ transport.send(486+ session.encrypt(487+ encodePairingFrame(488+ PairingFrame(489+ type = "PAIR_IDENTITY",490+ deviceId = ourIdentity.deviceId,491+ deviceName = ourIdentity.deviceName,492+ deviceType = ourIdentity.deviceType,493+ longTermPublicKeyHex = ourIdentity.longTermPublicKeyHex,494+ signingPublicKeyHex = ourIdentity.signingPublicKeyHex,495+ wsPort = ourIdentity.wsPort,496+ ),497+ ),498+ ),499+ )500+501+ return PairingHandshakeResult(502+ device = frameToPairedDevice(theirFrame),503+ sas = SASDerivation.derive(session.handshakeHash),504+ )505+}506+507+private data class PairingFrame(508+ val type: String,509+ val deviceId: String,510+ val deviceName: String,511+ val deviceType: DeviceType,512+ val longTermPublicKeyHex: String,513+ val signingPublicKeyHex: String? = null,514+ val wsPort: Int? = null,515+)516+517+private fun encodePairingFrame(frame: PairingFrame): ByteArray {518+ val builder = StringBuilder()519+ builder.append('{')520+ builder.append("\"type\":\"").append(frame.type).append('\"')521+ builder.append(",\"device_id\":\"").append(escapeJson(frame.deviceId)).append('\"')522+ builder.append(",\"device_name\":\"").append(escapeJson(frame.deviceName)).append('\"')523+ builder.append(",\"device_type\":\"").append(frame.deviceType.wireValue).append('\"')524+ builder.append(",\"long_term_public_key_hex\":\"").append(frame.longTermPublicKeyHex).append('\"')525+ if (!frame.signingPublicKeyHex.isNullOrBlank()) {526+ builder.append(",\"signing_public_key_hex\":\"").append(frame.signingPublicKeyHex).append('\"')527+ }528+ if (frame.wsPort != null) {529+ builder.append(",\"ws_port\":").append(frame.wsPort)530+ }531+ builder.append('}')532+ return builder.toString().encodeToByteArray()533+}534+535+private fun decodePairingFrame(bytes: ByteArray): PairingFrame {536+ val text = bytes.decodeToString()537+ val parsed = simpleJsonObject(text)538+ require(parsed["type"] == "PAIR_IDENTITY") { "expected PAIR_IDENTITY frame" }539+ val deviceId = parsed["device_id"] ?: error("device_id missing")540+ val deviceName = parsed["device_name"] ?: error("device_name missing")541+ val deviceType = when (parsed["device_type"]) {542+ "extension" -> DeviceType.EXTENSION543+ "android" -> DeviceType.ANDROID544+ "ios" -> DeviceType.IOS545+ "desktop" -> DeviceType.DESKTOP546+ else -> error("device_type missing")547+ }548+ val longTermPublicKeyHex = parsed["long_term_public_key_hex"] ?: error("long_term_public_key_hex missing")549+ require(longTermPublicKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {550+ "long_term_public_key_hex is not 32-byte hex"551+ }552+ val signingPublicKeyHex = parsed["signing_public_key_hex"]?.takeIf { it.isNotBlank() }553+ if (signingPublicKeyHex != null) {554+ require(signingPublicKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {555+ "signing_public_key_hex is not 32-byte hex"556+ }557+ }558+ val wsPort = parsed["ws_port"]?.toIntOrNull()559+ return PairingFrame(560+ type = "PAIR_IDENTITY",561+ deviceId = deviceId,562+ deviceName = deviceName,563+ deviceType = deviceType,564+ longTermPublicKeyHex = longTermPublicKeyHex,565+ signingPublicKeyHex = signingPublicKeyHex,566+ wsPort = wsPort,567+ )568+}569+570+private fun frameToPairedDevice(frame: PairingFrame): PairedDevice {571+ return PairedDevice(572+ deviceId = frame.deviceId,573+ deviceName = frame.deviceName,574+ deviceType = frame.deviceType.wireValue,575+ longTermPublicKeyHex = frame.longTermPublicKeyHex,576+ signingPublicKeyHex = frame.signingPublicKeyHex,577+ trustSource = "direct",578+ wsPort = frame.wsPort,579+ pairedAt = System.currentTimeMillis(),580+ )581+}582+583+private fun escapeJson(value: String): String {584+ return buildString(value.length) {585+ for (ch in value) {586+ when (ch) {587+ '\\' -> append("\\\\")588+ '"' -> append("\\\"")589+ '\b' -> append("\\b")590+ '\u000C' -> append("\\f")591+ '\n' -> append("\\n")592+ '\r' -> append("\\r")593+ '\t' -> append("\\t")594+ else -> append(ch)595+ }596+ }597+ }598+}599+600+private fun simpleJsonObject(text: String): Map<String, String> {601+ val trimmed = text.trim()602+ require(trimmed.startsWith("{") && trimmed.endsWith("}")) { "expected JSON object" }603+ val body = trimmed.substring(1, trimmed.length - 1).trim()604+ if (body.isEmpty()) return emptyMap()605+ val out = linkedMapOf<String, String>()606+ var i = 0607+ while (i < body.length) {608+ while (i < body.length && body[i].isWhitespace()) i++609+ require(i < body.length && body[i] == '"') { "expected string key" }610+ i++611+ val keyStart = i612+ while (i < body.length && body[i] != '"') i++613+ val key = body.substring(keyStart, i)614+ i++615+ while (i < body.length && (body[i].isWhitespace() || body[i] == ':')) i++616+ val value: String617+ if (i < body.length && body[i] == '"') {618+ i++619+ val valueStart = i620+ while (i < body.length && body[i] != '"') i++621+ value = body.substring(valueStart, i)622+ i++623+ } else {624+ val valueStart = i625+ while (i < body.length && body[i] != ',') i++626+ value = body.substring(valueStart, i).trim()627+ }628+ out[key] = value629+ while (i < body.length && body[i].isWhitespace()) i++630+ if (i < body.length && body[i] == ',') i++631+ }632+ return out633+}app/src/main/java/com/peachpasswords/sync/ChirpPayload.kt+109 −0
@@ -0,0 +1,109 @@1+package com.peachpasswords.sync2+3+class ChirpDecodeError(kind: Kind, message: String) : Error(message) {4+ enum class Kind {5+ LENGTH,6+ MAGIC,7+ VERSION,8+ DEVICE_TYPE,9+ CHECKSUM,10+ PADDING,11+ }12+13+ val kind: Kind = kind14+}15+16+data class ChirpPayload(17+ val version: Int,18+ val deviceType: Byte,19+ val ephemeralPublicKey: ByteArray,20+ val sessionNonce: ByteArray,21+)22+23+fun encodeChirpPayload(payload: ChirpPayload): ByteArray {24+ require(payload.ephemeralPublicKey.size == 32) { "ephemeralPublicKey must be 32 bytes" }25+ require(payload.sessionNonce.size == 16) { "sessionNonce must be 16 bytes" }26+27+ val buf = ByteArray(CHIRP_PAYLOAD_LENGTH)28+ CHIRP_MAGIC_BYTES.copyInto(buf, 0)29+ buf[4] = (payload.version and 0xff).toByte()30+ buf[5] = payload.deviceType31+ payload.ephemeralPublicKey.copyInto(buf, 6)32+ payload.sessionNonce.copyInto(buf, 38)33+34+ val crc = crc32(buf.copyOfRange(0, 54))35+ buf[54] = ((crc ushr 24) and 0xff).toByte()36+ buf[55] = ((crc ushr 16) and 0xff).toByte()37+ buf[56] = ((crc ushr 8) and 0xff).toByte()38+ buf[57] = (crc and 0xff).toByte()39+ return buf40+}41+42+fun decodeChirpPayload(buf: ByteArray): ChirpPayload {43+ if (buf.size != CHIRP_PAYLOAD_LENGTH) {44+ throw ChirpDecodeError(45+ ChirpDecodeError.Kind.LENGTH,46+ "chirp payload must be $CHIRP_PAYLOAD_LENGTH bytes, got ${buf.size}",47+ )48+ }49+ for (i in 0 until 4) {50+ if (buf[i] != CHIRP_MAGIC_BYTES[i]) {51+ throw ChirpDecodeError(ChirpDecodeError.Kind.MAGIC, "magic bytes are not PEAC")52+ }53+ }54+ val version = buf[4].toInt() and 0xff55+ if (version != CHIRP_PROTOCOL_VERSION) {56+ throw ChirpDecodeError(ChirpDecodeError.Kind.VERSION, "unsupported chirp protocol version $version")57+ }58+ val deviceType = buf[5]59+ if ((deviceType.toInt() and 0xff) !in 0x01..0x04) {60+ throw ChirpDecodeError(61+ ChirpDecodeError.Kind.DEVICE_TYPE,62+ "unknown device type byte 0x${(deviceType.toInt() and 0xff).toString(16)}",63+ )64+ }65+ val declared =66+ ((buf[54].toInt() and 0xff) shl 24) or67+ ((buf[55].toInt() and 0xff) shl 16) or68+ ((buf[56].toInt() and 0xff) shl 8) or69+ (buf[57].toInt() and 0xff)70+ val computed = crc32(buf.copyOfRange(0, 54))71+ if (declared != computed) {72+ throw ChirpDecodeError(ChirpDecodeError.Kind.CHECKSUM, "CRC32 mismatch")73+ }74+ for (i in 58 until CHIRP_PAYLOAD_LENGTH) {75+ if (buf[i] != 0.toByte()) {76+ throw ChirpDecodeError(ChirpDecodeError.Kind.PADDING, "reserved padding bytes must be zero")77+ }78+ }79+ return ChirpPayload(80+ version = version,81+ deviceType = deviceType,82+ ephemeralPublicKey = buf.copyOfRange(6, 38),83+ sessionNonce = buf.copyOfRange(38, 54),84+ )85+}86+87+private var crcTable: IntArray? = null88+89+private fun buildCrcTable(): IntArray {90+ val table = IntArray(256)91+ for (i in 0 until 256) {92+ var c = i93+ for (k in 0 until 8) {94+ c = if ((c and 1) != 0) (0xedb88320.toInt() xor (c ushr 1)) else (c ushr 1)95+ }96+ table[i] = c97+ }98+ return table99+}100+101+fun crc32(bytes: ByteArray): Int {102+ if (crcTable == null) crcTable = buildCrcTable()103+ var crc = -1104+ val table = crcTable!!105+ for (b in bytes) {106+ crc = table[(crc xor (b.toInt() and 0xff)) and 0xff] xor (crc ushr 8)107+ }108+ return crc xor -1109+}app/src/main/java/com/peachpasswords/sync/ChirpSyncTransport.kt+254 −0
@@ -0,0 +1,254 @@1+package com.peachpasswords.sync2+3+import kotlinx.coroutines.async4+import kotlinx.coroutines.awaitAll5+import kotlinx.coroutines.coroutineScope6+import kotlinx.coroutines.ExperimentalCoroutinesApi7+import kotlinx.coroutines.channels.Channel8+import kotlinx.coroutines.suspendCancellableCoroutine9+import kotlinx.coroutines.withTimeout10+import okhttp3.OkHttpClient11+import okhttp3.Request12+import okhttp3.Response13+import okhttp3.WebSocket14+import okhttp3.WebSocketListener15+import okio.ByteString.Companion.toByteString16+import java.io.IOException17+import java.util.concurrent.TimeUnit18+import java.util.concurrent.atomic.AtomicBoolean19+import kotlin.coroutines.resume20+import kotlin.coroutines.resumeWithException21+22+const val DEFAULT_PROBE_TIMEOUT_MS: Long = 50023+const val DEFAULT_PROBE_BATCH: Int = 1624+const val DEFAULT_CONNECT_TIMEOUT_MS: Long = 4_00025+const val SUBNET_PROBE_COOLDOWN_MS: Long = 60_00026+27+data class ChirpSyncSession(28+ val remoteStaticPublicKey: ByteArray,29+ val send: (ByteArray) -> Unit,30+ val receive: suspend () -> ByteArray,31+ val close: suspend () -> Unit,32+)33+34+data class SyncEndpoint(35+ val ip: String,36+ val port: Int,37+)38+39+private val lastProbeAt = mutableMapOf<String, Long>()40+private val webSocketClient = OkHttpClient.Builder().build()41+42+suspend fun openChirpSyncSession(43+ endpoint: SyncEndpoint,44+ ourLongTermPrivateKey: ByteArray,45+ ourLongTermPublicKey: ByteArray,46+ expectedRemotePubkeyHex: String,47+ connectTimeoutMs: Long = DEFAULT_CONNECT_TIMEOUT_MS,48+): ChirpSyncSession {49+ val connection = connectWebSocket(endpoint, connectTimeoutMs)50+51+ val session = try {52+ noiseXXInitiator(53+ ourLongTermPrivateKey,54+ ourLongTermPublicKey,55+ send = connection::send,56+ receive = connection::receive,57+ )58+ } catch (err: Throwable) {59+ connection.close()60+ throw err61+ }62+63+ val remoteHex = pubkeyToHex(session.remoteStaticPublicKey)64+ if (remoteHex != expectedRemotePubkeyHex) {65+ connection.close()66+ throw IllegalStateException(67+ "paired-device static key mismatch (got ${remoteHex.take(16)}…, expected ${expectedRemotePubkeyHex.take(16)}…)",68+ )69+ }70+ voidHex(expectedRemotePubkeyHex)71+72+ return ChirpSyncSession(73+ remoteStaticPublicKey = session.remoteStaticPublicKey,74+ send = { plaintext -> connection.send(session.encrypt(plaintext)) },75+ receive = { session.decrypt(connection.receive()) },76+ close = { connection.close() },77+ )78+}79+80+fun subnetProbeOnCooldown(81+ expectedRemotePubkeyHex: String,82+ now: Long = System.currentTimeMillis(),83+ cooldownMs: Long = SUBNET_PROBE_COOLDOWN_MS,84+): Boolean {85+ val last = lastProbeAt[expectedRemotePubkeyHex]86+ return last != null && now - last < cooldownMs87+}88+89+fun resetSubnetProbeCooldown() {90+ lastProbeAt.clear()91+}92+93+suspend fun probeSubnetForPeer(94+ subnet: String,95+ port: Int,96+ ourLongTermPrivateKey: ByteArray,97+ ourLongTermPublicKey: ByteArray,98+ expectedRemotePubkeyHex: String,99+ batch: Int = DEFAULT_PROBE_BATCH,100+ timeoutMs: Long = DEFAULT_PROBE_TIMEOUT_MS,101+ cooldownMs: Long = SUBNET_PROBE_COOLDOWN_MS,102+ now: Long = System.currentTimeMillis(),103+): SyncEndpoint? {104+ if (subnetProbeOnCooldown(expectedRemotePubkeyHex, now, cooldownMs)) {105+ return null106+ }107+ lastProbeAt[expectedRemotePubkeyHex] = now108+109+ for (start in 1..254 step batch) {110+ val end = minOf(start + batch - 1, 254)111+ val results = coroutineScope {112+ (start..end).map { i ->113+ val ip = "$subnet.$i"114+ async {115+ probeOne(116+ endpoint = SyncEndpoint(ip = ip, port = port),117+ ourLongTermPrivateKey = ourLongTermPrivateKey,118+ ourLongTermPublicKey = ourLongTermPublicKey,119+ expectedRemotePubkeyHex = expectedRemotePubkeyHex,120+ timeoutMs = timeoutMs,121+ )122+ }123+ }.awaitAll()124+ }125+ val hit = results.firstOrNull { it != null }126+ if (hit != null) return hit127+ }128+ return null129+}130+131+private suspend fun probeOne(132+ endpoint: SyncEndpoint,133+ ourLongTermPrivateKey: ByteArray,134+ ourLongTermPublicKey: ByteArray,135+ expectedRemotePubkeyHex: String,136+ timeoutMs: Long,137+): SyncEndpoint? {138+ return try {139+ val session = withTimeout(timeoutMs) {140+ openChirpSyncSession(141+ endpoint = endpoint,142+ ourLongTermPrivateKey = ourLongTermPrivateKey,143+ ourLongTermPublicKey = ourLongTermPublicKey,144+ expectedRemotePubkeyHex = expectedRemotePubkeyHex,145+ connectTimeoutMs = timeoutMs,146+ )147+ }148+ session.close()149+ endpoint150+ } catch (_: Throwable) {151+ null152+ }153+}154+155+private suspend fun connectWebSocket(156+ endpoint: SyncEndpoint,157+ timeoutMs: Long,158+): RawWebSocketConnection {159+ return withTimeout(timeoutMs) {160+ suspendCancellableCoroutine { cont ->161+ val request = Request.Builder()162+ .url("ws://${endpoint.ip}:${endpoint.port}/")163+ .build()164+ val connection = RawWebSocketConnection()165+ val listener = object : WebSocketListener() {166+ override fun onMessage(webSocket: WebSocket, bytes: okio.ByteString) {167+ connection.onMessage(bytes)168+ }169+170+ override fun onOpen(webSocket: WebSocket, response: Response) {171+ connection.install(webSocket)172+ if (cont.isActive) cont.resume(connection) else webSocket.cancel()173+ }174+175+ override fun onClosed(webSocket: WebSocket, code: Int, reason: String) {176+ connection.onClosed(IOException("WebSocket closed"))177+ }178+179+ override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) {180+ connection.onFailure(IOException("WebSocket connect to ${endpoint.ip}:${endpoint.port} errored", t))181+ if (cont.isActive) {182+ cont.resumeWithException(IOException("WebSocket connect to ${endpoint.ip}:${endpoint.port} errored", t))183+ }184+ }185+ }186+ val ws = webSocketClient.newWebSocket(request, listener)187+ connection.install(ws)188+ cont.invokeOnCancellation {189+ try {190+ ws.cancel()191+ } catch (_: Throwable) {192+ // ignore193+ }194+ }195+ }196+ }197+}198+199+private class RawWebSocketConnection {200+ private val inbox = Channel<ByteArray>(Channel.UNLIMITED)201+ private val closed = AtomicBoolean(false)202+ private var ws: WebSocket? = null203+204+ fun install(webSocket: WebSocket) {205+ ws = webSocket206+ }207+208+ fun onMessage(bytes: okio.ByteString) {209+ inbox.trySend(bytes.toByteArray())210+ }211+212+ @OptIn(ExperimentalCoroutinesApi::class)213+ fun onClosed(cause: Throwable) {214+ if (closed.compareAndSet(false, true)) {215+ inbox.close(cause)216+ }217+ }218+219+ fun onFailure(cause: Throwable) {220+ onClosed(cause)221+ }222+223+ fun send(bytes: ByteArray) {224+ val socket = ws ?: throw IOException("WebSocket not open")225+ if (!socket.send(bytes.toByteString())) {226+ throw IOException("WebSocket send failed")227+ }228+ }229+230+ suspend fun receive(): ByteArray {231+ if (closed.get() && inbox.isEmpty) {232+ throw IOException("WebSocket closed before frame")233+ }234+ return try {235+ inbox.receive()236+ } catch (err: kotlinx.coroutines.channels.ClosedReceiveChannelException) {237+ throw IOException("WebSocket closed before frame", err)238+ }239+ }240+241+ fun close() {242+ try {243+ onClosed(IOException("WebSocket closed"))244+ ws?.close(1000, null)245+ } catch (_: Throwable) {246+ // ignore247+ }248+ }249+}250+251+private fun voidHex(value: String) {252+ // Keep the expected pubkey source pinned in the call graph.253+ hexToPubkey(value)254+}app/src/main/java/com/peachpasswords/sync/ChirpTypes.kt+22 −0
@@ -0,0 +1,22 @@1+package com.peachpasswords.sync2+3+enum class DeviceType(val wireValue: String, val wireByte: Byte) {4+ EXTENSION("extension", 0x01),5+ ANDROID("android", 0x02),6+ IOS("ios", 0x03),7+ DESKTOP("desktop", 0x04),8+}9+10+val CHIRP_MAGIC_BYTES: ByteArray = byteArrayOf(0x50, 0x45, 0x41, 0x43)11+const val CHIRP_PROTOCOL_VERSION: Int = 0x0112+const val CHIRP_PAYLOAD_LENGTH: Int = 6413+14+fun deviceTypeFromByte(b: Byte): DeviceType = when (b.toInt() and 0xff) {15+ 0x01 -> DeviceType.EXTENSION16+ 0x02 -> DeviceType.ANDROID17+ 0x03 -> DeviceType.IOS18+ 0x04 -> DeviceType.DESKTOP19+ else -> throw IllegalArgumentException("unknown device type byte 0x${(b.toInt() and 0xff).toString(16)}")20+}21+22+fun deviceTypeToByte(t: DeviceType): Byte = t.wireByteapp/src/main/java/com/peachpasswords/sync/Ggwave.kt+41 −0
@@ -0,0 +1,41 @@1+package com.peachpasswords.sync2+3+enum class GgwaveProtocol {4+ AUDIBLE_NORMAL,5+ AUDIBLE_FAST,6+ AUDIBLE_FASTEST,7+ ULTRASOUND_NORMAL,8+ ULTRASOUND_FAST,9+ ULTRASOUND_FASTEST,10+ DT_NORMAL,11+ DT_FAST,12+ DT_FASTEST,13+}14+15+interface ChirpCodec {16+ fun encode(payload: ByteArray): FloatArray17+ fun decode(samples: FloatArray): ByteArray?18+ fun free()19+}20+21+data class ChirpCodecOptions(22+ val sampleRate: Int,23+ val protocol: GgwaveProtocol = GgwaveProtocol.ULTRASOUND_FASTEST,24+ val volumePercent: Int = 10,25+)26+27+typealias ChirpCodecFactory = suspend (ChirpCodecOptions) -> ChirpCodec28+29+/**30+ * Native ggwave binding placeholder.31+ *32+ * The browser source loads vendored JS/WASM at runtime. Android needs a33+ * platform-specific audio bridge plus native codec binding, which is a34+ * separate implementation step. The coordinator and tests inject their own35+ * codec so the pairing protocol can still be exercised now.36+ */37+suspend fun createChirpCodec(opts: ChirpCodecOptions): ChirpCodec {38+ throw UnsupportedOperationException(39+ "Android ggwave codec is not yet implemented (sampleRate=${opts.sampleRate})",40+ )41+}app/src/main/java/com/peachpasswords/sync/NoiseNK.kt+224 −0
@@ -0,0 +1,224 @@1+package com.peachpasswords.sync2+3+import org.bouncycastle.crypto.digests.Blake2sDigest4+import org.bouncycastle.crypto.digests.SHA256Digest5+import org.bouncycastle.crypto.generators.HKDFBytesGenerator6+import org.bouncycastle.crypto.modes.ChaCha20Poly13057+import org.bouncycastle.crypto.params.AEADParameters8+import org.bouncycastle.crypto.params.HKDFParameters9+import org.bouncycastle.crypto.params.KeyParameter10+import org.bouncycastle.crypto.params.X25519PrivateKeyParameters11+import org.bouncycastle.crypto.params.X25519PublicKeyParameters12+import java.nio.ByteBuffer13+import java.nio.ByteOrder14+import java.security.SecureRandom15+16+private const val NOISE_NK_PROTOCOL_NAME = "Noise_NK_25519_ChaChaPoly_BLAKE2s"17+18+interface NoiseNKSession {19+ fun encrypt(plaintext: ByteArray): ByteArray20+ fun decrypt(ciphertext: ByteArray): ByteArray21+ val handshakeHash: ByteArray22+}23+24+private data class NoiseNKKeyPair(25+ val publicKey: ByteArray,26+ val secretKey: ByteArray,27+)28+29+private fun initHash(): ByteArray {30+ val nameBytes = NOISE_NK_PROTOCOL_NAME.encodeToByteArray()31+ if (nameBytes.size <= 32) {32+ return ByteArray(32).also { nameBytes.copyInto(it) }33+ }34+ val sha = SHA256Digest()35+ sha.update(nameBytes, 0, nameBytes.size)36+ val out = ByteArray(32)37+ sha.doFinal(out, 0)38+ return out39+}40+41+private fun mixHash(h: ByteArray, data: ByteArray): ByteArray {42+ val blake = Blake2sDigest(256)43+ blake.update(h, 0, h.size)44+ blake.update(data, 0, data.size)45+ val out = ByteArray(32)46+ blake.doFinal(out, 0)47+ return out48+}49+50+private fun hkdf2(ck: ByteArray, ikm: ByteArray): Pair<ByteArray, ByteArray> {51+ val generator = HKDFBytesGenerator(SHA256Digest())52+ generator.init(HKDFParameters(ikm, ck, ByteArray(0)))53+ val out = ByteArray(64)54+ generator.generateBytes(out, 0, out.size)55+ return out.copyOfRange(0, 32) to out.copyOfRange(32, 64)56+}57+58+private fun nonceBytes(n: Long): ByteArray {59+ val buf = ByteArray(12)60+ ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).putLong(4, n)61+ return buf62+}63+64+private fun generateKeyPair(): NoiseNKKeyPair {65+ val priv = X25519PrivateKeyParameters(SecureRandom())66+ return NoiseNKKeyPair(67+ publicKey = priv.generatePublicKey().encoded,68+ secretKey = priv.encoded,69+ )70+}71+72+private fun sharedKey(privateKey: ByteArray, publicKey: ByteArray): ByteArray {73+ val priv = X25519PrivateKeyParameters(privateKey, 0)74+ val pub = X25519PublicKeyParameters(publicKey, 0)75+ val out = ByteArray(32)76+ priv.generateSecret(pub, out, 0)77+ return out78+}79+80+private fun chachaSeal(key: ByteArray, nonce: ByteArray, plaintext: ByteArray, aad: ByteArray): ByteArray {81+ val cipher = ChaCha20Poly1305()82+ cipher.init(true, AEADParameters(KeyParameter(key), 128, nonce, aad))83+ val out = ByteArray(cipher.getOutputSize(plaintext.size))84+ var len = cipher.processBytes(plaintext, 0, plaintext.size, out, 0)85+ len += cipher.doFinal(out, len)86+ return out.copyOf(len)87+}88+89+private fun chachaOpen(key: ByteArray, nonce: ByteArray, ciphertext: ByteArray, aad: ByteArray): ByteArray? {90+ return try {91+ val cipher = ChaCha20Poly1305()92+ cipher.init(false, AEADParameters(KeyParameter(key), 128, nonce, aad))93+ val out = ByteArray(cipher.getOutputSize(ciphertext.size))94+ var len = cipher.processBytes(ciphertext, 0, ciphertext.size, out, 0)95+ len += cipher.doFinal(out, len)96+ out.copyOf(len)97+ } catch (_: Throwable) {98+ null99+ }100+}101+102+suspend fun noiseNKInitiator(103+ responderStaticPublicKey: ByteArray,104+ send: suspend (ByteArray) -> Unit,105+ receive: suspend () -> ByteArray,106+): NoiseNKSession {107+ var h = initHash()108+ var ck = h.copyOf()109+110+ h = mixHash(h, responderStaticPublicKey)111+112+ val ephemeral = generateKeyPair()113+ h = mixHash(h, ephemeral.publicKey)114+ val es = sharedKey(ephemeral.secretKey, responderStaticPublicKey)115+ val (ck1, k1) = hkdf2(ck, es)116+ ck = ck1117+118+ val cipher1 = ChaCha20Poly1305()119+ cipher1.init(true, AEADParameters(KeyParameter(k1), 128, nonceBytes(0L), h))120+ val encrypted1 = ByteArray(cipher1.getOutputSize(0))121+ cipher1.doFinal(encrypted1, 0)122+ h = mixHash(h, encrypted1)123+124+ val msg1 = ByteArray(32 + encrypted1.size)125+ ephemeral.publicKey.copyInto(msg1, 0)126+ encrypted1.copyInto(msg1, 32)127+ send(msg1)128+129+ val msg2 = receive()130+ require(msg2.size >= 48) { "Noise NK: msg2 too short" }131+ val remoteEphemeralPublic = msg2.copyOfRange(0, 32)132+ val encrypted2 = msg2.copyOfRange(32, msg2.size)133+134+ h = mixHash(h, remoteEphemeralPublic)135+ val ee = sharedKey(ephemeral.secretKey, remoteEphemeralPublic)136+ val (ck2, k2) = hkdf2(ck, ee)137+ ck = ck2138+139+ val decrypted2 = chachaOpen(k2, nonceBytes(0L), encrypted2, h)140+ requireNotNull(decrypted2) { "Noise NK: msg2 auth failed — wrong responder key or MITM" }141+ h = mixHash(h, encrypted2)142+143+ val (sendKey, recvKey) = hkdf2(ck, ByteArray(0))144+ val sessionHash = h.copyOf()145+146+ var sendNonce = 0L147+ var recvNonce = 0L148+149+ return object : NoiseNKSession {150+ override fun encrypt(plaintext: ByteArray): ByteArray {151+ return chachaSeal(sendKey, nonceBytes(sendNonce++), plaintext, ByteArray(0))152+ }153+154+ override fun decrypt(ciphertext: ByteArray): ByteArray {155+ return chachaOpen(recvKey, nonceBytes(recvNonce++), ciphertext, ByteArray(0))156+ ?: throw IllegalStateException("Noise NK: decryption failed")157+ }158+159+ override val handshakeHash: ByteArray = sessionHash160+ }161+}162+163+suspend fun noiseNKResponder(164+ ourStaticPrivateKey: ByteArray,165+ ourStaticPublicKey: ByteArray,166+ send: suspend (ByteArray) -> Unit,167+ receive: suspend () -> ByteArray,168+): NoiseNKSession {169+ var h = initHash()170+ var ck = h.copyOf()171+172+ h = mixHash(h, ourStaticPublicKey)173+174+ val msg1 = receive()175+ require(msg1.size >= 48) { "Noise NK: msg1 too short" }176+ val remoteEphemeralPublic = msg1.copyOfRange(0, 32)177+ val encrypted1 = msg1.copyOfRange(32, msg1.size)178+179+ h = mixHash(h, remoteEphemeralPublic)180+ val es = sharedKey(ourStaticPrivateKey, remoteEphemeralPublic)181+ val (ck1, k1) = hkdf2(ck, es)182+ ck = ck1183+184+ val decrypted1 = chachaOpen(k1, nonceBytes(0L), encrypted1, h)185+ requireNotNull(decrypted1) { "Noise NK: msg1 auth failed — wrong static key or MITM" }186+ h = mixHash(h, encrypted1)187+188+ val ephemeral = generateKeyPair()189+ h = mixHash(h, ephemeral.publicKey)190+ val ee = sharedKey(ephemeral.secretKey, remoteEphemeralPublic)191+ val (ck2, k2) = hkdf2(ck, ee)192+ ck = ck2193+194+ val encrypted2 = chachaSeal(k2, nonceBytes(0L), ByteArray(0), h)195+ h = mixHash(h, encrypted2)196+197+ val msg2 = ByteArray(32 + encrypted2.size)198+ ephemeral.publicKey.copyInto(msg2, 0)199+ encrypted2.copyInto(msg2, 32)200+ send(msg2)201+202+ val (initiatorSendKey, responderSendKey) = hkdf2(ck, ByteArray(0))203+ val sessionHash = h.copyOf()204+205+ var sendNonce = 0L206+ var recvNonce = 0L207+208+ return object : NoiseNKSession {209+ override fun encrypt(plaintext: ByteArray): ByteArray {210+ return chachaSeal(responderSendKey, nonceBytes(sendNonce++), plaintext, ByteArray(0))211+ }212+213+ override fun decrypt(ciphertext: ByteArray): ByteArray {214+ return chachaOpen(initiatorSendKey, nonceBytes(recvNonce++), ciphertext, ByteArray(0))215+ ?: throw IllegalStateException("Noise NK: decryption failed")216+ }217+218+ override val handshakeHash: ByteArray = sessionHash219+ }220+}221+222+fun derivePairingSAS(handshakeHash: ByteArray): String {223+ return SASDerivation.derive(handshakeHash)224+}app/src/main/java/com/peachpasswords/sync/NoiseXX.kt+254 −0
@@ -0,0 +1,254 @@1+package com.peachpasswords.sync2+3+import org.bouncycastle.crypto.InvalidCipherTextException4+import org.bouncycastle.crypto.digests.Blake2sDigest5+import org.bouncycastle.crypto.digests.SHA256Digest6+import org.bouncycastle.crypto.generators.HKDFBytesGenerator7+import org.bouncycastle.crypto.modes.ChaCha20Poly13058+import org.bouncycastle.crypto.params.AEADParameters9+import org.bouncycastle.crypto.params.HKDFParameters10+import org.bouncycastle.crypto.params.KeyParameter11+import org.bouncycastle.crypto.params.X25519PrivateKeyParameters12+import org.bouncycastle.crypto.params.X25519PublicKeyParameters13+import java.nio.ByteBuffer14+import java.nio.ByteOrder15+import java.security.SecureRandom16+17+private const val PROTOCOL_NAME = "Noise_XX_25519_ChaChaPoly_BLAKE2s"18+19+private fun initHash(): ByteArray {20+ val nameBytes = PROTOCOL_NAME.encodeToByteArray()21+ if (nameBytes.size <= 32) {22+ return ByteArray(32).also { nameBytes.copyInto(it) }23+ }24+ val sha = SHA256Digest()25+ sha.update(nameBytes, 0, nameBytes.size)26+ val out = ByteArray(32)27+ sha.doFinal(out, 0)28+ return out29+}30+31+private fun mixHash(h: ByteArray, data: ByteArray): ByteArray {32+ val blake = Blake2sDigest(256)33+ blake.update(h, 0, h.size)34+ blake.update(data, 0, data.size)35+ val out = ByteArray(32)36+ blake.doFinal(out, 0)37+ return out38+}39+40+private fun hkdf2(ck: ByteArray, ikm: ByteArray): Pair<ByteArray, ByteArray> {41+ val generator = HKDFBytesGenerator(SHA256Digest())42+ generator.init(HKDFParameters(ikm, ck, ByteArray(0)))43+ val out = ByteArray(64)44+ generator.generateBytes(out, 0, out.size)45+ return out.copyOfRange(0, 32) to out.copyOfRange(32, 64)46+}47+48+private fun nonceBytes(n: Long): ByteArray {49+ val buf = ByteArray(12)50+ ByteBuffer.wrap(buf).order(ByteOrder.LITTLE_ENDIAN).putLong(4, n)51+ return buf52+}53+54+interface NoiseXXSession {55+ fun encrypt(plaintext: ByteArray): ByteArray56+ fun decrypt(ciphertext: ByteArray): ByteArray57+ val remoteStaticPublicKey: ByteArray58+ val handshakeHash: ByteArray59+}60+61+private data class X25519KeyPair(62+ val publicKey: ByteArray,63+ val secretKey: ByteArray,64+)65+66+private fun generateKeyPair(): X25519KeyPair {67+ val priv = X25519PrivateKeyParameters(SecureRandom())68+ return X25519KeyPair(69+ publicKey = priv.generatePublicKey().encoded,70+ secretKey = priv.encoded,71+ )72+}73+74+private fun sharedKey(privateKey: ByteArray, publicKey: ByteArray): ByteArray {75+ val priv = X25519PrivateKeyParameters(privateKey, 0)76+ val pub = X25519PublicKeyParameters(publicKey, 0)77+ val out = ByteArray(32)78+ priv.generateSecret(pub, out, 0)79+ return out80+}81+82+private fun chachaSeal(key: ByteArray, nonce: ByteArray, plaintext: ByteArray, aad: ByteArray): ByteArray {83+ val cipher = ChaCha20Poly1305()84+ cipher.init(true, AEADParameters(KeyParameter(key), 128, nonce, aad))85+ val out = ByteArray(cipher.getOutputSize(plaintext.size))86+ var len = cipher.processBytes(plaintext, 0, plaintext.size, out, 0)87+ len += cipher.doFinal(out, len)88+ return out.copyOf(len)89+}90+91+private fun chachaOpen(key: ByteArray, nonce: ByteArray, ciphertext: ByteArray, aad: ByteArray): ByteArray? {92+ return try {93+ val cipher = ChaCha20Poly1305()94+ cipher.init(false, AEADParameters(KeyParameter(key), 128, nonce, aad))95+ val out = ByteArray(cipher.getOutputSize(ciphertext.size))96+ var len = cipher.processBytes(ciphertext, 0, ciphertext.size, out, 0)97+ len += cipher.doFinal(out, len)98+ out.copyOf(len)99+ } catch (_: InvalidCipherTextException) {100+ null101+ }102+}103+104+suspend fun noiseXXInitiator(105+ ourStaticPrivateKey: ByteArray,106+ ourStaticPublicKey: ByteArray,107+ send: suspend (ByteArray) -> Unit,108+ receive: suspend () -> ByteArray,109+): NoiseXXSession {110+ var h = initHash()111+ var ck = h.copyOf()112+113+ val e = generateKeyPair()114+ h = mixHash(h, e.publicKey)115+ send(e.publicKey)116+117+ val msg2 = receive()118+ require(msg2.size >= 32 + 32 + 16 + 16) { "Noise XX: msg2 too short" }119+ val remoteEphemeral = msg2.copyOfRange(0, 32)120+ val encryptedStatic = msg2.copyOfRange(32, 32 + 32 + 16)121+ val encryptedPayload = msg2.copyOfRange(32 + 32 + 16, msg2.size)122+123+ h = mixHash(h, remoteEphemeral)124+ val ee = sharedKey(e.secretKey, remoteEphemeral)125+ val (ck1, k1) = hkdf2(ck, ee)126+ ck = ck1127+128+ val remoteStaticPlain = chachaOpen(k1, nonceBytes(0L), encryptedStatic, h)129+ ?: throw IllegalStateException("Noise XX: msg2 static auth failed")130+ require(remoteStaticPlain.size == 32) { "Noise XX: msg2 static auth failed" }131+ h = mixHash(h, encryptedStatic)132+133+ val es = sharedKey(e.secretKey, remoteStaticPlain)134+ val (ck2, k2) = hkdf2(ck, es)135+ ck = ck2136+137+ val payloadPlain = chachaOpen(k2, nonceBytes(0L), encryptedPayload, h)138+ ?: throw IllegalStateException("Noise XX: msg2 payload auth failed")139+ h = mixHash(h, encryptedPayload)140+ @Suppress("UNUSED_VARIABLE")141+ val _payloadPlain = payloadPlain142+143+ val encryptedOurStatic = chachaSeal(k2, nonceBytes(1L), ourStaticPublicKey, h)144+ h = mixHash(h, encryptedOurStatic)145+146+ val se = sharedKey(ourStaticPrivateKey, remoteEphemeral)147+ val (ck3, k3) = hkdf2(ck, se)148+ ck = ck3149+150+ val encryptedFinalPayload = chachaSeal(k3, nonceBytes(0L), ByteArray(0), h)151+ h = mixHash(h, encryptedFinalPayload)152+153+ val msg3 = ByteArray(encryptedOurStatic.size + encryptedFinalPayload.size)154+ encryptedOurStatic.copyInto(msg3, 0)155+ encryptedFinalPayload.copyInto(msg3, encryptedOurStatic.size)156+ send(msg3)157+158+ val (initSend, respSend) = hkdf2(ck, ByteArray(0))159+ val sendCipher = initSend160+ val recvCipher = respSend161+ var sendNonce = 0L162+ var recvNonce = 0L163+164+ return object : NoiseXXSession {165+ override fun encrypt(plaintext: ByteArray): ByteArray {166+ return chachaSeal(sendCipher, nonceBytes(sendNonce++), plaintext, ByteArray(0))167+ }168+169+ override fun decrypt(ciphertext: ByteArray): ByteArray {170+ return chachaOpen(recvCipher, nonceBytes(recvNonce++), ciphertext, ByteArray(0))171+ ?: throw IllegalStateException("Noise XX: decryption failed")172+ }173+174+ override val remoteStaticPublicKey: ByteArray = remoteStaticPlain175+ override val handshakeHash: ByteArray = h.copyOf()176+ }177+}178+179+suspend fun noiseXXResponder(180+ ourStaticPrivateKey: ByteArray,181+ ourStaticPublicKey: ByteArray,182+ send: suspend (ByteArray) -> Unit,183+ receive: suspend () -> ByteArray,184+): NoiseXXSession {185+ var h = initHash()186+ var ck = h.copyOf()187+188+ val msg1 = receive()189+ require(msg1.size >= 32) { "Noise XX: msg1 too short" }190+ val remoteEphemeral = msg1.copyOfRange(0, 32)191+ h = mixHash(h, remoteEphemeral)192+193+ val e = generateKeyPair()194+ h = mixHash(h, e.publicKey)195+ val ee = sharedKey(e.secretKey, remoteEphemeral)196+ val (ck1, k1) = hkdf2(ck, ee)197+ ck = ck1198+199+ val encryptedOurStatic = chachaSeal(k1, nonceBytes(0L), ourStaticPublicKey, h)200+ h = mixHash(h, encryptedOurStatic)201+202+ val es = sharedKey(ourStaticPrivateKey, remoteEphemeral)203+ val (ck2, k2) = hkdf2(ck, es)204+ ck = ck2205+206+ val encryptedPayload = chachaSeal(k2, nonceBytes(0L), ByteArray(0), h)207+ h = mixHash(h, encryptedPayload)208+209+ val msg2 = ByteArray(e.publicKey.size + encryptedOurStatic.size + encryptedPayload.size)210+ e.publicKey.copyInto(msg2, 0)211+ encryptedOurStatic.copyInto(msg2, e.publicKey.size)212+ encryptedPayload.copyInto(msg2, e.publicKey.size + encryptedOurStatic.size)213+ send(msg2)214+215+ val msg3 = receive()216+ require(msg3.size >= 32 + 16 + 16) { "Noise XX: msg3 too short" }217+ val encryptedRemoteStatic = msg3.copyOfRange(0, 32 + 16)218+ val encryptedFinalPayload = msg3.copyOfRange(32 + 16, msg3.size)219+220+ val remoteStaticPlain = chachaOpen(k2, nonceBytes(1L), encryptedRemoteStatic, h)221+ ?: throw IllegalStateException("Noise XX: msg3 static auth failed")222+ require(remoteStaticPlain.size == 32) { "Noise XX: msg3 static auth failed" }223+ h = mixHash(h, encryptedRemoteStatic)224+225+ val se = sharedKey(e.secretKey, remoteStaticPlain)226+ val (ck3, k3) = hkdf2(ck, se)227+ ck = ck3228+229+ val finalPayloadPlain = chachaOpen(k3, nonceBytes(0L), encryptedFinalPayload, h)230+ ?: throw IllegalStateException("Noise XX: msg3 final payload auth failed")231+ h = mixHash(h, encryptedFinalPayload)232+ @Suppress("UNUSED_VARIABLE")233+ val _finalPayloadPlain = finalPayloadPlain234+235+ val (initSend, respSend) = hkdf2(ck, ByteArray(0))236+ val sendCipher = respSend237+ val recvCipher = initSend238+ var sendNonce = 0L239+ var recvNonce = 0L240+241+ return object : NoiseXXSession {242+ override fun encrypt(plaintext: ByteArray): ByteArray {243+ return chachaSeal(sendCipher, nonceBytes(sendNonce++), plaintext, ByteArray(0))244+ }245+246+ override fun decrypt(ciphertext: ByteArray): ByteArray {247+ return chachaOpen(recvCipher, nonceBytes(recvNonce++), ciphertext, ByteArray(0))248+ ?: throw IllegalStateException("Noise XX: decryption failed")249+ }250+251+ override val remoteStaticPublicKey: ByteArray = remoteStaticPlain252+ override val handshakeHash: ByteArray = h.copyOf()253+ }254+}app/src/main/java/com/peachpasswords/sync/PairedDevice.kt+17 −0
@@ -0,0 +1,17 @@1+package com.peachpasswords.sync2+3+import kotlinx.serialization.Serializable4+5+@Serializable6+data class PairedDevice(7+ val deviceId: String,8+ val deviceName: String? = null,9+ val deviceType: String? = null,10+ val longTermPublicKeyHex: String? = null,11+ val signingPublicKeyHex: String? = null,12+ val trustSource: String? = null,13+ val wsPort: Int? = null,14+ val pairedAt: Long,15+ val lastSyncedAt: Long? = null,16+ val lastKnownIp: String? = null,17+)app/src/main/java/com/peachpasswords/sync/PairingProgress.kt+19 −0
@@ -0,0 +1,19 @@1+package com.peachpasswords.sync2+3+enum class PairingPhase(val wireValue: String) {4+ IDLE("idle"),5+ LISTENING("listening"),6+ CHIRPING("chirping"),7+ HANDSHAKE("handshake"),8+ PAIRED("paired"),9+ TIMEOUT("timeout"),10+ MIC_DENIED("mic_denied"),11+ VERSION_MISMATCH("version_mismatch"),12+ HANDSHAKE_FAILED("handshake_failed"),13+}14+15+data class PairingProgress(16+ val phase: PairingPhase,17+ val peerDeviceName: String? = null,18+ val errorMessage: String? = null,19+)app/src/main/java/com/peachpasswords/sync/SASDerivation.kt+12 −0
@@ -0,0 +1,12 @@1+package com.peachpasswords.sync2+3+object SASDerivation {4+ fun derive(handshakeHash: ByteArray): String {5+ require(handshakeHash.size >= 4) { "Handshake hash too short" }6+ val n = (((handshakeHash[0].toInt() and 0xFF) shl 24) or7+ ((handshakeHash[1].toInt() and 0xFF) shl 16) or8+ ((handshakeHash[2].toInt() and 0xFF) shl 8) or9+ (handshakeHash[3].toInt() and 0xFF)).toLong() and 0xFFFFFFFFL10+ return (n % 1_000_000L).toString().padStart(6, '0')11+ }12+}app/src/main/java/com/peachpasswords/sync/SyncIdentity.kt+89 −0
@@ -0,0 +1,89 @@1+package com.peachpasswords.sync2+3+import org.bouncycastle.crypto.digests.Blake3Digest4+import org.bouncycastle.crypto.params.X25519PrivateKeyParameters5+import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters6+import org.bouncycastle.crypto.generators.HKDFBytesGenerator7+import org.bouncycastle.crypto.params.HKDFParameters8+9+data class SyncIdentityKeypair(10+ val publicKey: ByteArray,11+ val secretKey: ByteArray,12+)13+14+data class SyncSigningKeypair(15+ val privateKey: Ed25519PrivateKeyParameters,16+ val publicKeyRaw: ByteArray,17+)18+19+private val SYNC_IDENTITY_SALT = "peach-sync-identity-v1".encodeToByteArray()20+private val SYNC_SIGNING_SALT = "peach-sync-signing-v1".encodeToByteArray()21+private val VAULT_ID_INFO = "peach-vault-id".encodeToByteArray()22+23+fun deriveSyncIdentityKeypair(masterKey: ByteArray, deviceId: String): SyncIdentityKeypair {24+ require(masterKey.isNotEmpty()) { "masterKey must not be empty" }25+ require(deviceId.isNotEmpty()) { "deviceId must not be empty" }26+ val info = deviceId.encodeToByteArray()27+ val seed = hkdf(masterKey, SYNC_IDENTITY_SALT, info, 32)28+ val priv = X25519PrivateKeyParameters(seed, 0)29+ return SyncIdentityKeypair(publicKey = priv.generatePublicKey().encoded, secretKey = seed)30+}31+32+fun computeVaultId(masterKey: ByteArray): String {33+ require(masterKey.isNotEmpty()) { "masterKey must not be empty" }34+ val buf = masterKey + VAULT_ID_INFO35+ val digest = Blake3Digest(256)36+ digest.update(buf, 0, buf.size)37+ val out = ByteArray(32)38+ digest.doFinal(out, 0)39+ return out.joinToString("") { "%02x".format(it) }40+}41+42+fun deriveSyncSigningKeypair(masterKey: ByteArray, deviceId: String): SyncSigningKeypair {43+ require(masterKey.isNotEmpty()) { "masterKey must not be empty" }44+ require(deviceId.isNotEmpty()) { "deviceId must not be empty" }45+ val info = deviceId.encodeToByteArray()46+ val seed = hkdf(masterKey, SYNC_SIGNING_SALT, info, 32)47+ val privateKey = Ed25519PrivateKeyParameters(seed, 0)48+ return SyncSigningKeypair(privateKey = privateKey, publicKeyRaw = privateKey.generatePublicKey().encoded)49+}50+51+fun verifyEd25519(publicKeyRaw: ByteArray, message: ByteArray, signature: ByteArray): Boolean {52+ return try {53+ if (publicKeyRaw.size != 32 || signature.size != 64) return false54+ val publicKey = org.bouncycastle.crypto.params.Ed25519PublicKeyParameters(publicKeyRaw, 0)55+ val verifier = org.bouncycastle.crypto.signers.Ed25519Signer()56+ verifier.init(false, publicKey)57+ verifier.update(message, 0, message.size)58+ verifier.verifySignature(signature)59+ } catch (_: Exception) {60+ false61+ }62+}63+64+fun signEd25519(privateKey: Ed25519PrivateKeyParameters, message: ByteArray): ByteArray {65+ val signer = org.bouncycastle.crypto.signers.Ed25519Signer()66+ signer.init(true, privateKey)67+ signer.update(message, 0, message.size)68+ return signer.generateSignature()69+}70+71+fun pubkeyToHex(pk: ByteArray): String = pk.joinToString("") { "%02x".format(it) }72+73+fun hexToPubkey(hex: String): ByteArray {74+ require(hex.length % 2 == 0) { "hex length must be even" }75+ val out = ByteArray(hex.length / 2)76+ for (i in out.indices) {77+ val byte = hex.substring(i * 2, i * 2 + 2).toInt(16)78+ out[i] = byte.toByte()79+ }80+ return out81+}82+83+private fun hkdf(ikm: ByteArray, salt: ByteArray, info: ByteArray, length: Int): ByteArray {84+ val generator = HKDFBytesGenerator(org.bouncycastle.crypto.digests.SHA256Digest())85+ generator.init(HKDFParameters(ikm, salt, info))86+ val out = ByteArray(length)87+ generator.generateBytes(out, 0, length)88+ return out89+}app/src/main/java/com/peachpasswords/sync/SyncStatus.kt+9 −0
@@ -0,0 +1,9 @@1+package com.peachpasswords.sync2+3+sealed class SyncStatus {4+ data object Idle : SyncStatus()5+ data object Syncing : SyncStatus()6+ data class LastSynced(val timestamp: Long) : SyncStatus()7+ data class Error(val message: String) : SyncStatus()8+ data object Offline : SyncStatus()9+}app/src/main/java/com/peachpasswords/ui/PeachAppNavHost.kt+99 −0
@@ -0,0 +1,99 @@1+package com.peachpasswords.ui2+3+import androidx.compose.animation.core.tween4+import androidx.compose.animation.fadeIn5+import androidx.compose.animation.fadeOut6+import androidx.compose.animation.slideInVertically7+import androidx.compose.animation.slideOutVertically8+import androidx.compose.runtime.Composable9+import androidx.navigation.NavHostController10+import androidx.navigation.NavType11+import androidx.navigation.compose.NavHost12+import androidx.navigation.compose.composable13+import androidx.navigation.compose.rememberNavController14+import androidx.navigation.navArgument15+import com.peachpasswords.ui.lock.LockScreen16+import com.peachpasswords.ui.screens.SimpleStub17+import com.peachpasswords.ui.settings.SettingsScreen18+import com.peachpasswords.ui.theme.PeachMotion19+import com.peachpasswords.ui.vault.EntryDetailScreen20+import com.peachpasswords.ui.vault.EntryEditScreen21+import com.peachpasswords.ui.vault.VaultListScreen22+23+@Composable24+fun PeachAppNavHost(25+ navController: NavHostController = rememberNavController(),26+ startDestination: PeachNav = PeachNav.Lock,27+) {28+ val nav: (PeachNav) -> Unit = { navController.navigate(it.route) }29+ val back: () -> Unit = { navController.popBackStack() }30+31+ NavHost(32+ navController = navController,33+ startDestination = startDestination.route,34+ enterTransition = {35+ slideInVertically(36+ initialOffsetY = { (it * 0.05f).toInt() },37+ animationSpec = tween(PeachMotion.Enter, easing = PeachMotion.Spring),38+ ) + fadeIn(tween(PeachMotion.Enter, easing = PeachMotion.Spring))39+ },40+ exitTransition = {41+ slideOutVertically(42+ targetOffsetY = { -(it * 0.03f).toInt() },43+ animationSpec = tween(PeachMotion.Exit, easing = PeachMotion.Retreat),44+ ) + fadeOut(tween(PeachMotion.Exit, easing = PeachMotion.Retreat))45+ },46+ popEnterTransition = {47+ fadeIn(tween(PeachMotion.Enter, easing = PeachMotion.Spring))48+ },49+ popExitTransition = {50+ slideOutVertically(51+ targetOffsetY = { (it * 0.05f).toInt() },52+ animationSpec = tween(PeachMotion.Exit, easing = PeachMotion.Retreat),53+ ) + fadeOut(tween(PeachMotion.Exit, easing = PeachMotion.Retreat))54+ },55+ ) {56+ composable(PeachNav.Lock.route) {57+ LockScreen(58+ onUnlocked = {59+ navController.navigate(PeachNav.VaultList.route) {60+ popUpTo(PeachNav.Lock.route) { inclusive = true }61+ }62+ },63+ onNavigate = nav,64+ )65+ }66+ composable(PeachNav.VaultList.route) { VaultListScreen(onNavigate = nav) }67+68+ composable(69+ route = PeachNav.EntryDetail.ROUTE,70+ arguments = listOf(navArgument("id") { type = NavType.StringType }),71+ ) { backStack ->72+ EntryDetailScreen(73+ id = backStack.arguments?.getString("id").orEmpty(),74+ onNavigate = nav,75+ onBack = back,76+ )77+ }78+ composable(79+ route = PeachNav.EntryEdit.ROUTE,80+ arguments = listOf(navArgument("id") { type = NavType.StringType; nullable = true }),81+ ) { backStack ->82+ EntryEditScreen(id = backStack.arguments?.getString("id"), onBack = back)83+ }84+85+ composable(PeachNav.Settings.route) { SettingsScreen(onBack = back, onNavigate = nav) }86+ composable(PeachNav.SettingsProtection.route) { SimpleStub("Protection", back) }87+ composable(PeachNav.SettingsVault.route) { SimpleStub("Vault settings", back) }88+ composable(PeachNav.SettingsSync.route) { SimpleStub("Sync", back) }89+ composable(PeachNav.SettingsAppearance.route) { SimpleStub("Appearance", back) }90+ composable(PeachNav.SettingsPro.route) { SimpleStub("Peach Pro", back) }91+ composable(PeachNav.CodexGenerate.route) { SimpleStub("Codex backup", back) }92+ composable(PeachNav.CodexRestore.route) { SimpleStub("Codex restore", back) }93+ composable(PeachNav.ChirpPair.route) { SimpleStub("Pair a device", back) }94+ composable(PeachNav.Health.route) { SimpleStub("Vault health", back) }95+ composable(PeachNav.Trash.route) { SimpleStub("Trash", back) }96+ composable(PeachNav.Import.route) { SimpleStub("Import", back) }97+ composable(PeachNav.Export.route) { SimpleStub("Export", back) }98+ }99+}app/src/main/java/com/peachpasswords/ui/PeachNav.kt+39 −0
@@ -0,0 +1,39 @@1+package com.peachpasswords.ui2+3+/**4+ * Every navigation destination in the app. [route] is the concrete route used5+ * with `navController.navigate(...)`; parameterized destinations expose a6+ * `ROUTE` pattern (with `{arg}` placeholders) for registration in the graph.7+ */8+sealed class PeachNav(val route: String) {9+ data object Lock : PeachNav("lock")10+ data object VaultList : PeachNav("vault")11+12+ data class EntryDetail(val id: String) : PeachNav("entry/$id") {13+ companion object {14+ const val ROUTE = "entry/{id}"15+ fun of(id: String) = "entry/$id"16+ }17+ }18+19+ data class EntryEdit(val id: String?) : PeachNav("edit?id=${id ?: ""}") {20+ companion object {21+ const val ROUTE = "edit?id={id}"22+ fun of(id: String?) = "edit?id=${id ?: ""}"23+ }24+ }25+26+ data object Settings : PeachNav("settings")27+ data object SettingsProtection : PeachNav("settings/protection")28+ data object SettingsVault : PeachNav("settings/vault")29+ data object SettingsSync : PeachNav("settings/sync")30+ data object SettingsAppearance : PeachNav("settings/appearance")31+ data object SettingsPro : PeachNav("settings/pro")32+ data object CodexGenerate : PeachNav("codex/generate")33+ data object CodexRestore : PeachNav("codex/restore")34+ data object ChirpPair : PeachNav("chirp/pair")35+ data object Health : PeachNav("health")36+ data object Trash : PeachNav("trash")37+ data object Import : PeachNav("import")38+ data object Export : PeachNav("export")39+}app/src/main/java/com/peachpasswords/ui/components/CharEnterText.kt+76 −0
@@ -0,0 +1,76 @@1+package com.peachpasswords.ui.components2+3+import androidx.compose.animation.core.animateFloatAsState4+import androidx.compose.animation.core.tween5+import androidx.compose.material3.Text6+import androidx.compose.runtime.Composable7+import androidx.compose.runtime.LaunchedEffect8+import androidx.compose.runtime.getValue9+import androidx.compose.runtime.mutableStateOf10+import androidx.compose.runtime.remember11+import androidx.compose.runtime.setValue12+import androidx.compose.ui.Modifier13+import androidx.compose.ui.graphics.graphicsLayer14+import androidx.compose.ui.layout.Layout15+import androidx.compose.ui.platform.LocalDensity16+import androidx.compose.ui.text.TextStyle17+import com.peachpasswords.ui.theme.LocalReduceMotion18+import com.peachpasswords.ui.theme.PeachMotion19+import kotlinx.coroutines.delay20+21+/**22+ * Per-character entrance: each glyph fades in and rises into place with a23+ * staggered delay. Port of the browser CharEnterText (PeachMotion.CharDelay /24+ * CharDuration). Respects reduce-motion by rendering instantly.25+ */26+@Composable27+fun CharEnterText(28+ text: String,29+ style: TextStyle,30+ modifier: Modifier = Modifier,31+) {32+ val reduceMotion = LocalReduceMotion.current33+ var visible by remember(text) { mutableStateOf(reduceMotion) }34+ LaunchedEffect(text) {35+ if (!reduceMotion) { delay(50); visible = true }36+ }37+ val density = LocalDensity.current38+ val riseStartPx = with(density) { (style.fontSize.toPx() * 0.22f) }39+40+ Layout(41+ modifier = modifier,42+ content = {43+ text.forEachIndexed { index, char ->44+ val alpha by animateFloatAsState(45+ targetValue = if (visible) 1f else 0f,46+ animationSpec = tween(PeachMotion.CharDuration, index * PeachMotion.CharDelay, PeachMotion.Spring),47+ label = "char-alpha",48+ )49+ val rise by animateFloatAsState(50+ targetValue = if (visible) 0f else riseStartPx,51+ animationSpec = tween(PeachMotion.CharDuration, index * PeachMotion.CharDelay, PeachMotion.Spring),52+ label = "char-rise",53+ )54+ Text(55+ text = char.toString(),56+ style = style,57+ modifier = Modifier.charState(alpha, rise),58+ )59+ }60+ },61+ ) { measurables, constraints ->62+ val placeables = measurables.map { it.measure(constraints) }63+ val width = placeables.sumOf { it.width }64+ val height = placeables.maxOfOrNull { it.height } ?: 065+ layout(width, height) {66+ var x = 067+ placeables.forEach { p ->68+ p.placeRelativeWithLayer(x, 0)69+ x += p.width70+ }71+ }72+ }73+}74+75+private fun Modifier.charState(alpha: Float, riseY: Float): Modifier =76+ this.graphicsLayer { this.alpha = alpha; this.translationY = riseY }app/src/main/java/com/peachpasswords/ui/components/FaviconInitials.kt+74 −0
@@ -0,0 +1,74 @@1+package com.peachpasswords.ui.components2+3+import androidx.compose.foundation.layout.Box4+import androidx.compose.foundation.layout.size5+import androidx.compose.foundation.shape.RoundedCornerShape6+import androidx.compose.material3.Text7+import androidx.compose.runtime.Composable8+import androidx.compose.ui.Alignment9+import androidx.compose.ui.Modifier10+import androidx.compose.ui.draw.clip11+import androidx.compose.ui.graphics.Color12+import androidx.compose.ui.draw.drawBehind13+import androidx.compose.ui.unit.Dp14+import androidx.compose.ui.unit.dp15+import androidx.compose.ui.unit.sp16+import com.peachpasswords.ui.theme.PeachColors17+import com.peachpasswords.ui.theme.PeachType18+19+/**20+ * Initials chip used in place of a network favicon (offline-first). Ports the21+ * browser titleInitials + titleBackground (deterministic HSL 32%/26%).22+ */23+@Composable24+fun FaviconInitials(source: String, modifier: Modifier = Modifier, size: Dp = 36.dp) {25+ val bg = titleBackground(source)26+ Box(27+ modifier = modifier28+ .size(size)29+ .clip(RoundedCornerShape(10.dp))30+ .drawBehind { drawRect(bg) },31+ contentAlignment = Alignment.Center,32+ ) {33+ Text(34+ text = titleInitials(source),35+ color = PeachColors.T0,36+ fontFamily = PeachType.Mono,37+ fontSize = (size.value * 0.34f).sp,38+ )39+ }40+}41+42+fun titleInitials(source: String): String {43+ val cleaned = source.replace(Regex("^https?://"), "").removePrefix("www.").trim()44+ if (cleaned.isEmpty()) return "·"45+ val words = cleaned.split(Regex("[\\s.\\-_/]+")).filter { it.isNotEmpty() }46+ if (words.size >= 2 && words[0].isNotEmpty() && words[1].isNotEmpty()) {47+ return (words[0][0].toString() + words[1][0].toString()).uppercase()48+ }49+ val single = words.firstOrNull() ?: cleaned50+ return single.take(2).uppercase()51+}52+53+/** Deterministic muted HSL(hue, 32%, 26%) background, matching the browser. */54+fun titleBackground(source: String): Color {55+ var hash = 056+ for (ch in source) hash = ((hash shl 5) - hash + ch.code)57+ val hue = (((hash % 360) + 360) % 360).toFloat()58+ return hsl(hue, 0.32f, 0.26f)59+}60+61+private fun hsl(h: Float, s: Float, l: Float): Color {62+ val c = (1f - kotlin.math.abs(2 * l - 1f)) * s63+ val x = c * (1f - kotlin.math.abs((h / 60f) % 2f - 1f))64+ val m = l - c / 2f65+ val (r, g, b) = when {66+ h < 60 -> Triple(c, x, 0f)67+ h < 120 -> Triple(x, c, 0f)68+ h < 180 -> Triple(0f, c, x)69+ h < 240 -> Triple(0f, x, c)70+ h < 300 -> Triple(x, 0f, c)71+ else -> Triple(c, 0f, x)72+ }73+ return Color(r + m, g + m, b + m)74+}app/src/main/java/com/peachpasswords/ui/components/LockRuneString.kt+70 −0
@@ -0,0 +1,70 @@1+package com.peachpasswords.ui.components2+3+import androidx.compose.animation.animateColorAsState4+import androidx.compose.foundation.layout.Row5+import androidx.compose.material3.Text6+import androidx.compose.runtime.Composable7+import androidx.compose.runtime.getValue8+import androidx.compose.runtime.mutableIntStateOf9+import androidx.compose.runtime.remember10+import androidx.compose.runtime.setValue11+import androidx.compose.ui.Modifier12+import androidx.compose.ui.graphics.Shadow13+import androidx.compose.ui.text.TextStyle14+import androidx.compose.ui.text.font.FontStyle15+import androidx.compose.ui.unit.sp16+import com.peachpasswords.ui.theme.LocalPeachAccent17+import com.peachpasswords.ui.theme.LocalReduceMotion18+import com.peachpasswords.ui.theme.PeachColors19+import com.peachpasswords.ui.theme.PeachType20+import kotlinx.coroutines.delay21+import androidx.compose.runtime.LaunchedEffect22+import kotlin.random.Random23+24+private const val RUNE_COUNT = 925+26+/**27+ * A faint row of PeachScript runes (Private Use Area glyphs). Mirrors the28+ * browser LockRuneCanvas: ~13sp, text at 12% opacity, and one rune periodically29+ * picks up the accent color with a soft glow before fading back.30+ */31+@Composable32+fun LockRuneString(modifier: Modifier = Modifier) {33+ val accent = LocalPeachAccent.current34+ val reduceMotion = LocalReduceMotion.current35+ val runes = remember {36+ (0 until RUNE_COUNT).map { (0xE000 + Random.nextInt(256)).toChar().toString() }37+ }38+ var glowIdx by remember { mutableIntStateOf(-1) }39+40+ if (!reduceMotion) {41+ LaunchedEffect(Unit) {42+ while (true) {43+ delay(1500L + Random.nextLong(3000))44+ glowIdx = Random.nextInt(RUNE_COUNT)45+ delay(2000L + Random.nextLong(1500))46+ glowIdx = -147+ }48+ }49+ }50+51+ Row(modifier = modifier) {52+ runes.forEachIndexed { idx, ch ->53+ val glowing = idx == glowIdx54+ val color by animateColorAsState(55+ targetValue = if (glowing) accent else PeachColors.T0.copy(alpha = 0.12f),56+ label = "rune-glow",57+ )58+ Text(59+ text = ch,60+ color = color,61+ style = TextStyle(62+ fontFamily = PeachType.Script,63+ fontStyle = FontStyle.Normal,64+ fontSize = 13.sp,65+ shadow = if (glowing) Shadow(color = accent, blurRadius = 12f) else null,66+ ),67+ )68+ }69+ }70+}app/src/main/java/com/peachpasswords/ui/components/PeachMark.kt+53 −0
@@ -0,0 +1,53 @@1+package com.peachpasswords.ui.components2+3+import androidx.compose.foundation.Canvas4+import androidx.compose.foundation.layout.size5+import androidx.compose.runtime.Composable6+import androidx.compose.runtime.remember7+import androidx.compose.ui.Modifier8+import androidx.compose.ui.geometry.Offset9+import androidx.compose.ui.geometry.Size10+import androidx.compose.ui.graphics.Color11+import androidx.compose.ui.graphics.drawscope.Stroke12+import androidx.compose.ui.graphics.drawscope.rotate13+import androidx.compose.ui.graphics.drawscope.scale14+import androidx.compose.ui.graphics.vector.PathParser15+import androidx.compose.ui.unit.Dp16+import androidx.compose.ui.unit.dp17+18+/**19+ * The Peach brand mark — a peach fruit with a single leaf. Exact port of the20+ * browser PeachMark.tsx SVG (viewBox 240×240). The leaf is ALWAYS sage green21+ * (#92AC65 fill, #5E7A42 vein) and the body is fixed peach tones — none of it22+ * is accent-driven. [alpha] dims the whole mark for the faint lock-screen art.23+ */24+@Composable25+fun PeachMark(26+ modifier: Modifier = Modifier,27+ size: Dp = 14.dp,28+ alpha: Float = 1f,29+) {30+ val leaf = remember { PathParser().parsePathString("M 124 64 C 134 32 168 16 200 22 C 198 56 168 72 130 66 Z").toPath() }31+ val vein = remember { PathParser().parsePathString("M 130 64 C 152 46 178 30 196 24").toPath() }32+ val bodyLight = remember { PathParser().parsePathString("M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 185 222 222 185 220 130 C 218 78 170 45 120 60 Z").toPath() }33+ val bodyShadow = remember { PathParser().parsePathString("M 120 60 C 75 45 28 75 22 130 C 18 185 65 222 125 222 C 105 195 75 150 100 90 C 105 75 112 65 120 60 Z").toPath() }34+35+ Canvas(modifier = modifier.size(size)) {36+ val s = this.size.minDimension / 240f37+ scale(scaleX = s, scaleY = s, pivot = Offset.Zero) {38+ drawPath(bodyLight, Color(0xFFFFB082), alpha = alpha)39+ drawPath(bodyShadow, Color(0xFFE5805C), alpha = alpha)40+ // Highlight ellipse: cx178 cy108 rx20 ry11, rotate(-26°).41+ rotate(degrees = -26f, pivot = Offset(178f, 108f)) {42+ drawOval(43+ color = Color(0xFFFFD0A8),44+ topLeft = Offset(178f - 20f, 108f - 11f),45+ size = Size(40f, 22f),46+ alpha = alpha * 0.7f,47+ )48+ }49+ drawPath(leaf, Color(0xFF92AC65), alpha = alpha)50+ drawPath(vein, Color(0xFF5E7A42), alpha = alpha, style = Stroke(width = 2.6f))51+ }52+ }53+}app/src/main/java/com/peachpasswords/ui/components/TOTPRing.kt+47 −0
@@ -0,0 +1,47 @@1+package com.peachpasswords.ui.components2+3+import androidx.compose.foundation.Canvas4+import androidx.compose.foundation.layout.size5+import androidx.compose.runtime.Composable6+import androidx.compose.runtime.getValue7+import androidx.compose.runtime.produceState8+import androidx.compose.ui.Modifier9+import androidx.compose.ui.geometry.Offset10+import androidx.compose.ui.geometry.Size11+import androidx.compose.ui.graphics.StrokeCap12+import androidx.compose.ui.graphics.drawscope.Stroke13+import androidx.compose.ui.unit.Dp14+import androidx.compose.ui.unit.dp15+import com.peachpasswords.ui.theme.LocalPeachAccent16+import com.peachpasswords.ui.theme.PeachColors17+import com.peachpasswords.vault.TOTPGenerator18+import kotlinx.coroutines.delay19+20+/**21+ * A small ring that sweeps once per TOTP period and turns breach-red in the22+ * final 5 seconds. Port of the brief's TOTPRing.23+ */24+@Composable25+fun TOTPRing(modifier: Modifier = Modifier, size: Dp = 28.dp) {26+ val accent = LocalPeachAccent.current27+ val progress by produceState(TOTPGenerator.periodProgress()) {28+ while (true) { value = TOTPGenerator.periodProgress(); delay(100) }29+ }30+ val isHot = TOTPGenerator.remainingSeconds() <= 531+32+ Canvas(modifier = modifier.size(size)) {33+ val stroke = 2.dp.toPx()34+ val radius = (this.size.minDimension - stroke) / 2f35+ val center = Offset(this.size.width / 2f, this.size.height / 2f)36+ drawCircle(color = PeachColors.T3, radius = radius, style = Stroke(stroke))37+ drawArc(38+ color = if (isHot) PeachColors.Breach else accent,39+ startAngle = -90f,40+ sweepAngle = 360f * progress,41+ useCenter = false,42+ style = Stroke(stroke, cap = StrokeCap.Round),43+ topLeft = Offset(center.x - radius, center.y - radius),44+ size = Size(radius * 2, radius * 2),45+ )46+ }47+}app/src/main/java/com/peachpasswords/ui/lock/BiometricUnlockActivity.kt+11 −0
@@ -0,0 +1,11 @@1+package com.peachpasswords.ui.lock2+3+import android.app.Activity4+import android.os.Bundle5+6+class BiometricUnlockActivity : Activity() {7+ override fun onCreate(savedInstanceState: Bundle?) {8+ super.onCreate(savedInstanceState)9+ finish()10+ }11+}app/src/main/java/com/peachpasswords/ui/lock/Biometrics.kt+40 −0
@@ -0,0 +1,40 @@1+package com.peachpasswords.ui.lock2+3+import android.content.Context4+import androidx.biometric.BiometricManager5+import androidx.biometric.BiometricManager.Authenticators.BIOMETRIC_STRONG6+import androidx.biometric.BiometricManager.Authenticators.DEVICE_CREDENTIAL7+import androidx.biometric.BiometricPrompt8+import androidx.core.content.ContextCompat9+import androidx.fragment.app.FragmentActivity10+11+/** Thin wrapper over androidx BiometricPrompt for the re-auth gate. */12+object Biometrics {13+ private const val AUTHENTICATORS = BIOMETRIC_STRONG or DEVICE_CREDENTIAL14+15+ fun isAvailable(context: Context): Boolean =16+ BiometricManager.from(context).canAuthenticate(AUTHENTICATORS) == BiometricManager.BIOMETRIC_SUCCESS17+18+ fun authenticate(19+ activity: FragmentActivity,20+ title: String,21+ subtitle: String,22+ onSuccess: () -> Unit,23+ onFail: () -> Unit = {},24+ ) {25+ val prompt = BiometricPrompt(26+ activity,27+ ContextCompat.getMainExecutor(activity),28+ object : BiometricPrompt.AuthenticationCallback() {29+ override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) = onSuccess()30+ override fun onAuthenticationError(errorCode: Int, errString: CharSequence) = onFail()31+ },32+ )33+ val info = BiometricPrompt.PromptInfo.Builder()34+ .setTitle(title)35+ .setSubtitle(subtitle)36+ .setAllowedAuthenticators(AUTHENTICATORS)37+ .build()38+ prompt.authenticate(info)39+ }40+}app/src/main/java/com/peachpasswords/ui/lock/LockScreen.kt+245 −0
@@ -0,0 +1,245 @@1+package com.peachpasswords.ui.lock2+3+import androidx.compose.animation.core.Animatable4+import androidx.compose.animation.core.keyframes5+import androidx.compose.foundation.background6+import androidx.compose.foundation.border7+import androidx.compose.foundation.clickable8+import androidx.compose.foundation.layout.Arrangement9+import androidx.compose.foundation.layout.Box10+import androidx.compose.foundation.layout.Column11+import androidx.compose.foundation.layout.Row12+import androidx.compose.foundation.layout.Spacer13+import androidx.compose.foundation.layout.fillMaxSize14+import androidx.compose.foundation.layout.offset15+import androidx.compose.foundation.layout.fillMaxWidth16+import androidx.compose.foundation.layout.height17+import androidx.compose.foundation.layout.padding18+import androidx.compose.foundation.layout.systemBarsPadding19+import androidx.compose.foundation.shape.RoundedCornerShape20+import androidx.compose.foundation.text.KeyboardActions21+import androidx.compose.foundation.text.KeyboardOptions22+import androidx.compose.material3.LocalTextStyle23+import androidx.compose.material3.Text24+import androidx.compose.runtime.Composable25+import androidx.compose.runtime.LaunchedEffect26+import androidx.compose.runtime.getValue27+import androidx.compose.runtime.mutableStateOf28+import androidx.compose.runtime.remember29+import androidx.compose.runtime.setValue30+import androidx.compose.ui.Alignment31+import androidx.compose.ui.Modifier32+import androidx.compose.ui.draw.alpha33+import androidx.compose.ui.graphics.Color34+import androidx.compose.ui.text.input.ImeAction35+import androidx.compose.ui.text.input.KeyboardType36+import androidx.compose.ui.text.input.PasswordVisualTransformation37+import androidx.compose.ui.text.font.FontStyle38+import androidx.compose.ui.text.font.FontWeight39+import androidx.compose.ui.text.style.TextAlign40+import androidx.compose.ui.unit.IntOffset41+import androidx.compose.ui.unit.dp42+import androidx.compose.ui.unit.sp43+import androidx.hilt.navigation.compose.hiltViewModel44+import androidx.compose.runtime.collectAsState45+import com.peachpasswords.ui.PeachNav46+import com.peachpasswords.ui.components.LockRuneString47+import com.peachpasswords.ui.components.PeachMark48+import com.peachpasswords.ui.theme.LocalPeachAccent49+import com.peachpasswords.ui.theme.PeachColors50+import com.peachpasswords.ui.theme.PeachType51+import com.peachpasswords.ui.theme.ShellBackground52+53+@Composable54+fun LockScreen(55+ onUnlocked: () -> Unit,56+ onNavigate: (PeachNav) -> Unit,57+ vm: LockViewModel = hiltViewModel(),58+) {59+ val state by vm.state.collectAsState()60+ val accent = LocalPeachAccent.current61+62+ var password by remember { mutableStateOf("") }63+ var confirm by remember { mutableStateOf("") }64+65+ LaunchedEffect(state.unlocked) { if (state.unlocked) onUnlocked() }66+67+ // Shake the password field on each failed unlock (matches the 300ms browser shake).68+ val shake = remember { Animatable(0f) }69+ LaunchedEffect(state.shakeNonce) {70+ if (state.shakeNonce > 0) {71+ shake.animateTo(72+ targetValue = 0f,73+ animationSpec = keyframes {74+ durationMillis = 30075+ 8f at 50; -8f at 100; 8f at 150; -8f at 200; 4f at 250; 0f at 30076+ },77+ )78+ }79+ }80+81+ // 400ms biometric trigger — dormant until enrollment lands (canTryBiometric == false).82+ LaunchedEffect(Unit) {83+ if (state.hasVault && vm.canTryBiometric()) {84+ kotlinx.coroutines.delay(400)85+ // biometric prompt wired with Protection settings86+ }87+ }88+89+ ShellBackground {90+ // Faint PeachMark art, top-right, 120dp at 12% opacity.91+ PeachMark(92+ modifier = Modifier93+ .align(Alignment.TopEnd)94+ .systemBarsPadding()95+ .padding(end = 20.dp, top = 8.dp),96+ size = 120.dp,97+ alpha = 0.12f,98+ )99+100+ Column(101+ modifier = Modifier102+ .fillMaxSize()103+ .systemBarsPadding()104+ .padding(horizontal = 32.dp),105+ verticalArrangement = Arrangement.Center,106+ horizontalAlignment = Alignment.CenterHorizontally,107+ ) {108+ Text(109+ text = "peach",110+ color = accent,111+ fontFamily = PeachType.Display,112+ fontStyle = FontStyle.Italic,113+ fontWeight = FontWeight.Light,114+ fontSize = 44.sp,115+ )116+ Spacer(Modifier.height(10.dp))117+ LockRuneString()118+ Spacer(Modifier.height(36.dp))119+120+ Box(modifier = Modifier.offset { IntOffset(shake.value.dp.roundToPx(), 0) }) {121+ Column(horizontalAlignment = Alignment.CenterHorizontally) {122+ PasswordField(123+ value = password,124+ onChange = { password = it; vm.clearError() },125+ placeholder = if (state.hasVault) "master password" else "create a master password",126+ imeAction = if (state.hasVault) ImeAction.Go else ImeAction.Next,127+ onImeAction = { if (state.hasVault) vm.unlock(password) },128+ )129+ if (!state.hasVault) {130+ Spacer(Modifier.height(12.dp))131+ PasswordField(132+ value = confirm,133+ onChange = { confirm = it; vm.clearError() },134+ placeholder = "confirm password",135+ imeAction = ImeAction.Go,136+ onImeAction = { vm.create(password, confirm) },137+ )138+ }139+ }140+ }141+142+ Spacer(Modifier.height(8.dp))143+ Text(144+ text = state.error ?: " ",145+ color = PeachColors.Breach,146+ fontFamily = PeachType.Mono,147+ fontSize = 11.sp,148+ textAlign = TextAlign.Center,149+ modifier = Modifier.height(20.dp),150+ )151+152+ Spacer(Modifier.height(8.dp))153+ PrimaryButton(154+ label = if (state.hasVault) "unlock" else "create vault",155+ enabled = !state.loading,156+ onClick = { if (state.hasVault) vm.unlock(password) else vm.create(password, confirm) },157+ )158+159+ if (!state.hasVault) {160+ Spacer(Modifier.height(28.dp))161+ RestoreTabs(onNavigate = onNavigate)162+ }163+ }164+ }165+}166+167+@Composable168+private fun PasswordField(169+ value: String,170+ onChange: (String) -> Unit,171+ placeholder: String,172+ imeAction: ImeAction,173+ onImeAction: () -> Unit,174+) {175+ androidx.compose.foundation.text.BasicTextField(176+ value = value,177+ onValueChange = onChange,178+ singleLine = true,179+ textStyle = LocalTextStyle.current.copy(180+ color = PeachColors.T0,181+ fontFamily = PeachType.Mono,182+ fontSize = 15.sp,183+ textAlign = TextAlign.Center,184+ ),185+ cursorBrush = androidx.compose.ui.graphics.SolidColor(LocalPeachAccent.current),186+ visualTransformation = PasswordVisualTransformation(),187+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = imeAction),188+ keyboardActions = KeyboardActions(onGo = { onImeAction() }, onNext = { onImeAction() }),189+ modifier = Modifier190+ .fillMaxWidth()191+ .border(1.dp, PeachColors.T3, RoundedCornerShape(12.dp))192+ .padding(vertical = 16.dp, horizontal = 16.dp),193+ decorationBox = { inner ->194+ Box(contentAlignment = Alignment.Center) {195+ if (value.isEmpty()) {196+ Text(placeholder, color = PeachColors.T2, fontFamily = PeachType.Mono, fontSize = 14.sp)197+ }198+ inner()199+ }200+ },201+ )202+}203+204+@Composable205+private fun PrimaryButton(label: String, enabled: Boolean, onClick: () -> Unit) {206+ val accent = LocalPeachAccent.current207+ Box(208+ modifier = Modifier209+ .fillMaxWidth()210+ .alpha(if (enabled) 1f else 0.5f)211+ .border(1.dp, accent.copy(alpha = 0.5f), RoundedCornerShape(12.dp))212+ .background(accent.copy(alpha = 0.10f), RoundedCornerShape(12.dp))213+ .clickable(enabled = enabled, onClick = onClick)214+ .padding(vertical = 16.dp),215+ contentAlignment = Alignment.Center,216+ ) {217+ Text(label, color = accent, fontFamily = PeachType.Mono, fontSize = 14.sp)218+ }219+}220+221+@Composable222+private fun RestoreTabs(onNavigate: (PeachNav) -> Unit) {223+ val tabs = listOf(224+ "PeachScript" to PeachNav.Import,225+ "CSV" to PeachNav.Import,226+ "From Phone" to PeachNav.ChirpPair,227+ "Codex" to PeachNav.CodexRestore,228+ )229+ Column(horizontalAlignment = Alignment.CenterHorizontally) {230+ Text("restore instead", color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 10.sp)231+ Spacer(Modifier.height(10.dp))232+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {233+ tabs.forEach { (label, dest) ->234+ Box(235+ modifier = Modifier236+ .border(1.dp, PeachColors.T3, RoundedCornerShape(8.dp))237+ .clickable { onNavigate(dest) }238+ .padding(horizontal = 10.dp, vertical = 8.dp),239+ ) {240+ Text(label, color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 9.sp)241+ }242+ }243+ }244+ }245+}app/src/main/java/com/peachpasswords/ui/lock/LockViewModel.kt+71 −0
@@ -0,0 +1,71 @@1+package com.peachpasswords.ui.lock2+3+import androidx.lifecycle.ViewModel4+import androidx.lifecycle.viewModelScope5+import com.peachpasswords.vault.CreateVaultResult6+import com.peachpasswords.vault.UnlockResult7+import com.peachpasswords.vault.VaultRepository8+import dagger.hilt.android.lifecycle.HiltViewModel9+import kotlinx.coroutines.flow.MutableStateFlow10+import kotlinx.coroutines.flow.StateFlow11+import kotlinx.coroutines.flow.asStateFlow12+import kotlinx.coroutines.flow.update13+import kotlinx.coroutines.launch14+import javax.inject.Inject15+16+data class LockUiState(17+ val hasVault: Boolean = false,18+ val loading: Boolean = false,19+ val error: String? = null,20+ val unlocked: Boolean = false,21+ /** Increments on each failed unlock so the screen can fire its shake animation. */22+ val shakeNonce: Int = 0,23+)24+25+const val MIN_PASSWORD_LENGTH = 826+27+@HiltViewModel28+class LockViewModel @Inject constructor(29+ private val vault: VaultRepository,30+) : ViewModel() {31+ private val _state = MutableStateFlow(LockUiState(hasVault = vault.hasVault()))32+ val state: StateFlow<LockUiState> = _state.asStateFlow()33+34+ fun unlock(password: String) {35+ if (password.isBlank() || _state.value.loading) return36+ _state.update { it.copy(loading = true, error = null) }37+ viewModelScope.launch {38+ when (val r = vault.unlock(password)) {39+ is UnlockResult.Success -> _state.update { it.copy(loading = false, unlocked = true) }40+ is UnlockResult.WrongPassword -> _state.update {41+ it.copy(loading = false, error = "incorrect password", shakeNonce = it.shakeNonce + 1)42+ }43+ is UnlockResult.Error -> _state.update {44+ it.copy(loading = false, error = r.reason, shakeNonce = it.shakeNonce + 1)45+ }46+ }47+ }48+ }49+50+ fun create(password: String, confirm: String) {51+ if (_state.value.loading) return52+ when {53+ password.length < MIN_PASSWORD_LENGTH ->54+ return _state.update { it.copy(error = "password must be at least $MIN_PASSWORD_LENGTH characters") }55+ password != confirm ->56+ return _state.update { it.copy(error = "passwords do not match") }57+ }58+ _state.update { it.copy(loading = true, error = null) }59+ viewModelScope.launch {60+ when (val r = vault.createVault(password)) {61+ is CreateVaultResult.Success -> _state.update { it.copy(loading = false, unlocked = true) }62+ is CreateVaultResult.Error -> _state.update { it.copy(loading = false, error = r.reason) }63+ }64+ }65+ }66+67+ fun clearError() = _state.update { it.copy(error = null) }68+69+ /** Dormant until biometric enrollment lands with Protection settings. */70+ fun canTryBiometric(): Boolean = false71+}app/src/main/java/com/peachpasswords/ui/screens/PlaceholderScreens.kt+120 −0
@@ -0,0 +1,120 @@1+package com.peachpasswords.ui.screens2+3+import androidx.compose.foundation.clickable4+import androidx.compose.foundation.layout.Arrangement5+import androidx.compose.foundation.layout.Box6+import androidx.compose.foundation.layout.Column7+import androidx.compose.foundation.layout.fillMaxSize8+import androidx.compose.foundation.layout.fillMaxWidth9+import androidx.compose.foundation.layout.padding10+import androidx.compose.foundation.layout.systemBarsPadding11+import androidx.compose.foundation.shape.RoundedCornerShape12+import androidx.compose.material3.MaterialTheme13+import androidx.compose.material3.Text14+import androidx.compose.runtime.Composable15+import androidx.compose.ui.Alignment16+import androidx.compose.ui.Modifier17+import androidx.compose.ui.draw.clip18+import androidx.compose.ui.graphics.Color19+import androidx.compose.ui.text.font.FontStyle20+import androidx.compose.ui.text.font.FontWeight21+import androidx.compose.ui.text.style.TextAlign22+import androidx.compose.ui.unit.dp23+import androidx.compose.ui.unit.sp24+import com.peachpasswords.ui.PeachNav25+import com.peachpasswords.ui.theme.LocalPeachAccent26+import com.peachpasswords.ui.theme.PeachColors27+import com.peachpasswords.ui.theme.PeachType28+import com.peachpasswords.ui.theme.ShellBackground29+30+/**31+ * Phase-1 placeholder. Each later phase replaces the matching screen with the32+ * real implementation; until then these prove the shell + navigation graph work.33+ */34+@Composable35+private fun Placeholder(36+ title: String,37+ subtitle: String? = null,38+ actions: List<Pair<String, () -> Unit>> = emptyList(),39+ onBack: (() -> Unit)? = null,40+) {41+ val accent = LocalPeachAccent.current42+ ShellBackground {43+ Column(44+ modifier = Modifier45+ .fillMaxSize()46+ .systemBarsPadding()47+ .padding(horizontal = 28.dp, vertical = 24.dp),48+ verticalArrangement = Arrangement.Center,49+ horizontalAlignment = Alignment.CenterHorizontally,50+ ) {51+ Text(52+ text = title,53+ color = accent,54+ fontFamily = PeachType.Display,55+ fontStyle = FontStyle.Italic,56+ fontWeight = FontWeight.Light,57+ fontSize = 34.sp,58+ textAlign = TextAlign.Center,59+ )60+ if (subtitle != null) {61+ Text(62+ text = subtitle,63+ color = PeachColors.T1,64+ fontFamily = PeachType.Mono,65+ fontSize = 11.sp,66+ textAlign = TextAlign.Center,67+ modifier = Modifier.padding(top = 10.dp),68+ )69+ }70+ actions.forEach { (label, onClick) ->71+ NavButton(label, onClick, modifier = Modifier.padding(top = 14.dp))72+ }73+ if (onBack != null) {74+ NavButton("← Back", onBack, modifier = Modifier.padding(top = 14.dp), subtle = true)75+ }76+ }77+ }78+}79+80+@Composable81+private fun NavButton(82+ label: String,83+ onClick: () -> Unit,84+ modifier: Modifier = Modifier,85+ subtle: Boolean = false,86+) {87+ val accent = LocalPeachAccent.current88+ Box(89+ modifier = modifier90+ .fillMaxWidth()91+ .clip(RoundedCornerShape(12.dp))92+ .clickable(onClick = onClick)93+ .padding(vertical = 14.dp),94+ contentAlignment = Alignment.Center,95+ ) {96+ Text(97+ text = label,98+ color = if (subtle) PeachColors.T1 else accent,99+ fontFamily = PeachType.Mono,100+ fontSize = 13.sp,101+ )102+ }103+}104+105+@Composable106+fun SettingsScreenStub(onNavigate: (PeachNav) -> Unit, onBack: () -> Unit) =107+ Placeholder(108+ title = "Settings",109+ subtitle = "PHASE 1 · SETTINGS SHELL",110+ actions = listOf(111+ "Sync" to { onNavigate(PeachNav.SettingsSync) },112+ "Pair a device" to { onNavigate(PeachNav.ChirpPair) },113+ "Codex backup" to { onNavigate(PeachNav.CodexGenerate) },114+ ),115+ onBack = onBack,116+ )117+118+@Composable119+fun SimpleStub(title: String, onBack: () -> Unit) =120+ Placeholder(title = title, subtitle = "PHASE 1 · SHELL", onBack = onBack)app/src/main/java/com/peachpasswords/ui/settings/CardIcon.kt+78 −0
@@ -0,0 +1,78 @@1+package com.peachpasswords.ui.settings2+3+import androidx.compose.foundation.Canvas4+import androidx.compose.foundation.layout.size5+import androidx.compose.runtime.Composable6+import androidx.compose.runtime.remember7+import androidx.compose.ui.Modifier8+import androidx.compose.ui.geometry.Offset9+import androidx.compose.ui.graphics.Color10+import androidx.compose.ui.graphics.StrokeCap11+import androidx.compose.ui.graphics.StrokeJoin12+import androidx.compose.ui.graphics.drawscope.Stroke13+import androidx.compose.ui.graphics.drawscope.scale14+import androidx.compose.ui.graphics.vector.PathParser15+import androidx.compose.ui.unit.Dp16+import androidx.compose.ui.unit.dp17+18+/**19+ * The seven settings-card glyphs — exact ports of the browser CardIcon.tsx20+ * SVGs (viewBox 0 0 16 16, stroke 1.25, round caps/joins). Stroked in21+ * currentColor so each card tints them with its own foreground.22+ */23+enum class StackIcon { Spark, Shield, Lock, Sync, Sun, Keys, Bubble }24+25+private val ICON_PATHS: Map<StackIcon, List<String>> = mapOf(26+ StackIcon.Shield to listOf(27+ "M8 2.2 3.4 4.4v3.2c0 3 2.1 5.1 4.6 6.2 2.5-1.1 4.6-3.2 4.6-6.2V4.4L8 2.2Z",28+ "M6.3 8.1 7.4 9.2 9.9 6.6",29+ ),30+ StackIcon.Lock to listOf(31+ "M3 7h10v7H3Z",32+ "M5.8 7V5.4a2.2 2.2 0 0 1 4.4 0V7",33+ ),34+ StackIcon.Sync to listOf(35+ "M4 8a4 4 0 0 1 6.8-2.8",36+ "M11 3.6v2.2H8.8",37+ "M12 8a4 4 0 0 1-6.8 2.8",38+ "M5 12.4v-2.2h2.2",39+ ),40+ StackIcon.Sun to listOf(41+ "M8 5.2a2.8 2.8 0 1 0 0 5.6 2.8 2.8 0 0 0 0-5.6Z",42+ "M8 1.8v1.3M8 12.9v1.3M1.8 8h1.3M12.9 8h1.3M3.6 3.6l.9.9M11.5 11.5l.9.9M12.4 3.6l-.9.9M4.5 11.5l-.9.9",43+ ),44+ StackIcon.Keys to listOf(45+ "M3 5h3a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V6a1 1 0 0 1 1-1Z",46+ "M10 7h3a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-3a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1Z",47+ "M7 7h2M7 9h2",48+ ),49+ StackIcon.Spark to listOf(50+ "M8 1.8 9.2 6l4.1 1.2-4.1 1.2L8 12.6 6.8 8.4 2.7 7.2 6.8 6 8 1.8Z",51+ "m12 11 .5 1.5L14 13l-1.5.5L12 15l-.5-1.5L10 13l1.5-.5L12 11Z",52+ ),53+ StackIcon.Bubble to listOf(54+ "M3 4.2h10a1 1 0 0 1 1 1v5.6a1 1 0 0 1-1 1H6l-3.2 2V5.2a1 1 0 0 1 1-1Z",55+ "M5.5 7h5M5.5 9.2h3.2",56+ ),57+)58+59+@Composable60+fun CardIcon(61+ kind: StackIcon,62+ color: Color,63+ modifier: Modifier = Modifier,64+ size: Dp = 16.dp,65+) {66+ val paths = remember(kind) {67+ ICON_PATHS.getValue(kind).map { PathParser().parsePathString(it).toPath() }68+ }69+ val stroke = remember {70+ Stroke(width = 1.25f, cap = StrokeCap.Round, join = StrokeJoin.Round)71+ }72+ Canvas(modifier = modifier.size(size)) {73+ val s = this.size.minDimension / 16f74+ scale(scaleX = s, scaleY = s, pivot = Offset.Zero) {75+ paths.forEach { drawPath(it, color, style = stroke) }76+ }77+ }78+}app/src/main/java/com/peachpasswords/ui/settings/SettingsCardBodies.kt+509 −0
@@ -0,0 +1,509 @@1+package com.peachpasswords.ui.settings2+3+import android.content.Intent4+import android.net.Uri5+import androidx.compose.animation.AnimatedVisibility6+import androidx.compose.animation.core.animateDpAsState7+import androidx.compose.foundation.background8+import androidx.compose.foundation.border9+import androidx.compose.foundation.clickable10+import androidx.compose.foundation.layout.Arrangement11+import androidx.compose.foundation.layout.Box12+import androidx.compose.foundation.layout.Column13+import androidx.compose.foundation.layout.FlowRow14+import androidx.compose.foundation.layout.ExperimentalLayoutApi15+import androidx.compose.foundation.layout.Row16+import androidx.compose.foundation.layout.RowScope17+import androidx.compose.foundation.layout.Spacer18+import androidx.compose.foundation.layout.fillMaxWidth19+import androidx.compose.foundation.layout.height20+import androidx.compose.foundation.layout.padding21+import androidx.compose.foundation.layout.size22+import androidx.compose.foundation.layout.width23+import androidx.compose.foundation.shape.CircleShape24+import androidx.compose.foundation.shape.RoundedCornerShape25+import androidx.compose.foundation.text.BasicTextField26+import androidx.compose.runtime.Composable27+import androidx.compose.runtime.getValue28+import androidx.compose.runtime.mutableStateOf29+import androidx.compose.runtime.remember30+import androidx.compose.runtime.rememberCoroutineScope31+import androidx.compose.runtime.setValue32+import androidx.compose.ui.Alignment33+import androidx.compose.ui.Modifier34+import androidx.compose.ui.draw.clip35+import androidx.compose.ui.graphics.Color36+import androidx.compose.ui.graphics.SolidColor37+import androidx.compose.ui.platform.LocalContext38+import androidx.compose.ui.text.TextStyle39+import androidx.compose.ui.text.font.FontStyle40+import androidx.compose.ui.text.input.PasswordVisualTransformation41+import androidx.compose.ui.unit.Dp42+import androidx.compose.ui.unit.dp43+import androidx.compose.ui.unit.em44+import androidx.compose.ui.unit.sp45+import androidx.compose.material3.Text46+import com.peachpasswords.ui.PeachNav47+import com.peachpasswords.ui.theme.ACCENT_COLORS48+import com.peachpasswords.ui.theme.PeachType49+import com.peachpasswords.vault.VaultSettings50+import kotlinx.coroutines.launch51+52+private const val PRO_URL = "https://buy.polar.sh/polar_cl_IXSFIPojx67rcOTksn8LkH5mnU3osPHtYqBIl1eyuIz"53+54+/**55+ * Body content for the active stack card. Everything is tinted with the card's56+ * own foreground [fg] (the browser's `currentColor` convention), so each card's57+ * rows inherit its palette. Rows whose backend doesn't exist yet (duress,58+ * canary, license activation) render their browser visual but defer the action59+ * to a later phase — noted inline where that's the case.60+ */61+@Composable62+fun CardBody(63+ id: CardId,64+ fg: Color,65+ vm: SettingsViewModel,66+ settings: VaultSettings,67+ entriesCount: Int,68+ onNavigate: (PeachNav) -> Unit,69+) {70+ when (id) {71+ CardId.Appearance -> AppearanceBody(fg, vm, settings)72+ CardId.Protection -> ProtectionBody(fg, vm, settings)73+ CardId.Vault -> VaultBody(fg, vm, settings, entriesCount, onNavigate)74+ CardId.Sync -> SyncBody(fg, onNavigate)75+ CardId.Shortcuts -> ShortcutsBody(fg)76+ CardId.Pro -> ProBody(fg)77+ CardId.Feedback -> FeedbackBody(fg)78+ }79+}80+81+/* ───────────────────────── shared row vocabulary ───────────────────────── */82+83+@Composable84+private fun SubLabel(text: String, fg: Color, top: Dp = 14.dp) {85+ Text(86+ text,87+ modifier = Modifier.padding(top = top, bottom = 4.dp),88+ color = fg.copy(alpha = 0.58f),89+ fontFamily = PeachType.Mono,90+ fontSize = 8.sp,91+ letterSpacing = 0.22.em,92+ )93+}94+95+@Composable96+private fun RowLine(fg: Color, content: @Composable RowScope.() -> Unit) {97+ Row(98+ Modifier.fillMaxWidth().padding(vertical = 9.dp),99+ verticalAlignment = Alignment.CenterVertically,100+ horizontalArrangement = Arrangement.SpaceBetween,101+ content = content,102+ )103+ Box(Modifier.fillMaxWidth().height(1.dp).background(fg.copy(alpha = 0.12f)))104+}105+106+@Composable107+private fun RowScope.Name(text: String, fg: Color) {108+ Text(text, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp, modifier = Modifier.weight(1f))109+}110+111+@Composable112+private fun ValueText(text: String, fg: Color) {113+ Text(text, color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Mono, fontSize = 11.sp)114+}115+116+@Composable117+private fun SubtleButton(label: String, fg: Color, onClick: () -> Unit) {118+ Box(119+ Modifier.clip(RoundedCornerShape(8.dp))120+ .border(1.dp, fg.copy(alpha = 0.28f), RoundedCornerShape(8.dp))121+ .background(fg.copy(alpha = 0.08f))122+ .clickable(onClick = onClick)123+ .padding(horizontal = 12.dp, vertical = 6.dp),124+ ) {125+ Text(label, color = fg, fontFamily = PeachType.Mono, fontSize = 11.sp)126+ }127+}128+129+@Composable130+private fun Toggle(on: Boolean, fg: Color, onToggle: (Boolean) -> Unit) {131+ val knob by animateDpAsState(if (on) 16.dp else 2.dp, label = "knob")132+ Box(133+ Modifier.size(width = 34.dp, height = 20.dp).clip(RoundedCornerShape(999.dp))134+ .background(if (on) fg.copy(alpha = 0.28f) else fg.copy(alpha = 0.08f))135+ .border(1.dp, fg.copy(alpha = if (on) 0.5f else 0.32f), RoundedCornerShape(999.dp))136+ .clickable { onToggle(!on) },137+ ) {138+ Box(139+ Modifier.padding(top = 2.dp).width(16.dp).fillMaxWidth().height(16.dp)140+ .padding(start = knob - 2.dp)141+ .size(14.dp).clip(CircleShape)142+ .background(if (on) fg else fg.copy(alpha = 0.58f)),143+ )144+ }145+}146+147+@Composable148+private fun Pill(label: String, active: Boolean, fg: Color, onClick: () -> Unit) {149+ Box(150+ Modifier.clip(RoundedCornerShape(999.dp))151+ .border(1.dp, fg.copy(alpha = if (active) 0.55f else 0.32f), RoundedCornerShape(999.dp))152+ .background(if (active) fg.copy(alpha = 0.18f) else Color.Transparent)153+ .clickable(onClick = onClick)154+ .padding(horizontal = 12.dp, vertical = 5.dp),155+ ) {156+ Text(label, color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp)157+ }158+}159+160+@Composable161+private fun ProBadge(fg: Color) {162+ Box(163+ Modifier.padding(start = 6.dp).clip(RoundedCornerShape(4.dp))164+ .background(fg.copy(alpha = 0.16f)).padding(horizontal = 5.dp, vertical = 1.dp),165+ ) {166+ Text("Pro", color = fg.copy(alpha = 0.85f), fontFamily = PeachType.Mono, fontSize = 8.sp)167+ }168+}169+170+@Composable171+private fun Hint(text: String, fg: Color) {172+ Text(173+ text,174+ modifier = Modifier.padding(top = 6.dp),175+ color = fg.copy(alpha = 0.6f),176+ fontFamily = PeachType.Display,177+ fontStyle = FontStyle.Italic,178+ fontSize = 11.5.sp,179+ lineHeight = 16.sp,180+ )181+}182+183+/* ────────────────────────────── Appearance ─────────────────────────────── */184+185+@OptIn(ExperimentalLayoutApi::class)186+@Composable187+private fun AppearanceBody(fg: Color, vm: SettingsViewModel, s: VaultSettings) {188+ SubLabel("THEME", fg, top = 0.dp)189+ RowLine(fg) {190+ Name("Theme", fg)191+ SubtleButton(if (s.theme == "dark") "Switch to light" else "Switch to dark", fg) {192+ vm.setTheme(if (s.theme == "dark") "light" else "dark")193+ }194+ }195+ SubLabel("ACCENT", fg)196+ FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {197+ ACCENT_COLORS.forEach { (name, color) ->198+ Box(199+ Modifier.size(22.dp).clip(CircleShape).background(color)200+ .border(201+ if (s.accentColor == name) 2.dp else 1.dp,202+ if (s.accentColor == name) fg else fg.copy(alpha = 0.2f),203+ CircleShape,204+ )205+ .clickable { vm.setAccent(name) },206+ )207+ }208+ }209+ SubLabel("TEXT SIZE", fg)210+ RowLine(fg) {211+ Name("Size", fg)212+ Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {213+ Pill("Default", s.textSize == "medium", fg) { vm.setTextSize("medium") }214+ Pill("Large", s.textSize == "large", fg) { vm.setTextSize("large") }215+ }216+ }217+ SubLabel("MOTION", fg)218+ RowLine(fg) {219+ Name("Reduce motion", fg)220+ SubtleButton(if (s.reduceMotion) "On" else "Off", fg) { vm.setReduceMotion(!s.reduceMotion) }221+ }222+}223+224+/* ────────────────────────────── Protection ─────────────────────────────── */225+226+@Composable227+private fun ProtectionBody(fg: Color, vm: SettingsViewModel, s: VaultSettings) {228+ val lockOptions = listOf(1 to "1 minute", 5 to "5 minutes", 15 to "15 minutes", 30 to "30 minutes", 0 to "Never")229+ val current = s.autoLockMinutes ?: 0230+231+ SubLabel("LOCKING", fg, top = 0.dp)232+ RowLine(fg) {233+ Name("Auto-lock after", fg)234+ val idx = lockOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)235+ SubtleButton(lockOptions[idx].second, fg) {236+ val next = lockOptions[(idx + 1) % lockOptions.size].first237+ vm.setAutoLockMinutes(if (next == 0) 0 else next)238+ }239+ }240+ SubLabel("BIOMETRICS", fg)241+ RowLine(fg) {242+ Name("Unlock with biometrics", fg)243+ Toggle(s.biometricsEnabled, fg) { vm.setBiometrics(it) }244+ }245+ SubLabel("BREACH PROTECTION", fg)246+ RowLine(fg) {247+ Name("Breach monitoring", fg)248+ Toggle(s.breachMonitoring, fg) { vm.setBreachMonitoring(it) }249+ }250+251+ SubLabel("MASTER PASSWORD", fg)252+ ChangePasswordRow(fg, vm)253+254+ SubLabel("DURESS PASSWORD", fg)255+ RowLine(fg) {256+ Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {257+ Name("Duress password", fg); ProBadge(fg)258+ }259+ ValueText("off", fg)260+ }261+ Hint("If entered under coercion, a decoy empty vault opens; your real vault stays hidden. Arrives with Pro sync.", fg)262+}263+264+@Composable265+private fun ChangePasswordRow(fg: Color, vm: SettingsViewModel) {266+ var open by remember { mutableStateOf(false) }267+ var current by remember { mutableStateOf("") }268+ var next by remember { mutableStateOf("") }269+ var confirm by remember { mutableStateOf("") }270+ var error by remember { mutableStateOf<String?>(null) }271+ var done by remember { mutableStateOf(false) }272+ val scope = rememberCoroutineScope()273+274+ RowLine(fg) {275+ Name("Master password", fg)276+ SubtleButton(if (open) "cancel" else "change", fg) { open = !open; error = null; done = false }277+ }278+ AnimatedVisibility(open) {279+ Column(Modifier.fillMaxWidth().padding(top = 8.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {280+ PwField("current password", current, fg) { current = it }281+ PwField("new password (min 12 chars)", next, fg) { next = it }282+ PwField("confirm new password", confirm, fg) { confirm = it }283+ error?.let { Text(it, color = Color(0xFFE5805C), fontFamily = PeachType.Mono, fontSize = 10.sp) }284+ if (done) Text("password changed ✓", color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp)285+ SubtleButton("save new password", fg) {286+ error = when {287+ current.isBlank() -> "enter your current password"288+ next.length < 12 -> "new password must be at least 12 characters"289+ next != confirm -> "new passwords do not match"290+ next == current -> "new password must differ from current"291+ else -> null292+ }293+ if (error == null) scope.launch {294+ if (vm.changePassword(current, next)) {295+ current = ""; next = ""; confirm = ""; open = false; done = true296+ } else error = "incorrect current password"297+ }298+ }299+ }300+ }301+}302+303+@Composable304+private fun PwField(placeholder: String, value: String, fg: Color, onChange: (String) -> Unit) {305+ Box(306+ Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))307+ .background(Color(0x2E000000))308+ .border(1.dp, fg.copy(alpha = 0.22f), RoundedCornerShape(8.dp))309+ .padding(horizontal = 10.dp, vertical = 10.dp),310+ ) {311+ if (value.isEmpty()) {312+ Text(placeholder, color = fg.copy(alpha = 0.42f), fontFamily = PeachType.Mono, fontSize = 12.sp)313+ }314+ BasicTextField(315+ value = value,316+ onValueChange = onChange,317+ singleLine = true,318+ textStyle = TextStyle(color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp),319+ cursorBrush = SolidColor(fg),320+ visualTransformation = PasswordVisualTransformation(),321+ modifier = Modifier.fillMaxWidth(),322+ )323+ }324+}325+326+/* ──────────────────────────────── Vault ───────────────────────────────── */327+328+@Composable329+private fun VaultBody(330+ fg: Color,331+ vm: SettingsViewModel,332+ s: VaultSettings,333+ entriesCount: Int,334+ onNavigate: (PeachNav) -> Unit,335+) {336+ val trashOptions = listOf(7 to "7 days", 30 to "30 days", 90 to "90 days", 0 to "Never")337+ val current = s.trashRetentionDays ?: 0338+339+ SubLabel("ENTRIES", fg, top = 0.dp)340+ RowLine(fg) { Name("Entries", fg); ValueText("$entriesCount", fg) }341+342+ SubLabel("MAINTENANCE", fg)343+ RowLine(fg) {344+ Name("Trash auto-delete", fg)345+ val idx = trashOptions.indexOfFirst { it.first == current }.coerceAtLeast(0)346+ SubtleButton(trashOptions[idx].second, fg) {347+ vm.setTrashRetentionDays(trashOptions[(idx + 1) % trashOptions.size].first)348+ }349+ }350+ RowLine(fg) { Name("Advanced Vault Health", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Health) } }351+ RowLine(fg) { Name("Trash", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Trash) } }352+353+ SubLabel("DATA", fg)354+ RowLine(fg) { Name("Import passwords", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Import) } }355+ RowLine(fg) { Name("Export backup", fg); SubtleButton("open", fg) { onNavigate(PeachNav.Export) } }356+ RowLine(fg) {357+ Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) { Name("Peach Codex", fg); ProBadge(fg) }358+ SubtleButton("open", fg) { onNavigate(PeachNav.CodexGenerate) }359+ }360+ RowLine(fg) { Name("Restore from Codex", fg); SubtleButton("open", fg) { onNavigate(PeachNav.CodexRestore) } }361+}362+363+/* ──────────────────────────────── Sync ────────────────────────────────── */364+365+@Composable366+private fun SyncBody(fg: Color, onNavigate: (PeachNav) -> Unit) {367+ SubLabel("PAIRING", fg, top = 0.dp)368+ RowLine(fg) {369+ Column(Modifier.weight(1f)) {370+ Row(verticalAlignment = Alignment.CenterVertically) {371+ Text("Peach Sync", color = fg, fontFamily = PeachType.Body, fontSize = 13.sp); ProBadge(fg)372+ }373+ Text(374+ "Pair nearby devices by chirp and keep encrypted vault blobs in step without a central account.",375+ color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 11.sp, lineHeight = 16.sp,376+ modifier = Modifier.padding(top = 2.dp),377+ )378+ }379+ }380+ RowLine(fg) { Name("Status", fg); ValueText("Requires Pro", fg) }381+ RowLine(fg) { Name("Sync hub", fg); SubtleButton("open", fg) { onNavigate(PeachNav.ChirpPair) } }382+383+ SubLabel("DEVICE FLOW", fg)384+ RowLine(fg) { Name("Pair new device", fg); SubtleButton("pair", fg) { onNavigate(PeachNav.ChirpPair) } }385+ Hint("Sync uses the same zero-knowledge vault format as backup and restore; pairing authorizes a device, not a cloud account.", fg)386+}387+388+/* ────────────────────────────── Shortcuts ──────────────────────────────── */389+390+@Composable391+private fun ShortcutsBody(fg: Color) {392+ val bindings = listOf(393+ "Copy password" to "⌘C", "Copy username" to "⌘⇧C", "Open entry" to "↵",394+ "Edit entry" to "E", "New entry" to "⌘N", "Search" to "/",395+ )396+ SubLabel("KEYBINDINGS", fg, top = 0.dp)397+ Hint("Shortcuts apply when a hardware keyboard is attached. Defaults shown below.", fg)398+ Spacer(Modifier.height(8.dp))399+ bindings.forEach { (label, key) ->400+ RowLine(fg) {401+ Name(label, fg)402+ Box(403+ Modifier.clip(RoundedCornerShape(4.dp)).background(fg.copy(alpha = 0.06f))404+ .border(1.dp, fg.copy(alpha = 0.32f), RoundedCornerShape(4.dp))405+ .padding(horizontal = 7.dp, vertical = 2.dp),406+ ) { Text(key, color = fg, fontFamily = PeachType.Mono, fontSize = 10.sp) }407+ }408+ }409+}410+411+/* ──────────────────────────────── Pro ─────────────────────────────────── */412+413+@Composable414+private fun ProBody(fg: Color) {415+ val ctx = LocalContext.current416+ val features = listOf(417+ "Peach Sync" to "Encrypted · peer-to-peer",418+ "Peach Codex" to "Restore from paper",419+ "Passkeys" to "Zero-knowledge WebAuthn",420+ "Advanced Vault Health" to "Reuse · age · exposure",421+ "Canary entries" to "Detects vault compromise",422+ "Duress vault" to "Decoy under coercion",423+ )424+ Text("PEACH PRO · ONE-TIME", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 8.sp, letterSpacing = 0.22.em)425+ Text(426+ "Everything, everywhere.",427+ modifier = Modifier.padding(top = 8.dp),428+ color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 24.sp,429+ )430+ Text(431+ "One key unlocks every Pro feature — for the lifetime of the app.",432+ modifier = Modifier.padding(top = 6.dp),433+ color = fg.copy(alpha = 0.72f), fontFamily = PeachType.Body, fontSize = 12.sp, lineHeight = 17.sp,434+ )435+ Spacer(Modifier.height(12.dp))436+ features.forEachIndexed { i, (name, desc) ->437+ RowLine(fg) {438+ Row(Modifier.weight(1f), verticalAlignment = Alignment.CenterVertically) {439+ Text("%02d".format(i + 1), color = fg.copy(alpha = 0.5f), fontFamily = PeachType.Mono, fontSize = 10.sp, modifier = Modifier.padding(end = 10.dp))440+ Text(name, color = fg, fontFamily = PeachType.Body, fontSize = 13.sp)441+ }442+ Text(desc, color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 11.sp)443+ }444+ }445+ Spacer(Modifier.height(14.dp))446+ Text(447+ "$39",448+ color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 28.sp,449+ )450+ Text("once · yours forever", color = fg.copy(alpha = 0.6f), fontFamily = PeachType.Mono, fontSize = 9.sp, letterSpacing = 0.18.em)451+ Spacer(Modifier.height(10.dp))452+ Box(453+ Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp))454+ .background(fg.copy(alpha = 0.16f))455+ .border(1.dp, fg.copy(alpha = 0.4f), RoundedCornerShape(10.dp))456+ .clickable {457+ runCatching { ctx.startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(PRO_URL))) }458+ }459+ .padding(vertical = 12.dp),460+ contentAlignment = Alignment.Center,461+ ) { Text("Get Peach Pro", color = fg, fontFamily = PeachType.Mono, fontSize = 12.sp) }462+ Hint("Already have a key? License activation arrives with Pro sync in a later update.", fg)463+}464+465+/* ────────────────────────────── Feedback ───────────────────────────────── */466+467+@OptIn(ExperimentalLayoutApi::class)468+@Composable469+private fun FeedbackBody(fg: Color) {470+ val categories = listOf("Bug report", "Feature request", "Question", "Other")471+ var category by remember { mutableStateOf(categories[0]) }472+ var message by remember { mutableStateOf("") }473+ var sent by remember { mutableStateOf(false) }474+475+ if (sent) {476+ Box(477+ Modifier.fillMaxWidth().clip(RoundedCornerShape(10.dp)).background(fg.copy(alpha = 0.08f))478+ .border(1.dp, fg.copy(alpha = 0.32f), RoundedCornerShape(10.dp)).padding(16.dp),479+ ) {480+ Column {481+ Text("Thank you", color = fg, fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 18.sp)482+ Text("Your note is in the queue. Someone will process it soon.", color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 12.sp, modifier = Modifier.padding(top = 4.dp))483+ }484+ }485+ return486+ }487+488+ Text("Help us improve Peach. Every report goes directly to our inbox.", color = fg.copy(alpha = 0.7f), fontFamily = PeachType.Body, fontSize = 12.sp, lineHeight = 17.sp)489+ SubLabel("TYPE", fg)490+ FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {491+ categories.forEach { cat -> Pill(cat, category == cat, fg) { category = cat } }492+ }493+ SubLabel("MESSAGE", fg)494+ Box(495+ Modifier.fillMaxWidth().height(110.dp).clip(RoundedCornerShape(8.dp))496+ .background(Color(0x2E000000)).border(1.dp, fg.copy(alpha = 0.22f), RoundedCornerShape(8.dp))497+ .padding(10.dp),498+ ) {499+ if (message.isEmpty()) Text("Describe the issue or idea...", color = fg.copy(alpha = 0.42f), fontFamily = PeachType.Body, fontSize = 12.sp)500+ BasicTextField(501+ value = message, onValueChange = { message = it },502+ textStyle = TextStyle(color = fg, fontFamily = PeachType.Body, fontSize = 12.sp),503+ cursorBrush = SolidColor(fg), modifier = Modifier.fillMaxWidth(),504+ )505+ }506+ Spacer(Modifier.height(8.dp))507+ SubtleButton("Send", fg) { if (message.isNotBlank()) sent = true }508+ Hint("Sent anonymously · no account required", fg)509+}app/src/main/java/com/peachpasswords/ui/settings/SettingsScreen.kt+386 −0
@@ -0,0 +1,386 @@1+package com.peachpasswords.ui.settings2+3+import androidx.activity.compose.BackHandler4+import androidx.compose.animation.core.Animatable5+import androidx.compose.animation.core.animateDpAsState6+import androidx.compose.animation.core.animateFloat7+import androidx.compose.animation.core.animateFloatAsState8+import androidx.compose.animation.core.infiniteRepeatable9+import androidx.compose.animation.core.keyframes10+import androidx.compose.animation.core.rememberInfiniteTransition11+import androidx.compose.animation.core.tween12+import androidx.compose.foundation.background13+import androidx.compose.foundation.clickable14+import androidx.compose.foundation.interaction.MutableInteractionSource15+import androidx.compose.foundation.layout.Arrangement16+import androidx.compose.foundation.layout.Box17+import androidx.compose.foundation.layout.BoxWithConstraints18+import androidx.compose.foundation.layout.Column19+import androidx.compose.foundation.layout.Row20+import androidx.compose.foundation.layout.Spacer21+import androidx.compose.foundation.layout.fillMaxSize22+import androidx.compose.foundation.layout.fillMaxWidth23+import androidx.compose.foundation.layout.height24+import androidx.compose.foundation.layout.padding25+import androidx.compose.foundation.layout.size26+import androidx.compose.foundation.layout.statusBarsPadding27+import androidx.compose.foundation.rememberScrollState28+import androidx.compose.foundation.shape.RoundedCornerShape29+import androidx.compose.foundation.verticalScroll30+import androidx.compose.runtime.Composable31+import androidx.compose.runtime.LaunchedEffect32+import androidx.compose.runtime.getValue33+import androidx.compose.runtime.mutableStateOf34+import androidx.compose.runtime.remember35+import androidx.compose.runtime.rememberCoroutineScope36+import androidx.compose.runtime.setValue37+import androidx.compose.runtime.collectAsState38+import androidx.compose.ui.Alignment39+import androidx.compose.ui.Modifier40+import androidx.compose.ui.draw.clip41+import androidx.compose.ui.draw.drawWithCache42+import androidx.compose.ui.draw.shadow43+import androidx.compose.ui.geometry.Offset44+import androidx.compose.ui.graphics.BlendMode45+import androidx.compose.ui.graphics.Brush46+import androidx.compose.ui.graphics.Color47+import androidx.compose.ui.graphics.graphicsLayer48+import androidx.compose.ui.platform.LocalDensity49+import androidx.compose.ui.text.font.FontStyle50+import androidx.compose.ui.text.font.FontWeight51+import androidx.compose.ui.text.style.TextOverflow52+import androidx.compose.ui.unit.dp53+import androidx.compose.ui.unit.em54+import androidx.compose.ui.unit.sp55+import androidx.compose.ui.zIndex56+import androidx.hilt.navigation.compose.hiltViewModel57+import androidx.compose.material3.Text58+import com.peachpasswords.ui.theme.LocalReduceMotion59+import com.peachpasswords.ui.theme.PeachColors60+import com.peachpasswords.ui.theme.PeachMotion61+import com.peachpasswords.ui.theme.PeachStackColors62+import com.peachpasswords.ui.theme.PeachType63+import com.peachpasswords.ui.theme.ShellBackground64+import kotlinx.coroutines.delay65+import kotlinx.coroutines.launch66+67+// Deck geometry — ported verbatim from StackDeck.tsx constants. The active card68+// sits at top:0; every other card is a thin tab fanned below it, ordered69+// cyclically starting just after the active card so the stack reads as a loop.70+private val EXPANDED_H = 258.dp71+private val TAB_H = 46.dp72+private val TAB_OVERLAP = 14.dp73+private val TAB_CARD_H = TAB_H + 4.dp74+75+@Composable76+fun SettingsScreen(77+ onBack: () -> Unit,78+ onNavigate: (com.peachpasswords.ui.PeachNav) -> Unit = {},79+ vm: SettingsViewModel = hiltViewModel(),80+) {81+ val entries by vm.entries.collectAsState()82+ val settings by vm.settings.collectAsState()83+ val reduceMotion = LocalReduceMotion.current84+ val scope = rememberCoroutineScope()85+86+ var active by remember { mutableStateOf(CardId.Pro) }87+ var deckOpen by remember { mutableStateOf(true) }88+ var fanning by remember { mutableStateOf(false) }89+ var celebrating by remember { mutableStateOf<CardId?>(null) }90+91+ val activeIndex = STACK_CARDS.indexOfFirst { it.id == active }.coerceAtLeast(0)92+93+ fun handleBack() {94+ if (!deckOpen) deckOpen = true else onBack()95+ }96+ BackHandler { handleBack() }97+98+ // Pro celebration: replay every card in a quick fan, land back on Pro, shake.99+ fun celebrate() {100+ if (fanning) return101+ scope.launch {102+ fanning = true103+ active = CardId.Pro104+ CELEBRATION_FAN.forEachIndexed { i, id ->105+ delay(150L)106+ active = id107+ }108+ delay(150L)109+ active = CardId.Pro110+ fanning = false111+ celebrating = CardId.Pro112+ delay(900L)113+ celebrating = null114+ }115+ }116+117+ ShellBackground {118+ Column(Modifier.fillMaxSize().statusBarsPadding().padding(horizontal = 12.dp)) {119+ // Masthead: back chevron · "Settings" · card counter.120+ Row(121+ Modifier.fillMaxWidth().padding(top = 10.dp, bottom = 8.dp),122+ verticalAlignment = Alignment.CenterVertically,123+ ) {124+ Box(125+ Modifier.size(28.dp).clip(RoundedCornerShape(999.dp))126+ .background(Color(0x04F0E8D8))127+ .clickable { handleBack() },128+ contentAlignment = Alignment.Center,129+ ) {130+ Text("‹", color = PeachColors.T1, fontFamily = PeachType.Mono, fontSize = 16.sp)131+ }132+ Text(133+ "Settings",134+ modifier = Modifier.weight(1f).padding(start = 10.dp),135+ color = PeachColors.T0,136+ fontFamily = PeachType.Display,137+ fontStyle = FontStyle.Italic,138+ fontSize = 22.sp,139+ )140+ Text(141+ "${activeIndex + 1} / ${STACK_CARDS.size}",142+ color = PeachColors.T2,143+ fontFamily = PeachType.Mono,144+ fontSize = 9.sp,145+ letterSpacing = 0.22.em,146+ )147+ }148+149+ BoxWithConstraints(Modifier.fillMaxSize()) {150+ val focusHeight = maxHeight - 8.dp151+ STACK_CARDS.forEachIndexed { index, card ->152+ val isActive = card.id == active153+ val distance = when {154+ index == activeIndex -> -1155+ index > activeIndex -> index - activeIndex - 1156+ else -> STACK_CARDS.size - activeIndex + index - 1157+ }158+ val targetTop = when {159+ isActive -> 0.dp160+ !deckOpen -> focusHeight + 44.dp + (distance * 8).dp161+ else -> EXPANDED_H - TAB_OVERLAP + (distance * (TAB_H - TAB_OVERLAP).value.toInt()).dp162+ }163+ val targetHeight = when {164+ isActive && deckOpen -> EXPANDED_H165+ isActive -> focusHeight166+ else -> TAB_CARD_H167+ }168+ val concealed = !deckOpen && !isActive169+170+ val animSpec = if (fanning) {171+ tween<Float>(140, easing = PeachMotion.Celebrate)172+ } else {173+ tween<Float>(PeachMotion.Stack, easing = PeachMotion.StackSpring)174+ }175+ val top by animateDpAsState(176+ targetTop,177+ animationSpec = if (fanning) tween(140, easing = PeachMotion.Celebrate)178+ else tween(PeachMotion.Stack, easing = PeachMotion.StackSpring),179+ label = "top",180+ )181+ val cardH by animateDpAsState(182+ targetHeight,183+ animationSpec = if (fanning) tween(140, easing = PeachMotion.Celebrate)184+ else tween(PeachMotion.Stack, easing = PeachMotion.StackSpring),185+ label = "h",186+ )187+ val alpha by animateFloatAsState(if (concealed) 0f else 1f, animSpec, label = "a")188+ val zIndex = if (isActive) 99f else (50 - distance).toFloat()189+190+ // Celebration shake — keyframed bob + tilt as the Pro card lands.191+ val shakeDy = remember { Animatable(0f) }192+ val shakeRot = remember { Animatable(0f) }193+ LaunchedEffect(celebrating == card.id) {194+ if (celebrating == card.id && !reduceMotion) {195+ launch {196+ shakeRot.animateTo(0f, keyframes {197+ durationMillis = 880198+ 0f at 0; -1.3f at 211; 0.9f at 422; -0.45f at 616; 0f at 757199+ })200+ }201+ shakeDy.animateTo(0f, keyframes {202+ durationMillis = 880203+ 0f at 0; -10f at 211; 5f at 422; -4f at 616; 2f at 757204+ })205+ }206+ }207+208+ val density = LocalDensity.current209+ StackCard(210+ spec = card,211+ active = isActive,212+ focused = isActive && !deckOpen,213+ lede = vm.lede(card.id, entries.count { it.deletedAt == null }, settings),214+ showSparkle = card.id == CardId.Pro && vm.isPro,215+ onIconClick = if (card.id == CardId.Pro && vm.isPro) ({ celebrate() }) else null,216+ body = {217+ CardBody(218+ id = card.id,219+ fg = card.fg,220+ vm = vm,221+ settings = settings,222+ entriesCount = entries.count { it.deletedAt == null },223+ onNavigate = onNavigate,224+ )225+ },226+ modifier = Modifier227+ .fillMaxWidth()228+ .align(Alignment.TopStart)229+ .zIndex(zIndex)230+ .graphicsLayer {231+ translationY = top.toPx() + with(density) { shakeDy.value.dp.toPx() }232+ rotationZ = shakeRot.value233+ this.alpha = alpha234+ }235+ .height(cardH),236+ onClick = {237+ if (isActive) {238+ if (deckOpen) deckOpen = false239+ } else {240+ active = card.id241+ deckOpen = false242+ }243+ },244+ enabled = !concealed,245+ )246+ }247+ }248+ }249+ }250+}251+252+@Composable253+private fun StackCard(254+ spec: StackCardSpec,255+ active: Boolean,256+ focused: Boolean,257+ lede: String,258+ showSparkle: Boolean,259+ onIconClick: (() -> Unit)?,260+ body: @Composable () -> Unit,261+ modifier: Modifier,262+ onClick: () -> Unit,263+ enabled: Boolean,264+) {265+ val interaction = remember { MutableInteractionSource() }266+ Box(267+ modifier268+ .shadow(if (active) 18.dp else 8.dp, RoundedCornerShape(PeachStackColors.CardRadius), clip = false)269+ .clip(RoundedCornerShape(PeachStackColors.CardRadius))270+ .background(Brush.linearGradient(listOf(spec.bgStart, spec.bgEnd)))271+ .clickable(272+ interactionSource = interaction,273+ indication = null,274+ enabled = enabled && !active || (active && !focused),275+ ) { onClick() }276+ .padding(277+ horizontal = if (active) 18.dp else 16.dp,278+ vertical = if (active) 16.dp else 12.dp,279+ ),280+ ) {281+ if (showSparkle) SparkleDust(Modifier.fillMaxSize())282+ if (active) {283+ Column(Modifier.fillMaxSize()) {284+ Row(285+ Modifier.fillMaxWidth(),286+ horizontalArrangement = Arrangement.SpaceBetween,287+ verticalAlignment = Alignment.CenterVertically,288+ ) {289+ Text(290+ spec.num,291+ color = spec.fg.copy(alpha = 0.7f),292+ fontFamily = PeachType.Mono,293+ fontSize = 8.5.sp,294+ letterSpacing = 0.26.em,295+ )296+ Box(297+ Modifier.clip(RoundedCornerShape(999.dp))298+ .then(if (onIconClick != null) Modifier.clickable { onIconClick() } else Modifier)299+ .padding(2.dp),300+ ) {301+ CardIcon(spec.icon, spec.fg.copy(alpha = 0.85f))302+ }303+ }304+ Text(305+ spec.title,306+ modifier = Modifier.padding(top = 6.dp),307+ color = spec.fg,308+ fontFamily = PeachType.Display,309+ fontStyle = FontStyle.Italic,310+ fontSize = 26.sp,311+ )312+ Text(313+ lede,314+ modifier = Modifier.padding(top = 4.dp),315+ color = spec.fg.copy(alpha = 0.72f),316+ fontFamily = PeachType.Display,317+ fontStyle = FontStyle.Italic,318+ fontSize = 12.5.sp,319+ )320+ // Body scrolls independently; only revealed at full height in321+ // focus mode, but kept mounted so deck-mode shows a preview.322+ Column(323+ Modifier.fillMaxWidth().weight(1f)324+ .padding(top = 14.dp)325+ .verticalScroll(rememberScrollState()),326+ ) {327+ body()328+ Spacer(Modifier.height(24.dp))329+ }330+ }331+ } else {332+ // Tab: just the title, single line, vertically centred.333+ Box(Modifier.fillMaxSize(), contentAlignment = Alignment.CenterStart) {334+ Text(335+ spec.title,336+ color = spec.fg,337+ fontFamily = PeachType.Display,338+ fontStyle = FontStyle.Italic,339+ fontWeight = FontWeight.Normal,340+ fontSize = 19.sp,341+ maxLines = 1,342+ overflow = TextOverflow.Ellipsis,343+ )344+ }345+ }346+ }347+}348+349+/**350+ * Ambient drifting sparkle dust for the Pro card. Three offset dot grids slowly351+ * translate diagonally and loop, screen-blended at low opacity — the Compose352+ * analogue of the browser's `stk-pro-dust` keyframes.353+ */354+@Composable355+private fun SparkleDust(modifier: Modifier = Modifier) {356+ val reduceMotion = LocalReduceMotion.current357+ val t = rememberInfiniteTransition(label = "dust")358+ val drift by if (reduceMotion) {359+ remember { mutableStateOf(0f) }360+ } else {361+ t.animateFloat(362+ initialValue = 0f,363+ targetValue = 1f,364+ animationSpec = infiniteRepeatable(tween(14000, easing = androidx.compose.animation.core.LinearEasing)),365+ label = "drift",366+ )367+ }368+ Box(369+ modifier.drawWithCache {370+ val tile = 48.dp.toPx()371+ val dx = drift * tile372+ onDrawBehind {373+ val cols = (size.width / tile).toInt() + 2374+ val rows = (size.height / tile).toInt() + 2375+ for (r in 0..rows) {376+ for (c in 0..cols) {377+ val baseX = c * tile + dx378+ val baseY = r * tile + dx379+ drawCircle(Color(0xFFFFF8DC), 0.6f, Offset(baseX % (size.width + tile), baseY % (size.height + tile)), alpha = 0.11f, blendMode = BlendMode.Screen)380+ drawCircle(Color(0xFFFFEEAA), 1f, Offset((baseX + 19f) % (size.width + tile), (baseY + 15f) % (size.height + tile)), alpha = 0.08f, blendMode = BlendMode.Screen)381+ }382+ }383+ }384+ },385+ )386+}app/src/main/java/com/peachpasswords/ui/settings/SettingsStack.kt+56 −0
@@ -0,0 +1,56 @@1+package com.peachpasswords.ui.settings2+3+import androidx.compose.ui.graphics.Color4+import com.peachpasswords.ui.theme.PeachStackColors5+6+/** The seven settings categories, in deck order (Pro on top). */7+enum class CardId { Pro, Protection, Vault, Sync, Appearance, Shortcuts, Feedback }8+9+/**10+ * Static visual identity for one stack card. The [lede] is the only field that11+ * changes with vault state, so it's supplied per-render rather than baked in.12+ */13+data class StackCardSpec(14+ val id: CardId,15+ val num: String,16+ val title: String,17+ val icon: StackIcon,18+ val bgStart: Color,19+ val bgEnd: Color,20+ val fg: Color,21+)22+23+val STACK_CARDS: List<StackCardSpec> = listOf(24+ StackCardSpec(25+ CardId.Pro, "I · FOREVER", "Peach Pro", StackIcon.Spark,26+ PeachStackColors.ProBgStart, PeachStackColors.ProBgEnd, PeachStackColors.ProFg,27+ ),28+ StackCardSpec(29+ CardId.Protection, "II · PROTECT", "Protection", StackIcon.Shield,30+ PeachStackColors.ProtectBgStart, PeachStackColors.ProtectBgEnd, PeachStackColors.ProtectFg,31+ ),32+ StackCardSpec(33+ CardId.Vault, "III · KEEP", "Vault", StackIcon.Lock,34+ PeachStackColors.VaultBgStart, PeachStackColors.VaultBgEnd, PeachStackColors.VaultFg,35+ ),36+ StackCardSpec(37+ CardId.Sync, "IV · ECHO", "Sync", StackIcon.Sync,38+ PeachStackColors.SyncBgStart, PeachStackColors.SyncBgEnd, PeachStackColors.SyncFg,39+ ),40+ StackCardSpec(41+ CardId.Appearance, "V · DRESS", "Appearance", StackIcon.Sun,42+ PeachStackColors.AppearBgStart, PeachStackColors.AppearBgEnd, PeachStackColors.AppearFg,43+ ),44+ StackCardSpec(45+ CardId.Shortcuts, "VI · KEYS", "Shortcuts", StackIcon.Keys,46+ PeachStackColors.ShortcutBgStart, PeachStackColors.ShortcutBgEnd, PeachStackColors.ShortcutFg,47+ ),48+ StackCardSpec(49+ CardId.Feedback, "VII · ECHO", "Feedback", StackIcon.Bubble,50+ PeachStackColors.FeedbackBgStart, PeachStackColors.FeedbackBgEnd, PeachStackColors.FeedbackFg,51+ ),52+)53+54+/** Fan replay order for the Pro celebration — every non-Pro card, then home. */55+val CELEBRATION_FAN: List<CardId> =56+ listOf(CardId.Protection, CardId.Vault, CardId.Sync, CardId.Appearance, CardId.Shortcuts, CardId.Feedback)app/src/main/java/com/peachpasswords/ui/settings/SettingsViewModel.kt+50 −0
@@ -0,0 +1,50 @@1+package com.peachpasswords.ui.settings2+3+import androidx.lifecycle.ViewModel4+import androidx.lifecycle.viewModelScope5+import com.peachpasswords.vault.VaultRepository6+import com.peachpasswords.vault.VaultSettings7+import dagger.hilt.android.lifecycle.HiltViewModel8+import kotlinx.coroutines.flow.StateFlow9+import kotlinx.coroutines.launch10+import javax.inject.Inject11+12+@HiltViewModel13+class SettingsViewModel @Inject constructor(14+ private val vault: VaultRepository,15+) : ViewModel() {16+ val entries: StateFlow<List<com.peachpasswords.vault.VaultEntry>> = vault.entries17+ val settings: StateFlow<VaultSettings> = vault.settings18+19+ /** Pro entitlement is not wired until Phase 8 sync/license — Pro-gated for now. */20+ val isPro: Boolean = false21+22+ private fun mutate(block: (VaultSettings) -> VaultSettings) {23+ viewModelScope.launch { vault.updateSettings(block(vault.settings.value)) }24+ }25+26+ fun setTheme(theme: String) = mutate { it.copy(theme = theme) }27+ fun setAccent(name: String) = mutate { it.copy(accentColor = name) }28+ fun setTextSize(size: String) = mutate { it.copy(textSize = size) }29+ fun setReduceMotion(on: Boolean) = mutate { it.copy(reduceMotion = on) }30+ fun setBreachMonitoring(on: Boolean) = mutate { it.copy(breachMonitoring = on) }31+ fun setBiometrics(on: Boolean) = mutate { it.copy(biometricsEnabled = on) }32+ fun setAutoLockMinutes(min: Int?) = mutate { it.copy(autoLockMinutes = min) }33+ fun setTrashRetentionDays(days: Int?) = mutate { it.copy(trashRetentionDays = days) }34+35+ suspend fun changePassword(current: String, next: String): Boolean =36+ vault.changePassword(current, next)37+38+ /** One-line summary shown under each card title; mirrors the browser ledes. */39+ fun lede(id: CardId, entriesCount: Int, s: VaultSettings): String = when (id) {40+ CardId.Pro -> if (isPro) "active · paid once, yours forever" else "$39 once · yours forever"41+ CardId.Protection ->42+ "${if (s.breachMonitoring) "breaches watched" else "breach watch off"} · manual lock"43+ CardId.Vault ->44+ "$entriesCount ${if (entriesCount == 1) "entry" else "entries"} · backups, history, cleanup"45+ CardId.Sync -> if (isPro) "pair by chirp, keep in step" else "Pro · encrypted device pairing"46+ CardId.Appearance -> "${s.theme} · ${s.accentColor} · ${s.textSize}"47+ CardId.Shortcuts -> "bindings · what your fingers know"48+ CardId.Feedback -> "tell us what would make it better"49+ }50+}app/src/main/java/com/peachpasswords/ui/theme/AccentColors.kt+20 −0
@@ -0,0 +1,20 @@1+package com.peachpasswords.ui.theme2+3+import androidx.compose.ui.graphics.Color4+5+val ACCENT_COLORS = mapOf(6+ "peach" to Color(0xFFF49C70),7+ "rose" to Color(0xFFFF8AA6),8+ "plum" to Color(0xFFD597F2),9+ "lavender" to Color(0xFFA6A8FF),10+ "sky" to Color(0xFF5BC8EE),11+ "mint" to Color(0xFF5EE0B0),12+ "sage" to Color(0xFFB5D870),13+ "butter" to Color(0xFFFFD45A),14+ "sand" to Color(0xFFEDBC85),15+ "clay" to Color(0xFFF08660),16+ "slate" to Color(0xFF80BEDE),17+ "stone" to Color(0xFFC8B8A8),18+)19+20+val DEFAULT_ACCENT = ACCENT_COLORS.getValue("peach")app/src/main/java/com/peachpasswords/ui/theme/PeachColors.kt+37 −0
@@ -0,0 +1,37 @@1+package com.peachpasswords.ui.theme2+3+import androidx.compose.ui.graphics.Color4+5+object PeachColors {6+ val Bg = Color(0xFF0C0A06)7+ val S1 = Color(0xFF131109)8+ val S2 = Color(0xFF1A1710)9+ val S3 = Color(0xFF221F14)10+ val SurfaceCard = Color(0x05F0E8D8)11+ val SurfaceElevated = Color(0xE0131109)12+ val SettingsGroupBg = Color(0x991A1410)13+14+ val T0 = Color(0xFFF0E8D8)15+ val T1 = Color(0x80F0E8D8)16+ val T2 = Color(0x33F0E8D8)17+ val T3 = Color(0x12F0E8D8)18+ val T4 = Color(0x0AF0E8D8)19+20+ val Accent = Color(0xFFE8956D)21+ val AccentDim = Color(0x40E8956D)22+ val AccentGlow = Color(0x2AF49C70)23+ val AccentSurfaceTint = Color(0x09F49C70)24+ val AccentBorder = Color(0x24F49C70)25+26+ val Breach = Color(0xB3DC503C)27+ val BreachBg = Color(0x12DC503C)28+ val BreachBorder = Color(0x2EDC503C)29+ val HealthOk = Color(0xBF64D264)30+ val TotpTag = Color(0xBF78AFFF)31+ val SyncOk = Color(0xFF5EBD5E)32+ val SyncBusy = Color(0xFFC8A840)33+ val SyncErr = Color(0xB3DC503C)34+35+ val ShellTopSolid = Color(0xFF000000)36+ val ShellTopFade = Color(0xF20C0A06)37+}app/src/main/java/com/peachpasswords/ui/theme/PeachColorsLight.kt+26 −0
@@ -0,0 +1,26 @@1+package com.peachpasswords.ui.theme2+3+import androidx.compose.ui.graphics.Color4+5+object PeachColorsLight {6+ val Bg = Color(0xFFEFEEE9)7+ val S1 = Color(0xFFF0E9DF)8+ val S2 = Color(0xFFF5EDE2)9+ val S3 = Color(0xFFEEE7DD)10+ val T0 = Color(0xFF1A1208)11+ val T1 = Color(0xFF3D2E18)12+ val T2 = Color(0xFFA8A099)13+ val T3 = Color(0xFFDDD5CB)14+ val T4 = Color(0x0F1A1208)15+ val SurfaceCard = Color(0xFFF0E9DF)16+ val SurfaceElevated = Color(0xF7F5EDE2)17+ val SettingsGroupBg = Color(0xB3F5EDE2)18+19+ val TextLabel = Color(0xFF79766F)20+ val TextLink = Color(0xFFB87155)21+ val TextDim = Color(0xFF9E9890)22+ val BorderSubtle = Color(0xFFE8E2D8)23+ val BorderStrong = Color(0xFFC4BAB0)24+ val BreachBg = Color(0xFFF1E5D9)25+ val BreachText = Color(0xFFDA6931)26+}app/src/main/java/com/peachpasswords/ui/theme/PeachMotion.kt+27 −0
@@ -0,0 +1,27 @@1+package com.peachpasswords.ui.theme2+3+import androidx.compose.animation.core.CubicBezierEasing4+import androidx.compose.animation.core.tween5+6+object PeachMotion {7+ val Spring = CubicBezierEasing(0.16f, 1f, 0.3f, 1f)8+ val Retreat = CubicBezierEasing(0.4f, 0f, 1f, 1f)9+ val Settle = CubicBezierEasing(0.34f, 1.56f, 0.64f, 1f)10+ val StackSpring = CubicBezierEasing(0.18f, 0.9f, 0.22f, 1.02f)11+ val Celebrate = CubicBezierEasing(0.22f, 1f, 0.36f, 1f)12+ val Standard = CubicBezierEasing(0.4f, 0f, 0.2f, 1f)13+14+ const val Micro = 8015+ const val Quick = 15016+ const val Exit = 28017+ const val Enter = 50018+ const val Stack = 38019+ const val Ring = 72020+ const val CharDelay = 2021+ const val CharDuration = 38022+23+ fun enterTween() = tween<Float>(Enter, easing = Spring)24+ fun exitTween() = tween<Float>(Exit, easing = Retreat)25+ fun stackTween() = tween<Float>(Stack, easing = StackSpring)26+ fun microTween() = tween<Float>(Micro, easing = Standard)27+}app/src/main/java/com/peachpasswords/ui/theme/PeachRadius.kt+18 −0
@@ -0,0 +1,18 @@1+package com.peachpasswords.ui.theme2+3+import androidx.compose.ui.unit.dp4+5+object PeachRadius {6+ val Button = 12.dp7+ val IconButton = 8.dp8+ val Card = 18.dp9+ val StackCard = 16.dp10+ val LockPanel = 18.dp11+ val EntryIcon = 7.dp12+ val Pill = 999.dp13+ val TypeTab = 6.dp14+ val PasskeyToast = 14.dp15+ val SettingsGroup = 12.dp16+ val DangerNotice = 6.dp17+ val OverlayCard = 12.dp18+}app/src/main/java/com/peachpasswords/ui/theme/PeachStackColors.kt+39 −0
@@ -0,0 +1,39 @@1+package com.peachpasswords.ui.theme2+3+import androidx.compose.ui.graphics.Color4+import androidx.compose.ui.unit.Dp5+import androidx.compose.ui.unit.dp6+7+object PeachStackColors {8+ val ProtectBgStart = Color(0xFFB85A3A)9+ val ProtectBgEnd = Color(0xFF6E2818)10+ val ProtectFg = Color(0xFFFFFEDD)11+12+ val VaultBgStart = Color(0xFF2A3A4D)13+ val VaultBgEnd = Color(0xFF0F1620)14+ val VaultFg = Color(0xFFE5EEFA)15+16+ val SyncBgStart = Color(0xFF3A4E3A)17+ val SyncBgEnd = Color(0xFF15241A)18+ val SyncFg = Color(0xFFE6F2DE)19+20+ val AppearBgStart = Color(0xFF5A4A2C)21+ val AppearBgEnd = Color(0xFF281D10)22+ val AppearFg = Color(0xFFF4E9D2)23+24+ val ShortcutBgStart = Color(0xFF3A3A45)25+ val ShortcutBgEnd = Color(0xFF1A1A22)26+ val ShortcutFg = Color(0xFFE4E0D6)27+28+ val ProBgStart = Color(0xFFC2884A)29+ val ProBgEnd = Color(0xFF6E3E1A)30+ val ProFg = Color(0xFFFFF1DD)31+32+ val FeedbackBgStart = Color(0xFF4A3A4E)33+ val FeedbackBgEnd = Color(0xFF1D1424)34+ val FeedbackFg = Color(0xFFEEE4F2)35+36+ val CardRadius: Dp = 16.dp37+ val TabHeightMobile: Dp = 64.dp38+ val TabOverlapMobile: Dp = 16.dp39+}app/src/main/java/com/peachpasswords/ui/theme/PeachTheme.kt+92 −0
@@ -0,0 +1,92 @@1+package com.peachpasswords.ui.theme2+3+import androidx.compose.material3.MaterialTheme4+import androidx.compose.material3.darkColorScheme5+import androidx.compose.material3.lightColorScheme6+import androidx.compose.runtime.Composable7+import androidx.compose.runtime.CompositionLocalProvider8+import androidx.compose.runtime.compositionLocalOf9+import androidx.compose.runtime.staticCompositionLocalOf10+import androidx.compose.ui.graphics.Color11+import androidx.compose.ui.text.TextStyle12+import androidx.compose.ui.text.font.FontStyle13+import androidx.compose.ui.text.font.FontWeight14+import androidx.compose.ui.unit.sp15+16+/** Current accent color, available to any composable under [PeachTheme]. */17+val LocalPeachAccent = compositionLocalOf { DEFAULT_ACCENT }18+19+/** When true, decorative/long-running animations should be skipped or shortened. */20+val LocalReduceMotion = staticCompositionLocalOf { false }21+22+/** True when the active scheme is dark — some surfaces tune themselves off this. */23+val LocalPeachDark = staticCompositionLocalOf { true }24+25+@Composable26+fun PeachTheme(27+ darkTheme: Boolean = true,28+ accent: Color = DEFAULT_ACCENT,29+ reduceMotion: Boolean = false,30+ content: @Composable () -> Unit,31+) {32+ val colors = if (darkTheme) {33+ darkColorScheme(34+ primary = accent,35+ onPrimary = PeachColors.Bg,36+ secondary = PeachColors.SyncBusy,37+ onSecondary = PeachColors.Bg,38+ background = PeachColors.Bg,39+ onBackground = PeachColors.T0,40+ surface = PeachColors.S1,41+ onSurface = PeachColors.T0,42+ surfaceVariant = PeachColors.S2,43+ onSurfaceVariant = PeachColors.T1,44+ outline = PeachColors.T3,45+ error = PeachColors.Breach,46+ onError = PeachColors.Bg,47+ )48+ } else {49+ lightColorScheme(50+ primary = accent,51+ onPrimary = PeachColorsLight.Bg,52+ secondary = PeachColorsLight.TextLink,53+ onSecondary = PeachColorsLight.Bg,54+ background = PeachColorsLight.Bg,55+ onBackground = PeachColorsLight.T0,56+ surface = PeachColorsLight.S1,57+ onSurface = PeachColorsLight.T0,58+ surfaceVariant = PeachColorsLight.S2,59+ onSurfaceVariant = PeachColorsLight.T1,60+ outline = PeachColorsLight.BorderSubtle,61+ error = PeachColorsLight.BreachText,62+ onError = PeachColorsLight.Bg,63+ )64+ }65+66+ val typography = androidx.compose.material3.Typography(67+ bodyLarge = TextStyle(68+ fontFamily = PeachType.Body,69+ fontSize = 16.sp,70+ fontWeight = FontWeight.Normal,71+ ),72+ titleLarge = TextStyle(73+ fontFamily = PeachType.Display,74+ fontSize = 24.sp,75+ fontStyle = FontStyle.Italic,76+ fontWeight = FontWeight.Light,77+ ),78+ labelLarge = TextStyle(79+ fontFamily = PeachType.Body,80+ fontSize = 12.sp,81+ fontWeight = FontWeight.Medium,82+ ),83+ )84+85+ CompositionLocalProvider(86+ LocalPeachAccent provides accent,87+ LocalReduceMotion provides reduceMotion,88+ LocalPeachDark provides darkTheme,89+ ) {90+ MaterialTheme(colorScheme = colors, typography = typography, content = content)91+ }92+}app/src/main/java/com/peachpasswords/ui/theme/PeachType.kt+29 −0
@@ -0,0 +1,29 @@1+package com.peachpasswords.ui.theme2+3+import androidx.compose.ui.text.font.Font4+import androidx.compose.ui.text.font.FontFamily5+import androidx.compose.ui.text.font.FontStyle6+import androidx.compose.ui.text.font.FontWeight7+import com.peachpasswords.R8+9+object PeachType {10+ val Display = FontFamily(11+ Font(R.font.cormorant_garamond_light, FontWeight.Light),12+ Font(R.font.cormorant_garamond_light_italic, FontWeight.Light, FontStyle.Italic),13+ Font(R.font.cormorant_garamond_regular, FontWeight.Normal),14+ Font(R.font.cormorant_garamond_regular_italic, FontWeight.Normal, FontStyle.Italic),15+ )16+17+ val Mono = FontFamily(18+ Font(R.font.ibm_plex_mono_light, FontWeight.Light),19+ Font(R.font.ibm_plex_mono_light_italic, FontWeight.Light, FontStyle.Italic),20+ Font(R.font.ibm_plex_mono_regular, FontWeight.Normal),21+ )22+23+ val Body = FontFamily(24+ Font(R.font.inter_regular, FontWeight.Normal),25+ Font(R.font.inter_variable, FontWeight.Normal),26+ )27+28+ val Script = FontFamily(Font(R.font.peachscript_regular, FontWeight.Normal))29+}app/src/main/java/com/peachpasswords/ui/theme/ShellBackground.kt+64 −0
@@ -0,0 +1,64 @@1+package com.peachpasswords.ui.theme2+3+import androidx.compose.foundation.layout.Box4+import androidx.compose.foundation.layout.BoxScope5+import androidx.compose.foundation.layout.fillMaxSize6+import androidx.compose.runtime.Composable7+import androidx.compose.ui.Modifier8+import androidx.compose.ui.draw.drawBehind9+import androidx.compose.ui.geometry.Offset10+import androidx.compose.ui.geometry.Size11+import androidx.compose.ui.graphics.Brush12+import androidx.compose.ui.graphics.Color13+14+/**15+ * The two-bloom shell background that sits behind every screen.16+ *17+ * Mirrors the browser shell (popup.css):18+ * radial-gradient(120% 80% at 0% 0%, accent 8%, transparent 65%)19+ * radial-gradient(85% 100% at 100% 100%, accent 6%, transparent 70%)20+ * over a flat --bg fill. Compose radial gradients are circular, so each21+ * bloom is sized off the dominant CSS axis to land in the same corner.22+ */23+@Composable24+fun ShellBackground(25+ modifier: Modifier = Modifier,26+ content: @Composable BoxScope.() -> Unit,27+) {28+ val accent = LocalPeachAccent.current29+ val base = MaterialTheme_background()30+ Box(31+ modifier = modifier32+ .fillMaxSize()33+ .drawBehind {34+ drawRect(color = base)35+36+ // Top-left bloom — CSS 120% × 80% at 0% 0%, accent 8% → transparent @65%.37+ val topRadius = size.width * 1.2f38+ drawRect(39+ brush = Brush.radialGradient(40+ colors = listOf(accent.copy(alpha = 0.08f), Color.Transparent),41+ center = Offset(0f, 0f),42+ radius = topRadius,43+ ),44+ size = Size(size.width, size.height),45+ )46+47+ // Bottom-right bloom — CSS 85% × 100% at 100% 100%, accent 6% → transparent @70%.48+ val bottomRadius = size.height * 1.0f49+ drawRect(50+ brush = Brush.radialGradient(51+ colors = listOf(accent.copy(alpha = 0.06f), Color.Transparent),52+ center = Offset(size.width, size.height),53+ radius = bottomRadius,54+ ),55+ size = Size(size.width, size.height),56+ )57+ },58+ content = content,59+ )60+}61+62+@Composable63+private fun MaterialTheme_background(): Color =64+ androidx.compose.material3.MaterialTheme.colorScheme.backgroundapp/src/main/java/com/peachpasswords/ui/vault/EntryDetailScreen.kt+238 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/vault/EntryDetailViewModel.kt+75 −0
@@ -0,0 +1,75 @@1+package com.peachpasswords.ui.vault2+3+import android.content.ClipData4+import android.content.ClipboardManager5+import android.content.Context6+import androidx.lifecycle.SavedStateHandle7+import androidx.lifecycle.ViewModel8+import androidx.lifecycle.viewModelScope9+import com.peachpasswords.vault.TOTPGenerator10+import com.peachpasswords.vault.VaultEntry11+import com.peachpasswords.vault.VaultRepository12+import dagger.hilt.android.lifecycle.HiltViewModel13+import dagger.hilt.android.qualifiers.ApplicationContext14+import kotlinx.coroutines.flow.MutableStateFlow15+import kotlinx.coroutines.flow.SharingStarted16+import kotlinx.coroutines.flow.StateFlow17+import kotlinx.coroutines.flow.asStateFlow18+import kotlinx.coroutines.flow.map19+import kotlinx.coroutines.flow.stateIn20+import kotlinx.coroutines.launch21+import javax.inject.Inject22+23+@HiltViewModel24+class EntryDetailViewModel @Inject constructor(25+ private val vault: VaultRepository,26+ @ApplicationContext private val appContext: Context,27+ savedStateHandle: SavedStateHandle,28+) : ViewModel() {29+ private val id: String = savedStateHandle.get<String>("id").orEmpty()30+31+ val entry: StateFlow<VaultEntry?> =32+ vault.entries.map { list -> list.firstOrNull { it.id == id } }33+ .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), vault.getEntry(id))34+35+ private val _revealed = MutableStateFlow(false)36+ val revealed: StateFlow<Boolean> = _revealed.asStateFlow()37+38+ private val _copiedField = MutableStateFlow<String?>(null)39+ val copiedField: StateFlow<String?> = _copiedField.asStateFlow()40+41+ /** Reveal the password and auto-mask after 10 seconds (matches the browser). */42+ fun reveal() {43+ _revealed.value = true44+ viewModelScope.launch {45+ kotlinx.coroutines.delay(10_000)46+ _revealed.value = false47+ }48+ }49+50+ fun mask() { _revealed.value = false }51+52+ fun copy(field: String, value: String?) {53+ val v = value ?: return54+ val cm = appContext.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager55+ cm.setPrimaryClip(ClipData.newPlainText("peach", v))56+ viewModelScope.launch {57+ _copiedField.value = field58+ kotlinx.coroutines.delay(1200)59+ if (_copiedField.value == field) _copiedField.value = null60+ }61+ }62+63+ /** Copy the live TOTP code (never the seed). */64+ fun copyTotp() {65+ val totp = entry.value?.totp ?: return66+ copy("totp", TOTPGenerator.generateCode(totp))67+ }68+69+ fun delete(onDone: () -> Unit) {70+ viewModelScope.launch {71+ runCatching { vault.deleteEntry(id) }72+ onDone()73+ }74+ }75+}app/src/main/java/com/peachpasswords/ui/vault/EntryEditScreen.kt+267 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/vault/EntryEditViewModel.kt+131 −0
@@ -0,0 +1,131 @@1+package com.peachpasswords.ui.vault2+3+import androidx.lifecycle.SavedStateHandle4+import androidx.lifecycle.ViewModel5+import androidx.lifecycle.viewModelScope6+import com.peachpasswords.vault.PasswordGenerator7+import com.peachpasswords.vault.VaultEntry8+import com.peachpasswords.vault.VaultRepository9+import dagger.hilt.android.lifecycle.HiltViewModel10+import kotlinx.coroutines.flow.MutableStateFlow11+import kotlinx.coroutines.flow.StateFlow12+import kotlinx.coroutines.flow.asStateFlow13+import kotlinx.coroutines.flow.update14+import kotlinx.coroutines.launch15+import javax.inject.Inject16+17+data class EditForm(18+ val type: String = "login",19+ val title: String = "",20+ val username: String = "",21+ val email: String = "",22+ val password: String = "",23+ val url: String = "",24+ val totp: String = "",25+ val notes: String = "",26+ val showPassword: Boolean = false,27+ val generatorOpen: Boolean = false,28+ val genLength: Int = 20,29+ val genUpper: Boolean = true,30+ val genLower: Boolean = true,31+ val genNumbers: Boolean = true,32+ val genSymbols: Boolean = true,33+ val saving: Boolean = false,34+ val error: String? = null,35+)36+37+@HiltViewModel38+class EntryEditViewModel @Inject constructor(39+ private val vault: VaultRepository,40+ savedStateHandle: SavedStateHandle,41+) : ViewModel() {42+ private val id: String? = savedStateHandle.get<String>("id")?.takeIf { it.isNotBlank() }43+ val isNew: Boolean = id == null44+ private val existing: VaultEntry? = id?.let { vault.getEntry(it) }45+46+ private val _form = MutableStateFlow(47+ existing?.let {48+ EditForm(49+ type = it.type ?: "login",50+ title = it.title,51+ username = it.username.orEmpty(),52+ email = it.email.orEmpty(),53+ password = it.password.orEmpty(),54+ url = it.url.orEmpty(),55+ totp = it.totp.orEmpty(),56+ notes = it.notes.orEmpty(),57+ )58+ } ?: EditForm(),59+ )60+ val form: StateFlow<EditForm> = _form.asStateFlow()61+62+ fun setType(t: String) = _form.update { it.copy(type = t) }63+ fun setTitle(v: String) = _form.update { it.copy(title = v, error = null) }64+ fun setUsername(v: String) = _form.update { it.copy(username = v) }65+ fun setEmail(v: String) = _form.update { it.copy(email = v) }66+ fun setPassword(v: String) = _form.update { it.copy(password = v) }67+ fun setUrl(v: String) = _form.update { it.copy(url = v) }68+ fun setTotp(v: String) = _form.update { it.copy(totp = v) }69+ fun setNotes(v: String) = _form.update { it.copy(notes = v) }70+ fun toggleShowPassword() = _form.update { it.copy(showPassword = !it.showPassword) }71+ fun toggleGenerator() = _form.update { it.copy(generatorOpen = !it.generatorOpen) }72+ fun setGenLength(n: Int) = _form.update { it.copy(genLength = n) }73+ fun setGenUpper(b: Boolean) = _form.update { it.copy(genUpper = b) }74+ fun setGenLower(b: Boolean) = _form.update { it.copy(genLower = b) }75+ fun setGenNumbers(b: Boolean) = _form.update { it.copy(genNumbers = b) }76+ fun setGenSymbols(b: Boolean) = _form.update { it.copy(genSymbols = b) }77+78+ fun generate() {79+ val f = _form.value80+ val pw = PasswordGenerator.generate(81+ PasswordGenerator.Options(82+ length = f.genLength,83+ includeUppercase = f.genUpper,84+ includeLowercase = f.genLower,85+ includeNumbers = f.genNumbers,86+ includeSymbols = f.genSymbols,87+ ),88+ )89+ _form.update { it.copy(password = pw, showPassword = true) }90+ }91+92+ fun save(onDone: () -> Unit) {93+ val f = _form.value94+ if (f.title.isBlank()) {95+ _form.update { it.copy(error = "title is required") }96+ return97+ }98+ _form.update { it.copy(saving = true, error = null) }99+ viewModelScope.launch {100+ runCatching {101+ if (isNew) {102+ vault.addEntry(103+ VaultEntry(104+ id = "", type = f.type, title = f.title.trim(),105+ username = f.username.ifBlank { null },106+ email = f.email.ifBlank { null },107+ password = f.password.ifBlank { null },108+ url = f.url.ifBlank { null },109+ totp = f.totp.ifBlank { null },110+ notes = f.notes.ifBlank { null },111+ createdAt = 0, modifiedAt = 0,112+ ),113+ )114+ } else {115+ vault.updateEntry(116+ existing!!.copy(117+ type = f.type, title = f.title.trim(),118+ username = f.username.ifBlank { null },119+ email = f.email.ifBlank { null },120+ password = f.password.ifBlank { null },121+ url = f.url.ifBlank { null },122+ totp = f.totp.ifBlank { null },123+ notes = f.notes.ifBlank { null },124+ ),125+ )126+ }127+ }.onSuccess { onDone() }128+ .onFailure { e -> _form.update { it.copy(saving = false, error = e.message ?: "save failed") } }129+ }130+ }131+}app/src/main/java/com/peachpasswords/ui/vault/VaultListScreen.kt+343 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/ui/vault/VaultListViewModel.kt+105 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/Canary.kt+14 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/PasskeyData.kt+24 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/PasswordGenerator.kt+45 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/RecoveryWordList.kt+2053 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/RecoveryWords.kt+87 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/SavedIdentity.kt+12 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/TOTPGenerator.kt+92 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/VaultCrypto.kt+95 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/VaultEntry.kt+67 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/VaultHealth.kt+102 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+347 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/VaultSettings.kt+28 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/VaultSnapshot.kt+13 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/vault/VaultStore.kt+114 −0
not shown here: too long for one page
app/src/main/java/com/peachpasswords/widget/PeachWidgets.kt+43 −0
not shown here: too long for one page
app/src/main/res/drawable/ic_launcher_background.xml+4 −0
not shown here: too long for one page
app/src/main/res/drawable/ic_launcher_foreground.xml+15 −0
not shown here: too long for one page
app/src/main/res/drawable/ic_launcher_monochrome.xml+5 −0
not shown here: too long for one page
app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml+6 −0
not shown here: too long for one page
app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml+6 −0
not shown here: too long for one page
app/src/main/res/xml/autofill_service_config.xml+3 −0
not shown here: too long for one page
app/src/main/res/xml/credential_provider_config.xml+6 −0
not shown here: too long for one page
app/src/main/res/xml/peach_medium_widget_info.xml+10 −0
not shown here: too long for one page
app/src/main/res/xml/peach_small_widget_info.xml+10 −0
not shown here: too long for one page
app/src/test/java/com/peachpasswords/sync/ChirpPairingTest.kt+226 −0
not shown here: too long for one page
app/src/test/java/com/peachpasswords/sync/ChirpSyncTransportTest.kt+99 −0
not shown here: too long for one page
app/src/test/java/com/peachpasswords/vault/PasswordGeneratorTest.kt+36 −0
not shown here: too long for one page
app/src/test/java/com/peachpasswords/vault/TOTPGeneratorTest.kt+33 −0
not shown here: too long for one page
app/src/test/java/com/peachpasswords/vault/VaultRepositoryTest.kt+142 −0
not shown here: too long for one page