nanoflags 0.1.0 → 0.2.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,411 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "socket"
4
+ require "openssl"
5
+ require "securerandom"
6
+ require "digest"
7
+ require "uri"
8
+
9
+ module NanoFlags
10
+ # A minimal RFC 6455 WebSocket client for the edge's live socket (+/v1/live+), on the standard library only (TCP,
11
+ # OpenSSL, an HTTP CONNECT tunnel through +HTTPS_PROXY+ / +HTTP_PROXY+ honouring +NO_PROXY+). It speaks what the
12
+ # live protocol needs: text messages (fragmented or not), ping/pong and the close handshake. No extensions (no
13
+ # compression), no redirects.
14
+ #
15
+ # One thread reads and writes ({Connection#recv}, {Connection#send_text}); {Connection#close} may be called from any
16
+ # thread and makes a blocked +recv+ raise {Closed}.
17
+ module WebSocket
18
+ GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
19
+ MAX_MESSAGE = 8 * 1024 * 1024
20
+ MAX_HEADER = 16 * 1024
21
+
22
+ # Connecting (or the handshake) took longer than +open_timeout+.
23
+ class TimeoutError < IOError; end
24
+
25
+ # The handshake failed. +status+ is the HTTP status of the answer (0 when there was none).
26
+ class HandshakeError < IOError
27
+ attr_reader :status
28
+
29
+ def initialize(message, status = 0)
30
+ super(message)
31
+ @status = status
32
+ end
33
+ end
34
+
35
+ # The connection is closed. +code+ is the close code the server sent (nil when the connection simply ended).
36
+ class Closed < IOError
37
+ attr_reader :code, :reason
38
+
39
+ def initialize(code = nil, reason = nil)
40
+ super(code ? "WebSocket closed (#{code}#{reason.to_s.empty? ? "" : " #{reason}"})" : "WebSocket connection ended")
41
+ @code = code
42
+ @reason = reason
43
+ end
44
+ end
45
+
46
+ module_function
47
+
48
+ # Opens a connection to a +ws://+ or +wss://+ URL. +headers+ are sent with the upgrade request (never put a key
49
+ # in the URL); +protocols+ are the offered subprotocols. Raises {HandshakeError} or a socket error.
50
+ def connect(url, headers: {}, protocols: [], open_timeout: 10, ssl_context: nil)
51
+ uri = URI(url)
52
+ raise ArgumentError, "not a WebSocket URL: #{url}" unless %w[ws wss].include?(uri.scheme)
53
+
54
+ tls = uri.scheme == "wss"
55
+ port = uri.port || (tls ? 443 : 80)
56
+ deadline = monotonic + open_timeout
57
+ hostname = uri.hostname # without the brackets of an IPv6 literal
58
+ io = open_tcp(hostname, port, tls, deadline)
59
+ begin
60
+ if tls
61
+ ctx = ssl_context || default_ssl_context
62
+ ssl = OpenSSL::SSL::SSLSocket.new(io, ctx)
63
+ ssl.sync_close = true
64
+ ssl.hostname = hostname
65
+ wait_io(ssl, deadline) { ssl.connect_nonblock(exception: false) }
66
+ ssl.post_connection_check(hostname) if ctx.verify_mode != OpenSSL::SSL::VERIFY_NONE
67
+ io = ssl
68
+ end
69
+ key = [SecureRandom.random_bytes(16)].pack("m0")
70
+ host = uri.host # bracketed for IPv6
71
+ lines = ["GET #{uri.request_uri} HTTP/1.1", "Host: #{port == (tls ? 443 : 80) ? host : "#{host}:#{port}"}",
72
+ "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Key: #{key}", "Sec-WebSocket-Version: 13"]
73
+ lines << "Sec-WebSocket-Protocol: #{protocols.join(", ")}" unless protocols.empty?
74
+ headers.each do |k, v|
75
+ raise ArgumentError, "invalid header" if "#{k}#{v}".match?(/[\r\n]/)
76
+
77
+ lines << "#{k}: #{v}"
78
+ end
79
+ write_all(io, "#{lines.join("\r\n")}\r\n\r\n", deadline)
80
+ reader = Reader.new(io)
81
+ head = reader.read_head(deadline)
82
+ status_line, *header_lines = head.split("\r\n")
83
+ status = status_line.to_s[/\AHTTP\/1\.[01] (\d{3})/, 1].to_i
84
+ res = {}
85
+ header_lines.each do |l|
86
+ k, v = l.split(":", 2)
87
+ res[k.to_s.strip.downcase] = v.to_s.strip if v
88
+ end
89
+ raise HandshakeError.new("WebSocket upgrade refused with HTTP #{status}", status) unless status == 101
90
+ raise HandshakeError.new("not a WebSocket upgrade", status) unless res["upgrade"].to_s.casecmp?("websocket") && res["connection"].to_s.downcase.split(/\s*,\s*/).include?("upgrade")
91
+
92
+ expected = [Digest::SHA1.digest(key + GUID)].pack("m0")
93
+ raise HandshakeError.new("invalid Sec-WebSocket-Accept", status) unless res["sec-websocket-accept"] == expected
94
+
95
+ protocol = res["sec-websocket-protocol"]
96
+ raise HandshakeError.new("unexpected subprotocol #{protocol.inspect}", status) if protocol && !protocols.include?(protocol)
97
+ raise HandshakeError.new("extensions were not offered", status) if res["sec-websocket-extensions"]
98
+
99
+ Connection.new(io, reader, protocol)
100
+ rescue StandardError
101
+ begin
102
+ io.close
103
+ rescue StandardError
104
+ nil
105
+ end
106
+ raise
107
+ end
108
+ end
109
+
110
+ def default_ssl_context
111
+ ctx = OpenSSL::SSL::SSLContext.new
112
+ ctx.set_params(verify_mode: OpenSSL::SSL::VERIFY_PEER)
113
+ ctx
114
+ end
115
+
116
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
117
+
118
+ # A TCP connection to host:port, through the environment's HTTP proxy when one applies (a CONNECT tunnel).
119
+ def open_tcp(host, port, tls, deadline)
120
+ proxy = URI("#{tls ? "https" : "http"}://#{host.include?(":") ? "[#{host}]" : host}:#{port}").find_proxy
121
+ left = [deadline - monotonic, 0.001].max
122
+ return Socket.tcp(host, port, connect_timeout: left) unless proxy
123
+
124
+ io = Socket.tcp(proxy.hostname, proxy.port, connect_timeout: left)
125
+ begin
126
+ target = host.include?(":") ? "[#{host}]:#{port}" : "#{host}:#{port}"
127
+ req = +"CONNECT #{target} HTTP/1.1\r\nHost: #{target}\r\n"
128
+ if proxy.user
129
+ creds = "#{URI.decode_www_form_component(proxy.user)}:#{URI.decode_www_form_component(proxy.password.to_s)}"
130
+ req << "Proxy-Authorization: Basic #{[creds].pack("m0")}\r\n"
131
+ end
132
+ write_all(io, "#{req}\r\n", deadline)
133
+ head = Reader.new(io).read_head(deadline) # the tunnel answer only: nothing follows until the client speaks
134
+ status = head[/\AHTTP\/1\.[01] (\d{3})/, 1].to_i
135
+ raise HandshakeError.new("proxy CONNECT failed with HTTP #{status}", 0) unless status == 200
136
+
137
+ io
138
+ rescue StandardError
139
+ io.close
140
+ raise
141
+ end
142
+ end
143
+
144
+ # Runs a nonblocking operation until it completes or +deadline+ passes.
145
+ def wait_io(io, deadline)
146
+ loop do
147
+ r = yield
148
+ case r
149
+ when :wait_readable, :wait_writable
150
+ left = deadline - monotonic
151
+ raise TimeoutError, "timed out" if left <= 0
152
+
153
+ ready = r == :wait_readable ? IO.select([io], nil, nil, left) : IO.select(nil, [io], nil, left)
154
+ raise TimeoutError, "timed out" unless ready
155
+ else
156
+ return r
157
+ end
158
+ end
159
+ end
160
+
161
+ def write_all(io, data, deadline)
162
+ data = data.b
163
+ until data.empty?
164
+ n = wait_io(io, deadline) { io.write_nonblock(data, exception: false) }
165
+ data = data.byteslice(n..)
166
+ end
167
+ end
168
+
169
+ # Buffered nonblocking reads (OpenSSL may hold decrypted bytes that IO.select does not see).
170
+ class Reader
171
+ def initialize(io)
172
+ @io = io
173
+ @buf = "".b
174
+ end
175
+
176
+ def buffered = @buf.bytesize
177
+
178
+ # Reads at least one more chunk; returns false on timeout. Raises {Closed} at the end of the stream.
179
+ def fill(deadline)
180
+ loop do
181
+ r = @io.read_nonblock(65_536, exception: false)
182
+ case r
183
+ when nil then raise Closed
184
+ when :wait_readable, :wait_writable
185
+ left = deadline.nil? ? nil : deadline - WebSocket.monotonic
186
+ return false if left && left <= 0
187
+
188
+ ready = r == :wait_readable ? IO.select([@io], nil, nil, left) : IO.select(nil, [@io], nil, left)
189
+ return false unless ready
190
+ else
191
+ @buf << r
192
+ return true
193
+ end
194
+ end
195
+ rescue IOError, SystemCallError, OpenSSL::SSL::SSLError => e
196
+ raise e if e.is_a?(Closed)
197
+
198
+ raise Closed
199
+ end
200
+
201
+ # Removes and returns +n+ bytes, or nil when they did not arrive before +deadline+.
202
+ def take(n, deadline)
203
+ while @buf.bytesize < n
204
+ return nil unless fill(deadline)
205
+ end
206
+ @buf.slice!(0, n)
207
+ end
208
+
209
+ def read_head(deadline)
210
+ loop do
211
+ if (i = @buf.index("\r\n\r\n"))
212
+ head = @buf.slice!(0, i + 4)
213
+ return head.byteslice(0, i).force_encoding(Encoding::UTF_8)
214
+ end
215
+ raise HandshakeError, "response header too large" if @buf.bytesize > MAX_HEADER
216
+ raise TimeoutError, "timed out" unless fill(deadline)
217
+ end
218
+ end
219
+ end
220
+
221
+ # An open WebSocket connection.
222
+ class Connection
223
+ attr_reader :protocol
224
+
225
+ def initialize(io, reader, protocol)
226
+ @io = io
227
+ @reader = reader
228
+ @protocol = protocol
229
+ @write_lock = Mutex.new
230
+ @closed = false
231
+ @close_sent = false
232
+ @partial = nil
233
+ @frame = nil
234
+ end
235
+
236
+ def closed? = @closed
237
+
238
+ # Sends one text message.
239
+ def send_text(text) = send_frame(0x1, text.to_s.b)
240
+
241
+ # The next text message (String), or nil when nothing arrived within +timeout+ seconds. Answers pings, skips
242
+ # pongs and binary messages. Raises {Closed} (with the server's close code) when the connection ends.
243
+ def recv(timeout)
244
+ deadline = WebSocket.monotonic + timeout
245
+ loop do
246
+ raise Closed if @closed && @reader.buffered.zero?
247
+
248
+ frame = next_frame(deadline)
249
+ return nil if frame.nil?
250
+
251
+ fin, opcode, payload = frame
252
+ case opcode
253
+ when 0x0
254
+ raise protocol_error("unexpected continuation") unless @partial
255
+
256
+ append(payload)
257
+ return finish if fin
258
+ when 0x1, 0x2
259
+ raise protocol_error("interleaved message") if @partial
260
+
261
+ @partial = [opcode, payload]
262
+ check_size
263
+ return finish if fin
264
+ when 0x8 then handle_close(payload)
265
+ when 0x9 then send_frame(0xA, payload)
266
+ when 0xA then nil
267
+ else raise protocol_error("unknown opcode #{opcode}")
268
+ end
269
+ end
270
+ end
271
+
272
+ # Starts the close handshake (best effort) and closes the socket. Safe from any thread; idempotent.
273
+ def close(code = 1000, reason = "")
274
+ return if @closed
275
+
276
+ begin
277
+ payload = [code].pack("n") + reason.to_s.b.byteslice(0, 120)
278
+ send_frame(0x8, payload, timeout: 1) unless @close_sent
279
+ rescue StandardError
280
+ nil
281
+ end
282
+ shutdown
283
+ end
284
+
285
+ private
286
+
287
+ def shutdown
288
+ @closed = true
289
+ begin
290
+ @io.close
291
+ rescue StandardError
292
+ nil
293
+ end
294
+ end
295
+
296
+ def protocol_error(why)
297
+ close(1002, "protocol error")
298
+ Closed.new(1002, why)
299
+ end
300
+
301
+ def append(payload)
302
+ @partial[1] << payload
303
+ check_size
304
+ end
305
+
306
+ def check_size
307
+ return if @partial[1].bytesize <= MAX_MESSAGE
308
+
309
+ close(1009, "too big")
310
+ raise Closed.new(1009, "message too big")
311
+ end
312
+
313
+ def finish
314
+ opcode, data = @partial
315
+ @partial = nil
316
+ return nil if opcode == 0x2 # the live protocol only uses text
317
+
318
+ text = data.force_encoding(Encoding::UTF_8)
319
+ raise protocol_error("invalid UTF-8") unless text.valid_encoding?
320
+
321
+ text
322
+ end
323
+
324
+ def handle_close(payload)
325
+ code = payload.bytesize >= 2 ? payload.unpack1("n") : nil
326
+ reason = payload.bytesize > 2 ? payload.byteslice(2..).force_encoding(Encoding::UTF_8) : nil
327
+ unless @close_sent
328
+ begin
329
+ send_frame(0x8, payload.bytesize >= 2 ? payload.byteslice(0, 2) : "".b, timeout: 1)
330
+ rescue StandardError
331
+ nil
332
+ end
333
+ end
334
+ shutdown
335
+ raise Closed.new(code, reason)
336
+ end
337
+
338
+ # One frame as [fin, opcode, payload], or nil on timeout. A partially received frame is kept for the next call.
339
+ def next_frame(deadline)
340
+ @frame ||= {}
341
+ f = @frame
342
+ unless f[:b0]
343
+ head = @reader.take(2, deadline) or return nil
344
+ f[:b0], f[:b1] = head.unpack("CC")
345
+ raise protocol_error("reserved bits set") if f[:b0] & 0x70 != 0
346
+ raise protocol_error("masked server frame") if f[:b1] & 0x80 != 0
347
+ end
348
+ unless f[:len]
349
+ len = f[:b1] & 0x7F
350
+ if len == 126
351
+ ext = @reader.take(2, deadline) or return nil
352
+ len = ext.unpack1("n")
353
+ elsif len == 127
354
+ ext = @reader.take(8, deadline) or return nil
355
+ len = ext.unpack1("Q>")
356
+ end
357
+ opcode = f[:b0] & 0x0F
358
+ raise protocol_error("control frame too long") if opcode >= 0x8 && (len > 125 || f[:b0] & 0x80 == 0)
359
+ if len > MAX_MESSAGE
360
+ close(1009, "too big")
361
+ raise Closed.new(1009, "message too big")
362
+ end
363
+
364
+ f[:len] = len
365
+ end
366
+ payload = f[:len].zero? ? "".b : (@reader.take(f[:len], deadline) or return nil)
367
+ @frame = nil
368
+ [f[:b0] & 0x80 != 0, f[:b0] & 0x0F, payload]
369
+ end
370
+
371
+ def send_frame(opcode, payload, timeout: 10)
372
+ payload = payload.b
373
+ @write_lock.synchronize do
374
+ raise Closed if @closed || @close_sent
375
+
376
+ @close_sent = true if opcode == 0x8
377
+ len = payload.bytesize
378
+ head = [0x80 | opcode].pack("C")
379
+ head << if len < 126 then [0x80 | len].pack("C")
380
+ elsif len < 65_536 then [0x80 | 126, len].pack("Cn")
381
+ else [0x80 | 127, len].pack("CQ>")
382
+ end
383
+ mask = SecureRandom.random_bytes(4)
384
+ head << mask
385
+ WebSocket.write_all(@io, head << WebSocket.mask(payload, mask), WebSocket.monotonic + timeout)
386
+ end
387
+ rescue IOError, SystemCallError, OpenSSL::SSL::SSLError => e
388
+ raise e if e.is_a?(Closed)
389
+
390
+ shutdown
391
+ raise Closed
392
+ end
393
+ end
394
+
395
+ # XORs +data+ with the 4-byte +key+ (RFC 6455 §5.3).
396
+ def mask(data, key)
397
+ return data.dup if data.empty?
398
+
399
+ k = key.unpack("C4")
400
+ words = data.bytesize / 4
401
+ out = if words.positive?
402
+ kw = key.unpack1("N")
403
+ data.byteslice(0, words * 4).unpack("N*").map { |w| w ^ kw }.pack("N*")
404
+ else
405
+ "".b
406
+ end
407
+ (words * 4...data.bytesize).each { |i| out << (data.getbyte(i) ^ k[i % 4]) }
408
+ out
409
+ end
410
+ end
411
+ end
data/lib/nanoflags.rb CHANGED
@@ -1,10 +1,12 @@
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"
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/websocket"
9
+ require_relative "nanoflags/store"
10
+ require_relative "nanoflags/evaluation_detail"
11
+ require_relative "nanoflags/client"
12
+ require_relative "nanoflags/session"
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: nanoflags
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Alibtekarat Althkiya Company for Trading & Marketing (Intinovate)
@@ -11,10 +11,11 @@ cert_chain: []
11
11
  date: 2026-11-18 00:00:00.000000000 Z
12
12
  dependencies: []
13
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.
14
+ as every NanoFlags SDK), keeps the configuration current in background threads (live
15
+ WebSocket pushes, with the event stream and ETag polling as fallback), verifies
16
+ bundle signatures, resolves test sessions (Rack middleware), survives forks (Puma,
17
+ Unicorn, Passenger, Resque) and reports sampled, redacted evaluation telemetry.
18
+ No runtime dependencies.
18
19
  email:
19
20
  - support@nanoflags.io
20
21
  executables: []
@@ -33,9 +34,11 @@ files:
33
34
  - lib/nanoflags/evaluation_detail.rb
34
35
  - lib/nanoflags/http.rb
35
36
  - lib/nanoflags/keys.rb
37
+ - lib/nanoflags/session.rb
36
38
  - lib/nanoflags/store.rb
37
39
  - lib/nanoflags/verify.rb
38
40
  - lib/nanoflags/version.rb
41
+ - lib/nanoflags/websocket.rb
39
42
  homepage: https://nanoflags.io
40
43
  licenses:
41
44
  - Apache-2.0
@@ -61,7 +64,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
61
64
  - !ruby/object:Gem::Version
62
65
  version: '0'
63
66
  requirements: []
64
- rubygems_version: 3.4.20
67
+ rubygems_version: 3.5.22
65
68
  signing_key:
66
69
  specification_version: 4
67
70
  summary: 'NanoFlags server SDK for Ruby: local, deterministic feature-flag evaluation