import { createUniqueLegacyTenantIpAddress, adminGetAllLegacyTenants, findLegacyTenantById, findLegacyTenantByIdOrSlug, type LegacyTenantWithDetails, } from "@toolctrl/db/accounts.server"; import { createLegacyApiKeyLog, findLegacyApiKeyByKey, setLegacyApiKeyLogStatus, } from "@toolctrl/db/api-keys.server"; import { listWorkspaceAuthProviders, revalidateWorkspaceContext, type WorkspaceAuthProviderDto, } from "@toolctrl/db/auth-providers.server"; import { createAnalyticsEvent, createAnalyticsPageView, findFeatureFlagByName, getAnalyticsOverview, getAnalyticsSettings, getOrCreateAnalyticsUniqueVisitor, isAnalyticsPeriod, defaultAnalyticsPeriod, updateAnalyticsUniqueVisitorSource, type AnalyticsOverview, type AnalyticsInfo, type AnalyticsPeriod, type AnalyticsUniqueVisitor, } from "@toolctrl/db/analytics.server"; import { findLegacyAuthUserById, findLegacyLoginUserByEmail, recordLegacyLogin, type LegacyAuthUser, type LegacyLoginUser, } from "@toolctrl/db/users.server"; import { findLegacyEntityByName, type LegacyEntity, type LegacyEntityWithDetails } from "@toolctrl/db/entities.server"; import { createLegacyEntityRow, deleteLegacyEntityRow, findLegacyRelationshipRowById, getAllLegacyEntityRows, getLegacyEntityRow, updateLegacyEntityRow, type LegacyEntityRow, type LegacyEntityRowPage, type LegacyRelationshipRow, } from "@toolctrl/db/rows.server"; import { createLegacyRowRelationship, deleteLegacyRowRelationshipById, findLegacyEntityRelationship, findLegacyRowRelationshipById, type LegacyEntityRelationshipDetails, type LegacyRowRelationshipDetails, } from "@toolctrl/db/relationships.server"; import { findLegacyEventWebhookAttemptById, updateLegacyEventWebhookAttempt, type LegacyEventWebhookAttempt, type LegacyEventWebhookAttemptUpdate, } from "@toolctrl/db/event-webhook-attempts.server"; import { createLegacyEvent } from "@toolctrl/db/events.server"; import { markEmailSequenceDeliveryBounced, type MarkEmailSequenceDeliveryBouncedInput, type EmailSequenceProviderWebhookResult } from "@toolctrl/db/email-sequences.server"; import { findExportJobForDownload, type ExportJobDownloadRecord } from "@toolctrl/db/export-jobs.server"; import { readExportProgressFromSharedStore } from "./export-progress.js"; import { findTenantSubscriptionProductByStripeSubscriptionId, getTenantSubscription, updateTenantSubscriptionProductFromStripe, type StripeTenantSubscriptionProduct, type TenantSubscriptionWithDetails, } from "@toolctrl/db/subscriptions.server"; import { getTenantApiUsage } from "@toolctrl/db/usage.server"; import { publishOutboxEvent } from "@toolctrl/db/outbox"; import { createInboundSupportTicketFromEmail, type InboundSupportTicketInput, type InboundSupportTicketResult } from "@toolctrl/db/support-tickets.server"; import { acceptWorkspaceInvite, createWorkspaceInvite, listWorkspaceInvites, revokeWorkspaceInvite, type WorkspaceInviteCreateResult, type WorkspaceInviteDto, } from "@toolctrl/db/workspace-invites.server"; import { getDbClient } from "@toolctrl/db/client.server"; import { getNotificationStreamSnapshot, type NotificationStreamCursor, type NotificationStreamSnapshot } from "@toolctrl/db/notifications.server"; import bcrypt from "bcryptjs"; import Stripe from "stripe"; import { checkLoginRateLimit, recordFailedLoginAttempt, recordSuccessfulLogin, resetLoginRateLimiterForTests, type LoginRateLimitRequest, } from "./auth/login-rate-limit.js"; import { apiSessionStore } from "./auth/session/session-store.js"; import { getApiRuntimeConfig } from "./config.js"; import { createMemoryIdempotencyStorageClient, type IdempotencyStorageClient, } from "./idempotency/store.js"; import { createSharedStoreIdempotencyStorageClient } from "./idempotency/shared-store-client.js"; import { getSharedStore } from "./shared-store.js"; import { createStorageFile, createStorageSignedDownloadUrl, type CreateStorageSignedDownloadUrlInput, type StorageSignedDownloadUrlResult } from "./storage.js"; import { queueLegacyEventWebhookAttemptDelivery, type QueueLegacyEventWebhookAttemptDeliveryInput, type QueueLegacyEventWebhookAttemptDeliveryResult, } from "./webhookDeliveryQueue.js"; import { queueExportArtifactRetention, type QueueExportArtifactRetentionInput, type QueueExportArtifactRetentionResult, } from "./exportRetentionQueue.js"; export { defaultAnalyticsPeriod, isAnalyticsPeriod }; export type { AnalyticsInfo, AnalyticsOverview, AnalyticsPeriod, AnalyticsUniqueVisitor, ExportJobDownloadRecord, LegacyEntity, LegacyEntityRelationshipDetails, LegacyEntityRow, LegacyEntityRowPage, LegacyEntityWithDetails, LegacyEventWebhookAttempt, LegacyRelationshipRow, LegacyRowRelationshipDetails, LegacyTenantWithDetails, LoginRateLimitRequest, NotificationStreamCursor, NotificationStreamSnapshot, StripeTenantSubscriptionProduct, TenantSubscriptionWithDetails, WorkspaceAuthProviderDto, WorkspaceInviteCreateResult, WorkspaceInviteDto, }; type AnalyticsEventCreateData = { uniqueVisitorId: string; action: string; category?: string; label?: string; value?: string; url?: string; route?: string; featureFlagId?: string; portalId?: string | null; portalUserId?: string | null; }; type AnalyticsPageViewCreateData = { uniqueVisitorId: string; url: string; route?: string; portalId?: string | null; portalUserId?: string | null; }; export type ApiAppDependencies = { findLegacyApiKeyByKey: typeof findLegacyApiKeyByKey; createLegacyApiKeyLog: typeof createLegacyApiKeyLog; setLegacyApiKeyLogStatus: typeof setLegacyApiKeyLogStatus; createUniqueLegacyTenantIpAddress: typeof createUniqueLegacyTenantIpAddress; createAnalyticsEvent(data: AnalyticsEventCreateData): Promise; createAnalyticsPageView(data: AnalyticsPageViewCreateData): Promise; findFeatureFlagByName(name: string): Promise<{ id: string } | null>; getAnalyticsOverview(args: { period: AnalyticsPeriod; portalId: string | null | undefined }): Promise; findLegacyAuthUserById(userId: string): Promise; findLegacyEntityByName(args: { tenantId: string | null | undefined; name: string; active?: boolean }): Promise; getAllLegacyEntityRows(args: { entityId: string; tenantId: string | null; page: number; pageSize: number }): Promise; getLegacyEntityRow(args: { entityId: string; tenantId: string | null; rowId: string }): Promise; findLegacyRelationshipRowById(args: { id: string; tenantId?: string | null }): Promise; findLegacyEntityRelationship(args: { parentId: string; childId: string }): Promise; findLegacyRowRelationshipById(id: string, tenantId?: string | null): Promise; createLegacyRowRelationship(args: { relationshipId: string; parentId: string; childId: string; tenantId?: string | null; metadata?: string | null }): Promise; deleteLegacyRowRelationshipById(args: { id: string; relationshipId: string; parentId: string; childId: string; tenantId: string | null }): Promise; createLegacyEntityRow(args: { entity: LegacyEntityWithDetails; tenantId: string | null; createdByUserId?: string | null; createdByApiKeyId?: string | null; data: Record }): Promise; updateLegacyEntityRow(args: { entity: LegacyEntityWithDetails; tenantId: string | null; rowId: string; data: Record }): Promise; deleteLegacyEntityRow(args: { entityId: string; tenantId: string | null; rowId: string }): Promise; findLegacyEventWebhookAttemptById(id: string): Promise; findTenantSubscriptionProductByStripeSubscriptionId(stripeSubscriptionId: string): Promise; updateTenantSubscriptionProductFromStripe: typeof updateTenantSubscriptionProductFromStripe; createLegacyEvent: typeof createLegacyEvent; /** * Phase 03 #42 — transaction runner used by the Stripe webhook so the * subscription update + outbox publishes commit atomically. The * callback receives a transaction client that doubles as both a * Prisma-style subscription writer and an OutboxPublisherTransaction. */ runStripeWebhookTransaction: import("./billing/stripe-webhook-route.js").StripeWebhookTransactionRunner; /** * Phase 03 #42 — outbox publisher bound to the surrounding * transaction. Defaults to `publishOutboxEvent` from `@toolctrl/db/outbox`. */ publishOutboxEvent: typeof import("@toolctrl/db/outbox").publishOutboxEvent; findLegacyLoginUserByEmail(email: string): Promise; adminGetAllLegacyTenants(): Promise; findLegacyTenantById(id: string): Promise; findLegacyTenantByIdOrSlug(idOrSlug: string): Promise<{ id: string } | null>; getTenantSubscription: typeof getTenantSubscription; getTenantApiUsage: typeof getTenantApiUsage; createInboundSupportTicketFromEmail(input: InboundSupportTicketInput): Promise; markEmailSequenceDeliveryBounced(input: MarkEmailSequenceDeliveryBouncedInput): Promise; findExportJobForDownload(args: { id: string; tenantId: string }): Promise; readExportProgress(args: { exportJobId: string; tenantId: string }): Promise<{ processedRows: number; totalEstimate: number | null; updatedAt: string | null } | null>; getAnalyticsSettings(): Promise<{ public: boolean; ignorePages: string } | null>; getOrCreateAnalyticsUniqueVisitor(args: { cookie: string; fromUrl?: string; fromRoute?: string; analytics: AnalyticsInfo }): Promise; updateAnalyticsUniqueVisitorSource(visitor: AnalyticsUniqueVisitor, analytics: AnalyticsInfo): Promise; updateLegacyEventWebhookAttempt(args: { id: string; tenantId: string | null }, data: LegacyEventWebhookAttemptUpdate): Promise; queueLegacyEventWebhookAttemptDelivery(input: QueueLegacyEventWebhookAttemptDeliveryInput): Promise; queueExportArtifactRetention(input: QueueExportArtifactRetentionInput): Promise; getNotificationStreamSnapshot(filters: { tenantId: string; userId: string; afterCursor?: NotificationStreamCursor | null }): Promise; createWorkspaceInvite(input: Parameters[0]): Promise; listWorkspaceInvites(input: Parameters[0]): Promise; acceptWorkspaceInvite(input: Parameters[0]): Promise; revokeWorkspaceInvite(input: Parameters[0]): Promise; listWorkspaceAuthProviders(input: Parameters[0]): Promise; revalidateWorkspaceContext(input: Parameters[0]): ReturnType; uploadFile(bucketId: string, path: string, file: UploadBody, contentType?: string): Promise<{ id: string; publicUrl: string | null }>; createSignedDownloadUrl(bucketId: string, input: CreateStorageSignedDownloadUrlInput): Promise; constructStripeWebhookEvent(payload: string, signature: string): Stripe.Event; retrieveStripeSubscription(id: string): Promise; recordLegacyLogin(userId: string): Promise; comparePassword(password: string, passwordHash: string): Promise; checkLoginRateLimit(request: LoginRateLimitRequest): ReturnType; recordFailedLoginAttempt(request: LoginRateLimitRequest): Promise; recordSuccessfulLogin(request: Pick): Promise; resetLoginRateLimiter(): Promise; resetApiSessionStore(): void; createApiSession(userId: string): ReturnType; getActiveApiSession(sessionId: string): ReturnType; rotateApiSession(sessionId: string): ReturnType; revokeApiSession(sessionId: string): ReturnType; getIdempotencyClient(): IdempotencyStorageClient; checkReadiness(): Promise; }; type UploadBody = Parameters[2]; const STRIPE_API_VERSION = "2025-10-29.clover"; let apiStripeClient: Stripe | null = null; let apiStripeClientSecretKey: string | undefined; function getApiStripeClient() { const secretKey = getApiRuntimeConfig().stripe.secretKey; if (!secretKey) { throw new Error("STRIPE_SK is required before using Stripe API services."); } if (!apiStripeClient || apiStripeClientSecretKey !== secretKey) { apiStripeClient = new Stripe(secretKey, { apiVersion: STRIPE_API_VERSION }); apiStripeClientSecretKey = secretKey; } return apiStripeClient; } /** * Idempotency-storage backend selection (Phase 03 #38). * * Default is the Postgres-backed Prisma client, which is already * multi-replica-safe. Setting `IDEMPOTENCY_BACKEND=shared-store` swaps in * the SharedStore-backed client (Redis in production) so a deployment can * keep idempotency state off the primary database. Any other value — or * none — keeps the Prisma default. */ let sharedStoreIdempotencyClient: IdempotencyStorageClient | null = null; function resolveIdempotencyClient(): IdempotencyStorageClient { if (process.env.IDEMPOTENCY_BACKEND === "shared-store") { if (!sharedStoreIdempotencyClient) { sharedStoreIdempotencyClient = createSharedStoreIdempotencyStorageClient({ store: getSharedStore() }); } return sharedStoreIdempotencyClient; } return getDbClient() as unknown as IdempotencyStorageClient; } const defaultApiAppDependencies: ApiAppDependencies = { findLegacyApiKeyByKey, createLegacyApiKeyLog, setLegacyApiKeyLogStatus, createUniqueLegacyTenantIpAddress, createAnalyticsEvent, createAnalyticsPageView, findFeatureFlagByName, getAnalyticsOverview, findLegacyAuthUserById, findLegacyEntityByName, getAllLegacyEntityRows, getLegacyEntityRow, findLegacyRelationshipRowById, findLegacyEntityRelationship, findLegacyRowRelationshipById, createLegacyRowRelationship, deleteLegacyRowRelationshipById, createLegacyEntityRow, updateLegacyEntityRow, deleteLegacyEntityRow, findLegacyEventWebhookAttemptById, findTenantSubscriptionProductByStripeSubscriptionId, updateTenantSubscriptionProductFromStripe, createLegacyEvent, // Phase 03 #42 — Stripe-webhook outbox migration. The default runs // the callback inside `prisma.$transaction(...)`; the resulting tx // client doubles as both StripeTenantSubscriptionProductClient and // OutboxPublisherTransaction (Prisma transaction clients implement // both surfaces structurally). runStripeWebhookTransaction: (async (fn: (tx: import("./billing/stripe-webhook-route.js").StripeWebhookTransactionClient) => Promise) => { const prisma = getDbClient() as unknown as { $transaction: (runner: (tx: import("./billing/stripe-webhook-route.js").StripeWebhookTransactionClient) => Promise) => Promise; }; return prisma.$transaction(fn); }) as import("./billing/stripe-webhook-route.js").StripeWebhookTransactionRunner, publishOutboxEvent, findLegacyLoginUserByEmail, adminGetAllLegacyTenants, findLegacyTenantById, findLegacyTenantByIdOrSlug, getTenantSubscription, getTenantApiUsage, createInboundSupportTicketFromEmail, markEmailSequenceDeliveryBounced, findExportJobForDownload, readExportProgress: readExportProgressFromSharedStore, getAnalyticsSettings, getOrCreateAnalyticsUniqueVisitor, updateAnalyticsUniqueVisitorSource, updateLegacyEventWebhookAttempt, queueLegacyEventWebhookAttemptDelivery, queueExportArtifactRetention, getNotificationStreamSnapshot, createWorkspaceInvite, listWorkspaceInvites, acceptWorkspaceInvite, revokeWorkspaceInvite, listWorkspaceAuthProviders, revalidateWorkspaceContext, uploadFile: createStorageFile, createSignedDownloadUrl: createStorageSignedDownloadUrl, constructStripeWebhookEvent(payload, signature) { const config = getApiRuntimeConfig(); if (!config.stripe.webhookSigningSecret) { throw new Error("STRIPE_WEBHOOK_SIGNING_SECRET is required before verifying Stripe webhooks."); } return getApiStripeClient().webhooks.constructEvent(payload, signature, config.stripe.webhookSigningSecret); }, async retrieveStripeSubscription(id) { try { return await getApiStripeClient().subscriptions.retrieve(id); } catch { return null; } }, recordLegacyLogin, comparePassword: bcrypt.compare, checkLoginRateLimit, recordFailedLoginAttempt, recordSuccessfulLogin, resetLoginRateLimiter: resetLoginRateLimiterForTests, resetApiSessionStore: apiSessionStore.reset, createApiSession: apiSessionStore.createSession, getActiveApiSession: apiSessionStore.getActiveSession, rotateApiSession: apiSessionStore.rotateSession, revokeApiSession: apiSessionStore.revokeSession, getIdempotencyClient() { return resolveIdempotencyClient(); }, async checkReadiness() { await getDbClient().$queryRaw`SELECT 1`; }, }; let apiAppDependencies = defaultApiAppDependencies; export function getApiAppDependencies() { return apiAppDependencies; } export function configureApiAppDependenciesForTests(dependencies: Partial = {}) { const idempotencyClient = createMemoryIdempotencyStorageClient(); // Fire-and-forget; the rate limiter and session store reset to a clean // state on the next access regardless of when this promise settles. void defaultApiAppDependencies.resetLoginRateLimiter(); defaultApiAppDependencies.resetApiSessionStore(); apiAppDependencies = { ...defaultApiAppDependencies, getIdempotencyClient: () => idempotencyClient, ...dependencies, }; return () => { void apiAppDependencies.resetLoginRateLimiter(); apiAppDependencies.resetApiSessionStore(); apiAppDependencies = defaultApiAppDependencies; }; }