# scorpiox-identity-server-native

Native C CGI route handlers for **Personal Identity Server** — a local OpenID Connect (OIDC) and OAuth 2.0 authorization server.

Powered by `scorpiox-server.dll` (pure C HTTP engine) with zero external runtime dependencies.

## Architecture

```
scorpiox-server.dll   web_server_start(port, {root_dir: handlers/})
        │
        ▼  (native CGI executable dispatch)
  wellknown  authorize  token  revoke  introspect  userinfo  jwks  login  logout  end_session
  account  audit  api  index  _fallback
        │
        ▼
  JSON Data Store in IDENTITY_DATA_DIR:
    users.json    clients.json    tokens.json    secret.key    keys.json    revoked.json
    consents.json login_attempts.json login_attempts_ip.json audit_log.json
```

## Features

- **OpenID Connect Discovery**: `/.well-known/openid-configuration` & `/wellknown`
- **OAuth 2.0 Authorization Code Flow + PKCE**:
  - `S256` only (PKCE `plain` was dropped in v1.2.0 — OAuth 2.1)
  - Secure redirect URI validation: registration rejects any `redirect_uri` that is not an
    absolute `http://` / `https://` URI without a fragment or whitespace (v1.8.0, RFC 6749
    §3.1.2). `/authorize` re-checks the registered value, so a row written before v1.8.0
    cannot receive a code either. Exact matching at authorize time is unchanged.
- **Token Endpoint**:
  - `grant_type=authorization_code` (PKCE verification -> access_token + id_token + refresh_token)
  - `grant_type=refresh_token` (single-use refresh token rotation)
- **RFC 7009 /revoke + RFC 7662 /introspect** (v1.4.0): a relying party can withdraw its own
  tokens. `/revoke` is always `200` with an empty body (§2.2 — never leaks token existence) and
  revokes the whole refresh rotation family; revoked access tokens are deny-listed by `jti` in
  `revoked.json` so `/userinfo` and `/introspect` reject them immediately. `/introspect` returns
  the RFC 7662 claim set for an active token and exactly `{"active":false}` for anything else.
  Both are client-authenticated by the same `id_authenticate_client()` rule as `/token`.
- **JWT RS256** (v1.3.0+): RSA-2048 signing via vendored BearSSL subset; real JWKS; key rotation/pruning via /api?r=keys. HS256 tokens from v1.2.x remain verifiable for their lifetime (dropped in v1.4).
- **Roles (v1.3.1)**: `users.json` carries `role` (`owner`/`admin`/`user`). The first user created becomes `owner`; `/api` beyond `?r=status` requires owner/admin (or the `X-Identity-Admin` secret). A plain user can only read their own token list.
- **Password/legacy crypto**: Embedded pure-C SHA-256 / HMAC-SHA256 / PBKDF2 (100,000 iterations)
- **User Management**: Session cookies, login form / JSON authentication, password hashing
- **Sign-in audit log** (v1.9.0): every sign-in, failed sign-in, sign-out and password change is
  recorded in `audit_log.json` (bounded 2000, oldest dropped on write; an audit write can never fail a
  sign-in). Read it as JSON with `/api?r=audit` (newest first) or as a table at `/audit` — 302 to
  `/login` when signed out, 403 for a non-admin session, 200 for an owner/admin. The `ip` field is
  `X-Forwarded-For`'s first hop or the literal `"?"` (the engine does not export `REMOTE_ADDR`).
- **Last-administrator guard** (v1.9.1): `POST /api?r=users&action=delete` refuses to delete the
  last `owner`/`admin` — `{"ok":false,"error":"cannot delete the last administrator — create
  another owner or admin first"}`, status 200, `users.json` untouched. Without it two deletes leave
  an IdP with zero administrators and the only way back is the `X-Identity-Admin` secret, which no
  page exposes. `owner` and `admin` are one class; the secret caller is refused too.
- **Email validation** (v1.9.2): `POST /api?r=users&action=create` refuses a malformed address with
  `email must look like name@example.com` (or `email must not contain whitespace`), status 200,
  `users.json` unchanged. Empty is still allowed. The rule is one shared `id_email_check()`:
  exactly one `@`, non-empty local part, domain with a dot and non-empty labels, no
  whitespace/control characters — not RFC 5322. A row already stored is never re-validated.
- **Lockout messages name the wait** (v1.9.2): the per-caller throttle says
  `Too many failed attempts from this address. Try again in N s.` on the HTML door (the same
  sentence shape as the per-account lockout) and adds `"retry_after": N` to the JSON refusal while
  keeping `"error":"too_many_attempts"` byte-identical. N is the caller's real remaining window
  (1..600), computed once in `id_login_ip_retry_after()`.
- **Role change** (v1.9.3): `POST /api?r=users&action=set-role` changes an **existing** user's role —
  `username` + `role` (`owner` | `admin` | `user`, case-insensitive, normalised to lowercase).
  Success is `200 {"ok":true,"username":…,"role":…,"user_id":…}` and `users.json` carries the new
  role. `404 {"ok":false,"error":"user not found"}` for an unknown username (resolved
  case-insensitively). `400` for a role we do not have (`invalid role (must be owner, admin, or
  user)`) — a typo must never silently fold to `user` the way `id_role_name()` does when *reading*
  a store — and `400` for demoting the **last** `owner`/`admin` (`cannot remove the last
  administrator — assign another owner or admin first`), the same guard class v1.9.1 puts on
  delete. `GET` stays `405 method_not_allowed` (the v1.2.0 CSRF rule). No store schema change, no
  new route, no migration — an existing row keeps its id, sessions and audit history.
- **Administration API**: `/api?r=users`, `/api?r=clients`, `/api?r=tokens`, `/api?r=status`,
  `/api?r=consents`, `/api?r=audit`
- **Zero Dependencies**: Pure C99, vendored `yyjson` (MIT), embedded crypto.

## Build

### Linux
```bash
mkdir build && cd build
cmake ..
cmake --build . -j8
```

### Windows (MinGW static)
```powershell
cmake -G Ninja -DCMAKE_BUILD_TYPE=Release -S . -B build
cmake --build build --config Release
```

## License
MIT / Public Domain.
