Metadata-Version: 2.4
Name: typsa-sso-client
Version: 0.3.0
Summary: Desktop Typsa SSO helper client for Lambda-based Microsoft auth flows.
Author: TYPSA
License-Expression: MIT
Project-URL: Homepage, https://pypi.org/project/typsa-sso-client/
Project-URL: Repository, https://github.com/adtTEyS/SSO-Package-Pip.git
Project-URL: Issues, https://github.com/adtTEyS/SSO-Package-Pip.git/issues
Keywords: sso,desktop,oauth,openid,microsoft,lambda
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: test
Requires-Dist: pytest>=7; extra == "test"
Dynamic: license-file

# typsa-sso-client

Python helper for desktop applications that sign users in through the TYPSA SSO Lambda (Cognito + Microsoft Entra ID).

- **`authenticate()` / `authenticate_strict()`** use protocol v2 and still return `TokenResponse`, so existing applications keep the same call. The flow validates a per-attempt `state`, binds a one-time code to PKCE, keeps tokens out of the browser URL, and only talks to SSO endpoints on an explicit allowlist.
- **`authenticate_secure()`** is the same protocol and returns `AuthResult` (tokens plus the redirect URI used for that attempt).
- **Legacy (deprecated):** `authenticate_with_loopback()`, `start_auth()` and `complete_auth()` still speak the 0.2.4 protocol.

Security design: [SECURITY.md](SECURITY.md). Upgrading from 0.2.4: [MIGRATION.md](MIGRATION.md). Changes: [CHANGELOG.md](CHANGELOG.md).

## Install

```bash
pip install typsa-sso-client
```

No runtime dependencies (standard library only). Python ≥ 3.9.

## Quick start (secure flow)

```python
from sso_typsa import TypsaSSOClient, SSOAuthError

client = TypsaSSOClient.set_config()

try:
    # Existing call. Now runs protocol v2 and still returns TokenResponse.
    tokens = client.authenticate("user@typsa.es", timeout_seconds=180)  # 10..600
    # tokens = client.authenticate_strict("user@typsa.es")  # also requires refresh_token
except SSOAuthError as exc:
    print("Login failed:", exc.error_code)   # safe to log; never contains tokens
else:
    id_token = tokens.id_token
    refresh_token = tokens.refresh_token     # opaque: store in the OS credential vault
```

What happens:

1. A fresh `state` and PKCE `code_verifier` are generated for this attempt.
2. A single-use callback server is bound to `127.0.0.1` on an ephemeral port (or `callback_port=`), at `callback_path="/callback"`.
3. The browser opens `…/sso?protocol_version=2&email&redirect_uri&state&code_challenge&code_challenge_method=S256`.
4. After sign-in, the Lambda redirects to `http://localhost:<port>/callback?code=<one-time>&state=<state>`.
5. The client checks the method, exact path, `Host`, parameters and `state`, then redeems the code at `POST …/sso/token` with the verifier.
6. Only then does the browser show *Authentication complete*. Any failure shows a safe error page and raises.

`authenticate_secure()` is the same login and returns `AuthResult` (`result.tokens` is the `TokenResponse`). There is **no fallback** to the legacy protocol. If the server answers in the legacy format, `SSOProtocolError` is raised.

A `redirect_uri` passed to `authenticate()` must be `http://localhost` or `http://127.0.0.1` with a port; that port and path are used for the loopback listener, and the URI sent to SSO is `http://localhost:<port><path>`. The listener still binds `127.0.0.1`. Omit `redirect_uri` to use an ephemeral port. `SSO_REDIRECT_URI` is not used.

### Cancellation, GUI apps, and no-browser environments

```python
import threading

cancel = threading.Event()
# call cancel.set() from your UI thread to abort; raises SSOCancelledError
result = client.authenticate_secure("user@typsa.es", cancel_event=cancel)

# Handle the URL yourself (treat it as sensitive; do not log it)
result = client.authenticate_secure("user@typsa.es", open_browser=False, on_auth_url=show_link)
```

`authenticate_secure` blocks the calling thread, so run it in a worker thread in Tk/Qt applications.

### Refreshing tokens

```python
tokens = client.refresh_tokens(refresh_token, username=claims["cognito:username"])
tokens.id_token, tokens.access_token, tokens.expires_in
```

Raises `SSORefreshError` (with `status_code`) when the refresh token is expired or revoked. When that happens, call `authenticate_secure()` again.

## What your application must still do

The package handles the authentication protocol. It does **not** decide whether the user may use your application.

1. **Validate the ID token** before trusting any claim: signature against the Cognito JWKS (`https://cognito-idp.eu-west-1.amazonaws.com/<userPoolId>/.well-known/jwks.json`), `iss`, `aud` (your Cognito app client ID), `exp`, and `token_use == "id"`. Getting a token back from the package isn't proof of authentication.
2. Apply application roles and permissions, and manage your own session.
3. Store the refresh token in the OS credential store (for example `keyring`). Never write it to plain files or logs.
4. Handle logout, refresh and re-authentication.

Example using PyJWT (not a dependency of this package):

```python
import jwt  # pip install "pyjwt[crypto]"

jwks = jwt.PyJWKClient(f"https://cognito-idp.eu-west-1.amazonaws.com/{USER_POOL_ID}/.well-known/jwks.json")
claims = jwt.decode(
    result.id_token,
    jwks.get_signing_key_from_jwt(result.id_token).key,
    algorithms=["RS256"],
    audience=COGNITO_APP_CLIENT_ID,
    issuer=f"https://cognito-idp.eu-west-1.amazonaws.com/{USER_POOL_ID}",
)
assert claims["token_use"] == "id"
```

## Configuration

| Setting | Where | Secure flow | Legacy flow |
|---|---|---|---|
| SSO endpoint | `DEFAULT_SSO_AUTHORIZE_URL`, `authorize_url=`, or env `SSO_AUTHORIZE_URL` / `TYPSA_SSO_AUTHORIZE_URL` | Host must be in `allowed_hosts` | Used as is |
| Trusted SSO hosts | `allowed_hosts=` (code only; default `DEFAULT_TRUSTED_SSO_HOSTS`) | Enforced | — |
| Redirect URI | `redirect_uri=` on `authenticate()`, or env `SSO_REDIRECT_URI` / `TYPSA_SSO_REDIRECT_URI` / `SSO_CALLBACK_URL` | Env vars ignored. An explicit loopback `redirect_uri` selects port and path; the URI sent is `http://localhost:<port><path>`. Omitted means an ephemeral port | Env value used by `authenticate_with_loopback` / `start_auth`; host must be `localhost`/`127.0.0.1` |
| Callback port / path | `callback_port=` (0 = ephemeral, or 1024–65535), `callback_path=` | Validated | — |
| Timeout | `timeout_seconds=` | 10–600 s, out-of-range raises | As given |
| HTTP timeout | `TypsaSSOClient(..., http_timeout_seconds=15)` | Token/refresh requests | — |

Environment variables can **not** add trusted hosts. To trust another stage or a local development server, list it in code:

```python
client = TypsaSSOClient(
    "http://localhost:3000/dev/sso",
    allowed_hosts=("localhost:3000",),   # plain http only for explicit loopback hosts
)
```

The library does not call `load_dotenv()`. See `.env.example`.

## Errors

All exceptions derive from `SSOAuthError` and expose a safe `error_code`.

| Exception | Meaning |
|---|---|
| `SSOConfigurationError` | Untrusted endpoint, invalid option, port unavailable |
| `SSOStateMismatchError` | Callback `state` missing or not matching this attempt |
| `SSOCallbackError` | Malformed callback (duplicate/unknown parameters, bad code) |
| `SSOServerError` | SSO returned an OAuth error (`.error`, e.g. `access_denied`, `unauthorized_client`) |
| `SSOProtocolError` | Server answered with the legacy protocol (Lambda not upgraded) |
| `SSOTokenExchangeError` | `/sso/token` rejected the code (`.status_code`, `.error`) |
| `SSOInvalidTokenResponseError` / `SSOTokenNotFoundError` | Token response malformed or missing tokens |
| `SSONetworkError` | SSO service unreachable |
| `SSOTimeoutError` / `SSOCancelledError` | No callback in time / cancelled by the caller |
| `SSORefreshError` | Refresh rejected |

## Legacy API (0.2.x, deprecated)

`start_auth()`, `complete_auth()` and `authenticate_with_loopback()` keep the 0.2.4 wire contract (`/sso?email&redirect_uri`, tokens returned on `{redirect_uri}login-success`). `authenticate_with_loopback()` emits `DeprecationWarning`. These methods will be removed in 1.0. See [MIGRATION.md](MIGRATION.md).

## Development

```bash
pip install -e ".[test]"
python -m pytest                     # unit tests (no network, no real accounts)
```

Cross-repository contract tests against the real Lambda controllers, with mocked Cognito and MongoDB:

```powershell
# in TEST-Serverless-Framework
node test/e2e/desktop-harness.mjs
# here
$env:TYPSA_SSO_E2E_BASE_URL = "http://localhost:3000/dev/sso"
python -m pytest tests/e2e
```

## Release process

`.github/workflows/release.yml` builds and **publishes to PyPI on every push to `main`** (and on `v*` tags). Merging the version bump therefore publishes it.

1. Make sure the SSO Lambda with protocol v2 is deployed to the target stage first. `authenticate()` and `authenticate_secure()` raise `SSOProtocolError` against an old Lambda. `authenticate_with_loopback()` is unaffected.
2. Bump `version` in `pyproject.toml` and `__version__` in `src/sso_typsa/__init__.py`, and update `CHANGELOG.md`.
3. Locally: `python -m build`, then install the wheel in a clean virtualenv and run `python -m pytest`.
4. Merge to `main` (or push tag `vX.Y.Z`). The workflow publishes with `skip_existing: true`.

The desktop UI demo lives in `desktop_app/app.py` and consumes the package; it is not part of the distribution.
