pasteval 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
pasteval/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """Pasteval: redact sensitive information from text before sharing it."""
2
+
3
+ __version__ = "0.0.1"
pasteval/__main__.py ADDED
@@ -0,0 +1,8 @@
1
+ """Lets `python -m pasteval` behave like the `pasteval` command."""
2
+
3
+ import sys
4
+
5
+ from pasteval.cli import main
6
+
7
+ if __name__ == "__main__":
8
+ sys.exit(main())
pasteval/cli.py ADDED
@@ -0,0 +1,97 @@
1
+ """Command-line interface: reading input, writing output, exit codes.
2
+
3
+ No detection logic lives here. Sanitized text goes to stdout; everything else
4
+ (hints, summaries, errors) goes to stderr so stdout can be piped safely.
5
+
6
+ Exit codes: 0 success, 1 runtime error, 2 usage error (set by argparse).
7
+ """
8
+
9
+ import argparse
10
+ import sys
11
+ from collections.abc import Sequence
12
+ from pathlib import Path
13
+
14
+ from pasteval import __version__
15
+ from pasteval.redactor import RedactionResult, redact
16
+
17
+ EXIT_OK = 0
18
+ EXIT_ERROR = 1
19
+
20
+
21
+ def build_parser() -> argparse.ArgumentParser:
22
+ parser = argparse.ArgumentParser(
23
+ prog="pasteval",
24
+ description=(
25
+ "Redact sensitive information from text before sharing it. "
26
+ "Reads standard input (paste or pipe) unless --file is given, "
27
+ "and prints the redacted text to standard output."
28
+ ),
29
+ )
30
+ parser.add_argument(
31
+ "--file",
32
+ type=Path,
33
+ metavar="PATH",
34
+ help="read a UTF-8 text file instead of standard input",
35
+ )
36
+ parser.add_argument(
37
+ "--version", action="version", version=f"pasteval {__version__}"
38
+ )
39
+ return parser
40
+
41
+
42
+ def _read_input(file: Path | None) -> str:
43
+ """Read all input as UTF-8.
44
+
45
+ We read bytes and decode them ourselves so line endings (\\n or \\r\\n)
46
+ arrive exactly as they were written.
47
+ """
48
+ if file is not None:
49
+ return file.read_bytes().decode("utf-8")
50
+ if sys.stdin.isatty():
51
+ print(
52
+ "Paste your text, then press Ctrl+D on a new line to finish "
53
+ "(Ctrl+Z then Enter on Windows).",
54
+ file=sys.stderr,
55
+ )
56
+ return sys.stdin.buffer.read().decode("utf-8")
57
+
58
+
59
+ def _summary(result: RedactionResult) -> str:
60
+ """Describe what was redacted using type names and counts only."""
61
+ total = sum(result.counts.values())
62
+ if total == 0:
63
+ return "pasteval: nothing to redact."
64
+ details = ", ".join(f"{count} {name}" for name, count in result.counts.items())
65
+ noun = "item" if total == 1 else "items"
66
+ return f"pasteval: redacted {total} {noun}: {details}"
67
+
68
+
69
+ def main(argv: Sequence[str] | None = None) -> int:
70
+ args = build_parser().parse_args(argv)
71
+
72
+ # Error messages below are fixed strings. They never include the
73
+ # exception text or any input, so they cannot leak what the user pasted.
74
+ try:
75
+ text = _read_input(args.file)
76
+ except UnicodeDecodeError:
77
+ print("pasteval: error: input is not valid UTF-8 text.", file=sys.stderr)
78
+ return EXIT_ERROR
79
+ except OSError:
80
+ source = f"file '{args.file}'" if args.file else "standard input"
81
+ print(f"pasteval: error: could not read {source}.", file=sys.stderr)
82
+ return EXIT_ERROR
83
+
84
+ try:
85
+ result = redact(text)
86
+ except Exception: # noqa: BLE001 - fail closed on any redaction bug
87
+ print(
88
+ "pasteval: error: redaction failed; no output was written.",
89
+ file=sys.stderr,
90
+ )
91
+ return EXIT_ERROR
92
+
93
+ # Only now, with redaction finished, do we write anything to stdout.
94
+ sys.stdout.buffer.write(result.text.encode("utf-8"))
95
+ sys.stdout.buffer.flush()
96
+ print(_summary(result), file=sys.stderr)
97
+ return EXIT_OK
pasteval/detector.py ADDED
@@ -0,0 +1,54 @@
1
+ """Find sensitive values in text and resolve overlapping matches."""
2
+
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass, field
5
+
6
+ from pasteval.rules import RULES, Rule
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class Match:
11
+ """A span of text [start, end) that one rule recognized.
12
+
13
+ `key` holds the normalized sensitive value. It is excluded from repr() so
14
+ that printing or logging a Match can never leak the value by accident.
15
+ """
16
+
17
+ start: int
18
+ end: int
19
+ rule_name: str
20
+ key: str = field(repr=False)
21
+
22
+
23
+ def find_matches(text: str, rules: Sequence[Rule] = RULES) -> list[Match]:
24
+ """Return non-overlapping matches, ordered by position in the text.
25
+
26
+ Overlap rule: the match that starts earliest wins; on a tie the longest
27
+ wins; on a further tie the rule listed first wins.
28
+ """
29
+ candidates: list[tuple[int, int, int, Match]] = []
30
+ for priority, rule in enumerate(rules):
31
+ for found in rule.pattern.finditer(text):
32
+ if found.start() == found.end():
33
+ continue # ignore empty matches from a badly written rule
34
+ match = Match(
35
+ start=found.start(),
36
+ end=found.end(),
37
+ rule_name=rule.name,
38
+ key=rule.normalize(found.group()),
39
+ )
40
+ # Sort key: earliest start, then longest (negative length), then
41
+ # rule order.
42
+ candidates.append(
43
+ (match.start, -(match.end - match.start), priority, match)
44
+ )
45
+
46
+ candidates.sort(key=lambda item: item[:3])
47
+
48
+ kept: list[Match] = []
49
+ covered_up_to = 0
50
+ for _, _, _, match in candidates:
51
+ if match.start >= covered_up_to:
52
+ kept.append(match)
53
+ covered_up_to = match.end
54
+ return kept
pasteval/redactor.py ADDED
@@ -0,0 +1,47 @@
1
+ """Replace detected values with numbered placeholders."""
2
+
3
+ from collections.abc import Sequence
4
+ from dataclasses import dataclass
5
+
6
+ from pasteval.detector import find_matches
7
+ from pasteval.rules import RULES, Rule
8
+
9
+
10
+ @dataclass(frozen=True)
11
+ class RedactionResult:
12
+ """The redacted text plus how many values of each type were replaced.
13
+
14
+ `counts` contains only type names and numbers, never the values, so it is
15
+ safe to show to the user.
16
+ """
17
+
18
+ text: str
19
+ counts: dict[str, int]
20
+
21
+
22
+ def redact(text: str, rules: Sequence[Rule] = RULES) -> RedactionResult:
23
+ """Return `text` with every detected value replaced by a placeholder.
24
+
25
+ Placeholders are numbered per type in order of first appearance. The same
26
+ value always gets the same placeholder; everything else is left untouched.
27
+ """
28
+ placeholders: dict[tuple[str, str], str] = {} # (type, value) -> "[EMAIL_1]"
29
+ next_number: dict[str, int] = {}
30
+ counts: dict[str, int] = {}
31
+
32
+ pieces: list[str] = []
33
+ position = 0
34
+ for match in find_matches(text, rules):
35
+ identity = (match.rule_name, match.key)
36
+ if identity not in placeholders:
37
+ number = next_number.get(match.rule_name, 0) + 1
38
+ next_number[match.rule_name] = number
39
+ placeholders[identity] = f"[{match.rule_name}_{number}]"
40
+
41
+ pieces.append(text[position:match.start]) # untouched text before it
42
+ pieces.append(placeholders[identity])
43
+ position = match.end
44
+ counts[match.rule_name] = counts.get(match.rule_name, 0) + 1
45
+
46
+ pieces.append(text[position:]) # untouched text after the last match
47
+ return RedactionResult(text="".join(pieces), counts=counts)
pasteval/rules.py ADDED
@@ -0,0 +1,52 @@
1
+ """Detection rules.
2
+
3
+ A rule is a name plus a compiled regular expression. To support a new kind of
4
+ sensitive value, add a Rule to RULES and write tests for it. Nothing else in
5
+ the application needs to change.
6
+
7
+ Order matters only as a tie-breaker: when two rules match exactly the same
8
+ span of text, the rule listed first wins.
9
+ """
10
+
11
+ import re
12
+ from collections.abc import Callable
13
+ from dataclasses import dataclass
14
+
15
+
16
+ def _unchanged(value: str) -> str:
17
+ return value
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Rule:
22
+ """One kind of sensitive value.
23
+
24
+ name: used in the placeholder, e.g. "EMAIL" gives "[EMAIL_1]".
25
+ pattern: compiled regex that matches the value.
26
+ normalize: turns a matched value into the key used to decide whether two
27
+ matches are "the same value". Emails lower-case here so that
28
+ Alex@Example.com and alex@example.com share one placeholder.
29
+ """
30
+
31
+ name: str
32
+ pattern: re.Pattern[str]
33
+ normalize: Callable[[str], str] = _unchanged
34
+
35
+
36
+ # Email addresses, deliberately conservative (ASCII only):
37
+ # - the local part starts with a letter or digit
38
+ # - the domain needs at least one dot and a letter-only ending of 2+ letters
39
+ # - the lookbehind/lookahead stop us matching the middle of a longer token
40
+ # Internationalized addresses (non-ASCII) are not detected.
41
+ _EMAIL_PATTERN = re.compile(
42
+ r"(?<![A-Za-z0-9._%+-])" # not mid-token
43
+ r"[A-Za-z0-9][A-Za-z0-9._%+-]*" # local part
44
+ r"@"
45
+ r"(?:[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?\.)+" # domain labels
46
+ r"[A-Za-z]{2,}" # top-level domain
47
+ r"(?![A-Za-z0-9-])" # domain really ends
48
+ )
49
+
50
+ EMAIL = Rule(name="EMAIL", pattern=_EMAIL_PATTERN, normalize=str.lower)
51
+
52
+ RULES: tuple[Rule, ...] = (EMAIL,)
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.4
2
+ Name: pasteval
3
+ Version: 0.0.1
4
+ Summary: Redact sensitive information from text before you paste it into AI tools.
5
+ License-Expression: MIT
6
+ Project-URL: Homepage, https://pasteval.com
7
+ Keywords: redaction,privacy,secrets,cli,sanitize
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Environment :: Console
10
+ Classifier: Intended Audience :: Developers
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Security
13
+ Classifier: Topic :: Text Processing :: Filters
14
+ Requires-Python: >=3.11
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Provides-Extra: dev
18
+ Requires-Dist: pytest>=8; extra == "dev"
19
+ Dynamic: license-file
20
+
21
+ # Pasteval
22
+
23
+ Pasteval is a small command-line tool that redacts sensitive information from
24
+ text before you paste it into an AI tool or any other external service.
25
+
26
+ It runs entirely on your computer. No account, no API key, no network access,
27
+ and no dependencies beyond Python itself.
28
+
29
+ ## Why use it
30
+
31
+ When you paste a log, an email, or a config snippet into a chatbot, it is easy
32
+ to include something you did not mean to share. Pasteval replaces what it
33
+ recognizes with a placeholder, so the text stays useful and the value stays
34
+ private.
35
+
36
+ ## Install
37
+
38
+ Pasteval needs Python 3.11 or newer. Install it from source:
39
+
40
+ ```bash
41
+ git clone <this repository>
42
+ cd pasteval
43
+ pip install -e .
44
+ ```
45
+
46
+ ## Usage
47
+
48
+ Paste text interactively, then press Ctrl+D on a new line to finish
49
+ (Ctrl+Z then Enter on Windows):
50
+
51
+ ```bash
52
+ pasteval
53
+ ```
54
+
55
+ Pipe text in:
56
+
57
+ ```bash
58
+ cat notes.txt | pasteval
59
+ ```
60
+
61
+ Read a file:
62
+
63
+ ```bash
64
+ pasteval --file notes.txt
65
+ ```
66
+
67
+ Other options:
68
+
69
+ ```bash
70
+ pasteval --help
71
+ pasteval --version
72
+ ```
73
+
74
+ The redacted text is written to standard output. A short summary (types and
75
+ counts only, never the values) is written to standard error, so you can pipe
76
+ the output safely, for example `pasteval --file notes.txt | pbcopy` on macOS.
77
+
78
+ ## Example
79
+
80
+ Input:
81
+
82
+ ```text
83
+ Hi, I'm Alex.
84
+ My email is alex@example.com.
85
+ Please copy sam@example.com, and reply to alex@example.com.
86
+ ```
87
+
88
+ Output:
89
+
90
+ ```text
91
+ Hi, I'm Alex.
92
+ My email is [EMAIL_1].
93
+ Please copy [EMAIL_2], and reply to [EMAIL_1].
94
+ ```
95
+
96
+ The same value always gets the same placeholder, so the text still makes sense.
97
+
98
+ ## What is redacted
99
+
100
+ | Type | Placeholder |
101
+ |---|---|
102
+ | Email addresses | `[EMAIL_1]`, `[EMAIL_2]`, ... |
103
+
104
+ ## Security limitations
105
+
106
+ Pasteval reduces the risk of accidental sharing. It does not guarantee it.
107
+
108
+ - It can miss things (false negatives). Anything not listed above is left as
109
+ it is, including names, postal addresses, passwords, and API keys.
110
+ - Email addresses containing non-English characters are not detected.
111
+ - It can occasionally redact something harmless (false positives).
112
+ - Text you paste into a terminal may remain in the terminal's scrollback.
113
+ - Always read the output before you share it.
114
+
115
+ Pasteval never sends your text anywhere, never saves it, and never prints the
116
+ original values in its messages. If something goes wrong it prints an error
117
+ and no text at all.
118
+
119
+ ## Development
120
+
121
+ ```bash
122
+ pip install -e ".[dev]"
123
+ pytest
124
+ ```
125
+
126
+ Detection rules live in `src/pasteval/rules.py`. To add one, add a `Rule` to
127
+ the `RULES` list and write tests for it.
128
+
129
+ ## License
130
+
131
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,12 @@
1
+ pasteval/__init__.py,sha256=kbAJ9if9M6G80TQl5wL6hAt1Orxb7UzYpvyY0RmCSN8,97
2
+ pasteval/__main__.py,sha256=NkElTgTO4yX3Fr9CYyfhspd4B7Oh3DZV15xjU6cVJ3o,160
3
+ pasteval/cli.py,sha256=Oow2MS1Kv1ubeye3lpHlPi2IUzy-b1bBui_izBmUxZQ,3208
4
+ pasteval/detector.py,sha256=QxEhkXgEdqJQ9kJB-AsQ2DQA8K1ULqZUZ8JrQTI32L0,1773
5
+ pasteval/redactor.py,sha256=xWNM2zCyPnEyQbzB5UFxPyndZEbKaOt54G5dFO1_LsI,1681
6
+ pasteval/rules.py,sha256=Y3hxE4mOc6o0CXwoJu87PGU3WJhLKVSJmzdRUKXBuEQ,1850
7
+ pasteval-0.0.1.dist-info/licenses/LICENSE,sha256=H905oxT5eby7qsaBBL0KX0gmvdXOwZKBSXvh7i87vHM,1069
8
+ pasteval-0.0.1.dist-info/METADATA,sha256=kaeg2fyPgSYMURziQlKFmprJ40thjw_ovOngwKd1Acc,3219
9
+ pasteval-0.0.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
10
+ pasteval-0.0.1.dist-info/entry_points.txt,sha256=3ufvSaR-mVQZUqnvWC6iwB4CpSy8EIH0dlUU66JOCmE,47
11
+ pasteval-0.0.1.dist-info/top_level.txt,sha256=VXeLM0i7qdwzSy0TP6i1dv9eFCzOYGk-1i4cSiyK8RE,9
12
+ pasteval-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ pasteval = pasteval.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Harshil Shah
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 @@
1
+ pasteval