import { createUniqueLegacyTenantIpAddress, adminGetAllLegacyTenants, findLegacyTenantById, findLegacyTenantByIdOrSlug, type LegacyTenantWithDetails, } from "@hivegrid/db/accounts.server"; import { createLegacyApiKeyLog, findLegacyApiKeyByKey, setLegacyApiKeyLogStatus, } from "@hivegrid/db/api-keys.server"; import { listWorkspaceAuthProviders, revalidateWorkspaceContext, type WorkspaceAuthProviderDto, } from "@hivegrid/db/auth-providers.server"; import { createAnalyticsEvent, createAnalyticsPageView, findFeatureFlagByName, getAnalyticsOverview, getAnalyticsSettings, getOrCreateAnalyticsUniqueVisitor, isAnalyticsPeriod, defaultAnalyticsPeriod, updateAnalyticsUniqueVisitorSource, type AnalyticsOverview, type AnalyticsInfo, type AnalyticsPeriod, type AnalyticsUniqueVisitor, } from "@hivegrid/db/analytics.server"; import { findLegacyAuthUserById, findLegacyLoginUserByEmail, recordLegacyLogin, type LegacyAuthUser, type LegacyLoginUser, } from "@hivegrid/db/users.server"; import { findLegacyEventWebhookAttemptById, updateLegacyEventWebhookAttempt, type LegacyEventWebhookAttempt, type LegacyEventWebhookAttemptUpdate, } from "@hivegrid/db/event-webhook-attempts.server"; import { createLegacyEvent } from "@hivegrid/db/events.server"; import { markEmailSequenceDeliveryBounced, type MarkEmailSequenceDeliveryBouncedInput, type EmailSequenceProviderWebhookResult } from "@hivegrid/db/email-sequences.server"; import { recordEmailSuppression } from "@hivegrid/db/email-suppression.server"; import { findExportJobForDownload, type ExportJobDownloadRecord } from "@hivegrid/db/export-jobs.server"; import { readExportProgressFromSharedStore } from "./export-progress.js"; import { getTenantSubscription, type TenantSubscriptionWithDetails, } from "@hivegrid/db/subscriptions.server"; import { applyLagoSubscriptionSync, applyMolliePaymentSync } from "@hivegrid/db/billing-sync.server"; import { getTenantApiUsage } from "@hivegrid/db/usage.server"; import { createPublicWebhookIngestionLog, findPublicIncomingWebhookEndpoint, ingestPublicLeadWebhook, type IngestPublicLeadWebhookResult, } from "@hivegrid/db/public-api.server"; import { createInboundSupportTicketFromEmail, type InboundSupportTicketInput, type InboundSupportTicketResult } from "@hivegrid/db/support-tickets.server"; import { acceptWorkspaceInvite, createWorkspaceInvite, listWorkspaceInvites, revokeWorkspaceInvite, type WorkspaceInviteCreateResult, type WorkspaceInviteDto, } from "@hivegrid/db/workspace-invites.server"; import { getDbClient } from "@hivegrid/db/client.server"; import { getNotificationStreamSnapshot, type NotificationStreamCursor, type NotificationStreamSnapshot } from "@hivegrid/db/notifications.server"; import bcrypt from "bcryptjs"; import { checkLoginRateLimit, recordFailedLoginAttempt, recordSuccessfulLogin, resetLoginRateLimiterForTests, type LoginRateLimitRequest, } from "./auth/login-rate-limit.js"; import { apiSessionStore } from "./auth/session/session-store.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"; import { listPublicApiResource } from "./public-api/read-service.js"; import type { PublicApiListInput, PublicApiListResult } from "./public-api/resources.js"; import { createDefaultLagoInvoicePaymentStatusUpdater, createDefaultMollieWebhookResolver } from "./billing/mollie-webhook-route.js"; export { defaultAnalyticsPeriod, isAnalyticsPeriod }; export type { AnalyticsInfo, AnalyticsOverview, AnalyticsPeriod, AnalyticsUniqueVisitor, ExportJobDownloadRecord, LegacyEventWebhookAttempt, LegacyTenantWithDetails, LoginRateLimitRequest, NotificationStreamCursor, NotificationStreamSnapshot, 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; findLegacyEventWebhookAttemptById(id: string): Promise; createLegacyEvent: typeof createLegacyEvent; applyLagoSubscriptionSync: typeof import("@hivegrid/db/billing-sync.server").applyLagoSubscriptionSync; applyMolliePaymentSync: typeof import("@hivegrid/db/billing-sync.server").applyMolliePaymentSync; resolveMollieWebhookPayment: ReturnType; updateLagoInvoicePaymentStatus: ReturnType; findLegacyLoginUserByEmail(email: string): Promise; adminGetAllLegacyTenants(): Promise; findLegacyTenantById(id: string): Promise; findLegacyTenantByIdOrSlug(idOrSlug: string): Promise<{ id: string } | null>; getTenantSubscription: typeof getTenantSubscription; getTenantApiUsage: typeof getTenantApiUsage; listPublicApiResource(input: PublicApiListInput): Promise; findPublicIncomingWebhookEndpoint: typeof findPublicIncomingWebhookEndpoint; createPublicWebhookIngestionLog: typeof createPublicWebhookIngestionLog; ingestPublicLeadWebhook(input: Parameters[0]): Promise; createInboundSupportTicketFromEmail(input: InboundSupportTicketInput): Promise; markEmailSequenceDeliveryBounced(input: MarkEmailSequenceDeliveryBouncedInput): Promise; recordSuppression: typeof recordEmailSuppression; 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; 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]; /** * 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, findLegacyEventWebhookAttemptById, createLegacyEvent, applyLagoSubscriptionSync, applyMolliePaymentSync, resolveMollieWebhookPayment: createDefaultMollieWebhookResolver(), updateLagoInvoicePaymentStatus: createDefaultLagoInvoicePaymentStatusUpdater(), findLegacyLoginUserByEmail, adminGetAllLegacyTenants, findLegacyTenantById, findLegacyTenantByIdOrSlug, getTenantSubscription, getTenantApiUsage, listPublicApiResource, findPublicIncomingWebhookEndpoint, createPublicWebhookIngestionLog, ingestPublicLeadWebhook, createInboundSupportTicketFromEmail, markEmailSequenceDeliveryBounced, recordSuppression: recordEmailSuppression, findExportJobForDownload, readExportProgress: readExportProgressFromSharedStore, getAnalyticsSettings, getOrCreateAnalyticsUniqueVisitor, updateAnalyticsUniqueVisitorSource, updateLegacyEventWebhookAttempt, queueLegacyEventWebhookAttemptDelivery, queueExportArtifactRetention, getNotificationStreamSnapshot, createWorkspaceInvite, listWorkspaceInvites, acceptWorkspaceInvite, revokeWorkspaceInvite, listWorkspaceAuthProviders, revalidateWorkspaceContext, uploadFile: createStorageFile, createSignedDownloadUrl: createStorageSignedDownloadUrl, 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; }; }