@remit/backend 0.0.143 → 0.0.144
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/dev-server/content-handler.d.ts +38 -0
- package/dist/dev-server/content-handler.js +46 -0
- package/dist/src/api.d.ts +7 -0
- package/dist/src/api.js +144 -0
- package/dist/src/auth.d.ts +30 -0
- package/dist/src/auth.js +73 -0
- package/dist/src/config/msoauth.d.ts +30 -0
- package/dist/src/config/msoauth.js +30 -0
- package/{src/data-backend.ts → dist/src/data-backend.d.ts} +2 -4
- package/dist/src/data-backend.js +12 -0
- package/{src/derive/autoMoved.ts → dist/src/derive/autoMoved.d.ts} +1 -29
- package/dist/src/derive/autoMoved.js +49 -0
- package/dist/src/derive/contentSignature.d.ts +41 -0
- package/{src/derive/contentSignature.ts → dist/src/derive/contentSignature.js} +27 -72
- package/dist/src/derive/contentUrl.d.ts +46 -0
- package/dist/src/derive/contentUrl.js +46 -0
- package/{src/derive/deriveMuted.ts → dist/src/derive/deriveMuted.d.ts} +1 -3
- package/dist/src/derive/deriveMuted.js +7 -0
- package/dist/src/derive/enrichThreadRows.d.ts +118 -0
- package/dist/src/derive/enrichThreadRows.js +151 -0
- package/dist/src/derive/filterThreadCriteria.d.ts +23 -0
- package/dist/src/derive/filterThreadCriteria.js +24 -0
- package/{src/derive/pendingMoveCounts.ts → dist/src/derive/pendingMoveCounts.d.ts} +5 -53
- package/dist/src/derive/pendingMoveCounts.js +53 -0
- package/{src/derive/senderTrust.ts → dist/src/derive/senderTrust.d.ts} +1 -9
- package/dist/src/derive/senderTrust.js +19 -0
- package/dist/src/error.d.ts +21 -0
- package/dist/src/error.js +85 -0
- package/dist/src/handlers/account-guards.d.ts +36 -0
- package/dist/src/handlers/account-guards.js +107 -0
- package/dist/src/handlers/account-oauth.d.ts +14 -0
- package/dist/src/handlers/account-oauth.js +387 -0
- package/dist/src/handlers/account-overrides.d.ts +53 -0
- package/dist/src/handlers/account-overrides.js +233 -0
- package/dist/src/handlers/account-signature.d.ts +28 -0
- package/dist/src/handlers/account-signature.js +85 -0
- package/dist/src/handlers/account.d.ts +6 -0
- package/dist/src/handlers/account.js +350 -0
- package/dist/src/handlers/address.d.ts +35 -0
- package/dist/src/handlers/address.js +141 -0
- package/dist/src/handlers/calendar-event.d.ts +70 -0
- package/dist/src/handlers/calendar-event.js +425 -0
- package/dist/src/handlers/calendar-feed.d.ts +47 -0
- package/dist/src/handlers/calendar-feed.js +192 -0
- package/dist/src/handlers/calendar-suggestion.d.ts +47 -0
- package/dist/src/handlers/calendar-suggestion.js +212 -0
- package/dist/src/handlers/calendar.d.ts +116 -0
- package/dist/src/handlers/calendar.js +330 -0
- package/dist/src/handlers/config.d.ts +43 -0
- package/dist/src/handlers/config.js +176 -0
- package/dist/src/handlers/ensure-account-config.d.ts +9 -0
- package/dist/src/handlers/ensure-account-config.js +27 -0
- package/dist/src/handlers/filter.d.ts +3 -0
- package/dist/src/handlers/filter.js +103 -0
- package/dist/src/handlers/folder-role-appointments.d.ts +68 -0
- package/dist/src/handlers/folder-role-appointments.js +168 -0
- package/dist/src/handlers/folder-role-labels.d.ts +26 -0
- package/dist/src/handlers/folder-role-labels.js +40 -0
- package/dist/src/handlers/folder-role.d.ts +9 -0
- package/dist/src/handlers/folder-role.js +40 -0
- package/dist/src/handlers/index.d.ts +2 -0
- package/dist/src/handlers/index.js +60 -0
- package/dist/src/handlers/label.d.ts +43 -0
- package/dist/src/handlers/label.js +114 -0
- package/dist/src/handlers/mailbox-bindings.d.ts +41 -0
- package/dist/src/handlers/mailbox-bindings.js +61 -0
- package/dist/src/handlers/mailbox.d.ts +23 -0
- package/dist/src/handlers/mailbox.js +219 -0
- package/dist/src/handlers/me.d.ts +2 -0
- package/dist/src/handlers/me.js +138 -0
- package/dist/src/handlers/message.d.ts +84 -0
- package/dist/src/handlers/message.js +607 -0
- package/dist/src/handlers/organize.d.ts +10 -0
- package/dist/src/handlers/organize.js +112 -0
- package/dist/src/handlers/outbox-attachment.d.ts +23 -0
- package/dist/src/handlers/outbox-attachment.js +81 -0
- package/dist/src/handlers/outbox.d.ts +4 -0
- package/dist/src/handlers/outbox.js +144 -0
- package/dist/src/handlers/sync-progress.d.ts +46 -0
- package/dist/src/handlers/sync-progress.js +63 -0
- package/dist/src/handlers/sync.d.ts +28 -0
- package/dist/src/handlers/sync.js +82 -0
- package/dist/src/handlers/system-update.d.ts +2 -0
- package/dist/src/handlers/system-update.js +172 -0
- package/dist/src/handlers/thread.d.ts +148 -0
- package/dist/src/handlers/thread.js +233 -0
- package/dist/src/handlers/unified-threads.d.ts +247 -0
- package/dist/src/handlers/unified-threads.js +409 -0
- package/{src/handlers/vip-suggestions.ts → dist/src/handlers/vip-suggestions.d.ts} +1 -13
- package/dist/src/handlers/vip-suggestions.js +16 -0
- package/dist/src/index.d.ts +2 -0
- package/dist/src/index.js +37 -0
- package/{src/json.ts → dist/src/json.d.ts} +1 -4
- package/dist/src/json.js +10 -0
- package/dist/src/jwt-auth.d.ts +18 -0
- package/dist/src/jwt-auth.js +97 -0
- package/dist/src/request-context.d.ts +9 -0
- package/dist/src/request-context.js +22 -0
- package/dist/src/request.d.ts +3 -0
- package/dist/src/request.js +7 -0
- package/dist/src/response.d.ts +27 -0
- package/dist/src/response.js +87 -0
- package/dist/src/service/account-deletion.d.ts +22 -0
- package/dist/src/service/account-deletion.js +39 -0
- package/dist/src/service/compose-sqlite.d.ts +2 -0
- package/dist/src/service/compose-sqlite.js +11 -0
- package/dist/src/service/create-remit-client.d.ts +95 -0
- package/dist/src/service/create-remit-client.js +207 -0
- package/dist/src/service/data-client.d.ts +12 -0
- package/dist/src/service/data-client.js +44 -0
- package/dist/src/service/export-identity.d.ts +3 -0
- package/dist/src/service/export-identity.js +35 -0
- package/dist/src/service/fire-and-forget.d.ts +54 -0
- package/dist/src/service/fire-and-forget.js +38 -0
- package/dist/src/service/organize.d.ts +184 -0
- package/dist/src/service/organize.js +384 -0
- package/dist/src/service/refusal.d.ts +4 -0
- package/dist/src/service/refusal.js +20 -0
- package/dist/src/service/sender-category.d.ts +51 -0
- package/{src/service/sender-category.ts → dist/src/service/sender-category.js} +40 -81
- package/dist/src/service/sqs.d.ts +1 -0
- package/{src/service/sqs.ts → dist/src/service/sqs.js} +0 -1
- package/dist/src/service/trigger-sync.d.ts +51 -0
- package/dist/src/service/trigger-sync.js +39 -0
- package/dist/src/types.d.ts +49 -0
- package/dist/src/types.js +1 -0
- package/package.json +113 -98
- package/.env.test +0 -4
- package/dev-server/content-auth.test.ts +0 -113
- package/dev-server/content-auth.ts +0 -54
- package/dev-server/content-handler.test.ts +0 -105
- package/dev-server/content-handler.ts +0 -79
- package/dev-server/content-path.test.ts +0 -37
- package/dev-server/content-path.ts +0 -27
- package/dev-server/cors.test.ts +0 -48
- package/dev-server/cors.ts +0 -25
- package/dev-server/keep-alive.test.ts +0 -24
- package/dev-server/lambda-helpers.ts +0 -69
- package/dev-server/log-output.test.ts +0 -173
- package/dev-server/oauth-callback-route.test.ts +0 -66
- package/dev-server/relational-health.test.ts +0 -83
- package/dev-server/relational-health.ts +0 -39
- package/dev-server/server.ts +0 -384
- package/dev-server/sync-age.test.ts +0 -91
- package/dev-server/sync-age.ts +0 -55
- package/dev-server/upload-handler.ts +0 -132
- package/dev-server/upload-route.test.ts +0 -196
- package/scripts/backfill-classification.ts +0 -91
- package/scripts/backfill-list-id.ts +0 -83
- package/scripts/config-save.ts +0 -128
- package/src/auth.test.ts +0 -12
- package/src/auth.ts +0 -92
- package/src/config/msoauth.test.ts +0 -48
- package/src/config/msoauth.ts +0 -48
- package/src/data-backend.test.ts +0 -23
- package/src/derive/autoMoved.test.ts +0 -104
- package/src/derive/contentSignature.test.ts +0 -161
- package/src/derive/contentUrl.test.ts +0 -172
- package/src/derive/contentUrl.ts +0 -86
- package/src/derive/deriveMuted.test.ts +0 -34
- package/src/derive/enrichThreadRows.test.ts +0 -360
- package/src/derive/enrichThreadRows.ts +0 -234
- package/src/derive/filterThreadCriteria.test.ts +0 -126
- package/src/derive/filterThreadCriteria.ts +0 -51
- package/src/derive/senderTrust.test.ts +0 -67
- package/src/error.test.ts +0 -201
- package/src/error.ts +0 -123
- package/src/handlers/account-guards.test.ts +0 -67
- package/src/handlers/account-guards.ts +0 -169
- package/src/handlers/account-oauth-callback.test.ts +0 -155
- package/src/handlers/account-oauth-consent.test.ts +0 -336
- package/src/handlers/account-oauth-start.test.ts +0 -191
- package/src/handlers/account-oauth.test.ts +0 -439
- package/src/handlers/account-oauth.ts +0 -635
- package/src/handlers/account-overrides.test.ts +0 -88
- package/src/handlers/account-overrides.ts +0 -323
- package/src/handlers/account-ownership.ts +0 -25
- package/src/handlers/account-signature.ts +0 -117
- package/src/handlers/account-synced-services.test.ts +0 -245
- package/src/handlers/account.ts +0 -552
- package/src/handlers/address.test.ts +0 -381
- package/src/handlers/address.ts +0 -200
- package/src/handlers/calendar-event.test.ts +0 -685
- package/src/handlers/calendar-event.ts +0 -738
- package/src/handlers/calendar-feed-validators.test.ts +0 -228
- package/src/handlers/calendar-feed.test.ts +0 -439
- package/src/handlers/calendar-feed.ts +0 -291
- package/src/handlers/calendar-sqlite-fixture.ts +0 -36
- package/src/handlers/calendar-suggestion.test.ts +0 -1269
- package/src/handlers/calendar-suggestion.ts +0 -425
- package/src/handlers/calendar.test.ts +0 -1080
- package/src/handlers/calendar.ts +0 -517
- package/src/handlers/config.test.ts +0 -245
- package/src/handlers/config.ts +0 -332
- package/src/handlers/ensure-account-config.ts +0 -30
- package/src/handlers/filter.test.ts +0 -644
- package/src/handlers/filter.ts +0 -518
- package/src/handlers/folder-role-appointments.test.ts +0 -438
- package/src/handlers/folder-role-appointments.ts +0 -249
- package/src/handlers/folder-role-labels.ts +0 -63
- package/src/handlers/folder-role.test.ts +0 -209
- package/src/handlers/folder-role.ts +0 -80
- package/src/handlers/index.ts +0 -83
- package/src/handlers/label.test.ts +0 -112
- package/src/handlers/label.ts +0 -210
- package/src/handlers/mailbox-bindings.ts +0 -111
- package/src/handlers/mailbox-rename-refusal.test.ts +0 -247
- package/src/handlers/mailbox-settled-target.test.ts +0 -251
- package/src/handlers/mailbox.test.ts +0 -280
- package/src/handlers/mailbox.ts +0 -581
- package/src/handlers/me.test.ts +0 -81
- package/src/handlers/me.ts +0 -203
- package/src/handlers/message-read-backfill.test.ts +0 -103
- package/src/handlers/message.test.ts +0 -131
- package/src/handlers/message.ts +0 -1131
- package/src/handlers/organize.test.ts +0 -277
- package/src/handlers/organize.ts +0 -197
- package/src/handlers/outbox-attachment.test.ts +0 -765
- package/src/handlers/outbox-attachment.ts +0 -126
- package/src/handlers/outbox-list.test.ts +0 -179
- package/src/handlers/outbox.test.ts +0 -772
- package/src/handlers/outbox.ts +0 -258
- package/src/handlers/search.test.ts +0 -161
- package/src/handlers/search.ts +0 -105
- package/src/handlers/sync-progress.test.ts +0 -205
- package/src/handlers/sync-progress.ts +0 -99
- package/src/handlers/sync.test.ts +0 -168
- package/src/handlers/sync.ts +0 -118
- package/src/handlers/system-update.test.ts +0 -497
- package/src/handlers/system-update.ts +0 -230
- package/src/handlers/thread.test.ts +0 -396
- package/src/handlers/thread.ts +0 -427
- package/src/handlers/unified-threads-mail-sources.sqlite.test.ts +0 -197
- package/src/handlers/unified-threads.test.ts +0 -785
- package/src/handlers/unified-threads.ts +0 -669
- package/src/index.test.ts +0 -83
- package/src/index.ts +0 -228
- package/src/jwt-auth.test.ts +0 -152
- package/src/jwt-auth.ts +0 -132
- package/src/log-redaction.test.ts +0 -144
- package/src/openapi-spec.test.ts +0 -118
- package/src/request-context.test.ts +0 -61
- package/src/request-context.ts +0 -33
- package/src/request-pipeline.test.ts +0 -88
- package/src/request.ts +0 -10
- package/src/response.test.ts +0 -130
- package/src/response.ts +0 -144
- package/src/service/compose-sqlite.ts +0 -98
- package/src/service/config-import.ts +0 -39
- package/src/service/create-remit-client.ts +0 -522
- package/src/service/data-client.test.ts +0 -97
- package/src/service/data-client.ts +0 -58
- package/src/service/export-identity.ts +0 -39
- package/src/service/filter.ts +0 -40
- package/src/service/fire-and-forget.test.ts +0 -126
- package/src/service/fire-and-forget.ts +0 -79
- package/src/service/localhost-env-config.test.ts +0 -36
- package/src/service/organize-queue.ts +0 -98
- package/src/service/organize.test.ts +0 -1451
- package/src/service/organize.ts +0 -1025
- package/src/service/read-path-filter-config.test.ts +0 -243
- package/src/service/semantic-capability.test.ts +0 -78
- package/src/service/semantic-capability.ts +0 -95
- package/src/service/sender-category.test.ts +0 -235
- package/src/service/trigger-sync.test.ts +0 -205
- package/src/service/trigger-sync.ts +0 -100
- package/src/stdout-capture-fixture.ts +0 -40
- package/src/types.ts +0 -271
- package/tsconfig.json +0 -7
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { AccountSettingItem, IAccountSettingRepository } from "@remit/data-ports";
|
|
2
|
+
export interface AccountSignature {
|
|
3
|
+
plainText?: string;
|
|
4
|
+
html?: string;
|
|
5
|
+
}
|
|
6
|
+
/**
|
|
7
|
+
* Build a per-account signature lookup from the whole settings set of one
|
|
8
|
+
* account configuration. Signatures are stored as composite-named rows
|
|
9
|
+
* (`AccountSignaturePlainText#<accountId>` / `AccountSignatureHtml#<accountId>`),
|
|
10
|
+
* so one `listByAccountConfig` query yields every account's signature; this
|
|
11
|
+
* groups them by the `#<accountId>` suffix.
|
|
12
|
+
*/
|
|
13
|
+
export declare const groupSignaturesByAccount: (settings: AccountSettingItem[]) => Map<string, AccountSignature>;
|
|
14
|
+
/**
|
|
15
|
+
* Resolve the signature for a single account by reading just its two composite
|
|
16
|
+
* rows. Used by the account create/update handlers, which act on one account.
|
|
17
|
+
*/
|
|
18
|
+
export declare const loadSignatureForAccount: (accountSetting: IAccountSettingRepository, accountConfigId: string, accountId: string) => Promise<AccountSignature>;
|
|
19
|
+
/**
|
|
20
|
+
* Idempotent upsert of an account's signature fields. Only writes the parts the
|
|
21
|
+
* caller supplied — an empty string is a valid stored value (it clears the
|
|
22
|
+
* displayed signature without removing the row), matching the prior PATCH
|
|
23
|
+
* semantics where setting `""` stored `""`.
|
|
24
|
+
*/
|
|
25
|
+
export declare const upsertAccountSignature: (accountSetting: IAccountSettingRepository, accountConfigId: string, accountId: string, signature: {
|
|
26
|
+
plainText?: string;
|
|
27
|
+
html?: string;
|
|
28
|
+
}) => Promise<void>;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { baseSettingName, composeSettingName, SETTING_NAME_SEPARATOR, } from "@remit/data-ports/account-settings";
|
|
2
|
+
const SIGNATURE_NAMES = {
|
|
3
|
+
plainText: "AccountSignaturePlainText",
|
|
4
|
+
html: "AccountSignatureHtml",
|
|
5
|
+
};
|
|
6
|
+
const stringValueOf = (item) => {
|
|
7
|
+
const { value } = item;
|
|
8
|
+
if (value.kind === "String")
|
|
9
|
+
return value.value;
|
|
10
|
+
return undefined;
|
|
11
|
+
};
|
|
12
|
+
const accountIdOf = (name) => {
|
|
13
|
+
const idx = name.indexOf(SETTING_NAME_SEPARATOR);
|
|
14
|
+
if (idx === -1)
|
|
15
|
+
return undefined;
|
|
16
|
+
return name.slice(idx + SETTING_NAME_SEPARATOR.length) || undefined;
|
|
17
|
+
};
|
|
18
|
+
/**
|
|
19
|
+
* Build a per-account signature lookup from the whole settings set of one
|
|
20
|
+
* account configuration. Signatures are stored as composite-named rows
|
|
21
|
+
* (`AccountSignaturePlainText#<accountId>` / `AccountSignatureHtml#<accountId>`),
|
|
22
|
+
* so one `listByAccountConfig` query yields every account's signature; this
|
|
23
|
+
* groups them by the `#<accountId>` suffix.
|
|
24
|
+
*/
|
|
25
|
+
export const groupSignaturesByAccount = (settings) => {
|
|
26
|
+
const byAccount = new Map();
|
|
27
|
+
for (const setting of settings) {
|
|
28
|
+
const accountId = accountIdOf(setting.name);
|
|
29
|
+
if (!accountId)
|
|
30
|
+
continue;
|
|
31
|
+
const base = baseSettingName(setting.name);
|
|
32
|
+
const text = stringValueOf(setting);
|
|
33
|
+
if (text === undefined)
|
|
34
|
+
continue;
|
|
35
|
+
const current = byAccount.get(accountId) ?? {};
|
|
36
|
+
if (base === SIGNATURE_NAMES.plainText)
|
|
37
|
+
current.plainText = text;
|
|
38
|
+
if (base === SIGNATURE_NAMES.html)
|
|
39
|
+
current.html = text;
|
|
40
|
+
byAccount.set(accountId, current);
|
|
41
|
+
}
|
|
42
|
+
return byAccount;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Resolve the signature for a single account by reading just its two composite
|
|
46
|
+
* rows. Used by the account create/update handlers, which act on one account.
|
|
47
|
+
*/
|
|
48
|
+
export const loadSignatureForAccount = async (accountSetting, accountConfigId, accountId) => {
|
|
49
|
+
const [plain, html] = await Promise.all([
|
|
50
|
+
accountSetting.get(accountConfigId, composeSettingName(SIGNATURE_NAMES.plainText, accountId)),
|
|
51
|
+
accountSetting.get(accountConfigId, composeSettingName(SIGNATURE_NAMES.html, accountId)),
|
|
52
|
+
]);
|
|
53
|
+
const signature = {};
|
|
54
|
+
const plainText = plain ? stringValueOf(plain) : undefined;
|
|
55
|
+
const htmlText = html ? stringValueOf(html) : undefined;
|
|
56
|
+
if (plainText !== undefined)
|
|
57
|
+
signature.plainText = plainText;
|
|
58
|
+
if (htmlText !== undefined)
|
|
59
|
+
signature.html = htmlText;
|
|
60
|
+
return signature;
|
|
61
|
+
};
|
|
62
|
+
/**
|
|
63
|
+
* Idempotent upsert of an account's signature fields. Only writes the parts the
|
|
64
|
+
* caller supplied — an empty string is a valid stored value (it clears the
|
|
65
|
+
* displayed signature without removing the row), matching the prior PATCH
|
|
66
|
+
* semantics where setting `""` stored `""`.
|
|
67
|
+
*/
|
|
68
|
+
export const upsertAccountSignature = async (accountSetting, accountConfigId, accountId, signature) => {
|
|
69
|
+
const writes = [];
|
|
70
|
+
if (signature.plainText !== undefined) {
|
|
71
|
+
writes.push(accountSetting.upsert({
|
|
72
|
+
accountConfigId,
|
|
73
|
+
name: composeSettingName(SIGNATURE_NAMES.plainText, accountId),
|
|
74
|
+
value: { kind: "String", value: signature.plainText },
|
|
75
|
+
}));
|
|
76
|
+
}
|
|
77
|
+
if (signature.html !== undefined) {
|
|
78
|
+
writes.push(accountSetting.upsert({
|
|
79
|
+
accountConfigId,
|
|
80
|
+
name: composeSettingName(SIGNATURE_NAMES.html, accountId),
|
|
81
|
+
value: { kind: "String", value: signature.html },
|
|
82
|
+
}));
|
|
83
|
+
}
|
|
84
|
+
await Promise.all(writes);
|
|
85
|
+
};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import type { AccountDetailOperationIds, AccountOperationIds, OperationHandler } from "../types.js";
|
|
2
|
+
import { assertNotOAuthCreate, assertPasswordProvided, toAccountResponse } from "./account-guards.js";
|
|
3
|
+
export { assertNotOAuthCreate, assertPasswordProvided, toAccountResponse };
|
|
4
|
+
export declare const triggerAccountSyncSafe: (accountId: string) => Promise<void>;
|
|
5
|
+
export declare const AccountOperations: Record<AccountOperationIds, OperationHandler<AccountOperationIds>>;
|
|
6
|
+
export declare const AccountDetailOperations: Record<AccountDetailOperationIds, OperationHandler<AccountDetailOperationIds>>;
|
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
import { AccountAuthType, AccountService, ConnectionState, } from "@remit/domain-enums";
|
|
2
|
+
import { logger } from "@remit/logger";
|
|
3
|
+
import { createMailOAuthService, microsoftProviderConfig, RefreshTokenError, } from "@remit/mail-oauth-service";
|
|
4
|
+
import { ownedAccount, resolveConnectionCredentials, testImapConnection, testSmtpConnection, } from "@remit/mailbox-service";
|
|
5
|
+
import { deserializeEncryptedPayload, serializeEncryptedPayload, } from "@remit/secrets-service";
|
|
6
|
+
import { env } from "expect-env";
|
|
7
|
+
import { getAccountConfigIdFromEvent } from "../auth.js";
|
|
8
|
+
import { deleteAccount } from "../service/account-deletion.js";
|
|
9
|
+
import { getClient } from "../service/data-client.js";
|
|
10
|
+
import { fireAndForget } from "../service/fire-and-forget.js";
|
|
11
|
+
import { unwrap } from "../service/refusal.js";
|
|
12
|
+
import { sqsClient } from "../service/sqs.js";
|
|
13
|
+
import { triggerAccountSync } from "../service/trigger-sync.js";
|
|
14
|
+
import { assertNoDuplicateMailbox, assertNotOAuthCreate, assertPasswordProvided, resolveSyncedServices, toAccountResponse, } from "./account-guards.js";
|
|
15
|
+
import { loadAccountOverrides, upsertAccountDisplayName, writeAccountComposeLanguages, writeAccountMuted, } from "./account-overrides.js";
|
|
16
|
+
import { loadSignatureForAccount, upsertAccountSignature, } from "./account-signature.js";
|
|
17
|
+
import { ensureAccountConfig } from "./ensure-account-config.js";
|
|
18
|
+
import { resolveAccountFolderAppointments } from "./folder-role-appointments.js";
|
|
19
|
+
export { assertNotOAuthCreate, assertPasswordProvided, toAccountResponse };
|
|
20
|
+
export const triggerAccountSyncSafe = async (accountId) => {
|
|
21
|
+
const queueUrl = env.SQS_QUEUE_URL;
|
|
22
|
+
// Best-effort: account creation must still return 200 even if the sync
|
|
23
|
+
// enqueue fails. fireAndForget catches and logs every rejection loudly with
|
|
24
|
+
// the alertable structured fields and never rejects, so a failure here (SQS
|
|
25
|
+
// unreachable in smoke/e2e, an IAM/SQS misconfig in prod) cannot leak an
|
|
26
|
+
// unhandled rejection onto an unrelated in-flight request.
|
|
27
|
+
await fireAndForget(async () => {
|
|
28
|
+
const { eventId } = await triggerAccountSync({
|
|
29
|
+
sqsClient,
|
|
30
|
+
queueUrl,
|
|
31
|
+
accountId,
|
|
32
|
+
});
|
|
33
|
+
// biome-ignore lint/plugin/no-logger-info: sync-triggered-for-new-account is an audit-grade signal
|
|
34
|
+
logger.info({ accountId, eventId }, "Sync triggered for new account");
|
|
35
|
+
}, {
|
|
36
|
+
source: "account_create",
|
|
37
|
+
message: "Failed to enqueue SYNC_MAILBOXES for new account (best-effort)",
|
|
38
|
+
ids: { accountId },
|
|
39
|
+
});
|
|
40
|
+
};
|
|
41
|
+
/**
|
|
42
|
+
* Test connectivity for an OAuth (Microsoft) account.
|
|
43
|
+
*
|
|
44
|
+
* Mints an access token from the stored refresh token via
|
|
45
|
+
* resolveConnectionCredentials (the single authType branch), then runs the
|
|
46
|
+
* IMAP — and, when configured, SMTP — connection tests with those credentials.
|
|
47
|
+
*
|
|
48
|
+
* A revoked / expired refresh token surfaces as RefreshTokenError; the
|
|
49
|
+
* reauth-required case is mapped to the distinct `reauth_required` error code
|
|
50
|
+
* so the UI can route the user into the OAuth re-auth flow.
|
|
51
|
+
*
|
|
52
|
+
* MSOAUTH_* env vars are only present in deployed Lambdas; fall back to "".
|
|
53
|
+
*/
|
|
54
|
+
const testOAuthConnection = async (existingAccount, account, secrets) => {
|
|
55
|
+
const tokenService = createMailOAuthService(microsoftProviderConfig({
|
|
56
|
+
clientId: process.env.MSOAUTH_CLIENT_ID ?? "",
|
|
57
|
+
clientSecret: process.env.MSOAUTH_CLIENT_SECRET ?? "",
|
|
58
|
+
overrides: process.env.MSOAUTH_TOKEN_ENDPOINT
|
|
59
|
+
? { tokenEndpoint: process.env.MSOAUTH_TOKEN_ENDPOINT }
|
|
60
|
+
: undefined,
|
|
61
|
+
}));
|
|
62
|
+
let resolution;
|
|
63
|
+
try {
|
|
64
|
+
resolution = await resolveConnectionCredentials(existingAccount, {
|
|
65
|
+
secrets,
|
|
66
|
+
tokenService,
|
|
67
|
+
persistRotatedToken: async (id, encryptedHash, updatedAt) => {
|
|
68
|
+
await account.update(id, {
|
|
69
|
+
oauthRefreshTokenHash: encryptedHash,
|
|
70
|
+
oauthTokenUpdatedAt: updatedAt,
|
|
71
|
+
});
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
catch (err) {
|
|
76
|
+
if (err instanceof RefreshTokenError &&
|
|
77
|
+
err.error.kind === "reauth-required") {
|
|
78
|
+
return {
|
|
79
|
+
imapSuccess: false,
|
|
80
|
+
imapError: "reauth_required",
|
|
81
|
+
smtpSuccess: undefined,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
throw err;
|
|
85
|
+
}
|
|
86
|
+
if (resolution.status === "missing") {
|
|
87
|
+
return {
|
|
88
|
+
imapSuccess: false,
|
|
89
|
+
imapError: "oauth_not_configured",
|
|
90
|
+
smtpSuccess: undefined,
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
const credentials = resolution.credentials;
|
|
94
|
+
const result = {
|
|
95
|
+
imapSuccess: false,
|
|
96
|
+
smtpSuccess: undefined,
|
|
97
|
+
};
|
|
98
|
+
const imapResult = await testImapConnection({
|
|
99
|
+
host: existingAccount.imapHost,
|
|
100
|
+
port: existingAccount.imapPort,
|
|
101
|
+
secure: existingAccount.imapTls,
|
|
102
|
+
user: existingAccount.username,
|
|
103
|
+
credentials,
|
|
104
|
+
});
|
|
105
|
+
result.imapSuccess = imapResult.success;
|
|
106
|
+
if (!imapResult.success) {
|
|
107
|
+
result.imapError = imapResult.error;
|
|
108
|
+
}
|
|
109
|
+
// OAuth accounts share the same access token for IMAP and SMTP.
|
|
110
|
+
if (existingAccount.smtpEnabled) {
|
|
111
|
+
const smtpResult = await testSmtpConnection({
|
|
112
|
+
host: existingAccount.smtpHost ?? "",
|
|
113
|
+
port: existingAccount.smtpPort ?? 587,
|
|
114
|
+
secure: existingAccount.smtpTls ?? false,
|
|
115
|
+
user: existingAccount.smtpUsername || existingAccount.username,
|
|
116
|
+
credentials,
|
|
117
|
+
});
|
|
118
|
+
result.smtpSuccess = smtpResult.success;
|
|
119
|
+
if (!smtpResult.success) {
|
|
120
|
+
result.smtpError = smtpResult.error;
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return result;
|
|
124
|
+
};
|
|
125
|
+
export const AccountOperations = {
|
|
126
|
+
AccountOperations_createAccount: async (_context, ...args) => {
|
|
127
|
+
const event = args[0];
|
|
128
|
+
const accountConfigId = getAccountConfigIdFromEvent(event);
|
|
129
|
+
const input = JSON.parse(event.body ?? "{}");
|
|
130
|
+
// OAuth accounts must be created via the dedicated connect flow
|
|
131
|
+
assertNotOAuthCreate(input.authType);
|
|
132
|
+
// Password accounts require a non-empty password
|
|
133
|
+
assertPasswordProvided(input.authType, input.password);
|
|
134
|
+
const syncedServices = resolveSyncedServices({ authType: AccountAuthType.Password, grantedScopes: [] }, input.syncedServices ?? [AccountService.Mail]);
|
|
135
|
+
const { account, accountConfig, accountSetting, mailbox, secrets } = await getClient();
|
|
136
|
+
await ensureAccountConfig(accountConfig, accountConfigId);
|
|
137
|
+
// Reject re-onboarding the same mailbox-in-the-same-place. Message
|
|
138
|
+
// identity is account-scoped (#633), so duplicate onboards are no longer
|
|
139
|
+
// incidentally deduped — this is the explicit replacement (#635).
|
|
140
|
+
const existingAccounts = await account.listAllByAccountConfig(accountConfigId);
|
|
141
|
+
assertNoDuplicateMailbox(existingAccounts, {
|
|
142
|
+
imapHost: input.imapHost,
|
|
143
|
+
username: input.username ?? input.email,
|
|
144
|
+
});
|
|
145
|
+
// biome-ignore lint/style/noNonNullAssertion: guard above ensures password is set for password-auth accounts
|
|
146
|
+
const passwordPayload = await secrets.encrypt(input.password);
|
|
147
|
+
const passwordHash = JSON.stringify(serializeEncryptedPayload(passwordPayload));
|
|
148
|
+
let smtpPasswordHash;
|
|
149
|
+
if (input.smtpPassword) {
|
|
150
|
+
const smtpPayload = await secrets.encrypt(input.smtpPassword);
|
|
151
|
+
smtpPasswordHash = JSON.stringify(serializeEncryptedPayload(smtpPayload));
|
|
152
|
+
}
|
|
153
|
+
const newAccount = await account.create({
|
|
154
|
+
accountConfigId,
|
|
155
|
+
email: input.email,
|
|
156
|
+
username: input.username ?? input.email,
|
|
157
|
+
authType: AccountAuthType.Password,
|
|
158
|
+
syncedServices,
|
|
159
|
+
passwordHash,
|
|
160
|
+
imapHost: input.imapHost,
|
|
161
|
+
imapPort: input.imapPort,
|
|
162
|
+
imapTls: input.imapTls,
|
|
163
|
+
imapStartTls: input.imapStartTls,
|
|
164
|
+
// RFC 032 Tier 2: smtpEnabled is the explicit send-capability marker.
|
|
165
|
+
// Honour an explicit flag from the client; otherwise enable sending when
|
|
166
|
+
// an SMTP host was supplied (the prior implicit behaviour).
|
|
167
|
+
smtpEnabled: input.smtpEnabled ?? Boolean(input.smtpHost),
|
|
168
|
+
smtpHost: input.smtpHost,
|
|
169
|
+
smtpPort: input.smtpPort,
|
|
170
|
+
smtpTls: input.smtpTls,
|
|
171
|
+
smtpStartTls: input.smtpStartTls,
|
|
172
|
+
smtpUsername: input.smtpUsername,
|
|
173
|
+
smtpPasswordHash,
|
|
174
|
+
isActive: true,
|
|
175
|
+
connectionState: ConnectionState.NotAuthenticated,
|
|
176
|
+
});
|
|
177
|
+
// Display name lives in a per-account AccountSetting row (RFC 032), not on
|
|
178
|
+
// the entity. Persist it when supplied so the response and later reads
|
|
179
|
+
// surface it unchanged.
|
|
180
|
+
if (input.displayName !== undefined) {
|
|
181
|
+
await upsertAccountDisplayName(accountSetting, accountConfigId, newAccount.accountId, input.displayName);
|
|
182
|
+
}
|
|
183
|
+
await triggerAccountSyncSafe(newAccount.accountId);
|
|
184
|
+
const [overrides, folderAppointments] = await Promise.all([
|
|
185
|
+
loadAccountOverrides(accountSetting, accountConfigId, newAccount.accountId),
|
|
186
|
+
resolveAccountFolderAppointments({ mailbox, accountSetting }, accountConfigId, newAccount.accountId),
|
|
187
|
+
]);
|
|
188
|
+
return toAccountResponse(newAccount, {}, overrides, folderAppointments);
|
|
189
|
+
},
|
|
190
|
+
AccountOperations_testConnection: async (_context, ...args) => {
|
|
191
|
+
const event = args[0];
|
|
192
|
+
const accountConfigId = getAccountConfigIdFromEvent(event);
|
|
193
|
+
const input = JSON.parse(event.body ?? "{}");
|
|
194
|
+
const { account, secrets } = await getClient();
|
|
195
|
+
// Resolve password - use provided password or decrypt stored password
|
|
196
|
+
let imapPassword = input.password;
|
|
197
|
+
let smtpPassword = input.smtpPassword;
|
|
198
|
+
if (!imapPassword && input.accountId) {
|
|
199
|
+
const existingAccount = await account.get(input.accountId);
|
|
200
|
+
unwrap(ownedAccount(existingAccount, accountConfigId, "read"));
|
|
201
|
+
const authType = existingAccount.authType ?? "password";
|
|
202
|
+
if (authType === "oauthMicrosoft") {
|
|
203
|
+
return testOAuthConnection(existingAccount, account, secrets);
|
|
204
|
+
}
|
|
205
|
+
if (existingAccount.passwordHash) {
|
|
206
|
+
const payload = deserializeEncryptedPayload(JSON.parse(existingAccount.passwordHash));
|
|
207
|
+
imapPassword = await secrets.decrypt(payload);
|
|
208
|
+
}
|
|
209
|
+
// Also get SMTP password if needed and available
|
|
210
|
+
if (!smtpPassword && existingAccount.smtpPasswordHash) {
|
|
211
|
+
const smtpPayload = deserializeEncryptedPayload(JSON.parse(existingAccount.smtpPasswordHash));
|
|
212
|
+
smtpPassword = await secrets.decrypt(smtpPayload);
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
if (!imapPassword) {
|
|
216
|
+
return {
|
|
217
|
+
imapSuccess: false,
|
|
218
|
+
imapError: "Password required",
|
|
219
|
+
smtpSuccess: undefined,
|
|
220
|
+
};
|
|
221
|
+
}
|
|
222
|
+
const result = {
|
|
223
|
+
imapSuccess: false,
|
|
224
|
+
smtpSuccess: undefined,
|
|
225
|
+
};
|
|
226
|
+
// Test IMAP connection
|
|
227
|
+
const imapResult = await testImapConnection({
|
|
228
|
+
host: input.imapHost,
|
|
229
|
+
port: input.imapPort,
|
|
230
|
+
secure: input.imapTls,
|
|
231
|
+
startTls: input.imapStartTls,
|
|
232
|
+
user: input.username,
|
|
233
|
+
credentials: { kind: "password", password: imapPassword },
|
|
234
|
+
});
|
|
235
|
+
result.imapSuccess = imapResult.success;
|
|
236
|
+
if (!imapResult.success) {
|
|
237
|
+
result.imapError = imapResult.error;
|
|
238
|
+
}
|
|
239
|
+
// Test SMTP connection if configured
|
|
240
|
+
if (input.smtpHost) {
|
|
241
|
+
const smtpResult = await testSmtpConnection({
|
|
242
|
+
host: input.smtpHost,
|
|
243
|
+
port: input.smtpPort ?? 587,
|
|
244
|
+
secure: input.smtpTls ?? false,
|
|
245
|
+
user: input.smtpUsername ?? input.username,
|
|
246
|
+
credentials: {
|
|
247
|
+
kind: "password",
|
|
248
|
+
password: smtpPassword ?? imapPassword,
|
|
249
|
+
},
|
|
250
|
+
});
|
|
251
|
+
result.smtpSuccess = smtpResult.success;
|
|
252
|
+
if (!smtpResult.success) {
|
|
253
|
+
result.smtpError = smtpResult.error;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
return result;
|
|
257
|
+
},
|
|
258
|
+
};
|
|
259
|
+
const encryptedSecret = async (secrets, plaintext) => plaintext
|
|
260
|
+
? JSON.stringify(serializeEncryptedPayload(await secrets.encrypt(plaintext)))
|
|
261
|
+
: undefined;
|
|
262
|
+
export const AccountDetailOperations = {
|
|
263
|
+
AccountDetailOperations_updateAccount: async (context, ...args) => {
|
|
264
|
+
const event = args[0];
|
|
265
|
+
const accountConfigId = getAccountConfigIdFromEvent(event);
|
|
266
|
+
const { accountId } = context.request.params;
|
|
267
|
+
const input = JSON.parse(event.body ?? "{}");
|
|
268
|
+
const { account, accountSetting, mailbox, secrets } = await getClient();
|
|
269
|
+
const existing = await account.get(accountId);
|
|
270
|
+
unwrap(ownedAccount(existing, accountConfigId, "act"));
|
|
271
|
+
const entityFields = {
|
|
272
|
+
imapHost: input.imapHost,
|
|
273
|
+
imapPort: input.imapPort,
|
|
274
|
+
imapTls: input.imapTls,
|
|
275
|
+
imapStartTls: input.imapStartTls,
|
|
276
|
+
// RFC 032 Tier 2: keep the explicit send-capability marker in sync. When a
|
|
277
|
+
// caller changes the SMTP host without passing smtpEnabled, derive it from
|
|
278
|
+
// host presence so the marker can't drift from the config.
|
|
279
|
+
smtpEnabled: input.smtpEnabled ??
|
|
280
|
+
(input.smtpHost === undefined ? undefined : Boolean(input.smtpHost)),
|
|
281
|
+
smtpHost: input.smtpHost,
|
|
282
|
+
smtpPort: input.smtpPort,
|
|
283
|
+
smtpTls: input.smtpTls,
|
|
284
|
+
smtpStartTls: input.smtpStartTls,
|
|
285
|
+
smtpUsername: input.smtpUsername,
|
|
286
|
+
isActive: input.isActive,
|
|
287
|
+
syncedServices: input.syncedServices === undefined
|
|
288
|
+
? undefined
|
|
289
|
+
: resolveSyncedServices(existing, input.syncedServices),
|
|
290
|
+
};
|
|
291
|
+
const updates = {
|
|
292
|
+
...entityFields,
|
|
293
|
+
passwordHash: await encryptedSecret(secrets, input.password),
|
|
294
|
+
smtpPasswordHash: await encryptedSecret(secrets, input.smtpPassword),
|
|
295
|
+
};
|
|
296
|
+
// Display name and the mute flag live in per-account AccountSetting rows
|
|
297
|
+
// (RFC 032), not on the account entity. Display name upserts when supplied;
|
|
298
|
+
// the mute flag follows the address-flag null→remove, object→set semantics
|
|
299
|
+
// (the client populates setAt).
|
|
300
|
+
if (input.displayName !== undefined) {
|
|
301
|
+
await upsertAccountDisplayName(accountSetting, accountConfigId, accountId, input.displayName);
|
|
302
|
+
}
|
|
303
|
+
if (input.composeLanguages !== undefined) {
|
|
304
|
+
await writeAccountComposeLanguages(accountSetting, accountConfigId, accountId, input.composeLanguages);
|
|
305
|
+
}
|
|
306
|
+
if (Object.hasOwn(input, "muted")) {
|
|
307
|
+
if (input.muted !== undefined) {
|
|
308
|
+
await writeAccountMuted(accountSetting, accountConfigId, accountId, input.muted);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
// Signatures live in per-account AccountSetting rows (RFC 032), not on the
|
|
312
|
+
// account entity. Persist each supplied part as a composite-named setting;
|
|
313
|
+
// an empty string is a valid stored value (preserves the prior "set ''
|
|
314
|
+
// stores ''" semantics — it does not delete the row).
|
|
315
|
+
if (input.signaturePlainText !== undefined ||
|
|
316
|
+
input.signatureHtml !== undefined) {
|
|
317
|
+
await upsertAccountSignature(accountSetting, accountConfigId, accountId, {
|
|
318
|
+
plainText: input.signaturePlainText,
|
|
319
|
+
html: input.signatureHtml,
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
const updated = await account.update(accountId, updates);
|
|
323
|
+
const [signature, overrides, folderAppointments] = await Promise.all([
|
|
324
|
+
loadSignatureForAccount(accountSetting, accountConfigId, accountId),
|
|
325
|
+
loadAccountOverrides(accountSetting, accountConfigId, accountId),
|
|
326
|
+
resolveAccountFolderAppointments({ mailbox, accountSetting }, accountConfigId, accountId),
|
|
327
|
+
]);
|
|
328
|
+
return toAccountResponse(updated, signature, overrides, folderAppointments);
|
|
329
|
+
},
|
|
330
|
+
AccountDetailOperations_deleteAccount: async (context, ...args) => {
|
|
331
|
+
const event = args[0];
|
|
332
|
+
const accountConfigId = getAccountConfigIdFromEvent(event);
|
|
333
|
+
const { accountId } = context.request.params;
|
|
334
|
+
const { account } = await getClient();
|
|
335
|
+
const existing = await account.get(accountId);
|
|
336
|
+
unwrap(ownedAccount(existing, accountConfigId, "act"));
|
|
337
|
+
const deletedAt = Date.now();
|
|
338
|
+
await deleteAccount({
|
|
339
|
+
account,
|
|
340
|
+
sqsClient,
|
|
341
|
+
accountFanoutQueueUrl: env.SQS_QUEUE_URL_ACCOUNT_FANOUT,
|
|
342
|
+
log: logger,
|
|
343
|
+
}, existing, deletedAt);
|
|
344
|
+
return {
|
|
345
|
+
accountId,
|
|
346
|
+
deletedAt,
|
|
347
|
+
message: "Account marked for deletion. Data cleanup will complete shortly.",
|
|
348
|
+
};
|
|
349
|
+
},
|
|
350
|
+
};
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { AddressResponse, UpdateAddressInput } from "@remit/api-openapi-types";
|
|
2
|
+
import type { AddressFlags, AddressItem, FlagsMergePatch } from "@remit/data-ports";
|
|
3
|
+
import type { AddressDetailOperationIds, AddressOperationIds, OperationHandler } from "../types.js";
|
|
4
|
+
export declare const toAddressResponse: (item: AddressItem) => AddressResponse;
|
|
5
|
+
/**
|
|
6
|
+
* Translate the wire-format `UpdateAddressInput` into a service-level
|
|
7
|
+
* `FlagsMergePatch`. Only known flag keys are forwarded; unknown keys are
|
|
8
|
+
* silently dropped (a TypeSpec-only schema means unknown keys are a client
|
|
9
|
+
* bug, not a security risk).
|
|
10
|
+
*
|
|
11
|
+
* `clearFlags` is the removal form for every flag whatever its value type, and
|
|
12
|
+
* is applied after `flags`, so a key named in both ends up removed. The `null`
|
|
13
|
+
* alternative on a flag key stays honoured for callers that can express it,
|
|
14
|
+
* but it is unreachable over OAS 3.0: TypeSpec emits a nullable `$ref` as
|
|
15
|
+
* `allOf`, and the request validator drops the `nullable` there.
|
|
16
|
+
*/
|
|
17
|
+
export declare const buildFlagsPatch: (input: UpdateAddressInput | undefined) => FlagsMergePatch;
|
|
18
|
+
/**
|
|
19
|
+
* The category flag a back-apply should be enqueued for, or `undefined` when
|
|
20
|
+
* this patch asks for none (issue #415).
|
|
21
|
+
*
|
|
22
|
+
* A SET fires one; a CLEAR — `null` in the patch, whether it came from
|
|
23
|
+
* `clearFlags` or from the nullable flag value — never does. Reverting a sender
|
|
24
|
+
* to auto-classification says nothing about what the classifier would have
|
|
25
|
+
* answered on mail already filed, and re-deriving that would need every
|
|
26
|
+
* message's body back; the revert takes effect on the sender's next message,
|
|
27
|
+
* exactly as the override itself did before this.
|
|
28
|
+
*
|
|
29
|
+
* The whole flag, not just its value: `setAt` identifies WHICH set the job was
|
|
30
|
+
* fired for, and the worker refuses to apply a job whose set is no longer the
|
|
31
|
+
* one standing on the Address.
|
|
32
|
+
*/
|
|
33
|
+
export declare const backApplyCategoryFlag: (patch: FlagsMergePatch) => NonNullable<AddressFlags["category"]> | undefined;
|
|
34
|
+
export declare const AddressOperations: Record<AddressOperationIds, OperationHandler<AddressOperationIds>>;
|
|
35
|
+
export declare const AddressDetailOperations: Record<AddressDetailOperationIds, OperationHandler<AddressDetailOperationIds>>;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
import { SendMessageCommand } from "@aws-sdk/client-sqs";
|
|
2
|
+
import { ForbiddenError } from "@remit/data-ports/errors";
|
|
3
|
+
import { AddressFlagKey } from "@remit/domain-enums";
|
|
4
|
+
import { env } from "expect-env";
|
|
5
|
+
import { getAccountConfigIdFromEvent } from "../auth.js";
|
|
6
|
+
import { getClient } from "../service/data-client.js";
|
|
7
|
+
import { sqsClient } from "../service/sqs.js";
|
|
8
|
+
export const toAddressResponse = (item) => ({
|
|
9
|
+
addressId: item.addressId,
|
|
10
|
+
accountConfigId: item.accountConfigId,
|
|
11
|
+
displayName: item.displayName,
|
|
12
|
+
localPart: item.localPart,
|
|
13
|
+
domain: item.domain,
|
|
14
|
+
normalizedEmail: item.normalizedEmail,
|
|
15
|
+
flags: item.flags ?? {},
|
|
16
|
+
inboundCount: item.inboundCount ?? 0,
|
|
17
|
+
outboundCount: item.outboundCount ?? 0,
|
|
18
|
+
replyCount: item.replyCount ?? 0,
|
|
19
|
+
lastInboundAt: item.lastInboundAt ?? 0,
|
|
20
|
+
lastReplyAt: item.lastReplyAt ?? 0,
|
|
21
|
+
createdAt: item.createdAt,
|
|
22
|
+
updatedAt: item.updatedAt,
|
|
23
|
+
});
|
|
24
|
+
const FLAG_KEYS = Object.values(AddressFlagKey);
|
|
25
|
+
/**
|
|
26
|
+
* Translate the wire-format `UpdateAddressInput` into a service-level
|
|
27
|
+
* `FlagsMergePatch`. Only known flag keys are forwarded; unknown keys are
|
|
28
|
+
* silently dropped (a TypeSpec-only schema means unknown keys are a client
|
|
29
|
+
* bug, not a security risk).
|
|
30
|
+
*
|
|
31
|
+
* `clearFlags` is the removal form for every flag whatever its value type, and
|
|
32
|
+
* is applied after `flags`, so a key named in both ends up removed. The `null`
|
|
33
|
+
* alternative on a flag key stays honoured for callers that can express it,
|
|
34
|
+
* but it is unreachable over OAS 3.0: TypeSpec emits a nullable `$ref` as
|
|
35
|
+
* `allOf`, and the request validator drops the `nullable` there.
|
|
36
|
+
*/
|
|
37
|
+
export const buildFlagsPatch = (input) => {
|
|
38
|
+
if (!input)
|
|
39
|
+
return {};
|
|
40
|
+
const patch = {};
|
|
41
|
+
const flags = input.flags;
|
|
42
|
+
if (flags) {
|
|
43
|
+
for (const key of FLAG_KEYS) {
|
|
44
|
+
if (!(key in flags))
|
|
45
|
+
continue;
|
|
46
|
+
const value = flags[key];
|
|
47
|
+
if (value === null) {
|
|
48
|
+
patch[key] = null;
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
if (value === undefined)
|
|
52
|
+
continue;
|
|
53
|
+
patch[key] = value;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
for (const key of input.clearFlags ?? []) {
|
|
57
|
+
if (!FLAG_KEYS.includes(key))
|
|
58
|
+
continue;
|
|
59
|
+
patch[key] = null;
|
|
60
|
+
}
|
|
61
|
+
return patch;
|
|
62
|
+
};
|
|
63
|
+
/**
|
|
64
|
+
* The category flag a back-apply should be enqueued for, or `undefined` when
|
|
65
|
+
* this patch asks for none (issue #415).
|
|
66
|
+
*
|
|
67
|
+
* A SET fires one; a CLEAR — `null` in the patch, whether it came from
|
|
68
|
+
* `clearFlags` or from the nullable flag value — never does. Reverting a sender
|
|
69
|
+
* to auto-classification says nothing about what the classifier would have
|
|
70
|
+
* answered on mail already filed, and re-deriving that would need every
|
|
71
|
+
* message's body back; the revert takes effect on the sender's next message,
|
|
72
|
+
* exactly as the override itself did before this.
|
|
73
|
+
*
|
|
74
|
+
* The whole flag, not just its value: `setAt` identifies WHICH set the job was
|
|
75
|
+
* fired for, and the worker refuses to apply a job whose set is no longer the
|
|
76
|
+
* one standing on the Address.
|
|
77
|
+
*/
|
|
78
|
+
export const backApplyCategoryFlag = (patch) => {
|
|
79
|
+
const flag = patch.category;
|
|
80
|
+
if (flag === null || flag === undefined)
|
|
81
|
+
return undefined;
|
|
82
|
+
return flag;
|
|
83
|
+
};
|
|
84
|
+
export const AddressOperations = {
|
|
85
|
+
AddressOperations_searchAddresses: async (context, ...args) => {
|
|
86
|
+
const event = args[0];
|
|
87
|
+
const accountConfigId = getAccountConfigIdFromEvent(event);
|
|
88
|
+
const { q, limit } = context.request.query;
|
|
89
|
+
const client = await getClient();
|
|
90
|
+
const result = await client.address.listByAccountConfig({
|
|
91
|
+
accountConfigId,
|
|
92
|
+
search: q.toLowerCase(),
|
|
93
|
+
limit: limit ?? 10,
|
|
94
|
+
});
|
|
95
|
+
return {
|
|
96
|
+
items: result.items.map(toAddressResponse),
|
|
97
|
+
continuationToken: result.continuationToken,
|
|
98
|
+
};
|
|
99
|
+
},
|
|
100
|
+
};
|
|
101
|
+
export const AddressDetailOperations = {
|
|
102
|
+
AddressDetailOperations_updateAddress: async (context, ...args) => {
|
|
103
|
+
const event = args[0];
|
|
104
|
+
const accountConfigId = getAccountConfigIdFromEvent(event);
|
|
105
|
+
const { addressId } = context.request.params;
|
|
106
|
+
const body = (context.request.requestBody ?? {});
|
|
107
|
+
const client = await getClient();
|
|
108
|
+
// Authorize: address must belong to the caller's accountConfig
|
|
109
|
+
const existing = await client.address.getAddress(accountConfigId, addressId);
|
|
110
|
+
if (existing.accountConfigId !== accountConfigId) {
|
|
111
|
+
throw new ForbiddenError(`Address ${addressId} not in account config`);
|
|
112
|
+
}
|
|
113
|
+
const patch = buildFlagsPatch(body);
|
|
114
|
+
if (Object.keys(patch).length === 0) {
|
|
115
|
+
return toAddressResponse(existing);
|
|
116
|
+
}
|
|
117
|
+
const updated = await client.address.mergeFlags(accountConfigId, addressId, patch);
|
|
118
|
+
const flag = backApplyCategoryFlag(patch);
|
|
119
|
+
if (flag) {
|
|
120
|
+
// The flag itself is already durable. A queue failure here costs the
|
|
121
|
+
// user the retroactive pass and nothing else, so the 500 says so and
|
|
122
|
+
// names the retry — re-sending the same category enqueues a fresh job.
|
|
123
|
+
await sqsClient
|
|
124
|
+
.send(new SendMessageCommand({
|
|
125
|
+
QueueUrl: env.SQS_QUEUE_URL_ACCOUNT_FANOUT,
|
|
126
|
+
MessageBody: JSON.stringify({
|
|
127
|
+
type: "SenderCategoryBackApply",
|
|
128
|
+
accountConfigId,
|
|
129
|
+
addressId,
|
|
130
|
+
normalizedEmail: updated.normalizedEmail,
|
|
131
|
+
category: flag.value,
|
|
132
|
+
categorySetAt: flag.setAt,
|
|
133
|
+
}),
|
|
134
|
+
}))
|
|
135
|
+
.catch((cause) => {
|
|
136
|
+
throw new Error(`The ${flag.value} override is saved and applies to this sender's next message, but the pass over their existing mail could not be started. Setting the same category again retries it.`, { cause });
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
return toAddressResponse(updated);
|
|
140
|
+
},
|
|
141
|
+
};
|