bydev-server 0.1.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-APACHE +202 -0
- data/LICENSE-MIT +21 -0
- data/README.md +58 -0
- data/lib/bydev/claims.rb +45 -0
- data/lib/bydev/error.rb +14 -0
- data/lib/bydev/generated.rb +86 -0
- data/lib/bydev/http.rb +23 -0
- data/lib/bydev/server.rb +10 -0
- data/lib/bydev/server_verifier.rb +211 -0
- data/lib/bydev/version.rb +5 -0
- data/lib/bydev/webhook.rb +53 -0
- data/lib/bydev-server.rb +3 -0
- metadata +55 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: e507104a4f478fc8e0f3d8c345e55e2a8de444696704f296751ecf81ccf52684
|
|
4
|
+
data.tar.gz: 1e1fbc78fdb67825c990fb1a4c97754738242518bb802195d5910085835cb5e6
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: a2d58d717ac154ce55b805a83f897375c86b713be0dbdaff7af6834443f133a3db8d5252da8d74ca55ef5d2e4f4d963b1c78f421a5a4bd4effd95797d85ef4b7
|
|
7
|
+
data.tar.gz: 7b19626f58e245b235a204386ef83d9a404b9fe8fa654db9eb8b055e51733e0ca7ea47139b816c30be1adf8338401f5deb0543eaf00b58717e3653ab731ee205
|
data/LICENSE-APACHE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
data/LICENSE-MIT
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 한비트 주식회사
|
|
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,58 @@
|
|
|
1
|
+
# 데브 서버 도우미: Ruby
|
|
2
|
+
|
|
3
|
+
판매자 서버에서 쓰는 두 기능만 담은 작은 젬입니다. Rails, Sinatra, Hanami 같은 Ruby 서버에서 웹훅 서명을 검증하고, 토큰(access_token,
|
|
4
|
+
licenseToken)을 검증합니다.
|
|
5
|
+
|
|
6
|
+
로그인이나 세션 같은 데스크톱 앱용 기능은 들어 있지 않습니다. 의존성은 표준 라이브러리(`openssl`, `json`, `net/http`)뿐입니다.
|
|
7
|
+
|
|
8
|
+
| 지원 | 버전 |
|
|
9
|
+
|---|---|
|
|
10
|
+
| 동작 명세 | 1.2.0 (12절 서버 도우미) |
|
|
11
|
+
| Ruby | 3.3 이상(Ed25519를 쓰려면 OpenSSL 1.1.1 이상) |
|
|
12
|
+
|
|
13
|
+
젬 이름은 `bydev-server`입니다. 지금 RubyGems에 있는 0.x 판은 이름을 먼저 등록하려고 낸 미리보기입니다. 1.0.0은 서비스 오픈과 함께 내며, 그 전에는
|
|
14
|
+
호환되지 않는 변경이 있을 수 있습니다. 판매하는 서비스에는 1.0.0 이상을 써 주세요.
|
|
15
|
+
|
|
16
|
+
## 빠른 시작
|
|
17
|
+
|
|
18
|
+
```ruby
|
|
19
|
+
require 'bydev-server'
|
|
20
|
+
|
|
21
|
+
# 웹훅: 받은 본문 그대로 검증하세요. JSON으로 읽었다가 다시 만든 문자열로는 서명이 맞지 않습니다. 시크릿을 교체하는 중이면 둘 다 넘기세요
|
|
22
|
+
event = Bydev.verify_webhook(secrets: [ENV.fetch('BYDEV_WEBHOOK_SECRET')], headers: request.headers, raw_body: request.raw_post)
|
|
23
|
+
# event.id로 중복 수신을 걸러 주세요. 검증에 실패하면 Bydev::Error가 발생합니다(code == Bydev::Codes::WEBHOOK_INVALID)
|
|
24
|
+
|
|
25
|
+
# 앱이 보낸 access_token을 검증합니다. 인스턴스 하나를 오래 두고 쓰세요. 여러 프로세스가 JWKS를 함께 쓰려면 Rails 캐시를 넘기세요
|
|
26
|
+
VERIFIER = Bydev::ServerVerifier.new(base_url: 'https://api.developedby.dev',
|
|
27
|
+
client_id: 'cli_01J9M0Y6X4N3Q8ZD5R2KT7VCPW', cache: Rails.cache)
|
|
28
|
+
claims = VERIFIER.verify_access_token(bearer_token) # claims.sub는 이 판매자 전용 가명 식별자입니다
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## 사용 조건
|
|
32
|
+
|
|
33
|
+
- **실패**하면 `Bydev::Error`가 발생합니다. 분기는 `code`로 해 주세요.
|
|
34
|
+
|
|
35
|
+
값은 `Bydev::Codes::*`에 있으며, `WEBHOOK_INVALID`, `TOKEN_INVALID`,
|
|
36
|
+
`GENERATION_REGRESSED`, `NETWORK_ERROR` 등이 있습니다.
|
|
37
|
+
- **헤더**: 헤더 이름의 대소문자를 가리지 않으며, Rack env 형식(`HTTP_WEBHOOK_ID`)으로 넘겨도 됩니다.
|
|
38
|
+
- **JWKS 캐시**: 응답의 `Cache-Control: max-age` 동안만 보관합니다. 처음 보는 `kid`가 오면 마지막으로 받은 지 1분이 지났을 때만 다시 받습니다.
|
|
39
|
+
|
|
40
|
+
인스턴스 하나를 여러 스레드에서 함께 써도 됩니다.
|
|
41
|
+
- **licenseToken**: `verify_license_token(token, min_generation:)`을 사용해 주세요. 지금까지 본 가장 큰 세대번호(세션을 새로 얻거나 인수할 때마다 커지는
|
|
42
|
+
번호)보다 작은 세대번호의 토큰은 거부합니다.
|
|
43
|
+
- **HTTP**: 표준 Net::HTTP를 쓰며, 리다이렉트는 따라가지 않습니다. 프록시가 필요하면 `http:` 인자에 `call(url) → [상태, 소문자 헤더, 본문]` 모양의
|
|
44
|
+
객체를 전달해 주세요.
|
|
45
|
+
- 라이선스는 MIT 또는 Apache-2.0입니다.
|
|
46
|
+
|
|
47
|
+
## 출처 확인
|
|
48
|
+
|
|
49
|
+
이 꾸러미는 공개 저장소 `developedby-dev/server-ruby`의 GitHub Actions가 판 태그에서 짓고 올립니다. RubyGems에 올린 `.gem`에는 GitHub 출처 증명이 있습니다. 받은 파일을 `gh attestation verify <파일> --repo developedby-dev/server-ruby`로 확인할 수 있습니다.
|
|
50
|
+
|
|
51
|
+
## 개발
|
|
52
|
+
|
|
53
|
+
| 명령 | 하는 일 |
|
|
54
|
+
|---|---|
|
|
55
|
+
| `ruby -w -Ilib -Itest test/test_server.rb` | minitest로 시험을 돌립니다. 웹훅 안내서의 예시, 토큰 검증, JWKS 캐시 규칙, 표준 TCPServer로 띄운 실제 HTTP 통신을 확인합니다. |
|
|
56
|
+
| `pnpm sdk:check ruby` | 같은 시험을 돌립니다. |
|
|
57
|
+
|
|
58
|
+
`lib/bydev/generated.rb`는 생성된 파일이며, `pnpm --filter @bydev/sdk-codegen generate`로 다시 만듭니다.
|
data/lib/bydev/claims.rb
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Bydev
|
|
4
|
+
# 검증된 access_token 클레임 (명세 12절). `sub`가 그 판매자용 가명 식별자다.
|
|
5
|
+
AccessClaims = Data.define(:iss, :sub, :aud, :client_id, :scope, :iat, :exp, :jti) do
|
|
6
|
+
def self.read(c)
|
|
7
|
+
new(iss: Claims.text(c, 'iss'), sub: Claims.text(c, 'sub'), aud: Claims.text(c, 'aud'),
|
|
8
|
+
client_id: Claims.text(c, 'client_id'), scope: Claims.text(c, 'scope'), iat: Claims.integer(c, 'iat'),
|
|
9
|
+
exp: Claims.integer(c, 'exp'), jti: Claims.text(c, 'jti'))
|
|
10
|
+
end
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
# 검증된 licenseToken 클레임 (명세 9 · 12절). `build_id`는 세션을 얻을 때 앱이 보낸 대상 · 버전으로 데브가 확정한 빌드(ADR-0049) —
|
|
14
|
+
# 확정하지 못했으면 nil.
|
|
15
|
+
LicenseClaims = Data.define(:iss, :sub, :aud, :product_id, :device_id, :sid, :generation, :iat, :exp, :build_id) do
|
|
16
|
+
def self.read(c)
|
|
17
|
+
new(iss: Claims.text(c, 'iss'), sub: Claims.text(c, 'sub'), aud: Claims.text(c, 'aud'),
|
|
18
|
+
product_id: Claims.text(c, 'product_id'), device_id: Claims.text(c, 'device_id'), sid: Claims.text(c, 'sid'),
|
|
19
|
+
generation: Claims.integer(c, 'generation'), iat: Claims.integer(c, 'iat'), exp: Claims.integer(c, 'exp'),
|
|
20
|
+
build_id: Claims.optional_text(c, 'build_id'))
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
|
|
24
|
+
# @api private 클레임 읽기 — 모양이 다르면 TOKEN_INVALID.
|
|
25
|
+
module Claims
|
|
26
|
+
def self.text(c, key)
|
|
27
|
+
value = c[key]
|
|
28
|
+
raise Error.new(Codes::TOKEN_INVALID, "클레임 #{key}가 문자열이 아니다") unless value.is_a?(String)
|
|
29
|
+
|
|
30
|
+
value
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# 없으면 nil, 있는데 문자열이 아니면 TOKEN_INVALID.
|
|
34
|
+
def self.optional_text(c, key)
|
|
35
|
+
c[key].nil? ? nil : text(c, key)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
def self.integer(c, key)
|
|
39
|
+
value = c[key]
|
|
40
|
+
raise Error.new(Codes::TOKEN_INVALID, "클레임 #{key}가 정수가 아니다") unless value.is_a?(Integer)
|
|
41
|
+
|
|
42
|
+
value
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
end
|
data/lib/bydev/error.rb
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module Bydev
|
|
4
|
+
# 실패 하나 — `code`로 분기한다(`Bydev::Codes`). 메시지는 보여 주기만 한다.
|
|
5
|
+
class Error < StandardError
|
|
6
|
+
attr_reader :code, :http_status
|
|
7
|
+
|
|
8
|
+
def initialize(code, message, http_status: nil)
|
|
9
|
+
super(message)
|
|
10
|
+
@code = code
|
|
11
|
+
@http_status = http_status
|
|
12
|
+
end
|
|
13
|
+
end
|
|
14
|
+
end
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Code generated by sdks/codegen. DO NOT EDIT.
|
|
4
|
+
# 원천: packages/contracts · sdks/spec/rules.json — 다시 만들기: pnpm --filter @bydev/sdk-codegen generate
|
|
5
|
+
|
|
6
|
+
module Bydev
|
|
7
|
+
# 이 패키지가 따르는 동작 명세 판.
|
|
8
|
+
SPEC_VERSION = '1.2.0'
|
|
9
|
+
|
|
10
|
+
# 에러 코드 — API(contracts ERROR_CODES)와 SDK(명세 3.3). 분기는 이 값으로 한다.
|
|
11
|
+
module Codes
|
|
12
|
+
INVALID_CLIENT = 'INVALID_CLIENT'
|
|
13
|
+
AUTHORIZATION_PENDING = 'AUTHORIZATION_PENDING'
|
|
14
|
+
SLOW_DOWN = 'SLOW_DOWN'
|
|
15
|
+
EXPIRED_TOKEN = 'EXPIRED_TOKEN'
|
|
16
|
+
INVALID_GRANT = 'INVALID_GRANT'
|
|
17
|
+
SCOPE_INSUFFICIENT = 'SCOPE_INSUFFICIENT'
|
|
18
|
+
ENTITLEMENT_NOT_FOUND = 'ENTITLEMENT_NOT_FOUND'
|
|
19
|
+
ENTITLEMENT_EXPIRED = 'ENTITLEMENT_EXPIRED'
|
|
20
|
+
ENTITLEMENT_REVOKED = 'ENTITLEMENT_REVOKED'
|
|
21
|
+
ENTITLEMENT_SUSPENDED = 'ENTITLEMENT_SUSPENDED'
|
|
22
|
+
DEVICE_IN_USE = 'DEVICE_IN_USE'
|
|
23
|
+
INSTANCE_ALREADY_RUNNING = 'INSTANCE_ALREADY_RUNNING'
|
|
24
|
+
DEVICE_LIMIT_EXCEEDED = 'DEVICE_LIMIT_EXCEEDED'
|
|
25
|
+
SESSION_REVOKED = 'SESSION_REVOKED'
|
|
26
|
+
SESSION_SUPERSEDED = 'SESSION_SUPERSEDED'
|
|
27
|
+
TAKEOVER_LIMIT_EXCEEDED = 'TAKEOVER_LIMIT_EXCEEDED'
|
|
28
|
+
DEVICE_NOT_FOUND = 'DEVICE_NOT_FOUND'
|
|
29
|
+
DEVICE_RELEASE_LIMIT_EXCEEDED = 'DEVICE_RELEASE_LIMIT_EXCEEDED'
|
|
30
|
+
PRODUCT_NOT_FOUND = 'PRODUCT_NOT_FOUND'
|
|
31
|
+
PRODUCT_SUSPENDED = 'PRODUCT_SUSPENDED'
|
|
32
|
+
RATE_LIMITED = 'RATE_LIMITED'
|
|
33
|
+
IDEMPOTENCY_KEY_CONFLICT = 'IDEMPOTENCY_KEY_CONFLICT'
|
|
34
|
+
VALIDATION_FAILED = 'VALIDATION_FAILED'
|
|
35
|
+
TEST_MODE_ONLY = 'TEST_MODE_ONLY'
|
|
36
|
+
INTERNAL_ERROR = 'INTERNAL_ERROR'
|
|
37
|
+
ENTITLEMENT_VERSION_NOT_COVERED = 'ENTITLEMENT_VERSION_NOT_COVERED'
|
|
38
|
+
NETWORK_ERROR = 'NETWORK_ERROR'
|
|
39
|
+
PROTOCOL_ERROR = 'PROTOCOL_ERROR'
|
|
40
|
+
STORAGE_FAILED = 'STORAGE_FAILED'
|
|
41
|
+
NOT_SIGNED_IN = 'NOT_SIGNED_IN'
|
|
42
|
+
TOKEN_INVALID = 'TOKEN_INVALID'
|
|
43
|
+
GENERATION_REGRESSED = 'GENERATION_REGRESSED'
|
|
44
|
+
OFFLINE_EXPIRED = 'OFFLINE_EXPIRED'
|
|
45
|
+
DOWNLOAD_INTEGRITY = 'DOWNLOAD_INTEGRITY'
|
|
46
|
+
LOGIN_CANCELLED = 'LOGIN_CANCELLED'
|
|
47
|
+
CONFIGURATION = 'CONFIGURATION'
|
|
48
|
+
WEBHOOK_INVALID = 'WEBHOOK_INVALID'
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
# 규칙 (sdks/spec/rules.json).
|
|
52
|
+
module Rules
|
|
53
|
+
SPEC_VERSION = '1.2.0'
|
|
54
|
+
API = 'v1'
|
|
55
|
+
USER_AGENT_LANGUAGES = ['typescript', 'dotnet', 'swift', 'kotlin', 'python', 'go', 'rust', 'c'].freeze
|
|
56
|
+
USER_AGENT_PATTERN = '^bydev-(typescript|dotnet|swift|kotlin|python|go|rust|c)/[0-9]+\\.[0-9]+\\.[0-9]+(-[0-9A-Za-z.-]+)?( .+)?$'
|
|
57
|
+
HTTP_TIMEOUT_SEC = 30
|
|
58
|
+
LOGIN_POLL_JITTER_MIN = 1.0
|
|
59
|
+
LOGIN_POLL_JITTER_MAX = 1.15
|
|
60
|
+
LOGIN_SLOW_DOWN_INCREMENT_SEC = 5
|
|
61
|
+
TOKEN_REFRESH_SKEW_SEC = 60
|
|
62
|
+
TOKEN_REFRESH_RETRY_DELAYS_SEC = [1.0, 3.0, 7.0].freeze
|
|
63
|
+
TOKEN_CLOCK_LEEWAY_SEC = 60
|
|
64
|
+
SESSION_HEARTBEAT_JITTER_MIN = 0.85
|
|
65
|
+
SESSION_HEARTBEAT_JITTER_MAX = 1.15
|
|
66
|
+
SESSION_START_RETRY_DELAYS_SEC = [2.0, 5.0, 10.0, 30.0, 60.0].freeze
|
|
67
|
+
JWKS_DEFAULT_MAX_AGE_SEC = 300
|
|
68
|
+
JWKS_UNKNOWN_KID_REFETCH_MIN_INTERVAL_SEC = 60
|
|
69
|
+
FINGERPRINT_ALGORITHM = 'SHA-256'
|
|
70
|
+
FINGERPRINT_SALT = 'bydev-device-v1'
|
|
71
|
+
FINGERPRINT_ENCODING = 'hex-lower'
|
|
72
|
+
FINGERPRINT_SOURCE_READ_ATTEMPTS = 3
|
|
73
|
+
FINGERPRINT_SOURCE_READ_RETRY_DELAY_MS = 300
|
|
74
|
+
STORAGE_SERVICE = 'dev.developedby.sdk'
|
|
75
|
+
STORAGE_RECORD_VERSION = 1
|
|
76
|
+
TRANSIENT_CODES = ['NETWORK_ERROR', 'RATE_LIMITED', 'INTERNAL_ERROR'].freeze
|
|
77
|
+
TRANSIENT_UNKNOWN_CODE_STATUSES = [429].freeze
|
|
78
|
+
TRANSIENT_UNKNOWN_CODE_STATUS_RANGES = [(500..599)].freeze
|
|
79
|
+
WEBHOOK_SIGNATURE_VERSION = 'v1'
|
|
80
|
+
WEBHOOK_SECRET_PREFIX = 'whsec_'
|
|
81
|
+
WEBHOOK_TOLERANCE_SEC = 300
|
|
82
|
+
SDK_ERROR_CODES = ['NETWORK_ERROR', 'PROTOCOL_ERROR', 'STORAGE_FAILED', 'NOT_SIGNED_IN', 'TOKEN_INVALID', 'GENERATION_REGRESSED', 'OFFLINE_EXPIRED', 'DOWNLOAD_INTEGRITY', 'LOGIN_CANCELLED', 'CONFIGURATION', 'WEBHOOK_INVALID'].freeze
|
|
83
|
+
SESSION_STATES = ['Starting', 'Active', 'Degraded', 'NeedsDecision', 'Locked', 'Stopped'].freeze
|
|
84
|
+
NEEDS_DECISION_REASONS = ['DEVICE_IN_USE', 'INSTANCE_ALREADY_RUNNING', 'DEVICE_LIMIT_EXCEEDED'].freeze
|
|
85
|
+
end
|
|
86
|
+
end
|
data/lib/bydev/http.rb
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'net/http'
|
|
4
|
+
require 'uri'
|
|
5
|
+
|
|
6
|
+
module Bydev
|
|
7
|
+
# 기본 HTTP GET — 표준 Net::HTTP. 리다이렉트를 따라가지 않는다(Net::HTTP는 원래 따라가지 않는다) · 시간 초과는 `Rules::HTTP_TIMEOUT_SEC`.
|
|
8
|
+
# 프록시 · 인증서 고정이 필요하면 `ServerVerifier`에 같은 모양의 호출 가능한 것을 준다.
|
|
9
|
+
module Http
|
|
10
|
+
# @return [Array(Integer, Hash{String=>String}, String)] 상태 · 소문자 헤더 · 본문
|
|
11
|
+
def self.get(url)
|
|
12
|
+
uri = URI(url)
|
|
13
|
+
response = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https',
|
|
14
|
+
open_timeout: Rules::HTTP_TIMEOUT_SEC,
|
|
15
|
+
read_timeout: Rules::HTTP_TIMEOUT_SEC) do |http|
|
|
16
|
+
http.get(uri.request_uri, 'Accept' => 'application/json', 'User-Agent' => "bydev-ruby-server/#{VERSION}")
|
|
17
|
+
end
|
|
18
|
+
[response.code.to_i, response.each_header.to_h { |k, v| [k.downcase, v] }, response.body.to_s]
|
|
19
|
+
rescue SystemCallError, IOError, SocketError, Timeout::Error, OpenSSL::SSL::SSLError => e
|
|
20
|
+
raise Error.new(Codes::NETWORK_ERROR, "API에 연결하지 못했다: #{e.class}")
|
|
21
|
+
end
|
|
22
|
+
end
|
|
23
|
+
end
|
data/lib/bydev/server.rb
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# 데브 라이선스 API 판매자 서버 도우미 — `Bydev.verify_webhook` · `Bydev::ServerVerifier` (ADR-0040 정해야 할 것 5).
|
|
4
|
+
require_relative 'version'
|
|
5
|
+
require_relative 'generated'
|
|
6
|
+
require_relative 'error'
|
|
7
|
+
require_relative 'claims'
|
|
8
|
+
require_relative 'http'
|
|
9
|
+
require_relative 'webhook'
|
|
10
|
+
require_relative 'server_verifier'
|
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'digest'
|
|
4
|
+
require 'json'
|
|
5
|
+
require 'openssl'
|
|
6
|
+
|
|
7
|
+
module Bydev
|
|
8
|
+
# 판매자 서버의 토큰 검증 (명세 9 · 12절 · 안내서 09장) — 발견 문서와 JWKS를 받아 access_token(`at+jwt`) · licenseToken(`license+jwt`)의
|
|
9
|
+
# 서명 · `iss` · `aud` · `exp`를 확인한다. 스레드 사이에 나눠 쓴다 — 인스턴스 하나를 오래 둔다(프로세스마다 하나).
|
|
10
|
+
#
|
|
11
|
+
# 여러 프로세스(Puma 작업자 등)가 받은 JWKS를 나누려면 Rails 캐시 모양(`read(key)` · `write(key, value, expires_in:)`)의 `cache:`를 준다.
|
|
12
|
+
# JWKS는 응답의 `Cache-Control: max-age`까지만 두고(명세 9.1), 모르는 `kid`는 마지막으로 받은 지 1분이 지났을 때만 다시 받는다.
|
|
13
|
+
class ServerVerifier
|
|
14
|
+
# SubjectPublicKeyInfo(Ed25519)의 앞부분 — 뒤에 32바이트 공개키가 붙는다 (RFC 8410)
|
|
15
|
+
SPKI_PREFIX = ['302a300506032b6570032100'].pack('H*').freeze
|
|
16
|
+
CACHE_PREFIX = 'bydev.server.'
|
|
17
|
+
|
|
18
|
+
# @param http [#call, nil] GET — url → [상태, 소문자 헤더, 본문] (기본 `Http.get`)
|
|
19
|
+
# @param clock [#call, nil] 지금(Unix 초) — 시험에서 준다
|
|
20
|
+
# @param cache [#read & #write, nil] Rails 캐시 모양(선택)
|
|
21
|
+
def initialize(base_url:, client_id:, http: nil, clock: nil, cache: nil)
|
|
22
|
+
@base_url = base_url.chomp('/')
|
|
23
|
+
@client_id = client_id
|
|
24
|
+
@http = http || Http.method(:get)
|
|
25
|
+
@clock = clock || -> { Time.now.to_f }
|
|
26
|
+
@cache = cache
|
|
27
|
+
@mutex = Mutex.new
|
|
28
|
+
@discovery = nil
|
|
29
|
+
@key_set = nil
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# access_token(at+jwt)을 검증한다 — 앱이 판매자 서버에 보낸 토큰으로 사용자를 알아볼 때.
|
|
33
|
+
def verify_access_token(token)
|
|
34
|
+
AccessClaims.read(verify_signed(token, 'at+jwt'))
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
# licenseToken(license+jwt)을 검증한다. `min_generation` — 같은 sub · device_id에서 판매자 서버가 이미 본 가장 큰 세대번호(0이면 보지 않는다).
|
|
38
|
+
# 그보다 작으면 GENERATION_REGRESSED.
|
|
39
|
+
def verify_license_token(token, min_generation: 0)
|
|
40
|
+
claims = LicenseClaims.read(verify_signed(token, 'license+jwt'))
|
|
41
|
+
if min_generation.positive? && claims.generation < min_generation
|
|
42
|
+
raise Error.new(Codes::GENERATION_REGRESSED, "세대번호 #{claims.generation} < 이미 본 #{min_generation}")
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
claims
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
private
|
|
49
|
+
|
|
50
|
+
# 9절 1 ~ 4를 통과한 페이로드
|
|
51
|
+
def verify_signed(token, typ)
|
|
52
|
+
parts = token.to_s.split('.', -1)
|
|
53
|
+
raise invalid('JWT 형식이 아니다') unless parts.size == 3
|
|
54
|
+
|
|
55
|
+
header = json(base64url(parts[0]))
|
|
56
|
+
payload = json(base64url(parts[1]))
|
|
57
|
+
signature = base64url(parts[2])
|
|
58
|
+
raise invalid('JWT를 읽지 못했다') unless header.is_a?(Hash) && payload.is_a?(Hash) && signature
|
|
59
|
+
|
|
60
|
+
raise invalid('alg가 EdDSA가 아니다') unless header['alg'] == 'EdDSA'
|
|
61
|
+
raise invalid("typ가 #{typ}가 아니다") unless header['typ'] == typ
|
|
62
|
+
|
|
63
|
+
kid = header['kid']
|
|
64
|
+
raise invalid('kid가 없다') unless kid.is_a?(String) && !kid.empty?
|
|
65
|
+
raise invalid('서명이 맞지 않는다') unless ed25519_verify(key_for(kid), signature, "#{parts[0]}.#{parts[1]}")
|
|
66
|
+
raise invalid('iss가 다르다') unless payload['iss'] == discovery[:issuer]
|
|
67
|
+
raise invalid('aud가 이 client_id가 아니다') unless payload['aud'] == @client_id
|
|
68
|
+
|
|
69
|
+
exp = payload['exp']
|
|
70
|
+
raise invalid('만료된 토큰') if !exp.is_a?(Integer) || exp <= @clock.call - Rules::TOKEN_CLOCK_LEEWAY_SEC
|
|
71
|
+
|
|
72
|
+
payload
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def ed25519_verify(public_key, signature, message)
|
|
76
|
+
return false unless signature.bytesize == 64
|
|
77
|
+
|
|
78
|
+
OpenSSL::PKey.read(SPKI_PREFIX + public_key).verify(nil, signature, message)
|
|
79
|
+
rescue OpenSSL::PKey::PKeyError
|
|
80
|
+
false
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# 9.1절 — 지난 캐시는 쓰지 않는다 · 모르는 kid는 1분에 한 번만 다시 받는다
|
|
84
|
+
def key_for(kid)
|
|
85
|
+
now = @clock.call
|
|
86
|
+
set = @mutex.synchronize { @key_set } || cached_keys
|
|
87
|
+
set = fetch_keys if set.nil? || now >= set[:expires_at]
|
|
88
|
+
return set[:keys][kid] if set[:keys].key?(kid)
|
|
89
|
+
raise invalid("모르는 kid #{kid}") if now - set[:fetched_at] < Rules::JWKS_UNKNOWN_KID_REFETCH_MIN_INTERVAL_SEC
|
|
90
|
+
|
|
91
|
+
fetch_keys[:keys].fetch(kid) { raise invalid("모르는 kid #{kid}") }
|
|
92
|
+
end
|
|
93
|
+
|
|
94
|
+
def fetch_keys
|
|
95
|
+
headers, body = get(discovery[:jwks_uri])
|
|
96
|
+
keys = {}
|
|
97
|
+
Array(body['keys']).each do |jwk|
|
|
98
|
+
next unless jwk.is_a?(Hash) && jwk['kty'] == 'OKP' && jwk['crv'] == 'Ed25519'
|
|
99
|
+
|
|
100
|
+
kid = jwk['kid']
|
|
101
|
+
raw = jwk['x'].is_a?(String) ? base64url(jwk['x']) : nil
|
|
102
|
+
keys[kid] = raw.freeze if kid.is_a?(String) && !kid.empty? && raw&.bytesize == 32
|
|
103
|
+
end
|
|
104
|
+
max_age = headers['cache-control'].to_s[/(?:\A|,)\s*max-age=(\d+)/, 1]&.to_i || Rules::JWKS_DEFAULT_MAX_AGE_SEC
|
|
105
|
+
now = @clock.call.to_f
|
|
106
|
+
# 통째로 바꾼다 — 빠진 키는 더는 믿지 않는다
|
|
107
|
+
set = { keys: keys.freeze, fetched_at: now, expires_at: now + max_age }.freeze
|
|
108
|
+
@mutex.synchronize { @key_set = set }
|
|
109
|
+
store('jwks', { 'keys' => keys.transform_values { |raw| [raw].pack('m0').tr('+/', '-_').delete('=') },
|
|
110
|
+
'fetchedAt' => now, 'expiresAt' => now + max_age },
|
|
111
|
+
max_age + Rules::JWKS_UNKNOWN_KID_REFETCH_MIN_INTERVAL_SEC)
|
|
112
|
+
set
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
# 처음 한 번 받아 둔다. issuer가 base_url과 다르면 CONFIGURATION (명세 4절)
|
|
116
|
+
def discovery
|
|
117
|
+
found = @mutex.synchronize { @discovery }
|
|
118
|
+
return found if found
|
|
119
|
+
|
|
120
|
+
cached = cached_value('discovery')
|
|
121
|
+
found = if cached.is_a?(Hash) && cached['issuer'].is_a?(String) && cached['jwks_uri'].is_a?(String)
|
|
122
|
+
{ issuer: cached['issuer'], jwks_uri: cached['jwks_uri'] }
|
|
123
|
+
else
|
|
124
|
+
fetch_discovery
|
|
125
|
+
end
|
|
126
|
+
@mutex.synchronize { @discovery = found.freeze }
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
def fetch_discovery
|
|
130
|
+
_, body = get("#{@base_url}/.well-known/openid-configuration")
|
|
131
|
+
issuer = body['issuer']
|
|
132
|
+
jwks_uri = body['jwks_uri']
|
|
133
|
+
raise Error.new(Codes::PROTOCOL_ERROR, '발견 문서에 issuer · jwks_uri가 없다') unless issuer.is_a?(String) && jwks_uri.is_a?(String)
|
|
134
|
+
if issuer.chomp('/') != @base_url
|
|
135
|
+
raise Error.new(Codes::CONFIGURATION, "발견 문서의 issuer(#{issuer})가 base_url(#{@base_url})과 다르다")
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
store('discovery', { 'issuer' => issuer, 'jwks_uri' => jwks_uri }, 86_400)
|
|
139
|
+
{ issuer: issuer, jwks_uri: jwks_uri }
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
# 2xx면 [헤더, JSON], 아니면 에러
|
|
143
|
+
def get(url)
|
|
144
|
+
status, headers, body = begin
|
|
145
|
+
@http.call(url)
|
|
146
|
+
rescue Error
|
|
147
|
+
raise
|
|
148
|
+
rescue StandardError => e
|
|
149
|
+
raise Error.new(Codes::NETWORK_ERROR, "API에 연결하지 못했다: #{e.class}")
|
|
150
|
+
end
|
|
151
|
+
parsed = json(body)
|
|
152
|
+
if (200..299).cover?(status)
|
|
153
|
+
raise Error.new(Codes::PROTOCOL_ERROR, '응답 본문이 JSON이 아니다', http_status: status) unless parsed.is_a?(Hash)
|
|
154
|
+
|
|
155
|
+
return [headers, parsed]
|
|
156
|
+
end
|
|
157
|
+
if parsed.is_a?(Hash) && parsed['code'].is_a?(String) && parsed['message'].is_a?(String)
|
|
158
|
+
raise Error.new(parsed['code'], parsed['message'], http_status: status)
|
|
159
|
+
end
|
|
160
|
+
|
|
161
|
+
code = if status >= 500 then Codes::INTERNAL_ERROR
|
|
162
|
+
elsif status == 429 then Codes::RATE_LIMITED
|
|
163
|
+
else Codes::PROTOCOL_ERROR
|
|
164
|
+
end
|
|
165
|
+
raise Error.new(code, "HTTP #{status}", http_status: status)
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def cached_keys
|
|
169
|
+
value = cached_value('jwks')
|
|
170
|
+
return nil unless value.is_a?(Hash) && value['fetchedAt'].is_a?(Numeric) && value['expiresAt'].is_a?(Numeric)
|
|
171
|
+
|
|
172
|
+
keys = value['keys'].to_h.filter_map do |kid, x|
|
|
173
|
+
raw = x.is_a?(String) ? base64url(x) : nil
|
|
174
|
+
[kid.to_s, raw.freeze] if raw&.bytesize == 32
|
|
175
|
+
end.to_h
|
|
176
|
+
set = { keys: keys.freeze, fetched_at: value['fetchedAt'].to_f, expires_at: value['expiresAt'].to_f }.freeze
|
|
177
|
+
@mutex.synchronize { @key_set = set }
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
def cache_key(name) = "#{CACHE_PREFIX}#{name}.#{Digest::MD5.hexdigest(@base_url)}"
|
|
181
|
+
|
|
182
|
+
def cached_value(name)
|
|
183
|
+
return nil unless @cache
|
|
184
|
+
|
|
185
|
+
raw = @cache.read(cache_key(name))
|
|
186
|
+
raw.is_a?(String) ? json(raw) : nil
|
|
187
|
+
end
|
|
188
|
+
|
|
189
|
+
def store(name, value, ttl)
|
|
190
|
+
@cache&.write(cache_key(name), JSON.generate(value), expires_in: ttl)
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
def invalid(message) = Error.new(Codes::TOKEN_INVALID, message)
|
|
194
|
+
|
|
195
|
+
def json(text)
|
|
196
|
+
text.is_a?(String) ? JSON.parse(text) : nil
|
|
197
|
+
rescue JSON::ParserError
|
|
198
|
+
nil
|
|
199
|
+
end
|
|
200
|
+
|
|
201
|
+
def base64url(text)
|
|
202
|
+
return nil unless text.match?(/\A[A-Za-z0-9_-]*\z/)
|
|
203
|
+
|
|
204
|
+
padded = text.tr('-_', '+/')
|
|
205
|
+
padded += '=' * ((4 - (padded.length % 4)) % 4)
|
|
206
|
+
padded.unpack1('m0')
|
|
207
|
+
rescue ArgumentError
|
|
208
|
+
nil
|
|
209
|
+
end
|
|
210
|
+
end
|
|
211
|
+
end
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'openssl'
|
|
4
|
+
|
|
5
|
+
module Bydev
|
|
6
|
+
# 검증된 웹훅의 id와 시각(Unix 초) — 중복 수신은 id로 거른다.
|
|
7
|
+
WebhookVerification = Data.define(:id, :timestamp)
|
|
8
|
+
|
|
9
|
+
# 웹훅 서명 검증 (명세 12절 · 안내서 11장 — Standard Webhooks v1).
|
|
10
|
+
#
|
|
11
|
+
# `raw_body`는 **받은 그대로의 본문**이다(Rails `request.raw_post` · Rack `request.body.read`) — JSON으로 읽었다가 다시 만든 글자는 서명이 맞지
|
|
12
|
+
# 않는다. 시크릿을 교체하는 중이면 둘 다 넘긴다. 헤더 이름의 대소문자 · `HTTP_` 접두사(Rack env)는 가리지 않는다.
|
|
13
|
+
def self.verify_webhook(secrets:, headers:, raw_body:, now: Time.now.to_i)
|
|
14
|
+
lowered = headers.to_h.to_h { |name, value| [name.to_s.downcase.delete_prefix('http_').tr('_', '-'), Array(value).first.to_s] }
|
|
15
|
+
id = lowered.fetch('webhook-id', '')
|
|
16
|
+
timestamp = lowered.fetch('webhook-timestamp', '')
|
|
17
|
+
signatures = lowered.fetch('webhook-signature', '')
|
|
18
|
+
if id.empty? || timestamp.empty? || signatures.empty?
|
|
19
|
+
raise Error.new(Codes::WEBHOOK_INVALID, '웹훅 헤더(webhook-id · webhook-timestamp · webhook-signature)가 없다')
|
|
20
|
+
end
|
|
21
|
+
if !timestamp.match?(/\A\d+\z/) || (now - timestamp.to_i).abs > Rules::WEBHOOK_TOLERANCE_SEC
|
|
22
|
+
raise Error.new(Codes::WEBHOOK_INVALID, '웹훅 시각이 허용 범위 밖이다 — 재전송 공격일 수 있다')
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
candidates = signatures.split(' ').filter_map do |entry|
|
|
26
|
+
version, value = entry.split(',', 2)
|
|
27
|
+
next unless version == Rules::WEBHOOK_SIGNATURE_VERSION && value && !value.empty?
|
|
28
|
+
|
|
29
|
+
begin
|
|
30
|
+
value.unpack1('m0')
|
|
31
|
+
rescue ArgumentError
|
|
32
|
+
nil
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
signed = "#{id}.#{timestamp}.".b + raw_body.to_s.b
|
|
36
|
+
secrets.each do |secret|
|
|
37
|
+
unless secret.start_with?(Rules::WEBHOOK_SECRET_PREFIX)
|
|
38
|
+
raise Error.new(Codes::CONFIGURATION, "웹훅 시크릿은 #{Rules::WEBHOOK_SECRET_PREFIX}로 시작한다")
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
key = begin
|
|
42
|
+
secret.delete_prefix(Rules::WEBHOOK_SECRET_PREFIX).unpack1('m0')
|
|
43
|
+
rescue ArgumentError
|
|
44
|
+
raise Error.new(Codes::CONFIGURATION, '웹훅 시크릿을 읽지 못했다')
|
|
45
|
+
end
|
|
46
|
+
expected = OpenSSL::HMAC.digest('SHA256', key, signed)
|
|
47
|
+
if candidates.any? { |candidate| candidate.bytesize == expected.bytesize && OpenSSL.fixed_length_secure_compare(candidate, expected) }
|
|
48
|
+
return WebhookVerification.new(id: id, timestamp: timestamp.to_i)
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
raise Error.new(Codes::WEBHOOK_INVALID, '웹훅 서명이 맞지 않는다')
|
|
52
|
+
end
|
|
53
|
+
end
|
data/lib/bydev-server.rb
ADDED
metadata
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
|
2
|
+
name: bydev-server
|
|
3
|
+
version: !ruby/object:Gem::Version
|
|
4
|
+
version: 0.1.0
|
|
5
|
+
platform: ruby
|
|
6
|
+
authors:
|
|
7
|
+
- 한비트 주식회사
|
|
8
|
+
bindir: bin
|
|
9
|
+
cert_chain: []
|
|
10
|
+
date: 1980-01-02 00:00:00.000000000 Z
|
|
11
|
+
dependencies: []
|
|
12
|
+
description: '판매자 서버(Rails · Sinatra 등)에서 쓰는 두 함수를 제공합니다: Standard Webhooks v1 서명
|
|
13
|
+
검증과 Ed25519 토큰 검증. 표준 라이브러리만 사용합니다.'
|
|
14
|
+
executables: []
|
|
15
|
+
extensions: []
|
|
16
|
+
extra_rdoc_files: []
|
|
17
|
+
files:
|
|
18
|
+
- LICENSE-APACHE
|
|
19
|
+
- LICENSE-MIT
|
|
20
|
+
- README.md
|
|
21
|
+
- lib/bydev-server.rb
|
|
22
|
+
- lib/bydev/claims.rb
|
|
23
|
+
- lib/bydev/error.rb
|
|
24
|
+
- lib/bydev/generated.rb
|
|
25
|
+
- lib/bydev/http.rb
|
|
26
|
+
- lib/bydev/server.rb
|
|
27
|
+
- lib/bydev/server_verifier.rb
|
|
28
|
+
- lib/bydev/version.rb
|
|
29
|
+
- lib/bydev/webhook.rb
|
|
30
|
+
homepage: https://developedby.dev/sell/docs/sdks
|
|
31
|
+
licenses:
|
|
32
|
+
- MIT
|
|
33
|
+
- Apache-2.0
|
|
34
|
+
metadata:
|
|
35
|
+
source_code_uri: https://github.com/developedby-dev/server-ruby
|
|
36
|
+
documentation_uri: https://developedby.dev/sell/docs/sdks
|
|
37
|
+
rubygems_mfa_required: 'true'
|
|
38
|
+
rdoc_options: []
|
|
39
|
+
require_paths:
|
|
40
|
+
- lib
|
|
41
|
+
required_ruby_version: !ruby/object:Gem::Requirement
|
|
42
|
+
requirements:
|
|
43
|
+
- - ">="
|
|
44
|
+
- !ruby/object:Gem::Version
|
|
45
|
+
version: '3.3'
|
|
46
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
|
47
|
+
requirements:
|
|
48
|
+
- - ">="
|
|
49
|
+
- !ruby/object:Gem::Version
|
|
50
|
+
version: '0'
|
|
51
|
+
requirements: []
|
|
52
|
+
rubygems_version: 3.6.9
|
|
53
|
+
specification_version: 4
|
|
54
|
+
summary: 데브 라이선스 API 판매자 서버 도우미 — 웹훅 서명 검증 · access_token · licenseToken 검증
|
|
55
|
+
test_files: []
|