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



564
565
566
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 564

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

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



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 260

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



470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 470

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"],
    "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



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

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_redirect_uris(client) ⇒ Object



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

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_response(client, include_secret: true) ⇒ Object



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
204
205
206
207
208
209
210
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 177

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: data["requirePKCE"],
    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:



306
307
308
309
310
311
312
313
314
315
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 306

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
  verify_pkce!(data, code_verifier) if data[:code_challenge]

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

Raises:



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

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

  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)

  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

   = stringify_keys(body["metadata"] || {})
  ["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["userId"] = owner_session[:user]["id"] if owner_session
  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



256
257
258
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 256

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



516
517
518
519
520
521
522
523
524
525
526
527
528
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 516

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



591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 591

def id_token(user, client_id, issuer_value, audience, ctx: nil, signer: nil, session_id: nil, include_sid: false, nonce: nil, auth_time: nil)
  payload = {
    sub: user["id"],
    iss: issuer_value,
    aud: audience || client_id,
    email: user["email"],
    email_verified: !!user["emailVerified"],
    name: user["name"]
  }
  payload[:sid] = session_id if include_sid && session_id
  payload[:nonce] = nonce if nonce
  payload[:auth_time] = timestamp_seconds(auth_time) if auth_time
  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, jwt_access_token: false, pairwise_secret: nil, nonce: nil, auth_time: nil, reference_id: nil) ⇒ Object



345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
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
414
415
416
417
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 345

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, jwt_access_token: false, pairwise_secret: nil, nonce: nil, auth_time: nil, reference_id: 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 = 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)
    }
    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
    }
    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,
    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) 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!(extra) 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

.loopback_host?(host) ⇒ Boolean

Returns:

  • (Boolean)


82
83
84
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 82

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
# 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)
  return false unless loopback_host?(requested.host)

  redirects.any? do |allowed|
    allowed_uri = URI.parse(allowed.to_s)
    allowed_uri.scheme == requested.scheme &&
      loopback_host?(allowed_uri.host) &&
      allowed_uri.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



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

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)


337
338
339
340
341
342
343
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 337

def pkce_required?(client, scopes)
  data = stringify_keys(client)
  return true if parse_scopes(scopes).include?("offline_access")
  return data["requirePKCE"] unless data["requirePKCE"].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, jwt_access_token: false, pairwise_secret: nil) ⇒ Object

Raises:



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

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

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



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

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)


560
561
562
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 560

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



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

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



629
630
631
632
633
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 629

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

.store_client_secret_value(ctx, secret, mode) ⇒ Object



645
646
647
648
649
650
651
652
653
654
655
656
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 645

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



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

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



677
678
679
680
681
682
683
684
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 677

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

.stringify_keys(value) ⇒ Object



686
687
688
689
690
691
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 686

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



568
569
570
571
572
573
574
575
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 568

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



612
613
614
615
616
617
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 612

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



635
636
637
638
639
640
641
642
643
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 635

def timestamp_seconds(value)
  return value.to_i if value.is_a?(Integer)
  return value.to_i if value.is_a?(Float)
  return value.to_i if value.respond_to?(:to_i) && !value.is_a?(String)

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

.token_prefix(prefix, kind) ⇒ Object



577
578
579
580
581
582
583
584
585
586
587
588
589
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 577

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



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

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: {}) ⇒ Object

Raises:



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

def userinfo(store, authorization, additional_claim: nil, prefix: {})
  token = authorization.to_s.delete_prefix("Bearer ").strip
  record = token_record(store, token, prefix: prefix)
  raise APIError.new("UNAUTHORIZED", message: "invalid_token") unless record
  user = stringify_keys(record["user"])
  scopes = parse_scopes(record["scopes"])
  raise APIError.new("FORBIDDEN", message: "openid scope is required") 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

.validate_admin_only_fields!(body, admin:) ⇒ Object



248
249
250
251
252
253
254
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 248

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



326
327
328
329
330
331
332
333
334
335
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 326

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:



231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 231

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



212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 212

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

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



658
659
660
661
662
663
664
665
666
667
668
669
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 658

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:



317
318
319
320
321
322
323
324
# File 'lib/better_auth/plugins/oauth_protocol.rb', line 317

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