Merge pull request #3643 from fosrl/dev

1.22.0-s.1
This commit is contained in:
Owen Schwartz
2026-08-26 10:53:37 -04:00
committed by GitHub
11 changed files with 51 additions and 42 deletions
+1 -1
View File
@@ -1984,7 +1984,7 @@ export const aiSessionLog = pgTable(
// were cut short at AI_SESSION_LOG_MAX_BODY_CHARS before storage. // were cut short at AI_SESSION_LOG_MAX_BODY_CHARS before storage.
truncated: boolean("truncated").notNull().default(false), truncated: boolean("truncated").notNull().default(false),
statusCode: integer("statusCode"), statusCode: integer("statusCode"),
createdAt: bigint("createdAt", { mode: "number" }).notNull() // epoch ms createdAt: bigint("createdAt", { mode: "number" }).notNull() // epoch seconds
}, },
(t) => [ (t) => [
index("idx_ai_session_log_org_created").on(t.orgId, t.createdAt), index("idx_ai_session_log_org_created").on(t.orgId, t.createdAt),
+1 -1
View File
@@ -1980,7 +1980,7 @@ export const aiSessionLog = sqliteTable(
.notNull() .notNull()
.default(false), .default(false),
statusCode: integer("statusCode"), statusCode: integer("statusCode"),
createdAt: integer("createdAt").notNull() // epoch ms createdAt: integer("createdAt").notNull() // epoch seconds
}, },
(t) => [ (t) => [
index("idx_ai_session_log_org_created").on(t.orgId, t.createdAt), index("idx_ai_session_log_org_created").on(t.orgId, t.createdAt),
+3 -1
View File
@@ -580,6 +580,8 @@ export async function recordUsage(input: UsageRecordInput): Promise<void> {
); );
} }
const timestamp = Math.floor(Date.now() / 1000);
usageRecordBuffer.push({ usageRecordBuffer.push({
orgId: input.orgId, orgId: input.orgId,
providerId: input.providerId, providerId: input.providerId,
@@ -597,7 +599,7 @@ export async function recordUsage(input: UsageRecordInput): Promise<void> {
totalTokens, totalTokens,
costUsd: input.costUsd, costUsd: input.costUsd,
estimated: usage.estimated, estimated: usage.estimated,
createdAt: input.createdAt ?? Date.now() createdAt: input.createdAt ?? timestamp
}); });
// Flush immediately if buffer is full, otherwise schedule a flush // Flush immediately if buffer is full, otherwise schedule a flush
+1 -2
View File
@@ -52,8 +52,7 @@ export async function validateAndConstructDomain(
}; };
} }
// Check if organization has access to domain if (!domainRes.orgDomains) {
if (domainRes.orgDomains && domainRes.orgDomains.orgId !== orgId) {
return { return {
success: false, success: false,
error: `Organization does not have access to domain with ID ${domainId}` error: `Organization does not have access to domain with ID ${domainId}`
@@ -151,17 +151,14 @@ async function getRetentionDays(orgId: string): Promise<number> {
} }
export async function cleanUpOldLogs(orgId: string, retentionDays: number) { export async function cleanUpOldLogs(orgId: string, retentionDays: number) {
// calculateCutoffTimestamp returns a seconds-epoch cutoff (built for const cutoffTimestamp = calculateCutoffTimestamp(retentionDays) * 1000;
// requestAuditLog.timestamp), but aiSessionLog.createdAt is ms-epoch to
// match aiUsageRecords - convert before comparing.
const cutoffTimestampMs = calculateCutoffTimestamp(retentionDays) * 1000;
try { try {
await logsDb await logsDb
.delete(aiSessionLog) .delete(aiSessionLog)
.where( .where(
and( and(
lt(aiSessionLog.createdAt, cutoffTimestampMs), lt(aiSessionLog.createdAt, cutoffTimestamp),
eq(aiSessionLog.orgId, orgId) eq(aiSessionLog.orgId, orgId)
) )
); );
@@ -243,6 +240,8 @@ export function logAiSession(data: {
); );
} }
const timestamp = Math.floor(Date.now() / 1000);
sessionLogBuffer.push({ sessionLogBuffer.push({
sessionId: data.sessionId, sessionId: data.sessionId,
orgId: sanitizeString(data.orgId), orgId: sanitizeString(data.orgId),
@@ -270,7 +269,7 @@ export function logAiSession(data: {
(normalizedRequestText?.truncated ?? false) || (normalizedRequestText?.truncated ?? false) ||
(normalizedResponseText?.truncated ?? false), (normalizedResponseText?.truncated ?? false),
statusCode: data.statusCode, statusCode: data.statusCode,
createdAt: Date.now() createdAt: timestamp
}); });
// Flush immediately if buffer is full, otherwise schedule a flush // Flush immediately if buffer is full, otherwise schedule a flush
@@ -18,7 +18,7 @@ export const aiUsageAnalyticsFiltersQuery = z.object({
.refine((val) => !isNaN(Date.parse(val)), { .refine((val) => !isNaN(Date.parse(val)), {
error: "timeStart must be a valid ISO date string" error: "timeStart must be a valid ISO date string"
}) })
.transform((val) => new Date(val).getTime()) .transform((val) => Math.floor(new Date(val).getTime() / 1000))
.prefault(() => getSevenDaysAgo().toISOString()) .prefault(() => getSevenDaysAgo().toISOString())
.openapi({ .openapi({
type: "string", type: "string",
@@ -31,7 +31,7 @@ export const aiUsageAnalyticsFiltersQuery = z.object({
.refine((val) => !isNaN(Date.parse(val)), { .refine((val) => !isNaN(Date.parse(val)), {
error: "timeEnd must be a valid ISO date string" error: "timeEnd must be a valid ISO date string"
}) })
.transform((val) => new Date(val).getTime()) .transform((val) => Math.floor(new Date(val).getTime() / 1000))
.prefault(() => new Date().toISOString()) .prefault(() => new Date().toISOString())
.openapi({ .openapi({
type: "string", type: "string",
@@ -122,12 +122,12 @@ export function buildAiUsageWhere(
); );
} }
// Buckets createdAt (epoch ms) down to a per-day string, dialect-aware, same // Buckets createdAt (epoch seconds) down to a per-day string, dialect-aware,
// approach as the DATE_TRUNC/DATE branch in queryRequestAnalytics.ts. // same approach as the DATE_TRUNC/DATE branch in queryRequestAnalytics.ts.
export function dayBucketExpr() { export function dayBucketExpr() {
return driver === "pg" return driver === "pg"
? sql<string>`DATE_TRUNC('day', TO_TIMESTAMP(${aiUsageRecords.createdAt} / 1000.0))` ? sql<string>`DATE_TRUNC('day', TO_TIMESTAMP(${aiUsageRecords.createdAt}))`
: sql<string>`DATE(${aiUsageRecords.createdAt} / 1000, 'unixepoch')`; : sql<string>`DATE(${aiUsageRecords.createdAt}, 'unixepoch')`;
} }
export type DailyMetricRow<K extends string> = { export type DailyMetricRow<K extends string> = {
@@ -32,7 +32,7 @@ export const queryAiSessionLogsQuery = z.strictObject({
.refine((val) => !isNaN(Date.parse(val)), { .refine((val) => !isNaN(Date.parse(val)), {
error: "timeStart must be a valid ISO date string" error: "timeStart must be a valid ISO date string"
}) })
.transform((val) => new Date(val).getTime()) .transform((val) => Math.floor(new Date(val).getTime() / 1000))
.prefault(() => getSevenDaysAgo().toISOString()) .prefault(() => getSevenDaysAgo().toISOString())
.openapi({ .openapi({
type: "string", type: "string",
@@ -45,7 +45,7 @@ export const queryAiSessionLogsQuery = z.strictObject({
.refine((val) => !isNaN(Date.parse(val)), { .refine((val) => !isNaN(Date.parse(val)), {
error: "timeEnd must be a valid ISO date string" error: "timeEnd must be a valid ISO date string"
}) })
.transform((val) => new Date(val).getTime()) .transform((val) => Math.floor(new Date(val).getTime() / 1000))
.optional() .optional()
.prefault(() => new Date().toISOString()) .prefault(() => new Date().toISOString())
.openapi({ .openapi({
@@ -30,14 +30,14 @@ const queryAiUsageFilterOptionsQuery = z.object({
.refine((val) => !isNaN(Date.parse(val)), { .refine((val) => !isNaN(Date.parse(val)), {
error: "timeStart must be a valid ISO date string" error: "timeStart must be a valid ISO date string"
}) })
.transform((val) => new Date(val).getTime()) .transform((val) => Math.floor(new Date(val).getTime() / 1000))
.prefault(() => getSevenDaysAgo().toISOString()), .prefault(() => getSevenDaysAgo().toISOString()),
timeEnd: z timeEnd: z
.string() .string()
.refine((val) => !isNaN(Date.parse(val)), { .refine((val) => !isNaN(Date.parse(val)), {
error: "timeEnd must be a valid ISO date string" error: "timeEnd must be a valid ISO date string"
}) })
.transform((val) => new Date(val).getTime()) .transform((val) => Math.floor(new Date(val).getTime() / 1000))
.prefault(() => new Date().toISOString()) .prefault(() => new Date().toISOString())
}); });
+15 -11
View File
@@ -66,6 +66,10 @@ import * as aiBudget from "@server/routers/aiBudget";
import * as virtualApiKey from "@server/routers/virtualApiKey"; import * as virtualApiKey from "@server/routers/virtualApiKey";
import * as certificates from "@server/routers/certificates"; import * as certificates from "@server/routers/certificates";
function rateLimitIdentityKey(value: unknown): string {
return typeof value === "string" ? value.trim().toLowerCase() : "";
}
// Root routes // Root routes
export const unauthenticated = Router(); export const unauthenticated = Router();
@@ -1927,7 +1931,7 @@ authRouter.put(
windowMs: 15 * 60 * 1000, windowMs: 15 * 60 * 1000,
max: 15, max: 15,
keyGenerator: (req) => keyGenerator: (req) =>
`signup:${ipKeyGenerator(req.ip || "")}:${req.body.email}`, `signup:${ipKeyGenerator(req.ip || "")}:${rateLimitIdentityKey(req.body.email)}`,
handler: (req, res, next) => { handler: (req, res, next) => {
const message = `You can only sign up ${15} times every ${15} minutes. Please try again later.`; const message = `You can only sign up ${15} times every ${15} minutes. Please try again later.`;
return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message)); return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message));
@@ -1942,7 +1946,7 @@ authRouter.post(
windowMs: 15 * 60 * 1000, windowMs: 15 * 60 * 1000,
max: 15, max: 15,
keyGenerator: (req) => keyGenerator: (req) =>
`login:${req.body.email || ipKeyGenerator(req.ip || "")}`, `login:${rateLimitIdentityKey(req.body.email) || ipKeyGenerator(req.ip || "")}`,
handler: (req, res, next) => { handler: (req, res, next) => {
const message = `You can only log in ${15} times every ${15} minutes. Please try again later.`; const message = `You can only log in ${15} times every ${15} minutes. Please try again later.`;
return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message)); return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message));
@@ -1959,7 +1963,7 @@ authRouter.post(
windowMs: 15 * 60 * 1000, windowMs: 15 * 60 * 1000,
max: 15, max: 15,
keyGenerator: (req) => keyGenerator: (req) =>
`lookupUser:${req.body.identifier || ipKeyGenerator(req.ip || "")}`, `lookupUser:${rateLimitIdentityKey(req.body.identifier) || ipKeyGenerator(req.ip || "")}`,
handler: (req, res, next) => { handler: (req, res, next) => {
const message = `You can only lookup users ${15} times every ${15} minutes. Please try again later.`; const message = `You can only lookup users ${15} times every ${15} minutes. Please try again later.`;
return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message)); return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message));
@@ -2037,7 +2041,7 @@ authRouter.post(
windowMs: 15 * 60 * 1000, windowMs: 15 * 60 * 1000,
max: 15, max: 15,
keyGenerator: (req) => { keyGenerator: (req) => {
return `signup:${req.body.email || req.user?.userId || ipKeyGenerator(req.ip || "")}`; return `signup:${rateLimitIdentityKey(req.body.email) || req.user?.userId || ipKeyGenerator(req.ip || "")}`;
}, },
handler: (req, res, next) => { handler: (req, res, next) => {
const message = `You can only enable 2FA ${15} times every ${15} minutes. Please try again later.`; const message = `You can only enable 2FA ${15} times every ${15} minutes. Please try again later.`;
@@ -2053,7 +2057,7 @@ authRouter.post(
windowMs: 15 * 60 * 1000, windowMs: 15 * 60 * 1000,
max: 15, max: 15,
keyGenerator: (req) => { keyGenerator: (req) => {
return `signup:${req.body.email || req.user?.userId || ipKeyGenerator(req.ip || "")}`; return `signup:${rateLimitIdentityKey(req.body.email) || req.user?.userId || ipKeyGenerator(req.ip || "")}`;
}, },
handler: (req, res, next) => { handler: (req, res, next) => {
const message = `You can only request a 2FA code ${15} times every ${15} minutes. Please try again later.`; const message = `You can only request a 2FA code ${15} times every ${15} minutes. Please try again later.`;
@@ -2085,7 +2089,7 @@ authRouter.post(
windowMs: 15 * 60 * 1000, windowMs: 15 * 60 * 1000,
max: 15, max: 15,
keyGenerator: (req) => keyGenerator: (req) =>
`signup:${req.body.email || ipKeyGenerator(req.ip || "")}`, `signup:${rateLimitIdentityKey(req.body.email) || ipKeyGenerator(req.ip || "")}`,
handler: (req, res, next) => { handler: (req, res, next) => {
const message = `You can only sign up ${15} times every ${15} minutes. Please try again later.`; const message = `You can only sign up ${15} times every ${15} minutes. Please try again later.`;
return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message)); return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message));
@@ -2103,7 +2107,7 @@ authRouter.post(
windowMs: 15 * 60 * 1000, windowMs: 15 * 60 * 1000,
max: 15, max: 15,
keyGenerator: (req) => keyGenerator: (req) =>
`requestEmailVerificationCode:${req.user?.email || ipKeyGenerator(req.ip || "")}`, `requestEmailVerificationCode:${rateLimitIdentityKey(req.user?.email) || ipKeyGenerator(req.ip || "")}`,
handler: (req, res, next) => { handler: (req, res, next) => {
const message = `You can only request an email verification code ${15} times every ${15} minutes. Please try again later.`; const message = `You can only request an email verification code ${15} times every ${15} minutes. Please try again later.`;
return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message)); return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message));
@@ -2125,7 +2129,7 @@ authRouter.post(
windowMs: 15 * 60 * 1000, windowMs: 15 * 60 * 1000,
max: 15, max: 15,
keyGenerator: (req) => keyGenerator: (req) =>
`requestPasswordReset:${req.body.email || ipKeyGenerator(req.ip || "")}`, `requestPasswordReset:${rateLimitIdentityKey(req.body.email) || ipKeyGenerator(req.ip || "")}`,
handler: (req, res, next) => { handler: (req, res, next) => {
const message = `You can only request a password reset ${15} times every ${15} minutes. Please try again later.`; const message = `You can only request a password reset ${15} times every ${15} minutes. Please try again later.`;
return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message)); return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message));
@@ -2141,7 +2145,7 @@ authRouter.post(
windowMs: 15 * 60 * 1000, windowMs: 15 * 60 * 1000,
max: 15, max: 15,
keyGenerator: (req) => keyGenerator: (req) =>
`resetPassword:${req.body.email || ipKeyGenerator(req.ip || "")}`, `resetPassword:${rateLimitIdentityKey(req.body.email) || ipKeyGenerator(req.ip || "")}`,
handler: (req, res, next) => { handler: (req, res, next) => {
const message = `You can only request a password reset ${15} times every ${15} minutes. Please try again later.`; const message = `You can only request a password reset ${15} times every ${15} minutes. Please try again later.`;
return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message)); return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message));
@@ -2188,7 +2192,7 @@ authRouter.post(
windowMs: 15 * 60 * 1000, windowMs: 15 * 60 * 1000,
max: 15, max: 15,
keyGenerator: (req) => keyGenerator: (req) =>
`authWithWhitelist:${ipKeyGenerator(req.ip || "")}:${req.body.email}:${req.params.resourceId}`, `authWithWhitelist:${ipKeyGenerator(req.ip || "")}:${rateLimitIdentityKey(req.body.email)}:${req.params.resourceId}`,
handler: (req, res, next) => { handler: (req, res, next) => {
const message = `You can only request an email OTP ${15} times every ${15} minutes. Please try again later.`; const message = `You can only request an email OTP ${15} times every ${15} minutes. Please try again later.`;
return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message)); return next(createHttpError(HttpCode.TOO_MANY_REQUESTS, message));
@@ -2240,7 +2244,7 @@ authRouter.post(
windowMs: 15 * 60 * 1000, // 15 minutes windowMs: 15 * 60 * 1000, // 15 minutes
max: 10, // Allow 10 authentication attempts per 15 minutes per IP max: 10, // Allow 10 authentication attempts per 15 minutes per IP
keyGenerator: (req) => { keyGenerator: (req) => {
return `securityKeyAuth:${req.body.email || ipKeyGenerator(req.ip || "")}`; return `securityKeyAuth:${rateLimitIdentityKey(req.body.email) || ipKeyGenerator(req.ip || "")}`;
}, },
handler: (req, res, next) => { handler: (req, res, next) => {
const message = `You can only attempt security key authentication ${10} times every ${15} minutes. Please try again later.`; const message = `You can only attempt security key authentication ${10} times every ${15} minutes. Please try again later.`;
+5 -3
View File
@@ -16,13 +16,12 @@ const getOrgSchema = z.strictObject({
}); });
export type GetOrgResponse = { export type GetOrgResponse = {
org: Org; org: Omit<Org, "sshCaPrivateKey">;
}; };
const GetOrgResponseDataSchema = z.object({ const GetOrgResponseDataSchema = z.object({
org: z.object({}).passthrough() org: z.object({}).passthrough()
}); });
registry.registerPath({ registry.registerPath({
method: "get", method: "get",
path: "/org/{orgId}", path: "/org/{orgId}",
@@ -76,9 +75,12 @@ export async function getOrg(
); );
} }
// sshCaPrivateKey is encrypted anyway but just to be safe
const { sshCaPrivateKey: _, ...orgWithoutPrivateKey } = org;
return response<GetOrgResponse>(res, { return response<GetOrgResponse>(res, {
data: { data: {
org org: orgWithoutPrivateKey
}, },
success: true, success: true,
error: false, error: false,
+10 -7
View File
@@ -18,7 +18,7 @@ const getSiteResourceParamsSchema = z.strictObject({
.pipe(z.int().positive().optional()) .pipe(z.int().positive().optional())
.optional(), .optional(),
niceId: z.string().optional(), niceId: z.string().optional(),
orgId: z.string() orgId: z.string().optional()
}); });
async function query(siteResourceId?: number, niceId?: string, orgId?: string) { async function query(siteResourceId?: number, niceId?: string, orgId?: string) {
@@ -34,6 +34,13 @@ async function query(siteResourceId?: number, niceId?: string, orgId?: string) {
) )
.limit(1); .limit(1);
return siteResource; return siteResource;
} else if (siteResourceId) {
const [siteResource] = await db
.select()
.from(siteResources)
.where(eq(siteResources.siteResourceId, siteResourceId))
.limit(1);
return siteResource;
} else if (niceId && orgId) { } else if (niceId && orgId) {
const [siteResource] = await db const [siteResource] = await db
.select() .select()
@@ -60,9 +67,7 @@ registry.registerPath({
tags: [OpenAPITags.PrivateResourceLegacy], tags: [OpenAPITags.PrivateResourceLegacy],
request: { request: {
params: z.object({ params: z.object({
siteResourceId: z.number(), siteResourceId: z.number()
siteId: z.number(),
orgId: z.string()
}) })
}, },
responses: { responses: {
@@ -90,9 +95,7 @@ registry.registerPath({
tags: [OpenAPITags.PrivateResource], tags: [OpenAPITags.PrivateResource],
request: { request: {
params: z.object({ params: z.object({
siteResourceId: z.number(), siteResourceId: z.number()
siteId: z.number(),
orgId: z.string()
}) })
}, },
responses: { responses: {