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
@@ -0,0 +1,123 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // POST /api/chat/dms (DESIGN.md §16.2): get or create the DM between the caller and another user.
3
+ // Idempotent, so the client calls it every time someone clicks "Message".
4
+
5
+ /**
6
+ * @param {string} message
7
+ * @param {string} [code]
8
+ */
9
+ function userError(message, code = "validation_invalid_value") {
10
+ return new BadRequestError("Failed to open the conversation.", { user: new ValidationError(code, message) });
11
+ }
12
+
13
+ /**
14
+ * @param {core.App} app
15
+ * @param {string} key
16
+ */
17
+ function findByKey(app, key) {
18
+ try {
19
+ return app.findFirstRecordByFilter("rooms", "dm_key = {:key}", { key });
20
+ } catch {
21
+ return null;
22
+ }
23
+ }
24
+
25
+ /**
26
+ * The room as the rooms API returns it to the client (ROOM_FIELDS in web/src/api.ts), with the members
27
+ * expanded to id, name and avatar only (never email).
28
+ * @param {core.App} app
29
+ * @param {core.Record} room
30
+ */
31
+ function shape(app, room) {
32
+ const members = room.getStringSlice("members").map((id) => {
33
+ const u = app.findRecordById("users", id);
34
+ return { id: u.id, name: u.getString("name"), avatar: u.getString("avatar") };
35
+ });
36
+ return {
37
+ id: room.id,
38
+ name: room.getString("name"),
39
+ kind: room.getString("kind"),
40
+ visibility: room.getString("visibility"),
41
+ archived: room.getBool("archived"),
42
+ created_by: room.getString("created_by"),
43
+ members: room.getStringSlice("members"),
44
+ posting: room.getString("posting"),
45
+ writers: room.getStringSlice("writers"),
46
+ last_message_at: room.getString("last_message_at"),
47
+ created: room.getString("created"),
48
+ expand: { members },
49
+ };
50
+ }
51
+
52
+ /**
53
+ * The first of these users who doesn't take direct messages (§16.7), or null.
54
+ * @param {core.App} app
55
+ * @param {string[]} ids
56
+ */
57
+ function noDmsUser(app, ids) {
58
+ for (const id of ids) {
59
+ try {
60
+ const u = app.findRecordById("users", id);
61
+ if (u.getBool("no_dms")) return u;
62
+ } catch {
63
+ // a member deleted meanwhile: the relation drops it
64
+ }
65
+ }
66
+ return null;
67
+ }
68
+
69
+ /**
70
+ * Why `me` can't write in a DM with these members, or "" when they can.
71
+ * @param {core.App} app
72
+ * @param {string} me
73
+ * @param {string[]} members
74
+ */
75
+ function dmRefusal(app, me, members) {
76
+ const u = noDmsUser(app, members);
77
+ if (!u) return "";
78
+ return u.id === me ? "You've turned off direct messages." : `${u.getString("name")} doesn't take direct messages.`;
79
+ }
80
+
81
+ /** @param {core.RequestEvent} e */
82
+ function openDm(e) {
83
+ const me = e.auth;
84
+ if (!me) throw new UnauthorizedError("The request requires a logged-in user.");
85
+ const body = /** @type {Record<string, unknown>} */ (e.requestInfo().body);
86
+ const other = typeof body.user === "string" ? body.user : "";
87
+ if (!other) throw userError("Choose who to message.", "validation_required");
88
+ if (other === me.id) throw userError("You can't message yourself.");
89
+ try {
90
+ e.app.findRecordById("users", other);
91
+ } catch {
92
+ throw userError("There is no such user.");
93
+ }
94
+ const refused = dmRefusal(e.app, me.id, [me.id, other]);
95
+ if (refused) throw userError(refused);
96
+
97
+ const members = [me.id, other].sort();
98
+ const key = members.join(":");
99
+ let room = findByKey(e.app, key);
100
+ if (!room) {
101
+ const created = new Record(e.app.findCollectionByNameOrId("rooms"));
102
+ created.set("kind", "dm");
103
+ created.set("members", members);
104
+ created.set("dm_key", key);
105
+ created.set("created_by", me.id);
106
+ try {
107
+ e.app.save(created);
108
+ room = created;
109
+ } catch (err) {
110
+ // Lost a race with a concurrent call for the same pair: the unique dm_key index kept it to one room.
111
+ room = findByKey(e.app, key);
112
+ if (!room) throw err;
113
+ }
114
+ }
115
+
116
+ // Reopen it for the caller if they had closed it (§16.4).
117
+ const rows = e.app.findRecordsByFilter("hidden_rooms", "user = {:user} && room = {:room}", "", 1, 0, { user: me.id, room: room.id });
118
+ for (const row of rows) if (row) e.app.delete(row);
119
+
120
+ return e.json(200, shape(e.app, room));
121
+ }
122
+
123
+ module.exports = { openDm, dmRefusal };
@@ -0,0 +1,28 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // The emoji a reaction may be (DESIGN.md §20.1): exactly those the picker offers (web/src/lib/emoji.ts, one line per
3
+ // category there). tests/unit/lib/emoji.test.ts fails if the two drift apart.
4
+
5
+ const EMOJI = [
6
+ "😀 😃 😄 😁 😆 😅 🤣 😂 🙂 🙃 😉 😊 😇 🥰 😍 🤩 😘 😗 😚 😙 😋 😛 😜 🤪 😝 🤑 🤗 🤭 🤫 🤔 🤐 🤨 😐 😑 😶 😏 😒 🙄 😬 😌 😔 😪 🤤 😴 😷 🤒 🤕 🤢 🤮 🥵 🥶 🥴 😵 🤯 🤠 🥳 😎 🤓 🧐 😕 😟 🙁 😮 😯 😲 😳 🥺 😦 😧 😨 😰 😥 😢 😭 😱 😖 😣 😞 😓 😩 😫 🥱 😤 😡 😠 🤬 😈 👿 💀 💩 🤡 👻 👽 🤖 😺 😸 😹 😻 😼 😽 🙀 😿 😾 🙈 🙉 🙊",
7
+ "👋 🤚 🖐️ ✋ 🖖 👌 🤏 ✌️ 🤞 🤟 🤘 🤙 👈 👉 👆 👇 ☝️ 👍 👎 ✊ 👊 🤛 🤜 👏 🙌 👐 🤲 🤝 🙏 ✍️ 💅 💪 🧠 👀 👅 👄 👶 🧒 👦 👧 🧑 👨 👩 🧓 👴 👵 🙋 🙇 🤦 🤷 💁 🙆 🙅 🕺 💃 👯 🏃 🚶",
8
+ "🐶 🐱 🐭 🐹 🐰 🦊 🐻 🐼 🐨 🐯 🦁 🐮 🐷 🐸 🐵 🐔 🐧 🐦 🐤 🦆 🦅 🦉 🦇 🐺 🐗 🐴 🦄 🐝 🐛 🦋 🐌 🐞 🐜 🐢 🐍 🦎 🐙 🦑 🦀 🐠 🐟 🐬 🐳 🦈 🐊 🦒 🐘 🦔 🐾 🌵 🎄 🌲 🌳 🌴 🌱 🌿 🍀 🍁 🍂 🍃 🌷 🌹 🌺 🌸 🌼 🌻 🌞 🌝 🌚 🌙 🌎 🪐 ☀️ ⛅ ❄️ ☃️ ⛄ 🌈 🌊 💧 ☔",
9
+ "🍏 🍎 🍐 🍊 🍋 🍌 🍉 🍇 🍓 🍈 🍒 🍑 🥭 🍍 🥥 🥝 🍅 🥑 🍆 🥔 🥕 🌽 🌶️ 🥒 🥦 🧄 🧅 🍄 🥜 🍞 🥐 🥖 🥨 🥯 🥞 🧇 🧀 🍖 🍗 🥩 🥓 🍔 🍟 🍕 🌭 🥪 🌮 🌯 🥗 🍝 🍜 🍲 🍛 🍣 🍱 🥟 🍤 🍙 🍚 🍘 🍥 🍦 🍧 🍨 🍩 🍪 🎂 🍰 🧁 🥧 🍫 🍬 🍭 🍮 🍯 🍼 ☕ 🍵 🧃 🥤 🍶 🍺 🍻 🥂 🍷 🥃 🍸 🍹 🍾 🧊",
10
+ "⚽ 🏀 🏈 ⚾ 🥎 🎾 🏐 🏉 🥏 🎱 🏓 🏸 🏒 🥅 ⛳ 🏹 🎣 🥊 🥋 🎽 🛹 ⛸️ 🎿 🏂 🏆 🥇 🥈 🥉 🏅 🎖️ 🎫 🎪 🎭 🎨 🎬 🎤 🎧 🎼 🎹 🥁 🎷 🎺 🎸 🎻 🎲 ♟️ 🎯 🎳 🎮 🎰 🧩 🎉 🎊 🎈 🎁 🎀 🎃 🎆 🎇 🧨",
11
+ "🚗 🚕 🚙 🚌 🏎️ 🚓 🚑 🚒 🚚 🚜 🛵 🏍️ 🚲 🛴 🚨 🚃 🚄 🚂 ✈️ 🛫 🛬 🚀 🛸 🚁 ⛵ 🚤 🚢 ⚓ 🗺️ 🗽 🗼 🏰 🏯 🏟️ 🎡 🎢 🎠 ⛲ 🏖️ 🏝️ 🏜️ 🌋 ⛰️ 🏔️ 🏕️ 🏠 🏡 🏢 🏥 🏦 🏨 🏫 🏛️ ⛪ 🕌 🌃 🌆 🌇 🌉 🌌",
12
+ "⌚ 📱 💻 ⌨️ 🖥️ 🖨️ 🖱️ 💾 💿 📷 📸 🎥 📞 ☎️ 📺 📻 🎙️ ⏰ ⏳ 🔋 🔌 💡 🔦 🕯️ 💸 💵 💰 💳 💎 ⚖️ 🔧 🔨 🛠️ ⚙️ 🔩 🧲 🧪 🔬 🔭 💊 💉 🧬 🔑 🗝️ 🚪 🛋️ 🛏️ 🧸 ✉️ 📦 📫 📝 📁 📅 📌 📎 ✂️ 🔒 🔓 📚 📖 🔖 🏷️ 📈 📉 📊 🗑️ 🔔 🔕 📣 🕶️ 👓 👑 🎩 👟 👠 👕 👖 💼 🎒 ☂️",
13
+ "❤️ 🧡 💛 💚 💙 💜 🖤 🤍 🤎 💔 ❣️ 💕 💞 💓 💗 💖 💘 💝 💯 💢 💥 💫 💦 💨 💬 💭 💤 ✅ ❌ ❓ ❗ ‼️ ⁉️ ⚠️ 🚫 ⭕ 🔥 ✨ ⭐ 🌟 ⚡ 🎵 🎶 ➕ ➖ ✔️ ☑️ 🆗 🆒 🆕 🆙 🔝 ♻️ ⬆️ ⬇️ ➡️ ⬅️ 🔴 🟠 🟡 🟢 🔵 🟣 ⚫ ⚪ 🏁 🚩 🏳️ 🏴 🏳️‍🌈 🏴‍☠️",
14
+ ].join(" ");
15
+
16
+ /** @type {Set<string> | null} */
17
+ let allowed = null;
18
+
19
+ /**
20
+ * Is `s` one of the picker's emoji?
21
+ * @param {unknown} s
22
+ */
23
+ function isReactionEmoji(s) {
24
+ if (!allowed) allowed = new Set(EMOJI.split(" "));
25
+ return typeof s === "string" && allowed.has(s);
26
+ }
27
+
28
+ module.exports = { EMOJI, isReactionEmoji };
@@ -0,0 +1,75 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // What the messages enrich hook (main.pb.js) needs before it loads lib/messages.js: whether a message needs anything
3
+ // at all, and the list routes' mark on the rooms they checked. No require here: under load PocketBase runs a hook
4
+ // beyond --hooksPool in a JS runtime made for that one call, which loads every module it requires from scratch, and
5
+ // lib/messages.js with what it requires made a room page several times slower (docs/PERF.md).
6
+
7
+ /**
8
+ * The query parameter a list route (lib/lists.js) adds while it enriches its page: the rooms it has checked the caller
9
+ * can see, every listed message being in one of them. The hooks then leave those messages to the route (lib/messages.js
10
+ * showOriginals), and a page costs no query per message. The hooks see a copy of the request's info, but its query is
11
+ * the same map. A client can send the parameter too, so its value starts with a secret of this process.
12
+ */
13
+ const CHECKED = "__chirkle_checked";
14
+ const SECRET_KEY = "enrich.checkedSecret";
15
+
16
+ /** @param {core.App} app */
17
+ const secret = (app) => String(app.store().getOrSet(SECRET_KEY, () => $security.randomString(32)));
18
+
19
+ /**
20
+ * Run `enrich` (a call of $apis.enrichRecords) with the mark that rooms `rooms` were checked.
21
+ * @template T
22
+ * @param {core.RequestEvent} e
23
+ * @param {string[]} rooms
24
+ * @param {() => T} enrich
25
+ * @returns {T}
26
+ */
27
+ function markChecked(e, rooms, enrich) {
28
+ const query = e.requestInfo().query;
29
+ query[CHECKED] = `${secret(e.app)} ${rooms.join(",")}`;
30
+ try {
31
+ return enrich();
32
+ } finally {
33
+ delete query[CHECKED];
34
+ }
35
+ }
36
+
37
+ /**
38
+ * Did a list route check this message's room?
39
+ * @param {core.RecordEnrichEvent} e
40
+ */
41
+ function inCheckedRoom(e) {
42
+ const mark = String(e.requestInfo?.query?.[CHECKED] ?? "");
43
+ if (!mark) return false;
44
+ const s = secret(e.app);
45
+ return (
46
+ mark.startsWith(`${s} `) &&
47
+ mark
48
+ .slice(s.length + 1)
49
+ .split(",")
50
+ .includes(e.record?.getString("room") ?? "")
51
+ );
52
+ }
53
+
54
+ /**
55
+ * Has lib/messages.js anything to do for this message (showOriginal: a forward; keepToRoom: a reply or reactions)?
56
+ * Most messages have neither.
57
+ * @param {core.RecordEnrichEvent} e
58
+ */
59
+ function needsWork(e) {
60
+ const rec = e.record;
61
+ if (!rec || inCheckedRoom(e)) return false;
62
+ if (rec.getString("forward_of") && !rec.getBool("deleted")) return true;
63
+ const reactions = rec.getString("reactions");
64
+ return !!rec.getString("reply_to") || !(reactions === "" || reactions === "[]" || reactions === "null");
65
+ }
66
+
67
+ /**
68
+ * Is anything about this message's author kept to themselves (lib/anonymous.js, DESIGN.md §35), or the author of the
69
+ * message it replies to? Checked for every message, the list routes' too.
70
+ * @param {core.RecordEnrichEvent} e
71
+ */
72
+ const isAnonymous = (e) =>
73
+ !!e.record && (e.record.getBool("anonymous") || e.record.getBool("forwarded_anonymous") || !!e.record.expand()?.reply_to);
74
+
75
+ module.exports = { markChecked, inCheckedRoom, needsWork, isAnonymous };
@@ -0,0 +1,31 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // The optional features that act on the core collections' saves: linked instances (§33, federation/) and the
3
+ // Telegram bridge (§26, telegram/). main.pb.js registers every hook on messages, rooms and users and calls them from
4
+ // there, in one stated order: the federation's part first (it reads a record as it was, before the core's hooks
5
+ // change it), then the core's, then the bridge's; after the save, the other way round. Each feature's own collections
6
+ // (fed_*, tg_*), routes and worker stay in its .pb.js file.
7
+
8
+ /**
9
+ * The federation's modules while this server is linked with any other (federation/config.js `inUse`), else null.
10
+ * @param {core.App} app
11
+ */
12
+ function federation(app) {
13
+ if (!require(`${__hooks}/federation/config.js`).inUse(app)) return null;
14
+ return {
15
+ rooms: require(`${__hooks}/federation/rooms.js`),
16
+ mirror: require(`${__hooks}/federation/mirror.js`),
17
+ people: require(`${__hooks}/federation/people.js`),
18
+ messages: require(`${__hooks}/federation/messages.js`),
19
+ };
20
+ }
21
+
22
+ /** The bridge's modules while it is on (TELEGRAM_BOT_TOKEN), else null. */
23
+ function telegram() {
24
+ if (!$os.getenv("TELEGRAM_BOT_TOKEN").trim()) return null;
25
+ return {
26
+ outbound: require(`${__hooks}/telegram/outbound.js`),
27
+ people: require(`${__hooks}/telegram/people.js`),
28
+ };
29
+ }
30
+
31
+ module.exports = { federation, telegram };
@@ -0,0 +1,375 @@
1
+ /// <reference path="../../types/pocketbase.d.ts" />
2
+ // Shared files (DESIGN.md §37): every attachment and collection item's file is stored once, as a row of `files`
3
+ // (pb_migrations/1760000041_shared_files.js), and messages and collection items name it. Saving to a collection or
4
+ // attaching from one adds a name, never a copy.
5
+ //
6
+ // - A message's `files` and an item's `file` hold stored names, as they did when they were file fields, so clients
7
+ // build the same URLs: /api/files/messages/{message}/{name} and /api/files/collection_items/{item}/{name}. serve()
8
+ // answers those with the shared file (PocketBase's own handler, the path pointed at the `files` row), checking only
9
+ // that the message or item still has it. No file token: whoever has the URL has the file (§37.3).
10
+ // - `refs` counts the messages and items that name a file. link() and unlink() keep it in the same save; a file named
11
+ // by nothing is deleted, and PocketBase deletes what is stored once that is committed.
12
+ // - The media worker (lib/media.js) makes each file's thumbnails and video poster once, whoever names it.
13
+ // - A file from before shared files may not be in its row's folder yet: `src` is where it still is (a message's or an
14
+ // item's old folder), the migration having left the moves to the worker (DESIGN.md §37.5). keyOf and posterKeyOf say
15
+ // where a file is now, and serve() serves such a file from there.
16
+
17
+ const { fieldError } = require(`${__hooks}/lib/records.js`);
18
+ const { clipFileName, tidy, unescapeUploadName } = require(`${__hooks}/lib/text.js`);
19
+
20
+ /** As messages' limits (§17.1): files a message, and bytes a file. */
21
+ const MAX_FILES = 10;
22
+ const MAX_SIZE = 20 * 1024 * 1024;
23
+
24
+ /** As web/src/lib/files.ts says. */
25
+ const IMAGE_EXT = ["jpg", "jpeg", "png", "gif", "webp", "avif"];
26
+ const VIDEO_EXT = ["mp4", "m4v", "webm", "mov", "ogv"];
27
+
28
+ /** @param {string} name */
29
+ const ext = (name) => (name.includes(".") ? name.slice(name.lastIndexOf(".") + 1).toLowerCase() : "");
30
+ /** @param {string} name */
31
+ const isVideo = (name) => VIDEO_EXT.includes(ext(name));
32
+ /** @param {string} name */
33
+ const isImage = (name) => IMAGE_EXT.includes(ext(name));
34
+ /** @param {string} name */
35
+ const isMedia = (name) => isImage(name) || isVideo(name);
36
+
37
+ /** A file's own folder in storage, and where its file, thumbnails and video poster go there. @param {core.Record} row */
38
+ const dirOf = (row) => row.baseFilesPath();
39
+ /** @param {core.Record} row */
40
+ const homeKeyOf = (row) => `${dirOf(row)}/${row.getString("file")}`;
41
+ /** Where a file is now: its old place until the worker has moved it (`src`), then its own folder. @param {core.Record} row */
42
+ const keyOf = (row) => row.getString("src") || homeKeyOf(row);
43
+ /** The folder beside a stored file that has its thumbnails and poster. @param {string} key */
44
+ const thumbsDirOf = (key) => {
45
+ const slash = key.lastIndexOf("/");
46
+ return `${key.slice(0, slash)}/thumbs_${key.slice(slash + 1)}/`;
47
+ };
48
+ /** Where a stored file's thumbnail `size` (or "poster.jpg") is. @param {string} key @param {string} size */
49
+ const thumbKeyOf = (key, size) => `${thumbsDirOf(key)}${size === "poster.jpg" ? size : `${size}_${key.slice(key.lastIndexOf("/") + 1)}`}`;
50
+ /** @param {core.Record} row */
51
+ const posterKeyOf = (row) => thumbKeyOf(keyOf(row), "poster.jpg");
52
+
53
+ /**
54
+ * The `files` row of a stored name, or null.
55
+ * @param {core.App} app
56
+ * @param {string} name
57
+ */
58
+ function byName(app, name) {
59
+ if (!name) return null;
60
+ try {
61
+ return app.findFirstRecordByFilter("files", "file = {:name}", { name });
62
+ } catch {
63
+ return null;
64
+ }
65
+ }
66
+
67
+ /**
68
+ * The `files` rows of these stored names, by name (those that exist).
69
+ * @param {core.App} app
70
+ * @param {string[]} names
71
+ * @returns {Map<string, core.Record>}
72
+ */
73
+ function byNames(app, names) {
74
+ /** @type {Map<string, core.Record>} */
75
+ const out = new Map();
76
+ if (!names.length) return out;
77
+ const rows = app.findAllRecords("files", $dbx.in("file", ...names));
78
+ for (const row of rows) if (row) out.set(row.getString("file"), row);
79
+ return out;
80
+ }
81
+
82
+ /**
83
+ * New `files` rows for uploads, named by nothing yet (link them in the same transaction). Each upload's original name
84
+ * is cleaned like a display name (QA BUG-28, BUG-35), its size held to the field's limit, and an image's to what its
85
+ * thumbnails can decode (QA BUG-24, BUG-140), with its shape kept (§17.5). Errors name `field`, as the clients know.
86
+ * @param {core.App} app
87
+ * @param {filesystem.File[]} uploads
88
+ * @param {string} [field]
89
+ * @returns {core.Record[]}
90
+ */
91
+ function fromUploads(app, uploads, field = "files") {
92
+ const { assertImagesFit } = require(`${__hooks}/lib/images.js`);
93
+ const collection = app.findCollectionByNameOrId("files");
94
+ return uploads.map((upload) => {
95
+ const original = clipFileName(tidy(unescapeUploadName(upload.originalName)));
96
+ upload.originalName = original || upload.name;
97
+ const row = new Record(collection);
98
+ row.set("file", upload);
99
+ const name = upload.name;
100
+ row.set("name", (original || name).slice(0, 200));
101
+ row.set("video", isVideo(name));
102
+ row.set("refs", 0);
103
+ if (upload.size > MAX_SIZE) {
104
+ throw fieldError(field, `Files can be at most ${MAX_SIZE / 1024 / 1024} MB.`, "validation_file_size_limit");
105
+ }
106
+ const dims = assertImagesFit(row, "file", field);
107
+ if (dims[name]) row.set("dims", dims[name]);
108
+ // The worker makes thumbnails of images and a video's poster; its shape it reads once the poster is there.
109
+ row.set("ready", !isMedia(name));
110
+ row.set("sized", !isVideo(name) && (!isImage(name) || !!dims[name]));
111
+ app.save(row);
112
+ return row;
113
+ });
114
+ }
115
+
116
+ /**
117
+ * These rows are named once more (a message or item saved with them, in the same transaction).
118
+ * @param {core.App} app
119
+ * @param {string[]} ids
120
+ */
121
+ function link(app, ids) {
122
+ if (!ids.length) return;
123
+ app
124
+ .db()
125
+ .newQuery("UPDATE files SET refs = refs + 1 WHERE id IN (SELECT value FROM json_each({:ids}))")
126
+ .bind({ ids: JSON.stringify(ids) })
127
+ .execute();
128
+ }
129
+
130
+ /**
131
+ * These stored names are named once less (a message deleted, an item taken out); a file nothing names any more is
132
+ * deleted, and PocketBase deletes what is stored once the transaction is committed. A name twice counts twice.
133
+ * @param {core.App} app
134
+ * @param {string[]} names
135
+ */
136
+ function unlink(app, names) {
137
+ const list = names.filter(Boolean);
138
+ if (!list.length) return;
139
+ for (const name of list) {
140
+ app.db().newQuery("UPDATE files SET refs = refs - 1 WHERE file = {:name}").bind({ name }).execute();
141
+ }
142
+ for (const row of app.findAllRecords("files", $dbx.in("file", ...list), $dbx.exp("refs <= 0"))) {
143
+ if (!row) continue;
144
+ // Not moved yet: what is in its old place goes too, once this is committed (lib/media.js cleanupPass).
145
+ const src = row.getString("src");
146
+ if (src) cleanupLater(app, src);
147
+ app.delete(row);
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Delete what is stored under `prefix` (a record's folder, or a file and its thumbnails), after the transaction this
153
+ * is in commits: the media worker does it (cleanupPass).
154
+ * @param {core.App} app
155
+ * @param {string} prefix
156
+ */
157
+ function cleanupLater(app, prefix) {
158
+ app
159
+ .db()
160
+ .newQuery("INSERT INTO storage_cleanup (id, prefix) VALUES ({:id}, {:prefix})")
161
+ .bind({ id: $security.randomStringWithAlphabet(15, "abcdefghijklmnopqrstuvwxyz0123456789"), prefix })
162
+ .execute();
163
+ }
164
+
165
+ /**
166
+ * The stored names a message or item names as committed (read in the save's transaction, so after any save before it):
167
+ * [] when it is gone, or a message is deleted already. Two deletes of one record at once both load it named; only the
168
+ * first may unlink (QA BUG-223).
169
+ * @param {core.App} app
170
+ * @param {"messages" | "collection_items"} collection
171
+ * @param {string} id
172
+ * @returns {string[]}
173
+ */
174
+ function namedBy(app, collection, id) {
175
+ let rec;
176
+ try {
177
+ rec = app.findRecordById(collection, id);
178
+ } catch {
179
+ return [];
180
+ }
181
+ if (collection === "collection_items") return [rec.getString("file")].filter(Boolean);
182
+ return rec.getBool("deleted") ? [] : rec.getStringSlice("files");
183
+ }
184
+
185
+ /**
186
+ * What a message's attachments are, set on `rec` (about to be created) from `rows` in order (a name once): its
187
+ * `files`, their original names, shapes and, for those attached from collections, which collection (`sources`). The
188
+ * rows are linked. At most MAX_FILES.
189
+ * @param {core.App} app
190
+ * @param {core.Record} rec
191
+ * @param {core.Record[]} rows
192
+ * @param {Record<string, string>} [sources] stored name → collection id
193
+ */
194
+ function setMessageFiles(app, rec, rows, sources = {}) {
195
+ /** @type {core.Record[]} */
196
+ const list = [];
197
+ const seen = new Set();
198
+ for (const row of rows) {
199
+ const name = row.getString("file");
200
+ if (seen.has(name)) continue;
201
+ seen.add(name);
202
+ list.push(row);
203
+ }
204
+ if (list.length > MAX_FILES) throw fieldError("files", `At most ${MAX_FILES} files.`, "validation_too_many_values");
205
+ /** @type {Record<string, string>} */
206
+ const names = {};
207
+ /** @type {Record<string, unknown>} */
208
+ const dims = {};
209
+ /** @type {Record<string, string>} */
210
+ const from = {};
211
+ for (const row of list) {
212
+ const name = row.getString("file");
213
+ names[name] = row.getString("name");
214
+ const shape = parse(row.getString("dims"));
215
+ if (Array.isArray(shape) && shape.length === 2) dims[name] = shape;
216
+ if (sources[name]) from[name] = sources[name];
217
+ }
218
+ rec.set(
219
+ "files",
220
+ list.map((r) => r.getString("file")),
221
+ );
222
+ rec.set("file_names", names);
223
+ rec.set("file_dims", dims);
224
+ rec.set("file_sources", from);
225
+ link(
226
+ app,
227
+ list.map((r) => r.id),
228
+ );
229
+ }
230
+
231
+ /** @param {string} s */
232
+ function parse(s) {
233
+ try {
234
+ return JSON.parse(s);
235
+ } catch {
236
+ return null;
237
+ }
238
+ }
239
+
240
+ /**
241
+ * A message about to be created from uploads (the Telegram bridge, a peer's files): their rows, set on it.
242
+ * @param {core.App} app
243
+ * @param {core.Record} rec
244
+ * @param {filesystem.File[]} uploads
245
+ */
246
+ function attachUploads(app, rec, uploads) {
247
+ setMessageFiles(app, rec, fromUploads(app, uploads));
248
+ }
249
+
250
+ /**
251
+ * Does message `msg` (as stored) show stored name `name`: its own, or as a forward, its original's (§21.3)? Never
252
+ * once deleted.
253
+ * @param {core.App} app
254
+ * @param {core.Record} msg
255
+ * @param {string} name
256
+ */
257
+ function messageShows(app, msg, name) {
258
+ if (msg.getBool("deleted")) return false;
259
+ if (msg.getStringSlice("files").includes(name)) return true;
260
+ const id = msg.getString("forward_of");
261
+ if (!id) return false;
262
+ try {
263
+ const original = app.findRecordById("messages", id);
264
+ return !original.getBool("deleted") && original.getStringSlice("files").includes(name);
265
+ } catch {
266
+ return false;
267
+ }
268
+ }
269
+
270
+ /**
271
+ * The `files` row that `collection`'s record `id` shows as `name` (a message's attachment, a collection item's file),
272
+ * or null when it doesn't show it (any more).
273
+ * @param {core.App} app
274
+ * @param {string} collection "messages" or "collection_items"
275
+ * @param {string} id
276
+ * @param {string} name
277
+ */
278
+ function shownBy(app, collection, id, name) {
279
+ let rec;
280
+ try {
281
+ rec = app.findRecordById(collection, id);
282
+ } catch {
283
+ return null;
284
+ }
285
+ const shows = collection === "messages" ? messageShows(app, rec, name) : rec.getString("file") === name;
286
+ return shows ? byName(app, name) : null;
287
+ }
288
+
289
+ /**
290
+ * GET /api/files/{collection}/{record}/{name} (a router middleware, before PocketBase's own route): a message's or a
291
+ * collection item's file is served from its `files` row, by PocketBase's handler (thumbnails, ranges, the headers that
292
+ * keep it from running as a page), the path pointed at that row. The token clients still send is ignored. 404 when
293
+ * the message or item doesn't show it (deleted, taken out). The `files` rows themselves only through these. True when
294
+ * it has answered (a file not moved yet), false to go on to PocketBase's route.
295
+ * @param {core.RequestEvent} e
296
+ * @returns {boolean}
297
+ */
298
+ function serve(e) {
299
+ const req = e.request;
300
+ if (!req || (req.method !== "GET" && req.method !== "HEAD")) return false;
301
+ const collection = req.pathValue("collection");
302
+ const id = req.pathValue("recordId");
303
+ const name = req.pathValue("filename");
304
+ if (!collection || !id || !name) return false;
305
+ let coll;
306
+ try {
307
+ coll = e.app.findCachedCollectionByNameOrId(collection);
308
+ } catch {
309
+ return false; // PocketBase answers 404
310
+ }
311
+ if (coll.name === "files") throw new NotFoundError();
312
+ if (coll.name !== "messages" && coll.name !== "collection_items") return false;
313
+ const row = shownBy(e.app, coll.name, id, name);
314
+ if (!row) throw new NotFoundError();
315
+ if (row.getString("src")) {
316
+ serveUnmoved(e, row);
317
+ return true;
318
+ }
319
+ req.setPathValue("collection", row.collection().id);
320
+ req.setPathValue("recordId", row.id);
321
+ return false;
322
+ }
323
+
324
+ /**
325
+ * A file not moved to its folder yet, served from its old place (src): a thumbnail asked for if it is there (the old
326
+ * folders have those that were ever asked for), else the file itself. PocketBase's handler would make a missing one,
327
+ * but serves only a file field's own files. As it does, `download` makes it an attachment.
328
+ * @param {core.RequestEvent} e
329
+ * @param {core.Record} row
330
+ */
331
+ function serveUnmoved(e, row) {
332
+ const key = row.getString("src");
333
+ const name = row.getString("file");
334
+ const q = e.request?.url?.query();
335
+ const thumb = q?.get("thumb") ?? "";
336
+ const sizes = /** @type {any} */ (row.collection().fields.getByName("file")).thumbs ?? [];
337
+ const fs = e.app.newFilesystem();
338
+ try {
339
+ let served = key;
340
+ if (thumb && sizes.includes(thumb) && isImage(name) && fs.exists(thumbKeyOf(key, thumb))) served = thumbKeyOf(key, thumb);
341
+ else if (!fs.exists(key)) throw new NotFoundError();
342
+ const download = q?.get("download") ?? "";
343
+ if (download && download !== "0" && download !== "false") {
344
+ e.response.header().set("Content-Disposition", `attachment; filename=${name}`);
345
+ }
346
+ fs.serve(e.response, /** @type {any} */ (e.request), served, name);
347
+ } finally {
348
+ fs.close();
349
+ }
350
+ }
351
+
352
+ module.exports = {
353
+ MAX_FILES,
354
+ isImage,
355
+ isVideo,
356
+ isMedia,
357
+ ext,
358
+ dirOf,
359
+ homeKeyOf,
360
+ keyOf,
361
+ thumbsDirOf,
362
+ thumbKeyOf,
363
+ posterKeyOf,
364
+ cleanupLater,
365
+ byName,
366
+ byNames,
367
+ fromUploads,
368
+ link,
369
+ unlink,
370
+ namedBy,
371
+ setMessageFiles,
372
+ attachUploads,
373
+ shownBy,
374
+ serve,
375
+ };