@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
package/src/error.ts DELETED
@@ -1,123 +0,0 @@
1
- import { isPublicApiError } from "@remit/data-ports/errors";
2
- import { logger } from "@remit/logger-lambda";
3
- import type { APIGatewayProxyResult } from "aws-lambda";
4
- import { formatResponse } from "./response.js";
5
-
6
- /**
7
- * The `code` a refusal carries when it does not name its own. Every error body
8
- * the API emits is flat `{ code, message }` (issue #371), and `code` is the
9
- * only field a client may branch on — a message is a sentence for a person and
10
- * is free to change.
11
- *
12
- * A 5xx always answers `internal_error`, whatever the throw site said: a coded
13
- * 5xx is a mistake at the throw site, not a contract, and a fixed token cannot
14
- * carry anything about the failure out of the process.
15
- */
16
- export const INTERNAL_ERROR_CODE = "internal_error";
17
-
18
- /**
19
- * The one sentence any 5xx answers with. A thrown message is written for a log
20
- * line, not for a stranger — it names hosts, queries and ids — so it is
21
- * replaced rather than trusted. The real message is already on the error log
22
- * beside the correlation id the response carries.
23
- */
24
- export const INTERNAL_ERROR_MESSAGE = "Internal server error";
25
-
26
- const CODE_BY_STATUS: Record<number, string> = {
27
- 400: "invalid_request",
28
- 401: "unauthorized",
29
- 403: "forbidden",
30
- 404: "not_found",
31
- 409: "conflict",
32
- 412: "precondition_failed",
33
- 413: "payload_too_large",
34
- 422: "unprocessable_entity",
35
- };
36
-
37
- export const defaultErrorCode = (statusCode: number): string => {
38
- if (statusCode >= 500) return INTERNAL_ERROR_CODE;
39
- return CODE_BY_STATUS[statusCode] ?? "request_refused";
40
- };
41
-
42
- export const handleError = async (
43
- error: unknown,
44
- ): Promise<APIGatewayProxyResult> => {
45
- if (error instanceof Error) {
46
- if ("statusCode" in error) {
47
- logger.error(
48
- {
49
- error: error.message,
50
- statusCode: error.statusCode,
51
- stack: error.stack,
52
- },
53
- "Error with statusCode",
54
- );
55
- // An error that opted in names its own code and details, and only below
56
- // 500: the status bound keeps a coded 5xx from reaching a client rather
57
- // than trusting every future thrower to leave `publicApiError` alone.
58
- // Everything else takes the status class's code, so no response goes out
59
- // without one. A 5xx keeps neither the thrower's code nor its message —
60
- // one status, one code, one sentence, whatever failed.
61
- const statusCode =
62
- typeof error.statusCode === "number" ? error.statusCode : 500;
63
- if (statusCode >= 500) {
64
- return formatResponse(
65
- { code: INTERNAL_ERROR_CODE, message: INTERNAL_ERROR_MESSAGE },
66
- statusCode,
67
- );
68
- }
69
- const publicApiError =
70
- "publicApiError" in error && isPublicApiError(error.publicApiError)
71
- ? error.publicApiError
72
- : undefined;
73
- return formatResponse(
74
- {
75
- code: defaultErrorCode(statusCode),
76
- message: error.message,
77
- ...publicApiError,
78
- },
79
- statusCode,
80
- );
81
- }
82
-
83
- if (error.name === "ElectroError") {
84
- // DynamoDB client/infrastructure errors should be 500
85
- // These contain "aws-error" in the message or reference URL
86
- const isInfrastructureError =
87
- error.message.includes("aws-error") ||
88
- error.message.includes("DynamoDB client");
89
-
90
- const statusCode = isInfrastructureError ? 500 : 400;
91
- const logMessage = isInfrastructureError
92
- ? "DynamoDB infrastructure error"
93
- : "ElectroError";
94
-
95
- logger.error({ error: error.message, stack: error.stack }, logMessage);
96
-
97
- // Don't expose internal details for infrastructure errors
98
- const responseMessage = isInfrastructureError
99
- ? "Database temporarily unavailable"
100
- : error.message;
101
-
102
- return formatResponse(
103
- { code: defaultErrorCode(statusCode), message: responseMessage },
104
- statusCode,
105
- );
106
- }
107
-
108
- logger.error(
109
- { error: error.message, name: error.name, stack: error.stack },
110
- "Unhandled Error",
111
- );
112
- return formatResponse(
113
- { code: INTERNAL_ERROR_CODE, message: INTERNAL_ERROR_MESSAGE },
114
- 500,
115
- );
116
- }
117
-
118
- logger.error({ error: JSON.stringify(error) }, "Unknown error type");
119
- return formatResponse(
120
- { code: INTERNAL_ERROR_CODE, message: INTERNAL_ERROR_MESSAGE },
121
- 500,
122
- );
123
- };
@@ -1,67 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { describe, it } from "node:test";
3
- import { AccountAuthType } from "@remit/domain-enums";
4
- import type { APIGatewayProxyResult } from "aws-lambda";
5
- import { handleError } from "../error.js";
6
- import {
7
- assertNotOAuthCreate,
8
- assertPasswordProvided,
9
- } from "./account-guards.js";
10
-
11
- const refusalOf = (guard: () => void): Promise<APIGatewayProxyResult> => {
12
- let thrown: unknown;
13
- assert.throws(guard, (error: unknown) => {
14
- thrown = error;
15
- return true;
16
- });
17
- return handleError(thrown);
18
- };
19
-
20
- // Both guards used to throw `{ status: 400 }`, and the emitter reads
21
- // `statusCode`. The status never matched, so a create the API meant to refuse
22
- // as malformed answered 500 with "Internal server error" — telling the caller
23
- // the server broke rather than what to change (issue #371).
24
- describe("the create-account guards", () => {
25
- it("refuses an OAuth create as a 400 the caller can act on", async () => {
26
- const response = await refusalOf(() =>
27
- assertNotOAuthCreate(AccountAuthType.OauthMicrosoft),
28
- );
29
-
30
- assert.equal(response.statusCode, 400);
31
- const body = JSON.parse(response.body) as {
32
- code: string;
33
- message: string;
34
- };
35
- assert.equal(body.code, "invalid_request");
36
- assert.match(body.message, /OAuth connect flow/);
37
- });
38
-
39
- it("refuses a password create with no password as a 400", async () => {
40
- const response = await refusalOf(() =>
41
- assertPasswordProvided(AccountAuthType.Password, undefined),
42
- );
43
-
44
- assert.equal(response.statusCode, 400);
45
- const body = JSON.parse(response.body) as {
46
- code: string;
47
- message: string;
48
- };
49
- assert.equal(body.code, "invalid_request");
50
- assert.match(body.message, /password is required/);
51
- });
52
-
53
- it("refuses a create that omits authType and password alike", async () => {
54
- const response = await refusalOf(() =>
55
- assertPasswordProvided(undefined, undefined),
56
- );
57
-
58
- assert.equal(response.statusCode, 400);
59
- });
60
-
61
- it("lets a password create with a password through", () => {
62
- assert.doesNotThrow(() =>
63
- assertPasswordProvided(AccountAuthType.Password, "hunter2"),
64
- );
65
- assert.doesNotThrow(() => assertNotOAuthCreate(AccountAuthType.Password));
66
- });
67
- });
@@ -1,169 +0,0 @@
1
- import type {
2
- AccountResponse,
3
- AccountService as AccountServiceName,
4
- FolderAppointment,
5
- } from "@remit/api-openapi-types";
6
- import type { AccountItem } from "@remit/data-ports";
7
- import { BadRequestError, ConflictError } from "@remit/data-ports/errors";
8
- import { AccountAuthType, AccountService } from "@remit/domain-enums";
9
- import {
10
- microsoftServicesGranted,
11
- orderServices,
12
- } from "@remit/mail-oauth-service";
13
- import type { AccountOverrides } from "./account-overrides.js";
14
- import type { AccountSignature } from "./account-signature.js";
15
-
16
- /**
17
- * Natural key identifying "the same mailbox in the same place" within an
18
- * account config. IMAP host and login username are both case-insensitive, so we
19
- * fold to lowercase before comparing. Used as the explicit server-side
20
- * uniqueness key now that message identity is account-scoped (entropy per
21
- * onboard) and no longer incidentally dedups duplicate onboards (#633/#635).
22
- */
23
- export interface MailboxNaturalKey {
24
- imapHost: string;
25
- username: string;
26
- }
27
-
28
- const mailboxKeyOf = (key: MailboxNaturalKey): string =>
29
- `${key.imapHost.toLowerCase()}\u0000${key.username.toLowerCase()}`;
30
-
31
- /**
32
- * Find an existing ACTIVE (non-deleted) account that occupies the same
33
- * mailbox-in-the-same-place as `key`. Soft-deleted accounts are ignored so a
34
- * re-onboard after delete still succeeds.
35
- *
36
- * Callers pass the accounts already scoped to one account config (the natural
37
- * key's accountConfigId component), so this only matches on host + username.
38
- */
39
- export const findActiveDuplicateMailbox = (
40
- existing: AccountItem[],
41
- key: MailboxNaturalKey,
42
- ): AccountItem | undefined => {
43
- const target = mailboxKeyOf(key);
44
- return existing.find(
45
- (account) =>
46
- !account.deletedAt &&
47
- mailboxKeyOf({
48
- imapHost: account.imapHost,
49
- username: account.username,
50
- }) === target,
51
- );
52
- };
53
-
54
- /**
55
- * Reject the create when an active account already onboards the same mailbox in
56
- * the same place. Surfaces as a typed 409 ConflictError so the web-client can
57
- * show a "already added" message instead of silently creating a duplicate.
58
- */
59
- export const assertNoDuplicateMailbox = (
60
- existing: AccountItem[],
61
- key: MailboxNaturalKey,
62
- ): void => {
63
- const duplicate = findActiveDuplicateMailbox(existing, key);
64
- if (!duplicate) return;
65
- throw new ConflictError(
66
- `An account for ${key.username} on ${key.imapHost} already exists`,
67
- );
68
- };
69
-
70
- /** Rejects OAuth accounts that must go through the dedicated connect flow. */
71
- export const assertNotOAuthCreate = (authType: string | undefined): void => {
72
- if (authType === AccountAuthType.OauthMicrosoft) {
73
- throw new BadRequestError(
74
- "OAuth accounts must be created via the OAuth connect flow (POST /accounts/oauth/microsoft/start)",
75
- );
76
- }
77
- };
78
-
79
- /** Rejects password-auth account creation when no password is supplied. */
80
- export const assertPasswordProvided = (
81
- authType: string | undefined,
82
- password: string | undefined,
83
- ): void => {
84
- const isPasswordAuth = authType === AccountAuthType.Password || !authType;
85
- if (isPasswordAuth && !password) {
86
- throw new BadRequestError(
87
- "password is required when authType is 'password' (or when authType is omitted)",
88
- );
89
- }
90
- };
91
-
92
- export const resolveSyncedServices = (
93
- account: Pick<AccountItem, "authType" | "grantedScopes">,
94
- requested: readonly AccountServiceName[],
95
- ): AccountServiceName[] => {
96
- const services = orderServices(requested);
97
- if (services.length === 0) {
98
- throw new BadRequestError(
99
- "syncedServices must name at least one service. To stop syncing an account entirely, delete it with DELETE /accounts/{accountId}.",
100
- );
101
- }
102
- if (account.authType !== AccountAuthType.OauthMicrosoft) {
103
- if (services.some((service) => service !== AccountService.Mail)) {
104
- throw new BadRequestError(
105
- `A password account syncs mail only, so syncedServices must be ["${AccountService.Mail}"].`,
106
- );
107
- }
108
- return services;
109
- }
110
- const granted = microsoftServicesGranted(account.grantedScopes);
111
- const uncovered = services.filter((service) => !granted.includes(service));
112
- if (uncovered.length > 0) {
113
- throw new BadRequestError(
114
- `This account's granted scopes lack ${uncovered.join(", ")}. Consent to them through POST /accounts/oauth/microsoft/start with services ${JSON.stringify(services)}, then sign in to Microsoft again.`,
115
- );
116
- }
117
- return services;
118
- };
119
-
120
- // SECURITY: passwordHash, oauthRefreshTokenHash, and smtpPasswordHash are
121
- // intentionally omitted — never expose token material in API responses.
122
- // Display name, mute flag, and signatures live in per-account AccountSetting
123
- // rows (RFC 032); the caller resolves them and passes them in. Absent means the
124
- // override is unset. `folderAppointments` (RFC 032 exclusive-folder-appointment,
125
- // #976) is resolved the same way — persisted rows merged with server-proposed
126
- // defaults for any unfilled role — via `resolveFolderAppointments`.
127
- export const toAccountResponse = (
128
- account: AccountItem,
129
- signature: AccountSignature = {},
130
- overrides: AccountOverrides = {},
131
- folderAppointments: FolderAppointment[] = [],
132
- ): AccountResponse => ({
133
- accountId: account.accountId,
134
- accountConfigId: account.accountConfigId,
135
- displayName: overrides.displayName,
136
- username: account.username,
137
- email: account.email,
138
- authType: account.authType ?? AccountAuthType.Password,
139
- syncedServices: account.syncedServices,
140
- grantedScopes: account.grantedScopes,
141
- imapHost: account.imapHost,
142
- imapPort: account.imapPort,
143
- imapTls: account.imapTls,
144
- imapStartTls: account.imapStartTls,
145
- // RFC 032 Tier 2: SMTP config is total. ElectroDB `default` applies on write
146
- // only, so rows written before this change still lack these attributes —
147
- // coalesce to the schema defaults on read so the response is always complete.
148
- smtpEnabled: account.smtpEnabled ?? false,
149
- smtpHost: account.smtpHost ?? "",
150
- smtpPort: account.smtpPort ?? 587,
151
- smtpTls: account.smtpTls ?? false,
152
- smtpStartTls: account.smtpStartTls ?? true,
153
- smtpUsername: account.smtpUsername ?? "",
154
- signaturePlainText: signature.plainText,
155
- signatureHtml: signature.html,
156
- composeLanguages: overrides.composeLanguages,
157
- isActive: account.isActive,
158
- connectionState: account.connectionState,
159
- lastConnectedAt: account.lastConnectedAt,
160
- lastSyncAt: account.lastSyncAt,
161
- lastError: account.lastError,
162
- syncPhase: account.syncPhase,
163
- mailboxCountTotal: account.mailboxCountTotal,
164
- mailboxCountSynced: account.mailboxCountSynced,
165
- muted: overrides.muted,
166
- createdAt: account.createdAt,
167
- updatedAt: account.updatedAt,
168
- folderAppointments,
169
- });
@@ -1,155 +0,0 @@
1
- /**
2
- * The browser Microsoft sends back, and where it ends up.
3
- *
4
- * The callback answers a redirect, so the whole response is its Location
5
- * header: an answer that arrives without it is a blank page with the account
6
- * either connected or not and no way to tell. Driven through the real OpenAPI
7
- * document and the self-host request path, so what is asserted is what a
8
- * self-hosted deployment writes onto the wire — the header included, which a
9
- * handler returning a bare `{statusCode, headers}` shape lost on the way out.
10
- */
11
-
12
- import assert from "node:assert/strict";
13
- import { randomUUID } from "node:crypto";
14
- import { createServer, type Server } from "node:http";
15
- import type { AddressInfo } from "node:net";
16
- import { after, before, describe, it } from "node:test";
17
- import { AccountService } from "@remit/domain-enums";
18
- import type { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
19
- import {
20
- _resetForTest,
21
- type RemitClient,
22
- setClient,
23
- } from "../service/data-client.js";
24
- import { signState } from "./account-oauth.js";
25
- import { createCalendarSqliteClient } from "./calendar-sqlite-fixture.js";
26
-
27
- const CLIENT_SECRET = "callback-test-client-secret";
28
- const WEB_ORIGIN = "https://mail.example.com";
29
- const CALLBACK_PATH = "/accounts/oauth/microsoft/callback";
30
-
31
- let handler: (
32
- event: APIGatewayProxyEvent,
33
- context: unknown,
34
- ) => Promise<APIGatewayProxyResult>;
35
- let client: RemitClient;
36
- let cleanup: () => void;
37
- let tokenEndpoint: Server;
38
-
39
- const jwt = (claims: Record<string, unknown>): string =>
40
- [
41
- Buffer.from(JSON.stringify({ alg: "RS256" })).toString("base64url"),
42
- Buffer.from(JSON.stringify(claims), "utf8").toString("base64url"),
43
- "signature-not-checked-here",
44
- ].join(".");
45
-
46
- /** Microsoft's token endpoint, close enough for the one call the callback makes. */
47
- const startTokenEndpoint = async (): Promise<string> => {
48
- tokenEndpoint = createServer((_request, response) => {
49
- response.writeHead(200, { "Content-Type": "application/json" });
50
- response.end(
51
- JSON.stringify({
52
- access_token: "access-token",
53
- refresh_token: "refresh-token",
54
- id_token: jwt({ preferred_username: "matthijs@example.com" }),
55
- scope:
56
- "https://outlook.office.com/IMAP.AccessAsUser.All https://outlook.office.com/SMTP.Send",
57
- expires_in: 3600,
58
- }),
59
- );
60
- });
61
- await new Promise<void>((resolve) => tokenEndpoint.listen(0, resolve));
62
- const { port } = tokenEndpoint.address() as AddressInfo;
63
- return `http://127.0.0.1:${port}/token`;
64
- };
65
-
66
- const callback = (
67
- query: Record<string, string>,
68
- ): Promise<APIGatewayProxyResult> =>
69
- handler(
70
- {
71
- httpMethod: "GET",
72
- path: CALLBACK_PATH,
73
- headers: {},
74
- queryStringParameters: query,
75
- body: null,
76
- requestContext: {},
77
- } as unknown as APIGatewayProxyEvent,
78
- { awsRequestId: `req-${randomUUID()}`, functionName: "test" },
79
- );
80
-
81
- const headerOf = (
82
- response: APIGatewayProxyResult,
83
- name: string,
84
- ): string | undefined => {
85
- for (const [key, value] of Object.entries(response.headers ?? {})) {
86
- if (key.toLowerCase() === name) return String(value);
87
- }
88
- return undefined;
89
- };
90
-
91
- before(async () => {
92
- _resetForTest();
93
- process.env.DATA_BACKEND = "sqlite";
94
- process.env.CORS_ALLOWED_ORIGINS = WEB_ORIGIN;
95
- process.env.MSOAUTH_REDIRECT_URI = `${WEB_ORIGIN}${CALLBACK_PATH}`;
96
- process.env.MSOAUTH_CLIENT_ID = "callback-test-client-id";
97
- process.env.MSOAUTH_CLIENT_SECRET = CLIENT_SECRET;
98
- process.env.MSOAUTH_TOKEN_ENDPOINT = await startTokenEndpoint();
99
- // The self-host key that encrypts the stored refresh token.
100
- process.env.FAKE_KMS_DATAKEY = "0".repeat(64);
101
- // Static credentials so the best-effort sync enqueue fails against the local
102
- // queue instead of walking the instance-metadata chain for a minute.
103
- process.env.AWS_REGION = "eu-west-1";
104
- process.env.AWS_ACCESS_KEY_ID = "test";
105
- process.env.AWS_SECRET_ACCESS_KEY = "test";
106
- ({ client, cleanup } = await createCalendarSqliteClient());
107
- setClient(client);
108
- ({ handler } = (await import("../index.js")) as unknown as {
109
- handler: typeof handler;
110
- });
111
- });
112
-
113
- after(async () => {
114
- _resetForTest();
115
- cleanup();
116
- await new Promise<void>((resolve) => tokenEndpoint.close(() => resolve()));
117
- });
118
-
119
- describe("the Microsoft OAuth callback", () => {
120
- it("sends the consenting browser on to the connected account", async () => {
121
- const accountConfigId = randomUUID();
122
- const state = await signState(
123
- {
124
- accountConfigId,
125
- nonce: "nonce",
126
- timestamp: Date.now(),
127
- services: [AccountService.Mail],
128
- },
129
- CLIENT_SECRET,
130
- );
131
-
132
- const response = await callback({ code: "auth-code", state });
133
-
134
- assert.equal(response.statusCode, 302, response.body);
135
- const location = headerOf(response, "location");
136
- assert.ok(location, "a redirect without a Location header is a blank page");
137
- const [connected] =
138
- await client.account.listAllByAccountConfig(accountConfigId);
139
- assert.ok(connected, "the callback stored the account it redirects to");
140
- assert.equal(
141
- location,
142
- `${WEB_ORIGIN}/settings/accounts?connected=${encodeURIComponent(connected.accountId)}`,
143
- );
144
- });
145
-
146
- it("sends a refused consent back with the reason Microsoft gave", async () => {
147
- const response = await callback({ error: "access_denied" });
148
-
149
- assert.equal(response.statusCode, 302, response.body);
150
- assert.equal(
151
- headerOf(response, "location"),
152
- `${WEB_ORIGIN}/settings/accounts?oauthError=access_denied`,
153
- );
154
- });
155
- });