@remit/backend 0.0.142 → 0.0.144

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 (269) hide show
  1. package/dist/dev-server/content-handler.d.ts +38 -0
  2. package/dist/dev-server/content-handler.js +46 -0
  3. package/dist/src/api.d.ts +7 -0
  4. package/dist/src/api.js +144 -0
  5. package/dist/src/auth.d.ts +30 -0
  6. package/dist/src/auth.js +73 -0
  7. package/dist/src/config/msoauth.d.ts +30 -0
  8. package/dist/src/config/msoauth.js +30 -0
  9. package/{src/data-backend.ts → dist/src/data-backend.d.ts} +2 -4
  10. package/dist/src/data-backend.js +12 -0
  11. package/{src/derive/autoMoved.ts → dist/src/derive/autoMoved.d.ts} +1 -29
  12. package/dist/src/derive/autoMoved.js +49 -0
  13. package/dist/src/derive/contentSignature.d.ts +41 -0
  14. package/{src/derive/contentSignature.ts → dist/src/derive/contentSignature.js} +27 -72
  15. package/dist/src/derive/contentUrl.d.ts +46 -0
  16. package/dist/src/derive/contentUrl.js +46 -0
  17. package/{src/derive/deriveMuted.ts → dist/src/derive/deriveMuted.d.ts} +1 -3
  18. package/dist/src/derive/deriveMuted.js +7 -0
  19. package/dist/src/derive/enrichThreadRows.d.ts +118 -0
  20. package/dist/src/derive/enrichThreadRows.js +151 -0
  21. package/dist/src/derive/filterThreadCriteria.d.ts +23 -0
  22. package/dist/src/derive/filterThreadCriteria.js +24 -0
  23. package/{src/derive/pendingMoveCounts.ts → dist/src/derive/pendingMoveCounts.d.ts} +5 -53
  24. package/dist/src/derive/pendingMoveCounts.js +53 -0
  25. package/{src/derive/senderTrust.ts → dist/src/derive/senderTrust.d.ts} +1 -9
  26. package/dist/src/derive/senderTrust.js +19 -0
  27. package/dist/src/error.d.ts +21 -0
  28. package/dist/src/error.js +85 -0
  29. package/dist/src/handlers/account-guards.d.ts +36 -0
  30. package/dist/src/handlers/account-guards.js +107 -0
  31. package/dist/src/handlers/account-oauth.d.ts +14 -0
  32. package/dist/src/handlers/account-oauth.js +387 -0
  33. package/dist/src/handlers/account-overrides.d.ts +53 -0
  34. package/dist/src/handlers/account-overrides.js +233 -0
  35. package/dist/src/handlers/account-signature.d.ts +28 -0
  36. package/dist/src/handlers/account-signature.js +85 -0
  37. package/dist/src/handlers/account.d.ts +6 -0
  38. package/dist/src/handlers/account.js +350 -0
  39. package/dist/src/handlers/address.d.ts +35 -0
  40. package/dist/src/handlers/address.js +141 -0
  41. package/dist/src/handlers/calendar-event.d.ts +70 -0
  42. package/dist/src/handlers/calendar-event.js +425 -0
  43. package/dist/src/handlers/calendar-feed.d.ts +47 -0
  44. package/dist/src/handlers/calendar-feed.js +192 -0
  45. package/dist/src/handlers/calendar-suggestion.d.ts +47 -0
  46. package/dist/src/handlers/calendar-suggestion.js +212 -0
  47. package/dist/src/handlers/calendar.d.ts +116 -0
  48. package/dist/src/handlers/calendar.js +330 -0
  49. package/dist/src/handlers/config.d.ts +43 -0
  50. package/dist/src/handlers/config.js +176 -0
  51. package/dist/src/handlers/ensure-account-config.d.ts +9 -0
  52. package/dist/src/handlers/ensure-account-config.js +27 -0
  53. package/dist/src/handlers/filter.d.ts +3 -0
  54. package/dist/src/handlers/filter.js +103 -0
  55. package/dist/src/handlers/folder-role-appointments.d.ts +68 -0
  56. package/dist/src/handlers/folder-role-appointments.js +168 -0
  57. package/dist/src/handlers/folder-role-labels.d.ts +26 -0
  58. package/dist/src/handlers/folder-role-labels.js +40 -0
  59. package/dist/src/handlers/folder-role.d.ts +9 -0
  60. package/dist/src/handlers/folder-role.js +40 -0
  61. package/dist/src/handlers/index.d.ts +2 -0
  62. package/dist/src/handlers/index.js +60 -0
  63. package/dist/src/handlers/label.d.ts +43 -0
  64. package/dist/src/handlers/label.js +114 -0
  65. package/dist/src/handlers/mailbox-bindings.d.ts +41 -0
  66. package/dist/src/handlers/mailbox-bindings.js +61 -0
  67. package/dist/src/handlers/mailbox.d.ts +23 -0
  68. package/dist/src/handlers/mailbox.js +219 -0
  69. package/dist/src/handlers/me.d.ts +2 -0
  70. package/dist/src/handlers/me.js +138 -0
  71. package/dist/src/handlers/message.d.ts +84 -0
  72. package/dist/src/handlers/message.js +607 -0
  73. package/dist/src/handlers/organize.d.ts +10 -0
  74. package/dist/src/handlers/organize.js +112 -0
  75. package/dist/src/handlers/outbox-attachment.d.ts +23 -0
  76. package/dist/src/handlers/outbox-attachment.js +81 -0
  77. package/dist/src/handlers/outbox.d.ts +4 -0
  78. package/dist/src/handlers/outbox.js +144 -0
  79. package/dist/src/handlers/sync-progress.d.ts +46 -0
  80. package/dist/src/handlers/sync-progress.js +63 -0
  81. package/dist/src/handlers/sync.d.ts +28 -0
  82. package/dist/src/handlers/sync.js +82 -0
  83. package/dist/src/handlers/system-update.d.ts +2 -0
  84. package/dist/src/handlers/system-update.js +172 -0
  85. package/dist/src/handlers/thread.d.ts +148 -0
  86. package/dist/src/handlers/thread.js +233 -0
  87. package/dist/src/handlers/unified-threads.d.ts +247 -0
  88. package/dist/src/handlers/unified-threads.js +409 -0
  89. package/{src/handlers/vip-suggestions.ts → dist/src/handlers/vip-suggestions.d.ts} +1 -13
  90. package/dist/src/handlers/vip-suggestions.js +16 -0
  91. package/dist/src/index.d.ts +2 -0
  92. package/dist/src/index.js +37 -0
  93. package/{src/json.ts → dist/src/json.d.ts} +1 -4
  94. package/dist/src/json.js +10 -0
  95. package/dist/src/jwt-auth.d.ts +18 -0
  96. package/dist/src/jwt-auth.js +97 -0
  97. package/dist/src/request-context.d.ts +9 -0
  98. package/dist/src/request-context.js +22 -0
  99. package/dist/src/request.d.ts +3 -0
  100. package/dist/src/request.js +7 -0
  101. package/dist/src/response.d.ts +27 -0
  102. package/dist/src/response.js +87 -0
  103. package/dist/src/service/account-deletion.d.ts +22 -0
  104. package/dist/src/service/account-deletion.js +39 -0
  105. package/dist/src/service/compose-sqlite.d.ts +2 -0
  106. package/dist/src/service/compose-sqlite.js +11 -0
  107. package/dist/src/service/create-remit-client.d.ts +95 -0
  108. package/dist/src/service/create-remit-client.js +207 -0
  109. package/dist/src/service/data-client.d.ts +12 -0
  110. package/dist/src/service/data-client.js +44 -0
  111. package/dist/src/service/export-identity.d.ts +3 -0
  112. package/dist/src/service/export-identity.js +35 -0
  113. package/dist/src/service/fire-and-forget.d.ts +54 -0
  114. package/dist/src/service/fire-and-forget.js +38 -0
  115. package/dist/src/service/organize.d.ts +184 -0
  116. package/dist/src/service/organize.js +384 -0
  117. package/dist/src/service/refusal.d.ts +4 -0
  118. package/dist/src/service/refusal.js +20 -0
  119. package/dist/src/service/sender-category.d.ts +51 -0
  120. package/{src/service/sender-category.ts → dist/src/service/sender-category.js} +40 -81
  121. package/dist/src/service/sqs.d.ts +1 -0
  122. package/{src/service/sqs.ts → dist/src/service/sqs.js} +0 -1
  123. package/dist/src/service/trigger-sync.d.ts +51 -0
  124. package/dist/src/service/trigger-sync.js +39 -0
  125. package/dist/src/types.d.ts +49 -0
  126. package/dist/src/types.js +1 -0
  127. package/package.json +113 -98
  128. package/.env.test +0 -4
  129. package/dev-server/content-auth.test.ts +0 -113
  130. package/dev-server/content-auth.ts +0 -54
  131. package/dev-server/content-handler.test.ts +0 -105
  132. package/dev-server/content-handler.ts +0 -79
  133. package/dev-server/content-path.test.ts +0 -37
  134. package/dev-server/content-path.ts +0 -27
  135. package/dev-server/cors.test.ts +0 -48
  136. package/dev-server/cors.ts +0 -25
  137. package/dev-server/keep-alive.test.ts +0 -24
  138. package/dev-server/lambda-helpers.ts +0 -69
  139. package/dev-server/log-output.test.ts +0 -173
  140. package/dev-server/oauth-callback-route.test.ts +0 -66
  141. package/dev-server/relational-health.test.ts +0 -83
  142. package/dev-server/relational-health.ts +0 -39
  143. package/dev-server/server.ts +0 -384
  144. package/dev-server/sync-age.test.ts +0 -91
  145. package/dev-server/sync-age.ts +0 -55
  146. package/dev-server/upload-handler.ts +0 -132
  147. package/dev-server/upload-route.test.ts +0 -196
  148. package/scripts/backfill-classification.ts +0 -91
  149. package/scripts/backfill-list-id.ts +0 -83
  150. package/scripts/config-save.ts +0 -128
  151. package/src/auth.test.ts +0 -12
  152. package/src/auth.ts +0 -92
  153. package/src/config/msoauth.test.ts +0 -48
  154. package/src/config/msoauth.ts +0 -48
  155. package/src/data-backend.test.ts +0 -23
  156. package/src/derive/autoMoved.test.ts +0 -104
  157. package/src/derive/contentSignature.test.ts +0 -161
  158. package/src/derive/contentUrl.test.ts +0 -172
  159. package/src/derive/contentUrl.ts +0 -86
  160. package/src/derive/deriveMuted.test.ts +0 -34
  161. package/src/derive/enrichThreadRows.test.ts +0 -360
  162. package/src/derive/enrichThreadRows.ts +0 -234
  163. package/src/derive/filterThreadCriteria.test.ts +0 -126
  164. package/src/derive/filterThreadCriteria.ts +0 -51
  165. package/src/derive/senderTrust.test.ts +0 -67
  166. package/src/error.test.ts +0 -201
  167. package/src/error.ts +0 -123
  168. package/src/handlers/account-guards.test.ts +0 -67
  169. package/src/handlers/account-guards.ts +0 -169
  170. package/src/handlers/account-oauth-callback.test.ts +0 -155
  171. package/src/handlers/account-oauth-consent.test.ts +0 -336
  172. package/src/handlers/account-oauth-start.test.ts +0 -191
  173. package/src/handlers/account-oauth.test.ts +0 -439
  174. package/src/handlers/account-oauth.ts +0 -635
  175. package/src/handlers/account-overrides.test.ts +0 -88
  176. package/src/handlers/account-overrides.ts +0 -323
  177. package/src/handlers/account-ownership.ts +0 -25
  178. package/src/handlers/account-signature.ts +0 -117
  179. package/src/handlers/account-synced-services.test.ts +0 -245
  180. package/src/handlers/account.ts +0 -552
  181. package/src/handlers/address.test.ts +0 -381
  182. package/src/handlers/address.ts +0 -200
  183. package/src/handlers/calendar-event.test.ts +0 -685
  184. package/src/handlers/calendar-event.ts +0 -738
  185. package/src/handlers/calendar-feed-validators.test.ts +0 -228
  186. package/src/handlers/calendar-feed.test.ts +0 -439
  187. package/src/handlers/calendar-feed.ts +0 -291
  188. package/src/handlers/calendar-sqlite-fixture.ts +0 -36
  189. package/src/handlers/calendar-suggestion.test.ts +0 -1269
  190. package/src/handlers/calendar-suggestion.ts +0 -425
  191. package/src/handlers/calendar.test.ts +0 -1080
  192. package/src/handlers/calendar.ts +0 -517
  193. package/src/handlers/config.test.ts +0 -245
  194. package/src/handlers/config.ts +0 -332
  195. package/src/handlers/ensure-account-config.ts +0 -30
  196. package/src/handlers/filter.test.ts +0 -644
  197. package/src/handlers/filter.ts +0 -518
  198. package/src/handlers/folder-role-appointments.test.ts +0 -438
  199. package/src/handlers/folder-role-appointments.ts +0 -249
  200. package/src/handlers/folder-role-labels.ts +0 -63
  201. package/src/handlers/folder-role.test.ts +0 -209
  202. package/src/handlers/folder-role.ts +0 -80
  203. package/src/handlers/index.ts +0 -83
  204. package/src/handlers/label.test.ts +0 -112
  205. package/src/handlers/label.ts +0 -210
  206. package/src/handlers/mailbox-bindings.ts +0 -111
  207. package/src/handlers/mailbox-rename-refusal.test.ts +0 -247
  208. package/src/handlers/mailbox-settled-target.test.ts +0 -251
  209. package/src/handlers/mailbox.test.ts +0 -280
  210. package/src/handlers/mailbox.ts +0 -581
  211. package/src/handlers/me.test.ts +0 -81
  212. package/src/handlers/me.ts +0 -203
  213. package/src/handlers/message-read-backfill.test.ts +0 -103
  214. package/src/handlers/message.test.ts +0 -131
  215. package/src/handlers/message.ts +0 -1131
  216. package/src/handlers/organize.test.ts +0 -277
  217. package/src/handlers/organize.ts +0 -197
  218. package/src/handlers/outbox-attachment.test.ts +0 -765
  219. package/src/handlers/outbox-attachment.ts +0 -126
  220. package/src/handlers/outbox-list.test.ts +0 -179
  221. package/src/handlers/outbox.test.ts +0 -772
  222. package/src/handlers/outbox.ts +0 -258
  223. package/src/handlers/search.test.ts +0 -161
  224. package/src/handlers/search.ts +0 -105
  225. package/src/handlers/sync-progress.test.ts +0 -205
  226. package/src/handlers/sync-progress.ts +0 -99
  227. package/src/handlers/sync.test.ts +0 -168
  228. package/src/handlers/sync.ts +0 -118
  229. package/src/handlers/system-update.test.ts +0 -497
  230. package/src/handlers/system-update.ts +0 -230
  231. package/src/handlers/thread.test.ts +0 -396
  232. package/src/handlers/thread.ts +0 -427
  233. package/src/handlers/unified-threads-mail-sources.sqlite.test.ts +0 -197
  234. package/src/handlers/unified-threads.test.ts +0 -785
  235. package/src/handlers/unified-threads.ts +0 -669
  236. package/src/index.test.ts +0 -83
  237. package/src/index.ts +0 -228
  238. package/src/jwt-auth.test.ts +0 -152
  239. package/src/jwt-auth.ts +0 -132
  240. package/src/log-redaction.test.ts +0 -144
  241. package/src/openapi-spec.test.ts +0 -118
  242. package/src/request-context.test.ts +0 -61
  243. package/src/request-context.ts +0 -33
  244. package/src/request-pipeline.test.ts +0 -88
  245. package/src/request.ts +0 -10
  246. package/src/response.test.ts +0 -130
  247. package/src/response.ts +0 -144
  248. package/src/service/compose-sqlite.ts +0 -98
  249. package/src/service/config-import.ts +0 -39
  250. package/src/service/create-remit-client.ts +0 -521
  251. package/src/service/data-client.test.ts +0 -97
  252. package/src/service/data-client.ts +0 -58
  253. package/src/service/export-identity.ts +0 -39
  254. package/src/service/filter.ts +0 -40
  255. package/src/service/fire-and-forget.test.ts +0 -126
  256. package/src/service/fire-and-forget.ts +0 -79
  257. package/src/service/localhost-env-config.test.ts +0 -36
  258. package/src/service/organize-queue.ts +0 -98
  259. package/src/service/organize.test.ts +0 -1451
  260. package/src/service/organize.ts +0 -1025
  261. package/src/service/read-path-filter-config.test.ts +0 -243
  262. package/src/service/semantic-capability.test.ts +0 -78
  263. package/src/service/semantic-capability.ts +0 -95
  264. package/src/service/sender-category.test.ts +0 -235
  265. package/src/service/trigger-sync.test.ts +0 -205
  266. package/src/service/trigger-sync.ts +0 -100
  267. package/src/stdout-capture-fixture.ts +0 -40
  268. package/src/types.ts +0 -271
  269. package/tsconfig.json +0 -7
@@ -0,0 +1,330 @@
1
+ import { DEFAULT_CALENDAR_URL_SEGMENT, isResolvableZone, prepareCalendarObject, provisionDefaultCalendar, readCalendarFeed, readSubscriptionUrl, writeCalendarFeed, } from "@remit/calendar-service";
2
+ import { normalizeCalendarUrlSegment } from "@remit/data-ports/id";
3
+ import { CalendarSource } from "@remit/domain-enums";
4
+ import { getAccountConfigIdFromEvent } from "../auth.js";
5
+ import { defaultErrorCode } from "../error.js";
6
+ import { getClient } from "../service/data-client.js";
7
+ export const refuseCalendar = (code, message) => ({ ok: false, error: { code, message } });
8
+ /**
9
+ * `CalendarRefusal.code` is this module's and `@remit/calendar-service`'s own
10
+ * routing token, in PascalCase; the API's `code` vocabulary is snake_case
11
+ * (issue #371). Derived rather than mapped by hand, so a refusal added to
12
+ * either producer reaches the wire under its own name instead of silently
13
+ * collapsing into the status-class code.
14
+ */
15
+ const wireCode = (code) => code.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase();
16
+ /**
17
+ * A 400 keeps the refusal's own code — `unknown_time_zone` and
18
+ * `url_segment_taken` are what a client branches on, and the status class alone
19
+ * would not distinguish them. A 404 and a 412 have nothing to add to their
20
+ * status, so they take the shared token.
21
+ */
22
+ export const badRequest = (error) => ({
23
+ statusCode: 400,
24
+ body: { code: wireCode(error.code), message: error.message },
25
+ });
26
+ export const notFound = (message) => ({
27
+ statusCode: 404,
28
+ body: { code: defaultErrorCode(404), message },
29
+ });
30
+ export const preconditionFailed = (message) => ({
31
+ statusCode: 412,
32
+ body: { code: defaultErrorCode(412), message },
33
+ });
34
+ /** The calendar half of the client, named so a handler takes only what it uses. */
35
+ export const calendarDepsOf = (client) => ({
36
+ calendarCollection: client.calendarCollection,
37
+ calendarObject: client.calendarObject,
38
+ calendarEventIndex: client.calendarEventIndex,
39
+ calendarFeedToken: client.calendarFeedToken,
40
+ calendarStore: client.calendarStore,
41
+ });
42
+ const toCalendarResponse = (item) => ({
43
+ calendarId: item.calendarId,
44
+ accountConfigId: item.accountConfigId,
45
+ urlSegment: item.urlSegment,
46
+ displayName: item.displayName,
47
+ color: item.color,
48
+ componentSet: item.componentSet,
49
+ source: item.source,
50
+ timezone: item.timezone,
51
+ syncSequence: item.syncSequence,
52
+ subscriptionUrl: item.subscriptionUrl,
53
+ subscriptionEnabled: item.subscriptionEnabled,
54
+ subscriptionCheckedAt: item.subscriptionCheckedAt,
55
+ subscriptionFetchedAt: item.subscriptionFetchedAt,
56
+ subscriptionError: item.subscriptionError,
57
+ createdAt: item.createdAt,
58
+ updatedAt: item.updatedAt,
59
+ });
60
+ /**
61
+ * Every collection the account config holds, provisioning the default one when
62
+ * it holds none.
63
+ *
64
+ * Safe to race with itself: `calendarId` is derived from the account config and
65
+ * the URL segment, so two first reads arriving together write the same row
66
+ * rather than two, and the loser's write is a no-op instead of a second
67
+ * calendar nobody asked for.
68
+ */
69
+ export const listCalendarsFor = async (deps, accountConfigId) => {
70
+ const existing = await deps.calendarCollection.listByAccountConfig(accountConfigId);
71
+ if (existing.length > 0)
72
+ return existing;
73
+ await provisionDefaultCalendar(deps.calendarStore, accountConfigId);
74
+ return deps.calendarCollection.listByAccountConfig(accountConfigId);
75
+ };
76
+ /** One of the caller's collections, or a refusal naming the one they asked for. */
77
+ export const findCalendarFor = async (deps, accountConfigId, calendarId) => {
78
+ const collections = await deps.calendarCollection.listByAccountConfig(accountConfigId);
79
+ const found = collections.find((collection) => collection.calendarId === calendarId);
80
+ if (!found) {
81
+ return refuseCalendar("NotFound", `no calendar ${calendarId} on this account`);
82
+ }
83
+ return { ok: true, value: found };
84
+ };
85
+ /**
86
+ * One of the caller's collections that a person may write events into. A
87
+ * subscribed collection holds what its feed holds: an edit made here would be
88
+ * overwritten by the next refresh, so it is refused rather than accepted and
89
+ * silently lost.
90
+ */
91
+ export const findWritableCalendarFor = async (deps, accountConfigId, calendarId) => {
92
+ const found = await findCalendarFor(deps, accountConfigId, calendarId);
93
+ if (!found.ok)
94
+ return found;
95
+ if (found.value.source === CalendarSource.Subscribed) {
96
+ return refuseCalendar("ReadOnlyCalendar", `"${found.value.displayName}" is subscribed to a feed and is read-only — change the event where the feed comes from`);
97
+ }
98
+ return found;
99
+ };
100
+ /**
101
+ * A collection's timezone is what every floating time in it is read in, so a
102
+ * name this server cannot resolve is not a cosmetic setting — it silently moves
103
+ * every all-day and unzoned event in the calendar. A Windows zone name, which
104
+ * is what a client that has not normalised its input sends, is refused here
105
+ * rather than stored and quietly read as UTC.
106
+ */
107
+ export const readCollectionTimezone = (timezone) => {
108
+ if (timezone === undefined || timezone === "")
109
+ return { ok: true, value: "" };
110
+ if (!isResolvableZone(timezone)) {
111
+ return refuseCalendar("UnknownTimeZone", `"${timezone}" is not a time zone this server can resolve — use an IANA name such as "Europe/Amsterdam"`);
112
+ }
113
+ return { ok: true, value: timezone };
114
+ };
115
+ /**
116
+ * Creates a collection subscribed to a feed. The feed is read before anything
117
+ * is written, so an address that cannot be fetched leaves no empty calendar
118
+ * behind; its events then land through the one write path, in the same unit as
119
+ * the collection itself.
120
+ */
121
+ const createSubscribedCalendarFor = async (deps, accountConfigId, input, collection, fetcher, now) => {
122
+ const url = readSubscriptionUrl(input.subscriptionUrl);
123
+ if (!url.ok)
124
+ return url;
125
+ const feed = await readCalendarFeed(url.value, fetcher);
126
+ if (!feed.ok) {
127
+ return refuseCalendar("SubscriptionUnreachable", `the calendar was not created: ${feed.reason}`);
128
+ }
129
+ const { repos } = deps.calendarStore;
130
+ const made = await repos.calendarCollection.createExclusive({
131
+ accountConfigId,
132
+ urlSegment: collection.urlSegment,
133
+ displayName: input.displayName,
134
+ color: input.color,
135
+ timezone: collection.timezone,
136
+ source: CalendarSource.Subscribed,
137
+ subscriptionUrl: url.value,
138
+ subscriptionEnabled: true,
139
+ });
140
+ if (!made) {
141
+ return refuseCalendar("UrlSegmentTaken", `"${collection.urlSegment}" already addresses a calendar on this account — pick another`);
142
+ }
143
+ // A separate step from the create: a collection the feed write never
144
+ // reached is enabled and never checked, so the scheduled refresh takes it
145
+ // on its next pass and fills it from the same feed.
146
+ await writeCalendarFeed(deps.calendarStore, { accountConfigId, calendarId: made.calendarId }, feed.value, now);
147
+ return {
148
+ ok: true,
149
+ value: await repos.calendarCollection.get(accountConfigId, made.calendarId),
150
+ };
151
+ };
152
+ export const createCalendarFor = async (deps, accountConfigId, input, fetcher = fetch, now = Date.now()) => {
153
+ const urlSegment = normalizeCalendarUrlSegment(input.urlSegment);
154
+ if (urlSegment === "") {
155
+ return refuseCalendar("InvalidUrlSegment", "a calendar needs a url segment to be addressed by");
156
+ }
157
+ const timezone = readCollectionTimezone(input.timezone);
158
+ if (!timezone.ok)
159
+ return timezone;
160
+ const { subscriptionUrl } = input;
161
+ if (subscriptionUrl !== undefined) {
162
+ return createSubscribedCalendarFor(deps, accountConfigId, { ...input, subscriptionUrl }, { urlSegment, timezone: timezone.value }, fetcher, now);
163
+ }
164
+ // The write decides, not a prior read: two creates of one segment arriving
165
+ // together would both find it free, and the loser would silently be handed
166
+ // the winner's calendar to write into.
167
+ const created = await deps.calendarStore.repos.calendarCollection.createExclusive({
168
+ accountConfigId,
169
+ urlSegment,
170
+ displayName: input.displayName,
171
+ color: input.color,
172
+ timezone: timezone.value,
173
+ source: CalendarSource.UserCreated,
174
+ });
175
+ if (!created) {
176
+ return refuseCalendar("UrlSegmentTaken", `"${urlSegment}" already addresses a calendar on this account — pick another`);
177
+ }
178
+ return { ok: true, value: created };
179
+ };
180
+ /**
181
+ * Removes a collection with everything in it, in one unit.
182
+ *
183
+ * The default collection stays: it is where an accepted invitation and a first
184
+ * event land, and an account config with no calendar has nowhere to put one.
185
+ */
186
+ export const deleteCalendarFor = async (deps, accountConfigId, calendarId) => {
187
+ const collection = await findCalendarFor(deps, accountConfigId, calendarId);
188
+ if (!collection.ok)
189
+ return collection;
190
+ if (collection.value.source === CalendarSource.Default) {
191
+ return refuseCalendar("DefaultCalendarUndeletable", `"${DEFAULT_CALENDAR_URL_SEGMENT}" is the calendar this account files events into and cannot be removed`);
192
+ }
193
+ await deps.calendarStore.commit([
194
+ { kind: "DeleteCollection", accountConfigId, calendarId },
195
+ ]);
196
+ return { ok: true, value: null };
197
+ };
198
+ /**
199
+ * Reduce a PATCH body to the fields a collection update may set. `urlSegment`
200
+ * is deliberately absent: it is the collection's identity and the path a client
201
+ * has bookmarked, so moving it is making a different calendar.
202
+ */
203
+ export const pickCalendarUpdate = (body) => {
204
+ const patch = {};
205
+ if (Object.hasOwn(body, "displayName"))
206
+ patch.displayName = body.displayName;
207
+ if (Object.hasOwn(body, "color"))
208
+ patch.color = body.color;
209
+ if (Object.hasOwn(body, "timezone"))
210
+ patch.timezone = body.timezone;
211
+ if (Object.hasOwn(body, "subscriptionEnabled")) {
212
+ patch.subscriptionEnabled = body.subscriptionEnabled;
213
+ }
214
+ return patch;
215
+ };
216
+ /**
217
+ * Applies a collection patch, rewriting what the collection's timezone decides.
218
+ *
219
+ * The timezone is not a label. Every floating and all-day time in the
220
+ * collection is read in it, so changing it moves every occurrence row those
221
+ * resources produced — and a row left at the old zone is an event drawn hours
222
+ * from where the calendar now says it is. Each resource is therefore written
223
+ * again from its own stored bytes, which re-projects and re-expands it and
224
+ * bumps the collection's sequence so a syncing client sees the change. The
225
+ * whole set is one unit: a half-converted calendar is worse than either zone.
226
+ */
227
+ export const updateCalendarFor = async (deps, accountConfigId, calendarId, body) => {
228
+ const current = await findCalendarFor(deps, accountConfigId, calendarId);
229
+ if (!current.ok)
230
+ return current;
231
+ const patch = pickCalendarUpdate(body);
232
+ if (patch.subscriptionEnabled !== undefined &&
233
+ current.value.source !== CalendarSource.Subscribed) {
234
+ return refuseCalendar("NotSubscribed", `"${current.value.displayName}" is not subscribed to a feed, so there is no refresh to turn on or off`);
235
+ }
236
+ if (patch.timezone !== undefined) {
237
+ const timezone = readCollectionTimezone(patch.timezone);
238
+ if (!timezone.ok)
239
+ return timezone;
240
+ patch.timezone = timezone.value;
241
+ }
242
+ const rezone = patch.timezone !== undefined && patch.timezone !== current.value.timezone;
243
+ const { repos } = deps.calendarStore;
244
+ const rewrites = [];
245
+ if (rezone) {
246
+ const zone = { timezone: patch.timezone ?? current.value.timezone };
247
+ for (const object of await repos.calendarObject.listByCalendar(calendarId)) {
248
+ const rewritten = await prepareCalendarObject(zone, {
249
+ accountConfigId,
250
+ calendarId,
251
+ resourceName: object.resourceName,
252
+ icalData: object.icalData,
253
+ });
254
+ if (!rewritten.ok) {
255
+ throw new Error(`stored calendar object ${object.calendarObjectId} was refused on re-expansion: ${rewritten.error.code}`);
256
+ }
257
+ rewrites.push({
258
+ ...rewritten.value,
259
+ kind: "ReprojectObject",
260
+ readEtag: object.etag,
261
+ });
262
+ }
263
+ }
264
+ await deps.calendarStore.commit([
265
+ { kind: "UpdateCollection", accountConfigId, calendarId, patch },
266
+ ...rewrites,
267
+ ]);
268
+ return {
269
+ ok: true,
270
+ value: await repos.calendarCollection.get(accountConfigId, calendarId),
271
+ };
272
+ };
273
+ export const CalendarOperations = {
274
+ CalendarOperations_listCalendars: async (_context, ...args) => {
275
+ const event = args[0];
276
+ const accountConfigId = getAccountConfigIdFromEvent(event);
277
+ const deps = calendarDepsOf(await getClient());
278
+ const items = await listCalendarsFor(deps, accountConfigId);
279
+ return { items: items.map(toCalendarResponse) };
280
+ },
281
+ CalendarOperations_createCalendar: async (context, ...args) => {
282
+ const event = args[0];
283
+ const accountConfigId = getAccountConfigIdFromEvent(event);
284
+ const input = context.request.requestBody;
285
+ const deps = calendarDepsOf(await getClient());
286
+ const created = await createCalendarFor(deps, accountConfigId, input);
287
+ if (!created.ok)
288
+ return badRequest(created.error);
289
+ return toCalendarResponse(created.value);
290
+ },
291
+ };
292
+ export const CalendarDetailOperations = {
293
+ CalendarDetailOperations_getCalendar: async (context, ...args) => {
294
+ const event = args[0];
295
+ const accountConfigId = getAccountConfigIdFromEvent(event);
296
+ const { calendarId } = context.request.params;
297
+ const deps = calendarDepsOf(await getClient());
298
+ const found = await findCalendarFor(deps, accountConfigId, calendarId);
299
+ if (!found.ok)
300
+ return notFound(found.error.message);
301
+ return toCalendarResponse(found.value);
302
+ },
303
+ CalendarDetailOperations_updateCalendar: async (context, ...args) => {
304
+ const event = args[0];
305
+ const accountConfigId = getAccountConfigIdFromEvent(event);
306
+ const { calendarId } = context.request.params;
307
+ const body = context.request.requestBody;
308
+ const deps = calendarDepsOf(await getClient());
309
+ const updated = await updateCalendarFor(deps, accountConfigId, calendarId, body);
310
+ if (!updated.ok) {
311
+ return updated.error.code === "NotFound"
312
+ ? notFound(updated.error.message)
313
+ : badRequest(updated.error);
314
+ }
315
+ return toCalendarResponse(updated.value);
316
+ },
317
+ CalendarDetailOperations_deleteCalendar: async (context, ...args) => {
318
+ const event = args[0];
319
+ const accountConfigId = getAccountConfigIdFromEvent(event);
320
+ const { calendarId } = context.request.params;
321
+ const deps = calendarDepsOf(await getClient());
322
+ const removed = await deleteCalendarFor(deps, accountConfigId, calendarId);
323
+ if (!removed.ok) {
324
+ return removed.error.code === "NotFound"
325
+ ? notFound(removed.error.message)
326
+ : badRequest(removed.error);
327
+ }
328
+ return { statusCode: 204 };
329
+ },
330
+ };
@@ -0,0 +1,43 @@
1
+ import type { SQSClient } from "@aws-sdk/client-sqs";
2
+ import { type StoredCredentialFields } from "@remit/mailbox-service/account-credentials";
3
+ import type { ConfigOperationIds, OperationHandler } from "../types.js";
4
+ type StructuredLog = (fields: Record<string, unknown>, message: string) => void;
5
+ interface ConfigSyncTriggerDeps {
6
+ sqsClient: SQSClient;
7
+ queueUrl: string;
8
+ logger: {
9
+ info: StructuredLog;
10
+ error: StructuredLog;
11
+ };
12
+ }
13
+ /**
14
+ * Fire-and-forget sync trigger for the accounts surfaced by GET /config.
15
+ *
16
+ * GET /config is a READ: its response is already computed and does not depend
17
+ * on the trigger succeeding. A failure here (the SQS queue unreachable in
18
+ * smoke/e2e, an IAM/SQS misconfig in prod) must therefore never reach the read
19
+ * response — but it also silently stops ALL sync, so it has to be loud and
20
+ * alertable rather than swallowed.
21
+ *
22
+ * This helper is fully self-contained: it catches every per-account rejection
23
+ * internally and resolves to void, so the caller can `void`-fire it with no
24
+ * chance of an unhandled rejection escaping. The dev/Lambda runtime shares one
25
+ * event loop, so an escaped rejection lands on whatever request is active when
26
+ * the deferred SQS retry finally fails — which is how a `/config` enqueue
27
+ * failure ended up 500-ing unrelated reads like `/outbox` and `/threads`.
28
+ *
29
+ * Each failure is logged as a distinct structured error carrying the SDK error
30
+ * name/code on dedicated fields plus a stable `alert: "sync_trigger_failed"`
31
+ * discriminator a CloudWatch metric filter / alarm can key off.
32
+ *
33
+ * An account storing no credential is not enqueued at all (issue #1120): the
34
+ * import wizard lands accounts without a password by design, and the client
35
+ * polls this read while the user is still typing one. The guard is the stored
36
+ * credential rather than `connectionState`, which stays `credentials_missing`
37
+ * until a connect succeeds — see `hasStoredCredential`.
38
+ */
39
+ export declare const triggerConfigLoadSyncs: (accountConfigId: string, accounts: ReadonlyArray<{
40
+ accountId: string;
41
+ } & StoredCredentialFields>, deps?: ConfigSyncTriggerDeps) => Promise<void>;
42
+ export declare const ConfigOperations: Record<ConfigOperationIds, OperationHandler<ConfigOperationIds>>;
43
+ export {};
@@ -0,0 +1,176 @@
1
+ import { importConfig, pendingImportOf, readConfigForExport, } from "@remit/config-transfer";
2
+ import { ConfigNotEmptyError, NotFoundError } from "@remit/data-ports/errors";
3
+ import { logger } from "@remit/logger";
4
+ import { hasStoredCredential, } from "@remit/mailbox-service/account-credentials";
5
+ import { env } from "expect-env";
6
+ import { getAccountConfigIdFromEvent, getSubFromEvent } from "../auth.js";
7
+ import { getClient } from "../service/data-client.js";
8
+ import { exportIdentity } from "../service/export-identity.js";
9
+ import { fireAndForget } from "../service/fire-and-forget.js";
10
+ import { sqsClient } from "../service/sqs.js";
11
+ import { triggerAccountSync } from "../service/trigger-sync.js";
12
+ import { toAccountResponse } from "./account-guards.js";
13
+ import { groupAccountOverrides, } from "./account-overrides.js";
14
+ import { groupSignaturesByAccount, } from "./account-signature.js";
15
+ import { groupFolderAppointmentsByAccount, resolveFolderAppointments, writeFolderRoleAppointment, } from "./folder-role-appointments.js";
16
+ const defaultConfigSyncTriggerDeps = () => ({
17
+ sqsClient,
18
+ queueUrl: env.SQS_QUEUE_URL,
19
+ logger,
20
+ });
21
+ /**
22
+ * Fire-and-forget sync trigger for the accounts surfaced by GET /config.
23
+ *
24
+ * GET /config is a READ: its response is already computed and does not depend
25
+ * on the trigger succeeding. A failure here (the SQS queue unreachable in
26
+ * smoke/e2e, an IAM/SQS misconfig in prod) must therefore never reach the read
27
+ * response — but it also silently stops ALL sync, so it has to be loud and
28
+ * alertable rather than swallowed.
29
+ *
30
+ * This helper is fully self-contained: it catches every per-account rejection
31
+ * internally and resolves to void, so the caller can `void`-fire it with no
32
+ * chance of an unhandled rejection escaping. The dev/Lambda runtime shares one
33
+ * event loop, so an escaped rejection lands on whatever request is active when
34
+ * the deferred SQS retry finally fails — which is how a `/config` enqueue
35
+ * failure ended up 500-ing unrelated reads like `/outbox` and `/threads`.
36
+ *
37
+ * Each failure is logged as a distinct structured error carrying the SDK error
38
+ * name/code on dedicated fields plus a stable `alert: "sync_trigger_failed"`
39
+ * discriminator a CloudWatch metric filter / alarm can key off.
40
+ *
41
+ * An account storing no credential is not enqueued at all (issue #1120): the
42
+ * import wizard lands accounts without a password by design, and the client
43
+ * polls this read while the user is still typing one. The guard is the stored
44
+ * credential rather than `connectionState`, which stays `credentials_missing`
45
+ * until a connect succeeds — see `hasStoredCredential`.
46
+ */
47
+ export const triggerConfigLoadSyncs = async (accountConfigId, accounts, deps = defaultConfigSyncTriggerDeps()) => {
48
+ await Promise.all(accounts.filter(hasStoredCredential).map(({ accountId }) => fireAndForget(async () => {
49
+ const { eventId } = await triggerAccountSync({
50
+ sqsClient: deps.sqsClient,
51
+ queueUrl: deps.queueUrl,
52
+ accountId,
53
+ });
54
+ deps.logger.info({ accountId, eventId }, "Sync triggered on config load");
55
+ }, {
56
+ source: "config_load",
57
+ message: "Failed to trigger account sync on config load",
58
+ ids: { accountId, accountConfigId },
59
+ logger: deps.logger,
60
+ })));
61
+ };
62
+ const toAccountConfigResponse = (config) => ({
63
+ accountConfigId: config.accountConfigId,
64
+ userId: config.userId,
65
+ name: config.name,
66
+ state: (config.state ??
67
+ "active"),
68
+ createdAt: config.createdAt,
69
+ updatedAt: config.updatedAt,
70
+ });
71
+ const buildCommit = () => process.env.REMIT_WORKER_SHA || process.env.GITHUB_SHA || "dev";
72
+ /**
73
+ * Returned by GET /config when no AccountConfig row exists yet for this user.
74
+ * GET must never mutate state, so instead of creating a row we synthesize a
75
+ * stable, empty shape the frontend can render as a "no accounts yet" state.
76
+ * The POST account-creation flow will materialize the real row when the user
77
+ * adds their first account.
78
+ */
79
+ const emptyConfigResponse = (accountConfigId, event) => {
80
+ const now = Date.now();
81
+ const userId = getSubFromEvent(event) ?? accountConfigId;
82
+ return {
83
+ accountConfig: {
84
+ accountConfigId,
85
+ userId,
86
+ state: "active",
87
+ createdAt: now,
88
+ updatedAt: now,
89
+ },
90
+ accounts: [],
91
+ buildCommit: buildCommit(),
92
+ };
93
+ };
94
+ export const ConfigOperations = {
95
+ ConfigOperations_getConfig: async (_context, ...args) => {
96
+ const event = args[0];
97
+ const accountConfigId = getAccountConfigIdFromEvent(event);
98
+ const client = await getClient();
99
+ const description = await client.accountConfig
100
+ .describe(accountConfigId)
101
+ .catch((err) => {
102
+ if (err instanceof NotFoundError)
103
+ return undefined;
104
+ throw err;
105
+ });
106
+ if (!description || description.accountConfig.length === 0) {
107
+ return emptyConfigResponse(accountConfigId, event);
108
+ }
109
+ const accountConfig = description.accountConfig[0];
110
+ if (!accountConfig) {
111
+ return emptyConfigResponse(accountConfigId, event);
112
+ }
113
+ // Filter out deleted accounts (tombstone pattern)
114
+ const activeAccounts = description.account.filter((acc) => acc.deletedAt === undefined);
115
+ // Signatures and the display-name/mute overrides are stored per-account in
116
+ // AccountSetting rows (RFC 032). Load the whole set for this config once and
117
+ // key both by accountId so the account mapping below surfaces each without
118
+ // an N+1. The per-account folder-role map (RFC 032
119
+ // exclusive-folder-appointment, #976) rides the same settings rows, grouped
120
+ // the same way.
121
+ const allSettings = await client.accountSetting.listByAccountConfig(accountConfigId);
122
+ const signaturesByAccount = groupSignaturesByAccount(allSettings);
123
+ const overridesByAccount = groupAccountOverrides(allSettings);
124
+ const appointmentsByAccount = groupFolderAppointmentsByAccount(allSettings);
125
+ const signatureOf = (accountId) => signaturesByAccount.get(accountId) ?? {};
126
+ const overridesOf = (accountId) => overridesByAccount.get(accountId) ?? {};
127
+ // One mailbox list per account, fetched in parallel: `findFolderForRole`
128
+ // needs each account's folders to fill any role the user hasn't appointed
129
+ // yet (RFC 032: "the map is never empty for a normal provider").
130
+ const mailboxesByAccount = new Map(await Promise.all(activeAccounts.map(async (acc) => [
131
+ acc.accountId,
132
+ await client.mailbox.listAllByAccount(acc.accountId),
133
+ ])));
134
+ // Fire-and-forget: a failed sync enqueue must never fail this read.
135
+ // triggerConfigLoadSyncs swallows nothing — it logs each failure loudly
136
+ // with an alertable structured field — but it also never rejects, so the
137
+ // `void` here cannot leak an unhandled rejection into a later request.
138
+ void triggerConfigLoadSyncs(accountConfigId, activeAccounts);
139
+ // An import that named folders IMAP had not produced yet rides the config
140
+ // read rather than a route of its own, so nothing has to poll for it.
141
+ const pendingImport = pendingImportOf(await client.configImport.listByAccountConfig(accountConfigId));
142
+ return {
143
+ accountConfig: toAccountConfigResponse(accountConfig),
144
+ ...(pendingImport ? { pendingImport } : {}),
145
+ buildCommit: buildCommit(),
146
+ accounts: activeAccounts.map((acc) => toAccountResponse(acc, signatureOf(acc.accountId), overridesOf(acc.accountId), resolveFolderAppointments(appointmentsByAccount.get(acc.accountId) ?? new Map(), mailboxesByAccount.get(acc.accountId) ?? []))),
147
+ };
148
+ },
149
+ ConfigOperations_exportConfig: async (_context, ...args) => {
150
+ const event = args[0];
151
+ const accountConfigId = getAccountConfigIdFromEvent(event);
152
+ const client = await getClient();
153
+ const document = await readConfigForExport(client, accountConfigId, exportIdentity());
154
+ return { schemaVersion: document.schemaVersion, document };
155
+ },
156
+ ConfigOperations_importConfig: async (context, ...args) => {
157
+ const event = args[0];
158
+ const accountConfigId = getAccountConfigIdFromEvent(event);
159
+ const body = (context.request.requestBody ?? {});
160
+ const client = await getClient();
161
+ const outcome = await importConfig({
162
+ repositories: client,
163
+ appointFolderRole: (configId, accountId, role, mailboxId, lastKnownPath) => writeFolderRoleAppointment(client.accountSetting, configId, accountId, role, mailboxId, lastKnownPath),
164
+ }, {
165
+ accountConfigId,
166
+ userId: getSubFromEvent(event) ?? accountConfigId,
167
+ document: body.document,
168
+ mode: body.mode ?? "validate",
169
+ onExisting: body.onExisting ?? "abort",
170
+ });
171
+ if (outcome.outcome === "conflict") {
172
+ throw new ConfigNotEmptyError(outcome.conflict.message, outcome.conflict.details);
173
+ }
174
+ return outcome.report;
175
+ },
176
+ };
@@ -0,0 +1,9 @@
1
+ import type { IAccountConfigRepository } from "@remit/data-ports";
2
+ /**
3
+ * Ensure an AccountConfig row exists for the given id. A first-time caller
4
+ * coming from Cognito will not yet have one; subsequent calls are idempotent.
5
+ *
6
+ * We attempt a read first to avoid relying on a race on `create()` — the
7
+ * deterministic id (derived from Cognito `sub`) makes both paths safe.
8
+ */
9
+ export declare const ensureAccountConfig: (accountConfig: IAccountConfigRepository, accountConfigId: string) => Promise<void>;
@@ -0,0 +1,27 @@
1
+ import { ConflictError, NotFoundError } from "@remit/data-ports/errors";
2
+ /**
3
+ * Ensure an AccountConfig row exists for the given id. A first-time caller
4
+ * coming from Cognito will not yet have one; subsequent calls are idempotent.
5
+ *
6
+ * We attempt a read first to avoid relying on a race on `create()` — the
7
+ * deterministic id (derived from Cognito `sub`) makes both paths safe.
8
+ */
9
+ export const ensureAccountConfig = async (accountConfig, accountConfigId) => {
10
+ const existing = await accountConfig.get(accountConfigId).catch((err) => {
11
+ if (err instanceof NotFoundError)
12
+ return undefined;
13
+ throw err;
14
+ });
15
+ if (existing)
16
+ return;
17
+ await accountConfig
18
+ .create({
19
+ accountConfigId,
20
+ userId: accountConfigId,
21
+ })
22
+ .catch((err) => {
23
+ if (err instanceof ConflictError)
24
+ return;
25
+ throw err;
26
+ });
27
+ };
@@ -0,0 +1,3 @@
1
+ import type { FilterDetailOperationIds, FilterOperationIds, OperationHandler } from "../types.js";
2
+ export declare const FilterOperations: Record<FilterOperationIds, OperationHandler<FilterOperationIds>>;
3
+ export declare const FilterDetailOperations: Record<FilterDetailOperationIds, OperationHandler<FilterDetailOperationIds>>;