mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-10-19 13:36:48 +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.
284 lines
12 KiB
TypeScript
284 lines
12 KiB
TypeScript
import React, { useState, useEffect } from 'react'
|
|
import { adminApi, tripsApi } from '../../api/client'
|
|
import { getApiErrorMessage } from '../../utils/apiError'
|
|
import { useAuthStore } from '../../store/authStore'
|
|
import { useToast } from '../shared/Toast'
|
|
import {
|
|
Bell, Zap, ArrowRight, CheckCircle, Navigation, User,
|
|
Calendar, Clock, Image, MessageSquare, Tag, UserPlus,
|
|
Download, MapPin,
|
|
} from 'lucide-react'
|
|
|
|
interface Trip {
|
|
id: number
|
|
title: string
|
|
}
|
|
|
|
interface AppUser {
|
|
id: number
|
|
username: string
|
|
email: string
|
|
}
|
|
|
|
export default function DevNotificationsPanel(): React.ReactElement {
|
|
const toast = useToast()
|
|
const user = useAuthStore(s => s.user)
|
|
const [sending, setSending] = useState<string | null>(null)
|
|
const [trips, setTrips] = useState<Trip[]>([])
|
|
const [selectedTripId, setSelectedTripId] = useState<number | null>(null)
|
|
const [users, setUsers] = useState<AppUser[]>([])
|
|
const [selectedUserId, setSelectedUserId] = useState<number | null>(null)
|
|
|
|
useEffect(() => {
|
|
tripsApi.list().then(data => {
|
|
const list = (data.trips || data || []) as Trip[]
|
|
setTrips(list)
|
|
if (list.length > 0) setSelectedTripId(list[0].id)
|
|
}).catch(() => {})
|
|
adminApi.users().then(data => {
|
|
const list = (data.users || data || []) as AppUser[]
|
|
setUsers(list)
|
|
if (list.length > 0) setSelectedUserId(list[0].id)
|
|
}).catch(() => {})
|
|
}, [])
|
|
|
|
const fire = async (label: string, payload: Record<string, unknown>) => {
|
|
setSending(label)
|
|
try {
|
|
await adminApi.sendTestNotification(payload)
|
|
toast.success(`Sent: ${label}`)
|
|
} catch (err: unknown) {
|
|
toast.error(getApiErrorMessage(err, 'Failed'))
|
|
} finally {
|
|
setSending(null)
|
|
}
|
|
}
|
|
|
|
const selectedTrip = trips.find(t => t.id === selectedTripId)
|
|
const selectedUser = users.find(u => u.id === selectedUserId)
|
|
const username = user?.username || 'Admin'
|
|
const tripTitle = selectedTrip?.title || 'Test Trip'
|
|
|
|
// ── Helpers ──────────────────────────────────────────────────────────────
|
|
|
|
const Btn = ({
|
|
id, label, sub, icon: Icon, color, onClick,
|
|
}: {
|
|
id: string; label: string; sub: string; icon: React.ElementType; color: string; onClick: () => void
|
|
}) => (
|
|
<button type="button"
|
|
onClick={onClick}
|
|
disabled={sending !== null}
|
|
className="flex items-center gap-3 px-4 py-3 rounded-lg border transition-colors text-left w-full border-edge bg-surface-card"
|
|
onMouseEnter={e => { e.currentTarget.style.background = 'var(--bg-hover)' }}
|
|
onMouseLeave={e => { e.currentTarget.style.background = 'var(--bg-card)' }}
|
|
>
|
|
<div className="w-8 h-8 rounded-lg flex items-center justify-center flex-shrink-0"
|
|
style={{ background: `${color}20`, color }}>
|
|
<Icon className="w-4 h-4" />
|
|
</div>
|
|
<div className="min-w-0 flex-1">
|
|
<p className="text-sm font-medium text-content">{label}</p>
|
|
<p className="text-xs truncate text-content-faint">{sub}</p>
|
|
</div>
|
|
{sending === id && (
|
|
<div className="w-4 h-4 border-2 border-slate-200 border-t-indigo-500 rounded-full animate-spin flex-shrink-0" />
|
|
)}
|
|
</button>
|
|
)
|
|
|
|
const SectionTitle = ({ children }: { children: React.ReactNode }) => (
|
|
<h3 className="text-sm font-semibold mb-3 text-content-secondary">{children}</h3>
|
|
)
|
|
|
|
const TripSelector = () => (
|
|
<select
|
|
value={selectedTripId ?? ''}
|
|
onChange={e => setSelectedTripId(Number(e.target.value))}
|
|
className="w-full px-3 py-2 rounded-lg border text-sm mb-3 border-edge bg-surface-card text-content"
|
|
>
|
|
{trips.map(trip => <option key={trip.id} value={trip.id}>{trip.title}</option>)}
|
|
</select>
|
|
)
|
|
|
|
const UserSelector = () => (
|
|
<select
|
|
value={selectedUserId ?? ''}
|
|
onChange={e => setSelectedUserId(Number(e.target.value))}
|
|
className="w-full px-3 py-2 rounded-lg border text-sm mb-3 border-edge bg-surface-card text-content"
|
|
>
|
|
{users.map(u => <option key={u.id} value={u.id}>{u.username} ({u.email})</option>)}
|
|
</select>
|
|
)
|
|
|
|
return (
|
|
<div className="space-y-8">
|
|
<div className="flex items-center gap-2">
|
|
<div className="px-2 py-0.5 rounded text-xs font-mono font-bold bg-[#fbbf24] text-[#000]">
|
|
DEV ONLY
|
|
</div>
|
|
<span className="text-sm font-medium text-content">
|
|
Notification Testing
|
|
</span>
|
|
</div>
|
|
|
|
{/* ── Type Testing ─────────────────────────────────────────────────── */}
|
|
<div>
|
|
<SectionTitle>Type Testing</SectionTitle>
|
|
<p className="text-xs mb-3 text-content-muted">
|
|
Test how each in-app notification type renders, sent to yourself.
|
|
</p>
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
|
<Btn id="simple-me" label="Simple → Me" sub="test_simple · user" icon={Bell} color="#6366f1"
|
|
onClick={() => fire('simple-me', {
|
|
event: 'test_simple',
|
|
scope: 'user',
|
|
targetId: user?.id,
|
|
params: {},
|
|
})}
|
|
/>
|
|
<Btn id="boolean-me" label="Boolean → Me" sub="test_boolean · user" icon={CheckCircle} color="#10b981"
|
|
onClick={() => fire('boolean-me', {
|
|
event: 'test_boolean',
|
|
scope: 'user',
|
|
targetId: user?.id,
|
|
params: {},
|
|
inApp: {
|
|
type: 'boolean',
|
|
positiveCallback: { action: 'test_approve', payload: {} },
|
|
negativeCallback: { action: 'test_deny', payload: {} },
|
|
},
|
|
})}
|
|
/>
|
|
<Btn id="navigate-me" label="Navigate → Me" sub="test_navigate · user" icon={Navigation} color="#f59e0b"
|
|
onClick={() => fire('navigate-me', {
|
|
event: 'test_navigate',
|
|
scope: 'user',
|
|
targetId: user?.id,
|
|
params: {},
|
|
})}
|
|
/>
|
|
<Btn id="simple-admins" label="Simple → All Admins" sub="test_simple · admin" icon={Zap} color="#ef4444"
|
|
onClick={() => fire('simple-admins', {
|
|
event: 'test_simple',
|
|
scope: 'admin',
|
|
targetId: 0,
|
|
params: {},
|
|
})}
|
|
/>
|
|
</div>
|
|
</div>
|
|
|
|
{/* ── Trip-Scoped Events ───────────────────────────────────────────── */}
|
|
{trips.length > 0 && (
|
|
<div>
|
|
<SectionTitle>Trip-Scoped Events</SectionTitle>
|
|
<p className="text-xs mb-3 text-content-muted">
|
|
Fires each trip event to all members of the selected trip (excluding yourself).
|
|
</p>
|
|
<TripSelector />
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
|
<Btn id="booking_change" label="booking_change" sub="navigate · trip" icon={Calendar} color="#6366f1"
|
|
onClick={() => selectedTripId && fire('booking_change', {
|
|
event: 'booking_change',
|
|
scope: 'trip',
|
|
targetId: selectedTripId,
|
|
params: { actor: username, trip: tripTitle, booking: 'Test Hotel', type: 'hotel', tripId: String(selectedTripId) },
|
|
})}
|
|
/>
|
|
<Btn id="trip_reminder" label="trip_reminder" sub="navigate · trip" icon={Clock} color="#10b981"
|
|
onClick={() => selectedTripId && fire('trip_reminder', {
|
|
event: 'trip_reminder',
|
|
scope: 'trip',
|
|
targetId: selectedTripId,
|
|
params: { trip: tripTitle, tripId: String(selectedTripId) },
|
|
})}
|
|
/>
|
|
<Btn id="photos_shared" label="photos_shared" sub="navigate · trip" icon={Image} color="#f59e0b"
|
|
onClick={() => selectedTripId && fire('photos_shared', {
|
|
event: 'photos_shared',
|
|
scope: 'trip',
|
|
targetId: selectedTripId,
|
|
params: { actor: username, trip: tripTitle, count: '5', tripId: String(selectedTripId) },
|
|
})}
|
|
/>
|
|
<Btn id="collab_message" label="collab_message" sub="navigate · trip" icon={MessageSquare} color="#8b5cf6"
|
|
onClick={() => selectedTripId && fire('collab_message', {
|
|
event: 'collab_message',
|
|
scope: 'trip',
|
|
targetId: selectedTripId,
|
|
params: { actor: username, trip: tripTitle, preview: 'This is a test message preview.', tripId: String(selectedTripId) },
|
|
})}
|
|
/>
|
|
<Btn id="packing_tagged" label="packing_tagged" sub="navigate · trip" icon={Tag} color="#ec4899"
|
|
onClick={() => selectedTripId && fire('packing_tagged', {
|
|
event: 'packing_tagged',
|
|
scope: 'trip',
|
|
targetId: selectedTripId,
|
|
params: { actor: username, trip: tripTitle, category: 'Clothing', tripId: String(selectedTripId) },
|
|
})}
|
|
/>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* ── User-Scoped Events ───────────────────────────────────────────── */}
|
|
{users.length > 0 && (
|
|
<div>
|
|
<SectionTitle>User-Scoped Events</SectionTitle>
|
|
<p className="text-xs mb-3 text-content-muted">
|
|
Fires each user event to the selected recipient.
|
|
</p>
|
|
<UserSelector />
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
|
<Btn
|
|
id={`trip_invite-${selectedUserId}`}
|
|
label="trip_invite"
|
|
sub="navigate · user"
|
|
icon={UserPlus}
|
|
color="#06b6d4"
|
|
onClick={() => selectedUserId && fire(`trip_invite-${selectedUserId}`, {
|
|
event: 'trip_invite',
|
|
scope: 'user',
|
|
targetId: selectedUserId,
|
|
params: { actor: username, trip: tripTitle, invitee: selectedUser?.email || '', tripId: String(selectedTripId ?? 0) },
|
|
})}
|
|
/>
|
|
<Btn
|
|
id={`vacay_invite-${selectedUserId}`}
|
|
label="vacay_invite"
|
|
sub="navigate · user"
|
|
icon={MapPin}
|
|
color="#f97316"
|
|
onClick={() => selectedUserId && fire(`vacay_invite-${selectedUserId}`, {
|
|
event: 'vacay_invite',
|
|
scope: 'user',
|
|
targetId: selectedUserId,
|
|
params: { actor: username, planId: '1' },
|
|
})}
|
|
/>
|
|
</div>
|
|
</div>
|
|
)}
|
|
|
|
{/* ── Admin-Scoped Events ──────────────────────────────────────────── */}
|
|
<div>
|
|
<SectionTitle>Admin-Scoped Events</SectionTitle>
|
|
<p className="text-xs mb-3 text-content-muted">
|
|
Fires to all admin users.
|
|
</p>
|
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
|
|
<Btn id="version_available" label="version_available" sub="navigate · admin" icon={Download} color="#64748b"
|
|
onClick={() => fire('version_available', {
|
|
event: 'version_available',
|
|
scope: 'admin',
|
|
targetId: 0,
|
|
params: { version: '9.9.9-test' },
|
|
})}
|
|
/>
|
|
</div>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|