mirror of
https://github.com/bitwarden/android.git
synced 2025-12-10 09:56:45 -06:00
Compare commits
524 Commits
v2025.7.0-
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1503e3f769 | ||
|
|
6840a6c207 | ||
|
|
d32e767c62 | ||
|
|
4a874668f2 | ||
|
|
cd27fe339d | ||
|
|
2eb8ad4221 | ||
|
|
28db795790 | ||
|
|
8c6782dcb1 | ||
|
|
127809b8df | ||
|
|
ca13e615ec | ||
|
|
5e3e8a04aa | ||
|
|
8077895eb8 | ||
|
|
33e9313c6c | ||
|
|
593bfbf8cf | ||
|
|
4905358adb | ||
|
|
02733f785b | ||
|
|
8baa4bf041 | ||
|
|
4d20453d0f | ||
|
|
4b951a1df2 | ||
|
|
9349b235bc | ||
|
|
e9ab5f2def | ||
|
|
3bef282426 | ||
|
|
e1bb3a4b5d | ||
|
|
1904c4ffb9 | ||
|
|
26e7178300 | ||
|
|
2c01abda46 | ||
|
|
b86cbfcd87 | ||
|
|
3f303d3f39 | ||
|
|
ca7a65fc95 | ||
|
|
f02b374e98 | ||
|
|
1a90860080 | ||
|
|
adf83cd315 | ||
|
|
489c0ea8d6 | ||
|
|
9831358a8b | ||
|
|
8bdbccd8de | ||
|
|
a75d904317 | ||
|
|
a395f28eba | ||
|
|
53e358d7b3 | ||
|
|
663eb3641f | ||
|
|
ab305b2631 | ||
|
|
946b0784e0 | ||
|
|
167a46a073 | ||
|
|
7b491d3c3c | ||
|
|
7918abdccf | ||
|
|
5ec0a1986d | ||
|
|
839e9e8a1a | ||
|
|
979237b751 | ||
|
|
621f97d161 | ||
|
|
d81b0005ee | ||
|
|
794b27a750 | ||
|
|
169b21cfdb | ||
|
|
4623a4f079 | ||
|
|
21afa81322 | ||
|
|
55c7ab4cee | ||
|
|
7a40bfe522 | ||
|
|
0c234ee0aa | ||
|
|
7b0b93a204 | ||
|
|
473416c1b4 | ||
|
|
f3646790e3 | ||
|
|
35b87f4390 | ||
|
|
7120eefc94 | ||
|
|
5eb56cafaa | ||
|
|
b2d94fae40 | ||
|
|
ad748eef7f | ||
|
|
8010e8d6c3 | ||
|
|
7a6a493f24 | ||
|
|
4032d2bb5c | ||
|
|
e2c9aae9c1 | ||
|
|
56566b958c | ||
|
|
06bf603ec8 | ||
|
|
79d6da0a61 | ||
|
|
2d2ea9acee | ||
|
|
05d6fe1ba1 | ||
|
|
1024f77ddf | ||
|
|
50e50eb08c | ||
|
|
bd98df6eb9 | ||
|
|
9baec6e6a5 | ||
|
|
efd15b027c | ||
|
|
b715a51188 | ||
|
|
94ed32790f | ||
|
|
dca97e0c8e | ||
|
|
aceb96d18f | ||
|
|
510072b34f | ||
|
|
7324be04f4 | ||
|
|
bfbe47f48f | ||
|
|
2bb06063c7 | ||
|
|
ed47ff4d18 | ||
|
|
448ba97ae2 | ||
|
|
14e833247d | ||
|
|
4b7fcdb6ea | ||
|
|
0959284e6f | ||
|
|
1f24ca7de1 | ||
|
|
dc79176274 | ||
|
|
a631d6822a | ||
|
|
845a5dec22 | ||
|
|
b1195b5f46 | ||
|
|
8de3a07715 | ||
|
|
9c4bd2ee14 | ||
|
|
6dad8c4def | ||
|
|
bc74337eae | ||
|
|
d86443c6dd | ||
|
|
d07b119802 | ||
|
|
dbf2e9f68a | ||
|
|
9ddfd376a9 | ||
|
|
dd1dbd0b97 | ||
|
|
f6be363e98 | ||
|
|
600744538d | ||
|
|
de33ba021b | ||
|
|
290f59441f | ||
|
|
94c51cacf9 | ||
|
|
6f27642a30 | ||
|
|
2ad3014da2 | ||
|
|
e6dc8e02f8 | ||
|
|
c16d31fb33 | ||
|
|
43d7b84d0a | ||
|
|
c0f8307361 | ||
|
|
064a98f86b | ||
|
|
e3b111c383 | ||
|
|
52304a266e | ||
|
|
51c23ec464 | ||
|
|
7d7951d4ca | ||
|
|
78b1676745 | ||
|
|
be27c76bd3 | ||
|
|
38bdda0a41 | ||
|
|
c61fec176a | ||
|
|
bb11b17823 | ||
|
|
562b48d689 | ||
|
|
c3496ca60f | ||
|
|
a8f8450ec9 | ||
|
|
47628a6da2 | ||
|
|
5a540a3460 | ||
|
|
92cfce1224 | ||
|
|
4597337500 | ||
|
|
e610a7541d | ||
|
|
ae4b398258 | ||
|
|
0482f9eb4d | ||
|
|
9f4bd70c8d | ||
|
|
9874aad65a | ||
|
|
97bb93c18e | ||
|
|
31e7e05eda | ||
|
|
afeeb494da | ||
|
|
d5912a5dc3 | ||
|
|
13fa8a1ed0 | ||
|
|
5a145ee163 | ||
|
|
74b9a12e19 | ||
|
|
71e830bb09 | ||
|
|
8f3f1fa3ba | ||
|
|
9bd35ccca5 | ||
|
|
74aa0a78ec | ||
|
|
ae3470c598 | ||
|
|
a70b2172cb | ||
|
|
714f7cfadc | ||
|
|
53d04375b1 | ||
|
|
3ace095b86 | ||
|
|
8a90d77fd7 | ||
|
|
4b96007a77 | ||
|
|
03df341a1e | ||
|
|
d966423087 | ||
|
|
f7cbcd21ec | ||
|
|
188ddf98f4 | ||
|
|
b8f4129691 | ||
|
|
b8482de96c | ||
|
|
9e860008e8 | ||
|
|
af737b3f07 | ||
|
|
5b5176db40 | ||
|
|
e7365b355f | ||
|
|
433b3b6fb0 | ||
|
|
318307c377 | ||
|
|
912eba14d6 | ||
|
|
837dd27106 | ||
|
|
a75e938070 | ||
|
|
054afab2cf | ||
|
|
c015c8aa43 | ||
|
|
4161020e6c | ||
|
|
5543bc6ab5 | ||
|
|
5cdee938bf | ||
|
|
62f76a4f8b | ||
|
|
7ea87505a4 | ||
|
|
c6f132d5f7 | ||
|
|
0604d15d7d | ||
|
|
5706ca2ba3 | ||
|
|
de8c344b46 | ||
|
|
957460f403 | ||
|
|
2b88743bea | ||
|
|
5243ed27d3 | ||
|
|
a7bbb81b31 | ||
|
|
2d2b740ae1 | ||
|
|
81fa635430 | ||
|
|
a1cb948257 | ||
|
|
5bb7abbf5a | ||
|
|
d98ff6478f | ||
|
|
44c373a354 | ||
|
|
3d493bb9d0 | ||
|
|
07b8115d7a | ||
|
|
9ced8647a3 | ||
|
|
b3c3365b5a | ||
|
|
266c16958d | ||
|
|
340b4f25f7 | ||
|
|
572d3357ee | ||
|
|
3a4f1d719f | ||
|
|
bebf94796c | ||
|
|
10a92dd2a3 | ||
|
|
d306813d1f | ||
|
|
97c4cd705b | ||
|
|
9fee973563 | ||
|
|
202dd65229 | ||
|
|
7849bbbb0a | ||
|
|
cd9c7f98e7 | ||
|
|
0c9530472f | ||
|
|
2636a4f93a | ||
|
|
ca474b272a | ||
|
|
acc9113f9a | ||
|
|
2eb829a25b | ||
|
|
04a1d4118f | ||
|
|
9f63cede11 | ||
|
|
a93037d63e | ||
|
|
4e57f306d3 | ||
|
|
1638a20bf0 | ||
|
|
874edfad69 | ||
|
|
0469731fba | ||
|
|
0abfa5bb97 | ||
|
|
13e6728d46 | ||
|
|
116bfd6351 | ||
|
|
6ca8a39355 | ||
|
|
24a54ce214 | ||
|
|
8d76ef50d3 | ||
|
|
22114d588a | ||
|
|
81245cf3e5 | ||
|
|
fec6479f6a | ||
|
|
a02a84ee08 | ||
|
|
df63bb4b6c | ||
|
|
2a134c619d | ||
|
|
5c5bd25d16 | ||
|
|
2363b0d619 | ||
|
|
f0946e05d5 | ||
|
|
24ccebd822 | ||
|
|
fd555e92d3 | ||
|
|
eab2c17614 | ||
|
|
617be1fd95 | ||
|
|
d5d4caea62 | ||
|
|
7bf4acbb28 | ||
|
|
2694138aa1 | ||
|
|
d2645863ea | ||
|
|
3edd5bd852 | ||
|
|
4cd5a1ed56 | ||
|
|
c122f83fa6 | ||
|
|
b558d70703 | ||
|
|
89ad7818f9 | ||
|
|
e91ba77105 | ||
|
|
cc685b2307 | ||
|
|
d14fba0c01 | ||
|
|
e965134697 | ||
|
|
df34db52e4 | ||
|
|
cf5d208516 | ||
|
|
d74040e7b9 | ||
|
|
8a2bcfade8 | ||
|
|
bc1dd730ec | ||
|
|
fa5053b5cc | ||
|
|
ad46d8d7c0 | ||
|
|
98530ed33d | ||
|
|
e57af949fc | ||
|
|
6f6aacabfb | ||
|
|
b0e0b44671 | ||
|
|
d53f3f313c | ||
|
|
4f244c52fa | ||
|
|
b4a31764c4 | ||
|
|
f4569cef2b | ||
|
|
b4926b72d9 | ||
|
|
0f899df83c | ||
|
|
ff03f49f43 | ||
|
|
2756bd9fde | ||
|
|
a39f83349f | ||
|
|
7d3ed2af88 | ||
|
|
8de465381e | ||
|
|
f22f4399be | ||
|
|
766e6b1bb9 | ||
|
|
0fb364128e | ||
|
|
0cbce39499 | ||
|
|
f954b0b941 | ||
|
|
cfd0a5b8a5 | ||
|
|
d61e1cb6f1 | ||
|
|
b31983da8b | ||
|
|
e22d309423 | ||
|
|
9b53095b5e | ||
|
|
c6814c8870 | ||
|
|
7710ad8a73 | ||
|
|
80b3a7e675 | ||
|
|
8235045dad | ||
|
|
481a8c8fbc | ||
|
|
1dc6ea2227 | ||
|
|
6554234898 | ||
|
|
e990397b29 | ||
|
|
417835ef3f | ||
|
|
39a6dd1c4b | ||
|
|
4093e61b09 | ||
|
|
c4adf3ad42 | ||
|
|
417a1494e3 | ||
|
|
ef39ea6d5d | ||
|
|
f6c20e08d1 | ||
|
|
987e065dd7 | ||
|
|
ba7ee04281 | ||
|
|
808d57edc5 | ||
|
|
3356925c7a | ||
|
|
0487d95122 | ||
|
|
0834a7a883 | ||
|
|
2b0e8f9941 | ||
|
|
0702078b04 | ||
|
|
46c7e79039 | ||
|
|
1d6e733c08 | ||
|
|
a298b85374 | ||
|
|
fe79ea4822 | ||
|
|
4c50f873e2 | ||
|
|
2bd4834b14 | ||
|
|
393931a5c6 | ||
|
|
fe6346013b | ||
|
|
41e499fdf5 | ||
|
|
aa39e6c6be | ||
|
|
eec4233486 | ||
|
|
58db64da1a | ||
|
|
a7d0d6844d | ||
|
|
249e1d3a5c | ||
|
|
d8f3e7af92 | ||
|
|
1c4e4dcaf4 | ||
|
|
9adc25471e | ||
|
|
ec6562336c | ||
|
|
f402391ed8 | ||
|
|
9b074f2106 | ||
|
|
3fa33faa35 | ||
|
|
e1434dfe21 | ||
|
|
659bbc5169 | ||
|
|
dfa1f24c30 | ||
|
|
4f65c3f7d3 | ||
|
|
0f74c3dded | ||
|
|
f7139b8b91 | ||
|
|
2b35ac0d3a | ||
|
|
4a79d7e6c8 | ||
|
|
b9a496aa57 | ||
|
|
0a398839c4 | ||
|
|
aab8198457 | ||
|
|
d2d89b5a0f | ||
|
|
ddadd0135f | ||
|
|
dc198eaf72 | ||
|
|
ff23dc3ab2 | ||
|
|
191ff4c652 | ||
|
|
99ab2245f6 | ||
|
|
bc7e682941 | ||
|
|
517829e7b0 | ||
|
|
a1c6276092 | ||
|
|
bc67bf3dff | ||
|
|
bc5788556c | ||
|
|
45e20d8c9e | ||
|
|
a972a40a49 | ||
|
|
717d5665e0 | ||
|
|
bc0a18f250 | ||
|
|
2f72553454 | ||
|
|
e5a1546291 | ||
|
|
d8e319948c | ||
|
|
b3528249e9 | ||
|
|
5f42c9bb39 | ||
|
|
b010c9a29d | ||
|
|
3e55f561c9 | ||
|
|
277e4d8d6f | ||
|
|
32e8fb7d8e | ||
|
|
4a18e57cca | ||
|
|
070ef45087 | ||
|
|
a658cf890a | ||
|
|
d3dea3c9cb | ||
|
|
5ab0517bf3 | ||
|
|
e8b01c2d44 | ||
|
|
b34d873471 | ||
|
|
3c3d8710c9 | ||
|
|
20dea9b5ff | ||
|
|
44410efe56 | ||
|
|
a999592fb6 | ||
|
|
25a78f60ab | ||
|
|
a8546bb4eb | ||
|
|
6c6d4f2d91 | ||
|
|
7347d91fdd | ||
|
|
0a99359978 | ||
|
|
aca4b05b59 | ||
|
|
b0c7995cb7 | ||
|
|
af322b5d1f | ||
|
|
9fcfcc9e41 | ||
|
|
ff6b7b675d | ||
|
|
3164c29184 | ||
|
|
c5663431af | ||
|
|
4fb96cb782 | ||
|
|
36e06cdac7 | ||
|
|
3cf325becf | ||
|
|
584bdb6277 | ||
|
|
b2a9f4b455 | ||
|
|
b0b4379307 | ||
|
|
b9cc664efa | ||
|
|
e30e0ffbb4 | ||
|
|
2ffd71c69a | ||
|
|
3488ad6217 | ||
|
|
58005d908a | ||
|
|
a320e6ea61 | ||
|
|
5a23ceabc1 | ||
|
|
f4102bcd30 | ||
|
|
6d25c12271 | ||
|
|
ef03cdb2db | ||
|
|
474ec4907f | ||
|
|
a68fd8b44f | ||
|
|
3282992221 | ||
|
|
26252ebcdb | ||
|
|
a688693f43 | ||
|
|
3ed63ef5eb | ||
|
|
1e2bc4aa70 | ||
|
|
694865c213 | ||
|
|
29243c8f44 | ||
|
|
4e1dfcaeec | ||
|
|
75f3065085 | ||
|
|
402e399fd4 | ||
|
|
810cbc8da5 | ||
|
|
9bfbe0c087 | ||
|
|
d06c87beb3 | ||
|
|
9b120701eb | ||
|
|
e8f1242744 | ||
|
|
1c525b9dfc | ||
|
|
c613c2df86 | ||
|
|
9a9125321e | ||
|
|
2902b89402 | ||
|
|
93edbb61bf | ||
|
|
85bc76d0a6 | ||
|
|
db18e8012a | ||
|
|
db03c7d703 | ||
|
|
6ee7f9b80f | ||
|
|
fc88ca1ba8 | ||
|
|
3c033d4aa2 | ||
|
|
59c2261e7c | ||
|
|
b6aa0952b1 | ||
|
|
905e3248f2 | ||
|
|
72250dce90 | ||
|
|
60ee129e0b | ||
|
|
911bb40be8 | ||
|
|
308a8a564c | ||
|
|
337e751c05 | ||
|
|
f4c4e06dcc | ||
|
|
38b92133ff | ||
|
|
e381d72d5c | ||
|
|
87a61bbbbd | ||
|
|
7cc3c1c755 | ||
|
|
f614d6039f | ||
|
|
a6d622c3b9 | ||
|
|
b781acb1fa | ||
|
|
45f0ddc60f | ||
|
|
8876418177 | ||
|
|
67b64034ff | ||
|
|
79a232919a | ||
|
|
2fa9ea18b5 | ||
|
|
9b297286e5 | ||
|
|
376a62edaf | ||
|
|
01570c2555 | ||
|
|
4a3db4fea7 | ||
|
|
3c0818232f | ||
|
|
1799d0b716 | ||
|
|
cf896d6bf1 | ||
|
|
40dff74d3f | ||
|
|
ddd2d7fad5 | ||
|
|
b4efc0e59d | ||
|
|
4ffd41c33f | ||
|
|
a70f441064 | ||
|
|
867e2287dc | ||
|
|
912f734cae | ||
|
|
02b5cbb199 | ||
|
|
f589546e6a | ||
|
|
517198b265 | ||
|
|
91f1180be7 | ||
|
|
8589a37e5a | ||
|
|
e4678cc7df | ||
|
|
e665c386ff | ||
|
|
2f2ec71fc4 | ||
|
|
7b115df83a | ||
|
|
edd1763198 | ||
|
|
37d3ff30e4 | ||
|
|
258a58aa25 | ||
|
|
da5dcef41e | ||
|
|
7a578ff2c5 | ||
|
|
355facc36b | ||
|
|
c60f3131b6 | ||
|
|
bb950c8c59 | ||
|
|
c7df80ff00 | ||
|
|
d308b84943 | ||
|
|
79ad18877d | ||
|
|
4f51507e4b | ||
|
|
88fcd35d1a | ||
|
|
987639b2a3 | ||
|
|
d32b4c7c7e | ||
|
|
9ed59e61a3 | ||
|
|
3342ebf139 | ||
|
|
4050215145 | ||
|
|
3e0ee5fcd8 | ||
|
|
fcd7326f2c | ||
|
|
c94fe56b47 | ||
|
|
17287680d9 | ||
|
|
e4935318de | ||
|
|
f22643fec1 | ||
|
|
6454dc1a58 | ||
|
|
411e359600 | ||
|
|
e75d7844de | ||
|
|
25680f9255 | ||
|
|
628cb12081 | ||
|
|
710e35680b | ||
|
|
b5cd0c9d9d | ||
|
|
9995fa92f1 | ||
|
|
44aae70fe4 | ||
|
|
fca4ebe023 | ||
|
|
2d2a5e74da | ||
|
|
b53ca30974 | ||
|
|
8178a61dba | ||
|
|
f0bdc8ede3 | ||
|
|
145c19da22 | ||
|
|
39b1409cbd | ||
|
|
f26d54a2e2 | ||
|
|
33cfaa5e95 | ||
|
|
9274e0f349 | ||
|
|
46656d659e | ||
|
|
811f0f2757 | ||
|
|
8f783a43e4 | ||
|
|
b8f74cdefa | ||
|
|
5e6dcb5b58 | ||
|
|
c5a40a89d9 | ||
|
|
929233081c |
105
.claude/CLAUDE.md
Normal file
105
.claude/CLAUDE.md
Normal file
@ -0,0 +1,105 @@
|
|||||||
|
# Claude Guidelines
|
||||||
|
|
||||||
|
Core directives for maintaining code quality and consistency in the Bitwarden Android project.
|
||||||
|
|
||||||
|
## Core Directives
|
||||||
|
|
||||||
|
**You MUST follow these directives at all times.**
|
||||||
|
|
||||||
|
1. **Adhere to Architecture**: All code modifications MUST follow patterns in `docs/ARCHITECTURE.md`
|
||||||
|
2. **Follow Code Style**: ALWAYS follow `docs/STYLE_AND_BEST_PRACTICES.md`
|
||||||
|
3. **Error Handling**: Use Result types and sealed classes per architecture guidelines
|
||||||
|
4. **Best Practices**: Follow Kotlin idioms (immutability, appropriate data structures, coroutines)
|
||||||
|
5. **Document Everything**: All public APIs require KDoc documentation
|
||||||
|
6. **Dependency Management**: Use Hilt DI patterns as established in the project
|
||||||
|
7. **Use Established Patterns**: Leverage existing components before creating new ones
|
||||||
|
8. **File References**: Use file:line_number format when referencing code
|
||||||
|
|
||||||
|
## Code Quality Standards
|
||||||
|
|
||||||
|
### Module Organization
|
||||||
|
|
||||||
|
**Core Library Modules:**
|
||||||
|
- **`:core`** - Common utilities and managers shared across multiple modules
|
||||||
|
- **`:data`** - Data sources, database, data repositories
|
||||||
|
- **`:network`** - Networking interfaces, API clients, network utilities
|
||||||
|
- **`:ui`** - Reusable Bitwarden Composables, theming, UI utilities
|
||||||
|
|
||||||
|
**Application Modules:**
|
||||||
|
- **`:app`** - Password Manager application, feature screens, ViewModels, DI setup
|
||||||
|
- **`:authenticator`** - Authenticator application for 2FA/TOTP code generation
|
||||||
|
|
||||||
|
**Specialized Library Modules:**
|
||||||
|
- **`:authenticatorbridge`** - Communication bridge between :authenticator and :app
|
||||||
|
- **`:annotation`** - Custom annotations for code generation (Hilt, Room, etc.)
|
||||||
|
- **`:cxf`** - Android Credential Exchange (CXF/CXP) integration layer
|
||||||
|
|
||||||
|
### Patterns Enforcement
|
||||||
|
|
||||||
|
- **MVVM + UDF**: ViewModels with StateFlow, Compose UI
|
||||||
|
- **Hilt DI**: Interface injection, @HiltViewModel, @Inject constructor
|
||||||
|
- **Testing**: JUnit 5, MockK, Turbine for Flow testing
|
||||||
|
- **Error Handling**: Sealed Result types, no throws in business logic
|
||||||
|
|
||||||
|
## Security Requirements
|
||||||
|
|
||||||
|
**Every change must consider:**
|
||||||
|
- Zero-knowledge architecture preservation
|
||||||
|
- Proper encryption key handling (Android Keystore)
|
||||||
|
- Input validation and sanitization
|
||||||
|
- Secure data storage patterns
|
||||||
|
- Threat model implications
|
||||||
|
|
||||||
|
## Workflow Practices
|
||||||
|
|
||||||
|
### Before Implementation
|
||||||
|
|
||||||
|
1. Read relevant architecture documentation
|
||||||
|
2. Search for existing patterns to follow
|
||||||
|
3. Identify affected modules and dependencies
|
||||||
|
4. Consider security implications
|
||||||
|
|
||||||
|
### During Implementation
|
||||||
|
|
||||||
|
1. Follow existing code style in surrounding files
|
||||||
|
2. Write tests alongside implementation
|
||||||
|
3. Add KDoc to all public APIs
|
||||||
|
4. Validate against architecture guidelines
|
||||||
|
|
||||||
|
### After Implementation
|
||||||
|
|
||||||
|
1. Ensure all tests pass
|
||||||
|
2. Verify compilation succeeds
|
||||||
|
3. Review security considerations
|
||||||
|
4. Update relevant documentation
|
||||||
|
|
||||||
|
## Anti-Patterns
|
||||||
|
|
||||||
|
**Avoid these:**
|
||||||
|
- Creating new patterns when established ones exist
|
||||||
|
- Exception-based error handling in business logic
|
||||||
|
- Direct dependency access (use DI)
|
||||||
|
- Mutable state in ViewModels (use StateFlow)
|
||||||
|
- Missing null safety handling
|
||||||
|
- Undocumented public APIs
|
||||||
|
- Tight coupling between modules
|
||||||
|
|
||||||
|
## Communication & Decision-Making
|
||||||
|
|
||||||
|
Always clarify ambiguous requirements before implementing. Use specific questions:
|
||||||
|
- "Should this use [Approach A] or [Approach B]?"
|
||||||
|
- "This affects [X]. Proceed or review first?"
|
||||||
|
- "Expected behavior for [specific requirement]?"
|
||||||
|
|
||||||
|
Defer high-impact decisions to the user:
|
||||||
|
- Architecture/module changes, public API modifications
|
||||||
|
- Security mechanisms, database migrations
|
||||||
|
- Third-party library additions
|
||||||
|
|
||||||
|
## Reference Documentation
|
||||||
|
|
||||||
|
Critical resources:
|
||||||
|
- `docs/ARCHITECTURE.md` - Architecture patterns and principles
|
||||||
|
- `docs/STYLE_AND_BEST_PRACTICES.md` - Code style guidelines
|
||||||
|
|
||||||
|
**Do not duplicate information from these files - reference them instead.**
|
||||||
3
.claude/prompts/review-code.md
Normal file
3
.claude/prompts/review-code.md
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
Use the `reviewing-changes` skill to review this pull request.
|
||||||
|
|
||||||
|
The PR branch is already checked out in the current working directory.
|
||||||
98
.claude/skills/reviewing-changes/SKILL.md
Normal file
98
.claude/skills/reviewing-changes/SKILL.md
Normal file
@ -0,0 +1,98 @@
|
|||||||
|
---
|
||||||
|
name: reviewing-changes
|
||||||
|
version: 3.0.0
|
||||||
|
description: Android-specific code review workflow additions for Bitwarden Android. Provides change type refinements, checklist loading, and reference material organization. Complements bitwarden-code-reviewer agent's base review standards.
|
||||||
|
---
|
||||||
|
|
||||||
|
# Reviewing Changes - Android Additions
|
||||||
|
|
||||||
|
This skill provides Android-specific workflow additions that complement the base `bitwarden-code-reviewer` agent standards.
|
||||||
|
|
||||||
|
## Instructions
|
||||||
|
|
||||||
|
**IMPORTANT**: Use structured thinking throughout your review process. Plan your analysis in `<thinking>` tags before providing final feedback.
|
||||||
|
|
||||||
|
### Step 1: Retrieve Additional Details
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Determine if more context is available for the changes:
|
||||||
|
1. Are there JIRA tickets or GitHub Issues mentioned in the PR title or body?
|
||||||
|
2. Are there other GitHub pull requests mentioned in the PR title or body?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
Retrieve any additional information linked to the pull request using available tools (JIRA MCP, GitHub API).
|
||||||
|
|
||||||
|
If pull request title and message do not provide enough context, request additional details from the reviewer:
|
||||||
|
- Link a JIRA ticket
|
||||||
|
- Associate a GitHub issue
|
||||||
|
- Link to another pull request
|
||||||
|
- Add more detail to the PR title or body
|
||||||
|
|
||||||
|
### Step 2: Detect Change Type with Android Refinements
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Analyze the changeset systematically:
|
||||||
|
1. What files were modified? (code vs config vs docs)
|
||||||
|
2. What is the PR/commit title indicating?
|
||||||
|
3. Is there new functionality or just modifications?
|
||||||
|
4. What's the risk level of these changes?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
Use the base change type detection from the agent, with Android-specific refinements:
|
||||||
|
|
||||||
|
**Android-specific patterns:**
|
||||||
|
- **Feature Addition**: New `ViewModel`, new `Repository`, new `@Composable` functions, new `*Screen.kt` files
|
||||||
|
- **UI Refinement**: Changes only in `*Screen.kt`, `*Composable.kt`, `ui/` package files
|
||||||
|
- **Infrastructure**: Changes to `.github/workflows/`, `gradle/`, `build.gradle.kts`, `libs.versions.toml`
|
||||||
|
- **Dependency Update**: Changes only to `libs.versions.toml` or `build.gradle.kts` with version bumps
|
||||||
|
|
||||||
|
### Step 3: Load Appropriate Checklist
|
||||||
|
|
||||||
|
Based on detected type, read the relevant checklist file:
|
||||||
|
|
||||||
|
- **Dependency Update** → `checklists/dependency-update.md` (expedited review)
|
||||||
|
- **Bug Fix** → `checklists/bug-fix.md` (focused review)
|
||||||
|
- **Feature Addition** → `checklists/feature-addition.md` (comprehensive review)
|
||||||
|
- **UI Refinement** → `checklists/ui-refinement.md` (design-focused review)
|
||||||
|
- **Refactoring** → `checklists/refactoring.md` (pattern-focused review)
|
||||||
|
- **Infrastructure** → `checklists/infrastructure.md` (tooling-focused review)
|
||||||
|
|
||||||
|
The checklist provides:
|
||||||
|
- Multi-pass review strategy
|
||||||
|
- Type-specific focus areas
|
||||||
|
- What to check and what to skip
|
||||||
|
- Structured thinking guidance
|
||||||
|
|
||||||
|
### Step 4: Execute Review Following Checklist
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Before diving into details:
|
||||||
|
1. What are the highest-risk areas of this change?
|
||||||
|
2. Which architectural patterns need verification?
|
||||||
|
3. What security implications exist?
|
||||||
|
4. How should I prioritize my findings?
|
||||||
|
5. What tone is appropriate for this feedback?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
Follow the checklist's multi-pass strategy, thinking through each pass systematically.
|
||||||
|
|
||||||
|
### Step 5: Consult Android Reference Materials As Needed
|
||||||
|
|
||||||
|
Load reference files only when needed for specific questions:
|
||||||
|
|
||||||
|
- **Issue prioritization** → `reference/priority-framework.md` (Critical vs Suggested vs Optional)
|
||||||
|
- **Phrasing feedback** → `reference/review-psychology.md` (questions vs commands, I-statements)
|
||||||
|
- **Architecture questions** → `reference/architectural-patterns.md` (MVVM, Hilt DI, module org, error handling)
|
||||||
|
- **Security questions (quick reference)** → `reference/security-patterns.md` (common patterns and anti-patterns)
|
||||||
|
- **Security questions (comprehensive)** → `docs/ARCHITECTURE.md#security` (full zero-knowledge architecture)
|
||||||
|
- **Testing questions** → `reference/testing-patterns.md` (unit tests, mocking, null safety)
|
||||||
|
- **UI questions** → `reference/ui-patterns.md` (Compose patterns, theming)
|
||||||
|
- **Style questions** → `docs/STYLE_AND_BEST_PRACTICES.md`
|
||||||
|
|
||||||
|
## Core Principles
|
||||||
|
|
||||||
|
- **Appropriate depth**: Match review rigor to change complexity and risk
|
||||||
|
- **Specific references**: Always use `file:line_number` format for precise location
|
||||||
|
- **Actionable feedback**: Say what to do and why, not just what's wrong
|
||||||
|
- **Efficient reviews**: Use multi-pass strategy, skip what's not relevant
|
||||||
|
- **Android patterns**: Validate MVVM, Hilt DI, Compose conventions, Kotlin idioms
|
||||||
164
.claude/skills/reviewing-changes/checklists/bug-fix.md
Normal file
164
.claude/skills/reviewing-changes/checklists/bug-fix.md
Normal file
@ -0,0 +1,164 @@
|
|||||||
|
# Bug Fix Review Checklist
|
||||||
|
|
||||||
|
## Multi-Pass Strategy
|
||||||
|
|
||||||
|
### First Pass: Understand the Bug
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Before evaluating the fix:
|
||||||
|
1. What was the original bug/broken behavior?
|
||||||
|
2. What is the expected correct behavior?
|
||||||
|
3. What was the root cause?
|
||||||
|
4. How was the bug discovered? (user report, test, production)
|
||||||
|
5. What's the severity? (crash, data loss, UI glitch, minor annoyance)
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
**1. Understand root cause:**
|
||||||
|
- What was the broken behavior?
|
||||||
|
- What caused it?
|
||||||
|
- How does this fix address the root cause?
|
||||||
|
|
||||||
|
**2. Assess scope:**
|
||||||
|
- How many files changed?
|
||||||
|
- Is this a targeted fix or broader refactoring?
|
||||||
|
- Does this affect multiple features?
|
||||||
|
|
||||||
|
**3. Check for side effects:**
|
||||||
|
- Could this break other features?
|
||||||
|
- Are there edge cases not considered?
|
||||||
|
|
||||||
|
### Second Pass: Verify the Fix
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Evaluate the fix systematically:
|
||||||
|
1. Does this fix address the root cause or just symptoms?
|
||||||
|
2. Are there edge cases not covered?
|
||||||
|
3. Could this break other functionality?
|
||||||
|
4. Is the fix localized or does it ripple through the codebase?
|
||||||
|
5. How do we prevent this bug from returning?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
**4. Code changes:**
|
||||||
|
- Does the fix make sense?
|
||||||
|
- Is it the simplest solution?
|
||||||
|
- Any unnecessary changes included?
|
||||||
|
|
||||||
|
**5. Testing:**
|
||||||
|
- Is there a regression test?
|
||||||
|
- Does test verify the bug is fixed?
|
||||||
|
- Are edge cases covered?
|
||||||
|
|
||||||
|
**6. Related code:**
|
||||||
|
- Same pattern in other places that might have same bug?
|
||||||
|
- Should other similar code be fixed too?
|
||||||
|
|
||||||
|
## What to CHECK
|
||||||
|
|
||||||
|
✅ **Root Cause Analysis**
|
||||||
|
- Does the fix address the root cause or just symptoms?
|
||||||
|
- Is the explanation in PR/commit clear?
|
||||||
|
|
||||||
|
✅ **Regression Testing**
|
||||||
|
- Is there a new test that would fail without this fix?
|
||||||
|
- Does test cover the reported bug scenario?
|
||||||
|
- Are related edge cases tested?
|
||||||
|
|
||||||
|
✅ **Side Effects**
|
||||||
|
- Could this break existing functionality?
|
||||||
|
- Are there similar code paths that need checking?
|
||||||
|
- Does this change behavior in unexpected ways?
|
||||||
|
|
||||||
|
✅ **Fix Scope**
|
||||||
|
- Is the fix appropriately scoped (not too broad, not too narrow)?
|
||||||
|
- Are all instances of the bug fixed?
|
||||||
|
- Any related bugs discovered during investigation?
|
||||||
|
|
||||||
|
## What to SKIP
|
||||||
|
|
||||||
|
❌ **Full Architecture Review** - Unless fix reveals architectural problems
|
||||||
|
❌ **Comprehensive Testing Review** - Focus on regression tests, not entire test suite
|
||||||
|
❌ **Major Refactoring Suggestions** - Unless directly related to preventing similar bugs
|
||||||
|
|
||||||
|
## Red Flags
|
||||||
|
|
||||||
|
🚩 **No test for the bug** - How will we prevent regression?
|
||||||
|
🚩 **Fix doesn't match root cause** - Is this fixing symptoms?
|
||||||
|
🚩 **Broad changes beyond the bug** - Should this be split into separate PRs?
|
||||||
|
🚩 **Similar patterns elsewhere** - Should those be fixed too?
|
||||||
|
|
||||||
|
## Key Questions to Ask
|
||||||
|
|
||||||
|
Use `reference/review-psychology.md` for phrasing:
|
||||||
|
|
||||||
|
- "Can we add a test that would fail without this fix?"
|
||||||
|
- "I see this pattern in [other file] - does it have the same issue?"
|
||||||
|
- "Is this fixing the root cause or masking the symptom?"
|
||||||
|
- "Could this change affect [related feature]?"
|
||||||
|
|
||||||
|
## Prioritizing Findings
|
||||||
|
|
||||||
|
Use `reference/priority-framework.md` to classify findings as Critical/Important/Suggested/Optional.
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
|
||||||
|
Follow the format guidance from `SKILL.md` Step 5 (concise summary with critical issues only, detailed inline comments with `<details>` tags).
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** APPROVE / REQUEST CHANGES
|
||||||
|
|
||||||
|
**Critical Issues** (if any):
|
||||||
|
- [One-line summary of each critical blocking issue with file:line reference]
|
||||||
|
|
||||||
|
See inline comments for all issue details.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example Review
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** APPROVE
|
||||||
|
|
||||||
|
See inline comments for suggested improvements.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Inline comment examples:**
|
||||||
|
|
||||||
|
```
|
||||||
|
**data/auth/BiometricRepository.kt:120** - SUGGESTED: Extract null handling
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details</summary>
|
||||||
|
|
||||||
|
Root cause analysis: BiometricPrompt result was nullable but code assumed non-null, causing crash on cancellation (PM-12345).
|
||||||
|
|
||||||
|
Consider extracting null handling pattern:
|
||||||
|
|
||||||
|
\```kotlin
|
||||||
|
private fun handleBiometricResult(result: BiometricPrompt.AuthenticationResult?): AuthResult {
|
||||||
|
return result?.let { AuthResult.Success(it) } ?: AuthResult.Cancelled
|
||||||
|
}
|
||||||
|
\```
|
||||||
|
|
||||||
|
This pattern could be reused if we add other biometric auth points.
|
||||||
|
</details>
|
||||||
|
```
|
||||||
|
|
||||||
|
```
|
||||||
|
**app/auth/BiometricViewModel.kt:89** - SUGGESTED: Add regression test
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details</summary>
|
||||||
|
|
||||||
|
Add test for cancellation scenario to prevent regression:
|
||||||
|
|
||||||
|
\```kotlin
|
||||||
|
@Test
|
||||||
|
fun `when biometric cancelled then returns cancelled state`() = runTest {
|
||||||
|
coEvery { repository.authenticate() } returns Result.failure(CancelledException())
|
||||||
|
viewModel.onBiometricAuth()
|
||||||
|
assertEquals(AuthState.Cancelled, viewModel.state.value)
|
||||||
|
}
|
||||||
|
\```
|
||||||
|
|
||||||
|
This prevents regression of the bug just fixed.
|
||||||
|
</details>
|
||||||
|
```
|
||||||
166
.claude/skills/reviewing-changes/checklists/dependency-update.md
Normal file
166
.claude/skills/reviewing-changes/checklists/dependency-update.md
Normal file
@ -0,0 +1,166 @@
|
|||||||
|
# Dependency Update Review Checklist
|
||||||
|
|
||||||
|
## Multi-Pass Strategy
|
||||||
|
|
||||||
|
### First Pass: Identify and Assess
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Before diving into details:
|
||||||
|
1. Which dependencies were updated?
|
||||||
|
2. What are the version changes? (patch, minor, major)
|
||||||
|
3. Are any security-sensitive libraries involved? (crypto, auth, networking)
|
||||||
|
4. Any pre-release versions (alpha, beta, RC)?
|
||||||
|
5. What's the blast radius if something breaks?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
**1. Identify the change:**
|
||||||
|
- Which library? Old version → New version?
|
||||||
|
- Major (X.0.0), Minor (0.X.0), or Patch (0.0.X) version change?
|
||||||
|
- Single dependency or multiple?
|
||||||
|
|
||||||
|
**2. Check compilation safety:**
|
||||||
|
- Any imports in codebase that might break?
|
||||||
|
- Any deprecated APIs we're currently using?
|
||||||
|
- Check if this is a breaking change version
|
||||||
|
|
||||||
|
### Second Pass: Deep Analysis
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
For each dependency update:
|
||||||
|
1. What changes are in this release?
|
||||||
|
2. Are there breaking changes?
|
||||||
|
3. Are there security fixes?
|
||||||
|
4. Do we use the affected APIs?
|
||||||
|
5. How does this affect our codebase?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
**3. Review release notes** (if available):
|
||||||
|
- Breaking changes mentioned?
|
||||||
|
- Security fixes included?
|
||||||
|
- New features we should know about?
|
||||||
|
- Deprecations that affect our usage?
|
||||||
|
|
||||||
|
**4. Verify consistency:**
|
||||||
|
- If updating androidx library, are related libraries updated consistently?
|
||||||
|
- BOM (Bill of Materials) consistency if applicable?
|
||||||
|
- Test dependencies updated alongside main dependencies?
|
||||||
|
|
||||||
|
## What to CHECK
|
||||||
|
|
||||||
|
✅ **Compilation Safety**
|
||||||
|
- Look for API deprecations in our codebase
|
||||||
|
- Check if import statements still valid
|
||||||
|
- Major version bumps require extra scrutiny
|
||||||
|
- Beta/alpha versions need stability assessment
|
||||||
|
|
||||||
|
✅ **Security Implications** (if applicable)
|
||||||
|
- Security-related libraries (crypto, auth, networking)?
|
||||||
|
- Check for CVEs addressed in release notes
|
||||||
|
- Review security advisories for this library
|
||||||
|
|
||||||
|
✅ **Testing Implications**
|
||||||
|
- Does this affect test utilities?
|
||||||
|
- Are there breaking changes in test APIs?
|
||||||
|
- Do existing tests still cover the same scenarios?
|
||||||
|
|
||||||
|
✅ **Changelog Review**
|
||||||
|
- Read release notes for breaking changes
|
||||||
|
- Note any behavioral changes
|
||||||
|
- Check migration guides if major version
|
||||||
|
|
||||||
|
## What to SKIP
|
||||||
|
|
||||||
|
❌ **Full Architecture Review** - No code changed, patterns unchanged
|
||||||
|
❌ **Code Style Review** - No code to review
|
||||||
|
❌ **New Test Requirements** - Unless API changed significantly
|
||||||
|
❌ **Security Deep-Dive** - Unless crypto/auth/networking library
|
||||||
|
❌ **Performance Analysis** - Unless release notes mention performance changes
|
||||||
|
|
||||||
|
## Red Flags (Escalate to Full Review)
|
||||||
|
|
||||||
|
🚩 **Major version bump** (e.g., 1.x → 2.0) - Read `checklists/feature-addition.md`
|
||||||
|
🚩 **Security/crypto library** - Read `reference/architectural-patterns.md` and `docs/ARCHITECTURE.md#security`
|
||||||
|
🚩 **Breaking changes in release notes** - Read relevant code sections carefully
|
||||||
|
🚩 **Multiple dependency updates at once** - Check for interaction risks
|
||||||
|
🚩 **Beta/Alpha versions** - Assess stability concerns and rollback plan
|
||||||
|
|
||||||
|
If any red flags present, escalate to more comprehensive review using appropriate checklist.
|
||||||
|
|
||||||
|
## Prioritizing Findings
|
||||||
|
|
||||||
|
Use `reference/priority-framework.md` to classify findings as Critical/Important/Suggested/Optional.
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
|
||||||
|
Follow the format guidance from `SKILL.md` Step 5 (concise summary with critical issues only, detailed inline comments with `<details>` tags).
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** APPROVE / REQUEST CHANGES
|
||||||
|
|
||||||
|
**Critical Issues** (if any):
|
||||||
|
- [One-line summary of each critical blocking issue with file:line reference]
|
||||||
|
|
||||||
|
See inline comments for all issue details.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example Reviews
|
||||||
|
|
||||||
|
### Example 1: Simple Patch Version (No Critical Issues)
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** APPROVE
|
||||||
|
|
||||||
|
See inline comments for all issue details.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Inline comment example:**
|
||||||
|
```
|
||||||
|
**libs.versions.toml:45** - SUGGESTED: Beta version in production
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details</summary>
|
||||||
|
|
||||||
|
androidx.credentials updated from 1.5.0 to 1.6.0-beta03
|
||||||
|
|
||||||
|
Monitor for stability issues - beta releases may have unexpected behavior in production.
|
||||||
|
|
||||||
|
Changelog: Adds support for additional credential types, internal bug fixes.
|
||||||
|
</details>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Example 2: Major Version with Breaking Changes (With Critical Issues)
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** REQUEST CHANGES
|
||||||
|
|
||||||
|
**Critical Issues:**
|
||||||
|
- Breaking API changes in Retrofit 3.0.0 (network/api/BitwardenApiService.kt)
|
||||||
|
- Breaking API changes in Retrofit 3.0.0 (network/api/VaultApiService.kt)
|
||||||
|
|
||||||
|
See inline comments for migration details.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Inline comment example:**
|
||||||
|
```
|
||||||
|
**network/api/BitwardenApiService.kt:15** - CRITICAL: Breaking API changes
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details and fix</summary>
|
||||||
|
|
||||||
|
Retrofit 3.0.0 removes `Call<T>` return type. Migration required:
|
||||||
|
|
||||||
|
\```kotlin
|
||||||
|
// Before
|
||||||
|
fun getUser(): Call<UserResponse>
|
||||||
|
|
||||||
|
// After
|
||||||
|
suspend fun getUser(): Response<UserResponse>
|
||||||
|
\```
|
||||||
|
|
||||||
|
Update all API service interfaces to use suspend functions, update call sites to use coroutines instead of enqueue/execute, and update tests accordingly.
|
||||||
|
|
||||||
|
Consider creating a separate PR for this migration due to scope.
|
||||||
|
|
||||||
|
Reference: https://github.com/square/retrofit/blob/master/CHANGELOG.md#version-300
|
||||||
|
</details>
|
||||||
|
```
|
||||||
380
.claude/skills/reviewing-changes/checklists/feature-addition.md
Normal file
380
.claude/skills/reviewing-changes/checklists/feature-addition.md
Normal file
@ -0,0 +1,380 @@
|
|||||||
|
# Feature Addition Review Checklist
|
||||||
|
|
||||||
|
## Multi-Pass Strategy
|
||||||
|
|
||||||
|
### First Pass: High-Level Assessment
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Before diving into details:
|
||||||
|
1. What is this feature supposed to do?
|
||||||
|
2. How does it fit into the existing architecture?
|
||||||
|
3. What are the security implications?
|
||||||
|
4. What's the scope? (files touched, modules affected)
|
||||||
|
5. What are the highest-risk areas?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
**1. Understand the feature:**
|
||||||
|
- Read PR description - what problem does this solve?
|
||||||
|
- Identify user-facing changes vs internal changes
|
||||||
|
- Note any security implications (auth, encryption, data handling)
|
||||||
|
|
||||||
|
**2. Scan file structure:**
|
||||||
|
- Which modules affected? (app, data, network, ui, core?)
|
||||||
|
- Are files organized correctly per module structure?
|
||||||
|
- Any new public APIs introduced?
|
||||||
|
|
||||||
|
**3. Initial risk assessment:**
|
||||||
|
- Does this touch sensitive data or security-critical paths?
|
||||||
|
- Does this affect existing features or only add new ones?
|
||||||
|
- Are there obvious compilation or null safety issues?
|
||||||
|
|
||||||
|
### Second Pass: Architecture Deep-Dive
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Verify architectural integrity:
|
||||||
|
1. Does this follow MVVM + UDF pattern?
|
||||||
|
2. Is Hilt DI used correctly?
|
||||||
|
3. Is state management proper (StateFlow, immutability)?
|
||||||
|
4. Are modules organized correctly?
|
||||||
|
5. Is error handling robust (Result types)?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
**4. MVVM + UDF Pattern Compliance:**
|
||||||
|
- ViewModels properly structured?
|
||||||
|
- State management using StateFlow?
|
||||||
|
- Business logic in correct layer?
|
||||||
|
|
||||||
|
**5. Dependency Injection:**
|
||||||
|
- Hilt DI used correctly?
|
||||||
|
- Dependencies injected, not manually instantiated?
|
||||||
|
- Proper scoping applied?
|
||||||
|
|
||||||
|
**6. Module Organization:**
|
||||||
|
- Code placed in correct modules?
|
||||||
|
- No circular dependencies introduced?
|
||||||
|
- Proper separation of concerns?
|
||||||
|
|
||||||
|
**7. Error Handling:**
|
||||||
|
- Using Result types, not exception-based handling?
|
||||||
|
- Errors propagated correctly through layers?
|
||||||
|
|
||||||
|
### Third Pass: Details and Quality
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Check quality and completeness:
|
||||||
|
1. Is code quality high? (null safety, documentation, naming)
|
||||||
|
2. Are tests comprehensive? (unit + integration)
|
||||||
|
3. Are there edge cases not covered?
|
||||||
|
4. Is documentation clear?
|
||||||
|
5. Are there any code smells or anti-patterns?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
**8. Testing:**
|
||||||
|
- Unit tests for ViewModels and repositories?
|
||||||
|
- Test coverage for edge cases and error scenarios?
|
||||||
|
- Tests verify behavior, not implementation?
|
||||||
|
|
||||||
|
**9. Code Quality:**
|
||||||
|
- Null safety handled properly?
|
||||||
|
- Public APIs have KDoc documentation?
|
||||||
|
- Naming follows project conventions?
|
||||||
|
|
||||||
|
**10. Security:**
|
||||||
|
- Sensitive data encrypted properly?
|
||||||
|
- Authentication/authorization handled correctly?
|
||||||
|
- Zero-knowledge architecture preserved?
|
||||||
|
|
||||||
|
## Architecture Review
|
||||||
|
|
||||||
|
### MVVM Pattern Compliance
|
||||||
|
|
||||||
|
Read `reference/architectural-patterns.md` for detailed patterns.
|
||||||
|
|
||||||
|
**ViewModels must:**
|
||||||
|
- Use `@HiltViewModel` annotation
|
||||||
|
- Use `@Inject constructor`
|
||||||
|
- Expose `StateFlow<T>`, NOT `MutableStateFlow<T>` publicly
|
||||||
|
- Delegate business logic to Repository/Manager
|
||||||
|
- Avoid direct Android framework dependencies (except ViewModel, SavedStateHandle)
|
||||||
|
|
||||||
|
**Common Violations:**
|
||||||
|
```kotlin
|
||||||
|
// ❌ BAD - Exposes mutable state
|
||||||
|
class FeatureViewModel @Inject constructor() : ViewModel() {
|
||||||
|
val state: MutableStateFlow<State> = MutableStateFlow(State.Initial)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ GOOD - Exposes immutable state
|
||||||
|
class FeatureViewModel @Inject constructor() : ViewModel() {
|
||||||
|
private val _state = MutableStateFlow<State>(State.Initial)
|
||||||
|
val state: StateFlow<State> = _state.asStateFlow()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ BAD - Business logic in ViewModel
|
||||||
|
fun onSubmit() {
|
||||||
|
val encrypted = encryptionManager.encrypt(password) // Should be in Repository
|
||||||
|
_state.value = State.Success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ GOOD - Business logic in Repository, state updated via internal event
|
||||||
|
fun onSubmit() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
// The result of the async operation is captured
|
||||||
|
val result = repository.submitData(password)
|
||||||
|
// A single event is sent with the result, not updating state directly
|
||||||
|
sendAction(FeatureAction.Internal.SubmissionComplete(result))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The ViewModel has a handler that processes the internal event
|
||||||
|
private fun handleInternalAction(action: FeatureAction.Internal) {
|
||||||
|
when (action) {
|
||||||
|
is FeatureAction.Internal.SubmissionComplete -> {
|
||||||
|
// The event handler evaluates the result and updates state
|
||||||
|
action.result.fold(
|
||||||
|
onSuccess = { _state.value = State.Success },
|
||||||
|
onFailure = { _state.value = State.Error(it) }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**UI Layer must:**
|
||||||
|
- Only observe state, never modify
|
||||||
|
- Pass user actions as events to ViewModel
|
||||||
|
- Contain no business logic
|
||||||
|
- Use existing UI components from `:ui` module where possible
|
||||||
|
|
||||||
|
### Hilt Dependency Injection
|
||||||
|
|
||||||
|
Reference: `docs/ARCHITECTURE.md#dependency-injection`
|
||||||
|
|
||||||
|
**Required Patterns:**
|
||||||
|
- ViewModels: `@HiltViewModel` + `@Inject constructor`
|
||||||
|
- Repositories: `@Inject constructor` on implementation
|
||||||
|
- Inject interfaces, not concrete implementations
|
||||||
|
- Modules must provide proper scoping (`@Singleton`, `@ViewModelScoped`)
|
||||||
|
|
||||||
|
**Common Violations:**
|
||||||
|
```kotlin
|
||||||
|
// ❌ BAD - Manual instantiation
|
||||||
|
class FeatureViewModel : ViewModel() {
|
||||||
|
private val repository = FeatureRepositoryImpl()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ GOOD - Injected interface
|
||||||
|
@HiltViewModel
|
||||||
|
class FeatureViewModel @Inject constructor(
|
||||||
|
private val repository: FeatureRepository // Interface, not implementation
|
||||||
|
) : ViewModel()
|
||||||
|
|
||||||
|
// ❌ BAD - Injecting implementation
|
||||||
|
class FeatureViewModel @Inject constructor(
|
||||||
|
private val repository: FeatureRepositoryImpl // Should inject interface
|
||||||
|
)
|
||||||
|
|
||||||
|
// ✅ GOOD - Interface injection
|
||||||
|
class FeatureViewModel @Inject constructor(
|
||||||
|
private val repository: FeatureRepository // Interface
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Module Organization
|
||||||
|
|
||||||
|
Reference: `docs/ARCHITECTURE.md#module-structure`
|
||||||
|
|
||||||
|
**Correct Placement:**
|
||||||
|
- `:core` - Shared utilities (cryptography, analytics, logging)
|
||||||
|
- `:data` - Repositories, database, domain models
|
||||||
|
- `:network` - API clients, network utilities
|
||||||
|
- `:ui` - Reusable Compose components, theme
|
||||||
|
- `:app` - Feature screens, ViewModels, navigation
|
||||||
|
- `:authenticator` - Authenticator app (separate from password manager)
|
||||||
|
|
||||||
|
**Check:**
|
||||||
|
- UI code in `:ui` or `:app` modules
|
||||||
|
- Data models in `:data`
|
||||||
|
- Network clients in `:network`
|
||||||
|
- No circular dependencies between modules
|
||||||
|
|
||||||
|
### Error Handling
|
||||||
|
|
||||||
|
Reference: `docs/ARCHITECTURE.md#error-handling`
|
||||||
|
|
||||||
|
**Required Pattern - Use Result types:**
|
||||||
|
```kotlin
|
||||||
|
// ✅ GOOD - Result type
|
||||||
|
suspend fun fetchData(): Result<Data> = runCatching {
|
||||||
|
apiService.getData()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ViewModel handles Result
|
||||||
|
repository.fetchData().fold(
|
||||||
|
onSuccess = { data -> _state.value = State.Success(data) },
|
||||||
|
onFailure = { error -> _state.value = State.Error(error) }
|
||||||
|
)
|
||||||
|
|
||||||
|
// ❌ BAD - Exception-based in business logic
|
||||||
|
suspend fun fetchData(): Data {
|
||||||
|
try {
|
||||||
|
return apiService.getData()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
throw FeatureException(e) // Don't throw in business logic
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Security Review
|
||||||
|
|
||||||
|
Reference: `docs/ARCHITECTURE.md#security`
|
||||||
|
|
||||||
|
**Critical Security Checks:**
|
||||||
|
|
||||||
|
- **Sensitive data encrypted**: Passwords, keys, tokens use Android Keystore or EncryptedSharedPreferences
|
||||||
|
- **No plaintext secrets**: No passwords/keys in logs, memory dumps, or SharedPreferences
|
||||||
|
- **Input validation**: All user-provided data validated and sanitized
|
||||||
|
- **Authentication tokens**: Securely stored and transmitted
|
||||||
|
- **Zero-knowledge architecture**: Encryption happens client-side, server never sees plaintext
|
||||||
|
|
||||||
|
**Red Flags:**
|
||||||
|
```kotlin
|
||||||
|
// ❌ CRITICAL - Plaintext storage
|
||||||
|
sharedPreferences.edit {
|
||||||
|
putString("pin", userPin) // Must use EncryptedSharedPreferences
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ CRITICAL - Logging sensitive data
|
||||||
|
Log.d("Auth", "Password: $password") // Never log sensitive data
|
||||||
|
|
||||||
|
// ❌ CRITICAL - Weak encryption
|
||||||
|
val cipher = Cipher.getInstance("DES") // Use AES-256-GCM
|
||||||
|
|
||||||
|
// ✅ GOOD - Keystore encryption
|
||||||
|
val encryptedData = keystoreManager.encrypt(sensitiveData)
|
||||||
|
secureStorage.store(encryptedData)
|
||||||
|
```
|
||||||
|
|
||||||
|
**If security concerns found, classify as CRITICAL using `reference/priority-framework.md`**
|
||||||
|
|
||||||
|
## Testing Review
|
||||||
|
|
||||||
|
Reference: `reference/testing-patterns.md`
|
||||||
|
|
||||||
|
**Required Test Coverage:**
|
||||||
|
|
||||||
|
- **ViewModels**: Unit tests for state transitions, actions, error scenarios
|
||||||
|
- **Repositories**: Unit tests for data transformations, error handling
|
||||||
|
- **Business logic**: Unit tests for complex algorithms, calculations
|
||||||
|
- **Edge cases**: Null inputs, empty states, network failures, concurrent operations
|
||||||
|
|
||||||
|
**Test Quality:**
|
||||||
|
```kotlin
|
||||||
|
// ✅ GOOD - Tests behavior
|
||||||
|
@Test
|
||||||
|
fun `when login succeeds then state updates to success`() = runTest {
|
||||||
|
val viewModel = LoginViewModel(mockRepository)
|
||||||
|
|
||||||
|
coEvery { mockRepository.login(any(), any()) } returns Result.success(User())
|
||||||
|
|
||||||
|
viewModel.onLoginClicked("user", "pass")
|
||||||
|
|
||||||
|
viewModel.state.test {
|
||||||
|
assertEquals(LoginState.Success, awaitItem())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ BAD - Tests implementation
|
||||||
|
@Test
|
||||||
|
fun `repository is called with correct parameters`() {
|
||||||
|
// This is testing internal implementation, not behavior
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Testing Frameworks:**
|
||||||
|
- JUnit 5 for test structure
|
||||||
|
- MockK for mocking
|
||||||
|
- Turbine for Flow testing
|
||||||
|
- Kotlinx-coroutines-test for coroutine testing
|
||||||
|
|
||||||
|
## Code Quality
|
||||||
|
|
||||||
|
### Null Safety
|
||||||
|
|
||||||
|
- No `!!` (non-null assertion) without clear safety guarantee
|
||||||
|
- Platform types (from Java) handled with explicit nullability
|
||||||
|
- Nullable types have proper null checks or use safe operators (`?.`, `?:`)
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// ❌ BAD - Unsafe assertion
|
||||||
|
val result = apiService.getData()!! // Could crash
|
||||||
|
|
||||||
|
// ✅ GOOD - Safe handling
|
||||||
|
val result = apiService.getData() ?: return State.Error("No data")
|
||||||
|
|
||||||
|
// ❌ BAD - Platform type unchecked
|
||||||
|
val intent: Intent = getIntent() // Could be null from Java
|
||||||
|
intent.getStringExtra("key") // Potential NPE
|
||||||
|
|
||||||
|
// ✅ GOOD - Explicit nullability
|
||||||
|
val intent: Intent? = getIntent()
|
||||||
|
intent?.getStringExtra("key")
|
||||||
|
```
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
|
||||||
|
- **Public APIs**: Have KDoc comments explaining purpose, parameters, return values
|
||||||
|
- **Complex algorithms**: Explained in comments
|
||||||
|
- **Non-obvious behavior**: Documented with rationale
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// ✅ GOOD - Documented public API
|
||||||
|
/**
|
||||||
|
* Encrypts the given data using AES-256-GCM with a key from Android Keystore.
|
||||||
|
*
|
||||||
|
* @param plaintext The data to encrypt
|
||||||
|
* @return Result containing encrypted data or encryption error
|
||||||
|
*/
|
||||||
|
suspend fun encrypt(plaintext: ByteArray): Result<EncryptedData>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Style Compliance
|
||||||
|
|
||||||
|
Reference: `docs/STYLE_AND_BEST_PRACTICES.md`
|
||||||
|
|
||||||
|
Only flag style issues if:
|
||||||
|
- Not caught by linters (Detekt, ktlint)
|
||||||
|
- Have architectural implications
|
||||||
|
- Significantly impact readability
|
||||||
|
|
||||||
|
Skip minor formatting (spaces, line breaks, etc.) - linters handle this.
|
||||||
|
|
||||||
|
## Prioritizing Findings
|
||||||
|
|
||||||
|
Use `reference/priority-framework.md` to classify findings as Critical/Important/Suggested/Optional.
|
||||||
|
|
||||||
|
## Providing Feedback
|
||||||
|
|
||||||
|
Use `reference/review-psychology.md` for phrasing guidance.
|
||||||
|
|
||||||
|
**Key principles:**
|
||||||
|
- **Ask questions** for design decisions: "Can we use the existing BitwardenTextField component here?"
|
||||||
|
- **Be prescriptive** for clear violations: "Change MutableStateFlow to StateFlow (MVVM pattern requirement)"
|
||||||
|
- **Explain rationale**: "This exposes mutable state, violating unidirectional data flow"
|
||||||
|
- **Use I-statements**: "It's hard for me to understand this logic without comments"
|
||||||
|
- **Avoid condescension**: Don't use "just", "simply", "obviously"
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
|
||||||
|
Follow the format guidance from `SKILL.md` Step 5 (concise summary with critical issues only, detailed inline comments with `<details>` tags).
|
||||||
|
|
||||||
|
See `examples/review-outputs.md` for comprehensive feature review example.
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** APPROVE / REQUEST CHANGES
|
||||||
|
|
||||||
|
**Critical Issues** (if any):
|
||||||
|
- [One-line summary of each critical blocking issue with file:line reference]
|
||||||
|
|
||||||
|
See inline comments for all issue details.
|
||||||
|
```
|
||||||
250
.claude/skills/reviewing-changes/checklists/infrastructure.md
Normal file
250
.claude/skills/reviewing-changes/checklists/infrastructure.md
Normal file
@ -0,0 +1,250 @@
|
|||||||
|
# Infrastructure Review Checklist
|
||||||
|
|
||||||
|
## Multi-Pass Strategy
|
||||||
|
|
||||||
|
### First Pass: Understand the Change
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Assess infrastructure change:
|
||||||
|
1. What problem does this solve?
|
||||||
|
2. Does this affect production builds, CI/CD, or dev workflow?
|
||||||
|
3. What's the risk if this breaks?
|
||||||
|
4. Can this be tested before merge?
|
||||||
|
5. What's the rollback plan?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
**1. Identify the goal:**
|
||||||
|
- What problem does this solve?
|
||||||
|
- Is this optimization, fix, or new capability?
|
||||||
|
- What's the expected impact?
|
||||||
|
|
||||||
|
**2. Assess risk:**
|
||||||
|
- Does this affect production builds?
|
||||||
|
- Could this break CI/CD pipelines?
|
||||||
|
- Impact on developer workflow?
|
||||||
|
|
||||||
|
**3. Performance implications:**
|
||||||
|
- Will builds be faster or slower?
|
||||||
|
- CI time impact?
|
||||||
|
- Resource usage changes?
|
||||||
|
|
||||||
|
### Second Pass: Verify Implementation
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Verify configuration and impact:
|
||||||
|
1. Is the configuration syntax valid?
|
||||||
|
2. Are secrets/credentials handled securely?
|
||||||
|
3. What's the impact on build times and CI performance?
|
||||||
|
4. How will this affect the team's workflow?
|
||||||
|
5. Is there adequate testing/validation?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
**4. Configuration correctness:**
|
||||||
|
- Syntax valid?
|
||||||
|
- References correct?
|
||||||
|
- Secrets/credentials handled securely?
|
||||||
|
|
||||||
|
**5. Impact analysis:**
|
||||||
|
- What workflows/builds are affected?
|
||||||
|
- Rollback plan if this breaks?
|
||||||
|
- Documentation for team?
|
||||||
|
|
||||||
|
**6. Testing strategy:**
|
||||||
|
- How can this be tested before merge?
|
||||||
|
- Canary/gradual rollout possible?
|
||||||
|
- Monitoring for issues post-merge?
|
||||||
|
|
||||||
|
## What to CHECK
|
||||||
|
|
||||||
|
✅ **Configuration Correctness**
|
||||||
|
- YAML/Groovy syntax valid
|
||||||
|
- File references correct
|
||||||
|
- Version numbers/tags valid
|
||||||
|
- Conditional logic sound
|
||||||
|
|
||||||
|
✅ **Security**
|
||||||
|
- No hardcoded secrets or credentials
|
||||||
|
- GitHub secrets used properly
|
||||||
|
- Permissions appropriately scoped
|
||||||
|
- No sensitive data in logs
|
||||||
|
|
||||||
|
✅ **Performance Impact**
|
||||||
|
- Build time implications understood
|
||||||
|
- CI queue time impact assessed
|
||||||
|
- Resource usage reasonable
|
||||||
|
|
||||||
|
✅ **Rollback Plan**
|
||||||
|
- Can this be reverted easily?
|
||||||
|
- Dependencies on other changes?
|
||||||
|
- Gradual rollout possible?
|
||||||
|
|
||||||
|
✅ **Documentation**
|
||||||
|
- Changes documented for team?
|
||||||
|
- README or CONTRIBUTING updated?
|
||||||
|
- Breaking changes clearly noted?
|
||||||
|
|
||||||
|
## What to SKIP
|
||||||
|
|
||||||
|
❌ **Bikeshedding Configuration** - Unless clear performance/maintenance benefit
|
||||||
|
❌ **Over-Optimization** - Unless current system has proven problems
|
||||||
|
❌ **Suggesting Major Rewrites** - Unless current approach is fundamentally broken
|
||||||
|
|
||||||
|
## Red Flags
|
||||||
|
|
||||||
|
🚩 **Hardcoded secrets** - Use GitHub secrets or secure storage
|
||||||
|
🚩 **No rollback plan** - Critical infrastructure should be revertible
|
||||||
|
🚩 **Untested changes** - CI changes should be validated
|
||||||
|
🚩 **Breaking changes without notice** - Team needs advance warning
|
||||||
|
🚩 **Performance regression** - Builds shouldn't get significantly slower
|
||||||
|
|
||||||
|
## Key Questions to Ask
|
||||||
|
|
||||||
|
Use `reference/review-psychology.md` for phrasing:
|
||||||
|
|
||||||
|
- "What's the rollback plan if this breaks CI?"
|
||||||
|
- "Can we test this on a feature branch before main?"
|
||||||
|
- "Will this impact build times? By how much?"
|
||||||
|
- "Should this be documented in CONTRIBUTING.md?"
|
||||||
|
|
||||||
|
## Common Infrastructure Patterns
|
||||||
|
|
||||||
|
### GitHub Actions
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# ✅ GOOD - Secure, clear, tested
|
||||||
|
name: Build and Test
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 30 # Prevent runaway builds
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- name: Run tests
|
||||||
|
env:
|
||||||
|
API_KEY: ${{ secrets.API_KEY }} # Secure secret usage
|
||||||
|
run: ./gradlew test
|
||||||
|
|
||||||
|
# ❌ BAD - Insecure, unclear
|
||||||
|
name: Build
|
||||||
|
on: push # Too broad, runs on all branches
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
# No timeout - could run forever
|
||||||
|
steps:
|
||||||
|
- run: |
|
||||||
|
export API_KEY="hardcoded_key_here" # Hardcoded secret!
|
||||||
|
./gradlew test
|
||||||
|
```
|
||||||
|
|
||||||
|
### Gradle Configuration
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// ✅ GOOD - Clear, maintainable
|
||||||
|
dependencies {
|
||||||
|
implementation(libs.androidx.core.ktx) // Version catalog
|
||||||
|
implementation(libs.hilt.android)
|
||||||
|
|
||||||
|
testImplementation(libs.junit5)
|
||||||
|
testImplementation(libs.mockk)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ BAD - Hardcoded versions
|
||||||
|
dependencies {
|
||||||
|
implementation("androidx.core:core-ktx:1.12.0") // Hardcoded version
|
||||||
|
implementation("com.google.dagger:hilt-android:2.48")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Build Optimization
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// ✅ GOOD - Parallel, cached
|
||||||
|
tasks.register("checkAll") {
|
||||||
|
dependsOn("detekt", "ktlintCheck", "testStandardDebug")
|
||||||
|
group = "verification"
|
||||||
|
description = "Run all checks in parallel"
|
||||||
|
|
||||||
|
// Enable caching for faster builds
|
||||||
|
outputs.upToDateWhen { false }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ BAD - Sequential, no caching
|
||||||
|
tasks.register("checkAll") {
|
||||||
|
doLast {
|
||||||
|
exec { commandLine("./gradlew", "detekt") }
|
||||||
|
exec { commandLine("./gradlew", "ktlintCheck") } // Sequential
|
||||||
|
exec { commandLine("./gradlew", "test") }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Prioritizing Findings
|
||||||
|
|
||||||
|
Use `reference/priority-framework.md` to classify findings as Critical/Important/Suggested/Optional.
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
|
||||||
|
Follow the format guidance from `SKILL.md` Step 5 (concise summary with critical issues only, detailed inline comments with `<details>` tags).
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** APPROVE / REQUEST CHANGES
|
||||||
|
|
||||||
|
**Critical Issues** (if any):
|
||||||
|
- [One-line summary of each critical blocking issue with file:line reference]
|
||||||
|
|
||||||
|
See inline comments for all issue details.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example Review
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Summary
|
||||||
|
Optimizes CI build by parallelizing test execution and caching dependencies
|
||||||
|
|
||||||
|
Impact: Estimated 40% reduction in CI time (12 min → 7 min per build)
|
||||||
|
|
||||||
|
## Critical Issues
|
||||||
|
None
|
||||||
|
|
||||||
|
## Suggested Improvements
|
||||||
|
|
||||||
|
**.github/workflows/build.yml:23** - Add timeout for safety
|
||||||
|
```yaml
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 30 # Prevent builds from hanging
|
||||||
|
steps:
|
||||||
|
# ...
|
||||||
|
```
|
||||||
|
This prevents runaway builds if something goes wrong.
|
||||||
|
|
||||||
|
**.github/workflows/build.yml:45** - Consider matrix strategy for module tests
|
||||||
|
Can we run module tests in parallel using a matrix strategy?
|
||||||
|
```yaml
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
module: [app, data, network, ui]
|
||||||
|
jobs:
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- run: ./gradlew :${{ matrix.module }}:test
|
||||||
|
```
|
||||||
|
This could further reduce CI time.
|
||||||
|
|
||||||
|
**build.gradle.kts:12** - Document caching strategy
|
||||||
|
Can we add a comment explaining the caching configuration?
|
||||||
|
Future maintainers will appreciate understanding why these specific cache keys are used.
|
||||||
|
|
||||||
|
## Rollback Plan
|
||||||
|
If CI breaks:
|
||||||
|
- Revert commit: `git revert [commit-hash]`
|
||||||
|
- Previous workflow available at: `.github/workflows/build.yml@main^`
|
||||||
|
- Monitor CI times at: https://github.com/[org]/[repo]/actions
|
||||||
|
```
|
||||||
294
.claude/skills/reviewing-changes/checklists/refactoring.md
Normal file
294
.claude/skills/reviewing-changes/checklists/refactoring.md
Normal file
@ -0,0 +1,294 @@
|
|||||||
|
# Refactoring Review Checklist
|
||||||
|
|
||||||
|
## Multi-Pass Strategy
|
||||||
|
|
||||||
|
### First Pass: Understand the Refactoring
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Analyze the refactoring scope:
|
||||||
|
1. What pattern is being improved?
|
||||||
|
2. Why is this refactoring needed?
|
||||||
|
3. Does this change behavior or just structure?
|
||||||
|
4. What's the scope? (files affected, migration completeness)
|
||||||
|
5. What are the risks if something breaks?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
**1. Understand the goal:**
|
||||||
|
- What pattern is being improved?
|
||||||
|
- Why is this refactoring needed?
|
||||||
|
- What's the scope of changes?
|
||||||
|
|
||||||
|
**2. Assess completeness:**
|
||||||
|
- Are all instances refactored or just some?
|
||||||
|
- Are there related areas that should also change?
|
||||||
|
- Is the migration complete or partial?
|
||||||
|
|
||||||
|
**3. Risk assessment:**
|
||||||
|
- Does this change behavior?
|
||||||
|
- How many files affected?
|
||||||
|
- Are tests updated to reflect changes?
|
||||||
|
|
||||||
|
### Second Pass: Verify Consistency
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Verify refactoring quality:
|
||||||
|
1. Is the new pattern applied consistently throughout?
|
||||||
|
2. Are there missed instances of the old pattern?
|
||||||
|
3. Do tests still pass with same behavior?
|
||||||
|
4. Is the migration complete or partial?
|
||||||
|
5. Does this introduce any new issues?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
**4. Pattern consistency:**
|
||||||
|
- Is the new pattern applied consistently throughout?
|
||||||
|
- Are there missed instances of the old pattern?
|
||||||
|
- Does this match established project patterns?
|
||||||
|
|
||||||
|
**5. Migration completeness:**
|
||||||
|
- Old pattern fully removed or deprecated?
|
||||||
|
- All usages updated?
|
||||||
|
- Documentation updated?
|
||||||
|
|
||||||
|
**6. Test coverage:**
|
||||||
|
- Do tests still pass?
|
||||||
|
- Are tests refactored to match?
|
||||||
|
- Does behavior remain unchanged?
|
||||||
|
|
||||||
|
## What to CHECK
|
||||||
|
|
||||||
|
✅ **Pattern Consistency**
|
||||||
|
- New pattern applied consistently across all touched code
|
||||||
|
- Follows established project patterns (MVVM, DI, error handling)
|
||||||
|
- No mix of old and new patterns
|
||||||
|
|
||||||
|
✅ **Migration Completeness**
|
||||||
|
- All instances of old pattern updated?
|
||||||
|
- Deprecated methods removed or marked @Deprecated?
|
||||||
|
- Related code also updated (tests, docs)?
|
||||||
|
|
||||||
|
✅ **Behavior Preservation**
|
||||||
|
- Refactoring doesn't change behavior
|
||||||
|
- Tests still pass
|
||||||
|
- Edge cases still handled
|
||||||
|
|
||||||
|
✅ **Deprecation Strategy** (if applicable)
|
||||||
|
- Old APIs marked @Deprecated with migration guidance
|
||||||
|
- Replacement clearly documented
|
||||||
|
- Timeline for removal specified
|
||||||
|
|
||||||
|
## What to SKIP
|
||||||
|
|
||||||
|
❌ **Suggesting Additional Refactorings** - Unless directly related to current changes
|
||||||
|
❌ **Scope Creep** - Don't request refactoring of untouched code
|
||||||
|
❌ **Perfection** - Better code is better than perfect code
|
||||||
|
|
||||||
|
## Red Flags
|
||||||
|
|
||||||
|
🚩 **Incomplete migration** - Mix of old and new patterns
|
||||||
|
🚩 **Behavior changes** - Refactoring shouldn't change behavior
|
||||||
|
🚩 **Broken tests** - Tests should be updated to match refactoring
|
||||||
|
🚩 **Undocumented pattern** - New pattern should be clear to team
|
||||||
|
|
||||||
|
## Key Questions to Ask
|
||||||
|
|
||||||
|
Use `reference/review-psychology.md` for phrasing:
|
||||||
|
|
||||||
|
- "I see the old pattern still used in [file:line] - should that be updated too?"
|
||||||
|
- "Can we add @Deprecated to the old method with migration guidance?"
|
||||||
|
- "How do we ensure this behavior remains the same?"
|
||||||
|
- "Should this pattern be documented in ARCHITECTURE.md?"
|
||||||
|
|
||||||
|
## Common Refactoring Patterns
|
||||||
|
|
||||||
|
### Extract Interface/Repository
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// ✅ GOOD - Complete migration
|
||||||
|
interface FeatureRepository {
|
||||||
|
suspend fun getData(): Result<Data>
|
||||||
|
}
|
||||||
|
|
||||||
|
class FeatureRepositoryImpl @Inject constructor(
|
||||||
|
private val apiService: FeatureApiService
|
||||||
|
) : FeatureRepository {
|
||||||
|
override suspend fun getData(): Result<Data> = runCatching {
|
||||||
|
apiService.fetchData()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// All usages updated to inject interface
|
||||||
|
class FeatureViewModel @Inject constructor(
|
||||||
|
private val repository: FeatureRepository // Interface
|
||||||
|
) : ViewModel()
|
||||||
|
|
||||||
|
// ❌ BAD - Incomplete migration
|
||||||
|
// Some files still inject FeatureRepositoryImpl directly
|
||||||
|
```
|
||||||
|
|
||||||
|
### Modernize Error Handling
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// ✅ GOOD - Complete migration
|
||||||
|
// Old exception-based removed
|
||||||
|
suspend fun fetchData(): Result<Data> = runCatching {
|
||||||
|
apiService.getData()
|
||||||
|
}
|
||||||
|
|
||||||
|
// All call sites updated
|
||||||
|
repository.fetchData().fold(
|
||||||
|
onSuccess = { /* handle */ },
|
||||||
|
onFailure = { /* handle */ }
|
||||||
|
)
|
||||||
|
|
||||||
|
// ❌ BAD - Mixed patterns
|
||||||
|
// Some functions use Result, others still throw exceptions
|
||||||
|
```
|
||||||
|
|
||||||
|
### Extract Reusable Component
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// ✅ GOOD - Complete extraction
|
||||||
|
// Component moved to :ui module
|
||||||
|
@Composable
|
||||||
|
fun BitwardenButton(
|
||||||
|
text: String,
|
||||||
|
onClick: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier
|
||||||
|
)
|
||||||
|
|
||||||
|
// All usages updated to use new component
|
||||||
|
// Old inline button implementations removed
|
||||||
|
|
||||||
|
// ❌ BAD - Incomplete extraction
|
||||||
|
// Some screens use new component, others still have inline implementation
|
||||||
|
```
|
||||||
|
|
||||||
|
## Prioritizing Findings
|
||||||
|
|
||||||
|
Use `reference/priority-framework.md` to classify findings as Critical/Important/Suggested/Optional.
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
|
||||||
|
Follow the format guidance from `SKILL.md` Step 5 (concise summary with critical issues only, detailed inline comments with `<details>` tags).
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** APPROVE / REQUEST CHANGES
|
||||||
|
|
||||||
|
**Critical Issues** (if any):
|
||||||
|
- [One-line summary of each critical blocking issue with file:line reference]
|
||||||
|
|
||||||
|
See inline comments for all issue details.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example Reviews
|
||||||
|
|
||||||
|
### Example 1: Refactoring with Incomplete Migration
|
||||||
|
|
||||||
|
**Context**: Refactoring authentication to Repository pattern, but one ViewModel still uses old pattern
|
||||||
|
|
||||||
|
**Summary Comment:**
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** REQUEST CHANGES
|
||||||
|
|
||||||
|
**Critical Issues:**
|
||||||
|
- Incomplete migration (app/vault/VaultViewModel.kt:89)
|
||||||
|
|
||||||
|
See inline comments for details.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Inline Comment 1** (on `app/vault/VaultViewModel.kt:89`):
|
||||||
|
```markdown
|
||||||
|
**IMPORTANT**: Incomplete migration
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details and fix</summary>
|
||||||
|
|
||||||
|
This ViewModel still injects AuthManager directly. Should it use AuthRepository like the other 11 ViewModels?
|
||||||
|
|
||||||
|
\```kotlin
|
||||||
|
// Current (old pattern)
|
||||||
|
class VaultViewModel @Inject constructor(
|
||||||
|
private val authManager: AuthManager
|
||||||
|
)
|
||||||
|
|
||||||
|
// Should be (new pattern)
|
||||||
|
class VaultViewModel @Inject constructor(
|
||||||
|
private val authRepository: AuthRepository
|
||||||
|
)
|
||||||
|
\```
|
||||||
|
|
||||||
|
This is the only ViewModel still using the old pattern.
|
||||||
|
</details>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Inline Comment 2** (on `data/auth/AuthManager.kt:1`):
|
||||||
|
```markdown
|
||||||
|
**SUGGESTED**: Add deprecation notice
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details</summary>
|
||||||
|
|
||||||
|
Can we add @Deprecated to AuthManager to guide future development?
|
||||||
|
|
||||||
|
\```kotlin
|
||||||
|
@Deprecated(
|
||||||
|
message = "Use AuthRepository interface instead",
|
||||||
|
replaceWith = ReplaceWith("AuthRepository"),
|
||||||
|
level = DeprecationLevel.WARNING
|
||||||
|
)
|
||||||
|
class AuthManager @Inject constructor(...)
|
||||||
|
\```
|
||||||
|
|
||||||
|
This helps prevent new code from using the old pattern.
|
||||||
|
</details>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Example 2: Clean Refactoring (No Issues)
|
||||||
|
|
||||||
|
**Context**: Refactoring with complete migration, all patterns followed correctly, tests passing
|
||||||
|
|
||||||
|
**Review Comment:**
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** APPROVE
|
||||||
|
|
||||||
|
Clean refactoring moving ExitManager to :ui module. Follows established patterns, eliminates duplication, tests updated correctly.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Token count:** ~30 tokens (vs ~800 for verbose format)
|
||||||
|
|
||||||
|
**Why this works:**
|
||||||
|
- 3 lines total
|
||||||
|
- Clear approval decision
|
||||||
|
- Briefly notes what was done
|
||||||
|
- No elaborate sections, checkmarks, or excessive praise
|
||||||
|
- Author gets immediate green light to merge
|
||||||
|
|
||||||
|
**What NOT to do for clean refactorings:**
|
||||||
|
```markdown
|
||||||
|
❌ DO NOT create these sections:
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
This PR successfully refactors ExitManager into shared code...
|
||||||
|
|
||||||
|
## Key Strengths
|
||||||
|
- ✅ Follows established module organization patterns
|
||||||
|
- ✅ Removes code duplication between apps
|
||||||
|
- ✅ Improves test coverage
|
||||||
|
- ✅ Maintains consistent behavior
|
||||||
|
[...20 more checkmarks...]
|
||||||
|
|
||||||
|
## Code Quality & Architecture
|
||||||
|
**Architectural Compliance:** ✅
|
||||||
|
- Correctly places manager in :ui module
|
||||||
|
- Follows established pattern for UI-layer managers
|
||||||
|
[...detailed analysis...]
|
||||||
|
|
||||||
|
## Changes
|
||||||
|
- ✅ Moved ExitManager interface from app → ui module
|
||||||
|
- ✅ Moved ExitManagerImpl from app → ui module
|
||||||
|
[...listing every file...]
|
||||||
|
```
|
||||||
|
|
||||||
|
This is excessive. **For clean PRs: 2-3 lines maximum.**
|
||||||
233
.claude/skills/reviewing-changes/checklists/ui-refinement.md
Normal file
233
.claude/skills/reviewing-changes/checklists/ui-refinement.md
Normal file
@ -0,0 +1,233 @@
|
|||||||
|
# UI Refinement Review Checklist
|
||||||
|
|
||||||
|
## Multi-Pass Strategy
|
||||||
|
|
||||||
|
### First Pass: Visual Changes
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Analyze the UI changes:
|
||||||
|
1. What visual/UX problem is being solved?
|
||||||
|
2. Are there designs or screenshots to reference?
|
||||||
|
3. Is this affecting existing screens or new ones?
|
||||||
|
4. What's the scope of visual changes?
|
||||||
|
5. Are design tokens (colors, spacing, typography) being used correctly?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
**1. Understand the changes:**
|
||||||
|
- What visual/UX problem is being solved?
|
||||||
|
- Are there designs or screenshots to reference?
|
||||||
|
- Is this a bug fix or enhancement?
|
||||||
|
|
||||||
|
**2. Component usage:**
|
||||||
|
- Using existing components from `:ui` module?
|
||||||
|
- Any new custom components created?
|
||||||
|
- Could existing components be reused?
|
||||||
|
|
||||||
|
### Second Pass: Implementation Review
|
||||||
|
|
||||||
|
<thinking>
|
||||||
|
Check implementation quality:
|
||||||
|
1. Are Compose best practices followed?
|
||||||
|
2. Is state hoisting applied correctly?
|
||||||
|
3. Are existing components reused where possible?
|
||||||
|
4. Is accessibility properly handled?
|
||||||
|
5. Does this follow design system patterns?
|
||||||
|
</thinking>
|
||||||
|
|
||||||
|
**3. Compose best practices:**
|
||||||
|
- Composables properly structured?
|
||||||
|
- State hoisted correctly?
|
||||||
|
- Preview composables included?
|
||||||
|
|
||||||
|
**4. Accessibility:**
|
||||||
|
- Content descriptions for images/icons?
|
||||||
|
- Semantic properties for screen readers?
|
||||||
|
- Touch targets meet minimum size (48dp)?
|
||||||
|
|
||||||
|
**5. Design consistency:**
|
||||||
|
- Using theme colors, spacing, typography?
|
||||||
|
- Consistent with other screens?
|
||||||
|
- Responsive to different screen sizes?
|
||||||
|
|
||||||
|
## What to CHECK
|
||||||
|
|
||||||
|
✅ **Compose Best Practices**
|
||||||
|
- Composables are stateless where possible
|
||||||
|
- State hoisting follows patterns
|
||||||
|
- Side effects (LaunchedEffect, DisposableEffect) used correctly
|
||||||
|
- Preview composables provided for development
|
||||||
|
|
||||||
|
✅ **Component Reuse**
|
||||||
|
- Using existing BitwardenButton, BitwardenTextField, etc.?
|
||||||
|
- Could custom UI be replaced with existing components?
|
||||||
|
- New reusable components placed in `:ui` module?
|
||||||
|
|
||||||
|
✅ **Accessibility**
|
||||||
|
- `contentDescription` for icons and images
|
||||||
|
- `semantics` for custom interactions
|
||||||
|
- Sufficient contrast ratios
|
||||||
|
- Touch targets ≥ 48dp minimum
|
||||||
|
|
||||||
|
✅ **Design Consistency**
|
||||||
|
- Using `BitwardenTheme` colors (not hardcoded)
|
||||||
|
- Using `BitwardenTheme` spacing (16.dp, 8.dp, etc.)
|
||||||
|
- Using `BitwardenTheme` typography styles
|
||||||
|
- Consistent with existing screen patterns
|
||||||
|
|
||||||
|
✅ **Responsive Design**
|
||||||
|
- Handles different screen sizes?
|
||||||
|
- Scrollable content where appropriate?
|
||||||
|
- Landscape orientation considered?
|
||||||
|
|
||||||
|
## What to SKIP
|
||||||
|
|
||||||
|
❌ **Deep Architecture Review** - Unless ViewModel changes are substantial
|
||||||
|
❌ **Business Logic Review** - Focus is on presentation, not logic
|
||||||
|
❌ **Security Review** - Unless UI exposes sensitive data improperly
|
||||||
|
|
||||||
|
## Red Flags
|
||||||
|
|
||||||
|
🚩 **Duplicating existing components** - Should reuse from `:ui` module
|
||||||
|
🚩 **Hardcoded colors/dimensions** - Should use theme
|
||||||
|
🚩 **Missing accessibility properties** - Critical for screen readers
|
||||||
|
🚩 **State management in UI** - Should be hoisted to ViewModel
|
||||||
|
|
||||||
|
## Key Questions to Ask
|
||||||
|
|
||||||
|
Use `reference/review-psychology.md` for phrasing:
|
||||||
|
|
||||||
|
- "Can we use BitwardenButton here instead of this custom button?"
|
||||||
|
- "Should this color come from BitwardenTheme instead of being hardcoded?"
|
||||||
|
- "How will this look on a small screen?"
|
||||||
|
- "Is there a contentDescription for this icon?"
|
||||||
|
|
||||||
|
## Common Patterns
|
||||||
|
|
||||||
|
### Composable Structure
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// ✅ GOOD - Stateless, hoisted state
|
||||||
|
@Composable
|
||||||
|
fun FeatureScreen(
|
||||||
|
state: FeatureState,
|
||||||
|
onActionClick: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier
|
||||||
|
) {
|
||||||
|
// UI rendering only
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ BAD - Business state in composable
|
||||||
|
@Composable
|
||||||
|
fun FeatureScreen() {
|
||||||
|
var userData by remember { mutableStateOf<User?>(null) } // Business state should be in ViewModel
|
||||||
|
var isLoading by remember { mutableStateOf(false) } // App state should be in ViewModel
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
|
||||||
|
// ✅ OK - UI-local state in composable
|
||||||
|
@Composable
|
||||||
|
fun LoginForm(onSubmit: (String, String) -> Unit) {
|
||||||
|
var username by remember { mutableStateOf("") } // UI-local input state is fine
|
||||||
|
var password by remember { mutableStateOf("") }
|
||||||
|
// Hoist only as high as needed
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Theme Usage
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// ✅ GOOD - Using theme
|
||||||
|
Text(
|
||||||
|
text = "Title",
|
||||||
|
style = BitwardenTheme.typography.titleLarge,
|
||||||
|
color = BitwardenTheme.colorScheme.primary
|
||||||
|
)
|
||||||
|
|
||||||
|
// Design system uses 4.dp increments (4, 8, 12, 16, 24, 32, etc.)
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
|
||||||
|
// ❌ BAD - Hardcoded
|
||||||
|
Text(
|
||||||
|
text = "Title",
|
||||||
|
style = TextStyle(fontSize = 24.sp, fontWeight = FontWeight.Bold), // Should use theme
|
||||||
|
color = Color(0xFF0000FF) // Should use theme color
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(17.dp)) // Non-standard spacing
|
||||||
|
```
|
||||||
|
|
||||||
|
### Accessibility
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// ✅ GOOD - Interactive element with description
|
||||||
|
Icon(
|
||||||
|
painter = painterResource(R.drawable.ic_password),
|
||||||
|
contentDescription = "Password visibility toggle",
|
||||||
|
modifier = Modifier.clickable { onToggle() }
|
||||||
|
)
|
||||||
|
|
||||||
|
// ✅ GOOD - Decorative icon with explicit null
|
||||||
|
Icon(
|
||||||
|
painter = painterResource(R.drawable.ic_check),
|
||||||
|
contentDescription = null, // Decorative icon next to descriptive text
|
||||||
|
tint = BitwardenTheme.colorScheme.success
|
||||||
|
)
|
||||||
|
|
||||||
|
// ❌ BAD - Interactive element missing description
|
||||||
|
Icon(
|
||||||
|
painter = painterResource(R.drawable.ic_delete),
|
||||||
|
contentDescription = null, // Interactive elements need descriptions
|
||||||
|
modifier = Modifier.clickable { onDelete() }
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Prioritizing Findings
|
||||||
|
|
||||||
|
Use `reference/priority-framework.md` to classify findings as Critical/Important/Suggested/Optional.
|
||||||
|
|
||||||
|
## Output Format
|
||||||
|
|
||||||
|
Follow the format guidance from `SKILL.md` Step 5 (concise summary with critical issues only, detailed inline comments with `<details>` tags).
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** APPROVE / REQUEST CHANGES
|
||||||
|
|
||||||
|
**Critical Issues** (if any):
|
||||||
|
- [One-line summary of each critical blocking issue with file:line reference]
|
||||||
|
|
||||||
|
See inline comments for all issue details.
|
||||||
|
```
|
||||||
|
|
||||||
|
## Example Review
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Summary
|
||||||
|
Updates login screen layout for improved visual hierarchy and touch targets
|
||||||
|
|
||||||
|
## Critical Issues
|
||||||
|
None
|
||||||
|
|
||||||
|
## Suggested Improvements
|
||||||
|
|
||||||
|
**app/auth/LoginScreen.kt:67** - Can we use BitwardenTextField?
|
||||||
|
This custom text field looks very similar to `ui/components/BitwardenTextField.kt:89`.
|
||||||
|
Would using the existing component maintain consistency?
|
||||||
|
|
||||||
|
**app/auth/LoginScreen.kt:123** - Add contentDescription
|
||||||
|
```kotlin
|
||||||
|
Icon(
|
||||||
|
painter = painterResource(R.drawable.ic_visibility),
|
||||||
|
contentDescription = "Show password", // Add for accessibility
|
||||||
|
modifier = Modifier.clickable { onToggleVisibility() }
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**app/auth/LoginScreen.kt:145** - Use design system spacing
|
||||||
|
```kotlin
|
||||||
|
// Current
|
||||||
|
Spacer(modifier = Modifier.height(17.dp))
|
||||||
|
|
||||||
|
// Design system uses 4.dp increments (4, 8, 12, 16, 24, 32, etc.)
|
||||||
|
Spacer(modifier = Modifier.height(16.dp))
|
||||||
|
```
|
||||||
|
```
|
||||||
446
.claude/skills/reviewing-changes/examples/review-outputs.md
Normal file
446
.claude/skills/reviewing-changes/examples/review-outputs.md
Normal file
@ -0,0 +1,446 @@
|
|||||||
|
# Review Output Examples
|
||||||
|
|
||||||
|
Well-structured code reviews demonstrating appropriate depth, tone, and formatting for different change types.
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
**Format Reference:**
|
||||||
|
- [Quick Format Reference](#quick-format-reference)
|
||||||
|
- [Inline Comment Format](#inline-comment-format-required)
|
||||||
|
- [Summary Comment Format](#summary-comment-format)
|
||||||
|
|
||||||
|
**Examples:**
|
||||||
|
- [Example 1: Clean PR (No Issues)](#example-1-clean-pr-no-issues)
|
||||||
|
- [Example 2: Dependency Update with Breaking Changes](#example-2-dependency-update-with-breaking-changes)
|
||||||
|
- [Example 3: Feature Addition with Critical Issues](#example-3-feature-addition-with-critical-issues)
|
||||||
|
|
||||||
|
**Anti-Patterns:**
|
||||||
|
- [❌ Anti-Patterns to Avoid](#-anti-patterns-to-avoid)
|
||||||
|
- [Problem: Verbose Summary with Multiple Sections](#problem-verbose-summary-with-multiple-sections)
|
||||||
|
- [Problem: Praise-Only Inline Comments](#problem-praise-only-inline-comments)
|
||||||
|
- [Problem: Missing `<details>` Tags](#problem-missing-details-tags)
|
||||||
|
|
||||||
|
**Summary:**
|
||||||
|
- [Summary](#summary)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick Format Reference
|
||||||
|
|
||||||
|
### Inline Comment Format (REQUIRED)
|
||||||
|
|
||||||
|
**MUST use `<details>` tags.** Only severity + description visible; all other content collapsed.
|
||||||
|
|
||||||
|
```
|
||||||
|
[emoji] **[SEVERITY]**: [One-line issue description]
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details and fix</summary>
|
||||||
|
|
||||||
|
[Code example or specific fix]
|
||||||
|
|
||||||
|
[Rationale explaining why]
|
||||||
|
|
||||||
|
Reference: [docs link if applicable]
|
||||||
|
</details>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Severity Levels:**
|
||||||
|
- ❌ **CRITICAL** - Blocking, must fix (security, crashes, architecture violations)
|
||||||
|
- ⚠️ **IMPORTANT** - Should fix (missing tests, quality issues)
|
||||||
|
- ♻️ **DEBT** - Technical debt (duplication, convention violations, future rework needed)
|
||||||
|
- 🎨 **SUGGESTED** - Nice to have (refactoring, improvements)
|
||||||
|
- 💭 **QUESTION** - Seeking clarification (requirements, design decisions)
|
||||||
|
|
||||||
|
### Summary Comment Format
|
||||||
|
|
||||||
|
**Required format for ALL PRs:**
|
||||||
|
```
|
||||||
|
**Overall Assessment:** APPROVE / REQUEST CHANGES
|
||||||
|
|
||||||
|
**Critical Issues** (if any):
|
||||||
|
- [issue with file:line]
|
||||||
|
|
||||||
|
See inline comments for details.
|
||||||
|
```
|
||||||
|
|
||||||
|
All PRs use the same minimal format - no exceptions for size or complexity. Summary must be 5-10 lines maximum.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Example 1: Clean PR (No Issues)
|
||||||
|
|
||||||
|
**Context**: Moving shared code to common module, complete migration, all patterns followed
|
||||||
|
|
||||||
|
**Review Comment:**
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** APPROVE
|
||||||
|
|
||||||
|
Clean refactoring that moves ExitManager to :ui module, eliminating duplication between apps.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why this works:**
|
||||||
|
- Immediate approval visible (2-3 lines)
|
||||||
|
- One sentence acknowledging the work
|
||||||
|
- No unnecessary sections or elaborate praise
|
||||||
|
- Author gets quick feedback and can proceed
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Example 2: Dependency Update with Breaking Changes
|
||||||
|
|
||||||
|
**Context**: Major version update requiring code migration
|
||||||
|
|
||||||
|
**Summary Comment:**
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** REQUEST CHANGES
|
||||||
|
|
||||||
|
**Critical Issues:**
|
||||||
|
- API migration required for Retrofit 3.0 breaking changes (network/api/BitwardenApiService.kt:34)
|
||||||
|
|
||||||
|
See inline comments for migration details.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Inline Comment 1** (on `network/api/BitwardenApiService.kt:34`):
|
||||||
|
```markdown
|
||||||
|
❌ **CRITICAL**: API migration required for Retrofit 3.0
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details and fix</summary>
|
||||||
|
|
||||||
|
Retrofit 3.0 removes the `Call<T>` return type. All 12 API methods in this file need migration:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// Current (deprecated in Retrofit 3.0)
|
||||||
|
@GET("api/accounts/profile")
|
||||||
|
fun getProfile(): Call<ProfileResponse>
|
||||||
|
|
||||||
|
// Must migrate to
|
||||||
|
@GET("api/accounts/profile")
|
||||||
|
suspend fun getProfile(): Response<ProfileResponse>
|
||||||
|
```
|
||||||
|
|
||||||
|
Breaking API change affects:
|
||||||
|
- 12 methods in BitwardenApiService
|
||||||
|
- 8 methods in VaultApiService
|
||||||
|
- All call sites using enqueue/execute
|
||||||
|
- Test utilities
|
||||||
|
|
||||||
|
Consider creating separate PR for this migration given the scope.
|
||||||
|
|
||||||
|
Reference: [Retrofit 3.0 migration guide](https://square.github.io/retrofit/changelogs/changelog-3.x/)
|
||||||
|
</details>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Features:**
|
||||||
|
- Minimal summary (2-3 lines)
|
||||||
|
- Full details in collapsed inline comment
|
||||||
|
- Specific file:line references
|
||||||
|
- Code examples in <details>
|
||||||
|
- Migration guidance and scope assessment
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Example 3: Feature Addition with Critical Issues
|
||||||
|
|
||||||
|
**Context**: Implements PIN unlock for vault access
|
||||||
|
|
||||||
|
**Summary Comment:**
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** REQUEST CHANGES
|
||||||
|
|
||||||
|
**Critical Issues:**
|
||||||
|
- Exposes mutable state violating MVVM (UnlockViewModel.kt:78)
|
||||||
|
- PIN stored without encryption - SECURITY ISSUE (UnlockRepository.kt:145)
|
||||||
|
|
||||||
|
See inline comments for all issues and suggestions.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Inline Comment 1** (on `app/vault/unlock/UnlockViewModel.kt:78`):
|
||||||
|
```markdown
|
||||||
|
❌ **CRITICAL**: Exposes mutable state
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details and fix</summary>
|
||||||
|
|
||||||
|
Change `MutableStateFlow<State>` to `StateFlow<State>`:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// Current (problematic)
|
||||||
|
val unlockState: MutableStateFlow<UnlockState>
|
||||||
|
|
||||||
|
// Should be
|
||||||
|
private val _unlockState = MutableStateFlow<UnlockState>()
|
||||||
|
val unlockState: StateFlow<UnlockState> = _unlockState.asStateFlow()
|
||||||
|
```
|
||||||
|
|
||||||
|
Exposing MutableStateFlow allows external mutation, violating MVVM unidirectional data flow.
|
||||||
|
|
||||||
|
Reference: docs/ARCHITECTURE.md#mvvm-pattern
|
||||||
|
</details>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Inline Comment 2** (on `data/vault/UnlockRepository.kt:145`):
|
||||||
|
```markdown
|
||||||
|
❌ **CRITICAL**: PIN stored without encryption - SECURITY ISSUE
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details and fix</summary>
|
||||||
|
|
||||||
|
Storing PIN in plaintext SharedPreferences exposes it to backup systems and rooted devices.
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
// Current (CRITICAL SECURITY ISSUE)
|
||||||
|
sharedPreferences.edit {
|
||||||
|
putString(KEY_PIN, pin)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Must use Android Keystore encryption
|
||||||
|
suspend fun storePin(pin: String): Result<Unit> = runCatching {
|
||||||
|
val encrypted = keystoreManager.encrypt(pin.toByteArray())
|
||||||
|
encryptedPrefs.putBytes(KEY_PIN, encrypted)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Use Android Keystore encryption or EncryptedSharedPreferences per security architecture.
|
||||||
|
|
||||||
|
Reference: docs/ARCHITECTURE.md#security
|
||||||
|
</details>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Inline Comment 3** (on `app/vault/unlock/UnlockViewModel.kt:92`):
|
||||||
|
```markdown
|
||||||
|
⚠️ **IMPORTANT**: Missing error handling test
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details and fix</summary>
|
||||||
|
|
||||||
|
Add test to prevent regression if error handling changes:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
@Test
|
||||||
|
fun `when incorrect PIN entered then returns error state`() = runTest {
|
||||||
|
val viewModel = UnlockViewModel(mockRepository)
|
||||||
|
coEvery { mockRepository.validatePin("1234") }
|
||||||
|
returns Result.failure(InvalidPinException())
|
||||||
|
|
||||||
|
viewModel.onPinEntered("1234")
|
||||||
|
|
||||||
|
assertEquals(UnlockState.Error("Invalid PIN"), viewModel.state.value)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Ensures error flow remains robust across refactorings.
|
||||||
|
</details>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Inline Comment 4** (on `app/vault/unlock/UnlockViewModel.kt:105`):
|
||||||
|
```markdown
|
||||||
|
🎨 **SUGGESTED**: Consider rate limiting for PIN attempts
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details and fix</summary>
|
||||||
|
|
||||||
|
Currently allows unlimited attempts, which could enable brute force attacks.
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
private var attemptCount = 0
|
||||||
|
private var lockoutUntil: Instant? = null
|
||||||
|
|
||||||
|
fun onPinEntered(pin: String) {
|
||||||
|
if (isLockedOut()) {
|
||||||
|
_state.value = UnlockState.LockedOut(lockoutUntil!!)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// ... validate PIN ...
|
||||||
|
if (invalid) {
|
||||||
|
attemptCount++
|
||||||
|
if (attemptCount >= MAX_ATTEMPTS) {
|
||||||
|
lockoutUntil = clock.millis() + 15.minutes
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Would add security layer against brute force. Consider discussing threat model with security team.
|
||||||
|
</details>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Inline Comment 5** (on `app/vault/unlock/UnlockScreen.kt:134`):
|
||||||
|
```markdown
|
||||||
|
💭 **QUESTION**: Can we use BitwardenTextField?
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details</summary>
|
||||||
|
|
||||||
|
This custom PIN input field looks similar to `ui/components/BitwardenTextField.kt:67`.
|
||||||
|
|
||||||
|
Would using the existing component maintain consistency and reduce custom UI code?
|
||||||
|
</details>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Features:**
|
||||||
|
- Minimal summary (3-4 lines) with critical issues only
|
||||||
|
- Each issue gets separate inline comment with `<details>` tag
|
||||||
|
- Multiple severity levels demonstrated (CRITICAL, IMPORTANT, SUGGESTED, QUESTION)
|
||||||
|
- Mix of prescriptive fixes and collaborative questions
|
||||||
|
- Code examples collapsed in <details>
|
||||||
|
- No "Good Practices" or "Action Items" sections
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ❌ Anti-Patterns to Avoid
|
||||||
|
|
||||||
|
### Problem: Verbose Summary with Multiple Sections
|
||||||
|
|
||||||
|
**What NOT to do:**
|
||||||
|
```markdown
|
||||||
|
### Review Complete ✅
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
[Lengthy description of what the PR does]
|
||||||
|
|
||||||
|
### Strengths 👍
|
||||||
|
1. **Excellent documentation** - KDoc comments are comprehensive
|
||||||
|
2. **Proper fail-closed design** - Security defaults to rejection
|
||||||
|
3. **Defense in depth** - Multiple validation layers
|
||||||
|
[7 total items with elaboration]
|
||||||
|
|
||||||
|
### Critical Issues ⚠️
|
||||||
|
- Missing test coverage for security-critical code (with full details)
|
||||||
|
- [More issues with full explanations]
|
||||||
|
|
||||||
|
### Recommendations 🎨
|
||||||
|
- [Multiple recommendations]
|
||||||
|
|
||||||
|
### Test Coverage Status 📊
|
||||||
|
- [Analysis]
|
||||||
|
|
||||||
|
### Architecture Compliance ✅
|
||||||
|
- [Analysis]
|
||||||
|
|
||||||
|
## Recommendation
|
||||||
|
**Conditional approval** with follow-up...
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why this is wrong:**
|
||||||
|
- 800+ tokens for a summary comment
|
||||||
|
- Multiple sections (Strengths, Recommendations, Test Coverage, Architecture)
|
||||||
|
- Elaborates on positive aspects ("Excellent documentation...")
|
||||||
|
- Duplicates critical issues (summary has details + inline comments have same details)
|
||||||
|
- Creates visual clutter in PR conversation
|
||||||
|
|
||||||
|
**Correct approach:**
|
||||||
|
```markdown
|
||||||
|
**Overall Assessment:** REQUEST CHANGES
|
||||||
|
|
||||||
|
**Critical Issues:**
|
||||||
|
- Missing test coverage for security-critical code (PasswordManagerSignatureVerifierImpl.kt:47)
|
||||||
|
|
||||||
|
See inline comments for details.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key differences:**
|
||||||
|
- 3-5 lines vs 800+ tokens
|
||||||
|
- Verdict + critical issues only
|
||||||
|
- All details belong in inline comments
|
||||||
|
- No positive commentary sections
|
||||||
|
- Scales with PR complexity, not analysis thoroughness
|
||||||
|
|
||||||
|
### Problem: Praise-Only Inline Comments
|
||||||
|
|
||||||
|
**What NOT to do:**
|
||||||
|
|
||||||
|
Creating inline comment on `AuthenticatorBridgeManagerImpl.kt:73`:
|
||||||
|
```markdown
|
||||||
|
👍 **Excellent integration of signature verification**
|
||||||
|
|
||||||
|
The signature verification is properly integrated into the connection flow:
|
||||||
|
- Checked during initialization (line 73)
|
||||||
|
- Checked before binding (line 134)
|
||||||
|
- Ensures only validated apps can connect
|
||||||
|
|
||||||
|
This is exactly the right approach for fail-safe security.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why this is wrong:**
|
||||||
|
- Entire comment is positive feedback with no actionable issue
|
||||||
|
- Takes up space in PR conversation
|
||||||
|
- Distracts from actual issues
|
||||||
|
- Violates "focus on actionable feedback" principle
|
||||||
|
|
||||||
|
**Correct approach:**
|
||||||
|
- Do not create this comment at all
|
||||||
|
- Reserve inline comments exclusively for issues requiring attention
|
||||||
|
|
||||||
|
### Problem: Missing `<details>` Tags
|
||||||
|
|
||||||
|
**What NOT to do:**
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
❌ **CRITICAL**: Missing test coverage for security-critical code
|
||||||
|
|
||||||
|
The `@OmitFromCoverage` annotation excludes this entire class from test coverage.
|
||||||
|
|
||||||
|
**Problems:**
|
||||||
|
1. No validation that certificate hashes match actual Bitwarden certificates
|
||||||
|
2. No verification of fail-closed behavior on edge cases
|
||||||
|
3. No tests for multiple signer rejection logic
|
||||||
|
4. Certificate hash typos would go undetected until production
|
||||||
|
|
||||||
|
**Recommendation:**
|
||||||
|
Replace `@OmitFromCoverage` with proper unit tests.
|
||||||
|
|
||||||
|
Example test structure:
|
||||||
|
[long code block]
|
||||||
|
|
||||||
|
Security-critical code should have the highest test coverage, not be omitted.
|
||||||
|
```
|
||||||
|
|
||||||
|
**Why this is wrong:**
|
||||||
|
- All content visible immediately (code examples, problems list, rationale)
|
||||||
|
- Creates visual clutter in PR conversation
|
||||||
|
- Makes it hard to scan multiple issues quickly
|
||||||
|
|
||||||
|
**Correct approach:**
|
||||||
|
```markdown
|
||||||
|
❌ **CRITICAL**: Missing test coverage for security-critical code
|
||||||
|
|
||||||
|
<details>
|
||||||
|
<summary>Details and fix</summary>
|
||||||
|
|
||||||
|
The `@OmitFromCoverage` annotation excludes this entire class from test coverage.
|
||||||
|
|
||||||
|
**Problems:**
|
||||||
|
1. No validation that certificate hashes match actual Bitwarden certificates
|
||||||
|
2. No verification of fail-closed behavior on edge cases
|
||||||
|
3. No tests for multiple signer rejection logic
|
||||||
|
4. Certificate hash typos would go undetected until production
|
||||||
|
|
||||||
|
**Recommendation:**
|
||||||
|
Replace `@OmitFromCoverage` with proper unit tests.
|
||||||
|
|
||||||
|
Example test structure:
|
||||||
|
[code block]
|
||||||
|
|
||||||
|
Security-critical code should have the highest test coverage, not be omitted.
|
||||||
|
</details>
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key difference:** Only severity + one-line description visible. All details collapsed.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
**Always use:**
|
||||||
|
- Minimal summary (verdict + critical issues)
|
||||||
|
- Separate inline comments with `<details>` tags
|
||||||
|
- Hybrid emoji + text severity prefixes
|
||||||
|
- Focus exclusively on actionable feedback
|
||||||
|
|
||||||
|
**Never use:**
|
||||||
|
- Multiple summary sections (Strengths, Recommendations, etc.)
|
||||||
|
- Praise-only inline comments
|
||||||
|
- Duplication between summary and inline comments
|
||||||
|
- Verbose analysis in summary (belongs in inline comments)
|
||||||
@ -0,0 +1,312 @@
|
|||||||
|
# Architectural Patterns Quick Reference
|
||||||
|
|
||||||
|
Quick reference for Bitwarden Android architectural patterns during code reviews. For comprehensive details, read `docs/ARCHITECTURE.md` and `docs/STYLE_AND_BEST_PRACTICES.md`.
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
**Core Patterns:**
|
||||||
|
- [MVVM + UDF Pattern](#mvvm--udf-pattern)
|
||||||
|
- [ViewModel Structure](#viewmodel-structure)
|
||||||
|
- [UI Layer (Compose)](#ui-layer-compose)
|
||||||
|
- [Hilt Dependency Injection](#hilt-dependency-injection)
|
||||||
|
- [ViewModels](#viewmodels)
|
||||||
|
- [Repositories and Managers](#repositories-and-managers)
|
||||||
|
- [Module Organization](#module-organization)
|
||||||
|
- [Error Handling](#error-handling)
|
||||||
|
- [Use Result Types, Not Exceptions](#use-result-types-not-exceptions)
|
||||||
|
- [Quick Checklist](#quick-checklist)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## MVVM + UDF Pattern
|
||||||
|
|
||||||
|
### ViewModel Structure
|
||||||
|
|
||||||
|
**✅ GOOD - Proper state encapsulation**:
|
||||||
|
```kotlin
|
||||||
|
@HiltViewModel
|
||||||
|
class FeatureViewModel @Inject constructor(
|
||||||
|
private val repository: FeatureRepository
|
||||||
|
) : ViewModel() {
|
||||||
|
// Private mutable state
|
||||||
|
private val _state = MutableStateFlow<FeatureState>(FeatureState.Initial)
|
||||||
|
|
||||||
|
// Public immutable state
|
||||||
|
val state: StateFlow<FeatureState> = _state.asStateFlow()
|
||||||
|
|
||||||
|
// Actions as functions, state updated via internal action
|
||||||
|
fun onActionClicked() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val result = repository.performAction()
|
||||||
|
sendAction(FeatureAction.Internal.ActionComplete(result))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The ViewModel has a handler that processes the internal action
|
||||||
|
private fun handleInternalAction(action: FeatureAction.Internal) {
|
||||||
|
when (action) {
|
||||||
|
is FeatureAction.Internal.ActionComplete -> {
|
||||||
|
// The action handler evaluates the result and updates state
|
||||||
|
action.result.fold(
|
||||||
|
onSuccess = { _state.value = State.Success },
|
||||||
|
onFailure = { _state.value = State.Error(it) }
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**❌ BAD - Common violations**:
|
||||||
|
```kotlin
|
||||||
|
class FeatureViewModel : ViewModel() {
|
||||||
|
// ❌ Exposes mutable state
|
||||||
|
val state: MutableStateFlow<FeatureState>
|
||||||
|
|
||||||
|
// ❌ Business logic in ViewModel
|
||||||
|
fun onSubmit() {
|
||||||
|
val encrypted = encryptionManager.encrypt(data) // Should be in Repository
|
||||||
|
_state.value = FeatureState.Success
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ Direct Android framework dependency
|
||||||
|
fun onCreate(context: Context) { // ViewModels shouldn't depend on Context
|
||||||
|
// ...
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Rules**:
|
||||||
|
- Expose `StateFlow<T>`, never `MutableStateFlow<T>`
|
||||||
|
- Delegate business logic to Repository/Manager
|
||||||
|
- No direct Android framework dependencies (except ViewModel, SavedStateHandle)
|
||||||
|
- Use `viewModelScope` for coroutines
|
||||||
|
|
||||||
|
Reference: `docs/ARCHITECTURE.md#mvvm-pattern`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### UI Layer (Compose)
|
||||||
|
|
||||||
|
**✅ GOOD - Stateless, observes only**:
|
||||||
|
```kotlin
|
||||||
|
@Composable
|
||||||
|
fun FeatureScreen(
|
||||||
|
state: FeatureState,
|
||||||
|
onActionClick: () -> Unit,
|
||||||
|
modifier: Modifier = Modifier
|
||||||
|
) {
|
||||||
|
Column(modifier = modifier) {
|
||||||
|
when (state) {
|
||||||
|
is FeatureState.Loading -> LoadingIndicator()
|
||||||
|
is FeatureState.Success -> SuccessContent(state.data)
|
||||||
|
is FeatureState.Error -> ErrorMessage(state.error)
|
||||||
|
}
|
||||||
|
|
||||||
|
BitwardenButton(
|
||||||
|
text = "Action",
|
||||||
|
onClick = onActionClick // Sends event to ViewModel
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**❌ BAD - Stateful, modifies state**:
|
||||||
|
```kotlin
|
||||||
|
@Composable
|
||||||
|
fun FeatureScreen(viewModel: FeatureViewModel) {
|
||||||
|
var localState by remember { mutableStateOf(...) } // ❌ State in UI
|
||||||
|
|
||||||
|
Button(onClick = {
|
||||||
|
viewModel._state.value = FeatureState.Loading // ❌ Directly modifying ViewModel state
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Rules**:
|
||||||
|
- Compose screens observe state, never modify
|
||||||
|
- User actions passed as events/callbacks to ViewModel
|
||||||
|
- No business logic in UI layer
|
||||||
|
- Use existing components from `:ui` module
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Hilt Dependency Injection
|
||||||
|
|
||||||
|
### ViewModels
|
||||||
|
|
||||||
|
**✅ GOOD - Interface injection**:
|
||||||
|
```kotlin
|
||||||
|
@HiltViewModel
|
||||||
|
class FeatureViewModel @Inject constructor(
|
||||||
|
private val repository: FeatureRepository, // Interface, not implementation
|
||||||
|
private val authManager: AuthManager,
|
||||||
|
savedStateHandle: SavedStateHandle
|
||||||
|
) : ViewModel()
|
||||||
|
```
|
||||||
|
|
||||||
|
**❌ BAD - Common violations**:
|
||||||
|
```kotlin
|
||||||
|
// ❌ No @HiltViewModel annotation
|
||||||
|
class FeatureViewModel @Inject constructor(...)
|
||||||
|
|
||||||
|
// ❌ Injecting implementation instead of interface
|
||||||
|
class FeatureViewModel @Inject constructor(
|
||||||
|
private val repository: FeatureRepositoryImpl // Should inject interface
|
||||||
|
)
|
||||||
|
|
||||||
|
// ❌ Manual instantiation
|
||||||
|
class FeatureViewModel : ViewModel() {
|
||||||
|
private val repository = FeatureRepositoryImpl() // Should use @Inject
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Rules**:
|
||||||
|
- Annotate with `@HiltViewModel`
|
||||||
|
- Use `@Inject constructor`
|
||||||
|
- Inject interfaces, not implementations
|
||||||
|
- Use `SavedStateHandle` for process death survival
|
||||||
|
|
||||||
|
Reference: `docs/ARCHITECTURE.md#dependency-injection`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Repositories and Managers
|
||||||
|
|
||||||
|
**✅ GOOD - Implementation with @Inject**:
|
||||||
|
```kotlin
|
||||||
|
interface FeatureRepository {
|
||||||
|
suspend fun fetchData(): Result<Data>
|
||||||
|
}
|
||||||
|
|
||||||
|
class FeatureRepositoryImpl @Inject constructor(
|
||||||
|
private val apiService: FeatureApiService,
|
||||||
|
private val database: FeatureDao
|
||||||
|
) : FeatureRepository {
|
||||||
|
override suspend fun fetchData(): Result<Data> = runCatching {
|
||||||
|
apiService.getData()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Module provides interface**:
|
||||||
|
```kotlin
|
||||||
|
@Module
|
||||||
|
@InstallIn(SingletonComponent::class)
|
||||||
|
abstract class DataModule {
|
||||||
|
@Binds
|
||||||
|
@Singleton
|
||||||
|
abstract fun bindFeatureRepository(
|
||||||
|
impl: FeatureRepositoryImpl
|
||||||
|
): FeatureRepository
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Rules**:
|
||||||
|
- Define interface for abstraction
|
||||||
|
- Implementation uses `@Inject constructor`
|
||||||
|
- Module binds implementation to interface
|
||||||
|
- Appropriate scoping (`@Singleton`, `@ViewModelScoped`)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Module Organization
|
||||||
|
|
||||||
|
```
|
||||||
|
android/
|
||||||
|
├── core/ # Shared utilities (cryptography, analytics, logging)
|
||||||
|
├── data/ # Repositories, database, domain models
|
||||||
|
├── network/ # API clients, network utilities
|
||||||
|
├── ui/ # Reusable Compose components, theme
|
||||||
|
├── app/ # Application, feature screens, ViewModels
|
||||||
|
└── authenticator/ # Authenticator app (separate from password manager)
|
||||||
|
```
|
||||||
|
|
||||||
|
**Correct Placement**:
|
||||||
|
- UI screens and ViewModels → `:app`
|
||||||
|
- Reusable Compose components → `:ui`
|
||||||
|
- Data models and Repositories → `:data`
|
||||||
|
- API services → `:network`
|
||||||
|
- Cryptography, logging → `:core`
|
||||||
|
|
||||||
|
**Check for**:
|
||||||
|
- No circular dependencies
|
||||||
|
- Correct module placement
|
||||||
|
- Proper visibility (internal vs public)
|
||||||
|
|
||||||
|
Reference: `docs/ARCHITECTURE.md#module-structure`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Error Handling
|
||||||
|
|
||||||
|
### Use Result Types, Not Exceptions
|
||||||
|
|
||||||
|
**✅ GOOD - Result-based**:
|
||||||
|
```kotlin
|
||||||
|
// Repository
|
||||||
|
suspend fun fetchData(): Result<Data> = runCatching {
|
||||||
|
apiService.getData()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ViewModel
|
||||||
|
fun onFetch() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
val result = repository.fetchData()
|
||||||
|
sendAction(FeatureAction.Internal.FetchComplete(result))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**❌ BAD - Exception-based in business logic**:
|
||||||
|
```kotlin
|
||||||
|
// ❌ Don't throw in business logic
|
||||||
|
suspend fun fetchData(): Data {
|
||||||
|
try {
|
||||||
|
return apiService.getData()
|
||||||
|
} catch (e: Exception) {
|
||||||
|
throw FeatureException(e) // Don't throw in repositories
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ Try-catch in ViewModel
|
||||||
|
fun onFetch() {
|
||||||
|
viewModelScope.launch {
|
||||||
|
try {
|
||||||
|
val data = repository.fetchData()
|
||||||
|
sendAction(FeatureAction.Internal.FetchComplete(data))
|
||||||
|
} catch (e: Exception) {
|
||||||
|
sendAction(FeatureAction.Internal.FetchComplete(e))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Rules**:
|
||||||
|
- Use `Result<T>` return types in repositories
|
||||||
|
- Use `runCatching { }` to wrap API calls
|
||||||
|
- Handle results with `.fold()` in ViewModels
|
||||||
|
- Don't throw exceptions in business logic
|
||||||
|
|
||||||
|
Reference: `docs/ARCHITECTURE.md#error-handling`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick Checklist
|
||||||
|
|
||||||
|
### Architecture
|
||||||
|
- [ ] ViewModels expose StateFlow, not MutableStateFlow?
|
||||||
|
- [ ] Business logic in Repository, not ViewModel?
|
||||||
|
- [ ] Using Hilt DI (@HiltViewModel, @Inject constructor)?
|
||||||
|
- [ ] Injecting interfaces, not implementations?
|
||||||
|
- [ ] Correct module placement?
|
||||||
|
|
||||||
|
### Error Handling
|
||||||
|
- [ ] Using Result types, not exceptions in business logic?
|
||||||
|
- [ ] Errors handled with .fold() in ViewModels?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
For comprehensive details, always refer to:
|
||||||
|
- `docs/ARCHITECTURE.md` - Full architecture patterns
|
||||||
|
- `docs/STYLE_AND_BEST_PRACTICES.md` - Complete style guide
|
||||||
431
.claude/skills/reviewing-changes/reference/priority-framework.md
Normal file
431
.claude/skills/reviewing-changes/reference/priority-framework.md
Normal file
@ -0,0 +1,431 @@
|
|||||||
|
# Finding Priority Framework
|
||||||
|
|
||||||
|
Use this framework to classify findings during code review. Clear prioritization helps authors triage and address issues effectively.
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
**Severity Categories:**
|
||||||
|
- [❌ CRITICAL (Blocker - Must Fix Before Merge)](#critical-blocker---must-fix-before-merge)
|
||||||
|
- [⚠️ IMPORTANT (Should Fix)](#important-should-fix)
|
||||||
|
- [♻️ DEBT (Technical Debt)](#debt-technical-debt)
|
||||||
|
- [🎨 SUGGESTED (Nice to Have)](#suggested-nice-to-have)
|
||||||
|
- [💭 QUESTION (Seeking Clarification)](#question-seeking-clarification)
|
||||||
|
- [Optional (Acknowledge But Don't Require)](#optional-acknowledge-but-dont-require)
|
||||||
|
|
||||||
|
**Guidelines:**
|
||||||
|
- [Classification Guidelines](#classification-guidelines)
|
||||||
|
- [When Something is Between Categories](#when-something-is-between-categories)
|
||||||
|
- [Context Matters](#context-matters)
|
||||||
|
- [Examples by Change Type](#examples-by-change-type)
|
||||||
|
- [Special Cases](#special-cases)
|
||||||
|
- [Summary](#summary)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ❌ **CRITICAL** (Blocker - Must Fix Before Merge)
|
||||||
|
|
||||||
|
These issues **must** be addressed before the PR can be merged. They pose immediate risks to security, stability, or architecture integrity.
|
||||||
|
|
||||||
|
### Security
|
||||||
|
- Data leaks or plaintext sensitive data (passwords, keys, tokens)
|
||||||
|
- Weak encryption or insecure key storage
|
||||||
|
- Missing authentication or authorization checks
|
||||||
|
- Input injection vulnerabilities (SQL, XSS, command injection)
|
||||||
|
- Sensitive data in logs or error messages
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**data/vault/VaultRepository.kt:145** - CRITICAL: PIN stored without encryption
|
||||||
|
PIN must be encrypted using Android Keystore, not stored in plaintext SharedPreferences.
|
||||||
|
Reference: docs/ARCHITECTURE.md#security
|
||||||
|
```
|
||||||
|
|
||||||
|
### Stability
|
||||||
|
- Compilation errors or warnings
|
||||||
|
- Null pointer exceptions in production paths
|
||||||
|
- Resource leaks (file handles, network connections, memory)
|
||||||
|
- Crashes or unhandled exceptions in critical paths
|
||||||
|
- Thread safety violations
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**app/auth/BiometricRepository.kt:120** - CRITICAL: Missing null safety check
|
||||||
|
biometricPrompt result can be null. Add explicit null check to prevent crash.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Architecture
|
||||||
|
- Mutable state exposure in ViewModels (violates MVVM)
|
||||||
|
- Exception-based error handling in business logic (should use Result)
|
||||||
|
- Circular dependencies between modules
|
||||||
|
- Violation of zero-knowledge principles
|
||||||
|
- Direct dependency instantiation (should use DI)
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**app/login/LoginViewModel.kt:45** - CRITICAL: Exposes mutable state
|
||||||
|
Change MutableStateFlow to StateFlow in public API to prevent external state mutation.
|
||||||
|
This violates MVVM encapsulation pattern.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚠️ **IMPORTANT** (Should Fix)
|
||||||
|
|
||||||
|
These issues should be addressed but don't block merge if there's a compelling reason. They improve code quality, maintainability, or robustness.
|
||||||
|
|
||||||
|
### Testing
|
||||||
|
- Missing tests for critical paths (authentication, encryption, data sync)
|
||||||
|
- Missing tests for new public APIs
|
||||||
|
- Tests that don't verify actual behavior (test implementation, not behavior)
|
||||||
|
- Missing test coverage for error scenarios
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**data/auth/BiometricRepository.kt** - IMPORTANT: Missing test for cancellation
|
||||||
|
Add test for user cancellation scenario to prevent regression.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Architecture
|
||||||
|
- Inconsistent patterns within PR (mixing error handling approaches)
|
||||||
|
- Poor separation of concerns
|
||||||
|
- Tight coupling between components
|
||||||
|
- Not following established project patterns
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**app/vault/VaultViewModel.kt:89** - IMPORTANT: Business logic in ViewModel
|
||||||
|
Encryption logic should be in Repository, not ViewModel.
|
||||||
|
Reference: docs/ARCHITECTURE.md#mvvm-pattern
|
||||||
|
```
|
||||||
|
|
||||||
|
### Documentation
|
||||||
|
- Undocumented public APIs (missing KDoc)
|
||||||
|
- Missing documentation for complex algorithms
|
||||||
|
- Unclear naming or confusing interfaces
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**core/crypto/EncryptionManager.kt:34** - IMPORTANT: Missing KDoc
|
||||||
|
Public encryption method should document parameters, return value, and exceptions.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Performance
|
||||||
|
- Inefficient algorithms in hot paths (with evidence from profiling)
|
||||||
|
- Blocking main thread with I/O operations
|
||||||
|
- Memory inefficient data structures (with evidence)
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**app/vault/VaultListViewModel.kt:78** - IMPORTANT: N+1 query pattern
|
||||||
|
Fetching items one-by-one in loop. Consider batch fetch to reduce database queries.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ♻️ **DEBT** (Technical Debt)
|
||||||
|
|
||||||
|
Code that duplicates existing patterns, violates established conventions, or will require rework within 6 months. Introduces technical debt that should be tracked for future cleanup.
|
||||||
|
|
||||||
|
### Duplication
|
||||||
|
- Copy-pasted code blocks across files
|
||||||
|
- Repeated validation or business logic
|
||||||
|
- Multiple implementations of same pattern
|
||||||
|
- Data transformation duplicated in multiple places
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**app/vault/VaultListViewModel.kt:156** - DEBT: Duplicates encryption logic
|
||||||
|
Same encryption pattern exists in VaultRepository.kt:234 and SyncManager.kt:89.
|
||||||
|
Extract to shared EncryptionUtil to reduce maintenance burden.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Convention Violations
|
||||||
|
- Inconsistent error handling approaches within same module
|
||||||
|
- Mixing architectural patterns (MVVM + MVC)
|
||||||
|
- Not following established DI patterns
|
||||||
|
- Deviating from project code style significantly
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**data/auth/AuthRepository.kt:78** - DEBT: Exception-based error handling
|
||||||
|
Project standard is Result<T> for error handling. This uses try-catch with throws.
|
||||||
|
Creates inconsistency and makes testing harder.
|
||||||
|
Reference: docs/ARCHITECTURE.md#error-handling
|
||||||
|
```
|
||||||
|
|
||||||
|
### Future Rework Required
|
||||||
|
- Hardcoded values that should be configurable
|
||||||
|
- Temporary workarounds without TODO/FIXME
|
||||||
|
- Code that will need changes when planned features arrive
|
||||||
|
- Tight coupling that prevents future extensibility
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**app/settings/SettingsViewModel.kt:45** - DEBT: Hardcoded feature flags
|
||||||
|
Feature flags should come from remote config for A/B testing.
|
||||||
|
Will require rework when experimentation framework launches.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎨 **SUGGESTED** (Nice to Have)
|
||||||
|
|
||||||
|
These are improvement opportunities but not required. Consider the effort vs. benefit before requesting changes.
|
||||||
|
|
||||||
|
### Code Quality
|
||||||
|
- Minor style inconsistencies (if not caught by linter)
|
||||||
|
- Opportunities for DRY improvements
|
||||||
|
- Better variable naming for clarity
|
||||||
|
- Simplification opportunities
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**app/vault/VaultScreen.kt:145** - SUGGESTED: Consider extracting helper function
|
||||||
|
This 20-line block appears in 3 places. Consider extracting to reduce duplication.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Testing
|
||||||
|
- Additional test coverage for edge cases (beyond critical paths)
|
||||||
|
- More comprehensive integration tests
|
||||||
|
- Performance tests for non-critical paths
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**app/login/LoginViewModelTest.kt** - SUGGESTED: Add test for concurrent login attempts
|
||||||
|
Not critical, but would increase confidence in edge case handling.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Refactoring
|
||||||
|
- Extracting reusable patterns
|
||||||
|
- Modernizing old patterns (if touching related code)
|
||||||
|
- Improving testability
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**data/vault/VaultRepository.kt:200** - SUGGESTED: Consider extracting validation logic
|
||||||
|
Could be extracted to separate validator class for reusability and testing.
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💭 **QUESTION** (Seeking Clarification)
|
||||||
|
|
||||||
|
Questions about requirements, unclear intent, or potential conflicts that require human knowledge to answer. Open inquiries that cannot be resolved through code inspection alone.
|
||||||
|
|
||||||
|
### Requirements Clarification
|
||||||
|
- Ambiguous acceptance criteria
|
||||||
|
- Multiple valid implementation approaches
|
||||||
|
- Unclear business rules or edge case handling
|
||||||
|
- Conflicting requirements between specs and implementation
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**app/vault/ItemListViewModel.kt:67** - QUESTION: Expected sort behavior for equal timestamps?
|
||||||
|
When items have identical timestamps, should secondary sort be by:
|
||||||
|
- Name (alphabetical)
|
||||||
|
- Creation order
|
||||||
|
- Item type priority
|
||||||
|
|
||||||
|
Spec doesn't specify tie-breaking logic.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Design Decisions
|
||||||
|
- Architecture choices that could go multiple ways
|
||||||
|
- Trade-offs between approaches without clear winner
|
||||||
|
- Feature flag strategy or rollout approach
|
||||||
|
- API design with multiple valid patterns
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**data/sync/SyncManager.kt:134** - QUESTION: Should sync failures retry automatically?
|
||||||
|
Current implementation fails immediately. Options:
|
||||||
|
- Exponential backoff (3 retries)
|
||||||
|
- User-triggered retry only
|
||||||
|
- Background retry on network restore
|
||||||
|
|
||||||
|
What's the expected UX?
|
||||||
|
```
|
||||||
|
|
||||||
|
### System Integration
|
||||||
|
- Unclear contracts with external systems
|
||||||
|
- Potential conflicts with other features/modules
|
||||||
|
- Assumptions about third-party API behavior
|
||||||
|
- Cross-team coordination needs
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**app/auth/BiometricPrompt.kt:89** - QUESTION: Compatibility with pending device credentials PR?
|
||||||
|
PR #1234 is refactoring device credentials. Should this:
|
||||||
|
- Merge first and adapt later
|
||||||
|
- Wait for #1234 to land
|
||||||
|
- Coordinate with that author
|
||||||
|
|
||||||
|
Timing unclear.
|
||||||
|
```
|
||||||
|
|
||||||
|
### Testing Strategy
|
||||||
|
- Uncertainty about test scope or approach
|
||||||
|
- Questions about mocking external dependencies
|
||||||
|
- Edge cases that need product input
|
||||||
|
- Performance testing requirements
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**data/vault/EncryptionTest.kt:45** - QUESTION: Should we test against real Keystore?
|
||||||
|
Currently using mocked Keystore. Real Keystore testing would:
|
||||||
|
+ Catch hardware-specific issues
|
||||||
|
- Slow down CI significantly
|
||||||
|
- Require API 23+ emulators
|
||||||
|
|
||||||
|
What's the priority?
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Optional (Acknowledge But Don't Require)
|
||||||
|
|
||||||
|
Note good practices to reinforce positive patterns. Keep these **brief** - list only, no elaboration.
|
||||||
|
|
||||||
|
### Good Practices
|
||||||
|
|
||||||
|
**Format**: Simple bullet list, no explanation
|
||||||
|
|
||||||
|
```markdown
|
||||||
|
## Good Practices
|
||||||
|
- Proper Hilt DI usage throughout
|
||||||
|
- Comprehensive unit test coverage
|
||||||
|
- Clear separation of concerns
|
||||||
|
- Well-documented public APIs
|
||||||
|
```
|
||||||
|
|
||||||
|
**Don't do this** (too verbose):
|
||||||
|
```markdown
|
||||||
|
## Good Practices
|
||||||
|
- Proper Hilt DI usage throughout: Great job using @Inject constructor and injecting interfaces! This follows our established patterns perfectly and makes the code very testable. Really excellent work here! 👍
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Classification Guidelines
|
||||||
|
|
||||||
|
### When Something is Between Categories
|
||||||
|
|
||||||
|
**If unsure between Critical and Important**:
|
||||||
|
- Ask: "Could this cause production incidents, data loss, or security breaches?"
|
||||||
|
- If yes → Critical
|
||||||
|
- If no → Important
|
||||||
|
|
||||||
|
**If unsure between Important and Debt**:
|
||||||
|
- Ask: "Is this a bug/defect or just duplication/inconsistency?"
|
||||||
|
- If bug/defect → Important
|
||||||
|
- If duplication/inconsistency → Debt
|
||||||
|
|
||||||
|
**If unsure between Important and Suggested**:
|
||||||
|
- Ask: "Would I block merge over this?"
|
||||||
|
- If yes → Important
|
||||||
|
- If no → Suggested
|
||||||
|
|
||||||
|
**If unsure between Debt and Suggested**:
|
||||||
|
- Ask: "Will this require rework within 6 months?"
|
||||||
|
- If yes → Debt
|
||||||
|
- If no → Suggested
|
||||||
|
|
||||||
|
**If unsure between Suggested and Question**:
|
||||||
|
- Ask: "Am I requesting a change or asking for clarification?"
|
||||||
|
- If requesting change → Suggested
|
||||||
|
- If seeking clarification → Question
|
||||||
|
|
||||||
|
**If unsure between Suggested and Optional**:
|
||||||
|
- Ask: "Is this actionable feedback or just acknowledgment?"
|
||||||
|
- If actionable → Suggested
|
||||||
|
- If acknowledgment → Optional
|
||||||
|
|
||||||
|
### Context Matters
|
||||||
|
|
||||||
|
**Same issue, different contexts**:
|
||||||
|
|
||||||
|
```
|
||||||
|
// Critical for production code
|
||||||
|
Missing null safety check in auth flow → CRITICAL
|
||||||
|
|
||||||
|
// Suggested for internal test utility
|
||||||
|
Missing null safety check in test helper → SUGGESTED
|
||||||
|
```
|
||||||
|
|
||||||
|
**Same pattern, different risk levels**:
|
||||||
|
|
||||||
|
```
|
||||||
|
// Critical for new feature
|
||||||
|
Missing tests for new auth method → CRITICAL
|
||||||
|
|
||||||
|
// Important for bug fix
|
||||||
|
Missing regression test → IMPORTANT
|
||||||
|
|
||||||
|
// Suggested for refactoring
|
||||||
|
Missing tests for refactored helper → SUGGESTED
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Examples by Change Type
|
||||||
|
|
||||||
|
### Dependency Update
|
||||||
|
- **Critical**: Known CVEs in old version not addressed
|
||||||
|
- **Important**: Breaking changes that need migration
|
||||||
|
- **Suggested**: Beta/alpha version stability concerns
|
||||||
|
|
||||||
|
### Bug Fix
|
||||||
|
- **Critical**: Fix doesn't address root cause
|
||||||
|
- **Important**: Missing regression test
|
||||||
|
- **Suggested**: Similar bugs in related code
|
||||||
|
|
||||||
|
### Feature Addition
|
||||||
|
- **Critical**: Security vulnerabilities, architecture violations
|
||||||
|
- **Important**: Missing tests for critical paths
|
||||||
|
- **Suggested**: Additional test coverage, minor refactoring
|
||||||
|
|
||||||
|
### UI Refinement
|
||||||
|
- **Critical**: Missing accessibility for key actions
|
||||||
|
- **Important**: Not using theme (hardcoded colors)
|
||||||
|
- **Suggested**: Minor spacing/alignment improvements
|
||||||
|
|
||||||
|
### Refactoring
|
||||||
|
- **Critical**: Changes behavior (should be behavior-preserving)
|
||||||
|
- **Important**: Incomplete migration (mix of old/new patterns)
|
||||||
|
- **Suggested**: Additional instances that could be refactored
|
||||||
|
|
||||||
|
### Infrastructure
|
||||||
|
- **Critical**: Hardcoded secrets, no rollback plan
|
||||||
|
- **Important**: Performance regression in build times
|
||||||
|
- **Suggested**: Further optimization opportunities
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Special Cases
|
||||||
|
|
||||||
|
### Technical Debt
|
||||||
|
- Acknowledge existing tech debt but don't require fixing in unrelated PR
|
||||||
|
- Exception: If change makes tech debt worse, it's Important to address
|
||||||
|
|
||||||
|
### Scope Creep
|
||||||
|
- Don't request changes outside PR scope
|
||||||
|
- Can note as "Future consideration" but not required for this PR
|
||||||
|
|
||||||
|
### Linter-Catchable Issues
|
||||||
|
- Don't flag issues that automated tools handle
|
||||||
|
- Exception: If linter is misconfigured and missing real issues
|
||||||
|
|
||||||
|
### Personal Preferences
|
||||||
|
- Don't flag unless grounded in project standards or architectural principles
|
||||||
|
- Use "I-statements" if suggesting alternative approaches
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
**Critical**: Block merge, must fix (security, stability, architecture)
|
||||||
|
**Important**: Should fix before merge (testing, quality, performance)
|
||||||
|
**Debt**: Technical debt introduced, track for future cleanup
|
||||||
|
**Suggested**: Nice to have, consider effort vs benefit
|
||||||
|
**Question**: Seeking clarification on requirements or design
|
||||||
|
**Optional**: Acknowledge good practices, keep brief
|
||||||
175
.claude/skills/reviewing-changes/reference/review-psychology.md
Normal file
175
.claude/skills/reviewing-changes/reference/review-psychology.md
Normal file
@ -0,0 +1,175 @@
|
|||||||
|
# Review Psychology: Constructive Feedback Phrasing
|
||||||
|
|
||||||
|
Effective code review feedback is clear, actionable, and constructive. This guide provides phrasing patterns for inline comments.
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
**Guidelines:**
|
||||||
|
- [Core Directives](#core-directives)
|
||||||
|
- [Phrasing Templates](#phrasing-templates)
|
||||||
|
- [Critical Issues (Prescriptive)](#critical-issues-prescriptive)
|
||||||
|
- [Suggested Improvements (Exploratory)](#suggested-improvements-exploratory)
|
||||||
|
- [Questions (Collaborative)](#questions-collaborative)
|
||||||
|
- [Test Suggestions](#test-suggestions)
|
||||||
|
- [When to Be Prescriptive vs Ask Questions](#when-to-be-prescriptive-vs-ask-questions)
|
||||||
|
- [Special Cases](#special-cases)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Core Directives
|
||||||
|
|
||||||
|
- **Keep positive feedback minimal**: For clean PRs with no issues, use 2-3 line approval only. When acknowledging good practices in PRs with issues, use single bullet list with no elaboration. Never create elaborate sections praising correct implementations.
|
||||||
|
- Ask questions for design decisions, be prescriptive for clear violations
|
||||||
|
- Focus on code, not people ("This code..." not "You...")
|
||||||
|
- Use I-statements for subjective feedback ("Hard for me to understand...")
|
||||||
|
- Explain rationale with every recommendation
|
||||||
|
- Avoid: "just", "simply", "obviously", "easy"
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Phrasing Templates
|
||||||
|
|
||||||
|
### Critical Issues (Prescriptive)
|
||||||
|
|
||||||
|
**Pattern**: State problem + Provide solution + Explain why
|
||||||
|
|
||||||
|
```
|
||||||
|
**[file:line]** - CRITICAL: [Issue description]
|
||||||
|
|
||||||
|
[Specific fix with code example if applicable]
|
||||||
|
|
||||||
|
[Rationale explaining why this is critical]
|
||||||
|
|
||||||
|
Reference: [docs link if applicable]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**data/vault/VaultRepository.kt:145** - CRITICAL: PIN stored without encryption
|
||||||
|
|
||||||
|
PIN must be encrypted using Android Keystore, not stored in plaintext SharedPreferences.
|
||||||
|
Plaintext storage exposes the PIN to backup systems and rooted devices.
|
||||||
|
|
||||||
|
Reference: docs/ARCHITECTURE.md#security
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Suggested Improvements (Exploratory)
|
||||||
|
|
||||||
|
**Pattern**: Observe + Suggest + Explain benefit
|
||||||
|
|
||||||
|
```
|
||||||
|
**[file:line]** - Consider [alternative approach]
|
||||||
|
|
||||||
|
[Current observation]
|
||||||
|
Can we [specific suggestion]?
|
||||||
|
|
||||||
|
[Benefit or rationale]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**app/login/LoginScreen.kt:89** - Consider using existing BitwardenButton
|
||||||
|
|
||||||
|
This custom button implementation looks similar to `ui/components/BitwardenButton.kt:45`.
|
||||||
|
Can we use the existing component to maintain consistency across the app?
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Questions (Collaborative)
|
||||||
|
|
||||||
|
**Pattern**: Ask + Provide context (optional)
|
||||||
|
|
||||||
|
```
|
||||||
|
**[file:line]** - [Question about intent or approach]?
|
||||||
|
|
||||||
|
[Optional context or observation]
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**data/sync/SyncManager.kt:234** - How does this handle concurrent sync attempts?
|
||||||
|
|
||||||
|
It looks like multiple coroutines could call `startSync()` simultaneously.
|
||||||
|
Is there a mechanism to prevent race conditions, or is that handled elsewhere?
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### Test Suggestions
|
||||||
|
|
||||||
|
**Pattern**: Observe gap + Suggest specific test + Provide skeleton
|
||||||
|
|
||||||
|
```
|
||||||
|
**[file:line]** - Consider adding test for [scenario]
|
||||||
|
|
||||||
|
[Rationale]
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
@Test
|
||||||
|
fun `test description`() = runTest {
|
||||||
|
// Test skeleton
|
||||||
|
}
|
||||||
|
```
|
||||||
|
```
|
||||||
|
|
||||||
|
**Example**:
|
||||||
|
```
|
||||||
|
**data/auth/BiometricRepository.kt** - Consider adding test for cancellation scenario
|
||||||
|
|
||||||
|
This would prevent regression of the bug you just fixed:
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
@Test
|
||||||
|
fun `when biometric cancelled then returns cancelled state`() = runTest {
|
||||||
|
coEvery { biometricPrompt.authenticate() } returns null
|
||||||
|
|
||||||
|
val result = repository.authenticate()
|
||||||
|
|
||||||
|
assertEquals(AuthResult.Cancelled, result)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## When to Be Prescriptive vs Ask Questions
|
||||||
|
|
||||||
|
**Be Prescriptive** (Tell them what to do):
|
||||||
|
- Security issues
|
||||||
|
- Architecture pattern violations
|
||||||
|
- Null safety problems
|
||||||
|
- Compilation errors
|
||||||
|
- Documented project standards
|
||||||
|
|
||||||
|
**Ask Questions** (Seek explanation):
|
||||||
|
- Design decisions with multiple valid approaches
|
||||||
|
- Performance trade-offs without data
|
||||||
|
- Unclear intent or reasoning
|
||||||
|
- Scope decisions (this PR vs future work)
|
||||||
|
- Patterns not documented in project guidelines
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Special Cases
|
||||||
|
|
||||||
|
**Nitpicks** - For truly minor suggestions, use "Nit:" prefix:
|
||||||
|
```
|
||||||
|
**Nit**: Extra blank line at line 145
|
||||||
|
```
|
||||||
|
|
||||||
|
**Uncertainty** - If unsure, acknowledge it:
|
||||||
|
```
|
||||||
|
I'm not certain, but this might be called frequently.
|
||||||
|
Has this been profiled?
|
||||||
|
```
|
||||||
|
|
||||||
|
**Positive Feedback** - Brief list only, no elaboration:
|
||||||
|
```
|
||||||
|
## Good Practices
|
||||||
|
- Proper Hilt DI usage throughout
|
||||||
|
- Comprehensive unit test coverage
|
||||||
|
- Clear separation of concerns
|
||||||
|
```
|
||||||
@ -0,0 +1,90 @@
|
|||||||
|
# Security Patterns Quick Reference
|
||||||
|
|
||||||
|
Quick reference for Bitwarden Android security patterns during code reviews. For comprehensive details, read `docs/ARCHITECTURE.md#security`.
|
||||||
|
|
||||||
|
## Encryption and Key Storage
|
||||||
|
|
||||||
|
**✅ GOOD - Android Keystore**:
|
||||||
|
```kotlin
|
||||||
|
// Sensitive data encrypted with Keystore
|
||||||
|
class SecureStorage @Inject constructor(
|
||||||
|
private val keystoreManager: KeystoreManager
|
||||||
|
) {
|
||||||
|
suspend fun storePin(pin: String): Result<Unit> = runCatching {
|
||||||
|
val encrypted = keystoreManager.encrypt(pin.toByteArray())
|
||||||
|
securePreferences.putBytes(KEY_PIN, encrypted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Or use EncryptedSharedPreferences
|
||||||
|
val encryptedPrefs = EncryptedSharedPreferences.create(
|
||||||
|
context,
|
||||||
|
"secure_prefs",
|
||||||
|
masterKey,
|
||||||
|
EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
|
||||||
|
EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**❌ BAD - Plaintext or weak encryption**:
|
||||||
|
```kotlin
|
||||||
|
// ❌ CRITICAL - Plaintext storage
|
||||||
|
sharedPreferences.edit {
|
||||||
|
putString("pin", userPin) // Never store sensitive data in plaintext
|
||||||
|
}
|
||||||
|
|
||||||
|
// ❌ CRITICAL - Weak encryption
|
||||||
|
val cipher = Cipher.getInstance("DES") // Use AES-256-GCM
|
||||||
|
|
||||||
|
// ❌ CRITICAL - Hardcoded keys
|
||||||
|
val key = "my_secret_key_123" // Use Android Keystore
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Rules**:
|
||||||
|
- Use Android Keystore for encryption keys
|
||||||
|
- Use EncryptedSharedPreferences for simple key-value storage
|
||||||
|
- Use AES-256-GCM for encryption
|
||||||
|
- Never store sensitive data in plaintext
|
||||||
|
- Never hardcode encryption keys
|
||||||
|
|
||||||
|
Reference: `docs/ARCHITECTURE.md#security`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Logging Sensitive Data
|
||||||
|
|
||||||
|
**✅ GOOD - No sensitive data**:
|
||||||
|
```kotlin
|
||||||
|
Log.d(TAG, "Authentication attempt for user")
|
||||||
|
Log.d(TAG, "Vault sync completed with ${items.size} items")
|
||||||
|
```
|
||||||
|
|
||||||
|
**❌ BAD - Logs sensitive data**:
|
||||||
|
```kotlin
|
||||||
|
// ❌ CRITICAL
|
||||||
|
Log.d(TAG, "Password: $password")
|
||||||
|
Log.d(TAG, "Auth token: $token")
|
||||||
|
Log.d(TAG, "PIN: $pin")
|
||||||
|
Log.d(TAG, "Encryption key: ${key.encoded}")
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Rules**:
|
||||||
|
- Never log passwords, PINs, tokens, keys
|
||||||
|
- Never log encryption keys or sensitive data
|
||||||
|
- Be careful with error messages (don't include sensitive context)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick Checklist
|
||||||
|
|
||||||
|
### Security
|
||||||
|
- [ ] Sensitive data encrypted with Keystore?
|
||||||
|
- [ ] No plaintext passwords/keys?
|
||||||
|
- [ ] No sensitive data in logs?
|
||||||
|
- [ ] Using AES-256-GCM for encryption?
|
||||||
|
- [ ] No hardcoded encryption keys?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
For comprehensive security details, always refer to:
|
||||||
|
- `docs/ARCHITECTURE.md#security` - Complete security architecture and zero-knowledge principles
|
||||||
127
.claude/skills/reviewing-changes/reference/testing-patterns.md
Normal file
127
.claude/skills/reviewing-changes/reference/testing-patterns.md
Normal file
@ -0,0 +1,127 @@
|
|||||||
|
# Testing Patterns Quick Reference
|
||||||
|
|
||||||
|
Quick reference for Bitwarden Android testing patterns during code reviews. For comprehensive details, read `docs/ARCHITECTURE.md` and `docs/STYLE_AND_BEST_PRACTICES.md`.
|
||||||
|
|
||||||
|
## ViewModel Tests
|
||||||
|
|
||||||
|
**✅ GOOD - Tests behavior**:
|
||||||
|
```kotlin
|
||||||
|
@Test
|
||||||
|
fun `when login succeeds then state updates to success`() = runTest {
|
||||||
|
// Arrange
|
||||||
|
val viewModel = LoginViewModel(mockRepository)
|
||||||
|
coEvery { mockRepository.login(any(), any()) } returns Result.success(User())
|
||||||
|
|
||||||
|
// Act
|
||||||
|
viewModel.onLoginClicked("user@example.com", "password")
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
viewModel.state.test {
|
||||||
|
assertEquals(LoginState.Loading, awaitItem())
|
||||||
|
assertEquals(LoginState.Success, awaitItem())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**❌ BAD - Tests implementation**:
|
||||||
|
```kotlin
|
||||||
|
@Test
|
||||||
|
fun `repository is called with correct parameters`() {
|
||||||
|
// ❌ This tests implementation details, not behavior
|
||||||
|
viewModel.onLoginClicked("user", "pass")
|
||||||
|
coVerify { mockRepository.login("user", "pass") }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Rules**:
|
||||||
|
- Test behavior, not implementation
|
||||||
|
- Use `runTest` for coroutine tests
|
||||||
|
- Use Turbine for Flow testing
|
||||||
|
- Use MockK for mocking
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Repository Tests
|
||||||
|
|
||||||
|
**✅ GOOD - Tests data transformations**:
|
||||||
|
```kotlin
|
||||||
|
@Test
|
||||||
|
fun `fetchItems maps API response to domain model`() = runTest {
|
||||||
|
// Arrange
|
||||||
|
val apiResponse = listOf(ApiItem(id = "1", name = "Test"))
|
||||||
|
coEvery { apiService.getItems() } returns apiResponse
|
||||||
|
|
||||||
|
// Act
|
||||||
|
val result = repository.fetchItems()
|
||||||
|
|
||||||
|
// Assert
|
||||||
|
assertTrue(result.isSuccess)
|
||||||
|
assertEquals(
|
||||||
|
listOf(DomainItem(id = "1", name = "Test")),
|
||||||
|
result.getOrThrow()
|
||||||
|
)
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Rules**:
|
||||||
|
- Test data transformations
|
||||||
|
- Test error handling (network failures, API errors)
|
||||||
|
- Test caching behavior if applicable
|
||||||
|
- Mock API services and databases
|
||||||
|
|
||||||
|
Reference: Project uses JUnit 5, MockK, Turbine, kotlinx-coroutines-test
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Null Safety
|
||||||
|
|
||||||
|
**✅ GOOD - Safe handling**:
|
||||||
|
```kotlin
|
||||||
|
// Safe call with elvis operator
|
||||||
|
val result = apiService.getData() ?: return State.Error("No data")
|
||||||
|
|
||||||
|
// Let with safe call
|
||||||
|
intent?.getStringExtra("key")?.let { value ->
|
||||||
|
processValue(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Require with message
|
||||||
|
val data = requireNotNull(response.data) { "Response data must not be null" }
|
||||||
|
```
|
||||||
|
|
||||||
|
**❌ BAD - Unsafe assertions**:
|
||||||
|
```kotlin
|
||||||
|
// ❌ Unsafe - can crash
|
||||||
|
val result = apiService.getData()!!
|
||||||
|
|
||||||
|
// ❌ Platform type unchecked
|
||||||
|
val intent: Intent = getIntent() // Could be null from Java
|
||||||
|
val value = intent.getStringExtra("key") // Potential NPE
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Rules**:
|
||||||
|
- Avoid `!!` unless safety is guaranteed (rare)
|
||||||
|
- Handle platform types with explicit nullability
|
||||||
|
- Use safe calls (`?.`), elvis operator (`?:`), or explicit checks
|
||||||
|
- Use `requireNotNull` with descriptive message if crash is acceptable
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick Checklist
|
||||||
|
|
||||||
|
### Testing
|
||||||
|
- [ ] ViewModels have unit tests?
|
||||||
|
- [ ] Tests verify behavior, not implementation?
|
||||||
|
- [ ] Edge cases covered?
|
||||||
|
- [ ] Error scenarios tested?
|
||||||
|
|
||||||
|
### Code Quality
|
||||||
|
- [ ] Null safety handled properly (no `!!` without guarantee)?
|
||||||
|
- [ ] Public APIs have KDoc?
|
||||||
|
- [ ] Following naming conventions?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
For comprehensive details, always refer to:
|
||||||
|
- `docs/ARCHITECTURE.md` - Full architecture patterns
|
||||||
|
- `docs/STYLE_AND_BEST_PRACTICES.md` - Complete style guide
|
||||||
85
.claude/skills/reviewing-changes/reference/ui-patterns.md
Normal file
85
.claude/skills/reviewing-changes/reference/ui-patterns.md
Normal file
@ -0,0 +1,85 @@
|
|||||||
|
# Compose UI Patterns Quick Reference
|
||||||
|
|
||||||
|
Quick reference for Bitwarden Android Compose UI patterns during code reviews. For comprehensive details, read `docs/ARCHITECTURE.md` and `docs/STYLE_AND_BEST_PRACTICES.md`.
|
||||||
|
|
||||||
|
## Component Reuse
|
||||||
|
|
||||||
|
**✅ GOOD - Uses existing components**:
|
||||||
|
```kotlin
|
||||||
|
BitwardenButton(
|
||||||
|
text = "Submit",
|
||||||
|
onClick = onSubmit
|
||||||
|
)
|
||||||
|
|
||||||
|
BitwardenTextField(
|
||||||
|
value = text,
|
||||||
|
onValueChange = onTextChange,
|
||||||
|
label = "Email"
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
**❌ BAD - Duplicates existing components**:
|
||||||
|
```kotlin
|
||||||
|
// ❌ Recreating BitwardenButton
|
||||||
|
Button(
|
||||||
|
onClick = onSubmit,
|
||||||
|
colors = ButtonDefaults.buttonColors(
|
||||||
|
containerColor = BitwardenTheme.colorScheme.primary
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
Text("Submit")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Rules**:
|
||||||
|
- Check `:ui` module for existing components before creating custom ones
|
||||||
|
- Use BitwardenButton, BitwardenTextField, etc. for consistency
|
||||||
|
- Place new reusable components in `:ui` module
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Theme Usage
|
||||||
|
|
||||||
|
**✅ GOOD - Uses theme**:
|
||||||
|
```kotlin
|
||||||
|
Text(
|
||||||
|
text = "Title",
|
||||||
|
style = BitwardenTheme.typography.titleLarge,
|
||||||
|
color = BitwardenTheme.colorScheme.primary
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(16.dp)) // Standard spacing
|
||||||
|
```
|
||||||
|
|
||||||
|
**❌ BAD - Hardcoded values**:
|
||||||
|
```kotlin
|
||||||
|
Text(
|
||||||
|
text = "Title",
|
||||||
|
style = TextStyle(fontSize = 24.sp, fontWeight = FontWeight.Bold), // Use theme
|
||||||
|
color = Color(0xFF0066FF) // Use theme color
|
||||||
|
)
|
||||||
|
|
||||||
|
Spacer(modifier = Modifier.height(17.dp)) // Non-standard spacing
|
||||||
|
```
|
||||||
|
|
||||||
|
**Key Rules**:
|
||||||
|
- Use `BitwardenTheme.colorScheme` for colors
|
||||||
|
- Use `BitwardenTheme.typography` for text styles
|
||||||
|
- Use standard spacing (4.dp, 8.dp, 16.dp, 24.dp)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Quick Checklist
|
||||||
|
|
||||||
|
### UI Patterns
|
||||||
|
- [ ] Using existing Bitwarden components from `:ui` module?
|
||||||
|
- [ ] Using BitwardenTheme for colors and typography?
|
||||||
|
- [ ] Using standard spacing values (4, 8, 16, 24 dp)?
|
||||||
|
- [ ] No hardcoded colors or text styles?
|
||||||
|
- [ ] UI is stateless (observes state, doesn't modify)?
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
For comprehensive details, always refer to:
|
||||||
|
- `docs/ARCHITECTURE.md` - Full architecture patterns
|
||||||
|
- `docs/STYLE_AND_BEST_PRACTICES.md` - Complete style guide
|
||||||
11
.github/CODEOWNERS
vendored
11
.github/CODEOWNERS
vendored
@ -10,6 +10,11 @@
|
|||||||
# Actions and workflow changes.
|
# Actions and workflow changes.
|
||||||
.github/ @bitwarden/dept-development-mobile
|
.github/ @bitwarden/dept-development-mobile
|
||||||
|
|
||||||
|
# Claude related files
|
||||||
|
.claude/ @bitwarden/team-ai-sme
|
||||||
|
.github/workflows/respond.yml @bitwarden/team-ai-sme
|
||||||
|
.github/workflows/review-code.yml @bitwarden/team-ai-sme
|
||||||
|
|
||||||
# Auth
|
# Auth
|
||||||
# app/src/main/java/com/x8bit/bitwarden/data/auth @bitwarden/team-auth-dev
|
# app/src/main/java/com/x8bit/bitwarden/data/auth @bitwarden/team-auth-dev
|
||||||
# app/src/main/java/com/x8bit/bitwarden/ui/auth @bitwarden/team-auth-dev
|
# app/src/main/java/com/x8bit/bitwarden/ui/auth @bitwarden/team-auth-dev
|
||||||
@ -48,3 +53,9 @@
|
|||||||
# app/src/main/java/com/x8bit/bitwarden/ui/vault @bitwarden/team-vault-dev
|
# app/src/main/java/com/x8bit/bitwarden/ui/vault @bitwarden/team-vault-dev
|
||||||
# app/src/test/java/com/x8bit/bitwarden/data/vault @bitwarden/team-vault-dev
|
# app/src/test/java/com/x8bit/bitwarden/data/vault @bitwarden/team-vault-dev
|
||||||
# app/src/test/java/com/x8bit/bitwarden/ui/vault @bitwarden/team-vault-dev
|
# app/src/test/java/com/x8bit/bitwarden/ui/vault @bitwarden/team-vault-dev
|
||||||
|
|
||||||
|
# Docker-related files
|
||||||
|
**/Dockerfile @bitwarden/team-appsec @bitwarden/dept-bre
|
||||||
|
**/*.dockerignore @bitwarden/team-appsec @bitwarden/dept-bre
|
||||||
|
**/entrypoint.sh @bitwarden/team-appsec @bitwarden/dept-bre
|
||||||
|
**/docker-compose.yml @bitwarden/team-appsec @bitwarden/dept-bre
|
||||||
|
|||||||
24
.github/actions/log-inputs/action.yml
vendored
Normal file
24
.github/actions/log-inputs/action.yml
vendored
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
name: 'Log Inputs to Job Summary'
|
||||||
|
description: 'Log workflow inputs to the GitHub Actions job summary'
|
||||||
|
|
||||||
|
inputs:
|
||||||
|
inputs:
|
||||||
|
description: 'Workflow inputs as JSON'
|
||||||
|
required: true
|
||||||
|
|
||||||
|
runs:
|
||||||
|
using: 'composite'
|
||||||
|
steps:
|
||||||
|
- name: Log inputs to job summary
|
||||||
|
shell: bash
|
||||||
|
env:
|
||||||
|
INPUTS: ${{ inputs.inputs }}
|
||||||
|
run: |
|
||||||
|
{
|
||||||
|
echo "<details><summary>Job Inputs</summary>"
|
||||||
|
echo ""
|
||||||
|
echo '```json'
|
||||||
|
echo "$INPUTS"
|
||||||
|
echo '```'
|
||||||
|
echo "</details>"
|
||||||
|
} >> "$GITHUB_STEP_SUMMARY"
|
||||||
48
.github/actions/setup-android-build/action.yml
vendored
Normal file
48
.github/actions/setup-android-build/action.yml
vendored
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
name: 'Setup Android Build'
|
||||||
|
description: 'Setup Android build environment with Gradle, Ruby, and Fastlane'
|
||||||
|
inputs:
|
||||||
|
java-version:
|
||||||
|
description: 'Java version to use'
|
||||||
|
required: false
|
||||||
|
default: '21'
|
||||||
|
runs:
|
||||||
|
using: 'composite'
|
||||||
|
steps:
|
||||||
|
- name: Validate Gradle wrapper
|
||||||
|
uses: gradle/actions/wrapper-validation@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||||
|
|
||||||
|
- name: Cache Gradle files
|
||||||
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.gradle/caches
|
||||||
|
~/.gradle/wrapper
|
||||||
|
key: ${{ runner.os }}-gradle-v2-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', '**/libs.versions.toml') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-gradle-v2-
|
||||||
|
|
||||||
|
- name: Cache build output
|
||||||
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
${{ github.workspace }}/build-cache
|
||||||
|
key: ${{ runner.os }}-build-cache-${{ github.sha }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-build-
|
||||||
|
|
||||||
|
- name: Configure Ruby
|
||||||
|
uses: ruby/setup-ruby@44511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0
|
||||||
|
with:
|
||||||
|
bundler-cache: true
|
||||||
|
|
||||||
|
- name: Configure JDK
|
||||||
|
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||||
|
with:
|
||||||
|
distribution: "temurin"
|
||||||
|
java-version: ${{ inputs.java-version }}
|
||||||
|
|
||||||
|
- name: Install Fastlane
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
bundle config path vendor/bundle
|
||||||
|
bundle install --jobs 4 --retry 3
|
||||||
50
.github/label-pr.json
vendored
Normal file
50
.github/label-pr.json
vendored
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"catch_all_label": "t:misc",
|
||||||
|
"title_patterns": {
|
||||||
|
"t:new-feature": ["feat", "feature"],
|
||||||
|
"t:enhancement": ["enhancement", "enh", "impr"],
|
||||||
|
"t:bug": ["fix", "bug", "bugfix"],
|
||||||
|
"t:tech-debt": ["refactor", "chore", "cleanup", "revert", "debt", "test", "perf"],
|
||||||
|
"t:docs": ["docs"],
|
||||||
|
"t:ci": ["ci", "build", "chore(ci)"],
|
||||||
|
"t:deps": ["deps"],
|
||||||
|
"t:breaking-change": ["breaking", "breaking-change"],
|
||||||
|
"t:misc": ["misc"]
|
||||||
|
},
|
||||||
|
"path_patterns": {
|
||||||
|
"app:shared": [
|
||||||
|
"annotation/",
|
||||||
|
"core/",
|
||||||
|
"data/",
|
||||||
|
"network/",
|
||||||
|
"ui/",
|
||||||
|
"authenticatorbridge/",
|
||||||
|
"gradle/"
|
||||||
|
],
|
||||||
|
"app:password-manager": [
|
||||||
|
"app/",
|
||||||
|
"cxf/",
|
||||||
|
"testharness/"
|
||||||
|
],
|
||||||
|
"app:authenticator": [
|
||||||
|
"authenticator/"
|
||||||
|
],
|
||||||
|
"t:ci": [
|
||||||
|
".github/",
|
||||||
|
"scripts/",
|
||||||
|
"fastlane/",
|
||||||
|
".gradle/",
|
||||||
|
".claude/",
|
||||||
|
"detekt-config.yml"
|
||||||
|
],
|
||||||
|
"t:docs": [
|
||||||
|
"docs/"
|
||||||
|
],
|
||||||
|
"t:deps": [
|
||||||
|
"gradle/"
|
||||||
|
],
|
||||||
|
"t:misc": [
|
||||||
|
"keystore/"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
4
.github/renovate.json
vendored
4
.github/renovate.json
vendored
@ -27,6 +27,10 @@
|
|||||||
],
|
],
|
||||||
"matchManagers": [
|
"matchManagers": [
|
||||||
"gradle"
|
"gradle"
|
||||||
|
],
|
||||||
|
"excludePackageNames": [
|
||||||
|
"com.github.bumptech.glide:compose",
|
||||||
|
"com.bitwarden:sdk-android"
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
238
.github/scripts/label-pr.py
vendored
Normal file
238
.github/scripts/label-pr.py
vendored
Normal file
@ -0,0 +1,238 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# Requires Python 3.9+
|
||||||
|
"""
|
||||||
|
Label pull requests based on changed file paths and PR title patterns (conventional commit format).
|
||||||
|
|
||||||
|
Usage:
|
||||||
|
python label-pr.py <pr-number> [-a|--add|-r|--replace] [-d|--dry-run] [-c|--config CONFIG]
|
||||||
|
|
||||||
|
Arguments:
|
||||||
|
pr-number: The pull request number
|
||||||
|
-a, --add: Add labels without removing existing ones (default)
|
||||||
|
-r, --replace: Replace all existing labels
|
||||||
|
-d, --dry-run: Run without actually applying labels
|
||||||
|
-c, --config: Path to JSON config file (default: .github/label-pr.json)
|
||||||
|
|
||||||
|
Examples:
|
||||||
|
python label-pr.py 1234
|
||||||
|
python label-pr.py 1234 -a
|
||||||
|
python label-pr.py 1234 --replace
|
||||||
|
python label-pr.py 1234 -r -d
|
||||||
|
python label-pr.py 1234 --config custom-config.json
|
||||||
|
"""
|
||||||
|
|
||||||
|
import argparse
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
DEFAULT_MODE = "add"
|
||||||
|
DEFAULT_CONFIG_PATH = ".github/label-pr.json"
|
||||||
|
|
||||||
|
def load_config_json(config_file: str) -> dict:
|
||||||
|
"""Load configuration from JSON file."""
|
||||||
|
if not os.path.exists(config_file):
|
||||||
|
print(f"❌ Config file not found: {config_file}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
try:
|
||||||
|
with open(config_file, 'r') as f:
|
||||||
|
config = json.load(f)
|
||||||
|
print(f"✅ Loaded config from: {config_file}")
|
||||||
|
|
||||||
|
valid_config = True
|
||||||
|
if not config.get("catch_all_label"):
|
||||||
|
print("❌ Missing 'catch_all_label' in config file")
|
||||||
|
valid_config = False
|
||||||
|
if not config.get("title_patterns"):
|
||||||
|
print("❌ Missing 'title_patterns' in config file")
|
||||||
|
valid_config = False
|
||||||
|
if not config.get("path_patterns"):
|
||||||
|
print("❌ Missing 'path_patterns' in config file")
|
||||||
|
valid_config = False
|
||||||
|
|
||||||
|
if not valid_config:
|
||||||
|
print("::error::Invalid label-pr.json config file, exiting...")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
return config
|
||||||
|
except json.JSONDecodeError as e:
|
||||||
|
print(f"❌ JSON deserialization error in label-pr.json config: {e}")
|
||||||
|
sys.exit(1)
|
||||||
|
except Exception as e:
|
||||||
|
print(f"❌ Unexpected error loading label-pr.json config: {e}")
|
||||||
|
sys.exit(1)
|
||||||
|
|
||||||
|
def gh_get_changed_files(pr_number: str) -> list[str]:
|
||||||
|
"""Get list of changed files in a pull request."""
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
["gh", "pr", "diff", pr_number, "--name-only"],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
check=True
|
||||||
|
)
|
||||||
|
changed_files = result.stdout.strip().split("\n")
|
||||||
|
return list(filter(None, changed_files))
|
||||||
|
except subprocess.CalledProcessError as e:
|
||||||
|
print(f"::error::Error getting changed files: {e}")
|
||||||
|
return []
|
||||||
|
|
||||||
|
def gh_get_pr_title(pr_number: str) -> str:
|
||||||
|
"""Get the title of a pull request."""
|
||||||
|
try:
|
||||||
|
result = subprocess.run(
|
||||||
|
["gh", "pr", "view", pr_number, "--json", "title", "--jq", ".title"],
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
check=True
|
||||||
|
)
|
||||||
|
return result.stdout.strip()
|
||||||
|
except subprocess.CalledProcessError as e:
|
||||||
|
print(f"::error::Error getting PR title: {e}")
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def gh_add_labels(pr_number: str, labels: list[str]) -> None:
|
||||||
|
"""Add labels to a pull request (doesn't remove existing labels)."""
|
||||||
|
gh_labels = ','.join(labels)
|
||||||
|
subprocess.run(
|
||||||
|
["gh", "pr", "edit", pr_number, "--add-label", gh_labels],
|
||||||
|
check=True
|
||||||
|
)
|
||||||
|
|
||||||
|
def gh_replace_labels(pr_number: str, labels: list[str]) -> None:
|
||||||
|
"""Replace all labels on a pull request with the specified labels."""
|
||||||
|
payload = json.dumps({"labels": labels})
|
||||||
|
subprocess.run(
|
||||||
|
["gh", "api", "repos/{owner}/{repo}/issues/" + pr_number, "-X", "PATCH", "--silent", "--input", "-"],
|
||||||
|
input=payload,
|
||||||
|
text=True,
|
||||||
|
check=True
|
||||||
|
)
|
||||||
|
|
||||||
|
def label_filepaths(changed_files: list[str], path_patterns: dict) -> list[str]:
|
||||||
|
"""Check changed files against path patterns and return labels to apply."""
|
||||||
|
if not changed_files:
|
||||||
|
return []
|
||||||
|
|
||||||
|
labels_to_apply = set() # Use set to avoid duplicates
|
||||||
|
|
||||||
|
for label, patterns in path_patterns.items():
|
||||||
|
for file in changed_files:
|
||||||
|
if any(file.startswith(pattern) for pattern in patterns):
|
||||||
|
print(f"👀 File '{file}' matches pattern for label '{label}'")
|
||||||
|
labels_to_apply.add(label)
|
||||||
|
break
|
||||||
|
|
||||||
|
if "app:shared" in labels_to_apply:
|
||||||
|
labels_to_apply.add("app:password-manager")
|
||||||
|
labels_to_apply.add("app:authenticator")
|
||||||
|
labels_to_apply.remove("app:shared")
|
||||||
|
|
||||||
|
if not labels_to_apply:
|
||||||
|
print("::warning::No matching file paths found, no labels applied.")
|
||||||
|
|
||||||
|
return list(labels_to_apply)
|
||||||
|
|
||||||
|
def label_title(pr_title: str, title_patterns: dict) -> list[str]:
|
||||||
|
"""Check PR title against patterns and return labels to apply."""
|
||||||
|
if not pr_title:
|
||||||
|
return []
|
||||||
|
|
||||||
|
labels_to_apply = set()
|
||||||
|
title_lower = pr_title.lower()
|
||||||
|
for label, patterns in title_patterns.items():
|
||||||
|
for pattern in patterns:
|
||||||
|
# Check for pattern with : or ( suffix (conventional commits format)
|
||||||
|
if f"{pattern}:" in title_lower or f"{pattern}(" in title_lower:
|
||||||
|
print(f"📝 Title matches pattern '{pattern}' for label '{label}'")
|
||||||
|
labels_to_apply.add(label)
|
||||||
|
break
|
||||||
|
|
||||||
|
if not labels_to_apply:
|
||||||
|
print("::warning::No matching title patterns found, no labels applied.")
|
||||||
|
|
||||||
|
return list(labels_to_apply)
|
||||||
|
|
||||||
|
def parse_args():
|
||||||
|
"""Parse command line arguments."""
|
||||||
|
parser = argparse.ArgumentParser(
|
||||||
|
description="Label pull requests based on changed file paths and PR title patterns."
|
||||||
|
)
|
||||||
|
parser.add_argument(
|
||||||
|
"pr_number",
|
||||||
|
help="The pull request number"
|
||||||
|
)
|
||||||
|
|
||||||
|
mode_group = parser.add_mutually_exclusive_group()
|
||||||
|
mode_group.add_argument(
|
||||||
|
"-a", "--add",
|
||||||
|
action="store_true",
|
||||||
|
help="Add labels without removing existing ones (default)"
|
||||||
|
)
|
||||||
|
mode_group.add_argument(
|
||||||
|
"-r", "--replace",
|
||||||
|
action="store_true",
|
||||||
|
help="Replace all existing labels"
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"-d", "--dry-run",
|
||||||
|
action="store_true",
|
||||||
|
help="Run without actually applying labels"
|
||||||
|
)
|
||||||
|
|
||||||
|
parser.add_argument(
|
||||||
|
"-c", "--config",
|
||||||
|
default=DEFAULT_CONFIG_PATH,
|
||||||
|
help=f"Path to JSON config file (default: {DEFAULT_CONFIG_PATH})"
|
||||||
|
)
|
||||||
|
args, unknown = parser.parse_known_args() # required to handle --dry-run passed as an empty string ("") by the workflow
|
||||||
|
return args
|
||||||
|
|
||||||
|
def main():
|
||||||
|
args = parse_args()
|
||||||
|
config = load_config_json(args.config)
|
||||||
|
CATCH_ALL_LABEL = config["catch_all_label"]
|
||||||
|
LABEL_TITLE_PATTERNS = config["title_patterns"]
|
||||||
|
LABEL_PATH_PATTERNS = config["path_patterns"]
|
||||||
|
|
||||||
|
pr_number = args.pr_number
|
||||||
|
mode = "replace" if args.replace else "add"
|
||||||
|
|
||||||
|
if args.dry_run:
|
||||||
|
print("🔍 DRY RUN MODE - Labels will not be applied")
|
||||||
|
print(f"📌 Labeling mode: {mode}")
|
||||||
|
print(f"🔍 Checking PR #{pr_number}...")
|
||||||
|
|
||||||
|
pr_title = gh_get_pr_title(pr_number)
|
||||||
|
print(f"📋 PR Title: {pr_title}\n")
|
||||||
|
|
||||||
|
changed_files = gh_get_changed_files(pr_number)
|
||||||
|
print("👀 Changed files:\n" + "\n".join(changed_files) + "\n")
|
||||||
|
|
||||||
|
filepath_labels = label_filepaths(changed_files, LABEL_PATH_PATTERNS)
|
||||||
|
title_labels = label_title(pr_title, LABEL_TITLE_PATTERNS)
|
||||||
|
all_labels = set(filepath_labels + title_labels)
|
||||||
|
|
||||||
|
if not any(label.startswith("t:") for label in all_labels):
|
||||||
|
all_labels.add(CATCH_ALL_LABEL)
|
||||||
|
|
||||||
|
if all_labels:
|
||||||
|
labels_str = ', '.join(sorted(all_labels))
|
||||||
|
if mode == "add":
|
||||||
|
print(f"🏷️ Adding labels: {labels_str}")
|
||||||
|
if not args.dry_run:
|
||||||
|
gh_add_labels(pr_number, list(all_labels))
|
||||||
|
else:
|
||||||
|
print(f"🏷️ Replacing labels with: {labels_str}")
|
||||||
|
if not args.dry_run:
|
||||||
|
gh_replace_labels(pr_number, list(all_labels))
|
||||||
|
else:
|
||||||
|
print("ℹ️ No matching patterns found, no labels applied.")
|
||||||
|
|
||||||
|
print("✅ Done")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
173
.github/workflows/_version.yml
vendored
Normal file
173
.github/workflows/_version.yml
vendored
Normal file
@ -0,0 +1,173 @@
|
|||||||
|
name: Calculate Version Name and Number
|
||||||
|
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
app_codename:
|
||||||
|
description: "App Name - e.g. 'bwpm' or 'bwa'"
|
||||||
|
base_version_number:
|
||||||
|
description: "Base Version Number - Will be added to the calculated version number"
|
||||||
|
type: number
|
||||||
|
default: 0
|
||||||
|
version_name:
|
||||||
|
description: "Version Name Override - e.g. '2024.8.1'"
|
||||||
|
version_number:
|
||||||
|
description: "Version Number Override - e.g. '1021'"
|
||||||
|
patch_version:
|
||||||
|
description: "Patch Version Override - e.g. '999'"
|
||||||
|
distinct_id:
|
||||||
|
description: "Unique ID for this dispatch, used by dispatch-and-download.yml"
|
||||||
|
skip_checkout:
|
||||||
|
description: "Skip checking out the repository"
|
||||||
|
type: boolean
|
||||||
|
workflow_call:
|
||||||
|
inputs:
|
||||||
|
app_codename:
|
||||||
|
description: "App Name - e.g. 'bwpm' or 'bwa'"
|
||||||
|
type: string
|
||||||
|
base_version_number:
|
||||||
|
description: "Base Version Number - Will be added to the calculated version number"
|
||||||
|
type: number
|
||||||
|
default: 0
|
||||||
|
version_name:
|
||||||
|
description: "Version Name Override - e.g. '2024.8.1'"
|
||||||
|
type: string
|
||||||
|
version_number:
|
||||||
|
description: "Version Number Override - e.g. '1021'"
|
||||||
|
type: string
|
||||||
|
patch_version:
|
||||||
|
description: "Patch Version Override - e.g. '999'"
|
||||||
|
type: string
|
||||||
|
distinct_id:
|
||||||
|
description: "Unique ID for this dispatch, used by dispatch-and-download.yml"
|
||||||
|
type: string
|
||||||
|
skip_checkout:
|
||||||
|
description: "Skip checking out the repository"
|
||||||
|
type: boolean
|
||||||
|
outputs:
|
||||||
|
version_name:
|
||||||
|
description: "Version Name"
|
||||||
|
value: ${{ jobs.calculate-version.outputs.version_name }}
|
||||||
|
version_number:
|
||||||
|
description: "Version Number"
|
||||||
|
value: ${{ jobs.calculate-version.outputs.version_number }}
|
||||||
|
|
||||||
|
env:
|
||||||
|
APP_CODENAME: ${{ inputs.app_codename }}
|
||||||
|
BASE_VERSION_NUMBER: ${{ inputs.base_version_number || 0 }}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
calculate-version:
|
||||||
|
name: Calculate Version Name and Number
|
||||||
|
runs-on: ubuntu-22.04
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
outputs:
|
||||||
|
version_name: ${{ steps.calc-version-name.outputs.version_name }}
|
||||||
|
version_number: ${{ steps.calc-version-number.outputs.version_number }}
|
||||||
|
steps:
|
||||||
|
- name: Log inputs to job summary
|
||||||
|
uses: bitwarden/android/.github/actions/log-inputs@main
|
||||||
|
with:
|
||||||
|
inputs: "${{ toJson(inputs) }}"
|
||||||
|
|
||||||
|
- name: Echo distinct ID ${{ github.event.inputs.distinct_id }}
|
||||||
|
env:
|
||||||
|
_DISTINCT_ID: ${{ inputs.distinct_id }}
|
||||||
|
run: echo "${_DISTINCT_ID}"
|
||||||
|
|
||||||
|
- name: Check out repository
|
||||||
|
if: ${{ !inputs.skip_checkout || false }}
|
||||||
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
with:
|
||||||
|
fetch-depth: 0
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
|
- name: Calculate version name
|
||||||
|
id: calc-version-name
|
||||||
|
env:
|
||||||
|
_VERSION_NAME: ${{ inputs.version_name }}
|
||||||
|
_PATCH_VERSION: ${{ inputs.patch_version }}
|
||||||
|
run: |
|
||||||
|
output() {
|
||||||
|
local version_name=$1
|
||||||
|
echo "version_name=$version_name" >> "$GITHUB_OUTPUT"
|
||||||
|
}
|
||||||
|
|
||||||
|
# override version name if provided
|
||||||
|
if [[ ! -z "${_VERSION_NAME}" ]]; then
|
||||||
|
version_name=${_VERSION_NAME}
|
||||||
|
echo "::warning::Override applied: $version_name"
|
||||||
|
output "$version_name"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
current_year=$(date +%Y)
|
||||||
|
current_month=$(date +%-m)
|
||||||
|
|
||||||
|
latest_tag_version=$(git tag -l --sort=-creatordate | grep "$APP_CODENAME" | head -n 1)
|
||||||
|
if [[ -z "$latest_tag_version" ]]; then
|
||||||
|
version_name="${current_year}.${current_month}.${_PATCH_VERSION:-0}"
|
||||||
|
echo "::warning::No tags found, did you checkout? Calculating version from current date: $version_name"
|
||||||
|
output "$version_name"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Git tag was found, calculate version from latest tag
|
||||||
|
latest_version=${latest_tag_version:1} # remove 'v' from tag version
|
||||||
|
|
||||||
|
latest_major_version=$(echo "$latest_version" | cut -d "." -f 1)
|
||||||
|
latest_minor_version=$(echo "$latest_version" | cut -d "." -f 2)
|
||||||
|
patch_version=0
|
||||||
|
if [[ ! -z "${_PATCH_VERSION}" ]]; then
|
||||||
|
patch_version=${_PATCH_VERSION}
|
||||||
|
echo "::warning::Patch Version Override applied: $patch_version"
|
||||||
|
elif [[ "$current_year" == "$latest_major_version" && "$current_month" == "$latest_minor_version" ]]; then
|
||||||
|
latest_patch_version=$(echo "$latest_version" | cut -d "." -f 3)
|
||||||
|
patch_version=$(($latest_patch_version + 1))
|
||||||
|
fi
|
||||||
|
|
||||||
|
version_name="${current_year}.${current_month}.${patch_version}"
|
||||||
|
output "$version_name"
|
||||||
|
|
||||||
|
- name: Calculate version number
|
||||||
|
id: calc-version-number
|
||||||
|
env:
|
||||||
|
_VERSION_NUMBER: ${{ inputs.version_number }}
|
||||||
|
run: |
|
||||||
|
# override version number if provided
|
||||||
|
if [[ ! -z "${_VERSION_NUMBER}" ]]; then
|
||||||
|
version_number=${_VERSION_NUMBER}
|
||||||
|
echo "::warning::Override applied: $version_number"
|
||||||
|
echo "version_number=$version_number" >> "$GITHUB_OUTPUT"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
version_number=$(($GITHUB_RUN_NUMBER + ${BASE_VERSION_NUMBER}))
|
||||||
|
echo "version_number=$version_number" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Create version info JSON
|
||||||
|
env:
|
||||||
|
_VERSION_NUMBER: ${{ steps.calc-version-number.outputs.version_number }}
|
||||||
|
_VERSION_NAME: ${{ steps.calc-version-name.outputs.version_name }}
|
||||||
|
run: |
|
||||||
|
json=$(cat <<EOF
|
||||||
|
{
|
||||||
|
"version_number": "${_VERSION_NUMBER}",
|
||||||
|
"version_name": "${_VERSION_NAME}"
|
||||||
|
}
|
||||||
|
EOF
|
||||||
|
)
|
||||||
|
echo "$json" > version_info.json
|
||||||
|
|
||||||
|
echo "## version-info.json" >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
echo '```json' >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
echo "$json" >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
echo '```' >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|
||||||
|
- name: Upload version info artifact
|
||||||
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
|
with:
|
||||||
|
name: version-info
|
||||||
|
path: version_info.json
|
||||||
158
.github/workflows/build-authenticator.yml
vendored
158
.github/workflows/build-authenticator.yml
vendored
@ -4,6 +4,7 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
|
- release/**/*
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
version-name:
|
version-name:
|
||||||
@ -14,6 +15,9 @@ on:
|
|||||||
description: "Optional. Build number to use. Overrides default of GitHub run number."
|
description: "Optional. Build number to use. Overrides default of GitHub run number."
|
||||||
required: false
|
required: false
|
||||||
type: number
|
type: number
|
||||||
|
patch_version:
|
||||||
|
description: "Order 999 - Overrides Patch version"
|
||||||
|
type: boolean
|
||||||
distribute-to-firebase:
|
distribute-to-firebase:
|
||||||
description: "Optional. Distribute artifacts to Firebase."
|
description: "Optional. Distribute artifacts to Firebase."
|
||||||
required: false
|
required: false
|
||||||
@ -27,35 +31,43 @@ on:
|
|||||||
|
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
JAVA_VERSION: 17
|
JAVA_VERSION: 21
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
packages: read
|
packages: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
version:
|
||||||
|
name: Calculate Version Name and Number
|
||||||
|
uses: bitwarden/android/.github/workflows/_version.yml@main
|
||||||
|
with:
|
||||||
|
app_codename: "bwa"
|
||||||
|
base_version_number: 0
|
||||||
|
version_name: ${{ inputs.version-name }}
|
||||||
|
version_number: ${{ inputs.version-code }}
|
||||||
|
patch_version: ${{ inputs.patch_version && '999' || '' }}
|
||||||
|
|
||||||
build:
|
build:
|
||||||
name: Build Authenticator
|
name: Build Authenticator
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Log inputs to job summary
|
- name: Log inputs to job summary
|
||||||
run: |
|
uses: bitwarden/android/.github/actions/log-inputs@main
|
||||||
echo "<details><summary>Job Inputs</summary>" >> $GITHUB_STEP_SUMMARY
|
with:
|
||||||
echo "" >> $GITHUB_STEP_SUMMARY
|
inputs: "${{ toJson(inputs) }}"
|
||||||
echo '```json' >> $GITHUB_STEP_SUMMARY
|
|
||||||
echo '${{ toJson(inputs) }}' >> $GITHUB_STEP_SUMMARY
|
|
||||||
echo '```' >> $GITHUB_STEP_SUMMARY
|
|
||||||
echo "</details>" >> $GITHUB_STEP_SUMMARY
|
|
||||||
|
|
||||||
- name: Check out repo
|
- name: Check out repo
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
- name: Validate Gradle wrapper
|
- name: Validate Gradle wrapper
|
||||||
uses: gradle/actions/wrapper-validation@06832c7b30a0129d7fb559bcc6e43d26f6374244 # v4.3.1
|
uses: gradle/actions/wrapper-validation@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||||
|
|
||||||
- name: Cache Gradle files
|
- name: Cache Gradle files
|
||||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/.gradle/caches
|
~/.gradle/caches
|
||||||
@ -65,7 +77,7 @@ jobs:
|
|||||||
${{ runner.os }}-gradle-v2-
|
${{ runner.os }}-gradle-v2-
|
||||||
|
|
||||||
- name: Cache build output
|
- name: Cache build output
|
||||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
${{ github.workspace }}/build-cache
|
${{ github.workspace }}/build-cache
|
||||||
@ -74,19 +86,18 @@ jobs:
|
|||||||
${{ runner.os }}-build-
|
${{ runner.os }}-build-
|
||||||
|
|
||||||
- name: Configure JDK
|
- name: Configure JDK
|
||||||
uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
|
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||||
with:
|
with:
|
||||||
distribution: "temurin"
|
distribution: "temurin"
|
||||||
java-version: ${{ env.JAVA_VERSION }}
|
java-version: ${{ env.JAVA_VERSION }}
|
||||||
|
|
||||||
- name: Configure Ruby
|
- name: Configure Ruby
|
||||||
uses: ruby/setup-ruby@ca041f971d66735f3e5ff1e21cc13e2d51e7e535 # v1.233.0
|
uses: ruby/setup-ruby@44511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0
|
||||||
with:
|
with:
|
||||||
bundler-cache: true
|
bundler-cache: true
|
||||||
|
|
||||||
- name: Install Fastlane
|
- name: Install Fastlane
|
||||||
run: |
|
run: |
|
||||||
gem install bundler:2.2.27
|
|
||||||
bundle config path vendor/bundle
|
bundle config path vendor/bundle
|
||||||
bundle install --jobs 4 --retry 3
|
bundle install --jobs 4 --retry 3
|
||||||
|
|
||||||
@ -99,8 +110,11 @@ jobs:
|
|||||||
publish_playstore:
|
publish_playstore:
|
||||||
name: Publish Authenticator Play Store artifacts
|
name: Publish Authenticator Play Store artifacts
|
||||||
needs:
|
needs:
|
||||||
|
- version
|
||||||
- build
|
- build
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
@ -108,23 +122,33 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Check out repo
|
- name: Check out repo
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
- name: Configure Ruby
|
- name: Configure Ruby
|
||||||
uses: ruby/setup-ruby@ca041f971d66735f3e5ff1e21cc13e2d51e7e535 # v1.233.0
|
uses: ruby/setup-ruby@44511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0
|
||||||
with:
|
with:
|
||||||
bundler-cache: true
|
bundler-cache: true
|
||||||
|
|
||||||
- name: Install Fastlane
|
- name: Install Fastlane
|
||||||
run: |
|
run: |
|
||||||
gem install bundler:2.2.27
|
|
||||||
bundle config path vendor/bundle
|
bundle config path vendor/bundle
|
||||||
bundle install --jobs 4 --retry 3
|
bundle install --jobs 4 --retry 3
|
||||||
|
|
||||||
- name: Log in to Azure
|
- name: Log in to Azure
|
||||||
uses: Azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0
|
uses: bitwarden/gh-actions/azure-login@main
|
||||||
with:
|
with:
|
||||||
creds: ${{ secrets.AZURE_KV_CI_SERVICE_PRINCIPAL }}
|
subscription_id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
tenant_id: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
client_id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
|
|
||||||
|
- name: Get Azure Key Vault secrets
|
||||||
|
id: get-kv-secrets
|
||||||
|
uses: bitwarden/gh-actions/get-keyvault-secrets@main
|
||||||
|
with:
|
||||||
|
keyvault: gh-android
|
||||||
|
secrets: "BWA-AAB-KEYSTORE-STORE-PASSWORD,BWA-AAB-KEYSTORE-KEY-PASSWORD,BWA-APK-KEYSTORE-STORE-PASSWORD,BWA-APK-KEYSTORE-KEY-PASSWORD"
|
||||||
|
|
||||||
- name: Retrieve secrets
|
- name: Retrieve secrets
|
||||||
env:
|
env:
|
||||||
@ -134,27 +158,27 @@ jobs:
|
|||||||
mkdir -p ${{ github.workspace }}/secrets
|
mkdir -p ${{ github.workspace }}/secrets
|
||||||
mkdir -p ${{ github.workspace }}/keystores
|
mkdir -p ${{ github.workspace }}/keystores
|
||||||
|
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name authenticator_apk-keystore.jks --file ${{ github.workspace }}/keystores/authenticator_apk-keystore.jks --output none
|
--name authenticator_apk-keystore.jks --file ${{ github.workspace }}/keystores/authenticator_apk-keystore.jks --output none
|
||||||
|
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name authenticator_aab-keystore.jks --file ${{ github.workspace }}/keystores/authenticator_aab-keystore.jks --output none
|
--name authenticator_aab-keystore.jks --file ${{ github.workspace }}/keystores/authenticator_aab-keystore.jks --output none
|
||||||
|
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name com.bitwarden.authenticator-google-services.json --file ${{ github.workspace }}/authenticator/src/google-services.json --output none
|
--name com.bitwarden.authenticator-google-services.json --file ${{ github.workspace }}/authenticator/src/google-services.json --output none
|
||||||
|
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name com.bitwarden.authenticator.dev-google-services.json --file ${{ github.workspace }}/authenticator/src/debug/google-services.json --output none
|
--name com.bitwarden.authenticator.dev-google-services.json --file ${{ github.workspace }}/authenticator/src/debug/google-services.json --output none
|
||||||
|
|
||||||
- name: Download Firebase credentials
|
- name: Download Firebase credentials
|
||||||
if : ${{ inputs.distribute-to-firebase || github.event_name == 'push' }}
|
if: ${{ inputs.distribute-to-firebase || github.event_name == 'push' }}
|
||||||
env:
|
env:
|
||||||
ACCOUNT_NAME: bitwardenci
|
ACCOUNT_NAME: bitwardenci
|
||||||
CONTAINER_NAME: mobile
|
CONTAINER_NAME: mobile
|
||||||
run: |
|
run: |
|
||||||
mkdir -p ${{ github.workspace }}/secrets
|
mkdir -p ${{ github.workspace }}/secrets
|
||||||
|
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name authenticator_play_firebase-creds.json --file ${{ github.workspace }}/secrets/authenticator_play_firebase-creds.json --output none
|
--name authenticator_play_firebase-creds.json --file ${{ github.workspace }}/secrets/authenticator_play_firebase-creds.json --output none
|
||||||
|
|
||||||
- name: Download Play Store credentials
|
- name: Download Play Store credentials
|
||||||
@ -165,20 +189,23 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
mkdir -p ${{ github.workspace }}/secrets
|
mkdir -p ${{ github.workspace }}/secrets
|
||||||
|
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name authenticator_play_store-creds.json --file ${{ github.workspace }}/secrets/authenticator_play_store-creds.json --output none
|
--name authenticator_play_store-creds.json --file ${{ github.workspace }}/secrets/authenticator_play_store-creds.json --output none
|
||||||
|
|
||||||
|
- name: AZ Logout
|
||||||
|
uses: bitwarden/gh-actions/azure-logout@main
|
||||||
|
|
||||||
- name: Verify Play Store credentials
|
- name: Verify Play Store credentials
|
||||||
if: ${{ inputs.publish-to-play-store }}
|
if: ${{ inputs.publish-to-play-store }}
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane run validate_play_store_json_key \
|
bundle exec fastlane run validate_play_store_json_key \
|
||||||
json_key:${{ github.workspace }}/secrets/authenticator_play_store-creds.json }}
|
json_key:"${{ github.workspace }}/secrets/authenticator_play_store-creds.json"
|
||||||
|
|
||||||
- name: Validate Gradle wrapper
|
- name: Validate Gradle wrapper
|
||||||
uses: gradle/actions/wrapper-validation@06832c7b30a0129d7fb559bcc6e43d26f6374244 # v4.3.1
|
uses: gradle/actions/wrapper-validation@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||||
|
|
||||||
- name: Cache Gradle files
|
- name: Cache Gradle files
|
||||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/.gradle/caches
|
~/.gradle/caches
|
||||||
@ -188,7 +215,7 @@ jobs:
|
|||||||
${{ runner.os }}-gradle-v2-
|
${{ runner.os }}-gradle-v2-
|
||||||
|
|
||||||
- name: Cache build output
|
- name: Cache build output
|
||||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
${{ github.workspace }}/build-cache
|
${{ github.workspace }}/build-cache
|
||||||
@ -197,47 +224,66 @@ jobs:
|
|||||||
${{ runner.os }}-build-
|
${{ runner.os }}-build-
|
||||||
|
|
||||||
- name: Configure JDK
|
- name: Configure JDK
|
||||||
uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
|
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||||
with:
|
with:
|
||||||
distribution: "temurin"
|
distribution: "temurin"
|
||||||
java-version: ${{ env.JAVA_VERSION }}
|
java-version: ${{ env.JAVA_VERSION }}
|
||||||
|
|
||||||
- name: Increment version
|
- name: Update app CI Build info
|
||||||
run: |
|
run: |
|
||||||
DEFAULT_VERSION_CODE=$GITHUB_RUN_NUMBER
|
./scripts/update_app_ci_build_info.sh \
|
||||||
VERSION_CODE="${{ inputs.version-code || '$DEFAULT_VERSION_CODE' }}"
|
"$GITHUB_REPOSITORY" \
|
||||||
bundle exec fastlane setAuthenticatorBuildVersionInfo \
|
"$GITHUB_REF_NAME" \
|
||||||
versionCode:$VERSION_CODE \
|
"$GITHUB_SHA" \
|
||||||
versionName:${{ inputs.version-name || '' }}
|
"$GITHUB_RUN_ID" \
|
||||||
|
"$GITHUB_RUN_ATTEMPT"
|
||||||
|
|
||||||
regex='versionName = "([^"]+)"'
|
- name: Increment version
|
||||||
if [[ "$(cat authenticator/build.gradle.kts)" =~ $regex ]]; then
|
env:
|
||||||
|
DEFAULT_VERSION_CODE: ${{ github.run_number }}
|
||||||
|
INPUT_VERSION_CODE: "${{ needs.version.outputs.version_number }}"
|
||||||
|
INPUT_VERSION_NAME: ${{ needs.version.outputs.version_name }}
|
||||||
|
run: |
|
||||||
|
VERSION_CODE="${INPUT_VERSION_CODE:-$DEFAULT_VERSION_CODE}"
|
||||||
|
VERSION_NAME_INPUT="${INPUT_VERSION_NAME:-}"
|
||||||
|
bundle exec fastlane setBuildVersionInfo \
|
||||||
|
versionCode:"$VERSION_CODE" \
|
||||||
|
versionName:"$VERSION_NAME_INPUT"
|
||||||
|
|
||||||
|
regex='appVersionName = "([^"]+)"'
|
||||||
|
if [[ "$(cat gradle/libs.versions.toml)" =~ $regex ]]; then
|
||||||
VERSION_NAME="${BASH_REMATCH[1]}"
|
VERSION_NAME="${BASH_REMATCH[1]}"
|
||||||
fi
|
fi
|
||||||
echo "Version Name: ${VERSION_NAME}" >> $GITHUB_STEP_SUMMARY
|
echo "Version Name: ${VERSION_NAME}" >> "$GITHUB_STEP_SUMMARY"
|
||||||
echo "Version Number: $VERSION_CODE" >> $GITHUB_STEP_SUMMARY
|
echo "Version Number: $VERSION_CODE" >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|
||||||
- name: Generate release Play Store bundle
|
- name: Generate release Play Store bundle
|
||||||
if: ${{ matrix.variant == 'aab' }}
|
if: ${{ matrix.variant == 'aab' }}
|
||||||
|
env:
|
||||||
|
STORE_PASSWORD: ${{ steps.get-kv-secrets.outputs.BWA-AAB-KEYSTORE-STORE-PASSWORD }}
|
||||||
|
KEY_PASSWORD: ${{ steps.get-kv-secrets.outputs.BWA-AAB-KEYSTORE-KEY-PASSWORD }}
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane bundleAuthenticatorRelease \
|
bundle exec fastlane bundleAuthenticatorRelease \
|
||||||
storeFile:${{ github.workspace }}/keystores/authenticator_aab-keystore.jks \
|
storeFile:"${{ github.workspace }}/keystores/authenticator_aab-keystore.jks" \
|
||||||
storePassword:'${{ secrets.BWA_AAB_KEYSTORE_STORE_PASSWORD }}' \
|
storePassword:"$STORE_PASSWORD" \
|
||||||
keyAlias:authenticatorupload \
|
keyAlias:"authenticatorupload" \
|
||||||
keyPassword:'${{ secrets.BWA_AAB_KEYSTORE_KEY_PASSWORD }}'
|
keyPassword:"$KEY_PASSWORD"
|
||||||
|
|
||||||
- name: Generate release Play Store APK
|
- name: Generate release Play Store APK
|
||||||
if: ${{ matrix.variant == 'apk' }}
|
if: ${{ matrix.variant == 'apk' }}
|
||||||
|
env:
|
||||||
|
STORE_PASSWORD: ${{ steps.get-kv-secrets.outputs.BWA-APK-KEYSTORE-STORE-PASSWORD }}
|
||||||
|
KEY_PASSWORD: ${{ steps.get-kv-secrets.outputs.BWA-APK-KEYSTORE-KEY-PASSWORD }}
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane buildAuthenticatorRelease \
|
bundle exec fastlane buildAuthenticatorRelease \
|
||||||
storeFile:${{ github.workspace }}/keystores/authenticator_apk-keystore.jks \
|
storeFile:"${{ github.workspace }}/keystores/authenticator_apk-keystore.jks" \
|
||||||
storePassword:'${{ secrets.BWA_APK_KEYSTORE_STORE_PASSWORD }}' \
|
storePassword:"$STORE_PASSWORD" \
|
||||||
keyAlias:bitwardenauthenticator \
|
keyAlias:"bitwardenauthenticator" \
|
||||||
keyPassword:'${{ secrets.BWA_APK_KEYSTORE_KEY_PASSWORD }}'
|
keyPassword:"$KEY_PASSWORD"
|
||||||
|
|
||||||
- name: Upload release Play Store .aab artifact
|
- name: Upload release Play Store .aab artifact
|
||||||
if: ${{ matrix.variant == 'aab' }}
|
if: ${{ matrix.variant == 'aab' }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.bitwarden.authenticator.aab
|
name: com.bitwarden.authenticator.aab
|
||||||
path: authenticator/build/outputs/bundle/release/com.bitwarden.authenticator.aab
|
path: authenticator/build/outputs/bundle/release/com.bitwarden.authenticator.aab
|
||||||
@ -245,7 +291,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload release .apk artifact
|
- name: Upload release .apk artifact
|
||||||
if: ${{ matrix.variant == 'apk' }}
|
if: ${{ matrix.variant == 'apk' }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.bitwarden.authenticator.apk
|
name: com.bitwarden.authenticator.apk
|
||||||
path: authenticator/build/outputs/apk/release/com.bitwarden.authenticator.apk
|
path: authenticator/build/outputs/apk/release/com.bitwarden.authenticator.apk
|
||||||
@ -265,7 +311,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload .apk SHA file for release
|
- name: Upload .apk SHA file for release
|
||||||
if: ${{ matrix.variant == 'apk' }}
|
if: ${{ matrix.variant == 'apk' }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: authenticator-android-apk-sha256.txt
|
name: authenticator-android-apk-sha256.txt
|
||||||
path: ./authenticator-android-apk-sha256.txt
|
path: ./authenticator-android-apk-sha256.txt
|
||||||
@ -273,7 +319,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload .aab SHA file for release
|
- name: Upload .aab SHA file for release
|
||||||
if: ${{ matrix.variant == 'aab' }}
|
if: ${{ matrix.variant == 'aab' }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: authenticator-android-aab-sha256.txt
|
name: authenticator-android-aab-sha256.txt
|
||||||
path: ./authenticator-android-aab-sha256.txt
|
path: ./authenticator-android-aab-sha256.txt
|
||||||
@ -289,7 +335,7 @@ jobs:
|
|||||||
FIREBASE_CREDS_PATH: ${{ github.workspace }}/secrets/authenticator_play_firebase-creds.json
|
FIREBASE_CREDS_PATH: ${{ github.workspace }}/secrets/authenticator_play_firebase-creds.json
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane distributeAuthenticatorReleaseBundleToFirebase \
|
bundle exec fastlane distributeAuthenticatorReleaseBundleToFirebase \
|
||||||
serviceCredentialsFile:${{ env.FIREBASE_CREDS_PATH }}
|
serviceCredentialsFile:"$FIREBASE_CREDS_PATH"
|
||||||
|
|
||||||
# Only publish bundles to Play Store when `publish-to-play-store` is true while building
|
# Only publish bundles to Play Store when `publish-to-play-store` is true while building
|
||||||
# bundles
|
# bundles
|
||||||
@ -299,4 +345,4 @@ jobs:
|
|||||||
PLAY_STORE_CREDS_FILE: ${{ github.workspace }}/secrets/authenticator_play_store-creds.json
|
PLAY_STORE_CREDS_FILE: ${{ github.workspace }}/secrets/authenticator_play_store-creds.json
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane publishAuthenticatorReleaseToGooglePlayStore \
|
bundle exec fastlane publishAuthenticatorReleaseToGooglePlayStore \
|
||||||
serviceCredentialsFile:${{ env.PLAY_STORE_CREDS_FILE }} \
|
serviceCredentialsFile:"$PLAY_STORE_CREDS_FILE" \
|
||||||
|
|||||||
134
.github/workflows/build-testharness.yml
vendored
Normal file
134
.github/workflows/build-testharness.yml
vendored
Normal file
@ -0,0 +1,134 @@
|
|||||||
|
name: Build Test Harness
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
paths:
|
||||||
|
- testharness/**
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
version-name:
|
||||||
|
description: "Optional. Version string to use, in X.Y.Z format. Overrides default in the project."
|
||||||
|
required: false
|
||||||
|
type: string
|
||||||
|
version-code:
|
||||||
|
description: "Optional. Build number to use. Overrides default of GitHub run number."
|
||||||
|
required: false
|
||||||
|
type: number
|
||||||
|
patch_version:
|
||||||
|
description: "Order 999 - Overrides Patch version"
|
||||||
|
type: boolean
|
||||||
|
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
JAVA_VERSION: 21
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: read
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
version:
|
||||||
|
name: Calculate Version Name and Number
|
||||||
|
uses: bitwarden/android/.github/workflows/_version.yml@main
|
||||||
|
with:
|
||||||
|
app_codename: "bwpm"
|
||||||
|
base_version_number: 0
|
||||||
|
version_name: ${{ inputs.version-name }}
|
||||||
|
version_number: ${{ inputs.version-code }}
|
||||||
|
patch_version: ${{ inputs.patch_version && '999' || '' }}
|
||||||
|
|
||||||
|
build:
|
||||||
|
name: Build Test Harness
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
needs: version
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Log inputs to job summary
|
||||||
|
uses: bitwarden/android/.github/actions/log-inputs@main
|
||||||
|
with:
|
||||||
|
inputs: "${{ toJson(inputs) }}"
|
||||||
|
|
||||||
|
- name: Check out repo
|
||||||
|
uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
|
- name: Validate Gradle wrapper
|
||||||
|
uses: gradle/actions/wrapper-validation@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||||
|
|
||||||
|
- name: Cache Gradle files
|
||||||
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
~/.gradle/caches
|
||||||
|
~/.gradle/wrapper
|
||||||
|
key: ${{ runner.os }}-gradle-v2-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', '**/libs.versions.toml') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-gradle-v2-
|
||||||
|
|
||||||
|
- name: Cache build output
|
||||||
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
${{ github.workspace }}/build-cache
|
||||||
|
key: ${{ runner.os }}-build-cache-${{ github.sha }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-build-
|
||||||
|
|
||||||
|
- name: Configure JDK
|
||||||
|
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||||
|
with:
|
||||||
|
distribution: "temurin"
|
||||||
|
java-version: ${{ env.JAVA_VERSION }}
|
||||||
|
|
||||||
|
- name: Configure Ruby
|
||||||
|
uses: ruby/setup-ruby@44511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0
|
||||||
|
with:
|
||||||
|
bundler-cache: true
|
||||||
|
|
||||||
|
- name: Install Fastlane
|
||||||
|
run: |
|
||||||
|
gem install bundler:2.2.27
|
||||||
|
bundle config path vendor/bundle
|
||||||
|
bundle install --jobs 4 --retry 3
|
||||||
|
|
||||||
|
- name: Increment version
|
||||||
|
env:
|
||||||
|
DEFAULT_VERSION_CODE: ${{ github.run_number }}
|
||||||
|
INPUT_VERSION_CODE: "${{ needs.version.outputs.version_number }}"
|
||||||
|
INPUT_VERSION_NAME: ${{ needs.version.outputs.version_name }}
|
||||||
|
run: |
|
||||||
|
VERSION_CODE="${INPUT_VERSION_CODE:-$DEFAULT_VERSION_CODE}"
|
||||||
|
VERSION_NAME_INPUT="${INPUT_VERSION_NAME:-}"
|
||||||
|
bundle exec fastlane setBuildVersionInfo \
|
||||||
|
versionCode:"$VERSION_CODE" \
|
||||||
|
versionName:"$VERSION_NAME_INPUT"
|
||||||
|
|
||||||
|
regex='appVersionName = "(.+)"'
|
||||||
|
if [[ "$(cat gradle/libs.versions.toml)" =~ $regex ]]; then
|
||||||
|
VERSION_NAME="${BASH_REMATCH[1]}"
|
||||||
|
fi
|
||||||
|
echo "Version Name: ${VERSION_NAME}" >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
echo "Version Number: $VERSION_CODE" >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|
||||||
|
- name: Build Test Harness Debug APK
|
||||||
|
run: ./gradlew :testharness:assembleDebug
|
||||||
|
|
||||||
|
- name: Upload Test Harness APK
|
||||||
|
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||||
|
with:
|
||||||
|
name: com.bitwarden.testharness.dev-debug.apk
|
||||||
|
path: testharness/build/outputs/apk/debug/com.bitwarden.testharness.dev.apk
|
||||||
|
if-no-files-found: error
|
||||||
|
|
||||||
|
- name: Create checksum for Test Harness APK
|
||||||
|
run: |
|
||||||
|
sha256sum "testharness/build/outputs/apk/debug/com.bitwarden.testharness.dev.apk" \
|
||||||
|
> ./com.bitwarden.testharness.dev.apk-sha256.txt
|
||||||
|
|
||||||
|
- name: Upload Test Harness SHA file
|
||||||
|
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||||
|
with:
|
||||||
|
name: com.bitwarden.testharness.dev.apk-sha256.txt
|
||||||
|
path: ./com.bitwarden.testharness.dev.apk-sha256.txt
|
||||||
|
if-no-files-found: error
|
||||||
268
.github/workflows/build.yml
vendored
268
.github/workflows/build.yml
vendored
@ -4,6 +4,7 @@ on:
|
|||||||
push:
|
push:
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
|
- release/**/*
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
version-name:
|
version-name:
|
||||||
@ -14,20 +15,23 @@ on:
|
|||||||
description: "Optional. Build number to use. Overrides default of GitHub run number."
|
description: "Optional. Build number to use. Overrides default of GitHub run number."
|
||||||
required: false
|
required: false
|
||||||
type: number
|
type: number
|
||||||
|
patch_version:
|
||||||
|
description: "Order 999 - Overrides Patch version"
|
||||||
|
type: boolean
|
||||||
distribute-to-firebase:
|
distribute-to-firebase:
|
||||||
description: "Optional. Distribute artifacts to Firebase."
|
description: "Optional. Distribute artifacts to Firebase."
|
||||||
required: false
|
required: false
|
||||||
default: false
|
default: true
|
||||||
type: boolean
|
type: boolean
|
||||||
publish-to-play-store:
|
publish-to-play-store:
|
||||||
description: "Optional. Deploy bundle artifact to Google Play Store"
|
description: "Optional. Deploy bundle artifact to Google Play Store"
|
||||||
required: false
|
required: false
|
||||||
default: false
|
default: true
|
||||||
type: boolean
|
type: boolean
|
||||||
|
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
JAVA_VERSION: 17
|
JAVA_VERSION: 21
|
||||||
GITHUB_ACTION_RUN_URL: "https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
GITHUB_ACTION_RUN_URL: "https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
||||||
|
|
||||||
permissions:
|
permissions:
|
||||||
@ -35,28 +39,37 @@ permissions:
|
|||||||
packages: read
|
packages: read
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
|
version:
|
||||||
|
name: Calculate Version Name and Number
|
||||||
|
uses: bitwarden/android/.github/workflows/_version.yml@main
|
||||||
|
with:
|
||||||
|
app_codename: "bwpm"
|
||||||
|
# Start from 11000 to prevent collisions with mobile build version codes
|
||||||
|
base_version_number: 11000
|
||||||
|
version_name: ${{ inputs.version-name }}
|
||||||
|
version_number: ${{ inputs.version-code }}
|
||||||
|
patch_version: ${{ inputs.patch_version && '999' || '' }}
|
||||||
|
|
||||||
build:
|
build:
|
||||||
name: Build
|
name: Build
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Log inputs to job summary
|
- name: Log inputs to job summary
|
||||||
run: |
|
uses: bitwarden/android/.github/actions/log-inputs@main
|
||||||
echo "<details><summary>Job Inputs</summary>" >> $GITHUB_STEP_SUMMARY
|
with:
|
||||||
echo "" >> $GITHUB_STEP_SUMMARY
|
inputs: "${{ toJson(inputs) }}"
|
||||||
echo '```json' >> $GITHUB_STEP_SUMMARY
|
|
||||||
echo '${{ toJson(inputs) }}' >> $GITHUB_STEP_SUMMARY
|
|
||||||
echo '```' >> $GITHUB_STEP_SUMMARY
|
|
||||||
echo "</details>" >> $GITHUB_STEP_SUMMARY
|
|
||||||
|
|
||||||
- name: Check out repo
|
- name: Check out repo
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
- name: Validate Gradle wrapper
|
- name: Validate Gradle wrapper
|
||||||
uses: gradle/actions/wrapper-validation@06832c7b30a0129d7fb559bcc6e43d26f6374244 # v4.3.1
|
uses: gradle/actions/wrapper-validation@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||||
|
|
||||||
- name: Cache Gradle files
|
- name: Cache Gradle files
|
||||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/.gradle/caches
|
~/.gradle/caches
|
||||||
@ -66,7 +79,7 @@ jobs:
|
|||||||
${{ runner.os }}-gradle-v2-
|
${{ runner.os }}-gradle-v2-
|
||||||
|
|
||||||
- name: Cache build output
|
- name: Cache build output
|
||||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
${{ github.workspace }}/build-cache
|
${{ github.workspace }}/build-cache
|
||||||
@ -75,19 +88,18 @@ jobs:
|
|||||||
${{ runner.os }}-build-
|
${{ runner.os }}-build-
|
||||||
|
|
||||||
- name: Configure JDK
|
- name: Configure JDK
|
||||||
uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
|
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||||
with:
|
with:
|
||||||
distribution: "temurin"
|
distribution: "temurin"
|
||||||
java-version: ${{ env.JAVA_VERSION }}
|
java-version: ${{ env.JAVA_VERSION }}
|
||||||
|
|
||||||
- name: Configure Ruby
|
- name: Configure Ruby
|
||||||
uses: ruby/setup-ruby@ca041f971d66735f3e5ff1e21cc13e2d51e7e535 # v1.233.0
|
uses: ruby/setup-ruby@44511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0
|
||||||
with:
|
with:
|
||||||
bundler-cache: true
|
bundler-cache: true
|
||||||
|
|
||||||
- name: Install Fastlane
|
- name: Install Fastlane
|
||||||
run: |
|
run: |
|
||||||
gem install bundler:2.2.27
|
|
||||||
bundle config path vendor/bundle
|
bundle config path vendor/bundle
|
||||||
bundle install --jobs 4 --retry 3
|
bundle install --jobs 4 --retry 3
|
||||||
|
|
||||||
@ -98,7 +110,7 @@ jobs:
|
|||||||
run: bundle exec fastlane assembleDebugApks
|
run: bundle exec fastlane assembleDebugApks
|
||||||
|
|
||||||
- name: Upload test reports on failure
|
- name: Upload test reports on failure
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
if: failure()
|
if: failure()
|
||||||
with:
|
with:
|
||||||
name: test-reports
|
name: test-reports
|
||||||
@ -107,8 +119,11 @@ jobs:
|
|||||||
publish_playstore:
|
publish_playstore:
|
||||||
name: Publish Play Store artifacts
|
name: Publish Play Store artifacts
|
||||||
needs:
|
needs:
|
||||||
|
- version
|
||||||
- build
|
- build
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
@ -116,23 +131,33 @@ jobs:
|
|||||||
artifact: ["apk", "aab"]
|
artifact: ["apk", "aab"]
|
||||||
steps:
|
steps:
|
||||||
- name: Check out repo
|
- name: Check out repo
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
- name: Configure Ruby
|
- name: Configure Ruby
|
||||||
uses: ruby/setup-ruby@ca041f971d66735f3e5ff1e21cc13e2d51e7e535 # v1.233.0
|
uses: ruby/setup-ruby@44511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0
|
||||||
with:
|
with:
|
||||||
bundler-cache: true
|
bundler-cache: true
|
||||||
|
|
||||||
- name: Install Fastlane
|
- name: Install Fastlane
|
||||||
run: |
|
run: |
|
||||||
gem install bundler:2.2.27
|
|
||||||
bundle config path vendor/bundle
|
bundle config path vendor/bundle
|
||||||
bundle install --jobs 4 --retry 3
|
bundle install --jobs 4 --retry 3
|
||||||
|
|
||||||
- name: Log in to Azure
|
- name: Log in to Azure
|
||||||
uses: Azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0
|
uses: bitwarden/gh-actions/azure-login@main
|
||||||
with:
|
with:
|
||||||
creds: ${{ secrets.AZURE_KV_CI_SERVICE_PRINCIPAL }}
|
subscription_id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
tenant_id: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
client_id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
|
|
||||||
|
- name: Get Azure Key Vault secrets
|
||||||
|
id: get-kv-secrets
|
||||||
|
uses: bitwarden/gh-actions/get-keyvault-secrets@main
|
||||||
|
with:
|
||||||
|
keyvault: gh-android
|
||||||
|
secrets: "UPLOAD-KEYSTORE-PASSWORD,UPLOAD-BETA-KEYSTORE-PASSWORD,UPLOAD-BETA-KEY-PASSWORD,PLAY-KEYSTORE-PASSWORD,PLAY-BETA-KEYSTORE-PASSWORD,PLAY-BETA-KEY-PASSWORD"
|
||||||
|
|
||||||
- name: Retrieve secrets
|
- name: Retrieve secrets
|
||||||
env:
|
env:
|
||||||
@ -143,19 +168,19 @@ jobs:
|
|||||||
mkdir -p ${{ github.workspace }}/app/src/standardBeta
|
mkdir -p ${{ github.workspace }}/app/src/standardBeta
|
||||||
mkdir -p ${{ github.workspace }}/app/src/standardRelease
|
mkdir -p ${{ github.workspace }}/app/src/standardRelease
|
||||||
|
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name app_play-keystore.jks --file ${{ github.workspace }}/keystores/app_play-keystore.jks --output none
|
--name app_play-keystore.jks --file ${{ github.workspace }}/keystores/app_play-keystore.jks --output none
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name app_upload-keystore.jks --file ${{ github.workspace }}/keystores/app_upload-keystore.jks --output none
|
--name app_upload-keystore.jks --file ${{ github.workspace }}/keystores/app_upload-keystore.jks --output none
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name play_creds.json --file ${{ github.workspace }}/secrets/play_creds.json --output none
|
--name play_creds.json --file ${{ github.workspace }}/secrets/play_creds.json --output none
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name app_beta_play-keystore.jks --file ${{ github.workspace }}/keystores/app_beta_play-keystore.jks --output none
|
--name app_beta_play-keystore.jks --file ${{ github.workspace }}/keystores/app_beta_play-keystore.jks --output none
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name app_beta_upload-keystore.jks --file ${{ github.workspace }}/keystores/app_beta_upload-keystore.jks --output none
|
--name app_beta_upload-keystore.jks --file ${{ github.workspace }}/keystores/app_beta_upload-keystore.jks --output none
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name google-services.json --file ${{ github.workspace }}/app/src/standardRelease/google-services.json --output none
|
--name google-services.json --file ${{ github.workspace }}/app/src/standardRelease/google-services.json --output none
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name google-services.json --file ${{ github.workspace }}/app/src/standardBeta/google-services.json --output none
|
--name google-services.json --file ${{ github.workspace }}/app/src/standardBeta/google-services.json --output none
|
||||||
|
|
||||||
- name: Download Firebase credentials
|
- name: Download Firebase credentials
|
||||||
@ -166,14 +191,17 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
mkdir -p ${{ github.workspace }}/secrets
|
mkdir -p ${{ github.workspace }}/secrets
|
||||||
|
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name app_play_prod_firebase-creds.json --file ${{ github.workspace }}/secrets/app_play_prod_firebase-creds.json --output none
|
--name app_play_prod_firebase-creds.json --file ${{ github.workspace }}/secrets/app_play_prod_firebase-creds.json --output none
|
||||||
|
|
||||||
|
- name: Log out from Azure
|
||||||
|
uses: bitwarden/gh-actions/azure-logout@main
|
||||||
|
|
||||||
- name: Validate Gradle wrapper
|
- name: Validate Gradle wrapper
|
||||||
uses: gradle/actions/wrapper-validation@06832c7b30a0129d7fb559bcc6e43d26f6374244 # v4.3.1
|
uses: gradle/actions/wrapper-validation@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||||
|
|
||||||
- name: Cache Gradle files
|
- name: Cache Gradle files
|
||||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/.gradle/caches
|
~/.gradle/caches
|
||||||
@ -183,7 +211,7 @@ jobs:
|
|||||||
${{ runner.os }}-gradle-v2-
|
${{ runner.os }}-gradle-v2-
|
||||||
|
|
||||||
- name: Cache build output
|
- name: Cache build output
|
||||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
${{ github.workspace }}/build-cache
|
${{ github.workspace }}/build-cache
|
||||||
@ -192,7 +220,7 @@ jobs:
|
|||||||
${{ runner.os }}-build-
|
${{ runner.os }}-build-
|
||||||
|
|
||||||
- name: Configure JDK
|
- name: Configure JDK
|
||||||
uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
|
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||||
with:
|
with:
|
||||||
distribution: "temurin"
|
distribution: "temurin"
|
||||||
java-version: ${{ env.JAVA_VERSION }}
|
java-version: ${{ env.JAVA_VERSION }}
|
||||||
@ -200,64 +228,67 @@ jobs:
|
|||||||
- name: Update app CI Build info
|
- name: Update app CI Build info
|
||||||
run: |
|
run: |
|
||||||
./scripts/update_app_ci_build_info.sh \
|
./scripts/update_app_ci_build_info.sh \
|
||||||
$GITHUB_REPOSITORY \
|
"$GITHUB_REPOSITORY" \
|
||||||
$GITHUB_REF_NAME \
|
"$GITHUB_REF_NAME" \
|
||||||
$GITHUB_SHA \
|
"$GITHUB_SHA" \
|
||||||
$GITHUB_RUN_ID \
|
"$GITHUB_RUN_ID" \
|
||||||
$GITHUB_RUN_ATTEMPT
|
"$GITHUB_RUN_ATTEMPT"
|
||||||
|
|
||||||
- name: Increment version
|
- name: Increment version
|
||||||
|
env:
|
||||||
|
VERSION_CODE: ${{ needs.version.outputs.version_number }}
|
||||||
|
VERSION_NAME: ${{ needs.version.outputs.version_name }}
|
||||||
run: |
|
run: |
|
||||||
DEFAULT_VERSION_CODE=$((11000+GITHUB_RUN_NUMBER))
|
VERSION_CODE="${VERSION_CODE:-$GITHUB_RUN_NUMBER}"
|
||||||
bundle exec fastlane setBuildVersionInfo \
|
bundle exec fastlane setBuildVersionInfo \
|
||||||
versionCode:${{ inputs.version-code || '$DEFAULT_VERSION_CODE' }} \
|
versionCode:$VERSION_CODE \
|
||||||
versionName:${{ inputs.version-name }}
|
versionName:$VERSION_NAME
|
||||||
|
|
||||||
- name: Generate release Play Store bundle
|
- name: Generate release Play Store bundle
|
||||||
if: ${{ matrix.variant == 'prod' && matrix.artifact == 'aab' }}
|
if: ${{ matrix.variant == 'prod' && matrix.artifact == 'aab' }}
|
||||||
env:
|
env:
|
||||||
UPLOAD_KEYSTORE_PASSWORD: ${{ secrets.UPLOAD_KEYSTORE_PASSWORD }}
|
UPLOAD_KEYSTORE_PASSWORD: ${{ steps.get-kv-secrets.outputs.UPLOAD-KEYSTORE-PASSWORD }}
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane bundlePlayStoreRelease \
|
bundle exec fastlane bundlePlayStoreRelease \
|
||||||
storeFile:app_upload-keystore.jks \
|
storeFile:app_upload-keystore.jks \
|
||||||
storePassword:${{ env.UPLOAD_KEYSTORE_PASSWORD }} \
|
storePassword:$UPLOAD_KEYSTORE_PASSWORD \
|
||||||
keyAlias:upload \
|
keyAlias:upload \
|
||||||
keyPassword:${{ env.UPLOAD_KEYSTORE_PASSWORD }}
|
keyPassword:$UPLOAD_KEYSTORE_PASSWORD
|
||||||
|
|
||||||
- name: Generate beta Play Store bundle
|
- name: Generate beta Play Store bundle
|
||||||
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
|
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
|
||||||
env:
|
env:
|
||||||
UPLOAD_BETA_KEYSTORE_PASSWORD: ${{ secrets.UPLOAD_BETA_KEYSTORE_PASSWORD }}
|
UPLOAD_BETA_KEYSTORE_PASSWORD: ${{ steps.get-kv-secrets.outputs.UPLOAD-BETA-KEYSTORE-PASSWORD }}
|
||||||
UPLOAD_BETA_KEY_PASSWORD: ${{ secrets.UPLOAD_BETA_KEY_PASSWORD }}
|
UPLOAD_BETA_KEY_PASSWORD: ${{ steps.get-kv-secrets.outputs.UPLOAD-BETA-KEY-PASSWORD }}
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane bundlePlayStoreBeta \
|
bundle exec fastlane bundlePlayStoreBeta \
|
||||||
storeFile:app_beta_upload-keystore.jks \
|
storeFile:app_beta_upload-keystore.jks \
|
||||||
storePassword:${{ env.UPLOAD_BETA_KEYSTORE_PASSWORD }} \
|
storePassword:$UPLOAD_BETA_KEYSTORE_PASSWORD \
|
||||||
keyAlias:bitwarden-beta-upload \
|
keyAlias:bitwarden-beta-upload \
|
||||||
keyPassword:${{ env.UPLOAD_BETA_KEY_PASSWORD }}
|
keyPassword:$UPLOAD_BETA_KEY_PASSWORD
|
||||||
|
|
||||||
- name: Generate release Play Store APK
|
- name: Generate release Play Store APK
|
||||||
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
|
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
|
||||||
env:
|
env:
|
||||||
PLAY_KEYSTORE_PASSWORD: ${{ secrets.PLAY_KEYSTORE_PASSWORD }}
|
PLAY_KEYSTORE_PASSWORD: ${{ steps.get-kv-secrets.outputs.PLAY-KEYSTORE-PASSWORD }}
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane assemblePlayStoreReleaseApk \
|
bundle exec fastlane assemblePlayStoreReleaseApk \
|
||||||
storeFile:app_play-keystore.jks \
|
storeFile:app_play-keystore.jks \
|
||||||
storePassword:${{ env.PLAY_KEYSTORE_PASSWORD }} \
|
storePassword:$PLAY_KEYSTORE_PASSWORD \
|
||||||
keyAlias:bitwarden \
|
keyAlias:bitwarden \
|
||||||
keyPassword:${{ env.PLAY_KEYSTORE_PASSWORD }}
|
keyPassword:$PLAY_KEYSTORE_PASSWORD
|
||||||
|
|
||||||
- name: Generate beta Play Store APK
|
- name: Generate beta Play Store APK
|
||||||
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
|
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
|
||||||
env:
|
env:
|
||||||
PLAY_BETA_KEYSTORE_PASSWORD: ${{ secrets.PLAY_BETA_KEYSTORE_PASSWORD }}
|
PLAY_BETA_KEYSTORE_PASSWORD: ${{ steps.get-kv-secrets.outputs.PLAY-BETA-KEYSTORE-PASSWORD }}
|
||||||
PLAY_BETA_KEY_PASSWORD: ${{ secrets.PLAY_BETA_KEY_PASSWORD }}
|
PLAY_BETA_KEY_PASSWORD: ${{ steps.get-kv-secrets.outputs.PLAY-BETA-KEY-PASSWORD }}
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane assemblePlayStoreBetaApk \
|
bundle exec fastlane assemblePlayStoreBetaApk \
|
||||||
storeFile:app_beta_play-keystore.jks \
|
storeFile:app_beta_play-keystore.jks \
|
||||||
storePassword:${{ env.PLAY_BETA_KEYSTORE_PASSWORD }} \
|
storePassword:$PLAY_BETA_KEYSTORE_PASSWORD \
|
||||||
keyAlias:bitwarden-beta \
|
keyAlias:bitwarden-beta \
|
||||||
keyPassword:${{ env.PLAY_BETA_KEY_PASSWORD }}
|
keyPassword:$PLAY_BETA_KEY_PASSWORD
|
||||||
|
|
||||||
- name: Generate debug Play Store APKs
|
- name: Generate debug Play Store APKs
|
||||||
if: ${{ (matrix.variant != 'prod') && (matrix.artifact == 'apk') }}
|
if: ${{ (matrix.variant != 'prod') && (matrix.artifact == 'apk') }}
|
||||||
@ -266,7 +297,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload release Play Store .aab artifact
|
- name: Upload release Play Store .aab artifact
|
||||||
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
|
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden.aab
|
name: com.x8bit.bitwarden.aab
|
||||||
path: app/build/outputs/bundle/standardRelease/com.x8bit.bitwarden.aab
|
path: app/build/outputs/bundle/standardRelease/com.x8bit.bitwarden.aab
|
||||||
@ -274,7 +305,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload beta Play Store .aab artifact
|
- name: Upload beta Play Store .aab artifact
|
||||||
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
|
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden.beta.aab
|
name: com.x8bit.bitwarden.beta.aab
|
||||||
path: app/build/outputs/bundle/standardBeta/com.x8bit.bitwarden.beta.aab
|
path: app/build/outputs/bundle/standardBeta/com.x8bit.bitwarden.beta.aab
|
||||||
@ -282,7 +313,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload release .apk artifact
|
- name: Upload release .apk artifact
|
||||||
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
|
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden.apk
|
name: com.x8bit.bitwarden.apk
|
||||||
path: app/build/outputs/apk/standard/release/com.x8bit.bitwarden.apk
|
path: app/build/outputs/apk/standard/release/com.x8bit.bitwarden.apk
|
||||||
@ -290,7 +321,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload beta .apk artifact
|
- name: Upload beta .apk artifact
|
||||||
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
|
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden.beta.apk
|
name: com.x8bit.bitwarden.beta.apk
|
||||||
path: app/build/outputs/apk/standard/beta/com.x8bit.bitwarden.beta.apk
|
path: app/build/outputs/apk/standard/beta/com.x8bit.bitwarden.beta.apk
|
||||||
@ -299,7 +330,7 @@ jobs:
|
|||||||
# When building variants other than 'prod'
|
# When building variants other than 'prod'
|
||||||
- name: Upload debug .apk artifact
|
- name: Upload debug .apk artifact
|
||||||
if: ${{ (matrix.variant != 'prod') && (matrix.artifact == 'apk') }}
|
if: ${{ (matrix.variant != 'prod') && (matrix.artifact == 'apk') }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden.${{ matrix.variant }}.apk
|
name: com.x8bit.bitwarden.${{ matrix.variant }}.apk
|
||||||
path: app/build/outputs/apk/standard/debug/com.x8bit.bitwarden.dev.apk
|
path: app/build/outputs/apk/standard/debug/com.x8bit.bitwarden.dev.apk
|
||||||
@ -337,7 +368,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload .apk SHA file for release
|
- name: Upload .apk SHA file for release
|
||||||
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
|
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden.apk-sha256.txt
|
name: com.x8bit.bitwarden.apk-sha256.txt
|
||||||
path: ./com.x8bit.bitwarden.apk-sha256.txt
|
path: ./com.x8bit.bitwarden.apk-sha256.txt
|
||||||
@ -345,7 +376,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload .apk SHA file for beta
|
- name: Upload .apk SHA file for beta
|
||||||
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
|
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'apk') }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden.beta.apk-sha256.txt
|
name: com.x8bit.bitwarden.beta.apk-sha256.txt
|
||||||
path: ./com.x8bit.bitwarden.beta.apk-sha256.txt
|
path: ./com.x8bit.bitwarden.beta.apk-sha256.txt
|
||||||
@ -353,7 +384,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload .aab SHA file for release
|
- name: Upload .aab SHA file for release
|
||||||
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
|
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden.aab-sha256.txt
|
name: com.x8bit.bitwarden.aab-sha256.txt
|
||||||
path: ./com.x8bit.bitwarden.aab-sha256.txt
|
path: ./com.x8bit.bitwarden.aab-sha256.txt
|
||||||
@ -361,7 +392,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload .aab SHA file for beta
|
- name: Upload .aab SHA file for beta
|
||||||
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
|
if: ${{ (matrix.variant == 'prod') && (matrix.artifact == 'aab') }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden.beta.aab-sha256.txt
|
name: com.x8bit.bitwarden.beta.aab-sha256.txt
|
||||||
path: ./com.x8bit.bitwarden.beta.aab-sha256.txt
|
path: ./com.x8bit.bitwarden.beta.aab-sha256.txt
|
||||||
@ -369,7 +400,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload .apk SHA file for debug
|
- name: Upload .apk SHA file for debug
|
||||||
if: ${{ (matrix.variant != 'prod') && (matrix.artifact == 'apk') }}
|
if: ${{ (matrix.variant != 'prod') && (matrix.artifact == 'apk') }}
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden.${{ matrix.variant }}.apk-sha256.txt
|
name: com.x8bit.bitwarden.${{ matrix.variant }}.apk-sha256.txt
|
||||||
path: ./com.x8bit.bitwarden.${{ matrix.variant }}.apk-sha256.txt
|
path: ./com.x8bit.bitwarden.${{ matrix.variant }}.apk-sha256.txt
|
||||||
@ -385,8 +416,8 @@ jobs:
|
|||||||
APP_PLAY_FIREBASE_CREDS_PATH: ${{ github.workspace }}/secrets/app_play_prod_firebase-creds.json
|
APP_PLAY_FIREBASE_CREDS_PATH: ${{ github.workspace }}/secrets/app_play_prod_firebase-creds.json
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane distributeReleasePlayStoreToFirebase \
|
bundle exec fastlane distributeReleasePlayStoreToFirebase \
|
||||||
actionUrl:${{ env.GITHUB_ACTION_RUN_URL }} \
|
actionUrl:$GITHUB_ACTION_RUN_URL \
|
||||||
service_credentials_file:${{ env.APP_PLAY_FIREBASE_CREDS_PATH }}
|
service_credentials_file:$APP_PLAY_FIREBASE_CREDS_PATH
|
||||||
|
|
||||||
- name: Publish beta artifacts to Firebase
|
- name: Publish beta artifacts to Firebase
|
||||||
if: ${{ (matrix.variant == 'prod' && matrix.artifact == 'apk') && (inputs.distribute-to-firebase || github.event_name == 'push') }}
|
if: ${{ (matrix.variant == 'prod' && matrix.artifact == 'apk') && (inputs.distribute-to-firebase || github.event_name == 'push') }}
|
||||||
@ -394,8 +425,8 @@ jobs:
|
|||||||
APP_PLAY_FIREBASE_CREDS_PATH: ${{ github.workspace }}/secrets/app_play_prod_firebase-creds.json
|
APP_PLAY_FIREBASE_CREDS_PATH: ${{ github.workspace }}/secrets/app_play_prod_firebase-creds.json
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane distributeBetaPlayStoreToFirebase \
|
bundle exec fastlane distributeBetaPlayStoreToFirebase \
|
||||||
actionUrl:${{ env.GITHUB_ACTION_RUN_URL }} \
|
actionUrl:$GITHUB_ACTION_RUN_URL \
|
||||||
service_credentials_file:${{ env.APP_PLAY_FIREBASE_CREDS_PATH }}
|
service_credentials_file:$APP_PLAY_FIREBASE_CREDS_PATH
|
||||||
|
|
||||||
- name: Verify Play Store credentials
|
- name: Verify Play Store credentials
|
||||||
if: ${{ matrix.variant == 'prod' && inputs.publish-to-play-store }}
|
if: ${{ matrix.variant == 'prod' && inputs.publish-to-play-store }}
|
||||||
@ -403,7 +434,7 @@ jobs:
|
|||||||
bundle exec fastlane run validate_play_store_json_key
|
bundle exec fastlane run validate_play_store_json_key
|
||||||
|
|
||||||
- name: Publish Play Store bundle
|
- name: Publish Play Store bundle
|
||||||
if: ${{ matrix.variant == 'prod' && matrix.artifact == 'aab' && (inputs.publish-to-play-store || github.ref_name == 'main') }}
|
if: ${{ matrix.variant == 'prod' && matrix.artifact == 'aab' && (inputs.publish-to-play-store || github.event_name == 'push') }}
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane publishProdToPlayStore
|
bundle exec fastlane publishProdToPlayStore
|
||||||
bundle exec fastlane publishBetaToPlayStore
|
bundle exec fastlane publishBetaToPlayStore
|
||||||
@ -411,36 +442,49 @@ jobs:
|
|||||||
publish_fdroid:
|
publish_fdroid:
|
||||||
name: Publish F-Droid artifacts
|
name: Publish F-Droid artifacts
|
||||||
needs:
|
needs:
|
||||||
|
- version
|
||||||
- build
|
- build
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
steps:
|
steps:
|
||||||
- name: Check out repo
|
- name: Check out repo
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
- name: Configure Ruby
|
- name: Configure Ruby
|
||||||
uses: ruby/setup-ruby@ca041f971d66735f3e5ff1e21cc13e2d51e7e535 # v1.233.0
|
uses: ruby/setup-ruby@44511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0
|
||||||
with:
|
with:
|
||||||
bundler-cache: true
|
bundler-cache: true
|
||||||
|
|
||||||
- name: Install Fastlane
|
- name: Install Fastlane
|
||||||
run: |
|
run: |
|
||||||
gem install bundler:2.2.27
|
|
||||||
bundle config path vendor/bundle
|
bundle config path vendor/bundle
|
||||||
bundle install --jobs 4 --retry 3
|
bundle install --jobs 4 --retry 3
|
||||||
|
|
||||||
- name: Log in to Azure
|
- name: Log in to Azure
|
||||||
uses: Azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0
|
uses: bitwarden/gh-actions/azure-login@main
|
||||||
with:
|
with:
|
||||||
creds: ${{ secrets.AZURE_KV_CI_SERVICE_PRINCIPAL }}
|
subscription_id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
tenant_id: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
client_id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
|
|
||||||
|
- name: Get Azure Key Vault secrets
|
||||||
|
id: get-kv-secrets
|
||||||
|
uses: bitwarden/gh-actions/get-keyvault-secrets@main
|
||||||
|
with:
|
||||||
|
keyvault: gh-android
|
||||||
|
secrets: "FDROID-KEYSTORE-PASSWORD,FDROID-BETA-KEYSTORE-PASSWORD,FDROID-BETA-KEY-PASSWORD"
|
||||||
|
|
||||||
- name: Retrieve secrets
|
- name: Retrieve secrets
|
||||||
env:
|
env:
|
||||||
ACCOUNT_NAME: bitwardenci
|
ACCOUNT_NAME: bitwardenci
|
||||||
CONTAINER_NAME: mobile
|
CONTAINER_NAME: mobile
|
||||||
run: |
|
run: |
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name app_fdroid-keystore.jks --file ${{ github.workspace }}/keystores/app_fdroid-keystore.jks --output none
|
--name app_fdroid-keystore.jks --file ${{ github.workspace }}/keystores/app_fdroid-keystore.jks --output none
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name app_beta_fdroid-keystore.jks --file ${{ github.workspace }}/keystores/app_beta_fdroid-keystore.jks --output none
|
--name app_beta_fdroid-keystore.jks --file ${{ github.workspace }}/keystores/app_beta_fdroid-keystore.jks --output none
|
||||||
|
|
||||||
- name: Download Firebase credentials
|
- name: Download Firebase credentials
|
||||||
@ -451,14 +495,17 @@ jobs:
|
|||||||
run: |
|
run: |
|
||||||
mkdir -p ${{ github.workspace }}/secrets
|
mkdir -p ${{ github.workspace }}/secrets
|
||||||
|
|
||||||
az storage blob download --account-name $ACCOUNT_NAME --container-name $CONTAINER_NAME \
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
--name app_fdroid_firebase-creds.json --file ${{ github.workspace }}/secrets/app_fdroid_firebase-creds.json --output none
|
--name app_fdroid_firebase-creds.json --file ${{ github.workspace }}/secrets/app_fdroid_firebase-creds.json --output none
|
||||||
|
|
||||||
|
- name: Log out from Azure
|
||||||
|
uses: bitwarden/gh-actions/azure-logout@main
|
||||||
|
|
||||||
- name: Validate Gradle wrapper
|
- name: Validate Gradle wrapper
|
||||||
uses: gradle/actions/wrapper-validation@06832c7b30a0129d7fb559bcc6e43d26f6374244 # v4.3.1
|
uses: gradle/actions/wrapper-validation@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||||
|
|
||||||
- name: Cache Gradle files
|
- name: Cache Gradle files
|
||||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/.gradle/caches
|
~/.gradle/caches
|
||||||
@ -468,7 +515,7 @@ jobs:
|
|||||||
${{ runner.os }}-gradle-v2-
|
${{ runner.os }}-gradle-v2-
|
||||||
|
|
||||||
- name: Cache build output
|
- name: Cache build output
|
||||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
${{ github.workspace }}/build-cache
|
${{ github.workspace }}/build-cache
|
||||||
@ -477,7 +524,7 @@ jobs:
|
|||||||
${{ runner.os }}-build-
|
${{ runner.os }}-build-
|
||||||
|
|
||||||
- name: Configure JDK
|
- name: Configure JDK
|
||||||
uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
|
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||||
with:
|
with:
|
||||||
distribution: "temurin"
|
distribution: "temurin"
|
||||||
java-version: ${{ env.JAVA_VERSION }}
|
java-version: ${{ env.JAVA_VERSION }}
|
||||||
@ -485,50 +532,51 @@ jobs:
|
|||||||
- name: Update app CI Build info
|
- name: Update app CI Build info
|
||||||
run: |
|
run: |
|
||||||
./scripts/update_app_ci_build_info.sh \
|
./scripts/update_app_ci_build_info.sh \
|
||||||
$GITHUB_REPOSITORY \
|
"$GITHUB_REPOSITORY" \
|
||||||
$GITHUB_REF_NAME \
|
"$GITHUB_REF_NAME" \
|
||||||
$GITHUB_SHA \
|
"$GITHUB_SHA" \
|
||||||
$GITHUB_RUN_ID \
|
"$GITHUB_RUN_ID" \
|
||||||
$GITHUB_RUN_ATTEMPT
|
"$GITHUB_RUN_ATTEMPT"
|
||||||
|
|
||||||
# Start from 11000 to prevent collisions with mobile build version codes
|
|
||||||
- name: Increment version
|
- name: Increment version
|
||||||
|
env:
|
||||||
|
VERSION_CODE: ${{ needs.version.outputs.version_number }}
|
||||||
|
VERSION_NAME: ${{ needs.version.outputs.version_name }}
|
||||||
run: |
|
run: |
|
||||||
DEFAULT_VERSION_CODE=$((11000+GITHUB_RUN_NUMBER))
|
VERSION_CODE="${VERSION_CODE:-$GITHUB_RUN_NUMBER}"
|
||||||
VERSION_CODE="${{ inputs.version-code || '$DEFAULT_VERSION_CODE' }}"
|
|
||||||
bundle exec fastlane setBuildVersionInfo \
|
bundle exec fastlane setBuildVersionInfo \
|
||||||
versionCode:$VERSION_CODE \
|
versionCode:$VERSION_CODE \
|
||||||
versionName:${{ inputs.version-name || '' }}
|
versionName:$VERSION_NAME
|
||||||
|
|
||||||
regex='versionName = "([^"]+)"'
|
regex='appVersionName = "([^"]+)"'
|
||||||
if [[ "$(cat app/build.gradle.kts)" =~ $regex ]]; then
|
if [[ "$(cat gradle/libs.versions.toml)" =~ $regex ]]; then
|
||||||
VERSION_NAME="${BASH_REMATCH[1]}"
|
VERSION_NAME="${BASH_REMATCH[1]}"
|
||||||
fi
|
fi
|
||||||
echo "Version Name: ${VERSION_NAME}" >> $GITHUB_STEP_SUMMARY
|
echo "Version Name: ${VERSION_NAME}" >> "$GITHUB_STEP_SUMMARY"
|
||||||
echo "Version Number: $VERSION_CODE" >> $GITHUB_STEP_SUMMARY
|
echo "Version Number: $VERSION_CODE" >> "$GITHUB_STEP_SUMMARY"
|
||||||
- name: Generate F-Droid artifacts
|
- name: Generate F-Droid artifacts
|
||||||
env:
|
env:
|
||||||
FDROID_STORE_PASSWORD: ${{ secrets.FDROID_KEYSTORE_PASSWORD }}
|
FDROID_STORE_PASSWORD: ${{ steps.get-kv-secrets.outputs.FDROID-KEYSTORE-PASSWORD }}
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane assembleFDroidReleaseApk \
|
bundle exec fastlane assembleFDroidReleaseApk \
|
||||||
storeFile:app_fdroid-keystore.jks \
|
storeFile:app_fdroid-keystore.jks \
|
||||||
storePassword:"${{ env.FDROID_STORE_PASSWORD }}" \
|
storePassword:$FDROID_STORE_PASSWORD \
|
||||||
keyAlias:bitwarden \
|
keyAlias:bitwarden \
|
||||||
keyPassword:"${{ env.FDROID_STORE_PASSWORD }}"
|
keyPassword:$FDROID_STORE_PASSWORD
|
||||||
|
|
||||||
- name: Generate F-Droid Beta Artifacts
|
- name: Generate F-Droid Beta Artifacts
|
||||||
env:
|
env:
|
||||||
FDROID_BETA_KEYSTORE_PASSWORD: ${{ secrets.FDROID_BETA_KEYSTORE_PASSWORD }}
|
FDROID_BETA_KEYSTORE_PASSWORD: ${{ steps.get-kv-secrets.outputs.FDROID-BETA-KEYSTORE-PASSWORD }}
|
||||||
FDROID_BETA_KEY_PASSWORD: ${{ secrets.FDROID_BETA_KEY_PASSWORD }}
|
FDROID_BETA_KEY_PASSWORD: ${{ steps.get-kv-secrets.outputs.FDROID-BETA-KEY-PASSWORD }}
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane assembleFDroidBetaApk \
|
bundle exec fastlane assembleFDroidBetaApk \
|
||||||
storeFile:app_beta_fdroid-keystore.jks \
|
storeFile:app_beta_fdroid-keystore.jks \
|
||||||
storePassword:"${{ env.FDROID_BETA_KEYSTORE_PASSWORD }}" \
|
storePassword:$FDROID_BETA_KEYSTORE_PASSWORD \
|
||||||
keyAlias:bitwarden-beta \
|
keyAlias:bitwarden-beta \
|
||||||
keyPassword:"${{ env.FDROID_BETA_KEY_PASSWORD }}"
|
keyPassword:$FDROID_BETA_KEY_PASSWORD
|
||||||
|
|
||||||
- name: Upload F-Droid .apk artifact
|
- name: Upload F-Droid .apk artifact
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden-fdroid.apk
|
name: com.x8bit.bitwarden-fdroid.apk
|
||||||
path: app/build/outputs/apk/fdroid/release/com.x8bit.bitwarden-fdroid.apk
|
path: app/build/outputs/apk/fdroid/release/com.x8bit.bitwarden-fdroid.apk
|
||||||
@ -540,14 +588,14 @@ jobs:
|
|||||||
> ./com.x8bit.bitwarden-fdroid.apk-sha256.txt
|
> ./com.x8bit.bitwarden-fdroid.apk-sha256.txt
|
||||||
|
|
||||||
- name: Upload F-Droid SHA file
|
- name: Upload F-Droid SHA file
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden-fdroid.apk-sha256.txt
|
name: com.x8bit.bitwarden-fdroid.apk-sha256.txt
|
||||||
path: ./com.x8bit.bitwarden-fdroid.apk-sha256.txt
|
path: ./com.x8bit.bitwarden-fdroid.apk-sha256.txt
|
||||||
if-no-files-found: error
|
if-no-files-found: error
|
||||||
|
|
||||||
- name: Upload F-Droid Beta .apk artifact
|
- name: Upload F-Droid Beta .apk artifact
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden.beta-fdroid.apk
|
name: com.x8bit.bitwarden.beta-fdroid.apk
|
||||||
path: app/build/outputs/apk/fdroid/beta/com.x8bit.bitwarden.beta-fdroid.apk
|
path: app/build/outputs/apk/fdroid/beta/com.x8bit.bitwarden.beta-fdroid.apk
|
||||||
@ -559,7 +607,7 @@ jobs:
|
|||||||
> ./com.x8bit.bitwarden.beta-fdroid.apk-sha256.txt
|
> ./com.x8bit.bitwarden.beta-fdroid.apk-sha256.txt
|
||||||
|
|
||||||
- name: Upload F-Droid Beta SHA file
|
- name: Upload F-Droid Beta SHA file
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
with:
|
with:
|
||||||
name: com.x8bit.bitwarden.beta-fdroid.apk-sha256.txt
|
name: com.x8bit.bitwarden.beta-fdroid.apk-sha256.txt
|
||||||
path: ./com.x8bit.bitwarden.beta-fdroid.apk-sha256.txt
|
path: ./com.x8bit.bitwarden.beta-fdroid.apk-sha256.txt
|
||||||
@ -575,5 +623,5 @@ jobs:
|
|||||||
APP_FDROID_FIREBASE_CREDS_PATH: ${{ github.workspace }}/secrets/app_fdroid_firebase-creds.json
|
APP_FDROID_FIREBASE_CREDS_PATH: ${{ github.workspace }}/secrets/app_fdroid_firebase-creds.json
|
||||||
run: |
|
run: |
|
||||||
bundle exec fastlane distributeReleaseFDroidToFirebase \
|
bundle exec fastlane distributeReleaseFDroidToFirebase \
|
||||||
actionUrl:${{ env.GITHUB_ACTION_RUN_URL }} \
|
actionUrl:$GITHUB_ACTION_RUN_URL \
|
||||||
service_credentials_file:${{ env.APP_FDROID_FIREBASE_CREDS_PATH }}
|
service_credentials_file:$APP_FDROID_FIREBASE_CREDS_PATH
|
||||||
|
|||||||
@ -3,7 +3,7 @@ name: Cron / Sync Google Privileged Browsers List
|
|||||||
on:
|
on:
|
||||||
schedule:
|
schedule:
|
||||||
# Run weekly on Monday at 00:00 UTC
|
# Run weekly on Monday at 00:00 UTC
|
||||||
- cron: '0 0 * * 1'
|
- cron: "0 0 * * 1"
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
@ -21,25 +21,26 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout
|
- name: Checkout
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # 4.2.2
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
with:
|
||||||
|
persist-credentials: true
|
||||||
|
|
||||||
- name: Download Google Privileged Browsers List
|
- name: Download Google Privileged Browsers List
|
||||||
run: curl -s $SOURCE_URL -o $GOOGLE_FILE
|
run: curl -s "$SOURCE_URL" -o "$GOOGLE_FILE"
|
||||||
|
|
||||||
- name: Check for changes
|
- name: Check for changes
|
||||||
id: check-changes
|
id: check-changes
|
||||||
run: |
|
run: |
|
||||||
if git diff --quiet -- $GOOGLE_FILE; then
|
if git diff --quiet -- "$GOOGLE_FILE"; then
|
||||||
echo "👀 No changes detected, skipping..."
|
echo "👀 No changes detected, skipping..."
|
||||||
echo "has_changes=false" >> $GITHUB_OUTPUT
|
echo "has_changes=false" >> "$GITHUB_OUTPUT"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "has_changes=true" >> $GITHUB_OUTPUT
|
echo "has_changes=true" >> "$GITHUB_OUTPUT"
|
||||||
echo "👀 Changes detected, validating fido2_privileged_google.json..."
|
echo "👀 Changes detected, validating fido2_privileged_google.json..."
|
||||||
|
|
||||||
python .github/scripts/validate-json/validate_json.py validate $GOOGLE_FILE
|
if ! python .github/scripts/validate-json/validate_json.py validate "$GOOGLE_FILE"; then
|
||||||
if [ $? -ne 0 ]; then
|
|
||||||
echo "::error::JSON validation failed for $GOOGLE_FILE"
|
echo "::error::JSON validation failed for $GOOGLE_FILE"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
@ -47,14 +48,14 @@ jobs:
|
|||||||
echo "👀 fido2_privileged_google.json is valid, checking for duplicates..."
|
echo "👀 fido2_privileged_google.json is valid, checking for duplicates..."
|
||||||
|
|
||||||
# Check for duplicates between Google and Community files
|
# Check for duplicates between Google and Community files
|
||||||
python .github/scripts/validate-json/validate_json.py duplicates $GOOGLE_FILE $COMMUNITY_FILE duplicates.txt
|
python .github/scripts/validate-json/validate_json.py duplicates "$GOOGLE_FILE" "$COMMUNITY_FILE" duplicates.txt
|
||||||
|
|
||||||
if [ -f duplicates.txt ]; then
|
if [ -f duplicates.txt ]; then
|
||||||
echo "::warning::Duplicate package names found between Google and Community files."
|
echo "::warning::Duplicate package names found between Google and Community files."
|
||||||
echo "duplicates_found=true" >> $GITHUB_OUTPUT
|
echo "duplicates_found=true" >> "$GITHUB_OUTPUT"
|
||||||
else
|
else
|
||||||
echo "✅ No duplicate package names found between Google and Community files"
|
echo "✅ No duplicate package names found between Google and Community files"
|
||||||
echo "duplicates_found=false" >> $GITHUB_OUTPUT
|
echo "duplicates_found=false" >> "$GITHUB_OUTPUT"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
- name: Create branch and commit
|
- name: Create branch and commit
|
||||||
@ -65,11 +66,11 @@ jobs:
|
|||||||
BRANCH_NAME="cron-sync-privileged-browsers/$GITHUB_RUN_NUMBER-sync"
|
BRANCH_NAME="cron-sync-privileged-browsers/$GITHUB_RUN_NUMBER-sync"
|
||||||
git config user.name "GitHub Actions Bot"
|
git config user.name "GitHub Actions Bot"
|
||||||
git config user.email "actions@github.com"
|
git config user.email "actions@github.com"
|
||||||
git checkout -b $BRANCH_NAME
|
git checkout -b "$BRANCH_NAME"
|
||||||
git add $GOOGLE_FILE
|
git add "$GOOGLE_FILE"
|
||||||
git commit -m "Update Google privileged browsers list"
|
git commit -m "Update Google privileged browsers list"
|
||||||
git push origin $BRANCH_NAME
|
git push origin "$BRANCH_NAME"
|
||||||
echo "BRANCH_NAME=$BRANCH_NAME" >> $GITHUB_ENV
|
echo "BRANCH_NAME=$BRANCH_NAME" >> "$GITHUB_ENV"
|
||||||
echo "🌱 Branch created: $BRANCH_NAME"
|
echo "🌱 Branch created: $BRANCH_NAME"
|
||||||
|
|
||||||
- name: Create Pull Request
|
- name: Create Pull Request
|
||||||
@ -89,10 +90,10 @@ jobs:
|
|||||||
fi
|
fi
|
||||||
|
|
||||||
# Use echo -e to interpret escape sequences and pipe to gh pr create
|
# Use echo -e to interpret escape sequences and pipe to gh pr create
|
||||||
PR_URL=$(echo -e "$PR_BODY" | gh pr create \
|
echo -e "$PR_BODY" | gh pr create \
|
||||||
--title "Update Google privileged browsers list" \
|
--title "Update Google privileged browsers list" \
|
||||||
--body-file - \
|
--body-file - \
|
||||||
--base main \
|
--base main \
|
||||||
--head $BRANCH_NAME \
|
--head "$BRANCH_NAME" \
|
||||||
--label "automated-pr" \
|
--label "automated-pr" \
|
||||||
--label "t:ci")
|
--label "t:ci"
|
||||||
|
|||||||
62
.github/workflows/crowdin-pull.yml
vendored
62
.github/workflows/crowdin-pull.yml
vendored
@ -4,34 +4,35 @@ run-name: Crowdin Pull - ${{ github.event_name == 'workflow_dispatch' && 'Manual
|
|||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '0 0 * * 5'
|
- cron: "0 0 * * 5"
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
crowdin-sync:
|
crowdin-sync:
|
||||||
name: Crowdin Pull - ${{ matrix.name }} - ${{ github.event_name }}
|
name: Crowdin Pull - ${{ github.event_name }}
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
strategy:
|
id-token: write
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- name: Password Manager
|
|
||||||
project_id: 269690
|
|
||||||
config: crowdin-bwpm.yml
|
|
||||||
branch: crowdin-pull-bwpm
|
|
||||||
- name: Authenticator
|
|
||||||
project_id: 673718
|
|
||||||
config: crowdin-bwa.yml
|
|
||||||
branch: crowdin-pull-bwa
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repo
|
- name: Checkout repo
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
|
||||||
- name: Login to Azure - CI Subscription
|
|
||||||
uses: Azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0
|
|
||||||
with:
|
with:
|
||||||
creds: ${{ secrets.AZURE_KV_CI_SERVICE_PRINCIPAL }}
|
persist-credentials: false
|
||||||
|
|
||||||
|
- name: Log in to Azure
|
||||||
|
uses: bitwarden/gh-actions/azure-login@main
|
||||||
|
with:
|
||||||
|
subscription_id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
tenant_id: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
client_id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
|
|
||||||
|
- name: Get Azure Key Vault secrets
|
||||||
|
id: get-kv-secrets
|
||||||
|
uses: bitwarden/gh-actions/get-keyvault-secrets@main
|
||||||
|
with:
|
||||||
|
keyvault: gh-org-bitwarden
|
||||||
|
secrets: "BW-GHAPP-ID,BW-GHAPP-KEY"
|
||||||
|
|
||||||
- name: Retrieve secrets
|
- name: Retrieve secrets
|
||||||
id: retrieve-secrets
|
id: retrieve-secrets
|
||||||
@ -40,30 +41,33 @@ jobs:
|
|||||||
keyvault: "bitwarden-ci"
|
keyvault: "bitwarden-ci"
|
||||||
secrets: "crowdin-api-token, github-gpg-private-key, github-gpg-private-key-passphrase"
|
secrets: "crowdin-api-token, github-gpg-private-key, github-gpg-private-key-passphrase"
|
||||||
|
|
||||||
|
- name: Log out from Azure
|
||||||
|
uses: bitwarden/gh-actions/azure-logout@main
|
||||||
|
|
||||||
- name: Generate GH App token
|
- name: Generate GH App token
|
||||||
uses: actions/create-github-app-token@3ff1caaa28b64c9cc276ce0a02e2ff584f3900c5 # v2.0.2
|
uses: actions/create-github-app-token@a8d616148505b5069dccd32f177bb87d7f39123b # v2.1.1
|
||||||
id: app-token
|
id: app-token
|
||||||
with:
|
with:
|
||||||
app-id: ${{ secrets.BW_GHAPP_ID }}
|
app-id: ${{ steps.get-kv-secrets.outputs.BW-GHAPP-ID }}
|
||||||
private-key: ${{ secrets.BW_GHAPP_KEY }}
|
private-key: ${{ steps.get-kv-secrets.outputs.BW-GHAPP-KEY }}
|
||||||
|
|
||||||
- name: Download translations for ${{ matrix.name }}
|
- name: Download translations
|
||||||
uses: crowdin/github-action@b8012bd5491b8aa8578b73ab5b5f5e7c94aaa6e2 # v2.7.0
|
uses: crowdin/github-action@0749939f635900a2521aa6aac7a3766642b2dc71 # v2.11.0
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
|
GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||||
CROWDIN_API_TOKEN: ${{ steps.retrieve-secrets.outputs.crowdin-api-token }}
|
CROWDIN_API_TOKEN: ${{ steps.retrieve-secrets.outputs.crowdin-api-token }}
|
||||||
_CROWDIN_PROJECT_ID: ${{ matrix.project_id }}
|
_CROWDIN_PROJECT_ID: "269690"
|
||||||
with:
|
with:
|
||||||
config: ${{ matrix.config }}
|
config: crowdin.yml
|
||||||
upload_sources: false
|
upload_sources: false
|
||||||
upload_translations: false
|
upload_translations: false
|
||||||
download_translations: true
|
download_translations: true
|
||||||
github_user_name: "bitwarden-devops-bot"
|
github_user_name: "bitwarden-devops-bot"
|
||||||
github_user_email: "106330231+bitwarden-devops-bot@users.noreply.github.com"
|
github_user_email: "106330231+bitwarden-devops-bot@users.noreply.github.com"
|
||||||
commit_message: "Crowdin Pull - ${{ matrix.name }}"
|
commit_message: "Crowdin Pull"
|
||||||
localization_branch_name: ${{ matrix.branch }}
|
localization_branch_name: "crowdin-pull"
|
||||||
create_pull_request: true
|
create_pull_request: true
|
||||||
pull_request_title: "Crowdin Pull - ${{ matrix.name }}"
|
pull_request_title: "Crowdin Pull"
|
||||||
pull_request_body: ":inbox_tray: New translations for ${{ matrix.name }} received!"
|
pull_request_body: ":inbox_tray: New translations received!"
|
||||||
gpg_private_key: ${{ steps.retrieve-secrets.outputs.github-gpg-private-key }}
|
gpg_private_key: ${{ steps.retrieve-secrets.outputs.github-gpg-private-key }}
|
||||||
gpg_passphrase: ${{ steps.retrieve-secrets.outputs.github-gpg-private-key-passphrase }}
|
gpg_passphrase: ${{ steps.retrieve-secrets.outputs.github-gpg-private-key-passphrase }}
|
||||||
|
|||||||
29
.github/workflows/crowdin-push.yml
vendored
29
.github/workflows/crowdin-push.yml
vendored
@ -13,14 +13,19 @@ jobs:
|
|||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
|
id-token: write
|
||||||
steps:
|
steps:
|
||||||
- name: Check out repo
|
- name: Check out repo
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
- name: Log in to Azure
|
- name: Log in to Azure
|
||||||
uses: Azure/login@a457da9ea143d694b1b9c7c869ebb04ebe844ef5 # v2.3.0
|
uses: bitwarden/gh-actions/azure-login@main
|
||||||
with:
|
with:
|
||||||
creds: ${{ secrets.AZURE_KV_CI_SERVICE_PRINCIPAL }}
|
subscription_id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
tenant_id: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
client_id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
|
|
||||||
- name: Retrieve secrets
|
- name: Retrieve secrets
|
||||||
id: retrieve-secrets
|
id: retrieve-secrets
|
||||||
@ -29,24 +34,16 @@ jobs:
|
|||||||
keyvault: "bitwarden-ci"
|
keyvault: "bitwarden-ci"
|
||||||
secrets: "crowdin-api-token"
|
secrets: "crowdin-api-token"
|
||||||
|
|
||||||
- name: Upload sources for Password Manager
|
- name: Upload sources
|
||||||
uses: crowdin/github-action@b8012bd5491b8aa8578b73ab5b5f5e7c94aaa6e2 # v2.7.0
|
uses: crowdin/github-action@0749939f635900a2521aa6aac7a3766642b2dc71 # v2.11.0
|
||||||
env:
|
env:
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
CROWDIN_API_TOKEN: ${{ steps.retrieve-secrets.outputs.crowdin-api-token }}
|
CROWDIN_API_TOKEN: ${{ steps.retrieve-secrets.outputs.crowdin-api-token }}
|
||||||
_CROWDIN_PROJECT_ID: "269690"
|
_CROWDIN_PROJECT_ID: "269690"
|
||||||
with:
|
with:
|
||||||
config: crowdin-bwpm.yml
|
config: crowdin.yml
|
||||||
upload_sources: true
|
upload_sources: true
|
||||||
upload_translations: false
|
upload_translations: false
|
||||||
|
|
||||||
- name: Upload sources for Authenticator
|
- name: Log out from Azure
|
||||||
uses: crowdin/github-action@b8012bd5491b8aa8578b73ab5b5f5e7c94aaa6e2 # v2.7.0
|
uses: bitwarden/gh-actions/azure-logout@main
|
||||||
env:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
CROWDIN_API_TOKEN: ${{ steps.retrieve-secrets.outputs.crowdin-api-token }}
|
|
||||||
_CROWDIN_PROJECT_ID: "673718"
|
|
||||||
with:
|
|
||||||
config: crowdin-bwa.yml
|
|
||||||
upload_sources: true
|
|
||||||
upload_translations: false
|
|
||||||
|
|||||||
167
.github/workflows/github-release.yml
vendored
167
.github/workflows/github-release.yml
vendored
@ -4,16 +4,16 @@ on:
|
|||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
artifact-run-id:
|
artifact-run-id:
|
||||||
description: 'GitHub Action Run ID containing artifacts'
|
description: "GitHub Action Run ID containing artifacts"
|
||||||
required: true
|
required: true
|
||||||
type: string
|
type: string
|
||||||
release-ticket-id:
|
release-ticket-id:
|
||||||
description: 'Release Ticket ID - e.g. RELEASE-1762'
|
description: "Release Ticket ID - e.g. RELEASE-1762"
|
||||||
required: true
|
required: true
|
||||||
type: string
|
type: string
|
||||||
|
|
||||||
env:
|
env:
|
||||||
ARTIFACTS_PATH: artifacts
|
ARTIFACTS_PATH: artifacts
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
create-release:
|
create-release:
|
||||||
@ -21,12 +21,19 @@ jobs:
|
|||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
|
id-token: write
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Check out repository
|
- name: Check out repository
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
persist-credentials: true
|
||||||
|
|
||||||
|
- name: Log inputs to job summary
|
||||||
|
uses: ./.github/actions/log-inputs
|
||||||
|
with:
|
||||||
|
inputs: ${{ toJson(inputs) }}
|
||||||
|
|
||||||
- name: Get branch from workflow run
|
- name: Get branch from workflow run
|
||||||
id: get_release_branch
|
id: get_release_branch
|
||||||
@ -34,7 +41,7 @@ jobs:
|
|||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
ARTIFACT_RUN_ID: ${{ inputs.artifact-run-id }}
|
ARTIFACT_RUN_ID: ${{ inputs.artifact-run-id }}
|
||||||
run: |
|
run: |
|
||||||
workflow_data=$(gh run view $ARTIFACT_RUN_ID --json headBranch,workflowName)
|
workflow_data=$(gh run view "$ARTIFACT_RUN_ID" --json headBranch,workflowName)
|
||||||
release_branch=$(echo "$workflow_data" | jq -r .headBranch)
|
release_branch=$(echo "$workflow_data" | jq -r .headBranch)
|
||||||
workflow_name=$(echo "$workflow_data" | jq -r .workflowName)
|
workflow_name=$(echo "$workflow_data" | jq -r .workflowName)
|
||||||
|
|
||||||
@ -44,23 +51,29 @@ jobs:
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "release_branch=$release_branch" >> $GITHUB_OUTPUT
|
echo "🔖 Release branch: $release_branch"
|
||||||
echo "workflow_name=$workflow_name" >> $GITHUB_OUTPUT
|
echo "🔖 Workflow name: $workflow_name"
|
||||||
|
echo "release_branch=$release_branch" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "workflow_name=$workflow_name" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
case "$workflow_name" in
|
case "$workflow_name" in
|
||||||
*"Password Manager"* | "Build")
|
*"Password Manager"* | "Build")
|
||||||
echo "app_name=Password Manager" >> $GITHUB_OUTPUT
|
app_name="Password Manager"
|
||||||
echo "app_name_suffix=bwpm" >> $GITHUB_OUTPUT
|
app_name_suffix="bwpm"
|
||||||
;;
|
;;
|
||||||
*"Authenticator"*)
|
*"Authenticator"*)
|
||||||
echo "app_name=Authenticator" >> $GITHUB_OUTPUT
|
app_name="Authenticator"
|
||||||
echo "app_name_suffix=bwa" >> $GITHUB_OUTPUT
|
app_name_suffix="bwa"
|
||||||
;;
|
;;
|
||||||
*)
|
*)
|
||||||
echo "::error::Unknown workflow name: $workflow_name"
|
echo "::error::Unknown workflow name: $workflow_name"
|
||||||
exit 1
|
exit 1
|
||||||
;;
|
;;
|
||||||
esac
|
esac
|
||||||
|
echo "🔖 App name: $app_name"
|
||||||
|
echo "🔖 App name suffix: $app_name_suffix"
|
||||||
|
echo "app_name=$app_name" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "app_name_suffix=$app_name_suffix" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Get version info from run logs and set release tag name
|
- name: Get version info from run logs and set release tag name
|
||||||
id: get_release_info
|
id: get_release_info
|
||||||
@ -69,7 +82,7 @@ jobs:
|
|||||||
ARTIFACT_RUN_ID: ${{ inputs.artifact-run-id }}
|
ARTIFACT_RUN_ID: ${{ inputs.artifact-run-id }}
|
||||||
_APP_NAME_SUFFIX: ${{ steps.get_release_branch.outputs.app_name_suffix }}
|
_APP_NAME_SUFFIX: ${{ steps.get_release_branch.outputs.app_name_suffix }}
|
||||||
run: |
|
run: |
|
||||||
workflow_log=$(gh run view $ARTIFACT_RUN_ID --log)
|
workflow_log=$(gh run view "$ARTIFACT_RUN_ID" --log)
|
||||||
|
|
||||||
version_number_with_trailing_dot=$(grep -m 1 "Setting version code to" <<< "$workflow_log" | sed 's/.*Setting version code to //')
|
version_number_with_trailing_dot=$(grep -m 1 "Setting version code to" <<< "$workflow_log" | sed 's/.*Setting version code to //')
|
||||||
version_number=${version_number_with_trailing_dot%.} # remove trailing dot
|
version_number=${version_number_with_trailing_dot%.} # remove trailing dot
|
||||||
@ -91,30 +104,75 @@ jobs:
|
|||||||
echo "✅ Found version number: $version_number"
|
echo "✅ Found version number: $version_number"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo "version_number=$version_number" >> $GITHUB_OUTPUT
|
echo "version_number=$version_number" >> "$GITHUB_OUTPUT"
|
||||||
echo "version_name=$version_name" >> $GITHUB_OUTPUT
|
echo "version_name=$version_name" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
tag_name="v$version_name-$_APP_NAME_SUFFIX" # e.g. v2025.6.0-bwpm
|
tag_name="v$version_name-$_APP_NAME_SUFFIX" # e.g. v2025.6.0-bwpm
|
||||||
echo "🔖 New tag name: $tag_name"
|
echo "🔖 New tag name: $tag_name"
|
||||||
echo "tag_name=$tag_name" >> $GITHUB_OUTPUT
|
echo "tag_name=$tag_name" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
last_release_tag=$(git tag -l --sort=-authordate | grep "$APP_NAME_SUFFIX" | head -n 1)
|
last_release_tag=$(git tag -l --sort=-authordate | grep "$_APP_NAME_SUFFIX" | head -n 1)
|
||||||
echo "🔖 Last release tag: $last_release_tag"
|
echo "🔖 Last release tag: $last_release_tag"
|
||||||
echo "last_release_tag=$last_release_tag" >> $GITHUB_OUTPUT
|
echo "last_release_tag=$last_release_tag" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Download artifacts
|
- name: Download artifacts
|
||||||
env:
|
env:
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
ARTIFACT_RUN_ID: ${{ inputs.artifact-run-id }}
|
ARTIFACT_RUN_ID: ${{ inputs.artifact-run-id }}
|
||||||
run: |
|
run: |
|
||||||
gh run download $ARTIFACT_RUN_ID -D $ARTIFACTS_PATH
|
gh run download "$ARTIFACT_RUN_ID" -D "$ARTIFACTS_PATH"
|
||||||
file_count=$(find $ARTIFACTS_PATH -type f | wc -l)
|
file_count=$(find "$ARTIFACTS_PATH" -type f | wc -l)
|
||||||
echo "Downloaded $file_count file(s)."
|
echo "Downloaded $file_count file(s)."
|
||||||
if [ "$file_count" -gt 0 ]; then
|
if [ "$file_count" -gt 0 ]; then
|
||||||
echo "Downloaded files:"
|
echo "Downloaded files:"
|
||||||
find $ARTIFACTS_PATH -type f
|
find "$ARTIFACTS_PATH" -type f
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# Files that won't be included in any release
|
||||||
|
files_to_remove=(
|
||||||
|
"com.x8bit.bitwarden.aab"
|
||||||
|
"com.x8bit.bitwarden.aab-sha256.txt"
|
||||||
|
|
||||||
|
"com.x8bit.bitwarden.beta.apk"
|
||||||
|
"com.x8bit.bitwarden.beta.apk-sha256.txt"
|
||||||
|
"com.x8bit.bitwarden.beta.aab"
|
||||||
|
"com.x8bit.bitwarden.beta.aab-sha256.txt"
|
||||||
|
|
||||||
|
"com.x8bit.bitwarden.beta-fdroid.apk"
|
||||||
|
"com.x8bit.bitwarden.beta-fdroid.apk-sha256.txt"
|
||||||
|
|
||||||
|
"com.x8bit.bitwarden.dev.apk"
|
||||||
|
"com.x8bit.bitwarden.dev.apk-sha256.txt"
|
||||||
|
|
||||||
|
"com.bitwarden.authenticator.aab"
|
||||||
|
"authenticator-android-aab-sha256.txt"
|
||||||
|
)
|
||||||
|
|
||||||
|
for file in "${files_to_remove[@]}"; do
|
||||||
|
find "$ARTIFACTS_PATH" -name "$file" -type f -delete
|
||||||
|
done
|
||||||
|
echo "🔖 Removed internal artifacts."
|
||||||
|
echo ""
|
||||||
|
echo "🔖 Files to be included in the release:"
|
||||||
|
find "$ARTIFACTS_PATH" -type f
|
||||||
|
|
||||||
|
- name: Log in to Azure
|
||||||
|
uses: bitwarden/gh-actions/azure-login@main
|
||||||
|
with:
|
||||||
|
subscription_id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
tenant_id: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
client_id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
|
|
||||||
|
- name: Get Azure Key Vault secrets
|
||||||
|
id: get-kv-secrets
|
||||||
|
uses: bitwarden/gh-actions/get-keyvault-secrets@main
|
||||||
|
with:
|
||||||
|
keyvault: gh-android
|
||||||
|
secrets: "JIRA-API-EMAIL,JIRA-API-TOKEN"
|
||||||
|
|
||||||
|
- name: Log out from Azure
|
||||||
|
uses: bitwarden/gh-actions/azure-logout@main
|
||||||
|
|
||||||
- name: Get product release notes
|
- name: Get product release notes
|
||||||
id: get_release_notes
|
id: get_release_notes
|
||||||
env:
|
env:
|
||||||
@ -122,11 +180,11 @@ jobs:
|
|||||||
ARTIFACT_RUN_ID: ${{ inputs.artifact-run-id }}
|
ARTIFACT_RUN_ID: ${{ inputs.artifact-run-id }}
|
||||||
_VERSION_NAME: ${{ steps.get_release_info.outputs.version_name }}
|
_VERSION_NAME: ${{ steps.get_release_info.outputs.version_name }}
|
||||||
_RELEASE_TICKET_ID: ${{ inputs.release-ticket-id }}
|
_RELEASE_TICKET_ID: ${{ inputs.release-ticket-id }}
|
||||||
_JIRA_API_EMAIL: ${{ secrets.JIRA_API_EMAIL }}
|
_JIRA_API_EMAIL: ${{ steps.get-kv-secrets.outputs.JIRA-API-EMAIL }}
|
||||||
_JIRA_API_TOKEN: ${{ secrets.JIRA_API_TOKEN }}
|
_JIRA_API_TOKEN: ${{ steps.get-kv-secrets.outputs.JIRA-API-TOKEN }}
|
||||||
run: |
|
run: |
|
||||||
echo "Getting product release notes"
|
echo "Getting product release notes"
|
||||||
product_release_notes=$(python3 .github/scripts/jira-get-release-notes/jira_release_notes.py $_RELEASE_TICKET_ID $_JIRA_API_EMAIL $_JIRA_API_TOKEN)
|
product_release_notes=$(python3 .github/scripts/jira-get-release-notes/jira_release_notes.py "$_RELEASE_TICKET_ID" "$_JIRA_API_EMAIL" "$_JIRA_API_TOKEN")
|
||||||
|
|
||||||
if [[ -z "$product_release_notes" || $product_release_notes == "Error checking"* ]]; then
|
if [[ -z "$product_release_notes" || $product_release_notes == "Error checking"* ]]; then
|
||||||
echo "::warning::Failed to fetch release notes from Jira. Output: $product_release_notes"
|
echo "::warning::Failed to fetch release notes from Jira. Output: $product_release_notes"
|
||||||
@ -149,23 +207,28 @@ jobs:
|
|||||||
_TAG_NAME: ${{ steps.get_release_info.outputs.tag_name }}
|
_TAG_NAME: ${{ steps.get_release_info.outputs.tag_name }}
|
||||||
_LAST_RELEASE_TAG: ${{ steps.get_release_info.outputs.last_release_tag }}
|
_LAST_RELEASE_TAG: ${{ steps.get_release_info.outputs.last_release_tag }}
|
||||||
run: |
|
run: |
|
||||||
|
is_latest_release=false
|
||||||
|
if [[ "$_APP_NAME" == "Password Manager" ]]; then
|
||||||
|
is_latest_release=true
|
||||||
|
fi
|
||||||
|
|
||||||
echo "⌛️ Creating release for $_APP_NAME $_VERSION_NAME ($_VERSION_NUMBER) on $_TARGET_COMMIT"
|
echo "⌛️ Creating release for $_APP_NAME $_VERSION_NAME ($_VERSION_NUMBER) on $_TARGET_COMMIT"
|
||||||
release_url=$(gh release create "$_TAG_NAME" \
|
release_url=$(gh release create "$_TAG_NAME" \
|
||||||
--title "$_APP_NAME $_VERSION_NAME ($_VERSION_NUMBER)" \
|
--title "$_APP_NAME $_VERSION_NAME ($_VERSION_NUMBER)" \
|
||||||
--target "$_TARGET_COMMIT" \
|
--target "$_TARGET_COMMIT" \
|
||||||
--generate-notes \
|
--generate-notes \
|
||||||
--notes-start-tag "$_LAST_RELEASE_TAG" \
|
--notes-start-tag "$_LAST_RELEASE_TAG" \
|
||||||
|
--latest=$is_latest_release \
|
||||||
--draft \
|
--draft \
|
||||||
$ARTIFACTS_PATH/*/*)
|
"$ARTIFACTS_PATH/*/*")
|
||||||
|
|
||||||
|
# Extract release tag from URL
|
||||||
|
release_id_from_url=$(echo "$release_url" | sed 's/.*\/tag\///')
|
||||||
|
echo "release_id_from_url=$release_id_from_url" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "url=$release_url" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
echo "✅ Release created: $release_url"
|
echo "✅ Release created: $release_url"
|
||||||
|
echo "🔖 Release ID from URL: $release_id_from_url"
|
||||||
# Get release info for outputs
|
|
||||||
release_data=$(gh release view "$_TAG_NAME" --json id)
|
|
||||||
release_id=$(echo "$release_data" | jq -r .id)
|
|
||||||
|
|
||||||
echo "id=$release_id" >> $GITHUB_OUTPUT
|
|
||||||
echo "url=$release_url" >> $GITHUB_OUTPUT
|
|
||||||
|
|
||||||
- name: Update Release Description
|
- name: Update Release Description
|
||||||
id: update_release_description
|
id: update_release_description
|
||||||
@ -173,10 +236,10 @@ jobs:
|
|||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
ARTIFACT_RUN_ID: ${{ inputs.artifact-run-id }}
|
ARTIFACT_RUN_ID: ${{ inputs.artifact-run-id }}
|
||||||
_VERSION_NAME: ${{ steps.get_release_info.outputs.version_name }}
|
_VERSION_NAME: ${{ steps.get_release_info.outputs.version_name }}
|
||||||
_TAG_NAME: ${{ steps.get_release_info.outputs.tag_name }}
|
_RELEASE_ID: ${{ steps.create_release.outputs.release_id_from_url }}
|
||||||
run: |
|
run: |
|
||||||
echo "Getting current release body. Tag: $_TAG_NAME"
|
echo "Getting current release body. Release ID: $_RELEASE_ID"
|
||||||
current_body=$(gh release view "$_TAG_NAME" --json body --jq .body)
|
current_body=$(gh release view "$_RELEASE_ID" --json body --jq .body)
|
||||||
|
|
||||||
product_release_notes=$(cat product_release_notes.txt)
|
product_release_notes=$(cat product_release_notes.txt)
|
||||||
|
|
||||||
@ -187,10 +250,10 @@ jobs:
|
|||||||
${current_body}
|
${current_body}
|
||||||
**Builds Source:** https://github.com/${{ github.repository }}/actions/runs/$ARTIFACT_RUN_ID"
|
**Builds Source:** https://github.com/${{ github.repository }}/actions/runs/$ARTIFACT_RUN_ID"
|
||||||
|
|
||||||
new_release_url=$(gh release edit "$_TAG_NAME" --notes "$updated_body")
|
new_release_url=$(gh release edit "$_RELEASE_ID" --notes "$updated_body")
|
||||||
|
|
||||||
# draft release links change after editing
|
# draft release links change after editing
|
||||||
echo "release_url=$new_release_url" >> $GITHUB_OUTPUT
|
echo "release_url=$new_release_url" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Add Release Summary
|
- name: Add Release Summary
|
||||||
env:
|
env:
|
||||||
@ -201,20 +264,26 @@ jobs:
|
|||||||
_RELEASE_BRANCH: ${{ steps.get_release_branch.outputs.release_branch }}
|
_RELEASE_BRANCH: ${{ steps.get_release_branch.outputs.release_branch }}
|
||||||
_RELEASE_URL: ${{ steps.update_release_description.outputs.release_url }}
|
_RELEASE_URL: ${{ steps.update_release_description.outputs.release_url }}
|
||||||
run: |
|
run: |
|
||||||
echo "# :fish_cake: Release ready at:" >> $GITHUB_STEP_SUMMARY
|
{
|
||||||
echo "$_RELEASE_URL" >> $GITHUB_STEP_SUMMARY
|
echo "# :fish_cake: Release ready at:"
|
||||||
echo "" >> $GITHUB_STEP_SUMMARY
|
echo "$_RELEASE_URL"
|
||||||
|
echo ""
|
||||||
|
} >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|
||||||
if [[ "$_VERSION_NAME" == "0.0.0" || "$_VERSION_NUMBER" == "0" ]]; then
|
if [[ "$_VERSION_NAME" == "0.0.0" || "$_VERSION_NUMBER" == "0" ]]; then
|
||||||
echo "> [!CAUTION]" >> $GITHUB_STEP_SUMMARY
|
{
|
||||||
echo "> Version name or number wasn't previously found and a default value was used. You'll need to manually update the release Title, Tag and Description, specifically, the "Full Changelog" link." >> $GITHUB_STEP_SUMMARY
|
echo "> [!CAUTION]"
|
||||||
echo "" >> $GITHUB_STEP_SUMMARY
|
echo "> Version name or number wasn't previously found and a default value was used. You'll need to manually update the release Title, Tag and Description, specifically, the \"Full Changelog\" link."
|
||||||
|
echo ""
|
||||||
|
} >> "$GITHUB_STEP_SUMMARY"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
echo ":clipboard: Confirm that the defined GitHub Release options are correct:" >> $GITHUB_STEP_SUMMARY
|
{
|
||||||
echo " * :bookmark: New tag name: \`$_RELEASE_TAG\`" >> $GITHUB_STEP_SUMMARY
|
echo ":clipboard: Confirm that the defined GitHub Release options are correct:"
|
||||||
echo " * :palm_tree: Target branch: \`$_RELEASE_BRANCH\`" >> $GITHUB_STEP_SUMMARY
|
echo " * :bookmark: New tag name: \`$_RELEASE_TAG\`"
|
||||||
echo " * :ocean: Previous tag set in the description \"Full Changelog\" link: \`$_LAST_RELEASE_TAG\`" >> $GITHUB_STEP_SUMMARY
|
echo " * :palm_tree: Target branch: \`$_RELEASE_BRANCH\`"
|
||||||
echo " * :white_check_mark: Description has automated release notes and they match the commits in the release branch" >> $GITHUB_STEP_SUMMARY
|
echo " * :ocean: Previous tag set in the description \"Full Changelog\" link: \`$_LAST_RELEASE_TAG\`"
|
||||||
echo "> [!NOTE]" >> $GITHUB_STEP_SUMMARY
|
echo " * :white_check_mark: Description has automated release notes and they match the commits in the release branch"
|
||||||
echo "> Commits directly pushed to branches without a Pull Request won't appear in the automated release notes." >> $GITHUB_STEP_SUMMARY
|
echo "> [!NOTE]"
|
||||||
|
echo "> Commits directly pushed to branches without a Pull Request won't appear in the automated release notes."
|
||||||
|
} >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|||||||
23
.github/workflows/publish-github-release-bwa.yml
vendored
Normal file
23
.github/workflows/publish-github-release-bwa.yml
vendored
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
name: Publish Authenticator GitHub Release as newest
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
schedule:
|
||||||
|
- cron: '0 * * * 1-5' # Every hour on the hour on weekdays
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
id-token: write
|
||||||
|
actions: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish-release-authenticator:
|
||||||
|
name: Publish Authenticator Release
|
||||||
|
uses: bitwarden/gh-actions/.github/workflows/_publish-mobile-github-release.yml@main
|
||||||
|
with:
|
||||||
|
release_name: "Authenticator"
|
||||||
|
workflow_name: "publish-github-release-bwa.yml"
|
||||||
|
credentials_filename: "authenticator_play_store-creds.json"
|
||||||
|
project_type: android
|
||||||
|
check_release_command: >
|
||||||
|
bundle exec fastlane getLatestPlayStoreVersion package_name:com.bitwarden.authenticator track:production
|
||||||
|
secrets: inherit
|
||||||
24
.github/workflows/publish-github-release-bwpm.yml
vendored
Normal file
24
.github/workflows/publish-github-release-bwpm.yml
vendored
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
name: Publish Password Manager GitHub Release as newest
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
schedule:
|
||||||
|
- cron: '0 * * * 1-5' # Every hour on the hour on weekdays
|
||||||
|
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
id-token: write
|
||||||
|
actions: write
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
publish-release-password-manager:
|
||||||
|
name: Publish Password Manager Release
|
||||||
|
uses: bitwarden/gh-actions/.github/workflows/_publish-mobile-github-release.yml@main
|
||||||
|
with:
|
||||||
|
release_name: "Password Manager"
|
||||||
|
workflow_name: "publish-github-release-bwpm.yml"
|
||||||
|
credentials_filename: "play_creds.json"
|
||||||
|
project_type: android
|
||||||
|
check_release_command: >
|
||||||
|
bundle exec fastlane getLatestPlayStoreVersion package_name:com.x8bit.bitwarden track:production
|
||||||
|
secrets: inherit
|
||||||
14
.github/workflows/publish-github-release.yml
vendored
14
.github/workflows/publish-github-release.yml
vendored
@ -1,14 +0,0 @@
|
|||||||
name: Publish GitHub Release as newest
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
|
|
||||||
permissions: {}
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
stub:
|
|
||||||
runs-on: ubuntu-24.04
|
|
||||||
name: Stub
|
|
||||||
steps:
|
|
||||||
- name: Stub
|
|
||||||
run: echo "This is a stub job to trigger the workflow."
|
|
||||||
185
.github/workflows/publish-store.yml
vendored
185
.github/workflows/publish-store.yml
vendored
@ -1,16 +1,181 @@
|
|||||||
|
name: Publish to Google Play
|
||||||
name: Publish
|
run-name: >
|
||||||
|
${{ inputs.dry-run && ' (Dry Run)' || '' }}Promoting ${{ inputs.product }} ${{ inputs.version-code }} from ${{ inputs.track-from }} to ${{ inputs.track-target }}
|
||||||
on:
|
on:
|
||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
product:
|
||||||
|
description: "Which app is being released."
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
- Password Manager
|
||||||
|
- Authenticator
|
||||||
|
version-name:
|
||||||
|
description: "Version name to promote to production ex 2025.1.1"
|
||||||
|
type: string
|
||||||
|
version-code:
|
||||||
|
description: "Build number to promote to production."
|
||||||
|
required: true
|
||||||
|
type: string
|
||||||
|
rollout-percentage:
|
||||||
|
description: "Percentage of users who will receive this version update."
|
||||||
|
required: true
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
- 10%
|
||||||
|
- 30%
|
||||||
|
- 50%
|
||||||
|
- 100%
|
||||||
|
default: 10%
|
||||||
|
release-notes:
|
||||||
|
description: "Change notes to be included with this release."
|
||||||
|
type: string
|
||||||
|
default: "Bug fixes."
|
||||||
|
required: true
|
||||||
|
track-from:
|
||||||
|
description: "Track to promote from."
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
- internal
|
||||||
|
- Fastlane Automation Source
|
||||||
|
required: true
|
||||||
|
default: "internal"
|
||||||
|
track-target:
|
||||||
|
description: "Track to promote to."
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
- production
|
||||||
|
- Fastlane Automation Target
|
||||||
|
required: true
|
||||||
|
dry-run:
|
||||||
|
description: "Dry-Run, Run the workflow without publishing to the store"
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
GITHUB_ACTION_RUN_URL: "https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}"
|
||||||
|
|
||||||
permissions: {}
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: read
|
||||||
|
id-token: write
|
||||||
|
actions: write
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
publish:
|
promote:
|
||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
name: Promote build to Production in Play Store
|
name: Promote build to Production in Play Store
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: TEST STEP
|
- name: Log inputs to job summary
|
||||||
run: exit 0
|
uses: bitwarden/android/.github/actions/log-inputs@main
|
||||||
|
with:
|
||||||
|
inputs: "${{ toJson(inputs) }}"
|
||||||
|
|
||||||
|
- name: Check out repo
|
||||||
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
- name: Configure Ruby
|
||||||
|
uses: ruby/setup-ruby@44511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0
|
||||||
|
with:
|
||||||
|
bundler-cache: true
|
||||||
|
|
||||||
|
- name: Install Fastlane
|
||||||
|
run: |
|
||||||
|
bundle config path vendor/bundle
|
||||||
|
bundle install --jobs 4 --retry 3
|
||||||
|
|
||||||
|
- name: Log in to Azure
|
||||||
|
uses: bitwarden/gh-actions/azure-login@main
|
||||||
|
with:
|
||||||
|
subscription_id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
tenant_id: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
client_id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
|
|
||||||
|
- name: Get Azure Key Vault secrets
|
||||||
|
id: get-kv-secrets
|
||||||
|
uses: bitwarden/gh-actions/get-keyvault-secrets@main
|
||||||
|
with:
|
||||||
|
keyvault: gh-android
|
||||||
|
secrets: "PLAY-BETA-KEYSTORE-PASSWORD,PLAY-BETA-KEY-PASSWORD"
|
||||||
|
|
||||||
|
- name: Retrieve secrets
|
||||||
|
env:
|
||||||
|
ACCOUNT_NAME: bitwardenci
|
||||||
|
CONTAINER_NAME: mobile
|
||||||
|
run: |
|
||||||
|
mkdir -p ${{ github.workspace }}/secrets
|
||||||
|
mkdir -p ${{ github.workspace }}/app/src/standardRelease
|
||||||
|
|
||||||
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
|
--name play_creds.json --file ${{ github.workspace }}/secrets/play_creds.json --output none
|
||||||
|
|
||||||
|
az storage blob download --account-name "$ACCOUNT_NAME" --container-name "$CONTAINER_NAME" \
|
||||||
|
--name authenticator_play_store-creds.json --file ${{ github.workspace }}/secrets/authenticator_play_store-creds.json --output none
|
||||||
|
|
||||||
|
- name: Log out from Azure
|
||||||
|
uses: bitwarden/gh-actions/azure-logout@main
|
||||||
|
|
||||||
|
- name: Format Release Notes
|
||||||
|
env:
|
||||||
|
RELEASE_NOTES: ${{ inputs.release-notes }}
|
||||||
|
run: |
|
||||||
|
FORMATTED_MESSAGE="$(echo "$RELEASE_NOTES" | sed 's/ /\n/g')"
|
||||||
|
{
|
||||||
|
echo "RELEASE_NOTES<<EOF"
|
||||||
|
printf '%s\n' "$FORMATTED_MESSAGE"
|
||||||
|
echo "EOF"
|
||||||
|
} >> "$GITHUB_ENV"
|
||||||
|
|
||||||
|
- name: Promote Play Store version to production
|
||||||
|
env:
|
||||||
|
PLAY_KEYSTORE_PASSWORD: ${{ steps.get-kv-secrets.outputs.PLAY-BETA-KEYSTORE-PASSWORD }}
|
||||||
|
PLAY_KEY_PASSWORD: ${{ steps.get-kv-secrets.outputs.PLAY-BETA-KEY-PASSWORD }}
|
||||||
|
VERSION_CODE_INPUT: ${{ inputs.version-code }}
|
||||||
|
VERSION_NAME: ${{inputs.version-name}}
|
||||||
|
ROLLOUT_PERCENTAGE: ${{ inputs.rollout-percentage }}
|
||||||
|
PRODUCT: ${{ inputs.product }}
|
||||||
|
TRACK_FROM: ${{ inputs.track-from }}
|
||||||
|
TRACK_TARGET: ${{ inputs.track-target }}
|
||||||
|
run: |
|
||||||
|
if [ "$PRODUCT" = "Password Manager" ]; then
|
||||||
|
PACKAGE_NAME="com.x8bit.bitwarden"
|
||||||
|
elif [ "$PRODUCT" = "Authenticator" ]; then
|
||||||
|
PACKAGE_NAME="com.bitwarden.authenticator"
|
||||||
|
else
|
||||||
|
echo "Unsupported product: $PRODUCT"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
VERSION_CODE=$(echo "${VERSION_CODE_INPUT}" | tr -d ',')
|
||||||
|
|
||||||
|
decimal=$(echo "scale=2; ${ROLLOUT_PERCENTAGE/\%/} / 100" | bc)
|
||||||
|
|
||||||
|
bundle exec fastlane updateReleaseNotes \
|
||||||
|
releaseNotes:"$RELEASE_NOTES" \
|
||||||
|
versionCode:"$VERSION_CODE" \
|
||||||
|
packageName:"$PACKAGE_NAME"
|
||||||
|
|
||||||
|
bundle exec fastlane promoteToProduction \
|
||||||
|
versionCode:"$VERSION_CODE" \
|
||||||
|
versionName:"$VERSION_NAME" \
|
||||||
|
rolloutPercentage:"$decimal" \
|
||||||
|
packageName:"$PACKAGE_NAME" \
|
||||||
|
releaseNotes:"$RELEASE_NOTES" \
|
||||||
|
track:"$TRACK_FROM" \
|
||||||
|
trackPromoteTo:"$TRACK_TARGET"
|
||||||
|
|
||||||
|
- name: Enable Publish Github Release Workflow
|
||||||
|
env:
|
||||||
|
PRODUCT: ${{ inputs.product }}
|
||||||
|
run: |
|
||||||
|
if ${{ inputs.dry-run }} ; then
|
||||||
|
gh workflow view publish-github-release-bwpm.yml
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
if [ "$PRODUCT" = "Password Manager" ]; then
|
||||||
|
gh workflow enable publish-github-release-bwpm.yml
|
||||||
|
elif [ "$PRODUCT" = "Authenticator" ]; then
|
||||||
|
gh workflow enable publish-github-release-bwa.yml
|
||||||
|
fi
|
||||||
|
|||||||
68
.github/workflows/release-branch.yml
vendored
68
.github/workflows/release-branch.yml
vendored
@ -4,12 +4,14 @@ on:
|
|||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
inputs:
|
inputs:
|
||||||
release_type:
|
release_type:
|
||||||
description: 'Release Type'
|
description: "Release Type"
|
||||||
required: true
|
required: true
|
||||||
type: choice
|
type: choice
|
||||||
options:
|
options:
|
||||||
- RC
|
- RC
|
||||||
- Hotfix
|
- Hotfix Password Manager
|
||||||
|
- Hotfix Authenticator
|
||||||
|
- Test
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
create-release-branch:
|
create-release-branch:
|
||||||
@ -17,42 +19,68 @@ jobs:
|
|||||||
runs-on: ubuntu-24.04
|
runs-on: ubuntu-24.04
|
||||||
permissions:
|
permissions:
|
||||||
contents: write
|
contents: write
|
||||||
|
actions: write
|
||||||
steps:
|
steps:
|
||||||
- name: Check out repository
|
- name: Check out repository
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
with:
|
with:
|
||||||
fetch-depth: 0
|
fetch-depth: 0
|
||||||
|
persist-credentials: true
|
||||||
|
|
||||||
- name: Create RC Branch
|
- name: Create RC or Test Branch
|
||||||
if: inputs.release_type == 'RC'
|
id: rc_branch
|
||||||
|
if: inputs.release_type == 'RC' || inputs.release_type == 'Test'
|
||||||
env:
|
env:
|
||||||
RC_PREFIX_DATE: "true" # replace with input if needed
|
_TEST_MODE: ${{ inputs.release_type == 'Test' }}
|
||||||
|
_RELEASE_TYPE: ${{ inputs.release_type }}
|
||||||
run: |
|
run: |
|
||||||
if [ "$RC_PREFIX_DATE" = "true" ]; then
|
current_date=$(date +'%Y.%-m')
|
||||||
current_date=$(date +'%Y.%m')
|
branch_name="${current_date}-rc${{ github.run_number }}"
|
||||||
branch_name="release/${current_date}-rc${{ github.run_number }}"
|
|
||||||
else
|
if [ "$_TEST_MODE" = "true" ]; then
|
||||||
branch_name="release/rc${{ github.run_number }}"
|
branch_name="WORKFLOW-TEST-${branch_name}"
|
||||||
fi
|
fi
|
||||||
|
branch_name="release/${branch_name}"
|
||||||
|
|
||||||
git switch main
|
git switch main
|
||||||
git switch -c $branch_name
|
git switch -c "$branch_name"
|
||||||
git push origin $branch_name
|
git push origin "$branch_name"
|
||||||
echo "# :cherry_blossom: RC branch: ${branch_name}" >> $GITHUB_STEP_SUMMARY
|
echo "# :cherry_blossom: ${_RELEASE_TYPE} branch: ${branch_name}" >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
echo "branch_name=$branch_name" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
- name: Create Hotfix Branch
|
- name: Create Hotfix Branch
|
||||||
if: inputs.release_type == 'Hotfix'
|
id: hotfix_branch
|
||||||
|
if: startsWith(inputs.release_type, 'Hotfix')
|
||||||
|
env:
|
||||||
|
_RELEASE_TYPE: ${{ inputs.release_type }}
|
||||||
run: |
|
run: |
|
||||||
latest_tag=$(git tag -l --sort=-creatordate | head -n 1)
|
app_codename="bwpm"
|
||||||
|
if [ "$_RELEASE_TYPE" == "Hotfix Authenticator" ]; then
|
||||||
|
app_codename="bwa"
|
||||||
|
fi
|
||||||
|
echo "🌿 app codename: $app_codename"
|
||||||
|
|
||||||
|
latest_tag=$(git tag -l --sort=-creatordate | grep "$app_codename" | head -n 1)
|
||||||
if [ -z "$latest_tag" ]; then
|
if [ -z "$latest_tag" ]; then
|
||||||
echo "::error::No tags found in the repository"
|
echo "::error::No tags found in the repository"
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
branch_name="release/hotfix-${latest_tag}"
|
branch_name="release/hotfix-${latest_tag}"
|
||||||
echo "🌿 branch name: $branch_name"
|
echo "🌿 branch name: $branch_name"
|
||||||
|
echo "branch_name=$branch_name" >> "$GITHUB_OUTPUT"
|
||||||
if git show-ref --verify --quiet "refs/remotes/origin/$branch_name"; then
|
if git show-ref --verify --quiet "refs/remotes/origin/$branch_name"; then
|
||||||
echo "# :fire: :warning: Hotfix branch already exists: ${branch_name}" >> $GITHUB_STEP_SUMMARY
|
echo "# :fire: :warning: Hotfix branch already exists: ${branch_name}" >> "$GITHUB_STEP_SUMMARY"
|
||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
git switch -c $branch_name $latest_tag
|
git switch -c "$branch_name" "$latest_tag"
|
||||||
git push origin $branch_name
|
git push origin "$branch_name"
|
||||||
echo "# :fire: Hotfix branch: ${branch_name}" >> $GITHUB_STEP_SUMMARY
|
echo "# :fire: Hotfix branch: ${branch_name}" >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|
||||||
|
- name: Trigger CI Workflows
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
_BRANCH_NAME: ${{ steps.rc_branch.outputs.branch_name || steps.hotfix_branch.outputs.branch_name }}
|
||||||
|
run: |
|
||||||
|
echo "🌿 branch name: $_BRANCH_NAME"
|
||||||
|
gh workflow run build.yml --ref "$_BRANCH_NAME" -f distribute-to-firebase=true -f publish-to-play-store=true
|
||||||
|
gh workflow run build-authenticator.yml --ref "$_BRANCH_NAME" -f distribute-to-firebase=true -f publish-to-play-store=true
|
||||||
|
|||||||
28
.github/workflows/respond.yml
vendored
Normal file
28
.github/workflows/respond.yml
vendored
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
name: Respond
|
||||||
|
|
||||||
|
on:
|
||||||
|
issue_comment:
|
||||||
|
types: [created]
|
||||||
|
pull_request_review_comment:
|
||||||
|
types: [created]
|
||||||
|
issues:
|
||||||
|
types: [opened, assigned]
|
||||||
|
pull_request_review:
|
||||||
|
types: [submitted]
|
||||||
|
|
||||||
|
permissions: {}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
respond:
|
||||||
|
name: Respond
|
||||||
|
uses: bitwarden/gh-actions/.github/workflows/_respond.yml@main
|
||||||
|
secrets:
|
||||||
|
AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
|
permissions:
|
||||||
|
actions: read
|
||||||
|
contents: write
|
||||||
|
id-token: write
|
||||||
|
issues: write
|
||||||
|
pull-requests: write
|
||||||
21
.github/workflows/review-code.yml
vendored
Normal file
21
.github/workflows/review-code.yml
vendored
Normal file
@ -0,0 +1,21 @@
|
|||||||
|
name: Code Review
|
||||||
|
|
||||||
|
on:
|
||||||
|
pull_request:
|
||||||
|
types: [opened, synchronize, reopened, ready_for_review]
|
||||||
|
|
||||||
|
permissions: {}
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
review:
|
||||||
|
name: Review
|
||||||
|
uses: bitwarden/gh-actions/.github/workflows/_review-code.yml@main
|
||||||
|
secrets:
|
||||||
|
AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
|
permissions:
|
||||||
|
actions: read
|
||||||
|
contents: read
|
||||||
|
id-token: write
|
||||||
|
pull-requests: write
|
||||||
61
.github/workflows/scan-ci.yml
vendored
61
.github/workflows/scan-ci.yml
vendored
@ -6,55 +6,30 @@ on:
|
|||||||
branches:
|
branches:
|
||||||
- "main"
|
- "main"
|
||||||
|
|
||||||
|
permissions: {}
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
sast:
|
sast:
|
||||||
name: SAST scan
|
name: Checkmarx
|
||||||
runs-on: ubuntu-24.04
|
uses: bitwarden/gh-actions/.github/workflows/_checkmarx.yml@main
|
||||||
|
secrets:
|
||||||
|
AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
|
pull-requests: write
|
||||||
security-events: write
|
security-events: write
|
||||||
|
id-token: write
|
||||||
steps:
|
|
||||||
- name: Check out repo
|
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Scan with Checkmarx
|
|
||||||
uses: checkmarx/ast-github-action@ef93013c95adc60160bc22060875e90800d3ecfc # 2.3.19
|
|
||||||
with:
|
|
||||||
project_name: ${{ github.repository }}
|
|
||||||
cx_tenant: ${{ secrets.CHECKMARX_TENANT }}
|
|
||||||
base_uri: https://ast.checkmarx.net/
|
|
||||||
cx_client_id: ${{ secrets.CHECKMARX_CLIENT_ID }}
|
|
||||||
cx_client_secret: ${{ secrets.CHECKMARX_SECRET }}
|
|
||||||
additional_params: |
|
|
||||||
--report-format sarif \
|
|
||||||
--filter "state=TO_VERIFY;PROPOSED_NOT_EXPLOITABLE;CONFIRMED;URGENT" \
|
|
||||||
--output-path .
|
|
||||||
|
|
||||||
- name: Upload Checkmarx results to GitHub
|
|
||||||
uses: github/codeql-action/upload-sarif@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15
|
|
||||||
with:
|
|
||||||
sarif_file: cx_result.sarif
|
|
||||||
|
|
||||||
quality:
|
quality:
|
||||||
name: Quality scan
|
name: Sonar
|
||||||
runs-on: ubuntu-24.04
|
uses: bitwarden/gh-actions/.github/workflows/_sonar.yml@main
|
||||||
|
secrets:
|
||||||
|
AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
|
pull-requests: write
|
||||||
steps:
|
id-token: write
|
||||||
- name: Check out repo
|
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
|
|
||||||
- name: Scan with SonarCloud
|
|
||||||
uses: sonarsource/sonarqube-scan-action@aa494459d7c39c106cc77b166de8b4250a32bb97 # v5.1.0
|
|
||||||
env:
|
|
||||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
|
||||||
with:
|
|
||||||
args: >
|
|
||||||
-Dsonar.organization=${{ github.repository_owner }}
|
|
||||||
-Dsonar.projectKey=${{ github.repository_owner }}_${{ github.event.repository.name }}
|
|
||||||
|
|||||||
65
.github/workflows/scan.yml
vendored
65
.github/workflows/scan.yml
vendored
@ -6,7 +6,7 @@ on:
|
|||||||
types: [opened, synchronize, reopened]
|
types: [opened, synchronize, reopened]
|
||||||
branches-ignore:
|
branches-ignore:
|
||||||
- main
|
- main
|
||||||
pull_request_target:
|
pull_request_target: # zizmor: ignore[dangerous-triggers]
|
||||||
types: [opened, synchronize, reopened]
|
types: [opened, synchronize, reopened]
|
||||||
branches:
|
branches:
|
||||||
- main
|
- main
|
||||||
@ -21,63 +21,28 @@ jobs:
|
|||||||
contents: read
|
contents: read
|
||||||
|
|
||||||
sast:
|
sast:
|
||||||
name: SAST scan
|
name: Checkmarx
|
||||||
runs-on: ubuntu-24.04
|
uses: bitwarden/gh-actions/.github/workflows/_checkmarx.yml@main
|
||||||
needs: check-run
|
needs: check-run
|
||||||
|
secrets:
|
||||||
|
AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
security-events: write
|
security-events: write
|
||||||
|
id-token: write
|
||||||
steps:
|
|
||||||
- name: Check out repo
|
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
|
||||||
with:
|
|
||||||
ref: ${{ github.event.pull_request.head.sha }}
|
|
||||||
|
|
||||||
- name: Scan with Checkmarx
|
|
||||||
uses: checkmarx/ast-github-action@ef93013c95adc60160bc22060875e90800d3ecfc # 2.3.19
|
|
||||||
env:
|
|
||||||
INCREMENTAL: "${{ contains(github.event_name, 'pull_request') && '--sast-incremental' || '' }}"
|
|
||||||
with:
|
|
||||||
project_name: ${{ github.repository }}
|
|
||||||
cx_tenant: ${{ secrets.CHECKMARX_TENANT }}
|
|
||||||
base_uri: https://ast.checkmarx.net/
|
|
||||||
cx_client_id: ${{ secrets.CHECKMARX_CLIENT_ID }}
|
|
||||||
cx_client_secret: ${{ secrets.CHECKMARX_SECRET }}
|
|
||||||
additional_params: |
|
|
||||||
--report-format sarif \
|
|
||||||
--filter "state=TO_VERIFY;PROPOSED_NOT_EXPLOITABLE;CONFIRMED;URGENT" \
|
|
||||||
--output-path . ${{ env.INCREMENTAL }}
|
|
||||||
|
|
||||||
- name: Upload Checkmarx results to GitHub
|
|
||||||
uses: github/codeql-action/upload-sarif@45775bd8235c68ba998cffa5171334d58593da47 # v3.28.15
|
|
||||||
with:
|
|
||||||
sarif_file: cx_result.sarif
|
|
||||||
sha: ${{ contains(github.event_name, 'pull_request') && github.event.pull_request.head.sha || github.sha }}
|
|
||||||
ref: ${{ contains(github.event_name, 'pull_request') && format('refs/pull/{0}/head', github.event.pull_request.number) || github.ref }}
|
|
||||||
|
|
||||||
quality:
|
quality:
|
||||||
name: Quality scan
|
name: Sonar
|
||||||
runs-on: ubuntu-24.04
|
uses: bitwarden/gh-actions/.github/workflows/_sonar.yml@main
|
||||||
needs: check-run
|
needs: check-run
|
||||||
|
secrets:
|
||||||
|
AZURE_SUBSCRIPTION_ID: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
permissions:
|
permissions:
|
||||||
contents: read
|
contents: read
|
||||||
pull-requests: write
|
pull-requests: write
|
||||||
|
id-token: write
|
||||||
steps:
|
|
||||||
- name: Check out repo
|
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
|
||||||
with:
|
|
||||||
fetch-depth: 0
|
|
||||||
ref: ${{ github.event.pull_request.head.sha }}
|
|
||||||
|
|
||||||
- name: Scan with SonarCloud
|
|
||||||
uses: sonarsource/sonarqube-scan-action@aa494459d7c39c106cc77b166de8b4250a32bb97 # v5.1.0
|
|
||||||
env:
|
|
||||||
SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }}
|
|
||||||
with:
|
|
||||||
args: >
|
|
||||||
-Dsonar.organization=${{ github.repository_owner }}
|
|
||||||
-Dsonar.projectKey=${{ github.repository_owner }}_${{ github.event.repository.name }}
|
|
||||||
-Dsonar.pullrequest.key=${{ github.event.pull_request.number }}
|
|
||||||
|
|||||||
80
.github/workflows/sdlc-label-pr.yml
vendored
Normal file
80
.github/workflows/sdlc-label-pr.yml
vendored
Normal file
@ -0,0 +1,80 @@
|
|||||||
|
name: SDLC / Label PR by Files
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
pr-number:
|
||||||
|
description: "Pull Request Number"
|
||||||
|
required: true
|
||||||
|
type: number
|
||||||
|
mode:
|
||||||
|
description: "Labeling Mode"
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
- add
|
||||||
|
- replace
|
||||||
|
default: add
|
||||||
|
dry-run:
|
||||||
|
description: "Dry Run - Don't apply labels"
|
||||||
|
type: boolean
|
||||||
|
default: false
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
label-pr:
|
||||||
|
name: Label PR by Changed Files
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
permissions:
|
||||||
|
pull-requests: write # required to update labels
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out repository
|
||||||
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
|
- name: Determine label mode for Pull Request
|
||||||
|
id: label-mode
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
_PR_NUMBER: ${{ inputs.pr-number }}
|
||||||
|
_PR_USER: ${{ github.event.pull_request.user.login }}
|
||||||
|
_IS_FORK: ${{ github.event.pull_request.head.repo.fork }}
|
||||||
|
run: |
|
||||||
|
# Support workflow_dispatch testing by retrieving PR data
|
||||||
|
if [ -z "$_PR_USER" ]; then
|
||||||
|
echo "👀 PR User is empty, retrieving PR data for PR #$_PR_NUMBER..."
|
||||||
|
PR_DATA=$(gh pr view "$_PR_NUMBER" --json author,isCrossRepository)
|
||||||
|
_PR_USER=$(echo "$PR_DATA" | jq -r '.author.login')
|
||||||
|
_IS_FORK=$(echo "$PR_DATA" | jq -r '.isCrossRepository')
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "📋 PR User: $_PR_USER"
|
||||||
|
echo "📋 Is Fork: $_IS_FORK"
|
||||||
|
|
||||||
|
# Handle PRs with labels set by other automations by adding instead of replacing
|
||||||
|
if [ "$_IS_FORK" = "true" ]; then
|
||||||
|
echo "➡️ Fork PR ($_PR_USER). Label mode: --add"
|
||||||
|
echo "label_mode=--add" >> "$GITHUB_OUTPUT"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [ "$_PR_USER" = "renovate[bot]" ] || [ "$_PR_USER" = "bw-ghapp[bot]" ]; then
|
||||||
|
echo "➡️ Bot PR ($_PR_USER). Label mode: --add"
|
||||||
|
echo "label_mode=--add" >> "$GITHUB_OUTPUT"
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "➡️ Normal PR. Label mode: --replace"
|
||||||
|
echo "label_mode=--replace" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Label PR based on changed files
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
_PR_NUMBER: ${{ inputs.pr-number || github.event.pull_request.number }}
|
||||||
|
_LABEL_MODE: ${{ inputs.mode && format('--{0}', inputs.mode) || steps.label-mode.outputs.label_mode }}
|
||||||
|
_DRY_RUN: ${{ inputs.dry-run == true && '--dry-run' || '' }}
|
||||||
|
run: |
|
||||||
|
echo "🔍 Labeling PR #$_PR_NUMBER with mode: $_LABEL_MODE and dry-run: $_DRY_RUN"
|
||||||
|
python3 .github/scripts/label-pr.py "$_PR_NUMBER" "$_LABEL_MODE" "$_DRY_RUN"
|
||||||
|
|
||||||
230
.github/workflows/sdlc-sdk-update.yml
vendored
Normal file
230
.github/workflows/sdlc-sdk-update.yml
vendored
Normal file
@ -0,0 +1,230 @@
|
|||||||
|
name: SDLC / SDK Update
|
||||||
|
run-name: "SDK ${{inputs.run-mode == 'Update' && format('Update - {0}', inputs.sdk-version) || format('Test #{0} - {1}', inputs.pr-id, inputs.sdk-version)}}"
|
||||||
|
|
||||||
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
run-mode:
|
||||||
|
description: "Run Mode"
|
||||||
|
type: choice
|
||||||
|
options:
|
||||||
|
- Test # used for testing sdk-internal repo PRs
|
||||||
|
- Update # opens a PR in this repo updating the SDK
|
||||||
|
default: Test
|
||||||
|
sdk-package:
|
||||||
|
description: "SDK Package ID"
|
||||||
|
required: true
|
||||||
|
default: "com.bitwarden:sdk-android.dev"
|
||||||
|
sdk-version:
|
||||||
|
description: "SDK Version"
|
||||||
|
required: true
|
||||||
|
default: "1.0.0-2686-km-update-kdf-sdk"
|
||||||
|
pr-id:
|
||||||
|
description: "Pull Request ID"
|
||||||
|
|
||||||
|
env:
|
||||||
|
_BOT_NAME: "bw-ghapp[bot]"
|
||||||
|
_BOT_EMAIL: "178206702+bw-ghapp[bot]@users.noreply.github.com"
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
update:
|
||||||
|
name: Update and PR
|
||||||
|
if: ${{ inputs.run-mode == 'Update' }}
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Log in to Azure
|
||||||
|
uses: bitwarden/gh-actions/azure-login@main
|
||||||
|
with:
|
||||||
|
subscription_id: ${{ secrets.AZURE_SUBSCRIPTION_ID }}
|
||||||
|
tenant_id: ${{ secrets.AZURE_TENANT_ID }}
|
||||||
|
client_id: ${{ secrets.AZURE_CLIENT_ID }}
|
||||||
|
|
||||||
|
- name: Get Azure Key Vault secrets
|
||||||
|
id: get-kv-secrets
|
||||||
|
uses: bitwarden/gh-actions/get-keyvault-secrets@main
|
||||||
|
with:
|
||||||
|
keyvault: gh-org-bitwarden
|
||||||
|
secrets: "BW-GHAPP-ID,BW-GHAPP-KEY"
|
||||||
|
|
||||||
|
- name: Log out from Azure
|
||||||
|
uses: bitwarden/gh-actions/azure-logout@main
|
||||||
|
|
||||||
|
- name: Generate GH App token
|
||||||
|
uses: actions/create-github-app-token@a8d616148505b5069dccd32f177bb87d7f39123b # v2.1.1
|
||||||
|
id: app-token
|
||||||
|
with:
|
||||||
|
app-id: ${{ steps.get-kv-secrets.outputs.BW-GHAPP-ID }}
|
||||||
|
private-key: ${{ steps.get-kv-secrets.outputs.BW-GHAPP-KEY }}
|
||||||
|
permission-pull-requests: write
|
||||||
|
permission-actions: read
|
||||||
|
permission-contents: write
|
||||||
|
|
||||||
|
- name: Check out repo
|
||||||
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
with:
|
||||||
|
token: ${{ steps.app-token.outputs.token }}
|
||||||
|
fetch-depth: 0
|
||||||
|
persist-credentials: true
|
||||||
|
|
||||||
|
- name: Log inputs to job summary
|
||||||
|
uses: ./.github/actions/log-inputs
|
||||||
|
with:
|
||||||
|
inputs: ${{ toJson(inputs) }}
|
||||||
|
|
||||||
|
- name: Switch to branch
|
||||||
|
id: switch-branch
|
||||||
|
run: |
|
||||||
|
BRANCH_NAME="sdlc/sdk-update"
|
||||||
|
echo "branch_name=$BRANCH_NAME" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
if git switch "$BRANCH_NAME"; then
|
||||||
|
echo "✅ Switched to existing branch: $BRANCH_NAME"
|
||||||
|
echo "updating_existing_branch=true" >> "$GITHUB_OUTPUT"
|
||||||
|
else
|
||||||
|
echo "📝 Creating new branch: $BRANCH_NAME"
|
||||||
|
git switch -c "$BRANCH_NAME"
|
||||||
|
echo "updating_existing_branch=false" >> "$GITHUB_OUTPUT"
|
||||||
|
fi
|
||||||
|
|
||||||
|
- name: Prevent updating the branch when the last committer isn't the bot
|
||||||
|
if: ${{ steps.switch-branch.outputs.updating_existing_branch == 'true' }}
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||||
|
_BRANCH_NAME: ${{ steps.switch-branch.outputs.branch_name }}
|
||||||
|
run: |
|
||||||
|
LATEST_COMMIT_AUTHOR=$(git log -1 --format='%ae' "$_BRANCH_NAME")
|
||||||
|
|
||||||
|
echo "Latest commit author in branch ($_BRANCH_NAME): $LATEST_COMMIT_AUTHOR"
|
||||||
|
echo "Expected bot email: $_BOT_EMAIL"
|
||||||
|
|
||||||
|
if [ "$LATEST_COMMIT_AUTHOR" != "$_BOT_EMAIL" ]; then
|
||||||
|
echo "::error::Branch $_BRANCH_NAME has a commit not made by the bot." \
|
||||||
|
"This indicates manual changes have been made to the branch," \
|
||||||
|
"PR has to be merged or closed before running this workflow again."
|
||||||
|
echo "👀 Fetching existing PR..."
|
||||||
|
gh pr list --head "$_BRANCH_NAME" --base main --state open --json number --jq '.[0].number // empty'
|
||||||
|
EXISTING_PR=$(gh pr list --head "$_BRANCH_NAME" --base main --state open --json number --jq '.[0].number // empty')
|
||||||
|
if [ -z "$EXISTING_PR" ]; then
|
||||||
|
echo "::error::Couldn't find an existing PR for branch $_BRANCH_NAME."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
PR_URL="https://github.com/${{ github.repository }}/pull/$EXISTING_PR"
|
||||||
|
echo "## ❌ Merge or close: $PR_URL" >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "✅ Branch tip commit was made by the bot. Safe to proceed."
|
||||||
|
|
||||||
|
# Using main to retrieve the changelog on consecutive updates of the same PR.
|
||||||
|
- name: Get current SDK version from main branch
|
||||||
|
id: get-current-sdk
|
||||||
|
run: |
|
||||||
|
git show origin/main:gradle/libs.versions.toml
|
||||||
|
SDK_VERSION=$(git show origin/main:gradle/libs.versions.toml | grep "bitwardenSdk =" | cut -d'"' -f2)
|
||||||
|
if [ -z "$SDK_VERSION" ]; then
|
||||||
|
echo "::error::Failed to get current SDK version from main branch."
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
GIT_REF=$(echo "$SDK_VERSION" | cut -d'-' -f3-) # handles both commit hashes and branch names
|
||||||
|
echo "Current SDK version (from main): $SDK_VERSION"
|
||||||
|
echo "Current SDK git ref: $GIT_REF"
|
||||||
|
echo "version=$SDK_VERSION" >> "$GITHUB_OUTPUT"
|
||||||
|
echo "git_ref=$GIT_REF" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Update SDK Version
|
||||||
|
env:
|
||||||
|
_SDK_PACKAGE: ${{ inputs.sdk-package }}
|
||||||
|
_SDK_VERSION: ${{ inputs.sdk-version }}
|
||||||
|
run: |
|
||||||
|
./scripts/update-sdk-version.sh "$_SDK_PACKAGE" "$_SDK_VERSION"
|
||||||
|
|
||||||
|
- name: Create branch and commit
|
||||||
|
env:
|
||||||
|
_SDK_PACKAGE: ${{ inputs.sdk-package }}
|
||||||
|
_SDK_VERSION: ${{ inputs.sdk-version }}
|
||||||
|
_BRANCH_NAME: ${{ steps.switch-branch.outputs.branch_name }}
|
||||||
|
run: |
|
||||||
|
echo "👀 Committing SDK version update..."
|
||||||
|
|
||||||
|
git config user.name "$_BOT_NAME"
|
||||||
|
git config user.email "$_BOT_EMAIL"
|
||||||
|
|
||||||
|
git add gradle/libs.versions.toml
|
||||||
|
git commit -m "SDK Update - $_SDK_PACKAGE $_SDK_VERSION"
|
||||||
|
git push origin "$_BRANCH_NAME"
|
||||||
|
|
||||||
|
- name: Create or Update Pull Request
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ steps.app-token.outputs.token }}
|
||||||
|
_BRANCH_NAME: ${{ steps.switch-branch.outputs.branch_name }}
|
||||||
|
_SDK_PACKAGE: ${{ inputs.sdk-package }}
|
||||||
|
_SDK_VERSION: ${{ inputs.sdk-version }}
|
||||||
|
_OLD_SDK_VERSION: ${{ steps.get-current-sdk.outputs.version }}
|
||||||
|
_OLD_SDK_GIT_REF: ${{ steps.get-current-sdk.outputs.git_ref }}
|
||||||
|
run: |
|
||||||
|
NEW_SDK_GIT_REF=$(echo "$_SDK_VERSION" | cut -d'-' -f3-)
|
||||||
|
CHANGELOG=$(./scripts/get-repo-changelog.sh "bitwarden/sdk-internal" "$_OLD_SDK_GIT_REF" "$NEW_SDK_GIT_REF")
|
||||||
|
PR_BODY="Updates the SDK version from \`$_OLD_SDK_VERSION\` to \`$_SDK_PACKAGE $_SDK_VERSION\`
|
||||||
|
|
||||||
|
## What's Changed
|
||||||
|
|
||||||
|
$CHANGELOG"
|
||||||
|
|
||||||
|
EXISTING_PR=$(gh pr list --head "$_BRANCH_NAME" --base main --state open --json number --jq '.[0].number // empty')
|
||||||
|
|
||||||
|
if [ -n "$EXISTING_PR" ]; then
|
||||||
|
echo "🔄 Updating existing PR #$EXISTING_PR..."
|
||||||
|
echo -e "$PR_BODY" | gh pr edit "$EXISTING_PR" \
|
||||||
|
--title "Update SDK to $_SDK_VERSION" \
|
||||||
|
--body-file -
|
||||||
|
PR_URL="https://github.com/${{ github.repository }}/pull/$EXISTING_PR"
|
||||||
|
echo "## ✅ Updated PR: $PR_URL" >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
else
|
||||||
|
echo "📝 Creating new PR..."
|
||||||
|
PR_URL=$(echo -e "$PR_BODY" | gh pr create \
|
||||||
|
--title "Update SDK to $_SDK_VERSION" \
|
||||||
|
--body-file - \
|
||||||
|
--base main \
|
||||||
|
--head "$_BRANCH_NAME" \
|
||||||
|
--label "automated-pr" \
|
||||||
|
--label "t:ci")
|
||||||
|
echo "## 🚀 Created PR: $PR_URL" >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
fi
|
||||||
|
|
||||||
|
test:
|
||||||
|
name: Test Update
|
||||||
|
if: ${{ inputs.run-mode == 'Test' }}
|
||||||
|
runs-on: ubuntu-24.04
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
packages: read
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Check out repo
|
||||||
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
|
- name: Log inputs to job summary
|
||||||
|
uses: ./.github/actions/log-inputs
|
||||||
|
with:
|
||||||
|
inputs: ${{ toJson(inputs) }}
|
||||||
|
|
||||||
|
- name: Setup Android Build
|
||||||
|
uses: ./.github/actions/setup-android-build
|
||||||
|
|
||||||
|
- name: Update SDK Version
|
||||||
|
env:
|
||||||
|
_SDK_PACKAGE: ${{ inputs.sdk-package }}
|
||||||
|
_SDK_VERSION: ${{ inputs.sdk-version }}
|
||||||
|
run: |
|
||||||
|
./scripts/update-sdk-version.sh "$_SDK_PACKAGE" "$_SDK_VERSION"
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
env:
|
||||||
|
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # Used in settings.gradle.kts to download the SDK from GitHub Maven Packages
|
||||||
|
run: |
|
||||||
|
./gradlew assembleDebug --warn
|
||||||
34
.github/workflows/test.yml
vendored
34
.github/workflows/test.yml
vendored
@ -13,10 +13,9 @@ on:
|
|||||||
workflow_dispatch:
|
workflow_dispatch:
|
||||||
|
|
||||||
env:
|
env:
|
||||||
_JAVA_VERSION: 17
|
_JAVA_VERSION: 21
|
||||||
_GITHUB_ACTION_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}/attempts/${{ github.run_attempt }}
|
_GITHUB_ACTION_RUN_URL: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }}/attempts/${{ github.run_attempt }}
|
||||||
|
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
test:
|
test:
|
||||||
name: Test
|
name: Test
|
||||||
@ -27,13 +26,15 @@ jobs:
|
|||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Check out repo
|
- name: Check out repo
|
||||||
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0
|
||||||
|
with:
|
||||||
|
persist-credentials: false
|
||||||
|
|
||||||
- name: Validate Gradle wrapper
|
- name: Validate Gradle wrapper
|
||||||
uses: gradle/actions/wrapper-validation@06832c7b30a0129d7fb559bcc6e43d26f6374244 # v4.3.1
|
uses: gradle/actions/wrapper-validation@4d9f0ba0025fe599b4ebab900eb7f3a1d93ef4c2 # v5.0.0
|
||||||
|
|
||||||
- name: Cache Gradle files
|
- name: Cache Gradle files
|
||||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
~/.gradle/caches
|
~/.gradle/caches
|
||||||
@ -43,7 +44,7 @@ jobs:
|
|||||||
${{ runner.os }}-gradle-v2-
|
${{ runner.os }}-gradle-v2-
|
||||||
|
|
||||||
- name: Cache build output
|
- name: Cache build output
|
||||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
uses: actions/cache@0400d5f644dc74513175e3cd8d07132dd4860809 # v4.2.4
|
||||||
with:
|
with:
|
||||||
path: |
|
path: |
|
||||||
${{ github.workspace }}/build-cache
|
${{ github.workspace }}/build-cache
|
||||||
@ -52,19 +53,18 @@ jobs:
|
|||||||
${{ runner.os }}-build-
|
${{ runner.os }}-build-
|
||||||
|
|
||||||
- name: Configure Ruby
|
- name: Configure Ruby
|
||||||
uses: ruby/setup-ruby@ca041f971d66735f3e5ff1e21cc13e2d51e7e535 # v1.233.0
|
uses: ruby/setup-ruby@44511735964dcb71245e7e55f72539531f7bc0eb # v1.257.0
|
||||||
with:
|
with:
|
||||||
bundler-cache: true
|
bundler-cache: true
|
||||||
|
|
||||||
- name: Configure JDK
|
- name: Configure JDK
|
||||||
uses: actions/setup-java@c5195efecf7bdfc987ee8bae7a71cb8b11521c00 # v4.7.1
|
uses: actions/setup-java@dded0888837ed1f317902acf8a20df0ad188d165 # v5.0.0
|
||||||
with:
|
with:
|
||||||
distribution: "temurin"
|
distribution: "temurin"
|
||||||
java-version: ${{ env._JAVA_VERSION }}
|
java-version: ${{ env._JAVA_VERSION }}
|
||||||
|
|
||||||
- name: Install Fastlane
|
- name: Install Fastlane
|
||||||
run: |
|
run: |
|
||||||
gem install bundler:2.2.27
|
|
||||||
bundle config path vendor/bundle
|
bundle config path vendor/bundle
|
||||||
bundle install --jobs 4 --retry 3
|
bundle install --jobs 4 --retry 3
|
||||||
|
|
||||||
@ -75,7 +75,7 @@ jobs:
|
|||||||
bundle exec fastlane check
|
bundle exec fastlane check
|
||||||
|
|
||||||
- name: Upload test reports
|
- name: Upload test reports
|
||||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
uses: actions/upload-artifact@330a01c490aca151604b8cf639adc76d48f6c5d4 # v5.0.0
|
||||||
if: always()
|
if: always()
|
||||||
with:
|
with:
|
||||||
name: test-reports
|
name: test-reports
|
||||||
@ -91,7 +91,7 @@ jobs:
|
|||||||
|
|
||||||
- name: Upload to codecov.io
|
- name: Upload to codecov.io
|
||||||
id: upload-to-codecov
|
id: upload-to-codecov
|
||||||
uses: codecov/codecov-action@ad3126e916f78f00edff4ed0317cf185271ccc2d # v5.4.2
|
uses: codecov/codecov-action@5a1091511ad55cbe89839c7260b706298ca349f7 # v5.5.1
|
||||||
if: github.event_name == 'push' || github.event_name == 'pull_request'
|
if: github.event_name == 'push' || github.event_name == 'pull_request'
|
||||||
continue-on-error: true
|
continue-on-error: true
|
||||||
with:
|
with:
|
||||||
@ -103,14 +103,14 @@ jobs:
|
|||||||
- name: Comment PR if tests failed
|
- name: Comment PR if tests failed
|
||||||
if: steps.upload-to-codecov.outcome == 'failure' && (github.event_name == 'push' || github.event_name == 'pull_request')
|
if: steps.upload-to-codecov.outcome == 'failure' && (github.event_name == 'push' || github.event_name == 'pull_request')
|
||||||
env:
|
env:
|
||||||
PR_NUMBER: ${{ github.event.number }}
|
PR_NUMBER: ${{ github.event.number }}
|
||||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
RUN_ACTOR: ${{ github.triggering_actor }}
|
RUN_ACTOR: ${{ github.triggering_actor }}
|
||||||
run: |
|
run: |
|
||||||
echo "> [!WARNING]" >> $GITHUB_STEP_SUMMARY
|
echo "> [!WARNING]" >> "$GITHUB_STEP_SUMMARY"
|
||||||
echo "> Uploading code coverage report failed. Please check the \"Upload to codecov.io\" step of \"Process Test Reports\" job for more details." >> $GITHUB_STEP_SUMMARY
|
echo "> Uploading code coverage report failed. Please check the \"Upload to codecov.io\" step of \"Process Test Reports\" job for more details." >> "$GITHUB_STEP_SUMMARY"
|
||||||
|
|
||||||
if [ -n "$PR_NUMBER" ]; then
|
if [ -n "$PR_NUMBER" ]; then
|
||||||
message=$'> [!WARNING]\n> @'$RUN_ACTOR' Uploading code coverage report failed. Please check the "Upload to codecov.io" step of [Process Test Reports job]('$_GITHUB_ACTION_RUN_URL') for more details.'
|
message=$'> [!WARNING]\n> @'$RUN_ACTOR' Uploading code coverage report failed. Please check the "Upload to codecov.io" step of [Process Test Reports job]('$_GITHUB_ACTION_RUN_URL') for more details.'
|
||||||
gh pr comment --repo $GITHUB_REPOSITORY $PR_NUMBER --body "$message"
|
gh pr comment --repo "$GITHUB_REPOSITORY" "$PR_NUMBER" --body "$message"
|
||||||
fi
|
fi
|
||||||
|
|||||||
5
.github/zizmor.yml
vendored
Normal file
5
.github/zizmor.yml
vendored
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
rules:
|
||||||
|
unpinned-uses:
|
||||||
|
config:
|
||||||
|
policies:
|
||||||
|
bitwarden/gh-actions/*: ref-pin
|
||||||
7
.gitignore
vendored
7
.gitignore
vendored
@ -3,6 +3,13 @@
|
|||||||
fastlane/report.xml
|
fastlane/report.xml
|
||||||
fastlane/README.md
|
fastlane/README.md
|
||||||
|
|
||||||
|
# Ruby / Bundler
|
||||||
|
.bundle/
|
||||||
|
vendor/
|
||||||
|
|
||||||
|
# Backup files
|
||||||
|
*.bak
|
||||||
|
|
||||||
# General
|
# General
|
||||||
.DS_Store
|
.DS_Store
|
||||||
Thumbs.db
|
Thumbs.db
|
||||||
|
|||||||
@ -1 +0,0 @@
|
|||||||
npx lint-staged
|
|
||||||
@ -1 +1 @@
|
|||||||
3.3.1
|
3.4.2
|
||||||
|
|||||||
12
Gemfile
12
Gemfile
@ -7,3 +7,15 @@ gem 'time'
|
|||||||
|
|
||||||
plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile')
|
plugins_path = File.join(File.dirname(__FILE__), 'fastlane', 'Pluginfile')
|
||||||
eval_gemfile(plugins_path) if File.exist?(plugins_path)
|
eval_gemfile(plugins_path) if File.exist?(plugins_path)
|
||||||
|
|
||||||
|
# Since ruby 3.4.0 these are not included in the standard library
|
||||||
|
gem 'abbrev'
|
||||||
|
gem 'logger'
|
||||||
|
gem 'mutex_m'
|
||||||
|
gem 'csv'
|
||||||
|
|
||||||
|
# Since ruby 3.4.1 these are not included in the standard library
|
||||||
|
gem 'nkf'
|
||||||
|
|
||||||
|
# Starting with Ruby 3.5.0, these are not included in the standard library
|
||||||
|
gem 'ostruct'
|
||||||
|
|||||||
63
Gemfile.lock
63
Gemfile.lock
@ -1,40 +1,41 @@
|
|||||||
GEM
|
GEM
|
||||||
remote: https://rubygems.org/
|
remote: https://rubygems.org/
|
||||||
specs:
|
specs:
|
||||||
CFPropertyList (3.0.7)
|
CFPropertyList (3.0.8)
|
||||||
base64
|
abbrev (0.1.2)
|
||||||
nkf
|
addressable (2.8.8)
|
||||||
rexml
|
public_suffix (>= 2.0.2, < 8.0)
|
||||||
addressable (2.8.7)
|
|
||||||
public_suffix (>= 2.0.2, < 7.0)
|
|
||||||
artifactory (3.0.17)
|
artifactory (3.0.17)
|
||||||
atomos (0.1.3)
|
atomos (0.1.3)
|
||||||
aws-eventstream (1.4.0)
|
aws-eventstream (1.4.0)
|
||||||
aws-partitions (1.1125.0)
|
aws-partitions (1.1190.0)
|
||||||
aws-sdk-core (3.226.2)
|
aws-sdk-core (3.239.2)
|
||||||
aws-eventstream (~> 1, >= 1.3.0)
|
aws-eventstream (~> 1, >= 1.3.0)
|
||||||
aws-partitions (~> 1, >= 1.992.0)
|
aws-partitions (~> 1, >= 1.992.0)
|
||||||
aws-sigv4 (~> 1.9)
|
aws-sigv4 (~> 1.9)
|
||||||
base64
|
base64
|
||||||
|
bigdecimal
|
||||||
jmespath (~> 1, >= 1.6.1)
|
jmespath (~> 1, >= 1.6.1)
|
||||||
logger
|
logger
|
||||||
aws-sdk-kms (1.106.0)
|
aws-sdk-kms (1.118.0)
|
||||||
aws-sdk-core (~> 3, >= 3.225.0)
|
aws-sdk-core (~> 3, >= 3.239.1)
|
||||||
aws-sigv4 (~> 1.5)
|
aws-sigv4 (~> 1.5)
|
||||||
aws-sdk-s3 (1.192.0)
|
aws-sdk-s3 (1.206.0)
|
||||||
aws-sdk-core (~> 3, >= 3.225.0)
|
aws-sdk-core (~> 3, >= 3.234.0)
|
||||||
aws-sdk-kms (~> 1)
|
aws-sdk-kms (~> 1)
|
||||||
aws-sigv4 (~> 1.5)
|
aws-sigv4 (~> 1.5)
|
||||||
aws-sigv4 (1.12.1)
|
aws-sigv4 (1.12.1)
|
||||||
aws-eventstream (~> 1, >= 1.0.2)
|
aws-eventstream (~> 1, >= 1.0.2)
|
||||||
babosa (1.0.4)
|
babosa (1.0.4)
|
||||||
base64 (0.3.0)
|
base64 (0.3.0)
|
||||||
|
bigdecimal (3.3.1)
|
||||||
claide (1.1.0)
|
claide (1.1.0)
|
||||||
colored (1.2)
|
colored (1.2)
|
||||||
colored2 (3.1.2)
|
colored2 (3.1.2)
|
||||||
commander (4.6.0)
|
commander (4.6.0)
|
||||||
highline (~> 2.0.0)
|
highline (~> 2.0.0)
|
||||||
date (3.4.1)
|
csv (3.3.5)
|
||||||
|
date (3.5.0)
|
||||||
declarative (0.0.20)
|
declarative (0.0.20)
|
||||||
digest-crc (0.7.0)
|
digest-crc (0.7.0)
|
||||||
rake (>= 12.0.0, < 14.0.0)
|
rake (>= 12.0.0, < 14.0.0)
|
||||||
@ -54,9 +55,9 @@ GEM
|
|||||||
faraday-rack (~> 1.0)
|
faraday-rack (~> 1.0)
|
||||||
faraday-retry (~> 1.0)
|
faraday-retry (~> 1.0)
|
||||||
ruby2_keywords (>= 0.0.4)
|
ruby2_keywords (>= 0.0.4)
|
||||||
faraday-cookie_jar (0.0.7)
|
faraday-cookie_jar (0.0.8)
|
||||||
faraday (>= 0.8.0)
|
faraday (>= 0.8.0)
|
||||||
http-cookie (~> 1.0.0)
|
http-cookie (>= 1.0.0)
|
||||||
faraday-em_http (1.0.0)
|
faraday-em_http (1.0.0)
|
||||||
faraday-em_synchrony (1.0.1)
|
faraday-em_synchrony (1.0.1)
|
||||||
faraday-excon (1.1.0)
|
faraday-excon (1.1.0)
|
||||||
@ -71,8 +72,9 @@ GEM
|
|||||||
faraday_middleware (1.2.1)
|
faraday_middleware (1.2.1)
|
||||||
faraday (~> 1.0)
|
faraday (~> 1.0)
|
||||||
fastimage (2.4.0)
|
fastimage (2.4.0)
|
||||||
fastlane (2.228.0)
|
fastlane (2.229.0)
|
||||||
CFPropertyList (>= 2.3, < 4.0.0)
|
CFPropertyList (>= 2.3, < 4.0.0)
|
||||||
|
abbrev (~> 0.1.2)
|
||||||
addressable (>= 2.8, < 3.0.0)
|
addressable (>= 2.8, < 3.0.0)
|
||||||
artifactory (~> 3.0)
|
artifactory (~> 3.0)
|
||||||
aws-sdk-s3 (~> 1.0)
|
aws-sdk-s3 (~> 1.0)
|
||||||
@ -80,6 +82,7 @@ GEM
|
|||||||
bundler (>= 1.12.0, < 3.0.0)
|
bundler (>= 1.12.0, < 3.0.0)
|
||||||
colored (~> 1.2)
|
colored (~> 1.2)
|
||||||
commander (~> 4.6)
|
commander (~> 4.6)
|
||||||
|
csv (~> 3.3)
|
||||||
dotenv (>= 2.1.1, < 3.0.0)
|
dotenv (>= 2.1.1, < 3.0.0)
|
||||||
emoji_regex (>= 0.1, < 4.0)
|
emoji_regex (>= 0.1, < 4.0)
|
||||||
excon (>= 0.71.0, < 1.0.0)
|
excon (>= 0.71.0, < 1.0.0)
|
||||||
@ -99,6 +102,7 @@ GEM
|
|||||||
jwt (>= 2.1.0, < 3)
|
jwt (>= 2.1.0, < 3)
|
||||||
mini_magick (>= 4.9.4, < 5.0.0)
|
mini_magick (>= 4.9.4, < 5.0.0)
|
||||||
multipart-post (>= 2.0.0, < 3.0.0)
|
multipart-post (>= 2.0.0, < 3.0.0)
|
||||||
|
mutex_m (~> 0.3.0)
|
||||||
naturally (~> 2.2)
|
naturally (~> 2.2)
|
||||||
optparse (>= 0.1.1, < 1.0.0)
|
optparse (>= 0.1.1, < 1.0.0)
|
||||||
plist (>= 3.1.0, < 4.0.0)
|
plist (>= 3.1.0, < 4.0.0)
|
||||||
@ -165,37 +169,38 @@ GEM
|
|||||||
httpclient (2.9.0)
|
httpclient (2.9.0)
|
||||||
mutex_m
|
mutex_m
|
||||||
jmespath (1.6.2)
|
jmespath (1.6.2)
|
||||||
json (2.12.2)
|
json (2.17.1)
|
||||||
jwt (2.10.2)
|
jwt (2.10.2)
|
||||||
base64
|
base64
|
||||||
logger (1.7.0)
|
logger (1.7.0)
|
||||||
mini_magick (4.13.2)
|
mini_magick (4.13.2)
|
||||||
mini_mime (1.1.5)
|
mini_mime (1.1.5)
|
||||||
multi_json (1.15.0)
|
multi_json (1.18.0)
|
||||||
multipart-post (2.4.1)
|
multipart-post (2.4.1)
|
||||||
mutex_m (0.3.0)
|
mutex_m (0.3.0)
|
||||||
nanaimo (0.4.0)
|
nanaimo (0.4.0)
|
||||||
naturally (2.3.0)
|
naturally (2.3.0)
|
||||||
nkf (0.2.0)
|
nkf (0.2.0)
|
||||||
optparse (0.6.0)
|
optparse (0.8.0)
|
||||||
os (1.1.4)
|
os (1.1.4)
|
||||||
|
ostruct (0.6.3)
|
||||||
plist (3.7.2)
|
plist (3.7.2)
|
||||||
public_suffix (6.0.2)
|
public_suffix (7.0.0)
|
||||||
rake (13.3.0)
|
rake (13.3.1)
|
||||||
representable (3.2.0)
|
representable (3.2.0)
|
||||||
declarative (< 0.1.0)
|
declarative (< 0.1.0)
|
||||||
trailblazer-option (>= 0.1.1, < 0.2.0)
|
trailblazer-option (>= 0.1.1, < 0.2.0)
|
||||||
uber (< 0.2.0)
|
uber (< 0.2.0)
|
||||||
retriable (3.1.2)
|
retriable (3.1.2)
|
||||||
rexml (3.4.1)
|
rexml (3.4.4)
|
||||||
rouge (3.28.0)
|
rouge (3.28.0)
|
||||||
ruby2_keywords (0.0.5)
|
ruby2_keywords (0.0.5)
|
||||||
rubyzip (2.4.1)
|
rubyzip (2.4.1)
|
||||||
security (0.1.5)
|
security (0.1.5)
|
||||||
signet (0.20.0)
|
signet (0.21.0)
|
||||||
addressable (~> 2.8)
|
addressable (~> 2.8)
|
||||||
faraday (>= 0.17.5, < 3.a)
|
faraday (>= 0.17.5, < 3.a)
|
||||||
jwt (>= 1.5, < 3.0)
|
jwt (>= 1.5, < 4.0)
|
||||||
multi_json (~> 1.10)
|
multi_json (~> 1.10)
|
||||||
simctl (1.6.10)
|
simctl (1.6.10)
|
||||||
CFPropertyList
|
CFPropertyList
|
||||||
@ -230,12 +235,18 @@ PLATFORMS
|
|||||||
ruby
|
ruby
|
||||||
|
|
||||||
DEPENDENCIES
|
DEPENDENCIES
|
||||||
|
abbrev
|
||||||
|
csv
|
||||||
fastlane
|
fastlane
|
||||||
fastlane-plugin-firebase_app_distribution
|
fastlane-plugin-firebase_app_distribution
|
||||||
|
logger
|
||||||
|
mutex_m
|
||||||
|
nkf
|
||||||
|
ostruct
|
||||||
time
|
time
|
||||||
|
|
||||||
RUBY VERSION
|
RUBY VERSION
|
||||||
ruby 3.3.1p55
|
ruby 3.4.2p28
|
||||||
|
|
||||||
BUNDLED WITH
|
BUNDLED WITH
|
||||||
2.6.6
|
2.6.2
|
||||||
|
|||||||
51
README.md
51
README.md
@ -4,13 +4,12 @@
|
|||||||
|
|
||||||
- [Compatibility](#compatibility)
|
- [Compatibility](#compatibility)
|
||||||
- [Setup](#setup)
|
- [Setup](#setup)
|
||||||
- [Theme](#theme)
|
|
||||||
- [Dependencies](#dependencies)
|
- [Dependencies](#dependencies)
|
||||||
|
|
||||||
## Compatibility
|
## Compatibility
|
||||||
|
|
||||||
- **Minimum SDK**: 29
|
- **Minimum SDK**: 29 (Android 10)
|
||||||
- **Target SDK**: 35
|
- **Target SDK**: 36 (Android 16)
|
||||||
- **Device Types Supported**: Phone and Tablet
|
- **Device Types Supported**: Phone and Tablet
|
||||||
- **Orientations Supported**: Portrait and Landscape
|
- **Orientations Supported**: Portrait and Landscape
|
||||||
|
|
||||||
@ -52,34 +51,46 @@
|
|||||||
|
|
||||||
Please avoid mixing formatting and logical changes in the same commit/PR. When possible, fix any large formatting issues in a separate PR before opening one to make logical changes to the same code. This helps others focus on the meaningful code changes when reviewing the code.
|
Please avoid mixing formatting and logical changes in the same commit/PR. When possible, fix any large formatting issues in a separate PR before opening one to make logical changes to the same code. This helps others focus on the meaningful code changes when reviewing the code.
|
||||||
|
|
||||||
4. Setup JDK `Version` `17`:
|
4. Setup JDK `Version` `21`:
|
||||||
|
|
||||||
- Navigate to `Preferences > Build, Execution, Deployment > Build Tools > Gradle`.
|
- Navigate to `Preferences > Build, Execution, Deployment > Build Tools > Gradle`.
|
||||||
- Hit the selected Gradle JDK next to `Gradle JDK:`.
|
- Hit the selected Gradle JDK next to `Gradle JDK:`.
|
||||||
- Select a `17.x` version or hit `Download JDK...` if not present.
|
- Select a `21.x` version or hit `Download JDK...` if not present.
|
||||||
- Select `Version` `17`.
|
- Select `Version` `21`.
|
||||||
- Select your preferred `Vendor`.
|
- Select your preferred `Vendor`.
|
||||||
- Hit `Download`.
|
- Hit `Download`.
|
||||||
- Hit `Apply`.
|
- Hit `Apply`.
|
||||||
|
|
||||||
## Theme
|
5. Setup `detekt` pre-commit hook (optional):
|
||||||
|
|
||||||
### Icons & Illustrations
|
Run the following script from the root of the repository to install the hook. This will overwrite any existing pre-commit hook if present.
|
||||||
|
|
||||||
The app supports light mode, dark mode and dynamic colors. Most icons in the app will display correctly using tinting but multi-tonal icons and illustrations require extra processing in order to be displayed properly with dynamic colors.
|
```shell
|
||||||
|
echo "Writing detekt pre-commit hook..."
|
||||||
|
cat << 'EOL' > .git/hooks/pre-commit
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
All illustrations and multi-tonal icons require the svg paths to be tagged with the `name` attribute in order for each individual path to be tinted the appropriate color. Any untagged path will not be tinted and the resulting image will be incorrect.
|
echo "Running detekt check..."
|
||||||
|
OUTPUT="/tmp/detekt-$(date +%s)"
|
||||||
|
./gradlew -Pprecommit=true detekt > $OUTPUT
|
||||||
|
EXIT_CODE=$?
|
||||||
|
if [ $EXIT_CODE -ne 0 ]; then
|
||||||
|
cat $OUTPUT
|
||||||
|
rm $OUTPUT
|
||||||
|
echo "***********************************************"
|
||||||
|
echo " detekt failed "
|
||||||
|
echo " Please fix the above issues before committing "
|
||||||
|
echo "***********************************************"
|
||||||
|
exit $EXIT_CODE
|
||||||
|
fi
|
||||||
|
rm $OUTPUT
|
||||||
|
EOL
|
||||||
|
echo "detekt pre-commit hook written to .git/hooks/pre-commit"
|
||||||
|
echo "Making the hook executable"
|
||||||
|
chmod +x .git/hooks/pre-commit
|
||||||
|
|
||||||
The supported tags are as follows:
|
echo "detekt pre-commit hook installed successfully to .git/hooks/pre-commit"
|
||||||
|
```
|
||||||
* outline
|
|
||||||
* primary
|
|
||||||
* secondary
|
|
||||||
* tertiary
|
|
||||||
* accent
|
|
||||||
* logo
|
|
||||||
* navigation
|
|
||||||
* navigationActiveAccent
|
|
||||||
|
|
||||||
## Dependencies
|
## Dependencies
|
||||||
|
|
||||||
|
|||||||
@ -55,17 +55,24 @@ android {
|
|||||||
applicationId = "com.x8bit.bitwarden"
|
applicationId = "com.x8bit.bitwarden"
|
||||||
minSdk = libs.versions.minSdk.get().toInt()
|
minSdk = libs.versions.minSdk.get().toInt()
|
||||||
targetSdk = libs.versions.targetSdk.get().toInt()
|
targetSdk = libs.versions.targetSdk.get().toInt()
|
||||||
versionCode = 1
|
versionCode = libs.versions.appVersionCode.get().toInt()
|
||||||
versionName = "2025.4.0"
|
versionName = libs.versions.appVersionName.get()
|
||||||
|
|
||||||
setProperty("archivesBaseName", "com.x8bit.bitwarden")
|
|
||||||
|
|
||||||
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner"
|
||||||
|
|
||||||
|
// Set the base archive name for publishing purposes. This is used to derive the APK and AAB
|
||||||
|
// artifact names when uploading to Firebase and Play Store.
|
||||||
|
base.archivesName = "com.x8bit.bitwarden"
|
||||||
|
|
||||||
buildConfigField(
|
buildConfigField(
|
||||||
type = "String",
|
type = "String",
|
||||||
name = "CI_INFO",
|
name = "CI_INFO",
|
||||||
value = "${ciProperties.getOrDefault("ci.info", "\"local\"")}",
|
value = "${ciProperties.getOrDefault("ci.info", "\"\uD83D\uDCBB local\"")}",
|
||||||
|
)
|
||||||
|
buildConfigField(
|
||||||
|
type = "String",
|
||||||
|
name = "SDK_VERSION",
|
||||||
|
value = "\"${libs.versions.bitwardenSdk.get()}\"",
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -213,10 +220,11 @@ dependencies {
|
|||||||
add("standardImplementation", dependencyNotation)
|
add("standardImplementation", dependencyNotation)
|
||||||
}
|
}
|
||||||
|
|
||||||
implementation(files("libs/authenticatorbridge-1.0.1-release.aar"))
|
implementation(project(":authenticatorbridge"))
|
||||||
|
|
||||||
implementation(project(":annotation"))
|
implementation(project(":annotation"))
|
||||||
implementation(project(":core"))
|
implementation(project(":core"))
|
||||||
|
implementation(project(":cxf"))
|
||||||
implementation(project(":data"))
|
implementation(project(":data"))
|
||||||
implementation(project(":network"))
|
implementation(project(":network"))
|
||||||
implementation(project(":ui"))
|
implementation(project(":ui"))
|
||||||
@ -227,8 +235,7 @@ dependencies {
|
|||||||
implementation(libs.androidx.browser)
|
implementation(libs.androidx.browser)
|
||||||
implementation(libs.androidx.biometrics)
|
implementation(libs.androidx.biometrics)
|
||||||
implementation(libs.androidx.camera.camera2)
|
implementation(libs.androidx.camera.camera2)
|
||||||
implementation(libs.androidx.camera.lifecycle)
|
implementation(libs.androidx.camera.compose)
|
||||||
implementation(libs.androidx.camera.view)
|
|
||||||
implementation(platform(libs.androidx.compose.bom))
|
implementation(platform(libs.androidx.compose.bom))
|
||||||
implementation(libs.androidx.compose.animation)
|
implementation(libs.androidx.compose.animation)
|
||||||
implementation(libs.androidx.compose.material3)
|
implementation(libs.androidx.compose.material3)
|
||||||
@ -238,6 +245,8 @@ dependencies {
|
|||||||
implementation(libs.androidx.compose.ui.graphics)
|
implementation(libs.androidx.compose.ui.graphics)
|
||||||
implementation(libs.androidx.compose.ui.tooling.preview)
|
implementation(libs.androidx.compose.ui.tooling.preview)
|
||||||
implementation(libs.androidx.core.ktx)
|
implementation(libs.androidx.core.ktx)
|
||||||
|
implementation(libs.androidx.credentials)
|
||||||
|
implementation(libs.androidx.credentials.providerevents)
|
||||||
implementation(libs.androidx.hilt.navigation.compose)
|
implementation(libs.androidx.hilt.navigation.compose)
|
||||||
implementation(libs.androidx.lifecycle.process)
|
implementation(libs.androidx.lifecycle.process)
|
||||||
implementation(libs.androidx.lifecycle.runtime.compose)
|
implementation(libs.androidx.lifecycle.runtime.compose)
|
||||||
@ -251,19 +260,16 @@ dependencies {
|
|||||||
implementation(libs.androidx.work.runtime.ktx)
|
implementation(libs.androidx.work.runtime.ktx)
|
||||||
implementation(libs.bitwarden.sdk)
|
implementation(libs.bitwarden.sdk)
|
||||||
implementation(libs.bumptech.glide)
|
implementation(libs.bumptech.glide)
|
||||||
implementation(libs.androidx.credentials)
|
|
||||||
implementation(libs.google.hilt.android)
|
implementation(libs.google.hilt.android)
|
||||||
ksp(libs.google.hilt.compiler)
|
ksp(libs.google.hilt.compiler)
|
||||||
implementation(libs.kotlinx.collections.immutable)
|
implementation(libs.kotlinx.collections.immutable)
|
||||||
implementation(libs.kotlinx.coroutines.android)
|
implementation(libs.kotlinx.coroutines.android)
|
||||||
implementation(libs.kotlinx.serialization)
|
implementation(libs.kotlinx.serialization)
|
||||||
|
implementation(platform(libs.square.okhttp.bom))
|
||||||
implementation(libs.square.okhttp)
|
implementation(libs.square.okhttp)
|
||||||
implementation(libs.square.okhttp.logging)
|
|
||||||
implementation(platform(libs.square.retrofit.bom))
|
implementation(platform(libs.square.retrofit.bom))
|
||||||
implementation(libs.square.retrofit)
|
implementation(libs.square.retrofit)
|
||||||
implementation(libs.square.retrofit.kotlinx.serialization)
|
|
||||||
implementation(libs.timber)
|
implementation(libs.timber)
|
||||||
implementation(libs.zxing.zxing.core)
|
|
||||||
|
|
||||||
// For now we are restricted to running Compose tests for debug builds only
|
// For now we are restricted to running Compose tests for debug builds only
|
||||||
debugImplementation(libs.androidx.compose.ui.test.manifest)
|
debugImplementation(libs.androidx.compose.ui.test.manifest)
|
||||||
@ -276,6 +282,7 @@ dependencies {
|
|||||||
standardImplementation(libs.google.play.review)
|
standardImplementation(libs.google.play.review)
|
||||||
|
|
||||||
// Pull in test fixtures from other modules
|
// Pull in test fixtures from other modules
|
||||||
|
testImplementation(testFixtures(project(":core")))
|
||||||
testImplementation(testFixtures(project(":data")))
|
testImplementation(testFixtures(project(":data")))
|
||||||
testImplementation(testFixtures(project(":network")))
|
testImplementation(testFixtures(project(":network")))
|
||||||
testImplementation(testFixtures(project(":ui")))
|
testImplementation(testFixtures(project(":ui")))
|
||||||
@ -284,12 +291,11 @@ dependencies {
|
|||||||
testImplementation(libs.google.hilt.android.testing)
|
testImplementation(libs.google.hilt.android.testing)
|
||||||
testImplementation(platform(libs.junit.bom))
|
testImplementation(platform(libs.junit.bom))
|
||||||
testRuntimeOnly(libs.junit.platform.launcher)
|
testRuntimeOnly(libs.junit.platform.launcher)
|
||||||
testImplementation(libs.junit.junit5)
|
testImplementation(libs.junit.jupiter)
|
||||||
testImplementation(libs.junit.vintage)
|
testImplementation(libs.junit.vintage)
|
||||||
testImplementation(libs.kotlinx.coroutines.test)
|
testImplementation(libs.kotlinx.coroutines.test)
|
||||||
testImplementation(libs.mockk.mockk)
|
testImplementation(libs.mockk.mockk)
|
||||||
testImplementation(libs.robolectric.robolectric)
|
testImplementation(libs.robolectric.robolectric)
|
||||||
testImplementation(libs.square.okhttp.mockwebserver)
|
|
||||||
testImplementation(libs.square.turbine)
|
testImplementation(libs.square.turbine)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -298,7 +304,10 @@ tasks {
|
|||||||
useJUnitPlatform()
|
useJUnitPlatform()
|
||||||
maxHeapSize = "2g"
|
maxHeapSize = "2g"
|
||||||
maxParallelForks = Runtime.getRuntime().availableProcessors()
|
maxParallelForks = Runtime.getRuntime().availableProcessors()
|
||||||
jvmArgs = jvmArgs.orEmpty() + "-XX:+UseParallelGC" + "-Duser.country=US"
|
jvmArgs = jvmArgs.orEmpty() + "-XX:+UseParallelGC" +
|
||||||
|
// Explicitly setting the user Country and Language because tests assume en-US
|
||||||
|
"-Duser.country=US" +
|
||||||
|
"-Duser.language=en"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -323,6 +332,7 @@ private fun renameFile(path: String, newName: String) {
|
|||||||
if (originalFile.renameTo(newFile)) {
|
if (originalFile.renameTo(newFile)) {
|
||||||
println("Renamed $originalFile to $newFile")
|
println("Renamed $originalFile to $newFile")
|
||||||
} else {
|
} else {
|
||||||
|
@Suppress("TooGenericExceptionThrown")
|
||||||
throw RuntimeException("Failed to rename $originalFile to $newFile")
|
throw RuntimeException("Failed to rename $originalFile to $newFile")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
@ -0,0 +1,264 @@
|
|||||||
|
{
|
||||||
|
"formatVersion": 1,
|
||||||
|
"database": {
|
||||||
|
"version": 8,
|
||||||
|
"identityHash": "11387825dab701f9d2dd2e940ffbd794",
|
||||||
|
"entities": [
|
||||||
|
{
|
||||||
|
"tableName": "ciphers",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `user_id` TEXT NOT NULL, `has_totp` INTEGER NOT NULL DEFAULT 1, `cipher_type` TEXT NOT NULL, `cipher_json` TEXT NOT NULL, PRIMARY KEY(`id`))",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "userId",
|
||||||
|
"columnName": "user_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "hasTotp",
|
||||||
|
"columnName": "has_totp",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "cipherType",
|
||||||
|
"columnName": "cipher_type",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "cipherJson",
|
||||||
|
"columnName": "cipher_json",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": false,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"indices": [
|
||||||
|
{
|
||||||
|
"name": "index_ciphers_user_id",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_ciphers_user_id` ON `${TABLE_NAME}` (`user_id`)"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "collections",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `user_id` TEXT NOT NULL, `organization_id` TEXT NOT NULL, `should_hide_passwords` INTEGER NOT NULL, `name` TEXT NOT NULL, `external_id` TEXT, `read_only` INTEGER NOT NULL, `manage` INTEGER, `default_user_collection_email` TEXT, `type` TEXT NOT NULL DEFAULT '0', PRIMARY KEY(`id`))",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "userId",
|
||||||
|
"columnName": "user_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "organizationId",
|
||||||
|
"columnName": "organization_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "shouldHidePasswords",
|
||||||
|
"columnName": "should_hide_passwords",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "name",
|
||||||
|
"columnName": "name",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "externalId",
|
||||||
|
"columnName": "external_id",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "isReadOnly",
|
||||||
|
"columnName": "read_only",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "canManage",
|
||||||
|
"columnName": "manage",
|
||||||
|
"affinity": "INTEGER"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "defaultUserCollectionEmail",
|
||||||
|
"columnName": "default_user_collection_email",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "type",
|
||||||
|
"columnName": "type",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true,
|
||||||
|
"defaultValue": "'0'"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": false,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"indices": [
|
||||||
|
{
|
||||||
|
"name": "index_collections_user_id",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_collections_user_id` ON `${TABLE_NAME}` (`user_id`)"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "domains",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`user_id` TEXT NOT NULL, `domains_json` TEXT, PRIMARY KEY(`user_id`))",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "userId",
|
||||||
|
"columnName": "user_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "domainsJson",
|
||||||
|
"columnName": "domains_json",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": false,
|
||||||
|
"columnNames": [
|
||||||
|
"user_id"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "folders",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `user_id` TEXT NOT NULL, `name` TEXT, `revision_date` INTEGER NOT NULL, PRIMARY KEY(`id`))",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "userId",
|
||||||
|
"columnName": "user_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "name",
|
||||||
|
"columnName": "name",
|
||||||
|
"affinity": "TEXT"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "revisionDate",
|
||||||
|
"columnName": "revision_date",
|
||||||
|
"affinity": "INTEGER",
|
||||||
|
"notNull": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": false,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"indices": [
|
||||||
|
{
|
||||||
|
"name": "index_folders_user_id",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_folders_user_id` ON `${TABLE_NAME}` (`user_id`)"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"tableName": "sends",
|
||||||
|
"createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `user_id` TEXT NOT NULL, `send_type` TEXT NOT NULL, `send_json` TEXT NOT NULL, PRIMARY KEY(`id`))",
|
||||||
|
"fields": [
|
||||||
|
{
|
||||||
|
"fieldPath": "id",
|
||||||
|
"columnName": "id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "userId",
|
||||||
|
"columnName": "user_id",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "sendType",
|
||||||
|
"columnName": "send_type",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"fieldPath": "sendJson",
|
||||||
|
"columnName": "send_json",
|
||||||
|
"affinity": "TEXT",
|
||||||
|
"notNull": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"primaryKey": {
|
||||||
|
"autoGenerate": false,
|
||||||
|
"columnNames": [
|
||||||
|
"id"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"indices": [
|
||||||
|
{
|
||||||
|
"name": "index_sends_user_id",
|
||||||
|
"unique": false,
|
||||||
|
"columnNames": [
|
||||||
|
"user_id"
|
||||||
|
],
|
||||||
|
"orders": [],
|
||||||
|
"createSql": "CREATE INDEX IF NOT EXISTS `index_sends_user_id` ON `${TABLE_NAME}` (`user_id`)"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"setupQueries": [
|
||||||
|
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
|
||||||
|
"INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '11387825dab701f9d2dd2e940ffbd794')"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
27
app/src/debug/res/xml/network_security_config.xml
Normal file
27
app/src/debug/res/xml/network_security_config.xml
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<network-security-config xmlns:tools="http://schemas.android.com/tools">
|
||||||
|
|
||||||
|
<base-config
|
||||||
|
cleartextTrafficPermitted="true"
|
||||||
|
tools:ignore="InsecureBaseConfiguration">
|
||||||
|
<trust-anchors>
|
||||||
|
<!-- Trust pre-installed CAs -->
|
||||||
|
<certificates src="system" />
|
||||||
|
<!-- Additionally trust user added CAs -->
|
||||||
|
<certificates
|
||||||
|
src="user"
|
||||||
|
tools:ignore="AcceptsUserCertificates" />
|
||||||
|
</trust-anchors>
|
||||||
|
</base-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" />
|
||||||
|
</trust-anchors>
|
||||||
|
</domain-config>
|
||||||
|
|
||||||
|
</network-security-config>
|
||||||
@ -0,0 +1,44 @@
|
|||||||
|
Recognized as best password manager by PCMag, WIRED, The Verge, CNET, G2, and more!
|
||||||
|
|
||||||
|
SECURE YOUR DIGITAL LIFE
|
||||||
|
Secure your digital life and protect against data breaches by generating and saving unique, strong passwords for every account. Maintain everything in an end-to-end encrypted password vault that only you can access.
|
||||||
|
|
||||||
|
ACCESS YOUR DATA, ANYWHERE, ANYTIME, ON ANY DEVICE
|
||||||
|
Easily manage, store, secure, and share unlimited passwords and passkeys across unlimited devices without restrictions.
|
||||||
|
|
||||||
|
USE PASSKEYS WHEREVER YOU LOG IN
|
||||||
|
Create, store, and sync passkeys across the Bitwarden mobile app and browser extensions for a secure, passwordless experience no matter what device you're on.
|
||||||
|
|
||||||
|
EVERYONE SHOULD HAVE THE TOOLS TO STAY SAFE ONLINE
|
||||||
|
Utilize Bitwarden for free with no ads or selling data. Bitwarden believes everyone should have the ability to stay safe online. Premium plans offer access to advanced features.
|
||||||
|
|
||||||
|
EMPOWER YOUR TEAMS WITH BITWARDEN
|
||||||
|
Plans for Teams and Enterprise come with professional business features. Some examples include SSO integration, self-hosting, directory integration and SCIM provisioning, global policies, API access, event logs, and more.
|
||||||
|
|
||||||
|
Use Bitwarden to secure your workforce and share sensitive information with colleagues.
|
||||||
|
|
||||||
|
More reasons to choose Bitwarden:
|
||||||
|
|
||||||
|
World-Class Encryption
|
||||||
|
Passwords are protected with advanced end-to-end encryption (AES-256 bit, salted hashing, and PBKDF2 SHA-256) so your data stays secure and private.
|
||||||
|
|
||||||
|
3rd-party Audits
|
||||||
|
Bitwarden regularly conducts comprehensive third-party security audits with notable security firms. These annual audits include source code assessments and penetration testing across Bitwarden IPs, servers, and web applications.
|
||||||
|
|
||||||
|
Advanced 2FA
|
||||||
|
Secure your login with a third-party authenticator, emailed codes, or FIDO2 WebAuthn credentials such as a hardware security key or passkey.
|
||||||
|
|
||||||
|
Bitwarden Send
|
||||||
|
Transmit data directly to others while maintaining end-to-end encrypted security and limiting exposure.
|
||||||
|
|
||||||
|
Built-in Generator
|
||||||
|
Create long, complex, and distinct passwords and unique usernames for every site you visit. Integrate with email alias providers for additional privacy.
|
||||||
|
|
||||||
|
Global Translations
|
||||||
|
Bitwarden translations exist for more than 50 languages.
|
||||||
|
|
||||||
|
Cross-Platform Applications
|
||||||
|
Secure and share sensitive data within your Bitwarden Vault from any browser, mobile device, or desktop OS, and more.
|
||||||
|
|
||||||
|
|
||||||
|
Accessibility Services Disclosure: Bitwarden offers the ability to use the Accessibility Service to augment Autofill on older devices or in cases where autofill is not working correctly. When enabled, the Accessibility Service is used to search for login fields in apps and websites. This establishes the appropriate field IDs when a match for the app or site is found and inserts credentials. When the Accessibility Service is active Bitwarden does not store information or control any on-screen elements beyond inserting credentials.
|
||||||
@ -0,0 +1 @@
|
|||||||
|
Bitwarden is a login and password manager that helps keep you safe while online.
|
||||||
1
app/src/fdroid/fastlane/metadata/android/en-US/title.txt
Normal file
1
app/src/fdroid/fastlane/metadata/android/en-US/title.txt
Normal file
@ -0,0 +1 @@
|
|||||||
|
Bitwarden Password Manager
|
||||||
@ -13,6 +13,7 @@
|
|||||||
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
|
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
|
||||||
<uses-permission android:name="android.permission.NFC" />
|
<uses-permission android:name="android.permission.NFC" />
|
||||||
<uses-permission android:name="android.permission.CAMERA" />
|
<uses-permission android:name="android.permission.CAMERA" />
|
||||||
|
<uses-permission android:name="horizons.permission.HEADSET_CAMERA" />
|
||||||
<uses-permission android:name="android.permission.INTERNET" />
|
<uses-permission android:name="android.permission.INTERNET" />
|
||||||
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
|
||||||
<uses-permission android:name="android.permission.READ_USER_DICTIONARY" />
|
<uses-permission android:name="android.permission.READ_USER_DICTIONARY" />
|
||||||
@ -86,6 +87,8 @@
|
|||||||
<intent-filter>
|
<intent-filter>
|
||||||
<action android:name="com.x8bit.bitwarden.credentials.ACTION_CREATE_PASSKEY" />
|
<action android:name="com.x8bit.bitwarden.credentials.ACTION_CREATE_PASSKEY" />
|
||||||
<action android:name="com.x8bit.bitwarden.credentials.ACTION_GET_PASSKEY" />
|
<action android:name="com.x8bit.bitwarden.credentials.ACTION_GET_PASSKEY" />
|
||||||
|
<action android:name="com.x8bit.bitwarden.credentials.ACTION_CREATE_PASSWORD" />
|
||||||
|
<action android:name="com.x8bit.bitwarden.credentials.ACTION_GET_PASSWORD" />
|
||||||
<action android:name="com.x8bit.bitwarden.credentials.ACTION_UNLOCK_ACCOUNT" />
|
<action android:name="com.x8bit.bitwarden.credentials.ACTION_UNLOCK_ACCOUNT" />
|
||||||
|
|
||||||
<category android:name="android.intent.category.DEFAULT" />
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
@ -104,6 +107,17 @@
|
|||||||
<category android:name="android.intent.category.DEFAULT" />
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
<data android:scheme="bitwarden" />
|
<data android:scheme="bitwarden" />
|
||||||
</intent-filter>
|
</intent-filter>
|
||||||
|
<!-- Handle Credential Exchange transfer requests -->
|
||||||
|
<intent-filter
|
||||||
|
android:autoVerify="true"
|
||||||
|
tools:ignore="AppLinkUrlError">
|
||||||
|
<action android:name="androidx.identitycredentials.action.IMPORT_CREDENTIALS" />
|
||||||
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
|
<data
|
||||||
|
android:mimeType="application/octet-stream"
|
||||||
|
android:scheme="content"
|
||||||
|
tools:ignore="AppLinkUriRelativeFilterGroupError" />
|
||||||
|
</intent-filter>
|
||||||
</activity>
|
</activity>
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
@ -114,11 +128,11 @@
|
|||||||
android:theme="@android:style/Theme.NoDisplay" />
|
android:theme="@android:style/Theme.NoDisplay" />
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".AutofillTotpCopyActivity"
|
android:name=".AutofillCallbackActivity"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:launchMode="singleTop"
|
android:launchMode="singleTop"
|
||||||
android:noHistory="true"
|
android:noHistory="true"
|
||||||
android:theme="@style/AutofillTotpCopyTheme" />
|
android:theme="@style/AutofillCallbackTheme" />
|
||||||
|
|
||||||
<activity
|
<activity
|
||||||
android:name=".AuthCallbackActivity"
|
android:name=".AuthCallbackActivity"
|
||||||
@ -132,16 +146,6 @@
|
|||||||
<category android:name="android.intent.category.DEFAULT" />
|
<category android:name="android.intent.category.DEFAULT" />
|
||||||
<category android:name="android.intent.category.BROWSABLE" />
|
<category android:name="android.intent.category.BROWSABLE" />
|
||||||
|
|
||||||
<data
|
|
||||||
android:host="captcha-callback"
|
|
||||||
android:scheme="bitwarden" />
|
|
||||||
</intent-filter>
|
|
||||||
<intent-filter>
|
|
||||||
<action android:name="android.intent.action.VIEW" />
|
|
||||||
|
|
||||||
<category android:name="android.intent.category.DEFAULT" />
|
|
||||||
<category android:name="android.intent.category.BROWSABLE" />
|
|
||||||
|
|
||||||
<data
|
<data
|
||||||
android:host="duo-callback"
|
android:host="duo-callback"
|
||||||
android:scheme="bitwarden" />
|
android:scheme="bitwarden" />
|
||||||
@ -258,7 +262,7 @@
|
|||||||
android:name="com.x8bit.bitwarden.AutofillTileService"
|
android:name="com.x8bit.bitwarden.AutofillTileService"
|
||||||
android:exported="true"
|
android:exported="true"
|
||||||
android:icon="@drawable/ic_notification"
|
android:icon="@drawable/ic_notification"
|
||||||
android:label="@string/autofill"
|
android:label="@string/autofill_verb"
|
||||||
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
|
android:permission="android.permission.BIND_QUICK_SETTINGS_TILE"
|
||||||
tools:ignore="MissingClass">
|
tools:ignore="MissingClass">
|
||||||
<intent-filter>
|
<intent-filter>
|
||||||
|
|||||||
@ -48,6 +48,18 @@
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
"type": "android",
|
||||||
|
"info": {
|
||||||
|
"package_name": "org.ironfoxoss.ironfox.nightly",
|
||||||
|
"signatures": [
|
||||||
|
{
|
||||||
|
"build": "release",
|
||||||
|
"cert_fingerprint_sha256": "C5:E2:91:B5:A5:71:F9:C8:CD:9A:97:99:C2:C9:4E:02:EC:97:03:94:88:93:F2:CA:75:6D:67:B9:42:04:F9:04"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
{
|
{
|
||||||
"type": "android",
|
"type": "android",
|
||||||
"info": {
|
"info": {
|
||||||
|
|||||||
@ -1,8 +1,11 @@
|
|||||||
package com.x8bit.bitwarden
|
package com.x8bit.bitwarden
|
||||||
|
|
||||||
|
import android.app.ComponentCaller
|
||||||
|
import android.content.Intent
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
import com.bitwarden.annotation.OmitFromCoverage
|
import com.bitwarden.annotation.OmitFromCoverage
|
||||||
|
import com.bitwarden.ui.platform.util.validate
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An activity to be launched and then immediately closed so that the OS Shade can be collapsed
|
* An activity to be launched and then immediately closed so that the OS Shade can be collapsed
|
||||||
@ -11,7 +14,16 @@ import com.bitwarden.annotation.OmitFromCoverage
|
|||||||
@OmitFromCoverage
|
@OmitFromCoverage
|
||||||
class AccessibilityActivity : AppCompatActivity() {
|
class AccessibilityActivity : AppCompatActivity() {
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
intent = intent.validate()
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
finish()
|
finish()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun onNewIntent(intent: Intent) {
|
||||||
|
super.onNewIntent(intent.validate())
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNewIntent(intent: Intent, caller: ComponentCaller) {
|
||||||
|
super.onNewIntent(intent.validate(), caller)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,10 +1,12 @@
|
|||||||
package com.x8bit.bitwarden
|
package com.x8bit.bitwarden
|
||||||
|
|
||||||
|
import android.app.ComponentCaller
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import androidx.activity.viewModels
|
import androidx.activity.viewModels
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
import com.bitwarden.annotation.OmitFromCoverage
|
import com.bitwarden.annotation.OmitFromCoverage
|
||||||
|
import com.bitwarden.ui.platform.util.validate
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -21,6 +23,7 @@ class AuthCallbackActivity : AppCompatActivity() {
|
|||||||
private val viewModel: AuthCallbackViewModel by viewModels()
|
private val viewModel: AuthCallbackViewModel by viewModels()
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
intent = intent.validate()
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
|
||||||
viewModel.trySendAction(AuthCallbackAction.IntentReceive(intent = intent))
|
viewModel.trySendAction(AuthCallbackAction.IntentReceive(intent = intent))
|
||||||
@ -35,4 +38,12 @@ class AuthCallbackActivity : AppCompatActivity() {
|
|||||||
startActivity(intent)
|
startActivity(intent)
|
||||||
finish()
|
finish()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun onNewIntent(intent: Intent) {
|
||||||
|
super.onNewIntent(intent.validate())
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNewIntent(intent: Intent, caller: ComponentCaller) {
|
||||||
|
super.onNewIntent(intent.validate(), caller)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -3,7 +3,6 @@ package com.x8bit.bitwarden
|
|||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import com.bitwarden.ui.platform.base.BaseViewModel
|
import com.bitwarden.ui.platform.base.BaseViewModel
|
||||||
import com.x8bit.bitwarden.data.auth.repository.AuthRepository
|
import com.x8bit.bitwarden.data.auth.repository.AuthRepository
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.getCaptchaCallbackTokenResult
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.getDuoCallbackTokenResult
|
import com.x8bit.bitwarden.data.auth.repository.util.getDuoCallbackTokenResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.getSsoCallbackResult
|
import com.x8bit.bitwarden.data.auth.repository.util.getSsoCallbackResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.getWebAuthResultOrNull
|
import com.x8bit.bitwarden.data.auth.repository.util.getWebAuthResultOrNull
|
||||||
@ -27,7 +26,6 @@ class AuthCallbackViewModel @Inject constructor(
|
|||||||
private fun handleIntentReceived(action: AuthCallbackAction.IntentReceive) {
|
private fun handleIntentReceived(action: AuthCallbackAction.IntentReceive) {
|
||||||
val yubiKeyResult = action.intent.getYubiKeyResultOrNull()
|
val yubiKeyResult = action.intent.getYubiKeyResultOrNull()
|
||||||
val webAuthResult = action.intent.getWebAuthResultOrNull()
|
val webAuthResult = action.intent.getWebAuthResultOrNull()
|
||||||
val captchaCallbackTokenResult = action.intent.getCaptchaCallbackTokenResult()
|
|
||||||
val duoCallbackTokenResult = action.intent.getDuoCallbackTokenResult()
|
val duoCallbackTokenResult = action.intent.getDuoCallbackTokenResult()
|
||||||
val ssoCallbackResult = action.intent.getSsoCallbackResult()
|
val ssoCallbackResult = action.intent.getSsoCallbackResult()
|
||||||
when {
|
when {
|
||||||
@ -35,12 +33,6 @@ class AuthCallbackViewModel @Inject constructor(
|
|||||||
authRepository.setYubiKeyResult(yubiKeyResult = yubiKeyResult)
|
authRepository.setYubiKeyResult(yubiKeyResult = yubiKeyResult)
|
||||||
}
|
}
|
||||||
|
|
||||||
captchaCallbackTokenResult != null -> {
|
|
||||||
authRepository.setCaptchaCallbackTokenResult(
|
|
||||||
tokenResult = captchaCallbackTokenResult,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
duoCallbackTokenResult != null -> {
|
duoCallbackTokenResult != null -> {
|
||||||
authRepository.setDuoCallbackTokenResult(
|
authRepository.setDuoCallbackTokenResult(
|
||||||
tokenResult = duoCallbackTokenResult,
|
tokenResult = duoCallbackTokenResult,
|
||||||
|
|||||||
@ -1,10 +1,13 @@
|
|||||||
package com.x8bit.bitwarden
|
package com.x8bit.bitwarden
|
||||||
|
|
||||||
|
import android.app.ComponentCaller
|
||||||
|
import android.content.Intent
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import androidx.activity.viewModels
|
import androidx.activity.viewModels
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
import androidx.lifecycle.lifecycleScope
|
import androidx.lifecycle.lifecycleScope
|
||||||
import com.bitwarden.annotation.OmitFromCoverage
|
import com.bitwarden.annotation.OmitFromCoverage
|
||||||
|
import com.bitwarden.ui.platform.util.validate
|
||||||
import com.x8bit.bitwarden.data.autofill.manager.AutofillCompletionManager
|
import com.x8bit.bitwarden.data.autofill.manager.AutofillCompletionManager
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.flow.launchIn
|
import kotlinx.coroutines.flow.launchIn
|
||||||
@ -12,43 +15,43 @@ import kotlinx.coroutines.flow.onEach
|
|||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* An activity for copying a TOTP code to the clipboard. This is done when an autofill item is
|
* An activity that is launched to complete Autofill. This is done when an autofill item is selected
|
||||||
* selected and it requires TOTP authentication. Due to the constraints of the autofill framework,
|
* and is associated with a valid cipher. Due to the constraints of the autofill framework, we also
|
||||||
* we also have to re-fulfill the autofill for the views that are being filled.
|
* have to re-fulfill the autofill for the views that are being filled.
|
||||||
*/
|
*/
|
||||||
@OmitFromCoverage
|
@OmitFromCoverage
|
||||||
@AndroidEntryPoint
|
@AndroidEntryPoint
|
||||||
class AutofillTotpCopyActivity : AppCompatActivity() {
|
class AutofillCallbackActivity : AppCompatActivity() {
|
||||||
|
|
||||||
@Inject
|
@Inject
|
||||||
lateinit var autofillCompletionManager: AutofillCompletionManager
|
lateinit var autofillCompletionManager: AutofillCompletionManager
|
||||||
|
|
||||||
private val autofillTotpCopyViewModel: AutofillTotpCopyViewModel by viewModels()
|
private val viewModel: AutofillCallbackViewModel by viewModels()
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
intent = intent.validate()
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
|
||||||
observeViewModelEvents()
|
observeViewModelEvents()
|
||||||
|
|
||||||
autofillTotpCopyViewModel.trySendAction(
|
viewModel.trySendAction(AutofillCallbackAction.IntentReceived(intent = intent))
|
||||||
AutofillTotpCopyAction.IntentReceived(
|
}
|
||||||
intent = intent,
|
|
||||||
),
|
override fun onNewIntent(intent: Intent) {
|
||||||
)
|
super.onNewIntent(intent.validate())
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNewIntent(intent: Intent, caller: ComponentCaller) {
|
||||||
|
super.onNewIntent(intent.validate(), caller)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun observeViewModelEvents() {
|
private fun observeViewModelEvents() {
|
||||||
autofillTotpCopyViewModel
|
viewModel
|
||||||
.eventFlow
|
.eventFlow
|
||||||
.onEach { event ->
|
.onEach { event ->
|
||||||
when (event) {
|
when (event) {
|
||||||
is AutofillTotpCopyEvent.CompleteAutofill -> {
|
is AutofillCallbackEvent.CompleteAutofill -> handleCompleteAutofill(event)
|
||||||
handleCompleteAutofill(event)
|
is AutofillCallbackEvent.FinishActivity -> finishActivity()
|
||||||
}
|
|
||||||
|
|
||||||
is AutofillTotpCopyEvent.FinishActivity -> {
|
|
||||||
finishActivity()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.launchIn(lifecycleScope)
|
.launchIn(lifecycleScope)
|
||||||
@ -57,7 +60,7 @@ class AutofillTotpCopyActivity : AppCompatActivity() {
|
|||||||
/**
|
/**
|
||||||
* Complete autofill with the provided data.
|
* Complete autofill with the provided data.
|
||||||
*/
|
*/
|
||||||
private fun handleCompleteAutofill(event: AutofillTotpCopyEvent.CompleteAutofill) {
|
private fun handleCompleteAutofill(event: AutofillCallbackEvent.CompleteAutofill) {
|
||||||
autofillCompletionManager.completeAutofill(
|
autofillCompletionManager.completeAutofill(
|
||||||
activity = this,
|
activity = this,
|
||||||
cipherView = event.cipherView,
|
cipherView = event.cipherView,
|
||||||
@ -5,7 +5,7 @@ import androidx.lifecycle.viewModelScope
|
|||||||
import com.bitwarden.ui.platform.base.BaseViewModel
|
import com.bitwarden.ui.platform.base.BaseViewModel
|
||||||
import com.bitwarden.vault.CipherView
|
import com.bitwarden.vault.CipherView
|
||||||
import com.x8bit.bitwarden.data.auth.repository.AuthRepository
|
import com.x8bit.bitwarden.data.auth.repository.AuthRepository
|
||||||
import com.x8bit.bitwarden.data.autofill.util.getTotpCopyIntentOrNull
|
import com.x8bit.bitwarden.data.autofill.util.getAutofillCallbackIntentOrNull
|
||||||
import com.x8bit.bitwarden.data.platform.util.launchWithTimeout
|
import com.x8bit.bitwarden.data.platform.util.launchWithTimeout
|
||||||
import com.x8bit.bitwarden.data.vault.manager.model.GetCipherResult
|
import com.x8bit.bitwarden.data.vault.manager.model.GetCipherResult
|
||||||
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
|
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
|
||||||
@ -13,6 +13,7 @@ import com.x8bit.bitwarden.data.vault.repository.model.VaultUnlockData
|
|||||||
import com.x8bit.bitwarden.data.vault.repository.util.statusFor
|
import com.x8bit.bitwarden.data.vault.repository.util.statusFor
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -21,45 +22,63 @@ import javax.inject.Inject
|
|||||||
private const val CIPHER_WAIT_TIMEOUT_MILLIS: Long = 500
|
private const val CIPHER_WAIT_TIMEOUT_MILLIS: Long = 500
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A view model that handles logic for the [AutofillTotpCopyActivity].
|
* A view model that handles logic for the [AutofillCallbackActivity].
|
||||||
*/
|
*/
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
class AutofillTotpCopyViewModel @Inject constructor(
|
class AutofillCallbackViewModel @Inject constructor(
|
||||||
private val authRepository: AuthRepository,
|
private val authRepository: AuthRepository,
|
||||||
private val vaultRepository: VaultRepository,
|
private val vaultRepository: VaultRepository,
|
||||||
) : BaseViewModel<Unit, AutofillTotpCopyEvent, AutofillTotpCopyAction>(Unit) {
|
) : BaseViewModel<Unit, AutofillCallbackEvent, AutofillCallbackAction>(Unit) {
|
||||||
private val activeUserId: String? get() = authRepository.activeUserId
|
private val activeUserId: String? get() = authRepository.activeUserId
|
||||||
|
|
||||||
override fun handleAction(action: AutofillTotpCopyAction): Unit = when (action) {
|
override fun handleAction(action: AutofillCallbackAction): Unit = when (action) {
|
||||||
is AutofillTotpCopyAction.IntentReceived -> handleIntentReceived(action)
|
is AutofillCallbackAction.IntentReceived -> handleIntentReceived(action)
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Process the received intent and alert the activity of what to do next.
|
* Process the received intent and alert the activity of what to do next.
|
||||||
*/
|
*/
|
||||||
private fun handleIntentReceived(action: AutofillTotpCopyAction.IntentReceived) {
|
private fun handleIntentReceived(action: AutofillCallbackAction.IntentReceived) {
|
||||||
viewModelScope
|
viewModelScope
|
||||||
.launchWithTimeout(
|
.launchWithTimeout(
|
||||||
timeoutBlock = { finishActivity() },
|
timeoutBlock = {
|
||||||
|
Timber.w("Autofill -- Timeout")
|
||||||
|
finishActivity()
|
||||||
|
},
|
||||||
timeoutDuration = CIPHER_WAIT_TIMEOUT_MILLIS,
|
timeoutDuration = CIPHER_WAIT_TIMEOUT_MILLIS,
|
||||||
) {
|
) {
|
||||||
// Extract TOTP copy data from the intent.
|
// Extract TOTP copy data from the intent.
|
||||||
val cipherId = action
|
val cipherId = action
|
||||||
.intent
|
.intent
|
||||||
.getTotpCopyIntentOrNull()
|
.getAutofillCallbackIntentOrNull()
|
||||||
?.cipherId
|
?.cipherId
|
||||||
|
|
||||||
if (cipherId == null || isVaultLocked()) {
|
if (cipherId == null) {
|
||||||
|
Timber.w("Autofill -- Cipher was not provided")
|
||||||
|
finishActivity()
|
||||||
|
return@launchWithTimeout
|
||||||
|
}
|
||||||
|
if (isVaultLocked()) {
|
||||||
|
Timber.w("Autofill -- Vault is locked")
|
||||||
finishActivity()
|
finishActivity()
|
||||||
return@launchWithTimeout
|
return@launchWithTimeout
|
||||||
}
|
}
|
||||||
|
|
||||||
// Try and find the matching cipher.
|
// Try and find the matching cipher.
|
||||||
when (val result = vaultRepository.getCipher(cipherId = cipherId)) {
|
when (val result = vaultRepository.getCipher(cipherId = cipherId)) {
|
||||||
GetCipherResult.CipherNotFound -> finishActivity()
|
GetCipherResult.CipherNotFound -> {
|
||||||
is GetCipherResult.Failure -> finishActivity()
|
Timber.w("Autofill -- Cipher not found")
|
||||||
|
finishActivity()
|
||||||
|
}
|
||||||
|
|
||||||
|
is GetCipherResult.Failure -> {
|
||||||
|
Timber.w(result.error, "Autofill -- Get cipher failure")
|
||||||
|
finishActivity()
|
||||||
|
}
|
||||||
|
|
||||||
is GetCipherResult.Success -> {
|
is GetCipherResult.Success -> {
|
||||||
sendEvent(AutofillTotpCopyEvent.CompleteAutofill(result.cipherView))
|
Timber.d("Autofill -- Cipher found")
|
||||||
|
sendEvent(AutofillCallbackEvent.CompleteAutofill(result.cipherView))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -69,7 +88,7 @@ class AutofillTotpCopyViewModel @Inject constructor(
|
|||||||
* Send an event to the activity that signals it to finish.
|
* Send an event to the activity that signals it to finish.
|
||||||
*/
|
*/
|
||||||
private fun finishActivity() {
|
private fun finishActivity() {
|
||||||
sendEvent(AutofillTotpCopyEvent.FinishActivity)
|
sendEvent(AutofillCallbackEvent.FinishActivity)
|
||||||
}
|
}
|
||||||
|
|
||||||
private suspend fun isVaultLocked(): Boolean {
|
private suspend fun isVaultLocked(): Boolean {
|
||||||
@ -86,30 +105,30 @@ class AutofillTotpCopyViewModel @Inject constructor(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents actions that can be sent to the [AutofillTotpCopyViewModel].
|
* Represents actions that can be sent to the [AutofillCallbackViewModel].
|
||||||
*/
|
*/
|
||||||
sealed class AutofillTotpCopyAction {
|
sealed class AutofillCallbackAction {
|
||||||
/**
|
/**
|
||||||
* An [intent] has been received and is ready to be processed.
|
* An [intent] has been received and is ready to be processed.
|
||||||
*/
|
*/
|
||||||
data class IntentReceived(
|
data class IntentReceived(
|
||||||
val intent: Intent,
|
val intent: Intent,
|
||||||
) : AutofillTotpCopyAction()
|
) : AutofillCallbackAction()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Represents events emitted by the [AutofillTotpCopyViewModel].
|
* Represents events emitted by the [AutofillCallbackViewModel].
|
||||||
*/
|
*/
|
||||||
sealed class AutofillTotpCopyEvent {
|
sealed class AutofillCallbackEvent {
|
||||||
/**
|
/**
|
||||||
* Complete autofill with the provided [cipherView].
|
* Complete autofill with the provided [cipherView].
|
||||||
*/
|
*/
|
||||||
data class CompleteAutofill(
|
data class CompleteAutofill(
|
||||||
val cipherView: CipherView,
|
val cipherView: CipherView,
|
||||||
) : AutofillTotpCopyEvent()
|
) : AutofillCallbackEvent()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Finish the activity.
|
* Finish the activity.
|
||||||
*/
|
*/
|
||||||
data object FinishActivity : AutofillTotpCopyEvent()
|
data object FinishActivity : AutofillCallbackEvent()
|
||||||
}
|
}
|
||||||
@ -8,6 +8,7 @@ import com.x8bit.bitwarden.data.platform.manager.event.OrganizationEventManager
|
|||||||
import com.x8bit.bitwarden.data.platform.manager.network.NetworkConfigManager
|
import com.x8bit.bitwarden.data.platform.manager.network.NetworkConfigManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.network.NetworkConnectionManager
|
import com.x8bit.bitwarden.data.platform.manager.network.NetworkConnectionManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.restriction.RestrictionManager
|
import com.x8bit.bitwarden.data.platform.manager.restriction.RestrictionManager
|
||||||
|
import com.x8bit.bitwarden.data.platform.repository.EnvironmentRepository
|
||||||
import dagger.hilt.android.HiltAndroidApp
|
import dagger.hilt.android.HiltAndroidApp
|
||||||
import timber.log.Timber
|
import timber.log.Timber
|
||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
@ -38,6 +39,17 @@ class BitwardenApplication : Application() {
|
|||||||
@Inject
|
@Inject
|
||||||
lateinit var restrictionManager: RestrictionManager
|
lateinit var restrictionManager: RestrictionManager
|
||||||
|
|
||||||
|
@Inject
|
||||||
|
lateinit var environmentRepository: EnvironmentRepository
|
||||||
|
|
||||||
|
override fun onCreate() {
|
||||||
|
super.onCreate()
|
||||||
|
// These must be initialized in order to ensure that the restrictionManager does not
|
||||||
|
// override the environmentRepository values.
|
||||||
|
restrictionManager.initialize()
|
||||||
|
environmentRepository.initialize()
|
||||||
|
}
|
||||||
|
|
||||||
override fun onLowMemory() {
|
override fun onLowMemory() {
|
||||||
super.onLowMemory()
|
super.onLowMemory()
|
||||||
Timber.w("onLowMemory")
|
Timber.w("onLowMemory")
|
||||||
|
|||||||
@ -1,19 +1,21 @@
|
|||||||
package com.x8bit.bitwarden
|
package com.x8bit.bitwarden
|
||||||
|
|
||||||
|
import android.app.ComponentCaller
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.os.Build
|
import android.os.Build
|
||||||
import android.os.Bundle
|
import android.os.Bundle
|
||||||
import android.view.KeyEvent
|
import android.view.KeyEvent
|
||||||
import android.view.MotionEvent
|
import android.view.MotionEvent
|
||||||
import android.view.WindowManager
|
import android.view.WindowManager
|
||||||
import android.widget.Toast
|
|
||||||
import androidx.activity.compose.setContent
|
import androidx.activity.compose.setContent
|
||||||
import androidx.activity.viewModels
|
import androidx.activity.viewModels
|
||||||
import androidx.appcompat.app.AppCompatActivity
|
import androidx.appcompat.app.AppCompatActivity
|
||||||
import androidx.appcompat.app.AppCompatDelegate
|
import androidx.appcompat.app.AppCompatDelegate
|
||||||
|
import androidx.browser.auth.AuthTabIntent
|
||||||
import androidx.compose.runtime.Composable
|
import androidx.compose.runtime.Composable
|
||||||
import androidx.compose.runtime.getValue
|
import androidx.compose.runtime.getValue
|
||||||
import androidx.compose.runtime.remember
|
import androidx.compose.runtime.remember
|
||||||
|
import androidx.core.app.ActivityCompat
|
||||||
import androidx.core.os.LocaleListCompat
|
import androidx.core.os.LocaleListCompat
|
||||||
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen
|
||||||
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
import androidx.lifecycle.compose.collectAsStateWithLifecycle
|
||||||
@ -23,6 +25,7 @@ import com.bitwarden.annotation.OmitFromCoverage
|
|||||||
import com.bitwarden.ui.platform.base.util.EventsEffect
|
import com.bitwarden.ui.platform.base.util.EventsEffect
|
||||||
import com.bitwarden.ui.platform.theme.BitwardenTheme
|
import com.bitwarden.ui.platform.theme.BitwardenTheme
|
||||||
import com.bitwarden.ui.platform.util.setupEdgeToEdge
|
import com.bitwarden.ui.platform.util.setupEdgeToEdge
|
||||||
|
import com.bitwarden.ui.platform.util.validate
|
||||||
import com.x8bit.bitwarden.data.autofill.accessibility.manager.AccessibilityCompletionManager
|
import com.x8bit.bitwarden.data.autofill.accessibility.manager.AccessibilityCompletionManager
|
||||||
import com.x8bit.bitwarden.data.autofill.manager.AutofillActivityManager
|
import com.x8bit.bitwarden.data.autofill.manager.AutofillActivityManager
|
||||||
import com.x8bit.bitwarden.data.autofill.manager.AutofillCompletionManager
|
import com.x8bit.bitwarden.data.autofill.manager.AutofillCompletionManager
|
||||||
@ -33,9 +36,10 @@ import com.x8bit.bitwarden.ui.platform.composition.LocalManagerProvider
|
|||||||
import com.x8bit.bitwarden.ui.platform.feature.debugmenu.debugMenuDestination
|
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.manager.DebugMenuLaunchManager
|
||||||
import com.x8bit.bitwarden.ui.platform.feature.debugmenu.navigateToDebugMenuScreen
|
import com.x8bit.bitwarden.ui.platform.feature.debugmenu.navigateToDebugMenuScreen
|
||||||
import com.x8bit.bitwarden.ui.platform.feature.rootnav.ROOT_ROUTE
|
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.rootnav.rootNavDestination
|
||||||
import com.x8bit.bitwarden.ui.platform.feature.settings.appearance.model.AppLanguage
|
import com.x8bit.bitwarden.ui.platform.feature.settings.appearance.model.AppLanguage
|
||||||
|
import com.x8bit.bitwarden.ui.platform.model.AuthTabLaunchers
|
||||||
import com.x8bit.bitwarden.ui.platform.util.appLanguage
|
import com.x8bit.bitwarden.ui.platform.util.appLanguage
|
||||||
import dagger.hilt.android.AndroidEntryPoint
|
import dagger.hilt.android.AndroidEntryPoint
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
@ -66,11 +70,22 @@ class MainActivity : AppCompatActivity() {
|
|||||||
@Inject
|
@Inject
|
||||||
lateinit var debugLaunchManager: DebugMenuLaunchManager
|
lateinit var debugLaunchManager: DebugMenuLaunchManager
|
||||||
|
|
||||||
|
private val duoLauncher = AuthTabIntent.registerActivityResultLauncher(this) {
|
||||||
|
mainViewModel.trySendAction(MainAction.DuoResult(it))
|
||||||
|
}
|
||||||
|
private val ssoLauncher = AuthTabIntent.registerActivityResultLauncher(this) {
|
||||||
|
mainViewModel.trySendAction(MainAction.SsoResult(it))
|
||||||
|
}
|
||||||
|
private val webAuthnLauncher = AuthTabIntent.registerActivityResultLauncher(this) {
|
||||||
|
mainViewModel.trySendAction(MainAction.WebAuthnResult(it))
|
||||||
|
}
|
||||||
|
|
||||||
override fun onCreate(savedInstanceState: Bundle?) {
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
intent = intent.validate()
|
||||||
var shouldShowSplashScreen = true
|
var shouldShowSplashScreen = true
|
||||||
installSplashScreen().setKeepOnScreenCondition { shouldShowSplashScreen }
|
installSplashScreen().setKeepOnScreenCondition { shouldShowSplashScreen }
|
||||||
super.onCreate(savedInstanceState)
|
super.onCreate(savedInstanceState)
|
||||||
|
window.decorView.filterTouchesWhenObscured = true
|
||||||
if (savedInstanceState == null) {
|
if (savedInstanceState == null) {
|
||||||
mainViewModel.trySendAction(MainAction.ReceiveFirstIntent(intent = intent))
|
mainViewModel.trySendAction(MainAction.ReceiveFirstIntent(intent = intent))
|
||||||
}
|
}
|
||||||
@ -85,7 +100,14 @@ class MainActivity : AppCompatActivity() {
|
|||||||
SetupEventsEffect(navController = navController)
|
SetupEventsEffect(navController = navController)
|
||||||
val state by mainViewModel.stateFlow.collectAsStateWithLifecycle()
|
val state by mainViewModel.stateFlow.collectAsStateWithLifecycle()
|
||||||
updateScreenCapture(isScreenCaptureAllowed = state.isScreenCaptureAllowed)
|
updateScreenCapture(isScreenCaptureAllowed = state.isScreenCaptureAllowed)
|
||||||
LocalManagerProvider(featureFlagsState = state.featureFlagsState) {
|
LocalManagerProvider(
|
||||||
|
featureFlagsState = state.featureFlagsState,
|
||||||
|
authTabLaunchers = AuthTabLaunchers(
|
||||||
|
duo = duoLauncher,
|
||||||
|
sso = ssoLauncher,
|
||||||
|
webAuthn = webAuthnLauncher,
|
||||||
|
),
|
||||||
|
) {
|
||||||
ObserveScreenDataEffect(
|
ObserveScreenDataEffect(
|
||||||
onDataUpdate = remember(mainViewModel) {
|
onDataUpdate = remember(mainViewModel) {
|
||||||
{ mainViewModel.trySendAction(MainAction.ResumeScreenDataReceived(it)) }
|
{ mainViewModel.trySendAction(MainAction.ResumeScreenDataReceived(it)) }
|
||||||
@ -97,11 +119,11 @@ class MainActivity : AppCompatActivity() {
|
|||||||
) {
|
) {
|
||||||
NavHost(
|
NavHost(
|
||||||
navController = navController,
|
navController = navController,
|
||||||
startDestination = ROOT_ROUTE,
|
startDestination = RootNavigationRoute,
|
||||||
) {
|
) {
|
||||||
// Nothing else should end up at this top level, we just want the ability
|
// Both root navigation and debug menu exist at this top level.
|
||||||
// to have the debug menu appear on top of the rest of the app without
|
// The debug menu can appear on top of the rest of the app without
|
||||||
// interacting with the state-based navigation used by the RootNavScreen.
|
// interacting with the state-based navigation used by RootNavScreen.
|
||||||
rootNavDestination { shouldShowSplashScreen = false }
|
rootNavDestination { shouldShowSplashScreen = false }
|
||||||
debugMenuDestination(
|
debugMenuDestination(
|
||||||
onNavigateBack = { navController.popBackStack() },
|
onNavigateBack = { navController.popBackStack() },
|
||||||
@ -114,8 +136,15 @@ class MainActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
override fun onNewIntent(intent: Intent) {
|
override fun onNewIntent(intent: Intent) {
|
||||||
super.onNewIntent(intent)
|
val newIntent = intent.validate()
|
||||||
mainViewModel.trySendAction(action = MainAction.ReceiveNewIntent(intent = intent))
|
super.onNewIntent(newIntent)
|
||||||
|
mainViewModel.trySendAction(action = MainAction.ReceiveNewIntent(intent = newIntent))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onNewIntent(intent: Intent, caller: ComponentCaller) {
|
||||||
|
val newIntent = intent.validate()
|
||||||
|
super.onNewIntent(newIntent, caller)
|
||||||
|
mainViewModel.trySendAction(action = MainAction.ReceiveNewIntent(intent = newIntent))
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun onResume() {
|
override fun onResume() {
|
||||||
@ -173,12 +202,6 @@ class MainActivity : AppCompatActivity() {
|
|||||||
is MainEvent.CompleteAutofill -> handleCompleteAutofill(event)
|
is MainEvent.CompleteAutofill -> handleCompleteAutofill(event)
|
||||||
MainEvent.Recreate -> handleRecreate()
|
MainEvent.Recreate -> handleRecreate()
|
||||||
MainEvent.NavigateToDebugMenu -> navController.navigateToDebugMenuScreen()
|
MainEvent.NavigateToDebugMenu -> navController.navigateToDebugMenuScreen()
|
||||||
is MainEvent.ShowToast -> {
|
|
||||||
Toast
|
|
||||||
.makeText(baseContext, event.message.invoke(resources), Toast.LENGTH_SHORT)
|
|
||||||
.show()
|
|
||||||
}
|
|
||||||
|
|
||||||
is MainEvent.UpdateAppLocale -> {
|
is MainEvent.UpdateAppLocale -> {
|
||||||
AppCompatDelegate.setApplicationLocales(
|
AppCompatDelegate.setApplicationLocales(
|
||||||
LocaleListCompat.forLanguageTags(event.localeName),
|
LocaleListCompat.forLanguageTags(event.localeName),
|
||||||
@ -211,7 +234,7 @@ class MainActivity : AppCompatActivity() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private fun handleRecreate() {
|
private fun handleRecreate() {
|
||||||
recreate()
|
ActivityCompat.recreate(this)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun updateScreenCapture(isScreenCaptureAllowed: Boolean) {
|
private fun updateScreenCapture(isScreenCaptureAllowed: Boolean) {
|
||||||
|
|||||||
@ -2,16 +2,24 @@ package com.x8bit.bitwarden
|
|||||||
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.os.Parcelable
|
import android.os.Parcelable
|
||||||
|
import androidx.browser.auth.AuthTabIntent
|
||||||
import androidx.lifecycle.SavedStateHandle
|
import androidx.lifecycle.SavedStateHandle
|
||||||
import androidx.lifecycle.viewModelScope
|
import androidx.lifecycle.viewModelScope
|
||||||
|
import com.bitwarden.core.data.manager.toast.ToastManager
|
||||||
|
import com.bitwarden.cxf.model.ImportCredentialsRequestData
|
||||||
|
import com.bitwarden.cxf.util.getProviderImportCredentialsRequest
|
||||||
import com.bitwarden.ui.platform.base.BaseViewModel
|
import com.bitwarden.ui.platform.base.BaseViewModel
|
||||||
import com.bitwarden.ui.platform.feature.settings.appearance.model.AppTheme
|
import com.bitwarden.ui.platform.feature.settings.appearance.model.AppTheme
|
||||||
import com.bitwarden.ui.util.Text
|
import com.bitwarden.ui.platform.manager.share.ShareManager
|
||||||
import com.bitwarden.ui.util.asText
|
import com.bitwarden.ui.platform.model.TotpData
|
||||||
|
import com.bitwarden.ui.platform.resource.BitwardenString
|
||||||
import com.bitwarden.vault.CipherView
|
import com.bitwarden.vault.CipherView
|
||||||
import com.x8bit.bitwarden.data.auth.manager.AddTotpItemFromAuthenticatorManager
|
import com.x8bit.bitwarden.data.auth.manager.AddTotpItemFromAuthenticatorManager
|
||||||
import com.x8bit.bitwarden.data.auth.repository.AuthRepository
|
import com.x8bit.bitwarden.data.auth.repository.AuthRepository
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.EmailTokenResult
|
import com.x8bit.bitwarden.data.auth.repository.model.EmailTokenResult
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.util.getDuoCallbackTokenResult
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.util.getSsoCallbackResult
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.util.getWebAuthResult
|
||||||
import com.x8bit.bitwarden.data.auth.util.getCompleteRegistrationDataIntentOrNull
|
import com.x8bit.bitwarden.data.auth.util.getCompleteRegistrationDataIntentOrNull
|
||||||
import com.x8bit.bitwarden.data.auth.util.getPasswordlessRequestDataIntentOrNull
|
import com.x8bit.bitwarden.data.auth.util.getPasswordlessRequestDataIntentOrNull
|
||||||
import com.x8bit.bitwarden.data.autofill.accessibility.manager.AccessibilitySelectionManager
|
import com.x8bit.bitwarden.data.autofill.accessibility.manager.AccessibilitySelectionManager
|
||||||
@ -22,13 +30,12 @@ import com.x8bit.bitwarden.data.credentials.manager.BitwardenCredentialManager
|
|||||||
import com.x8bit.bitwarden.data.credentials.util.getCreateCredentialRequestOrNull
|
import com.x8bit.bitwarden.data.credentials.util.getCreateCredentialRequestOrNull
|
||||||
import com.x8bit.bitwarden.data.credentials.util.getFido2AssertionRequestOrNull
|
import com.x8bit.bitwarden.data.credentials.util.getFido2AssertionRequestOrNull
|
||||||
import com.x8bit.bitwarden.data.credentials.util.getGetCredentialsRequestOrNull
|
import com.x8bit.bitwarden.data.credentials.util.getGetCredentialsRequestOrNull
|
||||||
|
import com.x8bit.bitwarden.data.credentials.util.getProviderGetPasswordRequestOrNull
|
||||||
import com.x8bit.bitwarden.data.platform.manager.AppResumeManager
|
import com.x8bit.bitwarden.data.platform.manager.AppResumeManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.FeatureFlagManager
|
|
||||||
import com.x8bit.bitwarden.data.platform.manager.SpecialCircumstanceManager
|
import com.x8bit.bitwarden.data.platform.manager.SpecialCircumstanceManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.garbage.GarbageCollectionManager
|
import com.x8bit.bitwarden.data.platform.manager.garbage.GarbageCollectionManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.model.AppResumeScreenData
|
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.CompleteRegistrationData
|
||||||
import com.x8bit.bitwarden.data.platform.manager.model.FlagKey
|
|
||||||
import com.x8bit.bitwarden.data.platform.manager.model.SpecialCircumstance
|
import com.x8bit.bitwarden.data.platform.manager.model.SpecialCircumstance
|
||||||
import com.x8bit.bitwarden.data.platform.repository.EnvironmentRepository
|
import com.x8bit.bitwarden.data.platform.repository.EnvironmentRepository
|
||||||
import com.x8bit.bitwarden.data.platform.repository.SettingsRepository
|
import com.x8bit.bitwarden.data.platform.repository.SettingsRepository
|
||||||
@ -36,20 +43,21 @@ import com.x8bit.bitwarden.data.platform.util.isAddTotpLoginItemFromAuthenticato
|
|||||||
import com.x8bit.bitwarden.data.vault.manager.model.VaultStateEvent
|
import com.x8bit.bitwarden.data.vault.manager.model.VaultStateEvent
|
||||||
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
|
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
|
||||||
import com.x8bit.bitwarden.ui.platform.feature.settings.appearance.model.AppLanguage
|
import com.x8bit.bitwarden.ui.platform.feature.settings.appearance.model.AppLanguage
|
||||||
import com.x8bit.bitwarden.ui.platform.manager.intent.IntentManager
|
|
||||||
import com.x8bit.bitwarden.ui.platform.model.FeatureFlagsState
|
import com.x8bit.bitwarden.ui.platform.model.FeatureFlagsState
|
||||||
import com.x8bit.bitwarden.ui.platform.util.isAccountSecurityShortcut
|
import com.x8bit.bitwarden.ui.platform.util.isAccountSecurityShortcut
|
||||||
import com.x8bit.bitwarden.ui.platform.util.isMyVaultShortcut
|
import com.x8bit.bitwarden.ui.platform.util.isMyVaultShortcut
|
||||||
import com.x8bit.bitwarden.ui.platform.util.isPasswordGeneratorShortcut
|
import com.x8bit.bitwarden.ui.platform.util.isPasswordGeneratorShortcut
|
||||||
import com.x8bit.bitwarden.ui.vault.model.TotpData
|
|
||||||
import com.x8bit.bitwarden.ui.vault.util.getTotpDataOrNull
|
import com.x8bit.bitwarden.ui.vault.util.getTotpDataOrNull
|
||||||
import dagger.hilt.android.lifecycle.HiltViewModel
|
import dagger.hilt.android.lifecycle.HiltViewModel
|
||||||
import kotlinx.coroutines.delay
|
import kotlinx.coroutines.FlowPreview
|
||||||
|
import kotlinx.coroutines.flow.debounce
|
||||||
import kotlinx.coroutines.flow.distinctUntilChanged
|
import kotlinx.coroutines.flow.distinctUntilChanged
|
||||||
import kotlinx.coroutines.flow.drop
|
import kotlinx.coroutines.flow.drop
|
||||||
|
import kotlinx.coroutines.flow.filter
|
||||||
import kotlinx.coroutines.flow.first
|
import kotlinx.coroutines.flow.first
|
||||||
import kotlinx.coroutines.flow.launchIn
|
import kotlinx.coroutines.flow.launchIn
|
||||||
import kotlinx.coroutines.flow.map
|
import kotlinx.coroutines.flow.map
|
||||||
|
import kotlinx.coroutines.flow.merge
|
||||||
import kotlinx.coroutines.flow.onEach
|
import kotlinx.coroutines.flow.onEach
|
||||||
import kotlinx.coroutines.flow.update
|
import kotlinx.coroutines.flow.update
|
||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
@ -58,22 +66,22 @@ import java.time.Clock
|
|||||||
import javax.inject.Inject
|
import javax.inject.Inject
|
||||||
|
|
||||||
private const val SPECIAL_CIRCUMSTANCE_KEY = "special-circumstance"
|
private const val SPECIAL_CIRCUMSTANCE_KEY = "special-circumstance"
|
||||||
private const val ANIMATION_REFRESH_DELAY = 500L
|
private const val ANIMATION_DEBOUNCE_DELAY_MS = 500L
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* A view model that helps launch actions for the [MainActivity].
|
* A view model that helps launch actions for the [MainActivity].
|
||||||
*/
|
*/
|
||||||
|
@OptIn(FlowPreview::class)
|
||||||
@Suppress("LongParameterList", "TooManyFunctions")
|
@Suppress("LongParameterList", "TooManyFunctions")
|
||||||
@HiltViewModel
|
@HiltViewModel
|
||||||
class MainViewModel @Inject constructor(
|
class MainViewModel @Inject constructor(
|
||||||
accessibilitySelectionManager: AccessibilitySelectionManager,
|
accessibilitySelectionManager: AccessibilitySelectionManager,
|
||||||
autofillSelectionManager: AutofillSelectionManager,
|
autofillSelectionManager: AutofillSelectionManager,
|
||||||
featureFlagManager: FeatureFlagManager,
|
|
||||||
private val addTotpItemFromAuthenticatorManager: AddTotpItemFromAuthenticatorManager,
|
private val addTotpItemFromAuthenticatorManager: AddTotpItemFromAuthenticatorManager,
|
||||||
private val specialCircumstanceManager: SpecialCircumstanceManager,
|
private val specialCircumstanceManager: SpecialCircumstanceManager,
|
||||||
private val garbageCollectionManager: GarbageCollectionManager,
|
private val garbageCollectionManager: GarbageCollectionManager,
|
||||||
private val bitwardenCredentialManager: BitwardenCredentialManager,
|
private val bitwardenCredentialManager: BitwardenCredentialManager,
|
||||||
private val intentManager: IntentManager,
|
private val shareManager: ShareManager,
|
||||||
private val settingsRepository: SettingsRepository,
|
private val settingsRepository: SettingsRepository,
|
||||||
private val vaultRepository: VaultRepository,
|
private val vaultRepository: VaultRepository,
|
||||||
private val authRepository: AuthRepository,
|
private val authRepository: AuthRepository,
|
||||||
@ -81,13 +89,11 @@ class MainViewModel @Inject constructor(
|
|||||||
private val savedStateHandle: SavedStateHandle,
|
private val savedStateHandle: SavedStateHandle,
|
||||||
private val appResumeManager: AppResumeManager,
|
private val appResumeManager: AppResumeManager,
|
||||||
private val clock: Clock,
|
private val clock: Clock,
|
||||||
|
private val toastManager: ToastManager,
|
||||||
) : BaseViewModel<MainState, MainEvent, MainAction>(
|
) : BaseViewModel<MainState, MainEvent, MainAction>(
|
||||||
initialState = MainState(
|
initialState = MainState(
|
||||||
theme = settingsRepository.appTheme,
|
theme = settingsRepository.appTheme,
|
||||||
isScreenCaptureAllowed = settingsRepository.isScreenCaptureAllowed,
|
isScreenCaptureAllowed = settingsRepository.isScreenCaptureAllowed,
|
||||||
isErrorReportingDialogEnabled = featureFlagManager.getFeatureFlag(
|
|
||||||
key = FlagKey.MobileErrorReporting,
|
|
||||||
),
|
|
||||||
isDynamicColorsEnabled = settingsRepository.isDynamicColorsEnabled,
|
isDynamicColorsEnabled = settingsRepository.isDynamicColorsEnabled,
|
||||||
),
|
),
|
||||||
) {
|
) {
|
||||||
@ -106,12 +112,6 @@ class MainViewModel @Inject constructor(
|
|||||||
.onEach { specialCircumstance = it }
|
.onEach { specialCircumstance = it }
|
||||||
.launchIn(viewModelScope)
|
.launchIn(viewModelScope)
|
||||||
|
|
||||||
featureFlagManager
|
|
||||||
.getFeatureFlagFlow(key = FlagKey.MobileErrorReporting)
|
|
||||||
.map { MainAction.Internal.OnMobileErrorReportingReceive(it) }
|
|
||||||
.onEach(::sendAction)
|
|
||||||
.launchIn(viewModelScope)
|
|
||||||
|
|
||||||
accessibilitySelectionManager
|
accessibilitySelectionManager
|
||||||
.accessibilitySelectionFlow
|
.accessibilitySelectionFlow
|
||||||
.map { MainAction.Internal.AccessibilitySelectionReceive(it) }
|
.map { MainAction.Internal.AccessibilitySelectionReceive(it) }
|
||||||
@ -145,36 +145,23 @@ class MainViewModel @Inject constructor(
|
|||||||
.onEach(::trySendAction)
|
.onEach(::trySendAction)
|
||||||
.launchIn(viewModelScope)
|
.launchIn(viewModelScope)
|
||||||
|
|
||||||
authRepository
|
merge(
|
||||||
.userStateFlow
|
authRepository
|
||||||
.drop(count = 1)
|
.userStateFlow
|
||||||
// Trigger an action whenever the current user changes or we go into/out of a pending
|
.drop(count = 1)
|
||||||
// account state (which acts like switching to a temporary user).
|
// Trigger an action whenever the current user changes or we go into/out of a
|
||||||
.map { it?.activeUserId to it?.hasPendingAccountAddition }
|
// pending account state (which acts like switching to a temporary user).
|
||||||
.distinctUntilChanged()
|
.map { it?.activeUserId to it?.hasPendingAccountAddition }
|
||||||
.onEach {
|
.distinctUntilChanged(),
|
||||||
// Switching between account states often involves some kind of animation (ex:
|
vaultRepository
|
||||||
// account switcher) that we might want to give time to finish before triggering
|
.vaultStateEventFlow
|
||||||
// a refresh.
|
.filter { it is VaultStateEvent.Locked },
|
||||||
delay(ANIMATION_REFRESH_DELAY)
|
)
|
||||||
trySendAction(MainAction.Internal.CurrentUserStateChange)
|
// This debounce ensure we do not emit multiple times rapidly and also acts as a short
|
||||||
}
|
// delay to give animations time to finish (ex: account switcher).
|
||||||
.launchIn(viewModelScope)
|
.debounce(timeoutMillis = ANIMATION_DEBOUNCE_DELAY_MS)
|
||||||
|
.map { MainAction.Internal.CurrentUserOrVaultStateChange }
|
||||||
vaultRepository
|
.onEach(::sendAction)
|
||||||
.vaultStateEventFlow
|
|
||||||
.onEach {
|
|
||||||
when (it) {
|
|
||||||
is VaultStateEvent.Locked -> {
|
|
||||||
// Similar to account switching, triggering this action too soon can
|
|
||||||
// interfere with animations or navigation logic, so we will delay slightly.
|
|
||||||
delay(ANIMATION_REFRESH_DELAY)
|
|
||||||
trySendAction(MainAction.Internal.VaultUnlockStateChange)
|
|
||||||
}
|
|
||||||
|
|
||||||
is VaultStateEvent.Unlocked -> Unit
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.launchIn(viewModelScope)
|
.launchIn(viewModelScope)
|
||||||
|
|
||||||
// On app launch, mark all active users as having previously logged in.
|
// On app launch, mark all active users as having previously logged in.
|
||||||
@ -198,6 +185,9 @@ class MainViewModel @Inject constructor(
|
|||||||
MainAction.OpenDebugMenu -> handleOpenDebugMenu()
|
MainAction.OpenDebugMenu -> handleOpenDebugMenu()
|
||||||
is MainAction.ResumeScreenDataReceived -> handleAppResumeDataUpdated(action)
|
is MainAction.ResumeScreenDataReceived -> handleAppResumeDataUpdated(action)
|
||||||
is MainAction.AppSpecificLanguageUpdate -> handleAppSpecificLanguageUpdate(action)
|
is MainAction.AppSpecificLanguageUpdate -> handleAppSpecificLanguageUpdate(action)
|
||||||
|
is MainAction.DuoResult -> handleDuoResult(action)
|
||||||
|
is MainAction.SsoResult -> handleSsoResult(action)
|
||||||
|
is MainAction.WebAuthnResult -> handleWebAuthnResult(action)
|
||||||
is MainAction.Internal -> handleInternalAction(action)
|
is MainAction.Internal -> handleInternalAction(action)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -212,22 +202,13 @@ class MainViewModel @Inject constructor(
|
|||||||
handleAutofillSelectionReceive(action)
|
handleAutofillSelectionReceive(action)
|
||||||
}
|
}
|
||||||
|
|
||||||
is MainAction.Internal.CurrentUserStateChange -> handleCurrentUserStateChange()
|
is MainAction.Internal.CurrentUserOrVaultStateChange -> {
|
||||||
|
handleCurrentUserOrVaultStateChange()
|
||||||
|
}
|
||||||
|
|
||||||
is MainAction.Internal.ScreenCaptureUpdate -> handleScreenCaptureUpdate(action)
|
is MainAction.Internal.ScreenCaptureUpdate -> handleScreenCaptureUpdate(action)
|
||||||
is MainAction.Internal.ThemeUpdate -> handleAppThemeUpdated(action)
|
is MainAction.Internal.ThemeUpdate -> handleAppThemeUpdated(action)
|
||||||
is MainAction.Internal.VaultUnlockStateChange -> handleVaultUnlockStateChange()
|
|
||||||
is MainAction.Internal.DynamicColorsUpdate -> handleDynamicColorsUpdate(action)
|
is MainAction.Internal.DynamicColorsUpdate -> handleDynamicColorsUpdate(action)
|
||||||
is MainAction.Internal.OnMobileErrorReportingReceive -> {
|
|
||||||
handleOnMobileErrorReportingReceive(action)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun handleOnMobileErrorReportingReceive(
|
|
||||||
action: MainAction.Internal.OnMobileErrorReportingReceive,
|
|
||||||
) {
|
|
||||||
mutableStateFlow.update {
|
|
||||||
it.copy(isErrorReportingDialogEnabled = action.isErrorReportingEnabled)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -235,6 +216,20 @@ class MainViewModel @Inject constructor(
|
|||||||
settingsRepository.appLanguage = action.appLanguage
|
settingsRepository.appLanguage = action.appLanguage
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun handleDuoResult(action: MainAction.DuoResult) {
|
||||||
|
authRepository.setDuoCallbackTokenResult(
|
||||||
|
tokenResult = action.authResult.getDuoCallbackTokenResult(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleSsoResult(action: MainAction.SsoResult) {
|
||||||
|
authRepository.setSsoCallbackResult(result = action.authResult.getSsoCallbackResult())
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun handleWebAuthnResult(action: MainAction.WebAuthnResult) {
|
||||||
|
authRepository.setWebAuthResult(webAuthResult = action.authResult.getWebAuthResult())
|
||||||
|
}
|
||||||
|
|
||||||
private fun handleAppResumeDataUpdated(action: MainAction.ResumeScreenDataReceived) {
|
private fun handleAppResumeDataUpdated(action: MainAction.ResumeScreenDataReceived) {
|
||||||
when (val data = action.screenResumeData) {
|
when (val data = action.screenResumeData) {
|
||||||
null -> appResumeManager.clearResumeScreen()
|
null -> appResumeManager.clearResumeScreen()
|
||||||
@ -260,8 +255,9 @@ class MainViewModel @Inject constructor(
|
|||||||
sendEvent(MainEvent.CompleteAutofill(cipherView = action.cipherView))
|
sendEvent(MainEvent.CompleteAutofill(cipherView = action.cipherView))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleCurrentUserStateChange() {
|
private fun handleCurrentUserOrVaultStateChange() {
|
||||||
recreateUiAndGarbageCollect()
|
sendEvent(MainEvent.Recreate)
|
||||||
|
garbageCollectionManager.tryCollect()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleScreenCaptureUpdate(action: MainAction.Internal.ScreenCaptureUpdate) {
|
private fun handleScreenCaptureUpdate(action: MainAction.Internal.ScreenCaptureUpdate) {
|
||||||
@ -273,10 +269,6 @@ class MainViewModel @Inject constructor(
|
|||||||
sendEvent(MainEvent.UpdateAppTheme(osTheme = action.theme.osValue))
|
sendEvent(MainEvent.UpdateAppTheme(osTheme = action.theme.osValue))
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleVaultUnlockStateChange() {
|
|
||||||
recreateUiAndGarbageCollect()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun handleDynamicColorsUpdate(action: MainAction.Internal.DynamicColorsUpdate) {
|
private fun handleDynamicColorsUpdate(action: MainAction.Internal.DynamicColorsUpdate) {
|
||||||
mutableStateFlow.update { it.copy(isDynamicColorsEnabled = action.isDynamicColorsEnabled) }
|
mutableStateFlow.update { it.copy(isDynamicColorsEnabled = action.isDynamicColorsEnabled) }
|
||||||
}
|
}
|
||||||
@ -303,7 +295,7 @@ class MainViewModel @Inject constructor(
|
|||||||
val passwordlessRequestData = intent.getPasswordlessRequestDataIntentOrNull()
|
val passwordlessRequestData = intent.getPasswordlessRequestDataIntentOrNull()
|
||||||
val autofillSaveItem = intent.getAutofillSaveItemOrNull()
|
val autofillSaveItem = intent.getAutofillSaveItemOrNull()
|
||||||
val autofillSelectionData = intent.getAutofillSelectionDataOrNull()
|
val autofillSelectionData = intent.getAutofillSelectionDataOrNull()
|
||||||
val shareData = intentManager.getShareDataFromIntent(intent)
|
val shareData = shareManager.getShareDataOrNull(intent = intent)
|
||||||
val totpData: TotpData? =
|
val totpData: TotpData? =
|
||||||
// First grab TOTP URI directly from the intent data:
|
// First grab TOTP URI directly from the intent data:
|
||||||
intent.getTotpDataOrNull()
|
intent.getTotpDataOrNull()
|
||||||
@ -325,6 +317,8 @@ class MainViewModel @Inject constructor(
|
|||||||
val createCredentialRequest = intent.getCreateCredentialRequestOrNull()
|
val createCredentialRequest = intent.getCreateCredentialRequestOrNull()
|
||||||
val getCredentialsRequest = intent.getGetCredentialsRequestOrNull()
|
val getCredentialsRequest = intent.getGetCredentialsRequestOrNull()
|
||||||
val fido2AssertCredentialRequest = intent.getFido2AssertionRequestOrNull()
|
val fido2AssertCredentialRequest = intent.getFido2AssertionRequestOrNull()
|
||||||
|
val providerGetPasswordRequest = intent.getProviderGetPasswordRequestOrNull()
|
||||||
|
val importCredentialsRequest = intent.getProviderImportCredentialsRequest()
|
||||||
when {
|
when {
|
||||||
passwordlessRequestData != null -> {
|
passwordlessRequestData != null -> {
|
||||||
authRepository.activeUserId?.let {
|
authRepository.activeUserId?.let {
|
||||||
@ -415,6 +409,19 @@ class MainViewModel @Inject constructor(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
providerGetPasswordRequest != null -> {
|
||||||
|
// Set the user's verification status when a new GetPassword request is
|
||||||
|
// received to force explicit verification if the user's vault is
|
||||||
|
// unlocked when the request is received.
|
||||||
|
bitwardenCredentialManager.isUserVerified =
|
||||||
|
providerGetPasswordRequest.isUserPreVerified
|
||||||
|
|
||||||
|
specialCircumstanceManager.specialCircumstance =
|
||||||
|
SpecialCircumstance.ProviderGetPasswordRequest(
|
||||||
|
passwordGetRequest = providerGetPasswordRequest,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
getCredentialsRequest != null -> {
|
getCredentialsRequest != null -> {
|
||||||
specialCircumstanceManager.specialCircumstance =
|
specialCircumstanceManager.specialCircumstance =
|
||||||
SpecialCircumstance.ProviderGetCredentials(
|
SpecialCircumstance.ProviderGetCredentials(
|
||||||
@ -435,12 +442,17 @@ class MainViewModel @Inject constructor(
|
|||||||
specialCircumstanceManager.specialCircumstance =
|
specialCircumstanceManager.specialCircumstance =
|
||||||
SpecialCircumstance.AccountSecurityShortcut
|
SpecialCircumstance.AccountSecurityShortcut
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun recreateUiAndGarbageCollect() {
|
importCredentialsRequest != null -> {
|
||||||
sendEvent(MainEvent.Recreate)
|
specialCircumstanceManager.specialCircumstance =
|
||||||
garbageCollectionManager.tryCollect()
|
SpecialCircumstance.CredentialExchangeExport(
|
||||||
|
data = ImportCredentialsRequestData(
|
||||||
|
uri = importCredentialsRequest.uri,
|
||||||
|
requestJson = importCredentialsRequest.request.requestJson,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun handleCompleteRegistrationData(data: CompleteRegistrationData) {
|
private fun handleCompleteRegistrationData(data: CompleteRegistrationData) {
|
||||||
@ -455,15 +467,15 @@ class MainViewModel @Inject constructor(
|
|||||||
)
|
)
|
||||||
when (emailTokenResult) {
|
when (emailTokenResult) {
|
||||||
is EmailTokenResult.Error -> {
|
is EmailTokenResult.Error -> {
|
||||||
sendEvent(
|
emailTokenResult
|
||||||
MainEvent.ShowToast(
|
.message
|
||||||
message = emailTokenResult
|
?.let { toastManager.show(message = it) }
|
||||||
.message
|
?: run {
|
||||||
?.asText()
|
toastManager.show(
|
||||||
?: R.string.there_was_an_issue_validating_the_registration_token
|
messageId = BitwardenString
|
||||||
.asText(),
|
.there_was_an_issue_validating_the_registration_token,
|
||||||
),
|
)
|
||||||
)
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
EmailTokenResult.Expired -> {
|
EmailTokenResult.Expired -> {
|
||||||
@ -495,21 +507,33 @@ data class MainState(
|
|||||||
val theme: AppTheme,
|
val theme: AppTheme,
|
||||||
val isScreenCaptureAllowed: Boolean,
|
val isScreenCaptureAllowed: Boolean,
|
||||||
val isDynamicColorsEnabled: Boolean,
|
val isDynamicColorsEnabled: Boolean,
|
||||||
private val isErrorReportingDialogEnabled: Boolean,
|
|
||||||
) : Parcelable {
|
) : Parcelable {
|
||||||
/**
|
/**
|
||||||
* Contains all feature flags that are available to the UI.
|
* Contains all feature flags that are available to the UI.
|
||||||
*/
|
*/
|
||||||
val featureFlagsState: FeatureFlagsState
|
val featureFlagsState: FeatureFlagsState
|
||||||
get() = FeatureFlagsState(
|
get() = FeatureFlagsState
|
||||||
isErrorReportingDialogEnabled = isErrorReportingDialogEnabled,
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Models actions for the [MainActivity].
|
* Models actions for the [MainActivity].
|
||||||
*/
|
*/
|
||||||
sealed class MainAction {
|
sealed class MainAction {
|
||||||
|
/**
|
||||||
|
* Receive the result from the Duo login flow.
|
||||||
|
*/
|
||||||
|
data class DuoResult(val authResult: AuthTabIntent.AuthResult) : MainAction()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Receive the result from the SSO login flow.
|
||||||
|
*/
|
||||||
|
data class SsoResult(val authResult: AuthTabIntent.AuthResult) : MainAction()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Receive the result from the WebAuthn login flow.
|
||||||
|
*/
|
||||||
|
data class WebAuthnResult(val authResult: AuthTabIntent.AuthResult) : MainAction()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Receive first Intent by the application.
|
* Receive first Intent by the application.
|
||||||
*/
|
*/
|
||||||
@ -548,13 +572,6 @@ sealed class MainAction {
|
|||||||
val cipherView: CipherView,
|
val cipherView: CipherView,
|
||||||
) : Internal()
|
) : Internal()
|
||||||
|
|
||||||
/**
|
|
||||||
* Indicates the Mobile Error Reporting feature flag has been updated.
|
|
||||||
*/
|
|
||||||
data class OnMobileErrorReportingReceive(
|
|
||||||
val isErrorReportingEnabled: Boolean,
|
|
||||||
) : Internal()
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Indicates the user has manually selected the given [cipherView] for autofill.
|
* Indicates the user has manually selected the given [cipherView] for autofill.
|
||||||
*/
|
*/
|
||||||
@ -563,9 +580,9 @@ sealed class MainAction {
|
|||||||
) : Internal()
|
) : Internal()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Indicates a relevant change in the current user state.
|
* Indicates a relevant change in the current user state or vault locked state.
|
||||||
*/
|
*/
|
||||||
data object CurrentUserStateChange : Internal()
|
data object CurrentUserOrVaultStateChange : Internal()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Indicates that the screen capture state has changed.
|
* Indicates that the screen capture state has changed.
|
||||||
@ -581,11 +598,6 @@ sealed class MainAction {
|
|||||||
val theme: AppTheme,
|
val theme: AppTheme,
|
||||||
) : Internal()
|
) : Internal()
|
||||||
|
|
||||||
/**
|
|
||||||
* Indicates a relevant change in the current vault lock state.
|
|
||||||
*/
|
|
||||||
data object VaultUnlockStateChange : Internal()
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Indicates that the dynamic colors state has changed.
|
* Indicates that the dynamic colors state has changed.
|
||||||
*/
|
*/
|
||||||
@ -621,11 +633,6 @@ sealed class MainEvent {
|
|||||||
*/
|
*/
|
||||||
data object NavigateToDebugMenu : MainEvent()
|
data object NavigateToDebugMenu : MainEvent()
|
||||||
|
|
||||||
/**
|
|
||||||
* Show a toast with the given [message].
|
|
||||||
*/
|
|
||||||
data class ShowToast(val message: Text) : MainEvent()
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Indicates that the app language has been updated.
|
* Indicates that the app language has been updated.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
package com.x8bit.bitwarden.data.auth.datasource.disk
|
package com.x8bit.bitwarden.data.auth.datasource.disk
|
||||||
|
|
||||||
|
import com.bitwarden.network.model.AccountKeysJson
|
||||||
import com.bitwarden.network.model.SyncResponseJson
|
import com.bitwarden.network.model.SyncResponseJson
|
||||||
import com.bitwarden.network.provider.AppIdProvider
|
import com.bitwarden.network.provider.AppIdProvider
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.disk.model.AccountTokensJson
|
import com.x8bit.bitwarden.data.auth.datasource.disk.model.AccountTokensJson
|
||||||
@ -126,13 +127,34 @@ interface AuthDiskSource : AppIdProvider {
|
|||||||
/**
|
/**
|
||||||
* Retrieves a private key using a [userId].
|
* Retrieves a private key using a [userId].
|
||||||
*/
|
*/
|
||||||
|
@Deprecated(
|
||||||
|
message = "Use getAccountKeys instead.",
|
||||||
|
replaceWith = ReplaceWith("getAccountKeys"),
|
||||||
|
)
|
||||||
fun getPrivateKey(userId: String): String?
|
fun getPrivateKey(userId: String): String?
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stores a private key using a [userId].
|
* Stores a private key using a [userId].
|
||||||
*/
|
*/
|
||||||
|
@Deprecated(
|
||||||
|
message = "Use storeAccountKeys instead.",
|
||||||
|
replaceWith = ReplaceWith("storeAccountKeys"),
|
||||||
|
)
|
||||||
fun storePrivateKey(userId: String, privateKey: String?)
|
fun storePrivateKey(userId: String, privateKey: String?)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the profile account keys for the given [userId].
|
||||||
|
*/
|
||||||
|
fun getAccountKeys(userId: String): AccountKeysJson?
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stores the profile account keys for the given [userId].
|
||||||
|
*/
|
||||||
|
fun storeAccountKeys(
|
||||||
|
userId: String,
|
||||||
|
accountKeys: AccountKeysJson?,
|
||||||
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves a user auto-unlock key for the given [userId].
|
* Retrieves a user auto-unlock key for the given [userId].
|
||||||
*/
|
*/
|
||||||
@ -189,30 +211,64 @@ interface AuthDiskSource : AppIdProvider {
|
|||||||
/**
|
/**
|
||||||
* Gets the flow for the biometrics key for the given [userId].
|
* Gets the flow for the biometrics key for the given [userId].
|
||||||
*/
|
*/
|
||||||
fun getUserBiometicUnlockKeyFlow(userId: String): Flow<String?>
|
fun getUserBiometricUnlockKeyFlow(userId: String): Flow<String?>
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves a pin-protected user key for the given [userId].
|
* Retrieves a pin-protected user key for the given [userId].
|
||||||
*/
|
*/
|
||||||
|
@Deprecated(
|
||||||
|
message = "Use getPinProtectedUserKeyEnvelope instead.",
|
||||||
|
replaceWith = ReplaceWith("getPinProtectedUserKeyEnvelope"),
|
||||||
|
)
|
||||||
fun getPinProtectedUserKey(userId: String): String?
|
fun getPinProtectedUserKey(userId: String): String?
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves a pin-protected user key envelope for the given [userId].
|
||||||
|
*/
|
||||||
|
fun getPinProtectedUserKeyEnvelope(userId: String): String?
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stores a pin-protected user key for the given [userId].
|
* Stores a pin-protected user key for the given [userId].
|
||||||
*
|
*
|
||||||
* When [inMemoryOnly] is `true`, the value will only be available via a call to
|
* When [inMemoryOnly] is `true`, the value will only be available via a call to
|
||||||
* [getPinProtectedUserKey] during the current app session.
|
* [getPinProtectedUserKey] during the current app session.
|
||||||
*/
|
*/
|
||||||
|
@Deprecated(
|
||||||
|
message = "Use storePinProtectedUserKeyEnvelope instead.",
|
||||||
|
replaceWith = ReplaceWith("storePinProtectedUserKeyEnvelope"),
|
||||||
|
)
|
||||||
fun storePinProtectedUserKey(
|
fun storePinProtectedUserKey(
|
||||||
userId: String,
|
userId: String,
|
||||||
pinProtectedUserKey: String?,
|
pinProtectedUserKey: String?,
|
||||||
inMemoryOnly: Boolean = false,
|
inMemoryOnly: Boolean = false,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stores a pin-protected user key envelope for the given [userId].
|
||||||
|
*
|
||||||
|
* When [inMemoryOnly] is `true`, the value will only be available via a call to
|
||||||
|
* [getPinProtectedUserKeyEnvelope] during the current app session.
|
||||||
|
*/
|
||||||
|
fun storePinProtectedUserKeyEnvelope(
|
||||||
|
userId: String,
|
||||||
|
pinProtectedUserKeyEnvelope: String?,
|
||||||
|
inMemoryOnly: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves a flow for the pin-protected user key for the given [userId].
|
* Retrieves a flow for the pin-protected user key for the given [userId].
|
||||||
*/
|
*/
|
||||||
|
@Deprecated(
|
||||||
|
message = "Use getPinProtectedUserKeyEnvelopeFlow instead.",
|
||||||
|
replaceWith = ReplaceWith("getPinProtectedUserKeyEnvelopeFlow"),
|
||||||
|
)
|
||||||
fun getPinProtectedUserKeyFlow(userId: String): Flow<String?>
|
fun getPinProtectedUserKeyFlow(userId: String): Flow<String?>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves a flow for the pin-protected user key envelope for the given [userId].
|
||||||
|
*/
|
||||||
|
fun getPinProtectedUserKeyEnvelopeFlow(userId: String): Flow<String?>
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Gets a two-factor auth token using a user's [email].
|
* Gets a two-factor auth token using a user's [email].
|
||||||
*/
|
*/
|
||||||
|
|||||||
@ -4,6 +4,7 @@ import android.content.SharedPreferences
|
|||||||
import com.bitwarden.core.data.repository.util.bufferedMutableSharedFlow
|
import com.bitwarden.core.data.repository.util.bufferedMutableSharedFlow
|
||||||
import com.bitwarden.core.data.util.decodeFromStringOrNull
|
import com.bitwarden.core.data.util.decodeFromStringOrNull
|
||||||
import com.bitwarden.data.datasource.disk.BaseEncryptedDiskSource
|
import com.bitwarden.data.datasource.disk.BaseEncryptedDiskSource
|
||||||
|
import com.bitwarden.network.model.AccountKeysJson
|
||||||
import com.bitwarden.network.model.SyncResponseJson
|
import com.bitwarden.network.model.SyncResponseJson
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.disk.model.AccountTokensJson
|
import com.x8bit.bitwarden.data.auth.datasource.disk.model.AccountTokensJson
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.disk.model.OnboardingStatus
|
import com.x8bit.bitwarden.data.auth.datasource.disk.model.OnboardingStatus
|
||||||
@ -36,6 +37,7 @@ private const val INVALID_UNLOCK_ATTEMPTS_KEY = "invalidUnlockAttempts"
|
|||||||
private const val MASTER_KEY_ENCRYPTION_USER_KEY = "masterKeyEncryptedUserKey"
|
private const val MASTER_KEY_ENCRYPTION_USER_KEY = "masterKeyEncryptedUserKey"
|
||||||
private const val MASTER_KEY_ENCRYPTION_PRIVATE_KEY = "encPrivateKey"
|
private const val MASTER_KEY_ENCRYPTION_PRIVATE_KEY = "encPrivateKey"
|
||||||
private const val PIN_PROTECTED_USER_KEY_KEY = "pinKeyEncryptedUserKey"
|
private const val PIN_PROTECTED_USER_KEY_KEY = "pinKeyEncryptedUserKey"
|
||||||
|
private const val PIN_PROTECTED_USER_KEY_KEY_ENVELOPE = "pinKeyEncryptedUserKeyEnvelope"
|
||||||
private const val ENCRYPTED_PIN_KEY = "protectedPin"
|
private const val ENCRYPTED_PIN_KEY = "protectedPin"
|
||||||
private const val ORGANIZATIONS_KEY = "organizations"
|
private const val ORGANIZATIONS_KEY = "organizations"
|
||||||
private const val ORGANIZATION_KEYS_KEY = "encOrgKeys"
|
private const val ORGANIZATION_KEYS_KEY = "encOrgKeys"
|
||||||
@ -48,6 +50,7 @@ private const val USES_KEY_CONNECTOR = "usesKeyConnector"
|
|||||||
private const val ONBOARDING_STATUS_KEY = "onboardingStatus"
|
private const val ONBOARDING_STATUS_KEY = "onboardingStatus"
|
||||||
private const val SHOW_IMPORT_LOGINS_KEY = "showImportLogins"
|
private const val SHOW_IMPORT_LOGINS_KEY = "showImportLogins"
|
||||||
private const val LAST_LOCK_TIMESTAMP = "lastLockTimestamp"
|
private const val LAST_LOCK_TIMESTAMP = "lastLockTimestamp"
|
||||||
|
private const val PROFILE_ACCOUNT_KEYS_KEY = "profileAccountKeys"
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Primary implementation of [AuthDiskSource].
|
* Primary implementation of [AuthDiskSource].
|
||||||
@ -65,6 +68,7 @@ class AuthDiskSourceImpl(
|
|||||||
AuthDiskSource {
|
AuthDiskSource {
|
||||||
|
|
||||||
private val inMemoryPinProtectedUserKeys = mutableMapOf<String, String?>()
|
private val inMemoryPinProtectedUserKeys = mutableMapOf<String, String?>()
|
||||||
|
private val inMemoryPinProtectedUserKeyEnvelopes = mutableMapOf<String, String?>()
|
||||||
private val mutableShouldUseKeyConnectorFlowMap =
|
private val mutableShouldUseKeyConnectorFlowMap =
|
||||||
mutableMapOf<String, MutableSharedFlow<Boolean?>>()
|
mutableMapOf<String, MutableSharedFlow<Boolean?>>()
|
||||||
private val mutableOrganizationsFlowMap =
|
private val mutableOrganizationsFlowMap =
|
||||||
@ -80,6 +84,8 @@ class AuthDiskSourceImpl(
|
|||||||
mutableMapOf<String, MutableSharedFlow<String?>>()
|
mutableMapOf<String, MutableSharedFlow<String?>>()
|
||||||
private val mutablePinProtectedUserKeyFlowMap =
|
private val mutablePinProtectedUserKeyFlowMap =
|
||||||
mutableMapOf<String, MutableSharedFlow<String?>>()
|
mutableMapOf<String, MutableSharedFlow<String?>>()
|
||||||
|
private val mutablePinProtectedUserKeyEnvelopeFlowMap =
|
||||||
|
mutableMapOf<String, MutableSharedFlow<String?>>()
|
||||||
private val mutableUserStateFlow = bufferedMutableSharedFlow<UserStateJson?>(replay = 1)
|
private val mutableUserStateFlow = bufferedMutableSharedFlow<UserStateJson?>(replay = 1)
|
||||||
|
|
||||||
override var userState: UserStateJson?
|
override var userState: UserStateJson?
|
||||||
@ -139,9 +145,8 @@ class AuthDiskSourceImpl(
|
|||||||
storeInvalidUnlockAttempts(userId = userId, invalidUnlockAttempts = null)
|
storeInvalidUnlockAttempts(userId = userId, invalidUnlockAttempts = null)
|
||||||
storeUserKey(userId = userId, userKey = null)
|
storeUserKey(userId = userId, userKey = null)
|
||||||
storeUserAutoUnlockKey(userId = userId, userAutoUnlockKey = null)
|
storeUserAutoUnlockKey(userId = userId, userAutoUnlockKey = null)
|
||||||
storePinProtectedUserKey(userId = userId, pinProtectedUserKey = null)
|
|
||||||
storeEncryptedPin(userId = userId, encryptedPin = null)
|
|
||||||
storePrivateKey(userId = userId, privateKey = null)
|
storePrivateKey(userId = userId, privateKey = null)
|
||||||
|
storeAccountKeys(userId = userId, accountKeys = null)
|
||||||
storeOrganizationKeys(userId = userId, organizationKeys = null)
|
storeOrganizationKeys(userId = userId, organizationKeys = null)
|
||||||
storeOrganizations(userId = userId, organizations = null)
|
storeOrganizations(userId = userId, organizations = null)
|
||||||
storeUserBiometricInitVector(userId = userId, iv = null)
|
storeUserBiometricInitVector(userId = userId, iv = null)
|
||||||
@ -154,10 +159,14 @@ class AuthDiskSourceImpl(
|
|||||||
storeAuthenticatorSyncUnlockKey(userId = userId, authenticatorSyncUnlockKey = null)
|
storeAuthenticatorSyncUnlockKey(userId = userId, authenticatorSyncUnlockKey = null)
|
||||||
storeShowImportLogins(userId = userId, showImportLogins = null)
|
storeShowImportLogins(userId = userId, showImportLogins = null)
|
||||||
storeLastLockTimestamp(userId = userId, lastLockTimestamp = null)
|
storeLastLockTimestamp(userId = userId, lastLockTimestamp = null)
|
||||||
|
storeEncryptedPin(userId = userId, encryptedPin = null)
|
||||||
|
storePinProtectedUserKey(userId = userId, pinProtectedUserKey = null)
|
||||||
|
storePinProtectedUserKeyEnvelope(userId = userId, pinProtectedUserKeyEnvelope = null)
|
||||||
|
|
||||||
// Do not remove the DeviceKey or PendingAuthRequest on logout, these are persisted
|
// Certain values are never removed as required by the feature requirements:
|
||||||
// indefinitely unless the TDE flow explicitly removes them.
|
// * DeviceKey
|
||||||
// Do not remove OnboardingStatus we want to keep track of this even after logout.
|
// * PendingAuthRequest
|
||||||
|
// * OnboardingStatus
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun getAuthenticatorSyncUnlockKey(userId: String): String? =
|
override fun getAuthenticatorSyncUnlockKey(userId: String): String? =
|
||||||
@ -228,9 +237,11 @@ class AuthDiskSourceImpl(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Deprecated("Use getAccountKeys instead.", replaceWith = ReplaceWith("getAccountKeys"))
|
||||||
override fun getPrivateKey(userId: String): String? =
|
override fun getPrivateKey(userId: String): String? =
|
||||||
getString(key = MASTER_KEY_ENCRYPTION_PRIVATE_KEY.appendIdentifier(userId))
|
getString(key = MASTER_KEY_ENCRYPTION_PRIVATE_KEY.appendIdentifier(userId))
|
||||||
|
|
||||||
|
@Deprecated("Use storeAccountKeys instead.", replaceWith = ReplaceWith("storeAccountKeys"))
|
||||||
override fun storePrivateKey(userId: String, privateKey: String?) {
|
override fun storePrivateKey(userId: String, privateKey: String?) {
|
||||||
putString(
|
putString(
|
||||||
key = MASTER_KEY_ENCRYPTION_PRIVATE_KEY.appendIdentifier(userId),
|
key = MASTER_KEY_ENCRYPTION_PRIVATE_KEY.appendIdentifier(userId),
|
||||||
@ -238,6 +249,20 @@ class AuthDiskSourceImpl(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun getAccountKeys(userId: String): AccountKeysJson? =
|
||||||
|
getEncryptedString(key = PROFILE_ACCOUNT_KEYS_KEY.appendIdentifier(userId))
|
||||||
|
?.let { json.decodeFromStringOrNull(it) }
|
||||||
|
|
||||||
|
override fun storeAccountKeys(
|
||||||
|
userId: String,
|
||||||
|
accountKeys: AccountKeysJson?,
|
||||||
|
) {
|
||||||
|
putEncryptedString(
|
||||||
|
key = PROFILE_ACCOUNT_KEYS_KEY.appendIdentifier(userId),
|
||||||
|
value = accountKeys?.let { json.encodeToString(it) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
override fun getUserAutoUnlockKey(userId: String): String? =
|
override fun getUserAutoUnlockKey(userId: String): String? =
|
||||||
getEncryptedString(
|
getEncryptedString(
|
||||||
key = USER_AUTO_UNLOCK_KEY_KEY.appendIdentifier(userId),
|
key = USER_AUTO_UNLOCK_KEY_KEY.appendIdentifier(userId),
|
||||||
@ -306,14 +331,28 @@ class AuthDiskSourceImpl(
|
|||||||
getMutableBiometricUnlockKeyFlow(userId).tryEmit(biometricsKey)
|
getMutableBiometricUnlockKeyFlow(userId).tryEmit(biometricsKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun getUserBiometicUnlockKeyFlow(userId: String): Flow<String?> =
|
override fun getUserBiometricUnlockKeyFlow(userId: String): Flow<String?> =
|
||||||
getMutableBiometricUnlockKeyFlow(userId)
|
getMutableBiometricUnlockKeyFlow(userId)
|
||||||
.onSubscription { emit(getUserBiometricUnlockKey(userId = userId)) }
|
.onSubscription { emit(getUserBiometricUnlockKey(userId = userId)) }
|
||||||
|
|
||||||
|
@Deprecated(
|
||||||
|
"Use getPinProtectedUserKeyEnvelope instead.",
|
||||||
|
replaceWith = ReplaceWith("getPinProtectedUserKeyEnvelope"),
|
||||||
|
)
|
||||||
override fun getPinProtectedUserKey(userId: String): String? =
|
override fun getPinProtectedUserKey(userId: String): String? =
|
||||||
inMemoryPinProtectedUserKeys[userId]
|
inMemoryPinProtectedUserKeys[userId]
|
||||||
?: getString(key = PIN_PROTECTED_USER_KEY_KEY.appendIdentifier(userId))
|
?: getString(key = PIN_PROTECTED_USER_KEY_KEY.appendIdentifier(userId))
|
||||||
|
|
||||||
|
override fun getPinProtectedUserKeyEnvelope(userId: String): String? =
|
||||||
|
inMemoryPinProtectedUserKeyEnvelopes[userId]
|
||||||
|
?: getString(
|
||||||
|
key = PIN_PROTECTED_USER_KEY_KEY_ENVELOPE.appendIdentifier(userId),
|
||||||
|
)
|
||||||
|
|
||||||
|
@Deprecated(
|
||||||
|
"Use storePinProtectedUserKeyEnvelope instead.",
|
||||||
|
replaceWith = ReplaceWith("storePinProtectedUserKeyEnvelope"),
|
||||||
|
)
|
||||||
override fun storePinProtectedUserKey(
|
override fun storePinProtectedUserKey(
|
||||||
userId: String,
|
userId: String,
|
||||||
pinProtectedUserKey: String?,
|
pinProtectedUserKey: String?,
|
||||||
@ -328,10 +367,32 @@ class AuthDiskSourceImpl(
|
|||||||
getMutablePinProtectedUserKeyFlow(userId).tryEmit(pinProtectedUserKey)
|
getMutablePinProtectedUserKeyFlow(userId).tryEmit(pinProtectedUserKey)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
override fun storePinProtectedUserKeyEnvelope(
|
||||||
|
userId: String,
|
||||||
|
pinProtectedUserKeyEnvelope: String?,
|
||||||
|
inMemoryOnly: Boolean,
|
||||||
|
) {
|
||||||
|
inMemoryPinProtectedUserKeyEnvelopes[userId] = pinProtectedUserKeyEnvelope
|
||||||
|
if (inMemoryOnly) return
|
||||||
|
putString(
|
||||||
|
key = PIN_PROTECTED_USER_KEY_KEY_ENVELOPE.appendIdentifier(userId),
|
||||||
|
value = pinProtectedUserKeyEnvelope,
|
||||||
|
)
|
||||||
|
getMutablePinProtectedUserKeyEnvelopeFlow(userId).tryEmit(pinProtectedUserKeyEnvelope)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Deprecated(
|
||||||
|
"Use getPinProtectedUserKeyEnvelopeFlow instead.",
|
||||||
|
replaceWith = ReplaceWith("getPinProtectedUserKeyEnvelopeFlow"),
|
||||||
|
)
|
||||||
override fun getPinProtectedUserKeyFlow(userId: String): Flow<String?> =
|
override fun getPinProtectedUserKeyFlow(userId: String): Flow<String?> =
|
||||||
getMutablePinProtectedUserKeyFlow(userId)
|
getMutablePinProtectedUserKeyFlow(userId)
|
||||||
.onSubscription { emit(getPinProtectedUserKey(userId = userId)) }
|
.onSubscription { emit(getPinProtectedUserKey(userId = userId)) }
|
||||||
|
|
||||||
|
override fun getPinProtectedUserKeyEnvelopeFlow(userId: String): Flow<String?> =
|
||||||
|
getMutablePinProtectedUserKeyEnvelopeFlow(userId)
|
||||||
|
.onSubscription { emit(getPinProtectedUserKeyEnvelope(userId = userId)) }
|
||||||
|
|
||||||
override fun getTwoFactorToken(email: String): String? =
|
override fun getTwoFactorToken(email: String): String? =
|
||||||
getString(key = TWO_FACTOR_TOKEN_KEY.appendIdentifier(email))
|
getString(key = TWO_FACTOR_TOKEN_KEY.appendIdentifier(email))
|
||||||
|
|
||||||
@ -560,6 +621,12 @@ class AuthDiskSourceImpl(
|
|||||||
bufferedMutableSharedFlow(replay = 1)
|
bufferedMutableSharedFlow(replay = 1)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private fun getMutablePinProtectedUserKeyEnvelopeFlow(
|
||||||
|
userId: String,
|
||||||
|
): MutableSharedFlow<String?> = mutablePinProtectedUserKeyEnvelopeFlowMap.getOrPut(userId) {
|
||||||
|
bufferedMutableSharedFlow(replay = 1)
|
||||||
|
}
|
||||||
|
|
||||||
private fun migrateAccountTokens() {
|
private fun migrateAccountTokens() {
|
||||||
userState
|
userState
|
||||||
?.accounts
|
?.accounts
|
||||||
|
|||||||
@ -2,12 +2,14 @@ package com.x8bit.bitwarden.data.auth.datasource.disk.model
|
|||||||
|
|
||||||
import kotlinx.serialization.SerialName
|
import kotlinx.serialization.SerialName
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
|
import java.time.Instant
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Container for the user's API tokens.
|
* Container for the user's API tokens.
|
||||||
*
|
*
|
||||||
* @property accessToken The user's primary access token.
|
* @property accessToken The user's primary access token.
|
||||||
* @property refreshToken The user's refresh token.
|
* @property refreshToken The user's refresh token.
|
||||||
|
* @property expiresAtSec The time at which the token expires in epoch seconds.
|
||||||
*/
|
*/
|
||||||
@Serializable
|
@Serializable
|
||||||
data class AccountTokensJson(
|
data class AccountTokensJson(
|
||||||
@ -16,6 +18,9 @@ data class AccountTokensJson(
|
|||||||
|
|
||||||
@SerialName("refreshToken")
|
@SerialName("refreshToken")
|
||||||
val refreshToken: String?,
|
val refreshToken: String?,
|
||||||
|
|
||||||
|
@SerialName("expiresAtSec")
|
||||||
|
val expiresAtSec: Long = Instant.MAX.epochSecond,
|
||||||
) {
|
) {
|
||||||
/**
|
/**
|
||||||
* Returns `true` if the user is logged in, `false otherwise.
|
* Returns `true` if the user is logged in, `false otherwise.
|
||||||
|
|||||||
@ -27,6 +27,12 @@ enum class OnboardingStatus {
|
|||||||
@SerialName("autofillSetup")
|
@SerialName("autofillSetup")
|
||||||
AUTOFILL_SETUP,
|
AUTOFILL_SETUP,
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The user is completing the browser autofill service setup.
|
||||||
|
*/
|
||||||
|
@SerialName("browserAutofillSetup")
|
||||||
|
BROWSER_AUTOFILL_SETUP,
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The user is completing the final step of the onboarding process.
|
* The user is completing the final step of the onboarding process.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@ -30,7 +30,7 @@ class AuthSdkSourceImpl(
|
|||||||
getClient()
|
getClient()
|
||||||
.auth()
|
.auth()
|
||||||
.newAuthRequest(
|
.newAuthRequest(
|
||||||
email = email,
|
email = email.lowercase(),
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -42,7 +42,7 @@ class AuthSdkSourceImpl(
|
|||||||
.platform()
|
.platform()
|
||||||
.fingerprint(
|
.fingerprint(
|
||||||
req = FingerprintRequest(
|
req = FingerprintRequest(
|
||||||
fingerprintMaterial = email,
|
fingerprintMaterial = email.lowercase(),
|
||||||
publicKey = publicKey,
|
publicKey = publicKey,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|||||||
@ -1,9 +1,12 @@
|
|||||||
package com.x8bit.bitwarden.data.auth.datasource.sdk.util
|
package com.x8bit.bitwarden.data.auth.datasource.sdk.util
|
||||||
|
|
||||||
import com.bitwarden.crypto.Kdf
|
import com.bitwarden.crypto.Kdf
|
||||||
|
import com.bitwarden.network.model.KdfJson
|
||||||
import com.bitwarden.network.model.KdfTypeJson
|
import com.bitwarden.network.model.KdfTypeJson
|
||||||
import com.bitwarden.network.model.KdfTypeJson.ARGON2_ID
|
import com.bitwarden.network.model.KdfTypeJson.ARGON2_ID
|
||||||
import com.bitwarden.network.model.KdfTypeJson.PBKDF2_SHA256
|
import com.bitwarden.network.model.KdfTypeJson.PBKDF2_SHA256
|
||||||
|
import com.x8bit.bitwarden.data.auth.util.KdfParamsConstants.DEFAULT_ARGON2_MEMORY
|
||||||
|
import com.x8bit.bitwarden.data.auth.util.KdfParamsConstants.DEFAULT_ARGON2_PARALLELISM
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Convert a [Kdf] to a [KdfTypeJson].
|
* Convert a [Kdf] to a [KdfTypeJson].
|
||||||
@ -13,3 +16,36 @@ fun Kdf.toKdfTypeJson(): KdfTypeJson =
|
|||||||
is Kdf.Argon2id -> ARGON2_ID
|
is Kdf.Argon2id -> ARGON2_ID
|
||||||
is Kdf.Pbkdf2 -> PBKDF2_SHA256
|
is Kdf.Pbkdf2 -> PBKDF2_SHA256
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a [Kdf] to [KdfJson]
|
||||||
|
*/
|
||||||
|
fun Kdf.toKdfRequestModel(): KdfJson =
|
||||||
|
when (this) {
|
||||||
|
is Kdf.Argon2id -> KdfJson(
|
||||||
|
kdfType = toKdfTypeJson(),
|
||||||
|
iterations = iterations.toInt(),
|
||||||
|
memory = memory.toInt(),
|
||||||
|
parallelism = parallelism.toInt(),
|
||||||
|
)
|
||||||
|
|
||||||
|
is Kdf.Pbkdf2 -> KdfJson(
|
||||||
|
kdfType = toKdfTypeJson(),
|
||||||
|
iterations = iterations.toInt(),
|
||||||
|
memory = null,
|
||||||
|
parallelism = null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a [KdfJson] to a [Kdf].
|
||||||
|
*/
|
||||||
|
fun KdfJson.toKdf(): Kdf =
|
||||||
|
when (this.kdfType) {
|
||||||
|
ARGON2_ID -> Kdf.Argon2id(
|
||||||
|
iterations = iterations.toUInt(),
|
||||||
|
memory = memory?.toUInt() ?: DEFAULT_ARGON2_MEMORY.toUInt(),
|
||||||
|
parallelism = parallelism?.toUInt() ?: DEFAULT_ARGON2_PARALLELISM.toUInt(),
|
||||||
|
)
|
||||||
|
PBKDF2_SHA256 -> Kdf.Pbkdf2(iterations = iterations.toUInt())
|
||||||
|
}
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
package com.x8bit.bitwarden.data.auth.manager
|
package com.x8bit.bitwarden.data.auth.manager
|
||||||
|
|
||||||
import com.x8bit.bitwarden.ui.vault.model.TotpData
|
import com.bitwarden.ui.platform.model.TotpData
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Manager for keeping track of requests from the Bitwarden Authenticator app to add a TOTP
|
* Manager for keeping track of requests from the Bitwarden Authenticator app to add a TOTP
|
||||||
|
|||||||
@ -1,6 +1,6 @@
|
|||||||
package com.x8bit.bitwarden.data.auth.manager
|
package com.x8bit.bitwarden.data.auth.manager
|
||||||
|
|
||||||
import com.x8bit.bitwarden.ui.vault.model.TotpData
|
import com.bitwarden.ui.platform.model.TotpData
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Default in memory implementation for [AddTotpItemFromAuthenticatorManager].
|
* Default in memory implementation for [AddTotpItemFromAuthenticatorManager].
|
||||||
|
|||||||
@ -28,7 +28,6 @@ import kotlinx.coroutines.flow.flow
|
|||||||
import kotlinx.coroutines.isActive
|
import kotlinx.coroutines.isActive
|
||||||
import java.time.Clock
|
import java.time.Clock
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
import kotlin.coroutines.coroutineContext
|
|
||||||
|
|
||||||
private const val PASSWORDLESS_NOTIFICATION_TIMEOUT_MILLIS: Long = 15L * 60L * 1_000L
|
private const val PASSWORDLESS_NOTIFICATION_TIMEOUT_MILLIS: Long = 15L * 60L * 1_000L
|
||||||
private const val PASSWORDLESS_NOTIFICATION_RETRY_INTERVAL_MILLIS: Long = 4L * 1_000L
|
private const val PASSWORDLESS_NOTIFICATION_RETRY_INTERVAL_MILLIS: Long = 4L * 1_000L
|
||||||
@ -163,7 +162,7 @@ class AuthRequestManagerImpl(
|
|||||||
emit(result)
|
emit(result)
|
||||||
if (result is AuthRequestUpdatesResult.Error) return@flow
|
if (result is AuthRequestUpdatesResult.Error) return@flow
|
||||||
var isComplete = false
|
var isComplete = false
|
||||||
while (coroutineContext.isActive && !isComplete) {
|
while (currentCoroutineContext().isActive && !isComplete) {
|
||||||
delay(PASSWORDLESS_APPROVER_INTERVAL_MILLIS)
|
delay(PASSWORDLESS_APPROVER_INTERVAL_MILLIS)
|
||||||
val updateResult = result as AuthRequestUpdatesResult.Update
|
val updateResult = result as AuthRequestUpdatesResult.Update
|
||||||
authRequestsService
|
authRequestsService
|
||||||
|
|||||||
@ -8,12 +8,12 @@ import androidx.core.app.NotificationChannelCompat
|
|||||||
import androidx.core.app.NotificationCompat
|
import androidx.core.app.NotificationCompat
|
||||||
import androidx.core.app.NotificationManagerCompat
|
import androidx.core.app.NotificationManagerCompat
|
||||||
import com.bitwarden.annotation.OmitFromCoverage
|
import com.bitwarden.annotation.OmitFromCoverage
|
||||||
import com.bitwarden.data.manager.DispatcherManager
|
import com.bitwarden.core.data.manager.dispatcher.DispatcherManager
|
||||||
|
import com.bitwarden.core.util.toPendingIntentMutabilityFlag
|
||||||
import com.bitwarden.ui.platform.resource.BitwardenDrawable
|
import com.bitwarden.ui.platform.resource.BitwardenDrawable
|
||||||
import com.x8bit.bitwarden.R
|
import com.bitwarden.ui.platform.resource.BitwardenString
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
|
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
|
||||||
import com.x8bit.bitwarden.data.auth.util.createPasswordlessRequestDataIntent
|
import com.x8bit.bitwarden.data.auth.util.createPasswordlessRequestDataIntent
|
||||||
import com.x8bit.bitwarden.data.autofill.util.toPendingIntentMutabilityFlag
|
|
||||||
import com.x8bit.bitwarden.data.platform.manager.PushManager
|
import com.x8bit.bitwarden.data.platform.manager.PushManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.model.PasswordlessRequestData
|
import com.x8bit.bitwarden.data.platform.manager.model.PasswordlessRequestData
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
@ -49,14 +49,14 @@ class AuthRequestNotificationManagerImpl(
|
|||||||
NOTIFICATION_CHANNEL_ID,
|
NOTIFICATION_CHANNEL_ID,
|
||||||
NotificationManagerCompat.IMPORTANCE_DEFAULT,
|
NotificationManagerCompat.IMPORTANCE_DEFAULT,
|
||||||
)
|
)
|
||||||
.setName(context.getString(R.string.pending_log_in_requests))
|
.setName(context.getString(BitwardenString.pending_log_in_requests))
|
||||||
.build(),
|
.build(),
|
||||||
)
|
)
|
||||||
if (!notificationManager.areNotificationsEnabled(NOTIFICATION_CHANNEL_ID)) return
|
if (!notificationManager.areNotificationsEnabled(NOTIFICATION_CHANNEL_ID)) return
|
||||||
// Create the notification
|
// Create the notification
|
||||||
val builder = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
|
val builder = NotificationCompat.Builder(context, NOTIFICATION_CHANNEL_ID)
|
||||||
.setContentIntent(createContentIntent(data))
|
.setContentIntent(createContentIntent(data))
|
||||||
.setContentTitle(context.getString(R.string.log_in_requested))
|
.setContentTitle(context.getString(BitwardenString.log_in_requested))
|
||||||
.setContentText(
|
.setContentText(
|
||||||
authDiskSource
|
authDiskSource
|
||||||
.userState
|
.userState
|
||||||
@ -64,8 +64,8 @@ class AuthRequestNotificationManagerImpl(
|
|||||||
?.get(data.userId)
|
?.get(data.userId)
|
||||||
?.profile
|
?.profile
|
||||||
?.email
|
?.email
|
||||||
?.let { context.getString(R.string.confim_log_in_attemp_for_x, it) }
|
?.let { context.getString(BitwardenString.confim_log_in_attemp_for_x, it) }
|
||||||
?: context.getString(R.string.confirm_log_in),
|
?: context.getString(BitwardenString.confirm_log_in),
|
||||||
)
|
)
|
||||||
.setSmallIcon(BitwardenDrawable.ic_notification)
|
.setSmallIcon(BitwardenDrawable.ic_notification)
|
||||||
.setColor(Color.White.value.toInt())
|
.setColor(Color.White.value.toInt())
|
||||||
|
|||||||
@ -1,5 +1,6 @@
|
|||||||
package com.x8bit.bitwarden.data.auth.manager
|
package com.x8bit.bitwarden.data.auth.manager
|
||||||
|
|
||||||
|
import com.bitwarden.network.model.AuthTokenData
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
|
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -9,9 +10,20 @@ class AuthTokenManagerImpl(
|
|||||||
private val authDiskSource: AuthDiskSource,
|
private val authDiskSource: AuthDiskSource,
|
||||||
) : AuthTokenManager {
|
) : AuthTokenManager {
|
||||||
|
|
||||||
override fun getActiveAccessTokenOrNull(): String? = authDiskSource
|
override fun getAuthTokenDataOrNull(userId: String): AuthTokenData? =
|
||||||
|
authDiskSource
|
||||||
|
.getAccountTokens(userId = userId)
|
||||||
|
?.takeIf { it.accessToken != null }
|
||||||
|
?.let {
|
||||||
|
AuthTokenData(
|
||||||
|
userId = userId,
|
||||||
|
accessToken = requireNotNull(it.accessToken),
|
||||||
|
expiresAtSec = it.expiresAtSec,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun getAuthTokenDataOrNull(): AuthTokenData? = authDiskSource
|
||||||
.userState
|
.userState
|
||||||
?.activeUserId
|
?.activeUserId
|
||||||
?.let { authDiskSource.getAccountTokens(it) }
|
?.let(::getAuthTokenDataOrNull)
|
||||||
?.accessToken
|
|
||||||
}
|
}
|
||||||
|
|||||||
@ -0,0 +1,19 @@
|
|||||||
|
package com.x8bit.bitwarden.data.auth.manager
|
||||||
|
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.model.UpdateKdfMinimumsResult
|
||||||
|
|
||||||
|
/**
|
||||||
|
* An interface to manage the user KDF settings.
|
||||||
|
*/
|
||||||
|
interface KdfManager {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks if user's current KDF settings are below the minimums and needs update
|
||||||
|
*/
|
||||||
|
fun needsKdfUpdateToMinimums(): Boolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the user's KDF settings if below the minimums
|
||||||
|
*/
|
||||||
|
suspend fun updateKdfToMinimumsIfNeeded(password: String): UpdateKdfMinimumsResult
|
||||||
|
}
|
||||||
@ -0,0 +1,102 @@
|
|||||||
|
package com.x8bit.bitwarden.data.auth.manager
|
||||||
|
|
||||||
|
import com.bitwarden.core.UpdateKdfResponse
|
||||||
|
import com.bitwarden.core.data.manager.model.FlagKey
|
||||||
|
import com.bitwarden.core.data.util.flatMap
|
||||||
|
import com.bitwarden.crypto.Kdf
|
||||||
|
import com.bitwarden.network.model.KdfTypeJson
|
||||||
|
import com.bitwarden.network.model.MasterPasswordAuthenticationDataJson
|
||||||
|
import com.bitwarden.network.model.MasterPasswordUnlockDataJson
|
||||||
|
import com.bitwarden.network.model.UpdateKdfJsonRequest
|
||||||
|
import com.bitwarden.network.service.AccountsService
|
||||||
|
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
|
||||||
|
import com.x8bit.bitwarden.data.auth.datasource.sdk.util.toKdfRequestModel
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.model.UpdateKdfMinimumsResult
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.util.toUserStateJsonKdfUpdatedMinimums
|
||||||
|
import com.x8bit.bitwarden.data.auth.util.KdfParamsConstants.DEFAULT_PBKDF2_ITERATIONS
|
||||||
|
import com.x8bit.bitwarden.data.platform.manager.FeatureFlagManager
|
||||||
|
import com.x8bit.bitwarden.data.vault.datasource.sdk.VaultSdkSource
|
||||||
|
import timber.log.Timber
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Default implementation of [KdfManager].
|
||||||
|
*/
|
||||||
|
class KdfManagerImpl(
|
||||||
|
private val authDiskSource: AuthDiskSource,
|
||||||
|
private val vaultSdkSource: VaultSdkSource,
|
||||||
|
private val accountsService: AccountsService,
|
||||||
|
private val featureFlagManager: FeatureFlagManager,
|
||||||
|
) : KdfManager {
|
||||||
|
|
||||||
|
private val activeUserId: String? get() = authDiskSource.userState?.activeUserId
|
||||||
|
|
||||||
|
override fun needsKdfUpdateToMinimums(): Boolean {
|
||||||
|
if (!featureFlagManager.getFeatureFlag(FlagKey.ForceUpdateKdfSettings)) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
val account = authDiskSource
|
||||||
|
.userState
|
||||||
|
?.accounts
|
||||||
|
?.get(activeUserId)
|
||||||
|
?: return false
|
||||||
|
|
||||||
|
if (account.profile.userDecryptionOptions != null &&
|
||||||
|
!account.profile.userDecryptionOptions.hasMasterPassword
|
||||||
|
) {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
|
return account.profile.kdfType == KdfTypeJson.PBKDF2_SHA256 &&
|
||||||
|
account.profile.kdfIterations != null &&
|
||||||
|
account.profile.kdfIterations < DEFAULT_PBKDF2_ITERATIONS
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun updateKdfToMinimumsIfNeeded(password: String): UpdateKdfMinimumsResult {
|
||||||
|
val userId = activeUserId ?: return UpdateKdfMinimumsResult.ActiveAccountNotFound
|
||||||
|
|
||||||
|
if (!needsKdfUpdateToMinimums()) {
|
||||||
|
return UpdateKdfMinimumsResult.Success
|
||||||
|
}
|
||||||
|
return vaultSdkSource
|
||||||
|
.makeUpdateKdf(
|
||||||
|
userId = userId,
|
||||||
|
password = password,
|
||||||
|
kdf = Kdf.Pbkdf2(iterations = DEFAULT_PBKDF2_ITERATIONS.toUInt()),
|
||||||
|
)
|
||||||
|
.flatMap {
|
||||||
|
accountsService.updateKdf(createUpdateKdfRequest(it))
|
||||||
|
}
|
||||||
|
.fold(
|
||||||
|
onSuccess = {
|
||||||
|
authDiskSource.userState = authDiskSource.userState
|
||||||
|
?.toUserStateJsonKdfUpdatedMinimums()
|
||||||
|
Timber.d("[Auth] Upgraded user's KDF to minimums")
|
||||||
|
UpdateKdfMinimumsResult.Success
|
||||||
|
},
|
||||||
|
onFailure = { UpdateKdfMinimumsResult.Error(error = it) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun createUpdateKdfRequest(response: UpdateKdfResponse): UpdateKdfJsonRequest {
|
||||||
|
val authData = response.masterPasswordAuthenticationData
|
||||||
|
val oldAuthData = response.oldMasterPasswordAuthenticationData
|
||||||
|
val unlockData = response.masterPasswordUnlockData
|
||||||
|
|
||||||
|
return UpdateKdfJsonRequest(
|
||||||
|
authenticationData = MasterPasswordAuthenticationDataJson(
|
||||||
|
kdf = authData.kdf.toKdfRequestModel(),
|
||||||
|
masterPasswordAuthenticationHash = authData.masterPasswordAuthenticationHash,
|
||||||
|
salt = authData.salt,
|
||||||
|
),
|
||||||
|
key = unlockData.masterKeyWrappedUserKey,
|
||||||
|
masterPasswordHash = oldAuthData.masterPasswordAuthenticationHash,
|
||||||
|
newMasterPasswordHash = authData.masterPasswordAuthenticationHash,
|
||||||
|
unlockData = MasterPasswordUnlockDataJson(
|
||||||
|
kdf = unlockData.kdf.toKdfRequestModel(),
|
||||||
|
masterKeyWrappedUserKey = unlockData.masterKeyWrappedUserKey,
|
||||||
|
salt = unlockData.salt,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -1,15 +1,16 @@
|
|||||||
package com.x8bit.bitwarden.data.auth.manager
|
package com.x8bit.bitwarden.data.auth.manager
|
||||||
|
|
||||||
import androidx.annotation.StringRes
|
import androidx.annotation.StringRes
|
||||||
|
import com.bitwarden.core.data.manager.dispatcher.DispatcherManager
|
||||||
import com.bitwarden.core.data.manager.toast.ToastManager
|
import com.bitwarden.core.data.manager.toast.ToastManager
|
||||||
import com.bitwarden.core.data.repository.util.bufferedMutableSharedFlow
|
import com.bitwarden.core.data.repository.util.bufferedMutableSharedFlow
|
||||||
import com.bitwarden.data.manager.DispatcherManager
|
import com.bitwarden.ui.platform.resource.BitwardenString
|
||||||
import com.x8bit.bitwarden.R
|
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
|
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
|
||||||
import com.x8bit.bitwarden.data.auth.manager.model.LogoutEvent
|
import com.x8bit.bitwarden.data.auth.manager.model.LogoutEvent
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.LogoutReason
|
import com.x8bit.bitwarden.data.auth.repository.model.LogoutReason
|
||||||
import com.x8bit.bitwarden.data.platform.datasource.disk.PushDiskSource
|
import com.x8bit.bitwarden.data.platform.datasource.disk.PushDiskSource
|
||||||
import com.x8bit.bitwarden.data.platform.datasource.disk.SettingsDiskSource
|
import com.x8bit.bitwarden.data.platform.datasource.disk.SettingsDiskSource
|
||||||
|
import com.x8bit.bitwarden.data.platform.manager.CredentialExchangeRegistryManager
|
||||||
import com.x8bit.bitwarden.data.tools.generator.datasource.disk.GeneratorDiskSource
|
import com.x8bit.bitwarden.data.tools.generator.datasource.disk.GeneratorDiskSource
|
||||||
import com.x8bit.bitwarden.data.tools.generator.datasource.disk.PasswordHistoryDiskSource
|
import com.x8bit.bitwarden.data.tools.generator.datasource.disk.PasswordHistoryDiskSource
|
||||||
import com.x8bit.bitwarden.data.vault.datasource.disk.VaultDiskSource
|
import com.x8bit.bitwarden.data.vault.datasource.disk.VaultDiskSource
|
||||||
@ -34,10 +35,12 @@ class UserLogoutManagerImpl(
|
|||||||
private val toastManager: ToastManager,
|
private val toastManager: ToastManager,
|
||||||
private val vaultDiskSource: VaultDiskSource,
|
private val vaultDiskSource: VaultDiskSource,
|
||||||
private val vaultSdkSource: VaultSdkSource,
|
private val vaultSdkSource: VaultSdkSource,
|
||||||
|
private val credentialExchangeRegistryManager: CredentialExchangeRegistryManager,
|
||||||
dispatcherManager: DispatcherManager,
|
dispatcherManager: DispatcherManager,
|
||||||
) : UserLogoutManager {
|
) : UserLogoutManager {
|
||||||
private val scope = CoroutineScope(dispatcherManager.unconfined)
|
private val unconfinedScope = CoroutineScope(dispatcherManager.unconfined)
|
||||||
private val mainScope = CoroutineScope(dispatcherManager.main)
|
private val mainScope = CoroutineScope(dispatcherManager.main)
|
||||||
|
private val ioScope = CoroutineScope(dispatcherManager.io)
|
||||||
|
|
||||||
private val mutableLogoutEventFlow: MutableSharedFlow<LogoutEvent> =
|
private val mutableLogoutEventFlow: MutableSharedFlow<LogoutEvent> =
|
||||||
bufferedMutableSharedFlow()
|
bufferedMutableSharedFlow()
|
||||||
@ -46,20 +49,22 @@ class UserLogoutManagerImpl(
|
|||||||
override fun logout(userId: String, reason: LogoutReason) {
|
override fun logout(userId: String, reason: LogoutReason) {
|
||||||
authDiskSource.userState ?: return
|
authDiskSource.userState ?: return
|
||||||
Timber.d("logout reason=$reason")
|
Timber.d("logout reason=$reason")
|
||||||
val isExpired = reason == LogoutReason.SecurityStamp
|
val isSecurityStamp = reason == LogoutReason.SecurityStamp
|
||||||
if (isExpired) {
|
if (isSecurityStamp) {
|
||||||
showToast(message = R.string.login_expired)
|
showToast(message = BitwardenString.login_expired)
|
||||||
}
|
}
|
||||||
|
|
||||||
val ableToSwitchToNewAccount = switchUserIfAvailable(
|
val ableToSwitchToNewAccount = switchUserIfAvailable(
|
||||||
currentUserId = userId,
|
currentUserId = userId,
|
||||||
isExpired = isExpired,
|
isSecurityStamp = isSecurityStamp,
|
||||||
removeCurrentUserFromAccounts = true,
|
removeCurrentUserFromAccounts = true,
|
||||||
)
|
)
|
||||||
|
|
||||||
if (!ableToSwitchToNewAccount) {
|
if (!ableToSwitchToNewAccount) {
|
||||||
// Update the user information and log out
|
// Update the user information and log out.
|
||||||
authDiskSource.userState = null
|
authDiskSource.userState = null
|
||||||
|
// Unregister the application from CXP Export since there are no other accounts.
|
||||||
|
ioScope.launch { credentialExchangeRegistryManager.unregister() }
|
||||||
}
|
}
|
||||||
|
|
||||||
clearData(userId = userId)
|
clearData(userId = userId)
|
||||||
@ -68,23 +73,24 @@ class UserLogoutManagerImpl(
|
|||||||
|
|
||||||
override fun softLogout(userId: String, reason: LogoutReason) {
|
override fun softLogout(userId: String, reason: LogoutReason) {
|
||||||
Timber.d("softLogout reason=$reason")
|
Timber.d("softLogout reason=$reason")
|
||||||
val isExpired = reason == LogoutReason.SecurityStamp
|
val isSecurityStamp = reason == LogoutReason.SecurityStamp
|
||||||
if (isExpired) {
|
if (isSecurityStamp) {
|
||||||
showToast(message = R.string.login_expired)
|
showToast(message = BitwardenString.login_expired)
|
||||||
}
|
}
|
||||||
authDiskSource.storeAccountTokens(
|
|
||||||
userId = userId,
|
|
||||||
accountTokens = null,
|
|
||||||
)
|
|
||||||
|
|
||||||
// Save any data that will still need to be retained after otherwise clearing all dat
|
// Save any data that will still need to be retained after otherwise clearing all data
|
||||||
val vaultTimeoutInMinutes = settingsDiskSource.getVaultTimeoutInMinutes(userId = userId)
|
val vaultTimeoutInMinutes = settingsDiskSource.getVaultTimeoutInMinutes(userId = userId)
|
||||||
val vaultTimeoutAction = settingsDiskSource.getVaultTimeoutAction(userId = userId)
|
val vaultTimeoutAction = settingsDiskSource.getVaultTimeoutAction(userId = userId)
|
||||||
|
val encryptedPin = authDiskSource.getEncryptedPin(userId = userId)
|
||||||
|
val pinProtectedUserKey = authDiskSource.getPinProtectedUserKey(userId = userId)
|
||||||
|
val pinProtectedUserKeyEnvelope = authDiskSource.getPinProtectedUserKeyEnvelope(
|
||||||
|
userId = userId,
|
||||||
|
)
|
||||||
|
|
||||||
switchUserIfAvailable(
|
switchUserIfAvailable(
|
||||||
currentUserId = userId,
|
currentUserId = userId,
|
||||||
removeCurrentUserFromAccounts = false,
|
removeCurrentUserFromAccounts = false,
|
||||||
isExpired = isExpired,
|
isSecurityStamp = isSecurityStamp,
|
||||||
)
|
)
|
||||||
|
|
||||||
clearData(userId = userId)
|
clearData(userId = userId)
|
||||||
@ -101,6 +107,14 @@ class UserLogoutManagerImpl(
|
|||||||
vaultTimeoutAction = vaultTimeoutAction,
|
vaultTimeoutAction = vaultTimeoutAction,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
authDiskSource.apply {
|
||||||
|
storeEncryptedPin(userId = userId, encryptedPin = encryptedPin)
|
||||||
|
storePinProtectedUserKey(userId = userId, pinProtectedUserKey = pinProtectedUserKey)
|
||||||
|
storePinProtectedUserKeyEnvelope(
|
||||||
|
userId = userId,
|
||||||
|
pinProtectedUserKeyEnvelope = pinProtectedUserKeyEnvelope,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun clearData(userId: String) {
|
private fun clearData(userId: String) {
|
||||||
@ -109,7 +123,7 @@ class UserLogoutManagerImpl(
|
|||||||
generatorDiskSource.clearData(userId = userId)
|
generatorDiskSource.clearData(userId = userId)
|
||||||
pushDiskSource.clearData(userId = userId)
|
pushDiskSource.clearData(userId = userId)
|
||||||
settingsDiskSource.clearData(userId = userId)
|
settingsDiskSource.clearData(userId = userId)
|
||||||
scope.launch {
|
unconfinedScope.launch {
|
||||||
passwordHistoryDiskSource.clearPasswordHistories(userId = userId)
|
passwordHistoryDiskSource.clearPasswordHistories(userId = userId)
|
||||||
vaultDiskSource.deleteVaultData(userId = userId)
|
vaultDiskSource.deleteVaultData(userId = userId)
|
||||||
}
|
}
|
||||||
@ -122,7 +136,7 @@ class UserLogoutManagerImpl(
|
|||||||
private fun switchUserIfAvailable(
|
private fun switchUserIfAvailable(
|
||||||
currentUserId: String,
|
currentUserId: String,
|
||||||
removeCurrentUserFromAccounts: Boolean,
|
removeCurrentUserFromAccounts: Boolean,
|
||||||
isExpired: Boolean = false,
|
isSecurityStamp: Boolean,
|
||||||
): Boolean {
|
): Boolean {
|
||||||
val currentUserState = authDiskSource.userState ?: return false
|
val currentUserState = authDiskSource.userState ?: return false
|
||||||
|
|
||||||
@ -134,8 +148,8 @@ class UserLogoutManagerImpl(
|
|||||||
|
|
||||||
// Check if there is a new active user
|
// Check if there is a new active user
|
||||||
return if (updatedAccounts.isNotEmpty()) {
|
return if (updatedAccounts.isNotEmpty()) {
|
||||||
if (currentUserId == currentUserState.activeUserId && !isExpired) {
|
if (currentUserId == currentUserState.activeUserId && !isSecurityStamp) {
|
||||||
showToast(message = R.string.account_switched_automatically)
|
showToast(message = BitwardenString.account_switched_automatically)
|
||||||
}
|
}
|
||||||
|
|
||||||
// If we logged out a non-active user, we want to leave the active user unchanged.
|
// If we logged out a non-active user, we want to leave the active user unchanged.
|
||||||
|
|||||||
@ -0,0 +1,43 @@
|
|||||||
|
package com.x8bit.bitwarden.data.auth.manager
|
||||||
|
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.model.UserState
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Manages the global state of all users.
|
||||||
|
*/
|
||||||
|
interface UserStateManager {
|
||||||
|
/**
|
||||||
|
* Emits updates for changes to the [UserState].
|
||||||
|
*/
|
||||||
|
val userStateFlow: StateFlow<UserState?>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tracks whether there is an additional account that is pending login/registration in order to
|
||||||
|
* have multiple accounts available.
|
||||||
|
*
|
||||||
|
* This allows a direct view into and modification of [UserState.hasPendingAccountAddition].
|
||||||
|
* Note that this call has no effect when there is no [UserState] information available.
|
||||||
|
*/
|
||||||
|
var hasPendingAccountAddition: Boolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Emits updates for changes to the [UserState.hasPendingAccountAddition] flag.
|
||||||
|
*/
|
||||||
|
val hasPendingAccountAdditionStateFlow: StateFlow<Boolean>
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Tracks whether there is an account that is pending deletion in order to allow the account to
|
||||||
|
* remain active until the deletion is finalized.
|
||||||
|
*/
|
||||||
|
var hasPendingAccountDeletion: Boolean
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run the given [block] while preventing any updates to [UserState]. This is useful in cases
|
||||||
|
* where many individual changes might occur that would normally affect the [UserState] but we
|
||||||
|
* only want a single final emission. In the rare case that multiple threads are running
|
||||||
|
* transactions simultaneously, there will be no [UserState] updates until the last
|
||||||
|
* transaction completes.
|
||||||
|
*/
|
||||||
|
suspend fun <T> userStateTransaction(block: suspend () -> T): T
|
||||||
|
}
|
||||||
@ -0,0 +1,176 @@
|
|||||||
|
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.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
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.model.UserAccountTokens
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.model.UserKeyConnectorState
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.model.UserOrganizations
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.model.UserState
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.model.VaultUnlockType
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.util.currentOnboardingStatus
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.util.onboardingStatusChangesFlow
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.util.toUserState
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.util.userAccountTokens
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.util.userAccountTokensFlow
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.util.userKeyConnectorStateFlow
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.util.userKeyConnectorStateList
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.util.userOrganizationsList
|
||||||
|
import com.x8bit.bitwarden.data.auth.repository.util.userOrganizationsListFlow
|
||||||
|
import com.x8bit.bitwarden.data.platform.manager.FirstTimeActionManager
|
||||||
|
import com.x8bit.bitwarden.data.platform.manager.PolicyManager
|
||||||
|
import com.x8bit.bitwarden.data.platform.manager.model.FirstTimeState
|
||||||
|
import com.x8bit.bitwarden.data.vault.manager.VaultLockManager
|
||||||
|
import com.x8bit.bitwarden.data.vault.repository.model.VaultUnlockData
|
||||||
|
import kotlinx.coroutines.CoroutineScope
|
||||||
|
import kotlinx.coroutines.flow.MutableStateFlow
|
||||||
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
import kotlinx.coroutines.flow.combine
|
||||||
|
import kotlinx.coroutines.flow.filterNot
|
||||||
|
import kotlinx.coroutines.flow.merge
|
||||||
|
import kotlinx.coroutines.flow.stateIn
|
||||||
|
import kotlinx.coroutines.flow.update
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The default implementation of the [UserStateManager].
|
||||||
|
*/
|
||||||
|
class UserStateManagerImpl(
|
||||||
|
private val authDiskSource: AuthDiskSource,
|
||||||
|
firstTimeActionManager: FirstTimeActionManager,
|
||||||
|
vaultLockManager: VaultLockManager,
|
||||||
|
private val policyManager: PolicyManager,
|
||||||
|
dispatcherManager: DispatcherManager,
|
||||||
|
) : UserStateManager {
|
||||||
|
private val unconfinedScope = CoroutineScope(dispatcherManager.unconfined)
|
||||||
|
|
||||||
|
//region Pending Account Addition
|
||||||
|
private val mutableHasPendingAccountAdditionStateFlow = MutableStateFlow(value = false)
|
||||||
|
|
||||||
|
override val hasPendingAccountAdditionStateFlow: StateFlow<Boolean>
|
||||||
|
get() = mutableHasPendingAccountAdditionStateFlow
|
||||||
|
|
||||||
|
override var hasPendingAccountAddition: Boolean
|
||||||
|
by mutableHasPendingAccountAdditionStateFlow::value
|
||||||
|
//endregion Pending Account Addition
|
||||||
|
|
||||||
|
//region Pending Account Deletion
|
||||||
|
/**
|
||||||
|
* If there is a pending account deletion, continue showing the original UserState until it
|
||||||
|
* is confirmed. This is accomplished by blocking the emissions of the [userStateFlow]
|
||||||
|
* whenever set to `true`.
|
||||||
|
*/
|
||||||
|
private val mutableHasPendingAccountDeletionStateFlow = MutableStateFlow(value = false)
|
||||||
|
|
||||||
|
override var hasPendingAccountDeletion: Boolean
|
||||||
|
by mutableHasPendingAccountDeletionStateFlow::value
|
||||||
|
//endregion Pending Account Deletion
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whenever a function needs to update multiple underlying data-points that contribute to the
|
||||||
|
* [UserState], we update this [MutableStateFlow] and continue to show the original `UserState`
|
||||||
|
* until the transaction is complete. This is accomplished by blocking the emissions of the
|
||||||
|
* [userStateFlow] whenever this is set to a value above 0 (a count is used if more than one
|
||||||
|
* process is updating data simultaneously).
|
||||||
|
*/
|
||||||
|
private val mutableUserStateTransactionCountStateFlow = MutableStateFlow(0)
|
||||||
|
|
||||||
|
@Suppress("UNCHECKED_CAST", "MagicNumber")
|
||||||
|
override val userStateFlow: StateFlow<UserState?> = combine(
|
||||||
|
authDiskSource.userStateFlow,
|
||||||
|
authDiskSource.userAccountTokensFlow,
|
||||||
|
authDiskSource.userOrganizationsListFlow,
|
||||||
|
authDiskSource.userKeyConnectorStateFlow,
|
||||||
|
authDiskSource.onboardingStatusChangesFlow,
|
||||||
|
firstTimeActionManager.firstTimeStateFlow,
|
||||||
|
vaultLockManager.vaultUnlockDataStateFlow,
|
||||||
|
hasPendingAccountAdditionStateFlow,
|
||||||
|
// Ignore the data in the merge, but trigger an update when they emit.
|
||||||
|
merge(
|
||||||
|
mutableHasPendingAccountDeletionStateFlow,
|
||||||
|
mutableUserStateTransactionCountStateFlow,
|
||||||
|
vaultLockManager.isActiveUserUnlockingFlow,
|
||||||
|
),
|
||||||
|
) { array ->
|
||||||
|
val userStateJson = array[0] as UserStateJson?
|
||||||
|
val userAccountTokens = array[1] as List<UserAccountTokens>
|
||||||
|
val userOrganizationsList = array[2] as List<UserOrganizations>
|
||||||
|
val userIsUsingKeyConnectorList = array[3] as List<UserKeyConnectorState>
|
||||||
|
val onboardingStatus = array[4] as OnboardingStatus?
|
||||||
|
val firstTimeState = array[5] as FirstTimeState
|
||||||
|
val vaultState = array[6] as List<VaultUnlockData>
|
||||||
|
val hasPendingAccountAddition = array[7] as Boolean
|
||||||
|
userStateJson?.toUserState(
|
||||||
|
vaultState = vaultState,
|
||||||
|
userAccountTokens = userAccountTokens,
|
||||||
|
userOrganizationsList = userOrganizationsList,
|
||||||
|
userIsUsingKeyConnectorList = userIsUsingKeyConnectorList,
|
||||||
|
hasPendingAccountAddition = hasPendingAccountAddition,
|
||||||
|
onboardingStatus = onboardingStatus,
|
||||||
|
isBiometricsEnabledProvider = ::isBiometricsEnabled,
|
||||||
|
vaultUnlockTypeProvider = ::getVaultUnlockType,
|
||||||
|
isDeviceTrustedProvider = ::isDeviceTrusted,
|
||||||
|
firstTimeState = firstTimeState,
|
||||||
|
getUserPolicies = ::existingPolicies,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
.filterNot {
|
||||||
|
mutableHasPendingAccountDeletionStateFlow.value ||
|
||||||
|
mutableUserStateTransactionCountStateFlow.value > 0 ||
|
||||||
|
vaultLockManager.isActiveUserUnlockingFlow.value
|
||||||
|
}
|
||||||
|
.stateIn(
|
||||||
|
scope = unconfinedScope,
|
||||||
|
started = SharingStarted.Eagerly,
|
||||||
|
initialValue = authDiskSource
|
||||||
|
.userState
|
||||||
|
?.toUserState(
|
||||||
|
vaultState = vaultLockManager.vaultUnlockDataStateFlow.value,
|
||||||
|
userAccountTokens = authDiskSource.userAccountTokens,
|
||||||
|
userOrganizationsList = authDiskSource.userOrganizationsList,
|
||||||
|
userIsUsingKeyConnectorList = authDiskSource.userKeyConnectorStateList,
|
||||||
|
hasPendingAccountAddition = mutableHasPendingAccountAdditionStateFlow.value,
|
||||||
|
onboardingStatus = authDiskSource.currentOnboardingStatus,
|
||||||
|
isBiometricsEnabledProvider = ::isBiometricsEnabled,
|
||||||
|
vaultUnlockTypeProvider = ::getVaultUnlockType,
|
||||||
|
isDeviceTrustedProvider = ::isDeviceTrusted,
|
||||||
|
firstTimeState = firstTimeActionManager.currentOrDefaultUserFirstTimeState,
|
||||||
|
getUserPolicies = ::existingPolicies,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
|
||||||
|
override suspend fun <T> userStateTransaction(block: suspend () -> T): T {
|
||||||
|
mutableUserStateTransactionCountStateFlow.update { it.inc() }
|
||||||
|
return try {
|
||||||
|
block()
|
||||||
|
} finally {
|
||||||
|
mutableUserStateTransactionCountStateFlow.update { it.dec() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun isBiometricsEnabled(
|
||||||
|
userId: String,
|
||||||
|
): Boolean = authDiskSource.getUserBiometricUnlockKey(userId = userId) != null
|
||||||
|
|
||||||
|
private fun isDeviceTrusted(
|
||||||
|
userId: String,
|
||||||
|
): Boolean = authDiskSource.getDeviceKey(userId = userId) != null
|
||||||
|
|
||||||
|
private fun getVaultUnlockType(
|
||||||
|
userId: String,
|
||||||
|
): VaultUnlockType = authDiskSource
|
||||||
|
.getPinProtectedUserKeyEnvelope(userId = userId)
|
||||||
|
?.let { VaultUnlockType.PIN }
|
||||||
|
?: VaultUnlockType.MASTER_PASSWORD
|
||||||
|
|
||||||
|
private fun existingPolicies(
|
||||||
|
userId: String,
|
||||||
|
policyType: PolicyTypeJson,
|
||||||
|
): List<SyncResponseJson.Policy> = policyManager.getUserPolicies(
|
||||||
|
userId = userId,
|
||||||
|
type = policyType,
|
||||||
|
)
|
||||||
|
}
|
||||||
@ -1,8 +1,8 @@
|
|||||||
package com.x8bit.bitwarden.data.auth.manager.di
|
package com.x8bit.bitwarden.data.auth.manager.di
|
||||||
|
|
||||||
import android.content.Context
|
import android.content.Context
|
||||||
|
import com.bitwarden.core.data.manager.dispatcher.DispatcherManager
|
||||||
import com.bitwarden.core.data.manager.toast.ToastManager
|
import com.bitwarden.core.data.manager.toast.ToastManager
|
||||||
import com.bitwarden.data.manager.DispatcherManager
|
|
||||||
import com.bitwarden.network.service.AccountsService
|
import com.bitwarden.network.service.AccountsService
|
||||||
import com.bitwarden.network.service.AuthRequestsService
|
import com.bitwarden.network.service.AuthRequestsService
|
||||||
import com.bitwarden.network.service.DevicesService
|
import com.bitwarden.network.service.DevicesService
|
||||||
@ -17,6 +17,8 @@ import com.x8bit.bitwarden.data.auth.manager.AuthRequestNotificationManager
|
|||||||
import com.x8bit.bitwarden.data.auth.manager.AuthRequestNotificationManagerImpl
|
import com.x8bit.bitwarden.data.auth.manager.AuthRequestNotificationManagerImpl
|
||||||
import com.x8bit.bitwarden.data.auth.manager.AuthTokenManager
|
import com.x8bit.bitwarden.data.auth.manager.AuthTokenManager
|
||||||
import com.x8bit.bitwarden.data.auth.manager.AuthTokenManagerImpl
|
import com.x8bit.bitwarden.data.auth.manager.AuthTokenManagerImpl
|
||||||
|
import com.x8bit.bitwarden.data.auth.manager.KdfManager
|
||||||
|
import com.x8bit.bitwarden.data.auth.manager.KdfManagerImpl
|
||||||
import com.x8bit.bitwarden.data.auth.manager.KeyConnectorManager
|
import com.x8bit.bitwarden.data.auth.manager.KeyConnectorManager
|
||||||
import com.x8bit.bitwarden.data.auth.manager.KeyConnectorManagerImpl
|
import com.x8bit.bitwarden.data.auth.manager.KeyConnectorManagerImpl
|
||||||
import com.x8bit.bitwarden.data.auth.manager.TrustedDeviceManager
|
import com.x8bit.bitwarden.data.auth.manager.TrustedDeviceManager
|
||||||
@ -25,6 +27,8 @@ import com.x8bit.bitwarden.data.auth.manager.UserLogoutManager
|
|||||||
import com.x8bit.bitwarden.data.auth.manager.UserLogoutManagerImpl
|
import com.x8bit.bitwarden.data.auth.manager.UserLogoutManagerImpl
|
||||||
import com.x8bit.bitwarden.data.platform.datasource.disk.PushDiskSource
|
import com.x8bit.bitwarden.data.platform.datasource.disk.PushDiskSource
|
||||||
import com.x8bit.bitwarden.data.platform.datasource.disk.SettingsDiskSource
|
import com.x8bit.bitwarden.data.platform.datasource.disk.SettingsDiskSource
|
||||||
|
import com.x8bit.bitwarden.data.platform.manager.CredentialExchangeRegistryManager
|
||||||
|
import com.x8bit.bitwarden.data.platform.manager.FeatureFlagManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.PushManager
|
import com.x8bit.bitwarden.data.platform.manager.PushManager
|
||||||
import com.x8bit.bitwarden.data.tools.generator.datasource.disk.GeneratorDiskSource
|
import com.x8bit.bitwarden.data.tools.generator.datasource.disk.GeneratorDiskSource
|
||||||
import com.x8bit.bitwarden.data.tools.generator.datasource.disk.PasswordHistoryDiskSource
|
import com.x8bit.bitwarden.data.tools.generator.datasource.disk.PasswordHistoryDiskSource
|
||||||
@ -117,6 +121,7 @@ object AuthManagerModule {
|
|||||||
vaultDiskSource: VaultDiskSource,
|
vaultDiskSource: VaultDiskSource,
|
||||||
vaultSdkSource: VaultSdkSource,
|
vaultSdkSource: VaultSdkSource,
|
||||||
dispatcherManager: DispatcherManager,
|
dispatcherManager: DispatcherManager,
|
||||||
|
credentialExchangeRegistryManager: CredentialExchangeRegistryManager,
|
||||||
): UserLogoutManager =
|
): UserLogoutManager =
|
||||||
UserLogoutManagerImpl(
|
UserLogoutManagerImpl(
|
||||||
authDiskSource = authDiskSource,
|
authDiskSource = authDiskSource,
|
||||||
@ -128,6 +133,7 @@ object AuthManagerModule {
|
|||||||
vaultDiskSource = vaultDiskSource,
|
vaultDiskSource = vaultDiskSource,
|
||||||
vaultSdkSource = vaultSdkSource,
|
vaultSdkSource = vaultSdkSource,
|
||||||
dispatcherManager = dispatcherManager,
|
dispatcherManager = dispatcherManager,
|
||||||
|
credentialExchangeRegistryManager = credentialExchangeRegistryManager,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Provides
|
@Provides
|
||||||
@ -140,4 +146,18 @@ object AuthManagerModule {
|
|||||||
fun providesAuthTokenManager(
|
fun providesAuthTokenManager(
|
||||||
authDiskSource: AuthDiskSource,
|
authDiskSource: AuthDiskSource,
|
||||||
): AuthTokenManager = AuthTokenManagerImpl(authDiskSource = authDiskSource)
|
): AuthTokenManager = AuthTokenManagerImpl(authDiskSource = authDiskSource)
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun providesKdfManager(
|
||||||
|
authDiskSource: AuthDiskSource,
|
||||||
|
vaultSdkSource: VaultSdkSource,
|
||||||
|
accountsService: AccountsService,
|
||||||
|
featureFlagManager: FeatureFlagManager,
|
||||||
|
): KdfManager = KdfManagerImpl(
|
||||||
|
authDiskSource = authDiskSource,
|
||||||
|
vaultSdkSource = vaultSdkSource,
|
||||||
|
accountsService = accountsService,
|
||||||
|
featureFlagManager = featureFlagManager,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -26,6 +26,7 @@ fun TrustDeviceResponse.toUserStateJson(
|
|||||||
hasMasterPassword = false,
|
hasMasterPassword = false,
|
||||||
trustedDeviceUserDecryptionOptions = null,
|
trustedDeviceUserDecryptionOptions = null,
|
||||||
keyConnectorUserDecryptionOptions = null,
|
keyConnectorUserDecryptionOptions = null,
|
||||||
|
masterPasswordUnlock = null,
|
||||||
)
|
)
|
||||||
val deviceOptions = decryptionOptions
|
val deviceOptions = decryptionOptions
|
||||||
.trustedDeviceUserDecryptionOptions
|
.trustedDeviceUserDecryptionOptions
|
||||||
|
|||||||
@ -6,6 +6,8 @@ import com.bitwarden.network.model.TwoFactorDataModel
|
|||||||
import com.x8bit.bitwarden.data.auth.datasource.disk.model.ForcePasswordResetReason
|
import com.x8bit.bitwarden.data.auth.datasource.disk.model.ForcePasswordResetReason
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.disk.model.OnboardingStatus
|
import com.x8bit.bitwarden.data.auth.datasource.disk.model.OnboardingStatus
|
||||||
import com.x8bit.bitwarden.data.auth.manager.AuthRequestManager
|
import com.x8bit.bitwarden.data.auth.manager.AuthRequestManager
|
||||||
|
import com.x8bit.bitwarden.data.auth.manager.KdfManager
|
||||||
|
import com.x8bit.bitwarden.data.auth.manager.UserStateManager
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.AuthState
|
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.BreachCountResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.DeleteAccountResult
|
import com.x8bit.bitwarden.data.auth.repository.model.DeleteAccountResult
|
||||||
@ -27,17 +29,16 @@ import com.x8bit.bitwarden.data.auth.repository.model.ResetPasswordResult
|
|||||||
import com.x8bit.bitwarden.data.auth.repository.model.SendVerificationEmailResult
|
import com.x8bit.bitwarden.data.auth.repository.model.SendVerificationEmailResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.SetPasswordResult
|
import com.x8bit.bitwarden.data.auth.repository.model.SetPasswordResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.SwitchAccountResult
|
import com.x8bit.bitwarden.data.auth.repository.model.SwitchAccountResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.UserState
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.ValidatePasswordResult
|
import com.x8bit.bitwarden.data.auth.repository.model.ValidatePasswordResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.ValidatePinResult
|
import com.x8bit.bitwarden.data.auth.repository.model.ValidatePinResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.VerifiedOrganizationDomainSsoDetailsResult
|
import com.x8bit.bitwarden.data.auth.repository.model.VerifiedOrganizationDomainSsoDetailsResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.VerifyOtpResult
|
import com.x8bit.bitwarden.data.auth.repository.model.VerifyOtpResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.CaptchaCallbackTokenResult
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.DuoCallbackTokenResult
|
import com.x8bit.bitwarden.data.auth.repository.util.DuoCallbackTokenResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.SsoCallbackResult
|
import com.x8bit.bitwarden.data.auth.repository.util.SsoCallbackResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.WebAuthResult
|
import com.x8bit.bitwarden.data.auth.repository.util.WebAuthResult
|
||||||
import com.x8bit.bitwarden.data.auth.util.YubiKeyResult
|
import com.x8bit.bitwarden.data.auth.util.YubiKeyResult
|
||||||
import com.x8bit.bitwarden.data.platform.datasource.network.authenticator.AuthenticatorProvider
|
import com.x8bit.bitwarden.data.platform.datasource.network.authenticator.AuthenticatorProvider
|
||||||
|
import com.x8bit.bitwarden.data.platform.manager.BiometricsEncryptionManager
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
|
|
||||||
@ -45,23 +46,17 @@ import kotlinx.coroutines.flow.StateFlow
|
|||||||
* Provides an API for observing an modifying authentication state.
|
* Provides an API for observing an modifying authentication state.
|
||||||
*/
|
*/
|
||||||
@Suppress("TooManyFunctions")
|
@Suppress("TooManyFunctions")
|
||||||
interface AuthRepository : AuthenticatorProvider, AuthRequestManager {
|
interface AuthRepository :
|
||||||
|
AuthenticatorProvider,
|
||||||
|
AuthRequestManager,
|
||||||
|
BiometricsEncryptionManager,
|
||||||
|
KdfManager,
|
||||||
|
UserStateManager {
|
||||||
/**
|
/**
|
||||||
* Models the current auth state.
|
* Models the current auth state.
|
||||||
*/
|
*/
|
||||||
val authStateFlow: StateFlow<AuthState>
|
val authStateFlow: StateFlow<AuthState>
|
||||||
|
|
||||||
/**
|
|
||||||
* Emits updates for changes to the [UserState].
|
|
||||||
*/
|
|
||||||
val userStateFlow: StateFlow<UserState?>
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Flow of the current [CaptchaCallbackTokenResult]. Subscribers should listen to the flow
|
|
||||||
* in order to receive updates whenever [setCaptchaCallbackTokenResult] is called.
|
|
||||||
*/
|
|
||||||
val captchaTokenResultFlow: Flow<CaptchaCallbackTokenResult>
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Flow of the current [DuoCallbackTokenResult]. Subscribers should listen to the flow
|
* Flow of the current [DuoCallbackTokenResult]. Subscribers should listen to the flow
|
||||||
* in order to receive updates whenever [setDuoCallbackTokenResult] is called.
|
* in order to receive updates whenever [setDuoCallbackTokenResult] is called.
|
||||||
@ -117,15 +112,6 @@ interface AuthRepository : AuthenticatorProvider, AuthRequestManager {
|
|||||||
*/
|
*/
|
||||||
var shouldTrustDevice: Boolean
|
var shouldTrustDevice: Boolean
|
||||||
|
|
||||||
/**
|
|
||||||
* Tracks whether there is an additional account that is pending login/registration in order to
|
|
||||||
* have multiple accounts available.
|
|
||||||
*
|
|
||||||
* This allows a direct view into and modification of [UserState.hasPendingAccountAddition].
|
|
||||||
* Note that this call has no effect when there is no [UserState] information available.
|
|
||||||
*/
|
|
||||||
var hasPendingAccountAddition: Boolean
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Return the cached password policies for the current user.
|
* Return the cached password policies for the current user.
|
||||||
*/
|
*/
|
||||||
@ -147,11 +133,6 @@ interface AuthRepository : AuthenticatorProvider, AuthRequestManager {
|
|||||||
*/
|
*/
|
||||||
val showWelcomeCarousel: Boolean
|
val showWelcomeCarousel: Boolean
|
||||||
|
|
||||||
/**
|
|
||||||
* Clears the pending deletion state that occurs when the an account is successfully deleted.
|
|
||||||
*/
|
|
||||||
fun clearPendingAccountDeletion()
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Attempt to delete the current account using the [masterPassword] and log them out
|
* Attempt to delete the current account using the [masterPassword] and log them out
|
||||||
* upon success.
|
* upon success.
|
||||||
@ -186,7 +167,6 @@ interface AuthRepository : AuthenticatorProvider, AuthRequestManager {
|
|||||||
suspend fun login(
|
suspend fun login(
|
||||||
email: String,
|
email: String,
|
||||||
password: String,
|
password: String,
|
||||||
captchaToken: String?,
|
|
||||||
): LoginResult
|
): LoginResult
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -201,7 +181,6 @@ interface AuthRepository : AuthenticatorProvider, AuthRequestManager {
|
|||||||
asymmetricalKey: String,
|
asymmetricalKey: String,
|
||||||
requestPrivateKey: String,
|
requestPrivateKey: String,
|
||||||
masterPasswordHash: String?,
|
masterPasswordHash: String?,
|
||||||
captchaToken: String?,
|
|
||||||
): LoginResult
|
): LoginResult
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -213,7 +192,6 @@ interface AuthRepository : AuthenticatorProvider, AuthRequestManager {
|
|||||||
email: String,
|
email: String,
|
||||||
password: String?,
|
password: String?,
|
||||||
twoFactorData: TwoFactorDataModel,
|
twoFactorData: TwoFactorDataModel,
|
||||||
captchaToken: String?,
|
|
||||||
orgIdentifier: String?,
|
orgIdentifier: String?,
|
||||||
): LoginResult
|
): LoginResult
|
||||||
|
|
||||||
@ -226,7 +204,6 @@ interface AuthRepository : AuthenticatorProvider, AuthRequestManager {
|
|||||||
ssoCode: String,
|
ssoCode: String,
|
||||||
ssoCodeVerifier: String,
|
ssoCodeVerifier: String,
|
||||||
ssoRedirectUri: String,
|
ssoRedirectUri: String,
|
||||||
captchaToken: String?,
|
|
||||||
organizationIdentifier: String,
|
organizationIdentifier: String,
|
||||||
): LoginResult
|
): LoginResult
|
||||||
|
|
||||||
@ -239,7 +216,6 @@ interface AuthRepository : AuthenticatorProvider, AuthRequestManager {
|
|||||||
email: String,
|
email: String,
|
||||||
password: String?,
|
password: String?,
|
||||||
newDeviceOtp: String,
|
newDeviceOtp: String,
|
||||||
captchaToken: String?,
|
|
||||||
orgIdentifier: String?,
|
orgIdentifier: String?,
|
||||||
): LoginResult
|
): LoginResult
|
||||||
|
|
||||||
@ -294,7 +270,6 @@ interface AuthRepository : AuthenticatorProvider, AuthRequestManager {
|
|||||||
masterPassword: String,
|
masterPassword: String,
|
||||||
masterPasswordHint: String?,
|
masterPasswordHint: String?,
|
||||||
emailVerificationToken: String? = null,
|
emailVerificationToken: String? = null,
|
||||||
captchaToken: String?,
|
|
||||||
shouldCheckDataBreaches: Boolean,
|
shouldCheckDataBreaches: Boolean,
|
||||||
isMasterPasswordStrong: Boolean,
|
isMasterPasswordStrong: Boolean,
|
||||||
): RegisterResult
|
): RegisterResult
|
||||||
@ -332,11 +307,6 @@ interface AuthRepository : AuthenticatorProvider, AuthRequestManager {
|
|||||||
passwordHint: String?,
|
passwordHint: String?,
|
||||||
): SetPasswordResult
|
): SetPasswordResult
|
||||||
|
|
||||||
/**
|
|
||||||
* Set the value of [captchaTokenResultFlow].
|
|
||||||
*/
|
|
||||||
fun setCaptchaCallbackTokenResult(tokenResult: CaptchaCallbackTokenResult)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Set the value of [duoTokenResultFlow].
|
* Set the value of [duoTokenResultFlow].
|
||||||
*/
|
*/
|
||||||
|
|||||||
@ -2,6 +2,8 @@ package com.x8bit.bitwarden.data.auth.repository
|
|||||||
|
|
||||||
import com.bitwarden.core.AuthRequestMethod
|
import com.bitwarden.core.AuthRequestMethod
|
||||||
import com.bitwarden.core.InitUserCryptoMethod
|
import com.bitwarden.core.InitUserCryptoMethod
|
||||||
|
import com.bitwarden.core.data.manager.dispatcher.DispatcherManager
|
||||||
|
import com.bitwarden.core.data.repository.error.MissingPropertyException
|
||||||
import com.bitwarden.core.data.repository.util.bufferedMutableSharedFlow
|
import com.bitwarden.core.data.repository.util.bufferedMutableSharedFlow
|
||||||
import com.bitwarden.core.data.util.asFailure
|
import com.bitwarden.core.data.util.asFailure
|
||||||
import com.bitwarden.core.data.util.asSuccess
|
import com.bitwarden.core.data.util.asSuccess
|
||||||
@ -9,7 +11,6 @@ import com.bitwarden.core.data.util.flatMap
|
|||||||
import com.bitwarden.crypto.HashPurpose
|
import com.bitwarden.crypto.HashPurpose
|
||||||
import com.bitwarden.crypto.Kdf
|
import com.bitwarden.crypto.Kdf
|
||||||
import com.bitwarden.data.datasource.disk.ConfigDiskSource
|
import com.bitwarden.data.datasource.disk.ConfigDiskSource
|
||||||
import com.bitwarden.data.manager.DispatcherManager
|
|
||||||
import com.bitwarden.data.repository.util.toEnvironmentUrls
|
import com.bitwarden.data.repository.util.toEnvironmentUrls
|
||||||
import com.bitwarden.data.repository.util.toEnvironmentUrlsOrDefault
|
import com.bitwarden.data.repository.util.toEnvironmentUrlsOrDefault
|
||||||
import com.bitwarden.network.model.DeleteAccountResponseJson
|
import com.bitwarden.network.model.DeleteAccountResponseJson
|
||||||
@ -33,6 +34,8 @@ import com.bitwarden.network.model.SyncResponseJson
|
|||||||
import com.bitwarden.network.model.TrustedDeviceUserDecryptionOptionsJson
|
import com.bitwarden.network.model.TrustedDeviceUserDecryptionOptionsJson
|
||||||
import com.bitwarden.network.model.TwoFactorAuthMethod
|
import com.bitwarden.network.model.TwoFactorAuthMethod
|
||||||
import com.bitwarden.network.model.TwoFactorDataModel
|
import com.bitwarden.network.model.TwoFactorDataModel
|
||||||
|
import com.bitwarden.network.model.VerificationCodeResponseJson
|
||||||
|
import com.bitwarden.network.model.VerificationOtpResponseJson
|
||||||
import com.bitwarden.network.model.VerifyEmailTokenRequestJson
|
import com.bitwarden.network.model.VerifyEmailTokenRequestJson
|
||||||
import com.bitwarden.network.model.VerifyEmailTokenResponseJson
|
import com.bitwarden.network.model.VerifyEmailTokenResponseJson
|
||||||
import com.bitwarden.network.service.AccountsService
|
import com.bitwarden.network.service.AccountsService
|
||||||
@ -46,15 +49,16 @@ import com.x8bit.bitwarden.data.auth.datasource.disk.model.AccountJson
|
|||||||
import com.x8bit.bitwarden.data.auth.datasource.disk.model.AccountTokensJson
|
import com.x8bit.bitwarden.data.auth.datasource.disk.model.AccountTokensJson
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.disk.model.ForcePasswordResetReason
|
import com.x8bit.bitwarden.data.auth.datasource.disk.model.ForcePasswordResetReason
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.disk.model.OnboardingStatus
|
import com.x8bit.bitwarden.data.auth.datasource.disk.model.OnboardingStatus
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.disk.model.UserStateJson
|
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.network.model.DeviceDataModel
|
import com.x8bit.bitwarden.data.auth.datasource.network.model.DeviceDataModel
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.sdk.AuthSdkSource
|
import com.x8bit.bitwarden.data.auth.datasource.sdk.AuthSdkSource
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.sdk.util.toInt
|
import com.x8bit.bitwarden.data.auth.datasource.sdk.util.toInt
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.sdk.util.toKdfTypeJson
|
import com.x8bit.bitwarden.data.auth.datasource.sdk.util.toKdfTypeJson
|
||||||
import com.x8bit.bitwarden.data.auth.manager.AuthRequestManager
|
import com.x8bit.bitwarden.data.auth.manager.AuthRequestManager
|
||||||
|
import com.x8bit.bitwarden.data.auth.manager.KdfManager
|
||||||
import com.x8bit.bitwarden.data.auth.manager.KeyConnectorManager
|
import com.x8bit.bitwarden.data.auth.manager.KeyConnectorManager
|
||||||
import com.x8bit.bitwarden.data.auth.manager.TrustedDeviceManager
|
import com.x8bit.bitwarden.data.auth.manager.TrustedDeviceManager
|
||||||
import com.x8bit.bitwarden.data.auth.manager.UserLogoutManager
|
import com.x8bit.bitwarden.data.auth.manager.UserLogoutManager
|
||||||
|
import com.x8bit.bitwarden.data.auth.manager.UserStateManager
|
||||||
import com.x8bit.bitwarden.data.auth.manager.model.MigrateExistingUserToKeyConnectorResult
|
import com.x8bit.bitwarden.data.auth.manager.model.MigrateExistingUserToKeyConnectorResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.AuthState
|
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.BreachCountResult
|
||||||
@ -77,65 +81,49 @@ import com.x8bit.bitwarden.data.auth.repository.model.ResetPasswordResult
|
|||||||
import com.x8bit.bitwarden.data.auth.repository.model.SendVerificationEmailResult
|
import com.x8bit.bitwarden.data.auth.repository.model.SendVerificationEmailResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.SetPasswordResult
|
import com.x8bit.bitwarden.data.auth.repository.model.SetPasswordResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.SwitchAccountResult
|
import com.x8bit.bitwarden.data.auth.repository.model.SwitchAccountResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.UserAccountTokens
|
import com.x8bit.bitwarden.data.auth.repository.model.UpdateKdfMinimumsResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.UserKeyConnectorState
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.UserOrganizations
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.UserState
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.ValidatePasswordResult
|
import com.x8bit.bitwarden.data.auth.repository.model.ValidatePasswordResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.ValidatePinResult
|
import com.x8bit.bitwarden.data.auth.repository.model.ValidatePinResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.VaultUnlockType
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.VerifiedOrganizationDomainSsoDetailsResult
|
import com.x8bit.bitwarden.data.auth.repository.model.VerifiedOrganizationDomainSsoDetailsResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.VerifyOtpResult
|
import com.x8bit.bitwarden.data.auth.repository.model.VerifyOtpResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.toLoginErrorResult
|
import com.x8bit.bitwarden.data.auth.repository.model.toLoginErrorResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.CaptchaCallbackTokenResult
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.DuoCallbackTokenResult
|
import com.x8bit.bitwarden.data.auth.repository.util.DuoCallbackTokenResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.SsoCallbackResult
|
import com.x8bit.bitwarden.data.auth.repository.util.SsoCallbackResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.WebAuthResult
|
import com.x8bit.bitwarden.data.auth.repository.util.WebAuthResult
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.activeUserIdChangesFlow
|
import com.x8bit.bitwarden.data.auth.repository.util.activeUserIdChangesFlow
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.currentOnboardingStatus
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.onboardingStatusChangesFlow
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.policyInformation
|
import com.x8bit.bitwarden.data.auth.repository.util.policyInformation
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.toRemovedPasswordUserStateJson
|
import com.x8bit.bitwarden.data.auth.repository.util.toRemovedPasswordUserStateJson
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.toSdkParams
|
import com.x8bit.bitwarden.data.auth.repository.util.toSdkParams
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.toUserState
|
import com.x8bit.bitwarden.data.auth.repository.util.toUserState
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.toUserStateJsonWithPassword
|
import com.x8bit.bitwarden.data.auth.repository.util.toUserStateJsonWithPassword
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.userAccountTokens
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.userAccountTokensFlow
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.userKeyConnectorStateFlow
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.userKeyConnectorStateList
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.userOrganizationsList
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.userOrganizationsListFlow
|
|
||||||
import com.x8bit.bitwarden.data.auth.repository.util.userSwitchingChangesFlow
|
import com.x8bit.bitwarden.data.auth.repository.util.userSwitchingChangesFlow
|
||||||
import com.x8bit.bitwarden.data.auth.util.KdfParamsConstants.DEFAULT_PBKDF2_ITERATIONS
|
import com.x8bit.bitwarden.data.auth.util.KdfParamsConstants.DEFAULT_PBKDF2_ITERATIONS
|
||||||
import com.x8bit.bitwarden.data.auth.util.YubiKeyResult
|
import com.x8bit.bitwarden.data.auth.util.YubiKeyResult
|
||||||
import com.x8bit.bitwarden.data.auth.util.toSdkParams
|
import com.x8bit.bitwarden.data.auth.util.toSdkParams
|
||||||
import com.x8bit.bitwarden.data.platform.error.MissingPropertyException
|
import com.x8bit.bitwarden.data.platform.datasource.disk.SettingsDiskSource
|
||||||
import com.x8bit.bitwarden.data.platform.error.NoActiveUserException
|
import com.x8bit.bitwarden.data.platform.error.NoActiveUserException
|
||||||
import com.x8bit.bitwarden.data.platform.manager.FirstTimeActionManager
|
import com.x8bit.bitwarden.data.platform.manager.BiometricsEncryptionManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.LogsManager
|
import com.x8bit.bitwarden.data.platform.manager.LogsManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.PolicyManager
|
import com.x8bit.bitwarden.data.platform.manager.PolicyManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.PushManager
|
import com.x8bit.bitwarden.data.platform.manager.PushManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.model.FirstTimeState
|
|
||||||
import com.x8bit.bitwarden.data.platform.manager.util.getActivePolicies
|
import com.x8bit.bitwarden.data.platform.manager.util.getActivePolicies
|
||||||
import com.x8bit.bitwarden.data.platform.repository.EnvironmentRepository
|
import com.x8bit.bitwarden.data.platform.repository.EnvironmentRepository
|
||||||
import com.x8bit.bitwarden.data.platform.repository.SettingsRepository
|
import com.x8bit.bitwarden.data.platform.repository.SettingsRepository
|
||||||
import com.x8bit.bitwarden.data.vault.datasource.sdk.VaultSdkSource
|
import com.x8bit.bitwarden.data.vault.datasource.sdk.VaultSdkSource
|
||||||
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
|
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
|
||||||
import com.x8bit.bitwarden.data.vault.repository.model.VaultUnlockData
|
|
||||||
import com.x8bit.bitwarden.data.vault.repository.model.VaultUnlockError
|
import com.x8bit.bitwarden.data.vault.repository.model.VaultUnlockError
|
||||||
import com.x8bit.bitwarden.data.vault.repository.model.VaultUnlockResult
|
import com.x8bit.bitwarden.data.vault.repository.model.VaultUnlockResult
|
||||||
|
import com.x8bit.bitwarden.data.vault.repository.util.toSdkMasterPasswordUnlock
|
||||||
import kotlinx.coroutines.CoroutineScope
|
import kotlinx.coroutines.CoroutineScope
|
||||||
import kotlinx.coroutines.Dispatchers
|
import kotlinx.coroutines.Dispatchers
|
||||||
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
import kotlinx.coroutines.ExperimentalCoroutinesApi
|
||||||
import kotlinx.coroutines.channels.Channel
|
import kotlinx.coroutines.channels.Channel
|
||||||
import kotlinx.coroutines.flow.Flow
|
import kotlinx.coroutines.flow.Flow
|
||||||
import kotlinx.coroutines.flow.MutableStateFlow
|
|
||||||
import kotlinx.coroutines.flow.SharingStarted
|
import kotlinx.coroutines.flow.SharingStarted
|
||||||
import kotlinx.coroutines.flow.StateFlow
|
import kotlinx.coroutines.flow.StateFlow
|
||||||
import kotlinx.coroutines.flow.asSharedFlow
|
import kotlinx.coroutines.flow.asSharedFlow
|
||||||
import kotlinx.coroutines.flow.combine
|
import kotlinx.coroutines.flow.combine
|
||||||
import kotlinx.coroutines.flow.filter
|
import kotlinx.coroutines.flow.filter
|
||||||
import kotlinx.coroutines.flow.filterNot
|
|
||||||
import kotlinx.coroutines.flow.flatMapLatest
|
import kotlinx.coroutines.flow.flatMapLatest
|
||||||
import kotlinx.coroutines.flow.flowOf
|
import kotlinx.coroutines.flow.flowOf
|
||||||
import kotlinx.coroutines.flow.launchIn
|
import kotlinx.coroutines.flow.launchIn
|
||||||
@ -145,7 +133,8 @@ import kotlinx.coroutines.flow.merge
|
|||||||
import kotlinx.coroutines.flow.onEach
|
import kotlinx.coroutines.flow.onEach
|
||||||
import kotlinx.coroutines.flow.receiveAsFlow
|
import kotlinx.coroutines.flow.receiveAsFlow
|
||||||
import kotlinx.coroutines.flow.stateIn
|
import kotlinx.coroutines.flow.stateIn
|
||||||
import kotlinx.coroutines.flow.update
|
import timber.log.Timber
|
||||||
|
import java.time.Clock
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -154,6 +143,7 @@ import javax.inject.Singleton
|
|||||||
@Suppress("LargeClass", "LongParameterList", "TooManyFunctions")
|
@Suppress("LargeClass", "LongParameterList", "TooManyFunctions")
|
||||||
@Singleton
|
@Singleton
|
||||||
class AuthRepositoryImpl(
|
class AuthRepositoryImpl(
|
||||||
|
private val clock: Clock,
|
||||||
private val accountsService: AccountsService,
|
private val accountsService: AccountsService,
|
||||||
private val devicesService: DevicesService,
|
private val devicesService: DevicesService,
|
||||||
private val haveIBeenPwnedService: HaveIBeenPwnedService,
|
private val haveIBeenPwnedService: HaveIBeenPwnedService,
|
||||||
@ -162,21 +152,27 @@ class AuthRepositoryImpl(
|
|||||||
private val authSdkSource: AuthSdkSource,
|
private val authSdkSource: AuthSdkSource,
|
||||||
private val vaultSdkSource: VaultSdkSource,
|
private val vaultSdkSource: VaultSdkSource,
|
||||||
private val authDiskSource: AuthDiskSource,
|
private val authDiskSource: AuthDiskSource,
|
||||||
|
private val settingsDiskSource: SettingsDiskSource,
|
||||||
private val configDiskSource: ConfigDiskSource,
|
private val configDiskSource: ConfigDiskSource,
|
||||||
private val environmentRepository: EnvironmentRepository,
|
private val environmentRepository: EnvironmentRepository,
|
||||||
private val settingsRepository: SettingsRepository,
|
private val settingsRepository: SettingsRepository,
|
||||||
private val vaultRepository: VaultRepository,
|
private val vaultRepository: VaultRepository,
|
||||||
private val authRequestManager: AuthRequestManager,
|
private val authRequestManager: AuthRequestManager,
|
||||||
|
private val biometricsEncryptionManager: BiometricsEncryptionManager,
|
||||||
private val keyConnectorManager: KeyConnectorManager,
|
private val keyConnectorManager: KeyConnectorManager,
|
||||||
private val trustedDeviceManager: TrustedDeviceManager,
|
private val trustedDeviceManager: TrustedDeviceManager,
|
||||||
private val userLogoutManager: UserLogoutManager,
|
private val userLogoutManager: UserLogoutManager,
|
||||||
private val policyManager: PolicyManager,
|
private val policyManager: PolicyManager,
|
||||||
firstTimeActionManager: FirstTimeActionManager,
|
private val userStateManager: UserStateManager,
|
||||||
|
private val kdfManager: KdfManager,
|
||||||
logsManager: LogsManager,
|
logsManager: LogsManager,
|
||||||
pushManager: PushManager,
|
pushManager: PushManager,
|
||||||
dispatcherManager: DispatcherManager,
|
dispatcherManager: DispatcherManager,
|
||||||
) : AuthRepository,
|
) : AuthRepository,
|
||||||
AuthRequestManager by authRequestManager {
|
AuthRequestManager by authRequestManager,
|
||||||
|
BiometricsEncryptionManager by biometricsEncryptionManager,
|
||||||
|
KdfManager by kdfManager,
|
||||||
|
UserStateManager by userStateManager {
|
||||||
/**
|
/**
|
||||||
* A scope intended for use when simply collecting multiple flows in order to combine them. The
|
* A scope intended for use when simply collecting multiple flows in order to combine them. The
|
||||||
* use of [Dispatchers.Unconfined] allows for this to happen synchronously whenever any of
|
* use of [Dispatchers.Unconfined] allows for this to happen synchronously whenever any of
|
||||||
@ -189,24 +185,6 @@ class AuthRepositoryImpl(
|
|||||||
*/
|
*/
|
||||||
private val ioScope = CoroutineScope(dispatcherManager.io)
|
private val ioScope = CoroutineScope(dispatcherManager.io)
|
||||||
|
|
||||||
private val mutableHasPendingAccountAdditionStateFlow = MutableStateFlow(false)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* If there is a pending account deletion, continue showing the original UserState until it
|
|
||||||
* is confirmed. This is accomplished by blocking the emissions of the [userStateFlow]
|
|
||||||
* whenever set to `true`.
|
|
||||||
*/
|
|
||||||
private val mutableHasPendingAccountDeletionStateFlow = MutableStateFlow(false)
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Whenever a function needs to update multiple underlying data-points that contribute to the
|
|
||||||
* [UserState], we update this [MutableStateFlow] and continue to show the original `UserState`
|
|
||||||
* until the transaction is complete. This is accomplished by blocking the emissions of the
|
|
||||||
* [userStateFlow] whenever this is set to a value above 0 (a count is used if more than one
|
|
||||||
* process is updating data simultaneously).
|
|
||||||
*/
|
|
||||||
private val mutableUserStateTransactionCountStateFlow = MutableStateFlow(0)
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The auth information to make the identity token request will need to be
|
* The auth information to make the identity token request will need to be
|
||||||
* cached to make the request again in the case of two-factor authentication.
|
* cached to make the request again in the case of two-factor authentication.
|
||||||
@ -267,72 +245,6 @@ class AuthRepositoryImpl(
|
|||||||
initialValue = AuthState.Uninitialized,
|
initialValue = AuthState.Uninitialized,
|
||||||
)
|
)
|
||||||
|
|
||||||
@Suppress("UNCHECKED_CAST", "MagicNumber")
|
|
||||||
override val userStateFlow: StateFlow<UserState?> = combine(
|
|
||||||
authDiskSource.userStateFlow,
|
|
||||||
authDiskSource.userAccountTokensFlow,
|
|
||||||
authDiskSource.userOrganizationsListFlow,
|
|
||||||
authDiskSource.userKeyConnectorStateFlow,
|
|
||||||
authDiskSource.onboardingStatusChangesFlow,
|
|
||||||
firstTimeActionManager.firstTimeStateFlow,
|
|
||||||
vaultRepository.vaultUnlockDataStateFlow,
|
|
||||||
mutableHasPendingAccountAdditionStateFlow,
|
|
||||||
// Ignore the data in the merge, but trigger an update when they emit.
|
|
||||||
merge(
|
|
||||||
mutableHasPendingAccountDeletionStateFlow,
|
|
||||||
mutableUserStateTransactionCountStateFlow,
|
|
||||||
vaultRepository.isActiveUserUnlockingFlow,
|
|
||||||
),
|
|
||||||
) { array ->
|
|
||||||
val userStateJson = array[0] as UserStateJson?
|
|
||||||
val userAccountTokens = array[1] as List<UserAccountTokens>
|
|
||||||
val userOrganizationsList = array[2] as List<UserOrganizations>
|
|
||||||
val userIsUsingKeyConnectorList = array[3] as List<UserKeyConnectorState>
|
|
||||||
val onboardingStatus = array[4] as OnboardingStatus?
|
|
||||||
val firstTimeState = array[5] as FirstTimeState
|
|
||||||
val vaultState = array[6] as List<VaultUnlockData>
|
|
||||||
val hasPendingAccountAddition = array[7] as Boolean
|
|
||||||
userStateJson?.toUserState(
|
|
||||||
vaultState = vaultState,
|
|
||||||
userAccountTokens = userAccountTokens,
|
|
||||||
userOrganizationsList = userOrganizationsList,
|
|
||||||
userIsUsingKeyConnectorList = userIsUsingKeyConnectorList,
|
|
||||||
hasPendingAccountAddition = hasPendingAccountAddition,
|
|
||||||
onboardingStatus = onboardingStatus,
|
|
||||||
isBiometricsEnabledProvider = ::isBiometricsEnabled,
|
|
||||||
vaultUnlockTypeProvider = ::getVaultUnlockType,
|
|
||||||
isDeviceTrustedProvider = ::isDeviceTrusted,
|
|
||||||
firstTimeState = firstTimeState,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
.filterNot {
|
|
||||||
mutableHasPendingAccountDeletionStateFlow.value ||
|
|
||||||
mutableUserStateTransactionCountStateFlow.value > 0 ||
|
|
||||||
vaultRepository.isActiveUserUnlockingFlow.value
|
|
||||||
}
|
|
||||||
.stateIn(
|
|
||||||
scope = unconfinedScope,
|
|
||||||
started = SharingStarted.Eagerly,
|
|
||||||
initialValue = authDiskSource
|
|
||||||
.userState
|
|
||||||
?.toUserState(
|
|
||||||
vaultState = vaultRepository.vaultUnlockDataStateFlow.value,
|
|
||||||
userAccountTokens = authDiskSource.userAccountTokens,
|
|
||||||
userOrganizationsList = authDiskSource.userOrganizationsList,
|
|
||||||
userIsUsingKeyConnectorList = authDiskSource.userKeyConnectorStateList,
|
|
||||||
hasPendingAccountAddition = mutableHasPendingAccountAdditionStateFlow.value,
|
|
||||||
onboardingStatus = authDiskSource.currentOnboardingStatus,
|
|
||||||
isBiometricsEnabledProvider = ::isBiometricsEnabled,
|
|
||||||
vaultUnlockTypeProvider = ::getVaultUnlockType,
|
|
||||||
isDeviceTrustedProvider = ::isDeviceTrusted,
|
|
||||||
firstTimeState = firstTimeActionManager.currentOrDefaultUserFirstTimeState,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
|
|
||||||
private val captchaTokenChannel = Channel<CaptchaCallbackTokenResult>(capacity = Int.MAX_VALUE)
|
|
||||||
override val captchaTokenResultFlow: Flow<CaptchaCallbackTokenResult> =
|
|
||||||
captchaTokenChannel.receiveAsFlow()
|
|
||||||
|
|
||||||
private val duoTokenChannel = Channel<DuoCallbackTokenResult>(capacity = Int.MAX_VALUE)
|
private val duoTokenChannel = Channel<DuoCallbackTokenResult>(capacity = Int.MAX_VALUE)
|
||||||
override val duoTokenResultFlow: Flow<DuoCallbackTokenResult> = duoTokenChannel.receiveAsFlow()
|
override val duoTokenResultFlow: Flow<DuoCallbackTokenResult> = duoTokenChannel.receiveAsFlow()
|
||||||
|
|
||||||
@ -361,9 +273,6 @@ class AuthRepositoryImpl(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
override var hasPendingAccountAddition: Boolean
|
|
||||||
by mutableHasPendingAccountAdditionStateFlow::value
|
|
||||||
|
|
||||||
override val passwordPolicies: List<PolicyInformation.MasterPassword>
|
override val passwordPolicies: List<PolicyInformation.MasterPassword>
|
||||||
get() = policyManager.getActivePolicies()
|
get() = policyManager.getActivePolicies()
|
||||||
|
|
||||||
@ -382,7 +291,7 @@ class AuthRepositoryImpl(
|
|||||||
|
|
||||||
init {
|
init {
|
||||||
combine(
|
combine(
|
||||||
mutableHasPendingAccountAdditionStateFlow,
|
userStateManager.hasPendingAccountAdditionStateFlow,
|
||||||
authDiskSource.userStateFlow,
|
authDiskSource.userStateFlow,
|
||||||
environmentRepository.environmentStateFlow,
|
environmentRepository.environmentStateFlow,
|
||||||
) { hasPendingAddition, userState, environment ->
|
) { hasPendingAddition, userState, environment ->
|
||||||
@ -401,14 +310,21 @@ class AuthRepositoryImpl(
|
|||||||
.launchIn(unconfinedScope)
|
.launchIn(unconfinedScope)
|
||||||
pushManager
|
pushManager
|
||||||
.syncOrgKeysFlow
|
.syncOrgKeysFlow
|
||||||
.onEach {
|
.onEach { userId ->
|
||||||
val userId = activeUserId ?: return@onEach
|
// This will force the next authenticated request to refresh the auth token.
|
||||||
// TODO: [PM-20593] Investigate why tokens are explicitly refreshed.
|
authDiskSource.storeAccountTokens(
|
||||||
refreshAccessTokenSynchronouslyInternal(
|
|
||||||
userId = userId,
|
userId = userId,
|
||||||
logOutOnFailure = false,
|
accountTokens = authDiskSource
|
||||||
|
.getAccountTokens(userId = userId)
|
||||||
|
?.copy(expiresAtSec = 0L),
|
||||||
)
|
)
|
||||||
vaultRepository.sync(forced = true)
|
if (userId == activeUserId) {
|
||||||
|
// We just sync now to get the latest data
|
||||||
|
vaultRepository.sync(forced = true)
|
||||||
|
} else {
|
||||||
|
// We clear the last sync time to ensure we sync when we become the active user
|
||||||
|
settingsDiskSource.storeLastSyncTime(userId = userId, lastSyncTime = null)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
// This requires the ioScope to ensure that refreshAccessTokenSynchronously
|
// This requires the ioScope to ensure that refreshAccessTokenSynchronously
|
||||||
// happens on a background thread
|
// happens on a background thread
|
||||||
@ -466,16 +382,12 @@ class AuthRepositoryImpl(
|
|||||||
.launchIn(unconfinedScope)
|
.launchIn(unconfinedScope)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun clearPendingAccountDeletion() {
|
|
||||||
mutableHasPendingAccountDeletionStateFlow.value = false
|
|
||||||
}
|
|
||||||
|
|
||||||
override suspend fun deleteAccountWithMasterPassword(
|
override suspend fun deleteAccountWithMasterPassword(
|
||||||
masterPassword: String,
|
masterPassword: String,
|
||||||
): DeleteAccountResult {
|
): DeleteAccountResult {
|
||||||
val profile = authDiskSource.userState?.activeAccount?.profile
|
val profile = authDiskSource.userState?.activeAccount?.profile
|
||||||
?: return DeleteAccountResult.Error(message = null, error = NoActiveUserException())
|
?: return DeleteAccountResult.Error(message = null, error = NoActiveUserException())
|
||||||
mutableHasPendingAccountDeletionStateFlow.value = true
|
userStateManager.hasPendingAccountDeletion = true
|
||||||
return authSdkSource
|
return authSdkSource
|
||||||
.hashPassword(
|
.hashPassword(
|
||||||
email = profile.email,
|
email = profile.email,
|
||||||
@ -495,7 +407,7 @@ class AuthRepositoryImpl(
|
|||||||
override suspend fun deleteAccountWithOneTimePassword(
|
override suspend fun deleteAccountWithOneTimePassword(
|
||||||
oneTimePassword: String,
|
oneTimePassword: String,
|
||||||
): DeleteAccountResult {
|
): DeleteAccountResult {
|
||||||
mutableHasPendingAccountDeletionStateFlow.value = true
|
userStateManager.hasPendingAccountDeletion = true
|
||||||
return accountsService
|
return accountsService
|
||||||
.deleteAccount(
|
.deleteAccount(
|
||||||
masterPasswordHash = null,
|
masterPasswordHash = null,
|
||||||
@ -507,13 +419,13 @@ class AuthRepositoryImpl(
|
|||||||
private fun Result<DeleteAccountResponseJson>.finalizeDeleteAccount(): DeleteAccountResult =
|
private fun Result<DeleteAccountResponseJson>.finalizeDeleteAccount(): DeleteAccountResult =
|
||||||
fold(
|
fold(
|
||||||
onFailure = {
|
onFailure = {
|
||||||
clearPendingAccountDeletion()
|
userStateManager.hasPendingAccountDeletion = false
|
||||||
DeleteAccountResult.Error(error = it, message = null)
|
DeleteAccountResult.Error(error = it, message = null)
|
||||||
},
|
},
|
||||||
onSuccess = { response ->
|
onSuccess = { response ->
|
||||||
when (response) {
|
when (response) {
|
||||||
is DeleteAccountResponseJson.Invalid -> {
|
is DeleteAccountResponseJson.Invalid -> {
|
||||||
clearPendingAccountDeletion()
|
userStateManager.hasPendingAccountDeletion = false
|
||||||
DeleteAccountResult.Error(message = response.message, error = null)
|
DeleteAccountResult.Error(message = response.message, error = null)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -564,6 +476,10 @@ class AuthRepositoryImpl(
|
|||||||
.map { keys }
|
.map { keys }
|
||||||
}
|
}
|
||||||
.onSuccess { keys ->
|
.onSuccess { keys ->
|
||||||
|
// TDE and SSO user creation still uses crypto-v1. These users are not
|
||||||
|
// expected to have the AEAD keys so we only store the private key for now.
|
||||||
|
// See https://github.com/bitwarden/android/pull/5682#discussion_r2273940332
|
||||||
|
// for more details.
|
||||||
authDiskSource.storePrivateKey(
|
authDiskSource.storePrivateKey(
|
||||||
userId = userId,
|
userId = userId,
|
||||||
privateKey = keys.privateKey,
|
privateKey = keys.privateKey,
|
||||||
@ -592,11 +508,15 @@ class AuthRepositoryImpl(
|
|||||||
val profile = authDiskSource.userState?.activeAccount?.profile
|
val profile = authDiskSource.userState?.activeAccount?.profile
|
||||||
?: return LoginResult.Error(errorMessage = null, error = NoActiveUserException())
|
?: return LoginResult.Error(errorMessage = null, error = NoActiveUserException())
|
||||||
val userId = profile.userId
|
val userId = profile.userId
|
||||||
val privateKey = authDiskSource.getPrivateKey(userId = userId)
|
val accountKeys = authDiskSource.getAccountKeys(userId = userId)
|
||||||
|
val privateKey = accountKeys?.publicKeyEncryptionKeyPair?.wrappedPrivateKey
|
||||||
|
?: authDiskSource.getPrivateKey(userId = userId)
|
||||||
?: return LoginResult.Error(
|
?: return LoginResult.Error(
|
||||||
errorMessage = null,
|
errorMessage = null,
|
||||||
error = MissingPropertyException("Private Key"),
|
error = MissingPropertyException("Private Key"),
|
||||||
)
|
)
|
||||||
|
val signingKey = accountKeys?.signatureKeyPair?.wrappedSigningKey
|
||||||
|
val securityState = accountKeys?.securityState?.securityState
|
||||||
|
|
||||||
checkForVaultUnlockError(
|
checkForVaultUnlockError(
|
||||||
onVaultUnlockError = { error ->
|
onVaultUnlockError = { error ->
|
||||||
@ -606,6 +526,8 @@ class AuthRepositoryImpl(
|
|||||||
unlockVault(
|
unlockVault(
|
||||||
accountProfile = profile,
|
accountProfile = profile,
|
||||||
privateKey = privateKey,
|
privateKey = privateKey,
|
||||||
|
signingKey = signingKey,
|
||||||
|
securityState = securityState,
|
||||||
initUserCryptoMethod = InitUserCryptoMethod.AuthRequest(
|
initUserCryptoMethod = InitUserCryptoMethod.AuthRequest(
|
||||||
requestPrivateKey = requestPrivateKey,
|
requestPrivateKey = requestPrivateKey,
|
||||||
method = AuthRequestMethod.UserKey(protectedUserKey = asymmetricalKey),
|
method = AuthRequestMethod.UserKey(protectedUserKey = asymmetricalKey),
|
||||||
@ -620,7 +542,6 @@ class AuthRepositoryImpl(
|
|||||||
override suspend fun login(
|
override suspend fun login(
|
||||||
email: String,
|
email: String,
|
||||||
password: String,
|
password: String,
|
||||||
captchaToken: String?,
|
|
||||||
): LoginResult = identityService
|
): LoginResult = identityService
|
||||||
.preLogin(email = email)
|
.preLogin(email = email)
|
||||||
.flatMap {
|
.flatMap {
|
||||||
@ -639,7 +560,6 @@ class AuthRepositoryImpl(
|
|||||||
username = email,
|
username = email,
|
||||||
password = passwordHash,
|
password = passwordHash,
|
||||||
),
|
),
|
||||||
captchaToken = captchaToken,
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
.fold(
|
.fold(
|
||||||
@ -659,7 +579,6 @@ class AuthRepositoryImpl(
|
|||||||
asymmetricalKey: String,
|
asymmetricalKey: String,
|
||||||
requestPrivateKey: String,
|
requestPrivateKey: String,
|
||||||
masterPasswordHash: String?,
|
masterPasswordHash: String?,
|
||||||
captchaToken: String?,
|
|
||||||
): LoginResult =
|
): LoginResult =
|
||||||
loginCommon(
|
loginCommon(
|
||||||
email = email,
|
email = email,
|
||||||
@ -674,14 +593,12 @@ class AuthRepositoryImpl(
|
|||||||
asymmetricalKey = asymmetricalKey,
|
asymmetricalKey = asymmetricalKey,
|
||||||
privateKey = requestPrivateKey,
|
privateKey = requestPrivateKey,
|
||||||
),
|
),
|
||||||
captchaToken = captchaToken,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
override suspend fun login(
|
override suspend fun login(
|
||||||
email: String,
|
email: String,
|
||||||
password: String?,
|
password: String?,
|
||||||
twoFactorData: TwoFactorDataModel,
|
twoFactorData: TwoFactorDataModel,
|
||||||
captchaToken: String?,
|
|
||||||
orgIdentifier: String?,
|
orgIdentifier: String?,
|
||||||
): LoginResult = identityTokenAuthModel
|
): LoginResult = identityTokenAuthModel
|
||||||
?.let {
|
?.let {
|
||||||
@ -690,7 +607,6 @@ class AuthRepositoryImpl(
|
|||||||
password = password,
|
password = password,
|
||||||
authModel = it,
|
authModel = it,
|
||||||
twoFactorData = twoFactorData,
|
twoFactorData = twoFactorData,
|
||||||
captchaToken = captchaToken ?: twoFactorResponse?.captchaToken,
|
|
||||||
deviceData = twoFactorDeviceData,
|
deviceData = twoFactorDeviceData,
|
||||||
orgIdentifier = orgIdentifier,
|
orgIdentifier = orgIdentifier,
|
||||||
)
|
)
|
||||||
@ -704,7 +620,6 @@ class AuthRepositoryImpl(
|
|||||||
email: String,
|
email: String,
|
||||||
password: String?,
|
password: String?,
|
||||||
newDeviceOtp: String,
|
newDeviceOtp: String,
|
||||||
captchaToken: String?,
|
|
||||||
orgIdentifier: String?,
|
orgIdentifier: String?,
|
||||||
): LoginResult = identityTokenAuthModel
|
): LoginResult = identityTokenAuthModel
|
||||||
?.let {
|
?.let {
|
||||||
@ -713,7 +628,6 @@ class AuthRepositoryImpl(
|
|||||||
password = password,
|
password = password,
|
||||||
authModel = it,
|
authModel = it,
|
||||||
newDeviceOtp = newDeviceOtp,
|
newDeviceOtp = newDeviceOtp,
|
||||||
captchaToken = captchaToken ?: twoFactorResponse?.captchaToken,
|
|
||||||
deviceData = twoFactorDeviceData,
|
deviceData = twoFactorDeviceData,
|
||||||
orgIdentifier = orgIdentifier,
|
orgIdentifier = orgIdentifier,
|
||||||
)
|
)
|
||||||
@ -747,7 +661,6 @@ class AuthRepositoryImpl(
|
|||||||
ssoCode: String,
|
ssoCode: String,
|
||||||
ssoCodeVerifier: String,
|
ssoCodeVerifier: String,
|
||||||
ssoRedirectUri: String,
|
ssoRedirectUri: String,
|
||||||
captchaToken: String?,
|
|
||||||
organizationIdentifier: String,
|
organizationIdentifier: String,
|
||||||
): LoginResult = loginCommon(
|
): LoginResult = loginCommon(
|
||||||
email = email,
|
email = email,
|
||||||
@ -756,15 +669,62 @@ class AuthRepositoryImpl(
|
|||||||
ssoCodeVerifier = ssoCodeVerifier,
|
ssoCodeVerifier = ssoCodeVerifier,
|
||||||
ssoRedirectUri = ssoRedirectUri,
|
ssoRedirectUri = ssoRedirectUri,
|
||||||
),
|
),
|
||||||
captchaToken = captchaToken,
|
|
||||||
orgIdentifier = organizationIdentifier,
|
orgIdentifier = organizationIdentifier,
|
||||||
)
|
)
|
||||||
|
|
||||||
override fun refreshAccessTokenSynchronously(userId: String): Result<RefreshTokenResponseJson> =
|
override fun refreshAccessTokenSynchronously(
|
||||||
refreshAccessTokenSynchronouslyInternal(
|
userId: String,
|
||||||
userId = userId,
|
): Result<String> {
|
||||||
logOutOnFailure = true,
|
val refreshToken = authDiskSource
|
||||||
)
|
.getAccountTokens(userId = userId)
|
||||||
|
?.refreshToken
|
||||||
|
?: return IllegalStateException("Must be logged in.").asFailure()
|
||||||
|
return identityService
|
||||||
|
.refreshTokenSynchronously(refreshToken)
|
||||||
|
.flatMap { refreshTokenResponse ->
|
||||||
|
// Check to make sure the user is still logged in after making the request
|
||||||
|
authDiskSource
|
||||||
|
.userState
|
||||||
|
?.accounts
|
||||||
|
?.get(userId)
|
||||||
|
?.let { refreshTokenResponse.asSuccess() }
|
||||||
|
?: IllegalStateException("Must be logged in.").asFailure()
|
||||||
|
}
|
||||||
|
.flatMap { refreshTokenResponse ->
|
||||||
|
when (refreshTokenResponse) {
|
||||||
|
is RefreshTokenResponseJson.Error -> {
|
||||||
|
if (refreshTokenResponse.isInvalidGrant) {
|
||||||
|
logout(userId = userId, reason = LogoutReason.InvalidGrant)
|
||||||
|
}
|
||||||
|
IllegalStateException(refreshTokenResponse.error).asFailure()
|
||||||
|
}
|
||||||
|
|
||||||
|
is RefreshTokenResponseJson.Forbidden -> {
|
||||||
|
logout(userId = userId, reason = LogoutReason.RefreshForbidden)
|
||||||
|
refreshTokenResponse.error.asFailure()
|
||||||
|
}
|
||||||
|
|
||||||
|
is RefreshTokenResponseJson.Unauthorized -> {
|
||||||
|
logout(userId = userId, reason = LogoutReason.RefreshUnauthorized)
|
||||||
|
refreshTokenResponse.error.asFailure()
|
||||||
|
}
|
||||||
|
|
||||||
|
is RefreshTokenResponseJson.Success -> {
|
||||||
|
// Store the new token information
|
||||||
|
authDiskSource.storeAccountTokens(
|
||||||
|
userId = userId,
|
||||||
|
accountTokens = AccountTokensJson(
|
||||||
|
accessToken = refreshTokenResponse.accessToken,
|
||||||
|
refreshToken = refreshTokenResponse.refreshToken,
|
||||||
|
expiresAtSec = clock.instant().epochSecond +
|
||||||
|
refreshTokenResponse.expiresIn,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
refreshTokenResponse.accessToken.asSuccess()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
override fun logout(reason: LogoutReason) {
|
override fun logout(reason: LogoutReason) {
|
||||||
activeUserId?.let { userId -> logout(userId = userId, reason = reason) }
|
activeUserId?.let { userId -> logout(userId = userId, reason = reason) }
|
||||||
@ -796,7 +756,17 @@ class AuthRepositoryImpl(
|
|||||||
?.let { jsonRequest ->
|
?.let { jsonRequest ->
|
||||||
accountsService.resendVerificationCodeEmail(body = jsonRequest).fold(
|
accountsService.resendVerificationCodeEmail(body = jsonRequest).fold(
|
||||||
onFailure = { ResendEmailResult.Error(message = it.message, error = it) },
|
onFailure = { ResendEmailResult.Error(message = it.message, error = it) },
|
||||||
onSuccess = { ResendEmailResult.Success },
|
onSuccess = {
|
||||||
|
when (it) {
|
||||||
|
VerificationCodeResponseJson.Success -> ResendEmailResult.Success
|
||||||
|
is VerificationCodeResponseJson.Invalid -> {
|
||||||
|
ResendEmailResult.Error(
|
||||||
|
message = it.firstValidationErrorMessage,
|
||||||
|
error = null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
?: ResendEmailResult.Error(
|
?: ResendEmailResult.Error(
|
||||||
@ -808,8 +778,18 @@ class AuthRepositoryImpl(
|
|||||||
resendNewDeviceOtpRequestJson
|
resendNewDeviceOtpRequestJson
|
||||||
?.let { jsonRequest ->
|
?.let { jsonRequest ->
|
||||||
accountsService.resendNewDeviceOtp(body = jsonRequest).fold(
|
accountsService.resendNewDeviceOtp(body = jsonRequest).fold(
|
||||||
onFailure = { ResendEmailResult.Error(message = it.message, error = it) },
|
onFailure = { ResendEmailResult.Error(message = null, error = it) },
|
||||||
onSuccess = { ResendEmailResult.Success },
|
onSuccess = {
|
||||||
|
when (it) {
|
||||||
|
VerificationOtpResponseJson.Success -> ResendEmailResult.Success
|
||||||
|
is VerificationOtpResponseJson.Invalid -> {
|
||||||
|
ResendEmailResult.Error(
|
||||||
|
message = it.firstValidationErrorMessage,
|
||||||
|
error = null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
?: ResendEmailResult.Error(
|
?: ResendEmailResult.Error(
|
||||||
@ -832,7 +812,7 @@ class AuthRepositoryImpl(
|
|||||||
// We need to make sure that the environment is set back to the correct spot.
|
// We need to make sure that the environment is set back to the correct spot.
|
||||||
updateEnvironment()
|
updateEnvironment()
|
||||||
// No switching to do but clear any pending account additions
|
// No switching to do but clear any pending account additions
|
||||||
hasPendingAccountAddition = false
|
userStateManager.hasPendingAccountAddition = false
|
||||||
return SwitchAccountResult.NoChange
|
return SwitchAccountResult.NoChange
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -847,7 +827,7 @@ class AuthRepositoryImpl(
|
|||||||
authDiskSource.userState = currentUserState.copy(activeUserId = userId)
|
authDiskSource.userState = currentUserState.copy(activeUserId = userId)
|
||||||
|
|
||||||
// Clear any pending account additions
|
// Clear any pending account additions
|
||||||
hasPendingAccountAddition = false
|
userStateManager.hasPendingAccountAddition = false
|
||||||
|
|
||||||
return SwitchAccountResult.AccountSwitched
|
return SwitchAccountResult.AccountSwitched
|
||||||
}
|
}
|
||||||
@ -858,7 +838,6 @@ class AuthRepositoryImpl(
|
|||||||
masterPassword: String,
|
masterPassword: String,
|
||||||
masterPasswordHint: String?,
|
masterPasswordHint: String?,
|
||||||
emailVerificationToken: String?,
|
emailVerificationToken: String?,
|
||||||
captchaToken: String?,
|
|
||||||
shouldCheckDataBreaches: Boolean,
|
shouldCheckDataBreaches: Boolean,
|
||||||
isMasterPasswordStrong: Boolean,
|
isMasterPasswordStrong: Boolean,
|
||||||
): RegisterResult {
|
): RegisterResult {
|
||||||
@ -893,7 +872,6 @@ class AuthRepositoryImpl(
|
|||||||
email = email,
|
email = email,
|
||||||
masterPasswordHash = registerKeyResponse.masterPasswordHash,
|
masterPasswordHash = registerKeyResponse.masterPasswordHash,
|
||||||
masterPasswordHint = masterPasswordHint,
|
masterPasswordHint = masterPasswordHint,
|
||||||
captchaResponse = captchaToken,
|
|
||||||
key = registerKeyResponse.encryptedUserKey,
|
key = registerKeyResponse.encryptedUserKey,
|
||||||
keys = RegisterRequestJson.Keys(
|
keys = RegisterRequestJson.Keys(
|
||||||
publicKey = registerKeyResponse.keys.public,
|
publicKey = registerKeyResponse.keys.public,
|
||||||
@ -910,7 +888,6 @@ class AuthRepositoryImpl(
|
|||||||
masterPasswordHash = registerKeyResponse.masterPasswordHash,
|
masterPasswordHash = registerKeyResponse.masterPasswordHash,
|
||||||
masterPasswordHint = masterPasswordHint,
|
masterPasswordHint = masterPasswordHint,
|
||||||
emailVerificationToken = emailVerificationToken,
|
emailVerificationToken = emailVerificationToken,
|
||||||
captchaResponse = captchaToken,
|
|
||||||
userSymmetricKey = registerKeyResponse.encryptedUserKey,
|
userSymmetricKey = registerKeyResponse.encryptedUserKey,
|
||||||
userAsymmetricKeys = RegisterFinishRequestJson.Keys(
|
userAsymmetricKeys = RegisterFinishRequestJson.Keys(
|
||||||
publicKey = registerKeyResponse.keys.public,
|
publicKey = registerKeyResponse.keys.public,
|
||||||
@ -925,18 +902,9 @@ class AuthRepositoryImpl(
|
|||||||
.fold(
|
.fold(
|
||||||
onSuccess = {
|
onSuccess = {
|
||||||
when (it) {
|
when (it) {
|
||||||
is RegisterResponseJson.CaptchaRequired -> {
|
|
||||||
it.validationErrors.captchaKeys.firstOrNull()
|
|
||||||
?.let { key -> RegisterResult.CaptchaRequired(captchaId = key) }
|
|
||||||
?: RegisterResult.Error(
|
|
||||||
errorMessage = null,
|
|
||||||
error = MissingPropertyException("Captcha ID"),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
is RegisterResponseJson.Success -> {
|
is RegisterResponseJson.Success -> {
|
||||||
settingsRepository.hasUserLoggedInOrCreatedAccount = true
|
settingsRepository.hasUserLoggedInOrCreatedAccount = true
|
||||||
RegisterResult.Success(captchaToken = it.captchaBypassToken)
|
RegisterResult.Success
|
||||||
}
|
}
|
||||||
|
|
||||||
is RegisterResponseJson.Invalid -> {
|
is RegisterResponseJson.Invalid -> {
|
||||||
@ -1058,12 +1026,6 @@ class AuthRepositoryImpl(
|
|||||||
}
|
}
|
||||||
.fold(
|
.fold(
|
||||||
onSuccess = {
|
onSuccess = {
|
||||||
// Clear the password reset reason, since it's no longer relevant.
|
|
||||||
storeUserResetPasswordReason(
|
|
||||||
userId = activeAccount.profile.userId,
|
|
||||||
reason = null,
|
|
||||||
)
|
|
||||||
|
|
||||||
// Update the saved master password hash.
|
// Update the saved master password hash.
|
||||||
authSdkSource
|
authSdkSource
|
||||||
.hashPassword(
|
.hashPassword(
|
||||||
@ -1079,6 +1041,10 @@ class AuthRepositoryImpl(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Log out the user after successful password reset.
|
||||||
|
// This clears all user state including forcePasswordResetReason.
|
||||||
|
logout(reason = LogoutReason.PasswordReset)
|
||||||
|
|
||||||
// Return the success.
|
// Return the success.
|
||||||
ResetPasswordResult.Success
|
ResetPasswordResult.Success
|
||||||
},
|
},
|
||||||
@ -1150,6 +1116,9 @@ class AuthRepositoryImpl(
|
|||||||
)
|
)
|
||||||
.onSuccess {
|
.onSuccess {
|
||||||
rsaKeys?.private?.let {
|
rsaKeys?.private?.let {
|
||||||
|
// This process is used by TDE and Enterprise accounts during initial
|
||||||
|
// login. We continue to store the locally generated keys
|
||||||
|
// until TDE and Enterprise accounts support AEAD keys.
|
||||||
authDiskSource.storePrivateKey(userId = userId, privateKey = it)
|
authDiskSource.storePrivateKey(userId = userId, privateKey = it)
|
||||||
}
|
}
|
||||||
authDiskSource.storeUserKey(userId = userId, userKey = encryptedUserKey)
|
authDiskSource.storeUserKey(userId = userId, userKey = encryptedUserKey)
|
||||||
@ -1182,10 +1151,6 @@ class AuthRepositoryImpl(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
override fun setCaptchaCallbackTokenResult(tokenResult: CaptchaCallbackTokenResult) {
|
|
||||||
captchaTokenChannel.trySend(tokenResult)
|
|
||||||
}
|
|
||||||
|
|
||||||
override fun setDuoCallbackTokenResult(tokenResult: DuoCallbackTokenResult) {
|
override fun setDuoCallbackTokenResult(tokenResult: DuoCallbackTokenResult) {
|
||||||
duoTokenChannel.trySend(tokenResult)
|
duoTokenChannel.trySend(tokenResult)
|
||||||
}
|
}
|
||||||
@ -1331,8 +1296,8 @@ class AuthRepositoryImpl(
|
|||||||
?.activeAccount
|
?.activeAccount
|
||||||
?.profile
|
?.profile
|
||||||
?: return ValidatePinResult.Error(error = NoActiveUserException())
|
?: return ValidatePinResult.Error(error = NoActiveUserException())
|
||||||
val pinProtectedUserKey = authDiskSource
|
val pinProtectedUserKeyEnvelope = authDiskSource
|
||||||
.getPinProtectedUserKey(userId = activeAccount.userId)
|
.getPinProtectedUserKeyEnvelope(userId = activeAccount.userId)
|
||||||
?: return ValidatePinResult.Error(
|
?: return ValidatePinResult.Error(
|
||||||
error = MissingPropertyException("Pin Protected User Key"),
|
error = MissingPropertyException("Pin Protected User Key"),
|
||||||
)
|
)
|
||||||
@ -1340,7 +1305,7 @@ class AuthRepositoryImpl(
|
|||||||
.validatePin(
|
.validatePin(
|
||||||
userId = activeAccount.userId,
|
userId = activeAccount.userId,
|
||||||
pin = pin,
|
pin = pin,
|
||||||
pinProtectedUserKey = pinProtectedUserKey,
|
pinProtectedUserKey = pinProtectedUserKeyEnvelope,
|
||||||
)
|
)
|
||||||
.fold(
|
.fold(
|
||||||
onSuccess = { ValidatePinResult.Success(isValid = it) },
|
onSuccess = { ValidatePinResult.Success(isValid = it) },
|
||||||
@ -1394,10 +1359,10 @@ class AuthRepositoryImpl(
|
|||||||
)
|
)
|
||||||
.fold(
|
.fold(
|
||||||
onSuccess = {
|
onSuccess = {
|
||||||
when (val json = it) {
|
when (it) {
|
||||||
VerifyEmailTokenResponseJson.Valid -> EmailTokenResult.Success
|
VerifyEmailTokenResponseJson.Valid -> EmailTokenResult.Success
|
||||||
is VerifyEmailTokenResponseJson.Invalid -> {
|
is VerifyEmailTokenResponseJson.Invalid -> {
|
||||||
EmailTokenResult.Error(message = json.message, error = null)
|
EmailTokenResult.Error(message = it.message, error = null)
|
||||||
}
|
}
|
||||||
|
|
||||||
VerifyEmailTokenResponseJson.TokenExpired -> EmailTokenResult.Expired
|
VerifyEmailTokenResponseJson.TokenExpired -> EmailTokenResult.Expired
|
||||||
@ -1422,42 +1387,6 @@ class AuthRepositoryImpl(
|
|||||||
onFailure = { LeaveOrganizationResult.Error(error = it) },
|
onFailure = { LeaveOrganizationResult.Error(error = it) },
|
||||||
)
|
)
|
||||||
|
|
||||||
private fun refreshAccessTokenSynchronouslyInternal(
|
|
||||||
userId: String,
|
|
||||||
logOutOnFailure: Boolean,
|
|
||||||
): Result<RefreshTokenResponseJson> {
|
|
||||||
val refreshToken = authDiskSource
|
|
||||||
.getAccountTokens(userId = userId)
|
|
||||||
?.refreshToken
|
|
||||||
?: return IllegalStateException("Must be logged in.").asFailure()
|
|
||||||
return identityService
|
|
||||||
.refreshTokenSynchronously(refreshToken)
|
|
||||||
.flatMap { refreshTokenResponse ->
|
|
||||||
// Check to make sure the user is still logged in after making the request
|
|
||||||
authDiskSource
|
|
||||||
.userState
|
|
||||||
?.accounts
|
|
||||||
?.get(userId)
|
|
||||||
?.let { refreshTokenResponse.asSuccess() }
|
|
||||||
?: IllegalStateException("Must be logged in.").asFailure()
|
|
||||||
}
|
|
||||||
.onFailure {
|
|
||||||
if (logOutOnFailure) {
|
|
||||||
logout(userId = userId, reason = LogoutReason.TokenRefreshFail)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.onSuccess { refreshTokenResponse ->
|
|
||||||
// Update the existing UserState with updated token information
|
|
||||||
authDiskSource.storeAccountTokens(
|
|
||||||
userId = userId,
|
|
||||||
accountTokens = AccountTokensJson(
|
|
||||||
accessToken = refreshTokenResponse.accessToken,
|
|
||||||
refreshToken = refreshTokenResponse.refreshToken,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@Suppress("CyclomaticComplexMethod")
|
@Suppress("CyclomaticComplexMethod")
|
||||||
private suspend fun validatePasswordAgainstPolicy(
|
private suspend fun validatePasswordAgainstPolicy(
|
||||||
password: String,
|
password: String,
|
||||||
@ -1559,27 +1488,6 @@ class AuthRepositoryImpl(
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isBiometricsEnabled(
|
|
||||||
userId: String,
|
|
||||||
): Boolean = authDiskSource.getUserBiometricUnlockKey(userId = userId) != null
|
|
||||||
|
|
||||||
private fun isDeviceTrusted(
|
|
||||||
userId: String,
|
|
||||||
): Boolean = authDiskSource.getDeviceKey(userId = userId) != null
|
|
||||||
|
|
||||||
private fun getVaultUnlockType(
|
|
||||||
userId: String,
|
|
||||||
): VaultUnlockType =
|
|
||||||
when {
|
|
||||||
authDiskSource.getPinProtectedUserKey(userId = userId) != null -> {
|
|
||||||
VaultUnlockType.PIN
|
|
||||||
}
|
|
||||||
|
|
||||||
else -> {
|
|
||||||
VaultUnlockType.MASTER_PASSWORD
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Update the saved state with the force password reset reason.
|
* Update the saved state with the force password reset reason.
|
||||||
*/
|
*/
|
||||||
@ -1613,7 +1521,6 @@ class AuthRepositoryImpl(
|
|||||||
twoFactorData: TwoFactorDataModel? = null,
|
twoFactorData: TwoFactorDataModel? = null,
|
||||||
deviceData: DeviceDataModel? = null,
|
deviceData: DeviceDataModel? = null,
|
||||||
orgIdentifier: String? = null,
|
orgIdentifier: String? = null,
|
||||||
captchaToken: String?,
|
|
||||||
newDeviceOtp: String? = null,
|
newDeviceOtp: String? = null,
|
||||||
): LoginResult = identityService
|
): LoginResult = identityService
|
||||||
.getToken(
|
.getToken(
|
||||||
@ -1621,7 +1528,6 @@ class AuthRepositoryImpl(
|
|||||||
email = email,
|
email = email,
|
||||||
authModel = authModel,
|
authModel = authModel,
|
||||||
twoFactorData = twoFactorData ?: getRememberedTwoFactorData(email),
|
twoFactorData = twoFactorData ?: getRememberedTwoFactorData(email),
|
||||||
captchaToken = captchaToken,
|
|
||||||
newDeviceOtp = newDeviceOtp,
|
newDeviceOtp = newDeviceOtp,
|
||||||
)
|
)
|
||||||
.fold(
|
.fold(
|
||||||
@ -1640,10 +1546,6 @@ class AuthRepositoryImpl(
|
|||||||
},
|
},
|
||||||
onSuccess = { loginResponse ->
|
onSuccess = { loginResponse ->
|
||||||
when (loginResponse) {
|
when (loginResponse) {
|
||||||
is GetTokenResponseJson.CaptchaRequired -> LoginResult.CaptchaRequired(
|
|
||||||
captchaId = loginResponse.captchaKey,
|
|
||||||
)
|
|
||||||
|
|
||||||
is GetTokenResponseJson.TwoFactorRequired -> handleLoginCommonTwoFactorRequired(
|
is GetTokenResponseJson.TwoFactorRequired -> handleLoginCommonTwoFactorRequired(
|
||||||
loginResponse = loginResponse,
|
loginResponse = loginResponse,
|
||||||
email = email,
|
email = email,
|
||||||
@ -1696,7 +1598,7 @@ class AuthRepositoryImpl(
|
|||||||
deviceData: DeviceDataModel?,
|
deviceData: DeviceDataModel?,
|
||||||
orgIdentifier: String?,
|
orgIdentifier: String?,
|
||||||
userConfirmedKeyConnector: Boolean,
|
userConfirmedKeyConnector: Boolean,
|
||||||
): LoginResult = userStateTransaction {
|
): LoginResult = userStateManager.userStateTransaction {
|
||||||
val userStateJson = loginResponse.toUserState(
|
val userStateJson = loginResponse.toUserState(
|
||||||
previousUserState = authDiskSource.userState,
|
previousUserState = authDiskSource.userState,
|
||||||
environmentUrlData = environmentRepository.environment.environmentUrlData,
|
environmentUrlData = environmentRepository.environment.environmentUrlData,
|
||||||
@ -1735,7 +1637,7 @@ class AuthRepositoryImpl(
|
|||||||
// we should ask him to confirm the domain
|
// we should ask him to confirm the domain
|
||||||
if (isNewKeyConnectorUser && isNotConfirmed) {
|
if (isNewKeyConnectorUser && isNotConfirmed) {
|
||||||
keyConnectorResponse = loginResponse
|
keyConnectorResponse = loginResponse
|
||||||
return LoginResult.ConfirmKeyConnectorDomain(
|
return@userStateTransaction LoginResult.ConfirmKeyConnectorDomain(
|
||||||
domain = keyConnectorUrl,
|
domain = keyConnectorUrl,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@ -1780,21 +1682,39 @@ class AuthRepositoryImpl(
|
|||||||
accountTokens = AccountTokensJson(
|
accountTokens = AccountTokensJson(
|
||||||
accessToken = loginResponse.accessToken,
|
accessToken = loginResponse.accessToken,
|
||||||
refreshToken = loginResponse.refreshToken,
|
refreshToken = loginResponse.refreshToken,
|
||||||
|
expiresAtSec = clock.instant().epochSecond + loginResponse.expiresInSeconds,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
settingsRepository.hasUserLoggedInOrCreatedAccount = true
|
settingsRepository.hasUserLoggedInOrCreatedAccount = true
|
||||||
|
|
||||||
authDiskSource.userState = userStateJson
|
authDiskSource.userState = userStateJson
|
||||||
|
password?.let {
|
||||||
|
// Automatically update kdf to minimums after password unlock and userState update
|
||||||
|
kdfManager
|
||||||
|
.updateKdfToMinimumsIfNeeded(password = password)
|
||||||
|
.also { result ->
|
||||||
|
if (result is UpdateKdfMinimumsResult.Error) {
|
||||||
|
Timber.e(result.error, message = "Failed to silent update KDF settings.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
loginResponse.key?.let {
|
loginResponse.key?.let {
|
||||||
// Only set the value if it's present, since we may have set it already
|
// Only set the value if it's present, since we may have set it already
|
||||||
// when we completed the pending admin auth request.
|
// when we completed the pending admin auth request.
|
||||||
authDiskSource.storeUserKey(userId = userId, userKey = it)
|
authDiskSource.storeUserKey(userId = userId, userKey = it)
|
||||||
}
|
}
|
||||||
|
// We continue to store the private key for backwards compatibility. Key connector
|
||||||
|
// conversion still relies on the private key.
|
||||||
loginResponse.privateKey?.let {
|
loginResponse.privateKey?.let {
|
||||||
// Only set the value if it's present, since we may have set it already
|
// Only set the value if it's present, since we may have set it already
|
||||||
// when we completed the key connector conversion.
|
// when we completed the key connector conversion.
|
||||||
authDiskSource.storePrivateKey(userId = userId, privateKey = it)
|
authDiskSource.storePrivateKey(userId = userId, privateKey = it)
|
||||||
}
|
}
|
||||||
|
loginResponse.accountKeys?.let {
|
||||||
|
// Only set the value if it's present, since we may have set it already
|
||||||
|
// when we completed the key connector conversion.
|
||||||
|
authDiskSource.storeAccountKeys(userId = userId, accountKeys = it)
|
||||||
|
}
|
||||||
// If the user just authenticated with a two-factor code and selected the option to
|
// If the user just authenticated with a two-factor code and selected the option to
|
||||||
// remember it, then the API response will return a token that will be used in place
|
// remember it, then the API response will return a token that will be used in place
|
||||||
// of the two-factor code on the next login attempt.
|
// of the two-factor code on the next login attempt.
|
||||||
@ -1895,6 +1815,8 @@ class AuthRepositoryImpl(
|
|||||||
masterKey = it.masterKey,
|
masterKey = it.masterKey,
|
||||||
userKey = key,
|
userKey = key,
|
||||||
),
|
),
|
||||||
|
securityState = loginResponse.accountKeys?.securityState?.securityState,
|
||||||
|
signingKey = loginResponse.accountKeys?.signatureKeyPair?.wrappedSigningKey,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
.fold(
|
.fold(
|
||||||
@ -1918,6 +1840,8 @@ class AuthRepositoryImpl(
|
|||||||
val result = unlockVault(
|
val result = unlockVault(
|
||||||
accountProfile = profile,
|
accountProfile = profile,
|
||||||
privateKey = keyConnectorResponse.keys.private,
|
privateKey = keyConnectorResponse.keys.private,
|
||||||
|
securityState = loginResponse.accountKeys?.securityState?.securityState,
|
||||||
|
signingKey = loginResponse.accountKeys?.signatureKeyPair?.wrappedSigningKey,
|
||||||
initUserCryptoMethod = InitUserCryptoMethod.KeyConnector(
|
initUserCryptoMethod = InitUserCryptoMethod.KeyConnector(
|
||||||
masterKey = keyConnectorResponse.masterKey,
|
masterKey = keyConnectorResponse.masterKey,
|
||||||
userKey = keyConnectorResponse.encryptedUserKey,
|
userKey = keyConnectorResponse.encryptedUserKey,
|
||||||
@ -1930,10 +1854,16 @@ class AuthRepositoryImpl(
|
|||||||
userId = profile.userId,
|
userId = profile.userId,
|
||||||
userKey = keyConnectorResponse.encryptedUserKey,
|
userKey = keyConnectorResponse.encryptedUserKey,
|
||||||
)
|
)
|
||||||
|
// We continue to store the private key for backwards compatibility since
|
||||||
|
// key connector conversion still relies on the private key.
|
||||||
authDiskSource.storePrivateKey(
|
authDiskSource.storePrivateKey(
|
||||||
userId = profile.userId,
|
userId = profile.userId,
|
||||||
privateKey = keyConnectorResponse.keys.private,
|
privateKey = keyConnectorResponse.keys.private,
|
||||||
)
|
)
|
||||||
|
authDiskSource.storeAccountKeys(
|
||||||
|
userId = profile.userId,
|
||||||
|
accountKeys = loginResponse.accountKeys,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
result
|
result
|
||||||
}
|
}
|
||||||
@ -1955,15 +1885,23 @@ class AuthRepositoryImpl(
|
|||||||
): VaultUnlockResult? {
|
): VaultUnlockResult? {
|
||||||
// Attempt to unlock the vault with password if possible.
|
// Attempt to unlock the vault with password if possible.
|
||||||
val masterPassword = password ?: return null
|
val masterPassword = password ?: return null
|
||||||
val privateKey = loginResponse.privateKey ?: return null
|
val privateKey = loginResponse.privateKeyOrNull() ?: return null
|
||||||
val key = loginResponse.key ?: return null
|
|
||||||
|
val masterPasswordUnlock = loginResponse
|
||||||
|
.userDecryptionOptions
|
||||||
|
?.masterPasswordUnlock
|
||||||
|
?: return null
|
||||||
|
val initUserCryptoMethod = InitUserCryptoMethod.MasterPasswordUnlock(
|
||||||
|
password = masterPassword,
|
||||||
|
masterPasswordUnlock = masterPasswordUnlock.toSdkMasterPasswordUnlock(),
|
||||||
|
)
|
||||||
|
|
||||||
return unlockVault(
|
return unlockVault(
|
||||||
accountProfile = profile,
|
accountProfile = profile,
|
||||||
privateKey = privateKey,
|
privateKey = privateKey,
|
||||||
initUserCryptoMethod = InitUserCryptoMethod.Password(
|
securityState = loginResponse.accountKeys?.securityState?.securityState,
|
||||||
password = masterPassword,
|
signingKey = loginResponse.accountKeys?.signatureKeyPair?.wrappedSigningKey,
|
||||||
userKey = key,
|
initUserCryptoMethod = initUserCryptoMethod,
|
||||||
),
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -1977,13 +1915,15 @@ class AuthRepositoryImpl(
|
|||||||
): VaultUnlockResult? {
|
): VaultUnlockResult? {
|
||||||
// Attempt to unlock the vault with auth request if possible.
|
// Attempt to unlock the vault with auth request if possible.
|
||||||
// These values will only be null during the Just-in-Time provisioning flow.
|
// These values will only be null during the Just-in-Time provisioning flow.
|
||||||
val privateKey = loginResponse.privateKey
|
val privateKey = loginResponse.privateKeyOrNull()
|
||||||
val key = loginResponse.key
|
val key = loginResponse.key
|
||||||
if (privateKey != null && key != null) {
|
if (privateKey != null && key != null) {
|
||||||
deviceData?.let { model ->
|
deviceData?.let { model ->
|
||||||
return unlockVault(
|
return unlockVault(
|
||||||
accountProfile = profile,
|
accountProfile = profile,
|
||||||
privateKey = privateKey,
|
privateKey = privateKey,
|
||||||
|
securityState = loginResponse.accountKeys?.securityState?.securityState,
|
||||||
|
signingKey = loginResponse.accountKeys?.signatureKeyPair?.wrappedSigningKey,
|
||||||
initUserCryptoMethod = InitUserCryptoMethod.AuthRequest(
|
initUserCryptoMethod = InitUserCryptoMethod.AuthRequest(
|
||||||
requestPrivateKey = model.privateKey,
|
requestPrivateKey = model.privateKey,
|
||||||
method = model
|
method = model
|
||||||
@ -2008,13 +1948,26 @@ class AuthRepositoryImpl(
|
|||||||
.userDecryptionOptions
|
.userDecryptionOptions
|
||||||
?.trustedDeviceUserDecryptionOptions
|
?.trustedDeviceUserDecryptionOptions
|
||||||
?.let { options ->
|
?.let { options ->
|
||||||
loginResponse.privateKey?.let { privateKey ->
|
loginResponse.accountKeys
|
||||||
unlockVaultWithTrustedDeviceUserDecryptionOptionsAndStoreKeys(
|
?.let { accountKeys ->
|
||||||
options = options,
|
unlockVaultWithTrustedDeviceUserDecryptionOptionsAndStoreKeys(
|
||||||
profile = profile,
|
options = options,
|
||||||
privateKey = privateKey,
|
profile = profile,
|
||||||
)
|
privateKey = accountKeys.publicKeyEncryptionKeyPair.wrappedPrivateKey,
|
||||||
}
|
securityState = accountKeys.securityState?.securityState,
|
||||||
|
signingKey = accountKeys.signatureKeyPair?.wrappedSigningKey,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
?: loginResponse.privateKey
|
||||||
|
?.let { privateKey ->
|
||||||
|
unlockVaultWithTrustedDeviceUserDecryptionOptionsAndStoreKeys(
|
||||||
|
options = options,
|
||||||
|
profile = profile,
|
||||||
|
privateKey = privateKey,
|
||||||
|
securityState = null,
|
||||||
|
signingKey = null,
|
||||||
|
)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -2026,6 +1979,8 @@ class AuthRepositoryImpl(
|
|||||||
options: TrustedDeviceUserDecryptionOptionsJson,
|
options: TrustedDeviceUserDecryptionOptionsJson,
|
||||||
profile: AccountJson.Profile,
|
profile: AccountJson.Profile,
|
||||||
privateKey: String,
|
privateKey: String,
|
||||||
|
securityState: String?,
|
||||||
|
signingKey: String?,
|
||||||
): VaultUnlockResult? {
|
): VaultUnlockResult? {
|
||||||
var vaultUnlockResult: VaultUnlockResult? = null
|
var vaultUnlockResult: VaultUnlockResult? = null
|
||||||
val userId = profile.userId
|
val userId = profile.userId
|
||||||
@ -2044,6 +1999,8 @@ class AuthRepositoryImpl(
|
|||||||
vaultUnlockResult = unlockVault(
|
vaultUnlockResult = unlockVault(
|
||||||
accountProfile = profile,
|
accountProfile = profile,
|
||||||
privateKey = privateKey,
|
privateKey = privateKey,
|
||||||
|
signingKey = signingKey,
|
||||||
|
securityState = securityState,
|
||||||
initUserCryptoMethod = InitUserCryptoMethod.AuthRequest(
|
initUserCryptoMethod = InitUserCryptoMethod.AuthRequest(
|
||||||
requestPrivateKey = pendingRequest.requestPrivateKey,
|
requestPrivateKey = pendingRequest.requestPrivateKey,
|
||||||
method = AuthRequestMethod.UserKey(protectedUserKey = userKey),
|
method = AuthRequestMethod.UserKey(protectedUserKey = userKey),
|
||||||
@ -2071,6 +2028,8 @@ class AuthRepositoryImpl(
|
|||||||
vaultUnlockResult = unlockVault(
|
vaultUnlockResult = unlockVault(
|
||||||
accountProfile = profile,
|
accountProfile = profile,
|
||||||
privateKey = privateKey,
|
privateKey = privateKey,
|
||||||
|
securityState = securityState,
|
||||||
|
signingKey = signingKey,
|
||||||
initUserCryptoMethod = InitUserCryptoMethod.DeviceKey(
|
initUserCryptoMethod = InitUserCryptoMethod.DeviceKey(
|
||||||
deviceKey = deviceKey,
|
deviceKey = deviceKey,
|
||||||
protectedDevicePrivateKey = encryptedPrivateKey,
|
protectedDevicePrivateKey = encryptedPrivateKey,
|
||||||
@ -2090,6 +2049,8 @@ class AuthRepositoryImpl(
|
|||||||
private suspend fun unlockVault(
|
private suspend fun unlockVault(
|
||||||
accountProfile: AccountJson.Profile,
|
accountProfile: AccountJson.Profile,
|
||||||
privateKey: String,
|
privateKey: String,
|
||||||
|
securityState: String?,
|
||||||
|
signingKey: String?,
|
||||||
initUserCryptoMethod: InitUserCryptoMethod,
|
initUserCryptoMethod: InitUserCryptoMethod,
|
||||||
): VaultUnlockResult {
|
): VaultUnlockResult {
|
||||||
val userId = accountProfile.userId
|
val userId = accountProfile.userId
|
||||||
@ -2098,6 +2059,8 @@ class AuthRepositoryImpl(
|
|||||||
email = accountProfile.email,
|
email = accountProfile.email,
|
||||||
kdf = accountProfile.toSdkParams(),
|
kdf = accountProfile.toSdkParams(),
|
||||||
privateKey = privateKey,
|
privateKey = privateKey,
|
||||||
|
signingKey = signingKey,
|
||||||
|
securityState = securityState,
|
||||||
initUserCryptoMethod = initUserCryptoMethod,
|
initUserCryptoMethod = initUserCryptoMethod,
|
||||||
// The value for the organization keys here will typically be null. We can separately
|
// The value for the organization keys here will typically be null. We can separately
|
||||||
// unlock the vault for organization data after receiving the sync response if this
|
// unlock the vault for organization data after receiving the sync response if this
|
||||||
@ -2124,20 +2087,12 @@ class AuthRepositoryImpl(
|
|||||||
}
|
}
|
||||||
|
|
||||||
//endregion LoginCommon
|
//endregion LoginCommon
|
||||||
|
|
||||||
/**
|
|
||||||
* Run the given [block] while preventing any updates to [UserState]. This is useful in cases
|
|
||||||
* where many individual changes might occur that would normally affect the [UserState] but we
|
|
||||||
* only want a single final emission. In the rare case that multiple threads are running
|
|
||||||
* transactions simultaneously, there will be no [UserState] updates until the last
|
|
||||||
* transaction completes.
|
|
||||||
*/
|
|
||||||
private inline fun <T> userStateTransaction(block: () -> T): T {
|
|
||||||
mutableUserStateTransactionCountStateFlow.update { it.inc() }
|
|
||||||
return try {
|
|
||||||
block()
|
|
||||||
} finally {
|
|
||||||
mutableUserStateTransactionCountStateFlow.update { it.dec() }
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convenience function to extract the private key from the
|
||||||
|
* [GetTokenResponseJson.Success] response.
|
||||||
|
*/
|
||||||
|
private fun GetTokenResponseJson.Success.privateKeyOrNull(): String? =
|
||||||
|
this.accountKeys?.publicKeyEncryptionKeyPair?.wrappedPrivateKey
|
||||||
|
?: this.privateKey
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
package com.x8bit.bitwarden.data.auth.repository.di
|
package com.x8bit.bitwarden.data.auth.repository.di
|
||||||
|
|
||||||
|
import com.bitwarden.core.data.manager.dispatcher.DispatcherManager
|
||||||
import com.bitwarden.data.datasource.disk.ConfigDiskSource
|
import com.bitwarden.data.datasource.disk.ConfigDiskSource
|
||||||
import com.bitwarden.data.manager.DispatcherManager
|
|
||||||
import com.bitwarden.network.service.AccountsService
|
import com.bitwarden.network.service.AccountsService
|
||||||
import com.bitwarden.network.service.DevicesService
|
import com.bitwarden.network.service.DevicesService
|
||||||
import com.bitwarden.network.service.HaveIBeenPwnedService
|
import com.bitwarden.network.service.HaveIBeenPwnedService
|
||||||
@ -10,11 +10,16 @@ import com.bitwarden.network.service.OrganizationService
|
|||||||
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
|
import com.x8bit.bitwarden.data.auth.datasource.disk.AuthDiskSource
|
||||||
import com.x8bit.bitwarden.data.auth.datasource.sdk.AuthSdkSource
|
import com.x8bit.bitwarden.data.auth.datasource.sdk.AuthSdkSource
|
||||||
import com.x8bit.bitwarden.data.auth.manager.AuthRequestManager
|
import com.x8bit.bitwarden.data.auth.manager.AuthRequestManager
|
||||||
|
import com.x8bit.bitwarden.data.auth.manager.KdfManager
|
||||||
import com.x8bit.bitwarden.data.auth.manager.KeyConnectorManager
|
import com.x8bit.bitwarden.data.auth.manager.KeyConnectorManager
|
||||||
import com.x8bit.bitwarden.data.auth.manager.TrustedDeviceManager
|
import com.x8bit.bitwarden.data.auth.manager.TrustedDeviceManager
|
||||||
import com.x8bit.bitwarden.data.auth.manager.UserLogoutManager
|
import com.x8bit.bitwarden.data.auth.manager.UserLogoutManager
|
||||||
|
import com.x8bit.bitwarden.data.auth.manager.UserStateManager
|
||||||
|
import com.x8bit.bitwarden.data.auth.manager.UserStateManagerImpl
|
||||||
import com.x8bit.bitwarden.data.auth.repository.AuthRepository
|
import com.x8bit.bitwarden.data.auth.repository.AuthRepository
|
||||||
import com.x8bit.bitwarden.data.auth.repository.AuthRepositoryImpl
|
import com.x8bit.bitwarden.data.auth.repository.AuthRepositoryImpl
|
||||||
|
import com.x8bit.bitwarden.data.platform.datasource.disk.SettingsDiskSource
|
||||||
|
import com.x8bit.bitwarden.data.platform.manager.BiometricsEncryptionManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.FirstTimeActionManager
|
import com.x8bit.bitwarden.data.platform.manager.FirstTimeActionManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.LogsManager
|
import com.x8bit.bitwarden.data.platform.manager.LogsManager
|
||||||
import com.x8bit.bitwarden.data.platform.manager.PolicyManager
|
import com.x8bit.bitwarden.data.platform.manager.PolicyManager
|
||||||
@ -22,11 +27,13 @@ import com.x8bit.bitwarden.data.platform.manager.PushManager
|
|||||||
import com.x8bit.bitwarden.data.platform.repository.EnvironmentRepository
|
import com.x8bit.bitwarden.data.platform.repository.EnvironmentRepository
|
||||||
import com.x8bit.bitwarden.data.platform.repository.SettingsRepository
|
import com.x8bit.bitwarden.data.platform.repository.SettingsRepository
|
||||||
import com.x8bit.bitwarden.data.vault.datasource.sdk.VaultSdkSource
|
import com.x8bit.bitwarden.data.vault.datasource.sdk.VaultSdkSource
|
||||||
|
import com.x8bit.bitwarden.data.vault.manager.VaultLockManager
|
||||||
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
|
import com.x8bit.bitwarden.data.vault.repository.VaultRepository
|
||||||
import dagger.Module
|
import dagger.Module
|
||||||
import dagger.Provides
|
import dagger.Provides
|
||||||
import dagger.hilt.InstallIn
|
import dagger.hilt.InstallIn
|
||||||
import dagger.hilt.components.SingletonComponent
|
import dagger.hilt.components.SingletonComponent
|
||||||
|
import java.time.Clock
|
||||||
import javax.inject.Singleton
|
import javax.inject.Singleton
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -39,6 +46,7 @@ object AuthRepositoryModule {
|
|||||||
@Provides
|
@Provides
|
||||||
@Singleton
|
@Singleton
|
||||||
fun providesAuthRepository(
|
fun providesAuthRepository(
|
||||||
|
clock: Clock,
|
||||||
accountsService: AccountsService,
|
accountsService: AccountsService,
|
||||||
devicesService: DevicesService,
|
devicesService: DevicesService,
|
||||||
identityService: IdentityService,
|
identityService: IdentityService,
|
||||||
@ -47,20 +55,24 @@ object AuthRepositoryModule {
|
|||||||
authSdkSource: AuthSdkSource,
|
authSdkSource: AuthSdkSource,
|
||||||
vaultSdkSource: VaultSdkSource,
|
vaultSdkSource: VaultSdkSource,
|
||||||
authDiskSource: AuthDiskSource,
|
authDiskSource: AuthDiskSource,
|
||||||
|
settingsDiskSource: SettingsDiskSource,
|
||||||
configDiskSource: ConfigDiskSource,
|
configDiskSource: ConfigDiskSource,
|
||||||
dispatcherManager: DispatcherManager,
|
dispatcherManager: DispatcherManager,
|
||||||
environmentRepository: EnvironmentRepository,
|
environmentRepository: EnvironmentRepository,
|
||||||
settingsRepository: SettingsRepository,
|
settingsRepository: SettingsRepository,
|
||||||
vaultRepository: VaultRepository,
|
vaultRepository: VaultRepository,
|
||||||
|
biometricsEncryptionManager: BiometricsEncryptionManager,
|
||||||
keyConnectorManager: KeyConnectorManager,
|
keyConnectorManager: KeyConnectorManager,
|
||||||
authRequestManager: AuthRequestManager,
|
authRequestManager: AuthRequestManager,
|
||||||
trustedDeviceManager: TrustedDeviceManager,
|
trustedDeviceManager: TrustedDeviceManager,
|
||||||
userLogoutManager: UserLogoutManager,
|
userLogoutManager: UserLogoutManager,
|
||||||
pushManager: PushManager,
|
pushManager: PushManager,
|
||||||
policyManager: PolicyManager,
|
policyManager: PolicyManager,
|
||||||
firstTimeActionManager: FirstTimeActionManager,
|
|
||||||
logsManager: LogsManager,
|
logsManager: LogsManager,
|
||||||
|
userStateManager: UserStateManager,
|
||||||
|
kdfManager: KdfManager,
|
||||||
): AuthRepository = AuthRepositoryImpl(
|
): AuthRepository = AuthRepositoryImpl(
|
||||||
|
clock = clock,
|
||||||
accountsService = accountsService,
|
accountsService = accountsService,
|
||||||
devicesService = devicesService,
|
devicesService = devicesService,
|
||||||
identityService = identityService,
|
identityService = identityService,
|
||||||
@ -68,19 +80,38 @@ object AuthRepositoryModule {
|
|||||||
authSdkSource = authSdkSource,
|
authSdkSource = authSdkSource,
|
||||||
vaultSdkSource = vaultSdkSource,
|
vaultSdkSource = vaultSdkSource,
|
||||||
authDiskSource = authDiskSource,
|
authDiskSource = authDiskSource,
|
||||||
|
settingsDiskSource = settingsDiskSource,
|
||||||
configDiskSource = configDiskSource,
|
configDiskSource = configDiskSource,
|
||||||
haveIBeenPwnedService = haveIBeenPwnedService,
|
haveIBeenPwnedService = haveIBeenPwnedService,
|
||||||
dispatcherManager = dispatcherManager,
|
dispatcherManager = dispatcherManager,
|
||||||
environmentRepository = environmentRepository,
|
environmentRepository = environmentRepository,
|
||||||
settingsRepository = settingsRepository,
|
settingsRepository = settingsRepository,
|
||||||
vaultRepository = vaultRepository,
|
vaultRepository = vaultRepository,
|
||||||
|
biometricsEncryptionManager = biometricsEncryptionManager,
|
||||||
keyConnectorManager = keyConnectorManager,
|
keyConnectorManager = keyConnectorManager,
|
||||||
authRequestManager = authRequestManager,
|
authRequestManager = authRequestManager,
|
||||||
trustedDeviceManager = trustedDeviceManager,
|
trustedDeviceManager = trustedDeviceManager,
|
||||||
userLogoutManager = userLogoutManager,
|
userLogoutManager = userLogoutManager,
|
||||||
pushManager = pushManager,
|
pushManager = pushManager,
|
||||||
policyManager = policyManager,
|
policyManager = policyManager,
|
||||||
firstTimeActionManager = firstTimeActionManager,
|
|
||||||
logsManager = logsManager,
|
logsManager = logsManager,
|
||||||
|
userStateManager = userStateManager,
|
||||||
|
kdfManager = kdfManager,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Provides
|
||||||
|
@Singleton
|
||||||
|
fun providesUserStateManager(
|
||||||
|
authDiskSource: AuthDiskSource,
|
||||||
|
firstTimeActionManager: FirstTimeActionManager,
|
||||||
|
vaultLockManager: VaultLockManager,
|
||||||
|
policyManager: PolicyManager,
|
||||||
|
dispatcherManager: DispatcherManager,
|
||||||
|
): UserStateManager = UserStateManagerImpl(
|
||||||
|
authDiskSource = authDiskSource,
|
||||||
|
firstTimeActionManager = firstTimeActionManager,
|
||||||
|
vaultLockManager = vaultLockManager,
|
||||||
|
policyManager = policyManager,
|
||||||
|
dispatcherManager = dispatcherManager,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@ -9,11 +9,6 @@ sealed class LoginResult {
|
|||||||
*/
|
*/
|
||||||
data object Success : LoginResult()
|
data object Success : LoginResult()
|
||||||
|
|
||||||
/**
|
|
||||||
* Captcha verification is required.
|
|
||||||
*/
|
|
||||||
data class CaptchaRequired(val captchaId: String) : LoginResult()
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Encryption key migration is required.
|
* Encryption key migration is required.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@ -29,6 +29,24 @@ sealed class LogoutReason {
|
|||||||
data object NoLongerSupported : Biometrics()
|
data object NoLongerSupported : Biometrics()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates that the logout is happening because the there was an "invalid_grant" response
|
||||||
|
* from the network.
|
||||||
|
*/
|
||||||
|
data object InvalidGrant : LogoutReason()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates that the logout is happening because the there was a "Forbidden" response from
|
||||||
|
* token refresh API.
|
||||||
|
*/
|
||||||
|
data object RefreshForbidden : LogoutReason()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates that the logout is happening because the there was a "Unauthorized" response from
|
||||||
|
* token refresh API.
|
||||||
|
*/
|
||||||
|
data object RefreshUnauthorized : LogoutReason()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Indicates that the logout is happening because of an invalid state.
|
* Indicates that the logout is happening because of an invalid state.
|
||||||
*/
|
*/
|
||||||
@ -48,6 +66,11 @@ sealed class LogoutReason {
|
|||||||
*/
|
*/
|
||||||
data object Notification : LogoutReason()
|
data object Notification : LogoutReason()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Indicates that the logout is happening because the user reset their master password.
|
||||||
|
*/
|
||||||
|
data object PasswordReset : LogoutReason()
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Indicates that the logout is happening because the sync security stamp was invalidated.
|
* Indicates that the logout is happening because the sync security stamp was invalidated.
|
||||||
*/
|
*/
|
||||||
@ -58,11 +81,6 @@ sealed class LogoutReason {
|
|||||||
*/
|
*/
|
||||||
data object Timeout : LogoutReason()
|
data object Timeout : LogoutReason()
|
||||||
|
|
||||||
/**
|
|
||||||
* Indicates that the logout is happening because the access token could not be refreshed.
|
|
||||||
*/
|
|
||||||
data object TokenRefreshFail : LogoutReason()
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Indicates that the logout is happening because the user tried to unlock the vault
|
* Indicates that the logout is happening because the user tried to unlock the vault
|
||||||
* unsuccessfully too many times.
|
* unsuccessfully too many times.
|
||||||
|
|||||||
@ -122,6 +122,42 @@ sealed class PolicyInformation {
|
|||||||
val minutes: Int?,
|
val minutes: Int?,
|
||||||
|
|
||||||
@SerialName("action")
|
@SerialName("action")
|
||||||
val action: String?,
|
val action: Action?,
|
||||||
) : PolicyInformation()
|
|
||||||
|
@SerialName("type")
|
||||||
|
val type: Type?,
|
||||||
|
) : PolicyInformation() {
|
||||||
|
/**
|
||||||
|
* The action to take when the vault timeout is reached.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
enum class Action {
|
||||||
|
@SerialName("lock")
|
||||||
|
LOCK,
|
||||||
|
|
||||||
|
@SerialName("logOut")
|
||||||
|
LOGOUT,
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The type of vault timeout.
|
||||||
|
*/
|
||||||
|
@Serializable
|
||||||
|
enum class Type {
|
||||||
|
@SerialName("never")
|
||||||
|
NEVER,
|
||||||
|
|
||||||
|
@SerialName("onAppRestart")
|
||||||
|
ON_APP_RESTART,
|
||||||
|
|
||||||
|
@SerialName("onSystemLock")
|
||||||
|
ON_SYSTEM_LOCK,
|
||||||
|
|
||||||
|
@SerialName("immediately")
|
||||||
|
IMMEDIATELY,
|
||||||
|
|
||||||
|
@SerialName("custom")
|
||||||
|
CUSTOM,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -7,16 +7,8 @@ sealed class RegisterResult {
|
|||||||
/**
|
/**
|
||||||
* Register succeeded.
|
* Register succeeded.
|
||||||
*
|
*
|
||||||
* @param captchaToken the captcha bypass token to bypass future captcha verifications.
|
|
||||||
*/
|
*/
|
||||||
data class Success(val captchaToken: String?) : RegisterResult()
|
data object Success : RegisterResult()
|
||||||
|
|
||||||
/**
|
|
||||||
* Captcha verification is required.
|
|
||||||
*
|
|
||||||
* @param captchaId the captcha id for performing the captcha verification.
|
|
||||||
*/
|
|
||||||
data class CaptchaRequired(val captchaId: String) : RegisterResult()
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* There was an error logging in.
|
* There was an error logging in.
|
||||||
|
|||||||
@ -15,6 +15,6 @@ sealed class ResendEmailResult {
|
|||||||
*/
|
*/
|
||||||
data class Error(
|
data class Error(
|
||||||
val message: String?,
|
val message: String?,
|
||||||
val error: Throwable,
|
val error: Throwable?,
|
||||||
) : ResendEmailResult()
|
) : ResendEmailResult()
|
||||||
}
|
}
|
||||||
|
|||||||
@ -0,0 +1,25 @@
|
|||||||
|
package com.x8bit.bitwarden.data.auth.repository.model
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Models result of updating a user's kdf settings to minimums
|
||||||
|
*/
|
||||||
|
sealed class UpdateKdfMinimumsResult {
|
||||||
|
/**
|
||||||
|
* Active account was not found
|
||||||
|
*/
|
||||||
|
object ActiveAccountNotFound : UpdateKdfMinimumsResult()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* There was an error updating user to minimum kdf settings.
|
||||||
|
*
|
||||||
|
* @param error the error.
|
||||||
|
*/
|
||||||
|
data class Error(
|
||||||
|
val error: Throwable?,
|
||||||
|
) : UpdateKdfMinimumsResult()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updated user to minimum kdf settings successfully.
|
||||||
|
*/
|
||||||
|
object Success : UpdateKdfMinimumsResult()
|
||||||
|
}
|
||||||
@ -75,6 +75,7 @@ data class UserState(
|
|||||||
val isUsingKeyConnector: Boolean,
|
val isUsingKeyConnector: Boolean,
|
||||||
val onboardingStatus: OnboardingStatus,
|
val onboardingStatus: OnboardingStatus,
|
||||||
val firstTimeState: FirstTimeState,
|
val firstTimeState: FirstTimeState,
|
||||||
|
val isExportable: Boolean,
|
||||||
) {
|
) {
|
||||||
/**
|
/**
|
||||||
* Indicates that the user does or does not have a means to manually unlock the vault.
|
* Indicates that the user does or does not have a means to manually unlock the vault.
|
||||||
|
|||||||
@ -1,74 +0,0 @@
|
|||||||
package com.x8bit.bitwarden.data.auth.repository.util
|
|
||||||
|
|
||||||
import android.content.Intent
|
|
||||||
import android.net.Uri
|
|
||||||
import kotlinx.serialization.json.buildJsonObject
|
|
||||||
import kotlinx.serialization.json.put
|
|
||||||
import java.net.URLEncoder
|
|
||||||
import java.util.Base64
|
|
||||||
import java.util.Locale
|
|
||||||
|
|
||||||
private const val CAPTCHA_HOST: String = "captcha-callback"
|
|
||||||
private const val CALLBACK_URI = "bitwarden://$CAPTCHA_HOST"
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Generates a [Uri] to display a CAPTCHA challenge for Bitwarden authentication.
|
|
||||||
*/
|
|
||||||
fun generateUriForCaptcha(captchaId: String): Uri {
|
|
||||||
val json = buildJsonObject {
|
|
||||||
put(key = "siteKey", value = captchaId)
|
|
||||||
put(key = "locale", value = Locale.getDefault().toString())
|
|
||||||
put(key = "callbackUri", value = CALLBACK_URI)
|
|
||||||
put(key = "captchaRequiredText", value = "Captcha required")
|
|
||||||
}
|
|
||||||
val base64Data = Base64
|
|
||||||
.getEncoder()
|
|
||||||
.encodeToString(
|
|
||||||
json
|
|
||||||
.toString()
|
|
||||||
.toByteArray(Charsets.UTF_8),
|
|
||||||
)
|
|
||||||
val parentParam = URLEncoder.encode(CALLBACK_URI, "UTF-8")
|
|
||||||
val url = "https://vault.bitwarden.com/captcha-mobile-connector.html" +
|
|
||||||
"?data=$base64Data&parent=$parentParam&v=1"
|
|
||||||
return Uri.parse(url)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieves a [CaptchaCallbackTokenResult] from an Intent. There are three possible cases.
|
|
||||||
*
|
|
||||||
* - `null`: Intent is not a captcha callback, or data is null.
|
|
||||||
*
|
|
||||||
* - [CaptchaCallbackTokenResult.MissingToken]:
|
|
||||||
* Intent is the captcha callback, but its missing a token value.
|
|
||||||
*
|
|
||||||
* - [CaptchaCallbackTokenResult.Success]:
|
|
||||||
* Intent is the captcha callback, and it has a token.
|
|
||||||
*/
|
|
||||||
fun Intent.getCaptchaCallbackTokenResult(): CaptchaCallbackTokenResult? {
|
|
||||||
val localData = data
|
|
||||||
return if (
|
|
||||||
action == Intent.ACTION_VIEW && localData != null && localData.host == CAPTCHA_HOST
|
|
||||||
) {
|
|
||||||
localData.getQueryParameter("token")?.let {
|
|
||||||
CaptchaCallbackTokenResult.Success(token = it)
|
|
||||||
} ?: CaptchaCallbackTokenResult.MissingToken
|
|
||||||
} else {
|
|
||||||
null
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sealed class representing the result of captcha callback token extraction.
|
|
||||||
*/
|
|
||||||
sealed class CaptchaCallbackTokenResult {
|
|
||||||
/**
|
|
||||||
* Represents a missing token in the captcha callback.
|
|
||||||
*/
|
|
||||||
data object MissingToken : CaptchaCallbackTokenResult()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Represents a token present in the captcha callback.
|
|
||||||
*/
|
|
||||||
data class Success(val token: String) : CaptchaCallbackTokenResult()
|
|
||||||
}
|
|
||||||
@ -1,6 +1,9 @@
|
|||||||
package com.x8bit.bitwarden.data.auth.repository.util
|
package com.x8bit.bitwarden.data.auth.repository.util
|
||||||
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
|
import androidx.browser.auth.AuthTabIntent
|
||||||
|
import com.bitwarden.annotation.OmitFromCoverage
|
||||||
|
|
||||||
private const val DUO_HOST: String = "duo-callback"
|
private const val DUO_HOST: String = "duo-callback"
|
||||||
|
|
||||||
@ -16,21 +19,44 @@ private const val DUO_HOST: String = "duo-callback"
|
|||||||
*/
|
*/
|
||||||
fun Intent.getDuoCallbackTokenResult(): DuoCallbackTokenResult? {
|
fun Intent.getDuoCallbackTokenResult(): DuoCallbackTokenResult? {
|
||||||
val localData = data
|
val localData = data
|
||||||
return if (
|
return if (action == Intent.ACTION_VIEW && localData != null && localData.host == DUO_HOST) {
|
||||||
action == Intent.ACTION_VIEW && localData != null && localData.host == DUO_HOST
|
localData.getDuoCallbackTokenResult()
|
||||||
) {
|
|
||||||
val code = localData.getQueryParameter("code")
|
|
||||||
val state = localData.getQueryParameter("state")
|
|
||||||
if (code != null && state != null) {
|
|
||||||
DuoCallbackTokenResult.Success(token = "$code|$state")
|
|
||||||
} else {
|
|
||||||
DuoCallbackTokenResult.MissingToken
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves a [DuoCallbackTokenResult] from an Intent. There are three possible cases.
|
||||||
|
*
|
||||||
|
* - `null`: Intent is not a Duo callback, or data is null.
|
||||||
|
*
|
||||||
|
* - [DuoCallbackTokenResult.MissingToken]: Intent is the Duo callback, but it's missing the code or
|
||||||
|
* state value.
|
||||||
|
*
|
||||||
|
* - [DuoCallbackTokenResult.Success]: Intent is the Duo callback, and it has a token.
|
||||||
|
*/
|
||||||
|
@OmitFromCoverage
|
||||||
|
fun AuthTabIntent.AuthResult.getDuoCallbackTokenResult(): DuoCallbackTokenResult =
|
||||||
|
when (this.resultCode) {
|
||||||
|
AuthTabIntent.RESULT_OK -> this.resultUri.getDuoCallbackTokenResult()
|
||||||
|
AuthTabIntent.RESULT_CANCELED -> DuoCallbackTokenResult.MissingToken
|
||||||
|
AuthTabIntent.RESULT_UNKNOWN_CODE -> DuoCallbackTokenResult.MissingToken
|
||||||
|
AuthTabIntent.RESULT_VERIFICATION_FAILED -> DuoCallbackTokenResult.MissingToken
|
||||||
|
AuthTabIntent.RESULT_VERIFICATION_TIMED_OUT -> DuoCallbackTokenResult.MissingToken
|
||||||
|
else -> DuoCallbackTokenResult.MissingToken
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Uri?.getDuoCallbackTokenResult(): DuoCallbackTokenResult {
|
||||||
|
val code = this?.getQueryParameter("code")
|
||||||
|
val state = this?.getQueryParameter("state")
|
||||||
|
return if (code != null && state != null) {
|
||||||
|
DuoCallbackTokenResult.Success(token = "$code|$state")
|
||||||
|
} else {
|
||||||
|
DuoCallbackTokenResult.MissingToken
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sealed class representing the result of Duo callback token extraction.
|
* Sealed class representing the result of Duo callback token extraction.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@ -1,7 +1,10 @@
|
|||||||
package com.x8bit.bitwarden.data.auth.repository.util
|
package com.x8bit.bitwarden.data.auth.repository.util
|
||||||
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
|
import android.net.Uri
|
||||||
import android.os.Parcelable
|
import android.os.Parcelable
|
||||||
|
import androidx.browser.auth.AuthTabIntent
|
||||||
|
import com.bitwarden.annotation.OmitFromCoverage
|
||||||
import kotlinx.parcelize.Parcelize
|
import kotlinx.parcelize.Parcelize
|
||||||
import java.net.URLEncoder
|
import java.net.URLEncoder
|
||||||
import java.security.MessageDigest
|
import java.security.MessageDigest
|
||||||
@ -61,21 +64,40 @@ fun generateUriForSso(
|
|||||||
fun Intent.getSsoCallbackResult(): SsoCallbackResult? {
|
fun Intent.getSsoCallbackResult(): SsoCallbackResult? {
|
||||||
val localData = data
|
val localData = data
|
||||||
return if (action == Intent.ACTION_VIEW && localData?.host == SSO_HOST) {
|
return if (action == Intent.ACTION_VIEW && localData?.host == SSO_HOST) {
|
||||||
val state = localData.getQueryParameter("state")
|
localData.getSsoCallbackResult()
|
||||||
val code = localData.getQueryParameter("code")
|
|
||||||
if (code != null) {
|
|
||||||
SsoCallbackResult.Success(
|
|
||||||
state = state,
|
|
||||||
code = code,
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
SsoCallbackResult.MissingCode
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves an [SsoCallbackResult] from an [AuthTabIntent.AuthResult]. There are two possible
|
||||||
|
* cases.
|
||||||
|
*
|
||||||
|
* - [SsoCallbackResult.MissingCode]: The code is missing.
|
||||||
|
* - [SsoCallbackResult.Success]: The relevant data is present.
|
||||||
|
*/
|
||||||
|
@OmitFromCoverage
|
||||||
|
fun AuthTabIntent.AuthResult.getSsoCallbackResult(): SsoCallbackResult =
|
||||||
|
when (this.resultCode) {
|
||||||
|
AuthTabIntent.RESULT_OK -> this.resultUri.getSsoCallbackResult()
|
||||||
|
AuthTabIntent.RESULT_CANCELED -> SsoCallbackResult.MissingCode
|
||||||
|
AuthTabIntent.RESULT_UNKNOWN_CODE -> SsoCallbackResult.MissingCode
|
||||||
|
AuthTabIntent.RESULT_VERIFICATION_FAILED -> SsoCallbackResult.MissingCode
|
||||||
|
AuthTabIntent.RESULT_VERIFICATION_TIMED_OUT -> SsoCallbackResult.MissingCode
|
||||||
|
else -> SsoCallbackResult.MissingCode
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Uri?.getSsoCallbackResult(): SsoCallbackResult {
|
||||||
|
val state = this?.getQueryParameter("state")
|
||||||
|
val code = this?.getQueryParameter("code")
|
||||||
|
return if (code != null) {
|
||||||
|
SsoCallbackResult.Success(state = state, code = code)
|
||||||
|
} else {
|
||||||
|
SsoCallbackResult.MissingCode
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sealed class representing the result of an SSO callback data extraction.
|
* Sealed class representing the result of an SSO callback data extraction.
|
||||||
*/
|
*/
|
||||||
|
|||||||
@ -1,7 +1,9 @@
|
|||||||
package com.x8bit.bitwarden.data.auth.repository.util
|
package com.x8bit.bitwarden.data.auth.repository.util
|
||||||
|
|
||||||
import com.bitwarden.data.repository.util.toEnvironmentUrlsOrDefault
|
import com.bitwarden.data.repository.util.toEnvironmentUrlsOrDefault
|
||||||
|
import com.bitwarden.network.model.KdfTypeJson
|
||||||
import com.bitwarden.network.model.OrganizationType
|
import com.bitwarden.network.model.OrganizationType
|
||||||
|
import com.bitwarden.network.model.PolicyTypeJson
|
||||||
import com.bitwarden.network.model.SyncResponseJson
|
import com.bitwarden.network.model.SyncResponseJson
|
||||||
import com.bitwarden.network.model.UserDecryptionOptionsJson
|
import com.bitwarden.network.model.UserDecryptionOptionsJson
|
||||||
import com.bitwarden.ui.platform.base.util.toHexColorRepresentation
|
import com.bitwarden.ui.platform.base.util.toHexColorRepresentation
|
||||||
@ -12,6 +14,7 @@ import com.x8bit.bitwarden.data.auth.repository.model.UserKeyConnectorState
|
|||||||
import com.x8bit.bitwarden.data.auth.repository.model.UserOrganizations
|
import com.x8bit.bitwarden.data.auth.repository.model.UserOrganizations
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.UserState
|
import com.x8bit.bitwarden.data.auth.repository.model.UserState
|
||||||
import com.x8bit.bitwarden.data.auth.repository.model.VaultUnlockType
|
import com.x8bit.bitwarden.data.auth.repository.model.VaultUnlockType
|
||||||
|
import com.x8bit.bitwarden.data.auth.util.KdfParamsConstants.DEFAULT_PBKDF2_ITERATIONS
|
||||||
import com.x8bit.bitwarden.data.platform.manager.model.FirstTimeState
|
import com.x8bit.bitwarden.data.platform.manager.model.FirstTimeState
|
||||||
import com.x8bit.bitwarden.data.vault.repository.model.VaultUnlockData
|
import com.x8bit.bitwarden.data.vault.repository.model.VaultUnlockData
|
||||||
import com.x8bit.bitwarden.data.vault.repository.util.statusFor
|
import com.x8bit.bitwarden.data.vault.repository.util.statusFor
|
||||||
@ -32,6 +35,7 @@ fun UserStateJson.toRemovedPasswordUserStateJson(
|
|||||||
hasMasterPassword = false,
|
hasMasterPassword = false,
|
||||||
trustedDeviceUserDecryptionOptions = null,
|
trustedDeviceUserDecryptionOptions = null,
|
||||||
keyConnectorUserDecryptionOptions = null,
|
keyConnectorUserDecryptionOptions = null,
|
||||||
|
masterPasswordUnlock = null,
|
||||||
)
|
)
|
||||||
val updatedProfile = profile.copy(userDecryptionOptions = updatedUserDecryptionOptions)
|
val updatedProfile = profile.copy(userDecryptionOptions = updatedUserDecryptionOptions)
|
||||||
val updatedAccount = account.copy(profile = updatedProfile)
|
val updatedAccount = account.copy(profile = updatedProfile)
|
||||||
@ -54,6 +58,23 @@ fun UserStateJson.toUpdatedUserStateJson(
|
|||||||
val userId = syncProfile.id
|
val userId = syncProfile.id
|
||||||
val account = this.accounts[userId] ?: return this
|
val account = this.accounts[userId] ?: return this
|
||||||
val profile = account.profile
|
val profile = account.profile
|
||||||
|
val userDecryptionOptions = syncResponse
|
||||||
|
.userDecryption
|
||||||
|
?.let { syncUserDecryption ->
|
||||||
|
profile
|
||||||
|
.userDecryptionOptions
|
||||||
|
?.copy(masterPasswordUnlock = syncUserDecryption.masterPasswordUnlock)
|
||||||
|
?: UserDecryptionOptionsJson(
|
||||||
|
hasMasterPassword = syncUserDecryption.masterPasswordUnlock != null,
|
||||||
|
trustedDeviceUserDecryptionOptions = null,
|
||||||
|
keyConnectorUserDecryptionOptions = null,
|
||||||
|
masterPasswordUnlock = syncUserDecryption.masterPasswordUnlock,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
?: profile
|
||||||
|
.userDecryptionOptions
|
||||||
|
?.copy(masterPasswordUnlock = null)
|
||||||
|
|
||||||
val updatedProfile = profile
|
val updatedProfile = profile
|
||||||
.copy(
|
.copy(
|
||||||
avatarColorHex = syncProfile.avatarColor,
|
avatarColorHex = syncProfile.avatarColor,
|
||||||
@ -61,6 +82,7 @@ fun UserStateJson.toUpdatedUserStateJson(
|
|||||||
hasPremium = syncProfile.isPremium || syncProfile.isPremiumFromOrganization,
|
hasPremium = syncProfile.isPremium || syncProfile.isPremiumFromOrganization,
|
||||||
isTwoFactorEnabled = syncProfile.isTwoFactorEnabled,
|
isTwoFactorEnabled = syncProfile.isTwoFactorEnabled,
|
||||||
creationDate = syncProfile.creationDate,
|
creationDate = syncProfile.creationDate,
|
||||||
|
userDecryptionOptions = userDecryptionOptions,
|
||||||
)
|
)
|
||||||
val updatedAccount = account.copy(profile = updatedProfile)
|
val updatedAccount = account.copy(profile = updatedProfile)
|
||||||
return this
|
return this
|
||||||
@ -90,6 +112,7 @@ fun UserStateJson.toUserStateJsonWithPassword(): UserStateJson {
|
|||||||
hasMasterPassword = true,
|
hasMasterPassword = true,
|
||||||
keyConnectorUserDecryptionOptions = null,
|
keyConnectorUserDecryptionOptions = null,
|
||||||
trustedDeviceUserDecryptionOptions = null,
|
trustedDeviceUserDecryptionOptions = null,
|
||||||
|
masterPasswordUnlock = null,
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
val updatedAccount = account.copy(profile = updatedProfile)
|
val updatedAccount = account.copy(profile = updatedProfile)
|
||||||
@ -103,6 +126,30 @@ fun UserStateJson.toUserStateJsonWithPassword(): UserStateJson {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Updates the [UserStateJson] KDF settings to minimum requirements.
|
||||||
|
*/
|
||||||
|
fun UserStateJson.toUserStateJsonKdfUpdatedMinimums(): UserStateJson {
|
||||||
|
val account = this.activeAccount
|
||||||
|
val profile = account.profile
|
||||||
|
val updatedProfile = profile
|
||||||
|
.copy(
|
||||||
|
kdfType = KdfTypeJson.PBKDF2_SHA256,
|
||||||
|
kdfIterations = DEFAULT_PBKDF2_ITERATIONS,
|
||||||
|
kdfMemory = null,
|
||||||
|
kdfParallelism = null,
|
||||||
|
)
|
||||||
|
val updatedAccount = account.copy(profile = updatedProfile)
|
||||||
|
return this
|
||||||
|
.copy(
|
||||||
|
accounts = accounts
|
||||||
|
.toMutableMap()
|
||||||
|
.apply {
|
||||||
|
replace(activeUserId, updatedAccount)
|
||||||
|
},
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Converts the given [UserStateJson] to a [UserState] using the given [vaultState].
|
* Converts the given [UserStateJson] to a [UserState] using the given [vaultState].
|
||||||
*/
|
*/
|
||||||
@ -118,6 +165,7 @@ fun UserStateJson.toUserState(
|
|||||||
isBiometricsEnabledProvider: (userId: String) -> Boolean,
|
isBiometricsEnabledProvider: (userId: String) -> Boolean,
|
||||||
vaultUnlockTypeProvider: (userId: String) -> VaultUnlockType,
|
vaultUnlockTypeProvider: (userId: String) -> VaultUnlockType,
|
||||||
isDeviceTrustedProvider: (userId: String) -> Boolean,
|
isDeviceTrustedProvider: (userId: String) -> Boolean,
|
||||||
|
getUserPolicies: (userId: String, policy: PolicyTypeJson) -> List<SyncResponseJson.Policy>,
|
||||||
): UserState =
|
): UserState =
|
||||||
UserState(
|
UserState(
|
||||||
activeUserId = this.activeUserId,
|
activeUserId = this.activeUserId,
|
||||||
@ -157,6 +205,19 @@ fun UserStateJson.toUserState(
|
|||||||
hasManageResetPasswordPermission.takeIf { trustedDevice != null }
|
hasManageResetPasswordPermission.takeIf { trustedDevice != null }
|
||||||
val needsMasterPassword = decryptionOptions?.hasMasterPassword == false &&
|
val needsMasterPassword = decryptionOptions?.hasMasterPassword == false &&
|
||||||
(tdeUserNeedsMasterPassword ?: (keyConnectorOptions == null))
|
(tdeUserNeedsMasterPassword ?: (keyConnectorOptions == null))
|
||||||
|
|
||||||
|
val hasPersonalOwnershipRestrictedOrg = getUserPolicies(
|
||||||
|
userId,
|
||||||
|
PolicyTypeJson.PERSONAL_OWNERSHIP,
|
||||||
|
)
|
||||||
|
.any { it.isEnabled }
|
||||||
|
|
||||||
|
val hasPersonalVaultExportRestrictedOrg = getUserPolicies(
|
||||||
|
userId,
|
||||||
|
PolicyTypeJson.DISABLE_PERSONAL_VAULT_EXPORT,
|
||||||
|
)
|
||||||
|
.any { it.isEnabled }
|
||||||
|
|
||||||
UserState.Account(
|
UserState.Account(
|
||||||
userId = userId,
|
userId = userId,
|
||||||
name = profile.name,
|
name = profile.name,
|
||||||
@ -185,6 +246,8 @@ fun UserStateJson.toUserState(
|
|||||||
// using the app prior to the release of the onboarding flow.
|
// using the app prior to the release of the onboarding flow.
|
||||||
onboardingStatus = onboardingStatus ?: OnboardingStatus.COMPLETE,
|
onboardingStatus = onboardingStatus ?: OnboardingStatus.COMPLETE,
|
||||||
firstTimeState = firstTimeState,
|
firstTimeState = firstTimeState,
|
||||||
|
isExportable = !hasPersonalOwnershipRestrictedOrg &&
|
||||||
|
!hasPersonalVaultExportRestrictedOrg,
|
||||||
)
|
)
|
||||||
},
|
},
|
||||||
hasPendingAccountAddition = hasPendingAccountAddition,
|
hasPendingAccountAddition = hasPendingAccountAddition,
|
||||||
|
|||||||
@ -2,6 +2,9 @@ package com.x8bit.bitwarden.data.auth.repository.util
|
|||||||
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.net.Uri
|
import android.net.Uri
|
||||||
|
import androidx.browser.auth.AuthTabIntent
|
||||||
|
import androidx.core.net.toUri
|
||||||
|
import com.bitwarden.annotation.OmitFromCoverage
|
||||||
import kotlinx.serialization.json.JsonObject
|
import kotlinx.serialization.json.JsonObject
|
||||||
import kotlinx.serialization.json.buildJsonObject
|
import kotlinx.serialization.json.buildJsonObject
|
||||||
import kotlinx.serialization.json.put
|
import kotlinx.serialization.json.put
|
||||||
@ -24,15 +27,36 @@ fun Intent.getWebAuthResultOrNull(): WebAuthResult? {
|
|||||||
localData != null &&
|
localData != null &&
|
||||||
localData.host == WEB_AUTH_HOST
|
localData.host == WEB_AUTH_HOST
|
||||||
) {
|
) {
|
||||||
localData
|
localData.getWebAuthResult()
|
||||||
.getQueryParameter("data")
|
|
||||||
?.let { WebAuthResult.Success(token = it) }
|
|
||||||
?: WebAuthResult.Failure(message = localData.getQueryParameter("error"))
|
|
||||||
} else {
|
} else {
|
||||||
null
|
null
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Retrieves an [WebAuthResult] from an [AuthTabIntent.AuthResult]. There are two possible cases.
|
||||||
|
*
|
||||||
|
* - [WebAuthResult.Success]: The URI is the web auth key callback with correct data.
|
||||||
|
* - [WebAuthResult.Failure]: The URI is the web auth key callback with incorrect data or a failure
|
||||||
|
* has occurred.
|
||||||
|
*/
|
||||||
|
@OmitFromCoverage
|
||||||
|
fun AuthTabIntent.AuthResult.getWebAuthResult(): WebAuthResult =
|
||||||
|
when (this.resultCode) {
|
||||||
|
AuthTabIntent.RESULT_OK -> this.resultUri.getWebAuthResult()
|
||||||
|
AuthTabIntent.RESULT_CANCELED -> WebAuthResult.Failure(message = null)
|
||||||
|
AuthTabIntent.RESULT_UNKNOWN_CODE -> WebAuthResult.Failure(message = null)
|
||||||
|
AuthTabIntent.RESULT_VERIFICATION_FAILED -> WebAuthResult.Failure(message = null)
|
||||||
|
AuthTabIntent.RESULT_VERIFICATION_TIMED_OUT -> WebAuthResult.Failure(message = null)
|
||||||
|
else -> WebAuthResult.Failure(message = null)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun Uri?.getWebAuthResult(): WebAuthResult =
|
||||||
|
this
|
||||||
|
?.getQueryParameter("data")
|
||||||
|
?.let { WebAuthResult.Success(token = it) }
|
||||||
|
?: WebAuthResult.Failure(message = this?.getQueryParameter("error"))
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generates a [Uri] to display a web authn challenge for Bitwarden authentication.
|
* Generates a [Uri] to display a web authn challenge for Bitwarden authentication.
|
||||||
*/
|
*/
|
||||||
@ -59,7 +83,7 @@ fun generateUriForWebAuth(
|
|||||||
"?data=$base64Data" +
|
"?data=$base64Data" +
|
||||||
"&parent=$parentParam" +
|
"&parent=$parentParam" +
|
||||||
"&v=2"
|
"&v=2"
|
||||||
return Uri.parse(url)
|
return url.toUri()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@ -1,7 +1,7 @@
|
|||||||
package com.x8bit.bitwarden.data.auth.util
|
package com.x8bit.bitwarden.data.auth.util
|
||||||
|
|
||||||
import android.content.Intent
|
import android.content.Intent
|
||||||
import android.net.Uri
|
import androidx.core.net.toUri
|
||||||
import com.x8bit.bitwarden.data.platform.manager.model.CompleteRegistrationData
|
import com.x8bit.bitwarden.data.platform.manager.model.CompleteRegistrationData
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -14,7 +14,7 @@ fun Intent.getCompleteRegistrationDataIntentOrNull(): CompleteRegistrationData?
|
|||||||
newValue = "/",
|
newValue = "/",
|
||||||
ignoreCase = true,
|
ignoreCase = true,
|
||||||
)
|
)
|
||||||
val uri = runCatching { Uri.parse(sanitizedUriString) }.getOrNull() ?: return null
|
val uri = runCatching { sanitizedUriString.toUri() }.getOrNull() ?: return null
|
||||||
uri.host ?: return null
|
uri.host ?: return null
|
||||||
if (uri.path != "/finish-signup") return null
|
if (uri.path != "/finish-signup") return null
|
||||||
val email = uri.getQueryParameter("email") ?: return null
|
val email = uri.getQueryParameter("email") ?: return null
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user