passcheck-cli 1.0.0__tar.gz

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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Balaji Mahendra
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.4
2
+ Name: passcheck-cli
3
+ Version: 1.0.0
4
+ Summary: Password security CLI: breach checking (HIBP k-anonymity), secure generation, and ML-powered strength scoring.
5
+ Author: NameRectified
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/NameRectified/passcheck
8
+ Project-URL: Repository, https://github.com/NameRectified/passcheck
9
+ Keywords: password,security,hibp,breach,strength,generator
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: End Users/Desktop
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Security
20
+ Classifier: Topic :: Utilities
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: requests
25
+ Requires-Dist: pyperclip
26
+ Requires-Dist: scikit-learn
27
+ Requires-Dist: joblib
28
+ Dynamic: license-file
29
+
30
+ # PassCheck
31
+
32
+ A cross-platform CLI tool for password security: breach checking via the HIBP API, secure password generation, and ML-powered strength scoring with specific suggestions.
33
+
34
+ ### Flow Diagram
35
+ ```mermaid
36
+ flowchart TD
37
+ CLI["CLI (passcheck.py)"]
38
+ CH["checker.py<br/>HIBP breach check"]
39
+ SC["scorer.py<br/>ML + fallback"]
40
+ GEN["generator.py"]
41
+ ML["ML pipeline<br/>(training/*)"]
42
+
43
+ CLI --> CH
44
+ CLI --> SC
45
+ CLI --> GEN
46
+ SC --> ML
47
+ ```
48
+ ## Quick Install
49
+
50
+ ```bash
51
+ pip install passcheck-cli
52
+ ```
53
+
54
+ Then run `passcheck` anywhere.
55
+
56
+ For development, clone the repo and install in editable mode:
57
+
58
+ ```bash
59
+ git clone https://github.com/NameRectified/passcheck.git
60
+ cd passcheck
61
+ pip install -e .
62
+ ```
63
+
64
+ ## Usage
65
+
66
+ ### Interactive mode
67
+
68
+ ```bash
69
+ passcheck
70
+ ```
71
+
72
+ Shows a menu where you can pick **Check** or **Generate** without remembering flags.
73
+
74
+ ### Check a password
75
+
76
+ ```bash
77
+ passcheck check
78
+ Password: ********
79
+
80
+ Breach Status: Found in 2,266,543 data breaches
81
+ Strength: 25/100 (weak)
82
+
83
+ Suggestions:
84
+ • This password appears in 2,266,543 data breach(es) — never reuse it
85
+ • Add at least one uppercase letter
86
+ • Add at least one special character
87
+ • Avoid sequential characters like '123' or 'abc'
88
+ • Use a mix of upper/lowercase, digits, and special characters
89
+
90
+ Suggested replacement: :_Y8$4Ur/v-&6FuN (copied to clipboard)
91
+ ```
92
+
93
+ You can also pass the password directly:
94
+ ```bash
95
+ passcheck check yourpassword
96
+ ```
97
+ Omitting the argument prompts hidden-ly with `getpass`.
98
+
99
+ ### Generate a password
100
+
101
+ ```bash
102
+ passcheck generate -l 16
103
+
104
+ Generated: G_j2*8TUP8?7
105
+ Strength: 65/100 (strong)
106
+ Copied to clipboard.
107
+ ```
108
+
109
+ - `-l`, `--length`: Password length (default: 16)
110
+
111
+ ## Features
112
+
113
+ - **Breach checking**: Uses the [Have I Been Pwned](https://haveibeenpwned.com/API/v3#PwnedPasswords) API with k-anonymity — never sends the full hash over the network.
114
+ - **Password generation**: Uses `secrets` module. Excludes ambiguous characters (`0`, `O`, `1`, `l`, `I`, `|`). Guarantees at least one uppercase, one lowercase, three digits, and one special character.
115
+ - **ML strength scoring**: RandomForest model trained on 3500 passwords. Scores 0–100 with specific suggestions for improvement.
116
+ - **Specific suggestions**: Suggestions derived from the actual password — not generic templates.
117
+
118
+ ## Requirements
119
+
120
+ - Python 3.10+
121
+ - `requests`, `pyperclip`, `scikit-learn`, `joblib`
122
+
123
+ ## Project Structure
124
+
125
+ ```
126
+ passcheck/
127
+ ├── src/passcheck/
128
+ │ ├── __init__.py Package metadata
129
+ │ ├── cli.py CLI entry point
130
+ │ ├── checker.py Breach checking (HIBP API)
131
+ │ ├── generator.py Password generation
132
+ │ ├── scorer.py ML strength analysis + suggestions
133
+ │ ├── features.py ML feature extraction
134
+ │ ├── config.py Configuration constants
135
+ │ └── models/ Trained model (.pkl, shipped in the wheel)
136
+ ├── training/ ML pipeline (features, dataset, training)
137
+ ├── tests/ pytest test suite (32 tests)
138
+ ├── requirements.txt
139
+ └── pyproject.toml
140
+ ```
141
+
142
+ ## Running Tests
143
+
144
+ ```bash
145
+ pytest tests/
146
+ ```
147
+
148
+ ## License
149
+
150
+ MIT
@@ -0,0 +1,121 @@
1
+ # PassCheck
2
+
3
+ A cross-platform CLI tool for password security: breach checking via the HIBP API, secure password generation, and ML-powered strength scoring with specific suggestions.
4
+
5
+ ### Flow Diagram
6
+ ```mermaid
7
+ flowchart TD
8
+ CLI["CLI (passcheck.py)"]
9
+ CH["checker.py<br/>HIBP breach check"]
10
+ SC["scorer.py<br/>ML + fallback"]
11
+ GEN["generator.py"]
12
+ ML["ML pipeline<br/>(training/*)"]
13
+
14
+ CLI --> CH
15
+ CLI --> SC
16
+ CLI --> GEN
17
+ SC --> ML
18
+ ```
19
+ ## Quick Install
20
+
21
+ ```bash
22
+ pip install passcheck-cli
23
+ ```
24
+
25
+ Then run `passcheck` anywhere.
26
+
27
+ For development, clone the repo and install in editable mode:
28
+
29
+ ```bash
30
+ git clone https://github.com/NameRectified/passcheck.git
31
+ cd passcheck
32
+ pip install -e .
33
+ ```
34
+
35
+ ## Usage
36
+
37
+ ### Interactive mode
38
+
39
+ ```bash
40
+ passcheck
41
+ ```
42
+
43
+ Shows a menu where you can pick **Check** or **Generate** without remembering flags.
44
+
45
+ ### Check a password
46
+
47
+ ```bash
48
+ passcheck check
49
+ Password: ********
50
+
51
+ Breach Status: Found in 2,266,543 data breaches
52
+ Strength: 25/100 (weak)
53
+
54
+ Suggestions:
55
+ • This password appears in 2,266,543 data breach(es) — never reuse it
56
+ • Add at least one uppercase letter
57
+ • Add at least one special character
58
+ • Avoid sequential characters like '123' or 'abc'
59
+ • Use a mix of upper/lowercase, digits, and special characters
60
+
61
+ Suggested replacement: :_Y8$4Ur/v-&6FuN (copied to clipboard)
62
+ ```
63
+
64
+ You can also pass the password directly:
65
+ ```bash
66
+ passcheck check yourpassword
67
+ ```
68
+ Omitting the argument prompts hidden-ly with `getpass`.
69
+
70
+ ### Generate a password
71
+
72
+ ```bash
73
+ passcheck generate -l 16
74
+
75
+ Generated: G_j2*8TUP8?7
76
+ Strength: 65/100 (strong)
77
+ Copied to clipboard.
78
+ ```
79
+
80
+ - `-l`, `--length`: Password length (default: 16)
81
+
82
+ ## Features
83
+
84
+ - **Breach checking**: Uses the [Have I Been Pwned](https://haveibeenpwned.com/API/v3#PwnedPasswords) API with k-anonymity — never sends the full hash over the network.
85
+ - **Password generation**: Uses `secrets` module. Excludes ambiguous characters (`0`, `O`, `1`, `l`, `I`, `|`). Guarantees at least one uppercase, one lowercase, three digits, and one special character.
86
+ - **ML strength scoring**: RandomForest model trained on 3500 passwords. Scores 0–100 with specific suggestions for improvement.
87
+ - **Specific suggestions**: Suggestions derived from the actual password — not generic templates.
88
+
89
+ ## Requirements
90
+
91
+ - Python 3.10+
92
+ - `requests`, `pyperclip`, `scikit-learn`, `joblib`
93
+
94
+ ## Project Structure
95
+
96
+ ```
97
+ passcheck/
98
+ ├── src/passcheck/
99
+ │ ├── __init__.py Package metadata
100
+ │ ├── cli.py CLI entry point
101
+ │ ├── checker.py Breach checking (HIBP API)
102
+ │ ├── generator.py Password generation
103
+ │ ├── scorer.py ML strength analysis + suggestions
104
+ │ ├── features.py ML feature extraction
105
+ │ ├── config.py Configuration constants
106
+ │ └── models/ Trained model (.pkl, shipped in the wheel)
107
+ ├── training/ ML pipeline (features, dataset, training)
108
+ ├── tests/ pytest test suite (32 tests)
109
+ ├── requirements.txt
110
+ └── pyproject.toml
111
+ ```
112
+
113
+ ## Running Tests
114
+
115
+ ```bash
116
+ pytest tests/
117
+ ```
118
+
119
+ ## License
120
+
121
+ MIT
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "passcheck-cli"
7
+ version = "1.0.0"
8
+ description = "Password security CLI: breach checking (HIBP k-anonymity), secure generation, and ML-powered strength scoring."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "NameRectified" }]
13
+ keywords = ["password", "security", "hibp", "breach", "strength", "generator"]
14
+ classifiers = [
15
+ "Development Status :: 5 - Production/Stable",
16
+ "Environment :: Console",
17
+ "Intended Audience :: End Users/Desktop",
18
+ "License :: OSI Approved :: MIT License",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Topic :: Security",
25
+ "Topic :: Utilities",
26
+ ]
27
+ dependencies = [
28
+ "requests",
29
+ "pyperclip",
30
+ "scikit-learn",
31
+ "joblib",
32
+ ]
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/NameRectified/passcheck"
36
+ Repository = "https://github.com/NameRectified/passcheck"
37
+
38
+ [project.scripts]
39
+ passcheck = "passcheck.cli:main"
40
+
41
+ [tool.setuptools]
42
+ package-dir = { "" = "src" }
43
+ packages = ["passcheck"]
44
+
45
+ [tool.setuptools.package-data]
46
+ passcheck = ["models/*.pkl"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ """PassCheck — password security CLI: breach checking, generation, ML strength scoring."""
2
+
3
+ __version__ = "1.0.0"
@@ -0,0 +1,49 @@
1
+ import hashlib
2
+ import logging
3
+
4
+ import requests
5
+
6
+ from passcheck.config import HIBP_API_URL
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ def _sha1_hash(password: str) -> str:
12
+ """Return uppercase SHA-1 hex digest of the given password."""
13
+ return hashlib.sha1(password.encode("utf-8")).hexdigest().upper()
14
+
15
+
16
+ def check_breach(password: str) -> int:
17
+ """Check if a password appears in known data breaches via the HIBP API.
18
+
19
+ Uses the k-anonymity model — only the first 5 characters of the SHA-1 hash
20
+ are sent over the network.
21
+
22
+ Args:
23
+ password: The password to check.
24
+
25
+ Returns:
26
+ The number of times the password appears in breaches (0 if not found).
27
+
28
+ Raises:
29
+ ConnectionError: If the API request fails.
30
+ """
31
+ full_hash = _sha1_hash(password)
32
+ prefix, suffix = full_hash[:5], full_hash[5:]
33
+
34
+ logger.debug("Checking breach for hash prefix %s", prefix)
35
+
36
+ try:
37
+ response = requests.get(HIBP_API_URL + prefix, timeout=10)
38
+ response.raise_for_status()
39
+ except requests.RequestException as exc:
40
+ raise ConnectionError(f"Failed to reach HIBP API: {exc}") from exc
41
+
42
+ for line in response.text.splitlines():
43
+ hash_suffix, count = line.split(":")
44
+ if hash_suffix == suffix:
45
+ logger.info("Password found in %s breach(es)", count)
46
+ return int(count)
47
+
48
+ logger.info("Password not found in any known breaches")
49
+ return 0
@@ -0,0 +1,193 @@
1
+ #!/usr/bin/env python3.11
2
+
3
+ import argparse
4
+ import getpass
5
+ import logging
6
+ import sys
7
+
8
+ import pyperclip
9
+
10
+ from passcheck import checker, config, generator, scorer
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+ # ANSI escape codes for terminal text coloring.
15
+ # \033[92m = green, \033[94m = blue, \033[93m = yellow, \033[91m = red.
16
+ # \033[0m resets formatting back to default.
17
+ _STRENGTH_LABELS = {
18
+ "very_strong": "\033[92m",
19
+ "strong": "\033[94m",
20
+ "fair": "\033[93m",
21
+ "weak": "\033[91m",
22
+ }
23
+ _RESET = "\033[0m"
24
+
25
+ _BANNER = r"""
26
+ +-----------------------------+
27
+ | P A S S C H E C K |
28
+ | Password Security Tool |
29
+ +-----------------------------+
30
+ """
31
+
32
+
33
+ def _color_strength(strength: str) -> str:
34
+ """Wrap a strength label in ANSI color codes for terminal output."""
35
+ color = _STRENGTH_LABELS.get(strength, "")
36
+ return f"{color}{strength}{_RESET}" if color else strength
37
+
38
+
39
+ def _run_check(password: str) -> None:
40
+ """Run breach check + score + suggestions for a given password."""
41
+ logger.info("Checking password...")
42
+
43
+ try:
44
+ breach_count = checker.check_breach(password)
45
+ except ConnectionError as exc:
46
+ print(f"Error: {exc}")
47
+ return
48
+
49
+ analysis = scorer.analyze_password(password)
50
+ suggestions = scorer.get_suggestions(password, breach_count, analysis)
51
+
52
+ print()
53
+ if breach_count > 0:
54
+ print(f"Breach Status: Found in {breach_count:,} data breaches")
55
+ else:
56
+ print("Breach Status: Not found in known breaches")
57
+ print(
58
+ f"Strength: {analysis['score']}/100 "
59
+ f"({_color_strength(analysis['strength'])})"
60
+ )
61
+ print()
62
+
63
+ needs_replacement = breach_count > 0 or analysis["score"] < 60
64
+ if suggestions:
65
+ print("Suggestions:")
66
+ for s in suggestions:
67
+ print(f" \u2022 {s}") # \u2022 = bullet character (•)
68
+ print()
69
+
70
+ if needs_replacement:
71
+ replacement = generator.generate_password()
72
+ pyperclip.copy(replacement)
73
+ print(f"Suggested replacement: {replacement} (copied to clipboard)")
74
+ else:
75
+ pyperclip.copy(password)
76
+ print("Password is safe. Copied to clipboard.")
77
+
78
+
79
+ def _run_generate(length: int) -> None:
80
+ """Generate a strong password and display its score."""
81
+ password = generator.generate_password(length=length)
82
+ analysis = scorer.analyze_password(password)
83
+ pyperclip.copy(password)
84
+
85
+ print()
86
+ print(f"Generated: {password}")
87
+ print(
88
+ f"Strength: {analysis['score']}/100 "
89
+ f"({_color_strength(analysis['strength'])})"
90
+ )
91
+ print("Copied to clipboard.")
92
+
93
+
94
+ def cmd_check(args: argparse.Namespace) -> None:
95
+ """CLI subcommand: check a password."""
96
+ password = args.password or getpass.getpass("Password: ")
97
+ _run_check(password)
98
+
99
+
100
+ def cmd_generate(args: argparse.Namespace) -> None:
101
+ """CLI subcommand: generate a password."""
102
+ _run_generate(args.length)
103
+
104
+
105
+ def interactive_mode() -> None:
106
+ """Show a menu and run the selected action in a loop."""
107
+ print(_BANNER)
108
+ print()
109
+
110
+ while True:
111
+ print("\n[1] Check a password")
112
+ print("[2] Generate a password")
113
+ print("[3] Exit")
114
+ choice = input("\nSelect an option (1-3): ").strip()
115
+
116
+ if choice == "1":
117
+ password = getpass.getpass("Password: ")
118
+ _run_check(password)
119
+ if input("\nPress Enter to continue, or x to exit: ").lower() == "x":
120
+ break
121
+
122
+ elif choice == "2":
123
+ length_input = input(f"Length (default {config.DEFAULT_LENGTH}): ").strip()
124
+ length = int(length_input) if length_input else config.DEFAULT_LENGTH
125
+ _run_generate(length)
126
+ if input("\nPress Enter to continue, or x to exit: ").lower() == "x":
127
+ break
128
+
129
+ elif choice == "3":
130
+ print("Goodbye.")
131
+ break
132
+
133
+ else:
134
+ print(f"Invalid option '{choice}'. Enter 1, 2, or 3.")
135
+
136
+
137
+ def create_parser() -> argparse.ArgumentParser:
138
+ """Build the argument parser with check and generate subcommands."""
139
+ parser = argparse.ArgumentParser(
140
+ prog="passcheck",
141
+ description="Password security tool — check breaches, generate passwords, score strength.",
142
+ )
143
+ subparsers = parser.add_subparsers(
144
+ title="commands",
145
+ dest="command",
146
+ )
147
+
148
+ check_parser = subparsers.add_parser(
149
+ "check",
150
+ help="Check a password for breaches and get a strength score",
151
+ )
152
+ check_parser.add_argument(
153
+ "password",
154
+ nargs="?",
155
+ help="Password to check (omit for hidden prompt)",
156
+ )
157
+ check_parser.set_defaults(func=cmd_check)
158
+
159
+ generate_parser = subparsers.add_parser(
160
+ "generate",
161
+ help="Generate a strong random password",
162
+ )
163
+ generate_parser.add_argument(
164
+ "-l",
165
+ "--length",
166
+ type=int,
167
+ default=config.DEFAULT_LENGTH,
168
+ help="Password length (default: %(default)s)",
169
+ )
170
+ generate_parser.set_defaults(func=cmd_generate)
171
+
172
+ return parser
173
+
174
+
175
+ def main() -> None:
176
+ """Entry point: set up logging, parse args, dispatch or enter interactive mode."""
177
+ logging.basicConfig(
178
+ # Only show WARNING and above; change to logging.DEBUG for verbose output.
179
+ level=logging.WARNING,
180
+ format="%(levelname)s: %(message)s",
181
+ )
182
+
183
+ parser = create_parser()
184
+ args = parser.parse_args()
185
+
186
+ if args.command is None:
187
+ interactive_mode()
188
+ else:
189
+ args.func(args)
190
+
191
+
192
+ if __name__ == "__main__":
193
+ main()
@@ -0,0 +1,12 @@
1
+ from pathlib import Path
2
+
3
+ HIBP_API_URL: str = "https://api.pwnedpasswords.com/range/"
4
+
5
+ DEFAULT_LENGTH: int = 16
6
+ MIN_LENGTH: int = 8
7
+ MIN_DIGITS: int = 3
8
+ MIN_SPECIAL: int = 1
9
+
10
+ EXCLUDED_CHARS: str = "0O1lI|"
11
+
12
+ PROJECT_ROOT: Path = Path(__file__).parent
@@ -0,0 +1,109 @@
1
+ import math
2
+ import string
3
+
4
+
5
+ def extract_features(password: str) -> dict[str, float]:
6
+ """Convert a password into a dict of numeric features for the ML model.
7
+
8
+ The model can't read raw text — it needs numbers. Each feature
9
+ captures some property of the password (length, character diversity,
10
+ patterns, etc.).
11
+
12
+ Args:
13
+ password: The password string to analyze.
14
+
15
+ Returns:
16
+ A dict mapping feature names to numeric values.
17
+ """
18
+ length = len(password)
19
+ lower = sum(c.islower() for c in password)
20
+ upper = sum(c.isupper() for c in password)
21
+ digits = sum(c.isdigit() for c in password)
22
+ special = sum(c in string.punctuation for c in password)
23
+
24
+ # Shannon entropy: measures how random the password is.
25
+ # Higher entropy = harder to guess (typically stronger).
26
+ entropy = 0.0
27
+ if length:
28
+ unique_chars = len(set(password))
29
+ entropy = math.log2(unique_chars) * length
30
+
31
+ sequential_count = _count_sequential(password)
32
+ repeated_count = _count_repeats(password)
33
+
34
+ return {
35
+ "length": length,
36
+ "lowercase_count": lower,
37
+ "uppercase_count": upper,
38
+ "digit_count": digits,
39
+ "special_count": special,
40
+ # Ratios are scale-invariant — a 10-char pw with 3 digits
41
+ # has the same ratio as a 20-char pw with 6 digits.
42
+ "lowercase_ratio": lower / length if length else 0.0,
43
+ "uppercase_ratio": upper / length if length else 0.0,
44
+ "digit_ratio": digits / length if length else 0.0,
45
+ "special_ratio": special / length if length else 0.0,
46
+ "unique_chars": len(set(password)),
47
+ "entropy": entropy,
48
+ # Binary flags are useful for tree-based models — they create
49
+ # clean split points (e.g., "has_uppercase >= 0.5").
50
+ "has_lowercase": float(lower > 0),
51
+ "has_uppercase": float(upper > 0),
52
+ "has_digit": float(digits > 0),
53
+ "has_special": float(special > 0),
54
+ "sequential_runs": sequential_count,
55
+ "repeated_groups": repeated_count,
56
+ }
57
+
58
+
59
+ def _count_sequential(password: str) -> int:
60
+ """Count 3+ character sequential patterns (abc, bcd, 123, 234, etc.).
61
+
62
+ Sequential characters are common in weak passwords and make them
63
+ easier to guess.
64
+
65
+ Args:
66
+ password: The password to scan.
67
+
68
+ Returns:
69
+ Number of 3-char sequential runs found.
70
+ """
71
+ sequences = ["abcdefghijklmnopqrstuvwxyz", "0123456789"]
72
+ lowered = password.lower()
73
+ count = 0
74
+ for seq in sequences:
75
+ for i in range(len(seq) - 2):
76
+ if seq[i : i + 3] in lowered:
77
+ count += 1
78
+ return count
79
+
80
+
81
+ def _count_repeats(password: str) -> int:
82
+ """Count how many characters appear 3+ times consecutively (aaa, bbbb, etc.).
83
+
84
+ Repeated characters reduce password entropy and often appear in
85
+ weak passwords.
86
+
87
+ Args:
88
+ password: The password to scan.
89
+
90
+ Returns:
91
+ Number of repeat groups found (each distinct character counted once).
92
+ """
93
+ count = 0
94
+ run = 1
95
+ for i in range(1, len(password)):
96
+ if password[i] == password[i - 1]:
97
+ run += 1
98
+ else:
99
+ if run >= 3:
100
+ count += 1
101
+ run = 1
102
+ if run >= 3:
103
+ count += 1
104
+ return count
105
+
106
+
107
+ # Column order for the model's feature matrix. Must be consistent
108
+ # between training (train.py) and inference (scorer.py).
109
+ FEATURE_NAMES = list(extract_features("").keys())
@@ -0,0 +1,58 @@
1
+ import logging
2
+ import string
3
+ import secrets
4
+
5
+ from passcheck.config import DEFAULT_LENGTH, EXCLUDED_CHARS, MIN_DIGITS, MIN_SPECIAL
6
+
7
+ logger = logging.getLogger(__name__)
8
+
9
+ AMBIGUOUS: str = EXCLUDED_CHARS
10
+
11
+
12
+ def _build_pool(exclude_ambiguous: bool) -> str:
13
+ pool = string.ascii_letters + string.digits + string.punctuation
14
+ if exclude_ambiguous:
15
+ for ch in AMBIGUOUS:
16
+ pool = pool.replace(ch, "")
17
+ return pool
18
+
19
+
20
+ def _meets_criteria(
21
+ password: str,
22
+ min_digits: int,
23
+ min_special: int,
24
+ ) -> bool:
25
+ digit_count = sum(c.isdigit() for c in password)
26
+ special_count = sum(c in string.punctuation for c in password)
27
+ return (
28
+ any(c.islower() for c in password)
29
+ and any(c.isupper() for c in password)
30
+ and digit_count >= min_digits
31
+ and special_count >= min_special
32
+ )
33
+
34
+
35
+ def generate_password(
36
+ length: int = DEFAULT_LENGTH,
37
+ min_digits: int = MIN_DIGITS,
38
+ min_special: int = MIN_SPECIAL,
39
+ exclude_ambiguous: bool = True,
40
+ ) -> str:
41
+ """Generate a cryptographically secure password.
42
+
43
+ Args:
44
+ length: Total character length of the password.
45
+ min_digits: Minimum number of digits required.
46
+ min_special: Minimum number of special characters required.
47
+ exclude_ambiguous: If True, exclude characters like 0/O/1/l/I.
48
+
49
+ Returns:
50
+ A random password string that meets all criteria.
51
+ """
52
+ pool = _build_pool(exclude_ambiguous)
53
+
54
+ while True:
55
+ password = "".join(secrets.choice(pool) for _ in range(length))
56
+ if _meets_criteria(password, min_digits, min_special):
57
+ logger.debug("Generated password of length %d", length)
58
+ return password
@@ -0,0 +1,157 @@
1
+ import logging
2
+ import string
3
+ from pathlib import Path
4
+
5
+ import joblib
6
+
7
+ from passcheck.config import MIN_LENGTH
8
+ from passcheck.features import FEATURE_NAMES, _count_sequential, extract_features
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ _MODEL: object | None = None
13
+ _MODEL_PATH: Path = Path(__file__).parent / "models" / "strength_model.pkl"
14
+
15
+
16
+ def _load_model():
17
+ global _MODEL
18
+ if _MODEL is None and _MODEL_PATH.exists():
19
+ _MODEL = joblib.load(_MODEL_PATH)
20
+ logger.info("Loaded ML model from %s", _MODEL_PATH)
21
+ return _MODEL
22
+
23
+
24
+ def _heuristic_issues(password: str) -> list[str]:
25
+ issues: list[str] = []
26
+ length = len(password)
27
+ if length < MIN_LENGTH:
28
+ issues.append("too_short")
29
+ if not any(c.islower() for c in password):
30
+ issues.append("no_lowercase")
31
+ if not any(c.isupper() for c in password):
32
+ issues.append("no_uppercase")
33
+ if not any(c.isdigit() for c in password):
34
+ issues.append("no_digit")
35
+ if not any(c in string.punctuation for c in password):
36
+ issues.append("no_special")
37
+ if _count_sequential(password) > 0:
38
+ issues.append("sequential_chars")
39
+ issues.extend(_detect_repeats(password))
40
+ return issues
41
+
42
+
43
+ def _detect_repeats(password: str) -> list[str]:
44
+ seen: set[str] = set()
45
+ issues: list[str] = []
46
+ count = 1
47
+ for i in range(1, len(password)):
48
+ if password[i] == password[i - 1]:
49
+ count += 1
50
+ else:
51
+ if count >= 3:
52
+ ch = password[i - 1]
53
+ issue = f"repeated_char_{ch}"
54
+ if issue not in seen:
55
+ seen.add(issue)
56
+ issues.append(issue)
57
+ count = 1
58
+ if count >= 3:
59
+ ch = password[-1]
60
+ issue = f"repeated_char_{ch}"
61
+ if issue not in seen:
62
+ seen.add(issue)
63
+ issues.append(issue)
64
+ return issues
65
+
66
+
67
+ def analyze_password(password: str) -> dict:
68
+ """Analyze password strength using a trained ML model.
69
+
70
+ Falls back to heuristic scoring if the model is not available.
71
+
72
+ Args:
73
+ password: The password to analyze.
74
+
75
+ Returns:
76
+ A dict with keys:
77
+ score (int): 0–100.
78
+ strength (str): "weak", "fair", "strong", or "very_strong".
79
+ issues (list[str]): Machine-readable issue codes.
80
+ """
81
+ model = _load_model()
82
+
83
+ if model is not None:
84
+ features = extract_features(password)
85
+ row = [[features[name] for name in FEATURE_NAMES]]
86
+ raw_score = float(model.predict(row)[0])
87
+ score = max(0, min(100, round(raw_score)))
88
+ else:
89
+ score = 50
90
+
91
+ issues = _heuristic_issues(password)
92
+
93
+ if score >= 80:
94
+ strength = "very_strong"
95
+ elif score >= 60:
96
+ strength = "strong"
97
+ elif score >= 40:
98
+ strength = "fair"
99
+ else:
100
+ strength = "weak"
101
+
102
+ logger.debug("Password scored %d/100 (%s)", score, strength)
103
+ return {"score": score, "strength": strength, "issues": issues}
104
+
105
+
106
+ def get_suggestions(
107
+ password: str,
108
+ breach_count: int,
109
+ analysis: dict,
110
+ ) -> list[str]:
111
+ """Generate human-readable, password-specific suggestions.
112
+
113
+ Args:
114
+ password: The original password.
115
+ breach_count: Number of breaches found (0 if clean).
116
+ analysis: Result from analyze_password().
117
+
118
+ Returns:
119
+ A list of suggestion strings (2–5 items).
120
+ """
121
+ suggestions: list[str] = []
122
+ issues = analysis["issues"]
123
+
124
+ if breach_count > 0:
125
+ suggestions.append(
126
+ f"This password appears in {breach_count:,} data breach(es) — never reuse it"
127
+ )
128
+
129
+ issue_map: dict[str, str] = {
130
+ "too_short": (
131
+ f"Password is only {len(password)} characters "
132
+ f"(aim for {MIN_LENGTH}+)"
133
+ ),
134
+ "no_lowercase": "Add at least one lowercase letter",
135
+ "no_uppercase": "Add at least one uppercase letter",
136
+ "no_digit": "Add at least one digit",
137
+ "no_special": "Add at least one special character",
138
+ "sequential_chars": (
139
+ "Avoid sequential characters like '123' or 'abc'"
140
+ ),
141
+ }
142
+
143
+ for issue in issues:
144
+ if issue.startswith("repeated_char_"):
145
+ ch = issue[-1]
146
+ count = password.count(ch)
147
+ suggestions.append(
148
+ f"Repeated character '{ch}' appears {count} times"
149
+ )
150
+ elif issue in issue_map:
151
+ suggestions.append(issue_map[issue])
152
+
153
+ suggestions.append(
154
+ "Use a mix of upper/lowercase, digits, and special characters"
155
+ )
156
+
157
+ return suggestions[:5]
@@ -0,0 +1,150 @@
1
+ Metadata-Version: 2.4
2
+ Name: passcheck-cli
3
+ Version: 1.0.0
4
+ Summary: Password security CLI: breach checking (HIBP k-anonymity), secure generation, and ML-powered strength scoring.
5
+ Author: NameRectified
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/NameRectified/passcheck
8
+ Project-URL: Repository, https://github.com/NameRectified/passcheck
9
+ Keywords: password,security,hibp,breach,strength,generator
10
+ Classifier: Development Status :: 5 - Production/Stable
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: End Users/Desktop
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Security
20
+ Classifier: Topic :: Utilities
21
+ Requires-Python: >=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: requests
25
+ Requires-Dist: pyperclip
26
+ Requires-Dist: scikit-learn
27
+ Requires-Dist: joblib
28
+ Dynamic: license-file
29
+
30
+ # PassCheck
31
+
32
+ A cross-platform CLI tool for password security: breach checking via the HIBP API, secure password generation, and ML-powered strength scoring with specific suggestions.
33
+
34
+ ### Flow Diagram
35
+ ```mermaid
36
+ flowchart TD
37
+ CLI["CLI (passcheck.py)"]
38
+ CH["checker.py<br/>HIBP breach check"]
39
+ SC["scorer.py<br/>ML + fallback"]
40
+ GEN["generator.py"]
41
+ ML["ML pipeline<br/>(training/*)"]
42
+
43
+ CLI --> CH
44
+ CLI --> SC
45
+ CLI --> GEN
46
+ SC --> ML
47
+ ```
48
+ ## Quick Install
49
+
50
+ ```bash
51
+ pip install passcheck-cli
52
+ ```
53
+
54
+ Then run `passcheck` anywhere.
55
+
56
+ For development, clone the repo and install in editable mode:
57
+
58
+ ```bash
59
+ git clone https://github.com/NameRectified/passcheck.git
60
+ cd passcheck
61
+ pip install -e .
62
+ ```
63
+
64
+ ## Usage
65
+
66
+ ### Interactive mode
67
+
68
+ ```bash
69
+ passcheck
70
+ ```
71
+
72
+ Shows a menu where you can pick **Check** or **Generate** without remembering flags.
73
+
74
+ ### Check a password
75
+
76
+ ```bash
77
+ passcheck check
78
+ Password: ********
79
+
80
+ Breach Status: Found in 2,266,543 data breaches
81
+ Strength: 25/100 (weak)
82
+
83
+ Suggestions:
84
+ • This password appears in 2,266,543 data breach(es) — never reuse it
85
+ • Add at least one uppercase letter
86
+ • Add at least one special character
87
+ • Avoid sequential characters like '123' or 'abc'
88
+ • Use a mix of upper/lowercase, digits, and special characters
89
+
90
+ Suggested replacement: :_Y8$4Ur/v-&6FuN (copied to clipboard)
91
+ ```
92
+
93
+ You can also pass the password directly:
94
+ ```bash
95
+ passcheck check yourpassword
96
+ ```
97
+ Omitting the argument prompts hidden-ly with `getpass`.
98
+
99
+ ### Generate a password
100
+
101
+ ```bash
102
+ passcheck generate -l 16
103
+
104
+ Generated: G_j2*8TUP8?7
105
+ Strength: 65/100 (strong)
106
+ Copied to clipboard.
107
+ ```
108
+
109
+ - `-l`, `--length`: Password length (default: 16)
110
+
111
+ ## Features
112
+
113
+ - **Breach checking**: Uses the [Have I Been Pwned](https://haveibeenpwned.com/API/v3#PwnedPasswords) API with k-anonymity — never sends the full hash over the network.
114
+ - **Password generation**: Uses `secrets` module. Excludes ambiguous characters (`0`, `O`, `1`, `l`, `I`, `|`). Guarantees at least one uppercase, one lowercase, three digits, and one special character.
115
+ - **ML strength scoring**: RandomForest model trained on 3500 passwords. Scores 0–100 with specific suggestions for improvement.
116
+ - **Specific suggestions**: Suggestions derived from the actual password — not generic templates.
117
+
118
+ ## Requirements
119
+
120
+ - Python 3.10+
121
+ - `requests`, `pyperclip`, `scikit-learn`, `joblib`
122
+
123
+ ## Project Structure
124
+
125
+ ```
126
+ passcheck/
127
+ ├── src/passcheck/
128
+ │ ├── __init__.py Package metadata
129
+ │ ├── cli.py CLI entry point
130
+ │ ├── checker.py Breach checking (HIBP API)
131
+ │ ├── generator.py Password generation
132
+ │ ├── scorer.py ML strength analysis + suggestions
133
+ │ ├── features.py ML feature extraction
134
+ │ ├── config.py Configuration constants
135
+ │ └── models/ Trained model (.pkl, shipped in the wheel)
136
+ ├── training/ ML pipeline (features, dataset, training)
137
+ ├── tests/ pytest test suite (32 tests)
138
+ ├── requirements.txt
139
+ └── pyproject.toml
140
+ ```
141
+
142
+ ## Running Tests
143
+
144
+ ```bash
145
+ pytest tests/
146
+ ```
147
+
148
+ ## License
149
+
150
+ MIT
@@ -0,0 +1,21 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/passcheck/__init__.py
5
+ src/passcheck/checker.py
6
+ src/passcheck/cli.py
7
+ src/passcheck/config.py
8
+ src/passcheck/features.py
9
+ src/passcheck/generator.py
10
+ src/passcheck/scorer.py
11
+ src/passcheck/models/strength_model.pkl
12
+ src/passcheck_cli.egg-info/PKG-INFO
13
+ src/passcheck_cli.egg-info/SOURCES.txt
14
+ src/passcheck_cli.egg-info/dependency_links.txt
15
+ src/passcheck_cli.egg-info/entry_points.txt
16
+ src/passcheck_cli.egg-info/requires.txt
17
+ src/passcheck_cli.egg-info/top_level.txt
18
+ tests/test_checker.py
19
+ tests/test_generator.py
20
+ tests/test_ml_scorer.py
21
+ tests/test_scorer.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ passcheck = passcheck.cli:main
@@ -0,0 +1,4 @@
1
+ requests
2
+ pyperclip
3
+ scikit-learn
4
+ joblib
@@ -0,0 +1,43 @@
1
+ from unittest.mock import patch
2
+
3
+ import pytest
4
+ import requests
5
+
6
+ from passcheck.checker import _sha1_hash, check_breach
7
+
8
+
9
+ class TestSha1Hash:
10
+ def test_returns_uppercase_hex(self) -> None:
11
+ result = _sha1_hash("hello")
12
+ assert result == "AAF4C61DDCC5E8A2DABEDE0F3B482CD9AEA9434D"
13
+
14
+ def test_different_passwords_different_hashes(self) -> None:
15
+ assert _sha1_hash("abc") != _sha1_hash("xyz")
16
+
17
+
18
+ class TestCheckBreach:
19
+ @patch("passcheck.checker.requests.get")
20
+ def test_returns_count_when_hash_found(self, mock_get) -> None:
21
+ mock_get.return_value.status_code = 200
22
+ mock_get.return_value.text = (
23
+ "0018A45C4D1DEF81644B54AB7F969B88D65:1\n"
24
+ "00D4F6E8CB6C2DBB9F0C9C1C3B7E0A9B8C7:5\n"
25
+ )
26
+
27
+ count = check_breach("P@ssw0rd")
28
+ assert count == 0
29
+
30
+ @patch("passcheck.checker.requests.get")
31
+ def test_returns_zero_when_not_found(self, mock_get) -> None:
32
+ mock_get.return_value.status_code = 200
33
+ mock_get.return_value.text = "SOMEOTH:999\nANOTHER:2\n"
34
+
35
+ count = check_breach("not_breached_unique_xyz")
36
+ assert count == 0
37
+
38
+ @patch("passcheck.checker.requests.get")
39
+ def test_raises_on_network_error(self, mock_get) -> None:
40
+ mock_get.side_effect = requests.ConnectionError("no network")
41
+
42
+ with pytest.raises(ConnectionError):
43
+ check_breach("anything")
@@ -0,0 +1,41 @@
1
+ import string
2
+
3
+ from passcheck.generator import generate_password
4
+
5
+
6
+ class TestGeneratePassword:
7
+ def test_default_length(self) -> None:
8
+ pw = generate_password()
9
+ assert len(pw) == 16
10
+
11
+ def test_custom_length(self) -> None:
12
+ pw = generate_password(length=24)
13
+ assert len(pw) == 24
14
+
15
+ def test_has_lowercase(self) -> None:
16
+ pw = generate_password()
17
+ assert any(c.islower() for c in pw)
18
+
19
+ def test_has_uppercase(self) -> None:
20
+ pw = generate_password()
21
+ assert any(c.isupper() for c in pw)
22
+
23
+ def test_has_digits(self) -> None:
24
+ pw = generate_password(min_digits=4)
25
+ assert sum(c.isdigit() for c in pw) >= 4
26
+
27
+ def test_has_special_chars(self) -> None:
28
+ pw = generate_password(min_special=2)
29
+ assert sum(c in string.punctuation for c in pw) >= 2
30
+
31
+ def test_excludes_ambiguous_chars(self) -> None:
32
+ pw = generate_password(exclude_ambiguous=True)
33
+ assert not any(c in "0O1lI|" for c in pw)
34
+
35
+ def test_unique_results(self) -> None:
36
+ results = {generate_password() for _ in range(20)}
37
+ assert len(results) == 20
38
+
39
+ def test_minimal_length(self) -> None:
40
+ pw = generate_password(length=4, min_digits=1, min_special=1)
41
+ assert len(pw) == 4
@@ -0,0 +1,44 @@
1
+ import pytest
2
+
3
+ from passcheck.scorer import _MODEL_PATH, analyze_password, _load_model
4
+
5
+
6
+ class TestModelLoading:
7
+ def test_model_file_exists(self) -> None:
8
+ assert _MODEL_PATH.exists(), "Trained model not found — run training/train.py first"
9
+
10
+ def test_model_loads_successfully(self) -> None:
11
+ model = _load_model()
12
+ assert model is not None
13
+
14
+ def test_model_has_feature_importances(self) -> None:
15
+ model = _load_model()
16
+ assert hasattr(model, "feature_importances_")
17
+ assert len(model.feature_importances_) == 17
18
+
19
+
20
+ class TestMLScoring:
21
+ @pytest.fixture(autouse=True)
22
+ def ensure_model(self) -> None:
23
+ if _load_model() is None:
24
+ pytest.skip("Model not found — run training/train.py first")
25
+
26
+ def test_weak_password_scores_low(self) -> None:
27
+ result = analyze_password("123456")
28
+ assert result["score"] < 40
29
+ assert result["strength"] == "weak"
30
+
31
+ def test_strong_password_scores_high(self) -> None:
32
+ result = analyze_password("Kd9#mP2$xL8@qR5zA7&")
33
+ assert result["score"] >= 80
34
+ assert result["strength"] in ("strong", "very_strong")
35
+
36
+ def test_score_is_within_bounds(self) -> None:
37
+ for pw in ["a", "abc", "password", "Hello123!", "Kd9#mP2$xL8@qR5zA7&"]:
38
+ result = analyze_password(pw)
39
+ assert 0 <= result["score"] <= 100
40
+
41
+ def test_issues_are_returned(self) -> None:
42
+ result = analyze_password("abc")
43
+ assert isinstance(result["issues"], list)
44
+ assert len(result["issues"]) > 0
@@ -0,0 +1,66 @@
1
+ from passcheck.scorer import analyze_password, get_suggestions
2
+
3
+
4
+ class TestAnalyzePassword:
5
+ def test_short_password_is_weak(self) -> None:
6
+ result = analyze_password("ab")
7
+ assert result["score"] <= 20
8
+ assert result["strength"] == "weak"
9
+ assert "too_short" in result["issues"]
10
+
11
+ def test_long_and_diverse_is_very_strong(self) -> None:
12
+ result = analyze_password("Kd9#mP2$xL8@qR5zA7&")
13
+ assert result["score"] >= 70
14
+ assert result["strength"] in ("strong", "very_strong")
15
+
16
+ def test_detects_missing_uppercase(self) -> None:
17
+ result = analyze_password("abcdef123!")
18
+ assert "no_uppercase" in result["issues"]
19
+
20
+ def test_detects_missing_digit(self) -> None:
21
+ result = analyze_password("Abcdefgh!")
22
+ assert "no_digit" in result["issues"]
23
+
24
+ def test_detects_missing_special(self) -> None:
25
+ result = analyze_password("Abcdef123")
26
+ assert "no_special" in result["issues"]
27
+
28
+ def test_detects_sequential_chars(self) -> None:
29
+ result = analyze_password("abcXYZ789!")
30
+ assert "sequential_chars" in result["issues"]
31
+
32
+ def test_detects_repeated_chars(self) -> None:
33
+ result = analyze_password("Aaaabc123!")
34
+ assert any(i.startswith("repeated_char_") for i in result["issues"])
35
+
36
+
37
+ class TestGetSuggestions:
38
+ def test_breach_suggestion_included(self) -> None:
39
+ analysis = {"score": 30, "strength": "weak", "issues": ["too_short"]}
40
+ suggestions = get_suggestions("abc", breach_count=50, analysis=analysis)
41
+ assert any("breach" in s.lower() for s in suggestions)
42
+
43
+ def test_no_breach_suggestion_when_zero(self) -> None:
44
+ analysis = {"score": 95, "strength": "very_strong", "issues": []}
45
+ suggestions = get_suggestions("Str0ng!Pass#", breach_count=0, analysis=analysis)
46
+ assert not any("breach" in s.lower() for s in suggestions)
47
+
48
+ def test_max_five_suggestions(self) -> None:
49
+ analysis = {
50
+ "score": 10,
51
+ "strength": "weak",
52
+ "issues": [
53
+ "too_short",
54
+ "no_uppercase",
55
+ "no_digit",
56
+ "no_special",
57
+ "sequential_chars",
58
+ ],
59
+ }
60
+ suggestions = get_suggestions("abc", breach_count=100, analysis=analysis)
61
+ assert len(suggestions) <= 5
62
+
63
+ def test_suggestions_are_strings(self) -> None:
64
+ analysis = {"score": 50, "strength": "fair", "issues": ["no_uppercase"]}
65
+ suggestions = get_suggestions("hello", breach_count=0, analysis=analysis)
66
+ assert all(isinstance(s, str) for s in suggestions)