Reorganize repo structure and standards references

This commit is contained in:
david committed 2026-06-29 05:03:42 +02:00
1 parent 3cb93a81be
commit be2054274d
5885 files changed
+2588 -195

No files matched your search

@@ -0,0 +1,402 @@
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<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>;
findLegacyEntityByName(args: { tenantId: string | null | undefined; name: string; active?: boolean }): Promise<LegacyEntity>;
getAllLegacyEntityRows(args: { entityId: string; tenantId: string | null; page: number; pageSize: number }): Promise<LegacyEntityRowPage>;
getLegacyEntityRow(args: { entityId: string; tenantId: string | null; rowId: string }): Promise<LegacyEntityRow | null>;
findLegacyRelationshipRowById(args: { id: string; tenantId?: string | null }): Promise<LegacyRelationshipRow | null>;
findLegacyEntityRelationship(args: { parentId: string; childId: string }): Promise<LegacyEntityRelationshipDetails | null>;
findLegacyRowRelationshipById(id: string, tenantId?: string | null): Promise<LegacyRowRelationshipDetails | null>;
createLegacyRowRelationship(args: { relationshipId: string; parentId: string; childId: string; tenantId?: string | null; metadata?: string | null }): Promise<LegacyRowRelationshipDetails>;
deleteLegacyRowRelationshipById(args: { id: string; relationshipId: string; parentId: string; childId: string; tenantId: string | null }): Promise<unknown>;
createLegacyEntityRow(args: { entity: LegacyEntityWithDetails; tenantId: string | null; createdByUserId?: string | null; createdByApiKeyId?: string | null; data: Record<string, unknown> }): Promise<LegacyEntityRow>;
updateLegacyEntityRow(args: { entity: LegacyEntityWithDetails; tenantId: string | null; rowId: string; data: Record<string, unknown> }): Promise<LegacyEntityRow>;
deleteLegacyEntityRow(args: { entityId: string; tenantId: string | null; rowId: string }): Promise<string>;
findLegacyEventWebhookAttemptById(id: string): Promise<LegacyEventWebhookAttempt | null>;
findTenantSubscriptionProductByStripeSubscriptionId(stripeSubscriptionId: string): Promise<StripeTenantSubscriptionProduct | null>;
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<LegacyLoginUser | null>;
adminGetAllLegacyTenants(): Promise<LegacyTenantWithDetails[]>;
findLegacyTenantById(id: string): Promise<LegacyTenantWithDetails | null>;
findLegacyTenantByIdOrSlug(idOrSlug: string): Promise<{ id: string } | null>;
getTenantSubscription: typeof getTenantSubscription;
getTenantApiUsage: typeof getTenantApiUsage;
createInboundSupportTicketFromEmail(input: InboundSupportTicketInput): Promise<InboundSupportTicketResult>;
markEmailSequenceDeliveryBounced(input: MarkEmailSequenceDeliveryBouncedInput): Promise<EmailSequenceProviderWebhookResult>;
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>;
constructStripeWebhookEvent(payload: string, signature: string): Stripe.Event;
retrieveStripeSubscription(id: string): Promise<Stripe.Subscription | null>;
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];
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 <T,>(fn: (tx: import("./billing/stripe-webhook-route.js").StripeWebhookTransactionClient) => Promise<T>) => {
const prisma = getDbClient() as unknown as {
$transaction: <U>(runner: (tx: import("./billing/stripe-webhook-route.js").StripeWebhookTransactionClient) => Promise<U>) => Promise<U>;
};
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<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;
};
}