316 lines
14 KiB
TypeScript
316 lines
14 KiB
TypeScript
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<void>;
|
|
createAnalyticsPageView(data: AnalyticsPageViewCreateData): Promise<void>;
|
|
findFeatureFlagByName(name: string): Promise<{ id: string } | null>;
|
|
getAnalyticsOverview(args: { period: AnalyticsPeriod; portalId: string | null | undefined }): Promise<AnalyticsOverview>;
|
|
findLegacyAuthUserById(userId: string): Promise<LegacyAuthUser | null>;
|
|
findLegacyEventWebhookAttemptById(id: string): Promise<LegacyEventWebhookAttempt | null>;
|
|
createLegacyEvent: typeof createLegacyEvent;
|
|
applyLagoSubscriptionSync: typeof import("@hivegrid/db/billing-sync.server").applyLagoSubscriptionSync;
|
|
applyMolliePaymentSync: typeof import("@hivegrid/db/billing-sync.server").applyMolliePaymentSync;
|
|
resolveMollieWebhookPayment: ReturnType<typeof createDefaultMollieWebhookResolver>;
|
|
updateLagoInvoicePaymentStatus: ReturnType<typeof createDefaultLagoInvoicePaymentStatusUpdater>;
|
|
findLegacyLoginUserByEmail(email: string): Promise<LegacyLoginUser | null>;
|
|
adminGetAllLegacyTenants(): Promise<LegacyTenantWithDetails[]>;
|
|
findLegacyTenantById(id: string): Promise<LegacyTenantWithDetails | null>;
|
|
findLegacyTenantByIdOrSlug(idOrSlug: string): Promise<{ id: string } | null>;
|
|
getTenantSubscription: typeof getTenantSubscription;
|
|
getTenantApiUsage: typeof getTenantApiUsage;
|
|
listPublicApiResource(input: PublicApiListInput): Promise<PublicApiListResult>;
|
|
findPublicIncomingWebhookEndpoint: typeof findPublicIncomingWebhookEndpoint;
|
|
createPublicWebhookIngestionLog: typeof createPublicWebhookIngestionLog;
|
|
ingestPublicLeadWebhook(input: Parameters<typeof ingestPublicLeadWebhook>[0]): Promise<IngestPublicLeadWebhookResult>;
|
|
createInboundSupportTicketFromEmail(input: InboundSupportTicketInput): Promise<InboundSupportTicketResult>;
|
|
markEmailSequenceDeliveryBounced(input: MarkEmailSequenceDeliveryBouncedInput): Promise<EmailSequenceProviderWebhookResult>;
|
|
recordSuppression: typeof recordEmailSuppression;
|
|
findExportJobForDownload(args: { id: string; tenantId: string }): Promise<ExportJobDownloadRecord | null>;
|
|
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<AnalyticsUniqueVisitor>;
|
|
updateAnalyticsUniqueVisitorSource(visitor: AnalyticsUniqueVisitor, analytics: AnalyticsInfo): Promise<void>;
|
|
updateLegacyEventWebhookAttempt(args: { id: string; tenantId: string | null }, data: LegacyEventWebhookAttemptUpdate): Promise<void>;
|
|
queueLegacyEventWebhookAttemptDelivery(input: QueueLegacyEventWebhookAttemptDeliveryInput): Promise<QueueLegacyEventWebhookAttemptDeliveryResult>;
|
|
queueExportArtifactRetention(input: QueueExportArtifactRetentionInput): Promise<QueueExportArtifactRetentionResult>;
|
|
getNotificationStreamSnapshot(filters: { tenantId: string; userId: string; afterCursor?: NotificationStreamCursor | null }): Promise<NotificationStreamSnapshot>;
|
|
createWorkspaceInvite(input: Parameters<typeof createWorkspaceInvite>[0]): Promise<WorkspaceInviteCreateResult>;
|
|
listWorkspaceInvites(input: Parameters<typeof listWorkspaceInvites>[0]): Promise<WorkspaceInviteDto[]>;
|
|
acceptWorkspaceInvite(input: Parameters<typeof acceptWorkspaceInvite>[0]): Promise<WorkspaceInviteDto>;
|
|
revokeWorkspaceInvite(input: Parameters<typeof revokeWorkspaceInvite>[0]): Promise<WorkspaceInviteDto>;
|
|
listWorkspaceAuthProviders(input: Parameters<typeof listWorkspaceAuthProviders>[0]): Promise<WorkspaceAuthProviderDto[]>;
|
|
revalidateWorkspaceContext(input: Parameters<typeof revalidateWorkspaceContext>[0]): ReturnType<typeof revalidateWorkspaceContext>;
|
|
uploadFile(bucketId: string, path: string, file: UploadBody, contentType?: string): Promise<{ id: string; publicUrl: string | null }>;
|
|
createSignedDownloadUrl(bucketId: string, input: CreateStorageSignedDownloadUrlInput): Promise<StorageSignedDownloadUrlResult>;
|
|
recordLegacyLogin(userId: string): Promise<void>;
|
|
comparePassword(password: string, passwordHash: string): Promise<boolean>;
|
|
checkLoginRateLimit(request: LoginRateLimitRequest): ReturnType<typeof checkLoginRateLimit>;
|
|
recordFailedLoginAttempt(request: LoginRateLimitRequest): Promise<void>;
|
|
recordSuccessfulLogin(request: Pick<LoginRateLimitRequest, "account">): Promise<void>;
|
|
resetLoginRateLimiter(): Promise<void>;
|
|
resetApiSessionStore(): void;
|
|
createApiSession(userId: string): ReturnType<typeof apiSessionStore.createSession>;
|
|
getActiveApiSession(sessionId: string): ReturnType<typeof apiSessionStore.getActiveSession>;
|
|
rotateApiSession(sessionId: string): ReturnType<typeof apiSessionStore.rotateSession>;
|
|
revokeApiSession(sessionId: string): ReturnType<typeof apiSessionStore.revokeSession>;
|
|
getIdempotencyClient(): IdempotencyStorageClient;
|
|
checkReadiness(): Promise<void>;
|
|
};
|
|
|
|
type UploadBody = Parameters<typeof createStorageFile>[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<ApiAppDependencies> = {}) {
|
|
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;
|
|
};
|
|
}
|