Module: BetterAuth::Plugins::OAuthProtocol

Defined in:
lib/better_auth/plugins/oauth_protocol.rb

Constant Summary collapse

AUTH_CODE_GRANT =
"authorization_code"
REFRESH_GRANT =
"refresh_token"
CLIENT_CREDENTIALS_GRANT =
"client_credentials"
DEVICE_CODE_GRANT =
"urn:ietf:params:oauth:grant-type:device_code"

Class Method Summary collapse

Class Method Details

.apply_prefix(value, prefix, kind) ⇒ Object



789
790
791
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 789

def apply_prefix(value, prefix, kind)
  "#{token_prefix(prefix, kind)}#{value}"
end

.authenticate_client!(ctx, model, store_client_secret: "plain", prefix: {}, require_confidential: false) ⇒ Object



370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 370

def authenticate_client!(ctx, model, store_client_secret: "plain", prefix: {}, require_confidential: false)
  body = request_body!(ctx.body || {})
  client_id = body["client_id"]
  client_secret = strip_prefix(body["client_secret"], prefix, :client_secret) || body["client_secret"]

  authorization = ctx.headers["authorization"]
  auth_method_used = client_secret.to_s.empty? ? nil : "client_secret_post"
  if authorization.to_s.start_with?("Basic ")
    decoded = Base64.strict_decode64(authorization.delete_prefix("Basic "))
    unless decoded.include?(":")
      raise APIError.new("BAD_REQUEST", message: "invalid authorization header format", body: {error: "invalid_client", error_description: "invalid authorization header format"})
    end
    client_id, client_secret = decoded.split(":", 2)
    if client_id.to_s.empty? || client_secret.to_s.empty?
      raise APIError.new("BAD_REQUEST", message: "invalid authorization header format", body: {error: "invalid_client", error_description: "invalid authorization header format"})
    end
    auth_method_used = "client_secret_basic"
  end

  client = find_client(ctx, model, client_id)
  raise APIError.new("UNAUTHORIZED", message: "invalid_client") unless client

  client_data = stringify_keys(client)
  raise APIError.new("UNAUTHORIZED", message: "invalid_client") if client_data["disabled"]

  method = client_data["tokenEndpointAuthMethod"] || "client_secret_basic"
  if method == "none"
    raise APIError.new("UNAUTHORIZED", message: "invalid_client") if require_confidential
    raise APIError.new("UNAUTHORIZED", message: "invalid_client") unless client_secret.to_s.empty?
    return client
  end
  expected_method = (method == "client_secret_post") ? "client_secret_post" : "client_secret_basic"
  raise APIError.new("UNAUTHORIZED", message: "invalid_client") unless auth_method_used == expected_method
  if client_secret_expired?(client_data["clientSecretExpiresAt"])
    raise APIError.new("UNAUTHORIZED", message: "invalid_client")
  end
  if method != "none" && !verify_client_secret(ctx, stringify_keys(client)["clientSecret"], client_secret, store_client_secret)
    raise APIError.new("UNAUTHORIZED", message: "invalid_client")
  end

  client.merge("__providedClientSecret" => client_secret)
rescue ArgumentError
  raise APIError.new("BAD_REQUEST", message: "invalid authorization header format", body: {error: "invalid_client", error_description: "invalid authorization header format"})
end

.build_jwt_access_token(ctx, client, user, session, scope, audience, issuer_value, expires_at, custom_claims, reference_id: nil, use_jwt_plugin: false) ⇒ Object



642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 642

def build_jwt_access_token(ctx, client, user, session, scope, audience, issuer_value, expires_at, custom_claims, reference_id: nil, use_jwt_plugin: false)
  scopes = parse_scopes(scope)
  extra = if custom_claims.respond_to?(:call)
    custom_claims.call({user: user.empty? ? nil : user, scopes: scopes, resource: audience, reference_id: reference_id, metadata: stringify_keys(client["metadata"] || {})})
  end
  payload = (extra.is_a?(Hash) ? stringify_keys(extra) : {}).merge(
    "sub" => user["id"] || client["clientId"],
    "aud" => audience,
    "azp" => client["clientId"],
    "scope" => scope,
    "sid" => session["id"],
    "name" => user["name"],
    "email" => user["email"],
    "email_verified" => user["emailVerified"],
    "iss" => issuer_value,
    "iat" => Time.now.to_i,
    "exp" => expires_at.to_i
  ).compact
  if use_jwt_plugin
    return sign_oauth_jwt!(ctx, payload, issuer: issuer_value, audience: audience)
  end

  ::JWT.encode(payload, ctx.context.secret, "HS256")
end

.client_logout_redirect_uris(client) ⇒ Object



103
104
105
106
107
108
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 103

def client_logout_redirect_uris(client)
  value = client["postLogoutRedirectUris"] || client[:post_logout_redirect_uris]
  return value if value.is_a?(Array)

  value.to_s.split(",").map(&:strip).reject(&:empty?)
end

.client_metadata(body, strip_unknown: false) ⇒ Object



309
310
311
312
313
314
315
316
317
318
319
320
321
322
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 309

def (body, strip_unknown: false)
   = body["metadata"]
  unless .nil? || .is_a?(Hash)
    raise APIError.new("BAD_REQUEST", message: "metadata must be an object")
  end
   = stringify_keys( || {})
   = .slice("software_id", "software_version", "software_statement", "tos_uri", "policy_uri") if strip_unknown
  ["software_id"] = body["software_id"] if body["software_id"]
  ["software_version"] = body["software_version"] if body["software_version"]
  ["software_statement"] = body["software_statement"] if body["software_statement"]
  ["tos_uri"] = body["tos_uri"] if body["tos_uri"]
  ["policy_uri"] = body["policy_uri"] if body["policy_uri"]
  
end

.client_redirect_uris(client) ⇒ Object



96
97
98
99
100
101
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 96

def client_redirect_uris(client)
  value = client["redirectUris"] || client["redirectUrls"] || client[:redirect_uris] || client[:redirectUrls]
  return value if value.is_a?(Array)

  value.to_s.split(",").map(&:strip).reject(&:empty?)
end

.client_require_pkce(data) ⇒ Object



324
325
326
327
328
329
330
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 324

def client_require_pkce(data)
  data = stringify_keys(data || {})
  return data["requirePKCE"] if data.key?("requirePKCE")
  return data["requirePkce"] if data.key?("requirePkce")

  nil
end

.client_response(client, include_secret: true) ⇒ Object



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 205

def client_response(client, include_secret: true)
  data = stringify_keys(client || {})
   = stringify_keys(data["metadata"] || {})
  response = {
    client_id: data["clientId"],
    client_name: data["name"],
    client_uri: data["uri"],
    logo_uri: data["icon"],
    redirect_uris: client_redirect_uris(data),
    post_logout_redirect_uris: client_logout_redirect_uris(data),
    token_endpoint_auth_method: data["tokenEndpointAuthMethod"] || "client_secret_basic",
    grant_types: data["grantTypes"] || [],
    response_types: data["responseTypes"] || [],
    scope: scope_string(data["scopes"]),
    public: !!data["public"],
    type: data["type"],
    user_id: data["userId"],
    reference_id: data["referenceId"],
    require_pkce: client_require_pkce(data),
    subject_type: data["subjectType"],
    metadata: ,
    contacts: data["contacts"] || [],
    tos_uri: data["tos"],
    policy_uri: data["policy"],
    software_id: data["softwareId"],
    software_version: data["softwareVersion"],
    software_statement: data["softwareStatement"],
    client_secret_expires_at: data["clientSecretExpiresAt"]
  }
  response[:skip_consent] = true if data["skipConsent"]
  .each { |key, value| response[key.to_sym] = value }
  response[:client_secret] = data["clientSecret"] if include_secret && data["clientSecret"]
  response.compact
end

.client_secret_expired?(value) ⇒ Boolean

Returns:

  • (Boolean)


415
416
417
418
419
420
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 415

def client_secret_expired?(value)
  return false if value.nil? || value.to_i == 0

  seconds = timestamp_seconds(value)
  seconds && seconds <= Time.now.to_i
end

.consume_code!(internal_adapter, code, client_id:, redirect_uri:, code_verifier: nil, store_tokens: "hashed") ⇒ Object



440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 440

def consume_code!(internal_adapter, code, client_id:, redirect_uri:, code_verifier: nil, store_tokens: "hashed")
  stored_code = get_stored_token(store_tokens, code.to_s, "authorization_code")
  verification = internal_adapter.consume_verification_value(stored_code)
  verification ||= internal_adapter.consume_verification_value(code.to_s) if stored_code != code.to_s
  data = verification && JSON.parse(verification.fetch("value"), symbolize_names: true)
  unless data.is_a?(Hash) && !data[:client_id].to_s.empty? && !data[:redirect_uri].to_s.empty? && data[:session].is_a?(Hash) && data[:scopes].is_a?(Array)
    raise APIError.new("BAD_REQUEST", message: "invalid_grant")
  end
  raise APIError.new("BAD_REQUEST", message: "invalid_grant") unless data[:client_id] == client_id.to_s
  raise APIError.new("BAD_REQUEST", message: "invalid_grant") unless data[:redirect_uri] == redirect_uri.to_s
  if data[:code_challenge]
    verify_pkce!(data, code_verifier)
  elsif !code_verifier.to_s.empty?
    raise APIError.new("BAD_REQUEST", message: "invalid_grant")
  end

  data
rescue JSON::ParserError, KeyError, TypeError
  raise APIError.new("BAD_REQUEST", message: "invalid_grant")
end

.create_client(ctx, model:, body:, owner_session: nil, default_auth_method: "client_secret_basic", store_client_secret: "plain", unauthenticated: false, default_scopes: nil, allowed_scopes: nil, prefix: {}, dynamic_registration: false, admin: false, pairwise_secret: nil, strip_client_metadata: false, reference_id: nil, generate_client_id: nil, generate_client_secret: nil, client_registration_client_secret_expiration: nil) ⇒ Object

Raises:



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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
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
193
194
195
196
197
198
199
200
201
202
203
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 110

def create_client(ctx, model:, body:, owner_session: nil, default_auth_method: "client_secret_basic", store_client_secret: "plain", unauthenticated: false, default_scopes: nil, allowed_scopes: nil, prefix: {}, dynamic_registration: false, admin: false, pairwise_secret: nil, strip_client_metadata: false, reference_id: nil, generate_client_id: nil, generate_client_secret: nil, client_registration_client_secret_expiration: nil)
  body = request_body!(body || {})
  requested_auth_method = body["token_endpoint_auth_method"] || default_auth_method
  (requested_auth_method, body)
  validate_admin_only_fields!(body, admin: admin)
  auth_method = unauthenticated ? "none" : requested_auth_method
  public_client = auth_method == "none"
  client_id = generate_client_id.respond_to?(:call) ? generate_client_id.call : Crypto.random_string(32)
  client_secret = if public_client
    nil
  else
    generate_client_secret.respond_to?(:call) ? generate_client_secret.call : Crypto.random_string(32)
  end
  redirects = Array(body["redirect_uris"]).map(&:to_s)
  raise APIError.new("BAD_REQUEST", message: "redirect_uris is required") if redirects.empty?
  redirects.each { |uri| validate_safe_url!(uri, field: "redirect_uris") }
  Array(body["post_logout_redirect_uris"]).map(&:to_s).each { |uri| validate_safe_url!(uri, field: "post_logout_redirect_uris") }

  grant_types = Array(body["grant_types"] || [AUTH_CODE_GRANT]).map(&:to_s)
  response_types = Array(body["response_types"] || ["code"]).map(&:to_s)
  validate_client_registration!(auth_method, grant_types, response_types, body, unauthenticated: unauthenticated, dynamic_registration: dynamic_registration)
  validate_redirect_scheme_for_client!(auth_method, body, redirects)
  validate_pairwise_client!(body, redirects, pairwise_secret)

  scopes = parse_scopes(body["scope"] || body["scopes"])
  scopes = parse_scopes(default_scopes) if scopes.empty? && default_scopes
  allowed = parse_scopes(allowed_scopes)
  unless allowed.empty? || scopes.all? { |scope| allowed.include?(scope) }
    raise APIError.new("BAD_REQUEST", message: "invalid_scope")
  end

   = (body, strip_unknown: )
  ["software_id"] = body["software_id"] if body["software_id"]
  ["software_version"] = body["software_version"] if body["software_version"]
  ["software_statement"] = body["software_statement"] if body["software_statement"]
  ["tos_uri"] = body["tos_uri"] if body["tos_uri"]
  ["policy_uri"] = body["policy_uri"] if body["policy_uri"]
  require_pkce = body.key?("require_pkce") ? body["require_pkce"] : body["requirePKCE"]
  require_pkce = true if dynamic_registration && require_pkce.nil?

  client_type = if unauthenticated && public_client && body["type"] == "web"
    nil
  else
    body["type"] || (public_client ? nil : "web")
  end
  issued_at = Time.now.to_i
  secret_expires_at = if client_secret && dynamic_registration && !client_registration_client_secret_expiration.nil?
    resolve_client_secret_expires_at(client_registration_client_secret_expiration, issued_at)
  elsif admin
    body["client_secret_expires_at"] || 0
  end
  data = {
    "clientId" => client_id,
    "clientSecret" => client_secret ? store_client_secret_value(ctx, client_secret, store_client_secret) : nil,
    "public" => public_client,
    "type" => client_type,
    "name" => body["client_name"] || body["name"] || "OAuth Client",
    "icon" => body["logo_uri"],
    "uri" => body["client_uri"],
    "contacts" => Array(body["contacts"]).map(&:to_s),
    "tos" => body["tos_uri"],
    "policy" => body["policy_uri"],
    "softwareId" => body["software_id"] || ["software_id"],
    "softwareVersion" => body["software_version"] || ["software_version"],
    "softwareStatement" => body["software_statement"] || ["software_statement"],
    "redirectUris" => redirects,
    "redirectUrls" => redirects.join(","),
    "postLogoutRedirectUris" => Array(body["post_logout_redirect_uris"]).map(&:to_s),
    "clientSecretExpiresAt" => secret_expires_at,
    "tokenEndpointAuthMethod" => auth_method,
    "grantTypes" => grant_types,
    "responseTypes" => response_types,
    "scopes" => scopes,
    "skipConsent" => unauthenticated ? false : !!(body["skip_consent"] || body["skipConsent"]),
    "enableEndSession" => !!(body["enable_end_session"] || body["enableEndSession"]),
    "requirePKCE" => require_pkce,
    "subjectType" => body["subject_type"] || body["subjectType"],
    "metadata" => ,
    "disabled" => false
  }
  data["referenceId"] = reference_id if reference_id
  data["userId"] = owner_session[:user]["id"] if owner_session && !reference_id
  created = ctx.context.adapter.create(model: model, data: data)
  response = client_response(created).merge(
    client_secret: client_secret ? apply_prefix(client_secret, prefix, :client_secret) : nil,
    client_id_issued_at: Time.now.to_i
  ).compact
  response[:require_pkce] = require_pkce unless require_pkce.nil?
  if client_secret
    expires = stringify_keys(created || {})["clientSecretExpiresAt"] || secret_expires_at
    response[:client_secret_expires_at] = timestamp_seconds(expires) || 0
  end
  response
end

.decode_refresh_token(token, prefix:, format_refresh_token: nil) ⇒ Object



802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 802

def decode_refresh_token(token, prefix:, format_refresh_token: nil)
  value = strip_prefix(token, prefix, :refresh_token)
  return nil if value.nil?

  if format_refresh_token.is_a?(Hash) && format_refresh_token[:decrypt].respond_to?(:call)
    decrypted = format_refresh_token[:decrypt].call(value)
    if decrypted.is_a?(Hash)
      decrypted[:token] || decrypted["token"]
    else
      decrypted.to_s
    end
  else
    value
  end
end

.encode_refresh_token(token_value, prefix:, format_refresh_token: nil, session_id: nil) ⇒ Object



793
794
795
796
797
798
799
800
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 793

def encode_refresh_token(token_value, prefix:, format_refresh_token: nil, session_id: nil)
  formatted = if format_refresh_token.is_a?(Hash) && format_refresh_token[:encrypt].respond_to?(:call)
    format_refresh_token[:encrypt].call(token_value, session_id)
  else
    token_value
  end
  apply_prefix(formatted, prefix, :refresh_token)
end

.endpoint_base(ctx) ⇒ Object



43
44
45
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 43

def endpoint_base(ctx)
  ctx.context.canonical_base_url
end

.find_client(ctx, model, client_id, cached_trusted_clients: nil) ⇒ Object



357
358
359
360
361
362
363
364
365
366
367
368
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 357

def find_client(ctx, model, client_id, cached_trusted_clients: nil)
  client_id = client_id.to_s
  if (cached = trusted_client_cache[client_id])
    return cached
  end

  client = ctx.context.adapter.find_one(model: model, where: [{field: "clientId", value: client_id}])
  if client && cached_trusted_clients&.include?(client_id)
    trusted_client_cache[client_id] = client
  end
  client
end

.find_token_by_hint(store, token, hint, prefix: {}, format_refresh_token: nil) ⇒ Object



738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 738

def find_token_by_hint(store, token, hint, prefix: {}, format_refresh_token: nil)
  access = -> { (value = strip_prefix(token, prefix, :access_token)) && store[:tokens][value] }
  refresh = lambda {
    value = decode_refresh_token(token, prefix: prefix, format_refresh_token: format_refresh_token)
    value && store[:refresh_tokens][value]
  }

  case hint.to_s
  when "access_token"
    access.call
  when "refresh_token"
    refresh.call
  else
    access.call || refresh.call
  end
end

.get_stored_token(storage_method, token, type) ⇒ Object



1039
1040
1041
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 1039

def get_stored_token(storage_method, token, type)
  store_token_value(storage_method, token, type)
end

.id_token(user, client_id, issuer_value, audience, ctx: nil, signer: nil, session_id: nil, include_sid: false, nonce: nil, auth_time: nil, custom_claims: nil, scopes: [], client: {}, filter_claims_by_scope: false, expires_in: 3600, use_jwt_plugin: false) ⇒ Object



875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 875

def id_token(user, client_id, issuer_value, audience, ctx: nil, signer: nil, session_id: nil, include_sid: false, nonce: nil, auth_time: nil, custom_claims: nil, scopes: [], client: {}, filter_claims_by_scope: false, expires_in: 3600, use_jwt_plugin: false)
  requested_scopes = parse_scopes(scopes)
  payload = {
    sub: user["id"],
    iss: issuer_value,
    aud: audience || client_id
  }
  include_profile_claims = !filter_claims_by_scope || requested_scopes.include?("profile")
  include_email_claims = !filter_claims_by_scope || requested_scopes.include?("email")
  payload[:name] = user["name"] if include_profile_claims
  if include_email_claims
    payload[:email] = user["email"]
    payload[:email_verified] = !!user["emailVerified"]
  end
  payload[:sid] = session_id if include_sid && session_id
  payload[:nonce] = nonce if nonce
  payload[:auth_time] = timestamp_seconds(auth_time) if auth_time
  if custom_claims.respond_to?(:call)
    extra = custom_claims.call({user: user, scopes: requested_scopes, client: client})
    if extra.is_a?(Hash)
      pinned = %w[sub iss aud exp iat nonce sid]
      payload.merge!(stringify_keys(extra).except(*pinned).transform_keys(&:to_sym))
    end
  end
  return signer.call(ctx, payload) if signer.respond_to?(:call)

  if use_jwt_plugin && ctx
    return sign_oauth_jwt!(ctx, payload, issuer: issuer_value, audience: audience)
  end

  Crypto.sign_jwt(
    payload,
    id_token_hs256_key(ctx, client_id, stringify_keys(client)["clientSecret"] || stringify_keys(client)["client_secret"]),
    expires_in: expires_in
  )
end

.id_token_hs256_key(ctx, client_id, client_secret = nil) ⇒ Object



912
913
914
915
916
917
918
919
920
921
922
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 912

def id_token_hs256_key(ctx, client_id, client_secret = nil)
  oauth_provider = ctx&.context&.options&.plugins&.find { |plugin| plugin.id == "oauth-provider" }
  if oauth_provider&.options&.fetch(:store_client_secret, nil).to_s == "hashed"
    label = client_id.to_s.empty? ? "better-auth" : client_id.to_s
    return OpenSSL::HMAC.hexdigest("SHA256", ctx.context.secret.to_s, "oidc.id_token.#{label}")
  end
  return client_secret.to_s unless client_secret.to_s.empty?

  label = client_id.to_s.empty? ? "better-auth" : client_id.to_s
  OpenSSL::HMAC.hexdigest("SHA256", ctx.context.secret.to_s, "oidc.id_token.#{label}")
end

.issue_tokens(ctx, store, model:, client:, session:, scopes:, include_refresh: false, issuer: nil, jwt_audience: nil, access_token_expires_in: 3600, refresh_token_expires_in: 2_592_000, id_token_expires_in: 3600, id_token_signer: nil, prefix: {}, audience: nil, grant_type: nil, custom_token_response_fields: nil, custom_access_token_claims: nil, custom_id_token_claims: nil, jwt_access_token: false, use_jwt_plugin: false, pairwise_secret: nil, nonce: nil, auth_time: nil, reference_id: nil, filter_id_token_claims_by_scope: false, store_tokens: "hashed", generate_opaque_access_token: nil, generate_refresh_token: nil, format_refresh_token: nil) ⇒ Object



491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 491

def issue_tokens(ctx, store, model:, client:, session:, scopes:, include_refresh: false, issuer: nil, jwt_audience: nil, access_token_expires_in: 3600, refresh_token_expires_in: 2_592_000, id_token_expires_in: 3600, id_token_signer: nil, prefix: {}, audience: nil, grant_type: nil, custom_token_response_fields: nil, custom_access_token_claims: nil, custom_id_token_claims: nil, jwt_access_token: false, use_jwt_plugin: false, pairwise_secret: nil, nonce: nil, auth_time: nil, reference_id: nil, filter_id_token_claims_by_scope: false, store_tokens: "hashed", generate_opaque_access_token: nil, generate_refresh_token: nil, format_refresh_token: nil)
  data = stringify_keys(session || {})
  user = stringify_keys(data["user"] || data[:user] || {})
  session_data = stringify_keys(data["session"] || data[:session] || {})
  client_data = stringify_keys(client)
  subject = subject_identifier(user["id"], client_data, pairwise_secret)
  token_auth_time = auth_time || session_auth_time({"session" => session_data})
  token_reference_id = reference_id || client_data["referenceId"]
  access_token_value = generate_opaque_access_token.respond_to?(:call) ? generate_opaque_access_token.call : Crypto.random_string(32)
  refresh_token_value = if include_refresh
    generate_refresh_token.respond_to?(:call) ? generate_refresh_token.call : Crypto.random_string(32)
  end
  refresh_token = refresh_token_value ? encode_refresh_token(refresh_token_value, prefix: prefix, format_refresh_token: format_refresh_token, session_id: session_data["id"]) : nil
  scope = scope_string(scopes)
  expires_at = Time.now + access_token_expires_in.to_i
  access_token = if jwt_access_token && audience
    build_jwt_access_token(ctx, client_data, user, session_data, scope, audience, issuer || issuer(ctx), expires_at, custom_access_token_claims, reference_id: token_reference_id, use_jwt_plugin: use_jwt_plugin)
  else
    apply_prefix(access_token_value, prefix, :access_token)
  end
  refresh_record = nil
  if refresh_token_value
    refresh_record = {
      "token" => store_token_value(store_tokens, refresh_token_value, "refresh_token"),
      "clientId" => client_data["clientId"],
      "sessionId" => session_data["id"],
      "userId" => user["id"],
      "referenceId" => token_reference_id,
      "authTime" => token_auth_time,
      "expiresAt" => Time.now + refresh_token_expires_in.to_i,
      "createdAt" => Time.now,
      "revoked" => nil,
      "scopes" => parse_scopes(scope),
      "subject" => subject,
      "audience" => audience,
      "issuer" => issuer || issuer(ctx),
      "issuedAt" => Time.now
    }
    created_refresh = schema_model?(ctx, "oauthRefreshToken") ? ctx.context.adapter.create(model: "oauthRefreshToken", data: refresh_record) : nil
    refresh_record = refresh_record.merge("id" => stringify_keys(created_refresh || {})["id"], "token" => refresh_token_value, "user" => user, "session" => session_data, "client" => client_data, "scope" => scope)
    store[:refresh_tokens][refresh_token_value] = refresh_record
    store[:refresh_tokens][refresh_token] = refresh_record
  end
  unless jwt_access_token && audience
    record = {
      "token" => store_token_value(store_tokens, access_token_value, "access_token"),
      "expiresAt" => expires_at,
      "clientId" => client_data["clientId"],
      "userId" => user["id"],
      "subject" => subject,
      "sessionId" => session_data["id"],
      "scopes" => parse_scopes(scope),
      "revoked" => nil,
      "referenceId" => token_reference_id,
      "authTime" => token_auth_time,
      "refreshId" => refresh_record && refresh_record["id"],
      "audience" => audience,
      "issuer" => issuer || issuer(ctx),
      "issuedAt" => Time.now
    }
    created_access = ctx.context.adapter.create(model: model, data: record)
    created = stringify_keys(created_access || {})
    record = record.merge("id" => created["id"]) if created["id"]
    stored_record = record.merge("token" => access_token_value, "user" => user, "session" => session_data, "client" => client_data)
    store[:tokens][access_token_value] = stored_record
    store[:tokens][access_token] = stored_record
  end

  response = {
    access_token: access_token,
    token_type: "Bearer",
    expires_in: access_token_expires_in.to_i,
    expires_at: expires_at.to_i,
    scope: scope
  }
  response[:audience] = audience if audience
  response[:refresh_token] = refresh_token if refresh_token
  id_token_client_data = client_data.merge("clientSecret" => client_data["__providedClientSecret"] || client_data["clientSecret"])
  response[:id_token] = id_token(user.merge("id" => subject), client_data["clientId"], issuer || issuer(ctx), jwt_audience || client_data["clientId"], ctx: ctx, signer: id_token_signer, session_id: session_data["id"], include_sid: !!client_data["enableEndSession"], nonce: nonce, auth_time: token_auth_time, custom_claims: custom_id_token_claims, scopes: parse_scopes(scope), client: id_token_client_data, filter_claims_by_scope: filter_id_token_claims_by_scope, expires_in: id_token_expires_in, use_jwt_plugin: use_jwt_plugin) if parse_scopes(scope).include?("openid")
  if custom_token_response_fields.respond_to?(:call)
    extra = custom_token_response_fields.call({grant_type: grant_type, user: user.empty? ? nil : user, scopes: parse_scopes(scope), metadata: stringify_keys(client_data["metadata"] || {})})
    response.merge!(stringify_keys(extra).reject { |key, _value| standard_token_response_field?(key) }.transform_keys(&:to_sym)) if extra.is_a?(Hash)
  end
  response
end

.issuer(ctx) ⇒ Object



39
40
41
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 39

def issuer(ctx)
  origin_for(ctx.context.canonical_base_url)
end

.jwt_plugin_options(ctx) ⇒ Object



924
925
926
927
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 924

def jwt_plugin_options(ctx)
  plugin = ctx.context.options.plugins.find { |entry| entry.id == "jwt" }
  plugin&.options
end

.jwt_userinfo(token, jwt_secret, additional_claim: nil, ctx: nil, issuer: nil) ⇒ Object



702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 702

def jwt_userinfo(token, jwt_secret, additional_claim: nil, ctx: nil, issuer: nil)
  payload = if ctx
    verify_oauth_jwt(ctx, token, issuer: issuer || issuer(ctx), hs256_secret: jwt_secret)
  else
    ::JWT.decode(token, jwt_secret.to_s, true, algorithm: "HS256").first
  end
  scopes = parse_scopes(payload["scope"])
  raise userinfo_openid_scope_error unless scopes.include?("openid")

  response = {sub: payload["sub"]}
  if scopes.include?("profile")
    response[:name] = payload["name"] if payload["name"]
    response[:given_name] = payload["name"].to_s.split(/\s+/, 2).first if payload["name"]
    response[:family_name] = payload["name"].to_s.split(/\s+/, 2).last if payload["name"].to_s.include?(" ")
  end
  if scopes.include?("email")
    response[:email] = payload["email"]
    response[:email_verified] = !!payload["email_verified"]
  end
  if additional_claim.respond_to?(:call)
    extra = additional_claim.call({user: payload, scopes: scopes, jwt: payload, client: {}})
    response.merge!(extra) if extra.is_a?(Hash)
  end
  response
rescue ::JWT::DecodeError
  raise APIError.new("UNAUTHORIZED", message: "invalid_token")
end

.loopback_host?(host) ⇒ Boolean

Returns:

  • (Boolean)


92
93
94
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 92

def loopback_host?(host)
  ["127.0.0.1", "::1"].include?(host.to_s)
end

.loopback_redirect_match?(redirects, redirect_uri) ⇒ Boolean

Returns:

  • (Boolean)


71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 71

def loopback_redirect_match?(redirects, redirect_uri)
  requested = URI.parse(redirect_uri.to_s)
  return false unless ["http", "https"].include?(requested.scheme)
  requested_host = requested.hostname || requested.host
  return false unless loopback_host?(requested_host)

  redirects.any? do |allowed|
    allowed_uri = URI.parse(allowed.to_s)
    allowed_host = allowed_uri.hostname || allowed_uri.host
    allowed_uri.scheme == requested.scheme &&
      loopback_host?(allowed_host) &&
      allowed_host == requested_host &&
      allowed_uri.path == requested.path &&
      allowed_uri.query == requested.query
  rescue URI::InvalidURIError
    false
  end
rescue URI::InvalidURIError
  false
end

.normalize_secret_storage_mode(mode) ⇒ Object



1061
1062
1063
1064
1065
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 1061

def normalize_secret_storage_mode(mode)
  return stringify_keys(mode).transform_keys(&:to_sym) if mode.is_a?(Hash)

  mode.to_s
end

.oauth_jwt_config(ctx, issuer:, audience:) ⇒ Object



929
930
931
932
933
934
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 929

def oauth_jwt_config(ctx, issuer:, audience:)
  options = jwt_plugin_options(ctx)
  return nil unless options

  BetterAuth::Plugins.deep_merge(options, jwt: {issuer: issuer, audience: audience})
end

.origin_for(url) ⇒ Object



47
48
49
50
51
52
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 47

def origin_for(url)
  uri = URI.parse(url.to_s)
  port = uri.port
  default_port = (uri.scheme == "http" && port == 80) || (uri.scheme == "https" && port == 443)
  default_port ? "#{uri.scheme}://#{uri.host}" : "#{uri.scheme}://#{uri.host}:#{port}"
end

.parse_duration(value) ⇒ Object

Raises:

  • (TypeError)


834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 834

def parse_duration(value)
  match = value.strip.match(/\A(-?\d+)\s*(s|sec|secs|second|seconds|m|min|mins|minute|minutes|h|hr|hrs|hour|hours|d|day|days|w|week|weeks|y|yr|yrs|year|years)(?:\s+from now|\s+ago)?\z/i)
  raise TypeError, "Invalid time string" unless match

  amount = match[1].to_i
  amount = -amount if value.include?("ago")
  unit = match[2].downcase
  multiplier = case unit
  when "s", "sec", "secs", "second", "seconds" then 1
  when "m", "min", "mins", "minute", "minutes" then 60
  when "h", "hr", "hrs", "hour", "hours" then 3600
  when "d", "day", "days" then 86_400
  when "w", "week", "weeks" then 604_800
  else 31_557_600
  end
  amount * multiplier
end

.parse_scopes(value) ⇒ Object



20
21
22
23
24
25
26
27
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 20

def parse_scopes(value)
  case value
  when Array
    value.map(&:to_s).reject(&:empty?)
  else
    value.to_s.split(/\s+/).reject(&:empty?)
  end
end

.pkce_required?(client, scopes) ⇒ Boolean

Returns:

  • (Boolean)


481
482
483
484
485
486
487
488
489
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 481

def pkce_required?(client, scopes)
  data = stringify_keys(client)
  return true if data["public"] || data["tokenEndpointAuthMethod"] == "none" || ["native", "user-agent-based"].include?(data["type"])
  return true if parse_scopes(scopes).include?("offline_access")
  require_pkce = client_require_pkce(data)
  return require_pkce unless require_pkce.nil?

  true
end

.redirect_uri_with_params(uri, params) ⇒ Object



54
55
56
57
58
59
60
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 54

def redirect_uri_with_params(uri, params)
  parsed = URI.parse(uri.to_s)
  existing = URI.decode_www_form(parsed.query.to_s)
  params.each { |key, value| existing << [key.to_s, value.to_s] unless value.nil? }
  parsed.query = URI.encode_www_form(existing)
  parsed.to_s
end

.refresh_tokens(ctx, store, model:, client:, refresh_token:, scopes: nil, issuer: nil, access_token_expires_in: 3600, refresh_token_expires_in: 2_592_000, id_token_expires_in: 3600, id_token_signer: nil, prefix: {}, audience: nil, custom_token_response_fields: nil, custom_access_token_claims: nil, custom_id_token_claims: nil, jwt_access_token: false, use_jwt_plugin: false, pairwise_secret: nil, filter_id_token_claims_by_scope: false, store_tokens: "hashed", generate_opaque_access_token: nil, generate_refresh_token: nil, format_refresh_token: nil) ⇒ Object

Raises:



577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 577

def refresh_tokens(ctx, store, model:, client:, refresh_token:, scopes: nil, issuer: nil, access_token_expires_in: 3600, refresh_token_expires_in: 2_592_000, id_token_expires_in: 3600, id_token_signer: nil, prefix: {}, audience: nil, custom_token_response_fields: nil, custom_access_token_claims: nil, custom_id_token_claims: nil, jwt_access_token: false, use_jwt_plugin: false, pairwise_secret: nil, filter_id_token_claims_by_scope: false, store_tokens: "hashed", generate_opaque_access_token: nil, generate_refresh_token: nil, format_refresh_token: nil)
  refresh_token_value = decode_refresh_token(refresh_token, prefix: prefix, format_refresh_token: format_refresh_token)
  raise APIError.new("BAD_REQUEST", message: "invalid_grant") if refresh_token_value.to_s.empty?
  data = store[:refresh_tokens][refresh_token_value]
  raise APIError.new("BAD_REQUEST", message: "invalid_grant") unless data
  if data["revoked"]
    revoke_refresh_family!(ctx, store, data)
    raise APIError.new("BAD_REQUEST", message: "invalid_grant")
  end
  raise APIError.new("BAD_REQUEST", message: "invalid_grant") if data["expiresAt"] && data["expiresAt"] <= Time.now

  client_data = stringify_keys(client)
  unless data["clientId"].to_s == client_data["clientId"].to_s
    raise APIError.new("BAD_REQUEST", message: "invalid_grant")
  end

  requested = scopes ? parse_scopes(scopes) : data["scopes"]
  unless requested.all? { |scope| data["scopes"].include?(scope) }
    raise APIError.new("BAD_REQUEST", message: "invalid_scope")
  end
  data["revoked"] = Time.now
  ctx.context.adapter.update(model: "oauthRefreshToken", where: [{field: "id", value: data["id"]}], update: {revoked: data["revoked"]}) if data["id"] && schema_model?(ctx, "oauthRefreshToken")

  issue_tokens(
    ctx,
    store,
    model: model,
    client: client,
    session: {"user" => data["user"], "session" => data["session"]},
    scopes: requested,
    include_refresh: true,
    issuer: issuer,
    access_token_expires_in: access_token_expires_in,
    refresh_token_expires_in: refresh_token_expires_in,
    id_token_signer: id_token_signer,
    prefix: prefix,
    audience: audience,
    grant_type: REFRESH_GRANT,
    custom_token_response_fields: custom_token_response_fields,
    custom_access_token_claims: custom_access_token_claims,
    custom_id_token_claims: custom_id_token_claims,
    jwt_access_token: jwt_access_token,
    use_jwt_plugin: use_jwt_plugin,
    pairwise_secret: pairwise_secret,
    id_token_expires_in: id_token_expires_in,
    auth_time: data["authTime"],
    reference_id: data["referenceId"],
    filter_id_token_claims_by_scope: filter_id_token_claims_by_scope,
    store_tokens: store_tokens,
    generate_opaque_access_token: generate_opaque_access_token,
    generate_refresh_token: generate_refresh_token,
    format_refresh_token: format_refresh_token
  )
end

.request_body!(value) ⇒ Object

Raises:



33
34
35
36
37
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 33

def request_body!(value)
  return stringify_keys(value || {}) if value.nil? || value.is_a?(Hash)

  raise APIError.new("BAD_REQUEST", message: "request body must be an object")
end

.resolve_client_secret_expires_at(value, issued_at) ⇒ Object



822
823
824
825
826
827
828
829
830
831
832
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 822

def resolve_client_secret_expires_at(value, issued_at)
  return value.to_i if value.is_a?(Numeric)
  return value.to_i if value.is_a?(Time)

  seconds = timestamp_seconds(value)
  return seconds if seconds && !value.is_a?(String)

  issued_at.to_i + parse_duration(value.to_s)
rescue TypeError
  0
end

.revoke_refresh_family!(ctx, store, refresh_record) ⇒ Object



755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 755

def revoke_refresh_family!(ctx, store, refresh_record)
  client_id = refresh_record["clientId"]
  user_id = refresh_record["userId"]
  store[:refresh_tokens].delete_if { |_token, record| record["clientId"] == client_id && record["userId"] == user_id }
  store[:tokens].delete_if { |_token, record| record["clientId"] == client_id && record["userId"] == user_id }
  if schema_model?(ctx, "oauthRefreshToken")
    refresh_ids = ctx.context.adapter.find_many(
      model: "oauthRefreshToken",
      where: [
        {field: "clientId", value: client_id},
        {field: "userId", value: user_id}
      ]
    ).map { |entry| stringify_keys(entry)["id"] }

    ctx.context.adapter.delete_many(
      model: "oauthRefreshToken",
      where: [
        {field: "clientId", value: client_id},
        {field: "userId", value: user_id}
      ]
    )

    if schema_model?(ctx, "oauthAccessToken")
      refresh_ids.each do |refresh_id|
        ctx.context.adapter.delete_many(model: "oauthAccessToken", where: [{field: "refreshId", value: refresh_id}])
      end
    end
  end
end

.schema_model?(ctx, model) ⇒ Boolean

Returns:

  • (Boolean)


785
786
787
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 785

def schema_model?(ctx, model)
  Schema.auth_tables(ctx.context.options).key?(model.to_s)
end

.scope_string(value) ⇒ Object



29
30
31
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 29

def scope_string(value)
  parse_scopes(value).join(" ")
end

.sector_identifier(client) ⇒ Object



973
974
975
976
977
978
979
980
981
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 973

def sector_identifier(client)
  data = stringify_keys(client)
  uri = client_redirect_uris(data).first
  raise APIError.new("BAD_REQUEST", message: "pairwise subject_type requires redirect_uris") if uri.to_s.empty?

  URI.parse(uri.to_s).host || data["clientId"]
rescue URI::InvalidURIError
  data["clientId"]
end

.session_auth_time(session) ⇒ Object



983
984
985
986
987
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 983

def session_auth_time(session)
  data = stringify_keys(session || {})
  session_data = stringify_keys(data["session"] || data[:session] || data)
  session_data["createdAt"] || session_data["created_at"]
end

.sign_oauth_jwt(ctx, payload, issuer:, audience:) ⇒ Object



936
937
938
939
940
941
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 936

def sign_oauth_jwt(ctx, payload, issuer:, audience:)
  config = oauth_jwt_config(ctx, issuer: issuer, audience: audience)
  return nil unless config

  BetterAuth::Plugins.sign_jwt_payload(ctx, stringify_keys(payload), config)
end

.sign_oauth_jwt!(ctx, payload, issuer:, audience:) ⇒ Object

Raises:



943
944
945
946
947
948
949
950
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 943

def sign_oauth_jwt!(ctx, payload, issuer:, audience:)
  raise BetterAuth::Error, "jwt_config" unless jwt_plugin_options(ctx)

  signed = sign_oauth_jwt(ctx, payload, issuer: issuer, audience: audience)
  raise BetterAuth::Error, "jwt_config" unless signed

  signed
end

.standard_token_response_field?(key) ⇒ Boolean

Returns:

  • (Boolean)


962
963
964
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 962

def standard_token_response_field?(key)
  %w[access_token token_type expires_in scope refresh_token id_token audience].include?(key.to_s)
end

.store_client_secret_value(ctx, secret, mode) ⇒ Object



1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 1014

def store_client_secret_value(ctx, secret, mode)
  mode = normalize_secret_storage_mode(mode)
  return Crypto.sha256(secret, encoding: :base64url) if mode == "hashed"
  return Crypto.symmetric_encrypt(key: ctx.context.secret_config, data: secret) if mode == "encrypted"

  if mode.is_a?(Hash)
    return mode[:hash].call(secret) if mode[:hash].respond_to?(:call)
    return mode[:encrypt].call(secret) if mode[:encrypt].respond_to?(:call)
  end

  secret
end

.store_code(internal_adapter, code:, client_id:, redirect_uri:, session:, scopes:, code_challenge: nil, code_challenge_method: nil, nonce: nil, reference_id: nil, auth_time: nil, expires_in: 600, store_tokens: "hashed") ⇒ Object



422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 422

def store_code(internal_adapter, code:, client_id:, redirect_uri:, session:, scopes:, code_challenge: nil, code_challenge_method: nil, nonce: nil, reference_id: nil, auth_time: nil, expires_in: 600, store_tokens: "hashed")
  stored_code = get_stored_token(store_tokens, code, "authorization_code")
  expires_at = Time.now + expires_in.to_i
  data = {
    client_id: client_id,
    redirect_uri: redirect_uri,
    session: session,
    scopes: parse_scopes(scopes),
    code_challenge: code_challenge,
    code_challenge_method: code_challenge_method,
    nonce: nonce,
    reference_id: reference_id,
    auth_time: auth_time || session_auth_time(session),
    expires_at: expires_at.iso8601(6)
  }
  internal_adapter.create_verification_value(identifier: stored_code, value: JSON.generate(data), expiresAt: expires_at)
end

.store_token_value(storage_method, token, type) ⇒ Object



1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 1027

def store_token_value(storage_method, token, type)
  case storage_method
  when "hashed", :hashed
    Crypto.sha256(token.to_s, encoding: :base64url)
  else
    mode = normalize_secret_storage_mode(storage_method)
    return mode[:hash].call(token.to_s, type) if mode.is_a?(Hash) && mode[:hash].respond_to?(:call)

    raise Error, "storeToken: unsupported storageMethod type '#{storage_method}'"
  end
end

.storesObject



1067
1068
1069
1070
1071
1072
1073
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 1067

def stores
  {
    tokens: {},
    refresh_tokens: {},
    consents: {}
  }
end

.stringify_keys(value) ⇒ Object



1075
1076
1077
1078
1079
1080
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 1075

def stringify_keys(value)
  return value.each_with_object({}) { |(key, object_value), result| result[key.to_s] = stringify_keys(object_value) } if value.is_a?(Hash)
  return value.map { |entry| stringify_keys(entry) } if value.is_a?(Array)

  value
end

.strip_prefix(value, prefix, kind) ⇒ Object



852
853
854
855
856
857
858
859
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 852

def strip_prefix(value, prefix, kind)
  token = value.to_s
  expected = token_prefix(prefix, kind)
  return token if expected.empty?
  return token.delete_prefix(expected) if token.start_with?(expected)

  nil
end

.subject_identifier(user_id, client, pairwise_secret) ⇒ Object



966
967
968
969
970
971
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 966

def subject_identifier(user_id, client, pairwise_secret)
  data = stringify_keys(client)
  return user_id unless data["subjectType"] == "pairwise" && pairwise_secret && user_id

  OpenSSL::HMAC.hexdigest("SHA256", pairwise_secret.to_s, "#{sector_identifier(data)}.#{user_id}")
end

.timestamp_seconds(value) ⇒ Object



989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 989

def timestamp_seconds(value)
  if value.is_a?(Numeric)
    return nil unless value.finite?
    return nil if value.abs > 8_640_000_000_000_000

    return (value / 1000.0).floor if value.abs >= 100_000_000_000

    return value.to_i
  end
  if value.is_a?(String) && value.match?(/\A[-+]?(?:\d+(?:\.\d+)?|\.\d+)(?:e[-+]?\d+)?\z/i)
    numeric = value.to_f
    return nil unless numeric.finite?
    return nil if numeric.abs > 8_640_000_000_000_000

    return (numeric / 1000.0).floor if numeric.abs >= 100_000_000_000

    return numeric.to_i
  end
  return timestamp_seconds(value.to_i) if value.respond_to?(:to_i) && !value.is_a?(String)

  Time.parse(value.to_s).to_i
rescue ArgumentError, TypeError, FloatDomainError
  nil
end

.token_prefix(prefix, kind) ⇒ Object



861
862
863
864
865
866
867
868
869
870
871
872
873
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 861

def token_prefix(prefix, kind)
  data = stringify_keys(prefix || {})
  case kind
  when :access_token
    data["opaque_access_token"] || data["opaqueAccessToken"] || "ba_at_"
  when :refresh_token
    data["refresh_token"] || data["refreshToken"] || "ba_rt_"
  when :client_secret
    data["client_secret"] || data["clientSecret"] || ""
  else
    ""
  end
end

.token_record(store, token, prefix: {}) ⇒ Object



632
633
634
635
636
637
638
639
640
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 632

def token_record(store, token, prefix: {})
  token_value = strip_prefix(token, prefix, :access_token)
  data = token_value ? store[:tokens][token_value] : nil
  return nil unless data
  return nil if data["revoked"]
  return nil if data["expiresAt"] && data["expiresAt"] <= Time.now

  data
end

.trusted_client_cacheObject



818
819
820
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 818

def trusted_client_cache
  @trusted_client_cache ||= {}
end

.userinfo(store, authorization, additional_claim: nil, prefix: {}, jwt_secret: nil, ctx: nil, issuer: nil) ⇒ Object



667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 667

def userinfo(store, authorization, additional_claim: nil, prefix: {}, jwt_secret: nil, ctx: nil, issuer: nil)
  if authorization.to_s.strip.empty?
    raise APIError.new(
      "UNAUTHORIZED",
      message: "authorization header not found",
      body: {error: "invalid_request", error_description: "authorization header not found"}
    )
  end
  token = authorization.to_s.delete_prefix("Bearer ").strip
  record = token_record(store, token, prefix: prefix)
  return jwt_userinfo(token, jwt_secret, additional_claim: additional_claim, ctx: ctx, issuer: issuer) unless record
  user = stringify_keys(record["user"])
  scopes = parse_scopes(record["scopes"])
  raise userinfo_openid_scope_error unless scopes.include?("openid")

  response = {sub: record["subject"] || user["id"]}
  response[:name] = user["name"] if scopes.include?("profile")
  response[:given_name] = user["name"].to_s.split(/\s+/, 2).first if scopes.include?("profile") && user["name"]
  response[:family_name] = user["name"].to_s.split(/\s+/, 2).last if scopes.include?("profile") && user["name"].to_s.include?(" ")
  response[:picture] = user["image"] if scopes.include?("profile") && user["image"]
  if scopes.include?("email")
    response[:email] = user["email"]
    response[:email_verified] = !!user["emailVerified"]
  end
  if additional_claim.respond_to?(:call)
    extra = begin
      additional_claim.call({user: user, scopes: scopes, jwt: record, client: stringify_keys(record["client"] || {})})
    rescue ArgumentError
      additional_claim.call(user, scopes, stringify_keys(record["client"] || {}))
    end
    response.merge!(extra) if extra.is_a?(Hash)
  end
  response
end

.userinfo_openid_scope_errorObject



730
731
732
733
734
735
736
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 730

def userinfo_openid_scope_error
  APIError.new(
    "BAD_REQUEST",
    message: "openid scope is required",
    body: {error: "invalid_request", error_description: "openid scope is required"}
  )
end

.validate_admin_only_fields!(body, admin:) ⇒ Object



349
350
351
352
353
354
355
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 349

def validate_admin_only_fields!(body, admin:)
  return if admin

  %w[client_secret_expires_at clientSecretExpiresAt].each do |key|
    raise APIError.new("BAD_REQUEST", message: "field #{key} is server-only") if body.key?(key)
  end
end

.validate_authorize_pkce(client, scopes, code_challenge, code_challenge_method) ⇒ Object



470
471
472
473
474
475
476
477
478
479
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 470

def validate_authorize_pkce(client, scopes, code_challenge, code_challenge_method)
  method = code_challenge_method.to_s
  return "code_challenge_method must be S256" if !code_challenge.to_s.empty? && method != "S256"

  return nil unless pkce_required?(client, scopes)
  return "PKCE is required" if code_challenge.to_s.empty?
  return "code_challenge_method must be S256" if method != "S256"

  nil
end

.validate_client_metadata_enums!(auth_method, body) ⇒ Object

Raises:



332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 332

def (auth_method, body)
  unless ["client_secret_basic", "client_secret_post", "none"].include?(auth_method)
    raise APIError.new("BAD_REQUEST", message: "invalid token_endpoint_auth_method")
  end

  invalid_grant = Array(body["grant_types"]).map(&:to_s) - [AUTH_CODE_GRANT, CLIENT_CREDENTIALS_GRANT, REFRESH_GRANT]
  raise APIError.new("BAD_REQUEST", message: "invalid grant_types") unless invalid_grant.empty?

  invalid_response = Array(body["response_types"]).map(&:to_s) - ["code"]
  raise APIError.new("BAD_REQUEST", message: "invalid response_types") unless invalid_response.empty?

  client_type = body["type"]
  if client_type && !["web", "native", "user-agent-based"].include?(client_type)
    raise APIError.new("BAD_REQUEST", message: "invalid type")
  end
end

.validate_client_registration!(auth_method, grant_types, response_types, body, unauthenticated:, dynamic_registration:) ⇒ Object



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 240

def validate_client_registration!(auth_method, grant_types, response_types, body, unauthenticated:, dynamic_registration:)
  public_client = auth_method == "none"
  if dynamic_registration && (body["require_pkce"] == false || body["requirePKCE"] == false)
    raise APIError.new("BAD_REQUEST", message: "pkce is required for registered clients")
  end
  if dynamic_registration && (body["enable_end_session"] || body["enableEndSession"])
    raise APIError.new("BAD_REQUEST", message: "enable_end_session is not allowed during dynamic client registration")
  end
  if public_client && grant_types.include?(CLIENT_CREDENTIALS_GRANT)
    raise APIError.new("BAD_REQUEST", message: "public clients cannot use client_credentials")
  end
  if grant_types.include?(AUTH_CODE_GRANT) && !response_types.include?("code")
    raise APIError.new("BAD_REQUEST", message: "authorization_code clients must support code response_type")
  end
  if auth_method != "none" && ["native", "user-agent-based"].include?(body["type"])
    raise APIError.new("BAD_REQUEST", message: "public client types must use token_endpoint_auth_method none")
  end
  if !unauthenticated && auth_method == "none" && body["type"] == "web"
    raise APIError.new("BAD_REQUEST", message: "web clients must be confidential")
  end
end

.validate_pairwise_client!(body, redirects, pairwise_secret) ⇒ Object



276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 276

def validate_pairwise_client!(body, redirects, pairwise_secret)
  subject_type = body["subject_type"] || body["subjectType"]
  return unless subject_type == "pairwise"

  raise APIError.new("BAD_REQUEST", message: "pairwise subject_type requires pairwise_secret") if pairwise_secret.to_s.empty?

  hosts = redirects.map { |uri| URI.parse(uri).host }.uniq
  if hosts.length > 1
    raise APIError.new(
      "BAD_REQUEST",
      message: "pairwise clients with redirect_uris on different hosts require a sector_identifier_uri, which is not yet supported. All redirect_uris must share the same host."
    )
  end
rescue URI::InvalidURIError
  raise APIError.new("BAD_REQUEST", message: "invalid redirect_uris")
end

.validate_redirect_scheme_for_client!(auth_method, body, redirects) ⇒ Object



262
263
264
265
266
267
268
269
270
271
272
273
274
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 262

def validate_redirect_scheme_for_client!(auth_method, body, redirects)
  return if auth_method == "none" && body["type"] != "web"

  redirects.each do |value|
    uri = URI.parse(value.to_s)
    next if uri.scheme == "https"
    next if uri.scheme == "http" && loopback_host?(uri.hostname || uri.host)

    raise APIError.new("BAD_REQUEST", message: "redirect_uris is invalid")
  end
rescue URI::InvalidURIError
  raise APIError.new("BAD_REQUEST", message: "redirect_uris is invalid")
end

.validate_redirect_uri!(client, redirect_uri) ⇒ Object

Raises:



62
63
64
65
66
67
68
69
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 62

def validate_redirect_uri!(client, redirect_uri)
  validate_safe_url!(redirect_uri, field: "redirect_uri")
  redirects = client_redirect_uris(client)
  return if redirects.include?(redirect_uri.to_s)
  return if loopback_redirect_match?(redirects, redirect_uri)

  raise APIError.new("BAD_REQUEST", message: "invalid redirect_uri")
end

.validate_safe_url!(value, field:) ⇒ Object



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 293

def validate_safe_url!(value, field:)
  raise APIError.new("BAD_REQUEST", message: "#{field} is invalid") if value.to_s.empty?

  uri = URI.parse(value.to_s)
  scheme = uri.scheme.to_s.downcase
  raise APIError.new("BAD_REQUEST", message: "#{field} is invalid") if scheme.empty?
  raise APIError.new("BAD_REQUEST", message: "#{field} is invalid") if %w[javascript data vbscript].include?(scheme)

  if scheme == "http"
    raise APIError.new("BAD_REQUEST", message: "#{field} is invalid") unless ["localhost", "127.0.0.1", "::1"].include?(uri.hostname || uri.host)
  end
  true
rescue URI::InvalidURIError
  raise APIError.new("BAD_REQUEST", message: "#{field} is invalid")
end

.verify_client_secret(ctx, stored_secret, provided_secret, mode) ⇒ Object



1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 1043

def verify_client_secret(ctx, stored_secret, provided_secret, mode)
  mode = normalize_secret_storage_mode(mode)
  return Crypto.constant_time_compare(Crypto.sha256(provided_secret, encoding: :base64url), stored_secret.to_s) if mode == "hashed"
  if mode == "encrypted"
    decrypted = Crypto.symmetric_decrypt(key: ctx.context.secret_config, data: stored_secret)
    return Crypto.constant_time_compare(decrypted.to_s, provided_secret.to_s)
  end

  if mode.is_a?(Hash)
    return Crypto.constant_time_compare(mode[:hash].call(provided_secret).to_s, stored_secret.to_s) if mode[:hash].respond_to?(:call)
    return Crypto.constant_time_compare(mode[:decrypt].call(stored_secret).to_s, provided_secret.to_s) if mode[:decrypt].respond_to?(:call)
  end

  Crypto.constant_time_compare(stored_secret.to_s, provided_secret.to_s)
rescue Error, ArgumentError
  false
end

.verify_oauth_jwt(ctx, token, issuer:, hs256_secret:) ⇒ Object



952
953
954
955
956
957
958
959
960
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 952

def verify_oauth_jwt(ctx, token, issuer:, hs256_secret:)
  payload = ::JWT.decode(token.to_s, nil, false).first
  audience = payload["aud"]
  config = oauth_jwt_config(ctx, issuer: issuer, audience: audience.is_a?(Array) ? audience.first : audience)
  verified = BetterAuth::Plugins.verify_jwt_token(ctx, token, config) if config
  return verified if verified

  ::JWT.decode(token, hs256_secret.to_s, true, algorithm: "HS256").first
end

.verify_pkce!(code_data, verifier) ⇒ Object

Raises:



461
462
463
464
465
466
467
468
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 461

def verify_pkce!(code_data, verifier)
  raise APIError.new("BAD_REQUEST", message: "invalid_grant") if verifier.to_s.empty?

  raise APIError.new("BAD_REQUEST", message: "invalid_grant") unless code_data[:code_challenge_method].to_s == "S256"

  challenge = Base64.urlsafe_encode64(OpenSSL::Digest.digest("SHA256", verifier.to_s), padding: false)
  raise APIError.new("BAD_REQUEST", message: "invalid_grant") unless challenge == code_data[:code_challenge]
end