Skip to main content

Shared Libraries

Importing

import { JwtAuthGuard, OrgAccessGuard, CurrentUser, CurrentOrg, ProductAccess } from '@app/auth';
import { PaginationQueryDto, ApiResponse, initSentry, captureException } from '@app/common';
import { BaseEntity, Organization, OrgProductSubscription, User } from '@app/database';
import { EmailService } from '@app/email';

@app/auth

Guards

  • JwtAuthGuard - Validates Cognito JWT (global, applied via APP_GUARD)
  • OrgAccessGuard - Validates organization membership, attaches request.organization
  • OrgRolesGuard - Validates organization role (admin, owner, etc.)
  • OrgProductAccessGuard - Validates per-product role with hierarchy checks
  • PlatformAdminGuard - Restricts to Cognito PlatformAdmins group
  • ScimAuthGuard - Validates SCIM bearer tokens (SHA256 hash lookup)

Decorators

  • @CurrentUser() or @User() - Get authenticated user (supports @User('userId'))
  • @CurrentOrg() - Get validated organization (set by OrgAccessGuard)
  • @Public() - Skip JWT validation
  • @OrgRoles('admin', 'owner') - Require org roles
  • @ProductAccess('alerting', 'manager') - Require product-specific role
  • @PlatformAdmin() - Require platform admin

The AuthCookieController provides httpOnly cookie-based auth endpoints (registered on all APIs):

EndpointMethodAuthDescription
/auth/set-cookiePOSTJWTStore tokens in httpOnly cookies
/auth/meGETCookie/JWTGet current user from session
/auth/refreshPOSTCookieRefresh tokens using refresh cookie
/auth/logoutPOSTPublicClear httpOnly auth cookies

Token Extraction Priority

JwtStrategy extracts tokens in this order:

  1. httpOnly cookie statux_id_token (browser requests)
  2. Authorization: Bearer header (API clients, mobile, testing)

Impersonation

Platform admins can impersonate users by setting the x-impersonate-user-id header. The original admin's identity is preserved in user.originalUserId and user.originalEmail.

@app/common

Response Format

All responses wrapped in envelope:

{ "data": { ... } }

Paginated:

{ "data": [...], "meta": { "page": 1, "limit": 20, "total": 100, "totalPages": 5 } }

EncryptionService

const encrypted = this.encryptionService.encrypt('secret');
const decrypted = this.encryptionService.decrypt(encrypted);

Sentry Integration

All APIs initialize Sentry on startup via initSentry(). The HttpExceptionFilter (applied globally) calls captureException() for all 500+ errors with request context.

// In main.ts — SENTRY_DSN loaded from Secrets Manager via config loader
initSentry({ dsn: process.env.SENTRY_DSN || '', service: 'alerting-api' });

Config Loader

loadSecretsConfig() fetches configuration from AWS Secrets Manager and forwards SENTRY_DSN to process.env for use by initSentry().

@app/database

BaseEntity

export class MyEntity extends BaseEntity {
// Inherits: id (UUID), createdAt, updatedAt
}

Shared Entities

EntityTableDescription
Organizationcore.organizationsOrg name, slug, branding
OrganizationMembercore.organization_membersMembership + invite fields
OrgProductRolecore.org_product_rolesPer-product role assignments
OrgProductSubscriptioncore.org_product_subscriptionsPer-product-per-org licensing
Usercore.userscognitoSub, email, isEmployee flag
Subscriptioncore.subscriptionsLegacy per-user subscription
ScimTokencore.scim_tokensSCIM 2.0 provisioning tokens
AnalyticsEventcore.analytics_eventsProduct usage telemetry
UserActivitycore.user_activitiesLast seen tracking
Product enum-statuspages, alerting, synthetics, insights

Product Access

  • OrgProductAccessGuard + @ProductAccess() decorator - Checks OrgProductRole for product access
  • ProductAccessService / ProductAccessModule - Queries active/trial subscriptions, returns accessible products per user
  • Org OWNER/GLOBAL_ADMIN/ADMIN bypass product role checks automatically

@app/email

AWS SES email service (replaced Resend SDK). Global module registered across all apps.

import { EmailService } from '@app/email';

// Plain text email
await this.emailService.sendText({
to: 'user@example.com',
subject: 'Hello',
body: 'Message content',
});

// HTML email
await this.emailService.sendHtml({
to: 'user@example.com',
subject: 'Hello',
htmlBody: '<h1>Welcome</h1>',
});

Includes escapeHtml() for XSS prevention in HTML templates and sanitizeFromName() for From header injection protection.

@app/billing

BillingService

Handles Stripe integration for the Platform API:

  • createCheckoutSession() - Create a Stripe checkout session
  • createBillingPortalSession() - Generate billing portal URL
  • constructWebhookEvent() - Validate and parse Stripe webhooks
  • getOrCreateCustomer() - Find or create Stripe customer