@remit/backend 0.0.143 → 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 -522
  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,28 @@
1
+ import type { AccountSettingItem, IAccountSettingRepository } from "@remit/data-ports";
2
+ export interface AccountSignature {
3
+ plainText?: string;
4
+ html?: string;
5
+ }
6
+ /**
7
+ * Build a per-account signature lookup from the whole settings set of one
8
+ * account configuration. Signatures are stored as composite-named rows
9
+ * (`AccountSignaturePlainText#<accountId>` / `AccountSignatureHtml#<accountId>`),
10
+ * so one `listByAccountConfig` query yields every account's signature; this
11
+ * groups them by the `#<accountId>` suffix.
12
+ */
13
+ export declare const groupSignaturesByAccount: (settings: AccountSettingItem[]) => Map<string, AccountSignature>;
14
+ /**
15
+ * Resolve the signature for a single account by reading just its two composite
16
+ * rows. Used by the account create/update handlers, which act on one account.
17
+ */
18
+ export declare const loadSignatureForAccount: (accountSetting: IAccountSettingRepository, accountConfigId: string, accountId: string) => Promise<AccountSignature>;
19
+ /**
20
+ * Idempotent upsert of an account's signature fields. Only writes the parts the
21
+ * caller supplied — an empty string is a valid stored value (it clears the
22
+ * displayed signature without removing the row), matching the prior PATCH
23
+ * semantics where setting `""` stored `""`.
24
+ */
25
+ export declare const upsertAccountSignature: (accountSetting: IAccountSettingRepository, accountConfigId: string, accountId: string, signature: {
26
+ plainText?: string;
27
+ html?: string;
28
+ }) => Promise<void>;
@@ -0,0 +1,85 @@
1
+ import { baseSettingName, composeSettingName, SETTING_NAME_SEPARATOR, } from "@remit/data-ports/account-settings";
2
+ const SIGNATURE_NAMES = {
3
+ plainText: "AccountSignaturePlainText",
4
+ html: "AccountSignatureHtml",
5
+ };
6
+ const stringValueOf = (item) => {
7
+ const { value } = item;
8
+ if (value.kind === "String")
9
+ return value.value;
10
+ return undefined;
11
+ };
12
+ const accountIdOf = (name) => {
13
+ const idx = name.indexOf(SETTING_NAME_SEPARATOR);
14
+ if (idx === -1)
15
+ return undefined;
16
+ return name.slice(idx + SETTING_NAME_SEPARATOR.length) || undefined;
17
+ };
18
+ /**
19
+ * Build a per-account signature lookup from the whole settings set of one
20
+ * account configuration. Signatures are stored as composite-named rows
21
+ * (`AccountSignaturePlainText#<accountId>` / `AccountSignatureHtml#<accountId>`),
22
+ * so one `listByAccountConfig` query yields every account's signature; this
23
+ * groups them by the `#<accountId>` suffix.
24
+ */
25
+ export const groupSignaturesByAccount = (settings) => {
26
+ const byAccount = new Map();
27
+ for (const setting of settings) {
28
+ const accountId = accountIdOf(setting.name);
29
+ if (!accountId)
30
+ continue;
31
+ const base = baseSettingName(setting.name);
32
+ const text = stringValueOf(setting);
33
+ if (text === undefined)
34
+ continue;
35
+ const current = byAccount.get(accountId) ?? {};
36
+ if (base === SIGNATURE_NAMES.plainText)
37
+ current.plainText = text;
38
+ if (base === SIGNATURE_NAMES.html)
39
+ current.html = text;
40
+ byAccount.set(accountId, current);
41
+ }
42
+ return byAccount;
43
+ };
44
+ /**
45
+ * Resolve the signature for a single account by reading just its two composite
46
+ * rows. Used by the account create/update handlers, which act on one account.
47
+ */
48
+ export const loadSignatureForAccount = async (accountSetting, accountConfigId, accountId) => {
49
+ const [plain, html] = await Promise.all([
50
+ accountSetting.get(accountConfigId, composeSettingName(SIGNATURE_NAMES.plainText, accountId)),
51
+ accountSetting.get(accountConfigId, composeSettingName(SIGNATURE_NAMES.html, accountId)),
52
+ ]);
53
+ const signature = {};
54
+ const plainText = plain ? stringValueOf(plain) : undefined;
55
+ const htmlText = html ? stringValueOf(html) : undefined;
56
+ if (plainText !== undefined)
57
+ signature.plainText = plainText;
58
+ if (htmlText !== undefined)
59
+ signature.html = htmlText;
60
+ return signature;
61
+ };
62
+ /**
63
+ * Idempotent upsert of an account's signature fields. Only writes the parts the
64
+ * caller supplied — an empty string is a valid stored value (it clears the
65
+ * displayed signature without removing the row), matching the prior PATCH
66
+ * semantics where setting `""` stored `""`.
67
+ */
68
+ export const upsertAccountSignature = async (accountSetting, accountConfigId, accountId, signature) => {
69
+ const writes = [];
70
+ if (signature.plainText !== undefined) {
71
+ writes.push(accountSetting.upsert({
72
+ accountConfigId,
73
+ name: composeSettingName(SIGNATURE_NAMES.plainText, accountId),
74
+ value: { kind: "String", value: signature.plainText },
75
+ }));
76
+ }
77
+ if (signature.html !== undefined) {
78
+ writes.push(accountSetting.upsert({
79
+ accountConfigId,
80
+ name: composeSettingName(SIGNATURE_NAMES.html, accountId),
81
+ value: { kind: "String", value: signature.html },
82
+ }));
83
+ }
84
+ await Promise.all(writes);
85
+ };
@@ -0,0 +1,6 @@
1
+ import type { AccountDetailOperationIds, AccountOperationIds, OperationHandler } from "../types.js";
2
+ import { assertNotOAuthCreate, assertPasswordProvided, toAccountResponse } from "./account-guards.js";
3
+ export { assertNotOAuthCreate, assertPasswordProvided, toAccountResponse };
4
+ export declare const triggerAccountSyncSafe: (accountId: string) => Promise<void>;
5
+ export declare const AccountOperations: Record<AccountOperationIds, OperationHandler<AccountOperationIds>>;
6
+ export declare const AccountDetailOperations: Record<AccountDetailOperationIds, OperationHandler<AccountDetailOperationIds>>;
@@ -0,0 +1,350 @@
1
+ import { AccountAuthType, AccountService, ConnectionState, } from "@remit/domain-enums";
2
+ import { logger } from "@remit/logger";
3
+ import { createMailOAuthService, microsoftProviderConfig, RefreshTokenError, } from "@remit/mail-oauth-service";
4
+ import { ownedAccount, resolveConnectionCredentials, testImapConnection, testSmtpConnection, } from "@remit/mailbox-service";
5
+ import { deserializeEncryptedPayload, serializeEncryptedPayload, } from "@remit/secrets-service";
6
+ import { env } from "expect-env";
7
+ import { getAccountConfigIdFromEvent } from "../auth.js";
8
+ import { deleteAccount } from "../service/account-deletion.js";
9
+ import { getClient } from "../service/data-client.js";
10
+ import { fireAndForget } from "../service/fire-and-forget.js";
11
+ import { unwrap } from "../service/refusal.js";
12
+ import { sqsClient } from "../service/sqs.js";
13
+ import { triggerAccountSync } from "../service/trigger-sync.js";
14
+ import { assertNoDuplicateMailbox, assertNotOAuthCreate, assertPasswordProvided, resolveSyncedServices, toAccountResponse, } from "./account-guards.js";
15
+ import { loadAccountOverrides, upsertAccountDisplayName, writeAccountComposeLanguages, writeAccountMuted, } from "./account-overrides.js";
16
+ import { loadSignatureForAccount, upsertAccountSignature, } from "./account-signature.js";
17
+ import { ensureAccountConfig } from "./ensure-account-config.js";
18
+ import { resolveAccountFolderAppointments } from "./folder-role-appointments.js";
19
+ export { assertNotOAuthCreate, assertPasswordProvided, toAccountResponse };
20
+ export const triggerAccountSyncSafe = async (accountId) => {
21
+ const queueUrl = env.SQS_QUEUE_URL;
22
+ // Best-effort: account creation must still return 200 even if the sync
23
+ // enqueue fails. fireAndForget catches and logs every rejection loudly with
24
+ // the alertable structured fields and never rejects, so a failure here (SQS
25
+ // unreachable in smoke/e2e, an IAM/SQS misconfig in prod) cannot leak an
26
+ // unhandled rejection onto an unrelated in-flight request.
27
+ await fireAndForget(async () => {
28
+ const { eventId } = await triggerAccountSync({
29
+ sqsClient,
30
+ queueUrl,
31
+ accountId,
32
+ });
33
+ // biome-ignore lint/plugin/no-logger-info: sync-triggered-for-new-account is an audit-grade signal
34
+ logger.info({ accountId, eventId }, "Sync triggered for new account");
35
+ }, {
36
+ source: "account_create",
37
+ message: "Failed to enqueue SYNC_MAILBOXES for new account (best-effort)",
38
+ ids: { accountId },
39
+ });
40
+ };
41
+ /**
42
+ * Test connectivity for an OAuth (Microsoft) account.
43
+ *
44
+ * Mints an access token from the stored refresh token via
45
+ * resolveConnectionCredentials (the single authType branch), then runs the
46
+ * IMAP — and, when configured, SMTP — connection tests with those credentials.
47
+ *
48
+ * A revoked / expired refresh token surfaces as RefreshTokenError; the
49
+ * reauth-required case is mapped to the distinct `reauth_required` error code
50
+ * so the UI can route the user into the OAuth re-auth flow.
51
+ *
52
+ * MSOAUTH_* env vars are only present in deployed Lambdas; fall back to "".
53
+ */
54
+ const testOAuthConnection = async (existingAccount, account, secrets) => {
55
+ const tokenService = createMailOAuthService(microsoftProviderConfig({
56
+ clientId: process.env.MSOAUTH_CLIENT_ID ?? "",
57
+ clientSecret: process.env.MSOAUTH_CLIENT_SECRET ?? "",
58
+ overrides: process.env.MSOAUTH_TOKEN_ENDPOINT
59
+ ? { tokenEndpoint: process.env.MSOAUTH_TOKEN_ENDPOINT }
60
+ : undefined,
61
+ }));
62
+ let resolution;
63
+ try {
64
+ resolution = await resolveConnectionCredentials(existingAccount, {
65
+ secrets,
66
+ tokenService,
67
+ persistRotatedToken: async (id, encryptedHash, updatedAt) => {
68
+ await account.update(id, {
69
+ oauthRefreshTokenHash: encryptedHash,
70
+ oauthTokenUpdatedAt: updatedAt,
71
+ });
72
+ },
73
+ });
74
+ }
75
+ catch (err) {
76
+ if (err instanceof RefreshTokenError &&
77
+ err.error.kind === "reauth-required") {
78
+ return {
79
+ imapSuccess: false,
80
+ imapError: "reauth_required",
81
+ smtpSuccess: undefined,
82
+ };
83
+ }
84
+ throw err;
85
+ }
86
+ if (resolution.status === "missing") {
87
+ return {
88
+ imapSuccess: false,
89
+ imapError: "oauth_not_configured",
90
+ smtpSuccess: undefined,
91
+ };
92
+ }
93
+ const credentials = resolution.credentials;
94
+ const result = {
95
+ imapSuccess: false,
96
+ smtpSuccess: undefined,
97
+ };
98
+ const imapResult = await testImapConnection({
99
+ host: existingAccount.imapHost,
100
+ port: existingAccount.imapPort,
101
+ secure: existingAccount.imapTls,
102
+ user: existingAccount.username,
103
+ credentials,
104
+ });
105
+ result.imapSuccess = imapResult.success;
106
+ if (!imapResult.success) {
107
+ result.imapError = imapResult.error;
108
+ }
109
+ // OAuth accounts share the same access token for IMAP and SMTP.
110
+ if (existingAccount.smtpEnabled) {
111
+ const smtpResult = await testSmtpConnection({
112
+ host: existingAccount.smtpHost ?? "",
113
+ port: existingAccount.smtpPort ?? 587,
114
+ secure: existingAccount.smtpTls ?? false,
115
+ user: existingAccount.smtpUsername || existingAccount.username,
116
+ credentials,
117
+ });
118
+ result.smtpSuccess = smtpResult.success;
119
+ if (!smtpResult.success) {
120
+ result.smtpError = smtpResult.error;
121
+ }
122
+ }
123
+ return result;
124
+ };
125
+ export const AccountOperations = {
126
+ AccountOperations_createAccount: async (_context, ...args) => {
127
+ const event = args[0];
128
+ const accountConfigId = getAccountConfigIdFromEvent(event);
129
+ const input = JSON.parse(event.body ?? "{}");
130
+ // OAuth accounts must be created via the dedicated connect flow
131
+ assertNotOAuthCreate(input.authType);
132
+ // Password accounts require a non-empty password
133
+ assertPasswordProvided(input.authType, input.password);
134
+ const syncedServices = resolveSyncedServices({ authType: AccountAuthType.Password, grantedScopes: [] }, input.syncedServices ?? [AccountService.Mail]);
135
+ const { account, accountConfig, accountSetting, mailbox, secrets } = await getClient();
136
+ await ensureAccountConfig(accountConfig, accountConfigId);
137
+ // Reject re-onboarding the same mailbox-in-the-same-place. Message
138
+ // identity is account-scoped (#633), so duplicate onboards are no longer
139
+ // incidentally deduped — this is the explicit replacement (#635).
140
+ const existingAccounts = await account.listAllByAccountConfig(accountConfigId);
141
+ assertNoDuplicateMailbox(existingAccounts, {
142
+ imapHost: input.imapHost,
143
+ username: input.username ?? input.email,
144
+ });
145
+ // biome-ignore lint/style/noNonNullAssertion: guard above ensures password is set for password-auth accounts
146
+ const passwordPayload = await secrets.encrypt(input.password);
147
+ const passwordHash = JSON.stringify(serializeEncryptedPayload(passwordPayload));
148
+ let smtpPasswordHash;
149
+ if (input.smtpPassword) {
150
+ const smtpPayload = await secrets.encrypt(input.smtpPassword);
151
+ smtpPasswordHash = JSON.stringify(serializeEncryptedPayload(smtpPayload));
152
+ }
153
+ const newAccount = await account.create({
154
+ accountConfigId,
155
+ email: input.email,
156
+ username: input.username ?? input.email,
157
+ authType: AccountAuthType.Password,
158
+ syncedServices,
159
+ passwordHash,
160
+ imapHost: input.imapHost,
161
+ imapPort: input.imapPort,
162
+ imapTls: input.imapTls,
163
+ imapStartTls: input.imapStartTls,
164
+ // RFC 032 Tier 2: smtpEnabled is the explicit send-capability marker.
165
+ // Honour an explicit flag from the client; otherwise enable sending when
166
+ // an SMTP host was supplied (the prior implicit behaviour).
167
+ smtpEnabled: input.smtpEnabled ?? Boolean(input.smtpHost),
168
+ smtpHost: input.smtpHost,
169
+ smtpPort: input.smtpPort,
170
+ smtpTls: input.smtpTls,
171
+ smtpStartTls: input.smtpStartTls,
172
+ smtpUsername: input.smtpUsername,
173
+ smtpPasswordHash,
174
+ isActive: true,
175
+ connectionState: ConnectionState.NotAuthenticated,
176
+ });
177
+ // Display name lives in a per-account AccountSetting row (RFC 032), not on
178
+ // the entity. Persist it when supplied so the response and later reads
179
+ // surface it unchanged.
180
+ if (input.displayName !== undefined) {
181
+ await upsertAccountDisplayName(accountSetting, accountConfigId, newAccount.accountId, input.displayName);
182
+ }
183
+ await triggerAccountSyncSafe(newAccount.accountId);
184
+ const [overrides, folderAppointments] = await Promise.all([
185
+ loadAccountOverrides(accountSetting, accountConfigId, newAccount.accountId),
186
+ resolveAccountFolderAppointments({ mailbox, accountSetting }, accountConfigId, newAccount.accountId),
187
+ ]);
188
+ return toAccountResponse(newAccount, {}, overrides, folderAppointments);
189
+ },
190
+ AccountOperations_testConnection: async (_context, ...args) => {
191
+ const event = args[0];
192
+ const accountConfigId = getAccountConfigIdFromEvent(event);
193
+ const input = JSON.parse(event.body ?? "{}");
194
+ const { account, secrets } = await getClient();
195
+ // Resolve password - use provided password or decrypt stored password
196
+ let imapPassword = input.password;
197
+ let smtpPassword = input.smtpPassword;
198
+ if (!imapPassword && input.accountId) {
199
+ const existingAccount = await account.get(input.accountId);
200
+ unwrap(ownedAccount(existingAccount, accountConfigId, "read"));
201
+ const authType = existingAccount.authType ?? "password";
202
+ if (authType === "oauthMicrosoft") {
203
+ return testOAuthConnection(existingAccount, account, secrets);
204
+ }
205
+ if (existingAccount.passwordHash) {
206
+ const payload = deserializeEncryptedPayload(JSON.parse(existingAccount.passwordHash));
207
+ imapPassword = await secrets.decrypt(payload);
208
+ }
209
+ // Also get SMTP password if needed and available
210
+ if (!smtpPassword && existingAccount.smtpPasswordHash) {
211
+ const smtpPayload = deserializeEncryptedPayload(JSON.parse(existingAccount.smtpPasswordHash));
212
+ smtpPassword = await secrets.decrypt(smtpPayload);
213
+ }
214
+ }
215
+ if (!imapPassword) {
216
+ return {
217
+ imapSuccess: false,
218
+ imapError: "Password required",
219
+ smtpSuccess: undefined,
220
+ };
221
+ }
222
+ const result = {
223
+ imapSuccess: false,
224
+ smtpSuccess: undefined,
225
+ };
226
+ // Test IMAP connection
227
+ const imapResult = await testImapConnection({
228
+ host: input.imapHost,
229
+ port: input.imapPort,
230
+ secure: input.imapTls,
231
+ startTls: input.imapStartTls,
232
+ user: input.username,
233
+ credentials: { kind: "password", password: imapPassword },
234
+ });
235
+ result.imapSuccess = imapResult.success;
236
+ if (!imapResult.success) {
237
+ result.imapError = imapResult.error;
238
+ }
239
+ // Test SMTP connection if configured
240
+ if (input.smtpHost) {
241
+ const smtpResult = await testSmtpConnection({
242
+ host: input.smtpHost,
243
+ port: input.smtpPort ?? 587,
244
+ secure: input.smtpTls ?? false,
245
+ user: input.smtpUsername ?? input.username,
246
+ credentials: {
247
+ kind: "password",
248
+ password: smtpPassword ?? imapPassword,
249
+ },
250
+ });
251
+ result.smtpSuccess = smtpResult.success;
252
+ if (!smtpResult.success) {
253
+ result.smtpError = smtpResult.error;
254
+ }
255
+ }
256
+ return result;
257
+ },
258
+ };
259
+ const encryptedSecret = async (secrets, plaintext) => plaintext
260
+ ? JSON.stringify(serializeEncryptedPayload(await secrets.encrypt(plaintext)))
261
+ : undefined;
262
+ export const AccountDetailOperations = {
263
+ AccountDetailOperations_updateAccount: async (context, ...args) => {
264
+ const event = args[0];
265
+ const accountConfigId = getAccountConfigIdFromEvent(event);
266
+ const { accountId } = context.request.params;
267
+ const input = JSON.parse(event.body ?? "{}");
268
+ const { account, accountSetting, mailbox, secrets } = await getClient();
269
+ const existing = await account.get(accountId);
270
+ unwrap(ownedAccount(existing, accountConfigId, "act"));
271
+ const entityFields = {
272
+ imapHost: input.imapHost,
273
+ imapPort: input.imapPort,
274
+ imapTls: input.imapTls,
275
+ imapStartTls: input.imapStartTls,
276
+ // RFC 032 Tier 2: keep the explicit send-capability marker in sync. When a
277
+ // caller changes the SMTP host without passing smtpEnabled, derive it from
278
+ // host presence so the marker can't drift from the config.
279
+ smtpEnabled: input.smtpEnabled ??
280
+ (input.smtpHost === undefined ? undefined : Boolean(input.smtpHost)),
281
+ smtpHost: input.smtpHost,
282
+ smtpPort: input.smtpPort,
283
+ smtpTls: input.smtpTls,
284
+ smtpStartTls: input.smtpStartTls,
285
+ smtpUsername: input.smtpUsername,
286
+ isActive: input.isActive,
287
+ syncedServices: input.syncedServices === undefined
288
+ ? undefined
289
+ : resolveSyncedServices(existing, input.syncedServices),
290
+ };
291
+ const updates = {
292
+ ...entityFields,
293
+ passwordHash: await encryptedSecret(secrets, input.password),
294
+ smtpPasswordHash: await encryptedSecret(secrets, input.smtpPassword),
295
+ };
296
+ // Display name and the mute flag live in per-account AccountSetting rows
297
+ // (RFC 032), not on the account entity. Display name upserts when supplied;
298
+ // the mute flag follows the address-flag null→remove, object→set semantics
299
+ // (the client populates setAt).
300
+ if (input.displayName !== undefined) {
301
+ await upsertAccountDisplayName(accountSetting, accountConfigId, accountId, input.displayName);
302
+ }
303
+ if (input.composeLanguages !== undefined) {
304
+ await writeAccountComposeLanguages(accountSetting, accountConfigId, accountId, input.composeLanguages);
305
+ }
306
+ if (Object.hasOwn(input, "muted")) {
307
+ if (input.muted !== undefined) {
308
+ await writeAccountMuted(accountSetting, accountConfigId, accountId, input.muted);
309
+ }
310
+ }
311
+ // Signatures live in per-account AccountSetting rows (RFC 032), not on the
312
+ // account entity. Persist each supplied part as a composite-named setting;
313
+ // an empty string is a valid stored value (preserves the prior "set ''
314
+ // stores ''" semantics — it does not delete the row).
315
+ if (input.signaturePlainText !== undefined ||
316
+ input.signatureHtml !== undefined) {
317
+ await upsertAccountSignature(accountSetting, accountConfigId, accountId, {
318
+ plainText: input.signaturePlainText,
319
+ html: input.signatureHtml,
320
+ });
321
+ }
322
+ const updated = await account.update(accountId, updates);
323
+ const [signature, overrides, folderAppointments] = await Promise.all([
324
+ loadSignatureForAccount(accountSetting, accountConfigId, accountId),
325
+ loadAccountOverrides(accountSetting, accountConfigId, accountId),
326
+ resolveAccountFolderAppointments({ mailbox, accountSetting }, accountConfigId, accountId),
327
+ ]);
328
+ return toAccountResponse(updated, signature, overrides, folderAppointments);
329
+ },
330
+ AccountDetailOperations_deleteAccount: async (context, ...args) => {
331
+ const event = args[0];
332
+ const accountConfigId = getAccountConfigIdFromEvent(event);
333
+ const { accountId } = context.request.params;
334
+ const { account } = await getClient();
335
+ const existing = await account.get(accountId);
336
+ unwrap(ownedAccount(existing, accountConfigId, "act"));
337
+ const deletedAt = Date.now();
338
+ await deleteAccount({
339
+ account,
340
+ sqsClient,
341
+ accountFanoutQueueUrl: env.SQS_QUEUE_URL_ACCOUNT_FANOUT,
342
+ log: logger,
343
+ }, existing, deletedAt);
344
+ return {
345
+ accountId,
346
+ deletedAt,
347
+ message: "Account marked for deletion. Data cleanup will complete shortly.",
348
+ };
349
+ },
350
+ };
@@ -0,0 +1,35 @@
1
+ import type { AddressResponse, UpdateAddressInput } from "@remit/api-openapi-types";
2
+ import type { AddressFlags, AddressItem, FlagsMergePatch } from "@remit/data-ports";
3
+ import type { AddressDetailOperationIds, AddressOperationIds, OperationHandler } from "../types.js";
4
+ export declare const toAddressResponse: (item: AddressItem) => AddressResponse;
5
+ /**
6
+ * Translate the wire-format `UpdateAddressInput` into a service-level
7
+ * `FlagsMergePatch`. Only known flag keys are forwarded; unknown keys are
8
+ * silently dropped (a TypeSpec-only schema means unknown keys are a client
9
+ * bug, not a security risk).
10
+ *
11
+ * `clearFlags` is the removal form for every flag whatever its value type, and
12
+ * is applied after `flags`, so a key named in both ends up removed. The `null`
13
+ * alternative on a flag key stays honoured for callers that can express it,
14
+ * but it is unreachable over OAS 3.0: TypeSpec emits a nullable `$ref` as
15
+ * `allOf`, and the request validator drops the `nullable` there.
16
+ */
17
+ export declare const buildFlagsPatch: (input: UpdateAddressInput | undefined) => FlagsMergePatch;
18
+ /**
19
+ * The category flag a back-apply should be enqueued for, or `undefined` when
20
+ * this patch asks for none (issue #415).
21
+ *
22
+ * A SET fires one; a CLEAR — `null` in the patch, whether it came from
23
+ * `clearFlags` or from the nullable flag value — never does. Reverting a sender
24
+ * to auto-classification says nothing about what the classifier would have
25
+ * answered on mail already filed, and re-deriving that would need every
26
+ * message's body back; the revert takes effect on the sender's next message,
27
+ * exactly as the override itself did before this.
28
+ *
29
+ * The whole flag, not just its value: `setAt` identifies WHICH set the job was
30
+ * fired for, and the worker refuses to apply a job whose set is no longer the
31
+ * one standing on the Address.
32
+ */
33
+ export declare const backApplyCategoryFlag: (patch: FlagsMergePatch) => NonNullable<AddressFlags["category"]> | undefined;
34
+ export declare const AddressOperations: Record<AddressOperationIds, OperationHandler<AddressOperationIds>>;
35
+ export declare const AddressDetailOperations: Record<AddressDetailOperationIds, OperationHandler<AddressDetailOperationIds>>;
@@ -0,0 +1,141 @@
1
+ import { SendMessageCommand } from "@aws-sdk/client-sqs";
2
+ import { ForbiddenError } from "@remit/data-ports/errors";
3
+ import { AddressFlagKey } from "@remit/domain-enums";
4
+ import { env } from "expect-env";
5
+ import { getAccountConfigIdFromEvent } from "../auth.js";
6
+ import { getClient } from "../service/data-client.js";
7
+ import { sqsClient } from "../service/sqs.js";
8
+ export const toAddressResponse = (item) => ({
9
+ addressId: item.addressId,
10
+ accountConfigId: item.accountConfigId,
11
+ displayName: item.displayName,
12
+ localPart: item.localPart,
13
+ domain: item.domain,
14
+ normalizedEmail: item.normalizedEmail,
15
+ flags: item.flags ?? {},
16
+ inboundCount: item.inboundCount ?? 0,
17
+ outboundCount: item.outboundCount ?? 0,
18
+ replyCount: item.replyCount ?? 0,
19
+ lastInboundAt: item.lastInboundAt ?? 0,
20
+ lastReplyAt: item.lastReplyAt ?? 0,
21
+ createdAt: item.createdAt,
22
+ updatedAt: item.updatedAt,
23
+ });
24
+ const FLAG_KEYS = Object.values(AddressFlagKey);
25
+ /**
26
+ * Translate the wire-format `UpdateAddressInput` into a service-level
27
+ * `FlagsMergePatch`. Only known flag keys are forwarded; unknown keys are
28
+ * silently dropped (a TypeSpec-only schema means unknown keys are a client
29
+ * bug, not a security risk).
30
+ *
31
+ * `clearFlags` is the removal form for every flag whatever its value type, and
32
+ * is applied after `flags`, so a key named in both ends up removed. The `null`
33
+ * alternative on a flag key stays honoured for callers that can express it,
34
+ * but it is unreachable over OAS 3.0: TypeSpec emits a nullable `$ref` as
35
+ * `allOf`, and the request validator drops the `nullable` there.
36
+ */
37
+ export const buildFlagsPatch = (input) => {
38
+ if (!input)
39
+ return {};
40
+ const patch = {};
41
+ const flags = input.flags;
42
+ if (flags) {
43
+ for (const key of FLAG_KEYS) {
44
+ if (!(key in flags))
45
+ continue;
46
+ const value = flags[key];
47
+ if (value === null) {
48
+ patch[key] = null;
49
+ continue;
50
+ }
51
+ if (value === undefined)
52
+ continue;
53
+ patch[key] = value;
54
+ }
55
+ }
56
+ for (const key of input.clearFlags ?? []) {
57
+ if (!FLAG_KEYS.includes(key))
58
+ continue;
59
+ patch[key] = null;
60
+ }
61
+ return patch;
62
+ };
63
+ /**
64
+ * The category flag a back-apply should be enqueued for, or `undefined` when
65
+ * this patch asks for none (issue #415).
66
+ *
67
+ * A SET fires one; a CLEAR — `null` in the patch, whether it came from
68
+ * `clearFlags` or from the nullable flag value — never does. Reverting a sender
69
+ * to auto-classification says nothing about what the classifier would have
70
+ * answered on mail already filed, and re-deriving that would need every
71
+ * message's body back; the revert takes effect on the sender's next message,
72
+ * exactly as the override itself did before this.
73
+ *
74
+ * The whole flag, not just its value: `setAt` identifies WHICH set the job was
75
+ * fired for, and the worker refuses to apply a job whose set is no longer the
76
+ * one standing on the Address.
77
+ */
78
+ export const backApplyCategoryFlag = (patch) => {
79
+ const flag = patch.category;
80
+ if (flag === null || flag === undefined)
81
+ return undefined;
82
+ return flag;
83
+ };
84
+ export const AddressOperations = {
85
+ AddressOperations_searchAddresses: async (context, ...args) => {
86
+ const event = args[0];
87
+ const accountConfigId = getAccountConfigIdFromEvent(event);
88
+ const { q, limit } = context.request.query;
89
+ const client = await getClient();
90
+ const result = await client.address.listByAccountConfig({
91
+ accountConfigId,
92
+ search: q.toLowerCase(),
93
+ limit: limit ?? 10,
94
+ });
95
+ return {
96
+ items: result.items.map(toAddressResponse),
97
+ continuationToken: result.continuationToken,
98
+ };
99
+ },
100
+ };
101
+ export const AddressDetailOperations = {
102
+ AddressDetailOperations_updateAddress: async (context, ...args) => {
103
+ const event = args[0];
104
+ const accountConfigId = getAccountConfigIdFromEvent(event);
105
+ const { addressId } = context.request.params;
106
+ const body = (context.request.requestBody ?? {});
107
+ const client = await getClient();
108
+ // Authorize: address must belong to the caller's accountConfig
109
+ const existing = await client.address.getAddress(accountConfigId, addressId);
110
+ if (existing.accountConfigId !== accountConfigId) {
111
+ throw new ForbiddenError(`Address ${addressId} not in account config`);
112
+ }
113
+ const patch = buildFlagsPatch(body);
114
+ if (Object.keys(patch).length === 0) {
115
+ return toAddressResponse(existing);
116
+ }
117
+ const updated = await client.address.mergeFlags(accountConfigId, addressId, patch);
118
+ const flag = backApplyCategoryFlag(patch);
119
+ if (flag) {
120
+ // The flag itself is already durable. A queue failure here costs the
121
+ // user the retroactive pass and nothing else, so the 500 says so and
122
+ // names the retry — re-sending the same category enqueues a fresh job.
123
+ await sqsClient
124
+ .send(new SendMessageCommand({
125
+ QueueUrl: env.SQS_QUEUE_URL_ACCOUNT_FANOUT,
126
+ MessageBody: JSON.stringify({
127
+ type: "SenderCategoryBackApply",
128
+ accountConfigId,
129
+ addressId,
130
+ normalizedEmail: updated.normalizedEmail,
131
+ category: flag.value,
132
+ categorySetAt: flag.setAt,
133
+ }),
134
+ }))
135
+ .catch((cause) => {
136
+ throw new Error(`The ${flag.value} override is saved and applies to this sender's next message, but the pass over their existing mail could not be started. Setting the same category again retries it.`, { cause });
137
+ });
138
+ }
139
+ return toAddressResponse(updated);
140
+ },
141
+ };