# Security

Security in **El Sewedy In Sawa** centers on a **dual-token authentication model**, encrypted on-device storage, disciplined session invalidation, and a privacy-conscious posture (no remote telemetry, no continuous location tracking). This document describes those mechanisms and notes one item to harden before production.

## Authentication Model (Dual-Token)

The app separates client identity from employee identity:

- **Gateway / client JWT** — sent in the `Authorization: Bearer` header on **every** request.
- **Employee session token** (`employee_token`) — sent **only inside the JSON-RPC request body** of protected routes, **never in a header**.

`DioHelper.postProtected` enforces the token-in-body requirement for protected routes. Login and registration are public and identify the user by credentials. Full endpoint detail is in [API_SUMMARY.md](./API_SUMMARY.md#dual-token-authentication-model).

## Secure Storage

Sensitive material is kept in **`flutter_secure_storage`**, backed by the platform **Keychain (iOS)** / **Keystore (Android)**:

- Employee session token
- `employee_code`
- `employee_pass`

Storing credentials securely is what enables **silent re-authentication** without prompting the user again.

## JWT Handling

`JwtUtil` is a **dependency-free** helper that provides:

- `isJwt` — structural validation
- `isExpired` — expiry check via the `exp` claim
- `expirationDate` — decoded expiry timestamp

This lets the app detect local token expiry before a request is even sent.

## Session Guarding & Invalidation

`SessionGuard` centralizes **session-invalidation detection** and classifies each case:

| Signal | Interpretation |
|--------|----------------|
| Local `exp` expired | Recoverable expiry |
| HTTP `401` | Recoverable expiry |
| Body markers (e.g. `"expired"`, `"token doesn't match"`) | Evaluated for recoverable vs. genuine mismatch |

The guard distinguishes two outcomes:

1. **Recoverable expiry** → **silent re-authentication** from saved credentials, then retry the original request once. This is **single-flight**: only one re-auth runs at a time, and an interceptor-free login client is used to avoid recursion.
2. **Genuine cross-device mismatch** (the session was superseded elsewhere) → **force-logout** via `AppNavigator.forceLogout`, protected by a **single in-flight lock** so multiple failing requests can't trigger repeated logouts.

There is **no background polling or timers** — session checks happen in the request/response path, not on a schedule.

## Offline Tolerance

Session restore is resilient to connectivity gaps: if the network is unreachable during restore, the app **keeps the session** rather than logging the user out. Only an **explicit server rejection** clears the session. This avoids punishing users for transient network loss.

## Telemetry & Privacy

- **`ErrorLogger` is debug-only** (`kDebugMode`). There is **no remote crash telemetry** and **no PII shipped off-device**.
- **Location is read only during check-in/out** for geofence verification — never continuously. See [FEATURES.md](./FEATURES.md#attendance--live-punch--geofencing).
- The in-app **Privacy Policy** states: role-based access control, encryption / secure communication, secure authentication, monitoring and logging, data retention per applicable law, and an HR contact for data-rights requests (`Holding.HR@elsewedy-ind.com`).

## Production Hardening Note (Honest Disclosure)

The gateway token supports a **build-time override** via `--dart-define=FALLBACK_TOKEN`. A **default gateway JWT literal is currently present in source as a fallback**. For production hardening, this literal should be **supplied through the build-time define** (or otherwise injected at build) and **removed from source**, so that no gateway credential is committed to the repository.

```bash
# Recommended: inject the gateway token at build time
flutter build apk --dart-define=FALLBACK_TOKEN=<gateway_jwt>
flutter build ios --dart-define=FALLBACK_TOKEN=<gateway_jwt>
```

## Security Summary

| Control | Status |
|---------|--------|
| Dual-token auth (header + body separation) | Implemented |
| Encrypted credential storage (Keychain/Keystore) | Implemented |
| Dependency-free JWT expiry checks | Implemented |
| Centralized session guarding (recoverable vs. force-logout) | Implemented |
| Single-flight silent re-auth | Implemented |
| Offline-tolerant session restore | Implemented |
| No remote telemetry / no PII off-device | Implemented |
| Location read only on punch | Implemented |
| Gateway token removed from source | **To harden** (use `--dart-define`) |
