bunko 0.3.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.
Files changed (63) hide show
  1. bunko-0.3.0/LICENSE +21 -0
  2. bunko-0.3.0/PKG-INFO +169 -0
  3. bunko-0.3.0/README.md +139 -0
  4. bunko-0.3.0/THIRD_PARTY_NOTICES.md +17 -0
  5. bunko-0.3.0/bunko/__init__.py +1 -0
  6. bunko-0.3.0/bunko/__main__.py +3 -0
  7. bunko-0.3.0/bunko/access.py +225 -0
  8. bunko-0.3.0/bunko/cli.py +231 -0
  9. bunko-0.3.0/bunko/contents.py +207 -0
  10. bunko-0.3.0/bunko/index.py +110 -0
  11. bunko-0.3.0/bunko/media.py +178 -0
  12. bunko-0.3.0/bunko/office/__init__.py +87 -0
  13. bunko-0.3.0/bunko/office/common.py +136 -0
  14. bunko-0.3.0/bunko/office/excel.py +322 -0
  15. bunko-0.3.0/bunko/office/word.py +615 -0
  16. bunko-0.3.0/bunko/paths.py +75 -0
  17. bunko-0.3.0/bunko/places.py +262 -0
  18. bunko-0.3.0/bunko/server.py +558 -0
  19. bunko-0.3.0/bunko/service.py +195 -0
  20. bunko-0.3.0/bunko/static/index.html +53 -0
  21. bunko-0.3.0/bunko/static/js/api.js +27 -0
  22. bunko-0.3.0/bunko/static/js/app.js +299 -0
  23. bunko-0.3.0/bunko/static/js/chrome.js +110 -0
  24. bunko-0.3.0/bunko/static/js/dom.js +66 -0
  25. bunko-0.3.0/bunko/static/js/format.js +44 -0
  26. bunko-0.3.0/bunko/static/js/icons.js +45 -0
  27. bunko-0.3.0/bunko/static/js/kinds.js +65 -0
  28. bunko-0.3.0/bunko/static/js/limits.js +11 -0
  29. bunko-0.3.0/bunko/static/js/paths.js +17 -0
  30. bunko-0.3.0/bunko/static/js/places.js +435 -0
  31. bunko-0.3.0/bunko/static/js/search.js +207 -0
  32. bunko-0.3.0/bunko/static/js/settings-panel.js +116 -0
  33. bunko-0.3.0/bunko/static/js/sidebar.js +39 -0
  34. bunko-0.3.0/bunko/static/js/state.js +16 -0
  35. bunko-0.3.0/bunko/static/js/store.js +29 -0
  36. bunko-0.3.0/bunko/static/js/tree.js +145 -0
  37. bunko-0.3.0/bunko/static/js/viewers/document.js +246 -0
  38. bunko-0.3.0/bunko/static/js/viewers/folder.js +185 -0
  39. bunko-0.3.0/bunko/static/js/viewers/media.js +228 -0
  40. bunko-0.3.0/bunko/static/js/viewers/page.js +64 -0
  41. bunko-0.3.0/bunko/static/js/viewers/table.js +415 -0
  42. bunko-0.3.0/bunko/static/js/viewers/text.js +117 -0
  43. bunko-0.3.0/bunko/static/style.css +1783 -0
  44. bunko-0.3.0/bunko/static/theme.js +7 -0
  45. bunko-0.3.0/bunko/static/vendor/LICENSES/dompurify-apache-2.0.txt +202 -0
  46. bunko-0.3.0/bunko/static/vendor/LICENSES/dompurify-mpl-2.0.txt +373 -0
  47. bunko-0.3.0/bunko/static/vendor/LICENSES/highlight.js.txt +29 -0
  48. bunko-0.3.0/bunko/static/vendor/LICENSES/marked.txt +44 -0
  49. bunko-0.3.0/bunko/static/vendor/VERSIONS.txt +3 -0
  50. bunko-0.3.0/bunko/static/vendor/highlight.js +1257 -0
  51. bunko-0.3.0/bunko/static/vendor/marked.js +85 -0
  52. bunko-0.3.0/bunko/static/vendor/purify.js +6 -0
  53. bunko-0.3.0/bunko/storage.py +31 -0
  54. bunko-0.3.0/bunko.egg-info/PKG-INFO +169 -0
  55. bunko-0.3.0/bunko.egg-info/SOURCES.txt +61 -0
  56. bunko-0.3.0/bunko.egg-info/dependency_links.txt +1 -0
  57. bunko-0.3.0/bunko.egg-info/entry_points.txt +2 -0
  58. bunko-0.3.0/bunko.egg-info/top_level.txt +1 -0
  59. bunko-0.3.0/pyproject.toml +78 -0
  60. bunko-0.3.0/setup.cfg +4 -0
  61. bunko-0.3.0/tests/test_features.py +731 -0
  62. bunko-0.3.0/tests/test_office.py +582 -0
  63. bunko-0.3.0/tests/test_server.py +389 -0
bunko-0.3.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ivan Arevalo
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.
bunko-0.3.0/PKG-INFO ADDED
@@ -0,0 +1,169 @@
1
+ Metadata-Version: 2.4
2
+ Name: bunko
3
+ Version: 0.3.0
4
+ Summary: A read-only file server that renders Markdown, HTML, tables, Office files, images, and video in the browser
5
+ Author: Ivan Arevalo
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/ivanfarevalo/bunko
8
+ Project-URL: Documentation, https://github.com/ivanfarevalo/bunko/tree/main/docs
9
+ Project-URL: Issues, https://github.com/ivanfarevalo/bunko/issues
10
+ Project-URL: Changelog, https://github.com/ivanfarevalo/bunko/blob/main/CHANGELOG.md
11
+ Keywords: http.server,file server,file browser,markdown,viewer,tailscale
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Web Environment
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Operating System :: POSIX
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3 :: Only
19
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
20
+ Classifier: Topic :: System :: Filesystems
21
+ Requires-Python: >=3.8
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ License-File: THIRD_PARTY_NOTICES.md
25
+ License-File: bunko/static/vendor/LICENSES/dompurify-apache-2.0.txt
26
+ License-File: bunko/static/vendor/LICENSES/dompurify-mpl-2.0.txt
27
+ License-File: bunko/static/vendor/LICENSES/highlight.js.txt
28
+ License-File: bunko/static/vendor/LICENSES/marked.txt
29
+ Dynamic: license-file
30
+
31
+ # Bunko
32
+
33
+ **A read-only file server that renders what it serves.** Point it at a folder
34
+ and open it in a browser: Markdown, HTML reports, Word documents, Excel
35
+ workbooks, CSV and JSONL tables, images, video, PDFs, code, and logs all open
36
+ in place, with the folder tree and search in a sidebar. It's a drop-in
37
+ replacement for `python -m http.server`, with no dependencies beyond Python.
38
+
39
+ *Bunko* (文庫) is Japanese for a small library, or a collection of books.
40
+
41
+ ![A folder in Bunko](https://raw.githubusercontent.com/ivanfarevalo/bunko/main/docs/img/folder.png)
42
+
43
+ It's built for reading files where they live, usually on a remote machine:
44
+
45
+ - **Results and reports** from experiments, training runs, and pipelines:
46
+ plots, tables, logs, videos, and HTML reports, without copying anything back.
47
+ - **Plans, notes, and reports written by AI coding agents** such as Claude Code.
48
+ They render as they're written, and stay on your own machine.
49
+ - **A shared, read-only document folder** for a small team, with search and
50
+ personal favorites and tags.
51
+
52
+ ## Launch it
53
+
54
+ ### 1. Install
55
+
56
+ Bunko needs Python 3.8 or later, and nothing else. Pick whichever fits:
57
+
58
+ ```bash
59
+ uvx bunko # try it without installing anything (needs uv)
60
+ uv tool install bunko # install the bunko command (or: pipx install bunko)
61
+ ```
62
+
63
+ On a server without uv or pipx, this puts a single-file `bunko` in
64
+ `~/.local/bin`, using only Python and curl:
65
+
66
+ ```bash
67
+ curl -fsSL https://github.com/ivanfarevalo/bunko/releases/latest/download/install.sh | sh
68
+ ```
69
+
70
+ Or copy `bunko.pyz` from the [latest release](https://github.com/ivanfarevalo/bunko/releases/latest)
71
+ anywhere, and run it with `python3 bunko.pyz`.
72
+
73
+ ### 2. Start it
74
+
75
+ ```bash
76
+ bunko # serve the current folder on port 8000, or the next free one
77
+ bunko 8099 ~/reports # choose the port and the folder
78
+ ```
79
+
80
+ Bunko prints the address to open, then serves until you press `Ctrl+C`.
81
+
82
+ ### 3. Open it
83
+
84
+ | Where Bunko runs | How to open it |
85
+ |---|---|
86
+ | Your own machine | Open the printed `http://localhost:8000/` |
87
+ | A remote machine, just for you | `bunko 8099 ~/reports` there, then `ssh -L 8099:localhost:8099 server` here, and open `http://localhost:8099/` |
88
+ | A remote machine, for named people on your tailnet (recommended) | See [Security](#security) below |
89
+ | A remote machine, behind a password-like token | `bunko 8099 ~/reports -b 0.0.0.0 --token`, then open the link it prints |
90
+
91
+ ### 4. Keep it running (optional)
92
+
93
+ ```bash
94
+ tmux new-session -d -s bunko 'bunko 8099 ~/reports' # in tmux
95
+ bunko service install --name reports -- 8099 ~/reports # as a systemd user service
96
+ ```
97
+
98
+ [docs/deployment.md](https://github.com/ivanfarevalo/bunko/blob/main/docs/deployment.md) covers both, plus the optional tools
99
+ that add thumbnails (ffmpeg) and fast content search (ripgrep).
100
+
101
+ ## Features
102
+
103
+ - **Recent files, favorites, and tags** pinned at the top of the sidebar, each
104
+ tag with its own section. They're kept on the server, so they follow you
105
+ between devices.
106
+ - **Folder tree and search.** Find files by name (`Ctrl+K`) or search inside
107
+ them (`Ctrl+Shift+F`, with [ripgrep](https://github.com/BurntSushi/ripgrep)
108
+ when installed). Content results open the file at the matching line.
109
+ - **Markdown.** GitHub-flavored, with highlighted code, working relative links
110
+ and images, and an optional outline beside the page.
111
+ - **HTML pages** render with their own CSS, scripts, and relative assets, as
112
+ under `http.server`.
113
+ - **Images and galleries,** with thumbnails generated by ffmpeg and cached.
114
+ - **Video with review tools:** frame stepping, exact frame numbers from
115
+ ffprobe, speed control, and links to an exact moment (`?t=12.345`).
116
+ - **CSV, TSV, and JSONL tables.** Virtualized, sortable, filterable, and
117
+ loaded in pieces, so large files open instantly.
118
+ - **Word and Excel.** `.docx` files open as pages, with headings, lists,
119
+ tables, images, and footnotes. `.xlsx` sheets open as tables with Excel's
120
+ row numbers and a tab per sheet. No Office or extra packages needed.
121
+ - **Code and logs** with highlighting and line numbers. Large files load in steps.
122
+ - **Live reload.** The open file refreshes when it changes on disk.
123
+ - **Access control.** Tailscale identity (recommended) or an access token.
124
+ - **Runs anywhere:** foreground, tmux, or a systemd user service.
125
+
126
+ | | |
127
+ |---|---|
128
+ | ![Markdown with outline](https://raw.githubusercontent.com/ivanfarevalo/bunko/main/docs/img/outline.png) | ![A large CSV](https://raw.githubusercontent.com/ivanfarevalo/bunko/main/docs/img/table.png) |
129
+ | ![Video review tools](https://raw.githubusercontent.com/ivanfarevalo/bunko/main/docs/img/video.png) | ![Search inside files](https://raw.githubusercontent.com/ivanfarevalo/bunko/main/docs/img/content-search.png) |
130
+
131
+ ## Security
132
+
133
+ Bunko never changes the folder it serves, hides dotfiles (including through
134
+ symlinks), and refuses path tricks. **By default it listens only on this
135
+ machine** (`127.0.0.1`). Reaching it from elsewhere is a choice you make:
136
+
137
+ | Setup | Who gets in | Transport |
138
+ |---|---|---|
139
+ | **Tailscale Serve + `--allow-user` (recommended)** | Named people, by Tailscale identity | HTTPS |
140
+ | The default + an SSH port forward | Whoever can SSH in | SSH |
141
+ | `-b <your Tailscale IP>` | Everyone on your tailnet | WireGuard |
142
+ | `-b 0.0.0.0 --token` | Anyone holding the token | Plain HTTP unless something adds HTTPS |
143
+ | `-b 0.0.0.0` | Anyone who can reach the port, as with `http.server` | Plain HTTP |
144
+
145
+ The recommended setup takes two commands:
146
+
147
+ ```bash
148
+ bunko 8100 ~/reports --allow-user you@example.com
149
+ sudo tailscale serve --bg --https=8100 http://127.0.0.1:8100
150
+ # open https://<machine>.<tailnet>.ts.net:8100/
151
+ ```
152
+
153
+ [docs/security.md](https://github.com/ivanfarevalo/bunko/blob/main/docs/security.md) explains each mode and its limits.
154
+
155
+ ## Documentation
156
+
157
+ - [Features and shortcuts](https://github.com/ivanfarevalo/bunko/blob/main/docs/features.md)
158
+ - [Security and access control](https://github.com/ivanfarevalo/bunko/blob/main/docs/security.md)
159
+ - [Deployment: tmux, systemd, remote machines](https://github.com/ivanfarevalo/bunko/blob/main/docs/deployment.md)
160
+ - [Command-line reference](https://github.com/ivanfarevalo/bunko/blob/main/docs/cli.md)
161
+ - [Development: environment, linters, tests, practices](https://github.com/ivanfarevalo/bunko/blob/main/docs/development.md)
162
+
163
+ The [project wiki](https://github.com/ivanfarevalo/bunko/blob/main/wiki/Home.md) tracks what Bunko is, where it's going, how
164
+ it's built, and what has been done so far, phase by phase.
165
+
166
+ ## License
167
+
168
+ MIT. See [LICENSE](https://github.com/ivanfarevalo/bunko/blob/main/LICENSE). Bundled front-end libraries keep their own
169
+ licenses: [THIRD_PARTY_NOTICES.md](https://github.com/ivanfarevalo/bunko/blob/main/THIRD_PARTY_NOTICES.md).
bunko-0.3.0/README.md ADDED
@@ -0,0 +1,139 @@
1
+ # Bunko
2
+
3
+ **A read-only file server that renders what it serves.** Point it at a folder
4
+ and open it in a browser: Markdown, HTML reports, Word documents, Excel
5
+ workbooks, CSV and JSONL tables, images, video, PDFs, code, and logs all open
6
+ in place, with the folder tree and search in a sidebar. It's a drop-in
7
+ replacement for `python -m http.server`, with no dependencies beyond Python.
8
+
9
+ *Bunko* (文庫) is Japanese for a small library, or a collection of books.
10
+
11
+ ![A folder in Bunko](https://raw.githubusercontent.com/ivanfarevalo/bunko/main/docs/img/folder.png)
12
+
13
+ It's built for reading files where they live, usually on a remote machine:
14
+
15
+ - **Results and reports** from experiments, training runs, and pipelines:
16
+ plots, tables, logs, videos, and HTML reports, without copying anything back.
17
+ - **Plans, notes, and reports written by AI coding agents** such as Claude Code.
18
+ They render as they're written, and stay on your own machine.
19
+ - **A shared, read-only document folder** for a small team, with search and
20
+ personal favorites and tags.
21
+
22
+ ## Launch it
23
+
24
+ ### 1. Install
25
+
26
+ Bunko needs Python 3.8 or later, and nothing else. Pick whichever fits:
27
+
28
+ ```bash
29
+ uvx bunko # try it without installing anything (needs uv)
30
+ uv tool install bunko # install the bunko command (or: pipx install bunko)
31
+ ```
32
+
33
+ On a server without uv or pipx, this puts a single-file `bunko` in
34
+ `~/.local/bin`, using only Python and curl:
35
+
36
+ ```bash
37
+ curl -fsSL https://github.com/ivanfarevalo/bunko/releases/latest/download/install.sh | sh
38
+ ```
39
+
40
+ Or copy `bunko.pyz` from the [latest release](https://github.com/ivanfarevalo/bunko/releases/latest)
41
+ anywhere, and run it with `python3 bunko.pyz`.
42
+
43
+ ### 2. Start it
44
+
45
+ ```bash
46
+ bunko # serve the current folder on port 8000, or the next free one
47
+ bunko 8099 ~/reports # choose the port and the folder
48
+ ```
49
+
50
+ Bunko prints the address to open, then serves until you press `Ctrl+C`.
51
+
52
+ ### 3. Open it
53
+
54
+ | Where Bunko runs | How to open it |
55
+ |---|---|
56
+ | Your own machine | Open the printed `http://localhost:8000/` |
57
+ | A remote machine, just for you | `bunko 8099 ~/reports` there, then `ssh -L 8099:localhost:8099 server` here, and open `http://localhost:8099/` |
58
+ | A remote machine, for named people on your tailnet (recommended) | See [Security](#security) below |
59
+ | A remote machine, behind a password-like token | `bunko 8099 ~/reports -b 0.0.0.0 --token`, then open the link it prints |
60
+
61
+ ### 4. Keep it running (optional)
62
+
63
+ ```bash
64
+ tmux new-session -d -s bunko 'bunko 8099 ~/reports' # in tmux
65
+ bunko service install --name reports -- 8099 ~/reports # as a systemd user service
66
+ ```
67
+
68
+ [docs/deployment.md](https://github.com/ivanfarevalo/bunko/blob/main/docs/deployment.md) covers both, plus the optional tools
69
+ that add thumbnails (ffmpeg) and fast content search (ripgrep).
70
+
71
+ ## Features
72
+
73
+ - **Recent files, favorites, and tags** pinned at the top of the sidebar, each
74
+ tag with its own section. They're kept on the server, so they follow you
75
+ between devices.
76
+ - **Folder tree and search.** Find files by name (`Ctrl+K`) or search inside
77
+ them (`Ctrl+Shift+F`, with [ripgrep](https://github.com/BurntSushi/ripgrep)
78
+ when installed). Content results open the file at the matching line.
79
+ - **Markdown.** GitHub-flavored, with highlighted code, working relative links
80
+ and images, and an optional outline beside the page.
81
+ - **HTML pages** render with their own CSS, scripts, and relative assets, as
82
+ under `http.server`.
83
+ - **Images and galleries,** with thumbnails generated by ffmpeg and cached.
84
+ - **Video with review tools:** frame stepping, exact frame numbers from
85
+ ffprobe, speed control, and links to an exact moment (`?t=12.345`).
86
+ - **CSV, TSV, and JSONL tables.** Virtualized, sortable, filterable, and
87
+ loaded in pieces, so large files open instantly.
88
+ - **Word and Excel.** `.docx` files open as pages, with headings, lists,
89
+ tables, images, and footnotes. `.xlsx` sheets open as tables with Excel's
90
+ row numbers and a tab per sheet. No Office or extra packages needed.
91
+ - **Code and logs** with highlighting and line numbers. Large files load in steps.
92
+ - **Live reload.** The open file refreshes when it changes on disk.
93
+ - **Access control.** Tailscale identity (recommended) or an access token.
94
+ - **Runs anywhere:** foreground, tmux, or a systemd user service.
95
+
96
+ | | |
97
+ |---|---|
98
+ | ![Markdown with outline](https://raw.githubusercontent.com/ivanfarevalo/bunko/main/docs/img/outline.png) | ![A large CSV](https://raw.githubusercontent.com/ivanfarevalo/bunko/main/docs/img/table.png) |
99
+ | ![Video review tools](https://raw.githubusercontent.com/ivanfarevalo/bunko/main/docs/img/video.png) | ![Search inside files](https://raw.githubusercontent.com/ivanfarevalo/bunko/main/docs/img/content-search.png) |
100
+
101
+ ## Security
102
+
103
+ Bunko never changes the folder it serves, hides dotfiles (including through
104
+ symlinks), and refuses path tricks. **By default it listens only on this
105
+ machine** (`127.0.0.1`). Reaching it from elsewhere is a choice you make:
106
+
107
+ | Setup | Who gets in | Transport |
108
+ |---|---|---|
109
+ | **Tailscale Serve + `--allow-user` (recommended)** | Named people, by Tailscale identity | HTTPS |
110
+ | The default + an SSH port forward | Whoever can SSH in | SSH |
111
+ | `-b <your Tailscale IP>` | Everyone on your tailnet | WireGuard |
112
+ | `-b 0.0.0.0 --token` | Anyone holding the token | Plain HTTP unless something adds HTTPS |
113
+ | `-b 0.0.0.0` | Anyone who can reach the port, as with `http.server` | Plain HTTP |
114
+
115
+ The recommended setup takes two commands:
116
+
117
+ ```bash
118
+ bunko 8100 ~/reports --allow-user you@example.com
119
+ sudo tailscale serve --bg --https=8100 http://127.0.0.1:8100
120
+ # open https://<machine>.<tailnet>.ts.net:8100/
121
+ ```
122
+
123
+ [docs/security.md](https://github.com/ivanfarevalo/bunko/blob/main/docs/security.md) explains each mode and its limits.
124
+
125
+ ## Documentation
126
+
127
+ - [Features and shortcuts](https://github.com/ivanfarevalo/bunko/blob/main/docs/features.md)
128
+ - [Security and access control](https://github.com/ivanfarevalo/bunko/blob/main/docs/security.md)
129
+ - [Deployment: tmux, systemd, remote machines](https://github.com/ivanfarevalo/bunko/blob/main/docs/deployment.md)
130
+ - [Command-line reference](https://github.com/ivanfarevalo/bunko/blob/main/docs/cli.md)
131
+ - [Development: environment, linters, tests, practices](https://github.com/ivanfarevalo/bunko/blob/main/docs/development.md)
132
+
133
+ The [project wiki](https://github.com/ivanfarevalo/bunko/blob/main/wiki/Home.md) tracks what Bunko is, where it's going, how
134
+ it's built, and what has been done so far, phase by phase.
135
+
136
+ ## License
137
+
138
+ MIT. See [LICENSE](https://github.com/ivanfarevalo/bunko/blob/main/LICENSE). Bundled front-end libraries keep their own
139
+ licenses: [THIRD_PARTY_NOTICES.md](https://github.com/ivanfarevalo/bunko/blob/main/THIRD_PARTY_NOTICES.md).
@@ -0,0 +1,17 @@
1
+ # Third-party notices
2
+
3
+ Bunko bundles these front-end libraries in `bunko/static/vendor/`, so it works
4
+ without internet access. Each keeps its own license; full texts are in
5
+ `bunko/static/vendor/LICENSES/`.
6
+
7
+ | Library | Version | License | File |
8
+ |---|---|---|---|
9
+ | [marked](https://github.com/markedjs/marked) | 18.1.3 | MIT | `LICENSES/marked.txt` |
10
+ | [DOMPurify](https://github.com/cure53/DOMPurify) | 3.5.0 | Apache-2.0 or MPL-2.0, at your option | `LICENSES/dompurify-apache-2.0.txt`, `LICENSES/dompurify-mpl-2.0.txt` |
11
+ | [highlight.js](https://github.com/highlightjs/highlight.js) | 11.11.1 | BSD-3-Clause | `LICENSES/highlight.js.txt` |
12
+
13
+ Bunko can also call these programs when they're installed. They aren't bundled
14
+ or required:
15
+
16
+ - [FFmpeg](https://ffmpeg.org/), meaning `ffmpeg` and `ffprobe`, for thumbnails and video facts.
17
+ - [ripgrep](https://github.com/BurntSushi/ripgrep), meaning `rg`, for content search.
@@ -0,0 +1 @@
1
+ __version__ = "0.3.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ main()
@@ -0,0 +1,225 @@
1
+ """Who may use the server.
2
+
3
+ Three modes:
4
+
5
+ - open: anyone who can reach the port. The default, as with http.server.
6
+ - tailscale: only named Tailscale users. Bunko listens on loopback behind
7
+ `tailscale serve`, which strips any identity headers a client sends and adds
8
+ the real Tailscale-User-Login. This is the recommended mode.
9
+ - token: anyone holding a secret token. The token arrives once in the URL, then
10
+ lives in a cookie. Weaker: it's a shared secret, and plain HTTP exposes it to
11
+ anyone who can watch the network.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import fnmatch
17
+ import hashlib
18
+ import hmac
19
+ import ipaddress
20
+ import os
21
+ import secrets
22
+ from contextlib import suppress
23
+ from dataclasses import dataclass
24
+ from email.header import decode_header
25
+ from http.cookies import CookieError, SimpleCookie
26
+ from urllib.parse import urlencode
27
+
28
+ from .storage import config_dir, write_private
29
+
30
+ IDENTITY_HEADER = "Tailscale-User-Login"
31
+ NAME_HEADER = "Tailscale-User-Name"
32
+ COOKIE_AGE = 365 * 24 * 3600
33
+
34
+
35
+ def default_token_path() -> str:
36
+ return os.path.join(config_dir(), "token")
37
+
38
+
39
+ def is_loopback(host: str) -> bool:
40
+ if host == "localhost":
41
+ return True
42
+ try:
43
+ return ipaddress.ip_address(host).is_loopback
44
+ except ValueError:
45
+ return False
46
+
47
+
48
+ def decode_rfc2047(value: str) -> str:
49
+ """Tailscale may send non-ASCII names as =?utf-8?q?...?=."""
50
+ try:
51
+ parts = decode_header(value)
52
+ except (ValueError, LookupError):
53
+ return value
54
+ return "".join(
55
+ part.decode(charset or "utf-8", "replace") if isinstance(part, bytes) else part
56
+ for part, charset in parts
57
+ )
58
+
59
+
60
+ class TokenStore:
61
+ """The token file, re-read when it changes so rotation needs no restart."""
62
+
63
+ def __init__(self, path: str | None = None):
64
+ self.env = os.environ.get("BUNKO_TOKEN") or None
65
+ self.path = path or default_token_path()
66
+ self._seen = None
67
+ self._token = None
68
+
69
+ def describe(self) -> str:
70
+ return "the BUNKO_TOKEN environment variable" if self.env else self.path
71
+
72
+ def ensure(self) -> str:
73
+ """Return the token, creating the file on first use."""
74
+ if self.env:
75
+ return self.env
76
+ if not os.path.exists(self.path):
77
+ return self.rotate()
78
+ return self.current()
79
+
80
+ def rotate(self) -> str:
81
+ if self.env:
82
+ raise SystemExit("bunko: the token comes from BUNKO_TOKEN; change it there")
83
+ token = secrets.token_urlsafe(24)
84
+ write_private(self.path, token + "\n")
85
+ return token
86
+
87
+ def current(self) -> str | None:
88
+ if self.env:
89
+ return self.env
90
+ try:
91
+ info = os.stat(self.path)
92
+ except OSError:
93
+ return None
94
+ stamp = (info.st_mtime_ns, info.st_size)
95
+ if stamp != self._seen:
96
+ with open(self.path) as handle:
97
+ self._token = handle.read().strip() or None
98
+ self._seen = stamp
99
+ return self._token
100
+
101
+
102
+ @dataclass
103
+ class Decision:
104
+ """The answer to "may this request go ahead?", and what to send with it."""
105
+
106
+ allowed: bool
107
+ user: str | None = None # display name, shown in the app
108
+ reason: str = "" # why not, when refused
109
+ login: str | None = None # Tailscale login, which keys per-person state
110
+ cookie: str | None = None # a Set-Cookie value to send
111
+ clean_url: str | None = None # redirect here to drop ?token= from the address bar
112
+
113
+
114
+ class Access:
115
+ """The access mode in force, and the check every request goes through."""
116
+
117
+ def __init__(
118
+ self, mode: str = "open", port: int = 0, tokens: TokenStore | None = None, users=()
119
+ ):
120
+ self.mode = mode
121
+ self.port = port
122
+ self.tokens = tokens
123
+ self.users = [user.lower() for user in users]
124
+
125
+ # -- token helpers ---------------------------------------------------
126
+
127
+ @property
128
+ def cookie_name(self) -> str:
129
+ # Cookies are shared by every port on a host, so name ours by port.
130
+ return f"bunko_{self.port}"
131
+
132
+ def session_value(self, token: str) -> str:
133
+ # The cookie holds a derivative, so the raw token never sits in it.
134
+ return hmac.new(token.encode(), b"bunko-session-v1", hashlib.sha256).hexdigest()
135
+
136
+ def session_cookie(self, token: str) -> str:
137
+ value = self.session_value(token)
138
+ return f"{self.cookie_name}={value}; Path=/; Max-Age={COOKIE_AGE}; HttpOnly; SameSite=Lax"
139
+
140
+ def logout_cookie(self) -> str:
141
+ return f"{self.cookie_name}=; Path=/; Max-Age=0; HttpOnly; SameSite=Lax"
142
+
143
+ def user_allowed(self, login: str) -> bool:
144
+ login = login.lower()
145
+ return any(fnmatch.fnmatchcase(login, pattern) for pattern in self.users)
146
+
147
+ # -- the check -------------------------------------------------------
148
+
149
+ def decide(self, headers, raw_path: str, query: dict, navigating: bool) -> Decision:
150
+ """Check a request. raw_path is still percent-encoded, for use in redirects."""
151
+ if self.mode == "open":
152
+ return Decision(True)
153
+ if self.mode == "tailscale":
154
+ return self._tailscale(headers)
155
+ return self._token(headers, raw_path, query, navigating)
156
+
157
+ def _tailscale(self, headers) -> Decision:
158
+ login = headers.get(IDENTITY_HEADER)
159
+ if not login:
160
+ return Decision(False, reason="no-identity")
161
+ login = decode_rfc2047(login)
162
+ if not self.user_allowed(login):
163
+ return Decision(False, user=login, reason="not-allowed")
164
+ name = headers.get(NAME_HEADER)
165
+ return Decision(True, user=decode_rfc2047(name) if name else login, login=login.lower())
166
+
167
+ def _token(self, headers, raw_path: str, query: dict, navigating: bool) -> Decision:
168
+ token = self.tokens.current()
169
+ if not token:
170
+ return Decision(False, reason="no-token-configured")
171
+ expected = self.session_value(token)
172
+
173
+ offered = query.get("token", [None])[0]
174
+ if offered is not None:
175
+ if not hmac.compare_digest(offered.encode(), token.encode()):
176
+ return Decision(False, reason="bad-token")
177
+ decision = Decision(True, cookie=self.session_cookie(token))
178
+ if navigating:
179
+ rest = {key: values for key, values in query.items() if key != "token"}
180
+ decision.clean_url = raw_path + ("?" + urlencode(rest, doseq=True) if rest else "")
181
+ return decision
182
+
183
+ auth = headers.get("Authorization", "")
184
+ if auth.lower().startswith("bearer "):
185
+ if hmac.compare_digest(auth[7:].strip().encode(), token.encode()):
186
+ return Decision(True)
187
+ return Decision(False, reason="bad-token")
188
+
189
+ cookies = SimpleCookie()
190
+ with suppress(CookieError):
191
+ cookies.load(headers.get("Cookie", ""))
192
+ morsel = cookies.get(self.cookie_name)
193
+ if morsel and hmac.compare_digest(morsel.value.encode(), expected.encode()):
194
+ return Decision(True)
195
+ return Decision(False, reason="no-session")
196
+
197
+
198
+ # Filled in with .replace("{message}", ...) rather than %-formatting, because the CSS has % signs.
199
+ LOGIN_PAGE = """<!doctype html>
200
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
201
+ <title>Bunko · sign in</title>
202
+ <style>
203
+ :root{--bg:#fff;--text:#1e2329;--muted:#5d6670;--line:rgba(30,35,41,.16);--accent:#0e7c86;color-scheme:light}
204
+ @media (prefers-color-scheme:dark){:root{--bg:#15171a;--text:#e3e6ea;--muted:#9aa3ad;--line:rgba(227,230,234,.14);--accent:#2a8f99;color-scheme:dark}}
205
+ *{box-sizing:border-box}body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--text);font:15px/1.5 ui-sans-serif,-apple-system,"Segoe UI",Helvetica,Arial,sans-serif;padding:16px}
206
+ main{width:min(380px,100%)}h1{font-size:22px;margin:0 0 6px}p{color:var(--muted);margin:0 0 18px}
207
+ input{width:100%;height:38px;padding:0 10px;border:1px solid var(--line);border-radius:6px;background:var(--bg);color:var(--text);font:inherit}
208
+ input:focus{outline:2px solid var(--accent);outline-offset:-1px}button{margin-top:10px;width:100%;height:38px;border:0;border-radius:6px;background:var(--accent);color:#fff;font:inherit;cursor:pointer}
209
+ .err{color:#e5484d;margin:-6px 0 14px}
210
+ </style></head><body><main>
211
+ <h1>Bunko</h1><p>This server needs an access token. Paste it here, or open the link the server printed.</p>
212
+ {message}<form method="get" action="/"><input name="token" type="password" autocomplete="current-password" placeholder="Access token" aria-label="Access token" autofocus required><button>Open</button></form>
213
+ </main></body></html>"""
214
+
215
+ DENIED_PAGE = """<!doctype html>
216
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
217
+ <title>Bunko · no access</title>
218
+ <style>
219
+ :root{--bg:#fff;--text:#1e2329;--muted:#5d6670;color-scheme:light}
220
+ @media (prefers-color-scheme:dark){:root{--bg:#15171a;--text:#e3e6ea;--muted:#9aa3ad;color-scheme:dark}}
221
+ body{margin:0;min-height:100vh;display:grid;place-items:center;background:var(--bg);color:var(--text);font:15px/1.5 ui-sans-serif,-apple-system,"Segoe UI",Helvetica,Arial,sans-serif;padding:16px}
222
+ main{width:min(440px,100%)}h1{font-size:22px;margin:0 0 6px}p{color:var(--muted)}
223
+ </style></head><body><main><h1>No access</h1><p>{message}</p></main></body></html>"""
224
+
225
+ PAGE_CSP = "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'"