Skip to content
Explanation Concepts

Concepts

How Klyroo.Hotkey separates server-side credentials from user sessions, models browser and handoff lifecycles, handles idempotency and retries, authenticates incoming webhooks with zero-allocation HMAC-SHA256 verification, and achieves NativeAOT compatibility.

On this page

Server-side architecture and security boundary

Hotkey hosts persistent cloud browsers behind an HTTPS API (https://console.hotkey.so/v1/). Unlike the Blazor/MAUI UI libraries in Klyroo, Klyroo.Hotkey is strictly a server-side library because every operation requires secret credentials (a bearer API key or a webhook signing secret):

  Blazor / MAUI client (authenticated user)
            |
            |  1. Authenticated call to your app API (no Hotkey key on client)
            v
  Your .NET backend  ----[2. HotkeyClient + Bearer key]---->  Hotkey HTTP API
            |                                                      |
            |  3. Return expiring ask.Link / embed.Url             |
            v     to authorized user only                          |
  User completes step in Hotkey hosted view                        |
            |                                                      |
            |<---------[4. POST raw body + Hotkey-Signature]-------+
            |
            +-- 5. HotkeyWebhook.VerifyAndRead (HMAC-SHA256, ±300s)
            +-- 6. Deduplicate on delivery.Id, verify browser ownership, resume workflow

Three invariants protect this boundary:

  1. Ownership lives in your database. Your backend authenticates the user and maps their stable user ID (ExternalId) to HotkeyBrowser.Id. Never trust a browser ID sent by a client without checking your ownership table.
  2. Credentials never cross to the client. Workspace API keys, browser-scoped keys and webhook secrets stay in server configuration (IConfiguration, environment variables, secret stores).
  3. Clients only receive scoped, expiring URLs. CreateAskAsync returns a one-time expiring handoff link (ask.Link); CreateEmbedAsync returns a short-lived origin-restricted embed URL (embed.Url).

Workspace keys vs browser-scoped keys

Key type Created by Capabilities Where it belongs
Workspace key Hotkey console Provision/delete browsers, configure workspace embed origins, manage webhook endpoints, read workspace usage Provisioning service and admin backend only
Browser-scoped agent key CreateBrowserAgentKeyAsync Operates on a single browser only; revocable independently via RevokeAgentKeyAsync Per-user background workers or isolated automation jobs
Webhook signing secret CreateWebhookEndpointAsync / console Authenticates incoming POST deliveries via Hotkey-Signature Webhook receiver endpoint only

Keeping the workspace key out of worker processes limits blast radius if a single job or worker is compromised.

Idempotency and retry state machine

HotkeyClient serializes each JSON request body to UTF-8 bytes once before entering the retry loop, because Hotkey compares exact payload bytes when an Idempotency-Key is replayed.

Operation class Automatic retries Retry triggers Max delay waited
Safe reads (GET) Up to 2 retries ConnectionError, ResponseEnded, HTTP 429, 500, 502, 503, 504 30 seconds
Idempotent mutations (POST/PATCH with idempotencyKey, or auto-generated per-call GUID) Up to 2 retries Same as above + Hotkey error code idempotency_key_in_use 30 seconds
CreateEmbedAsync 0 retries (sent once) None — each call mints a fresh embed token —
DELETE calls (DeleteBrowserAsync, RevokeEmbedAsync, RevokeAgentKeyAsync, etc.) 0 retries (sent once) None —
  • Backoff calculation: HotkeyClient respects the HTTP Retry-After header (delta or date) first, then the JSON error's retry_after field, falling back to linear backoff (1s, 2s; 250ms, 500ms for connection drops).
  • 30-second ceiling: If Hotkey asks to wait longer than 30 seconds, HotkeyClient throws HotkeyException immediately with RetryAfter populated so your web request thread is never stalled and a durable queue can reschedule the job.
  • Conflict recovery (GetOrCreateBrowserAsync): Catches 409 Conflict when Code == "browser_exists" and ExistingBrowserId is present, fetches that browser, and confirms existing.ExternalId == settings.ExternalId before returning it.

Signed webhook verification

HotkeyWebhook.VerifyAndRead authenticates the raw HTTP body before deserializing JSON:

  1. Header validation: Parses Hotkey-Signature strictly as t=<unix_seconds>,v1=<64_hex_chars> (rejecting extra suffixes, malformed hex, or overlong timestamps).
  2. Replay window: Rejects timestamps outside ±300 seconds (5 minutes) around now ?? DateTimeOffset.UtcNow.
  3. Constant-time HMAC-SHA256: Hashes "<timestamp>." + rawBody using stack-allocated buffers for the timestamp prefix and standard-length secrets, zeroes secret bytes in a finally block (CryptographicOperations.ZeroMemory), and compares against v1 with CryptographicOperations.FixedTimeEquals.
  4. Source-generated deserialization: Deserializes HotkeyEvent with HotkeyJsonContext.Default.HotkeyEvent only after authentication succeeds, and rejects events missing a non-empty Id or Type.

Because verification hashes the exact transmitted bytes, parsing and re-serializing JSON before calling VerifyAndRead will break the signature.

Transport hardening and credential hygiene

  • Header injection protection: Both apiKey and caller-supplied idempotencyKey are validated to reject whitespace and ASCII control characters (\r, \n, < 0x21, 0x7f).
  • Resource ID validation: Every resource identifier (browserId, askId, embedId, downloadId, keyId, endpointId, signInId) is validated to contain only ASCII letters, digits, _ and - before building request paths, eliminating path traversal or query smuggling.
  • Bounded error responses: Error bodies are read with a 64 KiB cap (MaxErrorBodyBytes) so a misbehaving proxy returning a large HTML page cannot exhaust backend memory.
  • No redirects or cookies: AddKlyrooHotkey configures SocketsHttpHandler with AllowAutoRedirect = false (preventing bearer token leakage to a redirect target), UseCookies = false, PooledConnectionLifetime = 2 minutes (safe DNS rotation), ConnectTimeout = 10 seconds and MaxResponseHeadersLength = 32 KiB.
  • Secret-safe models: Types carrying expiring links, embed tokens or secrets (HotkeyAsk, HotkeyEmbed, HotkeyAgentKey, HotkeyWebhookEndpoint) are sealed class types rather than record types, so compiler-generated ToString() never prints sensitive fields into structured logs.

Source-generated JSON and NativeAOT

All request and response types are serialized through a compile-time System.Text.Json JsonSerializerContext (HotkeyJsonContext) with snake_case naming and null omission. Klyroo.Hotkey uses zero runtime reflection and builds cleanly under IsTrimmable = true and IsAotCompatible = true.

Design decisions and trade-offs

  • Server-side only, outside Klyroo.Stack. Keeping Klyroo.Hotkey as an independently versioned server-side package avoids pulling API-credential workflows into browser or mobile clients and adds zero overhead to apps that do not need cloud browsers. The cost is one extra package reference and registration call when you adopt it.
  • Sealed classes for secret-bearing payloads. Avoiding record on HotkeyAsk, HotkeyEmbed, HotkeyAgentKey and HotkeyWebhookEndpoint prevents accidental secret disclosure in logs. The trade-off is no compiler-synthesized value equality on those four types.
  • Bounded retries with a 30-second ceiling. Retrying up to twice for short delays absorbs brief transient faults without tying up ASP.NET Core request threads on long rate limits.
  • No automatic retry on CreateEmbedAsync. Minting an embed creates a new token per request, so blind retries could issue untracked live-view tokens.
  • Raw-byte HMAC verification before JSON parsing. Hashing the exact HTTP body bytes avoids JSON canonicalization mismatches and blocks unauthenticated payloads before deserialization. The trade-off is buffering the request body stream in your webhook endpoint.