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



676
677
678
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 676

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

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



316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 316

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

  authorization = ctx.headers["authorization"]
  if authorization.to_s.start_with?("Basic ") && client_id.to_s.empty?
    decoded = Base64.decode64(authorization.delete_prefix("Basic "))
    client_id, client_secret = decoded.split(":", 2)
  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") unless client_secret.to_s.empty?
    return 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
rescue ArgumentError
  raise APIError.new("UNAUTHORIZED", message: "invalid_client")
end

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



540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 540

def build_jwt_access_token(ctx, client, user, session, scope, audience, issuer_value, expires_at, custom_claims, reference_id: nil)
  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"],
    "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
  ::JWT.encode(payload, ctx.context.secret, "HS256")
end

.client_logout_redirect_uris(client) ⇒ Object



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

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



268
269
270
271
272
273
274
275
276
277
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 268

def (body, strip_unknown: false)
   = stringify_keys(body["metadata"] || {})
   = .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



88
89
90
91
92
93
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 88

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



279
280
281
282
283
284
285
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 279

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



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 183

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

.consume_code!(store, code, client_id:, redirect_uri:, code_verifier: nil) ⇒ Object

Raises:



362
363
364
365
366
367
368
369
370
371
372
373
374
375
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 362

def consume_code!(store, code, client_id:, redirect_uri:, code_verifier: nil)
  data = store[:codes].delete(code.to_s)
  raise APIError.new("BAD_REQUEST", message: "invalid_grant") unless data
  raise APIError.new("BAD_REQUEST", message: "invalid_grant") if data[:expires_at] <= Time.now
  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
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) ⇒ Object

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
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
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 102

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)
  body = stringify_keys(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 = Crypto.random_string(32)
  client_secret = public_client ? nil : Crypto.random_string(32)
  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_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
  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" => admin ? (body["client_secret_expires_at"] || 0) : nil,
    "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?
  response[:client_secret_expires_at] = 0 if client_secret
  response
end

.endpoint_base(ctx) ⇒ Object



36
37
38
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 36

def endpoint_base(ctx)
  ctx.context.base_url
end

.find_client(ctx, model, client_id) ⇒ Object



312
313
314
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 312

def find_client(ctx, model, client_id)
  ctx.context.adapter.find_one(model: model, where: [{field: "clientId", value: client_id.to_s}])
end

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



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

def find_token_by_hint(store, token, hint, prefix: {})
  access = -> { (value = strip_prefix(token, prefix, :access_token)) && store[:tokens][value] }
  refresh = -> { (value = strip_prefix(token, prefix, :refresh_token)) && 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

.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) ⇒ Object



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
729
730
731
732
733
734
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 703

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)
  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)

  Crypto.sign_jwt(
    payload,
    client_id.to_s.empty? ? "better-auth" : client_id.to_s,
    expires_in: 3600
  )
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_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, pairwise_secret: nil, nonce: nil, auth_time: nil, reference_id: nil, filter_id_token_claims_by_scope: false) ⇒ Object



406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 406

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_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, pairwise_secret: nil, nonce: nil, auth_time: nil, reference_id: nil, filter_id_token_claims_by_scope: false)
  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 = Crypto.random_string(32)
  refresh_token_value = include_refresh ? Crypto.random_string(32) : nil
  refresh_token = refresh_token_value ? apply_prefix(refresh_token_value, prefix, :refresh_token) : 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)
  else
    apply_prefix(access_token_value, prefix, :access_token)
  end
  refresh_record = nil
  if refresh_token_value
    refresh_record = {
      "token" => refresh_token_value,
      "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"], "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" => access_token_value,
      "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
    }
    ctx.context.adapter.create(model: model, data: record)
    stored_record = record.merge("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
  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: client_data, filter_claims_by_scope: filter_id_token_claims_by_scope) 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



32
33
34
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 32

def issuer(ctx)
  ctx.context.options.base_url.to_s.empty? ? origin_for(ctx.context.base_url) : ctx.context.options.base_url
end

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



596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 596

def jwt_userinfo(token, jwt_secret, additional_claim: nil)
  payload = ::JWT.decode(token, jwt_secret.to_s, true, algorithm: "HS256").first
  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)


84
85
86
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 84

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

.loopback_redirect_match?(redirects, redirect_uri) ⇒ Boolean

Returns:

  • (Boolean)


63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 63

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



814
815
816
817
818
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 814

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

  mode.to_s
end

.origin_for(url) ⇒ Object



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

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_scopes(value) ⇒ Object



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

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)


397
398
399
400
401
402
403
404
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 397

def pkce_required?(client, scopes)
  data = stringify_keys(client)
  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



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

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_signer: nil, prefix: {}, audience: nil, custom_token_response_fields: nil, custom_access_token_claims: nil, custom_id_token_claims: nil, jwt_access_token: false, pairwise_secret: nil, filter_id_token_claims_by_scope: false) ⇒ Object

Raises:



487
488
489
490
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
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 487

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_signer: nil, prefix: {}, audience: nil, custom_token_response_fields: nil, custom_access_token_claims: nil, custom_id_token_claims: nil, jwt_access_token: false, pairwise_secret: nil, filter_id_token_claims_by_scope: false)
  refresh_token_value = strip_prefix(refresh_token, prefix, :refresh_token)
  data = refresh_token_value ? store[:refresh_tokens][refresh_token_value] : nil
  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

  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,
    pairwise_secret: pairwise_secret,
    auth_time: data["authTime"],
    reference_id: data["referenceId"],
    filter_id_token_claims_by_scope: filter_id_token_claims_by_scope
  )
end

.revoke_refresh_family!(ctx, store, refresh_record) ⇒ 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
666
667
668
669
670
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 642

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)


672
673
674
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 672

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

.scope_string(value) ⇒ Object



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

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

.sector_identifier(client) ⇒ Object



747
748
749
750
751
752
753
754
755
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 747

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



757
758
759
760
761
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 757

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

.standard_token_response_field?(key) ⇒ Boolean

Returns:

  • (Boolean)


736
737
738
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 736

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



788
789
790
791
792
793
794
795
796
797
798
799
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 788

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, 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(store, code:, client_id:, redirect_uri:, session:, scopes:, code_challenge: nil, code_challenge_method: nil, nonce: nil, reference_id: nil, auth_time: nil) ⇒ Object



347
348
349
350
351
352
353
354
355
356
357
358
359
360
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 347

def store_code(store, code:, client_id:, redirect_uri:, session:, scopes:, code_challenge: nil, code_challenge_method: nil, nonce: nil, reference_id: nil, auth_time: nil)
  store[:codes][code] = {
    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: Time.now + 600
  }
end

.storesObject



820
821
822
823
824
825
826
827
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 820

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

.stringify_keys(value) ⇒ Object



829
830
831
832
833
834
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 829

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



680
681
682
683
684
685
686
687
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 680

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



740
741
742
743
744
745
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 740

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



763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 763

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



689
690
691
692
693
694
695
696
697
698
699
700
701
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 689

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



530
531
532
533
534
535
536
537
538
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 530

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

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



561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 561

def userinfo(store, authorization, additional_claim: nil, prefix: {}, jwt_secret: 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) 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



620
621
622
623
624
625
626
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 620

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



304
305
306
307
308
309
310
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 304

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



386
387
388
389
390
391
392
393
394
395
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 386

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:



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 287

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



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 218

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



240
241
242
243
244
245
246
247
248
249
250
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 240

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
  raise APIError.new("BAD_REQUEST", message: "pairwise redirect_uris must share the same host") if hosts.length > 1
rescue URI::InvalidURIError
  raise APIError.new("BAD_REQUEST", message: "invalid redirect_uris")
end

.validate_redirect_uri!(client, redirect_uri) ⇒ Object

Raises:



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

def validate_redirect_uri!(client, 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



252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 252

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



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

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"
  return Crypto.symmetric_decrypt(key: ctx.context.secret, data: stored_secret) == provided_secret.to_s if mode == "encrypted"

  if mode.is_a?(Hash)
    return mode[:hash].call(provided_secret).to_s == stored_secret.to_s if mode[:hash].respond_to?(:call)
    return 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)
end

.verify_pkce!(code_data, verifier) ⇒ Object

Raises:



377
378
379
380
381
382
383
384
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 377

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