Class: AtprotoAuth::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/atproto_auth/client.rb

Overview

Main client class for AT Protocol OAuth implementation. Handles the complete OAuth flow including authorization, token management, and identity verification.

Defined Under Namespace

Classes: CallbackError, SessionError, TokenError

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(client_id:, redirect_uri:, metadata: nil, dpop_key: nil) ⇒ Client

Creates a new AT Protocol OAuth client

Parameters:

  • client_id (String)

    OAuth client ID URL

  • redirect_uri (String)

    OAuth redirect URI

  • metadata (Hash, nil) (defaults to: nil)

    Optional pre-loaded client metadata

  • dpop_key (Hash, nil) (defaults to: nil)

    Optional existing DPoP key in JWK format

Raises:

  • (Error)

    if configuration is invalid



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/atproto_auth/client.rb', line 42

def initialize(client_id:, redirect_uri:, metadata: nil, dpop_key: nil)
  @client_id = client_id
  @redirect_uri = redirect_uri

  # Initialize core dependencies
  @client_metadata = ()
  validate_redirect_uri!

  @session_manager = State::SessionManager.new
  @identity_resolver = Identity::Resolver.new
  @dpop_client = initialize_dpop(dpop_key)
end

Instance Attribute Details

#client_idString (readonly)

Returns OAuth client ID.

Returns:

  • (String)

    OAuth client ID



24
25
26
# File 'lib/atproto_auth/client.rb', line 24

def client_id
  @client_id
end

#client_metadataClientMetadata (readonly)

Returns Validated client metadata.

Returns:



28
29
30
# File 'lib/atproto_auth/client.rb', line 28

def 
  @client_metadata
end

#dpop_clientDPoP::Client (readonly)

Returns DPoP client.

Returns:



34
35
36
# File 'lib/atproto_auth/client.rb', line 34

def dpop_client
  @dpop_client
end

#identity_resolverIdentity::Resolver (readonly)

Returns Identity resolver.

Returns:



32
33
34
# File 'lib/atproto_auth/client.rb', line 32

def identity_resolver
  @identity_resolver
end

#redirect_uriString (readonly)

Returns OAuth redirect URI.

Returns:

  • (String)

    OAuth redirect URI



26
27
28
# File 'lib/atproto_auth/client.rb', line 26

def redirect_uri
  @redirect_uri
end

#session_managerSessionManager (readonly)

Returns Session state manager.

Returns:

  • (SessionManager)

    Session state manager



30
31
32
# File 'lib/atproto_auth/client.rb', line 30

def session_manager
  @session_manager
end

Instance Method Details

#auth_headers(session_id:, method:, url:) ⇒ Hash

Generates headers for an authenticated request

Parameters:

  • session_id (String)

    ID of session to use

  • method (String)

    HTTP method for the request

  • url (String)

    Full URL for the request

Returns:

  • (Hash)

    Headers to add to request

Raises:

  • (TokenError)

    if session is invalid or unauthorized



208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
# File 'lib/atproto_auth/client.rb', line 208

def auth_headers(session_id:, method:, url:)
  session = session_manager.get_session(session_id)
  raise TokenError, "Invalid session" unless session
  raise TokenError, "Session not authorized" unless session.authorized?

  # Generate DPoP proof
  proof = dpop_client.generate_proof(
    http_method: method,
    http_uri: url,
    access_token: session.tokens.access_token
  )

  {
    "Authorization" => "DPoP #{session.tokens.access_token}",
    "DPoP" => proof
  }
end

#authorize(handle: nil, pds_url: nil, scope: "atproto") ⇒ Hash

Begins an authorization flow and generates authorization URL

Parameters:

  • handle (String, nil) (defaults to: nil)

    Optional user handle

  • pds_url (String, nil) (defaults to: nil)

    Optional PDS URL

  • scope (String) (defaults to: "atproto")

    OAuth scope (must include “atproto”)

Returns:

  • (Hash)

    Authorization details including :url and :session_id

Raises:

  • (Error)

    if parameters are invalid or resolution fails



61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
# File 'lib/atproto_auth/client.rb', line 61

def authorize(handle: nil, pds_url: nil, scope: "atproto")
  validate_auth_params!(handle, pds_url, scope)

  # Create new session
  session = session_manager.create_session(
    client_id: client_id,
    scope: scope
  )

  # Store session with storage backend
  session_manager.update_session(session)

  # Resolve identity and authorization server if handle provided
  if handle
    auth_info = resolve_from_handle(handle, session)
  elsif pds_url
    auth_info = resolve_from_pds(pds_url, session)
  else
    raise Error, "Either handle or pds_url must be provided"
  end

  # Generate authorization URL
  auth_url = generate_authorization_url(
    auth_info[:server],
    session,
    login_hint: handle
  )

  {
    url: auth_url,
    session_id: session.session_id
  }
end

#authorized?(session_id) ⇒ Boolean

Checks if a session has valid tokens

Parameters:

  • session_id (String)

    ID of session to check

Returns:

  • (Boolean)

    true if session exists and has valid tokens



197
198
199
200
# File 'lib/atproto_auth/client.rb', line 197

def authorized?(session_id)
  session = session_manager.get_session(session_id)
  session&.authorized? || false
end

#cleanup_expired_sessionsvoid

This method returns an undefined value.

Cleans up expired sessions from storage



237
238
239
# File 'lib/atproto_auth/client.rb', line 237

def cleanup_expired_sessions
  session_manager.cleanup_expired
end

#get_tokens(session_id) ⇒ Hash?

Gets active tokens for a session

Parameters:

  • session_id (String)

    ID of session to get tokens for

Returns:

  • (Hash, nil)

    Current token information if session exists and is authorized



149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/atproto_auth/client.rb', line 149

def get_tokens(session_id)
  session = session_manager.get_session(session_id)
  return nil unless session&.authorized?

  {
    access_token: session.tokens.access_token,
    token_type: session.tokens.token_type,
    expires_in: (session.tokens.expires_at - Time.now).to_i,
    refresh_token: session.tokens.refresh_token,
    scope: session.tokens.scope
  }
end

#handle_callback(code:, state:, iss:) ⇒ Hash

Handles the authorization callback and completes token exchange

Parameters:

  • code (String)

    Authorization code from callback

  • state (String)

    State parameter from callback

  • iss (String)

    Issuer from callback (required by AT Protocol OAuth)

Returns:

  • (Hash)

    Token response including :access_token and :session_id

Raises:



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/atproto_auth/client.rb', line 102

def handle_callback(code:, state:, iss:)
  # Find and validate session
  session = session_manager.get_session_by_state(state)
  raise CallbackError, "Invalid state parameter" unless session

  # Verify issuer matches session
  raise CallbackError, "Issuer mismatch" unless session.auth_server && session.auth_server.issuer == iss

  AtprotoAuth.storage.with_lock(Storage::KeyBuilder.lock_key("session", session.session_id), ttl: 30) do
    # Exchange code for tokens
    token_response = exchange_code(
      code: code,
      session: session
    )

    # Validate token response
    validate_token_response!(token_response, session)

    # Create token set and store in session
    token_set = State::TokenSet.new(
      access_token: token_response["access_token"],
      token_type: token_response["token_type"],
      expires_in: token_response["expires_in"],
      refresh_token: token_response["refresh_token"],
      scope: token_response["scope"],
      sub: token_response["sub"]
    )
    session.tokens = token_set

    # Update stored session
    session_manager.update_session(session)

    {
      access_token: token_set.access_token,
      token_type: token_set.token_type,
      expires_in: (token_set.expires_at - Time.now).to_i,
      refresh_token: token_set.refresh_token,
      scope: token_set.scope,
      session_id: session.session_id,
      did: session.did
    }
  end
end

#refresh_token(session_id) ⇒ Object

Refreshes tokens for a session

Parameters:

  • session_id (String)

    ID of session to refresh

Raises:



164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/atproto_auth/client.rb', line 164

def refresh_token(session_id)
  session = session_manager.get_session(session_id)
  raise TokenError, "Invalid session" unless session
  raise TokenError, "Session not authorized" unless session.renewable?

  AtprotoAuth.storage.with_lock(Storage::KeyBuilder.lock_key("session", session.session_id), ttl: 30) do
    refresher = Token::Refresh.new(
      session: session,
      dpop_client: @dpop_client,
      auth_server: session.auth_server,
      client_metadata: 
    )

    new_tokens = refresher.perform!
    session.tokens = new_tokens

    # Update stored session
    session_manager.update_session(session)

    {
      access_token: new_tokens.access_token,
      token_type: new_tokens.token_type,
      expires_in: (new_tokens.expires_at - Time.now).to_i,
      refresh_token: new_tokens.refresh_token,
      scope: new_tokens.scope,
      session_id: session.session_id
    }
  end
end

#remove_session(session_id) ⇒ void

This method returns an undefined value.

Removes a session and its stored data

Parameters:

  • session_id (String)

    ID of session to remove



229
230
231
232
233
# File 'lib/atproto_auth/client.rb', line 229

def remove_session(session_id)
  key = Storage::KeyBuilder.session_key(session_id)
  AtprotoAuth.storage.delete(key)
  session_manager.remove_session(session_id)
end