zeroclick-sellers 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 +203 -0
- data/README.md +195 -0
- data/lib/zeroclick/sellers/client.rb +199 -0
- data/lib/zeroclick/sellers/contracts.rb +254 -0
- data/lib/zeroclick/sellers/errors.rb +48 -0
- data/lib/zeroclick/sellers/middleware.rb +247 -0
- data/lib/zeroclick/sellers/railtie.rb +46 -0
- data/lib/zeroclick/sellers/responses.rb +62 -0
- data/lib/zeroclick/sellers/usage.rb +154 -0
- data/lib/zeroclick/sellers/verify.rb +177 -0
- data/lib/zeroclick/sellers/version.rb +9 -0
- data/lib/zeroclick/sellers.rb +74 -0
- metadata +58 -0
checksums.yaml
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
---
|
|
2
|
+
SHA256:
|
|
3
|
+
metadata.gz: 06b9bd195b7dc0b39d12660feeb511f4260c2b6627270d8dc643576e69b005a0
|
|
4
|
+
data.tar.gz: d5e7a552b95d6f7664a96185de1446a0d215735fdcdf40e18479de90c7c30d1b
|
|
5
|
+
SHA512:
|
|
6
|
+
metadata.gz: 117c713bf87542ba54035ce2fa1d256716716f2297cd2cbab53739da2350c7b9ae9fa30e9f252ade7f660666bf93a5e61871e11cf976205cf66bb6559cf1cc25
|
|
7
|
+
data.tar.gz: 01b80f728b183fa5d9d55aed65c25592c40bf77649bae4e6917ad0300e27c2ae3021aea45110bb708919175be2d74ca75c92e79b345a11b925d365d7127bd010
|
data/LICENSE
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
Copyright 2026 ZeroClick
|
|
2
|
+
|
|
3
|
+
Apache License
|
|
4
|
+
Version 2.0, January 2004
|
|
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,
|
|
12
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
13
|
+
|
|
14
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
15
|
+
the copyright owner that is granting the License.
|
|
16
|
+
|
|
17
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
18
|
+
other entities that control, are controlled by, or are under common
|
|
19
|
+
control with that entity. For the purposes of this definition,
|
|
20
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
21
|
+
direction or management of such entity, whether by contract or
|
|
22
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
23
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
24
|
+
|
|
25
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
26
|
+
exercising permissions granted by this License.
|
|
27
|
+
|
|
28
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
29
|
+
including but not limited to software source code, documentation
|
|
30
|
+
source, and configuration files.
|
|
31
|
+
|
|
32
|
+
"Object" form shall mean any form resulting from mechanical
|
|
33
|
+
transformation or translation of a Source form, including but
|
|
34
|
+
not limited to compiled object code, generated documentation,
|
|
35
|
+
and conversions to other media types.
|
|
36
|
+
|
|
37
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
38
|
+
Object form, made available under the License, as indicated by a
|
|
39
|
+
copyright notice that is included in or attached to the work
|
|
40
|
+
(an example is provided in the Appendix below).
|
|
41
|
+
|
|
42
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
43
|
+
form, that is based on (or derived from) the Work and for which the
|
|
44
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
45
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
46
|
+
of this License, Derivative Works shall not include works that remain
|
|
47
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
48
|
+
the Work and Derivative Works thereof.
|
|
49
|
+
|
|
50
|
+
"Contribution" shall mean any work of authorship, including
|
|
51
|
+
the original version of the Work and any modifications or additions
|
|
52
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
53
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
54
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
55
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
56
|
+
means any form of electronic, verbal, or written communication sent
|
|
57
|
+
to the Licensor or its representatives, including but not limited to
|
|
58
|
+
communication on electronic mailing lists, source code control systems,
|
|
59
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
60
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
61
|
+
excluding communication that is conspicuously marked or otherwise
|
|
62
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
63
|
+
|
|
64
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
65
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
66
|
+
subsequently incorporated within the Work.
|
|
67
|
+
|
|
68
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
69
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
70
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
71
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
72
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
73
|
+
Work and such Derivative Works in Source or Object form.
|
|
74
|
+
|
|
75
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
76
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
77
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
78
|
+
(except as stated in this section) patent license to make, have made,
|
|
79
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
80
|
+
where such license applies only to those patent claims licensable
|
|
81
|
+
by such Contributor that are necessarily infringed by their
|
|
82
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
83
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
84
|
+
institute patent litigation against any entity (including a
|
|
85
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
86
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
87
|
+
or contributory patent infringement, then any patent licenses
|
|
88
|
+
granted to You under this License for that Work shall terminate
|
|
89
|
+
as of the date such litigation is filed.
|
|
90
|
+
|
|
91
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
92
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
93
|
+
modifications, and in Source or Object form, provided that You
|
|
94
|
+
meet the following conditions:
|
|
95
|
+
|
|
96
|
+
(a) You must give any other recipients of the Work or
|
|
97
|
+
Derivative Works a copy of this License; and
|
|
98
|
+
|
|
99
|
+
(b) You must cause any modified files to carry prominent notices
|
|
100
|
+
stating that You changed the files; and
|
|
101
|
+
|
|
102
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
103
|
+
that You distribute, all copyright, patent, trademark, and
|
|
104
|
+
attribution notices from the Source form of the Work,
|
|
105
|
+
excluding those notices that do not pertain to any part of
|
|
106
|
+
the Derivative Works; and
|
|
107
|
+
|
|
108
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
109
|
+
distribution, then any Derivative Works that You distribute must
|
|
110
|
+
include a readable copy of the attribution notices contained
|
|
111
|
+
within such NOTICE file, excluding those notices that do not
|
|
112
|
+
pertain to any part of the Derivative Works, in at least one
|
|
113
|
+
of the following places: within a NOTICE text file distributed
|
|
114
|
+
as part of the Derivative Works; within the Source form or
|
|
115
|
+
documentation, if provided along with the Derivative Works; or,
|
|
116
|
+
within a display generated by the Derivative Works, if and
|
|
117
|
+
wherever such third-party notices normally appear. The contents
|
|
118
|
+
of the NOTICE file are for informational purposes only and
|
|
119
|
+
do not modify the License. You may add Your own attribution
|
|
120
|
+
notices within Derivative Works that You distribute, alongside
|
|
121
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
122
|
+
that such additional attribution notices cannot be construed
|
|
123
|
+
as modifying the License.
|
|
124
|
+
|
|
125
|
+
You may add Your own copyright statement to Your modifications and
|
|
126
|
+
may provide additional or different license terms and conditions
|
|
127
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
128
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
129
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
130
|
+
the conditions stated in this License.
|
|
131
|
+
|
|
132
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
133
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
134
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
135
|
+
this License, without any additional terms or conditions.
|
|
136
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
137
|
+
the terms of any separate license agreement you may have executed
|
|
138
|
+
with Licensor regarding such Contributions.
|
|
139
|
+
|
|
140
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
141
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
142
|
+
except as required for reasonable and customary use in describing the
|
|
143
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
144
|
+
|
|
145
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
146
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
147
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
148
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
149
|
+
implied, including, without limitation, any warranties or conditions
|
|
150
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
151
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
152
|
+
appropriateness of using or redistributing the Work and assume any
|
|
153
|
+
risks associated with Your exercise of permissions under this License.
|
|
154
|
+
|
|
155
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
156
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
157
|
+
unless required by applicable law (such as deliberate and grossly
|
|
158
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
159
|
+
liable to You for damages, including any direct, indirect, special,
|
|
160
|
+
incidental, or consequential damages of any character arising as a
|
|
161
|
+
result of this License or out of the use or inability to use the
|
|
162
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
163
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
164
|
+
other commercial damages or losses), even if such Contributor
|
|
165
|
+
has been advised of the possibility of such damages.
|
|
166
|
+
|
|
167
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
168
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
169
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
170
|
+
or other liability obligations and/or rights consistent with this
|
|
171
|
+
License. However, in accepting such obligations, You may act only
|
|
172
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
173
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
174
|
+
defend, and hold each Contributor harmless for any liability
|
|
175
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
176
|
+
of your accepting any such warranty or additional liability.
|
|
177
|
+
|
|
178
|
+
END OF TERMS AND CONDITIONS
|
|
179
|
+
|
|
180
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
181
|
+
|
|
182
|
+
To apply the Apache License to your work, attach the following
|
|
183
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
184
|
+
replaced with your own identifying information. (Don't include
|
|
185
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
186
|
+
comment syntax for the file format. We also recommend that a
|
|
187
|
+
file or class name and description of purpose be included on the
|
|
188
|
+
same "printed page" as the copyright notice for easier
|
|
189
|
+
identification within third-party archives.
|
|
190
|
+
|
|
191
|
+
Copyright [yyyy] [name of copyright owner]
|
|
192
|
+
|
|
193
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
194
|
+
you may not use this file except in compliance with the License.
|
|
195
|
+
You may obtain a copy of the License at
|
|
196
|
+
|
|
197
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
198
|
+
|
|
199
|
+
Unless required by applicable law or agreed to in writing, software
|
|
200
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
201
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
202
|
+
See the License for the specific language governing permissions and
|
|
203
|
+
limitations under the License.
|
data/README.md
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
# zeroclick-sellers
|
|
2
|
+
|
|
3
|
+
The ZeroClick billing guard for Ruby backends. It verifies that a request really
|
|
4
|
+
came from ZeroClick, checks that the buyer can pay **before** you do the work,
|
|
5
|
+
builds the refusal responses ZeroClick expects, and reports what was used.
|
|
6
|
+
|
|
7
|
+
Ships Rack middleware, so it works in Rails, Sinatra, Hanami and Roda alike —
|
|
8
|
+
Rails is a Rack app.
|
|
9
|
+
|
|
10
|
+
```ruby
|
|
11
|
+
# config.ru — or config/application.rb under Rails
|
|
12
|
+
require "zeroclick/sellers"
|
|
13
|
+
|
|
14
|
+
SELLER = ZeroClick::Sellers.create(
|
|
15
|
+
api_key: ENV.fetch("ZEROCLICK_API_KEY"),
|
|
16
|
+
signing_secrets: ZeroClick::Sellers.secrets_from_env
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
# The service slug is per-route, not per-client: one process can serve several.
|
|
20
|
+
use ZeroClick::Sellers::Middleware::Meter,
|
|
21
|
+
seller: SELLER,
|
|
22
|
+
service_slug: "extractor",
|
|
23
|
+
usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "requests", quantity: 1)]
|
|
24
|
+
|
|
25
|
+
run ->(env) { [200, { "content-type" => "application/json" }, ['{"ok":true}']] }
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
That is the whole integration for a fixed-price endpoint. The middleware
|
|
29
|
+
verifies the signature, refuses unpayable requests with a `402`, and — only if
|
|
30
|
+
your app answers `2xx` — reports the usage on the way out.
|
|
31
|
+
|
|
32
|
+
## Install
|
|
33
|
+
|
|
34
|
+
```ruby
|
|
35
|
+
gem "zeroclick-sellers"
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Requires Ruby 3.1+. **No runtime dependencies**: the core is stdlib-only
|
|
39
|
+
(`openssl`, `json`, `net/http`), and the Rack middleware is duck-typed, so
|
|
40
|
+
adding this gem cannot change how anything else in your bundle resolves.
|
|
41
|
+
|
|
42
|
+
## Configuration
|
|
43
|
+
|
|
44
|
+
```ruby
|
|
45
|
+
SELLER = ZeroClick::Sellers.create(
|
|
46
|
+
api_key: ENV.fetch("ZEROCLICK_API_KEY"),
|
|
47
|
+
signing_secrets: ZeroClick::Sellers.secrets_from_env
|
|
48
|
+
)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
`ZEROCLICK_SIGNING_SECRETS` is formatted `kid1:secret1,kid2:secret2`. It is a
|
|
52
|
+
map rather than a single secret because during a rotation both the old and the
|
|
53
|
+
new `kid` must verify, or every in-flight request fails.
|
|
54
|
+
|
|
55
|
+
| Option | Default | Why you would change it |
|
|
56
|
+
| --- | --- | --- |
|
|
57
|
+
| `api_key` | — | A both-scopes credential. |
|
|
58
|
+
| `usage_read_key` / `usage_write_key` | falls back to `api_key` | Split by direction when a separate worker reports usage. |
|
|
59
|
+
| `signing_secrets` | — | A `kid => secret` map. Exactly one of this or `resolve_signing_secret`. |
|
|
60
|
+
| `resolve_signing_secret` | — | A callable, when secrets live in a vault rather than the environment. |
|
|
61
|
+
| `allowance_unavailable_policy` | `"allow"` | `"deny"` or `"throw"` if serving unbilled work during an outage is worse than refusing. |
|
|
62
|
+
| `check_timeout_seconds` | `1.5` | The allowance check sits in your request path. |
|
|
63
|
+
| `on_allowance_unavailable` | — | A callable, to alert on fail-open events. |
|
|
64
|
+
|
|
65
|
+
### Fail open, but only after verification
|
|
66
|
+
|
|
67
|
+
If the allowance API cannot give an answer, `allowance_unavailable_policy`
|
|
68
|
+
decides: serve it (`"allow"`, the default), refuse with `503` (`"deny"`), or
|
|
69
|
+
raise (`"throw"`).
|
|
70
|
+
|
|
71
|
+
The policy is applied **only after a signature verifies**. A fail-open allowance
|
|
72
|
+
policy never becomes a fail-open signature policy — an unsigned request is
|
|
73
|
+
refused regardless.
|
|
74
|
+
|
|
75
|
+
An `Allow` reached this way reports `allowance == "unavailable"` rather than
|
|
76
|
+
`"allowed"`, so you can log or meter it.
|
|
77
|
+
|
|
78
|
+
## Rails
|
|
79
|
+
|
|
80
|
+
The Railtie is opt-in, so the gem stays usable without Rails on the load path.
|
|
81
|
+
|
|
82
|
+
```ruby
|
|
83
|
+
# config/application.rb
|
|
84
|
+
require "zeroclick/sellers/railtie"
|
|
85
|
+
|
|
86
|
+
config.zeroclick.api_key = ENV.fetch("ZEROCLICK_API_KEY")
|
|
87
|
+
config.zeroclick.signing_secrets = ZeroClick::Sellers.secrets_from_env
|
|
88
|
+
|
|
89
|
+
# No seller: here. config.middleware.use evaluates its arguments in the
|
|
90
|
+
# Application class body, which runs BEFORE the initializer that reads
|
|
91
|
+
# config.zeroclick — so no client exists yet. Omit it and the middleware
|
|
92
|
+
# resolves ZeroClick::Sellers.seller on the first request instead.
|
|
93
|
+
config.middleware.use ZeroClick::Sellers::Middleware::Meter,
|
|
94
|
+
service_slug: "extractor",
|
|
95
|
+
usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "requests", quantity: 1)]
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
Verified against Rails 8.1: this boots, and an unsigned request is refused with
|
|
99
|
+
`401` by the guard.
|
|
100
|
+
|
|
101
|
+
In **development only**, `ActionDispatch::HostAuthorization` sits at the top of
|
|
102
|
+
the stack and answers `403` before the guard is ever reached, so a local tunnel
|
|
103
|
+
or any non-localhost `Host` needs allowing:
|
|
104
|
+
|
|
105
|
+
```ruby
|
|
106
|
+
config.hosts << "my-tunnel.ngrok.app" # development only
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
It is absent from the production stack, so a deployed app needs nothing here.
|
|
110
|
+
|
|
111
|
+
In a controller, the verified caller is on the request env:
|
|
112
|
+
|
|
113
|
+
```ruby
|
|
114
|
+
zc = request.env["zeroclick.context"]
|
|
115
|
+
zc.zc_agent_id # the buyer
|
|
116
|
+
zc.zc_request_id # correlates with ZeroClick's logs — use it for idempotency
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
## Guarding without the middleware
|
|
120
|
+
|
|
121
|
+
When the charge depends on the request, guard inside the action instead:
|
|
122
|
+
|
|
123
|
+
```ruby
|
|
124
|
+
request = ZeroClick::Sellers::Middleware.request_from_env(env).first
|
|
125
|
+
decision = SELLER.guard(
|
|
126
|
+
request,
|
|
127
|
+
service_slug: "extractor",
|
|
128
|
+
usage: [ZeroClick::Sellers::UsageItem.new(meter_slug: "requests", quantity: pages)]
|
|
129
|
+
)
|
|
130
|
+
|
|
131
|
+
unless decision.allow?
|
|
132
|
+
return [decision.response.status, decision.response.headers, [decision.response.body]]
|
|
133
|
+
end
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
`guard_identity` is the same for a free endpoint that still needs to know which
|
|
137
|
+
buyer is calling. It makes no network call.
|
|
138
|
+
|
|
139
|
+
## Reporting variable usage
|
|
140
|
+
|
|
141
|
+
`Meter` settles usage from what it declared, so it requires an explicit
|
|
142
|
+
`quantity` on every item and refuses the rest **at wire-up**. A `max_quantity`
|
|
143
|
+
ceiling — or an item with neither quantity nor ceiling — has no settled amount,
|
|
144
|
+
and inventing one would silently mis-bill a delivered `200`. Both forms are
|
|
145
|
+
still fine for `guard`, which only asks whether the buyer could pay.
|
|
146
|
+
|
|
147
|
+
For work whose cost is unknown until it is done, declare the fixed part in the
|
|
148
|
+
middleware and report the rest afterwards:
|
|
149
|
+
|
|
150
|
+
```ruby
|
|
151
|
+
SELLER.report_usage(
|
|
152
|
+
zc_agent_id: zc.zc_agent_id,
|
|
153
|
+
idempotency_key: "extract:#{zc.zc_request_id}", # seller-owned, derived
|
|
154
|
+
service_slug: "extractor",
|
|
155
|
+
meter_slug: "tokens",
|
|
156
|
+
quantity: tokens_used
|
|
157
|
+
)
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
The idempotency key is yours to derive and must be stable for the request. The
|
|
161
|
+
SDK never invents one and never retries on your behalf — a retry that changed
|
|
162
|
+
the key would double-bill.
|
|
163
|
+
|
|
164
|
+
## Behaviour worth knowing
|
|
165
|
+
|
|
166
|
+
- **Verify first, always.** Every entry point verifies `zc-signature` before
|
|
167
|
+
anything else. The signature is an HMAC-SHA256 over the raw request bytes.
|
|
168
|
+
- **Decisions, not exceptions.** A guard returns `Allow` or `Deny`; `Deny#response`
|
|
169
|
+
is ready to return. `ZeroClick::Sellers::Error` is reserved for what you got
|
|
170
|
+
wrong or what the environment did.
|
|
171
|
+
- **Only delivered responses are billed.** A non-2xx answer gets no `zc-usage`.
|
|
172
|
+
- **The body still reads.** Verification must consume `rack.input`; the
|
|
173
|
+
middleware replaces it with a fresh stream over the same bytes. It does not
|
|
174
|
+
rely on `#rewind`, which Rack 3 no longer guarantees.
|
|
175
|
+
- **Bodies are bounded.** 10 MiB by default (`max_body_bytes:`). Verification
|
|
176
|
+
covers the whole body, so it must be buffered — and an attacker needs no valid
|
|
177
|
+
signature to make you buffer.
|
|
178
|
+
- **Raw targets matter.** The signature covers the percent-encoded target. The
|
|
179
|
+
middleware prefers `REQUEST_URI` (Puma sets it) over the decoded `PATH_INFO`;
|
|
180
|
+
behind a server that decodes, a route containing `%2F` cannot verify.
|
|
181
|
+
|
|
182
|
+
## Development
|
|
183
|
+
|
|
184
|
+
```sh
|
|
185
|
+
bundle install
|
|
186
|
+
bundle exec rake test
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
The suite executes the shared wire vectors in `test/vectors/`, generated
|
|
190
|
+
independently of any SDK, so passing means this implementation matches the spec
|
|
191
|
+
rather than matching itself.
|
|
192
|
+
|
|
193
|
+
## License
|
|
194
|
+
|
|
195
|
+
Apache-2.0.
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative "contracts"
|
|
4
|
+
require_relative "errors"
|
|
5
|
+
require_relative "responses"
|
|
6
|
+
require_relative "usage"
|
|
7
|
+
require_relative "verify"
|
|
8
|
+
|
|
9
|
+
module ZeroClick
|
|
10
|
+
module Sellers
|
|
11
|
+
# The facade a seller uses. Blocking, because Ruby web apps are.
|
|
12
|
+
class Client
|
|
13
|
+
# Usage keys can be split by direction: the read key covers allowance
|
|
14
|
+
# checks (#guard, #check_allowance), the write key covers usage reporting —
|
|
15
|
+
# often a separate process, such as a Sidekiq worker. +api_key+ remains a
|
|
16
|
+
# single both-scopes credential and backfills either side.
|
|
17
|
+
#
|
|
18
|
+
# Provide exactly one of +signing_secrets+ (Hash of kid => secret) or
|
|
19
|
+
# +resolve_signing_secret+ (callable taking a kid).
|
|
20
|
+
#
|
|
21
|
+
# +allowance_unavailable_policy+ decides what happens when the allowance
|
|
22
|
+
# API fails to give an answer: "allow" (default), "deny" or "throw". It is
|
|
23
|
+
# applied only AFTER a signature verifies, which is what keeps a fail-open
|
|
24
|
+
# allowance policy from becoming a fail-open signature policy.
|
|
25
|
+
def initialize(api_key: nil,
|
|
26
|
+
usage_read_key: nil,
|
|
27
|
+
usage_write_key: nil,
|
|
28
|
+
signing_secrets: nil,
|
|
29
|
+
resolve_signing_secret: nil,
|
|
30
|
+
api_base_url: DEFAULT_API_BASE_URL,
|
|
31
|
+
tolerance_seconds: DEFAULT_TOLERANCE_SECONDS,
|
|
32
|
+
allowance_unavailable_policy: "allow",
|
|
33
|
+
check_timeout_seconds: DEFAULT_CHECK_TIMEOUT_SECONDS,
|
|
34
|
+
on_allowance_unavailable: nil,
|
|
35
|
+
clock: -> { Time.now.to_i },
|
|
36
|
+
# The transport, injectable so every decision this class
|
|
37
|
+
# makes about a response is testable without a socket.
|
|
38
|
+
# Must return [status, body] or raise Error.
|
|
39
|
+
http_post: Usage.method(:post))
|
|
40
|
+
usage_read_key ||= api_key
|
|
41
|
+
usage_write_key ||= api_key
|
|
42
|
+
|
|
43
|
+
if usage_read_key.nil? || usage_read_key.empty?
|
|
44
|
+
raise Error.new("malformed_input", operation: "create",
|
|
45
|
+
message: "Provide usage_read_key (or a both-scopes api_key) for allowance checks")
|
|
46
|
+
end
|
|
47
|
+
if usage_write_key.nil? || usage_write_key.empty?
|
|
48
|
+
raise Error.new("malformed_input", operation: "create",
|
|
49
|
+
message: "Provide usage_write_key (or a both-scopes api_key) for usage reporting")
|
|
50
|
+
end
|
|
51
|
+
if signing_secrets.nil? == resolve_signing_secret.nil?
|
|
52
|
+
raise Error.new("malformed_input", operation: "create",
|
|
53
|
+
message: "Provide exactly one of signing_secrets or resolve_signing_secret")
|
|
54
|
+
end
|
|
55
|
+
if !signing_secrets.nil? && signing_secrets.empty?
|
|
56
|
+
raise Error.new("malformed_input", operation: "create",
|
|
57
|
+
message: "At least one signing secret is required")
|
|
58
|
+
end
|
|
59
|
+
unless ALLOWANCE_UNAVAILABLE_POLICIES.include?(allowance_unavailable_policy.to_s)
|
|
60
|
+
raise Error.new("malformed_input", operation: "create",
|
|
61
|
+
message: "allowance_unavailable_policy must be allow, deny or throw")
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
@usage_read_key = usage_read_key
|
|
65
|
+
@usage_write_key = usage_write_key
|
|
66
|
+
@signing_secrets = signing_secrets&.to_h&.freeze
|
|
67
|
+
@resolve_signing_secret = resolve_signing_secret
|
|
68
|
+
@api_base_url = api_base_url
|
|
69
|
+
@tolerance_seconds = tolerance_seconds
|
|
70
|
+
@policy = allowance_unavailable_policy.to_s
|
|
71
|
+
@timeout = check_timeout_seconds
|
|
72
|
+
@on_allowance_unavailable = on_allowance_unavailable
|
|
73
|
+
@clock = clock
|
|
74
|
+
@http_post = http_post
|
|
75
|
+
freeze
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def verify_request(request)
|
|
79
|
+
Verify.call(
|
|
80
|
+
request,
|
|
81
|
+
signing_secrets: @signing_secrets,
|
|
82
|
+
resolve_signing_secret: @resolve_signing_secret,
|
|
83
|
+
tolerance_seconds: @tolerance_seconds,
|
|
84
|
+
clock: @clock
|
|
85
|
+
)
|
|
86
|
+
end
|
|
87
|
+
|
|
88
|
+
# Verify, then check the buyer can pay for +usage+ before you do the work.
|
|
89
|
+
#
|
|
90
|
+
# Returns Allow or Deny. Deny#response is ready to return as-is.
|
|
91
|
+
def guard(request, service_slug:, usage:, plan_slug: nil)
|
|
92
|
+
items = Sellers.normalize_usage(usage, operation: "guard", allow_empty: false)
|
|
93
|
+
verification = verify_request(request)
|
|
94
|
+
return Deny.new(verification.reason, verification.response) unless verification.ok?
|
|
95
|
+
|
|
96
|
+
begin
|
|
97
|
+
status, body = @http_post.call(
|
|
98
|
+
base_url: @api_base_url,
|
|
99
|
+
path: Usage::CHECK_PATH,
|
|
100
|
+
api_key: @usage_read_key,
|
|
101
|
+
payload: Usage.build_check_payload(
|
|
102
|
+
zc_request_id: verification.context.zc_request_id,
|
|
103
|
+
service_slug: service_slug,
|
|
104
|
+
usage: items
|
|
105
|
+
),
|
|
106
|
+
timeout: @timeout,
|
|
107
|
+
operation: "check_allowance"
|
|
108
|
+
)
|
|
109
|
+
decision = Usage.interpret_check(status, body)
|
|
110
|
+
rescue Error => e
|
|
111
|
+
return on_allowance_error(e, verification.context)
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
return Allow.new(verification.context, "allowed") if decision.allowed?
|
|
115
|
+
|
|
116
|
+
Deny.new(
|
|
117
|
+
decision.reason || "allowance_denied",
|
|
118
|
+
Responses.payment_required(service_slug: service_slug, usage: items, plan_slug: plan_slug)
|
|
119
|
+
)
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
# Guard a free endpoint that must still know which buyer is calling.
|
|
123
|
+
# Makes no network call.
|
|
124
|
+
def guard_identity(request, service_slug:)
|
|
125
|
+
verification = verify_request(request)
|
|
126
|
+
return Deny.new(verification.reason, verification.response) unless verification.ok?
|
|
127
|
+
|
|
128
|
+
agent_id = verification.context.zc_agent_id
|
|
129
|
+
if agent_id.nil? || agent_id.empty?
|
|
130
|
+
return Deny.new("identity_required", Responses.payment_required(service_slug: service_slug, usage: []))
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
Allow.new(verification.context, "not_required")
|
|
134
|
+
end
|
|
135
|
+
|
|
136
|
+
def check_allowance(zc_request_id:, service_slug:, usage:)
|
|
137
|
+
status, body = @http_post.call(
|
|
138
|
+
base_url: @api_base_url,
|
|
139
|
+
path: Usage::CHECK_PATH,
|
|
140
|
+
api_key: @usage_read_key,
|
|
141
|
+
payload: Usage.build_check_payload(
|
|
142
|
+
zc_request_id: zc_request_id, service_slug: service_slug, usage: usage
|
|
143
|
+
),
|
|
144
|
+
timeout: @timeout,
|
|
145
|
+
operation: "check_allowance"
|
|
146
|
+
)
|
|
147
|
+
Usage.interpret_check(status, body)
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
# Report usage asynchronously. +idempotency_key+ is seller-owned and must
|
|
151
|
+
# be derived from the request — the SDK never invents one, and never
|
|
152
|
+
# retries on your behalf.
|
|
153
|
+
def report_usage(zc_agent_id:, idempotency_key:, service_slug:, meter_slug:, quantity:, occurred_at: nil)
|
|
154
|
+
status, body = @http_post.call(
|
|
155
|
+
base_url: @api_base_url,
|
|
156
|
+
path: Usage::REPORT_PATH,
|
|
157
|
+
api_key: @usage_write_key,
|
|
158
|
+
payload: Usage.build_report_payload(
|
|
159
|
+
zc_agent_id: zc_agent_id,
|
|
160
|
+
idempotency_key: idempotency_key,
|
|
161
|
+
service_slug: service_slug,
|
|
162
|
+
meter_slug: meter_slug,
|
|
163
|
+
quantity: quantity,
|
|
164
|
+
occurred_at: occurred_at
|
|
165
|
+
),
|
|
166
|
+
timeout: @timeout,
|
|
167
|
+
operation: "report_usage"
|
|
168
|
+
)
|
|
169
|
+
Usage.interpret_report(status, body)
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
# -- response helpers --------------------------------------------------
|
|
173
|
+
|
|
174
|
+
def payment_required(service_slug:, usage:, plan_slug: nil)
|
|
175
|
+
Responses.payment_required(service_slug: service_slug, usage: usage, plan_slug: plan_slug)
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
def with_usage(response, usage)
|
|
179
|
+
Responses.with_usage(response, usage)
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
private
|
|
183
|
+
|
|
184
|
+
# Apply the configured policy to an allowance-API failure. Reached only
|
|
185
|
+
# after a signature has verified.
|
|
186
|
+
def on_allowance_error(error, context)
|
|
187
|
+
raise error unless ALLOWANCE_API_ERROR_CODES.include?(error.code)
|
|
188
|
+
|
|
189
|
+
@on_allowance_unavailable&.call(error)
|
|
190
|
+
|
|
191
|
+
case @policy
|
|
192
|
+
when "throw" then raise error
|
|
193
|
+
when "deny" then Deny.new("allowance_unavailable", Responses.allowance_unavailable)
|
|
194
|
+
else Allow.new(context, "unavailable")
|
|
195
|
+
end
|
|
196
|
+
end
|
|
197
|
+
end
|
|
198
|
+
end
|
|
199
|
+
end
|