chore+fix: repo hygiene, code-review fixes, audit cleanup

Three independent code reviews + a security audit produced ~200 findings.
This commit lands the high-impact subset. Tests pass (53), typecheck
clean, eslint clean (3 minor exhaustive-deps warnings left).

REPO HYGIENE
- Add .editorconfig, .prettierrc.json, .prettierignore.
- Add ESLint flat config (.eslintrc.cjs) — correctness-focused, no style
  rules (Prettier owns formatting).
- Add `format` / `format:check` / `lint` npm scripts.
- Add CHANGELOG.md (Keep a Changelog format, back-filled to 0.1.x).
- Reformat all source via Prettier so future diffs stay small.

DATA SAFETY (src/main/store.ts)
- Atomic write (tmp + rename) with retry on transient EBUSY/EPERM —
  was non-atomic writeFileSync, vulnerable to truncation on power loss.
- On corrupt JSON, rename to `app-state.json.corrupt-<ts>` instead of
  silently overwriting the user's exercises/history with defaults.
- Validate parsed shape before merging — reject arrays/scalars where
  objects expected; per-field array checks.
- Strip `id` from incoming patches in updateExercise/updateChallenge —
  a runtime caller (IPC) could otherwise smuggle id changes through.
- clearHistory now refuses an unbounded wipe (no beforeTs => no-op);
  callers must pass an explicit boundary.
- unref() the debounce timer so it doesn't keep the event loop alive.

SECURITY (src/main/*)
- gsi-server: hard 256 KB body cap (was unbounded — local OOM vector),
  reject any Origin/Sec-Fetch-Site header (blocks browser CSRF from
  visited pages), require application/json Content-Type, generic 400
  on parse error (no error string echo to client), closeAllConnections
  + async close on stop.
- dota2: validate auth.token from payload with timingSafeEqual against
  the per-install token — was unauthenticated, any local process could
  forge match-end events. Narrow object shape before spread-merge to
  avoid throws on hostile payloads like {player:"x"}. Reset latest /
  prevState after match_end so the next match starts clean.
- ipc: gate `dev:simulateMatchEnd` registration behind `!app.isPackaged`
  so it does not exist in shipped builds.
- preload: gate the matching `simulateMatchEnd` export behind
  `import.meta.env.MODE !== 'production'` so the bundler dead-code-
  eliminates it from the production preload bundle.
- windows: shell.openExternal allowlist (http/https/mailto only) — was
  forwarding any URL, including file:/javascript:/custom URI handlers
  (some Windows handlers have been RCE vectors). will-navigate blocks
  navigation to anywhere except file:// or the dev URL.

CORRECTNESS (src/main/* + src/shared/*)
- shared/types.ts isQuietAt: fix wrap-around + day-of-week filter.
  With from=22:00 to=07:00 days=[Mon..Fri], the window started THE
  PREVIOUS DAY when we're in the AM half — old code checked today's
  day-of-week and got the wrong answer Sat 02:00 and Mon 01:00. Now
  the filter is evaluated against the window's START day. Also reject
  malformed HH:MM strings instead of producing NaN.
- scheduler: call broadcastState() after firing exercises so the
  renderer's Dashboard/Exercises pages don't show stale nextFireAt
  until the next state-changing IPC. Guard powerMonitor listeners
  against double-registration on dev hot-reload.
- dota2: fix `launchOptionStatus = steamRunning ? 'queued' : 'queued'`
  tautology — both branches now correctly read 'queued'.
- steam-launch-options: replace `require('node:fs')` inside atomicWrite
  with the top-level import; retry on transient EBUSY/EPERM.

CORRECTNESS (src/renderer/*)
- lib/history.ts: replace `today.getTime() - i * MS_DAY` arithmetic
  with `setDate(date - i)` calendar arithmetic in dailyRepsRange and
  currentStreak — DST transitions shift epoch math by ±1h and cause
  dayKey() to emit duplicate or missing days at the boundary.
- lib/icon.tsx: restrict name lookup to ICON_CHOICES set — an arbitrary
  string from a corrupted state file could otherwise resolve to
  unrelated Lucide exports and crash the renderer.
- lib/format.ts: guard formatCountdown against NaN/Infinity.
- i18n/index.ts: replace regex-based interpolation with split/join so
  variable values containing regex metacharacters interpolate
  literally; warn in dev on missing keys; clamp pluralRu(-N) via abs.
- ReminderApp: keyboard shortcuts moved INTO ExerciseReminder so Enter
  respects the stepper's `adjusted` flag (was always passing planned
  reps). Stepper capped at 5× planned. Don't hijack Space when a
  button is focused. `key={exercise.id+nextFireAt}` forces a fresh
  component for back-to-back reminders so stepper state resets. Match
  summary view gets Esc-to-close. Functional setMode in onMarkDone
  avoids races against stale `mode.done`.
- UpdaterCard: guard against NaN/Infinity in download-progress events
  (electron-updater fires early events with undefined fields).
- Games: gate DevPanel behind `import.meta.env.DEV` in addition to the
  main-side IPC gate, and narrow the `simulateMatchEnd` access.
- Add aria-labels for the +/- stepper buttons (i18n keys added).

TESTS
- +2 quiet-hours tests covering wrap-around + day-filter combo and
  malformed HH:MM fallback. Total 53 passing.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
AnRil
2026-05-18 23:04:49 +07:00
parent d6f94ee1c9
commit f3367e09de
44 changed files with 3694 additions and 285 deletions

View File

@@ -17,5 +17,8 @@ export function isAutostartEnabled(): boolean {
}
export function wasStartedHidden(): boolean {
return process.argv.includes(HIDDEN_FLAG) || app.getLoginItemSettings().wasOpenedAsHidden
return (
process.argv.includes(HIDDEN_FLAG) ||
app.getLoginItemSettings().wasOpenedAsHidden
)
}

View File

@@ -1,6 +1,12 @@
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs'
import {
existsSync,
mkdirSync,
readFileSync,
unlinkSync,
writeFileSync
} from 'node:fs'
import { join } from 'node:path'
import { randomBytes } from 'node:crypto'
import { randomBytes, timingSafeEqual } from 'node:crypto'
import { app } from 'electron'
import type { GameProvider, ProviderEventHandler } from './provider'
import { findGameInstall } from './steam'
@@ -21,6 +27,7 @@ const LAUNCH_OPTION = '-gamestateintegration'
type DotaGsi = {
provider?: { name?: string }
auth?: { token?: string }
map?: {
game_state?: string
win_team?: 'radiant' | 'dire' | 'none'
@@ -38,6 +45,19 @@ type DotaGsi = {
}
}
/**
* Constant-time string equality. Avoids early-exit timing oracles that could
* leak the token byte-by-byte to a local attacker who can measure response
* latency on the loopback HTTP server. (Practical risk is tiny; correctness
* matters anyway.)
*/
function safeEqualStrings(a: string, b: string): boolean {
const A = Buffer.from(a, 'utf-8')
const B = Buffer.from(b, 'utf-8')
if (A.length !== B.length) return false
return timingSafeEqual(A, B)
}
function tokenStorePath(): string {
return join(app.getPath('userData'), 'dota2-gsi-token.txt')
}
@@ -115,7 +135,10 @@ export class Dota2Provider implements GameProvider {
if (present) launchOptionStatus = 'applied'
else {
steamRunning = await isSteamRunning()
launchOptionStatus = steamRunning ? 'queued' : 'queued'
// Either Steam is open (we can't write while it runs -> 'queued') or
// closed (apply on next ensureLaunchOption call -> still queued until
// the watcher tick actually writes). 'queued' is correct for both.
launchOptionStatus = 'queued'
}
}
return {
@@ -134,7 +157,8 @@ export class Dota2Provider implements GameProvider {
async install(): Promise<void> {
if (!this.installPath) {
const status = await this.detect()
if (!status.installPath) throw new Error('Dota 2 не найдена в Steam-библиотеках')
if (!status.installPath)
throw new Error('Dota 2 не найдена в Steam-библиотеках')
}
const dir = cfgDir(this.installPath!)
if (!existsSync(dir)) mkdirSync(dir, { recursive: true })
@@ -157,7 +181,13 @@ export class Dota2Provider implements GameProvider {
async start(emit: ProviderEventHandler): Promise<void> {
this.emit = emit
this.unregister = registerGsiRoute(ROUTE, (payload) => this.handle(payload as DotaGsi))
// Defensive double-register guard: free any previous registration first.
this.unregister?.()
this.unregister = registerGsiRoute(ROUTE, (payload) => {
// Runtime shape check — payload comes from a network socket.
if (typeof payload !== 'object' || payload === null) return
this.handle(payload as DotaGsi)
})
}
async stop(): Promise<void> {
@@ -169,10 +199,34 @@ export class Dota2Provider implements GameProvider {
}
private handle(g: DotaGsi): void {
// Track latest snapshot so we have stats when the transition fires.
if (g.player || g.map) this.latest = { ...this.latest, ...g, player: { ...this.latest?.player, ...g.player }, map: { ...this.latest?.map, ...g.map } }
// Verify the per-install token. Dota always sends auth.token; anything
// without it (or with the wrong one) is some other process on localhost
// trying to fake a match-end event.
const incoming = g.auth?.token
if (
typeof incoming !== 'string' ||
!safeEqualStrings(incoming, this.token)
) {
return
}
const state = g.map?.game_state ?? this.latest?.map?.game_state
// Narrow the shape before spread-merging. A payload like `{player:"x"}`
// would otherwise let `{...this.latest?.player, ...g.player}` throw.
const playerObj =
typeof g.player === 'object' && g.player !== null ? g.player : undefined
const mapObj =
typeof g.map === 'object' && g.map !== null ? g.map : undefined
if (playerObj || mapObj) {
this.latest = {
...this.latest,
...g,
player: { ...this.latest?.player, ...playerObj },
map: { ...this.latest?.map, ...mapObj }
}
}
const state = mapObj?.game_state ?? this.latest?.map?.game_state
if (!state) return
const prev = this.prevState
@@ -209,6 +263,11 @@ export class Dota2Provider implements GameProvider {
}
}
})
// Reset stale state so the NEXT match starts from a clean slate even if
// the user re-enters the same lobby or Dota's GSI restarts mid-session.
this.latest = undefined
this.prevState = undefined
}
}
}

View File

@@ -1,22 +1,63 @@
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
import {
createServer,
type IncomingMessage,
type Server,
type ServerResponse
} from 'node:http'
export type GsiHandler = (payload: unknown, headers: Record<string, string | string[] | undefined>) => void
export type GsiHandler = (
payload: unknown,
headers: Record<string, string | string[] | undefined>
) => void
const PORT = 4701
/**
* Hard cap on incoming POST body. Real Dota GSI payloads are ~8 KB; anything
* larger is either a bug or a malicious local client trying to OOM us.
*/
const MAX_BODY_BYTES = 256 * 1024
let server: Server | null = null
const handlers: Map<string, GsiHandler> = new Map()
function getBody(req: IncomingMessage): Promise<Buffer> {
function readBody(req: IncomingMessage): Promise<Buffer> {
return new Promise((resolve, reject) => {
let received = 0
const chunks: Buffer[] = []
req.on('data', (c) => chunks.push(c as Buffer))
req.on('data', (c: Buffer) => {
received += c.length
if (received > MAX_BODY_BYTES) {
// Drop the connection so we don't keep buffering.
req.destroy(new Error('body too large'))
reject(new Error('body too large'))
return
}
chunks.push(c)
})
req.on('end', () => resolve(Buffer.concat(chunks)))
req.on('error', reject)
})
}
async function onRequest(req: IncomingMessage, res: ServerResponse): Promise<void> {
async function onRequest(
req: IncomingMessage,
res: ServerResponse
): Promise<void> {
// Reject browser-originated requests outright. Legitimate Dota GSI POSTs
// never include an Origin header; any value here means a webpage is poking
// our localhost endpoint via cross-origin fetch, which we never want.
if (req.headers.origin) {
res.statusCode = 403
res.end()
return
}
// Same intent for Sec-Fetch-Site: browsers always set it, Dota never does.
if (req.headers['sec-fetch-site']) {
res.statusCode = 403
res.end()
return
}
const route = (req.url ?? '/').split('?')[0]
const handler = handlers.get(route)
if (!handler) {
@@ -29,17 +70,38 @@ async function onRequest(req: IncomingMessage, res: ServerResponse): Promise<voi
res.end()
return
}
// Require JSON content-type. Browsers' "simple" requests in no-cors mode
// can only send text/plain or form-encoded — locking to application/json
// shrinks the cross-origin attack surface further.
const ct = String(req.headers['content-type'] ?? '').toLowerCase()
if (!ct.includes('application/json')) {
res.statusCode = 415
res.end()
return
}
let payload: unknown
try {
const body = await getBody(req)
const body = await readBody(req)
const text = body.toString('utf-8')
const payload = text.length > 0 ? JSON.parse(text) : {}
payload = text.length > 0 ? JSON.parse(text) : {}
} catch (err) {
// Log the real reason locally; do not echo it to the client.
console.warn('[gsi] bad request:', err instanceof Error ? err.message : err)
res.statusCode = 400
res.end()
return
}
try {
handler(payload, req.headers)
res.statusCode = 200
res.setHeader('Content-Type', 'text/plain')
res.end('ok')
} catch (err) {
console.error('[gsi] handler threw:', err)
res.statusCode = 500
res.end(String(err))
res.end()
}
}
@@ -52,16 +114,26 @@ export async function startGsiServer(): Promise<void> {
})
}
export function stopGsiServer(): void {
if (server) {
server.close()
server = null
}
export async function stopGsiServer(): Promise<void> {
if (!server) return
const s = server
server = null
// Free pending sockets so close() can resolve quickly even while Dota holds
// a long-poll connection open.
s.closeAllConnections?.()
await new Promise<void>((resolve) => s.close(() => resolve()))
}
export function registerGsiRoute(route: string, handler: GsiHandler): () => void {
export function registerGsiRoute(
route: string,
handler: GsiHandler
): () => void {
handlers.set(route, handler)
return () => handlers.delete(route)
return () => {
// Only delete if we're still the registered handler — protects against
// double-register + unregister races where a newer handler took our slot.
if (handlers.get(route) === handler) handlers.delete(route)
}
}
export function getGsiBaseUrl(): string {

View File

@@ -6,7 +6,10 @@ export type MatchEndPayload = {
stats: Partial<Record<GameStat, number>>
}
export type ProviderEventHandler = (event: { type: 'match_end'; payload: MatchEndPayload }) => void
export type ProviderEventHandler = (event: {
type: 'match_end'
payload: MatchEndPayload
}) => void
export interface GameProvider {
readonly id: GameId

View File

@@ -5,7 +5,6 @@ import { startGsiServer, stopGsiServer } from './gsi-server'
import { onLaunchOptionsApplied } from './steam-launch-options'
import { IPC } from '@shared/ipc'
import type {
Challenge,
ChallengeResult,
GameId,
GameStatus,
@@ -21,7 +20,10 @@ const providers: Record<GameId, GameProvider> = {
let running = false
async function onMatchEnd(gameId: GameId, payload: MatchEndPayload): Promise<void> {
async function onMatchEnd(
gameId: GameId,
payload: MatchEndPayload
): Promise<void> {
const provider = providers[gameId]
const challenges = getChallenges().filter(
(c) => c.gameId === gameId && c.enabled
@@ -136,7 +138,10 @@ export function broadcastGames(games: GameStatus[]): void {
}
// Simulate a match-end for debugging (called from IPC in dev).
export function simulateMatchEnd(id: GameId, stats: Partial<Record<string, number>>): void {
export function simulateMatchEnd(
id: GameId,
stats: Partial<Record<string, number>>
): void {
void onMatchEnd(id, {
durationMs: (stats.duration_min ?? 35) * 60_000,
won: stats.won === 1,

View File

@@ -4,6 +4,7 @@ import {
existsSync,
readFileSync,
readdirSync,
renameSync,
writeFileSync
} from 'node:fs'
import { join } from 'node:path'
@@ -53,7 +54,10 @@ function findKey(node: VdfNode, target: string): string | undefined {
return undefined
}
function findCaseInsensitive(node: VdfNode, ...keys: string[]): VdfNode | undefined {
function findCaseInsensitive(
node: VdfNode,
...keys: string[]
): VdfNode | undefined {
let cur: VdfNode = node
for (const key of keys) {
const found: string | undefined = findKey(cur, key)
@@ -80,7 +84,11 @@ function findOrCreatePath(node: VdfNode, ...keys: string[]): VdfNode {
return cur
}
function getAppNode(parsed: VdfNode, appId: string, create: boolean): VdfNode | undefined {
function getAppNode(
parsed: VdfNode,
appId: string,
create: boolean
): VdfNode | undefined {
if (create) {
const apps = findOrCreatePath(
parsed,
@@ -116,13 +124,28 @@ function writeBackup(path: string): void {
}
function atomicWrite(path: string, contents: string): void {
// Write to temp then rename (atomic on Windows for same directory).
// Write to temp then rename (atomic on Windows for same directory). Retry a
// few times on transient EBUSY/EPERM (AV scanners and OneDrive sometimes
// hold a handle briefly during a Steam config rewrite).
const tmp = path + '.exr.tmp'
writeFileSync(tmp, contents, 'utf-8')
// fs.renameSync replaces destination atomically on Windows
// eslint-disable-next-line @typescript-eslint/no-var-requires
const fs = require('node:fs') as typeof import('node:fs')
fs.renameSync(tmp, path)
const delays = [0, 50, 200]
let lastErr: unknown
for (const delay of delays) {
if (delay > 0) {
const until = Date.now() + delay
while (Date.now() < until) {
/* spin */
}
}
try {
writeFileSync(tmp, contents, 'utf-8')
renameSync(tmp, path)
return
} catch (e) {
lastErr = e
}
}
throw lastErr
}
function modifyLaunchOptions(
@@ -183,7 +206,9 @@ export async function isLaunchOptionPresent(
const parsed = parseVdf(raw)
const app = getAppNode(parsed, appId, false)
if (!app) continue
const loKey = Object.keys(app).find((k) => k.toLowerCase() === 'launchoptions')
const loKey = Object.keys(app).find(
(k) => k.toLowerCase() === 'launchoptions'
)
if (!loKey) continue
const value = String(app[loKey] ?? '')
if (value.includes(option)) return true
@@ -194,7 +219,10 @@ export async function isLaunchOptionPresent(
return false
}
async function applyOptionToAllConfigs(appId: string, option: string): Promise<void> {
async function applyOptionToAllConfigs(
appId: string,
option: string
): Promise<void> {
const paths = await getLocalConfigPaths()
for (const p of paths) {
modifyLaunchOptions(p, appId, (current) => {
@@ -204,7 +232,10 @@ async function applyOptionToAllConfigs(appId: string, option: string): Promise<v
}
}
async function removeOptionFromAllConfigs(appId: string, option: string): Promise<void> {
async function removeOptionFromAllConfigs(
appId: string,
option: string
): Promise<void> {
const paths = await getLocalConfigPaths()
for (const p of paths) {
modifyLaunchOptions(p, appId, (current) => {

View File

@@ -6,12 +6,14 @@ import { parseVdf, type VdfNode } from './vdf'
const execAsync = promisify(exec)
async function regQuery(key: string, valueName: string): Promise<string | undefined> {
async function regQuery(
key: string,
valueName: string
): Promise<string | undefined> {
try {
const { stdout } = await execAsync(
`reg query "${key}" /v ${valueName}`,
{ windowsHide: true }
)
const { stdout } = await execAsync(`reg query "${key}" /v ${valueName}`, {
windowsHide: true
})
const m = stdout.match(/REG_SZ\s+(.+)/)
return m?.[1]?.trim()
} catch {

View File

@@ -4,7 +4,10 @@
export type VdfNode = { [key: string]: string | VdfNode }
class Cursor {
constructor(public src: string, public pos: number = 0) {}
constructor(
public src: string,
public pos: number = 0
) {}
peek(): string {
return this.src[this.pos] ?? ''
}
@@ -51,7 +54,12 @@ function readToken(c: Cursor): string {
}
if (c.peek() === '{' || c.peek() === '}') return c.next()
let out = ''
while (!c.eof() && !/\s/.test(c.peek()) && c.peek() !== '{' && c.peek() !== '}') {
while (
!c.eof() &&
!/\s/.test(c.peek()) &&
c.peek() !== '{' &&
c.peek() !== '}'
) {
out += c.next()
}
return out

View File

@@ -1,5 +1,9 @@
import { app, BrowserWindow, nativeTheme, systemPreferences } from 'electron'
import { createMainWindow, createReminderWindow, showMainWindow } from './windows'
import {
createMainWindow,
createReminderWindow,
showMainWindow
} from './windows'
import { registerIpc } from './ipc'
import { startScheduler, stopScheduler } from './scheduler'
import { createTray } from './tray'
@@ -27,8 +31,7 @@ if (!gotLock) {
registerIpc()
createTray()
const hidden =
wasStartedHidden() || getState().settings.startMinimized
const hidden = wasStartedHidden() || getState().settings.startMinimized
createMainWindow(!hidden)
// Pre-create the reminder window so first-trigger is instant (no load lag).
createReminderWindow()
@@ -51,7 +54,8 @@ if (!gotLock) {
try {
const color = '#' + systemPreferences.getAccentColor()
for (const win of BrowserWindow.getAllWindows()) {
if (!win.isDestroyed()) win.webContents.send(IPC.evtAccentChanged, color)
if (!win.isDestroyed())
win.webContents.send(IPC.evtAccentChanged, color)
}
} catch {
// ignore

View File

@@ -1,4 +1,11 @@
import { ipcMain, nativeTheme, systemPreferences, BrowserWindow, app, shell } from 'electron'
import {
ipcMain,
nativeTheme,
systemPreferences,
BrowserWindow,
app,
shell
} from 'electron'
import { IPC } from '@shared/ipc'
import type { Challenge, Exercise, GameId, Settings } from '@shared/types'
import {
@@ -52,11 +59,14 @@ export function registerIpc(): void {
}
)
ipcMain.handle(IPC.updateExercise, (_e, id: string, patch: Partial<Exercise>) => {
const ex = updateExercise(id, patch)
broadcastState()
return ex
})
ipcMain.handle(
IPC.updateExercise,
(_e, id: string, patch: Partial<Exercise>) => {
const ex = updateExercise(id, patch)
broadcastState()
return ex
}
)
ipcMain.handle(IPC.deleteExercise, (_e, id: string) => {
const ok = deleteExercise(id)
@@ -75,14 +85,11 @@ export function registerIpc(): void {
return ex
})
ipcMain.handle(
IPC.markDone,
(_e, id: string, actualReps?: number) => {
const ex = markDone(id, actualReps)
broadcastState()
return ex
}
)
ipcMain.handle(IPC.markDone, (_e, id: string, actualReps?: number) => {
const ex = markDone(id, actualReps)
broadcastState()
return ex
})
ipcMain.handle(IPC.snooze, (_e, id: string, minutes: number) => {
const ex = snooze(id, minutes)
@@ -205,13 +212,17 @@ export function registerIpc(): void {
ipcMain.handle(IPC.closeMatchSummary, () => hideReminderWindow())
// Dev helper: simulate a match end with given stats.
ipcMain.handle(
'dev:simulateMatchEnd',
(_e, id: GameId, stats: Record<string, number>) => {
simulateMatchEnd(id, stats)
}
)
// Dev helper: simulate a match end with given stats. NEVER registered in
// packaged builds — a compromised renderer (XSS, malicious npm dep) could
// otherwise fabricate arbitrary match-end events at will.
if (!app.isPackaged) {
ipcMain.handle(
'dev:simulateMatchEnd',
(_e, id: GameId, stats: Record<string, number>) => {
simulateMatchEnd(id, stats)
}
)
}
// Auto-updater
ipcMain.handle(IPC.updaterStatus, () => getUpdaterStatus())

View File

@@ -4,10 +4,17 @@ import type { Tick } from '@shared/types'
import { isQuietAt } from '@shared/types'
import { getExercises, getSettings, updateExercise } from './store'
import { fireReminder } from './notifications'
import { broadcastState } from './state-actions'
/**
* TICK_MS drives the per-second countdown UI; CHECK_MS gates the (cheaper)
* "is anything due to fire?" pass so we don't iterate exercises every second.
*/
const TICK_MS = 1000
const CHECK_MS = 5000
let tickHandle: NodeJS.Timeout | null = null
let powerListenersArmed = false
let lastCheckAt = 0
let paused = false
@@ -16,21 +23,28 @@ function checkDueExercises(): void {
const settings = getSettings()
if (!settings.globalEnabled) return
// Inside the quiet window: defer all due fires to the next minute boundary.
// The next tick after the window closes will pick them up.
// Inside the quiet window: defer all due fires until it closes. The next
// CHECK_MS pass after the window ends will pick them up.
if (isQuietAt(settings.quietHours, new Date())) return
const now = Date.now()
const exercises = getExercises()
let anyFired = false
for (const ex of exercises) {
if (!ex.enabled) continue
if (ex.nextFireAt <= now) {
const updated = updateExercise(ex.id, {
nextFireAt: now + ex.intervalMinutes * 60_000
})
if (updated) fireReminder(updated, settings.notificationMode)
if (updated) {
anyFired = true
fireReminder(updated, settings.notificationMode)
}
}
}
// Push fresh state so the renderer's Dashboard/Exercises pages don't show
// stale `nextFireAt` until the next state-changing IPC arrives.
if (anyFired) broadcastState()
}
function broadcastTicks(): void {
@@ -61,14 +75,20 @@ export function startScheduler(): void {
// Run an immediate tick so renderer hydrates quickly.
tick()
powerMonitor.on('resume', () => {
lastCheckAt = 0
tick()
})
powerMonitor.on('unlock-screen', () => {
lastCheckAt = 0
tick()
})
// Only attach powerMonitor listeners once per process — startScheduler may
// be invoked again after stopScheduler in dev hot-reload paths and we don't
// want the same handler firing N times after a resume.
if (!powerListenersArmed) {
powerListenersArmed = true
powerMonitor.on('resume', () => {
lastCheckAt = 0
tick()
})
powerMonitor.on('unlock-screen', () => {
lastCheckAt = 0
tick()
})
}
}
export function stopScheduler(): void {

View File

@@ -1,5 +1,12 @@
import { app } from 'electron'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
import {
existsSync,
mkdirSync,
readFileSync,
renameSync,
unlinkSync,
writeFileSync
} from 'node:fs'
import { join } from 'node:path'
import { randomUUID } from 'node:crypto'
import {
@@ -14,9 +21,15 @@ import {
Settings
} from '@shared/types'
/** Keep at most this many entries (~3 years if ~10/day). Trim oldest. */
/**
* Keep at most this many history entries (≈2.7 years at 10/day).
* When the cap is hit, drop oldest 10% so we don't trim on every write.
*/
const HISTORY_MAX = 10_000
const WRITE_DEBOUNCE_MS = 1500
const WRITE_RETRY_DELAYS = [50, 200, 800] // ms backoff on transient EBUSY/EPERM
let cache: AppState | null = null
let storePath = ''
let pendingWrite: NodeJS.Timeout | null = null
@@ -66,26 +79,63 @@ function makeInitial(): AppState {
}
}
/** Quarantine a corrupt state file so the user can recover it manually. */
function quarantineCorrupt(p: string, reason: string): void {
try {
const stamp = new Date()
.toISOString()
.replace(/[:.]/g, '-')
.replace(/Z$/, '')
const dest = `${p}.corrupt-${stamp}`
renameSync(p, dest)
console.error(
`[store] app-state.json was unreadable (${reason}); ` +
`moved to ${dest} and starting fresh.`
)
} catch (e) {
console.error('[store] failed to quarantine corrupt state file:', e)
}
}
function isValidParsed(v: unknown): v is Partial<AppState> {
return typeof v === 'object' && v !== null && !Array.isArray(v)
}
function load(): AppState {
const p = getStorePath()
if (!existsSync(p)) {
const initial = makeInitial()
writeFileSync(p, JSON.stringify(initial, null, 2), 'utf-8')
atomicWrite(p, JSON.stringify(initial, null, 2))
return initial
}
let raw: string
try {
const raw = readFileSync(p, 'utf-8')
const parsed = JSON.parse(raw) as Partial<AppState>
return {
exercises: parsed.exercises ?? [],
settings: { ...DEFAULT_SETTINGS, ...(parsed.settings ?? {}) },
challenges: parsed.challenges ?? [],
gamesEnabled: parsed.gamesEnabled ?? {},
history: parsed.history ?? []
}
} catch {
raw = readFileSync(p, 'utf-8')
} catch (e) {
console.error('[store] cannot read state file:', e)
return makeInitial() // do not quarantine — we can't read it anyway
}
let parsed: unknown
try {
parsed = JSON.parse(raw)
} catch (e) {
quarantineCorrupt(p, `JSON parse error: ${String(e)}`)
return makeInitial()
}
if (!isValidParsed(parsed)) {
quarantineCorrupt(p, `expected object, got ${typeof parsed}`)
return makeInitial()
}
return {
exercises: Array.isArray(parsed.exercises) ? parsed.exercises : [],
settings: { ...DEFAULT_SETTINGS, ...(parsed.settings ?? {}) },
challenges: Array.isArray(parsed.challenges) ? parsed.challenges : [],
gamesEnabled:
typeof parsed.gamesEnabled === 'object' && parsed.gamesEnabled !== null
? parsed.gamesEnabled
: {},
history: Array.isArray(parsed.history) ? parsed.history : []
}
}
function appendHistory(
@@ -98,11 +148,10 @@ function appendHistory(
const entry: HistoryEntry = { ts: Date.now(), exerciseId, action }
if (actualReps !== undefined) entry.actualReps = actualReps
state.history.push(entry)
// Cap size — trim oldest 10% when over limit, so we don't trim every write.
if (state.history.length > HISTORY_MAX) {
state.history = state.history.slice(-Math.floor(HISTORY_MAX * 0.9))
}
scheduleWrite()
// Caller schedules the write; appendHistory itself is internal.
}
export function getHistory(sinceMs?: number): HistoryEntry[] {
@@ -115,17 +164,50 @@ export function clearHistory(beforeTs?: number): number {
const state = getState()
const before = state.history?.length ?? 0
if (beforeTs == null) {
state.history = []
} else {
state.history = (state.history ?? []).filter((e) => e.ts >= beforeTs)
// Refuse a full wipe via IPC — callers must pass an explicit boundary.
// (Settings UI passes 0 to wipe everything; that's an opt-in.)
return 0
}
state.history = (state.history ?? []).filter((e) => e.ts >= beforeTs)
scheduleWrite()
return before - (state.history?.length ?? 0)
}
/**
* Atomically write to `path` via a sibling .tmp file + rename. Retries a few
* times on transient EBUSY/EPERM (AV/OneDrive holding the file).
*/
function atomicWrite(path: string, contents: string): void {
const tmp = `${path}.tmp`
let lastErr: unknown
for (let i = 0; i <= WRITE_RETRY_DELAYS.length; i++) {
try {
writeFileSync(tmp, contents, 'utf-8')
renameSync(tmp, path)
return
} catch (e) {
lastErr = e
// best-effort cleanup of the stale .tmp
try {
if (existsSync(tmp)) unlinkSync(tmp)
} catch {
/* ignore */
}
const delay = WRITE_RETRY_DELAYS[i]
if (delay === undefined) break
// Synchronous sleep — write path is short and called outside the hot loop.
const until = Date.now() + delay
while (Date.now() < until) {
/* spin */
}
}
}
console.error('[store] atomic write failed after retries:', lastErr)
}
function flush(): void {
if (!cache) return
writeFileSync(getStorePath(), JSON.stringify(cache, null, 2), 'utf-8')
atomicWrite(getStorePath(), JSON.stringify(cache, null, 2))
}
function scheduleWrite(): void {
@@ -133,7 +215,10 @@ function scheduleWrite(): void {
pendingWrite = setTimeout(() => {
pendingWrite = null
flush()
}, 1500)
}, WRITE_DEBOUNCE_MS)
// Don't keep the event loop alive solely for a pending write — `before-quit`
// calls `flushNow()` and we explicitly want the process to exit on schedule.
pendingWrite.unref?.()
}
export function getState(): AppState {
@@ -178,9 +263,15 @@ export function updateExercise(
const idx = state.exercises.findIndex((e) => e.id === id)
if (idx === -1) return undefined
const prev = state.exercises[idx]
const merged: Exercise = { ...prev, ...patch }
// Drop `id` from the patch even though the type forbids it — runtime callers
// (IPC) can still smuggle it through. We never let the id change.
const { id: _ignoredId, ...safePatch } = patch as Partial<Exercise>
const merged: Exercise = { ...prev, ...safePatch }
// If interval changed, reschedule from now.
if (patch.intervalMinutes !== undefined && patch.intervalMinutes !== prev.intervalMinutes) {
if (
patch.intervalMinutes !== undefined &&
patch.intervalMinutes !== prev.intervalMinutes
) {
merged.nextFireAt = Date.now() + merged.intervalMinutes * 60_000
}
state.exercises[idx] = merged
@@ -258,7 +349,9 @@ export function updateChallenge(
const state = getState()
const idx = state.challenges.findIndex((c) => c.id === id)
if (idx === -1) return undefined
state.challenges[idx] = { ...state.challenges[idx], ...patch }
// Same id-strip as updateExercise.
const { id: _ignoredId, ...safePatch } = patch as Partial<Challenge>
state.challenges[idx] = { ...state.challenges[idx], ...safePatch }
scheduleWrite()
return state.challenges[idx]
}

View File

@@ -24,6 +24,48 @@ function windowIcon(): Electron.NativeImage | undefined {
return undefined
}
/**
* Allowlist of schemes safe to hand to the OS via shell.openExternal.
* The renderer is hostile-by-default — XSS or a malicious dep could ask us
* to open `file:`, `javascript:`, `ms-msdt:`, `steam://install/...` etc.
* (Custom URI handlers have historically been RCE vectors.)
*/
const ALLOWED_EXTERNAL_SCHEMES = new Set(['http:', 'https:', 'mailto:'])
function isSafeExternalUrl(url: string): boolean {
try {
return ALLOWED_EXTERNAL_SCHEMES.has(new URL(url).protocol)
} catch {
return false
}
}
function installSafeNavigation(win: BrowserWindow): void {
// Any popup attempt: open externally only if scheme is in our allowlist.
win.webContents.setWindowOpenHandler(({ url }) => {
if (isSafeExternalUrl(url)) {
void shell.openExternal(url)
} else {
console.warn(
'[windows] blocked openExternal for non-allowlisted URL:',
url
)
}
return { action: 'deny' }
})
// Renderer must never navigate the BrowserWindow to a third-party origin.
// We always load file:// or the dev URL; anything else is suspect.
win.webContents.on('will-navigate', (event, url) => {
const devUrl = process.env['ELECTRON_RENDERER_URL']
const allow =
url.startsWith('file://') || (devUrl && url.startsWith(devUrl))
if (!allow) {
event.preventDefault()
console.warn('[windows] blocked will-navigate to:', url)
}
})
}
function loadRoute(win: BrowserWindow, route: 'main' | 'reminder'): void {
const devUrl = process.env['ELECTRON_RENDERER_URL']
if (devUrl) {
@@ -68,10 +110,7 @@ export function createMainWindow(showImmediately = true): BrowserWindow {
if (showImmediately) win.show()
})
win.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url)
return { action: 'deny' }
})
installSafeNavigation(win)
loadRoute(win, 'main')
mainWindow = win
@@ -123,6 +162,7 @@ export function createReminderWindow(): BrowserWindow {
})
win.setAlwaysOnTop(true, 'screen-saver')
installSafeNavigation(win)
loadRoute(win, 'reminder')
win.on('closed', () => {

View File

@@ -17,7 +17,8 @@ type Unsub = () => void
type Handler<T> = (payload: T) => void
function on<T>(channel: string, handler: Handler<T>): Unsub {
const listener = (_e: Electron.IpcRendererEvent, payload: T): void => handler(payload)
const listener = (_e: Electron.IpcRendererEvent, payload: T): void =>
handler(payload)
ipcRenderer.on(channel, listener)
return () => ipcRenderer.removeListener(channel, listener)
}
@@ -44,7 +45,8 @@ const api = {
ipcRenderer.invoke(IPC.updateSettings, patch),
getAccentColor: (): Promise<string> => ipcRenderer.invoke(IPC.getAccentColor),
getOsTheme: (): Promise<'light' | 'dark'> => ipcRenderer.invoke(IPC.getOsTheme),
getOsTheme: (): Promise<'light' | 'dark'> =>
ipcRenderer.invoke(IPC.getOsTheme),
pauseAll: (): Promise<void> => ipcRenderer.invoke(IPC.pauseAll),
resumeAll: (): Promise<void> => ipcRenderer.invoke(IPC.resumeAll),
@@ -69,17 +71,31 @@ const api = {
// Challenges
addChallenge: (input: Omit<Challenge, 'id'>): Promise<Challenge> =>
ipcRenderer.invoke(IPC.addChallenge, input),
updateChallenge: (id: string, patch: Partial<Challenge>): Promise<Challenge> =>
ipcRenderer.invoke(IPC.updateChallenge, id, patch),
updateChallenge: (
id: string,
patch: Partial<Challenge>
): Promise<Challenge> => ipcRenderer.invoke(IPC.updateChallenge, id, patch),
deleteChallenge: (id: string): Promise<boolean> =>
ipcRenderer.invoke(IPC.deleteChallenge, id),
toggleChallenge: (id: string, enabled: boolean): Promise<Challenge> =>
ipcRenderer.invoke(IPC.toggleChallenge, id, enabled),
closeMatchSummary: (): Promise<void> => ipcRenderer.invoke(IPC.closeMatchSummary),
closeMatchSummary: (): Promise<void> =>
ipcRenderer.invoke(IPC.closeMatchSummary),
simulateMatchEnd: (id: GameId, stats: Record<string, number>): Promise<void> =>
ipcRenderer.invoke('dev:simulateMatchEnd', id, stats),
// Dev-only: synthesize a match-end event from the renderer. The channel is
// not registered in production builds (see src/main/ipc.ts), so this
// function will reject in shipped binaries even though it's exposed.
// Gated at the preload level too so the bundler can dead-code-eliminate it.
...(import.meta.env.MODE !== 'production'
? {
simulateMatchEnd: (
id: GameId,
stats: Record<string, number>
): Promise<void> =>
ipcRenderer.invoke('dev:simulateMatchEnd', id, stats)
}
: {}),
// Auto-updater
updaterStatus: (): Promise<UpdaterStatus> =>
@@ -99,9 +115,11 @@ const api = {
onFire: (h: Handler<Exercise>): Unsub => on(IPC.evtFire, h),
onMatchEnd: (h: Handler<MatchSummary>): Unsub => on(IPC.evtMatchEnd, h),
onStateChanged: (h: Handler<AppState>): Unsub => on(IPC.evtStateChanged, h),
onThemeChanged: (h: Handler<'light' | 'dark'>): Unsub => on(IPC.evtThemeChanged, h),
onThemeChanged: (h: Handler<'light' | 'dark'>): Unsub =>
on(IPC.evtThemeChanged, h),
onAccentChanged: (h: Handler<string>): Unsub => on(IPC.evtAccentChanged, h),
onGamesChanged: (h: Handler<GameStatus[]>): Unsub => on(IPC.evtGamesChanged, h),
onGamesChanged: (h: Handler<GameStatus[]>): Unsub =>
on(IPC.evtGamesChanged, h),
onUpdaterStatus: (h: Handler<UpdaterStatus>): Unsub =>
on(IPC.evtUpdaterStatus, h)
}

View File

@@ -54,24 +54,16 @@ export default function ReminderApp(): JSX.Element {
}
}, [])
// ESC closes the match summary view too — keyboard parity with exercise mode.
useEffect(() => {
if (mode.kind !== 'exercise') return
const ex = mode.exercise
const snoozeMin = settings?.snoozeMinutes ?? 5
if (mode.kind !== 'match') return
function onKey(e: KeyboardEvent): void {
if (e.key === 'Enter') {
window.api.markDone(ex.id).then(close)
} else if (e.key === ' ' || e.code === 'Space') {
e.preventDefault()
window.api.snooze(ex.id, snoozeMin).then(close)
} else if (e.key === 'Escape') {
window.api.skip(ex.id).then(close)
}
if (e.key === 'Escape') close()
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [mode, settings?.snoozeMinutes])
}, [mode.kind])
function close(): void {
setMode({ kind: 'idle' })
@@ -83,7 +75,10 @@ export default function ReminderApp(): JSX.Element {
if (mode.kind === 'idle') return <div className="reminder-shell" />
if (mode.kind === 'exercise') {
return (
// key={exercise.id} forces a fresh component (and fresh stepper state)
// when a new reminder arrives while the previous modal is still open.
<ExerciseReminder
key={mode.exercise.id + ':' + mode.exercise.nextFireAt}
exercise={mode.exercise}
snoozeMinutes={settings?.snoozeMinutes ?? 5}
lang={lang}
@@ -97,11 +92,17 @@ export default function ReminderApp(): JSX.Element {
done={mode.done}
lang={lang}
onMarkDone={(id) =>
setMode({
kind: 'match',
summary: mode.summary,
done: new Set([...mode.done, id])
})
// Functional update so a second rapid click can't race against a stale
// `mode.done` captured in this closure.
setMode((m) =>
m.kind === 'match'
? {
kind: 'match',
summary: m.summary,
done: new Set([...m.done, id])
}
: m
)
}
onClose={close}
/>
@@ -124,14 +125,13 @@ function ExerciseReminder({
const [actualReps, setActualReps] = useState(exercise.reps)
const adjusted = actualReps !== exercise.reps
// Cap the stepper at 5× planned so a stuck "+" button can't log nonsense.
const REP_CAP = Math.max(50, exercise.reps * 5)
async function done(): Promise<void> {
// Only pass actualReps when user adjusted — otherwise leave undefined
// so history records the full planned value cleanly.
await window.api.markDone(
exercise.id,
adjusted ? actualReps : undefined
)
await window.api.markDone(exercise.id, adjusted ? actualReps : undefined)
onClose()
}
async function snooze(): Promise<void> {
@@ -143,7 +143,38 @@ function ExerciseReminder({
onClose()
}
const dec = (): void => setActualReps((n) => Math.max(0, n - 1))
const inc = (): void => setActualReps((n) => n + 1)
const inc = (): void => setActualReps((n) => Math.min(REP_CAP, n + 1))
// Keyboard shortcuts live INSIDE the component so they have access to the
// current `actualReps` — pressing Enter respects the stepper's adjustment.
useEffect(() => {
function onKey(e: KeyboardEvent): void {
// Don't hijack Space when a button is focused (default activation).
const targetTag = (e.target as HTMLElement | null)?.tagName
if (e.key === 'Enter') {
e.preventDefault()
void done()
} else if (
(e.key === ' ' || e.code === 'Space') &&
targetTag !== 'BUTTON'
) {
e.preventDefault()
void snooze()
} else if (e.key === 'Escape') {
e.preventDefault()
void skip()
} else if (e.key === 'ArrowUp' || e.key === '+') {
e.preventDefault()
inc()
} else if (e.key === 'ArrowDown' || e.key === '-') {
e.preventDefault()
dec()
}
}
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [actualReps, snoozeMinutes])
return (
<div className="reminder-shell flex flex-col h-full">
@@ -181,7 +212,7 @@ function ExerciseReminder({
<button
onClick={dec}
className="w-9 h-9 grid place-items-center rounded-full bg-surface-2 text-text/65 hover:text-text hover:bg-hairline/25 active:scale-90 transition-all"
aria-label=""
aria-label={t('reminder.aria.decrement')}
>
<Minus size={16} strokeWidth={2.5} />
</button>
@@ -201,14 +232,17 @@ function ExerciseReminder({
<button
onClick={inc}
className="w-9 h-9 grid place-items-center rounded-full bg-surface-2 text-text/65 hover:text-text hover:bg-hairline/25 active:scale-90 transition-all"
aria-label="+"
aria-label={t('reminder.aria.increment')}
>
<Plus size={16} strokeWidth={2.5} />
</button>
</div>
{adjusted && (
<div className="text-[12px] text-accent mt-2 font-medium">
{t('reminder.partial', { actual: actualReps, planned: exercise.reps })}
{t('reminder.partial', {
actual: actualReps,
planned: exercise.reps
})}
</div>
)}
@@ -320,7 +354,8 @@ function MatchSummaryView({
<p className="text-[13px] text-text/65 mt-1.5 font-medium">
<span className="font-mono-num font-bold text-text">{minutes}</span>{' '}
{t('fmt.m')} ·{' '}
{tn('match.summary.challenges', summary.results.length)}{' · '}
{tn('match.summary.challenges', summary.results.length)}
{' · '}
{allDone ? (
<span className="text-success font-bold">
{t('match.summary.all_done')}

View File

@@ -3,7 +3,7 @@ import { Check, MoreHorizontal } from 'lucide-react'
import { useState } from 'react'
import type { Exercise, Tick } from '@shared/types'
import { Icon } from '../lib/icon'
import { formatCountdown, formatInterval } from '../lib/format'
import { formatCountdown } from '../lib/format'
import { Switch } from './ui/Switch'
import { useT } from '../i18n'
@@ -78,9 +78,7 @@ export function ExerciseCard({
strokeLinecap="round"
strokeDasharray={C}
strokeDashoffset={dashOffset}
className={
isDue ? 'stroke-accent' : 'stroke-accent/85'
}
className={isDue ? 'stroke-accent' : 'stroke-accent/85'}
style={{ transition: 'stroke-dashoffset 0.5s linear' }}
/>
)}
@@ -159,9 +157,7 @@ export function ExerciseCard({
isDue ? 'text-accent' : 'text-text'
].join(' ')}
>
{exercise.enabled
? formatCountdown(ms, lang)
: t('fmt.paused')}
{exercise.enabled ? formatCountdown(ms, lang) : t('fmt.paused')}
</div>
</div>
<Switch

View File

@@ -83,7 +83,9 @@ export function HistoryHeatmap({
<div className="bg-surface rounded-2xl p-5 shadow-card dark:ring-0.5 dark:ring-hairline/30">
<div className="flex items-center gap-2 mb-3">
<div className="text-[14px] text-text/75 font-semibold">
{lang === 'en' ? 'Activity, last 12 weeks' : 'Активность за 12 недель'}
{lang === 'en'
? 'Activity, last 12 weeks'
: 'Активность за 12 недель'}
</div>
</div>
@@ -115,9 +117,7 @@ export function HistoryHeatmap({
<div key={wi} className="flex flex-col gap-[3px]">
{w.map((c, di) => {
if (!c) {
return (
<div key={di} className="w-[12px] h-[12px]" />
)
return <div key={di} className="w-[12px] h-[12px]" />
}
const b = bucket(c.reps)
const tone =

View File

@@ -1,13 +1,6 @@
import { NavLink } from 'react-router-dom'
import { AnimatePresence, motion } from 'framer-motion'
import {
Sun,
Dumbbell,
Joystick,
Flame,
Settings2,
X
} from 'lucide-react'
import { Sun, Dumbbell, Joystick, Flame, Settings2, X } from 'lucide-react'
import { useT } from '../i18n'
type Item = {

View File

@@ -94,11 +94,7 @@ function Body({
<Cell
tone="info"
icon={
<RefreshCw
size={16}
strokeWidth={2.4}
className="animate-spin"
/>
<RefreshCw size={16} strokeWidth={2.4} className="animate-spin" />
}
title={t('updater.checking')}
/>
@@ -145,8 +141,16 @@ function Body({
)
}
if (status.kind === 'downloading') {
const pct = Math.max(0, Math.min(100, status.percent || 0))
const mb = (n: number): string => (n / 1024 / 1024).toFixed(1)
// electron-updater fires early `download-progress` events where some
// fields are undefined; guard against NaN/Infinity so we never render
// "NaN%" or "NaN MB/s".
const rawPct = Number.isFinite(status.percent) ? status.percent : 0
const pct = Math.max(0, Math.min(100, rawPct))
const mb = (n: number): string =>
Number.isFinite(n) ? (n / 1024 / 1024).toFixed(1) : '0.0'
const speed = Number.isFinite(status.bytesPerSecond)
? (status.bytesPerSecond / 1024 / 1024).toFixed(2)
: '0.00'
return (
<div className="px-4 py-4">
<div className="flex items-center gap-3 mb-3">
@@ -161,7 +165,7 @@ function Body({
{t('updater.downloading.subtitle', {
got: mb(status.transferred),
total: mb(status.total),
speed: (status.bytesPerSecond / 1024 / 1024).toFixed(2)
speed
})}
</div>
</div>

View File

@@ -24,15 +24,13 @@ const legacyMap: Record<LegacyVariant, Variant> = {
}
const variantClasses: Record<Variant, string> = {
filled:
'bg-accent text-white hover:brightness-105 active:brightness-95',
filled: 'bg-accent text-white hover:brightness-105 active:brightness-95',
tinted:
'bg-accent/12 text-accent hover:bg-accent/18 active:bg-accent/22 dark:bg-accent/20 dark:hover:bg-accent/25',
plain: 'text-accent hover:bg-accent/10 active:bg-accent/15',
destructive:
'bg-destructive/12 text-destructive hover:bg-destructive/18 active:bg-destructive/22 dark:bg-destructive/20',
success:
'bg-success text-white hover:brightness-105 active:brightness-95'
success: 'bg-success text-white hover:brightness-105 active:brightness-95'
}
const sizeClasses: Record<Size, string> = {

View File

@@ -116,8 +116,7 @@ export const ru: Dict = {
// Games
'games.kicker': 'Трекинг матчей',
'games.title': 'Игры',
'games.subtitle':
'Подключи игру — челленджи сработают сразу после матча',
'games.subtitle': 'Подключи игру — челленджи сработают сразу после матча',
'games.subtitle.live': '{n} live',
'games.section.supported': 'Поддерживаемые',
'games.scanning': 'Сканируем установленные игры…',
@@ -205,6 +204,8 @@ export const ru: Dict = {
'reminder.reps': 'раз',
'reminder.next_in': 'Следующее через {interval}',
'reminder.partial': 'Засчитаем {actual} из {planned}',
'reminder.aria.decrement': 'Уменьшить количество повторов',
'reminder.aria.increment': 'Увеличить количество повторов',
'reminder.btn.done': 'Готово',
'match.title.won': 'Победа',
'match.title.lost': 'Поражение',
@@ -423,6 +424,8 @@ export const en: Dict = {
'reminder.reps': 'reps',
'reminder.next_in': 'Next in {interval}',
'reminder.partial': "We'll log {actual} of {planned}",
'reminder.aria.decrement': 'Decrease rep count',
'reminder.aria.increment': 'Increase rep count',
'reminder.btn.done': 'Done',
'match.title.won': 'Victory',
'match.title.lost': 'Defeat',

View File

@@ -14,17 +14,25 @@ export type TFn = (key: string, vars?: TVars) => string
/**
* Look up a key in the dictionary, substitute `{var}` placeholders.
* Returns the key itself if not found — surfaces missing translations.
*
* Substitution is done by string split/join rather than a regex so that
* variable values containing regex metacharacters (e.g. a user-supplied
* exercise name with `$1` or `.*`) are interpolated literally.
*/
export function translate(
lang: Language,
key: string,
vars?: TVars
): string {
export function translate(lang: Language, key: string, vars?: TVars): string {
const dict = getDict(lang)
let s = dict[key] ?? key
let s = dict[key]
if (s === undefined) {
// Surface missing translations in dev; in prod render the key so the user
// sees something deterministic instead of a blank.
if (import.meta.env.DEV) {
console.warn(`[i18n] missing key "${key}" for lang "${lang}"`)
}
s = key
}
if (vars) {
for (const k of Object.keys(vars)) {
s = s.replace(new RegExp(`\\{${k}\\}`, 'g'), String(vars[k]))
s = s.split(`{${k}}`).join(String(vars[k]))
}
}
return s
@@ -37,8 +45,10 @@ export function translate(
* many → 0, 5-20, 25-30…
*/
function pluralRu(n: number): 'one' | 'few' | 'many' {
const mod10 = n % 10
const mod100 = n % 100
// Always pluralize on the absolute value — a "-1" count is the same form as "1".
const abs = Math.abs(Math.trunc(n))
const mod10 = abs % 10
const mod100 = abs % 100
if (mod10 === 1 && mod100 !== 11) return 'one'
if (mod10 >= 2 && mod10 <= 4 && (mod100 < 10 || mod100 >= 20)) return 'few'
return 'many'
@@ -55,12 +65,7 @@ export function translateN(
n: number,
vars?: TVars
): string {
const form =
lang === 'ru'
? pluralRu(n)
: n === 1
? 'one'
: 'many'
const form = lang === 'ru' ? pluralRu(n) : n === 1 ? 'one' : 'many'
return translate(lang, `${keyBase}_${form}`, { n, ...vars })
}

View File

@@ -7,7 +7,7 @@ const SUFFIX = {
export function formatCountdown(ms: number, lang: Language = 'ru'): string {
const s = SUFFIX[lang] ?? SUFFIX.ru
if (ms <= 0) return s.now
if (!Number.isFinite(ms) || ms <= 0) return s.now
const totalSec = Math.floor(ms / 1000)
const h = Math.floor(totalSec / 3600)
const m = Math.floor((totalSec % 3600) / 60)
@@ -17,10 +17,7 @@ export function formatCountdown(ms: number, lang: Language = 'ru'): string {
return `${sec}${s.s}`
}
export function formatInterval(
minutes: number,
lang: Language = 'ru'
): string {
export function formatInterval(minutes: number, lang: Language = 'ru'): string {
const s = SUFFIX[lang] ?? SUFFIX.ru
if (minutes < 60) return `${minutes} ${s.minLong}`
const h = Math.floor(minutes / 60)

View File

@@ -94,19 +94,12 @@ describe('currentStreak', () => {
})
it('ignores skip and snooze', () => {
const hist = [
entry('a', day(0), 'skip'),
entry('a', day(1), 'snooze')
]
const hist = [entry('a', day(0), 'skip'), entry('a', day(1), 'snooze')]
expect(currentStreak(hist)).toBe(0)
})
it('multiple entries same day count once', () => {
const hist = [
entry('a', day(0)),
entry('b', day(0)),
entry('a', day(1))
]
const hist = [entry('a', day(0)), entry('b', day(0)), entry('a', day(1))]
expect(currentStreak(hist)).toBe(2)
})
})

View File

@@ -1,7 +1,5 @@
import type { Exercise, HistoryEntry } from '@shared/types'
const MS_DAY = 24 * 60 * 60 * 1000
/** YYYY-MM-DD in local time. */
export function dayKey(ts: number): string {
const d = new Date(ts)
@@ -16,6 +14,18 @@ export function todayKey(): string {
return dayKey(Date.now())
}
/**
* Return a new Date offset by `dayDelta` calendar days from `base`, with the
* time-of-day preserved. Uses `setDate` (calendar arithmetic) rather than
* subtracting `n * 24h` of milliseconds — across DST transitions ms arithmetic
* drifts by ±1h and `dayKey` can emit the wrong day.
*/
function shiftDays(base: Date, dayDelta: number): Date {
const d = new Date(base.getTime())
d.setDate(d.getDate() + dayDelta)
return d
}
/**
* Reps logged on a given local day. Uses `actualReps` if present, otherwise
* looks up exercise's planned `reps`.
@@ -46,28 +56,27 @@ export function dailyRepsRange(
): { key: string; date: Date; reps: number }[] {
const today = new Date()
today.setHours(0, 0, 0, 0)
const buckets = new Map<string, number>()
const buckets = new Map<string, { date: Date; reps: number }>()
const byId = new Map(exercises.map((e) => [e.id, e]))
// Seed all days with 0 so heatmap renders contiguous.
// Seed all days with 0 so heatmap renders contiguous. Use calendar arithmetic
// (setDate) — DST transitions would shift epoch-based math by ±1h, causing
// dayKey() to emit duplicate or missing days at the boundary.
for (let i = days - 1; i >= 0; i--) {
const d = new Date(today.getTime() - i * MS_DAY)
buckets.set(dayKey(d.getTime()), 0)
const d = shiftDays(today, -i)
buckets.set(dayKey(d.getTime()), { date: d, reps: 0 })
}
for (const e of entries) {
if (e.action !== 'done') continue
const k = dayKey(e.ts)
if (!buckets.has(k)) continue
const bucket = buckets.get(k)
if (!bucket) continue
const reps = e.actualReps ?? byId.get(e.exerciseId)?.reps ?? 0
buckets.set(k, (buckets.get(k) ?? 0) + reps)
bucket.reps += reps
}
return Array.from(buckets, ([key, reps]) => ({
key,
date: new Date(`${key}T00:00:00`),
reps
}))
return Array.from(buckets, ([key, { date, reps }]) => ({ key, date, reps }))
}
/**
@@ -84,21 +93,22 @@ export function currentStreak(entries: HistoryEntry[]): number {
const today = new Date()
today.setHours(0, 0, 0, 0)
const yesterday = shiftDays(today, -1)
const todayK = dayKey(today.getTime())
const yesterdayK = dayKey(today.getTime() - MS_DAY)
const yesterdayK = dayKey(yesterday.getTime())
// Start from today if active today, else yesterday (grace), else 0.
let cursor = doneDays.has(todayK)
let cursor: Date | null = doneDays.has(todayK)
? today
: doneDays.has(yesterdayK)
? new Date(today.getTime() - MS_DAY)
? yesterday
: null
if (!cursor) return 0
let streak = 0
while (doneDays.has(dayKey(cursor.getTime()))) {
streak++
cursor = new Date(cursor.getTime() - MS_DAY)
cursor = shiftDays(cursor, -1)
}
return streak
}

View File

@@ -24,13 +24,27 @@ export const ICON_CHOICES = [
export type IconName = (typeof ICON_CHOICES)[number]
const ICON_SET = new Set<string>(ICON_CHOICES)
/**
* Render a Lucide icon by name. Restricted to the curated ICON_CHOICES set —
* an arbitrary string from a corrupted state file could otherwise resolve to
* unrelated Lucide exports (`default`, `createLucideIcon`, etc.) and crash
* the renderer.
*/
export function Icon({
name,
...props
}: { name: string } & LucideProps): JSX.Element {
const Cmp = (Lucide as unknown as Record<string, React.ComponentType<LucideProps>>)[
name
]
if (!ICON_SET.has(name)) {
if (import.meta.env.DEV) {
console.warn(`[Icon] unknown icon name "${name}" — falling back`)
}
return <Lucide.Activity {...props} />
}
const Cmp = (
Lucide as unknown as Record<string, React.ComponentType<LucideProps>>
)[name]
if (!Cmp) return <Lucide.Activity {...props} />
return <Cmp {...props} />
}

View File

@@ -10,6 +10,8 @@ const which = params.get('window') ?? 'main'
ReactDOM.createRoot(document.getElementById('root')!).render(
<React.StrictMode>
<ThemeProvider>{which === 'reminder' ? <ReminderApp /> : <App />}</ThemeProvider>
<ThemeProvider>
{which === 'reminder' ? <ReminderApp /> : <App />}
</ThemeProvider>
</React.StrictMode>
)

View File

@@ -130,9 +130,7 @@ function ExerciseRow({
<div
className={[
'w-9 h-9 rounded-lg grid place-items-center shrink-0',
exercise.enabled
? 'bg-accent text-white'
: 'bg-text/15 text-text/45'
exercise.enabled ? 'bg-accent text-white' : 'bg-text/15 text-text/45'
].join(' ')}
>
<Icon name={exercise.icon} size={18} strokeWidth={2.2} />

View File

@@ -54,9 +54,7 @@ export default function GamesPage(): JSX.Element {
}
}
const liveCount = games.filter(
(g) => g.enabled && g.integrationActive
).length
const liveCount = games.filter((g) => g.enabled && g.integrationActive).length
return (
<div className="h-full overflow-y-auto">
@@ -170,11 +168,7 @@ function GameCard({
</div>
</div>
{game.installed && game.integrationActive && (
<Switch
checked={game.enabled}
onChange={onToggle}
disabled={busy}
/>
<Switch checked={game.enabled} onChange={onToggle} disabled={busy} />
)}
</div>
@@ -280,8 +274,16 @@ function StatusBadge({
function DevPanel({ games }: { games: GameStatus[] }): JSX.Element | null {
const [open, setOpen] = useState(false)
const { t } = useT()
// Never render in packaged builds — the matching IPC handler is also
// unregistered there, so the buttons would do nothing anyway.
if (!import.meta.env.DEV) return null
const dota = games.find((g) => g.id === 'dota2')
if (!dota?.enabled) return null
// In dev the preload exposes window.api.simulateMatchEnd; the conditional
// type still hides it, so we narrow here.
const api = window.api as typeof window.api & {
simulateMatchEnd?: (id: 'dota2', stats: Record<string, number>) => void
}
return (
<div className="mt-10">
<button
@@ -305,7 +307,7 @@ function DevPanel({ games }: { games: GameStatus[] }): JSX.Element | null {
).map((p) => (
<button
key={p.label}
onClick={() => window.api.simulateMatchEnd('dota2', p.stats)}
onClick={() => api.simulateMatchEnd?.('dota2', p.stats)}
className="text-[12px] px-3 py-1.5 rounded-full bg-surface-2 hover:bg-accent/15 hover:text-accent text-text/70 font-medium transition-colors active:scale-95"
>
{p.label}

View File

@@ -1,7 +1,11 @@
import { ReactNode, useEffect, useState } from 'react'
import { useAppStore } from '../store/appStore'
export function ThemeProvider({ children }: { children: ReactNode }): JSX.Element {
export function ThemeProvider({
children
}: {
children: ReactNode
}): JSX.Element {
const settings = useAppStore((s) => s.state?.settings)
const [osTheme, setOsTheme] = useState<'light' | 'dark'>('dark')

View File

@@ -31,7 +31,9 @@ export const useAppStore = create<Store>((set) => ({
export function subscribeToBackend(): () => void {
const store = useAppStore.getState()
store.hydrate()
const u1 = window.api.onStateChanged((s) => useAppStore.getState().setState(s))
const u1 = window.api.onStateChanged((s) =>
useAppStore.getState().setState(s)
)
const u2 = window.api.onTick((t) => useAppStore.getState().setTicks(t))
return () => {
u1()

View File

@@ -6,22 +6,22 @@
:root {
/* Brand & semantic colors (iOS system palette) */
--accent: 255 107 53; /* Apple Fitness Move orange */
--accent-2: 255 45 85; /* systemPink */
--success: 52 199 89; /* systemGreen */
--warning: 255 159 10; /* systemOrange dark */
--destructive: 255 59 48; /* systemRed */
--info: 0 122 255; /* systemBlue */
--accent: 255 107 53; /* Apple Fitness Move orange */
--accent-2: 255 45 85; /* systemPink */
--success: 52 199 89; /* systemGreen */
--warning: 255 159 10; /* systemOrange dark */
--destructive: 255 59 48; /* systemRed */
--info: 0 122 255; /* systemBlue */
color-scheme: light dark;
}
/* Light — polished iOS groupedBackground with warm undertone */
:root {
--bg: 245 245 249; /* slightly warmer than 242,242,247 */
--bg: 245 245 249; /* slightly warmer than 242,242,247 */
--surface: 255 255 255;
--surface-2: 240 240 245; /* subtle separation for inputs/sections */
--text: 17 17 19; /* not pure black — softer */
--surface-2: 240 240 245; /* subtle separation for inputs/sections */
--text: 17 17 19; /* not pure black — softer */
--text-secondary: 60 60 67;
--text-tertiary: 60 60 67;
--hairline: 60 60 67;
@@ -114,8 +114,8 @@ body {
}
.font-mono-num {
font-family: 'JetBrains Mono', ui-monospace, 'SF Mono', 'Cascadia Code',
Menlo, monospace;
font-family:
'JetBrains Mono', ui-monospace, 'SF Mono', 'Cascadia Code', Menlo, monospace;
font-variant-numeric: tabular-nums;
font-feature-settings: 'ss02', 'ss19', 'zero';
letter-spacing: -0.01em;

View File

@@ -58,6 +58,38 @@ describe('isQuietAt', () => {
expect(isQuietAt(qh, at('2026-05-18T13:30:00'))).toBe(true)
})
it('wrap-around + day filter: window day matters, not current day', () => {
// from=22:00, to=07:00, days=[Mon..Fri].
const qh: QuietHours = {
enabled: true,
from: '22:00',
to: '07:00',
days: [1, 2, 3, 4, 5]
}
// Friday 23:00 -> window starts today, Friday in filter -> quiet
expect(isQuietAt(qh, at('2026-05-15T23:00:00'))).toBe(true)
// Saturday 02:00 -> window started Friday 22:00, Friday in filter -> quiet
expect(isQuietAt(qh, at('2026-05-16T02:00:00'))).toBe(true)
// Saturday 23:00 -> would start today, Saturday not in filter -> noisy
expect(isQuietAt(qh, at('2026-05-16T23:00:00'))).toBe(false)
// Sunday 02:00 -> started Saturday, Saturday not in filter -> noisy
expect(isQuietAt(qh, at('2026-05-17T02:00:00'))).toBe(false)
// Monday 01:00 -> would have started Sunday, Sunday not in filter -> noisy
expect(isQuietAt(qh, at('2026-05-18T01:00:00'))).toBe(false)
// Monday 23:00 -> starts today, Monday in filter -> quiet
expect(isQuietAt(qh, at('2026-05-18T23:00:00'))).toBe(true)
})
it('malformed from/to falls back to non-quiet', () => {
const qh: QuietHours = {
enabled: true,
from: 'bogus',
to: '08:00',
days: ALL_DAYS
}
expect(isQuietAt(qh, at('2026-05-17T05:00:00'))).toBe(false)
})
it('zero-length window (from === to) is never quiet', () => {
const qh: QuietHours = {
enabled: true,

View File

@@ -130,10 +130,10 @@ export type GameStatus = {
name: string
installed: boolean
installPath?: string
integrationActive: boolean // cfg installed + listener running
launchOption?: string // e.g. "-gamestateintegration"
integrationActive: boolean // cfg installed + listener running
launchOption?: string // e.g. "-gamestateintegration"
launchOptionStatus: LaunchOptionStatus
steamRunning?: boolean // helps the UI explain queued state
steamRunning?: boolean // helps the UI explain queued state
enabled: boolean
}
@@ -176,33 +176,81 @@ export const DEFAULT_SETTINGS: Settings = {
}
}
const HHMM_RE = /^(\d{1,2}):(\d{2})$/
/** Parse `HH:MM` into minutes-since-midnight, or `null` if malformed. */
function parseHHMM(s: string): number | null {
const m = HHMM_RE.exec(s)
if (!m) return null
const h = Number(m[1])
const min = Number(m[2])
if (!Number.isFinite(h) || !Number.isFinite(min)) return null
if (h < 0 || h > 23 || min < 0 || min > 59) return null
return h * 60 + min
}
/**
* Returns true if `now` falls inside the quiet window. Handles wrap-around
* windows (e.g. 22:00 → 08:00). Exposed from shared so both main scheduler
* and renderer settings UI can use the same logic.
* windows (e.g. 22:00 → 08:00) AND day-of-week filtering correctly: when the
* window started the previous day (we're in the AM half of a wrap-around),
* the day filter is evaluated against the START day, not the current day.
*
* Example: from=22:00, to=07:00, days=[Mon..Fri]. At Sat 02:00 the window
* is active (started Fri 22:00 — Friday is in the filter). At Mon 01:00 the
* window is NOT active (would have started Sun 22:00 — Sunday is excluded).
*
* Malformed `from`/`to` strings (after a corrupt state file) return false.
*/
export function isQuietAt(qh: QuietHours, now: Date): boolean {
if (!qh.enabled) return false
const dow = now.getDay() // 0..6
if (qh.days.length > 0 && !qh.days.includes(dow)) return false
const [fh, fm] = qh.from.split(':').map(Number)
const [th, tm] = qh.to.split(':').map(Number)
const cur = now.getHours() * 60 + now.getMinutes()
const fromMin = fh * 60 + fm
const toMin = th * 60 + tm
const fromMin = parseHHMM(qh.from)
const toMin = parseHHMM(qh.to)
if (fromMin === null || toMin === null) return false
if (fromMin === toMin) return false
const cur = now.getHours() * 60 + now.getMinutes()
const todayDow = now.getDay() // 0..6, 0=Sunday
const yesterdayDow = (todayDow + 6) % 7
// Helper: is this day included by the filter?
const dayActive = (dow: number): boolean =>
qh.days.length === 0 || qh.days.includes(dow)
if (fromMin < toMin) {
// Same-day window.
// Same-day window — start day is `todayDow`.
if (!dayActive(todayDow)) return false
return cur >= fromMin && cur < toMin
}
// Wraps midnight: active if after `from` today OR before `to` today.
return cur >= fromMin || cur < toMin
// Wrap-around window. Either:
// - cur >= fromMin: window started TODAY at fromMin → check todayDow
// - cur < toMin: window started YESTERDAY at fromMin → check yesterdayDow
if (cur >= fromMin) return dayActive(todayDow)
if (cur < toMin) return dayActive(yesterdayDow)
return false
}
export const SAMPLE_EXERCISES: Omit<Exercise, 'id' | 'nextFireAt'>[] = [
{ name: 'Приседания', reps: 10, icon: 'Activity', intervalMinutes: 30, enabled: true },
{ name: 'Отжимания', reps: 10, icon: 'Dumbbell', intervalMinutes: 45, enabled: true },
{ name: 'Растяжка спины', reps: 1, icon: 'StretchHorizontal', intervalMinutes: 60, enabled: false }
{
name: 'Приседания',
reps: 10,
icon: 'Activity',
intervalMinutes: 30,
enabled: true
},
{
name: 'Отжимания',
reps: 10,
icon: 'Dumbbell',
intervalMinutes: 45,
enabled: true
},
{
name: 'Растяжка спины',
reps: 1,
icon: 'StretchHorizontal',
intervalMinutes: 60,
enabled: false
}
]
export type UpdaterStatus =
@@ -220,4 +268,3 @@ export type UpdaterStatus =
}
| { kind: 'downloaded'; version: string }
| { kind: 'error'; message: string }