mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-20 05:56:53 +00:00
2c2d008dc2
* fix(security): mint idempotency keys properly, and resolve the extractor by path Three findings out of a sweep of every open Sonar security issue. The other 49 turned out to be false positives and are documented in sonar-project.properties rather than changed — each entry scoped to a file, never a whole rule, so a future Math.random() on an auth path still fails. The idempotency key is the one that can lose data. Both producers fell back to Math.random when crypto.randomUUID was missing, and randomUUID needs a secure context — TREK's own quickstart is http://localhost:3000 and LAN installs run on http://192.168.x.x, so on the deployments the README documents the fallback is what actually runs. The axios one was `Math.random().toString(36).slice(2)`, which is not length-stable: 0.5 yields a single character and 0 yields the empty string, which the interceptor reads as "no key" and skips deduplication for entirely. Two writes sharing a key collapse into one — the second gets the first one's cached response and the edit is gone with no error anywhere. Both now come from utils/randomId, which has the getRandomValues rung that works in insecure contexts too. The extractor probe stored the bare binary name, so every extraction re-resolved it through whatever PATH held at that moment. The official image sets KITINERARY_EXTRACTOR_PATH and never reaches that branch, but a bare-metal install without it ran an unqualified name from a PATH it does not control. It now walks the search path itself and keeps the absolute path of the file it verified; execFileSync also drops the /bin/sh hop the old probe needed. PATH comes through app-config because process.env is walled off in src/. * fix: four tests and sorts that were not doing what they claimed Sonar reported 43 high-impact reliability issues. Reading all of them, four are real; the rest are cosmetic or would be made worse by the suggested change. budget.test.ts hand-built `paid: true`, but both emitters send `paid: body.paid ? 1 : 0` and the handler stores the value verbatim — the test asserted a payload the server never sends. The line below it already used a number. admin.controller.test.ts had a `.resolves` assertion with no await. The promise was dropped, so that line could not fail the test. The two to-do category lists sorted with a bare .sort(), which is byte order: every accented name files behind the whole ASCII range, so in a German trip "Übernachtung" lands after "Zelt". TREK ships 23 locales, so this is real data. One side effect worth knowing: katColor picks a category's dot colour by its index, so re-sorting can move which category shows which colour — it already moves whenever a category is added, and the colour carries no meaning. Deliberately not changed: the two `| 0` truncations (Math.trunc is not equivalent — `| 0` wraps at 32 bits and these carry millisecond timestamps), the two .map() callbacks whose second parameter is declared and used, and the sha1 in thumbnail.service (its own comment says a swap would orphan every existing thumbnail). * refactor: give every button a type, and prefer the Number statics Two mechanical sweeps, no behaviour change intended in either. A <button> with no type attribute is type="submit" per the HTML spec. Outside a form that does nothing today, but it turns into a surprise the moment the markup is wrapped in one, which is what Sonar's S9011 is warning about. 870 buttons get an explicit type="button". Two things were left alone on purpose: buttons that take a {...spread}, because the spread may carry a type and the merge order decides which wins, and anything inside a <form> — there the answer is a judgement call, and checking all eleven form files found every real submit button already carrying type="submit". The Number sweep covers only the three globals that are exactly equivalent to their Number twin: parseInt, parseFloat and NaN. isNaN is NOT in it — the global coerces its argument, so isNaN('abc') is true where Number.isNaN('abc') is false, and renaming it would change what the code does. It reaches server and plugin-sdk as well as the client; both copies of egress-policy.ts got the identical edit, so the mirror the SDK's parity test guards stays intact.
139 lines
5.3 KiB
TypeScript
139 lines
5.3 KiB
TypeScript
import tzlookup from 'tz-lookup'
|
|
|
|
// The open/closed ring used to show whatever `open_now` the details endpoint had
|
|
// handed back — a boolean Google computed when the payload was fetched and that the
|
|
// server then cached for days. Read from another continent that value is wrong twice
|
|
// over: it is stale, and nothing in the chain ever looked at the place's own clock.
|
|
// The details payload also carries machine-readable periods — day/hour/minute, the
|
|
// same shape for Google and for OSM places — and those are what the ring is recomputed
|
|
// from, in the timezone of the coordinates. The weekday lines stay what they always
|
|
// were: display text in the user's language, unusable as a data source. Issue #1680.
|
|
|
|
const MINUTES_PER_DAY = 24 * 60
|
|
const MINUTES_PER_WEEK = 7 * MINUTES_PER_DAY
|
|
|
|
// Periods count days the way Google does: Sunday is 0. Intl reports the weekday by
|
|
// name, so this maps one to the other.
|
|
const WEEKDAY_NUMBER: Record<string, number> = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 }
|
|
|
|
export interface OpeningTimePoint {
|
|
day: number
|
|
hour: number
|
|
minute: number
|
|
}
|
|
|
|
export interface OpeningPeriod {
|
|
open: OpeningTimePoint
|
|
/** Absent or null means the place never closes. */
|
|
close?: OpeningTimePoint | null
|
|
}
|
|
|
|
export interface PlaceOpeningHours {
|
|
periods?: OpeningPeriod[] | null
|
|
/** YYYY-MM-DD dates the weekly periods do not describe (holidays and the like). */
|
|
specialDays?: string[] | null
|
|
}
|
|
|
|
export function resolvePlaceTimeZone(lat: unknown, lng: unknown): string | null {
|
|
if (typeof lat !== 'number' || typeof lng !== 'number' || !Number.isFinite(lat) || !Number.isFinite(lng)) return null
|
|
try {
|
|
return tzlookup(lat, lng)
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
/** Monday-based weekday index for `now` in `timeZone`; the viewer's own zone when it is null. */
|
|
export function placeWeekdayIndex(now: Date, timeZone: string | null): number {
|
|
const local = localParts(now, timeZone)
|
|
if (local) return (local.day + 6) % 7
|
|
const jsDay = now.getDay()
|
|
return jsDay === 0 ? 6 : jsDay - 1
|
|
}
|
|
|
|
/** Weekday (Sunday = 0), minute of day and calendar date of `now` in `timeZone`. */
|
|
function localParts(now: Date, timeZone: string | null): { day: number; minutes: number; date: string } | null {
|
|
if (!timeZone) return null
|
|
try {
|
|
const parts = new Intl.DateTimeFormat('en-US', {
|
|
timeZone,
|
|
weekday: 'short',
|
|
year: 'numeric',
|
|
month: '2-digit',
|
|
day: '2-digit',
|
|
hour: '2-digit',
|
|
minute: '2-digit',
|
|
hourCycle: 'h23',
|
|
}).formatToParts(now)
|
|
const value = (type: Intl.DateTimeFormatPartTypes) => parts.find(p => p.type === type)?.value ?? ''
|
|
const day = WEEKDAY_NUMBER[value('weekday')]
|
|
const hour = Number.parseInt(value('hour'), 10)
|
|
const minute = Number.parseInt(value('minute'), 10)
|
|
if (day === undefined || Number.isNaN(hour) || Number.isNaN(minute)) return null
|
|
return {
|
|
day,
|
|
minutes: (hour % 24) * 60 + minute,
|
|
date: `${value('year')}-${value('month')}-${value('day')}`,
|
|
}
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
function isTimePoint(point: unknown): point is OpeningTimePoint {
|
|
if (!point || typeof point !== 'object') return false
|
|
const { day, hour, minute } = point as OpeningTimePoint
|
|
if (typeof day !== 'number' || typeof hour !== 'number' || typeof minute !== 'number') return false
|
|
return day >= 0 && day <= 6 && hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59
|
|
}
|
|
|
|
/** Periods with a usable open point; a close point is optional but must be usable if present. */
|
|
function usablePeriods(periods: unknown): OpeningPeriod[] {
|
|
if (!Array.isArray(periods)) return []
|
|
return periods.filter(
|
|
(p): p is OpeningPeriod =>
|
|
!!p && isTimePoint((p as OpeningPeriod).open) && ((p as OpeningPeriod).close == null || isTimePoint((p as OpeningPeriod).close)),
|
|
)
|
|
}
|
|
|
|
function pointMinutes(point: OpeningTimePoint): number {
|
|
return point.day * MINUTES_PER_DAY + point.hour * 60 + point.minute
|
|
}
|
|
|
|
/**
|
|
* Open/closed state of a place at `now`, judged by its own local clock.
|
|
* Returns `fallback` (the server's `open_now`) whenever the periods cannot decide it.
|
|
*/
|
|
export function resolveOpenNow(
|
|
hours: PlaceOpeningHours | null | undefined,
|
|
lat: unknown,
|
|
lng: unknown,
|
|
fallback: boolean | null | undefined,
|
|
now: Date = new Date(),
|
|
): boolean | null {
|
|
const fb = fallback ?? null
|
|
const periods = usablePeriods(hours?.periods)
|
|
if (periods.length === 0) return fb
|
|
|
|
const local = localParts(now, resolvePlaceTimeZone(lat, lng))
|
|
if (!local) return fb
|
|
|
|
// A holiday is not in the weekly periods, but Google knew about it when it computed
|
|
// open_now — on such a day its verdict stands rather than our recomputation.
|
|
const specialDays = hours?.specialDays
|
|
if (Array.isArray(specialDays) && specialDays.includes(local.date)) return fb
|
|
|
|
const nowMinutes = local.day * MINUTES_PER_DAY + local.minutes
|
|
for (const period of periods) {
|
|
if (period.close == null) return true
|
|
const start = pointMinutes(period.open)
|
|
let end = pointMinutes(period.close)
|
|
// A closing time at or before the opening time runs past midnight, and past the end
|
|
// of the week when it opens on Saturday — hence the second comparison.
|
|
if (end <= start) end += MINUTES_PER_WEEK
|
|
if (nowMinutes >= start && nowMinutes < end) return true
|
|
if (nowMinutes + MINUTES_PER_WEEK >= start && nowMinutes + MINUTES_PER_WEEK < end) return true
|
|
}
|
|
return false
|
|
}
|