scanii-ruby 0.0.1 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: a216ea149bec56b29bd6b1a9337b07c31084a9387aaf74be336b6e0c08a53145
4
- data.tar.gz: 24b8201eb8ed2cf9596ab5ca94850107f908b2268dc59edc6dc0f9c78d099db3
3
+ metadata.gz: 0e3c62870b928231999c133d889594f002682b74b34769c5741dbfe9a9c12693
4
+ data.tar.gz: a1673812fa7c2e46fa12657a3898fb01fdf56399c04146e95dfdf048d12ef185
5
5
  SHA512:
6
- metadata.gz: b4e5e75b11d1989195d0d46399ad9e906883bb06bba7b8040cc32931b8cfee9347a3bcac01e571671bcb619a97f5be368b9bf41855ad837053b789468a3a96b8
7
- data.tar.gz: d8df27af608f542892c73a4b2a93de77a3032e4d5f1f0a3e978df73164185caac083290bea6b0f6a8102b7847810ce36eb3b565d80ec2c558b9b95312626f127
6
+ metadata.gz: 1afa93f5a49873f5813dbf9701d5886b173a3e3d5dbdda9d214690308eb77d92b8ff96bde66b6fa78b2f455af32d317bf8e1ce1338824fa0a5801f2dbe4786cd
7
+ data.tar.gz: 6ed39afbb9846cec5916f8a77c8119a717f6e5c6e6da81dd17756a456fa069735063a20762a772090400d09b1e4fd85c883a92176beecf36479fe10d38ae7bd4
data/CHANGELOG.md ADDED
@@ -0,0 +1,35 @@
1
+ # Changelog
2
+
3
+ All notable changes to `scanii-ruby` are documented here. Versions follow [SemVer](https://semver.org).
4
+
5
+ ## 1.0.1 — Release infrastructure fix
6
+
7
+ Wires up `bundler/gem_tasks` in the Rakefile so `bundle exec rake release` (invoked by `rubygems/release-gem@v1`) resolves correctly. v1.0.0 was tagged but never published to RubyGems because the release workflow failed at the `rake release` task lookup; v1.0.1 is functionally identical to that tag. No SDK behavior changes.
8
+
9
+ ## 1.0.0 — Initial release
10
+
11
+ First public release of the Scanii Ruby SDK on RubyGems as `scanii-ruby` (the plain `scanii` gem name is held by an abandoned third-party gem; this SDK uses the `scanii-ruby` convention matching `twilio-ruby`). Supersedes the `scanii-ruby 0.0.1` namespace-reservation placeholder.
12
+
13
+ Reference implementation frozen at scanii-java v8.0.0.
14
+
15
+ ### API surface
16
+
17
+ - `Scanii::Client#process(file_path, metadata:, callback:)` → `Scanii::ProcessingResult`
18
+ - `Scanii::Client#process_async(file_path, metadata:, callback:)` → `Scanii::PendingResult`
19
+ - `Scanii::Client#fetch(url, metadata:, callback:)` → `Scanii::PendingResult`
20
+ - `Scanii::Client#retrieve(id)` → `Scanii::ProcessingResult`
21
+ - `Scanii::Client#ping` → `true`
22
+ - `Scanii::Client#create_auth_token(timeout_seconds)` → `Scanii::AuthToken`
23
+ - `Scanii::Client#retrieve_auth_token(id)` → `Scanii::AuthToken`
24
+ - `Scanii::Client#delete_auth_token(id)` → `true`
25
+
26
+ Errors: `Scanii::Error` (base), `Scanii::AuthError` (401/403), `Scanii::RateLimitError` (429, with `retry_after`).
27
+
28
+ ### Highlights
29
+
30
+ - **Zero runtime dependencies.** Stdlib `net/http` + `json` + `securerandom` + `base64` only.
31
+ - **Hand-rolled multipart/form-data encoder** (no `multipart-post`, no `rack-mime`).
32
+ - **Synchronous.** Single-threaded by default; create one `Scanii::Client` per thread.
33
+ - **Targets Ruby 3.4+.**
34
+ - **scanii-cli** integration tests cover Linux / macOS / Windows on Ruby 3.4 and 4.0 without burning real Scanii credits. (Ruby 3.5 was preview-only and has no rubyinstaller2 build for Windows.)
35
+ - **OIDC trusted publishing** to RubyGems via `rubygems/release-gem` — no long-lived API key in repo secrets.
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
95
+ Derivative 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
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying 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 [yyyy] [name of copyright owner]
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,5 +1,134 @@
1
- # scanii-ruby (placeholder)
1
+ # scanii-ruby
2
2
 
3
- The official Scanii Ruby SDK is being released as `scanii-ruby` v1.0.0 shortly.
3
+ Official Ruby SDK for the [Scanii](https://www.scanii.com) content security API.
4
4
 
5
- In the meantime, see [scanii.com](https://scanii.com) and [github.com/scanii/scanii-ruby](https://github.com/scanii/scanii-ruby).
5
+ [![Gem Version](https://img.shields.io/gem/v/scanii-ruby.svg)](https://rubygems.org/gems/scanii-ruby)
6
+
7
+ > **Looking for `scanii`?** That gem name is held by an abandoned third-party gem. The official Scanii Ruby SDK is published as **`scanii-ruby`** (matching the [`twilio-ruby`](https://rubygems.org/gems/twilio-ruby) convention).
8
+
9
+ ## SDK Principles
10
+
11
+ 1. **Light.** Zero runtime dependencies, stdlib only.
12
+ 2. **Up to date.** Always current with the latest Scanii API.
13
+ 3. **Integration-only.** Wraps the REST API — retries, concurrency, and batching are the caller's responsibility.
14
+
15
+ ## Install
16
+
17
+ Add to your `Gemfile`:
18
+
19
+ ```ruby
20
+ gem "scanii-ruby", "~> 1.0"
21
+ ```
22
+
23
+ Or install directly:
24
+
25
+ ```bash
26
+ gem install scanii-ruby
27
+ ```
28
+
29
+ Targets Ruby 3.4+. Zero runtime dependencies.
30
+
31
+ ## Quickstart
32
+
33
+ ```ruby
34
+ require "scanii"
35
+
36
+ client = Scanii::Client.new(key: "your-key", secret: "your-secret")
37
+
38
+ result = client.process("./file.pdf")
39
+ puts "findings: #{result.findings.inspect}"
40
+ ```
41
+
42
+ `findings` is an `Array<String>`. An empty array means the content is clean.
43
+
44
+ ## API
45
+
46
+ | Method | REST | Returns |
47
+ |---|---|---|
48
+ | `process(file_path, metadata:, callback:)` | `POST /files` | `Scanii::ProcessingResult` |
49
+ | `process_async(file_path, metadata:, callback:)` | `POST /files/async` | `Scanii::PendingResult` |
50
+ | `fetch(url, metadata:, callback:)` | `POST /files/fetch` | `Scanii::PendingResult` |
51
+ | `retrieve(id)` | `GET /files/{id}` | `Scanii::ProcessingResult` |
52
+ | `ping` | `GET /ping` | `true` |
53
+ | `create_auth_token(timeout_seconds)` | `POST /auth/tokens` | `Scanii::AuthToken` |
54
+ | `retrieve_auth_token(id)` | `GET /auth/tokens/{id}` | `Scanii::AuthToken` |
55
+ | `delete_auth_token(id)` | `DELETE /auth/tokens/{id}` | `true` |
56
+
57
+ Full API reference: <https://scanii.github.io/openapi/v22/>.
58
+
59
+ ## Regional endpoints
60
+
61
+ ```ruby
62
+ client = Scanii::Client.new(
63
+ key: "k",
64
+ secret: "s",
65
+ endpoint: "https://api-eu1.scanii.com"
66
+ )
67
+ ```
68
+
69
+ | Region | Endpoint |
70
+ |---|---|
71
+ | Auto (default) | `https://api.scanii.com` |
72
+ | US 1 | `https://api-us1.scanii.com` |
73
+ | EU 1 | `https://api-eu1.scanii.com` |
74
+ | EU 2 | `https://api-eu2.scanii.com` |
75
+ | AP 1 | `https://api-ap1.scanii.com` |
76
+ | AP 2 | `https://api-ap2.scanii.com` |
77
+ | CA 1 | `https://api-ca1.scanii.com` |
78
+
79
+ ## Errors
80
+
81
+ ```ruby
82
+ require "scanii"
83
+
84
+ begin
85
+ client.ping
86
+ rescue Scanii::AuthError => e
87
+ warn "bad creds: #{e.message} (request_id=#{e.request_id})"
88
+ rescue Scanii::RateLimitError => e
89
+ warn "rate-limited; retry after #{e.retry_after}s"
90
+ rescue Scanii::Error => e
91
+ warn "other error: #{e.message} (status=#{e.status_code})"
92
+ end
93
+ ```
94
+
95
+ Error hierarchy:
96
+
97
+ - `Scanii::Error` — base class, carries `status_code`, `request_id`, `host_id`, `body`
98
+ - `Scanii::AuthError` — HTTP 401 / 403
99
+ - `Scanii::RateLimitError` — HTTP 429, with `retry_after` (seconds, when the server provided `Retry-After`)
100
+
101
+ Per SDK Principle 3, the SDK does not retry on the caller's behalf — backoff and retry policy belong to your application.
102
+
103
+ ## Auth tokens
104
+
105
+ Mint a short-lived token server-side and authenticate with it from a less-trusted client:
106
+
107
+ ```ruby
108
+ server_client = Scanii::Client.new(key: "k", secret: "s")
109
+ token = server_client.create_auth_token(300)
110
+
111
+ token_client = Scanii::Client.new(token: token.id)
112
+ token_client.ping
113
+ ```
114
+
115
+ ## Local testing with scanii-cli
116
+
117
+ The SDK ships integration tests against [scanii-cli](https://github.com/scanii/scanii-cli), a local mock server. No real Scanii credentials are needed.
118
+
119
+ ```bash
120
+ docker run -d --name scanii-cli -p 4000:4000 ghcr.io/scanii/scanii-cli:latest server
121
+
122
+ bundle install
123
+ bundle exec rake test
124
+ ```
125
+
126
+ Test credentials are `key` / `secret`. Override the endpoint by exporting `SCANII_TEST_ENDPOINT=...` before `rake test`. Integration tests self-skip when scanii-cli is not reachable, so `rake test` is safe to run in any environment.
127
+
128
+ ## Contributing
129
+
130
+ Bug reports and PRs welcome at <https://github.com/scanii/scanii-ruby/issues>.
131
+
132
+ ## License
133
+
134
+ [Apache-2.0](LICENSE).
@@ -0,0 +1,40 @@
1
+ require "json"
2
+
3
+ module Scanii
4
+ # Short-lived auth token returned by Client#create_auth_token and
5
+ # Client#retrieve_auth_token.
6
+ #
7
+ # Pass id back as the token: keyword argument when constructing a Client to
8
+ # authenticate using the token instead of API key + secret.
9
+ #
10
+ # @see https://scanii.github.io/openapi/v22/
11
+ class AuthToken
12
+ attr_reader :id, :creation_date, :expiration_date,
13
+ :request_id, :host_id, :resource_location, :raw_response
14
+
15
+ def initialize(id:, creation_date:, expiration_date:,
16
+ request_id:, host_id:, resource_location:, raw_response:)
17
+ @id = id
18
+ @creation_date = creation_date
19
+ @expiration_date = expiration_date
20
+ @request_id = request_id
21
+ @host_id = host_id
22
+ @resource_location = resource_location
23
+ @raw_response = raw_response
24
+ end
25
+
26
+ def self.from_response(body, headers)
27
+ json = body.nil? || body.empty? ? {} : JSON.parse(body)
28
+
29
+ new(
30
+ id: (json["id"] || "").to_s,
31
+ creation_date: json["creation_date"]&.to_s,
32
+ expiration_date: json["expiration_date"]&.to_s,
33
+ request_id: headers["x-scanii-request-id"],
34
+ host_id: headers["x-scanii-host-id"],
35
+ resource_location: headers["location"],
36
+ raw_response: body
37
+ )
38
+ end
39
+ end
40
+ end
@@ -0,0 +1,271 @@
1
+ require "json"
2
+ require "net/http"
3
+ require "uri"
4
+
5
+ module Scanii
6
+ # Synchronous client for the Scanii REST API v2.2.
7
+ #
8
+ # Construct with either +key:+ + +secret:+ (HTTP Basic Auth) or +token:+
9
+ # (auth-token authentication). Mixing the two raises ArgumentError.
10
+ #
11
+ # Per SDK Principle 3 the client is integration-only: it does not retry,
12
+ # batch, or paginate. Each public method maps to exactly one HTTP request.
13
+ #
14
+ # @see https://scanii.github.io/openapi/v22/
15
+ #
16
+ # @example
17
+ # client = Scanii::Client.new(key: "your-key", secret: "your-secret")
18
+ # result = client.process("./file.pdf")
19
+ # puts result.findings # [] when clean
20
+ class Client
21
+ DEFAULT_ENDPOINT = "https://api.scanii.com".freeze
22
+ DEFAULT_TIMEOUT = 60
23
+ API_VERSION_PATH = "/v2.2".freeze
24
+ USER_AGENT = "scanii-ruby/#{Scanii::VERSION}".freeze
25
+
26
+ attr_reader :endpoint, :timeout, :user_agent
27
+
28
+ # @param key [String, nil] API key (mutually exclusive with token)
29
+ # @param secret [String, nil] API secret (required when key is set)
30
+ # @param token [String, nil] auth-token id (mutually exclusive with key/secret)
31
+ # @param endpoint [String] base URL; defaults to https://api.scanii.com
32
+ # @param timeout [Integer] open + read timeout in seconds; default 60
33
+ # @param user_agent [String, nil] optional fragment prepended to the SDK's default User-Agent
34
+ def initialize(key: nil, secret: nil, token: nil, endpoint: DEFAULT_ENDPOINT,
35
+ timeout: DEFAULT_TIMEOUT, user_agent: nil)
36
+ @auth_header = build_auth_header(key, secret, token)
37
+ @endpoint = endpoint.to_s.sub(%r{/+\z}, "")
38
+ raise ArgumentError, "endpoint must not be empty" if @endpoint.empty?
39
+
40
+ @base_uri = URI.parse("#{@endpoint}#{API_VERSION_PATH}")
41
+ raise ArgumentError, "endpoint must be http(s)" unless %w[http https].include?(@base_uri.scheme)
42
+
43
+ @timeout = Integer(timeout)
44
+ @user_agent = user_agent && !user_agent.empty? ? "#{user_agent} #{USER_AGENT}" : USER_AGENT
45
+ end
46
+
47
+ # Submit a file for synchronous scanning.
48
+ #
49
+ # @see https://scanii.github.io/openapi/v22/ POST /files
50
+ # @return [Scanii::ProcessingResult]
51
+ def process(file_path, metadata: nil, callback: nil)
52
+ assert_readable(file_path)
53
+ fields = build_text_fields(metadata, callback)
54
+ body, content_type = Multipart.encode(fields, file_path)
55
+ status, resp_body, headers = post("/files", body: body, content_type: content_type)
56
+ raise_for_status(status, resp_body, headers) unless status == 201
57
+ ProcessingResult.from_response(resp_body, headers)
58
+ end
59
+
60
+ # Submit a file for server-side asynchronous scanning. Returns a pending
61
+ # id; the final result is delivered to +callback+ (when supplied) or
62
+ # fetched via #retrieve.
63
+ #
64
+ # @see https://scanii.github.io/openapi/v22/ POST /files/async
65
+ # @return [Scanii::PendingResult]
66
+ def process_async(file_path, metadata: nil, callback: nil)
67
+ assert_readable(file_path)
68
+ fields = build_text_fields(metadata, callback)
69
+ body, content_type = Multipart.encode(fields, file_path)
70
+ status, resp_body, headers = post("/files/async", body: body, content_type: content_type)
71
+ raise_for_status(status, resp_body, headers) unless status == 202
72
+ PendingResult.from_response(resp_body, headers)
73
+ end
74
+
75
+ # Ask Scanii to download a remote URL and scan it asynchronously.
76
+ #
77
+ # @see https://scanii.github.io/openapi/v22/ POST /files/fetch
78
+ # @return [Scanii::PendingResult]
79
+ def fetch(url, metadata: nil, callback: nil)
80
+ raise ArgumentError, "url must not be empty" if url.nil? || url.empty?
81
+
82
+ form = { "location" => url }
83
+ form["callback"] = callback if callback && !callback.empty?
84
+ (metadata || {}).each { |k, v| form["metadata[#{k}]"] = v.to_s }
85
+
86
+ status, resp_body, headers = post(
87
+ "/files/fetch",
88
+ body: URI.encode_www_form(form),
89
+ content_type: "application/x-www-form-urlencoded"
90
+ )
91
+ raise_for_status(status, resp_body, headers) unless status == 202
92
+ PendingResult.from_response(resp_body, headers)
93
+ end
94
+
95
+ # Retrieve a previously submitted scan result by id.
96
+ #
97
+ # @see https://scanii.github.io/openapi/v22/ GET /files/{id}
98
+ # @return [Scanii::ProcessingResult]
99
+ def retrieve(id)
100
+ raise ArgumentError, "id must not be empty" if id.nil? || id.empty?
101
+
102
+ status, resp_body, headers = request("GET", "/files/#{url_encode(id)}")
103
+ raise_for_status(status, resp_body, headers) unless status == 200
104
+ ProcessingResult.from_response(resp_body, headers)
105
+ end
106
+
107
+ # Verify that the configured credentials reach the API.
108
+ #
109
+ # @see https://scanii.github.io/openapi/v22/ GET /ping
110
+ # @return [Boolean] true when the API responds 200
111
+ def ping
112
+ status, resp_body, headers = request("GET", "/ping")
113
+ return true if status == 200
114
+
115
+ raise_for_status(status, resp_body, headers)
116
+ end
117
+
118
+ # Mint a short-lived auth token. timeout_seconds must be positive.
119
+ #
120
+ # @see https://scanii.github.io/openapi/v22/ POST /auth/tokens
121
+ # @return [Scanii::AuthToken]
122
+ def create_auth_token(timeout_seconds)
123
+ ts = Integer(timeout_seconds)
124
+ raise ArgumentError, "timeout_seconds must be positive" if ts <= 0
125
+
126
+ status, resp_body, headers = post(
127
+ "/auth/tokens",
128
+ body: URI.encode_www_form("timeout" => ts),
129
+ content_type: "application/x-www-form-urlencoded"
130
+ )
131
+ raise_for_status(status, resp_body, headers) unless [200, 201].include?(status)
132
+ AuthToken.from_response(resp_body, headers)
133
+ end
134
+
135
+ # Inspect a previously created auth token.
136
+ #
137
+ # @see https://scanii.github.io/openapi/v22/ GET /auth/tokens/{id}
138
+ # @return [Scanii::AuthToken]
139
+ def retrieve_auth_token(id)
140
+ raise ArgumentError, "id must not be empty" if id.nil? || id.empty?
141
+
142
+ status, resp_body, headers = request("GET", "/auth/tokens/#{url_encode(id)}")
143
+ raise_for_status(status, resp_body, headers) unless status == 200
144
+ AuthToken.from_response(resp_body, headers)
145
+ end
146
+
147
+ # Revoke an auth token.
148
+ #
149
+ # @see https://scanii.github.io/openapi/v22/ DELETE /auth/tokens/{id}
150
+ # @return [Boolean] true on 204
151
+ def delete_auth_token(id)
152
+ raise ArgumentError, "id must not be empty" if id.nil? || id.empty?
153
+
154
+ status, resp_body, headers = request("DELETE", "/auth/tokens/#{url_encode(id)}")
155
+ raise_for_status(status, resp_body, headers) unless status == 204
156
+ true
157
+ end
158
+
159
+ private
160
+
161
+ def build_auth_header(key, secret, token)
162
+ if token && !token.empty?
163
+ raise ArgumentError, "supply either token: or key:+secret:, not both" if key || secret
164
+
165
+ "Basic #{base64_encode("#{token}:")}"
166
+ else
167
+ raise ArgumentError, "key must be set (or use token: for auth-token mode)" if key.nil? || key.empty?
168
+ raise ArgumentError, "key must not contain a colon" if key.include?(":")
169
+ raise ArgumentError, "secret must be set when using key auth" if secret.nil? || secret.empty?
170
+
171
+ "Basic #{base64_encode("#{key}:#{secret}")}"
172
+ end
173
+ end
174
+
175
+ # Stdlib-only base64. Array#pack("m0") emits RFC 4648 base64 with no
176
+ # newlines -- identical output to Base64.strict_encode64 -- without
177
+ # requiring the unbundled `base64` gem on Ruby 3.4+.
178
+ def base64_encode(value)
179
+ [value].pack("m0")
180
+ end
181
+
182
+ def assert_readable(path)
183
+ raise ArgumentError, "file at #{path} is not readable" unless File.file?(path) && File.readable?(path)
184
+ end
185
+
186
+ def build_text_fields(metadata, callback)
187
+ fields = {}
188
+ (metadata || {}).each { |k, v| fields["metadata[#{k}]"] = v.to_s }
189
+ fields["callback"] = callback if callback && !callback.empty?
190
+ fields
191
+ end
192
+
193
+ def post(path, body:, content_type:)
194
+ request("POST", path, body: body, content_type: content_type)
195
+ end
196
+
197
+ def request(method, path, body: nil, content_type: nil)
198
+ uri = URI.parse("#{@base_uri}#{path}")
199
+
200
+ req = build_request(method, uri, body, content_type)
201
+
202
+ Net::HTTP.start(uri.hostname, uri.port,
203
+ use_ssl: uri.scheme == "https",
204
+ open_timeout: @timeout,
205
+ read_timeout: @timeout) do |http|
206
+ response = http.request(req)
207
+ headers = capture_headers(response)
208
+ [response.code.to_i, response.body.to_s, headers]
209
+ end
210
+ rescue Errno::ECONNREFUSED, Errno::ECONNRESET, Net::OpenTimeout, Net::ReadTimeout, SocketError => e
211
+ raise Scanii::Error, "transport error: #{e.class}: #{e.message}"
212
+ end
213
+
214
+ def build_request(method, uri, body, content_type)
215
+ klass = case method
216
+ when "GET" then Net::HTTP::Get
217
+ when "POST" then Net::HTTP::Post
218
+ when "DELETE" then Net::HTTP::Delete
219
+ else raise ArgumentError, "unsupported method: #{method}"
220
+ end
221
+
222
+ req = klass.new(uri.request_uri)
223
+ req["Authorization"] = @auth_header
224
+ req["User-Agent"] = @user_agent
225
+ req["Accept"] = "application/json"
226
+ req["Content-Type"] = content_type if content_type
227
+ req.body = body if body
228
+ req
229
+ end
230
+
231
+ def capture_headers(response)
232
+ headers = {}
233
+ response.each_header { |name, value| headers[name.downcase] = value }
234
+ headers
235
+ end
236
+
237
+ def raise_for_status(status, body, headers)
238
+ request_id = headers["x-scanii-request-id"]
239
+ host_id = headers["x-scanii-host-id"]
240
+ message = extract_error_message(body) || "HTTP #{status}"
241
+
242
+ case status
243
+ when 401, 403
244
+ raise Scanii::AuthError.new(message, status_code: status, request_id: request_id,
245
+ host_id: host_id, body: body)
246
+ when 429
247
+ retry_after = headers["retry-after"]&.to_i
248
+ raise Scanii::RateLimitError.new(message, status_code: status, request_id: request_id,
249
+ host_id: host_id, body: body, retry_after: retry_after)
250
+ else
251
+ raise Scanii::Error.new(message, status_code: status, request_id: request_id,
252
+ host_id: host_id, body: body)
253
+ end
254
+ end
255
+
256
+ def extract_error_message(body)
257
+ return nil if body.nil? || body.empty?
258
+
259
+ decoded = JSON.parse(body)
260
+ return decoded["error"].to_s if decoded.is_a?(Hash) && decoded["error"].is_a?(String)
261
+
262
+ body
263
+ rescue JSON::ParserError
264
+ body
265
+ end
266
+
267
+ def url_encode(value)
268
+ URI.encode_www_form_component(value)
269
+ end
270
+ end
271
+ end
@@ -0,0 +1,36 @@
1
+ module Scanii
2
+ # Base class for all errors raised by Scanii::Client. Carries the API-supplied
3
+ # message plus optional X-Scanii-Request-Id and X-Scanii-Host-Id headers for
4
+ # support handoffs.
5
+ #
6
+ # Per SDK Principle 3 (integration-only) the SDK does not retry on the caller's
7
+ # behalf -- backoff is the caller's responsibility.
8
+ #
9
+ # @see https://scanii.github.io/openapi/v22/
10
+ class Error < StandardError
11
+ attr_reader :status_code, :request_id, :host_id, :body
12
+
13
+ def initialize(message, status_code: nil, request_id: nil, host_id: nil, body: nil)
14
+ super(message)
15
+ @status_code = status_code
16
+ @request_id = request_id
17
+ @host_id = host_id
18
+ @body = body
19
+ end
20
+ end
21
+
22
+ # Raised on HTTP 401 / 403 -- the credentials were rejected by the API.
23
+ class AuthError < Error
24
+ end
25
+
26
+ # Raised on HTTP 429. retry_after carries the value of the Retry-After
27
+ # response header in seconds when the server provided one.
28
+ class RateLimitError < Error
29
+ attr_reader :retry_after
30
+
31
+ def initialize(message, retry_after: nil, **)
32
+ super(message, **)
33
+ @retry_after = retry_after
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,100 @@
1
+ require "securerandom"
2
+
3
+ module Scanii
4
+ # Hand-rolled multipart/form-data encoder (RFC 7578).
5
+ #
6
+ # Ruby's stdlib Net::HTTP does not bundle a multipart encoder; this is the
7
+ # smallest viable implementation that covers the Scanii POST /files payload.
8
+ #
9
+ # Body is assembled as a single binary-encoded String -- file contents are
10
+ # read into memory rather than streamed. This matches the PHP SDK's approach;
11
+ # callers scanning very large files should be aware.
12
+ module Multipart
13
+ module_function
14
+
15
+ # Generate a unique multipart boundary.
16
+ def make_boundary
17
+ "----scanii-ruby-boundary-#{SecureRandom.hex(16)}"
18
+ end
19
+
20
+ # Build the Content-Type header value for a request using boundary.
21
+ def make_content_type(boundary)
22
+ "multipart/form-data; boundary=#{boundary}"
23
+ end
24
+
25
+ # Encode a multipart body containing the bytes at file_path plus the given
26
+ # text fields.
27
+ #
28
+ # @param fields [Hash{String=>String}] text form fields (e.g. metadata[k] => v, callback => url)
29
+ # @param file_path [String] path to the file to upload
30
+ # @param file_field [String] name of the file form field; default "file"
31
+ # @return [Array(String, String)] tuple of [body, content_type]
32
+ def encode(fields, file_path, file_field: "file")
33
+ boundary = make_boundary
34
+
35
+ filename = File.basename(file_path)
36
+ content_type = guess_content_type(file_path)
37
+ file_bytes = File.binread(file_path)
38
+
39
+ body = String.new(encoding: Encoding::BINARY)
40
+
41
+ fields.each do |name, value|
42
+ write_text_part(body, boundary, name.to_s, value.to_s)
43
+ end
44
+
45
+ body << "--#{boundary}\r\n".b
46
+ body << "Content-Disposition: form-data; name=\"#{file_field}\"; filename=\"#{filename}\"\r\n".b
47
+ body << "Content-Type: #{content_type}\r\n\r\n".b
48
+ body << file_bytes.b
49
+ body << "\r\n".b
50
+ body << "--#{boundary}--\r\n".b
51
+
52
+ [body, make_content_type(boundary)]
53
+ end
54
+
55
+ # Best-effort content-type lookup by extension. Falls back to
56
+ # application/octet-stream. The Scanii API does not require an accurate
57
+ # content-type on the multipart part -- the server inspects the bytes -- so
58
+ # a short table is sufficient.
59
+ def guess_content_type(path)
60
+ ext = File.extname(path).delete_prefix(".").downcase
61
+ MIME_TYPES.fetch(ext, "application/octet-stream")
62
+ end
63
+
64
+ MIME_TYPES = {
65
+ "txt" => "text/plain",
66
+ "html" => "text/html",
67
+ "htm" => "text/html",
68
+ "css" => "text/css",
69
+ "csv" => "text/csv",
70
+ "json" => "application/json",
71
+ "xml" => "application/xml",
72
+ "pdf" => "application/pdf",
73
+ "zip" => "application/zip",
74
+ "gz" => "application/gzip",
75
+ "jpg" => "image/jpeg",
76
+ "jpeg" => "image/jpeg",
77
+ "png" => "image/png",
78
+ "gif" => "image/gif",
79
+ "webp" => "image/webp",
80
+ "svg" => "image/svg+xml",
81
+ "mp3" => "audio/mpeg",
82
+ "mp4" => "video/mp4",
83
+ "mov" => "video/quicktime",
84
+ "doc" => "application/msword",
85
+ "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
86
+ "xls" => "application/vnd.ms-excel",
87
+ "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
88
+ }.freeze
89
+ private_constant :MIME_TYPES
90
+
91
+ def write_text_part(body, boundary, name, value)
92
+ body << "--#{boundary}\r\n".b
93
+ body << "Content-Disposition: form-data; name=\"#{name}\"\r\n".b
94
+ body << "Content-Type: text/plain; charset=UTF-8\r\n\r\n".b
95
+ body << value.b
96
+ body << "\r\n".b
97
+ end
98
+ private_class_method :write_text_part
99
+ end
100
+ end
@@ -0,0 +1,34 @@
1
+ require "json"
2
+
3
+ module Scanii
4
+ # Result of an asynchronous scan submission returned by Client#process_async
5
+ # and Client#fetch.
6
+ #
7
+ # The actual scan result is fetched later via Client#retrieve, or delivered
8
+ # to the supplied callback URL.
9
+ #
10
+ # @see https://scanii.github.io/openapi/v22/
11
+ class PendingResult
12
+ attr_reader :id, :request_id, :host_id, :resource_location, :raw_response
13
+
14
+ def initialize(id:, request_id:, host_id:, resource_location:, raw_response:)
15
+ @id = id
16
+ @request_id = request_id
17
+ @host_id = host_id
18
+ @resource_location = resource_location
19
+ @raw_response = raw_response
20
+ end
21
+
22
+ def self.from_response(body, headers)
23
+ json = body.nil? || body.empty? ? {} : JSON.parse(body)
24
+
25
+ new(
26
+ id: (json["id"] || "").to_s,
27
+ request_id: headers["x-scanii-request-id"],
28
+ host_id: headers["x-scanii-host-id"],
29
+ resource_location: headers["location"],
30
+ raw_response: body
31
+ )
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,51 @@
1
+ require "json"
2
+
3
+ module Scanii
4
+ # Result of a synchronous file scan returned by Client#process and
5
+ # Client#retrieve.
6
+ #
7
+ # findings is always an Array. Empty array means the content is clean.
8
+ #
9
+ # @see https://scanii.github.io/openapi/v22/
10
+ class ProcessingResult
11
+ attr_reader :id, :findings, :checksum, :content_length, :content_type,
12
+ :metadata, :creation_date, :error,
13
+ :request_id, :host_id, :resource_location, :raw_response
14
+
15
+ def initialize(id:, findings:, checksum:, content_length:, content_type:,
16
+ metadata:, creation_date:, error:,
17
+ request_id:, host_id:, resource_location:, raw_response:)
18
+ @id = id
19
+ @findings = findings
20
+ @checksum = checksum
21
+ @content_length = content_length
22
+ @content_type = content_type
23
+ @metadata = metadata
24
+ @creation_date = creation_date
25
+ @error = error
26
+ @request_id = request_id
27
+ @host_id = host_id
28
+ @resource_location = resource_location
29
+ @raw_response = raw_response
30
+ end
31
+
32
+ def self.from_response(body, headers)
33
+ json = body.nil? || body.empty? ? {} : JSON.parse(body)
34
+
35
+ new(
36
+ id: (json["id"] || "").to_s,
37
+ findings: Array(json["findings"]).map(&:to_s),
38
+ checksum: json["checksum"]&.to_s,
39
+ content_length: json["content_length"]&.to_i,
40
+ content_type: json["content_type"]&.to_s,
41
+ metadata: (json["metadata"] || {}).transform_values(&:to_s),
42
+ creation_date: json["creation_date"]&.to_s,
43
+ error: json["error"]&.to_s,
44
+ request_id: headers["x-scanii-request-id"],
45
+ host_id: headers["x-scanii-host-id"],
46
+ resource_location: headers["location"],
47
+ raw_response: body
48
+ )
49
+ end
50
+ end
51
+ end
@@ -0,0 +1,3 @@
1
+ module Scanii
2
+ VERSION = "1.0.1".freeze
3
+ end
data/lib/scanii.rb ADDED
@@ -0,0 +1,13 @@
1
+ require_relative "scanii/version"
2
+ require_relative "scanii/error"
3
+ require_relative "scanii/processing_result"
4
+ require_relative "scanii/pending_result"
5
+ require_relative "scanii/auth_token"
6
+ require_relative "scanii/multipart"
7
+ require_relative "scanii/client"
8
+
9
+ # Top-level namespace for the Scanii Ruby SDK.
10
+ #
11
+ # See https://scanii.github.io/openapi/v22/ for the full API reference.
12
+ module Scanii
13
+ end
metadata CHANGED
@@ -1,30 +1,95 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: scanii-ruby
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.0.1
4
+ version: 1.0.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Scanii
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2026-04-28 00:00:00.000000000 Z
12
- dependencies: []
13
- description: Placeholder release. See https://github.com/scanii/scanii-ruby for the
14
- upcoming v1.0.0.
15
- email:
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: minitest
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '5'
19
+ type: :development
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '5'
26
+ - !ruby/object:Gem::Dependency
27
+ name: rake
28
+ requirement: !ruby/object:Gem::Requirement
29
+ requirements:
30
+ - - "~>"
31
+ - !ruby/object:Gem::Version
32
+ version: '13'
33
+ type: :development
34
+ prerelease: false
35
+ version_requirements: !ruby/object:Gem::Requirement
36
+ requirements:
37
+ - - "~>"
38
+ - !ruby/object:Gem::Version
39
+ version: '13'
40
+ - !ruby/object:Gem::Dependency
41
+ name: rubocop
42
+ requirement: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - "~>"
45
+ - !ruby/object:Gem::Version
46
+ version: '1'
47
+ type: :development
48
+ prerelease: false
49
+ version_requirements: !ruby/object:Gem::Requirement
50
+ requirements:
51
+ - - "~>"
52
+ - !ruby/object:Gem::Version
53
+ version: '1'
54
+ - !ruby/object:Gem::Dependency
55
+ name: webmock
56
+ requirement: !ruby/object:Gem::Requirement
57
+ requirements:
58
+ - - "~>"
59
+ - !ruby/object:Gem::Version
60
+ version: '3'
61
+ type: :development
62
+ prerelease: false
63
+ version_requirements: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - "~>"
66
+ - !ruby/object:Gem::Version
67
+ version: '3'
68
+ description: Ruby client for Scanii (scanii.com). Stdlib only -- no runtime dependencies.
16
69
  executables: []
17
70
  extensions: []
18
71
  extra_rdoc_files: []
19
72
  files:
73
+ - CHANGELOG.md
74
+ - LICENSE
20
75
  - README.md
76
+ - lib/scanii.rb
77
+ - lib/scanii/auth_token.rb
78
+ - lib/scanii/client.rb
79
+ - lib/scanii/error.rb
80
+ - lib/scanii/multipart.rb
81
+ - lib/scanii/pending_result.rb
82
+ - lib/scanii/processing_result.rb
83
+ - lib/scanii/version.rb
21
84
  homepage: https://github.com/scanii/scanii-ruby
22
85
  licenses:
23
86
  - Apache-2.0
24
87
  metadata:
25
88
  homepage_uri: https://scanii.com
26
89
  source_code_uri: https://github.com/scanii/scanii-ruby
27
- post_install_message:
90
+ documentation_uri: https://scanii.github.io/openapi/v22/
91
+ changelog_uri: https://github.com/scanii/scanii-ruby/blob/main/CHANGELOG.md
92
+ rubygems_mfa_required: 'true'
28
93
  rdoc_options: []
29
94
  require_paths:
30
95
  - lib
@@ -39,9 +104,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
39
104
  - !ruby/object:Gem::Version
40
105
  version: '0'
41
106
  requirements: []
42
- rubygems_version: 3.0.3.1
43
- signing_key:
107
+ rubygems_version: 4.0.6
44
108
  specification_version: 4
45
- summary: Placeholder. The official Scanii Ruby SDK is releasing as scanii-ruby v1.0.0
46
- — coming soon.
109
+ summary: Zero-dependency Ruby SDK for the Scanii content security API
47
110
  test_files: []