tuna-sdk 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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 7466d9d0276c4fb503ef075fec6717507de831a5830ec482cd301a768ab30782
4
+ data.tar.gz: a45f9b9a90dddbe04c81b8f32df605e75a72bfae92e7318e5d19ba24969058f3
5
+ SHA512:
6
+ metadata.gz: a20b730949120f18e17e4519294289df0aa4d841820fb25d4953661666910b6a5b40de56b69b0da88d062faa42cffd813e0589c7ed5a44eee974503703b40494
7
+ data.tar.gz: af20793ea1913975a2df8341ae4989360218598642321d2cfa75e2ea1c6eea8c1d5577a5f8db7aded78fe0f15f73a7730e098411fa5a6b69a5b3e01dcf29e4c9
data/CHANGELOG.md ADDED
@@ -0,0 +1,6 @@
1
+ # Changelog
2
+
3
+ ## v0.1.0
4
+
5
+ First public release: `Tuna::SDK.listen` and `Tuna::SDK.forward` for HTTP and
6
+ TCP tunnels, reconnects to the same public address after network failures.
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 tuna.am authors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,139 @@
1
+ # tuna-sdk-ruby
2
+
3
+ Open [tuna.am](https://tuna.am) tunnels straight from Ruby code: expose a local
4
+ HTTP or TCP service at a public address without installing the `tuna` CLI.
5
+
6
+ - Two ways in: `Tuna::SDK.listen` hands you each connection as a socket,
7
+ `Tuna::SDK.forward` proxies connections to a local address.
8
+ - Survives network failures: reconnects with backoff and keeps the same
9
+ public address.
10
+ - Small: only the standard library and [net-ssh](https://github.com/net-ssh/net-ssh).
11
+
12
+ The API is not stable yet: it may change before v1.
13
+
14
+ ## Install
15
+
16
+ ```shell
17
+ gem install tuna-sdk
18
+ ```
19
+
20
+ or in a `Gemfile`:
21
+
22
+ ```ruby
23
+ gem "tuna-sdk"
24
+ ```
25
+
26
+ Requires Ruby 3.1 or later. net-ssh 8 needs the `openssl` gem 3.2 or later:
27
+ Ruby 3.3 and newer ship it, on 3.1 and 3.2 it is built on install and needs
28
+ the OpenSSL headers (`libssl-dev` or similar).
29
+
30
+ ## Authentication
31
+
32
+ Create an API key with the `tunnels:connect` scope at
33
+ [my.tuna.am](https://my.tuna.am) and pass it as `api_key` or in the
34
+ `TUNA_API_KEY` environment variable.
35
+
36
+ ## Forward to a local service
37
+
38
+ ```ruby
39
+ require "tuna/sdk"
40
+
41
+ Tuna::SDK.forward({ protocol: "http" }, "127.0.0.1:3000") do |tunnel|
42
+ puts "public URL: #{tunnel.url}"
43
+ tunnel.wait
44
+ end
45
+ ```
46
+
47
+ The local address is `host:port` or `unix:///path/to.sock`. Without a block
48
+ `forward` blocks until the tunnel ends for good. With a block it yields the
49
+ connected tunnel and closes it when the block returns; `tunnel.wait` blocks
50
+ until `tunnel.close` is called, for example from a signal handler:
51
+
52
+ ```ruby
53
+ trap("TERM") { Thread.new { tunnel.close } }
54
+ ```
55
+
56
+ ## Handle connections yourself
57
+
58
+ ```ruby
59
+ Tuna::SDK.listen(protocol: "tcp", port: "my-db") do |tunnel|
60
+ puts "public URL: #{tunnel.url}"
61
+ while (conn = tunnel.accept)
62
+ Thread.new(conn) do |c|
63
+ c.write(c.gets)
64
+ ensure
65
+ c.close
66
+ end
67
+ end
68
+ end
69
+ ```
70
+
71
+ `accept` returns a `UNIXSocket` connected to the visitor, or `nil` once the
72
+ tunnel is closed. Without a block `listen` returns the tunnel.
73
+
74
+ [`examples/runner.rb`](examples/runner.rb) is a complete command-line client
75
+ built on both calls.
76
+
77
+ ## Options
78
+
79
+ `options` is a Hash or a `Tuna::SDK::Options`:
80
+
81
+ | Key | Meaning |
82
+ |---|---|
83
+ | `protocol` | `"http"` or `"tcp"`, required |
84
+ | `api_key` | API key, defaults to `$TUNA_API_KEY` |
85
+ | `subdomain`, `domain` | reserved subdomain or custom domain for HTTP |
86
+ | `port` | reserved TCP port or its alias |
87
+ | `proxy_protocol` | PROXY protocol header version for TCP: `1` or `2` |
88
+ | `cidr_allow`, `cidr_deny` | client CIDRs filtered by the tuna.am node, TCP only |
89
+ | `location` | only for names and ports reserved in the legacy `ru` or `nl` zones; empty lets the server pick |
90
+ | `on_event` | callable receiving a `Tuna::SDK::Event` |
91
+ | `connect_timeout` | seconds to wait for the first connection; `nil` means no limit |
92
+ | `server_url`, `client_name` | API address and client name reported to the server |
93
+
94
+ ## Events and errors
95
+
96
+ `on_event` receives a `Tuna::SDK::Event` whose `type` is `:connected`,
97
+ `:reconnecting`, `:reconnected`, `:banner`, `:session_expiring`, `:terminated`
98
+ or `:local_error`, with `url`, `message`, `reason`, `error`, `retry_in` and
99
+ `expires_in` (seconds) where they apply. Calls never overlap and run on the
100
+ tunnel's threads, so keep the callback short.
101
+
102
+ ```ruby
103
+ on_event = ->(e) { warn "#{e.type} #{e.url || e.error&.message}" }
104
+ Tuna::SDK.forward({ protocol: "http", on_event: on_event }, "127.0.0.1:3000")
105
+ ```
106
+
107
+ Network failures and temporary server errors are retried: the pause grows from
108
+ 1 to 15 seconds with random jitter, and `Retry-After` is respected. A silent
109
+ node is detected by keepalive within 15 seconds and reported as
110
+ `Tuna::SDK::KeepAliveTimeoutError` in a `:reconnecting` event. The tunnel ends
111
+ with an error when retrying is pointless; check it with
112
+ `Tuna::SDK.permanent?(err)`:
113
+
114
+ - `Tuna::SDK::ServerError` — the API rejected the request: bad or revoked
115
+ key, missing scope, unknown reserved name, unpaid plan; it carries `status`,
116
+ `code`, `text` and `request_id`;
117
+ - `Tuna::SDK::TerminatedError` — the server closed the tunnel: it was
118
+ deleted, suspended or hit the session time limit; `reason` tells which.
119
+
120
+ ## Behaviour worth knowing
121
+
122
+ - `close` stops accepting and reconnecting, but the tunnel stays connected
123
+ until the last accepted connection is closed.
124
+ - When either side of a forwarded connection closes, the connection is closed
125
+ in both directions.
126
+ - The `Host` header and the PROXY protocol header reach your service as sent.
127
+ - The tunnel runs the SSH connection on its own thread; `accept`, `wait` and
128
+ `close` may be called from any thread.
129
+ - The API client is `Net::HTTP`. Use `SSL_CERT_FILE` for a private CA.
130
+
131
+ ## Contributing
132
+
133
+ This repository is a read-only mirror of the SDK directory in the tuna.am
134
+ monorepo. Issues and pull requests are welcome here: accepted changes are
135
+ applied upstream and come back with the next release.
136
+
137
+ ## License
138
+
139
+ [MIT](LICENSE)
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Tuna
4
+ module SDK
5
+ # The SDK version.
6
+ VERSION = "0.1.0"
7
+ end
8
+ end
data/lib/tuna/sdk.rb ADDED
@@ -0,0 +1,649 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "net/http"
5
+ require "net/ssh"
6
+ require "rbconfig"
7
+ require "socket"
8
+ require "timeout"
9
+ require "uri"
10
+ require_relative "sdk/version"
11
+
12
+ module Tuna
13
+ # Opens tuna.am tunnels from Ruby code.
14
+ #
15
+ # Tuna::SDK.listen returns a Tunnel whose #accept yields connections arriving
16
+ # at the public address. Tuna::SDK.forward proxies them to a local address.
17
+ #
18
+ # A tunnel survives network failures: it reconnects with backoff and keeps
19
+ # its public address. It ends on Tunnel#close or a permanent error (see
20
+ # Tuna::SDK.permanent?).
21
+ module SDK
22
+ # The tuna.am API used when Options#server_url is empty.
23
+ DEFAULT_SERVER_URL = "https://api.tuna.am"
24
+
25
+ CLIENT_VERSION = 2
26
+ SSH_USER = "tuna"
27
+ DIAL_TIMEOUT = 10
28
+ API_TIMEOUT = 15
29
+ KEEPALIVE_REQUEST = "keepalive@openssh.com"
30
+ KEEPALIVE_INTERVAL = 5
31
+ KEEPALIVE_TIMEOUT = 15
32
+ LOOP_TICK = 0.1
33
+ MIN_BACKOFF = 1.0
34
+ MAX_BACKOFF = 15.0
35
+ MAX_RETRY_AFTER = 300
36
+ PERMANENT_CODES = %w[PaymentRequired Unauthorized AuthorizationRequired Forbidden BadRequest NotFound UpgradeRequired].freeze
37
+ TERMINATE_MESSAGES = {
38
+ "deleted" => "tunnel was deleted",
39
+ "suspended" => "tunnel was suspended",
40
+ "session_limit" => "session time limit reached",
41
+ "session_ended" => "client session ended",
42
+ "reconnect" => "tunnel was taken over by another connection"
43
+ }.freeze
44
+ private_constant :CLIENT_VERSION, :SSH_USER, :DIAL_TIMEOUT, :API_TIMEOUT, :KEEPALIVE_REQUEST,
45
+ :KEEPALIVE_INTERVAL, :KEEPALIVE_TIMEOUT, :LOOP_TICK, :MIN_BACKOFF, :MAX_BACKOFF,
46
+ :MAX_RETRY_AFTER, :PERMANENT_CODES, :TERMINATE_MESSAGES
47
+
48
+ # Tunnel settings. Only +protocol+ is required.
49
+ #
50
+ # api_key:: tuna.am API key with the tunnels:connect scope, defaults to $TUNA_API_KEY
51
+ # protocol:: "http" or "tcp"
52
+ # location:: only for names and ports reserved in the legacy "ru" or "nl" zones
53
+ # subdomain, domain:: reserved subdomain or custom domain for HTTP tunnels
54
+ # port:: reserved TCP port or its alias
55
+ # proxy_protocol:: PROXY protocol header version for TCP tunnels, 1 or 2
56
+ # cidr_allow, cidr_deny:: client CIDRs allowed or rejected by a TCP tunnel
57
+ # server_url:: tuna.am API address, defaults to DEFAULT_SERVER_URL
58
+ # client_name:: name reported to the server, defaults to "tuna-sdk-ruby/<VERSION>"
59
+ # connect_timeout:: seconds to wait for the first connection, nil means no limit
60
+ # on_event:: callable receiving an Event; calls never overlap and come from
61
+ # the tunnel's own threads, so it must return quickly
62
+ Options = Struct.new(:api_key, :protocol, :location, :subdomain, :domain, :port, :proxy_protocol,
63
+ :cidr_allow, :cidr_deny, :server_url, :client_name, :connect_timeout, :on_event,
64
+ keyword_init: true)
65
+
66
+ # A change in the tunnel state.
67
+ #
68
+ # type:: :connected, :reconnected, :reconnecting, :banner, :session_expiring,
69
+ # :terminated or :local_error
70
+ # url:: public address, for :connected and :reconnected
71
+ # message:: human-readable text, for :banner and :terminated
72
+ # reason:: machine-readable cause, for :terminated
73
+ # error:: the cause, for :reconnecting and :local_error
74
+ # retry_in:: seconds before the next attempt, for :reconnecting
75
+ # expires_in:: seconds left, for :session_expiring
76
+ Event = Struct.new(:type, :url, :message, :reason, :error, :retry_in, :expires_in, keyword_init: true)
77
+
78
+ # Base class of SDK errors.
79
+ class Error < StandardError
80
+ # Whether retrying after this error is pointless.
81
+ def permanent?
82
+ false
83
+ end
84
+ end
85
+
86
+ # An error response from the tuna.am API.
87
+ class ServerError < Error
88
+ # HTTP status code.
89
+ attr_reader :status
90
+ # Machine-readable error code.
91
+ attr_reader :code
92
+ # Human-readable error text.
93
+ attr_reader :text
94
+ # Identifies the request for tuna.am support.
95
+ attr_reader :request_id
96
+ # Delay in seconds requested by the server, or nil.
97
+ attr_reader :retry_after
98
+
99
+ # Creates the error; +before_first_connect+ makes non-JSON 4xx permanent.
100
+ def initialize(status:, text:, code: nil, request_id: nil, retry_after: nil, before_first_connect: false)
101
+ @status = status
102
+ @text = text
103
+ @code = code
104
+ @request_id = request_id
105
+ @retry_after = retry_after
106
+ @before_first_connect = before_first_connect
107
+ super(request_id.to_s.empty? ? "tuna: #{text}" : "tuna: #{text} (request id #{request_id})")
108
+ end
109
+
110
+ # Marks the error as received before the tunnel ever came up.
111
+ def before_first_connect!
112
+ @before_first_connect = true
113
+ end
114
+
115
+ # Whether retrying after this error is pointless.
116
+ def permanent?
117
+ return true if status.between?(300, 399)
118
+ return true if @before_first_connect && status.between?(400, 499) && ![408, 429].include?(status)
119
+
120
+ PERMANENT_CODES.include?(code)
121
+ end
122
+ end
123
+
124
+ # The server closed the tunnel for good.
125
+ class TerminatedError < Error
126
+ # Machine-readable cause, e.g. "deleted" or "session_limit".
127
+ attr_reader :reason
128
+
129
+ # Creates the error for a terminate reason.
130
+ def initialize(reason)
131
+ @reason = reason
132
+ super("tuna: #{text}")
133
+ end
134
+
135
+ # Human-readable cause.
136
+ def text
137
+ TERMINATE_MESSAGES.fetch(reason) { "tunnel terminated by server (#{reason})" }
138
+ end
139
+
140
+ # Always true.
141
+ def permanent?
142
+ true
143
+ end
144
+ end
145
+
146
+ # The node stopped answering keepalive requests.
147
+ class KeepAliveTimeoutError < Error
148
+ # Creates the error.
149
+ def initialize(msg = "tuna: keepalive timeout")
150
+ super
151
+ end
152
+ end
153
+
154
+ class HostKeyVerifier
155
+ def initialize(blobs)
156
+ @blobs = blobs
157
+ end
158
+
159
+ def verify(arguments)
160
+ @blobs.include?(arguments[:key_blob])
161
+ end
162
+
163
+ def verify_signature
164
+ yield
165
+ end
166
+ end
167
+ private_constant :HostKeyVerifier
168
+
169
+ class << self
170
+ # Connects a tunnel that proxies connections to +addr+ ("host:port" or
171
+ # "unix:///path.sock") and blocks until it ends: returns nil after
172
+ # Tunnel#close, raises on a permanent error. With a block, yields the
173
+ # connected Tunnel, closes it when the block returns and returns the
174
+ # block's value.
175
+ def forward(options, addr)
176
+ dial_target(addr)
177
+ tunnel = Tunnel.new(options, addr)
178
+ return tunnel.wait unless block_given?
179
+
180
+ begin
181
+ yield tunnel
182
+ ensure
183
+ tunnel.close
184
+ end
185
+ end
186
+
187
+ # Connects a tunnel and returns it once it is up; Tunnel#accept returns
188
+ # its connections. With a block, yields the Tunnel, closes it when the
189
+ # block returns and returns the block's value.
190
+ def listen(options)
191
+ tunnel = Tunnel.new(options)
192
+ return tunnel unless block_given?
193
+
194
+ begin
195
+ yield tunnel
196
+ ensure
197
+ tunnel.close
198
+ end
199
+ end
200
+
201
+ # Whether retrying after +err+ is pointless.
202
+ def permanent?(err)
203
+ err.respond_to?(:permanent?) && err.permanent?
204
+ end
205
+
206
+ # Splits "host:port", "[v6]:port" or "unix:///path" into a socket target.
207
+ def dial_target(addr)
208
+ return [:unix, addr.delete_prefix("unix://")] if addr.start_with?("unix://")
209
+
210
+ host, sep, port = addr.rpartition(":")
211
+ raise ArgumentError, "tuna: invalid address #{addr.inspect}: want host:port or unix:///path.sock" if sep.empty? || host.empty? || port !~ /\A\d+\z/
212
+
213
+ [:tcp, host.delete_prefix("[").delete_suffix("]"), Integer(port, 10)]
214
+ end
215
+
216
+ # Opens a connection to a local address with the SDK's dial timeout.
217
+ def dial_local(addr)
218
+ kind, host, port = dial_target(addr)
219
+ return UNIXSocket.new(host) if kind == :unix
220
+
221
+ Socket.tcp(host, port, connect_timeout: DIAL_TIMEOUT)
222
+ end
223
+
224
+ # Pause before the next attempt for the current backoff and error.
225
+ def retry_delay(backoff, err, rand: Random)
226
+ wait = [MAX_BACKOFF, MIN_BACKOFF + rand.rand * backoff].min
227
+ wait = err.retry_after.to_f if err.is_a?(ServerError) && err.retry_after && err.retry_after > wait
228
+ wait
229
+ end
230
+
231
+ # Public address from a /v1/connect response.
232
+ def public_url(response, protocol)
233
+ url = response["public_url"].to_s
234
+ return url unless url.empty?
235
+ return "tcp://#{response['domain_name']}:#{response['endpoint_port'].to_i}" if protocol == "tcp"
236
+
237
+ "https://#{response['domain_name']}"
238
+ end
239
+
240
+ # Parses a /v1/connect response or raises ServerError.
241
+ def parse_response(status, body, location: nil, retry_after: nil)
242
+ return JSON.parse(body) if status.between?(200, 299)
243
+
244
+ fields = {}
245
+ if status.between?(300, 399)
246
+ fields[:text] = "server redirects to #{location.to_s.inspect}, check the server URL"
247
+ else
248
+ parsed = begin
249
+ JSON.parse(body.to_s)
250
+ rescue JSON::ParserError
251
+ nil
252
+ end
253
+ if parsed.is_a?(Hash) && !parsed["error"].to_s.empty?
254
+ fields = { text: parsed["error"], code: parsed["code"], request_id: parsed["request_id"] }
255
+ else
256
+ fields[:text] = "server responded with status #{status}"
257
+ end
258
+ end
259
+ secs = Integer(retry_after.to_s, 10, exception: false)
260
+ fields[:retry_after] = [secs, MAX_RETRY_AFTER].min if secs&.positive?
261
+ raise ServerError.new(status: status, **fields)
262
+ end
263
+
264
+ # Event from a line of the node's events channel: [:terminate, reason],
265
+ # [:session_expiring, seconds] or nil for anything else.
266
+ def node_event(line)
267
+ ev = JSON.parse(line)
268
+ return unless ev.is_a?(Hash)
269
+
270
+ case ev["type"]
271
+ when "terminate" then [:terminate, ev["reason"].to_s]
272
+ when "session_expiring" then [:session_expiring, ev["expires_in"].to_f]
273
+ end
274
+ rescue JSON::ParserError
275
+ nil
276
+ end
277
+
278
+ # Operating system name as the server expects it.
279
+ def os_name
280
+ case RbConfig::CONFIG["host_os"]
281
+ when /linux/ then "linux"
282
+ when /darwin/ then "darwin"
283
+ when /mswin|mingw|cygwin/ then "windows"
284
+ when /freebsd/ then "freebsd"
285
+ when /openbsd/ then "openbsd"
286
+ else RbConfig::CONFIG["host_os"]
287
+ end
288
+ end
289
+
290
+ # CPU architecture as the server expects it.
291
+ def arch_name
292
+ case RbConfig::CONFIG["host_cpu"]
293
+ when /x86_64|amd64|x64/ then "amd64"
294
+ when /aarch64|arm64/ then "arm64"
295
+ when /i[3-6]86/ then "386"
296
+ else RbConfig::CONFIG["host_cpu"]
297
+ end
298
+ end
299
+
300
+ # Options with defaults applied, or ArgumentError.
301
+ def normalize(options)
302
+ o = options.is_a?(Options) ? options.dup : Options.new(**options)
303
+ o.api_key = ENV.fetch("TUNA_API_KEY", "") if o.api_key.to_s.empty?
304
+ raise ArgumentError, "tuna: API key is required: set api_key or TUNA_API_KEY" if o.api_key.to_s.empty?
305
+
306
+ o.protocol = o.protocol.to_s
307
+ raise ArgumentError, "tuna: unsupported protocol #{o.protocol.inspect}" unless %w[http tcp].include?(o.protocol)
308
+
309
+ o.server_url = DEFAULT_SERVER_URL if o.server_url.to_s.empty?
310
+ uri = URI.parse(o.server_url)
311
+ raise ArgumentError, "tuna: invalid server URL #{o.server_url.inspect}: want https://host" unless %w[http https].include?(uri.scheme) && !uri.host.to_s.empty?
312
+
313
+ o.client_name = "tuna-sdk-ruby/#{VERSION}" if o.client_name.to_s.empty?
314
+ raise ArgumentError, "tuna: client_name must not contain control characters" if o.client_name.match?(/[[:cntrl:]]/)
315
+
316
+ o
317
+ rescue URI::InvalidURIError => e
318
+ raise ArgumentError, "tuna: invalid server URL: #{e.message}"
319
+ end
320
+
321
+ def monotonic
322
+ Process.clock_gettime(Process::CLOCK_MONOTONIC)
323
+ end
324
+ end
325
+
326
+ # A connected tunnel. It survives reconnects; it ends after #close or a
327
+ # permanent error.
328
+ class Tunnel
329
+ # Current public address, e.g. https://name.tuna.am or tcp://ru.tuna.am:40000.
330
+ attr_reader :url
331
+
332
+ # Connects and returns once the tunnel is up; raises on a permanent
333
+ # error or when Options#connect_timeout passes. Use Tuna::SDK.listen or
334
+ # Tuna::SDK.forward instead of calling it directly.
335
+ def initialize(options, forward_to = nil)
336
+ @o = SDK.normalize(options)
337
+ @forward_to = forward_to
338
+ @lock = Mutex.new
339
+ @cond = ConditionVariable.new
340
+ @emit_lock = Mutex.new
341
+ @conns = Thread::Queue.new
342
+ @state = :connecting
343
+ @closing = false
344
+ @error = nil
345
+ @last_error = nil
346
+ @ever_up = false
347
+ @session_id = ""
348
+ @banner_shown = false
349
+ @thread = Thread.new { run }
350
+ wait_ready
351
+ end
352
+
353
+ # Waits for the next connection to the public address and returns it as
354
+ # a socket. Returns nil after #close; raises the error that ended the
355
+ # tunnel.
356
+ def accept
357
+ io = @conns.pop
358
+ return io if io
359
+
360
+ @lock.synchronize { raise @error if @error }
361
+ nil
362
+ end
363
+
364
+ # Stops accepting connections and reconnecting. Connections accepted
365
+ # earlier keep working: the tunnel stays connected to the node until the
366
+ # last of them is closed. Does not wait; see #wait.
367
+ def close
368
+ @lock.synchronize do
369
+ @closing = true
370
+ @cond.broadcast
371
+ end
372
+ @conns.close
373
+ drain
374
+ nil
375
+ end
376
+
377
+ # Blocks until the tunnel ends: returns nil after #close, raises the
378
+ # permanent error otherwise.
379
+ def wait
380
+ @lock.synchronize { @cond.wait(@lock) until @state == :done }
381
+ raise @error if @error
382
+
383
+ nil
384
+ end
385
+
386
+ private
387
+
388
+ def drain
389
+ loop { @conns.pop(true).close }
390
+ rescue ThreadError
391
+ nil
392
+ end
393
+
394
+ def closing?
395
+ @lock.synchronize { @closing }
396
+ end
397
+
398
+ def wait_ready
399
+ timeout = @o.connect_timeout
400
+ deadline = timeout && SDK.monotonic + timeout
401
+ @lock.synchronize do
402
+ while @state == :connecting
403
+ left = deadline && deadline - SDK.monotonic
404
+ if left && left <= 0
405
+ @closing = true
406
+ @cond.broadcast
407
+ raise Error, start_error("tuna: tunnel did not come up within #{timeout}s")
408
+ end
409
+ @cond.wait(@lock, left)
410
+ end
411
+ raise @error || Error.new("tuna: tunnel closed before it came up") if @state == :done && !@ever_up
412
+ end
413
+ end
414
+
415
+ def start_error(msg)
416
+ @last_error ? "#{msg} (last attempt: #{@last_error.message})" : msg
417
+ end
418
+
419
+ def emit(**fields)
420
+ return unless @o.on_event
421
+
422
+ @emit_lock.synchronize { @o.on_event.call(Event.new(**fields)) }
423
+ end
424
+
425
+ def finish(err)
426
+ @lock.synchronize do
427
+ return if @state == :done
428
+
429
+ @error = err
430
+ @state = :done
431
+ @cond.broadcast
432
+ end
433
+ @conns.close
434
+ end
435
+
436
+ def sleep_unless_closed(seconds)
437
+ deadline = SDK.monotonic + seconds
438
+ @lock.synchronize do
439
+ until @closing
440
+ left = deadline - SDK.monotonic
441
+ return false if left <= 0
442
+
443
+ @cond.wait(@lock, left)
444
+ end
445
+ true
446
+ end
447
+ end
448
+
449
+ def run
450
+ backoff = MIN_BACKOFF
451
+ loop do
452
+ connected, err = session
453
+ return finish(nil) if closing?
454
+
455
+ err.before_first_connect! if err.is_a?(ServerError) && !@ever_up
456
+ @last_error = err
457
+ if SDK.permanent?(err)
458
+ emit(type: :terminated, reason: err.reason, message: err.text) if err.is_a?(TerminatedError)
459
+ return finish(err)
460
+ end
461
+ backoff = MIN_BACKOFF if connected
462
+ wait = SDK.retry_delay(backoff, err)
463
+ emit(type: :reconnecting, error: err, retry_in: wait)
464
+ return finish(nil) if sleep_unless_closed(wait)
465
+
466
+ backoff = [backoff * 2, MAX_BACKOFF].min
467
+ end
468
+ rescue StandardError => e
469
+ finish(e)
470
+ end
471
+
472
+ def session
473
+ cr = connect
474
+ @session_id = cr["tunnel_session_id"].to_s
475
+ if !cr["banner"].to_s.empty? && !@banner_shown
476
+ @banner_shown = true
477
+ emit(type: :banner, message: cr["banner"])
478
+ end
479
+ return [false, nil] if closing?
480
+
481
+ serve(dial(cr), cr)
482
+ rescue StandardError => e
483
+ [false, e]
484
+ end
485
+
486
+ def connect
487
+ uri = URI.parse("#{@o.server_url.chomp('/')}/v1/connect")
488
+ http = Net::HTTP.new(uri.host, uri.port)
489
+ http.use_ssl = uri.scheme == "https"
490
+ http.open_timeout = http.read_timeout = http.write_timeout = API_TIMEOUT
491
+ req = Net::HTTP::Post.new(uri, "Content-Type" => "application/json", "User-Agent" => @o.client_name)
492
+ req.body = JSON.generate(connect_body)
493
+ resp = http.request(req)
494
+ SDK.parse_response(resp.code.to_i, resp.body, location: resp["Location"], retry_after: resp["Retry-After"])
495
+ end
496
+
497
+ def connect_body
498
+ body = {
499
+ client_version: CLIENT_VERSION,
500
+ client_name: @o.client_name,
501
+ sdk_version: VERSION,
502
+ forwards_to: @forward_to.to_s,
503
+ protocol: @o.protocol,
504
+ location: @o.location.to_s,
505
+ subdomain: @o.subdomain.to_s,
506
+ domain: @o.domain.to_s,
507
+ token: @o.api_key,
508
+ os: SDK.os_name,
509
+ arch: SDK.arch_name,
510
+ port_or_alias: @o.port.to_s,
511
+ tunnel_session_id: @session_id,
512
+ proxy_protocol: @o.proxy_protocol.to_i
513
+ }
514
+ body[:cidr_allow_list] = Array(@o.cidr_allow) unless Array(@o.cidr_allow).empty?
515
+ body[:cidr_deny_list] = Array(@o.cidr_deny) unless Array(@o.cidr_deny).empty?
516
+ body
517
+ end
518
+
519
+ def dial(cr)
520
+ blobs = Array(cr["host_keys"]).map do |hk|
521
+ Net::SSH::Buffer.from(:key, Net::SSH::KeyFactory.load_data_public_key(hk["key"].to_s)).to_s
522
+ rescue StandardError => e
523
+ raise Error, "tuna: parse host key: #{e.message}"
524
+ end
525
+ _, host, port = SDK.dial_target(cr["address"].to_s)
526
+ Timeout.timeout(DIAL_TIMEOUT, Error, "tuna: node did not answer within #{DIAL_TIMEOUT}s") do
527
+ Net::SSH.start(host, SSH_USER,
528
+ port: port, password: cr["token"].to_s, auth_methods: ["password"],
529
+ verify_host_key: HostKeyVerifier.new(blobs), timeout: DIAL_TIMEOUT,
530
+ config: false, use_agent: false, keys: [], keys_only: true, non_interactive: true,
531
+ number_of_password_prompts: 0, user_known_hosts_file: [], global_known_hosts_file: [])
532
+ end
533
+ end
534
+
535
+ def serve(ssh, cr)
536
+ failure = nil
537
+ fail = ->(err) { failure ||= err }
538
+ connected = false
539
+ last_reply = last_ping = SDK.monotonic
540
+ ssh.forward
541
+ ssh.on_open_channel("forwarded-tcpip") { |_s, channel, _packet| accept_channel(ssh, channel) }
542
+ ssh.send_global_request("tcpip-forward", :string, "127.0.0.1", :long, 0) do |ok, _response|
543
+ next fail.call(Error.new("tuna: remote forward: request refused")) unless ok
544
+
545
+ open_events(ssh, fail)
546
+ connected = true
547
+ up(cr)
548
+ end
549
+ begin
550
+ ssh.loop(LOOP_TICK) do
551
+ now = SDK.monotonic
552
+ if now - last_reply > KEEPALIVE_TIMEOUT
553
+ fail.call(KeepAliveTimeoutError.new)
554
+ elsif now - last_ping >= KEEPALIVE_INTERVAL
555
+ last_ping = now
556
+ ssh.send_global_request(KEEPALIVE_REQUEST) { last_reply = SDK.monotonic }
557
+ end
558
+ failure.nil? && !(closing? && ssh.channels.values.none? { |c| c[:tuna_conn] })
559
+ end
560
+ rescue StandardError => e
561
+ fail.call(Error.new("tuna: connection to node lost: #{e.message}"))
562
+ ensure
563
+ begin
564
+ ssh.shutdown!
565
+ rescue StandardError
566
+ nil
567
+ end
568
+ end
569
+ [connected, failure]
570
+ end
571
+
572
+ def up(cr)
573
+ @url = SDK.public_url(cr, @o.protocol)
574
+ if @ever_up
575
+ emit(type: :reconnected, url: @url)
576
+ else
577
+ @ever_up = true
578
+ emit(type: :connected, url: @url)
579
+ @lock.synchronize do
580
+ @state = :up if @state == :connecting
581
+ @cond.broadcast
582
+ end
583
+ end
584
+ end
585
+
586
+ def open_events(ssh, fail)
587
+ buf = +""
588
+ channel = ssh.open_channel do |ch|
589
+ ch.exec("events") { |_c, _ok| nil }
590
+ ch.on_data do |c, data|
591
+ buf << data
592
+ while (i = buf.index("\n"))
593
+ kind, value = SDK.node_event(buf.slice!(0..i))
594
+ case kind
595
+ when :terminate
596
+ fail.call(TerminatedError.new(value))
597
+ c.close
598
+ when :session_expiring
599
+ emit(type: :session_expiring, expires_in: value)
600
+ end
601
+ end
602
+ end
603
+ end
604
+ channel.on_open_failed { |*| nil }
605
+ end
606
+
607
+ def accept_channel(ssh, channel)
608
+ ours, theirs = UNIXSocket.pair
609
+ channel[:tuna_conn] = true
610
+ ssh.forward.send(:prepare_client, ours, channel, :remote)
611
+ return theirs.close if closing?
612
+ return Thread.new { pipe(theirs) } if @forward_to
613
+
614
+ begin
615
+ @conns << theirs
616
+ rescue ClosedQueueError
617
+ theirs.close
618
+ end
619
+ end
620
+
621
+ def pipe(remote)
622
+ local = begin
623
+ SDK.dial_local(@forward_to)
624
+ rescue StandardError => e
625
+ emit(type: :local_error, error: e)
626
+ return remote.close
627
+ end
628
+ done = Thread::Queue.new
629
+ [[remote, local], [local, remote]].each do |src, dst|
630
+ Thread.new do
631
+ IO.copy_stream(src, dst)
632
+ rescue StandardError
633
+ nil
634
+ ensure
635
+ done << true
636
+ end
637
+ end
638
+ done.pop
639
+ [remote, local].each do |io|
640
+ io.shutdown
641
+ rescue StandardError
642
+ nil
643
+ ensure
644
+ io.close
645
+ end
646
+ end
647
+ end
648
+ end
649
+ end
metadata ADDED
@@ -0,0 +1,61 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: tuna-sdk
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - tuna.am authors
8
+ bindir: bin
9
+ cert_chain: []
10
+ date: 1980-01-02 00:00:00.000000000 Z
11
+ dependencies:
12
+ - !ruby/object:Gem::Dependency
13
+ name: net-ssh
14
+ requirement: !ruby/object:Gem::Requirement
15
+ requirements:
16
+ - - "~>"
17
+ - !ruby/object:Gem::Version
18
+ version: '8.2'
19
+ type: :runtime
20
+ prerelease: false
21
+ version_requirements: !ruby/object:Gem::Requirement
22
+ requirements:
23
+ - - "~>"
24
+ - !ruby/object:Gem::Version
25
+ version: '8.2'
26
+ description: Expose a local HTTP or TCP service at a public tuna.am address without
27
+ installing the tuna CLI.
28
+ email: info@tuna.am
29
+ executables: []
30
+ extensions: []
31
+ extra_rdoc_files: []
32
+ files:
33
+ - CHANGELOG.md
34
+ - LICENSE
35
+ - README.md
36
+ - lib/tuna/sdk.rb
37
+ - lib/tuna/sdk/version.rb
38
+ homepage: https://github.com/yuccastream/tuna-sdk-ruby
39
+ licenses:
40
+ - MIT
41
+ metadata:
42
+ source_code_uri: https://github.com/yuccastream/tuna-sdk-ruby
43
+ changelog_uri: https://github.com/yuccastream/tuna-sdk-ruby/blob/main/CHANGELOG.md
44
+ rdoc_options: []
45
+ require_paths:
46
+ - lib
47
+ required_ruby_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: '3.1'
52
+ required_rubygems_version: !ruby/object:Gem::Requirement
53
+ requirements:
54
+ - - ">="
55
+ - !ruby/object:Gem::Version
56
+ version: '0'
57
+ requirements: []
58
+ rubygems_version: 3.6.9
59
+ specification_version: 4
60
+ summary: Open tuna.am tunnels from Ruby code
61
+ test_files: []