@remit/backend 0.0.143 → 0.0.145
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 +5 -0
- package/dist/src/api.js +73 -0
- package/dist/src/auth.d.ts +24 -0
- package/dist/src/auth.js +81 -0
- package/dist/src/config/api-config.d.ts +20 -0
- package/dist/src/config/api-config.js +1 -0
- package/dist/src/config/from-env.d.ts +2 -0
- package/dist/src/config/from-env.js +65 -0
- package/dist/src/config/msoauth-secrets-manager.d.ts +2 -0
- package/dist/src/config/msoauth-secrets-manager.js +28 -0
- package/dist/src/config/msoauth.d.ts +19 -0
- package/dist/src/config/msoauth.js +6 -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 +40 -0
- package/{src/derive/contentSignature.ts → dist/src/derive/contentSignature.js} +23 -77
- package/dist/src/derive/contentUrl.d.ts +33 -0
- package/dist/src/derive/contentUrl.js +27 -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 +15 -0
- package/dist/src/handlers/account-oauth.js +334 -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 +7 -0
- package/dist/src/handlers/account.js +337 -0
- package/dist/src/handlers/address.d.ts +35 -0
- package/dist/src/handlers/address.js +133 -0
- package/dist/src/handlers/calendar-event.d.ts +70 -0
- package/dist/src/handlers/calendar-event.js +417 -0
- package/dist/src/handlers/calendar-feed.d.ts +47 -0
- package/dist/src/handlers/calendar-feed.js +184 -0
- package/dist/src/handlers/calendar-suggestion.d.ts +47 -0
- package/dist/src/handlers/calendar-suggestion.js +204 -0
- package/dist/src/handlers/calendar.d.ts +116 -0
- package/dist/src/handlers/calendar.js +323 -0
- package/dist/src/handlers/config.d.ts +43 -0
- package/dist/src/handlers/config.js +164 -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 +88 -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 +37 -0
- package/dist/src/handlers/index.d.ts +88 -0
- package/dist/src/handlers/index.js +62 -0
- package/dist/src/handlers/label.d.ts +43 -0
- package/dist/src/handlers/label.js +107 -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 +211 -0
- package/dist/src/handlers/me.d.ts +2 -0
- package/dist/src/handlers/me.js +117 -0
- package/dist/src/handlers/message.d.ts +82 -0
- package/dist/src/handlers/message.js +595 -0
- package/dist/src/handlers/organize.d.ts +10 -0
- package/dist/src/handlers/organize.js +103 -0
- package/dist/src/handlers/outbox-attachment.d.ts +25 -0
- package/dist/src/handlers/outbox-attachment.js +77 -0
- package/dist/src/handlers/outbox.d.ts +4 -0
- package/dist/src/handlers/outbox.js +136 -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 +73 -0
- package/dist/src/handlers/system-update.d.ts +2 -0
- package/dist/src/handlers/system-update.js +159 -0
- package/dist/src/handlers/thread.d.ts +148 -0
- package/dist/src/handlers/thread.js +228 -0
- package/dist/src/handlers/unified-threads.d.ts +247 -0
- package/dist/src/handlers/unified-threads.js +406 -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 +5 -0
- package/dist/src/index.js +53 -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 +15 -0
- package/dist/src/jwt-auth.js +45 -0
- package/dist/src/lambda.d.ts +13 -0
- package/dist/src/lambda.js +33 -0
- package/dist/src/request.d.ts +9 -0
- package/dist/src/request.js +17 -0
- package/dist/src/response.d.ts +44 -0
- package/dist/src/response.js +80 -0
- package/dist/src/serve.d.ts +31 -0
- package/dist/src/serve.js +117 -0
- package/dist/src/service/account-deletion.d.ts +20 -0
- package/dist/src/service/account-deletion.js +33 -0
- package/dist/src/service/compose-sqlite.d.ts +3 -0
- package/dist/src/service/compose-sqlite.js +13 -0
- package/dist/src/service/create-remit-client.d.ts +109 -0
- package/dist/src/service/create-remit-client.js +188 -0
- package/dist/src/service/data-client.d.ts +12 -0
- package/dist/src/service/data-client.js +42 -0
- package/dist/src/service/export-identity.d.ts +4 -0
- package/dist/src/service/export-identity.js +33 -0
- package/dist/src/service/fire-and-forget.d.ts +54 -0
- package/dist/src/service/fire-and-forget.js +37 -0
- package/dist/src/service/organize.d.ts +181 -0
- package/dist/src/service/organize.js +367 -0
- package/dist/src/service/queues.d.ts +12 -0
- package/dist/src/service/queues.js +1 -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/shared-deps.d.ts +6 -0
- package/dist/src/service/shared-deps.js +24 -0
- package/dist/src/service/trigger-sync.d.ts +57 -0
- package/dist/src/service/trigger-sync.js +31 -0
- package/dist/src/types.d.ts +72 -0
- package/dist/src/types.js +1 -0
- package/package.json +125 -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/data-backend.ts +0 -14
- 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/sqs.ts +0 -4
- 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
|
@@ -1,8 +1,6 @@
|
|
|
1
1
|
import type { AddressFlags } from "@remit/api-openapi-types";
|
|
2
2
|
import { SenderTrust } from "@remit/domain-enums";
|
|
3
|
-
|
|
4
3
|
export type SenderTrustValue = (typeof SenderTrust)[keyof typeof SenderTrust];
|
|
5
|
-
|
|
6
4
|
/**
|
|
7
5
|
* Derive the SenderTrust discriminator from an Address's flags map.
|
|
8
6
|
*
|
|
@@ -14,10 +12,4 @@ export type SenderTrustValue = (typeof SenderTrust)[keyof typeof SenderTrust];
|
|
|
14
12
|
* Pure function, no I/O. Frontend never derives this — single source of
|
|
15
13
|
* truth for the UI badge state.
|
|
16
14
|
*/
|
|
17
|
-
export const deriveSenderTrust
|
|
18
|
-
flags: AddressFlags | undefined,
|
|
19
|
-
): SenderTrustValue => {
|
|
20
|
-
if (flags?.vip?.value === true) return SenderTrust.Vip;
|
|
21
|
-
if (flags?.wellknown?.value === true) return SenderTrust.Wellknown;
|
|
22
|
-
return SenderTrust.Unknown;
|
|
23
|
-
};
|
|
15
|
+
export declare const deriveSenderTrust: (flags: AddressFlags | undefined) => SenderTrustValue;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { SenderTrust } from "@remit/domain-enums";
|
|
2
|
+
/**
|
|
3
|
+
* Derive the SenderTrust discriminator from an Address's flags map.
|
|
4
|
+
*
|
|
5
|
+
* Precedence (per EDD #232):
|
|
6
|
+
* flags.vip.value === true → "vip"
|
|
7
|
+
* flags.wellknown.value === true → "wellknown"
|
|
8
|
+
* otherwise → "unknown"
|
|
9
|
+
*
|
|
10
|
+
* Pure function, no I/O. Frontend never derives this — single source of
|
|
11
|
+
* truth for the UI badge state.
|
|
12
|
+
*/
|
|
13
|
+
export const deriveSenderTrust = (flags) => {
|
|
14
|
+
if (flags?.vip?.value === true)
|
|
15
|
+
return SenderTrust.Vip;
|
|
16
|
+
if (flags?.wellknown?.value === true)
|
|
17
|
+
return SenderTrust.Wellknown;
|
|
18
|
+
return SenderTrust.Unknown;
|
|
19
|
+
};
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { APIGatewayProxyResult } from "aws-lambda";
|
|
2
|
+
/**
|
|
3
|
+
* The `code` a refusal carries when it does not name its own. Every error body
|
|
4
|
+
* the API emits is flat `{ code, message }` (issue #371), and `code` is the
|
|
5
|
+
* only field a client may branch on — a message is a sentence for a person and
|
|
6
|
+
* is free to change.
|
|
7
|
+
*
|
|
8
|
+
* A 5xx always answers `internal_error`, whatever the throw site said: a coded
|
|
9
|
+
* 5xx is a mistake at the throw site, not a contract, and a fixed token cannot
|
|
10
|
+
* carry anything about the failure out of the process.
|
|
11
|
+
*/
|
|
12
|
+
export declare const INTERNAL_ERROR_CODE = "internal_error";
|
|
13
|
+
/**
|
|
14
|
+
* The one sentence any 5xx answers with. A thrown message is written for a log
|
|
15
|
+
* line, not for a stranger — it names hosts, queries and ids — so it is
|
|
16
|
+
* replaced rather than trusted. The real message is already on the error log
|
|
17
|
+
* beside the correlation id the response carries.
|
|
18
|
+
*/
|
|
19
|
+
export declare const INTERNAL_ERROR_MESSAGE = "Internal server error";
|
|
20
|
+
export declare const defaultErrorCode: (statusCode: number) => string;
|
|
21
|
+
export declare const handleError: (error: unknown) => Promise<APIGatewayProxyResult>;
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { isPublicApiError } from "@remit/data-ports/errors";
|
|
2
|
+
import { logger } from "@remit/logger";
|
|
3
|
+
import { formatResponse } from "./response.js";
|
|
4
|
+
/**
|
|
5
|
+
* The `code` a refusal carries when it does not name its own. Every error body
|
|
6
|
+
* the API emits is flat `{ code, message }` (issue #371), and `code` is the
|
|
7
|
+
* only field a client may branch on — a message is a sentence for a person and
|
|
8
|
+
* is free to change.
|
|
9
|
+
*
|
|
10
|
+
* A 5xx always answers `internal_error`, whatever the throw site said: a coded
|
|
11
|
+
* 5xx is a mistake at the throw site, not a contract, and a fixed token cannot
|
|
12
|
+
* carry anything about the failure out of the process.
|
|
13
|
+
*/
|
|
14
|
+
export const INTERNAL_ERROR_CODE = "internal_error";
|
|
15
|
+
/**
|
|
16
|
+
* The one sentence any 5xx answers with. A thrown message is written for a log
|
|
17
|
+
* line, not for a stranger — it names hosts, queries and ids — so it is
|
|
18
|
+
* replaced rather than trusted. The real message is already on the error log
|
|
19
|
+
* beside the correlation id the response carries.
|
|
20
|
+
*/
|
|
21
|
+
export const INTERNAL_ERROR_MESSAGE = "Internal server error";
|
|
22
|
+
const CODE_BY_STATUS = {
|
|
23
|
+
400: "invalid_request",
|
|
24
|
+
401: "unauthorized",
|
|
25
|
+
403: "forbidden",
|
|
26
|
+
404: "not_found",
|
|
27
|
+
409: "conflict",
|
|
28
|
+
412: "precondition_failed",
|
|
29
|
+
413: "payload_too_large",
|
|
30
|
+
422: "unprocessable_entity",
|
|
31
|
+
};
|
|
32
|
+
export const defaultErrorCode = (statusCode) => {
|
|
33
|
+
if (statusCode >= 500)
|
|
34
|
+
return INTERNAL_ERROR_CODE;
|
|
35
|
+
return CODE_BY_STATUS[statusCode] ?? "request_refused";
|
|
36
|
+
};
|
|
37
|
+
export const handleError = async (error) => {
|
|
38
|
+
if (error instanceof Error) {
|
|
39
|
+
if ("statusCode" in error) {
|
|
40
|
+
logger.error({
|
|
41
|
+
error: error.message,
|
|
42
|
+
statusCode: error.statusCode,
|
|
43
|
+
stack: error.stack,
|
|
44
|
+
}, "Error with statusCode");
|
|
45
|
+
// An error that opted in names its own code and details, and only below
|
|
46
|
+
// 500: the status bound keeps a coded 5xx from reaching a client rather
|
|
47
|
+
// than trusting every future thrower to leave `publicApiError` alone.
|
|
48
|
+
// Everything else takes the status class's code, so no response goes out
|
|
49
|
+
// without one. A 5xx keeps neither the thrower's code nor its message —
|
|
50
|
+
// one status, one code, one sentence, whatever failed.
|
|
51
|
+
const statusCode = typeof error.statusCode === "number" ? error.statusCode : 500;
|
|
52
|
+
if (statusCode >= 500) {
|
|
53
|
+
return formatResponse({ code: INTERNAL_ERROR_CODE, message: INTERNAL_ERROR_MESSAGE }, statusCode);
|
|
54
|
+
}
|
|
55
|
+
const publicApiError = "publicApiError" in error && isPublicApiError(error.publicApiError)
|
|
56
|
+
? error.publicApiError
|
|
57
|
+
: undefined;
|
|
58
|
+
return formatResponse({
|
|
59
|
+
code: defaultErrorCode(statusCode),
|
|
60
|
+
message: error.message,
|
|
61
|
+
...publicApiError,
|
|
62
|
+
}, statusCode);
|
|
63
|
+
}
|
|
64
|
+
if (error.name === "ElectroError") {
|
|
65
|
+
// DynamoDB client/infrastructure errors should be 500
|
|
66
|
+
// These contain "aws-error" in the message or reference URL
|
|
67
|
+
const isInfrastructureError = error.message.includes("aws-error") ||
|
|
68
|
+
error.message.includes("DynamoDB client");
|
|
69
|
+
const statusCode = isInfrastructureError ? 500 : 400;
|
|
70
|
+
const logMessage = isInfrastructureError
|
|
71
|
+
? "DynamoDB infrastructure error"
|
|
72
|
+
: "ElectroError";
|
|
73
|
+
logger.error({ error: error.message, stack: error.stack }, logMessage);
|
|
74
|
+
// Don't expose internal details for infrastructure errors
|
|
75
|
+
const responseMessage = isInfrastructureError
|
|
76
|
+
? "Database temporarily unavailable"
|
|
77
|
+
: error.message;
|
|
78
|
+
return formatResponse({ code: defaultErrorCode(statusCode), message: responseMessage }, statusCode);
|
|
79
|
+
}
|
|
80
|
+
logger.error({ error: error.message, name: error.name, stack: error.stack }, "Unhandled Error");
|
|
81
|
+
return formatResponse({ code: INTERNAL_ERROR_CODE, message: INTERNAL_ERROR_MESSAGE }, 500);
|
|
82
|
+
}
|
|
83
|
+
logger.error({ error: JSON.stringify(error) }, "Unknown error type");
|
|
84
|
+
return formatResponse({ code: INTERNAL_ERROR_CODE, message: INTERNAL_ERROR_MESSAGE }, 500);
|
|
85
|
+
};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { AccountResponse, AccountService as AccountServiceName, FolderAppointment } from "@remit/api-openapi-types";
|
|
2
|
+
import type { AccountItem } from "@remit/data-ports";
|
|
3
|
+
import type { AccountOverrides } from "./account-overrides.js";
|
|
4
|
+
import type { AccountSignature } from "./account-signature.js";
|
|
5
|
+
/**
|
|
6
|
+
* Natural key identifying "the same mailbox in the same place" within an
|
|
7
|
+
* account config. IMAP host and login username are both case-insensitive, so we
|
|
8
|
+
* fold to lowercase before comparing. Used as the explicit server-side
|
|
9
|
+
* uniqueness key now that message identity is account-scoped (entropy per
|
|
10
|
+
* onboard) and no longer incidentally dedups duplicate onboards (#633/#635).
|
|
11
|
+
*/
|
|
12
|
+
export interface MailboxNaturalKey {
|
|
13
|
+
imapHost: string;
|
|
14
|
+
username: string;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Find an existing ACTIVE (non-deleted) account that occupies the same
|
|
18
|
+
* mailbox-in-the-same-place as `key`. Soft-deleted accounts are ignored so a
|
|
19
|
+
* re-onboard after delete still succeeds.
|
|
20
|
+
*
|
|
21
|
+
* Callers pass the accounts already scoped to one account config (the natural
|
|
22
|
+
* key's accountConfigId component), so this only matches on host + username.
|
|
23
|
+
*/
|
|
24
|
+
export declare const findActiveDuplicateMailbox: (existing: AccountItem[], key: MailboxNaturalKey) => AccountItem | undefined;
|
|
25
|
+
/**
|
|
26
|
+
* Reject the create when an active account already onboards the same mailbox in
|
|
27
|
+
* the same place. Surfaces as a typed 409 ConflictError so the web-client can
|
|
28
|
+
* show a "already added" message instead of silently creating a duplicate.
|
|
29
|
+
*/
|
|
30
|
+
export declare const assertNoDuplicateMailbox: (existing: AccountItem[], key: MailboxNaturalKey) => void;
|
|
31
|
+
/** Rejects OAuth accounts that must go through the dedicated connect flow. */
|
|
32
|
+
export declare const assertNotOAuthCreate: (authType: string | undefined) => void;
|
|
33
|
+
/** Rejects password-auth account creation when no password is supplied. */
|
|
34
|
+
export declare const assertPasswordProvided: (authType: string | undefined, password: string | undefined) => void;
|
|
35
|
+
export declare const resolveSyncedServices: (account: Pick<AccountItem, "authType" | "grantedScopes">, requested: readonly AccountServiceName[]) => AccountServiceName[];
|
|
36
|
+
export declare const toAccountResponse: (account: AccountItem, signature?: AccountSignature, overrides?: AccountOverrides, folderAppointments?: FolderAppointment[]) => AccountResponse;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { BadRequestError, ConflictError } from "@remit/data-ports/errors";
|
|
2
|
+
import { AccountAuthType, AccountService } from "@remit/domain-enums";
|
|
3
|
+
import { microsoftServicesGranted, orderServices, } from "@remit/mail-oauth-service";
|
|
4
|
+
const mailboxKeyOf = (key) => `${key.imapHost.toLowerCase()}\u0000${key.username.toLowerCase()}`;
|
|
5
|
+
/**
|
|
6
|
+
* Find an existing ACTIVE (non-deleted) account that occupies the same
|
|
7
|
+
* mailbox-in-the-same-place as `key`. Soft-deleted accounts are ignored so a
|
|
8
|
+
* re-onboard after delete still succeeds.
|
|
9
|
+
*
|
|
10
|
+
* Callers pass the accounts already scoped to one account config (the natural
|
|
11
|
+
* key's accountConfigId component), so this only matches on host + username.
|
|
12
|
+
*/
|
|
13
|
+
export const findActiveDuplicateMailbox = (existing, key) => {
|
|
14
|
+
const target = mailboxKeyOf(key);
|
|
15
|
+
return existing.find((account) => !account.deletedAt &&
|
|
16
|
+
mailboxKeyOf({
|
|
17
|
+
imapHost: account.imapHost,
|
|
18
|
+
username: account.username,
|
|
19
|
+
}) === target);
|
|
20
|
+
};
|
|
21
|
+
/**
|
|
22
|
+
* Reject the create when an active account already onboards the same mailbox in
|
|
23
|
+
* the same place. Surfaces as a typed 409 ConflictError so the web-client can
|
|
24
|
+
* show a "already added" message instead of silently creating a duplicate.
|
|
25
|
+
*/
|
|
26
|
+
export const assertNoDuplicateMailbox = (existing, key) => {
|
|
27
|
+
const duplicate = findActiveDuplicateMailbox(existing, key);
|
|
28
|
+
if (!duplicate)
|
|
29
|
+
return;
|
|
30
|
+
throw new ConflictError(`An account for ${key.username} on ${key.imapHost} already exists`);
|
|
31
|
+
};
|
|
32
|
+
/** Rejects OAuth accounts that must go through the dedicated connect flow. */
|
|
33
|
+
export const assertNotOAuthCreate = (authType) => {
|
|
34
|
+
if (authType === AccountAuthType.OauthMicrosoft) {
|
|
35
|
+
throw new BadRequestError("OAuth accounts must be created via the OAuth connect flow (POST /accounts/oauth/microsoft/start)");
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
/** Rejects password-auth account creation when no password is supplied. */
|
|
39
|
+
export const assertPasswordProvided = (authType, password) => {
|
|
40
|
+
const isPasswordAuth = authType === AccountAuthType.Password || !authType;
|
|
41
|
+
if (isPasswordAuth && !password) {
|
|
42
|
+
throw new BadRequestError("password is required when authType is 'password' (or when authType is omitted)");
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
export const resolveSyncedServices = (account, requested) => {
|
|
46
|
+
const services = orderServices(requested);
|
|
47
|
+
if (services.length === 0) {
|
|
48
|
+
throw new BadRequestError("syncedServices must name at least one service. To stop syncing an account entirely, delete it with DELETE /accounts/{accountId}.");
|
|
49
|
+
}
|
|
50
|
+
if (account.authType !== AccountAuthType.OauthMicrosoft) {
|
|
51
|
+
if (services.some((service) => service !== AccountService.Mail)) {
|
|
52
|
+
throw new BadRequestError(`A password account syncs mail only, so syncedServices must be ["${AccountService.Mail}"].`);
|
|
53
|
+
}
|
|
54
|
+
return services;
|
|
55
|
+
}
|
|
56
|
+
const granted = microsoftServicesGranted(account.grantedScopes);
|
|
57
|
+
const uncovered = services.filter((service) => !granted.includes(service));
|
|
58
|
+
if (uncovered.length > 0) {
|
|
59
|
+
throw new BadRequestError(`This account's granted scopes lack ${uncovered.join(", ")}. Consent to them through POST /accounts/oauth/microsoft/start with services ${JSON.stringify(services)}, then sign in to Microsoft again.`);
|
|
60
|
+
}
|
|
61
|
+
return services;
|
|
62
|
+
};
|
|
63
|
+
// SECURITY: passwordHash, oauthRefreshTokenHash, and smtpPasswordHash are
|
|
64
|
+
// intentionally omitted — never expose token material in API responses.
|
|
65
|
+
// Display name, mute flag, and signatures live in per-account AccountSetting
|
|
66
|
+
// rows (RFC 032); the caller resolves them and passes them in. Absent means the
|
|
67
|
+
// override is unset. `folderAppointments` (RFC 032 exclusive-folder-appointment,
|
|
68
|
+
// #976) is resolved the same way — persisted rows merged with server-proposed
|
|
69
|
+
// defaults for any unfilled role — via `resolveFolderAppointments`.
|
|
70
|
+
export const toAccountResponse = (account, signature = {}, overrides = {}, folderAppointments = []) => ({
|
|
71
|
+
accountId: account.accountId,
|
|
72
|
+
accountConfigId: account.accountConfigId,
|
|
73
|
+
displayName: overrides.displayName,
|
|
74
|
+
username: account.username,
|
|
75
|
+
email: account.email,
|
|
76
|
+
authType: account.authType ?? AccountAuthType.Password,
|
|
77
|
+
syncedServices: account.syncedServices,
|
|
78
|
+
grantedScopes: account.grantedScopes,
|
|
79
|
+
imapHost: account.imapHost,
|
|
80
|
+
imapPort: account.imapPort,
|
|
81
|
+
imapTls: account.imapTls,
|
|
82
|
+
imapStartTls: account.imapStartTls,
|
|
83
|
+
// RFC 032 Tier 2: SMTP config is total. ElectroDB `default` applies on write
|
|
84
|
+
// only, so rows written before this change still lack these attributes —
|
|
85
|
+
// coalesce to the schema defaults on read so the response is always complete.
|
|
86
|
+
smtpEnabled: account.smtpEnabled ?? false,
|
|
87
|
+
smtpHost: account.smtpHost ?? "",
|
|
88
|
+
smtpPort: account.smtpPort ?? 587,
|
|
89
|
+
smtpTls: account.smtpTls ?? false,
|
|
90
|
+
smtpStartTls: account.smtpStartTls ?? true,
|
|
91
|
+
smtpUsername: account.smtpUsername ?? "",
|
|
92
|
+
signaturePlainText: signature.plainText,
|
|
93
|
+
signatureHtml: signature.html,
|
|
94
|
+
composeLanguages: overrides.composeLanguages,
|
|
95
|
+
isActive: account.isActive,
|
|
96
|
+
connectionState: account.connectionState,
|
|
97
|
+
lastConnectedAt: account.lastConnectedAt,
|
|
98
|
+
lastSyncAt: account.lastSyncAt,
|
|
99
|
+
lastError: account.lastError,
|
|
100
|
+
syncPhase: account.syncPhase,
|
|
101
|
+
mailboxCountTotal: account.mailboxCountTotal,
|
|
102
|
+
mailboxCountSynced: account.mailboxCountSynced,
|
|
103
|
+
muted: overrides.muted,
|
|
104
|
+
createdAt: account.createdAt,
|
|
105
|
+
updatedAt: account.updatedAt,
|
|
106
|
+
folderAppointments,
|
|
107
|
+
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { AccountService as AccountServiceName } from "@remit/api-openapi-types";
|
|
2
|
+
import type { MicrosoftOAuthOperationIds, OperationHandler, PublicOperationHandler, PublicOperationIds } from "../types.js";
|
|
3
|
+
export interface OAuthState {
|
|
4
|
+
accountConfigId: string;
|
|
5
|
+
nonce: string;
|
|
6
|
+
timestamp: number;
|
|
7
|
+
services: AccountServiceName[];
|
|
8
|
+
}
|
|
9
|
+
export declare const STATE_TTL_MS: number;
|
|
10
|
+
export declare function signState(payload: OAuthState, clientSecret: string): Promise<string>;
|
|
11
|
+
export declare function verifyState(state: string, clientSecret: string): Promise<OAuthState>;
|
|
12
|
+
export declare function parseJwtClaims(token: string): Promise<Record<string, unknown> | null>;
|
|
13
|
+
export declare function getWebOrigin(origins: readonly string[]): string;
|
|
14
|
+
export declare const microsoftOAuthCallback: PublicOperationHandler<"sync">;
|
|
15
|
+
export declare const MicrosoftOAuthOperations: Record<Exclude<MicrosoftOAuthOperationIds, PublicOperationIds>, OperationHandler<MicrosoftOAuthOperationIds, "sync">>;
|
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { AccountAuthType, AccountService, ConnectionState, } from "@remit/domain-enums";
|
|
3
|
+
import { logger } from "@remit/logger";
|
|
4
|
+
import { createMailOAuthService, microsoftProviderConfig, microsoftServicesGranted, orderServices, RefreshTokenError, } from "@remit/mail-oauth-service";
|
|
5
|
+
import { serializeEncryptedPayload } from "@remit/secrets-service";
|
|
6
|
+
import { loadMsOAuth } from "../config/msoauth.js";
|
|
7
|
+
import { safeJsonParse } from "../json.js";
|
|
8
|
+
import { rawApiResponse } from "../response.js";
|
|
9
|
+
import { triggerAccountSyncSafe } from "./account.js";
|
|
10
|
+
import { findActiveDuplicateMailbox } from "./account-guards.js";
|
|
11
|
+
import { ensureAccountConfig } from "./ensure-account-config.js";
|
|
12
|
+
const OUTLOOK_IMAP_HOST = "outlook.office365.com";
|
|
13
|
+
const ACCOUNT_SERVICES = Object.values(AccountService);
|
|
14
|
+
const isServiceList = (value) => Array.isArray(value) &&
|
|
15
|
+
value.length > 0 &&
|
|
16
|
+
value.every((service) => typeof service === "string" && ACCOUNT_SERVICES.includes(service));
|
|
17
|
+
export const STATE_TTL_MS = 10 * 60 * 1000; // 10 minutes
|
|
18
|
+
/**
|
|
19
|
+
* Derive a signing key from the client secret, namespaced to avoid reuse.
|
|
20
|
+
* The key is HMAC-SHA256("oauth-state-signing:" + clientSecret).
|
|
21
|
+
*/
|
|
22
|
+
function deriveSigningKey(clientSecret) {
|
|
23
|
+
return createHmac("sha256", `oauth-state-signing:${clientSecret}`)
|
|
24
|
+
.update("")
|
|
25
|
+
.digest();
|
|
26
|
+
}
|
|
27
|
+
function base64urlEncode(buf) {
|
|
28
|
+
return buf.toString("base64url");
|
|
29
|
+
}
|
|
30
|
+
function base64urlDecode(str) {
|
|
31
|
+
return Buffer.from(str, "base64url");
|
|
32
|
+
}
|
|
33
|
+
export async function signState(payload, clientSecret) {
|
|
34
|
+
const key = deriveSigningKey(clientSecret);
|
|
35
|
+
const payloadBuf = Buffer.from(JSON.stringify(payload), "utf8");
|
|
36
|
+
const payloadEncoded = base64urlEncode(payloadBuf);
|
|
37
|
+
const sig = createHmac("sha256", key).update(payloadEncoded).digest();
|
|
38
|
+
const sigEncoded = base64urlEncode(sig);
|
|
39
|
+
return `${payloadEncoded}.${sigEncoded}`;
|
|
40
|
+
}
|
|
41
|
+
export async function verifyState(state, clientSecret) {
|
|
42
|
+
const dotIndex = state.lastIndexOf(".");
|
|
43
|
+
if (dotIndex < 0)
|
|
44
|
+
throw new Error("Malformed state: missing dot separator");
|
|
45
|
+
const payloadEncoded = state.slice(0, dotIndex);
|
|
46
|
+
const sigEncoded = state.slice(dotIndex + 1);
|
|
47
|
+
const key = deriveSigningKey(clientSecret);
|
|
48
|
+
const expectedSig = createHmac("sha256", key).update(payloadEncoded).digest();
|
|
49
|
+
const actualSig = base64urlDecode(sigEncoded);
|
|
50
|
+
if (actualSig.length !== expectedSig.length ||
|
|
51
|
+
!timingSafeEqual(actualSig, expectedSig)) {
|
|
52
|
+
throw new Error("State signature verification failed");
|
|
53
|
+
}
|
|
54
|
+
const payload = JSON.parse(base64urlDecode(payloadEncoded).toString("utf8"));
|
|
55
|
+
if (Date.now() - payload.timestamp > STATE_TTL_MS) {
|
|
56
|
+
throw new Error("State has expired");
|
|
57
|
+
}
|
|
58
|
+
if (payload.services === undefined) {
|
|
59
|
+
return { ...payload, services: [AccountService.Mail] };
|
|
60
|
+
}
|
|
61
|
+
if (!isServiceList(payload.services)) {
|
|
62
|
+
throw new Error("State names no requested services");
|
|
63
|
+
}
|
|
64
|
+
return payload;
|
|
65
|
+
}
|
|
66
|
+
// ─── JWT claims parsing ──────────────────────────────────────────────────────
|
|
67
|
+
export async function parseJwtClaims(token) {
|
|
68
|
+
const parts = token.split(".");
|
|
69
|
+
if (parts.length !== 3)
|
|
70
|
+
return null;
|
|
71
|
+
return safeJsonParse(Buffer.from(parts[1], "base64url").toString("utf8")).catch(() => null);
|
|
72
|
+
}
|
|
73
|
+
// ─── Web origin helper ───────────────────────────────────────────────────────
|
|
74
|
+
export function getWebOrigin(origins) {
|
|
75
|
+
// Prefer the first HTTPS origin (production frontend)
|
|
76
|
+
const httpsOrigin = origins.find((o) => o.startsWith("https://"));
|
|
77
|
+
return httpsOrigin ?? origins[0] ?? "https://localhost:3000";
|
|
78
|
+
}
|
|
79
|
+
const scopeRefusalUrl = (webOrigin, email, missingServices) => {
|
|
80
|
+
const url = new URL(`${webOrigin}/settings/accounts`);
|
|
81
|
+
url.searchParams.set("oauthError", "scope_not_granted");
|
|
82
|
+
url.searchParams.set("oauthEmail", email);
|
|
83
|
+
url.searchParams.set("missingServices", missingServices.join(","));
|
|
84
|
+
return url.toString();
|
|
85
|
+
};
|
|
86
|
+
const redeemEachService = async (serviceFor, initialToken, services, accountConfigId) => {
|
|
87
|
+
let token = initialToken;
|
|
88
|
+
const grantedScopes = [];
|
|
89
|
+
for (const service of services) {
|
|
90
|
+
const redeemed = await serviceFor(service)
|
|
91
|
+
.refresh(token)
|
|
92
|
+
.catch((err) => {
|
|
93
|
+
logger.warn({
|
|
94
|
+
alert: "oauth_callback_failed",
|
|
95
|
+
reason: "scope_redemption_failed",
|
|
96
|
+
accountConfigId,
|
|
97
|
+
service,
|
|
98
|
+
error: err,
|
|
99
|
+
}, "MS OAuth callback: the consent did not cover a requested service");
|
|
100
|
+
return err instanceof RefreshTokenError &&
|
|
101
|
+
err.error.kind === "transient"
|
|
102
|
+
? "exchange_failed"
|
|
103
|
+
: "scope_not_granted";
|
|
104
|
+
});
|
|
105
|
+
if (redeemed === "exchange_failed")
|
|
106
|
+
return { kind: "refused", reason: redeemed };
|
|
107
|
+
if (redeemed === "scope_not_granted")
|
|
108
|
+
return { kind: "refused", reason: redeemed, service };
|
|
109
|
+
grantedScopes.push(...redeemed.grantedScopes);
|
|
110
|
+
token = redeemed.refreshToken ?? token;
|
|
111
|
+
}
|
|
112
|
+
return { kind: "granted", refreshToken: token, grantedScopes };
|
|
113
|
+
};
|
|
114
|
+
// ─── Handlers ────────────────────────────────────────────────────────────────
|
|
115
|
+
export const microsoftOAuthCallback = async (context, ctx) => {
|
|
116
|
+
const webOrigin = getWebOrigin(ctx.config.corsAllowedOrigins);
|
|
117
|
+
const qs = context.request.query;
|
|
118
|
+
// Marked raw so the response formatter forwards the Location header
|
|
119
|
+
// instead of serializing this object as a JSON body. Microsoft's browser
|
|
120
|
+
// redirect lands here, so a dropped Location is a blank page.
|
|
121
|
+
const redirect = (url) => rawApiResponse({
|
|
122
|
+
statusCode: 302,
|
|
123
|
+
headers: { Location: url },
|
|
124
|
+
body: "",
|
|
125
|
+
});
|
|
126
|
+
// If Microsoft returned an error, pass it through to the frontend
|
|
127
|
+
if (qs.error) {
|
|
128
|
+
const errorCode = encodeURIComponent(qs.error);
|
|
129
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=${errorCode}`);
|
|
130
|
+
}
|
|
131
|
+
const code = qs.code;
|
|
132
|
+
const state = qs.state;
|
|
133
|
+
if (!code || !state) {
|
|
134
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=missing_params`);
|
|
135
|
+
}
|
|
136
|
+
const loaded = await loadMsOAuth(ctx.config.msOAuth).catch((err) => {
|
|
137
|
+
logger.error({
|
|
138
|
+
alert: "oauth_callback_failed",
|
|
139
|
+
reason: "config_error",
|
|
140
|
+
errorName: err?.name,
|
|
141
|
+
errorCode: err?.Code ?? err?.code,
|
|
142
|
+
error: err,
|
|
143
|
+
}, "MS OAuth callback: failed to load OAuth config");
|
|
144
|
+
return null;
|
|
145
|
+
});
|
|
146
|
+
if (loaded === null)
|
|
147
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=config_error`);
|
|
148
|
+
const { config, credentials } = loaded;
|
|
149
|
+
// Verify the HMAC-signed state
|
|
150
|
+
// A bad/expired/forged state is a security-relevant signal (CSRF
|
|
151
|
+
// attempt, clock skew, or a stale callback) — must not be swallowed
|
|
152
|
+
// silently. Warn so it's observable; still redirect the user cleanly.
|
|
153
|
+
const statePayload = await verifyState(state, credentials.clientSecret).catch((err) => {
|
|
154
|
+
logger.warn({
|
|
155
|
+
alert: "oauth_callback_failed",
|
|
156
|
+
reason: "invalid_state",
|
|
157
|
+
errorName: err?.name,
|
|
158
|
+
error: err,
|
|
159
|
+
}, "MS OAuth callback: state verification failed");
|
|
160
|
+
return null;
|
|
161
|
+
});
|
|
162
|
+
if (statePayload === null)
|
|
163
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=invalid_state`);
|
|
164
|
+
const { accountConfigId } = statePayload;
|
|
165
|
+
const [firstService] = orderServices(statePayload.services);
|
|
166
|
+
const serviceFor = (service) => createMailOAuthService(microsoftProviderConfig({
|
|
167
|
+
clientId: credentials.clientId,
|
|
168
|
+
clientSecret: credentials.clientSecret,
|
|
169
|
+
services: [service],
|
|
170
|
+
overrides: config.overrides,
|
|
171
|
+
}));
|
|
172
|
+
// Exchange the authorization code for tokens
|
|
173
|
+
const tokenSet = await serviceFor(firstService)
|
|
174
|
+
.exchangeCode(code, config.redirectUri)
|
|
175
|
+
.catch((err) => {
|
|
176
|
+
logger.error({ accountConfigId, error: err }, "MS OAuth code exchange failed");
|
|
177
|
+
return null;
|
|
178
|
+
});
|
|
179
|
+
if (tokenSet === null)
|
|
180
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=exchange_failed`);
|
|
181
|
+
if (!tokenSet.refreshToken) {
|
|
182
|
+
logger.error({ accountConfigId }, "MS OAuth token exchange returned no refresh_token");
|
|
183
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=exchange_failed`);
|
|
184
|
+
}
|
|
185
|
+
// Extract the user's email from the ID token returned alongside the access
|
|
186
|
+
// token when openid+email scopes are requested.
|
|
187
|
+
//
|
|
188
|
+
// We prefer the ID token (idToken) because Outlook resource access tokens
|
|
189
|
+
// (IMAP.AccessAsUser.All, SMTP.Send) are opaque/non-JWT and cannot be
|
|
190
|
+
// decoded. The ID token is a standard OIDC token that always contains
|
|
191
|
+
// identity claims (preferred_username / email).
|
|
192
|
+
//
|
|
193
|
+
// Falls back to parsing the access token only in test/dev environments where
|
|
194
|
+
// idToken may not be present (e.g. custom token endpoints that don't issue
|
|
195
|
+
// OIDC tokens).
|
|
196
|
+
const tokenToParse = tokenSet.idToken ?? tokenSet.accessToken;
|
|
197
|
+
const claims = await parseJwtClaims(tokenToParse);
|
|
198
|
+
if (!claims) {
|
|
199
|
+
// A non-JWT or unparseable token. The empty-email guard below turns
|
|
200
|
+
// this into a user-facing missing_email redirect; log here so the parse
|
|
201
|
+
// failure itself is observable (e.g. an unexpected token shape).
|
|
202
|
+
logger.warn({
|
|
203
|
+
alert: "oauth_callback_failed",
|
|
204
|
+
reason: "jwt_parse_failed",
|
|
205
|
+
accountConfigId,
|
|
206
|
+
}, "MS OAuth callback: failed to parse identity token claims");
|
|
207
|
+
}
|
|
208
|
+
const email = claims
|
|
209
|
+
? (claims.preferred_username ??
|
|
210
|
+
claims.email ??
|
|
211
|
+
claims.upn)
|
|
212
|
+
: undefined;
|
|
213
|
+
if (!email) {
|
|
214
|
+
logger.error({ accountConfigId }, "MS OAuth: could not extract email from token claims");
|
|
215
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=missing_email`);
|
|
216
|
+
}
|
|
217
|
+
const { account, accountConfig, secrets } = ctx.client;
|
|
218
|
+
// Reconnect when an active OAuth account already onboards this mailbox.
|
|
219
|
+
// Same natural key as the IMAP create guard (#635); the OAuth flow returns
|
|
220
|
+
// the existing account (token refresh) rather than rejecting, because a
|
|
221
|
+
// re-auth is the expected, idempotent path for OAuth.
|
|
222
|
+
const existingAccounts = (await account.listAllByAccountConfig(accountConfigId)).filter((a) => a.authType === AccountAuthType.OauthMicrosoft);
|
|
223
|
+
const existing = findActiveDuplicateMailbox(existingAccounts, {
|
|
224
|
+
imapHost: OUTLOOK_IMAP_HOST,
|
|
225
|
+
username: email,
|
|
226
|
+
});
|
|
227
|
+
const services = orderServices([
|
|
228
|
+
...statePayload.services,
|
|
229
|
+
...(existing?.syncedServices ?? []),
|
|
230
|
+
]);
|
|
231
|
+
const redemption = await redeemEachService(serviceFor, tokenSet.refreshToken, services.filter((service) => service !== firstService), accountConfigId);
|
|
232
|
+
if (redemption.kind === "refused" &&
|
|
233
|
+
redemption.reason === "scope_not_granted")
|
|
234
|
+
return redirect(scopeRefusalUrl(webOrigin, email, [redemption.service]));
|
|
235
|
+
if (redemption.kind === "refused")
|
|
236
|
+
return redirect(`${webOrigin}/settings/accounts?oauthError=${redemption.reason}`);
|
|
237
|
+
const grantedScopes = [
|
|
238
|
+
...new Set([...tokenSet.grantedScopes, ...redemption.grantedScopes]),
|
|
239
|
+
];
|
|
240
|
+
const grantedServices = microsoftServicesGranted(grantedScopes);
|
|
241
|
+
const missingServices = services.filter((service) => !grantedServices.includes(service));
|
|
242
|
+
if (missingServices.length > 0) {
|
|
243
|
+
logger.warn({
|
|
244
|
+
alert: "oauth_callback_failed",
|
|
245
|
+
reason: "scope_not_granted",
|
|
246
|
+
accountConfigId,
|
|
247
|
+
missingServices,
|
|
248
|
+
grantedScopes,
|
|
249
|
+
}, "MS OAuth callback: granted scopes lack a requested service");
|
|
250
|
+
return redirect(scopeRefusalUrl(webOrigin, email, missingServices));
|
|
251
|
+
}
|
|
252
|
+
// Ensure the account config row exists for this user
|
|
253
|
+
await ensureAccountConfig(accountConfig, accountConfigId);
|
|
254
|
+
// Encrypt the refresh token
|
|
255
|
+
const tokenPayload = await secrets.encrypt(redemption.refreshToken);
|
|
256
|
+
const oauthRefreshTokenHash = JSON.stringify(serializeEncryptedPayload(tokenPayload));
|
|
257
|
+
const oauthTokenUpdatedAt = Date.now();
|
|
258
|
+
let accountId;
|
|
259
|
+
if (existing) {
|
|
260
|
+
// Reconnect: update the stored token and clear any reauth_required state
|
|
261
|
+
const updated = await account.update(existing.accountId, {
|
|
262
|
+
oauthRefreshTokenHash,
|
|
263
|
+
oauthTokenUpdatedAt,
|
|
264
|
+
syncedServices: services,
|
|
265
|
+
grantedScopes,
|
|
266
|
+
connectionState: ConnectionState.NotAuthenticated,
|
|
267
|
+
}, ["lastError"]);
|
|
268
|
+
accountId = updated.accountId;
|
|
269
|
+
// biome-ignore lint/plugin/no-logger-info: OAuth reconnect is an audit-grade signal
|
|
270
|
+
logger.info({ accountConfigId, accountId }, "MS OAuth reconnect: refresh token updated");
|
|
271
|
+
}
|
|
272
|
+
else {
|
|
273
|
+
// First connect: create a new account
|
|
274
|
+
const newAccount = await account.create({
|
|
275
|
+
accountConfigId,
|
|
276
|
+
email,
|
|
277
|
+
username: email,
|
|
278
|
+
authType: AccountAuthType.OauthMicrosoft,
|
|
279
|
+
syncedServices: services,
|
|
280
|
+
grantedScopes,
|
|
281
|
+
oauthRefreshTokenHash,
|
|
282
|
+
oauthTokenUpdatedAt,
|
|
283
|
+
imapHost: OUTLOOK_IMAP_HOST,
|
|
284
|
+
imapPort: 993,
|
|
285
|
+
imapTls: true,
|
|
286
|
+
imapStartTls: false,
|
|
287
|
+
smtpEnabled: true,
|
|
288
|
+
smtpHost: "smtp.office365.com",
|
|
289
|
+
smtpPort: 587,
|
|
290
|
+
smtpTls: false,
|
|
291
|
+
smtpStartTls: true,
|
|
292
|
+
isActive: true,
|
|
293
|
+
connectionState: ConnectionState.NotAuthenticated,
|
|
294
|
+
});
|
|
295
|
+
accountId = newAccount.accountId;
|
|
296
|
+
// biome-ignore lint/plugin/no-logger-info: OAuth account creation is an audit-grade signal
|
|
297
|
+
logger.info({ accountConfigId, accountId }, "MS OAuth: new account created");
|
|
298
|
+
}
|
|
299
|
+
if (services.includes(AccountService.Mail)) {
|
|
300
|
+
await triggerAccountSyncSafe(ctx.client, accountId);
|
|
301
|
+
}
|
|
302
|
+
return redirect(`${webOrigin}/settings/accounts?connected=${encodeURIComponent(accountId)}`);
|
|
303
|
+
};
|
|
304
|
+
export const MicrosoftOAuthOperations = {
|
|
305
|
+
MicrosoftOAuthOperations_microsoftOAuthStart: async (context, ctx) => {
|
|
306
|
+
const accountConfigId = ctx.identity.accountConfigId;
|
|
307
|
+
const input = context.request.requestBody;
|
|
308
|
+
const email = typeof input.email === "string" ? input.email : undefined;
|
|
309
|
+
const services = orderServices(input.services ?? [AccountService.Mail]);
|
|
310
|
+
const { config, credentials } = await loadMsOAuth(ctx.config.msOAuth);
|
|
311
|
+
const oauthService = createMailOAuthService(microsoftProviderConfig({
|
|
312
|
+
clientId: credentials.clientId,
|
|
313
|
+
clientSecret: credentials.clientSecret,
|
|
314
|
+
services,
|
|
315
|
+
overrides: config.overrides,
|
|
316
|
+
}));
|
|
317
|
+
const nonce = randomBytes(16).toString("hex");
|
|
318
|
+
const statePayload = {
|
|
319
|
+
accountConfigId,
|
|
320
|
+
nonce,
|
|
321
|
+
timestamp: Date.now(),
|
|
322
|
+
services,
|
|
323
|
+
};
|
|
324
|
+
const state = await signState(statePayload, credentials.clientSecret);
|
|
325
|
+
const authorizationUrl = oauthService.buildAuthorizationUrl({
|
|
326
|
+
redirectUri: config.redirectUri,
|
|
327
|
+
state,
|
|
328
|
+
loginHint: email,
|
|
329
|
+
});
|
|
330
|
+
// biome-ignore lint/plugin/no-logger-info: OAuth initiation is an audit-grade signal
|
|
331
|
+
logger.info({ accountConfigId, services }, "Microsoft OAuth start initiated");
|
|
332
|
+
return { authorizationUrl };
|
|
333
|
+
},
|
|
334
|
+
};
|