diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 09224bbe..8fe2233f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -4,6 +4,9 @@ on: pull_request: push: +permissions: + contents: read + concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true diff --git a/build/dev-feedback-plugin.test.ts b/build/dev-feedback-plugin.test.ts deleted file mode 100644 index 385b763e..00000000 --- a/build/dev-feedback-plugin.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import assert from "node:assert/strict"; -import { EventEmitter } from "node:events"; -import type { IncomingMessage, ServerResponse } from "node:http"; -import test from "node:test"; - -import { feedbackMiddleware, feedbackRelayHint, sendToDiscord, validateFeedbackRequest } from "./dev-feedback-plugin.ts"; - -test("validateFeedbackRequest accepts a POST carrying an embeds array", () => { - const raw = JSON.stringify({ embeds: [{ title: "Hardware Test Report" }] }); - const validated = validateFeedbackRequest("POST", raw); - assert.equal(validated.valid, true); - assert.equal(validated.status, 200); - assert.deepEqual(validated.embeds, [{ title: "Hardware Test Report" }]); - assert.equal(validated.rawBody, raw); -}); - -test("validateFeedbackRequest rejects non-POST methods like the production relay", () => { - assert.equal(validateFeedbackRequest("GET", "").valid, false); - assert.equal(validateFeedbackRequest("GET", "").status, 405); - assert.equal(validateFeedbackRequest("OPTIONS", "").status, 405); - assert.equal(validateFeedbackRequest("PUT", "").status, 405); -}); - -test("validateFeedbackRequest rejects malformed JSON and bodies without an embeds array", () => { - assert.equal(validateFeedbackRequest("POST", "").status, 400); - assert.equal(validateFeedbackRequest("POST", "{nope").status, 400); - assert.equal(validateFeedbackRequest("POST", "hello").status, 400); - assert.equal(validateFeedbackRequest("POST", "{}").status, 400); - assert.equal(validateFeedbackRequest("POST", JSON.stringify({ content: "hello" })).status, 400); -}); - -test("sendToDiscord reports an accepted delivery", async () => { - let forwardedBody = ""; - const fakeFetch = (async (url: string, init: { body: string }) => { - assert.equal(url, "https://discord.example/webhook"); - assert.equal(init.body, "{}"); - forwardedBody = init.body; - return { ok: true, status: 204 } as Response; - }) as unknown as typeof fetch; - - const result = await sendToDiscord("https://discord.example/webhook", "{}", fakeFetch); - assert.deepEqual(result, { ok: true, status: 204 }); - assert.equal(forwardedBody, "{}"); -}); - -test("sendToDiscord reports when Discord rejects the payload", async () => { - const fakeFetch = (async () => ({ ok: false, status: 400 }) as Response) as unknown as typeof fetch; - const result = await sendToDiscord("https://discord.example/webhook", "bad", fakeFetch); - assert.deepEqual(result, { ok: false, status: 400 }); -}); - -test("sendToDiscord maps network failures to 502", async () => { - const fakeFetch = (async () => { - throw new Error("network down"); - }) as unknown as typeof fetch; - const result = await sendToDiscord("https://discord.example/webhook", "{}", fakeFetch); - assert.deepEqual(result, { ok: false, status: 502 }); -}); - -test("feedbackRelayHint announces live delivery when the webhook is configured", () => { - const hint = feedbackRelayHint("https://discord.com/api/webhooks/1/abc"); - assert.match(hint, /delivers to Discord/); - assert.doesNotMatch(hint, /503/); -}); - -test("feedbackRelayHint tells the developer to configure the webhook when it is missing", () => { - for (const webhook of [undefined, "", "https://example.com/not-discord"]) { - const hint = feedbackRelayHint(webhook); - assert.match(hint, /DISCORD_FEEDBACK_WEBHOOK/); - assert.match(hint, /503/); - assert.match(hint, /restart the dev server/); - } -}); - -test("feedbackMiddleware answers 413 with no-store for bodies over 1MB", async () => { - const req = new EventEmitter() as unknown as IncomingMessage; - (req as { method?: string }).method = "POST"; - let resolveEnd: (() => void) | undefined; - const ended = new Promise((resolve) => { resolveEnd = resolve; }); - const headers: Record = {}; - const res = { - statusCode: 0, - setHeader: (name: string, value: string): void => { headers[name.toLowerCase()] = value; }, - end: (body?: string): void => { - res.body = body; - resolveEnd?.(); - }, - body: undefined as string | undefined, - } as unknown as ServerResponse; - feedbackMiddleware(req, res, { webhook: "https://discord.com/api/webhooks/1/abc" }); - req.emit("data", Buffer.alloc(1024 * 1024 + 1)); - await ended; - assert.equal(res.statusCode, 413); - assert.equal(headers["cache-control"], "no-store"); - assert.match(res.body ?? "", /Payload too large/); -}); \ No newline at end of file diff --git a/build/dev-feedback-plugin.ts b/build/dev-feedback-plugin.ts deleted file mode 100644 index 1716e86b..00000000 --- a/build/dev-feedback-plugin.ts +++ /dev/null @@ -1,150 +0,0 @@ -import type { Plugin } from "vite"; -import { loadEnv } from "vite"; -import type { IncomingMessage, ServerResponse } from "node:http"; - -export interface FeedbackValidation { - valid: boolean; - status: number; - body: string; - embeds: unknown[] | null; - rawBody: string; -} - -export interface DiscordForwardResult { - ok: boolean; - status: number; -} - -export function feedbackRelayHint(webhook: string | undefined): string { - if (!webhook || !webhook.startsWith("https://discord")) { - return "[dev-feedback] relay up, but DISCORD_FEEDBACK_WEBHOOK is not set in .env.local — Share report will answer 503 until it is; add it and restart the dev server"; - } - return "[dev-feedback] relay up — DISCORD_FEEDBACK_WEBHOOK set; Share report delivers to Discord"; -} - - -export function validateFeedbackRequest(method: string | undefined, rawBody: string): FeedbackValidation { - if (method !== "POST") { - return { valid: false, status: 405, body: JSON.stringify({ message: "Method not allowed." }), embeds: null, rawBody }; - } - if (typeof rawBody !== "string" || rawBody === "") { - return { valid: false, status: 400, body: JSON.stringify({ message: "Expected a JSON body." }), embeds: null, rawBody }; - } - let parsed: unknown; - try { - parsed = JSON.parse(rawBody); - } catch { - return { valid: false, status: 400, body: JSON.stringify({ message: "Invalid JSON." }), embeds: null, rawBody }; - } - const embeds = (parsed as { embeds?: unknown }).embeds; - if (!Array.isArray(embeds)) { - return { valid: false, status: 400, body: JSON.stringify({ message: "Expected an embeds array." }), embeds: null, rawBody }; - } - return { valid: true, status: 200, body: JSON.stringify({ ok: true }), embeds, rawBody }; -} - -export async function sendToDiscord( - webhook: string, - rawBody: string, - fetchImpl: typeof fetch = fetch, -): Promise { - try { - const response = await fetchImpl(webhook, { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: rawBody, - }); - return { ok: response.ok, status: response.status }; - } catch { - return { ok: false, status: 502 }; - } -} - -export const MAX_DEV_BODY_BYTES = 1024 * 1024; - -export interface FeedbackMiddlewareOptions { - webhook: string | undefined; - onInfo?: (message: string) => void; -} - -/** Test seam for the dev-only /api/feedback middleware: enforces the 1MB cap, - * validates the JSON body, then relays to Discord. Every response carries - * Cache-Control: no-store so reports never linger in a cache. */ -export function feedbackMiddleware( - req: IncomingMessage, - res: ServerResponse, - options: FeedbackMiddlewareOptions, - fetchImpl: typeof fetch = fetch, -): void { - const info = options.onInfo ?? (() => {}); - const chunks: Buffer[] = []; - let size = 0; - let finished = false; - req.on("data", (chunk: Buffer) => { - if (finished) return; - size += chunk.length; - if (size <= MAX_DEV_BODY_BYTES) { - chunks.push(chunk); - return; - } - finished = true; - endJson(res, 413, JSON.stringify({ message: "Payload too large." })); - }); - req.on("end", async () => { - if (finished) return; - const raw = Buffer.concat(chunks).toString("utf8"); - const validation = validateFeedbackRequest(req.method, raw); - if (!validation.valid) { - endJson(res, validation.status, validation.body); - return; - } - const count = validation.embeds?.length ?? 0; - const titles = (validation.embeds ?? []) - .map((embed) => (embed as { title?: unknown })?.title ?? "untitled") - .join(" · "); - if (!options.webhook || !options.webhook.startsWith("https://discord")) { - info( - `[dev-feedback] received ${count} embed(s) (${titles}) but DISCORD_FEEDBACK_WEBHOOK is not set — add it to .env.local to deliver from dev`, - ); - endJson( - res, - 503, - JSON.stringify({ - message: "Feedback is not configured — set DISCORD_FEEDBACK_WEBHOOK in .env.local to deliver locally.", - }), - ); - return; - } - const delivery = await sendToDiscord(options.webhook, raw, fetchImpl); - if (!delivery.ok) { - info(`[dev-feedback] Discord rejected the delivery (${delivery.status}).`); - endJson(res, delivery.status, JSON.stringify({ message: "Discord rejected the feedback." })); - return; - } - info(`[dev-feedback] relayed ${count} embed(s) to Discord: ${titles}`); - endJson(res, 200, JSON.stringify({ ok: true })); - }); -} - -function endJson(res: ServerResponse, status: number, body: string): void { - res.statusCode = status; - res.setHeader("Content-Type", "application/json"); - res.setHeader("Cache-Control", "no-store"); - res.end(body); -} - -export function devFeedback(): Plugin { - return { - name: "openmouse:dev-feedback", - apply: "serve", - configureServer(server) { - const env = loadEnv(server.config.mode, server.config.root, ""); - const webhook = env.DISCORD_FEEDBACK_WEBHOOK; - server.config.logger.info(feedbackRelayHint(webhook)); - const info = (message: string): void => server.config.logger.info(message); - server.middlewares.use("/api/feedback", (req: IncomingMessage, res: ServerResponse) => - feedbackMiddleware(req, res, { webhook, onInfo: info }), - ); - }, - }; -} \ No newline at end of file diff --git a/functions/_lib/admin.js b/functions/_lib/admin.js index 7eb8a315..9641ac8e 100644 --- a/functions/_lib/admin.js +++ b/functions/_lib/admin.js @@ -9,9 +9,14 @@ export const ADMIN_UNBAN_PATH = "/api/admin/unban"; // Constant-time string compare — a plain `===` leaks the token prefix one byte // at a time to a patient attacker. export function safeEqual(a, b) { - if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false; - let diff = 0; - for (let i = 0; i < a.length; i += 1) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); + if (typeof a !== "string" || typeof b !== "string") return false; + let diff = a.length ^ b.length; + const len = Math.max(a.length, b.length); + for (let i = 0; i < len; i += 1) { + const ca = i < a.length ? a.charCodeAt(i) : 0; + const cb = i < b.length ? b.charCodeAt(i) : 0; + diff |= ca ^ cb; + } return diff === 0; } diff --git a/functions/_lib/feedback-payload.js b/functions/_lib/feedback-payload.js deleted file mode 100644 index 1c3779a2..00000000 --- a/functions/_lib/feedback-payload.js +++ /dev/null @@ -1,48 +0,0 @@ -function text(value, max) { - if (typeof value !== "string" || value.length > max) throw new Error("Invalid text"); - return value; -} - -export function feedbackPayload(input) { - if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("Invalid payload"); - const payload = { allowed_mentions: { parse: [] } }; - if (input.content !== undefined) payload.content = text(input.content, 2000); - if (input.embeds !== undefined) { - if (!Array.isArray(input.embeds) || input.embeds.length > 10) throw new Error("Invalid embeds"); - let total = 0; - payload.embeds = input.embeds.map((embed) => { - if (!embed || typeof embed !== "object" || Array.isArray(embed)) throw new Error("Invalid embed"); - const result = {}; - for (const [key, limit] of [["title", 256], ["description", 4096]]) { - if (embed[key] !== undefined) { result[key] = text(embed[key], limit); total += result[key].length; } - } - if (embed.color !== undefined) { - if (!Number.isInteger(embed.color) || embed.color < 0 || embed.color > 0xffffff) throw new Error("Invalid color"); - result.color = embed.color; - } - if (embed.fields !== undefined) { - if (!Array.isArray(embed.fields) || embed.fields.length > 25) throw new Error("Invalid fields"); - result.fields = embed.fields.map((field) => { - const name = text(field?.name, 256); - const value = text(field?.value, 1024); - total += name.length + value.length; - return { name, value, ...(typeof field.inline === "boolean" ? { inline: field.inline } : {}) }; - }); - } - if (embed.footer !== undefined) { - const value = text(embed.footer?.text, 2048); - total += value.length; - result.footer = { text: value }; - } - if (embed.timestamp !== undefined) { - const value = text(embed.timestamp, 64); - if (!Number.isFinite(Date.parse(value))) throw new Error("Invalid timestamp"); - result.timestamp = value; - } - return result; - }); - if (total > 6000) throw new Error("Embeds too long"); - } - if (!payload.content && !payload.embeds?.length) throw new Error("Empty feedback"); - return payload; -} diff --git a/functions/_middleware.js b/functions/_middleware.js index b215f945..40cf9f77 100644 --- a/functions/_middleware.js +++ b/functions/_middleware.js @@ -145,7 +145,7 @@ const MAX_BODY_BYTES = 8 * 1024 * 1024; const GET_LIMIT_PER_MINUTE = 240; const POST_LIMIT_PER_MINUTE = 30; -function clientIp(request) { +export function clientIp(request) { return ( request.headers.get("CF-Connecting-IP") || request.headers.get("x-real-ip") || @@ -156,7 +156,7 @@ function clientIp(request) { // Adds a strike; returns true when the threshold is crossed and the IP is now // permanently banned. -async function strike(kv, ip) { +export async function strike(kv, ip) { const current = Number((await kv.get(`strikes:${ip}`)) ?? "0"); const next = current + 1; if (next >= STRIKES_TO_BAN) { @@ -181,31 +181,37 @@ export async function onRequest(context) { } async function handle({ request, env, next }) { - const limit = MAX_BODY_BYTES; - try { - request = await boundedRequest(request, limit); - } catch (error) { - return error instanceof BodyTooLarge ? tooLarge() : new Response("Invalid body", { status: 400 }); - } - const forward = () => next(request); const kv = env.SECURITY_KV; - if (!kv) return forward(); - const ip = clientIp(request); const url = new URL(request.url); // Subresources are the bulk of traffic and the bulk of the KV bill; skip them - // before any storage work. - if (isStaticSubresource(request, url)) return forward(); + // before any storage work or body buffering. + if (kv && isStaticSubresource(request, url)) return next(request); + // Check permanent bans before buffering up to MAX_BODY_BYTES into memory. // An admin who is themselves caught by a ban (shared/NAT IP) still has to // reach the unban endpoint, so that one path is exempt — and only when the // request carries the correct ADMIN_TOKEN, which the endpoint re-checks. - const banReason = await kv.get(`ban:${ip}`); - if (banReason && !isAdminUnbanRequest(request, env, url.pathname)) { - return banPage(banReason === "1" ? "security" : banReason); + if (kv) { + const banReason = await kv.get(`ban:${ip}`); + if (banReason && !isAdminUnbanRequest(request, env, url.pathname)) { + return banPage(banReason === "1" ? "security" : banReason); + } } + try { + request = await boundedRequest(request, MAX_BODY_BYTES); + } catch (error) { + if (error instanceof BodyTooLarge) { + if (kv) await strike(kv, ip); + return tooLarge(); + } + return new Response("Invalid body", { status: 400 }); + } + const forward = () => next(request); + if (!kv) return forward(); + const method = request.method.toUpperCase(); // When a WAF rate limiting rule is enforcing limits at the edge @@ -226,11 +232,6 @@ async function handle({ request, env, next }) { return block(); } - if (method === "POST" && Number(request.headers.get("Content-Length") ?? "0") > MAX_BODY_BYTES) { - await strike(kv, ip); - return tooLarge(); - } - if (kvRateLimit && await enforceRateLimit(kv, request, ip)) { await strike(kv, ip); return tooMany(); diff --git a/functions/api/admin/unban.js b/functions/api/admin/unban.js index aef641a5..e5db78eb 100644 --- a/functions/api/admin/unban.js +++ b/functions/api/admin/unban.js @@ -14,6 +14,7 @@ // variables); unset disables the route entirely. import { isAdminRequest } from "../../_lib/admin.js"; +import { clientIp, strike } from "../../_middleware.js"; const json = (body, status = 200) => new Response(JSON.stringify(body), { @@ -25,6 +26,7 @@ export async function onRequest({ request, env }) { if (request.method !== "POST") return json({ message: "Method not allowed." }, 405); if (!isAdminRequest(request, env)) { + if (env.SECURITY_KV) await strike(env.SECURITY_KV, clientIp(request)); return json({ message: "Unauthorized." }, 401); } diff --git a/functions/api/feedback.js b/functions/api/feedback.js deleted file mode 100644 index 8bf89452..00000000 --- a/functions/api/feedback.js +++ /dev/null @@ -1,54 +0,0 @@ -import { boundedRequest, BodyTooLarge } from "../_lib/body-limit.js"; -import { feedbackPayload } from "../_lib/feedback-payload.js"; - -const json = (body, status = 200) => new Response(JSON.stringify(body), { - status, - headers: { "Content-Type": "application/json", "Cache-Control": "no-store" }, -}); - -export async function onRequest({ request, env }) { - if (request.method !== "POST") return json({ message: "Method not allowed." }, 405); - const origin = request.headers.get("Origin"); - if (origin && origin !== new URL(request.url).origin) return json({ message: "Origin not allowed." }, 403); - let webhook; - try { webhook = new URL(env.DISCORD_FEEDBACK_WEBHOOK); } catch { return json({ message: "Feedback is not configured." }, 503); } - if (webhook.protocol !== "https:" || !["discord.com", "discordapp.com"].includes(webhook.hostname) || !webhook.pathname.startsWith("/api/webhooks/")) return json({ message: "Feedback is not configured." }, 503); - let body; - let headers; - try { - const type = request.headers.get("Content-Type") ?? ""; - const multipart = /^multipart\/form-data(?:;|$)/i.test(type); - if (!multipart && !/^application\/json(?:;|$)/i.test(type)) return json({ message: "Unsupported content type." }, 415); - request = await boundedRequest(request, multipart ? 8 * 1024 * 1024 : 64 * 1024); - if (multipart) { - const input = await request.formData(); - const raw = input.getAll("payload_json"); - if (raw.length !== 1 || typeof raw[0] !== "string" || new TextEncoder().encode(raw[0]).length > 64 * 1024) throw new Error("Invalid payload_json"); - const payload = feedbackPayload(JSON.parse(raw[0])); - const form = new FormData(); - const names = new Set(); - for (const [key, file] of input) { - if (key === "payload_json") continue; - if (!/^files\[[0-3]\]$/.test(key) || names.has(key) || typeof file === "string" || file.size > 2 * 1024 * 1024) throw new Error("Invalid attachment"); - names.add(key); - form.append(key, file, file.name); - } - form.set("payload_json", JSON.stringify(payload)); - body = form; - } else { - body = JSON.stringify(feedbackPayload(await request.json())); - headers = { "Content-Type": "application/json" }; - } - } catch (error) { - return json({ message: error instanceof BodyTooLarge ? "Feedback too large." : "Invalid feedback." }, error instanceof BodyTooLarge ? 413 : 400); - } - try { - // A hung Discord webhook must not hold the Worker: the existing 502 path - // covers the timeout abort below. - const response = await fetch(webhook.href, { method: "POST", headers, body, signal: AbortSignal.timeout(10000) }); - if (!response.ok) return json({ message: "Discord rejected the feedback." }, 502); - return json({ ok: true }); - } catch { - return json({ message: "Discord unreachable." }, 502); - } -} diff --git a/src/device/firmware-updates.ts b/src/device/firmware-updates.ts index 4af51243..0ddf3eee 100644 --- a/src/device/firmware-updates.ts +++ b/src/device/firmware-updates.ts @@ -246,12 +246,21 @@ export function getDfuInfo(device: FirmwareDeviceRef, manifest: FirmwareManifest const current = currentFirmwareVersion(device.firmware); if (!current) return null; const available = compareVersions(current, entry.latestVersion) < 0; + let downloadUrl: string | undefined; + if (typeof entry.downloadUrl === "string" && entry.downloadUrl.trim()) { + try { + const parsed = new URL(entry.downloadUrl.trim()); + if (parsed.protocol === "https:") downloadUrl = parsed.href; + } catch { + downloadUrl = undefined; + } + } return { currentVersion: current, latestVersion: entry.latestVersion, dfuAvailable: available, dfuRequired: available && entry.required === true, - downloadUrl: entry.downloadUrl, + downloadUrl, releaseNotes: entry.releaseNotes, history: entry.history, }; diff --git a/src/features/games/GameRequestDialog.tsx b/src/features/games/GameRequestDialog.tsx deleted file mode 100644 index ee8cc61b..00000000 --- a/src/features/games/GameRequestDialog.tsx +++ /dev/null @@ -1,453 +0,0 @@ -import { displayText } from "../../i18n/index"; -import { track } from "../../platform/analytics"; -import { useUiLocale } from "../../shared/ui-locale"; -import { useEffect, useRef, useState, type ReactNode } from "react"; -import { Check, Copy, Gamepad2 } from "lucide-react"; -import * as control from "../../device/controller"; -import { bridgeApplicationIconUrl, bridgeRunningApplications, type BridgeApplication, type BridgeGame } from "../bridge/bridge"; -import { t, tp, type I18nKey } from "../../i18n/index"; -import type { InterfaceLocale } from "../settings/interface-preferences"; - -const REQUEST_URL = "/api/feedback"; -const MAX_NAME_LENGTH = 80; -const MAX_PATH_LENGTH = 400; -const COOLDOWN_KEY = "openmouse.gamereq.sentAt"; -const COOLDOWN_MS = 60_000; -// Discord's current username rules: 2–32 of lowercase letters, digits, `_` and `.`. -const DISCORD_USERNAME = /^[a-z0-9_.]{2,32}$/; - -type Platform = "windows" | "macos" | "linux"; -type RequestKind = "game" | "app"; - -const KIND_TITLES: Record = { game: "Game Request", app: "App Request" }; - -// Each command prints the path of the running game or app's executable. -// macOS asks for the frontmost window directly, so it waits a few seconds for -// the user to switch to it first. -const COMMANDS: Record = { - windows: { - shell: "PowerShell", - command: "Get-Process | Where-Object MainWindowTitle | Select-Object MainWindowTitle, Path | Format-List", - hint: "gamereq.cmdWindowsHint", - }, - macos: { - shell: "Terminal", - command: "sleep 5; ps -o comm= -p $(osascript -e 'tell application \"System Events\" to unix id of first process whose frontmost is true')", - hint: "gamereq.cmdMacHint", - }, - linux: { - shell: "Terminal", - command: "ps -eo args= | grep -iE '\\.exe|steamapps' | grep -v grep | sort -u", - hint: "gamereq.cmdLinuxHint", - }, -}; - -const PATH_EXAMPLES: Record> = { - game: { - windows: "C:\\Program Files (x86)\\Steam\\steamapps\\common\\Game\\game.exe", - macos: "/Applications/Game.app/Contents/MacOS/Game", - linux: "/home/you/.steam/steam/steamapps/common/Game/game", - }, - app: { - windows: "C:\\Program Files\\Adobe\\Adobe Premiere Pro 2026\\Adobe Premiere Pro.exe", - macos: "/Applications/Adobe Premiere Pro 2026/Adobe Premiere Pro 2026.app/Contents/MacOS/Adobe Premiere Pro 2026", - linux: "/usr/bin/blender", - }, -}; - -const PLATFORM_LABELS: Record = { windows: "Windows", macos: "macOS", linux: "Linux" }; - -function detectPlatform(): Platform { - const hint = (navigator as Navigator & { userAgentData?: { platform?: string } }).userAgentData?.platform - ?? navigator.platform - ?? ""; - if (/mac/i.test(hint)) return "macos"; - if (/linux|x11|cros/i.test(hint)) return "linux"; - return "windows"; -} - -/** Strips the quotes Explorer's "Copy as path" and shell output wrap paths in. */ -function cleanPath(raw: string): string { - return raw.trim().replace(/^["']+|["']+$/g, "").trim(); -} - -/** The file name Bridge actually matches on (`cs2.exe`, `ghostty`). */ -function executableName(path: string): string { - return path.split(/[\\/]/).filter(Boolean).pop() ?? ""; -} - -/** Keeps user text from breaking out of the inline-code span in the embed. */ -function codeSpan(value: string): string { - return `\`${value.replace(/`/g, "'")}\``; -} - -function readSentAt(): number { - try { - return Number(window.localStorage.getItem(COOLDOWN_KEY)) || 0; - } catch { - return 0; - } -} - -function useCopied(): [string | null, (key: string, text: string) => void] { - const [copied, setCopied] = useState(null); - useEffect(() => { - if (!copied) return; - const timer = window.setTimeout(() => setCopied(null), 1600); - return () => window.clearTimeout(timer); - }, [copied]); - return [copied, (key, text) => { - void navigator.clipboard?.writeText(text).then(() => setCopied(key)).catch(() => undefined); - }]; -} - -/** Bridge only extracts icons on Windows; everywhere else the URL 404s. */ -function AppIcon({ app }: { app: BridgeApplication }): ReactNode { - const __uiLocale = useUiLocale(); - const [failed, setFailed] = useState(false); - if (failed) return