Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
64 changes: 63 additions & 1 deletion packages/docs-next/src/hybrid-search.test.tsx
Original file line number Diff line number Diff line change
@@ -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";

Expand Down Expand Up @@ -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(
<FrameworkProvider
usePathname={() => "/"}
useRouter={() => ({ push() {}, replace() {}, refresh() {}, prefetch() {} }) as never}
useParams={() => ({})}
>
<HybridSearchDialog open={open} onOpenChange={() => {}} />
</FrameworkProvider>,
);
});
await render(true);
const input = document.querySelector<HTMLInputElement>('[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, []);
});
4 changes: 3 additions & 1 deletion packages/docs-next/src/hybrid-search.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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 (
<SearchDialog {...search} {...props}>
<SearchDialog {...search} {...props} onSelect={sendSearchGoal}>
<SearchDialogOverlay />
<SearchDialogContent>
<SearchDialogHeader>
Expand Down
36 changes: 36 additions & 0 deletions packages/docs-next/src/search-analytics.test.ts
Original file line number Diff line number Diff line change
@@ -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);
});
67 changes: 67 additions & 0 deletions packages/docs-next/src/search-analytics.ts
Original file line number Diff line number Diff line change
@@ -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;
}
Loading
Loading