chirkle 0.3.0 → 0.4.1

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 (156) hide show
  1. package/README.md +99 -47
  2. package/bin/release/darwin-amd64/chirkle-server +4 -0
  3. package/bin/release/darwin-arm64/chirkle-server +0 -0
  4. package/bin/release/linux-amd64/chirkle-server +0 -0
  5. package/bin/release/linux-arm64/chirkle-server +0 -0
  6. package/package.json +9 -6
  7. package/pb_hooks/federation/inbox.js +2 -69
  8. package/pb_hooks/federation/messages.js +5 -3
  9. package/pb_hooks/federation/net.js +1 -0
  10. package/pb_hooks/federation/people.js +1 -0
  11. package/pb_hooks/federation.pb.js +1 -8
  12. package/pb_hooks/lib/access.js +33 -10
  13. package/pb_hooks/lib/account.js +542 -6
  14. package/pb_hooks/lib/anonymous.js +2 -129
  15. package/pb_hooks/lib/bulk.js +1 -2
  16. package/pb_hooks/lib/collections.js +4 -4
  17. package/pb_hooks/lib/dms.js +1 -1
  18. package/pb_hooks/lib/files.js +82 -120
  19. package/pb_hooks/lib/handles.js +2 -2
  20. package/pb_hooks/lib/inbox.js +40 -54
  21. package/pb_hooks/lib/invites.js +266 -0
  22. package/pb_hooks/lib/media.js +5 -43
  23. package/pb_hooks/lib/messages.js +72 -117
  24. package/pb_hooks/lib/moderation.js +2 -16
  25. package/pb_hooks/lib/reactions.js +28 -4
  26. package/pb_hooks/lib/retention.js +88 -0
  27. package/pb_hooks/lib/site.js +13 -2
  28. package/pb_hooks/lib/stats.js +6 -34
  29. package/pb_hooks/lib/users.js +88 -7
  30. package/pb_hooks/lib/worker.js +22 -1
  31. package/pb_hooks/main.pb.js +85 -94
  32. package/pb_hooks/telegram/api.js +64 -12
  33. package/pb_hooks/telegram/inbound.js +158 -31
  34. package/pb_hooks/telegram/links.js +4 -3
  35. package/pb_hooks/telegram/outbound.js +86 -45
  36. package/pb_hooks/telegram/people.js +3 -3
  37. package/pb_hooks/telegram/worker.js +59 -15
  38. package/pb_migrations/1760000045_password_reset.js +38 -0
  39. package/pb_migrations/1760000047_telegram_supergroup_ids.js +51 -0
  40. package/pb_migrations/1760000048_inbox_reactions_merged.js +24 -0
  41. package/pb_migrations/1760000049_inbox_room_index.js +22 -0
  42. package/pb_migrations/1760000050_messages_unread_index.js +22 -0
  43. package/pb_migrations/1760000051_users_kind.js +31 -0
  44. package/pb_migrations/1760000052_deleted_accounts.js +19 -0
  45. package/pb_migrations/1760000053_account_jobs.js +45 -0
  46. package/pb_migrations/1760000054_room_invites.js +39 -0
  47. package/pb_migrations/1760000055_invite_barred.js +16 -0
  48. package/pb_migrations/1760000056_telegram_fetch.js +21 -0
  49. package/pb_public/assets/{access-PB77EH4F.css → access-GPRLOZOO.css} +2 -2
  50. package/pb_public/assets/{access-PB77EH4F.css.map → access-GPRLOZOO.css.map} +2 -2
  51. package/pb_public/assets/access-UK3L54NR.js +2 -0
  52. package/pb_public/assets/access-UK3L54NR.js.map +7 -0
  53. package/pb_public/assets/account-CT2BVMAX.css +2 -0
  54. package/pb_public/assets/account-CT2BVMAX.css.map +7 -0
  55. package/pb_public/assets/account-api-J6A6IYVX.js +2 -0
  56. package/pb_public/assets/account-api-J6A6IYVX.js.map +7 -0
  57. package/pb_public/assets/app-HB3NZHQ2.js +3 -0
  58. package/pb_public/assets/app-HB3NZHQ2.js.map +7 -0
  59. package/pb_public/assets/app-XJ73EU5O.css +2 -0
  60. package/pb_public/assets/app-XJ73EU5O.css.map +7 -0
  61. package/pb_public/assets/chunk-56ACD3V5.js +2 -0
  62. package/pb_public/assets/chunk-56ACD3V5.js.map +7 -0
  63. package/pb_public/assets/chunk-AG73QNUN.js +2 -0
  64. package/pb_public/assets/chunk-AG73QNUN.js.map +7 -0
  65. package/pb_public/assets/chunk-DCLJRQ53.js +2 -0
  66. package/pb_public/assets/chunk-DCLJRQ53.js.map +7 -0
  67. package/pb_public/assets/chunk-DZC4SY4M.js +2 -0
  68. package/pb_public/assets/chunk-DZC4SY4M.js.map +7 -0
  69. package/pb_public/assets/chunk-N2OFGBCZ.js +2 -0
  70. package/pb_public/assets/chunk-N2OFGBCZ.js.map +7 -0
  71. package/pb_public/assets/chunk-OKIIBH7O.js +2 -0
  72. package/pb_public/assets/chunk-OKIIBH7O.js.map +7 -0
  73. package/pb_public/assets/chunk-RPCBA7VF.js +2 -0
  74. package/pb_public/assets/chunk-RPCBA7VF.js.map +7 -0
  75. package/pb_public/assets/chunk-UZDXAORM.js +2 -0
  76. package/pb_public/assets/chunk-UZDXAORM.js.map +7 -0
  77. package/pb_public/assets/chunk-VTOUI25E.js +4 -0
  78. package/pb_public/assets/chunk-VTOUI25E.js.map +7 -0
  79. package/pb_public/assets/chunk-WR25F7FU.js +2 -0
  80. package/pb_public/assets/chunk-WR25F7FU.js.map +7 -0
  81. package/pb_public/assets/{emoji-VA2WCEAC.css → emoji-WWNPWCF3.css} +2 -2
  82. package/pb_public/assets/{emoji-VA2WCEAC.css.map → emoji-WWNPWCF3.css.map} +2 -2
  83. package/pb_public/assets/{emoji-picker-65VVVGYW.js → emoji-picker-K6JTK2GV.js} +4 -4
  84. package/pb_public/assets/emoji-picker-K6JTK2GV.js.map +7 -0
  85. package/pb_public/assets/forward-267HRNPY.js +2 -0
  86. package/pb_public/assets/forward-267HRNPY.js.map +7 -0
  87. package/pb_public/assets/inbox-CLMYESNI.js +2 -0
  88. package/pb_public/assets/inbox-CLMYESNI.js.map +7 -0
  89. package/pb_public/assets/invite-OGT5E2MZ.js +2 -0
  90. package/pb_public/assets/invite-OGT5E2MZ.js.map +7 -0
  91. package/pb_public/assets/invite-api-7G7XPXQW.js +2 -0
  92. package/pb_public/assets/invite-api-7G7XPXQW.js.map +7 -0
  93. package/pb_public/assets/lazy-H3KIJVB5.js +2 -0
  94. package/pb_public/assets/lazy-H3KIJVB5.js.map +7 -0
  95. package/pb_public/assets/login-TK6K4WGB.js +2 -0
  96. package/pb_public/assets/login-TK6K4WGB.js.map +7 -0
  97. package/pb_public/assets/media-WZ4653L5.js +2 -0
  98. package/pb_public/assets/media-WZ4653L5.js.map +7 -0
  99. package/pb_public/assets/mention-suggest-ODJD2IC5.js +2 -0
  100. package/pb_public/assets/mention-suggest-ODJD2IC5.js.map +7 -0
  101. package/pb_public/assets/notify-EPDM772N.js +2 -0
  102. package/pb_public/assets/notify-EPDM772N.js.map +7 -0
  103. package/pb_public/assets/profile-3R6S5QYS.js +2 -0
  104. package/pb_public/assets/profile-3R6S5QYS.js.map +7 -0
  105. package/pb_public/assets/search-WCHOGAJQ.js +2 -0
  106. package/pb_public/assets/search-WCHOGAJQ.js.map +7 -0
  107. package/pb_public/assets/stats-GTO2H6PG.js +2 -0
  108. package/pb_public/assets/stats-GTO2H6PG.js.map +7 -0
  109. package/pb_public/assets/switcher-TFSO45KV.js +2 -0
  110. package/pb_public/assets/switcher-TFSO45KV.js.map +7 -0
  111. package/pb_public/assets/user-search-3HQOCQWL.js +2 -0
  112. package/pb_public/assets/user-search-3HQOCQWL.js.map +7 -0
  113. package/pb_public/assets/viewer-2Y5FJBW4.js +2 -0
  114. package/pb_public/assets/viewer-2Y5FJBW4.js.map +7 -0
  115. package/pb_public/index.html +10 -2
  116. package/pb_public/stats.html +1 -1
  117. package/scripts/service.mjs +201 -0
  118. package/scripts/start.mjs +21 -17
  119. package/pb_hooks/lib/enrich.js +0 -75
  120. package/pb_hooks/lib/lists.js +0 -179
  121. package/pb_hooks/lib/live.js +0 -137
  122. package/pb_hooks/lib/reads.js +0 -183
  123. package/pb_public/assets/access-GUDTDXIP.js +0 -2
  124. package/pb_public/assets/access-GUDTDXIP.js.map +0 -7
  125. package/pb_public/assets/app-3WX5JYL2.js +0 -3
  126. package/pb_public/assets/app-3WX5JYL2.js.map +0 -7
  127. package/pb_public/assets/app-WAFKVN2H.css +0 -2
  128. package/pb_public/assets/app-WAFKVN2H.css.map +0 -7
  129. package/pb_public/assets/emoji-picker-65VVVGYW.js.map +0 -7
  130. package/pb_public/assets/forward-66PELNWT.js +0 -2
  131. package/pb_public/assets/forward-66PELNWT.js.map +0 -7
  132. package/pb_public/assets/inbox-TZJWPRTG.js +0 -2
  133. package/pb_public/assets/inbox-TZJWPRTG.js.map +0 -7
  134. package/pb_public/assets/lazy-4CXRBHHM.js +0 -2
  135. package/pb_public/assets/lazy-4CXRBHHM.js.map +0 -7
  136. package/pb_public/assets/login-G7Y44CJ7.js +0 -2
  137. package/pb_public/assets/login-G7Y44CJ7.js.map +0 -7
  138. package/pb_public/assets/media-FPRU2QH5.js +0 -2
  139. package/pb_public/assets/media-FPRU2QH5.js.map +0 -7
  140. package/pb_public/assets/mention-suggest-R7MXUH6R.js +0 -2
  141. package/pb_public/assets/mention-suggest-R7MXUH6R.js.map +0 -7
  142. package/pb_public/assets/notify-RQ6ZLR46.js +0 -2
  143. package/pb_public/assets/notify-RQ6ZLR46.js.map +0 -7
  144. package/pb_public/assets/profile-2CNVT2KX.js +0 -2
  145. package/pb_public/assets/profile-2CNVT2KX.js.map +0 -7
  146. package/pb_public/assets/search-3UT4HMES.js +0 -2
  147. package/pb_public/assets/search-3UT4HMES.js.map +0 -7
  148. package/pb_public/assets/stats-JX52AQCO.js +0 -2
  149. package/pb_public/assets/stats-JX52AQCO.js.map +0 -7
  150. package/pb_public/assets/switcher-CEUKRLEY.js +0 -2
  151. package/pb_public/assets/switcher-CEUKRLEY.js.map +0 -7
  152. package/pb_public/assets/user-search-7GNEIXMN.js +0 -2
  153. package/pb_public/assets/user-search-7GNEIXMN.js.map +0 -7
  154. package/pb_public/assets/viewer-DXT7SKOU.js +0 -2
  155. package/pb_public/assets/viewer-DXT7SKOU.js.map +0 -7
  156. package/scripts/fetch-pocketbase.sh +0 -63
@@ -1,5 +1,5 @@
1
1
  /// <reference path="../types/pocketbase.d.ts" />
2
- // Server-side hooks (DESIGN.md §5.6, §16, §18, §20, §21, §22, §23, §24, §28, §30, §31, §36, §37, §40; docs/ANDROID.md §9.4). Logic lives in lib/, one module per collection
2
+ // Server-side hooks (DESIGN.md §5.6, §16, §18, §20, §21, §22, §23, §24, §28, §30, §31, §36, §37, §40, §43, §44; docs/ANDROID.md §9.4). Logic lives in lib/, one module per collection
3
3
  // or route: PocketBase hook handlers can't see top-level variables, so each handler require()s its module.
4
4
 
5
5
  onBootstrap((e) => {
@@ -11,47 +11,12 @@ onBootstrap((e) => {
11
11
  // open realtime connection and every file on its way from S3 would keep some, and room pages, whose enrich hooks need
12
12
  // one each, would make new ones (docs/PERF.md §6). What one would do for every request is done by the routes and hooks
13
13
  // it concerns: the headers by the routes that serve pages (lib/http.js), the body limit by PocketBase (it sizes each
14
- // collection's create and update by its fields, DESIGN.md §17.1), the files and the anonymous rooms' checks below.
14
+ // collection's create and update by its fields, DESIGN.md §17.1), the files and the anonymous rooms' checks in Go.
15
15
 
16
- // Nobody but superusers finds out who wrote a message in an anonymous room by filtering, sorting or expanding (§35):
17
- // checked by everything that takes a filter, sort or expand (the routes here that enrich records do too).
18
- onRecordsListRequest((e) => {
19
- require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
20
- e.next();
21
- });
22
- onRecordViewRequest((e) => {
23
- require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
24
- e.next();
25
- });
26
- onRecordCreateRequest((e) => {
27
- require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
28
- e.next();
29
- });
30
- onRecordUpdateRequest((e) => {
31
- require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
32
- e.next();
33
- });
34
- // Every auth answer (password, OAuth2, OTP, refresh, impersonation) has the record, expanded as asked.
35
- onRecordAuthRequest((e) => {
36
- require(`${__hooks}/lib/anonymous.js`).refuseProbes(e);
37
- e.next();
38
- });
39
- onRealtimeSubscribeRequest((e) => {
40
- require(`${__hooks}/lib/anonymous.js`).refuseSubscriptionProbes(e);
41
- // Which app the connection is, and its account active today, for the statistics (§40).
42
- require(`${__hooks}/lib/stats.js`).subscribed(e);
43
- e.next();
44
- });
45
-
46
- // A message's or collection item's file is its shared `files` row's (§37): served without a file token, by routes more
47
- // specific than PocketBase's /api/files/{collection}/… (lib/files.js serve). The rows themselves never directly.
48
- routerAdd("GET", "/api/files/messages/{recordId}/{filename}", (e) => require(`${__hooks}/lib/files.js`).serve(e, "messages"));
49
- routerAdd("GET", "/api/files/collection_items/{recordId}/{filename}", (e) =>
50
- require(`${__hooks}/lib/files.js`).serve(e, "collection_items"),
51
- );
52
- onFileDownloadRequest(() => {
53
- throw new NotFoundError();
54
- }, "files");
16
+ // In Go (server/), so they take no JS runtime (docs/REFACTOR.md item 61): refusing filters, sorts and expands that say who
17
+ // wrote a message in an anonymous room (§35, server/anonymous.go bindProbes); a realtime subscription's app and account
18
+ // for the statistics (§40, server/stats.go); messages' and collection items' files and video posters, served from their
19
+ // `files` rows without a file token (§37, server/files.go), and the rows themselves never directly.
55
20
 
56
21
  // The app's pages (index.html at any path that isn't a file, §7.1) and its files, with their headers (§5.6).
57
22
  routerAdd("GET", "/{path...}", (e) => require(`${__hooks}/lib/http.js`).page(e));
@@ -70,21 +35,12 @@ routerAdd("GET", "/api/{path...}", () => {
70
35
  throw new NotFoundError();
71
36
  });
72
37
  routerAdd("POST", "/api/previews/tick", (e) => require(`${__hooks}/lib/previews.js`).tick(e), $apis.requireSuperuserAuth());
73
- routerAdd("GET", "/api/chat/rooms", (e) => require(`${__hooks}/lib/lists.js`).rooms(e));
74
- routerAdd("GET", "/api/chat/rooms/{room}/messages", (e) => require(`${__hooks}/lib/lists.js`).messages(e));
75
- routerAdd("GET", "/api/chat/notifiable", (e) => require(`${__hooks}/lib/lists.js`).notifiable(e), $apis.requireAuth("users"));
76
38
  routerAdd("POST", "/api/chat/dms", (e) => require(`${__hooks}/lib/dms.js`).openDm(e), $apis.requireAuth("users"));
77
- routerAdd("GET", "/api/chat/live", (e) => require(`${__hooks}/lib/live.js`).info(e));
78
- routerAdd("GET", "/api/chat/unread", (e) => require(`${__hooks}/lib/reads.js`).unread(e), $apis.requireAuth("users"));
79
- routerAdd("GET", "/api/chat/unread/{room}", (e) => require(`${__hooks}/lib/reads.js`).firstUnread(e), $apis.requireAuth("users"));
80
- routerAdd("POST", "/api/chat/reads", (e) => require(`${__hooks}/lib/reads.js`).markRead(e), $apis.requireAuth("users"));
81
39
  routerAdd("POST", "/api/chat/reactions", (e) => require(`${__hooks}/lib/reactions.js`).react(e), $apis.requireAuth("users"));
82
40
  routerAdd("POST", "/api/chat/delete", (e) => require(`${__hooks}/lib/bulk.js`).deleteMessages(e), $apis.requireAuth("users"));
83
41
  routerAdd("POST", "/api/chat/ban", (e) => require(`${__hooks}/lib/moderation.js`).ban(e), $apis.requireAuth("users"));
84
42
  routerAdd("POST", "/api/chat/forward", (e) => require(`${__hooks}/lib/bulk.js`).forward(e), $apis.requireAuth("users"));
85
43
  routerAdd("GET", "/api/chat/media/{room}", (e) => require(`${__hooks}/lib/media.js`).list(e));
86
- routerAdd("GET", "/api/chat/posters/{message}/{file}", (e) => require(`${__hooks}/lib/media.js`).poster(e));
87
- routerAdd("GET", "/api/chat/posters/items/{item}/{file}", (e) => require(`${__hooks}/lib/media.js`).itemPoster(e));
88
44
  routerAdd("GET", "/api/chat/collections", (e) => require(`${__hooks}/lib/collections.js`).list(e), $apis.requireAuth("users"));
89
45
  routerAdd("GET", "/api/chat/badges", (e) => require(`${__hooks}/lib/collections.js`).badges(e));
90
46
  routerAdd("POST", "/api/chat/items", (e) => require(`${__hooks}/lib/collections.js`).saveItem(e), $apis.requireAuth("users"));
@@ -95,12 +51,27 @@ routerAdd("POST", "/api/chat/subs/seen", (e) => require(`${__hooks}/lib/collecti
95
51
  routerAdd("POST", "/api/keepalive/tick", (e) => require(`${__hooks}/lib/keepalive.js`).tick(e), $apis.requireSuperuserAuth());
96
52
  routerAdd("GET", "/api/chat/stats", (e) => require(`${__hooks}/lib/stats.js`).get(e));
97
53
  routerAdd("POST", "/api/stats/tick", (e) => require(`${__hooks}/lib/stats.js`).tick(e), $apis.requireSuperuserAuth());
54
+ routerAdd("POST", "/api/retention/tick", (e) => require(`${__hooks}/lib/retention.js`).tick(e), $apis.requireSuperuserAuth());
98
55
  routerAdd("POST", "/api/media/tick", (e) => require(`${__hooks}/lib/media.js`).tick(e), $apis.requireSuperuserAuth());
99
56
  routerAdd("GET", "/api/chat/users", (e) => require(`${__hooks}/lib/users.js`).searchUsers(e), $apis.requireAuth("users"));
100
57
  routerAdd("GET", "/api/chat/mentionable", (e) => require(`${__hooks}/lib/handles.js`).mentionable(e), $apis.requireAuth("users"));
101
58
  routerAdd("GET", "/api/chat/inbox", (e) => require(`${__hooks}/lib/inbox.js`).list(e), $apis.requireAuth("users"));
102
59
  routerAdd("POST", "/api/chat/inbox/seen", (e) => require(`${__hooks}/lib/inbox.js`).markSeen(e), $apis.requireAuth("users"));
103
60
  routerAdd("POST", "/api/chat/password", (e) => require(`${__hooks}/lib/account.js`).changePassword(e), $apis.requireAuth("users"));
61
+ // Your data, and deleting your account (§43).
62
+ routerAdd("GET", "/api/chat/export", (e) => require(`${__hooks}/lib/account.js`).exportState(e), $apis.requireAuth("users"));
63
+ routerAdd("POST", "/api/chat/export", (e) => require(`${__hooks}/lib/account.js`).startExport(e), $apis.requireAuth("users"));
64
+ // Signed in or with a file token (a plain link), checked by the route.
65
+ routerAdd("GET", "/api/chat/export/file", (e) => require(`${__hooks}/lib/account.js`).exportFile(e));
66
+ routerAdd("POST", "/api/account/tick", (e) => require(`${__hooks}/lib/account.js`).tick(e), $apis.requireSuperuserAuth());
67
+ routerAdd("POST", "/api/chat/account/delete", (e) => require(`${__hooks}/lib/account.js`).deleteAccount(e), $apis.requireAuth("users"));
68
+ // Room invite links (§44): a private room's managers make and revoke its link; anyone reads where a link goes, and
69
+ // joins by it signed in.
70
+ routerAdd("GET", "/api/chat/rooms/{room}/invite", (e) => require(`${__hooks}/lib/invites.js`).get(e), $apis.requireAuth("users"));
71
+ routerAdd("POST", "/api/chat/rooms/{room}/invite", (e) => require(`${__hooks}/lib/invites.js`).create(e), $apis.requireAuth("users"));
72
+ routerAdd("DELETE", "/api/chat/rooms/{room}/invite", (e) => require(`${__hooks}/lib/invites.js`).revoke(e), $apis.requireAuth("users"));
73
+ routerAdd("GET", "/api/chat/invites/{token}", (e) => require(`${__hooks}/lib/invites.js`).preview(e));
74
+ routerAdd("POST", "/api/chat/invites/{token}", (e) => require(`${__hooks}/lib/invites.js`).join(e), $apis.requireAuth("users"));
104
75
 
105
76
  // The core collections' hooks (messages, rooms, users) are all here, with the optional features' parts (lib/features.js)
106
77
  // called in order: the federation's first, then the core's, then the Telegram bridge's; after the save, the other way
@@ -142,6 +113,7 @@ onRecordCreateRequest((e) => {
142
113
  features.federation(e.app)?.people.refuseLabelName(e);
143
114
  require(`${__hooks}/lib/site.js`).checkInvite(e);
144
115
  features.telegram()?.people.refuseStandInName(e);
116
+ require(`${__hooks}/lib/users.js`).checkPasswordLength(e.requestInfo().body.password);
145
117
  e.next();
146
118
  }, "users");
147
119
 
@@ -158,6 +130,17 @@ onRecordAuthWithPasswordRequest((e) => {
158
130
  e.next();
159
131
  }, "users");
160
132
 
133
+ onRecordRequestPasswordResetRequest((e) => require(`${__hooks}/lib/users.js`).skipStandInReset(e), "users");
134
+ onRecordConfirmPasswordResetRequest((e) => {
135
+ require(`${__hooks}/lib/users.js`).checkPasswordLength(e.requestInfo().body.password);
136
+ e.next();
137
+ }, "users");
138
+
139
+ onRecordEnrich((e) => {
140
+ require(`${__hooks}/lib/site.js`).showPasswordReset(e);
141
+ e.next();
142
+ }, "site");
143
+
161
144
  onRecordCreateRequest((e) => {
162
145
  require(`${__hooks}/lib/rooms.js`).beforeRoomCreateRequest(e);
163
146
  e.next();
@@ -169,8 +152,11 @@ onRecordUpdateRequest((e) => {
169
152
  if (fed) fed.rooms.checkHomeMembers(e);
170
153
  const members = fed ? fed.mirror.checkMirrorEdit(e) : null;
171
154
  require(`${__hooks}/lib/rooms.js`).beforeRoomUpdateRequest(e);
155
+ const wasMembers = e.record?.original().getStringSlice("members") ?? [];
172
156
  e.next();
173
157
  if (fed && members && e.record) fed.mirror.sendMembers(e.app, e.record, members);
158
+ // Taken out of a private room: its invite link doesn't let them back in (§44.2, QA BUG-280).
159
+ if (e.record) require(`${__hooks}/lib/invites.js`).barRemoved(e.app, wasMembers, e.record);
174
160
  }, "rooms");
175
161
 
176
162
  onRecordCreate((e) => {
@@ -190,6 +176,8 @@ onRecordUpdate((e) => {
190
176
  e.next();
191
177
  // Saved: whoever can't see it any more is told (§23.4).
192
178
  if (e.record) access.dropLostAccess(e.app, before, e.record);
179
+ // No longer private: its invite link goes (§44).
180
+ if (e.record) require(`${__hooks}/lib/invites.js`).dropInvites(e.app, before.visibility, e.record);
193
181
  // Its anonymous messages show its new name (§35).
194
182
  if (e.record) require(`${__hooks}/lib/anonymous.js`).forget(e.app, e.record.id);
195
183
  // A home room's changes go to its mirrors (§33).
@@ -208,13 +196,17 @@ onRecordDelete((e) => {
208
196
  onRecordCreateRequest((e) => {
209
197
  const messages = require(`${__hooks}/lib/messages.js`);
210
198
  messages.beforeMessageCreateRequest(e);
211
- // One transaction for the attachments' `files` rows (uploads, and files attached from collections, §31, §37) and
212
- // the message: refused, nothing is left stored.
213
- e.app.runInTransaction((tx) => {
214
- e.app = tx;
215
- messages.setRequestFiles(e);
199
+ // Checked, its mentions found, its uploads stored and its attachments set before the save (docs/PERF.md §12), which
200
+ // links them in its own transaction (below): the write connection isn't held for the reads, the uploads' round trips
201
+ // to S3 or the answer's enrich hook. Refused, nothing is left stored.
202
+ const prepared = messages.prepareCreate(e);
203
+ messages.setRequestFiles(e, prepared);
204
+ try {
216
205
  e.next();
217
- });
206
+ } catch (err) {
207
+ require(`${__hooks}/lib/files.js`).discard(e.app, prepared.uploaded);
208
+ throw err;
209
+ }
218
210
  }, "messages");
219
211
 
220
212
  onRecordCreate((e) => {
@@ -264,19 +256,33 @@ onRecordCreate((e) => {
264
256
  const features = require(`${__hooks}/lib/features.js`);
265
257
  if (e.record) {
266
258
  messages.setTextKey(e.record);
267
- // Who it mentions (§41): from its text, or as the linked instance it comes from says.
259
+ // Who it mentions (§41): from its text, or as the linked instance it comes from says. A create request's are
260
+ // found before its transaction (lib/messages.js prepareCreate).
268
261
  const fed = features.federation(e.app);
269
- require(`${__hooks}/lib/handles.js`).setMentions(e.app, e.record, !!fed && fed.messages.isFromPeer(e.app, e.record));
262
+ if (!messages.checked(e.record)) {
263
+ require(`${__hooks}/lib/handles.js`).setMentions(e.app, e.record, !!fed && fed.messages.isFromPeer(e.app, e.record));
264
+ }
265
+ }
266
+ // One transaction for the message, its attachments' links (§37) and what it tells and queues: whom it tells (§41),
267
+ // and what each feature does with a new message. Inside the caller's, when it has one (the bridges, forwards).
268
+ const app = e.app;
269
+ try {
270
+ app.runInTransaction((tx) => {
271
+ e.app = tx;
272
+ if (e.record) require(`${__hooks}/lib/files.js`).linkPending(tx, e.record);
273
+ e.next();
274
+ const rec = e.record;
275
+ if (!rec) return;
276
+ require(`${__hooks}/lib/inbox.js`).messageCreated(tx, rec);
277
+ features.telegram()?.outbound.queueCreate(tx, rec);
278
+ require(`${__hooks}/lib/previews.js`).queue(tx, rec);
279
+ require(`${__hooks}/lib/media.js`).add(tx, rec);
280
+ features.federation(tx)?.messages.messageCreated(tx, rec);
281
+ });
282
+ } finally {
283
+ // Committed (or the caller's): the after-save hooks (realtime, the DM's activity) run on the app as given.
284
+ e.app = app;
270
285
  }
271
- e.next();
272
- const rec = e.record;
273
- if (!rec) return;
274
- // Saved: whom it tells (§41), and what each feature does with a new message is queued, in the save's transaction.
275
- require(`${__hooks}/lib/inbox.js`).messageCreated(e.app, rec);
276
- features.telegram()?.outbound.queueCreate(e.app, rec);
277
- require(`${__hooks}/lib/previews.js`).queue(e.app, rec);
278
- require(`${__hooks}/lib/media.js`).add(e.app, rec);
279
- features.federation(e.app)?.messages.messageCreated(e.app, rec);
280
286
  }, "messages");
281
287
 
282
288
  onRecordAfterCreateSuccess((e) => {
@@ -284,20 +290,9 @@ onRecordAfterCreateSuccess((e) => {
284
290
  e.next();
285
291
  }, "messages");
286
292
 
287
- // Live (lib/live.js): each message once to everyone listening who can see its room, once committed. A failure to send
288
- // is logged, never the save's: the apps load what they missed when they reconnect.
289
- onRecordAfterCreateSuccess((e) => {
290
- e.next();
291
- require(`${__hooks}/lib/live.js`).sendSafely(e.app, e.record, "create");
292
- }, "messages");
293
- onRecordAfterUpdateSuccess((e) => {
294
- e.next();
295
- require(`${__hooks}/lib/live.js`).sendSafely(e.app, e.record, "update");
296
- }, "messages");
297
- onRecordAfterDeleteSuccess((e) => {
298
- e.next();
299
- require(`${__hooks}/lib/live.js`).sendSafely(e.app, e.record, "delete");
300
- }, "messages");
293
+ // Live messages (each message once to everyone listening who can see its room) are sent by the Go server
294
+ // (server/live.go), as are the messages enrich hook (server/enrich.go), the list routes (server/lists.go), the
295
+ // unread counts (server/unread.go) and POST /api/chat/reads (server/reads.go): docs/REFACTOR.md item 47.
301
296
 
302
297
  // The inbox (§41): each row added or removed, once committed, to its person's apps.
303
298
  onRecordAfterCreateSuccess((e) => {
@@ -356,19 +351,6 @@ onRecordUpdate((e) => {
356
351
  if (fed && was) fed.messages.messageChanged(e.app, rec, was);
357
352
  }, "messages");
358
353
 
359
- onRecordEnrich((e) => {
360
- const enrich = require(`${__hooks}/lib/enrich.js`);
361
- // lib/messages.js only for the messages that need it: loading it costs more than the rest (lib/enrich.js).
362
- if (enrich.needsWork(e)) {
363
- const messages = require(`${__hooks}/lib/messages.js`);
364
- messages.keepToRoom(e);
365
- messages.showOriginal(e);
366
- }
367
- e.next();
368
- // An anonymous room's message shows the room, not its author (§35): once expanded (in next()), by the real author.
369
- if (enrich.isAnonymous(e)) require(`${__hooks}/lib/anonymous.js`).hide(e);
370
- }, "messages");
371
-
372
354
  onRecordUpdateRequest((e) => {
373
355
  require(`${__hooks}/lib/messages.js`).beforeMessageUpdateRequest(e);
374
356
  // One transaction for the save, so beforeMessageUpdate reads the reactions it keeps right before writing (§20.2).
@@ -394,6 +376,15 @@ if ($os.getenv("STATS_CRON").trim().toLowerCase() !== "off") {
394
376
  cronAdd("stats-prune", "23 3 * * *", () => require(`${__hooks}/lib/stats.js`).prune($app));
395
377
  }
396
378
 
379
+ // Retention (REFACTOR item 49): old inbox rows and rows left behind by raw deletes, daily (lib/retention.js).
380
+ cronAdd("retention", "41 3 * * *", () => require(`${__hooks}/lib/retention.js`).prune($app));
381
+
382
+ // Account jobs (§43.5): exports made and deleted accounts' collections and messages deleted, by a worker, a minute's run
383
+ // at a time. ACCOUNT_CRON=off leaves them to POST /api/account/tick (tests).
384
+ if ($os.getenv("ACCOUNT_CRON").trim().toLowerCase() !== "off") {
385
+ cronAdd("account", "* * * * *", () => require(`${__hooks}/lib/account.js`).run($app));
386
+ }
387
+
397
388
  // The media grid's thumbnails and video posters (§30.1): made by a worker, a minute's run at a time. MEDIA_CRON=off
398
389
  // leaves them to POST /api/media/tick (tests).
399
390
  if ($os.getenv("MEDIA_CRON").trim().toLowerCase() !== "off") {
@@ -22,6 +22,13 @@ function config() {
22
22
  * message_reaction only where the bot is an admin. */
23
23
  const UPDATES = ["message", "edited_message", "channel_post", "edited_channel_post", "my_chat_member", "message_reaction"];
24
24
 
25
+ /**
26
+ * What a failed request's error says when it never reached Telegram: no connection was made (no address, refused,
27
+ * unreachable, the connection or its TLS handshake failed or timed out). Anything else (no answer in time, the
28
+ * connection lost or reset once made) may have reached it: a send may have been made.
29
+ */
30
+ const UNSENT = /dial tcp|no such host|connection refused|network is unreachable|no route to host|tls handshake|tls: /i;
31
+
25
32
  /** A refused or failed call. `retryAfter`: seconds Telegram asks to wait (429). `status` 0: no answer. */
26
33
  class TelegramError extends Error {
27
34
  /**
@@ -40,6 +47,14 @@ class TelegramError extends Error {
40
47
  get transient() {
41
48
  return this.status === 0 || this.status === 429 || this.status >= 500;
42
49
  }
50
+
51
+ /**
52
+ * It may have done what it asked though it failed: no answer came (a timeout, a connection lost or reset), after
53
+ * the request may have reached Telegram. Not when Telegram answered (it refused), nor when no connection was made.
54
+ */
55
+ get maybeDone() {
56
+ return this.status === 0 && !UNSENT.test(this.message);
57
+ }
43
58
  }
44
59
 
45
60
  /**
@@ -49,13 +64,20 @@ class TelegramError extends Error {
49
64
  */
50
65
  const asTelegram = (err) => (err instanceof TelegramError ? err : null);
51
66
 
67
+ /**
68
+ * Seconds an upload or download of `bytes` may take: enough at 200 KB/s, from 30 s up to 300 s. A connection that
69
+ * stops answering fails within that, not after a fixed 5 minutes, which held the worker past its lock (§26.7).
70
+ * @param {number} bytes
71
+ */
72
+ const transferTimeout = (bytes) => Math.min(300, 30 + Math.ceil(bytes / 200_000));
73
+
52
74
  /**
53
75
  * Call a Bot API method. Files (filesystem.File by field name) go as multipart, the other params as fields (objects
54
76
  * as JSON); without files the params are a JSON body.
55
77
  * @param {string} method
56
78
  * @param {Record<string, unknown>} [params]
57
79
  * @param {Record<string, any>} [files]
58
- * @param {number} [timeout] seconds
80
+ * @param {number} [timeout] seconds (with files: the upload's, transferTimeout)
59
81
  * @returns {any} the method's result
60
82
  */
61
83
  function call(method, params = {}, files, timeout = 30) {
@@ -71,7 +93,7 @@ function call(method, params = {}, files, timeout = 30) {
71
93
  if (v !== undefined) form.append(k, typeof v === "string" ? v : JSON.stringify(v));
72
94
  }
73
95
  for (const [k, f] of Object.entries(files)) form.append(k, f);
74
- res = $http.send({ url, method: "POST", body: form, timeout: Math.max(timeout, 300) });
96
+ res = $http.send({ url, method: "POST", body: form, timeout });
75
97
  } else {
76
98
  res = $http.send({ url, method: "POST", body: JSON.stringify(params), headers: { "content-type": "application/json" }, timeout });
77
99
  }
@@ -107,23 +129,53 @@ function storedName(name, path) {
107
129
  }
108
130
 
109
131
  /**
110
- * Download a file the bot can see (at most 20 MB, the Bot API's limit), named `name`.
132
+ * `fn` again at once, up to `tries` times in all, while it fails for now: for what may run twice (getFile, a
133
+ * download). A failure that has to wait longer (429 with retry_after over 5 s) is left to the caller.
134
+ * @template T
135
+ * @param {() => T} fn
136
+ * @param {number} [tries]
137
+ * @returns {T}
138
+ */
139
+ function retrying(fn, tries = 2) {
140
+ for (let i = 1; ; i++) {
141
+ try {
142
+ return fn();
143
+ } catch (err) {
144
+ const tg = asTelegram(err);
145
+ if (!tg?.transient || i >= tries || tg.retryAfter > 5) throw err;
146
+ sleep(tg.retryAfter ? tg.retryAfter * 1000 : 500 * i);
147
+ }
148
+ }
149
+ }
150
+
151
+ /** getFile's timeout: a small call, which a connection that answers does at once. */
152
+ const GET_FILE_TIMEOUT = 10;
153
+
154
+ /**
155
+ * Download a file the bot can see (at most 20 MB, the Bot API's limit), named `name`. A failure that may pass is
156
+ * tried again at once: a connection that drops now and then fails one request, rarely two (§26.4).
111
157
  * @param {string} fileId
112
158
  * @param {string} name
159
+ * @param {number} [size] its size, when Telegram said: how long the download may take
113
160
  */
114
- function download(fileId, name) {
161
+ function download(fileId, name, size = 0) {
115
162
  const { token, base } = config();
116
- const info = call("getFile", { file_id: fileId });
163
+ const info = retrying(() => call("getFile", { file_id: fileId }, undefined, GET_FILE_TIMEOUT));
117
164
  if (!info?.file_path) throw new TelegramError(400, "getFile: no file_path");
118
- let file;
119
- try {
120
- file = $filesystem.fileFromURL(`${base}/file/bot${token}/${info.file_path}`, 120);
121
- } catch (err) {
122
- throw new TelegramError(0, `download: ${String(err).replace(token, "<token>")}`);
123
- }
165
+ const timeout = transferTimeout(size || info.file_size || 20 * 1024 * 1024);
166
+ const file = retrying(() => {
167
+ try {
168
+ return $filesystem.fileFromURL(`${base}/file/bot${token}/${info.file_path}`, timeout);
169
+ } catch (err) {
170
+ const text = String(err).replace(token, "<token>");
171
+ // "failed to download url … (404)": Telegram answered.
172
+ const status = Number((/\((\d{3})\)\s*$/.exec(text) || ["", "0"])[1]);
173
+ throw new TelegramError(status, `download: ${text}`);
174
+ }
175
+ });
124
176
  file.originalName = name;
125
177
  file.name = storedName(name, info.file_path);
126
178
  return file;
127
179
  }
128
180
 
129
- module.exports = { config, call, download, asTelegram, TelegramError, UPDATES };
181
+ module.exports = { config, call, download, asTelegram, TelegramError, transferTimeout, UPDATES };