Skip to content

A local-first personal finance app

[AI] Reject invalid periodic automation intervals (#9021)

Matty Ice27290a8990ef
diff --git a/packages/loot-core/src/server/budget/category-template-context.test.ts b/packages/loot-core/src/server/budget/category-template-context.test.ts
index 83e7a507f2..f18e39c0e0 100644
--- a/packages/loot-core/src/server/budget/category-template-context.test.ts
+++ b/packages/loot-core/src/server/budget/category-template-context.test.ts
@@ -3,6 +3,7 @@ import { vi } from 'vitest';
import * as aql from '#server/aql';
import * as db from '#server/db';
import type { DbCategory } from '#server/db';
+import * as monthUtils from '#shared/months';
import { amountToInteger } from '#shared/util';
import type { CategoryEntity } from '#types/models';
import type { ByTemplate, Template } from '#types/models/templates';
@@ -355,6 +356,33 @@ describe('CategoryTemplateContext', () => {
instance = new TestCategoryTemplateContext([], category, '2024-01', 0, 0);
});
+ it.each(['2023-12-01', '2024-01-01'])(
+ 'rejects a stalled date shift in either loop (starting %s)',
+ starting => {
+ const shift = vi.spyOn(monthUtils, 'addDays').mockReturnValue(starting);
+ try {
+ expect(() =>
+ CategoryTemplateContext.runPeriodic(
+ {
+ type: 'periodic',
+ amount: 100,
+ period: { period: 'day', amount: 1 },
+ starting,
+ directive: 'template',
+ priority: 0,
+ },
+ instance,
+ ),
+ ).toThrow(
+ 'Infinite loop detected in repeating template, check the repeat interval',
+ );
+ expect(shift).toHaveBeenCalledOnce();
+ } finally {
+ shift.mockRestore();
+ }
+ },
+ );
+
//5 mondays in January 2024
it('should calculate weekly amount for single week', () => {
const template: Template = {
@@ -1956,6 +1984,31 @@ describe('CategoryTemplateContext', () => {
vi.mocked(actions.isTrackingBudget).mockReturnValue(false);
});
+ it.each([
+ 0,
+ -1,
+ 0.5,
+ Number.NaN,
+ Number.POSITIVE_INFINITY,
+ Number.MAX_SAFE_INTEGER + 1,
+ ])('rejects an invalid saved repeat interval (%s)', async interval => {
+ const templates: Template[] = [
+ {
+ type: 'periodic',
+ amount: 100,
+ period: { period: 'day', amount: interval },
+ starting: '2023-12-01',
+ directive: 'template',
+ priority: 0,
+ },
+ ];
+ await expect(
+ CategoryTemplateContext.init(templates, category, '2024-01', 0),
+ ).rejects.toThrow(
+ 'Template repeat interval must be a whole number greater than 0',
+ );
+ });
+
it('throws when a schedule template references a non-existent schedule', async () => {
vi.mocked(statements.getActiveSchedules).mockResolvedValue([
{ name: 'Rent', id: 's1' },
diff --git a/packages/loot-core/src/server/budget/category-template-context.ts b/packages/loot-core/src/server/budget/category-template-context.ts
index 609f46dbf6..e67540ce41 100644
--- a/packages/loot-core/src/server/budget/category-template-context.ts
+++ b/packages/loot-core/src/server/budget/category-template-context.ts
@@ -79,6 +79,7 @@ export class CategoryTemplateContext {
}
// run all checks
+ CategoryTemplateContext.checkPeriodicInterval(templates);
await CategoryTemplateContext.checkByAndScheduleAndSpend(templates, month);
await CategoryTemplateContext.checkPercentage(templates);
@@ -468,6 +469,19 @@ export class CategoryTemplateContext {
//-----------------------------------------------------------------------------
// Template Validation
+ private static checkPeriodicInterval(templates: Template[]) {
+ templates
+ .filter(template => template.type === 'periodic')
+ .forEach(template => {
+ const interval = template.period?.amount;
+ if (!Number.isSafeInteger(interval) || interval < 1) {
+ throw new Error(
+ 'Template repeat interval must be a whole number greater than 0',
+ );
+ }
+ });
+ }
+
static async checkByAndScheduleAndSpend(
templates: Template[],
month: string,
@@ -713,7 +727,7 @@ export class CategoryTemplateContext {
? template.starting
: monthUtils.firstDayOfMonth(templateContext.month);
- let dateShiftFunction;
+ let dateShiftFunction: (date: string, numPeriods: number) => string;
switch (period) {
case 'day':
dateShiftFunction = monthUtils.addDays;
@@ -733,9 +747,21 @@ export class CategoryTemplateContext {
throw new Error(`Unrecognized periodic period: ${String(period)}`);
}
+ // Both loops below only end once the date moves past a bound, so stop
+ // instead of hanging if a shift ever fails to advance the date.
+ function advanceDate(current: string): string {
+ const next = dateShiftFunction(current, numPeriods);
+ if (!monthUtils.isAfter(next, current)) {
+ throw new Error(
+ 'Infinite loop detected in repeating template, check the repeat interval',
+ );
+ }
+ return next;
+ }
+
//shift the starting date until its in our month or in the future
while (templateContext.month > date) {
- date = dateShiftFunction(date, numPeriods);
+ date = advanceDate(date);
}
if (
@@ -747,7 +773,7 @@ export class CategoryTemplateContext {
const nextMonth = monthUtils.addMonths(templateContext.month, 1);
while (date < nextMonth) {
toBudget += amount;
- date = dateShiftFunction(date, numPeriods);
+ date = advanceDate(date);
}
return toBudget;
diff --git a/packages/loot-core/src/server/budget/goal-template.pegjs b/packages/loot-core/src/server/budget/goal-template.pegjs
index fd2f790bfa..9469a43c83 100644
--- a/packages/loot-core/src/server/budget/goal-template.pegjs
+++ b/packages/loot-core/src/server/budget/goal-template.pegjs
@@ -57,12 +57,12 @@ percentOf = percent:percent _ of _ 'previous'i _ { return { percent: percent, pr
/ percent:percent _ of _ { return { percent: percent, prev: false}}
periodCount = 'day'i { return {period: 'day', amount: 1 }}
- / n: number _ 'days'i _ { return { period: 'day', amount: +n }}
+ / n: positive _ 'days'i _ { return { period: 'day', amount: +n }}
/ week _ { return {period: 'week', amount: 1 }}
- / n: number _ weeks { return {period: 'week', amount: +n }}
- / n: number _ 'months'i _ {return {period: 'month', amount: +n }}
+ / n: positive _ weeks { return {period: 'week', amount: +n }}
+ / n: positive _ 'months'i _ {return {period: 'month', amount: +n }}
/ 'year'i _ { return {period: 'year', amount: 1 }}
- / n: number _ 'years'i _ { return { period: 'year', amount: +n }}
+ / n: positive _ 'years'i _ { return { period: 'year', amount: +n }}
spendFrom = _ 'spend'i _ 'from'i _ month: month { return month }
diff --git a/packages/loot-core/src/server/budget/template-notes.test.ts b/packages/loot-core/src/server/budget/template-notes.test.ts
index bfcdb7984d..9f4470495d 100644
--- a/packages/loot-core/src/server/budget/template-notes.test.ts
+++ b/packages/loot-core/src/server/budget/template-notes.test.ts
@@ -526,3 +526,30 @@ describe('unparse descriptions', () => {
expect(serialized).toBe('first\nsecond\n#template 10');
});
});
+
+describe('periodic template intervals', () => {
+ it.each(['days', 'weeks', 'months', 'years'])(
+ 'rejects a zero-%s interval in legacy notes',
+ unit => {
+ expect(() =>
+ parse(`#template 100 repeat every 0 ${unit} starting 2026-09-01`),
+ ).toThrow();
+ },
+ );
+ it.each(['days', 'weeks', 'months', 'years'])(
+ 'continues to parse positive %s intervals',
+ unit => {
+ expect(
+ parse(`#template 100 repeat every 2 ${unit} starting 2026-09-01`),
+ ).toMatchObject({
+ type: 'periodic',
+ period: { amount: 2 },
+ });
+ },
+ );
+ it.each(['002', '000'])('rejects an interval with leading zeroes (%s)', n => {
+ expect(() =>
+ parse(`#template 100 repeat every ${n} days starting 2026-09-01`),
+ ).toThrow();
+ });
+});
diff --git a/upcoming-release-notes/fix-periodic-template-intervals.md b/upcoming-release-notes/fix-periodic-template-intervals.md
new file mode 100644
index 0000000000..a7476965cd
--- /dev/null
+++ b/upcoming-release-notes/fix-periodic-template-intervals.md
@@ -0,0 +1,6 @@
+---
+category: Bugfix
+authors: [mattm4444]
+---
+
+Prevent invalid repeating budget automations from freezing the budget.