diff --git a/web/src/lib/app.svelte.ts b/web/src/lib/app.svelte.ts index bbb946b..593c7f5 100644 --- a/web/src/lib/app.svelte.ts +++ b/web/src/lib/app.svelte.ts @@ -52,7 +52,7 @@ export function settingsHistory(): Doc[] { } 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 { export async function stopEntry(id: string): Promise { 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 { } export async function autoStopStale(): Promise { - 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; diff --git a/web/src/lib/app.test.ts b/web/src/lib/app.test.ts index 294aa89..5d392a0 100644 --- a/web/src/lib/app.test.ts +++ b/web/src/lib/app.test.ts @@ -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')); diff --git a/web/src/lib/db.svelte.ts b/web/src/lib/db.svelte.ts index 8dd4850..0b92935 100644 --- a/web/src/lib/db.svelte.ts +++ b/web/src/lib/db.svelte.ts @@ -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 = { entries: ['start_time', 'end_time'], @@ -151,7 +153,8 @@ function readOnce( 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(); const pendingCursor = new Map(); const staleBuffer = new Map(); /** 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 { 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 { 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, AnyDoc, string> { } } override async sync(name: string, options?: { force?: boolean; onlyWithChanges?: boolean }): Promise { - 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 { 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 { 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(); diff --git a/web/src/lib/db.test.ts b/web/src/lib/db.test.ts index 2ea4145..e8fa81a 100644 --- a/web/src/lib/db.test.ts +++ b/web/src/lib/db.test.ts @@ -122,6 +122,8 @@ const settingsRow = { effective_from: '2026-01-01', hours_per_week: 40, workdays const settled = () => new Promise((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; diff --git a/web/src/lib/session.svelte.ts b/web/src/lib/session.svelte.ts index 1336123..3dfa24c 100644 --- a/web/src/lib/session.svelte.ts +++ b/web/src/lib/session.svelte.ts @@ -114,7 +114,9 @@ export async function logout(): Promise { } 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; } diff --git a/web/src/lib/session.test.ts b/web/src/lib/session.test.ts index 780704b..6f7237a 100644 --- a/web/src/lib/session.test.ts +++ b/web/src/lib/session.test.ts @@ -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'); + } }); }); diff --git a/web/src/routes/+layout.svelte b/web/src/routes/+layout.svelte index 0444136..107b46d 100644 --- a/web/src/routes/+layout.svelte +++ b/web/src/routes/+layout.svelte @@ -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)}`; }); diff --git a/web/src/routes/login/+page.svelte b/web/src/routes/login/+page.svelte index 03e7c44..766eef2 100644 --- a/web/src/routes/login/+page.svelte +++ b/web/src/routes/login/+page.svelte @@ -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;