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:
@@ -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
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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]
|
||||
}
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
Reference in New Issue
Block a user