Metadata-Version: 2.4
Name: hidden-char-scan
Version: 0.1.0
Summary: Scan text files for hidden or confusable Unicode characters (CLI, SARIF, pre-commit, and an optional MCP server).
Author: Mackenzie O'Brien
License-Expression: MIT
Project-URL: Homepage, https://mac-labs-ai.github.io/hidden-char-scan/
Project-URL: Repository, https://github.com/Mac-Labs-AI/hidden-char-scan
Project-URL: Issues, https://github.com/Mac-Labs-AI/hidden-char-scan/issues
Project-URL: Project, https://mac-labs-ai.github.io/hidden-char-scan/
Project-URL: Hack Week 26, https://hackweek.opensuse.org/26/projects/hidden-char-scan
Keywords: unicode,security,lint,hidden-characters,homoglyph,bidi,mcp,sarif,pre-commit
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Topic :: Text Processing
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Dynamic: license-file

<p align="center">
  <img src="docs/brand/logo-lockup.svg" alt="hidden-char-scan" width="520">
</p>

# hidden-char-scan

**Try it:** [live demo on Hugging Face Spaces](https://huggingface.co/spaces/mackenzietechdocs/hidden-char-scan)
(free CPU, sample files or your own text). Project page:
[mac-labs-ai.github.io/hidden-char-scan](https://mac-labs-ai.github.io/hidden-char-scan/).
Built for [openSUSE Hack Week 26](https://hackweek.opensuse.org/26/projects/hidden-char-scan).

A Python command-line tool that scans text files for Unicode characters
that are easy for a person to miss: invisible or format characters,
bidirectional controls, lookalike letters from another alphabet, and a few
related controls.

AI agents and review tools often read markdown, RPM spec files, systemd unit
files, JSON (including MCP tool descriptors), and source code. Those files are
usually reviewed as ordinary text. Hidden or confusable characters can be
present in a file without showing up clearly in a diff or in a terminal. This
scanner reports them so you can inspect the file and decide whether they belong
there.

It only detects characters that are already in the files you point it at. It
does not rewrite files, and it is not a general security auditor.

Beyond a one-off scan it fits into review workflows: a GitHub Actions example,
a pre-commit hook, SARIF output for code scanning, scans of only the files git
reports as changed, standard input, a sanitized snippet of the line around each
finding, a baseline for known and accepted findings, and an optional MCP
server and a portable agent skill so an AI agent can run it. See
[Integrations](#integrations).

## Install

Python 3.11 or newer is required. There are no runtime dependencies beyond the
standard library.

```bash
pip install -e .
```

That provides the `hidden-char-scan` console script (and `hidden-char-scan-mcp`,
the optional MCP server). You can also run the module without installing:

```bash
python -m hidden_char_scan --help
```

For development (tests):

```bash
pip install -e ".[dev]"
python -m pytest
```

## Usage

```bash
hidden-char-scan path/to/file.md
hidden-char-scan docs/ packaging/ systemd/
hidden-char-scan --json src/
hidden-char-scan --fail-on medium .
hidden-char-scan --strict --fail-on info .
hidden-char-scan --allow U+00A0 --allow-path "vendor/**" .
hidden-char-scan --config hidden-char-scan.toml .
hidden-char-scan --max-bytes 1048576 .
hidden-char-scan --git-staged
hidden-char-scan --git-diff=origin/main
echo "some text" | hidden-char-scan --stdin
hidden-char-scan --sarif -o results.sarif .
hidden-char-scan --write-baseline hcs-baseline.json .
hidden-char-scan --baseline hcs-baseline.json .
hidden-char-scan --list-codes
```

By default the tool recurses directories, skips VCS and tool-cache directories
(`.git`, `.hg`, `node_modules`, `__pycache__`, and similar), and scans files
with known text extensions: markdown, RPM spec and `.changes`, systemd units,
`.desktop`, JSON, TOML, YAML, XML, AppArmor and polkit policy files, `.in`
templates, plain text, Python, shell, and a few other source and config types.
Extensionless files are scanned only when they start with a `#!` line (or have
a well-known name such as `Makefile`). Use `--all-text` to include every
regular file that is not binary. A file you name on the command line is always
scanned, whatever its extension.

Nothing is dropped silently. The report lists what was not scanned and why:

- **Binary files** (a NUL byte) are skipped, with a reason.
- **Invalid UTF-8** does not skip the file. The file is still scanned, and each
  invalid byte is reported as an `ENCODING` finding (`0xFF`, not a made-up code
  point) while the rest of the text is checked normally. A UTF-16 file with a
  byte order mark is decoded as UTF-16. UTF-32 files are skipped with a reason.
- **Files over the size limit** (default 32 MiB, change with `--max-bytes` or
  `max_bytes` in the config; `0` means no limit) are skipped and listed. A file
  you named explicitly that is over the limit is an error instead, so a CI run
  cannot pass without having read it.
- **Symbolic links** found while walking a directory are listed as skipped and
  not followed.
- **Errors**: a file or directory that cannot be read, a path that does not
  exist, or a named path that is not a regular file or directory is an error
  and the exit status is `2`. The other files are still scanned and reported.

Exit status:

- `0` if there are no findings at the `--fail-on` threshold (default: `medium`,
  so information-only findings still pass) and no errors
- `1` if a finding at that threshold or higher is present
- `2` if there was any error (usage, a missing or unreadable path, an
  unreadable directory, an oversize named file, git missing or not a repository
  for `--git-*`, an unreadable or invalid baseline); this takes precedence over `1`

`--strict` raises the severity of some otherwise-low findings (for example a
leading byte-order mark, a no-break space, a combining mark in prose, or a
zero-width joiner in an emoji sequence) and, unless you also pass `--fail-on`,
fails on `info`.

Settings come from a TOML file. The tool looks for `hidden-char-scan.toml` or
`.hidden-char-scan.toml` in the current directory and then in each parent
directory, stopping after the first directory that contains `.git` (so a
repository's own config is used) or at the filesystem root. `--config` always
wins. An example is in `hidden-char-scan.example.toml`. Command-line options
override the file. Path patterns are matched against paths relative to the
directory you run the tool from.

## Integrations

Every integration runs the same scanner with the same exit status: `0` clean,
`1` a finding at `--fail-on` or higher, `2` an error.

### GitHub Actions

[examples/github-actions/hidden-char-scan.yml](examples/github-actions/hidden-char-scan.yml)
is a workflow that installs the package, runs the scan, fails the job at the
configured `--fail-on`, and uploads SARIF to code scanning (with `if: always()`
so findings are uploaded even when the job fails). It also has an optional job
that scans only the files a pull request changed. The package is not on a
package index yet, so the example installs from the checkout; the comments show
the line to use once it is published.

```yaml
- name: Scan (fails at --fail-on)
  run: hidden-char-scan --fail-on medium --sarif -o hidden-char-scan.sarif .
```

### Pre-commit

A local hook works today
([examples/pre-commit-config.yaml](examples/pre-commit-config.yaml)):

```yaml
repos:
  - repo: local
    hooks:
      - id: hidden-char-scan
        name: hidden-char-scan
        entry: hidden-char-scan --fail-on medium
        language: system
        types: [text]
```

Install the package first (`pip install -e .` in your checkout) so the command
is on PATH. The repository also contains `.pre-commit-hooks.yaml`, so you can use the
public repository as a normal `repo:` hook. There are no release tags yet, so
pin `rev:` to a commit SHA.

### SARIF

`--sarif` writes a SARIF 2.1.0 report instead of text or JSON (not together
with `--json`). Rule ids are the detector codes (`BIDI`, `INVISIBLE`, ...).
Severity maps to SARIF levels: `high` is `error`, `medium` is `warning`, `info`
is `note`. Each result carries the line and column, a sanitized message and
snippet, and a stable `partialFingerprints` entry (the same fingerprint the
baseline uses). Files that could not be read appear as invocation notifications
and make `executionSuccessful` false. Use `-o PATH` to write the report to a
file instead of standard output.

```bash
hidden-char-scan --sarif -o results.sarif .
```

### Only changed files

```bash
hidden-char-scan --git-staged               # files staged in the index
hidden-char-scan --git-diff                 # changed against HEAD (staged and unstaged)
hidden-char-scan --git-diff=origin/main     # changed against a ref
hidden-char-scan --git-diff=origin/main...HEAD
hidden-char-scan --git-staged docs/         # only changed files under docs/
```

Added, copied, modified, and renamed files are scanned; deleted files are not.
``--git-staged`` reads the *index* (the content that would be committed), not
later unstaged edits, and it still works if the working-tree file was deleted
after staging. ``--git-diff`` reads the working-tree copy (after a GitHub
Actions checkout, that is the commit being checked). Changed files are treated
like files named on the command line, so any extension is scanned and an
oversize file is an error. Paths are shown relative to the repository root. Write
`--git-diff=REF`; a bare `--git-diff` followed by a path is an error rather than
a guess. If git is not installed, the directory is not a repository, or the
revision does not exist, the exit status is `2` with a message. The tool never
falls back to scanning everything.

### Standard input

`-` as a path, or `--stdin`, scans standard input. It is shown as `<stdin>`.
Use `--stdin-filename NAME` (for example `example.py`) only to choose code or
prose severity; the name is not shown. The `--max-bytes` limit applies, and
invalid UTF-8 is reported the same way as in a file.

```bash
git show HEAD:docs/readme.md | hidden-char-scan --stdin
```

### Context snippets

Each finding includes `context`: the line around the finding, up to about 120
characters, with everything outside printable ASCII written as `<U+XXXX>` (or
`<0xNN>` for an invalid byte). In the text report it is the `|` line under the
finding; in JSON it is `context`; in SARIF it is the region snippet. Use
`--no-context` to leave it out. The snippet never contains the raw character, so
a lookalike letter shows up as its code point.

```text
doc.md:3:25: high INVISIBLE U+200B ZERO WIDTH SPACE
  Invisible or format character. ...
  | Please review the change<U+200B>log before tagging a release.
```

### Baseline (known, accepted findings)

A baseline lets you adopt the scanner on a tree that already has findings
someone has reviewed, such as a legitimate no-break space or emoji joiner, and
fail only on new ones. It is for known accepted findings, not for hiding them:
the baseline is a plain JSON file you review like code, a baselined finding is
counted in the report, and an entry stops matching as soon as its position or
character changes.

```bash
hidden-char-scan --write-baseline hcs-baseline.json .   # records current findings, exits 0
hidden-char-scan --baseline hcs-baseline.json .         # fails only on new findings
```

`--write-baseline` writes nothing and exits `2` if any input could not be
scanned. A configuration file may set `baseline = "hcs-baseline.json"`;
`--baseline` overrides it.

A finding's fingerprint is `path:line:column:DETECTOR:CODE`, stored as separate
fields in the file:

- `path` is relative to the directory you ran from (the repository root for
  `--git-*`), uses `/`, and anything outside printable ASCII is written as
  `<U+XXXX>`.
- `line` and `column` are the 1-based position.
- `detector` is the code such as `INVISIBLE`.
- `code` is the code point as `U+XXXX`. For `ENCODING`, which reports a raw
  byte and not a code point, it is the byte as `0xNN`, so a different invalid
  byte at the same position is a different finding.

Severity is not part of the fingerprint, so `--strict` does not invalidate a
baseline. If lines above a finding are added or removed, the entry goes stale
and the finding is reported again; the report counts stale entries so you can
regenerate the file after review. `--allow` and `--allow-path` behave exactly as
before and are applied first; a baseline never changes what they do. A baseline
does not hide errors.

### Agents and MCP

Any agent that can run a shell command can use the command line directly:

```bash
python -m hidden_char_scan --json PATH [PATH ...]
```

The portable instructions for an agent are in
[skills/hidden-char-scan/SKILL.md](skills/hidden-char-scan/SKILL.md): how to
install and run it, the `--json` report, exit codes, and how to read the `U+XXXX`
markers. It is plain Markdown with only `name` and `description` in its
frontmatter, so it can be copied into whatever skills or instructions location a
given agent uses. `AGENTS.md` points at the same file. Nothing is installed
anywhere automatically.

For agents that speak the Model Context Protocol, an optional stdio server is
included. It uses only the standard library:

```bash
python -m hidden_char_scan.mcp       # or: hidden-char-scan-mcp
```

It exposes two read-only tools and nothing that writes:

| Tool | Arguments | Result |
| --- | --- | --- |
| `scan_paths` | `paths` (required), `fail_on`, `strict`, `all_text`, `allow_codepoints`, `max_bytes`, `include_context`, `config`, `ignore_config`, `baseline` | The `--json` report for those files or directories on the machine running the server. |
| `scan_text` | `text` (required), `filename` (optional hint for code or prose severity), `fail_on`, `strict`, `allow_codepoints`, `include_context`, `config`, `ignore_config`, `baseline` | The `--json` report only. The text is never returned, and the filename hint is not echoed. |

Results have the same shape as `--json` (`ok`, `fail_on`, `files_scanned`,
`files_skipped`, `findings`, `skipped`, `errors`, plus `result` and `exit_code`).
They are returned as both structured content and a JSON text block. Bad
arguments come back as a tool error, not a crash. By default the server also
loads a `hidden-char-scan.toml` from its working directory the same way the CLI
does; tool arguments override the file, and `ignore_config` skips it. Relative
`paths` and config paths are relative to the server's working directory, so prefer
absolute paths.

Example client configuration for Claude Desktop, Cursor, and other clients that
use an `mcpServers` block (replace the placeholders; no machine-specific paths
are included):

```json
{
  "mcpServers": {
    "hidden-char-scan": {
      "command": "/ABSOLUTE/PATH/TO/VENV/bin/python",
      "args": ["-m", "hidden_char_scan.mcp"]
    }
  }
}
```

With the package installed so that `hidden-char-scan-mcp` is on PATH, use
`"command": "hidden-char-scan-mcp"` with `"args": []`. Both files are in
[examples/mcp/](examples/mcp/). The server implements the stdio transport and the
`initialize`, `server/discover`, `tools/list`, `tools/call`, and `ping` methods,
and is covered by this project's tests; it has not been submitted to any MCP
registry. It has also been run over stdio against the official MCP Python SDK
(`mcp.ClientSession`) and the MCP Inspector CLI.

## What it flags

Each finding has a detector code, a severity (`high`, `medium`, or `info`), a
line and column, a code point (`U+202E`), and a short explanation. Run
`hidden-char-scan --list-codes` for the same list.

| Code | What it reports |
| --- | --- |
| `BIDI` | Bidirectional controls such as RLO, LRO, RLI, LRI, FSI, PDI, and PDF, which can change the visual order of a line. Direction marks (LRM, RLM, ALM) are also reported, at lower severity when they sit near right-to-left text. |
| `INVISIBLE` | Format characters that are usually invisible, including zero-width space, word joiner, soft hyphen, and a lone zero-width joiner or non-joiner. |
| `UNUSUAL_SPACE` | Spaces other than the ordinary ASCII space, such as no-break space or thin space. Next to words in a non-Latin script (for example a no-break space in Russian text) this is `info`. |
| `BOM` | A byte-order mark. At the start of a file this is `info`; later in the file it is treated as an invisible character and reported as `high`. |
| `CONFUSABLE` | Letters that look like Latin characters but come from another script (for example a Cyrillic or Greek lookalike inside an otherwise Latin word), fullwidth Latin letters, and mathematical alphanumeric letters and digits. Also a short curated list of punctuation lookalikes: the Greek question mark (U+037E, looks like `;`), fullwidth ASCII punctuation and digits (U+FF01 to U+FF5E), and the division and fraction slashes (U+2215, U+2044, code files only). |
| `MIXED_SCRIPT` | A word or identifier that mixes Latin letters with another letter script, when that mix is not a known lookalike already reported as `CONFUSABLE`. |
| `COMBINING` | A combining mark on a Latin letter, a digit, punctuation, or with no base character. See the notes below for how severity is chosen. |
| `TAG` | Unexpected characters in the Unicode tag block. |
| `VARIATION_SELECTOR` | A variation selector that is not attached to a symbol or emoji. |
| `DEPRECATED` | Deprecated format controls (U+206A through U+206F). |
| `CONTROL` | Unexpected C0 or C1 controls (other than tab and ordinary newlines), Unicode line or paragraph separators, and lone surrogates. |
| `BLANK_LOOKALIKE` | Characters that look like a blank in many fonts but are not a space, such as Hangul fillers. |
| `ENCODING` | A byte that is not valid UTF-8. The `codepoint` field is the raw byte (`0xFF`), not a Unicode code point. It cannot be silenced with `--allow`; use `--allow-path` if a file is meant to be non-UTF-8. |
| `NONCHARACTER` | Unicode noncharacters (U+FDD0 to U+FDEF, and U+FFFE or U+FFFF on every plane). `medium`, or `high` in code files and `--strict`. |
| `REPLACEMENT` | U+FFFD, the replacement character, which usually means text was damaged by an earlier decoding step. `info` in prose, `medium` in code files and `--strict`. |

Severity is chosen so that the default `--fail-on medium` stays useful:

- Bidirectional overrides and embeddings, unexpected tag characters, deprecated
  controls, lone invisible format characters in source, and blank lookalikes
  are `high` or `medium`.
- Known-legitimate cases are `info` by default: a zero-width joiner in an emoji
  sequence, a zero-width non-joiner near a script that commonly uses it, a
  leading BOM, a soft hyphen in prose, or a no-break space that is not inside
  an identifier.
- A paragraph of Russian (or another non-Latin language) is not flagged just
  because it is not Latin. Confusable and mixed-script checks apply when a
  Latin-looking token contains letters from another script, or when
  lookalikes appear on a line that is otherwise Latin.

How combining marks are judged (a deliberately conservative rule, not a full
normalization check):

- A combining mark on a non-Latin letter is part of that script's normal
  spelling (Arabic, Hebrew, Indic scripts, Thai, Lao, Tibetan, Myanmar, Khmer,
  Cyrillic stress marks, Greek accents, Japanese voiced marks, and so on) and is
  never reported.
- On a Latin letter, digit, or punctuation, or with no base character: in code
  and config files it is `medium` (`high` with `--strict`), whether or not it
  composes into a normal accented letter. In prose it is `info` if it composes
  to a normal letter (decomposed accents such as `e` plus U+0301 are common) and
  `medium` if it does not (for example U+0338). A keycap sequence is ignored.
- A precomposed letter such as U+00E9 is never reported.

Lookalike punctuation, digits, and slashes are reported in code files (unless
the line is mostly non-Latin text) and on Latin-dominant prose lines. Greek,
Russian, and CJK prose that uses its own punctuation is left alone. En and em
dashes and hyphens in prose are never reported.

Reports always print code points as `U+XXXX` (or `0xNN` for an invalid byte,
and `<U+XXXX>` inside file names and snippets). They do not write the raw
character back to the terminal, so a bidirectional control cannot scramble the
report. This holds for the text, JSON, and SARIF reports and for the MCP tools.

## What it does not do

- It does not generate, encode, or recommend hidden characters.
- It does not try to judge the meaning of a file, a comment, or a tool
  description.
- It does not scan binaries, and it does not follow symbolic links found while
  walking a directory (they are listed as skipped).
- It does not claim a complete Unicode Security Mechanisms (UTS #39)
  confusable database. The lookalike list is a curated subset aimed at Latin
  identifiers, words, and a few punctuation marks, built with the standard
  library.
- It does not normalize, validate, or judge Unicode text beyond the checks
  above, and it does not read UTF-32 files.
- It does not rewrite or "fix" files. Removing or replacing a character is a
  decision for the file's maintainer. The CLI, the MCP server, and the agent
  skill are all detect-only, and nothing here creates or inserts hidden
  characters.
- A baseline records findings someone has already reviewed; it does not decide
  whether they are acceptable.

## Related study (planned)

A planned empirical study of how often these characters appear in openSUSE
package text, public MCP metadata, and human- versus model-written files is
described in [study/proposal.md](study/proposal.md). The study has not been
run. The proposal is a design to be built out after [openSUSE Hack Week 26](https://hackweek.opensuse.org/26/projects/hidden-char-scan).

## License

MIT. See [LICENSE](LICENSE).
