diff --git a/packages/schemas/src/schemas.test.ts b/packages/schemas/src/schemas.test.ts index 7b215987..019ff3de 100644 --- a/packages/schemas/src/schemas.test.ts +++ b/packages/schemas/src/schemas.test.ts @@ -33,6 +33,13 @@ test('rateLimitSchema invalid', () => { }) ).toThrowErrorMatchingSnapshot() + expect(() => + rateLimitSchema.parse({ + interval: 0, + maxPerInterval: 5 + }) + ).toThrowErrorMatchingSnapshot() + expect(() => rateLimitSchema.parse({ interval: '--', diff --git a/packages/schemas/src/schemas.ts b/packages/schemas/src/schemas.ts index cffff7a6..dd9ffe2f 100644 --- a/packages/schemas/src/schemas.ts +++ b/packages/schemas/src/schemas.ts @@ -17,12 +17,13 @@ export const rateLimitSchema = z /** * The interval at which the rate limit is applied. * - * Either a number in seconds or a valid [ms](https://github.com/vercel/ms) - * string (eg, "10s", "1m", "1h", "1d", "1w", "1y", etc). + * Either a positive number expressed in seconds or a valid positive + * [ms](https://github.com/vercel/ms) string (eg, "10s", "1m", "8h", "2d", + * "1w", "1y", etc). */ interval: z .union([ - z.number().nonnegative(), // seconds + z.number().positive(), // seconds z .string() @@ -31,8 +32,14 @@ export const rateLimitSchema = z try { // TODO: `ms` module has broken types const ms = parseIntervalAsMs(value as any) as unknown as number + const seconds = Math.floor(ms / 1000) - if (typeof ms !== 'number' || ms < 0) { + if ( + typeof ms !== 'number' || + Number.isNaN(ms) || + ms <= 0 || + seconds <= 0 + ) { ctx.addIssue({ code: z.ZodIssueCode.custom, message: `Invalid interval "${value}"`, @@ -42,7 +49,6 @@ export const rateLimitSchema = z return z.NEVER } - const seconds = Math.floor(ms / 1000) return seconds } catch { ctx.addIssue({ @@ -56,7 +62,7 @@ export const rateLimitSchema = z }) ]) .describe( - `The interval at which the rate limit is applied. Either a number in seconds or a valid [ms](https://github.com/vercel/ms) string (eg, "10s", "1m", "1h", "1d", "1w", "1y", etc).` + `The interval at which the rate limit is applied. Either a positive number in seconds or a valid positive [ms](https://github.com/vercel/ms) string (eg, "10s", "1m", "8h", "2d", "1w", "1y", etc).` ), /**