@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
@@ -1,772 +0,0 @@
1
- /**
2
- * Issue #604: composing a reply, sending it, and then letting one more autosave
3
- * land 500'd the browser with "Internal server error" two seconds after a send
4
- * that had actually succeeded.
5
- *
6
- * A PATCH against an entry that is no longer a draft is a foreseeable race, not
7
- * a fault: the draft editor debounces its writes, so the last one can be in
8
- * flight while the send flips the status. The designed answer is 409 — the
9
- * entry is immutable now, and saying so truthfully is what lets a client stop.
10
- *
11
- * Driven through the real handlers, the real OutboxQueueService and the real
12
- * error funnel, so what is asserted is the status code the browser receives.
13
- * Only the queue and the store are stood in for.
14
- */
15
-
16
- import assert from "node:assert/strict";
17
- import { afterEach, describe, it } from "node:test";
18
- import type { SQSClient } from "@aws-sdk/client-sqs";
19
- import type {
20
- CreateOutboxAttachmentInput,
21
- CreateOutboxMessageInput,
22
- IAccountRepository,
23
- IOutboxAttachmentRepository,
24
- IOutboxMessageRepository,
25
- OutboxAttachmentItem,
26
- OutboxMessageItem,
27
- UpdateOutboxMessageInput,
28
- } from "@remit/data-ports";
29
- import { APPENDED_UID_NONE } from "@remit/data-ports";
30
- import { NotFoundError } from "@remit/data-ports/errors";
31
- import { OutboxMessageStatus } from "@remit/domain-enums";
32
- import {
33
- OutboxAttachmentService,
34
- OutboxQueueService,
35
- } from "@remit/mailbox-service";
36
- import {
37
- createMockStorageService,
38
- type StorageService,
39
- } from "@remit/storage-service";
40
- import type { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
41
- import type { Context } from "openapi-backend";
42
- import { deriveAccountConfigId } from "../auth.js";
43
- import { handleError } from "../error.js";
44
- import { formatResponse } from "../response.js";
45
- import {
46
- _resetForTest,
47
- getClient,
48
- type RemitClient,
49
- setClient,
50
- } from "../service/data-client.js";
51
- import { OutboxDetailOperations, OutboxOperations } from "./outbox.js";
52
-
53
- const CONTENT_DOMAIN = "https://content.test";
54
- process.env.CONTENT_DELIVERY_DOMAIN = CONTENT_DOMAIN;
55
-
56
- const SUB = "cognito-sub-604";
57
- const ACCOUNT_CONFIG_ID = deriveAccountConfigId(SUB);
58
- const ACCOUNT_ID = "acc-604";
59
- const ACCOUNT_EMAIL = "sender@example.com";
60
-
61
- const createInMemoryOutboxRepository = (): IOutboxMessageRepository => {
62
- const rows = new Map<string, OutboxMessageItem>();
63
- let sequence = 0;
64
-
65
- const mustGet = (outboxMessageId: string): OutboxMessageItem => {
66
- const row = rows.get(outboxMessageId);
67
- if (!row) throw new NotFoundError(`No outbox message ${outboxMessageId}`);
68
- return row;
69
- };
70
-
71
- const repository = {
72
- create: async (
73
- input: CreateOutboxMessageInput,
74
- ): Promise<OutboxMessageItem> => {
75
- sequence += 1;
76
- const now = Date.now();
77
- const row: OutboxMessageItem = {
78
- ...input,
79
- ccAddresses: input.ccAddresses ?? [],
80
- bccAddresses: input.bccAddresses ?? [],
81
- references: input.references ?? [],
82
- appendedUid: APPENDED_UID_NONE,
83
- outboxMessageId: `outbox-${sequence}`,
84
- createdAt: now,
85
- updatedAt: now,
86
- };
87
- rows.set(row.outboxMessageId, row);
88
- return row;
89
- },
90
- get: async (
91
- _accountConfigId: string,
92
- outboxMessageId: string | string[],
93
- ) =>
94
- Array.isArray(outboxMessageId)
95
- ? outboxMessageId.map(mustGet)
96
- : mustGet(outboxMessageId),
97
- update: async (
98
- _accountConfigId: string,
99
- outboxMessageId: string,
100
- input: UpdateOutboxMessageInput,
101
- ): Promise<OutboxMessageItem> => {
102
- const row = {
103
- ...mustGet(outboxMessageId),
104
- ...input,
105
- updatedAt: Date.now(),
106
- };
107
- rows.set(outboxMessageId, row);
108
- return row;
109
- },
110
- updateStatus: async (
111
- accountConfigId: string,
112
- outboxMessageId: string,
113
- status: OutboxMessageItem["status"],
114
- ) => repository.update(accountConfigId, outboxMessageId, { status }),
115
- updateIfStatus: async (
116
- accountConfigId: string,
117
- outboxMessageId: string,
118
- expected: OutboxMessageItem["status"],
119
- input: UpdateOutboxMessageInput,
120
- ) => {
121
- if (mustGet(outboxMessageId).status !== expected) return null;
122
- return repository.update(accountConfigId, outboxMessageId, input);
123
- },
124
- markSent: async (
125
- accountConfigId: string,
126
- outboxMessageId: string,
127
- fields: { sentAt: number; smtpMessageId?: string },
128
- ) =>
129
- repository.update(accountConfigId, outboxMessageId, {
130
- ...fields,
131
- status: OutboxMessageStatus.sent,
132
- }),
133
- delete: async (_accountConfigId: string, outboxMessageId: string) => {
134
- rows.delete(outboxMessageId);
135
- },
136
- deleteMany: async (
137
- _accountConfigId: string,
138
- outboxMessageIds: string[],
139
- ) => {
140
- for (const id of outboxMessageIds) rows.delete(id);
141
- },
142
- listByAccount: async () => ({
143
- items: [...rows.values()],
144
- continuationToken: null,
145
- }),
146
- listQueued: async () =>
147
- [...rows.values()].filter(
148
- (row) => row.status === OutboxMessageStatus.queued,
149
- ),
150
- } as unknown as IOutboxMessageRepository;
151
-
152
- return repository;
153
- };
154
-
155
- const acceptingSqsClient = (): SQSClient =>
156
- ({ send: async () => ({}) }) as unknown as SQSClient;
157
-
158
- /** A queue that refuses every send until `accept()` is called. */
159
- const refusingSqsClient = (): { client: SQSClient; accept: () => void } => {
160
- let accepting = false;
161
- return {
162
- client: {
163
- send: async () => {
164
- if (!accepting) throw new Error("SQS unavailable");
165
- return {};
166
- },
167
- } as unknown as SQSClient,
168
- accept: () => {
169
- accepting = true;
170
- },
171
- };
172
- };
173
-
174
- let accountSyncedServices: string[] = ["Mail"];
175
-
176
- const accountRepository = {
177
- get: async () => ({
178
- accountId: ACCOUNT_ID,
179
- accountConfigId: ACCOUNT_CONFIG_ID,
180
- email: ACCOUNT_EMAIL,
181
- syncedServices: accountSyncedServices,
182
- }),
183
- } as unknown as IAccountRepository;
184
-
185
- let installedStorage: StorageService | null = null;
186
- let attachmentRows = new Map<string, OutboxAttachmentItem>();
187
-
188
- /** Rows only — this suite asserts what a discard takes, not how bytes move. */
189
- const createAttachmentRepository = (
190
- rows: Map<string, OutboxAttachmentItem>,
191
- ): IOutboxAttachmentRepository =>
192
- ({
193
- reserve: async (input: CreateOutboxAttachmentInput) => {
194
- const item = {
195
- ...input,
196
- state: "Pending",
197
- createdAt: 0,
198
- updatedAt: 0,
199
- } as OutboxAttachmentItem;
200
- rows.set(item.outboxAttachmentId, item);
201
- return { outcome: "Reserved", item };
202
- },
203
- listByOutboxMessage: async (
204
- _accountConfigId: string,
205
- outboxMessageId: string,
206
- ) =>
207
- [...rows.values()].filter(
208
- (row) => row.outboxMessageId === outboxMessageId,
209
- ),
210
- deleteByOutboxMessage: async (
211
- _accountConfigId: string,
212
- outboxMessageId: string,
213
- ) => {
214
- for (const row of [...rows.values()]) {
215
- if (row.outboxMessageId === outboxMessageId) {
216
- rows.delete(row.outboxAttachmentId);
217
- }
218
- }
219
- },
220
- deleteLapsedReservations: async (
221
- accountConfigId: string,
222
- outboxMessageId: string,
223
- nowSeconds: number,
224
- ) => {
225
- const gone: string[] = [];
226
- for (const row of [...rows.values()]) {
227
- if (
228
- row.accountConfigId === accountConfigId &&
229
- row.outboxMessageId === outboxMessageId &&
230
- row.state === "Pending" &&
231
- row.reservationExpiresAt < nowSeconds
232
- ) {
233
- rows.delete(row.outboxAttachmentId);
234
- gone.push(row.outboxAttachmentId);
235
- }
236
- }
237
- return gone;
238
- },
239
- deleteMany: async (_accountConfigId: string, ids: string[]) => {
240
- for (const id of ids) rows.delete(id);
241
- },
242
- }) as unknown as IOutboxAttachmentRepository;
243
-
244
- const installClient = (sqsClient: SQSClient = acceptingSqsClient()): void => {
245
- const outboxMessage = createInMemoryOutboxRepository();
246
- const storage = createMockStorageService();
247
- attachmentRows = new Map<string, OutboxAttachmentItem>();
248
- const outboxAttachmentService = new OutboxAttachmentService({
249
- outboxMessageService: outboxMessage,
250
- outboxAttachmentService: createAttachmentRepository(attachmentRows),
251
- storage,
252
- });
253
- installedStorage = storage;
254
- setClient({
255
- outboxMessage,
256
- storage,
257
- account: accountRepository,
258
- outboxAttachment: outboxAttachmentService,
259
- outboxQueue: new OutboxQueueService({
260
- outboxMessageService: outboxMessage,
261
- outboxAttachmentService,
262
- accountService: accountRepository,
263
- sqsSmtpQueueUrl: "http://localhost:9324/queue/outbox-test",
264
- sqsClient,
265
- }),
266
- } as unknown as RemitClient);
267
- };
268
-
269
- const authorizedEvent = (body?: unknown): APIGatewayProxyEvent =>
270
- ({
271
- body: body === undefined ? null : JSON.stringify(body),
272
- requestContext: { authorizer: { claims: { sub: SUB } } },
273
- }) as unknown as APIGatewayProxyEvent;
274
-
275
- const requestContext = (request: {
276
- params?: Record<string, string>;
277
- requestBody?: unknown;
278
- }): Context => ({ request }) as unknown as Context;
279
-
280
- type Handler = (
281
- context: Context,
282
- event: APIGatewayProxyEvent,
283
- ) => Promise<Record<string, unknown>>;
284
-
285
- const createDraft =
286
- OutboxOperations.OutboxOperations_createOutboxMessage as Handler;
287
- const sendMessage =
288
- OutboxDetailOperations.OutboxDetailOperations_sendOutboxMessage as Handler;
289
- const updateDraft =
290
- OutboxDetailOperations.OutboxDetailOperations_updateOutboxMessage as Handler;
291
- const deleteDraft =
292
- OutboxDetailOperations.OutboxDetailOperations_deleteOutboxMessage as Handler;
293
- const getMessage =
294
- OutboxDetailOperations.OutboxDetailOperations_getOutboxMessage as Handler;
295
-
296
- type Outcome =
297
- | { readonly ok: true; readonly body: Record<string, unknown> }
298
- | { readonly ok: false; readonly error: unknown };
299
-
300
- /** The response the browser would receive, error funnel included. */
301
- const respond = async (
302
- run: () => Promise<Record<string, unknown>>,
303
- ): Promise<APIGatewayProxyResult> => {
304
- const outcome: Outcome = await run().then(
305
- (body) => ({ ok: true, body }) as const,
306
- (error: unknown) => ({ ok: false, error }) as const,
307
- );
308
- if (!outcome.ok) return handleError(outcome.error);
309
- return formatResponse(outcome.body);
310
- };
311
-
312
- const sentOutboxMessageId = async (): Promise<string> => {
313
- const draft = await createDraft(
314
- requestContext({}),
315
- authorizedEvent({
316
- accountId: ACCOUNT_ID,
317
- toAddresses: ["recipient@example.com"],
318
- subject: "Re: the thing",
319
- textBody: "on it",
320
- }),
321
- );
322
- const outboxMessageId = draft.outboxMessageId;
323
- assert.equal(typeof outboxMessageId, "string");
324
-
325
- const sent = await sendMessage(
326
- requestContext({ params: { outboxMessageId: String(outboxMessageId) } }),
327
- authorizedEvent(),
328
- );
329
- assert.notEqual(sent.status, "draft");
330
-
331
- return String(outboxMessageId);
332
- };
333
-
334
- afterEach(() => {
335
- _resetForTest();
336
- accountSyncedServices = ["Mail"];
337
- });
338
-
339
- describe("an outbox entry that has left draft (#604)", () => {
340
- it("answers a late autosave PATCH with 409, never a 500", async () => {
341
- installClient();
342
- const outboxMessageId = await sentOutboxMessageId();
343
-
344
- const response = await respond(() =>
345
- updateDraft(
346
- requestContext({
347
- params: { outboxMessageId },
348
- requestBody: { subject: "Re: the thing", textBody: "on it!" },
349
- }),
350
- authorizedEvent(),
351
- ),
352
- );
353
-
354
- assert.equal(response.statusCode, 409);
355
- const body = JSON.parse(response.body) as { message?: string };
356
- assert.match(String(body.message), /can no longer be edited/);
357
- });
358
-
359
- it("refuses a second send with 409, never a 500", async () => {
360
- installClient();
361
- const outboxMessageId = await sentOutboxMessageId();
362
-
363
- const response = await respond(() =>
364
- sendMessage(
365
- requestContext({ params: { outboxMessageId } }),
366
- authorizedEvent(),
367
- ),
368
- );
369
-
370
- assert.equal(response.statusCode, 409);
371
- });
372
-
373
- it("refuses a discard with 409, never a 500", async () => {
374
- installClient();
375
- const outboxMessageId = await sentOutboxMessageId();
376
-
377
- const response = await respond(() =>
378
- deleteDraft(
379
- requestContext({ params: { outboxMessageId } }),
380
- authorizedEvent(),
381
- ),
382
- );
383
-
384
- assert.equal(response.statusCode, 409);
385
- });
386
-
387
- it("still discards a message that was sent but never filed", async () => {
388
- installClient();
389
- const outboxMessageId = await sentOutboxMessageId();
390
- const client = await getClient();
391
- await client.outboxMessage.update(ACCOUNT_CONFIG_ID, outboxMessageId, {
392
- status: OutboxMessageStatus.unfiled,
393
- });
394
-
395
- const response = await respond(() =>
396
- deleteDraft(
397
- requestContext({ params: { outboxMessageId } }),
398
- authorizedEvent(),
399
- ),
400
- );
401
-
402
- assert.equal(response.statusCode, 204);
403
- });
404
-
405
- it("still accepts an autosave PATCH while the entry is a draft", async () => {
406
- installClient();
407
- const draft = await createDraft(
408
- requestContext({}),
409
- authorizedEvent({
410
- accountId: ACCOUNT_ID,
411
- toAddresses: ["recipient@example.com"],
412
- }),
413
- );
414
-
415
- const response = await respond(() =>
416
- updateDraft(
417
- requestContext({
418
- params: { outboxMessageId: String(draft.outboxMessageId) },
419
- requestBody: { subject: "still editing" },
420
- }),
421
- authorizedEvent(),
422
- ),
423
- );
424
-
425
- assert.equal(response.statusCode, 200);
426
- const body = JSON.parse(response.body) as { subject?: string };
427
- assert.equal(body.subject, "still editing");
428
- });
429
- });
430
-
431
- describe("a send whose enqueue fails (#845.8)", () => {
432
- const draftAgainstQueue = async (
433
- queue: SQSClient,
434
- ): Promise<{ outboxMessageId: string; response: APIGatewayProxyResult }> => {
435
- installClient(queue);
436
- const draft = await createDraft(
437
- requestContext({}),
438
- authorizedEvent({
439
- accountId: ACCOUNT_ID,
440
- toAddresses: ["recipient@example.com"],
441
- subject: "the one that got stuck",
442
- textBody: "sending",
443
- }),
444
- );
445
- const outboxMessageId = String(draft.outboxMessageId);
446
- const response = await respond(() =>
447
- sendMessage(
448
- requestContext({ params: { outboxMessageId } }),
449
- authorizedEvent(),
450
- ),
451
- );
452
- return { outboxMessageId, response };
453
- };
454
-
455
- const statusOf = async (outboxMessageId: string): Promise<unknown> => {
456
- const response = await respond(() =>
457
- getMessage(
458
- requestContext({ params: { outboxMessageId } }),
459
- authorizedEvent(),
460
- ),
461
- );
462
- assert.equal(response.statusCode, 200);
463
- return (JSON.parse(response.body) as { status?: string }).status;
464
- };
465
-
466
- it("answers 500, never a success the send never had", async () => {
467
- const { response } = await draftAgainstQueue(refusingSqsClient().client);
468
-
469
- assert.equal(response.statusCode, 500);
470
- });
471
-
472
- it("settles the row at failed, not stranded at queued and not back at draft", async () => {
473
- const { outboxMessageId } = await draftAgainstQueue(
474
- refusingSqsClient().client,
475
- );
476
-
477
- // `queued` is the dead end this suite exists for. `draft` is the other
478
- // wrong answer: it is inside the SMTP worker's send fence, and an error
479
- // from SQS does not prove the event was refused — one that landed anyway
480
- // would send a row the user can still send by hand. `failed` is outside
481
- // the fence and, since #933, still editable and sendable.
482
- assert.equal(await statusOf(outboxMessageId), OutboxMessageStatus.failed);
483
- });
484
-
485
- it("still lets the user discard what could not be queued", async () => {
486
- const { outboxMessageId } = await draftAgainstQueue(
487
- refusingSqsClient().client,
488
- );
489
-
490
- const response = await respond(() =>
491
- deleteDraft(
492
- requestContext({ params: { outboxMessageId } }),
493
- authorizedEvent(),
494
- ),
495
- );
496
-
497
- assert.equal(response.statusCode, 204);
498
- });
499
-
500
- it("sends once the queue comes back", async () => {
501
- const queue = refusingSqsClient();
502
- const { outboxMessageId } = await draftAgainstQueue(queue.client);
503
- queue.accept();
504
-
505
- const response = await respond(() =>
506
- sendMessage(
507
- requestContext({ params: { outboxMessageId } }),
508
- authorizedEvent(),
509
- ),
510
- );
511
-
512
- assert.equal(response.statusCode, 200);
513
- assert.equal(
514
- (JSON.parse(response.body) as { status?: string }).status,
515
- OutboxMessageStatus.queued,
516
- );
517
- });
518
- });
519
-
520
- describe("discarding a draft that carries files (#679)", () => {
521
- it("takes the stored bytes with it, leaving nothing behind", async () => {
522
- installClient();
523
- const storage = installedStorage;
524
- assert.ok(storage);
525
-
526
- const draft = await createDraft(
527
- requestContext({}),
528
- authorizedEvent({
529
- accountId: ACCOUNT_ID,
530
- toAddresses: ["recipient@example.com"],
531
- }),
532
- );
533
- const outboxMessageId = String(draft.outboxMessageId);
534
-
535
- const client = await getClient();
536
- const minted = await client.outboxAttachment.mint({
537
- accountConfigId: ACCOUNT_CONFIG_ID,
538
- outboxMessageId,
539
- filename: "receipt.pdf",
540
- contentType: "application/pdf",
541
- sizeBytes: 16,
542
- });
543
- assert.equal(minted.outcome, "Minted");
544
- // A mint reserves in the ledger; nothing is uploaded yet, so what a discard
545
- // has to take with it is the reservation, not an object.
546
- // A mint writes a row; nothing is uploaded yet, so what a discard has to
547
- // take with it is the row, not an object.
548
- assert.equal(attachmentRows.size, 1);
549
-
550
- const response = await respond(() =>
551
- deleteDraft(
552
- requestContext({ params: { outboxMessageId } }),
553
- authorizedEvent(),
554
- ),
555
- );
556
-
557
- assert.equal(response.statusCode, 204);
558
- // Nothing else references these objects, so a row that goes without them
559
- // leaves bytes no sweep collects.
560
- assert.deepEqual(
561
- await storage.listOutboxAttachments(
562
- ACCOUNT_CONFIG_ID,
563
- ACCOUNT_ID,
564
- outboxMessageId,
565
- ),
566
- [],
567
- );
568
- assert.equal(attachmentRows.size, 0);
569
- });
570
- });
571
-
572
- describe("attachmentIds on a draft update (#679)", () => {
573
- const seed = async (): Promise<{
574
- outboxMessageId: string;
575
- ids: string[];
576
- }> => {
577
- const draft = await createDraft(
578
- requestContext({}),
579
- authorizedEvent({
580
- accountId: ACCOUNT_ID,
581
- toAddresses: ["recipient@example.com"],
582
- }),
583
- );
584
- const outboxMessageId = String(draft.outboxMessageId);
585
- const client = await getClient();
586
- const ids: string[] = [];
587
- for (const filename of ["one.txt", "two.txt"]) {
588
- const minted = await client.outboxAttachment.mint({
589
- accountConfigId: ACCOUNT_CONFIG_ID,
590
- outboxMessageId,
591
- filename,
592
- contentType: "text/plain",
593
- sizeBytes: 8,
594
- });
595
- assert.equal(minted.outcome, "Minted");
596
- if (minted.outcome !== "Minted") throw new Error("unreachable");
597
- ids.push(minted.reservation.outboxAttachmentId);
598
- }
599
- return { outboxMessageId, ids };
600
- };
601
-
602
- const patch = (outboxMessageId: string, requestBody: unknown) =>
603
- respond(() =>
604
- updateDraft(
605
- requestContext({ params: { outboxMessageId }, requestBody }),
606
- authorizedEvent(),
607
- ),
608
- );
609
-
610
- it("absent leaves the files alone — a subject-only save keeps them", async () => {
611
- installClient();
612
- const { outboxMessageId } = await seed();
613
-
614
- const response = await patch(outboxMessageId, { subject: "still typing" });
615
-
616
- assert.equal(response.statusCode, 200);
617
- const body = JSON.parse(response.body) as { attachments: unknown[] };
618
- assert.equal(body.attachments.length, 2);
619
- assert.equal(attachmentRows.size, 2);
620
- });
621
-
622
- it("names each file by its content-id and where its bytes are read from", async () => {
623
- installClient();
624
- const { outboxMessageId, ids } = await seed();
625
-
626
- const response = await patch(outboxMessageId, { subject: "still typing" });
627
-
628
- const body = JSON.parse(response.body) as {
629
- attachments: {
630
- outboxAttachmentId: string;
631
- contentId: string;
632
- contentUrl: string;
633
- }[];
634
- };
635
- const [first] = body.attachments.filter(
636
- (item) => item.outboxAttachmentId === ids[0],
637
- );
638
- assert.equal(first.contentId, `${ids[0]}@remit`);
639
- assert.ok(
640
- first.contentUrl.startsWith(
641
- `${CONTENT_DOMAIN}/content/${attachmentRows.get(ids[0])?.storageKey}`,
642
- ),
643
- first.contentUrl,
644
- );
645
- });
646
-
647
- it("present and empty removes every file", async () => {
648
- installClient();
649
- const { outboxMessageId } = await seed();
650
-
651
- const response = await patch(outboxMessageId, { attachmentIds: [] });
652
-
653
- assert.equal(response.statusCode, 200);
654
- assert.deepEqual(
655
- (JSON.parse(response.body) as { attachments: unknown[] }).attachments,
656
- [],
657
- );
658
- assert.equal(attachmentRows.size, 0);
659
- });
660
-
661
- it("present with ids keeps those and removes the rest, bytes included", async () => {
662
- installClient();
663
- const { outboxMessageId, ids } = await seed();
664
- const storage = installedStorage;
665
- assert.ok(storage);
666
- await storage.storeOutboxAttachment({
667
- accountConfigId: ACCOUNT_CONFIG_ID,
668
- accountId: ACCOUNT_ID,
669
- outboxMessageId,
670
- outboxAttachmentId: ids[1],
671
- content: Buffer.from("dropped"),
672
- });
673
-
674
- const response = await patch(outboxMessageId, {
675
- attachmentIds: [ids[0]],
676
- });
677
-
678
- assert.equal(response.statusCode, 200);
679
- const body = JSON.parse(response.body) as {
680
- attachments: { outboxAttachmentId: string }[];
681
- };
682
- assert.deepEqual(
683
- body.attachments.map((item) => item.outboxAttachmentId),
684
- [ids[0]],
685
- );
686
- assert.equal(
687
- await storage.statOutboxAttachment(
688
- ACCOUNT_CONFIG_ID,
689
- ACCOUNT_ID,
690
- outboxMessageId,
691
- ids[1],
692
- ),
693
- null,
694
- );
695
- });
696
-
697
- it("an unknown id is a no-op, not a reason to drop the known ones", async () => {
698
- installClient();
699
- const { outboxMessageId, ids } = await seed();
700
-
701
- const response = await patch(outboxMessageId, {
702
- attachmentIds: [...ids, "never-existed"],
703
- });
704
-
705
- assert.equal(response.statusCode, 200);
706
- assert.equal(attachmentRows.size, 2);
707
- });
708
- });
709
-
710
- describe("sending from an account with mail off (#1181)", () => {
711
- const assertRefusal = (response: APIGatewayProxyResult): void => {
712
- assert.equal(response.statusCode, 400);
713
- const body = JSON.parse(response.body) as {
714
- code?: string;
715
- message?: string;
716
- details?: Record<string, string>;
717
- };
718
- assert.equal(body.code, "mail_sync_off");
719
- assert.match(String(body.message), /Turn Mail back on .* in Settings/);
720
- assert.deepEqual(body.details, { accountId: ACCOUNT_ID });
721
- };
722
-
723
- it("answers a send of a saved draft with a 400 naming the fix", async () => {
724
- installClient();
725
- const draft = await createDraft(
726
- requestContext({}),
727
- authorizedEvent({
728
- accountId: ACCOUNT_ID,
729
- toAddresses: ["recipient@example.com"],
730
- subject: "hello",
731
- }),
732
- );
733
- accountSyncedServices = ["Calendar"];
734
-
735
- const response = await respond(() =>
736
- sendMessage(
737
- requestContext({
738
- params: { outboxMessageId: String(draft.outboxMessageId) },
739
- }),
740
- authorizedEvent(),
741
- ),
742
- );
743
-
744
- assertRefusal(response);
745
- const kept = await getMessage(
746
- requestContext({
747
- params: { outboxMessageId: String(draft.outboxMessageId) },
748
- }),
749
- authorizedEvent(),
750
- );
751
- assert.equal(kept.status, "draft");
752
- });
753
-
754
- it("answers a send-immediately create with the same 400", async () => {
755
- installClient();
756
- accountSyncedServices = ["Calendar"];
757
-
758
- const response = await respond(() =>
759
- createDraft(
760
- requestContext({}),
761
- authorizedEvent({
762
- accountId: ACCOUNT_ID,
763
- toAddresses: ["recipient@example.com"],
764
- subject: "hello",
765
- sendImmediately: true,
766
- }),
767
- ),
768
- );
769
-
770
- assertRefusal(response);
771
- });
772
- });