Files
TREK/client/src/components/Planner/SubscribeLinks.tsx
T
Maurice 2c2d008dc2 fix: clear every open Sonar security issue, and half the reliability ones (#2037)
* 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.
2026-08-25 15:22:38 +02:00

134 lines
4.9 KiB
TypeScript

import { useState } from 'react'
import { Copy, Check, CalendarPlus, Calendar } from 'lucide-react'
interface SubscribeLinksProps {
httpsUrl: string
webcalUrl: string
}
/**
* Shared presentation for calendar subscription URLs. Renders one-click
* subscribe actions (Google deep link + webcal handoff) plus a copy fallback.
* Used by both the per-trip and all-trips subscribe modals.
*/
export function SubscribeLinks({ httpsUrl, webcalUrl }: SubscribeLinksProps) {
const [copied, setCopied] = useState<'https' | 'webcal' | null>(null)
// Google Calendar's add-by-URL deep link. The cid must carry the webcal://
// scheme (not https), URL-encoded, and the feed must be served over HTTPS.
const googleUrl = `https://www.google.com/calendar/render?cid=${encodeURIComponent(webcalUrl)}`
const copy = async (url: string, which: 'https' | 'webcal') => {
try {
if (navigator.clipboard && window.isSecureContext) {
await navigator.clipboard.writeText(url)
} else {
// Fallback for non-secure contexts (plain HTTP) where navigator.clipboard is unavailable
const ta = document.createElement('textarea')
ta.value = url
ta.style.position = 'fixed'
ta.style.left = '-9999px'
document.body.appendChild(ta)
ta.focus()
ta.select()
document.execCommand('copy')
document.body.removeChild(ta)
}
setCopied(which)
setTimeout(() => setCopied(null), 2000)
} catch { /* ignore */ }
}
return (
<div>
{/* One-click subscribe actions */}
<div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 16 }}>
<a
href={googleUrl}
target="_blank"
rel="noopener noreferrer"
style={{
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
padding: '9px 14px', borderRadius: 9, textDecoration: 'none',
background: 'var(--accent, #6366f1)', color: 'var(--accent-text, #fff)',
fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
}}
>
<CalendarPlus size={14} strokeWidth={2} />
Add to Google Calendar
</a>
<a
href={webcalUrl}
style={{
display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
padding: '9px 14px', borderRadius: 9, textDecoration: 'none',
background: 'none', border: '1px solid var(--border-primary)',
color: 'var(--text-primary)', fontSize: 12, fontWeight: 600, fontFamily: 'inherit',
}}
>
<Calendar size={14} strokeWidth={2} />
Add to Apple Calendar / Outlook
</a>
</div>
{/* Manual fallback — raw URLs for any other client / "From URL" boxes */}
<details style={{ fontSize: 11, color: 'var(--text-muted)' }}>
<summary style={{ cursor: 'pointer', userSelect: 'none', marginBottom: 8 }}>
Or copy a link manually
</summary>
<UrlRow
label="Google Calendar"
hint="paste into “From URL”"
url={httpsUrl}
copied={copied === 'https'}
onCopy={() => copy(httpsUrl, 'https')}
/>
<UrlRow
label="Apple Calendar / Outlook"
hint="webcal://"
url={webcalUrl}
copied={copied === 'webcal'}
onCopy={() => copy(webcalUrl, 'webcal')}
/>
</details>
</div>
)
}
function UrlRow({ label, hint, url, copied, onCopy }: {
label: string; hint: string; url: string; copied: boolean; onCopy: () => void
}) {
return (
<div style={{ marginBottom: 12 }}>
<div style={{ fontSize: 11, fontWeight: 500, marginBottom: 5, color: 'var(--text-primary)' }}>
{label} <span style={{ color: 'var(--text-muted)', fontWeight: 400 }}>— {hint}</span>
</div>
<div style={{ display: 'flex', gap: 6, alignItems: 'center' }}>
<div style={{
flex: 1, fontSize: 10, fontFamily: 'monospace',
padding: '5px 8px', borderRadius: 6,
border: '1px solid var(--border-faint)',
background: 'var(--bg-subtle, #f9fafb)',
color: 'var(--text-muted)',
overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap',
}}>
{url}
</div>
<button type="button"
onClick={onCopy}
title="Copy"
style={{
flexShrink: 0, display: 'flex', alignItems: 'center', justifyContent: 'center',
width: 28, height: 28, borderRadius: 6,
border: '1px solid var(--border-primary)', background: 'none',
cursor: 'pointer', color: copied ? 'var(--accent, #6366f1)' : 'var(--text-muted)',
transition: 'color 0.15s',
}}
>
{copied ? <Check size={12} strokeWidth={2.5} /> : <Copy size={12} strokeWidth={2} />}
</button>
</div>
</div>
)
}