@remit/backend 0.0.143 → 0.0.145

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 (279) 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 +5 -0
  4. package/dist/src/api.js +73 -0
  5. package/dist/src/auth.d.ts +24 -0
  6. package/dist/src/auth.js +81 -0
  7. package/dist/src/config/api-config.d.ts +20 -0
  8. package/dist/src/config/api-config.js +1 -0
  9. package/dist/src/config/from-env.d.ts +2 -0
  10. package/dist/src/config/from-env.js +65 -0
  11. package/dist/src/config/msoauth-secrets-manager.d.ts +2 -0
  12. package/dist/src/config/msoauth-secrets-manager.js +28 -0
  13. package/dist/src/config/msoauth.d.ts +19 -0
  14. package/dist/src/config/msoauth.js +6 -0
  15. package/{src/derive/autoMoved.ts → dist/src/derive/autoMoved.d.ts} +1 -29
  16. package/dist/src/derive/autoMoved.js +49 -0
  17. package/dist/src/derive/contentSignature.d.ts +40 -0
  18. package/{src/derive/contentSignature.ts → dist/src/derive/contentSignature.js} +23 -77
  19. package/dist/src/derive/contentUrl.d.ts +33 -0
  20. package/dist/src/derive/contentUrl.js +27 -0
  21. package/{src/derive/deriveMuted.ts → dist/src/derive/deriveMuted.d.ts} +1 -3
  22. package/dist/src/derive/deriveMuted.js +7 -0
  23. package/dist/src/derive/enrichThreadRows.d.ts +118 -0
  24. package/dist/src/derive/enrichThreadRows.js +151 -0
  25. package/dist/src/derive/filterThreadCriteria.d.ts +23 -0
  26. package/dist/src/derive/filterThreadCriteria.js +24 -0
  27. package/{src/derive/pendingMoveCounts.ts → dist/src/derive/pendingMoveCounts.d.ts} +5 -53
  28. package/dist/src/derive/pendingMoveCounts.js +53 -0
  29. package/{src/derive/senderTrust.ts → dist/src/derive/senderTrust.d.ts} +1 -9
  30. package/dist/src/derive/senderTrust.js +19 -0
  31. package/dist/src/error.d.ts +21 -0
  32. package/dist/src/error.js +85 -0
  33. package/dist/src/handlers/account-guards.d.ts +36 -0
  34. package/dist/src/handlers/account-guards.js +107 -0
  35. package/dist/src/handlers/account-oauth.d.ts +15 -0
  36. package/dist/src/handlers/account-oauth.js +334 -0
  37. package/dist/src/handlers/account-overrides.d.ts +53 -0
  38. package/dist/src/handlers/account-overrides.js +233 -0
  39. package/dist/src/handlers/account-signature.d.ts +28 -0
  40. package/dist/src/handlers/account-signature.js +85 -0
  41. package/dist/src/handlers/account.d.ts +7 -0
  42. package/dist/src/handlers/account.js +337 -0
  43. package/dist/src/handlers/address.d.ts +35 -0
  44. package/dist/src/handlers/address.js +133 -0
  45. package/dist/src/handlers/calendar-event.d.ts +70 -0
  46. package/dist/src/handlers/calendar-event.js +417 -0
  47. package/dist/src/handlers/calendar-feed.d.ts +47 -0
  48. package/dist/src/handlers/calendar-feed.js +184 -0
  49. package/dist/src/handlers/calendar-suggestion.d.ts +47 -0
  50. package/dist/src/handlers/calendar-suggestion.js +204 -0
  51. package/dist/src/handlers/calendar.d.ts +116 -0
  52. package/dist/src/handlers/calendar.js +323 -0
  53. package/dist/src/handlers/config.d.ts +43 -0
  54. package/dist/src/handlers/config.js +164 -0
  55. package/dist/src/handlers/ensure-account-config.d.ts +9 -0
  56. package/dist/src/handlers/ensure-account-config.js +27 -0
  57. package/dist/src/handlers/filter.d.ts +3 -0
  58. package/dist/src/handlers/filter.js +88 -0
  59. package/dist/src/handlers/folder-role-appointments.d.ts +68 -0
  60. package/dist/src/handlers/folder-role-appointments.js +168 -0
  61. package/dist/src/handlers/folder-role-labels.d.ts +26 -0
  62. package/dist/src/handlers/folder-role-labels.js +40 -0
  63. package/dist/src/handlers/folder-role.d.ts +9 -0
  64. package/dist/src/handlers/folder-role.js +37 -0
  65. package/dist/src/handlers/index.d.ts +88 -0
  66. package/dist/src/handlers/index.js +62 -0
  67. package/dist/src/handlers/label.d.ts +43 -0
  68. package/dist/src/handlers/label.js +107 -0
  69. package/dist/src/handlers/mailbox-bindings.d.ts +41 -0
  70. package/dist/src/handlers/mailbox-bindings.js +61 -0
  71. package/dist/src/handlers/mailbox.d.ts +23 -0
  72. package/dist/src/handlers/mailbox.js +211 -0
  73. package/dist/src/handlers/me.d.ts +2 -0
  74. package/dist/src/handlers/me.js +117 -0
  75. package/dist/src/handlers/message.d.ts +82 -0
  76. package/dist/src/handlers/message.js +595 -0
  77. package/dist/src/handlers/organize.d.ts +10 -0
  78. package/dist/src/handlers/organize.js +103 -0
  79. package/dist/src/handlers/outbox-attachment.d.ts +25 -0
  80. package/dist/src/handlers/outbox-attachment.js +77 -0
  81. package/dist/src/handlers/outbox.d.ts +4 -0
  82. package/dist/src/handlers/outbox.js +136 -0
  83. package/dist/src/handlers/sync-progress.d.ts +46 -0
  84. package/dist/src/handlers/sync-progress.js +63 -0
  85. package/dist/src/handlers/sync.d.ts +28 -0
  86. package/dist/src/handlers/sync.js +73 -0
  87. package/dist/src/handlers/system-update.d.ts +2 -0
  88. package/dist/src/handlers/system-update.js +159 -0
  89. package/dist/src/handlers/thread.d.ts +148 -0
  90. package/dist/src/handlers/thread.js +228 -0
  91. package/dist/src/handlers/unified-threads.d.ts +247 -0
  92. package/dist/src/handlers/unified-threads.js +406 -0
  93. package/{src/handlers/vip-suggestions.ts → dist/src/handlers/vip-suggestions.d.ts} +1 -13
  94. package/dist/src/handlers/vip-suggestions.js +16 -0
  95. package/dist/src/index.d.ts +5 -0
  96. package/dist/src/index.js +53 -0
  97. package/{src/json.ts → dist/src/json.d.ts} +1 -4
  98. package/dist/src/json.js +10 -0
  99. package/dist/src/jwt-auth.d.ts +15 -0
  100. package/dist/src/jwt-auth.js +45 -0
  101. package/dist/src/lambda.d.ts +13 -0
  102. package/dist/src/lambda.js +33 -0
  103. package/dist/src/request.d.ts +9 -0
  104. package/dist/src/request.js +17 -0
  105. package/dist/src/response.d.ts +44 -0
  106. package/dist/src/response.js +80 -0
  107. package/dist/src/serve.d.ts +31 -0
  108. package/dist/src/serve.js +117 -0
  109. package/dist/src/service/account-deletion.d.ts +20 -0
  110. package/dist/src/service/account-deletion.js +33 -0
  111. package/dist/src/service/compose-sqlite.d.ts +3 -0
  112. package/dist/src/service/compose-sqlite.js +13 -0
  113. package/dist/src/service/create-remit-client.d.ts +109 -0
  114. package/dist/src/service/create-remit-client.js +188 -0
  115. package/dist/src/service/data-client.d.ts +12 -0
  116. package/dist/src/service/data-client.js +42 -0
  117. package/dist/src/service/export-identity.d.ts +4 -0
  118. package/dist/src/service/export-identity.js +33 -0
  119. package/dist/src/service/fire-and-forget.d.ts +54 -0
  120. package/dist/src/service/fire-and-forget.js +37 -0
  121. package/dist/src/service/organize.d.ts +181 -0
  122. package/dist/src/service/organize.js +367 -0
  123. package/dist/src/service/queues.d.ts +12 -0
  124. package/dist/src/service/queues.js +1 -0
  125. package/dist/src/service/refusal.d.ts +4 -0
  126. package/dist/src/service/refusal.js +20 -0
  127. package/dist/src/service/sender-category.d.ts +51 -0
  128. package/{src/service/sender-category.ts → dist/src/service/sender-category.js} +40 -81
  129. package/dist/src/service/shared-deps.d.ts +6 -0
  130. package/dist/src/service/shared-deps.js +24 -0
  131. package/dist/src/service/trigger-sync.d.ts +57 -0
  132. package/dist/src/service/trigger-sync.js +31 -0
  133. package/dist/src/types.d.ts +72 -0
  134. package/dist/src/types.js +1 -0
  135. package/package.json +125 -98
  136. package/.env.test +0 -4
  137. package/dev-server/content-auth.test.ts +0 -113
  138. package/dev-server/content-auth.ts +0 -54
  139. package/dev-server/content-handler.test.ts +0 -105
  140. package/dev-server/content-handler.ts +0 -79
  141. package/dev-server/content-path.test.ts +0 -37
  142. package/dev-server/content-path.ts +0 -27
  143. package/dev-server/cors.test.ts +0 -48
  144. package/dev-server/cors.ts +0 -25
  145. package/dev-server/keep-alive.test.ts +0 -24
  146. package/dev-server/lambda-helpers.ts +0 -69
  147. package/dev-server/log-output.test.ts +0 -173
  148. package/dev-server/oauth-callback-route.test.ts +0 -66
  149. package/dev-server/relational-health.test.ts +0 -83
  150. package/dev-server/relational-health.ts +0 -39
  151. package/dev-server/server.ts +0 -384
  152. package/dev-server/sync-age.test.ts +0 -91
  153. package/dev-server/sync-age.ts +0 -55
  154. package/dev-server/upload-handler.ts +0 -132
  155. package/dev-server/upload-route.test.ts +0 -196
  156. package/scripts/backfill-classification.ts +0 -91
  157. package/scripts/backfill-list-id.ts +0 -83
  158. package/scripts/config-save.ts +0 -128
  159. package/src/auth.test.ts +0 -12
  160. package/src/auth.ts +0 -92
  161. package/src/config/msoauth.test.ts +0 -48
  162. package/src/config/msoauth.ts +0 -48
  163. package/src/data-backend.test.ts +0 -23
  164. package/src/data-backend.ts +0 -14
  165. package/src/derive/autoMoved.test.ts +0 -104
  166. package/src/derive/contentSignature.test.ts +0 -161
  167. package/src/derive/contentUrl.test.ts +0 -172
  168. package/src/derive/contentUrl.ts +0 -86
  169. package/src/derive/deriveMuted.test.ts +0 -34
  170. package/src/derive/enrichThreadRows.test.ts +0 -360
  171. package/src/derive/enrichThreadRows.ts +0 -234
  172. package/src/derive/filterThreadCriteria.test.ts +0 -126
  173. package/src/derive/filterThreadCriteria.ts +0 -51
  174. package/src/derive/senderTrust.test.ts +0 -67
  175. package/src/error.test.ts +0 -201
  176. package/src/error.ts +0 -123
  177. package/src/handlers/account-guards.test.ts +0 -67
  178. package/src/handlers/account-guards.ts +0 -169
  179. package/src/handlers/account-oauth-callback.test.ts +0 -155
  180. package/src/handlers/account-oauth-consent.test.ts +0 -336
  181. package/src/handlers/account-oauth-start.test.ts +0 -191
  182. package/src/handlers/account-oauth.test.ts +0 -439
  183. package/src/handlers/account-oauth.ts +0 -635
  184. package/src/handlers/account-overrides.test.ts +0 -88
  185. package/src/handlers/account-overrides.ts +0 -323
  186. package/src/handlers/account-ownership.ts +0 -25
  187. package/src/handlers/account-signature.ts +0 -117
  188. package/src/handlers/account-synced-services.test.ts +0 -245
  189. package/src/handlers/account.ts +0 -552
  190. package/src/handlers/address.test.ts +0 -381
  191. package/src/handlers/address.ts +0 -200
  192. package/src/handlers/calendar-event.test.ts +0 -685
  193. package/src/handlers/calendar-event.ts +0 -738
  194. package/src/handlers/calendar-feed-validators.test.ts +0 -228
  195. package/src/handlers/calendar-feed.test.ts +0 -439
  196. package/src/handlers/calendar-feed.ts +0 -291
  197. package/src/handlers/calendar-sqlite-fixture.ts +0 -36
  198. package/src/handlers/calendar-suggestion.test.ts +0 -1269
  199. package/src/handlers/calendar-suggestion.ts +0 -425
  200. package/src/handlers/calendar.test.ts +0 -1080
  201. package/src/handlers/calendar.ts +0 -517
  202. package/src/handlers/config.test.ts +0 -245
  203. package/src/handlers/config.ts +0 -332
  204. package/src/handlers/ensure-account-config.ts +0 -30
  205. package/src/handlers/filter.test.ts +0 -644
  206. package/src/handlers/filter.ts +0 -518
  207. package/src/handlers/folder-role-appointments.test.ts +0 -438
  208. package/src/handlers/folder-role-appointments.ts +0 -249
  209. package/src/handlers/folder-role-labels.ts +0 -63
  210. package/src/handlers/folder-role.test.ts +0 -209
  211. package/src/handlers/folder-role.ts +0 -80
  212. package/src/handlers/index.ts +0 -83
  213. package/src/handlers/label.test.ts +0 -112
  214. package/src/handlers/label.ts +0 -210
  215. package/src/handlers/mailbox-bindings.ts +0 -111
  216. package/src/handlers/mailbox-rename-refusal.test.ts +0 -247
  217. package/src/handlers/mailbox-settled-target.test.ts +0 -251
  218. package/src/handlers/mailbox.test.ts +0 -280
  219. package/src/handlers/mailbox.ts +0 -581
  220. package/src/handlers/me.test.ts +0 -81
  221. package/src/handlers/me.ts +0 -203
  222. package/src/handlers/message-read-backfill.test.ts +0 -103
  223. package/src/handlers/message.test.ts +0 -131
  224. package/src/handlers/message.ts +0 -1131
  225. package/src/handlers/organize.test.ts +0 -277
  226. package/src/handlers/organize.ts +0 -197
  227. package/src/handlers/outbox-attachment.test.ts +0 -765
  228. package/src/handlers/outbox-attachment.ts +0 -126
  229. package/src/handlers/outbox-list.test.ts +0 -179
  230. package/src/handlers/outbox.test.ts +0 -772
  231. package/src/handlers/outbox.ts +0 -258
  232. package/src/handlers/search.test.ts +0 -161
  233. package/src/handlers/search.ts +0 -105
  234. package/src/handlers/sync-progress.test.ts +0 -205
  235. package/src/handlers/sync-progress.ts +0 -99
  236. package/src/handlers/sync.test.ts +0 -168
  237. package/src/handlers/sync.ts +0 -118
  238. package/src/handlers/system-update.test.ts +0 -497
  239. package/src/handlers/system-update.ts +0 -230
  240. package/src/handlers/thread.test.ts +0 -396
  241. package/src/handlers/thread.ts +0 -427
  242. package/src/handlers/unified-threads-mail-sources.sqlite.test.ts +0 -197
  243. package/src/handlers/unified-threads.test.ts +0 -785
  244. package/src/handlers/unified-threads.ts +0 -669
  245. package/src/index.test.ts +0 -83
  246. package/src/index.ts +0 -228
  247. package/src/jwt-auth.test.ts +0 -152
  248. package/src/jwt-auth.ts +0 -132
  249. package/src/log-redaction.test.ts +0 -144
  250. package/src/openapi-spec.test.ts +0 -118
  251. package/src/request-context.test.ts +0 -61
  252. package/src/request-context.ts +0 -33
  253. package/src/request-pipeline.test.ts +0 -88
  254. package/src/request.ts +0 -10
  255. package/src/response.test.ts +0 -130
  256. package/src/response.ts +0 -144
  257. package/src/service/compose-sqlite.ts +0 -98
  258. package/src/service/config-import.ts +0 -39
  259. package/src/service/create-remit-client.ts +0 -522
  260. package/src/service/data-client.test.ts +0 -97
  261. package/src/service/data-client.ts +0 -58
  262. package/src/service/export-identity.ts +0 -39
  263. package/src/service/filter.ts +0 -40
  264. package/src/service/fire-and-forget.test.ts +0 -126
  265. package/src/service/fire-and-forget.ts +0 -79
  266. package/src/service/localhost-env-config.test.ts +0 -36
  267. package/src/service/organize-queue.ts +0 -98
  268. package/src/service/organize.test.ts +0 -1451
  269. package/src/service/organize.ts +0 -1025
  270. package/src/service/read-path-filter-config.test.ts +0 -243
  271. package/src/service/semantic-capability.test.ts +0 -78
  272. package/src/service/semantic-capability.ts +0 -95
  273. package/src/service/sender-category.test.ts +0 -235
  274. package/src/service/sqs.ts +0 -4
  275. package/src/service/trigger-sync.test.ts +0 -205
  276. package/src/service/trigger-sync.ts +0 -100
  277. package/src/stdout-capture-fixture.ts +0 -40
  278. package/src/types.ts +0 -271
  279. package/tsconfig.json +0 -7
@@ -0,0 +1,337 @@
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 { loadMsOAuth } from "../config/msoauth.js";
7
+ import { deleteAccount } from "../service/account-deletion.js";
8
+ import { fireAndForget } from "../service/fire-and-forget.js";
9
+ import { unwrap } from "../service/refusal.js";
10
+ import { triggerAccountSync } from "../service/trigger-sync.js";
11
+ import { assertNoDuplicateMailbox, assertNotOAuthCreate, assertPasswordProvided, resolveSyncedServices, toAccountResponse, } from "./account-guards.js";
12
+ import { loadAccountOverrides, upsertAccountDisplayName, writeAccountComposeLanguages, writeAccountMuted, } from "./account-overrides.js";
13
+ import { loadSignatureForAccount, upsertAccountSignature, } from "./account-signature.js";
14
+ import { ensureAccountConfig } from "./ensure-account-config.js";
15
+ import { resolveAccountFolderAppointments } from "./folder-role-appointments.js";
16
+ export { assertNotOAuthCreate, assertPasswordProvided, toAccountResponse };
17
+ export const triggerAccountSyncSafe = async (client, accountId) => {
18
+ // Best-effort: account creation must still return 200 even if the sync
19
+ // enqueue fails. fireAndForget catches and logs every rejection loudly with
20
+ // the alertable structured fields and never rejects, so a failure here (SQS
21
+ // unreachable in smoke/e2e, an IAM/SQS misconfig in prod) cannot leak an
22
+ // unhandled rejection onto an unrelated in-flight request.
23
+ await fireAndForget(async () => {
24
+ const { eventId } = await triggerAccountSync({
25
+ queue: client.queues.sync,
26
+ accountId,
27
+ });
28
+ // biome-ignore lint/plugin/no-logger-info: sync-triggered-for-new-account is an audit-grade signal
29
+ logger.info({ accountId, eventId }, "Sync triggered for new account");
30
+ }, {
31
+ source: "account_create",
32
+ message: "Failed to enqueue SYNC_MAILBOXES for new account (best-effort)",
33
+ ids: { accountId },
34
+ });
35
+ };
36
+ /**
37
+ * Test connectivity for an OAuth (Microsoft) account.
38
+ *
39
+ * Mints an access token from the stored refresh token via
40
+ * resolveConnectionCredentials (the single authType branch), then runs the
41
+ * IMAP — and, when configured, SMTP — connection tests with those credentials.
42
+ *
43
+ * A revoked / expired refresh token surfaces as RefreshTokenError; the
44
+ * reauth-required case is mapped to the distinct `reauth_required` error code
45
+ * so the UI can route the user into the OAuth re-auth flow.
46
+ */
47
+ const testOAuthConnection = async (msOAuth, existingAccount, account, secrets) => {
48
+ const { config, credentials: app } = await loadMsOAuth(msOAuth);
49
+ const tokenService = createMailOAuthService(microsoftProviderConfig({
50
+ clientId: app.clientId,
51
+ clientSecret: app.clientSecret,
52
+ overrides: config.overrides,
53
+ }));
54
+ let resolution;
55
+ try {
56
+ resolution = await resolveConnectionCredentials(existingAccount, {
57
+ secrets,
58
+ tokenService,
59
+ persistRotatedToken: async (id, encryptedHash, updatedAt) => {
60
+ await account.update(id, {
61
+ oauthRefreshTokenHash: encryptedHash,
62
+ oauthTokenUpdatedAt: updatedAt,
63
+ });
64
+ },
65
+ });
66
+ }
67
+ catch (err) {
68
+ if (err instanceof RefreshTokenError &&
69
+ err.error.kind === "reauth-required") {
70
+ return {
71
+ imapSuccess: false,
72
+ imapError: "reauth_required",
73
+ smtpSuccess: undefined,
74
+ };
75
+ }
76
+ throw err;
77
+ }
78
+ if (resolution.status === "missing") {
79
+ return {
80
+ imapSuccess: false,
81
+ imapError: "oauth_not_configured",
82
+ smtpSuccess: undefined,
83
+ };
84
+ }
85
+ const credentials = resolution.credentials;
86
+ const result = {
87
+ imapSuccess: false,
88
+ smtpSuccess: undefined,
89
+ };
90
+ const imapResult = await testImapConnection({
91
+ host: existingAccount.imapHost,
92
+ port: existingAccount.imapPort,
93
+ secure: existingAccount.imapTls,
94
+ user: existingAccount.username,
95
+ credentials,
96
+ });
97
+ result.imapSuccess = imapResult.success;
98
+ if (!imapResult.success) {
99
+ result.imapError = imapResult.error;
100
+ }
101
+ // OAuth accounts share the same access token for IMAP and SMTP.
102
+ if (existingAccount.smtpEnabled) {
103
+ const smtpResult = await testSmtpConnection({
104
+ host: existingAccount.smtpHost ?? "",
105
+ port: existingAccount.smtpPort ?? 587,
106
+ secure: existingAccount.smtpTls ?? false,
107
+ user: existingAccount.smtpUsername || existingAccount.username,
108
+ credentials,
109
+ });
110
+ result.smtpSuccess = smtpResult.success;
111
+ if (!smtpResult.success) {
112
+ result.smtpError = smtpResult.error;
113
+ }
114
+ }
115
+ return result;
116
+ };
117
+ export const AccountOperations = {
118
+ AccountOperations_createAccount: async (context, ctx) => {
119
+ const accountConfigId = ctx.identity.accountConfigId;
120
+ const input = context.request.requestBody;
121
+ // OAuth accounts must be created via the dedicated connect flow
122
+ assertNotOAuthCreate(input.authType);
123
+ // Password accounts require a non-empty password
124
+ assertPasswordProvided(input.authType, input.password);
125
+ const syncedServices = resolveSyncedServices({ authType: AccountAuthType.Password, grantedScopes: [] }, input.syncedServices ?? [AccountService.Mail]);
126
+ const { account, accountConfig, accountSetting, mailbox, secrets } = ctx.client;
127
+ await ensureAccountConfig(accountConfig, accountConfigId);
128
+ // Reject re-onboarding the same mailbox-in-the-same-place. Message
129
+ // identity is account-scoped (#633), so duplicate onboards are no longer
130
+ // incidentally deduped — this is the explicit replacement (#635).
131
+ const existingAccounts = await account.listAllByAccountConfig(accountConfigId);
132
+ assertNoDuplicateMailbox(existingAccounts, {
133
+ imapHost: input.imapHost,
134
+ username: input.username ?? input.email,
135
+ });
136
+ // biome-ignore lint/style/noNonNullAssertion: guard above ensures password is set for password-auth accounts
137
+ const passwordPayload = await secrets.encrypt(input.password);
138
+ const passwordHash = JSON.stringify(serializeEncryptedPayload(passwordPayload));
139
+ let smtpPasswordHash;
140
+ if (input.smtpPassword) {
141
+ const smtpPayload = await secrets.encrypt(input.smtpPassword);
142
+ smtpPasswordHash = JSON.stringify(serializeEncryptedPayload(smtpPayload));
143
+ }
144
+ const newAccount = await account.create({
145
+ accountConfigId,
146
+ email: input.email,
147
+ username: input.username ?? input.email,
148
+ authType: AccountAuthType.Password,
149
+ syncedServices,
150
+ passwordHash,
151
+ imapHost: input.imapHost,
152
+ imapPort: input.imapPort,
153
+ imapTls: input.imapTls,
154
+ imapStartTls: input.imapStartTls,
155
+ // RFC 032 Tier 2: smtpEnabled is the explicit send-capability marker.
156
+ // Honour an explicit flag from the client; otherwise enable sending when
157
+ // an SMTP host was supplied (the prior implicit behaviour).
158
+ smtpEnabled: input.smtpEnabled ?? Boolean(input.smtpHost),
159
+ smtpHost: input.smtpHost,
160
+ smtpPort: input.smtpPort,
161
+ smtpTls: input.smtpTls,
162
+ smtpStartTls: input.smtpStartTls,
163
+ smtpUsername: input.smtpUsername,
164
+ smtpPasswordHash,
165
+ isActive: true,
166
+ connectionState: ConnectionState.NotAuthenticated,
167
+ });
168
+ // Display name lives in a per-account AccountSetting row (RFC 032), not on
169
+ // the entity. Persist it when supplied so the response and later reads
170
+ // surface it unchanged.
171
+ if (input.displayName !== undefined) {
172
+ await upsertAccountDisplayName(accountSetting, accountConfigId, newAccount.accountId, input.displayName);
173
+ }
174
+ await triggerAccountSyncSafe(ctx.client, newAccount.accountId);
175
+ const [overrides, folderAppointments] = await Promise.all([
176
+ loadAccountOverrides(accountSetting, accountConfigId, newAccount.accountId),
177
+ resolveAccountFolderAppointments({ mailbox, accountSetting }, accountConfigId, newAccount.accountId),
178
+ ]);
179
+ return toAccountResponse(newAccount, {}, overrides, folderAppointments);
180
+ },
181
+ AccountOperations_testConnection: async (context, ctx) => {
182
+ const accountConfigId = ctx.identity.accountConfigId;
183
+ const input = context.request.requestBody;
184
+ const { account, secrets } = ctx.client;
185
+ // Resolve password - use provided password or decrypt stored password
186
+ let imapPassword = input.password;
187
+ let smtpPassword = input.smtpPassword;
188
+ if (!imapPassword && input.accountId) {
189
+ const existingAccount = await account.get(input.accountId);
190
+ unwrap(ownedAccount(existingAccount, accountConfigId, "read"));
191
+ const authType = existingAccount.authType ?? "password";
192
+ if (authType === "oauthMicrosoft") {
193
+ return testOAuthConnection(ctx.config.msOAuth, existingAccount, account, secrets);
194
+ }
195
+ if (existingAccount.passwordHash) {
196
+ const payload = deserializeEncryptedPayload(JSON.parse(existingAccount.passwordHash));
197
+ imapPassword = await secrets.decrypt(payload);
198
+ }
199
+ // Also get SMTP password if needed and available
200
+ if (!smtpPassword && existingAccount.smtpPasswordHash) {
201
+ const smtpPayload = deserializeEncryptedPayload(JSON.parse(existingAccount.smtpPasswordHash));
202
+ smtpPassword = await secrets.decrypt(smtpPayload);
203
+ }
204
+ }
205
+ if (!imapPassword) {
206
+ return {
207
+ imapSuccess: false,
208
+ imapError: "Password required",
209
+ smtpSuccess: undefined,
210
+ };
211
+ }
212
+ const result = {
213
+ imapSuccess: false,
214
+ smtpSuccess: undefined,
215
+ };
216
+ // Test IMAP connection
217
+ const imapResult = await testImapConnection({
218
+ host: input.imapHost,
219
+ port: input.imapPort,
220
+ secure: input.imapTls,
221
+ startTls: input.imapStartTls,
222
+ user: input.username,
223
+ credentials: { kind: "password", password: imapPassword },
224
+ });
225
+ result.imapSuccess = imapResult.success;
226
+ if (!imapResult.success) {
227
+ result.imapError = imapResult.error;
228
+ }
229
+ // Test SMTP connection if configured
230
+ if (input.smtpHost) {
231
+ const smtpResult = await testSmtpConnection({
232
+ host: input.smtpHost,
233
+ port: input.smtpPort ?? 587,
234
+ secure: input.smtpTls ?? false,
235
+ user: input.smtpUsername ?? input.username,
236
+ credentials: {
237
+ kind: "password",
238
+ password: smtpPassword ?? imapPassword,
239
+ },
240
+ });
241
+ result.smtpSuccess = smtpResult.success;
242
+ if (!smtpResult.success) {
243
+ result.smtpError = smtpResult.error;
244
+ }
245
+ }
246
+ return result;
247
+ },
248
+ };
249
+ const encryptedSecret = async (secrets, plaintext) => plaintext
250
+ ? JSON.stringify(serializeEncryptedPayload(await secrets.encrypt(plaintext)))
251
+ : undefined;
252
+ export const AccountDetailOperations = {
253
+ AccountDetailOperations_updateAccount: async (context, ctx) => {
254
+ const accountConfigId = ctx.identity.accountConfigId;
255
+ const { accountId } = context.request.params;
256
+ const input = context.request.requestBody;
257
+ const { account, accountSetting, mailbox, secrets } = ctx.client;
258
+ const existing = await account.get(accountId);
259
+ unwrap(ownedAccount(existing, accountConfigId, "act"));
260
+ const entityFields = {
261
+ imapHost: input.imapHost,
262
+ imapPort: input.imapPort,
263
+ imapTls: input.imapTls,
264
+ imapStartTls: input.imapStartTls,
265
+ // RFC 032 Tier 2: keep the explicit send-capability marker in sync. When a
266
+ // caller changes the SMTP host without passing smtpEnabled, derive it from
267
+ // host presence so the marker can't drift from the config.
268
+ smtpEnabled: input.smtpEnabled ??
269
+ (input.smtpHost === undefined ? undefined : Boolean(input.smtpHost)),
270
+ smtpHost: input.smtpHost,
271
+ smtpPort: input.smtpPort,
272
+ smtpTls: input.smtpTls,
273
+ smtpStartTls: input.smtpStartTls,
274
+ smtpUsername: input.smtpUsername,
275
+ isActive: input.isActive,
276
+ syncedServices: input.syncedServices === undefined
277
+ ? undefined
278
+ : resolveSyncedServices(existing, input.syncedServices),
279
+ };
280
+ const updates = {
281
+ ...entityFields,
282
+ passwordHash: await encryptedSecret(secrets, input.password),
283
+ smtpPasswordHash: await encryptedSecret(secrets, input.smtpPassword),
284
+ };
285
+ // Display name and the mute flag live in per-account AccountSetting rows
286
+ // (RFC 032), not on the account entity. Display name upserts when supplied;
287
+ // the mute flag follows the address-flag null→remove, object→set semantics
288
+ // (the client populates setAt).
289
+ if (input.displayName !== undefined) {
290
+ await upsertAccountDisplayName(accountSetting, accountConfigId, accountId, input.displayName);
291
+ }
292
+ if (input.composeLanguages !== undefined) {
293
+ await writeAccountComposeLanguages(accountSetting, accountConfigId, accountId, input.composeLanguages);
294
+ }
295
+ if (Object.hasOwn(input, "muted")) {
296
+ if (input.muted !== undefined) {
297
+ await writeAccountMuted(accountSetting, accountConfigId, accountId, input.muted);
298
+ }
299
+ }
300
+ // Signatures live in per-account AccountSetting rows (RFC 032), not on the
301
+ // account entity. Persist each supplied part as a composite-named setting;
302
+ // an empty string is a valid stored value (preserves the prior "set ''
303
+ // stores ''" semantics — it does not delete the row).
304
+ if (input.signaturePlainText !== undefined ||
305
+ input.signatureHtml !== undefined) {
306
+ await upsertAccountSignature(accountSetting, accountConfigId, accountId, {
307
+ plainText: input.signaturePlainText,
308
+ html: input.signatureHtml,
309
+ });
310
+ }
311
+ const updated = await account.update(accountId, updates);
312
+ const [signature, overrides, folderAppointments] = await Promise.all([
313
+ loadSignatureForAccount(accountSetting, accountConfigId, accountId),
314
+ loadAccountOverrides(accountSetting, accountConfigId, accountId),
315
+ resolveAccountFolderAppointments({ mailbox, accountSetting }, accountConfigId, accountId),
316
+ ]);
317
+ return toAccountResponse(updated, signature, overrides, folderAppointments);
318
+ },
319
+ AccountDetailOperations_deleteAccount: async (context, ctx) => {
320
+ const accountConfigId = ctx.identity.accountConfigId;
321
+ const { accountId } = context.request.params;
322
+ const { account } = ctx.client;
323
+ const existing = await account.get(accountId);
324
+ unwrap(ownedAccount(existing, accountConfigId, "act"));
325
+ const deletedAt = Date.now();
326
+ await deleteAccount({
327
+ account,
328
+ queue: ctx.client.queues.accountFanout,
329
+ log: logger,
330
+ }, existing, deletedAt);
331
+ return {
332
+ accountId,
333
+ deletedAt,
334
+ message: "Account marked for deletion. Data cleanup will complete shortly.",
335
+ };
336
+ },
337
+ };
@@ -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, "accountFanout">>;
35
+ export declare const AddressDetailOperations: Record<AddressDetailOperationIds, OperationHandler<AddressDetailOperationIds, "accountFanout">>;
@@ -0,0 +1,133 @@
1
+ import { ForbiddenError } from "@remit/data-ports/errors";
2
+ import { AddressFlagKey } from "@remit/domain-enums";
3
+ export const toAddressResponse = (item) => ({
4
+ addressId: item.addressId,
5
+ accountConfigId: item.accountConfigId,
6
+ displayName: item.displayName,
7
+ localPart: item.localPart,
8
+ domain: item.domain,
9
+ normalizedEmail: item.normalizedEmail,
10
+ flags: item.flags ?? {},
11
+ inboundCount: item.inboundCount ?? 0,
12
+ outboundCount: item.outboundCount ?? 0,
13
+ replyCount: item.replyCount ?? 0,
14
+ lastInboundAt: item.lastInboundAt ?? 0,
15
+ lastReplyAt: item.lastReplyAt ?? 0,
16
+ createdAt: item.createdAt,
17
+ updatedAt: item.updatedAt,
18
+ });
19
+ const FLAG_KEYS = Object.values(AddressFlagKey);
20
+ /**
21
+ * Translate the wire-format `UpdateAddressInput` into a service-level
22
+ * `FlagsMergePatch`. Only known flag keys are forwarded; unknown keys are
23
+ * silently dropped (a TypeSpec-only schema means unknown keys are a client
24
+ * bug, not a security risk).
25
+ *
26
+ * `clearFlags` is the removal form for every flag whatever its value type, and
27
+ * is applied after `flags`, so a key named in both ends up removed. The `null`
28
+ * alternative on a flag key stays honoured for callers that can express it,
29
+ * but it is unreachable over OAS 3.0: TypeSpec emits a nullable `$ref` as
30
+ * `allOf`, and the request validator drops the `nullable` there.
31
+ */
32
+ export const buildFlagsPatch = (input) => {
33
+ if (!input)
34
+ return {};
35
+ const patch = {};
36
+ const flags = input.flags;
37
+ if (flags) {
38
+ for (const key of FLAG_KEYS) {
39
+ if (!(key in flags))
40
+ continue;
41
+ const value = flags[key];
42
+ if (value === null) {
43
+ patch[key] = null;
44
+ continue;
45
+ }
46
+ if (value === undefined)
47
+ continue;
48
+ patch[key] = value;
49
+ }
50
+ }
51
+ for (const key of input.clearFlags ?? []) {
52
+ if (!FLAG_KEYS.includes(key))
53
+ continue;
54
+ patch[key] = null;
55
+ }
56
+ return patch;
57
+ };
58
+ /**
59
+ * The category flag a back-apply should be enqueued for, or `undefined` when
60
+ * this patch asks for none (issue #415).
61
+ *
62
+ * A SET fires one; a CLEAR — `null` in the patch, whether it came from
63
+ * `clearFlags` or from the nullable flag value — never does. Reverting a sender
64
+ * to auto-classification says nothing about what the classifier would have
65
+ * answered on mail already filed, and re-deriving that would need every
66
+ * message's body back; the revert takes effect on the sender's next message,
67
+ * exactly as the override itself did before this.
68
+ *
69
+ * The whole flag, not just its value: `setAt` identifies WHICH set the job was
70
+ * fired for, and the worker refuses to apply a job whose set is no longer the
71
+ * one standing on the Address.
72
+ */
73
+ export const backApplyCategoryFlag = (patch) => {
74
+ const flag = patch.category;
75
+ if (flag === null || flag === undefined)
76
+ return undefined;
77
+ return flag;
78
+ };
79
+ export const AddressOperations = {
80
+ AddressOperations_searchAddresses: async (context, ctx) => {
81
+ const accountConfigId = ctx.identity.accountConfigId;
82
+ const { q, limit } = context.request.query;
83
+ const client = ctx.client;
84
+ const result = await client.address.listByAccountConfig({
85
+ accountConfigId,
86
+ search: q.toLowerCase(),
87
+ limit: limit ?? 10,
88
+ });
89
+ return {
90
+ items: result.items.map(toAddressResponse),
91
+ continuationToken: result.continuationToken,
92
+ };
93
+ },
94
+ };
95
+ export const AddressDetailOperations = {
96
+ AddressDetailOperations_updateAddress: async (context, ctx) => {
97
+ const accountConfigId = ctx.identity.accountConfigId;
98
+ const { addressId } = context.request.params;
99
+ const body = (context.request.requestBody ?? {});
100
+ const client = ctx.client;
101
+ // Authorize: address must belong to the caller's accountConfig
102
+ const existing = await client.address.getAddress(accountConfigId, addressId);
103
+ if (existing.accountConfigId !== accountConfigId) {
104
+ throw new ForbiddenError(`Address ${addressId} not in account config`);
105
+ }
106
+ const patch = buildFlagsPatch(body);
107
+ if (Object.keys(patch).length === 0) {
108
+ return toAddressResponse(existing);
109
+ }
110
+ const updated = await client.address.mergeFlags(accountConfigId, addressId, patch);
111
+ const flag = backApplyCategoryFlag(patch);
112
+ if (flag) {
113
+ // The flag itself is already durable. A queue failure here costs the
114
+ // user the retroactive pass and nothing else, so the 500 says so and
115
+ // names the retry — re-sending the same category enqueues a fresh job.
116
+ await client.queues.accountFanout
117
+ .send({
118
+ body: {
119
+ type: "SenderCategoryBackApply",
120
+ accountConfigId,
121
+ addressId,
122
+ normalizedEmail: updated.normalizedEmail,
123
+ category: flag.value,
124
+ categorySetAt: flag.setAt,
125
+ },
126
+ })
127
+ .catch((cause) => {
128
+ 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 });
129
+ });
130
+ }
131
+ return toAddressResponse(updated);
132
+ },
133
+ };
@@ -0,0 +1,70 @@
1
+ import type { CreateCalendarEventInput, UpdateCalendarEventInput } from "@remit/api-openapi-types";
2
+ import { type CalendarEventFields, type CalendarWindow, type RecurrenceScopeValue, type ScopedWrite } from "@remit/calendar-service";
3
+ import type { CalendarCollectionItem, CalendarObjectItem } from "@remit/data-ports";
4
+ import type { CalendarEventDetailOperationIds, CalendarEventOperationIds, CalendarFreeBusyOperationIds, OperationHandler } from "../types.js";
5
+ import { type CalendarDeps, type CalendarOutcome } from "./calendar.js";
6
+ /**
7
+ * The widest window a single read may ask for. A year covers every view the
8
+ * client has — a year grid is the coarsest — and keeps one request from asking
9
+ * the server to expand a decade of a daily series.
10
+ */
11
+ export declare const CALENDAR_MAX_WINDOW_DAYS = 366;
12
+ /** Mints the id a new resource is named and identified by. */
13
+ export interface CalendarEventDeps extends CalendarDeps {
14
+ newId: () => string;
15
+ now: () => Date;
16
+ }
17
+ export declare const calendarEventDepsOf: (deps: CalendarDeps) => CalendarEventDeps;
18
+ /**
19
+ * Reads the window a listing asked for.
20
+ *
21
+ * Both ends must carry an offset, because a window with no offset names no
22
+ * span of time — and a client whose `from` was read an hour out gets an
23
+ * apparently empty morning rather than an error.
24
+ */
25
+ export declare const readWindow: (from: unknown, to: unknown) => CalendarOutcome<CalendarWindow>;
26
+ /** The collections a listing covers, defaulting to every one the caller holds. */
27
+ export declare const collectionsForListing: (deps: CalendarDeps, accountConfigId: string, calendarIds: string[]) => Promise<CalendarOutcome<CalendarCollectionItem[]>>;
28
+ /**
29
+ * Reduce a PATCH body to the event fields an update may set, preserving
30
+ * absence: a body carrying only `summary` yields only `summary`, and the
31
+ * resource's times are then left exactly as they were.
32
+ */
33
+ export declare const pickEventUpdate: (body: Partial<UpdateCalendarEventInput>) => Partial<CalendarEventFields>;
34
+ /**
35
+ * Whether an `If-Match` header lets the write through.
36
+ *
37
+ * No header is no precondition, which is what HTTP says and what a first-party
38
+ * client that just read the resource wants. `*` matches any existing resource.
39
+ * Quotes and a weak-validator prefix are transport spelling and are stripped
40
+ * before comparing, because the stored tag carries neither.
41
+ */
42
+ export declare const etagMatches: (ifMatch: string | undefined, etag: string) => boolean;
43
+ /**
44
+ * An absent scope means the whole series, which is what a client editing an
45
+ * event that does not recur sends. A scope that is present but not one of the
46
+ * three is refused rather than read as `All`: the widest, most destructive
47
+ * reading is the worst possible answer to a typo.
48
+ */
49
+ export declare const readScope: (value: unknown) => CalendarOutcome<RecurrenceScopeValue>;
50
+ /**
51
+ * Writes what a scoped edit resolved to.
52
+ *
53
+ * A split is two resources and one write set: the truncated original and the
54
+ * remainder land together or not at all, because half a split is a series the
55
+ * user sees twice or not at all.
56
+ */
57
+ export declare const commitScopedWrite: (deps: CalendarEventDeps, accountConfigId: string, object: CalendarObjectItem, collectionTimezone: string, write: ScopedWrite) => Promise<CalendarOutcome<CalendarObjectItem | null>>;
58
+ export declare const createCalendarEventFor: (deps: CalendarEventDeps, accountConfigId: string, input: CreateCalendarEventInput) => Promise<CalendarOutcome<CalendarObjectItem>>;
59
+ export interface ScopedRequest {
60
+ calendarId: string;
61
+ calendarObjectId: string;
62
+ scope: RecurrenceScopeValue;
63
+ recurrenceId: string;
64
+ ifMatch: string | undefined;
65
+ }
66
+ export declare const updateCalendarEventFor: (deps: CalendarEventDeps, accountConfigId: string, request: ScopedRequest, patch: Partial<CalendarEventFields>) => Promise<CalendarOutcome<CalendarObjectItem | null>>;
67
+ export declare const deleteCalendarEventFor: (deps: CalendarEventDeps, accountConfigId: string, request: ScopedRequest) => Promise<CalendarOutcome<CalendarObjectItem | null>>;
68
+ export declare const CalendarEventOperations: Record<CalendarEventOperationIds, OperationHandler<CalendarEventOperationIds>>;
69
+ export declare const CalendarEventDetailOperations: Record<CalendarEventDetailOperationIds, OperationHandler<CalendarEventDetailOperationIds>>;
70
+ export declare const CalendarFreeBusyOperations: Record<CalendarFreeBusyOperationIds, OperationHandler<CalendarFreeBusyOperationIds>>;