diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 0846feb6..9c545add 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -239,6 +239,12 @@ With `DOCS_ANALYTICS` on (coder.com's consent manager and tag manager, `apps/doc Each vendor is named by origin except jsDelivr, a public CDN for any npm package, which is named only by the one package directory its tag loads (`https://cdn.jsdelivr.net/npm/hockeystack@latest/`). The router applies that policy to archive responses when its own `DOCS_ANALYTICS` is on; `apps/docs/vercel.json`, which cannot vary by environment, keeps the policy above. Widening `script-src` this way is a security decision and needs sign-off before the flag is turned on anywhere. +Both search dialogs send HockeyStack's `Docs Search` goal with a `search_term` property, through `useSearchGoal` in `packages/docs-next/src/search-analytics.ts`. +It sends a term once, after a 1-second pause in typing or at once when a result is selected, and only while the dialog is open, for a term that returned at least one result, and when the reader has accepted analytics consent (`window.Osano.cm.getConsent().ANALYTICS === "ACCEPT"`, failing closed on anything else). +`searchGoalTerm` drops a term that is empty, longer than 100 characters, contains a run of 20 or more characters without spaces, or contains an email address, and it runs on every send, so a slowly typed term stops going out once it takes a secret's shape; it never truncates. +The call is a no-op until the tag has loaded, and a tag of another shape or one that throws is ignored. +The Osano API shape is only what the consent bootstrap in `packages/docs-config/src/analytics.ts` already reads; it has not been checked against Osano's documentation. +The goal and property names must match the goal set up in HockeyStack. Hardening path, not yet taken: the inline scripts in a static export are fixed at build time, so `csp:check` could emit their SHA-256 hashes and the policy could name them in place of `'unsafe-inline'`. That makes the policy a real barrier to injected inline scripts at the cost of regenerating the header on every build and keeping the router's archive headers in step per version. diff --git a/packages/docs-next/src/hybrid-search.test.tsx b/packages/docs-next/src/hybrid-search.test.tsx index 9f92cdea..8c903d12 100644 --- a/packages/docs-next/src/hybrid-search.test.tsx +++ b/packages/docs-next/src/hybrid-search.test.tsx @@ -1,12 +1,14 @@ import assert from "node:assert/strict"; -import { afterEach, test } from "node:test"; +import { type TestContext, afterEach, test } from "node:test"; import type { SortedResult } from "fumadocs-core/search"; import { FrameworkProvider } from "fumadocs-core/framework"; import { type MetaData, type VirtualFile, loader } from "fumadocs-core/source"; import { act, createElement } from "react"; import { createRoot } from "react-dom/client"; +import { stubHockeyStack } from "../test/hockeystack.js"; import { CORPUS_PARAGRAPHS, FORBIDDEN_ELEMENTS } from "../test/search-xss.js"; import HybridSearchDialog, { hybridSearchClient, preloadSemanticIndex } from "./hybrid-search.js"; +import { SEARCH_GOAL_DELAY_MS } from "./search-analytics.js"; import { createDocsSearchRoute } from "./search.js"; import type { DocsPageData } from "./types.js"; @@ -191,3 +193,63 @@ test("search keeps keyword and semantic hits to the product it is given", async assert.deepEqual(await pages("coder"), ["/install"], `semantic: ${semantic}`); } }); + +async function typeInto(t: TestContext, terms: string[], closeAfterTyping = false) { + serve({ "/api/search": await corpusIndex() }); + const warn = console.warn; + console.warn = () => {}; + const container = document.createElement("div"); + document.body.append(container); + const root = createRoot(container); + t.after(async () => { + console.warn = warn; + await act(async () => root.unmount()); + container.remove(); + }); + const render = (open: boolean) => + act(async () => { + root.render( + "/"} + useRouter={() => ({ push() {}, replace() {}, refresh() {}, prefetch() {} }) as never} + useParams={() => ({})} + > + {}} /> + , + ); + }); + await render(true); + const input = document.querySelector('[role="dialog"] input'); + assert.ok(input, "expected the search input to render"); + for (const value of terms) { + await act(async () => { + Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, "value")?.set?.call(input, value); + input.dispatchEvent(new Event("input", { bubbles: true })); + }); + } + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, 300)); + }); + if (closeAfterTyping) await render(false); + await act(async () => { + await new Promise((resolve) => setTimeout(resolve, SEARCH_GOAL_DELAY_MS + 100)); + }); +} + +test("the hybrid dialog sends one HockeyStack goal for a settled search that has results", async (t) => { + const goals = stubHockeyStack(t); + await typeInto(t, ["w", "work", "workspace"]); + assert.deepEqual(goals, [["Docs Search", { search_term: "workspace" }]]); +}); + +test("the hybrid dialog sends no goal for a search with no results", async (t) => { + const goals = stubHockeyStack(t); + await typeInto(t, ["qzxqzx"]); + assert.deepEqual(goals, []); +}); + +test("the hybrid dialog sends no goal for a search dismissed before the delay ends", async (t) => { + const goals = stubHockeyStack(t); + await typeInto(t, ["workspace"], true); + assert.deepEqual(goals, []); +}); diff --git a/packages/docs-next/src/hybrid-search.tsx b/packages/docs-next/src/hybrid-search.tsx index 87c88909..06114697 100644 --- a/packages/docs-next/src/hybrid-search.tsx +++ b/packages/docs-next/src/hybrid-search.tsx @@ -14,6 +14,7 @@ import { } from "fumadocs-ui/components/dialog/search"; import type { SharedProps } from "fumadocs-ui/contexts/search"; import { useCallback, useEffect, useMemo, useState } from "react"; +import { useSearchGoal } from "./search-analytics.js"; import { SearchResultItem, renderSearchTable, useActiveProduct } from "./search-markdown.js"; import { type SemanticIndex, @@ -113,8 +114,9 @@ export default function HybridSearchDialog({ // oxlint-disable-next-line react-hooks/exhaustive-deps -- `loaded` re-runs the current query once the semantic index arrives. const run = useCallback((query: string) => client.search(query), [client, loaded]); const search = experimental_useSearch(run); + const sendSearchGoal = useSearchGoal(search.search, props.open, search.data); return ( - + diff --git a/packages/docs-next/src/search-analytics.test.ts b/packages/docs-next/src/search-analytics.test.ts new file mode 100644 index 00000000..8954da57 --- /dev/null +++ b/packages/docs-next/src/search-analytics.test.ts @@ -0,0 +1,36 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { searchGoalTerm } from "./search-analytics.js"; + +test("an ordinary term is trimmed and kept", () => { + assert.equal(searchGoalTerm(" workspace proxy "), "workspace proxy"); +}); + +test("an empty or whitespace-only term is dropped", () => { + assert.equal(searchGoalTerm(""), null); + assert.equal(searchGoalTerm(" "), null); +}); + +test("a token-shaped run of 20 or more characters is dropped", () => { + assert.equal(searchGoalTerm("coder_session_AbCdEf0123456789xyz"), null); + assert.equal(searchGoalTerm("a".repeat(20)), null); + assert.equal(searchGoalTerm("token a1b2c3d4e5f6g7h8i9j0"), null); + assert.equal(searchGoalTerm("workspace-proxy-configuration"), null); + assert.equal(searchGoalTerm("a".repeat(19)), "a".repeat(19)); +}); + +test("an email address is dropped", () => { + assert.equal(searchGoalTerm("jo@example.com"), null); + assert.equal(searchGoalTerm("reset password for jo@example.com"), null); +}); + +test("a term over 100 characters is dropped and never truncated", () => { + const spaced = "a b ".repeat(26).trim(); + assert.equal(spaced.length, 103); + assert.equal(searchGoalTerm(spaced), null); + assert.equal(searchGoalTerm(spaced.slice(0, 100).trim())?.length, 99); + const exact = `${"ab ".repeat(33)}a`; + assert.equal(exact.length, 100); + assert.equal(searchGoalTerm(exact), exact); + assert.equal(searchGoalTerm(`${exact}b`), null); +}); diff --git a/packages/docs-next/src/search-analytics.ts b/packages/docs-next/src/search-analytics.ts new file mode 100644 index 00000000..0979874d --- /dev/null +++ b/packages/docs-next/src/search-analytics.ts @@ -0,0 +1,67 @@ +import type { SearchResult } from "fumadocs-core/search/client"; +import { useCallback, useEffect, useRef } from "react"; + +declare global { + interface Window { + HockeyStack?: { goal?: unknown }; + Osano?: { cm?: { getConsent?: () => unknown } }; + } +} + +export const SEARCH_GOAL_DELAY_MS = 1000; +const MAX_TERM_LENGTH = 100; +const SECRET_SHAPED = /[A-Za-z0-9_\-.+/=]{20,}/; +const EMAIL_SHAPED = /\S+@\S+\.\S+/; + +/** The trimmed term when it is safe to send to HockeyStack, else null. */ +export function searchGoalTerm(search: string): string | null { + const term = search.trim(); + if (!term || term.length > MAX_TERM_LENGTH) return null; + if (SECRET_SHAPED.test(term) || EMAIL_SHAPED.test(term)) return null; + return term; +} + +// The Osano API shape is only what the consent bootstrap in docs-config already reads. +function analyticsAccepted(): boolean { + const consent: unknown = window.Osano?.cm?.getConsent?.(); + return ( + typeof consent === "object" && + consent !== null && + "ANALYTICS" in consent && + consent.ANALYTICS === "ACCEPT" + ); +} + +function sendGoal(term: string): void { + try { + if (!analyticsAccepted()) return; + const goal = window.HockeyStack?.goal; + if (typeof goal !== "function") return; + goal.call(window.HockeyStack, "Docs Search", { search_term: term }); + } catch { + // A tag that changed shape must not break the dialog. + } +} + +/** + * Sends the HockeyStack `Docs Search` goal once per search that is open, has + * results for the current term and passes `searchGoalTerm`, when typing has + * paused for `SEARCH_GOAL_DELAY_MS` or at once through the returned callback. + */ +export function useSearchGoal(search: string, open: boolean, data: SearchResult | undefined) { + const sent = useRef(""); + const settled = open && data?.query === search && data.items.length > 0; + const term = settled ? searchGoalTerm(search) : null; + const send = useCallback(() => { + if (term === null || term === sent.current) return; + sent.current = term; + sendGoal(term); + }, [term]); + useEffect(() => { + if (!open || !search.trim()) sent.current = ""; + if (term === null) return; + const timer = setTimeout(send, SEARCH_GOAL_DELAY_MS); + return () => clearTimeout(timer); + }, [open, search, term, send]); + return send; +} diff --git a/packages/docs-next/src/search-dialog.test.tsx b/packages/docs-next/src/search-dialog.test.tsx index 3874f99c..f0812cd7 100644 --- a/packages/docs-next/src/search-dialog.test.tsx +++ b/packages/docs-next/src/search-dialog.test.tsx @@ -9,9 +9,11 @@ import type { import { loader } from "fumadocs-core/source"; import { act, createElement } from "react"; import { createRoot } from "react-dom/client"; +import { stubHockeyStack } from "../test/hockeystack.js"; import { FORBIDDEN_ELEMENTS, corpusIndexTexts } from "../test/search-xss.js"; import { SearchDialog } from "fumadocs-ui/components/dialog/search"; import DocsSearchDialog, { SearchDialogView } from "./search-dialog.js"; +import { SEARCH_GOAL_DELAY_MS } from "./search-analytics.js"; import { createDocsSearchRoute } from "./search.js"; import { SearchResultItem as DocsSearchResultItem } from "./search-markdown.js"; @@ -34,6 +36,7 @@ const ITEMS = [ type DialogProps = Partial[0], "data">> & { items?: SearchResultItem[] | null; + dataQuery?: string; }; function toData(items: DialogProps["items"], query = "proxy"): SearchResult | undefined { @@ -71,7 +74,10 @@ async function mount(t: TestContext, items: DialogProps["items"], props: DialogP onSearchChange={() => {}} {...props} {...next} - data={toData("items" in next ? next.items : items, next.search ?? props.search)} + data={toData( + "items" in next ? next.items : items, + next.dataQuery ?? next.search ?? props.dataQuery ?? props.search, + )} /> , ); @@ -469,3 +475,156 @@ for (const [pathname, expected] of [ assert.deepEqual(names(), expected); }); } + +const settle = () => wait(SEARCH_GOAL_DELAY_MS + 100); +const GOAL = ["Docs Search", { search_term: "proxy" }]; + +test("Docs Search goal: a term with results is sent once, trimmed, after typing settles", async (t) => { + const goals = stubHockeyStack(t); + const { render } = await mount(t, ITEMS, { search: "p" }); + await render({ search: "pro" }); + await render({ search: " proxy " }); + assert.deepEqual(goals, []); + await settle(); + assert.deepEqual(goals, [GOAL]); + await render({ search: "proxy" }); + await settle(); + assert.equal(goals.length, 1, "a re-render with the same term sends nothing"); +}); + +test("Docs Search goal: selecting a result sends the goal at once and not again when the delay ends", async (t) => { + const goals = stubHockeyStack(t); + await mount(t, ITEMS, { search: "proxy" }); + await press("Enter"); + assert.deepEqual(goals, [GOAL]); + await settle(); + assert.equal(goals.length, 1); +}); + +test("Docs Search goal: a search with no results sends nothing", async (t) => { + const goals = stubHockeyStack(t); + await mount(t, [], { search: "proxy" }); + await settle(); + assert.deepEqual(goals, []); +}); + +test("Docs Search goal: results for an earlier term do not send the current one", async (t) => { + const goals = stubHockeyStack(t); + await mount(t, ITEMS, { search: "proxy", dataQuery: "pro" }); + await press("Enter"); + await settle(); + assert.deepEqual(goals, []); +}); + +test("Docs Search goal: an empty or whitespace-only search sends nothing", async (t) => { + const goals = stubHockeyStack(t); + const { render } = await mount(t, null, { search: "" }); + await render({ search: " " }); + await settle(); + assert.deepEqual(goals, []); +}); + +for (const [name, term] of [ + ["a token-shaped term", "coder_session_AbCdEf0123456789xyz"], + ["an email address", "who is jo@example.com"], + ["a term over 100 characters", "a b ".repeat(26)], +] as const) { + test(`Docs Search goal: ${name} sends nothing, even with results`, async (t) => { + const goals = stubHockeyStack(t); + await mount(t, ITEMS, { search: term }); + await press("Enter"); + await settle(); + assert.deepEqual(goals, []); + }); +} + +test("Docs Search goal: a 100-character term is sent whole", async (t) => { + const goals = stubHockeyStack(t); + const term = `${"ab ".repeat(33)}a`; + await mount(t, ITEMS, { search: term }); + await settle(); + assert.deepEqual(goals, [["Docs Search", { search_term: term }]]); +}); + +test("Docs Search goal: a term that grows into a token shape stops being sent", async (t) => { + const goals = stubHockeyStack(t); + const { render } = await mount(t, ITEMS, { search: "abcdefghij" }); + await settle(); + await render({ search: "abcdefghijklmnopqrstuvwxyz" }); + await settle(); + assert.deepEqual(goals, [["Docs Search", { search_term: "abcdefghij" }]]); +}); + +test("Docs Search goal: a search dismissed before the delay ends is not sent", async (t) => { + const goals = stubHockeyStack(t); + const { render } = await mount(t, ITEMS, { search: "proxy" }); + await render({ open: false }); + await settle(); + assert.deepEqual(goals, []); +}); + +test("Docs Search goal: a dialog reopened with the same term sends it again", async (t) => { + const goals = stubHockeyStack(t); + const { render } = await mount(t, ITEMS, { search: "proxy" }); + await settle(); + await render({ open: false }); + await render({ open: true }); + await settle(); + assert.deepEqual(goals, [GOAL, GOAL]); +}); + +for (const consent of ["DENY", "NOT_CHOSEN", "absent", "throws"] as const) { + test(`Docs Search goal: analytics consent ${consent} sends nothing`, async (t) => { + const goals = stubHockeyStack(t, consent); + await mount(t, ITEMS, { search: "proxy" }); + await press("Enter"); + await settle(); + assert.deepEqual(goals, []); + }); +} + +function uncaughtErrors(t: TestContext) { + const messages: string[] = []; + const listener = (event: ErrorEvent) => { + event.preventDefault(); + messages.push(event.message); + }; + window.addEventListener("error", listener); + t.after(() => window.removeEventListener("error", listener)); + return messages; +} + +test("Docs Search goal: a goal that is not a function neither throws nor sends", async (t) => { + stubHockeyStack(t); + window.HockeyStack = { goal: "not a function" }; + const errors = uncaughtErrors(t); + await mount(t, ITEMS, { search: "proxy" }); + await press("Enter"); + await settle(); + assert.deepEqual(errors, []); +}); + +test("Docs Search goal: a goal that throws is contained", async (t) => { + stubHockeyStack(t); + let calls = 0; + window.HockeyStack = { + goal: () => { + calls += 1; + throw new Error("tag changed"); + }, + }; + const errors = uncaughtErrors(t); + await mount(t, ITEMS, { search: "proxy" }); + await press("Enter"); + await settle(); + assert.equal(calls, 1); + assert.deepEqual(errors, []); +}); + +test("Docs Search goal: a search before HockeyStack has loaded does not throw", async (t) => { + stubHockeyStack(t); + delete window.HockeyStack; + await mount(t, ITEMS, { search: "proxy" }); + await press("Enter"); + await settle(); +}); diff --git a/packages/docs-next/src/search-dialog.tsx b/packages/docs-next/src/search-dialog.tsx index 2c940745..42118dff 100644 --- a/packages/docs-next/src/search-dialog.tsx +++ b/packages/docs-next/src/search-dialog.tsx @@ -17,6 +17,7 @@ import type { DefaultSearchDialogProps } from "fumadocs-ui/components/dialog/sea import { useI18n } from "fumadocs-ui/contexts/i18n"; import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { focusAfterNavigation, returnFocusTo } from "./return-focus.js"; +import { useSearchGoal } from "./search-analytics.js"; import { SearchResultItem, renderSearchTable, useActiveProduct } from "./search-markdown.js"; function renderItem(props: Parameters[0] & { onClick: () => void }) { @@ -158,6 +159,7 @@ export function SearchDialogView({ announceDelayMs?: number; }) { const { onSelect, ...contentProps } = useReturnFocus(); + const sendSearchGoal = useSearchGoal(search, open, data); return ( { + sendSearchGoal(); + onSelect(item); + }} > diff --git a/packages/docs-next/test/hockeystack.ts b/packages/docs-next/test/hockeystack.ts new file mode 100644 index 00000000..2a65a805 --- /dev/null +++ b/packages/docs-next/test/hockeystack.ts @@ -0,0 +1,27 @@ +import type { TestContext } from "node:test"; + +type Consent = "ACCEPT" | "DENY" | "NOT_CHOSEN" | "absent" | "throws"; + +/** Stubs `window.HockeyStack` and Osano's analytics consent for one test and returns the goals recorded. */ +export function stubHockeyStack(t: TestContext, consent: Consent = "ACCEPT") { + const goals: [string, unknown][] = []; + window.HockeyStack = { + goal: (name: string, properties: unknown) => goals.push([name, properties]), + }; + if (consent === "throws") { + window.Osano = { + cm: { + getConsent: () => { + throw new Error("consent unavailable"); + }, + }, + }; + } else if (consent !== "absent") { + window.Osano = { cm: { getConsent: () => ({ ANALYTICS: consent, MARKETING: "ACCEPT" }) } }; + } + t.after(() => { + delete window.HockeyStack; + delete window.Osano; + }); + return goals; +}