diff --git a/_components/Feedback.tsx b/_components/Feedback.tsx deleted file mode 100644 index 6c8bbc537..000000000 --- a/_components/Feedback.tsx +++ /dev/null @@ -1,134 +0,0 @@ -import EditThisPage from "./EditThisPage.tsx"; - -export default function Feedback({ file }: { file: string | undefined }) { - if (!file) { - return <>; - } else { - return ( -
-
-
-
-

- Did you find what you needed? -

- - - - - {!file.includes("[") && } -
- -
- - Privacy policy - -
-
- ); - } -} diff --git a/_includes/doc.tsx b/_includes/doc.tsx index c9c2af803..c60ab4bb4 100644 --- a/_includes/doc.tsx +++ b/_includes/doc.tsx @@ -68,7 +68,7 @@ export default function Doc(data: Lume.Data, helpers: Lume.Helpers) { ); const isLintRule = data.url.startsWith("/lint/rules/"); - // Compute file path used by Feedback component + // Compute file path used by the CopyPage and EditThisPage components const file = isLintRule ? `/lint/rules/${encodeURIComponent(data.title ?? "")}.md` : data.page.sourcePath; @@ -266,7 +266,11 @@ export default function Doc(data: Lume.Data, helpers: Lume.Helpers) { - + {file && !file.includes("[") && ( +
+ +
+ )} {isReference && tocCtx && ( diff --git a/_includes/layout.tsx b/_includes/layout.tsx index 899376115..9cf822a20 100644 --- a/_includes/layout.tsx +++ b/_includes/layout.tsx @@ -121,7 +121,6 @@ export default function Layout(data: Lume.Data) { - diff --git a/deno.json b/deno.json index 4647bae53..776d6b395 100644 --- a/deno.json +++ b/deno.json @@ -17,8 +17,6 @@ "prismjs": "npm:prismjs@1.29.0", "tailwindcss": "npm:tailwindcss@^4.1.11", "@orama/core": "jsr:@orama/core@^1.2.4", - "@octokit/core": "npm:@octokit/core@^5.2.0", - "leo-profanity": "npm:leo-profanity@^1.7.0", "https://cdn.jsdelivr.net/gh/esbuild/deno-esbuild@0.27.0/mod.js": "https://cdn.jsdelivr.net/gh/esbuild/deno-esbuild@0.27.0/wasm.js" }, "tasks": { diff --git a/deno.lock b/deno.lock index dbfbf2701..6a8ad5d32 100644 --- a/deno.lock +++ b/deno.lock @@ -145,7 +145,6 @@ "npm:@duckdb/node-api@*": "2.0.0-r.1", "npm:@mdx-js/mdx@3.1.1": "3.1.1_acorn@8.15.0", "npm:@modelcontextprotocol/sdk@*": "1.32.2_zod@4.6.7", - "npm:@octokit/core@^5.2.0": "5.2.2", "npm:@orama/cuid2@2.2.3": "2.2.3", "npm:@orama/oramacore-events-parser@0.0.5": "0.0.5", "npm:@resvg/resvg-wasm@2.6.2": "2.6.2", @@ -171,7 +170,6 @@ "npm:ico-endec@0.1.6": "0.1.6", "npm:jose@6": "6.2.9", "npm:katex@0.16": "0.16.47", - "npm:leo-profanity@^1.7.0": "1.8.0", "npm:lightningcss-wasm@1.30.1": "1.30.1", "npm:lightningcss-wasm@1.30.2": "1.30.2", "npm:markdown-it-anchor@9": "9.2.0_@types+markdown-it@14.1.2_markdown-it@14.1.0", @@ -846,7 +844,7 @@ "@babel/runtime@7.29.13": { "integrity": "sha512-v+oN26xP4YIlQsbQ/CbTH1WG5m/l/DjKKZNy/Kp3f/AFvbgt7Em/D0FeMM3O2hX0YzeN2M16W8lOpyhIkfCBcQ==" }, - "@better-auth/core@1.7.21_@better-auth+utils@0.5.1_@better-fetch+fetch@1.3.3_better-call@1.4.5__zod@4.6.7_jose@6.2.9_kysely@0.29.8_nanostores@1.5.5": { + "@better-auth/core@1.7.21_@better-auth+utils@0.5.1_@better-fetch+fetch@1.3.3_better-call@1.4.5_jose@6.2.9_kysely@0.29.8_nanostores@1.5.5": { "integrity": "sha512-dHv0Az7hUrnzkvpGG+e/fwlBPWS4+TNr4ruyxQj0ATkBNf3jG2I24J4VNMVNq0kaDygcWW7GnqI1cqMGDFD/xw==", "dependencies": [ "@better-auth/utils", @@ -859,14 +857,14 @@ "zod@4.6.7" ] }, - "@better-auth/drizzle-adapter@1.7.21_@better-auth+core@1.7.21__@better-auth+utils@0.5.1__@better-fetch+fetch@1.3.3__better-call@1.4.5___zod@4.6.7__jose@6.2.9__kysely@0.29.8__nanostores@1.5.5_@better-auth+utils@0.5.1_@better-fetch+fetch@1.3.3_better-call@1.4.5__zod@4.6.7_jose@6.2.9_kysely@0.29.8_nanostores@1.5.5": { + "@better-auth/drizzle-adapter@1.7.21_@better-auth+core@1.7.21_@better-auth+utils@0.5.1_@better-fetch+fetch@1.3.3_better-call@1.4.5_jose@6.2.9_kysely@0.29.8_nanostores@1.5.5": { "integrity": "sha512-fDPl0wjnbvUkSRdwOacjgnlf+NsT7MrXEBm13ga5+l1KZwjeDUvGTkHeUmu85cQEZionCdMw4TjoOqlLTC2Jzg==", "dependencies": [ "@better-auth/core", "@better-auth/utils" ] }, - "@better-auth/kysely-adapter@1.7.21_@better-auth+core@1.7.21__@better-auth+utils@0.5.1__@better-fetch+fetch@1.3.3__better-call@1.4.5___zod@4.6.7__jose@6.2.9__kysely@0.29.8__nanostores@1.5.5_@better-auth+utils@0.5.1_kysely@0.29.8_@better-fetch+fetch@1.3.3_better-call@1.4.5__zod@4.6.7_jose@6.2.9_nanostores@1.5.5": { + "@better-auth/kysely-adapter@1.7.21_@better-auth+core@1.7.21_@better-auth+utils@0.5.1_kysely@0.29.8_@better-fetch+fetch@1.3.3_better-call@1.4.5_jose@6.2.9_nanostores@1.5.5": { "integrity": "sha512-FDggDRhtb6/w74H5QfawOaK4EqGYVEtKqBFDoN6M2mcjAnmO0j5kw6YoVonIWO0G+CvnkqP/K5UHUy0eqxQ9rA==", "dependencies": [ "@better-auth/core", @@ -877,14 +875,14 @@ "kysely" ] }, - "@better-auth/memory-adapter@1.7.21_@better-auth+core@1.7.21__@better-auth+utils@0.5.1__@better-fetch+fetch@1.3.3__better-call@1.4.5___zod@4.6.7__jose@6.2.9__kysely@0.29.8__nanostores@1.5.5_@better-auth+utils@0.5.1_@better-fetch+fetch@1.3.3_better-call@1.4.5__zod@4.6.7_jose@6.2.9_kysely@0.29.8_nanostores@1.5.5": { + "@better-auth/memory-adapter@1.7.21_@better-auth+core@1.7.21_@better-auth+utils@0.5.1_@better-fetch+fetch@1.3.3_better-call@1.4.5_jose@6.2.9_kysely@0.29.8_nanostores@1.5.5": { "integrity": "sha512-3BgGf/+AyK/QQ8S1Jg6LrXH+lpgSD1/+UJAr3WKPdNtT99u/+HchIQ2YPYwsIKQMVhK4D/oannnojc/ReL7omw==", "dependencies": [ "@better-auth/core", "@better-auth/utils" ] }, - "@better-auth/mongo-adapter@1.7.21_@better-auth+core@1.7.21__@better-auth+utils@0.5.1__@better-fetch+fetch@1.3.3__better-call@1.4.5___zod@4.6.7__jose@6.2.9__kysely@0.29.8__nanostores@1.5.5_@better-auth+utils@0.5.1_mongodb@7.5.0_@better-fetch+fetch@1.3.3_better-call@1.4.5__zod@4.6.7_jose@6.2.9_kysely@0.29.8_nanostores@1.5.5": { + "@better-auth/mongo-adapter@1.7.21_@better-auth+core@1.7.21_@better-auth+utils@0.5.1_mongodb@7.5.0_@better-fetch+fetch@1.3.3_better-call@1.4.5_jose@6.2.9_kysely@0.29.8_nanostores@1.5.5": { "integrity": "sha512-WEbZtZ6JRhXM4LglulQBvG/Sx+JQdElG8q7j6ebbMSCEqfnk9fSx0sP8OvZ/amdEeIguCKx7sk7H7SFF7o+UJw==", "dependencies": [ "@better-auth/core", @@ -895,14 +893,14 @@ "mongodb" ] }, - "@better-auth/prisma-adapter@1.7.21_@better-auth+core@1.7.21__@better-auth+utils@0.5.1__@better-fetch+fetch@1.3.3__better-call@1.4.5___zod@4.6.7__jose@6.2.9__kysely@0.29.8__nanostores@1.5.5_@better-auth+utils@0.5.1_@better-fetch+fetch@1.3.3_better-call@1.4.5__zod@4.6.7_jose@6.2.9_kysely@0.29.8_nanostores@1.5.5": { + "@better-auth/prisma-adapter@1.7.21_@better-auth+core@1.7.21_@better-auth+utils@0.5.1_@better-fetch+fetch@1.3.3_better-call@1.4.5_jose@6.2.9_kysely@0.29.8_nanostores@1.5.5": { "integrity": "sha512-wP+4bdlXoL6gVrRACJAbb9RvZOW6Z3h066R3k07w/NPUO3P2KL+RQUOu9S0yVqTjUyhEetzHEl1ugCqPY0ge2g==", "dependencies": [ "@better-auth/core", "@better-auth/utils" ] }, - "@better-auth/telemetry@1.7.21_@better-auth+core@1.7.21__@better-auth+utils@0.5.1__@better-fetch+fetch@1.3.3__better-call@1.4.5___zod@4.6.7__jose@6.2.9__kysely@0.29.8__nanostores@1.5.5_@better-auth+utils@0.5.1_@better-fetch+fetch@1.3.3_better-call@1.4.5__zod@4.6.7_jose@6.2.9_kysely@0.29.8_nanostores@1.5.5": { + "@better-auth/telemetry@1.7.21_@better-auth+core@1.7.21_@better-auth+utils@0.5.1_@better-fetch+fetch@1.3.3_better-call@1.4.5_jose@6.2.9_kysely@0.29.8_nanostores@1.5.5": { "integrity": "sha512-7haA957hu3JzVzEFK1Li5+Sc/fzEjoevVlo9EKSfDgiLhKVvtEWZSRmNcNRZ+n7KwDUiG8YnUE3+O1brkrOQEQ==", "dependencies": [ "@better-auth/core", @@ -1387,62 +1385,6 @@ "@noble/hashes@2.4.0": { "integrity": "sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==" }, - "@octokit/auth-token@4.0.0": { - "integrity": "sha512-tY/msAuJo6ARbK6SPIxZrPBms3xPbfwBrulZe0Wtr/DIY9lje2HeV1uoebShn6mx7SjCHif6EjMvoREj+gZ+SA==" - }, - "@octokit/core@5.2.2": { - "integrity": "sha512-/g2d4sW9nUDJOMz3mabVQvOGhVa4e/BN/Um7yca9Bb2XTzPPnfTWHWQg+IsEYO7M3Vx+EXvaM/I2pJWIMun1bg==", - "dependencies": [ - "@octokit/auth-token", - "@octokit/graphql", - "@octokit/request", - "@octokit/request-error", - "@octokit/types", - "before-after-hook", - "universal-user-agent" - ] - }, - "@octokit/endpoint@9.0.6": { - "integrity": "sha512-H1fNTMA57HbkFESSt3Y9+FBICv+0jFceJFPWDePYlR/iMGrwM5ph+Dd4XRQs+8X+PUFURLQgX9ChPfhJ/1uNQw==", - "dependencies": [ - "@octokit/types", - "universal-user-agent" - ] - }, - "@octokit/graphql@7.1.1": { - "integrity": "sha512-3mkDltSfcDUoa176nlGoA32RGjeWjl3K7F/BwHwRMJUW/IteSa4bnSV8p2ThNkcIcZU2umkZWxwETSSCJf2Q7g==", - "dependencies": [ - "@octokit/request", - "@octokit/types", - "universal-user-agent" - ] - }, - "@octokit/openapi-types@24.2.0": { - "integrity": "sha512-9sIH3nSUttelJSXUrmGzl7QUBFul0/mB8HRYl3fOlgHbIWG+WnYDXU3v/2zMtAvuzZ/ed00Ei6on975FhBfzrg==" - }, - "@octokit/request-error@5.1.1": { - "integrity": "sha512-v9iyEQJH6ZntoENr9/yXxjuezh4My67CBSu9r6Ve/05Iu5gNgnisNWOsoJHTP6k0Rr0+HQIpnH+kyammu90q/g==", - "dependencies": [ - "@octokit/types", - "deprecation", - "once" - ] - }, - "@octokit/request@8.4.1": { - "integrity": "sha512-qnB2+SY3hkCmBxZsR/MPCybNmbJe4KAlfWErXq+rBKkQJlbjdJeS85VI9r8UqeLYLvnAenU8Q1okM/0MBsAGXw==", - "dependencies": [ - "@octokit/endpoint", - "@octokit/request-error", - "@octokit/types", - "universal-user-agent" - ] - }, - "@octokit/types@13.10.0": { - "integrity": "sha512-ifLaO34EbbPj0Xgro4G5lP5asESjwHracYJvVaPIyXMuiuXLlhic3S47cBdTb+jfODkTE5YtGCLt3Ay3+J97sA==", - "dependencies": [ - "@octokit/openapi-types" - ] - }, "@opentelemetry/api@1.10.0": { "integrity": "sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==" }, @@ -2018,9 +1960,6 @@ "base64-js@1.5.1": { "integrity": "sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==" }, - "before-after-hook@2.2.3": { - "integrity": "sha512-NzUnlZexiaH/46WDhANlyR2bXRopNg4F/zuSA3OpZnllCUgRaOF2znDioDWrmbNVsuZk6l9pMquQB38cfBZwkQ==" - }, "better-auth@1.7.21_mongodb@7.5.0": { "integrity": "sha512-KMcZWuCaNAMs3JNrZeKoEi+Ym5ChkBcZ0YH6jK3hvj6Djz04ZtuiXQfEXNXG8Nqp9+ByYo+N/ckrgVUXxFrVPw==", "dependencies": [ @@ -2274,9 +2213,6 @@ "depd@2.0.0": { "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==" }, - "deprecation@2.3.1": { - "integrity": "sha512-xmHIy4F3scKVwMsQ4WnVaS8bHOx0DmVwRywosKhaILI0ywMDWPtBSku2HNxRvF7jtwDRsoEwYQSfbxj8b7RlJQ==" - }, "dequal@2.0.3": { "integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==" }, @@ -2590,9 +2526,6 @@ "forwarded@0.2.0": { "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==" }, - "french-badwords-list@1.0.7": { - "integrity": "sha512-H1ziKs2PJh2+UXZ9oCGJ/rRQpsI9NBykGf2Sc7WaKaj1OnWFuBXfsvANTdRcfVmOghGQaUmRyZ1hJOPbDpy04Q==" - }, "fresh@0.5.2": { "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==" }, @@ -2916,13 +2849,6 @@ "dayjs" ] }, - "leo-profanity@1.8.0": { - "integrity": "sha512-TATupbZhT3oFCtsiEXzgXcLvW6cDPhDtN+0yQAibjwBdSw3WJFLKM0DZ18eEW8KeFTT10x8gCP+DDZz0cI4Bfg==", - "optionalDependencies": [ - "french-badwords-list", - "russian-bad-words" - ] - }, "lightningcss-android-arm64@1.30.2": { "integrity": "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A==", "os": ["android"], @@ -4060,9 +3986,6 @@ "path-to-regexp@8.4.2" ] }, - "russian-bad-words@0.5.0": { - "integrity": "sha512-euNvEYki6iYYpkNbeudW+lEMMYGEmN7EBwVF8ezlbv0bZoQpVYB7W10cCeUIGV7Ed50sJynLQ0c559q5iI0ejQ==" - }, "safe-buffer@5.2.1": { "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==" }, @@ -4472,9 +4395,6 @@ "unist-util-visit-parents" ] }, - "universal-user-agent@6.0.1": { - "integrity": "sha512-yCzhz6FN2wU1NiiQRogkTQszlQSlpWaw8SvVegAc+bDxbzHgh1vX8uIe8OYyMH6DwH+sdTJsgMl36+mSMdRJIQ==" - }, "unpipe@1.0.0": { "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==" }, @@ -5211,9 +5131,7 @@ "jsr:@std/media-types@^1.0.3", "jsr:@std/path@^1.0.8", "jsr:@std/yaml@^1.0.11", - "npm:@octokit/core@^5.2.0", "npm:googleapis@144", - "npm:leo-profanity@^1.7.0", "npm:prismjs@1.29.0", "npm:tailwindcss@^4.1.11" ] diff --git a/js/feedback.ts b/js/feedback.ts deleted file mode 100644 index 90864647f..000000000 --- a/js/feedback.ts +++ /dev/null @@ -1,102 +0,0 @@ -// This runs in the browser -// deno-lint-ignore-file no-window -import type { FeedbackSubmission } from "../types.ts"; - -// Keep in sync with MAX_COMMENT_LENGTH in middleware/functions/feedback.ts -// and the maxlength on the textarea in _components/Feedback.tsx -const MAX_COMMENT_LENGTH = 2000; - -let lastFeedbackItemId: string | null = null; -const feedbackYes = document.getElementById("feedback-yes"); -const feedbackNo = document.getElementById("feedback-no"); -const feedbackForm = document.getElementById("feedback-form"); -const feedbackSection = document.getElementById("feedback-section"); -const feedbackComment = document.getElementById( - "feedback-comment", -) as HTMLTextAreaElement | null; -const feedbackCommentCount = document.getElementById("feedback-comment-count"); - -feedbackComment?.addEventListener("input", () => { - const length = feedbackComment.value.length; - if (feedbackCommentCount) { - feedbackCommentCount.textContent = `${length} / ${MAX_COMMENT_LENGTH}`; - // Highlight the counter once the comment reaches the limit - const atLimit = length >= MAX_COMMENT_LENGTH; - feedbackCommentCount.classList.toggle("text-red-600", atLimit); - feedbackCommentCount.classList.toggle("dark:text-red-400", atLimit); - feedbackCommentCount.classList.toggle("text-gray-600", !atLimit); - feedbackCommentCount.classList.toggle("dark:text-gray-400", !atLimit); - } -}); - -feedbackYes?.addEventListener("click", () => { - sendFeedback({ - sentiment: "yes", - }); -}); - -feedbackNo?.addEventListener("click", () => { - sendFeedback({ - sentiment: "no", - }); -}); - -feedbackForm?.addEventListener("submit", async (event) => { - event.preventDefault(); - const formData = new FormData(feedbackForm as HTMLFormElement); - const form = Object.fromEntries(formData.entries()); - const ok = await sendFeedback({ - sentiment: form["feedback-vote"] as "yes" | "no", - comment: form["feedback-comment"] as string, - contact: form["feedback-contact"] as string, - }); - if (feedbackSection) { - feedbackSection.innerHTML = ok - ? "

Thank you for helping make the Deno docs awesome!

" - : "

Sorry, something went wrong sending your feedback. Please try again later.

"; - } -}); - -// "Request a new guide" box on the Examples landing page; reuses the -// feedback endpoint, which files a GitHub issue when a comment is present. -const guideRequestForm = document.getElementById("guide-request-form"); -const guideRequestBox = document.getElementById("guide-request-box"); - -guideRequestForm?.addEventListener("submit", (event) => { - event.preventDefault(); - const formData = new FormData(guideRequestForm as HTMLFormElement); - const form = Object.fromEntries(formData.entries()); - const comment = (form["guide-request-comment"] as string)?.trim(); - if (!comment) return; - sendFeedback({ - sentiment: "no", - comment: `[Guide request] ${comment}`, - contact: form["guide-request-contact"] as string, - }); - if (guideRequestBox) { - guideRequestBox.innerHTML = - "

Thanks! Your request has been filed — we'll take a look.

"; - } -}); - -async function sendFeedback(feedback: Partial) { - feedback.path = feedback.path || new URL(window.location.href).pathname; - feedback.id = lastFeedbackItemId ? lastFeedbackItemId : null; - - const result = await fetch("/_api/send-feedback", { - method: "POST", - headers: { - "Content-Type": "application/json", - }, - body: JSON.stringify(feedback), - }); - - const responseBody = await result.json(); - lastFeedbackItemId = responseBody.id; - - if (!result.ok) { - console.error("Failed to send feedback", responseBody); - } - - return result.ok; -} diff --git a/middleware/functions/feedback.ts b/middleware/functions/feedback.ts deleted file mode 100644 index 546804a88..000000000 --- a/middleware/functions/feedback.ts +++ /dev/null @@ -1,533 +0,0 @@ -import { Octokit } from "@octokit/core"; -import profanity from "leo-profanity"; -import type { FeedbackSubmission } from "../../types.ts"; - -// GitHub API configuration -const githubToken = Deno.env.get("GITHUB_FEEDBACK_TOKEN"); -const githubRepo = Deno.env.get("GITHUB_FEEDBACK_REPO") || "denoland/docs"; -const [owner, repo] = githubRepo.split("/"); -const projectId = "PVT_kwDOAoGdk84Aj-nW"; - -// Check if the API key is set -const enableFeedbackMiddleware = !!githubToken; - -// Profanity filter configuration -const enableProfanityFilter = - (Deno.env.get("FEEDBACK_PROFANITY_FILTER") ?? "true").toLowerCase() !== - "false"; -const customProfanityCSV = Deno.env.get("FEEDBACK_PROFANITY_WORDS") || ""; // optional comma-separated words -// Initialize profanity dictionary once -if (enableProfanityFilter) { - // Use English dictionary by default - profanity.loadDictionary(); - if (customProfanityCSV.trim()) { - const extra = customProfanityCSV.split(",").map((w) => w.trim()).filter( - Boolean, - ); - if (extra.length) profanity.add(extra); - } -} - -// Rate limiting configuration -const RATE_LIMIT_WINDOW = 60 * 60 * 1000; // 1 hour in milliseconds -const MAX_REQUESTS_PER_IP = 5; // Max 5 feedback submissions per hour per IP -const MAX_REQUESTS_PER_PATH = 10; // Max 10 feedback submissions per hour per path -const rateLimitStore = new Map(); -// Allow disabling rate limits for local testing -const disableRateLimiting = - (Deno.env.get("FEEDBACK_DISABLE_RATELIMIT") ?? "false").toLowerCase() === - "true"; - -// Field length constraints (single source of truth) -const MAX_PATH_LENGTH = 500; -const MAX_COMMENT_LENGTH = 2000; -const MAX_CONTACT_LENGTH = 256; - -// Suspicious user agent patterns -const SUSPICIOUS_USER_AGENTS = [ - /curl/i, - /wget/i, - /postman/i, - /python/i, - /node/i, - /bot/i, - /crawler/i, - /scraper/i, -]; - -// Allowed origins for CORS (add your actual domains) -const ALLOWED_ORIGINS = [ - "https://docs.deno.com", - "https://deno.com", - "http://localhost:3000", // For development - "http://localhost:8000", // For development -]; - -// Helpers -function checkRateLimit(identifier: string, maxRequests: number): boolean { - const now = Date.now(); - const current = rateLimitStore.get(identifier); - - if (!current || now > current.resetTime) { - rateLimitStore.set(identifier, { - count: 1, - resetTime: now + RATE_LIMIT_WINDOW, - }); - return true; - } - - if (current.count >= maxRequests) { - return false; - } - - current.count++; - return true; -} - -function getClientIP(req: Request): string { - return ( - req.headers.get("cf-connecting-ip") || - req.headers.get("x-forwarded-for") || - req.headers.get("x-real-ip") || - "unknown" - ); -} - -// Minimal JSON response helper with CORS -function jsonResponse( - data: unknown, - init?: ResponseInit & { corsHeaders?: Record }, -): Response { - const baseCors = { - "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Methods": "POST, OPTIONS", - "Access-Control-Allow-Headers": "Content-Type, Authorization", - "Access-Control-Max-Age": "86400", - } as const; - return new Response(JSON.stringify(data), { - status: init?.status ?? 200, - headers: { - ...baseCors, - ...(init?.corsHeaders ?? {}), - "Content-Type": "application/json", - }, - }); -} - -// Validate request origin and headers -function validateRequest(req: Request): { valid: boolean; reason?: string } { - const userAgent = req.headers.get("user-agent") || ""; - const origin = req.headers.get("origin"); - const referer = req.headers.get("referer"); - - // Check for suspicious user agents - if (SUSPICIOUS_USER_AGENTS.some((pattern) => pattern.test(userAgent))) { - return { valid: false, reason: "Suspicious user agent detected" }; - } - - // Check origin if present (for CORS requests) - if (origin && !ALLOWED_ORIGINS.includes(origin)) { - return { valid: false, reason: "Origin not allowed" }; - } - - // Check referer if no origin (for non-CORS requests) - if (!origin && referer) { - const isValidReferer = ALLOWED_ORIGINS.some((allowedOrigin) => - referer.startsWith(allowedOrigin) - ); - if (!isValidReferer) { - return { valid: false, reason: "Invalid referer" }; - } - } - - return { valid: true }; -} - -// Enhanced content validation -function validateFeedbackContent( - submission: FeedbackSubmission, -): { valid: boolean; reason?: string } { - const { path, sentiment, comment, contact } = submission; - - // Basic field validation - if (!path || typeof path !== "string" || path.length > MAX_PATH_LENGTH) { - return { valid: false, reason: "Invalid path" }; - } - - if (!sentiment || !["yes", "no"].includes(sentiment)) { - return { valid: false, reason: "Invalid sentiment" }; - } - - // If comment is provided, validate it - if (comment) { - if (typeof comment !== "string") { - return { valid: false, reason: "Invalid comment format" }; - } - - if (comment.length < 3) { - return { valid: false, reason: "Comment too short" }; - } - - if (comment.length > MAX_COMMENT_LENGTH) { - return { valid: false, reason: "Comment too long" }; - } - - if (enableProfanityFilter && profanity.check(comment)) { - return { - valid: false, - reason: "Comment contains inappropriate language", - }; - } - } - - // If contact is provided, validate it - if (contact) { - if (typeof contact !== "string" || contact.length > MAX_CONTACT_LENGTH) { - return { valid: false, reason: "Invalid contact format" }; - } - } - - return { valid: true }; -} - -// Create Octokit instance with GraphQL support -const octokit = new Octokit({ - auth: githubToken, -}); - -// Clean up GitHub username by removing @ if present -function cleanGitHubUsername(username: string | undefined): string | undefined { - if (!username) return undefined; - return username.startsWith("@") ? username.substring(1) : username; -} - -// Add issue to GitHub Project -async function addIssueToProject(issueNodeId: string) { - console.log( - `Attempting to add issue (${issueNodeId}) to project (${projectId})`, - ); - - try { - // The GraphQL mutation for adding an item to a project - const mutation = ` - mutation AddIssueToProject($projectId: ID!, $contentId: ID!) { - addProjectV2ItemById(input: { - projectId: $projectId - contentId: $contentId - }) { - item { - id - } - } - } - `; - - // Execute the GraphQL mutation with variables - const response = await octokit.graphql(mutation, { - projectId: projectId, - contentId: issueNodeId, - headers: { - "X-GitHub-Api-Version": "2022-11-28", - Accept: "application/vnd.github.v3+json", - }, - }); - - console.log("Successfully added issue to project."); - return response; - } catch (error) { - console.error("Failed to add issue to project:", error); - // Log the specific error message for debugging - if (error instanceof Error) { - console.error("Error message:", error.message); - } - } -} - -// Create GitHub issue for feedback only when comments are provided -const upsertFeedbackIssue = async ( - { path, sentiment, comment, contact, id }: FeedbackSubmission, -) => { - const cleanedContact = cleanGitHubUsername(contact); - - // Record basic sentiment without creating GitHub issue if no comment - if (!comment || comment.trim() === "") { - console.log( - `Feedback received for ${path}: ${sentiment} (no comment, no GitHub issue created)`, - ); - return { id: null }; // Return null ID as no GitHub issue was created - } - - // If comment exists, create or update GitHub issue - if (id) { - // If an ID exists, it means we're updating an existing issue - if (enableProfanityFilter && comment && profanity.check(comment)) { - throw new Error("Comment rejected due to inappropriate language"); - } - const commentBody = ` -Additional feedback: -${comment ? `\n> ${comment}` : "No additional comment provided"} -${cleanedContact ? `\n**GitHub User:** @${cleanedContact}` : ""} -`; - - try { - await octokit.request( - "POST /repos/{owner}/{repo}/issues/{issue_number}/comments", - { - owner, - repo, - issue_number: parseInt(id), - body: commentBody, - headers: { - "X-GitHub-Api-Version": "2022-11-28", - }, - }, - ); - - return { id }; - } catch (error) { - console.error("GitHub API error (add comment):", error); - throw error; - } - } else { - // Create a new issue - if (enableProfanityFilter && comment && profanity.check(comment)) { - throw new Error("Comment rejected due to inappropriate language"); - } - const title = `Feedback: ${path} - ${ - sentiment === "yes" ? "Positive" : "Needs Improvement" - }`; - - const body = ` -## Documentation Feedback - -**Path:** [${path}](https://docs.deno.com${path}) -**Helpful:** ${sentiment === "yes" ? "Yes ✅" : "No ❌"} - -${comment ? `**Feedback:**\n> ${comment}` : "No additional comment provided"} -${cleanedContact ? `\n**GitHub User:** @${cleanedContact}` : ""} - ---- -*This issue was automatically created from the documentation feedback system.* -`; - - try { - // Define labels explicitly and ensure they are exactly as defined in GitHub - const labelNames = []; - - // Add sentiment label - if (sentiment === "yes") { - labelNames.push("positive"); - } else { - labelNames.push("needs-improvement"); - } - - // Always add a feedback label - labelNames.push("feedback"); - - console.log( - `Creating issue with labels: ${labelNames.join(", ")}`, - ); - - // Create the issue with specified labels - const response = await octokit.request( - "POST /repos/{owner}/{repo}/issues", - { - owner, - repo, - title, - body, - labels: labelNames, - headers: { - "X-GitHub-Api-Version": "2022-11-28", - }, - }, - ); - - console.log(`Created GitHub issue #${response.data.number} for ${path}`); - - // Let's also verify if the issue was created with labels - if (response.data.labels && response.data.labels.length > 0) { - const labelNames = - (response.data.labels as Array) - .map((l) => typeof l === "string" ? l : l.name) - .filter(Boolean) - .join(", "); - console.log(`Issue created with labels: ${labelNames}`); - } else { - console.warn("Issue created but no labels were attached"); - - // Try adding labels in a separate request if they weren't added initially - try { - await octokit.request( - "POST /repos/{owner}/{repo}/issues/{issue_number}/labels", - { - owner, - repo, - issue_number: response.data.number, - labels: labelNames, - headers: { - "X-GitHub-Api-Version": "2022-11-28", - }, - }, - ); - console.log("Labels added in separate request"); - } catch (labelError) { - console.error( - "Failed to add labels in separate request:", - labelError, - ); - } - } - - // Verify we have the node_id before attempting to add to project - if (response.data.node_id) { - console.log(`Issue node_id: ${response.data.node_id}`); - try { - await addIssueToProject(response.data.node_id); - } catch (projectError) { - console.error( - "Project integration failed but issue was created:", - projectError, - ); - } - } else { - console.error("Missing node_id in GitHub response:", response.data); - } - - return { id: response.data.number }; - } catch (error) { - console.error("GitHub API error (create issue):", error); - throw error; - } - } -}; - -export default async function feedbackRequestHandler( - req: Request, -): Promise { - // Handle preflight requests - if (req.method === "OPTIONS") { - return new Response(null, { - status: 204, - headers: { - "Access-Control-Allow-Origin": "*", - "Access-Control-Allow-Methods": "POST, OPTIONS", - "Access-Control-Allow-Headers": "Content-Type, Authorization", - "Access-Control-Max-Age": "86400", - }, - }); - } - - // Only allow POST requests - if (req.method !== "POST") { - return jsonResponse({ error: "Method not allowed" }, { status: 405 }); - } - - if (!enableFeedbackMiddleware) { - return jsonResponse({ error: "Feedback API is not enabled" }, { - status: 500, - }); - } - - // Get client IP for rate limiting - const clientIP = getClientIP(req); - - // Validate request origin and headers - const requestValidation = validateRequest(req); - if (!requestValidation.valid) { - console.warn( - `Request blocked: ${requestValidation.reason} from IP: ${clientIP}`, - ); - return jsonResponse({ - error: "Request validation failed", - reason: requestValidation.reason, - }, { status: 403 }); - } - - // Check IP-based rate limiting - if ( - !disableRateLimiting && - !checkRateLimit(`ip:${clientIP}`, MAX_REQUESTS_PER_IP) - ) { - console.warn(`Rate limit exceeded for IP: ${clientIP}`); - return jsonResponse({ - error: "Too many requests", - message: "Please wait before submitting more feedback", - }, { status: 429, corsHeaders: { "Retry-After": "3600" } }); - } - - let submission: FeedbackSubmission; - - try { - submission = await req.json() as FeedbackSubmission; - } catch (error) { - return jsonResponse({ - error: "Invalid JSON payload", - details: error instanceof Error ? error.message : String(error), - }, { status: 400 }); - } - - // Validate feedback content - const contentValidation = validateFeedbackContent(submission); - if (!contentValidation.valid) { - console.warn( - `Content validation failed: ${contentValidation.reason} from IP: ${clientIP}`, - ); - return jsonResponse({ - error: "Content validation failed", - reason: contentValidation.reason, - }, { status: 400 }); - } - - const { path, sentiment, comment, contact, id } = submission; - - // Check path-based rate limiting - if ( - !disableRateLimiting && - !checkRateLimit(`path:${path}`, MAX_REQUESTS_PER_PATH) - ) { - console.warn(`Path rate limit exceeded for: ${path} from IP: ${clientIP}`); - return jsonResponse({ - error: "Too many requests for this page", - message: "This page has received too much feedback recently", - }, { status: 429, corsHeaders: { "Retry-After": "3600" } }); - } - - // Cap data at sensible max lengths (already validated above, but extra safety) - const contactCapped = contact && contact.length > MAX_CONTACT_LENGTH - ? contact.slice(0, MAX_CONTACT_LENGTH) - : contact; - - const commentCapped = comment && comment.length > MAX_COMMENT_LENGTH - ? comment.slice(0, MAX_COMMENT_LENGTH) - : comment; - - try { - const response = await upsertFeedbackIssue({ - path: path, - sentiment: sentiment, - comment: commentCapped, - contact: contactCapped, - id: id, - }); - - if (response.id) { - console.log( - `GitHub issue created/updated successfully from IP: ${clientIP}`, - ); - } else { - console.log( - `Feedback recorded without GitHub issue from IP: ${clientIP}`, - ); - } - - return jsonResponse({ success: true, id: response.id }); - } catch (error) { - console.error(`GitHub issue creation failed from IP: ${clientIP}:`, error); - const errorMessage = error instanceof Error ? error.message : String(error); - return jsonResponse({ - error: "Failed to process feedback", - details: errorMessage, - }, { status: 500 }); - } -} diff --git a/middleware/functions/routes.ts b/middleware/functions/routes.ts index 936a0e056..cdc92be36 100644 --- a/middleware/functions/routes.ts +++ b/middleware/functions/routes.ts @@ -1,8 +1,6 @@ import type { RequestHandler } from "lume/core/server.ts"; import healthRequestHandler from "./health.ts"; -import feedbackRequestHandler from "./feedback.ts"; export default { "/_api/health": healthRequestHandler, - "/_api/send-feedback": feedbackRequestHandler, } satisfies Record; diff --git a/style.css b/style.css index 738585689..eb5ce763d 100644 --- a/style.css +++ b/style.css @@ -1188,23 +1188,6 @@ position-try-fallbacks: flip-inline; } - #feedback-no:focus + label, - #feedback-yes:focus + label { - @apply shadow-[inset_0_0_0_1px]; - } - - #feedback-no:checked + label { - @apply bg-red-400 dark:bg-red-600; - } - - #feedback-yes:checked + label { - @apply bg-green-400 dark:bg-green-600; - } - - #feedback-more label { - @apply inline-block text-sm; - } - .learning-list-item { @apply leading-7 mb-1; } @@ -1986,14 +1969,6 @@ width: 100%; overflow: scroll; } - - #feedback-form__content:has(input[type="radio"]:checked) { - grid-template-rows: max-content 1fr; - - #feedback-more { - @apply flex flex-col gap-2; - } - } } /** diff --git a/types.ts b/types.ts index 6c3efadee..1632cad10 100644 --- a/types.ts +++ b/types.ts @@ -81,14 +81,6 @@ export interface TableOfContentsItem { children: TableOfContentsItem[]; } -export interface FeedbackSubmission { - path: string; - sentiment: "yes" | "no"; - comment?: string; - contact?: string; // Now represents GitHub username instead of email - id?: string | null; -} - export interface GoogleSheetsUpdateResponse { updates: { updatedRange: string;