Metadata-Version: 2.4
Name: tlx-sdk
Version: 0.3.2
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Rust
Classifier: License :: OSI Approved :: MIT License
Requires-Dist: pytest>=7.0 ; extra == 'dev'
Requires-Dist: hypothesis>=6.0 ; extra == 'dev'
Provides-Extra: dev
License-File: LICENSE
Summary: TLX Vendor SDK — Python bindings for ETDA-compliant document exchange
Keywords: tlx,etda,e-tax,document-exchange,jwe,invoice
Author-email: Xcellence <rddev@xclnc.com>
Maintainer-email: Xcellence <rddev@xclnc.com>
Requires-Python: >=3.9
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM

# tlx-sdk (Python)

Python SDK for the TLX document exchange platform. Built on the Rust `tlx-sdk` core
via [PyO3](https://pyo3.rs): RSA-4096 key generation, JWE encrypt/decrypt, ETDA
envelope and payload validation, canonical hashing, and the 33 platform operations
routed through the SDK Gateway.

Key generation, encryption, decryption, validation and hashing all run **in your
process**. The private key, its passphrase and the plaintext document never leave the
machine.

## Installation

```bash
pip install tlx-sdk
```

**Interpreter version matters.** The published wheels are built for **CPython 3.12**
only, for macOS arm64, macOS x64, manylinux x64, manylinux aarch64 and Windows x64.
PyO3 is not built against the stable ABI here, so pip on any other interpreter version
falls back to the sdist and compiles it, which needs a Rust toolchain. A matching
environment avoids that:

```bash
python3.12 -m venv .venv
.venv/bin/pip install tlx-sdk
```

Installing from the offline delivery package instead of the index:

```bash
.venv/bin/pip install python/wheels/tlx_sdk-<version>-cp312-cp312-<platform>.whl
.venv/bin/pip install python/wheels/tlx_sdk-<version>.tar.gz   # any other interpreter
```

## Start here

Two runnable examples cover the whole flow. **They are not inside the wheel** — a
wheel carries the importable package only. Take them from the `python/examples/`
directory of the delivery package, or from `tlx-sdk-python/examples/` in the sdist:

```bash
pip download tlx-sdk --no-binary :all: --no-deps -d .   # fetches the sdist
tar -xzf tlx_sdk-*.tar.gz
cd tlx_sdk-*/tlx-sdk-python/examples
python 01_convert_and_validate.py      # ERP record -> standard message -> validate
python 02_send_and_receive.py          # encrypt, send, delivery status, receive
```

Example 1 needs nothing but this package. Example 2 needs a gateway URL, a
Participant_Key and a paired partner.

`examples/README.md` alongside them covers what the SDK does and does not do — in
particular, it does **not** convert ERP data into a standard document. It recognises
which dialect a payload is written in and validates it; the mapping is yours, and
`examples/erp_to_standard.py` is a worked reference of it.

## Quick start

```python
import asyncio
import json
import uuid
from datetime import datetime, timezone

import tlx_sdk

sdk = tlx_sdk.TlxSdk(
    "https://sdk-gateway.tlx.or.th",   # SDK Gateway base URL
    "tlxk_...",                        # Participant_Key from portal -> API Key
)

# 1. Keys — generated locally; only publicJwk is ever published
keys = sdk.generate_key_pair("a-strong-passphrase")

# 2. An ETDA envelope. camelCase keys; senderId/receiverId are 13-digit Thai tax IDs.
message = {
    "messageId": str(uuid.uuid4()),
    "timestamp": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z"),
    "senderId": "0105561234567",
    "receiverId": "0105569876543",
    "documentType": "PURCHASE_ORDER",
    "version": "1.0",
    "payload": {
        "sourceDocType": "PURCHASE_ORDER",   # marks the ERP_FLAT dialect
        "poNo": "PO-26-00001",
        "poDate": "2026-08-20T00:00:00.000Z",
        "poAmt": 192600,
        "products": [
            {"itemNo": 1, "prodCode": "W0002", "prodName": "Wire",
             "uomCode": "ROLL", "qty": 100, "unitPrice": 1800},
        ],
    },
}

# 3. Validate BEFORE encrypting — afterwards the payload is ciphertext and the
#    receiver is the first party who can find a problem with it.
sdk.validate_message(message)                 # envelope only
report = sdk.inspect_payload(message)         # every payload error at once
if not report["valid"]:
    for e in report["errors"]:
        print(f"{e['path']}: {e['message']}")


async def send() -> None:
    # 4. Encrypt for the RECEIVER's public key, then relay through the gateway
    partner_keys = json.loads(await sdk.list_partner_keys(message["receiverId"]))
    jwe = sdk.encrypt_message(message, json.dumps(partner_keys["data"][0]["jwk"]))
    sent = json.loads(
        await sdk.send_message(
            message["senderId"], message["receiverId"], message["documentType"], jwe
        )
    )

    # 5. Receiving: decrypt locally, hash locally, send only the hash
    plain = sdk.decrypt_message(jwe, keys["privateJwkEncrypted"], "a-strong-passphrase")
    digest = sdk.compute_canonical_hash(plain)        # JCS-SHA256
    await sdk.verify_message_hash(sent["messageId"], digest, "JCS-SHA256")


asyncio.run(send())
```

## API surface

Everything is a method on `TlxSdk`. Local operations are synchronous and return
Python objects; **network operations are `async` and resolve to a JSON string** —
`await` then `json.loads`.

| Local (synchronous) | Purpose |
|---|---|
| `generate_key_pair(passphrase)` | RSA-4096 keypair; private half returned encrypted (AES-256-GCM, PBKDF2 600k) |
| `validate_message(message)` | Envelope rules only — payload may be any JSON. Raises `ValidationError`. |
| `validate_message_strict(message)` | Envelope **and** the payload contract for its document type |
| `inspect_payload(message)` | Returns `{valid, shape, errors[], rules_source}` — every payload error at once |
| `encrypt_message(message, recipient_public_jwk)` | JWE Compact Serialization |
| `decrypt_message(jwe, private_jwk_encrypted, passphrase)` | Returns the message dict |
| `compute_canonical_hash(message)` | JCS-SHA256 over `payload`, for the hash-only verify flow |
| `install_payload_contract` / `export_payload_contract` / `installed_payload_contracts` / `clear_payload_contracts` | Override the compiled validation tables without republishing this package |

Async methods cover keys and partner keys, participant updates, the key rotation
lifecycle, send/list/get messages, delivery status and hash verification, the PULL
inbox, matchings, partner search and the full pairing lifecycle, document-type
registration, and schema lookup. Full list with signatures:
`tlx_sdk/_tlx_sdk.pyi`.

Both constructor arguments are required; a missing or empty one raises `ConfigError`
naming the field.

## When validation happens

Never on its own, on the way out. `encrypt_message` is a crypto primitive: it enforces the
envelope's *structure*, because it deserializes into a typed message and a missing
`timestamp` or `senderId` fails there, and it checks nothing else. A payload that breaks
its document contract will be sealed, sent, and accepted — the platform stores only
ciphertext, so no later layer can look inside. Nothing downstream catches it.

Inbound is different: `decrypt_message` validates the envelope automatically.

So validate before you seal. `encrypt_message_validated` is the two calls in the order that
cannot be got wrong:

```python
jwe = sdk.encrypt_message_validated(message, public_jwk, "enforced")
```

| mode | envelope | document contract | payload no contract covers |
|---|---|---|---|
| `envelope` | fails | not checked | passes |
| `warn` | fails | logged, does not fail | passes |
| `strict` | fails | fails | **passes** |
| `enforced` | fails | fails | **fails** |

`strict` cannot tell *checked and clean* from *not checked*, and answers the same either
way. Coverage is per (`documentType`, dialect) and it is uneven: thirteen of the fifteen
types have a table in at least one dialect, but a payload written in the flat ERP dialect
is checked for only two of them, against eleven in the CII dialect. Whether `strict`
checked anything therefore depends on the dialect you write, and it will not tell you. Use `enforced` when the requirement is
that nothing leaves unless a contract vouched for it, and `strict` when an unchecked
payload is acceptable. `validate_message_with_mode(message, mode)` runs the same check without
encrypting.

## Two answers that look alike

`inspect_payload` reporting `valid: True` with `rules_source: "none"` means the
payload was **not checked** — no captured payload backs that `documentType` + `shape`
pair, so no rule table had an opinion. That is not the same as correct, and
`rules_source` is the only field that separates them. `"compiled"` means the tables in
this build judged it; a version string means an installed contract did.

## Before a send will land

1. Sender and receiver must be **paired**. Accepting a pairing request is what creates
   the matching; without one the send is `403 Participants are not matched`.
2. The **receiver** must have registered that `documentType`, or the send is `422`.

## Exceptions

Importable from `tlx_sdk`: `ConfigError`, `ValidationError`, `CryptoError`,
`HttpError`, `AuthError`, `ConnectionError`, `TimeoutError`, `KeyNotFoundError`.

Note that `ConnectionError` and `TimeoutError` shadow the Python builtins of the same
name inside this namespace, so import them explicitly rather than relying on bare
`except ConnectionError`.

## Further reading

Relative links are deliberately absent here: this file is rendered on pypi.org, which
does not rewrite them, so `./examples` would resolve against pypi.org and 404. The paths
below are where the files actually are.

- `python/examples/` in the delivery package, or `tlx-sdk-python/examples/` in the
  sdist — runnable, and the reference ERP converter. Not in the wheel.
- `docs/VENDOR_GUIDE.md` in the delivery package — the integrator manual (Thai)
- `docs/sdk-coverage-matrix.md` — which capability exists in which layer and language
- `docs/BUILDING-THE-SDK.md` — building from source, needed for any interpreter other
  than CPython 3.12

