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