Skip to content
Merged
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
3 changes: 3 additions & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,9 @@ Each vendor is named by origin except jsDelivr, a public CDN for any npm package
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.

The search dialog and the product switcher also push `docs_search` and `docs_product_switch` to the container's `dataLayer` through `trackDocsEvent`, which pushes only once the GTM container is on the page and otherwise drops the event, so nothing is sent before consent or without the flag (`apps/docs/README.md` "Analytics").
It adds no origin, so it needs no change to the policy.

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.
It is the next step if the sanitizer ever has to be weakened, and otherwise a later improvement.
Expand Down
18 changes: 18 additions & 0 deletions apps/docs/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -659,6 +659,24 @@ This has no effect on the public site, which the router serves and gates separat
coder.com's `next.config.js` restates the `/docs` policy (step 4 of "Serving through coder.com" below, and the [cutover runbook](https://app.notion.com/p/3f8d579be59281a691f1e6146c2fc1a9), internal, on Notion) and must carry the same origins.
Only `script-src` needs them: the policy has no `default-src`, so Osano's and the tags' requests, images, frames, and styles are not restricted.

#### Events

The docs push two custom events to the Tag Manager `dataLayer` through `trackDocsEvent` in `@coder/docs-config/client`, so any tag Marketing adds to the container (Segment, GA4) can read them.
The helper pushes only once `window.google_tag_manager["GTM-NLLNT3K"]` exists, that is, after a reader accepted marketing consent and GTM loaded.
Before that it drops the event instead of queueing it, because GTM replays everything already in `dataLayer` when it loads, which would send an event from before consent.
With the flag off, on previews, in the offline export, for a reader who denied, or before GTM has loaded, nothing is pushed.
A reader who withdraws marketing consent gets a page reload, so no event can follow the withdrawal.

| Event | Fires | Fields |
| ---------------------- | ------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `docs_search` | Once per search session, when the search dialog closes after the reader typed a query of 2 or more characters. | `search_term` (emails and runs of 32 or more token-like characters replaced with `[redacted]`, except snake_case names such as `CODER_ACCESS_URL` and `coder_agent`, whitespace collapsed, trimmed, at most 100 characters), `results_count` (0 if the results had not arrived), `product` (`coder` or `code-server`), `result_opened` (true when a result was chosen). |
| `docs_product_switch` | When a reader picks a different product in the sidebar switcher. | `from_product`, `to_product` (`coder` or `code-server`). |

Search queries can hold pasted text such as error messages, so `search_term` is redacted and capped, and Security and Privacy should still review it before Marketing sends it on to Segment.
The event carries no result URL.
Page views are not sent by the docs: the container needs a history-change trigger, since the docs navigate on the client.
Marketing needs a Custom Event trigger for each event name above in `GTM-NLLNT3K`, and a tag per destination that reads the fields as Data Layer Variables; until then the events are inert.

The offline export never loads any of this: `turbo.json` does not pass `DOCS_ANALYTICS` to its build, its source names none of the analytics exports, and `pnpm --filter @coder/offlinedocs analytics:check`, run in CI after the build, fails if any page in `out/` carries Osano, GTM, the bootstrap, or the footer control.

Turning the tags on for the public site takes four switches, in this order, because a page that loads the tags under a policy without their origins gets its scripts blocked:
Expand Down
4 changes: 4 additions & 0 deletions packages/docs-config/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,7 @@ export type {
OpenApiSchemas,
} from "./openapi.js";
export { isObject, type JsonObject } from "./json.js";

export { trackDocsEvent } from "./track.js";
export type { DocsEventData } from "./track.js";
export { GTM_CONTAINER_ID } from "./analytics.js";
66 changes: 66 additions & 0 deletions packages/docs-config/src/track.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import assert from "node:assert/strict";
import { afterEach, test } from "node:test";
import { GTM_CONTAINER_ID } from "./analytics.js";
import { trackDocsEvent } from "./track.js";

const realWindow = Object.getOwnPropertyDescriptor(globalThis, "window");

type FakeWindow = Record<string, unknown>;

function useWindow(setup: (window: FakeWindow) => void): FakeWindow {
const window: FakeWindow = {};
setup(window);
Object.defineProperty(globalThis, "window", { value: window, configurable: true });
return window;
}

function layerOf(window: FakeWindow): unknown[] {
const layer = window.dataLayer;
assert.ok(Array.isArray(layer));
return layer;
}

afterEach(() => {
if (realWindow) Object.defineProperty(globalThis, "window", realWindow);
else Reflect.deleteProperty(globalThis, "window");
});

test("trackDocsEvent pushes nothing while the container is absent, and queues nothing", () => {
const window = useWindow((w) => (w.dataLayer = []));
trackDocsEvent("docs_search", { search_term: "token" });
assert.equal(layerOf(window).length, 0);
window.google_tag_manager = { [GTM_CONTAINER_ID]: {} };
assert.equal(layerOf(window).length, 0);
});

test("trackDocsEvent pushes nothing for another container or without a data layer", () => {
const other = useWindow((w) => {
w.dataLayer = [];
w.google_tag_manager = { "GTM-OTHER": {} };
});
trackDocsEvent("docs_search");
assert.equal(layerOf(other).length, 0);
const bare = useWindow((w) => (w.google_tag_manager = { [GTM_CONTAINER_ID]: {} }));
trackDocsEvent("docs_search");
assert.equal(bare.dataLayer, undefined);
});

test("trackDocsEvent pushes the event and its fields once the container is present", () => {
const window = useWindow((w) => {
w.dataLayer = [];
w.google_tag_manager = { [GTM_CONTAINER_ID]: {} };
});
trackDocsEvent("docs_product_switch", { from_product: "coder", to_product: "code-server" });
const layer = layerOf(window);
assert.equal(layer.length, 1);
assert.deepEqual(layer[0], {
event: "docs_product_switch",
from_product: "coder",
to_product: "code-server",
});
});

test("trackDocsEvent does nothing outside a browser", () => {
Reflect.deleteProperty(globalThis, "window");
trackDocsEvent("docs_search");
});
13 changes: 13 additions & 0 deletions packages/docs-config/src/track.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { GTM_CONTAINER_ID } from "./analytics.js";
import { isObject } from "./json.js";

export type DocsEventData = Record<string, string | number | boolean>;

/** Pushes `event` to the Tag Manager data layer once the container has loaded, and otherwise drops it, since the container replays anything queued before consent. */
export function trackDocsEvent(event: `docs_${string}`, data: DocsEventData = {}): void {
if (typeof window === "undefined") return;
const containers: unknown = Reflect.get(window, "google_tag_manager");
if (!isObject(containers) || !(GTM_CONTAINER_ID in containers)) return;
const layer: unknown = Reflect.get(window, "dataLayer");
if (Array.isArray(layer)) layer.push({ event, ...data });
}
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 { useSearchEvent } from "./search-events.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 { onSelect } = useSearchEvent({ open: props.open, ...search, product });
return (
<SearchDialog {...search} {...props}>
<SearchDialog {...search} {...props} onSelect={onSelect}>
<SearchDialogOverlay />
<SearchDialogContent>
<SearchDialogHeader>
Expand Down
62 changes: 61 additions & 1 deletion packages/docs-next/src/product-switcher.test.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import assert from "node:assert/strict";
import { afterEach, beforeEach, test } from "node:test";
import { CODE_SERVER_PRODUCT, CODER_PRODUCT } from "@coder/docs-config/client";
import { CODE_SERVER_PRODUCT, CODER_PRODUCT, GTM_CONTAINER_ID } from "@coder/docs-config/client";
import { loader } from "fumadocs-core/source";
import { act } from "react";
import { type Root, createRoot } from "react-dom/client";
Expand Down Expand Up @@ -208,3 +208,63 @@ test("choosing an option closes the list", async () => {
});
assert.equal(document.querySelectorAll("[data-product-item]").length, 0);
});

function docsEvents(): Record<string, unknown>[] {
const layer: unknown[] = Reflect.get(window, "dataLayer");
return layer.flatMap((entry) =>
typeof entry === "object" && entry !== null && "event" in entry
? [Object.fromEntries(Object.entries(entry))]
: [],
);
}

async function choose(index: number) {
const { items } = await openFirst();
document.addEventListener("click", (event) => event.preventDefault(), { once: true });
await act(async () => {
items[index]?.dispatchEvent(
new window.MouseEvent("click", { bubbles: true, cancelable: true }),
);
});
}

test("choosing another product sends docs_product_switch with both product ids", async () => {
Reflect.set(window, "dataLayer", []);
Reflect.set(window, "google_tag_manager", { [GTM_CONTAINER_ID]: {} });
try {
await renderPage("/admin/users", corpus(true));
await choose(1);
const events = docsEvents();
assert.equal(events.length, 1);
assert.equal(events[0]?.event, "docs_product_switch");
assert.equal(events[0]?.from_product, "coder");
assert.equal(events[0]?.to_product, "code-server");
} finally {
Reflect.deleteProperty(window, "google_tag_manager");
Reflect.deleteProperty(window, "dataLayer");
}
});

test("choosing the current product sends no event", async () => {
Reflect.set(window, "dataLayer", []);
Reflect.set(window, "google_tag_manager", { [GTM_CONTAINER_ID]: {} });
try {
await renderPage("/code-server/install", corpus(true));
await choose(1);
assert.equal(docsEvents().length, 0);
} finally {
Reflect.deleteProperty(window, "google_tag_manager");
Reflect.deleteProperty(window, "dataLayer");
}
});

test("switching product sends nothing while the container has not loaded", async () => {
Reflect.set(window, "dataLayer", []);
try {
await renderPage("/admin/users", corpus(true));
await choose(1);
assert.equal(docsEvents().length, 0);
} finally {
Reflect.deleteProperty(window, "dataLayer");
}
});
11 changes: 9 additions & 2 deletions packages/docs-next/src/product-switcher.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { Popover, PopoverContent, PopoverTrigger } from "fumadocs-ui/components/
import { useTreeContext } from "fumadocs-ui/contexts/tree";
import { Check, ChevronsUpDown } from "lucide-react";
import { type KeyboardEvent, useState } from "react";
import type { DocsProduct } from "@coder/docs-config/client";
import { type DocsProduct, productForUrl, trackDocsEvent } from "@coder/docs-config/client";
import { productHome, productRoots, treeHome } from "./product-roots.js";

interface Choice {
Expand Down Expand Up @@ -91,7 +91,14 @@ export function ProductSwitcher({ primary }: { primary: DocsProduct }) {
href={choice.href}
data-product-item=""
aria-current={choice.current ? "true" : undefined}
onClick={() => setOpen(false)}
onClick={() => {
setOpen(false);
if (choice === current) return;
trackDocsEvent("docs_product_switch", {
from_product: productForUrl(current.href).id,
to_product: productForUrl(choice.href).id,
});
}}
className="flex items-center gap-2 rounded-lg p-1.5 hover:bg-fd-accent hover:text-fd-accent-foreground"
>
<span className="min-w-0">
Expand Down
20 changes: 10 additions & 10 deletions packages/docs-next/src/search-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { useI18n } from "fumadocs-ui/contexts/i18n";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { focusAfterNavigation, returnFocusTo } from "./return-focus.js";
import { SearchResultItem, renderSearchTable, useActiveProduct } from "./search-markdown.js";
import { countResults, useSearchEvent } from "./search-events.js";

function renderItem(props: Parameters<typeof SearchResultItem>[0] & { onClick: () => void }) {
return <SearchResultItem {...props} />;
Expand All @@ -29,15 +30,6 @@ function NoResults() {
return <div className="py-12 text-center text-sm text-fd-muted-foreground">No results found</div>;
}

/** The number of results a search found, counting each row of a table. */
export function countResults(data: SearchResult | undefined): number | null {
if (!data) return null;
return data.items.reduce(
(count, item) => count + (item.type === "table" ? item.rows.length : 1),
0,
);
}

export function searchStatus(search: string, isLoading: boolean, count: number | null): string {
if (search.trim() === "") return "";
if (isLoading) return "Searching";
Expand Down Expand Up @@ -145,6 +137,7 @@ export function SearchDialogView({
defaultItems,
footer,
announceDelayMs = 500,
onSelect: onSelectItem,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
Expand All @@ -156,8 +149,13 @@ export function SearchDialogView({
defaultItems?: SearchItemType[] | null;
footer?: DefaultSearchDialogProps["footer"];
announceDelayMs?: number;
onSelect?: () => void;
}) {
const { onSelect, ...contentProps } = useReturnFocus();
const { onSelect: returnFocusOnSelect, ...contentProps } = useReturnFocus();
const onSelect = (item: SearchItemType) => {
returnFocusOnSelect(item);
onSelectItem?.();
};
return (
<SearchDialog
open={open}
Expand Down Expand Up @@ -215,6 +213,7 @@ export default function DocsSearchDialog({
const { search, onSearchChange, isLoading, data, error } = experimental_useSearch(run, {
delayMs,
});
const { onSelect } = useSearchEvent({ open, search, data, product });
const defaultItems = useMemo<SearchItemType[] | null>(
() =>
links.length === 0
Expand All @@ -233,6 +232,7 @@ export default function DocsSearchDialog({
error={error}
defaultItems={defaultItems}
footer={footer}
onSelect={onSelect}
/>
);
}
Loading
Loading