logi_auth 1.0.0
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 +7 -0
- data/LICENSE +80 -0
- data/NOTICE +4 -0
- data/README.md +80 -0
- data/lib/logi_auth/errors.rb +33 -0
- data/lib/logi_auth/id_token_verifier.rb +147 -0
- data/lib/logi_auth/server.rb +202 -0
- data/lib/logi_auth/version.rb +5 -0
- data/lib/logi_auth.rb +14 -0
- metadata +66 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 0c3ae64ef8bf56e00d3edeef71184c59da5ce8ff9a8d4df3aae11c1556f222ba
|
|
4
|
+
data.tar.gz: 8838cb06f5305d4b1e231d52c8aeeed10fec22a9658370c2d98af878b7d7aaa8
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: afd06609d41ff98473b53a913174c7a2e2101428a03892f6d41f39dc598b0a73ecbd987cb2eb33ecd2cf951283dcc2947f08484c824834a21f158f681b95be6c
|
|
7
|
+
data.tar.gz: f587f3dd60e2dcbcb23a67e3eaa0d7a383521c07c90af24b49c346b222f4c47e2980949b0f52068a994158b32972e5cd99af8e55592d7cb15cc720bb55002820
|
data/LICENSE
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
|
|
5
|
+
http://www.apache.org/licenses/
|
|
6
|
+
|
|
7
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
8
|
+
|
|
9
|
+
1. Definitions.
|
|
10
|
+
|
|
11
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
16
|
+
|
|
17
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
18
|
+
|
|
19
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
20
|
+
|
|
21
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
22
|
+
|
|
23
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
24
|
+
|
|
25
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
26
|
+
|
|
27
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
28
|
+
|
|
29
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
30
|
+
|
|
31
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
32
|
+
|
|
33
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
34
|
+
|
|
35
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
36
|
+
|
|
37
|
+
You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
38
|
+
|
|
39
|
+
You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
40
|
+
|
|
41
|
+
You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
42
|
+
|
|
43
|
+
If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
56
|
+
|
|
57
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
58
|
+
|
|
59
|
+
To apply the Apache License to your work, attach the following
|
|
60
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
61
|
+
replaced with your own identifying information. (Don't include
|
|
62
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
63
|
+
comment syntax for the file format. We also recommend that a
|
|
64
|
+
file or class name and description of purpose be included on the
|
|
65
|
+
same "printed page" as the copyright notice for easier
|
|
66
|
+
identification within third-party archives.
|
|
67
|
+
|
|
68
|
+
Copyright 2026 Dcode
|
|
69
|
+
|
|
70
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
71
|
+
you may not use this file except in compliance with the License.
|
|
72
|
+
You may obtain a copy of the License at
|
|
73
|
+
|
|
74
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
75
|
+
|
|
76
|
+
Unless required by applicable law or agreed to in writing, software
|
|
77
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
78
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
79
|
+
See the License for the specific language governing permissions and
|
|
80
|
+
limitations under the License.
|
data/NOTICE
ADDED
data/README.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# logi_auth (Ruby)
|
|
2
|
+
|
|
3
|
+
Server-side **"Sign in with logi"** for Ruby / Rails backends — confidential
|
|
4
|
+
OAuth 2.0 Authorization Code exchange + **id_token (RS256) verification**. Zero
|
|
5
|
+
gem dependencies (stdlib `OpenSSL` + `net/http` + `json`).
|
|
6
|
+
|
|
7
|
+
This is the **confidential / backend** counterpart to the public-client SDKs
|
|
8
|
+
(browser, iOS, Android, Flutter). If your RP has a backend, verify on the
|
|
9
|
+
server with this gem — do **not** rely on a client-side check.
|
|
10
|
+
|
|
11
|
+
> **Why it matters:** a backend that skips the id_token `aud` check can be
|
|
12
|
+
> tricked into accepting a token minted for a *different* client (cross-client
|
|
13
|
+
> account takeover — the launchcrew/krx incident). `exchange_code_and_verify`
|
|
14
|
+
> always verifies signature + iss + aud + exp + nonce before returning `sub`.
|
|
15
|
+
|
|
16
|
+
## Supported versions
|
|
17
|
+
|
|
18
|
+
| Requirement | Version |
|
|
19
|
+
|-------------|---------|
|
|
20
|
+
| **Ruby** | **>= 3.0** (stdlib OpenSSL/JSON/net-http; no external gems) |
|
|
21
|
+
| **Rails** | any (**>= 6.1** tested pattern) — the gem is framework-agnostic; use it from any controller |
|
|
22
|
+
| Sinatra / Rack | any |
|
|
23
|
+
|
|
24
|
+
## Install
|
|
25
|
+
|
|
26
|
+
```ruby
|
|
27
|
+
# Gemfile
|
|
28
|
+
gem "logi_auth"
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Rails controller example
|
|
32
|
+
|
|
33
|
+
```ruby
|
|
34
|
+
# config/initializers/logi_auth.rb
|
|
35
|
+
LOGI = LogiAuth::Server.new(
|
|
36
|
+
client_id: ENV.fetch("LOGI_CLIENT_ID"),
|
|
37
|
+
client_secret: ENV.fetch("LOGI_CLIENT_SECRET"), # confidential client
|
|
38
|
+
redirect_uri: "https://app.example.com/auth/logi/callback"
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
# app/controllers/logi_auth_controller.rb
|
|
42
|
+
class LogiAuthController < ApplicationController
|
|
43
|
+
def start
|
|
44
|
+
state = SecureRandom.hex(16)
|
|
45
|
+
nonce = SecureRandom.hex(16)
|
|
46
|
+
session[:logi_state] = state
|
|
47
|
+
session[:logi_nonce] = nonce
|
|
48
|
+
redirect_to LOGI.authorization_url(state: state, nonce: nonce), allow_other_host: true
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def callback
|
|
52
|
+
return head(:bad_request) unless params[:state] == session.delete(:logi_state)
|
|
53
|
+
|
|
54
|
+
result = LOGI.exchange_code_and_verify(
|
|
55
|
+
code: params[:code],
|
|
56
|
+
nonce: session.delete(:logi_nonce)
|
|
57
|
+
)
|
|
58
|
+
# result.sub is the verified pairwise subject — key your User record on it.
|
|
59
|
+
user = User.find_or_create_by!(logi_sub: result.sub) { |u| u.email = result.email }
|
|
60
|
+
session[:user_id] = user.id
|
|
61
|
+
redirect_to root_path
|
|
62
|
+
rescue LogiAuth::ServerError => e
|
|
63
|
+
redirect_to login_path, alert: "로그인 실패 (#{e.code})"
|
|
64
|
+
end
|
|
65
|
+
end
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Public client (PKCE, no secret)
|
|
69
|
+
|
|
70
|
+
Omit `client_secret` and pass a `code_challenge` / `code_verifier`:
|
|
71
|
+
|
|
72
|
+
```ruby
|
|
73
|
+
logi = LogiAuth::Server.new(client_id:, redirect_uri:) # no secret
|
|
74
|
+
url = logi.authorization_url(state:, nonce:, code_challenge:)
|
|
75
|
+
result = logi.exchange_code_and_verify(code:, nonce:, code_verifier:)
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## License
|
|
79
|
+
|
|
80
|
+
Apache-2.0
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module LogiAuth
|
|
4
|
+
# Base for all errors raised by this gem.
|
|
5
|
+
class Error < StandardError; end
|
|
6
|
+
|
|
7
|
+
# id_token verification failure. #code mirrors the Web verifier and the
|
|
8
|
+
# golden-vector strings exactly (e.g. "bad_signature", "aud_mismatch").
|
|
9
|
+
class IdTokenError < Error
|
|
10
|
+
CODES = %w[
|
|
11
|
+
malformed missing_kid unknown_kid bad_signature
|
|
12
|
+
iss_mismatch aud_mismatch expired nonce_mismatch missing_claim
|
|
13
|
+
].freeze
|
|
14
|
+
|
|
15
|
+
attr_reader :code
|
|
16
|
+
|
|
17
|
+
def initialize(code)
|
|
18
|
+
@code = code
|
|
19
|
+
super("id_token verification failed: #{code}")
|
|
20
|
+
end
|
|
21
|
+
end
|
|
22
|
+
|
|
23
|
+
# Raised by Server for OAuth / transport failures.
|
|
24
|
+
class ServerError < Error
|
|
25
|
+
attr_reader :code, :detail
|
|
26
|
+
|
|
27
|
+
def initialize(code, message, detail: nil)
|
|
28
|
+
@code = code
|
|
29
|
+
@detail = detail
|
|
30
|
+
super(message)
|
|
31
|
+
end
|
|
32
|
+
end
|
|
33
|
+
end
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "openssl"
|
|
4
|
+
require "json"
|
|
5
|
+
require "base64"
|
|
6
|
+
|
|
7
|
+
require_relative "errors"
|
|
8
|
+
|
|
9
|
+
module LogiAuth
|
|
10
|
+
# RS256 id_token verification — stdlib OpenSSL only (zero gem dependencies).
|
|
11
|
+
# Mirrors the server (server/app/lib/oauth/jwt_verifier.rb) and the other
|
|
12
|
+
# SDKs: kid -> JWKS -> RS256 signature -> iss / aud / exp / iat / nonce / sub.
|
|
13
|
+
# Passes the shared 4-SDK golden vectors (../../test-vectors).
|
|
14
|
+
#
|
|
15
|
+
# Why not a JWT gem: iOS(Security.framework)/Web(WebCrypto)/Java(java.security)
|
|
16
|
+
# each use their platform crypto primitive; Ruby's is stdlib OpenSSL. The JWS
|
|
17
|
+
# parsing + claim checks are implemented here (mirroring verify.ts).
|
|
18
|
+
#
|
|
19
|
+
# Note: this is the public-client-neutral verification core. A confidential
|
|
20
|
+
# Rails RP should call Server#exchange_code_and_verify, which uses this.
|
|
21
|
+
module IdTokenVerifier
|
|
22
|
+
Result = Struct.new(:sub, :claims, keyword_init: true)
|
|
23
|
+
|
|
24
|
+
module_function
|
|
25
|
+
|
|
26
|
+
# Verify +id_token+ and return a Result. Raises IdTokenError on any failure.
|
|
27
|
+
# Claim order: signature -> iss -> aud -> exp -> iat -> nonce -> sub.
|
|
28
|
+
#
|
|
29
|
+
# jwks: Hash with "keys" => [ {"kty","n","e","kid",...}, ... ]
|
|
30
|
+
# expected: { issuer:, client_id:, nonce: } (nonce optional)
|
|
31
|
+
# now: Unix seconds; defaults to Time.now. Injectable for tests.
|
|
32
|
+
def verify(id_token, jwks:, expected:, now: nil, clock_skew_sec: 60)
|
|
33
|
+
now ||= Time.now.to_i
|
|
34
|
+
|
|
35
|
+
parts = id_token.split(".")
|
|
36
|
+
raise IdTokenError, "malformed" unless parts.length == 3 && parts.none? { |p| p.nil? || p.empty? }
|
|
37
|
+
|
|
38
|
+
header = decode_json_segment(parts[0])
|
|
39
|
+
payload = decode_json_segment(parts[1])
|
|
40
|
+
raise IdTokenError, "malformed" if header.nil? || payload.nil?
|
|
41
|
+
|
|
42
|
+
# Only RS256 is accepted — never verify a token whose header declares
|
|
43
|
+
# another (or no) algorithm, even if the RSA signature happens to match.
|
|
44
|
+
raise IdTokenError, "bad_signature" unless header["alg"] == "RS256"
|
|
45
|
+
|
|
46
|
+
kid = header["kid"]
|
|
47
|
+
raise IdTokenError, "missing_kid" unless kid.is_a?(String) && !kid.empty?
|
|
48
|
+
|
|
49
|
+
jwk = Array(jwks["keys"]).find { |k| k["kid"] == kid }
|
|
50
|
+
raise IdTokenError, "unknown_kid" if jwk.nil?
|
|
51
|
+
|
|
52
|
+
signature = base64url_decode(parts[2])
|
|
53
|
+
unless signature && verify_rs256("#{parts[0]}.#{parts[1]}", signature, jwk)
|
|
54
|
+
raise IdTokenError, "bad_signature"
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
raise IdTokenError, "iss_mismatch" unless payload["iss"] == expected[:issuer]
|
|
58
|
+
|
|
59
|
+
aud = payload["aud"]
|
|
60
|
+
raise IdTokenError, "aud_mismatch" unless audience_matches?(aud, expected[:client_id])
|
|
61
|
+
# OIDC §3.1.3.7: with multiple audiences an `azp` MUST be present; whenever
|
|
62
|
+
# `azp` is present it MUST equal our client_id. Guards against accepting a
|
|
63
|
+
# token issued to another authorized party that merely also lists us.
|
|
64
|
+
azp = payload["azp"]
|
|
65
|
+
if aud.is_a?(Array) && aud.length > 1
|
|
66
|
+
raise IdTokenError, "aud_mismatch" unless azp == expected[:client_id]
|
|
67
|
+
elsif !azp.nil?
|
|
68
|
+
raise IdTokenError, "aud_mismatch" unless azp == expected[:client_id]
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
exp = numeric_claim(payload["exp"])
|
|
72
|
+
raise IdTokenError, "expired" if exp.nil? || exp <= now - clock_skew_sec
|
|
73
|
+
|
|
74
|
+
iat = numeric_claim(payload["iat"])
|
|
75
|
+
# iat missing or in the future -> malformed (mirrors the other verifiers).
|
|
76
|
+
raise IdTokenError, "malformed" if iat.nil? || iat > now + clock_skew_sec
|
|
77
|
+
|
|
78
|
+
if expected[:nonce] && payload["nonce"] != expected[:nonce]
|
|
79
|
+
raise IdTokenError, "nonce_mismatch"
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
sub = payload["sub"]
|
|
83
|
+
raise IdTokenError, "missing_claim" unless sub.is_a?(String) && !sub.empty?
|
|
84
|
+
|
|
85
|
+
Result.new(sub: sub, claims: payload)
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
def verify_rs256(signing_input, signature, jwk)
|
|
89
|
+
key = rsa_public_key(jwk)
|
|
90
|
+
return false unless key
|
|
91
|
+
|
|
92
|
+
key.verify(OpenSSL::Digest::SHA256.new, signature, signing_input)
|
|
93
|
+
rescue OpenSSL::PKey::PKeyError, OpenSSL::OpenSSLError
|
|
94
|
+
false
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
# Build an RSA public key from a JWK (n, e) via a SubjectPublicKeyInfo DER.
|
|
98
|
+
def rsa_public_key(jwk)
|
|
99
|
+
n_bytes = base64url_decode(jwk["n"])
|
|
100
|
+
e_bytes = base64url_decode(jwk["e"])
|
|
101
|
+
return nil unless n_bytes && e_bytes
|
|
102
|
+
|
|
103
|
+
n = OpenSSL::BN.new(n_bytes, 2) # 2 = unsigned big-endian
|
|
104
|
+
e = OpenSSL::BN.new(e_bytes, 2)
|
|
105
|
+
pkcs1 = OpenSSL::ASN1::Sequence([OpenSSL::ASN1::Integer(n), OpenSSL::ASN1::Integer(e)])
|
|
106
|
+
algo = OpenSSL::ASN1::Sequence([
|
|
107
|
+
OpenSSL::ASN1::ObjectId("rsaEncryption"),
|
|
108
|
+
OpenSSL::ASN1::Null.new(nil)
|
|
109
|
+
])
|
|
110
|
+
spki = OpenSSL::ASN1::Sequence([algo, OpenSSL::ASN1::BitString.new(pkcs1.to_der)])
|
|
111
|
+
OpenSSL::PKey::RSA.new(spki.to_der)
|
|
112
|
+
rescue OpenSSL::OpenSSLError, ArgumentError
|
|
113
|
+
nil
|
|
114
|
+
end
|
|
115
|
+
|
|
116
|
+
def decode_json_segment(segment)
|
|
117
|
+
bytes = base64url_decode(segment)
|
|
118
|
+
return nil unless bytes
|
|
119
|
+
|
|
120
|
+
parsed = JSON.parse(bytes)
|
|
121
|
+
parsed.is_a?(Hash) ? parsed : nil
|
|
122
|
+
rescue JSON::ParserError
|
|
123
|
+
nil
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def audience_matches?(aud, client_id)
|
|
127
|
+
case aud
|
|
128
|
+
when String then aud == client_id
|
|
129
|
+
when Array then aud.include?(client_id)
|
|
130
|
+
else false
|
|
131
|
+
end
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
def numeric_claim(value)
|
|
135
|
+
value.is_a?(Numeric) ? value.to_i : nil
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
def base64url_decode(str)
|
|
139
|
+
return nil unless str.is_a?(String)
|
|
140
|
+
|
|
141
|
+
pad = (4 - (str.length % 4)) % 4
|
|
142
|
+
Base64.urlsafe_decode64(str + ("=" * pad))
|
|
143
|
+
rescue ArgumentError
|
|
144
|
+
nil
|
|
145
|
+
end
|
|
146
|
+
end
|
|
147
|
+
end
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require "net/http"
|
|
4
|
+
require "uri"
|
|
5
|
+
require "json"
|
|
6
|
+
|
|
7
|
+
require_relative "errors"
|
|
8
|
+
require_relative "id_token_verifier"
|
|
9
|
+
|
|
10
|
+
module LogiAuth
|
|
11
|
+
# Server-side "Sign in with logi" for Ruby/Rails backends. Confidential-client
|
|
12
|
+
# OAuth 2.0 code exchange + id_token (RS256) verification.
|
|
13
|
+
#
|
|
14
|
+
# Why this exists: a backend RP that skips the id_token +aud+ check can be
|
|
15
|
+
# tricked into accepting a token minted for a DIFFERENT client (cross-client
|
|
16
|
+
# account takeover). #exchange_code_and_verify ALWAYS verifies
|
|
17
|
+
# signature + iss + aud + exp + nonce before returning +sub+.
|
|
18
|
+
class Server
|
|
19
|
+
Session = Struct.new(
|
|
20
|
+
:sub, :email, :id_token, :access_token,
|
|
21
|
+
:refresh_token, :expires_at, :scope, :claims,
|
|
22
|
+
keyword_init: true
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
attr_reader :client_id, :redirect_uri, :issuer, :token_issuer, :default_scopes
|
|
26
|
+
|
|
27
|
+
def initialize(client_id:, redirect_uri:, client_secret: nil,
|
|
28
|
+
issuer: "https://api.1pass.dev", token_issuer: "https://api.1pass.dev",
|
|
29
|
+
scopes: %w[openid profile:basic email], jwks_cache_ttl: 3600)
|
|
30
|
+
raise ArgumentError, "client_id is required" if client_id.nil? || client_id.empty?
|
|
31
|
+
raise ArgumentError, "redirect_uri is required" if redirect_uri.nil? || redirect_uri.empty?
|
|
32
|
+
|
|
33
|
+
@client_id = client_id
|
|
34
|
+
@redirect_uri = redirect_uri
|
|
35
|
+
@client_secret = client_secret
|
|
36
|
+
@issuer = issuer.sub(%r{/+\z}, "")
|
|
37
|
+
@token_issuer = token_issuer
|
|
38
|
+
@default_scopes = scopes
|
|
39
|
+
@jwks_cache_ttl = jwks_cache_ttl
|
|
40
|
+
@jwks_cache = nil
|
|
41
|
+
@jwks_fetched_at = 0
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# Build the /oauth/authorize URL to redirect the browser to.
|
|
45
|
+
def authorization_url(state:, nonce:, scopes: nil, code_challenge: nil, prompt: nil)
|
|
46
|
+
params = {
|
|
47
|
+
"response_type" => "code",
|
|
48
|
+
"client_id" => @client_id,
|
|
49
|
+
"redirect_uri" => @redirect_uri,
|
|
50
|
+
"scope" => (scopes || @default_scopes).join(" "),
|
|
51
|
+
"state" => state,
|
|
52
|
+
"nonce" => nonce
|
|
53
|
+
}
|
|
54
|
+
if code_challenge
|
|
55
|
+
params["code_challenge"] = code_challenge
|
|
56
|
+
params["code_challenge_method"] = "S256"
|
|
57
|
+
end
|
|
58
|
+
params["prompt"] = prompt if prompt
|
|
59
|
+
"#{@issuer}/oauth/authorize?#{URI.encode_www_form(params)}"
|
|
60
|
+
end
|
|
61
|
+
|
|
62
|
+
# Exchange the authorization code and verify the id_token. Returns a
|
|
63
|
+
# verified Session (sub set only after signature + iss + aud + exp + nonce
|
|
64
|
+
# all pass). Raises ServerError on any failure.
|
|
65
|
+
def exchange_code_and_verify(code:, nonce:, code_verifier: nil)
|
|
66
|
+
# The server flow ALWAYS generated a nonce in authorization_url, so a
|
|
67
|
+
# nil/empty nonce here (e.g. an expired session) is a bug — never proceed
|
|
68
|
+
# with the nonce check silently disabled. (codex P1.)
|
|
69
|
+
if nonce.nil? || nonce.to_s.empty?
|
|
70
|
+
raise ServerError.new("invalid_nonce",
|
|
71
|
+
"nonce is required — the sign-in session may have expired")
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
form = {
|
|
75
|
+
"grant_type" => "authorization_code",
|
|
76
|
+
"code" => code,
|
|
77
|
+
"redirect_uri" => @redirect_uri,
|
|
78
|
+
"client_id" => @client_id
|
|
79
|
+
}
|
|
80
|
+
form["client_secret"] = @client_secret if @client_secret
|
|
81
|
+
form["code_verifier"] = code_verifier if code_verifier
|
|
82
|
+
|
|
83
|
+
resp = http_post("#{@issuer}/oauth/token", form)
|
|
84
|
+
unless success?(resp)
|
|
85
|
+
raise ServerError.new("token_exchange_failed", "Token exchange failed (HTTP #{resp.code})",
|
|
86
|
+
detail: truncate(resp.body))
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
tokens = parse_token_body(resp.body)
|
|
90
|
+
id_token = tokens["id_token"]
|
|
91
|
+
unless id_token.is_a?(String) && !id_token.empty?
|
|
92
|
+
raise ServerError.new("missing_id_token", "Token response had no id_token — was `openid` in the scopes?")
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
verified = verify_with_rotation_retry(id_token, nonce)
|
|
96
|
+
email = verified.claims["email"]
|
|
97
|
+
expires_in = tokens["expires_in"]
|
|
98
|
+
|
|
99
|
+
Session.new(
|
|
100
|
+
sub: verified.sub,
|
|
101
|
+
email: email.is_a?(String) ? email : nil,
|
|
102
|
+
id_token: id_token,
|
|
103
|
+
access_token: tokens["access_token"],
|
|
104
|
+
refresh_token: tokens["refresh_token"],
|
|
105
|
+
expires_at: expires_in.is_a?(Numeric) ? Time.now.to_i + expires_in.to_i : nil,
|
|
106
|
+
scope: tokens["scope"],
|
|
107
|
+
claims: verified.claims
|
|
108
|
+
)
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
private
|
|
112
|
+
|
|
113
|
+
def verify_with_rotation_retry(id_token, nonce)
|
|
114
|
+
expected = { issuer: @token_issuer, client_id: @client_id, nonce: nonce }
|
|
115
|
+
jwks, from_cache = fetch_jwks(force: false)
|
|
116
|
+
begin
|
|
117
|
+
IdTokenVerifier.verify(id_token, jwks: jwks, expected: expected)
|
|
118
|
+
rescue IdTokenError => e
|
|
119
|
+
# Key rotation within the cache TTL — bust + refetch once.
|
|
120
|
+
if e.code == "unknown_kid" && from_cache
|
|
121
|
+
fresh, = fetch_jwks(force: true)
|
|
122
|
+
begin
|
|
123
|
+
IdTokenVerifier.verify(id_token, jwks: fresh, expected: expected)
|
|
124
|
+
rescue IdTokenError => retry_err
|
|
125
|
+
raise as_id_token_invalid(retry_err)
|
|
126
|
+
end
|
|
127
|
+
else
|
|
128
|
+
raise as_id_token_invalid(e)
|
|
129
|
+
end
|
|
130
|
+
end
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
def as_id_token_invalid(err)
|
|
134
|
+
ServerError.new("id_token_invalid", "id_token verification failed (#{err.code})", detail: err.code)
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def fetch_jwks(force:)
|
|
138
|
+
if !force && @jwks_cache && (Time.now.to_i - @jwks_fetched_at) < @jwks_cache_ttl
|
|
139
|
+
return [@jwks_cache, true]
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
resp = http_get("#{@issuer}/.well-known/jwks.json")
|
|
143
|
+
raise ServerError.new("jwks_fetch_failed", "JWKS fetch failed (HTTP #{resp.code})") unless success?(resp)
|
|
144
|
+
|
|
145
|
+
jwks = begin
|
|
146
|
+
parsed = JSON.parse(resp.body)
|
|
147
|
+
raise "missing keys" unless parsed.is_a?(Hash) && parsed["keys"].is_a?(Array)
|
|
148
|
+
|
|
149
|
+
parsed
|
|
150
|
+
rescue JSON::ParserError, RuntimeError => e
|
|
151
|
+
raise ServerError.new("jwks_fetch_failed", "JWKS response was malformed", detail: e.message)
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
@jwks_cache = jwks
|
|
155
|
+
@jwks_fetched_at = Time.now.to_i
|
|
156
|
+
[jwks, false]
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def parse_token_body(body)
|
|
160
|
+
tokens = JSON.parse(body)
|
|
161
|
+
unless tokens.is_a?(Hash) && tokens["access_token"].is_a?(String)
|
|
162
|
+
raise ServerError.new("token_exchange_failed", "Token response was missing access_token")
|
|
163
|
+
end
|
|
164
|
+
tokens
|
|
165
|
+
rescue JSON::ParserError => e
|
|
166
|
+
raise ServerError.new("token_exchange_failed", "Token response was not valid JSON", detail: e.message)
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
def http_post(url, form)
|
|
170
|
+
uri = URI(url)
|
|
171
|
+
req = Net::HTTP::Post.new(uri)
|
|
172
|
+
req["Accept"] = "application/json"
|
|
173
|
+
req.set_form_data(form)
|
|
174
|
+
perform(uri, req)
|
|
175
|
+
end
|
|
176
|
+
|
|
177
|
+
def http_get(url)
|
|
178
|
+
uri = URI(url)
|
|
179
|
+
req = Net::HTTP::Get.new(uri)
|
|
180
|
+
req["Accept"] = "application/json"
|
|
181
|
+
perform(uri, req)
|
|
182
|
+
end
|
|
183
|
+
|
|
184
|
+
def perform(uri, req)
|
|
185
|
+
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == "https",
|
|
186
|
+
open_timeout: 15, read_timeout: 15) do |http|
|
|
187
|
+
http.request(req)
|
|
188
|
+
end
|
|
189
|
+
rescue StandardError => e
|
|
190
|
+
raise ServerError.new("network_error", "Network error: #{e.message}", detail: e.message)
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
def success?(resp)
|
|
194
|
+
(200..299).cover?(resp.code.to_i)
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
def truncate(str, limit = 2048)
|
|
198
|
+
s = str.to_s
|
|
199
|
+
s.length > limit ? "#{s[0, limit]}…[truncated]" : s
|
|
200
|
+
end
|
|
201
|
+
end
|
|
202
|
+
end
|
data/lib/logi_auth.rb
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# logi_auth — thin server-side "Sign in with logi" for Ruby / Rails backends.
|
|
4
|
+
# Confidential OAuth 2.0 code exchange + id_token (RS256) verification. Same
|
|
5
|
+
# safety contract as the iOS/Android/Web/Flutter/Node SDKs (shared golden
|
|
6
|
+
# vectors). Zero gem dependencies (stdlib OpenSSL + net/http + json).
|
|
7
|
+
|
|
8
|
+
require_relative "logi_auth/version"
|
|
9
|
+
require_relative "logi_auth/errors"
|
|
10
|
+
require_relative "logi_auth/id_token_verifier"
|
|
11
|
+
require_relative "logi_auth/server"
|
|
12
|
+
|
|
13
|
+
module LogiAuth
|
|
14
|
+
end
|
metadata
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: logi_auth
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 1.0.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- Dcode
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 2026-07-01 00:00:00.000000000 Z
|
|
11
|
+
dependencies:
|
|
12
|
+
- !ruby/object:Gem::Dependency
|
|
13
|
+
name: minitest
|
|
14
|
+
requirement: !ruby/object:Gem::Requirement
|
|
15
|
+
requirements:
|
|
16
|
+
- - "~>"
|
|
17
|
+
- !ruby/object:Gem::Version
|
|
18
|
+
version: '5.0'
|
|
19
|
+
type: :development
|
|
20
|
+
prerelease: false
|
|
21
|
+
version_requirements: !ruby/object:Gem::Requirement
|
|
22
|
+
requirements:
|
|
23
|
+
- - "~>"
|
|
24
|
+
- !ruby/object:Gem::Version
|
|
25
|
+
version: '5.0'
|
|
26
|
+
description: Thin backend connector for logi (1pass) as an identity provider. Confidential-client
|
|
27
|
+
code exchange with mandatory id_token verification (signature + iss + aud + exp
|
|
28
|
+
+ nonce). Zero gem dependencies (stdlib OpenSSL + net/http).
|
|
29
|
+
executables: []
|
|
30
|
+
extensions: []
|
|
31
|
+
extra_rdoc_files: []
|
|
32
|
+
files:
|
|
33
|
+
- LICENSE
|
|
34
|
+
- NOTICE
|
|
35
|
+
- README.md
|
|
36
|
+
- lib/logi_auth.rb
|
|
37
|
+
- lib/logi_auth/errors.rb
|
|
38
|
+
- lib/logi_auth/id_token_verifier.rb
|
|
39
|
+
- lib/logi_auth/server.rb
|
|
40
|
+
- lib/logi_auth/version.rb
|
|
41
|
+
homepage: https://github.com/dcode-co/logi-auth-ruby
|
|
42
|
+
licenses:
|
|
43
|
+
- Apache-2.0
|
|
44
|
+
metadata:
|
|
45
|
+
source_code_uri: https://github.com/dcode-co/logi-auth-ruby
|
|
46
|
+
bug_tracker_uri: https://github.com/dcode-co/logi-auth-ruby/issues
|
|
47
|
+
rubygems_mfa_required: 'true'
|
|
48
|
+
rdoc_options: []
|
|
49
|
+
require_paths:
|
|
50
|
+
- lib
|
|
51
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
52
|
+
requirements:
|
|
53
|
+
- - ">="
|
|
54
|
+
- !ruby/object:Gem::Version
|
|
55
|
+
version: '3.0'
|
|
56
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
57
|
+
requirements:
|
|
58
|
+
- - ">="
|
|
59
|
+
- !ruby/object:Gem::Version
|
|
60
|
+
version: '0'
|
|
61
|
+
requirements: []
|
|
62
|
+
rubygems_version: 3.6.2
|
|
63
|
+
specification_version: 4
|
|
64
|
+
summary: Server-side "Sign in with logi" for Ruby/Rails — confidential OAuth 2.0 +
|
|
65
|
+
id_token (RS256) verification.
|
|
66
|
+
test_files: []
|