113 lines
4.0 KiB
TypeScript
113 lines
4.0 KiB
TypeScript
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";
|
|
|
|
type UsageRouteDependencies = Pick<
|
|
ApiAppDependencies,
|
|
| "findLegacyApiKeyByKey"
|
|
| "createLegacyApiKeyLog"
|
|
| "setLegacyApiKeyLogStatus"
|
|
| "createUniqueLegacyTenantIpAddress"
|
|
| "getTenantSubscription"
|
|
| "getTenantApiUsage"
|
|
>;
|
|
|
|
export async function getUsageRequest(c: Context<ApiErrorEnv>, dependencies: UsageRouteDependencies) {
|
|
const startTime = performance.now();
|
|
const endpoint = new URL(c.req.url).pathname;
|
|
const config = getApiRuntimeConfig();
|
|
const apiKeyValue = extractApiKeyFromRequest(c.req.raw, undefined);
|
|
if (!apiKeyValue) {
|
|
await createApiUsageErrorLog(c, dependencies, endpoint, "Invalid API Key", 401);
|
|
return apiError(c, 401, "unauthorized", "Valid API key credentials are required.");
|
|
}
|
|
|
|
const apiKey = await dependencies.findLegacyApiKeyByKey(apiKeyValue, undefined as never, config.jwtSecret, {
|
|
allowPlaintextFallback: config.apiKeys.allowLegacyPlaintextFallback,
|
|
});
|
|
if (!apiKey) {
|
|
await createApiUsageErrorLog(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, code: string, message: string) => {
|
|
await dependencies.setLegacyApiKeyLogStatus({ id: apiKeyLog.id, tenantId: apiKey.tenantId }, { status, error: message, startTime });
|
|
return 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.");
|
|
}
|
|
|
|
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 && !usage.enabled) {
|
|
return fail(402, "payment_required", "API usage is disabled or exhausted.");
|
|
}
|
|
|
|
await dependencies.setLegacyApiKeyLogStatus({ id: apiKeyLog.id, tenantId: apiKey.tenantId }, { status: 200, startTime });
|
|
return c.json({
|
|
plan: usage ? formatTenantApiUsagePlanTitle(usage) : "",
|
|
remaining: usage?.type === SUBSCRIPTION_FEATURE_LIMIT.included ? undefined : usage?.remaining,
|
|
});
|
|
}
|
|
|
|
async function createApiUsageErrorLog(
|
|
c: Context<ApiErrorEnv>,
|
|
dependencies: Pick<UsageRouteDependencies, "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();
|
|
}
|