Reorganize repo structure and standards references
This commit is contained in:
1 parent
3cb93a81be
commit
be2054274d
5885 files changed
+2588
-195
No files matched your search
@@ -0,0 +1,110 @@
|
||||
import { formatTenantApiUsagePlanTitle, SUBSCRIPTION_FEATURE_LIMIT } from "@toolctrl/db/usage.server";
|
||||
import type { Context } from "hono";
|
||||
|
||||
import { extractApiKeyFromRequest } from "../auth.js";
|
||||
import { getApiRuntimeConfig } from "../config.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) {
|
||||
return request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || request.headers.get("x-real-ip") || "";
|
||||
}
|
||||
|
||||
function serializeRequestSearchParams(request: Request) {
|
||||
return new URL(request.url).searchParams.toString();
|
||||
}
|
||||
Reference in new issue
Block a user