chirkle 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +310 -2
  3. package/package.json +75 -4
  4. package/pb_hooks/federation/config.js +276 -0
  5. package/pb_hooks/federation/inbox.js +316 -0
  6. package/pb_hooks/federation/messages.js +420 -0
  7. package/pb_hooks/federation/mirror.js +277 -0
  8. package/pb_hooks/federation/net.js +247 -0
  9. package/pb_hooks/federation/peers.js +490 -0
  10. package/pb_hooks/federation/people.js +376 -0
  11. package/pb_hooks/federation/rooms.js +552 -0
  12. package/pb_hooks/federation/worker.js +413 -0
  13. package/pb_hooks/federation.pb.js +141 -0
  14. package/pb_hooks/lib/access.js +102 -0
  15. package/pb_hooks/lib/account.js +31 -0
  16. package/pb_hooks/lib/anonymous.js +189 -0
  17. package/pb_hooks/lib/bulk.js +187 -0
  18. package/pb_hooks/lib/collections.js +587 -0
  19. package/pb_hooks/lib/dms.js +123 -0
  20. package/pb_hooks/lib/emoji.js +28 -0
  21. package/pb_hooks/lib/enrich.js +75 -0
  22. package/pb_hooks/lib/features.js +31 -0
  23. package/pb_hooks/lib/files.js +375 -0
  24. package/pb_hooks/lib/http.js +146 -0
  25. package/pb_hooks/lib/images.js +160 -0
  26. package/pb_hooks/lib/keepalive.js +31 -0
  27. package/pb_hooks/lib/lists.js +173 -0
  28. package/pb_hooks/lib/media.js +635 -0
  29. package/pb_hooks/lib/messages.js +519 -0
  30. package/pb_hooks/lib/moderation.js +128 -0
  31. package/pb_hooks/lib/outbound.js +116 -0
  32. package/pb_hooks/lib/pages.js +171 -0
  33. package/pb_hooks/lib/previews.js +346 -0
  34. package/pb_hooks/lib/reactions.js +110 -0
  35. package/pb_hooks/lib/reads.js +181 -0
  36. package/pb_hooks/lib/records.js +77 -0
  37. package/pb_hooks/lib/rooms.js +148 -0
  38. package/pb_hooks/lib/site.js +102 -0
  39. package/pb_hooks/lib/text.js +110 -0
  40. package/pb_hooks/lib/users.js +81 -0
  41. package/pb_hooks/lib/worker.js +159 -0
  42. package/pb_hooks/main.pb.js +324 -0
  43. package/pb_hooks/telegram/api.js +128 -0
  44. package/pb_hooks/telegram/inbound.js +548 -0
  45. package/pb_hooks/telegram/links.js +157 -0
  46. package/pb_hooks/telegram/outbound.js +323 -0
  47. package/pb_hooks/telegram/people.js +166 -0
  48. package/pb_hooks/telegram/rich.js +192 -0
  49. package/pb_hooks/telegram/worker.js +181 -0
  50. package/pb_hooks/telegram.pb.js +47 -0
  51. package/pb_migrations/1760000000_init.js +150 -0
  52. package/pb_migrations/1760000001_qa_fixes.js +69 -0
  53. package/pb_migrations/1760000002_avatars.js +39 -0
  54. package/pb_migrations/1760000003_direct_messages.js +142 -0
  55. package/pb_migrations/1760000004_attachments.js +28 -0
  56. package/pb_migrations/1760000005_file_names.js +16 -0
  57. package/pb_migrations/1760000006_room_reads.js +41 -0
  58. package/pb_migrations/1760000007_replies.js +23 -0
  59. package/pb_migrations/1760000008_lowercase_emails.js +24 -0
  60. package/pb_migrations/1760000009_reactions.js +32 -0
  61. package/pb_migrations/1760000010_fit_thumbs.js +18 -0
  62. package/pb_migrations/1760000011_forwarding.js +39 -0
  63. package/pb_migrations/1760000012_accounts.js +55 -0
  64. package/pb_migrations/1760000013_qa_pass5.js +19 -0
  65. package/pb_migrations/1760000014_room_access.js +96 -0
  66. package/pb_migrations/1760000015_site.js +46 -0
  67. package/pb_migrations/1760000016_forward_refs.js +43 -0
  68. package/pb_migrations/1760000017_no_dms.js +18 -0
  69. package/pb_migrations/1760000018_attachment_limits.js +24 -0
  70. package/pb_migrations/1760000019_telegram.js +109 -0
  71. package/pb_migrations/1760000020_service_messages.js +21 -0
  72. package/pb_migrations/1760000021_forward_view_index.js +41 -0
  73. package/pb_migrations/1760000022_link_previews.js +43 -0
  74. package/pb_migrations/1760000023_room_writers.js +49 -0
  75. package/pb_migrations/1760000024_message_search.js +51 -0
  76. package/pb_migrations/1760000025_search_dotted_i.js +16 -0
  77. package/pb_migrations/1760000026_push.js +67 -0
  78. package/pb_migrations/1760000027_push_tokens_per_user.js +31 -0
  79. package/pb_migrations/1760000028_media_grid_thumbs.js +18 -0
  80. package/pb_migrations/1760000029_media.js +71 -0
  81. package/pb_migrations/1760000030_collections.js +140 -0
  82. package/pb_migrations/1760000031_unread_limit.js +20 -0
  83. package/pb_migrations/1760000032_federation.js +227 -0
  84. package/pb_migrations/1760000033_federation_requests.js +44 -0
  85. package/pb_migrations/1760000034_telegram_parts.js +26 -0
  86. package/pb_migrations/1760000035_telegram_anonymous.js +16 -0
  87. package/pb_migrations/1760000036_chirkle.js +20 -0
  88. package/pb_migrations/1760000037_file_dims.js +35 -0
  89. package/pb_migrations/1760000038_drop_push.js +64 -0
  90. package/pb_migrations/1760000039_anonymous_rooms.js +40 -0
  91. package/pb_migrations/1760000040_moderators.js +42 -0
  92. package/pb_migrations/1760000041_shared_files.js +500 -0
  93. package/pb_migrations/1760000042_files_src.js +17 -0
  94. package/pb_public/assets/access-ALBW2MT2.js +2 -0
  95. package/pb_public/assets/access-ALBW2MT2.js.map +7 -0
  96. package/pb_public/assets/access-PB77EH4F.css +2 -0
  97. package/pb_public/assets/access-PB77EH4F.css.map +7 -0
  98. package/pb_public/assets/app-ECR34OBK.css +2 -0
  99. package/pb_public/assets/app-ECR34OBK.css.map +7 -0
  100. package/pb_public/assets/app-SILEBEXB.js +3 -0
  101. package/pb_public/assets/app-SILEBEXB.js.map +7 -0
  102. package/pb_public/assets/collections-VEOIOCAW.css +2 -0
  103. package/pb_public/assets/collections-VEOIOCAW.css.map +7 -0
  104. package/pb_public/assets/emoji-WSTVXAW5.css +2 -0
  105. package/pb_public/assets/emoji-WSTVXAW5.css.map +7 -0
  106. package/pb_public/assets/emoji-picker-QYRX6NYL.js +609 -0
  107. package/pb_public/assets/emoji-picker-QYRX6NYL.js.map +7 -0
  108. package/pb_public/assets/inter-cyrillic-JEOLYBOO.woff2 +0 -0
  109. package/pb_public/assets/inter-cyrillic-ext-IYF56FF6.woff2 +0 -0
  110. package/pb_public/assets/inter-greek-IRE366VL.woff2 +0 -0
  111. package/pb_public/assets/inter-latin-NRMW37G5.woff2 +0 -0
  112. package/pb_public/assets/inter-latin-ext-HA22NDSG.woff2 +0 -0
  113. package/pb_public/assets/lazy-SCCVSUZO.js +2 -0
  114. package/pb_public/assets/lazy-SCCVSUZO.js.map +7 -0
  115. package/pb_public/assets/media-DH7ECZSF.js +2 -0
  116. package/pb_public/assets/media-DH7ECZSF.js.map +7 -0
  117. package/pb_public/assets/media-L3EYTHKT.css +2 -0
  118. package/pb_public/assets/media-L3EYTHKT.css.map +7 -0
  119. package/pb_public/assets/notify-L6GERFNO.js +2 -0
  120. package/pb_public/assets/notify-L6GERFNO.js.map +7 -0
  121. package/pb_public/assets/search-3UT4HMES.js +2 -0
  122. package/pb_public/assets/search-3UT4HMES.js.map +7 -0
  123. package/pb_public/assets/switcher-CEUKRLEY.js +2 -0
  124. package/pb_public/assets/switcher-CEUKRLEY.js.map +7 -0
  125. package/pb_public/assets/viewer-DXT7SKOU.js +2 -0
  126. package/pb_public/assets/viewer-DXT7SKOU.js.map +7 -0
  127. package/pb_public/assets/viewer-P7GYCBYM.css +2 -0
  128. package/pb_public/assets/viewer-P7GYCBYM.css.map +7 -0
  129. package/pb_public/icons/apple-touch-icon.png +0 -0
  130. package/pb_public/icons/icon-192.png +0 -0
  131. package/pb_public/icons/icon-512.png +0 -0
  132. package/pb_public/icons/icon.svg +1 -0
  133. package/pb_public/icons/maskable-512.png +0 -0
  134. package/pb_public/index.html +21 -0
  135. package/pb_public/sw.js +1 -0
  136. package/scripts/fetch-pocketbase.sh +63 -0
  137. package/scripts/start.mjs +93 -0
package/README.md CHANGED
@@ -1,3 +1,311 @@
1
- # Temporary Holding Version
1
+ # <img src="logo.svg" alt="" width="36" height="36" align="top"> Chirkle
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A small, fast, real-time group chat. One [PocketBase](https://pocketbase.io) binary is the whole backend
4
+ (auth, data, realtime, static files); the frontend is vanilla TypeScript bundled by esbuild — no framework,
5
+ ~49 KB of JS and ~11 KB of CSS gzipped (`npm run build` fails over its budget: 49.75 KB of JS,
6
+ 11.25 KB of CSS; rarer screens such as the image viewer, search, room access and collections load on first use).
7
+
8
+ <picture>
9
+ <source media="(prefers-color-scheme: dark)" srcset="docs/screenshot-dark.png">
10
+ <img alt="A room in Chirkle: the room list with unread counts on the left; messages with avatars, a reply, a photo and emoji reactions on the right" src="docs/screenshot-light.png">
11
+ </picture>
12
+
13
+ - Public rooms anyone can create; hide rooms you don't care about; creators archive rooms (read-only, history kept)
14
+ - Room access, chosen by each room's creator: **Private** (only the people they add), **Public** (everyone with an account) or **Open Air** (anyone can read it, no account needed; the home page shows these rooms to guests, who log in or sign up to join in); and who can post: everyone who can read it, or only the people they choose (the others read and react)
15
+ - Live messages, edits and deletes (deleted messages leave a placeholder)
16
+ - Full history: scroll back to the very first message of any room (windowed, ≤300 messages in the DOM)
17
+ - Direct messages between any two users, private to them; close a conversation and it comes back on the next message
18
+ - Avatars (or colored initials) and a profile page to change your picture, display name (unique) and password, and to log out
19
+ - Search in any room or DM: every word you type, in any case ("привет" finds "Привет"), newest first; pick a result to go to it, however far back
20
+ - Replies: answer any message with a quote of it; click the quote to jump to the original, however far back
21
+ - Links in messages are clickable and open in a new tab (http, https and www. addresses only)
22
+ - Emoji: a picker in the composer, and reactions on any message (as many different ones as you like), live for everyone
23
+ - Attachments: up to 10 files of 20 MB per message, with an upload progress bar; images shown as thumbnails and videos as their first frame (4 tiles, then "+N"); files are private to whoever can read the message
24
+ - Image viewer: click a thumbnail to see it full size (or a video to play it) and step through the room's images and videos (buttons, arrow keys, swipe);
25
+ loaded only when first used, so it adds nothing to the page's first load
26
+ - Collections: save any image or video from the chat to collections of your own, public or private, and attach from them to messages; subscribe to other people's public collections to use theirs too, with a count of what's new and the new items highlighted; media attached from a collection link to it (or say "Private collection")
27
+ - Select messages (up to 50): forward them to any room or DM, with "Forwarded from" and their attachments (forwards show the original, so nothing is copied), or delete them together when they are yours
28
+ - Unread counts on every room and DM, live, and in sync across your tabs and devices; the total shows in the tab's favicon and title;
29
+ a room with unread messages opens at the first of them, under a "New" line
30
+ - What you were typing is kept per room, even across a reload; "Jump to latest" whenever you are scrolled up
31
+ - Your own branding (title and logo) and, if you like, invite-only signups: set by the admin in PocketBase
32
+ - Telegram bridge (optional): link rooms to Telegram groups through a bot; messages, replies, edits and files go both ways (deletes from Chirkle to Telegram), Telegram people show under stand-in accounts with their names and pictures — see [Telegram integration](#telegram-integration)
33
+ - Fast room switching: each room's latest messages are kept in the browser (IndexedDB) and shown at once while the
34
+ server answers; unread rooms are fetched ahead. Attachment thumbnails are kept by the service worker, so going back
35
+ to a room (or reloading) doesn't download them again. All of it is cleared on logout
36
+ - Notifications of DMs and replies to you, with a pop-up and/or a sound, turned on in your profile, and of every
37
+ message in the rooms you choose from their menu: they come from the open tab's live connection (even in the
38
+ background), so no push service (Google, Mozilla, Apple) is involved
39
+ - Installable as an app (PWA: Add to Home Screen, the browser's Install button); it opens offline to its shell
40
+ - Optimistic sending with safe retries, reconnect gap-fill, light/dark themes, works on phones
41
+ - A native Android app (Kotlin, Jetpack Compose) with the same features, notifications and a 3 MB download — see
42
+ [Android app](#android-app)
43
+
44
+ Design: [`docs/DESIGN.md`](docs/DESIGN.md) · Android app: [`docs/ANDROID.md`](docs/ANDROID.md) · QA: [`docs/QA.md`](docs/QA.md) · Refactoring plan: [`docs/REFACTOR.md`](docs/REFACTOR.md) · Archived plans: [MVP build](docs/history/BUILD_PLAN.md), [avatars, DMs, attachments](docs/history/NEXT_FEATURES_PLAN.md)
45
+
46
+ ## Requirements
47
+
48
+ - Node.js ≥ 22 and npm ≥ 11
49
+ - Linux or macOS (x64/arm64) — `npm start` and `npm run setup` download the matching PocketBase binary (Windows: WSL or Docker)
50
+ - Optional, for the server's workers: `ffmpeg` (video posters) and `curl` (link previews) on the `PATH`
51
+ - For e2e tests: Playwright's Chromium (`npx playwright install chromium`)
52
+
53
+ ## Quick start
54
+
55
+ ```sh
56
+ npm install
57
+ npm start # builds the web app, downloads PocketBase on the first run, serves http://127.0.0.1:8090
58
+ ```
59
+
60
+ Or without a clone, from npm (the package ships the built web app and the server's hooks and migrations):
61
+
62
+ ```sh
63
+ npx chirkle # data in ./pb_data
64
+ npx chirkle chat.example.com # HTTPS with Let's Encrypt on ports 80/443
65
+ ```
66
+
67
+ Open the page and sign up. The first run prints a link to create the admin (superuser) account, or create one with
68
+ `npx chirkle superuser upsert you@example.com <password>` (`npm start -- superuser upsert …` in a clone).
69
+ `HOST` and `PORT` choose the address (default `127.0.0.1:8090`; `HOST=0.0.0.0` to reach it from other machines),
70
+ `CHIRKLE_DATA` the data directory (default `./pb_data`), and any other `pocketbase serve` flags can follow
71
+ (`npx chirkle --http=0.0.0.0:80`). The settings of [Deploying](#deploying) (`TRUSTED_PROXY` behind a reverse proxy, …)
72
+ apply as they are. PocketBase is kept in the package's `bin/` (or `~/.cache/chirkle/` when that isn't writable).
73
+
74
+ ## Getting started (development)
75
+
76
+ ```sh
77
+ npm ci
78
+ npm run setup # downloads the pinned PocketBase (checksum-verified) into bin/
79
+ npm run dev # esbuild watch + PocketBase on http://127.0.0.1:8090
80
+ ```
81
+
82
+ Open http://127.0.0.1:8090 and sign up (top right). The dev database lives in `pb_data/` — delete it to start over.
83
+ The PocketBase admin UI is at http://127.0.0.1:8090/_/ (create a superuser with
84
+ `bin/pocketbase superuser upsert you@example.com <password> --dir=pb_data`).
85
+
86
+ ## Scripts
87
+
88
+ | Script | What it does |
89
+ |---|---|
90
+ | `npm start` | Production build, then the server (`scripts/start.mjs`, the package's `chirkle` command): PocketBase on http://127.0.0.1:8090 with `pb_data/` |
91
+ | `npm run dev` | Unminified watch build into `pb_public/` + `pocketbase serve --dev` |
92
+ | `npm run build` | Production build (hashed assets) into `pb_public/`; fails if over the size budget |
93
+ | `npm run typecheck` | `tsc` (strict) for the frontend, tests and scripts, plus `pb_hooks/` + `pb_migrations/` against PocketBase's generated types (`types/pocketbase.d.ts`, written by `scripts/pb-types.sh`) |
94
+ | `npm run lint` | Biome: formatting, lint rules, import order (`npm run format` applies the fixes) |
95
+ | `npm run lint:sinks` | Fails if frontend code uses `innerHTML` & co. (XSS guard) |
96
+ | `npm test` | Unit tests (Vitest + happy-dom, no server) and component tests (views and services against a real, throwaway PocketBase) |
97
+ | `npm run test:unit` | Only the unit tests: no server, ~10 s |
98
+ | `npm run test:int` | Integration tests: schema, API rules, hooks, realtime, pagination |
99
+ | `npm run test:e2e` | Playwright end-to-end tests against the production build |
100
+ | `npm run schema:snapshot` | Rewrite `docs/schema.snapshot.json` (every collection's API rules, fields and indexes, and the rate limits) after a migration changes them; `test:int` fails while it is out of date |
101
+ | `npm run screenshots` | Rewrite the README screenshots (`docs/screenshot-*.png`): a throwaway server with made-up people and messages, photographed in Chromium after `npm run build` |
102
+ | `npm run check` | typecheck + lint + lint:sinks + test + test:int + build (what CI runs before e2e) |
103
+
104
+ Every test run starts its own PocketBase on a free port with a temp data dir — nothing to clean up, and no fakes
105
+ except a stub Telegram Bot API for the bridge's tests. CI (`.github/workflows/ci.yml`) runs typecheck, lint and build, then unit, integration and e2e side by side, e2e once
106
+ per browser (Chromium, Firefox, WebKit).
107
+
108
+ ## Project layout
109
+
110
+ ```
111
+ pb_migrations/ schema + API rules (the source of truth for access control)
112
+ pb_hooks/ server-side hooks: trimming, soft delete, edit/archive stamps, DM + unread routes, guards, security headers;
113
+ telegram.pb.js + telegram/: the optional Telegram bridge
114
+ web/src/ frontend: api.ts (the only module that talks to PocketBase, through pb.ts, a minimal client), router,
115
+ store, cache.ts (the room cache), sw.ts (the service worker), views/, lib/ (pure logic)
116
+ web/styles/ app.css (bundles app/*.css, one file per part) and viewer.css
117
+ web/public/ icons/: the logo (logo.svg) as icon.svg and the PNG app icons, served as they are
118
+ scripts/ build, dev, fetch-pocketbase, pb-types (PocketBase's types for the hooks), html-sink check
119
+ tests/ unit/, integration/, e2e/, perf/ (scale measurements), support/ (PocketBase harness, Telegram stub, helpers)
120
+ android/ the Android app (docs/ANDROID.md): core/data (API, realtime, database, sync), core/ui, feature/*, app
121
+ ```
122
+
123
+ ## Deploying
124
+
125
+ Build once, then copy `bin/pocketbase`, `pb_public/`, `pb_migrations/` and `pb_hooks/` to the server.
126
+ Migrations run automatically on start, and nothing is served until they are done, so they change only the database.
127
+ What stored files need moving (the shared files of DESIGN.md §37) the media worker does afterwards, while the server
128
+ runs.
129
+
130
+ ```sh
131
+ npm ci && npm run setup && npm run build
132
+ rsync -a bin/pocketbase pb_public pb_migrations pb_hooks server:/opt/chirkle/
133
+ ```
134
+
135
+ With a domain pointing at the server, PocketBase serves HTTPS itself (Let's Encrypt):
136
+
137
+ ```ini
138
+ # /etc/systemd/system/chirkle.service
139
+ [Unit]
140
+ Description=Chirkle (PocketBase)
141
+ After=network-online.target
142
+
143
+ [Service]
144
+ User=chirkle
145
+ WorkingDirectory=/opt/chirkle
146
+ ExecStart=/opt/chirkle/pocketbase serve chat.example.com --hooksPool=100 --dir=/opt/chirkle/pb_data --publicDir=/opt/chirkle/pb_public --migrationsDir=/opt/chirkle/pb_migrations --hooksDir=/opt/chirkle/pb_hooks
147
+ Restart=on-failure
148
+ AmbientCapabilities=CAP_NET_BIND_SERVICE
149
+ LimitNOFILE=65536
150
+
151
+ [Install]
152
+ WantedBy=multi-user.target
153
+ ```
154
+
155
+ ```sh
156
+ sudo systemctl enable --now chirkle
157
+ sudo -u chirkle /opt/chirkle/pocketbase superuser upsert you@example.com <password> --dir=/opt/chirkle/pb_data
158
+ ```
159
+
160
+ Behind an existing reverse proxy instead, use `serve --http=127.0.0.1:8090` and proxy to it (keep
161
+ `/api/realtime` unbuffered — it is a Server-Sent Events stream — and let request bodies through up to 210 MB, since a
162
+ message may carry 10 files of 20 MB), and start PocketBase with
163
+ `TRUSTED_PROXY=X-Forwarded-For` (`Environment=` in the unit). The rate limits are per client IP: without it, every
164
+ request seems to come from the proxy, and one client tripping a limit trips it for everyone. The rightmost address of
165
+ the header is used, the one your proxy added. The Docker image sets it (Dokku always runs a proxy in front); run it
166
+ with `-e TRUSTED_PROXY=off` if clients reach port 8090 directly, since they could then choose their own IP. Unset, the
167
+ setting is left as configured under *Settings → Application* in the admin UI.
168
+
169
+ ### Dokku
170
+
171
+ The `Dockerfile` builds the production image (frontend + pinned PocketBase), and `app.json` gives Dokku its health
172
+ check. On the server:
173
+
174
+ ```sh
175
+ dokku apps:create chirkle
176
+ # All data (SQLite + uploads) lives in /pb_data: keep it on the host. The directory is owned by uid 32767, the
177
+ # image's user.
178
+ dokku storage:ensure-directory chirkle
179
+ dokku storage:mount chirkle /var/lib/dokku/data/storage/chirkle:/pb_data
180
+ dokku domains:set chirkle chat.example.com
181
+ # nginx allows 1 MB bodies by default; a message may carry 10 files of 20 MB.
182
+ dokku nginx:set chirkle client-max-body-size 210m
183
+ dokku letsencrypt:enable chirkle # with the dokku-letsencrypt plugin
184
+ ```
185
+
186
+ Then deploy (`git push dokku master` from a clone with `dokku@server:chirkle` as the `dokku` remote) and create a
187
+ superuser:
188
+
189
+ ```sh
190
+ dokku run chirkle /app/pocketbase superuser upsert you@example.com <password> --dir=/pb_data
191
+ ```
192
+
193
+ Settings go in as environment variables (`dokku config:set chirkle KEY=value`, which restarts the app); the image already
194
+ sets `TRUSTED_PROXY` for Dokku's proxy. `dokku logs chirkle -t` shows PocketBase's output; the app's own log (request
195
+ log and errors from hooks) is in the admin UI under *Logs*.
196
+
197
+ ### Running it
198
+
199
+ **Branding and invite-only signups:** in the admin UI, *Collections → site*, edit the one record: `title` and `logo`
200
+ are shown in the app bar, on the login page and in the tab's title. Tick `invite_only` and fill `invite_code` to let
201
+ only people who have the code sign up (they enter it on the Sign up form; it is case-sensitive). Change the code to stop
202
+ the old one working; leave it empty to close signups. Existing accounts are unaffected, and you can still create
203
+ accounts yourself under *Collections → users*.
204
+
205
+ **Backups:** in the admin UI, *Settings → Backups* — schedule automatic backups (optionally to S3-compatible
206
+ storage). Uploaded files (avatars, attachments) live in `pb_data/storage` (or S3, under *Settings → Files storage*) and
207
+ are part of the backups, so plan disk space for them. **Rate limits** (per IP: messages 10 per 5 s, edits/deletes 20
208
+ per 10 s, reactions 30 per 10 s, forwarding and deleting several messages 20 requests per minute each, password changes 5 per minute, new rooms 5 per minute, opening DMs 10 per minute, marking rooms read 120 per minute, signups 20 per minute; PocketBase defaults for the rest)
209
+ are set by the migrations and adjustable under *Settings → Rate limits*.
210
+
211
+ ## Android app
212
+
213
+ In active development alongside the web client (it was frozen 2026-10-21..23): web features and fixes are ported to
214
+ it ([`CLAUDE.md`](CLAUDE.md), [`android/PARITY.md`](android/PARITY.md)).
215
+
216
+ A native client for any server running Chirkle, with several accounts at once on one server or many (`android/`,
217
+ design: [`docs/ANDROID.md`](docs/ANDROID.md), §17 for servers and accounts). It needs JDK 17+
218
+ (21 recommended) and the Android SDK (`ANDROID_HOME`, or `sdk.dir` in `android/local.properties`); Gradle fetches the
219
+ rest. Its tests start PocketBase from `bin/`, so run `npm run setup` first.
220
+
221
+ ```sh
222
+ cd android
223
+ ./gradlew assembleDebug # app/build/outputs/apk/debug: offers http://10.0.2.2:8090 (the dev server, from the emulator)
224
+ ./gradlew check # lint, unit tests, API tests against PocketBase, UI tests on Robolectric
225
+ ./gradlew checkApkSize -Pchirkle.server=https://chat.example.org -Pchirkle.appId=org.example.chirkle
226
+ ```
227
+
228
+ People choose their server when they log in or sign up (Change server), and add more accounts from their profile.
229
+ A build only sets the server offered first: `-Pchirkle.devServer=http://192.168.1.20:8090` for a debug build on a device,
230
+ `chirkle.server` for a release (without one, the app asks for a server, and no host's links open in the app). Debug builds
231
+ take http addresses; release builds take https only. The app notifies of DMs and replies to you by checking each
232
+ account's server about every 15 minutes (WorkManager), with no Google services and nothing to set up on the server
233
+ (ANDROID.md §21). Links to rooms on the build's server open in the app once `ANDROID_CERT_SHA256` is
234
+ set (`/.well-known/assetlinks.json`; `ANDROID_APP_ID` only for a build with another `chirkle.appId`). An admin can set
235
+ `min_android_version` on the site record to make older apps ask for an update. What is built and what isn't yet:
236
+ [`docs/ANDROID.md` §16](docs/ANDROID.md#16-implementation-2026-10-18), and [`android/PARITY.md`](android/PARITY.md).
237
+
238
+ ## Link previews
239
+
240
+ Messages show a line under them for each link: the page's favicon and title ([`docs/DESIGN.md` §28](docs/DESIGN.md)).
241
+ The server fetches them with `curl` (in the Docker image), only from public addresses. Set `LINK_PREVIEWS=off` to turn
242
+ it off.
243
+
244
+ ## Media grid
245
+
246
+ Each room's Media button shows its images and videos as a grid ([`docs/DESIGN.md` §30](docs/DESIGN.md)). A worker on
247
+ the server makes their thumbnails ahead of time, and a poster frame for each video with `ffmpeg` (in the Docker
248
+ image), which the room shows too, so browsers don't load videos just to draw their first frame. Set `FFMPEG=off` to
249
+ go without: videos then show their first frame in the room as before, and plain tiles in the grid.
250
+
251
+ ## Telegram integration
252
+
253
+ An optional bridge between rooms and Telegram groups ([`docs/DESIGN.md` §26](docs/DESIGN.md)). A bot sits in your
254
+ groups; once a group is linked to a room, messages, replies, edits and files go both ways (deletes only from Chirkle
255
+ to Telegram). Telegram people show in the room under stand-in users ("Ann Lee (TG)") with their names and pictures;
256
+ the bot posts Chirkle messages with the author's name above them.
257
+
258
+ **Setup**
259
+
260
+ 1. Create a bot with [@BotFather](https://t.me/BotFather) (`/newbot`) and keep its token. Turn its privacy mode off
261
+ (`/setprivacy` → Disable) so it sees group messages; if the bot is already in a group, remove it and add it again.
262
+ 2. Set the environment and restart:
263
+ - `TELEGRAM_BOT_TOKEN` — the bot's token (without it the bridge is off)
264
+ - `TELEGRAM_WEBHOOK_URL` — `https://<your domain>/api/telegram/webhook` (without it the bridge polls Telegram,
265
+ for local development)
266
+
267
+ With Dokku: `dokku config:set chirkle TELEGRAM_BOT_TOKEN='…' TELEGRAM_WEBHOOK_URL='https://chat.example.com/api/telegram/webhook'`.
268
+ 3. Add the bot to a Telegram group. A row for it appears in the admin UI under *Collections → tg_links*: pick the
269
+ room and tick `enabled`. `/chatid` in the group says whether it is linked. Tick `anonymous` too to repost the
270
+ room's messages to that group without their authors' names.
271
+
272
+ To make a room **anonymous**, tick `anonymous` on its row under *Collections → rooms* in the admin UI. Messages
273
+ posted from then on show the room's name instead of their authors to everyone but the authors themselves (and
274
+ superusers); see DESIGN.md §35. Telegram groups linked to it get the room's name as the author too.
275
+
276
+ The bridge is self-contained: `pb_hooks/telegram.pb.js`, `pb_hooks/telegram/` and its own `tg_*` collections. Delete
277
+ the first two to remove it.
278
+
279
+ ## Linked instances
280
+
281
+ Two or more servers running this app can share rooms and let their people write DMs to each other
282
+ ([`docs/DESIGN.md` §33](docs/DESIGN.md)). Each room has a home server; the others keep a copy, and messages, edits,
283
+ replies, reactions and files go both ways. People from the other server show under stand-in users named after them
284
+ ("Ann (B)"). Only the admins of both servers pair them and choose which rooms to share.
285
+
286
+ **Setup** (on each server)
287
+
288
+ 1. Turn it on: in the admin UI, set *Settings → Application → Application URL* to the server's public address, e.g.
289
+ `https://chat.example.com`, then tick `federation` on the record under *Collections → site*. Peers are reached over
290
+ https, on public addresses only. The address is part of the ids the peers keep, so it can't be changed while any
291
+ peer is listed. (A server set up with the old `FEDERATION_ORIGIN` variable gets both done by its next start's
292
+ migration; the variable is no longer read after that.)
293
+ 2. Pair: on server A, under *Collections → fed_peers*, add a row with B's address and a short label for its people
294
+ (`B`); tick `dms` to let people write DMs across. A sends B the request, and it shows on B as a row with status
295
+ `requested` (B checks with A that it really asked). B's admin accepts by setting its status to `active`, choosing
296
+ a label for A's people (and `dms`); both rows are then `active`. Deleting the request declines it. A request B
297
+ can't be reached for is sent again every minute; one nobody accepts expires after 7 days. If both admins add
298
+ each other, they pair at once.
299
+ 3. Share a room: on its home, add a row under *fed_shares* with the room and the peer. The peer's admin finds it under
300
+ *fed_shares* there and ticks `accepted`; the room then appears there, named "general (A)", with its latest 200
301
+ messages. Private rooms too: each side's admins add their own people (on the copy, by editing its members), and the
302
+ room's creator can add people from the other server by their address, `ann@b.example`.
303
+ 4. DMs: with `dms` ticked on both sides, people type `name@b.example` in "New message".
304
+
305
+ Suspend a peer by setting its `status` to `suspended`; delete its row to unpair (the copies are archived, DMs become
306
+ read-only). The feature is self-contained: `pb_hooks/federation.pb.js`, `pb_hooks/federation/` and the `fed_*`
307
+ collections; while `federation` isn't ticked, its routes answer 404 and nothing is sent.
308
+
309
+ ## License
310
+
311
+ [GNU General Public License v3.0](LICENSE) or later.
package/package.json CHANGED
@@ -1,6 +1,77 @@
1
1
  {
2
2
  "name": "chirkle",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "A small, fast, real-time group chat: one PocketBase server, a vanilla TypeScript web app",
5
+ "license": "GPL-3.0-or-later",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/border-radius/chirkle.git"
9
+ },
10
+ "homepage": "https://github.com/border-radius/chirkle#readme",
11
+ "keywords": [
12
+ "chat",
13
+ "pocketbase",
14
+ "self-hosted",
15
+ "realtime"
16
+ ],
17
+ "type": "module",
18
+ "bin": {
19
+ "chirkle": "scripts/start.mjs"
20
+ },
21
+ "files": [
22
+ "pb_public/",
23
+ "pb_hooks/",
24
+ "pb_migrations/",
25
+ "scripts/start.mjs",
26
+ "scripts/fetch-pocketbase.sh"
27
+ ],
28
+ "engines": {
29
+ "node": ">=22",
30
+ "npm": ">=11"
31
+ },
32
+ "os": [
33
+ "linux",
34
+ "darwin"
35
+ ],
36
+ "cpu": [
37
+ "x64",
38
+ "arm64"
39
+ ],
40
+ "scripts": {
41
+ "start": "node scripts/start.mjs",
42
+ "prepack": "npm run build",
43
+ "setup": "sh scripts/fetch-pocketbase.sh",
44
+ "dev": "node scripts/dev.mjs",
45
+ "build": "node scripts/build.mjs",
46
+ "typecheck": "sh scripts/pb-types.sh && tsc --noEmit && tsc --noEmit -p tsconfig.server.json",
47
+ "lint": "biome check .",
48
+ "format": "biome check --write .",
49
+ "lint:sinks": "sh scripts/check-no-html-sinks.sh",
50
+ "test": "vitest run --project unit --project component",
51
+ "test:unit": "vitest run --project unit",
52
+ "test:watch": "vitest --project unit --project component",
53
+ "test:int": "vitest run --project integration",
54
+ "test:e2e": "playwright test",
55
+ "screenshots": "node --no-warnings scripts/screenshots.ts",
56
+ "profile:web": "node --no-warnings scripts/profile-web.ts",
57
+ "schema:snapshot": "vitest run --project integration -u tests/integration/schema.snapshot.test.ts",
58
+ "check": "npm run typecheck && npm run lint && npm run lint:sinks && npm test && npm run test:int && npm run build"
59
+ },
60
+ "devDependencies": {
61
+ "@axe-core/playwright": "4.13.0",
62
+ "@biomejs/biome": "2.5.14",
63
+ "@playwright/test": "1.63.0",
64
+ "@types/node": "22.20.5",
65
+ "@vitest/coverage-v8": "5.0.2",
66
+ "esbuild": "0.28.2",
67
+ "eventsource": "5.1.2",
68
+ "happy-dom": "20.14.5",
69
+ "playwright-core": "1.63.0",
70
+ "pocketbase": "0.28.1",
71
+ "typescript": "7.0.2",
72
+ "vitest": "5.0.2"
73
+ },
74
+ "allowScripts": {
75
+ "esbuild@0.28.2": true
76
+ }
77
+ }
@@ -0,0 +1,276 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Linked instances (DESIGN.md §33): this server's origin, global ids, peers, and the queue every part writes to.
3
+
4
+ /** Tests and development only: peers on private addresses and plain http (§33.6). */
5
+ const allowPrivate = () => $os.getenv("FEDERATION_ALLOW_PRIVATE").trim() === "1";
6
+
7
+ /**
8
+ * An origin as stored: scheme and host (and port), lowercased, no path. "" for anything else.
9
+ * @param {string} raw
10
+ */
11
+ function cleanOrigin(raw) {
12
+ const m = /^(https?):\/\/([a-z0-9.-]+(?::\d+)?)\/?$/i.exec(String(raw || "").trim());
13
+ if (!m) return "";
14
+ return `${m[1].toLowerCase()}://${m[2].toLowerCase()}`;
15
+ }
16
+
17
+ /** This server's public origin: the Application URL (Settings → Application), as stored. "" when it isn't one. */
18
+ const origin = () => cleanOrigin($app.settings().meta.appURL);
19
+
20
+ /**
21
+ * Why this server can't link with others, or "" when it can: the Application URL must be its public https address
22
+ * (http and localhost only with FEDERATION_ALLOW_PRIVATE).
23
+ * @param {string} [o] an Application URL to check instead of the current one
24
+ */
25
+ function originProblem(o = origin()) {
26
+ const c = cleanOrigin(o);
27
+ if (!c) return "Set the Application URL (Settings → Application) to this server's public address, like https://chat.example.org.";
28
+ if (allowPrivate()) return "";
29
+ if (!c.startsWith("https://")) return "The Application URL must be this server's public https:// address.";
30
+ if (/^https:\/\/(localhost|127\.|\[?::1)/.test(c)) return "The Application URL must be this server's public address, not localhost.";
31
+ return "";
32
+ }
33
+
34
+ /**
35
+ * Is the module on (§33.2): the site record's `federation` ticked, and an Application URL that can be linked with.
36
+ * Off, the /api/fed/ routes answer 404 and the worker sends nothing.
37
+ * @param {core.App} app
38
+ */
39
+ function enabled(app) {
40
+ if (originProblem()) return false;
41
+ const found = app.findRecordsByFilter("site", "", "created", 1, 0);
42
+ return !!found[0]?.getBool("federation");
43
+ }
44
+
45
+ /**
46
+ * The /api/fed/ routes (and remote-users) while the module is off: 404, as on a server without it.
47
+ * @param {core.App} app
48
+ */
49
+ function requireOn(app) {
50
+ if (!enabled(app)) throw new NotFoundError("Linking with other instances is off here.");
51
+ }
52
+
53
+ const IN_USE_KEY = "fed.inUse";
54
+
55
+ /**
56
+ * Has this instance any fed_peers row at all: the record hooks have nothing to do without one, and skip their queries.
57
+ * Kept in the app store, dropped whenever a row is created or deleted.
58
+ * @param {core.App} app
59
+ */
60
+ function inUse(app) {
61
+ const known = app.store().get(IN_USE_KEY);
62
+ if (known !== undefined && known !== null) return !!known;
63
+ const any = app.findRecordsByFilter("fed_peers", "", "", 1, 0).length > 0;
64
+ app.store().set(IN_USE_KEY, any);
65
+ return any;
66
+ }
67
+
68
+ /** @param {core.App} app */
69
+ const forgetInUse = (app) => app.store().remove(IN_USE_KEY);
70
+
71
+ /**
72
+ * The host of an origin, lowercased, with its port if it has one: "https://B.example" → "b.example".
73
+ * @param {string} o
74
+ */
75
+ const hostOf = (o) =>
76
+ o
77
+ .replace(/^[a-z]+:\/\//i, "")
78
+ .replace(/\/.*$/, "")
79
+ .toLowerCase();
80
+
81
+ /** This server's host, as global ids end in. Changing the Application URL's host is refused while paired (§33.2). */
82
+ const myHost = () => hostOf(origin());
83
+
84
+ /**
85
+ * A thing's global id (§33.6): its id on the instance it was made on, and that instance's host.
86
+ * @param {string} id
87
+ * @param {string} [host]
88
+ */
89
+ const gid = (id, host = myHost()) => `${id}@${host}`;
90
+
91
+ /**
92
+ * A global id split at its last "@": { id, host }. Null for anything else.
93
+ * @param {unknown} g
94
+ */
95
+ function splitGid(g) {
96
+ if (typeof g !== "string") return null;
97
+ const at = g.lastIndexOf("@");
98
+ if (at < 1 || at === g.length - 1 || g.length > 300) return null;
99
+ const id = g.slice(0, at);
100
+ if (!/^[a-z0-9]{1,64}$/i.test(id)) return null;
101
+ return { id, host: g.slice(at + 1).toLowerCase() };
102
+ }
103
+
104
+ /** Is this global id one of this instance's own? @param {string} g */
105
+ const isMine = (g) => splitGid(g)?.host === myHost();
106
+
107
+ /** A new record id, as PocketBase makes them. */
108
+ const newId = () => $security.randomStringWithAlphabet(15, "abcdefghijklmnopqrstuvwxyz0123456789");
109
+
110
+ /**
111
+ * @param {core.App} app
112
+ * @param {string} id
113
+ */
114
+ function peerById(app, id) {
115
+ if (!id) return null;
116
+ try {
117
+ return app.findRecordById("fed_peers", id);
118
+ } catch {
119
+ return null;
120
+ }
121
+ }
122
+
123
+ /**
124
+ * @param {core.App} app
125
+ * @param {string} o
126
+ */
127
+ function peerByOrigin(app, o) {
128
+ try {
129
+ return app.findFirstRecordByFilter("fed_peers", "origin = {:o}", { o: o.replace(/\/+$/, "") });
130
+ } catch {
131
+ return null;
132
+ }
133
+ }
134
+
135
+ /**
136
+ * The peer whose host this is, or null.
137
+ * @param {core.App} app
138
+ * @param {string} host
139
+ */
140
+ function peerByHost(app, host) {
141
+ for (const p of app.findRecordsByFilter("fed_peers", "", "created", 0, 0)) {
142
+ if (p && hostOf(p.getString("origin")) === host) return p;
143
+ }
144
+ return null;
145
+ }
146
+
147
+ /** @param {core.Record} peer */
148
+ const peerHost = (peer) => hostOf(peer.getString("origin"));
149
+
150
+ /** @param {core.Record | null} peer */
151
+ const isActive = (peer) => !!peer && peer.getString("status") === "active";
152
+
153
+ /**
154
+ * The next queue position: microseconds since 1970, one more than the last at least, so rows queued in the same
155
+ * millisecond keep their order.
156
+ * @param {core.App} app
157
+ */
158
+ function nextSeq(app) {
159
+ let seq = 0;
160
+ app.store().setFunc("fed.seq", (old) => {
161
+ seq = Math.max(Number(old || 0) + 1, Date.now() * 1000);
162
+ return seq;
163
+ });
164
+ return seq;
165
+ }
166
+
167
+ /**
168
+ * Queue an event for a peer (§33.8). It goes in the caller's transaction, so it is sent only if what it tells of is
169
+ * saved. Its id is the queue row's: unique here, which is what the peer drops repeats by.
170
+ * @param {core.App} app
171
+ * @param {string} peerId
172
+ * @param {Record<string, unknown>} event
173
+ */
174
+ function enqueue(app, peerId, event) {
175
+ const row = new Record(app.findCollectionByNameOrId("fed_queue"));
176
+ const id = newId();
177
+ row.set("id", id);
178
+ row.set("peer", peerId);
179
+ row.set("op", "event");
180
+ row.set("seq", nextSeq(app));
181
+ row.set("payload", { ...event, id });
182
+ app.save(row);
183
+ }
184
+
185
+ /**
186
+ * Queue other work for the worker: files ("fetch") or an avatar ("avatar") to fetch from a peer.
187
+ * @param {core.App} app
188
+ * @param {string} peerId
189
+ * @param {"fetch" | "avatar"} op
190
+ * @param {Record<string, unknown>} payload
191
+ */
192
+ function enqueueWork(app, peerId, op, payload) {
193
+ const row = new Record(app.findCollectionByNameOrId("fed_queue"));
194
+ row.set("peer", peerId);
195
+ row.set("op", op);
196
+ row.set("seq", nextSeq(app));
197
+ row.set("payload", payload);
198
+ app.save(row);
199
+ }
200
+
201
+ // ---------------------------------------------------------------- what came from a peer
202
+
203
+ /**
204
+ * Saves made for a peer's event say so here, by record id, while they run: the hooks then don't send the change back
205
+ * where it came from (a mirror's own people's changes go to the home; the home's to every mirror but the sender).
206
+ * In the app store, which every hook sees, whichever JS runtime it runs in.
207
+ * @param {string} id
208
+ */
209
+ const ORIGIN_KEY = (id) => `fed.origin.${id}`;
210
+
211
+ /**
212
+ * Run `fn` with record `id`'s saves marked as coming from `peerId`.
213
+ * @template T
214
+ * @param {core.App} app
215
+ * @param {string} id
216
+ * @param {string} peerId
217
+ * @param {() => T} fn
218
+ * @returns {T}
219
+ */
220
+ function fromPeer(app, id, peerId, fn) {
221
+ app.store().set(ORIGIN_KEY(id), peerId);
222
+ try {
223
+ return fn();
224
+ } finally {
225
+ app.store().remove(ORIGIN_KEY(id));
226
+ }
227
+ }
228
+
229
+ /**
230
+ * The peer a save of record `id` is being made for, "" when it is this instance's own.
231
+ * @param {core.App} app
232
+ * @param {string} id
233
+ */
234
+ const originOf = (app, id) => String(app.store().get(ORIGIN_KEY(id)) || "");
235
+
236
+ /**
237
+ * Read a JSON field as a value ({} or [] when empty or bad).
238
+ * @param {core.Record} rec
239
+ * @param {string} field
240
+ * @param {any} fallback
241
+ */
242
+ function jsonOf(rec, field, fallback) {
243
+ try {
244
+ const v = JSON.parse(rec.getString(field) || "null");
245
+ return v === null || v === undefined ? fallback : v;
246
+ } catch {
247
+ return fallback;
248
+ }
249
+ }
250
+
251
+ module.exports = {
252
+ origin,
253
+ allowPrivate,
254
+ cleanOrigin,
255
+ originProblem,
256
+ enabled,
257
+ requireOn,
258
+ inUse,
259
+ forgetInUse,
260
+ hostOf,
261
+ myHost,
262
+ gid,
263
+ splitGid,
264
+ isMine,
265
+ newId,
266
+ peerById,
267
+ peerByOrigin,
268
+ peerByHost,
269
+ peerHost,
270
+ isActive,
271
+ enqueue,
272
+ enqueueWork,
273
+ fromPeer,
274
+ originOf,
275
+ jsonOf,
276
+ };