From 42d4158c439a0300ec043f2bd827d76f4f7fb1b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mathias=20W=C3=B6=C3=9F?= Date: Sat, 14 Nov 2026 00:31:50 +0100 Subject: [PATCH 1/9] feat: add feedback worker function (to be deployed as endpoint) --- feedback-api/api/feedback.ts | 161 ++++++++++++++++++++++++++++ feedback-api/package.json | 8 ++ feedback-api/tests/feedback.test.ts | 107 ++++++++++++++++++ tsconfig.json | 1 + 4 files changed, 277 insertions(+) create mode 100644 feedback-api/api/feedback.ts create mode 100644 feedback-api/package.json create mode 100644 feedback-api/tests/feedback.test.ts diff --git a/feedback-api/api/feedback.ts b/feedback-api/api/feedback.ts new file mode 100644 index 0000000..4f61a11 --- /dev/null +++ b/feedback-api/api/feedback.ts @@ -0,0 +1,161 @@ +export interface FeedbackPayload { + message: string; + version: string; + userAgent: string; + script?: { filename: string; source: string }; +} + +interface ResendEmail { + from: string; + to: string; + subject: string; + text: string; + attachments?: { filename: string; content: string }[]; +} + +const MAX_MESSAGE = 5_000; +const MAX_SCRIPT = 200_000; + +const isString = (v: unknown): v is string => typeof v === "string"; + +/** Validates an untrusted request body, returning the payload or an error message. */ +export function parseFeedback(body: unknown): FeedbackPayload | string { + if (typeof body !== "object" || body === null) return "Invalid body"; + const { message, version, userAgent, script } = body as Record< + string, + unknown + >; + if (!isString(message) || !message.trim()) return "Message is required"; + if (message.length > MAX_MESSAGE) return "Message too long"; + if (!isString(version) || version.length > 32) return "Invalid version"; + if (!isString(userAgent) || userAgent.length > 512) + return "Invalid user agent"; + + const payload: FeedbackPayload = { + message: message.trim(), + version, + userAgent, + }; + + if (script !== undefined) { + const { filename, source } = script as Record; + if (!isString(filename) || filename.length > 256 || !isString(source)) + return "Invalid script"; + if (source.length > MAX_SCRIPT) return "Script too large"; + payload.script = { filename, source }; + } + + return payload; +} + +/** Matches an origin against an allow-list; entries ending in `*` match by prefix. */ +export function isAllowedOrigin(origin: string | null, allowed: string[]) { + if (!origin) return false; + return allowed.some((entry) => + entry.endsWith("*") + ? origin.startsWith(entry.slice(0, -1)) + : entry === origin, + ); +} + +/** Builds the Resend API request body for a feedback payload. */ +export function buildEmail( + payload: FeedbackPayload, + from: string, + to: string, +): ResendEmail { + const firstLine = payload.message.split("\n")[0].slice(0, 60); + const attachments: { filename: string; content: string }[] = []; + if (payload.script) { + attachments.push({ + filename: payload.script.filename, + content: Buffer.from(payload.script.source).toString("base64"), + }); + } + return { + from, + to, + subject: `[Scriptmonkey v${payload.version}] ${firstLine}`, + text: `${payload.message}\n\n---\nVersion: ${payload.version}\nUser agent: ${payload.userAgent}`, + ...(attachments.length && { attachments }), + }; +} + +function allowedOrigins() { + return (process.env.ALLOWED_ORIGINS ?? "") + .split(",") + .map((s) => s.trim()) + .filter(Boolean); +} + +function corsHeaders(origin: string): HeadersInit { + return { + "Access-Control-Allow-Origin": origin, + "Access-Control-Allow-Methods": "POST, OPTIONS", + "Access-Control-Allow-Headers": "Content-Type", + Vary: "Origin", + }; +} + +/** Sends the validated feedback payload via the Resend API. */ +export async function sendFeedbackEmail( + payload: FeedbackPayload, + apiKey: string, + from: string, + to: string, +): Promise<{ ok: boolean; status: number; error?: string }> { + const res = await fetch("https://api.resend.com/emails", { + method: "POST", + headers: { + Authorization: `Bearer ${apiKey}`, + "Content-Type": "application/json", + }, + body: JSON.stringify(buildEmail(payload, from, to)), + }); + if (!res.ok) { + const text = await res.text(); + return { ok: false, status: res.status, error: text }; + } + return { ok: true, status: 200 }; +} + +export function OPTIONS(request: Request): Response { + const origin = request.headers.get("Origin"); + if (!origin || !isAllowedOrigin(origin, allowedOrigins())) + return new Response(null, { status: 403 }); + return new Response(null, { status: 204, headers: corsHeaders(origin) }); +} + +export async function POST(request: Request): Promise { + const origin = request.headers.get("Origin"); + if (!origin || !isAllowedOrigin(origin, allowedOrigins())) + return new Response("Forbidden", { status: 403 }); + const headers = corsHeaders(origin); + + let body: unknown; + try { + body = await request.json(); + } catch { + return new Response("Invalid JSON", { status: 400, headers }); + } + const payload = parseFeedback(body); + if (typeof payload === "string") + return new Response(payload, { status: 400, headers }); + + const { RESEND_API_KEY, FEEDBACK_FROM, FEEDBACK_TO } = process.env; + if (!RESEND_API_KEY || !FEEDBACK_FROM || !FEEDBACK_TO) + return new Response("Server not configured", { status: 500, headers }); + + const result = await sendFeedbackEmail( + payload, + RESEND_API_KEY, + FEEDBACK_FROM, + FEEDBACK_TO, + ); + + if (!result.ok) { + console.error("Resend error", result.status, result.error); + return new Response("Failed to send feedback", { status: 502, headers }); + } + return new Response(null, { status: 204, headers }); +} diff --git a/feedback-api/package.json b/feedback-api/package.json new file mode 100644 index 0000000..284d014 --- /dev/null +++ b/feedback-api/package.json @@ -0,0 +1,8 @@ +{ + "name": "scriptmonkey-feedback-api", + "private": true, + "type": "module", + "engines": { + "node": ">=22" + } +} diff --git a/feedback-api/tests/feedback.test.ts b/feedback-api/tests/feedback.test.ts new file mode 100644 index 0000000..aa48764 --- /dev/null +++ b/feedback-api/tests/feedback.test.ts @@ -0,0 +1,107 @@ +// @vitest-environment node +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + buildEmail, + isAllowedOrigin, + OPTIONS, + POST, + parseFeedback, +} from "../api/feedback"; + +const valid = { message: " Hello\nworld ", version: "1.0.0", userAgent: "UA" }; +const EXT = "chrome-extension://abc"; + +function request(body: unknown, origin = EXT) { + return new Request("https://x/api/feedback", { + method: "POST", + headers: { Origin: origin, "Content-Type": "application/json" }, + body: typeof body === "string" ? body : JSON.stringify(body), + }); +} + +describe("parseFeedback", () => { + it("accepts and trims a minimal payload", () => { + expect(parseFeedback(valid)).toEqual({ ...valid, message: "Hello\nworld" }); + }); + + it.each([ + [null, "Invalid body"], + [{ ...valid, message: " " }, "Message is required"], + [{ ...valid, message: "x".repeat(5001) }, "Message too long"], + [{ ...valid, version: 1 }, "Invalid version"], + [{ ...valid, script: { filename: "a.js" } }, "Invalid script"], + ])("rejects %j", (body, error) => { + expect(parseFeedback(body)).toBe(error); + }); +}); + +describe("isAllowedOrigin", () => { + it("matches exact entries and prefix wildcards", () => { + const allowed = ["https://site.io", "chrome-extension://*"]; + expect(isAllowedOrigin("https://site.io", allowed)).toBe(true); + expect(isAllowedOrigin(EXT, allowed)).toBe(true); + expect(isAllowedOrigin("https://evil.io", allowed)).toBe(false); + expect(isAllowedOrigin(null, allowed)).toBe(false); + }); +}); + +describe("buildEmail", () => { + it("attaches the script as base64", () => { + const email = buildEmail( + { + ...valid, + message: "Bug\ndetails", + script: { filename: "a.user.js", source: "hi" }, + }, + "from@x", + "to@x", + ); + expect(email.subject).toBe("[Scriptmonkey v1.0.0] Bug"); + expect(email.attachments).toEqual([ + { filename: "a.user.js", content: "aGk=" }, + ]); + }); +}); + +describe("handlers", () => { + afterEach(() => { + vi.unstubAllEnvs(); + vi.unstubAllGlobals(); + }); + + function configure() { + vi.stubEnv("ALLOWED_ORIGINS", EXT); + vi.stubEnv("RESEND_API_KEY", "key"); + vi.stubEnv("FEEDBACK_FROM", "from@x"); + vi.stubEnv("FEEDBACK_TO", "to@x"); + const fetchMock = vi.fn(async () => new Response("{}")); + vi.stubGlobal("fetch", fetchMock); + return fetchMock; + } + + it("sends the email via Resend", async () => { + const fetchMock = configure(); + const res = await POST(request(valid)); + expect(res.status).toBe(204); + expect(res.headers.get("Access-Control-Allow-Origin")).toBe(EXT); + expect(fetchMock).toHaveBeenCalledWith( + "https://api.resend.com/emails", + expect.objectContaining({ method: "POST" }), + ); + }); + + it("rejects foreign origins and bad bodies without sending", async () => { + const fetchMock = configure(); + expect((await POST(request(valid, "https://evil.io"))).status).toBe(403); + expect((await POST(request("{nope"))).status).toBe(400); + expect((await POST(request({}))).status).toBe(400); + expect(OPTIONS(request(valid, "https://evil.io")).status).toBe(403); + expect(fetchMock).not.toHaveBeenCalled(); + }); + + it("reports Resend failures as 502", async () => { + configure().mockResolvedValueOnce(new Response("err", { status: 500 })); + vi.spyOn(console, "error").mockImplementation(() => {}); + expect((await POST(request(valid))).status).toBe(502); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 1987dca..6555e7e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -26,6 +26,7 @@ "vite.config.ts", "playwright.config.ts", "e2e", + "feedback-api", "scripts" ], "exclude": ["node_modules"] From 8361b1f6baf44dfa779cc813294d90f6fa9e2697 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mathias=20W=C3=B6=C3=9F?= Date: Sat, 14 Nov 2026 00:39:03 +0100 Subject: [PATCH 2/9] feat: add feedback button to both dashboard and popup --- src/components/FeedbackDialog.css | 70 ++++++++++++++++ src/components/FeedbackDialog.tsx | 132 ++++++++++++++++++++++++++++++ src/components/FeedbackIcon.tsx | 29 +++++++ src/dashboard/App.css | 4 + src/dashboard/App.tsx | 16 ++++ src/popup/App.css | 8 ++ src/popup/App.tsx | 19 +++++ src/utils/feedback.ts | 20 +++++ 8 files changed, 298 insertions(+) create mode 100644 src/components/FeedbackDialog.css create mode 100644 src/components/FeedbackDialog.tsx create mode 100644 src/components/FeedbackIcon.tsx create mode 100644 src/utils/feedback.ts diff --git a/src/components/FeedbackDialog.css b/src/components/FeedbackDialog.css new file mode 100644 index 0000000..f7a9a64 --- /dev/null +++ b/src/components/FeedbackDialog.css @@ -0,0 +1,70 @@ +.feedback-dialog { + margin: auto; + width: min(420px, calc(100vw - 32px)); + max-height: calc(100vh - 32px); + overflow-y: auto; + padding: 20px; + background: var(--surface-elevated); + color: var(--text); + border: 1px solid var(--border); + border-radius: var(--radius); + box-shadow: 0 12px 32px rgba(0, 0, 0, 0.45); +} + +.feedback-dialog::backdrop { + background: var(--backdrop-bg); +} + +.feedback-dialog h3 { + margin-bottom: 12px; + font-size: 14px; + color: var(--text-bold); +} + +.feedback-dialog form { + display: flex; + flex-direction: column; + gap: 10px; +} + +.feedback-dialog textarea, +.feedback-dialog select { + width: 100%; + padding: 8px 10px; + font-size: 12px; + color: var(--text-bold); + background: var(--surface); + border: 1px solid var(--border); + border-radius: 6px; +} + +.feedback-dialog textarea { + resize: vertical; +} + +.feedback-dialog textarea:focus-visible, +.feedback-dialog select:focus-visible { + border-color: var(--border-focus); + outline: none; +} + +.feedback-field { + display: flex; + gap: 8px; + align-items: center; + font-size: 11.5px; +} + +.feedback-field span { + flex-shrink: 0; +} + +.feedback-note { + font-size: 10.5px; + color: var(--muted); +} + +.feedback-error { + font-size: 11px; + color: var(--danger); +} diff --git a/src/components/FeedbackDialog.tsx b/src/components/FeedbackDialog.tsx new file mode 100644 index 0000000..2918395 --- /dev/null +++ b/src/components/FeedbackDialog.tsx @@ -0,0 +1,132 @@ +import type React from "react"; +import { useEffect, useRef, useState } from "react"; +import type { Script } from "../types"; +import { sendFeedback } from "../utils/feedback"; +import "./FeedbackDialog.css"; + +interface Props { + open: boolean; + onClose: () => void; + scripts: Script[]; +} + +type Status = "idle" | "sending" | "sent" | "error"; + +export function FeedbackDialog({ open, onClose, scripts }: Props) { + const dialogRef = useRef(null); + const [message, setMessage] = useState(""); + const [scriptId, setScriptId] = useState(""); + const [status, setStatus] = useState("idle"); + const [error, setError] = useState(""); + + useEffect(() => { + const dialog = dialogRef.current; + if (!dialog) return; + if (open && !dialog.open) dialog.showModal(); + if (!open && dialog.open) dialog.close(); + }, [open]); + + const handleClose = () => { + if (status === "sent") { + setMessage(""); + setScriptId(""); + setStatus("idle"); + } + onClose(); + }; + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + setStatus("sending"); + setError(""); + const script = scripts.find((s) => s.id === scriptId); + try { + await sendFeedback({ + message, + script: script && { filename: script.filename, source: script.source }, + }); + setStatus("sent"); + } catch (err) { + setError(err instanceof Error ? err.message : String(err)); + setStatus("error"); + } + }; + + return ( + +

Send Feedback

+ {status === "sent" ? ( + <> +

Thanks! Your feedback was sent.

+
+ +
+ + ) : ( +
+