python-vaultwarden2 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- python_vaultwarden2-0.1.0.dist-info/METADATA +69 -0
- python_vaultwarden2-0.1.0.dist-info/RECORD +34 -0
- python_vaultwarden2-0.1.0.dist-info/WHEEL +4 -0
- python_vaultwarden2-0.1.0.dist-info/licenses/LICENSE +202 -0
- vaultwarden2/__init__.py +47 -0
- vaultwarden2/_async/__init__.py +1 -0
- vaultwarden2/_async/account.py +379 -0
- vaultwarden2/_async/admin.py +485 -0
- vaultwarden2/_async/auth.py +218 -0
- vaultwarden2/_async/base.py +462 -0
- vaultwarden2/_async/client.py +130 -0
- vaultwarden2/_async/organizations.py +914 -0
- vaultwarden2/_async/vault.py +970 -0
- vaultwarden2/_core.py +1103 -0
- vaultwarden2/_encode.py +422 -0
- vaultwarden2/_json.py +215 -0
- vaultwarden2/_merge.py +529 -0
- vaultwarden2/_offload.py +65 -0
- vaultwarden2/_sync/__init__.py +1 -0
- vaultwarden2/_sync/account.py +381 -0
- vaultwarden2/_sync/admin.py +487 -0
- vaultwarden2/_sync/auth.py +220 -0
- vaultwarden2/_sync/base.py +464 -0
- vaultwarden2/_sync/client.py +132 -0
- vaultwarden2/_sync/organizations.py +914 -0
- vaultwarden2/_sync/vault.py +968 -0
- vaultwarden2/crypto.py +634 -0
- vaultwarden2/dump.py +362 -0
- vaultwarden2/errors.py +123 -0
- vaultwarden2/export.py +128 -0
- vaultwarden2/models.py +842 -0
- vaultwarden2/py.typed +0 -0
- vaultwarden2/search.py +206 -0
- vaultwarden2/totp.py +214 -0
|
@@ -0,0 +1,379 @@
|
|
|
1
|
+
"""Account management.
|
|
2
|
+
|
|
3
|
+
Every operation is a single server-side request. Password, KDF and email changes only re-wrap the user key
|
|
4
|
+
with a new master key; vault data is never re-encrypted, so nothing can become unreadable.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from typing import TYPE_CHECKING
|
|
10
|
+
from urllib.parse import quote
|
|
11
|
+
|
|
12
|
+
from vaultwarden2 import _core, _offload, crypto
|
|
13
|
+
from vaultwarden2._json import JsonObject
|
|
14
|
+
from vaultwarden2.errors import ApiError, VaultwardenError
|
|
15
|
+
from vaultwarden2.models import KnownDevice, TotpSetup, TwoFactorProvider
|
|
16
|
+
from vaultwarden2.totp import totp_code
|
|
17
|
+
|
|
18
|
+
from . import auth as _auth_mod
|
|
19
|
+
|
|
20
|
+
if TYPE_CHECKING:
|
|
21
|
+
from vaultwarden2.crypto import KdfParams
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class AsyncAccountMixin(_auth_mod.AsyncAuthMixin):
|
|
25
|
+
"""Master password, KDF, email, two-step login, devices and the account itself."""
|
|
26
|
+
|
|
27
|
+
async def _email(self) -> str:
|
|
28
|
+
"""The email of the logged-in account.
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
The email address (from the cached profile, fetched if needed).
|
|
32
|
+
"""
|
|
33
|
+
profile = self._profile or await self._load_profile()
|
|
34
|
+
return profile.get_str('email') or ''
|
|
35
|
+
|
|
36
|
+
async def _after_credentials_change(self, email: str, password: str) -> None:
|
|
37
|
+
"""Get a fresh session after the server reset the security stamp.
|
|
38
|
+
|
|
39
|
+
Tries the refresh token first and falls back to a full login with the new credentials.
|
|
40
|
+
|
|
41
|
+
Args:
|
|
42
|
+
email: The (possibly new) email address.
|
|
43
|
+
password: The (possibly new) master password.
|
|
44
|
+
"""
|
|
45
|
+
try:
|
|
46
|
+
await self.refresh()
|
|
47
|
+
except VaultwardenError:
|
|
48
|
+
await self.login_password(email, password)
|
|
49
|
+
else:
|
|
50
|
+
await self._load_profile()
|
|
51
|
+
|
|
52
|
+
async def verify_password(self, password: str) -> bool:
|
|
53
|
+
"""Check the master password against the server, without logging in again.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
password: The master password to check.
|
|
57
|
+
|
|
58
|
+
Returns:
|
|
59
|
+
True if the password is correct.
|
|
60
|
+
|
|
61
|
+
Raises:
|
|
62
|
+
ApiError: The server failed for another reason than a wrong password.
|
|
63
|
+
"""
|
|
64
|
+
try:
|
|
65
|
+
await self.request('POST', '/api/accounts/verify-password', json={'masterPasswordHash': await self._password_hash(password)})
|
|
66
|
+
except ApiError as e:
|
|
67
|
+
if e.status_code == 400:
|
|
68
|
+
return False
|
|
69
|
+
raise
|
|
70
|
+
return True
|
|
71
|
+
|
|
72
|
+
async def change_master_password(self, old_password: str, new_password: str, *, hint: str | None = None) -> None:
|
|
73
|
+
"""Change the master password.
|
|
74
|
+
|
|
75
|
+
The user key is re-wrapped with the new master key in one atomic request; vault data is not touched. The
|
|
76
|
+
payload is re-derived and checked before it is sent. The server logs out all other devices; this client
|
|
77
|
+
continues with a fresh session.
|
|
78
|
+
|
|
79
|
+
Args:
|
|
80
|
+
old_password: The current master password.
|
|
81
|
+
new_password: The new master password.
|
|
82
|
+
hint: The new password hint; None removes the hint.
|
|
83
|
+
|
|
84
|
+
Raises:
|
|
85
|
+
ApiError: The current password is wrong; nothing was changed.
|
|
86
|
+
UnsafeWriteError: The self-check of the new key material failed; nothing was sent.
|
|
87
|
+
"""
|
|
88
|
+
keys = self._require_keys()
|
|
89
|
+
email = await self._email()
|
|
90
|
+
kdf = await self.prelogin(email)
|
|
91
|
+
payload = {
|
|
92
|
+
'masterPasswordHash': await self._password_hash(old_password),
|
|
93
|
+
'masterPasswordHint': hint,
|
|
94
|
+
**await _offload.arun_cpu(_core.master_password_data, email, new_password, kdf, keys.user_key),
|
|
95
|
+
}
|
|
96
|
+
await self.request('POST', '/api/accounts/password', json=payload)
|
|
97
|
+
await self._after_credentials_change(email, new_password)
|
|
98
|
+
|
|
99
|
+
async def set_password_hint(self, password: str, hint: str | None) -> None:
|
|
100
|
+
"""Set or remove the master password hint.
|
|
101
|
+
|
|
102
|
+
Internally a password change to the same password, so other devices are logged out.
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
password: The current master password.
|
|
106
|
+
hint: The new hint; None removes it.
|
|
107
|
+
|
|
108
|
+
Raises:
|
|
109
|
+
ApiError: The password is wrong; nothing was changed.
|
|
110
|
+
"""
|
|
111
|
+
await self.change_master_password(password, password, hint=hint)
|
|
112
|
+
|
|
113
|
+
async def change_kdf(self, password: str, kdf: KdfParams) -> None:
|
|
114
|
+
"""Change the key derivation settings, for example from PBKDF2 to Argon2id.
|
|
115
|
+
|
|
116
|
+
Atomic like [change_master_password][vaultwarden2.AsyncVaultwardenClient.change_master_password]: only the
|
|
117
|
+
user key is re-wrapped. The settings are checked against vaultwarden's limits before anything is sent.
|
|
118
|
+
|
|
119
|
+
Args:
|
|
120
|
+
password: The master password.
|
|
121
|
+
kdf: The new settings, for example ``KdfParams.argon2id()`` or ``KdfParams.pbkdf2(1_000_000)``.
|
|
122
|
+
|
|
123
|
+
Raises:
|
|
124
|
+
CryptoError: The settings are outside the supported range: PBKDF2 100000-2000000 iterations; Argon2id
|
|
125
|
+
2-10 iterations, 16-1024 MiB, 1-16 lanes. Within it, vaultwarden accepts the settings and both this library
|
|
126
|
+
and the official apps can log in afterwards. Nothing was sent.
|
|
127
|
+
ApiError: The password is wrong; nothing was changed.
|
|
128
|
+
"""
|
|
129
|
+
_core.validate_kdf(kdf)
|
|
130
|
+
keys = self._require_keys()
|
|
131
|
+
email = await self._email()
|
|
132
|
+
payload = {
|
|
133
|
+
'masterPasswordHash': await self._password_hash(password),
|
|
134
|
+
**await _offload.arun_cpu(_core.master_password_data, email, password, kdf, keys.user_key),
|
|
135
|
+
}
|
|
136
|
+
await self.request('POST', '/api/accounts/kdf', json=payload)
|
|
137
|
+
await self._after_credentials_change(email, password)
|
|
138
|
+
|
|
139
|
+
async def request_email_change(self, new_email: str, password: str) -> None:
|
|
140
|
+
"""Start an email change: the server mails a confirmation token to the new address.
|
|
141
|
+
|
|
142
|
+
Servers that send no emails (neither ``SMTP_HOST`` nor ``USE_SENDMAIL`` configured) skip the token check, see
|
|
143
|
+
[confirm_email_change][vaultwarden2.AsyncVaultwardenClient.confirm_email_change].
|
|
144
|
+
|
|
145
|
+
Args:
|
|
146
|
+
new_email: The new email address.
|
|
147
|
+
password: The master password.
|
|
148
|
+
|
|
149
|
+
Raises:
|
|
150
|
+
ApiError: Wrong password, the address is in use, or email changes are disabled on the server.
|
|
151
|
+
"""
|
|
152
|
+
payload = {'newEmail': crypto.normalize_email(new_email), 'masterPasswordHash': await self._password_hash(password)}
|
|
153
|
+
await self.request('POST', '/api/accounts/email-token', json=payload)
|
|
154
|
+
|
|
155
|
+
async def confirm_email_change(self, new_email: str, password: str, token: str | None = None) -> None:
|
|
156
|
+
"""Finish an email change.
|
|
157
|
+
|
|
158
|
+
The email is the KDF salt, so the user key is re-wrapped for the new address (atomic, vault data untouched).
|
|
159
|
+
This client continues with a fresh session.
|
|
160
|
+
|
|
161
|
+
Args:
|
|
162
|
+
new_email: The new email address (as passed to ``request_email_change``).
|
|
163
|
+
password: The master password.
|
|
164
|
+
token: The token from the confirmation mail. Servers that send no emails do not check it, so it can be omitted.
|
|
165
|
+
|
|
166
|
+
Raises:
|
|
167
|
+
ApiError: Wrong password or token, or no email change is pending.
|
|
168
|
+
"""
|
|
169
|
+
keys = self._require_keys()
|
|
170
|
+
old_email = await self._email()
|
|
171
|
+
kdf = await self.prelogin(old_email)
|
|
172
|
+
data = await _offload.arun_cpu(_core.master_password_data, new_email, password, kdf, keys.user_key)
|
|
173
|
+
payload = {
|
|
174
|
+
'masterPasswordHash': await self._password_hash(password),
|
|
175
|
+
'newEmail': crypto.normalize_email(new_email),
|
|
176
|
+
'newMasterPasswordHash': data['authenticationData']['masterPasswordAuthenticationHash'],
|
|
177
|
+
'key': data['unlockData']['masterKeyWrappedUserKey'],
|
|
178
|
+
'token': token or '0',
|
|
179
|
+
}
|
|
180
|
+
await self.request('POST', '/api/accounts/email', json=payload)
|
|
181
|
+
await self._after_credentials_change(new_email, password)
|
|
182
|
+
|
|
183
|
+
async def update_profile(self, *, name: str) -> None:
|
|
184
|
+
"""Change the account's display name.
|
|
185
|
+
|
|
186
|
+
Args:
|
|
187
|
+
name: The new name (at most 50 characters).
|
|
188
|
+
|
|
189
|
+
Raises:
|
|
190
|
+
ApiError: The server rejected the name.
|
|
191
|
+
"""
|
|
192
|
+
await self.request('PUT', '/api/accounts/profile', json={'name': name})
|
|
193
|
+
await self._load_profile()
|
|
194
|
+
|
|
195
|
+
async def rotate_api_key(self, password: str) -> tuple[str, str]:
|
|
196
|
+
"""Replace the personal API key secret; the old secret stops working immediately.
|
|
197
|
+
|
|
198
|
+
Args:
|
|
199
|
+
password: The master password.
|
|
200
|
+
|
|
201
|
+
Returns:
|
|
202
|
+
``(client_id, client_secret)``: the id is unchanged, the secret is new.
|
|
203
|
+
|
|
204
|
+
Raises:
|
|
205
|
+
ApiError: Wrong password, or the server returned no key.
|
|
206
|
+
"""
|
|
207
|
+
body = JsonObject(await self.request('POST', '/api/accounts/rotate-api-key', json={'masterPasswordHash': await self._password_hash(password)}))
|
|
208
|
+
secret = body.get_str('apiKey')
|
|
209
|
+
if not secret:
|
|
210
|
+
raise ApiError(500, 'server returned no apiKey')
|
|
211
|
+
if self._api_key is not None:
|
|
212
|
+
self._api_key = (self._api_key[0], secret)
|
|
213
|
+
profile = self._profile or await self._load_profile()
|
|
214
|
+
return f'user.{profile.get_str("id")}', secret
|
|
215
|
+
|
|
216
|
+
async def delete_account(self, password: str, *, confirm: str) -> None:
|
|
217
|
+
"""Delete the account with all personal items, folders and sends. This cannot be undone.
|
|
218
|
+
|
|
219
|
+
The client is logged out afterwards.
|
|
220
|
+
|
|
221
|
+
Args:
|
|
222
|
+
password: The master password.
|
|
223
|
+
confirm: The account's email address, repeated as a guard against accidental calls
|
|
224
|
+
(case and spaces do not matter).
|
|
225
|
+
|
|
226
|
+
Raises:
|
|
227
|
+
VaultwardenError: ``confirm`` does not match the account's email; nothing was sent.
|
|
228
|
+
ApiError: Wrong password.
|
|
229
|
+
"""
|
|
230
|
+
email = await self._email()
|
|
231
|
+
if crypto.normalize_email(confirm) != crypto.normalize_email(email):
|
|
232
|
+
raise VaultwardenError('confirm must be the email address of the account being deleted')
|
|
233
|
+
await self.request('DELETE', '/api/accounts', json={'masterPasswordHash': await self._password_hash(password)})
|
|
234
|
+
self.logout()
|
|
235
|
+
|
|
236
|
+
# ------------------------------------------------------------ two-step login
|
|
237
|
+
|
|
238
|
+
async def two_factor_providers(self) -> list[TwoFactorProvider | int]:
|
|
239
|
+
"""The enabled two-step login methods.
|
|
240
|
+
|
|
241
|
+
Returns:
|
|
242
|
+
The enabled providers, see [TwoFactorProvider][vaultwarden2.models.TwoFactorProvider]
|
|
243
|
+
(unknown provider numbers are returned as plain ints). Empty if two-step login is off.
|
|
244
|
+
"""
|
|
245
|
+
body = JsonObject(await self.request('GET', '/api/two-factor'))
|
|
246
|
+
result: list[TwoFactorProvider | int] = []
|
|
247
|
+
for entry in body.objs('data'):
|
|
248
|
+
value = entry.get_int('type')
|
|
249
|
+
if value is not None and entry.get_bool('enabled', default=True):
|
|
250
|
+
try:
|
|
251
|
+
result.append(TwoFactorProvider(value))
|
|
252
|
+
except ValueError:
|
|
253
|
+
result.append(value)
|
|
254
|
+
return result
|
|
255
|
+
|
|
256
|
+
async def begin_totp_setup(self, password: str) -> TotpSetup:
|
|
257
|
+
"""Start setting up an authenticator app (TOTP).
|
|
258
|
+
|
|
259
|
+
Nothing changes on the account yet. Show ``setup.uri`` as a QR code or ``setup.secret`` for manual entry,
|
|
260
|
+
then call [finish_totp_setup][vaultwarden2.AsyncVaultwardenClient.finish_totp_setup] with a code from the app.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
password: The master password.
|
|
264
|
+
|
|
265
|
+
Returns:
|
|
266
|
+
The pending setup with the secret and the ``otpauth://`` URI.
|
|
267
|
+
|
|
268
|
+
Raises:
|
|
269
|
+
VaultwardenError: An authenticator is already enabled; disable it first.
|
|
270
|
+
ApiError: Wrong password.
|
|
271
|
+
"""
|
|
272
|
+
body = JsonObject(await self.request('POST', '/api/two-factor/get-authenticator', json={'masterPasswordHash': await self._password_hash(password)}))
|
|
273
|
+
authenticator = body.obj('authenticator')
|
|
274
|
+
secret = authenticator.get_str('key') if authenticator else None
|
|
275
|
+
if authenticator is None or not secret:
|
|
276
|
+
raise ApiError(500, 'server returned no authenticator key')
|
|
277
|
+
if authenticator.get_bool('enabled'):
|
|
278
|
+
raise VaultwardenError('an authenticator is already enabled; disable it first')
|
|
279
|
+
email = await self._email()
|
|
280
|
+
uri = f'otpauth://totp/{quote("Vaultwarden:" + email)}?secret={secret}&issuer=Vaultwarden'
|
|
281
|
+
return TotpSetup(secret=secret, uri=uri, verification_token=body.get_str('userVerificationToken') or '')
|
|
282
|
+
|
|
283
|
+
async def finish_totp_setup(self, setup: TotpSetup, password: str, code: str | None = None) -> str:
|
|
284
|
+
"""Enable the authenticator after checking a current code from it.
|
|
285
|
+
|
|
286
|
+
The server accepts each 30-second code only once, so the next login needs a newer code.
|
|
287
|
+
|
|
288
|
+
Args:
|
|
289
|
+
setup: The pending setup from ``begin_totp_setup``.
|
|
290
|
+
password: The master password (needed to read the recovery code).
|
|
291
|
+
code: The current code shown by the authenticator app. Without it, the library computes the code from
|
|
292
|
+
the secret, for automation that stores the secret itself.
|
|
293
|
+
|
|
294
|
+
Returns:
|
|
295
|
+
The recovery code. Store it safely: it is the way back in if the authenticator is lost.
|
|
296
|
+
|
|
297
|
+
Raises:
|
|
298
|
+
ApiError: The code is wrong or expired.
|
|
299
|
+
"""
|
|
300
|
+
payload = {'key': setup.secret, 'token': code or totp_code(setup.secret).code, 'userVerificationToken': setup.verification_token}
|
|
301
|
+
await self.request('POST', '/api/two-factor/authenticator', json=payload)
|
|
302
|
+
recovery = await self.two_factor_recovery_code(password)
|
|
303
|
+
if not recovery:
|
|
304
|
+
raise ApiError(500, 'authenticator enabled but the server returned no recovery code')
|
|
305
|
+
return recovery
|
|
306
|
+
|
|
307
|
+
async def disable_totp(self, password: str) -> None:
|
|
308
|
+
"""Turn the authenticator off. Does nothing if none is enabled.
|
|
309
|
+
|
|
310
|
+
Args:
|
|
311
|
+
password: The master password.
|
|
312
|
+
|
|
313
|
+
Raises:
|
|
314
|
+
ApiError: Wrong password.
|
|
315
|
+
"""
|
|
316
|
+
body = JsonObject(await self.request('POST', '/api/two-factor/get-authenticator', json={'masterPasswordHash': await self._password_hash(password)}))
|
|
317
|
+
authenticator = body.obj('authenticator')
|
|
318
|
+
if authenticator is None or not authenticator.get_bool('enabled'):
|
|
319
|
+
return
|
|
320
|
+
payload = {'key': authenticator.get_str('key'), 'userVerificationToken': body.get_str('userVerificationToken')}
|
|
321
|
+
await self.request('DELETE', '/api/two-factor/authenticator', json=payload)
|
|
322
|
+
|
|
323
|
+
async def two_factor_recovery_code(self, password: str) -> str | None:
|
|
324
|
+
"""Read the two-step login recovery code.
|
|
325
|
+
|
|
326
|
+
Args:
|
|
327
|
+
password: The master password.
|
|
328
|
+
|
|
329
|
+
Returns:
|
|
330
|
+
The recovery code, or None if no two-step method is enabled.
|
|
331
|
+
|
|
332
|
+
Raises:
|
|
333
|
+
ApiError: Wrong password.
|
|
334
|
+
"""
|
|
335
|
+
body = JsonObject(await self.request('POST', '/api/two-factor/get-recover', json={'masterPasswordHash': await self._password_hash(password)}))
|
|
336
|
+
return body.get_str('code')
|
|
337
|
+
|
|
338
|
+
# ------------------------------------------------------------ devices and sessions
|
|
339
|
+
|
|
340
|
+
async def devices(self) -> list[KnownDevice]:
|
|
341
|
+
"""The devices (clients) that have logged in to the account.
|
|
342
|
+
|
|
343
|
+
Returns:
|
|
344
|
+
One entry per device, including this client.
|
|
345
|
+
"""
|
|
346
|
+
body = JsonObject(await self.request('GET', '/api/devices'))
|
|
347
|
+
return [
|
|
348
|
+
KnownDevice(
|
|
349
|
+
id=d.get_str('id') or '',
|
|
350
|
+
name=d.get_str('name'),
|
|
351
|
+
type=d.get_int('type'),
|
|
352
|
+
identifier=d.get_str('identifier'),
|
|
353
|
+
creation_date=d.get_datetime('creationDate'),
|
|
354
|
+
raw=d.raw,
|
|
355
|
+
)
|
|
356
|
+
for d in body.objs('data')
|
|
357
|
+
]
|
|
358
|
+
|
|
359
|
+
async def deauthorize_sessions(self, password: str, *, relogin: bool = True) -> None:
|
|
360
|
+
"""Log out every device, including this one.
|
|
361
|
+
|
|
362
|
+
The server issues a new security stamp, so all existing sessions end, and removes all devices from the
|
|
363
|
+
account's device list.
|
|
364
|
+
|
|
365
|
+
Args:
|
|
366
|
+
password: The master password.
|
|
367
|
+
relogin: Log this client in again afterwards. Accounts with two-step login cannot do that without a code:
|
|
368
|
+
pass False and log in yourself.
|
|
369
|
+
|
|
370
|
+
Raises:
|
|
371
|
+
ApiError: Wrong password; nothing was changed.
|
|
372
|
+
TwoFactorRequiredError: ``relogin`` is True but the account needs a second factor.
|
|
373
|
+
"""
|
|
374
|
+
email = await self._email()
|
|
375
|
+
await self.request('POST', '/api/accounts/security-stamp', json={'masterPasswordHash': await self._password_hash(password)})
|
|
376
|
+
if relogin:
|
|
377
|
+
await self.login_password(email, password)
|
|
378
|
+
else:
|
|
379
|
+
self.logout()
|