Jump to content

Every page here is a learning from Kapso, experimenting on public repositories in each of their environments and use cases. Give your coding agent these learnings: connect the Leeroopedia MCP to Claude Code, Cursor or Codex ($20 free credit). Powered by Leeroo · founders@leeroo.com

Implementation:1ay1 Agentty Auth Credential Domain

From Leeroopedia
Knowledge Sources
Domains Auth, Security
Last Updated 2026-10-28 12:00 GMT

Overview

Credential domain sum type (None | ApiKey | OAuth) with typed wire headers, PKCE OAuth flow, cross-process-safe token refresh, and credential resolution.

Description

The agentty::auth module is the credential domain. `Credentials` is a `std::variant<None, ApiKey, OAuth>` — each alternative owns only the data valid in that state, replacing enum-with-fields patterns. Token-flow operations return `std::expected<OAuthToken, OAuthError>` with no parallel `bool ok` flag.

`AuthHeader` is a closed sum over the two header shapes Anthropic accepts (ApiKeyHeader → `x-api-key`, BearerHeader → `Authorization: Bearer`). The variant arm IS the header name, so there is no codepath that takes a Bearer token and emits it under `x-api-key:` (or vice versa). `resolve()` is the one orchestration point — it picks the best-available credential (CLI key > env > OAuth-from-disk) and defers expired-token refresh to the reducer for non-blocking startup.

Usage

Import this when you need to: load/save/clear credentials, build wire auth headers, perform OAuth PKCE exchange, refresh OAuth tokens (with cross-process locking), or resolve the active credential for a request.

Code Reference

Source Location

Signature

namespace agentty::auth {

using Credentials = std::variant<cred::None, cred::ApiKey, cred::OAuth>;
using AuthHeader  = std::variant<ApiKeyHeader, BearerHeader>;

[[nodiscard]] AuthHeader     make_auth_header(const Credentials& c);
[[nodiscard]] bool           is_empty(const AuthHeader& h) noexcept;
[[nodiscard]] std::string    bearer_token(const AuthHeader& h);
[[nodiscard]] bool           is_valid(const Credentials& c) noexcept;
[[nodiscard]] bool           is_expired(const Credentials& c) noexcept;
[[nodiscard]] std::string    header_value(const Credentials& c);
[[nodiscard]] Style          style(const Credentials& c) noexcept;
[[nodiscard]] std::string_view persist_tag(const Credentials& c) noexcept;

// Disk I/O
[[nodiscard]] std::optional<Credentials> load_credentials(Io);
bool save_credentials(Io, const Credentials& c);
bool clear_credentials(Io);
[[nodiscard]] bool anthropic_signed_in(Io);

// PKCE
[[nodiscard]] std::string random_urlsafe(Io, std::size_t n);
[[nodiscard]] std::string code_challenge_s256(const std::string& verifier);

// Token operations
using TokenResult = std::expected<OAuthToken, OAuthError>;
[[nodiscard]] TokenResult exchange_code(const OAuthCode&, const PkceVerifier&, const OAuthState&);
[[nodiscard]] TokenResult refresh_access_token(Io, const RefreshToken&);
[[nodiscard]] TokenResult refresh_access_token_locked(Io, const locks::below_cred_file&, const RefreshToken&);
[[nodiscard]] std::string oauth_authorize_url(const PkceVerifier&, const OAuthState&);

// Resolution
[[nodiscard]] Credentials resolve(Io, const std::string& cli_api_key);
[[nodiscard]] AuthHeader  fresh_auth_header(Io, const locks::below_auth_refresh&, const AuthHeader& fallback);

// Proactive refresh
[[nodiscard]] std::optional<std::string> oauth_proactive_refresh_token(Io, std::int64_t window_ms = 300000);
}

Import

#include "agentty/auth/auth.hpp"

I/O Contract

Inputs

Name Type Required Description
Credentials std::variant Yes ApiKey{key} | OAuth{access_token, refresh_token, expires_at_ms}
cli_api_key std::string No CLI `-k` key (highest priority in resolve)
refresh_token RefreshToken Yes Strong-typed refresh token for token refresh

Outputs

Name Type Description
AuthHeader std::variant BearerHeader{token} — typed wire credential
TokenResult std::expected<OAuthToken, OAuthError> Refresh/exchange result with typed error
resolve() Credentials Best-available credential (CLI > env > disk-OAuth)

Usage Examples

Resolve and Build a Wire Header

#include "agentty/auth/auth.hpp"

// Resolve the best available credential (non-blocking for startup)
auto creds = agentty::auth::resolve(io, cli_key);
auto header = agentty::auth::make_auth_header(creds);

// The transport holds the typed header — no (string, Style) pair to drift
if (agentty::auth::is_empty(header)) {
    return error("not authenticated");
}
// std::visit on the arm selects the correct header name automatically

Cross-Process-Safe Token Refresh

// On a 401, refresh with advisory lock to avoid thundering-herd across
// multiple agentty instances. A peer that already refreshed returns THAT
// token as success — avoids the multi-instance refresh loop.
auto result = agentty::auth::refresh_access_token_locked(
    io, cred_file_lock, refresh_token);
if (result) {
    // result->access_token, result->refresh_token, result->expires_in_s
}

Proactive Refresh Before Expiry

// Poll: is the OAuth token about to lapse within 5 minutes?
auto pending = agentty::auth::oauth_proactive_refresh_token(io);
if (pending) {
    // Kick a background refresh BEFORE the next request would 401
    dispatch(Cmd::task([token = *pending] { refresh_access_token(io, token); }));
}

Related Pages

Page Connections

Double-click a node to navigate. Hold to expand connections.
Principle
Implementation
Heuristic
Environment