cf-share-screenshot 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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 gabrys
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.
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.4
2
+ Name: cf-share-screenshot
3
+ Version: 0.1.0
4
+ Summary: Share a GNOME/Wayland screenshot through a Cloudflare quick tunnel and copy its URL.
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/gabrys/cf-share-screenshot
7
+ Project-URL: Issues, https://github.com/gabrys/cf-share-screenshot/issues
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Environment :: Console
10
+ Classifier: Operating System :: POSIX :: Linux
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Topic :: Multimedia :: Graphics :: Capture :: Screen Capture
14
+ Classifier: Topic :: Utilities
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # cf-share-screenshot
21
+
22
+ Select an area of the screen, upload it to a temporary public URL through a
23
+ Cloudflare quick tunnel, and copy that URL to the clipboard. Useful for pasting
24
+ a screenshot link into a chat with an AI agent or a colleague.
25
+
26
+ The clipboard receives
27
+ `screenshot at https://….trycloudflare.com/image/<id>.png (try again in a few seconds if this URL doesn't work)`.
28
+
29
+ ## Requirements
30
+
31
+ Linux with GNOME on Wayland, Python 3.10 or newer (standard library only), and
32
+ these executables on your `PATH`:
33
+
34
+ - [`cloudflared`](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/)
35
+ - `gnome-screenshot`
36
+ - `wl-copy` (from `wl-clipboard`)
37
+ - `notify-send` (from `libnotify`) for desktop notifications
38
+
39
+ All four are checked at startup, before the area selection, and every missing
40
+ one is reported in a single error. Installing this package does not install
41
+ any of them. On Debian or Ubuntu:
42
+
43
+ ```sh
44
+ sudo apt install gnome-screenshot wl-clipboard libnotify-bin
45
+ ```
46
+
47
+ ## Installation
48
+
49
+ ```sh
50
+ uv tool install cf-share-screenshot
51
+ ```
52
+
53
+ Requires [uv](https://docs.astral.sh/uv/getting-started/installation/).
54
+ This puts `cf-share-screenshot` in `~/.local/bin`. A one-off run with
55
+ `uvx cf-share-screenshot` also works, but a persistent installation is
56
+ better for a keyboard shortcut.
57
+
58
+ You can also run the single file without installing anything:
59
+
60
+ ```sh
61
+ python3 cf_share_screenshot.py
62
+ ```
63
+
64
+ ## Usage
65
+
66
+ ```sh
67
+ cf-share-screenshot # select an area, upload it, copy the URL
68
+ ```
69
+
70
+ There are no subcommands; the background server starts automatically when needed.
71
+
72
+ Bind the command to a keyboard shortcut in GNOME Settings → Keyboard → Custom
73
+ Shortcuts, using the full path, for example
74
+ `/home/you/.local/bin/cf-share-screenshot`.
75
+
76
+ ## How it works
77
+
78
+ The first screenshot starts a background server on `127.0.0.1:18765` and a
79
+ `cloudflared` quick tunnel to it. Later screenshots reuse both, so the public
80
+ host name stays the same while the server runs.
81
+
82
+ - The screenshot is uploaded as soon as the local server answers. On the first
83
+ start the server holds the upload until `cloudflared` reports its URL (up to
84
+ 20 seconds) and returns it right away, without checking it. A brand-new
85
+ host name may need a few more seconds before it resolves.
86
+ - Each screenshot is kept in memory for 30 minutes under a random 64-bit ID.
87
+ - The server checks its public URL about every minute and restarts the tunnel
88
+ if it stops responding; the host name then changes.
89
+ - After 3 hours without uploads the server and the tunnel shut down.
90
+ - Cancelling the area selection does not start the server.
91
+ - The bound port is the server's lock: a second server exits silently.
92
+
93
+ The background server writes no log; it reports tunnel restarts, failures and
94
+ its shutdown through desktop notifications. The bearer token lives in
95
+ `$XDG_RUNTIME_DIR/cf-share-screenshot/` with mode `0700`.
96
+
97
+ ## Security
98
+
99
+ Anyone who knows an image URL can download that image until it expires. The IDs
100
+ are random and are not listed anywhere, but treat the URL as a secret and don't
101
+ share screenshots with sensitive content. Uploads and `/status` require a bearer
102
+ token that only the local user can read. The tunnel depends on Cloudflare's free quick tunnel service, which has
103
+ no uptime guarantee.
104
+
105
+ ## Development
106
+
107
+ ```sh
108
+ uv run python -m unittest discover -s tests -v
109
+ uvx --from build pyproject-build
110
+ uvx twine check --strict dist/*
111
+ ```
112
+
113
+ ## Publishing
114
+
115
+ The version lives in `__version__` in `cf_share_screenshot.py` (currently
116
+ `0.1.0`). Build from a clean checkout using the commands above, ensuring `dist/`
117
+ contains only the current release. Upload to TestPyPI:
118
+
119
+ ```sh
120
+ uvx twine upload --repository testpypi dist/*
121
+ ```
122
+
123
+ Verify the TestPyPI release in an isolated environment:
124
+
125
+ ```sh
126
+ uvx --isolated --index https://test.pypi.org/simple/ --default-index https://pypi.org/simple/ cf-share-screenshot@0.1.0 --help
127
+ ```
128
+
129
+ Then upload the same artifacts to PyPI:
130
+
131
+ ```sh
132
+ uvx twine upload dist/*
133
+ ```
134
+
135
+ Use an API token when Twine prompts for credentials. Never commit credentials.
136
+ For subsequent releases, bump `__version__` and build fresh artifacts; PyPI does
137
+ not allow replacing an existing release file. GitHub Actions runs tests and
138
+ validates distributions; publishing is manual.
139
+
140
+ ## License
141
+
142
+ MIT; see [LICENSE](LICENSE).
@@ -0,0 +1,123 @@
1
+ # cf-share-screenshot
2
+
3
+ Select an area of the screen, upload it to a temporary public URL through a
4
+ Cloudflare quick tunnel, and copy that URL to the clipboard. Useful for pasting
5
+ a screenshot link into a chat with an AI agent or a colleague.
6
+
7
+ The clipboard receives
8
+ `screenshot at https://….trycloudflare.com/image/<id>.png (try again in a few seconds if this URL doesn't work)`.
9
+
10
+ ## Requirements
11
+
12
+ Linux with GNOME on Wayland, Python 3.10 or newer (standard library only), and
13
+ these executables on your `PATH`:
14
+
15
+ - [`cloudflared`](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/)
16
+ - `gnome-screenshot`
17
+ - `wl-copy` (from `wl-clipboard`)
18
+ - `notify-send` (from `libnotify`) for desktop notifications
19
+
20
+ All four are checked at startup, before the area selection, and every missing
21
+ one is reported in a single error. Installing this package does not install
22
+ any of them. On Debian or Ubuntu:
23
+
24
+ ```sh
25
+ sudo apt install gnome-screenshot wl-clipboard libnotify-bin
26
+ ```
27
+
28
+ ## Installation
29
+
30
+ ```sh
31
+ uv tool install cf-share-screenshot
32
+ ```
33
+
34
+ Requires [uv](https://docs.astral.sh/uv/getting-started/installation/).
35
+ This puts `cf-share-screenshot` in `~/.local/bin`. A one-off run with
36
+ `uvx cf-share-screenshot` also works, but a persistent installation is
37
+ better for a keyboard shortcut.
38
+
39
+ You can also run the single file without installing anything:
40
+
41
+ ```sh
42
+ python3 cf_share_screenshot.py
43
+ ```
44
+
45
+ ## Usage
46
+
47
+ ```sh
48
+ cf-share-screenshot # select an area, upload it, copy the URL
49
+ ```
50
+
51
+ There are no subcommands; the background server starts automatically when needed.
52
+
53
+ Bind the command to a keyboard shortcut in GNOME Settings → Keyboard → Custom
54
+ Shortcuts, using the full path, for example
55
+ `/home/you/.local/bin/cf-share-screenshot`.
56
+
57
+ ## How it works
58
+
59
+ The first screenshot starts a background server on `127.0.0.1:18765` and a
60
+ `cloudflared` quick tunnel to it. Later screenshots reuse both, so the public
61
+ host name stays the same while the server runs.
62
+
63
+ - The screenshot is uploaded as soon as the local server answers. On the first
64
+ start the server holds the upload until `cloudflared` reports its URL (up to
65
+ 20 seconds) and returns it right away, without checking it. A brand-new
66
+ host name may need a few more seconds before it resolves.
67
+ - Each screenshot is kept in memory for 30 minutes under a random 64-bit ID.
68
+ - The server checks its public URL about every minute and restarts the tunnel
69
+ if it stops responding; the host name then changes.
70
+ - After 3 hours without uploads the server and the tunnel shut down.
71
+ - Cancelling the area selection does not start the server.
72
+ - The bound port is the server's lock: a second server exits silently.
73
+
74
+ The background server writes no log; it reports tunnel restarts, failures and
75
+ its shutdown through desktop notifications. The bearer token lives in
76
+ `$XDG_RUNTIME_DIR/cf-share-screenshot/` with mode `0700`.
77
+
78
+ ## Security
79
+
80
+ Anyone who knows an image URL can download that image until it expires. The IDs
81
+ are random and are not listed anywhere, but treat the URL as a secret and don't
82
+ share screenshots with sensitive content. Uploads and `/status` require a bearer
83
+ token that only the local user can read. The tunnel depends on Cloudflare's free quick tunnel service, which has
84
+ no uptime guarantee.
85
+
86
+ ## Development
87
+
88
+ ```sh
89
+ uv run python -m unittest discover -s tests -v
90
+ uvx --from build pyproject-build
91
+ uvx twine check --strict dist/*
92
+ ```
93
+
94
+ ## Publishing
95
+
96
+ The version lives in `__version__` in `cf_share_screenshot.py` (currently
97
+ `0.1.0`). Build from a clean checkout using the commands above, ensuring `dist/`
98
+ contains only the current release. Upload to TestPyPI:
99
+
100
+ ```sh
101
+ uvx twine upload --repository testpypi dist/*
102
+ ```
103
+
104
+ Verify the TestPyPI release in an isolated environment:
105
+
106
+ ```sh
107
+ uvx --isolated --index https://test.pypi.org/simple/ --default-index https://pypi.org/simple/ cf-share-screenshot@0.1.0 --help
108
+ ```
109
+
110
+ Then upload the same artifacts to PyPI:
111
+
112
+ ```sh
113
+ uvx twine upload dist/*
114
+ ```
115
+
116
+ Use an API token when Twine prompts for credentials. Never commit credentials.
117
+ For subsequent releases, bump `__version__` and build fresh artifacts; PyPI does
118
+ not allow replacing an existing release file. GitHub Actions runs tests and
119
+ validates distributions; publishing is manual.
120
+
121
+ ## License
122
+
123
+ MIT; see [LICENSE](LICENSE).
@@ -0,0 +1,142 @@
1
+ Metadata-Version: 2.4
2
+ Name: cf-share-screenshot
3
+ Version: 0.1.0
4
+ Summary: Share a GNOME/Wayland screenshot through a Cloudflare quick tunnel and copy its URL.
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/gabrys/cf-share-screenshot
7
+ Project-URL: Issues, https://github.com/gabrys/cf-share-screenshot/issues
8
+ Classifier: Development Status :: 3 - Alpha
9
+ Classifier: Environment :: Console
10
+ Classifier: Operating System :: POSIX :: Linux
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Programming Language :: Python :: 3 :: Only
13
+ Classifier: Topic :: Multimedia :: Graphics :: Capture :: Screen Capture
14
+ Classifier: Topic :: Utilities
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # cf-share-screenshot
21
+
22
+ Select an area of the screen, upload it to a temporary public URL through a
23
+ Cloudflare quick tunnel, and copy that URL to the clipboard. Useful for pasting
24
+ a screenshot link into a chat with an AI agent or a colleague.
25
+
26
+ The clipboard receives
27
+ `screenshot at https://….trycloudflare.com/image/<id>.png (try again in a few seconds if this URL doesn't work)`.
28
+
29
+ ## Requirements
30
+
31
+ Linux with GNOME on Wayland, Python 3.10 or newer (standard library only), and
32
+ these executables on your `PATH`:
33
+
34
+ - [`cloudflared`](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/)
35
+ - `gnome-screenshot`
36
+ - `wl-copy` (from `wl-clipboard`)
37
+ - `notify-send` (from `libnotify`) for desktop notifications
38
+
39
+ All four are checked at startup, before the area selection, and every missing
40
+ one is reported in a single error. Installing this package does not install
41
+ any of them. On Debian or Ubuntu:
42
+
43
+ ```sh
44
+ sudo apt install gnome-screenshot wl-clipboard libnotify-bin
45
+ ```
46
+
47
+ ## Installation
48
+
49
+ ```sh
50
+ uv tool install cf-share-screenshot
51
+ ```
52
+
53
+ Requires [uv](https://docs.astral.sh/uv/getting-started/installation/).
54
+ This puts `cf-share-screenshot` in `~/.local/bin`. A one-off run with
55
+ `uvx cf-share-screenshot` also works, but a persistent installation is
56
+ better for a keyboard shortcut.
57
+
58
+ You can also run the single file without installing anything:
59
+
60
+ ```sh
61
+ python3 cf_share_screenshot.py
62
+ ```
63
+
64
+ ## Usage
65
+
66
+ ```sh
67
+ cf-share-screenshot # select an area, upload it, copy the URL
68
+ ```
69
+
70
+ There are no subcommands; the background server starts automatically when needed.
71
+
72
+ Bind the command to a keyboard shortcut in GNOME Settings → Keyboard → Custom
73
+ Shortcuts, using the full path, for example
74
+ `/home/you/.local/bin/cf-share-screenshot`.
75
+
76
+ ## How it works
77
+
78
+ The first screenshot starts a background server on `127.0.0.1:18765` and a
79
+ `cloudflared` quick tunnel to it. Later screenshots reuse both, so the public
80
+ host name stays the same while the server runs.
81
+
82
+ - The screenshot is uploaded as soon as the local server answers. On the first
83
+ start the server holds the upload until `cloudflared` reports its URL (up to
84
+ 20 seconds) and returns it right away, without checking it. A brand-new
85
+ host name may need a few more seconds before it resolves.
86
+ - Each screenshot is kept in memory for 30 minutes under a random 64-bit ID.
87
+ - The server checks its public URL about every minute and restarts the tunnel
88
+ if it stops responding; the host name then changes.
89
+ - After 3 hours without uploads the server and the tunnel shut down.
90
+ - Cancelling the area selection does not start the server.
91
+ - The bound port is the server's lock: a second server exits silently.
92
+
93
+ The background server writes no log; it reports tunnel restarts, failures and
94
+ its shutdown through desktop notifications. The bearer token lives in
95
+ `$XDG_RUNTIME_DIR/cf-share-screenshot/` with mode `0700`.
96
+
97
+ ## Security
98
+
99
+ Anyone who knows an image URL can download that image until it expires. The IDs
100
+ are random and are not listed anywhere, but treat the URL as a secret and don't
101
+ share screenshots with sensitive content. Uploads and `/status` require a bearer
102
+ token that only the local user can read. The tunnel depends on Cloudflare's free quick tunnel service, which has
103
+ no uptime guarantee.
104
+
105
+ ## Development
106
+
107
+ ```sh
108
+ uv run python -m unittest discover -s tests -v
109
+ uvx --from build pyproject-build
110
+ uvx twine check --strict dist/*
111
+ ```
112
+
113
+ ## Publishing
114
+
115
+ The version lives in `__version__` in `cf_share_screenshot.py` (currently
116
+ `0.1.0`). Build from a clean checkout using the commands above, ensuring `dist/`
117
+ contains only the current release. Upload to TestPyPI:
118
+
119
+ ```sh
120
+ uvx twine upload --repository testpypi dist/*
121
+ ```
122
+
123
+ Verify the TestPyPI release in an isolated environment:
124
+
125
+ ```sh
126
+ uvx --isolated --index https://test.pypi.org/simple/ --default-index https://pypi.org/simple/ cf-share-screenshot@0.1.0 --help
127
+ ```
128
+
129
+ Then upload the same artifacts to PyPI:
130
+
131
+ ```sh
132
+ uvx twine upload dist/*
133
+ ```
134
+
135
+ Use an API token when Twine prompts for credentials. Never commit credentials.
136
+ For subsequent releases, bump `__version__` and build fresh artifacts; PyPI does
137
+ not allow replacing an existing release file. GitHub Actions runs tests and
138
+ validates distributions; publishing is manual.
139
+
140
+ ## License
141
+
142
+ MIT; see [LICENSE](LICENSE).
@@ -0,0 +1,13 @@
1
+ LICENSE
2
+ README.md
3
+ cf_share_screenshot.py
4
+ pyproject.toml
5
+ cf_share_screenshot.egg-info/PKG-INFO
6
+ cf_share_screenshot.egg-info/SOURCES.txt
7
+ cf_share_screenshot.egg-info/dependency_links.txt
8
+ cf_share_screenshot.egg-info/entry_points.txt
9
+ cf_share_screenshot.egg-info/top_level.txt
10
+ tests/test_cli.py
11
+ tests/test_say.py
12
+ tests/test_server.py
13
+ tests/test_token.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ cf-share-screenshot = cf_share_screenshot:main
@@ -0,0 +1 @@
1
+ cf_share_screenshot
@@ -0,0 +1,434 @@
1
+ #!/usr/bin/env python3
2
+ """cf-share-screenshot: GNOME/Wayland screenshot -> temporary Cloudflare Quick Tunnel URL.
3
+
4
+ Python standard library only. External executables: cloudflared, gnome-screenshot,
5
+ wl-copy, notify-send. Linux/POSIX only.
6
+ """
7
+ import argparse
8
+ import errno
9
+ import hmac
10
+ import http.client
11
+ import http.server
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+ import re
16
+ import secrets
17
+ import shutil
18
+ import signal
19
+ import socket
20
+ import ssl
21
+ import subprocess
22
+ import sys
23
+ import tempfile
24
+ import threading
25
+ import time
26
+ from urllib.parse import urlsplit
27
+ import urllib.error
28
+ import urllib.request
29
+
30
+ __version__ = '0.1.0'
31
+
32
+ PORT = 18765
33
+ HOST = '127.0.0.1'
34
+ TTL = 30 * 60
35
+ IDLE = 3 * 60 * 60
36
+ CHECK_EVERY = 60
37
+ MAX_IMAGE = 20 * 1024 * 1024
38
+ SERVER_START_TIMEOUT = 5 # local HTTP server only; the tunnel may still be starting
39
+ TUNNEL_TIMEOUT = 20 # how long an upload waits for cloudflared to report its URL
40
+ APP_DIR = Path(os.environ.get('XDG_RUNTIME_DIR') or f'/tmp/cf-share-screenshot-{os.getuid()}') / 'cf-share-screenshot'
41
+ TOKEN_FILE = APP_DIR / 'bearer.token'
42
+ # Skip api.trycloudflare.com, which cloudflared mentions in its error messages.
43
+ URL_RE = re.compile(r'https://(?!api\.)[a-z0-9-]+\.trycloudflare\.com', re.I)
44
+ EDGE_HOST = 'api.trycloudflare.com' # any stable host on Cloudflare's edge
45
+ ID_BYTES = 8 # 64-bit random image IDs
46
+ IMAGE_PATH_RE = re.compile(rf'/image/[a-f0-9]{{{ID_BYTES * 2}}}\.png')
47
+ PNG_MAGIC = b'\x89PNG\r\n\x1a\n'
48
+ REQUIRED_COMMANDS = ('cloudflared', 'gnome-screenshot', 'wl-copy', 'notify-send')
49
+
50
+
51
+ def say(message, file=None, notify=False, clipboard=False):
52
+ """The single way to tell the user something.
53
+
54
+ Writes MESSAGE to FILE (default stdout). With clipboard=True also copies it
55
+ with wl-copy, and with notify=True shows it with notify-send. Each of those
56
+ is silently skipped when its tool is missing or fails.
57
+ """
58
+ if clipboard and shutil.which('wl-copy'):
59
+ try:
60
+ subprocess.run(['wl-copy', '--type', 'text/plain;charset=utf-8'],
61
+ input=message.encode('utf-8'), check=True, timeout=10,
62
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
63
+ except (OSError, subprocess.SubprocessError):
64
+ pass
65
+ print(message, file=file or sys.stdout, flush=True)
66
+ if notify and shutil.which('notify-send'):
67
+ try:
68
+ subprocess.run(['notify-send', '-a', 'cf-share-screenshot', 'cf-share-screenshot', message],
69
+ timeout=10, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
70
+ except (OSError, subprocess.SubprocessError):
71
+ pass
72
+
73
+
74
+ def check_commands():
75
+ """Fail before doing anything if any required executable is missing."""
76
+ missing = [cmd for cmd in REQUIRED_COMMANDS if not shutil.which(cmd)]
77
+ if missing:
78
+ raise RuntimeError(
79
+ f"Missing commands: {', '.join(missing)}. Install them and try again.")
80
+
81
+
82
+ def read_token():
83
+ try:
84
+ token = TOKEN_FILE.read_text(encoding='ascii').strip()
85
+ except FileNotFoundError:
86
+ raise RuntimeError('cf-share-screenshot token not found')
87
+ if not token: # an empty token would let anyone in with "Bearer "
88
+ raise RuntimeError(f'The token file {TOKEN_FILE} is empty; delete it and try again.')
89
+ return token
90
+
91
+
92
+ def ensure_token():
93
+ """Return the saved token, creating it once if it does not exist yet.
94
+
95
+ The token is reused across server restarts. It is written to a temporary
96
+ file and hard-linked into place, so concurrent callers never see a partial
97
+ file and never replace a token that another process already created.
98
+ """
99
+ TOKEN_FILE.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
100
+ os.chmod(TOKEN_FILE.parent, 0o700)
101
+ if not TOKEN_FILE.exists():
102
+ fd, tmp = tempfile.mkstemp(dir=TOKEN_FILE.parent, prefix='.token-') # mode 0600
103
+ try:
104
+ with os.fdopen(fd, 'w', encoding='ascii') as f:
105
+ f.write(secrets.token_urlsafe(32))
106
+ try:
107
+ os.link(tmp, TOKEN_FILE)
108
+ except FileExistsError:
109
+ pass # another process created it first; use theirs
110
+ finally:
111
+ os.unlink(tmp)
112
+ return read_token()
113
+
114
+
115
+ def control(method, path, payload=None, timeout=3):
116
+ token = read_token()
117
+ headers = {'Authorization': 'Bearer ' + token}
118
+ if payload is not None:
119
+ headers['Content-Type'] = 'image/png'
120
+ request = urllib.request.Request(
121
+ f'http://{HOST}:{PORT}{path}', data=payload, headers=headers, method=method)
122
+ try:
123
+ with urllib.request.urlopen(request, timeout=timeout) as response:
124
+ return json.loads(response.read())
125
+ except urllib.error.HTTPError as exc:
126
+ try:
127
+ message = json.loads(exc.read()).get('error', str(exc))
128
+ except (ValueError, OSError):
129
+ message = str(exc)
130
+ raise RuntimeError(message) from exc
131
+
132
+
133
+ def alive():
134
+ try:
135
+ return control('GET', '/status', timeout=0.7).get('ok') is True
136
+ except (OSError, ValueError, RuntimeError, urllib.error.URLError):
137
+ return False
138
+
139
+
140
+ def ensure_server():
141
+ if alive():
142
+ return False
143
+ ensure_token()
144
+ say('Starting the server and the Cloudflare tunnel…', file=sys.stderr, notify=True)
145
+ # The server reports problems through notifications, not a log file.
146
+ subprocess.Popen([sys.executable, str(Path(__file__).resolve()),
147
+ '--internal-cmd', 'serve'],
148
+ stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
149
+ stderr=subprocess.DEVNULL, start_new_session=True, close_fds=True)
150
+ # Wait only for the local HTTP server; the upload itself waits for the tunnel.
151
+ deadline = time.monotonic() + SERVER_START_TIMEOUT
152
+ while time.monotonic() < deadline:
153
+ if alive():
154
+ return True
155
+ time.sleep(0.1)
156
+ raise RuntimeError(f'The server did not start within {SERVER_START_TIMEOUT}s '
157
+ f'(is port {PORT} used by another program?).')
158
+
159
+
160
+ def screenshot():
161
+ fd, path = tempfile.mkstemp(prefix='cf-share-screenshot-', suffix='.png')
162
+ os.close(fd)
163
+ try:
164
+ result = subprocess.run(['gnome-screenshot', '-a', '-f', path], check=False)
165
+ if result.returncode != 0:
166
+ raise RuntimeError('Screenshot cancelled or gnome-screenshot failed.')
167
+ data = Path(path).read_bytes()
168
+ if not data.startswith(PNG_MAGIC):
169
+ raise RuntimeError('gnome-screenshot did not produce a valid PNG image.')
170
+ if len(data) > MAX_IMAGE:
171
+ raise RuntimeError('The screenshot exceeds the 20 MiB limit.')
172
+ return data
173
+ finally:
174
+ Path(path).unlink(missing_ok=True)
175
+
176
+
177
+ def share_screenshot():
178
+ check_commands()
179
+ # Take the screenshot before starting the tunnel, so cancelling does not launch a server.
180
+ data = screenshot()
181
+ ensure_server()
182
+ # The server holds this request until cloudflared reports its URL (up to TUNNEL_TIMEOUT).
183
+ result = control('POST', '/image', data, timeout=TUNNEL_TIMEOUT + 5)
184
+ say(f"screenshot at {result['url']} (try again in a few seconds if this URL doesn't work)",
185
+ notify=True, clipboard=True)
186
+
187
+
188
+ class State:
189
+ def __init__(self):
190
+ self.token = read_token()
191
+ self.lock = threading.RLock()
192
+ self.images = {} # id -> (png bytes, expiration)
193
+ self.last_upload = time.monotonic()
194
+ self.public_url = None
195
+ self.process = None
196
+ self.stop = threading.Event()
197
+ self.ready = threading.Event()
198
+
199
+ def cleanup(self):
200
+ now = time.monotonic()
201
+ with self.lock:
202
+ for key, (_, expiration) in list(self.images.items()):
203
+ if expiration <= now:
204
+ del self.images[key]
205
+
206
+ def terminate_tunnel(self):
207
+ with self.lock:
208
+ proc = self.process
209
+ self.process = None
210
+ self.public_url = None
211
+ self.ready.clear()
212
+ if proc is not None and proc.poll() is None:
213
+ proc.terminate()
214
+ try:
215
+ proc.wait(timeout=5)
216
+ except subprocess.TimeoutExpired:
217
+ proc.kill()
218
+ proc.wait(timeout=5)
219
+
220
+ def start_tunnel(self):
221
+ self.terminate_tunnel()
222
+ proc = subprocess.Popen(
223
+ ['cloudflared', 'tunnel', '--no-autoupdate', '--url', f'http://{HOST}:{PORT}'],
224
+ stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
225
+ text=True, errors='replace', bufsize=1, start_new_session=True)
226
+ with self.lock:
227
+ self.process = proc
228
+ threading.Thread(target=self.read_tunnel_log, args=(proc,), daemon=True).start()
229
+
230
+ def read_tunnel_log(self, proc):
231
+ # Keep draining stderr so cloudflared never blocks on a full pipe.
232
+ try:
233
+ for line in proc.stderr:
234
+ match = URL_RE.search(line)
235
+ if match:
236
+ with self.lock:
237
+ if self.process is proc: # ignore a replaced cloudflared
238
+ self.public_url = match.group(0).rstrip('/')
239
+ self.ready.set()
240
+ except (OSError, ValueError):
241
+ pass
242
+
243
+ def public_healthy(self):
244
+ with self.lock:
245
+ url = self.public_url
246
+ proc = self.process
247
+ if not url or proc is None or proc.poll() is not None:
248
+ return False
249
+ # Never look up the new host name locally: trycloudflare.com has a 60 s
250
+ # negative TTL, so a lookup made before the record exists makes the local
251
+ # resolver answer "no such host" for a minute. Instead connect to a
252
+ # Cloudflare edge address (api.trycloudflare.com always exists) and pass
253
+ # the new host name as SNI and Host.
254
+ host = urlsplit(url).hostname
255
+ conn = None
256
+ try:
257
+ edge_ip = socket.gethostbyname(EDGE_HOST)
258
+ context = ssl.create_default_context()
259
+ conn = http.client.HTTPSConnection(host, 443, timeout=12, context=context)
260
+ conn.sock = context.wrap_socket(
261
+ socket.create_connection((edge_ip, 443), timeout=12), server_hostname=host)
262
+ conn.request('GET', '/status', headers={
263
+ 'Cache-Control': 'no-cache', 'Authorization': 'Bearer ' + self.token})
264
+ response = conn.getresponse()
265
+ return response.status == 200 and json.loads(response.read(1024)).get('ok') is True
266
+ except (OSError, ValueError, http.client.HTTPException):
267
+ return False
268
+ finally:
269
+ if conn is not None:
270
+ conn.close()
271
+
272
+ def monitor(self):
273
+ failures = 0
274
+ next_check = time.monotonic() + CHECK_EVERY # serve() already started the tunnel
275
+ while not self.stop.is_set():
276
+ self.cleanup()
277
+ if time.monotonic() - self.last_upload >= IDLE:
278
+ say('No uploads for 3 hours; shutting down.', file=sys.stderr, notify=True)
279
+ self.stop.set()
280
+ break
281
+ if time.monotonic() >= next_check:
282
+ next_check = time.monotonic() + CHECK_EVERY
283
+ if self.public_healthy():
284
+ failures = 0
285
+ else:
286
+ failures += 1
287
+ # If there is no URL or the process died, restart immediately.
288
+ # Otherwise tolerate 2 transient failures before replacing the URL.
289
+ with self.lock:
290
+ missing = (not self.public_url or self.process is None
291
+ or self.process.poll() is not None)
292
+ if missing or failures >= 3:
293
+ say('Restarting the Cloudflare tunnel...', file=sys.stderr, notify=True)
294
+ try:
295
+ self.start_tunnel()
296
+ except OSError as exc:
297
+ say(f'Failed to start cloudflared: {exc}', file=sys.stderr,
298
+ notify=True, clipboard=True)
299
+ failures = 0
300
+ self.stop.wait(1)
301
+
302
+
303
+ def make_handler(state):
304
+ class Handler(http.server.BaseHTTPRequestHandler):
305
+ server_version = 'cf-share-screenshot/' + __version__
306
+
307
+ def respond(self, status, data, mime='application/json'):
308
+ self.send_response(status)
309
+ self.send_header('Content-Type', mime)
310
+ self.send_header('Cache-Control', 'no-store')
311
+ self.send_header('X-Content-Type-Options', 'nosniff')
312
+ self.send_header('Content-Length', str(len(data)))
313
+ self.end_headers()
314
+ try:
315
+ self.wfile.write(data)
316
+ except (BrokenPipeError, ConnectionResetError):
317
+ pass
318
+
319
+ def obj(self, status, value):
320
+ self.respond(status, json.dumps(value).encode('utf-8'))
321
+
322
+ def authorized(self):
323
+ # Compare bytes: compare_digest on str raises TypeError for non-ASCII headers.
324
+ return hmac.compare_digest(
325
+ self.headers.get('Authorization', '').encode('utf-8', 'surrogateescape'),
326
+ ('Bearer ' + state.token).encode('ascii'))
327
+
328
+ def do_GET(self):
329
+ path = urlsplit(self.path).path
330
+ if IMAGE_PATH_RE.fullmatch(path):
331
+ ident = path[len('/image/'):]
332
+ with state.lock:
333
+ item = state.images.get(ident)
334
+ if item and item[1] > time.monotonic():
335
+ self.respond(200, item[0], 'image/png')
336
+ return
337
+ self.obj(404, {'error': 'Not found'})
338
+ return
339
+ if path == '/status':
340
+ if not self.authorized():
341
+ self.obj(401, {'error': 'Unauthorized'})
342
+ return
343
+ self.obj(200, {'ok': True, 'version': __version__})
344
+ return
345
+ self.obj(404, {'error': 'Not found'})
346
+
347
+ def do_POST(self):
348
+ if urlsplit(self.path).path != '/image':
349
+ self.obj(404, {'error': 'Not found'})
350
+ return
351
+ if not self.authorized():
352
+ self.obj(401, {'error': 'Unauthorized'})
353
+ return
354
+ try:
355
+ size = int(self.headers.get('Content-Length', ''))
356
+ except ValueError:
357
+ size = -1
358
+ data = self.rfile.read(size) if len(PNG_MAGIC) <= size <= MAX_IMAGE else b''
359
+ if len(data) != size or not data.startswith(PNG_MAGIC):
360
+ self.obj(400, {'error': 'Invalid image'})
361
+ return
362
+ # Wait only until cloudflared reports its URL, then answer at once
363
+ # without checking it; the periodic monitor checks the public URL.
364
+ state.ready.wait(timeout=TUNNEL_TIMEOUT)
365
+ with state.lock:
366
+ if not state.public_url:
367
+ self.obj(503, {'error': 'The tunnel is not up yet. Try again.'})
368
+ return
369
+ ident = secrets.token_hex(ID_BYTES) + '.png'
370
+ state.images[ident] = (data, time.monotonic() + TTL)
371
+ state.last_upload = time.monotonic()
372
+ url = f'{state.public_url}/image/{ident}'
373
+ self.obj(201, {'url': url})
374
+
375
+ def log_message(self, fmt, *args):
376
+ # Never log screenshot IDs or bearer tokens.
377
+ pass
378
+
379
+ return Handler
380
+
381
+
382
+ def serve():
383
+ """Run the local server and the tunnel; started in the background by share_screenshot."""
384
+ # The bound port is the lock: if another server holds it, exit silently.
385
+ # Bind before touching the token so a second server never overwrites it.
386
+ # Requests wait in the listen backlog until the real handler is set below.
387
+ try:
388
+ public = http.server.ThreadingHTTPServer((HOST, PORT), http.server.BaseHTTPRequestHandler)
389
+ except OSError as exc:
390
+ if exc.errno == errno.EADDRINUSE:
391
+ return
392
+ raise
393
+ ensure_token()
394
+ state = State()
395
+ public.RequestHandlerClass = make_handler(state)
396
+ state.start_tunnel()
397
+ threads = [threading.Thread(target=public.serve_forever, daemon=True),
398
+ threading.Thread(target=state.monitor, daemon=True)]
399
+ for t in threads:
400
+ t.start()
401
+
402
+ def shutdown(signum, frame):
403
+ state.stop.set()
404
+ signal.signal(signal.SIGTERM, shutdown)
405
+ signal.signal(signal.SIGINT, shutdown)
406
+ try:
407
+ state.stop.wait()
408
+ finally:
409
+ state.terminate_tunnel()
410
+ public.shutdown()
411
+ public.server_close()
412
+
413
+
414
+ def main():
415
+ parser = argparse.ArgumentParser(
416
+ prog='cf-share-screenshot',
417
+ description='Take a screenshot, share it through a Cloudflare quick tunnel '
418
+ 'and copy the URL to the clipboard.')
419
+ parser.add_argument('--version', action='version', version='%(prog)s ' + __version__)
420
+ # Internal: the background server is started with --internal-cmd serve.
421
+ parser.add_argument('--internal-cmd', choices=['serve'], help=argparse.SUPPRESS)
422
+ args = parser.parse_args()
423
+ try:
424
+ if args.internal_cmd == 'serve':
425
+ serve()
426
+ else:
427
+ share_screenshot()
428
+ except (RuntimeError, OSError, subprocess.SubprocessError) as exc:
429
+ say(f'Error: {exc}', file=sys.stderr, notify=True)
430
+ sys.exit(1)
431
+
432
+
433
+ if __name__ == '__main__':
434
+ main()
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "cf-share-screenshot"
7
+ dynamic = ["version"]
8
+ description = "Share a GNOME/Wayland screenshot through a Cloudflare quick tunnel and copy its URL."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ dependencies = []
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Environment :: Console",
17
+ "Operating System :: POSIX :: Linux",
18
+ "Programming Language :: Python :: 3",
19
+ "Programming Language :: Python :: 3 :: Only",
20
+ "Topic :: Multimedia :: Graphics :: Capture :: Screen Capture",
21
+ "Topic :: Utilities",
22
+ ]
23
+
24
+ [project.urls]
25
+ Repository = "https://github.com/gabrys/cf-share-screenshot"
26
+ Issues = "https://github.com/gabrys/cf-share-screenshot/issues"
27
+
28
+ [project.scripts]
29
+ cf-share-screenshot = "cf_share_screenshot:main"
30
+
31
+ [tool.setuptools]
32
+ py-modules = ["cf_share_screenshot"]
33
+
34
+ [tool.setuptools.dynamic]
35
+ version = { attr = "cf_share_screenshot.__version__" }
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,72 @@
1
+ import os
2
+ import subprocess
3
+ import sys
4
+ import tempfile
5
+ import unittest
6
+
7
+ import cf_share_screenshot
8
+
9
+
10
+ def run_cli(*args, env=None):
11
+ return subprocess.run(
12
+ [sys.executable, '-m', 'cf_share_screenshot', *args],
13
+ capture_output=True, text=True, check=False, env=env, timeout=30,
14
+ )
15
+
16
+
17
+ class CommandTests(unittest.TestCase):
18
+ def test_help(self):
19
+ result = run_cli('--help')
20
+ self.assertEqual(result.returncode, 0)
21
+ self.assertIn('usage: cf-share-screenshot [-h] [--version]\n', result.stdout)
22
+ for hidden in ('snap', 'status', '--internal-cmd'):
23
+ self.assertNotIn(hidden, result.stdout)
24
+
25
+ def test_positional_arguments_are_rejected(self):
26
+ for command in ('snap', 'serve', 'status'):
27
+ result = run_cli(command)
28
+ self.assertEqual(result.returncode, 2, command)
29
+ self.assertIn('unrecognized arguments', result.stderr)
30
+
31
+ def test_internal_cmd_only_accepts_serve(self):
32
+ result = run_cli('--internal-cmd', 'status')
33
+ self.assertEqual(result.returncode, 2)
34
+ self.assertIn('invalid choice', result.stderr)
35
+
36
+ def test_version(self):
37
+ result = run_cli('--version')
38
+ self.assertEqual(result.returncode, 0)
39
+ self.assertIn(cf_share_screenshot.__version__, result.stdout)
40
+
41
+ def test_reports_missing_tool(self):
42
+ with tempfile.TemporaryDirectory() as empty:
43
+ env = dict(os.environ, PATH=empty)
44
+ result = run_cli(env=env)
45
+ self.assertEqual(result.returncode, 1)
46
+ self.assertIn('Missing commands: cloudflared, gnome-screenshot, wl-copy, notify-send.',
47
+ result.stderr)
48
+
49
+ def test_reports_only_missing_tools(self):
50
+ with tempfile.TemporaryDirectory() as bin_dir:
51
+ for name in ('cloudflared', 'notify-send'):
52
+ tool = os.path.join(bin_dir, name)
53
+ with open(tool, 'w') as f:
54
+ f.write('#!/bin/sh\nexit 0\n')
55
+ os.chmod(tool, 0o755)
56
+ env = dict(os.environ, PATH=bin_dir)
57
+ result = run_cli(env=env)
58
+ self.assertEqual(result.returncode, 1)
59
+ self.assertIn('Missing commands: gnome-screenshot, wl-copy.', result.stderr)
60
+
61
+
62
+ class TunnelUrlTests(unittest.TestCase):
63
+ def test_finds_quick_tunnel_url(self):
64
+ line = '2026-11-23T12:00:00Z INF | https://some-random-words.trycloudflare.com |'
65
+ match = cf_share_screenshot.URL_RE.search(line)
66
+ self.assertEqual(match.group(0), 'https://some-random-words.trycloudflare.com')
67
+
68
+ def test_ignores_api_url_in_errors(self):
69
+ line = ('2026-11-23T12:00:00Z ERR Error unmarshaling QuickTunnel response '
70
+ 'error="failed to request quick Tunnel: Post '
71
+ '\\"https://api.trycloudflare.com/tunnel\\""')
72
+ self.assertIsNone(cf_share_screenshot.URL_RE.search(line))
@@ -0,0 +1,69 @@
1
+ import contextlib
2
+ import io
3
+ import os
4
+ import tempfile
5
+ import unittest
6
+ from pathlib import Path
7
+ from unittest.mock import patch
8
+
9
+ import cf_share_screenshot as app
10
+
11
+ FAKE_TOOLS = {
12
+ 'wl-copy': '#!/bin/sh\n/bin/cat > "$SAY_OUT/clipboard"\n',
13
+ 'notify-send': '#!/bin/sh\nprintf "%s\\n" "$@" > "$SAY_OUT/notification"\n',
14
+ 'failing-wl-copy': '#!/bin/sh\nexit 1\n',
15
+ }
16
+
17
+
18
+ class SayTests(unittest.TestCase):
19
+ def setUp(self):
20
+ tmp = tempfile.TemporaryDirectory()
21
+ self.addCleanup(tmp.cleanup)
22
+ self.out = Path(tmp.name) / 'out'
23
+ self.bin = Path(tmp.name) / 'bin'
24
+ self.out.mkdir()
25
+ self.bin.mkdir()
26
+ patcher = patch.dict(os.environ, {'PATH': str(self.bin), 'SAY_OUT': str(self.out)})
27
+ patcher.start()
28
+ self.addCleanup(patcher.stop)
29
+
30
+ def install(self, name, source=None):
31
+ tool = self.bin / name
32
+ tool.write_text(FAKE_TOOLS[source or name])
33
+ tool.chmod(0o755)
34
+
35
+ def call(self, message, to_stderr=False, **kwargs):
36
+ stdout, stderr = io.StringIO(), io.StringIO()
37
+ with contextlib.redirect_stdout(stdout), contextlib.redirect_stderr(stderr):
38
+ if to_stderr:
39
+ kwargs['file'] = app.sys.stderr
40
+ app.say(message, **kwargs)
41
+ return stdout.getvalue(), stderr.getvalue()
42
+
43
+ def test_default_is_stdout_only(self):
44
+ self.install('wl-copy')
45
+ self.install('notify-send')
46
+ stdout, stderr = self.call('hello')
47
+ self.assertEqual((stdout, stderr), ('hello\n', ''))
48
+ self.assertEqual(list(self.out.iterdir()), [])
49
+
50
+ def test_stderr(self):
51
+ stdout, stderr = self.call('oops', to_stderr=True)
52
+ self.assertEqual((stdout, stderr), ('', 'oops\n'))
53
+
54
+ def test_clipboard_and_notification(self):
55
+ self.install('wl-copy')
56
+ self.install('notify-send')
57
+ stdout, stderr = self.call('screenshot at https://x', notify=True, clipboard=True)
58
+ self.assertEqual((stdout, stderr), ('screenshot at https://x\n', ''))
59
+ self.assertEqual((self.out / 'clipboard').read_text(), 'screenshot at https://x')
60
+ self.assertIn('screenshot at https://x', (self.out / 'notification').read_text())
61
+
62
+ def test_missing_tools_are_skipped(self):
63
+ stdout, stderr = self.call('hello', notify=True, clipboard=True)
64
+ self.assertEqual((stdout, stderr), ('hello\n', ''))
65
+
66
+ def test_failing_clipboard_is_ignored(self):
67
+ self.install('wl-copy', 'failing-wl-copy')
68
+ stdout, stderr = self.call('hello', clipboard=True)
69
+ self.assertEqual((stdout, stderr), ('hello\n', ''))
@@ -0,0 +1,161 @@
1
+ import http.client
2
+ import json
3
+ import secrets
4
+ import tempfile
5
+ import socket
6
+ import threading
7
+ import time
8
+ import unittest
9
+ from pathlib import Path
10
+ from unittest.mock import patch
11
+
12
+ import cf_share_screenshot as app
13
+
14
+ PNG = b'\x89PNG\r\n\x1a\n' + b'\0' * 32
15
+ PUBLIC_URL = 'https://example.trycloudflare.com'
16
+
17
+
18
+ class ServerTests(unittest.TestCase):
19
+ def setUp(self):
20
+ tmp = tempfile.TemporaryDirectory()
21
+ self.addCleanup(tmp.cleanup)
22
+ token_file = Path(tmp.name) / 'bearer.token'
23
+ patcher = patch.object(app, 'TOKEN_FILE', token_file)
24
+ patcher.start()
25
+ self.addCleanup(patcher.stop)
26
+ self.token = app.ensure_token()
27
+ self.state = app.State()
28
+ self.server = app.http.server.ThreadingHTTPServer(
29
+ ('127.0.0.1', 0), app.make_handler(self.state))
30
+ threading.Thread(target=self.server.serve_forever, daemon=True).start()
31
+ self.addCleanup(self.server.server_close)
32
+ self.addCleanup(self.server.shutdown)
33
+
34
+ def request(self, method, path, body=None, auth=True, headers=None):
35
+ conn = http.client.HTTPConnection('127.0.0.1', self.server.server_address[1], timeout=10)
36
+ self.addCleanup(conn.close)
37
+ all_headers = dict(headers or {})
38
+ if auth:
39
+ all_headers['Authorization'] = 'Bearer ' + self.token
40
+ conn.request(method, path, body=body, headers=all_headers)
41
+ response = conn.getresponse()
42
+ return response.status, response.read()
43
+
44
+ def make_tunnel_ready(self):
45
+ self.state.public_url = PUBLIC_URL
46
+ self.state.ready.set()
47
+
48
+ def forbid_http_check(self):
49
+ """Uploads must trust cloudflared's URL without checking it over HTTP."""
50
+ patcher = patch.object(app.State, 'public_healthy')
51
+ check = patcher.start()
52
+ self.addCleanup(patcher.stop)
53
+ self.addCleanup(lambda: check.assert_not_called())
54
+
55
+ def test_status_requires_token(self):
56
+ status, _ = self.request('GET', '/status', auth=False)
57
+ self.assertEqual(status, 401)
58
+ status, body = self.request('GET', '/status')
59
+ self.assertEqual(status, 200)
60
+ self.assertEqual(json.loads(body), {'ok': True, 'version': app.__version__})
61
+
62
+ def test_wrong_and_non_ascii_tokens_are_rejected(self):
63
+ for value in ('Bearer wrong', 'Bearer ąż'):
64
+ conn = http.client.HTTPConnection('127.0.0.1', self.server.server_address[1], timeout=10)
65
+ self.addCleanup(conn.close)
66
+ conn.putrequest('GET', '/status')
67
+ conn.putheader('Authorization', value.encode('utf-8'))
68
+ conn.endheaders()
69
+ self.assertEqual(conn.getresponse().status, 401, value)
70
+
71
+ def test_unknown_paths_and_images_are_404(self):
72
+ self.assertEqual(self.request('GET', '/')[0], 404)
73
+ self.assertEqual(self.request('GET', f'/image/{secrets.token_hex(8)}.png')[0], 404)
74
+ self.assertEqual(self.request('POST', '/upload', PNG)[0], 404)
75
+ # The client no longer chooses the image ID.
76
+ self.assertEqual(self.request('POST', f'/image/{secrets.token_hex(8)}.png', PNG)[0], 404)
77
+
78
+ def test_upload_requires_token_and_png(self):
79
+ self.make_tunnel_ready()
80
+ self.assertEqual(self.request('POST', '/image', PNG, auth=False)[0], 401)
81
+ for body in (b'', b'GIF89a' + b'\0' * 32, PNG[:5]):
82
+ self.assertEqual(self.request('POST', '/image', body)[0], 400, body)
83
+ self.assertEqual(self.state.images, {})
84
+
85
+ def test_upload_and_download(self):
86
+ self.forbid_http_check()
87
+ self.make_tunnel_ready()
88
+ status, body = self.request('POST', '/image', PNG, headers={'Content-Type': 'image/png'})
89
+ self.assertEqual(status, 201)
90
+ url = json.loads(body)['url']
91
+ self.assertRegex(url, r'^https://example\.trycloudflare\.com/image/[0-9a-f]{16}\.png$')
92
+ status, body = self.request('GET', url[len(PUBLIC_URL):], auth=False)
93
+ self.assertEqual(status, 200)
94
+ self.assertEqual(body, PNG)
95
+
96
+ def test_each_upload_gets_a_new_id(self):
97
+ self.make_tunnel_ready()
98
+ urls = {json.loads(self.request('POST', '/image', PNG)[1])['url'] for _ in range(3)}
99
+ self.assertEqual(len(urls), 3)
100
+
101
+ def test_upload_sent_before_tunnel_is_ready_waits_for_it(self):
102
+ self.forbid_http_check()
103
+ result = {}
104
+
105
+ def upload():
106
+ result['response'] = self.request('POST', '/image', PNG)
107
+
108
+ uploader = threading.Thread(target=upload)
109
+ uploader.start()
110
+ time.sleep(0.5)
111
+ self.assertTrue(uploader.is_alive(), 'upload must wait for the tunnel')
112
+ self.assertEqual(self.state.images, {})
113
+ self.make_tunnel_ready() # cloudflared reported its URL
114
+ uploader.join(timeout=10)
115
+ status, body = result['response']
116
+ self.assertEqual(status, 201)
117
+ self.assertTrue(json.loads(body)['url'].startswith(PUBLIC_URL + '/image/'))
118
+
119
+ def test_upload_fails_when_tunnel_never_comes_up(self):
120
+ with patch.object(app, 'TUNNEL_TIMEOUT', 0.5):
121
+ status, body = self.request('POST', '/image', PNG)
122
+ self.assertEqual(status, 503)
123
+ self.assertEqual(self.state.images, {})
124
+
125
+ def test_expired_images_are_removed(self):
126
+ ident = secrets.token_hex(8) + '.png'
127
+ self.state.images[ident] = (PNG, 0)
128
+ self.assertEqual(self.request('GET', '/image/' + ident, auth=False)[0], 404)
129
+ self.state.cleanup()
130
+ self.assertNotIn(ident, self.state.images)
131
+
132
+
133
+ class MonitorTests(unittest.TestCase):
134
+ def test_no_restart_right_after_start(self):
135
+ with tempfile.TemporaryDirectory() as tmp, \
136
+ patch.object(app, 'TOKEN_FILE', Path(tmp) / 'bearer.token'):
137
+ app.ensure_token()
138
+ state = app.State()
139
+ with patch.object(app, 'say') as say, \
140
+ patch.object(app.State, 'start_tunnel') as start, \
141
+ patch.object(app.State, 'public_healthy') as check:
142
+ monitor = threading.Thread(target=state.monitor)
143
+ monitor.start()
144
+ time.sleep(1.5)
145
+ state.stop.set()
146
+ monitor.join(timeout=5)
147
+ say.assert_not_called()
148
+ start.assert_not_called()
149
+ check.assert_not_called()
150
+
151
+
152
+ class PortLockTests(unittest.TestCase):
153
+ def test_serve_exits_silently_when_port_is_taken(self):
154
+ with tempfile.TemporaryDirectory() as tmp, socket.socket() as busy:
155
+ busy.bind(('127.0.0.1', 0))
156
+ busy.listen()
157
+ app_dir = Path(tmp) / 'app'
158
+ with patch.object(app, 'PORT', busy.getsockname()[1]), \
159
+ patch.object(app, 'TOKEN_FILE', app_dir / 'bearer.token'):
160
+ self.assertIsNone(app.serve())
161
+ self.assertFalse(app_dir.exists(), 'a second server must not touch the token')
@@ -0,0 +1,36 @@
1
+ import stat
2
+ import tempfile
3
+ import unittest
4
+ from pathlib import Path
5
+ from unittest.mock import patch
6
+
7
+ import cf_share_screenshot as app
8
+
9
+
10
+ class TokenTests(unittest.TestCase):
11
+ def setUp(self):
12
+ tmp = tempfile.TemporaryDirectory()
13
+ self.addCleanup(tmp.cleanup)
14
+ self.dir = Path(tmp.name) / 'app'
15
+ self.file = self.dir / 'bearer.token'
16
+ patcher = patch.object(app, 'TOKEN_FILE', self.file)
17
+ patcher.start()
18
+ self.addCleanup(patcher.stop)
19
+
20
+ def test_created_once_with_private_permissions(self):
21
+ token = app.ensure_token()
22
+ self.assertGreaterEqual(len(token), 40)
23
+ self.assertEqual(stat.S_IMODE(self.file.stat().st_mode), 0o600)
24
+ self.assertEqual(stat.S_IMODE(self.dir.stat().st_mode), 0o700)
25
+ self.assertEqual([p.name for p in self.dir.iterdir()], ['bearer.token'])
26
+
27
+ def test_existing_token_is_reused(self):
28
+ first = app.ensure_token()
29
+ self.assertEqual(app.ensure_token(), first)
30
+ self.assertEqual(app.read_token(), first)
31
+
32
+ def test_empty_token_file_is_rejected(self):
33
+ self.dir.mkdir()
34
+ self.file.write_text('\n')
35
+ with self.assertRaises(RuntimeError):
36
+ app.ensure_token()