Metadata-Version: 2.5
Name: desktop-2fa
Version: 0.10.0
Summary: Secure offline 2FA desktop authenticator
Author: Łukasz Perek
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [2025] [Łukasz Perek]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
License-File: NOTICE
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.11
Requires-Dist: argon2-cffi>=23.1.0
Requires-Dist: cryptography>=42.0.0
Requires-Dist: pydantic>=2.0.0
Requires-Dist: pyperclip==1.8.2
Requires-Dist: rich>=13.0.0
Requires-Dist: textual>=6.0.0
Requires-Dist: typer>=0.9.0
Requires-Dist: zxcvbn-python>=4.0.0
Provides-Extra: dev
Requires-Dist: black==26.10.1; extra == 'dev'
Requires-Dist: mypy>=1.0.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff>=0.6.0; extra == 'dev'
Description-Content-Type: text/markdown

# 🛡️ Desktop-2FA

A secure, offline two-factor authentication (2FA) manager for desktop environments. Built with Python, featuring strong encryption and no cloud dependencies.

🌐 **Landing Page**: [desktop-2fa.org](https://desktop-2fa.org/)

![PyPI - Downloads](https://img.shields.io/pypi/dm/desktop-2fa)
[![PyPI version](https://img.shields.io/pypi/v/desktop-2fa.svg)](https://pypi.org/project/desktop-2fa/)
![Python versions](https://img.shields.io/pypi/pyversions/desktop-2fa.svg)
![License](https://img.shields.io/github/license/wrogistefan/desktop-2fa)
![Build](https://github.com/wrogistefan/desktop-2fa/actions/workflows/ci.yml/badge.svg)

---

## ✨ Features

| Feature | Description |
|---------|-------------|
| 🔐 **Vault Security** | AES-256-GCM encryption with Argon2id key derivation |
| ⏱️ **TOTP Generation** | RFC 6238 compliant code generation |
| 💻 **Full CLI** | Complete command-line interface for managing tokens |
| 📋 **Clipboard Support** | Automatic copying of TOTP codes to clipboard |
| 🔓 **Stateless Design** | Vault contents require authentication; no long-lived sessions |
| 🛡️ **Password Policy** | Configurable password strength enforcement with zxcvbn |
| 🧪 **Well Tested** | Regression tests include RFC 6238 vectors and historical vault fixtures |
| 📖 **Security Model** | Detailed threat analysis and cryptographic design documentation |
| 🖥️ **Textual UI** | Early prototype for listing accounts and generating or copying TOTP codes |

---

## 📸 Screenshots

English dark-terminal captures from Desktop-2FA 0.10.0. All accounts and
credentials are synthetic. Terminal images render actual command output;
interactive prompts use a test runner and Textual runs headlessly.
See the [capture notes and report](assets/screenshots/release-0.10.0/README.md).

![Add entry with hidden secret](assets/screenshots/release-0.10.0/interactive.png)
*Adding an entry without displaying its secret.*

![Accounts and indices](assets/screenshots/release-0.10.0/accounts.png)
*Initializing a vault and listing synthetic accounts.*

![Code output modes](assets/screenshots/release-0.10.0/codes.png)
*Human-readable, raw and JSON code output.*

![Encrypted backup and recovery](assets/screenshots/release-0.10.0/recovery.png)
*Encrypted export, overwrite refusal and recovery into a separate vault.*

![Textual prototype](assets/screenshots/release-0.10.0/textual.png)
*The Textual prototype lists accounts; entry management uses the CLI.*

---

## 🚀 Quick Start

### Installation

```bash
pip install desktop-2fa
```

Verify installation:

```bash
python -c "import desktop_2fa; print(desktop_2fa.__version__)"
# Output: 0.10.0
```

### Basic Usage

```bash
# Initialize a new vault
d2fa vault init

# Add a new TOTP token
d2fa add GitHub GitHub JBSWY3DPEHPK3PXP

# Or add a provisioning URI (quote it so the shell preserves '&')
d2fa add "otpauth://totp/Example:alice?secret=JBSWY3DPEHPK3PXP&issuer=Example&algorithm=SHA256&digits=8&period=60"

# List all entries
d2fa list

# Generate a code
d2fa code GitHub
```

The vault is stored by default at `~/.desktop-2fa/vault`. Select a different
file for any command with the global `--vault` option, or set
`DESKTOP_2FA_VAULT` to choose one by default. An explicit `--vault` takes
precedence over the environment variable; without either, the default remains
`~/.desktop-2fa/vault`.

```bash
# Use a separate vault for this command
d2fa --vault ./development-vault list

# Show the currently selected vault path
d2fa --vault ./development-vault vault path

# Launch the early Textual UI prototype with that vault
d2fa --vault ./development-vault ui
```

URI-based add preserves algorithm, digits and period; omitted parameters default
to SHA1, 6 digits and 30 seconds. Labels are percent-decoded, and an issuer query
parameter must agree with any issuer prefix. Unsupported or contradictory
provisioning data exits with status 6 before vault access. Interactive add also
accepts a URI at the issuer prompt and skips the separate secret prompt. The URI
label supplies the account name.

Interactive `add` hides input at the dedicated `Secret` prompt; name and issuer
remain visible. Secrets/URIs passed as arguments can appear in shell history or
process inspection, and a URI pasted into the visible issuer prompt can be
echoed. Prefer a plain issuer name plus the hidden secret prompt to avoid those
exposures. See [interactive add](docs/user_manual.md#add---add-new-totp-entry).

The Textual UI is at an **early prototype stage**. It prompts for the vault
password unless one is supplied with `--password` or `--password-file`, and
supports listing entries, generating codes, and copying codes to the clipboard.
It does not support entry management or create a missing vault.

### Non-Interactive Usage

```bash
# Provide password via command line
d2fa --password mypassphrase add GitHub GitHub JBSWY3DPEHPK3PXP

# Provide password via file
d2fa --password-file /path/to/passphrase.txt add GitHub GitHub JBSWY3DPEHPK3PXP
```

---

## 📁 Vault Lifecycle

The vault is an encrypted storage file located by default at
`~/.desktop-2fa/vault`; use `--vault` or `DESKTOP_2FA_VAULT` to select another
path. Vault files must be regular files no larger than 10 MiB.

### Before Upgrading

The current loader supports vault format version 1. Future releases are not
guaranteed to support every older format. Before upgrading, create an encrypted
backup and store it securely.

Desktop-2FA 0.9.0 changes the public Python API: `Vault.save()` and
`Vault.load()` require an explicit, non-empty password. Vaults created by
earlier Python API versions with no password must be opened and re-saved with a
non-empty password using the previous release before upgrading. CLI and
Textual UI flows already require a non-empty password.

```bash
d2fa backup
```

### Vault Creation

New TOTP secrets use shared Base32 rules: ASCII case and spaces are accepted,
correct trailing padding is optional, and empty decoded keys are refused before
vault access. New records use canonical uppercase padded text with identical
decoded bytes. Existing secret text is preserved on load/save. Legacy empty or
historically admitted Unicode-folded secrets remain listable but cannot generate
codes; `code` reports `invalid_secret` with status 6. See the
[explicit repair procedure](docs/user_manual.md#legacy-invalid-totp-secrets).

Only `vault init`, `list` and `add` create missing vaults. Other content commands
report a missing-vault error. For creation:

1. The CLI prompts for a new password (interactive mode) or requires `--password`/`--password-file` (non-interactive mode)
2. `list` creates an empty encrypted vault; `add` creates one with the validated entry
3. Successful creation prints: `Vault created at <path>`

The Textual UI does not create a missing vault; it displays the vault-loading
error instead.

### Vault Loading

When a command requires a vault and it exists:

1. The CLI prompts for the existing password (interactive mode) or requires credentials (non-interactive mode)
2. The vault is decrypted and loaded
3. Authentication failure exits with status 2; other failures use the shared
   [exit-status contract](docs/user_manual.md#exit-codes) and never report success.

### Duplicate Entry Handling

The `code` and `remove` commands resolve names case-sensitively. An exact
`account_name` match takes precedence over another entry's issuer. Without an
exact account match, a unique issuer match is accepted for compatibility.
Multiple exact account matches or multiple fallback issuer matches are rejected
with an `Ambiguous entry` error (exit status 6); the vault is left unchanged.
`code --json` reports `entry_ambiguous`. Python `Vault.get_entry()` and
`Vault.remove_entry()`, and the public code/removal helpers, use the same rule;
ambiguous lookups raise `desktop_2fa.vault.AmbiguousEntry`, a `ValueError` subclass.

The `rename` command uses the same exact-account-name/unique-issuer rule and
rejects an occupied destination account name before mutation. Ambiguity without
an explicit selector, invalid selectors and occupied destinations exit with
status 6. Both account name and issuer are updated; renaming a uniquely named
entry to itself is allowed and still updates its issuer.

For legacy duplicates, run `d2fa list --indices`, then
`d2fa rename OLD NEW --index N` using a displayed one-based entry number.
The selected entry must match `OLD` at the account-name/issuer tier that ordinary
lookup would use. Indices describe the current list order, not permanent IDs;
list again after adding/removing entries and avoid concurrent vault edits.
See [duplicate recovery](docs/user_manual.md#duplicate-names-in-vault).

---

## 📖 CLI Commands

### Core Commands

| Command | Description |
|---------|-------------|
| `d2fa add <name> <issuer> <secret>` | Add a new TOTP entry |
| `d2fa list` | List all stored TOTP entries |
| `d2fa rename <old> <new>` | Rename an entry |
| `d2fa remove <name>` | Remove an entry |
| `d2fa code <name> [--copy\|--copy-only]` | Generate TOTP code with clipboard copy options |

### Vault Management

| Command | Description |
|---------|-------------|
| `d2fa vault init [--force]` | Initialize a new vault (`d2fa init-vault` is an alias) |
| `d2fa vault unlock` | Open vault with weak password warning (if configured) |
| `d2fa vault change-password` | Change the vault password |
| `d2fa vault path` | Show the currently selected vault path |
| `d2fa backup` | Create an encrypted backup of the vault |
| `d2fa export <path> [--force]` | Export encrypted D2FA v1; existing files require `--force` |
| `d2fa import <path> [--force]` | Import vault from file |
| `d2fa ui` | Launch the early Textual UI prototype |

External-format Python helpers are described in the
[adapter contract](docs/import_adapters.md); they are not CLI import modes.

### Global Options

| Option | Description |
|--------|-------------|
| `--version` | Show the installed version |
| `--password <pwd>` | Provide vault password directly |
| `--password-file <path>` | Read one UTF-8 password line without BOM; preserve spaces |
| `--vault <path>` | Select the vault file; place before the command |
| `--allow-weak-passwords` | Allow weak passwords |
| `--help` | Show command help |

Password files remove only one optional final LF or CRLF. Spaces, tabs and
Unicode remain significant. Older files read with `.strip()` may require an
explicit update to contain the actual previously used password; no alternate
password is tried automatically. See [password-file compatibility](docs/user_manual.md#password-file-format-and-compatibility).

The `--vault` option takes precedence over `DESKTOP_2FA_VAULT`. When neither
is provided, Desktop-2FA uses `~/.desktop-2fa/vault`. The `code` command also
supports `--json`, `--raw`, `--quiet`, `--copy`, and `--copy-only`; `--force`
is available on vault initialization and import commands.

`code --json` writes one JSON success/error object to stdout, including early
option and password errors. `code --raw` prints only the code on success.
Diagnostics and password prompts use stderr; `code --quiet` suppresses both
streams but retains the exit status. See the [output contract](docs/user_manual.md#json-error-format).

---

## 🔒 Security

The vault uses:
- **AES-256-GCM** for authenticated encryption
- **Argon2id** for key derivation (time_cost=4, memory_cost=128MiB, parallelism=2)
- **zxcvbn** for password strength evaluation
- **Versioned header** to identify the vault format

Every command that accesses vault contents requires password authentication.
Path and version queries do not access vault contents. No session-based access.

### Password Strength Evaluation

Desktop-2FA uses **zxcvbn** to evaluate password strength when creating or changing vault passwords:

- **Score 0-2 (Weak)**: Easily guessable passwords (e.g., "password123")
- **Score 3-4 (Strong)**: Resistant to common attacks (recommended)

**Examples:**
- ❌ Weak: `password`, `123456`, `qwerty`, `admin2024`
- ✅ Strong: `Battery-Horse-Staple-Correct`, `Mountain@River*2024`, `MySecureVault#42`

**Configuration** (`~/.config/d2fa/config.toml`):

```toml
[security]
# Require strong passwords (score >= 3)
reject_weak_passwords = false  # warn but allow | true: reject weak passwords
```

When `reject_weak_passwords = false`:
- Weak passwords trigger a diagnostic warning
- User is prompted to confirm continuation
- Password acceptance is non-blocking

When `reject_weak_passwords = true`:
- Weak passwords are rejected immediately
- Command exits with error
- User must choose a stronger password

**Backward Compatibility:**
If you have `min_password_entropy` set in your config (legacy option), it is recognized and treated as equivalent to requiring zxcvbn score >= 3.

### Security Hardening
Version 0.8.2 added bounded vault loading and atomic saves; version 0.8.3 added
the early Textual UI prototype; version 0.9.0 requires explicit, non-empty
passwords in the public Python vault API:
- Empty passwords are immediately rejected with a clear error message
- Permission errors are distinguished from missing vault files
- Vault loading accepts only regular files and reads at most 10 MiB
- Vault saves use unique temporary files and atomic replacement
- Only payload schema 1 is supported; unknown versions and fields are refused
  before a vault can be rewritten and lose metadata.
- Concurrent mutations reject stale revisions under a short OS publication lock;
  status 6 asks you to reload and retry. Empty `.NAME.lock` sidecars remain beside
  vaults. File symlinks and multiply linked files are read-only.
- The CLI boundary maps failures to documented statuses and messages without exception details
- User-friendly error messages for filesystem permission issues
- CLI and cryptographic components are separate modules; this is not a process-isolation guarantee
- zxcvbn-based password strength evaluation


---

## 📚 Documentation

Start at the [documentation index](docs/README.md). Historical audits and
completion reports are archived and are not current verification evidence.

| Document | Description |
|----------|-------------|
| [User Manual](docs/user_manual.md) | Complete usage guide |
| [Security Model](docs/SECURITY.md) | Detailed threat analysis and cryptographic design |
| [CLI UX Specification](docs/ux.md) | UX contract and behavior |
| [Cryptography](docs/crypto.md) | Security implementation details |

---

## 🧪 Testing

See [development commands](docs/development.md) for the project environment,
quality checks and optional coverage measurement. Test counts and coverage
change; use CI results for the exact commit rather than historical totals.

---

## 🏗️ Project Structure

```
src/desktop_2fa/
├── app/           # Retained dormant module paths
├── cli/           # Command-line interface
├── crypto/        # Encryption utilities
├── totp/          # TOTP generation
├── ui_textual/    # Early Textual UI prototype
├── vault/         # Vault management
└── utils/         # Utilities
```

---

## 📄 License

Apache License 2.0. See [LICENSE](LICENSE) file.

---

## 👤 Author

Łukasz Perek

---

## 🏆 Sponsorship

desktop‑2fa is supported through the Kilo OSS Sponsorship Program.

---

## 📧 Contact

For questions or support, contact us at contact@desktop-2fa.org

---

## 💖 Support the Project

Desktop‑2FA is an independent open‑source tool built with a focus on autonomy, transparency, and offline security.
If you find it useful and want to support ongoing development, you can do so through the platforms below:

- **Ko‑fi**: https://ko-fi.com/lukaszperek
- **Buy Me a Coffee**: https://buymeacoffee.com/lukaszperek
- **AirTM**: https://airtm.me/lukper
