Files
HiveGrid-Wireframes/03 Quellen und Referenzen/hivegrid-cloud/packages/integrations/src/admin-mail-provider.server.ts
T

374 lines
12 KiB
TypeScript

import {
buildGmailAuthorizationUrl,
exchangeGmailCodeForTokens,
fetchGmailUserInfo,
refreshGmailAccessToken,
resolveGmailOAuthConfig,
revokeGmailToken,
sendRawMessage,
} from "./google/gmailApi.js";
import {
buildMicrosoftAuthorizationUrl,
exchangeMicrosoftCodeForTokens,
fetchGraphUserProfile,
refreshMicrosoftAccessToken,
resolveMicrosoftMailOAuthConfig,
sendGraphMail,
} from "./microsoft/graphMailApi.js";
import type {
AdminMailConnectionProvider,
AdminOAuthCredentialBundle,
} from "./admin-connections.js";
import { normalizeAdminOAuthCredentialBundle } from "./admin-connections.js";
import {
buildRfc2822Message,
type MappedEmailAddress,
} from "./email-message-mapping.js";
export type AdminMailAccount = {
readonly externalAccountId: string;
readonly emailAddress: string;
readonly displayName: string | null;
};
export type AdminMailOAuthGrant = {
readonly credentials: AdminOAuthCredentialBundle;
readonly account: AdminMailAccount;
};
export type AdminMailProviderPorts = {
readonly gmail: {
readonly configured: () => boolean;
readonly authorizationUrl: (state: string) => string;
readonly exchange: (code: string) => Promise<{
readonly accessToken: string;
readonly refreshToken?: string;
readonly expiresAt: Date;
readonly scopes: readonly string[];
}>;
readonly profile: (accessToken: string) => Promise<{
readonly externalAccountId: string;
readonly email: string;
readonly name?: string;
}>;
readonly refresh: (refreshToken: string) => Promise<{
readonly accessToken: string;
readonly refreshToken?: string;
readonly expiresAt: Date;
readonly scopes: readonly string[];
}>;
readonly revoke: (token: string) => Promise<void>;
readonly send: (
accessToken: string,
rawBase64Url: string,
threadId?: string
) => Promise<{ readonly id: string; readonly threadId?: string }>;
};
readonly microsoft: {
readonly configured: () => boolean;
readonly authorizationUrl: (state: string) => string;
readonly exchange: (code: string) => Promise<{
readonly accessToken: string;
readonly refreshToken?: string;
readonly expiresAt: Date;
readonly scopes: readonly string[];
}>;
readonly profile: (accessToken: string) => Promise<{
readonly externalAccountId: string;
readonly email: string;
readonly displayName?: string;
}>;
readonly refresh: (refreshToken: string) => Promise<{
readonly accessToken: string;
readonly refreshToken?: string;
readonly expiresAt: Date;
readonly scopes: readonly string[];
}>;
readonly send: (
accessToken: string,
input: {
readonly subject: string;
readonly bodyHtml: string;
readonly to: readonly MappedEmailAddress[];
readonly cc?: readonly MappedEmailAddress[];
readonly bcc?: readonly MappedEmailAddress[];
}
) => Promise<void>;
};
};
export function createAdminMailProviderGateway(
ports: AdminMailProviderPorts = defaultPorts()
) {
return {
configured(provider: AdminMailConnectionProvider): boolean {
return provider === "google_mail"
? ports.gmail.configured()
: ports.microsoft.configured();
},
authorizationUrl(
provider: AdminMailConnectionProvider,
state: string
): string {
if (!this.configured(provider)) {
throw new AdminMailProviderError("provider_not_configured");
}
return provider === "google_mail"
? ports.gmail.authorizationUrl(state)
: ports.microsoft.authorizationUrl(state);
},
async exchange(
provider: AdminMailConnectionProvider,
code: string
): Promise<AdminMailOAuthGrant> {
if (!this.configured(provider)) {
throw new AdminMailProviderError("provider_not_configured");
}
const grant =
provider === "google_mail"
? await exchangeGoogle(ports, code)
: await exchangeMicrosoft(ports, code);
return Object.freeze(grant);
},
async refresh(
provider: AdminMailConnectionProvider,
credentials: AdminOAuthCredentialBundle
): Promise<AdminOAuthCredentialBundle> {
const current = normalizeAdminOAuthCredentialBundle(
provider,
credentials
);
const next =
provider === "google_mail"
? await ports.gmail.refresh(current.refreshToken)
: await ports.microsoft.refresh(current.refreshToken);
return normalizeAdminOAuthCredentialBundle(provider, {
accessToken: next.accessToken,
refreshToken: next.refreshToken ?? current.refreshToken,
expiresAt: next.expiresAt.toISOString(),
scopes: next.scopes.length > 0 ? next.scopes : current.scopes,
});
},
async revoke(
provider: AdminMailConnectionProvider,
credentials: AdminOAuthCredentialBundle
): Promise<void> {
const normalized = normalizeAdminOAuthCredentialBundle(
provider,
credentials
);
if (provider === "google_mail") {
await ports.gmail.revoke(normalized.refreshToken);
}
// Microsoft delegated tokens have no app-side revoke endpoint. Removing
// the encrypted refresh token is the reviewed disconnect boundary.
},
async send(
provider: AdminMailConnectionProvider,
credentials: AdminOAuthCredentialBundle,
message: {
readonly fromAddress: string;
readonly fromName?: string | null;
readonly to: readonly MappedEmailAddress[];
readonly cc?: readonly MappedEmailAddress[];
readonly bcc?: readonly MappedEmailAddress[];
readonly subject: string;
readonly bodyHtml: string;
readonly inReplyToInternetMessageId?: string | null;
readonly referencesInternetMessageIds?: readonly string[];
readonly providerThreadId?: string | null;
}
): Promise<{
readonly providerMessageId: string | null;
readonly providerThreadId: string | null;
}> {
const normalized = normalizeAdminOAuthCredentialBundle(
provider,
credentials
);
if (provider === "google_mail") {
const raw = buildRfc2822Message({
fromAddress: message.fromAddress,
fromName: message.fromName ?? undefined,
to: message.to,
cc: message.cc,
bcc: message.bcc,
subject: message.subject,
bodyHtml: message.bodyHtml,
inReplyToInternetMessageId:
message.inReplyToInternetMessageId,
referencesInternetMessageIds:
message.referencesInternetMessageIds,
});
const result = await ports.gmail.send(
normalized.accessToken,
Buffer.from(raw, "utf8").toString("base64url"),
message.providerThreadId ?? undefined
);
return {
providerMessageId: result.id,
providerThreadId: result.threadId ?? null,
};
}
await ports.microsoft.send(normalized.accessToken, {
subject: message.subject,
bodyHtml: message.bodyHtml,
to: message.to,
cc: message.cc,
bcc: message.bcc,
});
return { providerMessageId: null, providerThreadId: null };
},
};
}
async function exchangeGoogle(
ports: AdminMailProviderPorts,
code: string
): Promise<AdminMailOAuthGrant> {
const token = await ports.gmail.exchange(requiredCode(code));
if (!token.refreshToken) {
throw new AdminMailProviderError("refresh_token_missing");
}
const profile = await ports.gmail.profile(token.accessToken);
return {
credentials: normalizeAdminOAuthCredentialBundle("google_mail", {
accessToken: token.accessToken,
refreshToken: token.refreshToken,
expiresAt: token.expiresAt.toISOString(),
scopes: token.scopes,
}),
account: normalizeAccount({
externalAccountId: profile.externalAccountId,
emailAddress: profile.email,
displayName: profile.name ?? null,
}),
};
}
async function exchangeMicrosoft(
ports: AdminMailProviderPorts,
code: string
): Promise<AdminMailOAuthGrant> {
const token = await ports.microsoft.exchange(requiredCode(code));
if (!token.refreshToken) {
throw new AdminMailProviderError("refresh_token_missing");
}
const profile = await ports.microsoft.profile(token.accessToken);
return {
credentials: normalizeAdminOAuthCredentialBundle("microsoft_mail", {
accessToken: token.accessToken,
refreshToken: token.refreshToken,
expiresAt: token.expiresAt.toISOString(),
scopes: token.scopes,
}),
account: normalizeAccount({
externalAccountId: profile.externalAccountId,
emailAddress: profile.email,
displayName: profile.displayName ?? null,
}),
};
}
function defaultPorts(): AdminMailProviderPorts {
return {
gmail: {
configured: () => resolveGmailOAuthConfig() !== null,
authorizationUrl: (state) => {
const config = resolveGmailOAuthConfig();
if (!config) throw new AdminMailProviderError("provider_not_configured");
return buildGmailAuthorizationUrl(config, state);
},
exchange: (code) => {
const config = resolveGmailOAuthConfig();
if (!config) throw new AdminMailProviderError("provider_not_configured");
return exchangeGmailCodeForTokens(config, code);
},
profile: async (accessToken) => {
const profile = await fetchGmailUserInfo(accessToken);
return {
externalAccountId: profile.sub,
email: profile.email,
};
},
refresh: (refreshToken) => {
const config = resolveGmailOAuthConfig();
if (!config) throw new AdminMailProviderError("provider_not_configured");
return refreshGmailAccessToken(config, refreshToken);
},
revoke: revokeGmailToken,
send: sendRawMessage,
},
microsoft: {
configured: () => resolveMicrosoftMailOAuthConfig() !== null,
authorizationUrl: (state) => {
const config = resolveMicrosoftMailOAuthConfig();
if (!config) throw new AdminMailProviderError("provider_not_configured");
return buildMicrosoftAuthorizationUrl(config, state);
},
exchange: (code) => {
const config = resolveMicrosoftMailOAuthConfig();
if (!config) throw new AdminMailProviderError("provider_not_configured");
return exchangeMicrosoftCodeForTokens(config, code);
},
profile: async (accessToken) => {
const profile = await fetchGraphUserProfile(accessToken);
return {
externalAccountId: profile.id,
email: profile.email,
displayName: profile.displayName,
};
},
refresh: (refreshToken) => {
const config = resolveMicrosoftMailOAuthConfig();
if (!config) throw new AdminMailProviderError("provider_not_configured");
return refreshMicrosoftAccessToken(config, refreshToken);
},
send: sendGraphMail,
},
};
}
function normalizeAccount(account: AdminMailAccount): AdminMailAccount {
const emailAddress = account.emailAddress.trim().toLowerCase();
const externalAccountId = account.externalAccountId.trim();
if (
!externalAccountId ||
!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(emailAddress)
) {
throw new AdminMailProviderError("invalid_provider_account");
}
return Object.freeze({
externalAccountId,
emailAddress,
displayName: account.displayName?.trim() || null,
});
}
function requiredCode(code: string): string {
const normalized = code.trim();
if (!normalized || normalized.length > 8_192) {
throw new AdminMailProviderError("invalid_oauth_code");
}
return normalized;
}
export class AdminMailProviderError extends Error {
readonly code:
| "provider_not_configured"
| "invalid_oauth_code"
| "refresh_token_missing"
| "invalid_provider_account";
constructor(code: AdminMailProviderError["code"]) {
super(code);
this.name = "AdminMailProviderError";
this.code = code;
}
}