oximg-rails 0.10.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 ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 60dbe6811adcd8fe7e15ad740a12fc31495313d001f724cc2dcf06d15332d7cc
4
+ data.tar.gz: 5ee8b0e337d0dcf4d2cdad614dcfd64abd37a795a5821ee5872136290c90b4c9
5
+ SHA512:
6
+ metadata.gz: 4a5e41199af0c831458f82eff0957a05e1efccaa478052717116f84b76e70b99388ad2902b8ffe59538fdb92004cba300d5775f227050c4d99ef06cee81d3d70
7
+ data.tar.gz: 3a4f26a4c18172386bc2b3559039f6eed845e31dbc30180fb6046224ebef7dd830a263af7efa4ec6e375266af8044f9e32f0bc3376a935235f4848d5bb6a07a5
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,100 @@
1
+ # oximg-rails
2
+
3
+ The Rails-facing half of [oximg](https://github.com/oximg/oximg). The
4
+ split mirrors `imgproxy` / `imgproxy-rails`: the
5
+ [`oximg`](../oximg) gem does local image processing and stays
6
+ framework-free, and everything that points a Rails app at an oximg
7
+ **server** — or wires oximg into ActiveStorage — lives here.
8
+
9
+ ```ruby
10
+ gem "oximg-rails"
11
+ ```
12
+
13
+ ## Remote mode: URLs for an oximg server
14
+
15
+ If you run oximg as a service, the app does not process images at all;
16
+ it emits signed URLs and the server does the work.
17
+
18
+ ```ruby
19
+ Oximg::Server.configure do |config|
20
+ config.endpoint = "https://img.example.com"
21
+ config.key = ENV["OXIMG_KEY"] # hex, as the server takes it
22
+ config.salt = ENV["OXIMG_SALT"] # hex
23
+ end
24
+
25
+ Oximg::Server.url_for("photos/a.jpg", width: 750)
26
+ #=> "https://img.example.com/YkUw…/resize/750/0/photos/a.jpg"
27
+
28
+ Oximg::Server.url_for("photos/a.jpg", width: 750, height: 500, format: :webp)
29
+ #=> ".../resize/750/500/photos/a.jpg@webp"
30
+ ```
31
+
32
+ The source is fitted within the box and never enlarged. A zero axis is
33
+ unconstrained, so `width: 750` alone is exactly what an `srcset` `w`
34
+ descriptor and a Next.js loader mean.
35
+
36
+ Every setting defaults from the environment, and three of the four
37
+ variables are the ones the server itself reads — so an app deployed
38
+ alongside a configured oximg needs no Ruby-side setup at all:
39
+
40
+ | Variable | Meaning |
41
+ |---|---|
42
+ | `OXIMG_ENDPOINT` | Root of the deployment. Client-only: the server has no notion of its own public URL. Unset emits root-relative URLs, which is the right answer when oximg is mounted on the app's own origin behind a CDN |
43
+ | `OXIMG_KEY` / `OXIMG_SALT` | Hex HMAC material. Both set means URLs are signed; both unset means they are not; **exactly one set raises** — the same half-configuration the server refuses to boot on |
44
+ | `OXIMG_OPTIONS_PREFIX` | Mount point of the options route, if the server has one |
45
+
46
+ ### The options route
47
+
48
+ If the server mounts the Cloudflare-Images-compatible route
49
+ (`OXIMG_OPTIONS_PREFIX`), `options_url_for` speaks its grammar — this is
50
+ the route that carries per-request `quality`:
51
+
52
+ ```ruby
53
+ Oximg::Server.options_url_for("photos/a.png", width: 750, quality: 80)
54
+ #=> "https://img.example.com/…/image/width=750,quality=80/photos/a.png"
55
+ ```
56
+
57
+ Options are emitted in a fixed order (`width`, `height`, `quality`,
58
+ `format`). The signature covers the list verbatim, so a stable order is
59
+ also a stable cache key.
60
+
61
+ ### Signing
62
+
63
+ The scheme is imgproxy's, and it is the server's:
64
+
65
+ ```
66
+ base64url(HMAC-SHA256(key, salt || path))
67
+ ```
68
+
69
+ over the **percent-decoded** path — so one signature covers every URL
70
+ encoding of the same source, and the gem escapes the URL after signing
71
+ it. The signature covers the format token too: a URL for `photo.jpg`
72
+ does not authorize `photo.jpg@avif` and its heavier encode.
73
+
74
+ `test/server_signer_test.rb` pins this against the exact vectors the
75
+ Rust integration suite serves 200s for. A scheme with two
76
+ implementations is kept honest by shared vectors, not by two readings of
77
+ the same paragraph.
78
+
79
+ ## Local mode: ActiveStorage
80
+
81
+ **Not implemented yet.** Planned, on top of the `oximg` gem:
82
+
83
+ - **A variant processor.** `config.active_storage.variant_processor`
84
+ resolves `ImageProcessing::<Name>`, so an `ImageProcessing::Oximg`
85
+ backend can plug in beside `:vips` and `:mini_magick` without a
86
+ monkeypatch — and a Rails app can drop libvips/ImageMagick entirely.
87
+ - **Attachment URL helpers** — `oximg_url` on an attachment, resolving a
88
+ blob's key into an oximg source path, so remote mode needs no manual
89
+ path plumbing.
90
+
91
+ Until then, `Oximg.resize` from the `oximg` gem works fine inside a job.
92
+
93
+ ## Versioning
94
+
95
+ The gem version tracks the oximg release whose URL grammar it speaks,
96
+ the same convention as the `oximg` gem and the npm package.
97
+
98
+ ## License
99
+
100
+ Apache-2.0, same as oximg. See [LICENSE](LICENSE).
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Oximg
4
+ # Note for anything added here later: inside this namespace, a bare
5
+ # `Rails` resolves to *this* module, not the framework. Always write
6
+ # `::Rails` for the framework.
7
+ module Rails
8
+ # Tracks the oximg release whose URL grammar the client speaks, the
9
+ # same convention as the oximg gem and the npm package.
10
+ VERSION = "0.10.1"
11
+ end
12
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "oximg"
4
+ require_relative "rails/version"
5
+ require_relative "server"
6
+
7
+ module Oximg
8
+ # Rails integration for oximg, split from the `oximg` gem the way
9
+ # `imgproxy-rails` is split from `imgproxy`: the base gem stays
10
+ # framework-free, and everything that reaches into Rails lives here.
11
+ #
12
+ # What is here today is the server-URL builder (Oximg::Server), which
13
+ # this gem owns. The ActiveStorage glue — an `ImageProcessing::Oximg`
14
+ # variant processor for local processing, and attachment URL helpers
15
+ # for the remote mode — is not implemented yet; see the README.
16
+ #
17
+ # Note for anything added here: inside this namespace a bare `Rails`
18
+ # resolves to *this* module, not the framework. Always write
19
+ # `::Rails`.
20
+ module Rails
21
+ end
22
+ end
@@ -0,0 +1,96 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Oximg
4
+ module Server
5
+ # The client-side half of an oximg deployment's configuration: where
6
+ # the server is, and the signing material it was started with. What
7
+ # the server *does* with a request (quality profiles, source origin,
8
+ # memory caps) is server-side config and is deliberately not restated
9
+ # here — a knob duplicated on both sides is a knob that drifts.
10
+ #
11
+ # The defaults read the same environment variables the server itself
12
+ # reads (+OXIMG_KEY+, +OXIMG_SALT+, +OXIMG_OPTIONS_PREFIX+), so an app
13
+ # deployed alongside a configured oximg needs no Ruby-side setup at
14
+ # all. +OXIMG_ENDPOINT+ is client-only: the server has no notion of
15
+ # its own public URL.
16
+ class Config
17
+ # Root of the oximg deployment, without a trailing slash
18
+ # (+https://img.example.com+). Leave it +nil+ to emit root-relative
19
+ # URLs — the right answer when oximg is mounted on the app's own
20
+ # origin behind a CDN.
21
+ attr_reader :endpoint
22
+
23
+ # Hex +OXIMG_KEY+/+OXIMG_SALT+, decoded to bytes. Both nil means
24
+ # signing is off; exactly one set is a configuration error, checked
25
+ # at URL-build time (the server refuses to boot on the same
26
+ # half-configuration rather than serving unsigned).
27
+ attr_reader :key, :salt
28
+
29
+ # Mount point of the Cloudflare-Images-style options route, matching
30
+ # the server's +OXIMG_OPTIONS_PREFIX+ (e.g. +/image+). Nil means the
31
+ # route is not mounted and #options_url_for is unavailable.
32
+ attr_reader :options_prefix
33
+
34
+ def initialize(env: ENV)
35
+ self.endpoint = env["OXIMG_ENDPOINT"]
36
+ self.key = env["OXIMG_KEY"]
37
+ self.salt = env["OXIMG_SALT"]
38
+ self.options_prefix = env["OXIMG_OPTIONS_PREFIX"]
39
+ end
40
+
41
+ def endpoint=(value)
42
+ @endpoint = blank?(value) ? nil : value.to_s.sub(%r{/+\z}, "")
43
+ end
44
+
45
+ def key=(value)
46
+ @key = decode_hex("key", value)
47
+ end
48
+
49
+ def salt=(value)
50
+ @salt = decode_hex("salt", value)
51
+ end
52
+
53
+ def options_prefix=(value)
54
+ if blank?(value)
55
+ @options_prefix = nil
56
+ return
57
+ end
58
+ prefix = value.to_s.sub(%r{/+\z}, "")
59
+ prefix = "/#{prefix}" unless prefix.start_with?("/")
60
+ @options_prefix = prefix
61
+ end
62
+
63
+ # True when URLs will carry a signature.
64
+ def signing?
65
+ !@key.nil? && !@salt.nil?
66
+ end
67
+
68
+ # Fail closed the way the server does: a half-configured signing
69
+ # pair must never quietly produce unsigned URLs that the server will
70
+ # answer with 403.
71
+ def validate!
72
+ return if @key.nil? == @salt.nil?
73
+
74
+ raise ConfigurationError,
75
+ "key and salt must both be set to enable signing (got only #{@key.nil? ? "salt" : "key"})"
76
+ end
77
+
78
+ private
79
+
80
+ def blank?(value)
81
+ value.nil? || value.to_s.strip.empty?
82
+ end
83
+
84
+ def decode_hex(name, value)
85
+ return nil if blank?(value)
86
+
87
+ hex = value.to_s.strip
88
+ unless hex.match?(/\A(?:[0-9a-fA-F]{2})+\z/)
89
+ raise ConfigurationError, "#{name} is not valid hex (even-length 0-9a-f)"
90
+ end
91
+
92
+ [hex].pack("H*")
93
+ end
94
+ end
95
+ end
96
+ end
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module Oximg
6
+ module Server
7
+ # The imgproxy-style signing scheme, exactly as the server verifies it
8
+ # (+Signing::verify+ in src/main.rs): the signature is
9
+ # +base64url(HMAC-SHA256(key, salt || path))+ over the percent-DECODED
10
+ # path, so one signature covers every URL encoding of the same source.
11
+ #
12
+ # test/server_signer_test.rb pins this against the vectors the Rust
13
+ # integration suite serves 200s for — a scheme with two
14
+ # implementations needs shared vectors, not two readings of the prose.
15
+ module Signer
16
+ module_function
17
+
18
+ # +path+ is the decoded path the server reconstructs before
19
+ # verifying: "/resize/{w}/{h}/{file}" on the positional route,
20
+ # "{prefix}/{options}/{file}" on the options route.
21
+ def sign(key, salt, path)
22
+ # Force binary before concatenating: key material is arbitrary
23
+ # bytes, and a non-ASCII filename in a UTF-8 path would otherwise
24
+ # raise Encoding::CompatibilityError on the join.
25
+ digest = OpenSSL::HMAC.digest("SHA256", key, salt + path.to_s.b)
26
+ # Unpadded base64url. The server strips "=" before decoding, so
27
+ # padding would verify too — but every vector it ships is
28
+ # unpadded, and an unpadded signature is one path segment with no
29
+ # escaping question.
30
+ [digest].pack("m0").tr("+/", "-_").delete("=")
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,144 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Oximg
4
+ module Server
5
+ # Builds URLs for the two routes an oximg server mounts. Nothing here
6
+ # talks to the server: a URL is pure arithmetic over the config, so a
7
+ # Rails view can emit thousands of them without leaving the process.
8
+ #
9
+ # Validation mirrors the server's own bounds and fails closed on the
10
+ # same inputs. That is not defence — the server validates regardless —
11
+ # it is so a typo surfaces at the call site with a name, instead of as
12
+ # a 400 in an <img> tag nobody is watching.
13
+ class UrlBuilder
14
+ # The server's cap on either axis (src/main.rs); 0 means
15
+ # "unconstrained" on the positional route only.
16
+ MAX_DIMENSION = 8192
17
+
18
+ # Tokens the positional route's @fmt suffix accepts. "jxl" is
19
+ # reserved by the server for a future encoder and answers 400, so it
20
+ # is not offered here.
21
+ FORMATS = %w[jpg jpeg png webp avif].freeze
22
+
23
+ # The options route additionally understands format=auto, which
24
+ # means "negotiate, else the source's own format".
25
+ OPTION_FORMATS = (FORMATS + %w[auto]).freeze
26
+
27
+ # Everything outside RFC 3986's unreserved set gets percent-encoded.
28
+ # "/" stays literal so S3-style prefixes remain readable, and "@" so
29
+ # the format token survives; both are legal in a path segment, and
30
+ # the server signs the decoded form either way.
31
+ UNSAFE = %r{[^A-Za-z0-9\-._~/@]}
32
+
33
+ def initialize(config)
34
+ @config = config
35
+ end
36
+
37
+ # The positional route: +/resize/{w}/{h}/{file}+, where the source
38
+ # is fitted within the box and never enlarged. A zero axis is
39
+ # unconstrained — <tt>width: 750</tt> alone is exactly what an
40
+ # +srcset+ +w+ descriptor means.
41
+ #
42
+ # builder.resize("photos/a.jpg", width: 750)
43
+ # builder.resize("photos/a.jpg", width: 750, height: 500, format: :webp)
44
+ def resize(source, width: 0, height: 0, format: nil)
45
+ w = dimension(width, "width")
46
+ h = dimension(height, "height")
47
+ if w.zero? && h.zero?
48
+ raise ArgumentError, "at least one of width/height must be non-zero"
49
+ end
50
+
51
+ file = source_path(source)
52
+ file = "#{file}@#{token(format, FORMATS, "format")}" unless format.nil?
53
+ build("/resize/#{w}/#{h}/", file)
54
+ end
55
+
56
+ # The Cloudflare-Images-compatible options route,
57
+ # +{prefix}/width=750,quality=80/{file}+. Requires the server to
58
+ # have +OXIMG_OPTIONS_PREFIX+ set and the same prefix configured
59
+ # here. Options are emitted in a fixed order: the signature covers
60
+ # the list verbatim, so a stable order is also a stable cache key.
61
+ def options(source, width: nil, height: nil, quality: nil, format: nil)
62
+ prefix = @config.options_prefix
63
+ unless prefix
64
+ raise ConfigurationError,
65
+ "options_prefix is not configured (set it to the server's OXIMG_OPTIONS_PREFIX)"
66
+ end
67
+
68
+ build("#{prefix}/#{option_list(width, height, quality, format)}/", source_path(source))
69
+ end
70
+
71
+ private
72
+
73
+ # +prefix+ is generated, ASCII-safe and already signed-form; only
74
+ # the caller's source path needs escaping. The signature is computed
75
+ # over the decoded path and prepended as its own segment, which is
76
+ # what puts it before the options route's prefix rather than after.
77
+ def build(prefix, file)
78
+ @config.validate!
79
+ url = +""
80
+ url << @config.endpoint if @config.endpoint
81
+ if @config.signing?
82
+ url << "/" << Signer.sign(@config.key, @config.salt, "#{prefix}#{file}")
83
+ end
84
+ url << prefix << escape(file)
85
+ url.freeze
86
+ end
87
+
88
+ def escape(path)
89
+ path.gsub(UNSAFE) { |c| c.unpack("C*").map { |b| format("%%%02X", b) }.join }
90
+ end
91
+
92
+ def source_path(source)
93
+ path = source.to_s.sub(%r{\A/+}, "")
94
+ raise ArgumentError, "source path is empty" if path.empty?
95
+
96
+ # "." and ".." would make the signed path and the path the server
97
+ # resolves two different things; the server refuses them anyway.
98
+ if path.split("/").any? { |segment| segment == "." || segment == ".." }
99
+ raise ArgumentError, "source path must not contain \".\" or \"..\" segments: #{source.inspect}"
100
+ end
101
+
102
+ path
103
+ end
104
+
105
+ def dimension(value, name)
106
+ unless value.is_a?(Integer) && value >= 0 && value <= MAX_DIMENSION
107
+ raise ArgumentError, "#{name} must be an Integer in 0..#{MAX_DIMENSION}, got #{value.inspect}"
108
+ end
109
+
110
+ value
111
+ end
112
+
113
+ def option_list(width, height, quality, format)
114
+ if width.nil? && height.nil?
115
+ raise ArgumentError, "at least one of width/height is required on the options route"
116
+ end
117
+
118
+ parts = []
119
+ parts << "width=#{bounded(width, "width", 1, MAX_DIMENSION)}" unless width.nil?
120
+ parts << "height=#{bounded(height, "height", 1, MAX_DIMENSION)}" unless height.nil?
121
+ parts << "quality=#{bounded(quality, "quality", 1, 100)}" unless quality.nil?
122
+ parts << "format=#{token(format, OPTION_FORMATS, "format")}" unless format.nil?
123
+ parts.join(",")
124
+ end
125
+
126
+ def bounded(value, name, min, max)
127
+ unless value.is_a?(Integer) && value >= min && value <= max
128
+ raise ArgumentError, "#{name} must be an Integer in #{min}..#{max}, got #{value.inspect}"
129
+ end
130
+
131
+ value
132
+ end
133
+
134
+ def token(value, allowed, name)
135
+ token = value.to_s.downcase
136
+ unless allowed.include?(token)
137
+ raise ArgumentError, "unknown #{name} #{value.inspect} (#{allowed.join("|")})"
138
+ end
139
+
140
+ token
141
+ end
142
+ end
143
+ end
144
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "oximg"
4
+
5
+ require_relative "server/config"
6
+ require_relative "server/signer"
7
+ require_relative "server/url_builder"
8
+
9
+ module Oximg
10
+ # The remote half of oximg: building — and HMAC-signing — URLs for an
11
+ # oximg **server**, for deployments that let the server do the work
12
+ # instead of processing locally with +Oximg.resize+.
13
+ #
14
+ # Oximg::Server.configure do |config|
15
+ # config.endpoint = "https://img.example.com"
16
+ # config.key = ENV["OXIMG_KEY"]
17
+ # config.salt = ENV["OXIMG_SALT"]
18
+ # end
19
+ #
20
+ # Oximg::Server.url_for("photos/a.jpg", width: 750)
21
+ # #=> "https://img.example.com/{sig}/resize/750/0/photos/a.jpg"
22
+ #
23
+ # Nothing here talks to the server: a URL is arithmetic over the
24
+ # config, so a view can emit thousands of them without leaving the
25
+ # process.
26
+ module Server
27
+ # Raised for a configuration that cannot produce a URL the server
28
+ # would accept — a half-set signing pair, or the options route used
29
+ # without its prefix.
30
+ class ConfigurationError < Oximg::Error; end
31
+
32
+ class << self
33
+ # The process-wide configuration, seeded from the environment
34
+ # (see Config). Set it up once at boot; it is read, not written,
35
+ # per URL.
36
+ def config
37
+ @config ||= Config.new
38
+ end
39
+
40
+ attr_writer :config
41
+
42
+ def configure
43
+ yield config
44
+ config
45
+ end
46
+
47
+ # Drops the configuration back to the environment defaults.
48
+ # Exists for tests — an app should configure once at boot.
49
+ def reset!
50
+ @config = Config.new
51
+ end
52
+
53
+ # The positional route: see UrlBuilder#resize.
54
+ def url_for(source, **options)
55
+ UrlBuilder.new(config).resize(source, **options)
56
+ end
57
+
58
+ # The Cloudflare-Images-style options route: see
59
+ # UrlBuilder#options.
60
+ def options_url_for(source, **options)
61
+ UrlBuilder.new(config).options(source, **options)
62
+ end
63
+ end
64
+ end
65
+ end
metadata ADDED
@@ -0,0 +1,68 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: oximg-rails
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.10.1
5
+ platform: ruby
6
+ authors:
7
+ - oximg contributors
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 2026-08-06 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: oximg
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: 0.10.1
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: 0.10.1
26
+ description: 'The Rails-facing half of oximg: builds and HMAC-signs URLs for a remote
27
+ oximg server, for apps that let the server do the work instead of processing locally
28
+ with the `oximg` gem. ActiveStorage glue is in progress.'
29
+ executables: []
30
+ extensions: []
31
+ extra_rdoc_files: []
32
+ files:
33
+ - LICENSE
34
+ - README.md
35
+ - lib/oximg/rails.rb
36
+ - lib/oximg/rails/version.rb
37
+ - lib/oximg/server.rb
38
+ - lib/oximg/server/config.rb
39
+ - lib/oximg/server/signer.rb
40
+ - lib/oximg/server/url_builder.rb
41
+ homepage: https://github.com/oximg/oximg
42
+ licenses:
43
+ - Apache-2.0
44
+ metadata:
45
+ homepage_uri: https://github.com/oximg/oximg
46
+ source_code_uri: https://github.com/oximg/oximg/tree/main/rubygem/oximg-rails
47
+ changelog_uri: https://github.com/oximg/oximg/blob/main/CHANGELOG.md
48
+ bug_tracker_uri: https://github.com/oximg/oximg/issues
49
+ documentation_uri: https://github.com/oximg/oximg/blob/main/rubygem/oximg-rails/README.md
50
+ rubygems_mfa_required: 'true'
51
+ rdoc_options: []
52
+ require_paths:
53
+ - lib
54
+ required_ruby_version: !ruby/object:Gem::Requirement
55
+ requirements:
56
+ - - ">="
57
+ - !ruby/object:Gem::Version
58
+ version: '3.1'
59
+ required_rubygems_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: '0'
64
+ requirements: []
65
+ rubygems_version: 3.6.2
66
+ specification_version: 4
67
+ summary: Rails integration for oximg, and URL building for a remote oximg server
68
+ test_files: []