Skip to content
Back to search

ksafe

MarketplaceWorks with Claude CodeGitHub

Agent skills for the KSafe Kotlin Multiplatform encrypted persistence library

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/ioannisa--ksafe/badge.svg)](/listings/ioannisa--ksafe)

HTML

<a href="/listings/ioannisa--ksafe"><img src="/api/listings/ioannisa--ksafe/badge.svg" alt="findsafeskills safety rating" /></a>

Install

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

1 - Add the Dependency

// commonMain or Android-only build.gradle(.kts)
implementation("eu.anifantakis:ksafe:3.3.0")
implementation("eu.anifantakis:ksafe-compose:3.3.0")     // ← Compose state (optional)
implementation("eu.anifantakis:ksafe-biometrics:3.3.0")  // ← Biometric auth (optional)

> Skip `ksafe-compose` if you don't use Jetpack Compose or `mutableStateOf` persistence. > > Skip `ksafe-biometrics` if you don't need Face ID / Touch ID / Fingerprint verification. The biometrics module is fully independent — it has no dependency on `:ksafe` and can be used on its own to protect any action in your app.

> **Note:** `kotlinx-serialization-json` comes in transitively — don't add it yourself.

2 - Apply the kotlinx-serialization plugin

Required only if you store `@Serializable` data classes. Add it to `libs.versions.toml`:

[versions]
kotlin = "2.2.21"

[plugins]
kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }

then apply it in `build.gradle.kts`:

plugins {
  //...
  alias(libs.plugins.kotlin.serialization)
}

3 - Instantiate

// Android
val ksafe = KSafe(context)

// iOS / macOS / JVM / WASM / JS
val ksafe = KSafe()

With Koin (recommended for KMP):

// Android
actual val platformModule = module {
    single { KSafe(androidApplication()) }
}

// iOS / macOS / JVM / WASM / JS
actual val platformModule = module {
    single { KSafe() }
}

Multi-instance setups, web `awaitCacheReady()`, custom storage directories, key namespacing for Desktop/Web (`appNamespace`), and AES key-size configuration: **[docs/SETUP.md](docs/SETUP.md)**.

> **Compose Desktop release builds:** add `modules("jdk.unsupported", "java.management")` to `nativeDistributions` for OS-backed key custody — why, and what happens without it: [docs/JVM_PROTECTION.md](docs/JVM_PROTECTION.md#compose-desktop-release-distributables-jdkunsupported).

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 14 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. {
  2. "name": "ksafe",
  3. "description": "Agent skills for the KSafe Kotlin Multiplatform encrypted persistence library",
  4. "owner": {
  5. "name": "Ioannis Anifantakis"
  6. },
  7. "plugins": [
  8. {
  9. "name": "ksafe",
  10. "source": "./",
  11. "description": "KSafe \u2014 Kotlin Multiplatform encrypted persistence: patterns, anti-patterns, and gotchas for AI agents"
  12. }
  13. ]
  14. }
README.md · README · 472 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # KSafe — Universal Key/Value Persistence for Kotlin Multiplatform and Android
  2. * **Encrypted by default. Plain _(unencrypted)_ when needed.**
  3. * **Persist variables, Compose State, StateFlow, and serializable objects across Android, iOS, macOS, Desktop, and Web**
  4. * **Easy to use by design** — plus key rotation, cross-platform biometrics, and an encryption preflight
  5. [![Maven Central](https://img.shields.io/maven-central/v/eu.anifantakis/ksafe.svg?label=Maven%20Central)](https://central.sonatype.com/artifact/eu.anifantakis/ksafe)
  6. [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://opensource.org/licenses/Apache-2.0)
  7. [![Changelog](https://img.shields.io/badge/Changelog-latest-informational.svg)](CHANGELOG.md)
  8. ![image](https://github.com/user-attachments/assets/e1b396e3-70a7-4473-a703-1ca0f2aa23c2)
  9. ## What is KSafe?
  10. KSafe is a secure-by-default Kotlin Multiplatform key/value persistence library. Persist ordinary Kotlin variables, Compose `MutableState`, `MutableStateFlow`, and `@Serializable` objects across app restarts with **one API** on Android, iOS, macOS, JVM/Desktop, WASM, and Kotlin/JS. **Encrypted (AES-256-GCM) by default; plain per-entry with `mode = KSafeWriteMode.Plain`.**
  11. ```kotlin
  12. var counter by ksafe(0)
  13. counter++ // auto-encrypted (AES-256-GCM), auto-persisted, survives process death
  14. ```
  15. Read and write it like any normal Kotlin variable — no `suspend`, no `runBlocking`, no DataStore boilerplate, no explicit `encrypt`/`decrypt`. Reads hit a hot in-memory cache; writes encrypt and flush in the background — **synchronous, but never blocking**. Reach for the `suspend` API (`get` / `put`) only when *you* want to await the disk flush.
  16. - **Easy?** ✔ one-line setup, property-delegate API
  17. - **Encrypted by default?** ✔ AES-256-GCM, hardware-backed where available
  18. - **Plain storage?** ✔ opt out with one parameter
  19. - **Synchronous?** ✔ non-blocking hot-cache reads
  20. - **Asynchronous?** ✔ full suspend API for guaranteed disk flushes
  21. **Extras when you encrypt:** biometrics (Face ID / Touch ID / Fingerprint — optional standalone `ksafe-biometrics` module) · root/jailbreak detection (WARN/BLOCK + analytics callback) · memory policy (RAM-exposure modes) · a one-line hardware-isolated DB passphrase for SQLCipher / SQLDelight / Room.
  22. ## 🤖 KSafe Skill for AI agents
  23. KSafe ships an [agentskills.io](https://agentskills.io)-compatible skill — [**skills/ksafe/SKILL.md**](skills/ksafe/SKILL.md) — that teaches any AI agent (Claude Code, Codex, Gemini CLI, Copilot CLI, Junie) KSafe's patterns, anti-patterns and gotchas, so the code it writes for you is the code this README describes.
  24. **Claude Code** — run both, in this order, once. Restart the session afterwards; skills load at session start:
  25. ```
  26. /plugin marketplace add ioannisa/KSafe # register this repo as a plugin source
  27. /plugin install ksafe@ksafe # install the skill from it
  28. ```
  29. **Any other agent** — one command, then pick your agents from its prompt:
  30. ```bash
  31. npx skills add ioannisa/KSafe
  32. ```
  33. Forcing an update, installing without any tooling, and why you should not *also* hand-copy `SKILL.md`: **[docs/AI_AGENTS.md](docs/AI_AGENTS.md)**.
  34. ## Demo & Videos
  35. KSafe in action across many scenarios: **[KSafeDemo — Compose Multiplatform app](https://github.com/ioannisa/KSafeDemo)**.
  36. | Author's Video | Philipp Lackner's Video | Jimmy Plazas's Video |
  37. |:--------------:|:---------------:|:---------------:|
  38. | [<img width="200" alt="image" src="https://github.com/user-attachments/assets/8c317a36-4baa-491e-8c88-4c44b8545bad" />](https://youtu.be/mFKGx0DMZEA) | [<img width="200" alt="image" src="https://github.com/user-attachments/assets/59cce32b-634e-4b17-bb5f-5e084dff899f" />](https://youtu.be/cLyxWGV6GKg) | [<img width="200" alt="image" src="https://github.com/user-attachments/assets/65dba780-9c80-470c-9ad0-927a86510a26" />](https://youtu.be/M4U06OnAl-I) |
  39. | [KSafe - Kotlin Multiplatform Encrypted DataStore Persistence Library](https://youtu.be/mFKGx0DMZEA) | [How to Encrypt Local Preferences In KMP With KSafe](https://youtu.be/cLyxWGV6GKg) | [Encripta datos localmente en Kotlin Multiplatform con KSafe - Ejemplo + Arquitectura](https://youtu.be/M4U06OnAl-I) |
  40. ***
  41. ## Setup
  42. ### 1 - Add the Dependency
  43. ```kotlin
  44. // commonMain or Android-only build.gradle(.kts)
  45. implementation("eu.anifantakis:ksafe:3.3.0")
  46. implementation("eu.anifantakis:ksafe-compose:3.3.0") // ← Compose state (optional)
  47. implementation("eu.anifantakis:ksafe-biometrics:3.3.0") // ← Biometric auth (optional)
  48. ```
  49. > Skip `ksafe-compose` if you don't use Jetpack Compose or `mutableStateOf` persistence.
  50. >
  51. > Skip `ksafe-biometrics` if you don't need Face ID / Touch ID / Fingerprint verification. The biometrics module is fully independent — it has no dependency on `:ksafe` and can be used on its own to protect any action in your app.
  52. > **Note:** `kotlinx-serialization-json` comes in transitively — don't add it yourself.
  53. ### 2 - Apply the kotlinx-serialization plugin
  54. Required only if you store `@Serializable` data classes. Add it to `libs.versions.toml`:
  55. ```toml
  56. [versions]
  57. kotlin = "2.2.21"
  58. [plugins]
  59. kotlin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" }
  60. ```
  61. then apply it in `build.gradle.kts`:
  62. ```Kotlin
  63. plugins {
  64. //...
  65. alias(libs.plugins.kotlin.serialization)
  66. }
  67. ```
  68. ### 3 - Instantiate
  69. ```kotlin
  70. // Android
  71. val ksafe = KSafe(context)
  72. // iOS / macOS / JVM / WASM / JS
  73. val ksafe = KSafe()
  74. ```
  75. With Koin (recommended for KMP):
  76. ```kotlin
  77. // Android
  78. actual val platformModule = module {
  79. single { KSafe(androidApplication()) }
  80. }
  81. // iOS / macOS / JVM / WASM / JS
  82. actual val platformModule = module {
  83. single { KSafe() }
  84. }
  85. ```
  86. Multi-instance setups, web `awaitCacheReady()`, custom storage directories, key namespacing for Desktop/Web (`appNamespace`), and AES key-size configuration: **[docs/SETUP.md](docs/SETUP.md)**.
  87. > **Compose Desktop release builds:** add `modules("jdk.unsupported", "java.management")` to `nativeDistributions` for OS-backed key custody — why, and what happens without it: [docs/JVM_PROTECTION.md](docs/JVM_PROTECTION.md#compose-desktop-release-distributables-jdkunsupported).
  88. ---
  89. ## 🟢 Basic Usage 🟢
  90. There are two ways to reach your data, and they share the same store and the same hot cache, so you can mix them freely. Full reference (Compose `policy`, cross-screen sync, write modes, nullables, deletion, full ViewModel): **[docs/USAGE.md](docs/USAGE.md)**.
  91. ### A variable per stored key
  92. You declare one variable per value. KSafe persists it, encrypts it, and keeps it in the hot cache, so reads and writes are synchronous and never suspend.
  93. **Property delegation** — the key is the property name:
  94. ```kotlin
  95. var counter by ksafe(0)
  96. counter++
  97. ```
  98. **Direct handle (3.2.0+)** — the same call without `by`. Keep the handle in a `val`, pass it around, read and write `.value`. The key must be given explicitly, because there is no property name to infer it from:
  99. ```kotlin
  100. val counter = ksafe(0, key = "counter") // KSafeReference<Int>
  101. counter.value++
  102. ```
  103. ### Through the KSafe instance
  104. No variable per key. You address any key, at any time, straight on the instance. Each operation comes in two forms: a `suspend` one that waits for the disk flush, and a `Direct` one that returns at once, serves reads from the hot cache and flushes writes in the background (about 1000x faster for bulk work).
  105. ```kotlin
  106. // Put
  107. ksafe.put("profile", user) // suspend — returns after the disk flush
  108. ksafe.putDirect("counter", 42) // non-suspend — background flush
  109. // Get
  110. val loaded: User = ksafe.get("profile", User())
  111. val n = ksafe.getDirect("counter", 0)
  112. // Delete
  113. ksafe.delete("profile")
  114. ksafe.deleteDirect("counter")
  115. // Wipe the store — every value and the keys that protected them (logout)
  116. ksafe.clearAll() // suspend
  117. ```
  118. ### Flows
  119. Reactive reads that pick up changes made anywhere: another screen, a background sync, a delegate against the same key. Four shapes, and the same two doors as above — the property names the key, or you do:
  120. | Shape | Type | Hot or cold | Writes | Scope | Same thing, key spelled out |
  121. |---|---|---|---|---|---|
  122. | `asFlow` | `Flow<T>` | cold | — | none | `getFlow(key, default)` |
  123. | `asWritableFlow` | `WritableKSafeFlow<T>` | cold | `set(value)` | none | — |
  124. | `asStateFlow` | `StateFlow<T>` | hot, `.value` | — | needed | `getStateFlow(key, default, scope)` |
  125. | `asMutableStateFlow` | `MutableStateFlow<T>` | hot, `.value` | `.value =`, `update {}` | needed | — |
  126. **Cold** — nothing runs until someone collects, so there is no scope to manage:
  127. ```kotlin
  128. val toggleMode: Flow<Boolean> by ksafe.asFlow(defaultValue = false)
  129. toggleMode.collect { on -> render(on) }
  130. ksafe.putDirect("toggleMode", true) // updated from anywhere — the collector above sees true
  131. // Writable: one declaration you both collect and write through
  132. val themeMode: WritableKSafeFlow<ThemeMode> by ksafe.asWritableFlow(ThemeMode.DEVICE)
  133. themeMode.collect { mode -> applyTheme(mode) }
  134. themeMode.set(ThemeMode.DARK) // persists, and every collector sees it
  135. ```
  136. **Hot** — a current value is always there, and that is what the scope pays for. Something has to sit on the store, watch for changes made elsewhere and push them in; that watcher is a coroutine, and it must die with your ViewModel:
  137. ```kotlin
  138. val isLoggedIn: StateFlow<Boolean> by ksafe.asStateFlow(true, viewModelScope)
  139. isLoggedIn.value // read it any time, with no collector at all
  140. ksafe.putDirect("isLoggedIn", false) // every collector sees false
  141. // Writable: the _state / state pattern, persisted
  142. private val _count by ksafe.asMutableStateFlow(0, viewModelScope)
  143. val count = _count.asStateFlow()
  144. _count.update { it + 1 } // persists
  145. _count.value = 42 // persists
  146. ```
  147. **Without the delegate** — the same shapes and the same types, with the key spelled out. Note that a flow is always bound to one key: unlike `put` or `getDirect`, there is no flow over *any* key.
  148. ```kotlin
  149. // Cold: call it inline, as often as you like — a cold Flow starts nothing on its own
  150. ksafe.getFlow("isLoggedIn", defaultValue = true).collect { loggedIn -> render(loggedIn) }
  151. // Hot: call it ONCE and keep the result — every call runs stateIn() and starts its own watcher
  152. val isLoggedIn: StateFlow<Boolean> = ksafe.getStateFlow("isLoggedIn", true, viewModelScope)
  153. ```
  154. > [!WARNING]
  155. > **Call `getStateFlow` once and keep the result.** Every call runs `stateIn()` and launches its own
  156. > watcher coroutine in the scope you pass, so calling it inline, in a loop, or inside a composable
  157. > leaks one watcher per call until that scope is cancelled. The `by ksafe.asStateFlow(...)` delegate
  158. > is safe by construction — it builds its `StateFlow` on first read and hands back the same instance
  159. > forever after. `getFlow` is cold and costs nothing: call it as often as you like.
  160. For the cold shapes the two forms are interchangeable — pick whichever reads better.
  161. There is no writable shape without the delegate, and none is needed: to write, use `put` or `putDirect`, and every reader of that key sees it — a delegated flow in a ViewModel, a `getFlow` on another screen, a Compose state. One store, one cache.
  162. ### Compose
  163. Persistent state inside a `@Composable` body. The `rememberSaveable` analogue that also survives app restarts; the key resolves to the property name and no ViewModel is needed. `KSafe` is `@Stable`, so it can be passed as a parameter without breaking skipping. The default mode here is `Plain`, because this is UI state, not a secret. Requires `ksafe-compose`.
  164. ```kotlin
  165. @Composable
  166. fun TabbedScreen(ksafe: KSafe) {
  167. var currentTab by ksafe.rememberKSafeState(Tab.Home)
  168. // ...
  169. }
  170. ```
  171. ### State
  172. Compose `MutableState` on a ViewModel or any class field. The UI recomposes on change, the value persists, and two screens holding the same key stay in sync. Requires `ksafe-compose`.
  173. ```kotlin
  174. var username by ksafe.mutableStateOf("Guest")
  175. ```
  176. ### Helper classes (3.1.0+)
  177. Every write above takes an optional `KSafeWriteMode`. The default is encrypted; you can step up or step down per entry:
  178. ```kotlin
  179. var token by ksafe("") // encrypted, the default
  180. var token by ksafe("", mode = KSafeWriteMode.Encrypted()) // the same, spelled out
  181. var pin by ksafe("", mode = KSafeWriteMode.Encrypted(KSafeEncryptedProtection.HARDWARE_ISOLATED)) // step up: StrongBox / Secure Enclave
  182. var theme by ksafe("light", mode = KSafeWriteMode.Plain) // step down: no encryption
  183. ```
  184. The helper classes freeze that mode at the type level, so no call site can forget it or pick the wrong one. They wrap an existing instance and offer every API shape above — `KSafePlain(ksafe)`, `KSafeEncrypted(ksafe)`, `KSafeHardwareIsolated(ksafe)`. With Koin:
  185. ```kotlin
  186. val appModule = module {
  187. single<KSafe> { KSafe() }
  188. single { KSafePlain(get()) } // every write plain
  189. single { KSafeEncrypted(get()) } // every write encrypted
  190. single { KSafeHardwareIsolated(get()) } // every write requests StrongBox / Secure Enclave
  191. }
  192. class PreferencesViewModel(
  193. private val prefs: KSafePlain,
  194. private val secrets: KSafeEncrypted,
  195. private val vault: KSafeHardwareIsolated,
  196. ) : ViewModel() {
  197. var counter by prefs(0) // delegate, plain
  198. var pin by vault("0000") // delegate, hardware-isolated
  199. fun save(token: String) = secrets.putDirect("token", token) // instance API, encrypted
  200. }
  201. ```
  202. **Alternative spelling** — the accessors `ksafe.encrypted`, `ksafe.hardwareIsolated` and `ksafe.plain` create the same helpers on the spot, with no declaration or injection:
  203. ```kotlin
  204. var token by ksafe.encrypted("") // KSafeEncrypted
  205. var pin by ksafe.hardwareIsolated("") // KSafeHardwareIsolated: StrongBox / Secure Enclave
  206. var theme by ksafe.plain("light") // KSafePlain
  207. ```
  208. `KSafeWriteMode.Encrypted(requireUnlockedDevice = true)` additionally binds the key to the lock screen, so the value cannot be read while the device is locked. On Android 9 to 14 without a secure lock screen the key is minted without that binding, and `ksafe.protectionInfo.notes` says so: [docs/SECURITY_MODEL.md](docs/SECURITY_MODEL.md#known-limitations).
  209. ### More in one line
  210. **Complex objects** — mark them `@Serializable`; JSON and encryption are automatic:
  211. ```kotlin
  212. @Serializable
  213. data class AuthInfo(val accessToken: String = "", val refreshToken: String = "")
  214. var authInfo by ksafe(AuthInfo())
  215. authInfo = authInfo.copy(accessToken = "newToken")
  216. ```
  217. **Nullable values** — `null` is stored as a real value. But a bare `null` default cannot tell Kotlin the type, so name it, on every read shape:
  218. ```kotlin
  219. var token: String? by ksafe(null) // typed declaration
  220. val token = ksafe.get<String?>("token", null) // explicit type parameter
  221. ksafe.getFlow<String?>("token", null).collect { … } // same rule for flows
  222. ```
  223. **Key rotation** — re-encrypt everything under fresh keys, on every platform:
  224. ```kotlin
  225. val result = ksafe.rotateKeys() // on demand: rotated / skipped / failed counts + new generation
  226. // …or make it a policy and forget about it
  227. val ksafe = KSafe(config = KSafeConfig(
  228. keyRotationPolicy = KSafeKeyRotationPolicy.MaxAge(90.days) // rotates in the background at key age 90 days
  229. ))
  230. ```
  231. Crash-safe and resumable: an interrupted rotation keeps everything readable and finishes on the next KSafe instance. Values never change, only key material does. Details: **[docs/KEY_ROTATION.md](docs/KEY_ROTATION.md)**.
  232. **Encrypted database passphrase** — a stable, hardware-isolated 256-bit secret for SQLCipher / SQLDelight / Room:
  233. ```kotlin
  234. val passphrase = ksafe.getOrCreateSecret("main.db") // generated once, same value on every call after
  235. ```
  236. It refuses to overwrite a secret it cannot read back, so it can never silently orphan your database, and key rotation preserves its value. Sizes, protection tiers, full Room + SQLCipher examples: **[docs/SECURITY_MODEL.md#cryptographic-utilities](docs/SECURITY_MODEL.md#cryptographic-utilities)**.
  237. **Biometric gate** — one call raises the platform's own prompt (Face ID, Touch ID, fingerprint, Windows Hello, passkey) from shared code. Requires `ksafe-biometrics`:
  238. ```kotlin
  239. if (KSafeBiometrics.verifyBiometric("Unlock your wallet")) showSecrets()
  240. ```
  241. Pass `authorizationDuration = BiometricAuthorizationDuration(duration = 60_000L, scope = "payments")` to keep the next minute prompt-free in that scope. Details: **[docs/BIOMETRICS.md](docs/BIOMETRICS.md)**.
  242. **What protection did I actually get** — per store and per key, at runtime:
  243. ```kotlin
  244. ksafe.protectionInfo.effectiveLevel // the tier the store really runs at
  245. ksafe.protectionInfo.isEncryptionOperational // will encrypted reads and writes succeed right now?
  246. ksafe.getKeyInfo("pin")?.level // where this one key's material landed
  247. ```
  248. Read it off the main thread on Android. Details: **[docs/PROTECTION_INFO.md](docs/PROTECTION_INFO.md)**.
  249. > **Note:** The property delegate and the direct handle work with **any** KSafe instance — `var x by myKsafe(default)` makes `myKsafe` the storage backend. The bare `ksafe(default)` form requires an in-scope `ksafe` (the conventional name, typically your default instance). See [docs/SETUP.md](docs/SETUP.md#multiple-instances) for the multi-instance pattern.
  250. ### Deleting data
  251. Three calls remove things, and they do very different jobs:
  252. | Call | What it removes | How far it reaches |
  253. |---|---|---|
  254. | `ksafe.delete(key)` / `ksafe.deleteDirect(key)` | one value | one key |
  255. | `ksafe.clearAll()` | every value in the store **and** the encryption keys that protected them | the whole store (this `fileName`) |
  256. | `KSafeBiometrics.clearBiometricAuth()` (`:ksafe-biometrics`) | nothing stored — only the "recently authenticated" window | biometric prompts |
  257. ```kotlin
  258. ksafe.delete("profile") // suspend — returns once the removal is on disk
  259. ksafe.deleteDirect("counter") // returns at once; the cache updates now, the disk follows
  260. ksafe.clearAll() // suspend — wipes this store: values and keys, irreversibly
  261. KSafeBiometrics.clearBiometricAuth() // the next gated action prompts again (all scopes)
  262. KSafeBiometrics.clearBiometricAuth("payments") // or just one scope
  263. ```
  264. Before you call `clearAll()` on logout, know what it takes with it:
  265. - **Everything in this store**, including values written through `ksafe.plain` / `ksafe.encrypted` / `ksafe.hardwareIsolated`, which share it. Stores with a different `fileName` are untouched.
  266. - **Secrets from `getOrCreateSecret`.** A database passphrase kept there is gone, and the next call creates a new one, so a database encrypted with the old passphrase can no longer be opened. If a logout must not touch it, keep it in a separate store, such as `KSafe(fileName = "secrets")`.
  267. - **It cannot be undone.**
  268. There is no `clear()`: use `delete(key)` for one value and `clearAll()` for everything.
  269. ### Hiding KSafe behind your own interface (3.3.0+)
  270. Requested in [#37](https://github.com/ioannisa/KSafe/issues/37).
  271. *The goal.* Your repositories depend on an interface you own, not on KSafe. In the app, that interface is backed by KSafe. In plain unit tests, it is a fake that keeps values in a map, so the tests need no device, no Keystore and no Android `Context`.
  272. ```kotlin
  273. // 1. Your own interface: the rest of the app depends only on this
  274. interface SecureStore {
  275. suspend fun <T> get(key: String, defaultValue: T, serializer: KSerializer<T>): T
  276. suspend fun <T> put(key: String, value: T, serializer: KSerializer<T>)
  277. }
  278. // 2. In the app: backed by KSafe
  279. class KSafeSecureStore(private val ksafe: KSafe) : SecureStore {
  280. override suspend fun <T> get(key: String, defaultValue: T, serializer: KSerializer<T>): T =
  281. ksafe.get(key, defaultValue, serializer)
  282. override suspend fun <T> put(key: String, value: T, serializer: KSerializer<T>) =
  283. ksafe.put(key, value, serializer)
  284. }
  285. // 3. In unit tests: a fake that keeps values in a map
  286. class FakeSecureStore : SecureStore {
  287. private val values = mutableMapOf<String, Any?>()
  288. @Suppress("UNCHECKED_CAST")
  289. override suspend fun <T> get(key: String, defaultValue: T, serializer: KSerializer<T>): T =
  290. if (key in values) values[key] as T else defaultValue
  291. override suspend fun <T> put(key: String, value: T, serializer: KSerializer<T>) {
  292. values[key] = value
  293. }
  294. }
  295. // 4. Your code sees only SecureStore
  296. class AuthRepository(private val store: SecureStore) {
  297. suspend fun accessToken(): String? = store.get("access_token", null, String.serializer().nullable)
  298. suspend fun saveAccessToken(token: String) = store.put("access_token", token, String.serializer())
  299. }
  300. ```
  301. In the app: `AuthRepository(KSafeSecureStore(ksafe))`. In unit tests: `AuthRepository(FakeSecureStore())`.
  302. - Both forms use the same storage: a value saved with `put(key, value, serializer)` reads back with `get(key, default)`, and the other way round.
  303. - For a nullable type, pass a nullable serializer, as `accessToken()` does above.
  304. - To keep short calls such as `store.get("age", 0)`, add a `reified` extension to your interface: **[docs/USAGE.md](docs/USAGE.md#explicit-serializers-330--ksafe-behind-your-own-interface)**.
  305. ***
  306. ## Documentation
  307. Everything else lives in [docs/](docs/). **New here? Start with [USAGE](docs/USAGE.md) and [SETUP](docs/SETUP.md).**
  308. | Topic | What's inside |
  309. |-------|---------------|
  310. | [Complete Usage Guide](docs/USAGE.md) | Every API shape: delegates, flows, Compose state, write modes, mode-typed views, nullables, explicit serializers, full ViewModel |
  311. | [Setup](docs/SETUP.md) | Koin per platform, multi-instance, web `awaitCacheReady()`, custom storage directory, `appNamespace` |
  312. | [Custom JSON Serialization](docs/SERIALIZATION.md) | `KSerializer`s for `UUID`, `Instant`, and other third-party types |
  313. | [Biometric Authentication](docs/BIOMETRICS.md) | Face ID / Touch ID / Fingerprint / Windows Hello / WebAuthn — gate any action, auth caching, scoped sessions |
  314. | [Security Model](docs/SECURITY_MODEL.md) | Runtime security policy (root/debugger/emulator), encryption internals, threat model, crypto utilities (`getOrCreateSecret`, `secureRandomBytes`) |
  315. | [Key Rotation](docs/KEY_ROTATION.md) | `rotateKeys()` and the `MaxAge` policy: crash-safe, resumable, compliance notes |
  316. | [Protection Info](docs/PROTECTION_INFO.md) | `KSafe.protectionInfo` diagnostics: effective key custody, `isEncryptionOperational`, gating patterns |
  317. | [JVM Key Protection](docs/JVM_PROTECTION.md) | Windows DPAPI / macOS Keychain / Linux Secret Service, software fallback, `jdk.unsupported` |
  318. | [Memory Policy](docs/MEMORY.md) | RAM-exposure trade-offs: `LAZY_PLAIN_TEXT`, `PLAIN_TEXT`, `ENCRYPTED`, `ENCRYPTED_WITH_TIMED_CACHE` |
  319. | [Encryption Proof](docs/ENCRYPTION_PROOF.md) | Automated proof tests + commands to inspect the raw stored bytes yourself |
  320. | [Performance Benchmarks](docs/BENCHMARKS.md) | Full tables, cold-start numbers, methodology |
  321. | [Alternatives & Comparison](docs/COMPARISON.md) | KSafe vs SharedPrefs, DataStore, multiplatform-settings, KVault, SQLCipher |
  322. | [Architecture](docs/ARCHITECTURE.md) | The conceptual model: modules, rings, hot cache + write coalescer |
  323. | [Source-tree Tour](docs/TOUR.md) | File-by-file walkthrough of `:ksafe` |
  324. | [Testing](docs/TESTING.md) | Running tests, iOS test app |
  325. | [Migration Guide](docs/MIGRATION.md) | Upgrading from older KSafe versions |
  326. | [Skill for AI Agents](docs/AI_AGENTS.md) | Installing the KSafe skill in Claude Code and other agents, updating it, common pitfalls |
  327. **Compatibility:** Android API 24+ · iOS 13+ · macOS 11+ (`macosArm64`/`macosX64`) · JDK 11+ · WasmGC browsers · Kotlin/JS. Kotlin 2.0+.
  328. ***
  329. ## Community
  330. Contributions are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) before opening issues or pull requests, and follow the [Code of Conduct](CODE_OF_CONDUCT.md). Release notes live in [CHANGELOG.md](CHANGELOG.md).
  331. Security-sensitive bug reports should follow [SECURITY.md](SECURITY.md), not public GitHub issues.
  332. ***
  333. ## Licence
  334. Licensed under the Apache License 2.0 — see http://www.apache.org/licenses/LICENSE-2.0. Distributed "AS IS", without warranties of any kind.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.