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.
vaultwarden2/dump.py ADDED
@@ -0,0 +1,362 @@
1
+ """Encrypted, compressed dump files of a vault or organization export.
2
+
3
+ Pipeline: JSON export (see [vaultwarden2.export][]) -> compress -> encrypt -> file.
4
+
5
+ Encryption: the passphrase is stretched with Argon2id (RFC 9106 parameters, random 16-byte salt per
6
+ file) into a 256-bit key for ChaCha20-Poly1305 (RFC 8439). The whole header (format version, KDF
7
+ parameters, salt, nonce, compressor name) is authenticated as associated data, so any change to the
8
+ file is detected on load.
9
+
10
+ Compression is pluggable: anything with ``compress(bytes) -> bytes`` and ``decompress(bytes) -> bytes``
11
+ works (``gzip``, ``bz2``, ``lzma``, ``zlib``, ``compression.zstd``...). The compressor's name is stored in
12
+ the header, so :func:`load_dump` picks the right one automatically for the well-known ones. The default
13
+ is zstd (``compression.zstd`` on Python 3.14+, else the optional ``zstandard`` package:
14
+ ``pip install python-vaultwarden2[zstd]``), falling back to lzma.
15
+
16
+ File layout (big-endian)::
17
+
18
+ magic 'VW2DUMP' + NUL (8) | version (1) | cipher (1) | kdf (1) | argon2 time cost (4) | memory KiB (4)
19
+ | lanes (1) | salt (16) | nonce (12) | compressor name length (1) | compressor name | ciphertext+tag
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import importlib
25
+ import json
26
+ import os
27
+ import struct
28
+ from dataclasses import dataclass
29
+ from pathlib import Path
30
+ from typing import TYPE_CHECKING, Any, Protocol
31
+
32
+ from cryptography.exceptions import InvalidTag
33
+ from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
34
+ from cryptography.hazmat.primitives.kdf.argon2 import Argon2id
35
+
36
+ from vaultwarden2.errors import CryptoError, VaultwardenError
37
+ from vaultwarden2.export import to_export_json
38
+
39
+ if TYPE_CHECKING:
40
+ from vaultwarden2.models import OrganizationExport, Vault
41
+
42
+ MAGIC = b'VW2DUMP\0'
43
+ FORMAT_VERSION = 1
44
+ CIPHER_CHACHA20_POLY1305 = 1
45
+ KDF_ARGON2ID = 1
46
+ SALT_SIZE = 16
47
+ NONCE_SIZE = 12
48
+ _PARAMS = struct.Struct('>BBBIIB')
49
+ MAX_MEMORY_KIB = 4 * 1024 * 1024
50
+ """Refuse files asking for more than 4 GiB of Argon2 memory (protects against hostile headers)."""
51
+ MAX_TIME_COST = 64
52
+
53
+
54
+ class Compressor(Protocol):
55
+ """Anything with ``compress`` and ``decompress`` functions.
56
+
57
+ For example the modules ``gzip``, ``bz2``, ``lzma``, ``zlib`` or ``compression.zstd``.
58
+ """
59
+
60
+ def compress(self, data: bytes, /) -> bytes:
61
+ """Compress data.
62
+
63
+ Args:
64
+ data: The data.
65
+
66
+ Returns:
67
+ The compressed data.
68
+ """
69
+ ...
70
+
71
+ def decompress(self, data: bytes, /) -> bytes:
72
+ """Decompress data.
73
+
74
+ Args:
75
+ data: The compressed data.
76
+
77
+ Returns:
78
+ The original data.
79
+ """
80
+ ...
81
+
82
+
83
+ class _NoCompression:
84
+ """A compressor that stores data unchanged."""
85
+
86
+ @staticmethod
87
+ def compress(data: bytes, /) -> bytes:
88
+ """Return the data unchanged.
89
+
90
+ Args:
91
+ data: The data.
92
+
93
+ Returns:
94
+ The same data.
95
+ """
96
+ return data
97
+
98
+ @staticmethod
99
+ def decompress(data: bytes, /) -> bytes:
100
+ """Return the data unchanged.
101
+
102
+ Args:
103
+ data: The data.
104
+
105
+ Returns:
106
+ The same data.
107
+ """
108
+ return data
109
+
110
+
111
+ NO_COMPRESSION: Compressor = _NoCompression()
112
+ """Pass as ``compressor`` to store the JSON uncompressed."""
113
+
114
+
115
+ @dataclass(frozen=True, slots=True)
116
+ class Argon2Params:
117
+ """Cost of the passphrase key derivation (Argon2id).
118
+
119
+ The defaults are RFC 9106's second recommended option. Raise them for long-term archives; every load of the
120
+ file pays the same cost.
121
+
122
+ Attributes:
123
+ time_cost: Passes over memory.
124
+ memory_kib: Memory in KiB.
125
+ lanes: Parallel lanes.
126
+ """
127
+
128
+ time_cost: int = 3
129
+ memory_kib: int = 64 * 1024
130
+ lanes: int = 4
131
+
132
+
133
+ def _zstd() -> Compressor | None:
134
+ """The zstd module, if available.
135
+
136
+ Returns:
137
+ ``compression.zstd`` (Python 3.14+) or ``zstandard`` (extra ``zstd``), or None.
138
+ """
139
+ for module in ('compression.zstd', 'zstandard'):
140
+ try:
141
+ return importlib.import_module(module)
142
+ except ImportError:
143
+ continue
144
+ return None
145
+
146
+
147
+ _STDLIB = {'gzip', 'bz2', 'lzma', 'zlib'}
148
+
149
+
150
+ def compressor_by_name(name: str) -> Compressor:
151
+ """Find the compressor for a name stored in a dump header.
152
+
153
+ Args:
154
+ name: ``'zstd'``, ``'lzma'``, ``'gzip'``, ``'bz2'``, ``'zlib'`` or ``'none'``.
155
+
156
+ Returns:
157
+ The compressor.
158
+
159
+ Raises:
160
+ VaultwardenError: zstd is needed but not available, or the name is unknown (pass the compressor
161
+ explicitly).
162
+ """
163
+ if name == 'none':
164
+ return NO_COMPRESSION
165
+ if name == 'zstd':
166
+ zstd = _zstd()
167
+ if zstd is None:
168
+ raise VaultwardenError('file is zstd-compressed: use Python 3.14+ or install the zstd extra (pip install python-vaultwarden2[zstd])')
169
+ return zstd
170
+ if name in _STDLIB:
171
+ return importlib.import_module(name)
172
+ raise VaultwardenError(f'unknown compressor {name!r}; pass it explicitly via compressor=')
173
+
174
+
175
+ def default_compressor() -> tuple[str, Compressor]:
176
+ """The compressor used when none is given.
177
+
178
+ Returns:
179
+ ``('zstd', module)`` when zstd is available (Python 3.14+ or the ``zstd`` extra), else ``('lzma', lzma)``.
180
+ """
181
+ zstd = _zstd()
182
+ if zstd is not None:
183
+ return 'zstd', zstd
184
+ return 'lzma', compressor_by_name('lzma')
185
+
186
+
187
+ def _name_of(compressor: Compressor) -> str:
188
+ """The name stored in the dump header for a compressor.
189
+
190
+ Args:
191
+ compressor: The compressor.
192
+
193
+ Returns:
194
+ Its name; both zstd modules map to ``'zstd'``.
195
+ """
196
+ if compressor is NO_COMPRESSION:
197
+ return 'none'
198
+ name = getattr(compressor, '__name__', None) or getattr(compressor, 'name', None) or type(compressor).__name__
199
+ if name in {'compression.zstd', 'zstandard'}:
200
+ return 'zstd'
201
+ return str(name).removeprefix('compression.')
202
+
203
+
204
+ def _derive_key(passphrase: str, salt: bytes, params: Argon2Params) -> bytes:
205
+ """Derive the file key from the passphrase with Argon2id.
206
+
207
+ Args:
208
+ passphrase: The passphrase.
209
+ salt: The random salt from the file header.
210
+ params: The Argon2id cost.
211
+
212
+ Returns:
213
+ The 32-byte key.
214
+
215
+ Raises:
216
+ CryptoError: The passphrase is empty.
217
+ """
218
+ if not passphrase:
219
+ raise CryptoError('empty passphrase')
220
+ return Argon2id(salt=salt, length=32, iterations=params.time_cost, lanes=params.lanes, memory_cost=params.memory_kib).derive(passphrase.encode())
221
+
222
+
223
+ def encrypt_dump(
224
+ data: bytes,
225
+ passphrase: str,
226
+ *,
227
+ compressor: Compressor | None = None,
228
+ compressor_name: str | None = None,
229
+ argon2: Argon2Params | None = None,
230
+ ) -> bytes:
231
+ """Compress and encrypt data into the dump format.
232
+
233
+ Args:
234
+ data: The plaintext.
235
+ passphrase: The passphrase the key is derived from.
236
+ compressor: The compressor; defaults to zstd when available, else lzma. ``NO_COMPRESSION`` stores the data
237
+ uncompressed.
238
+ compressor_name: The name stored in the header. Defaults to the module name; needed for custom compressors
239
+ so they can be found again (or pass the same object to ``decrypt_dump``).
240
+ argon2: The key derivation cost; defaults to RFC 9106 parameters.
241
+
242
+ Returns:
243
+ The complete file content.
244
+
245
+ Raises:
246
+ CryptoError: The passphrase is empty.
247
+ VaultwardenError: The compressor name is longer than 255 bytes.
248
+ """
249
+ if compressor is None:
250
+ name, compressor = default_compressor()
251
+ else:
252
+ name = compressor_name or _name_of(compressor)
253
+ encoded_name = name.encode()
254
+ if len(encoded_name) > 255:
255
+ raise VaultwardenError('compressor name too long')
256
+ params = argon2 or Argon2Params()
257
+ salt, nonce = os.urandom(SALT_SIZE), os.urandom(NONCE_SIZE)
258
+ header = (
259
+ MAGIC
260
+ + _PARAMS.pack(FORMAT_VERSION, CIPHER_CHACHA20_POLY1305, KDF_ARGON2ID, params.time_cost, params.memory_kib, params.lanes)
261
+ + salt
262
+ + nonce
263
+ + bytes([len(encoded_name)])
264
+ + encoded_name
265
+ )
266
+ key = _derive_key(passphrase, salt, params)
267
+ return header + ChaCha20Poly1305(key).encrypt(nonce, compressor.compress(data), header)
268
+
269
+
270
+ def decrypt_dump(blob: bytes, passphrase: str, *, compressor: Compressor | None = None) -> bytes:
271
+ """Decrypt and decompress a dump.
272
+
273
+ Args:
274
+ blob: The complete file content.
275
+ passphrase: The passphrase.
276
+ compressor: The compressor to use instead of the one named in the header (needed for custom compressors).
277
+
278
+ Returns:
279
+ The plaintext.
280
+
281
+ Raises:
282
+ CryptoError: Not a dump, an unsupported version, out-of-range KDF settings, a wrong passphrase or a modified
283
+ file.
284
+ VaultwardenError: The compressor named in the header is not available.
285
+ """
286
+ if not blob.startswith(MAGIC):
287
+ raise CryptoError('not a vaultwarden2 dump file')
288
+ offset = len(MAGIC)
289
+ try:
290
+ version, cipher, kdf, time_cost, memory_kib, lanes = _PARAMS.unpack_from(blob, offset)
291
+ except struct.error as e:
292
+ raise CryptoError('truncated dump header') from e
293
+ offset += _PARAMS.size
294
+ if (version, cipher, kdf) != (FORMAT_VERSION, CIPHER_CHACHA20_POLY1305, KDF_ARGON2ID):
295
+ raise CryptoError(f'unsupported dump format (version {version}, cipher {cipher}, kdf {kdf})')
296
+ if not (1 <= time_cost <= MAX_TIME_COST and 8 * lanes <= memory_kib <= MAX_MEMORY_KIB and lanes >= 1):
297
+ raise CryptoError('dump header has out-of-range KDF parameters')
298
+ salt, nonce = blob[offset : offset + SALT_SIZE], blob[offset + SALT_SIZE : offset + SALT_SIZE + NONCE_SIZE]
299
+ offset += SALT_SIZE + NONCE_SIZE
300
+ if len(blob) <= offset:
301
+ raise CryptoError('truncated dump header')
302
+ name_len = blob[offset]
303
+ name = blob[offset + 1 : offset + 1 + name_len].decode(errors='replace')
304
+ offset += 1 + name_len
305
+ header, ciphertext = blob[:offset], blob[offset:]
306
+ key = _derive_key(passphrase, salt, Argon2Params(time_cost, memory_kib, lanes))
307
+ try:
308
+ compressed = ChaCha20Poly1305(key).decrypt(nonce, ciphertext, header)
309
+ except InvalidTag as e:
310
+ raise CryptoError('wrong passphrase or modified/corrupted dump file') from e
311
+ return (compressor or compressor_by_name(name)).decompress(compressed)
312
+
313
+
314
+ def write_dump(
315
+ source: Vault | OrganizationExport,
316
+ path: str | os.PathLike[str],
317
+ passphrase: str,
318
+ *,
319
+ compressor: Compressor | None = None,
320
+ compressor_name: str | None = None,
321
+ argon2: Argon2Params | None = None,
322
+ ) -> None:
323
+ """Write a personal or organization export as an encrypted, compressed JSON export file.
324
+
325
+ Args:
326
+ source: The decrypted vault (personal export) or organization export.
327
+ path: The file to create; it must not exist yet and is created with mode ``0600``.
328
+ passphrase: The passphrase protecting the file.
329
+ compressor: The compressor (see ``encrypt_dump``).
330
+ compressor_name: The name stored in the header (see ``encrypt_dump``).
331
+ argon2: The key derivation cost.
332
+
333
+ Raises:
334
+ FileExistsError: ``path`` exists already.
335
+ CryptoError: The passphrase is empty.
336
+ """
337
+ blob = encrypt_dump(to_export_json(source).encode(), passphrase, compressor=compressor, compressor_name=compressor_name, argon2=argon2)
338
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
339
+ with os.fdopen(fd, 'wb') as f:
340
+ f.write(blob)
341
+
342
+
343
+ def load_dump(path: str | os.PathLike[str], passphrase: str, *, compressor: Compressor | None = None) -> dict[str, Any]:
344
+ """Read a dump file back into the JSON export structure.
345
+
346
+ Args:
347
+ path: The dump file.
348
+ passphrase: The passphrase.
349
+ compressor: The compressor to use instead of the one named in the header.
350
+
351
+ Returns:
352
+ The export dict (``{'encrypted': False, 'items': [...], ...}``).
353
+
354
+ Raises:
355
+ CryptoError: Wrong passphrase, modified file or not a dump.
356
+ VaultwardenError: The content is not a JSON export, or the compressor is not available.
357
+ """
358
+ data = decrypt_dump(Path(path).read_bytes(), passphrase, compressor=compressor)
359
+ result = json.loads(data)
360
+ if not isinstance(result, dict):
361
+ raise VaultwardenError('dump does not contain a JSON export')
362
+ return result
vaultwarden2/errors.py ADDED
@@ -0,0 +1,123 @@
1
+ """Exceptions and warnings raised by vaultwarden2.
2
+
3
+ All exceptions derive from [VaultwardenError][vaultwarden2.VaultwardenError], so one ``except`` clause catches
4
+ everything the library raises on purpose.
5
+ """
6
+
7
+
8
+ class VaultwardenError(Exception):
9
+ """Base class of all exceptions raised by vaultwarden2."""
10
+
11
+
12
+ class AuthenticationError(VaultwardenError):
13
+ """Login failed, or the session is no longer valid.
14
+
15
+ Raised for wrong credentials, a rejected or expired session that cannot be renewed, a disabled account, or a
16
+ wrong master password when unlocking.
17
+ """
18
+
19
+
20
+ class TwoFactorRequiredError(AuthenticationError):
21
+ """The account needs a second factor: log in again with a two-step login code.
22
+
23
+ Args:
24
+ providers: The two-step login methods the server offers (provider numbers).
25
+
26
+ Attributes:
27
+ providers: The offered methods, see [TwoFactorProvider][vaultwarden2.models.TwoFactorProvider]
28
+ (for example 0 for an authenticator app, 1 for email).
29
+ """
30
+
31
+ providers: list[int]
32
+
33
+ def __init__(self, providers: list[int]) -> None:
34
+ super().__init__(f'two-factor authentication required (providers: {providers})')
35
+ self.providers = providers
36
+
37
+
38
+ class CryptoError(VaultwardenError):
39
+ """Decryption or key handling failed.
40
+
41
+ Raised for wrong keys, tampered or malformed encrypted data, unsupported formats, and unsafe KDF settings
42
+ announced by the server.
43
+ """
44
+
45
+
46
+ class NotUnlockedError(VaultwardenError):
47
+ """The operation needs a logged-in client with unlocked keys (or an organization key that is not available yet)."""
48
+
49
+
50
+ class ApiError(VaultwardenError):
51
+ """The server answered with an unexpected HTTP status.
52
+
53
+ Args:
54
+ status_code: The HTTP status code.
55
+ message: The error message from the server (or a summary of the response).
56
+
57
+ Attributes:
58
+ status_code: The HTTP status code.
59
+ message: The error message from the server.
60
+ """
61
+
62
+ status_code: int
63
+ message: str
64
+
65
+ def __init__(self, status_code: int, message: str) -> None:
66
+ super().__init__(f'HTTP {status_code}: {message}')
67
+ self.status_code = status_code
68
+ self.message = message
69
+
70
+
71
+ class RateLimitError(ApiError):
72
+ """The server rejected the request because of rate limiting (HTTP 429). Wait and retry later."""
73
+
74
+
75
+ class BulkOperationError(VaultwardenError):
76
+ """A bulk organization operation failed for some entries; the others were applied.
77
+
78
+ Args:
79
+ failures: The error message for each failed entry, by membership id.
80
+
81
+ Attributes:
82
+ failures: The error message for each failed entry, by membership id.
83
+ """
84
+
85
+ failures: dict[str, str]
86
+
87
+ def __init__(self, failures: dict[str, str]) -> None:
88
+ super().__init__(f'{len(failures)} entries failed: ' + '; '.join(f'{k}: {v}' for k, v in failures.items()))
89
+ self.failures = failures
90
+
91
+
92
+ class InsecureTransportWarning(UserWarning):
93
+ """The server is reached over plain HTTP, so login hashes, tokens and encrypted data travel unprotected.
94
+
95
+ Not raised for ``localhost``, ``127.0.0.1``, ``::1`` and ``*.localhost``.
96
+ """
97
+
98
+
99
+ class UnsafeWriteError(VaultwardenError):
100
+ """A write was refused because it could lose or corrupt data on the server. Nothing was sent.
101
+
102
+ Raised, for example, when an update would overwrite data the library cannot interpret, when a payload fails
103
+ verification, or when the server left out data an update would have to send back.
104
+ """
105
+
106
+
107
+ class ConflictError(UnsafeWriteError):
108
+ """The item changed on the server since it was read, in a way that conflicts with the update. Nothing was sent.
109
+
110
+ Read the item again, re-apply the change and retry.
111
+ """
112
+
113
+
114
+ class VaultwardenDataWarning(UserWarning):
115
+ """Server data could not be fully decrypted or interpreted.
116
+
117
+ Issued once per read that met problems. Each problem is logged in detail on the ``vaultwarden2`` logger;
118
+ affected items are listed in ``Vault.undecryptable`` or carry ``Cipher.issues``.
119
+ """
120
+
121
+
122
+ class TotpError(VaultwardenError):
123
+ """A TOTP seed is missing, malformed or of an unsupported kind. The secret is never part of the message."""
vaultwarden2/export.py ADDED
@@ -0,0 +1,128 @@
1
+ """Unencrypted JSON export in the web vault's format ("Bitwarden JSON"), importable by the web vault and the official apps.
2
+
3
+ The output contains every secret in plain text. Store it accordingly.
4
+ Attachments are not part of the format and are not exported.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ from vaultwarden2._core import IDENTITY_FIELDS
13
+ from vaultwarden2._encode import format_date
14
+ from vaultwarden2.models import Cipher, CipherType, OrganizationExport, Vault
15
+
16
+ if TYPE_CHECKING:
17
+ from datetime import datetime
18
+
19
+
20
+ def _date(value: datetime | None) -> str | None:
21
+ """Format a timestamp as in web vault exports.
22
+
23
+ Args:
24
+ value: The timestamp, or None.
25
+
26
+ Returns:
27
+ The ISO-8601 UTC string with milliseconds, or None.
28
+ """
29
+ return format_date(value) if value else None
30
+
31
+
32
+ def _item(cipher: Cipher, *, include_collections: bool) -> dict[str, Any]:
33
+ """One item in the export format.
34
+
35
+ Args:
36
+ cipher: The decrypted item.
37
+ include_collections: Write ``collectionIds`` (organization exports).
38
+
39
+ Returns:
40
+ The item as export dict.
41
+ """
42
+ item: dict[str, Any] = {
43
+ 'passwordHistory': [{'lastUsedDate': _date(p.last_used_date), 'password': p.password} for p in cipher.password_history] or None,
44
+ 'revisionDate': _date(cipher.revision_date),
45
+ 'creationDate': _date(cipher.creation_date),
46
+ 'deletedDate': _date(cipher.deleted_date),
47
+ 'archivedDate': _date(cipher.archived_date),
48
+ 'id': cipher.id,
49
+ 'organizationId': cipher.organization_id,
50
+ 'folderId': cipher.folder_id,
51
+ 'type': int(cipher.type),
52
+ 'reprompt': int(cipher.reprompt),
53
+ 'name': cipher.name,
54
+ 'notes': cipher.notes,
55
+ 'favorite': cipher.favorite,
56
+ 'fields': [{'name': f.name, 'value': f.value, 'type': int(f.type), 'linkedId': f.linked_id} for f in cipher.fields] or None,
57
+ 'collectionIds': list(cipher.collection_ids) if include_collections else None,
58
+ }
59
+ if cipher.type == CipherType.LOGIN and cipher.login is not None:
60
+ login = cipher.login
61
+ item['login'] = {
62
+ 'fido2Credentials': list(login.fido2_credentials),
63
+ 'uris': [{'match': int(u.match) if u.match is not None else None, 'uri': u.uri} for u in login.uris],
64
+ 'username': login.username,
65
+ 'password': login.password,
66
+ 'totp': login.totp,
67
+ }
68
+ elif cipher.type == CipherType.SECURE_NOTE:
69
+ item['secureNote'] = {'type': cipher.secure_note_type or 0}
70
+ elif cipher.type == CipherType.CARD and cipher.card is not None:
71
+ c = cipher.card
72
+ item['card'] = {
73
+ 'cardholderName': c.cardholder_name,
74
+ 'brand': c.brand,
75
+ 'number': c.number,
76
+ 'expMonth': c.exp_month,
77
+ 'expYear': c.exp_year,
78
+ 'code': c.code,
79
+ }
80
+ elif cipher.type == CipherType.IDENTITY and cipher.identity is not None:
81
+ item['identity'] = {json_key: getattr(cipher.identity, attr) for attr, json_key in IDENTITY_FIELDS.items()}
82
+ elif cipher.type == CipherType.SSH_KEY and cipher.ssh_key is not None:
83
+ k = cipher.ssh_key
84
+ item['sshKey'] = {'privateKey': k.private_key, 'publicKey': k.public_key, 'keyFingerprint': k.key_fingerprint}
85
+ else:
86
+ item.update(cipher.data)
87
+ return item
88
+
89
+
90
+ def to_export_dict(source: Vault | OrganizationExport) -> dict[str, Any]:
91
+ """Build the export structure.
92
+
93
+ A [Vault][vaultwarden2.models.Vault] gives a personal export (folders and personal items, as the web vault does:
94
+ organization items are left out); an [OrganizationExport][vaultwarden2.models.OrganizationExport] gives an
95
+ organization export (collections and items). Items in the trash are skipped, like in the official clients.
96
+
97
+ Args:
98
+ source: The decrypted vault or organization export.
99
+
100
+ Returns:
101
+ The export as dict, ready for ``json.dumps``.
102
+ """
103
+ if isinstance(source, OrganizationExport):
104
+ return {
105
+ 'encrypted': False,
106
+ 'collections': [{'id': c.id, 'organizationId': c.organization_id, 'name': c.name, 'externalId': c.external_id} for c in source.collections],
107
+ 'items': [_item(c, include_collections=True) for c in source.ciphers if not c.is_deleted],
108
+ }
109
+ return {
110
+ 'encrypted': False,
111
+ 'folders': [{'id': f.id, 'name': f.name} for f in source.folders],
112
+ 'items': [_item(c, include_collections=False) for c in source.ciphers if not c.organization_id and not c.is_deleted],
113
+ }
114
+
115
+
116
+ def to_export_json(source: Vault | OrganizationExport, *, indent: int | None = 2) -> str:
117
+ """The export as JSON text (see ``to_export_dict``).
118
+
119
+ The result contains every secret in plain text. Store it accordingly.
120
+
121
+ Args:
122
+ source: The decrypted vault or organization export.
123
+ indent: JSON indentation; None for the most compact output.
124
+
125
+ Returns:
126
+ The JSON text.
127
+ """
128
+ return json.dumps(to_export_dict(source), indent=indent, ensure_ascii=False)