Restore a vault from a backup¶
Written for bwtidy 1.0.0-beta.6 (261206 26404a6). The project is at https://github.com/tnek213/bwtidy.
This page is for when your vault on a Bitwarden or Vaultwarden server is gone or badly broken. The account may be lost or most items deleted, or you may be moving to a new account. You import a backup's exports into an empty account and put the attachments back. Every item comes back as a new item with a new id (see What does not come back).
Tip
When only a bwtidy change went wrong and the vault is otherwise fine, use Restore on that change's row in bwtidy's Change log instead.
To restore a current-format backup you need age (or rage) from any
distribution and Python 3.8 or later with its standard library. You also
need the official Bitwarden CLI and Bash or PowerShell to run the commands.
Every backup holds this page as RESTORE.md. The repository has it as
docs/restore.md.
What you need on your system¶
The Python programs are the same on every system. Each step gives the shell
commands as a pair. Use the Bash commands on Linux or macOS and the
PowerShell commands on Windows. Check your tools with age --version and
bw --version.
Linux¶
The same instructions work in WSL. Run python3 --version and
bash --version to check Python and Bash.
agefrom your distribution or as a release binary. It isapt install ageon Debian or Ubuntu anddnf install ageon Fedora.pacman -S ageinstalls it on Arch, and the age page lists the rest.python3, which is usually there already.- The Bitwarden CLI, which step 3 installs from npm. You can also take the standalone build.
- bash, which is there already.
macOS¶
agefrombrew install ageor as a release binary from the age page.python3from the Xcode command line tools (xcode-select --install). One from python.org or Homebrew works too.- The Bitwarden CLI, which step 3 installs from npm. Node.js for it comes
from nodejs.org or Homebrew. You can also take the
standalone build. Homebrew's
bitwarden-cliworks too, although it is not Bitwarden's own package. - bash. The system's bash 3.2 is enough because no command here needs bash 4.
The default shell of Terminal is zsh, so run
bashfirst. You can also paste the commands into zsh, which takes them as they are.
Windows¶
- Windows PowerShell 5.1 comes with Windows 10 and 11. Run
$PSVersionTable.PSVersionto check its version. - Python from python.org or the
Python install manager from the Microsoft Store. Run
py --versionto check it. agefromwinget install --id FiloSottile.ageor Scoop. For Scoop runscoop bucket add extrasand thenscoop install age. You can also take the Windows release binary from the age page and putage.exeon yourPATH.- The Bitwarden CLI in one of the three ways the
CLI documentation names. They are the
standalone
bw.exefrom the download page,choco install bitwarden-cliandnpm install -g @bitwarden/cli. Step 3 installs it from npm. - Step 1 sets
$env:PYTHONUTF8 = "1"so Python reads and writes UTF-8 as it does on Linux. Without it Python would use the Windows code page. - On Windows and macOS step 1 uses the temporary folder on disk. The decrypted files stay there until step 7 deletes them.
What a backup holds¶
A decrypted backup holds these files.
backup.zip the backup FILE.zip.age, decrypted in step 1
├── personal-export.zip data.json (bw import takes it) and attachments folders not to use
├── org-<orgId>-export.json one per organization
├── item-attachments/
│ └── <itemId>/
│ └── <fileName> every attachment by the id of its item
├── raw/
│ ├── items.json every active item as bwtidy saw it, the archived ones left out
│ ├── trash.json the trash, which no export holds, the archived items left out
│ ├── archived.json every archived item, also those in the trash
│ ├── folders.json
│ ├── collections.json
│ └── organizations.json
└── RESTORE.md this file
The attachments folders in personal-export.zip are filed by item name, so
they lose the files of items with the same name. Take attachments from
item-attachments only. When an item has two attachments with the same file
name, the second one is stored as <attachmentId>-<fileName>.
raw/archived.json also holds the archived items of an account without
premium, such as one whose premium ended. bw lists no archived item without
premium and no export holds a trashed one, so the ids come from bw's CLI
state and each item is fetched by id, its attachments like the others.
1. Decrypt the backup¶
The decrypted files hold every secret in plain text. They therefore stay in
RAM on systems with /dev/shm and in the temporary folder elsewhere.
Step 7 deletes them.
Pick the newest backup from before the loss. bwtidy keeps each one as
HOST/EMAIL/<UTC timestamp>.zip.age under its backups mount. HOST is the
server (vault.bitwarden.com for the default one) and EMAIL is the
account's email in lowercase. The mount is /backups in the container,
which is the volume bwtidy-backups or the host directory that
BWTIDY_BACKUPS names. A copy from a backup tool works the same.
age asks for the passphrase at a terminal. It is the master password bwtidy
last logged in with, since a login with a new master password re-encrypts
every backup under its backups mount. A backup keeps an earlier one when it
was copied elsewhere before the change or its re-encryption was cut off. So
does a backup that bwtidy could not open at that login. The bwtidy note lists
these passphrases in its hidden fields backup-password and
older-backup-passwords. It is a secure note named bwtidy unless you
renamed it. The note keeps an earlier password only until the re-encryption
is done, so for an older copy you may need to remember it yourself. Every
backup that opens holds the note too. The program unpack.py below prints
these two fields.
These commands make the restore directory $D and decrypt the backup there.
Replace the example backup path with yours. Keep the quotes around the
Windows path. Replace FILE.zip.age with your backup's file name. The last
command prints the path of $D where you save the Python programs.
$env:PYTHONUTF8 = "1"
$D = Join-Path $env:TEMP ("bwtidy-restore." + [IO.Path]::GetRandomFileName())
New-Item -ItemType Directory -Path $D -ErrorAction Stop | Out-Null
Set-Location -LiteralPath $D -ErrorAction Stop
Copy-Item -LiteralPath "C:\path\to\FILE.zip.age" -Destination .
age -d -o backup.zip FILE.zip.age
if ($LASTEXITCODE -eq 0) {
Remove-Item -LiteralPath FILE.zip.age
}
$D
Migrate a backup made before archived items were kept¶
If your backup predates archived item support, decrypt it as above. Before
running unpack.py, use scripts/migrate-backup from a bwtidy source checkout.
Run it with the Python interpreter from an already installed bwtidy backend
environment. The command works offline and takes two local paths.
The destination must be a new file on a filesystem that supports hard links. The command keeps the source ZIP and adds an empty archived-items listing to the copy. Any archived items missing from the original backup are still missing from the copy.
For the vault restore below, use the migrated file as backup.zip in the
restore directory. Keep the source ZIP at a different path because
unpack.py deletes the ZIP it unpacks. Both ZIPs contain plaintext vault data.
To restore from bwtidy's change history, encrypt the migrated ZIP with your current vault password.
Keep the original encrypted backup outside the active backup directory. Put the new encrypted file there under the backup name recorded in change history.
Unpack the backup¶
The program unpack.py unpacks the backup and prints how many items it
holds. It also prints the id and name of each organization. Then it prints
the two fields of the bwtidy note with the note's name. It finds the note as
a personal secure note with the field backup-password, so a renamed note
shows too. Save it as unpack.py in the restore directory ($D) with any
text editor.
import json
import os
import zipfile
def load(path):
with open(path, encoding="utf-8") as file:
return json.load(file)
with zipfile.ZipFile("backup.zip") as backup:
backup.extractall(".")
os.remove("backup.zip")
with zipfile.ZipFile("personal-export.zip") as personal:
personal.extract("data.json")
for name in "raw/items.json", "raw/trash.json", "raw/archived.json":
print(len(load(name)), "items in", name)
for org in load("raw/organizations.json"):
print("organization", org["id"], org["name"])
wanted = ("backup-password", "older-backup-passwords")
for item in load("raw/items.json"):
if item.get("type") != 2 or item.get("organizationId"):
continue
fields = [f for f in item.get("fields") or [] if f.get("name") in wanted]
if any(f["name"] == "backup-password" for f in fields):
print(item["name"])
print(json.dumps(fields, indent=2))
2. Prepare an empty account¶
Warning
Import into an empty account. That is a new account or the old one emptied with Purge vault on the My account page of Settings. An import into a vault that has items adds the backup's items next to them and replaces nothing.
Organization items go into organizations you own. Each
org-<orgId>-export.json needs one with the name it had in the backup, which
step 1 printed. Each of these organizations must be empty as well. The CLI
cannot create an organization. Create the missing ones in the web vault and
rename an existing one whose name changed. Step 5 finds an item's
organization by its name, so the names must also be unique in the backup and
in the account.
3. Set up a Bitwarden CLI of its own¶
Take the official CLI as the native executable or as the npm package. The
native one is under Command line interface at https://bitwarden.com/download/
and goes on your PATH. The npm package goes into a directory of its own,
which may be on the disk since it holds no secrets. These commands install
the version that bwtidy uses.
With a native bw on the PATH you skip these commands and leave CLI
unset. For an npm install PowerShell uses the bw.cmd shim because the
default execution policy blocks bw.ps1. Use a fresh shell for the restore.
The CLI keeps its state (BITWARDENCLI_APPDATA_DIR) in $D as well, apart
from any CLI state that something else on the machine uses. Then log in to
the account of step 2. bw config server takes the HOST of step 1 as a
URL, and a self-hosted server goes by its own URL. For a new device
bitwarden.com mails you a one-time code.
4. Import the exports¶
bw import has no zip format, so the personal export goes in as its
data.json in the format bitwardenjson.
Each organization export goes into the organization of the same name. Step 1
printed the old ids (OLDID) with their names, and the program orgs.py
prints the new ones (NEWID). Run the import once for each organization with
its two ids. Save the program as orgs.py in the restore directory ($D)
with any text editor.
import json
import shutil
import subprocess
# the full path finds bw.cmd of an npm install on Windows too
BW = shutil.which("bw") or "bw"
def bw(*args):
return json.loads(subprocess.run([BW, *args], check=True, stdout=subprocess.PIPE).stdout)
for org in bw("list", "organizations"):
print(org["id"], org["name"])
5. Upload the attachments and set organization folders¶
The import gives every item a new id. To get the files under
item-attachments/<old id>/ onto the right item, each backup item has to be
found again among the imported items. It is found by its content. A backup
item and an imported item match when all of these are the same:
- the type and the name
- every other value except the item's id and dates and attachments. That covers the login and notes as well as fields, password history and passkeys.
- the folder and the collections, compared by name
- the organization, compared by name (or both items are personal)
An organization export holds no folder and no favorite flag, as both belong to each user and not to the organization. For an organization item the match leaves them out.
Items that are equal in all of that are taken in order. It does not matter which of them gets which file, as the vault comes out the same. A backup item that matched no unused imported item gets a second try once every item has had its first. It then gets the one unused imported item of its type, name and organization if there is exactly one.
Each paired organization item then gets the folder and the favorite flag it
had in the backup. The program finds the folder by its name among the
account's folders and saves both with bw edit item. An item that already
has them is left as it is.

The program attach.py pairs the items, sets the organization items' folders
and favorites and uploads the attachments. bw names an attachment after its
file, so the program first copies each file to its real file name under
upload/.
It runs on the backup items of raw/items.json and raw/archived.json. It
leaves out the archived items in the trash, which step 6 brings back. It syncs
bw and lists what the account has now, the archived items included. It prints a
line for each organization item whose folder or favorite it sets. It also prints
one for each attachment it uploads or cannot upload. Save the program as
attach.py in the restore directory ($D) with any text editor.
An account without premium gets no archived item from bw list items
--archived. bw lists the items that are not archived in their place. So the
program keeps only the listed items with an archivedDate. It takes the ids of
the other archived items from bw's CLI state (BITWARDENCLI_APPDATA_DIR of
step 3) and gets each one by its id. Without that list of ids it goes on only
when the premium flags of the CLI state or the listings show premium.
import base64
import json
import os
import shutil
import subprocess
import sys
# what bw answers for an attachment of a personal item when the account has no premium
PREMIUM = "Premium status is required"
# what an import makes anew, and what the key compares by name instead
LEFT_OUT = {"id", "revisionDate", "creationDate", "deletedDate", "archivedDate",
"organizationId", "collectionIds", "folderId", "attachments"}
# the full path finds bw.cmd of an npm install on Windows too
BW = shutil.which("bw") or "bw"
def bw(*args):
return json.loads(subprocess.run([BW, *args], check=True, stdout=subprocess.PIPE).stdout)
def load(path):
with open(path, encoding="utf-8") as file:
return json.load(file)
NO_STATE = ("bw lists archived items only for an account with premium. Without premium this "
"program finds them by id in bw's CLI state, which is not in "
"BITWARDENCLI_APPDATA_DIR. Set BITWARDENCLI_APPDATA_DIR as step 3 does and run the "
"program again.")
UNREADABLE = ("bw's CLI state is in BITWARDENCLI_APPDATA_DIR but holds no item list this "
"program can read. Without premium bw lists no archived item and the program "
"finds them by id only in that list. Run the program with the bw that step 3 "
"installs or give the account premium.")
def cli_state():
"""bw's CLI state, None when there is none and {} when it is no JSON object."""
appdata = os.environ.get("BITWARDENCLI_APPDATA_DIR")
path = os.path.join(appdata, "data.json") if appdata else ""
if not os.path.isfile(path):
return None
try:
with open(path, encoding="utf-8") as file:
state = json.load(file)
except (OSError, ValueError):
return {}
return state if isinstance(state, dict) else {}
def archived_ids(state):
"""The ids of the archived items outside the trash in the state, None without its ciphers."""
# None also when bw keeps its ciphers under a key this program does not know
found = None
for key, ciphers in state.items():
if not key.endswith("_ciphers") or not isinstance(ciphers, dict):
continue
if found is None:
found = []
for cipher_id, cipher in ciphers.items():
if isinstance(cipher, dict) and cipher.get("archivedDate") \
and not cipher.get("deletedDate"):
found.append(cipher.get("id") or cipher_id)
return found
def has_premium(state):
"""Whether the premium flags bw goes by give the account premium, None without them."""
for key, profile in state.items():
if key.endswith("_billing_accountProfile") and isinstance(profile, dict):
return bool(profile.get("hasPremiumPersonally")
or profile.get("hasPremiumFromAnyOrganization"))
return None
def account_items():
"""Every item of the account outside the trash, the archived ones too."""
items = bw("list", "items")
# without premium bw lists the items that are not archived in place of the archived ones
listed = bw("list", "items", "--archived")
archived = [item for item in listed if item.get("archivedDate")]
state = cli_state()
ids = None if state is None else archived_ids(state)
if ids is not None:
known = {item["id"] for item in items + archived}
# bw gets an archived item by its id also without premium
return items + archived + [bw("get", "item", i) for i in ids if i not in known]
premium = None if state is None else has_premium(state)
if premium is None:
# without premium both listings are the same, so two empty ones tell nothing
premium = (bool(listed) and len(archived) == len(listed)) or (bool(items) and not listed)
if not premium:
sys.exit(NO_STATE if state is None else UNREADABLE)
return items + archived
def names(listing):
return {entry["id"]: entry["name"] for entry in listing if entry.get("id")}
def leaves(value, path=()):
"""Every value below value that is neither an object nor an array, with its path."""
if isinstance(value, dict):
for key, child in value.items():
yield from leaves(child, path + (key,))
elif isinstance(value, list):
for index, child in enumerate(value):
yield from leaves(child, path + (index,))
elif value is not None:
yield [path, value]
class Names:
"""Folder, collection and organization names by id, of the backup or of the account."""
def __init__(self, where, folders, collections, organizations):
org_names = [org["name"] for org in organizations]
if len(set(org_names)) != len(org_names):
sys.exit(f"{where} has organizations of the same name, give each a name of its own")
self.folders = names(folders)
self.collections = names(collections)
self.organizations = names(organizations)
def place(self, item):
org = item.get("organizationId")
return [item.get("type"), item.get("name"),
(self.organizations.get(org) or f"id {org}") if org else None]
def key(self, item):
# an organization export holds neither the folder nor the favorite flag
personal = not item.get("organizationId")
folder = item.get("folderId") if personal else None
content = {k: v for k, v in item.items()
if k not in LEFT_OUT and (personal or k != "favorite")}
return json.dumps(self.place(item) + [
self.folders.get(folder) if folder else None,
sorted(json.dumps(self.collections.get(c)) for c in item.get("collectionIds") or []),
sorted(json.dumps(leaf) for leaf in leaves(content)),
])
def members(item):
"""Each attachment's id, file name and file in item-attachments/<item id>/."""
used = set()
for attachment in item.get("attachments") or []:
member = attachment["fileName"]
while member in used:
member = f"{attachment['id']}-{member}"
used.add(member)
yield attachment["id"], attachment["fileName"], member
# an item of the trash comes back only through step 6, which drops its deletedDate
old = [item for path in sys.argv[1:] for item in load(path) if not item.get("deletedDate")]
old_names = Names("the backup", load("raw/folders.json"), load("raw/collections.json"),
load("raw/organizations.json"))
subprocess.run([BW, "sync"], check=True, stdout=subprocess.DEVNULL)
new = account_items()
new_names = Names("the account", bw("list", "folders"), bw("list", "collections"),
bw("list", "organizations"))
# the same content: the first unused imported item with the same key
pool = {}
for item in new:
pool.setdefault(new_names.key(item), []).append(item)
pairs = {}
used = set()
for item in old:
same = pool.get(old_names.key(item))
if same:
pairs[item["id"]] = same.pop(0)
used.add(pairs[item["id"]]["id"])
# else the one unused imported item of its type, name and organization
for item in old:
if item["id"] not in pairs:
place = old_names.place(item)
fits = [n for n in new if n["id"] not in used and new_names.place(n) == place]
if len(fits) == 1:
pairs[item["id"]] = fits[0]
used.add(fits[0]["id"])
# an organization item's folder and favorite flag by the backup, as the import sets neither
folder_ids = {}
for folder_id, folder_name in new_names.folders.items():
folder_ids.setdefault(folder_name, folder_id)
for item in old:
target = pairs.get(item["id"])
if target is None or not item.get("organizationId"):
continue
folder = item.get("folderId")
wanted = {"folderId": None, "favorite": bool(item.get("favorite"))}
if folder:
wanted["folderId"] = folder_ids.get(old_names.folders.get(folder))
if wanted["folderId"] is None:
print(f"the account has no folder named as the one of backup item {item['id']}, "
f"item {target['id']} stays in its folder", flush=True)
wanted["folderId"] = target.get("folderId")
if (target.get("folderId") == wanted["folderId"]
and bool(target.get("favorite")) == wanted["favorite"]):
continue
edited = dict(bw("get", "item", target["id"]), **wanted)
encoded = base64.b64encode(json.dumps(edited).encode("utf-8"))
# bw reads the encoded item from stdin, as a long one exceeds the Windows command line
done = subprocess.run([BW, "edit", "item", target["id"]], input=encoded,
stdout=subprocess.DEVNULL)
if done.returncode == 0:
print(f"item {target['id']} has the folder and favorite of backup item {item['id']}",
flush=True)
for item in old:
target = pairs.get(item["id"])
there = [a["fileName"] for a in (target or {}).get("attachments") or []]
for attachment, file_name, member in members(item):
said = f"attachment {attachment} of backup item {item['id']}"
source = os.path.join("item-attachments", item["id"], member)
if target is None:
print(f"no imported item fits backup item {item['id']}, "
f"attachment {attachment} is not uploaded", flush=True)
elif file_name in there:
there.remove(file_name)
elif not os.path.isfile(source):
print(f"{said} has no file in the backup, it is not uploaded", flush=True)
else:
os.makedirs(os.path.join("upload", attachment), exist_ok=True)
upload = os.path.join("upload", attachment, file_name)
shutil.copyfile(source, upload)
done = subprocess.run([BW, "create", "attachment", "--file", upload,
"--itemid", target["id"]],
stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
error = done.stderr.decode("utf-8", "replace")
if done.returncode == 0:
print(f"{said} is on item {target['id']}", flush=True)
elif PREMIUM in error:
print(f"{said} is on a personal item and needs premium, "
f"it is not uploaded", flush=True)
else:
sys.stderr.write(error)
shutil.rmtree("upload", ignore_errors=True)
A failed upload or bw edit item prints bw's error. Then run the program
again. It skips each attachment that is already there (one of that file name
on the item) and each item that has its folder and favorite. It adds only what
is missing.
The program stops at once with "has organizations of the same name" when two
organizations share a name. That can be in the backup (raw/organizations.json)
or in the account (bw list organizations). Give each one a name of its own
in the account. For the backup put the new name into raw/organizations.json
under that id as well. Then run the program again.
Each "no imported item fits" line is an attachment of a backup item that matches nothing. No imported item has its content and no single unused one has its type, name and organization.
When every item of an organization gets such a line, check that the organization has the name it had in the backup (step 2). Otherwise upload the attachments by hand.
The program show.py prints the old item (OLDID) from the items file you give
it, and the commands after it look in both files of the backup items. For an
item of the trash put with-trash.json of step 6 in place of raw/items.json.
Save the program as show.py in the restore directory ($D) with any text
editor.
import json
import sys
with open(sys.argv[1], encoding="utf-8") as file:
for item in json.load(file):
if item["id"] == sys.argv[2]:
print(json.dumps(item, indent=2))
Its files are under item-attachments/OLDID/, and the old item lists their
attachment ids and file names. bw list items --search NAME lists the new
candidates, which include those whose name only contains NAME. Compare their
values to find the right one. Copy each file to its real file name and upload
it with bw create attachment --file FILE --itemid NEWID.
Each "has no folder named as" line is an organization item whose folder in the backup has a name no folder of the account has. The item keeps the folder it is in. Create the folder in the web vault and run the program again.
Each "has no file in the backup" line means that the zip is damaged or was unpacked only in part. Decrypt and unpack it again (step 1) and run the program once more.
The program stops at once with "bw lists archived items only for an account
with premium" when bw's CLI state is not where BITWARDENCLI_APPDATA_DIR
points and the account may lack premium. Set it as in step 3 and run the
program again.
It stops with "bw's CLI state is in BITWARDENCLI_APPDATA_DIR but holds no item list" when the CLI state is there in a form the program cannot read. That happens with another version of bw. Run the program with the bw of step 3.
An account without premium¶
Bitwarden takes an attachment of a personal item only from an account with premium. Each "needs premium" line is such an attachment that is not uploaded. The items themselves are all there and so are the attachments of organization items.
To get the files back give the account premium and run the program again. It uploads only what is missing. You can also move those items into an organization in the web vault and upload their files by hand as described above.
6. Import the trash if you want it¶
No export holds the trash. It is only in raw/trash.json, and its archived
items are in raw/archived.json. bw import refuses some of a trashed item's
keys or would take them over, so the program trash.py drops them first. It
writes the rest to trash-import.json and with-trash.json. The commands after
it import trash-import.json into the personal vault and then run the program
of step 5 again. Save the program as trash.py in the restore directory ($D)
with any text editor.
import json
def load(path):
with open(path, encoding="utf-8") as file:
return json.load(file)
archived = load("raw/archived.json")
trash = load("raw/trash.json") + [i for i in archived if i.get("deletedDate")]
dropped = ("deletedDate", "folderId", "organizationId", "collectionIds")
moved = [{k: v for k, v in item.items() if k not in dropped} for item in trash]
with open("trash-import.json", "w", encoding="utf-8") as file:
items = [{k: v for k, v in item.items() if k != "id"} for item in moved]
json.dump({"encrypted": False, "items": items}, file)
with open("with-trash.json", "w", encoding="utf-8") as file:
json.dump(load("raw/items.json") + moved, file)
with-trash.json holds the active items and the trashed ones with their old
ids, so the program of step 5 finds the trashed items as well. The
attachments of the other items are already there and only those of the
trashed items get uploaded. The trashed items come back as personal items in
no folder, active or archived as they were. Move them to the trash in the
web vault if that is where they belong.
7. Check and clean up¶
The account must now have as many items and attachments as the backup. The
program check.py syncs bw and prints one line for the account and one for the
backup items of the files you give it. It finds the archived items as
attach.py does. The two lines must show the same numbers. Each "not uploaded"
line of step 5 is one missing attachment. If you imported the
trash in step 6, put with-trash.json in place of raw/items.json in
the command that runs check.py.
After the count the commands log bw out. They delete $D with every
decrypted file and the npm CLI of step 3. Save the program as check.py in
the restore directory ($D) with any text editor.
import json
import os
import shutil
import subprocess
import sys
# the full path finds bw.cmd of an npm install on Windows too
BW = shutil.which("bw") or "bw"
def bw(*args):
return json.loads(subprocess.run([BW, *args], check=True, stdout=subprocess.PIPE).stdout)
def load(path):
with open(path, encoding="utf-8") as file:
return json.load(file)
NO_STATE = ("bw lists archived items only for an account with premium. Without premium this "
"program finds them by id in bw's CLI state, which is not in "
"BITWARDENCLI_APPDATA_DIR. Set BITWARDENCLI_APPDATA_DIR as step 3 does and run the "
"program again.")
UNREADABLE = ("bw's CLI state is in BITWARDENCLI_APPDATA_DIR but holds no item list this "
"program can read. Without premium bw lists no archived item and the program "
"finds them by id only in that list. Run the program with the bw that step 3 "
"installs or give the account premium.")
def cli_state():
"""bw's CLI state, None when there is none and {} when it is no JSON object."""
appdata = os.environ.get("BITWARDENCLI_APPDATA_DIR")
path = os.path.join(appdata, "data.json") if appdata else ""
if not os.path.isfile(path):
return None
try:
with open(path, encoding="utf-8") as file:
state = json.load(file)
except (OSError, ValueError):
return {}
return state if isinstance(state, dict) else {}
def archived_ids(state):
"""The ids of the archived items outside the trash in the state, None without its ciphers."""
# None also when bw keeps its ciphers under a key this program does not know
found = None
for key, ciphers in state.items():
if not key.endswith("_ciphers") or not isinstance(ciphers, dict):
continue
if found is None:
found = []
for cipher_id, cipher in ciphers.items():
if isinstance(cipher, dict) and cipher.get("archivedDate") \
and not cipher.get("deletedDate"):
found.append(cipher.get("id") or cipher_id)
return found
def has_premium(state):
"""Whether the premium flags bw goes by give the account premium, None without them."""
for key, profile in state.items():
if key.endswith("_billing_accountProfile") and isinstance(profile, dict):
return bool(profile.get("hasPremiumPersonally")
or profile.get("hasPremiumFromAnyOrganization"))
return None
def account_items():
"""Every item of the account outside the trash, the archived ones too."""
items = bw("list", "items")
# without premium bw lists the items that are not archived in place of the archived ones
listed = bw("list", "items", "--archived")
archived = [item for item in listed if item.get("archivedDate")]
state = cli_state()
ids = None if state is None else archived_ids(state)
if ids is not None:
known = {item["id"] for item in items + archived}
# bw gets an archived item by its id also without premium
return items + archived + [bw("get", "item", i) for i in ids if i not in known]
premium = None if state is None else has_premium(state)
if premium is None:
# without premium both listings are the same, so two empty ones tell nothing
premium = (bool(listed) and len(archived) == len(listed)) or (bool(items) and not listed)
if not premium:
sys.exit(NO_STATE if state is None else UNREADABLE)
return items + archived
def count(items):
items = [item for item in items if not item.get("deletedDate")]
return len(items), sum(len(item.get("attachments") or []) for item in items)
subprocess.run([BW, "sync"], check=True, stdout=subprocess.DEVNULL)
account = account_items()
backup = [item for path in sys.argv[1:] for item in load(path)]
print("the account: %d items, %d attachments" % count(account))
print("the backup: %d items, %d attachments" % count(backup))
py check.py raw/items.json raw/archived.json
bw logout
Set-Location ~ -ErrorAction Stop
if ($D) {
Remove-Item -LiteralPath $D -Recurse -Force
}
if ($CLI) {
Remove-Item -LiteralPath $CLI -Recurse -Force
Remove-Item Alias:bw
$env:Path = $OriginalPath
}
Remove-Item Env:BW_SESSION, Env:BITWARDENCLI_APPDATA_DIR, Env:PYTHONUTF8 -ErrorAction SilentlyContinue
Then log bwtidy in to the restored account. If the account changed, first use Log out in bwtidy with "Also log out of Bitwarden" checked.
What does not come back¶
The test backend/tests/integration/test_backup_import.py in the repository
checks this on the dev vault:
- Every id is new, for items and attachments as well as folders and collections. bwtidy's Change log names the old ids, so its Restore buttons cannot find the restored items.
creationDateandrevisionDateare new.- Organization items land in the organization you import them into, which is the one of the same name (step 4). They go into its collections of the same names. Its members, groups and policies are not in the backup.
- The trash comes back without its deletion dates, as items outside the trash.
- An archived organization item comes back unarchived, as an organization export does not say which items you archived. Archive it again in the web vault.
Everything else comes back as it was:
- every value of every item, including custom fields of every type and with duplicate names or trailing spaces
- passkeys and password history
- favorites and master password reprompt
- which personal items are archived, also among the trash of step 6
- folders and collections by name, the empty ones too
- which item is in which folder and collections. Step 5 puts back the folders and favorites of organization items, which no export holds.
- every attachment with its file name and bytes
A backup holds no Sends and no organization settings. It also leaves out account settings such as two-step login, emergency access and devices.