@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.
- 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 -521
- 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,387 @@
|
|
|
1
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { inspect } from "node:util";
|
|
3
|
+
import { GetSecretValueCommand, SecretsManagerClient, } from "@aws-sdk/client-secrets-manager";
|
|
4
|
+
import { AccountAuthType, AccountService, ConnectionState, } from "@remit/domain-enums";
|
|
5
|
+
import { logger } from "@remit/logger";
|
|
6
|
+
import { createMailOAuthService, microsoftProviderConfig, microsoftServicesGranted, orderServices, RefreshTokenError, } from "@remit/mail-oauth-service";
|
|
7
|
+
import { serializeEncryptedPayload } from "@remit/secrets-service";
|
|
8
|
+
import { getAccountConfigIdFromEvent } from "../auth.js";
|
|
9
|
+
import { getMsOAuthConfig } from "../config/msoauth.js";
|
|
10
|
+
import { safeJsonParse } from "../json.js";
|
|
11
|
+
import { rawApiResponse } from "../response.js";
|
|
12
|
+
import { getClient } from "../service/data-client.js";
|
|
13
|
+
import { triggerAccountSyncSafe } from "./account.js";
|
|
14
|
+
import { findActiveDuplicateMailbox } from "./account-guards.js";
|
|
15
|
+
import { ensureAccountConfig } from "./ensure-account-config.js";
|
|
16
|
+
const OUTLOOK_IMAP_HOST = "outlook.office365.com";
|
|
17
|
+
const ACCOUNT_SERVICES = Object.values(AccountService);
|
|
18
|
+
const isServiceList = (value) => Array.isArray(value) &&
|
|
19
|
+
value.length > 0 &&
|
|
20
|
+
value.every((service) => typeof service === "string" && ACCOUNT_SERVICES.includes(service));
|
|
21
|
+
export const STATE_TTL_MS = 10 * 60 * 1000; // 10 minutes
|
|
22
|
+
/**
|
|
23
|
+
* Derive a signing key from the client secret, namespaced to avoid reuse.
|
|
24
|
+
* The key is HMAC-SHA256("oauth-state-signing:" + clientSecret).
|
|
25
|
+
*/
|
|
26
|
+
function deriveSigningKey(clientSecret) {
|
|
27
|
+
return createHmac("sha256", `oauth-state-signing:${clientSecret}`)
|
|
28
|
+
.update("")
|
|
29
|
+
.digest();
|
|
30
|
+
}
|
|
31
|
+
function base64urlEncode(buf) {
|
|
32
|
+
return buf.toString("base64url");
|
|
33
|
+
}
|
|
34
|
+
function base64urlDecode(str) {
|
|
35
|
+
return Buffer.from(str, "base64url");
|
|
36
|
+
}
|
|
37
|
+
export async function signState(payload, clientSecret) {
|
|
38
|
+
const key = deriveSigningKey(clientSecret);
|
|
39
|
+
const payloadBuf = Buffer.from(JSON.stringify(payload), "utf8");
|
|
40
|
+
const payloadEncoded = base64urlEncode(payloadBuf);
|
|
41
|
+
const sig = createHmac("sha256", key).update(payloadEncoded).digest();
|
|
42
|
+
const sigEncoded = base64urlEncode(sig);
|
|
43
|
+
return `${payloadEncoded}.${sigEncoded}`;
|
|
44
|
+
}
|
|
45
|
+
export async function verifyState(state, clientSecret) {
|
|
46
|
+
const dotIndex = state.lastIndexOf(".");
|
|
47
|
+
if (dotIndex < 0)
|
|
48
|
+
throw new Error("Malformed state: missing dot separator");
|
|
49
|
+
const payloadEncoded = state.slice(0, dotIndex);
|
|
50
|
+
const sigEncoded = state.slice(dotIndex + 1);
|
|
51
|
+
const key = deriveSigningKey(clientSecret);
|
|
52
|
+
const expectedSig = createHmac("sha256", key).update(payloadEncoded).digest();
|
|
53
|
+
const actualSig = base64urlDecode(sigEncoded);
|
|
54
|
+
if (actualSig.length !== expectedSig.length ||
|
|
55
|
+
!timingSafeEqual(actualSig, expectedSig)) {
|
|
56
|
+
throw new Error("State signature verification failed");
|
|
57
|
+
}
|
|
58
|
+
const payload = JSON.parse(base64urlDecode(payloadEncoded).toString("utf8"));
|
|
59
|
+
if (Date.now() - payload.timestamp > STATE_TTL_MS) {
|
|
60
|
+
throw new Error("State has expired");
|
|
61
|
+
}
|
|
62
|
+
if (payload.services === undefined) {
|
|
63
|
+
return { ...payload, services: [AccountService.Mail] };
|
|
64
|
+
}
|
|
65
|
+
if (!isServiceList(payload.services)) {
|
|
66
|
+
throw new Error("State names no requested services");
|
|
67
|
+
}
|
|
68
|
+
return payload;
|
|
69
|
+
}
|
|
70
|
+
// ─── JWT claims parsing ──────────────────────────────────────────────────────
|
|
71
|
+
export async function parseJwtClaims(token) {
|
|
72
|
+
const parts = token.split(".");
|
|
73
|
+
if (parts.length !== 3)
|
|
74
|
+
return null;
|
|
75
|
+
return safeJsonParse(Buffer.from(parts[1], "base64url").toString("utf8")).catch(() => null);
|
|
76
|
+
}
|
|
77
|
+
let smClient = null;
|
|
78
|
+
function getSecretsManagerClient() {
|
|
79
|
+
if (!smClient)
|
|
80
|
+
smClient = new SecretsManagerClient({});
|
|
81
|
+
return smClient;
|
|
82
|
+
}
|
|
83
|
+
function credentialFailure(name, message) {
|
|
84
|
+
const error = new Error(message);
|
|
85
|
+
error.name = name;
|
|
86
|
+
return error;
|
|
87
|
+
}
|
|
88
|
+
async function getMsOAuthCredentials() {
|
|
89
|
+
const config = getMsOAuthConfig();
|
|
90
|
+
// Local dev: use env vars directly
|
|
91
|
+
if (config.clientId && config.clientSecret) {
|
|
92
|
+
return { clientId: config.clientId, clientSecret: config.clientSecret };
|
|
93
|
+
}
|
|
94
|
+
// Production: fetch from Secrets Manager
|
|
95
|
+
if (!config.secretArn) {
|
|
96
|
+
throw credentialFailure("MicrosoftOAuthNotConfigured", "No Microsoft OAuth credentials are configured on this instance: set MSOAUTH_CLIENT_ID and MSOAUTH_CLIENT_SECRET, or MSOAUTH_SECRET_ARN");
|
|
97
|
+
}
|
|
98
|
+
const sm = getSecretsManagerClient();
|
|
99
|
+
const result = await sm.send(new GetSecretValueCommand({ SecretId: config.secretArn }));
|
|
100
|
+
if (!result.SecretString) {
|
|
101
|
+
throw credentialFailure("MicrosoftOAuthSecretEmpty", "The Microsoft OAuth secret named by MSOAUTH_SECRET_ARN holds no SecretString");
|
|
102
|
+
}
|
|
103
|
+
const parsed = await safeJsonParse(result.SecretString).catch(() => null);
|
|
104
|
+
if (!parsed) {
|
|
105
|
+
throw credentialFailure("MicrosoftOAuthSecretUnparseable", "The Microsoft OAuth secret named by MSOAUTH_SECRET_ARN does not hold a JSON object");
|
|
106
|
+
}
|
|
107
|
+
const absent = ["clientId", "clientSecret"].filter((field) => !parsed[field]);
|
|
108
|
+
if (absent.length > 0) {
|
|
109
|
+
throw credentialFailure("MicrosoftOAuthSecretIncomplete", `The Microsoft OAuth secret named by MSOAUTH_SECRET_ARN is missing ${absent.join(" and ")}`);
|
|
110
|
+
}
|
|
111
|
+
return parsed;
|
|
112
|
+
}
|
|
113
|
+
// ─── Web origin helper ───────────────────────────────────────────────────────
|
|
114
|
+
export function getWebOrigin() {
|
|
115
|
+
const raw = process.env.CORS_ALLOWED_ORIGINS ?? "";
|
|
116
|
+
const origins = raw
|
|
117
|
+
.split(",")
|
|
118
|
+
.map((o) => o.trim())
|
|
119
|
+
.filter(Boolean);
|
|
120
|
+
// Prefer the first HTTPS origin (production frontend)
|
|
121
|
+
const httpsOrigin = origins.find((o) => o.startsWith("https://"));
|
|
122
|
+
return httpsOrigin ?? origins[0] ?? "https://localhost:3000";
|
|
123
|
+
}
|
|
124
|
+
const scopeRefusalUrl = (webOrigin, email, missingServices) => {
|
|
125
|
+
const url = new URL(`${webOrigin}/settings/accounts`);
|
|
126
|
+
url.searchParams.set("oauthError", "scope_not_granted");
|
|
127
|
+
url.searchParams.set("oauthEmail", email);
|
|
128
|
+
url.searchParams.set("missingServices", missingServices.join(","));
|
|
129
|
+
return url.toString();
|
|
130
|
+
};
|
|
131
|
+
const redeemEachService = async (serviceFor, initialToken, services, accountConfigId) => {
|
|
132
|
+
let token = initialToken;
|
|
133
|
+
const grantedScopes = [];
|
|
134
|
+
for (const service of services) {
|
|
135
|
+
const redeemed = await serviceFor(service)
|
|
136
|
+
.refresh(token)
|
|
137
|
+
.catch((err) => {
|
|
138
|
+
logger.warn({
|
|
139
|
+
alert: "oauth_callback_failed",
|
|
140
|
+
reason: "scope_redemption_failed",
|
|
141
|
+
accountConfigId,
|
|
142
|
+
service,
|
|
143
|
+
error: inspect(err),
|
|
144
|
+
}, "MS OAuth callback: the consent did not cover a requested service");
|
|
145
|
+
return err instanceof RefreshTokenError &&
|
|
146
|
+
err.error.kind === "transient"
|
|
147
|
+
? "exchange_failed"
|
|
148
|
+
: "scope_not_granted";
|
|
149
|
+
});
|
|
150
|
+
if (redeemed === "exchange_failed")
|
|
151
|
+
return { kind: "refused", reason: redeemed };
|
|
152
|
+
if (redeemed === "scope_not_granted")
|
|
153
|
+
return { kind: "refused", reason: redeemed, service };
|
|
154
|
+
grantedScopes.push(...redeemed.grantedScopes);
|
|
155
|
+
token = redeemed.refreshToken ?? token;
|
|
156
|
+
}
|
|
157
|
+
return { kind: "granted", refreshToken: token, grantedScopes };
|
|
158
|
+
};
|
|
159
|
+
// ─── Handlers ────────────────────────────────────────────────────────────────
|
|
160
|
+
export const MicrosoftOAuthOperations = {
|
|
161
|
+
MicrosoftOAuthOperations_microsoftOAuthStart: async (_context, ...args) => {
|
|
162
|
+
const event = args[0];
|
|
163
|
+
const accountConfigId = getAccountConfigIdFromEvent(event);
|
|
164
|
+
const input = JSON.parse(event.body ?? "{}");
|
|
165
|
+
const email = typeof input.email === "string" ? input.email : undefined;
|
|
166
|
+
const services = orderServices(input.services ?? [AccountService.Mail]);
|
|
167
|
+
const config = getMsOAuthConfig();
|
|
168
|
+
const credentials = await getMsOAuthCredentials();
|
|
169
|
+
const oauthService = createMailOAuthService(microsoftProviderConfig({
|
|
170
|
+
clientId: credentials.clientId,
|
|
171
|
+
clientSecret: credentials.clientSecret,
|
|
172
|
+
services,
|
|
173
|
+
overrides: config.tokenEndpoint
|
|
174
|
+
? { tokenEndpoint: config.tokenEndpoint }
|
|
175
|
+
: undefined,
|
|
176
|
+
}));
|
|
177
|
+
const nonce = randomBytes(16).toString("hex");
|
|
178
|
+
const statePayload = {
|
|
179
|
+
accountConfigId,
|
|
180
|
+
nonce,
|
|
181
|
+
timestamp: Date.now(),
|
|
182
|
+
services,
|
|
183
|
+
};
|
|
184
|
+
const state = await signState(statePayload, credentials.clientSecret);
|
|
185
|
+
const authorizationUrl = oauthService.buildAuthorizationUrl({
|
|
186
|
+
redirectUri: config.redirectUri,
|
|
187
|
+
state,
|
|
188
|
+
loginHint: email,
|
|
189
|
+
});
|
|
190
|
+
// biome-ignore lint/plugin/no-logger-info: OAuth initiation is an audit-grade signal
|
|
191
|
+
logger.info({ accountConfigId, services }, "Microsoft OAuth start initiated");
|
|
192
|
+
return { authorizationUrl };
|
|
193
|
+
},
|
|
194
|
+
MicrosoftOAuthOperations_microsoftOAuthCallback: async (_context, ...args) => {
|
|
195
|
+
const event = args[0];
|
|
196
|
+
const webOrigin = getWebOrigin();
|
|
197
|
+
const qs = event.queryStringParameters ?? {};
|
|
198
|
+
// Marked raw so the response formatter forwards the Location header
|
|
199
|
+
// instead of serializing this object as a JSON body. Microsoft's browser
|
|
200
|
+
// redirect lands here, so a dropped Location is a blank page.
|
|
201
|
+
const redirect = (url) => rawApiResponse({
|
|
202
|
+
statusCode: 302,
|
|
203
|
+
headers: { Location: url },
|
|
204
|
+
body: "",
|
|
205
|
+
});
|
|
206
|
+
// If Microsoft returned an error, pass it through to the frontend
|
|
207
|
+
if (qs.error) {
|
|
208
|
+
const errorCode = encodeURIComponent(qs.error);
|
|
209
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=${errorCode}`);
|
|
210
|
+
}
|
|
211
|
+
const code = qs.code;
|
|
212
|
+
const state = qs.state;
|
|
213
|
+
if (!code || !state) {
|
|
214
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=missing_params`);
|
|
215
|
+
}
|
|
216
|
+
const credentials = await getMsOAuthCredentials().catch((err) => {
|
|
217
|
+
logger.error({
|
|
218
|
+
alert: "oauth_callback_failed",
|
|
219
|
+
reason: "config_error",
|
|
220
|
+
errorName: err?.name,
|
|
221
|
+
errorCode: err?.Code ??
|
|
222
|
+
err?.code,
|
|
223
|
+
error: inspect(err),
|
|
224
|
+
}, "MS OAuth callback: failed to load OAuth config");
|
|
225
|
+
return null;
|
|
226
|
+
});
|
|
227
|
+
if (credentials === null)
|
|
228
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=config_error`);
|
|
229
|
+
// Verify the HMAC-signed state
|
|
230
|
+
// A bad/expired/forged state is a security-relevant signal (CSRF
|
|
231
|
+
// attempt, clock skew, or a stale callback) — must not be swallowed
|
|
232
|
+
// silently. Warn so it's observable; still redirect the user cleanly.
|
|
233
|
+
const statePayload = await verifyState(state, credentials.clientSecret).catch((err) => {
|
|
234
|
+
logger.warn({
|
|
235
|
+
alert: "oauth_callback_failed",
|
|
236
|
+
reason: "invalid_state",
|
|
237
|
+
errorName: err?.name,
|
|
238
|
+
error: inspect(err),
|
|
239
|
+
}, "MS OAuth callback: state verification failed");
|
|
240
|
+
return null;
|
|
241
|
+
});
|
|
242
|
+
if (statePayload === null)
|
|
243
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=invalid_state`);
|
|
244
|
+
const { accountConfigId } = statePayload;
|
|
245
|
+
const [firstService] = orderServices(statePayload.services);
|
|
246
|
+
const config = getMsOAuthConfig();
|
|
247
|
+
const serviceFor = (service) => createMailOAuthService(microsoftProviderConfig({
|
|
248
|
+
clientId: credentials.clientId,
|
|
249
|
+
clientSecret: credentials.clientSecret,
|
|
250
|
+
services: [service],
|
|
251
|
+
overrides: config.tokenEndpoint
|
|
252
|
+
? { tokenEndpoint: config.tokenEndpoint }
|
|
253
|
+
: undefined,
|
|
254
|
+
}));
|
|
255
|
+
// Exchange the authorization code for tokens
|
|
256
|
+
const tokenSet = await serviceFor(firstService)
|
|
257
|
+
.exchangeCode(code, config.redirectUri)
|
|
258
|
+
.catch((err) => {
|
|
259
|
+
logger.error({ accountConfigId, error: inspect(err) }, "MS OAuth code exchange failed");
|
|
260
|
+
return null;
|
|
261
|
+
});
|
|
262
|
+
if (tokenSet === null)
|
|
263
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=exchange_failed`);
|
|
264
|
+
if (!tokenSet.refreshToken) {
|
|
265
|
+
logger.error({ accountConfigId }, "MS OAuth token exchange returned no refresh_token");
|
|
266
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=exchange_failed`);
|
|
267
|
+
}
|
|
268
|
+
// Extract the user's email from the ID token returned alongside the access
|
|
269
|
+
// token when openid+email scopes are requested.
|
|
270
|
+
//
|
|
271
|
+
// We prefer the ID token (idToken) because Outlook resource access tokens
|
|
272
|
+
// (IMAP.AccessAsUser.All, SMTP.Send) are opaque/non-JWT and cannot be
|
|
273
|
+
// decoded. The ID token is a standard OIDC token that always contains
|
|
274
|
+
// identity claims (preferred_username / email).
|
|
275
|
+
//
|
|
276
|
+
// Falls back to parsing the access token only in test/dev environments where
|
|
277
|
+
// idToken may not be present (e.g. custom token endpoints that don't issue
|
|
278
|
+
// OIDC tokens).
|
|
279
|
+
const tokenToParse = tokenSet.idToken ?? tokenSet.accessToken;
|
|
280
|
+
const claims = await parseJwtClaims(tokenToParse);
|
|
281
|
+
if (!claims) {
|
|
282
|
+
// A non-JWT or unparseable token. The empty-email guard below turns
|
|
283
|
+
// this into a user-facing missing_email redirect; log here so the parse
|
|
284
|
+
// failure itself is observable (e.g. an unexpected token shape).
|
|
285
|
+
logger.warn({
|
|
286
|
+
alert: "oauth_callback_failed",
|
|
287
|
+
reason: "jwt_parse_failed",
|
|
288
|
+
accountConfigId,
|
|
289
|
+
}, "MS OAuth callback: failed to parse identity token claims");
|
|
290
|
+
}
|
|
291
|
+
const email = claims
|
|
292
|
+
? (claims.preferred_username ??
|
|
293
|
+
claims.email ??
|
|
294
|
+
claims.upn)
|
|
295
|
+
: undefined;
|
|
296
|
+
if (!email) {
|
|
297
|
+
logger.error({ accountConfigId }, "MS OAuth: could not extract email from token claims");
|
|
298
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=missing_email`);
|
|
299
|
+
}
|
|
300
|
+
const { account, accountConfig, secrets } = await getClient();
|
|
301
|
+
// Reconnect when an active OAuth account already onboards this mailbox.
|
|
302
|
+
// Same natural key as the IMAP create guard (#635); the OAuth flow returns
|
|
303
|
+
// the existing account (token refresh) rather than rejecting, because a
|
|
304
|
+
// re-auth is the expected, idempotent path for OAuth.
|
|
305
|
+
const existingAccounts = (await account.listAllByAccountConfig(accountConfigId)).filter((a) => a.authType === AccountAuthType.OauthMicrosoft);
|
|
306
|
+
const existing = findActiveDuplicateMailbox(existingAccounts, {
|
|
307
|
+
imapHost: OUTLOOK_IMAP_HOST,
|
|
308
|
+
username: email,
|
|
309
|
+
});
|
|
310
|
+
const services = orderServices([
|
|
311
|
+
...statePayload.services,
|
|
312
|
+
...(existing?.syncedServices ?? []),
|
|
313
|
+
]);
|
|
314
|
+
const redemption = await redeemEachService(serviceFor, tokenSet.refreshToken, services.filter((service) => service !== firstService), accountConfigId);
|
|
315
|
+
if (redemption.kind === "refused" &&
|
|
316
|
+
redemption.reason === "scope_not_granted")
|
|
317
|
+
return redirect(scopeRefusalUrl(webOrigin, email, [redemption.service]));
|
|
318
|
+
if (redemption.kind === "refused")
|
|
319
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=${redemption.reason}`);
|
|
320
|
+
const grantedScopes = [
|
|
321
|
+
...new Set([...tokenSet.grantedScopes, ...redemption.grantedScopes]),
|
|
322
|
+
];
|
|
323
|
+
const grantedServices = microsoftServicesGranted(grantedScopes);
|
|
324
|
+
const missingServices = services.filter((service) => !grantedServices.includes(service));
|
|
325
|
+
if (missingServices.length > 0) {
|
|
326
|
+
logger.warn({
|
|
327
|
+
alert: "oauth_callback_failed",
|
|
328
|
+
reason: "scope_not_granted",
|
|
329
|
+
accountConfigId,
|
|
330
|
+
missingServices,
|
|
331
|
+
grantedScopes,
|
|
332
|
+
}, "MS OAuth callback: granted scopes lack a requested service");
|
|
333
|
+
return redirect(scopeRefusalUrl(webOrigin, email, missingServices));
|
|
334
|
+
}
|
|
335
|
+
// Ensure the account config row exists for this user
|
|
336
|
+
await ensureAccountConfig(accountConfig, accountConfigId);
|
|
337
|
+
// Encrypt the refresh token
|
|
338
|
+
const tokenPayload = await secrets.encrypt(redemption.refreshToken);
|
|
339
|
+
const oauthRefreshTokenHash = JSON.stringify(serializeEncryptedPayload(tokenPayload));
|
|
340
|
+
const oauthTokenUpdatedAt = Date.now();
|
|
341
|
+
let accountId;
|
|
342
|
+
if (existing) {
|
|
343
|
+
// Reconnect: update the stored token and clear any reauth_required state
|
|
344
|
+
const updated = await account.update(existing.accountId, {
|
|
345
|
+
oauthRefreshTokenHash,
|
|
346
|
+
oauthTokenUpdatedAt,
|
|
347
|
+
syncedServices: services,
|
|
348
|
+
grantedScopes,
|
|
349
|
+
connectionState: ConnectionState.NotAuthenticated,
|
|
350
|
+
}, ["lastError"]);
|
|
351
|
+
accountId = updated.accountId;
|
|
352
|
+
// biome-ignore lint/plugin/no-logger-info: OAuth reconnect is an audit-grade signal
|
|
353
|
+
logger.info({ accountConfigId, accountId }, "MS OAuth reconnect: refresh token updated");
|
|
354
|
+
}
|
|
355
|
+
else {
|
|
356
|
+
// First connect: create a new account
|
|
357
|
+
const newAccount = await account.create({
|
|
358
|
+
accountConfigId,
|
|
359
|
+
email,
|
|
360
|
+
username: email,
|
|
361
|
+
authType: AccountAuthType.OauthMicrosoft,
|
|
362
|
+
syncedServices: services,
|
|
363
|
+
grantedScopes,
|
|
364
|
+
oauthRefreshTokenHash,
|
|
365
|
+
oauthTokenUpdatedAt,
|
|
366
|
+
imapHost: OUTLOOK_IMAP_HOST,
|
|
367
|
+
imapPort: 993,
|
|
368
|
+
imapTls: true,
|
|
369
|
+
imapStartTls: false,
|
|
370
|
+
smtpEnabled: true,
|
|
371
|
+
smtpHost: "smtp.office365.com",
|
|
372
|
+
smtpPort: 587,
|
|
373
|
+
smtpTls: false,
|
|
374
|
+
smtpStartTls: true,
|
|
375
|
+
isActive: true,
|
|
376
|
+
connectionState: ConnectionState.NotAuthenticated,
|
|
377
|
+
});
|
|
378
|
+
accountId = newAccount.accountId;
|
|
379
|
+
// biome-ignore lint/plugin/no-logger-info: OAuth account creation is an audit-grade signal
|
|
380
|
+
logger.info({ accountConfigId, accountId }, "MS OAuth: new account created");
|
|
381
|
+
}
|
|
382
|
+
if (services.includes(AccountService.Mail)) {
|
|
383
|
+
await triggerAccountSyncSafe(accountId);
|
|
384
|
+
}
|
|
385
|
+
return redirect(`${webOrigin}/settings/accounts?connected=${encodeURIComponent(accountId)}`);
|
|
386
|
+
},
|
|
387
|
+
};
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { MutedFlag } from "@remit/api-openapi-types";
|
|
2
|
+
import type { AccountSettingItem, IAccountSettingRepository } from "@remit/data-ports";
|
|
3
|
+
export interface AccountOverrides {
|
|
4
|
+
displayName?: string;
|
|
5
|
+
muted?: MutedFlag;
|
|
6
|
+
composeLanguages?: string[];
|
|
7
|
+
}
|
|
8
|
+
export interface MailboxOverrides {
|
|
9
|
+
displayNameOverride?: string;
|
|
10
|
+
muted?: MutedFlag;
|
|
11
|
+
}
|
|
12
|
+
export declare const groupAccountOverrides: (settings: AccountSettingItem[]) => Map<string, AccountOverrides>;
|
|
13
|
+
/**
|
|
14
|
+
* Resolve one account's display-name/mute overrides by reading just its two
|
|
15
|
+
* composite rows. Used by the account create/update handlers.
|
|
16
|
+
*/
|
|
17
|
+
export declare const loadAccountOverrides: (accountSetting: IAccountSettingRepository, accountConfigId: string, accountId: string) => Promise<AccountOverrides>;
|
|
18
|
+
export declare const upsertAccountDisplayName: (accountSetting: IAccountSettingRepository, accountConfigId: string, accountId: string, displayName: string) => Promise<unknown>;
|
|
19
|
+
/**
|
|
20
|
+
* Replace the account's compose-language list. An empty array deletes the row:
|
|
21
|
+
* the client falls back to the browser's own languages when the setting is
|
|
22
|
+
* absent, and an account that offers no language at all has nothing to pick
|
|
23
|
+
* from (RFC 032: absence is "unset").
|
|
24
|
+
*/
|
|
25
|
+
export declare const writeAccountComposeLanguages: (accountSetting: IAccountSettingRepository, accountConfigId: string, accountId: string, languages: string[]) => Promise<unknown>;
|
|
26
|
+
/**
|
|
27
|
+
* Set or clear the account mute flag. A `MutedFlag` upserts the row; `null`
|
|
28
|
+
* deletes it (RFC 032: absence is "unset"). Mirrors the address-flag
|
|
29
|
+
* null→remove, object→set semantics.
|
|
30
|
+
*/
|
|
31
|
+
export declare const writeAccountMuted: (accountSetting: IAccountSettingRepository, accountConfigId: string, accountId: string, muted: MutedFlag | null) => Promise<unknown>;
|
|
32
|
+
export declare const groupMailboxOverrides: (settings: AccountSettingItem[]) => Map<string, MailboxOverrides>;
|
|
33
|
+
/**
|
|
34
|
+
* Load every mailbox's overrides for an account configuration in one query,
|
|
35
|
+
* grouped by mailboxId. listMailboxes uses this once to avoid an N+1 per mailbox.
|
|
36
|
+
*/
|
|
37
|
+
export declare const loadMailboxOverridesForConfig: (accountSetting: IAccountSettingRepository, accountConfigId: string) => Promise<Map<string, MailboxOverrides>>;
|
|
38
|
+
/**
|
|
39
|
+
* Resolve one mailbox's overrides by reading just its two composite rows.
|
|
40
|
+
* Used by getMailbox and the rename/PATCH handler.
|
|
41
|
+
*/
|
|
42
|
+
export declare const loadMailboxOverrides: (accountSetting: IAccountSettingRepository, accountConfigId: string, mailboxId: string) => Promise<MailboxOverrides>;
|
|
43
|
+
/**
|
|
44
|
+
* Apply a mailbox PATCH's override changes (displayNameOverride / muted) to
|
|
45
|
+
* AccountSetting rows. For each field: `null` deletes the row, a value upserts
|
|
46
|
+
* it, `undefined`/absent is a no-op — the same semantics the entity-backed
|
|
47
|
+
* version used. The canonical role a folder fills is written separately via
|
|
48
|
+
* `writeFolderRoleAppointment` (RFC 032 exclusive-folder-appointment, #976).
|
|
49
|
+
*/
|
|
50
|
+
export declare const applyMailboxOverrideChanges: (accountSetting: Pick<IAccountSettingRepository, "upsert" | "delete">, accountConfigId: string, mailboxId: string, changes: {
|
|
51
|
+
displayNameOverride?: string | null;
|
|
52
|
+
muted?: MutedFlag | null;
|
|
53
|
+
}) => Promise<void>;
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
import { baseSettingName, composeSettingName, SETTING_NAME_SEPARATOR, } from "@remit/data-ports/account-settings";
|
|
2
|
+
/**
|
|
3
|
+
* RFC 032 Tier 1: the per-account display name and mute flag, and the
|
|
4
|
+
* per-mailbox display-name override and mute flag, live in AccountSetting
|
|
5
|
+
* rows — not on the Account/Mailbox entities. They are stored as composite-named
|
|
6
|
+
* rows keyed by the target id (`AccountDisplayName#<accountId>`,
|
|
7
|
+
* `MailboxMuted#<mailboxId>`, …), so one `listByAccountConfig` query yields every
|
|
8
|
+
* target's overrides; readers group them by the `#<targetId>` suffix. This mirrors
|
|
9
|
+
* the signature helper (`account-signature.ts`). The per-folder role override
|
|
10
|
+
* this module used to carry is superseded by the per-account role map — see
|
|
11
|
+
* `folder-role-appointments.ts` (RFC 032 exclusive-folder-appointment, #976).
|
|
12
|
+
*/
|
|
13
|
+
const ACCOUNT_OVERRIDE_NAMES = {
|
|
14
|
+
displayName: "AccountDisplayName",
|
|
15
|
+
muted: "AccountMuted",
|
|
16
|
+
composeLanguages: "AccountComposeLanguages",
|
|
17
|
+
};
|
|
18
|
+
const MAILBOX_OVERRIDE_NAMES = {
|
|
19
|
+
displayName: "MailboxDisplayName",
|
|
20
|
+
muted: "MailboxMuted",
|
|
21
|
+
};
|
|
22
|
+
const stringValueOf = (item) => {
|
|
23
|
+
const { value } = item;
|
|
24
|
+
if (value.kind === "String")
|
|
25
|
+
return value.value;
|
|
26
|
+
return undefined;
|
|
27
|
+
};
|
|
28
|
+
const mutedValueOf = (item) => {
|
|
29
|
+
const { value } = item;
|
|
30
|
+
if (value.kind === "MutedFlag")
|
|
31
|
+
return value.value;
|
|
32
|
+
return undefined;
|
|
33
|
+
};
|
|
34
|
+
const stringListValueOf = (item) => {
|
|
35
|
+
const { value } = item;
|
|
36
|
+
if (value.kind === "StringList")
|
|
37
|
+
return value.value;
|
|
38
|
+
return undefined;
|
|
39
|
+
};
|
|
40
|
+
const targetIdOf = (name) => {
|
|
41
|
+
const idx = name.indexOf(SETTING_NAME_SEPARATOR);
|
|
42
|
+
if (idx === -1)
|
|
43
|
+
return undefined;
|
|
44
|
+
return name.slice(idx + SETTING_NAME_SEPARATOR.length) || undefined;
|
|
45
|
+
};
|
|
46
|
+
// ============================================
|
|
47
|
+
// Account overrides (displayName + muted)
|
|
48
|
+
// ============================================
|
|
49
|
+
export const groupAccountOverrides = (settings) => {
|
|
50
|
+
const byAccount = new Map();
|
|
51
|
+
for (const setting of settings) {
|
|
52
|
+
const accountId = targetIdOf(setting.name);
|
|
53
|
+
if (!accountId)
|
|
54
|
+
continue;
|
|
55
|
+
const base = baseSettingName(setting.name);
|
|
56
|
+
if (base === ACCOUNT_OVERRIDE_NAMES.displayName) {
|
|
57
|
+
const displayName = stringValueOf(setting);
|
|
58
|
+
if (displayName === undefined)
|
|
59
|
+
continue;
|
|
60
|
+
const current = byAccount.get(accountId) ?? {};
|
|
61
|
+
current.displayName = displayName;
|
|
62
|
+
byAccount.set(accountId, current);
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (base === ACCOUNT_OVERRIDE_NAMES.muted) {
|
|
66
|
+
const muted = mutedValueOf(setting);
|
|
67
|
+
if (muted === undefined)
|
|
68
|
+
continue;
|
|
69
|
+
const current = byAccount.get(accountId) ?? {};
|
|
70
|
+
current.muted = muted;
|
|
71
|
+
byAccount.set(accountId, current);
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (base === ACCOUNT_OVERRIDE_NAMES.composeLanguages) {
|
|
75
|
+
const composeLanguages = stringListValueOf(setting);
|
|
76
|
+
if (composeLanguages === undefined)
|
|
77
|
+
continue;
|
|
78
|
+
const current = byAccount.get(accountId) ?? {};
|
|
79
|
+
current.composeLanguages = composeLanguages;
|
|
80
|
+
byAccount.set(accountId, current);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return byAccount;
|
|
84
|
+
};
|
|
85
|
+
/**
|
|
86
|
+
* Resolve one account's display-name/mute overrides by reading just its two
|
|
87
|
+
* composite rows. Used by the account create/update handlers.
|
|
88
|
+
*/
|
|
89
|
+
export const loadAccountOverrides = async (accountSetting, accountConfigId, accountId) => {
|
|
90
|
+
const [displayName, muted, composeLanguages] = await Promise.all([
|
|
91
|
+
accountSetting.get(accountConfigId, composeSettingName(ACCOUNT_OVERRIDE_NAMES.displayName, accountId)),
|
|
92
|
+
accountSetting.get(accountConfigId, composeSettingName(ACCOUNT_OVERRIDE_NAMES.muted, accountId)),
|
|
93
|
+
accountSetting.get(accountConfigId, composeSettingName(ACCOUNT_OVERRIDE_NAMES.composeLanguages, accountId)),
|
|
94
|
+
]);
|
|
95
|
+
const overrides = {};
|
|
96
|
+
const displayNameValue = displayName ? stringValueOf(displayName) : undefined;
|
|
97
|
+
const mutedValue = muted ? mutedValueOf(muted) : undefined;
|
|
98
|
+
const languagesValue = composeLanguages
|
|
99
|
+
? stringListValueOf(composeLanguages)
|
|
100
|
+
: undefined;
|
|
101
|
+
if (displayNameValue !== undefined)
|
|
102
|
+
overrides.displayName = displayNameValue;
|
|
103
|
+
if (mutedValue !== undefined)
|
|
104
|
+
overrides.muted = mutedValue;
|
|
105
|
+
if (languagesValue !== undefined)
|
|
106
|
+
overrides.composeLanguages = languagesValue;
|
|
107
|
+
return overrides;
|
|
108
|
+
};
|
|
109
|
+
export const upsertAccountDisplayName = (accountSetting, accountConfigId, accountId, displayName) => accountSetting.upsert({
|
|
110
|
+
accountConfigId,
|
|
111
|
+
name: composeSettingName(ACCOUNT_OVERRIDE_NAMES.displayName, accountId),
|
|
112
|
+
value: { kind: "String", value: displayName },
|
|
113
|
+
});
|
|
114
|
+
/**
|
|
115
|
+
* Replace the account's compose-language list. An empty array deletes the row:
|
|
116
|
+
* the client falls back to the browser's own languages when the setting is
|
|
117
|
+
* absent, and an account that offers no language at all has nothing to pick
|
|
118
|
+
* from (RFC 032: absence is "unset").
|
|
119
|
+
*/
|
|
120
|
+
export const writeAccountComposeLanguages = (accountSetting, accountConfigId, accountId, languages) => {
|
|
121
|
+
const name = composeSettingName(ACCOUNT_OVERRIDE_NAMES.composeLanguages, accountId);
|
|
122
|
+
if (languages.length === 0) {
|
|
123
|
+
return accountSetting.delete(accountConfigId, name);
|
|
124
|
+
}
|
|
125
|
+
return accountSetting.upsert({
|
|
126
|
+
accountConfigId,
|
|
127
|
+
name,
|
|
128
|
+
value: { kind: "StringList", value: languages },
|
|
129
|
+
});
|
|
130
|
+
};
|
|
131
|
+
/**
|
|
132
|
+
* Set or clear the account mute flag. A `MutedFlag` upserts the row; `null`
|
|
133
|
+
* deletes it (RFC 032: absence is "unset"). Mirrors the address-flag
|
|
134
|
+
* null→remove, object→set semantics.
|
|
135
|
+
*/
|
|
136
|
+
export const writeAccountMuted = (accountSetting, accountConfigId, accountId, muted) => {
|
|
137
|
+
const name = composeSettingName(ACCOUNT_OVERRIDE_NAMES.muted, accountId);
|
|
138
|
+
if (muted === null) {
|
|
139
|
+
return accountSetting.delete(accountConfigId, name);
|
|
140
|
+
}
|
|
141
|
+
return accountSetting.upsert({
|
|
142
|
+
accountConfigId,
|
|
143
|
+
name,
|
|
144
|
+
value: { kind: "MutedFlag", value: muted },
|
|
145
|
+
});
|
|
146
|
+
};
|
|
147
|
+
// ============================================
|
|
148
|
+
// Mailbox overrides (displayNameOverride + muted)
|
|
149
|
+
// ============================================
|
|
150
|
+
export const groupMailboxOverrides = (settings) => {
|
|
151
|
+
const byMailbox = new Map();
|
|
152
|
+
for (const setting of settings) {
|
|
153
|
+
const mailboxId = targetIdOf(setting.name);
|
|
154
|
+
if (!mailboxId)
|
|
155
|
+
continue;
|
|
156
|
+
const base = baseSettingName(setting.name);
|
|
157
|
+
if (base === MAILBOX_OVERRIDE_NAMES.displayName) {
|
|
158
|
+
const displayName = stringValueOf(setting);
|
|
159
|
+
if (displayName === undefined)
|
|
160
|
+
continue;
|
|
161
|
+
const current = byMailbox.get(mailboxId) ?? {};
|
|
162
|
+
current.displayNameOverride = displayName;
|
|
163
|
+
byMailbox.set(mailboxId, current);
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
if (base === MAILBOX_OVERRIDE_NAMES.muted) {
|
|
167
|
+
const muted = mutedValueOf(setting);
|
|
168
|
+
if (muted === undefined)
|
|
169
|
+
continue;
|
|
170
|
+
const current = byMailbox.get(mailboxId) ?? {};
|
|
171
|
+
current.muted = muted;
|
|
172
|
+
byMailbox.set(mailboxId, current);
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
return byMailbox;
|
|
176
|
+
};
|
|
177
|
+
/**
|
|
178
|
+
* Load every mailbox's overrides for an account configuration in one query,
|
|
179
|
+
* grouped by mailboxId. listMailboxes uses this once to avoid an N+1 per mailbox.
|
|
180
|
+
*/
|
|
181
|
+
export const loadMailboxOverridesForConfig = async (accountSetting, accountConfigId) => {
|
|
182
|
+
const settings = await accountSetting.listByAccountConfig(accountConfigId);
|
|
183
|
+
return groupMailboxOverrides(settings);
|
|
184
|
+
};
|
|
185
|
+
/**
|
|
186
|
+
* Resolve one mailbox's overrides by reading just its two composite rows.
|
|
187
|
+
* Used by getMailbox and the rename/PATCH handler.
|
|
188
|
+
*/
|
|
189
|
+
export const loadMailboxOverrides = async (accountSetting, accountConfigId, mailboxId) => {
|
|
190
|
+
const [displayName, muted] = await Promise.all([
|
|
191
|
+
accountSetting.get(accountConfigId, composeSettingName(MAILBOX_OVERRIDE_NAMES.displayName, mailboxId)),
|
|
192
|
+
accountSetting.get(accountConfigId, composeSettingName(MAILBOX_OVERRIDE_NAMES.muted, mailboxId)),
|
|
193
|
+
]);
|
|
194
|
+
const overrides = {};
|
|
195
|
+
const displayNameValue = displayName ? stringValueOf(displayName) : undefined;
|
|
196
|
+
const mutedValue = muted ? mutedValueOf(muted) : undefined;
|
|
197
|
+
if (displayNameValue !== undefined)
|
|
198
|
+
overrides.displayNameOverride = displayNameValue;
|
|
199
|
+
if (mutedValue !== undefined)
|
|
200
|
+
overrides.muted = mutedValue;
|
|
201
|
+
return overrides;
|
|
202
|
+
};
|
|
203
|
+
/**
|
|
204
|
+
* Apply a mailbox PATCH's override changes (displayNameOverride / muted) to
|
|
205
|
+
* AccountSetting rows. For each field: `null` deletes the row, a value upserts
|
|
206
|
+
* it, `undefined`/absent is a no-op — the same semantics the entity-backed
|
|
207
|
+
* version used. The canonical role a folder fills is written separately via
|
|
208
|
+
* `writeFolderRoleAppointment` (RFC 032 exclusive-folder-appointment, #976).
|
|
209
|
+
*/
|
|
210
|
+
export const applyMailboxOverrideChanges = async (accountSetting, accountConfigId, mailboxId, changes) => {
|
|
211
|
+
const writes = [];
|
|
212
|
+
if (changes.displayNameOverride !== undefined) {
|
|
213
|
+
const name = composeSettingName(MAILBOX_OVERRIDE_NAMES.displayName, mailboxId);
|
|
214
|
+
writes.push(changes.displayNameOverride === null
|
|
215
|
+
? accountSetting.delete(accountConfigId, name)
|
|
216
|
+
: accountSetting.upsert({
|
|
217
|
+
accountConfigId,
|
|
218
|
+
name,
|
|
219
|
+
value: { kind: "String", value: changes.displayNameOverride },
|
|
220
|
+
}));
|
|
221
|
+
}
|
|
222
|
+
if (changes.muted !== undefined) {
|
|
223
|
+
const name = composeSettingName(MAILBOX_OVERRIDE_NAMES.muted, mailboxId);
|
|
224
|
+
writes.push(changes.muted === null
|
|
225
|
+
? accountSetting.delete(accountConfigId, name)
|
|
226
|
+
: accountSetting.upsert({
|
|
227
|
+
accountConfigId,
|
|
228
|
+
name,
|
|
229
|
+
value: { kind: "MutedFlag", value: changes.muted },
|
|
230
|
+
}));
|
|
231
|
+
}
|
|
232
|
+
await Promise.all(writes);
|
|
233
|
+
};
|