@remit/backend 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.env.test +7 -0
- package/dev-server/content-auth.test.ts +113 -0
- package/dev-server/content-auth.ts +54 -0
- package/dev-server/content-handler.test.ts +105 -0
- package/dev-server/content-handler.ts +79 -0
- package/dev-server/content-path.test.ts +37 -0
- package/dev-server/content-path.ts +27 -0
- package/dev-server/cors.test.ts +48 -0
- package/dev-server/cors.ts +25 -0
- package/dev-server/lambda-helpers.ts +69 -0
- package/dev-server/server.ts +289 -0
- package/package.json +82 -0
- package/src/auth.ts +92 -0
- package/src/config/msoauth.ts +60 -0
- package/src/data-backend.test.ts +25 -0
- package/src/data-backend.ts +20 -0
- package/src/derive/autoMoved.ts +28 -0
- package/src/derive/contentSignature.test.ts +153 -0
- package/src/derive/contentSignature.ts +139 -0
- package/src/derive/contentUrl.test.ts +156 -0
- package/src/derive/contentUrl.ts +70 -0
- package/src/derive/enrichThreadRows.ts +155 -0
- package/src/derive/filterThreadCriteria.test.ts +119 -0
- package/src/derive/filterThreadCriteria.ts +60 -0
- package/src/derive/pendingMoveCounts.ts +90 -0
- package/src/derive/senderTrust.test.ts +67 -0
- package/src/derive/senderTrust.ts +23 -0
- package/src/error.ts +55 -0
- package/src/handlers/account-guards.ts +137 -0
- package/src/handlers/account-oauth.test.ts +383 -0
- package/src/handlers/account-oauth.ts +452 -0
- package/src/handlers/account-overrides.test.ts +69 -0
- package/src/handlers/account-overrides.ts +286 -0
- package/src/handlers/account-ownership.ts +25 -0
- package/src/handlers/account-signature.ts +129 -0
- package/src/handlers/account.ts +524 -0
- package/src/handlers/address.ts +136 -0
- package/src/handlers/config.test.ts +184 -0
- package/src/handlers/config.ts +219 -0
- package/src/handlers/ensure-account-config.ts +30 -0
- package/src/handlers/filter.ts +294 -0
- package/src/handlers/folder-role-appointments.test.ts +250 -0
- package/src/handlers/folder-role-appointments.ts +272 -0
- package/src/handlers/folder-role.ts +76 -0
- package/src/handlers/index.ts +48 -0
- package/src/handlers/mailbox.ts +411 -0
- package/src/handlers/me.ts +190 -0
- package/src/handlers/message.ts +886 -0
- package/src/handlers/organize.test.ts +43 -0
- package/src/handlers/organize.ts +196 -0
- package/src/handlers/outbox.ts +218 -0
- package/src/handlers/search.test.ts +182 -0
- package/src/handlers/search.ts +105 -0
- package/src/handlers/sync-progress.test.ts +158 -0
- package/src/handlers/sync-progress.ts +64 -0
- package/src/handlers/sync.test.ts +146 -0
- package/src/handlers/sync.ts +119 -0
- package/src/handlers/thread.ts +361 -0
- package/src/handlers/unified-threads.ts +196 -0
- package/src/handlers/vip-suggestions.ts +21 -0
- package/src/index.ts +170 -0
- package/src/json.ts +11 -0
- package/src/jwt-auth.test.ts +89 -0
- package/src/jwt-auth.ts +95 -0
- package/src/request-context.test.ts +61 -0
- package/src/request-context.ts +29 -0
- package/src/request.ts +10 -0
- package/src/response.test.ts +107 -0
- package/src/response.ts +80 -0
- package/src/service/compose-postgres.ts +72 -0
- package/src/service/compose-sqlite.ts +80 -0
- package/src/service/create-remit-client.ts +358 -0
- package/src/service/dynamodb.test.ts +100 -0
- package/src/service/dynamodb.ts +58 -0
- package/src/service/filter.ts +55 -0
- package/src/service/fire-and-forget.test.ts +126 -0
- package/src/service/fire-and-forget.ts +79 -0
- package/src/service/localhost-env-config.test.ts +40 -0
- package/src/service/organize.test.ts +384 -0
- package/src/service/organize.ts +354 -0
- package/src/service/semantic-capability.test.ts +64 -0
- package/src/service/semantic-capability.ts +62 -0
- package/src/service/sqs.ts +4 -0
- package/src/service/trigger-sync.test.ts +211 -0
- package/src/service/trigger-sync.ts +102 -0
- package/src/types.ts +161 -0
- package/tsconfig.json +7 -0
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { inspect } from "node:util";
|
|
3
|
+
import {
|
|
4
|
+
GetSecretValueCommand,
|
|
5
|
+
SecretsManagerClient,
|
|
6
|
+
} from "@aws-sdk/client-secrets-manager";
|
|
7
|
+
import { AccountAuthType, ConnectionState } from "@remit/domain-enums";
|
|
8
|
+
import { logger } from "@remit/logger-lambda";
|
|
9
|
+
import {
|
|
10
|
+
createMailOAuthService,
|
|
11
|
+
microsoftProviderConfig,
|
|
12
|
+
} from "@remit/mail-oauth-service";
|
|
13
|
+
import { serializeEncryptedPayload } from "@remit/secrets-service";
|
|
14
|
+
import type { APIGatewayProxyEvent, APIGatewayProxyResult } from "aws-lambda";
|
|
15
|
+
import type { Context } from "openapi-backend";
|
|
16
|
+
import { getAccountConfigIdFromEvent } from "../auth.js";
|
|
17
|
+
import { getMsOAuthConfig } from "../config/msoauth.js";
|
|
18
|
+
import { safeJsonParse } from "../json.js";
|
|
19
|
+
import { getClient } from "../service/dynamodb.js";
|
|
20
|
+
import type { MicrosoftOAuthOperationIds, OperationHandler } from "../types.js";
|
|
21
|
+
import { triggerAccountSyncSafe } from "./account.js";
|
|
22
|
+
import { findActiveDuplicateMailbox } from "./account-guards.js";
|
|
23
|
+
import { ensureAccountConfig } from "./ensure-account-config.js";
|
|
24
|
+
|
|
25
|
+
const OUTLOOK_IMAP_HOST = "outlook.office365.com";
|
|
26
|
+
|
|
27
|
+
// ─── HMAC state signing ──────────────────────────────────────────────────────
|
|
28
|
+
|
|
29
|
+
export interface OAuthState {
|
|
30
|
+
accountConfigId: string;
|
|
31
|
+
nonce: string;
|
|
32
|
+
timestamp: number;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const STATE_TTL_MS = 10 * 60 * 1000; // 10 minutes
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Derive a signing key from the client secret, namespaced to avoid reuse.
|
|
39
|
+
* The key is HMAC-SHA256("oauth-state-signing:" + clientSecret).
|
|
40
|
+
*/
|
|
41
|
+
function deriveSigningKey(clientSecret: string): Buffer {
|
|
42
|
+
return createHmac("sha256", `oauth-state-signing:${clientSecret}`)
|
|
43
|
+
.update("")
|
|
44
|
+
.digest();
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function base64urlEncode(buf: Buffer): string {
|
|
48
|
+
return buf.toString("base64url");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function base64urlDecode(str: string): Buffer {
|
|
52
|
+
return Buffer.from(str, "base64url");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function signState(
|
|
56
|
+
payload: OAuthState,
|
|
57
|
+
clientSecret: string,
|
|
58
|
+
): Promise<string> {
|
|
59
|
+
const key = deriveSigningKey(clientSecret);
|
|
60
|
+
const payloadBuf = Buffer.from(JSON.stringify(payload), "utf8");
|
|
61
|
+
const payloadEncoded = base64urlEncode(payloadBuf);
|
|
62
|
+
const sig = createHmac("sha256", key).update(payloadEncoded).digest();
|
|
63
|
+
const sigEncoded = base64urlEncode(sig);
|
|
64
|
+
return `${payloadEncoded}.${sigEncoded}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export async function verifyState(
|
|
68
|
+
state: string,
|
|
69
|
+
clientSecret: string,
|
|
70
|
+
): Promise<OAuthState> {
|
|
71
|
+
const dotIndex = state.lastIndexOf(".");
|
|
72
|
+
if (dotIndex < 0) throw new Error("Malformed state: missing dot separator");
|
|
73
|
+
|
|
74
|
+
const payloadEncoded = state.slice(0, dotIndex);
|
|
75
|
+
const sigEncoded = state.slice(dotIndex + 1);
|
|
76
|
+
|
|
77
|
+
const key = deriveSigningKey(clientSecret);
|
|
78
|
+
const expectedSig = createHmac("sha256", key).update(payloadEncoded).digest();
|
|
79
|
+
const actualSig = base64urlDecode(sigEncoded);
|
|
80
|
+
|
|
81
|
+
if (
|
|
82
|
+
actualSig.length !== expectedSig.length ||
|
|
83
|
+
!timingSafeEqual(actualSig, expectedSig)
|
|
84
|
+
) {
|
|
85
|
+
throw new Error("State signature verification failed");
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const payload = JSON.parse(
|
|
89
|
+
base64urlDecode(payloadEncoded).toString("utf8"),
|
|
90
|
+
) as OAuthState;
|
|
91
|
+
|
|
92
|
+
if (Date.now() - payload.timestamp > STATE_TTL_MS) {
|
|
93
|
+
throw new Error("State has expired");
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return payload;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// ─── JWT claims parsing ──────────────────────────────────────────────────────
|
|
100
|
+
|
|
101
|
+
export async function parseJwtClaims(
|
|
102
|
+
token: string,
|
|
103
|
+
): Promise<Record<string, unknown> | null> {
|
|
104
|
+
const parts = token.split(".");
|
|
105
|
+
if (parts.length !== 3) return null;
|
|
106
|
+
return safeJsonParse<Record<string, unknown>>(
|
|
107
|
+
Buffer.from(parts[1], "base64url").toString("utf8"),
|
|
108
|
+
).catch(() => null);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// ─── Secrets Manager / config helpers ───────────────────────────────────────
|
|
112
|
+
|
|
113
|
+
interface MsOAuthCredentials {
|
|
114
|
+
clientId: string;
|
|
115
|
+
clientSecret: string;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
let smClient: SecretsManagerClient | null = null;
|
|
119
|
+
|
|
120
|
+
function getSecretsManagerClient(): SecretsManagerClient {
|
|
121
|
+
if (!smClient) smClient = new SecretsManagerClient({});
|
|
122
|
+
return smClient;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function getMsOAuthCredentials(): Promise<MsOAuthCredentials> {
|
|
126
|
+
const config = getMsOAuthConfig();
|
|
127
|
+
|
|
128
|
+
// Local dev: use env vars directly
|
|
129
|
+
if (config.clientId && config.clientSecret) {
|
|
130
|
+
return { clientId: config.clientId, clientSecret: config.clientSecret };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
// Production: fetch from Secrets Manager
|
|
134
|
+
if (!config.secretArn) {
|
|
135
|
+
throw new Error(
|
|
136
|
+
"MSOAUTH_SECRET_ARN is required when MSOAUTH_CLIENT_ID/MSOAUTH_CLIENT_SECRET are not set",
|
|
137
|
+
);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const sm = getSecretsManagerClient();
|
|
141
|
+
const result = await sm.send(
|
|
142
|
+
new GetSecretValueCommand({ SecretId: config.secretArn }),
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
if (!result.SecretString) {
|
|
146
|
+
throw new Error("MSOAUTH secret has no SecretString value");
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const parsed = JSON.parse(result.SecretString) as MsOAuthCredentials;
|
|
150
|
+
if (!parsed.clientId || !parsed.clientSecret) {
|
|
151
|
+
throw new Error(
|
|
152
|
+
"MSOAUTH secret must contain clientId and clientSecret fields",
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return parsed;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ─── Web origin helper ───────────────────────────────────────────────────────
|
|
160
|
+
|
|
161
|
+
export function getWebOrigin(): string {
|
|
162
|
+
const raw = process.env.CORS_ALLOWED_ORIGINS ?? "";
|
|
163
|
+
const origins = raw
|
|
164
|
+
.split(",")
|
|
165
|
+
.map((o) => o.trim())
|
|
166
|
+
.filter(Boolean);
|
|
167
|
+
|
|
168
|
+
// Prefer the first HTTPS origin (production frontend)
|
|
169
|
+
const httpsOrigin = origins.find((o) => o.startsWith("https://"));
|
|
170
|
+
return httpsOrigin ?? origins[0] ?? "https://localhost:3000";
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// ─── Handlers ────────────────────────────────────────────────────────────────
|
|
174
|
+
|
|
175
|
+
export const MicrosoftOAuthOperations: Record<
|
|
176
|
+
MicrosoftOAuthOperationIds,
|
|
177
|
+
OperationHandler<MicrosoftOAuthOperationIds>
|
|
178
|
+
> = {
|
|
179
|
+
MicrosoftOAuthOperations_microsoftOAuthStart: async (
|
|
180
|
+
_context: Context,
|
|
181
|
+
...args: unknown[]
|
|
182
|
+
): Promise<{ authorizationUrl: string }> => {
|
|
183
|
+
const event = args[0] as APIGatewayProxyEvent;
|
|
184
|
+
const accountConfigId = getAccountConfigIdFromEvent(event);
|
|
185
|
+
|
|
186
|
+
const input = JSON.parse(event.body ?? "{}") as { email?: string };
|
|
187
|
+
const email = typeof input.email === "string" ? input.email : undefined;
|
|
188
|
+
|
|
189
|
+
const config = getMsOAuthConfig();
|
|
190
|
+
const credentials = await getMsOAuthCredentials();
|
|
191
|
+
|
|
192
|
+
const oauthService = createMailOAuthService(
|
|
193
|
+
microsoftProviderConfig({
|
|
194
|
+
clientId: credentials.clientId,
|
|
195
|
+
clientSecret: credentials.clientSecret,
|
|
196
|
+
overrides: config.tokenEndpoint
|
|
197
|
+
? { tokenEndpoint: config.tokenEndpoint }
|
|
198
|
+
: undefined,
|
|
199
|
+
}),
|
|
200
|
+
);
|
|
201
|
+
|
|
202
|
+
const nonce = randomBytes(16).toString("hex");
|
|
203
|
+
const statePayload: OAuthState = {
|
|
204
|
+
accountConfigId,
|
|
205
|
+
nonce,
|
|
206
|
+
timestamp: Date.now(),
|
|
207
|
+
};
|
|
208
|
+
|
|
209
|
+
const state = await signState(statePayload, credentials.clientSecret);
|
|
210
|
+
|
|
211
|
+
const authorizationUrl = oauthService.buildAuthorizationUrl({
|
|
212
|
+
redirectUri: config.redirectUri,
|
|
213
|
+
state,
|
|
214
|
+
loginHint: email,
|
|
215
|
+
});
|
|
216
|
+
|
|
217
|
+
// biome-ignore lint/plugin/no-logger-info: OAuth initiation is an audit-grade signal
|
|
218
|
+
logger.info({ accountConfigId }, "Microsoft OAuth start initiated");
|
|
219
|
+
|
|
220
|
+
return { authorizationUrl };
|
|
221
|
+
},
|
|
222
|
+
|
|
223
|
+
MicrosoftOAuthOperations_microsoftOAuthCallback: async (
|
|
224
|
+
_context: Context,
|
|
225
|
+
...args: unknown[]
|
|
226
|
+
): Promise<APIGatewayProxyResult> => {
|
|
227
|
+
const event = args[0] as APIGatewayProxyEvent;
|
|
228
|
+
const webOrigin = getWebOrigin();
|
|
229
|
+
const qs = event.queryStringParameters ?? {};
|
|
230
|
+
|
|
231
|
+
const redirect = (url: string): APIGatewayProxyResult => ({
|
|
232
|
+
statusCode: 302,
|
|
233
|
+
headers: { Location: url },
|
|
234
|
+
body: "",
|
|
235
|
+
});
|
|
236
|
+
|
|
237
|
+
// If Microsoft returned an error, pass it through to the frontend
|
|
238
|
+
if (qs.error) {
|
|
239
|
+
const errorCode = encodeURIComponent(qs.error);
|
|
240
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=${errorCode}`);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
const code = qs.code;
|
|
244
|
+
const state = qs.state;
|
|
245
|
+
|
|
246
|
+
if (!code || !state) {
|
|
247
|
+
return redirect(
|
|
248
|
+
`${webOrigin}/settings/accounts?oauthError=missing_params`,
|
|
249
|
+
);
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
const credentials = await getMsOAuthCredentials().catch((err: unknown) => {
|
|
253
|
+
logger.error(
|
|
254
|
+
{
|
|
255
|
+
alert: "oauth_callback_failed",
|
|
256
|
+
reason: "config_error",
|
|
257
|
+
errorName: (err as { name?: string })?.name,
|
|
258
|
+
errorCode:
|
|
259
|
+
(err as { Code?: string })?.Code ??
|
|
260
|
+
(err as { code?: string })?.code,
|
|
261
|
+
error: inspect(err),
|
|
262
|
+
},
|
|
263
|
+
"MS OAuth callback: failed to load OAuth config",
|
|
264
|
+
);
|
|
265
|
+
return null;
|
|
266
|
+
});
|
|
267
|
+
if (credentials === null)
|
|
268
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=config_error`);
|
|
269
|
+
|
|
270
|
+
// Verify the HMAC-signed state
|
|
271
|
+
// A bad/expired/forged state is a security-relevant signal (CSRF
|
|
272
|
+
// attempt, clock skew, or a stale callback) — must not be swallowed
|
|
273
|
+
// silently. Warn so it's observable; still redirect the user cleanly.
|
|
274
|
+
const statePayload = await verifyState(
|
|
275
|
+
state,
|
|
276
|
+
credentials.clientSecret,
|
|
277
|
+
).catch((err: unknown) => {
|
|
278
|
+
logger.warn(
|
|
279
|
+
{
|
|
280
|
+
alert: "oauth_callback_failed",
|
|
281
|
+
reason: "invalid_state",
|
|
282
|
+
errorName: (err as { name?: string })?.name,
|
|
283
|
+
error: inspect(err),
|
|
284
|
+
},
|
|
285
|
+
"MS OAuth callback: state verification failed",
|
|
286
|
+
);
|
|
287
|
+
return null;
|
|
288
|
+
});
|
|
289
|
+
if (statePayload === null)
|
|
290
|
+
return redirect(
|
|
291
|
+
`${webOrigin}/settings/accounts?oauthError=invalid_state`,
|
|
292
|
+
);
|
|
293
|
+
|
|
294
|
+
const { accountConfigId } = statePayload;
|
|
295
|
+
|
|
296
|
+
const config = getMsOAuthConfig();
|
|
297
|
+
const oauthService = createMailOAuthService(
|
|
298
|
+
microsoftProviderConfig({
|
|
299
|
+
clientId: credentials.clientId,
|
|
300
|
+
clientSecret: credentials.clientSecret,
|
|
301
|
+
overrides: config.tokenEndpoint
|
|
302
|
+
? { tokenEndpoint: config.tokenEndpoint }
|
|
303
|
+
: undefined,
|
|
304
|
+
}),
|
|
305
|
+
);
|
|
306
|
+
|
|
307
|
+
// Exchange the authorization code for tokens
|
|
308
|
+
const tokenSet = await oauthService
|
|
309
|
+
.exchangeCode(code, config.redirectUri)
|
|
310
|
+
.catch((err: unknown) => {
|
|
311
|
+
logger.error(
|
|
312
|
+
{ accountConfigId, error: inspect(err) },
|
|
313
|
+
"MS OAuth code exchange failed",
|
|
314
|
+
);
|
|
315
|
+
return null;
|
|
316
|
+
});
|
|
317
|
+
if (tokenSet === null)
|
|
318
|
+
return redirect(
|
|
319
|
+
`${webOrigin}/settings/accounts?oauthError=exchange_failed`,
|
|
320
|
+
);
|
|
321
|
+
|
|
322
|
+
if (!tokenSet.refreshToken) {
|
|
323
|
+
logger.error(
|
|
324
|
+
{ accountConfigId },
|
|
325
|
+
"MS OAuth token exchange returned no refresh_token",
|
|
326
|
+
);
|
|
327
|
+
return redirect(
|
|
328
|
+
`${webOrigin}/settings/accounts?oauthError=exchange_failed`,
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Extract the user's email from the ID token returned alongside the access
|
|
333
|
+
// token when openid+email scopes are requested.
|
|
334
|
+
//
|
|
335
|
+
// We prefer the ID token (idToken) because Outlook resource access tokens
|
|
336
|
+
// (IMAP.AccessAsUser.All, SMTP.Send) are opaque/non-JWT and cannot be
|
|
337
|
+
// decoded. The ID token is a standard OIDC token that always contains
|
|
338
|
+
// identity claims (preferred_username / email).
|
|
339
|
+
//
|
|
340
|
+
// Falls back to parsing the access token only in test/dev environments where
|
|
341
|
+
// idToken may not be present (e.g. custom token endpoints that don't issue
|
|
342
|
+
// OIDC tokens).
|
|
343
|
+
const tokenToParse = tokenSet.idToken ?? tokenSet.accessToken;
|
|
344
|
+
const claims = await parseJwtClaims(tokenToParse);
|
|
345
|
+
if (!claims) {
|
|
346
|
+
// A non-JWT or unparseable token. The empty-email guard below turns
|
|
347
|
+
// this into a user-facing missing_email redirect; log here so the parse
|
|
348
|
+
// failure itself is observable (e.g. an unexpected token shape).
|
|
349
|
+
logger.warn(
|
|
350
|
+
{
|
|
351
|
+
alert: "oauth_callback_failed",
|
|
352
|
+
reason: "jwt_parse_failed",
|
|
353
|
+
accountConfigId,
|
|
354
|
+
},
|
|
355
|
+
"MS OAuth callback: failed to parse identity token claims",
|
|
356
|
+
);
|
|
357
|
+
}
|
|
358
|
+
const email = claims
|
|
359
|
+
? ((claims.preferred_username as string | undefined) ??
|
|
360
|
+
(claims.email as string | undefined) ??
|
|
361
|
+
(claims.upn as string | undefined))
|
|
362
|
+
: undefined;
|
|
363
|
+
|
|
364
|
+
if (!email) {
|
|
365
|
+
logger.error(
|
|
366
|
+
{ accountConfigId },
|
|
367
|
+
"MS OAuth: could not extract email from token claims",
|
|
368
|
+
);
|
|
369
|
+
return redirect(
|
|
370
|
+
`${webOrigin}/settings/accounts?oauthError=missing_email`,
|
|
371
|
+
);
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
const { account, accountConfig, secrets } = await getClient();
|
|
375
|
+
|
|
376
|
+
// Ensure the account config row exists for this user
|
|
377
|
+
await ensureAccountConfig(accountConfig, accountConfigId);
|
|
378
|
+
|
|
379
|
+
// Encrypt the refresh token
|
|
380
|
+
const tokenPayload = await secrets.encrypt(tokenSet.refreshToken);
|
|
381
|
+
const oauthRefreshTokenHash = JSON.stringify(
|
|
382
|
+
serializeEncryptedPayload(tokenPayload),
|
|
383
|
+
);
|
|
384
|
+
const oauthTokenUpdatedAt = Date.now();
|
|
385
|
+
|
|
386
|
+
// Reconnect when an active OAuth account already onboards this mailbox.
|
|
387
|
+
// Same natural key as the IMAP create guard (#635); the OAuth flow returns
|
|
388
|
+
// the existing account (token refresh) rather than rejecting, because a
|
|
389
|
+
// re-auth is the expected, idempotent path for OAuth.
|
|
390
|
+
const existingAccounts = (
|
|
391
|
+
await account.listAllByAccountConfig(accountConfigId)
|
|
392
|
+
).filter((a) => a.authType === AccountAuthType.OauthMicrosoft);
|
|
393
|
+
const existing = findActiveDuplicateMailbox(existingAccounts, {
|
|
394
|
+
imapHost: OUTLOOK_IMAP_HOST,
|
|
395
|
+
username: email,
|
|
396
|
+
});
|
|
397
|
+
|
|
398
|
+
let accountId: string;
|
|
399
|
+
|
|
400
|
+
if (existing) {
|
|
401
|
+
// Reconnect: update the stored token and clear any reauth_required state
|
|
402
|
+
const updated = await account.update(
|
|
403
|
+
existing.accountId,
|
|
404
|
+
{
|
|
405
|
+
oauthRefreshTokenHash,
|
|
406
|
+
oauthTokenUpdatedAt,
|
|
407
|
+
connectionState: ConnectionState.NotAuthenticated,
|
|
408
|
+
},
|
|
409
|
+
["lastError"] as never,
|
|
410
|
+
);
|
|
411
|
+
accountId = updated.accountId;
|
|
412
|
+
// biome-ignore lint/plugin/no-logger-info: OAuth reconnect is an audit-grade signal
|
|
413
|
+
logger.info(
|
|
414
|
+
{ accountConfigId, accountId },
|
|
415
|
+
"MS OAuth reconnect: refresh token updated",
|
|
416
|
+
);
|
|
417
|
+
} else {
|
|
418
|
+
// First connect: create a new account
|
|
419
|
+
const newAccount = await account.create({
|
|
420
|
+
accountConfigId,
|
|
421
|
+
email,
|
|
422
|
+
username: email,
|
|
423
|
+
authType: AccountAuthType.OauthMicrosoft,
|
|
424
|
+
oauthRefreshTokenHash,
|
|
425
|
+
oauthTokenUpdatedAt,
|
|
426
|
+
imapHost: OUTLOOK_IMAP_HOST,
|
|
427
|
+
imapPort: 993,
|
|
428
|
+
imapTls: true,
|
|
429
|
+
imapStartTls: false,
|
|
430
|
+
smtpEnabled: true,
|
|
431
|
+
smtpHost: "smtp.office365.com",
|
|
432
|
+
smtpPort: 587,
|
|
433
|
+
smtpTls: false,
|
|
434
|
+
smtpStartTls: true,
|
|
435
|
+
isActive: true,
|
|
436
|
+
connectionState: ConnectionState.NotAuthenticated,
|
|
437
|
+
});
|
|
438
|
+
accountId = newAccount.accountId;
|
|
439
|
+
// biome-ignore lint/plugin/no-logger-info: OAuth account creation is an audit-grade signal
|
|
440
|
+
logger.info(
|
|
441
|
+
{ accountConfigId, accountId },
|
|
442
|
+
"MS OAuth: new account created",
|
|
443
|
+
);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
await triggerAccountSyncSafe(accountId);
|
|
447
|
+
|
|
448
|
+
return redirect(
|
|
449
|
+
`${webOrigin}/settings/accounts?connected=${encodeURIComponent(accountId)}`,
|
|
450
|
+
);
|
|
451
|
+
},
|
|
452
|
+
};
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import assert from "node:assert/strict";
|
|
2
|
+
import { describe, it } from "node:test";
|
|
3
|
+
import type { AccountSettingItem } from "@remit/data-ports";
|
|
4
|
+
import {
|
|
5
|
+
groupAccountOverrides,
|
|
6
|
+
groupMailboxOverrides,
|
|
7
|
+
} from "./account-overrides.js";
|
|
8
|
+
|
|
9
|
+
const setting = (
|
|
10
|
+
name: string,
|
|
11
|
+
value: AccountSettingItem["value"],
|
|
12
|
+
): AccountSettingItem =>
|
|
13
|
+
({
|
|
14
|
+
accountSettingId: `s-${name}`,
|
|
15
|
+
accountConfigId: "cfg-1",
|
|
16
|
+
name,
|
|
17
|
+
value,
|
|
18
|
+
createdAt: 0,
|
|
19
|
+
updatedAt: 0,
|
|
20
|
+
}) as AccountSettingItem;
|
|
21
|
+
|
|
22
|
+
const stringSetting = (name: string, value: string): AccountSettingItem =>
|
|
23
|
+
setting(name, { kind: "String", value });
|
|
24
|
+
|
|
25
|
+
describe("groupAccountOverrides", () => {
|
|
26
|
+
it("groups displayName and muted overrides by accountId", () => {
|
|
27
|
+
const settings = [
|
|
28
|
+
stringSetting("AccountDisplayName#acc-1", "Alice"),
|
|
29
|
+
stringSetting("AccountDisplayName#acc-2", "Bob"),
|
|
30
|
+
];
|
|
31
|
+
const grouped = groupAccountOverrides(settings);
|
|
32
|
+
assert.equal(grouped.get("acc-1")?.displayName, "Alice");
|
|
33
|
+
assert.equal(grouped.get("acc-2")?.displayName, "Bob");
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
it("ignores a leftover MailboxRole#<mailboxId> row instead of throwing", () => {
|
|
37
|
+
// Leftover rows from the #963/#964 backfill (superseded by
|
|
38
|
+
// FolderRoleAppointment, RFC 032 exclusive-folder-appointment #976) must
|
|
39
|
+
// not make GET /config throw — groupAccountOverrides only reacts to
|
|
40
|
+
// AccountDisplayName/AccountMuted bases, so this row is simply skipped.
|
|
41
|
+
const settings = [
|
|
42
|
+
stringSetting("AccountDisplayName#acc-1", "Alice"),
|
|
43
|
+
stringSetting("MailboxRole#mb-legacy", "custom"),
|
|
44
|
+
];
|
|
45
|
+
assert.doesNotThrow(() => groupAccountOverrides(settings));
|
|
46
|
+
const grouped = groupAccountOverrides(settings);
|
|
47
|
+
assert.equal(grouped.get("acc-1")?.displayName, "Alice");
|
|
48
|
+
assert.equal(grouped.size, 1);
|
|
49
|
+
});
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
describe("groupMailboxOverrides", () => {
|
|
53
|
+
it("groups displayNameOverride and muted overrides by mailboxId", () => {
|
|
54
|
+
const settings = [stringSetting("MailboxDisplayName#mb-1", "Work")];
|
|
55
|
+
const grouped = groupMailboxOverrides(settings);
|
|
56
|
+
assert.equal(grouped.get("mb-1")?.displayNameOverride, "Work");
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
it("ignores a leftover MailboxRole#<mailboxId> row instead of throwing", () => {
|
|
60
|
+
const settings = [
|
|
61
|
+
stringSetting("MailboxDisplayName#mb-1", "Work"),
|
|
62
|
+
stringSetting("MailboxRole#mb-legacy", "custom"),
|
|
63
|
+
];
|
|
64
|
+
assert.doesNotThrow(() => groupMailboxOverrides(settings));
|
|
65
|
+
const grouped = groupMailboxOverrides(settings);
|
|
66
|
+
assert.equal(grouped.get("mb-1")?.displayNameOverride, "Work");
|
|
67
|
+
assert.equal(grouped.size, 1);
|
|
68
|
+
});
|
|
69
|
+
});
|