foxlogin 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 53bf2d7b6a126b1e22d72b26de7eb8f0f287004e2c6f08e0d76ad6ca04c85160
4
+ data.tar.gz: 0bd038635a386ed66aaa1e49652235b1436530062b16d4e7ac77dd47ce58b896
5
+ SHA512:
6
+ metadata.gz: 2ef13f65636f3dbdadac9569b701e28b0828c593e693a031328ba5372d096ec85f89116f1e2a414c38c4c5d195e1445b422edacc93749a808f6d85a853e80a42
7
+ data.tar.gz: c5026e873739e9326a1c7c19a70b86345728c090607b4b254a1998716ffc3707a9088de6aac50e195b4513c4f39f39bf0bd05ba10617c37fc5703d18e211be10
data/CHANGELOG.md ADDED
@@ -0,0 +1,29 @@
1
+ # Changelog
2
+
3
+ ## 0.3.1 — 2026-12-02
4
+
5
+ - `FoxLogin::Admin` accepts per-application secret keys (`sk_live_…`) as well as organization
6
+ API keys (`fk_live_…`). Other keys raise `FoxLogin::Error` with code `invalid_api_key`. New
7
+ `secret_key:` keyword, same as `api_key:`.
8
+ - Fix: `FoxLogin::Error#message` returns the plain message. It used to recurse through `#to_s`
9
+ and raise `SystemStackError`.
10
+
11
+ ## 0.3.0 — 2026-12-02
12
+
13
+ - **Breaking:** `#sign_in`, `#verify_sign_up`, `#sign_in_with_code` and
14
+ `#confirm_password_reset` now return `{"status" => "signed_in", "user" => user}` or
15
+ `{"status" => "mfa_required", "mfa_token" => token}` instead of a user hash directly.
16
+ - Two-factor authentication: on `mfa_required` nothing is stored; call
17
+ `#verify_mfa(mfa_token:, code:)` (`POST /v1/client/sign_in/mfa`) to finish the sign-in and
18
+ store the session.
19
+ - Passwordless sign-in: `#send_sign_in_code(email:)` and `#sign_in_with_code(email:, code:)`.
20
+ - Password reset: `#start_password_reset(email:)` and
21
+ `#confirm_password_reset(email:, code:, password:)`.
22
+
23
+ ## 0.1.0 — 2026-12-02
24
+
25
+ - First release: `FoxLogin::Client` (`Mutex`-based single-flight refresh) — sign-up with email
26
+ code, sign-in, rotating sessions, `#get_token`, `#on_change`.
27
+ - `FoxLogin.verify_token` — EdDSA (Ed25519) only via the `jwt` + `jwt-eddsa` + `ed25519` gems,
28
+ JWKS cache, injectable keys.
29
+ - `FoxLogin::Admin` — `applications` and `users` management API.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 METANETSOFT
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,125 @@
1
+ # foxlogin
2
+
3
+ Official Ruby SDK for [Fox Login](https://foxlogin.app): hosted login where each user's data
4
+ is stored in their own region (EU or Türkiye).
5
+
6
+ ```sh
7
+ gem install foxlogin
8
+ # or, in a Gemfile:
9
+ gem "foxlogin"
10
+ ```
11
+
12
+ Ruby 3.0+. Uses `net/http` (stdlib) with an injectable transport, and the `jwt` + `jwt-eddsa` +
13
+ `ed25519` gems for EdDSA token verification.
14
+
15
+ ## Client: sign users in
16
+
17
+ ```ruby
18
+ require "foxlogin"
19
+
20
+ # The region comes from the key: pk_live_tr_... talks to tr.auth.foxlogin.app.
21
+ fox = FoxLogin::Client.new(publishable_key: "pk_live_tr_...")
22
+
23
+ fox.sign_up(email: email, password: password, country: "TR", name: name) # always "verification_sent"
24
+ fox.verify_sign_up(email: email, code: code) # 6-digit code from the email
25
+
26
+ result = fox.sign_in(email: email, password: password)
27
+ user = if result["status"] == "mfa_required"
28
+ code = gets.chomp
29
+ fox.verify_mfa(mfa_token: result["mfa_token"], code: code)
30
+ else
31
+ result["user"]
32
+ end
33
+
34
+ fox.on_change { |state| puts state[:status] }
35
+
36
+ # Send this to your backend; it refreshes itself before it expires.
37
+ token = fox.get_token
38
+
39
+ fox.sign_out
40
+ ```
41
+
42
+ Passwordless sign-in and password reset return the same `{"status" => "signed_in" | "mfa_required"}`
43
+ shape:
44
+
45
+ ```ruby
46
+ fox.send_sign_in_code(email: email) # always "code_sent"
47
+ result = fox.sign_in_with_code(email: email, code: code)
48
+
49
+ fox.start_password_reset(email: email) # always "code_sent"
50
+ result = fox.confirm_password_reset(email: email, code: code, password: new_password)
51
+ ```
52
+
53
+ Sessions live in memory by default (`FoxLogin::MemoryStorage`). Pass `storage:` with your own
54
+ object implementing `#get(key)`, `#set(key, value)` and `#remove(key)` to persist them.
55
+
56
+ `FoxLogin::Client` is thread-safe: concurrent `#get_token` calls from multiple threads share a
57
+ single in-flight refresh (`Mutex` + `ConditionVariable`), since refresh tokens rotate and two
58
+ parallel refreshes would otherwise end the session.
59
+
60
+ ## Server: check tokens and manage users
61
+
62
+ ```ruby
63
+ claims = FoxLogin.verify_token(bearer_token, application_id: "app_...")
64
+ # claims["sub"] = user id, claims["rgn"] = "TR", claims["labels"] = {"store" => "..."}
65
+
66
+ # A secret key (sk_live_...) belongs to one application. Copy it from the application's API keys tab.
67
+ admin = FoxLogin::Admin.new(secret_key: ENV.fetch("FOXLOGIN_SECRET_KEY"))
68
+ user = admin.users.create("app_...", email: "mehmet@anka.com.tr", country: "TR")
69
+ ```
70
+
71
+ A secret key works only inside its own application, within the role you gave it (Full access,
72
+ Read and write users, Read only). For work across applications, such as creating a new
73
+ application, use an organization API key (`fk_live_...`, page "API keys" in the dashboard).
74
+ `api_key:` and `secret_key:` are the same option.
75
+
76
+ ```ruby
77
+ org = FoxLogin::Admin.new(api_key: ENV.fetch("FOXLOGIN_API_KEY"))
78
+ app = org.applications.create(name: "Anka Market", region: "TR")
79
+ ```
80
+
81
+ Keep both keys on your server. Never ship them to a browser or app.
82
+
83
+ `FoxLogin.verify_token` accepts only EdDSA (Ed25519) tokens issued by
84
+ `https://api.foxlogin.app`, caches the public keys for an hour and refetches them once when it
85
+ sees a new key id. Pass `keys:` to verify offline against a fixed JWKS document (useful in
86
+ tests).
87
+
88
+ ### Rack middleware
89
+
90
+ ```ruby
91
+ class FoxLoginAuth
92
+ def initialize(app)
93
+ @app = app
94
+ end
95
+
96
+ def call(env)
97
+ header = env["HTTP_AUTHORIZATION"].to_s
98
+ if header.start_with?("Bearer ")
99
+ begin
100
+ env["foxlogin.claims"] = FoxLogin.verify_token(header.sub("Bearer ", ""))
101
+ rescue FoxLogin::Error => e
102
+ return [401, { "content-type" => "application/json" }, [{ error: e.code }.to_json]]
103
+ end
104
+ end
105
+ @app.call(env)
106
+ end
107
+ end
108
+
109
+ use FoxLoginAuth
110
+ ```
111
+
112
+ ## Errors
113
+
114
+ Every failure raises `FoxLogin::Error` with `status`, `code` (`invalid_credentials`,
115
+ `invalid_code`, `rate_limited`, `email_exists`, `country_not_allowed`, `invalid_token`,
116
+ `wrong_application`, ...), `message`, `retryable` and `retry_after` (seconds).
117
+
118
+ ## Other languages
119
+
120
+ JavaScript/TypeScript, Python, Go, PHP, Java, .NET, Rust, Swift, Kotlin and Dart SDKs follow
121
+ the same contract: see [SDK-SPEC.md](../SDK-SPEC.md).
122
+
123
+ ## License
124
+
125
+ MIT © METANETSOFT
@@ -0,0 +1,105 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "uri"
4
+
5
+ module FoxLogin
6
+ # Management API client for your backend.
7
+ #
8
+ # Pass a secret key (+sk_live_…+) for one application, or an organization API key
9
+ # (+fk_live_…+) for all applications. +secret_key:+ and +api_key:+ are the same option;
10
+ # +secret_key:+ wins when both are given. Creating applications needs an organization key.
11
+ #
12
+ # fox = FoxLogin::Admin.new(secret_key: ENV.fetch("FOXLOGIN_SECRET_KEY"))
13
+ # user = fox.users.create("app_...", email: "mehmet@anka.com.tr", country: "TR")
14
+ #
15
+ # org = FoxLogin::Admin.new(api_key: ENV.fetch("FOXLOGIN_API_KEY")) # fk_live_...
16
+ # app = org.applications.create(name: "Anka Market", region: "TR")
17
+ class Admin
18
+ attr_reader :applications, :users
19
+
20
+ # @raise [FoxLogin::Error] code +invalid_api_key+ when the key starts with neither +sk_+ nor +fk_+
21
+ def initialize(api_key: nil, secret_key: nil, base_url: nil, transport: nil)
22
+ key = secret_key.nil? ? api_key : secret_key
23
+ unless key.to_s.start_with?("sk_", "fk_")
24
+ raise FoxLogin::Error.new(
25
+ status: 0,
26
+ code: "invalid_api_key",
27
+ message: "Use a secret key (sk_live_…) or an organization API key (fk_live_…)."
28
+ )
29
+ end
30
+
31
+ @key = key
32
+ @base = (base_url || ISSUER).sub(%r{/\z}, "")
33
+ @transport = transport || NetHttpTransport.new
34
+ @applications = Applications.new(self)
35
+ @users = Users.new(self)
36
+ end
37
+
38
+ # @api private
39
+ def call(method, path, body = Http::NO_BODY)
40
+ Http.request(
41
+ @transport,
42
+ method,
43
+ "#{@base}/v1#{path}",
44
+ headers: { "authorization" => "Bearer #{@key}" },
45
+ json_body: body
46
+ )
47
+ end
48
+
49
+ class Applications
50
+ def initialize(admin)
51
+ @admin = admin
52
+ end
53
+
54
+ def create(name:, region:, sector: nil, user_countries: nil, country_restriction: nil)
55
+ @admin.call(
56
+ "POST",
57
+ "/applications",
58
+ {
59
+ name: name,
60
+ region: region,
61
+ sector: sector,
62
+ user_countries: user_countries || [],
63
+ country_restriction: country_restriction
64
+ }
65
+ )
66
+ end
67
+
68
+ def list
69
+ @admin.call("GET", "/applications")
70
+ end
71
+
72
+ def get(app_id)
73
+ @admin.call("GET", "/applications/#{URI.encode_www_form_component(app_id)}")
74
+ end
75
+ end
76
+
77
+ class Users
78
+ def initialize(admin)
79
+ @admin = admin
80
+ end
81
+
82
+ def create(app_id, email:, country:, name: nil, labels: nil, password: nil, email_verified: false)
83
+ @admin.call(
84
+ "POST",
85
+ "/applications/#{URI.encode_www_form_component(app_id)}/users",
86
+ {
87
+ email: email,
88
+ country: country,
89
+ name: name,
90
+ labels: labels || {},
91
+ password: password,
92
+ email_verified: email_verified
93
+ }
94
+ )
95
+ end
96
+
97
+ def get(app_id, user_id)
98
+ @admin.call(
99
+ "GET",
100
+ "/applications/#{URI.encode_www_form_component(app_id)}/users/#{URI.encode_www_form_component(user_id)}"
101
+ )
102
+ end
103
+ end
104
+ end
105
+ end
@@ -0,0 +1,261 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+
6
+ module FoxLogin
7
+ # End-user client: sign-up, sign-in, sessions. One instance per
8
+ # application.
9
+ #
10
+ # fox = FoxLogin::Client.new(publishable_key: "pk_live_eu_...")
11
+ # fox.sign_up(email: email, password: password, country: "TR")
12
+ # fox.verify_sign_up(email: email, code: code)
13
+ # token = fox.get_token # send to your backend as "Bearer <token>"
14
+ class Client
15
+ Stored = Struct.new(:user, :refresh_token, :access_token, :expires_at)
16
+
17
+ attr_reader :base_url
18
+
19
+ def initialize(publishable_key:, base_url: nil, storage: nil, transport: nil)
20
+ @key = publishable_key
21
+ @base_url = (base_url || "https://#{FoxLogin.region_from_publishable_key(publishable_key)}.auth.foxlogin.app")
22
+ .sub(%r{/\z}, "")
23
+ @storage = storage || MemoryStorage.new
24
+ @transport = transport || NetHttpTransport.new
25
+ @storage_key = "foxlogin:#{publishable_key[0, 24]}"
26
+
27
+ @mutex = Mutex.new
28
+ @refresh_cv = ConditionVariable.new
29
+ @refreshing = false
30
+ @refresh_result = nil
31
+ @refresh_error = nil
32
+ @listeners = []
33
+ @session = nil
34
+
35
+ raw = @storage.get(@storage_key)
36
+ if raw
37
+ begin
38
+ @session = load_session(raw)
39
+ rescue StandardError
40
+ @storage.remove(@storage_key)
41
+ end
42
+ end
43
+ end
44
+
45
+ # {status: :signed_in, user: user} or {status: :signed_out}.
46
+ def state
47
+ session = @mutex.synchronize { @session }
48
+ session ? { status: :signed_in, user: session.user } : { status: :signed_out }
49
+ end
50
+
51
+ # The signed-in user, or nil.
52
+ def user
53
+ @mutex.synchronize { @session&.user }
54
+ end
55
+
56
+ # Called on sign-in, refresh and sign-out. Returns the listener, which
57
+ # can be passed to #off_change.
58
+ def on_change(listener = nil, &block)
59
+ listener ||= block
60
+ @mutex.synchronize { @listeners << listener }
61
+ listener
62
+ end
63
+
64
+ def off_change(listener)
65
+ @mutex.synchronize { @listeners.delete(listener) }
66
+ end
67
+
68
+ # Always resolves to {"status" => "verification_sent"}, even when the
69
+ # address already has an account.
70
+ def sign_up(email:, password:, country:, name: nil)
71
+ body = { email: email, password: password, country: country }
72
+ body[:name] = name if name
73
+ post("/v1/client/sign_up", body)
74
+ end
75
+
76
+ def verify_sign_up(email:, code:)
77
+ complete_sign_in("/v1/client/sign_up/verify", { email: email, code: code })
78
+ end
79
+
80
+ def sign_in(email:, password:)
81
+ complete_sign_in("/v1/client/sign_in", { email: email, password: password })
82
+ end
83
+
84
+ # Second step when a sign-in-shaped call returned mfa_required: a TOTP
85
+ # or recovery code. Stores the session.
86
+ def verify_mfa(mfa_token:, code:)
87
+ session = post("/v1/client/sign_in/mfa", { mfa_token: mfa_token, code: code })
88
+ save(session["user"], session)
89
+ session["user"]
90
+ end
91
+
92
+ # Emails a sign-in code. Always resolves to {"status" => "code_sent"}.
93
+ def send_sign_in_code(email:)
94
+ post("/v1/client/sign_in/email_code", { email: email })
95
+ end
96
+
97
+ # Signs in with the emailed code (passwordless).
98
+ def sign_in_with_code(email:, code:)
99
+ complete_sign_in("/v1/client/sign_in/email_code/verify", { email: email, code: code })
100
+ end
101
+
102
+ # Emails a password reset code. Always resolves to {"status" => "code_sent"}.
103
+ def start_password_reset(email:)
104
+ post("/v1/client/password_reset", { email: email })
105
+ end
106
+
107
+ # Sets the new password with the emailed code, ends all other sessions
108
+ # and signs in.
109
+ def confirm_password_reset(email:, code:, password:)
110
+ complete_sign_in("/v1/client/password_reset/confirm", { email: email, code: code, password: password })
111
+ end
112
+
113
+ # A valid access token, refreshed first when it expires within 60
114
+ # seconds; nil when signed out. Concurrent calls share one refresh
115
+ # (refresh tokens rotate, so two parallel refreshes would end the
116
+ # session).
117
+ def get_token
118
+ session = @mutex.synchronize { @session }
119
+ return nil unless session
120
+ return session.access_token if session.expires_at - Time.now.to_f > 60
121
+
122
+ refresh
123
+ end
124
+
125
+ # Forces a refresh. Signs out on an invalid refresh token. Only one
126
+ # refresh runs at a time; other callers block and share its result.
127
+ def refresh
128
+ owner = false
129
+ @mutex.synchronize do
130
+ if @refreshing
131
+ @refresh_cv.wait(@mutex) while @refreshing
132
+ else
133
+ @refreshing = true
134
+ owner = true
135
+ end
136
+ end
137
+
138
+ unless owner
139
+ error, result = @mutex.synchronize { [@refresh_error, @refresh_result] }
140
+ raise error if error
141
+
142
+ return result
143
+ end
144
+
145
+ begin
146
+ result = do_refresh
147
+ @mutex.synchronize do
148
+ @refresh_result = result
149
+ @refresh_error = nil
150
+ end
151
+ result
152
+ rescue StandardError => e
153
+ @mutex.synchronize do
154
+ @refresh_error = e
155
+ @refresh_result = nil
156
+ end
157
+ raise
158
+ ensure
159
+ @mutex.synchronize do
160
+ @refreshing = false
161
+ @refresh_cv.broadcast
162
+ end
163
+ end
164
+ end
165
+
166
+ # Ends the session on the server and locally.
167
+ def sign_out
168
+ session = @mutex.synchronize { @session }
169
+ clear
170
+ return unless session
171
+
172
+ begin
173
+ post("/v1/client/sign_out", { refresh_token: session.refresh_token })
174
+ rescue FoxLogin::Error
175
+ # already signed out locally; the server session expires on its own
176
+ end
177
+ end
178
+
179
+ private
180
+
181
+ # Posts a sign-in-shaped request and returns either
182
+ # {"status" => "signed_in", "user" => user} (and stores the session) or
183
+ # {"status" => "mfa_required", "mfa_token" => token} (stores nothing).
184
+ def complete_sign_in(path, body)
185
+ result = post(path, body)
186
+ return { "status" => "mfa_required", "mfa_token" => result["mfa_token"] } if result["status"] == "mfa_required"
187
+
188
+ save(result["user"], result)
189
+ { "status" => "signed_in", "user" => result["user"] }
190
+ end
191
+
192
+ def do_refresh
193
+ session = @mutex.synchronize { @session }
194
+ return nil unless session
195
+
196
+ begin
197
+ pair = post("/v1/client/token", { refresh_token: session.refresh_token })
198
+ rescue FoxLogin::Error => e
199
+ if e.status == 401
200
+ clear
201
+ return nil
202
+ end
203
+ raise
204
+ end
205
+ save(session.user, pair)
206
+ pair["access_token"]
207
+ end
208
+
209
+ def post(path, body)
210
+ Http.request(
211
+ @transport,
212
+ "POST",
213
+ "#{@base_url}#{path}",
214
+ headers: { "x-fox-publishable-key" => @key },
215
+ json_body: body
216
+ )
217
+ end
218
+
219
+ def save(user, token_pair)
220
+ session = Stored.new(
221
+ user,
222
+ token_pair["refresh_token"],
223
+ token_pair["access_token"],
224
+ Time.now.to_f + token_pair["expires_in"]
225
+ )
226
+ @mutex.synchronize { @session = session }
227
+ @storage.set(@storage_key, dump_session(session))
228
+ emit
229
+ end
230
+
231
+ def clear
232
+ had = @mutex.synchronize do
233
+ existed = !@session.nil?
234
+ @session = nil
235
+ existed
236
+ end
237
+ @storage.remove(@storage_key)
238
+ emit if had
239
+ end
240
+
241
+ def emit
242
+ current = state
243
+ listeners = @mutex.synchronize { @listeners.dup }
244
+ listeners.each { |listener| listener.call(current) }
245
+ end
246
+
247
+ def dump_session(session)
248
+ JSON.generate(
249
+ "user" => session.user,
250
+ "refresh_token" => session.refresh_token,
251
+ "access_token" => session.access_token,
252
+ "expires_at" => session.expires_at
253
+ )
254
+ end
255
+
256
+ def load_session(raw)
257
+ data = JSON.parse(raw)
258
+ Stored.new(data["user"], data["refresh_token"], data["access_token"], data["expires_at"])
259
+ end
260
+ end
261
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FoxLogin
4
+ ISSUER = "https://api.foxlogin.app"
5
+ DEFAULT_JWKS_URL = "#{ISSUER}/.well-known/jwks.json"
6
+ ALGORITHMS = ["EdDSA"].freeze
7
+ end
@@ -0,0 +1,27 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FoxLogin
4
+ # Raised by every failing SDK call.
5
+ #
6
+ # +code+ is stable and meant for programs; +message+ is for people.
7
+ class Error < StandardError
8
+ attr_reader :status, :code, :message, :retryable, :retry_after, :region, :details
9
+
10
+ def initialize(status:, code:, message:, retryable: false, retry_after: nil, region: nil, details: nil)
11
+ super(message)
12
+ # Kept separately so #message returns the plain text; Exception#message would call #to_s,
13
+ # and #to_s below calls #message.
14
+ @message = message
15
+ @status = status
16
+ @code = code
17
+ @retryable = retryable
18
+ @retry_after = retry_after
19
+ @region = region
20
+ @details = details || {}
21
+ end
22
+
23
+ def to_s
24
+ "#{code} (status #{status}): #{message}"
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "json"
5
+ require "uri"
6
+
7
+ module FoxLogin
8
+ # A transport only needs to respond to #call(method, url, headers:, body:)
9
+ # and return a FoxLogin::HttpResponse (or anything with #status, #header
10
+ # and #body). Inject your own in tests instead of making real requests.
11
+ class HttpResponse
12
+ attr_reader :status, :body
13
+
14
+ def initialize(status:, headers: {}, body: nil)
15
+ @status = status
16
+ @headers = headers.each_with_object({}) { |(k, v), h| h[k.to_s.downcase] = v }
17
+ @body = body
18
+ end
19
+
20
+ def header(name)
21
+ @headers[name.to_s.downcase]
22
+ end
23
+ end
24
+
25
+ # Default transport: plain Net::HTTP, one connection per call.
26
+ class NetHttpTransport
27
+ def initialize(open_timeout: 10, read_timeout: 30)
28
+ @open_timeout = open_timeout
29
+ @read_timeout = read_timeout
30
+ end
31
+
32
+ def call(method, url, headers: {}, body: nil)
33
+ uri = URI.parse(url)
34
+ http = Net::HTTP.new(uri.host, uri.port)
35
+ http.use_ssl = uri.scheme == "https"
36
+ http.open_timeout = @open_timeout
37
+ http.read_timeout = @read_timeout
38
+
39
+ request_class = Net::HTTP.const_get(method.to_s.capitalize)
40
+ request = request_class.new(uri)
41
+ headers.each { |k, v| request[k] = v }
42
+ request.body = body if body
43
+
44
+ response = http.request(request)
45
+ HttpResponse.new(status: response.code.to_i, headers: response.each_header.to_h, body: response.body)
46
+ end
47
+ end
48
+
49
+ # JSON request helpers shared by the client and admin client. Not part of
50
+ # the public API.
51
+ module Http
52
+ NO_BODY = :__foxlogin_no_body__
53
+
54
+ class << self
55
+ def request(transport, method, url, headers:, json_body: NO_BODY)
56
+ send_headers = { "accept" => "application/json" }.merge(headers)
57
+ body = nil
58
+ if json_body != NO_BODY
59
+ send_headers["content-type"] = "application/json"
60
+ body = JSON.generate(json_body)
61
+ end
62
+
63
+ response = perform(transport, method, url, send_headers, body)
64
+ raise_for_error(response)
65
+ parse_json(response)
66
+ end
67
+
68
+ def raise_for_error(response)
69
+ return if response.status >= 200 && response.status < 300
70
+
71
+ error = parse_error_body(response)
72
+ raise FoxLogin::Error.new(
73
+ status: response.status,
74
+ code: error["code"].is_a?(String) ? error["code"] : "http_error",
75
+ message: error["message"].is_a?(String) ? error["message"] : "HTTP #{response.status}",
76
+ retryable: !!error["retryable"] || response.status == 429 || response.status >= 500,
77
+ retry_after: retry_after(response),
78
+ region: error["region"].is_a?(String) ? error["region"] : nil,
79
+ details: error["details"].is_a?(Hash) ? error["details"] : {}
80
+ )
81
+ end
82
+
83
+ def parse_json(response)
84
+ return nil if response.status == 204 || response.body.nil? || response.body.empty?
85
+
86
+ JSON.parse(response.body)
87
+ rescue JSON::ParserError
88
+ nil
89
+ end
90
+
91
+ private
92
+
93
+ def perform(transport, method, url, headers, body)
94
+ transport.call(method, url, headers: headers, body: body)
95
+ rescue FoxLogin::Error
96
+ raise
97
+ rescue StandardError => e
98
+ raise FoxLogin::Error.new(
99
+ status: 0,
100
+ code: "network_error",
101
+ message: "Could not reach Fox Login: #{e.message}",
102
+ retryable: true
103
+ )
104
+ end
105
+
106
+ def parse_error_body(response)
107
+ body = parse_json(response)
108
+ body.is_a?(Hash) && body["error"].is_a?(Hash) ? body["error"] : {}
109
+ end
110
+
111
+ def retry_after(response)
112
+ value = response.header("retry-after")
113
+ return nil if value.nil?
114
+
115
+ Float(value)
116
+ rescue ArgumentError, TypeError
117
+ nil
118
+ end
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "jwt"
4
+ require "jwt/eddsa"
5
+ require "ed25519"
6
+
7
+ module FoxLogin
8
+ # Caches JWKS verify keys per URL for an hour; refetches once on an
9
+ # unknown kid.
10
+ class JwksCache
11
+ DEFAULT_TTL = 3600 # seconds
12
+
13
+ def initialize(ttl: DEFAULT_TTL)
14
+ @ttl = ttl
15
+ @mutex = Mutex.new
16
+ @entries = {}
17
+ end
18
+
19
+ def key_for(url, kid, transport)
20
+ now = monotonic_now
21
+ entry = @mutex.synchronize { @entries[url] }
22
+ if entry && (now - entry[:fetched_at] < @ttl)
23
+ found = pick(entry[:keys], kid)
24
+ return found if found
25
+ end
26
+
27
+ # No cache, expired, or unknown kid: (re)fetch once.
28
+ keys = fetch(url, transport)
29
+ @mutex.synchronize { @entries[url] = { keys: keys, fetched_at: now } }
30
+ found = pick(keys, kid)
31
+ return found if found
32
+
33
+ raise FoxLogin::Error.new(
34
+ status: 401,
35
+ code: "invalid_token",
36
+ message: "No signing key for kid=#{kid.inspect}."
37
+ )
38
+ end
39
+
40
+ private
41
+
42
+ def pick(keys, kid)
43
+ return keys[kid] if kid
44
+
45
+ keys.size == 1 ? keys.values.first : nil
46
+ end
47
+
48
+ def fetch(url, transport)
49
+ response = transport.call("GET", url, headers: { "accept" => "application/json" }, body: nil)
50
+ Http.raise_for_error(response)
51
+ data = Http.parse_json(response) || {}
52
+ keys = {}
53
+ Array(data["keys"]).each do |raw|
54
+ next unless raw.is_a?(Hash)
55
+
56
+ kid = raw["kid"] || raw[:kid]
57
+ next unless kid
58
+
59
+ begin
60
+ keys[kid.to_s] = JWT::EdDSA::JWK::OKP.new(raw).verify_key
61
+ rescue StandardError
62
+ next
63
+ end
64
+ end
65
+ keys
66
+ rescue FoxLogin::Error
67
+ raise
68
+ rescue StandardError => e
69
+ raise FoxLogin::Error.new(
70
+ status: 0,
71
+ code: "network_error",
72
+ message: "Could not fetch JWKS: #{e.message}",
73
+ retryable: true
74
+ )
75
+ end
76
+
77
+ def monotonic_now
78
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,20 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FoxLogin
4
+ REGION_PATTERN = /\Apk_(?:live|test)_([a-z]{2})_/.freeze
5
+
6
+ class << self
7
+ # "pk_live_eu_..." -> "eu".
8
+ def region_from_publishable_key(key)
9
+ match = REGION_PATTERN.match(key.to_s)
10
+ unless match
11
+ raise FoxLogin::Error.new(
12
+ status: 0,
13
+ code: "invalid_publishable_key",
14
+ message: "The publishable key must look like pk_live_<region>_..."
15
+ )
16
+ end
17
+ match[1]
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "jwt"
4
+ require "jwt/eddsa"
5
+ require "ed25519"
6
+
7
+ module FoxLogin
8
+ @jwks_cache = JwksCache.new
9
+ @default_transport = NetHttpTransport.new
10
+
11
+ class << self
12
+ # Verifies a session token on your backend without calling Fox Login
13
+ # for every request.
14
+ #
15
+ # EdDSA (Ed25519) only; rejects +alg: none+, +HS256+, +RS256+ and
16
+ # anything else. Checks issuer and expiry (60 second leeway) and,
17
+ # optionally, that the token belongs to +application_id+.
18
+ #
19
+ # Pass +keys:+ (a JWKS document Hash, or a Hash of kid to an
20
+ # Ed25519::VerifyKey / JWK Hash) to verify offline in tests instead of
21
+ # fetching +jwks_url:+.
22
+ #
23
+ # Returns the claims Hash, or raises FoxLogin::Error with code
24
+ # +invalid_token+ or +wrong_application+.
25
+ def verify_token(token, jwks_url: nil, application_id: nil, keys: nil, transport: nil)
26
+ header = JWT.decode(token, nil, false).last
27
+
28
+ unless ALGORITHMS.include?(header["alg"])
29
+ raise FoxLogin::Error.new(
30
+ status: 401,
31
+ code: "invalid_token",
32
+ message: "Unsupported algorithm: #{header["alg"].inspect}"
33
+ )
34
+ end
35
+
36
+ verify_key =
37
+ if keys
38
+ key_for_injected(keys, header["kid"])
39
+ else
40
+ url = jwks_url || DEFAULT_JWKS_URL
41
+ @jwks_cache.key_for(url, header["kid"], transport || @default_transport)
42
+ end
43
+
44
+ claims = JWT.decode(
45
+ token,
46
+ verify_key,
47
+ true,
48
+ algorithm: "EdDSA",
49
+ iss: ISSUER,
50
+ verify_iss: true,
51
+ exp_leeway: 60,
52
+ required_claims: %w[exp iss]
53
+ ).first
54
+
55
+ if application_id && claims["app"] != application_id
56
+ raise FoxLogin::Error.new(
57
+ status: 401,
58
+ code: "wrong_application",
59
+ message: "The token belongs to another application."
60
+ )
61
+ end
62
+
63
+ claims
64
+ rescue FoxLogin::Error
65
+ raise
66
+ rescue JWT::DecodeError, ArgumentError, TypeError => e
67
+ raise FoxLogin::Error.new(status: 401, code: "invalid_token", message: e.message)
68
+ end
69
+
70
+ private
71
+
72
+ def key_for_injected(keys, kid)
73
+ normalized = normalize_keys(keys)
74
+ found = kid ? normalized[kid.to_s] : nil
75
+ found ||= normalized.values.first if normalized.size == 1
76
+ unless found
77
+ raise FoxLogin::Error.new(status: 401, code: "invalid_token", message: "No signing key for this token.")
78
+ end
79
+
80
+ found
81
+ end
82
+
83
+ def normalize_keys(keys)
84
+ list = keys.is_a?(Hash) && keys["keys"].is_a?(Array) ? keys["keys"] : nil
85
+ if list
86
+ list.each_with_object({}) do |raw, out|
87
+ kid = raw.is_a?(Hash) ? (raw["kid"] || raw[:kid]) : nil
88
+ out[kid.to_s] = to_verify_key(raw) if kid
89
+ end
90
+ elsif keys.is_a?(Hash)
91
+ keys.each_with_object({}) { |(kid, raw), out| out[kid.to_s] = to_verify_key(raw) }
92
+ else
93
+ raise TypeError, "keys must be a JWKS document ({'keys' => [...]}) or a Hash of kid to key"
94
+ end
95
+ end
96
+
97
+ def to_verify_key(raw)
98
+ return raw if raw.is_a?(Ed25519::VerifyKey)
99
+
100
+ JWT::EdDSA::JWK::OKP.new(raw).verify_key
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FoxLogin
4
+ # Where the session (refresh token and user) is kept between process runs.
5
+ # Any object implementing #get(key), #set(key, value) and #remove(key)
6
+ # works -- there is no base class to inherit from.
7
+ #
8
+ # Keeps the session in memory only: gone when the process exits. The safe
9
+ # default -- nothing is written to disk.
10
+ class MemoryStorage
11
+ def initialize
12
+ @mutex = Mutex.new
13
+ @data = {}
14
+ end
15
+
16
+ def get(key)
17
+ @mutex.synchronize { @data[key] }
18
+ end
19
+
20
+ def set(key, value)
21
+ @mutex.synchronize { @data[key] = value }
22
+ end
23
+
24
+ def remove(key)
25
+ @mutex.synchronize { @data.delete(key) }
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module FoxLogin
4
+ VERSION = "0.3.1"
5
+ end
data/lib/foxlogin.rb ADDED
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Fox Login SDK: hosted login where each user's data is stored in their own
4
+ # region (EU or Türkiye).
5
+ #
6
+ # require "foxlogin"
7
+ #
8
+ # fox = FoxLogin::Client.new(publishable_key: "pk_live_tr_...")
9
+ # fox.sign_up(email: email, password: password, country: "TR")
10
+ module FoxLogin
11
+ end
12
+
13
+ require_relative "foxlogin/version"
14
+ require_relative "foxlogin/constants"
15
+ require_relative "foxlogin/errors"
16
+ require_relative "foxlogin/region"
17
+ require_relative "foxlogin/http"
18
+ require_relative "foxlogin/storage"
19
+ require_relative "foxlogin/jwks_cache"
20
+ require_relative "foxlogin/server"
21
+ require_relative "foxlogin/client"
22
+ require_relative "foxlogin/admin"
metadata ADDED
@@ -0,0 +1,139 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: foxlogin
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.3.1
5
+ platform: ruby
6
+ authors:
7
+ - METANETSOFT
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-12-02 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: jwt
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '3.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '3.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: jwt-eddsa
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '1.1'
34
+ - - "<"
35
+ - !ruby/object:Gem::Version
36
+ version: '3.0'
37
+ type: :runtime
38
+ prerelease: false
39
+ version_requirements: !ruby/object:Gem::Requirement
40
+ requirements:
41
+ - - ">="
42
+ - !ruby/object:Gem::Version
43
+ version: '1.1'
44
+ - - "<"
45
+ - !ruby/object:Gem::Version
46
+ version: '3.0'
47
+ - !ruby/object:Gem::Dependency
48
+ name: ed25519
49
+ requirement: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '1.3'
54
+ type: :runtime
55
+ prerelease: false
56
+ version_requirements: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - "~>"
59
+ - !ruby/object:Gem::Version
60
+ version: '1.3'
61
+ - !ruby/object:Gem::Dependency
62
+ name: rake
63
+ requirement: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - "~>"
66
+ - !ruby/object:Gem::Version
67
+ version: '13.0'
68
+ type: :development
69
+ prerelease: false
70
+ version_requirements: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - "~>"
73
+ - !ruby/object:Gem::Version
74
+ version: '13.0'
75
+ - !ruby/object:Gem::Dependency
76
+ name: minitest
77
+ requirement: !ruby/object:Gem::Requirement
78
+ requirements:
79
+ - - "~>"
80
+ - !ruby/object:Gem::Version
81
+ version: '5.0'
82
+ type: :development
83
+ prerelease: false
84
+ version_requirements: !ruby/object:Gem::Requirement
85
+ requirements:
86
+ - - "~>"
87
+ - !ruby/object:Gem::Version
88
+ version: '5.0'
89
+ description: 'Fox Login SDK: sign-up, sign-in, sessions, token verification and the
90
+ Management API. User data stays in its own region (EU, TR).'
91
+ email:
92
+ executables: []
93
+ extensions: []
94
+ extra_rdoc_files: []
95
+ files:
96
+ - CHANGELOG.md
97
+ - LICENSE
98
+ - README.md
99
+ - lib/foxlogin.rb
100
+ - lib/foxlogin/admin.rb
101
+ - lib/foxlogin/client.rb
102
+ - lib/foxlogin/constants.rb
103
+ - lib/foxlogin/errors.rb
104
+ - lib/foxlogin/http.rb
105
+ - lib/foxlogin/jwks_cache.rb
106
+ - lib/foxlogin/region.rb
107
+ - lib/foxlogin/server.rb
108
+ - lib/foxlogin/storage.rb
109
+ - lib/foxlogin/version.rb
110
+ homepage: https://foxlogin.app
111
+ licenses:
112
+ - MIT
113
+ metadata:
114
+ homepage_uri: https://foxlogin.app
115
+ source_code_uri: https://github.com/METANETSOFT/foxlogin-ruby
116
+ bug_tracker_uri: https://github.com/METANETSOFT/foxlogin-ruby/issues
117
+ changelog_uri: https://github.com/METANETSOFT/foxlogin-ruby/blob/main/CHANGELOG.md
118
+ rubygems_mfa_required: 'true'
119
+ post_install_message:
120
+ rdoc_options: []
121
+ require_paths:
122
+ - lib
123
+ required_ruby_version: !ruby/object:Gem::Requirement
124
+ requirements:
125
+ - - ">="
126
+ - !ruby/object:Gem::Version
127
+ version: '3.0'
128
+ required_rubygems_version: !ruby/object:Gem::Requirement
129
+ requirements:
130
+ - - ">="
131
+ - !ruby/object:Gem::Version
132
+ version: '0'
133
+ requirements: []
134
+ rubygems_version: 3.5.22
135
+ signing_key:
136
+ specification_version: 4
137
+ summary: 'Fox Login SDK: sign-up, sign-in, sessions, token verification and the Management
138
+ API. User data stays in its own region (EU, TR).'
139
+ test_files: []