nanoflags 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,119 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "net/http"
4
+ require "uri"
5
+
6
+ module NanoFlags
7
+ # HTTP for the client: blocking requests and a server-sent event reader on Net::HTTP. Proxy settings come from the
8
+ # environment (`HTTPS_PROXY`, `NO_PROXY`), the CA store from OpenSSL's defaults (`SSL_CERT_FILE`). Redirects are
9
+ # never followed.
10
+ #
11
+ # Any object with the same two methods can be passed as the client's +http:+ option.
12
+ module HTTP
13
+ # A complete response; header names are lower-case.
14
+ Response = Struct.new(:status, :headers, :body) do
15
+ def header(name) = headers[name.to_s.downcase]
16
+ def ok? = status.between?(200, 299)
17
+ end
18
+
19
+ # Incremental text/event-stream parser.
20
+ class SseParser
21
+ def initialize
22
+ @buffer = +""
23
+ @event = "message"
24
+ @data = []
25
+ end
26
+
27
+ # Feeds a chunk; yields each complete event as (event, data).
28
+ def feed(chunk)
29
+ @buffer << chunk.b
30
+ while (p = @buffer.index("\n"))
31
+ line = @buffer.slice!(0, p + 1).chomp.delete_suffix("\r").force_encoding(Encoding::UTF_8)
32
+ if line.empty?
33
+ yield @event, @data.join("\n") unless @data.empty?
34
+ @event = "message"
35
+ @data = []
36
+ next
37
+ end
38
+ next if line.start_with?(":")
39
+
40
+ field, value = line.split(":", 2)
41
+ value = value.to_s.delete_prefix(" ")
42
+ case field
43
+ when "event" then @event = value
44
+ when "data" then @data << value
45
+ end
46
+ end
47
+ @buffer.clear if @buffer.bytesize > 65_536
48
+ end
49
+ end
50
+
51
+ # The default transport.
52
+ class NetHttp
53
+ MAX_BODY = 16 * 1024 * 1024
54
+
55
+ def initialize(user_agent: nil)
56
+ @user_agent = user_agent
57
+ end
58
+
59
+ # Performs one request and returns a {Response}. Raises on transport failures (no connection, timeout).
60
+ def call(method, url, headers, body, timeout)
61
+ uri = URI(url)
62
+ http = connection(uri, timeout, timeout)
63
+ http.start do |h|
64
+ req = Net::HTTPGenericRequest.new(method, !body.nil?, method != "HEAD", uri.request_uri, headers)
65
+ req.body = body if body
66
+ h.request(req) do |res|
67
+ buf = +""
68
+ res.read_body do |chunk|
69
+ buf << chunk
70
+ raise IOError, "response body larger than 16 MiB" if buf.bytesize > MAX_BODY
71
+ end
72
+ return Response.new(res.code.to_i, res.each_header.to_h, buf.force_encoding(Encoding::UTF_8))
73
+ end
74
+ end
75
+ end
76
+
77
+ # Reads a server-sent event stream, yielding (event, data) until it ends, the block returns +:stop+, nothing
78
+ # arrives for +read_timeout+ seconds, or +on_open+'s closer is called (from any thread). Returns the HTTP status
79
+ # (0 when no response arrived).
80
+ def stream(url, headers, open_timeout:, read_timeout:, on_open: nil)
81
+ uri = URI(url)
82
+ http = connection(uri, open_timeout, read_timeout)
83
+ status = 0
84
+ # Thrown through Net::HTTP, :stop skips reading the rest of the (endless) body; `start` closes the socket.
85
+ catch(:stop) do
86
+ http.start do |h|
87
+ on_open&.call(-> { h.finish if h.started? })
88
+ req = Net::HTTP::Get.new(uri.request_uri, headers)
89
+ h.request(req) do |res|
90
+ status = res.code.to_i
91
+ next unless status == 200
92
+
93
+ parser = SseParser.new
94
+ res.read_body do |chunk|
95
+ parser.feed(chunk) { |event, data| throw :stop if yield(event, data) == :stop }
96
+ end
97
+ end
98
+ end
99
+ end
100
+ status
101
+ rescue IOError, Errno::EBADF
102
+ status # closed from another thread
103
+ end
104
+
105
+ private
106
+
107
+ def connection(uri, open_timeout, read_timeout)
108
+ http = Net::HTTP.new(uri.host, uri.port)
109
+ http.use_ssl = uri.scheme == "https"
110
+ http.open_timeout = open_timeout
111
+ http.read_timeout = read_timeout
112
+ http.write_timeout = open_timeout if http.respond_to?(:write_timeout=)
113
+ http.ssl_timeout = open_timeout if http.use_ssl?
114
+ http.keep_alive_timeout = 2
115
+ http
116
+ end
117
+ end
118
+ end
119
+ end
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ module NanoFlags
4
+ # The hosted NanoFlags edge. With this base URL (the default) every bundle is verified against
5
+ # {OFFICIAL_SIGNING_KEYS}, and unsigned bundles are refused.
6
+ OFFICIAL_EDGE_URL = "https://edge.nanoflags.io"
7
+
8
+ # The public halves of the production bundle-signing keys (Ed25519, safe to embed). A bundle signed with a key id
9
+ # that is not listed here (a rotation after this release) makes the client load `GET /v1/keys` once (again at
10
+ # most once a minute). Keep in sync with packages/sdk/src/keys.ts.
11
+ OFFICIAL_SIGNING_KEYS = [
12
+ { "kty" => "OKP", "crv" => "Ed25519", "x" => "wQu1EsaE-yTjqpUbibGyBrajy3IiRb7LyaiqeYRxG4U", "kid" => "k1" }.freeze
13
+ ].freeze
14
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "tempfile"
4
+
5
+ module NanoFlags
6
+ # Persistence of the last good configuration, so that a restarting process can evaluate flags before (or without)
7
+ # reaching the edge. A store is any object with +get+ (the stored text, or nil) and +set(text)+. A store sits
8
+ # outside the trust boundary: a signed bundle read back from it is verified again before it is used.
9
+ module Store
10
+ # The last good bundle in a file (written atomically, mode 0600).
11
+ class File
12
+ def initialize(path)
13
+ @path = path.to_s
14
+ end
15
+
16
+ def get
17
+ ::File.exist?(@path) ? ::File.binread(@path).force_encoding(Encoding::UTF_8) : nil
18
+ end
19
+
20
+ def set(text)
21
+ dir = ::File.dirname(@path)
22
+ tmp = Tempfile.create([".nanoflags-", ".json"], dir, mode: ::File::BINARY)
23
+ begin
24
+ tmp.chmod(0o600)
25
+ tmp.write(text)
26
+ tmp.close
27
+ ::File.rename(tmp.path, @path)
28
+ rescue StandardError
29
+ ::File.unlink(tmp.path) if ::File.exist?(tmp.path)
30
+ raise
31
+ end
32
+ end
33
+ end
34
+
35
+ # In memory (tests).
36
+ class Memory
37
+ attr_accessor :text
38
+
39
+ def get = @text
40
+ def set(text) = (@text = text)
41
+ end
42
+
43
+ # Any ActiveSupport::Cache store (`Rails.cache`, a Redis or Memcached cache store), shared by every process that
44
+ # uses it.
45
+ class Cache
46
+ def initialize(cache, key: "nanoflags.bundle")
47
+ @cache = cache
48
+ @key = key
49
+ end
50
+
51
+ def get
52
+ v = @cache.read(@key)
53
+ v.is_a?(String) ? v : nil
54
+ end
55
+
56
+ def set(text) = @cache.write(@key, text)
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,180 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "openssl"
4
+
5
+ module NanoFlags
6
+ # Bundle signature verification: Ed25519 over the canonical string
7
+ # `"nanoflags-bundle-v1\n<environment id>\n<revision>\n<checksum>\n<sha256 hex of the bundle text>"`.
8
+ #
9
+ # Only PUBLIC keys are handled here; a JWK that carries a private member (`d`) is refused.
10
+ #
11
+ # @api private
12
+ module Signature
13
+ module_function
14
+
15
+ # SubjectPublicKeyInfo prefix of a raw Ed25519 public key (RFC 8410).
16
+ SPKI_PREFIX = ["302a300506032b6570032100"].pack("H*").freeze
17
+
18
+ # The signature a bundle was accepted with (kept so that a persisted copy can be verified again).
19
+ Info = Struct.new(:signature, :kid, :environment_id, :revision, :checksum) do
20
+ def to_h = { "signature" => signature, "kid" => kid, "environmentId" => environment_id, "revision" => revision, "checksum" => checksum }
21
+
22
+ def self.from_h(h)
23
+ return nil unless h.is_a?(Hash) && h["signature"].is_a?(String) && h["environmentId"].is_a?(String) && h["checksum"].is_a?(String)
24
+
25
+ rev = h["revision"]
26
+ rev = rev.to_i if rev.is_a?(Float) && rev == rev.floor
27
+ return nil unless rev.is_a?(Integer)
28
+
29
+ new(h["signature"], h["kid"].is_a?(String) && !h["kid"].empty? ? h["kid"] : nil, h["environmentId"], rev, h["checksum"])
30
+ end
31
+ end
32
+
33
+ Key = Struct.new(:kid, :key)
34
+
35
+ def base64url_decode(value)
36
+ s = value.to_s.tr("-_", "+/").sub(/=+\z/, "")
37
+ return nil unless s.match?(%r{\A[A-Za-z0-9+/]*\z}) && s.length % 4 != 1
38
+
39
+ (s + ("=" * ((4 - (s.length % 4)) % 4))).unpack1("m0")
40
+ rescue ArgumentError
41
+ nil
42
+ end
43
+
44
+ def public_ed25519_jwk?(jwk)
45
+ jwk.is_a?(Hash) && jwk["kty"] == "OKP" && jwk["crv"] == "Ed25519" && jwk["x"].is_a?(String) && !jwk["x"].empty? && !jwk.key?("d")
46
+ end
47
+
48
+ # The public Ed25519 JWKs among +jwks+ (anything else, including private keys, is skipped).
49
+ def import_keys(jwks)
50
+ Array(jwks).filter_map do |jwk|
51
+ jwk = jwk.transform_keys(&:to_s) if jwk.is_a?(Hash)
52
+ next unless public_ed25519_jwk?(jwk)
53
+
54
+ raw = base64url_decode(jwk["x"])
55
+ next unless raw && raw.bytesize == 32
56
+
57
+ begin
58
+ Key.new(jwk["kid"].is_a?(String) && !jwk["kid"].empty? ? jwk["kid"] : nil, OpenSSL::PKey.read(SPKI_PREFIX + raw))
59
+ rescue OpenSSL::PKey::PKeyError
60
+ nil
61
+ end
62
+ end
63
+ end
64
+
65
+ def canonical(environment_id, revision, checksum, bundle_text)
66
+ "nanoflags-bundle-v1\n#{environment_id}\n#{revision}\n#{checksum}\n#{OpenSSL::Digest::SHA256.hexdigest(bundle_text.b)}"
67
+ end
68
+
69
+ # Whether +info.signature+ is a valid signature by one of +keys+ over the canonical string for +bundle_text+.
70
+ # A key id narrows the candidates; an unknown key id matches no key.
71
+ def verify(keys, info, bundle_text)
72
+ sig = base64url_decode(info.signature)
73
+ return false unless sig && sig.bytesize == 64
74
+
75
+ msg = canonical(info.environment_id, info.revision, info.checksum, bundle_text).b
76
+ keys.any? do |k|
77
+ next false if info.kid && k.kid && k.kid != info.kid
78
+
79
+ begin
80
+ k.key.verify(nil, sig, msg)
81
+ rescue OpenSSL::PKey::PKeyError
82
+ false
83
+ end
84
+ end
85
+ end
86
+
87
+ # The exact source text of the top-level member +name+ of a JSON object (the last one when it repeats, like
88
+ # JSON.parse), or nil. The edge embeds the stored, signed bundle text byte-for-byte; hashing that span avoids any
89
+ # re-serialisation.
90
+ def raw_member(text, name)
91
+ t = text.b
92
+ n = t.bytesize
93
+ i = 0
94
+ ws = -> { i += 1 while i < n && " \n\r\t".include?(t.getbyte(i).chr) }
95
+ str = lambda do
96
+ return nil if i >= n || t.getbyte(i) != 34
97
+
98
+ start = i
99
+ i += 1
100
+ while i < n
101
+ c = t.getbyte(i)
102
+ if c == 92
103
+ i += 2
104
+ elsif c == 34
105
+ i += 1
106
+ return [start, i]
107
+ else
108
+ i += 1
109
+ end
110
+ end
111
+ nil
112
+ end
113
+ value = lambda do
114
+ ws.()
115
+ return false if i >= n
116
+
117
+ c = t.getbyte(i)
118
+ return !str.().nil? if c == 34
119
+
120
+ if c == 123 || c == 91
121
+ depth = 0
122
+ while i < n
123
+ c = t.getbyte(i)
124
+ if c == 34
125
+ return false if str.().nil?
126
+
127
+ next
128
+ end
129
+ if c == 123 || c == 91
130
+ depth += 1
131
+ elsif c == 125 || c == 93
132
+ depth -= 1
133
+ end
134
+ i += 1
135
+ return true if depth.zero?
136
+ end
137
+ return false
138
+ end
139
+ start = i
140
+ i += 1 while i < n && !",}] \n\r\t".include?(t.getbyte(i).chr)
141
+ i > start
142
+ end
143
+ ws.()
144
+ return nil if i >= n || t.getbyte(i) != 123
145
+
146
+ i += 1
147
+ found = nil
148
+ loop do
149
+ ws.()
150
+ return found if i < n && t.getbyte(i) == 125
151
+
152
+ key = str.()
153
+ return nil if key.nil?
154
+
155
+ ws.()
156
+ return nil if i >= n || t.getbyte(i) != 58
157
+
158
+ i += 1
159
+ ws.()
160
+ start = i
161
+ return nil unless value.()
162
+
163
+ k = begin
164
+ Engine::Json.parse(t.byteslice(key[0], key[1] - key[0]))
165
+ rescue StandardError
166
+ nil
167
+ end
168
+ found = t.byteslice(start, i - start).force_encoding(Encoding::UTF_8) if k == name
169
+ ws.()
170
+ if i < n && t.getbyte(i) == 44
171
+ i += 1
172
+ elsif i < n && t.getbyte(i) == 125
173
+ return found
174
+ else
175
+ return nil
176
+ end
177
+ end
178
+ end
179
+ end
180
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module NanoFlags
4
+ # The version of this gem, reported to the edge as "ruby/<version>".
5
+ VERSION = "0.1.0"
6
+ end
data/lib/nanoflags.rb ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "nanoflags/version"
4
+ require_relative "nanoflags/engine"
5
+ require_relative "nanoflags/keys"
6
+ require_relative "nanoflags/verify"
7
+ require_relative "nanoflags/http"
8
+ require_relative "nanoflags/store"
9
+ require_relative "nanoflags/evaluation_detail"
10
+ require_relative "nanoflags/client"
metadata ADDED
@@ -0,0 +1,69 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: nanoflags
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Alibtekarat Althkiya Company for Trading & Marketing (Intinovate)
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2026-11-18 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: Evaluates NanoFlags feature flags locally (the same engine and results
14
+ as every NanoFlags SDK), keeps the configuration current in background threads (event
15
+ stream + ETag polling), verifies bundle signatures, survives forks (Puma, Unicorn,
16
+ Passenger, Resque) and reports sampled, redacted evaluation telemetry. No runtime
17
+ dependencies.
18
+ email:
19
+ - support@nanoflags.io
20
+ executables: []
21
+ extensions: []
22
+ extra_rdoc_files: []
23
+ files:
24
+ - CHANGELOG.md
25
+ - LICENSE
26
+ - NOTICE
27
+ - README.md
28
+ - lib/nanoflags.rb
29
+ - lib/nanoflags/client.rb
30
+ - lib/nanoflags/engine.rb
31
+ - lib/nanoflags/engine/js.rb
32
+ - lib/nanoflags/engine/json.rb
33
+ - lib/nanoflags/evaluation_detail.rb
34
+ - lib/nanoflags/http.rb
35
+ - lib/nanoflags/keys.rb
36
+ - lib/nanoflags/store.rb
37
+ - lib/nanoflags/verify.rb
38
+ - lib/nanoflags/version.rb
39
+ homepage: https://nanoflags.io
40
+ licenses:
41
+ - Apache-2.0
42
+ metadata:
43
+ homepage_uri: https://nanoflags.io
44
+ documentation_uri: https://nanoflags.io/docs
45
+ source_code_uri: https://github.com/motazalmaroai/nanoflags-sdk/tree/main/ruby/nanoflags
46
+ changelog_uri: https://github.com/motazalmaroai/nanoflags-sdk/blob/main/ruby/nanoflags/CHANGELOG.md
47
+ bug_tracker_uri: https://github.com/motazalmaroai/nanoflags-sdk/issues
48
+ rubygems_mfa_required: 'true'
49
+ post_install_message:
50
+ rdoc_options: []
51
+ require_paths:
52
+ - lib
53
+ required_ruby_version: !ruby/object:Gem::Requirement
54
+ requirements:
55
+ - - ">="
56
+ - !ruby/object:Gem::Version
57
+ version: '3.1'
58
+ required_rubygems_version: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: '0'
63
+ requirements: []
64
+ rubygems_version: 3.4.20
65
+ signing_key:
66
+ specification_version: 4
67
+ summary: 'NanoFlags server SDK for Ruby: local, deterministic feature-flag evaluation
68
+ with signed live updates.'
69
+ test_files: []