chirkle 0.0.0-stage → 0.2.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 (139) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +326 -2
  3. package/package.json +76 -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 +129 -0
  44. package/pb_hooks/telegram/inbound.js +553 -0
  45. package/pb_hooks/telegram/links.js +157 -0
  46. package/pb_hooks/telegram/outbound.js +352 -0
  47. package/pb_hooks/telegram/people.js +166 -0
  48. package/pb_hooks/telegram/reactions.js +137 -0
  49. package/pb_hooks/telegram/rich.js +192 -0
  50. package/pb_hooks/telegram/worker.js +182 -0
  51. package/pb_hooks/telegram.pb.js +47 -0
  52. package/pb_migrations/1760000000_init.js +150 -0
  53. package/pb_migrations/1760000001_qa_fixes.js +69 -0
  54. package/pb_migrations/1760000002_avatars.js +39 -0
  55. package/pb_migrations/1760000003_direct_messages.js +142 -0
  56. package/pb_migrations/1760000004_attachments.js +28 -0
  57. package/pb_migrations/1760000005_file_names.js +16 -0
  58. package/pb_migrations/1760000006_room_reads.js +41 -0
  59. package/pb_migrations/1760000007_replies.js +23 -0
  60. package/pb_migrations/1760000008_lowercase_emails.js +24 -0
  61. package/pb_migrations/1760000009_reactions.js +32 -0
  62. package/pb_migrations/1760000010_fit_thumbs.js +18 -0
  63. package/pb_migrations/1760000011_forwarding.js +39 -0
  64. package/pb_migrations/1760000012_accounts.js +55 -0
  65. package/pb_migrations/1760000013_qa_pass5.js +19 -0
  66. package/pb_migrations/1760000014_room_access.js +96 -0
  67. package/pb_migrations/1760000015_site.js +46 -0
  68. package/pb_migrations/1760000016_forward_refs.js +43 -0
  69. package/pb_migrations/1760000017_no_dms.js +18 -0
  70. package/pb_migrations/1760000018_attachment_limits.js +24 -0
  71. package/pb_migrations/1760000019_telegram.js +109 -0
  72. package/pb_migrations/1760000020_service_messages.js +21 -0
  73. package/pb_migrations/1760000021_forward_view_index.js +41 -0
  74. package/pb_migrations/1760000022_link_previews.js +43 -0
  75. package/pb_migrations/1760000023_room_writers.js +49 -0
  76. package/pb_migrations/1760000024_message_search.js +51 -0
  77. package/pb_migrations/1760000025_search_dotted_i.js +16 -0
  78. package/pb_migrations/1760000026_push.js +67 -0
  79. package/pb_migrations/1760000027_push_tokens_per_user.js +31 -0
  80. package/pb_migrations/1760000028_media_grid_thumbs.js +18 -0
  81. package/pb_migrations/1760000029_media.js +71 -0
  82. package/pb_migrations/1760000030_collections.js +140 -0
  83. package/pb_migrations/1760000031_unread_limit.js +20 -0
  84. package/pb_migrations/1760000032_federation.js +227 -0
  85. package/pb_migrations/1760000033_federation_requests.js +44 -0
  86. package/pb_migrations/1760000034_telegram_parts.js +26 -0
  87. package/pb_migrations/1760000035_telegram_anonymous.js +16 -0
  88. package/pb_migrations/1760000036_chirkle.js +20 -0
  89. package/pb_migrations/1760000037_file_dims.js +35 -0
  90. package/pb_migrations/1760000038_drop_push.js +64 -0
  91. package/pb_migrations/1760000039_anonymous_rooms.js +40 -0
  92. package/pb_migrations/1760000040_moderators.js +42 -0
  93. package/pb_migrations/1760000041_shared_files.js +500 -0
  94. package/pb_migrations/1760000042_files_src.js +17 -0
  95. package/pb_migrations/1760000043_telegram_reactions.js +21 -0
  96. package/pb_public/assets/access-ALBW2MT2.js +2 -0
  97. package/pb_public/assets/access-ALBW2MT2.js.map +7 -0
  98. package/pb_public/assets/access-PB77EH4F.css +2 -0
  99. package/pb_public/assets/access-PB77EH4F.css.map +7 -0
  100. package/pb_public/assets/app-A3SXD3FF.css +2 -0
  101. package/pb_public/assets/app-A3SXD3FF.css.map +7 -0
  102. package/pb_public/assets/app-NDSIQW4L.js +3 -0
  103. package/pb_public/assets/app-NDSIQW4L.js.map +7 -0
  104. package/pb_public/assets/collections-DHJEOLHW.css +2 -0
  105. package/pb_public/assets/collections-DHJEOLHW.css.map +7 -0
  106. package/pb_public/assets/emoji-WSTVXAW5.css +2 -0
  107. package/pb_public/assets/emoji-WSTVXAW5.css.map +7 -0
  108. package/pb_public/assets/emoji-picker-QYRX6NYL.js +609 -0
  109. package/pb_public/assets/emoji-picker-QYRX6NYL.js.map +7 -0
  110. package/pb_public/assets/inter-cyrillic-JEOLYBOO.woff2 +0 -0
  111. package/pb_public/assets/inter-cyrillic-ext-IYF56FF6.woff2 +0 -0
  112. package/pb_public/assets/inter-greek-IRE366VL.woff2 +0 -0
  113. package/pb_public/assets/inter-latin-NRMW37G5.woff2 +0 -0
  114. package/pb_public/assets/inter-latin-ext-HA22NDSG.woff2 +0 -0
  115. package/pb_public/assets/lazy-4CXRBHHM.js +2 -0
  116. package/pb_public/assets/lazy-4CXRBHHM.js.map +7 -0
  117. package/pb_public/assets/media-7TCBG7WM.css +2 -0
  118. package/pb_public/assets/media-7TCBG7WM.css.map +7 -0
  119. package/pb_public/assets/media-FPRU2QH5.js +2 -0
  120. package/pb_public/assets/media-FPRU2QH5.js.map +7 -0
  121. package/pb_public/assets/notify-L6GERFNO.js +2 -0
  122. package/pb_public/assets/notify-L6GERFNO.js.map +7 -0
  123. package/pb_public/assets/search-3UT4HMES.js +2 -0
  124. package/pb_public/assets/search-3UT4HMES.js.map +7 -0
  125. package/pb_public/assets/switcher-CEUKRLEY.js +2 -0
  126. package/pb_public/assets/switcher-CEUKRLEY.js.map +7 -0
  127. package/pb_public/assets/viewer-DXT7SKOU.js +2 -0
  128. package/pb_public/assets/viewer-DXT7SKOU.js.map +7 -0
  129. package/pb_public/assets/viewer-P7GYCBYM.css +2 -0
  130. package/pb_public/assets/viewer-P7GYCBYM.css.map +7 -0
  131. package/pb_public/icons/apple-touch-icon.png +0 -0
  132. package/pb_public/icons/icon-192.png +0 -0
  133. package/pb_public/icons/icon-512.png +0 -0
  134. package/pb_public/icons/icon.svg +1 -0
  135. package/pb_public/icons/maskable-512.png +0 -0
  136. package/pb_public/index.html +21 -0
  137. package/pb_public/sw.js +1 -0
  138. package/scripts/fetch-pocketbase.sh +63 -0
  139. package/scripts/start.mjs +93 -0
@@ -0,0 +1,55 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Accounts (DESIGN.md §22):
3
+ // - users.name_key: display names are unique, compared like room names ("Ada" = "ADA" = "Ada​"), set by pb_hooks.
4
+ // - a rate limit for POST /api/chat/password (changing your password, which checks the current one).
5
+
6
+ const ACCOUNT_LIMITS = [{ label: "POST /api/chat/password", audience: "", duration: 60, maxRequests: 5 }];
7
+ const ACCOUNT_LABELS = ACCOUNT_LIMITS.map((r) => r.label);
8
+
9
+ /**
10
+ * Same as nameKey() in pb_hooks/lib/text.js (migrations can't load the hooks' modules).
11
+ * @param {string} name
12
+ */
13
+ function nameKey(name) {
14
+ const s = name.replace(/[­᠎​-‏‪-‮⁠-⁤⁦-⁩]/g, "");
15
+ return (typeof s.normalize === "function" ? s.normalize("NFKC") : s).toUpperCase().toLowerCase();
16
+ }
17
+
18
+ migrate(
19
+ (app) => {
20
+ const users = app.findCollectionByNameOrId("users");
21
+ users.fields.add(new TextField({ name: "name_key", hidden: true, max: 400 }));
22
+ app.save(users);
23
+
24
+ // Backfill with raw SQL (no hooks). Names that already clash keep a key made unique by their id; they may keep
25
+ // their name, but nobody can take it any more.
26
+ const seen = new Set();
27
+ for (const u of app.findAllRecords("users")) {
28
+ if (!u) continue;
29
+ let key = nameKey(u.getString("name"));
30
+ if (key === "") continue;
31
+ if (seen.has(key)) key = `${key}#${u.id}`;
32
+ seen.add(key);
33
+ app.db().newQuery("UPDATE users SET name_key = {:key} WHERE id = {:id}").bind({ key, id: u.id }).execute();
34
+ }
35
+
36
+ const withIndex = app.findCollectionByNameOrId("users");
37
+ withIndex.addIndex("idx_users_name_key", true, "`name_key`", "`name_key` != ''");
38
+ app.save(withIndex);
39
+
40
+ const settings = app.settings();
41
+ const rest = settings.rateLimits.rules.filter((r) => !ACCOUNT_LABELS.includes(r.label));
42
+ settings.rateLimits.rules = [.../** @type {any[]} */ (ACCOUNT_LIMITS), ...rest];
43
+ app.save(settings);
44
+ },
45
+ (app) => {
46
+ const users = app.findCollectionByNameOrId("users");
47
+ users.removeIndex("idx_users_name_key");
48
+ users.fields.removeByName("name_key");
49
+ app.save(users);
50
+
51
+ const settings = app.settings();
52
+ settings.rateLimits.rules = settings.rateLimits.rules.filter((r) => !ACCOUNT_LABELS.includes(r.label));
53
+ app.save(settings);
54
+ },
55
+ );
@@ -0,0 +1,19 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Fixes from the fifth QA pass (docs/QA.md):
3
+ // - BUG-53: a password only changes through POST /api/chat/password (§22.2), which is rate limited and checks the new
4
+ // one. PocketBase's own users update also accepted { oldPassword, password, passwordConfirm }, at the generic limit.
5
+
6
+ const NO_PASSWORD = "@request.body.password:isset = false && @request.body.passwordConfirm:isset = false";
7
+
8
+ migrate(
9
+ (app) => {
10
+ const users = app.findCollectionByNameOrId("users");
11
+ users.updateRule = `${users.updateRule} && ${NO_PASSWORD}`;
12
+ app.save(users);
13
+ },
14
+ (app) => {
15
+ const users = app.findCollectionByNameOrId("users");
16
+ users.updateRule = (users.updateRule ?? "").replace(` && ${NO_PASSWORD}`, "");
17
+ app.save(users);
18
+ },
19
+ );
@@ -0,0 +1,96 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Room access (DESIGN.md §23): a room's creator chooses who can see it.
3
+ // - `rooms.visibility`: "private" (only its members: the people the creator added, and the creator), "public" (every
4
+ // signed-in user, as before) or "open" (Open Air: also readable without an account, while it isn't archived). DMs
5
+ // are "private" to their two members. Existing rooms are backfilled.
6
+ // - `rooms.members` holds a private room's members (up to ROOM_MAX_MEMBERS); only the creator changes them, through the
7
+ // rooms API. The hooks keep it empty for other rooms and always list the creator in a private one.
8
+ // - Guests (no session) can list and read Open Air rooms, their messages and their attachments, and see the profile
9
+ // (name, avatar) of a user whose id they have, so messages show their authors. They can't write anything.
10
+ // - Writing in a room (a message, an edit, hiding it) needs the same access as seeing it, signed in.
11
+
12
+ const AUTHED = '@request.auth.id != ""';
13
+ const ROOM_MAX_MEMBERS = 100;
14
+
15
+ /** Signed in, and the room in `rel` is public or open, or the caller is one of its members (or its creator). */
16
+ const IS_MEMBER = (/** @type {string} */ rel) =>
17
+ `(${AUTHED} && (${rel}visibility != "private" || ${rel}members.id ?= @request.auth.id || ${rel}created_by = @request.auth.id))`;
18
+ /** MEMBER, or the room in `rel` is Open Air (and not archived): anyone can read it. */
19
+ const CAN_SEE = (/** @type {string} */ rel) => `((${rel}visibility = "open" && ${rel}archived = false) || ${IS_MEMBER(rel)})`;
20
+
21
+ /** The visibility conditions of 1760000003_direct_messages.js, replaced in place (later migrations appended to the rules). */
22
+ const OLD_VISIBLE = (/** @type {string} */ rel) => `(${rel}kind = "public" || ${rel}members.id ?= @request.auth.id)`;
23
+ const OLD_SEE = (/** @type {string} */ rel) => `${AUTHED} && ${OLD_VISIBLE(rel)}`;
24
+
25
+ /** @typedef {Parameters<Parameters<typeof migrate>[0]>[0]} AccessMigrationApp */
26
+
27
+ /**
28
+ * Replace `from` by `to` in `rule`, which must contain it (a rule changed by hand would otherwise lose its guard).
29
+ * @param {string | null | undefined} rule
30
+ * @param {string} from
31
+ * @param {string} to
32
+ */
33
+ function swap(rule, from, to) {
34
+ const r = rule ?? "";
35
+ if (!r.includes(from)) throw new Error(`room access migration: expected ${from} in ${r}`);
36
+ return r.replace(from, to);
37
+ }
38
+
39
+ /**
40
+ * @param {AccessMigrationApp} app
41
+ * @param {boolean} up
42
+ */
43
+ function setRules(app, up) {
44
+ const see = (/** @type {string} */ rel) => (up ? CAN_SEE(rel) : OLD_SEE(rel));
45
+ const rooms = app.findCollectionByNameOrId("rooms");
46
+ rooms.listRule = see("");
47
+ rooms.viewRule = see("");
48
+ // A room's creator may now set its members (§23.2): the hooks check them.
49
+ const MEMBERS_FIXED = " && @request.body.members:isset = false";
50
+ rooms.updateRule = up ? swap(rooms.updateRule, MEMBERS_FIXED, "") : `${rooms.updateRule}${MEMBERS_FIXED}`;
51
+ app.save(rooms);
52
+
53
+ const messages = app.findCollectionByNameOrId("messages");
54
+ messages.listRule = see("room.");
55
+ messages.viewRule = see("room.");
56
+ messages.createRule = up
57
+ ? swap(messages.createRule, OLD_VISIBLE("@request.body.room."), IS_MEMBER("@request.body.room."))
58
+ : swap(messages.createRule, IS_MEMBER("@request.body.room."), OLD_VISIBLE("@request.body.room."));
59
+ // Someone taken out of a private room can't edit (or delete) what they wrote there any more: they can't see it.
60
+ const STILL_MEMBER = ` && ${IS_MEMBER("room.")}`;
61
+ messages.updateRule = up ? `${messages.updateRule}${STILL_MEMBER}` : swap(messages.updateRule, STILL_MEMBER, "");
62
+ app.save(messages);
63
+
64
+ const hidden = app.findCollectionByNameOrId("hidden_rooms");
65
+ hidden.createRule = up
66
+ ? swap(hidden.createRule, OLD_VISIBLE("@request.body.room."), IS_MEMBER("@request.body.room."))
67
+ : swap(hidden.createRule, IS_MEMBER("@request.body.room."), OLD_VISIBLE("@request.body.room."));
68
+ app.save(hidden);
69
+
70
+ // Guests see who wrote a message (expand=author needs the users view rule). Listing (and so searching) users still
71
+ // needs a session: nobody can enumerate the accounts.
72
+ const users = app.findCollectionByNameOrId("users");
73
+ users.viewRule = up ? "" : AUTHED;
74
+ app.save(users);
75
+ }
76
+
77
+ migrate(
78
+ (app) => {
79
+ const rooms = app.findCollectionByNameOrId("rooms");
80
+ rooms.fields.add(new SelectField({ name: "visibility", required: true, maxSelect: 1, values: ["public", "private", "open"] }));
81
+ /** @type {any} */ (rooms.fields.getByName("members")).maxSelect = ROOM_MAX_MEMBERS;
82
+ app.save(rooms);
83
+ app.db().newQuery("UPDATE rooms SET visibility = CASE WHEN kind = 'dm' THEN 'private' ELSE 'public' END").execute();
84
+ setRules(app, true);
85
+ },
86
+ (app) => {
87
+ setRules(app, false);
88
+ // Private rooms would otherwise become visible to everyone: they are deleted with their messages first if that
89
+ // matters. Members beyond a DM's two are dropped.
90
+ app.db().newQuery("UPDATE rooms SET members = '[]' WHERE kind != 'dm'").execute();
91
+ const rooms = app.findCollectionByNameOrId("rooms");
92
+ rooms.fields.removeByName("visibility");
93
+ /** @type {any} */ (rooms.fields.getByName("members")).maxSelect = 2;
94
+ app.save(rooms);
95
+ },
96
+ );
@@ -0,0 +1,46 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Site settings (DESIGN.md §24): one `site` record, edited by a superuser in the admin UI (Collections → site).
3
+ // - `title` and `logo`: the branding shown in the header, on the login page and in the tab's title.
4
+ // - `invite_only` + `invite_code`: signups need the code (pb_hooks/lib/site.js). Invite-only without a code closes
5
+ // signups. The code is hidden: only superusers see it.
6
+ // Anyone can read the record (guests see the branding and whether signing up needs a code); nobody else can change it.
7
+
8
+ /** @param {Record<string, unknown>} data */
9
+ const siteCollection = (data) => new Collection(/** @type {any} */ (data));
10
+
11
+ migrate(
12
+ (app) => {
13
+ const site = siteCollection({
14
+ type: "base",
15
+ name: "site",
16
+ listRule: "",
17
+ viewRule: "",
18
+ createRule: null,
19
+ updateRule: null,
20
+ deleteRule: null,
21
+ fields: [
22
+ { type: "text", name: "title", required: true, min: 1, max: 48 },
23
+ {
24
+ type: "file",
25
+ name: "logo",
26
+ maxSelect: 1,
27
+ maxSize: 1024 * 1024,
28
+ mimeTypes: ["image/svg+xml", "image/png", "image/jpeg", "image/webp", "image/gif"],
29
+ protected: false,
30
+ },
31
+ { type: "bool", name: "invite_only" },
32
+ { type: "text", name: "invite_code", hidden: true, max: 100 },
33
+ { type: "autodate", name: "created", onCreate: true, onUpdate: false },
34
+ { type: "autodate", name: "updated", onCreate: true, onUpdate: true },
35
+ ],
36
+ });
37
+ app.save(site);
38
+
39
+ const rec = new Record(site);
40
+ rec.set("title", "Chat");
41
+ app.save(rec);
42
+ },
43
+ (app) => {
44
+ app.delete(app.findCollectionByNameOrId("site"));
45
+ },
46
+ );
@@ -0,0 +1,43 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Forwards point at the original instead of copying it (DESIGN.md §21.3). `messages.forward_of` is the message a
3
+ // forward shows: its text and attachments are the original's as they are now (an edit shows in every forward, a delete
4
+ // empties them), and nothing is copied, so forwarding can't multiply what is stored. Only POST /api/chat/forward
5
+ // (pb_hooks) sets it; clients can't set or change it.
6
+ // - Whoever can see a forward that isn't deleted can view the message it points at, and that message's attachments:
7
+ // the view rule grants it. Nothing else of the original's room: the list rule, which lists a room's messages and
8
+ // feeds their realtime events, is unchanged.
9
+ // - Forwards made before this keep their copies. Going down loses what forwards made since show: they hold nothing.
10
+
11
+ const NO_FORWARD_OF = "@request.body.forward_of:isset = false";
12
+ /** Another message of the collection, joined once so every condition below is about the same one. */
13
+ const F = "@collection.messages:fwd.";
14
+
15
+ /**
16
+ * A forward of this message that isn't deleted is in a room the caller can see (CAN_SEE of 1760000014_room_access.js,
17
+ * with the "any of" operators that @collection joins need).
18
+ */
19
+ const VIA_FORWARD =
20
+ `(${F}forward_of ?= id && ${F}deleted ?= false && ` +
21
+ `((${F}room.visibility ?= "open" && ${F}room.archived ?= false) || ` +
22
+ `(@request.auth.id != "" && (${F}room.visibility ?!= "private" || ${F}room.members.id ?= @request.auth.id || ${F}room.created_by ?= @request.auth.id))))`;
23
+
24
+ migrate(
25
+ (app) => {
26
+ const messages = app.findCollectionByNameOrId("messages");
27
+ messages.fields.add(
28
+ new RelationField(/** @type {any} */ ({ name: "forward_of", maxSelect: 1, collectionId: messages.id, cascadeDelete: false })),
29
+ );
30
+ messages.viewRule = `(${messages.listRule}) || ${VIA_FORWARD}`;
31
+ messages.createRule = `${messages.createRule} && ${NO_FORWARD_OF}`;
32
+ messages.updateRule = `${messages.updateRule} && ${NO_FORWARD_OF}`;
33
+ app.save(messages);
34
+ },
35
+ (app) => {
36
+ const messages = app.findCollectionByNameOrId("messages");
37
+ messages.fields.removeByName("forward_of");
38
+ messages.viewRule = messages.listRule;
39
+ messages.createRule = (messages.createRule ?? "").replace(` && ${NO_FORWARD_OF}`, "");
40
+ messages.updateRule = (messages.updateRule ?? "").replace(` && ${NO_FORWARD_OF}`, "");
41
+ app.save(messages);
42
+ },
43
+ );
@@ -0,0 +1,18 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // "Doesn't take direct messages" (DESIGN.md §16.7): `users.no_dms`. Nobody can open a DM with such a user, they can't
3
+ // open one either, and messages in a DM they are in are refused (pb_hooks/lib/dms.js, lib/messages.js). Off by
4
+ // default, so existing and new accounts are unchanged. Set for the Telegram bridge's stand-in users; a user may set it
5
+ // on their own record (the update rule allows it), which the profile may offer later.
6
+
7
+ migrate(
8
+ (app) => {
9
+ const users = app.findCollectionByNameOrId("users");
10
+ users.fields.add(new BoolField(/** @type {any} */ ({ name: "no_dms" })));
11
+ app.save(users);
12
+ },
13
+ (app) => {
14
+ const users = app.findCollectionByNameOrId("users");
15
+ users.fields.removeByName("no_dms");
16
+ app.save(users);
17
+ },
18
+ );
@@ -0,0 +1,24 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Bigger attachments (DESIGN.md §17.1): up to 10 files per message, 20 MB each, as many and as large as a Telegram
3
+ // album the bridge (§26) brings over. The request body limit grows with them (pb_hooks/lib/http.js MESSAGE_BODY_LIMIT).
4
+ // Going down keeps the files already stored: PocketBase checks the limits on uploads only.
5
+
6
+ /** @typedef {Parameters<Parameters<typeof migrate>[0]>[0]} MigrationApp */
7
+
8
+ /**
9
+ * @param {MigrationApp} app
10
+ * @param {number} maxSelect
11
+ * @param {number} maxSize
12
+ */
13
+ function setLimits(app, maxSelect, maxSize) {
14
+ const messages = app.findCollectionByNameOrId("messages");
15
+ const files = /** @type {core.FileField} */ (messages.fields.getByName("files"));
16
+ files.maxSelect = maxSelect;
17
+ files.maxSize = maxSize;
18
+ app.save(messages);
19
+ }
20
+
21
+ migrate(
22
+ (app) => setLimits(app, 10, 20 * 1024 * 1024),
23
+ (app) => setLimits(app, 4, 8 * 1024 * 1024),
24
+ );
@@ -0,0 +1,109 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Telegram bridge (DESIGN.md §26, pb_hooks/telegram.pb.js): its own collections, all named tg_*, readable and writable by
3
+ // superusers only (null rules). Nothing outside the bridge reads them, so removing the bridge can leave them, or go down
4
+ // this migration to drop them.
5
+ // - tg_links: a Telegram group and the room it is linked to. The bridge adds a row (no room, disabled) for every group
6
+ // it is added to; a superuser picks the room and enables it in the admin UI.
7
+ // - tg_people: a Telegram sender and the stand-in user ("Ann (TG)") whose name their messages show under.
8
+ // - tg_messages: which Telegram messages a chat message is, both ways, for replies, edits and deletes.
9
+ // - tg_queue: work for the bridge's worker: messages to send to Telegram, edits and deletes to pass on, and the items
10
+ // of a Telegram album waiting for the rest of it.
11
+
12
+ /** @param {Record<string, unknown>} data */
13
+ const tgCollection = (data) =>
14
+ new Collection(
15
+ /** @type {any} */ ({ type: "base", listRule: null, viewRule: null, createRule: null, updateRule: null, deleteRule: null, ...data }),
16
+ );
17
+
18
+ const NAMES = ["tg_queue", "tg_messages", "tg_people", "tg_links"];
19
+
20
+ migrate(
21
+ (app) => {
22
+ const rooms = app.findCollectionByNameOrId("rooms");
23
+ const users = app.findCollectionByNameOrId("users");
24
+ const messages = app.findCollectionByNameOrId("messages");
25
+ const stamps = [
26
+ { type: "autodate", name: "created", onCreate: true, onUpdate: false },
27
+ { type: "autodate", name: "updated", onCreate: true, onUpdate: true },
28
+ ];
29
+
30
+ app.save(
31
+ tgCollection({
32
+ name: "tg_links",
33
+ fields: [
34
+ { type: "text", name: "chat_id", required: true, max: 32 },
35
+ { type: "text", name: "title", max: 255 },
36
+ { type: "relation", name: "room", maxSelect: 1, collectionId: rooms.id, cascadeDelete: true },
37
+ { type: "bool", name: "enabled" },
38
+ ...stamps,
39
+ ],
40
+ indexes: ["CREATE UNIQUE INDEX idx_tg_links_chat ON tg_links (chat_id)", "CREATE INDEX idx_tg_links_room ON tg_links (room)"],
41
+ }),
42
+ );
43
+
44
+ app.save(
45
+ tgCollection({
46
+ name: "tg_people",
47
+ fields: [
48
+ { type: "text", name: "tg_user_id", required: true, max: 32 },
49
+ { type: "relation", name: "user", required: true, maxSelect: 1, collectionId: users.id, cascadeDelete: true },
50
+ { type: "text", name: "name", max: 255 },
51
+ { type: "text", name: "username", max: 64 },
52
+ { type: "text", name: "photo", max: 255 },
53
+ { type: "date", name: "photo_checked" },
54
+ ...stamps,
55
+ ],
56
+ indexes: [
57
+ "CREATE UNIQUE INDEX idx_tg_people_tg_user ON tg_people (tg_user_id)",
58
+ "CREATE UNIQUE INDEX idx_tg_people_user ON tg_people (user)",
59
+ ],
60
+ }),
61
+ );
62
+
63
+ app.save(
64
+ tgCollection({
65
+ name: "tg_messages",
66
+ fields: [
67
+ { type: "relation", name: "message", required: true, maxSelect: 1, collectionId: messages.id, cascadeDelete: true },
68
+ { type: "text", name: "chat_id", required: true, max: 32 },
69
+ { type: "number", name: "tg_message_id", required: true, onlyInt: true },
70
+ { type: "select", name: "direction", required: true, maxSelect: 1, values: ["in", "out"] },
71
+ // Which Telegram message holds the text: "text" (a message) or "caption" (a file's); "media" holds none.
72
+ { type: "select", name: "kind", required: true, maxSelect: 1, values: ["text", "caption", "media"] },
73
+ ...stamps,
74
+ ],
75
+ indexes: [
76
+ "CREATE UNIQUE INDEX idx_tg_messages_tg ON tg_messages (chat_id, tg_message_id)",
77
+ "CREATE INDEX idx_tg_messages_message ON tg_messages (message)",
78
+ ],
79
+ }),
80
+ );
81
+
82
+ app.save(
83
+ tgCollection({
84
+ name: "tg_queue",
85
+ fields: [
86
+ { type: "select", name: "op", required: true, maxSelect: 1, values: ["send", "edit", "delete", "album"] },
87
+ // send, edit, delete: the chat message.
88
+ { type: "text", name: "message", max: 15 },
89
+ { type: "text", name: "chat_id", max: 32 },
90
+ // album: the media_group_id, and the Telegram message itself.
91
+ { type: "text", name: "album", max: 64 },
92
+ { type: "json", name: "payload", maxSize: 65536 },
93
+ { type: "number", name: "tries", onlyInt: true },
94
+ { type: "date", name: "next_at" },
95
+ { type: "date", name: "locked_until" },
96
+ { type: "text", name: "error", max: 1000 },
97
+ ...stamps,
98
+ ],
99
+ indexes: [
100
+ "CREATE INDEX idx_tg_queue_created ON tg_queue (created)",
101
+ "CREATE INDEX idx_tg_queue_album ON tg_queue (chat_id, album)",
102
+ ],
103
+ }),
104
+ );
105
+ },
106
+ (app) => {
107
+ for (const name of NAMES) app.delete(app.findCollectionByNameOrId(name));
108
+ },
109
+ );
@@ -0,0 +1,21 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Service messages (DESIGN.md §5.3): a message without an author is the app's own notice in a room ("Telegram group
3
+ // … was disconnected"), made only by server code (lib/messages.js postService). The create rule still requires
4
+ // `author = @request.auth.id` and a signed-in caller, so no request can make one, and no update rule matches one.
5
+ // Deleting a user would now clear `author` on their messages rather than fail: a users delete hook
6
+ // (lib/messages.js beforeUserDelete) refuses it while they have any, as the required relation did.
7
+ // Going down drops them, since `author` is required again.
8
+
9
+ migrate(
10
+ (app) => {
11
+ const messages = app.findCollectionByNameOrId("messages");
12
+ /** @type {any} */ (messages.fields.getByName("author")).required = false;
13
+ app.save(messages);
14
+ },
15
+ (app) => {
16
+ for (const rec of app.findRecordsByFilter("messages", "author = ''", "", 0, 0)) if (rec) app.delete(rec);
17
+ const messages = app.findCollectionByNameOrId("messages");
18
+ /** @type {any} */ (messages.fields.getByName("author")).required = true;
19
+ app.save(messages);
20
+ },
21
+ );
@@ -0,0 +1,41 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // The messages view rule's forward condition (1760000016_forward_refs.js) as a back-relation, with an index on
3
+ // `forward_of`. PocketBase joins `@collection.messages:fwd` without a condition: every expanded message (a page's
4
+ // reply_to) was checked against every message there is, times their rooms' members, and a page with replies took
5
+ // ~20 s on a busy instance. `messages_via_forward_of` joins on `forward_of = id`, which the index finds at once. Same
6
+ // meaning: the "any of" operators all test the same joined forward, as with the alias.
7
+
8
+ const OLD = "@collection.messages:fwd.";
9
+ const NEW = "messages_via_forward_of.";
10
+ const INDEX = "CREATE INDEX `idx_messages_forward_of` ON `messages` (`forward_of`)";
11
+ /** The alias form's link to this message: the back-relation's join says it. */
12
+ const OLD_LINK = `${OLD}forward_of ?= id && `;
13
+ const NEW_LINK = `${NEW}id ?!= "" && `;
14
+
15
+ /**
16
+ * @param {string | null | undefined} rule
17
+ * @param {boolean} up
18
+ */
19
+ function rewrite(rule, up) {
20
+ const [fromLink, toLink, from, to] = up ? [OLD_LINK, NEW_LINK, OLD, NEW] : [NEW_LINK, OLD_LINK, NEW, OLD];
21
+ const r = rule ?? "";
22
+ if (!r.includes(fromLink)) throw new Error(`forward view migration: expected ${fromLink} in ${r}`);
23
+ return r.replace(fromLink, toLink).split(from).join(to);
24
+ }
25
+
26
+ /**
27
+ * @param {Parameters<Parameters<typeof migrate>[0]>[0]} app
28
+ * @param {boolean} up
29
+ */
30
+ function apply(app, up) {
31
+ const messages = app.findCollectionByNameOrId("messages");
32
+ messages.viewRule = rewrite(messages.viewRule, up);
33
+ const indexes = /** @type {string[]} */ (/** @type {any} */ (messages).indexes).filter((i) => i !== INDEX);
34
+ /** @type {any} */ (messages).indexes = up ? [...indexes, INDEX] : indexes;
35
+ app.save(messages);
36
+ }
37
+
38
+ migrate(
39
+ (app) => apply(app, true),
40
+ (app) => apply(app, false),
41
+ );
@@ -0,0 +1,43 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Link previews (DESIGN.md §28): what the links in a message show under it, a favicon and a title each.
3
+ // - messages.previews: [{ url, title, icon }], set by the server only (pb_hooks/lib/previews.js); icon is a data: URL.
4
+ // - link_queue: messages whose links the previews worker is still to look at. No API access.
5
+
6
+ const NO_PREVIEWS = "@request.body.previews:isset = false";
7
+
8
+ migrate(
9
+ (app) => {
10
+ const messages = app.findCollectionByNameOrId("messages");
11
+ messages.fields.add(new JSONField(/** @type {any} */ ({ name: "previews", maxSize: 131072 })));
12
+ messages.createRule = `${messages.createRule} && ${NO_PREVIEWS}`;
13
+ messages.updateRule = `${messages.updateRule} && ${NO_PREVIEWS}`;
14
+ app.save(messages);
15
+
16
+ app.save(
17
+ new Collection(
18
+ /** @type {any} */ ({
19
+ type: "base",
20
+ name: "link_queue",
21
+ listRule: null,
22
+ viewRule: null,
23
+ createRule: null,
24
+ updateRule: null,
25
+ deleteRule: null,
26
+ fields: [
27
+ { type: "relation", name: "message", required: true, maxSelect: 1, collectionId: messages.id, cascadeDelete: true },
28
+ { type: "autodate", name: "created", onCreate: true, onUpdate: false },
29
+ ],
30
+ indexes: ["CREATE INDEX idx_link_queue_created ON link_queue (created)"],
31
+ }),
32
+ ),
33
+ );
34
+ },
35
+ (app) => {
36
+ app.delete(app.findCollectionByNameOrId("link_queue"));
37
+ const messages = app.findCollectionByNameOrId("messages");
38
+ messages.fields.removeByName("previews");
39
+ messages.createRule = (messages.createRule ?? "").replace(` && ${NO_PREVIEWS}`, "");
40
+ messages.updateRule = (messages.updateRule ?? "").replace(` && ${NO_PREVIEWS}`, "");
41
+ app.save(messages);
42
+ },
43
+ );
@@ -0,0 +1,49 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Who can post in a room (DESIGN.md §23.6): everyone who can read it, or only the people its creator chose.
3
+ // - `rooms.posting`: "everyone" (the default, and every room from before) or "selected". DMs are always "everyone".
4
+ // - `rooms.writers`: who may post when "selected" (up to ROOM_MAX_WRITERS); only the creator changes it. The hooks keep
5
+ // it empty otherwise, always list the creator, and in a private room keep only its members.
6
+ // - Posting, editing and deleting a message need it on top of seeing the room. Reacting doesn't: readers may react.
7
+
8
+ const ROOM_MAX_WRITERS = 100;
9
+
10
+ /** The caller may post in the room in `rel` (seeing it is checked apart). */
11
+ const WRITER = (/** @type {string} */ rel) =>
12
+ `(${rel}posting != "selected" || ${rel}writers.id ?= @request.auth.id || ${rel}created_by = @request.auth.id)`;
13
+
14
+ const WRITERS_UNSET = "@request.body.writers:isset = false";
15
+
16
+ migrate(
17
+ (app) => {
18
+ const users = app.findCollectionByNameOrId("users");
19
+ const rooms = app.findCollectionByNameOrId("rooms");
20
+ rooms.fields.add(new SelectField({ name: "posting", required: true, maxSelect: 1, values: ["everyone", "selected"] }));
21
+ rooms.fields.add(
22
+ new RelationField(
23
+ /** @type {any} */ ({ name: "writers", maxSelect: ROOM_MAX_WRITERS, collectionId: users.id, cascadeDelete: false }),
24
+ ),
25
+ );
26
+ // A room starts with everyone posting, or only its creator: nobody else is chosen yet.
27
+ rooms.createRule = `${rooms.createRule} && ${WRITERS_UNSET}`;
28
+ app.save(rooms);
29
+ app.db().newQuery("UPDATE rooms SET posting = 'everyone', writers = '[]'").execute();
30
+
31
+ const messages = app.findCollectionByNameOrId("messages");
32
+ messages.createRule = `${messages.createRule} && ${WRITER("@request.body.room.")}`;
33
+ // Someone who may no longer post can't edit or delete what they wrote there either, as in an archived room.
34
+ messages.updateRule = `${messages.updateRule} && ${WRITER("room.")}`;
35
+ app.save(messages);
36
+ },
37
+ (app) => {
38
+ const messages = app.findCollectionByNameOrId("messages");
39
+ messages.createRule = (messages.createRule ?? "").replace(` && ${WRITER("@request.body.room.")}`, "");
40
+ messages.updateRule = (messages.updateRule ?? "").replace(` && ${WRITER("room.")}`, "");
41
+ app.save(messages);
42
+
43
+ const rooms = app.findCollectionByNameOrId("rooms");
44
+ rooms.createRule = (rooms.createRule ?? "").replace(` && ${WRITERS_UNSET}`, "");
45
+ rooms.fields.removeByName("writers");
46
+ rooms.fields.removeByName("posting");
47
+ app.save(rooms);
48
+ },
49
+ );
@@ -0,0 +1,51 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Message search (DESIGN.md §29): messages.text_key, the text case folded like names are compared (§22.1), set by
3
+ // pb_hooks on every save. Searching filters on it (`text_key ~ {:word}`), so "привет" finds "Привет" and "strasse"
4
+ // "Straße": SQLite's LIKE only ignores the case of ASCII letters (QA BUG-55). Not hidden, so the list API (and its
5
+ // rules) can filter on it; clients never ask for it (MSG_FIELDS).
6
+
7
+ /**
8
+ * Same as nameKey() in pb_hooks/lib/text.js (migrations can't load the hooks' modules).
9
+ * @param {string} text
10
+ */
11
+ function textKey(text) {
12
+ const s = text.replace(/[­᠎​-‏‪-‮⁠-⁤⁦-⁩]/g, "");
13
+ return (typeof s.normalize === "function" ? s.normalize("NFKC") : s).toUpperCase().toLowerCase();
14
+ }
15
+
16
+ /** Messages backfilled per query. */
17
+ const BATCH = 500;
18
+
19
+ migrate(
20
+ (app) => {
21
+ const messages = app.findCollectionByNameOrId("messages");
22
+ // NFKC can make text longer (one ligature becomes up to 18 letters): room for any 2000-character message.
23
+ messages.fields.add(new TextField({ name: "text_key", max: 40000 }));
24
+ app.save(messages);
25
+
26
+ // Backfill with raw SQL (no hooks: they would stamp edits). Deleted messages and forwards have no text.
27
+ let after = "";
28
+ for (;;) {
29
+ const rows = arrayOf(new DynamicModel({ id: "", text: "" }));
30
+ app
31
+ .db()
32
+ .newQuery("SELECT id, text FROM messages WHERE text != '' AND id > {:after} ORDER BY id LIMIT {:n}")
33
+ .bind({ after, n: BATCH })
34
+ .all(rows);
35
+ for (const r of rows) {
36
+ app
37
+ .db()
38
+ .newQuery("UPDATE messages SET text_key = {:key} WHERE id = {:id}")
39
+ .bind({ key: textKey(r.text), id: r.id })
40
+ .execute();
41
+ }
42
+ if (rows.length < BATCH) break;
43
+ after = rows[rows.length - 1].id;
44
+ }
45
+ },
46
+ (app) => {
47
+ const messages = app.findCollectionByNameOrId("messages");
48
+ messages.fields.removeByName("text_key");
49
+ app.save(messages);
50
+ },
51
+ );
@@ -0,0 +1,16 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Message search (DESIGN.md §29): "İ" is searched as "i" (QA BUG-113). Lowercased, "İ" is "i" followed by a combining
3
+ // dot above (U+0307), so the key of "İstanbul" was "i̇stanbul", which "istanbul" as typed never matched. The hooks now
4
+ // drop that dot (`searchKey` in pb_hooks/lib/text.js); this does the same to the keys already stored.
5
+
6
+ migrate(
7
+ (app) => {
8
+ app
9
+ .db()
10
+ .newQuery("UPDATE messages SET text_key = replace(text_key, 'i' || char(775), 'i') WHERE instr(text_key, 'i' || char(775)) > 0")
11
+ .execute();
12
+ },
13
+ () => {
14
+ // Nothing to undo: a key without the dot finds what it found before, and more.
15
+ },
16
+ );