datasette-tailscale 0.1a0__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.
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.4
2
+ Name: datasette-tailscale
3
+ Version: 0.1a0
4
+ Summary: Run a Datasette instance on a Tailscale network
5
+ Author: Simon Willison
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/datasette/datasette-tailscale
8
+ Project-URL: Changelog, https://github.com/datasette/datasette-tailscale/releases
9
+ Project-URL: Issues, https://github.com/datasette/datasette-tailscale/issues
10
+ Project-URL: CI, https://github.com/datasette/datasette-tailscale/actions
11
+ Classifier: Framework :: Datasette
12
+ Requires-Python: >=3.12
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: datasette
16
+ Requires-Dist: tailscale-py
17
+ Dynamic: license-file
18
+
19
+ # datasette-tailscale
20
+
21
+ [![PyPI](https://img.shields.io/pypi/v/datasette-tailscale.svg)](https://pypi.org/project/datasette-tailscale/)
22
+ [![Changelog](https://img.shields.io/github/v/release/datasette/datasette-tailscale?include_prereleases&label=changelog)](https://github.com/datasette/datasette-tailscale/releases)
23
+ [![Tests](https://github.com/datasette/datasette-tailscale/actions/workflows/test.yml/badge.svg)](https://github.com/datasette/datasette-tailscale/actions/workflows/test.yml)
24
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/datasette/datasette-tailscale/blob/main/LICENSE)
25
+
26
+ Run a Datasette instance on a [Tailscale](https://tailscale.com/) network
27
+
28
+ > [!WARNING]
29
+ > This is an *experimental alpha* plugin. The underlying library it uses ([tailscale-rs](https://github.com/tailscale/tailscale-rs#tailscale-rs)) is also experimental and carries no security guarantees.
30
+
31
+ This plugin adds a `datasette tailscale` command that serves Datasette as its
32
+ own node on your [Tailscale](https://tailscale.com/) tailnet. Datasette itself
33
+ binds only to `127.0.0.1` — a userspace Tailscale node is the sole way in, so
34
+ the instance is reachable only by other devices on your tailnet and never from
35
+ the public internet or your local network.
36
+
37
+ It uses the [tailscale-py](https://pypi.org/project/tailscale-py/) package
38
+ (Python bindings for `tailscale-rs`), so there's no `tailscaled` daemon to run
39
+ and no root privileges required.
40
+
41
+ ## Installation
42
+
43
+ Install this plugin in the same environment as Datasette.
44
+ ```bash
45
+ datasette install datasette-tailscale
46
+ ```
47
+ ## Usage
48
+
49
+ Generate a [Tailscale auth key](https://login.tailscale.com/admin/settings/keys)
50
+ (an ephemeral, reusable key is a good choice) and serve a database:
51
+
52
+ ```bash
53
+ datasette tailscale mydata.db --ts-authkey tskey-auth-xxxx
54
+ ```
55
+
56
+ You can also supply the key via the `TS_AUTHKEY` environment variable:
57
+
58
+ ```bash
59
+ export TS_AUTHKEY=tskey-auth-xxxx
60
+ datasette tailscale mydata.db
61
+ ```
62
+
63
+ If you omit the auth key entirely, an interactive login URL is printed on first
64
+ run for you to click.
65
+
66
+ Once it connects you'll see:
67
+
68
+ ```
69
+ Connected. Tailnet IPv4: 100.x.y.z
70
+ Serving Datasette at http://datasette (reachable only on your tailnet)
71
+ ```
72
+
73
+ Any other device on your tailnet can now reach it at `http://datasette/` (via
74
+ MagicDNS) or by its tailnet IP.
75
+
76
+ ### Options
77
+
78
+ The command accepts **all** the options that `datasette serve` accepts —
79
+ `-m/--metadata`, `--setting`, `--root`, `--immutable`, `--cors`, etc. — because
80
+ they are inherited dynamically from `datasette serve` at runtime. (The
81
+ `--host`, `--port`, `--reload`, `--uds`, `--get`, `--open` and `--ssl-*`
82
+ options are suppressed, since they don't apply when serving over a tailnet.)
83
+
84
+ In addition it adds these tailscale-specific options:
85
+
86
+ - `--ts-hostname` — the hostname this node registers as on your tailnet
87
+ (default: `datasette`).
88
+ - `--ts-authkey` — your Tailscale auth key (or set `TS_AUTHKEY`). If omitted, an
89
+ interactive login URL is printed on first run.
90
+ - `--ts-state-dir` — directory for persisting the tailnet node identity across
91
+ restarts (default: `$XDG_STATE_HOME/datasette-tailscale`). A persistent state
92
+ directory gives the node a stable identity; an ephemeral auth key lets the
93
+ node disappear from your tailnet when the process exits.
94
+ - `--ts-port` — the port to listen on over the tailnet (default: `80`).
95
+
96
+ ### HTTPS and security notes
97
+
98
+ Traffic between tailnet devices is end-to-end encrypted by WireGuard, so this
99
+ plugin serves plain **HTTP** over the tailnet rather than terminating TLS. The
100
+ URL is `http://`, but the wire is still encrypted.
101
+
102
+ `tailscale-rs` is early-stage, experimental software with unvalidated
103
+ cryptography. The plugin sets the `TS_RS_EXPERIMENT=this_is_unstable_software`
104
+ acknowledgement on your behalf and prints a warning. Use it only on a tailnet
105
+ you trust.
106
+
107
+ ## Development
108
+
109
+ To set up this plugin locally, first checkout the code. You can confirm it is available like this:
110
+ ```bash
111
+ cd datasette-tailscale
112
+ # Confirm the plugin is visible
113
+ uv run datasette plugins
114
+ ```
115
+ To run the tests:
116
+ ```bash
117
+ uv run pytest
118
+ ```
@@ -0,0 +1,100 @@
1
+ # datasette-tailscale
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/datasette-tailscale.svg)](https://pypi.org/project/datasette-tailscale/)
4
+ [![Changelog](https://img.shields.io/github/v/release/datasette/datasette-tailscale?include_prereleases&label=changelog)](https://github.com/datasette/datasette-tailscale/releases)
5
+ [![Tests](https://github.com/datasette/datasette-tailscale/actions/workflows/test.yml/badge.svg)](https://github.com/datasette/datasette-tailscale/actions/workflows/test.yml)
6
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/datasette/datasette-tailscale/blob/main/LICENSE)
7
+
8
+ Run a Datasette instance on a [Tailscale](https://tailscale.com/) network
9
+
10
+ > [!WARNING]
11
+ > This is an *experimental alpha* plugin. The underlying library it uses ([tailscale-rs](https://github.com/tailscale/tailscale-rs#tailscale-rs)) is also experimental and carries no security guarantees.
12
+
13
+ This plugin adds a `datasette tailscale` command that serves Datasette as its
14
+ own node on your [Tailscale](https://tailscale.com/) tailnet. Datasette itself
15
+ binds only to `127.0.0.1` — a userspace Tailscale node is the sole way in, so
16
+ the instance is reachable only by other devices on your tailnet and never from
17
+ the public internet or your local network.
18
+
19
+ It uses the [tailscale-py](https://pypi.org/project/tailscale-py/) package
20
+ (Python bindings for `tailscale-rs`), so there's no `tailscaled` daemon to run
21
+ and no root privileges required.
22
+
23
+ ## Installation
24
+
25
+ Install this plugin in the same environment as Datasette.
26
+ ```bash
27
+ datasette install datasette-tailscale
28
+ ```
29
+ ## Usage
30
+
31
+ Generate a [Tailscale auth key](https://login.tailscale.com/admin/settings/keys)
32
+ (an ephemeral, reusable key is a good choice) and serve a database:
33
+
34
+ ```bash
35
+ datasette tailscale mydata.db --ts-authkey tskey-auth-xxxx
36
+ ```
37
+
38
+ You can also supply the key via the `TS_AUTHKEY` environment variable:
39
+
40
+ ```bash
41
+ export TS_AUTHKEY=tskey-auth-xxxx
42
+ datasette tailscale mydata.db
43
+ ```
44
+
45
+ If you omit the auth key entirely, an interactive login URL is printed on first
46
+ run for you to click.
47
+
48
+ Once it connects you'll see:
49
+
50
+ ```
51
+ Connected. Tailnet IPv4: 100.x.y.z
52
+ Serving Datasette at http://datasette (reachable only on your tailnet)
53
+ ```
54
+
55
+ Any other device on your tailnet can now reach it at `http://datasette/` (via
56
+ MagicDNS) or by its tailnet IP.
57
+
58
+ ### Options
59
+
60
+ The command accepts **all** the options that `datasette serve` accepts —
61
+ `-m/--metadata`, `--setting`, `--root`, `--immutable`, `--cors`, etc. — because
62
+ they are inherited dynamically from `datasette serve` at runtime. (The
63
+ `--host`, `--port`, `--reload`, `--uds`, `--get`, `--open` and `--ssl-*`
64
+ options are suppressed, since they don't apply when serving over a tailnet.)
65
+
66
+ In addition it adds these tailscale-specific options:
67
+
68
+ - `--ts-hostname` — the hostname this node registers as on your tailnet
69
+ (default: `datasette`).
70
+ - `--ts-authkey` — your Tailscale auth key (or set `TS_AUTHKEY`). If omitted, an
71
+ interactive login URL is printed on first run.
72
+ - `--ts-state-dir` — directory for persisting the tailnet node identity across
73
+ restarts (default: `$XDG_STATE_HOME/datasette-tailscale`). A persistent state
74
+ directory gives the node a stable identity; an ephemeral auth key lets the
75
+ node disappear from your tailnet when the process exits.
76
+ - `--ts-port` — the port to listen on over the tailnet (default: `80`).
77
+
78
+ ### HTTPS and security notes
79
+
80
+ Traffic between tailnet devices is end-to-end encrypted by WireGuard, so this
81
+ plugin serves plain **HTTP** over the tailnet rather than terminating TLS. The
82
+ URL is `http://`, but the wire is still encrypted.
83
+
84
+ `tailscale-rs` is early-stage, experimental software with unvalidated
85
+ cryptography. The plugin sets the `TS_RS_EXPERIMENT=this_is_unstable_software`
86
+ acknowledgement on your behalf and prints a warning. Use it only on a tailnet
87
+ you trust.
88
+
89
+ ## Development
90
+
91
+ To set up this plugin locally, first checkout the code. You can confirm it is available like this:
92
+ ```bash
93
+ cd datasette-tailscale
94
+ # Confirm the plugin is visible
95
+ uv run datasette plugins
96
+ ```
97
+ To run the tests:
98
+ ```bash
99
+ uv run pytest
100
+ ```
@@ -0,0 +1,255 @@
1
+ import asyncio
2
+ import os
3
+ import pathlib
4
+ import socket
5
+
6
+ import click
7
+ from datasette import hookimpl
8
+
9
+ # tailscale-rs requires this env var to be set to acknowledge that it is
10
+ # experimental software. We set it on behalf of the user (and warn them) so
11
+ # that `datasette tailscale` works out of the box.
12
+ EXPERIMENT_VAR = "TS_RS_EXPERIMENT"
13
+ EXPERIMENT_VALUE = "this_is_unstable_software"
14
+
15
+ # datasette serve options that we override or that don't make sense when
16
+ # serving over a tailnet. Everything NOT in this set is inherited verbatim from
17
+ # datasette serve - so new serve options are picked up automatically.
18
+ OVERRIDDEN_SERVE_OPTIONS = {
19
+ "host", # forced to 127.0.0.1
20
+ "port", # forced to an OS-assigned free loopback port
21
+ "uds", # we bind host/port, not a unix socket
22
+ "reload", # hupper re-exec would re-run the tailnet connect on every change
23
+ "get", # one-shot request-and-exit makes no sense for a long-lived listener
24
+ "open_browser", # would open a useless loopback URL
25
+ "ssl_keyfile", # we reverse-proxy plain HTTP; the tailnet encrypts the wire
26
+ "ssl_certfile",
27
+ }
28
+
29
+
30
+ def _free_loopback_port():
31
+ "Ask the OS for a free port on 127.0.0.1."
32
+ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
33
+ s.bind(("127.0.0.1", 0))
34
+ return s.getsockname()[1]
35
+
36
+
37
+ def _default_state_dir():
38
+ "XDG state directory for persisting tailnet node identity."
39
+ base = os.environ.get("XDG_STATE_HOME") or os.path.expanduser(
40
+ "~/.local/state"
41
+ )
42
+ return pathlib.Path(base) / "datasette-tailscale"
43
+
44
+
45
+ @hookimpl
46
+ def register_commands(cli):
47
+ # Import here so importing the plugin never fails if datasette internals move
48
+ from datasette.cli import serve
49
+
50
+ # Inherit every serve option except the ones we override. This means future
51
+ # additions to `datasette serve` are picked up automatically without any
52
+ # changes to this plugin.
53
+ inherited = [
54
+ param
55
+ for param in serve.params
56
+ if param.name not in OVERRIDDEN_SERVE_OPTIONS
57
+ ]
58
+
59
+ # Our own tailscale-specific options, shown first in --help.
60
+ tailscale_options = [
61
+ click.Option(
62
+ ["--ts-hostname", "ts_hostname"],
63
+ default="datasette",
64
+ show_default=True,
65
+ help="Hostname for this node on your tailnet",
66
+ ),
67
+ click.Option(
68
+ ["--ts-authkey", "ts_authkey"],
69
+ envvar="TS_AUTHKEY",
70
+ default=None,
71
+ help=(
72
+ "Tailscale auth key (or set TS_AUTHKEY). If omitted, an "
73
+ "interactive login URL is printed on first run."
74
+ ),
75
+ ),
76
+ click.Option(
77
+ ["--ts-state-dir", "ts_state_dir"],
78
+ type=click.Path(file_okay=False, dir_okay=True),
79
+ default=None,
80
+ help=(
81
+ "Directory for persisting tailnet node identity "
82
+ "(default: $XDG_STATE_HOME/datasette-tailscale)"
83
+ ),
84
+ ),
85
+ click.Option(
86
+ ["--ts-port", "ts_port"],
87
+ type=click.IntRange(1, 65535),
88
+ default=80,
89
+ show_default=True,
90
+ help="Port to listen on over the tailnet",
91
+ ),
92
+ ]
93
+
94
+ def tailscale(ts_hostname, ts_authkey, ts_state_dir, ts_port, **serve_kwargs):
95
+ # Force Datasette to bind to loopback only - the tailnet listener is the
96
+ # sole ingress. Supply values for every serve option we suppressed so
97
+ # the serve callback's full signature is satisfied.
98
+ free_port = _free_loopback_port()
99
+ serve_kwargs.update(
100
+ host="127.0.0.1",
101
+ port=free_port,
102
+ uds=None,
103
+ reload=False,
104
+ get=None,
105
+ open_browser=False,
106
+ ssl_keyfile=None,
107
+ ssl_certfile=None,
108
+ )
109
+
110
+ # Build the Datasette instance using serve's own logic (file validation,
111
+ # --create, config_dir handling, metadata parsing, settings, etc.) but
112
+ # stop short of running uvicorn.
113
+ ds = serve.callback(**serve_kwargs, return_instance=True)
114
+
115
+ if ts_state_dir:
116
+ state_path = pathlib.Path(ts_state_dir)
117
+ else:
118
+ state_path = _default_state_dir()
119
+ state_path.mkdir(parents=True, exist_ok=True)
120
+ key_file = str(state_path / "{}.json".format(ts_hostname))
121
+
122
+ asyncio.run(
123
+ _run(ds, free_port, ts_hostname, ts_authkey, key_file, ts_port)
124
+ )
125
+
126
+ cmd = click.Command(
127
+ name="tailscale",
128
+ callback=tailscale,
129
+ params=tailscale_options + inherited,
130
+ help=(
131
+ "Serve Datasette over your Tailscale tailnet.\n\n"
132
+ "Datasette binds to 127.0.0.1 only; a userspace Tailscale node is "
133
+ "the sole ingress, so the instance is reachable only by other "
134
+ "devices on your tailnet. Accepts all the options that "
135
+ "`datasette serve` accepts."
136
+ ),
137
+ )
138
+ cli.add_command(cmd)
139
+
140
+
141
+ async def _proxy(ts_stream, port):
142
+ "Bridge one tailnet TCP stream to a fresh loopback connection to Datasette."
143
+ try:
144
+ reader, writer = await asyncio.open_connection("127.0.0.1", port)
145
+ except OSError:
146
+ return
147
+
148
+ # Disable Nagle on the loopback socket. Without this, small HTTP writes
149
+ # (headers, the tail of a response) can sit unflushed waiting for an ACK,
150
+ # which shows up as responses dribbling through or appearing to hang.
151
+ sock = writer.get_extra_info("socket")
152
+ if sock is not None:
153
+ try:
154
+ sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
155
+ except OSError:
156
+ pass
157
+
158
+ async def tailnet_to_local():
159
+ try:
160
+ while True:
161
+ data = await ts_stream.recv()
162
+ if not data:
163
+ break
164
+ writer.write(data)
165
+ await writer.drain()
166
+ except Exception:
167
+ pass
168
+ # Half-close: tell the backend we're done sending, but keep the socket
169
+ # open so it can still write its response back to us. Fully closing here
170
+ # would race the response and truncate it.
171
+ try:
172
+ if writer.can_write_eof():
173
+ writer.write_eof()
174
+ except Exception:
175
+ pass
176
+
177
+ async def local_to_tailnet():
178
+ try:
179
+ while True:
180
+ data = await reader.read(65536)
181
+ if not data:
182
+ break
183
+ # send() may transmit fewer bytes than offered.
184
+ while data:
185
+ sent = await ts_stream.send(data)
186
+ data = data[sent:]
187
+ except Exception:
188
+ pass
189
+
190
+ try:
191
+ await asyncio.gather(tailnet_to_local(), local_to_tailnet())
192
+ finally:
193
+ try:
194
+ writer.close()
195
+ except Exception:
196
+ pass
197
+
198
+
199
+ async def _run(ds, free_port, ts_hostname, authkey, key_file, ts_port):
200
+ import uvicorn
201
+
202
+ os.environ.setdefault(EXPERIMENT_VAR, EXPERIMENT_VALUE)
203
+ import tailscale
204
+
205
+ click.echo(
206
+ "datasette-tailscale uses tailscale-rs, which is experimental software "
207
+ "with unvalidated cryptography. Use only on a tailnet you trust.",
208
+ err=True,
209
+ )
210
+
211
+ # Run Datasette's startup plugin hooks, as `datasette serve` would.
212
+ await ds.invoke_startup()
213
+
214
+ # Start Datasette on loopback in this event loop.
215
+ config = uvicorn.Config(
216
+ ds.app(),
217
+ host="127.0.0.1",
218
+ port=free_port,
219
+ log_level="info",
220
+ lifespan="on",
221
+ # The tailnet client controls connection lifetime; keep the loopback
222
+ # connection alive long enough that the backend doesn't unilaterally
223
+ # tear down a keep-alive connection the client is still reusing.
224
+ timeout_keep_alive=120,
225
+ )
226
+ server = uvicorn.Server(config)
227
+ uvicorn_task = asyncio.create_task(server.serve())
228
+
229
+ # Join the tailnet.
230
+ click.echo("Connecting to your tailnet as {!r}...".format(ts_hostname))
231
+ if not authkey:
232
+ click.echo(
233
+ "No auth key supplied - watch for an interactive login URL below.",
234
+ err=True,
235
+ )
236
+ dev = await tailscale.connect(key_file, authkey, hostname=ts_hostname)
237
+ ipv4 = await dev.ipv4_addr()
238
+ click.echo("Connected. Tailnet IPv4: {}".format(ipv4))
239
+
240
+ listener = await dev.tcp_listen((ipv4, ts_port))
241
+ suffix = "" if ts_port == 80 else ":{}".format(ts_port)
242
+ click.echo(
243
+ "Serving Datasette at http://{}{} (reachable only on your tailnet)".format(
244
+ ts_hostname, suffix
245
+ )
246
+ )
247
+ click.echo("Press Ctrl-C to stop.")
248
+
249
+ try:
250
+ while True:
251
+ stream = await listener.accept()
252
+ asyncio.create_task(_proxy(stream, free_port))
253
+ finally:
254
+ server.should_exit = True
255
+ await uvicorn_task
@@ -0,0 +1,118 @@
1
+ Metadata-Version: 2.4
2
+ Name: datasette-tailscale
3
+ Version: 0.1a0
4
+ Summary: Run a Datasette instance on a Tailscale network
5
+ Author: Simon Willison
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/datasette/datasette-tailscale
8
+ Project-URL: Changelog, https://github.com/datasette/datasette-tailscale/releases
9
+ Project-URL: Issues, https://github.com/datasette/datasette-tailscale/issues
10
+ Project-URL: CI, https://github.com/datasette/datasette-tailscale/actions
11
+ Classifier: Framework :: Datasette
12
+ Requires-Python: >=3.12
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: datasette
16
+ Requires-Dist: tailscale-py
17
+ Dynamic: license-file
18
+
19
+ # datasette-tailscale
20
+
21
+ [![PyPI](https://img.shields.io/pypi/v/datasette-tailscale.svg)](https://pypi.org/project/datasette-tailscale/)
22
+ [![Changelog](https://img.shields.io/github/v/release/datasette/datasette-tailscale?include_prereleases&label=changelog)](https://github.com/datasette/datasette-tailscale/releases)
23
+ [![Tests](https://github.com/datasette/datasette-tailscale/actions/workflows/test.yml/badge.svg)](https://github.com/datasette/datasette-tailscale/actions/workflows/test.yml)
24
+ [![License](https://img.shields.io/badge/license-Apache%202.0-blue.svg)](https://github.com/datasette/datasette-tailscale/blob/main/LICENSE)
25
+
26
+ Run a Datasette instance on a [Tailscale](https://tailscale.com/) network
27
+
28
+ > [!WARNING]
29
+ > This is an *experimental alpha* plugin. The underlying library it uses ([tailscale-rs](https://github.com/tailscale/tailscale-rs#tailscale-rs)) is also experimental and carries no security guarantees.
30
+
31
+ This plugin adds a `datasette tailscale` command that serves Datasette as its
32
+ own node on your [Tailscale](https://tailscale.com/) tailnet. Datasette itself
33
+ binds only to `127.0.0.1` — a userspace Tailscale node is the sole way in, so
34
+ the instance is reachable only by other devices on your tailnet and never from
35
+ the public internet or your local network.
36
+
37
+ It uses the [tailscale-py](https://pypi.org/project/tailscale-py/) package
38
+ (Python bindings for `tailscale-rs`), so there's no `tailscaled` daemon to run
39
+ and no root privileges required.
40
+
41
+ ## Installation
42
+
43
+ Install this plugin in the same environment as Datasette.
44
+ ```bash
45
+ datasette install datasette-tailscale
46
+ ```
47
+ ## Usage
48
+
49
+ Generate a [Tailscale auth key](https://login.tailscale.com/admin/settings/keys)
50
+ (an ephemeral, reusable key is a good choice) and serve a database:
51
+
52
+ ```bash
53
+ datasette tailscale mydata.db --ts-authkey tskey-auth-xxxx
54
+ ```
55
+
56
+ You can also supply the key via the `TS_AUTHKEY` environment variable:
57
+
58
+ ```bash
59
+ export TS_AUTHKEY=tskey-auth-xxxx
60
+ datasette tailscale mydata.db
61
+ ```
62
+
63
+ If you omit the auth key entirely, an interactive login URL is printed on first
64
+ run for you to click.
65
+
66
+ Once it connects you'll see:
67
+
68
+ ```
69
+ Connected. Tailnet IPv4: 100.x.y.z
70
+ Serving Datasette at http://datasette (reachable only on your tailnet)
71
+ ```
72
+
73
+ Any other device on your tailnet can now reach it at `http://datasette/` (via
74
+ MagicDNS) or by its tailnet IP.
75
+
76
+ ### Options
77
+
78
+ The command accepts **all** the options that `datasette serve` accepts —
79
+ `-m/--metadata`, `--setting`, `--root`, `--immutable`, `--cors`, etc. — because
80
+ they are inherited dynamically from `datasette serve` at runtime. (The
81
+ `--host`, `--port`, `--reload`, `--uds`, `--get`, `--open` and `--ssl-*`
82
+ options are suppressed, since they don't apply when serving over a tailnet.)
83
+
84
+ In addition it adds these tailscale-specific options:
85
+
86
+ - `--ts-hostname` — the hostname this node registers as on your tailnet
87
+ (default: `datasette`).
88
+ - `--ts-authkey` — your Tailscale auth key (or set `TS_AUTHKEY`). If omitted, an
89
+ interactive login URL is printed on first run.
90
+ - `--ts-state-dir` — directory for persisting the tailnet node identity across
91
+ restarts (default: `$XDG_STATE_HOME/datasette-tailscale`). A persistent state
92
+ directory gives the node a stable identity; an ephemeral auth key lets the
93
+ node disappear from your tailnet when the process exits.
94
+ - `--ts-port` — the port to listen on over the tailnet (default: `80`).
95
+
96
+ ### HTTPS and security notes
97
+
98
+ Traffic between tailnet devices is end-to-end encrypted by WireGuard, so this
99
+ plugin serves plain **HTTP** over the tailnet rather than terminating TLS. The
100
+ URL is `http://`, but the wire is still encrypted.
101
+
102
+ `tailscale-rs` is early-stage, experimental software with unvalidated
103
+ cryptography. The plugin sets the `TS_RS_EXPERIMENT=this_is_unstable_software`
104
+ acknowledgement on your behalf and prints a warning. Use it only on a tailnet
105
+ you trust.
106
+
107
+ ## Development
108
+
109
+ To set up this plugin locally, first checkout the code. You can confirm it is available like this:
110
+ ```bash
111
+ cd datasette-tailscale
112
+ # Confirm the plugin is visible
113
+ uv run datasette plugins
114
+ ```
115
+ To run the tests:
116
+ ```bash
117
+ uv run pytest
118
+ ```
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ datasette_tailscale/__init__.py
5
+ datasette_tailscale.egg-info/PKG-INFO
6
+ datasette_tailscale.egg-info/SOURCES.txt
7
+ datasette_tailscale.egg-info/dependency_links.txt
8
+ datasette_tailscale.egg-info/entry_points.txt
9
+ datasette_tailscale.egg-info/requires.txt
10
+ datasette_tailscale.egg-info/top_level.txt
11
+ tests/test_tailscale.py
@@ -0,0 +1,2 @@
1
+ [datasette]
2
+ tailscale = datasette_tailscale
@@ -0,0 +1,2 @@
1
+ datasette
2
+ tailscale-py
@@ -0,0 +1 @@
1
+ datasette_tailscale
@@ -0,0 +1,39 @@
1
+ [project]
2
+ name = "datasette-tailscale"
3
+ version = "0.1a0"
4
+ description = "Run a Datasette instance on a Tailscale network"
5
+ readme = "README.md"
6
+ authors = [{name = "Simon Willison"}]
7
+ license = "Apache-2.0"
8
+ classifiers=[
9
+ "Framework :: Datasette"
10
+ ]
11
+ requires-python = ">=3.12"
12
+ dependencies = [
13
+ "datasette",
14
+ "tailscale-py"
15
+ ]
16
+
17
+ [dependency-groups]
18
+ dev = [
19
+ "pytest",
20
+ "pytest-asyncio"
21
+ ]
22
+
23
+ [build-system]
24
+ requires = ["setuptools"]
25
+ build-backend = "setuptools.build_meta"
26
+
27
+
28
+ [project.urls]
29
+ Homepage = "https://github.com/datasette/datasette-tailscale"
30
+ Changelog = "https://github.com/datasette/datasette-tailscale/releases"
31
+ Issues = "https://github.com/datasette/datasette-tailscale/issues"
32
+ CI = "https://github.com/datasette/datasette-tailscale/actions"
33
+
34
+ [project.entry-points.datasette]
35
+ tailscale = "datasette_tailscale"
36
+
37
+ [tool.pytest.ini_options]
38
+ asyncio_mode = "strict"
39
+ asyncio_default_fixture_loop_scope = "function"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,133 @@
1
+ import asyncio
2
+
3
+ import pytest
4
+ from click.testing import CliRunner
5
+ from datasette.app import Datasette
6
+ from datasette.cli import cli, serve
7
+
8
+ from datasette_tailscale import (
9
+ OVERRIDDEN_SERVE_OPTIONS,
10
+ _proxy,
11
+ register_commands,
12
+ )
13
+
14
+
15
+ @pytest.mark.asyncio
16
+ async def test_plugin_is_installed():
17
+ datasette = Datasette(memory=True)
18
+ response = await datasette.client.get("/-/plugins.json")
19
+ assert response.status_code == 200
20
+ installed_plugins = {p["name"] for p in response.json()}
21
+ assert "datasette-tailscale" in installed_plugins
22
+
23
+
24
+ def _build_tailscale_command():
25
+ captured = {}
26
+
27
+ class FakeCli:
28
+ def add_command(self, cmd):
29
+ captured["cmd"] = cmd
30
+
31
+ register_commands(FakeCli())
32
+ return captured["cmd"]
33
+
34
+
35
+ def test_command_registered():
36
+ result = CliRunner().invoke(cli, ["tailscale", "--help"])
37
+ assert result.exit_code == 0
38
+ assert "Serve Datasette over your Tailscale tailnet" in result.output
39
+
40
+
41
+ def test_inherits_serve_options_minus_overrides():
42
+ cmd = _build_tailscale_command()
43
+ names = {p.name for p in cmd.params}
44
+
45
+ # Our own options are present
46
+ assert {"ts_hostname", "ts_authkey", "ts_state_dir", "ts_port"} <= names
47
+
48
+ # Overridden serve options are NOT exposed
49
+ assert not (names & OVERRIDDEN_SERVE_OPTIONS)
50
+
51
+ # Every other serve option IS inherited automatically
52
+ serve_names = {p.name for p in serve.params}
53
+ expected_inherited = serve_names - OVERRIDDEN_SERVE_OPTIONS
54
+ assert expected_inherited <= names
55
+
56
+
57
+ def test_no_host_or_port_options_exposed():
58
+ cmd = _build_tailscale_command()
59
+ all_opts = [opt for p in cmd.params for opt in getattr(p, "opts", [])]
60
+ assert "--host" not in all_opts
61
+ assert "--port" not in all_opts
62
+ assert "--reload" not in all_opts
63
+ assert "--ssl-keyfile" not in all_opts
64
+
65
+
66
+ def test_our_options_use_ts_prefix():
67
+ # Our options are namespaced under --ts-* so they can never clash with a
68
+ # future `datasette serve` option that we inherit dynamically.
69
+ cmd = _build_tailscale_command()
70
+ our_names = {"ts_hostname", "ts_authkey", "ts_state_dir", "ts_port"}
71
+ for param in cmd.params:
72
+ if param.name in our_names:
73
+ assert all(
74
+ opt.startswith("--ts-") for opt in param.opts
75
+ ), param.opts
76
+
77
+
78
+ class FakeTcpStream:
79
+ """Mimics tailscale.TcpStream backed by an in-memory queue.
80
+
81
+ recv() yields chunks the test pushes in; send() records outgoing bytes.
82
+ """
83
+
84
+ def __init__(self, incoming):
85
+ self._incoming = list(incoming)
86
+ self.sent = bytearray()
87
+
88
+ async def recv(self):
89
+ await asyncio.sleep(0)
90
+ if self._incoming:
91
+ return self._incoming.pop(0)
92
+ return b"" # EOF
93
+
94
+ async def send(self, data):
95
+ # Exercise the partial-write loop: only send half each call.
96
+ n = max(1, len(data) // 2)
97
+ self.sent.extend(data[:n])
98
+ await asyncio.sleep(0)
99
+ return n
100
+
101
+
102
+ @pytest.mark.asyncio
103
+ async def test_proxy_bridges_to_loopback():
104
+ # A tiny loopback TCP server that upper-cases whatever it receives,
105
+ # standing in for Datasette.
106
+ received = bytearray()
107
+
108
+ async def handle(reader, writer):
109
+ data = await reader.read(1024)
110
+ received.extend(data)
111
+ writer.write(data.upper())
112
+ await writer.drain()
113
+ writer.close()
114
+
115
+ server = await asyncio.start_server(handle, "127.0.0.1", 0)
116
+ port = server.sockets[0].getsockname()[1]
117
+
118
+ async with server:
119
+ ts_stream = FakeTcpStream([b"hello ", b"tailnet"])
120
+ await _proxy(ts_stream, port)
121
+
122
+ # The loopback backend saw the bytes the tailnet stream produced...
123
+ assert bytes(received) == b"hello tailnet"
124
+ # ...and the upper-cased response made it back out to the tailnet stream.
125
+ assert bytes(ts_stream.sent) == b"HELLO TAILNET"
126
+
127
+
128
+ @pytest.mark.asyncio
129
+ async def test_proxy_handles_unreachable_backend():
130
+ # Port 1 on loopback should refuse the connection; _proxy must not raise.
131
+ ts_stream = FakeTcpStream([b"data"])
132
+ await _proxy(ts_stream, 1)
133
+ assert bytes(ts_stream.sent) == b""