Update hivegrid-cloud reference to latest main

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
davidandClaude Fable 5 committed 2026-07-08 16:15:37 +02:00
1 parent e98d38e716
commit 7b21524c86
3781 files changed
+373484 -225607

No files matched your search

@@ -1,4 +1,4 @@
# @toolctrl/api
# @hivegrid/api
Dedicated Hono API application for `api.<domain>/v1`.
@@ -13,7 +13,7 @@ This workspace owns the canonical API host. External integrations should use the
- `POST /v1/api-keys/validate` validates `apiKey` from the JSON body, `x-api-key` header, or bearer token and returns `{ "active": true, "keyType": "service-token" }` for the configured service token.
- `GET /v1/accounts`, `GET /v1/accounts/:id`, and `GET /v1/usage` expose service/API-key scoped account and usage metadata.
- `/v1/entities/*`, `/v1/relationships/*`, `/v1/exports/*`, and `/v1/workspaces/*` expose the current tenant-scoped API surface.
- `POST /v1/billing/stripe/webhooks` and `POST /v1/events/webhooks/attempts/:id` are signed webhook ingress routes.
- `POST /v1/billing/mollie/webhooks` and `POST /v1/events/webhooks/attempts/:id` are webhook ingress routes.
Use `/v1/openapi.json` and `apps/api/src/route-access-inventory.ts` for the detailed route inventory.
@@ -23,10 +23,10 @@ Set `API_ACCESS_TOKEN` in the API environment to enable the service-token primit
## Scripts
- `pnpm --filter @toolctrl/api dev` starts the API with `tsx watch`.
- `pnpm --filter @toolctrl/api build` compiles `src/` to `dist/`.
- `pnpm --filter @toolctrl/api start` runs the compiled server.
- `pnpm --filter @toolctrl/api typecheck` runs TypeScript without emitting files.
- `pnpm --filter @hivegrid/api dev` starts the API with `tsx watch`.
- `pnpm --filter @hivegrid/api build` compiles `src/` to `dist/`.
- `pnpm --filter @hivegrid/api start` runs the compiled server.
- `pnpm --filter @hivegrid/api typecheck` runs TypeScript without emitting files.
The server listens on `API_PORT` when set, falls back to `PORT`, and otherwise defaults to `3001`.
@@ -34,4 +34,4 @@ The server listens on `API_PORT` when set, falls back to `PORT`, and otherwise d
- Keep `src/app.ts` focused on Hono app composition so tests, adapters and future deployment targets can import the app without starting a listener.
- Keep newly extracted API behavior in focused API modules instead of growing `src/app.ts` with service logic.
- Keep shared environment validation in `@toolctrl/config` and update the catalog when API runtime keys change.
- Keep shared environment validation in `@hivegrid/config` and update the catalog when API runtime keys change.
@@ -1,5 +1,5 @@
{
"name": "@toolctrl/api",
"name": "@hivegrid/api",
"version": "0.0.0",
"private": true,
"type": "module",
@@ -16,6 +16,19 @@
"build": "node scripts/build.mjs"
},
"dependencies": {
"@hivegrid/billing": "workspace:*",
"@hivegrid/config": "workspace:*",
"@hivegrid/db": "workspace:*",
"@hivegrid/error-reporter": "workspace:*",
"@hivegrid/foundation": "workspace:*",
"@hivegrid/logger": "workspace:*",
"@hivegrid/metrics": "workspace:*",
"@hivegrid/observability": "workspace:*",
"@hivegrid/plugin-runtime": "workspace:*",
"@hivegrid/queue": "workspace:*",
"@hivegrid/realtime": "workspace:*",
"@hivegrid/shared-store": "workspace:*",
"@hivegrid/storage": "workspace:*",
"@hono/node-server": "^1.19.6",
"@opentelemetry/api": "^1.9.0",
"@opentelemetry/auto-instrumentations-node": "^0.76.0",
@@ -26,22 +39,9 @@
"@opentelemetry/sdk-trace-base": "^2.7.1",
"@opentelemetry/semantic-conventions": "^1.40.0",
"@sentry/node": "^10.53.1",
"@toolctrl/config": "workspace:*",
"@toolctrl/db": "workspace:*",
"@toolctrl/error-reporter": "workspace:*",
"@toolctrl/foundation": "workspace:*",
"@toolctrl/logger": "workspace:*",
"@toolctrl/metrics": "workspace:*",
"@toolctrl/observability": "workspace:*",
"@toolctrl/plugin-runtime": "workspace:*",
"@toolctrl/queue": "workspace:*",
"@toolctrl/realtime": "workspace:*",
"@toolctrl/shared-store": "workspace:*",
"@toolctrl/storage": "workspace:*",
"bcryptjs": "^2.4.3",
"hono": "^4.12.17",
"jsonwebtoken": "^9.0.0",
"stripe": "^19.1.0",
"zod": "^3.25.72"
},
"devDependencies": {
@@ -38,7 +38,7 @@ await build({
target: "node20",
sourcemap,
banner: {
js: 'import { createRequire as __toolctrlCreateRequire } from "node:module"; const require = __toolctrlCreateRequire(import.meta.url);',
js: 'import { createRequire as __hivegridCreateRequire } from "node:module"; const require = __hivegridCreateRequire(import.meta.url);',
},
plugins: [externalizeRuntimeDependencies],
logLevel: "warning",
@@ -9,8 +9,8 @@
* - the matching Sentry project receives both an Issue and a Transaction.
*
* Run from the repo root with one of:
* pnpm --filter @toolctrl/api exec tsx scripts/smoke-sentry.ts
* SENTRY_DSN_API=... pnpm --filter @toolctrl/api exec tsx scripts/smoke-sentry.ts
* pnpm --filter @hivegrid/api exec tsx scripts/smoke-sentry.ts
* SENTRY_DSN_API=... pnpm --filter @hivegrid/api exec tsx scripts/smoke-sentry.ts
*
* Exits 0 on a clean run, 1 when the SDK fails to load. A no-DSN run is
* intentionally a successful no-op so CI can call it unconditionally.
@@ -70,7 +70,7 @@ async function main(): Promise<void> {
// is worth for a manual smoke script.
await new Promise((resolve) => setTimeout(resolve, 1500));
// eslint-disable-next-line no-console
console.log("[smoke-sentry] done — check the Sentry UI (Issues + Performance) for boilerplate-api.");
console.log("[smoke-sentry] done — check the Sentry UI (Issues + Performance) for hivegrid-api.");
}
main().catch((cause) => {
@@ -4,17 +4,17 @@ import {
findLegacyTenantById,
findLegacyTenantByIdOrSlug,
type LegacyTenantWithDetails,
} from "@toolctrl/db/accounts.server";
} from "@hivegrid/db/accounts.server";
import {
createLegacyApiKeyLog,
findLegacyApiKeyByKey,
setLegacyApiKeyLogStatus,
} from "@toolctrl/db/api-keys.server";
} from "@hivegrid/db/api-keys.server";
import {
listWorkspaceAuthProviders,
revalidateWorkspaceContext,
type WorkspaceAuthProviderDto,
} from "@toolctrl/db/auth-providers.server";
} from "@hivegrid/db/auth-providers.server";
import {
createAnalyticsEvent,
createAnalyticsPageView,
@@ -29,54 +29,38 @@ import {
type AnalyticsInfo,
type AnalyticsPeriod,
type AnalyticsUniqueVisitor,
} from "@toolctrl/db/analytics.server";
} from "@hivegrid/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";
} from "@hivegrid/db/users.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";
} 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 {
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";
} 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,
@@ -84,11 +68,10 @@ import {
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";
} 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 Stripe from "stripe";
import {
checkLoginRateLimit,
recordFailedLoginAttempt,
@@ -97,7 +80,6 @@ import {
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,
@@ -115,6 +97,9 @@ import {
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 {
@@ -123,19 +108,11 @@ export type {
AnalyticsPeriod,
AnalyticsUniqueVisitor,
ExportJobDownloadRecord,
LegacyEntity,
LegacyEntityRelationshipDetails,
LegacyEntityRow,
LegacyEntityRowPage,
LegacyEntityWithDetails,
LegacyEventWebhookAttempt,
LegacyRelationshipRow,
LegacyRowRelationshipDetails,
LegacyTenantWithDetails,
LoginRateLimitRequest,
NotificationStreamCursor,
NotificationStreamSnapshot,
StripeTenantSubscriptionProduct,
TenantSubscriptionWithDetails,
WorkspaceAuthProviderDto,
WorkspaceInviteCreateResult,
@@ -173,41 +150,25 @@ export type ApiAppDependencies = {
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;
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>;
@@ -225,8 +186,6 @@ export type ApiAppDependencies = {
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>;
@@ -244,22 +203,6 @@ export type ApiAppDependencies = {
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).
*
@@ -291,41 +234,25 @@ const defaultApiAppDependencies: ApiAppDependencies = {
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,
applyLagoSubscriptionSync,
applyMolliePaymentSync,
resolveMollieWebhookPayment: createDefaultMollieWebhookResolver(),
updateLagoInvoicePaymentStatus: createDefaultLagoInvoicePaymentStatusUpdater(),
findLegacyLoginUserByEmail,
adminGetAllLegacyTenants,
findLegacyTenantById,
findLegacyTenantByIdOrSlug,
getTenantSubscription,
getTenantApiUsage,
listPublicApiResource,
findPublicIncomingWebhookEndpoint,
createPublicWebhookIngestionLog,
ingestPublicLeadWebhook,
createInboundSupportTicketFromEmail,
markEmailSequenceDeliveryBounced,
recordSuppression: recordEmailSuppression,
findExportJobForDownload,
readExportProgress: readExportProgressFromSharedStore,
getAnalyticsSettings,
@@ -343,20 +270,6 @@ const defaultApiAppDependencies: ApiAppDependencies = {
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,
File diff suppressed because it is too large. Load diff
@@ -1,9 +1,9 @@
import { Hono } from "hono";
import { cors } from "hono/cors";
import { isMetricsEnabled } from "@toolctrl/metrics";
import { isMetricsEnabled } from "@hivegrid/metrics";
import { getApiAppDependencies, configureApiAppDependenciesForTests, type ApiAppDependencies } from "./app-dependencies.js";
import type { ApiEnv } from "./api-types.js";
import { postStripeBillingWebhookRequest } from "./billing/stripe-webhook-route.js";
import { postMollieBillingWebhookRequest } from "./billing/mollie-webhook-route.js";
import { getAllowedCorsOrigin } from "./cors.js";
import { apiLogger } from "./logger.js";
import { getApiMetrics } from "./metrics.js";
@@ -15,15 +15,14 @@ import { createSentryTracingMiddleware } from "./middleware/sentryTracing.js";
import { createAuditContextMiddleware } from "./middleware/audit-context.js";
import { createApiMaintenanceMiddleware } from "./platform/maintenance/maintenance.js";
import { apiErrorReporter } from "./sentry.js";
import { registerPublicApiReadRoutes } from "./routes/public-api-routes.js";
import { registerAccountsRoutes } from "./routes/accounts-routes.js";
import { registerAnalyticsRoutes } from "./routes/analytics-routes.js";
import { registerAuthRoutes } from "./routes/auth-routes.js";
import { registerDevicesRoutes } from "./routes/devices-routes.js";
import { registerEntityRowRoutes } from "./routes/entity-row-routes.js";
import { registerMaintenanceRoutes } from "./routes/maintenance-routes.js";
import { handleApiMetricsRequest } from "./routes/metrics.js";
import { registerNotificationRoutes } from "./routes/notifications-routes.js";
import { registerRelationshipRoutes } from "./routes/relationship-routes.js";
import { handleApiStatusRequest } from "./routes/status.js";
import { registerSystemRoutes } from "./routes/system-routes.js";
import { registerWorkspaceRoutes } from "./routes/workspace-routes.js";
@@ -101,8 +100,8 @@ app.use(
"x-filename",
"x-request-id",
"x-tenant-id",
"x-toolctrl-tenant-id",
"x-toolctrl-user-id",
"x-hivegrid-tenant-id",
"x-hivegrid-user-id",
"x-storage-object-status",
"webhook-id",
"webhook-timestamp",
@@ -123,12 +122,11 @@ registerAnalyticsRoutes(app);
registerNotificationRoutes(app);
registerWorkspaceRoutes(app);
registerMaintenanceRoutes(app);
registerEntityRowRoutes(app);
registerRelationshipRoutes(app);
registerDevicesRoutes(app);
registerPublicApiReadRoutes(app);
app.get("/v1/usage", (c) => getUsageRequest(c, getApiAppDependencies()));
app.post("/v1/billing/stripe/webhooks", (c) => postStripeBillingWebhookRequest(c, getApiAppDependencies()));
app.post("/v1/billing/mollie/webhooks", (c) => postMollieBillingWebhookRequest(c, getApiAppDependencies()));
app.notFound(createNotFoundHandler());
app.onError(createErrorHandler({ reporter: apiErrorReporter }));
@@ -1,5 +1,5 @@
import { createHash, timingSafeEqual } from "node:crypto";
import type { ApiConfig } from "@toolctrl/config";
import type { ApiConfig } from "@hivegrid/config";
export type ServicePrincipal = {
type: "service-token";
@@ -1,5 +1,5 @@
import { describe, expect, test } from "vitest";
import type { ApiConfig } from "@toolctrl/config";
import type { ApiConfig } from "@hivegrid/config";
import { serializeApiAuthCookie, serializeExpiredApiAuthCookie } from "./session-cookie.js";
const baseConfig: ApiConfig = {
@@ -19,7 +19,8 @@ const baseConfig: ApiConfig = {
jwtSecret: "test-jwt-secret",
analytics: {},
mailjet: {},
stripe: {},
lago: { timeoutMs: 10000 },
mollie: { timeoutMs: 10000 },
apiKeys: {
allowLegacyPlaintextFallback: true,
},
@@ -41,13 +42,13 @@ describe("serializeApiAuthCookie", () => {
} satisfies ApiConfig;
const cookie = serializeApiAuthCookie("signed.jwt.value", config);
expect(cookie).toContain("RJ_api_session=signed.jwt.value");
expect(cookie).toContain("hivegrid_api_session=signed.jwt.value");
expect(cookie).toContain("Domain=example.com");
expect(cookie).toContain("SameSite=Lax");
expect(cookie).toContain("Secure");
expect(cookie).toContain("HttpOnly");
expect(cookie).toContain("Path=/");
expect(cookie).not.toContain("RJ_session=");
expect(cookie).not.toContain("hivegrid_session=");
expect(cookie).not.toContain(config.apiAccessToken);
expect(cookie).not.toContain(config.jwtSecret);
});
@@ -55,7 +56,7 @@ describe("serializeApiAuthCookie", () => {
test("omits Domain and Secure for localhost HTTP development", () => {
const cookie = serializeApiAuthCookie("local-token", baseConfig);
expect(cookie).toContain("RJ_api_session=local-token");
expect(cookie).toContain("hivegrid_api_session=local-token");
expect(cookie).toContain("SameSite=Lax");
expect(cookie).toContain("HttpOnly");
expect(cookie).toContain("Path=/");
@@ -68,7 +69,7 @@ describe("serializeApiAuthCookie", () => {
test("URL-encodes token values without serializing config secrets", () => {
const cookie = serializeApiAuthCookie("token with spaces;and=symbols", baseConfig);
expect(cookie).toContain("RJ_api_session=token%20with%20spaces%3Band%3Dsymbols");
expect(cookie).toContain("hivegrid_api_session=token%20with%20spaces%3Band%3Dsymbols");
expect(cookie).not.toContain("token with spaces;and=symbols");
expect(cookie).not.toContain(baseConfig.apiAccessToken);
expect(cookie).not.toContain(baseConfig.jwtSecret);
@@ -88,7 +89,7 @@ describe("serializeApiAuthCookie", () => {
} satisfies ApiConfig;
const cookie = serializeExpiredApiAuthCookie(config);
expect(cookie).toContain("RJ_api_session=");
expect(cookie).toContain("hivegrid_api_session=");
expect(cookie).toContain("Max-Age=0");
expect(cookie).toContain("Expires=Thu, 01 Jan 1970 00:00:00 GMT");
expect(cookie).toContain("Domain=example.com");
@@ -1,4 +1,4 @@
import { resolveApiSessionCookiePolicy, type ApiConfig } from "@toolctrl/config";
import { resolveApiSessionCookiePolicy, type ApiConfig } from "@hivegrid/config";
function serializeApiAuthCookieWithValue(value: string, config: ApiConfig, extraAttributes: string[] = []) {
const policy = resolveApiSessionCookiePolicy({
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { createSharedStore } from "@toolctrl/shared-store";
import { createSharedStore } from "@hivegrid/shared-store";
import {
LOGIN_RATE_LIMIT_ACCOUNT_ATTEMPTS,
@@ -17,7 +17,8 @@ import {
function request(account: string | undefined = "User@Example.com", ip: string | undefined = "203.0.113.10") {
return {
account,
headers: ip ? { "x-forwarded-for": ip } : {},
// Trusted proxy-set header — the limiter no longer trusts X-Forwarded-For.
headers: ip ? { "cf-connecting-ip": ip } : {},
};
}
@@ -76,14 +77,18 @@ describe("login rate limiter (shared-store)", () => {
expect(await checkLoginRateLimit(request("fresh@example.com", "203.0.113.2"))).toMatchObject({ allowed: true });
});
test("uses the first x-forwarded-for segment before x-real-ip and remote fallback", () => {
test("prefers trusted proxy headers and ignores spoofable X-Forwarded-For", () => {
// Cloudflare's CF-Connecting-IP wins over an attacker-forged X-Forwarded-For.
expect(
deriveLoginRateLimitClientIp({
headers: new Headers({ "x-forwarded-for": " 198.51.100.7, 10.0.0.1 ", "x-real-ip": "198.51.100.8" }),
headers: new Headers({ "x-forwarded-for": "1.2.3.4, 10.0.0.1", "cf-connecting-ip": "198.51.100.7" }),
remoteAddress: "198.51.100.9",
}),
).toBe("198.51.100.7");
// X-Real-IP is the next trusted fallback.
expect(deriveLoginRateLimitClientIp({ headers: { "x-real-ip": "198.51.100.8" }, remoteAddress: "198.51.100.9" })).toBe("198.51.100.8");
// A lone X-Forwarded-For is NOT trusted -> falls through to remoteAddress.
expect(deriveLoginRateLimitClientIp({ headers: { "x-forwarded-for": "203.0.113.9" }, remoteAddress: "198.51.100.9" })).toBe("198.51.100.9");
expect(deriveLoginRateLimitClientIp({ remoteAddress: "198.51.100.9" })).toBe("198.51.100.9");
expect(deriveLoginRateLimitClientIp({})).toBe("unknown");
});
@@ -1,4 +1,4 @@
import { createFixedWindowRateLimiter, type FixedWindowRateLimiter, type SharedStore } from "@toolctrl/shared-store";
import { createFixedWindowRateLimiter, type FixedWindowRateLimiter, type SharedStore } from "@hivegrid/shared-store";
import { getSharedStore } from "../shared-store.js";
export const LOGIN_RATE_LIMIT_WINDOW_MS = 60_000;
@@ -158,16 +158,17 @@ export function __resetLoginRateLimitStoreForTests(): void {
storeFactory = () => getSharedStore();
}
export function deriveLoginRateLimitClientIp(request: Pick<LoginRateLimitRequest, "headers" | "remoteAddress">): string {
const forwardedFor = readHeader(request.headers, "x-forwarded-for");
const forwardedClient = forwardedFor?.split(",")[0]?.trim();
if (forwardedClient) {
return forwardedClient;
}
// Trusted, proxy-set headers only. The leftmost X-Forwarded-For value is
// client-controlled, so keying the login throttle on it let an attacker reset
// their bucket by rotating the header (credential-stuffing bypass).
const TRUSTED_LOGIN_IP_HEADERS = ["cf-connecting-ip", "true-client-ip", "x-real-ip"] as const;
const realIp = readHeader(request.headers, "x-real-ip")?.trim();
if (realIp) {
return realIp;
export function deriveLoginRateLimitClientIp(request: Pick<LoginRateLimitRequest, "headers" | "remoteAddress">): string {
for (const headerName of TRUSTED_LOGIN_IP_HEADERS) {
const value = readHeader(request.headers, headerName)?.trim();
if (value) {
return value;
}
}
const remoteAddress = request.remoteAddress?.trim();
@@ -1,43 +0,0 @@
import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, resolve } from "node:path";
import { describe, expect, test } from "vitest";
const appSourcePath = resolve(dirname(fileURLToPath(import.meta.url)), "../app.ts");
const entityRowRoutesSourcePath = resolve(dirname(fileURLToPath(import.meta.url)), "../routes/entity-row-routes.ts");
const relationshipRoutesSourcePath = resolve(dirname(fileURLToPath(import.meta.url)), "../routes/relationship-routes.ts");
function read(path: string) {
return readFileSync(path, "utf8");
}
describe("API permission helper wiring", () => {
// The legacy v1 row + relationship routes were extracted out of
// `app.ts` into dedicated route modules. The assertions here pin the
// shared `authorizeApiEntityRowScope` / `authorizeApiRelationshipScope`
// helpers to those extraction sites so a regression that re-inlines
// permission checks in `app.ts` (or a different file) fails CI.
test("entity-row routes call the shared API permission helper", () => {
const src = read(entityRowRoutesSourcePath);
expect(src).toContain('import { authorizeApiEntityRowScope } from "../auth/permission.js";');
expect(src.match(/authorizeApiEntityRowScope\(/g)).toHaveLength(5);
});
test("relationship routes call the shared API permission helper", () => {
const src = read(relationshipRoutesSourcePath);
expect(src).toContain('import { authorizeApiRelationshipScope } from "../auth/permission.js";');
expect(src.match(/authorizeApiRelationshipScope\(/g)).toHaveLength(3);
});
test("app.ts does not define or call stale local entity-row scope helpers", () => {
const appSource = read(appSourcePath);
expect(appSource).not.toMatch(/function\s+authorizeEntityRowScope\b/);
expect(appSource).not.toMatch(/const\s+authorizeEntityRowScope\b/);
expect(appSource).not.toMatch(/=>\s*authorizeEntityRowScope\(/);
expect(appSource).not.toMatch(/\bauthorizeEntityRowScope\(/);
expect(appSource).not.toMatch(/\bgetEntityPermission\b/);
expect(appSource).not.toMatch(/\bverifyUserHasPermission\b/);
});
});
@@ -1,187 +0,0 @@
import type { LegacyApiKeySimple } from "@toolctrl/db/api-keys.server";
import type { LegacyEntity } from "@toolctrl/db/entities.server";
import { describe, expect, test } from "vitest";
import { createServicePrincipal } from "../auth.js";
import { authorizeApiEntityRowScope, authorizeApiRelationshipScope } from "./permission.js";
import { createStoredApiKeyPrincipal, type ApiScopeResult } from "./scope.js";
const NOW = new Date("2026-01-15T12:00:00.000Z");
function buildEntity(overrides: Partial<LegacyEntity> = {}): LegacyEntity {
return {
id: "entity-1",
name: "contacts",
description: null,
url: null,
multiTenant: true,
isPublic: false,
useAsUser: false,
createdById: null,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
...overrides,
};
}
function buildApiKey(overrides: Partial<LegacyApiKeySimple> = {}): LegacyApiKeySimple {
return {
id: "api-key-1",
alias: "Production key",
expires: new Date("2026-02-01T00:00:00.000Z"),
tenantId: "tenant-1",
active: true,
entities: [
{
entityId: "entity-1",
create: true,
read: true,
update: true,
delete: false,
},
{
entityId: "child-entity",
create: true,
read: true,
update: false,
delete: false,
},
],
tenant: {
id: "tenant-1",
name: "Tenant One",
slug: "tenant-one",
deactivatedReason: null,
},
...overrides,
};
}
function expectRedactedDeny(result: ApiScopeResult, reason: string) {
expect(result).toEqual({
allowed: false,
principalType: "api-key",
reason,
code: "FORBIDDEN_API_KEY_SCOPE",
});
const serialized = JSON.stringify(result);
expect(serialized).not.toContain("plaintext-secret");
expect(serialized).not.toContain("hash-value");
expect(serialized).not.toContain("service-token-value");
}
describe("authorizeApiEntityRowScope", () => {
test("allows entity row operations when the stored API key has the entity operation scope", () => {
const result = authorizeApiEntityRowScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: "tenant-1",
entity: buildEntity(),
operation: "read",
now: NOW,
});
expect(result).toEqual({
allowed: true,
principalType: "api-key",
});
});
test("denies entity row operations when the stored API key lacks the entity operation scope", () => {
const result = authorizeApiEntityRowScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: "tenant-1",
entity: buildEntity(),
operation: "delete",
now: NOW,
});
expectRedactedDeny(result, "operation_permission_missing");
});
test("fails closed for malformed legacy entities without an id", () => {
expect(() =>
authorizeApiEntityRowScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: "tenant-1",
entity: buildEntity({ id: "" }),
operation: "read",
now: NOW,
}),
).toThrow("Entity is missing an id.");
});
test("denies stored API keys when tenant scope cannot be resolved", () => {
const result = authorizeApiEntityRowScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: null,
entity: buildEntity(),
operation: "read",
now: NOW,
});
expectRedactedDeny(result, "tenant_mismatch");
});
});
describe("authorizeApiRelationshipScope", () => {
test("allows service-token principals for relationship operations without entity scopes", () => {
const result = authorizeApiRelationshipScope(createServicePrincipal(), {
tenantId: "tenant-1",
parentEntityId: "missing-parent",
childEntityId: "missing-child",
operation: "delete",
});
expect(result).toEqual({
allowed: true,
principalType: "service-token",
});
});
test("denies relationship operations when the parent entity lacks the requested operation", () => {
const result = authorizeApiRelationshipScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: "tenant-1",
parentEntityId: "missing-parent",
childEntityId: "child-entity",
operation: "read",
now: NOW,
});
expectRedactedDeny(result, "entity_permission_missing");
});
test("denies relationship operations when the child entity lacks the requested operation", () => {
const result = authorizeApiRelationshipScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: "tenant-1",
parentEntityId: "entity-1",
childEntityId: "child-entity",
operation: "update",
now: NOW,
});
expectRedactedDeny(result, "operation_permission_missing");
});
test("allows relationship operations when parent and child entities both include the requested operation", () => {
const result = authorizeApiRelationshipScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: "tenant-1",
parentEntityId: "entity-1",
childEntityId: "child-entity",
operation: "create",
now: NOW,
});
expect(result).toEqual({
allowed: true,
principalType: "api-key",
});
});
test("denies stored API keys for relationship operations when tenant scope cannot be resolved", () => {
const result = authorizeApiRelationshipScope(createStoredApiKeyPrincipal(buildApiKey()), {
tenantId: null,
parentEntityId: "entity-1",
childEntityId: "child-entity",
operation: "read",
now: NOW,
});
expectRedactedDeny(result, "tenant_mismatch");
});
});
@@ -1,54 +0,0 @@
import type { LegacyEntity } from "@toolctrl/db/entities.server";
import { authorizeApiScope, type ApiKeyScopeOperation, type ApiScopedPrincipal, type ApiScopeResult } from "./scope.js";
export type ApiEntityRowScopeRequest = {
tenantId: string | null;
entity: LegacyEntity;
operation: ApiKeyScopeOperation;
now?: Date;
};
export type ApiRelationshipScopeRequest = {
tenantId: string | null;
parentEntityId: string;
childEntityId: string;
operation: ApiKeyScopeOperation;
now?: Date;
};
export function authorizeApiEntityRowScope(principal: ApiScopedPrincipal, request: ApiEntityRowScopeRequest): ApiScopeResult {
return authorizeApiScope(principal, {
tenantId: request.tenantId ?? "",
entityId: getLegacyEntityId(request.entity),
operation: request.operation,
now: request.now,
});
}
export function authorizeApiRelationshipScope(principal: ApiScopedPrincipal, request: ApiRelationshipScopeRequest): ApiScopeResult {
const parentScope = authorizeApiScope(principal, {
tenantId: request.tenantId ?? "",
entityId: request.parentEntityId,
operation: request.operation,
now: request.now,
});
if (!parentScope.allowed) {
return parentScope;
}
return authorizeApiScope(principal, {
tenantId: request.tenantId ?? "",
entityId: request.childEntityId,
operation: request.operation,
now: request.now,
});
}
function getLegacyEntityId(entity: LegacyEntity) {
if (entity && typeof entity === "object" && "id" in entity && typeof entity.id === "string" && entity.id) {
return entity.id;
}
throw new Error("Entity is missing an id.");
}
@@ -1,130 +1,99 @@
import type { LegacyApiKeySimple } from "@toolctrl/db/api-keys.server";
import { describe, expect, test } from "vitest";
import { describe, expect, it } from "vitest";
import type { LegacyApiKeySimple } from "@hivegrid/db/api-keys.server";
import { createServicePrincipal } from "../auth.js";
import { authorizeApiScope, createStoredApiKeyPrincipal, type ApiScopeResult } from "./scope.js";
import type { ServicePrincipal } from "../auth.js";
import { createStoredApiKeyPrincipal, resolveApiTenantScope, type ApiScopedPrincipal } from "./scope.js";
const NOW = new Date("2026-01-15T12:00:00.000Z");
// R-P6B-β (AD-2): the entity-builder API-key *entity-scope* matrix was removed
// with the generic entity REST API; this test keeps the surviving tenant-scope
// resolution (service tokens + stored API keys) fully covered.
function buildApiKey(overrides: Partial<LegacyApiKeySimple> = {}): LegacyApiKeySimple {
return {
id: "api-key-1",
alias: "Production key",
expires: new Date("2026-02-01T00:00:00.000Z"),
tenantId: "tenant-1",
active: true,
entities: [
{
entityId: "entity-1",
create: true,
read: true,
update: true,
delete: false,
},
],
tenant: {
id: "tenant-1",
name: "Tenant One",
slug: "tenant-one",
deactivatedReason: null,
},
...overrides,
};
const serviceTokenPrincipal: ApiScopedPrincipal = { type: "service-token" } as ServicePrincipal;
function apiKeyPrincipal(overrides: Partial<{ active: boolean; expires: Date | null; tenantId: string; tenantDbId: string; deactivatedReason: string | null }> = {}) {
const { active = true, expires = null, tenantId = "tenant_1", tenantDbId = "tenant_1", deactivatedReason = null } = overrides;
const apiKey = {
id: "api_key_1",
tenantId,
active,
expires,
tenant: { id: tenantDbId, deactivatedReason },
} as unknown as LegacyApiKeySimple;
return createStoredApiKeyPrincipal(apiKey);
}
function authorize(apiKey: LegacyApiKeySimple, overrides: Partial<Parameters<typeof authorizeApiScope>[1]> = {}): ApiScopeResult {
return authorizeApiScope(createStoredApiKeyPrincipal(apiKey), {
tenantId: "tenant-1",
entityId: "entity-1",
operation: "read",
now: NOW,
...overrides,
describe("createStoredApiKeyPrincipal", () => {
it("wraps the API key in a stored-api-key principal", () => {
const apiKey = { id: "api_key_1" } as unknown as LegacyApiKeySimple;
expect(createStoredApiKeyPrincipal(apiKey)).toEqual({ type: "api-key", apiKey });
});
}
});
function expectRedactedDeny(result: ApiScopeResult, reason: string) {
expect(result).toEqual({
allowed: false,
principalType: "api-key",
reason,
code: "FORBIDDEN_API_KEY_SCOPE",
});
const serialized = JSON.stringify(result);
expect(serialized).not.toContain("plaintext-secret");
expect(serialized).not.toContain("hash-value");
expect(serialized).not.toContain("service-token");
}
describe("authorizeApiScope", () => {
test("allows service-token principals for every scoped operation", () => {
const principal = createServicePrincipal();
expect(
authorizeApiScope(principal, {
tenantId: "other-tenant",
entityId: "unknown-entity",
operation: "delete",
now: NOW,
}),
).toEqual({
describe("resolveApiTenantScope", () => {
it("allows service tokens for the requested tenant (including null)", () => {
expect(resolveApiTenantScope(serviceTokenPrincipal, "tenant_9")).toEqual({
allowed: true,
principalType: "service-token",
tenantId: "tenant_9",
});
expect(resolveApiTenantScope(serviceTokenPrincipal, null)).toEqual({
allowed: true,
principalType: "service-token",
tenantId: null,
});
});
test("allows active stored API keys with matching tenant, entity, and CRUD permission", () => {
expect(authorize(buildApiKey(), { operation: "create" })).toEqual({
allowed: true,
principalType: "api-key",
it("denies inactive API keys", () => {
expect(resolveApiTenantScope(apiKeyPrincipal({ active: false }), null)).toMatchObject({
allowed: false,
reason: "api_key_inactive",
code: "FORBIDDEN_API_KEY_SCOPE",
});
});
test("denies inactive stored API keys", () => {
expectRedactedDeny(authorize(buildApiKey({ active: false })), "api_key_inactive");
it("denies expired API keys (expiry at/under now)", () => {
const now = new Date("2026-06-30T12:00:00.000Z");
expect(resolveApiTenantScope(apiKeyPrincipal({ expires: new Date("2026-06-30T11:59:59.000Z") }), null, now)).toMatchObject({
allowed: false,
reason: "api_key_expired",
});
});
test("denies expired stored API keys", () => {
expectRedactedDeny(authorize(buildApiKey({ expires: new Date("2026-01-01T00:00:00.000Z") })), "api_key_expired");
it("denies API keys whose tenant is deactivated", () => {
expect(resolveApiTenantScope(apiKeyPrincipal({ deactivatedReason: "fraud" }), null)).toMatchObject({
allowed: false,
reason: "tenant_deactivated",
});
});
test("denies stored API keys for deactivated tenants", () => {
expectRedactedDeny(
authorize(
buildApiKey({
tenant: {
id: "tenant-1",
name: "Tenant One",
slug: "tenant-one",
deactivatedReason: "billing_issue",
},
}),
),
"tenant_deactivated",
);
it("denies a tenant/tenant.id row mismatch", () => {
expect(resolveApiTenantScope(apiKeyPrincipal({ tenantId: "tenant_1", tenantDbId: "tenant_2" }), null)).toMatchObject({
allowed: false,
reason: "tenant_mismatch",
});
});
test("denies stored API keys whose tenant does not match the request tenant", () => {
expectRedactedDeny(authorize(buildApiKey(), { tenantId: "tenant-2" }), "tenant_mismatch");
expectRedactedDeny(
authorize(
buildApiKey({
tenant: {
id: "tenant-2",
name: "Tenant Two",
slug: "tenant-two",
deactivatedReason: null,
},
}),
),
"tenant_mismatch",
);
it("denies a requested tenant that does not match the key tenant", () => {
expect(resolveApiTenantScope(apiKeyPrincipal({ tenantId: "tenant_1" }), "tenant_2")).toMatchObject({
allowed: false,
reason: "tenant_mismatch",
});
});
test("denies stored API keys missing the requested entity permission", () => {
expectRedactedDeny(authorize(buildApiKey(), { entityId: "entity-2" }), "entity_permission_missing");
it("allows a valid API key with no requested tenant and with a future expiry", () => {
const now = new Date("2026-06-30T12:00:00.000Z");
expect(resolveApiTenantScope(apiKeyPrincipal({ expires: new Date("2026-07-30T12:00:00.000Z") }), null, now)).toEqual({
allowed: true,
principalType: "api-key",
tenantId: "tenant_1",
});
});
test("denies stored API keys missing the requested CRUD operation permission", () => {
expectRedactedDeny(authorize(buildApiKey(), { operation: "delete" }), "operation_permission_missing");
it("allows a valid API key when the requested tenant matches", () => {
expect(resolveApiTenantScope(apiKeyPrincipal({ tenantId: "tenant_1" }), "tenant_1")).toEqual({
allowed: true,
principalType: "api-key",
tenantId: "tenant_1",
});
});
});
@@ -1,4 +1,4 @@
import type { LegacyApiKeySimple } from "@toolctrl/db/api-keys.server";
import type { LegacyApiKeySimple } from "@hivegrid/db/api-keys.server";
import type { ServicePrincipal } from "../auth.js";
@@ -13,20 +13,11 @@ export type StoredApiKeyPrincipal = {
export type ApiScopedPrincipal = ServicePrincipal | StoredApiKeyPrincipal;
export type ApiScopeRequest = {
tenantId: string;
entityId: string;
operation: ApiKeyScopeOperation;
now?: Date;
};
export type ApiScopeDenyReason =
| "api_key_inactive"
| "api_key_expired"
| "tenant_deactivated"
| "tenant_mismatch"
| "entity_permission_missing"
| "operation_permission_missing";
| "tenant_mismatch";
export type ApiScopeAllowed = {
allowed: true;
@@ -44,8 +35,6 @@ export type ApiScopeDenied = {
code: "FORBIDDEN_API_KEY_SCOPE";
};
export type ApiScopeResult = ApiScopeAllowed | ApiScopeDenied;
function deny(principalType: ApiScopedPrincipal["type"], reason: ApiScopeDenyReason): ApiScopeDenied {
return {
allowed: false,
@@ -62,48 +51,6 @@ export function createStoredApiKeyPrincipal(apiKey: LegacyApiKeySimple): StoredA
};
}
export function authorizeApiScope(principal: ApiScopedPrincipal, request: ApiScopeRequest): ApiScopeResult {
if (principal.type === "service-token") {
return {
allowed: true,
principalType: principal.type,
};
}
const { apiKey } = principal;
if (!apiKey.active) {
return deny(principal.type, "api_key_inactive");
}
if (apiKey.expires && apiKey.expires.getTime() <= (request.now ?? new Date()).getTime()) {
return deny(principal.type, "api_key_expired");
}
if (apiKey.tenant.deactivatedReason) {
return deny(principal.type, "tenant_deactivated");
}
if (apiKey.tenantId !== request.tenantId || apiKey.tenant.id !== request.tenantId) {
return deny(principal.type, "tenant_mismatch");
}
const entityPermission = apiKey.entities.find((entity) => entity.entityId === request.entityId);
if (!entityPermission) {
return deny(principal.type, "entity_permission_missing");
}
if (!entityPermission[request.operation]) {
return deny(principal.type, "operation_permission_missing");
}
return {
allowed: true,
principalType: principal.type,
};
}
export function resolveApiTenantScope(principal: ApiScopedPrincipal, requestedTenantId: string | null, now = new Date()): ApiTenantScopeAllowed | ApiScopeDenied {
if (principal.type === "service-token") {
return {
@@ -0,0 +1,573 @@
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
import { Hono } from "hono";
import { LagoBillingGatewayError, MolliePaymentGatewayError, type PaymentGatewayPayment } from "@hivegrid/billing";
import type { ApiConfig } from "@hivegrid/config";
import { createDefaultLagoInvoicePaymentStatusUpdater, createDefaultMollieWebhookResolver, postMollieBillingWebhookRequest } from "./mollie-webhook-route.js";
import { resetApiRuntimeConfigForTests, setApiRuntimeConfigForTests } from "../config.js";
import type { ApiErrorEnv } from "../middleware/error-envelope.js";
const TEST_API_CONFIG: ApiConfig = {
appName: "Test API",
nodeEnv: "test",
revision: "unknown",
listen: { port: 3001 },
routing: {
appBaseDomain: "localhost:3000",
webAppHost: "app.localhost:3000",
adminAppHost: "admin.localhost:3000",
apiHost: "api.localhost:3000",
protocol: "http",
},
origins: {},
apiAccessToken: "test-api-access-token",
jwtSecret: "test-jwt-secret-with-32-bytes-padding",
analytics: {},
mailjet: {},
lago: { timeoutMs: 10000 },
mollie: { apiKey: "test_mollie_key", timeoutMs: 10000 },
apiKeys: { allowLegacyPlaintextFallback: true },
storage: {},
};
beforeEach(() => {
setApiRuntimeConfigForTests(TEST_API_CONFIG);
});
afterEach(() => {
resetApiRuntimeConfigForTests();
});
function buildPayment(overrides: Partial<PaymentGatewayPayment> = {}): PaymentGatewayPayment {
return {
provider: "mollie",
providerPaymentId: "tr_test_123",
externalId: "payment_external_123",
status: "paid",
amountCents: 12900,
amountRefundedCents: null,
amountRemainingCents: 0,
currency: "EUR",
checkoutUrl: "https://www.mollie.com/checkout/test",
paidAt: "2026-07-04T03:00:00Z",
expiresAt: null,
metadata: {
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
paymentExternalId: "payment_external_123",
lagoCustomerId: null,
lagoSubscriptionId: null,
planCode: null,
seatQuantity: null,
},
...overrides,
};
}
function buildDeps(overrides: Partial<Parameters<typeof postMollieBillingWebhookRequest>[1]> = {}) {
return {
resolveMollieWebhookPayment: vi.fn(async () => buildPayment()),
findLegacyTenantById: vi.fn(async () => ({ id: "tenant_1", name: "Acme" }) as never),
applyMolliePaymentSync: vi.fn(async (input) => ({
tenantId: input.tenantId,
provider: "mollie" as const,
idempotencyKey: input.eventKey,
replayed: false,
status: "active" as const,
})),
applyLagoSubscriptionSync: vi.fn(async (input) => ({
tenantId: input.tenantId,
provider: "lago" as const,
idempotencyKey: input.eventKey,
replayed: false,
status: "active" as const,
})),
updateLagoInvoicePaymentStatus: vi.fn(async (input) => ({
provider: "lago" as const,
providerInvoiceId: input.invoiceExternalId,
number: "LAG-001",
externalCustomerId: input.tenantId,
status: "finalized" as const,
paymentStatus: input.paymentStatus,
invoiceType: "subscription",
currency: "EUR",
totalAmountCents: 12900,
issuingDate: "2026-07-04",
fileUrl: null,
})),
...overrides,
};
}
function buildApp(deps: ReturnType<typeof buildDeps>) {
const app = new Hono<ApiErrorEnv>();
app.post("/v1/billing/mollie/webhooks", (c) => postMollieBillingWebhookRequest(c, deps));
return app;
}
describe("postMollieBillingWebhookRequest", () => {
it("verifies a form webhook through Mollie and syncs tenant billing state", async () => {
const deps = buildDeps();
const app = buildApp(deps);
const res = await app.request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "id=tr_test_123",
});
expect(res.status).toBe(200);
await expect(res.json()).resolves.toEqual({
received: true,
provider: "mollie",
paymentId: "tr_test_123",
status: "paid",
synced: true,
replayed: false,
billingStatus: "active",
subscriptionSynced: false,
subscriptionReplay: false,
});
expect(deps.resolveMollieWebhookPayment).toHaveBeenCalledWith(expect.any(URLSearchParams));
expect(deps.findLegacyTenantById).toHaveBeenCalledWith("tenant_1");
expect(deps.applyMolliePaymentSync).toHaveBeenCalledWith(
expect.objectContaining({
tenantId: "tenant_1",
eventKey: "mollie:webhook:tr_test_123:paid:none",
paymentExternalId: "payment_external_123",
invoiceExternalId: "invoice_1",
status: "paid",
receivedAt: expect.any(Date),
})
);
expect(deps.updateLagoInvoicePaymentStatus).toHaveBeenCalledWith({
tenantId: "tenant_1",
invoiceExternalId: "invoice_1",
amountCents: 12900,
paymentStatus: "succeeded",
});
});
it("returns 400 when Mollie payload parsing rejects the payment id", async () => {
const deps = buildDeps({
resolveMollieWebhookPayment: vi.fn(async () => {
throw new MolliePaymentGatewayError("missing id", "WEBHOOK_INVALID");
}),
});
const app = buildApp(deps);
const res = await app.request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "",
});
expect(res.status).toBe(400);
await expect(res.json()).resolves.toMatchObject({ error: { code: "invalid_request" } });
expect(deps.applyMolliePaymentSync).not.toHaveBeenCalled();
});
it("returns 422 when verified Mollie metadata cannot be mapped", async () => {
const deps = buildDeps({
resolveMollieWebhookPayment: vi.fn(async () =>
buildPayment({
metadata: {
tenantId: null,
invoiceExternalId: "invoice_1",
paymentExternalId: null,
lagoCustomerId: null,
lagoSubscriptionId: null,
planCode: null,
seatQuantity: null,
},
})
),
});
const app = buildApp(deps);
const res = await app.request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ id: "tr_test_123" }),
});
expect(res.status).toBe(400);
await expect(res.json()).resolves.toMatchObject({ error: { code: "invalid_provider_payload" } });
expect(deps.findLegacyTenantById).not.toHaveBeenCalled();
expect(deps.applyMolliePaymentSync).not.toHaveBeenCalled();
});
it("returns 422 when the verified payment references an unknown tenant", async () => {
const deps = buildDeps({
findLegacyTenantById: vi.fn(async () => null),
});
const app = buildApp(deps);
const res = await app.request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "id=tr_test_123",
});
expect(res.status).toBe(400);
await expect(res.json()).resolves.toMatchObject({ error: { code: "invalid_provider_payload" } });
expect(deps.applyMolliePaymentSync).not.toHaveBeenCalled();
});
it("returns 503 when provider verification fails before sync", async () => {
const deps = buildDeps({
resolveMollieWebhookPayment: vi.fn(async () => {
throw new MolliePaymentGatewayError("upstream failed", "REQUEST_FAILED", 500);
}),
});
const app = buildApp(deps);
const res = await app.request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "id=tr_test_123",
});
expect(res.status).toBe(503);
await expect(res.json()).resolves.toMatchObject({ error: { code: "provider_unavailable" } });
expect(deps.applyMolliePaymentSync).not.toHaveBeenCalled();
});
it("surfaces idempotent replays without applying a second logical sync", async () => {
const deps = buildDeps({
applyMolliePaymentSync: vi.fn(async (input) => ({
tenantId: input.tenantId,
provider: "mollie" as const,
idempotencyKey: input.eventKey,
replayed: true,
status: "active" as const,
})),
});
const app = buildApp(deps);
const res = await app.request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "id=tr_test_123",
});
expect(res.status).toBe(200);
await expect(res.json()).resolves.toMatchObject({ synced: false, replayed: true, billingStatus: "active" });
});
it("activates the Lago subscription from paid self-service checkout metadata", async () => {
const deps = buildDeps({
resolveMollieWebhookPayment: vi.fn(async () =>
buildPayment({
metadata: {
tenantId: "tenant_1",
invoiceExternalId: "hgco_123",
paymentExternalId: "hgco_123",
lagoCustomerId: "lago_customer_1",
lagoSubscriptionId: "hgco_123",
planCode: "grow",
seatQuantity: 4,
},
})
),
});
const app = buildApp(deps);
const res = await app.request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "id=tr_test_123",
});
expect(res.status).toBe(200);
await expect(res.json()).resolves.toMatchObject({ subscriptionSynced: true, subscriptionReplay: false });
expect(deps.applyLagoSubscriptionSync).toHaveBeenCalledWith(
expect.objectContaining({
tenantId: "tenant_1",
eventKey: "mollie:lago:tr_test_123:paid",
lagoCustomerId: "lago_customer_1",
lagoSubscriptionId: "hgco_123",
planCode: "grow",
seatQuantity: 4,
invoiceExternalId: "hgco_123",
status: "active",
})
);
expect(deps.updateLagoInvoicePaymentStatus).toHaveBeenCalledWith({
tenantId: "tenant_1",
invoiceExternalId: "hgco_123",
amountCents: 12900,
paymentStatus: "succeeded",
});
});
it("falls back to the latest matching Lago invoice when the checkout id is not a Lago invoice id", async () => {
setApiRuntimeConfigForTests({
...TEST_API_CONFIG,
lago: { apiUrl: "https://lago.example.test", apiKey: "test_lago_key", timeoutMs: 10000 },
});
const fetchImpl = vi.spyOn(globalThis, "fetch").mockImplementation(
vi.fn<typeof fetch>(async (input, init) => {
const url = String(input);
if (url === "https://lago.example.test/api/v1/invoices/hgco_123" && init?.method === "PUT") {
return new Response("{}", { status: 404 });
}
if (url === "https://lago.example.test/api/v1/invoices?external_customer_id=tenant_1&page=1&per_page=50") {
return new Response(
JSON.stringify({
invoices: [
{
lago_id: "lago_invoice_old",
number: "HIV-001",
external_customer_id: "tenant_1",
status: "finalized",
payment_status: "pending",
invoice_type: "subscription",
currency: "EUR",
total_amount_cents: 12900,
issuing_date: "2026-07-04",
file_url: null,
},
{
lago_id: "lago_invoice_1",
number: "HIV-012",
external_customer_id: "tenant_1",
status: "finalized",
payment_status: "pending",
invoice_type: "subscription",
currency: "EUR",
total_amount_cents: 12900,
issuing_date: "2026-07-04",
file_url: null,
},
],
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
if (url === "https://lago.example.test/api/v1/invoices/lago_invoice_1" && init?.method === "PUT") {
return new Response(
JSON.stringify({
invoice: {
lago_id: "lago_invoice_1",
number: "HIV-001",
external_customer_id: "tenant_1",
status: "finalized",
payment_status: "succeeded",
invoice_type: "subscription",
currency: "EUR",
total_amount_cents: 12900,
issuing_date: "2026-07-04",
file_url: null,
},
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
return new Response("{}", { status: 500 });
})
);
await expect(
createDefaultLagoInvoicePaymentStatusUpdater()({
tenantId: "tenant_1",
invoiceExternalId: "hgco_123",
amountCents: 12900,
paymentStatus: "succeeded",
})
).resolves.toMatchObject({ providerInvoiceId: "lago_invoice_1", paymentStatus: "succeeded" });
expect(fetchImpl).toHaveBeenCalledTimes(3);
});
it("returns 503 when the Mollie webhook configuration is unavailable", async () => {
setApiRuntimeConfigForTests({ ...TEST_API_CONFIG, mollie: { timeoutMs: 10000 } });
const deps = buildDeps();
const res = await buildApp(deps).request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "id=tr_test_123",
});
expect(res.status).toBe(503);
await expect(res.json()).resolves.toMatchObject({ error: { code: "dependency_unavailable" } });
expect(deps.resolveMollieWebhookPayment).not.toHaveBeenCalled();
});
it("returns 404 when the Mollie payment cannot be verified", async () => {
const deps = buildDeps({
resolveMollieWebhookPayment: vi.fn(async () => {
throw new MolliePaymentGatewayError("not found", "WEBHOOK_PAYMENT_NOT_FOUND");
}),
});
const res = await buildApp(deps).request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "id=tr_test_123",
});
expect(res.status).toBe(404);
await expect(res.json()).resolves.toMatchObject({ error: { code: "not_found" } });
});
it("rethrows non-Mollie errors raised during verification", async () => {
const deps = buildDeps({
resolveMollieWebhookPayment: vi.fn(async () => {
throw new Error("boom");
}),
});
const res = await buildApp(deps).request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "id=tr_test_123",
});
expect(res.status).toBe(500);
});
it("skips the Lago invoice update and subscription sync for non-settling statuses", async () => {
const deps = buildDeps({
resolveMollieWebhookPayment: vi.fn(async () => buildPayment({ status: "open" })),
});
const res = await buildApp(deps).request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "id=tr_test_123",
});
expect(res.status).toBe(200);
await expect(res.json()).resolves.toMatchObject({ status: "open", subscriptionSynced: false });
expect(deps.updateLagoInvoicePaymentStatus).not.toHaveBeenCalled();
expect(deps.applyLagoSubscriptionSync).not.toHaveBeenCalled();
});
it("marks the Lago invoice failed for a failed Mollie payment", async () => {
const deps = buildDeps({
resolveMollieWebhookPayment: vi.fn(async () => buildPayment({ status: "failed" })),
});
const res = await buildApp(deps).request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "id=tr_test_123",
});
expect(res.status).toBe(200);
expect(deps.updateLagoInvoicePaymentStatus).toHaveBeenCalledWith(expect.objectContaining({ paymentStatus: "failed" }));
expect(deps.applyLagoSubscriptionSync).not.toHaveBeenCalled();
});
it("returns 503 when the Lago invoice payment status sync fails", async () => {
const deps = buildDeps({
updateLagoInvoicePaymentStatus: vi.fn(async () => {
throw new LagoBillingGatewayError("lago down", "CONFIG_INVALID");
}),
});
const res = await buildApp(deps).request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "id=tr_test_123",
});
expect(res.status).toBe(503);
await expect(res.json()).resolves.toMatchObject({ error: { code: "provider_unavailable" } });
});
it("rethrows non-Lago errors raised during invoice status sync", async () => {
const deps = buildDeps({
updateLagoInvoicePaymentStatus: vi.fn(async () => {
throw new Error("unexpected");
}),
});
const res = await buildApp(deps).request("/v1/billing/mollie/webhooks", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "id=tr_test_123",
});
expect(res.status).toBe(500);
});
it("parses multipart/form-data webhook payloads", async () => {
const deps = buildDeps();
const form = new FormData();
form.set("id", "tr_test_123");
const res = await buildApp(deps).request("/v1/billing/mollie/webhooks", { method: "POST", body: form });
// The multipart branch parses via c.req.formData(); assert the request completed and the
// resolver ran (avoids a cross-realm FormData constructor-identity mismatch under vitest).
expect(res.status).toBe(200);
expect(deps.resolveMollieWebhookPayment).toHaveBeenCalledTimes(1);
});
});
describe("createDefaultMollieWebhookResolver", () => {
it("throws when the Mollie API key is missing", () => {
setApiRuntimeConfigForTests({ ...TEST_API_CONFIG, mollie: { timeoutMs: 10000 } });
expect(() => createDefaultMollieWebhookResolver()(new URLSearchParams("id=tr_1"))).toThrow(MolliePaymentGatewayError);
});
});
describe("createDefaultLagoInvoicePaymentStatusUpdater", () => {
const updaterInput = { tenantId: "tenant_1", invoiceExternalId: "hgco_123", amountCents: 12900, paymentStatus: "succeeded" as const };
const lagoConfig = { apiUrl: "https://lago.example.test", apiKey: "test_lago_key", timeoutMs: 10000 };
afterEach(() => {
vi.restoreAllMocks();
});
it("throws when the Lago configuration is unavailable", async () => {
setApiRuntimeConfigForTests({ ...TEST_API_CONFIG, lago: { timeoutMs: 10000 } });
await expect(createDefaultLagoInvoicePaymentStatusUpdater()(updaterInput)).rejects.toBeInstanceOf(LagoBillingGatewayError);
});
it("updates the invoice directly when the checkout id is a Lago invoice id", async () => {
setApiRuntimeConfigForTests({ ...TEST_API_CONFIG, lago: lagoConfig });
const fetchImpl = vi.spyOn(globalThis, "fetch").mockImplementation(
vi.fn<typeof fetch>(async (input, init) => {
const url = String(input);
if (url === "https://lago.example.test/api/v1/invoices/hgco_123" && init?.method === "PUT") {
return new Response(
JSON.stringify({
invoice: {
lago_id: "hgco_123",
number: "HIV-001",
external_customer_id: "tenant_1",
status: "finalized",
payment_status: "succeeded",
invoice_type: "subscription",
currency: "EUR",
total_amount_cents: 12900,
issuing_date: "2026-07-04",
file_url: null,
},
}),
{ status: 200, headers: { "content-type": "application/json" } }
);
}
return new Response("{}", { status: 500 });
})
);
await expect(createDefaultLagoInvoicePaymentStatusUpdater()(updaterInput)).resolves.toMatchObject({
providerInvoiceId: "hgco_123",
paymentStatus: "succeeded",
});
expect(fetchImpl).toHaveBeenCalledTimes(1);
});
it("rethrows non-404 Lago errors from the direct invoice update", async () => {
setApiRuntimeConfigForTests({ ...TEST_API_CONFIG, lago: lagoConfig });
vi.spyOn(globalThis, "fetch").mockImplementation(vi.fn<typeof fetch>(async () => new Response("{}", { status: 500 })));
await expect(createDefaultLagoInvoicePaymentStatusUpdater()(updaterInput)).rejects.toBeInstanceOf(LagoBillingGatewayError);
});
it("returns null when no pending Lago invoice matches the payment", async () => {
setApiRuntimeConfigForTests({ ...TEST_API_CONFIG, lago: lagoConfig });
vi.spyOn(globalThis, "fetch").mockImplementation(
vi.fn<typeof fetch>(async (input, init) => {
const url = String(input);
if (url.includes("/invoices/hgco_123") && init?.method === "PUT") return new Response("{}", { status: 404 });
if (url.includes("/invoices?")) {
return new Response(JSON.stringify({ invoices: [] }), { status: 200, headers: { "content-type": "application/json" } });
}
return new Response("{}", { status: 500 });
})
);
await expect(createDefaultLagoInvoicePaymentStatusUpdater()(updaterInput)).resolves.toBeNull();
});
});
@@ -0,0 +1,228 @@
import {
createLagoBillingGateway,
createMolliePaymentGateway,
LagoBillingGatewayError,
MolliePaymentGatewayError,
resolveMollieWebhookPayment,
type BillingGatewayInvoice,
type PaymentGatewayPayment,
} from "@hivegrid/billing";
import type { ApplyLagoSubscriptionSyncInput, ApplyMolliePaymentSyncInput, BillingSyncResult } from "@hivegrid/db/billing-sync.server";
import type { Context } from "hono";
import type { ApiAppDependencies } from "../app.js";
import { getApiRuntimeConfig } from "../config.js";
import { apiError, type ApiErrorEnv } from "../middleware/error-envelope.js";
type MollieWebhookInput = URLSearchParams | FormData | Record<string, unknown>;
type LagoInvoicePaymentStatusUpdateInput = {
tenantId: string;
invoiceExternalId: string;
amountCents: number | null;
paymentStatus: BillingGatewayInvoice["paymentStatus"];
};
type LagoInvoicePaymentStatusUpdater = (input: LagoInvoicePaymentStatusUpdateInput) => Promise<BillingGatewayInvoice | null>;
export type MollieBillingWebhookDependencies = Pick<
ApiAppDependencies,
"applyLagoSubscriptionSync" | "applyMolliePaymentSync" | "findLegacyTenantById" | "resolveMollieWebhookPayment" | "updateLagoInvoicePaymentStatus"
>;
export async function postMollieBillingWebhookRequest(c: Context<ApiErrorEnv>, dependencies: MollieBillingWebhookDependencies) {
const config = getApiRuntimeConfig();
if (!config.mollie.apiKey) {
return apiError(c, 503, "dependency_unavailable", "Mollie billing webhook configuration is unavailable.");
}
const input = await parseMollieWebhookInput(c);
let payment: PaymentGatewayPayment;
try {
payment = await dependencies.resolveMollieWebhookPayment(input);
} catch (error) {
if (error instanceof MolliePaymentGatewayError) {
if (error.code === "WEBHOOK_INVALID" || error.code === "CONFIG_INVALID") {
return apiError(c, 400, "invalid_request", "Invalid Mollie webhook payload.");
}
if (error.code === "WEBHOOK_PAYMENT_NOT_FOUND") {
return apiError(c, 404, "not_found", "Mollie payment could not be verified.");
}
return apiError(c, 503, "provider_unavailable", "Mollie payment verification failed.");
}
throw error;
}
const tenantId = payment.metadata.tenantId?.trim() || null;
const invoiceExternalId = payment.metadata.invoiceExternalId?.trim() || null;
if (!tenantId || !invoiceExternalId) {
return apiError(c, 400, "invalid_provider_payload", "Mollie payment metadata is missing billing references.");
}
const tenant = await dependencies.findLegacyTenantById(tenantId);
if (!tenant) {
return apiError(c, 400, "invalid_provider_payload", "Mollie payment metadata references an unknown tenant.");
}
const receivedAt = new Date();
const result = await dependencies.applyMolliePaymentSync(buildMollieSyncInput(payment, tenantId, invoiceExternalId, receivedAt));
const invoicePaymentStatus = toLagoInvoicePaymentStatus(payment.status);
if (invoicePaymentStatus) {
try {
await dependencies.updateLagoInvoicePaymentStatus({
tenantId,
invoiceExternalId,
amountCents: payment.amountCents,
paymentStatus: invoicePaymentStatus,
});
} catch (error) {
if (error instanceof LagoBillingGatewayError) {
return apiError(c, 503, "provider_unavailable", "Lago invoice payment status sync failed.");
}
throw error;
}
}
const subscriptionResult = await syncLagoSubscriptionFromPaidMolliePayment(payment, tenantId, invoiceExternalId, receivedAt, dependencies);
return c.json(toMollieWebhookResponse(payment, result, subscriptionResult));
}
export function createDefaultMollieWebhookResolver() {
return (input: MollieWebhookInput) => {
const config = getApiRuntimeConfig();
if (!config.mollie.apiKey) {
throw new MolliePaymentGatewayError("Mollie API key is required.", "CONFIG_INVALID");
}
return resolveMollieWebhookPayment(
createMolliePaymentGateway({
apiKey: config.mollie.apiKey,
profileId: config.mollie.profileId ?? null,
timeoutMs: config.mollie.timeoutMs,
}),
input
);
};
}
export function createDefaultLagoInvoicePaymentStatusUpdater(): LagoInvoicePaymentStatusUpdater {
return async ({ tenantId, invoiceExternalId, amountCents, paymentStatus }) => {
const config = getApiRuntimeConfig();
if (!config.lago.apiUrl || !config.lago.apiKey) {
throw new LagoBillingGatewayError("Lago invoice sync configuration is unavailable.", "CONFIG_INVALID");
}
const gateway = createLagoBillingGateway({
apiUrl: config.lago.apiUrl,
apiKey: config.lago.apiKey,
timeoutMs: config.lago.timeoutMs,
});
try {
return await gateway.updateInvoicePaymentStatus(invoiceExternalId, paymentStatus);
} catch (error) {
if (!(error instanceof LagoBillingGatewayError) || error.status !== 404) throw error;
}
const invoices = await gateway.listInvoices({ tenantId, perPage: 50 });
const matchingInvoice = invoices
.filter((invoice) => {
if (invoice.paymentStatus !== "pending") return false;
if (typeof amountCents === "number" && invoice.totalAmountCents !== amountCents) return false;
return invoice.providerInvoiceId.trim().length > 0;
})
.sort(compareInvoicesNewestFirst)[0];
if (!matchingInvoice) return null;
return gateway.updateInvoicePaymentStatus(matchingInvoice.providerInvoiceId, paymentStatus);
};
}
function compareInvoicesNewestFirst(a: BillingGatewayInvoice, b: BillingGatewayInvoice): number {
const issuingDateCompare = (b.issuingDate ?? "").localeCompare(a.issuingDate ?? "");
if (issuingDateCompare !== 0) return issuingDateCompare;
return (b.number ?? b.providerInvoiceId).localeCompare(a.number ?? a.providerInvoiceId, undefined, { numeric: true, sensitivity: "base" });
}
async function parseMollieWebhookInput(c: Context): Promise<MollieWebhookInput> {
const contentType = c.req.header("content-type")?.toLowerCase() ?? "";
if (contentType.includes("application/json")) {
return (await c.req.json().catch(() => ({}))) as Record<string, unknown>;
}
if (contentType.includes("multipart/form-data")) {
return await c.req.formData();
}
return new URLSearchParams(await c.req.text());
}
function buildMollieSyncInput(
payment: PaymentGatewayPayment,
tenantId: string,
invoiceExternalId: string,
receivedAt: Date
): ApplyMolliePaymentSyncInput {
return {
tenantId,
eventKey: buildMollieWebhookEventKey(payment),
paymentExternalId: payment.externalId ?? payment.providerPaymentId,
invoiceExternalId,
status: payment.status,
receivedAt,
};
}
function buildMollieWebhookEventKey(payment: PaymentGatewayPayment): string {
const refundPart = typeof payment.amountRefundedCents === "number" ? payment.amountRefundedCents : "none";
return `mollie:webhook:${payment.providerPaymentId}:${payment.status}:${refundPart}`.replace(/[^A-Za-z0-9._:-]/gu, "_").slice(0, 256);
}
function toLagoInvoicePaymentStatus(paymentStatus: PaymentGatewayPayment["status"]): BillingGatewayInvoice["paymentStatus"] | null {
if (paymentStatus === "paid" || paymentStatus === "authorized") return "succeeded";
if (paymentStatus === "failed" || paymentStatus === "expired" || paymentStatus === "canceled" || paymentStatus === "refunded" || paymentStatus === "charged_back") {
return "failed";
}
return null;
}
function buildLagoSyncInputFromPayment(
payment: PaymentGatewayPayment,
tenantId: string,
invoiceExternalId: string,
receivedAt: Date
): ApplyLagoSubscriptionSyncInput | null {
if (payment.status !== "paid" && payment.status !== "authorized") return null;
const planCode = payment.metadata.planCode?.trim();
const lagoSubscriptionId = payment.metadata.lagoSubscriptionId?.trim();
if (!planCode || !lagoSubscriptionId) return null;
return {
tenantId,
eventKey: `mollie:lago:${payment.providerPaymentId}:${payment.status}`.replace(/[^A-Za-z0-9._:-]/gu, "_").slice(0, 256),
lagoCustomerId: payment.metadata.lagoCustomerId,
lagoSubscriptionId,
planCode,
seatQuantity: payment.metadata.seatQuantity,
invoiceExternalId,
status: "active",
receivedAt,
};
}
async function syncLagoSubscriptionFromPaidMolliePayment(
payment: PaymentGatewayPayment,
tenantId: string,
invoiceExternalId: string,
receivedAt: Date,
dependencies: MollieBillingWebhookDependencies
): Promise<BillingSyncResult | null> {
const input = buildLagoSyncInputFromPayment(payment, tenantId, invoiceExternalId, receivedAt);
if (!input) return null;
return dependencies.applyLagoSubscriptionSync(input);
}
function toMollieWebhookResponse(payment: PaymentGatewayPayment, result: BillingSyncResult, subscriptionResult: BillingSyncResult | null) {
return {
received: true,
provider: "mollie",
paymentId: payment.providerPaymentId,
status: payment.status,
synced: !result.replayed,
replayed: result.replayed,
billingStatus: result.status,
subscriptionSynced: subscriptionResult ? !subscriptionResult.replayed : false,
subscriptionReplay: subscriptionResult ? subscriptionResult.replayed : false,
};
}
@@ -1,566 +0,0 @@
import { describe, it, expect, beforeEach, vi } from "vitest";
import { Hono } from "hono";
import type Stripe from "stripe";
vi.mock("../cache/subscription-cache-publisher.js", () => {
const fn = vi.fn().mockResolvedValue(undefined);
(globalThis as typeof globalThis & { __publishMock?: ReturnType<typeof vi.fn> }).__publishMock = fn;
return {
publishSubscriptionInvalidation: fn,
__resetSubscriptionCachePublisherForTests: vi.fn(),
};
});
function getPublishMock(): ReturnType<typeof vi.fn> {
return (globalThis as typeof globalThis & { __publishMock: ReturnType<typeof vi.fn> }).__publishMock;
}
import { postStripeBillingWebhookRequest, type StripeWebhookTransactionClient } from "./stripe-webhook-route.js";
import { getApiMetrics, resetApiMetricsForTests } from "../metrics.js";
import { apiLogger } from "../logger.js";
import type { ApiErrorEnv } from "../middleware/error-envelope.js";
beforeEach(() => {
resetApiMetricsForTests();
getPublishMock().mockClear();
process.env.STRIPE_SK = "sk_test_abc";
process.env.STRIPE_WEBHOOK_SIGNING_SECRET = "whsec_test";
process.env.API_ACCESS_TOKEN = "test-access-token";
process.env.ANALYTICS_TOKEN = "test-analytics-token";
process.env.SESSION_SECRET = "test-session-secret-with-32-bytes-of-entropy-padding";
process.env.CRYPTO_SECRET = "test-crypto-secret-with-32-bytes-padding-yo";
process.env.APP_BASE_DOMAIN = "localhost";
process.env.DATABASE_URL = "postgres://test:test@localhost:5432/test";
});
function buildDeps(overrides: Partial<Parameters<typeof postStripeBillingWebhookRequest>[1]> = {}) {
// Default transaction runner just invokes the callback with a stub tx
// so callers can wire publishOutboxEvent. Tests overriding this must
// make sure the surrounding contract still holds.
return {
constructStripeWebhookEvent: ((payload: string, signature: string) => {
void payload;
void signature;
return { id: "evt_test_default", type: "invoice.paid", data: { object: { id: "in_test" } } } as unknown as Stripe.Event;
}) as never,
retrieveStripeSubscription: (async () => null) as never,
findTenantSubscriptionProductByStripeSubscriptionId: (async () => null) as never,
updateTenantSubscriptionProductFromStripe: (async () => undefined) as never,
runStripeWebhookTransaction: (async <T,>(fn: (tx: StripeWebhookTransactionClient) => Promise<T>) =>
fn({} as unknown as StripeWebhookTransactionClient)) as never,
publishOutboxEvent: (async () => ({ id: "outbox-1" })) as never,
...overrides,
};
}
function buildApp(deps: ReturnType<typeof buildDeps>) {
const app = new Hono<ApiErrorEnv>();
app.post("/v1/billing/stripe/webhooks", (c) => postStripeBillingWebhookRequest(c, deps));
return app;
}
describe("postStripeBillingWebhookRequest", () => {
it("records status=received with the event_type label on success", async () => {
const app = buildApp(buildDeps());
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: JSON.stringify({}),
});
expect(res.status).toBe(200);
const text = await getApiMetrics().registry.metrics();
expect(text).toMatch(/stripe_webhook_events_total\{[^}]*event_type="invoice.paid"[^}]*status="received"[^}]*\} 1/);
});
it("records status=missing_signature when stripe-signature header is absent", async () => {
const app = buildApp(buildDeps());
const res = await app.request("/v1/billing/stripe/webhooks", { method: "POST", body: "{}" });
expect(res.status).toBe(400);
const text = await getApiMetrics().registry.metrics();
expect(text).toMatch(/stripe_webhook_events_total\{[^}]*event_type="unknown"[^}]*status="missing_signature"[^}]*\} 1/);
});
it("publishes a subscription invalidation after updating the tenant subscription product", async () => {
const stripeSubscription = {
id: "sub_test",
cancel_at: null,
canceled_at: null,
ended_at: null,
items: {
data: [
{
id: "si_test",
current_period_start: 1_700_000_000,
current_period_end: 1_702_592_000,
},
],
},
} as unknown as Stripe.Subscription;
const tenantSubscriptionProduct = {
id: "tsp-1",
endsAt: null,
cancelledAt: null,
tenantSubscription: { tenant: { id: "tenant-abc", name: "Acme" } },
subscriptionProduct: { title: "Pro Plan" },
} as unknown as never;
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() =>
({ id: "evt_test_sub_update", type: "customer.subscription.updated", data: { object: { id: "sub_test" } } } as unknown as Stripe.Event)) as never,
retrieveStripeSubscription: (async () => stripeSubscription) as never,
findTenantSubscriptionProductByStripeSubscriptionId: (async () => tenantSubscriptionProduct as never) as never,
updateTenantSubscriptionProductFromStripe: (async () => undefined) as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
expect(res.status).toBe(200);
expect(getPublishMock()).toHaveBeenCalledWith("tenant-abc");
});
it("wraps the subscription update and outbox publishes in a single transaction (Phase 03 #42)", async () => {
const stripeSubscription = {
id: "sub_test",
cancel_at: 1_700_100_000, // triggers both endsAt + cancelledAt branches
canceled_at: null,
ended_at: null,
items: {
data: [
{
id: "si_test",
current_period_start: 1_700_000_000,
current_period_end: 1_702_592_000,
},
],
},
} as unknown as Stripe.Subscription;
const tenantSubscriptionProduct = {
id: "tsp-1",
endsAt: null,
cancelledAt: null,
tenantSubscription: { tenant: { id: "tenant-abc", name: "Acme" } },
subscriptionProduct: { title: "Pro Plan" },
} as unknown as never;
const updateCalls: Array<{ id: string; data: Record<string, unknown>; usedTxClient: boolean }> = [];
const publishCalls: Array<{ tenantId: string | null | undefined; type: string; payload: unknown; dispatchKey?: string | null }> = [];
const txClientSentinel = { __isStripeTx: true } as unknown as StripeWebhookTransactionClient;
let transactionsStarted = 0;
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() =>
({ id: "evt_test_lifecycle", type: "customer.subscription.updated", data: { object: { id: "sub_test" } } } as unknown as Stripe.Event)) as never,
retrieveStripeSubscription: (async () => stripeSubscription) as never,
findTenantSubscriptionProductByStripeSubscriptionId: (async () => tenantSubscriptionProduct as never) as never,
updateTenantSubscriptionProductFromStripe: (async (id: string, data: Record<string, unknown>, client?: unknown) => {
updateCalls.push({ id, data, usedTxClient: client === txClientSentinel });
return undefined;
}) as never,
runStripeWebhookTransaction: (async <T,>(fn: (tx: StripeWebhookTransactionClient) => Promise<T>) => {
transactionsStarted += 1;
return fn(txClientSentinel);
}) as never,
publishOutboxEvent: (async (tx: unknown, args: { tenantId?: string | null; type: string; payload: unknown; dispatchKey?: string | null }) => {
publishCalls.push({ tenantId: args.tenantId, type: args.type, payload: args.payload, dispatchKey: args.dispatchKey ?? null });
expect(tx).toBe(txClientSentinel);
return { id: `outbox-${publishCalls.length}` };
}) as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
expect(res.status).toBe(200);
expect(transactionsStarted).toBe(1);
expect(updateCalls).toHaveLength(1);
expect(updateCalls[0]!.usedTxClient).toBe(true);
expect(publishCalls).toHaveLength(2);
const types = publishCalls.map((c) => c.type).sort();
expect(types).toEqual(["billing.subscription.cancelled", "billing.subscription.ended"]);
for (const c of publishCalls) {
expect(c.tenantId).toBe("tenant-abc");
expect(c.dispatchKey).toMatch(/^stripe:evt_test_lifecycle:subscription\.(ended|cancelled)$/);
const payload = c.payload as { name: string; tenantId: string; description: string };
expect(payload.tenantId).toBe("tenant-abc");
expect(payload.description).toMatch(/Acme subscription/);
expect(["subscription.ended", "subscription.cancelled"]).toContain(payload.name);
}
});
it("records status=invalid_signature when constructEvent throws", async () => {
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() => {
throw new Error("bad sig");
}) as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "bogus" },
body: "{}",
});
expect(res.status).toBe(400);
const text = await getApiMetrics().registry.metrics();
expect(text).toMatch(/stripe_webhook_events_total\{[^}]*status="invalid_signature"[^}]*\} 1/);
});
it("records status=config_unavailable when stripe secrets are missing", async () => {
const prevSk = process.env.STRIPE_SK;
const prevSecret = process.env.STRIPE_WEBHOOK_SIGNING_SECRET;
delete process.env.STRIPE_SK;
delete process.env.STRIPE_WEBHOOK_SIGNING_SECRET;
try {
const app = buildApp(buildDeps());
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
expect(res.status).toBe(503);
const text = await getApiMetrics().registry.metrics();
expect(text).toMatch(/stripe_webhook_events_total\{[^}]*status="config_unavailable"[^}]*\} 1/);
} finally {
if (prevSk !== undefined) process.env.STRIPE_SK = prevSk;
if (prevSecret !== undefined) process.env.STRIPE_WEBHOOK_SIGNING_SECRET = prevSecret;
}
});
it("extracts the subscription id from a string-shaped subscription_schedule.canceled event", async () => {
const retrieveStripeSubscription = vi.fn(async () => null);
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() =>
({
id: "evt_schedule_string",
type: "subscription_schedule.canceled",
data: { object: { id: "schedule_1", subscription: "sub_via_string" } },
} as unknown as Stripe.Event)) as never,
retrieveStripeSubscription: retrieveStripeSubscription as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
expect(res.status).toBe(200);
expect(retrieveStripeSubscription).toHaveBeenCalledWith("sub_via_string");
});
it("extracts the subscription id from an object-shaped subscription_schedule.canceled event", async () => {
const retrieveStripeSubscription = vi.fn(async () => null);
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() =>
({
id: "evt_schedule_object",
type: "subscription_schedule.canceled",
data: { object: { id: "schedule_2", subscription: { id: "sub_via_object" } } },
} as unknown as Stripe.Event)) as never,
retrieveStripeSubscription: retrieveStripeSubscription as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
expect(res.status).toBe(200);
expect(retrieveStripeSubscription).toHaveBeenCalledWith("sub_via_object");
});
it("skips sync when subscription_schedule.canceled has no subscription reference", async () => {
const retrieveStripeSubscription = vi.fn(async () => null);
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() =>
({
id: "evt_schedule_none",
type: "subscription_schedule.canceled",
data: { object: { id: "schedule_3", subscription: null } },
} as unknown as Stripe.Event)) as never,
retrieveStripeSubscription: retrieveStripeSubscription as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
expect(res.status).toBe(200);
expect(retrieveStripeSubscription).not.toHaveBeenCalled();
});
it("skips sync when a subscription lifecycle event has no object id", async () => {
const retrieveStripeSubscription = vi.fn(async () => null);
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() =>
({
id: "evt_subscription_without_id",
type: "customer.subscription.updated",
data: { object: {} },
} as unknown as Stripe.Event)) as never,
retrieveStripeSubscription: retrieveStripeSubscription as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
expect(res.status).toBe(200);
expect(retrieveStripeSubscription).not.toHaveBeenCalled();
});
it("returns 200 and skips downstream work when retrieveStripeSubscription returns null", async () => {
const updateTenantSubscriptionProductFromStripe = vi.fn();
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() =>
({ id: "evt_missing_sub", type: "customer.subscription.deleted", data: { object: { id: "sub_missing" } } } as unknown as Stripe.Event)) as never,
retrieveStripeSubscription: (async () => null) as never,
updateTenantSubscriptionProductFromStripe: updateTenantSubscriptionProductFromStripe as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
expect(res.status).toBe(200);
expect(updateTenantSubscriptionProductFromStripe).not.toHaveBeenCalled();
});
it("returns 200 and skips downstream work when no tenant subscription product matches the stripe subscription", async () => {
const updateTenantSubscriptionProductFromStripe = vi.fn();
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() =>
({ id: "evt_no_tsp", type: "customer.subscription.deleted", data: { object: { id: "sub_known" } } } as unknown as Stripe.Event)) as never,
retrieveStripeSubscription: (async () => ({ id: "sub_known", cancel_at: null, canceled_at: null, ended_at: null, items: { data: [] } } as unknown as Stripe.Subscription)) as never,
findTenantSubscriptionProductByStripeSubscriptionId: (async () => null) as never,
updateTenantSubscriptionProductFromStripe: updateTenantSubscriptionProductFromStripe as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
expect(res.status).toBe(200);
expect(updateTenantSubscriptionProductFromStripe).not.toHaveBeenCalled();
});
it("derives endsAt from ended_at when canceled_at is set and the subscription has already ended", async () => {
const stripeSubscription = {
id: "sub_ended",
cancel_at: null,
canceled_at: 1_700_050_000,
ended_at: 1_700_060_000,
items: { data: [{ id: "si_test", current_period_start: 1_700_000_000, current_period_end: 1_702_592_000 }] },
} as unknown as Stripe.Subscription;
const tenantSubscriptionProduct = {
id: "tsp-2",
endsAt: null,
cancelledAt: null,
tenantSubscription: { tenant: { id: "tenant-end", name: "EndedCo" } },
subscriptionProduct: { title: "Pro" },
} as unknown as never;
const publishCalls: string[] = [];
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() =>
({ id: "evt_ended", type: "customer.subscription.deleted", data: { object: { id: "sub_ended" } } } as unknown as Stripe.Event)) as never,
retrieveStripeSubscription: (async () => stripeSubscription) as never,
findTenantSubscriptionProductByStripeSubscriptionId: (async () => tenantSubscriptionProduct as never) as never,
updateTenantSubscriptionProductFromStripe: (async (_id: string, data: Record<string, unknown>) => {
// endsAt should derive from ended_at, NOT from canceled_at.
expect((data.endsAt as Date).getTime()).toBe(1_700_060_000 * 1000);
expect((data.cancelledAt as Date).getTime()).toBe(1_700_050_000 * 1000);
return undefined;
}) as never,
publishOutboxEvent: (async (_tx: unknown, args: { type: string }) => {
publishCalls.push(args.type);
return { id: `outbox-${publishCalls.length}` };
}) as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
expect(res.status).toBe(200);
expect(publishCalls.sort()).toEqual(["billing.subscription.cancelled", "billing.subscription.ended"]);
});
it("uses 'now' for endsAt when canceled_at is set but ended_at is null", async () => {
const stripeSubscription = {
id: "sub_cancel_no_end",
cancel_at: null,
canceled_at: 1_700_050_000,
ended_at: null,
items: { data: [{ id: "si_test", current_period_start: 1_700_000_000, current_period_end: 1_702_592_000 }] },
} as unknown as Stripe.Subscription;
const tenantSubscriptionProduct = {
id: "tsp-3",
endsAt: null,
cancelledAt: null,
tenantSubscription: { tenant: { id: "tenant-now", name: "NowCo" } },
subscriptionProduct: { title: "Pro" },
} as unknown as never;
let observedEndsAtMs = 0;
const before = Date.now();
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() =>
({ id: "evt_cancel_now", type: "customer.subscription.updated", data: { object: { id: "sub_cancel_no_end" } } } as unknown as Stripe.Event)) as never,
retrieveStripeSubscription: (async () => stripeSubscription) as never,
findTenantSubscriptionProductByStripeSubscriptionId: (async () => tenantSubscriptionProduct as never) as never,
updateTenantSubscriptionProductFromStripe: (async (_id: string, data: Record<string, unknown>) => {
observedEndsAtMs = (data.endsAt as Date).getTime();
return undefined;
}) as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
const after = Date.now();
expect(res.status).toBe(200);
expect(observedEndsAtMs).toBeGreaterThanOrEqual(before);
expect(observedEndsAtMs).toBeLessThanOrEqual(after);
});
it("falls back to epoch period dates when the stripe subscription has no item data", async () => {
const stripeSubscription = {
id: "sub_empty_items",
cancel_at: null,
canceled_at: null,
ended_at: null,
items: { data: [] },
} as unknown as Stripe.Subscription;
const tenantSubscriptionProduct = {
id: "tsp-empty-items",
endsAt: null,
cancelledAt: null,
tenantSubscription: { tenant: { id: "tenant-empty-items", name: "EmptyItemsCo" } },
subscriptionProduct: { title: "Pro" },
} as unknown as never;
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() =>
({ id: "evt_empty_items", type: "customer.subscription.updated", data: { object: { id: "sub_empty_items" } } } as unknown as Stripe.Event)) as never,
retrieveStripeSubscription: (async () => stripeSubscription) as never,
findTenantSubscriptionProductByStripeSubscriptionId: (async () => tenantSubscriptionProduct as never) as never,
updateTenantSubscriptionProductFromStripe: (async (_id: string, data: Record<string, unknown>) => {
expect((data.currentPeriodStart as Date).getTime()).toBe(0);
expect((data.currentPeriodEnd as Date).getTime()).toBe(0);
return undefined;
}) as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
expect(res.status).toBe(200);
});
it("does not republish lifecycle events when endsAt/cancelledAt are unchanged from the previous record", async () => {
const stripeSubscription = {
id: "sub_noop",
cancel_at: 1_700_100_000,
canceled_at: null,
ended_at: null,
items: { data: [{ id: "si_test", current_period_start: 1_700_000_000, current_period_end: 1_702_592_000 }] },
} as unknown as Stripe.Subscription;
const tenantSubscriptionProduct = {
id: "tsp-4",
endsAt: new Date(1_700_100_000 * 1000),
cancelledAt: new Date(1_700_100_000 * 1000),
tenantSubscription: { tenant: { id: "tenant-noop", name: "NoopCo" } },
subscriptionProduct: { title: "Pro" },
} as unknown as never;
const publishCalls: string[] = [];
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() =>
({ id: "evt_noop", type: "customer.subscription.updated", data: { object: { id: "sub_noop" } } } as unknown as Stripe.Event)) as never,
retrieveStripeSubscription: (async () => stripeSubscription) as never,
findTenantSubscriptionProductByStripeSubscriptionId: (async () => tenantSubscriptionProduct as never) as never,
publishOutboxEvent: (async (_tx: unknown, args: { type: string }) => {
publishCalls.push(args.type);
return { id: `outbox-${publishCalls.length}` };
}) as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
expect(res.status).toBe(200);
expect(publishCalls).toEqual([]);
});
it("logs but does not surface publishSubscriptionInvalidation rejections", async () => {
const loggerWarn = vi.spyOn(apiLogger, "warn").mockImplementation(() => undefined);
const stripeSubscription = {
id: "sub_invalidate_fail",
cancel_at: null,
canceled_at: null,
ended_at: null,
items: { data: [{ id: "si_test", current_period_start: 1_700_000_000, current_period_end: 1_702_592_000 }] },
} as unknown as Stripe.Subscription;
const tenantSubscriptionProduct = {
id: "tsp-5",
endsAt: null,
cancelledAt: null,
tenantSubscription: { tenant: { id: "tenant-bad-pub", name: "PubCo" } },
subscriptionProduct: { title: "Pro" },
} as unknown as never;
getPublishMock().mockRejectedValueOnce(new Error("redis down"));
const app = buildApp(
buildDeps({
constructStripeWebhookEvent: (() =>
({ id: "evt_pub_fail", type: "customer.subscription.updated", data: { object: { id: "sub_invalidate_fail" } } } as unknown as Stripe.Event)) as never,
retrieveStripeSubscription: (async () => stripeSubscription) as never,
findTenantSubscriptionProductByStripeSubscriptionId: (async () => tenantSubscriptionProduct as never) as never,
}),
);
const res = await app.request("/v1/billing/stripe/webhooks", {
method: "POST",
headers: { "stripe-signature": "t=1,v1=abc" },
body: "{}",
});
expect(res.status).toBe(200);
await Promise.resolve();
expect(getPublishMock()).toHaveBeenCalledWith("tenant-bad-pub");
expect(loggerWarn).toHaveBeenCalledWith(
expect.objectContaining({ tenantId: "tenant-bad-pub" }),
"stripe-webhook: failed to publish subscription invalidation",
);
loggerWarn.mockRestore();
});
});
@@ -1,223 +0,0 @@
import type { StripeTenantSubscriptionProduct, StripeTenantSubscriptionProductClient } from "@toolctrl/db/subscriptions.server";
import type { OutboxPublisherTransaction, OutboxPublishArgs } from "@toolctrl/db/outbox";
import type { Context } from "hono";
import type Stripe from "stripe";
import type { ApiAppDependencies } from "../app.js";
import { getApiRuntimeConfig } from "../config.js";
import { apiLogger } from "../logger.js";
import { getApiMetrics } from "../metrics.js";
import { apiError, type ApiErrorEnv } from "../middleware/error-envelope.js";
import { publishSubscriptionInvalidation } from "../cache/subscription-cache-publisher.js";
function recordStripeWebhookOutcome(eventType: string, status: "received" | "invalid_signature" | "missing_signature" | "config_unavailable") {
try {
getApiMetrics().metrics.stripeWebhookEventsTotal.labels({ event_type: eventType, status }).inc();
} catch {
// Metric writes must never break webhook handling.
}
}
/**
* Transaction runner contract. Production wires this to
* `prisma.$transaction(fn)` so the subscription update + outbox publish
* land atomically (Phase 03 #42). The transaction client must satisfy
* both `StripeTenantSubscriptionProductClient` (for the subscription
* update) and `OutboxPublisherTransaction` (for outbox publishes).
*/
export type StripeWebhookTransactionClient = StripeTenantSubscriptionProductClient & OutboxPublisherTransaction;
export type StripeWebhookTransactionRunner = <T>(
fn: (tx: StripeWebhookTransactionClient) => Promise<T>,
) => Promise<T>;
type StripeBillingWebhookDependencies = Pick<
ApiAppDependencies,
| "constructStripeWebhookEvent"
| "retrieveStripeSubscription"
| "findTenantSubscriptionProductByStripeSubscriptionId"
| "updateTenantSubscriptionProductFromStripe"
> & {
/**
* Runs the subscription update + outbox publish in a single Prisma
* transaction (Phase 03 #42). Production wiring lives in
* `app-dependencies.ts`.
*/
runStripeWebhookTransaction: StripeWebhookTransactionRunner;
/**
* Outbox publisher bound against the transaction client. Defaults to
* `publishOutboxEvent` from `@toolctrl/db/outbox`; tests inject a
* recorder. Wrapped here as a dependency so we never reach for the
* top-level Prisma singleton inside the transaction.
*/
publishOutboxEvent: (tx: OutboxPublisherTransaction, args: OutboxPublishArgs) => Promise<unknown>;
};
export async function postStripeBillingWebhookRequest(c: Context<ApiErrorEnv>, dependencies: StripeBillingWebhookDependencies) {
const config = getApiRuntimeConfig();
if (!config.stripe.secretKey || !config.stripe.webhookSigningSecret) {
recordStripeWebhookOutcome("unknown", "config_unavailable");
return apiError(c, 503, "dependency_unavailable", "Stripe billing webhook configuration is unavailable.");
}
const signature = c.req.header("stripe-signature");
if (!signature) {
recordStripeWebhookOutcome("unknown", "missing_signature");
return apiError(c, 400, "invalid_request", "Missing Stripe signature.");
}
const payload = await c.req.text();
let event: Stripe.Event;
try {
event = dependencies.constructStripeWebhookEvent(payload, signature);
} catch {
recordStripeWebhookOutcome("unknown", "invalid_signature");
return apiError(c, 400, "invalid_signature", "Invalid Stripe webhook signature.");
}
if (
event.type === "subscription_schedule.canceled" ||
event.type === "customer.subscription.deleted" ||
event.type === "customer.subscription.updated"
) {
const stripeSubscriptionId = getStripeSubscriptionIdFromEvent(event);
if (stripeSubscriptionId) {
await syncStripeTenantSubscription(stripeSubscriptionId, event.id, dependencies);
}
}
recordStripeWebhookOutcome(event.type, "received");
return c.json({ received: true, event: event.type });
}
function getStripeSubscriptionIdFromEvent(event: Stripe.Event): string | null {
const object = event.data.object as { id?: string; subscription?: string | { id?: string } | null };
if (event.type === "subscription_schedule.canceled") {
if (typeof object.subscription === "string") return object.subscription;
return object.subscription?.id ?? null;
}
return object.id ?? null;
}
async function syncStripeTenantSubscription(
stripeSubscriptionId: string,
stripeEventId: string,
dependencies: StripeBillingWebhookDependencies,
) {
const stripeSubscription = await dependencies.retrieveStripeSubscription(stripeSubscriptionId);
if (!stripeSubscription) {
return;
}
const tenantSubscriptionProduct = await dependencies.findTenantSubscriptionProductByStripeSubscriptionId(stripeSubscription.id);
if (!tenantSubscriptionProduct) {
return;
}
const previousEndsAt = tenantSubscriptionProduct.endsAt?.getTime() ?? null;
const previousCancelledAt = tenantSubscriptionProduct.cancelledAt?.getTime() ?? null;
let endsAt: Date | null = null;
let cancelledAt: Date | null = null;
if (stripeSubscription.cancel_at) {
endsAt = new Date(stripeSubscription.cancel_at * 1000);
cancelledAt = new Date(stripeSubscription.cancel_at * 1000);
} else if (stripeSubscription.canceled_at) {
cancelledAt = new Date(stripeSubscription.canceled_at * 1000);
endsAt = stripeSubscription.ended_at ? new Date(stripeSubscription.ended_at * 1000) : new Date();
}
// Phase 03 #42 — wrap the DB update + outbox publishes in a single
// transaction. The legacy in-process `createLegacyEvent` write moved
// into a receiver worker (apps/worker/src/jobs/legacy-event-receiver.ts)
// that consumes the published events from the `outbox.notification`
// BullMQ queue. A crash between commit and dispatcher pickup is now
// safe: the events stay PENDING and the dispatcher claims them on
// the next tick.
await dependencies.runStripeWebhookTransaction(async (tx) => {
await dependencies.updateTenantSubscriptionProductFromStripe(
tenantSubscriptionProduct.id,
{
cancelledAt,
endsAt,
currentPeriodStart: new Date((stripeSubscription.items.data[0]?.current_period_start ?? 0) * 1000),
currentPeriodEnd: new Date((stripeSubscription.items.data[0]?.current_period_end ?? 0) * 1000),
},
tx,
);
await publishSubscriptionLifecycleEvents(
{
tenantSubscriptionProduct,
endsAt,
cancelledAt,
previousEndsAt,
previousCancelledAt,
stripeEventId,
},
tx,
dependencies,
);
});
// Cross-replica cache invalidation: publish so every web replica drops
// its in-process subscription cache for this tenant. Fire-and-forget;
// failures must not block webhook delivery (5xx → Stripe retries).
const tenantIdToInvalidate = tenantSubscriptionProduct.tenantSubscription.tenant.id;
publishSubscriptionInvalidation(tenantIdToInvalidate).catch((err: unknown) => {
apiLogger.warn({ err, tenantId: tenantIdToInvalidate }, "stripe-webhook: failed to publish subscription invalidation");
});
}
async function publishSubscriptionLifecycleEvents(
{
tenantSubscriptionProduct,
endsAt,
cancelledAt,
previousEndsAt,
previousCancelledAt,
stripeEventId,
}: {
tenantSubscriptionProduct: StripeTenantSubscriptionProduct;
endsAt: Date | null;
cancelledAt: Date | null;
previousEndsAt: number | null;
previousCancelledAt: number | null;
stripeEventId: string;
},
tx: StripeWebhookTransactionClient,
dependencies: Pick<StripeBillingWebhookDependencies, "publishOutboxEvent">,
) {
const tenant = tenantSubscriptionProduct.tenantSubscription.tenant;
const product = tenantSubscriptionProduct.subscriptionProduct;
if (endsAt && previousEndsAt !== endsAt.getTime()) {
await dependencies.publishOutboxEvent(tx, {
tenantId: tenant.id,
type: "billing.subscription.ended",
// Idempotent against duplicate Stripe deliveries: each Stripe event
// is identified by `evt_*`; combined with the lifecycle suffix this
// dedups re-deliveries of the same webhook event.
dispatchKey: `stripe:${stripeEventId}:subscription.ended`,
payload: {
name: "subscription.ended",
tenantId: tenant.id,
userId: null,
data: JSON.stringify({ tenant, product }),
description: `${tenant.name} subscription ended: ${product.title}`,
},
});
}
if (cancelledAt && previousCancelledAt !== cancelledAt.getTime()) {
await dependencies.publishOutboxEvent(tx, {
tenantId: tenant.id,
type: "billing.subscription.cancelled",
dispatchKey: `stripe:${stripeEventId}:subscription.cancelled`,
payload: {
name: "subscription.cancelled",
tenantId: tenant.id,
userId: null,
data: JSON.stringify({ tenant, product }),
description: `${tenant.name} subscription cancelled: ${product.title}`,
},
});
}
}
@@ -0,0 +1,112 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
// Mock the two-tier cache + shared-store seams so the test exercises the real
// publisher singleton/env-gating logic without a Redis connection.
const { createTwoTierCacheMock, invalidateMock, getSharedStoreMock } = vi.hoisted(() => {
const invalidateMock = vi.fn().mockResolvedValue(undefined);
return {
invalidateMock,
createTwoTierCacheMock: vi.fn(() => ({ invalidate: invalidateMock })),
getSharedStoreMock: vi.fn(() => ({ namespace: "subscription" })),
};
});
vi.mock("@hivegrid/shared-store", () => ({
createTwoTierCache: createTwoTierCacheMock,
}));
vi.mock("../shared-store.js", () => ({
getSharedStore: getSharedStoreMock,
}));
const { publishSubscriptionInvalidation, __resetSubscriptionCachePublisherForTests } = await import(
"./subscription-cache-publisher.js"
);
const ORIGINAL_FLAG = process.env.CACHE_INVALIDATION_ENABLED;
beforeEach(() => {
createTwoTierCacheMock.mockClear();
invalidateMock.mockClear();
getSharedStoreMock.mockClear();
__resetSubscriptionCachePublisherForTests();
delete process.env.CACHE_INVALIDATION_ENABLED;
});
afterEach(() => {
if (ORIGINAL_FLAG === undefined) {
delete process.env.CACHE_INVALIDATION_ENABLED;
} else {
process.env.CACHE_INVALIDATION_ENABLED = ORIGINAL_FLAG;
}
});
/** Read the `pubsubEnabled` flag the publisher passed to createTwoTierCache. */
function lastPubsubEnabled(): boolean {
// The mock's implementation takes no params, so vitest infers `mock.calls`
// as `[][]`. The real createTwoTierCache is invoked with an options object
// carrying `pubsubEnabled`, so cast to the actual call shape to read it back.
const lastCall = createTwoTierCacheMock.mock.calls.at(-1) as unknown as
| [{ pubsubEnabled: boolean }]
| undefined;
return (lastCall?.[0] as { pubsubEnabled: boolean }).pubsubEnabled;
}
describe("publishSubscriptionInvalidation", () => {
test("no-ops on an empty tenant id without constructing the publisher", async () => {
await publishSubscriptionInvalidation("");
expect(createTwoTierCacheMock).not.toHaveBeenCalled();
expect(invalidateMock).not.toHaveBeenCalled();
});
test("invalidates the subscription namespace for the given tenant", async () => {
await publishSubscriptionInvalidation("tenant_1");
expect(createTwoTierCacheMock).toHaveBeenCalledTimes(1);
expect(createTwoTierCacheMock).toHaveBeenCalledWith(
expect.objectContaining({ namespace: "subscription" }),
);
expect(invalidateMock).toHaveBeenCalledWith("tenant_1");
});
test("reuses a single publisher across calls and rebuilds after reset", async () => {
await publishSubscriptionInvalidation("tenant_1");
await publishSubscriptionInvalidation("tenant_2");
expect(createTwoTierCacheMock).toHaveBeenCalledTimes(1);
__resetSubscriptionCachePublisherForTests();
await publishSubscriptionInvalidation("tenant_3");
expect(createTwoTierCacheMock).toHaveBeenCalledTimes(2);
expect(invalidateMock).toHaveBeenNthCalledWith(3, "tenant_3");
});
test("defaults pub/sub to enabled when the flag is unset", async () => {
await publishSubscriptionInvalidation("tenant_1");
expect(lastPubsubEnabled()).toBe(true);
});
test.each(["false", "FALSE", "0"])(
"disables pub/sub when CACHE_INVALIDATION_ENABLED=%s",
async (value) => {
process.env.CACHE_INVALIDATION_ENABLED = value;
__resetSubscriptionCachePublisherForTests();
await publishSubscriptionInvalidation("tenant_1");
expect(lastPubsubEnabled()).toBe(false);
},
);
test.each(["true", "1", "yes"])(
"keeps pub/sub enabled for non-disabling value %s",
async (value) => {
process.env.CACHE_INVALIDATION_ENABLED = value;
__resetSubscriptionCachePublisherForTests();
await publishSubscriptionInvalidation("tenant_1");
expect(lastPubsubEnabled()).toBe(true);
},
);
});
@@ -1,4 +1,4 @@
import { createTwoTierCache, type TwoTierCache } from "@toolctrl/shared-store";
import { createTwoTierCache, type TwoTierCache } from "@hivegrid/shared-store";
import { getSharedStore } from "../shared-store.js";
import { apiLogger } from "../logger.js";
@@ -1,4 +1,4 @@
import { ApiConfigError, type ApiConfig } from "@toolctrl/config";
import { ApiConfigError, type ApiConfig } from "@hivegrid/config";
import { afterEach, describe, expect, test } from "vitest";
import { getApiRuntimeConfig, resetApiRuntimeConfigForTests, setApiRuntimeConfigForTests } from "./config.js";
@@ -137,7 +137,8 @@ describe("getApiRuntimeConfig", () => {
jwtSecret: "override-jwt-secret",
analytics: {},
mailjet: {},
stripe: {},
lago: { timeoutMs: 10000 },
mollie: { timeoutMs: 10000 },
apiKeys: {
allowLegacyPlaintextFallback: true,
},
@@ -1,4 +1,4 @@
import { loadRequiredApiConfig, type ApiConfig } from "@toolctrl/config";
import { loadRequiredApiConfig, type ApiConfig } from "@hivegrid/config";
let apiRuntimeConfigForTests: ApiConfig | undefined;
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, test } from "vitest";
import type { ApiConfig } from "@toolctrl/config";
import type { ApiConfig } from "@hivegrid/config";
import { resetApiRuntimeConfigForTests, setApiRuntimeConfigForTests } from "./config.js";
import { getAllowedCorsOrigin } from "./cors.js";
@@ -23,7 +23,8 @@ const TEST_API_CONFIG: ApiConfig = {
jwtSecret: "test-jwt-secret",
analytics: {},
mailjet: {},
stripe: {},
lago: { timeoutMs: 10000 },
mollie: { timeoutMs: 10000 },
apiKeys: {
allowLegacyPlaintextFallback: true,
},
@@ -10,6 +10,7 @@ type ProtectionClass =
| "service-or-tenant-api-key"
| "optional-api-key-validation"
| "webhook-signature"
| "provider-refetch-webhook"
| "public-analytics-token"
| "public-widget"
| "auth-credential-exchange";
@@ -30,6 +31,7 @@ const allowedProtectionClasses = new Set<ProtectionClass>([
"service-or-tenant-api-key",
"optional-api-key-validation",
"webhook-signature",
"provider-refetch-webhook",
"public-analytics-token",
"public-widget",
"auth-credential-exchange",
@@ -98,9 +100,15 @@ const expectedInventory: InventoryEntry[] = [
},
{
method: "POST",
path: "/v1/billing/stripe/webhooks",
path: "/v1/billing/mollie/webhooks",
protectionClass: "provider-refetch-webhook",
note: "Accepts only a Mollie payment id, then verifies and expands it by refetching the payment from Mollie server-side before any DB write.",
},
{
method: "POST",
path: "/v1/webhooks/incoming/:tenant/:slug",
protectionClass: "webhook-signature",
note: "Forwards a raw billing lifecycle webhook payload only with Stripe signing headers preserved.",
note: "Accepts third-party lead payloads only after the per-endpoint credential verifies (URL token, HMAC signature, or tenant API key) and rate limits pass.",
},
{
method: "POST",
@@ -108,36 +116,6 @@ const expectedInventory: InventoryEntry[] = [
protectionClass: "service-token",
note: "Queues export-artifact retention cleanup only after service-token authentication.",
},
{
method: "POST",
path: "/v1/entities/:entity/rows",
protectionClass: "service-or-tenant-api-key",
note: "Creates entity rows only after x-api-key or bearer service-token authentication.",
},
{
method: "PATCH",
path: "/v1/entities/:entity/rows/:rowId",
protectionClass: "service-or-tenant-api-key",
note: "Updates entity rows only after x-api-key or bearer service-token authentication.",
},
{
method: "DELETE",
path: "/v1/entities/:entity/rows/:rowId",
protectionClass: "service-or-tenant-api-key",
note: "Deletes entity rows only after x-api-key or bearer service-token authentication.",
},
{
method: "POST",
path: "/v1/relationships",
protectionClass: "service-or-tenant-api-key",
note: "Creates row relationships only after x-api-key or bearer service-token authentication.",
},
{
method: "DELETE",
path: "/v1/relationships/:id",
protectionClass: "service-or-tenant-api-key",
note: "Deletes row relationships only after x-api-key or bearer service-token authentication.",
},
{
method: "POST",
path: "/v1/workspaces/:tenantId/context/revalidate",
@@ -0,0 +1,127 @@
import { describe, expect, test } from "vitest";
import { parseMailjetSequenceWebhookPayload } from "./provider-webhook-route.js";
const NOW = new Date("2026-06-01T12:00:00.000Z");
describe("parseMailjetSequenceWebhookPayload", () => {
test("rejects non-JSON bodies", () => {
const result = parseMailjetSequenceWebhookPayload("<<not-json>>");
expect(result).toEqual({ ok: false, error: expect.stringContaining("valid JSON") });
});
test("rejects JSON that is not an object", () => {
const result = parseMailjetSequenceWebhookPayload("123");
expect(result).toEqual({ ok: false, error: expect.stringContaining("must be an object") });
});
test("treats an unknown/empty event as an ignorable webhook", () => {
const result = parseMailjetSequenceWebhookPayload(JSON.stringify({ foo: "bar" }));
expect(result).toEqual({ ok: true, action: "ignore", eventType: "unknown" });
});
test("ignores non-bounce delivery events", () => {
const result = parseMailjetSequenceWebhookPayload(JSON.stringify({ event: "sent", MessageID: "m1" }));
expect(result).toEqual({ ok: true, action: "ignore", eventType: "sent" });
});
test("treats blocked and spam as bounces and normalizes casing/spacing", () => {
const blocked = parseMailjetSequenceWebhookPayload(
JSON.stringify({ event: " Blocked ", MessageID: "m-blocked", time: 1700000000 }),
);
const spam = parseMailjetSequenceWebhookPayload(
JSON.stringify({ event: "SPAM", MessageID: "m-spam", time: 1700000000 }),
);
expect(blocked).toMatchObject({ ok: true, action: "bounce", eventType: "blocked", providerMessageId: "m-blocked" });
expect(spam).toMatchObject({ ok: true, action: "bounce", eventType: "spam", providerMessageId: "m-spam" });
});
test("folds the first event of a batched array payload", () => {
const result = parseMailjetSequenceWebhookPayload(
JSON.stringify([
{ event: "bounce", MessageID: "first", time: 1700000000, error: "user unknown" },
{ event: "bounce", MessageID: "second" },
]),
);
expect(result).toMatchObject({
ok: true,
action: "bounce",
providerMessageId: "first",
errorMessage: "bounce: user unknown",
});
});
test("fails closed when a bounce is missing a provider message id", () => {
const result = parseMailjetSequenceWebhookPayload(JSON.stringify({ event: "bounce" }));
expect(result).toEqual({ ok: false, error: expect.stringContaining("provider message id") });
});
test("reads a numeric MessageID and falls back to `now` when no timestamp is present", () => {
const result = parseMailjetSequenceWebhookPayload(JSON.stringify({ event: "bounce", MessageID: 98765 }), NOW);
expect(result).toMatchObject({
ok: true,
action: "bounce",
providerMessageId: "98765",
bouncedAt: NOW,
// No reason field => errorMessage is just the event type.
errorMessage: "bounce",
});
});
test("interprets a unix-seconds timestamp", () => {
const result = parseMailjetSequenceWebhookPayload(
JSON.stringify({ event: "bounce", MessageID: "m", time: 1700000000 }),
);
expect(result).toMatchObject({ ok: true, action: "bounce" });
if (result.ok && result.action === "bounce") {
expect(result.bouncedAt.getTime()).toBe(1700000000 * 1000);
}
});
test("interprets a unix-millis timestamp without re-scaling", () => {
const result = parseMailjetSequenceWebhookPayload(
JSON.stringify({ event: "bounce", MessageID: "m", time: 1700000000000 }),
);
if (result.ok && result.action === "bounce") {
expect(result.bouncedAt.getTime()).toBe(1700000000000);
} else {
throw new Error("expected a bounce result");
}
});
test("parses an ISO-8601 timestamp string", () => {
const result = parseMailjetSequenceWebhookPayload(
JSON.stringify({ event: "bounce", MessageID: "m", time: "2026-01-02T03:04:05.000Z" }),
);
if (result.ok && result.action === "bounce") {
expect(result.bouncedAt.toISOString()).toBe("2026-01-02T03:04:05.000Z");
} else {
throw new Error("expected a bounce result");
}
});
test("falls back to `now` for an unparseable timestamp", () => {
const result = parseMailjetSequenceWebhookPayload(
JSON.stringify({ event: "bounce", MessageID: "m", time: "definitely-not-a-date" }),
NOW,
);
expect(result).toMatchObject({ ok: true, action: "bounce", bouncedAt: NOW });
});
test("reads event id and reason from a nested data envelope", () => {
const result = parseMailjetSequenceWebhookPayload(
JSON.stringify({ data: { event: "bounce", MessageID: "nested-id", error: "mailbox full" } }),
NOW,
);
expect(result).toMatchObject({
ok: true,
action: "bounce",
providerMessageId: "nested-id",
errorMessage: "bounce: mailbox full",
});
});
});
@@ -2,10 +2,11 @@ import type { Context } from "hono";
import type {
EmailSequenceProviderWebhookResult,
MarkEmailSequenceDeliveryBouncedInput,
} from "@toolctrl/db/email-sequences.server";
} from "@hivegrid/db/email-sequences.server";
import type { ApiEnv } from "../api-types.js";
import { apiError } from "../middleware/error-envelope.js";
import { verifyMailjetWebhookAuth } from "../webhooks/mailjet-webhook-auth.js";
import { parseMailjetSuppressionSignal } from "../webhooks/mailjet-suppression.js";
// Mailjet event-webhook `event` values that represent a non-delivery. Both hard
// and soft bounces arrive as `event: "bounce"` (distinguished by `hard_bounce`);
@@ -15,6 +16,10 @@ const MAILJET_BOUNCE_EVENT_TYPES = new Set(["bounce", "blocked", "spam"]);
export type EmailSequenceProviderWebhookDependencies = {
webhookSecret: string | null | undefined;
markEmailSequenceDeliveryBounced(input: MarkEmailSequenceDeliveryBouncedInput): Promise<EmailSequenceProviderWebhookResult>;
// AK-P14a: optional per-tenant suppression-list write. When wired, a bounce /
// complaint additionally suppresses the recipient (best-effort, never fails the
// webhook). Absent in tests that only assert the sequence reconciliation.
recordSuppression?(input: { tenantId: string; emailAddress: string; reason: "bounce" | "complaint"; detail: string | null }): Promise<unknown>;
};
type ParsedMailjetSequenceWebhook =
@@ -53,6 +58,19 @@ export async function postMailjetEmailSequenceWebhookRequest(
}
const rawBody = await c.req.raw.text();
// AK-P14a: best-effort per-tenant suppression write, independent of the
// sequence reconciliation below (a bounced marketing send has no sequence
// delivery but must still suppress). Never throws into the webhook response.
if (deps.recordSuppression) {
const signal = parseMailjetSuppressionSignal(rawBody);
if (signal.action === "suppress") {
await deps
.recordSuppression({ tenantId: signal.tenantId, emailAddress: signal.emailAddress, reason: signal.suppressionReason, detail: signal.detail })
.catch(() => undefined);
}
}
const payloadResult = parseMailjetSequenceWebhookPayload(rawBody);
if (!payloadResult.ok) {
return apiError(c, 400, "invalid_request", payloadResult.error);
@@ -1,227 +0,0 @@
import { afterEach, describe, expect, test, vi } from "vitest";
import type { ApiConfig } from "@toolctrl/config";
const emitPluginHookFireAndForget = vi.fn().mockResolvedValue(undefined);
vi.mock("./plugin-hook-publisher.js", () => ({
emitPluginHookFireAndForget,
}));
const { app, configureApiAppDependenciesForTests } = await import("./app.js");
const { resetApiRuntimeConfigForTests, setApiRuntimeConfigForTests } = await import("./config.js");
const { PLUGIN_HOOK_ENTITY_CREATED, PLUGIN_HOOK_ENTITY_DELETED, PLUGIN_HOOK_ENTITY_UPDATED } = await import("@toolctrl/plugin-runtime");
const testApp: Pick<typeof app, "request"> = {
request: ((input, init, ...rest) => app.request(input, addTestContentLength(init), ...rest)) as typeof app.request,
};
const TEST_API_CONFIG: ApiConfig = {
appName: "Test API",
nodeEnv: "test",
revision: "unknown",
listen: { port: 3001 },
routing: {
appBaseDomain: "localhost:3000",
webAppHost: "app.localhost:3000",
adminAppHost: "admin.localhost:3000",
apiHost: "api.localhost:3000",
protocol: "http",
},
origins: {},
apiAccessToken: "service-secret",
jwtSecret: "test-jwt-secret",
analytics: {},
mailjet: {},
stripe: {},
storage: {},
apiKeys: { allowLegacyPlaintextFallback: true },
};
let resetDependencies: (() => void) | undefined;
afterEach(() => {
resetDependencies?.();
resetDependencies = undefined;
resetApiRuntimeConfigForTests();
emitPluginHookFireAndForget.mockClear();
});
describe("API entity row plugin hooks", () => {
test("emits minimal entity CRUD hooks after successful mutations without replay duplicates", async () => {
setApiRuntimeConfigForTests(TEST_API_CONFIG);
const entity = createLegacyEntityFixture();
const createLegacyEntityRow = vi.fn().mockResolvedValue(createLegacyRowFixture("row_created"));
const updateLegacyEntityRow = vi.fn().mockResolvedValue(createLegacyRowFixture("row_updated"));
const deleteLegacyEntityRow = vi.fn().mockResolvedValue("row_deleted");
resetDependencies = configureApiAppDependenciesForTests({
findLegacyEntityByName: vi.fn().mockResolvedValue(entity),
createLegacyEntityRow,
updateLegacyEntityRow,
deleteLegacyEntityRow,
});
const createResponse = await testApp.request("/v1/entities/contact/rows?tenantId=tenant_1", {
method: "POST",
headers: {
authorization: "Bearer service-secret",
"content-type": "application/json",
"idempotency-key": "hook-create-key",
},
body: JSON.stringify({ firstName: "Ada", secretNote: "do-not-emit" }),
});
const replayCreate = await testApp.request("/v1/entities/contact/rows?tenantId=tenant_1", {
method: "POST",
headers: {
authorization: "Bearer service-secret",
"content-type": "application/json",
"idempotency-key": "hook-create-key",
},
body: JSON.stringify({ firstName: "Ada", secretNote: "do-not-emit" }),
});
const updateResponse = await testApp.request("/v1/entities/contact/rows/row_updated?tenantId=tenant_1", {
method: "PATCH",
headers: {
authorization: "Bearer service-secret",
"content-type": "application/json",
"idempotency-key": "hook-update-key",
},
body: JSON.stringify({ firstName: "Grace", privateMemo: "do-not-emit" }),
});
const replayUpdate = await testApp.request("/v1/entities/contact/rows/row_updated?tenantId=tenant_1", {
method: "PATCH",
headers: {
authorization: "Bearer service-secret",
"content-type": "application/json",
"idempotency-key": "hook-update-key",
},
body: JSON.stringify({ firstName: "Grace", privateMemo: "do-not-emit" }),
});
const deleteResponse = await testApp.request("/v1/entities/contact/rows/row_deleted?tenantId=tenant_1", {
method: "DELETE",
headers: {
authorization: "Bearer service-secret",
"idempotency-key": "hook-delete-key",
},
});
const replayDelete = await testApp.request("/v1/entities/contact/rows/row_deleted?tenantId=tenant_1", {
method: "DELETE",
headers: {
authorization: "Bearer service-secret",
"idempotency-key": "hook-delete-key",
},
});
expect(createResponse.status).toBe(201);
expect(replayCreate.status).toBe(201);
expect(updateResponse.status).toBe(200);
expect(replayUpdate.status).toBe(200);
expect(deleteResponse.status).toBe(200);
expect(replayDelete.status).toBe(200);
expect(createLegacyEntityRow).toHaveBeenCalledTimes(1);
expect(updateLegacyEntityRow).toHaveBeenCalledTimes(1);
expect(deleteLegacyEntityRow).toHaveBeenCalledTimes(1);
expect(emitPluginHookFireAndForget).toHaveBeenCalledTimes(3);
expect(emitPluginHookFireAndForget).toHaveBeenNthCalledWith(
1,
PLUGIN_HOOK_ENTITY_CREATED,
expect.objectContaining({
entityType: "contact",
entityId: "row_created",
tenantId: "tenant_1",
userId: null,
}),
{ tenantId: "tenant_1", dispatchKey: "entity:contact:row_created:created" },
);
expect(emitPluginHookFireAndForget).toHaveBeenNthCalledWith(
2,
PLUGIN_HOOK_ENTITY_UPDATED,
expect.objectContaining({
entityType: "contact",
entityId: "row_updated",
tenantId: "tenant_1",
userId: null,
changedFields: ["firstName", "privateMemo"],
}),
{ tenantId: "tenant_1" },
);
expect(emitPluginHookFireAndForget).toHaveBeenNthCalledWith(
3,
PLUGIN_HOOK_ENTITY_DELETED,
expect.objectContaining({
entityType: "contact",
entityId: "row_deleted",
tenantId: "tenant_1",
userId: null,
}),
{ tenantId: "tenant_1", dispatchKey: "entity:contact:row_deleted:deleted" },
);
for (const [, payload] of emitPluginHookFireAndForget.mock.calls) {
expect(payload).not.toHaveProperty("firstName");
expect(payload).not.toHaveProperty("secretNote");
expect(payload).not.toHaveProperty("privateMemo");
expect(payload).toHaveProperty("occurredAt", expect.any(String));
}
});
});
function addTestContentLength<T extends RequestInit | undefined>(init: T): T {
if (!init?.body) {
return init;
}
const headers = new Headers(init.headers);
if (headers.has("content-length")) {
return init;
}
const length = getTestBodyLength(init.body);
if (length === null) {
return init;
}
headers.set("content-length", String(length));
return { ...init, headers } as T;
}
function getTestBodyLength(body: BodyInit): number | null {
if (typeof body === "string") {
return Buffer.byteLength(body);
}
if (body instanceof URLSearchParams) {
return Buffer.byteLength(body.toString());
}
if (body instanceof Blob) {
return body.size;
}
return null;
}
function createLegacyEntityFixture() {
return {
id: "entity_1",
name: "contact",
title: "Contact",
properties: [],
views: [],
tags: [],
parentEntities: [],
childEntities: [],
templates: [],
};
}
function createLegacyRowFixture(id: string) {
return {
id,
entityId: "entity_1",
tenantId: "tenant_1",
createdAt: "2026-01-01T00:00:00.000Z",
updatedAt: "2026-01-01T00:00:00.000Z",
values: [],
parentRows: [],
childRows: [],
};
}
@@ -1,4 +1,4 @@
import { createSharedStore } from "@toolctrl/shared-store";
import { createSharedStore } from "@hivegrid/shared-store";
import { beforeEach, describe, expect, it } from "vitest";
import { readExportProgressFromSharedStore } from "./export-progress.js";
@@ -1,6 +1,6 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { queueExportArtifactRetention } from "./exportRetentionQueue.js";
import { queueNames } from "@toolctrl/queue";
import { queueNames } from "@hivegrid/queue";
const globalMockStore = globalThis as typeof globalThis & {
__exportRetentionQueueTestMocks__?: {
@@ -14,7 +14,7 @@ globalMockStore.__exportRetentionQueueTestMocks__ ??= {
const mocks = globalMockStore.__exportRetentionQueueTestMocks__;
vi.mock("@toolctrl/queue/runtime", () => ({
vi.mock("@hivegrid/queue/runtime", () => ({
createQueue: mocks.createQueue,
}));
@@ -5,7 +5,7 @@ import {
resolveRedisConnectionOptions,
type RedisConnectionEnv,
type TypedQueue,
} from "@toolctrl/queue";
} from "@hivegrid/queue";
type MaintenanceQueue = TypedQueue<typeof queueNames.maintenance>;
type ExportRetentionQueueEnv = RedisConnectionEnv & {
@@ -97,6 +97,6 @@ async function createInternalQueue(env?: ExportRetentionQueueEnv): Promise<Maint
return undefined;
}
const { createQueue } = await import("@toolctrl/queue/runtime");
const { createQueue } = await import("@hivegrid/queue/runtime");
return createQueue(queueNames.maintenance, { connection });
}
@@ -1,5 +1,5 @@
import { describe, expect, it } from "vitest";
import { MemoryAdapter, createSharedStore } from "@toolctrl/shared-store";
import { MemoryAdapter, createSharedStore } from "@hivegrid/shared-store";
import { createSharedStoreIdempotencyStorageClient } from "./shared-store-client.js";
import { createIdempotencyStore } from "./store.js";
@@ -28,7 +28,7 @@
* (`deleteMany({ expiresAt: { lte } })`) keep working against the
* MemoryAdapter, which honors TTL lazily on read.
*/
import type { SharedStore } from "@toolctrl/shared-store";
import type { SharedStore } from "@hivegrid/shared-store";
import type { IdempotencyStorageClient } from "./store.js";
type JsonValue = null | boolean | number | string | JsonValue[] | { [key: string]: JsonValue };
@@ -1,5 +1,5 @@
import { createHash } from "node:crypto";
import { CatalogError, foundationErrors, withIdempotency, type IdempotencyClient } from "@toolctrl/foundation";
import { CatalogError, foundationErrors, withIdempotency, type IdempotencyClient } from "@hivegrid/foundation";
export type IdempotencyKey = string;
export type RequestFingerprint = string;
@@ -1,291 +0,0 @@
import { describe, expect, test, vi } from "vitest";
import { app } from "../app.js";
import {
TEST_API_CONFIG,
configureApiIsolationDependenciesForTests,
createLegacyEntityFixture,
createLegacyRowFixture,
createStoredApiKeyFixture,
installApiIsolationTestHooks,
} from "./fixtures/api-key.js";
installApiIsolationTestHooks();
const STORED_API_KEY_SECRET = "stored-row-key-secret";
const INVALID_API_KEY_SECRET = "invalid-row-key-secret";
const REQUEST_ID = "req_entity_rows_scope";
function createScopedEntityApiKey(patch: Parameters<typeof createStoredApiKeyFixture>[0] = {}) {
return createStoredApiKeyFixture({
entities: [{ entityId: "entity_1", read: true, create: true, update: true, delete: true }],
...patch,
});
}
function createEntityRowDependencies(apiKey = createScopedEntityApiKey()) {
const entity = createLegacyEntityFixture();
const listRow = createLegacyRowFixture("row_list_1");
const itemRow = createLegacyRowFixture("row_item_1");
const createdRow = createLegacyRowFixture("row_created", { createdByApiKeyId: apiKey.id });
const updatedRow = createLegacyRowFixture("row_item_1", { updatedAt: new Date("2026-01-02T00:00:00.000Z") });
const dependencies = {
findLegacyApiKeyByKey: vi.fn(async (key: string) => (key === STORED_API_KEY_SECRET ? apiKey : null)),
findLegacyEntityByName: vi.fn(async () => entity),
getAllLegacyEntityRows: vi.fn(async () => ({ page: 1, pageSize: 25, totalItems: 1, totalPages: 1, items: [listRow] })),
getLegacyEntityRow: vi.fn(async () => itemRow),
createLegacyEntityRow: vi.fn(async () => createdRow),
updateLegacyEntityRow: vi.fn(async () => updatedRow),
deleteLegacyEntityRow: vi.fn(async () => "row_item_1"),
};
configureApiIsolationDependenciesForTests(dependencies);
return { apiKey, entity, listRow, itemRow, createdRow, updatedRow, dependencies };
}
function apiKeyHeaders(secret = STORED_API_KEY_SECRET, requestId = REQUEST_ID) {
return { "x-api-key": secret, "x-request-id": requestId, "idempotency-key": `${requestId}-idempotency` };
}
function bearerHeaders(secret = STORED_API_KEY_SECRET, requestId = REQUEST_ID) {
return { authorization: `Bearer ${secret}`, "x-request-id": requestId, "idempotency-key": `${requestId}-idempotency` };
}
function jsonHeaders(headers: Record<string, string>) {
return { ...headers, "content-type": "application/json" };
}
function jsonRequest(headers: Record<string, string>, body: unknown) {
const serialized = JSON.stringify(body);
return {
body: serialized,
headers: { ...jsonHeaders(headers), "content-length": String(Buffer.byteLength(serialized)) },
};
}
async function expectRedactedError(response: Response, expected: { status: number; code: string; requestId: string }) {
expect(response.status).toBe(expected.status);
expect(response.headers.get("x-request-id")).toBe(expected.requestId);
const text = await response.text();
expect(text).toContain(expected.requestId);
expect(text).not.toContain(STORED_API_KEY_SECRET);
expect(text).not.toContain(INVALID_API_KEY_SECRET);
expect(text).not.toContain(TEST_API_CONFIG.apiAccessToken);
expect(text).not.toContain("scope-secret");
expect(JSON.parse(text)).toEqual({
error: expect.objectContaining({
code: expected.code,
requestId: expected.requestId,
}),
});
}
describe("stored API-key entity row isolation", () => {
test("allows header API key read on GET /v1/entities/:entity/rows for tenant_1 entity_1", async () => {
const { dependencies, listRow } = createEntityRowDependencies();
const response = await app.request("/v1/entities/contact/rows?tenantId=tenant_1", { headers: apiKeyHeaders() });
expect(response.status).toBe(200);
await expect(response.json()).resolves.toMatchObject({
success: true,
results: [expect.objectContaining({ id: listRow.id, entityId: "entity_1", tenantId: "tenant_1" })],
data: [expect.objectContaining({ id: listRow.id, entityId: "entity_1", tenantId: "tenant_1" })],
});
expect(dependencies.findLegacyApiKeyByKey).toHaveBeenCalledWith(STORED_API_KEY_SECRET, undefined, "scope-secret", { allowPlaintextFallback: true });
expect(dependencies.findLegacyEntityByName).toHaveBeenCalledWith({ tenantId: "tenant_1", name: "contact", active: true });
expect(dependencies.getAllLegacyEntityRows).toHaveBeenCalledWith({ entityId: "entity_1", tenantId: "tenant_1", page: 1, pageSize: 100 });
});
test("allows header API key read on GET /v1/entities/:entity/rows/:rowId for tenant_1 entity_1", async () => {
const { dependencies, itemRow } = createEntityRowDependencies();
const response = await app.request("/v1/entities/contact/rows/row_item_1?tenantId=tenant_1", { headers: apiKeyHeaders() });
expect(response.status).toBe(200);
await expect(response.json()).resolves.toMatchObject({ id: itemRow.id, entityId: "entity_1", tenantId: "tenant_1" });
expect(dependencies.getLegacyEntityRow).toHaveBeenCalledWith({ entityId: "entity_1", tenantId: "tenant_1", rowId: "row_item_1" });
});
test("allows header API key create on POST /v1/entities/:entity/rows and stores createdByApiKeyId", async () => {
const { apiKey, dependencies } = createEntityRowDependencies();
const response = await app.request("/v1/entities/contact/rows?tenantId=tenant_1", {
method: "POST",
...jsonRequest(apiKeyHeaders(), { firstName: "Ada" }),
});
expect(response.status).toBe(201);
await expect(response.json()).resolves.toMatchObject({ id: "row_created", createdByApiKeyId: apiKey.id });
expect(dependencies.findLegacyEntityByName).toHaveBeenCalledWith({ tenantId: "tenant_1", name: "contact", active: true });
expect(dependencies.createLegacyEntityRow).toHaveBeenCalledWith({
entity: expect.objectContaining({ id: "entity_1", name: "contact" }),
tenantId: "tenant_1",
createdByApiKeyId: apiKey.id,
data: { firstName: "Ada" },
});
});
test("allows header API key update on PATCH /v1/entities/:entity/rows/:rowId for tenant_1 entity_1", async () => {
const { dependencies } = createEntityRowDependencies();
const response = await app.request("/v1/entities/contact/rows/row_item_1?tenantId=tenant_1", {
method: "PATCH",
...jsonRequest(apiKeyHeaders(), { firstName: "Grace" }),
});
expect(response.status).toBe(200);
await expect(response.json()).resolves.toMatchObject({ id: "row_item_1" });
expect(dependencies.findLegacyEntityByName).toHaveBeenCalledWith({ tenantId: "tenant_1", name: "contact", active: true });
expect(dependencies.updateLegacyEntityRow).toHaveBeenCalledWith({
entity: expect.objectContaining({ id: "entity_1", name: "contact" }),
tenantId: "tenant_1",
rowId: "row_item_1",
data: { firstName: "Grace" },
});
});
test("allows header API key delete on DELETE /v1/entities/:entity/rows/:rowId for tenant_1 entity_1", async () => {
const { dependencies } = createEntityRowDependencies();
const response = await app.request("/v1/entities/contact/rows/row_item_1?tenantId=tenant_1", {
method: "DELETE",
headers: apiKeyHeaders(),
});
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual({ success: true, id: "row_item_1" });
expect(dependencies.findLegacyEntityByName).toHaveBeenCalledWith({ tenantId: "tenant_1", name: "contact", active: true });
expect(dependencies.deleteLegacyEntityRow).toHaveBeenCalledWith({ entityId: "entity_1", tenantId: "tenant_1", rowId: "row_item_1" });
});
test("denies read on GET /v1/entities/:entity/rows when tenantId=tenant_2 tampers tenant", async () => {
const { dependencies } = createEntityRowDependencies();
const response = await app.request("/v1/entities/contact/rows?tenantId=tenant_2", { headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_rows_wrong_tenant") });
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_rows_wrong_tenant" });
expect(dependencies.findLegacyEntityByName).not.toHaveBeenCalled();
expect(dependencies.getAllLegacyEntityRows).not.toHaveBeenCalled();
expect(dependencies.createLegacyEntityRow).not.toHaveBeenCalled();
expect(dependencies.updateLegacyEntityRow).not.toHaveBeenCalled();
expect(dependencies.deleteLegacyEntityRow).not.toHaveBeenCalled();
});
test("denies create on POST /v1/entities/:entity/rows when API key lacks create scope", async () => {
const apiKey = createScopedEntityApiKey({ entities: [{ entityId: "entity_1", read: true, create: false, update: true, delete: true }] });
const { dependencies } = createEntityRowDependencies(apiKey);
const response = await app.request("/v1/entities/contact/rows?tenantId=tenant_1", {
method: "POST",
...jsonRequest(apiKeyHeaders(STORED_API_KEY_SECRET, "req_rows_missing_create"), { firstName: "Ada" }),
});
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_rows_missing_create" });
expect(dependencies.createLegacyEntityRow).not.toHaveBeenCalled();
expect(dependencies.updateLegacyEntityRow).not.toHaveBeenCalled();
expect(dependencies.deleteLegacyEntityRow).not.toHaveBeenCalled();
});
test("returns the same forbidden response for missing entity names with stored API keys", async () => {
const { dependencies } = createEntityRowDependencies(createScopedEntityApiKey({ entities: [] }));
dependencies.findLegacyEntityByName.mockRejectedValueOnce(new Error("Entity with name missingContact not found"));
const response = await app.request("/v1/entities/missingContact/rows?tenantId=tenant_1", { headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_rows_missing_entity") });
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_rows_missing_entity" });
expect(dependencies.getAllLegacyEntityRows).not.toHaveBeenCalled();
expect(dependencies.createLegacyEntityRow).not.toHaveBeenCalled();
expect(dependencies.updateLegacyEntityRow).not.toHaveBeenCalled();
expect(dependencies.deleteLegacyEntityRow).not.toHaveBeenCalled();
});
test("denies update on PATCH /v1/entities/:entity/rows/:rowId when API key lacks update scope", async () => {
const apiKey = createScopedEntityApiKey({ entities: [{ entityId: "entity_1", read: true, create: true, update: false, delete: true }] });
const { dependencies } = createEntityRowDependencies(apiKey);
const response = await app.request("/v1/entities/contact/rows/row_item_1?tenantId=tenant_1", {
method: "PATCH",
...jsonRequest(apiKeyHeaders(STORED_API_KEY_SECRET, "req_rows_missing_update"), { firstName: "Grace" }),
});
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_rows_missing_update" });
expect(dependencies.updateLegacyEntityRow).not.toHaveBeenCalled();
expect(dependencies.deleteLegacyEntityRow).not.toHaveBeenCalled();
});
test("denies delete on DELETE /v1/entities/:entity/rows/:rowId when API key lacks delete scope", async () => {
const apiKey = createScopedEntityApiKey({ entities: [{ entityId: "entity_1", read: true, create: true, update: true, delete: false }] });
const { dependencies } = createEntityRowDependencies(apiKey);
const response = await app.request("/v1/entities/contact/rows/row_item_1?tenantId=tenant_1", {
method: "DELETE",
headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_rows_missing_delete"),
});
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_rows_missing_delete" });
expect(dependencies.deleteLegacyEntityRow).not.toHaveBeenCalled();
});
test("denies read on GET /v1/entities/:entity/rows for inactive API key", async () => {
const { dependencies } = createEntityRowDependencies(createScopedEntityApiKey({ active: false }));
const response = await app.request("/v1/entities/contact/rows?tenantId=tenant_1", { headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_rows_inactive") });
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_rows_inactive" });
expect(dependencies.getAllLegacyEntityRows).not.toHaveBeenCalled();
});
test("denies read on GET /v1/entities/:entity/rows for expired API key", async () => {
const { dependencies } = createEntityRowDependencies(createScopedEntityApiKey({ expires: new Date("2020-01-01T00:00:00.000Z") }));
const response = await app.request("/v1/entities/contact/rows?tenantId=tenant_1", { headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_rows_expired") });
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_rows_expired" });
expect(dependencies.getAllLegacyEntityRows).not.toHaveBeenCalled();
});
test("denies read on GET /v1/entities/:entity/rows for deactivated tenant API key", async () => {
const apiKey = createScopedEntityApiKey({ tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: "billing_failed" } });
const { dependencies } = createEntityRowDependencies(apiKey);
const response = await app.request("/v1/entities/contact/rows?tenantId=tenant_1", { headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_rows_deactivated") });
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_rows_deactivated" });
expect(dependencies.getAllLegacyEntityRows).not.toHaveBeenCalled();
});
test("denies read on GET /v1/entities/:entity/rows with invalid x-api-key without service-token fallback", async () => {
const { dependencies } = createEntityRowDependencies();
const response = await app.request("/v1/entities/contact/rows?tenantId=tenant_1", { headers: apiKeyHeaders(INVALID_API_KEY_SECRET, "req_rows_invalid_key") });
await expectRedactedError(response, { status: 401, code: "unauthorized", requestId: "req_rows_invalid_key" });
expect(dependencies.findLegacyApiKeyByKey).toHaveBeenCalledWith(INVALID_API_KEY_SECRET, undefined, "scope-secret", { allowPlaintextFallback: true });
expect(dependencies.findLegacyEntityByName).not.toHaveBeenCalled();
expect(dependencies.getAllLegacyEntityRows).not.toHaveBeenCalled();
expect(dependencies.createLegacyEntityRow).not.toHaveBeenCalled();
expect(dependencies.updateLegacyEntityRow).not.toHaveBeenCalled();
expect(dependencies.deleteLegacyEntityRow).not.toHaveBeenCalled();
});
test("denies read on GET /v1/entities/:entity/rows/:rowId with invalid bearer token without stored-key fallback", async () => {
const { dependencies } = createEntityRowDependencies();
const response = await app.request("/v1/entities/contact/rows/row_item_1?tenantId=tenant_1", {
headers: bearerHeaders(INVALID_API_KEY_SECRET, "req_rows_invalid_bearer"),
});
await expectRedactedError(response, { status: 401, code: "unauthorized", requestId: "req_rows_invalid_bearer" });
expect(dependencies.findLegacyApiKeyByKey).not.toHaveBeenCalled();
expect(dependencies.findLegacyEntityByName).not.toHaveBeenCalled();
expect(dependencies.getAllLegacyEntityRows).not.toHaveBeenCalled();
expect(dependencies.createLegacyEntityRow).not.toHaveBeenCalled();
expect(dependencies.updateLegacyEntityRow).not.toHaveBeenCalled();
expect(dependencies.deleteLegacyEntityRow).not.toHaveBeenCalled();
});
});
@@ -6,10 +6,6 @@ import {
TEST_API_CONFIG,
TEST_JWT_SECRET,
configureApiIsolationDependenciesForTests,
createLegacyEntityFixture,
createLegacyRelationshipRowFixture,
createLegacyRowFixture,
createLegacyRowRelationshipFixture,
createStoredApiKeyFixture,
installApiIsolationTestHooks,
patchApiIsolationConfig,
@@ -19,27 +15,14 @@ import {
installApiIsolationTestHooks();
describe("api-key isolation fixtures", () => {
test("exposes stable default runtime and row fixtures", () => {
test("exposes stable default runtime and api-key fixtures", () => {
const apiKey = createStoredApiKeyFixture();
const entity = createLegacyEntityFixture();
const row = createLegacyRowFixture();
const relationshipRow = createLegacyRelationshipRowFixture();
const rowRelationship = createLegacyRowRelationshipFixture();
expect(TEST_API_CONFIG.apiAccessToken).toBe("service-secret");
expect(TEST_API_CONFIG.jwtSecret).toBe(TEST_JWT_SECRET);
expect(TEST_JWT_SECRET).toBe("scope-secret");
expect(getApiRuntimeConfig()).toMatchObject({ apiAccessToken: "service-secret", jwtSecret: "scope-secret" });
expect(apiKey).toMatchObject({ tenantId: "tenant_1", tenant: { id: "tenant_1" }, active: true, entities: [] });
expect(entity).toMatchObject({ id: "entity_1", name: "contact" });
expect(row).toMatchObject({ id: "row_1", entityId: "entity_1", tenantId: "tenant_1", parentRows: [], childRows: [] });
expect(relationshipRow).toEqual({ id: "row_1", entityId: "entity_1", tenantId: "tenant_1" });
expect(rowRelationship).toMatchObject({
id: "row_relationship_1",
parentId: "parent_row_1",
childId: "child_row_1",
relationship: { parentId: "parent_entity_1", childId: "child_entity_1" },
});
expect(apiKey).toMatchObject({ tenantId: "tenant_1", tenant: { id: "tenant_1" }, active: true });
});
test("patches tenant-related fixture values without hiding mismatches", () => {
@@ -47,12 +30,13 @@ describe("api-key isolation fixtures", () => {
const apiKey = createStoredApiKeyFixture({ tenantId: "tenant_2" });
const mismatchedApiKey = createStoredApiKeyFixture({ tenantId: "tenant_2", tenant: { id: "tenant_3", name: "Other", slug: "other", deactivatedReason: null } });
const row = createLegacyRowFixture("row_tenant_2", { tenantId: "tenant_2" });
// tenant provided without an explicit tenantId → tenantId is derived from tenant.id.
const derivedTenantApiKey = createStoredApiKeyFixture({ tenant: { id: "tenant_5", name: "Derived", slug: "derived", deactivatedReason: null } });
expect(getApiRuntimeConfig()).toMatchObject({ apiAccessToken: "tenant-2-service", jwtSecret: "tenant-2-secret" });
expect(apiKey).toMatchObject({ tenantId: "tenant_2", tenant: { id: "tenant_2" } });
expect(mismatchedApiKey).toMatchObject({ tenantId: "tenant_2", tenant: { id: "tenant_3" } });
expect(row).toMatchObject({ id: "row_tenant_2", tenantId: "tenant_2" });
expect(derivedTenantApiKey).toMatchObject({ tenantId: "tenant_5", tenant: { id: "tenant_5" } });
});
test("resets runtime config patches after each test via installed hooks", () => {
@@ -87,7 +71,6 @@ describe("api-key isolation fixtures", () => {
origins: { web: "https://web.tenant-2.test" },
analytics: { token: "analytics_tenant2" },
mailjet: { webhookSecret: "mailer_tenant2_whsec" },
stripe: { secretKey: "sk_test_tenant2", webhookSigningSecret: "whsec_tenant2" },
storage: { bucket: "tenant-2-bucket", region: "eu-central-1" },
});
@@ -99,7 +82,6 @@ describe("api-key isolation fixtures", () => {
origins: { web: "https://web.tenant-2.test" },
analytics: { token: "analytics_tenant2" },
mailjet: { webhookSecret: "mailer_tenant2_whsec" },
stripe: { secretKey: "sk_test_tenant2", webhookSigningSecret: "whsec_tenant2" },
storage: { bucket: "tenant-2-bucket", region: "eu-central-1" },
});
});
@@ -1,300 +0,0 @@
import { describe, expect, test, vi } from "vitest";
import { app } from "../app.js";
import {
TEST_API_CONFIG,
configureApiIsolationDependenciesForTests,
createLegacyRelationshipRowFixture,
createLegacyRowFixture,
createLegacyRowRelationshipFixture,
createStoredApiKeyFixture,
installApiIsolationTestHooks,
} from "./fixtures/api-key.js";
installApiIsolationTestHooks();
const STORED_API_KEY_SECRET = "stored-relationship-key-secret";
const INVALID_API_KEY_SECRET = "invalid-relationship-key-secret";
const REQUEST_ID = "req_relationship_scope";
function createScopedRelationshipApiKey(patch: Parameters<typeof createStoredApiKeyFixture>[0] = {}) {
return createStoredApiKeyFixture({
entities: [
{ entityId: "parent_entity_1", read: true, create: true, update: false, delete: true },
{ entityId: "child_entity_1", read: true, create: true, update: false, delete: true },
],
...patch,
});
}
function createRelationshipDependencies(apiKey = createScopedRelationshipApiKey()) {
const parentRelationshipRow = createLegacyRelationshipRowFixture("parent_row_1", "parent_entity_1");
const childRelationshipRow = createLegacyRelationshipRowFixture("child_row_1", "child_entity_1");
const parentEntityRow = createLegacyRowFixture("parent_row_1", { entityId: "parent_entity_1" });
const childEntityRow = createLegacyRowFixture("child_row_1", { entityId: "child_entity_1" });
const rowRelationship = createLegacyRowRelationshipFixture("row_relationship_1", "parent_row_1", "child_row_1", "parent_entity_1", "child_entity_1");
const entityRelationship = { id: "entity_relationship_1", parentId: "parent_entity_1", childId: "child_entity_1" };
const createdRelationship = createLegacyRowRelationshipFixture("row_relationship_created", "parent_row_1", "child_row_1", "parent_entity_1", "child_entity_1");
const dependencies = {
findLegacyApiKeyByKey: vi.fn(async (key: string) => (key === STORED_API_KEY_SECRET ? apiKey : null)),
findLegacyRelationshipRowById: vi.fn(async ({ id, tenantId }: { id: string; tenantId?: string | null }) => {
if (tenantId !== "tenant_1") return null;
if (id === parentRelationshipRow.id) return parentRelationshipRow;
if (id === childRelationshipRow.id) return childRelationshipRow;
return null;
}),
findLegacyEntityRelationship: vi.fn(async () => entityRelationship),
findLegacyRowRelationshipById: vi.fn(async (id: string, tenantId?: string | null) => (id === rowRelationship.id && tenantId === "tenant_1" ? rowRelationship : null)),
getLegacyEntityRow: vi.fn(async ({ rowId }: { rowId: string }) => {
if (rowId === parentEntityRow.id) return parentEntityRow;
if (rowId === childEntityRow.id) return childEntityRow;
return null;
}),
createLegacyRowRelationship: vi.fn(async () => createdRelationship),
deleteLegacyRowRelationshipById: vi.fn(async () => undefined),
};
configureApiIsolationDependenciesForTests(dependencies);
return { apiKey, parentRelationshipRow, childRelationshipRow, parentEntityRow, childEntityRow, rowRelationship, entityRelationship, createdRelationship, dependencies };
}
function apiKeyHeaders(secret = STORED_API_KEY_SECRET, requestId = REQUEST_ID) {
return { "x-api-key": secret, "x-request-id": requestId, "idempotency-key": `${requestId}-idempotency` };
}
function bearerHeaders(secret = STORED_API_KEY_SECRET, requestId = REQUEST_ID) {
return { authorization: `Bearer ${secret}`, "x-request-id": requestId, "idempotency-key": `${requestId}-idempotency` };
}
function jsonHeaders(headers: Record<string, string>) {
return { ...headers, "content-type": "application/json" };
}
function jsonRequest(headers: Record<string, string>, body: unknown) {
const serialized = JSON.stringify(body);
return {
body: serialized,
headers: { ...jsonHeaders(headers), "content-length": String(Buffer.byteLength(serialized)) },
};
}
async function expectRedactedError(response: Response, expected: { status: number; code: string; requestId: string }) {
expect(response.status).toBe(expected.status);
expect(response.headers.get("x-request-id")).toBe(expected.requestId);
const text = await response.text();
expect(text).toContain(expected.requestId);
expect(text).not.toContain(STORED_API_KEY_SECRET);
expect(text).not.toContain(INVALID_API_KEY_SECRET);
expect(text).not.toContain(TEST_API_CONFIG.apiAccessToken);
expect(text).not.toContain("scope-secret");
expect(JSON.parse(text)).toEqual({
error: expect.objectContaining({
code: expected.code,
requestId: expected.requestId,
}),
});
}
function expectNoMutationAfterDeniedScope(dependencies: ReturnType<typeof createRelationshipDependencies>["dependencies"]) {
expect(dependencies.findLegacyEntityRelationship).not.toHaveBeenCalled();
expect(dependencies.createLegacyRowRelationship).not.toHaveBeenCalled();
expect(dependencies.deleteLegacyRowRelationshipById).not.toHaveBeenCalled();
}
describe("stored API-key relationship isolation", () => {
test("allows create on POST /v1/relationships when parent and child have create scope", async () => {
const { dependencies, createdRelationship } = createRelationshipDependencies();
const response = await app.request("/v1/relationships?tenantId=tenant_1", {
method: "POST",
...jsonRequest(apiKeyHeaders(), { parent: "parent_row_1", child: "child_row_1" }),
});
expect(response.status).toBe(201);
await expect(response.json()).resolves.toMatchObject({
relationship: { id: createdRelationship.id, parent: { id: "parent_row_1", entityId: "parent_entity_1" }, child: { id: "child_row_1", entityId: "child_entity_1" } },
});
expect(dependencies.findLegacyApiKeyByKey).toHaveBeenCalledWith(STORED_API_KEY_SECRET, undefined, "scope-secret", { allowPlaintextFallback: true });
expect(dependencies.findLegacyEntityRelationship).toHaveBeenCalledWith({ parentId: "parent_entity_1", childId: "child_entity_1" });
expect(dependencies.createLegacyRowRelationship).toHaveBeenCalledWith({
relationshipId: "entity_relationship_1",
parentId: "parent_row_1",
childId: "child_row_1",
tenantId: "tenant_1",
});
});
test("allows header API key read on GET /v1/relationships/:id when parent and child have read scope", async () => {
const { dependencies, rowRelationship } = createRelationshipDependencies();
const response = await app.request("/v1/relationships/row_relationship_1?tenantId=tenant_1", { headers: apiKeyHeaders() });
expect(response.status).toBe(200);
await expect(response.json()).resolves.toMatchObject({ relationship: { id: rowRelationship.id, parent: { entityId: "parent_entity_1" }, child: { entityId: "child_entity_1" } } });
expect(dependencies.findLegacyRowRelationshipById).toHaveBeenCalledWith("row_relationship_1", "tenant_1");
expect(dependencies.getLegacyEntityRow).toHaveBeenCalledWith({ entityId: "parent_entity_1", tenantId: "tenant_1", rowId: "parent_row_1" });
expect(dependencies.getLegacyEntityRow).toHaveBeenCalledWith({ entityId: "child_entity_1", tenantId: "tenant_1", rowId: "child_row_1" });
});
test("allows delete on DELETE /v1/relationships/:id when parent and child have delete scope", async () => {
const { dependencies, rowRelationship } = createRelationshipDependencies();
const response = await app.request("/v1/relationships/row_relationship_1?tenantId=tenant_1", {
method: "DELETE",
headers: apiKeyHeaders(),
});
expect(response.status).toBe(200);
await expect(response.json()).resolves.toMatchObject({ deleted: { id: rowRelationship.id, parent: { entityId: "parent_entity_1" }, child: { entityId: "child_entity_1" } } });
expect(dependencies.deleteLegacyRowRelationshipById).toHaveBeenCalledWith({
id: "row_relationship_1",
relationshipId: "entity_relationship_1",
parentId: "parent_row_1",
childId: "child_row_1",
tenantId: "tenant_1",
});
});
test("denies create on POST /v1/relationships when parent create scope is missing", async () => {
const apiKey = createScopedRelationshipApiKey({
entities: [
{ entityId: "parent_entity_1", read: true, create: false, update: false, delete: true },
{ entityId: "child_entity_1", read: true, create: true, update: false, delete: true },
],
});
const { dependencies } = createRelationshipDependencies(apiKey);
const response = await app.request("/v1/relationships?tenantId=tenant_1", {
method: "POST",
...jsonRequest(apiKeyHeaders(STORED_API_KEY_SECRET, "req_relationship_missing_parent_create"), { parent: "parent_row_1", child: "child_row_1" }),
});
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_relationship_missing_parent_create" });
expectNoMutationAfterDeniedScope(dependencies);
});
test("denies create on POST /v1/relationships when child create scope is missing", async () => {
const apiKey = createScopedRelationshipApiKey({
entities: [
{ entityId: "parent_entity_1", read: true, create: true, update: false, delete: true },
{ entityId: "child_entity_1", read: true, create: false, update: false, delete: true },
],
});
const { dependencies } = createRelationshipDependencies(apiKey);
const response = await app.request("/v1/relationships?tenantId=tenant_1", {
method: "POST",
...jsonRequest(apiKeyHeaders(STORED_API_KEY_SECRET, "req_relationship_missing_child_create"), { parent: "parent_row_1", child: "child_row_1" }),
});
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_relationship_missing_child_create" });
expectNoMutationAfterDeniedScope(dependencies);
});
test("returns the same forbidden response for missing relationship rows with stored API keys", async () => {
const apiKey = createScopedRelationshipApiKey({ entities: [] });
const { dependencies } = createRelationshipDependencies(apiKey);
const response = await app.request("/v1/relationships?tenantId=tenant_1", {
method: "POST",
...jsonRequest(apiKeyHeaders(STORED_API_KEY_SECRET, "req_relationship_missing_row"), { parent: "missing_parent_row", child: "child_row_1" }),
});
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_relationship_missing_row" });
expectNoMutationAfterDeniedScope(dependencies);
});
test("denies read on GET /v1/relationships/:id when tenantId=tenant_2 tampers tenant", async () => {
const { dependencies } = createRelationshipDependencies();
const response = await app.request("/v1/relationships/row_relationship_1?tenantId=tenant_2", { headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_relationship_wrong_tenant") });
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_relationship_wrong_tenant" });
expect(dependencies.findLegacyRowRelationshipById).not.toHaveBeenCalled();
expect(dependencies.deleteLegacyRowRelationshipById).not.toHaveBeenCalled();
expect(dependencies.createLegacyRowRelationship).not.toHaveBeenCalled();
});
test("returns the same forbidden response for missing relationship ids with stored API keys", async () => {
const apiKey = createScopedRelationshipApiKey({ entities: [] });
const { dependencies } = createRelationshipDependencies(apiKey);
const response = await app.request("/v1/relationships/missing_relationship?tenantId=tenant_1", { headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_relationship_missing_id") });
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_relationship_missing_id" });
expect(dependencies.deleteLegacyRowRelationshipById).not.toHaveBeenCalled();
expect(dependencies.createLegacyRowRelationship).not.toHaveBeenCalled();
});
test("denies delete on DELETE /v1/relationships/:id when parent delete scope is missing", async () => {
const apiKey = createScopedRelationshipApiKey({
entities: [
{ entityId: "parent_entity_1", read: true, create: true, update: false, delete: false },
{ entityId: "child_entity_1", read: true, create: true, update: false, delete: true },
],
});
const { dependencies } = createRelationshipDependencies(apiKey);
const response = await app.request("/v1/relationships/row_relationship_1?tenantId=tenant_1", {
method: "DELETE",
headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_relationship_missing_parent_delete"),
});
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_relationship_missing_parent_delete" });
expect(dependencies.deleteLegacyRowRelationshipById).not.toHaveBeenCalled();
expect(dependencies.createLegacyRowRelationship).not.toHaveBeenCalled();
expect(dependencies.findLegacyEntityRelationship).not.toHaveBeenCalled();
});
test("denies delete on DELETE /v1/relationships/:id when child delete scope is missing", async () => {
const apiKey = createScopedRelationshipApiKey({
entities: [
{ entityId: "parent_entity_1", read: true, create: true, update: false, delete: true },
{ entityId: "child_entity_1", read: true, create: true, update: false, delete: false },
],
});
const { dependencies } = createRelationshipDependencies(apiKey);
const response = await app.request("/v1/relationships/row_relationship_1?tenantId=tenant_1", {
method: "DELETE",
headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_relationship_missing_child_delete"),
});
await expectRedactedError(response, { status: 403, code: "forbidden", requestId: "req_relationship_missing_child_delete" });
expect(dependencies.deleteLegacyRowRelationshipById).not.toHaveBeenCalled();
expect(dependencies.createLegacyRowRelationship).not.toHaveBeenCalled();
expect(dependencies.findLegacyEntityRelationship).not.toHaveBeenCalled();
});
test("denies create on POST /v1/relationships with invalid x-api-key without service-token fallback", async () => {
const { dependencies } = createRelationshipDependencies();
const response = await app.request("/v1/relationships?tenantId=tenant_1", {
method: "POST",
...jsonRequest(apiKeyHeaders(INVALID_API_KEY_SECRET, "req_relationship_invalid_key"), { parent: "parent_row_1", child: "child_row_1" }),
});
await expectRedactedError(response, { status: 401, code: "unauthorized", requestId: "req_relationship_invalid_key" });
expect(dependencies.findLegacyApiKeyByKey).toHaveBeenCalledWith(INVALID_API_KEY_SECRET, undefined, "scope-secret", { allowPlaintextFallback: true });
expect(dependencies.findLegacyRelationshipRowById).not.toHaveBeenCalled();
expectNoMutationAfterDeniedScope(dependencies);
});
test("denies delete on DELETE /v1/relationships/:id with invalid bearer token without stored-key fallback", async () => {
const { dependencies } = createRelationshipDependencies();
const response = await app.request("/v1/relationships/row_relationship_1?tenantId=tenant_1", {
method: "DELETE",
headers: bearerHeaders(INVALID_API_KEY_SECRET, "req_relationship_invalid_bearer"),
});
await expectRedactedError(response, { status: 401, code: "unauthorized", requestId: "req_relationship_invalid_bearer" });
expect(dependencies.findLegacyApiKeyByKey).not.toHaveBeenCalled();
expect(dependencies.findLegacyRowRelationshipById).not.toHaveBeenCalled();
expect(dependencies.deleteLegacyRowRelationshipById).not.toHaveBeenCalled();
});
});
@@ -4,7 +4,6 @@ import { app } from "../app.js";
import {
TEST_API_CONFIG,
configureApiIsolationDependenciesForTests,
createLegacyEntityFixture,
createStoredApiKeyFixture,
installApiIsolationTestHooks,
} from "./fixtures/api-key.js";
@@ -22,7 +21,6 @@ function createBoundaryApiKey(patch: Parameters<typeof createStoredApiKeyFixture
id: "api_key_boundary_1",
tenantId: "tenant_1",
tenant: { id: "tenant_1", name: "Acme", slug: "acme", deactivatedReason: null },
entities: [{ entityId: "entity_1", read: true, create: true, update: true, delete: true }],
...patch,
});
}
@@ -52,7 +50,6 @@ function createBoundaryDependencies() {
tenant: { id: "tenant_2", name: "Other", slug: "other", deactivatedReason: null },
});
const exportJob = createExportJob();
const entity = createLegacyEntityFixture();
const dependencies = {
findLegacyApiKeyByKey: vi.fn(async (key: string) => {
@@ -71,12 +68,11 @@ function createBoundaryDependencies() {
expiresInSeconds: 300,
headers: { "x-download": "allowed" },
})),
findLegacyEntityByName: vi.fn(async () => entity),
};
configureApiIsolationDependenciesForTests(dependencies);
return { primaryApiKey, secondTenantApiKey, exportJob, entity, dependencies };
return { primaryApiKey, secondTenantApiKey, exportJob, dependencies };
}
function apiKeyHeaders(secret = STORED_API_KEY_SECRET, requestId = REQUEST_ID) {
@@ -203,7 +199,6 @@ describe("API-key validation service boundary", () => {
expect(dependencies.findLegacyApiKeyByKey).toHaveBeenCalledWith(INVALID_API_KEY_SECRET, undefined, "scope-secret", { allowPlaintextFallback: true });
});
});
describe("export download service boundary", () => {
test("rejects stored key export lookup when tenantId query is tampered", async () => {
const { dependencies } = createBoundaryDependencies();
@@ -287,15 +282,3 @@ describe("export download service boundary", () => {
expect(dependencies.createSignedDownloadUrl).not.toHaveBeenCalled();
});
});
describe("service-credential-only route boundaries", () => {
test("keeps non-CRUD entity metadata route outside stored API-key CRUD scope claims", async () => {
const { dependencies } = createBoundaryDependencies();
const response = await app.request("/v1/entities/contact?tenantId=tenant_1", { headers: apiKeyHeaders(STORED_API_KEY_SECRET, "req_service_only_entity") });
await expectRedactedError(response, { status: 401, code: "unauthorized", requestId: "req_service_only_entity" });
expect(dependencies.findLegacyApiKeyByKey).not.toHaveBeenCalled();
expect(dependencies.findLegacyEntityByName).not.toHaveBeenCalled();
});
});
@@ -1,10 +1,7 @@
import { afterEach, beforeEach } from "vitest";
import type { ApiConfig } from "@toolctrl/config";
import type { LegacyApiKeySimple } from "@toolctrl/db/api-keys.server";
import type { LegacyEntityWithDetails } from "@toolctrl/db/entities.server";
import type { LegacyRowRelationshipDetails } from "@toolctrl/db/relationships.server";
import type { LegacyEntityRow, LegacyRelationshipRow } from "@toolctrl/db/rows.server";
import type { ApiConfig } from "@hivegrid/config";
import type { LegacyApiKeySimple } from "@hivegrid/db/api-keys.server";
import { configureApiAppDependenciesForTests } from "../../app.js";
import { resetApiRuntimeConfigForTests, setApiRuntimeConfigForTests } from "../../config.js";
@@ -28,7 +25,8 @@ export const TEST_API_CONFIG: ApiConfig = {
jwtSecret: TEST_JWT_SECRET,
analytics: {},
mailjet: {},
stripe: {},
lago: { timeoutMs: 10000 },
mollie: { timeoutMs: 10000 },
apiKeys: {
allowLegacyPlaintextFallback: true,
},
@@ -49,7 +47,8 @@ function cloneApiConfig(config: ApiConfig): ApiConfig {
analytics: { ...config.analytics },
apiKeys: { ...config.apiKeys },
mailjet: { ...config.mailjet },
stripe: { ...config.stripe },
lago: { ...config.lago },
mollie: { ...config.mollie },
storage: { ...config.storage },
};
}
@@ -63,7 +62,8 @@ function mergeApiConfigPatch(config: ApiConfig, patch: Partial<ApiConfig>): ApiC
origins: patch.origins ? { ...config.origins, ...patch.origins } : { ...config.origins },
analytics: patch.analytics ? { ...config.analytics, ...patch.analytics } : { ...config.analytics },
mailjet: patch.mailjet ? { ...config.mailjet, ...patch.mailjet } : { ...config.mailjet },
stripe: patch.stripe ? { ...config.stripe, ...patch.stripe } : { ...config.stripe },
lago: patch.lago ? { ...config.lago, ...patch.lago } : { ...config.lago },
mollie: patch.mollie ? { ...config.mollie, ...patch.mollie } : { ...config.mollie },
storage: patch.storage ? { ...config.storage, ...patch.storage } : { ...config.storage },
};
}
@@ -112,137 +112,10 @@ export function createStoredApiKeyFixture(patch: Partial<LegacyApiKeySimple> = {
alias: "Primary integration key",
expires: null,
tenantId,
createdByUserId: "user_1",
active: true,
entities: [],
scopes: ["*"],
tenant: { id: tenantId, name: "Acme", slug: "acme", deactivatedReason: null },
...patch,
};
}
export function createLegacyEntityFixture(patch: Partial<LegacyEntityWithDetails> = {}): LegacyEntityWithDetails {
return {
id: "entity_1",
moduleId: null,
name: "contact",
title: "Contact",
titlePlural: "Contacts",
active: true,
slug: "contacts",
prefix: "CON",
type: "default",
hasApi: true,
showInSidebar: true,
hasTags: true,
hasComments: true,
hasTasks: true,
hasActivity: true,
hasBulkDelete: false,
hasViews: true,
defaultVisibility: "private",
onCreated: "redirectToOverview",
icon: "User",
onEdit: null,
promptFlowGroupId: null,
isAutogenerated: false,
order: 1,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
properties: [
{
id: "property_1",
tenantId: null,
entityId: "entity_1",
name: "firstName",
title: "First name",
type: 0,
subtype: null,
isHidden: false,
isDisplay: false,
isRequired: false,
isDefault: false,
isUnique: false,
canUpdate: true,
isReadOnly: false,
showInCreate: true,
order: 1,
formulaId: null,
attributes: [],
options: [],
formula: null,
},
{
id: "property_2",
tenantId: null,
entityId: "entity_1",
name: "hiddenName",
title: "Hidden name",
type: 0,
subtype: null,
isHidden: true,
isDisplay: false,
isRequired: false,
isDefault: false,
isUnique: false,
canUpdate: true,
isReadOnly: false,
showInCreate: false,
order: 2,
formulaId: null,
attributes: [],
options: [],
formula: null,
},
],
views: [],
tags: [],
parentEntities: [],
childEntities: [],
templates: [],
...patch,
};
}
export function createLegacyRowFixture(id = "row_1", patch: Partial<LegacyEntityRow> = {}): LegacyEntityRow {
return {
id,
entityId: "entity_1",
tenantId: "tenant_1",
createdAt: new Date("2026-01-01T00:00:00.000Z"),
updatedAt: new Date("2026-01-01T00:00:00.000Z"),
deletedAt: null,
createdByUserId: null,
createdByApiKeyId: null,
folio: 1,
order: 1,
createdByUser: null,
createdByApiKey: null,
values: [],
parentRows: [] ,
childRows: [],
...patch,
};
}
export function createLegacyRelationshipRowFixture(id = "row_1", entityId = "entity_1", patch: Partial<LegacyRelationshipRow> = {}): LegacyRelationshipRow {
return { id, entityId, tenantId: "tenant_1", ...patch };
}
export function createLegacyRowRelationshipFixture(
id = "row_relationship_1",
parentId = "parent_row_1",
childId = "child_row_1",
parentEntityId = "parent_entity_1",
childEntityId = "child_entity_1",
patch: Partial<LegacyRowRelationshipDetails> = {},
): LegacyRowRelationshipDetails {
return {
id,
relationshipId: "entity_relationship_1",
parentId,
childId,
metadata: null,
createdAt: new Date("2026-01-01T00:00:00.000Z"),
relationship: { id: "entity_relationship_1", parentId: parentEntityId, childId: childEntityId },
...patch,
};
}
@@ -1,5 +1,5 @@
import { createSentryErrorReporter, initializeTracing, type ErrorReporter } from "@toolctrl/error-reporter";
import { createChildLogger, defaultLogger } from "@toolctrl/logger";
import { createSentryErrorReporter, initializeTracing, type ErrorReporter } from "@hivegrid/error-reporter";
import { createChildLogger, defaultLogger } from "@hivegrid/logger";
export const apiLogger = createChildLogger(defaultLogger, { component: "api" });
@@ -8,8 +8,8 @@
* lets business code call `apiMetrics.aiTokensConsumedTotal.inc(...)` without
* branching on an env flag everywhere.
*/
import { createDefaultMetrics, createMetricsRegistry, type DefaultMetrics, type MetricsRegistry } from "@toolctrl/metrics";
import { setEnqueueObserver } from "@toolctrl/queue";
import { createDefaultMetrics, createMetricsRegistry, type DefaultMetrics, type MetricsRegistry } from "@hivegrid/metrics";
import { setEnqueueObserver } from "@hivegrid/queue";
type ApiMetricsBundle = {
registry: MetricsRegistry;
@@ -1,7 +1,7 @@
import { Hono } from "hono";
import { HTTPException } from "hono/http-exception";
import { afterEach, describe, expect, test, vi } from "vitest";
import type { ErrorReporter } from "@toolctrl/error-reporter";
import type { ErrorReporter } from "@hivegrid/error-reporter";
import { apiLogger } from "../logger.js";
import { apiError, createErrorHandler, createNotFoundHandler, normalizeErrorStatus, type ApiErrorEnv } from "./error-envelope.js";
@@ -1,4 +1,4 @@
import { reportError, type ErrorReporter } from "@toolctrl/error-reporter";
import { reportError, type ErrorReporter } from "@hivegrid/error-reporter";
import type { Context } from "hono";
import { HTTPException } from "hono/http-exception";
import { apiLogger } from "../logger.js";
@@ -0,0 +1,72 @@
import { describe, expect, it, vi } from "vitest";
import { createMetricsMiddleware, type ApiMetricsMiddlewareOptions } from "./metrics.js";
/**
* A metrics double that records the label set each timeseries was incremented /
* observed with. Invoking the middleware directly (rather than through a Hono
* app) is the only way to drive the `nextError` and missing-`res` branches:
* Hono's `onError` flow resolves `next()` and attaches the error to the
* context, so the middleware's own catch never runs in an integration test.
*/
function buildMetrics(options: { throwOnWrite?: boolean } = {}) {
const totalLabels = vi.fn((labels: Record<string, string>) => {
if (options.throwOnWrite) throw new Error("registry write failed");
return { inc: vi.fn(), labels } as never;
});
const durationLabels = vi.fn((labels: Record<string, string>) => ({ observe: vi.fn(), labels }) as never);
const metrics = {
httpRequestsTotal: { labels: totalLabels },
httpRequestDurationSeconds: { labels: durationLabels },
} as unknown as ApiMetricsMiddlewareOptions["metrics"];
return { metrics, totalLabels, durationLabels };
}
function buildContext(req: Record<string, unknown>, res?: { status: number }) {
return { req, res } as never;
}
describe("createMetricsMiddleware edge branches", () => {
it("records status 500 and rethrows when next() throws", async () => {
const { metrics, totalLabels } = buildMetrics();
const middleware = createMetricsMiddleware({ enabled: true, metrics, now: () => 0 });
const boom = new Error("kaboom");
await expect(
middleware(buildContext({ method: "get", routePath: "/v1/x" }, { status: 200 }), async () => {
throw boom;
}),
).rejects.toBe(boom);
expect(totalLabels).toHaveBeenCalledWith({ method: "GET", route: "/v1/x", status: "500" });
});
it("labels status as 0 when no response status is available", async () => {
const { metrics, totalLabels } = buildMetrics();
const middleware = createMetricsMiddleware({ enabled: true, metrics, now: () => 0 });
await middleware(buildContext({ method: "GET", routePath: "/v1/x" }, undefined), async () => undefined);
expect(totalLabels).toHaveBeenCalledWith({ method: "GET", route: "/v1/x", status: "0" });
});
it("falls back to <unmatched> route and UNKNOWN method labels", async () => {
const { metrics, totalLabels } = buildMetrics();
const middleware = createMetricsMiddleware({ enabled: true, metrics, now: () => 0 });
await middleware(buildContext({ method: undefined, routePath: "/*" }, { status: 404 }), async () => undefined);
expect(totalLabels).toHaveBeenCalledWith({ method: "UNKNOWN", route: "<unmatched>", status: "404" });
});
it("never lets a registry write error break the request", async () => {
const { metrics } = buildMetrics({ throwOnWrite: true });
const middleware = createMetricsMiddleware({ enabled: true, metrics, now: () => 0 });
const next = vi.fn(async () => undefined);
await expect(
middleware(buildContext({ method: "GET", routePath: "/v1/x" }, { status: 200 }), next),
).resolves.toBeUndefined();
expect(next).toHaveBeenCalledTimes(1);
});
});
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach } from "vitest";
import { Hono } from "hono";
import { createDefaultMetrics, createMetricsRegistry, type DefaultMetrics, type MetricsRegistry } from "@toolctrl/metrics";
import { createDefaultMetrics, createMetricsRegistry, type DefaultMetrics, type MetricsRegistry } from "@hivegrid/metrics";
import { createMetricsMiddleware } from "./metrics.js";
let registry: MetricsRegistry;
@@ -13,7 +13,7 @@
* @see docs/improvement-plan/02-observability/metrics-grafana.md
*/
import type { Context, MiddlewareHandler } from "hono";
import type { DefaultMetrics } from "@toolctrl/metrics";
import type { DefaultMetrics } from "@hivegrid/metrics";
export type ApiMetricsMiddlewareOptions = {
enabled: boolean;
@@ -0,0 +1,90 @@
import { describe, expect, it, vi } from "vitest";
import { createSentryTracingMiddleware, type SentryLikeForTracing, type SentrySpan } from "./sentryTracing.js";
type RecordedSpan = {
args: { op: string; name: string; attributes?: Record<string, unknown> };
attributes: Record<string, unknown>;
status?: { code: number; message?: string };
};
function buildFakeSentry() {
const captureException = vi.fn();
const spans: RecordedSpan[] = [];
const module: SentryLikeForTracing = {
captureException,
async startSpan(args, callback) {
const record: RecordedSpan = { args, attributes: { ...(args.attributes ?? {}) }, status: undefined };
spans.push(record);
const span: SentrySpan = {
setAttribute(key, value) {
record.attributes[key] = value;
},
setStatus(status) {
record.status = status;
},
};
return callback(span);
},
};
return { module, captureException, spans };
}
/**
* Minimal Hono-context double. The middleware only reads `req.method`,
* `req.routePath`, `get("requestId")`, `res?.status` and the dispatched
* `error`, so a hand-rolled object is enough to drive the branches that
* Hono's own routing/onError flow can't reproduce (a thrown-through error
* that propagates back out of `next()`).
*/
function buildContext(overrides: Partial<{ requestId: unknown; res: { status: number } | undefined }>) {
return {
req: { method: "POST", path: "/v1/things/abc", routePath: "/v1/things/:id" },
res: overrides.res,
error: undefined as unknown,
get: (key: string) => (key === "requestId" ? overrides.requestId : undefined),
};
}
describe("sentryTracingMiddleware error propagation", () => {
it("rethrows a downstream error and captures it with span context", async () => {
const { module, spans, captureException } = buildFakeSentry();
const middleware = createSentryTracingMiddleware({ enabled: true, sentry: module });
const c = buildContext({ requestId: "req-abc-123", res: undefined });
const next = vi.fn(async () => {
throw new Error("downstream boom");
});
await expect(middleware(c as never, next as never)).rejects.toThrow("downstream boom");
expect(spans).toHaveLength(1);
// No response object + an error => the middleware synthesizes a 500.
expect(spans[0].attributes["http.status_code"]).toBe(500);
expect(spans[0].status).toEqual({ code: 2, message: "internal_error" });
// String requestId is tagged onto the span.
expect(spans[0].attributes["hivegrid.request_id"]).toBe("req-abc-123");
expect(captureException).toHaveBeenCalledTimes(1);
const [thrown, context] = captureException.mock.calls[0] ?? [];
expect((thrown as Error).message).toBe("downstream boom");
expect((context as { tags?: Record<string, unknown> }).tags?.["http.route"]).toBe("/v1/things/:id");
});
it("omits the request_id attribute when no requestId is set", async () => {
const { module, spans, captureException } = buildFakeSentry();
const middleware = createSentryTracingMiddleware({ enabled: true, sentry: module });
const c = buildContext({ requestId: undefined, res: { status: 204 } });
const next = vi.fn(async () => undefined);
await middleware(c as never, next as never);
expect(next).toHaveBeenCalledTimes(1);
expect(spans[0].attributes).not.toHaveProperty("hivegrid.request_id");
expect(spans[0].attributes["http.status_code"]).toBe(204);
// 2xx response => no error status is set.
expect(spans[0].status).toBeUndefined();
expect(captureException).not.toHaveBeenCalled();
});
});
@@ -104,7 +104,7 @@ export function createSentryTracingMiddleware(options: SentryTracingMiddlewareOp
"http.method": method,
"http.target": c.req.path,
"http.route": routePattern,
...(typeof requestId === "string" && requestId ? { "toolctrl.request_id": requestId } : {}),
...(typeof requestId === "string" && requestId ? { "hivegrid.request_id": requestId } : {}),
},
},
async (span) => {
@@ -224,13 +224,10 @@ describe("openApiDocument", () => {
["/v1/workspaces/{tenantId}/invites", "post"],
["/v1/workspaces/{tenantId}/invites/{inviteId}/accept", "post"],
["/v1/workspaces/{tenantId}/invites/{inviteId}/revoke", "post"],
["/v1/entities/{entity}/rows", "post"],
["/v1/entities/{entity}/rows/{rowId}", "patch"],
["/v1/relationships", "post"],
["/v1/ai/upload", "post"],
["/v1/support/inbound-email", "post"],
["/v1/email-sequences/mailjet/webhooks", "post"],
["/v1/billing/stripe/webhooks", "post"],
["/v1/billing/mollie/webhooks", "post"],
["/v1/events/webhooks/attempts/{id}", "post"],
] as const;
@@ -268,12 +265,7 @@ describe("openApiDocument", () => {
["/v1/analytics/admin", "get"],
["/v1/accounts", "get"],
["/v1/accounts/{id}", "get"],
["/v1/entities/{entity}/rows", "get"],
["/v1/workspaces/{tenantId}/invites", "get"],
["/v1/entities/{entity}/rows/{rowId}", "get"],
["/v1/entities/{entity}/rows/{rowId}", "delete"],
["/v1/relationships/{id}", "get"],
["/v1/relationships/{id}", "delete"],
["/v1/exports/{exportJobId}/download-url", "get"],
] as const;
@@ -326,13 +318,13 @@ describe("openApiDocument", () => {
expect(serializedLoginRateLimitSchema).not.toMatch(
/email|password|credential|account|token|api[-_ ]?key|[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}|secret|Bearer\s+[A-Za-z0-9._~+/-]{12,}/i
);
expect(openApiDocument.paths["/v1/auth/login"].post.responses["200"].description).toContain("HttpOnly RJ_api_session cookie");
expect(openApiDocument.paths["/v1/auth/refresh-token"].post.responses["200"].description).toContain("HttpOnly RJ_api_session cookie");
expect(openApiDocument.paths["/v1/auth/login"].post.responses["200"].description).toContain("HttpOnly hivegrid_api_session cookie");
expect(openApiDocument.paths["/v1/auth/refresh-token"].post.responses["200"].description).toContain("HttpOnly hivegrid_api_session cookie");
expect(openApiDocument.paths["/v1/auth/logout"].post).toMatchObject({
operationId: "logoutApiSession",
security: [{ apiSessionBearer: [] }],
responses: {
"200": { description: expect.stringContaining("clears the HttpOnly RJ_api_session cookie") },
"200": { description: expect.stringContaining("clears the HttpOnly hivegrid_api_session cookie") },
"401": { description: expect.stringContaining("invalid") },
},
});
@@ -374,22 +366,6 @@ describe("openApiDocument", () => {
},
},
});
expect(openApiDocument.paths["/v1/relationships"].post.requestBody.content["application/json"].schema).toMatchObject({
additionalProperties: true,
required: ["parent", "child"],
properties: {
parent: { type: "string", minLength: 1 },
child: { type: "string", minLength: 1 },
},
});
expect(openApiDocument.paths["/v1/entities/{entity}/rows"].post.requestBody.content["application/json"].schema).toMatchObject({
type: "object",
additionalProperties: true,
});
expect(openApiDocument.paths["/v1/entities/{entity}/rows/{rowId}"].patch.requestBody.content["application/json"].schema).toMatchObject({
type: "object",
additionalProperties: true,
});
expect(JSON.stringify(openApiDocument)).not.toMatch(/(?:sk|pk)_(?:live|test)_[A-Za-z0-9]+|jwt_secret|secret_[A-Za-z0-9]+|Bearer\s+[A-Za-z0-9._~+/-]{12,}/i);
});
@@ -402,7 +378,7 @@ describe("openApiDocument", () => {
expect(openApiDocument.paths["/v1/analytics/public"].get.security).toEqual([{ analyticsTokenHeader: [] }]);
});
test("documents service credential gates for export download and legacy entity detail endpoints", () => {
test("documents service credential gates for export download endpoints", () => {
const serviceCredentialOperations = [
["/v1/exports/{exportJobId}/download-url", "get"],
] as const;
@@ -433,20 +409,6 @@ describe("openApiDocument", () => {
});
expect(documentedOperation).not.toHaveProperty("x-api-key-permissions");
}
const entityDetailOperation = openApiDocument.paths["/v1/entities/{entity}"].get;
expect(entityDetailOperation.security).toEqual([{ bearerAuth: [] }]);
expect(entityDetailOperation.parameters).toEqual(
expect.arrayContaining([
expect.objectContaining({ name: "tenantId", in: "query", required: false }),
expect.objectContaining({ name: "x-tenant-id", in: "header", required: false }),
expect.objectContaining({ name: "x-account-id", in: "header", required: false }),
])
);
expect(entityDetailOperation.responses["401"]).toMatchObject({
headers: { "x-request-id": { schema: { type: "string" } } },
});
expect(entityDetailOperation).not.toHaveProperty("x-api-key-permissions");
});
test("documents notification SSE stream contract and redaction boundaries", () => {
@@ -457,8 +419,8 @@ describe("openApiDocument", () => {
description: expect.stringContaining("tenant/user scoped notification delivery diagnostics"),
security: [{ bearerAuth: [] }],
parameters: [
{ name: "x-toolctrl-tenant-id", in: "header", required: false, schema: { type: "string", minLength: 1 } },
{ name: "x-toolctrl-user-id", in: "header", required: false, schema: { type: "string", minLength: 1 } },
{ name: "x-hivegrid-tenant-id", in: "header", required: false, schema: { type: "string", minLength: 1 } },
{ name: "x-hivegrid-user-id", in: "header", required: false, schema: { type: "string", minLength: 1 } },
{ name: "tenantId", in: "query", required: false, deprecated: true, schema: { type: "string", minLength: 1 } },
{ name: "userId", in: "query", required: false, deprecated: true, schema: { type: "string", minLength: 1 } },
expect.objectContaining({
@@ -559,9 +521,38 @@ describe("openApiDocument", () => {
security: [{ apiKeyHeader: [] }],
});
expect(openApiDocument.paths["/v1/billing/stripe/webhooks"].post).toMatchObject({
operationId: "receiveStripeBillingWebhook",
security: [{ stripeWebhookSignature: [] }],
expect(openApiDocument.paths["/v1/contacts"].get).toMatchObject({
operationId: "listPublicApiContacts",
security: [{ apiKeyHeader: [] }],
parameters: expect.arrayContaining([
expect.objectContaining({ name: "x-api-key", in: "header", required: true }),
expect.objectContaining({ name: "limit", in: "query" }),
expect.objectContaining({ name: "cursor", in: "query" }),
expect.objectContaining({ name: "fields", in: "query" }),
]),
responses: {
"200": expect.objectContaining({
description: expect.stringContaining("contacts"),
}),
"400": expect.any(Object),
"401": expect.any(Object),
"402": expect.any(Object),
},
});
expect(openApiDocument.paths["/v1/leads"].get!.parameters).toEqual(
expect.arrayContaining([expect.objectContaining({ name: "embed", description: expect.stringContaining("leadSource") })]),
);
expect(openApiDocument.paths["/v1/billing/mollie/webhooks"].post).toMatchObject({
operationId: "receiveMollieBillingWebhook",
security: [],
requestBody: {
content: {
"application/x-www-form-urlencoded": {
schema: expect.objectContaining({ required: ["id"] }),
},
},
},
});
expect(openApiDocument.paths["/v1/email-sequences/mailjet/webhooks"].post).toMatchObject({
operationId: "receiveEmailSequenceMailjetWebhook",
@@ -861,7 +852,8 @@ describe("openApiDocument", () => {
"apiSessionBearer",
"bearerAuth",
"mailjetWebhookAuth",
"stripeWebhookSignature",
"webhookHmac",
"webhookTokenHeader",
]);
expect(openApiDocument.components.securitySchemes.bearerAuth).toMatchObject({
@@ -887,12 +879,6 @@ describe("openApiDocument", () => {
scheme: "basic",
description: expect.stringContaining("HTTP Basic-Auth"),
});
expect(openApiDocument.components.securitySchemes.stripeWebhookSignature).toMatchObject({
type: "apiKey",
in: "header",
name: "stripe-signature",
description: expect.stringContaining("Stripe webhook signature"),
});
expect(openApiDocument.components.securitySchemes.analyticsTokenHeader).toMatchObject({
type: "apiKey",
in: "header",
@@ -908,69 +894,7 @@ describe("openApiDocument", () => {
}
});
test("documents idempotency for protected mutating entity-row and relationship operations only", () => {
const idempotentOperations = [
["/v1/entities/{entity}/rows", "post"],
["/v1/entities/{entity}/rows/{rowId}", "patch"],
["/v1/entities/{entity}/rows/{rowId}", "delete"],
["/v1/relationships", "post"],
["/v1/relationships/{id}", "delete"],
] as const;
const conflictResponses = idempotentOperations.map(([path, method]) => {
const documentedOperation = (openApiDocument.paths[path] as unknown as Record<typeof method, { parameters: Array<Record<string, unknown>>; responses: Record<string, unknown>; "x-idempotency-key": unknown }>)[method];
expect(documentedOperation["x-idempotency-key"], `${path} ${method} should require an idempotency key`).toBe("required");
expect(documentedOperation.parameters).toContainEqual(
expect.objectContaining({
name: "Idempotency-Key",
in: "header",
required: true,
description: expect.stringContaining("Fingerprints are redacted"),
schema: { type: "string", minLength: 1 },
})
);
expect(documentedOperation.responses["409"], `${path} ${method} should document idempotency conflicts`).toMatchObject({
description: expect.stringContaining("different redacted request fingerprint"),
headers: { "x-request-id": { schema: { type: "string" } } },
content: {
"application/json": {
schema: {
properties: {
error: {
properties: {
code: { enum: ["idempotency_key_conflict"] },
message: { type: "string" },
requestId: { type: "string" },
},
required: ["code", "message", "requestId"],
},
},
required: ["error"],
},
},
},
});
expect(documentedOperation.responses["400"], `${path} ${method} should document missing idempotency keys`).toMatchObject({
content: {
"application/json": {
schema: {
properties: {
error: {
properties: {
code: { enum: expect.arrayContaining(["idempotency_key_required"]) },
},
},
},
},
},
},
});
return documentedOperation.responses["409"];
});
expect(new Set(conflictResponses).size).toBe(1);
expect(JSON.stringify(conflictResponses)).not.toMatch(/(?:sk|pk)_(?:live|test)_[A-Za-z0-9]+|secret_[A-Za-z0-9]+|Bearer\s+[A-Za-z0-9._~+/-]{12,}|x-api-key/i);
test("does not advertise idempotency for unsupported mutating operations", () => {
const unsupportedMutatingOperations = [
["/v1/auth/login", "post"],
["/v1/auth/refresh-token", "post"],
@@ -978,6 +902,7 @@ describe("openApiDocument", () => {
["/v1/ai/upload", "post"],
["/v1/support/inbound-email", "post"],
["/v1/email-sequences/mailjet/webhooks", "post"],
["/v1/billing/mollie/webhooks", "post"],
["/v1/analytics/events", "post"],
["/v1/analytics/page-views", "post"],
["/v1/events/webhooks/attempts/{id}", "post"],
@@ -990,39 +915,4 @@ describe("openApiDocument", () => {
expect(documentedOperation.parameters ?? []).not.toContainEqual(expect.objectContaining({ name: "Idempotency-Key" }));
}
});
test("documents scoped API-key operation permissions", () => {
const scopedOperations = [
["/v1/entities/{entity}/rows", "get", "read"],
["/v1/entities/{entity}/rows", "post", "create"],
["/v1/entities/{entity}/rows/{rowId}", "get", "read"],
["/v1/entities/{entity}/rows/{rowId}", "patch", "update"],
["/v1/entities/{entity}/rows/{rowId}", "delete", "delete"],
["/v1/relationships", "post", "create"],
["/v1/relationships/{id}", "get", "read"],
["/v1/relationships/{id}", "delete", "delete"],
] as const;
for (const [path, method, operation] of scopedOperations) {
const documentedOperation = (openApiDocument.paths[path] as unknown as Record<typeof method, { security: unknown; responses: Record<string, unknown>; "x-api-key-permissions": { entityPermissions?: Array<{ entity: unknown; operation: unknown }>; [key: string]: unknown } }>)[method];
expect(documentedOperation.security).toEqual([{ bearerAuth: [] }, { apiKeyHeader: [] }]);
expect(documentedOperation.responses).toHaveProperty("403");
expect(documentedOperation["x-api-key-permissions"]).toMatchObject({
credential: "apiKeyHeader",
tenant: { source: "query", name: "tenantId" },
});
if (path.startsWith("/v1/entities")) {
expect(documentedOperation["x-api-key-permissions"]).toMatchObject({
entity: { source: "path", name: "entity" },
operation,
});
} else {
expect(documentedOperation["x-api-key-permissions"].entityPermissions).toEqual([
{ entity: { source: "relationship.parentEntity" }, operation },
{ entity: { source: "relationship.childEntity" }, operation },
]);
}
}
});
});
File diff suppressed because it is too large. Load diff
@@ -55,8 +55,8 @@ describe("parseOtlpHeaders", () => {
});
describe("readApiOtelConfig", () => {
it("defaults service.name to boilerplate-api", () => {
expect(readApiOtelConfig({}).serviceName).toBe("boilerplate-api");
it("defaults service.name to hivegrid-api", () => {
expect(readApiOtelConfig({}).serviceName).toBe("hivegrid-api");
});
it("respects OTEL_SERVICE_NAME override", () => {
@@ -102,7 +102,7 @@ describe("initApiOtel", () => {
serviceVersion: undefined,
serviceInstanceId: "test-1",
deploymentEnvironment: undefined,
serviceNamespace: "toolctrl",
serviceNamespace: "hivegrid",
tracesSamplerArg: 0,
debug: false,
});
@@ -30,7 +30,7 @@ import { resourceFromAttributes } from "@opentelemetry/resources";
import { NodeSDK } from "@opentelemetry/sdk-node";
import { BatchSpanProcessor, ParentBasedSampler, TraceIdRatioBasedSampler } from "@opentelemetry/sdk-trace-base";
import { ATTR_SERVICE_NAME, ATTR_SERVICE_VERSION } from "@opentelemetry/semantic-conventions";
import { PIISpanProcessor } from "@toolctrl/observability";
import { PIISpanProcessor } from "@hivegrid/observability";
export interface ApiOtelConfig {
endpoint: string | undefined;
@@ -44,8 +44,8 @@ export interface ApiOtelConfig {
debug: boolean;
}
const DEFAULT_SERVICE_NAME = "boilerplate-api";
const DEFAULT_SERVICE_NAMESPACE = "toolctrl";
const DEFAULT_SERVICE_NAME = "hivegrid-api";
const DEFAULT_SERVICE_NAMESPACE = "hivegrid";
const DEFAULT_TRACES_SAMPLER_ARG = 0.1;
/**
@@ -1,142 +0,0 @@
import { describe, expect, test } from "vitest";
import { API_KEY_SCOPE_OPERATIONS } from "./auth/scope.js";
import { openApiDocument } from "./openapi.js";
const scopedPermissionMatrix = [
{ path: "/v1/entities/{entity}/rows", method: "get", operation: "read" },
{ path: "/v1/entities/{entity}/rows", method: "post", operation: "create" },
{ path: "/v1/entities/{entity}/rows/{rowId}", method: "get", operation: "read" },
{ path: "/v1/entities/{entity}/rows/{rowId}", method: "patch", operation: "update" },
{ path: "/v1/entities/{entity}/rows/{rowId}", method: "delete", operation: "delete" },
{ path: "/v1/relationships", method: "post", operation: "create" },
{ path: "/v1/relationships/{id}", method: "get", operation: "read" },
{ path: "/v1/relationships/{id}", method: "delete", operation: "delete" },
] as const;
const unscopedPublicOrLegacyPaths = [
"/healthz",
"/readyz",
"/v1/api-keys/validate",
"/v1/analytics/public",
] as const;
const serviceCredentialMatrix = [
{ path: "/v1/exports/{exportJobId}/download-url", method: "get" },
] as const;
const serviceTokenOnlyMatrix = [
{ path: "/v1/entities/{entity}", method: "get" },
] as const;
const expectedSecurity = [{ bearerAuth: [] }, { apiKeyHeader: [] }];
const expectedServiceTokenOnlySecurity = [{ bearerAuth: [] }];
const expectedRuntimeCrudOperations = ["read", "create", "update", "delete"] as const;
type OpenApiPath = keyof typeof openApiDocument.paths;
type ScopedMatrixEntry = (typeof scopedPermissionMatrix)[number];
type ServiceCredentialMatrixEntry = (typeof serviceCredentialMatrix)[number] | (typeof serviceTokenOnlyMatrix)[number];
type DocumentedOperation = {
security?: unknown;
responses?: Record<string, unknown>;
"x-api-key-permissions"?: {
operation?: unknown;
entityPermissions?: Array<{ operation?: unknown }>;
};
};
function getDocumentedOperation({ path, method }: ScopedMatrixEntry | ServiceCredentialMatrixEntry): DocumentedOperation {
const pathItem = openApiDocument.paths[path];
expect(pathItem, `${path} must exist in openApiDocument.paths`).toBeDefined();
const operation = (pathItem as Record<typeof method, unknown>)[method];
expect(operation, `${method.toUpperCase()} ${path} must exist in openApiDocument.paths`).toBeDefined();
return operation as DocumentedOperation;
}
function collectPermissionOperations(permission: NonNullable<DocumentedOperation["x-api-key-permissions"]>) {
const operations = new Set<unknown>();
if (permission.operation !== undefined) {
operations.add(permission.operation);
}
for (const entityPermission of permission.entityPermissions ?? []) {
operations.add(entityPermission.operation);
}
return [...operations];
}
describe("scoped API-key permission matrix", () => {
test.each(scopedPermissionMatrix)("documents $method $path as requiring $operation scope", (entry) => {
const operation = getDocumentedOperation(entry);
expect(operation.security).toEqual(expectedSecurity);
expect(operation.responses).toHaveProperty("403");
expect(operation["x-api-key-permissions"], `${entry.method.toUpperCase()} ${entry.path} must document API-key permissions`).toBeDefined();
const permission = operation["x-api-key-permissions"];
expect(permission?.operation ?? permission?.entityPermissions?.[0]?.operation).toBe(entry.operation);
expect(collectPermissionOperations(permission ?? {})).toEqual([entry.operation]);
});
test("uses only supported scope operations and represents every runtime CRUD operation", () => {
const supportedOperations = new Set<string>(API_KEY_SCOPE_OPERATIONS);
const documentedOperations = new Set<string>();
for (const entry of scopedPermissionMatrix) {
const permission = getDocumentedOperation(entry)["x-api-key-permissions"];
expect(permission).toBeDefined();
for (const operation of collectPermissionOperations(permission ?? {})) {
expect(typeof operation, `${entry.method.toUpperCase()} ${entry.path} operation must be a string`).toBe("string");
expect(supportedOperations.has(operation as string), `${entry.method.toUpperCase()} ${entry.path} uses unsupported operation ${String(operation)}`).toBe(true);
documentedOperations.add(operation as string);
}
}
expect([...documentedOperations].sort()).toEqual([...expectedRuntimeCrudOperations].sort());
expect([...documentedOperations].sort()).toEqual([...API_KEY_SCOPE_OPERATIONS].sort());
});
test("covers exactly the scoped OpenAPI operations that publish API-key permissions", () => {
const expectedEntries = scopedPermissionMatrix.map(({ method, path }) => `${method.toUpperCase()} ${path}`).sort();
const documentedEntries = Object.entries(openApiDocument.paths)
.flatMap(([path, pathItem]) =>
Object.entries(pathItem)
.filter(([, operation]) => typeof operation === "object" && operation !== null && "x-api-key-permissions" in operation)
.map(([method]) => `${method.toUpperCase()} ${path}`)
)
.sort();
expect(documentedEntries).toEqual(expectedEntries);
});
test.each(unscopedPublicOrLegacyPaths)("keeps %s out of the scoped permission matrix", (path) => {
const scopedMatrixPaths = new Set<OpenApiPath>(scopedPermissionMatrix.map((entry) => entry.path));
expect(scopedMatrixPaths.has(path)).toBe(false);
const pathItem = openApiDocument.paths[path];
expect(pathItem, `${path} should remain documented as an unscoped public endpoint`).toBeDefined();
expect(Object.values(pathItem).some((operation) => typeof operation === "object" && operation !== null && "x-api-key-permissions" in operation)).toBe(false);
});
test.each(serviceCredentialMatrix)("documents $method $path as service-credential protected but not CRUD scoped", (entry) => {
const scopedMatrixPaths = new Set<OpenApiPath>(scopedPermissionMatrix.map(({ path }) => path));
expect(scopedMatrixPaths.has(entry.path)).toBe(false);
const operation = getDocumentedOperation(entry);
expect(operation.security).toEqual(expectedSecurity);
expect(operation.responses).toHaveProperty("401");
expect(operation["x-api-key-permissions"], `${entry.method.toUpperCase()} ${entry.path} must not publish CRUD scope claims`).toBeUndefined();
});
test.each(serviceTokenOnlyMatrix)("documents $method $path as bearer service-token protected but not CRUD scoped", (entry) => {
const scopedMatrixPaths = new Set<OpenApiPath>(scopedPermissionMatrix.map(({ path }) => path));
expect(scopedMatrixPaths.has(entry.path)).toBe(false);
const operation = getDocumentedOperation(entry);
expect(operation.security).toEqual(expectedServiceTokenOnlySecurity);
expect(operation.responses).toHaveProperty("401");
expect(operation["x-api-key-permissions"], `${entry.method.toUpperCase()} ${entry.path} must not publish CRUD scope claims`).toBeUndefined();
});
});
@@ -26,8 +26,8 @@ describe("API maintenance middleware", () => {
test("parses enabled and retry-after config from safe env values", () => {
expect(
getApiMaintenanceConfig({
TOOLCTRL_API_MAINTENANCE_MODE: "1",
TOOLCTRL_API_MAINTENANCE_RETRY_AFTER_SECONDS: "120",
HIVEGRID_API_MAINTENANCE_MODE: "1",
HIVEGRID_API_MAINTENANCE_RETRY_AFTER_SECONDS: "120",
})
).toEqual({ enabled: true, retryAfterSeconds: 120 });
});
@@ -35,15 +35,15 @@ describe("API maintenance middleware", () => {
test("ignores disabled flags and invalid retry-after values", () => {
expect(
getApiMaintenanceConfig({
TOOLCTRL_API_MAINTENANCE_MODE: "true",
TOOLCTRL_API_MAINTENANCE_RETRY_AFTER_SECONDS: "postgres://user:secret@db.local/app",
HIVEGRID_API_MAINTENANCE_MODE: "true",
HIVEGRID_API_MAINTENANCE_RETRY_AFTER_SECONDS: "postgres://user:secret@db.local/app",
})
).toEqual({ enabled: false, retryAfterSeconds: undefined });
expect(
getApiMaintenanceConfig({
TOOLCTRL_API_MAINTENANCE_MODE: "1",
TOOLCTRL_API_MAINTENANCE_RETRY_AFTER_SECONDS: "1.5",
HIVEGRID_API_MAINTENANCE_MODE: "1",
HIVEGRID_API_MAINTENANCE_RETRY_AFTER_SECONDS: "1.5",
})
).toEqual({ enabled: true, retryAfterSeconds: undefined });
});
@@ -1,8 +1,8 @@
import type { MiddlewareHandler } from "hono";
import type { ApiRequestIdVariables } from "../../middleware/request-id.js";
const MAINTENANCE_MODE_ENV = "TOOLCTRL_API_MAINTENANCE_MODE";
const RETRY_AFTER_ENV = "TOOLCTRL_API_MAINTENANCE_RETRY_AFTER_SECONDS";
const MAINTENANCE_MODE_ENV = "HIVEGRID_API_MAINTENANCE_MODE";
const RETRY_AFTER_ENV = "HIVEGRID_API_MAINTENANCE_RETRY_AFTER_SECONDS";
const MAINTENANCE_MESSAGE = "The API is temporarily unavailable for maintenance. Please retry later.";
const EXEMPT_PATHS = new Set(["/healthz", "/readyz", "/v1/openapi.json", "/v1/docs"]);
@@ -0,0 +1,117 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { PLUGIN_HOOK_ENTITY_CREATED } from "@hivegrid/plugin-runtime";
// The entity-row hook test mocks this module out entirely; here we exercise the
// REAL `emitPluginHookFireAndForget` and only stub the @hivegrid/db seams so the
// transaction/outbox plumbing and both error branches run without a database.
const { getDbClientMock, publishOutboxEventMock } = vi.hoisted(() => ({
getDbClientMock: vi.fn(),
publishOutboxEventMock: vi.fn(),
}));
vi.mock("@hivegrid/db/client.server", () => ({
getDbClient: getDbClientMock,
}));
vi.mock("@hivegrid/db/outbox", () => ({
publishOutboxEvent: publishOutboxEventMock,
}));
const { emitPluginHookFireAndForget } = await import("./plugin-hook-publisher.js");
const TX_SENTINEL = { __tx: true } as const;
/** Default happy-path db: $transaction runs the callback against a sentinel tx. */
function installRunningTransaction() {
getDbClientMock.mockReturnValue({
$transaction: async (runner: (tx: unknown) => Promise<unknown>) => runner(TX_SENTINEL),
});
}
const VALID_PAYLOAD = {
entityType: "contact",
entityId: "row_1",
tenantId: "tenant_1",
userId: null as string | null,
occurredAt: "2026-01-01T00:00:00.000Z",
};
beforeEach(() => {
publishOutboxEventMock.mockReset();
publishOutboxEventMock.mockResolvedValue(undefined);
getDbClientMock.mockReset();
});
afterEach(() => {
vi.clearAllMocks();
});
describe("emitPluginHookFireAndForget", () => {
test("publishes a validated payload to the outbox inside a transaction", async () => {
installRunningTransaction();
await emitPluginHookFireAndForget(PLUGIN_HOOK_ENTITY_CREATED, VALID_PAYLOAD, {
tenantId: "tenant_1",
dispatchKey: "entity:contact:row_1:created",
});
expect(publishOutboxEventMock).toHaveBeenCalledTimes(1);
expect(publishOutboxEventMock).toHaveBeenCalledWith(
TX_SENTINEL,
expect.objectContaining({
tenantId: "tenant_1",
// emitPluginHook maps the definition to its outbox event type.
type: "plugin.hook.entity.created",
dispatchKey: "entity:contact:row_1:created",
payload: expect.objectContaining({ entityType: "contact", entityId: "row_1" }),
}),
);
});
test("defaults tenantId and dispatchKey to null when no options are supplied", async () => {
installRunningTransaction();
await emitPluginHookFireAndForget(PLUGIN_HOOK_ENTITY_CREATED, VALID_PAYLOAD);
expect(publishOutboxEventMock).toHaveBeenCalledWith(
TX_SENTINEL,
expect.objectContaining({ tenantId: null, dispatchKey: null }),
);
});
test("swallows validation errors and never publishes an invalid payload", async () => {
installRunningTransaction();
// Missing required fields => PluginHookValidationError inside emitPluginHook.
await expect(
emitPluginHookFireAndForget(PLUGIN_HOOK_ENTITY_CREATED, { entityType: "contact" } as never, {
tenantId: "tenant_1",
}),
).resolves.toBeUndefined();
expect(publishOutboxEventMock).not.toHaveBeenCalled();
});
test("swallows outbox publish failures (fire-and-forget never rejects)", async () => {
installRunningTransaction();
publishOutboxEventMock.mockRejectedValue(new Error("outbox unreachable"));
await expect(
emitPluginHookFireAndForget(PLUGIN_HOOK_ENTITY_CREATED, VALID_PAYLOAD, { tenantId: "tenant_1" }),
).resolves.toBeUndefined();
expect(publishOutboxEventMock).toHaveBeenCalledTimes(1);
});
test("swallows transaction/database failures without publishing", async () => {
getDbClientMock.mockReturnValue({
$transaction: vi.fn().mockRejectedValue(new Error("Can't reach database server")),
});
await expect(
emitPluginHookFireAndForget(PLUGIN_HOOK_ENTITY_CREATED, VALID_PAYLOAD, { tenantId: "tenant_1" }),
).resolves.toBeUndefined();
expect(publishOutboxEventMock).not.toHaveBeenCalled();
});
});
@@ -1,6 +1,6 @@
import { getDbClient } from "@toolctrl/db/client.server";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@toolctrl/db/outbox";
import { emitPluginHook, PluginHookValidationError, type PluginHookDefinition } from "@toolctrl/plugin-runtime";
import { getDbClient } from "@hivegrid/db/client.server";
import { publishOutboxEvent, type OutboxPublisherTransaction } from "@hivegrid/db/outbox";
import { emitPluginHook, PluginHookValidationError, type PluginHookDefinition } from "@hivegrid/plugin-runtime";
import { apiLogger } from "./logger.js";
const pluginHookLogger = apiLogger.child?.({ component: "plugin-hook-publisher" }) ?? apiLogger;
@@ -0,0 +1,61 @@
import { MemoryAdapter, createSharedStore } from "@hivegrid/shared-store";
import { afterEach, describe, expect, test } from "vitest";
import {
PUBLIC_API_KEY_RATE_LIMIT_PER_HOUR,
__resetPublicApiRateLimitStoreForTests,
__setPublicApiRateLimitStoreForTests,
checkPublicApiRateLimit,
checkPublicApiScopes,
publicApiReadScopeForResource,
} from "./auth.js";
describe("public API auth", () => {
afterEach(() => {
__resetPublicApiRateLimitStoreForTests();
});
test("accepts wildcard, legacy read and resource scopes but rejects missing webhook scopes", () => {
expect(checkPublicApiScopes(["*"], ["public_api:webhooks:incoming"]).ok).toBe(true);
expect(checkPublicApiScopes(["public_api:read"], [publicApiReadScopeForResource("contacts")]).ok).toBe(true);
expect(checkPublicApiScopes(["public_api:read:contacts"], [publicApiReadScopeForResource("contacts")]).ok).toBe(true);
const result = checkPublicApiScopes(["public_api:read"], ["public_api:webhooks:incoming"]);
expect(result).toEqual({
ok: false,
status: 403,
code: "insufficient_scope",
message: "API key scope does not allow this operation.",
requiredScopes: ["public_api:webhooks:incoming"],
});
});
test("enforces the per-key fixed-window limit and emits public rate-limit headers", async () => {
const store = createSharedStore({ namespace: "public-api-auth-test", adapter: new MemoryAdapter() });
__setPublicApiRateLimitStoreForTests(store);
let result = await checkPublicApiRateLimit({ apiKeyId: "api_key_1", tenantId: "tenant_1" });
expect(result.allowed).toBe(true);
expect(result.headers).toMatchObject({
"X-RateLimit-Limit": "1000",
"X-RateLimit-Remaining": "999",
"X-RateLimit-Scope": "combined",
});
for (let index = 1; index < PUBLIC_API_KEY_RATE_LIMIT_PER_HOUR; index += 1) {
result = await checkPublicApiRateLimit({ apiKeyId: "api_key_1", tenantId: "tenant_1" });
}
const blocked = await checkPublicApiRateLimit({ apiKeyId: "api_key_1", tenantId: "tenant_1" });
expect(blocked).toMatchObject({
allowed: false,
status: 429,
code: "rate_limit_exceeded",
headers: {
"X-RateLimit-Limit": "1000",
"X-RateLimit-Remaining": "0",
"X-RateLimit-Scope": "key",
},
});
});
});
@@ -0,0 +1,178 @@
import { createFixedWindowRateLimiter, type FixedWindowDecision, type FixedWindowRateLimiter, type SharedStore } from "@hivegrid/shared-store";
import { getSharedStore } from "../shared-store.js";
export const PUBLIC_API_KEY_RATE_LIMIT_PER_HOUR = 1_000;
export const PUBLIC_API_TENANT_RATE_LIMIT_PER_HOUR = 10_000;
export const PUBLIC_API_RATE_LIMIT_WINDOW_SECONDS = 60 * 60;
export const PUBLIC_API_LEGACY_READ_SCOPE = "public_api:read";
export const PUBLIC_API_WILDCARD_SCOPE = "*";
export type PublicApiReadScope =
| "public_api:read:contacts"
| "public_api:read:companies"
| "public_api:read:deals"
| "public_api:read:projects"
| "public_api:read:tasks"
| "public_api:read:leads";
export type PublicApiWebhookScope = "public_api:webhooks:incoming" | "public_api:webhooks:outgoing" | "public_api:webhooks:manage";
export type PublicApiScope = typeof PUBLIC_API_WILDCARD_SCOPE | typeof PUBLIC_API_LEGACY_READ_SCOPE | PublicApiReadScope | PublicApiWebhookScope;
export type PublicApiScopeCheck =
| { ok: true }
| {
ok: false;
status: 403;
code: "insufficient_scope";
message: string;
requiredScopes: readonly PublicApiScope[];
};
export type PublicApiRateLimitAllowed = {
allowed: true;
headers: Record<string, string>;
};
export type PublicApiRateLimitBlocked = {
allowed: false;
status: 429;
code: "rate_limit_exceeded";
message: string;
headers: Record<string, string>;
};
export type PublicApiRateLimitResult = PublicApiRateLimitAllowed | PublicApiRateLimitBlocked;
type Limiters = {
key: FixedWindowRateLimiter;
tenant: FixedWindowRateLimiter;
store: SharedStore;
};
let limiters: Limiters | null = null;
let storeFactory: () => SharedStore = () => getSharedStore();
function getPublicApiLimiters(): Limiters {
if (limiters) {
return limiters;
}
const store = storeFactory();
limiters = {
store,
key: createFixedWindowRateLimiter({
store,
prefix: "public-api:key",
windowSeconds: PUBLIC_API_RATE_LIMIT_WINDOW_SECONDS,
max: PUBLIC_API_KEY_RATE_LIMIT_PER_HOUR,
}),
tenant: createFixedWindowRateLimiter({
store,
prefix: "public-api:tenant",
windowSeconds: PUBLIC_API_RATE_LIMIT_WINDOW_SECONDS,
max: PUBLIC_API_TENANT_RATE_LIMIT_PER_HOUR,
}),
};
return limiters;
}
export function normalizePublicApiScopes(value: unknown): readonly PublicApiScope[] {
if (!Array.isArray(value)) {
return [];
}
const scopes = value.filter((scope): scope is string => typeof scope === "string").map((scope) => scope.trim()).filter(Boolean);
return [...new Set(scopes)] as PublicApiScope[];
}
export function publicApiReadScopeForResource(resource: string): PublicApiReadScope {
return `public_api:read:${resource}` as PublicApiReadScope;
}
export function checkPublicApiScopes(grantedValue: unknown, requiredScopes: readonly PublicApiScope[]): PublicApiScopeCheck {
const granted = normalizePublicApiScopes(grantedValue);
if (
granted.includes(PUBLIC_API_WILDCARD_SCOPE) ||
requiredScopes.some((scope) => granted.includes(scope)) ||
(requiredScopes.some((scope) => scope.startsWith("public_api:read:")) && granted.includes(PUBLIC_API_LEGACY_READ_SCOPE))
) {
return { ok: true };
}
return {
ok: false,
status: 403,
code: "insufficient_scope",
message: "API key scope does not allow this operation.",
requiredScopes,
};
}
export async function checkPublicApiRateLimit(input: { apiKeyId: string; tenantId: string }): Promise<PublicApiRateLimitResult> {
const { key, tenant } = getPublicApiLimiters();
const [keyDecision, tenantDecision] = await Promise.all([key.consume(input.apiKeyId), tenant.consume(input.tenantId)]);
const blockedScope = !keyDecision.allowed ? "key" : !tenantDecision.allowed ? "tenant" : null;
const decision = blockedScope === "key" ? keyDecision : tenantDecision;
const limit = blockedScope === "key" ? PUBLIC_API_KEY_RATE_LIMIT_PER_HOUR : blockedScope === "tenant" ? PUBLIC_API_TENANT_RATE_LIMIT_PER_HOUR : Math.min(PUBLIC_API_KEY_RATE_LIMIT_PER_HOUR, PUBLIC_API_TENANT_RATE_LIMIT_PER_HOUR);
const headers = createRateLimitHeaders({
limit,
remaining: Math.min(keyDecision.remaining, tenantDecision.remaining),
resetAt: laterResetAt(keyDecision, tenantDecision),
scope: blockedScope ?? "combined",
});
if (blockedScope && decision) {
return {
allowed: false,
status: 429,
code: "rate_limit_exceeded",
message: `Public API ${blockedScope} rate limit exceeded. Try again after the reset time.`,
headers,
};
}
return { allowed: true, headers };
}
export async function resetPublicApiRateLimiterForTests(): Promise<void> {
const previous = limiters;
limiters = null;
if (!previous) {
return;
}
try {
for await (const fullKey of previous.store.adapter.scan(`shared-store:${previous.store.namespace}:rl:fixed:public-api:*`)) {
const prefix = `shared-store:${previous.store.namespace}:`;
if (fullKey.startsWith(prefix)) {
await previous.store.del(fullKey.slice(prefix.length));
}
}
} catch {
// Best-effort; isolated tests can inject a fresh store.
}
}
export function __setPublicApiRateLimitStoreForTests(store: SharedStore): void {
limiters = null;
storeFactory = () => store;
}
export function __resetPublicApiRateLimitStoreForTests(): void {
limiters = null;
storeFactory = () => getSharedStore();
}
function createRateLimitHeaders(input: { limit: number; remaining: number; resetAt: Date; scope: string }): Record<string, string> {
return {
"X-RateLimit-Limit": String(input.limit),
"X-RateLimit-Remaining": String(Math.max(0, input.remaining)),
"X-RateLimit-Reset": String(Math.ceil(input.resetAt.getTime() / 1000)),
"X-RateLimit-Scope": input.scope,
};
}
function laterResetAt(a: FixedWindowDecision, b: FixedWindowDecision): Date {
return a.resetAt.getTime() >= b.resetAt.getTime() ? a.resetAt : b.resetAt;
}
@@ -0,0 +1,303 @@
import { PUBLIC_API_DEFAULT_LIMIT, PUBLIC_API_MAX_LIMIT, PUBLIC_API_RESOURCE_NAMES, publicApiResources } from "./resources.js";
const requestIdHeader = {
description: "Request correlation identifier echoed from the request or generated by the API.",
schema: { type: "string" },
} as const;
const apiErrorResponse = (description: string, codes: string[]) => ({
description,
headers: { "x-request-id": requestIdHeader },
content: {
"application/json": {
schema: {
type: "object",
properties: {
error: {
type: "object",
properties: {
code: { type: "string", enum: codes },
message: { type: "string" },
params: { type: "object", additionalProperties: true },
requestId: { type: "string" },
},
required: ["code", "message", "requestId"],
},
},
required: ["error"],
},
},
},
});
type PublicApiOpenApiPathItem = {
get?: Record<string, unknown>;
post?: Record<string, unknown>;
};
const publicApiReadOpenApiPaths = Object.fromEntries(
PUBLIC_API_RESOURCE_NAMES.map((resourceName) => {
const resource = publicApiResources[resourceName];
return [
`/v1/${resource.name}`,
{
get: {
operationId: `listPublicApi${capitalize(resource.name)}`,
description: `${resource.description} Cursor-paginated, tenant-scoped and read-only. Sensitive fields are omitted instead of returning 403 for individual fields.`,
security: [{ apiKeyHeader: [] }],
parameters: [
{
name: "x-api-key",
in: "header",
required: true,
description: "Tenant-bound API key. The key determines tenant scope; callers must not pass tenant ids in the URL.",
schema: { type: "string", minLength: 1 },
},
{
name: "limit",
in: "query",
required: false,
description: `Page size. Defaults to ${PUBLIC_API_DEFAULT_LIMIT}; maximum ${PUBLIC_API_MAX_LIMIT}.`,
schema: { type: "integer", minimum: 1, maximum: PUBLIC_API_MAX_LIMIT, default: PUBLIC_API_DEFAULT_LIMIT },
},
{
name: "cursor",
in: "query",
required: false,
description: "Opaque cursor returned as pageInfo.nextCursor.",
schema: { type: "string" },
},
{
name: "sort",
in: "query",
required: false,
description: "Stable cursor sort.",
schema: { type: "string", enum: ["createdAt.desc", "createdAt.asc", "updatedAt.desc", "updatedAt.asc"], default: "createdAt.desc" },
},
{
name: "fields",
in: "query",
required: false,
description: `Sparse fieldset. Supported fields: ${resource.fields.join(", ")}. The id field is always included.`,
schema: { type: "string" },
},
{
name: "embed",
in: "query",
required: false,
description: resource.embeds.length ? `Comma-separated depth-1 embeds. Supported embeds: ${resource.embeds.join(", ")}.` : "No embeds are currently supported for this resource.",
schema: { type: "string" },
},
{
name: "q",
in: "query",
required: false,
description: "Case-insensitive text filter over the resource's primary display/search fields.",
schema: { type: "string" },
},
{
name: "status",
in: "query",
required: false,
description: resource.statusValues ? `Status filter. Supported values: ${resource.statusValues.join(", ")}.` : "Ignored for resources without status.",
schema: resource.statusValues ? { type: "string", enum: resource.statusValues } : { type: "string" },
},
{
name: "ownerUserId",
in: "query",
required: false,
description: "Owner/assignee filter where the resource has an owner-like field.",
schema: { type: "string" },
},
{
name: "createdSince",
in: "query",
required: false,
description: "Inclusive ISO date-time lower bound for createdAt.",
schema: { type: "string", format: "date-time" },
},
{
name: "updatedSince",
in: "query",
required: false,
description: "Inclusive ISO date-time lower bound for updatedAt.",
schema: { type: "string", format: "date-time" },
},
],
responses: {
"200": {
description: `Cursor-paginated ${resource.name} page.`,
headers: { "x-request-id": requestIdHeader },
content: {
"application/json": {
schema: {
type: "object",
properties: {
data: {
type: "array",
items: {
type: "object",
additionalProperties: true,
properties: Object.fromEntries(resource.fields.map((field) => [field, { oneOf: [{ type: "string" }, { type: "number" }, { type: "boolean" }, { type: "null" }] }])),
},
},
pageInfo: {
type: "object",
properties: {
limit: { type: "integer", minimum: 1, maximum: PUBLIC_API_MAX_LIMIT },
nextCursor: { type: ["string", "null"] },
sort: { type: "string" },
},
required: ["limit", "nextCursor", "sort"],
},
meta: {
type: "object",
properties: {
resource: { type: "string", enum: [resource.name] },
readOnly: { type: "boolean", const: true },
requestId: { type: "string" },
},
required: ["resource", "readOnly", "requestId"],
},
},
required: ["data", "pageInfo", "meta"],
},
},
},
},
"400": apiErrorResponse("Invalid list query.", ["invalid_limit", "invalid_cursor", "invalid_sort", "invalid_fields", "invalid_embed", "invalid_status", "invalid_created_since", "invalid_updated_since"]),
"401": apiErrorResponse("Missing or invalid API key.", ["unauthorized"]),
"402": apiErrorResponse("API usage is disabled or exhausted for the tenant plan.", ["payment_required"]),
"403": apiErrorResponse("Tenant is inactive or the API key scope does not allow this operation.", ["tenant_inactive", "insufficient_scope"]),
"429": apiErrorResponse("Hourly key or tenant rate limit exceeded.", ["rate_limit_exceeded"]),
"500": apiErrorResponse("Read request failed with a redacted request-ID-correlated envelope.", ["public_api_read_failed"]),
},
},
},
];
}),
) as unknown as Record<`/v1/${(typeof PUBLIC_API_RESOURCE_NAMES)[number]}`, PublicApiOpenApiPathItem>;
export const publicApiOpenApiPaths = {
...publicApiReadOpenApiPaths,
"/v1/webhooks/incoming/{tenant}/{slug}": {
post: {
operationId: "receivePublicApiIncomingWebhook",
description:
"Tenant-scoped incoming lead webhook. The endpoint authenticates by the endpoint's configured mode: API key, HMAC token/signature, or URL/header token. Successful requests create an InboxLead and queue webhook.received automation executions.",
security: [{ apiKeyHeader: [] }, { webhookTokenHeader: [] }, { webhookHmac: [] }],
parameters: [
{
name: "tenant",
in: "path",
required: true,
description: "Tenant id or slug addressed by the incoming webhook endpoint.",
schema: { type: "string", minLength: 1 },
},
{
name: "slug",
in: "path",
required: true,
description: "Tenant-local incoming webhook endpoint slug.",
schema: { type: "string", minLength: 1 },
},
{
name: "x-api-key",
in: "header",
required: false,
description: "Required when the endpoint auth mode is api_key. The key must include public_api:webhooks:incoming, public_api:read legacy scope does not grant writes.",
schema: { type: "string" },
},
{
name: "X-HiveGrid-Webhook-Token",
in: "header",
required: false,
description: "Required for hmac and url_token endpoint modes. For hmac, this presented token is also the HMAC key and is validated against the stored hash.",
schema: { type: "string" },
},
{
name: "X-HiveGrid-Timestamp",
in: "header",
required: false,
description: "Unix timestamp used in the HMAC signing input '<timestamp>.<rawBody>'. Required for hmac endpoint mode.",
schema: { type: "string" },
},
{
name: "X-HiveGrid-Signature",
in: "header",
required: false,
description: "HMAC-SHA256 signature in the form sha256=<hex>. Required for hmac endpoint mode.",
schema: { type: "string" },
},
{
name: "token",
in: "query",
required: false,
description: "Alternative token transport for url_token endpoints.",
schema: { type: "string" },
},
],
requestBody: {
required: true,
content: {
"application/json": {
schema: {
type: "object",
additionalProperties: true,
description: "Lead payload. Payload mapping on the endpoint selects fields such as email, phone, firstName, lastName and message.",
},
},
},
},
responses: {
"201": {
description: "Lead webhook accepted and persisted.",
headers: {
"x-request-id": requestIdHeader,
"X-RateLimit-Limit": { schema: { type: "string" } },
"X-RateLimit-Remaining": { schema: { type: "string" } },
"X-RateLimit-Reset": { schema: { type: "string" } },
},
content: {
"application/json": {
schema: {
type: "object",
properties: {
data: {
type: "object",
properties: {
leadId: { type: "string" },
matchedKontaktId: { type: ["string", "null"] },
automationExecutionIds: { type: "array", items: { type: "string" } },
},
required: ["leadId", "matchedKontaktId", "automationExecutionIds"],
},
meta: {
type: "object",
properties: {
requestId: { type: "string" },
endpoint: { type: "string" },
},
required: ["requestId", "endpoint"],
},
},
required: ["data", "meta"],
},
},
},
},
"400": apiErrorResponse("Invalid JSON webhook payload.", ["invalid_json"]),
"401": apiErrorResponse("Missing or invalid webhook credentials.", ["unauthorized"]),
"402": apiErrorResponse("Tenant plan or billing state blocks webhook writes.", ["payment_required"]),
"403": apiErrorResponse("API key scope does not allow incoming webhooks.", ["insufficient_scope"]),
"404": apiErrorResponse("Tenant or incoming webhook endpoint was not found.", ["not_found"]),
"429": apiErrorResponse("Hourly key or tenant rate limit exceeded.", ["rate_limit_exceeded"]),
"500": apiErrorResponse("Webhook ingestion failed with a redacted request-ID-correlated envelope.", ["webhook_ingestion_failed"]),
},
},
},
} satisfies Record<string, PublicApiOpenApiPathItem>;
function capitalize(value: string) {
return value.charAt(0).toUpperCase() + value.slice(1);
}
@@ -0,0 +1,469 @@
import { getDbClient } from "@hivegrid/db/client.server";
import type { Prisma } from "@hivegrid/db/prisma-browser";
import {
applySparseFields,
publicApiResources,
serializePublicApiCursor,
type PublicApiListInput,
type PublicApiListQuery,
type PublicApiListResult,
type PublicApiResourceName,
} from "./resources.js";
type TenantRlsClient = Prisma.TransactionClient;
type SortableRow = { id: string; createdAt: Date; updatedAt?: Date };
export async function listPublicApiResource(input: PublicApiListInput): Promise<PublicApiListResult> {
if (!input.tenantId) {
throw new Error("listPublicApiResource requires a tenantId");
}
return withApiTenantRLS(input.tenantId, (tx) => listPublicApiResourceWithTx(tx, input));
}
async function withApiTenantRLS<T>(tenantId: string, callback: (tx: TenantRlsClient) => Promise<T>): Promise<T> {
const db = getDbClient();
return db.$transaction(async (tx) => {
await tx.$executeRaw`SELECT set_config('app.tenant_id', ${tenantId}, true)`;
return callback(tx as TenantRlsClient);
});
}
async function listPublicApiResourceWithTx(tx: TenantRlsClient, input: PublicApiListInput): Promise<PublicApiListResult> {
switch (input.resource) {
case "contacts":
return listContacts(tx, input);
case "companies":
return listCompanies(tx, input);
case "deals":
return listProjects(tx, input, "sales");
case "projects":
return listProjects(tx, input, null);
case "tasks":
return listTasks(tx, input);
case "leads":
return listLeads(tx, input);
}
}
async function listContacts(tx: TenantRlsClient, input: PublicApiListInput): Promise<PublicApiListResult> {
const query = input.query;
const where = mergeWhere(
{ tenantId: input.tenantId, archivedAt: null, kontaktTyp: "privatperson" },
dateFilters(query),
cursorFilter(query),
ownerFilter(query),
contactSearchFilter(query),
);
const rows = await (tx.kontakt as unknown as PublicApiModelClient).findMany({
where,
take: query.limit + 1,
orderBy: orderBy(query),
select: {
id: true,
createdAt: true,
updatedAt: true,
vorname: true,
nachname: true,
primaerEmail: true,
primaerTelefon: true,
zustaendigerUserId: true,
isDemoData: true,
},
});
return pageResult(input.resource, query, rows.map(serializeContact), rows);
}
async function listCompanies(tx: TenantRlsClient, input: PublicApiListInput): Promise<PublicApiListResult> {
const query = input.query;
const where = mergeWhere(
{ tenantId: input.tenantId, archivedAt: null, kontaktTyp: "organisation" },
dateFilters(query),
cursorFilter(query),
ownerFilter(query),
companySearchFilter(query),
);
const rows = await (tx.kontakt as unknown as PublicApiModelClient).findMany({
where,
take: query.limit + 1,
orderBy: orderBy(query),
select: {
id: true,
createdAt: true,
updatedAt: true,
orgName: true,
orgMerkmal: true,
primaerEmail: true,
primaerTelefon: true,
zustaendigerUserId: true,
isDemoData: true,
},
});
return pageResult(input.resource, query, rows.map(serializeCompany), rows);
}
async function listProjects(tx: TenantRlsClient, input: PublicApiListInput, pipelineTypHint: "sales" | null): Promise<PublicApiListResult> {
const query = input.query;
const includePipeline = query.embed.includes("pipeline");
const includeStage = query.embed.includes("stage");
const where = mergeWhere(
{ tenantId: input.tenantId, archivedAt: null },
pipelineTypHint ? { pipeline: { typHint: pipelineTypHint } } : {},
dateFilters(query),
cursorFilter(query),
projectOwnerFilter(query),
projectSearchFilter(query),
);
const rows = await (tx.projekt as unknown as PublicApiModelClient).findMany({
where,
take: query.limit + 1,
orderBy: orderBy(query),
select: {
id: true,
createdAt: true,
updatedAt: true,
projektNummer: true,
projektname: true,
beschreibung: true,
projekttyp: true,
quelle: true,
prioritaet: true,
pipelineId: true,
stageId: true,
potenziellerAuftragswert: true,
auftragsvolumen: true,
startDatum: true,
deadline: true,
zustaendigePersonId: true,
projektleiterId: true,
konvertiertAusLeadId: true,
wonAt: true,
lostAt: true,
isDemoData: true,
...(includePipeline ? { pipeline: { select: { id: true, name: true, typHint: true } } } : {}),
...(includeStage ? { stage: { select: { id: true, name: true, stageKind: true, position: true } } } : {}),
},
});
return pageResult(input.resource, query, rows.map((row) => serializeProject(row, input.resource === "deals")), rows);
}
async function listTasks(tx: TenantRlsClient, input: PublicApiListInput): Promise<PublicApiListResult> {
const query = input.query;
const where = mergeWhere(
{ tenantId: input.tenantId, archivedAt: null },
dateFilters(query),
cursorFilter(query),
query.filters.status ? { status: query.filters.status } : {},
query.filters.ownerUserId ? { assignedToUserId: query.filters.ownerUserId } : {},
taskSearchFilter(query),
);
const rows = await (tx.task as unknown as PublicApiModelClient).findMany({
where,
take: query.limit + 1,
orderBy: orderBy(query),
select: {
id: true,
createdAt: true,
updatedAt: true,
title: true,
description: true,
status: true,
priority: true,
deadline: true,
assignedToUserId: true,
assignedToGroupId: true,
linkedEntityType: true,
linkedEntityId: true,
source: true,
completedAt: true,
isDemoData: true,
},
});
return pageResult(input.resource, query, rows.map(serializeTask), rows);
}
async function listLeads(tx: TenantRlsClient, input: PublicApiListInput): Promise<PublicApiListResult> {
const query = input.query;
const includeSource = query.embed.includes("leadSource");
const where = mergeWhere(
{ tenantId: input.tenantId, archivedAt: null },
dateFilters(query),
cursorFilter(query),
query.filters.status ? { status: query.filters.status } : {},
query.filters.ownerUserId ? { zustaendigerUserId: query.filters.ownerUserId } : {},
leadSearchFilter(query),
);
const rows = await (tx.inboxLead as unknown as PublicApiModelClient).findMany({
where,
take: query.limit + 1,
orderBy: orderBy(query),
select: {
id: true,
createdAt: true,
updatedAt: true,
quelle: true,
sourceOrigin: true,
status: true,
vorname: true,
nachname: true,
email: true,
telefon: true,
message: true,
zustaendigerUserId: true,
verknuepfterKontaktId: true,
konvertiertProjektId: true,
convertedAt: true,
isDemoData: true,
...(includeSource ? { source: { select: { id: true, key: true, name: true, displayLabel: true } } } : {}),
},
});
return pageResult(input.resource, query, rows.map(serializeLead), rows);
}
type PublicApiModelClient = {
findMany(args: Record<string, unknown>): Promise<Array<Record<string, unknown> & SortableRow>>;
};
function pageResult(resource: PublicApiResourceName, query: PublicApiListQuery, serializedRows: Array<Record<string, unknown>>, rawRows: SortableRow[]): PublicApiListResult {
const definition = publicApiResources[resource];
const pageRows = serializedRows.slice(0, query.limit).map((item) => applySparseFields(item, query.fields, definition.defaultFields, query.embed));
const nextRaw = rawRows.length > query.limit ? rawRows[query.limit - 1] : null;
const fieldValue = nextRaw ? nextRaw[query.sort.field] : null;
return {
data: pageRows,
pageInfo: {
limit: query.limit,
nextCursor: nextRaw && fieldValue instanceof Date ? serializePublicApiCursor({ fieldValue: fieldValue.toISOString(), id: nextRaw.id }) : null,
sort: `${query.sort.field}.${query.sort.direction}`,
},
};
}
function orderBy(query: PublicApiListQuery) {
return [{ [query.sort.field]: query.sort.direction }, { id: query.sort.direction }];
}
function dateFilters(query: PublicApiListQuery) {
const filters: Record<string, unknown> = {};
if (query.filters.createdSince) {
filters.createdAt = {
gte: query.filters.createdSince,
};
}
if (query.filters.updatedSince) {
filters.updatedAt = {
gte: query.filters.updatedSince,
};
}
return filters;
}
function cursorFilter(query: PublicApiListQuery) {
if (!query.cursor) {
return {};
}
const field = query.sort.field;
const cursorDate = new Date(query.cursor.fieldValue);
const operator = query.sort.direction === "desc" ? "lt" : "gt";
return {
OR: [
{ [field]: { [operator]: cursorDate } },
{ [field]: cursorDate, id: { [operator]: query.cursor.id } },
],
};
}
function ownerFilter(query: PublicApiListQuery) {
return query.filters.ownerUserId ? { zustaendigerUserId: query.filters.ownerUserId } : {};
}
function projectOwnerFilter(query: PublicApiListQuery) {
return query.filters.ownerUserId ? { OR: [{ zustaendigePersonId: query.filters.ownerUserId }, { projektleiterId: query.filters.ownerUserId }] } : {};
}
function contactSearchFilter(query: PublicApiListQuery) {
return stringSearch(query.filters.q, ["vorname", "nachname", "primaerEmail", "primaerTelefon"]);
}
function companySearchFilter(query: PublicApiListQuery) {
return stringSearch(query.filters.q, ["orgName", "primaerEmail", "primaerTelefon"]);
}
function projectSearchFilter(query: PublicApiListQuery) {
return stringSearch(query.filters.q, ["projektNummer", "projektname", "beschreibung"]);
}
function taskSearchFilter(query: PublicApiListQuery) {
return stringSearch(query.filters.q, ["title", "description"]);
}
function leadSearchFilter(query: PublicApiListQuery) {
return stringSearch(query.filters.q, ["vorname", "nachname", "email", "telefon", "message", "sourceOrigin"]);
}
function stringSearch(value: string | null, fields: readonly string[]) {
if (!value) {
return {};
}
return {
OR: fields.map((field) => ({
[field]: {
contains: value,
mode: "insensitive",
},
})),
};
}
function mergeWhere(...parts: Array<Record<string, unknown>>) {
const where: Record<string, unknown> = {};
const and: Array<Record<string, unknown>> = [];
for (const part of parts) {
for (const [key, value] of Object.entries(part)) {
if (value === undefined) {
continue;
}
if (key === "AND") {
if (Array.isArray(value)) {
and.push(...(value as Array<Record<string, unknown>>));
} else if (isRecord(value)) {
and.push(value);
}
continue;
}
if (Object.prototype.hasOwnProperty.call(where, key)) {
and.push({ [key]: where[key] }, { [key]: value });
delete where[key];
continue;
}
where[key] = value;
}
}
if (and.length > 0) {
where.AND = and;
}
return where;
}
function serializeContact(row: Record<string, unknown>) {
const firstName = nullableString(row.vorname);
const lastName = nullableString(row.nachname);
return {
id: row.id,
createdAt: iso(row.createdAt),
updatedAt: iso(row.updatedAt),
displayName: [firstName, lastName].filter(Boolean).join(" ").trim() || null,
firstName,
lastName,
email: nullableString(row.primaerEmail),
phone: nullableString(row.primaerTelefon),
ownerUserId: nullableString(row.zustaendigerUserId),
isDemoData: Boolean(row.isDemoData),
};
}
function serializeCompany(row: Record<string, unknown>) {
return {
id: row.id,
createdAt: iso(row.createdAt),
updatedAt: iso(row.updatedAt),
name: nullableString(row.orgName),
legalForm: nullableString(row.orgMerkmal),
email: nullableString(row.primaerEmail),
phone: nullableString(row.primaerTelefon),
ownerUserId: nullableString(row.zustaendigerUserId),
isDemoData: Boolean(row.isDemoData),
};
}
function serializeProject(row: Record<string, unknown>, dealView: boolean) {
return {
id: row.id,
createdAt: iso(row.createdAt),
updatedAt: iso(row.updatedAt),
number: nullableString(row.projektNummer),
name: nullableString(row.projektname),
description: nullableString(row.beschreibung),
type: dealView ? undefined : nullableString(row.projekttyp),
source: dealView ? undefined : nullableString(row.quelle),
priority: dealView ? undefined : nullableString(row.prioritaet),
pipelineId: nullableString(row.pipelineId),
stageId: nullableString(row.stageId),
potentialValue: decimalString(row.potenziellerAuftragswert),
orderVolume: decimalString(row.auftragsvolumen),
startDate: dealView ? undefined : iso(row.startDatum),
deadline: dealView ? undefined : iso(row.deadline),
ownerUserId: nullableString(row.zustaendigePersonId),
projectLeadUserId: nullableString(row.projektleiterId),
convertedFromLeadId: dealView ? undefined : nullableString(row.konvertiertAusLeadId),
wonAt: iso(row.wonAt),
lostAt: iso(row.lostAt),
isDemoData: Boolean(row.isDemoData),
...(isRecord(row.pipeline) ? { pipeline: row.pipeline } : {}),
...(isRecord(row.stage) ? { stage: row.stage } : {}),
};
}
function serializeTask(row: Record<string, unknown>) {
return {
id: row.id,
createdAt: iso(row.createdAt),
updatedAt: iso(row.updatedAt),
title: nullableString(row.title),
description: nullableString(row.description),
status: nullableString(row.status),
priority: nullableString(row.priority),
deadline: iso(row.deadline),
assignedToUserId: nullableString(row.assignedToUserId),
assignedToGroupId: nullableString(row.assignedToGroupId),
linkedEntityType: nullableString(row.linkedEntityType),
linkedEntityId: nullableString(row.linkedEntityId),
source: nullableString(row.source),
completedAt: iso(row.completedAt),
isDemoData: Boolean(row.isDemoData),
};
}
function serializeLead(row: Record<string, unknown>) {
return {
id: row.id,
createdAt: iso(row.createdAt),
updatedAt: iso(row.updatedAt),
source: nullableString(row.quelle),
sourceOrigin: nullableString(row.sourceOrigin),
status: nullableString(row.status),
firstName: nullableString(row.vorname),
lastName: nullableString(row.nachname),
email: nullableString(row.email),
phone: nullableString(row.telefon),
message: nullableString(row.message),
ownerUserId: nullableString(row.zustaendigerUserId),
linkedContactId: nullableString(row.verknuepfterKontaktId),
convertedProjectId: nullableString(row.konvertiertProjektId),
convertedAt: iso(row.convertedAt),
isDemoData: Boolean(row.isDemoData),
...(isRecord(row.source) ? { leadSource: row.source } : {}),
};
}
function iso(value: unknown) {
return value instanceof Date ? value.toISOString() : null;
}
function nullableString(value: unknown) {
return typeof value === "string" && value ? value : null;
}
function decimalString(value: unknown) {
if (value === null || value === undefined) {
return null;
}
return typeof value === "object" && "toString" in value && typeof value.toString === "function" ? value.toString() : String(value);
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value);
}
@@ -0,0 +1,66 @@
import { describe, expect, test } from "vitest";
import { applySparseFields, parsePublicApiListQuery, publicApiResources, serializePublicApiCursor } from "./resources.js";
describe("public API resources", () => {
test("parses bounded cursor list queries", () => {
const cursor = serializePublicApiCursor({ fieldValue: "2026-07-03T00:00:00.000Z", id: "row_1" });
const result = parsePublicApiListQuery(
publicApiResources.contacts,
new URLSearchParams({
limit: "25",
cursor,
sort: "updatedAt.asc",
fields: "displayName,email",
q: "Meyer",
updatedSince: "2026-07-01T00:00:00.000Z",
}),
);
expect(result).toMatchObject({
ok: true,
value: {
limit: 25,
cursor: { fieldValue: "2026-07-03T00:00:00.000Z", id: "row_1" },
sort: { field: "updatedAt", direction: "asc" },
fields: ["displayName", "email"],
filters: { q: "Meyer" },
},
});
});
test("rejects unsupported sparse fields and embeds", () => {
expect(parsePublicApiListQuery(publicApiResources.contacts, new URLSearchParams({ fields: "passwordHash" }))).toMatchObject({
ok: false,
code: "invalid_fields",
});
expect(parsePublicApiListQuery(publicApiResources.contacts, new URLSearchParams({ embed: "secrets" }))).toMatchObject({
ok: false,
code: "invalid_embed",
});
});
test("rejects cursor payloads with non-date sort values", () => {
const cursor = serializePublicApiCursor({ fieldValue: "not-a-date", id: "row_1" });
expect(parsePublicApiListQuery(publicApiResources.contacts, new URLSearchParams({ cursor }))).toMatchObject({
ok: false,
code: "invalid_cursor",
});
});
test("keeps id and requested embeds in sparse fieldsets", () => {
expect(
applySparseFields(
{ id: "deal_1", name: "Deal", email: "a@example.test", pipeline: { id: "pipeline_1" } },
["email"],
publicApiResources.deals.defaultFields,
["pipeline"],
),
).toEqual({
email: "a@example.test",
id: "deal_1",
pipeline: { id: "pipeline_1" },
});
});
});
@@ -0,0 +1,336 @@
export const PUBLIC_API_RESOURCE_NAMES = ["contacts", "companies", "deals", "projects", "tasks", "leads"] as const;
export type PublicApiResourceName = (typeof PUBLIC_API_RESOURCE_NAMES)[number];
export type PublicApiSortField = "createdAt" | "updatedAt";
export type PublicApiSortDirection = "asc" | "desc";
export type PublicApiSort = {
field: PublicApiSortField;
direction: PublicApiSortDirection;
};
export type PublicApiCursor = {
fieldValue: string;
id: string;
};
export type PublicApiListQuery = {
limit: number;
cursor: PublicApiCursor | null;
cursorRaw: string | null;
sort: PublicApiSort;
fields: readonly string[] | null;
embed: readonly string[];
filters: {
q: string | null;
status: string | null;
ownerUserId: string | null;
updatedSince: Date | null;
createdSince: Date | null;
};
};
export type PublicApiListInput = {
tenantId: string;
resource: PublicApiResourceName;
query: PublicApiListQuery;
};
export type PublicApiListResult = {
data: Array<Record<string, unknown>>;
pageInfo: {
limit: number;
nextCursor: string | null;
sort: string;
};
};
export type PublicApiResourceDefinition = {
name: PublicApiResourceName;
singular: string;
description: string;
fields: readonly string[];
defaultFields: readonly string[];
embeds: readonly string[];
statusValues?: readonly string[];
};
export const PUBLIC_API_MAX_LIMIT = 100;
export const PUBLIC_API_DEFAULT_LIMIT = 50;
export const PUBLIC_API_DEFAULT_SORT: PublicApiSort = Object.freeze({ field: "createdAt", direction: "desc" });
export const publicApiResources: Record<PublicApiResourceName, PublicApiResourceDefinition> = {
contacts: {
name: "contacts",
singular: "contact",
description: "Tenant-scoped private-person contacts from the CRM core.",
fields: ["id", "createdAt", "updatedAt", "displayName", "firstName", "lastName", "email", "phone", "ownerUserId", "isDemoData"],
defaultFields: ["id", "createdAt", "updatedAt", "displayName", "firstName", "lastName", "email", "phone", "ownerUserId"],
embeds: [],
},
companies: {
name: "companies",
singular: "company",
description: "Tenant-scoped organisation contacts from the CRM core.",
fields: ["id", "createdAt", "updatedAt", "name", "legalForm", "email", "phone", "ownerUserId", "isDemoData"],
defaultFields: ["id", "createdAt", "updatedAt", "name", "legalForm", "email", "phone", "ownerUserId"],
embeds: [],
},
deals: {
name: "deals",
singular: "deal",
description: "Sales-pipeline project view. Deals and projects share the Projekt core.",
fields: [
"id",
"createdAt",
"updatedAt",
"number",
"name",
"description",
"pipelineId",
"stageId",
"potentialValue",
"orderVolume",
"ownerUserId",
"projectLeadUserId",
"wonAt",
"lostAt",
"isDemoData",
],
defaultFields: ["id", "createdAt", "updatedAt", "number", "name", "pipelineId", "stageId", "potentialValue", "ownerUserId", "wonAt", "lostAt"],
embeds: ["pipeline", "stage"],
},
projects: {
name: "projects",
singular: "project",
description: "Tenant-scoped project records from the Projekt core.",
fields: [
"id",
"createdAt",
"updatedAt",
"number",
"name",
"description",
"type",
"source",
"priority",
"pipelineId",
"stageId",
"potentialValue",
"orderVolume",
"startDate",
"deadline",
"ownerUserId",
"projectLeadUserId",
"convertedFromLeadId",
"wonAt",
"lostAt",
"isDemoData",
],
defaultFields: ["id", "createdAt", "updatedAt", "number", "name", "priority", "pipelineId", "stageId", "ownerUserId", "deadline"],
embeds: ["pipeline", "stage"],
},
tasks: {
name: "tasks",
singular: "task",
description: "Tenant-scoped task records.",
fields: [
"id",
"createdAt",
"updatedAt",
"title",
"description",
"status",
"priority",
"deadline",
"assignedToUserId",
"assignedToGroupId",
"linkedEntityType",
"linkedEntityId",
"source",
"completedAt",
"isDemoData",
],
defaultFields: ["id", "createdAt", "updatedAt", "title", "status", "priority", "deadline", "assignedToUserId", "linkedEntityType", "linkedEntityId"],
embeds: [],
statusValues: ["open", "in_progress", "blocked", "done", "cancelled"],
},
leads: {
name: "leads",
singular: "lead",
description: "Tenant-scoped lead-inbox records.",
fields: [
"id",
"createdAt",
"updatedAt",
"source",
"sourceOrigin",
"status",
"firstName",
"lastName",
"email",
"phone",
"message",
"ownerUserId",
"linkedContactId",
"convertedProjectId",
"convertedAt",
"isDemoData",
],
defaultFields: ["id", "createdAt", "updatedAt", "source", "status", "firstName", "lastName", "email", "phone", "ownerUserId"],
embeds: ["leadSource"],
statusValues: ["new", "qualified", "converted", "lost", "spam"],
},
};
export function isPublicApiResourceName(value: string): value is PublicApiResourceName {
return (PUBLIC_API_RESOURCE_NAMES as readonly string[]).includes(value);
}
export function serializePublicApiCursor(cursor: PublicApiCursor): string {
return Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
}
export function parsePublicApiCursor(value: string): PublicApiCursor | null {
try {
const parsed = JSON.parse(Buffer.from(value, "base64url").toString("utf8")) as Partial<PublicApiCursor>;
if (typeof parsed.fieldValue !== "string" || !parsed.fieldValue || typeof parsed.id !== "string" || !parsed.id) {
return null;
}
return { fieldValue: parsed.fieldValue, id: parsed.id };
} catch {
return null;
}
}
export type PublicApiQueryParseResult = { ok: true; value: PublicApiListQuery } | { ok: false; code: string; message: string; params?: Record<string, string | number | boolean | null> };
export function parsePublicApiListQuery(resource: PublicApiResourceDefinition, searchParams: URLSearchParams): PublicApiQueryParseResult {
const limit = parseLimit(searchParams.get("limit"));
if (limit === null) {
return { ok: false, code: "invalid_limit", message: "limit must be an integer between 1 and 100.", params: { min: 1, max: PUBLIC_API_MAX_LIMIT } };
}
const cursorRaw = normalizeOptional(searchParams.get("cursor"));
const cursor = cursorRaw ? parsePublicApiCursor(cursorRaw) : null;
if (cursorRaw && !cursor) {
return { ok: false, code: "invalid_cursor", message: "cursor is invalid or expired." };
}
if (cursor && Number.isNaN(new Date(cursor.fieldValue).getTime())) {
return { ok: false, code: "invalid_cursor", message: "cursor is invalid or expired." };
}
const sort = parseSort(searchParams.get("sort"));
if (!sort) {
return { ok: false, code: "invalid_sort", message: "sort must be one of createdAt.desc, createdAt.asc, updatedAt.desc, updatedAt.asc." };
}
const fields = parseCsv(searchParams.get("fields"));
if (fields) {
const unknownField = fields.find((field) => !resource.fields.includes(field));
if (unknownField) {
return { ok: false, code: "invalid_fields", message: "fields contains an unsupported field.", params: { field: unknownField, resource: resource.name } };
}
}
const embed = parseCsv(searchParams.get("embed")) ?? [];
const unknownEmbed = embed.find((field) => !resource.embeds.includes(field));
if (unknownEmbed) {
return { ok: false, code: "invalid_embed", message: "embed contains an unsupported relation.", params: { embed: unknownEmbed, resource: resource.name } };
}
const updatedSince = parseOptionalDate(searchParams.get("updatedSince"));
if (updatedSince === false) {
return { ok: false, code: "invalid_updated_since", message: "updatedSince must be an ISO date-time." };
}
const createdSince = parseOptionalDate(searchParams.get("createdSince"));
if (createdSince === false) {
return { ok: false, code: "invalid_created_since", message: "createdSince must be an ISO date-time." };
}
const status = normalizeOptional(searchParams.get("status"));
if (status && resource.statusValues && !resource.statusValues.includes(status)) {
return { ok: false, code: "invalid_status", message: "status is not supported for this resource.", params: { status, resource: resource.name } };
}
return {
ok: true,
value: {
limit,
cursor,
cursorRaw,
sort,
fields,
embed,
filters: {
q: normalizeOptional(searchParams.get("q")),
status,
ownerUserId: normalizeOptional(searchParams.get("ownerUserId")),
updatedSince,
createdSince,
},
},
};
}
export function applySparseFields(item: Record<string, unknown>, fields: readonly string[] | null, defaultFields: readonly string[], embeds: readonly string[] = []) {
const selected = fields ?? defaultFields;
const result: Record<string, unknown> = {};
for (const field of [...selected, ...embeds]) {
if (Object.prototype.hasOwnProperty.call(item, field)) {
result[field] = item[field];
}
}
if (!Object.prototype.hasOwnProperty.call(result, "id") && Object.prototype.hasOwnProperty.call(item, "id")) {
result.id = item.id;
}
return result;
}
function parseLimit(value: string | null) {
if (!value) {
return PUBLIC_API_DEFAULT_LIMIT;
}
if (!/^\d+$/.test(value)) {
return null;
}
const parsed = Number(value);
return Number.isSafeInteger(parsed) && parsed >= 1 && parsed <= PUBLIC_API_MAX_LIMIT ? parsed : null;
}
function parseSort(value: string | null): PublicApiSort | null {
if (!value) {
return PUBLIC_API_DEFAULT_SORT;
}
const [field, direction] = value.split(".");
if ((field === "createdAt" || field === "updatedAt") && (direction === "asc" || direction === "desc")) {
return { field, direction };
}
return null;
}
function parseCsv(value: string | null): readonly string[] | null {
const normalized = normalizeOptional(value);
if (!normalized) {
return null;
}
const values = normalized
.split(",")
.map((part) => part.trim())
.filter(Boolean);
return values.length > 0 ? [...new Set(values)] : null;
}
function parseOptionalDate(value: string | null): Date | null | false {
const normalized = normalizeOptional(value);
if (!normalized) {
return null;
}
const date = new Date(normalized);
return Number.isNaN(date.getTime()) ? false : date;
}
function normalizeOptional(value: string | null) {
const normalized = value?.trim();
return normalized ? normalized : null;
}
@@ -52,10 +52,9 @@ function expectedSecurityFor(entry: RouteAccessInventoryEntry) {
case "canonical-redirect":
return undefined;
case "webhook-signature":
if (entry.path === "/v1/billing/stripe/webhooks") {
return [{ stripeWebhookSignature: [] }];
}
return [{ mailjetWebhookAuth: [] }];
case "provider-refetch-webhook":
return [];
case "jwt-auth":
return [{ apiSessionBearer: [] }];
case "service-token":
@@ -66,6 +65,8 @@ function expectedSecurityFor(entry: RouteAccessInventoryEntry) {
return [{ bearerAuth: [] }, { apiKeyHeader: [] }, {}];
case "tenant-api-key":
return [{ apiKeyHeader: [] }];
case "tenant-webhook-credential":
return [{ apiKeyHeader: [] }, { webhookTokenHeader: [] }, { webhookHmac: [] }];
}
}
@@ -5,7 +5,9 @@ export const routeAccessClasses = [
"service-or-tenant-api-key",
"optional-api-key-validation",
"tenant-api-key",
"tenant-webhook-credential",
"webhook-signature",
"provider-refetch-webhook",
"jwt-auth",
"auth-credential-exchange",
"public-analytics-token",
@@ -185,12 +187,61 @@ export const routeAccessInventory = [
rationale: "Usage lookups enter through the canonical API host and validate tenant API-key credentials in the API runtime.",
sensitiveData: "Returns plan and remaining API usage metadata for the credential-scoped tenant.",
},
{
method: "GET",
path: "/v1/contacts",
accessClass: "tenant-api-key",
rationale: "Public API contact reads validate a tenant-bound API-key credential before querying only that credential's tenant scope.",
sensitiveData: "Returns redacted contact fields for the credential-scoped tenant; internal notes and credential material are omitted.",
},
{
method: "GET",
path: "/v1/companies",
accessClass: "tenant-api-key",
rationale: "Public API company reads validate a tenant-bound API-key credential before querying only that credential's tenant scope.",
sensitiveData: "Returns redacted organisation contact fields for the credential-scoped tenant; internal notes and credential material are omitted.",
},
{
method: "GET",
path: "/v1/deals",
accessClass: "tenant-api-key",
rationale: "Public API deal reads validate a tenant-bound API-key credential before querying only that credential's tenant scope.",
sensitiveData: "Returns redacted sales-pipeline project fields for the credential-scoped tenant; internal notes and credential material are omitted.",
},
{
method: "GET",
path: "/v1/projects",
accessClass: "tenant-api-key",
rationale: "Public API project reads validate a tenant-bound API-key credential before querying only that credential's tenant scope.",
sensitiveData: "Returns redacted project fields for the credential-scoped tenant; internal notes and credential material are omitted.",
},
{
method: "GET",
path: "/v1/tasks",
accessClass: "tenant-api-key",
rationale: "Public API task reads validate a tenant-bound API-key credential before querying only that credential's tenant scope.",
sensitiveData: "Returns redacted task fields for the credential-scoped tenant; internal notes and credential material are omitted.",
},
{
method: "GET",
path: "/v1/leads",
accessClass: "tenant-api-key",
rationale: "Public API lead reads validate a tenant-bound API-key credential before querying only that credential's tenant scope.",
sensitiveData: "Returns redacted lead-inbox fields for the credential-scoped tenant; raw payloads, anti-spam internals and credential material are omitted.",
},
{
method: "POST",
path: "/v1/billing/stripe/webhooks",
accessClass: "webhook-signature",
rationale: "Stripe billing webhook ingress enters through the canonical API host and verifies the raw signed payload in the API runtime.",
sensitiveData: "Consumes signed billing lifecycle webhook payloads without returning signing material or plaintext credentials.",
path: "/v1/webhooks/incoming/:tenant/:slug",
accessClass: "tenant-webhook-credential",
rationale: "Incoming public webhooks enter through the canonical API host, resolve the tenant endpoint, validate the endpoint credential mode and create only tenant-scoped lead intake records.",
sensitiveData: "Consumes third-party lead payloads and stores redacted ingestion metadata; API keys, webhook tokens, HMAC material and raw signing secrets are omitted from responses.",
},
{
method: "POST",
path: "/v1/billing/mollie/webhooks",
accessClass: "provider-refetch-webhook",
rationale: "Mollie billing webhook ingress accepts only the provider payment id, refetches that payment from Mollie server-side, and syncs only tenant-scoped billing metadata from the verified payment.",
sensitiveData: "Consumes a provider payment id and stores redacted billing lifecycle metadata without returning provider payloads or plaintext credentials.",
},
{
method: "POST",
@@ -255,62 +306,6 @@ export const routeAccessInventory = [
rationale: "Export artifact retention cleanup is an operator maintenance action and requires service credentials before enqueueing work.",
sensitiveData: "Consumes an optional bounded batch size and returns only queue task metadata plus request correlation.",
},
{
method: "GET",
path: "/v1/entities/:entity/rows",
accessClass: "service-or-tenant-api-key",
rationale: "Entity row listing requires a service token or scoped stored API key with read permission for the resolved entity.",
sensitiveData: "Returns tenant-scoped legacy entity row data.",
},
{
method: "POST",
path: "/v1/entities/:entity/rows",
accessClass: "service-or-tenant-api-key",
rationale: "Entity row creation requires a service token or scoped stored API key with create permission for the resolved entity.",
sensitiveData: "Consumes and stores tenant-scoped legacy entity row data.",
},
{
method: "GET",
path: "/v1/entities/:entity/rows/:rowId",
accessClass: "service-or-tenant-api-key",
rationale: "Entity row lookup requires a service token or scoped stored API key with read permission for the resolved entity.",
sensitiveData: "Returns tenant-scoped legacy entity row data.",
},
{
method: "PATCH",
path: "/v1/entities/:entity/rows/:rowId",
accessClass: "service-or-tenant-api-key",
rationale: "Entity row update requires a service token or scoped stored API key with update permission for the resolved entity.",
sensitiveData: "Consumes and returns tenant-scoped legacy entity row data.",
},
{
method: "DELETE",
path: "/v1/entities/:entity/rows/:rowId",
accessClass: "service-or-tenant-api-key",
rationale: "Entity row deletion requires a service token or scoped stored API key with delete permission for the resolved entity.",
sensitiveData: "Deletes tenant-scoped legacy entity row data and returns the deleted row id.",
},
{
method: "POST",
path: "/v1/relationships",
accessClass: "service-or-tenant-api-key",
rationale: "Relationship creation requires a service token or scoped stored API key with create permission for both related entities.",
sensitiveData: "Consumes row identifiers and returns relationship metadata.",
},
{
method: "GET",
path: "/v1/relationships/:id",
accessClass: "service-or-tenant-api-key",
rationale: "Relationship lookup requires a service token or scoped stored API key with read permission for both related entities.",
sensitiveData: "Returns relationship metadata with parent and child row envelopes.",
},
{
method: "DELETE",
path: "/v1/relationships/:id",
accessClass: "service-or-tenant-api-key",
rationale: "Relationship deletion requires a service token or scoped stored API key with delete permission for both related entities.",
sensitiveData: "Deletes and returns relationship metadata with parent and child row envelopes.",
},
{
method: "GET",
path: "/v1/exports/:exportJobId/download-url",
@@ -318,13 +313,6 @@ export const routeAccessInventory = [
rationale: "Export download URL creation requires service credentials or a tenant-bound stored API key and blocks compliance-paused exports before returning a short-lived signed artifact URL envelope.",
sensitiveData: "Returns a signed artifact URL envelope without artifact bucket/key values, storage credentials, pause reason internals, filters, or object bodies.",
},
{
method: "GET",
path: "/v1/entities/:entity",
accessClass: "service-token",
rationale: "Legacy entity lookup requires service credentials before returning the named entity detail graph.",
sensitiveData: "Returns legacy entity schema and relationship details.",
},
{
method: "GET",
path: "/v1/exports/:exportJobId/progress",
@@ -63,7 +63,7 @@ function serializeAccountTenant(tenant: LegacyTenantWithDetails, subscription: T
subscription: subscription
? {
id: subscription.id,
stripeCustomerId: subscription.stripeCustomerId,
billingProviderCustomerId: subscription.billingProviderCustomerId,
products: subscription.products.map((product) => ({
id: product.id,
product: product.subscriptionProduct.title,
@@ -73,12 +73,12 @@ function serializeAccountTenant(tenant: LegacyTenantWithDetails, subscription: T
model: product.subscriptionProduct.model,
cancelledAt: product.cancelledAt ?? undefined,
endsAt: product.endsAt ?? undefined,
stripeId: product.stripeSubscriptionId,
billingProviderId: product.billingProviderSubscriptionId,
prices: product.prices.map((price) => ({
id: price.id,
...(price.subscriptionPrice
? {
stripeId: price.subscriptionPrice.stripeId,
billingProviderId: price.subscriptionPrice.billingProviderId,
type: price.subscriptionPrice.type,
billingPeriod: price.subscriptionPrice.billingPeriod,
price: Number(price.subscriptionPrice.price),
@@ -86,7 +86,7 @@ function serializeAccountTenant(tenant: LegacyTenantWithDetails, subscription: T
}
: price.subscriptionUsageBasedPrice
? {
stripeId: price.subscriptionUsageBasedPrice.stripeId,
billingProviderId: price.subscriptionUsageBasedPrice.billingProviderId,
billingPeriod: price.subscriptionUsageBasedPrice.billingPeriod,
currency: price.subscriptionUsageBasedPrice.currency,
unit: price.subscriptionUsageBasedPrice.unit,
@@ -8,15 +8,15 @@ const TEST_TOKEN = "test-service-token";
let mockStore: Map<string, { id: string; userId: string; tenantId: string | null; platform: string; token: string; pushProvider: string; appVersion: string | null; createdAt: Date; lastSeenAt: Date; revokedAt: Date | null }>;
vi.mock("@toolctrl/db/device-tokens.server", () => ({
vi.mock("@hivegrid/db/device-tokens.server", () => ({
parseDevicePlatform: (value: unknown) => {
return value === "ios" || value === "android" || value === "web" ? value : null;
return value === "web" ? value : null;
},
parsePushProvider: (value: unknown) => {
return value === "fcm" || value === "apns" || value === "webpush" ? value : null;
return value === "webpush" ? value : null;
},
async registerDeviceToken(input: { userId: string; tenantId: string | null; platform: "ios" | "android" | "web"; token: string; pushProvider?: "fcm" | "apns" | "webpush"; appVersion?: string | null }) {
const provider = input.pushProvider ?? (input.platform === "ios" ? "apns" : input.platform === "android" ? "fcm" : "webpush");
async registerDeviceToken(input: { userId: string; tenantId: string | null; platform: "web"; token: string; pushProvider?: "webpush"; appVersion?: string | null }) {
const provider = input.pushProvider ?? "webpush";
const now = new Date();
const existing = mockStore.get(input.token);
if (existing) {
@@ -102,7 +102,7 @@ describe("POST /v1/devices/register", () => {
it("rejects missing userId", async () => {
const app = buildApp();
const response = await postRegister(app, { platform: "ios", token: "t" });
const response = await postRegister(app, { platform: "web", token: "t" });
expect(response.status).toBe(400);
const json = (await response.json()) as { error: { params: { field: string } } };
expect(json.error.params.field).toBe("userId");
@@ -116,7 +116,7 @@ describe("POST /v1/devices/register", () => {
it("rejects missing token", async () => {
const app = buildApp();
const response = await postRegister(app, { userId: "u1", platform: "ios" });
const response = await postRegister(app, { userId: "u1", platform: "web" });
expect(response.status).toBe(400);
const json = (await response.json()) as { error: { params: { field: string } } };
expect(json.error.params.field).toBe("token");
@@ -127,23 +127,23 @@ describe("POST /v1/devices/register", () => {
const response = await postRegister(app, {
userId: "u-1",
tenantId: "t-1",
platform: "ios",
platform: "web",
token: "tok-1",
appVersion: "1.2.3",
});
expect(response.status).toBe(200);
const json = (await response.json()) as { success: boolean; data: { pushProvider: string; platform: string; appVersion: string | null } };
expect(json.success).toBe(true);
expect(json.data.platform).toBe("ios");
expect(json.data.pushProvider).toBe("apns");
expect(json.data.platform).toBe("web");
expect(json.data.pushProvider).toBe("webpush");
expect(json.data.appVersion).toBe("1.2.3");
expect(mockStore.size).toBe(1);
});
it("is idempotent: re-registering the same token bumps lastSeenAt without duplicating", async () => {
const app = buildApp();
await postRegister(app, { userId: "u-1", tenantId: null, platform: "android", token: "tok-x" });
const second = await postRegister(app, { userId: "u-1", tenantId: null, platform: "android", token: "tok-x" });
await postRegister(app, { userId: "u-1", tenantId: null, platform: "web", token: "tok-x" });
const second = await postRegister(app, { userId: "u-1", tenantId: null, platform: "web", token: "tok-x" });
expect(second.status).toBe(200);
expect(mockStore.size).toBe(1);
});
@@ -152,7 +152,7 @@ describe("POST /v1/devices/register", () => {
describe("POST /v1/devices/revoke", () => {
it("revokes a known token", async () => {
const app = buildApp();
await postRegister(app, { userId: "u-1", platform: "ios", token: "tok-a" });
await postRegister(app, { userId: "u-1", platform: "web", token: "tok-a" });
const response = await app.request("/v1/devices/revoke", {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${TEST_TOKEN}` },
@@ -1,20 +1,19 @@
/**
* Mobile device-token registration routes (Phase 08 #65).
* Web Push device-token registration routes.
*
* The Capacitor mobile shell calls `POST /v1/devices/register` once it
* has obtained an APNs / FCM / WebPush token from the native plugin.
* The PWA client calls `POST /v1/devices/register` once it has obtained
* a Web Push subscription/token from the browser Push API.
* The endpoint upserts by `token` (globally unique) so the same payload
* can be replayed on every cold start without producing duplicate rows.
*
* Authentication: service-credential (bearer or API-key) — the mobile
* Authentication: service-credential (bearer or API-key) — the web
* client forwards its session bearer through the same auth pipeline as
* every other API call. `userId` and `tenantId` come from the request
* body because the wrapping service-token has no inherent identity in
* the boilerplate's auth model; downstream calls verify these against
* the HiveGrid auth model; downstream calls verify these against
* the authenticated principal.
*
* @see packages/db/src/device-tokens.server.ts
* @see apps/mobile/src/pushRegistration.ts
*/
import {
parseDevicePlatform,
@@ -22,7 +21,7 @@ import {
registerDeviceToken,
revokeDeviceToken,
type DeviceTokenRecord,
} from "@toolctrl/db/device-tokens.server";
} from "@hivegrid/db/device-tokens.server";
import { Hono, type Context } from "hono";
import type { ApiEnv } from "../api-types.js";
import { apiError } from "../middleware/error-envelope.js";
@@ -66,7 +65,7 @@ async function postDeviceRegisterRequest(c: Context<ApiEnv>) {
return apiError(c, 400, "invalid_request", "Request validation failed.", { params: { reason: "field_too_long", field: "tenantId", max: MAX_TENANT_ID_LENGTH } });
}
if (!platform) {
return apiError(c, 400, "invalid_request", "Request validation failed.", { params: { reason: "field_value_invalid", field: "platform", allowed: "ios,android,web" } });
return apiError(c, 400, "invalid_request", "Request validation failed.", { params: { reason: "field_value_invalid", field: "platform", allowed: "web" } });
}
if (!token) {
return apiError(c, 400, "invalid_request", "Request validation failed.", { params: { reason: "field_required", field: "token" } });
@@ -1,343 +0,0 @@
import { Hono, type Context } from "hono";
import { PLUGIN_HOOK_ENTITY_CREATED, PLUGIN_HOOK_ENTITY_DELETED, PLUGIN_HOOK_ENTITY_UPDATED } from "@toolctrl/plugin-runtime";
import { getApiAppDependencies, type LegacyEntityWithDetails } from "../app-dependencies.js";
import type { ApiEnv } from "../api-types.js";
import { authenticateServiceRequest } from "../auth.js";
import { authorizeApiEntityRowScope } from "../auth/permission.js";
import { resolveApiTenantScope } from "../auth/scope.js";
import { getApiRuntimeConfig } from "../config.js";
import { apiError } from "../middleware/error-envelope.js";
import { parseRowsPaginationFromQuery } from "../pagination/rows.js";
import { emitPluginHookFireAndForget } from "../plugin-hook-publisher.js";
import { parseEntityRowObjectBody } from "../validation/request-schemas.js";
import {
apiKeyScopedMissingResourceError,
authenticateServiceCredentialRequest,
forbiddenApiKeyScopeError,
getLegacyEntityId,
isMissingLegacyEntityError,
isMissingLegacyRowError,
missingApiTenantScopeError,
normalizeUnknownError,
parseEntityRowRouteParams,
parseOptionalTenantId,
readJsonBody,
runIdempotentJson,
toJsonValue,
} from "./shared.js";
export function registerEntityRowRoutes(app: Hono<ApiEnv>) {
app.get("/v1/entities/:entity/rows", getEntityRowsRequest);
app.post("/v1/entities/:entity/rows", postEntityRowRequest);
app.get("/v1/entities/:entity/rows/:rowId", getEntityRowRequest);
app.patch("/v1/entities/:entity/rows/:rowId", patchEntityRowRequest);
app.delete("/v1/entities/:entity/rows/:rowId", deleteEntityRowRequest);
app.get("/v1/entities/:entity", getEntityRequest);
}
async function getEntityRowsRequest(c: Context<ApiEnv>) {
const principal = await authenticateServiceCredentialRequest(c);
if (!principal) {
return apiError(c, 401, "unauthorized", "A valid service credential is required.");
}
const entityName = c.req.param("entity");
if (!entityName) {
return apiError(c, 400, "invalid_request", "Expected entity.");
}
const pagination = parseRowsPaginationFromQuery((name) => c.req.query(name));
if (!pagination.ok) {
return apiError(c, 400, "invalid_pagination", pagination.error);
}
const tenantResult = resolveTenantScope(c, principal);
if (!tenantResult.ok) {
return tenantResult.response;
}
try {
const dependencies = getApiAppDependencies();
const entity = await dependencies.findLegacyEntityByName({ tenantId: tenantResult.tenantId, name: entityName, active: true });
const scope = authorizeApiEntityRowScope(principal, { tenantId: tenantResult.tenantId, entity, operation: "read" });
if (!scope.allowed) {
return forbiddenApiKeyScopeError(c);
}
const page = await dependencies.getAllLegacyEntityRows({ entityId: getLegacyEntityId(entity), tenantId: tenantResult.tenantId, ...pagination.value });
return c.json({ success: true, page: page.page, total_pages: page.totalPages, total_results: page.totalItems, results: page.items, data: page.items });
} catch (error) {
const normalizedError = normalizeUnknownError(error);
const apiKeyMissing = isMissingLegacyEntityError(normalizedError) ? apiKeyScopedMissingResourceError(c, principal) : null;
if (apiKeyMissing) {
return apiKeyMissing;
}
return apiError(c, isMissingLegacyEntityError(normalizedError) ? 404 : 500, isMissingLegacyEntityError(normalizedError) ? "entity_not_found" : "entity_rows_failed", isMissingLegacyEntityError(normalizedError) ? "Entity not found." : "Entity rows could not be loaded.");
}
}
async function postEntityRowRequest(c: Context<ApiEnv>) {
const principal = await authenticateServiceCredentialRequest(c);
if (!principal) {
return apiError(c, 401, "unauthorized", "A valid service credential is required.");
}
const entityName = c.req.param("entity");
if (!entityName) {
return apiError(c, 400, "invalid_request", "Expected entity.");
}
const body = await readJsonBody(c.req.raw);
const payload = parseEntityRowObjectBody(body);
if (!payload.ok) {
return apiError(c, 400, "invalid_json", payload.error.message, { params: payload.error.params });
}
const tenantResult = resolveTenantScope(c, principal);
if (!tenantResult.ok) {
return tenantResult.response;
}
try {
const dependencies = getApiAppDependencies();
const entity = await dependencies.findLegacyEntityByName({ tenantId: tenantResult.tenantId, name: entityName, active: true });
const scope = authorizeApiEntityRowScope(principal, { tenantId: tenantResult.tenantId, entity, operation: "create" });
if (!scope.allowed) {
return forbiddenApiKeyScopeError(c);
}
return await runIdempotentJson(c, {
method: "POST",
route: "/v1/entities/:entity/rows",
tenantId: tenantResult.tenantId,
entityId: getLegacyEntityId(entity),
parsedBody: toJsonValue(payload.value),
}, async () => {
const row = await dependencies.createLegacyEntityRow({
entity: entity as LegacyEntityWithDetails,
tenantId: tenantResult.tenantId,
createdByApiKeyId: principal.type === "api-key" ? principal.apiKey.id : null,
data: payload.value,
});
void emitPluginHookFireAndForget(
PLUGIN_HOOK_ENTITY_CREATED,
{
entityType: entityName,
entityId: row.id,
tenantId: tenantResult.tenantId,
userId: null,
occurredAt: new Date().toISOString(),
},
{ tenantId: tenantResult.tenantId, dispatchKey: `entity:${entityName}:${row.id}:created` },
);
return { status: 201, body: row as never };
});
} catch (error) {
const normalizedError = normalizeUnknownError(error);
const apiKeyMissing = isMissingLegacyEntityError(normalizedError) ? apiKeyScopedMissingResourceError(c, principal) : null;
if (apiKeyMissing) {
return apiKeyMissing;
}
return apiError(c, isMissingLegacyEntityError(normalizedError) ? 404 : 400, isMissingLegacyEntityError(normalizedError) ? "entity_not_found" : "entity_row_create_failed", isMissingLegacyEntityError(normalizedError) ? "Entity not found." : "Entity row could not be created.");
}
}
async function getEntityRowRequest(c: Context<ApiEnv>) {
const principal = await authenticateServiceCredentialRequest(c);
if (!principal) {
return apiError(c, 401, "unauthorized", "A valid service credential is required.");
}
const routeParams = parseEntityRowRouteParams(c);
if (!routeParams.ok) {
return apiError(c, 400, "invalid_request", routeParams.error);
}
const tenantResult = resolveTenantScope(c, principal);
if (!tenantResult.ok) {
return tenantResult.response;
}
try {
const dependencies = getApiAppDependencies();
const entity = await dependencies.findLegacyEntityByName({ tenantId: tenantResult.tenantId, name: routeParams.value.entityName, active: true });
const scope = authorizeApiEntityRowScope(principal, { tenantId: tenantResult.tenantId, entity, operation: "read" });
if (!scope.allowed) {
return forbiddenApiKeyScopeError(c);
}
const row = await dependencies.getLegacyEntityRow({ entityId: getLegacyEntityId(entity), tenantId: tenantResult.tenantId, rowId: routeParams.value.rowId });
if (!row) {
const apiKeyMissing = apiKeyScopedMissingResourceError(c, principal);
return apiKeyMissing ?? apiError(c, 404, "row_not_found", "Row not found.", { params: { rowId: routeParams.value.rowId } });
}
return c.json(row as never);
} catch (error) {
const normalizedError = normalizeUnknownError(error);
const apiKeyMissing = isMissingLegacyEntityError(normalizedError) ? apiKeyScopedMissingResourceError(c, principal) : null;
if (apiKeyMissing) {
return apiKeyMissing;
}
return apiError(c, isMissingLegacyEntityError(normalizedError) ? 404 : 500, isMissingLegacyEntityError(normalizedError) ? "entity_not_found" : "entity_row_failed", isMissingLegacyEntityError(normalizedError) ? "Entity not found." : "Entity row could not be loaded.");
}
}
async function patchEntityRowRequest(c: Context<ApiEnv>) {
const principal = await authenticateServiceCredentialRequest(c);
if (!principal) {
return apiError(c, 401, "unauthorized", "A valid service credential is required.");
}
const routeParams = parseEntityRowRouteParams(c);
if (!routeParams.ok) {
return apiError(c, 400, "invalid_request", routeParams.error);
}
const body = await readJsonBody(c.req.raw);
const payload = parseEntityRowObjectBody(body);
if (!payload.ok) {
return apiError(c, 400, "invalid_json", payload.error.message, { params: payload.error.params });
}
const tenantResult = resolveTenantScope(c, principal);
if (!tenantResult.ok) {
return tenantResult.response;
}
try {
const dependencies = getApiAppDependencies();
const entity = await dependencies.findLegacyEntityByName({ tenantId: tenantResult.tenantId, name: routeParams.value.entityName, active: true });
const scope = authorizeApiEntityRowScope(principal, { tenantId: tenantResult.tenantId, entity, operation: "update" });
if (!scope.allowed) {
return forbiddenApiKeyScopeError(c);
}
return await runIdempotentJson(c, {
method: "PATCH",
route: "/v1/entities/:entity/rows/:rowId",
tenantId: tenantResult.tenantId,
entityId: getLegacyEntityId(entity),
rowId: routeParams.value.rowId,
parsedBody: toJsonValue(payload.value),
}, async () => {
const row = await dependencies.updateLegacyEntityRow({ entity: entity as LegacyEntityWithDetails, tenantId: tenantResult.tenantId, rowId: routeParams.value.rowId, data: payload.value });
void emitPluginHookFireAndForget(
PLUGIN_HOOK_ENTITY_UPDATED,
{
entityType: routeParams.value.entityName,
entityId: routeParams.value.rowId,
tenantId: tenantResult.tenantId,
userId: null,
changedFields: Object.keys(payload.value),
occurredAt: new Date().toISOString(),
},
{ tenantId: tenantResult.tenantId },
);
return { status: 200, body: row as never };
});
} catch (error) {
const normalizedError = normalizeUnknownError(error);
const missing = isMissingLegacyEntityError(normalizedError) || isMissingLegacyRowError(normalizedError);
const apiKeyMissing = missing ? apiKeyScopedMissingResourceError(c, principal) : null;
if (apiKeyMissing) {
return apiKeyMissing;
}
return apiError(c, missing ? 404 : 400, isMissingLegacyEntityError(normalizedError) ? "entity_not_found" : isMissingLegacyRowError(normalizedError) ? "row_not_found" : "entity_row_update_failed", isMissingLegacyEntityError(normalizedError) ? "Entity not found." : isMissingLegacyRowError(normalizedError) ? "Row not found." : "Entity row could not be updated.");
}
}
async function deleteEntityRowRequest(c: Context<ApiEnv>) {
const principal = await authenticateServiceCredentialRequest(c);
if (!principal) {
return apiError(c, 401, "unauthorized", "A valid service credential is required.");
}
const routeParams = parseEntityRowRouteParams(c);
if (!routeParams.ok) {
return apiError(c, 400, "invalid_request", routeParams.error);
}
const tenantResult = resolveTenantScope(c, principal);
if (!tenantResult.ok) {
return tenantResult.response;
}
try {
const dependencies = getApiAppDependencies();
const entity = await dependencies.findLegacyEntityByName({ tenantId: tenantResult.tenantId, name: routeParams.value.entityName, active: true });
const scope = authorizeApiEntityRowScope(principal, { tenantId: tenantResult.tenantId, entity, operation: "delete" });
if (!scope.allowed) {
return forbiddenApiKeyScopeError(c);
}
const entityId = getLegacyEntityId(entity);
return await runIdempotentJson(c, {
method: "DELETE",
route: "/v1/entities/:entity/rows/:rowId",
tenantId: tenantResult.tenantId,
entityId,
rowId: routeParams.value.rowId,
}, async () => {
const id = await dependencies.deleteLegacyEntityRow({ entityId, tenantId: tenantResult.tenantId, rowId: routeParams.value.rowId });
void emitPluginHookFireAndForget(
PLUGIN_HOOK_ENTITY_DELETED,
{
entityType: routeParams.value.entityName,
entityId: id,
tenantId: tenantResult.tenantId,
userId: null,
occurredAt: new Date().toISOString(),
},
{ tenantId: tenantResult.tenantId, dispatchKey: `entity:${routeParams.value.entityName}:${id}:deleted` },
);
return { status: 200, body: { success: true, id } };
});
} catch (error) {
const normalizedError = normalizeUnknownError(error);
const missing = isMissingLegacyEntityError(normalizedError) || isMissingLegacyRowError(normalizedError);
const apiKeyMissing = missing ? apiKeyScopedMissingResourceError(c, principal) : null;
if (apiKeyMissing) {
return apiKeyMissing;
}
return apiError(c, missing ? 404 : 500, isMissingLegacyEntityError(normalizedError) ? "entity_not_found" : isMissingLegacyRowError(normalizedError) ? "row_not_found" : "entity_row_delete_failed", isMissingLegacyEntityError(normalizedError) ? "Entity not found." : isMissingLegacyRowError(normalizedError) ? "Row not found." : "Entity row could not be deleted.");
}
}
async function getEntityRequest(c: Context<ApiEnv>) {
const principal = authenticateServiceRequest(c.req.raw, getApiRuntimeConfig());
if (!principal) {
return apiError(c, 401, "unauthorized", "A valid service credential is required.");
}
const entityName = c.req.param("entity");
if (!entityName) {
return apiError(c, 400, "invalid_request", "Expected entity.");
}
const tenantScope = parseOptionalTenantId(c);
if (!tenantScope.ok) {
return apiError(c, 400, "invalid_request", tenantScope.error);
}
if (!tenantScope.value) {
return missingApiTenantScopeError(c);
}
try {
const entity = await getApiAppDependencies().findLegacyEntityByName({ tenantId: tenantScope.value, name: entityName, active: true });
return c.json(entity as never);
} catch (error) {
const normalizedError = normalizeUnknownError(error);
return apiError(c, isMissingLegacyEntityError(normalizedError) ? 404 : 500, isMissingLegacyEntityError(normalizedError) ? "entity_not_found" : "entity_failed", isMissingLegacyEntityError(normalizedError) ? "Entity not found." : "Entity lookup failed.");
}
}
function resolveTenantScope(c: Context<ApiEnv>, principal: Awaited<ReturnType<typeof authenticateServiceCredentialRequest>>) {
const tenantScope = parseOptionalTenantId(c);
if (!tenantScope.ok) {
return { ok: false as const, response: apiError(c, 400, "invalid_request", tenantScope.error) };
}
const resolvedTenantScope = resolveApiTenantScope(principal!, tenantScope.value);
if (!resolvedTenantScope.allowed) {
return { ok: false as const, response: forbiddenApiKeyScopeError(c) };
}
const tenantId = resolvedTenantScope.tenantId;
if (!tenantId) {
return { ok: false as const, response: missingApiTenantScopeError(c) };
}
return { ok: true as const, tenantId };
}
@@ -1,4 +1,4 @@
import { authorizeStorageObjectAccess, authorizeStorageUploadConstraints } from "@toolctrl/storage";
import { authorizeStorageObjectAccess, authorizeStorageUploadConstraints } from "@hivegrid/storage";
import { Hono, type Context } from "hono";
import { getApiAppDependencies, type ExportJobDownloadRecord, type LegacyEventWebhookAttempt } from "../app-dependencies.js";
import type { ApiEnv } from "../api-types.js";
@@ -31,6 +31,8 @@ export function registerMaintenanceRoutes(app: Hono<ApiEnv>) {
postMailjetEmailSequenceWebhookRequest(c, {
webhookSecret: getApiRuntimeConfig().mailjet.webhookSecret,
markEmailSequenceDeliveryBounced: getApiAppDependencies().markEmailSequenceDeliveryBounced,
// AK-P14a: a bounce/complaint also suppresses the recipient (best-effort).
recordSuppression: getApiAppDependencies().recordSuppression,
})
);
app.post("/v1/events/webhooks/attempts/:id", postEventWebhookAttemptRequest);
@@ -1,6 +1,6 @@
import { describe, it, expect, beforeEach } from "vitest";
import { Hono } from "hono";
import { createDefaultMetrics, createMetricsRegistry, type DefaultMetrics, type MetricsRegistry } from "@toolctrl/metrics";
import { createDefaultMetrics, createMetricsRegistry, type DefaultMetrics, type MetricsRegistry } from "@hivegrid/metrics";
import { handleApiMetricsRequest } from "./metrics.js";
const TOKEN = "x".repeat(64);
@@ -5,13 +5,13 @@
* scanners.
*
* Auth: `Authorization: Bearer <METRICS_TOKEN>`. Constant-time compare via
* `@toolctrl/metrics`.
* `@hivegrid/metrics`.
*
* @see docs/improvement-plan/02-observability/metrics-grafana.md
*/
import type { Context } from "hono";
import { validateMetricsTokenAuth } from "@toolctrl/metrics";
import type { MetricsRegistry } from "@toolctrl/metrics";
import { validateMetricsTokenAuth } from "@hivegrid/metrics";
import type { MetricsRegistry } from "@hivegrid/metrics";
export type ApiMetricsRouteDependencies = {
enabled: boolean;
@@ -5,7 +5,7 @@ import {
redactNotificationGuardDiagnostic,
serializeRealtimeComment,
serializeRealtimeEvent,
} from "@toolctrl/realtime";
} from "@hivegrid/realtime";
import { Hono, type Context } from "hono";
import { getApiAppDependencies } from "../app-dependencies.js";
import type { ApiEnv } from "../api-types.js";
@@ -32,8 +32,8 @@ async function getNotificationStreamRequest(c: Context<ApiEnv>) {
return {
ok: true,
scope: normalizeNotificationStreamScope({
tenantId: c.req.header("x-toolctrl-tenant-id") ?? c.req.query("tenantId"),
userId: c.req.header("x-toolctrl-user-id") ?? c.req.query("userId"),
tenantId: c.req.header("x-hivegrid-tenant-id") ?? c.req.query("tenantId"),
userId: c.req.header("x-hivegrid-user-id") ?? c.req.query("userId"),
afterCursor: c.req.header("last-event-id") ?? c.req.query("afterCursor"),
}),
};
@@ -0,0 +1,398 @@
import { formatTenantApiUsagePlanTitle, SUBSCRIPTION_FEATURE_LIMIT } from "@hivegrid/db/usage.server";
import { verifyPublicApiSecret, verifyPublicWebhookHmacWithPresentedSecret, type PublicWebhookPayload } from "@hivegrid/db/public-api.server";
import { Hono, type Context } from "hono";
import { extractApiKeyFromRequest } from "../auth.js";
import { getApiRuntimeConfig } from "../config.js";
import { getTrustedClientIp } from "../trusted-client-ip.js";
import { apiError } from "../middleware/error-envelope.js";
import type { ApiEnv } from "../api-types.js";
import type { ApiAppDependencies } from "../app-dependencies.js";
import { getApiAppDependencies } from "../app-dependencies.js";
import { checkPublicApiRateLimit, checkPublicApiScopes, publicApiReadScopeForResource, type PublicApiRateLimitResult } from "../public-api/auth.js";
import { parsePublicApiListQuery, publicApiResources, type PublicApiResourceName } from "../public-api/resources.js";
type PublicApiRouteDependencies = Pick<
ApiAppDependencies,
| "findLegacyApiKeyByKey"
| "createLegacyApiKeyLog"
| "setLegacyApiKeyLogStatus"
| "createUniqueLegacyTenantIpAddress"
| "getTenantSubscription"
| "getTenantApiUsage"
| "listPublicApiResource"
| "findLegacyTenantByIdOrSlug"
| "findPublicIncomingWebhookEndpoint"
| "createPublicWebhookIngestionLog"
| "ingestPublicLeadWebhook"
>;
export function registerPublicApiReadRoutes(app: Hono<ApiEnv>) {
app.get("/v1/contacts", (c) => getPublicApiResourceRequest(c, "contacts"));
app.get("/v1/companies", (c) => getPublicApiResourceRequest(c, "companies"));
app.get("/v1/deals", (c) => getPublicApiResourceRequest(c, "deals"));
app.get("/v1/projects", (c) => getPublicApiResourceRequest(c, "projects"));
app.get("/v1/tasks", (c) => getPublicApiResourceRequest(c, "tasks"));
app.get("/v1/leads", (c) => getPublicApiResourceRequest(c, "leads"));
app.post("/v1/webhooks/incoming/:tenant/:slug", (c) => postPublicIncomingWebhookRequest(c));
}
async function getPublicApiResourceRequest(c: Context<ApiEnv>, resource: PublicApiResourceName) {
const dependencies = getApiAppDependencies();
const endpoint = new URL(c.req.url).pathname;
const startTime = performance.now();
const apiKeyValue = extractApiKeyFromRequest(c.req.raw, undefined);
if (!apiKeyValue) {
await createPublicApiErrorLog(c, dependencies, endpoint, "Missing API key", 401);
return apiError(c, 401, "unauthorized", "Valid API key credentials are required.");
}
const apiKey = await dependencies.findLegacyApiKeyByKey(apiKeyValue, undefined as never, getApiRuntimeConfig().jwtSecret, {
allowPlaintextFallback: getApiRuntimeConfig().apiKeys.allowLegacyPlaintextFallback,
});
if (!apiKey) {
await createPublicApiErrorLog(c, dependencies, endpoint, "Invalid API key", 401);
return apiError(c, 401, "unauthorized", "Valid API key credentials are required.");
}
const apiKeyLog = await dependencies.createLegacyApiKeyLog({
tenantId: apiKey.tenantId,
apiKeyId: apiKey.id,
endpoint,
ip: getClientIpAddress(c.req.raw) ?? "",
method: c.req.method,
params: serializeRequestSearchParams(c.req.raw),
alias: apiKey.alias,
tenantName: apiKey.tenant.name,
});
const fail = async (status: 400 | 402 | 403 | 429 | 500, code: string, message: string, params?: Record<string, string | number | boolean | null>) => {
await dependencies.setLegacyApiKeyLogStatus({ id: apiKeyLog.id, tenantId: apiKey.tenantId }, { status, error: message, startTime });
return params ? apiError(c, status, code, message, { params }) : apiError(c, status, code, message);
};
if (apiKey.tenant.deactivatedReason) {
return fail(403, "tenant_inactive", "Account is inactive.");
}
if (!apiKey.active) {
return fail(400, "api_key_inactive", "API key is inactive.");
}
if (apiKey.expires && apiKey.expires < new Date()) {
return fail(400, "api_key_expired", "API key is expired.");
}
const scopeCheck = checkPublicApiScopes(apiKey.scopes, [publicApiReadScopeForResource(resource)]);
if (!scopeCheck.ok) {
return fail(scopeCheck.status, scopeCheck.code, scopeCheck.message, { requiredScopes: scopeCheck.requiredScopes.join(",") });
}
const rateLimit = await checkPublicApiRateLimit({ apiKeyId: apiKey.id, tenantId: apiKey.tenantId });
applyRateLimitHeaders(c, rateLimit);
if (!rateLimit.allowed) {
return fail(rateLimit.status, rateLimit.code, rateLimit.message);
}
const query = parsePublicApiListQuery(publicApiResources[resource], new URL(c.req.url).searchParams);
if (!query.ok) {
return fail(400, query.code, query.message, query.params);
}
await dependencies
.createUniqueLegacyTenantIpAddress({
ip: getClientIpAddress(c.req.raw) ?? "Unknown",
fromUrl: endpoint,
tenantId: apiKey.tenantId,
apiKeyId: apiKey.id,
})
.catch(() => undefined);
const tenantSubscription = await dependencies.getTenantSubscription(apiKey.tenantId);
const usage = await dependencies.getTenantApiUsage(apiKey.tenantId, tenantSubscription);
if (!usage?.enabled) {
return fail(402, "payment_required", "Public API access is disabled or exhausted for this tenant.", {
plan: usage ? formatTenantApiUsagePlanTitle(usage) : "API access not included",
remaining: usage ? (usage.type === SUBSCRIPTION_FEATURE_LIMIT.included ? "included" : String(usage.remaining)) : "0",
});
}
try {
const result = await dependencies.listPublicApiResource({ tenantId: apiKey.tenantId, resource, query: query.value });
await dependencies.setLegacyApiKeyLogStatus({ id: apiKeyLog.id, tenantId: apiKey.tenantId }, { status: 200, startTime });
return c.json({
data: result.data,
pageInfo: result.pageInfo,
meta: {
resource,
readOnly: true,
requestId: c.get("requestId"),
},
});
} catch {
return fail(500, "public_api_read_failed", "Public API read request failed.");
}
}
async function createPublicApiErrorLog(
c: Context<ApiEnv>,
dependencies: Pick<PublicApiRouteDependencies, "createLegacyApiKeyLog">,
endpoint: string,
error: string,
status: number
) {
await dependencies.createLegacyApiKeyLog({
tenantId: null,
apiKeyId: null,
endpoint,
ip: getClientIpAddress(c.req.raw) ?? "",
method: c.req.method,
params: serializeRequestSearchParams(c.req.raw),
error,
status,
});
}
function getClientIpAddress(request: Request) {
// Trusted proxy-set header only; leftmost X-Forwarded-For is client-spoofable.
return getTrustedClientIp(request);
}
function serializeRequestSearchParams(request: Request) {
return new URL(request.url).searchParams.toString();
}
function applyRateLimitHeaders(c: Context<ApiEnv>, result: PublicApiRateLimitResult) {
for (const [name, value] of Object.entries(result.headers)) {
c.header(name, value);
}
if (!result.allowed) {
const resetAt = Number.parseInt(result.headers["X-RateLimit-Reset"] ?? "0", 10);
if (Number.isFinite(resetAt) && resetAt > 0) {
c.header("Retry-After", String(Math.max(1, resetAt - Math.floor(Date.now() / 1000))));
}
}
}
async function postPublicIncomingWebhookRequest(c: Context<ApiEnv>) {
const dependencies = getApiAppDependencies();
const startTime = performance.now();
const tenantParam = c.req.param("tenant");
const slug = c.req.param("slug");
if (!tenantParam || !slug) {
return apiError(c, 404, "not_found", "Webhook endpoint was not found.");
}
const tenant = await dependencies.findLegacyTenantByIdOrSlug(tenantParam);
if (!tenant) {
return apiError(c, 404, "not_found", "Webhook endpoint was not found.");
}
const endpoint = await dependencies.findPublicIncomingWebhookEndpoint({ tenantId: tenant.id, slug });
if (!endpoint || endpoint.status !== "active") {
await createWebhookIngestionFailure(dependencies, {
tenantId: tenant.id,
endpointId: endpoint?.id ?? null,
endpointSlug: slug,
authMode: endpoint?.authMode ?? null,
requestId: c.get("requestId"),
sourceIp: getClientIpAddress(c.req.raw),
status: 404,
result: "endpoint_not_found",
error: "Webhook endpoint was not found.",
});
return apiError(c, 404, "not_found", "Webhook endpoint was not found.");
}
const rawBody = await c.req.text();
const parsedBody = parseWebhookJsonBody(rawBody);
if (!parsedBody.ok) {
await createWebhookIngestionFailure(dependencies, {
tenantId: tenant.id,
endpointId: endpoint.id,
endpointSlug: endpoint.slug,
authMode: endpoint.authMode,
requestId: c.get("requestId"),
sourceIp: getClientIpAddress(c.req.raw),
status: 400,
result: "invalid_json",
error: parsedBody.message,
});
return apiError(c, 400, "invalid_json", parsedBody.message);
}
const tenantSubscription = await dependencies.getTenantSubscription(tenant.id);
if (isTenantWriteBlocked(tenantSubscription)) {
return apiError(c, 402, "payment_required", "Account is read-only. Webhook writes are blocked until billing is resolved.");
}
const usage = await dependencies.getTenantApiUsage(tenant.id, tenantSubscription);
if (!usage?.enabled) {
return apiError(c, 402, "payment_required", "Public API access is disabled or exhausted for this tenant.", {
params: {
plan: usage ? formatTenantApiUsagePlanTitle(usage) : "API access not included",
remaining: usage ? (usage.type === SUBSCRIPTION_FEATURE_LIMIT.included ? "included" : String(usage.remaining)) : "0",
},
});
}
const authResult = await authenticateIncomingWebhookRequest(c, endpoint, rawBody, dependencies);
if (!authResult.ok) {
if (authResult.rateLimit) {
applyRateLimitHeaders(c, authResult.rateLimit);
}
if (authResult.apiKeyLogId) {
await dependencies.setLegacyApiKeyLogStatus(
{ id: authResult.apiKeyLogId, tenantId: tenant.id },
{ status: authResult.status, error: authResult.message, startTime }
);
}
await createWebhookIngestionFailure(dependencies, {
tenantId: tenant.id,
endpointId: endpoint.id,
endpointSlug: endpoint.slug,
authMode: endpoint.authMode,
requestId: c.get("requestId"),
sourceIp: getClientIpAddress(c.req.raw),
status: authResult.status,
result: authResult.code,
error: authResult.message,
});
return apiError(c, authResult.status, authResult.code, authResult.message);
}
if (authResult.rateLimit) {
applyRateLimitHeaders(c, authResult.rateLimit);
if (!authResult.rateLimit.allowed) {
return apiError(c, authResult.rateLimit.status, authResult.rateLimit.code, authResult.rateLimit.message);
}
}
try {
const result = await dependencies.ingestPublicLeadWebhook({
tenantId: tenant.id,
endpoint,
payload: parsedBody.value,
requestId: c.get("requestId"),
sourceIp: getClientIpAddress(c.req.raw),
});
if (authResult.apiKeyLogId) {
await dependencies.setLegacyApiKeyLogStatus({ id: authResult.apiKeyLogId, tenantId: tenant.id }, { status: 201, startTime });
}
return c.json(
{
data: {
leadId: result.lead.id,
matchedKontaktId: result.matchedKontaktId,
automationExecutionIds: result.automationExecutionIds,
},
meta: {
requestId: c.get("requestId"),
endpoint: endpoint.slug,
},
},
201
);
} catch {
if (authResult.apiKeyLogId) {
await dependencies.setLegacyApiKeyLogStatus(
{ id: authResult.apiKeyLogId, tenantId: tenant.id },
{ status: 500, error: "Webhook ingestion failed.", startTime }
);
}
return apiError(c, 500, "webhook_ingestion_failed", "Webhook ingestion failed.");
}
}
async function authenticateIncomingWebhookRequest(
c: Context<ApiEnv>,
endpoint: Awaited<ReturnType<PublicApiRouteDependencies["findPublicIncomingWebhookEndpoint"]>> & {},
rawBody: string,
dependencies: PublicApiRouteDependencies
): Promise<
| { ok: true; rateLimit?: PublicApiRateLimitResult; apiKeyLogId?: string }
| { ok: false; status: 401 | 403 | 429; code: string; message: string; rateLimit?: PublicApiRateLimitResult; apiKeyLogId?: string }
> {
if (endpoint.authMode === "url_token") {
const token = c.req.header("X-HiveGrid-Webhook-Token") ?? new URL(c.req.url).searchParams.get("token");
if (!verifyPublicApiSecret(token ?? "", endpoint.tokenHash)) {
return { ok: false, status: 401, code: "unauthorized", message: "Valid webhook token is required." };
}
const rateLimit = await checkPublicApiRateLimit({ apiKeyId: endpoint.id, tenantId: endpoint.tenantId });
return rateLimit.allowed ? { ok: true, rateLimit } : { ok: false, status: rateLimit.status, code: rateLimit.code, message: rateLimit.message, rateLimit };
}
if (endpoint.authMode === "hmac") {
const valid = verifyPublicWebhookHmacWithPresentedSecret({
body: rawBody,
timestamp: c.req.header("X-HiveGrid-Timestamp") ?? null,
signature: c.req.header("X-HiveGrid-Signature") ?? null,
presentedSecret: c.req.header("X-HiveGrid-Webhook-Token") ?? null,
secretHash: endpoint.hmacSecretHash,
});
if (!valid) {
return { ok: false, status: 401, code: "unauthorized", message: "Valid webhook HMAC signature is required." };
}
const rateLimit = await checkPublicApiRateLimit({ apiKeyId: endpoint.id, tenantId: endpoint.tenantId });
return rateLimit.allowed ? { ok: true, rateLimit } : { ok: false, status: rateLimit.status, code: rateLimit.code, message: rateLimit.message, rateLimit };
}
const apiKeyValue = extractApiKeyFromRequest(c.req.raw, undefined);
if (!apiKeyValue) {
return { ok: false, status: 401, code: "unauthorized", message: "Valid API key credentials are required." };
}
const apiKey = await dependencies.findLegacyApiKeyByKey(apiKeyValue, undefined as never, getApiRuntimeConfig().jwtSecret, {
allowPlaintextFallback: getApiRuntimeConfig().apiKeys.allowLegacyPlaintextFallback,
});
if (!apiKey || apiKey.tenantId !== endpoint.tenantId || (endpoint.apiKeyId && endpoint.apiKeyId !== apiKey.id)) {
return { ok: false, status: 401, code: "unauthorized", message: "Valid API key credentials are required." };
}
const apiKeyLog = await dependencies.createLegacyApiKeyLog({
tenantId: apiKey.tenantId,
apiKeyId: apiKey.id,
endpoint: new URL(c.req.url).pathname,
ip: getClientIpAddress(c.req.raw) ?? "",
method: c.req.method,
params: serializeRequestSearchParams(c.req.raw),
alias: apiKey.alias,
tenantName: apiKey.tenant.name,
});
if (!apiKey.active) {
return { ok: false, status: 401, code: "unauthorized", message: "API key is inactive.", apiKeyLogId: apiKeyLog.id };
}
if (apiKey.expires && apiKey.expires < new Date()) {
return { ok: false, status: 401, code: "unauthorized", message: "API key is expired.", apiKeyLogId: apiKeyLog.id };
}
const scopeCheck = checkPublicApiScopes(apiKey.scopes, ["public_api:webhooks:incoming"]);
if (!scopeCheck.ok) {
return { ok: false, status: scopeCheck.status, code: scopeCheck.code, message: scopeCheck.message, apiKeyLogId: apiKeyLog.id };
}
const rateLimit = await checkPublicApiRateLimit({ apiKeyId: apiKey.id, tenantId: endpoint.tenantId });
return rateLimit.allowed
? { ok: true, rateLimit, apiKeyLogId: apiKeyLog.id }
: { ok: false, status: rateLimit.status, code: rateLimit.code, message: rateLimit.message, rateLimit, apiKeyLogId: apiKeyLog.id };
}
async function createWebhookIngestionFailure(
dependencies: Pick<PublicApiRouteDependencies, "createPublicWebhookIngestionLog">,
data: Parameters<PublicApiRouteDependencies["createPublicWebhookIngestionLog"]>[0]
) {
await dependencies.createPublicWebhookIngestionLog(data).catch(() => undefined);
}
function parseWebhookJsonBody(rawBody: string): { ok: true; value: PublicWebhookPayload } | { ok: false; message: string } {
try {
const parsed = JSON.parse(rawBody || "{}") as PublicWebhookPayload;
if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
return { ok: false, message: "Webhook payload must be a JSON object." };
}
return { ok: true, value: parsed };
} catch {
return { ok: false, message: "Webhook payload must be valid JSON." };
}
}
function isTenantWriteBlocked(subscription: Awaited<ReturnType<PublicApiRouteDependencies["getTenantSubscription"]>>): boolean {
return Boolean(
subscription?.frozenAt ||
subscription?.pastDueSince ||
subscription?.cancelledAt ||
subscription?.status === "past_due" ||
subscription?.status === "frozen" ||
subscription?.status === "cancelled"
);
}
@@ -1,233 +0,0 @@
import { Hono, type Context } from "hono";
import { getApiAppDependencies, type LegacyRelationshipRow } from "../app-dependencies.js";
import type { ApiEnv } from "../api-types.js";
import { authorizeApiRelationshipScope } from "../auth/permission.js";
import { resolveApiTenantScope } from "../auth/scope.js";
import { apiError } from "../middleware/error-envelope.js";
import { parseRelationshipCreatePayload } from "../validation/request-schemas.js";
import {
ApiRouteError,
apiKeyScopedMissingResourceError,
authenticateServiceCredentialRequest,
forbiddenApiKeyScopeError,
parseOptionalTenantId,
readJsonBody,
runIdempotentJson,
toRelationshipEnvelope,
} from "./shared.js";
export function registerRelationshipRoutes(app: Hono<ApiEnv>) {
app.post("/v1/relationships", postRelationshipRequest);
app.get("/v1/relationships/:id", getRelationshipRequest);
app.delete("/v1/relationships/:id", deleteRelationshipRequest);
}
async function postRelationshipRequest(c: Context<ApiEnv>) {
const principal = await authenticateServiceCredentialRequest(c);
if (!principal) {
return apiError(c, 401, "unauthorized", "A valid service credential is required.");
}
const body = await readJsonBody(c.req.raw);
const payload = parseRelationshipCreatePayload(body);
if (!payload.ok) {
return apiError(c, 400, "invalid_request", payload.error.message, { params: payload.error.params });
}
const tenantResult = resolveRelationshipTenantScope(c, principal);
if (!tenantResult.ok) {
return tenantResult.response;
}
try {
const dependencies = getApiAppDependencies();
const parent = await dependencies.findLegacyRelationshipRowById({ id: payload.value.parent, tenantId: tenantResult.tenantId });
if (!parent) {
const apiKeyMissing = apiKeyScopedMissingResourceError(c, principal);
return apiKeyMissing ?? apiError(c, 404, "parent_row_not_found", "Parent row not found.", { params: { rowId: payload.value.parent } });
}
const child = await dependencies.findLegacyRelationshipRowById({ id: payload.value.child, tenantId: tenantResult.tenantId });
if (!child) {
const apiKeyMissing = apiKeyScopedMissingResourceError(c, principal);
return apiKeyMissing ?? apiError(c, 404, "child_row_not_found", "Child row not found.", { params: { rowId: payload.value.child } });
}
if (!relationshipRowsBelongToTenant(tenantResult.tenantId, parent, child)) {
const apiKeyMissing = apiKeyScopedMissingResourceError(c, principal);
return apiKeyMissing ?? apiError(c, 404, "relationship_rows_not_found", "Relationship rows not found.");
}
const scope = authorizeApiRelationshipScope(principal, { tenantId: tenantResult.tenantId, parentEntityId: parent.entityId, childEntityId: child.entityId, operation: "create" });
if (!scope.allowed) {
return forbiddenApiKeyScopeError(c);
}
return await runIdempotentJson(c, {
method: "POST",
route: "/v1/relationships",
tenantId: tenantResult.tenantId,
entityId: parent.entityId,
relationshipId: `${parent.id}:${child.id}`,
parsedBody: payload.value,
}, async () => {
const entityRelationship = await dependencies.findLegacyEntityRelationship({ parentId: parent.entityId, childId: child.entityId });
if (!entityRelationship) {
throw new ApiRouteError(404, "entity_relationship_not_found", "Entity relationship not found.");
}
const relationship = await dependencies.createLegacyRowRelationship({
relationshipId: entityRelationship.id,
parentId: parent.id,
childId: child.id,
tenantId: tenantResult.tenantId,
});
return { status: 201, body: { relationship: toRelationshipEnvelope(relationship, parent, child) } };
});
} catch (error) {
if (error instanceof ApiRouteError) {
return apiError(c, error.status, error.code, error.message, { params: error.params });
}
return apiError(c, 500, "relationship_create_failed", "Relationship could not be created.");
}
}
function relationshipRowsBelongToTenant(tenantId: string | null, ...rows: LegacyRelationshipRow[]) {
return Boolean(tenantId) && rows.every((row) => row.tenantId === tenantId);
}
async function getRelationshipRequest(c: Context<ApiEnv>) {
const principal = await authenticateServiceCredentialRequest(c);
if (!principal) {
return apiError(c, 401, "unauthorized", "A valid service credential is required.");
}
const id = c.req.param("id");
if (!id) {
return apiError(c, 400, "invalid_request", "Expected relationship id.");
}
const tenantResult = resolveRelationshipTenantScope(c, principal);
if (!tenantResult.ok) {
return tenantResult.response;
}
try {
const dependencies = getApiAppDependencies();
const relationship = await dependencies.findLegacyRowRelationshipById(id, tenantResult.tenantId);
if (!relationship) {
const apiKeyMissing = apiKeyScopedMissingResourceError(c, principal);
return apiKeyMissing ?? apiError(c, 404, "relationship_not_found", "Relationship not found.", { params: { relationshipId: id } });
}
const scope = authorizeApiRelationshipScope(principal, {
tenantId: tenantResult.tenantId,
parentEntityId: relationship.relationship.parentId,
childEntityId: relationship.relationship.childId,
operation: "read",
});
if (!scope.allowed) {
return forbiddenApiKeyScopeError(c);
}
const [parent, child] = await Promise.all([
dependencies.getLegacyEntityRow({ entityId: relationship.relationship.parentId, tenantId: tenantResult.tenantId, rowId: relationship.parentId }),
dependencies.getLegacyEntityRow({ entityId: relationship.relationship.childId, tenantId: tenantResult.tenantId, rowId: relationship.childId }),
]);
if (!parent) {
const apiKeyMissing = apiKeyScopedMissingResourceError(c, principal);
return apiKeyMissing ?? apiError(c, 404, "parent_row_not_found", "Parent row not found.", { params: { rowId: relationship.parentId } });
}
if (!child) {
const apiKeyMissing = apiKeyScopedMissingResourceError(c, principal);
return apiKeyMissing ?? apiError(c, 404, "child_row_not_found", "Child row not found.", { params: { rowId: relationship.childId } });
}
return c.json({ relationship: toRelationshipEnvelope(relationship, parent, child) });
} catch {
return apiError(c, 500, "relationship_get_failed", "Relationship could not be loaded.");
}
}
async function deleteRelationshipRequest(c: Context<ApiEnv>) {
const principal = await authenticateServiceCredentialRequest(c);
if (!principal) {
return apiError(c, 401, "unauthorized", "A valid service credential is required.");
}
const id = c.req.param("id");
if (!id) {
return apiError(c, 400, "invalid_request", "Expected relationship id.");
}
const tenantResult = resolveRelationshipTenantScope(c, principal);
if (!tenantResult.ok) {
return tenantResult.response;
}
try {
const dependencies = getApiAppDependencies();
const relationship = await dependencies.findLegacyRowRelationshipById(id, tenantResult.tenantId);
if (!relationship) {
const apiKeyMissing = apiKeyScopedMissingResourceError(c, principal);
return apiKeyMissing ?? apiError(c, 404, "relationship_not_found", "Relationship not found.", { params: { relationshipId: id } });
}
const scope = authorizeApiRelationshipScope(principal, {
tenantId: tenantResult.tenantId,
parentEntityId: relationship.relationship.parentId,
childEntityId: relationship.relationship.childId,
operation: "delete",
});
if (!scope.allowed) {
return forbiddenApiKeyScopeError(c);
}
const [parent, child] = await Promise.all([
dependencies.getLegacyEntityRow({ entityId: relationship.relationship.parentId, tenantId: tenantResult.tenantId, rowId: relationship.parentId }),
dependencies.getLegacyEntityRow({ entityId: relationship.relationship.childId, tenantId: tenantResult.tenantId, rowId: relationship.childId }),
]);
if (!parent) {
const apiKeyMissing = apiKeyScopedMissingResourceError(c, principal);
return apiKeyMissing ?? apiError(c, 404, "parent_row_not_found", "Parent row not found.", { params: { rowId: relationship.parentId } });
}
if (!child) {
const apiKeyMissing = apiKeyScopedMissingResourceError(c, principal);
return apiKeyMissing ?? apiError(c, 404, "child_row_not_found", "Child row not found.", { params: { rowId: relationship.childId } });
}
return await runIdempotentJson(c, {
method: "DELETE",
route: "/v1/relationships/:id",
tenantId: tenantResult.tenantId,
entityId: parent.entityId,
relationshipId: id,
}, async () => {
await dependencies.deleteLegacyRowRelationshipById({
id,
relationshipId: relationship.relationshipId,
parentId: relationship.parentId,
childId: relationship.childId,
tenantId: tenantResult.tenantId,
});
return { status: 200, body: { deleted: toRelationshipEnvelope(relationship, parent, child) } };
});
} catch {
return apiError(c, 500, "relationship_delete_failed", "Relationship could not be deleted.");
}
}
function resolveRelationshipTenantScope(c: Context<ApiEnv>, principal: Awaited<ReturnType<typeof authenticateServiceCredentialRequest>>) {
const tenantScope = parseOptionalTenantId(c);
if (!tenantScope.ok) {
return { ok: false as const, response: apiError(c, 400, "invalid_request", tenantScope.error) };
}
const resolvedTenantScope = resolveApiTenantScope(principal!, tenantScope.value);
if (!resolvedTenantScope.allowed) {
return { ok: false as const, response: forbiddenApiKeyScopeError(c) };
}
const tenantId = resolvedTenantScope.tenantId;
if (!tenantId) {
return { ok: false as const, response: apiError(c, 400, "invalid_request", "tenantId is required.") };
}
return { ok: true as const, tenantId };
}
@@ -1,9 +1,9 @@
import type { Context } from "hono";
import jwt from "jsonwebtoken";
import { WorkspaceContextRevalidationError } from "@toolctrl/db/auth-providers.server";
import { WorkspaceInviteError, type WorkspaceInviteStatus } from "@toolctrl/db/workspace-invites.server";
import type { StorageObjectStatus } from "@toolctrl/storage";
import type { LegacyEntity, LegacyEntityRow, LegacyRelationshipRow, LegacyRowRelationshipDetails, WorkspaceAuthProviderDto, WorkspaceInviteDto } from "../app-dependencies.js";
import { WorkspaceContextRevalidationError } from "@hivegrid/db/auth-providers.server";
import { WorkspaceInviteError, type WorkspaceInviteStatus } from "@hivegrid/db/workspace-invites.server";
import type { StorageObjectStatus } from "@hivegrid/storage";
import type { WorkspaceAuthProviderDto, WorkspaceInviteDto } from "../app-dependencies.js";
import { getApiAppDependencies } from "../app-dependencies.js";
import type { ApiEnv, ParseResult } from "../api-types.js";
import { authenticateServiceRequest, createServicePrincipal, extractBearerToken, isValidServiceToken } from "../auth.js";
@@ -344,37 +344,6 @@ export function parseOptionalTenantId(c: Context<ApiEnv>): ParseResult<string |
return { ok: true, value: tenantScopes[0]?.value ?? null };
}
export function parseEntityRowRouteParams(c: Context<ApiEnv>): ParseResult<{ entityName: string; rowId: string }> {
const entityName = c.req.param("entity");
if (!entityName) {
return { ok: false, error: "Expected entity." };
}
const rowId = c.req.param("rowId");
if (!rowId) {
return { ok: false, error: "Expected rowId." };
}
return { ok: true, value: { entityName, rowId } };
}
export function getLegacyEntityId(entity: LegacyEntity) {
if (entity && typeof entity === "object" && "id" in entity && typeof entity.id === "string" && entity.id) {
return entity.id;
}
throw new Error("Entity is missing an id.");
}
export function isMissingLegacyEntityError(error: Error) {
return /entity with name .+ not found/i.test(error.message);
}
export function isMissingLegacyRowError(error: Error) {
return /^Row .+ not found$/.test(error.message);
}
export function toRelationshipEnvelope(relationship: LegacyRowRelationshipDetails, parent: LegacyRelationshipRow | LegacyEntityRow, child: LegacyRelationshipRow | LegacyEntityRow): JsonValue {
return toJsonValue({ id: relationship.id, parent, child });
}
export function toJsonValue(value: unknown): JsonValue {
return JSON.parse(JSON.stringify(value)) as JsonValue;
}
@@ -58,29 +58,163 @@ export function registerSystemRoutes(app: Hono<ApiEnv>) {
<meta property="og:title" content="API Documentation | ${escapeHtml(appName)}">
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
:root { color-scheme: dark; }
body { margin: 0; background: #0f172a; color: #e2e8f0; font-family: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
header { border-bottom: 1px solid #334155; padding: 20px 24px; }
main { padding: 24px; }
main { display: grid; grid-template-columns: minmax(220px, 320px) minmax(0, 1fr); gap: 24px; padding: 24px; }
a { color: #93c5fd; }
button { border: 1px solid #475569; border-radius: 8px; background: #1e293b; color: #e2e8f0; cursor: pointer; font: inherit; padding: 8px 10px; text-align: left; }
button:hover, button[aria-current="true"] { border-color: #38bdf8; background: #0c4a6e; }
code, pre { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; }
pre { margin: 0; overflow: auto; border: 1px solid #334155; border-radius: 8px; background: #020617; padding: 16px; line-height: 1.5; }
.toolbar { display: flex; align-items: center; gap: 16px; flex-wrap: wrap; }
.muted { color: #94a3b8; }
.nav { display: grid; gap: 8px; align-content: start; }
.operation { border: 1px solid #334155; border-radius: 8px; background: #111827; overflow: hidden; }
.operation-header { display: flex; align-items: center; gap: 10px; border-bottom: 1px solid #334155; padding: 14px 16px; }
.method { border-radius: 999px; background: #0284c7; color: white; font-size: 12px; font-weight: 700; letter-spacing: .04em; padding: 4px 8px; }
.path { font-size: 18px; font-weight: 700; }
.section { padding: 16px; }
.grid { display: grid; gap: 10px; }
.row { display: grid; grid-template-columns: 180px minmax(0, 1fr); gap: 12px; border-top: 1px solid #1f2937; padding-top: 10px; }
.row:first-child { border-top: 0; padding-top: 0; }
.badge { display: inline-flex; width: fit-content; border-radius: 999px; background: #1e293b; color: #bae6fd; padding: 2px 8px; font-size: 12px; }
.try-grid { display: grid; gap: 10px; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; align-items: end; }
label { display: grid; gap: 6px; color: #cbd5e1; font-size: 13px; }
input { border: 1px solid #475569; border-radius: 8px; background: #020617; color: #e2e8f0; font: inherit; padding: 9px 10px; }
#try-result { min-height: 120px; }
#raw-panel { margin-top: 16px; }
@media (max-width: 780px) { main { grid-template-columns: 1fr; } .row, .try-grid { grid-template-columns: 1fr; } }
</style>
</head>
<body>
<header>
<h1>API Documentation</h1>
<a href="/v1/openapi.json">OpenAPI JSON</a>
<div class="toolbar">
<span class="muted">Swagger-style OpenAPI 3.1 explorer for the canonical API host.</span>
<a href="/v1/openapi.json">OpenAPI JSON</a>
</div>
</header>
<main>
<pre id="openapi">Loading /v1/openapi.json...</pre>
<nav class="nav" id="operation-nav" aria-label="API operations">
<span class="muted">Loading /v1/openapi.json...</span>
</nav>
<section>
<div id="operation-detail" class="operation"></div>
<details id="raw-panel">
<summary>Raw OpenAPI JSON</summary>
<pre id="openapi-json"></pre>
</details>
</section>
</main>
<script>
const nav = document.getElementById("operation-nav");
const detail = document.getElementById("operation-detail");
const raw = document.getElementById("openapi-json");
let currentEntry = null;
function escapeText(value) {
return String(value ?? "").replace(/[&<>"']/g, (character) => ({
"&": "&amp;",
"<": "&lt;",
">": "&gt;",
'"': "&quot;",
"'": "&#039;",
}[character]));
}
function operationEntries(spec) {
return Object.entries(spec.paths ?? {}).flatMap(([path, pathItem]) =>
Object.entries(pathItem ?? {})
.filter(([method]) => ["get", "post", "put", "patch", "delete"].includes(method))
.map(([method, operation]) => ({ path, method: method.toUpperCase(), operation }))
);
}
function renderNav(entries) {
nav.innerHTML = "";
for (const entry of entries) {
const button = document.createElement("button");
button.type = "button";
button.dataset.path = entry.path;
button.dataset.method = entry.method;
button.innerHTML = '<span class="method">' + escapeText(entry.method) + '</span> ' + escapeText(entry.path);
button.addEventListener("click", () => renderOperation(entry, button));
nav.appendChild(button);
}
}
function renderOperation(entry, activeButton) {
currentEntry = entry;
for (const button of nav.querySelectorAll("button")) {
button.removeAttribute("aria-current");
}
activeButton?.setAttribute("aria-current", "true");
const parameters = entry.operation.parameters ?? [];
const responses = Object.entries(entry.operation.responses ?? {});
detail.innerHTML = '<div class="operation-header"><span class="method">' + escapeText(entry.method) + '</span><span class="path">' + escapeText(entry.path) + '</span></div>'
+ '<div class="section grid">'
+ '<span class="badge">' + escapeText(entry.operation.operationId ?? "operation") + '</span>'
+ '<p>' + escapeText(entry.operation.description ?? "No description.") + '</p>'
+ '<h2>Parameters</h2>'
+ (parameters.length ? parameters.map((parameter) => '<div class="row"><code>' + escapeText(parameter.in) + ' ' + escapeText(parameter.name) + '</code><span>' + escapeText(parameter.description ?? "") + '</span></div>').join("") : '<p class="muted">No parameters.</p>')
+ '<h2>Responses</h2>'
+ (responses.length ? responses.map(([status, response]) => '<div class="row"><code>' + escapeText(status) + '</code><span>' + escapeText(response.description ?? "") + '</span></div>').join("") : '<p class="muted">No documented responses.</p>')
+ '<h2>Try request</h2>'
+ '<div class="try-grid">'
+ '<label>x-api-key<input id="try-api-key" type="password" autocomplete="off" placeholder="Paste tenant API key"></label>'
+ '<label>Query string<input id="try-query" type="text" placeholder="limit=10&fields=id,name"></label>'
+ '<button id="try-button" type="button">Send request</button>'
+ '</div>'
+ '<pre id="try-result" aria-live="polite">Response appears here.</pre>'
+ '</div>';
document.getElementById("try-button")?.addEventListener("click", sendTryRequest);
}
function buildTryRequestUrl(entry) {
const query = document.getElementById("try-query")?.value.trim() ?? "";
if (!query) {
return entry.path;
}
return entry.path + (query.startsWith("?") ? query : "?" + query);
}
function sendTryRequest() {
if (!currentEntry) {
return;
}
const result = document.getElementById("try-result");
const apiKey = document.getElementById("try-api-key")?.value.trim() ?? "";
result.textContent = "Loading...";
fetch(buildTryRequestUrl(currentEntry), {
method: currentEntry.method,
headers: apiKey ? { "x-api-key": apiKey } : {},
})
.then(async (response) => {
const text = await response.text();
try {
result.textContent = response.status + " " + response.statusText + "\\n" + JSON.stringify(JSON.parse(text), null, 2);
} catch {
result.textContent = response.status + " " + response.statusText + "\\n" + text;
}
})
.catch((error) => {
result.textContent = error.message;
});
}
fetch("/v1/openapi.json")
.then((response) => response.json())
.then((spec) => {
document.getElementById("openapi").textContent = JSON.stringify(spec, null, 2);
const entries = operationEntries(spec);
raw.textContent = JSON.stringify(spec, null, 2);
renderNav(entries);
if (entries[0]) {
renderOperation(entries[0], nav.querySelector("button"));
}
})
.catch((error) => {
document.getElementById("openapi").textContent = error.message;
nav.innerHTML = '<span class="muted">' + escapeText(error.message) + '</span>';
});
</script>
</body>
@@ -12,7 +12,7 @@
*
* @see docs/improvement-plan/02-observability/sentry-wiring-api-worker.md
*/
import { createNoopErrorReporter, createSentryErrorReporter, type ErrorReporter } from "@toolctrl/error-reporter";
import { createNoopErrorReporter, createSentryErrorReporter, type ErrorReporter } from "@hivegrid/error-reporter";
export interface ApiSentryConfig {
dsn: string | undefined;
@@ -54,7 +54,7 @@ let cachedConfig: ApiSentryConfig | undefined;
* Idempotent. The first call builds the Sentry-backed reporter (or the
* no-op reporter when `SENTRY_DSN_API` is empty); subsequent calls return
* the cached instance. The Sentry SDK is loaded lazily through the adapter
* in `@toolctrl/error-reporter`, so unit tests that do not import this
* in `@hivegrid/error-reporter`, so unit tests that do not import this
* module never touch `@sentry/node` at all.
*/
export function initApiSentry(config: ApiSentryConfig = readApiSentryConfig()): ErrorReporter {
@@ -1,4 +1,4 @@
import { createSharedStore, type SharedStore } from "@toolctrl/shared-store";
import { createSharedStore, type SharedStore } from "@hivegrid/shared-store";
/**
* Singleton SharedStore for the API process. All in-process Map-backed
@@ -0,0 +1,101 @@
import { afterEach, beforeEach, describe, expect, test } from "vitest";
import { resetApiRuntimeConfigForTests, setApiRuntimeConfigForTests } from "./config.js";
import { createStorageSignedDownloadUrl, resetStorageCachesForTests } from "./storage.js";
const baseConfig = {
appName: "Test API",
nodeEnv: "test",
revision: "unknown",
listen: { port: 3001 },
routing: {
appBaseDomain: "localhost:3000",
webAppHost: "app.localhost:3000",
adminAppHost: "admin.localhost:3000",
apiHost: "api.localhost:3000",
protocol: "http",
},
origins: {},
apiAccessToken: "service-token",
jwtSecret: "jwt-secret",
analytics: {},
mailjet: {},
lago: { timeoutMs: 10000 },
mollie: { timeoutMs: 10000 },
apiKeys: { allowLegacyPlaintextFallback: true },
storage: {
endpoint: "https://storage.example.com",
region: "us-east-1",
accessKeyId: "test-access-key",
secretAccessKey: "test-secret-key",
forcePathStyle: "true",
},
} as const;
beforeEach(() => {
resetStorageCachesForTests();
});
afterEach(() => {
resetApiRuntimeConfigForTests();
});
describe("createStorageSignedDownloadUrl edge cases", () => {
test("surfaces a config_missing diagnostic when storage credentials are absent", async () => {
setApiRuntimeConfigForTests({ ...baseConfig, storage: {} });
await expect(
createStorageSignedDownloadUrl("exports", { key: "a/b.csv", expiresInSeconds: 300 }),
).rejects.toMatchObject({
code: "signed_download_failed",
details: {
upstream: {
name: "StorageAdapterError",
// The signer enumerates every missing field before throwing.
message: expect.stringContaining("Missing signed URL storage configuration"),
},
},
});
// The error must name each missing credential to be actionable.
await expect(
createStorageSignedDownloadUrl("exports", { key: "a/b.csv", expiresInSeconds: 300 }),
).rejects.toMatchObject({
details: {
upstream: {
message: expect.stringMatching(/endpoint.*region.*accessKeyId.*secretAccessKey/),
},
},
});
});
test("embeds the session token as X-Amz-Security-Token when configured", async () => {
setApiRuntimeConfigForTests({
...baseConfig,
storage: { ...baseConfig.storage, sessionToken: "temp-session-token-123" },
});
const result = await createStorageSignedDownloadUrl("exports", {
key: "tenants/t1/file.csv",
expiresInSeconds: 300,
});
expect(result.url).toContain("X-Amz-Security-Token=temp-session-token-123");
});
test("uses virtual-hosted-style host when forcePathStyle is not enabled", async () => {
setApiRuntimeConfigForTests({
...baseConfig,
storage: { ...baseConfig.storage, forcePathStyle: "false" },
});
const result = await createStorageSignedDownloadUrl("exports", {
key: "tenants/t1/file.csv",
expiresInSeconds: 300,
});
// Bucket moves into the host; the path no longer carries the bucket segment.
expect(result.url).toContain("https://exports.storage.example.com/tenants/t1/file.csv");
expect(result.url).not.toContain("/exports/tenants/t1/file.csv");
});
});
@@ -20,7 +20,8 @@ const baseConfig = {
jwtSecret: "jwt-secret",
analytics: {},
mailjet: {},
stripe: {},
lago: { timeoutMs: 10000 },
mollie: { timeoutMs: 10000 },
apiKeys: {
allowLegacyPlaintextFallback: true,
},
@@ -10,7 +10,7 @@ import {
type SignedDownloadUrlResult,
type StorageAdapter,
type UploadBody,
} from "@toolctrl/storage";
} from "@hivegrid/storage";
import { getApiRuntimeConfig } from "./config.js";
@@ -0,0 +1,23 @@
// Trusted, proxy-set client-IP headers in order of preference. These are set
// by the edge/proxy and OVERWRITE any client-supplied value, so — unlike the
// leftmost X-Forwarded-For entry or X-Client-IP — they cannot be spoofed by the
// client. Every public request in this estate passes through Cloudflare
// (proxied), which sets CF-Connecting-IP; X-Real-IP is the immediate reverse
// proxy (Traefik) hop as a fallback for non-Cloudflare paths.
const TRUSTED_IP_HEADERS = ["cf-connecting-ip", "true-client-ip", "x-real-ip"] as const;
/**
* Read the client IP from a trusted header only. Use for security-sensitive
* decisions (rate limiting, abuse throttles) where an attacker must not be able
* to rotate their apparent IP by forging X-Forwarded-For. Returns the empty
* string when no trusted header is present so callers can key a shared bucket.
*/
export function getTrustedClientIp(request: Request): string {
for (const headerName of TRUSTED_IP_HEADERS) {
const value = request.headers.get(headerName)?.trim();
if (value) {
return value;
}
}
return "";
}
@@ -1,7 +1,7 @@
import { Hono } from "hono";
import type { ApiConfig } from "@toolctrl/config";
import type { LegacyApiKeySimple } from "@toolctrl/db/api-keys.server";
import { SUBSCRIPTION_FEATURE_LIMIT, type TenantApiUsageFeature } from "@toolctrl/db/usage.server";
import type { ApiConfig } from "@hivegrid/config";
import type { LegacyApiKeySimple } from "@hivegrid/db/api-keys.server";
import { SUBSCRIPTION_FEATURE_LIMIT, type TenantApiUsageFeature } from "@hivegrid/db/usage.server";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { resetApiRuntimeConfigForTests, setApiRuntimeConfigForTests } from "../config.js";
@@ -27,7 +27,8 @@ const TEST_API_CONFIG: ApiConfig = {
jwtSecret: "usage-route-secret",
analytics: {},
mailjet: {},
stripe: {},
lago: { timeoutMs: 10000 },
mollie: { timeoutMs: 10000 },
apiKeys: {
allowLegacyPlaintextFallback: true,
},
@@ -51,8 +52,9 @@ function createApiKeyFixture(patch: Partial<LegacyApiKeySimple> = {}): LegacyApi
alias: "Primary usage key",
expires: null,
tenantId,
createdByUserId: "user_usage_1",
active: true,
entities: [],
scopes: ["*"],
tenant: { id: tenantId, name: "Acme Usage", slug: "acme-usage", deactivatedReason: null },
...patch,
};
@@ -235,7 +237,7 @@ describe("getUsageRequest", () => {
test("swallows IP logging failures and still returns usage", async () => {
const { dependencies, mocks } = buildDeps({ ipLoggingError: new Error("ip write failed") });
const response = await requestUsage(dependencies, { "x-api-key": "valid-secret", "x-forwarded-for": "203.0.113.10, 10.0.0.1" });
const response = await requestUsage(dependencies, { "x-api-key": "valid-secret", "cf-connecting-ip": "203.0.113.10" });
expect(response.status).toBe(200);
await expect(response.json()).resolves.toEqual({ plan: "" });
@@ -1,8 +1,9 @@
import { formatTenantApiUsagePlanTitle, SUBSCRIPTION_FEATURE_LIMIT } from "@toolctrl/db/usage.server";
import { formatTenantApiUsagePlanTitle, SUBSCRIPTION_FEATURE_LIMIT } from "@hivegrid/db/usage.server";
import type { Context } from "hono";
import { extractApiKeyFromRequest } from "../auth.js";
import { getApiRuntimeConfig } from "../config.js";
import { getTrustedClientIp } from "../trusted-client-ip.js";
import { apiError, type ApiErrorEnv } from "../middleware/error-envelope.js";
import type { ApiAppDependencies } from "../app.js";
@@ -102,7 +103,8 @@ async function createApiUsageErrorLog(
}
function getClientIpAddress(request: Request) {
return request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || request.headers.get("x-real-ip") || "";
// Trusted proxy-set header only; leftmost X-Forwarded-For is client-spoofable.
return getTrustedClientIp(request);
}
function serializeRequestSearchParams(request: Request) {
@@ -0,0 +1,89 @@
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import type { LegacyEventWebhookAttempt } from "@hivegrid/db/event-webhook-attempts.server";
// Override only the Redis-connection resolver + the lazily-imported runtime
// queue factory so the "owned queue" branch (the API builds its own queue from
// the resolved connection, then closes it in `finally`) runs without Redis.
const { resolveRedisConnectionOptionsMock, createQueueMock, addMock, closeMock } = vi.hoisted(() => {
const addMock = vi.fn();
const closeMock = vi.fn().mockResolvedValue(undefined);
return {
addMock,
closeMock,
resolveRedisConnectionOptionsMock: vi.fn(),
createQueueMock: vi.fn(() => ({ add: addMock, close: closeMock })),
};
});
vi.mock("@hivegrid/queue", async (importOriginal) => {
const actual = await importOriginal<typeof import("@hivegrid/queue")>();
return { ...actual, resolveRedisConnectionOptions: resolveRedisConnectionOptionsMock };
});
vi.mock("@hivegrid/queue/runtime", () => ({
createQueue: createQueueMock,
}));
const { queueLegacyEventWebhookAttemptDelivery } = await import("./webhookDeliveryQueue.js");
const attempt = {
id: "attempt_owned_1",
endpoint: "https://example.test/webhooks/events",
tenantId: "tenant_owned",
} satisfies LegacyEventWebhookAttempt;
const body = { id: "evt_owned", type: "member.created" };
beforeEach(() => {
vi.clearAllMocks();
closeMock.mockResolvedValue(undefined);
});
afterEach(() => {
vi.restoreAllMocks();
});
describe("queueLegacyEventWebhookAttemptDelivery (self-owned queue)", () => {
test("returns missing-redis-connection when no connection can be resolved", async () => {
resolveRedisConnectionOptionsMock.mockReturnValue(undefined);
const result = await queueLegacyEventWebhookAttemptDelivery({ attempt, body, env: {} });
expect(result).toEqual({ enqueued: false, reason: "missing-redis-connection" });
expect(createQueueMock).not.toHaveBeenCalled();
});
test("builds, enqueues on, and then closes a self-owned queue", async () => {
resolveRedisConnectionOptionsMock.mockReturnValue({ host: "127.0.0.1", port: 6379 });
const job = { id: "job_owned_1" };
addMock.mockResolvedValue(job);
const result = await queueLegacyEventWebhookAttemptDelivery({
attempt,
body,
requestId: "req_owned",
env: { REDIS_URL: "redis://127.0.0.1:6379" } as never,
});
expect(createQueueMock).toHaveBeenCalledTimes(1);
expect(createQueueMock).toHaveBeenCalledWith("hivegrid.email", {
connection: { host: "127.0.0.1", port: 6379 },
});
expect(addMock).toHaveBeenCalledTimes(1);
expect(result).toEqual({ enqueued: true, job });
// The owned queue must be closed exactly once after enqueueing.
expect(closeMock).toHaveBeenCalledTimes(1);
});
test("closes the self-owned queue even when enqueue fails", async () => {
resolveRedisConnectionOptionsMock.mockReturnValue({ host: "127.0.0.1", port: 6379 });
const error = new Error("enqueue exploded");
addMock.mockRejectedValue(error);
await expect(
queueLegacyEventWebhookAttemptDelivery({ attempt, body, env: { REDIS_URL: "redis://x" } as never }),
).rejects.toThrow(error);
expect(closeMock).toHaveBeenCalledTimes(1);
});
});
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { buildRetryJobOptions } from "@toolctrl/queue";
import { buildRetryJobOptions } from "@hivegrid/queue";
import { buildLegacyEventWebhookAttemptDeliveryJob, queueLegacyEventWebhookAttemptDelivery } from "./webhookDeliveryQueue.js";
import type { LegacyEventWebhookAttempt } from "@toolctrl/db/event-webhook-attempts.server";
import type { LegacyEventWebhookAttempt } from "@hivegrid/db/event-webhook-attempts.server";
const attempt = {
@@ -22,7 +22,7 @@ beforeEach(() => {
describe("buildLegacyEventWebhookAttemptDeliveryJob", () => {
test("builds a deliver-webhook descriptor for legacy attempts", () => {
expect(buildLegacyEventWebhookAttemptDeliveryJob(attempt, body, "req_webhook_123")).toEqual({
queueName: "toolctrl.email",
queueName: "hivegrid.email",
jobName: "deliver-webhook",
payload: {
kind: "webhook.deliver",
@@ -6,8 +6,8 @@ import {
type RedisConnectionEnv,
type TypedQueue,
type WebhookDeliveryJobDescriptor,
} from "@toolctrl/queue";
import type { LegacyEventWebhookAttempt } from "@toolctrl/db/event-webhook-attempts.server";
} from "@hivegrid/queue";
import type { LegacyEventWebhookAttempt } from "@hivegrid/db/event-webhook-attempts.server";
type EmailQueue = TypedQueue<typeof queueNames.email>;
@@ -97,6 +97,6 @@ async function createInternalQueue(env?: RedisConnectionEnv): Promise<EmailQueue
return undefined;
}
const { createQueue } = await import("@toolctrl/queue/runtime");
const { createQueue } = await import("@hivegrid/queue/runtime");
return createQueue(queueNames.email, { connection });
}
@@ -0,0 +1,52 @@
import { describe, expect, it } from "vitest";
import { parseMailjetSuppressionSignal } from "./mailjet-suppression.js";
const tenantPayload = JSON.stringify({ t: "tenant-1" });
describe("parseMailjetSuppressionSignal", () => {
it("suppresses a hard bounce with a JSON tenant payload", () => {
const body = JSON.stringify({ event: "bounce", email: "Hard@Bounce.test", Payload: tenantPayload, error: "user unknown" });
expect(parseMailjetSuppressionSignal(body)).toEqual({
action: "suppress",
tenantId: "tenant-1",
emailAddress: "Hard@Bounce.test",
suppressionReason: "bounce",
detail: "bounce: user unknown",
});
});
it("classifies a spam event as a complaint", () => {
const body = JSON.stringify({ event: "spam", email: "a@x.test", CustomID: "tenant-9" });
expect(parseMailjetSuppressionSignal(body)).toMatchObject({ action: "suppress", tenantId: "tenant-9", suppressionReason: "complaint" });
});
it("accepts a bare tenant id in the payload", () => {
const body = JSON.stringify({ event: "blocked", email: "a@x.test", Payload: "tenant-7" });
expect(parseMailjetSuppressionSignal(body)).toMatchObject({ action: "suppress", tenantId: "tenant-7", suppressionReason: "bounce" });
});
it("folds a batched array to its first event", () => {
const body = JSON.stringify([{ event: "bounce", email: "a@x.test", Payload: tenantPayload }]);
expect(parseMailjetSuppressionSignal(body)).toMatchObject({ action: "suppress", tenantId: "tenant-1" });
});
it("ignores non-suppression events", () => {
expect(parseMailjetSuppressionSignal(JSON.stringify({ event: "open", email: "a@x.test", Payload: tenantPayload }))).toEqual({
action: "ignore",
reason: "non-suppression-event:open",
});
});
it("ignores a bounce whose tenant cannot be resolved", () => {
expect(parseMailjetSuppressionSignal(JSON.stringify({ event: "bounce", email: "a@x.test" }))).toEqual({ action: "ignore", reason: "unresolved-tenant" });
});
it("ignores a bounce with no recipient", () => {
expect(parseMailjetSuppressionSignal(JSON.stringify({ event: "bounce", Payload: tenantPayload }))).toEqual({ action: "ignore", reason: "missing-email" });
});
it("ignores invalid JSON", () => {
expect(parseMailjetSuppressionSignal("not json")).toEqual({ action: "ignore", reason: "invalid-json" });
});
});
@@ -0,0 +1,117 @@
// AK-P14a · P14 Email — Mailjet event → suppression signal parser (pure).
//
// Independent of the email-sequence bounce reconciliation (provider-webhook-route):
// that path keys off `providerMessageId` to fail a sequence run; THIS extracts the
// recipient address + the owning tenant so the address can be added to the tenant
// suppression list. The tenant is carried in Mailjet's custom `Payload` / `CustomID`
// field, which the AK-P14b send path stamps as JSON `{ "t": "<tenantId>" }` (or a
// bare tenant id). When the tenant cannot be resolved the signal is `ignore` —
// suppression is best-effort and must never break the webhook.
//
// Kept pure + separately unit-tested so it adds zero risk to the existing
// sequence-webhook tests.
export type MailjetSuppressionSignal =
| { action: "ignore"; reason: string }
| { action: "suppress"; tenantId: string; emailAddress: string; suppressionReason: "bounce" | "complaint"; detail: string | null };
// Mailjet `event` values that warrant a permanent suppression. `spam` is a
// complaint; hard `bounce` / `blocked` are delivery failures.
const SUPPRESSION_EVENT_TYPES = new Set(["bounce", "blocked", "spam"]);
export function parseMailjetSuppressionSignal(rawBody: string): MailjetSuppressionSignal {
let payload: unknown;
try {
payload = JSON.parse(rawBody) as unknown;
} catch {
return { action: "ignore", reason: "invalid-json" };
}
if (Array.isArray(payload)) {
payload = payload[0];
}
if (!isRecord(payload)) {
return { action: "ignore", reason: "not-an-object" };
}
const eventType = normalizeEventType(readString(payload, [["event"], ["type"], ["event_type"], ["data", "event"]]));
if (!eventType || !SUPPRESSION_EVENT_TYPES.has(eventType)) {
return { action: "ignore", reason: `non-suppression-event:${eventType ?? "unknown"}` };
}
const emailAddress = readString(payload, [["email"], ["Email"], ["recipient"], ["data", "email"], ["data", "recipient"]]);
if (!emailAddress) {
return { action: "ignore", reason: "missing-email" };
}
const tenantId = resolveTenantId(payload);
if (!tenantId) {
return { action: "ignore", reason: "unresolved-tenant" };
}
const detail = readString(payload, [["error"], ["comment"], ["reason"], ["error_related_to"], ["data", "error"]]) ?? null;
return {
action: "suppress",
tenantId,
emailAddress,
suppressionReason: eventType === "spam" ? "complaint" : "bounce",
detail: detail ? `${eventType}: ${detail}` : eventType,
};
}
/**
* Resolve the owning tenant from Mailjet's custom send-time metadata. Accepts a
* JSON object `{ "t": "<tenantId>" }` / `{ "tenantId": "<id>" }` or a bare string
* in `Payload` / `CustomID`.
*/
function resolveTenantId(payload: Record<string, unknown>): string | null {
const raw = readString(payload, [["Payload"], ["payload"], ["CustomID"], ["customId"], ["custom_id"], ["data", "Payload"], ["data", "CustomID"]]);
if (!raw) {
return null;
}
try {
const parsed = JSON.parse(raw) as unknown;
if (isRecord(parsed)) {
const fromJson = firstString([parsed["t"], parsed["tenantId"], parsed["tenant_id"]]);
if (fromJson) {
return fromJson;
}
}
} catch {
// not JSON — fall through to treating the whole value as a bare tenant id.
}
return raw;
}
function firstString(values: unknown[]): string | null {
for (const value of values) {
if (typeof value === "string" && value.trim()) {
return value.trim();
}
}
return null;
}
function readString(record: Record<string, unknown>, paths: string[][]): string | undefined {
for (const path of paths) {
let current: unknown = record;
for (const key of path) {
if (!isRecord(current)) {
current = undefined;
break;
}
current = current[key];
}
if (typeof current === "string" && current.trim()) {
return current.trim();
}
}
return undefined;
}
function normalizeEventType(value: string | undefined): string | undefined {
return value?.trim().toLowerCase().replace(/[\s-]+/g, "_");
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null;
}