Compare commits

...

87 Commits

Author SHA1 Message Date
Andre Rosado
9c5d53c9dc Merge branch 'PM-37255/fill-assist-data-layer' into PM-37255/fill-assist-integration 2026-06-10 11:02:43 +01:00
Andre Rosado
ad2aada6b1 updating environmentDiskSource.fillAssistUrl when serverConfigStateFlow updates
Updating code to schema with required values
2026-06-10 10:50:33 +01:00
Andre Rosado
bbdc2f10da Merge branch 'PM-37255/fill-assist-network-layer' into PM-37255/fill-assist-data-layer 2026-06-09 14:46:07 +01:00
Andre Rosado
31a9cf7c34 Added FillAssist to BaseUrlInterceptors 2026-06-09 13:59:15 +01:00
Andre Rosado
b25404e112 removed unnecessary null set 2026-06-09 13:16:20 +01:00
Andre Rosado
0b39ad2731 following autofill assist forms schema 2026-06-08 17:39:47 +01:00
Andre Rosado
f66485facd Removed nulls and sets on non nullable fields by schema definition. Removed unnecessary deserialization tests 2026-06-08 17:20:27 +01:00
Andre Rosado
b718f56bed Merge branch 'PM-37255/fill-assist-data-layer' into PM-37255/fill-assist-integration 2026-05-29 14:08:40 +01:00
Andre Rosado
61db0cd4c4 Merge branch 'PM-37255/fill-assist-network-layer' into PM-37255/fill-assist-data-layer 2026-05-29 14:07:33 +01:00
Andre Rosado
00b2479808 chained code on FillAssistManager 2026-05-29 13:56:30 +01:00
Andre Rosado
09692afff6 wire fill-assist manager into vault sync and app startup 2026-05-29 13:52:18 +01:00
Andre Rosado
8b6ce8bce9 Add fill assist data layer 2026-05-29 13:40:03 +01:00
Andre Rosado
f57a7d09a2 reverted unwanted changes on AuthRepositoryTest 2026-05-29 13:24:13 +01:00
Andre Rosado
c6463722f2 Add fill assist rules network data 2026-05-29 12:03:19 +01:00
Patrick Honkonen
e7e2c26bef [PM-36970] fix: Correct Update Payment status description (#6988) 2026-05-28 21:37:06 +00:00
Patrick Honkonen
c89a52e5d2 [PM-38279] fix: Hide Cancel Premium action for Update payment status (#6989) 2026-05-28 21:14:09 +00:00
David Perez
fb955e903f Deps: Update the protobuf library to v4.35.0 (#6985) 2026-05-28 20:44:14 +00:00
Patrick Honkonen
230c8f769d [PM-37181] feat: Surface Expired subscription substate (#6982) 2026-05-28 20:37:50 +00:00
David Perez
8661dfaf2f PM-38285: Feat: Filter unconfirmed organizations from the app (#6987) 2026-05-28 19:48:07 +00:00
David Perez
a872db128b Chore: Remove the Manager type from OrganizationType (#6984) 2026-05-28 19:47:41 +00:00
Patrick Honkonen
40604d0ec0 [PM-37804] fix: Drop redundant Stripe checkout confirmation on Upgrade Now (#6980) 2026-05-28 19:08:00 +00:00
bw-ghapp[bot]
0f4b3fb9f0 Update SDK to 3.0.0-7126-025e5d85 (#6976)
Co-authored-by: bw-ghapp[bot] <178206702+bw-ghapp[bot]@users.noreply.github.com>
2026-05-28 10:38:48 +00:00
David Perez
a0edef99e6 PM-38140 Feat: SDK policy filters (#6979) 2026-05-27 20:59:53 +00:00
Patrick Honkonen
cc6fcecc5b [PM-37232] fix: Hide upgrade CTAs while a Premium upgrade is pending (#6978) 2026-05-27 20:53:06 +00:00
David Perez
58408bcd77 PM-38130: Feat: Parse new organizations and policies properties from sync response (#6977) 2026-05-27 09:52:12 +00:00
David Perez
3732672ab4 PM-37985: Feat: Use PolicyView in the app (#6966) 2026-05-26 16:34:10 +00:00
renovate[bot]
b53d3fbd29 [deps]: Update com.google.devtools.ksp to v2.3.8 (#6971)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
2026-05-26 15:08:30 +00:00
bw-ghapp[bot]
f0f1f91c62 Update SDK to 3.0.0-7068-a635e32d (#6967)
Co-authored-by: bw-ghapp[bot] <178206702+bw-ghapp[bot]@users.noreply.github.com>
2026-05-26 14:48:57 +00:00
Patrick Honkonen
ecc47005fb [PM-37282] feat: Add Upgrade to Premium CTA to File Send dialog (#6968) 2026-05-26 14:40:15 +00:00
bw-ghapp[bot]
3fc5965a05 Crowdin Pull (#6969)
Co-authored-by: bitwarden-devops-bot <106330231+bitwarden-devops-bot@users.noreply.github.com>
2026-05-26 14:25:24 +00:00
Patrick Honkonen
8cd52a716f [PM-37916] feat: Add titleExtraLarge typography and apply to Premium header (#6962) 2026-05-22 20:00:40 +00:00
David Perez
7b94daf3ae Chore: Update Policy Types to conform to known values (#6965) 2026-05-22 19:42:23 +00:00
Patrick Honkonen
a5f7288208 [PM-37916] chore: Align Premium subscription card line items with Web (#6961) 2026-05-22 18:45:57 +00:00
David Perez
c6a439a791 Deps: Update to Junit v6.1.0 (#6964) 2026-05-22 17:51:54 +00:00
bw-ghapp[bot]
34ce0edc03 Update SDK to 3.0.0-7038-1a2acacb (#6956)
Co-authored-by: bw-ghapp[bot] <178206702+bw-ghapp[bot]@users.noreply.github.com>
2026-05-22 15:11:49 +00:00
Patrick Honkonen
f4507384e9 llm: Add interface KDoc rule to implementing-android-code skill (#6963) 2026-05-22 13:32:25 +00:00
Mick Letofsky
0005ed7a2f PM-36952 - Improve code review workflow with added triggers (#6933) 2026-05-22 12:56:03 +00:00
renovate[bot]
bf14dfbf40 [deps]: Lock file maintenance (#6904)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Álison Fernandes <vvolkgang@users.noreply.github.com>
2026-05-21 22:35:54 +00:00
renovate[bot]
fc2786d809 [deps]: Update gh minor (#6926)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Álison Fernandes <vvolkgang@users.noreply.github.com>
2026-05-21 22:23:57 +00:00
David Perez
c6bef627a2 Deps: Update Coroutines to v1.11.0 (#6959) 2026-05-21 19:42:39 +00:00
aj-rosado
afe296c3db [PM-37254] feat: Add fill-assist-targeting-rules feature flag (#6952) 2026-05-21 16:28:27 +00:00
David Perez
e4fb873d34 PM-34085: Chore: Remove the Authenticator Sync backwards compatibility (#6928) 2026-05-21 14:45:23 +00:00
Patrick Honkonen
50960456c5 [PM-37691] feat: Surface pending cancellation status on Premium plan view (#6957) 2026-05-21 12:18:54 +00:00
David Perez
ebc3bd8081 PM-37568: Feat: Remove feature flags (#6955) 2026-05-20 22:28:30 +00:00
Patrick Honkonen
8f72c10f8e [PM-37804] feat: Confirm before leaving the app to Stripe checkout (#6958) 2026-05-20 22:28:05 +00:00
Patrick Honkonen
c6746fb369 [PM-37814] feat: Add debug flag to disable self-host premium check (#6954) 2026-05-20 21:44:07 +00:00
Patrick Honkonen
31011b5789 [PM-37289] fix: Refresh archive row after premium upgrade (#6949) 2026-05-20 19:19:58 +00:00
Patrick Honkonen
a9048c6393 [PM-37810] fix: Update cancel premium confirmation dialog (#6953) 2026-05-20 19:03:13 +00:00
Patrick Honkonen
9e27b950e8 [PM-37284] fix: Show Upgraded to Premium card across all Send view states (#6947) 2026-05-20 18:00:32 +00:00
bw-ghapp[bot]
8940a2c490 Update SDK to 3.0.0-6963-1256a563 (#6921)
Co-authored-by: bw-ghapp[bot] <178206702+bw-ghapp[bot]@users.noreply.github.com>
2026-05-20 16:55:41 +00:00
Patrick Honkonen
2eab66ecd3 [PM-37076] fix: Manage Plan launches web vault subscription URL (#6944) 2026-05-20 16:39:08 +00:00
Patrick Honkonen
fce814d6bd [PM-36886] fix: Gate premium upgrade flow on self-hosted environments (#6939) 2026-05-20 15:29:31 +00:00
Patrick Honkonen
8002794c59 [PM-37294] fix: Announce external-link affordance on premium upgrade CTAs (#6951) 2026-05-20 15:15:20 +00:00
David Perez
304c32e1a4 PM-37705: Feat: Hide Send navigation when DISABLE_SEND policy is enabled (#6945) 2026-05-20 14:40:47 +00:00
Patrick Honkonen
cc210a5764 [PM-37335] fix: Route attachments upgrade CTA through in-app plan modal (#6946) 2026-05-20 01:17:24 +00:00
Patrick Honkonen
5f3f9d186c [PM-36969] feat: Surface subscription substate to premium gates (#6931)
Co-authored-by: claude[bot] <209825114+claude[bot]@users.noreply.github.com>
2026-05-19 22:17:12 +00:00
Álison Fernandes
6cf7227973 [PM-35435] ci: Stop applying Change Type labels based on changed files (#6925) 2026-05-19 21:02:39 +00:00
aj-rosado
e949dd710a [PM-33982] feat: Add device management screen (#6754) 2026-05-19 19:40:13 +00:00
David Perez
6ccb9d9f3e Bug: Update BitwardenDatePickerDialog to match current designs (#6943) 2026-05-19 16:41:21 +00:00
David Perez
83a9d35e32 PM-37690: feat: Update copy for adding a new item (#6940) 2026-05-18 21:30:11 +00:00
David Perez
5f415e2deb chore: Remove background event interface from action (#6941) 2026-05-18 21:29:06 +00:00
Patrick Honkonen
1f8280f76d [PM-37465] fix: Gate Plan row and Upgraded card on personal Premium (#6930) 2026-05-18 20:48:48 +00:00
David Perez
bc93d7c311 PM-37573: feat: Add DatePicker functionality to VaultAddEditScreen (#6937) 2026-05-18 17:47:32 +00:00
Patrick Honkonen
fcc1eebab1 [PM-32806] feat: Add Passport vault, listing, and search surfaces (#6929) 2026-05-18 17:27:00 +00:00
Patrick Honkonen
e2ab1f5663 Update MobilePremiumUpgrade feature flag key to lowercase (#6934) 2026-05-18 16:33:28 +00:00
David Perez
11bdb07bde PM-37573: Feat: Create DatePickerDialog (#6924) 2026-05-18 15:00:14 +00:00
bw-ghapp[bot]
4108811349 Crowdin Pull (#6932)
Co-authored-by: bitwarden-devops-bot <106330231+bitwarden-devops-bot@users.noreply.github.com>
2026-05-18 13:55:25 +00:00
David Perez
38a5e6fe55 PM-36508: Chore: Local network access permission (#6916) 2026-05-15 19:30:02 +00:00
David Perez
2f6a36ce1a bug: Update Passport and License date formats in VaultItemScreen (#6927) 2026-05-15 19:03:42 +00:00
Patrick Honkonen
484d326e14 [PM-32806] feat: Add Add/Edit support for Passport item type (#6923) 2026-05-15 16:14:13 +00:00
renovate[bot]
cc06636276 [deps]: Update fastlane to v2.233.1 (#6902)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Álison Fernandes <vvolkgang@users.noreply.github.com>
2026-05-14 21:56:06 +00:00
Patrick Honkonen
d390272c0c [PM-32806] feat: View Passport item type (#6853) 2026-05-14 19:28:31 +00:00
David Perez
92845c6a4d Bug: Fix CipherType crash (#6922) 2026-05-14 19:27:06 +00:00
bw-ghapp[bot]
f002c2c070 deps: Update SDK to 3.0.0-6822-fe351b43 (#6912)
Co-authored-by: bw-ghapp[bot] <178206702+bw-ghapp[bot]@users.noreply.github.com>
2026-05-14 13:08:25 +00:00
renovate[bot]
4f2a364eec [deps]: Update org.sonarqube to v7.3.0.8198 (#6903)
Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com>
Co-authored-by: Álison Fernandes <vvolkgang@users.noreply.github.com>
2026-05-13 20:45:01 +00:00
David Perez
e4f030d0e3 Bug: Support translations for Cookie Acquisition error (#6917) 2026-05-13 20:05:53 +00:00
Patrick Honkonen
8fe23ad275 [PM-32808] feat: Add Driver's License vault, listing, and search surfaces (#6909) 2026-05-13 19:22:02 +00:00
Patrick Honkonen
ecc4fa6dea [PM-32808] feat: Add Add/Edit support for Driver's License item type (#6908) 2026-05-13 14:20:03 +00:00
ifernandezdiaz
f6d56fa234 [QA-1859] Updating testTags in AddEditSendItemView (#6911) 2026-05-12 17:46:52 +00:00
David Perez
07a40c2c04 Chore: Remove Retrofit dependency from app module (#6896) 2026-05-12 16:57:57 +00:00
Patrick Honkonen
68f88b651e [PM-32808] feat: View License item type (#6852) 2026-05-12 15:42:44 +00:00
bw-ghapp[bot]
dbb27c1cd0 Update SDK to 3.0.0-6774-0a0f5faf (#6895)
Co-authored-by: bw-ghapp[bot] <178206702+bw-ghapp[bot]@users.noreply.github.com>
2026-05-12 14:27:26 +00:00
github-actions[bot]
73f1e2c645 chore: Update Google privileged browsers list (#6899)
Co-authored-by: GitHub Actions Bot <actions@github.com>
2026-05-11 18:07:45 +00:00
Fabian Freund
4e527f3097 [PM-37042] chore: Add eu.weblibre.gecko.alpha to privileged apps (#6905) 2026-05-11 18:07:10 +00:00
David Perez
7e553867d0 build: Allow logging and access to the debug menu for beta builds (#6874) 2026-05-11 14:59:16 +00:00
Gabriel Brand
33fcbad97f Use string resource for button label (#6897) 2026-05-11 14:09:10 +00:00
bw-ghapp[bot]
24a9aea1c9 Crowdin Pull (#6900)
Co-authored-by: bitwarden-devops-bot <106330231+bitwarden-devops-bot@users.noreply.github.com>
2026-05-11 14:00:05 +00:00
483 changed files with 29038 additions and 4726 deletions

View File

@@ -1,6 +1,6 @@
---
name: implementing-android-code
version: 0.1.3
version: 0.1.4
description: This skill should be used when implementing Android code in Bitwarden. Covers critical patterns, gotchas, and anti-patterns unique to this codebase. Triggered by "How do I implement a ViewModel?", "Create a new screen", "Add navigation", "Write a repository", "BaseViewModel pattern", "State-Action-Event", "type-safe navigation", "@Serializable route", "SavedStateHandle persistence", "process death recovery", "handleAction", "sendAction", "Hilt module", "Repository pattern", "implementing a screen", "adding a data source", "handling navigation", "encrypted storage", "security patterns", "Clock injection", "DataState", or any questions about implementing features, screens, ViewModels, data sources, or navigation in the Bitwarden Android app.
---
@@ -236,6 +236,44 @@ object ExampleRepositoryModule {
- ✅ Data sources return `Result<T>`, repositories return domain sealed classes
- ✅ Use `StateFlow` for continuously observed data
**KDoc on Interfaces vs. Implementations**
KDoc on an interface member describes the **contract** — what the caller can rely on. It must not describe **how** the implementation fulfills that contract. Implementation details (which data source is consulted, what is cached, what is logged, which manager is delegated to, ordering of internal calls, etc.) belong on the `...Impl` member — and only when the *why* is non-obvious from the code itself.
This applies to every interface in the codebase: repositories, managers, data sources, validators, and UI-layer interfaces alike. The rule is the same one CLAUDE.md states for comments in general — describe the contract or the non-obvious *why*, never the *what* a well-named identifier already conveys.
**Wrong** — interface KDoc leaks the implementation:
```kotlin
interface ExampleRepository {
/**
* Fetches data by reading from [ExampleDiskSource] first, falling back to
* [ExampleService] on cache miss and writing the network result back to disk.
*/
suspend fun fetchData(id: String): ExampleResult
}
```
**Right** — interface KDoc describes the contract; implementation details (if needed at all) live on the override:
```kotlin
interface ExampleRepository {
/** Returns the [ExampleData] for [id], or an error result on failure. */
suspend fun fetchData(id: String): ExampleResult
}
class ExampleRepositoryImpl(...) : ExampleRepository {
// No KDoc needed — the disk-then-network pattern is visible in the code.
override suspend fun fetchData(id: String): ExampleResult { ... }
}
```
Red flags that an interface KDoc has drifted into implementation territory:
- Names a concrete collaborator (`...DiskSource`, `...Service`, `...Manager`, `...Impl`)
- Describes ordering of internal calls ("first ... then ...", "falls back to ...")
- Mentions caching, retries, logging, or threading behavior that callers don't depend on
- Restates the method signature in prose ("Suspends until X returns Y")
If callers genuinely depend on a behavior (e.g., "this method is safe to call before vault unlock", "result is cached for the session"), that *is* part of the contract and belongs on the interface. The test: would a different valid implementation be free to change this? If yes, it's implementation detail — strip it.
---
### E. UI Components
@@ -504,6 +542,9 @@ Single-line branches (body fits on the same line as `->`) do **not** need braces
**NEVER call `Instant.now()` or `DateTime.now()` directly**
- Inject `Clock` via Hilt, use `clock.instant()` for testability
**NEVER put implementation details in interface KDoc**
- Interface KDoc describes the contract; concrete collaborators, call ordering, caching, and fallback behavior belong on the `...Impl` override (and only when the *why* is non-obvious). See section D for examples.
---
## Quick Reference

View File

@@ -12,12 +12,12 @@ runs:
uses: gradle/actions/setup-gradle@50e97c2cd7a37755bbfafc9c5b7cafaece252f6e # v6.1.0
- name: Configure Ruby
uses: ruby/setup-ruby@44511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0
uses: ruby/setup-ruby@6aaa311d81eba98ae12eaffbcb63296ace0efcde # v1.307.0
with:
bundler-cache: true
- name: Configure JDK
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
uses: actions/setup-java@be666c2fcd27ec809703dec50e508c2fdc7f6654 # v5.2.0
with:
distribution: "temurin"
java-version: ${{ inputs.java-version }}

26
.github/label-pr.json vendored
View File

@@ -27,32 +27,6 @@
],
"app:authenticator": [
"authenticator/"
],
"t:feature": [
"app/src/main/assets/fido2_privileged_community.json",
"app/src/main/assets/fido2_privileged_google.json",
"testharness/"
],
"t:tech-debt": [
"gradle.properties",
"keystore/"
],
"t:ci": [
".checkmarx/",
".github/",
"scripts/",
"fastlane/",
".gradle/",
"detekt-config.yml"
],
"t:docs": [
"docs/"
],
"t:deps": [
"gradle/"
],
"t:llm": [
".claude/"
]
}
}

View File

@@ -79,7 +79,7 @@ jobs:
- name: Check out repository
if: ${{ !inputs.skip_checkout || false }}
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
fetch-depth: 0
persist-credentials: false
@@ -167,7 +167,7 @@ jobs:
echo '```' >> "$GITHUB_STEP_SUMMARY"
- name: Upload version info artifact
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: version-info
path: version_info.json

View File

@@ -63,7 +63,7 @@ jobs:
steps:
- name: Check out repo
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
@@ -176,7 +176,7 @@ jobs:
- name: Upload to GitHub Artifacts - prod.aab
if: ${{ matrix.variant == 'aab' }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.bitwarden.authenticator.aab
path: authenticator/build/outputs/bundle/release/com.bitwarden.authenticator.aab
@@ -184,7 +184,7 @@ jobs:
- name: Upload to GitHub Artifacts - prod.apk
if: ${{ matrix.variant == 'apk' }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.bitwarden.authenticator.apk
path: authenticator/build/outputs/apk/release/com.bitwarden.authenticator.apk
@@ -204,7 +204,7 @@ jobs:
- name: Upload to GitHub Artifacts - prod.apk-sha256.txt
if: ${{ matrix.variant == 'apk' }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: authenticator-android-apk-sha256.txt
path: ./authenticator-android-apk-sha256.txt
@@ -212,7 +212,7 @@ jobs:
- name: Upload to GitHub Artifacts - prod.aab-sha256.txt
if: ${{ matrix.variant == 'aab' }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: authenticator-android-aab-sha256.txt
path: ./authenticator-android-aab-sha256.txt

View File

@@ -48,7 +48,7 @@ jobs:
inputs: "${{ toJson(inputs) }}"
- name: Check out repo
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
@@ -65,7 +65,7 @@ jobs:
run: ./gradlew :testharness:assembleDebug
- name: Upload Test Harness APK
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.bitwarden.testharness.dev-debug.apk
path: testharness/build/outputs/apk/debug/com.bitwarden.testharness.dev.apk
@@ -77,7 +77,7 @@ jobs:
> ./com.bitwarden.testharness.dev.apk-sha256.txt
- name: Upload Test Harness SHA file
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.bitwarden.testharness.dev.apk-sha256.txt
path: ./com.bitwarden.testharness.dev.apk-sha256.txt

View File

@@ -65,7 +65,7 @@ jobs:
artifact: ["apk", "aab"]
steps:
- name: Check out repo
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
@@ -192,7 +192,7 @@ jobs:
- name: Upload to GitHub Artifacts - prod.aab
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden.aab
path: app/build/outputs/bundle/standardRelease/com.x8bit.bitwarden.aab
@@ -200,7 +200,7 @@ jobs:
- name: Upload to GitHub Artifacts - beta.aab
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden.beta.aab
path: app/build/outputs/bundle/standardBeta/com.x8bit.bitwarden.beta.aab
@@ -208,7 +208,7 @@ jobs:
- name: Upload to GitHub Artifacts - prod.apk
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden.apk
path: app/build/outputs/apk/standard/release/com.x8bit.bitwarden.apk
@@ -216,7 +216,7 @@ jobs:
- name: Upload to GitHub Artifacts - beta.apk
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden.beta.apk
path: app/build/outputs/apk/standard/beta/com.x8bit.bitwarden.beta.apk
@@ -225,7 +225,7 @@ jobs:
# When building variants other than 'prod'
- name: Upload to GitHub Artifacts - dev.apk
if: ${{ (matrix.variant != 'prod') && (matrix.artifact == 'apk') }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden.${{ matrix.variant }}.apk
path: app/build/outputs/apk/standard/debug/com.x8bit.bitwarden.dev.apk
@@ -263,7 +263,7 @@ jobs:
- name: Upload to GitHub Artifacts - prod.apk-sha256.txt
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden.apk-sha256.txt
path: ./com.x8bit.bitwarden.apk-sha256.txt
@@ -271,7 +271,7 @@ jobs:
- name: Upload to GitHub Artifacts - beta.apk-sha256.txt
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden.beta.apk-sha256.txt
path: ./com.x8bit.bitwarden.beta.apk-sha256.txt
@@ -279,7 +279,7 @@ jobs:
- name: Upload to GitHub Artifacts - prod.aab-sha256.txt
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden.aab-sha256.txt
path: ./com.x8bit.bitwarden.aab-sha256.txt
@@ -287,7 +287,7 @@ jobs:
- name: Upload to GitHub Artifacts - beta.aab-sha256.txt
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden.beta.aab-sha256.txt
path: ./com.x8bit.bitwarden.beta.aab-sha256.txt
@@ -295,7 +295,7 @@ jobs:
- name: Upload to GitHub Artifacts - debug.apk-sha256.txt
if: ${{ (matrix.variant != 'prod') && (matrix.artifact == 'apk') }}
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden.${{ matrix.variant }}.apk-sha256.txt
path: ./com.x8bit.bitwarden.${{ matrix.variant }}.apk-sha256.txt
@@ -343,7 +343,7 @@ jobs:
id-token: write
steps:
- name: Check out repo
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
@@ -424,7 +424,7 @@ jobs:
keyPassword:$FDROID_BETA_KEY_PASSWORD
- name: Upload to GitHub Artifacts - fdroid.apk
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden-fdroid.apk
path: app/build/outputs/apk/fdroid/release/com.x8bit.bitwarden-fdroid.apk
@@ -436,14 +436,14 @@ jobs:
> ./com.x8bit.bitwarden-fdroid.apk-sha256.txt
- name: Upload to GitHub Artifacts - fdroid.apk-sha256.txt
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden-fdroid.apk-sha256.txt
path: ./com.x8bit.bitwarden-fdroid.apk-sha256.txt
if-no-files-found: error
- name: Upload to GitHub Artifacts - beta.fdroid.apk
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden.beta-fdroid.apk
path: app/build/outputs/apk/fdroid/beta/com.x8bit.bitwarden.beta-fdroid.apk
@@ -455,7 +455,7 @@ jobs:
> ./com.x8bit.bitwarden.beta-fdroid.apk-sha256.txt
- name: Upload to GitHub Artifacts - beta.fdroid.apk-sha256.txt
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
name: com.x8bit.bitwarden.beta-fdroid.apk-sha256.txt
path: ./com.x8bit.bitwarden.beta-fdroid.apk-sha256.txt

View File

@@ -21,7 +21,7 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: true

View File

@@ -18,7 +18,7 @@ jobs:
id-token: write
steps:
- name: Checkout repo
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
@@ -47,7 +47,7 @@ jobs:
uses: bitwarden/gh-actions/azure-logout@main
- name: Generate GH App token
uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859 # v3.0.0
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
id: app-token
with:
app-id: ${{ steps.get-kv-secrets.outputs.BW-GHAPP-ID }}
@@ -56,7 +56,7 @@ jobs:
permission-pull-requests: write # for creating pull request
- name: Download translations
uses: crowdin/github-action@0749939f635900a2521aa6aac7a3766642b2dc71 # v2.11.0
uses: crowdin/github-action@8868a33591d21088edfc398968173a3b98d51706 # v2.16.2
env:
GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
CROWDIN_API_TOKEN: ${{ steps.retrieve-secrets.outputs.CROWDIN-API-TOKEN }}

View File

@@ -16,7 +16,7 @@ jobs:
id-token: write
steps:
- name: Check out repo
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
@@ -35,7 +35,7 @@ jobs:
secrets: "CROWDIN-API-TOKEN"
- name: Upload sources
uses: crowdin/github-action@0749939f635900a2521aa6aac7a3766642b2dc71 # v2.11.0
uses: crowdin/github-action@8868a33591d21088edfc398968173a3b98d51706 # v2.16.2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
CROWDIN_API_TOKEN: ${{ steps.retrieve-secrets.outputs.CROWDIN-API-TOKEN }}

View File

@@ -25,7 +25,7 @@ jobs:
steps:
- name: Check out repository
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
fetch-depth: 0
persist-credentials: true

View File

@@ -73,11 +73,11 @@ jobs:
inputs: "${{ toJson(inputs) }}"
- name: Check out repo
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Configure Ruby
uses: ruby/setup-ruby@44511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0
uses: ruby/setup-ruby@6aaa311d81eba98ae12eaffbcb63296ace0efcde # v1.307.0
with:
bundler-cache: true

View File

@@ -22,7 +22,7 @@ jobs:
actions: write
steps:
- name: Check out repository
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
fetch-depth: 0
persist-credentials: true

View File

@@ -2,7 +2,7 @@ name: Code Review
on:
pull_request:
types: [opened, synchronize, reopened]
types: [labeled, opened, ready_for_review, reopened, synchronize]
permissions: {}

View File

@@ -24,7 +24,7 @@ jobs:
runs-on: ubuntu-24.04
steps:
- name: Check out repo
uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false

View File

@@ -34,7 +34,7 @@ jobs:
steps:
- name: Check out repository
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false

View File

@@ -53,7 +53,7 @@ jobs:
uses: bitwarden/gh-actions/azure-logout@main
- name: Generate GH App token
uses: actions/create-github-app-token@f8d387b68d61c58ab83c6c016672934102569859 # v3.0.0
uses: actions/create-github-app-token@bcd2ba49218906704ab6c1aa796996da409d3eb1 # v3.2.0
id: app-token
with:
app-id: ${{ steps.get-kv-secrets.outputs.BW-GHAPP-ID }}
@@ -63,7 +63,7 @@ jobs:
permission-contents: write
- name: Check out repo
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
token: ${{ steps.app-token.outputs.token }}
fetch-depth: 0
@@ -204,7 +204,7 @@ jobs:
steps:
- name: Check out repo
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false

View File

@@ -54,7 +54,7 @@ jobs:
steps:
- name: Check out repo
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
@@ -99,7 +99,7 @@ jobs:
disable_search: true
- name: Upload test reports
uses: actions/upload-artifact@bbbca2ddaa5d8feaa63e36b76fdaad77386f024f # v7.0.0
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
if: always()
with:
name: test-reports-${{ matrix.group }}

View File

@@ -2,7 +2,7 @@ source 'https://rubygems.org'
ruby File.read(".ruby-version").strip
gem 'fastlane', '2.229.1'
gem 'fastlane', '2.233.1'
gem 'time', '0.4.2'
plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile')

View File

@@ -8,8 +8,8 @@ GEM
artifactory (3.0.17)
atomos (0.1.3)
aws-eventstream (1.4.0)
aws-partitions (1.1241.0)
aws-sdk-core (3.246.0)
aws-partitions (1.1249.0)
aws-sdk-core (3.247.0)
aws-eventstream (~> 1, >= 1.3.0)
aws-partitions (~> 1, >= 1.992.0)
aws-sigv4 (~> 1.9)
@@ -17,17 +17,18 @@ GEM
bigdecimal
jmespath (~> 1, >= 1.6.1)
logger
aws-sdk-kms (1.123.0)
aws-sdk-core (~> 3, >= 3.244.0)
aws-sdk-kms (1.125.0)
aws-sdk-core (~> 3, >= 3.247.0)
aws-sigv4 (~> 1.5)
aws-sdk-s3 (1.220.0)
aws-sdk-core (~> 3, >= 3.244.0)
aws-sdk-s3 (1.222.0)
aws-sdk-core (~> 3, >= 3.247.0)
aws-sdk-kms (~> 1)
aws-sigv4 (~> 1.5)
aws-sigv4 (1.12.1)
aws-eventstream (~> 1, >= 1.0.2)
babosa (1.0.4)
base64 (0.2.0)
benchmark (0.5.0)
bigdecimal (4.1.2)
claide (1.1.0)
colored (1.2)
@@ -72,15 +73,16 @@ GEM
faraday_middleware (1.2.1)
faraday (~> 1.0)
fastimage (2.4.1)
fastlane (2.229.1)
fastlane (2.233.1)
CFPropertyList (>= 2.3, < 4.0.0)
abbrev (~> 0.1.2)
addressable (>= 2.8, < 3.0.0)
artifactory (~> 3.0)
aws-sdk-s3 (~> 1.0)
aws-sdk-s3 (~> 1.197)
babosa (>= 1.0.3, < 2.0.0)
base64 (~> 0.2.0)
bundler (>= 1.12.0, < 3.0.0)
benchmark (>= 0.1.0)
bundler (>= 1.17.3, < 5.0.0)
colored (~> 1.2)
commander (~> 4.6)
csv (~> 3.3)
@@ -91,22 +93,24 @@ GEM
faraday-cookie_jar (~> 0.0.6)
faraday_middleware (~> 1.0)
fastimage (>= 2.1.0, < 3.0.0)
fastlane-sirp (>= 1.0.0)
fastlane-sirp (>= 1.1.0)
gh_inspector (>= 1.1.2, < 2.0.0)
google-apis-androidpublisher_v3 (~> 0.3)
google-apis-playcustomapp_v1 (~> 0.1)
google-cloud-env (>= 1.6.0, < 2.0.0)
google-cloud-env (>= 1.6.0, <= 2.1.1)
google-cloud-storage (~> 1.31)
highline (~> 2.0)
http-cookie (~> 1.0.5)
json (< 3.0.0)
jwt (>= 2.1.0, < 3)
logger (>= 1.6, < 2.0)
mini_magick (>= 4.9.4, < 5.0.0)
multipart-post (>= 2.0.0, < 3.0.0)
mutex_m (~> 0.3.0)
naturally (~> 2.2)
nkf (~> 0.2.0)
optparse (>= 0.1.1, < 1.0.0)
ostruct (>= 0.1.0)
plist (>= 3.1.0, < 4.0.0)
rubyzip (>= 2.0.0, < 3.0.0)
security (= 0.1.5)
@@ -119,47 +123,50 @@ GEM
xcodeproj (>= 1.13.0, < 2.0.0)
xcpretty (~> 0.4.1)
xcpretty-travis-formatter (>= 0.0.3, < 2.0.0)
fastlane-plugin-firebase_app_distribution (0.10.1)
google-apis-firebaseappdistribution_v1 (~> 0.3.0)
google-apis-firebaseappdistribution_v1alpha (~> 0.2.0)
fastlane-plugin-firebase_app_distribution (1.0.0)
fastlane (>= 2.232.0)
google-apis-firebaseappdistribution_v1 (>= 0.9.0)
google-apis-firebaseappdistribution_v1alpha (>= 0.12.0)
fastlane-sirp (1.1.0)
gh_inspector (1.1.3)
google-apis-androidpublisher_v3 (0.54.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-core (0.11.3)
google-apis-androidpublisher_v3 (0.100.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-core (0.18.0)
addressable (~> 2.5, >= 2.5.1)
googleauth (>= 0.16.2, < 2.a)
httpclient (>= 2.8.1, < 3.a)
googleauth (~> 1.9)
httpclient (>= 2.8.3, < 3.a)
mini_mime (~> 1.0)
mutex_m
representable (~> 3.0)
retriable (>= 2.0, < 4.a)
rexml
google-apis-firebaseappdistribution_v1 (0.3.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-firebaseappdistribution_v1alpha (0.2.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-iamcredentials_v1 (0.17.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-playcustomapp_v1 (0.13.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-storage_v1 (0.31.0)
google-apis-core (>= 0.11.0, < 2.a)
google-apis-firebaseappdistribution_v1 (0.19.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-firebaseappdistribution_v1alpha (0.28.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-iamcredentials_v1 (0.27.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-playcustomapp_v1 (0.17.0)
google-apis-core (>= 0.15.0, < 2.a)
google-apis-storage_v1 (0.62.0)
google-apis-core (>= 0.15.0, < 2.a)
google-cloud-core (1.8.0)
google-cloud-env (>= 1.0, < 3.a)
google-cloud-errors (~> 1.0)
google-cloud-env (1.6.0)
faraday (>= 0.17.3, < 3.0)
google-cloud-env (2.1.1)
faraday (>= 1.0, < 3.a)
google-cloud-errors (1.6.0)
google-cloud-storage (1.47.0)
google-cloud-storage (1.60.0)
addressable (~> 2.8)
digest-crc (~> 0.4)
google-apis-iamcredentials_v1 (~> 0.1)
google-apis-storage_v1 (~> 0.31.0)
google-apis-core (>= 0.18, < 2)
google-apis-iamcredentials_v1 (~> 0.18)
google-apis-storage_v1 (>= 0.42)
google-cloud-core (~> 1.6)
googleauth (>= 0.16.2, < 2.a)
googleauth (~> 1.9)
mini_mime (~> 1.0)
googleauth (1.8.1)
faraday (>= 0.17.3, < 3.a)
googleauth (1.11.2)
faraday (>= 1.0, < 3.a)
google-cloud-env (~> 2.1)
jwt (>= 1.4, < 3.0)
multi_json (~> 1.11)
os (>= 0.9, < 2.0)
@@ -170,13 +177,13 @@ GEM
httpclient (2.9.0)
mutex_m
jmespath (1.6.2)
json (2.19.4)
json (2.19.5)
jwt (2.10.2)
base64
logger (1.7.0)
mini_magick (4.13.2)
mini_mime (1.1.5)
multi_json (1.20.1)
multi_json (1.21.1)
multipart-post (2.4.1)
mutex_m (0.3.0)
nanaimo (0.4.0)
@@ -237,7 +244,7 @@ PLATFORMS
DEPENDENCIES
abbrev (= 0.1.2)
csv (= 3.3.5)
fastlane (= 2.229.1)
fastlane (= 2.233.1)
fastlane-plugin-firebase_app_distribution
logger (= 1.7.0)
mutex_m (= 0.3.0)

View File

@@ -121,7 +121,7 @@ configure<ApplicationExtension> {
"proguard-rules.pro",
)
buildConfigField(type = "boolean", name = "HAS_DEBUG_MENU", value = "false")
buildConfigField(type = "boolean", name = "HAS_DEBUG_MENU", value = "true")
buildConfigField(type = "boolean", name = "HAS_LOGS_ENABLED", value = "false")
}
release {
@@ -285,8 +285,6 @@ dependencies {
implementation(libs.kotlinx.serialization)
implementation(platform(libs.square.okhttp.bom))
implementation(libs.square.okhttp)
implementation(platform(libs.square.retrofit.bom))
implementation(libs.square.retrofit)
implementation(libs.timber)
// For now we are restricted to running Compose tests for debug builds only

View File

@@ -0,0 +1,40 @@
<?xml version="1.0" encoding="utf-8"?>
<network-security-config xmlns:tools="http://schemas.android.com/tools">
<base-config cleartextTrafficPermitted="false">
<trust-anchors>
<!-- Trust pre-installed CAs -->
<certificates src="system" />
<!-- Additionally trust user added CAs -->
<certificates
src="user"
tools:ignore="AcceptsUserCertificates" />
</trust-anchors>
</base-config>
<!-- A lot of TLS certificates point to http:// URLs for CRL and OCSP checking,
so we need to allow cleartext traffic on them -->
<domain-config cleartextTrafficPermitted="true">
<!-- CRL Distribution Servers -->
<domain includeSubdomains="true">c.lencr.org</domain>
<domain includeSubdomains="true">c.pki.goog</domain>
<!-- OCSP Responder Servers -->
<domain includeSubdomains="true">o.pki.goog</domain>
<domain includeSubdomains="true">ocsp.sectigo.com</domain>
</domain-config>
<domain-config cleartextTrafficPermitted="false">
<domain includeSubdomains="true">bitwarden.com</domain>
<domain includeSubdomains="true">bitwarden.eu</domain>
<domain includeSubdomains="true">bitwarden.pw</domain>
<trust-anchors>
<!-- Only trust pre-installed CAs for Bitwarden domains and all subdomains -->
<certificates src="system" />
<!-- Additionally trust user added CAs -->
<certificates src="user" />
</trust-anchors>
</domain-config>
</network-security-config>

View File

@@ -9,6 +9,7 @@
android:name="android.hardware.nfc"
android:required="false" />
<uses-permission android:name="android.permission.ACCESS_LOCAL_NETWORK" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-permission android:name="android.permission.NFC" />

View File

@@ -28,6 +28,22 @@
]
}
},
{
"type": "android",
"info": {
"package_name": "eu.weblibre.gecko.alpha",
"signatures": [
{
"build": "release",
"cert_fingerprint_sha256": "BB:2A:97:F5:61:53:35:C9:E5:7C:86:6F:1C:30:ED:4F:D7:D7:BD:DC:BC:BC:06:68:FE:93:A5:79:17:3D:3D:2D"
},
{
"build": "release",
"cert_fingerprint_sha256": "8F:52:6E:1E:53:D6:BD:4D:FB:F4:F4:B9:3C:2A:91:EC:B5:CB:8D:A5:E1:4A:D9:4C:25:70:E1:E3:C7:13:52:7F"
}
]
}
},
{
"type": "android",
"info": {

View File

@@ -580,6 +580,18 @@
]
}
},
{
"type": "android",
"info": {
"package_name": "com.talonsec.intune.talon",
"signatures": [
{
"build": "release",
"cert_fingerprint_sha256": "09:0C:4C:E6:20:65:9B:04:00:35:8F:C8:3F:DC:9F:02:D2:AB:77:C3:7F:4C:80:14:30:8E:FF:96:BA:54:49:55"
}
]
}
},
{
"type": "android",
"info": {

View File

@@ -3,6 +3,7 @@ package com.x8bit.bitwarden
import android.app.Application
import com.bitwarden.annotation.OmitFromCoverage
import com.x8bit.bitwarden.data.auth.manager.AuthRequestNotificationManager
import com.x8bit.bitwarden.data.autofill.manager.FillAssistManager
import com.x8bit.bitwarden.data.platform.manager.LogsManager
import com.x8bit.bitwarden.data.platform.manager.event.OrganizationEventManager
import com.x8bit.bitwarden.data.platform.manager.network.NetworkConfigManager
@@ -20,6 +21,9 @@ import javax.inject.Inject
class BitwardenApplication : Application() {
// Inject classes here that must be triggered on startup but are not otherwise consumed by
// other callers.
@Inject
lateinit var fillAssistManager: FillAssistManager
@Inject
lateinit var logsManager: LogsManager

View File

@@ -41,6 +41,8 @@ import com.x8bit.bitwarden.ui.platform.feature.cookieacquisition.navigateToCooki
import com.x8bit.bitwarden.ui.platform.feature.debugmenu.debugMenuDestination
import com.x8bit.bitwarden.ui.platform.feature.debugmenu.manager.DebugMenuLaunchManager
import com.x8bit.bitwarden.ui.platform.feature.debugmenu.navigateToDebugMenuScreen
import com.x8bit.bitwarden.ui.platform.feature.localnetworkaccess.localNetworkAccessDestination
import com.x8bit.bitwarden.ui.platform.feature.localnetworkaccess.navigateToLocalNetworkAccess
import com.x8bit.bitwarden.ui.platform.feature.rootnav.RootNavigationRoute
import com.x8bit.bitwarden.ui.platform.feature.rootnav.rootNavDestination
import com.x8bit.bitwarden.ui.platform.feature.settings.appearance.model.AppLanguage
@@ -93,6 +95,21 @@ class MainActivity : AppCompatActivity() {
mainViewModel.trySendAction(MainAction.PremiumCheckoutResult(it))
}
private val stripePortalLauncher = AuthTabIntent.registerActivityResultLauncher(this) {
mainViewModel.trySendAction(MainAction.StripePortalResult(it))
}
private val authTabLaunchers by lazy {
AuthTabLaunchers(
duo = duoLauncher,
sso = ssoLauncher,
webAuthn = webAuthnLauncher,
cookie = cookieLauncher,
premiumCheckout = premiumCheckoutLauncher,
stripePortal = stripePortalLauncher,
)
}
override fun onCreate(savedInstanceState: Bundle?) {
intent = intent.validate()
var shouldShowSplashScreen = true
@@ -115,13 +132,7 @@ class MainActivity : AppCompatActivity() {
updateScreenCapture(isScreenCaptureAllowed = state.isScreenCaptureAllowed)
LocalManagerProvider(
featureFlagsState = state.featureFlagsState,
authTabLaunchers = AuthTabLaunchers(
duo = duoLauncher,
sso = ssoLauncher,
webAuthn = webAuthnLauncher,
cookie = cookieLauncher,
premiumCheckout = premiumCheckoutLauncher,
),
authTabLaunchers = authTabLaunchers,
) {
ObserveScreenDataEffect(
onDataUpdate = remember(mainViewModel) {
@@ -151,6 +162,10 @@ class MainActivity : AppCompatActivity() {
onDismiss = { navController.popBackStack() },
onSplashScreenRemoved = { shouldShowSplashScreen = false },
)
localNetworkAccessDestination(
onDismiss = { navController.popBackStack() },
onSplashScreenRemoved = { shouldShowSplashScreen = false },
)
}
}
}
@@ -235,6 +250,9 @@ class MainActivity : AppCompatActivity() {
MainEvent.Recreate -> handleRecreate()
MainEvent.NavigateToDebugMenu -> navController.navigateToDebugMenuScreen()
MainEvent.NavigateToCookieAcquisition -> navController.navigateToCookieAcquisition()
MainEvent.NavigateToLocalNetworkAccess -> {
navController.navigateToLocalNetworkAccess()
}
is MainEvent.UpdateAppLocale -> {
AppCompatDelegate.setApplicationLocales(

View File

@@ -37,6 +37,7 @@ import com.x8bit.bitwarden.data.platform.manager.garbage.GarbageCollectionManage
import com.x8bit.bitwarden.data.platform.manager.model.AppResumeScreenData
import com.x8bit.bitwarden.data.platform.manager.model.CompleteRegistrationData
import com.x8bit.bitwarden.data.platform.manager.model.SpecialCircumstance
import com.x8bit.bitwarden.data.platform.manager.network.NetworkPermissionManager
import com.x8bit.bitwarden.data.platform.repository.EnvironmentRepository
import com.x8bit.bitwarden.data.platform.repository.SettingsRepository
import com.x8bit.bitwarden.data.platform.util.isAddTotpLoginItemFromAuthenticator
@@ -80,6 +81,7 @@ class MainViewModel @Inject constructor(
accessibilitySelectionManager: AccessibilitySelectionManager,
autofillSelectionManager: AutofillSelectionManager,
cookieAcquisitionRequestManager: CookieAcquisitionRequestManager,
networkPermissionManager: NetworkPermissionManager,
private val addTotpItemFromAuthenticatorManager: AddTotpItemFromAuthenticatorManager,
private val specialCircumstanceManager: SpecialCircumstanceManager,
private val garbageCollectionManager: GarbageCollectionManager,
@@ -168,6 +170,13 @@ class MainViewModel @Inject constructor(
.onEach(::sendAction)
.launchIn(viewModelScope)
networkPermissionManager
.isLocalNetworkAccessRequiredStateFlow
.filter { it }
.map { MainAction.Internal.LocalNetworkAccessRequired }
.onEach(::sendAction)
.launchIn(viewModelScope)
cookieAcquisitionRequestManager
.cookieAcquisitionRequestFlow
.filterNotNull()
@@ -201,6 +210,7 @@ class MainViewModel @Inject constructor(
is MainAction.WebAuthnResult -> handleWebAuthnResult(action)
is MainAction.CookieAcquisitionResult -> handleCookieAcquisitionResult(action)
is MainAction.PremiumCheckoutResult -> handlePremiumCheckoutResult(action)
is MainAction.StripePortalResult -> handleStripePortalResult()
is MainAction.Internal -> handleInternalAction(action)
}
}
@@ -223,6 +233,7 @@ class MainViewModel @Inject constructor(
is MainAction.Internal.ThemeUpdate -> handleAppThemeUpdated(action)
is MainAction.Internal.DynamicColorsUpdate -> handleDynamicColorsUpdate(action)
is MainAction.Internal.CookieAcquisitionReady -> handleCookieAcquisitionReady()
is MainAction.Internal.LocalNetworkAccessRequired -> handleLocalNetworkAccessRequired()
is MainAction.Internal.ResizeHasBeenRequested -> handleResizeHasBeenRequested()
}
}
@@ -257,6 +268,10 @@ class MainViewModel @Inject constructor(
)
}
private fun handleStripePortalResult() {
specialCircumstanceManager.specialCircumstance = SpecialCircumstance.StripePortal
}
private fun handleAppResumeDataUpdated(action: MainAction.ResumeScreenDataReceived) {
when (val data = action.screenResumeData) {
null -> appResumeManager.clearResumeScreen()
@@ -304,6 +319,10 @@ class MainViewModel @Inject constructor(
sendEvent(MainEvent.NavigateToCookieAcquisition)
}
private fun handleLocalNetworkAccessRequired() {
sendEvent(MainEvent.NavigateToLocalNetworkAccess)
}
private fun handleResizeHasBeenRequested() {
mutableStateFlow.update { it.copy(hasResizeBeenRequested = true) }
}
@@ -579,6 +598,14 @@ sealed class MainAction {
val authResult: AuthTabIntent.AuthResult,
) : MainAction()
/**
* Receive the result from the Stripe customer portal flow. The AuthTab does not return a
* payload — closing the tab is the only signal that the user is back in the app.
*/
data class StripePortalResult(
val authResult: AuthTabIntent.AuthResult,
) : MainAction()
/**
* Receive first Intent by the application.
*/
@@ -656,6 +683,11 @@ sealed class MainAction {
*/
data object CookieAcquisitionReady : Internal()
/**
* Indicates that the local network access is required.
*/
data object LocalNetworkAccessRequired : Internal()
/**
* Indicates that resize has been requested on the Activity
*/
@@ -694,6 +726,11 @@ sealed class MainEvent {
*/
data object NavigateToCookieAcquisition : MainEvent()
/**
* Navigate to the local network access screen.
*/
data object NavigateToLocalNetworkAccess : MainEvent()
/**
* Indicates that the app language has been updated.
*/

View File

@@ -2,6 +2,7 @@ package com.x8bit.bitwarden.data.auth.datasource.disk
import android.content.SharedPreferences
import com.bitwarden.core.data.repository.util.bufferedMutableSharedFlow
import com.bitwarden.core.data.serializer.SafeMapSerializer
import com.bitwarden.core.data.util.decodeFromStringOrNull
import com.bitwarden.data.datasource.disk.BaseEncryptedDiskSource
import com.bitwarden.network.model.AccountKeysJson
@@ -14,6 +15,7 @@ import com.x8bit.bitwarden.data.platform.datasource.disk.legacy.LegacySecureStor
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.onSubscription
import kotlinx.serialization.builtins.serializer
import kotlinx.serialization.json.Json
import java.time.Instant
import java.util.UUID
@@ -485,8 +487,13 @@ class AuthDiskSourceImpl(
getString(key = POLICIES_KEY.appendIdentifier(userId))
?.let {
// The policies are stored as a map.
val policiesMap: Map<String, SyncResponseJson.Policy>? =
json.decodeFromStringOrNull(it)
val policiesMap = json.decodeFromStringOrNull(
deserializer = SafeMapSerializer(
keySerializer = String.serializer(),
valueSerializer = SyncResponseJson.Policy.serializer(),
),
string = it,
)
policiesMap?.values?.toList()
}

View File

@@ -42,7 +42,11 @@ data class AccountJson(
* @property name The user's name (if applicable).
* @property stamp The account's security stamp (if applicable).
* @property organizationId The ID of the associated organization (if applicable).
* @property hasPremium True if the user has a Premium account.
* @property hasPremiumPersonally True if the user has personal Premium (i.e., a personal
* subscription not derived from any organization membership).
* @property hasPremiumFromOrganization True if any organization the user is a member of grants
* Premium features. `null` when the value has not yet been synced (e.g., immediately after
* token-based login before the first sync completes).
* @property avatarColorHex Hex color value for a user's avatar in the "#AARRGGBB" format.
* @property forcePasswordResetReason Describes the reason for a forced password reset.
* @property kdfType The KDF type.
@@ -80,7 +84,10 @@ data class AccountJson(
val avatarColorHex: String?,
@SerialName("hasPremiumPersonally")
val hasPremium: Boolean?,
val hasPremiumPersonally: Boolean?,
@SerialName("hasPremiumFromOrganization")
val hasPremiumFromOrganization: Boolean?,
@SerialName("forcePasswordResetReason")
val forcePasswordResetReason: ForcePasswordResetReason?,

View File

@@ -11,6 +11,9 @@ import com.bitwarden.core.RegisterKeyResponse
import com.bitwarden.core.RegisterTdeKeyResponse
import com.bitwarden.crypto.HashPurpose
import com.bitwarden.crypto.Kdf
import com.bitwarden.policies.OrganizationUserPolicyContext
import com.bitwarden.policies.PolicyType
import com.bitwarden.policies.PolicyView
import com.x8bit.bitwarden.data.auth.datasource.sdk.model.PasswordStrength
/**
@@ -134,4 +137,13 @@ interface AuthSdkSource {
passwordStrength: PasswordStrength,
policy: MasterPasswordPolicyOptions,
): Result<Boolean>
/**
* Applies the appropriate filters for determining what policies apply to the user.
*/
fun filterPolicies(
policies: List<PolicyView>,
organizations: List<OrganizationUserPolicyContext>,
policyType: PolicyType,
): Result<List<PolicyView>>
}

View File

@@ -15,6 +15,9 @@ import com.bitwarden.core.RegisterKeyResponse
import com.bitwarden.core.RegisterTdeKeyResponse
import com.bitwarden.crypto.HashPurpose
import com.bitwarden.crypto.Kdf
import com.bitwarden.policies.OrganizationUserPolicyContext
import com.bitwarden.policies.PolicyType
import com.bitwarden.policies.PolicyView
import com.bitwarden.sdk.AuthClient
import com.x8bit.bitwarden.data.auth.datasource.sdk.model.PasswordStrength
import com.x8bit.bitwarden.data.auth.datasource.sdk.util.toPasswordStrengthOrNull
@@ -221,4 +224,16 @@ class AuthSdkSourceImpl(
)
}
}
override fun filterPolicies(
policies: List<PolicyView>,
organizations: List<OrganizationUserPolicyContext>,
policyType: PolicyType,
): Result<List<PolicyView>> = runCatchingWithLogs {
globalClient.policies().filterByType(
policies = policies,
organizationUserPolicyContexts = organizations,
policyType = policyType,
)
}
}

View File

@@ -1,8 +1,8 @@
package com.x8bit.bitwarden.data.auth.manager
import com.bitwarden.core.data.manager.dispatcher.DispatcherManager
import com.bitwarden.network.model.PolicyTypeJson
import com.bitwarden.network.model.SyncResponseJson
import com.bitwarden.policies.PolicyType
import com.bitwarden.policies.PolicyView
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
import com.x8bit.bitwarden.data.auth.datasource.disk.model.OnboardingStatus
import com.x8bit.bitwarden.data.auth.datasource.disk.model.UserStateJson
@@ -168,8 +168,8 @@ class UserStateManagerImpl(
private fun existingPolicies(
userId: String,
policyType: PolicyTypeJson,
): List<SyncResponseJson.Policy> = policyManager.getUserPolicies(
policyType: PolicyType,
): List<PolicyView> = policyManager.getUserPolicies(
userId = userId,
type = policyType,
)

View File

@@ -11,6 +11,7 @@ import com.x8bit.bitwarden.data.auth.repository.model.AuthState
import com.x8bit.bitwarden.data.auth.repository.model.BreachCountResult
import com.x8bit.bitwarden.data.auth.repository.model.DeleteAccountResult
import com.x8bit.bitwarden.data.auth.repository.model.EmailTokenResult
import com.x8bit.bitwarden.data.auth.repository.model.GetDevicesResult
import com.x8bit.bitwarden.data.auth.repository.model.KnownDeviceResult
import com.x8bit.bitwarden.data.auth.repository.model.LeaveOrganizationResult
import com.x8bit.bitwarden.data.auth.repository.model.LoginResult
@@ -357,6 +358,11 @@ interface AuthRepository :
*/
fun setCookieCallbackResult(result: CookieCallbackResult)
/**
* Retrieves all devices registered to the current user.
*/
suspend fun getDevices(): GetDevicesResult
/**
* Get a [Boolean] indicating whether this is a known device.
*/

View File

@@ -25,9 +25,9 @@ import com.bitwarden.network.model.GetTokenResponseJson
import com.bitwarden.network.model.IdentityTokenAuthModel
import com.bitwarden.network.model.OrganizationAutoEnrollStatusResponseJson
import com.bitwarden.network.model.OrganizationKeysResponseJson
import com.bitwarden.network.model.OrganizationStatusType
import com.bitwarden.network.model.OrganizationType
import com.bitwarden.network.model.PasswordHintResponseJson
import com.bitwarden.network.model.PolicyTypeJson
import com.bitwarden.network.model.PrevalidateSsoResponseJson
import com.bitwarden.network.model.RefreshTokenResponseJson
import com.bitwarden.network.model.RegisterFinishRequestJson
@@ -38,7 +38,6 @@ import com.bitwarden.network.model.ResetPasswordRequestJson
import com.bitwarden.network.model.SendVerificationEmailRequestJson
import com.bitwarden.network.model.SendVerificationEmailResponseJson
import com.bitwarden.network.model.SetPasswordRequestJson
import com.bitwarden.network.model.SyncResponseJson
import com.bitwarden.network.model.TrustedDeviceUserDecryptionOptionsJson
import com.bitwarden.network.model.TwoFactorAuthMethod
import com.bitwarden.network.model.TwoFactorDataModel
@@ -52,6 +51,8 @@ import com.bitwarden.network.service.HaveIBeenPwnedService
import com.bitwarden.network.service.IdentityService
import com.bitwarden.network.service.OrganizationService
import com.bitwarden.network.util.isSslHandShakeError
import com.bitwarden.policies.PolicyType
import com.bitwarden.policies.PolicyView
import com.bitwarden.ui.platform.resource.BitwardenString
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
import com.x8bit.bitwarden.data.auth.datasource.disk.model.AccountJson
@@ -73,6 +74,7 @@ import com.x8bit.bitwarden.data.auth.repository.model.AuthState
import com.x8bit.bitwarden.data.auth.repository.model.BreachCountResult
import com.x8bit.bitwarden.data.auth.repository.model.DeleteAccountResult
import com.x8bit.bitwarden.data.auth.repository.model.EmailTokenResult
import com.x8bit.bitwarden.data.auth.repository.model.GetDevicesResult
import com.x8bit.bitwarden.data.auth.repository.model.KnownDeviceResult
import com.x8bit.bitwarden.data.auth.repository.model.LeaveOrganizationResult
import com.x8bit.bitwarden.data.auth.repository.model.LoginResult
@@ -107,6 +109,7 @@ import com.x8bit.bitwarden.data.auth.repository.util.activeUserIdChangesFlow
import com.x8bit.bitwarden.data.auth.repository.util.policyInformation
import com.x8bit.bitwarden.data.auth.repository.util.privateKey
import com.x8bit.bitwarden.data.auth.repository.util.toAccountCryptographicState
import com.x8bit.bitwarden.data.auth.repository.util.toDeviceInfo
import com.x8bit.bitwarden.data.auth.repository.util.toOrganizations
import com.x8bit.bitwarden.data.auth.repository.util.toRemovedPasswordUserStateJson
import com.x8bit.bitwarden.data.auth.repository.util.toSdkParams
@@ -310,6 +313,7 @@ class AuthRepositoryImpl(
override val organizations: List<Organization>
get() = activeUserId
?.let { authDiskSource.getOrganizations(it) }
?.filter { it.status == OrganizationStatusType.CONFIRMED }
.orEmpty()
.toOrganizations()
@@ -364,7 +368,7 @@ class AuthRepositoryImpl(
// When the policies for the user have been set, complete the login process.
policyManager
.getActivePoliciesFlow(type = PolicyTypeJson.MASTER_PASSWORD)
.getActivePoliciesFlow(type = PolicyType.MASTER_PASSWORD)
.onEach { policies ->
val userId = activeUserId ?: return@onEach
@@ -1461,6 +1465,20 @@ class AuthRepositoryImpl(
mutableCookieCallbackResultFlow.tryEmit(result)
}
override suspend fun getDevices(): GetDevicesResult =
devicesService
.getDevices()
.fold(
onFailure = { GetDevicesResult.Error },
onSuccess = { response ->
GetDevicesResult.Success(
devices = response.devices.map { json ->
json.toDeviceInfo(currentDeviceIdentifier = authDiskSource.uniqueAppId)
},
)
},
)
override suspend fun getIsKnownDevice(emailAddress: String): KnownDeviceResult =
devicesService
.getIsKnownDevice(
@@ -1690,7 +1708,7 @@ class AuthRepositoryImpl(
*/
private suspend fun passwordPassesPolicies(
password: String,
policies: List<SyncResponseJson.Policy>,
policies: List<PolicyView>,
): Boolean {
// If there are no master password policies that are enabled and should be
// enforced on login, the check should complete.

View File

@@ -0,0 +1,32 @@
package com.x8bit.bitwarden.data.auth.repository.model
import android.os.Parcelable
import com.bitwarden.network.model.DeviceType
import kotlinx.parcelize.Parcelize
import java.time.Instant
/**
* Domain model for a device registered to the current user.
*
* @property id The unique identifier of the device.
* @property name The name of the device.
* @property identifier The unique device install identifier of the device.
* @property type The type of the device.
* @property isTrusted Whether this device is trusted.
* @property creationDate The date and time on which this device was created.
* @property lastActivityDate The date and time of the device's last activity, if available.
* @property pendingAuthRequest The pending auth request for this device, if any.
* @property isCurrentDevice If this is the current device being used.
*/
@Parcelize
data class DeviceInfo(
val id: String,
val name: String,
val identifier: String,
val type: DeviceType,
val isTrusted: Boolean,
val creationDate: Instant,
val lastActivityDate: Instant?,
val pendingAuthRequest: DevicePendingAuthRequest?,
val isCurrentDevice: Boolean,
) : Parcelable

View File

@@ -0,0 +1,17 @@
package com.x8bit.bitwarden.data.auth.repository.model
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
import java.time.Instant
/**
* Domain model for a pending auth request associated with a device.
*
* @property id The unique identifier of the pending auth request.
* @property creationDate The date and time on which this auth request was created.
*/
@Parcelize
data class DevicePendingAuthRequest(
val id: String,
val creationDate: Instant,
) : Parcelable

View File

@@ -0,0 +1,16 @@
package com.x8bit.bitwarden.data.auth.repository.model
/**
* Models result of retrieving all devices registered to the current user.
*/
sealed class GetDevicesResult {
/**
* Contains the list of [DeviceInfo] for the current user's registered devices.
*/
data class Success(val devices: List<DeviceInfo>) : GetDevicesResult()
/**
* There was an error retrieving the devices.
*/
data object Error : GetDevicesResult()
}

View File

@@ -42,7 +42,12 @@ data class UserState(
* @property name The user's name (if applicable).
* @property avatarColorHex Hex color value for a user's avatar in the "#AARRGGBB" format.
* @property environment The [Environment] associated with the user's account.
* @property isPremium `true` if the account has a Premium membership.
* @property isPremium `true` if the account has a Premium membership from any source (personal
* subscription or organization-granted).
* @property isPremiumFromSelf `true` if the account has a personal Premium subscription. This
* is `false` for users whose only Premium access is granted by an organization they are a
* member of. Use this when behavior should be gated on the user's own subscription, not on
* organization-granted Premium.
* @property isLoggedIn `true` if the account is logged in, or `false` if it requires additional
* authentication to view their vault.
* @property isVaultUnlocked Whether the user's vault is currently unlocked.
@@ -66,6 +71,7 @@ data class UserState(
val avatarColorHex: String,
val environment: Environment,
val isPremium: Boolean,
val isPremiumFromSelf: Boolean,
val isLoggedIn: Boolean,
val isVaultUnlocked: Boolean,
val needsPasswordReset: Boolean,
@@ -113,6 +119,7 @@ data class UserState(
avatarColorHex = "".toHexColorRepresentation(),
environment = Environment.Us,
isPremium = false,
isPremiumFromSelf = false,
isLoggedIn = false,
isVaultUnlocked = false,
needsPasswordReset = false,

View File

@@ -1,5 +1,6 @@
package com.x8bit.bitwarden.data.auth.repository.util
import com.bitwarden.network.model.OrganizationStatusType
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
import com.x8bit.bitwarden.data.auth.datasource.disk.model.OnboardingStatus
import com.x8bit.bitwarden.data.auth.repository.model.UserAccountTokens
@@ -27,6 +28,7 @@ val AuthDiskSource.userOrganizationsList: List<UserOrganizations>
userId = userId,
organizations = this
.getOrganizations(userId = userId)
?.filter { it.status == OrganizationStatusType.CONFIRMED }
.orEmpty()
.toOrganizations(),
)
@@ -48,10 +50,15 @@ val AuthDiskSource.userOrganizationsListFlow: Flow<List<UserOrganizations>>
.map { (userId, _) ->
this
.getOrganizationsFlow(userId = userId)
.map {
.map { organizations ->
UserOrganizations(
userId = userId,
organizations = it.orEmpty().toOrganizations(),
organizations = organizations
?.filter {
it.status == OrganizationStatusType.CONFIRMED
}
.orEmpty()
.toOrganizations(),
)
}
},

View File

@@ -0,0 +1,26 @@
package com.x8bit.bitwarden.data.auth.repository.util
import com.bitwarden.network.model.DeviceResponseJson
import com.x8bit.bitwarden.data.auth.repository.model.DeviceInfo
import com.x8bit.bitwarden.data.auth.repository.model.DevicePendingAuthRequest
/**
* Maps the given [DeviceResponseJson] to a [DeviceInfo].
*/
fun DeviceResponseJson.toDeviceInfo(currentDeviceIdentifier: String): DeviceInfo =
DeviceInfo(
id = id,
name = name,
identifier = identifier,
type = type,
isTrusted = isTrusted,
creationDate = creationDate,
lastActivityDate = lastActivityDate,
pendingAuthRequest = devicePendingAuthRequest?.let {
DevicePendingAuthRequest(
id = it.id,
creationDate = it.creationDate,
)
},
isCurrentDevice = identifier == currentDeviceIdentifier,
)

View File

@@ -31,7 +31,8 @@ fun GetTokenResponseJson.Success.toUserState(
stamp = null,
organizationId = null,
avatarColorHex = null,
hasPremium = jwtTokenData.hasPremium,
hasPremiumPersonally = jwtTokenData.hasPremium,
hasPremiumFromOrganization = null,
forcePasswordResetReason = this.toForcePasswordResetReason(),
kdfType = this.kdfType,
kdfIterations = this.kdfIterations,

View File

@@ -1,8 +1,9 @@
package com.x8bit.bitwarden.data.auth.repository.util
import com.bitwarden.core.data.util.decodeFromStringOrNull
import com.bitwarden.network.model.PolicyTypeJson
import com.bitwarden.network.model.SyncResponseJson
import com.bitwarden.policies.PolicyType
import com.bitwarden.policies.PolicyView
import com.x8bit.bitwarden.data.auth.repository.model.Organization
import com.x8bit.bitwarden.data.auth.repository.model.PolicyInformation
import kotlinx.serialization.json.Json
@@ -39,25 +40,24 @@ fun List<SyncResponseJson.Profile.Organization>.toOrganizations(): List<Organiza
this.mapNotNull { it.toOrganization() }
/**
* Convert the JSON data of the [SyncResponseJson.Policy] object into [PolicyInformation] data.
* Convert the JSON data of the [PolicyView] object into [PolicyInformation] data.
*/
val SyncResponseJson.Policy.policyInformation: PolicyInformation?
get() = data?.toString()?.let {
val PolicyView.policyInformation: PolicyInformation?
get() = data?.let {
when (type) {
PolicyTypeJson.MASTER_PASSWORD -> {
PolicyType.MASTER_PASSWORD -> {
JSON.decodeFromStringOrNull<PolicyInformation.MasterPassword>(it)
}
PolicyTypeJson.PASSWORD_GENERATOR -> {
PolicyType.PASSWORD_GENERATOR -> {
JSON.decodeFromStringOrNull<PolicyInformation.PasswordGenerator>(it)
}
PolicyTypeJson.MAXIMUM_VAULT_TIMEOUT -> {
PolicyType.MAXIMUM_VAULT_TIMEOUT -> {
JSON.decodeFromStringOrNull<PolicyInformation.VaultTimeout>(it)
}
PolicyTypeJson.SEND_OPTIONS -> {
PolicyType.SEND_OPTIONS -> {
JSON.decodeFromStringOrNull<PolicyInformation.SendOptions>(it)
}

View File

@@ -5,9 +5,10 @@ import com.bitwarden.data.repository.util.toEnvironmentUrlsOrDefault
import com.bitwarden.network.model.KdfTypeJson
import com.bitwarden.network.model.MasterPasswordUnlockDataJson
import com.bitwarden.network.model.OrganizationType
import com.bitwarden.network.model.PolicyTypeJson
import com.bitwarden.network.model.SyncResponseJson
import com.bitwarden.network.model.UserDecryptionOptionsJson
import com.bitwarden.policies.PolicyType
import com.bitwarden.policies.PolicyView
import com.bitwarden.ui.platform.base.util.toHexColorRepresentation
import com.x8bit.bitwarden.data.auth.datasource.disk.model.OnboardingStatus
import com.x8bit.bitwarden.data.auth.datasource.disk.model.UserStateJson
@@ -83,7 +84,8 @@ fun UserStateJson.toUpdatedUserStateJson(
.copy(
avatarColorHex = syncProfile.avatarColor,
stamp = syncProfile.securityStamp,
hasPremium = syncProfile.isPremium || syncProfile.isPremiumFromOrganization,
hasPremiumPersonally = syncProfile.isPremium,
hasPremiumFromOrganization = syncProfile.isPremiumFromOrganization,
isTwoFactorEnabled = syncProfile.isTwoFactorEnabled,
creationDate = syncProfile.creationDate,
userDecryptionOptions = userDecryptionOptions,
@@ -191,7 +193,7 @@ fun UserStateJson.toUserState(
isBiometricsEnabledProvider: (userId: String) -> Boolean,
vaultUnlockTypeProvider: (userId: String) -> VaultUnlockType,
isDeviceTrustedProvider: (userId: String) -> Boolean,
getUserPolicies: (userId: String, policy: PolicyTypeJson) -> List<SyncResponseJson.Policy>,
getUserPolicies: (userId: String, policy: PolicyType) -> List<PolicyView>,
): UserState =
UserState(
activeUserId = this.activeUserId,
@@ -234,15 +236,15 @@ fun UserStateJson.toUserState(
val hasPersonalOwnershipRestrictedOrg = getUserPolicies(
userId,
PolicyTypeJson.PERSONAL_OWNERSHIP,
PolicyType.ORGANIZATION_DATA_OWNERSHIP,
)
.any { it.isEnabled }
.any { it.enabled }
val hasPersonalVaultExportRestrictedOrg = getUserPolicies(
userId,
PolicyTypeJson.DISABLE_PERSONAL_VAULT_EXPORT,
PolicyType.DISABLE_PERSONAL_VAULT_EXPORT,
)
.any { it.isEnabled }
.any { it.enabled }
UserState.Account(
userId = userId,
@@ -253,7 +255,9 @@ fun UserStateJson.toUserState(
.settings
.environmentUrlData
.toEnvironmentUrlsOrDefault(),
isPremium = profile.hasPremium == true,
isPremium = profile.hasPremiumPersonally == true ||
profile.hasPremiumFromOrganization == true,
isPremiumFromSelf = profile.hasPremiumPersonally == true,
isLoggedIn = userAccountTokens
.find { it.userId == userId }
?.isLoggedIn == true,

View File

@@ -0,0 +1,44 @@
package com.x8bit.bitwarden.data.autofill.datasource.disk
import com.x8bit.bitwarden.data.autofill.model.FillAssistRules
/**
* Disk source for persisting fill-assist targeting rules per server.
*
* All operations are scoped by [serverUrl] (the fill-assist CDN base URL provided by the server
* config), so multiple accounts on the same server share one cached copy of the rules while
* accounts on different servers remain independent.
*/
interface FillAssistDiskSource {
/**
* Returns the cached [FillAssistRules] for [serverUrl], or null if none are stored.
*/
fun getFillAssistRules(serverUrl: String): FillAssistRules?
/**
* Stores [rules] for [serverUrl], or removes the entry when [rules] is null.
*/
fun storeFillAssistRules(serverUrl: String, rules: FillAssistRules?)
/**
* Returns the last known content hash (CID) for [serverUrl], or null if none is stored.
*/
fun getLastKnownCid(serverUrl: String): String?
/**
* Stores [cid] for [serverUrl], or removes the entry when [cid] is null.
*/
fun storeLastKnownCid(serverUrl: String, cid: String?)
/**
* Returns the epoch-millisecond timestamp of the last successful fetch for [serverUrl],
* or null if never fetched.
*/
fun getLastFetchTimestamp(serverUrl: String): Long?
/**
* Stores [timestamp] for [serverUrl], or removes the entry when [timestamp] is null.
*/
fun storeLastFetchTimestamp(serverUrl: String, timestamp: Long?)
}

View File

@@ -0,0 +1,71 @@
package com.x8bit.bitwarden.data.autofill.datasource.disk
import android.content.SharedPreferences
import com.bitwarden.core.data.util.decodeFromStringOrNull
import com.bitwarden.data.datasource.disk.BaseDiskSource
import com.x8bit.bitwarden.data.autofill.model.FillAssistRules
import kotlinx.serialization.json.Json
// Bump this constant in two cases:
// 1. The parsing logic changes in a way that invalidates previously cached results.
// 2. EXPECTED_SCHEMA_MAJOR in FillAssistManagerImpl is updated to support a new schema major.
// Without bumping this, the staleness check would skip re-downloading data that was previously
// rejected for an unsupported schema — meaning the app would never pick up the new rules.
// On the next app launch after a bump, all stored fill-assist data is cleared and re-downloaded.
private const val CURRENT_CACHE_VERSION = 0
private const val FILL_ASSIST_CACHE_VERSION_KEY = "fillAssistCacheVersion"
private const val FILL_ASSIST_RULES_KEY = "fillAssistRules"
private const val FILL_ASSIST_CID_KEY = "fillAssistLastCid"
private const val FILL_ASSIST_TIMESTAMP_KEY = "fillAssistLastFetchTimestamp"
/**
* Primary implementation of [FillAssistDiskSource].
*/
class FillAssistDiskSourceImpl(
sharedPreferences: SharedPreferences,
private val json: Json,
) : BaseDiskSource(sharedPreferences),
FillAssistDiskSource {
init {
performMigrationIfNeeded()
}
override fun getFillAssistRules(serverUrl: String): FillAssistRules? =
getString(FILL_ASSIST_RULES_KEY.appendIdentifier(serverUrl))
?.let { json.decodeFromStringOrNull(it) }
override fun storeFillAssistRules(serverUrl: String, rules: FillAssistRules?) {
putString(
FILL_ASSIST_RULES_KEY.appendIdentifier(serverUrl),
rules?.let { json.encodeToString(it) },
)
}
override fun getLastKnownCid(serverUrl: String): String? =
getString(FILL_ASSIST_CID_KEY.appendIdentifier(serverUrl))
override fun storeLastKnownCid(serverUrl: String, cid: String?) {
putString(FILL_ASSIST_CID_KEY.appendIdentifier(serverUrl), cid)
}
override fun getLastFetchTimestamp(serverUrl: String): Long? =
getLong(FILL_ASSIST_TIMESTAMP_KEY.appendIdentifier(serverUrl))
override fun storeLastFetchTimestamp(serverUrl: String, timestamp: Long?) {
putLong(FILL_ASSIST_TIMESTAMP_KEY.appendIdentifier(serverUrl), timestamp)
}
private fun performMigrationIfNeeded() {
if (getInt(FILL_ASSIST_CACHE_VERSION_KEY) == CURRENT_CACHE_VERSION) return
clearAllData()
}
private fun clearAllData() {
removeWithPrefix("${FILL_ASSIST_RULES_KEY}_")
removeWithPrefix("${FILL_ASSIST_CID_KEY}_")
removeWithPrefix("${FILL_ASSIST_TIMESTAMP_KEY}_")
putInt(FILL_ASSIST_CACHE_VERSION_KEY, CURRENT_CACHE_VERSION)
}
}

View File

@@ -0,0 +1,60 @@
package com.x8bit.bitwarden.data.autofill.di
import android.content.SharedPreferences
import com.bitwarden.core.data.manager.dispatcher.DispatcherManager
import com.bitwarden.data.datasource.disk.di.UnencryptedPreferences
import com.bitwarden.data.repository.ServerConfigRepository
import com.bitwarden.network.service.FillAssistService
import com.x8bit.bitwarden.data.autofill.datasource.disk.FillAssistDiskSource
import com.x8bit.bitwarden.data.autofill.datasource.disk.FillAssistDiskSourceImpl
import com.x8bit.bitwarden.data.autofill.manager.FillAssistManager
import com.x8bit.bitwarden.data.autofill.manager.FillAssistManagerImpl
import com.x8bit.bitwarden.data.platform.datasource.disk.EnvironmentDiskSource
import com.x8bit.bitwarden.data.platform.manager.FeatureFlagManager
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
import dagger.hilt.components.SingletonComponent
import java.time.Clock
import kotlinx.serialization.json.Json
import javax.inject.Singleton
/**
* Provides fill-assist dependencies.
*/
@Module
@InstallIn(SingletonComponent::class)
object FillAssistModule {
@Provides
@Singleton
fun providesFillAssistDiskSource(
@UnencryptedPreferences sharedPreferences: SharedPreferences,
json: Json,
): FillAssistDiskSource =
FillAssistDiskSourceImpl(
sharedPreferences = sharedPreferences,
json = json,
)
@Provides
@Singleton
fun providesFillAssistManager(
fillAssistService: FillAssistService,
fillAssistDiskSource: FillAssistDiskSource,
featureFlagManager: FeatureFlagManager,
serverConfigRepository: ServerConfigRepository,
environmentDiskSource: EnvironmentDiskSource,
clock: Clock,
dispatcherManager: DispatcherManager,
): FillAssistManager =
FillAssistManagerImpl(
fillAssistService = fillAssistService,
fillAssistDiskSource = fillAssistDiskSource,
featureFlagManager = featureFlagManager,
serverConfigRepository = serverConfigRepository,
environmentDiskSource = environmentDiskSource,
clock = clock,
dispatcherManager = dispatcherManager,
)
}

View File

@@ -0,0 +1,23 @@
package com.x8bit.bitwarden.data.autofill.manager
import com.x8bit.bitwarden.data.autofill.model.FillAssistRules
/**
* Manages fetching and caching fill-assist targeting rules.
*
* Rules are scoped per server (the fill-assist CDN URL from server config), so multiple accounts
* on the same server share one cached copy.
*/
interface FillAssistManager {
/**
* Triggers a background sync if no sync is currently running. The sync fetches and persists
* fill-assist rules when the feature flag is enabled and cached data is stale.
*/
fun syncIfNecessary()
/**
* Returns the last successfully cached [FillAssistRules] for the active server, or null if
* none exist.
*/
fun getFillAssistRules(): FillAssistRules?
}

View File

@@ -0,0 +1,237 @@
package com.x8bit.bitwarden.data.autofill.manager
import com.bitwarden.core.data.manager.dispatcher.DispatcherManager
import com.bitwarden.core.data.manager.model.FlagKey
import com.bitwarden.data.repository.ServerConfigRepository
import com.bitwarden.network.model.FillAssistFormsJson
import com.bitwarden.network.service.FillAssistService
import com.x8bit.bitwarden.data.autofill.datasource.disk.FillAssistDiskSource
import com.x8bit.bitwarden.data.autofill.model.FillAssistRules
import com.x8bit.bitwarden.data.autofill.model.FillAssistRules.SelectorClause
import com.x8bit.bitwarden.data.platform.datasource.disk.EnvironmentDiskSource
import com.x8bit.bitwarden.data.platform.manager.FeatureFlagManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.filterNotNull
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlinx.serialization.json.JsonArray
import kotlinx.serialization.json.JsonElement
import kotlinx.serialization.json.JsonPrimitive
import timber.log.Timber
import java.time.Clock
private const val CURRENT_FORMS_VERSION = "v1"
private const val EXPECTED_SCHEMA_MAJOR = "1"
/** Re-fetch interval in milliseconds (6 hours, matching the browser implementation). */
private const val UPDATE_INTERVAL_MS = 6 * 60 * 60 * 1000L
// Matches [attr='value'] and [attr="value"] attribute selectors.
private val ATTRIBUTE_REGEX = Regex("""\[([a-zA-Z\-]+)=['"](.*?)['"]]""")
// Matches the CSS #id shorthand (e.g. "input#oid", "select#state").
// Used as a fallback when [id='value'] is absent.
private val ID_SHORTHAND_REGEX = Regex("""#([^.\[#\s]+)""")
// Extracts the leading tag name from a selector (e.g. "input", "select", "form").
private val TAG_REGEX = Regex("""^([a-zA-Z][a-zA-Z0-9]*)""")
/**
* Primary implementation of [FillAssistManager].
*/
@Suppress("LongParameterList")
class FillAssistManagerImpl(
private val fillAssistService: FillAssistService,
private val fillAssistDiskSource: FillAssistDiskSource,
private val featureFlagManager: FeatureFlagManager,
private val serverConfigRepository: ServerConfigRepository,
private val environmentDiskSource: EnvironmentDiskSource,
private val clock: Clock,
dispatcherManager: DispatcherManager,
) : FillAssistManager {
private val unconfinedScope = CoroutineScope(dispatcherManager.unconfined)
private val ioScope = CoroutineScope(dispatcherManager.io)
private var syncJob: Job = Job().apply { complete() }
init {
serverConfigRepository.serverConfigStateFlow
.onEach { config ->
environmentDiskSource.fillAssistRulesUrl =
config?.serverData?.environment?.fillAssistRulesUrl
}
.filterNotNull()
.onEach { syncIfNecessary() }
.launchIn(unconfinedScope)
}
override fun syncIfNecessary() {
if (!featureFlagManager.getFeatureFlag(FlagKey.FillAssistTargetingRules)) return
val serverUrl = serverConfigRepository
.serverConfigStateFlow
.value
?.serverData
?.environment
?.fillAssistRulesUrl
?: return
val lastFetch = fillAssistDiskSource.getLastFetchTimestamp(serverUrl) ?: 0L
if (clock.millis() - lastFetch < UPDATE_INTERVAL_MS) return
if (!syncJob.isCompleted) return
syncJob = ioScope.launch { sync(serverUrl) }
}
private suspend fun sync(serverUrl: String) = runCatching {
val manifest = fillAssistService.getManifest().getOrThrow()
val versionEntry = manifest.maps.forms[CURRENT_FORMS_VERSION]
?: error("Version $CURRENT_FORMS_VERSION not found in manifest")
if (versionEntry.deprecated == true) {
Timber.w("Fill-assist forms $CURRENT_FORMS_VERSION is deprecated")
}
if (versionEntry.cid == fillAssistDiskSource.getLastKnownCid(serverUrl)) {
fillAssistDiskSource.storeLastFetchTimestamp(
serverUrl = serverUrl,
timestamp = clock.millis(),
)
return@runCatching
}
val forms = fillAssistService
.getForms(filename = versionEntry.filename)
.getOrThrow()
val schemaMajor = forms.schemaVersion.substringBefore('.')
if (schemaMajor != EXPECTED_SCHEMA_MAJOR) {
Timber.w("Unsupported fill-assist schema version: ${forms.schemaVersion}")
fillAssistDiskSource.storeLastFetchTimestamp(
serverUrl = serverUrl,
timestamp = clock.millis(),
)
return@runCatching
}
val rules = parseForms(forms)
fillAssistDiskSource.storeFillAssistRules(serverUrl = serverUrl, rules = rules)
fillAssistDiskSource.storeLastKnownCid(serverUrl = serverUrl, cid = versionEntry.cid)
fillAssistDiskSource.storeLastFetchTimestamp(
serverUrl = serverUrl,
timestamp = clock.millis(),
)
}.also { result ->
result.onFailure { Timber.w(it, "Fill-assist sync failed") }
}
override fun getFillAssistRules(): FillAssistRules? {
val serverUrl = serverConfigRepository
.serverConfigStateFlow
.value
?.serverData
?.environment
?.fillAssistRulesUrl
?: return null
return fillAssistDiskSource.getFillAssistRules(serverUrl = serverUrl)
}
}
// region CSS parser
private fun parseForms(forms: FillAssistFormsJson): FillAssistRules {
val hostRules = forms.hosts
.mapNotNull { (hostname, hostEntry) -> hostEntry?.let { hostname to parseHostEntry(it) } }
.filter { (_, rules) -> rules.isNotEmpty() }
.toMap()
return FillAssistRules(hostRules = hostRules)
}
private fun parseHostEntry(
hostEntry: FillAssistFormsJson.HostEntryJson,
): List<FillAssistRules.HostRule> {
val allForms = buildList {
addAll(hostEntry.forms.orEmpty())
hostEntry.pathnames?.values?.filterNotNull()?.forEach { addAll(it.forms) }
}.distinct()
return buildFieldsByCategory(allForms).map { (category, fields) ->
FillAssistRules.HostRule(
category = category,
fields = fields.mapValues { (_, selectors) -> selectors.distinct() },
)
}
}
private fun buildFieldsByCategory(
forms: List<FillAssistFormsJson.FormJson>,
): Map<String, MutableMap<String, MutableList<SelectorClause>>> {
val result = mutableMapOf<String, MutableMap<String, MutableList<SelectorClause>>>()
forms.forEach { form ->
val parsedFields = form.fields
.mapValues { (_, elem) -> parseCompositeSelectorArray(elem) }
.filterValues { it.isNotEmpty() }
.takeIf { it.isNotEmpty() } ?: return@forEach
val categoryFields = result.getOrPut(form.category) { mutableMapOf() }
parsedFields.forEach { (fieldKey, selectors) ->
categoryFields.getOrPut(fieldKey) { mutableListOf() }.addAll(selectors)
}
}
return result
}
private fun parseCompositeSelectorArray(element: JsonElement): List<SelectorClause> {
if (element !is JsonArray) return emptyList()
val result = mutableListOf<SelectorClause>()
for (item in element) {
when (item) {
is JsonPrimitive -> parseSingleSelector(item.content)?.let { result.add(it) }
is JsonArray -> item
.filterIsInstance<JsonPrimitive>()
.mapNotNull { parseSingleSelector(it.content) }
.forEach { result.add(it) }
else -> Unit
}
}
return result
}
internal fun parseSingleSelector(selector: String): SelectorClause? {
// For shadow DOM / iframe selectors (>>>), extract the last segment — the actual target
// element. Android's autofill framework may expose these elements via htmlInfo when they
// are reachable (e.g. open shadow roots), so we parse their attributes for matching.
val effective = if (selector.contains(">>>")) {
selector.substringAfterLast(">>>").trim()
} else {
selector
}
if (effective.trimStart().startsWith(".")) return null
val tag = TAG_REGEX.find(effective)?.groupValues?.get(1)
var id: String? = null
var name: String? = null
var type: String? = null
var role: String? = null
ATTRIBUTE_REGEX.findAll(effective).forEach { match ->
val attrName = match.groupValues[1]
val attrValue = match.groupValues[2]
when (attrName) {
"id" -> id = attrValue
"name" -> name = attrValue
"type" -> type = attrValue
"role" -> role = attrValue
}
}
// Fallback: extract id from #shorthand (e.g. input#oid) when not present as [id='...'].
if (id == null) {
id = ID_SHORTHAND_REGEX.find(effective)?.groupValues?.get(1)
}
return SelectorClause(tag = tag, id = id, name = name, type = type, role = role)
}
// endregion

View File

@@ -0,0 +1,47 @@
package com.x8bit.bitwarden.data.autofill.model
import kotlinx.serialization.Serializable
/**
* Parsed, storage-ready representation of fill-assist targeting rules for all known hosts.
*
* @property hostRules Map of hostname (with optional port) to a list of [HostRule] entries.
* Multiple [HostRule] entries per host are possible when different pages define different forms.
*/
@Serializable
data class FillAssistRules(
val hostRules: Map<String, List<HostRule>>,
) {
/**
* Describes one parsed form for a host. Combines host-level and pathname-level forms into a
* single pooled representation so the consumer does not need to know the current URL path.
*
* @property category The form's purpose category (e.g. "account-login", "payment-card").
* @property fields Map of field key (e.g. "username", "password") to a list of
* [SelectorClause] alternatives. The first clause that matches a view node is used.
*/
@Serializable
data class HostRule(
val category: String,
val fields: Map<String, List<SelectorClause>>,
)
/**
* A single parsed CSS selector expressing HTML attribute constraints for matching a view node
* via [android.view.ViewStructure.HtmlInfo]. All non-null fields are AND constraints.
*
* @property tag The HTML tag name (e.g. "input", "select").
* @property id The value of the element's [id] attribute.
* @property name The value of the element's [name] attribute.
* @property type The value of the element's [type] attribute (e.g. "password", "text").
* @property role The value of the element's [role] attribute.
*/
@Serializable
data class SelectorClause(
val tag: String?,
val id: String?,
val name: String?,
val type: String?,
val role: String?,
)
}

View File

@@ -6,7 +6,7 @@ import android.service.autofill.FillRequest
import android.service.autofill.SaveCallback
import android.service.autofill.SaveRequest
import com.bitwarden.core.data.manager.dispatcher.DispatcherManager
import com.bitwarden.network.model.PolicyTypeJson
import com.bitwarden.policies.PolicyType
import com.x8bit.bitwarden.data.autofill.builder.FillResponseBuilder
import com.x8bit.bitwarden.data.autofill.builder.FilledDataBuilder
import com.x8bit.bitwarden.data.autofill.builder.SaveInfoBuilder
@@ -80,7 +80,7 @@ class AutofillProcessorImpl(
return
}
if (policyManager.getActivePolicies(PolicyTypeJson.PERSONAL_OWNERSHIP).any()) {
if (policyManager.getActivePolicies(PolicyType.ORGANIZATION_DATA_OWNERSHIP).any()) {
saveCallback.onSuccess()
return
}

View File

@@ -1,6 +1,6 @@
package com.x8bit.bitwarden.data.autofill.provider
import com.bitwarden.network.model.PolicyTypeJson
import com.bitwarden.policies.PolicyType
import com.bitwarden.vault.CipherListView
import com.bitwarden.vault.CipherListViewType
import com.bitwarden.vault.CipherRepromptType
@@ -58,7 +58,7 @@ class AutofillCipherProviderImpl(
override suspend fun getCardAutofillCiphers(): List<AutofillCipher.Card> {
val cipherListViews = getUnlockedCipherListViewsOrNull() ?: return emptyList()
val organizationIdsWithCardTypeRestrictions = policyManager
.getActivePolicies(PolicyTypeJson.RESTRICT_ITEM_TYPES)
.getActivePolicies(PolicyType.RESTRICTED_ITEM_TYPES)
.map { it.organizationId }
return cipherListViews
.mapNotNull { cipherListView ->

View File

@@ -4,7 +4,6 @@ import android.content.Context
import com.bitwarden.core.data.manager.dispatcher.DispatcherManager
import com.bitwarden.network.service.BillingService
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
import com.x8bit.bitwarden.data.auth.repository.AuthRepository
import com.x8bit.bitwarden.data.billing.manager.PlayBillingManager
import com.x8bit.bitwarden.data.billing.manager.PlayBillingManagerImpl
import com.x8bit.bitwarden.data.billing.manager.PremiumStateManager
@@ -14,6 +13,7 @@ import com.x8bit.bitwarden.data.billing.repository.BillingRepositoryImpl
import com.x8bit.bitwarden.data.platform.datasource.disk.SettingsDiskSource
import com.x8bit.bitwarden.data.platform.manager.FeatureFlagManager
import com.x8bit.bitwarden.data.platform.manager.PushManager
import com.x8bit.bitwarden.data.platform.repository.EnvironmentRepository
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
import dagger.Module
import dagger.Provides
@@ -54,21 +54,21 @@ object BillingModule {
@Singleton
fun providePremiumStateManager(
authDiskSource: AuthDiskSource,
authRepository: AuthRepository,
billingRepository: BillingRepository,
settingsDiskSource: SettingsDiskSource,
vaultRepository: VaultRepository,
featureFlagManager: FeatureFlagManager,
environmentRepository: EnvironmentRepository,
pushManager: PushManager,
clock: Clock,
dispatcherManager: DispatcherManager,
): PremiumStateManager = PremiumStateManagerImpl(
authDiskSource = authDiskSource,
authRepository = authRepository,
billingRepository = billingRepository,
settingsDiskSource = settingsDiskSource,
vaultRepository = vaultRepository,
featureFlagManager = featureFlagManager,
environmentRepository = environmentRepository,
pushManager = pushManager,
clock = clock,
dispatcherManager = dispatcherManager,

View File

@@ -1,5 +1,7 @@
package com.x8bit.bitwarden.data.billing.manager
import com.x8bit.bitwarden.data.billing.repository.model.SubscriptionStatusState
import com.x8bit.bitwarden.data.billing.repository.model.UpgradeLifecycleState
import kotlinx.coroutines.flow.StateFlow
/**
@@ -26,6 +28,34 @@ interface PremiumStateManager {
*/
val isUpgradedToPremiumCardEligibleFlow: StateFlow<Boolean>
/**
* Emits `true` when the active user is eligible to see the Plan row in Settings, or `false`
* otherwise.
*/
val isPlanRowEligibleFlow: StateFlow<Boolean>
/**
* Emits the active user's latest [SubscriptionStatusState].
*/
val subscriptionStatusStateFlow: StateFlow<SubscriptionStatusState>
/**
* Emits the active user's current [UpgradeLifecycleState].
*/
val upgradeLifecycleStateFlow: StateFlow<UpgradeLifecycleState>
/**
* Emits whether the current state should be treated as self-hosted for premium upgrade
* gating. Reactive equivalent of [isSelfHosted].
*/
val isSelfHostedFlow: StateFlow<Boolean>
/**
* `true` when the current state should be treated as self-hosted for premium upgrade
* gating, or `false` otherwise.
*/
val isSelfHosted: Boolean
/**
* Returns `true` when the in-app upgrade flow is available, or `false` otherwise.
*/
@@ -42,4 +72,10 @@ interface PremiumStateManager {
* never re-appears for that user.
*/
fun dismissUpgradedToPremiumCard()
/**
* Marks the active user as having a Premium upgrade in flight (Stripe checkout completed
* but the server has not yet flipped `isPremium`).
*/
fun markPremiumUpgradePending(userId: String)
}

View File

@@ -3,27 +3,37 @@ package com.x8bit.bitwarden.data.billing.manager
import com.bitwarden.core.data.manager.dispatcher.DispatcherManager
import com.bitwarden.core.data.manager.model.FlagKey
import com.bitwarden.core.data.repository.model.DataState
import com.bitwarden.data.repository.model.Environment
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
import com.x8bit.bitwarden.data.auth.repository.AuthRepository
import com.x8bit.bitwarden.data.auth.datasource.disk.model.UserStateJson
import com.x8bit.bitwarden.data.auth.repository.util.activeUserIdChangesFlow
import com.x8bit.bitwarden.data.billing.repository.BillingRepository
import com.x8bit.bitwarden.data.billing.repository.model.PremiumSubscriptionStatus
import com.x8bit.bitwarden.data.billing.repository.model.SubscriptionResult
import com.x8bit.bitwarden.data.billing.repository.model.SubscriptionStatusState
import com.x8bit.bitwarden.data.billing.repository.model.UpgradeLifecycleState
import com.x8bit.bitwarden.data.platform.datasource.disk.SettingsDiskSource
import com.x8bit.bitwarden.data.platform.manager.FeatureFlagManager
import com.x8bit.bitwarden.data.platform.manager.PushManager
import com.x8bit.bitwarden.data.platform.repository.EnvironmentRepository
import com.x8bit.bitwarden.data.platform.util.isActive
import com.x8bit.bitwarden.data.platform.util.scanPairs
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
import com.x8bit.bitwarden.data.vault.repository.model.VaultData
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.stateIn
import java.time.Clock
@@ -33,14 +43,14 @@ import java.time.Instant
/**
* Default implementation of [PremiumStateManager].
*/
@Suppress("LongParameterList")
@Suppress("LongParameterList", "LargeClass")
class PremiumStateManagerImpl(
private val authDiskSource: AuthDiskSource,
authRepository: AuthRepository,
private val billingRepository: BillingRepository,
private val settingsDiskSource: SettingsDiskSource,
vaultRepository: VaultRepository,
private val featureFlagManager: FeatureFlagManager,
private val environmentRepository: EnvironmentRepository,
pushManager: PushManager,
private val clock: Clock,
dispatcherManager: DispatcherManager,
@@ -48,10 +58,74 @@ class PremiumStateManagerImpl(
private val unconfinedScope = CoroutineScope(dispatcherManager.unconfined)
private val subscriptionRefreshTriggerFlow =
MutableSharedFlow<Unit>(replay = 0, extraBufferCapacity = 1)
/**
* Keyed on the active user's id so a logout/switch retriggers the fetch. Runs whenever
* there is an active user regardless of `Account.isPremium` — users whose Stripe
* subscription has moved to a terminal state need their substate surfaced even though
* the server reports them as non-premium. Emits [SubscriptionStatusState.NoSubscription]
* when there is no active user or when the server returns 404 (no `GatewaySubscriptionId`,
* i.e. genuinely free users).
*/
@OptIn(ExperimentalCoroutinesApi::class)
override val subscriptionStatusStateFlow: StateFlow<SubscriptionStatusState> =
authDiskSource
.activeUserIdChangesFlow
.flatMapLatest { userId ->
if (userId != null) {
fetchSubscriptionStatusFlow()
} else {
flowOf(SubscriptionStatusState.NoSubscription)
}
}
.stateIn(
scope = unconfinedScope,
started = SharingStarted.Eagerly,
initialValue = SubscriptionStatusState.Loading,
)
@OptIn(ExperimentalCoroutinesApi::class)
override val upgradeLifecycleStateFlow: StateFlow<UpgradeLifecycleState> =
combine(
authDiskSource.userStateFlow,
subscriptionStatusStateFlow,
authDiskSource.activeUserIdChangesFlow
.flatMapLatest { userId ->
userId
?.let { id ->
settingsDiskSource
.getPremiumUpgradePendingFlow(id)
.map { it ?: false }
}
?: flowOf(false)
},
) { userState, subscriptionStatus, isPending ->
deriveLifecycleState(
userState = userState,
subscriptionStatus = subscriptionStatus,
isPending = isPending,
)
}
.distinctUntilChanged()
.stateIn(
scope = unconfinedScope,
started = SharingStarted.Eagerly,
initialValue = deriveLifecycleState(
userState = authDiskSource.userState,
subscriptionStatus = subscriptionStatusStateFlow.value,
isPending = authDiskSource.userState
?.activeUserId
?.let { settingsDiskSource.getPremiumUpgradePending(userId = it) }
?: false,
),
)
@OptIn(ExperimentalCoroutinesApi::class)
override val isPremiumUpgradeBannerEligibleFlow: StateFlow<Boolean> =
combine(
authRepository.userStateFlow,
authDiskSource.userStateFlow,
billingRepository.isInAppBillingSupportedFlow,
featureFlagManager.getFeatureFlagFlow(FlagKey.MobilePremiumUpgrade),
authDiskSource.activeUserIdChangesFlow
@@ -72,21 +146,71 @@ class PremiumStateManagerImpl(
isDismissed,
vaultDataState,
->
val activeAccount = userState?.activeAccount
?: return@combine false
val isPremium = activeAccount.isPremium
val isAccountOldEnough = activeAccount.creationDate.isOlderThanDays(
days = PREMIUM_UPGRADE_MINIMUM_ACCOUNT_AGE_DAYS,
clock = clock,
BannerInputs(
userState = userState,
isInAppBillingSupported = isInAppBillingSupported,
featureFlagEnabled = featureFlagEnabled,
isDismissed = isDismissed,
vaultDataState = vaultDataState,
)
val itemCount = vaultDataState.activeVaultItemCount()
}
.combine(upgradeLifecycleStateFlow) { inputs, lifecycle ->
val profile = inputs.userState?.activeAccount?.profile
?: return@combine false
val isAccountOldEnough = profile.creationDate.isOlderThanDays(
days = PREMIUM_UPGRADE_MINIMUM_ACCOUNT_AGE_DAYS,
clock = clock,
)
val itemCount = inputs.vaultDataState.activeVaultItemCount()
val lifecycleAllowsBanner = lifecycle is UpgradeLifecycleState.Free ||
(
lifecycle is UpgradeLifecycleState.Premium &&
lifecycle.subscriptionStatus.isInTroubleState()
)
!isPremium &&
isInAppBillingSupported &&
featureFlagEnabled &&
!isDismissed &&
isAccountOldEnough &&
itemCount >= PREMIUM_UPGRADE_MINIMUM_VAULT_ITEMS
lifecycleAllowsBanner &&
inputs.isInAppBillingSupported &&
inputs.featureFlagEnabled &&
!inputs.isDismissed &&
isAccountOldEnough &&
itemCount >= PREMIUM_UPGRADE_MINIMUM_VAULT_ITEMS
}
.stateIn(
scope = unconfinedScope,
started = SharingStarted.Eagerly,
initialValue = false,
)
override val isSelfHostedFlow: StateFlow<Boolean> =
combine(
environmentRepository.environmentStateFlow,
featureFlagManager.getFeatureFlagFlow(FlagKey.DebugDisableSelfHostPremiumCheck),
) { environment, isDebugBypassEnabled ->
environment is Environment.SelfHosted && !isDebugBypassEnabled
}
.stateIn(
scope = unconfinedScope,
started = SharingStarted.Eagerly,
initialValue = environmentRepository.environment is Environment.SelfHosted &&
!featureFlagManager.getFeatureFlag(FlagKey.DebugDisableSelfHostPremiumCheck),
)
/**
* Eligibility is keyed on the user holding personal Premium (or being eligible to purchase
* it). Organization-granted Premium does not surface the Plan row, since the user has no
* personal subscription to manage.
*/
override val isPlanRowEligibleFlow: StateFlow<Boolean> =
combine(
authDiskSource.userStateFlow,
featureFlagManager.getFeatureFlagFlow(FlagKey.MobilePremiumUpgrade),
) { userState, featureFlagEnabled ->
val profile = userState?.activeAccount?.profile ?: return@combine false
val hasPremium = profile.hasPremiumPersonally == true ||
profile.hasPremiumFromOrganization == true
val isPremiumFromSelf = profile.hasPremiumPersonally == true
val isOrgOnlyPremium = hasPremium && !isPremiumFromSelf
featureFlagEnabled && !isOrgOnlyPremium
}
.stateIn(
scope = unconfinedScope,
@@ -94,6 +218,12 @@ class PremiumStateManagerImpl(
initialValue = false,
)
/**
* The card surfaces only while the active user holds personal Premium. This guards against
* non-personal upgrade signals (e.g., the debug menu trigger or a stray
* `PREMIUM_STATUS_CHANGED` push for an organization grant) marking the card pending for users
* with no personal subscription to celebrate.
*/
@OptIn(ExperimentalCoroutinesApi::class)
override val isUpgradedToPremiumCardEligibleFlow: StateFlow<Boolean> =
authDiskSource
@@ -109,7 +239,14 @@ class PremiumStateManagerImpl(
settingsDiskSource
.getUpgradedToPremiumCardConsumedFlow(userId)
.map { it ?: false },
) { isPending, isConsumed -> isPending && !isConsumed }
authDiskSource
.userStateFlow
.map {
it?.activeAccount?.profile?.hasPremiumPersonally == true
},
) { isPending, isConsumed, isPremiumFromSelf ->
isPending && !isConsumed && isPremiumFromSelf
}
}
}
.distinctUntilChanged()
@@ -128,33 +265,41 @@ class PremiumStateManagerImpl(
if (data.isPremium) {
markUpgradedToPremiumCardPending(userId = data.userId)
}
// Push always re-fetches: a status push can mean either "newly premium" or
// "subscription moved into a trouble state" (e.g. past_due → unpaid).
subscriptionRefreshTriggerFlow.tryEmit(Unit)
}
.launchIn(unconfinedScope)
// Sync-delta detection: observe the active user's premium flag transitioning false → true
// (e.g., F-Droid users without push support). NOTE: UserState.Account.isPremium is
// derived from `hasPremium = isPremium || isPremiumFromOrganization` so this path may
// also fire for organization-granted premium. The push path (above) is personal-only and
// takes precedence on flavors that support it.
authRepository
// Sync-delta detection: observe the active user's personal premium flag transitioning
// false → true (e.g., F-Droid users without push support). Keyed on
// `hasPremiumPersonally` so that organization-granted premium does not trigger the
// personal-upgrade card.
authDiskSource
.userStateFlow
.map { state ->
state?.activeAccount?.let { it.userId to it.isPremium }
state?.activeAccount?.profile?.let {
it.userId to (it.hasPremiumPersonally == true)
}
}
.distinctUntilChanged()
.scanPairs()
.onEach { (previous, current) ->
if (current == null) return@onEach
val (currentUserId, currentIsPremium) = current
if (!currentIsPremium) return@onEach
// Same user transitioning from non-premium to premium counts as an upgrade.
val (currentUserId, currentIsPremiumFromSelf) = current
if (!currentIsPremiumFromSelf) return@onEach
// Same user transitioning from non-personal-premium to personal-premium counts as
// an upgrade.
if (previous?.first == currentUserId && !previous.second) {
markUpgradedToPremiumCardPending(userId = currentUserId)
clearPremiumUpgradePending(userId = currentUserId)
}
}
.launchIn(unconfinedScope)
}
override val isSelfHosted: Boolean get() = isSelfHostedFlow.value
override fun isInAppUpgradeAvailable(): Boolean =
billingRepository.isInAppBillingSupportedFlow.value &&
featureFlagManager.getFeatureFlag(FlagKey.MobilePremiumUpgrade)
@@ -179,6 +324,35 @@ class PremiumStateManagerImpl(
)
}
override fun markPremiumUpgradePending(userId: String) {
settingsDiskSource.storePremiumUpgradePending(
userId = userId,
isPending = true,
)
}
private fun clearPremiumUpgradePending(userId: String) {
settingsDiskSource.storePremiumUpgradePending(
userId = userId,
isPending = null,
)
}
private fun deriveLifecycleState(
userState: UserStateJson?,
subscriptionStatus: SubscriptionStatusState,
isPending: Boolean,
): UpgradeLifecycleState {
val profile = userState?.activeAccount?.profile ?: return UpgradeLifecycleState.Free
val hasPremium = profile.hasPremiumPersonally == true ||
profile.hasPremiumFromOrganization == true
return when {
hasPremium -> UpgradeLifecycleState.Premium(subscriptionStatus = subscriptionStatus)
isPending -> UpgradeLifecycleState.UpgradePending
else -> UpgradeLifecycleState.Free
}
}
private fun markUpgradedToPremiumCardPending(userId: String) {
// Don't re-arm the card if the user has already consumed it for this account.
if (settingsDiskSource.getUpgradedToPremiumCardConsumed(userId = userId) == true) {
@@ -189,8 +363,58 @@ class PremiumStateManagerImpl(
isPending = true,
)
}
@OptIn(ExperimentalCoroutinesApi::class)
private fun fetchSubscriptionStatusFlow(): Flow<SubscriptionStatusState> =
merge(
flowOf(Unit),
subscriptionRefreshTriggerFlow,
)
.flatMapLatest {
flow {
emit(SubscriptionStatusState.Loading)
emit(fetchSubscriptionStatusOnce())
}
}
private suspend fun fetchSubscriptionStatusOnce(): SubscriptionStatusState =
when (val result = billingRepository.getSubscription()) {
is SubscriptionResult.Success -> {
SubscriptionStatusState.Available(status = result.subscription.status)
}
SubscriptionResult.NotFound -> SubscriptionStatusState.NoSubscription
is SubscriptionResult.Error -> SubscriptionStatusState.Error(throwable = result.error)
}
}
private data class BannerInputs(
val userState: UserStateJson?,
val isInAppBillingSupported: Boolean,
val featureFlagEnabled: Boolean,
val isDismissed: Boolean,
val vaultDataState: DataState<VaultData>,
)
/**
* Returns `true` when the given [SubscriptionStatusState] represents a subscription substate
* that should disqualify a user from being treated as effectively premium.
*/
private fun SubscriptionStatusState.isInTroubleState(): Boolean =
this is SubscriptionStatusState.Available &&
when (this.status) {
PremiumSubscriptionStatus.CANCELED,
PremiumSubscriptionStatus.EXPIRED,
PremiumSubscriptionStatus.PAST_DUE,
PremiumSubscriptionStatus.PAUSED,
PremiumSubscriptionStatus.UPDATE_PAYMENT,
-> true
PremiumSubscriptionStatus.ACTIVE,
PremiumSubscriptionStatus.PENDING_CANCELLATION,
-> false
}
/**
* Returns `true` if this [Instant] is older than the given number of [days] based on
* the provided [clock]. Returns `false` if the receiver is `null`.

View File

@@ -32,7 +32,9 @@ interface BillingRepository {
suspend fun getPremiumPlanPricing(): PremiumPlanPricingResult
/**
* Fetches the current user's premium subscription details.
* Fetches the current user's premium subscription details. The endpoint 404s when the
* user has no `GatewaySubscriptionId` (free user); callers receive
* [SubscriptionResult.NotFound] in that case instead of [SubscriptionResult.Error].
*/
suspend fun getSubscription(): SubscriptionResult
}

View File

@@ -1,5 +1,6 @@
package com.x8bit.bitwarden.data.billing.repository
import com.bitwarden.network.model.GetSubscriptionResponse
import com.bitwarden.network.service.BillingService
import com.x8bit.bitwarden.data.billing.manager.PlayBillingManager
import com.x8bit.bitwarden.data.billing.repository.model.CheckoutSessionResult
@@ -54,10 +55,14 @@ class BillingRepositoryImpl(
billingService
.getSubscription()
.fold(
onSuccess = {
SubscriptionResult.Success(
subscription = it.toSubscriptionInfo(),
)
onSuccess = { response ->
when (response) {
is GetSubscriptionResponse.Success -> SubscriptionResult.Success(
subscription = response.subscription.toSubscriptionInfo(),
)
is GetSubscriptionResponse.NotFound -> SubscriptionResult.NotFound
}
},
onFailure = { SubscriptionResult.Error(error = it) },
)

View File

@@ -6,7 +6,19 @@ package com.x8bit.bitwarden.data.billing.repository.model
enum class PremiumSubscriptionStatus {
ACTIVE,
CANCELED,
OVERDUE_PAYMENT,
/**
* The subscription's initial payment never succeeded and Stripe voided the invoice, so
* the subscription never became active. Distinct from [CANCELED], which describes a
* subscription that was previously active.
*/
EXPIRED,
/**
* The subscription is scheduled to cancel at a future date but is still active until then.
*/
PENDING_CANCELLATION,
PAST_DUE,
PAUSED,
UPDATE_PAYMENT,
}

View File

@@ -17,6 +17,8 @@ import java.time.Instant
* @property nextChargeTotal The total of the next invoice:
* `seatsCost + (storageCost ?: 0) - (discountAmount ?: 0) + estimatedTax`.
* @property nextCharge The date of the next charge, or null if not applicable.
* @property cancelAt The date the subscription is scheduled to cancel at (the subscription is
* still active until this date), or null if no future cancellation is scheduled.
* @property canceledDate The date the subscription was canceled, or null.
* @property suspensionDate The date the subscription will be suspended, or null.
* @property gracePeriodDays The grace period in days, or null.
@@ -30,6 +32,7 @@ data class SubscriptionInfo(
val estimatedTax: BigDecimal,
val nextChargeTotal: BigDecimal,
val nextCharge: Instant?,
val cancelAt: Instant?,
val canceledDate: Instant?,
val suspensionDate: Instant?,
val gracePeriodDays: Int?,

View File

@@ -11,6 +11,13 @@ sealed class SubscriptionResult {
val subscription: SubscriptionInfo,
) : SubscriptionResult()
/**
* The endpoint returned 404, indicating the user has no subscription on record
* (e.g., the active account has never had a Stripe `GatewaySubscriptionId`).
* Consumers should treat this as a free user.
*/
data object NotFound : SubscriptionResult()
/**
* An error occurred while fetching subscription details.
*/

View File

@@ -0,0 +1,36 @@
package com.x8bit.bitwarden.data.billing.repository.model
/**
* Latest observed substate of the active user's premium subscription.
*
* The subscription endpoint is only meaningful for users who have a `GatewaySubscriptionId`
* on the server, so [NoSubscription] is emitted both for users we never queried (no personal
* premium signal) and for users whose fetch returned 404. [Error] preserves the failure for
* retry, while [Available] surfaces the raw status so consumers can apply their own policy.
*/
sealed class SubscriptionStatusState {
/**
* No fetch has been attempted yet for the active user.
*/
data object Loading : SubscriptionStatusState()
/**
* The active user has no recorded premium subscription.
*/
data object NoSubscription : SubscriptionStatusState()
/**
* The active user has a subscription with the given [status].
*/
data class Available(
val status: PremiumSubscriptionStatus,
) : SubscriptionStatusState()
/**
* The fetch failed for a reason other than 404.
*/
data class Error(
val throwable: Throwable,
) : SubscriptionStatusState()
}

View File

@@ -0,0 +1,33 @@
package com.x8bit.bitwarden.data.billing.repository.model
/**
* Represents the active user's position in the Premium upgrade lifecycle.
*
* Transitions:
* - [Free] → [UpgradePending] when the user completes Stripe checkout and the post-checkout
* sync still reports the user as non-premium — checkout is done, backend reconciliation
* is in flight.
* - [UpgradePending] → [Premium] when the server flips `isPremium` to `true`.
*
* Cancellation, expiration, and other terminal substates are surfaced via
* [Premium.subscriptionStatus] rather than as separate leaves.
*/
sealed class UpgradeLifecycleState {
/**
* The user has no Premium subscription and no upgrade is in flight.
*/
data object Free : UpgradeLifecycleState()
/**
* Stripe checkout completed but the server has not yet flipped `isPremium`.
*/
data object UpgradePending : UpgradeLifecycleState()
/**
* The user holds Premium; [subscriptionStatus] carries the substate (active, canceled, etc).
*/
data class Premium(
val subscriptionStatus: SubscriptionStatusState,
) : UpgradeLifecycleState()
}

View File

@@ -37,7 +37,7 @@ fun BitwardenSubscriptionResponseJson.toSubscriptionInfo(): SubscriptionInfo {
estimatedTax
return SubscriptionInfo(
status = status.toPremiumSubscriptionStatus(),
status = toPremiumSubscriptionStatus(),
cadence = cart.cadence.toPlanCadence(),
seatsCost = seatsCost,
storageCost = storageCost,
@@ -45,31 +45,37 @@ fun BitwardenSubscriptionResponseJson.toSubscriptionInfo(): SubscriptionInfo {
estimatedTax = estimatedTax,
nextChargeTotal = nextChargeTotal,
nextCharge = nextCharge,
cancelAt = cancelAt,
canceledDate = canceled,
suspensionDate = suspension,
gracePeriodDays = gracePeriod,
)
}
private fun SubscriptionStatusJson.toPremiumSubscriptionStatus(): PremiumSubscriptionStatus =
when (this) {
SubscriptionStatusJson.ACTIVE,
SubscriptionStatusJson.TRIALING,
-> PremiumSubscriptionStatus.ACTIVE
SubscriptionStatusJson.CANCELED,
SubscriptionStatusJson.INCOMPLETE_EXPIRED,
-> PremiumSubscriptionStatus.CANCELED
SubscriptionStatusJson.INCOMPLETE,
SubscriptionStatusJson.UNPAID,
-> PremiumSubscriptionStatus.OVERDUE_PAYMENT
SubscriptionStatusJson.PAST_DUE -> PremiumSubscriptionStatus.PAST_DUE
SubscriptionStatusJson.PAUSED -> PremiumSubscriptionStatus.PAUSED
private fun BitwardenSubscriptionResponseJson.toPremiumSubscriptionStatus():
PremiumSubscriptionStatus = when (status) {
SubscriptionStatusJson.ACTIVE,
SubscriptionStatusJson.TRIALING,
-> {
if (cancelAt != null) {
PremiumSubscriptionStatus.PENDING_CANCELLATION
} else {
PremiumSubscriptionStatus.ACTIVE
}
}
SubscriptionStatusJson.CANCELED -> PremiumSubscriptionStatus.CANCELED
SubscriptionStatusJson.INCOMPLETE_EXPIRED -> PremiumSubscriptionStatus.EXPIRED
SubscriptionStatusJson.INCOMPLETE,
SubscriptionStatusJson.UNPAID,
-> PremiumSubscriptionStatus.UPDATE_PAYMENT
SubscriptionStatusJson.PAST_DUE -> PremiumSubscriptionStatus.PAST_DUE
SubscriptionStatusJson.PAUSED -> PremiumSubscriptionStatus.PAUSED
}
private fun CadenceTypeJson.toPlanCadence(): PlanCadence = when (this) {
CadenceTypeJson.ANNUALLY -> PlanCadence.ANNUALLY
CadenceTypeJson.MONTHLY -> PlanCadence.MONTHLY

View File

@@ -45,7 +45,6 @@ import com.x8bit.bitwarden.data.vault.datasource.sdk.model.RegisterFido2Credenti
import com.x8bit.bitwarden.data.vault.datasource.sdk.util.toAndroidAttestationResponse
import com.x8bit.bitwarden.data.vault.datasource.sdk.util.toAndroidFido2PublicKeyCredential
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.fold
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
@@ -65,12 +64,10 @@ class BitwardenCredentialManagerImpl(
private val vaultRepository: VaultRepository,
private val cipherMatchingManager: CipherMatchingManager,
private val passkeyAttestationOptionsSanitizer: PasskeyAttestationOptionsSanitizer,
dispatcherManager: DispatcherManager,
private val dispatcherManager: DispatcherManager,
) : BitwardenCredentialManager,
Fido2CredentialStore by fido2CredentialStore {
private val ioScope = CoroutineScope(dispatcherManager.io)
override var isUserVerified: Boolean = false
override var authenticationAttempts: Int = 0
@@ -179,7 +176,7 @@ class BitwardenCredentialManagerImpl(
override suspend fun getCredentialEntries(
getCredentialsRequest: GetCredentialsRequest,
): Result<List<CredentialEntry>> = withContext(ioScope.coroutineContext) {
): Result<List<CredentialEntry>> = withContext(dispatcherManager.io) {
val cipherListViews = vaultRepository
.decryptCipherListResultStateFlow
.takeUntilLoaded()

View File

@@ -39,7 +39,7 @@ private const val RELEASE_BUILD = "release"
class PrivilegedAppRepositoryImpl(
private val privilegedAppDiskSource: PrivilegedAppDiskSource,
private val assetManager: AssetManager,
dispatcherManager: DispatcherManager,
private val dispatcherManager: DispatcherManager,
private val json: Json,
) : PrivilegedAppRepository {
@@ -118,7 +118,7 @@ class PrivilegedAppRepositoryImpl(
.toPrivilegedAppAllowListJson()
override suspend fun getGoogleTrustedPrivilegedAppsOrNull(): PrivilegedAppAllowListJson? =
withContext(ioScope.coroutineContext) {
withContext(dispatcherManager.io) {
assetManager
.readAsset(fileName = GOOGLE_ALLOW_LIST_FILE_NAME)
.map { json.decodeFromStringOrNull<PrivilegedAppAllowListJson>(it) }
@@ -126,7 +126,7 @@ class PrivilegedAppRepositoryImpl(
}
override suspend fun getCommunityTrustedPrivilegedAppsOrNull(): PrivilegedAppAllowListJson? {
return withContext(ioScope.coroutineContext) {
return withContext(dispatcherManager.io) {
assetManager
.readAsset(fileName = COMMUNITY_ALLOW_LIST_FILE_NAME)
.map { json.decodeFromStringOrNull<PrivilegedAppAllowListJson>(it) }

View File

@@ -27,4 +27,10 @@ interface EnvironmentDiskSource {
* Stores the [urls] for the given [userEmail].
*/
fun storePreAuthEnvironmentUrlDataForEmail(userEmail: String, urls: EnvironmentUrlDataJson)
/**
* The fill-assist URL provided by the server config, or `null` if the server does not
* configure fill-assist targeting rules.
*/
var fillAssistRulesUrl: String?
}

View File

@@ -11,6 +11,7 @@ import kotlinx.serialization.json.Json
private const val PRE_AUTH_URLS_KEY = "preAuthEnvironmentUrls"
private const val EMAIL_VERIFICATION_URLS = "emailVerificationUrls"
private const val FILL_ASSIST_RULES_URL_KEY = "fillAssistRulesUrl"
/**
* Primary implementation of [EnvironmentDiskSource].
@@ -54,4 +55,8 @@ class EnvironmentDiskSourceImpl(
value = json.encodeToString(urls),
)
}
override var fillAssistRulesUrl: String?
get() = getString(key = FILL_ASSIST_RULES_URL_KEY)
set(value) = putString(key = FILL_ASSIST_RULES_URL_KEY, value = value)
}

View File

@@ -182,6 +182,25 @@ interface SettingsDiskSource : FlightRecorderDiskSource {
*/
fun getUpgradedToPremiumCardPendingFlow(userId: String): Flow<Boolean?>
/**
* Retrieves the stored value of whether a Premium upgrade is awaiting server confirmation
* for the given [userId].
*/
fun getPremiumUpgradePending(userId: String): Boolean?
/**
* Stores whether a Premium upgrade is awaiting server confirmation for the given [userId].
*/
fun storePremiumUpgradePending(
userId: String,
isPending: Boolean?,
)
/**
* Emits updates that track [getPremiumUpgradePending] for the given [userId].
*/
fun getPremiumUpgradePendingFlow(userId: String): Flow<Boolean?>
/**
* Retrieves the biometric integrity validity for the given [userId] and
* [systemBioIntegrityState].

View File

@@ -57,11 +57,13 @@ private const val UPGRADED_TO_PREMIUM_CARD_CONSUMED =
"upgradedToPremiumCardConsumed"
private const val UPGRADED_TO_PREMIUM_CARD_PENDING =
"upgradedToPremiumCardPending"
private const val PREMIUM_UPGRADE_PENDING =
"premiumUpgradePending"
/**
* Primary implementation of [SettingsDiskSource].
*/
@Suppress("TooManyFunctions")
@Suppress("TooManyFunctions", "LargeClass")
class SettingsDiskSourceImpl(
private val sharedPreferences: SharedPreferences,
private val json: Json,
@@ -107,6 +109,9 @@ class SettingsDiskSourceImpl(
private val mutableUpgradedToPremiumCardPendingFlowMap =
mutableMapOf<String, MutableSharedFlow<Boolean?>>()
private val mutablePremiumUpgradePendingFlowMap =
mutableMapOf<String, MutableSharedFlow<Boolean?>>()
private val mutableIsIconLoadingDisabledFlow = bufferedMutableSharedFlow<Boolean?>()
private val mutableIsCrashLoggingEnabledFlow = bufferedMutableSharedFlow<Boolean?>()
@@ -264,6 +269,7 @@ class SettingsDiskSourceImpl(
// - Premium upgrade banner dismissed
// - Upgraded to Premium action card consumed
// - Upgraded to Premium action card pending
// - Premium upgrade pending
}
override fun getIntroducingArchiveActionCardDismissed(userId: String): Boolean? =
@@ -346,6 +352,26 @@ class SettingsDiskSourceImpl(
getMutableUpgradedToPremiumCardPendingFlow(userId = userId)
.onSubscription { emit(getUpgradedToPremiumCardPending(userId = userId)) }
override fun getPremiumUpgradePending(userId: String): Boolean? =
getBoolean(
key = PREMIUM_UPGRADE_PENDING.appendIdentifier(identifier = userId),
)
override fun storePremiumUpgradePending(
userId: String,
isPending: Boolean?,
) {
putBoolean(
key = PREMIUM_UPGRADE_PENDING.appendIdentifier(identifier = userId),
value = isPending,
)
getMutablePremiumUpgradePendingFlow(userId = userId).tryEmit(isPending)
}
override fun getPremiumUpgradePendingFlow(userId: String): Flow<Boolean?> =
getMutablePremiumUpgradePendingFlow(userId = userId)
.onSubscription { emit(getPremiumUpgradePending(userId = userId)) }
override fun getAccountBiometricIntegrityValidity(
userId: String,
systemBioIntegrityState: String,
@@ -711,6 +737,13 @@ class SettingsDiskSourceImpl(
bufferedMutableSharedFlow(replay = 1)
}
private fun getMutablePremiumUpgradePendingFlow(
userId: String,
): MutableSharedFlow<Boolean?> =
mutablePremiumUpgradePendingFlowMap.getOrPut(userId) {
bufferedMutableSharedFlow(replay = 1)
}
private fun getMutableLastSyncFlow(
userId: String,
): MutableSharedFlow<Instant?> =

View File

@@ -7,6 +7,7 @@ import com.bitwarden.network.interceptor.BaseUrlsProvider
import com.bitwarden.network.model.BitwardenServiceClientConfig
import com.bitwarden.network.service.ConfigService
import com.bitwarden.network.service.EventService
import com.bitwarden.network.service.FillAssistService
import com.bitwarden.network.service.PushService
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
import com.x8bit.bitwarden.data.auth.manager.AuthTokenManager
@@ -15,6 +16,7 @@ import com.x8bit.bitwarden.data.platform.datasource.network.util.HEADER_VALUE_CL
import com.x8bit.bitwarden.data.platform.datasource.network.util.HEADER_VALUE_USER_AGENT
import com.x8bit.bitwarden.data.platform.manager.CertificateManager
import com.x8bit.bitwarden.data.platform.manager.network.NetworkCookieManager
import com.x8bit.bitwarden.data.platform.manager.network.NetworkPermissionManager
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
@@ -31,6 +33,12 @@ import javax.inject.Singleton
@InstallIn(SingletonComponent::class)
object PlatformNetworkModule {
@Provides
@Singleton
fun providesFillAssistService(
bitwardenServiceClient: BitwardenServiceClient,
): FillAssistService = bitwardenServiceClient.fillAssistService
@Provides
@Singleton
fun providesConfigService(
@@ -58,6 +66,7 @@ object PlatformNetworkModule {
certificateManager: CertificateManager,
buildInfoManager: BuildInfoManager,
networkCookieManager: NetworkCookieManager,
networkPermissionManager: NetworkPermissionManager,
clock: Clock,
): BitwardenServiceClientConfig = BitwardenServiceClientConfig(
clock = clock,
@@ -72,6 +81,7 @@ object PlatformNetworkModule {
certificateProvider = certificateManager,
enableHttpBodyLogging = buildInfoManager.isDevBuild,
cookieProvider = networkCookieManager,
permissionProvider = networkPermissionManager,
)
@Provides

View File

@@ -11,6 +11,11 @@ import timber.log.Timber
abstract class BaseSdkSource(
protected val sdkClientManager: SdkClientManager,
) {
/**
* Helper function to retrieve the global [Client] synchronously.
*/
protected val globalClient get() = sdkClientManager.globalClient
/**
* Helper function to retrieve the [Client] associated with the given [userId].
*/

View File

@@ -1,7 +1,7 @@
package com.x8bit.bitwarden.data.platform.manager
import com.bitwarden.network.model.PolicyTypeJson
import com.bitwarden.network.model.SyncResponseJson
import com.bitwarden.policies.PolicyType
import com.bitwarden.policies.PolicyView
import kotlinx.coroutines.flow.Flow
/**
@@ -11,20 +11,20 @@ interface PolicyManager {
/**
* Returns a flow of all the active policies of the given type.
*/
fun getActivePoliciesFlow(type: PolicyTypeJson): Flow<List<SyncResponseJson.Policy>>
fun getActivePoliciesFlow(type: PolicyType): Flow<List<PolicyView>>
/**
* Get all the policies of the given [type] that are enabled and applicable to the user.
*/
fun getActivePolicies(type: PolicyTypeJson): List<SyncResponseJson.Policy>
fun getActivePolicies(type: PolicyType): List<PolicyView>
/**
* Get all the policies of the given [type] that are enabled and applicable to the [userId].
*/
fun getUserPolicies(
userId: String,
type: PolicyTypeJson,
): List<SyncResponseJson.Policy>
type: PolicyType,
): List<PolicyView>
/**
* Get the organization id of the personal ownership policy.

View File

@@ -1,17 +1,23 @@
package com.x8bit.bitwarden.data.platform.manager
import com.bitwarden.network.model.OrganizationStatusType
import com.bitwarden.network.model.OrganizationType
import com.bitwarden.network.model.PolicyTypeJson
import com.bitwarden.network.model.SyncResponseJson
import com.bitwarden.core.data.manager.model.FlagKey
import com.bitwarden.organizations.OrganizationUserStatusType
import com.bitwarden.organizations.OrganizationUserType
import com.bitwarden.policies.OrganizationUserPolicyContext
import com.bitwarden.policies.PolicyType
import com.bitwarden.policies.PolicyView
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
import com.x8bit.bitwarden.data.auth.datasource.sdk.AuthSdkSource
import com.x8bit.bitwarden.data.auth.repository.util.activeUserIdChangesFlow
import com.x8bit.bitwarden.data.vault.repository.util.toSdkOrganizationPolicyContext
import com.x8bit.bitwarden.data.vault.repository.util.toSdkPolicyViews
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.emptyFlow
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.mapNotNull
import kotlinx.coroutines.flow.map
/**
* The default [PolicyManager] implementation. This class is responsible for
@@ -19,114 +25,151 @@ import kotlinx.coroutines.flow.mapNotNull
*/
class PolicyManagerImpl(
private val authDiskSource: AuthDiskSource,
private val authSdkSource: AuthSdkSource,
private val featureFlagManager: FeatureFlagManager,
) : PolicyManager {
@OptIn(ExperimentalCoroutinesApi::class)
override fun getActivePoliciesFlow(type: PolicyTypeJson): Flow<List<SyncResponseJson.Policy>> =
override fun getActivePoliciesFlow(type: PolicyType): Flow<List<PolicyView>> =
authDiskSource
.activeUserIdChangesFlow
.flatMapLatest { activeUserId ->
activeUserId
?.let { userId ->
authDiskSource
.getPoliciesFlow(userId)
.mapNotNull {
filterPolicies(
userId = userId,
type = type,
policies = it,
)
}
}
?.let { userId -> getAppliedPolicyViewsFlow(userId = userId, type = type) }
?: emptyFlow()
}
.distinctUntilChanged()
override fun getActivePolicies(type: PolicyTypeJson): List<SyncResponseJson.Policy> =
override fun getActivePolicies(type: PolicyType): List<PolicyView> =
authDiskSource
.userState
?.activeUserId
?.let { userId ->
filterPolicies(
userId = userId,
type = type,
policies = authDiskSource.getPolicies(userId = userId),
)
}
?: emptyList()
?.let { userId -> getUserPolicies(userId = userId, type = type) }
.orEmpty()
override fun getUserPolicies(
userId: String,
type: PolicyTypeJson,
): List<SyncResponseJson.Policy> =
type: PolicyType,
): List<PolicyView> =
this
.filterPolicies(
userId = userId,
type = type,
policies = authDiskSource.getPolicies(userId = userId),
policies = authDiskSource
.getPolicies(userId = userId)
?.toSdkPolicyViews(),
organizations = authDiskSource
.getOrganizations(userId = userId)
?.map {
OrganizationPolicyData(
organizationUserPolicyContext = it.toSdkOrganizationPolicyContext(),
organizationShouldUsePolicies = it.permissions.shouldManagePolicies,
)
},
isPoliciesInAcceptedStateEnabled = featureFlagManager
.getFeatureFlag(key = FlagKey.PoliciesInAcceptedState),
)
.orEmpty()
override fun getPersonalOwnershipPolicyOrganizationId(): String? =
this
.getActivePolicies(PolicyTypeJson.PERSONAL_OWNERSHIP)
.getActivePolicies(type = PolicyType.ORGANIZATION_DATA_OWNERSHIP)
.sortedBy { it.revisionDate }
.firstOrNull()
?.organizationId
/**
* A helper method to filter policies.
*/
private fun filterPolicies(
private fun getAppliedPolicyViewsFlow(
userId: String,
type: PolicyTypeJson,
policies: List<SyncResponseJson.Policy>?,
): List<SyncResponseJson.Policy>? {
policies ?: return null
if (policies.isEmpty()) return emptyList()
// Get a list of the user's organizations that enforce policies.
val organizationIdsWithActivePolicies = authDiskSource
.getOrganizations(userId)
?.filter {
it.shouldUsePolicies &&
it.status >= OrganizationStatusType.ACCEPTED &&
!isOrganizationExemptFromPolicies(it, type)
}
?.map { it.id }
type: PolicyType,
): Flow<List<PolicyView>> = combine(
authDiskSource
.getPoliciesFlow(userId = userId)
.map { it?.toSdkPolicyViews() },
authDiskSource
.getOrganizationsFlow(userId = userId)
.map { organizations ->
organizations?.map {
OrganizationPolicyData(
organizationUserPolicyContext = it.toSdkOrganizationPolicyContext(),
organizationShouldUsePolicies = it.permissions.shouldManagePolicies,
)
}
},
featureFlagManager.getFeatureFlagFlow(key = FlagKey.PoliciesInAcceptedState),
) { policies, organizations, isEnabled ->
this
.filterPolicies(
type = type,
policies = policies,
organizations = organizations,
isPoliciesInAcceptedStateEnabled = isEnabled,
)
.orEmpty()
// Filter the policies based on the type, whether the policy is active,
// and whether the organization rules except the user from the policy.
return policies.filter {
it.type == type &&
it.isEnabled &&
organizationIdsWithActivePolicies.contains(it.organizationId)
}
}
private fun filterPolicies(
type: PolicyType,
policies: List<PolicyView>?,
organizations: List<OrganizationPolicyData>?,
isPoliciesInAcceptedStateEnabled: Boolean,
): List<PolicyView>? =
when {
policies == null -> null
policies.isEmpty() -> emptyList()
isPoliciesInAcceptedStateEnabled -> {
authSdkSource
.filterPolicies(
policies = policies,
policyType = type,
organizations = organizations
?.map { it.organizationUserPolicyContext }
.orEmpty(),
)
.getOrElse { emptyList() }
}
else -> {
// Legacy flow
val organizationIdsWithActivePolicies = organizations
?.filter {
@Suppress("MaxLineLength")
it.organizationUserPolicyContext.usePolicies &&
it.organizationUserPolicyContext.status >= OrganizationUserStatusType.ACCEPTED &&
!it.isOrganizationExemptFromPolicies(policyType = type)
}
?.map { it.organizationUserPolicyContext.id }
.orEmpty()
return policies.filter {
it.type == type &&
it.enabled &&
organizationIdsWithActivePolicies.contains(it.organizationId)
}
}
}
/**
* A helper method to determine if the organization is exempt from policies.
*/
private fun isOrganizationExemptFromPolicies(
organization: SyncResponseJson.Profile.Organization,
policyType: PolicyTypeJson,
private fun OrganizationPolicyData.isOrganizationExemptFromPolicies(
policyType: PolicyType,
): Boolean =
when (policyType) {
PolicyTypeJson.MAXIMUM_VAULT_TIMEOUT -> {
organization.type == OrganizationType.OWNER
PolicyType.MAXIMUM_VAULT_TIMEOUT -> {
this.organizationUserPolicyContext.role == OrganizationUserType.OWNER
}
PolicyTypeJson.PASSWORD_GENERATOR,
PolicyTypeJson.REMOVE_UNLOCK_WITH_PIN,
PolicyTypeJson.RESTRICT_ITEM_TYPES,
-> {
false
}
PolicyType.PASSWORD_GENERATOR,
PolicyType.REMOVE_UNLOCK_WITH_PIN,
PolicyType.RESTRICTED_ITEM_TYPES,
-> false
else -> {
(organization.type == OrganizationType.OWNER ||
organization.type == OrganizationType.ADMIN) ||
organization.permissions.shouldManagePolicies
this.organizationUserPolicyContext.role == OrganizationUserType.OWNER ||
this.organizationUserPolicyContext.role == OrganizationUserType.ADMIN ||
this.organizationShouldUsePolicies
}
}
}
private data class OrganizationPolicyData(
val organizationUserPolicyContext: OrganizationUserPolicyContext,
val organizationShouldUsePolicies: Boolean,
)

View File

@@ -7,6 +7,13 @@ import com.bitwarden.sdk.Client
*/
interface SdkClientManager {
/**
* Synchronously returns a [Client] that is unassociated with any user. It cannot be used for
* anything that performs a network requests. If the client is not yet ready, this will block
* until it is ready.
*/
val globalClient: Client
/**
* Returns the cached [Client] instance for the given [userId], otherwise creates and caches
* a new one and returns it.

View File

@@ -1,17 +1,24 @@
package com.x8bit.bitwarden.data.platform.manager
import android.os.Build
import com.bitwarden.core.data.manager.dispatcher.DispatcherManager
import com.bitwarden.core.data.util.concurrentMapOf
import com.bitwarden.core.util.isBuildVersionAtLeast
import com.bitwarden.data.manager.NativeLibraryManager
import com.bitwarden.sdk.Client
import com.x8bit.bitwarden.data.platform.manager.sdk.SdkPlatformApiFactory
import com.x8bit.bitwarden.data.platform.manager.sdk.SdkRepositoryFactory
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.async
import kotlinx.coroutines.runBlocking
/**
* Primary implementation of [SdkClientManager].
*/
class SdkClientManagerImpl(
nativeLibraryManager: NativeLibraryManager,
dispatcherManager: DispatcherManager,
sdkRepoFactory: SdkRepositoryFactory,
sdkPlatformApiFactory: SdkPlatformApiFactory,
private val featureFlagManager: FeatureFlagManager,
@@ -38,7 +45,9 @@ class SdkClientManagerImpl(
}
},
) : SdkClientManager {
private val userIdToClientMap = mutableMapOf<String, Client>()
private val userIdToClientMap = concurrentMapOf<String, Client>()
private val ioScope = CoroutineScope(context = dispatcherManager.io)
private val globalClientDeferred: Deferred<Client>
init {
// The SDK requires access to Android APIs that were not made public until API 31. In order
@@ -47,8 +56,13 @@ class SdkClientManagerImpl(
if (!isBuildVersionAtLeast(Build.VERSION_CODES.S)) {
nativeLibraryManager.loadLibrary("bitwarden_uniffi")
}
// Initialize this now, so that we can access it synchronously later on.
globalClientDeferred = ioScope.async { clientProvider(null, null) }
}
override val globalClient: Client
get() = runBlocking { globalClientDeferred.await() }
override suspend fun getOrCreateClient(
userId: String,
): Client = userIdToClientMap.getOrPut(key = userId) { clientProvider(userId, null) }

View File

@@ -19,6 +19,7 @@ import com.bitwarden.network.model.BitwardenServiceClientConfig
import com.bitwarden.network.service.EventService
import com.bitwarden.network.service.PushService
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
import com.x8bit.bitwarden.data.auth.datasource.sdk.AuthSdkSource
import com.x8bit.bitwarden.data.auth.manager.AddTotpItemFromAuthenticatorManager
import com.x8bit.bitwarden.data.auth.repository.AuthRepository
import com.x8bit.bitwarden.data.autofill.accessibility.manager.AccessibilityEnabledManager
@@ -74,6 +75,8 @@ import com.x8bit.bitwarden.data.platform.manager.network.NetworkConnectionManage
import com.x8bit.bitwarden.data.platform.manager.network.NetworkConnectionManagerImpl
import com.x8bit.bitwarden.data.platform.manager.network.NetworkCookieManager
import com.x8bit.bitwarden.data.platform.manager.network.NetworkCookieManagerImpl
import com.x8bit.bitwarden.data.platform.manager.network.NetworkPermissionManager
import com.x8bit.bitwarden.data.platform.manager.network.NetworkPermissionManagerImpl
import com.x8bit.bitwarden.data.platform.manager.restriction.RestrictionManager
import com.x8bit.bitwarden.data.platform.manager.restriction.RestrictionManagerImpl
import com.x8bit.bitwarden.data.platform.manager.sdk.SdkPlatformApiFactory
@@ -89,6 +92,7 @@ import com.x8bit.bitwarden.data.platform.repository.SettingsRepository
import com.x8bit.bitwarden.data.vault.datasource.disk.VaultDiskSource
import com.x8bit.bitwarden.data.vault.manager.VaultLockManager
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
import com.x8bit.bitwarden.ui.platform.manager.resource.ResourceManager
import dagger.Module
import dagger.Provides
import dagger.hilt.InstallIn
@@ -217,11 +221,13 @@ object PlatformManagerModule {
@Provides
@Singleton
fun provideSdkClientManager(
dispatcherManager: DispatcherManager,
featureFlagManager: FeatureFlagManager,
nativeLibraryManager: NativeLibraryManager,
sdkRepositoryFactory: SdkRepositoryFactory,
sdkPlatformApiFactory: SdkPlatformApiFactory,
): SdkClientManager = SdkClientManagerImpl(
dispatcherManager = dispatcherManager,
featureFlagManager = featureFlagManager,
nativeLibraryManager = nativeLibraryManager,
sdkRepoFactory = sdkRepositoryFactory,
@@ -259,8 +265,12 @@ object PlatformManagerModule {
@Singleton
fun providePolicyManager(
authDiskSource: AuthDiskSource,
authSdkSource: AuthSdkSource,
featureFlagManager: FeatureFlagManager,
): PolicyManager = PolicyManagerImpl(
authDiskSource = authDiskSource,
authSdkSource = authSdkSource,
featureFlagManager = featureFlagManager,
)
@Provides
@@ -439,12 +449,24 @@ object PlatformManagerModule {
@Provides
@Singleton
fun provideNetworkCookieManager(
resourceManager: ResourceManager,
configDiskSource: ConfigDiskSource,
cookieDiskSource: CookieDiskSource,
cookieAcquisitionRequestManager: CookieAcquisitionRequestManager,
): NetworkCookieManager = NetworkCookieManagerImpl(
resourceManager = resourceManager,
configDiskSource = configDiskSource,
cookieDiskSource = cookieDiskSource,
cookieAcquisitionRequestManager = cookieAcquisitionRequestManager,
)
@Provides
@Singleton
fun provideNetworkPermissionManager(
@ApplicationContext context: Context,
resourceManager: ResourceManager,
): NetworkPermissionManager = NetworkPermissionManagerImpl(
context = context,
resourceManager = resourceManager,
)
}

View File

@@ -5,9 +5,9 @@ import androidx.credentials.CredentialManager
import com.bitwarden.cxf.model.ImportCredentialsRequestData
import com.bitwarden.ui.platform.manager.share.model.ShareData
import com.bitwarden.ui.platform.model.TotpData
import com.x8bit.bitwarden.data.billing.util.PremiumCheckoutCallbackResult
import com.x8bit.bitwarden.data.autofill.model.AutofillSaveItem
import com.x8bit.bitwarden.data.autofill.model.AutofillSelectionData
import com.x8bit.bitwarden.data.billing.util.PremiumCheckoutCallbackResult
import com.x8bit.bitwarden.data.credentials.model.CreateCredentialRequest
import com.x8bit.bitwarden.data.credentials.model.Fido2CredentialAssertionRequest
import com.x8bit.bitwarden.data.credentials.model.GetCredentialsRequest
@@ -144,6 +144,13 @@ sealed class SpecialCircumstance : Parcelable {
val callbackResult: PremiumCheckoutCallbackResult,
) : SpecialCircumstance()
/**
* The user has returned from the Stripe customer portal (launched to manage or cancel their
* subscription). The close of the portal is the only signal — there is no callback payload.
*/
@Parcelize
data object StripePortal : SpecialCircumstance()
/**
* The app was launched to select an account to export credentials from.
*/

View File

@@ -2,11 +2,13 @@ package com.x8bit.bitwarden.data.platform.manager.network
import com.bitwarden.data.datasource.disk.ConfigDiskSource
import com.bitwarden.network.model.NetworkCookie
import com.bitwarden.ui.platform.resource.BitwardenString
import com.x8bit.bitwarden.data.platform.datasource.disk.CookieDiskSource
import com.x8bit.bitwarden.data.platform.datasource.disk.model.CookieConfigurationData
import com.x8bit.bitwarden.data.platform.manager.CookieAcquisitionRequestManager
import com.x8bit.bitwarden.data.platform.manager.model.CookieAcquisitionRequest
import com.x8bit.bitwarden.data.platform.manager.util.toNetworkCookieList
import com.x8bit.bitwarden.ui.platform.manager.resource.ResourceManager
import timber.log.Timber
private const val BOOTSTRAP_TYPE_SSO_COOKIE_VENDOR = "ssoCookieVendor"
@@ -15,6 +17,7 @@ private const val BOOTSTRAP_TYPE_SSO_COOKIE_VENDOR = "ssoCookieVendor"
* Default implementation of [NetworkCookieManager].
*/
class NetworkCookieManagerImpl(
private val resourceManager: ResourceManager,
private val configDiskSource: ConfigDiskSource,
private val cookieDiskSource: CookieDiskSource,
private val cookieAcquisitionRequestManager: CookieAcquisitionRequestManager,
@@ -32,6 +35,12 @@ class NetworkCookieManagerImpl(
?.takeIf { it.type == BOOTSTRAP_TYPE_SSO_COOKIE_VENDOR }
?.cookieDomain
override val errorMessageString: String
get() = resourceManager.getString(
resId = BitwardenString
.your_request_was_interrupted_because_the_app_needed_to_reauthenticate,
)
override fun needsBootstrap(hostname: String): Boolean {
val result = configDiskSource
.serverConfig

View File

@@ -0,0 +1,21 @@
package com.x8bit.bitwarden.data.platform.manager.network
import com.bitwarden.network.provider.PermissionProvider
import kotlinx.coroutines.flow.StateFlow
/**
* A manager class for handling network permissions.
*/
interface NetworkPermissionManager : PermissionProvider {
/**
* StateFlow indicating if local network access is being requested at this moment.
*
* Emits `true` when local network access is required, `false` otherwise.
*/
val isLocalNetworkAccessRequiredStateFlow: StateFlow<Boolean>
/**
* Sets the local network access required state to `false`.
*/
fun clearIsLocalNetworkAccessRequired()
}

View File

@@ -0,0 +1,49 @@
package com.x8bit.bitwarden.data.platform.manager.network
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.content.ContextCompat
import com.bitwarden.core.util.isBuildVersionAtLeast
import com.bitwarden.ui.platform.resource.BitwardenString
import com.x8bit.bitwarden.ui.platform.manager.resource.ResourceManager
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
/**
* The default implementation of [NetworkPermissionManager].
*/
internal class NetworkPermissionManagerImpl(
private val context: Context,
private val resourceManager: ResourceManager,
) : NetworkPermissionManager {
private val mutableIsLocalNetworkAccessRequiredStateFlow = MutableStateFlow(value = false)
override val errorMessageString: String
get() = resourceManager.getString(
resId = BitwardenString
.your_request_was_interrupted_because_the_app_needs_local_network_access,
)
override val hasLocalNetworkAccessPermission: Boolean
get() = if (isBuildVersionAtLeast(version = Build.VERSION_CODES.CINNAMON_BUN)) {
ContextCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_LOCAL_NETWORK,
) == PackageManager.PERMISSION_GRANTED
} else {
true
}
override val isLocalNetworkAccessRequiredStateFlow: StateFlow<Boolean> =
mutableIsLocalNetworkAccessRequiredStateFlow
override fun acquireLocalNetworkAccessPermission() {
mutableIsLocalNetworkAccessRequiredStateFlow.value = true
}
override fun clearIsLocalNetworkAccessRequired() {
mutableIsLocalNetworkAccessRequiredStateFlow.value = false
}
}

View File

@@ -1,6 +1,6 @@
package com.x8bit.bitwarden.data.platform.manager.util
import com.bitwarden.network.model.PolicyTypeJson
import com.bitwarden.policies.PolicyType
import com.x8bit.bitwarden.data.auth.repository.model.PolicyInformation
import com.x8bit.bitwarden.data.auth.repository.util.policyInformation
import com.x8bit.bitwarden.data.platform.manager.PolicyManager
@@ -12,7 +12,7 @@ import kotlinx.coroutines.flow.map
*/
inline fun <reified T : PolicyInformation> PolicyManager.getActivePolicies(): List<T> =
this
.getActivePolicies(type = getPolicyTypeJson<T>())
.getActivePolicies(type = getPolicyType<T>())
.mapNotNull { it.policyInformation as? T }
/**
@@ -20,21 +20,21 @@ inline fun <reified T : PolicyInformation> PolicyManager.getActivePolicies(): Li
*/
inline fun <reified T : PolicyInformation> PolicyManager.getActivePoliciesFlow(): Flow<List<T>> =
this
.getActivePoliciesFlow(type = getPolicyTypeJson<T>())
.getActivePoliciesFlow(type = getPolicyType<T>())
.map { policies ->
policies.mapNotNull { policy -> policy.policyInformation as? T }
}
/**
* Helper method for mapping a specific [PolicyInformation] type to its [PolicyTypeJson]
* Helper method for mapping a specific [PolicyInformation] type to its [PolicyType]
* counterpart.
*/
inline fun <reified T : PolicyInformation> getPolicyTypeJson(): PolicyTypeJson =
inline fun <reified T : PolicyInformation> getPolicyType(): PolicyType =
when (T::class.java) {
PolicyInformation.MasterPassword::class.java -> PolicyTypeJson.MASTER_PASSWORD
PolicyInformation.PasswordGenerator::class.java -> PolicyTypeJson.PASSWORD_GENERATOR
PolicyInformation.SendOptions::class.java -> PolicyTypeJson.SEND_OPTIONS
PolicyInformation.VaultTimeout::class.java -> PolicyTypeJson.MAXIMUM_VAULT_TIMEOUT
PolicyInformation.MasterPassword::class.java -> PolicyType.MASTER_PASSWORD
PolicyInformation.PasswordGenerator::class.java -> PolicyType.PASSWORD_GENERATOR
PolicyInformation.SendOptions::class.java -> PolicyType.SEND_OPTIONS
PolicyInformation.VaultTimeout::class.java -> PolicyType.MAXIMUM_VAULT_TIMEOUT
else -> {
throw IllegalStateException(
@@ -43,9 +43,10 @@ inline fun <reified T : PolicyInformation> getPolicyTypeJson(): PolicyTypeJson =
)
}
}
/**
* Helper method for verifying if user has enabled the restrict item policy.
*/
fun PolicyManager.hasRestrictItemTypes(): Boolean =
getActivePolicies(type = PolicyTypeJson.RESTRICT_ITEM_TYPES)
.any { it.isEnabled }
getActivePolicies(type = PolicyType.RESTRICTED_ITEM_TYPES)
.any { it.enabled }

View File

@@ -31,4 +31,6 @@ class BaseUrlsProviderImpl(
.toEnvironmentUrlsOrDefault()
.environmentUrlData
.baseEventsUrl
override fun getBaseFillAssistUrl(): String? = environmentDiskSource.fillAssistRulesUrl
}

View File

@@ -12,7 +12,6 @@ import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
import com.x8bit.bitwarden.data.auth.datasource.disk.model.AccountJson
import com.x8bit.bitwarden.data.auth.repository.util.toAccountCryptographicState
import com.x8bit.bitwarden.data.auth.repository.util.toSdkParams
import com.x8bit.bitwarden.data.platform.repository.util.sanitizeTotpUri
import com.x8bit.bitwarden.data.vault.datasource.disk.VaultDiskSource
import com.x8bit.bitwarden.data.vault.datasource.sdk.ScopedVaultSdkSource
import com.x8bit.bitwarden.data.vault.datasource.sdk.model.InitializeCryptoResult
@@ -104,11 +103,6 @@ class AuthenticatorBridgeRepositoryImpl(
decryptedCipher.login?.totp?.let { rawTotp ->
SharedAccountData.CipherData(
uri = rawTotp,
// TODO: PM-34085 Remove the legacyUri.
legacyUri = rawTotp.sanitizeTotpUri(
issuer = cipherName,
username = username,
),
id = cipherId,
name = cipherName,
username = username,

View File

@@ -4,8 +4,8 @@ import android.view.autofill.AutofillManager
import com.bitwarden.authenticatorbridge.util.generateSecretKey
import com.bitwarden.core.data.manager.dispatcher.DispatcherManager
import com.bitwarden.data.manager.flightrecorder.FlightRecorderManager
import com.bitwarden.network.model.PolicyTypeJson
import com.bitwarden.network.model.SyncResponseJson
import com.bitwarden.policies.PolicyType
import com.bitwarden.policies.PolicyView
import com.bitwarden.ui.platform.feature.settings.appearance.model.AppTheme
import com.x8bit.bitwarden.BuildConfig
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
@@ -374,7 +374,7 @@ class SettingsRepositoryImpl(
init {
policyManager
.getActivePoliciesFlow(type = PolicyTypeJson.MAXIMUM_VAULT_TIMEOUT)
.getActivePoliciesFlow(type = PolicyType.MAXIMUM_VAULT_TIMEOUT)
.onEach { updateVaultUnlockSettingsIfNecessary(it) }
.launchIn(unconfinedScope)
}
@@ -676,7 +676,7 @@ class SettingsRepositoryImpl(
* settings to determine whether to update the user's settings.
*/
private fun updateVaultUnlockSettingsIfNecessary(
policies: List<SyncResponseJson.Policy>,
policies: List<PolicyView>,
) {
// The vault timeout policy can only be implemented in organizations that have
// the single organization policy, meaning that if this is enabled, the user is

View File

@@ -1,75 +0,0 @@
package com.x8bit.bitwarden.data.platform.repository.util
import java.net.URLEncoder
private const val OTPAUTH_PREFIX = "otpauth://totp/"
private const val STEAM_PREFIX = "steam://"
/**
* Utility for ensuring that a given TOTP string is a properly formatted otpauth:// or steam:// URI.
* If the input TOTP is already a valid URI, it is returned as-is.
* If the TOTP is manually entered and does not follow the URI format,
* this function reconstructs it using the provided issuer and username.
*
* Uses this as a guide for format
* https://github.com/google/google-authenticator/wiki/Key-Uri-Format
*
* Replace spaces (+) with %20, and encode the label and issuer (per the above link)
* https://datatracker.ietf.org/doc/html/rfc5234
* */
fun String?.sanitizeTotpUri(
issuer: String?,
username: String?,
): String? {
if (this.isNullOrBlank()) return null
return if (this.startsWith(OTPAUTH_PREFIX) || this.startsWith(STEAM_PREFIX)) {
// ✅ Already a valid TOTP or Steam URI, return as-is.
this
} else {
// ❌ Manually entered secret, reconstruct as otpauth://totp/ URI.
// Trim spaces from issuer and username
val trimmedIssuer = issuer
?.trim()
?.takeIf { it.isNotEmpty() }
val trimmedUsername = username
?.trim()
?.takeIf { it.isNotEmpty() }
// Determine raw label correctly (avoid empty `:` issue)
val rawLabel = if (trimmedIssuer != null && trimmedUsername != null) {
"$trimmedIssuer:$trimmedUsername"
} else {
trimmedUsername
}
// Encode label only if it's not empty
val encodedLabel = rawLabel
?.let {
URLEncoder
.encode(it, "UTF-8")
.replace("+", "%20")
}
.orEmpty()
// Encode issuer separately for the query parameter
val encodedIssuer = trimmedIssuer?.let {
URLEncoder
.encode(it, "UTF-8")
.replace("+", "%20")
}
// Construct the issuer query parameter.
val issuerParameter = encodedIssuer
?.let { "&issuer=$it" }
.orEmpty()
// Remove spaces from the manually entered secret
val sanitizedSecret = this.filterNot { it.isWhitespace() }
// Construct final TOTP URI
"$OTPAUTH_PREFIX$encodedLabel?secret=$sanitizedSecret$issuerParameter"
}
}

View File

@@ -1,6 +1,7 @@
package com.x8bit.bitwarden.data.platform.util
import com.bitwarden.network.exception.CookieRedirectException
import com.bitwarden.network.exception.LocalNetworkAccessException
/**
* Returns a user-friendly error message if this [Throwable] is an allow-listed
@@ -8,6 +9,7 @@ import com.bitwarden.network.exception.CookieRedirectException
*/
val Throwable.userFriendlyMessage: String?
get() = when (this) {
is LocalNetworkAccessException -> message
is CookieRedirectException -> message
else -> null
}

View File

@@ -55,7 +55,7 @@ class GeneratorRepositoryImpl(
private val vaultSdkSource: VaultSdkSource,
private val passwordHistoryDiskSource: PasswordHistoryDiskSource,
private val reviewPromptManager: ReviewPromptManager,
dispatcherManager: DispatcherManager,
private val dispatcherManager: DispatcherManager,
) : GeneratorRepository {
private val scope = CoroutineScope(dispatcherManager.io)
@@ -193,7 +193,7 @@ class GeneratorRepositoryImpl(
override suspend fun generateForwardedServiceUsername(
forwardedServiceGeneratorRequest: UsernameGeneratorRequest.Forwarded,
): GeneratedForwardedServiceUsernameResult = withContext(scope.coroutineContext) {
): GeneratedForwardedServiceUsernameResult = withContext(dispatcherManager.io) {
generatorSdkSource.generateForwardedServiceEmail(forwardedServiceGeneratorRequest)
.fold(
onSuccess = { generatedEmail ->

View File

@@ -21,6 +21,7 @@ class ScopedVaultSdkSourceImpl(
sdkPlatformApiFactory: SdkPlatformApiFactory,
vaultSdkSource: VaultSdkSource = VaultSdkSourceImpl(
sdkClientManager = SdkClientManagerImpl(
dispatcherManager = dispatcherManager,
// We do not want to have the real NativeLibraryManager used here to avoid
// initializing the library twice.
nativeLibraryManager = object : NativeLibraryManager {

View File

@@ -12,6 +12,7 @@ import com.bitwarden.network.model.ArchiveCipherResponseJson
import com.bitwarden.network.model.AttachmentJsonResponse
import com.bitwarden.network.model.CreateCipherInOrganizationJsonRequest
import com.bitwarden.network.model.CreateCipherResponseJson
import com.bitwarden.network.model.GetCipherResponse
import com.bitwarden.network.model.ShareCipherJsonRequest
import com.bitwarden.network.model.UnarchiveCipherResponseJson
import com.bitwarden.network.model.UpdateCipherCollectionsJsonRequest
@@ -48,7 +49,6 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import retrofit2.HttpException
import java.io.File
import java.time.Clock
@@ -763,6 +763,7 @@ class CipherManagerImpl(
* are met. If the resource cannot be found cloud-side, and it was updated, delete it from disk
* for now.
*/
@Suppress("CyclomaticComplexMethod")
private suspend fun syncCipherIfNecessary(syncCipherUpsertData: SyncCipherUpsertData) {
val userId = syncCipherUpsertData.userId
val cipherId = syncCipherUpsertData.cipherId
@@ -817,15 +818,22 @@ class CipherManagerImpl(
ciphersService
.getCipher(cipherId = cipherId)
.fold(
onSuccess = { vaultDiskSource.saveCipher(userId = userId, cipher = it) },
onFailure = {
// Delete any updates if it's missing from the server
val httpException = it as? HttpException
@Suppress("MagicNumber")
if (httpException?.code() == 404 && isUpdate) {
vaultDiskSource.deleteCipher(userId = userId, cipherId = cipherId)
onSuccess = { response ->
when (response) {
is GetCipherResponse.NotFound -> {
if (isUpdate) {
vaultDiskSource.deleteCipher(userId = userId, cipherId = cipherId)
}
}
is GetCipherResponse.Success -> {
vaultDiskSource.saveCipher(userId = userId, cipher = response.cipher)
}
}
},
onFailure = {
// no-op
},
)
}
}

View File

@@ -8,6 +8,7 @@ import com.bitwarden.core.data.util.flatMap
import com.bitwarden.data.manager.file.FileManager
import com.bitwarden.network.model.CreateFileSendResponse
import com.bitwarden.network.model.CreateSendJsonResponse
import com.bitwarden.network.model.GetSendResponse
import com.bitwarden.network.model.UpdateSendResponseJson
import com.bitwarden.network.service.SendsService
import com.bitwarden.send.Send
@@ -32,7 +33,6 @@ import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import retrofit2.HttpException
/**
* The default implementation of the [SendManager].
@@ -291,15 +291,22 @@ class SendManagerImpl(
sendsService
.getSend(sendId = sendId)
.fold(
onSuccess = { vaultDiskSource.saveSend(userId = userId, send = it) },
onFailure = {
// Delete any updates if it's missing from the server
val httpException = it as? HttpException
@Suppress("MagicNumber")
if (httpException?.code() == 404 && isUpdate) {
vaultDiskSource.deleteSend(userId = userId, sendId = sendId)
onSuccess = { response ->
when (response) {
is GetSendResponse.NotFound -> {
if (isUpdate) {
vaultDiskSource.deleteSend(userId = userId, sendId = sendId)
}
}
is GetSendResponse.Success -> {
vaultDiskSource.saveSend(userId = userId, send = response.send)
}
}
},
onFailure = {
// no-op
},
)
}
}

View File

@@ -709,6 +709,7 @@ class VaultLockManagerImpl(
is InitUserCryptoMethod.KeyConnectorUrl,
is InitUserCryptoMethod.Pin,
is InitUserCryptoMethod.PinEnvelope,
is InitUserCryptoMethod.PinState,
-> return
}

View File

@@ -8,10 +8,11 @@ import com.bitwarden.core.data.util.asFailure
import com.bitwarden.core.data.util.asSuccess
import com.bitwarden.core.data.util.flatMap
import com.bitwarden.network.model.BulkShareCiphersJsonRequest
import com.bitwarden.network.model.PolicyTypeJson
import com.bitwarden.network.model.OrganizationStatusType
import com.bitwarden.network.model.SyncResponseJson
import com.bitwarden.network.model.toCipherWithIdJsonRequest
import com.bitwarden.network.service.CiphersService
import com.bitwarden.policies.PolicyType
import com.bitwarden.vault.CipherView
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
import com.x8bit.bitwarden.data.platform.datasource.disk.SettingsDiskSource
@@ -144,6 +145,7 @@ class VaultMigrationManagerImpl(
val orgName = authDiskSource
.getOrganizations(userId = userId)
?.filter { it.status == OrganizationStatusType.CONFIRMED }
?.firstOrNull { it.id == orgId }
?.name
?: return@update VaultMigrationData.NoMigrationRequired
@@ -167,9 +169,7 @@ class VaultMigrationManagerImpl(
hasPersonalCiphers: Boolean,
isNetworkConnected: Boolean,
): Boolean =
policyManager
.getActivePolicies(PolicyTypeJson.PERSONAL_OWNERSHIP)
.any() &&
policyManager.getActivePolicies(PolicyType.ORGANIZATION_DATA_OWNERSHIP).any() &&
featureFlagManager.getFeatureFlag(FlagKey.MigrateMyVaultToMyItems) &&
isNetworkConnected &&
hasPersonalCiphers

View File

@@ -7,6 +7,7 @@ import com.bitwarden.core.data.repository.model.DataState
import com.bitwarden.core.data.repository.util.combineDataStates
import com.bitwarden.core.data.repository.util.map
import com.bitwarden.core.data.repository.util.updateToPendingOrLoading
import com.bitwarden.network.model.OrganizationStatusType
import com.bitwarden.network.model.SyncResponseJson
import com.bitwarden.network.service.SyncService
import com.bitwarden.network.util.isNoConnectionError
@@ -14,6 +15,7 @@ import com.bitwarden.vault.DecryptCipherListResult
import com.bitwarden.vault.FolderView
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
import com.x8bit.bitwarden.data.auth.manager.UserLogoutManager
import com.x8bit.bitwarden.data.autofill.manager.FillAssistManager
import com.x8bit.bitwarden.data.auth.manager.UserStateManager
import com.x8bit.bitwarden.data.auth.repository.model.LogoutReason
import com.x8bit.bitwarden.data.auth.repository.util.toUpdatedUserStateJson
@@ -78,6 +80,7 @@ class VaultSyncManagerImpl(
private val authDiskSource: AuthDiskSource,
private val vaultDiskSource: VaultDiskSource,
private val vaultSdkSource: VaultSdkSource,
private val fillAssistManager: FillAssistManager,
private val userLogoutManager: UserLogoutManager,
private val userStateManager: UserStateManager,
private val vaultLockManager: VaultLockManager,
@@ -340,6 +343,7 @@ class VaultSyncManagerImpl(
lastSyncTime = clock.instant(),
)
vaultDiskSource.replaceVaultData(userId = userId, vault = syncResponse)
fillAssistManager.syncIfNecessary()
val itemsAvailable = syncResponse.ciphers?.isNotEmpty() == true
SyncVaultDataResult.Success(itemsAvailable = itemsAvailable)
}
@@ -469,6 +473,9 @@ class VaultSyncManagerImpl(
data = collections.sortAlphabeticallyByTypeAndOrganization(
userOrganizations = authDiskSource
.getOrganizations(userId = userId)
?.filter { org ->
org.status == OrganizationStatusType.CONFIRMED
}
.orEmpty(),
),
)

View File

@@ -44,6 +44,7 @@ import com.x8bit.bitwarden.data.vault.manager.VaultLockManager
import com.x8bit.bitwarden.data.vault.manager.VaultLockManagerImpl
import com.x8bit.bitwarden.data.vault.manager.VaultMigrationManager
import com.x8bit.bitwarden.data.vault.manager.VaultMigrationManagerImpl
import com.x8bit.bitwarden.data.autofill.manager.FillAssistManager
import com.x8bit.bitwarden.data.vault.manager.VaultSyncManager
import com.x8bit.bitwarden.data.vault.manager.VaultSyncManagerImpl
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
@@ -224,6 +225,7 @@ object VaultManagerModule {
@Provides
@Singleton
fun provideVaultSyncManager(
fillAssistManager: FillAssistManager,
syncService: SyncService,
settingsDiskSource: SettingsDiskSource,
authDiskSource: AuthDiskSource,
@@ -237,6 +239,7 @@ object VaultManagerModule {
pushManager: PushManager,
dispatcherManager: DispatcherManager,
): VaultSyncManager = VaultSyncManagerImpl(
fillAssistManager = fillAssistManager,
syncService = syncService,
settingsDiskSource = settingsDiskSource,
authDiskSource = authDiskSource,

View File

@@ -14,6 +14,7 @@ val InitUserCryptoMethod.logTag: String
is InitUserCryptoMethod.KeyConnector -> "Key Connector"
is InitUserCryptoMethod.Pin -> "Pin"
is InitUserCryptoMethod.PinEnvelope -> "Pin Envelope"
is InitUserCryptoMethod.PinState -> "Pin State"
is InitUserCryptoMethod.KeyConnectorUrl -> "Key Connector Url"
is InitUserCryptoMethod.MasterPasswordUnlock -> "Master Password Unlock"
}

View File

@@ -739,9 +739,8 @@ fun CipherTypeJson.toSdkCipherType(): CipherType =
CipherTypeJson.IDENTITY -> CipherType.IDENTITY
CipherTypeJson.SSH_KEY -> CipherType.SSH_KEY
CipherTypeJson.BANK_ACCOUNT -> CipherType.BANK_ACCOUNT
CipherTypeJson.DRIVERS_LICENSE,
CipherTypeJson.PASSPORT,
-> throw IllegalArgumentException("SDK mapping not yet available for $this")
CipherTypeJson.DRIVERS_LICENSE -> CipherType.DRIVERS_LICENSE
CipherTypeJson.PASSPORT -> CipherType.PASSPORT
}
/**

View File

@@ -0,0 +1,47 @@
package com.x8bit.bitwarden.data.vault.repository.util
import com.bitwarden.network.model.OrganizationStatusType
import com.bitwarden.network.model.OrganizationType
import com.bitwarden.network.model.SyncResponseJson
import com.bitwarden.organizations.OrganizationUserStatusType
import com.bitwarden.organizations.OrganizationUserType
import com.bitwarden.policies.OrganizationUserPolicyContext
/**
* Converts a list of network [SyncResponseJson.Profile.Organization] models to a list of SDK
* [OrganizationUserPolicyContext].
*/
@Suppress("MaxLineLength")
fun List<SyncResponseJson.Profile.Organization>.toSdkOrganizationPolicyContexts(): List<OrganizationUserPolicyContext> =
this.map { it.toSdkOrganizationPolicyContext() }
/**
* Converts a network [SyncResponseJson.Profile.Organization] model to an SDK
* [OrganizationUserPolicyContext].
*/
@Suppress("MaxLineLength")
fun SyncResponseJson.Profile.Organization.toSdkOrganizationPolicyContext(): OrganizationUserPolicyContext =
OrganizationUserPolicyContext(
id = this.id,
status = this.status.toSdkOrganizationUserStatusType,
role = this.type.toSdkOrganizationUserType,
enabled = this.isEnabled,
usePolicies = this.shouldUsePolicies,
isProviderUser = this.isProviderUser,
)
private val OrganizationStatusType.toSdkOrganizationUserStatusType: OrganizationUserStatusType
get() = when (this) {
OrganizationStatusType.REVOKED -> OrganizationUserStatusType.REVOKED
OrganizationStatusType.INVITED -> OrganizationUserStatusType.INVITED
OrganizationStatusType.ACCEPTED -> OrganizationUserStatusType.ACCEPTED
OrganizationStatusType.CONFIRMED -> OrganizationUserStatusType.CONFIRMED
}
private val OrganizationType.toSdkOrganizationUserType: OrganizationUserType
get() = when (this) {
OrganizationType.OWNER -> OrganizationUserType.OWNER
OrganizationType.ADMIN -> OrganizationUserType.ADMIN
OrganizationType.USER -> OrganizationUserType.USER
OrganizationType.CUSTOM -> OrganizationUserType.CUSTOM
}

View File

@@ -0,0 +1,55 @@
package com.x8bit.bitwarden.data.vault.repository.util
import com.bitwarden.network.model.PolicyTypeJson
import com.bitwarden.network.model.SyncResponseJson
import com.bitwarden.policies.PolicyType
import com.bitwarden.policies.PolicyView
import kotlinx.serialization.json.Json
/**
* Converts a list of network [SyncResponseJson.Policy] models to a list of SDK [PolicyView].
*/
fun List<SyncResponseJson.Policy>.toSdkPolicyViews(): List<PolicyView> =
this.map { it.toSdkPolicyView() }
/**
* Converts a network [SyncResponseJson.Policy] model to an SDK [PolicyView].
*/
private fun SyncResponseJson.Policy.toSdkPolicyView(): PolicyView =
PolicyView(
organizationId = this.organizationId,
id = this.id,
type = this.type.toSdkPolicyType,
enabled = this.isEnabled,
data = this.data?.let { Json.encodeToString(it) },
revisionDate = this.revisionDate,
)
private val PolicyTypeJson.toSdkPolicyType: PolicyType
get() = when (this) {
PolicyTypeJson.TWO_FACTOR_AUTHENTICATION -> PolicyType.TWO_FACTOR_AUTHENTICATION
PolicyTypeJson.MASTER_PASSWORD -> PolicyType.MASTER_PASSWORD
PolicyTypeJson.PASSWORD_GENERATOR -> PolicyType.PASSWORD_GENERATOR
PolicyTypeJson.ONLY_ORG -> PolicyType.SINGLE_ORG
PolicyTypeJson.REQUIRE_SSO -> PolicyType.REQUIRE_SSO
PolicyTypeJson.PERSONAL_OWNERSHIP -> PolicyType.ORGANIZATION_DATA_OWNERSHIP
PolicyTypeJson.DISABLE_SEND -> PolicyType.DISABLE_SEND
PolicyTypeJson.SEND_OPTIONS -> PolicyType.SEND_OPTIONS
PolicyTypeJson.RESET_PASSWORD -> PolicyType.RESET_PASSWORD
PolicyTypeJson.MAXIMUM_VAULT_TIMEOUT -> PolicyType.MAXIMUM_VAULT_TIMEOUT
PolicyTypeJson.DISABLE_PERSONAL_VAULT_EXPORT -> PolicyType.DISABLE_PERSONAL_VAULT_EXPORT
PolicyTypeJson.ACTIVATE_AUTOFILL -> PolicyType.ACTIVATE_AUTOFILL
PolicyTypeJson.AUTOMATIC_APP_LOG_IN -> PolicyType.AUTOMATIC_APP_LOG_IN
PolicyTypeJson.FREE_FAMILIES_SPONSORSHIP_POLICY -> PolicyType.FREE_FAMILIES_SPONSORSHIP
PolicyTypeJson.REMOVE_UNLOCK_WITH_PIN -> PolicyType.REMOVE_UNLOCK_WITH_PIN
PolicyTypeJson.RESTRICT_ITEM_TYPES -> PolicyType.RESTRICTED_ITEM_TYPES
PolicyTypeJson.URI_MATCH_DEFAULTS -> PolicyType.URI_MATCH_DEFAULTS
PolicyTypeJson.AUTOTYPE_DEFAULT_SETTING -> PolicyType.AUTOTYPE_DEFAULT_SETTING
PolicyTypeJson.AUTOMATIC_USER_CONFIRMATION -> PolicyType.AUTOMATIC_USER_CONFIRMATION
PolicyTypeJson.BLOCK_CLAIMED_DOMAIN_ACCOUNT_CREATION -> {
PolicyType.BLOCK_CLAIMED_DOMAIN_ACCOUNT_CREATION
}
PolicyTypeJson.ORGANIZATION_USER_NOTIFICATION -> PolicyType.ORGANIZATION_USER_NOTIFICATION
PolicyTypeJson.SEND_CONTROLS -> PolicyType.SEND_CONTROLS
}

View File

@@ -23,6 +23,7 @@ import com.bitwarden.cxf.ui.composition.LocalCredentialExchangeRequestValidator
import com.bitwarden.cxf.validator.CredentialExchangeRequestValidator
import com.bitwarden.cxf.validator.dsl.credentialExchangeRequestValidator
import com.bitwarden.ui.platform.composition.LocalCardTextAnalyzer
import com.bitwarden.ui.platform.composition.LocalClock
import com.bitwarden.ui.platform.composition.LocalExitManager
import com.bitwarden.ui.platform.composition.LocalIntentManager
import com.bitwarden.ui.platform.composition.LocalQrCodeAnalyzer
@@ -134,11 +135,6 @@ val LocalBiometricsManager: ProvidableCompositionLocal<BiometricsManager> = comp
error("CompositionLocal BiometricsManager not present")
}
/**
* Provides access to the clock throughout the app.
*/
val LocalClock: ProvidableCompositionLocal<Clock> = compositionLocalOf { Clock.systemDefaultZone() }
/**
* Provides access to the Auth Tab launchers throughout the app.
*/

View File

@@ -0,0 +1,40 @@
@file:OmitFromCoverage
package com.x8bit.bitwarden.ui.platform.feature.localnetworkaccess
import androidx.navigation.NavController
import androidx.navigation.NavGraphBuilder
import com.bitwarden.annotation.OmitFromCoverage
import com.bitwarden.ui.platform.base.util.composableWithSlideTransitions
import kotlinx.serialization.Serializable
/**
* The type-safe route for the local network access screen.
*/
@OmitFromCoverage
@Serializable
data object LocalNetworkAccessRoute
/**
* Add the local network access screen to the nav graph.
*/
fun NavGraphBuilder.localNetworkAccessDestination(
onDismiss: () -> Unit,
onSplashScreenRemoved: () -> Unit,
) {
composableWithSlideTransitions<LocalNetworkAccessRoute> {
LocalNetworkAccessScreen(onDismiss = onDismiss)
// If we are displaying the local network access screen, then we can just hide
// the splash screen.
onSplashScreenRemoved()
}
}
/**
* Navigate to the local network access screen.
*/
fun NavController.navigateToLocalNetworkAccess() {
this.navigate(route = LocalNetworkAccessRoute) {
launchSingleTop = true
}
}

Some files were not shown because too many files have changed in this diff Show More