# Native Session Fabric API

Gray sessions are opaque server-side records. The browser receives one
hardened cookie containing a 256-bit random token; stores receive only its
SHA-256 digest.

## Stores

```gray
set $memory = session_store_memory(10000, 67108864);

set $database = sqlite_pool("var/app.sqlite", 4, 1000);
set $sqlite = session_store_sqlite($database);

set $redis = redis_pool("127.0.0.1", 6379, 16, 1000);
set $shared = session_store_redis($redis, "my-app:");
```

SQLite and Redis-compatible stores require `GRAY_SESSION_KEYS`. Risk signals
use the separate `GRAY_SESSION_RISK_KEYS` keyring.

## Lifecycle

| Native function | Result and contract |
|---|---|
| `session_start(request, store, policy)` | Resume or create; schedules a hardened cookie when the identifier changes. |
| `session_get(session, key)` | Isolated value or `nothing`. |
| `session_set(session, key, value)` | Validated, isolated, atomic replacement. |
| `session_delete(session, key)` | Delete one value. |
| `session_rotate(session)` | Atomic new identifier with bounded old-request grace. |
| `session_authenticate(session, level)` | Record monotonic authentication state and rotate atomically; level is 1–10. |
| `session_require_recent(session, within_ms, level)` | Boolean recent-authentication check. |
| `session_destroy(session)` | Invalidate the record and expire its cookie. |
| `session_destroy_user(store, user_id)` | Log out every session for one bound identity. |
| `session_stats(store)` | Low-cardinality aggregate store state. |

Set `user_id` to an `int` or nonempty `String` before account-scoped
operations.

## Cross-device management

```gray
set $sessions = session_list($session, "account-settings");
set $removed = session_revoke(
    $session,
    "account-settings",
    $sessions[0]["id"]
);
```

`session_list` returns application-scoped management identifiers,
`current`, creation/last-seen times, and authentication metadata. Management
identifiers are derived from an independent internal random identity. They are
not cookies, store digests, or authentication credentials.

## Browser and authentication protection

| Native function | Contract |
|---|---|
| `session_csrf_token(session, context)` | Stable 43-character token bound to context and session generation. |
| `session_csrf_verify(session, context, token)` | Constant-time verification; malformed values return `false`. |
| `browser_protect(request, policy)` | Host, Origin, Fetch Metadata, trusted-proxy, CSP nonce, and response-header policy. |
| `session_rate_limit(session, context, limit, window_ms)` | Session-scoped fixed-window decision. |
| `session_account_rate_limit(session, context, limit, window_ms)` | User-scoped fixed-window decision. |

Rate-limit results contain only `allowed`, `remaining`, and
`retry_after_ms`. SQLite transactions and Redis Lua keep decisions atomic
across workers.

## Privacy-preserving risk

```gray
set $risk = session_risk(
    $session,
    $request,
    "billing",
    [
        "retention_ms": 3600000,
        "challenge_score": 40,
        "reauthenticate_score": 70,
        "privilege_sensitive": true
    ]
);
```

The result contains `score`, coarse `reasons`, `recommendation`,
`baseline_reset`, and `retention_deadline_ms`. Recommendations are `allow`,
`rotate`, `challenge`, or `reauthenticate`; Gray never automatically denies
the request. Applications make the final decision.

Signals are separately keyed, application-scoped, optional, and
retention-bounded. Raw IP addresses and User-Agent strings are never stored.

## Redacted observability

```gray
set $events = session_security_events(100);
set $snapshot = observability_snapshot();
set String $metrics = prometheus_metrics("accounts");
```

The event recorder retains at most 512 process-local events. Its closed fields
are sequence, monotonic time, event, decision, and coarse reason. It cannot
contain a token, cookie, user ID, client address, User-Agent, CSRF secret,
encryption key, or stored value.

See the [storage adapters](session-storage.md),
[key rotation](session-key-rotation.md), and
[privacy and retention](session-privacy.md) guides.
