stytch 6.4.0 → 9.8.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,255 @@
1
+ # frozen_string_literal: true
2
+
3
+ # !!!
4
+ # WARNING: This file is autogenerated
5
+ # Only modify code within MANUAL() sections
6
+ # or your changes may be overwritten later!
7
+ # !!!
8
+
9
+ require_relative 'request_helper'
10
+
11
+ module StytchB2B
12
+ class TOTPs
13
+ include Stytch::RequestHelper
14
+
15
+ def initialize(connection)
16
+ @connection = connection
17
+ end
18
+
19
+ # Create a new TOTP instance for a. The Member can use the authenticator application of their choice to scan the QR code or enter the secret.
20
+ #
21
+ # Passing an intermediate session token, session token, or session JWT is not required, but if passed must match the Member ID passed.
22
+ #
23
+ # == Parameters:
24
+ # organization_id::
25
+ # Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to perform operations on an Organization, so be sure to preserve this value.
26
+ # The type of this field is +String+.
27
+ # member_id::
28
+ # Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform operations on a Member, so be sure to preserve this value.
29
+ # The type of this field is +String+.
30
+ # expiration_minutes::
31
+ # The expiration for the TOTP registration. If the newly created TOTP registration is not authenticated within this time frame the member will have to restart the registration flow. Defaults to 60 (1 hour) with a minimum of 5 and a maximum of 1440.
32
+ # The type of this field is nilable +Integer+.
33
+ # intermediate_session_token::
34
+ # The Intermediate Session Token. This token does not necessarily belong to a specific instance of a Member, but represents a bag of factors that may be converted to a member session. The token can be used with the [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms), [TOTP Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-totp), or [Recovery Codes Recover endpoint](https://stytch.com/docs/b2b/api/recovery-codes-recover) to complete an MFA flow and log in to the Organization. It can also be used with the [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) to join a specific Organization that allows the factors represented by the intermediate session token; or the [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member.
35
+ # The type of this field is nilable +String+.
36
+ # session_token::
37
+ # A secret token for a given Stytch Session.
38
+ # The type of this field is nilable +String+.
39
+ # session_jwt::
40
+ # The JSON Web Token (JWT) for a given Stytch Session.
41
+ # The type of this field is nilable +String+.
42
+ #
43
+ # == Returns:
44
+ # An object with the following fields:
45
+ # request_id::
46
+ # Globally unique UUID that is returned with every API call. This value is important to log for debugging purposes; we may ask for this value to help identify a specific API call when helping you debug an issue.
47
+ # The type of this field is +String+.
48
+ # member_id::
49
+ # Globally unique UUID that identifies a specific Member.
50
+ # The type of this field is +String+.
51
+ # totp_registration_id::
52
+ # The unique ID for a TOTP instance.
53
+ # The type of this field is +String+.
54
+ # secret::
55
+ # The TOTP secret key shared between the authenticator app and the server used to generate TOTP codes.
56
+ # The type of this field is +String+.
57
+ # qr_code::
58
+ # The QR code image encoded in base64.
59
+ # The type of this field is +String+.
60
+ # recovery_codes::
61
+ # An array of recovery codes that can be used to recover a Member's account.
62
+ # The type of this field is list of +String+.
63
+ # member::
64
+ # The [Member object](https://stytch.com/docs/b2b/api/member-object)
65
+ # The type of this field is +Member+ (+object+).
66
+ # organization::
67
+ # The [Organization object](https://stytch.com/docs/b2b/api/organization-object).
68
+ # The type of this field is +Organization+ (+object+).
69
+ # status_code::
70
+ # The HTTP status code of the response. Stytch follows standard HTTP response status code patterns, e.g. 2XX values equate to success, 3XX values are redirects, 4XX are client errors, and 5XX are server errors.
71
+ # The type of this field is +Integer+.
72
+ def create(
73
+ organization_id:,
74
+ member_id:,
75
+ expiration_minutes: nil,
76
+ intermediate_session_token: nil,
77
+ session_token: nil,
78
+ session_jwt: nil
79
+ )
80
+ headers = {}
81
+ request = {
82
+ organization_id: organization_id,
83
+ member_id: member_id
84
+ }
85
+ request[:expiration_minutes] = expiration_minutes unless expiration_minutes.nil?
86
+ request[:intermediate_session_token] = intermediate_session_token unless intermediate_session_token.nil?
87
+ request[:session_token] = session_token unless session_token.nil?
88
+ request[:session_jwt] = session_jwt unless session_jwt.nil?
89
+
90
+ post_request('/v1/b2b/totp', request, headers)
91
+ end
92
+
93
+ # Authenticate a Member provided TOTP.
94
+ #
95
+ # == Parameters:
96
+ # organization_id::
97
+ # Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to perform operations on an Organization, so be sure to preserve this value.
98
+ # The type of this field is +String+.
99
+ # member_id::
100
+ # Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform operations on a Member, so be sure to preserve this value.
101
+ # The type of this field is +String+.
102
+ # code::
103
+ # The code to authenticate.
104
+ # The type of this field is +String+.
105
+ # intermediate_session_token::
106
+ # The Intermediate Session Token. This token does not necessarily belong to a specific instance of a Member, but represents a bag of factors that may be converted to a member session. The token can be used with the [OTP SMS Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-otp-sms), [TOTP Authenticate endpoint](https://stytch.com/docs/b2b/api/authenticate-totp), or [Recovery Codes Recover endpoint](https://stytch.com/docs/b2b/api/recovery-codes-recover) to complete an MFA flow and log in to the Organization. It can also be used with the [Exchange Intermediate Session endpoint](https://stytch.com/docs/b2b/api/exchange-intermediate-session) to join a specific Organization that allows the factors represented by the intermediate session token; or the [Create Organization via Discovery endpoint](https://stytch.com/docs/b2b/api/create-organization-via-discovery) to create a new Organization and Member.
107
+ # The type of this field is nilable +String+.
108
+ # session_token::
109
+ # A secret token for a given Stytch Session.
110
+ # The type of this field is nilable +String+.
111
+ # session_jwt::
112
+ # The JSON Web Token (JWT) for a given Stytch Session.
113
+ # The type of this field is nilable +String+.
114
+ # session_duration_minutes::
115
+ # Set the session lifetime to be this many minutes from now. This will start a new session if one doesn't already exist,
116
+ # returning both an opaque `session_token` and `session_jwt` for this session. Remember that the `session_jwt` will have a fixed lifetime of
117
+ # five minutes regardless of the underlying session duration, and will need to be refreshed over time.
118
+ #
119
+ # This value must be a minimum of 5 and a maximum of 527040 minutes (366 days).
120
+ #
121
+ # If a `session_token` or `session_jwt` is provided then a successful authentication will continue to extend the session this many minutes.
122
+ #
123
+ # If the `session_duration_minutes` parameter is not specified, a Stytch session will be created with a 60 minute duration. If you don't want
124
+ # to use the Stytch session product, you can ignore the session fields in the response.
125
+ # The type of this field is nilable +Integer+.
126
+ # session_custom_claims::
127
+ # Add a custom claims map to the Session being authenticated. Claims are only created if a Session is initialized by providing a value in
128
+ # `session_duration_minutes`. Claims will be included on the Session object and in the JWT. To update a key in an existing Session, supply a new value. To
129
+ # delete a key, supply a null value. Custom claims made with reserved claims (`iss`, `sub`, `aud`, `exp`, `nbf`, `iat`, `jti`) will be ignored.
130
+ # Total custom claims size cannot exceed four kilobytes.
131
+ # The type of this field is nilable +object+.
132
+ # set_mfa_enrollment::
133
+ # Optionally sets the Member’s MFA enrollment status upon a successful authentication. If the Organization’s MFA policy is `REQUIRED_FOR_ALL`, this field will be ignored. If this field is not passed in, the Member’s `mfa_enrolled` boolean will not be affected. The options are:
134
+ #
135
+ # `enroll` – sets the Member's `mfa_enrolled` boolean to `true`. The Member will be required to complete an MFA step upon subsequent logins to the Organization.
136
+ #
137
+ # `unenroll` – sets the Member's `mfa_enrolled` boolean to `false`. The Member will no longer be required to complete MFA steps when logging in to the Organization.
138
+ #
139
+ # The type of this field is nilable +String+.
140
+ # set_default_mfa::
141
+ # If passed will set the authenticated method to the default MFA method. Completing an MFA authentication flow for the first time for a Member will implicitly set the method to the default MFA method. This option can be used to update the default MFA method if multiple are being used.
142
+ # The type of this field is nilable +Boolean+.
143
+ #
144
+ # == Returns:
145
+ # An object with the following fields:
146
+ # request_id::
147
+ # Globally unique UUID that is returned with every API call. This value is important to log for debugging purposes; we may ask for this value to help identify a specific API call when helping you debug an issue.
148
+ # The type of this field is +String+.
149
+ # member_id::
150
+ # Globally unique UUID that identifies a specific Member.
151
+ # The type of this field is +String+.
152
+ # member::
153
+ # The [Member object](https://stytch.com/docs/b2b/api/member-object)
154
+ # The type of this field is +Member+ (+object+).
155
+ # organization::
156
+ # The [Organization object](https://stytch.com/docs/b2b/api/organization-object).
157
+ # The type of this field is +Organization+ (+object+).
158
+ # session_token::
159
+ # A secret token for a given Stytch Session.
160
+ # The type of this field is +String+.
161
+ # session_jwt::
162
+ # The JSON Web Token (JWT) for a given Stytch Session.
163
+ # The type of this field is +String+.
164
+ # status_code::
165
+ # The HTTP status code of the response. Stytch follows standard HTTP response status code patterns, e.g. 2XX values equate to success, 3XX values are redirects, 4XX are client errors, and 5XX are server errors.
166
+ # The type of this field is +Integer+.
167
+ # member_session::
168
+ # The [Session object](https://stytch.com/docs/b2b/api/session-object).
169
+ # The type of this field is nilable +MemberSession+ (+object+).
170
+ def authenticate(
171
+ organization_id:,
172
+ member_id:,
173
+ code:,
174
+ intermediate_session_token: nil,
175
+ session_token: nil,
176
+ session_jwt: nil,
177
+ session_duration_minutes: nil,
178
+ session_custom_claims: nil,
179
+ set_mfa_enrollment: nil,
180
+ set_default_mfa: nil
181
+ )
182
+ headers = {}
183
+ request = {
184
+ organization_id: organization_id,
185
+ member_id: member_id,
186
+ code: code
187
+ }
188
+ request[:intermediate_session_token] = intermediate_session_token unless intermediate_session_token.nil?
189
+ request[:session_token] = session_token unless session_token.nil?
190
+ request[:session_jwt] = session_jwt unless session_jwt.nil?
191
+ request[:session_duration_minutes] = session_duration_minutes unless session_duration_minutes.nil?
192
+ request[:session_custom_claims] = session_custom_claims unless session_custom_claims.nil?
193
+ request[:set_mfa_enrollment] = set_mfa_enrollment unless set_mfa_enrollment.nil?
194
+ request[:set_default_mfa] = set_default_mfa unless set_default_mfa.nil?
195
+
196
+ post_request('/v1/b2b/totp/authenticate', request, headers)
197
+ end
198
+
199
+ # Migrate an existing TOTP instance for a. Recovery codes are not required and will be minted for the Member if not provided.
200
+ #
201
+ # == Parameters:
202
+ # organization_id::
203
+ # Globally unique UUID that identifies a specific Organization. The `organization_id` is critical to perform operations on an Organization, so be sure to preserve this value.
204
+ # The type of this field is +String+.
205
+ # member_id::
206
+ # Globally unique UUID that identifies a specific Member. The `member_id` is critical to perform operations on a Member, so be sure to preserve this value.
207
+ # The type of this field is +String+.
208
+ # secret::
209
+ # The TOTP secret key shared between the authenticator app and the server used to generate TOTP codes.
210
+ # The type of this field is +String+.
211
+ # recovery_codes::
212
+ # An existing set of recovery codes to be imported into Stytch to be used to authenticate in place of the secondary MFA method.
213
+ # The type of this field is list of +String+.
214
+ #
215
+ # == Returns:
216
+ # An object with the following fields:
217
+ # request_id::
218
+ # Globally unique UUID that is returned with every API call. This value is important to log for debugging purposes; we may ask for this value to help identify a specific API call when helping you debug an issue.
219
+ # The type of this field is +String+.
220
+ # member_id::
221
+ # Globally unique UUID that identifies a specific Member.
222
+ # The type of this field is +String+.
223
+ # member::
224
+ # The [Member object](https://stytch.com/docs/b2b/api/member-object)
225
+ # The type of this field is +Member+ (+object+).
226
+ # organization::
227
+ # The [Organization object](https://stytch.com/docs/b2b/api/organization-object).
228
+ # The type of this field is +Organization+ (+object+).
229
+ # totp_registration_id::
230
+ # The unique ID for a TOTP instance.
231
+ # The type of this field is +String+.
232
+ # recovery_codes::
233
+ # An array of recovery codes that can be used to recover a Member's account.
234
+ # The type of this field is list of +String+.
235
+ # status_code::
236
+ # The HTTP status code of the response. Stytch follows standard HTTP response status code patterns, e.g. 2XX values equate to success, 3XX values are redirects, 4XX are client errors, and 5XX are server errors.
237
+ # The type of this field is +Integer+.
238
+ def migrate(
239
+ organization_id:,
240
+ member_id:,
241
+ secret:,
242
+ recovery_codes:
243
+ )
244
+ headers = {}
245
+ request = {
246
+ organization_id: organization_id,
247
+ member_id: member_id,
248
+ secret: secret,
249
+ recovery_codes: recovery_codes
250
+ }
251
+
252
+ post_request('/v1/b2b/totp/migrate', request, headers)
253
+ end
254
+ end
255
+ end
data/lib/stytch/client.rb CHANGED
@@ -6,6 +6,7 @@ require_relative 'magic_links'
6
6
  require_relative 'oauth'
7
7
  require_relative 'otps'
8
8
  require_relative 'passwords'
9
+ require_relative 'project'
9
10
  require_relative 'sessions'
10
11
  require_relative 'totps'
11
12
  require_relative 'users'
@@ -15,22 +16,24 @@ module Stytch
15
16
  class Client
16
17
  ENVIRONMENTS = %i[live test].freeze
17
18
 
18
- attr_reader :crypto_wallets, :m2m, :magic_links, :oauth, :otps, :passwords, :sessions, :totps, :users, :webauthn
19
+ attr_reader :crypto_wallets, :m2m, :magic_links, :oauth, :otps, :passwords, :project, :sessions, :totps, :users, :webauthn
19
20
 
20
21
  def initialize(project_id:, secret:, env: nil, &block)
21
22
  @api_host = api_host(env, project_id)
22
23
  @project_id = project_id
23
24
  @secret = secret
25
+ @is_b2b_client = false
24
26
 
25
27
  create_connection(&block)
26
28
 
27
29
  @crypto_wallets = Stytch::CryptoWallets.new(@connection)
28
- @m2m = Stytch::M2M.new(@connection, project_id)
30
+ @m2m = Stytch::M2M.new(@connection, @project_id, @is_b2b_client)
29
31
  @magic_links = Stytch::MagicLinks.new(@connection)
30
32
  @oauth = Stytch::OAuth.new(@connection)
31
33
  @otps = Stytch::OTPs.new(@connection)
32
34
  @passwords = Stytch::Passwords.new(@connection)
33
- @sessions = Stytch::Sessions.new(@connection, project_id)
35
+ @project = Stytch::Project.new(@connection)
36
+ @sessions = Stytch::Sessions.new(@connection, @project_id)
34
37
  @totps = Stytch::TOTPs.new(@connection)
35
38
  @users = Stytch::Users.new(@connection)
36
39
  @webauthn = Stytch::WebAuthn.new(@connection)
@@ -16,7 +16,12 @@ module Stytch
16
16
  @connection = connection
17
17
  end
18
18
 
19
- # Initiate the authentication of a crypto wallet. After calling this endpoint, the user will need to sign a message containing only the returned `challenge` field.
19
+ # Initiate the authentication of a crypto wallet. After calling this endpoint, the user will need to sign a message containing the returned `challenge` field.
20
+ #
21
+ # For Ethereum crypto wallets, you can optionally use the Sign In With Ethereum (SIWE) protocol for the message by passing in the `siwe_params`. The only required fields are `domain` and `uri`.
22
+ # If the crypto wallet detects that the domain in the message does not match the website's domain, it will display a warning to the user.
23
+ #
24
+ # If not using the SIWE protocol, the message will simply consist of the project name and a random string.
20
25
  #
21
26
  # == Parameters:
22
27
  # crypto_wallet_type::
@@ -34,6 +39,9 @@ module Stytch
34
39
  # session_jwt::
35
40
  # The `session_jwt` associated with a User's existing Session.
36
41
  # The type of this field is nilable +String+.
42
+ # siwe_params::
43
+ # The parameters for a Sign In With Ethereum (SIWE) message. May only be passed if the `crypto_wallet_type` is `ethereum`.
44
+ # The type of this field is nilable +SIWEParams+ (+object+).
37
45
  #
38
46
  # == Returns:
39
47
  # An object with the following fields:
@@ -57,8 +65,10 @@ module Stytch
57
65
  crypto_wallet_address:,
58
66
  user_id: nil,
59
67
  session_token: nil,
60
- session_jwt: nil
68
+ session_jwt: nil,
69
+ siwe_params: nil
61
70
  )
71
+ headers = {}
62
72
  request = {
63
73
  crypto_wallet_type: crypto_wallet_type,
64
74
  crypto_wallet_address: crypto_wallet_address
@@ -66,8 +76,9 @@ module Stytch
66
76
  request[:user_id] = user_id unless user_id.nil?
67
77
  request[:session_token] = session_token unless session_token.nil?
68
78
  request[:session_jwt] = session_jwt unless session_jwt.nil?
79
+ request[:siwe_params] = siwe_params unless siwe_params.nil?
69
80
 
70
- post_request('/v1/crypto_wallets/authenticate/start', request)
81
+ post_request('/v1/crypto_wallets/authenticate/start', request, headers)
71
82
  end
72
83
 
73
84
  # Complete the authentication of a crypto wallet by passing the signature.
@@ -131,6 +142,9 @@ module Stytch
131
142
  # See [GET sessions](https://stytch.com/docs/api/session-get) for complete response fields.
132
143
  #
133
144
  # The type of this field is nilable +Session+ (+object+).
145
+ # siwe_params::
146
+ # The parameters of the Sign In With Ethereum (SIWE) message that was signed.
147
+ # The type of this field is nilable +SIWEParamsResponse+ (+object+).
134
148
  def authenticate(
135
149
  crypto_wallet_type:,
136
150
  crypto_wallet_address:,
@@ -140,6 +154,7 @@ module Stytch
140
154
  session_jwt: nil,
141
155
  session_custom_claims: nil
142
156
  )
157
+ headers = {}
143
158
  request = {
144
159
  crypto_wallet_type: crypto_wallet_type,
145
160
  crypto_wallet_address: crypto_wallet_address,
@@ -150,7 +165,7 @@ module Stytch
150
165
  request[:session_jwt] = session_jwt unless session_jwt.nil?
151
166
  request[:session_custom_claims] = session_custom_claims unless session_custom_claims.nil?
152
167
 
153
- post_request('/v1/crypto_wallets/authenticate', request)
168
+ post_request('/v1/crypto_wallets/authenticate', request, headers)
154
169
  end
155
170
  end
156
171
  end
data/lib/stytch/errors.rb CHANGED
@@ -35,4 +35,25 @@ module Stytch
35
35
  super(msg)
36
36
  end
37
37
  end
38
+
39
+ class TenancyError < StandardError
40
+ def initialize(subject_org_id, request_org_id)
41
+ msg = "Subject organization_id #{subject_org_id} does not match authZ request organization_id #{request_org_id}"
42
+ super(msg)
43
+ end
44
+ end
45
+
46
+ class PermissionError < StandardError
47
+ def initialize(request)
48
+ msg = "Permission denied for request #{request}"
49
+ super(msg)
50
+ end
51
+ end
52
+
53
+ class M2MPermissionError < StandardError
54
+ def initialize(has_scopes, required_scopes)
55
+ msg = "Missing at least one required scope from #{required_scopes} for M2M request with scopes #{has_scopes}"
56
+ super(msg)
57
+ end
58
+ end
38
59
  end
data/lib/stytch/m2m.rb CHANGED
@@ -13,13 +13,13 @@ module Stytch
13
13
  include Stytch::RequestHelper
14
14
  attr_reader :clients
15
15
 
16
- def initialize(connection, project_id)
16
+ def initialize(connection, project_id, is_b2b_client)
17
17
  @connection = connection
18
18
 
19
19
  @clients = Stytch::M2M::Clients.new(@connection)
20
-
21
20
  @project_id = project_id
22
21
  @cache_last_update = 0
22
+ @is_b2b_client = is_b2b_client
23
23
  @jwks_loader = lambda do |options|
24
24
  @cached_keys = nil if options[:invalidate] && @cache_last_update < Time.now.to_i - 300
25
25
  @cached_keys ||= begin
@@ -38,9 +38,11 @@ module Stytch
38
38
  def get_jwks(
39
39
  project_id:
40
40
  )
41
+ headers = {}
41
42
  query_params = {}
42
- request = request_with_query_params("/v1/sessions/jwks/#{project_id}", query_params)
43
- get_request(request)
43
+ path = @is_b2b_client ? "/v1/b2b/sessions/jwks/#{project_id}" : "/v1/sessions/jwks/#{project_id}"
44
+ request = request_with_query_params(path, query_params)
45
+ get_request(request, headers)
44
46
  end
45
47
  # ENDMANUAL(M2M::get_jwks)
46
48
 
@@ -97,6 +99,13 @@ module Stytch
97
99
  # max_token_age::
98
100
  # The maximum possible lifetime in seconds for the token to be valid.
99
101
  # The type of this field is nilable +Integer+.
102
+ # scope_authorization_func::
103
+ # A function to check if the token has the required scopes. This defaults to a function that assumes
104
+ # scopes are either direct string matches or written in the form "action:resource". See the
105
+ # documentation for +perform_authorization_check+ for more information.
106
+ # clock_tolerance_seconds:
107
+ # The tolerance to use during verification of the nbf claim. This can help with clock drift issues.
108
+ # The type of this field is nilable +Integer+.
100
109
  # == Returns:
101
110
  # +nil+ if the token could not be validated, or an object with the following fields:
102
111
  # scopes::
@@ -108,9 +117,15 @@ module Stytch
108
117
  # custom_claims::
109
118
  # A map of custom claims present in the token.
110
119
  # The type of this field is +object+.
111
- def authenticate_token(access_token:, required_scopes: nil, max_token_age: nil)
120
+ def authenticate_token(
121
+ access_token:,
122
+ required_scopes: nil,
123
+ max_token_age: nil,
124
+ scope_authorization_func: method(:perform_authorization_check),
125
+ clock_tolerance_seconds: nil
126
+ )
112
127
  # Intentionally allow this to re-raise if authentication fails
113
- decoded_jwt = authenticate_token_local(access_token)
128
+ decoded_jwt = authenticate_token_local(access_token, clock_tolerance_seconds: clock_tolerance_seconds)
114
129
 
115
130
  iat_time = Time.at(decoded_jwt['iat']).to_datetime
116
131
 
@@ -120,20 +135,58 @@ module Stytch
120
135
  resp = marshal_jwt_into_response(decoded_jwt)
121
136
 
122
137
  unless required_scopes.nil?
123
- for scope in required_scopes
124
- raise TokenMissingScopeError, scope unless resp['scopes'].include?(scope)
125
- end
138
+ is_authorized = scope_authorization_func.call(
139
+ has_scopes: resp['scopes'],
140
+ required_scopes: required_scopes
141
+ )
142
+ raise M2MPermissionError.new(resp['scopes'], required_scopes) unless is_authorized
126
143
  end
127
144
 
128
145
  resp
129
146
  end
130
147
 
148
+ # Performs an authorization check against an M2M client and a set of required
149
+ # scopes. Returns true if the client has all the required scopes, false otherwise.
150
+ # A scope can match if the client has a wildcard resource or the specific resource.
151
+ # This function assumes that scopes are of the form "action:resource" or just
152
+ # "specific_scope". It is _also_ possible to represent scopes as "resource:action",
153
+ # but it is ultimately up to the developer to ensure consistency in the scopes format.
154
+ # Note that a scope of "*" will only match another literal "*" because wildcards are
155
+ # *not* supported in the prefix piece of a scope.
156
+ def perform_authorization_check(
157
+ has_scopes:,
158
+ required_scopes:
159
+ )
160
+ client_scopes = Hash.new { |hash, key| hash[key] = Set.new }
161
+ has_scopes.each do |scope|
162
+ action = scope
163
+ resource = '-'
164
+ action, resource = scope.split(':') if scope.include?(':')
165
+ client_scopes[action].add(resource)
166
+ end
167
+
168
+ required_scopes.each do |required_scope|
169
+ required_action = required_scope
170
+ required_resource = '-'
171
+ required_action, required_resource = required_scope.split(':') if required_scope.include?(':')
172
+ return false unless client_scopes.key?(required_action)
173
+
174
+ resources = client_scopes[required_action]
175
+ # The client can either have a wildcard resource or the specific resource
176
+ return false unless resources.include?('*') || resources.include?(required_resource)
177
+ end
178
+
179
+ true
180
+ end
181
+
131
182
  # Parse a M2M token and verify the signature locally (without calling /authenticate in the API)
132
- def authenticate_token_local(jwt)
183
+ # If clock_tolerance_seconds is not supplied 0 seconds will be used as the default.
184
+ def authenticate_token_local(jwt, clock_tolerance_seconds: nil)
185
+ clock_tolerance_seconds = 0 if clock_tolerance_seconds.nil?
133
186
  issuer = 'stytch.com/' + @project_id
134
187
  begin
135
188
  decoded_token = JWT.decode jwt, nil, true,
136
- { jwks: @jwks_loader, iss: issuer, verify_iss: true, aud: @project_id, verify_aud: true, algorithms: ['RS256'] }
189
+ { jwks: @jwks_loader, iss: issuer, verify_iss: true, aud: @project_id, verify_aud: true, algorithms: ['RS256'], nbf_leeway: clock_tolerance_seconds }
137
190
  decoded_token[0]
138
191
  rescue JWT::InvalidIssuerError
139
192
  raise JWTInvalidIssuerError
@@ -191,9 +244,10 @@ module Stytch
191
244
  def get(
192
245
  client_id:
193
246
  )
247
+ headers = {}
194
248
  query_params = {}
195
249
  request = request_with_query_params("/v1/m2m/clients/#{client_id}", query_params)
196
- get_request(request)
250
+ get_request(request, headers)
197
251
  end
198
252
 
199
253
  # Search for M2M Clients within your Stytch Project. Submit an empty `query` in the request to return all M2M Clients.
@@ -233,12 +287,13 @@ module Stytch
233
287
  limit: nil,
234
288
  query: nil
235
289
  )
290
+ headers = {}
236
291
  request = {}
237
292
  request[:cursor] = cursor unless cursor.nil?
238
293
  request[:limit] = limit unless limit.nil?
239
294
  request[:query] = query unless query.nil?
240
295
 
241
- post_request('/v1/m2m/clients/search', request)
296
+ post_request('/v1/m2m/clients/search', request, headers)
242
297
  end
243
298
 
244
299
  # Updates an existing M2M Client. You can use this endpoint to activate or deactivate a M2M Client by changing its `status`. A deactivated M2M Client will not be allowed to perform future token exchange flows until it is reactivated.
@@ -285,6 +340,7 @@ module Stytch
285
340
  scopes: nil,
286
341
  trusted_metadata: nil
287
342
  )
343
+ headers = {}
288
344
  request = {}
289
345
  request[:client_name] = client_name unless client_name.nil?
290
346
  request[:client_description] = client_description unless client_description.nil?
@@ -292,7 +348,7 @@ module Stytch
292
348
  request[:scopes] = scopes unless scopes.nil?
293
349
  request[:trusted_metadata] = trusted_metadata unless trusted_metadata.nil?
294
350
 
295
- put_request("/v1/m2m/clients/#{client_id}", request)
351
+ put_request("/v1/m2m/clients/#{client_id}", request, headers)
296
352
  end
297
353
 
298
354
  # Deletes the M2M Client.
@@ -319,7 +375,8 @@ module Stytch
319
375
  def delete(
320
376
  client_id:
321
377
  )
322
- delete_request("/v1/m2m/clients/#{client_id}")
378
+ headers = {}
379
+ delete_request("/v1/m2m/clients/#{client_id}", headers)
323
380
  end
324
381
 
325
382
  # Creates a new M2M Client. On initial client creation, you may pass in a custom `client_id` or `client_secret` to import an existing M2M client. If you do not pass in a custom `client_id` or `client_secret`, one will be generated automatically. The `client_id` must be unique among all clients in your project.
@@ -365,6 +422,7 @@ module Stytch
365
422
  client_description: nil,
366
423
  trusted_metadata: nil
367
424
  )
425
+ headers = {}
368
426
  request = {
369
427
  scopes: scopes
370
428
  }
@@ -374,7 +432,7 @@ module Stytch
374
432
  request[:client_description] = client_description unless client_description.nil?
375
433
  request[:trusted_metadata] = trusted_metadata unless trusted_metadata.nil?
376
434
 
377
- post_request('/v1/m2m/clients', request)
435
+ post_request('/v1/m2m/clients', request, headers)
378
436
  end
379
437
 
380
438
  class Secrets
@@ -408,9 +466,10 @@ module Stytch
408
466
  def rotate_start(
409
467
  client_id:
410
468
  )
469
+ headers = {}
411
470
  request = {}
412
471
 
413
- post_request("/v1/m2m/clients/#{client_id}/secrets/rotate/start", request)
472
+ post_request("/v1/m2m/clients/#{client_id}/secrets/rotate/start", request, headers)
414
473
  end
415
474
 
416
475
  # Cancel the rotation of an M2M client secret started with the [Start Secret Rotation Endpoint](https://stytch.com/docs/b2b/api/m2m-rotate-secret-start) [Start Secret Rotation Endpoint](https://stytch.com/docs/api/m2m-rotate-secret-start).
@@ -435,9 +494,10 @@ module Stytch
435
494
  def rotate_cancel(
436
495
  client_id:
437
496
  )
497
+ headers = {}
438
498
  request = {}
439
499
 
440
- post_request("/v1/m2m/clients/#{client_id}/secrets/rotate/cancel", request)
500
+ post_request("/v1/m2m/clients/#{client_id}/secrets/rotate/cancel", request, headers)
441
501
  end
442
502
 
443
503
  # Complete the rotation of an M2M client secret started with the [Start Secret Rotation Endpoint](https://stytch.com/docs/b2b/api/m2m-rotate-secret-start) [Start Secret Rotation Endpoint](https://stytch.com/docs/api/m2m-rotate-secret-start).
@@ -462,9 +522,10 @@ module Stytch
462
522
  def rotate(
463
523
  client_id:
464
524
  )
525
+ headers = {}
465
526
  request = {}
466
527
 
467
- post_request("/v1/m2m/clients/#{client_id}/secrets/rotate", request)
528
+ post_request("/v1/m2m/clients/#{client_id}/secrets/rotate", request, headers)
468
529
  end
469
530
  end
470
531
  end