Metadata-Version: 2.4
Name: passavant
Version: 0.1.0
Summary: LLM-aided Export Control self-classification assistant for open-source software.
Author: RοdοƖphе Dеȷеᴜnеѕ
License-Expression: MIT
Project-URL: Homepage, https://github.com/rdejeun/passavant
Project-URL: Source, https://github.com/rdejeun/passavant
Project-URL: Issues, https://github.com/rdejeun/passavant/issues
Keywords: export-control,ear,itar,cryptography,cbom,compliance,classification,llm
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Legal Industry
Classifier: Environment :: Console
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security :: Cryptography
Classifier: Topic :: Utilities
Requires-Python: >=3.12
Description-Content-Type: text/markdown
License-File: LICENSE.md
Requires-Dist: openai>=1.0
Requires-Dist: httpx>=0.27
Requires-Dist: python-dotenv>=1.0
Requires-Dist: unboxr>=0.2.3
Dynamic: license-file

# Passavant

Passavant helps you **self-classify open-source software components under the US Export Administration Regulations (EAR)**. It scans a local source repository, extracts the relevant excerpts with regular expressions, has an LLM (any OpenAI-compatible API) analyze them, and writes a structured JSON report for a human reviewer.

It runs two independent analyses, in the order a classification follows:

1. **Jurisdiction**: is the component really subject to the EAR? Passavant looks for hints that could place it under another regulation: design or modification for military use (ITAR / USML, EAR 600 series), or development or funding by the Department of State, the Treasury (OFAC), the Nuclear Regulatory Commission, the Department of Energy, the Patent and Trademark Office, or the Department of Defense / Foreign Military Sales.
2. **Cryptography**: what cryptography does the component implement, use or embed? Passavant builds an inventory of cryptographic assets, in a format inspired by the [CycloneDX CBOM](https://cyclonedx.org/capabilities/cbom/), with extra fields for EAR classification (security objective, effective key length, standardization status).

> **Not legal advice.** Passavant collects evidence for an export-control specialist to review. It does not conclude on jurisdiction or on the ECCN, and an LLM can miss, misread or invent findings: check each finding against the cited source lines. A `no-evidence` status means that nothing was found, not that nothing exists.

*In French customs vocabulary, a* passavant *is a permit that lets goods travel.*

## Requirements

- Python 3.12 or later, as required by [unboxr](https://pypi.org/project/unboxr/), the archive extraction library.
- Access to an OpenAI-compatible chat completions endpoint: the OpenAI API, or a corporate gateway.

**Data sent to the endpoint**: excerpts of the analyzed source code (complete READMEs and the lines around each regex match) and the repository URL go to the configured LLM endpoint. Make sure this is acceptable for the code you analyze.

## Installation

```bash
pip install passavant
```

This installs the `passavant` command. From a clone of the source repository, `pip install .` does the same.

## Configuration

Passavant reads its settings from environment variables, or from a `.env` file in the **current directory** (or, failing that, in one of its parents). [`.env.example`](https://github.com/rdejeun/passavant/blob/main/.env.example) is a template that documents each one: copy it as `.env` and fill in the values.

| Variable | Default | Description |
|---|---|---|
| `OPENAI_API_KEY` | none | API key of the endpoint. |
| `OPENAI_BASE_URL` | OpenAI client default | Base URL of the OpenAI-compatible endpoint. |
| `OPENAI_MODEL` | none | Model name. |
| `OPENAI_SSL_VERIFY` | `false` | Verify the endpoint's TLS certificate. Disabled by default for corporate proxies that intercept TLS; enable it whenever possible. |
| `OPENAI_SEND_TEMPERATURE` | `false` | Send `temperature=0.0`. Off by default because some models reject the parameter. |
| `OPENAI_JSON_MODE` | `false` | Send `response_format={"type": "json_object"}`. Not supported by every gateway. |
| `OPENAI_MAX_TOKENS` | `4096` | Read but deliberately **not sent**: some models return HTTP 400 when `max_tokens` plus the prompt exceeds their limit. |
| `CHUNK_MAX_CHARS` | `40000` | Maximum size, in characters, of the context sent per request (about 4 characters per token). The minimum is 2000. Larger contexts are split into chunks. |
| `DEBUG` | `0` | With `1`, saves the context of each chunk to `analysis-jurisdiction-NN.xml` and `analysis-crypto-NN.xml`. |

## Usage

```bash
passavant <source> [--repo-url <url>] [--max-chars <n>]
```

| Argument | Description |
|---|---|
| `source` | Local directory to analyze, typically a clone of the component's repository at the version being classified, or an archive file of the component (see below). |
| `--repo-url` | Original URL of the repository (default: `local`). The LLM receives it as part of the corpus: a repository published under a national laboratory's organization is itself a jurisdiction hint. |
| `--max-chars` | Overrides `CHUNK_MAX_CHARS` for this run. |
| `--version` | Prints the version and exits. |

Example:

```bash
git clone --depth 1 --branch v1.4.0 https://github.com/example/vault.git /tmp/vault
passavant /tmp/vault --repo-url https://github.com/example/vault
```

**Archive files.** When `source` is a file, Passavant extracts it with unboxr, and the archives it contains, into a temporary directory under `$TEMP`, analyzes the extracted tree, then removes the temporary directory. Every format unboxr supports is accepted (`.zip`, `.tar.gz`, `.whl`, `.jar`, `.deb`...). The report then identifies the archive file by its name and SHA-256 (see [Component identity](#component-identity)), and the `path:line` locations are relative to the root of the archive. A container that unboxr cannot open is reported in the console, and its content is not analyzed. For a file that is not an archive, Passavant stops with an error.

```bash
passavant vault-1.4.0.tar.gz
```

The exit code is 0 when the analysis has run, and 1 when the source cannot be analyzed (missing, or a file that is not an archive).

The outputs go to the **current directory**, not next to the source:

| File | Content |
|---|---|
| `compliance_report.json` | The report (see below). |
| `compliance_report_raw.txt` | Written only when some chunks failed: the raw LLM output or the API error of each failed chunk, under `===== Chunk jurisdiction i/n =====` and `===== Chunk crypto i/n =====` headings. |
| `analysis-jurisdiction-NN.xml`, `analysis-crypto-NN.xml` | With `DEBUG=1` only: the context sent for each chunk. |

## How it works

Each analysis runs the same four-step pipeline with its own regular expressions, corpus and prompt. The jurisdiction analysis runs first, then the cryptography analysis.

1. **Extraction.** Passavant walks the source directory (or the tree extracted from the archive file), skipping the `.git`, `.svn`, `node_modules`, `target`, `build` and `__pycache__` directories, common binary extensions, and files that are not valid UTF-8. `README*` files are kept in full, since they give the component's name, version and purpose. Other files are kept only around the lines that match the analysis's patterns: ±5 lines for jurisdiction, ±30 lines for cryptography. Each line is prefixed with its number so that the LLM can cite `path:line`, and lines that match a pattern are marked (`NNNN > ` instead of `NNNN | `).
2. **Chunking.** The excerpts are packed, in order and READMEs first, into chunks of at most `CHUNK_MAX_CHARS` characters, as pseudo-XML with the file contents in CDATA sections. A file is split only if it alone exceeds a chunk. From the second chunk on, an excerpt of the main README is repeated so that the LLM knows which component it is looking at.
3. **LLM analysis.** One request per chunk, in sequence. The system prompt holds the role, the rules and the output schema. The user message holds only the data, and the prompt tells the model to treat it as data, never as instructions. A failed chunk (API error or non-JSON answer) does not stop the following ones.
4. **Merging.** The partial reports are merged into one report:
   - jurisdiction: for military use and for each agency, the strongest status wins (`yes`, then `possible`, then `no-evidence`), and relations and evidence are combined;
   - cryptography: duplicate assets found in several chunks become a single asset. Lists are combined (`unknown` is dropped from a list that holds other values), and for the other fields the most reliable value wins (from the corpus, then inferred, then `unknown`).

   Values outside the closed vocabularies are reported in the console for review.

The regular expressions are deliberately broad. Many matched lines are not hints or contain no cryptography (a `Cast` type conversion, an `ENC` acronym, a person named Simon). The prompts tell the LLM to discard them.

## Report format

```json
{
    "name": "vault",
    "version": "1.4.0",
    "purl": "pkg:github/example/vault@1.4.0",
    "timestamp": "2026-10-31T09:00:00Z",
    "jurisdiction": {
        "militaryUse": {
            "status": "no-evidence",
            "evidence": []
        },
        "agencies": [
            {
                "agency": "doe",
                "relation": ["development", "funding"],
                "status": "yes",
                "evidence": [
                    {
                        "location": "LICENSE:4",
                        "content": "Produced at Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344",
                        "rationale": "Code produced by a DOE laboratory, under a DOE contract"
                    }
                ]
            }
        ]
    },
    "encryption": [
        {
            "detectionLocations": ["src/storage/vault.c:42", "src/storage/vault.c:118"],
            "detectionContent": "EVP_EncryptInit_ex(ctx, EVP_aes_256_gcm(), NULL, key, iv)",
            "usageDescription": "Encrypts secrets stored on disk",
            "assetType": "algorithm",
            "algorithmFamily": "AES",
            "parameterSetIdentifier": "256",
            "keyLengthBits": 256,
            "cryptoFunctions": ["encrypt", "decrypt"],
            "securityObjective": ["confidentiality"],
            "standardReference": ["ISO/IEC 18033-3"],
            "standardStatus": "standard"
        },
        {
            "detectionLocations": ["src/net/client.c:15"],
            "detectionContent": "SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION)",
            "usageDescription": "Protects communications with the synchronization server",
            "assetType": "protocol",
            "protocolType": "tls",
            "protocolVersion": "1.3",
            "securityObjective": ["confidentiality", "authentication", "integrity"],
            "standardReference": ["IETF RFC 8446"],
            "standardStatus": "standard"
        }
    ]
}
```

Keys are in English. Values taken from the source, such as the `content` and `detectionContent` excerpts, are copied verbatim; the other values, including `rationale` and `usageDescription`, are in English.

### Component identity

`name`, `version` and `purl` ([Package URL](https://github.com/package-url/purl-spec)) identify the component. When the source is an archive file, `fileName` (its name) and `fileSha256` (the hexadecimal SHA-256 of the file as given) follow them. `timestamp` is the start time of the run, in UTC, in ISO 8601 format with the `Z` suffix (for example `2026-10-31T09:00:00Z`).

### `jurisdiction`

| Field | Description |
|---|---|
| `militaryUse.status` | `yes`: stated explicitly in the corpus (declared military purpose, ITAR or USML marking). `possible`: indirect or ambiguous hint (military vocabulary without a stated military purpose, compliance with a MIL-STD or STANAG, an acronym the context cannot resolve). `no-evidence`: nothing found, which does not prove absence. |
| `agencies[].agency` | `department-of-state`, `treasury-ofac`, `nrc`, `doe`, `pto` or `dod-fms`. An agency is listed only if a hint was found. |
| `agencies[].relation` | `development` (the agency or its laboratories wrote the code) and/or `funding` (contract, grant or declared funding). |
| `agencies[].status` | Same levels as `militaryUse.status`. A DoD Distribution Statement (A to F) gives `dod-fms` with the status `yes`. |
| `agencies[].distributionStatement` | Only for a Distribution Statement found unambiguously: its letter and text, as written in the source, for example `A. Approved for public release`. If several are found, the most restrictive one is kept (from A, public release, to F). |
| `evidence[]` | Up to 5 hints per question or agency per chunk: `location` (`path:line`, or `repoUrl`), `content` (the excerpt), `rationale` (why it is a hint). |

A hint must concern the component itself: its purpose, intended users, authors, funding or legal notices. Processing an agency's data (screening against OFAC sanctions lists), applying a standard it published (DoD 5220.22-M disk wiping), marketing phrases ("military-grade encryption") and video game vocabulary are not hints. The LLM bases its answer on the corpus only, not on what it knows about the project.

### `encryption`

The inventory covers the cryptography of the deployable component. It excludes cryptography used only for version control or repository access (Git hashes, signed commits, CI/CD SSH keys) and anything that is not deployed (tests, examples, benchmarks, build scripts, development dependencies, license texts). An asset is an algorithm with its parameter set, a protocol with its version, or a certificate format: AES-128 and AES-256 are two assets. An empty list is a valid result.

Every asset has:

| Field | Description |
|---|---|
| `detectionLocations` | Up to 5 representative `path:line` locations per chunk, combined across chunks. |
| `detectionContent` | Excerpt of the most representative line. |
| `usageDescription` | What the asset is used for in the deployed component, written by the LLM (never with the ` ?` suffix). |
| `assetType` | `algorithm`, `protocol`, `certificate`, or `unknown` (cryptography is present but its nature cannot be determined). |
| `securityObjective` | List of `confidentiality`, `authentication`, `signature`, `integrity`, `right-management`, `entertainment`, `medical`, `other`, `unknown`. Encryption that serves only right management, entertainment or medical records is classified under that objective, not under `confidentiality`. |
| `standardReference` | List of the references of the standards that describe the asset, as `<body> <reference>` (for example `IETF RFC 8446`), limited to the bodies cited in EAR §772.1: IEEE, IETF, ISO, ITU, ETSI, 3GPP, TIA, GSMA. NIST (including its FIPS publications) is excluded, being a national body. The LLM gives a reference only when it is obvious, and lists every candidate when it hesitates between several standards: what matters is that at least one standard describes the asset. `["unknown"]` when no standard obviously describes it. Never with the ` ?` suffix. |
| `standardStatus` | Standardization status, as in the EAR definition of "non-standard cryptography" (§772.1): `standard` (adopted or approved by one of the bodies listed under `standardReference`), `published` (published but not adopted by those bodies, for example Blowfish, or an algorithm standardized only by NIST), `proprietary`, `unknown`. |

Depending on `assetType`, an asset also has the following fields. A field that does not apply to the asset type is omitted:

| `assetType` | Fields |
|---|---|
| `algorithm` | `algorithmFamily`, `parameterSetIdentifier`, `keyLengthBits` (effective key length in bits, parity bits excluded, for comparison with the thresholds of ECCN 5A002.a: an integer, `"N ?"` if inferred, `not-applicable` for keyless algorithms such as hash functions, or `unknown`), `cryptoFunctions` (list of `keygen`, `encrypt`, `decrypt`, `sign`, `verify`, `hash`, `mac`, `kdf`, `tag`, `keywrap`, `keyunwrap`, `encapsulate`, `decapsulate`). |
| `protocol` | `protocolType` (`tls`, `ssh`, `ipsec`, `ike`, `sstp`, `wpa`, `dtls`, `quic`, `eap-aka`, `eap-aka-prime`, `prins`, `5g-aka`, `other`, `unknown`), `protocolVersion`, and `protocolName` when `protocolType` is `other`. |
| `certificate` | `certificateFormat`. |

**Levels of evidence.** An asset exists in the report only if a line of the corpus shows it. For each field, a value found in the corpus is copied as is. Otherwise, the LLM may infer it from its own knowledge (a library's default key size, for example) and adds the ` ?` suffix, as in `"2048 ?"`. Without a basis for inference, the value is `unknown`. `usageDescription`, `standardReference` and the closed-vocabulary fields never take the suffix.

### Incomplete analyses

If some chunks fail, the report says so, so that a partial report cannot pass for a complete one:

```json
"incompleteAnalysis": {"failedParts": ["2/5", "3/5"], "totalParts": 5}
```

This field is added inside `jurisdiction` for the jurisdiction analysis, and at the root of the report for the cryptography analysis. If every jurisdiction chunk fails, `jurisdiction` contains only `incompleteAnalysis`, and no misleading `no-evidence`. If every chunk of both analyses fails, no JSON report is written. If no file matches either analysis, the report is `{"trade_compliance_analysis": []}` and the LLM is not called.

## Limitations

- Detection starts with regular expressions: a hint or an algorithm the patterns do not cover (unusual names, cryptography hidden behind a generic API) never reaches the LLM. READMEs are the exception, since they are always sent in full.
- Only the files in the source directory or archive are analyzed. Dependencies are covered only if their source is in the repository (vendored), and `node_modules`, `build` and `target` are skipped.
- Files that are not valid UTF-8 are skipped without warning.
- LLM answers vary from one run to the next, and from one model to another.

## Development

```bash
pip install -r requirements-dev.txt   # passavant in editable mode, its dependencies, pytest and ruff
python -m pytest                       # full suite, no network: the OpenAI client is simulated
python -m ruff check .
python passavant.py <source>           # run from the clone, without installing
```

Passavant is a single module, [`passavant.py`](https://github.com/rdejeun/passavant/blob/main/passavant.py); its dependencies are declared in `pyproject.toml`. It is organized, like the tests, into common parts, then "Analysis 1: jurisdiction", then "Analysis 2: cryptography".

Conventions:

- Everything is in English: code, comments, prompts, console messages and report. The only exception is the French terms in the detection patterns, so that French-language repositories are also covered.
- The system prompts (`PROMPT_JURISDICTION_SYSTEM`, `PROMPT_CRYPTO_SYSTEM`) do not go through `str.format`, and the example schema at the end of each must remain strict JSON: the model copies whatever it sees. Tests check that the schemas are valid and consistent with the rules, and that the closed vocabularies (`JURISDICTION_VOCABULARIES`, `CRYPTO_VOCABULARIES`) match the prompt text: change them together.
- `JURISDICTION_PATTERNS` is case-sensitive, so that acronyms do not match ordinary words (`DOE` but not "John Doe"); spelled-out names use `(?i:...)` groups. `CRYPTO_PATTERNS` is case-insensitive. When you change a pattern, add positive and negative cases to [`tests/test_extraction.py`](https://github.com/rdejeun/passavant/blob/main/tests/test_extraction.py). Each false positive enlarges the context and costs extra LLM calls.

### Releasing

The version is defined once, by `__version__` in `passavant.py`. To publish a version on PyPI:

1. Set `__version__` to the new version, for example `0.2.0`, and commit.
2. Publish a GitHub release whose tag is that bare version (`0.2.0`, without a `v` prefix).

The [`Publish`](https://github.com/rdejeun/passavant/blob/main/.github/workflows/publish.yml) workflow then runs the tests and ruff on Python 3.12 and 3.13, builds the sdist and the wheel, checks that the tag matches `__version__`, and uploads both files to PyPI with provenance attestations. It authenticates through PyPI Trusted Publishing, so no token is stored: the PyPI project must declare the `rdejeun/passavant` repository, the `publish.yml` workflow and the `pypi` environment as a trusted publisher (for the first release, as a "pending publisher").

## License

[MIT](https://github.com/rdejeun/passavant/blob/main/LICENSE.md). The license file includes a notice on the use of generative AI tools in the development of the software.
