mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-28 23:50:08 +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.
157 lines
6.8 KiB
TypeScript
157 lines
6.8 KiB
TypeScript
import React, { useEffect, useMemo, useState } from 'react'
|
|
import { Sparkles, Save } from 'lucide-react'
|
|
import { useTranslation } from '../../i18n'
|
|
import { useToast } from '../shared/Toast'
|
|
import { useSettingsStore } from '../../store/settingsStore'
|
|
import type { Settings } from '../../types'
|
|
import Section from './Section'
|
|
import ToggleSwitch from './ToggleSwitch'
|
|
import CustomSelect from '../shared/CustomSelect'
|
|
|
|
type Provider = NonNullable<Settings['llm_provider']>
|
|
|
|
/**
|
|
* Settings → Integrations → AI parsing. Per-user model used to extract bookings
|
|
* from uploaded files. It only takes effect when the admin has not configured an
|
|
* instance-wide model on the addon — the server resolves the admin config first.
|
|
* The API key is stored encrypted and never prefilled: a blank field keeps the
|
|
* stored key (mirrors the AirTrail connection layout).
|
|
*
|
|
* A free-form endpoint does not live here at all (#1772): the request goes out
|
|
* from the server, so only whoever runs the instance may name its target, and
|
|
* an instance has exactly one such target. It is configured once on the addon
|
|
* in the admin settings, including for the admin's own account. What is left
|
|
* here are the two hosted providers, which go to a fixed address with the
|
|
* user's own key. The server enforces this on both the read and the write path,
|
|
* so this is only the matching surface.
|
|
*/
|
|
export default function LlmConnectionSection(): React.ReactElement {
|
|
const { t } = useTranslation()
|
|
const toast = useToast()
|
|
const settings = useSettingsStore(s => s.settings)
|
|
const isLoaded = useSettingsStore(s => s.isLoaded)
|
|
const updateSettings = useSettingsStore(s => s.updateSettings)
|
|
const loadSettings = useSettingsStore(s => s.loadSettings)
|
|
|
|
const [provider, setProvider] = useState<Provider>('openai')
|
|
const [model, setModel] = useState('')
|
|
const [apiKey, setApiKey] = useState('')
|
|
const [multimodal, setMultimodal] = useState(false)
|
|
const [hasStoredKey, setHasStoredKey] = useState(false)
|
|
const [saving, setSaving] = useState(false)
|
|
|
|
// Hydrate from the loaded settings. llm_api_key arrives masked, so we only use
|
|
// its presence to drive the placeholder, never the value itself. A stored
|
|
// 'local' from before #1772 shows as OpenAI (local state only, nothing is
|
|
// saved until Save is pressed) so the form never offers a value the server
|
|
// would refuse.
|
|
useEffect(() => {
|
|
if (!isLoaded) return
|
|
const stored = settings.llm_provider || 'openai'
|
|
setProvider(stored === 'local' ? 'openai' : stored)
|
|
setModel(settings.llm_model || '')
|
|
setMultimodal(settings.llm_multimodal === true)
|
|
setHasStoredKey(!!settings.llm_api_key)
|
|
}, [isLoaded, settings.llm_provider, settings.llm_model, settings.llm_multimodal, settings.llm_api_key])
|
|
|
|
const providerOptions = useMemo(
|
|
() => [
|
|
{ value: 'openai', label: t('settings.aiParsing.providerOpenai') },
|
|
{ value: 'anthropic', label: t('settings.aiParsing.providerAnthropic') },
|
|
],
|
|
[t],
|
|
)
|
|
|
|
const handleSave = async () => {
|
|
setSaving(true)
|
|
try {
|
|
const payload: Partial<Settings> = {
|
|
llm_provider: provider,
|
|
llm_model: model.trim(),
|
|
// Always cleared: the endpoint is instance configuration now, and this
|
|
// also drops a value left over from before #1772.
|
|
llm_base_url: '',
|
|
llm_multimodal: multimodal,
|
|
}
|
|
// Send the key only when the user typed a new one — a blank field means
|
|
// "keep the stored key".
|
|
const key = apiKey.trim()
|
|
if (key) payload.llm_api_key = key
|
|
await updateSettings(payload)
|
|
setApiKey('')
|
|
if (key) setHasStoredKey(true)
|
|
toast.success(t('settings.aiParsing.toast.saved'))
|
|
} catch {
|
|
// updateSettings patches the store before the request and keeps the patch
|
|
// when the request fails, so a refused save (the 403 from #1772, or any
|
|
// other error) would leave the form showing a value the server never
|
|
// stored. Pull the stored settings back in so what is on screen is real.
|
|
await loadSettings()
|
|
toast.error(t('settings.aiParsing.toast.saveError'))
|
|
} finally {
|
|
setSaving(false)
|
|
}
|
|
}
|
|
|
|
return (
|
|
<Section title={t('settings.aiParsing.title')} icon={Sparkles}>
|
|
<div className="space-y-3">
|
|
<p className="text-xs text-content-secondary">{t('settings.aiParsing.hint')}</p>
|
|
|
|
<div>
|
|
<label className="block text-sm font-medium mb-1.5 text-content-secondary">{t('settings.aiParsing.provider')}</label>
|
|
<CustomSelect
|
|
value={provider}
|
|
onChange={v => setProvider(v as Provider)}
|
|
options={providerOptions}
|
|
/>
|
|
<p className="mt-1 text-xs text-content-faint">{t('settings.aiParsing.localAdminOnly')}</p>
|
|
</div>
|
|
|
|
<div>
|
|
<label className="block text-sm font-medium mb-1.5 text-content-secondary">{t('settings.aiParsing.model')}</label>
|
|
<input
|
|
type="text"
|
|
autoComplete="off"
|
|
value={model}
|
|
onChange={e => setModel(e.target.value)}
|
|
placeholder="qwen3:8b"
|
|
className="w-full px-3 py-2.5 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-400 border-edge bg-surface-secondary text-content"
|
|
/>
|
|
</div>
|
|
|
|
{/* Both remaining providers are hosted and need a key, so this is no
|
|
longer conditional (#1772). */}
|
|
<div>
|
|
<label className="block text-sm font-medium mb-1.5 text-content-secondary">{t('settings.aiParsing.apiKey')}</label>
|
|
<input
|
|
type="password"
|
|
value={apiKey}
|
|
onChange={e => setApiKey(e.target.value)}
|
|
autoComplete="off"
|
|
placeholder={hasStoredKey && !apiKey ? '••••••••' : t('settings.aiParsing.apiKey')}
|
|
className="w-full px-3 py-2.5 border rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-slate-400 border-edge bg-surface-secondary text-content"
|
|
/>
|
|
<p className="mt-1 text-xs text-content-faint">{t('settings.aiParsing.apiKeyHint')}</p>
|
|
</div>
|
|
|
|
<div>
|
|
<div className="flex items-center gap-3">
|
|
<ToggleSwitch on={multimodal} onToggle={() => setMultimodal(v => !v)} />
|
|
<span className="text-sm font-medium text-content-secondary">{t('settings.aiParsing.multimodal')}</span>
|
|
</div>
|
|
<p className="mt-1 text-xs text-content-faint">{t('settings.aiParsing.multimodalHint')}</p>
|
|
</div>
|
|
|
|
<button type="button"
|
|
onClick={handleSave}
|
|
disabled={saving || !isLoaded}
|
|
className="flex items-center gap-2 px-4 py-2 rounded-lg text-sm font-medium text-white bg-slate-900 hover:bg-slate-700 disabled:opacity-50"
|
|
>
|
|
<Save className="w-4 h-4" /> {t('common.save')}
|
|
</button>
|
|
</div>
|
|
</Section>
|
|
)
|
|
}
|