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,970 @@
1
+ """Personal vault: items, folders, attachments."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ from dataclasses import replace
7
+ from typing import TYPE_CHECKING
8
+
9
+ from vaultwarden2 import _core, _encode, _merge, _offload, crypto
10
+ from vaultwarden2 import search as _search
11
+ from vaultwarden2._json import JsonObject
12
+ from vaultwarden2.crypto import SymmetricKey
13
+ from vaultwarden2.errors import ApiError, UnsafeWriteError, VaultwardenError
14
+ from vaultwarden2.models import (
15
+ Attachment,
16
+ Card,
17
+ Cipher,
18
+ CipherType,
19
+ Collection,
20
+ CustomField,
21
+ FieldType,
22
+ Folder,
23
+ Identity,
24
+ Login,
25
+ LoginUri,
26
+ Organization,
27
+ RepromptType,
28
+ SshKey,
29
+ )
30
+
31
+ if TYPE_CHECKING:
32
+ from collections.abc import Callable, Mapping, Sequence
33
+
34
+ from vaultwarden2.models import CollectionRef, FolderRef, ItemRef, OrganizationRef, Profile, Vault
35
+
36
+ from . import account as _account_mod
37
+ from .base import _collection_id, _item_id
38
+
39
+
40
+ class AsyncVaultMixin(_account_mod.AsyncAccountMixin):
41
+ """Reading, searching and changing vault items, folders and attachments."""
42
+
43
+ async def profile(self) -> Profile:
44
+ """The logged-in account.
45
+
46
+ Returns:
47
+ The account profile (id, email, name, verification and premium state).
48
+ """
49
+ return _core.parse_profile(await self._load_profile())
50
+
51
+ async def sync(self, *, include_archived: bool = False) -> Vault:
52
+ """Fetch and decrypt the whole vault in one request.
53
+
54
+ Items that cannot be decrypted are skipped and listed in ``vault.undecryptable``; parts of items that cannot
55
+ be interpreted are listed in ``item.issues``. Both are reported on the ``vaultwarden2`` logger and as one
56
+ [VaultwardenDataWarning][vaultwarden2.VaultwardenDataWarning].
57
+
58
+ Args:
59
+ include_archived: Also return archived items. Items in the trash are always included
60
+ (see ``Cipher.is_deleted``).
61
+
62
+ Returns:
63
+ Profile, folders, items (personal and organization), collections and organizations.
64
+
65
+ Example:
66
+ ```python
67
+ vault = await vw.sync()
68
+ for item in vault.ciphers:
69
+ if item.login and not item.is_deleted:
70
+ print(item.name, item.login.username)
71
+ ```
72
+ """
73
+ keys = self._require_keys()
74
+ body = await self.request('GET', '/api/sync', params={'excludeDomains': 'true'})
75
+ vault = await _offload.arun_cpu(_core.decrypt_vault, body, keys)
76
+ self._profile = JsonObject(vault.profile.raw)
77
+ if include_archived:
78
+ return vault
79
+ return replace(vault, ciphers=tuple(c for c in vault.ciphers if not c.is_archived))
80
+
81
+ async def folders(self) -> list[Folder]:
82
+ """All folders, decrypted.
83
+
84
+ Returns:
85
+ The folders of the logged-in account.
86
+ """
87
+ keys = self._require_keys()
88
+ body = JsonObject(await self.request('GET', '/api/folders'))
89
+ return [_core.decrypt_folder(f.raw, keys) for f in body.objs('data')]
90
+
91
+ async def get_folder(self, folder_id: str) -> Folder:
92
+ """One folder, decrypted.
93
+
94
+ Args:
95
+ folder_id: The folder id.
96
+
97
+ Returns:
98
+ The folder.
99
+
100
+ Raises:
101
+ ApiError: No such folder.
102
+ """
103
+ return _core.decrypt_folder(await self.request('GET', f'/api/folders/{folder_id}'), self._require_keys())
104
+
105
+ async def ciphers(self, *, include_archived: bool = False) -> list[Cipher]:
106
+ """All items (personal and organization), decrypted.
107
+
108
+ Unlike [sync][vaultwarden2.AsyncVaultwardenClient.sync], an item that cannot be decrypted is an error here.
109
+
110
+ Args:
111
+ include_archived: Also return archived items.
112
+
113
+ Returns:
114
+ The items.
115
+
116
+ Raises:
117
+ CryptoError: An item cannot be decrypted.
118
+ """
119
+ keys = self._require_keys()
120
+ body = JsonObject(await self.request('GET', '/api/ciphers'))
121
+ items = await _offload.arun_cpu(_core.decrypt_ciphers, [c.raw for c in body.objs('data')], keys)
122
+ return items if include_archived else [c for c in items if not c.is_archived]
123
+
124
+ async def search(self, query: str, *, include_archived: bool = False, include_deleted: bool = False) -> list[Cipher]:
125
+ """Find items by text, locally (the server cannot search encrypted data).
126
+
127
+ Searches names, usernames, URIs, notes and custom field names, case-insensitively. Passwords and hidden
128
+ values are never searched. See [vaultwarden2.search.search][].
129
+
130
+ Args:
131
+ query: The text to look for.
132
+ include_archived: Also search archived items.
133
+ include_deleted: Also search items in the trash.
134
+
135
+ Returns:
136
+ The matching items, in vault order.
137
+ """
138
+ vault = await self.sync(include_archived=True)
139
+ return _search.search(vault.ciphers, query, include_archived=include_archived, include_deleted=include_deleted)
140
+
141
+ async def find_by_uri(self, url: str, *, mode: _search.SearchMode = 'host', include_archived: bool = False, include_deleted: bool = False) -> list[Cipher]:
142
+ """Find login items for a URL, locally. See [vaultwarden2.search.find_by_uri][].
143
+
144
+ Args:
145
+ url: The address to look up; the scheme is optional (``github.com`` works).
146
+ mode: ``'host'`` finds items with a URI on exactly the same host (and port). ``'autofill'`` applies each
147
+ stored URI's own match rule like browser autofill (base domain by default; needs the ``psl`` extra for
148
+ exact base-domain matching).
149
+ include_archived: Also return archived items.
150
+ include_deleted: Also return items in the trash.
151
+
152
+ Returns:
153
+ The matching login items.
154
+ """
155
+ vault = await self.sync(include_archived=True)
156
+ return _search.find_by_uri(vault.ciphers, url, mode=mode, include_archived=include_archived, include_deleted=include_deleted)
157
+
158
+ async def get_cipher(self, cipher_id: str) -> Cipher:
159
+ """One item, fresh from the server and decrypted.
160
+
161
+ Args:
162
+ cipher_id: The item id.
163
+
164
+ Returns:
165
+ The item.
166
+
167
+ Raises:
168
+ ApiError: No such item, or no access to it.
169
+ CryptoError: The item cannot be decrypted.
170
+ """
171
+ return _core.decrypt_cipher(await self.request('GET', f'/api/ciphers/{cipher_id}'), self._require_keys())
172
+
173
+ async def organizations(self) -> list[Organization]:
174
+ """The organizations the user is a member of.
175
+
176
+ Also refreshes the organization keys, so items of newly confirmed memberships can be decrypted.
177
+
178
+ Returns:
179
+ The memberships, with role and status.
180
+ """
181
+ profile = await self._load_profile()
182
+ _core.load_org_keys(profile, self._require_keys())
183
+ return [_core.parse_organization(o) for o in profile.objs('organizations')]
184
+
185
+ async def collections(self) -> list[Collection]:
186
+ """The collections the user can access, decrypted.
187
+
188
+ Returns:
189
+ The collections, across all organizations.
190
+ """
191
+ keys = self._require_keys()
192
+ body = JsonObject(await self.request('GET', '/api/collections'))
193
+ return [_core.decrypt_collection(c.raw, keys) for c in body.objs('data')]
194
+
195
+ async def _resolve_cipher(self, item: ItemRef) -> Cipher:
196
+ """The current server version of an item.
197
+
198
+ Args:
199
+ item: An item or its id.
200
+
201
+ Returns:
202
+ The item, fetched again from the server.
203
+ """
204
+ return await self.get_cipher(item.id if isinstance(item, Cipher) else item)
205
+
206
+ async def _resolve_folder(self, folder: FolderRef | None) -> str | None:
207
+ """Turn a folder reference into an id.
208
+
209
+ Args:
210
+ folder: A folder, its id, its unique name, or None.
211
+
212
+ Returns:
213
+ The folder id, or None for "no folder".
214
+
215
+ Raises:
216
+ VaultwardenError: No folder with that id or name, or the name is used by several folders.
217
+ """
218
+ if folder is None or isinstance(folder, Folder):
219
+ return folder.id if folder else None
220
+ folders = await self.folders()
221
+ if any(f.id == folder for f in folders):
222
+ return folder
223
+ matches = [f.id for f in folders if f.name == folder]
224
+ if len(matches) != 1:
225
+ raise VaultwardenError(f'folder {folder!r} not found' if not matches else f'folder name {folder!r} is ambiguous; pass the id')
226
+ return matches[0]
227
+
228
+ async def _resolve_organization(self, organization: OrganizationRef) -> str:
229
+ """Turn an organization reference into an id.
230
+
231
+ Args:
232
+ organization: An organization, its id or its unique name.
233
+
234
+ Returns:
235
+ The organization id.
236
+
237
+ Raises:
238
+ VaultwardenError: Not found, or the name is ambiguous.
239
+ """
240
+ if isinstance(organization, Organization):
241
+ return organization.id
242
+ orgs = await self.organizations()
243
+ if any(o.id == organization for o in orgs):
244
+ return organization
245
+ matches = [o.id for o in orgs if o.name == organization]
246
+ if len(matches) != 1:
247
+ raise VaultwardenError(f'organization {organization!r} not found' if not matches else f'organization name {organization!r} is ambiguous; pass the id')
248
+ return matches[0]
249
+
250
+ async def create_cipher(self, cipher: Cipher) -> Cipher:
251
+ """Create an item from a model.
252
+
253
+ The item gets its own random item key (as in the official clients). The encrypted payload is decrypted again
254
+ and checked before it is sent. For everyday cases the helpers such as
255
+ [create_login][vaultwarden2.AsyncVaultwardenClient.create_login] are simpler.
256
+
257
+ Args:
258
+ cipher: The item to create. Its ``id`` is ignored. For an organization item set ``organization_id`` and
259
+ ``collection_ids`` (at least one collection).
260
+
261
+ Returns:
262
+ The created item, decrypted, as stored on the server (with its id).
263
+
264
+ Raises:
265
+ UnsafeWriteError: The item carries data this library could not interpret (``cipher.issues``), or the
266
+ payload failed verification; nothing was sent.
267
+ ApiError: The server rejected the item.
268
+
269
+ Example:
270
+ ```python
271
+ from vaultwarden2.models import Cipher, CipherType, Login
272
+ item = await vw.create_cipher(Cipher(type=CipherType.LOGIN, name='GitHub', login=Login(username='alice')))
273
+ ```
274
+ """
275
+ keys = self._require_keys()
276
+ if cipher.issues:
277
+ raise UnsafeWriteError('the item contains data this library cannot interpret; refusing to copy it')
278
+ cipher = _merge.with_dated_history(cipher)
279
+ if not JsonObject(cipher.raw).get_str('key'): # own item key, like the official clients
280
+ cipher = replace(cipher, raw={**cipher.raw, 'key': _encode.new_item_key(cipher, keys)})
281
+ body = _encode.encode_cipher(cipher, keys, self._user_id())
282
+ for server_owned in ('id', 'lastKnownRevisionDate', 'revisionDate', 'creationDate', 'deletedDate'):
283
+ body.pop(server_owned, None)
284
+ await _offload.arun_cpu(_merge.verify_new, body, keys, cipher)
285
+ if cipher.organization_id:
286
+ result = await self.request('POST', '/api/ciphers/create', json={'cipher': body, 'collectionIds': list(cipher.collection_ids)})
287
+ else:
288
+ result = await self.request('POST', '/api/ciphers', json=body)
289
+ return _core.decrypt_cipher(result, keys)
290
+
291
+ async def update_cipher(self, cipher: Cipher, *, strict: bool = False) -> Cipher:
292
+ """Save changes to an item.
293
+
294
+ Start from an item read from the server (``get_cipher``, ``sync``, a create result) and change it with
295
+ ``dataclasses.replace``. The upload is built from the item's *current* server version: only the fields you
296
+ changed are re-encrypted, every other field keeps its exact ciphertext, and the payload is decrypted and
297
+ checked before it is sent. If the login password changed, the previous one goes to the password history.
298
+
299
+ Args:
300
+ cipher: The edited item.
301
+ strict: Refuse if the item changed on the server in any way since it was read. By default only a change
302
+ to one of the same fields counts as a conflict.
303
+
304
+ Returns:
305
+ The saved item, decrypted. If nothing changed, nothing is sent and the current server version is returned.
306
+
307
+ Raises:
308
+ ConflictError: The item changed on the server in a conflicting way (``strict``: in any way); re-read and
309
+ retry. Nothing was sent.
310
+ UnsafeWriteError: The change would overwrite data this library cannot interpret, would change ``id``,
311
+ ``type`` or ``organization_id``, the item was not read from the server, or verification failed.
312
+ Nothing was sent.
313
+ ApiError: The server rejected the update.
314
+
315
+ Example:
316
+ ```python
317
+ from dataclasses import replace
318
+ item = await vw.get_cipher(item_id)
319
+ item = await vw.update_cipher(replace(item, notes='rotated on 2026-11-28'))
320
+ ```
321
+ """
322
+ if not cipher.id:
323
+ raise VaultwardenError('cipher has no id; use create_cipher() for new items')
324
+ keys = self._require_keys()
325
+ current = await self.request('GET', f'/api/ciphers/{cipher.id}')
326
+ body = await _offload.arun_cpu(functools.partial(_merge.plan_update, strict=strict), cipher, current, keys, self._user_id())
327
+ if body is None:
328
+ return _core.decrypt_cipher(current, keys)
329
+ return _core.decrypt_cipher(await self.request('PUT', f'/api/ciphers/{cipher.id}', json=body), keys)
330
+
331
+ async def _partial_update(self, item: ItemRef, *, folder_id: str | None, favorite: bool | None) -> Cipher:
332
+ """Change folder and favorite without re-encrypting anything (works for read-only organization items too).
333
+
334
+ Args:
335
+ item: An item or its id.
336
+ folder_id: The new folder id, or None to keep the current folder.
337
+ favorite: The new favorite flag, or None to keep it.
338
+
339
+ Returns:
340
+ The updated item.
341
+ """
342
+ current = await self._resolve_cipher(item)
343
+ body = {
344
+ 'folderId': folder_id if folder_id is not None else current.folder_id,
345
+ 'favorite': favorite if favorite is not None else current.favorite,
346
+ }
347
+ return _core.decrypt_cipher(await self.request('PUT', f'/api/ciphers/{current.id}/partial', json=body), self._require_keys())
348
+
349
+ async def trash(self, item: ItemRef) -> None:
350
+ """Move an item to the trash. It can be restored with [restore][vaultwarden2.AsyncVaultwardenClient.restore].
351
+
352
+ Args:
353
+ item: The item, as object or id.
354
+
355
+ Raises:
356
+ ApiError: No such item, or no permission to delete it.
357
+ """
358
+ await self.request('PUT', f'/api/ciphers/{_item_id(item)}/delete')
359
+
360
+ async def restore(self, item: ItemRef) -> Cipher:
361
+ """Restore an item from the trash.
362
+
363
+ Args:
364
+ item: The item, as object or id.
365
+
366
+ Returns:
367
+ The restored item.
368
+
369
+ Raises:
370
+ ApiError: No such item in the trash.
371
+ """
372
+ return _core.decrypt_cipher(await self.request('PUT', f'/api/ciphers/{_item_id(item)}/restore'), self._require_keys())
373
+
374
+ async def delete(self, item: ItemRef) -> None:
375
+ """Delete an item permanently, without the trash. This cannot be undone.
376
+
377
+ Args:
378
+ item: The item, as object or id.
379
+
380
+ Raises:
381
+ ApiError: No such item, or no permission to delete it.
382
+ """
383
+ await self.request('DELETE', f'/api/ciphers/{_item_id(item)}')
384
+
385
+ async def archive(self, item: ItemRef) -> Cipher:
386
+ """Archive an item: it is kept, but hidden from normal listings and searches.
387
+
388
+ Args:
389
+ item: The item, as object or id.
390
+
391
+ Returns:
392
+ The archived item.
393
+
394
+ Raises:
395
+ ApiError: No such item.
396
+ """
397
+ return _core.decrypt_cipher(await self.request('PUT', f'/api/ciphers/{_item_id(item)}/archive'), self._require_keys())
398
+
399
+ async def unarchive(self, item: ItemRef) -> Cipher:
400
+ """Bring an archived item back to normal listings.
401
+
402
+ Args:
403
+ item: The item, as object or id.
404
+
405
+ Returns:
406
+ The item.
407
+
408
+ Raises:
409
+ ApiError: No such item.
410
+ """
411
+ return _core.decrypt_cipher(await self.request('PUT', f'/api/ciphers/{_item_id(item)}/unarchive'), self._require_keys())
412
+
413
+ # ------------------------------------------------------------ bulk operations (reversible only)
414
+
415
+ async def _validated_ids(self, items: Sequence[ItemRef], action: str, check: Callable[[Cipher], str | None]) -> list[str]:
416
+ """Check every item before a bulk request; any problem means nothing is sent.
417
+
418
+ The server applies bulk changes one by one and stops at the first error, leaving earlier items changed.
419
+
420
+ Args:
421
+ items: The items to act on.
422
+ action: Name of the action, for error messages.
423
+ check: Returns a problem description for an item that must not be included, or None.
424
+
425
+ Returns:
426
+ The item ids, in the given order.
427
+
428
+ Raises:
429
+ UnsafeWriteError: An item is listed twice, does not exist, is not accessible or fails ``check``.
430
+ """
431
+ if not items:
432
+ return []
433
+ ids = [_item_id(i) for i in items]
434
+ if len(set(ids)) != len(ids):
435
+ raise UnsafeWriteError(f'{action}: the same item is listed twice')
436
+ current = {c.id: c for c in (await self.sync(include_archived=True)).ciphers}
437
+ problems = []
438
+ for item_id in ids:
439
+ cipher = current.get(item_id)
440
+ problem = 'not found or not accessible' if cipher is None else check(cipher)
441
+ if problem:
442
+ problems.append(f'{item_id}: {problem}')
443
+ if problems:
444
+ raise UnsafeWriteError(f'{action} refused, nothing was changed: ' + '; '.join(problems))
445
+ return ids
446
+
447
+ async def move_many(self, items: Sequence[ItemRef], folder: FolderRef | None) -> None:
448
+ """Move several items to a folder, all or nothing.
449
+
450
+ Every item is checked first; if any is missing or inaccessible, nothing is sent.
451
+
452
+ Args:
453
+ items: The items, as objects or ids.
454
+ folder: The target folder (object, id or unique name), or None for no folder.
455
+
456
+ Raises:
457
+ UnsafeWriteError: An item failed the check; nothing was changed.
458
+ VaultwardenError: The folder was not found.
459
+ """
460
+ folder_id = await self._resolve_folder(folder)
461
+ ids = await self._validated_ids(items, 'move', lambda c: None)
462
+ if ids:
463
+ await self.request('POST', '/api/ciphers/move', json={'ids': ids, 'folderId': folder_id})
464
+
465
+ async def trash_many(self, items: Sequence[ItemRef]) -> None:
466
+ """Move several items to the trash, all or nothing.
467
+
468
+ Args:
469
+ items: The items, as objects or ids. None of them may already be in the trash or be read-only.
470
+
471
+ Raises:
472
+ UnsafeWriteError: An item failed the check; nothing was changed.
473
+ """
474
+ ids = await self._validated_ids(items, 'trash', lambda c: 'already in the trash' if c.is_deleted else None if c.edit else 'read-only')
475
+ if ids:
476
+ await self.request('PUT', '/api/ciphers/delete', json={'ids': ids})
477
+
478
+ async def restore_many(self, items: Sequence[ItemRef]) -> None:
479
+ """Restore several items from the trash, all or nothing.
480
+
481
+ Args:
482
+ items: The items, as objects or ids. All of them must be in the trash.
483
+
484
+ Raises:
485
+ UnsafeWriteError: An item failed the check; nothing was changed.
486
+ """
487
+ ids = await self._validated_ids(items, 'restore', lambda c: None if c.is_deleted else 'not in the trash')
488
+ if ids:
489
+ await self.request('PUT', '/api/ciphers/restore', json={'ids': ids})
490
+
491
+ async def archive_many(self, items: Sequence[ItemRef]) -> None:
492
+ """Archive several items, all or nothing.
493
+
494
+ Args:
495
+ items: The items, as objects or ids. None of them may be archived already or be in the trash.
496
+
497
+ Raises:
498
+ UnsafeWriteError: An item failed the check; nothing was changed.
499
+ """
500
+ ids = await self._validated_ids(items, 'archive', lambda c: 'already archived' if c.is_archived else 'in the trash' if c.is_deleted else None)
501
+ if ids:
502
+ await self.request('PUT', '/api/ciphers/archive', json={'ids': ids})
503
+
504
+ async def unarchive_many(self, items: Sequence[ItemRef]) -> None:
505
+ """Bring several archived items back, all or nothing.
506
+
507
+ Args:
508
+ items: The items, as objects or ids. All of them must be archived.
509
+
510
+ Raises:
511
+ UnsafeWriteError: An item failed the check; nothing was changed.
512
+ """
513
+ ids = await self._validated_ids(items, 'unarchive', lambda c: None if c.is_archived else 'not archived')
514
+ if ids:
515
+ await self.request('PUT', '/api/ciphers/unarchive', json={'ids': ids})
516
+
517
+ async def create_folder(self, name: str) -> Folder:
518
+ """Create a folder.
519
+
520
+ Folders are stored flat. The web vault and the apps nest them by name: `Work/Clients` is shown inside `Work`.
521
+
522
+ Args:
523
+ name: The folder name (encrypted before upload). Use `/` to nest it under another folder.
524
+
525
+ Returns:
526
+ The created folder.
527
+ """
528
+ keys = self._require_keys()
529
+ body = await self.request('POST', '/api/folders', json={'name': _merge.verified_encrypt(name, keys.user_key)})
530
+ return _core.decrypt_folder(body, keys)
531
+
532
+ async def rename_folder(self, folder: FolderRef, name: str) -> Folder:
533
+ """Rename a folder.
534
+
535
+ Only this folder changes. Sub-folders are separate folders named `<old name>/...`; they keep their names.
536
+
537
+ Args:
538
+ folder: The folder, as object, id or unique name.
539
+ name: The new name.
540
+
541
+ Returns:
542
+ The renamed folder.
543
+
544
+ Raises:
545
+ VaultwardenError: The folder was not found or the name is ambiguous.
546
+ """
547
+ keys = self._require_keys()
548
+ folder_id = await self._resolve_folder(folder)
549
+ body = await self.request('PUT', f'/api/folders/{folder_id}', json={'name': _merge.verified_encrypt(name, keys.user_key)})
550
+ return _core.decrypt_folder(body, keys)
551
+
552
+ async def delete_folder(self, folder: FolderRef) -> None:
553
+ """Delete a folder. Its items are kept and moved to "no folder".
554
+
555
+ Sub-folders (`<name>/...`) are separate folders and are not deleted.
556
+
557
+ Args:
558
+ folder: The folder, as object, id or unique name.
559
+
560
+ Raises:
561
+ VaultwardenError: The folder was not found or the name is ambiguous.
562
+ """
563
+ folder_id = await self._resolve_folder(folder)
564
+ await self.request('DELETE', f'/api/folders/{folder_id}')
565
+
566
+ async def add_attachment(self, item: ItemRef, file_name: str, data: bytes) -> Cipher:
567
+ """Encrypt a file and attach it to an item.
568
+
569
+ The file gets its own key; key, name and content are checked before upload. If the upload fails, the
570
+ half-created attachment record is removed again.
571
+
572
+ Args:
573
+ item: The item, as object or id.
574
+ file_name: The file name shown in the vault (encrypted).
575
+ data: The file content.
576
+
577
+ Returns:
578
+ The item with the new attachment in ``attachments``.
579
+
580
+ Raises:
581
+ UnsafeWriteError: The encryption self-check failed; nothing was sent.
582
+ ApiError: The server refused the attachment (for example storage limits or files over 525 MB).
583
+ """
584
+ keys = self._require_keys()
585
+ cipher = await self._resolve_cipher(item)
586
+ item_key = _core.cipher_key(JsonObject(cipher.raw), keys)
587
+ attachment_key = SymmetricKey.generate()
588
+ encrypted = crypto.encrypt_buffer(data, attachment_key)
589
+ request = _encode.encode_attachment_request(file_name, len(encrypted), attachment_key, item_key)
590
+ _merge.verify_attachment(request, encrypted, data, file_name, item_key)
591
+ meta = JsonObject(await self.request('POST', f'/api/ciphers/{cipher.id}/attachment/v2', json=request))
592
+ attachment_id = meta.get_str('attachmentId')
593
+ if not attachment_id:
594
+ raise ApiError(500, 'server returned no attachmentId')
595
+ try:
596
+ await self.request(
597
+ 'POST', f'/api/ciphers/{cipher.id}/attachment/{attachment_id}', files={'data': (request['fileName'], encrypted, 'application/octet-stream')}
598
+ )
599
+ except VaultwardenError:
600
+ await self.request('DELETE', f'/api/ciphers/{cipher.id}/attachment/{attachment_id}')
601
+ raise
602
+ return await self.get_cipher(cipher.id)
603
+
604
+ async def download_attachment(self, item: ItemRef, attachment: Attachment | str) -> bytes:
605
+ """Download and decrypt an attachment.
606
+
607
+ Args:
608
+ item: The item, as object or id.
609
+ attachment: The attachment, as object (from ``item.attachments``) or id.
610
+
611
+ Returns:
612
+ The decrypted file content.
613
+
614
+ Raises:
615
+ ApiError: No such attachment.
616
+ CryptoError: The file cannot be decrypted.
617
+ """
618
+ keys = self._require_keys()
619
+ cipher = await self._resolve_cipher(item)
620
+ attachment_id = attachment.id if isinstance(attachment, Attachment) else attachment
621
+ meta = JsonObject(await self.request('GET', f'/api/ciphers/{cipher.id}/attachment/{attachment_id}'))
622
+ url = meta.get_str('url')
623
+ if not url:
624
+ raise ApiError(500, 'server returned no attachment url')
625
+ response = await self._http.get(url)
626
+ _core.raise_for_status(response.status_code, None)
627
+ item_key = _core.cipher_key(JsonObject(cipher.raw), keys)
628
+ enc_key = meta.get_str('key')
629
+ attachment_key = SymmetricKey.from_bytes(crypto.decrypt(enc_key, item_key)) if enc_key else item_key
630
+ return crypto.decrypt_buffer(response.content, attachment_key)
631
+
632
+ async def delete_attachment(self, item: ItemRef, attachment: Attachment | str) -> None:
633
+ """Delete an attachment permanently.
634
+
635
+ Args:
636
+ item: The item, as object or id.
637
+ attachment: The attachment, as object or id.
638
+
639
+ Raises:
640
+ ApiError: No such attachment.
641
+ """
642
+ attachment_id = attachment.id if isinstance(attachment, Attachment) else attachment
643
+ await self.request('DELETE', f'/api/ciphers/{_item_id(item)}/attachment/{attachment_id}')
644
+
645
+ async def _create(
646
+ self,
647
+ cipher: Cipher,
648
+ folder: FolderRef | None,
649
+ fields: Mapping[str, str] | None,
650
+ organization: OrganizationRef | None = None,
651
+ collections: Sequence[CollectionRef] = (),
652
+ ) -> Cipher:
653
+ """Shared part of the ``create_*`` helpers: resolve references and create the item.
654
+
655
+ Args:
656
+ cipher: The prepared item.
657
+ folder: Folder reference, or None.
658
+ fields: Hidden custom fields to add, or None.
659
+ organization: Organization reference, or None for a personal item.
660
+ collections: Collection references for an organization item.
661
+
662
+ Returns:
663
+ The created item.
664
+
665
+ Raises:
666
+ VaultwardenError: An organization item without collections, or a reference was not found.
667
+ """
668
+ hidden = tuple(CustomField(name=k, value=v, type=FieldType.HIDDEN) for k, v in (fields or {}).items())
669
+ org_id = await self._resolve_organization(organization) if organization is not None else None
670
+ if org_id and not collections:
671
+ raise VaultwardenError('organization items need at least one collection')
672
+ return await self.create_cipher(
673
+ replace(
674
+ cipher,
675
+ folder_id=await self._resolve_folder(folder),
676
+ fields=cipher.fields + hidden,
677
+ organization_id=org_id,
678
+ collection_ids=tuple(_collection_id(c) for c in collections),
679
+ )
680
+ )
681
+
682
+ async def create_login(
683
+ self,
684
+ name: str,
685
+ *,
686
+ username: str | None = None,
687
+ password: str | None = None,
688
+ uris: Sequence[str | LoginUri] = (),
689
+ totp: str | None = None,
690
+ notes: str | None = None,
691
+ folder: FolderRef | None = None,
692
+ favorite: bool = False,
693
+ organization: OrganizationRef | None = None,
694
+ collections: Sequence[CollectionRef] = (),
695
+ fields: Mapping[str, str] | None = None,
696
+ reprompt: bool = False,
697
+ ) -> Cipher:
698
+ """Create a login item.
699
+
700
+ Args:
701
+ name: The item name.
702
+ username: The username.
703
+ password: The password.
704
+ uris: Websites or apps the login belongs to: plain strings, or
705
+ [LoginUri][vaultwarden2.models.LoginUri] to set a match rule.
706
+ totp: A TOTP seed (base32 secret, ``otpauth://totp/...`` or ``steam://...``), see
707
+ [Login.totp_code][vaultwarden2.models.Login.totp_code].
708
+ notes: Free-text notes (encrypted).
709
+ folder: The folder to put the item in, as [Folder][vaultwarden2.models.Folder], id or unique name.
710
+ None (the default) means no folder.
711
+ favorite: Mark the item as favorite.
712
+ organization: Create the item in this organization (object, id or unique name) instead of the personal vault.
713
+ Requires ``collections``.
714
+ collections: Collections of ``organization`` to put the item in (objects or ids); at least one if ``organization`` is set.
715
+ fields: Extra values as ``{name: value}``, stored as hidden custom fields.
716
+ reprompt: Require the master password again before the password is shown in the official apps.
717
+
718
+ Returns:
719
+ The created item, decrypted, as stored on the server (with its id).
720
+
721
+ Raises:
722
+ VaultwardenError: The folder or organization was not found, or an organization item has no collection.
723
+ UnsafeWriteError: The payload failed verification before upload; nothing was sent.
724
+ ApiError: The server rejected the item.
725
+
726
+ Example:
727
+ ```python
728
+ await vw.create_login('GitHub', username='alice', password=secret, uris=['https://github.com'], folder='Work')
729
+ ```
730
+ """
731
+ login = Login(username=username, password=password, totp=totp, uris=tuple(u if isinstance(u, LoginUri) else LoginUri(uri=u) for u in uris))
732
+ cipher = Cipher(
733
+ type=CipherType.LOGIN,
734
+ name=name,
735
+ notes=notes,
736
+ favorite=favorite,
737
+ login=login,
738
+ reprompt=RepromptType.PASSWORD if reprompt else RepromptType.NONE,
739
+ )
740
+ return await self._create(cipher, folder, fields, organization, collections)
741
+
742
+ async def create_note(
743
+ self,
744
+ name: str,
745
+ notes: str,
746
+ *,
747
+ folder: FolderRef | None = None,
748
+ favorite: bool = False,
749
+ organization: OrganizationRef | None = None,
750
+ collections: Sequence[CollectionRef] = (),
751
+ fields: Mapping[str, str] | None = None,
752
+ ) -> Cipher:
753
+ """Create a secure note.
754
+
755
+ Args:
756
+ name: The item name.
757
+ notes: The note text (encrypted).
758
+ folder: The folder to put the item in, as [Folder][vaultwarden2.models.Folder], id or unique name.
759
+ None (the default) means no folder.
760
+ favorite: Mark the item as favorite.
761
+ organization: Create the item in this organization (object, id or unique name) instead of the personal vault.
762
+ Requires ``collections``.
763
+ collections: Collections of ``organization`` to put the item in (objects or ids); at least one if ``organization`` is set.
764
+ fields: Extra values as ``{name: value}``, stored as hidden custom fields.
765
+
766
+ Returns:
767
+ The created item, decrypted, as stored on the server (with its id).
768
+
769
+ Raises:
770
+ VaultwardenError: The folder or organization was not found, or an organization item has no collection.
771
+ UnsafeWriteError: The payload failed verification before upload; nothing was sent.
772
+ ApiError: The server rejected the item.
773
+ """
774
+ cipher = Cipher(type=CipherType.SECURE_NOTE, name=name, notes=notes, favorite=favorite, secure_note_type=0)
775
+ return await self._create(cipher, folder, fields, organization, collections)
776
+
777
+ async def create_card(
778
+ self,
779
+ name: str,
780
+ *,
781
+ cardholder_name: str | None = None,
782
+ brand: str | None = None,
783
+ number: str | None = None,
784
+ exp_month: str | None = None,
785
+ exp_year: str | None = None,
786
+ code: str | None = None,
787
+ notes: str | None = None,
788
+ folder: FolderRef | None = None,
789
+ favorite: bool = False,
790
+ organization: OrganizationRef | None = None,
791
+ collections: Sequence[CollectionRef] = (),
792
+ ) -> Cipher:
793
+ """Create a payment card item.
794
+
795
+ Args:
796
+ name: The item name.
797
+ cardholder_name: The name on the card.
798
+ brand: The card brand, for example ``'Visa'``.
799
+ number: The card number.
800
+ exp_month: The expiry month, for example ``'12'``.
801
+ exp_year: The expiry year, for example ``'2030'``.
802
+ code: The security code (CVV).
803
+ notes: Free-text notes (encrypted).
804
+ folder: The folder to put the item in, as [Folder][vaultwarden2.models.Folder], id or unique name.
805
+ None (the default) means no folder.
806
+ favorite: Mark the item as favorite.
807
+ organization: Create the item in this organization (object, id or unique name) instead of the personal vault.
808
+ Requires ``collections``.
809
+ collections: Collections of ``organization`` to put the item in (objects or ids); at least one if ``organization`` is set.
810
+
811
+ Returns:
812
+ The created item, decrypted, as stored on the server (with its id).
813
+
814
+ Raises:
815
+ VaultwardenError: The folder or organization was not found, or an organization item has no collection.
816
+ UnsafeWriteError: The payload failed verification before upload; nothing was sent.
817
+ ApiError: The server rejected the item.
818
+ """
819
+ card = Card(cardholder_name=cardholder_name, brand=brand, number=number, exp_month=exp_month, exp_year=exp_year, code=code)
820
+ return await self._create(Cipher(type=CipherType.CARD, name=name, notes=notes, favorite=favorite, card=card), folder, None, organization, collections)
821
+
822
+ async def create_identity(
823
+ self,
824
+ name: str,
825
+ *,
826
+ notes: str | None = None,
827
+ folder: FolderRef | None = None,
828
+ favorite: bool = False,
829
+ organization: OrganizationRef | None = None,
830
+ collections: Sequence[CollectionRef] = (),
831
+ **identity: str | None,
832
+ ) -> Cipher:
833
+ """Create an identity item.
834
+
835
+ Args:
836
+ name: The item name.
837
+ notes: Free-text notes (encrypted).
838
+ folder: The folder to put the item in, as [Folder][vaultwarden2.models.Folder], id or unique name.
839
+ None (the default) means no folder.
840
+ favorite: Mark the item as favorite.
841
+ organization: Create the item in this organization (object, id or unique name) instead of the personal vault.
842
+ Requires ``collections``.
843
+ collections: Collections of ``organization`` to put the item in (objects or ids); at least one if ``organization`` is set.
844
+ **identity: Identity fields by name, see [Identity][vaultwarden2.models.Identity]
845
+ (``first_name``, ``last_name``, ``email``, ``phone``, ``address1``, ...).
846
+
847
+ Returns:
848
+ The created item, decrypted, as stored on the server (with its id).
849
+
850
+ Raises:
851
+ VaultwardenError: The folder or organization was not found, or an organization item has no collection.
852
+ UnsafeWriteError: The payload failed verification before upload; nothing was sent.
853
+ ApiError: The server rejected the item.
854
+ TypeError: An unknown identity field was passed.
855
+ """
856
+ cipher = Cipher(type=CipherType.IDENTITY, name=name, notes=notes, favorite=favorite, identity=Identity(**identity))
857
+ return await self._create(cipher, folder, None, organization, collections)
858
+
859
+ async def create_ssh_key(
860
+ self,
861
+ name: str,
862
+ *,
863
+ private_key: str,
864
+ public_key: str | None = None,
865
+ key_fingerprint: str | None = None,
866
+ notes: str | None = None,
867
+ folder: FolderRef | None = None,
868
+ favorite: bool = False,
869
+ organization: OrganizationRef | None = None,
870
+ collections: Sequence[CollectionRef] = (),
871
+ ) -> Cipher:
872
+ """Create an SSH key item.
873
+
874
+ The server and the official clients need all three of private key, public key and fingerprint; the latter
875
+ two are derived from the private key when not given.
876
+
877
+ Args:
878
+ name: The item name.
879
+ private_key: The private key (OpenSSH or PEM format, unencrypted).
880
+ public_key: The public key in OpenSSH format. Derived from ``private_key`` if omitted.
881
+ key_fingerprint: The ``SHA256:...`` fingerprint. Derived from ``private_key`` if omitted.
882
+ notes: Free-text notes (encrypted).
883
+ folder: The folder to put the item in, as [Folder][vaultwarden2.models.Folder], id or unique name.
884
+ None (the default) means no folder.
885
+ favorite: Mark the item as favorite.
886
+ organization: Create the item in this organization (object, id or unique name) instead of the personal vault.
887
+ Requires ``collections``.
888
+ collections: Collections of ``organization`` to put the item in (objects or ids); at least one if ``organization`` is set.
889
+
890
+ Returns:
891
+ The created item, decrypted, as stored on the server (with its id).
892
+
893
+ Raises:
894
+ VaultwardenError: The folder or organization was not found, or an organization item has no collection.
895
+ UnsafeWriteError: The payload failed verification before upload; nothing was sent.
896
+ ApiError: The server rejected the item.
897
+ CryptoError: The private key cannot be parsed and ``public_key``/``key_fingerprint`` were not given.
898
+ """
899
+ if public_key is None or key_fingerprint is None:
900
+ derived_public, derived_fingerprint = crypto.ssh_public_key_and_fingerprint(private_key)
901
+ public_key = public_key or derived_public
902
+ key_fingerprint = key_fingerprint or derived_fingerprint
903
+ ssh_key = SshKey(private_key=private_key, public_key=public_key, key_fingerprint=key_fingerprint)
904
+ return await self._create(
905
+ Cipher(type=CipherType.SSH_KEY, name=name, notes=notes, favorite=favorite, ssh_key=ssh_key), folder, None, organization, collections
906
+ )
907
+
908
+ async def set_password(self, item: ItemRef, password: str) -> Cipher:
909
+ """Change the password of a login item; the old password goes to the password history.
910
+
911
+ Args:
912
+ item: The item, as object or id.
913
+ password: The new password.
914
+
915
+ Returns:
916
+ The updated item.
917
+
918
+ Raises:
919
+ VaultwardenError: The item is not a login.
920
+ ConflictError: The item changed on the server in the meantime; nothing was sent.
921
+ """
922
+ cipher = await self._resolve_cipher(item)
923
+ if cipher.login is None:
924
+ raise VaultwardenError('item is not a login')
925
+ return await self.update_cipher(replace(cipher, login=replace(cipher.login, password=password)))
926
+
927
+ async def rename(self, item: ItemRef, name: str) -> Cipher:
928
+ """Rename an item.
929
+
930
+ Args:
931
+ item: The item, as object or id.
932
+ name: The new name.
933
+
934
+ Returns:
935
+ The updated item.
936
+
937
+ Raises:
938
+ ConflictError: The name changed on the server in the meantime; nothing was sent.
939
+ """
940
+ return await self.update_cipher(replace(await self._resolve_cipher(item), name=name))
941
+
942
+ async def move(self, item: ItemRef, folder: FolderRef | None) -> Cipher:
943
+ """Move an item to a folder. Nothing is re-encrypted.
944
+
945
+ Args:
946
+ item: The item, as object or id.
947
+ folder: The target folder (object, id or unique name), or None for no folder.
948
+
949
+ Returns:
950
+ The updated item.
951
+
952
+ Raises:
953
+ VaultwardenError: The folder was not found or the name is ambiguous.
954
+ """
955
+ folder_id = await self._resolve_folder(folder)
956
+ current = await self._resolve_cipher(item)
957
+ body = {'folderId': folder_id, 'favorite': current.favorite}
958
+ return _core.decrypt_cipher(await self.request('PUT', f'/api/ciphers/{current.id}/partial', json=body), self._require_keys())
959
+
960
+ async def set_favorite(self, item: ItemRef, favorite: bool = True) -> Cipher:
961
+ """Mark or unmark an item as favorite. Nothing is re-encrypted.
962
+
963
+ Args:
964
+ item: The item, as object or id.
965
+ favorite: True to mark, False to unmark.
966
+
967
+ Returns:
968
+ The updated item.
969
+ """
970
+ return await self._partial_update(item, folder_id=None, favorite=favorite)