knoxcall 0.0.1 → 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.
Files changed (56) hide show
  1. checksums.yaml +4 -4
  2. data/LICENSE +201 -0
  3. data/README.md +439 -2
  4. data/exe/knoxcall +8 -0
  5. data/lib/knoxcall/bootstrap.rb +70 -0
  6. data/lib/knoxcall/bound_route.rb +47 -0
  7. data/lib/knoxcall/cli/ai.rb +79 -0
  8. data/lib/knoxcall/cli/ai_control.rb +275 -0
  9. data/lib/knoxcall/cli/common.rb +96 -0
  10. data/lib/knoxcall/cli/init.rb +94 -0
  11. data/lib/knoxcall/cli/login.rb +306 -0
  12. data/lib/knoxcall/cli/logout.rb +41 -0
  13. data/lib/knoxcall/cli/whoami.rb +29 -0
  14. data/lib/knoxcall/cli.rb +377 -0
  15. data/lib/knoxcall/client.rb +1025 -0
  16. data/lib/knoxcall/credentials_file.rb +442 -0
  17. data/lib/knoxcall/dpop.rb +79 -0
  18. data/lib/knoxcall/egress_observations.rb +372 -0
  19. data/lib/knoxcall/errors.rb +304 -0
  20. data/lib/knoxcall/intercept_patch.rb +181 -0
  21. data/lib/knoxcall/intercept_pipeline.rb +455 -0
  22. data/lib/knoxcall/intercept_resolver.rb +140 -0
  23. data/lib/knoxcall/intercept_store.rb +203 -0
  24. data/lib/knoxcall/login.rb +144 -0
  25. data/lib/knoxcall/resources/account.rb +12 -0
  26. data/lib/knoxcall/resources/agents.rb +25 -0
  27. data/lib/knoxcall/resources/ai_gateway.rb +417 -0
  28. data/lib/knoxcall/resources/api_keys.rb +35 -0
  29. data/lib/knoxcall/resources/audit_logs.rb +45 -0
  30. data/lib/knoxcall/resources/clients.rb +39 -0
  31. data/lib/knoxcall/resources/crypto.rb +122 -0
  32. data/lib/knoxcall/resources/dynamic_db.rb +68 -0
  33. data/lib/knoxcall/resources/environments.rb +16 -0
  34. data/lib/knoxcall/resources/logs.rb +51 -0
  35. data/lib/knoxcall/resources/oauth_clients.rb +34 -0
  36. data/lib/knoxcall/resources/opportunities.rb +61 -0
  37. data/lib/knoxcall/resources/pki.rb +41 -0
  38. data/lib/knoxcall/resources/roles.rb +27 -0
  39. data/lib/knoxcall/resources/routes.rb +53 -0
  40. data/lib/knoxcall/resources/secrets.rb +98 -0
  41. data/lib/knoxcall/resources/unwraps_envelope.rb +90 -0
  42. data/lib/knoxcall/resources/vaults.rb +77 -0
  43. data/lib/knoxcall/resources/webhooks.rb +48 -0
  44. data/lib/knoxcall/resources/workflows.rb +86 -0
  45. data/lib/knoxcall/resources/wrap.rb +352 -0
  46. data/lib/knoxcall/route_refusal.rb +67 -0
  47. data/lib/knoxcall/signup.rb +122 -0
  48. data/lib/knoxcall/token_exchange.rb +169 -0
  49. data/lib/knoxcall/ulid.rb +19 -0
  50. data/lib/knoxcall/warnings.rb +63 -0
  51. data/lib/knoxcall/workload_provider.rb +192 -0
  52. data/lib/knoxcall/wrap_faraday_adapter.rb +119 -0
  53. data/lib/knoxcall/wrap_faraday_middleware.rb +67 -0
  54. data/lib/knoxcall/wrap_transport.rb +139 -0
  55. data/lib/knoxcall.rb +45 -1
  56. metadata +70 -9
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: c0e94c9fc8dddb7499ae737f1288460901462ee09a16e054ab8838790053742f
4
- data.tar.gz: 4a60f8582629bd101f4c52e6dc63158d05d7cda054edd12530ec1a7a76311b0a
3
+ metadata.gz: 78a17cfe7bcdbb2f1a56bc7f115d6f75cd4e9d56cde413e27808c9d9bb948fd0
4
+ data.tar.gz: 06ed43b2bd4f26379b89c0aea34c6d057f39a5cc7e5c52b4d9b57deccbb14121
5
5
  SHA512:
6
- metadata.gz: 878547713c90dc595e4a780407a085ec2e0fe6790e725328f0e9d17fd7504822af2d11b41993a18a6a0c0bad07d0da110e5e75eb102c7c479ae74ff4a886b78f
7
- data.tar.gz: 483c686963824b3b52bc94a01cb65b022841b12ec974a308ec1302436c3877aa6051b59cddc657e8fb74e6274e1793061d40643a900fe2d621c0e88e355f6491
6
+ metadata.gz: 5e247d3e650af82c5ee9df3ac668a8736219769a91575facd8a62d397c3316c9a49088c95c36818775df8ef829c026c940147ffb9f512df3bb626cc4be7b65c9
7
+ data.tar.gz: fd40ea3558e70ed9a1d9dd9fdf3ac560c90606582849124c4a02d0ba9c6d35fed8f80a3b216e8f9955f5abac97714625a85d9deb7501d6c1ed0fab13bfefe967
data/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 KnoxCall
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
data/README.md CHANGED
@@ -1,3 +1,440 @@
1
- # knoxcall
1
+ # knoxcall-ruby
2
2
 
3
- This name is reserved by KnoxCall (https://knoxcall.com). The official KnoxCall SDK will be published here. This placeholder contains no code.
3
+ Official KnoxCall API client for Ruby. Standards-based OAuth 2.1 + DPoP (RFC 9449) under the hood, zero dependencies (stdlib only) — your code just calls methods. Ruby >= 3.1.
4
+
5
+ ## Install
6
+
7
+ Not yet published — install from the monorepo path (`gem "knoxcall", path: "../knoxcall-ruby"` in your Gemfile) or via a git checkout (`gem "knoxcall", git: "...", glob: "sdk/knoxcall-ruby/*.gemspec"`).
8
+
9
+ ## Quickstart
10
+
11
+ ```ruby
12
+ require "knoxcall"
13
+
14
+ # Credentials inline — tenant auto-discovered from the credential.
15
+ client = KnoxCall::Client.new(client_id: "tk_xxxxxxxx", client_secret: "...")
16
+
17
+ # Or zero-arg with the environment configured
18
+ # (KNOXCALL_TENANT, KNOXCALL_CLIENT_ID, KNOXCALL_CLIENT_SECRET):
19
+ client = KnoxCall::Client.new
20
+
21
+ # A management call…
22
+ page = client.routes.list
23
+ puts "#{page['meta']['total']} routes"
24
+
25
+ # …and a data-plane call through a route (slug preferred).
26
+ res = client.call("api-orders", path: "/v1/customers")
27
+ customers = JSON.parse(res.body)
28
+ ```
29
+
30
+ The client is Mutex-safe: share a single instance across Puma / Sidekiq threads.
31
+
32
+ ## Authentication
33
+
34
+ Pass credentials as flat constructor options:
35
+
36
+ | Option | Use |
37
+ |---|---|
38
+ | `client_id:` + `client_secret:` | OAuth client-credentials grant (recommended for servers) |
39
+ | `access_token:` / `api_key:` | a pre-acquired token or key — works with `kc_…` tokens and legacy `tk_…`/`AKE…` keys (two spellings, one behavior) |
40
+ | `bootstrap:` | advanced: `ClientCredentials`, `AccessToken`, `OIDCTokenExchange` (workload identity), `StoredCredentials` (a specific credentials file/profile) |
41
+
42
+ Passing conflicting credential options (e.g. `api_key:` and `client_id:`) raises `ArgumentError` at construction. Explicit options always beat the environment.
43
+
44
+ With no explicit credentials, the SDK resolves from the environment in priority order:
45
+
46
+ 1. `KNOXCALL_ACCESS_TOKEN` (or `KNOXCALL_API_KEY`) env var
47
+ 2. Credentials file written by `knoxcall login` (`~/.knoxcall/credentials.json`)
48
+ 3. `KNOXCALL_CLIENT_ID` + `KNOXCALL_CLIENT_SECRET`
49
+
50
+ ### Log in once with the CLI
51
+
52
+ This gem ships the `knoxcall` CLI (`gem install knoxcall`). It signs you in
53
+ once in your browser; every script and worker on the machine picks the
54
+ credential up automatically. No env vars, no keys in code:
55
+
56
+ ```bash
57
+ knoxcall login # opens your browser (PKCE); prints the URL too
58
+ knoxcall login --device # headless/SSH machines: device-code flow
59
+ knoxcall login --profile staging # keep multiple accounts side by side
60
+ knoxcall whoami # show the signed-in tenant
61
+ knoxcall init # wrap-onboarding: confirm tenant + print a quickstart
62
+ knoxcall logout # revoke and remove the stored credential
63
+ ```
64
+
65
+ `knoxcall init` gets you wrapping a provider SDK. With no `--provider` it
66
+ confirms who you are signed in as and prints a two-step quickstart (no writes).
67
+ With `--provider stripe --secret-name wrap-stripe --host api.stripe.com` it moves
68
+ a provider key into KnoxCall custody and prints the gateway `base_url` to point
69
+ your SDK at — the key is read from the `KNOXCALL_WRAP_SECRET` env var (never a
70
+ flag, so it stays out of your shell history) and is never printed. It works
71
+ against the tenant you are already signed in to; it does not provision a tenant.
72
+
73
+ Every KnoxCall SDK (python, node, go, php — and this gem) ships the same
74
+ `knoxcall` executable with the same commands, writing the same
75
+ `~/.knoxcall/credentials.json`, and every SDK reads that file — log in once
76
+ with whichever CLI is on your PATH and all of them are signed in. Two SDKs
77
+ installed side by side colliding on the executable name is harmless by
78
+ construction.
79
+
80
+ ```ruby
81
+ client = KnoxCall::Client.new # zero config — tenant and base URL come from the login
82
+ routes = client.routes.list
83
+ ```
84
+
85
+ Credentials are stored in `~/.knoxcall/credentials.json` (file mode 0600). The
86
+ stored tenant and base URL seed the client automatically; explicit constructor
87
+ options or env vars always win. Access tokens refresh themselves, and refreshes
88
+ are cross-process safe (file lock + atomic rotation of the single-use refresh
89
+ token). If a refresh fails because the credential was revoked or expired, the
90
+ SDK raises `AuthenticationError` telling you to run `knoxcall login` again.
91
+ Select a non-default profile with `KNOXCALL_PROFILE` (or
92
+ `bootstrap: KnoxCall::StoredCredentials.new(profile: "staging")`).
93
+
94
+ ### Environment variables
95
+
96
+ | Variable | Meaning |
97
+ |---|---|
98
+ | `KNOXCALL_TENANT` | tenant slug (optional — auto-discovered from the credential when unset) |
99
+ | `KNOXCALL_ENVIRONMENT` | default environment for data-plane calls |
100
+ | `KNOXCALL_CLIENT_ID` / `KNOXCALL_CLIENT_SECRET` | client-credentials grant |
101
+ | `KNOXCALL_ACCESS_TOKEN` / `KNOXCALL_API_KEY` | pre-acquired token (ACCESS_TOKEN wins) |
102
+ | `KNOXCALL_BASE_URL` | management API base override (legacy alias: `KNOXCALL_API_BASE_URL`) |
103
+ | `KNOXCALL_PROXY_BASE_URL` | data-plane base override |
104
+ | `KNOXCALL_CREDENTIALS_FILE` | credentials file path override (default `~/.knoxcall/credentials.json`) |
105
+ | `KNOXCALL_PROFILE` | credentials-file profile to use (default `default`) |
106
+
107
+ Pass `sandbox: true` to target the isolated Test data plane (`sandbox.knoxcall.com` management host, `sandbox-{tenant}.knoxcall.com` proxy host) with a `tk_test_` key.
108
+
109
+ ### Security notes
110
+
111
+ - **A pre-acquired `access_token:` / `api_key:` is not auto-renewed.** It carries no refresh token, so the SDK sends it as-is until the server rejects it with a 401 — there is no silent refresh. For durable, self-renewing auth use `client_id:` + `client_secret:` (client-credentials) or log in with `knoxcall login` (the stored refresh token is rotated for you under a cross-process lock).
112
+ - **Plaintext transport is flagged.** If the resolved management base URL *or* the data-plane proxy URL is `http://` to a non-loopback host, the client emits a one-time warning to `$stderr` that credentials and tokens will be sent unencrypted. `http://localhost` (and other loopback addresses) is the normal dev case and stays silent — use `https://` everywhere else.
113
+ - **Loose credentials-file permissions are flagged.** On POSIX, if `~/.knoxcall/credentials.json` is readable by group or other, the SDK warns once to `chmod 600` it (it holds a refresh token). The check is skipped on Windows, where confidentiality rests on the `%USERPROFILE%` ACL rather than mode bits. These warnings never raise and never change behavior.
114
+
115
+ ## DPoP — sender-constrained tokens
116
+
117
+ For higher-security tenants, enable DPoP (RFC 9449):
118
+
119
+ ```ruby
120
+ client = KnoxCall::Client.new(tenant: "acme", dpop: "always")
121
+ ```
122
+
123
+ The SDK generates an ES256 keypair, binds the access token to it via the `cnf.jkt` claim, and signs a fresh proof JWT per request — token, management, and data-plane alike. Stolen tokens become useless without the keypair.
124
+
125
+ In the default `"auto"` mode the SDK starts with plain Bearer tokens and upgrades to DPoP automatically when the OAuth client record has `require_dpop` set (the token endpoint answers `invalid_dpop_proof`; the SDK generates a keypair, retries once, and operates as DPoP from then on). `dpop: "never"` opts out — if the server issues a DPoP-bound token anyway, the SDK raises `KnoxCall::TokenError` rather than 401-looping.
126
+
127
+ ## Data plane
128
+
129
+ `client.call` proxies a request through a KnoxCall route to your upstream and returns the raw `Net::HTTPResponse` — the upstream's status belongs to you; the SDK never turns it into an error. Reference routes by **slug** — the write-once machine handle set on the route. Slugs are immutable (rename-proof, unlike names) and portable across tenants (unlike UUIDs). UUIDs also work; bare names are legacy.
130
+
131
+ ```ruby
132
+ # GET
133
+ res = client.call("api-orders", path: "/users")
134
+
135
+ # POST with a body, targeting a specific environment
136
+ res = client.call("api-orders",
137
+ method: "POST",
138
+ path: "/v1/charges",
139
+ body: { amount: 2000, currency: "usd" },
140
+ environment: "staging")
141
+
142
+ res.code # => "201"
143
+ res.body # raw body string
144
+ ```
145
+
146
+ `path` is the **upstream** path. On a KnoxCall cloud tenant host the data plane is served under `/api` (`https://{tenant}.knoxcall.com/api/<path>`); the SDK adds that prefix itself whenever the proxy base is a cloud tenant host with no path of its own, and uses any other base verbatim (self-hosted, or an override that already carries a path). So `/api/v2/tickets` reaches an upstream path that itself begins with `/api`.
147
+
148
+ A per-call `timeout:` overrides the client default.
149
+
150
+ ### Bound routes
151
+
152
+ State the route (and optional defaults) once with `client.route`, then use plain HTTP verbs:
153
+
154
+ ```ruby
155
+ printnode = client.route("api-printnode", environment: "production")
156
+
157
+ res = printnode.get("/computers")
158
+ res = printnode.post("/printjobs", body: job)
159
+ res = printnode.request("DELETE", "/printjobs/42")
160
+ # per-call options still override the bound defaults:
161
+ res = printnode.get("/computers", environment: "staging")
162
+ ```
163
+
164
+ The handle holds no state beyond the defaults — retries, token refresh, and 401 re-mint behave exactly as on `call`.
165
+
166
+ ### Ephemeral proxy
167
+
168
+ One-shot proxying without a pre-configured route — the proxy resolves `{{ token: "..." }}` expressions in flight:
169
+
170
+ ```ruby
171
+ res = client.ephemeral("https://api.stripe.com/v1/charges", method: "POST", body: payload)
172
+ ```
173
+
174
+ ### Route-aware interception (preview)
175
+
176
+ Send an untouched third-party SDK's traffic through the Route that covers it —
177
+ and through the ephemeral proxy where no Route does — with no per-SDK wiring:
178
+
179
+ ```ruby
180
+ knox = KnoxCall::Client.new(api_key: api_key)
181
+ stop = knox.wrap.intercept!(hosts: ["api.resend.com"]) # hosts with NO Route still covered (ephemeral)
182
+ stop.ready # first manifest loaded
183
+
184
+ Net::HTTP.get(URI("https://api.hubapi.com/crm/v3/objects/contacts")) # any Net::HTTP caller, via the covering Route
185
+ stop.uninstall
186
+ ```
187
+
188
+ Per request: the kill switch (`KNOXCALL_INTERCEPT=off`), KnoxCall's own hosts
189
+ and route-around rules go direct; a Route in the manifest covering host + path
190
+ goes through that Route (the Route injects the stored secret — no provider
191
+ credential travels); a host in `hosts:` with no Route goes through the
192
+ ephemeral proxy; everything else is untouched. Turn a Route's **Intercept**
193
+ toggle on and it takes effect on the next request after the 60 s TTL, or on
194
+ the next refusal, with no code change. Per-host options:
195
+ `hosts: { "api.resend.com" => { credential: { secret: "resend-key" } } }`
196
+ (escrow) or `{ unavailable: :direct }` (transit only: send direct when
197
+ KnoxCall is unreachable; the default is fail closed). `require_context: true`
198
+ limits interception to code inside `knox.wrap.routed { }`.
199
+
200
+ `intercept!` is **opt-in and experimental**: it prepends `Net::HTTP#request`,
201
+ which reaches Faraday's default adapter, `rest-client`, `httparty` and raw
202
+ Net::HTTP. Not reached: Typhoeus, Curb, `http.rb` (their own socket layer) —
203
+ point those SDKs at `gateway_url`. The same decisions are available without
204
+ the process-wide seam: `knox.wrap.faraday_connection(routes: :auto)` for an
205
+ SDK that takes an injected connection (controls on `conn.knoxcall`), and
206
+ `conn.builder.insert_before(Faraday::Adapter, *knox.wrap.faraday_middleware(hosts: [...]))`
207
+ for a stack the SDK builds itself.
208
+
209
+ This is a convenience, not a security boundary: it patches a process global
210
+ and composes with other Net::HTTP patchers (WebMock, APM agents) in install
211
+ order. Route mode is the custody path — the key never enters your process.
212
+
213
+ #### What the SDK reports about uncovered calls, and how to turn it off
214
+
215
+ **Reporting is on by default.** When the interceptor sends a call direct
216
+ because no Route covers its host and you did not list the host, and that call
217
+ carries a credential header (`Authorization`, `X-Api-Key`, or any name ending
218
+ in `-api-key`, `-token`, `-secret` or `-auth`), the SDK counts it. About once a
219
+ minute, the SDK reports the counts to KnoxCall
220
+ (`POST /v1/wrap/egress-observations`) with its own credential. The dashboard
221
+ uses the report to show which credentials still leave your process outside
222
+ KnoxCall custody.
223
+
224
+ **What is sent.** Each report carries the host, the first path segment, the
225
+ method, the credential header's **name**, a count, and first/last-seen times.
226
+ The header's **value** is never sent, and neither are the query string, the
227
+ body, or any deeper path.
228
+
229
+ **How to turn it off.** Pass `observe_uncovered: false` when you install, or set
230
+ `KNOXCALL_OBSERVE_UNCOVERED=off` in the environment. Nothing is reported while
231
+ `KNOXCALL_INTERCEPT=off`. If your key lacks `routes:read`, the first report is
232
+ refused, you get one warning, and reporting stops. `on_observation_flush:` receives the
233
+ server's `{accepted, dropped}` after each report.
234
+
235
+ ## Pagination
236
+
237
+ The server wraps every JSON response in `{data, meta}` and paginates with `page`/`per_page` (default 20, cap 100). Single-object methods return the unwrapped Hash; paginated lists return the envelope; a few endpoints (environments, agents, crypto keys, PKI, dynamic-DB, OAuth clients, client credentials, route environments) return plain Arrays and take no page params.
238
+
239
+ ```ruby
240
+ page = client.secrets.list(page: 2, per_page: 50)
241
+ page["data"] # => [...]
242
+ page["meta"]["total"] # => 137
243
+ page["meta"]["total_pages"] # => 3
244
+ page["meta"]["request_id"] # for support
245
+
246
+ # Walk every page transparently — block form or lazy Enumerator:
247
+ client.secrets.each { |secret| puts secret["name"] }
248
+ names = client.secrets.each.map { |s| s["name"] }
249
+ first_ten = client.routes.each(per_page: 5).take(10) # fetches only 2 pages
250
+ ```
251
+
252
+ `each` fetches page by page until `page >= meta.total_pages` (or an empty page). Sub-lists have `each_*` twins: `routes.each_log(id)`, `webhooks.each_log(id)`, `vaults.each_token(name)`.
253
+
254
+ ## Resources
255
+
256
+ One-liner per area:
257
+
258
+ ```ruby
259
+ # Routes
260
+ route = client.routes.create(name: "orders", target_base_url: "https://api.example.com")
261
+ logs = client.routes.get_logs(route["id"])
262
+
263
+ # Route field-actions (declarative field-level encrypt/tokenize on the proxy path)
264
+ action = client.routes.create_action(route["id"], direction: "request", action: "tokenize",
265
+ selectors: ["$.card.number"], key_name: "cards-vault")
266
+
267
+ # Secrets
268
+ secret = client.secrets.create(name: "STRIPE_KEY", value: "sk_live_...")
269
+ client.secrets.set_value(secret["id"], value: "sk_live_rotated", environment: "production")
270
+
271
+ # OAuth2 provider secret (proxy injects the provider's access token upstream)
272
+ oauth = client.secrets.create_oauth2(name: "GITHUB", provider: "github",
273
+ client_id: "cid", client_secret: "csec",
274
+ scopes: ["repo"])
275
+ # Certificate / mTLS secret (certificate_type defaults to "pem")
276
+ cert = client.secrets.create_certificate(name: "UPSTREAM_MTLS",
277
+ certificate_content: pem, private_key: key)
278
+
279
+ # Webhooks (create returns the once-only "secret_key" — store it)
280
+ wh = client.webhooks.create(name: "orders-hook", url: "https://hooks.example.com/knox",
281
+ event_types: ["request.error"])
282
+ types = client.webhooks.list_event_types
283
+ result = client.webhooks.test(wh["id"])
284
+
285
+ # Clients (calling machines) + credentials
286
+ kc = client.clients.create(name: "ci-runner", type: "server", ip_address: "203.0.113.9")
287
+ creds = client.clients.list_credentials(kc["id"])
288
+
289
+ # OAuth clients ("client_secret" shown once; "warning" carries the server's top-level warning)
290
+ oc = client.oauth_clients.create(name: "svc")
291
+
292
+ # Environments (bare array — no pagination)
293
+ envs = client.environments.list
294
+
295
+ # API keys (create returns the once-only plaintext "api_key")
296
+ key = client.api_keys.create(name: "deploy-bot")
297
+
298
+ # Account
299
+ acct = client.account.get
300
+ usage = client.account.get_usage
301
+
302
+ # Audit logs
303
+ client.audit_logs.each(action: "secret.create") { |row| puts row["created_at"] }
304
+
305
+ # Agents ("agent_secret" shown once)
306
+ agent = client.agents.create("warehouse-agent")
307
+
308
+ # Crypto — keyed transit encryption
309
+ enc = client.crypto.encrypt("payments-key", plaintext: "hello")
310
+ dec = client.crypto.decrypt("payments-key", ciphertext: enc["ciphertext"], format: "utf8")
311
+
312
+ # Crypto — portable kc: encryption (structure-preserving, zero-config default key)
313
+ sealed = client.crypto.encrypt_data({ card: "4242..." })
314
+ opened = client.crypto.decrypt_data(sealed["ciphertext"])
315
+ meta = client.crypto.inspect("kc:1:enc:...")
316
+ bundle = client.crypto.get_sealing_bundle # public bits for browser-side sealing
317
+ cap = client.crypto.mint_client_token(action: "decrypt", data: "kc:1:enc:...")
318
+
319
+ # PKI (cert + CRL are raw text, not JSON)
320
+ root = client.pki.create_root("internal", { common_name: "Acme Internal CA" })
321
+ pem = client.pki.get_root_cert("internal")
322
+ leaf = client.pki.issue_cert("internal", "servers", common_name: "db.acme.internal")
323
+
324
+ # Vaults (tokenization)
325
+ vault = client.vaults.create(name: "cards-vault")
326
+ tok = client.vaults.tokenize("cards-vault", value: "4242424242424242")
327
+ val = client.vaults.detokenize("cards-vault", tok["token"])
328
+
329
+ # AI Gateway (secret -> gateway -> agent -> capability token).
330
+ # provider + upstream_secret_id compose the upstream route. An agent created
331
+ # with NEITHER those nor primary_route_id has no upstream and 502s on its first
332
+ # data-plane call. provider is a plain string — the catalog is server-side,
333
+ # and a bad value returns a 400 naming the valid set.
334
+ secret = client.secrets.create(name: "anthropic-key", value: ENV["ANTHROPIC_API_KEY"])
335
+ gw = client.ai_gateway.create_gateway(name: "Prod", slug: "prod", budget_daily_usd: 50)
336
+ agent = client.ai_gateway.create_agent(gw["id"], name: "copilot", slug: "copilot",
337
+ provider: "anthropic", upstream_secret_id: secret["id"],
338
+ default_model: "claude-sonnet-5")
339
+ minted = client.ai_gateway.mint_token(agent["id"], kind: "agent")
340
+ # minted["token"] is the plaintext capability token — shown exactly once.
341
+ # agent["agent_url"] is the base_url to point an AI SDK at.
342
+
343
+ # Dynamic DB credentials
344
+ minted = client.dynamic_db.mint("main-pg", "readonly")
345
+ leases = client.dynamic_db.list_leases
346
+
347
+ # Signup — credential-less, no client needed. Two steps: signup returns a claim
348
+ # handle and emails a sign-in link; claim_signup collects the key once clicked.
349
+ accepted = KnoxCall.signup({ email: "dev@example.com", tenant_name: "Acme Inc" })
350
+ claim = KnoxCall.claim_signup(accepted["claim_handle"]) # poll until status == "ready"
351
+ # claim["starter"]["api_key"]["api_key"] is shown exactly once — store it now.
352
+ ```
353
+
354
+ ## Wrapping third-party SDKs
355
+
356
+ Route an *official* third-party SDK's traffic through KnoxCall so its provider key leaves your codebase — the SDK keeps its own serialization, retries, idempotency keys, and error types; only its HTTP transport is swapped. Two halves:
357
+
358
+ **Escrow (all SDKs).** Hand the raw provider key to KnoxCall once; afterwards it is referenced by name and injected by the proxy.
359
+
360
+ ```ruby
361
+ client.wrap.escrow(provider: "stripe", name: "stripe-live",
362
+ value: "sk_live_...", hosts: ["api.stripe.com"])
363
+ ```
364
+
365
+ **Transport (Faraday-based SDKs only).** `wrap.faraday_connection` returns a `Faraday::Connection` whose transport re-targets each request through KnoxCall's ephemeral proxy in transparent mode — the Ruby analogue of the Node SDK's `wrap.fetch()`. Hand it to any SDK that accepts an **injected Faraday connection**.
366
+
367
+ ```ruby
368
+ conn = client.wrap.faraday_connection(url: "https://api.example.com")
369
+ sdk = SomeSDK.new(connection: conn) # the SDK's own injection point
370
+ ```
371
+
372
+ - **Transit mode (default)** lifts the wrapped SDK's own `Authorization` header out-of-band (never forwarded raw, never logged), with a both-must-agree Test/Live check against the client's `sandbox:` flag.
373
+ - **Escrow mode** (`credential: { secret: "stripe-live" }`) keeps the raw key in KnoxCall custody — only the escrowed name travels.
374
+ - **Route-around**: raw-card (PCI) endpoints are sent to the provider **directly**, untouched, by default; extend with `route_around:` and observe with `on_route_around:`.
375
+ - **Promoted routes**: after you promote wrapped traffic to a durable route, pass `route: "<slug>"`, or opt into `auto_switch: true` (surfaced via `on_promoted:`).
376
+
377
+ Requires the optional [`faraday`](https://rubygems.org/gems/faraday) gem — **KnoxCall itself has no runtime dependency on it** (`gem "faraday"` in your Gemfile); a clear `KnoxCall::Error` is raised if it is missing.
378
+
379
+ > **Limitation.** Ruby has **no production-safe *generic* transport seam** (intercepting `Net::HTTP` globally is monkey-patching, deliberately refused). So `faraday_connection` works **only** with SDKs that let you inject a Faraday connection. An SDK that builds its own connection internally, or exposes only a **base-URL override** (Resend, Mailgun, Airtable, …), cannot use it — mint a base-URL gateway with `wrap.gateway_url` instead:
380
+
381
+ ```ruby
382
+ gw = client.wrap.gateway_url(secret: "stripe-live", host: "api.stripe.com")
383
+ resend = Resend::Client.new(api_key: "placeholder", base_url: gw["base_url"])
384
+ ```
385
+
386
+ ## Webhook verification
387
+
388
+ `KnoxCall::Client.construct_event` (also available as `client.construct_event` and `client.webhooks.construct_event`) verifies the delivery's HMAC-SHA256 signature and parses it into an event Hash in one step. Pass the raw body string — never re-serialized JSON.
389
+
390
+ ```ruby
391
+ post "/webhooks/knoxcall" do
392
+ # Rack exposes inbound headers in request.env as HTTP_-prefixed CGI keys
393
+ # (HTTP_X_WEBHOOK_SIGNATURE); construct_event wants real header names, so
394
+ # strip the prefix and restore dashes.
395
+ headers = request.env
396
+ .select { |k, _| k.start_with?("HTTP_") }
397
+ .transform_keys { |k| k.sub(/\AHTTP_/, "").tr("_", "-") }
398
+ event = KnoxCall::Client.construct_event(request.body.read, headers, ENDPOINT_SECRET)
399
+
400
+ case event["event"]
401
+ when "audit.event"
402
+ log.info "audit: #{event['data']['action']}"
403
+ else # request.*
404
+ log.info "#{event['data']['route_name']} -> #{event['data']['response']['status']}"
405
+ end
406
+ 200
407
+ rescue KnoxCall::WebhookSignatureVerificationError
408
+ halt 400, "bad signature"
409
+ end
410
+ ```
411
+
412
+ Formats beyond the default `legacy` header (`stripe`, `github`, `slack`, `aws-sns`, `custom`) are selected with `format:`; the replay window defaults to 300s (`tolerance_seconds: nil` disables it); `custom` requires `header_name:`. All comparisons are constant-time. The boolean `verify_signature` helper remains for existing code.
413
+
414
+ ## Errors
415
+
416
+ All API failures are typed subclasses of `KnoxCall::Error`:
417
+
418
+ ```ruby
419
+ begin
420
+ client.secrets.create(name: "orders", value: secret)
421
+ rescue KnoxCall::RateLimitError => e
422
+ sleep e.retry_after || 1
423
+ rescue KnoxCall::ConflictError => e
424
+ logger.warn "already exists: #{e.code}" # 409 — do not blind-retry
425
+ rescue KnoxCall::ValidationError => e
426
+ logger.warn "invalid: #{e.fields.inspect}" # 422 — per-field breakdown when present
427
+ rescue KnoxCall::APIError => e
428
+ logger.error "#{e.status_code} #{e.code}: #{e.message} (request #{e.request_id})"
429
+ end
430
+ ```
431
+
432
+ Every `APIError` exposes `status_code`, `headers`, `body`, `code`/`type` (the server's
433
+ machine-readable error code) and `request_id` (the `X-Request-Id` correlation id, header
434
+ first then body) — branch on `e.code` rather than string-matching the message.
435
+
436
+ Hierarchy: `AuthenticationError` (401), `PermissionDeniedError` (403), `NotFoundError` (404), `ConflictError` (409), `ValidationError` (422, with `fields`), `RateLimitError` (429, with `retry_after`), `ServerError` (5xx), all under `APIError`; plus `SignupError` (with `status_code`/`error_type`/`request_id`), `WebhookSignatureVerificationError`, `TokenError`, and `NetworkError`/`ConnectionTimeoutError` for transport failures.
437
+
438
+ ## Retries & idempotency
439
+
440
+ Management requests retry automatically on transport errors and HTTP 408/429/500/502/503/504 (never 409 — a real conflict does not resolve by replaying), with exponential half-jitter backoff and `Retry-After` honored up to 30s. Every mutating request carries a ULID `X-Idempotency-Key` that stays stable across retries, so replays are safe. A 401 purges the cached token and retries once with fresh credentials. Data-plane calls never replay a mutating request after it may have reached the wire. Tune with `retry_max_attempts:`, `retry_base_delay:`, `retry_max_delay:`.
data/exe/knoxcall ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ # KnoxCall CLI — sign in once, every KnoxCall SDK on this machine picks it up.
5
+
6
+ require "knoxcall/cli"
7
+
8
+ exit KnoxCall::CLI.run(ARGV)