Back to .md Directory

Browser HITL Implementation Guide

Maps the architecture, state machines, API modules, and test coverage for a browser-based human-in-the-loop authentication system.

May 2, 2026
0 downloads
1 views
ai agent rag claude workflow automation
View source

What this file does

Maps the architecture, state machines, API modules, and test coverage for a browser-based human-in-the-loop authentication system.

When to use it

  • Onboarding to the adoptai/tabby codebase
  • Planning changes to session or baton state machines
  • Reviewing security rules for CDP streaming or auth tokens
  • Setting up local development or Kubernetes deployment

Assumes this stack

NestJSTypeORMPostgreSQLRedisNATS JetStreamPlaywright

Browser HITL Implementation Guide

Reference document for AI agents and developers working on this codebase.

Source of Truth Hierarchy

  1. specification_docs/MVP_BROWSER_SPEC_CODEX.md (v6) — canonical specification
  2. implementation_tracker/ — task plan and sprint tracking
  3. docs/SPECIFICATION_DIVERGENCE.md — where implementation differs from spec
  4. docs/internal/CLAUDE_RED_TEAM_REMEDIATIONS.md — security hardening audit trail
  5. docs/ARCHITECTURE_DECISIONS.md21 ADRs with reasoning (read before proposing architectural changes)
  6. docs/HEADLESS_AUTH_PROVIDER_SPEC.md — Headless Auth Provider workflow specification (the primary production use case)
  7. docs/SPEC_GAP_ANALYSIS.md — Red team gap analysis (14 gaps, all resolved by ADRs)
  8. implementation_tracker/phase_5/ — Phase 5 (Auth Provider Hardening) task plan and execution log

Technology Stack

LayerTechnologyVersion
FrameworkNestJS10.x
ORMTypeORM0.3.x
DatabasePostgreSQL16
CacheRedis (ioredis)7
MessagingNATS JetStream2.10
Object StorageMinIOS3-compatible
BrowserPlaywright + ChromiumHeaded (Xvfb) + Headless (CDP)
StreamingnoVNC (VNC mode) + CDP screencast (CDP mode)Dual-mode, per-app config
AuthPassport.js + JWTbcrypt cost 12
Validationclass-validatorDTO-based
Metricsprom-clientPrometheus-compatible
Docs@nestjs/swaggerOpenAPI 3.0
Monorepopnpm + NXWorkspace protocol
DeploymentHelm 3K8s native
CI/CDGitHub Actionslint+test+build+sbom+e2e

Monorepo Structure

apps/
  api/           NestJS API (20 modules, 15 entities, 24 test suites)
  controller/    Session reconciler (pod lifecycle, state machine)
  worker/        Browser automation (Playwright, DSL runner, OTP relay)
  slack-bot/     Slack HITL bridge (soft polling, OTP forwarding)
  teams-bot/     Teams HITL bridge (Bot Framework adapter)
  admin-ui/      Admin dashboard (server.js)
packages/
  shared/        Types, constants, state machines, validators, env helpers
charts/
  browser-hitl/  Helm chart (26 templates, values + local + production tiers)
infra/
  docker/        Dockerfiles for 7 services
scripts/         E2E batches (Python), local setup scripts (bash)
docs/            Architecture, functional overview, divergence, security audit

Critical Implementation Rules

  1. NATS sync_interval MUST be always — Jepsen-validated durability guarantee. Never change.
  2. Password rules are in shared constantsPASSWORD_RULES.PATTERN used in both DTO and service layer.
  3. All endpoints require JWT auth except /auth/login, /auth/bootstrap, /health/*.
  4. DTOs enforce validationwhitelist: true, forbidNonWhitelisted: true globally.
  5. Baton operations use pessimistic lockslock: { mode: 'pessimistic_write' } with CAS versioning.
  6. Metric names use underscoreshitl_latency_ms, not hitl.latency_ms (Prometheus convention).
  7. Bot auth uses service tokens/auth/service-token with client_id/secret. No admin credential fallback.
  8. Secrets never have defaults in productionvalues-production.yaml has empty strings for all secrets.
  9. Tests must fail if the fix is reverted — S-tier requirement from red team grading rubric.
  10. CDP streaming whitelists are security-critical — Only 6 CDP commands and 2 events are allowed through the relay. Adding commands requires security review. Target.* domain is always rejected.
  11. Streaming mode is per-applicationbrowser_policy.streaming_mode controls VNC vs CDP. Never assume one mode globally.
  12. Agent auth uses OAuth 2.0 Client Credentials/auth/agent-token with client_id/client_secret (HMAC-SHA256). Separate from human JWT flow.

Database Schema (15 Tables)

TablePurpose
tenantsMulti-tenant organizations
usersUser accounts (with failed_login_count, locked_until)
user_identitiesOAuth/identity linking (Slack, Teams)
applicationsApp configurations (login DSL, keepalive, export policy, browser_policy)
sessionsBrowser sessions (7-state machine)
session_batonsHITL baton state (4-state machine, CAS version)
artifact_bundlesEncrypted auth artifacts (AES-256-GCM)
artifact_consumptionsArtifact usage tracking
interventionsHITL intervention records (type, outcome, timing)
audit_eventsImmutable audit log (SHA-256 hash chain)
audit_anchorsDaily integrity anchors
agent_clientsOAuth 2.0 client credentials for agent authentication (HMAC-SHA256)
auth_requestsRequest coalescing for concurrent credential requests (ADR-002)
login_queueGlobal login serialization to prevent startup storms (ADR-015)
service_profilesVersioned credential configs with STAGING→CANARY→ACTIVE lifecycle (ADR-014)

Note: pg_advisory_lock(42) is used for audit hash chain serialization. It is a PostgreSQL advisory lock, not a table.

Session State Machine

STARTING ──→ HEALTHY ──→ UNHEALTHY ──→ LOGIN_NEEDED ──→ LOGIN_IN_PROGRESS
    │            │            │               │                  │
    │            ↓            ↓               ↓                  ↓
    ├──→ FAILED ←────────────┘          TERMINATED          HEALTHY
    │      │                                                   │
    │      ↓                                                   ↓
    └──→ TERMINATED (terminal)                              FAILED

Retry matrix: STARTING (3), UNHEALTHY_TRANSIENT (3), UNHEALTHY_AUTH (1), LOGIN_IN_PROGRESS (3), FAILED (0 — requires operator acknowledgement).

HITL Baton State Machine

AUTOMATION_CONTROL ──→ HUMAN_REQUESTED ──→ HUMAN_CONTROL ──→ HUMAN_RELEASED
       ↑                      │                                     │
       └──────────────────────┘ (timeout: 10min)                    │
       ↑                                                            │
       └────────────────────────────────────────────────────────────┘

Timeouts: HUMAN_REQUESTED=10min, HUMAN_CONTROL_INACTIVITY=5min.

API Modules (20)

ModuleController RoutesKey Services
Auth/auth/login, /auth/logout, /auth/service-tokenAuthService, TokenBlacklistService
Bootstrap(startup)BootstrapService
Users/users CRUDUsersService
Tenants/tenants CRUDTenantsService
Apps/apps CRUDAppsService
Sessions/sessions/scale, /sessionsSessionsService
HITL/sessions/:id/{stream,takeover,release,otp,acknowledge}HitlService
Streaming/stream WebSocketVncWsProxyService, CdpWsProxyService, StreamTokenService
Artifacts/artifactsArtifactsService
Agent/agent/run-urlAgentService
Credentials/credentialsCredentialsService
Profiles/profilesProfilesService
Login(internal)LoginQueueService, LoginSerializationService
Audit(internal)AuditService
EventsWebSocket /eventsEventsGateway
Nats(internal)NatsService
Redis(internal)RedisService (3-tier resilience)
Lifecycle(scheduled)LifecycleRetentionService
Observability/metricsObservabilityService (prom-client)
Health/health/live, /health/readyHealthController

Ports

ServicePortProtocol
API8080HTTP + WS (/events)
Controller8090HTTP (health)
Worker8091HTTP (health)
CDP Relay9223WebSocket (CDP mode streaming)
noVNC6080HTTP + WS (VNC mode)
VNC5900VNC (localhost only, VNC mode)
PostgreSQL5432TCP
Redis6379TCP
NATS4222TCP
NATS Monitor8222HTTP
MinIO9000/9001HTTP

Test Coverage

640 tests across 34 suites in 4 packages (shared: 78, api: 460, worker: 52, controller: 50). Includes adversarial security tests that catch regressions if remediations are reverted. E2E smoke suite (Python orchestrator, 25 checks) covers full credential delivery chain and CDP mode verification.

Run: pnpm nx run-many --target=test --all --parallel=3

What Requires Human Action

  • Kubernetes cluster provisioning and DNS configuration
  • Slack/Teams app creation and token generation
  • cert-manager installation for TLS
  • kube-prometheus-stack for alerting
  • External Secrets Operator for production secret management
  • Security sign-off and penetration testing
  • E2E UAT execution with real browser sessions

What's inside

15 tables, 2 state machines, 20 API modules, 12 port mappings, 640 tests across 34 suites

Change this for your project

  • Replace adoptai/tabby with your own repository name
  • Replace specification_docs/MVP_BROWSER_SPEC_CODEX.md with your canonical spec path
  • Replace charts/browser-hitl/ with your Helm chart directory

Where it goes

Save as AGENTS.md in your repository root. Read by Codex, Cursor and other agents that follow the AGENTS.md convention.

Worth borrowing

  • Per-application streaming mode via browser_policy.streaming_mode
  • Baton state machine with CAS versioning for HITL handoffs
  • Audit hash chain using PostgreSQL advisory locks

Related Documents