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.
@@ -0,0 +1,218 @@
1
+ """Registration and login."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from vaultwarden2 import _core, _offload, crypto
6
+ from vaultwarden2._json import JsonObject
7
+ from vaultwarden2.crypto import KdfParams
8
+ from vaultwarden2.errors import ApiError, AuthenticationError, VaultwardenError
9
+ from vaultwarden2.models import TwoFactorProvider
10
+
11
+ from . import base as _base_mod
12
+ from .base import _body
13
+
14
+
15
+ class AsyncAuthMixin(_base_mod.AsyncClientBase):
16
+ """Registration, the two login methods and the personal API key."""
17
+
18
+ async def register(
19
+ self,
20
+ email: str,
21
+ password: str,
22
+ *,
23
+ name: str | None = None,
24
+ hint: str | None = None,
25
+ kdf: KdfParams | None = None,
26
+ ) -> None:
27
+ """Create a new account.
28
+
29
+ The user key and the RSA key pair are generated on this machine; the server only receives them encrypted
30
+ with the master key, plus the authentication hash of the master password. The client is not logged in
31
+ afterwards: call [login_password][vaultwarden2.AsyncVaultwardenClient.login_password].
32
+
33
+ Works when the server allows the sign-up and does not send verification mails:
34
+
35
+ * sign-up allowed: ``SIGNUPS_ALLOWED=true``, or the email's domain is in ``SIGNUPS_DOMAINS_WHITELIST`` (which
36
+ then overrides ``SIGNUPS_ALLOWED``), or the email was invited on a server that sends no emails
37
+ (neither ``SMTP_HOST`` nor ``USE_SENDMAIL`` configured);
38
+ * no verification email: the server sends no emails, or ``SIGNUPS_VERIFY=false``.
39
+
40
+ Args:
41
+ email: Email address of the new account. Leading/trailing spaces are removed and it is lowercased,
42
+ as in the official apps (it is also the KDF salt).
43
+ password: The master password. It never leaves this machine.
44
+ name: Display name of the account.
45
+ hint: Master password hint, shown on request to whoever knows the email. Leave empty if unsure.
46
+ kdf: Key derivation settings. Defaults to PBKDF2-SHA256 with 600000 iterations (the default of vaultwarden
47
+ and the official apps); ``KdfParams.argon2id()`` uses Argon2id with the official apps' defaults.
48
+
49
+ Raises:
50
+ CryptoError: ``kdf`` is outside the supported range (see ``change_kdf``); nothing was sent.
51
+ VaultwardenError: The server requires email verification; finish the registration from the mailed link.
52
+ ApiError: The server refused the registration (sign-ups disabled, email already in use, invalid settings).
53
+ RateLimitError: Too many requests.
54
+
55
+ Example:
56
+ ```python
57
+ await vw.register('me@example.org', master_password, name='Me', kdf=KdfParams.argon2id())
58
+ await vw.login_password('me@example.org', master_password)
59
+ ```
60
+ """
61
+ response = await self._http.post(
62
+ '/identity/accounts/register/send-verification-email',
63
+ json={'email': crypto.normalize_email(email), 'name': name},
64
+ headers=self._headers(Accept='application/json'),
65
+ )
66
+ body = _body(response)
67
+ _core.raise_for_status(response.status_code, body)
68
+ if not isinstance(body, str) or not body:
69
+ raise VaultwardenError('the server requires email verification; finish the registration from the emailed link')
70
+ payload = await _offload.arun_cpu(_core.register_payload, email, password, kdf or KdfParams.pbkdf2(), body, hint)
71
+ response = await self._http.post('/identity/accounts/register/finish', json=payload, headers=self._headers())
72
+ _core.raise_for_status(response.status_code, _body(response))
73
+
74
+ async def login_password(
75
+ self,
76
+ email: str,
77
+ password: str,
78
+ *,
79
+ two_factor_token: str | None = None,
80
+ two_factor_provider: int | None = None,
81
+ two_factor_remember: bool = False,
82
+ ) -> None:
83
+ """Log in with email and master password, and unlock the vault.
84
+
85
+ The master key is derived locally from the password with the account's KDF settings; the server only
86
+ receives an authentication hash, never the password. On success, decrypted items are available right away.
87
+
88
+ Accounts with two-step login first raise [TwoFactorRequiredError][vaultwarden2.TwoFactorRequiredError];
89
+ call again with ``two_factor_token`` (and ``two_factor_provider``).
90
+
91
+ Args:
92
+ email: The account's email address (case and surrounding spaces do not matter).
93
+ password: The master password.
94
+ two_factor_token: The code from the second factor, for example the 6 digits of an authenticator app.
95
+ two_factor_provider: Which second factor ``two_factor_token`` comes from, see
96
+ [TwoFactorProvider][vaultwarden2.models.TwoFactorProvider]. Defaults to the authenticator app.
97
+ two_factor_remember: Ask the server for a "remember this device" token, available afterwards as
98
+ [two_factor_remember_token][vaultwarden2.AsyncVaultwardenClient.two_factor_remember_token]; later logins from
99
+ the same device can pass it instead of a code.
100
+
101
+ Raises:
102
+ TwoFactorRequiredError: The account needs a second factor; ``error.providers`` lists the offered methods.
103
+ AuthenticationError: Wrong email, password or code, or the account is disabled.
104
+ CryptoError: The server announced unsafe KDF settings, so no key was derived.
105
+ RateLimitError: Too many login attempts; wait before retrying.
106
+
107
+ Example:
108
+ ```python
109
+ try:
110
+ await vw.login_password(email, password)
111
+ except TwoFactorRequiredError:
112
+ await vw.login_password(email, password, two_factor_token=input('code: '))
113
+ ```
114
+ """
115
+ kdf = await self.prelogin(email)
116
+ master_key = await _offload.arun_cpu(crypto.make_master_key, password, email, kdf)
117
+ form = _core.token_form_password(
118
+ email,
119
+ crypto.master_password_hash(master_key, password),
120
+ self.device,
121
+ two_factor_token=two_factor_token,
122
+ two_factor_provider=two_factor_provider,
123
+ two_factor_remember=two_factor_remember,
124
+ )
125
+ self.logout()
126
+ token = await self._token_request(form)
127
+ await self._unlock(token, master_key)
128
+ self._two_factor_remember_token = token.data.get_str('TwoFactorToken')
129
+
130
+ async def login_api_key(self, client_id: str, client_secret: str, password: str) -> None:
131
+ """Log in with the personal API key, and unlock the vault with the master password.
132
+
133
+ The API key replaces email and password for authentication only (useful for automation and accounts with
134
+ two-step login, which the API key bypasses). Decrypting the vault still needs the master password. The
135
+ credentials are kept in memory so the session can be renewed without a refresh token.
136
+
137
+ Args:
138
+ client_id: The ``client_id`` of the personal API key (``user.<uuid>``), see
139
+ [get_api_key][vaultwarden2.AsyncVaultwardenClient.get_api_key].
140
+ client_secret: The ``client_secret`` of the personal API key.
141
+ password: The master password, needed to unlock the vault.
142
+
143
+ Raises:
144
+ AuthenticationError: Wrong API key or master password.
145
+ CryptoError: The server announced unsafe KDF settings, so no key was derived.
146
+ RateLimitError: Too many login attempts.
147
+
148
+ Example:
149
+ ```python
150
+ await vw.login_api_key(os.environ['BW_CLIENTID'], os.environ['BW_CLIENTSECRET'], master_password)
151
+ ```
152
+ """
153
+ self.logout()
154
+ token = await self._token_request(_core.token_form_api_key(client_id, client_secret, self.device))
155
+ self._api_key = (client_id, client_secret)
156
+ kdf_salt = _core.kdf_and_salt_from_token(token.data)
157
+ if kdf_salt is None:
158
+ email = (await self._load_profile()).get_str('email') or ''
159
+ kdf_salt = (await self.prelogin(email), email)
160
+ kdf, salt = kdf_salt
161
+ await self._unlock(token, await _offload.arun_cpu(crypto.make_master_key, password, salt, kdf))
162
+
163
+ async def _unlock(self, token: _core.TokenResponse, master_key: bytes) -> None:
164
+ """Unwrap the user key and private key from a token response and load the organization keys.
165
+
166
+ Args:
167
+ token: The successful token response (carries the protected user key and private key).
168
+ master_key: The master key derived from the master password.
169
+
170
+ Raises:
171
+ AuthenticationError: The keys cannot be unwrapped (wrong master password); the session is discarded.
172
+ """
173
+ try:
174
+ self._keys = _core.unlock(master_key, token.data.get_str('Key'), token.data.get_str('PrivateKey'))
175
+ except AuthenticationError:
176
+ self.logout()
177
+ raise
178
+ _core.load_org_keys(await self._load_profile(), self._keys)
179
+
180
+ async def login_with_recovery_code(self, email: str, password: str, recovery_code: str) -> None:
181
+ """Log in with the two-step login recovery code, for example after losing the authenticator.
182
+
183
+ The server then turns off all two-step login methods of the account and forgets all remembered devices; set
184
+ two-step login up again afterwards. Organizations that require two-step login revoke the account's
185
+ membership, as for any account without two-step login.
186
+
187
+ Args:
188
+ email: The account's email address.
189
+ password: The master password.
190
+ recovery_code: The recovery code shown when two-step login was set up
191
+ (see [two_factor_recovery_code][vaultwarden2.AsyncVaultwardenClient.two_factor_recovery_code]).
192
+
193
+ Raises:
194
+ AuthenticationError: Wrong email, password or recovery code.
195
+ """
196
+ await self.login_password(email, password, two_factor_token=recovery_code, two_factor_provider=TwoFactorProvider.RECOVERY_CODE)
197
+
198
+ async def get_api_key(self, password: str) -> tuple[str, str]:
199
+ """Read the personal API key of the logged-in account.
200
+
201
+ The secret does not change by reading it; use
202
+ [rotate_api_key][vaultwarden2.AsyncVaultwardenClient.rotate_api_key] to replace it.
203
+
204
+ Args:
205
+ password: The master password (the server re-checks it before revealing the key).
206
+
207
+ Returns:
208
+ ``(client_id, client_secret)`` for [login_api_key][vaultwarden2.AsyncVaultwardenClient.login_api_key].
209
+
210
+ Raises:
211
+ ApiError: Wrong master password, or the server returned no key.
212
+ """
213
+ profile = self._profile or await self._load_profile()
214
+ body = JsonObject(await self.request('POST', '/api/accounts/api-key', json={'masterPasswordHash': await self._password_hash(password)}))
215
+ secret = body.get_str('apiKey')
216
+ if not secret:
217
+ raise ApiError(500, 'server returned no apiKey')
218
+ return f'user.{profile.get_str("id")}', secret
@@ -0,0 +1,462 @@
1
+ """Client core shared by every part of the client: HTTP transport, sessions and tokens, unlocked keys.
2
+
3
+ ``vaultwarden2._async`` holds the source; ``vaultwarden2._sync`` is generated from it by unasyncd.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ import time
9
+ import warnings
10
+ from typing import TYPE_CHECKING, Any, Self
11
+
12
+ import httpx2
13
+
14
+ from vaultwarden2 import _core, _offload, crypto
15
+ from vaultwarden2._core import Device, UserKeys
16
+ from vaultwarden2._json import JsonObject
17
+ from vaultwarden2.errors import AuthenticationError, InsecureTransportWarning, NotUnlockedError
18
+ from vaultwarden2.models import (
19
+ Cipher,
20
+ CollectionAccess,
21
+ )
22
+
23
+ if TYPE_CHECKING:
24
+ from types import TracebackType
25
+
26
+ from vaultwarden2.crypto import KdfParams, SymmetricKey
27
+ from vaultwarden2.models import CollectionRef, ItemRef
28
+
29
+
30
+ DEFAULT_TIMEOUT = 30.0
31
+
32
+
33
+ def _body(response: httpx2.Response) -> Any:
34
+ """Decode a response body.
35
+
36
+ Args:
37
+ response: The HTTP response.
38
+
39
+ Returns:
40
+ The decoded JSON value, the text for non-JSON bodies, or None for an empty body.
41
+ """
42
+ if not response.content:
43
+ return None
44
+ try:
45
+ return response.json()
46
+ except ValueError:
47
+ return response.text
48
+
49
+
50
+ class AsyncClientBase:
51
+ """HTTP plumbing, session handling and unlocked key state shared by all parts of the client.
52
+
53
+ Not used directly: [AsyncVaultwardenClient][vaultwarden2.AsyncVaultwardenClient] combines it with the feature
54
+ mixins.
55
+
56
+ Args:
57
+ base_url: Address of the server, for example ``https://vault.example.org``. A trailing slash is ignored.
58
+ Plain ``http://`` to anything but localhost triggers an
59
+ [InsecureTransportWarning][vaultwarden2.InsecureTransportWarning].
60
+ timeout: Timeout for every HTTP request, in seconds.
61
+ verify: Verify the server's TLS certificate (passed to httpx2). Only disable for local testing.
62
+ device: How this client appears in the account's device list. Pass the same
63
+ [Device][vaultwarden2.Device] (same ``identifier``) on every run so repeated runs count as one device
64
+ and do not trigger "new device" notifications. Defaults to a new random device.
65
+ http_client: A preconfigured httpx2 client, for example with a proxy or a custom transport. Its
66
+ ``base_url`` must point at the server. It is closed together with this client. Defaults to a new client
67
+ built from ``base_url``, ``timeout`` and ``verify``.
68
+ """
69
+
70
+ def __init__(
71
+ self,
72
+ base_url: str,
73
+ *,
74
+ timeout: float = DEFAULT_TIMEOUT,
75
+ verify: bool = True,
76
+ device: Device | None = None,
77
+ http_client: httpx2.AsyncClient | None = None,
78
+ ) -> None:
79
+ self.base_url = base_url.rstrip('/')
80
+ _warn_if_plaintext(self.base_url)
81
+ self.device = device or Device()
82
+ self._http = http_client or httpx2.AsyncClient(base_url=self.base_url, timeout=timeout, verify=verify)
83
+ self._access_token: str | None = None
84
+ self._refresh_token: str | None = None
85
+ self._expires_at = 0.0
86
+ self._api_key: tuple[str, str] | None = None
87
+ self._keys: UserKeys | None = None
88
+ self._profile: JsonObject | None = None
89
+ self._two_factor_remember_token: str | None = None
90
+ self._refresh_lock = _offload.new_async_lock()
91
+
92
+ async def close(self) -> None:
93
+ """Close the connection pool. The client cannot be used afterwards."""
94
+ await self._http.aclose()
95
+
96
+ async def __aenter__(self) -> Self:
97
+ """Use the client as a context manager that closes it on exit.
98
+
99
+ Returns:
100
+ The client itself.
101
+ """
102
+ return self
103
+
104
+ async def __aexit__(
105
+ self,
106
+ exc_type: type[BaseException] | None,
107
+ exc: BaseException | None,
108
+ tb: TracebackType | None,
109
+ ) -> None:
110
+ """Close the client when leaving the ``with`` block.
111
+
112
+ Args:
113
+ exc_type: Type of the exception that ended the block, if any.
114
+ exc: The exception that ended the block, if any.
115
+ tb: Its traceback, if any.
116
+ """
117
+ await self.close()
118
+
119
+ @property
120
+ def is_authenticated(self) -> bool:
121
+ """Whether the client has logged in (the access token may still need a refresh).
122
+
123
+ Returns:
124
+ True after a successful login, False before and after [logout][vaultwarden2.AsyncVaultwardenClient.logout].
125
+ """
126
+ return self._access_token is not None
127
+
128
+ @property
129
+ def is_unlocked(self) -> bool:
130
+ """Whether the vault keys are available, so items can be decrypted and encrypted.
131
+
132
+ Returns:
133
+ True after a successful login, False before and after logout.
134
+ """
135
+ return self._keys is not None
136
+
137
+ def logout(self) -> None:
138
+ """Forget tokens and keys locally.
139
+
140
+ Nothing is sent to the server; the device stays registered on the account. Log in again to continue.
141
+ """
142
+ self._access_token = self._refresh_token = None
143
+ self._expires_at = 0.0
144
+ self._api_key = None
145
+ self._keys = None
146
+ self._profile = None
147
+ self._two_factor_remember_token = None
148
+
149
+ @property
150
+ def two_factor_remember_token(self) -> str | None:
151
+ """The "remember this device" token from the last two-step login with ``two_factor_remember=True``.
152
+
153
+ Store it securely and pass it on later logins as ``two_factor_token`` with
154
+ ``two_factor_provider=TwoFactorProvider.REMEMBER`` to skip the second factor. The server only accepts it
155
+ from the same device: use the same [Device][vaultwarden2.Device] identifier. It is reset by ``logout()``,
156
+ replaced by every new remembered login, and not issued when the server disables the feature
157
+ (``DISABLE_2FA_REMEMBER``) or the login used no second factor.
158
+
159
+ Returns:
160
+ The token, or None.
161
+ """
162
+ return self._two_factor_remember_token
163
+
164
+ def _require_keys(self) -> UserKeys:
165
+ """Return the unlocked keys or fail.
166
+
167
+ Returns:
168
+ The session's key material.
169
+
170
+ Raises:
171
+ NotUnlockedError: Nobody is logged in.
172
+ """
173
+ if self._keys is None:
174
+ raise NotUnlockedError('log in first')
175
+ return self._keys
176
+
177
+ def _headers(self, **extra: str) -> dict[str, str]:
178
+ """Headers sent with every request.
179
+
180
+ Args:
181
+ **extra: Additional headers for this request.
182
+
183
+ Returns:
184
+ The client version and device type headers, plus ``extra``.
185
+ """
186
+ return {'Bitwarden-Client-Version': _core.CLIENT_VERSION, 'Device-Type': str(self.device.type), **extra}
187
+
188
+ async def _token_request(self, form: dict[str, str]) -> _core.TokenResponse:
189
+ """Call the token endpoint and store the new tokens.
190
+
191
+ Args:
192
+ form: The form fields for the grant (password, API key or refresh token).
193
+
194
+ Returns:
195
+ The parsed token response.
196
+ """
197
+ response = await self._http.post('/identity/connect/token', data=form, headers=self._headers(Accept='application/json'))
198
+ token = _core.parse_token_response(response.status_code, _body(response))
199
+ self._access_token = token.access_token
200
+ self._refresh_token = token.refresh_token or self._refresh_token
201
+ self._expires_at = time.monotonic() + token.expires_in
202
+ return token
203
+
204
+ def _token_expiring(self) -> bool:
205
+ """Whether the access token expires within the refresh margin.
206
+
207
+ Returns:
208
+ True if a refresh is due.
209
+ """
210
+ return time.monotonic() >= self._expires_at - _core.TOKEN_REFRESH_MARGIN
211
+
212
+ async def _ensure_token(self) -> str:
213
+ """Return a valid access token, refreshing it first if it is about to expire.
214
+
215
+ Concurrent callers share one refresh.
216
+
217
+ Returns:
218
+ The access token.
219
+
220
+ Raises:
221
+ NotUnlockedError: Nobody is logged in.
222
+ """
223
+ if self._access_token is None:
224
+ raise NotUnlockedError('log in first')
225
+ if self._token_expiring():
226
+ async with self._refresh_lock:
227
+ # Concurrent callers wait here; only the first one refreshes, the others reuse its token.
228
+ if self._token_expiring():
229
+ await self._refresh_unlocked()
230
+ if self._access_token is None: # pragma: no cover - refresh raises instead
231
+ raise NotUnlockedError('log in first')
232
+ return self._access_token
233
+
234
+ async def request(self, method: str, path: str, *, json: Any = None, params: dict[str, Any] | None = None, files: Any = None) -> Any:
235
+ """Send an authenticated request to any API endpoint and return the decoded response.
236
+
237
+ An escape hatch for endpoints this library does not wrap yet. The access token is refreshed when needed;
238
+ if the server rejects it (HTTP 401), it is refreshed once and the request is sent again, unless ``files``
239
+ holds streams that cannot be read twice.
240
+
241
+ Args:
242
+ method: HTTP method, for example ``'GET'`` or ``'PUT'``.
243
+ path: Path below the server address, for example ``'/api/folders'``.
244
+ json: Request body, sent as JSON.
245
+ params: Query parameters.
246
+ files: Multipart files, in the format httpx2 accepts.
247
+
248
+ Returns:
249
+ The decoded JSON body, the text for non-JSON responses, or None for an empty response.
250
+
251
+ Raises:
252
+ NotUnlockedError: Nobody is logged in.
253
+ AuthenticationError: The session was rejected and could not be renewed.
254
+ RateLimitError: The server answered HTTP 429.
255
+ ApiError: Any other non-2xx answer.
256
+ """
257
+ token = await self._ensure_token()
258
+ response = await self._http.request(method, path, json=json, params=params, files=files, headers=self._headers(Authorization=f'Bearer {token}'))
259
+ if response.status_code == httpx2.codes.UNAUTHORIZED and (self._refresh_token or self._api_key) and _replayable(files):
260
+ async with self._refresh_lock:
261
+ if self._access_token == token: # nobody else refreshed in the meantime
262
+ await self._refresh_unlocked()
263
+ token = self._access_token or token
264
+ response = await self._http.request(method, path, json=json, params=params, files=files, headers=self._headers(Authorization=f'Bearer {token}'))
265
+ body = _body(response)
266
+ _core.raise_for_status(response.status_code, body)
267
+ return body
268
+
269
+ async def alive(self) -> bool:
270
+ """Check whether the server is up (``/alive``). Needs no login.
271
+
272
+ Returns:
273
+ True if the server answered the health check.
274
+ """
275
+ response = await self._http.get('/alive')
276
+ return response.status_code == httpx2.codes.OK
277
+
278
+ async def server_version(self) -> str | None:
279
+ """The vaultwarden version of the server. Needs no login.
280
+
281
+ Returns:
282
+ The version string, for example ``'1.37.5'``, or None if the server did not report one.
283
+ """
284
+ response = await self._http.get('/api/version')
285
+ body = _body(response)
286
+ return body if response.status_code == httpx2.codes.OK and isinstance(body, str) else None
287
+
288
+ async def prelogin(self, email: str) -> KdfParams:
289
+ """Look up the key derivation settings of an account. Needs no login.
290
+
291
+ For unknown emails the server answers with plausible decoy settings, so this cannot be used to find out
292
+ whether an account exists.
293
+
294
+ Args:
295
+ email: The account's email address.
296
+
297
+ Returns:
298
+ The KDF settings the account uses.
299
+
300
+ Raises:
301
+ CryptoError: The server announced settings outside the safe bounds of the official apps.
302
+ ApiError: The server rejected the request.
303
+ """
304
+ response = await self._http.post('/identity/accounts/prelogin', json={'email': crypto.normalize_email(email)}, headers=self._headers())
305
+ body = _body(response)
306
+ _core.raise_for_status(response.status_code, body)
307
+ return _core.parse_kdf(JsonObject(body))
308
+
309
+ async def _load_profile(self) -> JsonObject:
310
+ """Fetch the account profile and cache it.
311
+
312
+ Returns:
313
+ The profile JSON.
314
+ """
315
+ self._profile = JsonObject(await self.request('GET', '/api/accounts/profile'))
316
+ return self._profile
317
+
318
+ async def refresh(self) -> None:
319
+ """Renew the access token now.
320
+
321
+ Uses the refresh token, or the stored API key credentials after an API key login. Requests refresh
322
+ automatically shortly before expiry, so calling this is rarely needed.
323
+
324
+ Raises:
325
+ AuthenticationError: The session cannot be renewed; log in again.
326
+ """
327
+ async with self._refresh_lock:
328
+ await self._refresh_unlocked()
329
+
330
+ async def _refresh_unlocked(self) -> None:
331
+ """Renew the access token; the caller holds the refresh lock.
332
+
333
+ Raises:
334
+ AuthenticationError: Neither the refresh token nor stored API key credentials work.
335
+ """
336
+ if self._refresh_token:
337
+ try:
338
+ await self._token_request(_core.token_form_refresh(self._refresh_token))
339
+ except AuthenticationError:
340
+ if self._api_key is None:
341
+ raise
342
+ else:
343
+ return
344
+ if self._api_key is None:
345
+ raise AuthenticationError('session expired and cannot be refreshed; log in again')
346
+ await self._token_request(_core.token_form_api_key(*self._api_key, self.device))
347
+
348
+ async def _password_hash(self, password: str) -> str:
349
+ """Compute the server authentication hash of the master password, for endpoints that re-verify it.
350
+
351
+ Args:
352
+ password: The master password.
353
+
354
+ Returns:
355
+ The base64 authentication hash.
356
+ """
357
+ profile = self._profile or await self._load_profile()
358
+ email = profile.get_str('email') or ''
359
+ master_key = await _offload.arun_cpu(crypto.make_master_key, password, email, await self.prelogin(email))
360
+ return crypto.master_password_hash(master_key, password)
361
+
362
+ def _user_id(self) -> str:
363
+ """The id of the logged-in user.
364
+
365
+ Returns:
366
+ The user id.
367
+
368
+ Raises:
369
+ NotUnlockedError: Nobody is logged in.
370
+ """
371
+ user_id = self._profile.get_str('id') if self._profile else None
372
+ if not user_id:
373
+ raise NotUnlockedError('log in first')
374
+ return user_id
375
+
376
+ def _org_key(self, org_id: str) -> SymmetricKey:
377
+ """The key of an organization the user is a confirmed member of.
378
+
379
+ Args:
380
+ org_id: The organization id.
381
+
382
+ Returns:
383
+ The organization key.
384
+
385
+ Raises:
386
+ NotUnlockedError: The key is not available (not logged in, or the membership is not confirmed yet).
387
+ """
388
+ keys = self._require_keys()
389
+ if org_id not in keys.org_keys:
390
+ raise NotUnlockedError(f'no key for organization {org_id} (membership not confirmed yet?)')
391
+ return keys.org_keys[org_id]
392
+
393
+
394
+ def _warn_if_plaintext(base_url: str) -> None:
395
+ """Warn when credentials would travel over plain HTTP to a non-local server.
396
+
397
+ Args:
398
+ base_url: The server address.
399
+ """
400
+ url = httpx2.URL(base_url)
401
+ if url.scheme == 'http' and url.host not in {'localhost', '127.0.0.1', '::1'} and not url.host.endswith('.localhost'):
402
+ warnings.warn(f'{base_url} uses plain HTTP; use HTTPS for anything but local testing', InsecureTransportWarning, stacklevel=3)
403
+
404
+
405
+ def _replayable(files: Any) -> bool:
406
+ """Whether a multipart ``files`` argument can be sent twice.
407
+
408
+ httpx accepts a dict or a list of ``(field, value)`` pairs; ``value`` is the content or a
409
+ ``(filename, content[, content_type[, headers]])`` tuple. File objects are consumed by the first send.
410
+
411
+ Args:
412
+ files: The ``files`` argument of a request, or None.
413
+
414
+ Returns:
415
+ True if every content is in-memory ``bytes`` or ``str`` (or there are no files).
416
+ """
417
+ if files is None:
418
+ return True
419
+ pairs = files.items() if isinstance(files, dict) else files
420
+ for _field, value in pairs:
421
+ content = value[1] if isinstance(value, tuple) else value
422
+ if not isinstance(content, bytes | str):
423
+ return False
424
+ return True
425
+
426
+
427
+ def _item_id(item: ItemRef) -> str:
428
+ """The id of an item given as object or id.
429
+
430
+ Args:
431
+ item: An item or its id.
432
+
433
+ Returns:
434
+ The item id.
435
+ """
436
+ return item.id if isinstance(item, Cipher) else item
437
+
438
+
439
+ def _collection_id(collection: CollectionRef) -> str:
440
+ """The id of a collection given as object, access entry or id.
441
+
442
+ Args:
443
+ collection: A collection, a collection access entry or a collection id.
444
+
445
+ Returns:
446
+ The collection id.
447
+ """
448
+ return collection if isinstance(collection, str) else collection.id
449
+
450
+
451
+ def _collection_access(collection: CollectionRef) -> CollectionAccess:
452
+ """A collection access entry with default rights for a collection reference.
453
+
454
+ Args:
455
+ collection: A collection, an access entry (returned unchanged) or a collection id.
456
+
457
+ Returns:
458
+ The access entry.
459
+ """
460
+ if isinstance(collection, CollectionAccess):
461
+ return collection
462
+ return CollectionAccess(id=_collection_id(collection))