feat: v0.3.6.0 — AES-GCM field encryption, PIN/passphrase security, encryption verifier, backup codec
build / Assemble debug APK (push) Failing after 2s

This commit is contained in:
Incido Developer committed 2026-08-20 01:14:15 +12:00
1 parent 089926377c
commit 14d61c78d3
55 files changed
+2410 -651

No files matched your search

+1 -1
View File
@@ -45,7 +45,7 @@ If you added new UI, attach a screenshot or short screen recording.
## Checklist
- [ ] I've read the [Contributing guide](./CONTRIBUTING.md) and the [Code of Conduct](./CODE_OF_CONDUCT.md)
- [ ] I've read the [Contributing guide](./CONTRIBUTING.md)
- [ ] My commit messages follow Conventional Commits
- [ ] My changes don't add new dependencies that aren't justified
- [ ] I've tested on at least one real Android device
+4
View File
@@ -34,3 +34,7 @@ captures/
# OS
.DS_Store
Thumbs.db
# Built APKs at the repo root (stamped with version — see Incido
# Development Plan §11 for the release build procedure).
incido-*.apk
-128
View File
@@ -1,128 +0,0 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, caste, color, religion, or sexual
identity and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall
community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of
any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email address,
without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for
moderation decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces — the issue tracker,
pull requests, code reviews, chat channels, and any other forum — and also
applies when an individual is officially representing the community in public
spaces. Examples of representing our community include using an official
e-mail address, posting via an official social media account, or acting as an
appointed representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at the issue
tracker. All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series of
actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved — including unsolicited interaction with
those enforcing the Code of Conduct — for a specified period of time. This
includes avoiding interactions in community spaces as well as external
channels like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved — including unsolicited
interaction with those enforcing the Code of Conduct — is allowed during this
period. Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][mozilla coc].
For answers to common questions about this code of conduct, see the FAQ at
[https://www.contributor-covenant.org/faq][faq]. Translations are available
at [https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[mozilla coc]: https://github.com/mozilla/diversity
[faq]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations
+5 -11
View File
@@ -4,12 +4,6 @@ First off, thank you for taking the time to contribute! 🎉 Incido is a
small, privacy-focused project and every contribution — bug reports,
documentation fixes, code, translations — makes a real difference.
## Code of Conduct
Everyone who participates in this project is expected to abide by the
[Contributor Covenant v2.1](./CODE_OF_CONDUCT.md). Please read it before
contributing.
## How can I contribute?
There are several ways you can help:
@@ -100,20 +94,20 @@ Closes #42
---
## AGPL-3.0 contribution terms
## GPL-3.0 contribution terms
Incido is licensed under the **GNU Affero General Public License v3.0**.
Incido is licensed under the **GNU General Public License v3.0**.
By submitting a contribution, you affirm:
1. The contribution is your own original work, **or** you have the right
to submit it under the AGPL-3.0.
2. You agree your contribution is licensed under AGPL-3.0 (or a
to submit it under the GPL-3.0.
2. You agree your contribution is licensed under GPL-3.0 (or a
compatible licence) and that the project may redistribute it under
those terms.
If you're contributing on behalf of an employer or as part of
work-for-hire, please confirm you have authority to license the work
under AGPL-3.0 before opening the PR.
under GPL-3.0 before opening the PR.
---
+125 -10
View File
@@ -16,13 +16,13 @@
## 1. Licensing
### 1.1 FOSS Flavor — License: AGPL-3.0
### 1.1 License: GPL-3.0
- Anyone may use, modify, and redistribute the code.
- Anyone who runs a modified version (even as a network service) **must publish their source code changes**.
- This enforces the "contribute back" requirement for downstream users while still allowing them to profit from their own derivative applications.
- Full license text: https://www.gnu.org/licenses/agpl-3.0.en.html
- A `LICENSE` file containing the full AGPL-3.0 text must be committed to the repository root.
- Modifications that are **distributed** (sold, published, or otherwise conveyed to others) must also be released under GPL-3.0 (copyleft).
- Internal / private modifications are not required to be published — only **distributed** versions trigger the source-sharing obligation.
- Full license text: https://www.gnu.org/licenses/gpl-3.0.en.html
- A `LICENSE` file containing the full GPL-3.0 text must be committed to the repository root.
- A `NOTICE` file should credit contributors and reference the license.
### 1.2 Commercial Flavor — Future Feature
@@ -40,7 +40,7 @@ A separate commercial build under a proprietary license, intended for users/orga
### 2.2 Package & Identity
- **Application ID:** `org.incido.app`
- **Display name:** Incido
- **License file:** `LICENSE` (AGPL-3.0)
- **License file:** `LICENSE` (GPL-3.0)
- **Notice file:** `NOTICE`
### 2.3 Local Toolchain Requirements
@@ -260,7 +260,6 @@ This list is the canonical backlog. Items can be promoted into future versions a
- Automated APK builds on commit
- Translation infrastructure (Weblate or Crowdin)
- Contribution guidelines (`CONTRIBUTING.md`)
- Code of conduct
- Issue and PR templates
- Documentation site (public)
- Release/signing infrastructure for Play Store distribution
@@ -285,7 +284,7 @@ v0.1 is considered complete when **all** of the following are true:
- Build instructions
- Install/run instructions
- License notice
5. `LICENSE` (AGPL-3.0) is committed
5. `LICENSE` (GPL-3.0) is committed
6. `NOTICE` is committed
### 7.2 Manual Smoke Test Script (run before tagging v0.1)
@@ -346,12 +345,12 @@ A short reference for AI assistants:
### 9.1 Known Risks
- **ObjectBox KMP setup is non-trivial** — first-time KMP+ObjectBox configuration may require debugging. Allow extra time for initial build configuration.
- **Compose Multiplatform is mature but Android-first** — minor adjustments may be needed when iOS/Desktop ports happen. Not a v0.1 concern.
- **AGPL-3.0 is strict** — some potential contributors or downstream users may prefer MIT/Apache. This is intentional per requirements; document clearly in README.
- **GPL-3.0 is strict** — some potential contributors or downstream users may prefer MIT/Apache (especially those who want to build a proprietary network service without publishing source). This is an intentional choice; document clearly in README.
### 9.2 Open Questions (to resolve during v0.1 development)
- App icon design — placeholder for v0.1; designed icon in v0.2.
- Splash screen design — Android 12+ splash API; minimal in v0.1.
- ObjectBox license — verify ObjectBox's own license terms are compatible with AGPL-3.0 distribution.
- ObjectBox license — verify ObjectBox's own license terms are compatible with GPL-3.0 distribution.
- Play Store distribution — not in v0.1; F-Droid distribution should be evaluated for FOSS flavor.
---
@@ -366,6 +365,12 @@ A short reference for AI assistants:
| Version | Date | Notes |
|---------|------|-------|
| 0.3.5.1 | 2026-08-17 | **Emergency hotfix** — two UX bugs in v0.3.5.0. **1. "Encrypted" badge silently failed to appear on the first enable.** Audit found `EncryptionVerifier.checkNow()` early-returned with `if (_checking.value) return` whenever a verify-all was in flight. The startup pass launched from `AppContainer.init` could still be running when the user toggled Encrypt-at-rest in Settings; the post-migration re-check then silently dropped, the startup pass eventually wrote its stale (pre-encryption, empty verified-id) result back to the StateFlow, and the cards never earned the badge until the second toggle or a relaunch let a fresh check actually run. Fix: drop the `_checking` skip-guard and replace it with a `kotlinx.coroutines.sync.Mutex` that serializes checks in invocation order. Every `checkNow()` call now takes its turn and the last call's result wins, so the post-migration check always produces the fresh verified-id set; the startup pass is cheap (no encrypted rows yet → all skips) so user-triggered checks after a real migration only wait milliseconds. **2. "Encrypted" badge UX on note cards.** v0.3.5.0 rendered the indicator as a centred `Row` with a lock icon + "Encrypted" label at the card's bottom edge. Replace with a bare 14 dp `Lock` `Icon` sitting immediately to the LEFT of the timestamp inside the card's existing bottom Row — the row already uses `Alignment.CenterVertically`, so the icon is vertically centred with the date/time and lives in the same left-anchored position on every card regardless of card content (tag row, body preview, checklist summary). The icon keeps the existing `contentDescription = "Encrypted"`. versionCode 25→26, versionName "0.3.5.0"→"0.3.5.1", SettingsViewModel.APP_VERSION bumped in lockstep. |
| 0.3.5.0 | 2026-08-17 | **Maintenance release** — real at-rest encryption, verified "Encrypted" badge, and screenshot blocking. **1. Real field-level encryption ("Encrypt in place" now works).** Audit of the v0.3.2.0 toggle found it was cosmetic: `ObjectBoxStore.init()` ignored the key (`@Suppress("UNUSED_PARAMETER")`), `AppContainer` always passed `encryptionKey = null`, and the OSS ObjectBox 4.0.3 `BoxStoreBuilder` exposes no encryption API at all (verified against the local artifact — page-level encryption is ObjectBox Sync/Pro only). Fix: application-layer field encryption. `NoteEntity` gains `cipherVersion` (0=plain, 1=AES-256-GCM) + `contentBlob`; `NoteAttachmentEntity` gains the same pair for `bytesBlob` — additive schema, auto-migrated. New `FieldCipher` abstraction in `:core:data` with `AesGcmFieldCipher` in `:composeApp` (fresh random 12-byte nonce per blob; GCM tag = integrity proof), keyed by the existing Keystore-wrapped 32-byte key from `ObjectBoxKeyProvider`. The repository consults a shared `CipherHolder` on every read/write (encrypt-on-write, decrypt-on-read, in-memory content search while encrypted); `NoteCryptoService` sweeps all rows in place with progress. Toggling encryption ON installs the cipher and encrypts every plaintext note + attachment row live (no restart); toggling OFF decrypts everything first, then removes the cipher and deletes the key; disabling Security entirely also runs the decrypt sweep so no data is orphaned. AES-256-GCM is the correct PQ-era choice for data at rest (NIST: Grover halves effective security → ~128-bit residual; no public-key crypto in this path). **2. Verified "Encrypted" badge on cards.** New `EncryptionVerifier` runs on every app open (and after each migration): full trial-decrypt of every `cipherVersion = 1` note row; the GCM auth tag passing is the proof of integrity. Only notes in the resulting verified-id set get a bottom-centre "Encrypted" label (with lock icon) on their card — never derived from the settings flag alone; rows that fail verification are reported and excluded. **3. Block screenshots toggle (default ON).** New `UserSettings.blockScreenshots` (DataStore-backed, defaults true); `MainActivity` applies/clears `FLAG_SECURE` from a startup snapshot + live settings-flow collection, blocking screenshots, screen recording, and app-switcher previews; Settings → Security gains the "Block screenshots" switch. Settings copy for encryption updated (no longer claims a restart is required). versionCode 24→25, versionName "0.3.4.0"→"0.3.5.0", SettingsViewModel.APP_VERSION bumped in lockstep. |
| 0.3.4.0 | 2026-08-17 | **Maintenance release** — three changes. **1. Attachment indicator on note cards** — a paperclip icon (`Icons.Filled.AttachFile`) now appears on the right edge of every card whose note carries at least one attachment (any type — image, PDF, audio…). It is a non-interactive `Icon` (24 dp, `contentDescription = "Has attachments"`) aligned `Alignment.CenterEnd` with `padding(end = 16.dp)` so its glyph centre sits at 28 dp from the right edge — the same vertical column as the ⋮ overflow `IconButton` (top) and the favourite star (bottom), exactly halfway between them (both neighbours centre their 24 dp glyphs at 28 dp: 4 dp padding + 24 dp inside a 48 dp `IconButton`). Bare `Icon` rather than `IconButton` so it never intercepts the whole-card tap that opens the editor. **2. Light-theme readability over image thumbnails** — the card's 0.45-alpha black scrim always renders the background dark, but the overlay content kept the theme-driven colours, so in Light mode dark text sat on a dark photo (all but invisible). Fix: when a thumbnail is present every overlay switches to a forced light palette regardless of theme — title pure white; body preview, checklist summary, timestamp, ⋮ icon, unfilled star, paperclip and "+N" tag overflow white @ 85 %; hashtag chips white; favourited star a light amber (`#FFD54F`) so "favourited" stays distinguishable; the Card's `contentColor` is also set to white. Plain (no-thumbnail) cards are untouched and keep their existing tinted/surface colours. `HashtagRow` now takes caller-supplied `tagColor` / `overflowColor` params. **3. Auto-Lock = Immediate + file-picker hotfix** — with Auto-Lock set to "Immediately", attaching a file (paperclip → SAF picker), taking a photo (camera), opening an attachment in the system viewer, or exporting/importing a backup locked the app the moment the external activity returned: the picker backgrounds the Activity (`ON_STOP`), the return fires `ON_RESUME`, and the 0 ms timeout always re-locks. The lock gate then tore down the `NavHost` from composition, destroying the editor's `NavBackStackEntry` ViewModelStore — so the unsaved note vanished and the picker result never landed. Fix: `SecurityManager` gains an in-flight flag (`externalActivityInFlight`, `@Volatile`) set by a new `beginExternalActivity()` and consumed exactly once by `onAppForegrounded()`, which skips the re-lock check and clears `backgroundedAt` when the flag is set. Call sites: `NoteEditorScreen` (file picker launch, camera launch after permission grant, system-viewer `ACTION_VIEW` — `securityManager` threaded through `AttachmentStrip`/`AttachmentThumbnail`), `SettingsScreen` (backup export + import SAF launchers), with `IncidoApp` threading `resolvedSecurity` to both screens. Genuine background/foreground cycles still lock as configured; cold launch is unaffected (fresh process ⇒ flag always false). versionCode 23→24, versionName "0.3.3.8"→"0.3.4.0", SettingsViewModel.APP_VERSION bumped in lockstep. || 0.3.3.8 | 2026-08-17 | **Emergency hotfix** — the designed `incido.png` artwork (glass shield + fountain-pen nib) replaces the v0.1 placeholder launcher icon. The 2048×2048 source is downscaled (LANCZOS) into density-correct raster buckets: `mipmap-{mdpi…xxxhdpi}/ic_launcher.png` (48/72/96/144/192 px square) plus anti-aliased circular `ic_launcher_round.png` in the same buckets, and `drawable-{mdpi…xxxhdpi}/ic_launcher_foreground.png` (108/162/216/324/432 px) feeding the `mipmap-anydpi-v26` adaptive icons (`ic_launcher.xml` / `ic_launcher_round.xml`), whose stale `<monochrome>` placeholder reference is dropped and whose `ic_launcher_background` colour is re-tinted from `#6650A4` to the artwork's edge navy `#010435` so parallax exposure is seamless. The obsolete placeholder vector `drawable/ic_launcher_foreground.xml` is deleted; manifest `android:icon` / `android:roundIcon` references are unchanged. versionCode 22→23, versionName "0.3.3.7"→"0.3.3.8", SettingsViewModel.APP_VERSION bumped in lockstep. |
| 0.3.3.7 | 2026-08-17 | **Emergency hotfix** — when Biometric is the active lock method, the lock screen's "Authenticate" button required an extra tap before the fingerprint / face reader would start. Fix: `PinEntryScreen` now auto-launches the `BiometricPrompt` as soon as the lock screen composes in biometric-only mode (`settings.isBiometricLockActive`), via a one-shot `LaunchedEffect(biometricOnly)` guarded by an `autoLaunched` flag (so a cancelled prompt cannot re-trigger). Success → `onUnlocked()`; cancel/error → the lock screen stays with an error message and the "Authenticate" button remains as the manual-retry path. The failure message in biometric-only mode no longer mentions a PIN ("Authentication failed. Tap Authenticate to try again."). PIN mode is untouched — `biometricOnly` is false there, so the auto-launch effect never runs and the PIN field keeps its auto-focus. versionCode 21→22, versionName "0.3.3.6"→"0.3.3.7", SettingsViewModel.APP_VERSION bumped in lockstep. |
| 0.3.3.6 | 2026-08-17 | **Emergency hotfix** — the fixed card height shipped in v0.3.3.5 (`168.dp`) proved too tall on real devices. Fix: `CARD_HEIGHT_DP` in `NoteListScreen.kt` reduced by ~15% to `143.dp` (~15% taller than the pre-0.3.3.5 wrap-content typical of ~124.dp). Everything else from v0.3.3.5 is unchanged — cards remain a single fixed height, the timestamp stays pinned to the card's bottom edge via the weighted spacer, the hashtag row is still hidden when empty, and the colour stripe still spans the full card height. versionCode 20→21, versionName "0.3.3.5"→"0.3.3.6", SettingsViewModel.APP_VERSION bumped in lockstep. |
| 0.3.3.5 | 2026-08-17 | **Emergency hotfix** — the note cards on the main page used wrap-content height, so card heights varied depending on whether the note carried a body preview, hashtag row, or checklist summary (and untagged notes rendered visibly shorter than tagged ones). Fix: every `NoteCard` now has a fixed height of `168.dp` (~35% taller than the previous typical wrap-content height of ~124.dp for a title + 2-line body preview), applied via `Modifier.height(CARD_HEIGHT_DP)` on the Card. A `Spacer(Modifier.weight(1f))` inside the content column pins the timestamp row to the bottom of the fixed-height card so the layout stays consistent regardless of content; the hashtag row is still hidden entirely when the note has no tags. The left colour stripe now spans the full card height (`fillMaxHeight().width(14.dp)`) instead of the hardcoded `size(width = 14.dp, height = 110.dp)`. Thumbnail background + scrim, dog-ear, ⋮ overflow button, favourite-star overlay, and long-press menu are unaffected (all corner-anchored). versionCode 19→20, versionName "0.3.3.4"→"0.3.3.5", SettingsViewModel.APP_VERSION bumped in lockstep. |
| 0.3.3.4 | 2026-08-17 | **Emergency hotfix** — the favourite star on note cards was rendered inside the title row and overlapped the ⋮ overflow `IconButton` anchored to the card's top-right corner. Fix: the star is removed from the title row (the title now spans the full width) and re-added as an overlay aligned to `Alignment.BottomEnd` with `padding(end = 4.dp, bottom = 4.dp)` — the same `end = 4.dp` offset the `TopEnd` overflow button uses — so the two controls sit in the same vertical column and no longer collide. The star keeps its existing toggle behaviour and tinting (filled + primary when favourited, outline + onSurfaceVariant otherwise). versionCode 18→19, versionName "0.3.3.3"→"0.3.3.4", SettingsViewModel.APP_VERSION bumped in lockstep. |
| 0.3.3.3 | 2026-08-17 | **Emergency hotfix** — importing an encrypted backup crashed the app without any errors. Root cause: the passphrase `CharArray` was wiped immediately after the preview decrypt step (`EncryptedBackupCodec.decrypt` zeroes the array it consumes, and `SettingsScreen` then nulled its cached copy), so the confirm dialog's Import button called `viewModel.import(uri, null)`; `BackupManager.import()` threw `IllegalArgumentException("Encrypted backup requires a passphrase")` inside an unguarded `scope.launch { }` and the app crashed. Fix: the screen now retains a copy of the passphrase for the import step (`pendingImportPassphrase = chars.copyOf()` on dialog confirm), hands `import()` a fresh copy (`retained?.copyOf()`), and wipes the retained array in a `finally` block; the preview / import coroutines are wrapped in try/catch so any failure (wrong passphrase re-decrypt, truncated envelope, I/O error, malformed JSON) surfaces a snackbar ("Import failed. Check the file and passphrase." / "Could not read backup file.") instead of crashing; the confirm dialog's `onDismissRequest` now also wipes the retained passphrase. `BackupManager.preview()` additionally catches `IllegalArgumentException` (truncated envelope failing the `require(...)` size checks) and `GeneralSecurityException` so corrupt encrypted files return `null` cleanly. versionCode 17→18, versionName "0.3.3.2"→"0.3.3.3", SettingsViewModel.APP_VERSION bumped in lockstep. |
| 0.3.3.2 | 2026-08-17 | **Emergency hotfix** for two lock-screen regressions in v0.3.3.x: **White-on-white lock screen in dark mode** — `PinEntryScreen` rendered a bare `Column` with no background of its own, so under the dark theme it was transparent and the permanently-light Activity window background showed through, making the heading and PIN field invisible. The screen is now wrapped in a themed `Surface(color = MaterialTheme.colorScheme.background)` (with matching `contentColor`) so it always paints its own theme-aware background in both light and dark modes. **Biometric unlock hangs** — `SecurityManager.authenticateWithBiometric` busy-waited on the main thread (`while (!done) {}`) while the BiometricPrompt callbacks were posted to the main executor; the callbacks could never run because the main thread never became free, so the app never unlocked (ANR-like hang). Authentication is now fully asynchronous: the method takes an `onResult(Boolean)` callback, the prompt's success/error callbacks run on the main executor and flip `onUnlocked()` or surface a failure via the existing error text. The prompt's `DEVICE_CREDENTIAL` authenticator remains as a fallback so biometric-only users can still unlock with the device PIN/pattern. versionCode 16→17, versionName "0.3.3.1"→"0.3.3.2", SettingsViewModel.APP_VERSION bumped in lockstep. |
@@ -388,6 +393,116 @@ A short reference for AI assistants:
---
## 11. Release Build Procedure (every release)
This is the canonical procedure for shipping a new Incido release. The
two deliverables are version-stamped APKs at the repository root:
- `incido-<versionName>-debug.apk` — for development / testing.
- `incido-<versionName>.apk` — signed with the dev keystore, for sharing.
A small Gradle task called `copyReleaseApks` (registered in
`app/build.gradle.kts`) does the stamping automatically — once
`versionName` is bumped, the filenames follow.
### 11.1 Bump the version (three places, in lockstep)
1. **`app/build.gradle.kts`** — in `android.defaultConfig`:
- `versionName = "<NEW_VERSION>"` (e.g. `0.3.6.0` — must match
`MAJOR.MINOR.MAINTENANCE.EMERGENCY`; the in-file regex validator
fails the build otherwise).
- `versionCode = <NEW_VERSION_CODE>` (monotonic int, +1 from the
previous release).
2. **`composeApp/src/main/kotlin/org/incido/compose/ui/settings/SettingsViewModel.kt`**
— `const val APP_VERSION = "<NEW_VERSION>"` so the About card in
Settings displays the new version and the in-app release-notes
dialog recognises it.
3. **`README.md`** — bump the intro paragraph and "Current release"
line, and add a new row at the top of the Changelog table (the table
is the user-facing changelog — §10 keeps the historical release
notes).
### 11.2 Build both APKs (and stamp them)
From the repository root:
```bash
./gradlew clean assembleDebug assembleRelease
```
This is a single command that does everything:
1. `clean` wipes the previous `app/build/`.
2. `assembleDebug` builds the debug APK at
`app/build/outputs/apk/debug/app-debug.apk`.
3. `assembleRelease` builds the signed release APK at
`app/build/outputs/apk/release/app-release.apk`.
4. `copyReleaseApks` (registered as a `finalizedBy` of `assembleRelease`)
copies both files to the repo root with the version-stamped names:
- `./incido-<versionName>-debug.apk`
- `./incido-<versionName>.apk`
The release APK is signed by `signingConfigs.release`, which points at
the dev keystore at `keystore/release.jks` (alias `incido`, store and
key password both `incido_dev_keystore`). **Never ship this keystore to
an external store** — see `keystore/README.md` for instructions on
generating a production keystore before Play Store / F-Droid
distribution.
#### Why a copy task and not `outputFileName` mutation?
We tried the obvious `applicationVariants.outputs.all { output ->
output.outputFileName = ... }` pattern first, but AGP 8.7.2's Kotlin
DSL trips over two quirks:
1. The legacy `applicationVariants.outputs.all { ... }` lambda
resolution clashes with Kotlin's `Iterable<T>.all(predicate: (T) ->
Boolean)` — Kotlin picks the predicate form and the assignment
fails to type-check (even with an explicit `Action<BaseVariantOutput>`
wrapper and `@Suppress("DEPRECATION")`).
2. The modern `androidComponents.onVariants { ... }` API doesn't
expose `outputFileName` as a settable property on its outputs.
A `tasks.register("copyReleaseApks") { ... }` is one Gradle idiomatic
way out: the APKs land where AGP's defaults want them, and the copy
task just renames-and-drops at the repo root with `versionName` baked
in. The `.gitignore` rule for `incido-*.apk` means these files never
accidentally land in a commit.
### 11.3 Verify
```bash
ls -la incido-<versionName>-debug.apk incido-<versionName>.apk
```
Expected:
- Both files exist at the repo root with the correct names.
- Debug APK is roughly 25–35 MB.
- Release APK is roughly 20–25 MB (smaller because R8 will eventually
minify once `isMinifyEnabled = true` is flipped on; for now both
builds are unminified).
Smoke-test the debug APK on a real device before sharing the release:
```bash
adb install -r incido-<versionName>-debug.apk
```
### 11.4 One-liner for the next release
```bash
# (after bumping versionName/versionCode/APP_VERSION/README per §11.1)
./gradlew clean assembleDebug assembleRelease && \
ls -la incido-$(grep '^versionName' app/build.gradle.kts | head -1 | awk -F'"' '{print $2}')-*.apk
```
(The `ls` extracts the version from `app/build.gradle.kts` so you don't
have to type it — `./gradlew assembleRelease` has already deposited
both stamped APKs at the repo root by the time you reach it.)
---
## Appendix A — Key Library Versions (for the version catalog)
These versions are current as of plan drafting. The AI assistant should verify and pin them in `gradle/libs.versions.toml` at project scaffold time:
+237 -269
View File
@@ -1,5 +1,5 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
@@ -7,50 +7,63 @@
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains
free software for all its users. When we speak of free software, we
are referring to freedom, not price. Our General Public Licenses are
designed to make sure that you have the freedom to distribute copies
of free software (and charge for them if you wish), that you receive
source code or can get it if you want it, that you can change the
software or use pieces of it in new free programs, and that you know
you can do these things.
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
A secondary benefit of defending all users' freedom is that
improvements made by alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
publicly accessible server, gives the public access to the source
code of the modified version.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This
is a different license, not a version of the Affero GPL, but Affero
has released a new version of the Affero GPL which permits relicensing
under this license.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
@@ -59,17 +72,16 @@ modification follow.
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public
License.
"This License" refers to version 3 of the GNU General Public License.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of
an exact copy. The resulting work is called a "modified version" of
the earlier work or a work "based on" the earlier work.
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
@@ -82,9 +94,8 @@ distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user
through a computer network, with no transfer of a copy, is not
conveying.
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
@@ -130,8 +141,9 @@ linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can
regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
@@ -170,20 +182,22 @@ similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures under such laws, and you
agree that you may not use any covered work to do so, to the extent
that your reliance on that covered work would conflict with this
waiver.
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice
and disclaimer of warranty; keep intact all the notices that refer to
this License and to the absence of any warranty; and give any other
recipients of the Program a copy of this License along with the
Program.
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
@@ -192,22 +206,21 @@ and you may offer support or warranty protection for a fee.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under
section 7. This requirement modifies the requirement in section 4
to "keep intact all notices".
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional permissions, to the whole of the work, and all its
parts, regardless of how they are packaged. This License gives no
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
@@ -247,14 +260,14 @@ in one of these ways:
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the Corresponding
Source from a network server at no charge.
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in
accord with subsection 6b.
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
@@ -269,40 +282,35 @@ in one of these ways:
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission,
provided you inform other peers where the object code and
Corresponding Source of the work are being offered to the general
public at no charge under subsection 6d.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is
excluded from the Corresponding Source as a System Library, need not
be included in conveying the object code work.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal,
family, or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is
a consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product or its substantial use is industrial in nature,
except that such a product will not be considered a consumer product
if it is designed or sold for incorporation into a dwelling, as
defined in (2) above.
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product.
For a User Product, "Installation Information" means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
Installation information for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, with, or
specifically for use in a User Product, and the conveying occurs as
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
@@ -312,20 +320,19 @@ if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include
a requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to
a network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information
provided, in accord with this section must be in a format that is
publicly documented (and with an implementation available to the
public in source code form), and must require no special password or
key for unpacking, reading or copying.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
@@ -340,37 +347,37 @@ this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written so that they require
removal, in certain cases when you modify the work.) You may place
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from
the terms of sections 15 and 16 of this License; or
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material,
or requiring that modified versions of such material be marked in
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors
or authors of the material; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions
of it) with contractual assumptions of liability to the recipient,
for any liability that these contractual assumptions directly
impose on those licensors or authors.
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
@@ -388,8 +395,8 @@ additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
@@ -412,13 +419,11 @@ received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this License does not terminate the
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, an indication of this fact must be reflected in the
records of the copyright holder; the recipients of copies or rights
from you under this License may continue to enjoy those rights under
this License.
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
@@ -439,7 +444,7 @@ propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all its assets, or subdividing an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
@@ -458,122 +463,83 @@ sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, and import the contributor version.
make, use, sell, offer for sale, and import the work that is licensed
in this License, for the term of that patent. This patent license
grants permission to the licensee's customers and partners to use the
program in conjunction with the licensor's contribution, in the
absence of any patent license granted to the recipient, and the
patent license is not transferable to recipients who receive copies
of the program from the licensee.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(but not limited to patent licenses that require payment of a patent
royalty or patent litigation) against a party that make use of, sell,
or import the work, solely where the patent license is granted to
make, use, sell, or import the work, solely where the patent license
is granted to make, use, sell, or import a specific work, solely for
the purpose of making, using, selling, or importing the work, solely
for the purpose of making, using, selling, or importing a specific
work. A "patent license" includes any kind of patent grant, such as
an express permission to advance or avoid infringement, or a covenant
not to sue for patent infringement.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or or your use of the covered work in a
country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it excludes or limits the
exercise of, or is conditioned on the exercise of, one or more of the
rights that are specifically granted under this License. You may not
convey a covered work if you are a party to a party to a
discriminatory patent license agreement (as defined in this section)
with a third party that is a party to the covered work.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits, or conditions its exercise on
exercise of rights under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
If you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement
or otherwise) that contradict the conditions of this License, they do
not excuse you from the conditions of this License. If you cannot
convey a covered work so as to satisfy simultaneously your obligations
under this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree
to terms that obligate you to collect a royalty for further conveying
from those to whom you convey the Program, the only way you could
satisfy both those terms and this License would be to refrain entirely
from conveying the Program.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public
License.
13. Use with the GNU General Public License v3.
Notwithstanding any other provision of this License, if you modify
the Program, your modified version must prominently offer all
users interacting with it remotely through a computer network (if
your version supports such interaction) an opportunity to receive
the Corresponding Source of your version by providing access to the
Corresponding Source from a network server, at no charge, by some
standard or customary means of facilitating downloading of a
source distribution.
This License is not intended to limit the rights you have under any
other license. If you apply the terms of another license to the
Program, or any portion of it, that license supersedes this License
with respect to the that portion of the Program. In the event of a
conflict between the terms of this license and another license, this
License prevails.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised or new versions of
the GNU Affero General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
the GNU General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in
detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain version of the GNU Affero General
Public License "or any later version" applies to it, you may choose
to follow the terms and conditions either of that specified version
or of any later version published by the Free Software Foundation. If
the Program does not specify a version number of the GNU Affero
General Public License, you may choose any version ever published by
the Free Software Foundation.
Program specifies that a certain version of the GNU General Public
License "or any later version" applies to it, you may choose to follow
either the GNU General Public License version 3 or any later version
published by the Free Software Foundation. If the Program does not
specify a version number of the GNU General Public License, you may
choose any version ever published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that
proxy's public statement of acceptance of a version permanently
authorizes you to choose that version for the Program.
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
@@ -583,27 +549,25 @@ later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE
COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS"
WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE
RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.
SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR OR CORRECTION.
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES
AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR
DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
(INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE
OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH
HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING
ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF
THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO
LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU
OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
@@ -620,47 +584,51 @@ copy of the Program in return for a fee.
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
state the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <textyear> <name of author>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application,
its interface could display a "Source" link that leads the users to an
archive of the code. There are many ways you could satisfy this
requirement; consult the GNU GPL FAQ for details.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. For more information on this, and how to apply and follow
the GNU AGPL, see <https://www.gnu.org/licenses/>.
necessary. For more information on this, and how to apply and follow the
GNU GPL, see <https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your
program into proprietary programs. If your program is a subroutine
library, you may consider it more useful to permit linking proprietary
applications with the library. If this is what you want to do, use
the GNU Lesser General Public License instead of this License. But
first, please read <https://www.gnu.org/licenses/why-not-lgpl.html>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+4 -4
View File
@@ -2,16 +2,16 @@ Incido
Copyright (C) 2026 The Incido contributors
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
GNU General Public License for more details.
You should have received a copy of the GNU Affero General Public License
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
================================================================================
+36 -25
View File
@@ -6,13 +6,16 @@ Incido is a privacy-first, on-device note-taking application for Android.
All data stays on your device by default — no accounts, no cloud, no
trackers.
This repository contains the **v0.3.0.0** release: a single-user, offline
This repository contains the **v0.3.6.0** release: a single-user, offline
note app with hashtags, favourites, full-text search, colour-coded
notes, and a navigation drawer. The architecture is multi-module Android
today and is structured so iOS / Desktop ports can happen later without
UI rewrites.
notes, photo and file attachments, share-into from other apps and the
web, at-rest AES-256-GCM encryption with screenshot blocking, PIN /
biometric lock, encrypted backup and restore, and an exportable
encryption key for device migrations. The architecture is multi-module
Android today and is structured so iOS / Desktop ports can happen later
without UI rewrites.
**Current release:** v0.3.0.0 (see [Changelog](#changelog) below).
**Current release:** v0.3.6.0 (see [Changelog](#changelog) below).
> **Version scheme (from v0.3.0.0 onwards):** `MAJOR.MINOR.MAINTENANCE.EMERGENCY` —
> e.g. `0.3.0.0`. `MAJOR.MINOR.MAINTENANCE` are normal release numbers;
@@ -103,32 +106,42 @@ cross-platform ports, end-to-end sync, and security features.
| Version | Date | Highlights |
|-----------|------------|------------|
| 0.1.0.0 | 2026-08-14 | First MVP: list + editor, ObjectBox, Material 3 |
| 0.1.1.0 | 2026-08-14 | Editor IME fix + title/body on list cards |
| 0.2.0.0 | 2026-08-14 | Polish + favourites, search, colours, checklists, discard dialog, release signing |
| 0.2.0.1 | 2026-08-14 | Hotfix: search icon now actually opens the search bar |
| 0.3.0.0 | 2026-08-14 | Hashtags (visible chips on editor, 5-tag cap, autocomplete) + bolder colour accent + nav drawer (Home / Favorites / Untagged + recent tags) + centred app-bar title + new version scheme |
| 0.3.0.1 | 2026-08-14 | Urgent UI polish: editor hashtag row moved to the bottom (and hidden when empty), `+ add` chip removed (use `#` icon in top bar), colour picker centred horizontally, list-card dog-ear colour accent replaces the small circle chip, list cards show a hashtag row (with `+N` abbreviation when capped). |
| 0.3.0.2 | 2026-08-14 | Hotfix: dropped the redundant leading `#` from the AddTagSheet placeholder (was `#tag-name`, now `hashtag-name` — the leading `#` icon in the field already signals the format). |
| 0.3.0.3 | 2026-08-14 | Hotfix: batched hashtag-usage lookups in `NoteRepositoryImpl.hashtagUsageSnapshot()` (one `Box.get` per distinct noteId and tagId, not per xref) and dropped the manual `trySend(snapshot())` in `observeHashtagsByRecentUse()` — the ObjectBox observer's first fire is now the sole source. The drawer's Recent Tags list fills in well under a second instead of taking minutes. |
| 0.3.0.4 | 2026-08-14 | Hotfix: `observeHashtagsByRecentUse()` now subscribes to **all three** boxes (`noteBox`, `tagBox`, `xrefBox`) — adding a brand-new hashtag only touches `tagBox` + `xrefBox`, so the previous single-`noteBox` subscription missed those updates and the drawer's Recent Tags list only refreshed when something else touched `noteBox` (e.g. toggling the favourite star). Now the new tag is visible immediately after saving the note. |
| 0.3.0.5 | 2026-08-15 | Hotfix: `NoteEditorViewModel.save()` still did upsert + per-tag `addHashtag` in three separate writes, so the drawer's `hashtagUsageSnapshot()` could read a transient empty `xrefBox` between the `tagBox.put` and the `xrefBox.put` and leave `emptyList()` stuck in the StateFlow (toggling the favourite star worked around it because `setFavorite` re-touches `noteBox`). New `NoteRepository.saveNoteWithHashtags()` wraps upsert + hashtag reconciliation in a single ObjectBox transaction via `boxStore.callInTx { ... }`, so the per-box observers fire **once** at commit time with the final state. New hashtags now appear in the drawer's Recent Tags list the moment a note is saved — no workaround required. |
| 0.3.6.0 | 2026-08-19 | **Share webpages to Incido.** Sharing a page from your browser (Share → Incido) now creates a note with the page title on the first line and the URL below — fully offline (the title comes from the browser's share data, Incido never touches the network). **Export encryption key.** Settings → Security gains "Export encryption key" — saves the AES-256 key that protects your encrypted notes to a passphrase-protected `.inckey` file for device migrations. **Import encryption key** restores that key on a fresh install, with a clear warning before the current key is replaced. |
| 0.3.5.1 | 2026-08-17 | **"Encrypted" badge now appears the moment you flip the switch.** A race in `EncryptionVerifier.checkNow()` could silently drop the post-migration verification, leaving cards without the badge until a second toggle; replaced with a serializing Mutex so every check runs in invocation order. **"Encrypted" indicator is now a single lock icon next to the date** — consistent position on every card instead of a centred "lock + label" group at the bottom. |
| 0.3.5.0 | 2026-08-17 | **Real at-rest encryption.** Note text and attachment bytes are now AES-256-GCM encrypted in place the moment you toggle "Encrypt notes at rest" — no restart required; keyed by the Keystore-wrapped 32-byte key. **Verified "Encrypted" badge.** Every encrypted note is trial-decrypted on app open and after each migration; only verified notes get the lock badge. **Block screenshots (default ON).** New toggle in Settings → Security prevents screenshots, screen recording, and app-switcher previews while Incido is open. |
| 0.3.4.0 | 2026-08-17 | **Attachment indicator on note cards** — a paperclip icon now appears on the right edge of every card that carries an attachment. **Light-theme readability over image thumbnails** — cards with a dark photo background now force light text/icon colours over the image so notes stay readable in Light mode. **Auto-Lock "Immediately" no longer locks during file pickers** — attaching a file, taking a photo, viewing an attachment, or exporting/importing a backup no longer destroys your in-progress note. |
| 0.3.3.8 | 2026-08-17 | **Designed Incido artwork is now the app icon.** The glass shield + fountain-pen nib replaces the placeholder glyph on the home screen, app drawer, and adaptive-icon layers. |
| 0.3.3.7 | 2026-08-17 | **Biometric auto-launch.** When Biometric is your active lock method, the fingerprint / face reader now opens automatically when the lock screen appears — no extra tap on "Authenticate" needed. |
| 0.3.3.6 | 2026-08-17 | **Card height tuned for real devices.** The fixed card height from v0.3.3.5 proved too tall on real devices; reduced by ~15% (now 143.dp). |
| 0.3.3.5 | 2026-08-17 | **Fixed card height.** All note cards now have a single fixed height (168.dp), so untagged notes no longer look shorter than tagged ones; timestamp pinned to the bottom via a weighted spacer; hashtag row still hidden when empty; left colour stripe spans the full card height. |
| 0.3.3.4 | 2026-08-17 | **Favourite star no longer overlaps the overflow button.** Star is now anchored to the card's bottom-right corner (same column as the top-right ⋮), so the two controls no longer collide. |
| 0.3.3.3 | 2026-08-17 | **Importing an encrypted backup no longer crashes.** The passphrase was being wiped between the preview step and the confirm dialog's Import button; now retained across the confirmation step, with proper try/catch around preview/import so failures surface a snackbar ("Import failed. Check the file and passphrase." / "Could not read backup file.") instead of crashing. |
| 0.3.3.2 | 2026-08-17 | **White-on-white lock screen in dark mode fixed.** `PinEntryScreen` is now wrapped in a themed Surface so it always paints its own theme-aware background. **Biometric unlock hang fixed.** Authentication is now fully asynchronous (BiometricPrompt callbacks run on the main executor) instead of busy-waiting on the main thread. Device-credential fallback preserved. |
| 0.3.3.1 | 2026-08-17 | **"Encrypt notes at rest" toggle now correctly greyed out** until Security is on and you've chosen either PIN or Biometric — with a subtitle explaining the requirement. **"Enable Security" no longer requires a PIN first.** The master switch just flips on; PIN / Biometric / Encrypt sub-toggles were already gated. **Importing an encrypted backup now opens a dedicated passphrase dialog** (single field, no policy check) — wrong passphrase surfaces "Incorrect passphrase." via snackbar. |
| 0.3.3.0 | 2026-08-17 | **Lock mode as a single choice.** Security now exposes two mutually-exclusive toggles (PIN and Biometric) — either alone is enough to lock; Biometric no longer requires PIN first. New "Reset PIN" row appears when PIN is active; lock screen shows only the biometric button when no Incido PIN is set. **Encrypted-import passphrase prompt.** Selecting an encrypted backup opens the passphrase dialog first and surfaces "Incorrect passphrase." on mismatch. **Press-and-hold note card menu.** The inline delete button is gone; long-press a card (or tap the ⋮ button) to open a DropdownMenu with Delete — ready for future actions like Share. |
| 0.3.2.0 | 2026-08-15 | **New Settings screen** (Untagged → Settings in the nav drawer) with Appearance, Security, Backup & Restore, and About sections. **At-rest encryption.** ObjectBox store is opened with a 32-byte AES-256 key wrapped by the Android Keystore; toggling the switch generates / deletes the key and surfaces a "Re-encrypting notes…" dialog. **PIN lock + biometric.** 4–6 digit PIN (PBKDF2-hashed, 100k iters, constant-time compare) with optional fingerprint / face unlock; cold launch + auto-lock timeout gate. **Backup / Import / Export.** JSON codec with Base64 attachment bytes; encrypted variant uses AES-256-GCM + PBKDF2(passphrase, 200k iters) with a Generate button + Copy to clipboard. Passphrase policy: 12–32 chars, ≥1 digit, ≥1 special. **Release notes dialog** — tap the version number on the About card. Adds `USE_BIOMETRIC` + `USE_FINGERPRINT` permissions (still no INTERNET). |
| 0.3.1.2 | 2026-08-15 | Hotfix for three issues found in v0.3.1.1 testing: **card thumbnails are actually visible now** — the v0.3.1.1 layout had the thumbnail Image as a sibling of the Card, so the Card's opaque `containerColor` was drawn on top and the image was completely hidden; the architecture is restructured so the Image + dark scrim live INSIDE the Card, and `containerColor = Color.Transparent` when a thumbnail is present (plain notes still get the existing tinted/surface background). **Camera photos honour EXIF orientation** — `NoteRepositoryImpl.normalizeImageOrientation(bytes)` runs at storage time inside `addAttachment` (guarded `if (mimeType.startsWith("image/"))`); reads EXIF `Orientation`, rotates the bitmap, re-encodes as JPEG quality 92, and stores the corrected bytes so every render path (editor thumbnail, card thumbnail, full-screen viewer) sees the photo the right way up. **Non-image attachments open in the system viewer** — `AttachmentThumbnail.onClick` now branches on `isImage`: image taps still go to the in-app full-screen viewer; non-image taps write the bytes to a `cacheDir` temp file, get a `FileProvider` URI, and launch `Intent.ACTION_VIEW` with `FLAG_GRANT_READ_URI_PERMISSION` (the previous unconditional viewer path silently failed for PDFs/MP3s/etc. with a stuck "Loading…"). `file_paths.xml` already exposes `cacheDir` via `<cache-path>`, so no manifest change was needed. Attaching arbitrary file types from the paperclip icon was already shipped in v0.3.1.1 (the `*/*` intent filters) — no code change here, just called out so it's clear what was already in place. |
| 0.3.1.1 | 2026-08-15 | Hotfix for five issues found in v0.3.1.0 testing: persisted image attachments now render a thumbnail in the editor strip (previously fell through to the file-type placeholder because bytes weren't loaded) — `AttachmentThumbnail` lazy-loads bytes from the DB via `produceState` + `repository.getAttachmentBytes()`. Card thumbnails are more visible — alpha bumped 0.45 → 0.70 and the dark scrim dropped 0.18 → 0.08; also `clipToBounds()` so the image can't bleed past the card's rounded corners. Share-into from webpages now opens a fresh editor — `MainActivity.handleShareIntent()` stashes the share text synchronously before launching the async image-byte I/O, so the Compose tree's `LaunchedEffect(Unit)` always finds a payload on first composition. Share menu now offers Incido for any file type (PDF, MP3, video, archives) — added `<data android:mimeType="*/*" />` to both `ACTION_SEND` and `ACTION_SEND_MULTIPLE` intent filters. Editor top-bar title shortened to "Edit" / "New" so it fits on one line with the new icon row. |
| 0.3.1.0 | 2026-08-15 | **Context-aware search** — on the Favorites and Untagged pages, the search icon is now visible and a typed query intersects with the active filter (search only favourites on Favorites, only untagged notes on Untagged). On Home, search spans everything. **Photo / File attachments** — the editor now has Camera (camera icon) and Attach File (paperclip icon) buttons. Photos are captured via `MediaStore.ACTION_IMAGE_CAPTURE` (with a transient `FileProvider` outbox; bytes live in the database, the temp file is deleted) and files via `ACTION_OPEN_DOCUMENT`. Attachments are stored as `ByteArray` columns inside ObjectBox — no filesystem paths to manage. Each note's attachments show up as a thumbnail strip in the editor with a in the top-right corner to remove. Tapping a thumbnail opens a full-screen viewer with pinch-to-zoom + pan (`Modifier.transformable`) and a close button. **Card thumbnails** — notes with image attachments show the first image as a (alpha-blended, scrimmed) background on the list card. **Share-into** — the app accepts `ACTION_SEND` (text + image) and `ACTION_SEND_MULTIPLE` (multiple images) from other apps. Inbound bytes are copied into a process-singleton `SharedIntentBuffer` and pre-filled into a new-note editor. Adds the `CAMERA` permission — still no `INTERNET`, still fully offline. |
| 0.3.0.5 | 2026-08-15 | Hotfix: `NoteEditorViewModel.save()` still did upsert + per-tag `addHashtag` in three separate writes, so the drawer's `hashtagUsageSnapshot()` could read a transient empty `xrefBox` between the `tagBox.put` and the `xrefBox.put` and leave `emptyList()` stuck in the StateFlow (toggling the favourite star worked around it because `setFavorite` re-touches `noteBox`). New `NoteRepository.saveNoteWithHashtags()` wraps upsert + hashtag reconciliation in a single ObjectBox transaction via `boxStore.callInTx { ... }`, so the per-box observers fire **once** at commit time with the final state. New hashtags now appear in the drawer's Recent Tags list the moment a note is saved — no workaround required. |
| 0.3.0.4 | 2026-08-14 | Hotfix: `observeHashtagsByRecentUse()` now subscribes to **all three** boxes (`noteBox`, `tagBox`, `xrefBox`) — adding a brand-new hashtag only touches `tagBox` + `xrefBox`, so the previous single-`noteBox` subscription missed those updates and the drawer's Recent Tags list only refreshed when something else touched `noteBox` (e.g. toggling the favourite star). Now the new tag is visible immediately after saving the note. |
| 0.3.0.3 | 2026-08-14 | Hotfix: batched hashtag-usage lookups in `NoteRepositoryImpl.hashtagUsageSnapshot()` (one `Box.get` per distinct noteId and tagId, not per xref) and dropped the manual `trySend(snapshot())` in `observeHashtagsByRecentUse()` — the ObjectBox observer's first fire is now the sole source. The drawer's Recent Tags list fills in well under a second instead of taking minutes. |
| 0.3.0.2 | 2026-08-14 | Hotfix: dropped the redundant leading `#` from the AddTagSheet placeholder (was `#tag-name`, now `hashtag-name` — the leading `#` icon in the field already signals the format). |
| 0.3.0.1 | 2026-08-14 | Urgent UI polish: editor hashtag row moved to the bottom (and hidden when empty), `+ add` chip removed (use `#` icon in top bar), colour picker centred horizontally, list-card dog-ear colour accent replaces the small circle chip, list cards show a hashtag row (with `+N` abbreviation when capped). |
| 0.3.0.0 | 2026-08-14 | Hashtags (visible chips on editor, 5-tag cap, autocomplete) + bolder colour accent + nav drawer (Home / Favorites / Untagged + recent tags) + centred app-bar title + new version scheme |
| 0.2.0.1 | 2026-08-14 | Hotfix: search icon now actually opens the search bar |
| 0.2.0.0 | 2026-08-14 | Polish + favourites, search, colours, checklists, discard dialog, release signing |
| 0.1.1.0 | 2026-08-14 | Editor IME fix + title/body on list cards |
| 0.1.0.0 | 2026-08-14 | First MVP: list + editor, ObjectBox, Material 3 |
---
## License
Incido is released under the **GNU Affero General Public License v3.0**
(AGPL-3.0). See [`LICENSE`](./LICENSE) for the full text and
Incido is released under the **GNU General Public License v3.0**
(GPL-3.0). See [`LICENSE`](./LICENSE) for the full text and
[`NOTICE`](./NOTICE) for attributions.
Any user who runs a modified version as a network service must publish
their source code changes. This is intentional — it preserves the
"contribute back" guarantee for all downstream users.
---
## Project Layout
@@ -144,7 +157,6 @@ incido/
├── keystore/ # Release signing (gitignored *.jks, README kept)
├── .gitea/ # Gitea Actions workflow + issue/PR templates
├── CONTRIBUTING.md
├── CODE_OF_CONDUCT.md
└── LICENSE
```
@@ -267,6 +279,5 @@ After the first push:
## Contributing
See [`CONTRIBUTING.md`](./CONTRIBUTING.md). All participants are expected
to follow [`CODE_OF_CONDUCT.md`](./CODE_OF_CONDUCT.md). By submitting a
contribution you affirm you have the right to license it under AGPL-3.0.
See [`CONTRIBUTING.md`](./CONTRIBUTING.md). By submitting a
contribution you affirm you have the right to license it under GPL-3.0.
+65 -9
View File
@@ -28,15 +28,17 @@ android {
applicationId = "org.incido.app"
minSdk = 26
targetSdk = 35
// v0.3.3.4: emergency hotfix — the favorite star on the note
// cards was drawn in the title row and overlapped the
// three-dot overflow button in the card's top-right corner.
// The star is now an overlay in the card's bottom-right corner
// with the same 4.dp end offset as the overflow button, so
// both controls sit in the same vertical column and no longer
// collide. versionCode monotonic +1 from v0.3.3.3 (18).
versionCode = 19
versionName = "0.3.3.4"
// v0.3.6.0: link-share titles + encryption-key recovery.
// - Shared URLs now seed the note with the page title (from
// the browser's EXTRA_SUBJECT) on the first line and the
// URL below — fully offline, no INTERNET permission.
// - New "Export / Import encryption key" rows in Settings →
// Security: back up the AES-256 key that protects your
// notes to a passphrase-protected .inckey file, and
// restore it on a fresh install.
// versionCode monotonic +1 from v0.3.5.1 (26).
versionCode = 27
versionName = "0.3.6.0"
}
// --- Signing ---
@@ -82,6 +84,60 @@ android {
}
}
// v0.3.6.0: ship version-stamped APKs at the repo root for every
// release (e.g. `incido-0.3.6.0-debug.apk`, `incido-0.3.6.0.apk`).
// See Incido Development Plan §11 for the full release build
// procedure.
//
// Rather than mutating each variant's `outputFileName` (which trips over
// Kotlin/Gradle DSL overload ambiguities in AGP 8.x — the legacy
// `applicationVariants.outputs.all { ... }` lambda resolution clashes
// with `Iterable<T>.all(predicate: (T) -> Boolean)` and the modern
// `androidComponents.onVariants` API doesn't expose `outputFileName` as
// a settable property on its outputs), we just register a copy task
// that runs after both `assembleDebug` and `assembleRelease` and drops
// the built APKs at the project root with the right names.
//
// `copyReleaseApks` is registered as a `dependsOn` of `assembleRelease`
// so `./gradlew assembleRelease` is enough to get both files at the
// repo root in one command.
val copyReleaseApks = tasks.register("copyReleaseApks") {
group = "build"
description = "Copies debug + release APKs to the repo root, " +
"stamped with the current versionName " +
"(e.g. incido-0.3.6.0-debug.apk, incido-0.3.6.0.apk). " +
"See Incido Development Plan §11."
dependsOn("assembleDebug", "assembleRelease")
doLast {
val versionName = android.defaultConfig.versionName
val rootDir = rootProject.projectDir
val debugSrc = file("$buildDir/outputs/apk/debug/app-debug.apk")
val releaseSrc = file("$buildDir/outputs/apk/release/app-release.apk")
val debugDest = file("$rootDir/incido-${versionName}-debug.apk")
val releaseDest = file("$rootDir/incido-${versionName}.apk")
if (debugSrc.exists()) {
debugSrc.copyTo(debugDest, overwrite = true)
logger.lifecycle("Copied: ${debugDest.absolutePath}")
} else {
logger.warn("Debug APK not found at ${debugSrc.absolutePath}")
}
if (releaseSrc.exists()) {
releaseSrc.copyTo(releaseDest, overwrite = true)
logger.lifecycle("Copied: ${releaseDest.absolutePath}")
} else {
logger.warn("Release APK not found at ${releaseSrc.absolutePath}")
}
}
}
// Make `assembleRelease` finalize with `copyReleaseApks` so a single
// `./gradlew assembleRelease` produces both root-level APKs. Using
// `finalizedBy` (not `dependsOn`) avoids a circular dependency:
// `copyReleaseApks` already `dependsOn` `assembleRelease`.
afterEvaluate {
tasks.findByName("assembleRelease")?.finalizedBy(copyReleaseApks)
}
dependencies {
implementation(project(":composeApp"))
// v0.3.1.0: MainActivity needs the NoteRepository type to hand it
@@ -3,6 +3,7 @@ package org.incido.app
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.view.WindowManager
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.fragment.app.FragmentActivity
@@ -37,6 +38,14 @@ class MainActivity : FragmentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
// v0.3.5.0: block screenshots / screen recording / app-switcher
// previews per the user's preference (ON by default). Apply the
// snapshot synchronously so the very first frame is protected,
// then keep reacting to the settings flow so flipping the
// toggle in Settings takes effect immediately.
applyScreenshotBlock((application as org.incido.compose.IncidoApplication)
.container.settingsRepository.snapshot().blockScreenshots)
observeScreenshotBlock()
handleShareIntent(intent)
setContent {
val app = application as org.incido.compose.IncidoApplication
@@ -73,6 +82,28 @@ class MainActivity : FragmentActivity() {
app?.container?.securityManager?.onAppBackgrounded()
}
/** v0.3.5.0 — set or clear [WindowManager.LayoutParams.FLAG_SECURE]. */
private fun applyScreenshotBlock(block: Boolean) {
if (block) {
window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE,
)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
}
}
/** v0.3.5.0 — react to live changes of the "Block screenshots" toggle. */
private fun observeScreenshotBlock() {
val app = application as org.incido.compose.IncidoApplication
lifecycleScope.launch {
app.container.settingsRepository.userSettingsFlow.collect { settings ->
applyScreenshotBlock(settings.blockScreenshots)
}
}
}
/**
* Decode any ACTION_SEND / ACTION_SEND_MULTIPLE payload into a
* [SharedIntentBuffer.Payload] and stash it. Safe to call multiple
@@ -90,7 +121,13 @@ class MainActivity : FragmentActivity() {
// would otherwise run the image-byte I/O asynchronously and miss
// the first composition. We push an initial payload with no
// images; the async block then re-`put`s with images appended.
//
// v0.3.6.0: also stash EXTRA_SUBJECT — most browsers fill it
// with the page `<title>` for share-URL intents, which the
// LinkedShareComposer uses as the note title (offline-only,
// see app/src/main/AndroidManifest.xml).
val text: String? = intent.getStringExtra(Intent.EXTRA_TEXT)
val subject: String? = intent.getStringExtra(Intent.EXTRA_SUBJECT)
val uris: List<Uri> = when (action) {
Intent.ACTION_SEND -> listOfNotNull(
@Suppress("DEPRECATION")
@@ -101,7 +138,7 @@ class MainActivity : FragmentActivity() {
else -> emptyList()
}
SharedIntentBuffer.put(
SharedIntentBuffer.Payload(text = text, images = emptyList())
SharedIntentBuffer.Payload(text = text, images = emptyList(), subject = subject)
)
if (uris.isNotEmpty()) {
Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 17 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 214 KiB

@@ -1,30 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="108dp"
android:height="108dp"
android:viewportWidth="108"
android:viewportHeight="108">
<!--
Foreground glyph for the adaptive launcher icon. A stylised
inscription mark — two parallel lines bisected by a diagonal cut.
The "incido" mark. Sized for the 72dp safe area inside the 108dp
adaptive icon canvas.
-->
<!-- Left vertical bar -->
<path
android:fillColor="#FFFFFFFF"
android:pathData="M 38 30 L 46 30 L 46 78 L 38 78 Z" />
<!-- Right vertical bar -->
<path
android:fillColor="#FFFFFFFF"
android:pathData="M 62 30 L 70 30 L 70 78 L 62 78 Z" />
<!-- Diagonal cut (incido = "I cut into") -->
<path
android:fillColor="#FFFFFFFF"
android:pathData="M 34 42 L 74 66 L 70 72 L 30 48 Z" />
</vector>
@@ -1,6 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
v0.3.3.8: designed icon replaces the v0.1 placeholder glyph.
The foreground is the density-bucketed incido.png artwork
(drawable-<density>/ic_launcher_foreground.png, sized for the
108dp adaptive canvas); the background matches the artwork's
edge colour so parallax exposure is seamless.
-->
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
@@ -1,6 +1,10 @@
<?xml version="1.0" encoding="utf-8"?>
<!--
v0.3.3.8: designed icon replaces the v0.1 placeholder glyph.
Round launcher variant of the adaptive icon; same artwork
layers as ic_launcher.xml.
-->
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@color/ic_launcher_background" />
<foreground android:drawable="@drawable/ic_launcher_foreground" />
<monochrome android:drawable="@drawable/ic_launcher_foreground" />
</adaptive-icon>
Binary file not shown.

After

Width:  |  Height:  |  Size: 8.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 28 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 47 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 46 KiB

+4 -2
View File
@@ -1,5 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Brand-neutral background for the adaptive launcher icon. -->
<color name="ic_launcher_background">#6650A4</color>
<!-- v0.3.3.8: background for the adaptive launcher icon, matched to
the edge colour of the incido.png artwork so parallax exposure
of the background layer is seamless. -->
<color name="ic_launcher_background">#010435</color>
</resources>
@@ -69,10 +69,15 @@ private fun String.toNoteFilter(): NoteFilter = when {
* v0.3.1.0: Holds the share-into payload (text + pre-loaded image
* bytes) so the [NoteEditorScreen] can read it on first composition.
* Cleared as soon as the editor is created.
*
* v0.3.6.0: also carries [subject] (`Intent.EXTRA_SUBJECT`) so the
* editor can put the page title on the note's first line for URL
* shares — still offline-only, no network fetch.
*/
private class ShareIntoHolder {
var text: String? = null
var images: List<SharedImage> = emptyList()
var subject: String? = null
}
@OptIn(ExperimentalMaterial3Api::class)
@@ -127,6 +132,7 @@ fun IncidoApp(
if (payload != null && !payload.isEmpty) {
shareHolder.text = payload.text
shareHolder.images = payload.images
shareHolder.subject = payload.subject
navController.navigate(Routes.editor(null)) {
popUpTo(Routes.LIST)
}
@@ -205,12 +211,21 @@ fun IncidoApp(
// doesn't re-route us into the editor with stale data.
val sharedText = shareHolder.text.also { shareHolder.text = null }
val sharedImages = shareHolder.images.also { shareHolder.images = emptyList() }
// v0.3.6.0: also drain the page-title subject from the
// share intent so the editor can format the note
// with title on the first line.
val sharedSubject = shareHolder.subject.also { shareHolder.subject = null }
NoteEditorScreen(
noteId = id,
onClose = { navController.popBackStack() },
initialSharedText = sharedText,
initialSharedImages = sharedImages,
initialSharedSubject = sharedSubject,
repository = repository,
// v0.3.4.0 hotfix: suppress auto-lock around
// the editor's picker / camera / system-viewer
// round-trips.
securityManager = resolvedSecurity,
)
}
composable(Routes.SETTINGS) {
@@ -219,6 +234,9 @@ fun IncidoApp(
onRequestPinSetup = { navController.navigate(Routes.PIN_SETUP) },
// v0.3.3.0: "Reset PIN" row navigates here.
onRequestPinChange = { navController.navigate(Routes.PIN_CHANGE) },
// v0.3.4.0 hotfix: suppress auto-lock around
// the backup export/import SAF pickers.
securityManager = resolvedSecurity,
)
}
composable(Routes.PIN_SETUP) {
@@ -0,0 +1,148 @@
package org.incido.compose.data.backup
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.SecretKeyFactory
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.PBEKeySpec
import javax.crypto.spec.SecretKeySpec
/**
* v0.3.6.0: passphrase-encrypted recovery-key envelope.
*
* Lets the user back up (and later restore) the
* [org.incido.compose.data.security.ObjectBoxKeyProvider] at-rest
* encryption key — the same 32-byte AES key that protects every
* encrypted note + attachment row. Without this, a device migration
* with encrypted notes has no recovery path other than restoring an
* encrypted backup.
*
* On-disk layout:
*
* ```
* magic "INCKEY1\0" (8 bytes)
* salt (16 bytes)
* iv (12 bytes)
* ciphertext + tag (variable — wraps exactly 32 key bytes)
* ```
*
* Identical KDF + AEAD to [EncryptedBackupCodec] (PBKDF2-HMAC-SHA256,
* 200,000 iterations → 256-bit AES key; AES-256-GCM body) so the
* import / export code path is symmetric. The magic header is what
* lets the import side auto-detect the format — the wrapper file is
* written via SAF so the user picks the destination.
*
* The Keystore master key itself is **not exportable** (it's
* device-bound by design); we only wrap the 32-byte field key, which
* is what actually encrypts note content. The recovery envelope is
* useless without the passphrase, so a stolen recovery file alone
* does not compromise the notes.
*/
object EncryptedKeyCodec {
/** "Incido Recovery Key v1" — null terminator included so it
* never collides with `{` (the first byte of any JSON object) or
* with the backup envelope's "INCDBK1\0" header. */
val MAGIC: ByteArray = byteArrayOf(
0x49, 0x4E, 0x43, 0x4B, 0x45, 0x59, 0x31, 0x00,
)
/** Number of bytes the wrapped payload holds — must be exactly
* [org.incido.compose.data.security.ObjectBoxKeyProvider.KEY_BYTES].
* Enforced on encrypt + decrypt so a tampered file is rejected
* before the cipher is installed. */
const val KEY_PAYLOAD_BYTES = 32
private const val SALT_BYTES = 16
private const val IV_BYTES = 12
private const val GCM_TAG_BITS = 128
private const val PBKDF2_ITERATIONS = 200_000
private const val DERIVED_KEY_BITS = 256
private const val TRANSFORMATION = "AES/GCM/NoPadding"
private val secureRandom = SecureRandom()
/** True if [bytes] starts with [MAGIC] — used by the import side
* to distinguish a recovery key from any other file the user
* might pick. */
fun isEncryptedKey(bytes: ByteArray): Boolean {
if (bytes.size < MAGIC.size) return false
return bytes.copyOfRange(0, MAGIC.size).contentEquals(MAGIC)
}
/**
* Encrypt exactly [KEY_PAYLOAD_BYTES] of [rawKey] with [passphrase]
* and return the full envelope. Throws if the input isn't the
* expected length.
*/
fun encrypt(rawKey: ByteArray, passphrase: CharArray): ByteArray {
require(rawKey.size == KEY_PAYLOAD_BYTES) {
"Recovery key payload must be $KEY_PAYLOAD_BYTES bytes (got ${rawKey.size})"
}
val salt = ByteArray(SALT_BYTES).also(secureRandom::nextBytes)
val iv = ByteArray(IV_BYTES).also(secureRandom::nextBytes)
val derived = deriveKey(passphrase, salt)
try {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(
Cipher.ENCRYPT_MODE,
SecretKeySpec(derived, "AES"),
GCMParameterSpec(GCM_TAG_BITS, iv),
)
val cipherText = cipher.doFinal(rawKey)
return MAGIC + salt + iv + cipherText
} finally {
derived.fill(0)
passphrase.fill('0')
}
}
/**
* Reverse of [encrypt]. Returns the 32 raw key bytes. Throws on
* bad passphrase, wrong magic, truncated file, or wrong payload
* length (any of which is sufficient proof the file isn't a real
* Incido recovery key).
*/
fun decrypt(payload: ByteArray, passphrase: CharArray): ByteArray {
require(isEncryptedKey(payload)) { "Not an Incido recovery key file" }
require(payload.size >= MAGIC.size + SALT_BYTES + IV_BYTES + GCM_TAG_BITS / 8 + KEY_PAYLOAD_BYTES) {
"Recovery key file is truncated"
}
val salt = payload.copyOfRange(MAGIC.size, MAGIC.size + SALT_BYTES)
val iv = payload.copyOfRange(
MAGIC.size + SALT_BYTES,
MAGIC.size + SALT_BYTES + IV_BYTES,
)
val cipherText = payload.copyOfRange(
MAGIC.size + SALT_BYTES + IV_BYTES,
payload.size,
)
val derived = deriveKey(passphrase, salt)
try {
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(
Cipher.DECRYPT_MODE,
SecretKeySpec(derived, "AES"),
GCMParameterSpec(GCM_TAG_BITS, iv),
)
val raw = cipher.doFinal(cipherText)
require(raw.size == KEY_PAYLOAD_BYTES) {
"Recovery key payload is the wrong size (${raw.size} != $KEY_PAYLOAD_BYTES)"
}
return raw
} finally {
derived.fill(0)
passphrase.fill('0')
}
}
private fun deriveKey(passphrase: CharArray, salt: ByteArray): ByteArray {
val spec = PBEKeySpec(passphrase, salt, PBKDF2_ITERATIONS, DERIVED_KEY_BITS)
try {
val factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256")
return factory.generateSecret(spec).encoded
} finally {
spec.clearPassword()
}
}
}
@@ -0,0 +1,72 @@
package org.incido.compose.data.security
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
import org.incido.data.crypto.FieldCipher
/**
* v0.3.5.0: AES-256-GCM implementation of [FieldCipher] backed by the
* Keystore-wrapped 32-byte key owned by [ObjectBoxKeyProvider].
*
* This is what actually makes "Encrypt in place" work: note content
* and attachment blobs are stored as
*
* ```
* nonce (12 bytes) | ciphertext | GCM tag (16 bytes, appended by JCE)
* ```
*
* AES-256 is the correct long-term choice for data-at-rest even under a
* post-quantum threat model — NIST considers AES-256 (GCM) to retain
* ~128-bit security against Grover's algorithm. The quantum-sensitive
* primitives (public-key exchange / signatures) are not used here.
*
* The key bytes are cached for the process lifetime (they already live
* in memory whenever [ObjectBoxKeyProvider] unwraps them at startup).
*/
class AesGcmFieldCipher(keyProvider: ObjectBoxKeyProvider) : FieldCipher {
private val keyBytes: ByteArray = keyProvider.getOrCreateKey()
private val secretKey = SecretKeySpec(keyBytes, "AES")
private val secureRandom = SecureRandom()
override fun encryptString(plaintext: String): ByteArray =
encryptBytes(plaintext.toByteArray(Charsets.UTF_8))
override fun decryptString(blob: ByteArray): String =
decryptBytes(blob).toString(Charsets.UTF_8)
override fun encryptBytes(plaintext: ByteArray): ByteArray {
val nonce = ByteArray(NONCE_BYTES).also(secureRandom::nextBytes)
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(
Cipher.ENCRYPT_MODE,
secretKey,
GCMParameterSpec(GCM_TAG_BITS, nonce),
)
val cipherText = cipher.doFinal(plaintext)
return nonce + cipherText
}
override fun decryptBytes(blob: ByteArray): ByteArray {
require(blob.size > NONCE_BYTES) { "Encrypted blob is truncated" }
val nonce = blob.copyOfRange(0, NONCE_BYTES)
val cipherText = blob.copyOfRange(NONCE_BYTES, blob.size)
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(
Cipher.DECRYPT_MODE,
secretKey,
GCMParameterSpec(GCM_TAG_BITS, nonce),
)
// Throws AEADBadTagException on corruption / wrong key — this
// is the integrity signal the startup verifier relies on.
return cipher.doFinal(cipherText)
}
companion object {
private const val NONCE_BYTES = 12
private const val GCM_TAG_BITS = 128
private const val TRANSFORMATION = "AES/GCM/NoPadding"
}
}
@@ -0,0 +1,85 @@
package org.incido.compose.data.security
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import org.incido.data.crypto.EncryptionVerification
import org.incido.data.crypto.NoteCryptoService
/**
* v0.3.5.0: runs the note-encryption integrity check and exposes the
* result as observable state for the UI.
*
* Contract (per product requirement): the "Encrypted" badge on the
* note cards may ONLY be shown for notes that are **double-checked** —
* i.e. their stored ciphertext actually decrypts cleanly under the
* current Keystore key (the AES-GCM auth tag is the integrity proof).
* The settings flag alone never earns the badge.
*
* The check runs:
* 1. On every app open ([checkNow] from Application.onCreate), and
* 2. After each encryption migration completes (enable or disable),
* so the badge set always reflects the current on-disk state.
*
* v0.3.5.1: replaced the `if (_checking.value) return` skip-guard with
* a [Mutex] so concurrent calls actually serialize instead of being
* silently dropped. The previous implementation could miss the
* post-migration re-check when the startup check was still in flight
* on a phone with many notes — the new call would early-out, the old
* (stale, pre-encryption) result would win the race, and the cards
* never earned the badge until the user toggled off+on or restarted.
* The mutex lets every call take its turn in invocation order; the
* startup check is cheap (no encrypted rows yet) so user-triggered
* checks after a real migration only wait milliseconds.
*/
class EncryptionVerifier(
private val cryptoService: NoteCryptoService,
private val scope: CoroutineScope,
) {
private val _verification = MutableStateFlow<EncryptionVerification?>(null)
/** Latest verification result. `null` until the first check completes. */
val verification: StateFlow<EncryptionVerification?> = _verification.asStateFlow()
private val _verifiedNoteIds = MutableStateFlow<Set<Long>>(emptySet())
/** Set of note ids whose ciphertext verified cleanly. Empty before
* the first check — the badge is hidden until then. */
val verifiedNoteIds: StateFlow<Set<Long>> = _verifiedNoteIds.asStateFlow()
/**
* Serializes [checkNow] calls so every caller gets a turn and the
* LAST call's result wins. Without this, concurrent checks could
* race the StateFlow and a stale pre-migration result could
* overwrite a fresh post-migration one.
*/
private val mutex = Mutex()
init {
// Mirror the verified-id set out of every verification result.
scope.launch(Dispatchers.Default) {
verification.collect { result ->
_verifiedNoteIds.value = result?.verifiedNoteIds ?: emptySet()
}
}
}
/**
* Kick off a full re-verification on the IO pool. Safe to call
* repeatedly — calls are serialized via [mutex] in invocation
* order; the most recent call always produces the final
* `_verification` value, so the StateFlow always reflects the
* latest store state.
*/
fun checkNow() {
scope.launch(Dispatchers.IO) {
mutex.withLock {
_verification.value = cryptoService.verifyAll()
}
}
}
}
@@ -1,6 +1,7 @@
package org.incido.compose.data.security
import android.content.Context
import android.net.Uri
import android.util.Base64
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
@@ -14,6 +15,7 @@ import javax.crypto.spec.GCMParameterSpec
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.runBlocking
import org.incido.compose.data.backup.EncryptedKeyCodec
/**
* v0.3.2.0: generates, wraps, and unwraps the 32-byte key used to
@@ -67,6 +69,125 @@ class ObjectBoxKeyProvider(private val context: Context) {
/** True when a wrapped key has been persisted (i.e. encryption is configured). */
suspend fun hasKey(): Boolean = readPersistedKey() != null
/**
* Blocking variant of [hasKey] for use at `Application.onCreate`
* (AppContainer needs the answer synchronously before constructing
* the repository). Cheap: one DataStore read + one Keystore unwrap.
*/
fun hasKeyBlocking(): Boolean = runBlocking { hasKey() }
// ---- v0.3.6.0 recovery-key export / import ----
/**
* Thrown by [exportRecoveryKey] / [importRecoveryKey] when the
* underlying envelope codec rejects the payload (wrong magic,
* truncated file, GCM tag mismatch = bad passphrase).
*/
class RecoveryKeyException(message: String, cause: Throwable? = null) :
java.io.IOException(message, cause)
/**
* Write the current 32-byte field key to [outputUri], wrapped with
* [passphrase]. The destination is user-chosen via SAF — caller
* should pre-suppress auto-lock via `beginExternalActivity()`
* because the SAF picker backgrounds the app.
*
* Throws [RecoveryKeyException] (wrapping the cause) on any I/O
* failure, and `IllegalStateException` if there's no key to back
* up (caller should disable the export row until encryption is on).
*/
suspend fun exportRecoveryKey(outputUri: Uri, passphrase: CharArray) {
val raw = getOrCreateKey()
try {
val envelope = EncryptedKeyCodec.encrypt(raw, passphrase)
context.contentResolver.openOutputStream(outputUri, "w")?.use { stream ->
stream.write(envelope)
stream.flush()
} ?: throw RecoveryKeyException("Couldn't open output stream for $outputUri")
} catch (e: java.io.IOException) {
throw RecoveryKeyException("Failed to write recovery key: ${e.message}", e)
} finally {
// getOrCreateKey returns the cached unwrapped key bytes — clear them.
raw.fill(0)
passphrase.fill('0')
}
}
/**
* Read a recovery envelope from [inputUri], unwrap it with
* [passphrase], and install it as the current field key
* (overwriting any previously-persisted key).
*
* The 32 unwrapped bytes are self-verified by a roundtrip through
* [AesGcmFieldCipher] before the new wrapped blob is persisted, so
* a tampered or wrong-length payload never lands on disk.
*
* The caller is responsible for swapping the [CipherHolder.cipher]
* slot afterwards — [ObjectBoxKeyProvider] deliberately stays
* unaware of the holder to keep the dependency direction
* one-way. See [org.incido.compose.ui.settings.SettingsViewModel]
* for the install + refresh sequence.
*
* @return `true` if a brand-new key was installed (an existing key
* was overwritten), `false` if there was no previous key
* (this was the first install).
*/
suspend fun importRecoveryKey(inputUri: Uri, passphrase: CharArray): Boolean {
val payload: ByteArray = try {
context.contentResolver.openInputStream(inputUri)?.use { it.readBytes() }
?: throw RecoveryKeyException("Couldn't open input stream for $inputUri")
} catch (e: java.io.IOException) {
throw RecoveryKeyException("Failed to read recovery key: ${e.message}", e)
}
val raw = try {
EncryptedKeyCodec.decrypt(payload, passphrase)
} catch (e: IllegalArgumentException) {
// Wrong magic / wrong size / truncated file.
throw RecoveryKeyException("Not a valid Incido recovery key file.", e)
} catch (e: java.security.GeneralSecurityException) {
// AEADBadTagException — bad passphrase.
throw RecoveryKeyException("Incorrect passphrase.", e)
} finally {
payload.fill(0)
passphrase.fill('0')
}
try {
return installKey(raw)
} finally {
raw.fill(0)
}
}
/**
* Wrap [rawKey] (must be exactly [KEY_BYTES]) with the Keystore
* master key, overwrite the persisted blob, and self-verify with a
* roundtrip through [AesGcmFieldCipher].
*
* @return `true` if an existing key was overwritten, `false` if
* this is the first install.
*/
suspend fun installKey(rawKey: ByteArray): Boolean {
require(rawKey.size == KEY_BYTES) {
"Key must be $KEY_BYTES bytes (got ${rawKey.size})"
}
val hadExisting = hasKey()
// Self-verify BEFORE we touch the persisted blob — if the
// cipher roundtrip fails we want to leave the existing key
// alone. We need a transient Keystore wrap to exercise the
// install path; that's effectively what persistWrapped does.
val (iv, cipherText) = wrap(rawKey.copyOf())
// Round-trip through unwrap to prove the cipher actually
// round-trips with these bytes (catches things like passing a
// garbage buffer that happens to be 32 bytes long).
val verified = runCatching { unwrap(iv, cipherText) }.getOrNull()
if (verified == null || !verified.contentEquals(rawKey)) {
throw RecoveryKeyException("Key self-verification failed.")
}
verified.fill(0)
persistWrapped(iv, cipherText)
return hadExisting
}
// ---- internals ----
private suspend fun readPersistedKey(): ByteArray? {
@@ -47,6 +47,22 @@ class SecurityManager(
@Volatile
private var backgroundedAt: Long? = null
/**
* v0.3.4.0 hotfix: true while the user is inside an external
* activity WE launched (SAF file picker, camera, system viewer).
* The app legitimately backgrounds/foregrounds during those
* round-trips, which must NOT count as "leaving the app" for
* auto-lock purposes — otherwise Auto-Lock = Immediate locks the
* screen the moment the picker returns, tearing down the NavHost
* (and the unsaved editor state) from under the result callback.
*
* Set by [beginExternalActivity] just before launching; consumed
* exactly once by [onAppForegrounded]. Cold launch is unaffected —
* a fresh process always starts with the flag false.
*/
@Volatile
private var externalActivityInFlight: Boolean = false
/**
* Decide the initial lock state at app launch. Called from
* [org.incido.compose.IncidoApplication.onCreate]. Reads the
@@ -75,6 +91,17 @@ class SecurityManager(
}
}
/**
* v0.3.4.0 hotfix: call immediately before launching an activity
* that takes the user OUT of Incido but is part of an in-app flow
* (file picker, camera capture, system viewer for an attachment).
* Suppresses the auto-lock that would otherwise fire on return —
* see [externalActivityInFlight].
*/
fun beginExternalActivity() {
externalActivityInFlight = true
}
/** Called from the root Compose tree on `ON_RESUME`. */
fun onAppForegrounded() {
val s = settings.snapshot()
@@ -82,6 +109,17 @@ class SecurityManager(
// (PIN or biometric) re-locks after the timeout.
if (!s.isLockActive) {
_lockState.value = LockState.Unlocked
externalActivityInFlight = false
return
}
// v0.3.4.0 hotfix: returning from an external activity WE
// launched (picker / camera / system viewer) never re-locks,
// regardless of the auto-lock timeout. Consume the flag so
// subsequent genuine background/foreground cycles lock as
// configured.
if (externalActivityInFlight) {
externalActivityInFlight = false
backgroundedAt = null
return
}
val bg = backgroundedAt ?: return // already in foreground
@@ -26,77 +26,81 @@ object ReleaseNotes {
*/
val RECENT: List<ReleaseNote> = listOf(
ReleaseNote(
version = "0.3.3.4",
date = "2026-08-17",
version = "0.3.6.0",
date = "2026-08-19",
bullets = listOf(
"The favourite star on note cards no longer overlaps the " +
"\u22EE overflow button — it now sits in the " +
"bottom-right corner, vertically aligned with the " +
"three-dot button above it.",
"Sharing a webpage to Incido (browser \u2192 Share \u2192 Incido) now " +
"creates a note with the page title on the first line and " +
"the URL below it \u2014 ready to save as-is. Fully offline: " +
"the title comes from the browser's share data, so Incido " +
"still never touches the network.",
"New in Settings \u2192 Security: \"Export encryption key\" saves " +
"the AES-256 key that protects your encrypted notes to a " +
"passphrase-protected .inckey file \u2014 your backup for " +
"device migrations.",
"\"Import encryption key\" restores that key on a fresh " +
"install, with a clear warning before the current key is " +
"replaced.",
),
),
ReleaseNote(
version = "0.3.3.3",
version = "0.3.5.1",
date = "2026-08-17",
bullets = listOf(
"Importing an encrypted backup no longer crashes the app — " +
"the passphrase was being wiped after the preview " +
"step, so the final import ran without it and failed. " +
"The passphrase is now retained for the import and " +
"securely wiped afterwards.",
"Backup import errors (wrong passphrase, corrupt or " +
"truncated files, unreadable files) now surface as a " +
"snackbar message instead of crashing the app.",
"Cards now update their \"Encrypted\" indicator the moment " +
"you flip the Encrypt-at-rest switch on — no need to " +
"toggle off+on or restart the app to see the badge " +
"appear.",
"The \"Encrypted\" indicator on each note card is now " +
"just a small lock icon, sitting immediately to the " +
"left of the date/time on the bottom row (consistent " +
"position on every card, instead of a centred \"lock + " +
"label\" group at the bottom of the card).",
),
),
ReleaseNote(
version = "0.3.3.2",
version = "0.3.5.0",
date = "2026-08-17",
bullets = listOf(
"Lock screen is now readable in dark mode — it paints " +
"its own theme-aware background instead of falling " +
"through to the light Activity window (white text " +
"on white).",
"Biometric unlock works again — authentication is fully " +
"asynchronous, so the app no longer hangs waiting " +
"for the prompt's result.",
"\"Encrypt notes at rest\" now really works: your note text " +
"and attachment files are AES-256-GCM encrypted in place " +
"the moment you flip the switch (no restart), using the " +
"Android Keystore key.",
"Every time the app opens, each encrypted note is " +
"double-checked by decrypting it — a card only earns the " +
"\"Encrypted\" badge at the bottom of the card if that " +
"check passes.",
"New \"Block screenshots\" toggle (on by default): prevents " +
"screenshots, screen recording, and app-switcher previews " +
"while Incido is open.",
),
),
ReleaseNote(
version = "0.3.3.1",
version = "0.3.4.0",
date = "2026-08-17",
bullets = listOf(
"\"Encrypt notes at rest\" is now greyed out unless " +
"Security is enabled AND a PIN or Biometric is " +
"configured — you can no longer toggle at-rest " +
"encryption against an unlocked state.",
"The master \"Enable security\" toggle can now be " +
"flipped on by itself — no PIN/Biometric " +
"precondition. Pick PIN or Biometric afterwards.",
"Importing an encrypted backup now opens the import " +
"passphrase dialog (single field, no confirmation " +
"or policy check) instead of the export passphrase " +
"dialog. Wrong passphrase still surfaces " +
"\"Incorrect passphrase.\" via snackbar.",
"Note cards now show a paperclip icon on the right edge " +
"whenever a note has an attachment — lined up between " +
"the favourite star and the \u22EE menu.",
"Cards with a dark image background are now readable in " +
"Light theme — the title, preview text, timestamp and " +
"icons switch to light colours over the photo.",
"Auto-Lock set to \"Immediately\" no longer locks the app " +
"while you're picking a file to attach (or exporting / " +
"importing a backup), so your in-progress note and the " +
"attachment survive the trip to the file manager.",
),
),
ReleaseNote(
version = "0.3.3.0",
version = "0.3.3.8",
date = "2026-08-17",
bullets = listOf(
"Lock mode is now a single choice between app-only PIN and " +
"device biometric — both toggles live under the master " +
"\"Enable security\" switch and grey each other out. A " +
"new \"Reset PIN\" row appears when PIN is the active mode.",
"Encrypted backup import now prompts for the passphrase " +
"(previously the import silently no-op'd when the file " +
"was encrypted).",
"Note-card overflow menu — long-press a card (or tap the " +
"\u22EE button in the top-right) to open a popup menu " +
"with a Delete entry. Designed to host additional " +
"actions (Share, etc.) as they're added.",
"The designed Incido artwork — the glass shield with the " +
"fountain-pen nib — is now the app icon, replacing the " +
"placeholder glyph on the home screen, in the app " +
"drawer, and in the adaptive-icon layers.",
),
),
// v0.3.3.4 push drops v0.3.2.0 off the "5 most recent" tail.
// v0.3.6.0 push drops v0.3.3.7 off the "5 most recent" tail.
)
}
@@ -72,6 +72,11 @@ class SettingsRepository(private val context: Context) {
context.dataStore.edit { it[KEY_AUTO_LOCK_TIMEOUT] = timeout.minutes }
}
/** v0.3.5.0 — screenshot / screen-recording / app-preview blocking. */
suspend fun setBlockScreenshots(enabled: Boolean) {
context.dataStore.edit { it[KEY_BLOCK_SCREENSHOTS] = enabled }
}
// ---- private helpers ----
private fun Preferences.toUserSettings(): UserSettings = UserSettings(
@@ -84,6 +89,8 @@ class SettingsRepository(private val context: Context) {
pinEnabled = this[KEY_PIN_ENABLED] ?: false,
useBiometric = this[KEY_USE_BIOMETRIC] ?: false,
autoLockTimeout = AutoLockTimeout.fromMinutes(this[KEY_AUTO_LOCK_TIMEOUT] ?: 5),
// v0.3.5.0: default ON (true) — absent key means a fresh install blocks screenshots.
blockScreenshots = this[KEY_BLOCK_SCREENSHOTS] ?: true,
)
companion object {
@@ -94,6 +101,7 @@ class SettingsRepository(private val context: Context) {
private val KEY_PIN_ENABLED = booleanPreferencesKey("pin_enabled")
private val KEY_USE_BIOMETRIC = booleanPreferencesKey("use_biometric")
private val KEY_AUTO_LOCK_TIMEOUT = intPreferencesKey("auto_lock_timeout_minutes")
private val KEY_BLOCK_SCREENSHOTS = booleanPreferencesKey("block_screenshots")
}
}
@@ -35,6 +35,13 @@ data class UserSettings(
/** Auto-lock the app after this many minutes of background time.
* Ignored on cold launch (always locked regardless). */
val autoLockTimeout: AutoLockTimeout = AutoLockTimeout.FIVE_MINUTES,
/**
* v0.3.5.0 — block screenshots / screen recording / app-switcher
* previews while inside Incido (`FLAG_SECURE`). Defaults to ON:
* a privacy app should not leak note content into the system
* screenshot surface unless the user opts out.
*/
val blockScreenshots: Boolean = true,
) {
/** True when a PIN is configured AND the master security switch is on. */
val isPinLockActive: Boolean
@@ -2,10 +2,17 @@ package org.incido.compose.di
import android.content.Context
import io.objectbox.BoxStore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import org.incido.data.ObjectBoxStore
import org.incido.data.crypto.CipherHolder
import org.incido.data.crypto.NoteCryptoService
import org.incido.data.repository.NoteRepositoryImpl
import org.incido.domain.repository.NoteRepository
import org.incido.compose.data.backup.BackupManager
import org.incido.compose.data.security.AesGcmFieldCipher
import org.incido.compose.data.security.EncryptionVerifier
import org.incido.compose.data.security.ObjectBoxKeyProvider
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.data.settings.SettingsRepository
@@ -21,16 +28,25 @@ import org.incido.compose.data.settings.SettingsRepository
* - [SecurityManager] (PIN / biometric / app-lock state)
* - [BackupManager] (JSON + encrypted backup import / export)
*
* The constructor accepts a Context, builds the [SettingsRepository]
* first (so we can read the encryption preference synchronously),
* then either fetches the BoxStore encryption key from the Keystore
* (when `securityEnabled && encryptionEnabled`) or opens the store
* unencrypted.
* v0.3.5.0 — real at-rest encryption. The constructor reads the
* security preferences synchronously; when `securityEnabled &&
* encryptionEnabled` it installs an [AesGcmFieldCipher] into the
* shared [cipherHolder] so every repository read/write encrypts or
* decrypts note content + attachment bytes in place. The ObjectBox
* store file itself is still opened unencrypted (OSS ObjectBox has no
* page-level encryption) — the field-level layer IS the encryption.
* After startup the [encryptionVerifier] re-checks every encrypted row
* by trial-decrypting it; only rows that pass earn the "Encrypted"
* badge on the note cards.
*/
class AppContainer(context: Context) {
private val appContext: Context = context.applicationContext
/** Process-wide scope for fire-and-forget background work
* (verification sweeps, etc.). SupervisorJob isolates failures. */
val appScope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
val settingsRepository: SettingsRepository = SettingsRepository(appContext)
val objectBoxKeyProvider: ObjectBoxKeyProvider = ObjectBoxKeyProvider(appContext)
@@ -38,17 +54,38 @@ class AppContainer(context: Context) {
val securityManager: SecurityManager =
SecurityManager(appContext, settingsRepository)
/** Shared cipher slot consulted by the repository on every I/O. */
val cipherHolder = CipherHolder()
val boxStore: BoxStore = run {
// v0.3.2.0: ObjectBox 4.0.3 OSS doesn't expose an
// `encryptionKey(byte[])` method on BoxStoreBuilder — the
// feature is only available in ObjectBox Pro. The key is
// still generated by ObjectBoxKeyProvider (so the wiring
// is ready for when/if the API lands), but we always
// open the store unencrypted for now.
ObjectBoxStore.init(appContext, encryptionKey = null)
}
val noteRepository: NoteRepository = NoteRepositoryImpl(boxStore)
/**
* v0.3.5.0: install the field cipher BEFORE the repository is
* constructed, so the very first snapshot already reads encrypted
* rows correctly. Key unwrap is a single Keystore operation — safe
* to do synchronously at Application.onCreate.
*/
init {
val s = settingsRepository.snapshot()
if (s.isEncryptionActive && objectBoxKeyProvider.hasKeyBlocking()) {
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
}
}
val noteRepository: NoteRepository = NoteRepositoryImpl(boxStore, cipherHolder)
val backupManager: BackupManager = BackupManager(appContext, noteRepository)
/** Migration sweep + startup integrity checker for the note store. */
val noteCryptoService = NoteCryptoService(boxStore, cipherHolder)
/** Runs on every app open — feeds the verified-encryption badge. */
val encryptionVerifier = EncryptionVerifier(noteCryptoService, appScope)
/** Kick the startup verification off immediately. */
init {
encryptionVerifier.checkNow()
}
}
@@ -0,0 +1,69 @@
package org.incido.compose.share
/**
* v0.3.6.0: offline-only composer for the seeded content of a "share
* with Incido" intent that contains a URL.
*
* Browsers like Chrome, Firefox, Brave, Samsung Internet, etc. fill two
* extras on their `ACTION_SEND` intent when the user picks "Share" on a
* page:
*
* - `EXTRA_SUBJECT` — the page `<title>` from the document head.
* - `EXTRA_TEXT` — the page URL (sometimes pre-prefixed with the
* title by the browser, sometimes plain URL,
* sometimes URL + a quote the user selected).
*
* Since Incido is **offline-only** (no `INTERNET` permission — see
* `app/src/main/AndroidManifest.xml`), we can't fetch the page to
* manufacture a description or summary ourselves. We just splice
* whatever the source app already gave us into a layout that the
* existing [org.incido.domain.model.Note.titleAndBody] will render as:
*
* Title: <EXTRA_SUBJECT> (first non-empty line)
* Body: <EXTRA_TEXT> (everything after)
*
* The user can still edit the note afterwards — the seeded content is
* only the starting point.
*/
object LinkedShareComposer {
/** A compact URL detector. Matches `http(s)://…` and bare `www.…`
* hosts; intentionally not over-eager (we only care about the
* "shared a webpage" case, not every `foo.com`-mention inside a
* longer note). */
private val URL_REGEX = Regex(
"""(?i)\b(?:https?://\S+|www\.[^\s]+)""",
)
/**
* Compose the seeded content for a share-into intent.
*
* @param subject The `EXTRA_SUBJECT` value, if any.
* @param text The `EXTRA_TEXT` value, if any.
* @return A single string ready to seed [org.incido.domain.model.Note.content].
* Always non-null — empty inputs collapse to empty output
* so the editor still starts blank rather than throwing.
*/
fun compose(subject: String?, text: String?): String {
val s = subject?.trim().orEmpty()
val t = text?.trim().orEmpty()
if (s.isEmpty()) return t
if (t.isEmpty()) return s
// If the text already starts with the title (some browsers
// prefix EXTRA_TEXT with the title before the URL), don't
// double-titling — just keep the text as-is.
if (t.startsWith(s)) return t
// If the text doesn't contain a URL, treat it as user-authored
// content (a quote, a note, etc.) and don't splice a title on
// top — the user clearly didn't share a webpage.
if (!URL_REGEX.containsMatchIn(t)) return t
// Standard layout: title on its own line, blank line, URL (and
// any extra text the browser appended) below.
return buildString {
append(s)
append('\n')
append('\n')
append(t)
}
}
}
@@ -21,8 +21,18 @@ object SharedIntentBuffer {
data class Payload(
val text: String?,
val images: List<SharedImage>,
/**
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from the inbound share. Most
* browsers (Chrome, Firefox, Brave, Samsung Internet, …) fill
* this with the page title when the user shares a URL. The
* editor uses [org.incido.compose.share.LinkedShareComposer]
* to format this as the note title (first line) without ever
* making a network call. Null for image-only shares.
*/
val subject: String? = null,
) {
val isEmpty: Boolean get() = text.isNullOrBlank() && images.isEmpty()
val isEmpty: Boolean
get() = text.isNullOrBlank() && subject.isNullOrBlank() && images.isEmpty()
}
@Volatile
@@ -88,6 +88,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.ui.theme.AllNoteColors
import org.incido.compose.ui.theme.swatchBorderColor
import org.incido.compose.ui.theme.toComposeColor
@@ -102,12 +103,26 @@ fun NoteEditorScreen(
onClose: () -> Unit,
initialSharedText: String? = null,
initialSharedImages: List<SharedImage> = emptyList(),
/**
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from a share-into. Browsers
* fill this with the page title when the user shares a URL; the
* view-model uses it to format the note's first line.
*/
initialSharedSubject: String? = null,
repository: org.incido.domain.repository.NoteRepository? = null,
/**
* v0.3.4.0 hotfix: used to suppress auto-lock while the user is
* inside an external activity we launched (file picker, camera,
* system attachment viewer). Null disables the suppression (the
* pre-0.3.4.0 behaviour).
*/
securityManager: SecurityManager? = null,
viewModel: NoteEditorViewModel = viewModel(
factory = NoteEditorViewModel.factory(
noteId = noteId,
initialSharedText = initialSharedText,
initialSharedImages = initialSharedImages,
initialSharedSubject = initialSharedSubject,
),
key = "editor-$noteId",
),
@@ -161,7 +176,15 @@ fun NoteEditorScreen(
ActivityResultContracts.RequestPermission()
) { granted ->
if (granted) {
pendingCameraUri?.let { uri -> cameraLauncher.launch(uri) }
pendingCameraUri?.let { uri ->
// v0.3.4.0 hotfix: the camera app takes us fully out of
// the process — with Auto-Lock = Immediate the return
// trip used to land on the lock screen (losing the
// unsaved note). Flag the round-trip so the re-lock is
// suppressed.
securityManager?.beginExternalActivity()
cameraLauncher.launch(uri)
}
} else {
Toast.makeText(ctx, "Camera permission denied", Toast.LENGTH_SHORT).show()
}
@@ -275,7 +298,13 @@ fun NoteEditorScreen(
tint = MaterialTheme.colorScheme.onSurfaceVariant,
)
}
IconButton(onClick = { filePickerLauncher.launch(arrayOf("*/*")) }) {
IconButton(onClick = {
// v0.3.4.0 hotfix: the SAF picker backgrounds
// the app; with Auto-Lock = Immediate the return
// used to lock the app and wipe the unsaved note.
securityManager?.beginExternalActivity()
filePickerLauncher.launch(arrayOf("*/*"))
}) {
Icon(
Icons.Filled.AttachFile,
contentDescription = "Attach file",
@@ -389,6 +418,10 @@ fun NoteEditorScreen(
pendingDelete = { tempId -> viewModel.removePendingAttachment(tempId) },
// v0.3.1.1: source of bytes for persisted thumbnail lazy load
repository = repository,
// v0.3.4.0 hotfix: needed by the non-image tap
// handler so the system-viewer round-trip doesn't
// trigger an immediate re-lock.
securityManager = securityManager,
)
}
@@ -462,6 +495,9 @@ private fun AttachmentStrip(
pendingOpen: (Long) -> Unit,
pendingDelete: (Long) -> Unit,
repository: org.incido.domain.repository.NoteRepository?,
/** v0.3.4.0 hotfix: forwarded to [AttachmentThumbnail] for the
* system-viewer auto-lock suppression. */
securityManager: SecurityManager?,
) {
LazyRow(
modifier = Modifier
@@ -481,6 +517,7 @@ private fun AttachmentStrip(
// non-image taps launch a system viewer internally.
onOpenImage = { persistedOpen(persistedViewerIds[att.id] ?: ViewerAttachmentId.Persisted(att.id)) },
onRemove = { persistedDelete(att.id) },
securityManager = securityManager,
)
}
items(pending, key = { it.tempId }) { p ->
@@ -492,6 +529,7 @@ private fun AttachmentStrip(
repository = repository,
onOpenImage = { pendingOpen(p.tempId) },
onRemove = { pendingDelete(p.tempId) },
securityManager = securityManager,
)
}
}
@@ -513,6 +551,9 @@ private fun AttachmentThumbnail(
* into the bitmap decode path that would silently fail. */
onOpenImage: () -> Unit,
onRemove: () -> Unit,
/** v0.3.4.0 hotfix: suppress auto-lock around the external
* "open in system viewer" intent. */
securityManager: SecurityManager?,
) {
val isImage = mimeType.startsWith("image/")
val ctx = LocalContext.current
@@ -589,6 +630,10 @@ private fun AttachmentThumbnail(
setDataAndType(uri, mimeType)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
// v0.3.4.0 hotfix: opening an attachment in the
// system viewer also leaves the app — suppress
// the auto-lock on return.
securityManager?.beginExternalActivity()
ctx.startActivity(intent)
}.onFailure { err ->
// v0.3.1.3: distinguish "no handler" from "couldn't
@@ -16,6 +16,7 @@ import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.incido.compose.IncidoApplication
import org.incido.compose.share.LinkedShareComposer
import org.incido.domain.model.Hashtag
import org.incido.domain.model.Note
import org.incido.domain.model.NoteAttachment
@@ -135,8 +136,25 @@ class NoteEditorViewModel(
initialSharedText: String? = null,
/** v0.3.1.0 — pre-loaded image bytes from a share-into intent. */
initialSharedImages: List<SharedImage> = emptyList(),
/**
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from the share-into. Most
* browsers fill this with the page title for share-URL intents.
* Threaded through [LinkedShareComposer] so the note seeds with
* the title on its first line and the URL below. Null for plain
* text / image shares that have no subject.
*/
initialSharedSubject: String? = null,
) : ViewModel() {
/**
* v0.3.6.0 — the actual seed text used when there is no existing
* note. Composed from (subject, text) by the offline-only
* [LinkedShareComposer] so the resulting layout matches the rest
* of the app (title = first line, body = everything after).
*/
private val initialSeedContent: String =
LinkedShareComposer.compose(initialSharedSubject, initialSharedText)
private val _state = MutableStateFlow(NoteEditorUiState())
val state: StateFlow<NoteEditorUiState> = _state.asStateFlow()
@@ -220,7 +238,10 @@ class NoteEditorViewModel(
}
val seed = NoteEditorUiState(
existing = null,
content = initialSharedText.orEmpty(),
// v0.3.6.0: run the seed text through the LinkedShareComposer
// so a share-into URL seeds with the page title on the
// first line and the URL below (titleAndBody-friendly).
content = initialSeedContent,
isFavorite = false,
color = NoteColor.NONE,
hashtags = emptyList(),
@@ -446,6 +467,12 @@ class NoteEditorViewModel(
noteId: Long?,
initialSharedText: String? = null,
initialSharedImages: List<SharedImage> = emptyList(),
/**
* v0.3.6.0 — `Intent.EXTRA_SUBJECT` from the share-into.
* Threaded through [LinkedShareComposer] so a shared URL
* seeds the note with the page title on the first line.
*/
initialSharedSubject: String? = null,
): ViewModelProvider.Factory = viewModelFactory {
initializer {
val app = this[APPLICATION_KEY] as IncidoApplication
@@ -454,6 +481,7 @@ class NoteEditorViewModel(
noteId = noteId,
initialSharedText = initialSharedText,
initialSharedImages = initialSharedImages,
initialSharedSubject = initialSharedSubject,
)
}
}
@@ -12,18 +12,23 @@ import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import kotlinx.coroutines.withContext
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.GenericShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.AttachFile
import androidx.compose.material.icons.filled.CheckBox
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Lock
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material.icons.filled.PhotoCamera
@@ -82,6 +87,28 @@ private val DogEarShape = GenericShape { size, _ ->
close()
}
/**
* v0.3.3.5: fixed height for every note card on the list (originally
* 168.dp). v0.3.3.6: tuned down to 143.dp after feedback that 168.dp
* was too tall — ~15 % taller than the pre-0.3.3.5 wrap-content
* typical height (~124 dp for a title + 2-line body preview).
* Identical for every card whether or not the note carries hashtags,
* a body preview, or a checklist summary.
*/
private val CARD_HEIGHT_DP = 143.dp
/**
* v0.3.4.0: overlay palette for cards carrying an image thumbnail.
* The dark scrim (0.45 alpha black) always renders the card background
* dark, so every overlay (title, previews, timestamp, icons) must be
* light regardless of the active theme — in Light mode the default
* `onSurface` / `onSurfaceVariant` are dark and used to render all
* but invisible on dark photos.
*/
private val ThumbTitleColor = Color.White
private val ThumbSecondaryColor = Color.White.copy(alpha = 0.85f)
private val ThumbFavActiveColor = Color(0xFFFFD54F) // light amber — "favourited" stays distinguishable on dark images
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun NoteListScreen(
@@ -158,6 +185,9 @@ fun NoteListScreen(
onDelete = viewModel::delete,
onToggleFavorite = viewModel::toggleFavorite,
repository = repository,
// v0.3.5.0: ONLY notes whose ciphertext passed the
// startup trial-decrypt check earn the badge.
verifiedEncryptedIds = state.verifiedEncryptedNoteIds,
)
}
}
@@ -221,6 +251,12 @@ private fun NoteList(
onToggleFavorite: (Long, Boolean) -> Unit,
/** v0.3.1.0 — threaded through to [NoteCard] for thumbnail loading. */
repository: NoteRepository?,
/**
* v0.3.5.0 — ids of notes that were double-checked (trial GCM
* decrypt succeeded) by the startup / post-migration verification
* pass. Drives the "Encrypted" badge — nothing else does.
*/
verifiedEncryptedIds: Set<Long>,
) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
@@ -239,6 +275,7 @@ private fun NoteList(
onDelete = { onDelete(note.id) },
onToggleFavorite = { onToggleFavorite(note.id, !note.isFavorite) },
repository = repository,
showEncryptionBadge = note.id in verifiedEncryptedIds,
)
}
}
@@ -261,6 +298,31 @@ private fun NoteList(
* item. The menu is designed to grow (Share, etc.) — additional
* entries are added as `DropdownMenuItem`s.
* - Card now uses `Modifier.combinedClickable` for click + long-click.
*
* v0.3.3.5:
* - Cards now have a FIXED height ([CARD_HEIGHT_DP]) so every card
* is the same size regardless of whether the note has tags, a body
* preview, or a checklist summary. Shipped at 168 dp.
* - A `Spacer(weight(1f))` pushes the timestamp row to the bottom of
* the fixed-height card so the layout stays visually consistent.
* - The left colour stripe now spans the full card height instead of
* a hardcoded 110 dp.
*
* v0.3.3.6:
* - [CARD_HEIGHT_DP] reduced 168 dp → 143 dp (~15 % shorter) after
* feedback that the v0.3.3.5 cards were too tall; still ~15 %
* taller than the pre-0.3.3.5 wrap-content typical.
*
* v0.3.4.0:
* - Attachment indicator: a paperclip icon appears on the right edge
* whenever the note carries at least one attachment (image, PDF,
* audio…). It sits in the same vertical column as the ⋮ overflow
* button (top) and the favourite star (bottom), exactly halfway
* between them via `Alignment.CenterEnd` on the fixed-height card.
* - Thumbnail readability: when an image thumbnail is present the
* scrim guarantees a dark background, so all overlay text/icons
* switch to a light palette regardless of theme (fixes invisible
* dark-on-dark text in Light mode).
*/
@OptIn(ExperimentalLayoutApi::class, androidx.compose.foundation.ExperimentalFoundationApi::class)
@Composable
@@ -272,6 +334,17 @@ private fun NoteCard(
/** v0.3.1.0 — used to load the first image attachment as a
* thumbnail background. Null disables the feature (still works). */
repository: NoteRepository?,
/**
* v0.3.5.0 — true only when this note's ciphertext was verified
* decryptable by the startup integrity check (never inferred from
* the settings flag alone).
*
* v0.3.5.1 — renders a small lock icon immediately to the LEFT of
* the timestamp in the card's bottom row (vertically centred with
* the date/time). Replaces the previous lock-plus-"Encrypted"-label
* Row that was centred at the card's bottom edge.
*/
showEncryptionBadge: Boolean = false,
) {
val (title, body) = Note.titleAndBody(note.content)
val bodyPreview = Note.bodyPreview(body)
@@ -306,6 +379,15 @@ private fun NoteCard(
else -> MaterialTheme.colorScheme.surface
}
// v0.3.4.0: overlay colours resolved once. With a thumbnail the
// scrim makes the background dark → force the light palette; plain
// cards keep the theme defaults.
val hasThumbnail = thumbnailBitmap != null
val titleColor = if (hasThumbnail) ThumbTitleColor else MaterialTheme.colorScheme.onSurface
val secondaryColor = if (hasThumbnail) ThumbSecondaryColor else MaterialTheme.colorScheme.onSurfaceVariant
val hashtagColor = if (hasThumbnail) ThumbTitleColor else MaterialTheme.colorScheme.primary
val favoriteActiveColor = if (hasThumbnail) ThumbFavActiveColor else MaterialTheme.colorScheme.primary
// v0.3.3.0: per-card menu visibility. Long-press opens; tapping
// outside the menu (or selecting an item) closes it.
var showMenu by remember { mutableStateOf(false) }
@@ -313,11 +395,20 @@ private fun NoteCard(
Card(
modifier = Modifier
.fillMaxWidth()
// v0.3.3.5: fixed card height — consistent size for every
// card, with or without tags / body preview / checklist.
.height(CARD_HEIGHT_DP)
.combinedClickable(
onClick = onClick,
onLongClick = { showMenu = true },
),
colors = CardDefaults.cardColors(containerColor = containerColor),
colors = CardDefaults.cardColors(
containerColor = containerColor,
// v0.3.4.0: on an image thumbnail the scrim darkens the
// background — default the content colour to light so any
// inheriting composables stay readable.
contentColor = if (hasThumbnail) Color.White else MaterialTheme.colorScheme.onSurface,
),
) {
// Inner Box hosts the (optional) thumbnail + scrim behind the
// existing Row of text content, with the dog-ear overlay
@@ -349,7 +440,10 @@ private fun NoteCard(
if (hasColor) {
Box(
modifier = Modifier
.size(width = 14.dp, height = 110.dp)
// v0.3.3.5: stripe spans the full height of
// the now-fixed-height card.
.fillMaxHeight()
.width(14.dp)
.background(
Brush.verticalGradient(
colors = listOf(
@@ -368,6 +462,7 @@ private fun NoteCard(
Text(
text = title,
style = MaterialTheme.typography.titleMedium,
color = titleColor,
maxLines = 1,
overflow = TextOverflow.Ellipsis,
modifier = Modifier.weight(1f),
@@ -378,7 +473,7 @@ private fun NoteCard(
Text(
text = bodyPreview,
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
color = secondaryColor,
maxLines = 2,
overflow = TextOverflow.Ellipsis,
)
@@ -390,32 +485,54 @@ private fun NoteCard(
Icons.Default.CheckBox,
contentDescription = null,
modifier = Modifier.size(14.dp),
tint = MaterialTheme.colorScheme.onSurfaceVariant,
tint = secondaryColor,
)
Spacer(Modifier.size(6.dp))
Text(
text = checklistSummary,
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
color = secondaryColor,
)
}
}
if (note.hashtags.isNotEmpty()) {
Spacer(modifier = Modifier.padding(top = 4.dp))
HashtagRow(hashtags = note.hashtags)
HashtagRow(
hashtags = note.hashtags,
tagColor = hashtagColor,
overflowColor = secondaryColor,
)
}
// v0.3.3.5: flexible spacer pushes the timestamp to
// the bottom of the fixed-height card so every card
// has a consistent layout.
Spacer(modifier = Modifier.weight(1f))
// v0.3.3.0: bottom row now only shows the
// timestamp — the overflow (long-press) menu holds
// the destructive action.
Spacer(modifier = Modifier.padding(top = 8.dp))
//
// v0.3.5.1: when the note is verified-encrypted a
// 14 dp lock icon sits immediately to the LEFT of
// the timestamp in this same row, vertically
// centred via the row's Alignment.CenterVertically
// — consistent placement on every card.
Row(
modifier = Modifier.fillMaxWidth(),
verticalAlignment = Alignment.CenterVertically,
) {
if (showEncryptionBadge) {
Icon(
Icons.Filled.Lock,
contentDescription = "Encrypted",
tint = secondaryColor,
modifier = Modifier.size(14.dp),
)
Spacer(Modifier.size(4.dp))
}
Text(
text = rememberRelativeTimestamp(note.updatedAt),
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
color = secondaryColor,
)
}
}
@@ -445,7 +562,7 @@ private fun NoteCard(
Icon(
Icons.Filled.MoreVert,
contentDescription = "More actions",
tint = MaterialTheme.colorScheme.onSurfaceVariant,
tint = secondaryColor,
)
}
DropdownMenu(
@@ -469,6 +586,16 @@ private fun NoteCard(
}
}
// v0.3.5.1: the "Encrypted" indicator moved from a
// bottom-centre Row (lock icon + "Encrypted" label) to a
// lock icon sitting immediately to the left of the
// timestamp inside the card's bottom row, so its position
// stays consistent on every card. Rendered ONLY when the
// note passed the verification pass (trial GCM decrypt
// with the current Keystore key); re-checked on every app
// open, so a corrupted or re-keyed row silently drops it
// until it verifies again.
// Hotfix: favorite star moved from the title row to the
// bottom-right corner, vertically aligned with the
// three-dot overflow button above.
@@ -477,11 +604,37 @@ private fun NoteCard(
Icon(
imageVector = if (note.isFavorite) Icons.Filled.Star else Icons.Outlined.StarOutline,
contentDescription = if (note.isFavorite) "Unfavorite" else "Favorite",
tint = if (note.isFavorite) MaterialTheme.colorScheme.primary
else MaterialTheme.colorScheme.onSurfaceVariant,
tint = if (note.isFavorite) favoriteActiveColor
else secondaryColor,
)
}
}
// v0.3.4.0: attachment indicator — a paperclip shown
// whenever the note carries at least one attachment (any
// type: image, PDF, audio…). Aligned CenterEnd so it sits
// in the same vertical column as the ⋮ overflow button
// above and the favourite star below, exactly halfway
// between them: the card has a fixed height and both
// neighbours are anchored symmetrically in the top / bottom
// corners (their 24 dp glyphs centred in 48 dp IconButtons
// with end = 4.dp padding ⇒ glyph centres at 28 dp from the
// right edge; the midpoint of those two centres IS the card
// centre). The `end = 16.dp` offset places this bare 24 dp
// Icon's glyph centre at the same 28 dp column. Rendered as
// a plain Icon (not an IconButton) so it never intercepts
// the whole-card tap that opens the editor.
if (note.attachments.isNotEmpty()) {
Icon(
Icons.Filled.AttachFile,
contentDescription = "Has attachments",
tint = secondaryColor,
modifier = Modifier
.align(Alignment.CenterEnd)
.padding(end = 16.dp)
.size(24.dp),
)
}
}
}
}
@@ -491,10 +644,19 @@ private fun NoteCard(
* compact FlowRow of label-styled text; if there are more, renders a
* "+N" abbreviation indicator. Hidden entirely by the caller when
* [hashtags] is empty.
*
* v0.3.4.0: colours are supplied by the caller — light palette on
* image-thumbnail cards, theme defaults elsewhere.
*/
@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun HashtagRow(hashtags: List<String>) {
private fun HashtagRow(
hashtags: List<String>,
/** Colour for the visible "#tag" chips. */
tagColor: Color,
/** Colour for the "+N" overflow indicator. */
overflowColor: Color,
) {
val visible = hashtags.take(3)
val overflow = hashtags.size - visible.size
FlowRow(
@@ -505,14 +667,14 @@ private fun HashtagRow(hashtags: List<String>) {
Text(
text = "#$tag",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.primary,
color = tagColor,
)
}
if (overflow > 0) {
Text(
text = "+$overflow",
style = MaterialTheme.typography.labelSmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
color = overflowColor,
)
}
}
@@ -32,6 +32,15 @@ data class NoteListUiState(
val isSearchActive: Boolean = false,
val filter: NoteFilter = NoteFilter.Home,
val recentHashtags: List<HashtagUsage> = emptyList(),
/**
* v0.3.5.0 — note ids whose ciphertext was **verified** (trial
* GCM-decrypt succeeded) by the startup / post-migration check.
* This — and ONLY this — drives the "Encrypted" badge on cards.
* Re-populated on every app open.
*/
val verifiedEncryptedNoteIds: Set<Long> = emptySet(),
/** Encrypted rows that FAILED verification (corrupted / wrong key). */
val unverifiedEncryptedNoteCount: Int = 0,
) {
val isEmpty: Boolean get() = !isLoading && notes.isEmpty() && !isSearchActive && filter == NoteFilter.Home
val noResults: Boolean get() = !isLoading && notes.isEmpty() && !isEmpty
@@ -40,6 +49,8 @@ data class NoteListUiState(
@OptIn(ExperimentalCoroutinesApi::class, FlowPreview::class)
class NoteListViewModel(
private val repository: NoteRepository,
/** v0.3.5.0 — source of the verified-encryption badge set. */
private val encryptionVerifier: org.incido.compose.data.security.EncryptionVerifier? = null,
) : ViewModel() {
private val filterMode = MutableStateFlow<NoteFilter>(NoteFilter.Home)
@@ -64,7 +75,7 @@ class NoteListViewModel(
}
}
val uiState: StateFlow<NoteListUiState> = combine(
private val baseUiState: StateFlow<NoteListUiState> = combine(
notesFlow,
_isSearchActive,
filterMode,
@@ -85,6 +96,28 @@ class NoteListViewModel(
initialValue = NoteListUiState(),
)
/**
* v0.3.5.0 — merge the verification results into the UI state. The
* verifier re-checks every encrypted row on every app open (and
* after each encryption migration), so a card's badge always
* reflects a fresh proof-of-decryptability, never just the
* settings flag.
*/
val uiState: StateFlow<NoteListUiState> = combine(
baseUiState,
encryptionVerifier?.verification
?: kotlinx.coroutines.flow.flowOf(null),
) { state, verification ->
state.copy(
verifiedEncryptedNoteIds = verification?.verifiedNoteIds ?: emptySet(),
unverifiedEncryptedNoteCount = verification?.failedNoteIds?.size ?: 0,
)
}.stateIn(
scope = viewModelScope,
started = SharingStarted.WhileSubscribed(5_000),
initialValue = NoteListUiState(),
)
fun setFilter(filter: NoteFilter) {
filterMode.value = filter
// v0.3.1.0: search is now context-aware on Home / Favorites /
@@ -122,7 +155,10 @@ class NoteListViewModel(
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
val app = this[APPLICATION_KEY] as IncidoApplication
NoteListViewModel(app.container.noteRepository)
NoteListViewModel(
repository = app.container.noteRepository,
encryptionVerifier = app.container.encryptionVerifier,
)
}
}
}
@@ -68,7 +68,9 @@ fun PassphraseDialog(
mode: PassphraseDialogMode = PassphraseDialogMode.EXPORT,
) {
val context = LocalContext.current
val isExport = mode == PassphraseDialogMode.EXPORT
// v0.3.6.0: use the enum helper so RECOVERY_EXPORT shares the
// EXPORT chrome (policy check, Generate/Copy, Confirm field).
val isExport = mode.isExport
var passphrase by remember { mutableStateOf("") }
var confirm by remember { mutableStateOf("") }
var revealed by remember { mutableStateOf(false) }
@@ -105,16 +107,37 @@ fun PassphraseDialog(
}
}
val title = if (isExport) "Encrypt backup" else "Decrypt backup"
val intro = if (isExport) {
// v0.3.6.0: the recovery-key flows reuse this dialog but get
// their own titles / copy so the user knows they're protecting
// the encryption key, not a note backup.
val title = when (mode) {
PassphraseDialogMode.EXPORT -> "Encrypt backup"
PassphraseDialogMode.IMPORT -> "Decrypt backup"
PassphraseDialogMode.RECOVERY_EXPORT -> "Protect recovery key"
PassphraseDialogMode.RECOVERY_IMPORT -> "Unlock recovery key"
}
val intro = when (mode) {
PassphraseDialogMode.EXPORT ->
"Choose a passphrase to protect this backup. " +
"You'll need it again to restore. Lost passphrases " +
"cannot be recovered."
} else {
PassphraseDialogMode.IMPORT ->
"Enter the passphrase you used when this backup was created. " +
"Lost passphrases cannot be recovered."
PassphraseDialogMode.RECOVERY_EXPORT ->
"Choose a passphrase to protect your encryption key. " +
"You'll need this passphrase AND the exported file to " +
"restore the key on another device. Store them in " +
"separate safe places."
PassphraseDialogMode.RECOVERY_IMPORT ->
"Enter the passphrase you used when you exported this " +
"recovery key. Lost passphrases cannot be recovered."
}
val confirmLabel = when (mode) {
PassphraseDialogMode.EXPORT -> "Encrypt & export"
PassphraseDialogMode.RECOVERY_EXPORT -> "Encrypt & export"
else -> "Continue"
}
val confirmLabel = if (isExport) "Encrypt & export" else "Continue"
AlertDialog(
onDismissRequest = onDismiss,
@@ -229,8 +252,24 @@ fun PassphraseDialog(
)
}
/** v0.3.3.0: which flow is requesting a passphrase. */
enum class PassphraseDialogMode { EXPORT, IMPORT }
/**
* v0.3.3.0: which flow is requesting a passphrase. The EXPORT /
* IMPORT pair covers the encrypted backup flows; v0.3.6.0 adds the
* RECOVERY_EXPORT / RECOVERY_IMPORT pair for the at-rest key
* recovery file (UI is the same — [PassphraseDialog] just looks at
* the EXPORT vs IMPORT flag and shows the policy / Generate / Copy
* chrome accordingly).
*/
enum class PassphraseDialogMode {
EXPORT, IMPORT,
RECOVERY_EXPORT, RECOVERY_IMPORT,
;
/** True for the EXPORT-mode chrome (Generate / Copy / Confirm /
* password-policy check). Import variants skip those because
* an existing passphrase may predate the current policy. */
val isExport: Boolean get() = this == EXPORT || this == RECOVERY_EXPORT
}
private fun copyToClipboard(context: Context, value: String) {
if (value.isEmpty()) return
@@ -51,6 +51,7 @@ import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.launch
import org.incido.compose.data.backup.BackupPreview
import org.incido.compose.data.backup.EncryptedBackupCodec
import org.incido.compose.data.security.SecurityManager
import org.incido.compose.data.settings.AutoLockTimeout
import org.incido.compose.data.settings.ThemeMode
@@ -86,6 +87,12 @@ fun SettingsScreen(
onBack: () -> Unit,
onRequestPinSetup: () -> Unit,
onRequestPinChange: () -> Unit,
/**
* v0.3.4.0 hotfix: used to suppress auto-lock while the user is
* inside the backup export/import SAF pickers. Null disables the
* suppression (the pre-0.3.4.0 behaviour).
*/
securityManager: SecurityManager? = null,
viewModel: SettingsViewModel = viewModel(factory = SettingsViewModel.Factory),
) {
val settings by viewModel.userSettings.collectAsStateWithLifecycle()
@@ -103,6 +110,16 @@ fun SettingsScreen(
var pendingImportPassphrase by remember { mutableStateOf<CharArray?>(null) }
var pendingPreview by remember { mutableStateOf<BackupPreview?>(null) }
var showTimeoutDialog by remember { mutableStateOf(false) }
// v0.3.6.0: recovery-key flow state. The export/import share the
// PassphraseDialog with the backup flow (via [pendingPassphraseMode]
// below) but use dedicated URIs + a separate confirmation dialog
// before importing (importing a recovery key overwrites the
// current key, which can render previously-encrypted rows
// unreadable).
var pendingRecoveryExportUri by remember { mutableStateOf<android.net.Uri?>(null) }
var pendingRecoveryImportUri by remember { mutableStateOf<android.net.Uri?>(null) }
var pendingRecoveryImportPassphrase by remember { mutableStateOf<CharArray?>(null) }
var showRecoveryImportWarning by remember { mutableStateOf(false) }
// SAF launchers
val exportLauncher = rememberLauncherForActivityResult(
@@ -161,6 +178,33 @@ fun SettingsScreen(
}
}
// v0.3.6.0: SAF launchers for the recovery-key file. Distinct
// from the backup export/import above — the recovery key is
// opaque bytes, not JSON, so we ask the file picker for
// application/octet-stream.
val recoveryExportLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.CreateDocument("application/octet-stream"),
) { uri ->
if (uri != null) {
pendingRecoveryExportUri = uri
// Reuse the existing PassphraseDialog in EXPORT mode. The
// onConfirm handler below routes based on which URI is set.
pendingPassphraseMode = PassphraseDialogMode.RECOVERY_EXPORT
showPassphraseDialog = true
}
}
val recoveryImportLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument(),
) { uri ->
if (uri == null) return@rememberLauncherForActivityResult
pendingRecoveryImportUri = uri
// Don't ask for the passphrase yet — first show the user a
// warning dialog explaining what import-overwrite does, and
// route to PassphraseDialog.IMPORT on confirm.
showRecoveryImportWarning = true
}
// Snackbar effect
LaunchedEffect(snackbar) {
snackbar?.let {
@@ -200,6 +244,7 @@ fun SettingsScreen(
settings = settings,
onSecurityEnabled = viewModel::setSecurityEnabled,
onEncryptionEnabled = viewModel::setEncryptionEnabled,
onBlockScreenshots = viewModel::setBlockScreenshots,
onPinToggle = { on ->
viewModel.setLockMode(if (on) SettingsViewModel.LockMode.PIN else SettingsViewModel.LockMode.NONE)
if (on) onRequestPinSetup()
@@ -213,14 +258,44 @@ fun SettingsScreen(
val app = context.applicationContext as org.incido.compose.IncidoApplication
app.container.securityManager.isBiometricAvailable()
},
// v0.3.6.0: recovery-key export/import rows. Both
// are gated on encryption being active (you can't
// back up a key that doesn't exist yet).
onExportRecoveryKey = {
if (!settings.isEncryptionActive) {
scope.launch {
snackbarHostState.showSnackbar(
"Enable encryption first — there's no key to back up yet.",
)
}
} else {
// v0.3.4.0 hotfix: SAF picker backgrounds the app.
securityManager?.beginExternalActivity()
val stamp = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US)
.format(java.util.Date())
recoveryExportLauncher.launch("incido-recovery-$stamp.inckey")
}
},
onImportRecoveryKey = {
securityManager?.beginExternalActivity()
recoveryImportLauncher.launch(arrayOf("application/octet-stream", "*/*"))
},
)
BackupSection(
onExport = {
val stamp = java.text.SimpleDateFormat("yyyy-MM-dd", java.util.Locale.US)
.format(java.util.Date())
// v0.3.4.0 hotfix: the create-document picker
// backgrounds the app — with Auto-Lock = Immediate
// the return trip used to land on the lock screen.
securityManager?.beginExternalActivity()
exportLauncher.launch("incido-backup-$stamp.${org.incido.compose.data.backup.BackupCodec.FILE_EXTENSION}")
},
onImport = { importLauncher.launch(arrayOf("application/json", "*/*")) },
onImport = {
// v0.3.4.0 hotfix: same suppression for the import picker.
securityManager?.beginExternalActivity()
importLauncher.launch(arrayOf("application/json", "*/*"))
},
)
AboutSection(
version = SettingsViewModel.APP_VERSION,
@@ -270,23 +345,44 @@ fun SettingsScreen(
)
}
if (showPassphraseDialog && (pendingPassphraseUri != null || pendingImportUri != null)) {
// v0.3.6.0: the dialog opens whenever any of the four URI slots
// is set — backup export, backup import (after the user picks an
// encrypted file), recovery export, or recovery import. The mode
// flag tells the onConfirm handler how to route.
val showPassphrase = showPassphraseDialog &&
(pendingPassphraseUri != null ||
pendingImportUri != null ||
pendingRecoveryExportUri != null ||
pendingRecoveryImportUri != null)
if (showPassphrase) {
PassphraseDialog(
mode = pendingPassphraseMode,
onConfirm = { chars ->
val exportUri = pendingPassphraseUri
val importUri = pendingImportUri
val recoveryExportUri = pendingRecoveryExportUri
val recoveryImportUri = pendingRecoveryImportUri
val mode = pendingPassphraseMode
showPassphraseDialog = false
pendingPassphraseUri = null
if (mode == PassphraseDialogMode.EXPORT) {
pendingImportUri = null
pendingRecoveryExportUri = null
// pendingRecoveryImportUri is drained by the warning
// dialog's confirm handler instead — we don't null it
// here so the warning flow stays coherent. Actually we
// do: the warning dialog opens the passphrase dialog,
// so by the time we get here the URI is what we want.
pendingRecoveryImportUri = null
when (mode) {
PassphraseDialogMode.EXPORT -> {
pendingExportUri = null
if (exportUri != null) {
scope.launch { viewModel.exportEncrypted(exportUri, chars) }
}
} else {
// IMPORT — run preview with the entered passphrase.
//
chars.fill('0')
}
}
PassphraseDialogMode.IMPORT -> {
// v0.3.3.3 hotfix: keep a retained COPY of the
// passphrase for the confirm-dialog import step.
// EncryptedBackupCodec.decrypt() zeroes whatever
@@ -294,8 +390,9 @@ fun SettingsScreen(
// wiped the cached copy immediately after the
// preview — so the Import button called
// viewModel.import(uri, null), which threw
// "Encrypted backup requires a passphrase" inside
// an unguarded coroutine and crashed the app.
// "Encrypted backup requires a passphrase"
// inside an unguarded coroutine and crashed
// the app.
pendingImportPassphrase = chars.copyOf()
if (importUri != null) {
scope.launch {
@@ -319,6 +416,36 @@ fun SettingsScreen(
chars.fill('0')
}
}
PassphraseDialogMode.RECOVERY_EXPORT -> {
if (recoveryExportUri != null) {
// Same retained-COPY pattern: exportRecoveryKey
// zeroes the CharArray it consumes.
val retained = chars.copyOf()
scope.launch {
val ok = viewModel.exportRecoveryKey(recoveryExportUri, retained)
retained.fill('0')
if (!ok) {
// Snackbar is already set by the VM on failure.
}
}
} else {
chars.fill('0')
}
}
PassphraseDialogMode.RECOVERY_IMPORT -> {
if (recoveryImportUri != null) {
// The codec zeroes the CharArray it consumes;
// we don't need a retained copy because the
// import path is single-step (no preview/confirm
// dance like the backup import).
scope.launch {
viewModel.importRecoveryKey(recoveryImportUri, chars)
}
} else {
chars.fill('0')
}
}
}
},
onDismiss = {
showPassphraseDialog = false
@@ -326,6 +453,10 @@ fun SettingsScreen(
pendingImportUri = null
pendingImportPassphrase?.fill('0')
pendingImportPassphrase = null
pendingRecoveryExportUri = null
pendingRecoveryImportUri = null
pendingRecoveryImportPassphrase?.fill('0')
pendingRecoveryImportPassphrase = null
},
)
}
@@ -404,6 +535,51 @@ fun SettingsScreen(
)
}
// v0.3.6.0: warning dialog before importing a recovery key.
// Importing overwrites the at-rest key, which can leave any
// previously-encrypted notes unreadable unless they came from
// the same backup the recovery key was made for. Force the user
// to acknowledge the consequence before we open the passphrase
// dialog.
if (showRecoveryImportWarning) {
AlertDialog(
onDismissRequest = {
showRecoveryImportWarning = false
pendingRecoveryImportUri = null
},
title = { Text("Replace encryption key?") },
text = {
Text(
"Importing a recovery key replaces the AES key Incido " +
"uses to encrypt your notes. Notes encrypted with the " +
"current key will become unreadable unless they came " +
"from the same backup as the imported key.\n\n" +
"Only continue if you:\n" +
" • are restoring to a fresh install, OR\n" +
" • have already imported the matching backup.\n\n" +
"You'll be asked for the passphrase you set when you " +
"exported the key.",
style = MaterialTheme.typography.bodyMedium,
)
},
confirmButton = {
TextButton(onClick = {
showRecoveryImportWarning = false
// Drain the URI here — the PassphraseDialog will
// route to importRecoveryKey on confirm.
pendingPassphraseMode = PassphraseDialogMode.RECOVERY_IMPORT
showPassphraseDialog = true
}) { Text("Continue") }
},
dismissButton = {
TextButton(onClick = {
showRecoveryImportWarning = false
pendingRecoveryImportUri = null
}) { Text("Cancel") }
},
)
}
if (showTimeoutDialog) {
TimeoutDialog(
current = settings.autoLockTimeout,
@@ -419,7 +595,7 @@ fun SettingsScreen(
is SettingsViewModel.MigrationState.Running -> {
AlertDialog(
onDismissRequest = {},
title = { Text("Re-encrypting notes…") },
title = { Text("Updating note encryption…") },
text = {
Column {
Text("This can take a few seconds. Don't close the app.")
@@ -528,11 +704,21 @@ private fun SecuritySection(
settings: org.incido.compose.data.settings.UserSettings,
onSecurityEnabled: (Boolean) -> Unit,
onEncryptionEnabled: (Boolean) -> Unit,
onBlockScreenshots: (Boolean) -> Unit,
onPinToggle: (Boolean) -> Unit,
onBiometricToggle: (Boolean) -> Unit,
onResetPin: () -> Unit,
onTimeoutClick: () -> Unit,
biometricAvailable: Boolean,
/**
* v0.3.6.0: recovery-key export/import rows. Both are no-ops when
* encryption isn't active; the parent shows a snackbar so the
* user knows why nothing happened. We don't disable the rows in
* the UI because users may have just turned encryption off and
* still want to import an old key first.
*/
onExportRecoveryKey: () -> Unit,
onImportRecoveryKey: () -> Unit,
) {
SettingsSection(title = "Security") {
Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) {
@@ -573,18 +759,17 @@ private fun SecuritySection(
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
SettingsToggle(
title = "Encrypt notes at rest",
// v0.3.3.1 hotfix: greyed out until Security is on
// AND a PIN or Biometric is configured. Matches the
// intent of `UserSettings.isEncryptionActive` (already
// gated on the securityEnabled flag) plus the lock
// requirement so the encryption key can't be set up
// against an "anyone-can-open" lock state.
// v0.3.5.0: real in-place encryption — note content and
// attachment bytes are AES-256-GCM encrypted with the
// Android-Keystore key the moment the toggle flips (no
// restart). Greyed out until Security is on AND a PIN or
// Biometric is configured (v0.3.3.1 gating kept).
subtitle = if (settings.securityEnabled && (settings.pinEnabled || settings.useBiometric)) {
"AES-256 encryption for the local database. " +
"Toggling requires an app restart."
"AES-256 encryption for your notes and attachments. " +
"Applied in place — takes effect immediately."
} else {
"AES-256 encryption for the local database. " +
"Toggling requires an app restart. " +
"AES-256 encryption for your notes and attachments. " +
"Applied in place — takes effect immediately. " +
"Enable Security and set a PIN or Biometric first."
},
checked = settings.encryptionEnabled,
@@ -593,6 +778,37 @@ private fun SecuritySection(
enabled = settings.securityEnabled && (settings.pinEnabled || settings.useBiometric),
onCheckedChange = onEncryptionEnabled,
)
// v0.3.6.0: recovery-key export / import. Both rows are
// always tappable — if encryption isn't active, the parent
// shows a snackbar telling the user to enable it first.
// We don't disable the rows because users may have just
// turned encryption off and still want to import an old
// key first.
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
SettingsRow(
title = "Export encryption key",
subtitle = "Save the AES key that protects your notes to " +
"a file. You'll set a passphrase. Store the file " +
"and passphrase in separate safe places.",
onClick = onExportRecoveryKey,
)
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
SettingsRow(
title = "Import encryption key",
subtitle = "Restore a previously-exported key. This " +
"replaces the current key — existing notes encrypted " +
"with the old key will become unreadable unless they " +
"came from the same backup.",
onClick = onImportRecoveryKey,
)
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
SettingsToggle(
title = "Block screenshots",
subtitle = "Prevent screenshots, screen recording, and " +
"app-switcher previews while Incido is open. On by default.",
checked = settings.blockScreenshots,
onCheckedChange = onBlockScreenshots,
)
if (settings.isLockActive) {
HorizontalDivider(modifier = Modifier.padding(vertical = 4.dp))
SettingsRow(
@@ -14,8 +14,12 @@ import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import org.incido.compose.IncidoApplication
import org.incido.compose.data.backup.BackupManager
import org.incido.compose.data.security.AesGcmFieldCipher
import org.incido.compose.data.security.EncryptionVerifier
import org.incido.compose.data.security.ObjectBoxKeyProvider
import org.incido.compose.data.security.SecurityManager
import org.incido.data.crypto.CipherHolder
import org.incido.data.crypto.NoteCryptoService
import org.incido.compose.data.settings.AutoLockTimeout
import org.incido.compose.data.settings.SettingsRepository
import org.incido.compose.data.settings.ThemeMode
@@ -42,6 +46,9 @@ class SettingsViewModel(
private val security: SecurityManager,
private val objectBoxKeyProvider: ObjectBoxKeyProvider,
private val backupManager: BackupManager,
private val noteCryptoService: NoteCryptoService,
private val cipherHolder: CipherHolder,
private val encryptionVerifier: EncryptionVerifier,
) : ViewModel() {
val userSettings: StateFlow<UserSettings> = settings.userSettingsFlow.stateIn(
@@ -82,46 +89,91 @@ class SettingsViewModel(
settings.setSecurityEnabled(true)
return@launch
}
// Disabling: clear every sub-flag + wipe the stored PIN
// hash/salt + drop the ObjectBox encryption key.
// Disabling: decrypt any encrypted rows first (so the notes
// remain readable once the key goes), then clear every sub-flag
// + wipe the stored PIN hash/salt + drop the encryption key.
// v0.3.5.0: real decrypt sweep instead of the old no-op.
_migrationState.value = MigrationState.Running(0f)
try {
if (cipherHolder.cipher != null) {
noteCryptoService.decryptAllInPlace { done, total ->
_migrationState.value = MigrationState.Running(
if (total == 0) 1f else done.toFloat() / total,
)
}
cipherHolder.cipher = null
}
settings.setSecurityEnabled(false)
settings.setPinEnabled(false)
settings.setEncryptionEnabled(false)
settings.setUseBiometric(false)
security.clearPin()
objectBoxKeyProvider.deleteKey()
_migrationState.value = MigrationState.Idle
encryptionVerifier.checkNow()
_snackbar.value = "Security disabled."
} catch (t: Throwable) {
_migrationState.value = MigrationState.Failed(t.message ?: "Decryption failed")
}
}
/**
* v0.3.5.0 — the toggle now performs a REAL in-place migration and
* takes effect immediately (no app restart):
*
* - ENABLE: generate/unwrap the Keystore key, install the cipher
* into the shared [CipherHolder] (so every concurrent write is
* already encrypted), then sweep every plaintext note +
* attachment row into ciphertext with live progress.
* - DISABLE: decrypt every row back to plaintext first, then
* remove the cipher from the holder and delete the key.
*
* Either way the startup verifier re-checks afterwards, so the
* "Encrypted" badge on the cards always reflects rows that are
* provably decryptable.
*/
fun setEncryptionEnabled(enabled: Boolean) = viewModelScope.launch {
if (!_migrationState.value.canStart) return@launch
// v0.3.2.0 MVP: toggling encryption requires the app to be
// restarted so the BoxStore can be re-opened with the right
// key. We flip the flag and surface a migration notice — the
// full BoxStore re-open is handled by AppContainer on next
// process start.
_migrationState.value = MigrationState.Running(0f)
try {
if (enabled) {
// Generate the key now so it's ready for the next launch.
// Key first (idempotent), cipher into the holder, sweep.
objectBoxKeyProvider.getOrCreateKey()
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
noteCryptoService.encryptAllInPlace { done, total ->
_migrationState.value = MigrationState.Running(
if (total == 0) 1f else done.toFloat() / total,
)
}
settings.setEncryptionEnabled(true)
_migrationState.value = MigrationState.Done(
message = "Notes are now encrypted on this device.",
)
} else {
noteCryptoService.decryptAllInPlace { done, total ->
_migrationState.value = MigrationState.Running(
if (total == 0) 1f else done.toFloat() / total,
)
}
cipherHolder.cipher = null
objectBoxKeyProvider.deleteKey()
settings.setEncryptionEnabled(false)
}
_migrationState.value = MigrationState.Done(
message = if (enabled) {
"Encryption will be enabled on next app launch."
} else {
"Encryption will be disabled on next app launch."
},
message = "Notes are now stored unencrypted.",
)
}
// Re-verify so the badge set matches the new on-disk state.
encryptionVerifier.checkNow()
} catch (t: Throwable) {
_migrationState.value = MigrationState.Failed(t.message ?: "Migration failed")
}
}
/** v0.3.5.0 — FLAG_SECURE screenshot / recording blocking. */
fun setBlockScreenshots(enabled: Boolean) = viewModelScope.launch {
settings.setBlockScreenshots(enabled)
}
/**
* v0.3.3.0: switch the lock mode. Mutually exclusive — enabling
* one wipes the other. Switching to [LockMode.NONE] disables both
@@ -193,6 +245,70 @@ class SettingsViewModel(
_snackbar.value = "Imported $count note(s)."
}
// --- v0.3.6.0 recovery key ---
/**
* Write the at-rest encryption key to a user-chosen SAF uri,
* wrapped with [passphrase]. Caller is responsible for calling
* `securityManager.beginExternalActivity()` before launching the
* picker so the SAF round-trip doesn't trigger an auto-lock.
*
* @param uri The destination content uri.
* @param passphrase The passphrase the user entered in the
* export flow (zeroed by this method on completion).
* @return `true` on success, `false` if there is no encryption
* key to export (the caller should disable the export
* row until encryption is active — see SettingsScreen).
*/
suspend fun exportRecoveryKey(uri: android.net.Uri, passphrase: CharArray): Boolean {
if (!objectBoxKeyProvider.hasKey()) {
_snackbar.value = "Encryption isn't active — nothing to back up."
return false
}
try {
objectBoxKeyProvider.exportRecoveryKey(uri, passphrase)
_snackbar.value =
"Recovery key exported. Store the file and passphrase in separate safe places."
return true
} catch (e: org.incido.compose.data.security.ObjectBoxKeyProvider.RecoveryKeyException) {
_snackbar.value = "Couldn't write recovery key: ${e.message}"
return false
}
}
/**
* Read a recovery envelope from [uri] with [passphrase] and
* install it as the current field key. After install we swap in a
* fresh [AesGcmFieldCipher] that wraps the new key, and re-run
* the encryption verifier so the "Encrypted" badge reflects the
* new state.
*
* If the user already had encrypted rows the new key makes those
* rows unreadable (GCM tag fail → row enters [failedNoteIds] in
* the verifier). That's expected — a recovery key only matches
* when the user is moving to a fresh install (or intentionally
* rotating). The UI surfaces a warning dialog before this call.
*/
suspend fun importRecoveryKey(uri: android.net.Uri, passphrase: CharArray): Boolean {
try {
val overwroteExisting = objectBoxKeyProvider.importRecoveryKey(uri, passphrase)
// Swap the live cipher to point at the freshly-installed key.
// We build a new wrapper that re-reads the (just-persisted)
// wrapped blob — no need to re-implement the unwrap here.
cipherHolder.cipher = AesGcmFieldCipher(objectBoxKeyProvider)
encryptionVerifier.checkNow()
_snackbar.value = if (overwroteExisting) {
"Recovery key installed. Previously-encrypted notes will appear as unverified."
} else {
"Recovery key installed."
}
return true
} catch (e: org.incido.compose.data.security.ObjectBoxKeyProvider.RecoveryKeyException) {
_snackbar.value = e.message ?: "Couldn't import recovery key."
return false
}
}
// --- Migration dialog ---
fun acknowledgeMigration() {
@@ -217,7 +333,7 @@ class SettingsViewModel(
/** The version string baked into backup payloads and shown on
* the About card. Mirrors `app/build.gradle.kts` `versionName`
* — if you bump one, bump both. */
const val APP_VERSION = "0.3.3.4"
const val APP_VERSION = "0.3.6.0"
val Factory: ViewModelProvider.Factory = viewModelFactory {
initializer {
@@ -228,6 +344,9 @@ class SettingsViewModel(
security = c.securityManager,
objectBoxKeyProvider = c.objectBoxKeyProvider,
backupManager = c.backupManager,
noteCryptoService = c.noteCryptoService,
cipherHolder = c.cipherHolder,
encryptionVerifier = c.encryptionVerifier,
)
}
}
@@ -68,6 +68,17 @@ import org.incido.compose.data.settings.UserSettings
* producing white-on-white text in dark mode. Biometric unlock now
* uses the callback-based [SecurityManager.authenticateWithBiometric]
* (the old synchronous busy-wait deadlocked the main thread).
*
* v0.3.3.7 (hotfix): in **biometric-only** mode the biometric prompt is
* launched automatically the moment the lock screen appears — previously
* the user had to tap the "Authenticate" button first, adding an extra
* tap of friction to every unlock (cold launch + every auto-lock). The
* auto-launch fires at most once per lock-screen appearance; if the user
* cancels (or the prompt errors), the lock screen stays and the
* "Authenticate" button remains as the manual-retry path. PIN mode is
* untouched — [UserSettings.isBiometricLockActive] is false there, so
* the auto-launch effect never runs and the PIN field keeps its
* auto-focus behaviour.
*/
@OptIn(ExperimentalMaterial3Api::class)
@Composable
@@ -91,6 +102,35 @@ fun PinEntryScreen() {
val focusRequester = remember { FocusRequester() }
val scope = rememberCoroutineScope()
// v0.3.3.7: guard flag — the biometric prompt must auto-launch at
// most once per lock-screen appearance so a cancelled prompt can't
// re-trigger in a loop.
var autoLaunched by remember { mutableStateOf(false) }
// v0.3.3.7: in biometric-only mode, open the BiometricPrompt as
// soon as the lock screen composes instead of waiting for the user
// to tap "Authenticate". Keyed on [biometricOnly] so the effect
// re-runs when the real (non-default) settings arrive — the initial
// composition sees the default UserSettings() (biometricOnly=false)
// and is intentionally skipped.
LaunchedEffect(biometricOnly) {
if (!biometricOnly) return@LaunchedEffect
if (autoLaunched) return@LaunchedEffect
if (!securityManager.isBiometricAvailable()) return@LaunchedEffect
val activity = context as? FragmentActivity ?: return@LaunchedEffect
autoLaunched = true
busy = true
error = null
securityManager.authenticateWithBiometric(activity) { ok ->
busy = false
if (ok) {
securityManager.onUnlocked()
} else {
error = "Authentication failed. Tap Authenticate to try again."
}
}
}
LaunchedEffect(Unit) {
// Only request focus on the PIN field when we're showing one.
if (!biometricOnly) focusRequester.requestFocus()
@@ -205,7 +245,14 @@ fun PinEntryScreen() {
if (ok) {
securityManager.onUnlocked()
} else {
error = "Authentication failed. Try again or use your PIN."
// v0.3.3.7: biometric-only mode has no
// Incido PIN to fall back to, so don't
// mention one.
error = if (biometricOnly) {
"Authentication failed. Tap Authenticate to try again."
} else {
"Authentication failed. Try again or use your PIN."
}
}
}
} else {
@@ -8,13 +8,15 @@ import org.incido.data.entity.MyObjectBox
* Singleton holder for the process-wide [BoxStore]. Initialised once from
* the Application/Activity context.
*
* v0.3.2.0 — kept an `encryptionKey` parameter for forward compatibility,
* but the open-source ObjectBox 4.0.3 distribution doesn't expose a
* public `encryptionKey(byte[])` method on [io.objectbox.BoxStoreBuilder].
* At-rest encryption is only available in ObjectBox Sync / Pro; the
* `:composeApp` `ObjectBoxKeyProvider` keeps the wrapping logic
* ready for when the API becomes available (or for migration to the
* commercial build). For now the store always opens unencrypted.
* v0.3.5.0 — the open-source ObjectBox 4.0.3 distribution does not
* expose a public `encryptionKey(byte[])` builder method (that is
* ObjectBox Sync / Pro only), so the store file itself is opened
* unencrypted. At-rest protection is instead done one layer up:
* note content and attachment blobs are field-encrypted with
* AES-256-GCM by `NoteRepositoryImpl` / `NoteCryptoService` using the
* Keystore-wrapped key managed by `ObjectBoxKeyProvider`. The
* `encryptionKey` parameter is kept for forward compatibility with a
* commercial ObjectBox build but remains a no-op here.
*/
object ObjectBoxStore {
@Volatile
@@ -25,10 +27,9 @@ object ObjectBoxStore {
* return the existing instance.
*
* @param context application context
* @param encryptionKey reserved for future at-rest encryption support
* (currently a no-op — ObjectBox 4.0.3 OSS doesn't expose the
* API). The key is wrapped via Android Keystore by
* `ObjectBoxKeyProvider` and ready to plug in.
* @param encryptionKey reserved for future ObjectBox-native at-rest
* encryption (OSS 4.0.3 doesn't expose the API — currently a
* no-op; see class KDoc for the field-encryption approach).
*/
@Suppress("UNUSED_PARAMETER")
fun init(context: Context, encryptionKey: ByteArray? = null): BoxStore =
@@ -0,0 +1,47 @@
package org.incido.data.crypto
/**
* v0.3.5.0: abstraction for the field-level encryption used by the
* repository to protect note content and attachment bytes at rest.
*
* The [core:data] module stays free of Android Keystore dependencies —
* the concrete implementation lives in `:composeApp`
* (`AesGcmFieldCipher`), backed by the Keystore-wrapped key managed by
* `ObjectBoxKeyProvider`, and is injected via the repository
* constructor.
*
* Blob layout produced by all `encrypt*` methods:
*
* ```
* nonce (12 bytes) | ciphertext | GCM tag (16 bytes, appended by JCE)
* ```
*
* All `decrypt*` methods throw [javax.crypto.AEADBadTagException]
* (wrapped in [IllegalArgumentException] on some providers) when the
* payload is corrupted or was encrypted with a different key — callers
* use this as a **verification** signal (see the startup "Encrypted"
* badge re-check).
*/
interface FieldCipher {
/** Encrypt [plaintext] (UTF-8) into a self-describing blob. */
fun encryptString(plaintext: String): ByteArray
/**
* Reverse of [encryptString]. Throws if the blob is truncated,
* corrupted, or not encrypted with the current key.
*/
fun decryptString(blob: ByteArray): String
/** Encrypt raw [plaintext] bytes into a self-describing blob. */
fun encryptBytes(plaintext: ByteArray): ByteArray
/** Reverse of [encryptBytes]. Throws on integrity failure. */
fun decryptBytes(blob: ByteArray): ByteArray
}
/** Value stored in `cipherVersion` columns for plaintext rows. */
const val CIPHER_VERSION_PLAIN: Int = 0
/** Value stored in `cipherVersion` columns for AES-256-GCM encrypted rows. */
const val CIPHER_VERSION_AES_GCM: Int = 1
@@ -0,0 +1,184 @@
package org.incido.data.crypto
import io.objectbox.BoxStore
import io.objectbox.kotlin.boxFor
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.incido.data.entity.NoteAttachmentEntity
import org.incido.data.entity.NoteEntity
/**
* v0.3.5.0: process-wide holder for the currently-active [FieldCipher].
*
* The repository consults [cipher] on every read/write, which lets the
* settings flow flip encryption on or off **live** (no app restart):
*
* - enable → set the cipher, then run [NoteCryptoService.encryptAllInPlace]
* - disable → run [NoteCryptoService.decryptAllInPlace], then clear the cipher
*
* Rows stay self-describing via their `cipherVersion` column, so a mix
* of plaintext and encrypted rows is always readable.
*/
class CipherHolder {
@Volatile
var cipher: FieldCipher? = null
}
/**
* Result of the startup integrity check over every encrypted note row.
*
* [verifiedNoteIds] — rows whose ciphertext decrypts cleanly under the
* current key (the GCM auth tag is the proof of integrity). This is the
* ONLY source of truth for the "Encrypted" badge on the note cards —
* the badge is never shown based on the settings flag alone.
*
* [failedNoteIds] — rows marked encrypted whose ciphertext fails to
* decrypt (corruption or wrong key). Surfaced to the user as a warning.
*/
data class EncryptionVerification(
val verifiedNoteIds: Set<Long>,
val failedNoteIds: Set<Long>,
/** [System.currentTimeMillis] when the check ran. */
val checkedAt: Long,
) {
val allOk: Boolean get() = failedNoteIds.isEmpty()
}
/**
* v0.3.5.0: the service that makes "Encrypt in place" real. Operates
* directly on the ObjectBox store (bypassing the repository's
* domain-mapping layer) to sweep every note + attachment row and flip
* its `cipherVersion` in place, reporting progress for the migration
* dialog.
*
* It is also the startup **verifier**: [verifyAll] re-checks every
* encrypted note row by performing a full GCM decrypt — this runs on
* every app open so the "Encrypted" badge only ever reflects rows that
* are demonstrably decryptable right now.
*/
class NoteCryptoService(
private val boxStore: BoxStore,
private val cipherHolder: CipherHolder,
) {
private val noteBox = boxStore.boxFor<NoteEntity>()
private val attachmentBox = boxStore.boxFor<NoteAttachmentEntity>()
/**
* Encrypt every plaintext row in place (notes + attachments).
* Rows already at `cipherVersion = 1` are skipped, which makes the
* sweep idempotent and safe to re-run (e.g. resuming an interrupted
* migration). [onProgress] receives `(completed, total)` — called
* from a background thread; thread-safe sinks only (MutableStateFlow).
*/
suspend fun encryptAllInPlace(onProgress: (completed: Int, total: Int) -> Unit = { _, _ -> }) =
withContext(Dispatchers.IO) {
val cipher = cipherHolder.cipher
?: throw IllegalStateException("No cipher configured — cannot encrypt")
val notes = noteBox.all
val attachments = attachmentBox.all
val total = notes.count { it.cipherVersion == CIPHER_VERSION_PLAIN } +
attachments.count { it.cipherVersion == CIPHER_VERSION_PLAIN }
var done = 0
onProgress(done, total)
for (entity in notes) {
if (entity.cipherVersion != CIPHER_VERSION_PLAIN) continue
entity.contentBlob = cipher.encryptString(entity.content)
entity.content = ""
entity.cipherVersion = CIPHER_VERSION_AES_GCM
noteBox.put(entity)
done++
onProgress(done, total)
}
for (entity in attachments) {
if (entity.cipherVersion != CIPHER_VERSION_PLAIN) continue
entity.bytesBlob = cipher.encryptBytes(entity.bytes)
entity.bytes = ByteArray(0)
entity.cipherVersion = CIPHER_VERSION_AES_GCM
attachmentBox.put(entity)
done++
onProgress(done, total)
}
}
/**
* Reverse of [encryptAllInPlace] — decrypt every encrypted row back
* to plaintext. Idempotent; plaintext rows are skipped. Call this
* BEFORE clearing [CipherHolder.cipher] so any concurrent write
* still has a key while the sweep runs.
*/
suspend fun decryptAllInPlace(onProgress: (completed: Int, total: Int) -> Unit = { _, _ -> }) =
withContext(Dispatchers.IO) {
val cipher = cipherHolder.cipher
?: throw IllegalStateException("No cipher configured — cannot decrypt")
val notes = noteBox.all
val attachments = attachmentBox.all
val total = notes.count { it.cipherVersion == CIPHER_VERSION_AES_GCM } +
attachments.count { it.cipherVersion == CIPHER_VERSION_AES_GCM }
var done = 0
onProgress(done, total)
for (entity in notes) {
if (entity.cipherVersion != CIPHER_VERSION_AES_GCM) continue
entity.content = cipher.decryptString(entity.contentBlob)
entity.contentBlob = ByteArray(0)
entity.cipherVersion = CIPHER_VERSION_PLAIN
noteBox.put(entity)
done++
onProgress(done, total)
}
for (entity in attachments) {
if (entity.cipherVersion != CIPHER_VERSION_AES_GCM) continue
entity.bytes = cipher.decryptBytes(entity.bytesBlob)
entity.bytesBlob = ByteArray(0)
entity.cipherVersion = CIPHER_VERSION_PLAIN
attachmentBox.put(entity)
done++
onProgress(done, total)
}
}
/** True when any row is still marked encrypted. */
fun hasEncryptedRows(): Boolean =
noteBox.all.any { it.cipherVersion == CIPHER_VERSION_AES_GCM } ||
attachmentBox.all.any { it.cipherVersion == CIPHER_VERSION_AES_GCM }
/**
* Startup integrity check. Runs a **full trial decrypt** over every
* note row marked `cipherVersion = 1` — the GCM auth tag failing is
* our proof the row is corrupt / wrong-key, and such a row is
* reported in [EncryptionVerification.failedNoteIds] instead of
* earning the badge.
*
* Blocking — call from a background dispatcher (never the main
* thread). When no cipher is configured, any encrypted row is
* counted as failed (it is unreadable until the key is restored).
*/
fun verifyAll(): EncryptionVerification = run {
val cipher = cipherHolder.cipher
val verified = HashSet<Long>()
val failed = HashSet<Long>()
for (entity in noteBox.all) {
if (entity.cipherVersion != CIPHER_VERSION_AES_GCM) continue
val ok = cipher != null && runCatching {
if (entity.contentBlob.isEmpty()) {
false
} else {
cipher.decryptString(entity.contentBlob)
true
}
}.getOrDefault(false)
if (ok) verified.add(entity.id) else failed.add(entity.id)
}
EncryptionVerification(
verifiedNoteIds = verified,
failedNoteIds = failed,
checkedAt = System.currentTimeMillis(),
)
}
}
@@ -16,6 +16,12 @@ import org.incido.domain.model.NoteAttachment
* domain layer — list snapshots stay cheap because they don't load
* the (potentially large) blob. Callers fetch bytes on demand via
* [org.incido.domain.repository.NoteRepository.getAttachmentBytes].
*
* v0.3.5.0 — at-rest field encryption. [cipherVersion] records the
* state of the row: `0` = plaintext ([bytes] holds the raw file),
* `1` = AES-256-GCM encrypted ([bytesBlob] holds `nonce | ciphertext
* + tag` and [bytes] is kept empty). Both columns are additive so
* existing stores auto-migrate.
*/
@Entity
data class NoteAttachmentEntity(
@@ -26,7 +32,39 @@ data class NoteAttachmentEntity(
var createdAt: Long = 0,
var sizeBytes: Long = 0,
var bytes: ByteArray = ByteArray(0),
)
/** 0 = plaintext, 1 = AES-256-GCM encrypted into [bytesBlob]. */
var cipherVersion: Int = 0,
/** Encrypted payload: `nonce (12) | ciphertext + GCM tag`. Empty when plaintext. */
var bytesBlob: ByteArray = ByteArray(0),
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is NoteAttachmentEntity) return false
if (id != other.id) return false
if (noteId != other.noteId) return false
if (mimeType != other.mimeType) return false
if (displayName != other.displayName) return false
if (createdAt != other.createdAt) return false
if (sizeBytes != other.sizeBytes) return false
if (!bytes.contentEquals(other.bytes)) return false
if (cipherVersion != other.cipherVersion) return false
if (!bytesBlob.contentEquals(other.bytesBlob)) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + noteId.hashCode()
result = 31 * result + mimeType.hashCode()
result = 31 * result + displayName.hashCode()
result = 31 * result + createdAt.hashCode()
result = 31 * result + sizeBytes.hashCode()
result = 31 * result + bytes.contentHashCode()
result = 31 * result + cipherVersion.hashCode()
result = 31 * result + bytesBlob.contentHashCode()
return result
}
}
internal fun NoteAttachmentEntity.toDomain(): NoteAttachment = NoteAttachment(
id = id,
@@ -12,6 +12,14 @@ import org.incido.domain.model.NoteColor
*
* v0.2 adds [isFavorite] and [color]. Both are additive (the prior v0.1
* schema had neither) so existing user notes auto-migrate on first launch.
*
* v0.3.5.0 — at-rest field encryption. [cipherVersion] records the
* state of the row: `0` = plaintext ([content] holds the note text),
* `1` = AES-256-GCM encrypted ([contentBlob] holds `nonce | ciphertext
* + tag` and [content] is kept empty). The two columns are additive so
* existing stores auto-migrate. The repository transparently
* encrypts/decrypts on write/read when a [org.incido.data.crypto.FieldCipher]
* is supplied.
*/
@Entity
data class NoteEntity(
@@ -21,7 +29,37 @@ data class NoteEntity(
var updatedAt: Long = 0,
@Index var isFavorite: Boolean = false,
var colorKey: Short = 0,
)
/** 0 = plaintext, 1 = AES-256-GCM encrypted into [contentBlob]. */
var cipherVersion: Int = 0,
/** Encrypted payload: `nonce (12) | ciphertext + GCM tag`. Empty when plaintext. */
var contentBlob: ByteArray = ByteArray(0),
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is NoteEntity) return false
if (id != other.id) return false
if (content != other.content) return false
if (createdAt != other.createdAt) return false
if (updatedAt != other.updatedAt) return false
if (isFavorite != other.isFavorite) return false
if (colorKey != other.colorKey) return false
if (cipherVersion != other.cipherVersion) return false
if (!contentBlob.contentEquals(other.contentBlob)) return false
return true
}
override fun hashCode(): Int {
var result = id.hashCode()
result = 31 * result + content.hashCode()
result = 31 * result + createdAt.hashCode()
result = 31 * result + updatedAt.hashCode()
result = 31 * result + isFavorite.hashCode()
result = 31 * result + colorKey.hashCode()
result = 31 * result + cipherVersion.hashCode()
result = 31 * result + contentBlob.contentHashCode()
return result
}
}
internal fun NoteEntity.toDomain(): Note = Note(
id = id,
@@ -17,6 +17,9 @@ import kotlinx.coroutines.flow.callbackFlow
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.incido.data.crypto.CIPHER_VERSION_AES_GCM
import org.incido.data.crypto.CIPHER_VERSION_PLAIN
import org.incido.data.crypto.CipherHolder
import org.incido.data.entity.HashtagEntity
import org.incido.data.entity.HashtagEntity_
import org.incido.data.entity.NoteAttachmentEntity
@@ -45,11 +48,24 @@ import org.incido.domain.repository.NoteRepository
* Note: ObjectBox 4.0.3's Kotlin stubs are finicky around
* `QueryBuilder.equal(Property, String, ...)` — passing the
* `StringOrder` argument explicitly is the most reliable way to call it.
*
* v0.3.5.0 — at-rest field encryption. The repository consults
* [cipherHolder] on every read/write: when a cipher is active (settings
* "Encrypt notes at rest" is on), note content and attachment bytes are
* stored AES-256-GCM encrypted (`cipherVersion = 1`) and transparently
* decrypted on every read. Rows are self-describing via `cipherVersion`,
* so a store can hold a mix of plaintext and encrypted rows during
* (or after an interrupted) migration, and toggling encryption does not
* require an app restart. With no cipher set the repository behaves
* exactly like v0.3.4.0.
*/
class NoteRepositoryImpl(
private val boxStore: BoxStore,
private val cipherHolder: CipherHolder = CipherHolder(),
) : NoteRepository {
private val fieldCipher get() = cipherHolder.cipher
private val noteBox = boxStore.boxFor<NoteEntity>()
private val tagBox = boxStore.boxFor<HashtagEntity>()
private val xrefBox = boxStore.boxFor<NoteHashtagCrossRef>()
@@ -158,7 +174,8 @@ class NoteRepositoryImpl(
}.flowOn(Dispatchers.Default)
override suspend fun getAttachmentBytes(id: Long): ByteArray? {
return attachmentBox.get(id)?.bytes
val entity = attachmentBox.get(id) ?: return null
return decryptAttachmentBytes(entity)
}
override suspend fun addAttachment(
@@ -185,7 +202,102 @@ class NoteRepositoryImpl(
sizeBytes = storedBytes.size.toLong(),
bytes = storedBytes,
)
return attachmentBox.put(entity)
return attachmentBox.put(applyAttachmentEncryption(entity))
}
/**
* v0.3.5.0 — encrypt the attachment blob before it hits disk when
* a [fieldCipher] is active. Plaintext rows pass through unchanged
* (and any stale blob/version from a previous state is cleared).
*/
private fun applyAttachmentEncryption(entity: NoteAttachmentEntity): NoteAttachmentEntity {
val cipher = fieldCipher
return if (cipher == null) {
entity.apply {
cipherVersion = CIPHER_VERSION_PLAIN
bytesBlob = ByteArray(0)
}
} else {
entity.apply {
bytesBlob = cipher.encryptBytes(bytes)
bytes = ByteArray(0)
cipherVersion = CIPHER_VERSION_AES_GCM
}
}
}
/**
* v0.3.5.0 — reverse of [applyAttachmentEncryption]. Rows are
* self-describing via `cipherVersion`, so a row written while
* encryption was off still reads correctly after it is turned on
* (and vice-versa) until the migration sweep re-keys it.
*/
private fun decryptAttachmentBytes(entity: NoteAttachmentEntity): ByteArray {
return when {
entity.cipherVersion == CIPHER_VERSION_AES_GCM -> {
val cipher = fieldCipher
?: error("Encrypted attachment row ${entity.id} but no cipher configured")
cipher.decryptBytes(entity.bytesBlob)
}
else -> entity.bytes
}
}
/**
* v0.3.5.0 — return a plaintext *view* of [entity] for domain
* mapping. Encrypted rows (`cipherVersion = 1`) are decrypted on
* the fly; plaintext rows pass through unchanged. The returned
* entity must never be `put` back into the box — it is read-only.
*/
private fun toReadable(entity: NoteEntity): NoteEntity {
if (entity.cipherVersion != CIPHER_VERSION_AES_GCM) return entity
val cipher = fieldCipher
if (cipher == null || entity.contentBlob.isEmpty()) {
// Encrypted row but no key configured (e.g. encryption was
// disabled and the reverse migration didn't finish). The
// content is unreadable — surface it empty rather than
// crash the whole list; the startup verifier reports it.
return entity
}
return entity.copy(content = cipher.decryptString(entity.contentBlob))
}
/**
* v0.3.5.0 — prepare an entity for storage. When a cipher is
* active the content is encrypted into [NoteEntity.contentBlob]
* and the plaintext column is cleared; otherwise any stale
* ciphertext is wiped so the row is genuinely plaintext.
*/
private fun toWritable(entity: NoteEntity): NoteEntity {
val cipher = fieldCipher ?: return entity.apply {
cipherVersion = CIPHER_VERSION_PLAIN
contentBlob = ByteArray(0)
}
return entity.apply {
contentBlob = cipher.encryptString(content)
content = ""
cipherVersion = CIPHER_VERSION_AES_GCM
}
}
/**
* v0.3.5.0 — cipher-aware content matcher. ObjectBox's `contains()`
* query cannot see ciphertext, so when encryption is active we
* decrypt and filter in-memory (fine at notes-app scale). Hashtag
* matching is unaffected — tag names stay plaintext.
*/
private fun contentMatchingNoteIds(query: String): List<Long> {
if (fieldCipher == null) {
return noteBox.query()
.contains(NoteEntity_.content, query, QueryBuilder.StringOrder.CASE_INSENSITIVE)
.build()
.find()
.map { it.id }
}
val needle = query.lowercase()
return noteBox.all
.filter { toReadable(it).content.lowercase().contains(needle) }
.map { it.id }
}
/**
@@ -236,8 +348,9 @@ class NoteRepositoryImpl(
} else {
note.copy(updatedAt = now).toEntity()
}
val assignedId = noteBox.put(toPersist)
return noteBox.get(assignedId)?.toDomain() ?: note.copy(id = assignedId)
val assignedId = noteBox.put(toWritable(toPersist))
return noteBox.get(assignedId)?.let { toReadable(it).toDomain() }
?: note.copy(id = assignedId)
}
override suspend fun delete(id: Long) {
@@ -289,8 +402,8 @@ class NoteRepositoryImpl(
// tagBox observer could fire between the tagBox.put and the
// xrefBox.put, leaving the snapshot stuck on emptyList().
return boxStore.callInTx(Callable {
val assignedId = noteBox.put(toPersist)
val saved = noteBox.get(assignedId)?.toDomain()
val assignedId = noteBox.put(toWritable(toPersist))
val saved = noteBox.get(assignedId)?.let { toReadable(it).toDomain() }
?: note.copy(id = assignedId)
hashtagsToRemove.forEach { removeHashtagInternal(saved.id, it) }
hashtagsToAdd.forEach { addHashtagInternal(saved.id, it) }
@@ -394,7 +507,7 @@ class NoteRepositoryImpl(
compareByDescending<NoteEntity> { it.isFavorite }
.thenByDescending { it.updatedAt }
).map { e ->
val base = e.toDomain()
val base = toReadable(e).toDomain()
base.copy(
hashtags = tags[e.id].orEmpty(),
attachments = attachments[e.id].orEmpty(),
@@ -409,11 +522,9 @@ class NoteRepositoryImpl(
if (q.isEmpty()) return snapshotAll()
// Match against content (contains, case-insensitive).
val contentMatches: List<Long> = noteBox.query()
.contains(NoteEntity_.content, q, QueryBuilder.StringOrder.CASE_INSENSITIVE)
.build()
.find()
.map { it.id }
// v0.3.5.0: cipher-aware — ObjectBox `contains()` can't see
// ciphertext, so encrypted stores match in-memory.
val contentMatches: List<Long> = contentMatchingNoteIds(q)
// Match against hashtag names (case-insensitive exact equality).
val matchingTag: HashtagEntity? = tagBox.query()
@@ -474,11 +585,7 @@ class NoteRepositoryImpl(
val q = query.trim()
if (q.isEmpty()) return snapshotUntagged()
val noteIdsWithTags: Set<Long> = xrefBox.all.mapTo(HashSet(xrefBox.all.size)) { it.noteId }
val contentMatches: List<Long> = noteBox.query()
.contains(NoteEntity_.content, q, QueryBuilder.StringOrder.CASE_INSENSITIVE)
.build()
.find()
.map { it.id }
val contentMatches: List<Long> = contentMatchingNoteIds(q)
val matching: List<NoteEntity> = contentMatches
.mapNotNull { id -> noteBox.get(id) }
.filter { it.id !in noteIdsWithTags }
@@ -491,11 +598,7 @@ class NoteRepositoryImpl(
*/
private fun snapshotSearchMatchingNoteIds(query: String): Set<Long> {
// Match against content (contains, case-insensitive).
val contentMatches: List<Long> = noteBox.query()
.contains(NoteEntity_.content, query, QueryBuilder.StringOrder.CASE_INSENSITIVE)
.build()
.find()
.map { it.id }
val contentMatches: List<Long> = contentMatchingNoteIds(query)
// Match against hashtag names (case-insensitive exact equality).
val matchingTag: HashtagEntity? = tagBox.query()
@@ -533,7 +636,7 @@ class NoteRepositoryImpl(
val entity = noteBox.get(id) ?: return null
val tags = hashtagsByNoteId()[id].orEmpty()
val attachments = attachmentsByNoteId()[id].orEmpty()
return entity.toDomain().copy(
return toReadable(entity).toDomain().copy(
hashtags = tags,
attachments = attachments,
)