@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
@@ -1,552 +0,0 @@
1
- import { SendMessageCommand } from "@aws-sdk/client-sqs";
2
- import type {
3
- AccountResponse,
4
- CreateAccountInput,
5
- DeleteAccountResponse,
6
- TestConnectionInput,
7
- TestConnectionResponse,
8
- UpdateAccountInput,
9
- } from "@remit/api-openapi-types";
10
- import type { AccountItem, IAccountRepository } from "@remit/data-ports";
11
- import {
12
- AccountAuthType,
13
- AccountService,
14
- ConnectionState,
15
- } from "@remit/domain-enums";
16
- import { logger } from "@remit/logger-lambda";
17
- import {
18
- createMailOAuthService,
19
- microsoftProviderConfig,
20
- RefreshTokenError,
21
- } from "@remit/mail-oauth-service";
22
- import {
23
- resolveConnectionCredentials,
24
- testImapConnection,
25
- testSmtpConnection,
26
- } from "@remit/mailbox-service";
27
- import {
28
- deserializeEncryptedPayload,
29
- type SecretsService,
30
- serializeEncryptedPayload,
31
- } from "@remit/secrets-service";
32
- import type { APIGatewayProxyEvent } from "aws-lambda";
33
- import { env } from "expect-env";
34
- import type { Context } from "openapi-backend";
35
- import { getAccountConfigIdFromEvent } from "../auth.js";
36
- import { getClient } from "../service/data-client.js";
37
- import { fireAndForget } from "../service/fire-and-forget.js";
38
- import { sqsClient } from "../service/sqs.js";
39
- import { triggerAccountSync } from "../service/trigger-sync.js";
40
- import type {
41
- AccountDetailOperationIds,
42
- AccountOperationIds,
43
- OperationHandler,
44
- } from "../types.js";
45
- import {
46
- assertNoDuplicateMailbox,
47
- assertNotOAuthCreate,
48
- assertPasswordProvided,
49
- resolveSyncedServices,
50
- toAccountResponse,
51
- } from "./account-guards.js";
52
- import {
53
- loadAccountOverrides,
54
- upsertAccountDisplayName,
55
- writeAccountComposeLanguages,
56
- writeAccountMuted,
57
- } from "./account-overrides.js";
58
- import { assertAccountOwnership } from "./account-ownership.js";
59
- import {
60
- loadSignatureForAccount,
61
- upsertAccountSignature,
62
- } from "./account-signature.js";
63
- import { ensureAccountConfig } from "./ensure-account-config.js";
64
- import { resolveAccountFolderAppointments } from "./folder-role-appointments.js";
65
-
66
- export { assertNotOAuthCreate, assertPasswordProvided, toAccountResponse };
67
-
68
- export const triggerAccountSyncSafe = async (
69
- accountId: string,
70
- ): Promise<void> => {
71
- const queueUrl = env.SQS_QUEUE_URL;
72
- // Best-effort: account creation must still return 200 even if the sync
73
- // enqueue fails. fireAndForget catches and logs every rejection loudly with
74
- // the alertable structured fields and never rejects, so a failure here (SQS
75
- // unreachable in smoke/e2e, an IAM/SQS misconfig in prod) cannot leak an
76
- // unhandled rejection onto an unrelated in-flight request.
77
- await fireAndForget(
78
- async () => {
79
- const { eventId } = await triggerAccountSync({
80
- sqsClient,
81
- queueUrl,
82
- accountId,
83
- });
84
- // biome-ignore lint/plugin/no-logger-info: sync-triggered-for-new-account is an audit-grade signal
85
- logger.info({ accountId, eventId }, "Sync triggered for new account");
86
- },
87
- {
88
- source: "account_create",
89
- message: "Failed to enqueue SYNC_MAILBOXES for new account (best-effort)",
90
- ids: { accountId },
91
- },
92
- );
93
- };
94
-
95
- /**
96
- * Test connectivity for an OAuth (Microsoft) account.
97
- *
98
- * Mints an access token from the stored refresh token via
99
- * resolveConnectionCredentials (the single authType branch), then runs the
100
- * IMAP — and, when configured, SMTP — connection tests with those credentials.
101
- *
102
- * A revoked / expired refresh token surfaces as RefreshTokenError; the
103
- * reauth-required case is mapped to the distinct `reauth_required` error code
104
- * so the UI can route the user into the OAuth re-auth flow.
105
- *
106
- * MSOAUTH_* env vars are only present in deployed Lambdas; fall back to "".
107
- */
108
- const testOAuthConnection = async (
109
- existingAccount: AccountItem,
110
- account: IAccountRepository,
111
- secrets: SecretsService,
112
- ): Promise<TestConnectionResponse> => {
113
- const tokenService = createMailOAuthService(
114
- microsoftProviderConfig({
115
- clientId: process.env.MSOAUTH_CLIENT_ID ?? "",
116
- clientSecret: process.env.MSOAUTH_CLIENT_SECRET ?? "",
117
- overrides: process.env.MSOAUTH_TOKEN_ENDPOINT
118
- ? { tokenEndpoint: process.env.MSOAUTH_TOKEN_ENDPOINT }
119
- : undefined,
120
- }),
121
- );
122
-
123
- let resolution: Awaited<ReturnType<typeof resolveConnectionCredentials>>;
124
- try {
125
- resolution = await resolveConnectionCredentials(existingAccount, {
126
- secrets,
127
- tokenService,
128
- persistRotatedToken: async (id, encryptedHash, updatedAt) => {
129
- await account.update(id, {
130
- oauthRefreshTokenHash: encryptedHash,
131
- oauthTokenUpdatedAt: updatedAt,
132
- });
133
- },
134
- });
135
- } catch (err) {
136
- if (
137
- err instanceof RefreshTokenError &&
138
- err.error.kind === "reauth-required"
139
- ) {
140
- return {
141
- imapSuccess: false,
142
- imapError: "reauth_required",
143
- smtpSuccess: undefined,
144
- };
145
- }
146
- throw err;
147
- }
148
-
149
- if (resolution.status === "missing") {
150
- return {
151
- imapSuccess: false,
152
- imapError: "oauth_not_configured",
153
- smtpSuccess: undefined,
154
- };
155
- }
156
- const credentials = resolution.credentials;
157
-
158
- const result: TestConnectionResponse = {
159
- imapSuccess: false,
160
- smtpSuccess: undefined,
161
- };
162
-
163
- const imapResult = await testImapConnection({
164
- host: existingAccount.imapHost,
165
- port: existingAccount.imapPort,
166
- secure: existingAccount.imapTls,
167
- user: existingAccount.username,
168
- credentials,
169
- });
170
- result.imapSuccess = imapResult.success;
171
- if (!imapResult.success) {
172
- result.imapError = imapResult.error;
173
- }
174
-
175
- // OAuth accounts share the same access token for IMAP and SMTP.
176
- if (existingAccount.smtpEnabled) {
177
- const smtpResult = await testSmtpConnection({
178
- host: existingAccount.smtpHost ?? "",
179
- port: existingAccount.smtpPort ?? 587,
180
- secure: existingAccount.smtpTls ?? false,
181
- user: existingAccount.smtpUsername || existingAccount.username,
182
- credentials,
183
- });
184
- result.smtpSuccess = smtpResult.success;
185
- if (!smtpResult.success) {
186
- result.smtpError = smtpResult.error;
187
- }
188
- }
189
-
190
- return result;
191
- };
192
-
193
- export const AccountOperations: Record<
194
- AccountOperationIds,
195
- OperationHandler<AccountOperationIds>
196
- > = {
197
- AccountOperations_createAccount: async (
198
- _context: Context,
199
- ...args: unknown[]
200
- ): Promise<AccountResponse> => {
201
- const event = args[0] as APIGatewayProxyEvent;
202
- const accountConfigId = getAccountConfigIdFromEvent(event);
203
- const input = JSON.parse(event.body ?? "{}") as CreateAccountInput;
204
-
205
- // OAuth accounts must be created via the dedicated connect flow
206
- assertNotOAuthCreate(input.authType);
207
-
208
- // Password accounts require a non-empty password
209
- assertPasswordProvided(input.authType, input.password);
210
-
211
- const syncedServices = resolveSyncedServices(
212
- { authType: AccountAuthType.Password, grantedScopes: [] },
213
- input.syncedServices ?? [AccountService.Mail],
214
- );
215
-
216
- const { account, accountConfig, accountSetting, mailbox, secrets } =
217
- await getClient();
218
-
219
- await ensureAccountConfig(accountConfig, accountConfigId);
220
-
221
- // Reject re-onboarding the same mailbox-in-the-same-place. Message
222
- // identity is account-scoped (#633), so duplicate onboards are no longer
223
- // incidentally deduped — this is the explicit replacement (#635).
224
- const existingAccounts =
225
- await account.listAllByAccountConfig(accountConfigId);
226
- assertNoDuplicateMailbox(existingAccounts, {
227
- imapHost: input.imapHost,
228
- username: input.username ?? input.email,
229
- });
230
-
231
- // biome-ignore lint/style/noNonNullAssertion: guard above ensures password is set for password-auth accounts
232
- const passwordPayload = await secrets.encrypt(input.password!);
233
- const passwordHash = JSON.stringify(
234
- serializeEncryptedPayload(passwordPayload),
235
- );
236
-
237
- let smtpPasswordHash: string | undefined;
238
- if (input.smtpPassword) {
239
- const smtpPayload = await secrets.encrypt(input.smtpPassword);
240
- smtpPasswordHash = JSON.stringify(serializeEncryptedPayload(smtpPayload));
241
- }
242
-
243
- const newAccount = await account.create({
244
- accountConfigId,
245
- email: input.email,
246
- username: input.username ?? input.email,
247
- authType: AccountAuthType.Password,
248
- syncedServices,
249
- passwordHash,
250
- imapHost: input.imapHost,
251
- imapPort: input.imapPort,
252
- imapTls: input.imapTls,
253
- imapStartTls: input.imapStartTls,
254
- // RFC 032 Tier 2: smtpEnabled is the explicit send-capability marker.
255
- // Honour an explicit flag from the client; otherwise enable sending when
256
- // an SMTP host was supplied (the prior implicit behaviour).
257
- smtpEnabled: input.smtpEnabled ?? Boolean(input.smtpHost),
258
- smtpHost: input.smtpHost,
259
- smtpPort: input.smtpPort,
260
- smtpTls: input.smtpTls,
261
- smtpStartTls: input.smtpStartTls,
262
- smtpUsername: input.smtpUsername,
263
- smtpPasswordHash,
264
- isActive: true,
265
- connectionState: ConnectionState.NotAuthenticated,
266
- });
267
-
268
- // Display name lives in a per-account AccountSetting row (RFC 032), not on
269
- // the entity. Persist it when supplied so the response and later reads
270
- // surface it unchanged.
271
- if (input.displayName !== undefined) {
272
- await upsertAccountDisplayName(
273
- accountSetting,
274
- accountConfigId,
275
- newAccount.accountId,
276
- input.displayName,
277
- );
278
- }
279
-
280
- await triggerAccountSyncSafe(newAccount.accountId);
281
-
282
- const [overrides, folderAppointments] = await Promise.all([
283
- loadAccountOverrides(
284
- accountSetting,
285
- accountConfigId,
286
- newAccount.accountId,
287
- ),
288
- resolveAccountFolderAppointments(
289
- { mailbox, accountSetting },
290
- accountConfigId,
291
- newAccount.accountId,
292
- ),
293
- ]);
294
- return toAccountResponse(newAccount, {}, overrides, folderAppointments);
295
- },
296
-
297
- AccountOperations_testConnection: async (
298
- _context: Context,
299
- ...args: unknown[]
300
- ): Promise<TestConnectionResponse> => {
301
- const event = args[0] as APIGatewayProxyEvent;
302
- const accountConfigId = getAccountConfigIdFromEvent(event);
303
- const input = JSON.parse(event.body ?? "{}") as TestConnectionInput;
304
-
305
- const { account, secrets } = await getClient();
306
-
307
- // Resolve password - use provided password or decrypt stored password
308
- let imapPassword = input.password;
309
- let smtpPassword = input.smtpPassword;
310
-
311
- if (!imapPassword && input.accountId) {
312
- const existingAccount = await account.get(input.accountId);
313
- assertAccountOwnership(existingAccount, accountConfigId, "read");
314
-
315
- const authType = existingAccount.authType ?? "password";
316
- if (authType === "oauthMicrosoft") {
317
- return testOAuthConnection(existingAccount, account, secrets);
318
- }
319
-
320
- if (existingAccount.passwordHash) {
321
- const payload = deserializeEncryptedPayload(
322
- JSON.parse(existingAccount.passwordHash),
323
- );
324
- imapPassword = await secrets.decrypt(payload);
325
- }
326
-
327
- // Also get SMTP password if needed and available
328
- if (!smtpPassword && existingAccount.smtpPasswordHash) {
329
- const smtpPayload = deserializeEncryptedPayload(
330
- JSON.parse(existingAccount.smtpPasswordHash),
331
- );
332
- smtpPassword = await secrets.decrypt(smtpPayload);
333
- }
334
- }
335
-
336
- if (!imapPassword) {
337
- return {
338
- imapSuccess: false,
339
- imapError: "Password required",
340
- smtpSuccess: undefined,
341
- };
342
- }
343
-
344
- const result: TestConnectionResponse = {
345
- imapSuccess: false,
346
- smtpSuccess: undefined,
347
- };
348
-
349
- // Test IMAP connection
350
- const imapResult = await testImapConnection({
351
- host: input.imapHost,
352
- port: input.imapPort,
353
- secure: input.imapTls,
354
- startTls: input.imapStartTls,
355
- user: input.username,
356
- credentials: { kind: "password", password: imapPassword },
357
- });
358
-
359
- result.imapSuccess = imapResult.success;
360
- if (!imapResult.success) {
361
- result.imapError = imapResult.error;
362
- }
363
-
364
- // Test SMTP connection if configured
365
- if (input.smtpHost) {
366
- const smtpResult = await testSmtpConnection({
367
- host: input.smtpHost,
368
- port: input.smtpPort ?? 587,
369
- secure: input.smtpTls ?? false,
370
- user: input.smtpUsername ?? input.username,
371
- credentials: {
372
- kind: "password",
373
- password: smtpPassword ?? imapPassword,
374
- },
375
- });
376
-
377
- result.smtpSuccess = smtpResult.success;
378
- if (!smtpResult.success) {
379
- result.smtpError = smtpResult.error;
380
- }
381
- }
382
-
383
- return result;
384
- },
385
- };
386
-
387
- export const AccountDetailOperations: Record<
388
- AccountDetailOperationIds,
389
- OperationHandler<AccountDetailOperationIds>
390
- > = {
391
- AccountDetailOperations_updateAccount: async (
392
- context: Context,
393
- ...args: unknown[]
394
- ): Promise<AccountResponse> => {
395
- const event = args[0] as APIGatewayProxyEvent;
396
- const accountConfigId = getAccountConfigIdFromEvent(event);
397
- const { accountId } = context.request.params as { accountId: string };
398
- const input = JSON.parse(event.body ?? "{}") as UpdateAccountInput;
399
-
400
- const { account, accountSetting, mailbox, secrets } = await getClient();
401
-
402
- const existing = await account.get(accountId);
403
- assertAccountOwnership(existing, accountConfigId, "act");
404
-
405
- const updates: Record<string, unknown> = {};
406
-
407
- // Handle password updates
408
- if (input.password) {
409
- const payload = await secrets.encrypt(input.password);
410
- updates.passwordHash = JSON.stringify(serializeEncryptedPayload(payload));
411
- }
412
- if (input.smtpPassword) {
413
- const payload = await secrets.encrypt(input.smtpPassword);
414
- updates.smtpPasswordHash = JSON.stringify(
415
- serializeEncryptedPayload(payload),
416
- );
417
- }
418
-
419
- if (input.syncedServices !== undefined) {
420
- updates.syncedServices = resolveSyncedServices(
421
- existing,
422
- input.syncedServices,
423
- );
424
- }
425
-
426
- // Copy non-password fields
427
- const fields = [
428
- "imapHost",
429
- "imapPort",
430
- "imapTls",
431
- "imapStartTls",
432
- "smtpEnabled",
433
- "smtpHost",
434
- "smtpPort",
435
- "smtpTls",
436
- "smtpStartTls",
437
- "smtpUsername",
438
- "isActive",
439
- ] as const;
440
-
441
- for (const field of fields) {
442
- if (input[field] !== undefined) {
443
- updates[field] = input[field];
444
- }
445
- }
446
-
447
- // RFC 032 Tier 2: keep the explicit send-capability marker in sync. When a
448
- // caller changes the SMTP host without passing smtpEnabled, derive it from
449
- // host presence so the marker can't drift from the config.
450
- if (input.smtpEnabled === undefined && input.smtpHost !== undefined) {
451
- updates.smtpEnabled = Boolean(input.smtpHost);
452
- }
453
-
454
- // Display name and the mute flag live in per-account AccountSetting rows
455
- // (RFC 032), not on the account entity. Display name upserts when supplied;
456
- // the mute flag follows the address-flag null→remove, object→set semantics
457
- // (the client populates setAt).
458
- if (input.displayName !== undefined) {
459
- await upsertAccountDisplayName(
460
- accountSetting,
461
- accountConfigId,
462
- accountId,
463
- input.displayName,
464
- );
465
- }
466
- if (input.composeLanguages !== undefined) {
467
- await writeAccountComposeLanguages(
468
- accountSetting,
469
- accountConfigId,
470
- accountId,
471
- input.composeLanguages,
472
- );
473
- }
474
- if (Object.hasOwn(input, "muted")) {
475
- if (input.muted !== undefined) {
476
- await writeAccountMuted(
477
- accountSetting,
478
- accountConfigId,
479
- accountId,
480
- input.muted,
481
- );
482
- }
483
- }
484
-
485
- // Signatures live in per-account AccountSetting rows (RFC 032), not on the
486
- // account entity. Persist each supplied part as a composite-named setting;
487
- // an empty string is a valid stored value (preserves the prior "set ''
488
- // stores ''" semantics — it does not delete the row).
489
- if (
490
- input.signaturePlainText !== undefined ||
491
- input.signatureHtml !== undefined
492
- ) {
493
- await upsertAccountSignature(accountSetting, accountConfigId, accountId, {
494
- plainText: input.signaturePlainText,
495
- html: input.signatureHtml,
496
- });
497
- }
498
-
499
- const updated = await account.update(accountId, updates);
500
-
501
- const [signature, overrides, folderAppointments] = await Promise.all([
502
- loadSignatureForAccount(accountSetting, accountConfigId, accountId),
503
- loadAccountOverrides(accountSetting, accountConfigId, accountId),
504
- resolveAccountFolderAppointments(
505
- { mailbox, accountSetting },
506
- accountConfigId,
507
- accountId,
508
- ),
509
- ]);
510
- return toAccountResponse(updated, signature, overrides, folderAppointments);
511
- },
512
-
513
- AccountDetailOperations_deleteAccount: async (
514
- context: Context,
515
- ...args: unknown[]
516
- ): Promise<DeleteAccountResponse> => {
517
- const event = args[0] as APIGatewayProxyEvent;
518
- const accountConfigId = getAccountConfigIdFromEvent(event);
519
- const { accountId } = context.request.params as { accountId: string };
520
-
521
- const { account } = await getClient();
522
-
523
- const existing = await account.get(accountId);
524
- assertAccountOwnership(existing, accountConfigId, "act");
525
-
526
- const deletedAt = Date.now();
527
- await account.update(accountId, {
528
- deletedAt,
529
- isActive: false,
530
- });
531
-
532
- await sqsClient.send(
533
- new SendMessageCommand({
534
- QueueUrl: env.SQS_QUEUE_URL_ACCOUNT_FANOUT,
535
- MessageBody: JSON.stringify({
536
- type: "AccountDataPurge",
537
- accountId,
538
- accountConfigId,
539
- }),
540
- }),
541
- );
542
- // biome-ignore lint/plugin/no-logger-info: account data purge is an audit-grade signal
543
- logger.info({ accountId, accountConfigId }, "Account data purge initiated");
544
-
545
- return {
546
- accountId,
547
- deletedAt,
548
- message:
549
- "Account marked for deletion. Data cleanup will complete shortly.",
550
- };
551
- },
552
- };