@remit/backend 0.0.142 → 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 -521
  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,10 +1,5 @@
1
- import {
2
- type SignedPathFailure,
3
- signStoragePath,
4
- verifyStoragePath,
5
- } from "@remit/storage-service/signed-path";
1
+ import { signStoragePath, verifyStoragePath, } from "@remit/storage-service/signed-path";
6
2
  import { usesBetterAuthJwt } from "../data-backend.js";
7
-
8
3
  /**
9
4
  * Signed-URL scheme for `/content/*` on the self-host stack.
10
5
  *
@@ -29,9 +24,7 @@ import { usesBetterAuthJwt } from "../data-backend.js";
29
24
  * write side (an attachment upload URL) under a different derivation label. This
30
25
  * module is the read side's label, TTL and public shape.
31
26
  */
32
-
33
27
  const KEY_DERIVATION_LABEL = "remit-content-url-signing-v1";
34
-
35
28
  /**
36
29
  * Default validity window for a signed content URL. Long enough to cover a
37
30
  * viewing session (react-query caches describeMessage for 30 min and inline
@@ -39,33 +32,17 @@ const KEY_DERIVATION_LABEL = "remit-content-url-signing-v1";
39
32
  * leaks.
40
33
  */
41
34
  export const CONTENT_URL_TTL_SECONDS = 3600;
42
-
43
- export interface ContentSignature {
44
- exp: number;
45
- sig: string;
46
- }
47
-
48
- /**
49
- * A function that signs a decoded, account-scoped storage path and returns the
50
- * `exp`/`sig` query params to append to its content URL.
51
- */
52
- export type ContentSigner = (relativePath: string) => ContentSignature;
53
-
54
- export const createContentSigner = (
55
- masterSecret: string,
56
- ttlSeconds: number = CONTENT_URL_TTL_SECONDS,
57
- ): ContentSigner => {
58
- return (relativePath) => {
59
- const exp = Math.floor(Date.now() / 1000) + ttlSeconds;
60
- return {
61
- exp,
62
- sig: signStoragePath(masterSecret, KEY_DERIVATION_LABEL, relativePath, [
63
- exp,
64
- ]),
65
- };
66
- };
35
+ export const createContentSigner = (masterSecret, ttlSeconds = CONTENT_URL_TTL_SECONDS) => {
36
+ return (relativePath) => {
37
+ const exp = Math.floor(Date.now() / 1000) + ttlSeconds;
38
+ return {
39
+ exp,
40
+ sig: signStoragePath(masterSecret, KEY_DERIVATION_LABEL, relativePath, [
41
+ exp,
42
+ ]),
43
+ };
44
+ };
67
45
  };
68
-
69
46
  /**
70
47
  * Build the content-URL signer for the current environment, or `undefined` when
71
48
  * signing does not apply. Signing is enforced on the self-host SQL backend,
@@ -75,48 +52,26 @@ export const createContentSigner = (
75
52
  * master secret is missing, so a misconfigured deploy fails loud rather than
76
53
  * shipping unsigned (unauthenticated) content URLs.
77
54
  */
78
- export const getContentSigner = (): ContentSigner | undefined => {
79
- if (!usesBetterAuthJwt()) return undefined;
80
- const secret = process.env.BETTER_AUTH_SECRET;
81
- if (!secret || secret.length === 0) {
82
- throw new Error(
83
- "the self-host SQL backend requires BETTER_AUTH_SECRET to sign content URLs",
84
- );
85
- }
86
- return createContentSigner(secret);
55
+ export const getContentSigner = () => {
56
+ if (!usesBetterAuthJwt())
57
+ return undefined;
58
+ const secret = process.env.BETTER_AUTH_SECRET;
59
+ if (!secret || secret.length === 0) {
60
+ throw new Error("the self-host SQL backend requires BETTER_AUTH_SECRET to sign content URLs");
61
+ }
62
+ return createContentSigner(secret);
87
63
  };
88
-
89
- export type ContentSignatureFailure = SignedPathFailure;
90
-
91
- export type ContentSignatureResult =
92
- | { valid: true }
93
- | { valid: false; reason: ContentSignatureFailure };
94
-
95
64
  /**
96
65
  * Verify a signed content request. Recomputes the HMAC over the requested path
97
66
  * and the supplied expiry and constant-time compares it against the presented
98
67
  * signature. Pure so the decision can be unit-tested without a live server.
99
68
  */
100
- export const verifyContentSignature = (
101
- relativePath: string,
102
- expRaw: string | undefined,
103
- sig: string | undefined,
104
- masterSecret: string,
105
- nowSeconds: number,
106
- ): ContentSignatureResult => {
107
- if (!expRaw || !sig) return { valid: false, reason: "missing" };
108
-
109
- const exp = Number(expRaw);
110
- if (!Number.isInteger(exp) || exp <= 0) {
111
- return { valid: false, reason: "malformed" };
112
- }
113
-
114
- return verifyStoragePath(
115
- masterSecret,
116
- KEY_DERIVATION_LABEL,
117
- relativePath,
118
- [exp],
119
- sig,
120
- nowSeconds,
121
- );
69
+ export const verifyContentSignature = (relativePath, expRaw, sig, masterSecret, nowSeconds) => {
70
+ if (!expRaw || !sig)
71
+ return { valid: false, reason: "missing" };
72
+ const exp = Number(expRaw);
73
+ if (!Number.isInteger(exp) || exp <= 0) {
74
+ return { valid: false, reason: "malformed" };
75
+ }
76
+ return verifyStoragePath(masterSecret, KEY_DERIVATION_LABEL, relativePath, [exp], sig, nowSeconds);
122
77
  };
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Build the public CloudFront URL that fetches a single body part for a
3
+ * message. The path layout is what the Lambda@Edge JWT verifier expects
4
+ * (PR 1 of #224): `/content/accounts/{accountConfigId}/{accountId}/messages/
5
+ * {messageId}/parts/{partPath}`.
6
+ *
7
+ * The function is intentionally pure — domain comes from configuration so
8
+ * tests can pin the output without env vars. `partPath` is passed through
9
+ * `encodeURIComponent` because IMAP section paths are dot-separated digits
10
+ * (e.g. `1`, `1.2`, `2.1.3`) but a defensive encode keeps the builder safe
11
+ * if the path ever carries unexpected characters.
12
+ */
13
+ import type { ContentSigner } from "./contentSignature.js";
14
+ export interface BuildContentUrlInput {
15
+ domain: string;
16
+ accountConfigId: string;
17
+ accountId: string;
18
+ messageId: string;
19
+ partPath: string;
20
+ /**
21
+ * When present (self-host stack), append an `exp`/`sig` signature scoped to
22
+ * this account's storage path. Absent on AWS, where Lambda@Edge guards the
23
+ * URL and the path stays unsigned. See `contentSignature.ts`.
24
+ */
25
+ sign?: ContentSigner;
26
+ }
27
+ export interface BuildStorageContentUrlInput {
28
+ domain: string;
29
+ storageKey: string;
30
+ sign?: ContentSigner;
31
+ }
32
+ export declare const buildStorageContentUrl: (input: BuildStorageContentUrlInput) => string;
33
+ export declare const buildContentUrl: (input: BuildContentUrlInput) => string;
34
+ /**
35
+ * Read the CloudFront distribution domain from the environment. The CDK
36
+ * wires `CONTENT_DELIVERY_DOMAIN` onto the API Lambda from the
37
+ * ContentDelivery stack's published SSM parameter (`/{stage}/Remit/frontendUrl`).
38
+ *
39
+ * Throws when the env var is missing or empty. `BodyPartResponse.contentUrl`
40
+ * is required + URL-formatted in the API contract, so silently emitting a
41
+ * placeholder string would ship a contract lie to clients. Failing loud here
42
+ * surfaces the missing wire-up as a 500 the deploy team can act on (#299).
43
+ * Production synth hard-codes a syntactically-valid placeholder URL via
44
+ * `infra/bin/infra.ts` so this only fires when the env is actually unset.
45
+ */
46
+ export declare const getContentDeliveryDomain: () => string;
@@ -0,0 +1,46 @@
1
+ export const buildStorageContentUrl = (input) => {
2
+ const { domain, storageKey, sign } = input;
3
+ const normalizedDomain = domain.replace(/\/+$/, "");
4
+ const base = normalizedDomain.startsWith("http")
5
+ ? normalizedDomain
6
+ : `https://${normalizedDomain}`;
7
+ // The signed message is the decoded, account-scoped storage path — the same
8
+ // value the `/content` route recomputes from `req.path`. Keep it in lockstep
9
+ // with the verifier's `req.path.replace(/^\/content\//, "")`.
10
+ const safeKey = storageKey
11
+ .split("/")
12
+ .map((segment) => encodeURIComponent(segment))
13
+ .join("/");
14
+ const url = `${base}/content/${safeKey}`;
15
+ if (!sign)
16
+ return url;
17
+ const { exp, sig } = sign(storageKey);
18
+ return `${url}?exp=${exp}&sig=${encodeURIComponent(sig)}`;
19
+ };
20
+ export const buildContentUrl = (input) => {
21
+ const { domain, accountConfigId, accountId, messageId, partPath, sign } = input;
22
+ return buildStorageContentUrl({
23
+ domain,
24
+ storageKey: `accounts/${accountConfigId}/${accountId}/messages/${messageId}/parts/${partPath}`,
25
+ sign,
26
+ });
27
+ };
28
+ /**
29
+ * Read the CloudFront distribution domain from the environment. The CDK
30
+ * wires `CONTENT_DELIVERY_DOMAIN` onto the API Lambda from the
31
+ * ContentDelivery stack's published SSM parameter (`/{stage}/Remit/frontendUrl`).
32
+ *
33
+ * Throws when the env var is missing or empty. `BodyPartResponse.contentUrl`
34
+ * is required + URL-formatted in the API contract, so silently emitting a
35
+ * placeholder string would ship a contract lie to clients. Failing loud here
36
+ * surfaces the missing wire-up as a 500 the deploy team can act on (#299).
37
+ * Production synth hard-codes a syntactically-valid placeholder URL via
38
+ * `infra/bin/infra.ts` so this only fires when the env is actually unset.
39
+ */
40
+ export const getContentDeliveryDomain = () => {
41
+ const value = process.env.CONTENT_DELIVERY_DOMAIN;
42
+ if (!value || value.length === 0) {
43
+ throw new Error("CONTENT_DELIVERY_DOMAIN is not set; BodyPartResponse.contentUrl cannot be built. Wire the CloudFront distribution domain via the API Lambda env (see infra/bin/infra.ts).");
44
+ }
45
+ return value;
46
+ };
@@ -1,10 +1,8 @@
1
1
  import type { AddressFlags } from "@remit/api-openapi-types";
2
-
3
2
  /**
4
3
  * Derive whether the From address is muted from an Address's flags map.
5
4
  *
6
5
  * Pure function, no I/O. Frontend never derives this — single source of
7
6
  * truth for filtering the daily brief.
8
7
  */
9
- export const deriveMuted = (flags: AddressFlags | undefined): boolean =>
10
- flags?.muted?.value === true;
8
+ export declare const deriveMuted: (flags: AddressFlags | undefined) => boolean;
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Derive whether the From address is muted from an Address's flags map.
3
+ *
4
+ * Pure function, no I/O. Frontend never derives this — single source of
5
+ * truth for filtering the daily brief.
6
+ */
7
+ export const deriveMuted = (flags) => flags?.muted?.value === true;
@@ -0,0 +1,118 @@
1
+ import type { AddressItem, LabelItem, MessageItem, MessageLabelItem, ThreadMessageItem } from "@remit/data-ports";
2
+ /**
3
+ * Subset of the ElectroDB client surface used for batch enrichment. Declared
4
+ * structurally so unit tests can pass an in-memory fake without standing up
5
+ * DynamoDB.
6
+ */
7
+ export interface EnrichClient {
8
+ message: {
9
+ get(messageIds: string[]): Promise<MessageItem[]>;
10
+ };
11
+ address: {
12
+ getAddress(accountConfigId: string, addressIds: string[]): Promise<AddressItem[]>;
13
+ };
14
+ messageLabel: {
15
+ listByMessageIds(messageIds: string[]): Promise<MessageLabelItem[]>;
16
+ };
17
+ label: {
18
+ listByAccountConfig(accountConfigId: string): Promise<LabelItem[]>;
19
+ };
20
+ }
21
+ /**
22
+ * Plan the unique batch-fetch keys for a page of ThreadMessage rows.
23
+ *
24
+ * Splitting this out keeps the dedup logic testable without DynamoDB and
25
+ * documents the contract: a page of N rows produces at most one BatchGet
26
+ * for messages and one for addresses, no matter how many rows share the
27
+ * same messageId / sender.
28
+ *
29
+ * `addressId` is derived deterministically from `(accountConfigId, fromEmail)`
30
+ * via `deriveAddressId`, mirroring the write path in
31
+ * `body-sync.ts`. Rows without a `fromEmail` (rare; sentinel/system rows)
32
+ * contribute no addressId and fall back to `senderTrust: "unknown"`.
33
+ */
34
+ export interface BatchPlan {
35
+ messageIds: string[];
36
+ addressIds: string[];
37
+ addressIdByRow: Map<string, string>;
38
+ }
39
+ export declare const planBatchFetch: (rows: ThreadMessageItem[]) => BatchPlan;
40
+ /**
41
+ * Enrich a page of ThreadMessage rows with `senderTrust` and `muted` (both
42
+ * derived from the From Address's flags map), `authenticity`, `autoMoved` and
43
+ * `spamReport`, and the `status`/`syncStatus` pair an IMAP mutation leaves
44
+ * behind together with the mutation an abandoned one names (all projected
45
+ * straight from the Message row — no ThreadMessage
46
+ * column of their own, see `deriveAutoMoved`). `toResponse` seeds that pair
47
+ * with the ordinary inbound values, which the projection then overwrites; a
48
+ * ThreadMessage row whose Message row is missing from the batch is broken in a
49
+ * way this read path cannot report, and claiming a mutation it has no evidence
50
+ * of would be worse.
51
+ *
52
+ * `category` is not enriched: it is denormalized onto the ThreadMessage row
53
+ * (shared with `Message.category`'s write-once value, see body-sync.ts) and
54
+ * carried straight through by `toResponse`, so the value a client renders is
55
+ * the value the category filter matched.
56
+ *
57
+ * Two BatchGetItem calls per page, regardless of page size — see
58
+ * `planBatchFetch` for the dedup contract.
59
+ *
60
+ * Missing rows fall back gracefully: `senderTrust` defaults to `"unknown"`,
61
+ * `muted` defaults to `false`, and `authenticity` / `autoMoved` are omitted
62
+ * whenever the Message row is absent or the move isn't a real, in-effect
63
+ * auto-move.
64
+ *
65
+ * Not annotated `Promise<ThreadMessageResponse[]>`: `labels` is a new field on
66
+ * it in this same PR, and that package publishes separately from this repo —
67
+ * an explicit annotation here would contextually type the literal below
68
+ * against the currently-*published* shape (which lacks `labels`) and fail
69
+ * `check-consumer-typecheck`/`release:dry-run`. Callers assign the (wider,
70
+ * inferred) result into an already-typed `ThreadMessageResponse[]` property,
71
+ * which is a plain assignability check, not an excess-property one.
72
+ */
73
+ export declare const enrichThreadRows: (rows: ThreadMessageItem[], client: EnrichClient, accountConfigId: string) => Promise<{
74
+ senderTrust: import("./senderTrust.js").SenderTrustValue;
75
+ muted: boolean;
76
+ spamReport?: {
77
+ reportedAt: number;
78
+ } | undefined;
79
+ labels?: {
80
+ labelId: string;
81
+ name: string;
82
+ color: LabelItem["color"];
83
+ }[] | undefined;
84
+ autoMoved?: import("@remit/api-openapi-types").Components.Schemas.AutoMovedInfo;
85
+ authenticity?: {
86
+ fromDomain: string;
87
+ dkimMismatch: boolean;
88
+ dkimDomain?: string | undefined;
89
+ displayNameCorrespondence?: "Corresponds" | "Lookalike" | "ForeignAddress" | "Unrelated" | "NoClaim" | undefined;
90
+ offDomainLinkDomains?: string[] | undefined;
91
+ signerDomain?: string | undefined;
92
+ envelopeDomain?: string | undefined;
93
+ signerMessageCount?: number | undefined;
94
+ signerFirstSeenAt?: number | undefined;
95
+ } | undefined;
96
+ status: import("@remit/api-openapi-types").Components.Schemas.MessageStatus;
97
+ syncStatus: import("@remit/api-openapi-types").Components.Schemas.MessageSyncStatus;
98
+ abandonedMutation: import("@remit/api-openapi-types").Components.Schemas.MessageMutation;
99
+ threadMessageId: import("@remit/api-openapi-types").Components.Schemas.UUID;
100
+ threadId: import("@remit/api-openapi-types").Components.Schemas.UUID;
101
+ messageId: import("@remit/api-openapi-types").Components.Schemas.UUID;
102
+ accountConfigId: import("@remit/api-openapi-types").Components.Schemas.UUID;
103
+ mailboxId: import("@remit/api-openapi-types").Components.Schemas.UUID;
104
+ fromEmail?: string;
105
+ fromName?: string;
106
+ subject?: string;
107
+ sentDate: number;
108
+ isRead: boolean;
109
+ hasAttachment: boolean;
110
+ star: import("@remit/api-openapi-types").Components.Schemas.StarColor;
111
+ hasStars: boolean;
112
+ isDeleted: boolean;
113
+ snippet?: import("@remit/api-openapi-types").Components.Schemas.String256;
114
+ createdAt: number;
115
+ updatedAt: number;
116
+ category: import("@remit/api-openapi-types").Components.Schemas.MessageCategory;
117
+ accountId?: import("@remit/api-openapi-types").Components.Schemas.UUID;
118
+ }[]>;
@@ -0,0 +1,151 @@
1
+ import { deriveAddressId } from "@remit/data-ports/id";
2
+ import { MessageMutation, MessageStatus, MessageSyncStatus, SenderTrust, StarColor, } from "@remit/domain-enums";
3
+ import { deriveAutoMoved } from "./autoMoved.js";
4
+ import { deriveMuted } from "./deriveMuted.js";
5
+ import { deriveSenderTrust } from "./senderTrust.js";
6
+ const toResponse = (item) => ({
7
+ threadMessageId: item.threadMessageId,
8
+ threadId: item.threadId,
9
+ messageId: item.messageId,
10
+ accountConfigId: item.accountConfigId,
11
+ mailboxId: item.mailboxId,
12
+ fromEmail: item.fromEmail,
13
+ fromName: item.fromName,
14
+ subject: item.subject,
15
+ sentDate: item.sentDate,
16
+ isRead: item.isRead,
17
+ hasAttachment: item.hasAttachment,
18
+ star: item.star ?? StarColor.None,
19
+ hasStars: item.hasStars,
20
+ isDeleted: item.isDeleted,
21
+ snippet: item.snippet,
22
+ category: item.category,
23
+ createdAt: item.createdAt,
24
+ updatedAt: item.updatedAt,
25
+ senderTrust: SenderTrust.Unknown,
26
+ muted: false,
27
+ status: MessageStatus.active,
28
+ syncStatus: MessageSyncStatus.pending,
29
+ abandonedMutation: MessageMutation.none,
30
+ });
31
+ export const planBatchFetch = (rows) => {
32
+ const messageIds = new Set();
33
+ const addressIds = new Set();
34
+ const addressIdByRow = new Map();
35
+ for (const row of rows) {
36
+ messageIds.add(row.messageId);
37
+ if (!row.fromEmail)
38
+ continue;
39
+ const addressId = deriveAddressId(row.accountConfigId, row.fromEmail);
40
+ addressIds.add(addressId);
41
+ addressIdByRow.set(row.threadMessageId, addressId);
42
+ }
43
+ return {
44
+ messageIds: [...messageIds],
45
+ addressIds: [...addressIds],
46
+ addressIdByRow,
47
+ };
48
+ };
49
+ /**
50
+ * Enrich a page of ThreadMessage rows with `senderTrust` and `muted` (both
51
+ * derived from the From Address's flags map), `authenticity`, `autoMoved` and
52
+ * `spamReport`, and the `status`/`syncStatus` pair an IMAP mutation leaves
53
+ * behind together with the mutation an abandoned one names (all projected
54
+ * straight from the Message row — no ThreadMessage
55
+ * column of their own, see `deriveAutoMoved`). `toResponse` seeds that pair
56
+ * with the ordinary inbound values, which the projection then overwrites; a
57
+ * ThreadMessage row whose Message row is missing from the batch is broken in a
58
+ * way this read path cannot report, and claiming a mutation it has no evidence
59
+ * of would be worse.
60
+ *
61
+ * `category` is not enriched: it is denormalized onto the ThreadMessage row
62
+ * (shared with `Message.category`'s write-once value, see body-sync.ts) and
63
+ * carried straight through by `toResponse`, so the value a client renders is
64
+ * the value the category filter matched.
65
+ *
66
+ * Two BatchGetItem calls per page, regardless of page size — see
67
+ * `planBatchFetch` for the dedup contract.
68
+ *
69
+ * Missing rows fall back gracefully: `senderTrust` defaults to `"unknown"`,
70
+ * `muted` defaults to `false`, and `authenticity` / `autoMoved` are omitted
71
+ * whenever the Message row is absent or the move isn't a real, in-effect
72
+ * auto-move.
73
+ *
74
+ * Not annotated `Promise<ThreadMessageResponse[]>`: `labels` is a new field on
75
+ * it in this same PR, and that package publishes separately from this repo —
76
+ * an explicit annotation here would contextually type the literal below
77
+ * against the currently-*published* shape (which lacks `labels`) and fail
78
+ * `check-consumer-typecheck`/`release:dry-run`. Callers assign the (wider,
79
+ * inferred) result into an already-typed `ThreadMessageResponse[]` property,
80
+ * which is a plain assignability check, not an excess-property one.
81
+ */
82
+ export const enrichThreadRows = async (rows, client, accountConfigId) => {
83
+ if (rows.length === 0)
84
+ return [];
85
+ const plan = planBatchFetch(rows);
86
+ const [messages, addresses, messageLabels, labels] = await Promise.all([
87
+ plan.messageIds.length ? client.message.get(plan.messageIds) : [],
88
+ plan.addressIds.length
89
+ ? client.address.getAddress(accountConfigId, plan.addressIds)
90
+ : [],
91
+ client.messageLabel.listByMessageIds(plan.messageIds),
92
+ client.label.listByAccountConfig(accountConfigId),
93
+ ]);
94
+ const labelById = new Map(labels.map((label) => [label.labelId, label]));
95
+ const labelsByMessageId = new Map();
96
+ for (const messageLabel of messageLabels) {
97
+ const label = labelById.get(messageLabel.labelId);
98
+ if (!label)
99
+ continue;
100
+ const entry = {
101
+ labelId: label.labelId,
102
+ name: label.name,
103
+ color: label.color,
104
+ };
105
+ const existing = labelsByMessageId.get(messageLabel.messageId);
106
+ if (existing) {
107
+ existing.push(entry);
108
+ }
109
+ else {
110
+ labelsByMessageId.set(messageLabel.messageId, [entry]);
111
+ }
112
+ }
113
+ const authenticityByMessageId = new Map(messages.map((m) => [m.messageId, m.authenticity]));
114
+ const autoMovedByMessageId = new Map(messages.map((m) => [m.messageId, deriveAutoMoved(m)]));
115
+ const spamReportByMessageId = new Map(messages.map((m) => [m.messageId, m.spamReport]));
116
+ const settlementByMessageId = new Map(messages.map((m) => [
117
+ m.messageId,
118
+ {
119
+ status: m.status,
120
+ syncStatus: m.syncStatus,
121
+ abandonedMutation: m.abandonedMutation,
122
+ },
123
+ ]));
124
+ const trustByAddressId = new Map(addresses.map((a) => [a.addressId, deriveSenderTrust(a.flags)]));
125
+ const mutedByAddressId = new Map(addresses.map((a) => [a.addressId, deriveMuted(a.flags)]));
126
+ return rows.map((row) => {
127
+ const base = toResponse(row);
128
+ const authenticity = authenticityByMessageId.get(row.messageId);
129
+ const autoMoved = autoMovedByMessageId.get(row.messageId);
130
+ const spamReport = spamReportByMessageId.get(row.messageId);
131
+ const addressId = plan.addressIdByRow.get(row.threadMessageId);
132
+ const senderTrust = addressId
133
+ ? (trustByAddressId.get(addressId) ?? SenderTrust.Unknown)
134
+ : SenderTrust.Unknown;
135
+ const muted = addressId
136
+ ? (mutedByAddressId.get(addressId) ?? false)
137
+ : false;
138
+ const labels = labelsByMessageId.get(row.messageId);
139
+ const settlement = settlementByMessageId.get(row.messageId);
140
+ return {
141
+ ...base,
142
+ ...(settlement ?? {}),
143
+ ...(authenticity !== undefined ? { authenticity } : {}),
144
+ ...(autoMoved !== undefined ? { autoMoved } : {}),
145
+ ...(labels !== undefined ? { labels } : {}),
146
+ ...(spamReport !== undefined ? { spamReport } : {}),
147
+ senderTrust,
148
+ muted,
149
+ };
150
+ });
151
+ };
@@ -0,0 +1,23 @@
1
+ import type { SenderTrust, ThreadMessageResponse } from "@remit/api-openapi-types";
2
+ /**
3
+ * Off-row search criteria — fields that live on the underlying Message/Address,
4
+ * not on the ThreadMessage row. They are resolved by enriching the windowed
5
+ * rows (see enrichThreadRows) and filtering in app code, because no index or
6
+ * FilterExpression can serve them.
7
+ *
8
+ * `senderTrust` derives from AddressItem.flags and `dkimMismatch` from
9
+ * MessageItem.authenticity. `category` is not one of these: it is denormalized
10
+ * onto the ThreadMessage row and filtered in SQL, inside the window.
11
+ */
12
+ export interface OffRowCriteria {
13
+ senderTrust?: SenderTrust[];
14
+ dkimMismatch?: boolean;
15
+ }
16
+ export declare const hasOffRowCriteria: (criteria: OffRowCriteria) => boolean;
17
+ /**
18
+ * Filter enriched rows by the off-row criteria. Each active criterion is an
19
+ * any-of set (AND across criteria, OR within a set). A row with no
20
+ * `authenticity` signal never matches a `dkimMismatch` filter (absence means no
21
+ * signal, not a verdict).
22
+ */
23
+ export declare const filterByOffRowCriteria: (rows: ThreadMessageResponse[], criteria: OffRowCriteria) => ThreadMessageResponse[];
@@ -0,0 +1,24 @@
1
+ export const hasOffRowCriteria = (criteria) => Boolean(criteria.senderTrust?.length) || criteria.dkimMismatch !== undefined;
2
+ /**
3
+ * Filter enriched rows by the off-row criteria. Each active criterion is an
4
+ * any-of set (AND across criteria, OR within a set). A row with no
5
+ * `authenticity` signal never matches a `dkimMismatch` filter (absence means no
6
+ * signal, not a verdict).
7
+ */
8
+ export const filterByOffRowCriteria = (rows, criteria) => {
9
+ if (!hasOffRowCriteria(criteria))
10
+ return rows;
11
+ const trustSet = criteria.senderTrust?.length
12
+ ? new Set(criteria.senderTrust)
13
+ : undefined;
14
+ const { dkimMismatch } = criteria;
15
+ return rows.filter((row) => {
16
+ if (trustSet && !trustSet.has(row.senderTrust))
17
+ return false;
18
+ if (dkimMismatch !== undefined &&
19
+ row.authenticity?.dkimMismatch !== dkimMismatch) {
20
+ return false;
21
+ }
22
+ return true;
23
+ });
24
+ };
@@ -1,15 +1,13 @@
1
1
  import type { MailboxItem } from "@remit/data-ports";
2
-
3
2
  /**
4
3
  * The subset of a pending placement-move marker (issue #1271) this
5
4
  * derivation needs — decoupled from the concrete marker type so it stays a
6
5
  * pure function over plain data.
7
6
  */
8
7
  export interface PendingPlacementMove {
9
- sourceMailboxId: string;
10
- destinationMailboxId: string;
8
+ sourceMailboxId: string;
9
+ destinationMailboxId: string;
11
10
  }
12
-
13
11
  /**
14
12
  * The subset of a pending flag-push marker (issue #1273) this derivation
15
13
  * needs. Only `\Seen` markers are meaningful here — `mailboxId` is the
@@ -17,10 +15,9 @@ export interface PendingPlacementMove {
17
15
  * `applyPendingMoveCountPrediction` already tolerates for placement moves.
18
16
  */
19
17
  export interface PendingUnseenFlagPush {
20
- mailboxId: string;
21
- operation: "add" | "remove";
18
+ mailboxId: string;
19
+ operation: "add" | "remove";
22
20
  }
23
-
24
21
  /**
25
22
  * Adjusts `messageCount` and `unseenCount` on a set of mailboxes to reflect
26
23
  * every pending placement move (issue #1271) and pending `\Seen` flag push
@@ -42,49 +39,4 @@ export interface PendingUnseenFlagPush {
42
39
  * Pure: takes the mailboxes and the pending markers as plain input, returns a
43
40
  * new array. Never mutates its arguments.
44
41
  */
45
- export const applyPendingMoveCountPrediction = (
46
- mailboxes: readonly MailboxItem[],
47
- pendingMoves: readonly PendingPlacementMove[],
48
- pendingUnseenFlagPushes: readonly PendingUnseenFlagPush[] = [],
49
- ): MailboxItem[] => {
50
- if (pendingMoves.length === 0 && pendingUnseenFlagPushes.length === 0) {
51
- return [...mailboxes];
52
- }
53
-
54
- const messageCountDelta = new Map<string, number>();
55
- for (const move of pendingMoves) {
56
- if (move.sourceMailboxId === move.destinationMailboxId) continue;
57
- messageCountDelta.set(
58
- move.sourceMailboxId,
59
- (messageCountDelta.get(move.sourceMailboxId) ?? 0) - 1,
60
- );
61
- messageCountDelta.set(
62
- move.destinationMailboxId,
63
- (messageCountDelta.get(move.destinationMailboxId) ?? 0) + 1,
64
- );
65
- }
66
-
67
- const unseenCountDelta = new Map<string, number>();
68
- for (const push of pendingUnseenFlagPushes) {
69
- const adjustment = push.operation === "add" ? -1 : 1;
70
- unseenCountDelta.set(
71
- push.mailboxId,
72
- (unseenCountDelta.get(push.mailboxId) ?? 0) + adjustment,
73
- );
74
- }
75
-
76
- return mailboxes.map((mailbox) => {
77
- const messageAdjustment = messageCountDelta.get(mailbox.mailboxId);
78
- const unseenAdjustment = unseenCountDelta.get(mailbox.mailboxId);
79
- if (!messageAdjustment && !unseenAdjustment) return mailbox;
80
- return {
81
- ...mailbox,
82
- messageCount: messageAdjustment
83
- ? Math.max(0, mailbox.messageCount + messageAdjustment)
84
- : mailbox.messageCount,
85
- unseenCount: unseenAdjustment
86
- ? Math.max(0, mailbox.unseenCount + unseenAdjustment)
87
- : mailbox.unseenCount,
88
- };
89
- });
90
- };
42
+ export declare const applyPendingMoveCountPrediction: (mailboxes: readonly MailboxItem[], pendingMoves: readonly PendingPlacementMove[], pendingUnseenFlagPushes?: readonly PendingUnseenFlagPush[]) => MailboxItem[];