etunnel 1.7.52 → 1.7.53

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (4) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +19 -3
  3. data/lib/etunnel.rb +202 -21
  4. metadata +2 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: e7f78a74d07553dca294a05fa3e50a17c3e9e905441a6e719b4b3f880d584d01
4
- data.tar.gz: 7c474bed9762e4bc435736b73e232e3be46f79458f0571d15f8050c43571f035
3
+ metadata.gz: e1a132d6c9d6965bd9370be5be4b0067191b8bcc7a63c7077d3604ce994ceb79
4
+ data.tar.gz: 7db2c3aa6495b203c4e70fad0546b09f7a086bcce58e19ae7032f52af532b7af
5
5
  SHA512:
6
- metadata.gz: ca0a476786f3bcfe08a44ea4c5c857ef693a5b5b2cb6109f916266cc4c317b458efa4b00e55a89eeebef99d5ccad87a18dcbe0286bed12120c88da5220db75fc
7
- data.tar.gz: c7a4bb89cf23e534b7c19755ebe5f7a7b733e4fff94d1c7d08753d019934ff6044cb0b0e774207b36072fcd0de9f6fe95136d5dfc109ce2aeb613c51f1a125ef
6
+ metadata.gz: 30df7023060fc25fdae7ffb412c490dc8c52b0f40e75e4ceaabd2d8f1f6e7a5b52cd7d906ba6cf91005e19c59a771b03e423b1f6ab6ed2e66af9988bd0b012d0
7
+ data.tar.gz: 74654dfa0d78063c0abd3202c46f23be4a9a38531e1310febc41b1f935deaa707baa9b1ef2fafb17a5cf895d5cc03ebe71c904e006be8bb8cbd63a93cffbddfd
data/README.md CHANGED
@@ -54,6 +54,16 @@ jitter, reset on success) and prints `TUNNEL_URL:` again. The subdomain is
54
54
  server needs a stable `SESSION_SECRET`; see PROTOCOL.md §1). Set
55
55
  `ETUNNEL_RECONNECT=0` to restore the old one-shot behaviour.
56
56
 
57
+ **Edge liveness probe.** Every 60 s the SDK fetches its own public URL's
58
+ `/.well-known/etunnel-health` (first probe 3 s after `welcome`) and exposes the
59
+ result as `t.edge_state`: `"ok"`, `"unreachable"` (DNS, offline, proxy -
60
+ logged once via `warn`, tunnel kept) or `"unknown"` (no probe yet). Two
61
+ consecutive "edge does not know this tunnel" answers close the tunnel with
62
+ reason `edge lost tunnel` (`t.close_reason`), so a reconnect re-lands it.
63
+ `connect` options: `edge_probe_interval:` (seconds; 0 = 60, negative = off),
64
+ `edge_probe_url:` (probe another base URL, `Host` stays the tunnel's hostname);
65
+ CLI: `ETUNNEL_EDGE_PROBE_INTERVAL`, `ETUNNEL_EDGE_PROBE_URL`.
66
+
57
67
  ## Embed
58
68
 
59
69
  ```ruby
@@ -67,10 +77,14 @@ trap('INT') { t.close; exit } # sends `bye`, frees the subdomain
67
77
  sleep # keep the process alive
68
78
  ```
69
79
 
70
- `Etunnel.connect(server, local, token: nil, subdomain: nil, resume: nil, routes: nil)`
80
+ `Etunnel.connect(server, local, token: nil, subdomain: nil, resume: nil, routes: nil,
81
+ edge_probe_url: nil, edge_probe_interval: nil, on_close: nil, on_log: nil)`
71
82
  blocks until `welcome` and returns an `Etunnel::Tunnel`: `t.url` (public URL),
72
- `t.resume_token` (server-signed token; replay it via `resume:` to reclaim the
73
- same subdomain), `t.close` (sends `bye`).
83
+ `t.hostname`, `t.resume_token` (server-signed token; replay it via `resume:` to
84
+ reclaim the same subdomain), `t.close` (sends `bye`; `t.close(reason)`),
85
+ `t.closed?` / `t.close_reason`, `t.edge_state` (last edge probe result:
86
+ `"unknown"` | `"ok"` | `"unreachable"`). `on_close:` is called once with the
87
+ tunnel's end reason, `on_log:` receives the edge probe lines (default: `warn`).
74
88
  `local` is a port, `"host:port"`, or `nil` when `routes` is given. Each
75
89
  request is served on a worker thread; EventMachine runs in a background
76
90
  thread if no reactor is running (Rails: call `connect` from an initializer).
@@ -84,6 +98,8 @@ thread if no reactor is running (Rails: call `connect` from an initializer).
84
98
  | `ETUNNEL_TOKEN` | paid-plan API key (optional) | - |
85
99
  | `ETUNNEL_RECONNECT` | `0` disables auto-reconnect (one-shot CLI) | enabled |
86
100
  | `ETUNNEL_SUBDOMAIN` | custom subdomain (paid plans) | random |
101
+ | `ETUNNEL_EDGE_PROBE_INTERVAL` | seconds between edge liveness probes (0 = 60, negative = off) | `60` |
102
+ | `ETUNNEL_EDGE_PROBE_URL` | probe this base URL instead of the public URL | - |
87
103
 
88
104
  ## License
89
105
 
data/lib/etunnel.rb CHANGED
@@ -13,6 +13,7 @@
13
13
  require 'json'
14
14
  require 'socket'
15
15
  require 'net/http'
16
+ require 'uri'
16
17
  begin
17
18
  require 'eventmachine'
18
19
  require 'faye/websocket'
@@ -32,7 +33,22 @@ HOP = %w[connection transfer-encoding keep-alive upgrade proxy-connection te tra
32
33
 
33
34
  module Etunnel
34
35
  # SDK version reported in hello.version (stamped by scripts/bump-release.py).
35
- VERSION = '1.7.52'.freeze
36
+ VERSION = '1.7.53'.freeze
37
+
38
+ # Edge liveness probe (PROTOCOL.md §3a, Go sdk/edge.go parity): ping/pong only
39
+ # proves the control socket is alive; the public hostname can stop routing while
40
+ # the socket stays up. The SDK probes its own URL periodically and makes the
41
+ # result observable (Tunnel#edge_state, on_log), closing the tunnel only when
42
+ # the edge itself says it no longer knows the hostname (a reconnect re-lands it).
43
+ EDGE_HEALTH_PATH = '/.well-known/etunnel-health'.freeze
44
+ # EDGE_HEADER marks a genuine edge answer (200 or 404). Anything without it - a
45
+ # captive portal, a transparent proxy's error page - is "unreachable", not "lost".
46
+ EDGE_HEADER = 'X-Etunnel-Edge'.freeze
47
+ EDGE_PROBE_INTERVAL = 60.0 # edge_probe_interval: seconds, 0 = this
48
+ EDGE_PROBE_TIMEOUT = 10 # bounds one probe request
49
+ EDGE_PROBE_FIRST_DELAY = 3.0 # caps the wait before the very first probe
50
+ EDGE_PROBE_FAIL_LOG_EVERY = 300.0 # "edge still unreachable" cadence after the transition line
51
+ EDGE_LOST_THRESHOLD = 2 # consecutive marked 404s that close the tunnel
36
52
 
37
53
  def self.frame(kind, sid, payload)
38
54
  [kind].pack('C') + [sid].pack('N') + [payload.bytesize].pack('N') + payload
@@ -74,20 +90,72 @@ module Etunnel
74
90
  nil
75
91
  end
76
92
 
77
- # Handle returned by Etunnel.connect (#417-E27): url / resume_token
78
- # readers plus close (sends bye, then closes the socket).
93
+ # Handle returned by Etunnel.connect (#417-E27): url / hostname /
94
+ # resume_token readers, edge_state, closed? / close_reason, and close
95
+ # (sends bye, then closes the socket).
79
96
  class Tunnel
80
- attr_reader :url, :resume_token
97
+ attr_reader :url, :hostname, :resume_token, :close_reason
81
98
 
82
- def initialize(url, resume_token, socket)
99
+ def initialize(url, hostname, resume_token, socket, on_close: nil, on_log: nil)
83
100
  @url = url
101
+ @hostname = hostname
84
102
  @resume_token = resume_token
85
103
  @socket = socket
104
+ @on_close = on_close
105
+ @on_log = on_log
106
+ @mutex = Mutex.new
107
+ @closed = false
108
+ @close_reason = nil
109
+ @edge_state = 'unknown' # 'unknown' | 'ok' | 'unreachable' - last edge probe result
86
110
  end
87
111
 
88
- def close
112
+ # Result of the most recent edge probe (PROTOCOL.md 3a).
113
+ def edge_state
114
+ @edge_state
115
+ end
116
+
117
+ # Probe target: the override base (edge_probe_url) or the public URL, + path.
118
+ def probe_url(base)
119
+ (base.nil? || base.empty? ? @url : base) + Etunnel::EDGE_HEALTH_PATH
120
+ end
121
+
122
+ def closed?
123
+ @closed
124
+ end
125
+
126
+ def log(msg)
127
+ if @on_log
128
+ begin
129
+ @on_log.call(msg)
130
+ rescue StandardError
131
+ nil # a broken sink must not kill the loop
132
+ end
133
+ else
134
+ warn "etunnel: #{msg}"
135
+ end
136
+ end
137
+
138
+ # Internal: the probe loop publishes a new state here.
139
+ def set_edge_state(state) # :nodoc:
140
+ @edge_state = state
141
+ end
142
+
143
+ # Internal: record the end of the tunnel exactly once (ours or the server's)
144
+ # and fire on_close with the reason. Returns false when already closed.
145
+ def mark_closed(reason = 'read closed') # :nodoc:
146
+ @mutex.synchronize do
147
+ return false if @closed
148
+ @closed = true
149
+ @close_reason = reason
150
+ end
151
+ @on_close&.call(reason)
152
+ true
153
+ end
154
+
155
+ def close(reason = 'client closed')
156
+ mark_closed(reason)
89
157
  begin
90
- @socket.send(JSON.generate({ type: 'bye', reason: 'client closed' }))
158
+ @socket.send(JSON.generate({ type: 'bye', reason: reason }))
91
159
  rescue StandardError
92
160
  nil # socket already gone - still close below
93
161
  end
@@ -100,11 +168,100 @@ module Etunnel
100
168
  end
101
169
  end
102
170
 
103
- def self.connect(server, local, token: nil, subdomain: nil, resume: nil, routes: nil)
171
+ # One edge probe, classified per PROTOCOL.md 3a. Returns [state, lost, err];
172
+ # lost is true only for a marked 404 from the edge. Net::HTTP with p_addr :ENV
173
+ # honours http_proxy / no_proxy; never the local-service transport.
174
+ def self.probe_edge(url, hostname, override)
175
+ uri = URI.parse(url)
176
+ http = Net::HTTP.new(uri.host, uri.port, :ENV)
177
+ http.use_ssl = uri.scheme == 'https'
178
+ http.open_timeout = EDGE_PROBE_TIMEOUT
179
+ http.read_timeout = EDGE_PROBE_TIMEOUT
180
+ req = Net::HTTP::Get.new(uri.request_uri.empty? ? '/' : uri.request_uri)
181
+ req['Accept'] = 'application/json'
182
+ req['Cache-Control'] = 'no-store'
183
+ req['User-Agent'] = "etunnel-edge-probe/#{VERSION}"
184
+ if override
185
+ # Dial the override, but ask for the tunnel's own hostname: the edge
186
+ # routes (and vouches) by Host, not by IP.
187
+ req['Host'] = hostname
188
+ end
189
+ resp = http.request(req)
190
+ if resp[EDGE_HEADER].to_s.empty?
191
+ return ['unreachable', false,
192
+ "etunnel: edge probe: #{hostname} answered #{resp.code} without #{EDGE_HEADER} (not an etunnel edge)"]
193
+ end
194
+ case resp.code.to_i
195
+ when 200 then ['ok', false, nil]
196
+ when 404 then ['unknown', true, "etunnel: edge probe: #{hostname}: edge reports no tunnel for this hostname"]
197
+ else ['unreachable', false, "etunnel: edge probe: #{hostname}: unexpected status #{resp.code}"]
198
+ end
199
+ rescue StandardError => e
200
+ ["unreachable", false, "etunnel: edge probe: #{e.message}"]
201
+ end
202
+
203
+ # Sleep until the monotonic deadline or until the tunnel closes (slices, so
204
+ # the probe thread never outlives the socket).
205
+ def self.sleep_until(tunnel, deadline)
206
+ while !tunnel.closed? && (left = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)) > 0
207
+ sleep([left, 0.05].min)
208
+ end
209
+ end
210
+
211
+ # Edge probe loop: first probe after min(interval, 3s), then every interval.
212
+ # Runs on its own thread until the tunnel closes.
213
+ def self.edge_probe_loop(tunnel, interval, edge_base)
214
+ now = -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
215
+ delay = [interval, EDGE_PROBE_FIRST_DELAY].min
216
+ lost = 0
217
+ last_fail_log = 0.0
218
+ until tunnel.closed?
219
+ sleep_until(tunnel, now.call + delay)
220
+ return if tunnel.closed?
221
+
222
+ delay = interval
223
+ state, lost_now, err = probe_edge(tunnel.probe_url(edge_base), tunnel.hostname, !edge_base.empty?)
224
+ return if tunnel.closed? # torn down while the probe was in flight
225
+
226
+ lost = lost_now ? lost + 1 : 0
227
+ if state != tunnel.edge_state
228
+ tunnel.set_edge_state(state)
229
+ case state
230
+ when 'ok' then tunnel.log("edge reachable: #{tunnel.hostname} routes to this tunnel")
231
+ when 'unreachable'
232
+ tunnel.log("edge unreachable: #{err} (the public URL may not work from this host; tunnel kept)")
233
+ last_fail_log = now.call
234
+ end
235
+ elsif state == 'unreachable' && now.call - last_fail_log >= EDGE_PROBE_FAIL_LOG_EVERY
236
+ tunnel.log("edge still unreachable: #{err}")
237
+ last_fail_log = now.call
238
+ end
239
+ next unless lost >= EDGE_LOST_THRESHOLD
240
+
241
+ tunnel.log("edge does not know this tunnel (#{lost} consecutive probes): closing so a reconnect re-lands it")
242
+ tunnel.close('edge lost tunnel')
243
+ return
244
+ end
245
+ end
246
+
247
+ # edge_probe_interval: nil/0 = EDGE_PROBE_INTERVAL, negative = disabled, otherwise seconds.
248
+ def self.edge_interval(value)
249
+ return EDGE_PROBE_INTERVAL if value.nil?
250
+ v = Float(value)
251
+ return EDGE_PROBE_INTERVAL if v.zero? || v.nan?
252
+ v
253
+ rescue ArgumentError, TypeError
254
+ EDGE_PROBE_INTERVAL
255
+ end
256
+
257
+ def self.connect(server, local, token: nil, subdomain: nil, resume: nil, routes: nil,
258
+ edge_probe_url: nil, edge_probe_interval: nil, on_close: nil, on_log: nil)
104
259
  routes = normalize_routes(routes) if routes
105
260
  raise ArgumentError, 'etunnel: routes must not be empty' if routes && routes.empty?
106
261
  local = "127.0.0.1:#{local}" unless local.nil? || local.to_s.include?(':')
107
262
  ws = Faye::WebSocket::Client.new(server, ['etunnel-v1'])
263
+ edge_base = edge_probe_url.to_s.sub(%r{/+\z}, '')
264
+ interval = edge_interval(edge_probe_interval)
108
265
 
109
266
  queue = Queue.new
110
267
  ws.on :message do |event|
@@ -128,6 +285,7 @@ module Etunnel
128
285
  ws.send(JSON.generate(hello))
129
286
 
130
287
  url = nil
288
+ hostname = nil
131
289
  resume_token = '' # #417-E27: was only set inside the resumeToken branch - uninitialized otherwise
132
290
  loop do
133
291
  kind, payload = queue.pop
@@ -138,6 +296,7 @@ module Etunnel
138
296
  m = JSON.parse(payload)
139
297
  if m['type'] == 'welcome'
140
298
  url = m['url']
299
+ hostname = m['hostname']
141
300
  resume_token = m['resumeToken'].to_s
142
301
  break
143
302
  elsif m['type'] == 'error'
@@ -146,12 +305,23 @@ module Etunnel
146
305
  end
147
306
 
148
307
  streams = {}
149
- closed = false
308
+ # #417-E27 (P0, Ruby 4.0): the tunnel used to be an Object.new with three
309
+ # define_singleton_method blocks closing over locals. On Ruby 4.0 a
310
+ # block handed to define_singleton_method runs with the receiver as
311
+ # self and bare locals inside it (url, ws) resolve as method calls on
312
+ # that receiver - so `url` re-entered the getter we were defining:
313
+ # `stack level too deep` at the first tunnel.url read, same hazard for
314
+ # close's `ws`. Replaced with a plain class whose constructor captures
315
+ # the values: deterministic closure semantics on every Ruby version.
316
+ tunnel = Tunnel.new(url, hostname, resume_token, ws, on_close: on_close, on_log: on_log)
150
317
 
151
318
  Thread.new do
152
319
  loop do
153
320
  kind, payload = queue.pop
154
- break if kind == :close
321
+ if kind == :close # socket gone (our close, the server's, or a drop)
322
+ tunnel.mark_closed(tunnel.close_reason || 'read closed')
323
+ break
324
+ end
155
325
 
156
326
  if kind == :text
157
327
  m = JSON.parse(payload)
@@ -161,7 +331,7 @@ module Etunnel
161
331
  when 'ping'
162
332
  ws.send(JSON.generate({ type: 'pong', ts: m['ts'] || 0 }))
163
333
  when 'bye'
164
- closed = true
334
+ tunnel.mark_closed(m['reason'].to_s)
165
335
  ws.close
166
336
  break
167
337
  end
@@ -191,17 +361,14 @@ module Etunnel
191
361
  end
192
362
  end
193
363
 
194
- # #417-E27 (P0, Ruby 4.0): the tunnel used to be an Object.new with three
195
- # define_singleton_method blocks closing over locals. On Ruby 4.0 a
196
- # block handed to define_singleton_method runs with the receiver as
197
- # self and bare locals inside it (url, ws) resolve as method calls on
198
- # that receiver - so `url` re-entered the getter we were defining:
199
- # `stack level too deep` at the first tunnel.url read, same hazard for
200
- # close's `ws`. Replaced with a plain class whose constructor captures
201
- # the values: deterministic closure semantics on every Ruby version.
202
- Tunnel.new(url, resume_token, ws)
364
+ # Edge liveness probe on its own thread (PROTOCOL.md 3a); a slow probe - up
365
+ # to EDGE_PROBE_TIMEOUT - must never delay a request or a pong.
366
+ Thread.new { edge_probe_loop(tunnel, interval, edge_base) } if interval >= 0
367
+
368
+ tunnel
203
369
  end
204
370
 
371
+
205
372
  # Themed 502 page shown when the local app is down (same HTML as the other SDKs).
206
373
  def self.local_error_page(error)
207
374
  esc = error.to_s.gsub('&', '&amp;').gsub('<', '&lt;').gsub('>', '&gt;')
@@ -269,6 +436,10 @@ module Etunnel
269
436
  method = req['method'] || 'GET'
270
437
  path = req['path'] || '/'
271
438
  headers = (req['headers'] || {}).reject { |k, _| HOP.include?(k.downcase) }
439
+ # Go parity (sdk/stream.go): the local app should see its public host.
440
+ # Net::HTTP lets the caller set Host, so the request's Host is the
441
+ # X-Forwarded-Host the server attached (X-Forwarded-Host is kept too).
442
+ xfh = headers.find { |k, _| k.downcase == 'x-forwarded-host' }
272
443
 
273
444
  # Runs on its own worker thread (see the reader loop); no inner
274
445
  # Thread.new{}.value needed - that would just re-block the caller.
@@ -277,6 +448,7 @@ module Etunnel
277
448
  http.open_timeout = 10
278
449
  klass = Net::HTTP.const_get(method.capitalize)
279
450
  r = klass.new(path, headers.to_h { |k, v| [k, Array(v).first] })
451
+ r['Host'] = Array(xfh[1]).first.to_s if xfh && !Array(xfh[1]).first.to_s.empty?
280
452
  r.body = body unless method == 'GET' || method == 'HEAD'
281
453
  resp = http.request(r)
282
454
  [resp.code.to_i, resp.each_header.reject { |k, _| HOP.include?(k) }.to_h, resp.body || '']
@@ -302,6 +474,14 @@ def Etunnel.main(argv = ARGV)
302
474
  token = ENV['ETUNNEL_TOKEN']
303
475
  subdomain = ENV['ETUNNEL_SUBDOMAIN']
304
476
  reconnect = ENV['ETUNNEL_RECONNECT'] != '0'
477
+ # Edge liveness probe (PROTOCOL.md 3a): interval in seconds (0 = 60, negative = off).
478
+ edge_probe_url = ENV['ETUNNEL_EDGE_PROBE_URL']
479
+ edge_probe_interval = begin
480
+ v = ENV['ETUNNEL_EDGE_PROBE_INTERVAL'].to_s.strip
481
+ v.empty? ? nil : Float(v)
482
+ rescue ArgumentError
483
+ nil
484
+ end
305
485
 
306
486
  $stdout.sync = true
307
487
  stopped = false
@@ -327,7 +507,8 @@ def Etunnel.main(argv = ARGV)
327
507
  # with the websocket: watch it for the disconnect signal.
328
508
  before = Thread.list
329
509
  begin
330
- tunnel = Etunnel.connect(server, local, token: token, subdomain: subdomain, resume: resume)
510
+ tunnel = Etunnel.connect(server, local, token: token, subdomain: subdomain, resume: resume,
511
+ edge_probe_url: edge_probe_url, edge_probe_interval: edge_probe_interval)
331
512
  resume = tunnel.resume_token if tunnel.respond_to?(:resume_token) && !tunnel.resume_token.empty?
332
513
  rescue StandardError => e
333
514
  warn(e.message.start_with?('etunnel:') ? e.message : "etunnel: #{e}")
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: etunnel
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.7.52
4
+ version: 1.7.53
5
5
  platform: ruby
6
6
  authors:
7
7
  - etunnel authors
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-27 00:00:00.000000000 Z
11
+ date: 2026-11-29 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: faye-websocket