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,67 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // The Android app's server additions (docs/ANDROID.md §8, §12.4):
3
+ // - push_tokens: a device's push registration (an FCM token, or a UnifiedPush endpoint URL), the owner's only: they
4
+ // create, view and delete it; nobody lists them.
5
+ // - push_queue: messages whose pushes are still to be sent (pb_hooks/lib/push.js). No API access.
6
+ // - site.min_android_version: the oldest app the server still serves (0: any). Readable like the rest of the site.
7
+
8
+ const OWNER = "user = @request.auth.id";
9
+
10
+ migrate(
11
+ (app) => {
12
+ const users = app.findCollectionByNameOrId("users");
13
+ const messages = app.findCollectionByNameOrId("messages");
14
+ app.save(
15
+ new Collection(
16
+ /** @type {any} */ ({
17
+ type: "base",
18
+ name: "push_tokens",
19
+ listRule: null,
20
+ viewRule: OWNER,
21
+ createRule: `@request.auth.id != "" && @request.auth.collectionName = "users" && ${OWNER}`,
22
+ updateRule: null,
23
+ deleteRule: OWNER,
24
+ fields: [
25
+ { type: "relation", name: "user", required: true, maxSelect: 1, collectionId: users.id, cascadeDelete: true },
26
+ { type: "text", name: "token", required: true, min: 1, max: 1024 },
27
+ { type: "select", name: "provider", required: true, maxSelect: 1, values: ["fcm", "unifiedpush"] },
28
+ { type: "autodate", name: "created", onCreate: true, onUpdate: false },
29
+ { type: "autodate", name: "updated", onCreate: true, onUpdate: true },
30
+ ],
31
+ indexes: [
32
+ "CREATE UNIQUE INDEX idx_push_tokens_token ON push_tokens (token)",
33
+ "CREATE INDEX idx_push_tokens_user ON push_tokens (user)",
34
+ ],
35
+ }),
36
+ ),
37
+ );
38
+ app.save(
39
+ new Collection(
40
+ /** @type {any} */ ({
41
+ type: "base",
42
+ name: "push_queue",
43
+ listRule: null,
44
+ viewRule: null,
45
+ createRule: null,
46
+ updateRule: null,
47
+ deleteRule: null,
48
+ fields: [
49
+ { type: "relation", name: "message", required: true, maxSelect: 1, collectionId: messages.id, cascadeDelete: true },
50
+ { type: "autodate", name: "created", onCreate: true, onUpdate: false },
51
+ ],
52
+ indexes: ["CREATE INDEX idx_push_queue_created ON push_queue (created)"],
53
+ }),
54
+ ),
55
+ );
56
+ const site = app.findCollectionByNameOrId("site");
57
+ site.fields.add(new NumberField(/** @type {any} */ ({ name: "min_android_version", min: 0, onlyInt: true })));
58
+ app.save(site);
59
+ },
60
+ (app) => {
61
+ app.delete(app.findCollectionByNameOrId("push_queue"));
62
+ app.delete(app.findCollectionByNameOrId("push_tokens"));
63
+ const site = app.findCollectionByNameOrId("site");
64
+ site.fields.removeByName("min_android_version");
65
+ app.save(site);
66
+ },
67
+ );
@@ -0,0 +1,31 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // One device, several accounts (docs/ANDROID.md §17.4): the app registers the device's push token once per account, so
3
+ // two accounts on this server share a token. A token is now unique per user, not overall.
4
+
5
+ const PER_TOKEN = "CREATE UNIQUE INDEX idx_push_tokens_token ON push_tokens (token)";
6
+ const PER_USER = "CREATE UNIQUE INDEX idx_push_tokens_token_user ON push_tokens (token, user)";
7
+
8
+ /**
9
+ * @param {Parameters<Parameters<typeof migrate>[0]>[0]} app
10
+ * @param {string} from
11
+ * @param {string} to
12
+ */
13
+ function swap(app, from, to) {
14
+ const c = /** @type {any} */ (app.findCollectionByNameOrId("push_tokens"));
15
+ c.indexes = [.../** @type {string[]} */ (c.indexes).filter((i) => i !== from), to];
16
+ app.save(c);
17
+ }
18
+
19
+ migrate(
20
+ (app) => swap(app, PER_TOKEN, PER_USER),
21
+ (app) => {
22
+ // Back to one row per token: the newest registration of each keeps it.
23
+ app
24
+ .db()
25
+ .newQuery(
26
+ "DELETE FROM push_tokens WHERE id NOT IN (SELECT id FROM (SELECT id, ROW_NUMBER() OVER (PARTITION BY token ORDER BY updated DESC, id DESC) AS n FROM push_tokens) WHERE n = 1)",
27
+ )
28
+ .execute();
29
+ swap(app, PER_USER, PER_TOKEN);
30
+ },
31
+ );
@@ -0,0 +1,18 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // The room's media grid (DESIGN.md §30) shows square tiles: a "240x240" thumbnail is cropped to the square, centred,
3
+ // where the fitted ones (§17.5) would be blurry once cropped.
4
+
5
+ const BEFORE = ["800x480f", "480x240f"];
6
+ const AFTER = [...BEFORE, "240x240"];
7
+
8
+ /** @param {any} app @param {string[]} thumbs */
9
+ function setThumbs(app, thumbs) {
10
+ const messages = app.findCollectionByNameOrId("messages");
11
+ /** @type {any} */ (messages.fields.getByName("files")).thumbs = thumbs;
12
+ app.save(messages);
13
+ }
14
+
15
+ migrate(
16
+ (app) => setThumbs(app, AFTER),
17
+ (app) => setThumbs(app, BEFORE),
18
+ );
@@ -0,0 +1,71 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // The media grid's index (DESIGN.md §30.1): one row per image or video a room shows, its own or a forward's (§21.3),
3
+ // so the grid reads a room's media a page at a time without looking at its other messages, and the media worker
4
+ // (pb_hooks/lib/media.js) knows which files still need their thumbnails or video poster. No API access: the grid
5
+ // reads it through GET /api/chat/media/{room}. Kept by the messages hooks; filled here from the messages there are.
6
+ //
7
+ // - message: the message in the room (a forward, or the message itself); source: the one whose file it is.
8
+ // - pos: the file's place in the source's files; sent: the message's `created` (the grid's order, as the room's).
9
+ // - ready: the worker is done with it (forwards' rows are: their source's row does the work); poster: a video's
10
+ // poster frame is stored (thumbs_{file}/poster.jpg next to the file).
11
+
12
+ /** As web/src/lib/files.ts and pb_hooks/lib/media.js say, when this ran. */
13
+ const IMAGE_EXT = ["jpg", "jpeg", "png", "gif", "webp", "avif"];
14
+ const VIDEO_EXT = ["mp4", "m4v", "webm", "mov", "ogv"];
15
+
16
+ /** @param {string[]} exts */
17
+ const endsWith = (exts) => `(${exts.map((x) => `f.value LIKE '%.${x}'`).join(" OR ")})`;
18
+
19
+ migrate(
20
+ (app) => {
21
+ const messages = app.findCollectionByNameOrId("messages");
22
+ const rooms = app.findCollectionByNameOrId("rooms");
23
+ app.save(
24
+ new Collection(
25
+ /** @type {any} */ ({
26
+ type: "base",
27
+ name: "media",
28
+ listRule: null,
29
+ viewRule: null,
30
+ createRule: null,
31
+ updateRule: null,
32
+ deleteRule: null,
33
+ fields: [
34
+ { type: "relation", name: "room", required: true, maxSelect: 1, collectionId: rooms.id, cascadeDelete: true },
35
+ { type: "relation", name: "message", required: true, maxSelect: 1, collectionId: messages.id, cascadeDelete: true },
36
+ { type: "relation", name: "source", required: true, maxSelect: 1, collectionId: messages.id, cascadeDelete: true },
37
+ { type: "text", name: "file", required: true, max: 255 },
38
+ { type: "number", name: "pos", onlyInt: true, min: 0 },
39
+ { type: "bool", name: "video" },
40
+ { type: "date", name: "sent", required: true },
41
+ { type: "bool", name: "ready" },
42
+ { type: "bool", name: "poster" },
43
+ ],
44
+ indexes: [
45
+ "CREATE INDEX idx_media_room ON media (room, sent, message, pos)",
46
+ "CREATE INDEX idx_media_message ON media (message)",
47
+ "CREATE INDEX idx_media_source ON media (source, file)",
48
+ "CREATE INDEX idx_media_pending ON media (sent) WHERE ready = FALSE",
49
+ ],
50
+ }),
51
+ ),
52
+ );
53
+
54
+ // Every message there is that shows media and isn't deleted; a forward shows its original's.
55
+ app
56
+ .db()
57
+ .newQuery(
58
+ `INSERT INTO media (id, room, message, source, file, pos, video, sent, ready, poster)
59
+ SELECT substr(lower(hex(randomblob(8))), 1, 15), m.room, m.id, s.id, f.value, CAST(f.key AS INTEGER),
60
+ ${endsWith(VIDEO_EXT)}, m.created, s.id != m.id, FALSE
61
+ FROM messages m
62
+ JOIN messages s ON s.id = (CASE WHEN m.forward_of != '' THEN m.forward_of ELSE m.id END)
63
+ JOIN json_each(CASE WHEN json_valid(s.files) THEN s.files ELSE '[]' END) f
64
+ WHERE m.deleted = FALSE AND s.deleted = FALSE AND (${endsWith(IMAGE_EXT)} OR ${endsWith(VIDEO_EXT)})`,
65
+ )
66
+ .execute();
67
+ },
68
+ (app) => {
69
+ app.delete(app.findCollectionByNameOrId("media"));
70
+ },
71
+ );
@@ -0,0 +1,140 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Media collections (DESIGN.md §31): a user's own sets of images and videos, public or private, saved from the chat
3
+ // (a copy of the file, so it outlives the message and is seen by the collection's rules, not the room's) and attached
4
+ // to messages from there (copied again into the message). Others can subscribe to a public collection and see what
5
+ // is new in it.
6
+ //
7
+ // - collections: the owner manages them through the records API (rules below, pb_hooks/lib/collections.js checks the
8
+ // name and the limits); `items` and `last_added` are kept by the routes that add and remove items.
9
+ // - collection_items: one file each, protected (file tokens check this collection's view rule, §17.3). Written only by
10
+ // the routes. `origin` (hidden) says which message file or item it was copied from, so the same one isn't saved twice.
11
+ // - collection_subs: who follows which public collection, and up to when they have seen it (as room_reads, §18.1).
12
+ // - messages.file_sources: stored file name → the collection its file was attached from, set only by the create hook.
13
+
14
+ const C_NO_SOURCES = "@request.body.file_sources:isset = false";
15
+ const C_OWNER = "owner = @request.auth.id";
16
+ const C_VISIBLE = `public = true || ${C_OWNER}`;
17
+ const C_KEPT = "@request.body.items:isset = false && @request.body.last_added:isset = false && @request.body.name_key:isset = false";
18
+
19
+ const C_LIMITS = [
20
+ { label: "collections:create", audience: "", duration: 60, maxRequests: 10 },
21
+ { label: "POST /api/chat/items", audience: "", duration: 60, maxRequests: 30 },
22
+ { label: "POST /api/chat/subs", audience: "", duration: 60, maxRequests: 60 },
23
+ ];
24
+
25
+ /** The thumbnails of messages.files (§17.5, §30.1): an item attached to a message is shown at the same sizes. */
26
+ const C_THUMBS = ["800x480f", "480x240f", "240x240"];
27
+
28
+ migrate(
29
+ (app) => {
30
+ const users = app.findCollectionByNameOrId("users");
31
+ const collections = new Collection(
32
+ /** @type {any} */ ({
33
+ type: "base",
34
+ name: "collections",
35
+ listRule: C_VISIBLE,
36
+ viewRule: C_VISIBLE,
37
+ createRule: `@request.auth.id != "" && @request.body.owner = @request.auth.id && ${C_KEPT}`,
38
+ updateRule: `${C_OWNER} && @request.body.owner:isset = false && ${C_KEPT}`,
39
+ deleteRule: C_OWNER,
40
+ fields: [
41
+ { type: "relation", name: "owner", required: true, maxSelect: 1, collectionId: users.id, cascadeDelete: true },
42
+ { type: "text", name: "name", required: true, max: 60 },
43
+ { type: "text", name: "name_key", max: 240, hidden: true },
44
+ { type: "bool", name: "public" },
45
+ { type: "number", name: "items", onlyInt: true, min: 0 },
46
+ { type: "date", name: "last_added" },
47
+ { type: "autodate", name: "created", onCreate: true, onUpdate: false },
48
+ { type: "autodate", name: "updated", onCreate: true, onUpdate: true },
49
+ ],
50
+ indexes: ["CREATE UNIQUE INDEX idx_collections_owner_name ON collections (owner, name_key)"],
51
+ }),
52
+ );
53
+ app.save(collections);
54
+
55
+ app.save(
56
+ new Collection(
57
+ /** @type {any} */ ({
58
+ type: "base",
59
+ name: "collection_items",
60
+ listRule: "collection.public = true || collection.owner = @request.auth.id",
61
+ viewRule: "collection.public = true || collection.owner = @request.auth.id",
62
+ createRule: null,
63
+ updateRule: null,
64
+ deleteRule: null,
65
+ fields: [
66
+ { type: "relation", name: "collection", required: true, maxSelect: 1, collectionId: collections.id, cascadeDelete: true },
67
+ {
68
+ type: "file",
69
+ name: "file",
70
+ required: true,
71
+ maxSelect: 1,
72
+ maxSize: 20 * 1024 * 1024,
73
+ protected: true,
74
+ thumbs: C_THUMBS,
75
+ },
76
+ { type: "text", name: "name", max: 200 },
77
+ { type: "bool", name: "video" },
78
+ { type: "bool", name: "poster" },
79
+ { type: "bool", name: "ready", hidden: true },
80
+ { type: "text", name: "origin", max: 300, hidden: true },
81
+ { type: "autodate", name: "created", onCreate: true, onUpdate: false },
82
+ ],
83
+ indexes: [
84
+ "CREATE INDEX idx_collection_items_collection ON collection_items (collection, created)",
85
+ "CREATE UNIQUE INDEX idx_collection_items_origin ON collection_items (collection, origin) WHERE origin != ''",
86
+ "CREATE INDEX idx_collection_items_pending ON collection_items (created) WHERE ready = FALSE",
87
+ ],
88
+ }),
89
+ ),
90
+ );
91
+
92
+ app.save(
93
+ new Collection(
94
+ /** @type {any} */ ({
95
+ type: "base",
96
+ name: "collection_subs",
97
+ listRule: "user = @request.auth.id",
98
+ viewRule: "user = @request.auth.id",
99
+ createRule: null,
100
+ updateRule: null,
101
+ deleteRule: null,
102
+ fields: [
103
+ { type: "relation", name: "user", required: true, maxSelect: 1, collectionId: users.id, cascadeDelete: true },
104
+ { type: "relation", name: "collection", required: true, maxSelect: 1, collectionId: collections.id, cascadeDelete: true },
105
+ { type: "date", name: "seen_at", required: true },
106
+ { type: "autodate", name: "created", onCreate: true, onUpdate: false },
107
+ { type: "autodate", name: "updated", onCreate: true, onUpdate: true },
108
+ ],
109
+ indexes: [
110
+ "CREATE UNIQUE INDEX idx_collection_subs_user ON collection_subs (user, collection)",
111
+ "CREATE INDEX idx_collection_subs_collection ON collection_subs (collection)",
112
+ ],
113
+ }),
114
+ ),
115
+ );
116
+
117
+ const messages = app.findCollectionByNameOrId("messages");
118
+ messages.fields.add(new JSONField({ name: "file_sources", maxSize: 4096 }));
119
+ messages.createRule = `${messages.createRule} && ${C_NO_SOURCES}`;
120
+ messages.updateRule = `${messages.updateRule} && ${C_NO_SOURCES}`;
121
+ app.save(messages);
122
+
123
+ const settings = app.settings();
124
+ const labels = C_LIMITS.map((l) => l.label);
125
+ settings.rateLimits.rules = [.../** @type {any[]} */ (C_LIMITS), ...settings.rateLimits.rules.filter((r) => !labels.includes(r.label))];
126
+ app.save(settings);
127
+ },
128
+ (app) => {
129
+ const messages = app.findCollectionByNameOrId("messages");
130
+ messages.fields.removeByName("file_sources");
131
+ messages.createRule = (messages.createRule ?? "").replace(` && ${C_NO_SOURCES}`, "");
132
+ messages.updateRule = (messages.updateRule ?? "").replace(` && ${C_NO_SOURCES}`, "");
133
+ app.save(messages);
134
+ for (const name of ["collection_subs", "collection_items", "collections"]) app.delete(app.findCollectionByNameOrId(name));
135
+ const settings = app.settings();
136
+ const labels = C_LIMITS.map((l) => l.label);
137
+ settings.rateLimits.rules = settings.rateLimits.rules.filter((r) => !labels.includes(r.label));
138
+ app.save(settings);
139
+ },
140
+ );
@@ -0,0 +1,20 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // GET /api/chat/unread (DESIGN.md §18.1) counts every room the user can see, the heaviest read there is (237 ms with
3
+ // 1 000 rooms): held to what POST /api/chat/reads is, not just the /api/ limit (QA BUG-144). A client asks again at
4
+ // most every 250 ms, and only when something changed.
5
+
6
+ const UNREAD_LIMIT = { label: "GET /api/chat/unread", audience: "", duration: 60, maxRequests: 120 };
7
+
8
+ migrate(
9
+ (app) => {
10
+ const settings = app.settings();
11
+ const rest = settings.rateLimits.rules.filter((r) => r.label !== UNREAD_LIMIT.label);
12
+ settings.rateLimits.rules = [/** @type {any} */ (UNREAD_LIMIT), ...rest];
13
+ app.save(settings);
14
+ },
15
+ (app) => {
16
+ const settings = app.settings();
17
+ settings.rateLimits.rules = settings.rateLimits.rules.filter((r) => r.label !== UNREAD_LIMIT.label);
18
+ app.save(settings);
19
+ },
20
+ );
@@ -0,0 +1,227 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Linked instances (DESIGN.md §33, pb_hooks/federation.pb.js): its own collections, all named fed_*, readable and
3
+ // writable by superusers only (null rules), and a few fields on the core collections. Without FEDERATION_ORIGIN the
4
+ // module registers nothing and these stay empty.
5
+ // - fed_peers: an instance this one is paired with (or has invited), its shared secret, and how it is doing.
6
+ // - fed_shares: a room shared with a peer, on both sides: offered by the home's superuser, accepted by the peer's.
7
+ // - fed_people: who a stand-in user is (a person of a peer), and which of this instance's people a peer knows of.
8
+ // - fed_queue: work for the worker: events to send to a peer, files and avatars to fetch from one.
9
+ // - fed_seen: the ids of events taken from a peer (3 days), so a repeated delivery is dropped.
10
+ // - users.peer / users.instance: a stand-in's peer, and the host it is from (shown on profiles). rooms.peer /
11
+ // rooms.remote_id: a mirror's home and the room's id there. rooms.shared: who else holds the room (shown in its
12
+ // header). messages.remote_id: a copied message's global id (unique per room). Only the module sets them.
13
+
14
+ /** @param {Record<string, unknown>} data */
15
+ const fedCollection = (data) =>
16
+ new Collection(
17
+ /** @type {any} */ ({ type: "base", listRule: null, viewRule: null, createRule: null, updateRule: null, deleteRule: null, ...data }),
18
+ );
19
+
20
+ const F_NAMES = ["fed_seen", "fed_queue", "fed_people", "fed_shares", "fed_peers"];
21
+
22
+ const F_STAMPS = [
23
+ { type: "autodate", name: "created", onCreate: true, onUpdate: false },
24
+ { type: "autodate", name: "updated", onCreate: true, onUpdate: true },
25
+ ];
26
+
27
+ /** No client sets the module's fields. */
28
+ const F_USERS_UNSET = "@request.body.peer:isset = false && @request.body.instance:isset = false";
29
+ const F_ROOMS_UNSET = "@request.body.peer:isset = false && @request.body.remote_id:isset = false && @request.body.shared:isset = false";
30
+ const F_MESSAGES_UNSET = "@request.body.remote_id:isset = false";
31
+
32
+ /** Server requests come from a peer's address: held apart from what people send. */
33
+ const F_LIMIT = { label: "/api/fed/", audience: "", duration: 60, maxRequests: 600 };
34
+
35
+ /**
36
+ * @param {string | null | undefined} rule
37
+ * @param {string} extra
38
+ * @returns {any}
39
+ */
40
+ const andRule = (rule, extra) => (rule ? `${rule} && ${extra}` : rule);
41
+
42
+ /**
43
+ * @param {string | null | undefined} rule
44
+ * @param {string} extra
45
+ * @returns {any}
46
+ */
47
+ const dropRule = (rule, extra) => (rule ? rule.replace(` && ${extra}`, "") : rule);
48
+
49
+ migrate(
50
+ (app) => {
51
+ const rooms = app.findCollectionByNameOrId("rooms");
52
+ const users = app.findCollectionByNameOrId("users");
53
+ const messages = app.findCollectionByNameOrId("messages");
54
+
55
+ const peers = fedCollection({
56
+ name: "fed_peers",
57
+ fields: [
58
+ // https://b.example: where it is, and who it is (X-Fed-Origin).
59
+ { type: "text", name: "origin", required: true, max: 255 },
60
+ // B: what its people's names end in here ("Ann (B)").
61
+ { type: "text", name: "label", required: true, min: 1, max: 8 },
62
+ { type: "text", name: "secret", max: 128, hidden: true },
63
+ { type: "select", name: "status", maxSelect: 1, values: ["invited", "active", "suspended"] },
64
+ // People may open DMs across (both sides must tick it).
65
+ { type: "bool", name: "dms" },
66
+ // On the inviting side, the code to give the peer's admin, until it is used or expires; on the joining side,
67
+ // the code typed in (cleared once paired).
68
+ { type: "text", name: "invite", max: 64 },
69
+ { type: "date", name: "invite_expires" },
70
+ // Its site name, as it said when pairing.
71
+ { type: "text", name: "name", max: 255 },
72
+ { type: "date", name: "last_ok" },
73
+ { type: "text", name: "last_error", max: 1000 },
74
+ ...F_STAMPS,
75
+ ],
76
+ indexes: [
77
+ "CREATE UNIQUE INDEX idx_fed_peers_origin ON fed_peers (origin)",
78
+ "CREATE UNIQUE INDEX idx_fed_peers_label ON fed_peers (label COLLATE NOCASE)",
79
+ ],
80
+ });
81
+ app.save(peers);
82
+
83
+ app.save(
84
+ fedCollection({
85
+ name: "fed_shares",
86
+ fields: [
87
+ // Here: the room (the home's own, or the mirror). Empty on the peer's side until it is accepted.
88
+ { type: "relation", name: "room", maxSelect: 1, collectionId: rooms.id, cascadeDelete: true },
89
+ { type: "relation", name: "peer", required: true, maxSelect: 1, collectionId: peers.id, cascadeDelete: true },
90
+ // On a mirror's side: the room's global id at its home (id@host).
91
+ { type: "text", name: "remote_id", max: 300 },
92
+ { type: "select", name: "state", maxSelect: 1, values: ["offered", "active", "ended"] },
93
+ // On a mirror's side: ticked by its superuser to take the room.
94
+ { type: "bool", name: "accepted" },
95
+ // The home's room, as it was offered: what the peer's admin decides on.
96
+ { type: "text", name: "name", max: 255 },
97
+ { type: "text", name: "kind", max: 16 },
98
+ { type: "text", name: "visibility", max: 16 },
99
+ { type: "text", name: "last_error", max: 1000 },
100
+ ...F_STAMPS,
101
+ ],
102
+ indexes: [
103
+ "CREATE INDEX idx_fed_shares_room ON fed_shares (room)",
104
+ "CREATE INDEX idx_fed_shares_peer_remote ON fed_shares (peer, remote_id)",
105
+ ],
106
+ }),
107
+ );
108
+
109
+ app.save(
110
+ fedCollection({
111
+ name: "fed_people",
112
+ fields: [
113
+ { type: "relation", name: "peer", required: true, maxSelect: 1, collectionId: peers.id, cascadeDelete: true },
114
+ // Their global id: id@host of the instance they are on.
115
+ { type: "text", name: "remote", required: true, max: 300 },
116
+ { type: "relation", name: "user", required: true, maxSelect: 1, collectionId: users.id, cascadeDelete: true },
117
+ // "standin": `user` is the peer's person here. "known": `user` is one of ours, and the peer has heard of them
118
+ // (it is told when their profile changes).
119
+ { type: "select", name: "kind", required: true, maxSelect: 1, values: ["standin", "known"] },
120
+ // A stand-in's name and DM setting on their own instance, and which avatar it has (the peer's key for it).
121
+ { type: "text", name: "name", max: 255 },
122
+ { type: "bool", name: "no_dms" },
123
+ { type: "text", name: "avatar", max: 255 },
124
+ ...F_STAMPS,
125
+ ],
126
+ indexes: [
127
+ "CREATE UNIQUE INDEX idx_fed_people_remote ON fed_people (peer, remote)",
128
+ "CREATE INDEX idx_fed_people_user ON fed_people (user)",
129
+ ],
130
+ }),
131
+ );
132
+
133
+ app.save(
134
+ fedCollection({
135
+ name: "fed_queue",
136
+ fields: [
137
+ { type: "relation", name: "peer", required: true, maxSelect: 1, collectionId: peers.id, cascadeDelete: true },
138
+ // event: one to send. fetch: a message that came with files, saved once they are fetched. avatar: a
139
+ // stand-in's picture to fetch.
140
+ { type: "select", name: "op", required: true, maxSelect: 1, values: ["event", "fetch", "avatar"] },
141
+ { type: "json", name: "payload", maxSize: 1 << 20 },
142
+ // The order things are sent in: queued in one transaction, rows can share a created millisecond.
143
+ { type: "number", name: "seq", onlyInt: true },
144
+ { type: "number", name: "tries", onlyInt: true },
145
+ { type: "date", name: "next_at" },
146
+ { type: "date", name: "locked_until" },
147
+ { type: "text", name: "error", max: 1000 },
148
+ ...F_STAMPS,
149
+ ],
150
+ indexes: [
151
+ "CREATE INDEX idx_fed_queue_peer ON fed_queue (peer, op, seq)",
152
+ "CREATE INDEX idx_fed_queue_created ON fed_queue (created)",
153
+ ],
154
+ }),
155
+ );
156
+
157
+ app.save(
158
+ fedCollection({
159
+ name: "fed_seen",
160
+ fields: [
161
+ { type: "relation", name: "peer", required: true, maxSelect: 1, collectionId: peers.id, cascadeDelete: true },
162
+ { type: "text", name: "event", required: true, max: 64 },
163
+ { type: "autodate", name: "created", onCreate: true, onUpdate: false },
164
+ ],
165
+ indexes: [
166
+ "CREATE UNIQUE INDEX idx_fed_seen_event ON fed_seen (peer, event)",
167
+ "CREATE INDEX idx_fed_seen_created ON fed_seen (created)",
168
+ ],
169
+ }),
170
+ );
171
+
172
+ users.fields.add(new RelationField({ name: "peer", maxSelect: 1, collectionId: peers.id, hidden: true }));
173
+ users.fields.add(new TextField({ name: "instance", max: 255 }));
174
+ users.createRule = andRule(users.createRule, F_USERS_UNSET);
175
+ users.updateRule = andRule(users.updateRule, F_USERS_UNSET);
176
+ app.save(users);
177
+
178
+ rooms.fields.add(new RelationField({ name: "peer", maxSelect: 1, collectionId: peers.id, hidden: true }));
179
+ rooms.fields.add(new TextField({ name: "remote_id", max: 300, hidden: true }));
180
+ rooms.fields.add(new JSONField({ name: "shared", maxSize: 8192 }));
181
+ rooms.createRule = andRule(rooms.createRule, F_ROOMS_UNSET);
182
+ rooms.updateRule = andRule(rooms.updateRule, F_ROOMS_UNSET);
183
+ app.save(rooms);
184
+
185
+ messages.fields.add(new TextField({ name: "remote_id", max: 300, hidden: true }));
186
+ /** @type {any} */ (messages).indexes = [
187
+ .../** @type {string[]} */ (/** @type {any} */ (messages).indexes),
188
+ "CREATE UNIQUE INDEX idx_messages_remote ON messages (room, remote_id) WHERE remote_id != ''",
189
+ ];
190
+ messages.createRule = andRule(messages.createRule, F_MESSAGES_UNSET);
191
+ messages.updateRule = andRule(messages.updateRule, F_MESSAGES_UNSET);
192
+ app.save(messages);
193
+
194
+ const settings = app.settings();
195
+ const rest = settings.rateLimits.rules.filter((r) => r.label !== F_LIMIT.label);
196
+ settings.rateLimits.rules = [/** @type {any} */ (F_LIMIT), ...rest];
197
+ app.save(settings);
198
+ },
199
+ (app) => {
200
+ const settings = app.settings();
201
+ settings.rateLimits.rules = settings.rateLimits.rules.filter((r) => r.label !== F_LIMIT.label);
202
+ app.save(settings);
203
+
204
+ const messages = app.findCollectionByNameOrId("messages");
205
+ messages.createRule = dropRule(messages.createRule, F_MESSAGES_UNSET);
206
+ messages.updateRule = dropRule(messages.updateRule, F_MESSAGES_UNSET);
207
+ /** @type {any} */ (messages).indexes = /** @type {string[]} */ (/** @type {any} */ (messages).indexes).filter(
208
+ (i) => !i.includes("idx_messages_remote"),
209
+ );
210
+ messages.fields.removeByName("remote_id");
211
+ app.save(messages);
212
+
213
+ const rooms = app.findCollectionByNameOrId("rooms");
214
+ rooms.createRule = dropRule(rooms.createRule, F_ROOMS_UNSET);
215
+ rooms.updateRule = dropRule(rooms.updateRule, F_ROOMS_UNSET);
216
+ for (const f of ["peer", "remote_id", "shared"]) rooms.fields.removeByName(f);
217
+ app.save(rooms);
218
+
219
+ const users = app.findCollectionByNameOrId("users");
220
+ users.createRule = dropRule(users.createRule, F_USERS_UNSET);
221
+ users.updateRule = dropRule(users.updateRule, F_USERS_UNSET);
222
+ for (const f of ["peer", "instance"]) users.fields.removeByName(f);
223
+ app.save(users);
224
+
225
+ for (const name of F_NAMES) app.delete(app.findCollectionByNameOrId(name));
226
+ },
227
+ );
@@ -0,0 +1,44 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Linked instances (DESIGN.md §33.2, §33.3): no environment variable and no code to pass on.
3
+ // - site.federation: the module's switch, ticked by a superuser (Collections → site). The server's address is the
4
+ // Application URL (Settings). Hidden: nobody but superusers needs to know.
5
+ // - fed_peers.status "requested": an instance that asked to link with this one, waiting for this side's admin (who
6
+ // accepts by setting it active, or declines by deleting the row). `invite` then holds the asking side's code.
7
+ // - A server that ran with FEDERATION_ORIGIN (the first build's switch) keeps linking: that origin becomes the
8
+ // Application URL and `federation` is ticked.
9
+
10
+ migrate(
11
+ (app) => {
12
+ const site = app.findCollectionByNameOrId("site");
13
+ site.fields.add(new BoolField({ name: "federation", hidden: true }));
14
+ app.save(site);
15
+
16
+ const peers = app.findCollectionByNameOrId("fed_peers");
17
+ const status = /** @type {any} */ (peers.fields.getByName("status"));
18
+ status.values = ["invited", "requested", "active", "suspended"];
19
+ app.save(peers);
20
+
21
+ const was = $os.getenv("FEDERATION_ORIGIN").trim().replace(/\/+$/, "");
22
+ if (was) {
23
+ const settings = app.settings();
24
+ settings.meta.appURL = was;
25
+ app.save(settings);
26
+ const rec = app.findRecordsByFilter("site", "", "created", 1, 0)[0];
27
+ if (rec) {
28
+ rec.set("federation", true);
29
+ app.save(rec);
30
+ }
31
+ }
32
+ },
33
+ (app) => {
34
+ app.db().newQuery("DELETE FROM fed_peers WHERE status = 'requested'").execute();
35
+ const peers = app.findCollectionByNameOrId("fed_peers");
36
+ const status = /** @type {any} */ (peers.fields.getByName("status"));
37
+ status.values = ["invited", "active", "suspended"];
38
+ app.save(peers);
39
+
40
+ const site = app.findCollectionByNameOrId("site");
41
+ site.fields.removeByName("federation");
42
+ app.save(site);
43
+ },
44
+ );
@@ -0,0 +1,26 @@
1
+ /// <reference path="../types/pocketbase.d.ts" />
2
+ // Telegram → chat (DESIGN.md §26.4): a Telegram message longer than a chat message (4096 characters against 2000)
3
+ // comes over as several, in order, instead of cut. tg_messages.part says which of them a row is: 0 the first (the one
4
+ // a reply, an edit or a repeat delivery finds), 1, 2… the rest. A Telegram message is then one row per part.
5
+
6
+ migrate(
7
+ (app) => {
8
+ const tg = app.findCollectionByNameOrId("tg_messages");
9
+ tg.fields.add(new NumberField({ name: "part", onlyInt: true, min: 0 }));
10
+ /** @type {any} */ (tg).indexes = [
11
+ "CREATE UNIQUE INDEX idx_tg_messages_tg ON tg_messages (chat_id, tg_message_id, part)",
12
+ "CREATE INDEX idx_tg_messages_message ON tg_messages (message)",
13
+ ];
14
+ app.save(tg);
15
+ },
16
+ (app) => {
17
+ app.db().newQuery("DELETE FROM tg_messages WHERE part > 0").execute();
18
+ const tg = app.findCollectionByNameOrId("tg_messages");
19
+ tg.fields.removeByName("part");
20
+ /** @type {any} */ (tg).indexes = [
21
+ "CREATE UNIQUE INDEX idx_tg_messages_tg ON tg_messages (chat_id, tg_message_id)",
22
+ "CREATE INDEX idx_tg_messages_message ON tg_messages (message)",
23
+ ];
24
+ app.save(tg);
25
+ },
26
+ );