♻️ Tighten client side validation and helpers

The settings validation now mirrors the bounds of the server, 0.01 to
168 hours and a workday mask of 1 to 127, so a row the client accepts
no longer fails on the server. stopEntry and autoStopStale end an
entry in the timezone of the settings row effective on the entry's
day, as the server does, instead of in today's. updateEntry refuses
to clear end_time while another entry is running.

safeNext falls back for a next path with a backslash, a control
character or "//". The login page opens the OAuth popup itself within
the click and says "The popup was blocked" when the browser refuses
it, where the sign-in used to hang without a word.

The sync keeps a per-collection flag for the pull of the current sync
call instead of counting pulls globally, asks for a minute before the
cursor since the server clock can move backwards, and closeDb()
clears the sync error of the session that ended. The tooltip of the
sync button shows the first line of a multi-line error.
This commit is contained in:
2026-12-02 08:49:46 +01:00
parent 03c7b17ccb
commit d45c3d024f
8 changed files with 115 additions and 19 deletions
+4 -4
View File
@@ -52,7 +52,7 @@ export function settingsHistory(): Doc<Settings>[] {
}
function validateSettings(s: Settings): void {
if (!(s.hours_per_week > 0)) throw new Error('hours_per_week must be greater than 0');
if (!(s.hours_per_week >= 0.01) || s.hours_per_week > 168) throw new Error('hours_per_week must be between 0.01 and 168');
if (!Number.isInteger(s.workdays_mask) || s.workdays_mask < 1 || s.workdays_mask > 127) {
throw new Error('workdays_mask must be between 1 and 127');
}
@@ -113,7 +113,7 @@ export async function startEntry(note = ''): Promise<string> {
export async function stopEntry(id: string): Promise<void> {
const e = get('entries', id);
if (!e || e.deleted || e.end_time !== null) throw new Error('no running entry found');
const cap = endOfDayMs(e.day_key, currentSettings().timezone);
const cap = endOfDayMs(e.day_key, currentSettings(e.day_key).timezone);
const now = Date.now();
await update('entries', id, {
end_time: Math.min(Math.max(now, e.start_time + 1), cap),
@@ -145,6 +145,7 @@ export async function updateEntry(id: string, patch: Partial<Pick<Entry, 'start_
const start = patch.start_time ?? e.start_time;
const end = patch.end_time === undefined ? e.end_time : patch.end_time;
if (!Number.isFinite(start) || (end !== null && !Number.isFinite(end))) throw new Error('start_time and end_time are required');
if (end === null && e.end_time !== null && runningEntry()) throw new Error('an entry is already running');
if (patch.note !== undefined) checkNote(patch.note);
const tz = currentSettings().timezone;
const day = dayKeyForMs(start, tz);
@@ -162,12 +163,11 @@ export async function deleteEntry(id: string): Promise<void> {
}
export async function autoStopStale(): Promise<number> {
const tz = currentSettings().timezone;
const today = todayKey();
let count = 0;
for (const e of all('entries')) {
if (e.end_time !== null || e.day_key >= today) continue;
await update('entries', e.id, { end_time: endOfDayMs(e.day_key, tz), auto_stopped: true });
await update('entries', e.id, { end_time: endOfDayMs(e.day_key, currentSettings(e.day_key).timezone), auto_stopped: true });
count += 1;
}
return count;
+41 -5
View File
@@ -12,7 +12,8 @@ import {
settingsHistory,
startEntry,
stopEntry,
todayKey
todayKey,
updateEntry
} from './app.svelte';
import { closeDb, get, openDb, remove, save, status } from './db.svelte';
import { DEFAULT_SETTINGS } from './types';
@@ -90,13 +91,19 @@ describe('settings', () => {
expect(settingsHistory().map((s) => s.effective_from)).toEqual(['2026-07-01', '2026-06-01', '2026-01-01']);
});
it('addSettings rejects invalid rows', async () => {
await expect(addSettings(row('2026-01-01', 0))).rejects.toThrow('hours_per_week must be greater than 0');
await expect(addSettings({ ...row('2026-01-01', 40), workdays_mask: 0 })).rejects.toThrow('workdays_mask must be between 1 and 127');
await expect(addSettings({ ...row('2026-01-01', 40), workdays_mask: 128 })).rejects.toThrow();
it('addSettings rejects rows outside the bounds of the server', async () => {
for (const hours of [0, 0.009, 168.01, NaN]) {
await expect(addSettings(row('2026-01-01', hours))).rejects.toThrow('hours_per_week must be between 0.01 and 168');
}
for (const workdays_mask of [0, 128, 1.5]) {
await expect(addSettings({ ...row('2026-01-01', 40), workdays_mask })).rejects.toThrow('workdays_mask must be between 1 and 127');
}
await expect(addSettings(row('01.01.2026', 40))).rejects.toThrow('effective_from must be a date');
await expect(addSettings({ ...row('2026-01-01', 40), timezone: 'Mars/Olympus' })).rejects.toThrow('unknown timezone');
expect(settingsHistory()).toHaveLength(0);
await addSettings(row('2026-01-01', 0.01));
await addSettings({ ...row('2026-02-01', 168), workdays_mask: 127 });
expect(settingsHistory().map((s) => s.hours_per_week)).toEqual([168, 0.01]);
});
it('deleteSettings refuses the last row', async () => {
@@ -164,6 +171,35 @@ describe('entries', () => {
await expect(createInterval(Date.parse('2026-06-16T08:00:00Z'), Date.parse('2026-06-16T09:00:00Z'))).resolves.toMatch(/^[a-z0-9]{15}$/);
});
it('autoStopStale and stopEntry end an entry in the timezone effective on its day', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date('2026-06-16T10:00:00Z'));
await addSettings({ ...row('2026-01-01', 40), timezone: 'UTC' });
await addSettings({ ...row('2026-06-15', 40), timezone: 'Europe/Berlin' });
expect(currentSettings().timezone).toBe('Europe/Berlin');
const inUtc = await save('entries', null, { start_time: Date.parse('2026-06-14T17:00:00Z'), end_time: null, auto_stopped: false, note: '', day_key: '2026-06-14' });
expect(await autoStopStale()).toBe(1);
expect(get('entries', inUtc)).toMatchObject({ end_time: Date.parse('2026-06-14T23:59:59.999Z'), auto_stopped: true });
const capped = await save('entries', null, { start_time: Date.parse('2026-06-15T17:00:00Z'), end_time: null, auto_stopped: false, note: '', day_key: '2026-06-15' });
await stopEntry(capped);
expect(get('entries', capped)).toMatchObject({ end_time: Date.parse('2026-06-15T21:59:59.999Z'), auto_stopped: true });
const today = await startEntry('today');
await stopEntry(today);
expect(get('entries', today)?.end_time).toBe(Date.parse('2026-06-16T10:00:00Z') + 1);
});
it('updateEntry refuses to let a second entry run', async () => {
const running = await save('entries', null, { start_time: Date.parse('2026-06-15T08:00:00Z'), end_time: null, auto_stopped: false, note: '', day_key: '2026-06-15' });
const interval = await save('entries', null, { start_time: Date.parse('2026-06-15T10:00:00Z'), end_time: Date.parse('2026-06-15T11:00:00Z'), auto_stopped: false, note: '', day_key: '2026-06-15' });
await expect(updateEntry(interval, { end_time: null })).rejects.toThrow('an entry is already running');
expect(get('entries', interval)?.end_time).toBe(Date.parse('2026-06-15T11:00:00Z'));
await updateEntry(running, { end_time: null, note: 'still running' });
expect(runningEntry()?.id).toBe(running);
await stopEntry(running);
await updateEntry(interval, { end_time: null });
expect(runningEntry()?.id).toBe(interval);
});
it('stopEntry caps a stale running entry at the end of its day', async () => {
vi.useFakeTimers({ toFake: ['Date'] });
vi.setSystemTime(new Date('2026-06-16T10:00:00Z'));
+15 -6
View File
@@ -45,6 +45,8 @@ const PUSH_BATCH = 200;
const REMOTE_DEBOUNCE = 300;
/** Upper bound for opening the local database in milliseconds. */
const OPEN_TIMEOUT = 8000;
/** Records updated this long before the cursor are pulled again: the server clock can move backwards, and upserts make duplicates harmless. */
const PULL_OVERLAP = 60_000;
const NUMBER_FIELDS: Record<CollectionName, string[]> = {
entries: ['start_time', 'end_time'],
@@ -151,7 +153,8 @@ function readOnce<T extends BaseItem, R>(
const cursorKey = (uid: string, name: string) => `wotra-cursor:${uid}:${name}`;
let userId = '';
let epoch = 0;
let pullRuns = 0;
/** Collections whose pull ran inside their current sync call; the collection is in sync once that call returns. */
const pulled = new Set<string>();
const pendingCursor = new Map<string, string>();
const staleBuffer = new Map<string, AnyDoc[]>();
/** Change records the last push of a collection sent; the pull after it keeps newer local changes. */
@@ -185,14 +188,19 @@ async function waitForApply(name: string): Promise<void> {
while (applying.has(name)) await pause();
}
/** Server records changed since the cursor; a pull inside an apply lets local writes run while the request is out. */
/** The cursor minus the overlap, in the format PocketBase writes updated. */
function overlap(cursor: string): string {
return new Date(Date.parse(cursor.replace(' ', 'T')) - PULL_OVERLAP).toISOString().replace('T', ' ');
}
/** Server records changed since the cursor minus the overlap; a pull inside an apply lets local writes run while the request is out. */
async function pullRecords(name: string, cursor: string | null): Promise<RecordModel[]> {
const inside = applying.has(name);
if (inside) leaveApply(name);
try {
return await pb.collection(name).getFullList({
sort: 'updated',
...(cursor ? { filter: pb.filter('updated >= {:c}', { c: cursor }) } : {})
...(cursor ? { filter: pb.filter('updated >= {:c}', { c: overlap(cursor) }) } : {})
});
} finally {
if (inside) enterApply(name);
@@ -270,14 +278,14 @@ class WotraSync extends SyncManager<Record<string, unknown>, AnyDoc, string> {
}
}
override async sync(name: string, options?: { force?: boolean; onlyWithChanges?: boolean }): Promise<void> {
const before = pullRuns;
pulled.delete(name);
try {
await super.sync(name, options);
} catch (e) {
this.failures.push(e);
throw e;
}
if (pullRuns !== before) onSynced(name);
if (pulled.delete(name)) onSynced(name);
}
}
@@ -356,7 +364,7 @@ async function doOpenDb(uid: string): Promise<void> {
else if (status.online) status.error = err.message;
},
pull: async ({ name }) => {
pullRuns += 1;
pulled.add(name);
const n = name as CollectionName;
const pushed = pushedChanges.get(name);
pushedChanges.delete(name);
@@ -529,6 +537,7 @@ export async function closeDb(): Promise<void> {
epoch += 1;
status.ready = false;
status.lastSync = 0;
status.error = null;
if (remoteTimer) clearTimeout(remoteTimer);
remoteTimer = null;
for (const c of cleanups.splice(0)) c();
+26 -1
View File
@@ -122,6 +122,8 @@ const settingsRow = { effective_from: '2026-01-01', hours_per_week: 40, workdays
const settled = () => new Promise<void>((resolve) => setTimeout(resolve, 0));
const databaseNames = async () => (await indexedDB.databases()).map((d) => d.name);
const cursor = (uid: string, name: string) => localStorage.getItem(`wotra-cursor:${uid}:${name}`);
/** The moment a pull asks for instead of the cursor: a minute earlier. */
const beforeCursor = (stored: string) => new Date(Date.parse(stored.replace(' ', 'T')) - 60_000).toISOString().replace('T', ' ');
beforeEach(async () => {
status.online = false;
@@ -600,6 +602,7 @@ describe('user switch', () => {
expect(cursor(a, 'settings_history')).not.toBeNull();
expect(status.lastSync).toBeGreaterThan(0);
expect(await databaseNames()).toContain(`wotra-${a}`);
status.error = 'settings_history x: rejected';
mocks.server.clear();
const givenUp = mocks.unsubscribed.length;
await wipeLocal(a);
@@ -607,6 +610,7 @@ describe('user switch', () => {
await openDb(b);
expect(status.ready).toBe(true);
expect(status.lastSync).toBe(0);
expect(status.error).toBeNull();
expect(all('settings_history', true)).toEqual([]);
expect(get('settings_history', id)).toBeUndefined();
expect(cursor(a, 'settings_history')).toBeNull();
@@ -627,7 +631,7 @@ describe('user switch', () => {
expect(stored).not.toBeNull();
mocks.filters.length = 0;
await syncNow();
expect(mocks.filters[COLLECTIONS.indexOf('settings_history')]).toBe(`updated >= "${stored}"`);
expect(mocks.filters[COLLECTIONS.indexOf('settings_history')]).toBe(`updated >= "${beforeCursor(stored!)}"`);
await wipeLocal(uid);
expect(status.ready).toBe(false);
expect(cursor(uid, 'settings_history')).toBeNull();
@@ -641,6 +645,27 @@ describe('user switch', () => {
});
});
describe('pull overlap', () => {
it('a pull with a cursor asks for a minute before it and still moves the cursor forward only', async () => {
status.online = true;
await save('settings_history', null, settingsRow);
await syncNow();
const uid = `user-${n}`;
const first = cursor(uid, 'settings_history');
expect(first).not.toBeNull();
const id = all('settings_history')[0]!.id;
const store = mocks.server.get('settings_history')!;
const record = store.get(id)!;
const later = mocks.stamp();
store.set(id, { ...record, hours_per_week: 35, client_updated_at: Number(record.client_updated_at) + 1_000_000, updated: later });
mocks.filters.length = 0;
await syncNow();
expect(mocks.filters[COLLECTIONS.indexOf('settings_history')]).toBe(`updated >= "${beforeCursor(first!)}"`);
expect(cursor(uid, 'settings_history')).toBe(later);
expect(get('settings_history', id)?.hours_per_week).toBe(35);
});
});
describe('network failures', () => {
it('a push failing after a good pull keeps the change records and the cursor, and the next round pushes everything', async () => {
status.online = true;
+3 -1
View File
@@ -114,7 +114,9 @@ export async function logout(): Promise<void> {
} catch {}
}
/** The local path to continue after sign-in; anything that could leave the origin, or cannot be a path, falls back. */
export function safeNext(url: URL, fallback = '/today'): string {
const n = url.searchParams.get('next');
return n && n.startsWith('/') && !/^\/[\\/]/.test(n) ? n : fallback;
if (!n || !n.startsWith('/') || /[\\]/.test(n) || /[\u0000-\u001f\u007f]/.test(n) || n.includes('//')) return fallback;
return n;
}
+3
View File
@@ -178,5 +178,8 @@ describe('safeNext', () => {
expect(next(encodeURIComponent('/week?day=2026-06-15'))).toBe('/week?day=2026-06-15');
expect(next('https://evil.example')).toBe('/today');
expect(next('')).toBe('/today');
for (const path of ['/week\\evil?day=1', '//evil.example', '/week//day', '/week\n', '/week\u0000', '/week\u007f']) {
expect(next(encodeURIComponent(path)), path).toBe('/today');
}
});
});
+2 -1
View File
@@ -71,7 +71,8 @@
const syncTitle = $derived.by(() => {
tick;
return error ?? (!online ? 'Offline' : `Last synced: ${formatLastSynced(lastSync)}`);
if (error) return error.split('\n')[0];
return !online ? 'Offline' : `Last synced: ${formatLastSynced(lastSync)}`;
});
</script>
+21 -1
View File
@@ -58,15 +58,35 @@
}
}
/** Opens the popup within the click, as the SDK would; null when the browser blocked it. */
function openPopup(): Window | null {
const width = Math.min(1024, window.innerWidth);
const height = Math.min(768, window.innerHeight);
const top = (window.innerHeight - height) / 2;
const left = (window.innerWidth - width) / 2;
return window.open('', 'popup_window', `width=${width},height=${height},top=${top},left=${left},resizable,menubar=no`);
}
async function oauth(provider: string) {
error = '';
const next = safeNext(page.url);
const popup = openPopup();
if (!popup) {
error = 'The popup was blocked';
return;
}
busy = true;
try {
await pb.collection('users').authWithOAuth2({ provider });
await pb.collection('users').authWithOAuth2({
provider,
urlCallback: (url) => {
popup.location.href = url;
}
});
if ((await resolveGate()) !== 'app') throw new Error('Sign in failed');
await goto(next, { replaceState: true });
} catch (err) {
popup.close();
error = describe(err);
} finally {
busy = false;