Spaces:
Sleeping
Sleeping
Download apps/api/dist/integrations/integrations.service.js from Benaah/MicProtocol: direct link, hf CLI and curl.
- Browser
- Download file 62 kB
-
https://huggingface.co/spaces/Benaah/MicProtocol/resolve/main/apps/api/dist/integrations/integrations.service.js
- Command line
-
hf download hf://spaces/Benaah/MicProtocol/apps/api/dist/integrations/integrations.service.js
-
curl -L -o integrations.service.js https://huggingface.co/spaces/Benaah/MicProtocol/resolve/main/apps/api/dist/integrations/integrations.service.js
62 kB
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var IntegrationsService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntegrationsService = void 0;
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const crypto_1 = require("crypto");
const prisma_service_1 = require("../prisma/prisma.service");
const shared_types_1 = require("@micprotocol/shared-types");
const subscription_credentials_service_1 = require("../billing/subscription-credentials.service");
const self_hosted_clients_service_1 = require("./clients/self-hosted-clients.service");
const redis_constants_1 = require("../common/redis.constants");
let IntegrationsService = IntegrationsService_1 = class IntegrationsService {
prisma;
configService;
subscriptionCredentialsService;
selfHostedClients;
redis;
logger = new common_1.Logger(IntegrationsService_1.name);
oauthConfigs;
selfHostedConfigs;
oauthStateCache = new Map();
constructor(prisma, configService, subscriptionCredentialsService, selfHostedClients, redis) {
this.prisma = prisma;
this.configService = configService;
this.subscriptionCredentialsService = subscriptionCredentialsService;
this.selfHostedClients = selfHostedClients;
this.redis = redis;
const baseRedirect = this.configService.get("API_URL", "http://localhost:4000");
this.oauthConfigs = {
google_calendar: {
clientId: this.configService.get("GOOGLE_CLIENT_ID", ""),
clientSecret: this.configService.get("GOOGLE_CLIENT_SECRET", ""),
authUrl: "https://accounts.google.com/o/oauth2/v2/auth",
tokenUrl: "https://oauth2.googleapis.com/token",
scopes: [
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/calendar.events",
],
redirectUri: `${baseRedirect}/api/integrations/google/callback`,
},
google_mail: {
clientId: this.configService.get("GOOGLE_CLIENT_ID", ""),
clientSecret: this.configService.get("GOOGLE_CLIENT_SECRET", ""),
authUrl: "https://accounts.google.com/o/oauth2/v2/auth",
tokenUrl: "https://oauth2.googleapis.com/token",
scopes: [
"https://www.googleapis.com/auth/gmail.send",
"https://www.googleapis.com/auth/gmail.compose",
"https://www.googleapis.com/auth/gmail.modify",
],
redirectUri: `${baseRedirect}/api/integrations/google/callback`,
},
outlook: {
clientId: this.configService.get("OUTLOOK_CLIENT_ID", ""),
clientSecret: this.configService.get("OUTLOOK_CLIENT_SECRET", ""),
authUrl: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
tokenUrl: "https://login.microsoftonline.com/common/oauth2/v2.0/token",
scopes: [
"https://graph.microsoft.com/Calendars.ReadWrite",
"https://graph.microsoft.com/Mail.Send",
"https://graph.microsoft.com/User.Read",
],
redirectUri: `${baseRedirect}/api/integrations/outlook/callback`,
},
riverside: {
clientId: this.configService.get("RIVERSIDE_API_KEY", ""),
clientSecret: "",
authUrl: "https://riverside.fm/api/v2/authorize",
tokenUrl: "https://riverside.fm/api/v2/token",
scopes: ["rooms:create", "rooms:read", "recordings:read"],
redirectUri: `${baseRedirect}/api/integrations/riverside/callback`,
},
zoom: {
clientId: this.configService.get("ZOOM_CLIENT_ID", ""),
clientSecret: this.configService.get("ZOOM_CLIENT_SECRET", ""),
authUrl: "https://zoom.us/oauth/authorize",
tokenUrl: "https://zoom.us/oauth/token",
scopes: ["meeting:write", "meeting:read", "user:read"],
redirectUri: `${baseRedirect}/api/integrations/zoom/callback`,
},
cloudflare_r2: {
clientId: this.configService.get("CLOUDFLARE_R2_ACCESS_KEY_ID", ""),
clientSecret: this.configService.get("CLOUDFLARE_R2_SECRET_ACCESS_KEY", ""),
authUrl: "",
tokenUrl: "",
scopes: [
"read",
"write",
"delete",
"list",
],
redirectUri: "",
},
};
this.selfHostedConfigs = {
calcom: {
baseUrl: this.configService.get("CALCOM_URL", "http://localhost:3002"),
apiKeyEnv: "CALCOM_API_KEY",
webhookSecretEnv: "CALCOM_WEBHOOK_SECRET",
healthEndpoint: "/api/health",
},
chatwoot: {
baseUrl: this.configService.get("CHATWOOT_URL", "http://localhost:3005"),
apiKeyEnv: "CHATWOOT_API_KEY",
webhookSecretEnv: "CHATWOOT_WEBHOOK_SECRET",
healthEndpoint: "/health",
},
documenso: {
baseUrl: this.configService.get("DOCUMENSO_URL", "http://localhost:3004"),
apiKeyEnv: "DOCUMENSO_API_KEY",
webhookSecretEnv: "DOCUMENSO_WEBHOOK_SECRET",
healthEndpoint: "/api/health",
},
formbricks: {
baseUrl: this.configService.get("FORMBRICKS_URL", "http://localhost:3001"),
apiKeyEnv: "FORMBRICKS_API_KEY",
webhookSecretEnv: "FORMBRICKS_WEBHOOK_SECRET",
healthEndpoint: "/api/health",
},
listmonk: {
baseUrl: this.configService.get("LISTMONK_URL", "http://localhost:9000"),
apiKeyEnv: "LISTMONK_API_TOKEN",
webhookSecretEnv: "",
healthEndpoint: "/health",
},
pretix: {
baseUrl: this.configService.get("PRETIX_URL", "http://pretix:8000"),
apiKeyEnv: "PRETIX_API_KEY",
webhookSecretEnv: "PRETIX_WEBHOOK_SECRET",
healthEndpoint: "/health",
},
};
}
async resolveCredentialsWithTier(workspaceId, provider) {
return this.subscriptionCredentialsService.resolveCredentials(workspaceId, provider);
}
async listIntegrations(workspaceId, userId) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integrations = await this.prisma.workspaceIntegration.findMany({
where: { workspaceId },
orderBy: { createdAt: "desc" },
});
return integrations.map((integration) => {
const config = this.oauthConfigs[integration.provider];
return {
id: integration.id,
workspaceId: integration.workspaceId,
provider: integration.provider,
status: integration.status,
providerAccountId: integration.providerAccountId,
providerEmail: integration.providerEmail,
providerName: integration.providerName,
scopes: integration.scopes,
lastSyncAt: integration.lastSyncAt,
errorMessage: integration.errorMessage,
metadata: integration.metadata,
createdAt: integration.createdAt,
updatedAt: integration.updatedAt,
isConfigurable: !!config?.clientId,
hasValidConfig: this.isProviderConfigured(integration.provider),
};
});
}
async getIntegration(workspaceId, provider, userId) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.prisma.workspaceIntegration.findUnique({
where: {
workspaceId_provider: {
workspaceId,
provider: provider,
},
},
});
if (!integration) {
return null;
}
return {
id: integration.id,
workspaceId: integration.workspaceId,
provider: integration.provider,
status: integration.status,
providerAccountId: integration.providerAccountId,
providerEmail: integration.providerEmail,
providerName: integration.providerName,
scopes: integration.scopes,
lastSyncAt: integration.lastSyncAt,
errorMessage: integration.errorMessage,
metadata: integration.metadata,
createdAt: integration.createdAt,
updatedAt: integration.updatedAt,
};
}
async disconnectIntegration(workspaceId, provider, userId) {
await this.ensureWorkspacePermission(workspaceId, userId);
const integration = await this.prisma.workspaceIntegration.findUnique({
where: {
workspaceId_provider: {
workspaceId,
provider: provider,
},
},
});
if (!integration) {
throw new common_1.NotFoundException(`Integration ${provider} not found for this workspace`);
}
await this.revokeProviderTokens(integration);
await this.prisma.workspaceIntegration.update({
where: { id: integration.id },
data: {
status: "disconnected",
accessToken: null,
refreshToken: null,
tokenExpiresAt: null,
providerAccountId: null,
providerEmail: null,
providerName: null,
errorMessage: null,
},
});
this.logger.log(`Disconnected ${provider} for workspace ${workspaceId}`);
return { success: true, message: `${provider} integration disconnected` };
}
async getAuthUrl(workspaceId, provider, userId) {
await this.ensureWorkspacePermission(workspaceId, userId);
const config = this.oauthConfigs[provider];
const selfHosted = this.selfHostedConfigs[provider];
if (selfHosted) {
return selfHosted.baseUrl;
}
if (!config || !config.clientId) {
throw new common_1.BadRequestException(`Provider ${provider} is not configured. Set up API keys in environment variables first.`);
}
if (provider === "cloudflare_r2") {
return "";
}
const state = (0, crypto_1.randomBytes)(24).toString("hex");
await this.storeOAuthState(state, { workspaceId, provider, userId });
const params = new URLSearchParams({
client_id: config.clientId,
redirect_uri: config.redirectUri,
response_type: "code",
scope: config.scopes.join(" "),
state,
access_type: "offline",
prompt: "consent",
});
return `${config.authUrl}?${params.toString()}`;
}
async handleOAuthCallback(code, state) {
const stateData = await this.consumeOAuthState(state);
if (!stateData) {
throw new common_1.BadRequestException("Invalid or expired OAuth state parameter");
}
const { workspaceId, provider, userId } = stateData;
const config = this.oauthConfigs[provider];
if (!config) {
throw new common_1.BadRequestException(`Unknown provider: ${provider}`);
}
let tokens;
try {
tokens = await this.exchangeOAuthCode(provider, code, config);
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.logger.error(`OAuth token exchange failed for ${provider}: ${message}`);
await this.upsertIntegration(workspaceId, provider, {
status: "error",
errorMessage: `OAuth token exchange failed: ${message}`,
});
return { workspaceId, provider, success: false };
}
let accountInfo = null;
try {
accountInfo = await this.fetchProviderAccountInfo(provider, tokens.accessToken);
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.logger.warn(`Could not fetch account info for ${provider}: ${message}`);
}
await this.upsertIntegration(workspaceId, provider, {
status: "connected",
accessToken: tokens.accessToken,
refreshToken: tokens.refreshToken,
tokenExpiresAt: tokens.expiresAt,
scopes: config.scopes,
providerAccountId: accountInfo?.id ?? null,
providerEmail: accountInfo?.email ?? null,
providerName: accountInfo?.name ?? null,
errorMessage: null,
lastSyncAt: new Date(),
});
this.logger.log(`Successfully connected ${provider} for workspace ${workspaceId}`);
return { workspaceId, provider, success: true };
}
async updateApiKeyIntegration(workspaceId, provider, userId, credentials) {
await this.ensureWorkspacePermission(workspaceId, userId);
const selfHosted = this.selfHostedConfigs[provider];
const isSelfHosted = !!selfHosted;
const isCloudflare = provider === "cloudflare_r2";
if (!isSelfHosted && !isCloudflare) {
throw new common_1.BadRequestException("API key update is only supported for self-hosted integrations (calcom, chatwoot, documenso, formbricks, listmonk, pretix) and Cloudflare R2");
}
if (isCloudflare) {
if (!credentials.accessKeyId || !credentials.secretAccessKey) {
throw new common_1.BadRequestException("Access Key ID and Secret Access Key are required");
}
await this.upsertIntegration(workspaceId, provider, {
status: "connected",
accessToken: credentials.secretAccessKey,
providerAccountId: credentials.accessKeyId,
providerName: credentials.accountId || null,
scopes: ["read", "write", "delete", "list"],
errorMessage: null,
lastSyncAt: new Date(),
metadata: {
accessKeyId: credentials.accessKeyId,
accountId: credentials.accountId || null,
endpoint: `https://${credentials.accountId || ""}.r2.cloudflarestorage.com`,
},
});
return { success: true, message: "Cloudflare R2 integration updated" };
}
if (isSelfHosted) {
if (!credentials.apiKey) {
throw new common_1.BadRequestException(`API key is required for ${provider}`);
}
await this.upsertIntegration(workspaceId, provider, {
status: "connected",
accessToken: credentials.apiKey,
providerName: provider,
scopes: ["read", "write"],
errorMessage: null,
lastSyncAt: new Date(),
metadata: {
baseUrl: credentials.baseUrl || selfHosted.baseUrl,
webhookSecret: credentials.webhookSecret || "",
},
});
this.logger.log(`Connected ${provider} for workspace ${workspaceId}`);
return { success: true, message: `${provider} integration connected` };
}
}
async syncCalendarEvents(workspaceId, userId, provider) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.getValidatedIntegration(workspaceId, provider);
if (!integration.accessToken) {
throw new common_1.BadRequestException(`${provider} is not connected`);
}
try {
const events = await this.fetchCalendarEvents(provider, integration.accessToken);
for (const event of events) {
await this.prisma.integrationEvent.upsert({
where: {
integrationId_providerEventId: {
integrationId: integration.id,
providerEventId: event.id || "",
},
},
create: {
integrationId: integration.id,
providerEventId: event.id || "",
title: event.title,
description: event.description || null,
startTime: new Date(event.startTime),
endTime: new Date(event.endTime),
timezone: event.timezone || "UTC",
location: event.location || null,
meetLink: event.meetLink || null,
attendees: event.attendees || [],
isSynced: true,
lastSyncedAt: new Date(),
},
update: {
title: event.title,
description: event.description || null,
startTime: new Date(event.startTime),
endTime: new Date(event.endTime),
timezone: event.timezone || "UTC",
location: event.location || null,
meetLink: event.meetLink || null,
attendees: event.attendees || [],
isSynced: true,
lastSyncedAt: new Date(),
},
});
}
await this.prisma.workspaceIntegration.update({
where: { id: integration.id },
data: { lastSyncAt: new Date() },
});
return {
success: true,
syncedCount: events.length,
message: `Synced ${events.length} calendar events`,
};
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.logger.error(`Calendar sync failed for ${provider}: ${message}`);
throw new common_1.BadRequestException(`Calendar sync failed: ${message}`);
}
}
async getSyncedEvents(workspaceId, provider, userId, timeMin, timeMax) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.prisma.workspaceIntegration.findUnique({
where: {
workspaceId_provider: {
workspaceId,
provider,
},
},
});
if (!integration)
return [];
const whereClause = {
integrationId: integration.id,
};
if (timeMin || timeMax) {
whereClause.OR = [];
if (timeMin) {
whereClause.OR.push({ startTime: { gte: new Date(timeMin) } });
}
if (timeMax) {
whereClause.OR.push({ endTime: { lte: new Date(timeMax) } });
}
}
return this.prisma.integrationEvent.findMany({
where: whereClause,
orderBy: { startTime: "asc" },
take: 200,
});
}
async createCalendarEvent(workspaceId, userId, provider, eventData) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.getValidatedIntegration(workspaceId, provider);
if (!integration.accessToken) {
throw new common_1.BadRequestException(`${provider} is not connected`);
}
try {
const providerEvent = await this.createProviderEvent(provider, integration.accessToken, eventData);
if (providerEvent?.id) {
await this.prisma.integrationEvent.create({
data: {
integrationId: integration.id,
providerEventId: providerEvent.id,
title: eventData.title,
description: eventData.description || null,
startTime: new Date(eventData.startTime),
endTime: new Date(eventData.endTime),
timezone: eventData.timezone || "UTC",
location: eventData.location || null,
meetLink: providerEvent.meetLink || eventData.meetLink || null,
attendees: eventData.attendees || [],
isSynced: true,
lastSyncedAt: new Date(),
},
});
}
return { success: true, providerEventId: providerEvent?.id, meetLink: providerEvent?.meetLink };
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.logger.error(`Failed to create calendar event on ${provider}: ${message}`);
throw new common_1.BadRequestException(`Failed to create event: ${message}`);
}
}
async getIntegrationStats(workspaceId, userId) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integrations = await this.prisma.workspaceIntegration.findMany({
where: { workspaceId },
});
const total = integrations.length;
const connected = integrations.filter((i) => i.status === "connected").length;
const withErrors = integrations.filter((i) => i.status === "error").length;
const providerStatuses = {};
for (const integration of integrations) {
providerStatuses[integration.provider] = integration.status;
}
return {
total,
connected,
withErrors,
providerStatuses,
};
}
async getProviderMetrics() {
return this.selfHostedClients.getMetrics();
}
async getAllProviders() {
const providers = [
{
id: "google_calendar",
name: "Google Calendar",
description: "Sync recording slots and availability. Automatically create events for bookings.",
icon: "calendar",
color: "#4285F4",
isOAuth: true,
isConfigured: this.isProviderConfigured("google_calendar"),
docsUrl: "https://developers.google.com/calendar",
},
{
id: "google_mail",
name: "Gmail",
description: "Send outreach sequences, booking confirmations, and follow-ups via your Gmail account.",
icon: "mail",
color: "#EA4335",
isOAuth: true,
isConfigured: this.isProviderConfigured("google_mail"),
docsUrl: "https://developers.google.com/gmail",
},
{
id: "outlook",
name: "Outlook Calendar & Mail",
description: "Sync with Microsoft 365 calendar and send emails via Outlook.",
icon: "mail",
color: "#0078D4",
isOAuth: true,
isConfigured: this.isProviderConfigured("outlook"),
docsUrl: "https://learn.microsoft.com/en-us/graph/",
},
{
id: "riverside",
name: "Riverside.fm",
description: "Auto-generate recording rooms and manage recordings from within MicProtocol.",
icon: "video",
color: "#6C5CE7",
isOAuth: true,
isConfigured: this.isProviderConfigured("riverside"),
docsUrl: "https://riverside.fm/api",
},
{
id: "zoom",
name: "Zoom",
description: "Create Zoom meetings for recordings and manage meeting settings.",
icon: "video",
color: "#2D8CFF",
isOAuth: true,
isConfigured: this.isProviderConfigured("zoom"),
docsUrl: "https://developers.zoom.us",
},
{
id: "cloudflare_r2",
name: "Cloudflare R2",
description: "Store audio recordings, video clips, and assets in Cloudflare R2 object storage.",
icon: "cloud",
color: "#F38020",
isOAuth: false,
isConfigured: this.isProviderConfigured("cloudflare_r2"),
docsUrl: "https://developers.cloudflare.com/r2/",
},
{
id: "calcom",
name: "Cal.com",
description: "Self-hosted scheduling and booking. Manage availability, event types, and automate booking confirmations.",
icon: "calendar",
color: "#3B82F6",
isOAuth: false,
isConfigured: this.isProviderConfigured("calcom"),
docsUrl: "https://cal.com/docs",
},
{
id: "chatwoot",
name: "Chatwoot",
description: "Self-hosted customer support platform. Live chat, helpdesk tickets, and omnichannel messaging.",
icon: "message-circle",
color: "#1F93FF",
isOAuth: false,
isConfigured: this.isProviderConfigured("chatwoot"),
docsUrl: "https://www.chatwoot.com/docs",
},
{
id: "documenso",
name: "Documenso",
description: "Self-hosted document e-signing. Send, sign, and manage contracts and agreements.",
icon: "file-signature",
color: "#7C3AED",
isOAuth: false,
isConfigured: this.isProviderConfigured("documenso"),
docsUrl: "https://documenso.com/docs",
},
{
id: "formbricks",
name: "Formbricks",
description: "Self-hosted surveys and feedback. Create in-app surveys, NPS polls, and customer experience analytics.",
icon: "square-poll-vertical",
color: "#0F172A",
isOAuth: false,
isConfigured: this.isProviderConfigured("formbricks"),
docsUrl: "https://formbricks.com/docs",
},
{
id: "listmonk",
name: "Listmonk",
description: "Self-hosted newsletter and email marketing. Manage mailing lists, campaigns, and transactional emails.",
icon: "mail",
color: "#10B981",
isOAuth: false,
isConfigured: this.isProviderConfigured("listmonk"),
docsUrl: "https://listmonk.app/docs",
},
{
id: "pretix",
name: "Pretix",
description: "Self-hosted ticketing and event registration. Manage events, tickets, orders, and QR-coded attendees.",
icon: "ticket",
color: "#F59E0B",
isOAuth: false,
isConfigured: this.isProviderConfigured("pretix"),
docsUrl: "https://docs.pretix.eu",
},
];
return providers;
}
async storeOAuthState(state, data) {
try {
await this.redis.setEx(`oauth:state:${state}`, 600, JSON.stringify(data));
}
catch {
this.oauthStateCache.set(state, {
...data,
expiresAt: Date.now() + 10 * 60 * 1000,
});
}
}
async consumeOAuthState(state) {
if (!state)
return null;
try {
const raw = await this.redis.get(`oauth:state:${state}`);
if (raw) {
await this.redis.del(`oauth:state:${state}`);
return JSON.parse(raw);
}
}
catch {
}
const cached = this.oauthStateCache.get(state);
if (cached) {
this.oauthStateCache.delete(state);
if (cached.expiresAt > Date.now())
return cached;
}
return null;
}
async exchangeOAuthCode(provider, code, config) {
const response = await fetch(config.tokenUrl, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
code,
client_id: config.clientId,
client_secret: config.clientSecret,
redirect_uri: config.redirectUri,
grant_type: "authorization_code",
}),
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`Token exchange failed: ${response.status} ${errorBody}`);
}
const data = (await response.json());
const expiresAt = new Date();
expiresAt.setSeconds(expiresAt.getSeconds() + (data.expires_in || 3600));
return {
accessToken: data.access_token,
refreshToken: data.refresh_token || "",
expiresAt,
};
}
async refreshAccessToken(provider, refreshToken) {
const config = this.oauthConfigs[provider];
if (!config)
throw new Error(`Unknown provider: ${provider}`);
const response = await fetch(config.tokenUrl, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
refresh_token: refreshToken,
client_id: config.clientId,
client_secret: config.clientSecret,
grant_type: "refresh_token",
}),
});
if (!response.ok) {
throw new Error(`Token refresh failed: ${response.status}`);
}
const data = (await response.json());
const expiresAt = new Date();
expiresAt.setSeconds(expiresAt.getSeconds() + (data.expires_in || 3600));
return {
accessToken: data.access_token,
expiresAt,
};
}
async revokeProviderTokens(integration) {
if (!integration.refreshToken)
return;
try {
const config = this.oauthConfigs[integration.provider];
if (config) {
await fetch(config.tokenUrl.replace("/token", "/revoke"), {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
token: integration.refreshToken,
client_id: config.clientId,
client_secret: config.clientSecret,
}),
});
}
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.logger.warn(`Token revocation failed for ${integration.provider}: ${message}`);
}
}
async getValidatedIntegration(workspaceId, provider) {
const integration = await this.prisma.workspaceIntegration.findUnique({
where: {
workspaceId_provider: {
workspaceId,
provider: provider,
},
},
});
if (!integration || integration.status !== "connected") {
try {
const resolved = await this.subscriptionCredentialsService.resolveCredentials(workspaceId, provider);
if (resolved.source === "platform" && resolved.accessToken) {
return {
id: `platform:${provider}`,
workspaceId,
provider,
status: "connected",
accessToken: resolved.accessToken,
refreshToken: resolved.refreshToken,
tokenExpiresAt: resolved.tokenExpiresAt,
scopes: resolved.scopes,
metadata: resolved.metadata,
_source: "platform",
};
}
if (resolved.source === "platform" && resolved.apiKey) {
return {
id: `platform:${provider}`,
workspaceId,
provider,
status: "connected",
accessToken: resolved.apiKey,
refreshToken: null,
tokenExpiresAt: null,
scopes: resolved.scopes,
metadata: {
...resolved.metadata,
_credentialType: "apiKey",
apiSecret: resolved.apiSecret,
endpointUrl: resolved.endpointUrl,
},
_source: "platform",
};
}
}
catch (tierError) {
const tierErr = tierError instanceof Error ? tierError : new Error(String(tierError));
if (tierErr.constructor?.name === "ForbiddenException" ||
tierErr.constructor?.name === "BadRequestException") {
throw tierErr;
}
this.logger.warn(`Tier credential resolution failed for ${provider}: ${tierErr.message}`);
}
throw new common_1.BadRequestException(`${provider} is not connected. Please connect it in Settings > Integrations first.`);
}
if (integration.tokenExpiresAt && new Date() >= integration.tokenExpiresAt && integration.refreshToken) {
try {
const newTokens = await this.refreshAccessToken(provider, integration.refreshToken);
await this.prisma.workspaceIntegration.update({
where: { id: integration.id },
data: {
accessToken: newTokens.accessToken,
tokenExpiresAt: newTokens.expiresAt,
},
});
return { ...integration, accessToken: newTokens.accessToken };
}
catch {
await this.prisma.workspaceIntegration.update({
where: { id: integration.id },
data: { status: "expired" },
});
throw new common_1.BadRequestException(`${provider} token expired. Please reconnect.`);
}
}
return integration;
}
async fetchProviderAccountInfo(provider, accessToken) {
try {
switch (provider) {
case "google_calendar":
case "google_mail": {
const resp = await fetch("https://www.googleapis.com/oauth2/v2/userinfo", {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (resp.ok) {
const d = (await resp.json());
return { id: d.id, email: d.email, name: d.name };
}
break;
}
case "outlook": {
const resp = await fetch("https://graph.microsoft.com/v1.0/me", {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (resp.ok) {
const d = (await resp.json());
return { id: d.id, email: d.mail || d.userPrincipalName, name: d.displayName };
}
break;
}
case "zoom": {
const resp = await fetch("https://api.zoom.us/v2/users/me", {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (resp.ok) {
const d = (await resp.json());
return { id: d.id, email: d.email, name: `${d.first_name} ${d.last_name}` };
}
break;
}
case "riverside": {
const resp = await fetch("https://riverside.fm/api/v2/me", {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (resp.ok) {
const d = (await resp.json());
return { id: d.id, email: d.email || "", name: d.name || "" };
}
break;
}
default:
break;
}
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.logger.warn(`Failed to fetch account info for ${provider}: ${message}`);
}
return null;
}
async fetchCalendarEvents(provider, accessToken) {
const timeMin = new Date();
timeMin.setDate(timeMin.getDate() - 30);
const timeMax = new Date();
timeMax.setDate(timeMax.getDate() + 90);
const params = new URLSearchParams({
timeMin: timeMin.toISOString(),
timeMax: timeMax.toISOString(),
singleEvents: "true",
orderBy: "startTime",
maxResults: "250",
});
let url;
if (provider === "google_calendar") {
url = `https://www.googleapis.com/calendar/v3/calendars/primary/events?${params}`;
}
else {
url = `https://graph.microsoft.com/v1.0/me/calendar/events?$top=250&$filter=start/dateTime ge '${timeMin.toISOString()}'`;
}
const response = await fetch(url, {
headers: { Authorization: `Bearer ${accessToken}` },
});
if (!response.ok) {
const errorBody = await response.text();
throw new Error(`Calendar API error: ${response.status} ${errorBody}`);
}
const data = (await response.json());
if (provider === "google_calendar") {
return (data.items || []).map((item) => ({
id: item.id || "",
title: item.summary || "Untitled Event",
description: item.description || undefined,
startTime: item.start?.dateTime || item.start?.date || "",
endTime: item.end?.dateTime || item.end?.date || "",
timezone: item.start?.timeZone || "UTC",
location: item.location || undefined,
meetLink: item.conferenceData?.entryPoints?.find((ep) => ep.entryPointType === "video")?.uri || undefined,
attendees: (item.attendees || []).map((a) => ({
email: a.email || "",
name: a.displayName || a.email || "",
})),
}));
}
else {
return (data.value || []).map((item) => ({
id: item.id || "",
title: item.subject || "Untitled Event",
description: item.bodyPreview || undefined,
startTime: item.start?.dateTime || item.start?.date || "",
endTime: item.end?.dateTime || item.end?.date || "",
timezone: item.start?.timeZone || "UTC",
location: item.location?.displayName || undefined,
meetLink: item.onlineMeetingUrl || undefined,
attendees: (item.attendees || []).map((a) => ({
email: a.emailAddress?.address || "",
name: a.emailAddress?.name || "",
})),
}));
}
}
async createProviderEvent(provider, accessToken, eventData) {
try {
if (provider === "google_calendar") {
const body = {
summary: eventData.title,
description: eventData.description || "",
start: {
dateTime: eventData.startTime,
timeZone: eventData.timezone || "UTC",
},
end: {
dateTime: eventData.endTime,
timeZone: eventData.timezone || "UTC",
},
location: eventData.location || undefined,
attendees: (eventData.attendees || []).map((a) => ({ email: a.email })),
conferenceData: {
createRequest: {
requestId: `micprotocol-${Date.now()}`,
conferenceSolutionKey: { type: "hangoutsMeet" },
},
},
};
const response = await fetch("https://www.googleapis.com/calendar/v3/calendars/primary/events?conferenceDataVersion=1", {
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
if (!response.ok)
throw new Error(`Google Calendar API error: ${response.status}`);
const gCalResult = (await response.json());
return {
id: gCalResult.id || "",
meetLink: gCalResult.hangoutLink || gCalResult.conferenceData?.entryPoints?.find((ep) => ep.entryPointType === "video")?.uri,
};
}
else {
const body = {
subject: eventData.title,
body: {
contentType: "HTML",
content: eventData.description || "",
},
start: {
dateTime: eventData.startTime,
timeZone: eventData.timezone || "UTC",
},
end: {
dateTime: eventData.endTime,
timeZone: eventData.timezone || "UTC",
},
location: eventData.location ? { displayName: eventData.location } : undefined,
attendees: (eventData.attendees || []).map((a) => ({
emailAddress: { address: a.email, name: a.name },
type: "required",
})),
isOnlineMeeting: true,
onlineMeetingProvider: "teamsForBusiness",
};
const response = await fetch("https://graph.microsoft.com/v1.0/me/events", {
method: "POST",
headers: {
Authorization: `Bearer ${accessToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
if (!response.ok)
throw new Error(`Outlook API error: ${response.status}`);
const outlookResult = (await response.json());
return {
id: outlookResult.id,
meetLink: outlookResult.onlineMeeting?.joinUrl || outlookResult.onlineMeetingUrl,
};
}
}
catch (error) {
const message = error instanceof Error ? error.message : String(error);
this.logger.error(`Failed to create provider event: ${message}`);
return null;
}
}
async upsertIntegration(workspaceId, provider, opts) {
const updateData = {
status: opts.status,
errorMessage: opts.errorMessage ?? null,
};
if (opts.accessToken !== undefined)
updateData.accessToken = opts.accessToken ?? undefined;
if (opts.refreshToken !== undefined)
updateData.refreshToken = opts.refreshToken ?? undefined;
if (opts.tokenExpiresAt !== undefined)
updateData.tokenExpiresAt = opts.tokenExpiresAt;
if (opts.scopes !== undefined)
updateData.scopes = opts.scopes;
if (opts.providerAccountId !== undefined)
updateData.providerAccountId = opts.providerAccountId ?? undefined;
if (opts.providerEmail !== undefined)
updateData.providerEmail = opts.providerEmail ?? undefined;
if (opts.providerName !== undefined)
updateData.providerName = opts.providerName ?? undefined;
if (opts.lastSyncAt !== undefined)
updateData.lastSyncAt = opts.lastSyncAt ?? undefined;
if (opts.metadata !== undefined)
updateData.metadata = opts.metadata;
return this.prisma.workspaceIntegration.upsert({
where: {
workspaceId_provider: {
workspaceId,
provider: provider,
},
},
create: {
workspaceId,
provider: provider,
status: opts.status,
errorMessage: opts.errorMessage,
accessToken: opts.accessToken ?? undefined,
refreshToken: opts.refreshToken ?? undefined,
tokenExpiresAt: opts.tokenExpiresAt ?? undefined,
scopes: opts.scopes ?? [],
providerAccountId: opts.providerAccountId ?? undefined,
providerEmail: opts.providerEmail ?? undefined,
providerName: opts.providerName ?? undefined,
lastSyncAt: opts.lastSyncAt ?? undefined,
metadata: opts.metadata ?? {},
},
update: {
status: opts.status,
errorMessage: opts.errorMessage,
accessToken: opts.accessToken ?? undefined,
refreshToken: opts.refreshToken ?? undefined,
tokenExpiresAt: opts.tokenExpiresAt ?? undefined,
scopes: opts.scopes,
providerAccountId: opts.providerAccountId ?? undefined,
providerEmail: opts.providerEmail ?? undefined,
providerName: opts.providerName ?? undefined,
lastSyncAt: opts.lastSyncAt ?? undefined,
metadata: opts.metadata !== undefined ? opts.metadata : undefined,
},
});
}
async listSelfHostedIntegrations(workspaceId, userId) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integrations = await this.prisma.workspaceIntegration.findMany({
where: {
workspaceId,
provider: { in: ["calcom", "chatwoot", "documenso", "formbricks", "listmonk", "pretix"] },
},
orderBy: { createdAt: "desc" },
});
return integrations.map((integration) => ({
id: integration.id,
workspaceId: integration.workspaceId,
provider: integration.provider,
status: integration.status,
providerName: integration.providerName,
lastSyncAt: integration.lastSyncAt,
errorMessage: integration.errorMessage,
metadata: integration.metadata,
createdAt: integration.createdAt,
}));
}
async updateWebhookSecret(workspaceId, provider, secret, userId) {
await this.ensureWorkspacePermission(workspaceId, userId);
const integration = await this.prisma.workspaceIntegration.findUnique({
where: {
workspaceId_provider: {
workspaceId,
provider: provider,
},
},
});
if (!integration) {
throw new common_1.NotFoundException(`${provider} integration not found for this workspace`);
}
await this.prisma.workspaceIntegration.update({
where: { id: integration.id },
data: {
metadata: {
...integration.metadata,
webhookSecret: secret,
},
},
});
this.logger.log(`Updated webhook secret for ${provider} on workspace ${workspaceId}`);
return { success: true, message: `Webhook secret updated for ${provider}` };
}
async sendEmail(workspaceId, data) {
const integration = await this.getValidatedIntegration(workspaceId, "google_mail");
const token = integration.accessToken;
if (!token)
throw new common_1.BadRequestException("Gmail access token not available");
return this.selfHostedClients.sendGmailMessage(token, data);
}
async createRiversideRoom(workspaceId, data) {
const integration = await this.getValidatedIntegration(workspaceId, "riverside");
const token = integration.accessToken;
if (!token)
throw new common_1.BadRequestException("Riverside access token not available");
return this.selfHostedClients.createRiversideRoom(token, data);
}
async createZoomMeeting(workspaceId, data) {
const integration = await this.getValidatedIntegration(workspaceId, "zoom");
const token = integration.accessToken;
if (!token)
throw new common_1.BadRequestException("Zoom access token not available");
return this.selfHostedClients.createZoomMeeting(token, data);
}
async uploadToR2(workspaceId, bucket, key, data, contentType) {
if (!this.isProviderConfigured("cloudflare_r2")) {
throw new common_1.BadRequestException("Cloudflare R2 is not configured");
}
const accessKeyId = this.configService.get("R2_ACCESS_KEY_ID", "");
const secretAccessKey = this.configService.get("R2_SECRET_ACCESS_KEY", "");
const accountId = this.configService.get("R2_ACCOUNT_ID", "");
return this.selfHostedClients.uploadToR2(bucket, key, data, contentType);
}
async downloadFromR2(workspaceId, bucket, key) {
if (!this.isProviderConfigured("cloudflare_r2")) {
throw new common_1.BadRequestException("Cloudflare R2 is not configured");
}
return this.selfHostedClients.downloadFromR2(bucket, key);
}
async deleteFromR2(workspaceId, bucket, key) {
if (!this.isProviderConfigured("cloudflare_r2")) {
throw new common_1.BadRequestException("Cloudflare R2 is not configured");
}
return this.selfHostedClients.deleteFromR2(bucket, key);
}
async sendDocument(workspaceId, data) {
const integration = await this.getValidatedIntegration(workspaceId, "documenso");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Documenso API key not available");
return this.selfHostedClients.sendDocument(apiKey, data);
}
async getDocumensoDocumentStatus(workspaceId, documentId) {
const integration = await this.getValidatedIntegration(workspaceId, "documenso");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Documenso API key not available");
return this.selfHostedClients.getDocumentStatus(apiKey, documentId);
}
async listCalComEventTypes(workspaceId, userId) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.getValidatedIntegration(workspaceId, "calcom");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Cal.com API key not available");
return this.selfHostedClients.listEventTypes();
}
async createCalComBooking(workspaceId, userId, data) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.getValidatedIntegration(workspaceId, "calcom");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Cal.com API key not available");
return this.selfHostedClients.createBooking(data.eventTypeId, {
start: data.start,
attendee: data.attendee,
meetingUrl: data.meetingUrl,
});
}
async getChatwootConversations(workspaceId, userId) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.getValidatedIntegration(workspaceId, "chatwoot");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Chatwoot API key not available");
const base = await this.selfHostedClients.getChatwootUrl();
const account = await this.selfHostedClients.chatwootAccountId();
return this.selfHostedClients.fetchWithRetry("chatwoot", "listConversations", `${base}/api/v1/accounts/${account}/conversations`, { headers: this.selfHostedClients.chatwootHeaders(apiKey), signal: AbortSignal.timeout(10000) }).then((body) => body.payload ?? []);
}
async getChatwootMessages(workspaceId, userId, conversationId) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.getValidatedIntegration(workspaceId, "chatwoot");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Chatwoot API key not available");
const base = await this.selfHostedClients.getChatwootUrl();
const account = await this.selfHostedClients.chatwootAccountId();
return this.selfHostedClients.fetchWithRetry("chatwoot", "getMessages", `${base}/api/v1/accounts/${account}/conversations/${conversationId}/messages`, { headers: this.selfHostedClients.chatwootHeaders(apiKey), signal: AbortSignal.timeout(10000) }).then((body) => body.payload ?? []);
}
async sendChatwootMessage(workspaceId, userId, data) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.getValidatedIntegration(workspaceId, "chatwoot");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Chatwoot API key not available");
return this.selfHostedClients.sendChatwootMessage(apiKey, data.conversationId, data.content);
}
async createChatwootConversation(workspaceId, userId, data) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.getValidatedIntegration(workspaceId, "chatwoot");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Chatwoot API key not available");
let contact;
try {
contact = await this.selfHostedClients.createChatwootContact(apiKey, data.contactName, data.contactEmail, data.contactPhone, data.customAttributes);
}
catch {
contact = { id: 0, name: data.contactName, email: data.contactEmail };
}
const conversation = await this.selfHostedClients.createChatwootConversation(apiKey, data.inboxId, contact.id, data.message);
return { conversation, contact };
}
async sendListmonkEmail(workspaceId, data) {
const integration = await this.getValidatedIntegration(workspaceId, "listmonk");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Listmonk API key not available");
return this.selfHostedClients.sendTransactional(apiKey, data);
}
async listListmonkLists(workspaceId) {
const integration = await this.getValidatedIntegration(workspaceId, "listmonk");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Listmonk API key not available");
return this.selfHostedClients.listLists(apiKey);
}
async createListmonkList(workspaceId, data) {
const integration = await this.getValidatedIntegration(workspaceId, "listmonk");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Listmonk API key not available");
return this.selfHostedClients.createList(apiKey, data.name, data.type ?? "public");
}
async subscribeListmonkSubscriber(workspaceId, data) {
const integration = await this.getValidatedIntegration(workspaceId, "listmonk");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Listmonk API key not available");
return this.selfHostedClients.subscribe(apiKey, data.listId, data.email, data.name, data.attrs);
}
async listPretixEvents(workspaceId, userId, organizer) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.getValidatedIntegration(workspaceId, "pretix");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Pretix API key not available");
return this.selfHostedClients.listPretixEvents(apiKey, organizer);
}
async listPretixItems(workspaceId, userId, organizer, event) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.getValidatedIntegration(workspaceId, "pretix");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Pretix API key not available");
return this.selfHostedClients.listPretixItems(apiKey, organizer, event);
}
async listPretixOrders(workspaceId, userId, organizer, event) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.getValidatedIntegration(workspaceId, "pretix");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Pretix API key not available");
return this.selfHostedClients.listPretixOrders(apiKey, organizer, event);
}
async listPretixOrderPositions(workspaceId, userId, organizer, event, order) {
await this.ensureWorkspaceAccess(workspaceId, userId);
const integration = await this.getValidatedIntegration(workspaceId, "pretix");
const apiKey = integration.accessToken;
if (!apiKey)
throw new common_1.BadRequestException("Pretix API key not available");
return this.selfHostedClients.listPretixOrderPositions(apiKey, organizer, event, order);
}
isProviderConfigured(provider) {
const config = this.oauthConfigs[provider];
const selfHosted = this.selfHostedConfigs[provider];
if (selfHosted) {
const apiKey = this.configService.get(selfHosted.apiKeyEnv, "");
return !!apiKey;
}
if (!config)
return false;
if (provider === "cloudflare_r2") {
return !!(config.clientId && config.clientSecret);
}
return !!(config.clientId && config.clientSecret);
}
async ensureWorkspaceAccess(workspaceId, userId) {
const membership = await this.prisma.workspaceMember.findUnique({
where: { userId_workspaceId: { userId, workspaceId } },
});
if (!membership) {
throw new common_1.NotFoundException("Workspace not found or access denied");
}
return membership;
}
async ensureWorkspacePermission(workspaceId, userId) {
const membership = await this.ensureWorkspaceAccess(workspaceId, userId);
const role = membership.role;
if (![shared_types_1.WorkspaceRole.OWNER, shared_types_1.WorkspaceRole.ADMIN].includes(role)) {
throw new common_1.ConflictException("Only workspace owners and admins can manage integrations");
}
return membership;
}
};
exports.IntegrationsService = IntegrationsService;
exports.IntegrationsService = IntegrationsService = IntegrationsService_1 = __decorate([
(0, common_1.Injectable)(),
__param(4, (0, common_1.Inject)(redis_constants_1.REDIS_CLIENT)),
__metadata("design:paramtypes", [prisma_service_1.PrismaService,
config_1.ConfigService,
subscription_credentials_service_1.SubscriptionCredentialsService,
self_hosted_clients_service_1.SelfHostedClientsService, Object])
], IntegrationsService);
//# sourceMappingURL=integrations.service.js.map
;
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
var IntegrationsService_1;
Object.defineProperty(exports, "__esModule", { value: true });
exports.IntegrationsService = void 0;
const common_1 = require("@nestjs/common");
const config_1 = require("@nestjs/config");
const crypto_1 = require("crypto");
const prisma_service_1 = require("../prisma/prisma.service");
const shared_types_1 = require("@micprotocol/shared-types");
const subscription_credentials_service_1 = require("../billing/subscription-credentials.service");
const self_hosted_clients_service_1 = require("./clients/self-hosted-clients.service");
const redis_constants_1 = require("../common/redis.constants");
let IntegrationsService = IntegrationsService_1 = class IntegrationsService {
prisma;
configService;
subscriptionCredentialsService;
selfHostedClients;
redis;
logger = new common_1.Logger(IntegrationsService_1.name);
oauthConfigs;
selfHostedConfigs;
oauthStateCache = new Map();
constructor(prisma, configService, subscriptionCredentialsService, selfHostedClients, redis) {
this.prisma = prisma;
this.configService = configService;
this.subscriptionCredentialsService = subscriptionCredentialsService;
this.selfHostedClients = selfHostedClients;
this.redis = redis;
const baseRedirect = this.configService.get("API_URL", "http://localhost:4000");
this.oauthConfigs = {
google_calendar: {
clientId: this.configService.get("GOOGLE_CLIENT_ID", ""),
clientSecret: this.configService.get("GOOGLE_CLIENT_SECRET", ""),
authUrl: "https://accounts.google.com/o/oauth2/v2/auth",
tokenUrl: "https://oauth2.googleapis.com/token",
scopes: [
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/calendar.events",
],
redirectUri: `${baseRedirect}/api/integrations/google/callback`,
},
google_mail: {
clientId: this.configService.get("GOOGLE_CLIENT_ID", ""),
clientSecret: this.configService.get("GOOGLE_CLIENT_SECRET", ""),
authUrl: "https://accounts.google.com/o/oauth2/v2/auth",
tokenUrl: "https://oauth2.googleapis.com/token",
scopes: [
"https://www.googleapis.com/auth/gmail.send",
"https://www.googleapis.com/auth/gmail.compose",
"https://www.googleapis.com/auth/gmail.modify",
],
redirectUri: `${baseRedirect}/api/integrations/google/callback`,
},
outlook: {
clientId: this.configService.get("OUTLOOK_CLIENT_ID", ""),
clientSecret: this.configService.get("OUTLOOK_CLIENT_SECRET", ""),
authUrl: "https://login.microsoftonline.com/common/oauth2/v2.0/authorize",
tokenUrl: "https://login.microsoftonline.com/common/oauth2/v2.0/token",
scopes: [
"https://graph.microsoft.com/Calendars.ReadWrite",
"https://graph.microsoft.com/Mail.Send",
"https://graph.microsoft.com/User.Read",
],
redirectUri: `${baseRedirect}/api/integrations/outlook/callback`,
},
riverside: {
clientId: this.configService.get("RIVERSIDE_API_KEY", ""),
clientSecret: "",
authUrl: "https://riverside.fm/api/v2/authorize",
tokenUrl: "https://riverside.fm/api/v2/token",
scopes: ["rooms:create", "rooms:read", "recordings:read"],
redirectUri: `${baseRedirect}/api/integrations/riverside/callback`,
},
zoom: {
clientId: this.configService.get("ZOOM_CLIENT_ID", ""),
clientSecret: this.configService.get("ZOOM_CLIENT_SECRET", ""),
authUrl: "https://zoom.us/oauth/authorize",
tokenUrl: "https://zoom.us/oauth/token",
scopes: ["meeting:write", "meeting:read", "user:read"],
redirectUri: `${baseRedirect}/api/integrations/zoom/callback`,
},
cloudflare_r2: {
clientId: this.configService.get("CLOUDFLARE_R2_ACCESS_KEY_ID", ""),
clientSecret: this.configService.get("CLOUDFLARE_R2_SECRET_ACCESS_KEY", ""),
authUrl: "",
tokenUrl: "",
scopes: [
"read",