tuna-sdk 0.1.0__tar.gz
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.
- tuna_sdk-0.1.0/.gitignore +5 -0
- tuna_sdk-0.1.0/CHANGELOG.md +7 -0
- tuna_sdk-0.1.0/LICENSE +21 -0
- tuna_sdk-0.1.0/PKG-INFO +164 -0
- tuna_sdk-0.1.0/README.md +144 -0
- tuna_sdk-0.1.0/examples/runner.py +183 -0
- tuna_sdk-0.1.0/pyproject.toml +47 -0
- tuna_sdk-0.1.0/tests/test_tuna.py +127 -0
- tuna_sdk-0.1.0/tuna_sdk/__init__.py +46 -0
- tuna_sdk-0.1.0/tuna_sdk/_api.py +153 -0
- tuna_sdk-0.1.0/tuna_sdk/_tunnel.py +621 -0
- tuna_sdk-0.1.0/tuna_sdk/py.typed +0 -0
- tuna_sdk-0.1.0/tuna_sdk/sync.py +108 -0
tuna_sdk-0.1.0/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.
|
tuna_sdk-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: tuna-sdk
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Open tuna.am tunnels from Python code
|
|
5
|
+
Project-URL: Homepage, https://tuna.am
|
|
6
|
+
Project-URL: Source, https://github.com/yuccastream/tuna-sdk-python
|
|
7
|
+
Author-email: "tuna.am authors" <info@tuna.am>
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: localhost,ssh,tuna,tunnel,webhook
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Framework :: AsyncIO
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Internet
|
|
16
|
+
Classifier: Typing :: Typed
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Requires-Dist: asyncssh<3,>=2.24.1
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
20
|
+
|
|
21
|
+
# tuna-sdk-python
|
|
22
|
+
|
|
23
|
+
[](https://pypi.org/project/tuna-sdk/)
|
|
24
|
+
|
|
25
|
+
Open [tuna.am](https://tuna.am) tunnels straight from Python code: expose a
|
|
26
|
+
local HTTP or TCP service at a public address without installing the `tuna`
|
|
27
|
+
CLI.
|
|
28
|
+
|
|
29
|
+
- Two ways in: `listen` hands you each incoming connection as a
|
|
30
|
+
`(reader, writer)` stream pair, `forward` proxies connections to a local
|
|
31
|
+
address.
|
|
32
|
+
- asyncio first, with a blocking `tuna_sdk.sync` API that also works in
|
|
33
|
+
Jupyter.
|
|
34
|
+
- Survives network failures: reconnects with backoff and keeps the same
|
|
35
|
+
public address.
|
|
36
|
+
- Small: the only dependency is [asyncssh](https://pypi.org/project/asyncssh/).
|
|
37
|
+
- Typed: ships `py.typed`.
|
|
38
|
+
|
|
39
|
+
The API is not stable yet: it may change before v1.
|
|
40
|
+
|
|
41
|
+
## Install
|
|
42
|
+
|
|
43
|
+
```shell
|
|
44
|
+
pip install tuna-sdk
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
The module name is `tuna_sdk`. Requires Python 3.10 or later.
|
|
48
|
+
|
|
49
|
+
## Authentication
|
|
50
|
+
|
|
51
|
+
Create an API key with the `tunnels:connect` scope at
|
|
52
|
+
[my.tuna.am](https://my.tuna.am) and pass it in `Options.api_key` or the
|
|
53
|
+
`TUNA_API_KEY` environment variable.
|
|
54
|
+
|
|
55
|
+
## Forward to a local service
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
import asyncio
|
|
59
|
+
import tuna_sdk
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def on_event(e: tuna_sdk.Event) -> None:
|
|
63
|
+
if e.type == "connected":
|
|
64
|
+
print("forwarding", e.url, "-> 127.0.0.1:8080")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
asyncio.run(tuna_sdk.forward(tuna_sdk.Options(protocol="http", on_event=on_event), "127.0.0.1:8080"))
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The local address is `host:port` or `unix:///path/to.sock`. `forward` runs
|
|
71
|
+
until the task is cancelled or the tunnel ends for good.
|
|
72
|
+
|
|
73
|
+
Without asyncio:
|
|
74
|
+
|
|
75
|
+
```python
|
|
76
|
+
tuna_sdk.sync.forward(tuna_sdk.Options(protocol="tcp", port="my-db"), "127.0.0.1:5432")
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Accept connections yourself
|
|
80
|
+
|
|
81
|
+
```python
|
|
82
|
+
async def main() -> None:
|
|
83
|
+
async with tuna_sdk.listen(tuna_sdk.Options(protocol="tcp")) as tunnel:
|
|
84
|
+
print("public URL:", tunnel.url)
|
|
85
|
+
async for reader, writer in tunnel:
|
|
86
|
+
asyncio.ensure_future(handle(reader, writer))
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
`reader` and `writer` are asyncssh `SSHReader` and `SSHWriter` objects with
|
|
90
|
+
the same methods as asyncio streams (`read`, `readline`, `write`, `drain`,
|
|
91
|
+
`close`). `await tunnel.accept()` returns the next pair.
|
|
92
|
+
|
|
93
|
+
`tuna_sdk.sync.listen` returns a tunnel whose `accept()` gives a regular
|
|
94
|
+
blocking `socket.socket`, so it plugs into `socketserver` and similar code:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
with tuna_sdk.sync.listen(tuna_sdk.Options(protocol="http")) as tunnel:
|
|
98
|
+
print("public URL:", tunnel.url)
|
|
99
|
+
for sock in tunnel:
|
|
100
|
+
handle(sock)
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Leaving the `with` block, or calling `close()`, stops accepting and
|
|
104
|
+
reconnecting; connections accepted earlier keep working and the tunnel stays
|
|
105
|
+
connected until the last of them is closed. `abort()` cuts them off too.
|
|
106
|
+
|
|
107
|
+
[`examples/runner.py`](examples/runner.py) is a complete command-line client
|
|
108
|
+
built on the SDK.
|
|
109
|
+
|
|
110
|
+
## Options
|
|
111
|
+
|
|
112
|
+
| Field | Meaning |
|
|
113
|
+
|---|---|
|
|
114
|
+
| `protocol` | `http` or `tcp`, required |
|
|
115
|
+
| `api_key` | API key, defaults to `$TUNA_API_KEY` |
|
|
116
|
+
| `subdomain`, `domain` | reserved subdomain or custom domain for HTTP |
|
|
117
|
+
| `port` | reserved TCP port or its alias |
|
|
118
|
+
| `proxy_protocol` | PROXY protocol header version for TCP: `1` or `2` |
|
|
119
|
+
| `cidr_allow`, `cidr_deny` | client CIDRs filtered by the tuna.am node, TCP only |
|
|
120
|
+
| `location` | only for names and ports reserved in the legacy `ru` or `nl` zones; empty lets the server pick |
|
|
121
|
+
| `on_event` | callback for tunnel events |
|
|
122
|
+
| `connect_timeout` | seconds to wait for the first connection; `None` means no limit |
|
|
123
|
+
| `server_url`, `ssl_context`, `client_name` | API address, TLS settings for it, client name reported to the server |
|
|
124
|
+
|
|
125
|
+
## Events and errors
|
|
126
|
+
|
|
127
|
+
`on_event` receives an `Event` with `type` one of `connected`,
|
|
128
|
+
`reconnecting`, `reconnected`, `banner`, `session_expiring`, `terminated` and
|
|
129
|
+
`local_error`. Calls never overlap and run on the event loop (for
|
|
130
|
+
`tuna_sdk.sync`, on its background thread), so keep the callback short.
|
|
131
|
+
|
|
132
|
+
Network failures and temporary server errors are retried: the pause grows from
|
|
133
|
+
1 to 15 seconds with random jitter, and `Retry-After` is respected. The tunnel
|
|
134
|
+
ends with an exception when retrying is pointless; check it with
|
|
135
|
+
`is_permanent`:
|
|
136
|
+
|
|
137
|
+
- `ServerError` — the API rejected the request: bad or revoked key, missing
|
|
138
|
+
scope, unknown reserved name, unpaid plan. Has `status`, `code`, `message`
|
|
139
|
+
and `request_id`;
|
|
140
|
+
- `TerminatedError` — the server closed the tunnel: it was deleted,
|
|
141
|
+
suspended or hit the session time limit. Has `reason`.
|
|
142
|
+
|
|
143
|
+
A connection the node stopped answering is reported in a `reconnecting` event
|
|
144
|
+
with `KeepAliveTimeoutError`. `accept` raises `ClosedError` after `close`.
|
|
145
|
+
|
|
146
|
+
## Behaviour worth knowing
|
|
147
|
+
|
|
148
|
+
- When either side of a forwarded connection closes, the connection is closed
|
|
149
|
+
in both directions.
|
|
150
|
+
- The `Host` header and the PROXY protocol header reach your service as sent.
|
|
151
|
+
- The API client is `urllib` and honours `HTTPS_PROXY`. Connections to
|
|
152
|
+
tuna.am nodes are plain SSH over TCP and do not use the proxy.
|
|
153
|
+
- Use `ssl_context` for a private CA.
|
|
154
|
+
|
|
155
|
+
## Contributing
|
|
156
|
+
|
|
157
|
+
This repository is a read-only mirror of the SDK directory in the tuna.am
|
|
158
|
+
monorepo. Issues and pull requests are welcome here: accepted changes are
|
|
159
|
+
applied upstream and come back with the next release.
|
|
160
|
+
|
|
161
|
+
## License
|
|
162
|
+
|
|
163
|
+
[MIT](LICENSE). asyncssh is a separate package under EPL-2.0 or
|
|
164
|
+
GPL-2.0-or-later.
|
tuna_sdk-0.1.0/README.md
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
# tuna-sdk-python
|
|
2
|
+
|
|
3
|
+
[](https://pypi.org/project/tuna-sdk/)
|
|
4
|
+
|
|
5
|
+
Open [tuna.am](https://tuna.am) tunnels straight from Python code: expose a
|
|
6
|
+
local HTTP or TCP service at a public address without installing the `tuna`
|
|
7
|
+
CLI.
|
|
8
|
+
|
|
9
|
+
- Two ways in: `listen` hands you each incoming connection as a
|
|
10
|
+
`(reader, writer)` stream pair, `forward` proxies connections to a local
|
|
11
|
+
address.
|
|
12
|
+
- asyncio first, with a blocking `tuna_sdk.sync` API that also works in
|
|
13
|
+
Jupyter.
|
|
14
|
+
- Survives network failures: reconnects with backoff and keeps the same
|
|
15
|
+
public address.
|
|
16
|
+
- Small: the only dependency is [asyncssh](https://pypi.org/project/asyncssh/).
|
|
17
|
+
- Typed: ships `py.typed`.
|
|
18
|
+
|
|
19
|
+
The API is not stable yet: it may change before v1.
|
|
20
|
+
|
|
21
|
+
## Install
|
|
22
|
+
|
|
23
|
+
```shell
|
|
24
|
+
pip install tuna-sdk
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
The module name is `tuna_sdk`. Requires Python 3.10 or later.
|
|
28
|
+
|
|
29
|
+
## Authentication
|
|
30
|
+
|
|
31
|
+
Create an API key with the `tunnels:connect` scope at
|
|
32
|
+
[my.tuna.am](https://my.tuna.am) and pass it in `Options.api_key` or the
|
|
33
|
+
`TUNA_API_KEY` environment variable.
|
|
34
|
+
|
|
35
|
+
## Forward to a local service
|
|
36
|
+
|
|
37
|
+
```python
|
|
38
|
+
import asyncio
|
|
39
|
+
import tuna_sdk
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def on_event(e: tuna_sdk.Event) -> None:
|
|
43
|
+
if e.type == "connected":
|
|
44
|
+
print("forwarding", e.url, "-> 127.0.0.1:8080")
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
asyncio.run(tuna_sdk.forward(tuna_sdk.Options(protocol="http", on_event=on_event), "127.0.0.1:8080"))
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The local address is `host:port` or `unix:///path/to.sock`. `forward` runs
|
|
51
|
+
until the task is cancelled or the tunnel ends for good.
|
|
52
|
+
|
|
53
|
+
Without asyncio:
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
tuna_sdk.sync.forward(tuna_sdk.Options(protocol="tcp", port="my-db"), "127.0.0.1:5432")
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
## Accept connections yourself
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
async def main() -> None:
|
|
63
|
+
async with tuna_sdk.listen(tuna_sdk.Options(protocol="tcp")) as tunnel:
|
|
64
|
+
print("public URL:", tunnel.url)
|
|
65
|
+
async for reader, writer in tunnel:
|
|
66
|
+
asyncio.ensure_future(handle(reader, writer))
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`reader` and `writer` are asyncssh `SSHReader` and `SSHWriter` objects with
|
|
70
|
+
the same methods as asyncio streams (`read`, `readline`, `write`, `drain`,
|
|
71
|
+
`close`). `await tunnel.accept()` returns the next pair.
|
|
72
|
+
|
|
73
|
+
`tuna_sdk.sync.listen` returns a tunnel whose `accept()` gives a regular
|
|
74
|
+
blocking `socket.socket`, so it plugs into `socketserver` and similar code:
|
|
75
|
+
|
|
76
|
+
```python
|
|
77
|
+
with tuna_sdk.sync.listen(tuna_sdk.Options(protocol="http")) as tunnel:
|
|
78
|
+
print("public URL:", tunnel.url)
|
|
79
|
+
for sock in tunnel:
|
|
80
|
+
handle(sock)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Leaving the `with` block, or calling `close()`, stops accepting and
|
|
84
|
+
reconnecting; connections accepted earlier keep working and the tunnel stays
|
|
85
|
+
connected until the last of them is closed. `abort()` cuts them off too.
|
|
86
|
+
|
|
87
|
+
[`examples/runner.py`](examples/runner.py) is a complete command-line client
|
|
88
|
+
built on the SDK.
|
|
89
|
+
|
|
90
|
+
## Options
|
|
91
|
+
|
|
92
|
+
| Field | Meaning |
|
|
93
|
+
|---|---|
|
|
94
|
+
| `protocol` | `http` or `tcp`, required |
|
|
95
|
+
| `api_key` | API key, defaults to `$TUNA_API_KEY` |
|
|
96
|
+
| `subdomain`, `domain` | reserved subdomain or custom domain for HTTP |
|
|
97
|
+
| `port` | reserved TCP port or its alias |
|
|
98
|
+
| `proxy_protocol` | PROXY protocol header version for TCP: `1` or `2` |
|
|
99
|
+
| `cidr_allow`, `cidr_deny` | client CIDRs filtered by the tuna.am node, TCP only |
|
|
100
|
+
| `location` | only for names and ports reserved in the legacy `ru` or `nl` zones; empty lets the server pick |
|
|
101
|
+
| `on_event` | callback for tunnel events |
|
|
102
|
+
| `connect_timeout` | seconds to wait for the first connection; `None` means no limit |
|
|
103
|
+
| `server_url`, `ssl_context`, `client_name` | API address, TLS settings for it, client name reported to the server |
|
|
104
|
+
|
|
105
|
+
## Events and errors
|
|
106
|
+
|
|
107
|
+
`on_event` receives an `Event` with `type` one of `connected`,
|
|
108
|
+
`reconnecting`, `reconnected`, `banner`, `session_expiring`, `terminated` and
|
|
109
|
+
`local_error`. Calls never overlap and run on the event loop (for
|
|
110
|
+
`tuna_sdk.sync`, on its background thread), so keep the callback short.
|
|
111
|
+
|
|
112
|
+
Network failures and temporary server errors are retried: the pause grows from
|
|
113
|
+
1 to 15 seconds with random jitter, and `Retry-After` is respected. The tunnel
|
|
114
|
+
ends with an exception when retrying is pointless; check it with
|
|
115
|
+
`is_permanent`:
|
|
116
|
+
|
|
117
|
+
- `ServerError` — the API rejected the request: bad or revoked key, missing
|
|
118
|
+
scope, unknown reserved name, unpaid plan. Has `status`, `code`, `message`
|
|
119
|
+
and `request_id`;
|
|
120
|
+
- `TerminatedError` — the server closed the tunnel: it was deleted,
|
|
121
|
+
suspended or hit the session time limit. Has `reason`.
|
|
122
|
+
|
|
123
|
+
A connection the node stopped answering is reported in a `reconnecting` event
|
|
124
|
+
with `KeepAliveTimeoutError`. `accept` raises `ClosedError` after `close`.
|
|
125
|
+
|
|
126
|
+
## Behaviour worth knowing
|
|
127
|
+
|
|
128
|
+
- When either side of a forwarded connection closes, the connection is closed
|
|
129
|
+
in both directions.
|
|
130
|
+
- The `Host` header and the PROXY protocol header reach your service as sent.
|
|
131
|
+
- The API client is `urllib` and honours `HTTPS_PROXY`. Connections to
|
|
132
|
+
tuna.am nodes are plain SSH over TCP and do not use the proxy.
|
|
133
|
+
- Use `ssl_context` for a private CA.
|
|
134
|
+
|
|
135
|
+
## Contributing
|
|
136
|
+
|
|
137
|
+
This repository is a read-only mirror of the SDK directory in the tuna.am
|
|
138
|
+
monorepo. Issues and pull requests are welcome here: accepted changes are
|
|
139
|
+
applied upstream and come back with the next release.
|
|
140
|
+
|
|
141
|
+
## License
|
|
142
|
+
|
|
143
|
+
[MIT](LICENSE). asyncssh is a separate package under EPL-2.0 or
|
|
144
|
+
GPL-2.0-or-later.
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
"""A tuna-tiny compatible tunnel client built on tuna-sdk.
|
|
2
|
+
|
|
3
|
+
python runner.py http|tcp <addr> [-s SUBDOMAIN] [-d DOMAIN] [-p PORT]
|
|
4
|
+
[--proxy-protocol N] [--cidr-allow CIDR]... [--cidr-deny CIDR]...
|
|
5
|
+
[--listen] [--log-format text|json]
|
|
6
|
+
|
|
7
|
+
The API key comes from TUNA_API_KEY, the API address from TUNA_ADDR. With
|
|
8
|
+
--listen the runner accepts tunnel connections itself and copies them to addr.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import argparse
|
|
14
|
+
import asyncio
|
|
15
|
+
import contextlib
|
|
16
|
+
import datetime
|
|
17
|
+
import json
|
|
18
|
+
import os
|
|
19
|
+
import signal
|
|
20
|
+
import sys
|
|
21
|
+
import urllib.parse
|
|
22
|
+
|
|
23
|
+
import tuna_sdk
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def local_addr(s: str) -> str:
|
|
27
|
+
if s.startswith("unix://"):
|
|
28
|
+
return s
|
|
29
|
+
if "://" in s:
|
|
30
|
+
u = urllib.parse.urlsplit(s)
|
|
31
|
+
if u.scheme != "http":
|
|
32
|
+
raise ValueError(f'scheme "{u.scheme}" is not supported')
|
|
33
|
+
return f"{u.hostname}:{u.port or 80}"
|
|
34
|
+
if ":" not in s:
|
|
35
|
+
if not s.isdigit() or int(s) > 65535:
|
|
36
|
+
raise ValueError(f'address "{s}" is not a port, host:port, http:// URL or unix:// path')
|
|
37
|
+
return "127.0.0.1:" + s
|
|
38
|
+
return s
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def describe(err: BaseException | None) -> str:
|
|
42
|
+
if err is None:
|
|
43
|
+
return ""
|
|
44
|
+
return str(err) or type(err).__name__
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def printer(as_json: bool, addr: str):
|
|
48
|
+
def emit(e: tuna_sdk.Event) -> None:
|
|
49
|
+
if as_json:
|
|
50
|
+
line = {
|
|
51
|
+
"time": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
|
|
52
|
+
"event": e.type,
|
|
53
|
+
"url": e.url,
|
|
54
|
+
"message": e.message,
|
|
55
|
+
"reason": e.reason,
|
|
56
|
+
"error": describe(e.error),
|
|
57
|
+
"retry_in": e.retry_in,
|
|
58
|
+
"expires_in": e.expires_in,
|
|
59
|
+
}
|
|
60
|
+
print(json.dumps({k: v for k, v in line.items() if v or k in ("time", "event")}), flush=True)
|
|
61
|
+
elif e.type in ("connected", "reconnected"):
|
|
62
|
+
print(f"Forwarding {e.url} -> {addr}", file=sys.stderr, flush=True)
|
|
63
|
+
elif e.type == "reconnecting":
|
|
64
|
+
print(f"Connection error ({describe(e.error)}), retry in {e.retry_in:.1f}s", file=sys.stderr, flush=True)
|
|
65
|
+
elif e.type == "session_expiring":
|
|
66
|
+
print(f"Session expires in {e.expires_in:g}s", file=sys.stderr, flush=True)
|
|
67
|
+
elif e.type == "local_error":
|
|
68
|
+
print(f"Local service unavailable: {describe(e.error)}", file=sys.stderr, flush=True)
|
|
69
|
+
elif e.type in ("banner", "terminated"):
|
|
70
|
+
print(e.message, file=sys.stderr, flush=True)
|
|
71
|
+
else:
|
|
72
|
+
print(f"Error: {describe(e.error)}", file=sys.stderr, flush=True)
|
|
73
|
+
|
|
74
|
+
return emit
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
async def copy(src: asyncio.StreamReader, dst: asyncio.StreamWriter) -> None:
|
|
78
|
+
with contextlib.suppress(Exception):
|
|
79
|
+
while data := await src.read(32768):
|
|
80
|
+
dst.write(data)
|
|
81
|
+
await dst.drain()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
async def proxy(reader, writer, addr: str) -> None:
|
|
85
|
+
try:
|
|
86
|
+
host, _, port = addr.rpartition(":")
|
|
87
|
+
local_reader, local_writer = await asyncio.open_connection(host, int(port))
|
|
88
|
+
except OSError:
|
|
89
|
+
writer.close()
|
|
90
|
+
return
|
|
91
|
+
tasks = [asyncio.ensure_future(copy(reader, local_writer)), asyncio.ensure_future(copy(local_reader, writer))]
|
|
92
|
+
await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
|
|
93
|
+
for t in tasks:
|
|
94
|
+
t.cancel()
|
|
95
|
+
writer.close()
|
|
96
|
+
local_writer.close()
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
async def serve(options: tuna_sdk.Options, addr: str, stop: asyncio.Event) -> None:
|
|
100
|
+
async with tuna_sdk.listen(options) as tunnel:
|
|
101
|
+
conns: set[asyncio.Task[None]] = set()
|
|
102
|
+
|
|
103
|
+
async def accept() -> None:
|
|
104
|
+
async for reader, writer in tunnel:
|
|
105
|
+
task = asyncio.ensure_future(proxy(reader, writer, addr))
|
|
106
|
+
conns.add(task)
|
|
107
|
+
task.add_done_callback(conns.discard)
|
|
108
|
+
|
|
109
|
+
acceptor = asyncio.ensure_future(accept())
|
|
110
|
+
stopper = asyncio.ensure_future(stop.wait())
|
|
111
|
+
await asyncio.wait([acceptor, stopper], return_when=asyncio.FIRST_COMPLETED)
|
|
112
|
+
stopper.cancel()
|
|
113
|
+
if acceptor.done():
|
|
114
|
+
acceptor.result()
|
|
115
|
+
tunnel.close()
|
|
116
|
+
if conns:
|
|
117
|
+
await asyncio.wait(conns, timeout=30)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
async def run(options: tuna_sdk.Options, addr: str, listen: bool) -> int:
|
|
121
|
+
stop = asyncio.Event()
|
|
122
|
+
loop = asyncio.get_running_loop()
|
|
123
|
+
for sig in (signal.SIGINT, signal.SIGTERM):
|
|
124
|
+
loop.add_signal_handler(sig, stop.set)
|
|
125
|
+
main = asyncio.ensure_future(serve(options, addr, stop) if listen else tuna_sdk.forward(options, addr))
|
|
126
|
+
stopper = asyncio.ensure_future(stop.wait())
|
|
127
|
+
await asyncio.wait([main, stopper], return_when=asyncio.FIRST_COMPLETED)
|
|
128
|
+
if stop.is_set() and not listen:
|
|
129
|
+
main.cancel()
|
|
130
|
+
try:
|
|
131
|
+
await main
|
|
132
|
+
except asyncio.CancelledError:
|
|
133
|
+
return 0
|
|
134
|
+
except tuna_sdk.TerminatedError:
|
|
135
|
+
return 1
|
|
136
|
+
except Exception as e:
|
|
137
|
+
if stop.is_set():
|
|
138
|
+
return 0
|
|
139
|
+
assert options.on_event is not None
|
|
140
|
+
options.on_event(tuna_sdk.Event("error", error=e))
|
|
141
|
+
return 1
|
|
142
|
+
finally:
|
|
143
|
+
stopper.cancel()
|
|
144
|
+
return 0
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def main() -> int:
|
|
148
|
+
p = argparse.ArgumentParser(prog="runner")
|
|
149
|
+
p.add_argument("protocol", choices=["http", "tcp"])
|
|
150
|
+
p.add_argument("addr")
|
|
151
|
+
p.add_argument("--api-key", default="")
|
|
152
|
+
p.add_argument("-s", dest="subdomain", default=os.environ.get("TUNA_SUBDOMAIN", ""))
|
|
153
|
+
p.add_argument("-d", dest="domain", default=os.environ.get("TUNA_DOMAIN", ""))
|
|
154
|
+
p.add_argument("-p", dest="port", default=os.environ.get("TUNA_TCP_PORT", ""))
|
|
155
|
+
p.add_argument("--proxy-protocol", type=int, default=0)
|
|
156
|
+
p.add_argument("--cidr-allow", action="append", default=[])
|
|
157
|
+
p.add_argument("--cidr-deny", action="append", default=[])
|
|
158
|
+
p.add_argument("--listen", action="store_true")
|
|
159
|
+
p.add_argument("--log-format", choices=["text", "json"], default=os.environ.get("TUNA_LOG_FORMAT", "text"))
|
|
160
|
+
args = p.parse_intermixed_args()
|
|
161
|
+
try:
|
|
162
|
+
addr = local_addr(args.addr)
|
|
163
|
+
except ValueError as e:
|
|
164
|
+
print(f"Error: {e}", file=sys.stderr)
|
|
165
|
+
return 2
|
|
166
|
+
options = tuna_sdk.Options(
|
|
167
|
+
protocol=args.protocol,
|
|
168
|
+
api_key=args.api_key,
|
|
169
|
+
subdomain=args.subdomain,
|
|
170
|
+
domain=args.domain,
|
|
171
|
+
port=args.port,
|
|
172
|
+
proxy_protocol=args.proxy_protocol,
|
|
173
|
+
cidr_allow=args.cidr_allow,
|
|
174
|
+
cidr_deny=args.cidr_deny,
|
|
175
|
+
server_url=os.environ.get("TUNA_ADDR", ""),
|
|
176
|
+
location=os.environ.get("TUNA_LOCATION", ""),
|
|
177
|
+
on_event=printer(args.log_format == "json", addr),
|
|
178
|
+
)
|
|
179
|
+
return asyncio.run(run(options, addr, args.listen))
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
if __name__ == "__main__":
|
|
183
|
+
sys.exit(main())
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "tuna-sdk"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "Open tuna.am tunnels from Python code"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
license-files = ["LICENSE"]
|
|
12
|
+
authors = [{ name = "tuna.am authors", email = "info@tuna.am" }]
|
|
13
|
+
requires-python = ">=3.10"
|
|
14
|
+
dependencies = ["asyncssh>=2.24.1,<3"]
|
|
15
|
+
keywords = ["tunnel", "tuna", "ssh", "localhost", "webhook"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 4 - Beta",
|
|
18
|
+
"Framework :: AsyncIO",
|
|
19
|
+
"Intended Audience :: Developers",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Topic :: Internet",
|
|
22
|
+
"Typing :: Typed",
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
[project.urls]
|
|
26
|
+
Homepage = "https://tuna.am"
|
|
27
|
+
Source = "https://github.com/yuccastream/tuna-sdk-python"
|
|
28
|
+
|
|
29
|
+
[dependency-groups]
|
|
30
|
+
dev = ["pytest>=9.2"]
|
|
31
|
+
|
|
32
|
+
[tool.hatch.version]
|
|
33
|
+
path = "tuna_sdk/_tunnel.py"
|
|
34
|
+
pattern = 'VERSION = "(?P<version>[^"]+)"'
|
|
35
|
+
|
|
36
|
+
[tool.hatch.build.targets.sdist]
|
|
37
|
+
include = ["tuna_sdk", "tests", "examples", "README.md", "CHANGELOG.md", "LICENSE"]
|
|
38
|
+
|
|
39
|
+
[tool.hatch.build.targets.wheel]
|
|
40
|
+
packages = ["tuna_sdk"]
|
|
41
|
+
|
|
42
|
+
[tool.ruff]
|
|
43
|
+
target-version = "py310"
|
|
44
|
+
line-length = 120
|
|
45
|
+
|
|
46
|
+
[tool.ruff.lint]
|
|
47
|
+
select = ["E", "F", "W", "I", "UP", "B", "SIM", "RUF"]
|