MicProtocol / apps /api /dist /main.js
Benaah's picture
Upload folder using huggingface_hub (part 2)
9f29339 verified
Raw History Blame Contribute Delete
12.5 kB
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const core_1 = require("@nestjs/core");
const common_1 = require("@nestjs/common");
const swagger_1 = require("@nestjs/swagger");
const config_1 = require("@nestjs/config");
const helmet_1 = __importDefault(require("helmet"));
const compression_1 = __importDefault(require("compression"));
const cookie_parser_1 = __importDefault(require("cookie-parser"));
const crypto_1 = require("crypto");
const Sentry = __importStar(require("@sentry/nestjs"));
const origin_policy_1 = require("./common/origin-policy");
const auth_config_1 = require("./auth/auth.config");
const node_1 = require("better-auth/node");
const app_module_1 = require("./app.module");
const trpc_service_1 = require("./trpc/trpc.service");
const all_exceptions_filter_1 = require("./common/filters/all-exceptions.filter");
async function bootstrap() {
const logger = new common_1.Logger("Bootstrap");
const nodeEnv = process.env.NODE_ENV || "development";
process.on("unhandledRejection", (reason) => {
logger.error(`Unhandled Rejection: ${reason instanceof Error ? reason.message : String(reason)}`);
});
process.on("uncaughtException", (error) => {
logger.error(`Uncaught Exception: ${error.message}`);
setTimeout(() => process.exit(1), 1000);
});
const sentryTraceSampleRate = Number(process.env.SENTRY_TRACE_SAMPLE_RATE ?? (nodeEnv === "production" ? 0.1 : 1.0));
const sentryProfileSampleRate = Number(process.env.SENTRY_PROFILE_SAMPLE_RATE ?? (nodeEnv === "production" ? 0.05 : 1.0));
if (process.env.SENTRY_DSN) {
const integrations = [];
try {
const { nodeProfilingIntegration } = require("@sentry/profiling-node");
if (typeof nodeProfilingIntegration === "function") {
integrations.push(nodeProfilingIntegration());
}
}
catch {
logger.warn("Sentry profiling integration could not be loaded (Node version or platform mismatch)");
}
Sentry.init({
dsn: process.env.SENTRY_DSN,
integrations,
tracesSampleRate: Number.isFinite(sentryTraceSampleRate) ? sentryTraceSampleRate : 0.1,
profileSessionSampleRate: Number.isFinite(sentryProfileSampleRate) ? sentryProfileSampleRate : 0.05,
environment: nodeEnv,
});
logger.log("Sentry initialized");
}
const app = await core_1.NestFactory.create(app_module_1.AppModule, {
logger: ["error", "warn", "log", "debug", "verbose"],
rawBody: true,
});
const config = app.get(config_1.ConfigService);
const port = config.get("API_PORT", 4000);
const webUrl = config.get("WEB_URL", "http://localhost:3000");
const apiUrl = config.get("API_URL", `http://localhost:${port}`);
const apiLogger = new common_1.Logger("API");
const frontendUrl = config.get("FRONTEND_URL");
if (process.env.SENTRY_DSN) {
Sentry.setupExpressErrorHandler(app);
}
app.use((0, helmet_1.default)({
contentSecurityPolicy: nodeEnv === "production" ? undefined : false,
crossOriginEmbedderPolicy: nodeEnv === "production",
}));
app.use((0, compression_1.default)());
const cookieSecret = config.get("COOKIE_SECRET");
if (!cookieSecret) {
apiLogger.warn("COOKIE_SECRET is not set. Using a random secret — this will invalidate all sessions on restart.");
}
app.use((0, cookie_parser_1.default)(cookieSecret || (0, crypto_1.randomUUID)()));
app.use((req, res, next) => {
if (!req.cookies?.["csrf-token"]) {
res.cookie("csrf-token", (0, crypto_1.randomBytes)(24).toString("hex"), {
httpOnly: false,
secure: nodeEnv === "production",
sameSite: "strict",
path: "/",
});
}
next();
});
app.use((req, res, next) => {
if (["GET", "HEAD", "OPTIONS"].includes(req.method))
return next();
if (req.headers.authorization?.startsWith("Bearer "))
return next();
if (!req.cookies?.["sessionId"])
return next();
const csrfCookie = req.cookies?.["csrf-token"];
const csrfHeader = req.headers["x-csrf-token"];
if (!csrfCookie || !csrfHeader || csrfCookie !== csrfHeader) {
res.status(403).json({ message: "CSRF validation failed" });
return;
}
next();
});
app.use((req, res, next) => {
const startedAt = Date.now();
const requestIdHeader = req.headers["x-request-id"];
const requestId = (Array.isArray(requestIdHeader) ? requestIdHeader[0] : requestIdHeader) ||
(0, crypto_1.randomUUID)();
res.setHeader("x-request-id", requestId);
res.on("finish", () => {
const durationMs = Date.now() - startedAt;
const workspaceId = req.headers["x-workspace-id"] || "-";
const message = `${req.method} ${req.originalUrl} ${res.statusCode} ${durationMs}ms reqId=${requestId} workspace=${workspaceId}`;
if (res.statusCode >= 500) {
apiLogger.error(message);
}
else if (res.statusCode >= 400) {
apiLogger.warn(message);
}
else {
apiLogger.log(message);
}
});
next();
});
app.enableCors({
origin: (origin, callback) => {
callback(null, (0, origin_policy_1.isOriginAllowed)(origin, [webUrl, frontendUrl]));
},
credentials: true,
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
allowedHeaders: [
"Content-Type",
"Authorization",
"X-Requested-With",
"X-Workspace-Id",
"X-CSRF-Token",
"X-Subdomain",
"Accept",
"Origin",
],
exposedHeaders: ["X-Total-Count", "X-Page-Count"],
});
app.setGlobalPrefix("api", {
exclude: [
"/",
"/health",
"/health/detailed",
"/health/ready",
"/health/live",
"/trpc/*path",
],
});
app.enableVersioning({
type: common_1.VersioningType.URI,
defaultVersion: "1",
});
app.useGlobalPipes(new common_1.ValidationPipe({
whitelist: true,
forbidNonWhitelisted: true,
transform: true,
transformOptions: {
enableImplicitConversion: true,
},
validateCustomDecorators: true,
}));
const swaggerConfig = new swagger_1.DocumentBuilder()
.setTitle("MicProtocol API")
.setDescription(`# MicProtocol - Podcast Guest Management Platform\n\n` +
`## Overview\n` +
`MicProtocol is a domain-driven podcast guest management platform that automates ` +
`outreach, scheduling, asset collection, and promotion workflows.\n\n` +
`## Features\n` +
`- **Guest Management**: Track prospects, contacts, and published guests\n` +
`- **Outreach Automation**: Email sequences with tracking\n` +
`- **Scheduling**: Calendar integration and booking management\n` +
`- **Asset Collection**: Request and manage guest assets\n` +
`- **Content Studio**: Transcription and viral clip generation\n` +
`- **Analytics**: Performance metrics and insights\n\n` +
`## Authentication\n` +
`This API uses Better Auth for session-based authentication:\n` +
`- HTTP-only cookies for XSS protection\n` +
`- Redis-backed session cache with PostgreSQL persistence\n` +
`- bcrypt password hashing (configurable rounds)\n` +
`Login via POST /api/auth/sign-in/email to receive a session cookie.\n\n` +
`## tRPC Endpoint\n` +
`For type-safe real-time operations, use the tRPC endpoint at \`/trpc\``)
.setVersion("1.0.0")
.setContact("MicProtocol Support", "https://MicProtocol.io", "support@micprotocol.io")
.setLicense("Private - All rights reserved", "")
.addCookieAuth("better-auth.session_token", {
type: "apiKey",
in: "cookie",
description: "Better Auth session cookie",
}, "session")
.addApiKey({
type: "apiKey",
in: "header",
name: "X-Workspace-Id",
description: "Workspace ID for multi-tenant operations",
}, "workspace-id")
.addTag("Health", "System health and status endpoints")
.addTag("Guests", "Guest management operations")
.addTag("Outreach", "Email sequences and outreach automation")
.addTag("Scheduling", "Episode scheduling and booking")
.addTag("Assets", "Asset requests and submissions")
.addTag("Analytics", "Performance metrics and reporting")
.addTag("Content Studio", "Transcription and clip generation")
.addServer(apiUrl, "Production API")
.addServer("http://localhost:4000", "Local Development")
.build();
const document = swagger_1.SwaggerModule.createDocument(app, swaggerConfig, {
operationIdFactory: (controllerKey, methodKey) => `${controllerKey.replace("Controller", "").toLowerCase()}_${methodKey}`,
});
const enableSwagger = nodeEnv !== "production" ||
config.get("ENABLE_SWAGGER") === "true";
if (enableSwagger) {
swagger_1.SwaggerModule.setup("api/docs", app, document, {
swaggerOptions: {
persistAuthorization: true,
docExpansion: "list",
filter: true,
showRequestDuration: true,
tryItOutEnabled: true,
},
customSiteTitle: "MicProtocol API Documentation",
customCss: `
.swagger-ui .topbar { display: none }
.swagger-ui .info { margin: 20px 0 }
.swagger-ui .scheme-container { background: #f8f9fa }
`,
});
}
const expressApp = app.getHttpAdapter().getInstance();
expressApp.all(["/api/auth", "/api/auth/*path"], (0, node_1.toNodeHandler)(auth_config_1.auth));
const trpcService = app.get(trpc_service_1.TrpcService);
await trpcService.applyMiddleware(app);
app.useGlobalFilters(new all_exceptions_filter_1.AllExceptionsFilter());
app.enableShutdownHooks();
await app.listen(port, "0.0.0.0");
logger.log(`Server started on port ${port} (${nodeEnv})`);
console.log(`
MicProtocol API is running!
HTTP Server: http://localhost:${port}
API Docs: http://localhost:${port}/api/docs
tRPC Endpoint: http://localhost:${port}/trpc
Health Check: http://localhost:${port}/health (and /health/detailed, /health/ready, /health/live)
Environment: ${nodeEnv}
CORS Origins: ${webUrl}, http://localhost:3000
Ready to manage your podcast guests like a pro!
`);
}
bootstrap();
//# sourceMappingURL=main.js.map