diff --git a/README.md b/README.md index da8717e..5cefeba 100644 --- a/README.md +++ b/README.md @@ -125,3 +125,7 @@ MIT --- Built by 🦋 [SuperDoc — DOCX Editor and Agent SDK](https://superdoc.dev) + +### Analytics privacy verification + +For changes to the optional analytics controller or URL navigation, follow [the maintained consent runbook](docs/analytics-consent.md#required-privacy-follow-up-and-release-checks) and run the existing `bun run test:growth` checks. Mirror controller fixes between ooxml.dev and docxcorp.us, use matching site/project fixtures and retain exact source/build evidence before normal maintainer release. These checks use synthetic data and do not send analytics to production. diff --git a/apps/web/index.html b/apps/web/index.html index 6d686b2..8d0bc91 100644 --- a/apps/web/index.html +++ b/apps/web/index.html @@ -17,18 +17,25 @@ - - - ooxml.dev is an interactive reference for ECMA-376 (Office Open XML) — the standard behind .docx, .xlsx, and .pptx files. Built by the SuperDoc team, who implemented a native OOXML renderer from scratch. Features: live previews (edit XML, see it render in real-time using SuperDoc's native OOXML engine), implementation notes (documents real-world behavior where Microsoft Word diverges from the spec), semantic spec search (18,000+ spec chunks searchable by meaning via MCP server at api.ooxml.dev/mcp), and practical guides for paragraphs, tables, borders, bidirectional text, and document creation. The OOXML spec is 5,000+ pages of PDFs with no rendering guidance — this site bridges that gap with knowledge from people who actually implemented the spec. Covers WordprocessingML (the .docx subset). SuperDoc is open source at superdoc.dev. Built by Caio Pizzol (caiopizzol.com), Head of DX at SuperDoc.
+ + + +

Necessary storage saves your choice and supports essential site functions.

+ + + +

Privacy and cookie choices · SuperDoc privacy policy

+ +
+ + diff --git a/apps/web/public/_headers b/apps/web/public/_headers new file mode 100644 index 0000000..73db327 --- /dev/null +++ b/apps/web/public/_headers @@ -0,0 +1,3 @@ + +/privacy.md + Content-Type: text/markdown; charset=utf-8 diff --git a/apps/web/public/llms.txt b/apps/web/public/llms.txt index 240bdc3..514a7f2 100644 --- a/apps/web/public/llms.txt +++ b/apps/web/public/llms.txt @@ -53,3 +53,9 @@ Package metadata (curated from ECMA-376 Part 1 §11.3.x / §12.3.x / §13.3.x / ## About ooxml.dev is built by SuperDoc (https://superdoc.dev). SuperDoc is the open source DOCX Editor and Agent SDK for reviewing, filling, and editing documents. Word-quality DOCX editing, built for your product. The implementation notes on ooxml.dev come from building that engine against thousands of real-world documents. + +## Privacy and cookie choices + +- [Privacy and cookie choices](https://ooxml.dev/privacy/) +- [Privacy notice as Markdown](https://ooxml.dev/privacy.md) +- Optional Google Analytics and referral events stay off until a choice on ooxml.dev. DNT and GPC keep them off. Cookie settings are available in every page footer. diff --git a/apps/web/scripts/prerender.ts b/apps/web/scripts/prerender.ts index e6ee0ef..e3fd206 100644 --- a/apps/web/scripts/prerender.ts +++ b/apps/web/scripts/prerender.ts @@ -7,6 +7,12 @@ * Usage: bun apps/web/scripts/prerender.ts */ +import { + privacyTitle, + privacySections, + privacyLinks, + privacyMarkdown, +} from "../src/lib/privacy-content.mjs"; import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, resolve } from "node:path"; import { type DocPage, docs } from "../src/data/docs"; @@ -277,6 +283,8 @@ function buildHead(path: string): string { function getContentHtml(path: string): string { if (path === "/") return homePageHtml(); if (path === "/cli") return cliPageHtml(); + if (path === "/privacy") + return `
Back to ooxml.dev

${escapeHtml(privacyTitle)}

Cookie choices for ooxml.dev.

${privacySections.map((section) => `

${escapeHtml(section.title)}

${escapeHtml(section.text)}

`).join("")}

Read this notice as Markdown

`; if (path === "/mcp") return mcpPageHtml(); if (path === "/spec") return specPageHtml(); @@ -392,6 +400,8 @@ const notFoundHtml = render404Page(); writeFileSync(resolve(DIST, "404.html"), notFoundHtml); console.log(` ✓ /404.html`); +writeFileSync(resolve(DIST, "privacy.md"), privacyMarkdown("ooxml.dev")); + // Generate sitemap const sitemap = generateSitemap(paths); writeFileSync(resolve(DIST, "sitemap.xml"), sitemap); diff --git a/apps/web/src/consent.css b/apps/web/src/consent.css new file mode 100644 index 0000000..b42c2a2 --- /dev/null +++ b/apps/web/src/consent.css @@ -0,0 +1,158 @@ +[data-consent-banner][hidden], +[data-consent-signal][hidden], +[data-consent-reload][hidden] { + display: none !important; +} +.site-privacy-footer { + padding: 1rem; + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 1.5rem; + font: + 14px/1.6 system-ui, + sans-serif; +} +.site-privacy-footer a { + color: inherit; + text-decoration: underline; + text-underline-offset: 3px; +} +.site-cookie-banner, +.site-cookie-dialog { + box-sizing: border-box; + color: #1c1917; + background: #fff; + font: + 15px/1.6 system-ui, + sans-serif; + overflow-wrap: anywhere; +} +.site-cookie-banner { + position: fixed; + z-index: 10000; + bottom: 1rem; + left: 1rem; + right: 1rem; + max-width: 66rem; + margin: 0 auto; + padding: 1.25rem; + border: 1px solid #a8a29e; + border-radius: 12px; + box-shadow: 0 8px 30px #0002; + display: flex; + align-items: center; + gap: 1.5rem; + max-height: calc(100dvh - 2rem); + overflow-y: auto; +} +.site-cookie-banner p, +.site-cookie-dialog p { + margin: 0 0 0.75rem; +} +.site-cookie-banner a, +.site-cookie-dialog a { + color: #9a3412; + text-decoration: underline; +} +.site-cookie-actions { + display: flex; + flex-wrap: wrap; + gap: 0.75rem; + flex-shrink: 0; +} +.site-cookie-actions button, +.site-cookie-dialog button { + min-height: 44px; + padding: 0.65rem 1rem; + border: 1px solid #57534e; + border-radius: 6px; + background: #fff; + color: #1c1917; + cursor: pointer; + font: inherit; +} +.site-cookie-actions button:hover, +.site-cookie-dialog button:hover { + background: #f5f5f4; +} +.site-cookie-actions button:disabled, +.site-cookie-dialog button:disabled { + cursor: not-allowed; + opacity: 0.6; +} +.site-cookie-banner :focus-visible, +.site-cookie-dialog :focus-visible, +.site-privacy-footer :focus-visible { + outline: 3px solid #c2410c; + outline-offset: 3px; +} +.site-cookie-dialog { + width: min(36rem, calc(100% - 2rem)); + max-height: calc(100dvh - 2rem); + overflow: auto; + padding: 1.5rem; + border: 1px solid #a8a29e; + border-radius: 12px; + margin: auto; +} +.site-cookie-dialog::backdrop { + background: #0008; +} +.site-cookie-dialog h2 { + margin: 0 0 0.75rem; + font-size: 1.4rem; + font-weight: 650; +} +.site-cookie-purpose { + display: flex; + gap: 0.75rem; + margin: 1.25rem 0; + align-items: start; +} +.site-cookie-purpose input { + width: 1.25rem; + height: 1.25rem; + margin-top: 0.25rem; + accent-color: #9a3412; +} +.site-cookie-dialog footer { + display: flex; + gap: 0.75rem; + flex-wrap: wrap; + margin-top: 1.25rem; +} +.site-privacy-page { + max-width: 48rem; + margin: 0 auto; + padding: 3rem 1.25rem; + color: var(--color-text-primary, #1c1917); + line-height: 1.75; +} +.site-privacy-page h1 { + font-size: 2rem; + font-weight: 650; + margin: 1.25rem 0; +} +.site-privacy-page h2 { + font-size: 1.2rem; + font-weight: 650; + margin: 1.75rem 0 0.5rem; +} +.site-privacy-page a { + text-decoration: underline; +} +@media (max-width: 700px) { + .site-cookie-banner { + flex-direction: column; + align-items: stretch; + gap: 0.5rem; + padding: 1rem; + } + .site-cookie-actions { + flex-shrink: 1; + } + .site-cookie-actions button { + flex: 1 1 auto; + } +} diff --git a/apps/web/src/data/seo.ts b/apps/web/src/data/seo.ts index 8dcb9a2..c8d77ec 100644 --- a/apps/web/src/data/seo.ts +++ b/apps/web/src/data/seo.ts @@ -7,6 +7,11 @@ export interface SeoMeta { } const staticPages: Record = { + "/privacy": { + title: "Privacy and cookie choices | ooxml.dev", + description: "How optional analytics and cookie choices work on ooxml.dev.", + type: "website", + }, "/": { title: "ooxml.dev — The OOXML spec, explained by people who actually implemented it", description: @@ -60,7 +65,7 @@ export function getSeoMeta(path: string): SeoMeta { } export function getAllPaths(): string[] { - const paths = ["/", "/cli", "/mcp", "/spec", "/docs"]; + const paths = ["/", "/cli", "/mcp", "/spec", "/docs", "/privacy"]; for (const slug of Object.keys(docs)) { if (slug === "index") continue; paths.push(`/docs/${slug}`); diff --git a/apps/web/src/lib/analytics-consent.d.mts b/apps/web/src/lib/analytics-consent.d.mts new file mode 100644 index 0000000..b4c9383 --- /dev/null +++ b/apps/web/src/lib/analytics-consent.d.mts @@ -0,0 +1,30 @@ +export type AnalyticsSiteHost = "ooxml.dev" | "docxcorp.us"; +export type MeasurementId = `G-${string}`; +export interface ConsentChoice { + version: 1; + savedAt: number; + analytics: boolean; +} +export interface ConsentController { + readonly choice: ConsentChoice | null; + readonly blocked: boolean; + readonly reloadRequired: boolean; + save(analytics: boolean): ConsentChoice; + reconcile(fromStorage?: boolean): void; +} +export interface ConsentOptions { + measurementId: MeasurementId; + siteHost: AnalyticsSiteHost; + win?: any; + doc?: any; + clock?: () => number; +} +export const CONSENT_KEY: string; +export const CONSENT_MAX_AGE: number; +export function privacySignal(win: any): boolean; +export function validChoice(value: unknown, now?: number): ConsentChoice | null; +export function readConsent(win: any, now?: number): ConsentChoice | null; +export function publicSurface(location: { href: string }, siteHost: AnalyticsSiteHost): boolean; +export function clearAnalyticsCookies(doc: any, siteHost: AnalyticsSiteHost): void; +export function initializeAnalyticsConsent(options: ConsentOptions): ConsentController | null; +export function installConsentControls(options: ConsentOptions): ConsentController | null; diff --git a/apps/web/src/lib/analytics-consent.mjs b/apps/web/src/lib/analytics-consent.mjs new file mode 100644 index 0000000..c26062d --- /dev/null +++ b/apps/web/src/lib/analytics-consent.mjs @@ -0,0 +1,314 @@ +// Keep this small consent controller identical in ooxml.dev and docxcorp.us. +// Each origin owns its own choice. No homepage visit or cross-domain ID is used. +export const CONSENT_KEY = "superdoc_site_analytics_consent"; +export const CONSENT_MAX_AGE = 180 * 24 * 60 * 60 * 1000; +const INSTALLED = new WeakMap(); + +export function privacySignal(win) { + return ( + win?.navigator?.globalPrivacyControl === true || + win?.superdocAnalyticsOptOut === true || + [win?.navigator?.doNotTrack, win?.doNotTrack].some((value) => + ["1", "yes"].includes(String(value).trim().toLowerCase()), + ) + ); +} +export function validChoice(value, now = Date.now()) { + return value?.version === 1 && + typeof value.analytics === "boolean" && + Number.isFinite(value.savedAt) && + value.savedAt <= now && + now - value.savedAt <= CONSENT_MAX_AGE + ? value + : null; +} +export function readConsent(win, now = Date.now()) { + try { + return validChoice(JSON.parse(win.localStorage.getItem(CONSENT_KEY)), now); + } catch { + return null; + } +} +export function publicSurface(location, siteHost) { + try { + const url = new URL(location.href); + // OAuth responses may put credentials in either the query or fragment, + // including hash-router callback queries. Inspect decoded parameter names. + const fragment = url.hash.slice(1); + const fragmentParameters = [ + new URLSearchParams(fragment), + new URLSearchParams(fragment.includes("?") ? fragment.slice(fragment.indexOf("?") + 1) : ""), + ]; + const privateParameter = + /^(token|access_token|id_token|refresh_token|oauth_token|oauth_verifier|client_secret|key|email|auth|session|code|state)$/i; + return ( + url.protocol === "https:" && + [siteHost, "www." + siteHost].includes(url.hostname) && + !url.port && + !url.username && + !url.password && + !/^\/(account|checkout|trial|sign-in|sign-up|auth)(?:\/|$)/.test(url.pathname) && + ![ + ...url.searchParams.keys(), + ...fragmentParameters.flatMap((parameters) => [...parameters.keys()]), + ].some((key) => privateParameter.test(key)) + ); + } catch { + return false; + } +} +export function clearAnalyticsCookies(doc, siteHost) { + let visible = ""; + try { + visible = doc.cookie || ""; + } catch { + return; + } + const names = visible + .split(";") + .map((cookie) => cookie.trim().split("=")[0]) + .filter((name) => /^_ga(?:_|$)|^_gid$|^_gat(?:_|$)/.test(name)); + for (const name of names) + for (const domain of ["", `; Domain=${siteHost}`, `; Domain=.${siteHost}`]) { + try { + doc.cookie = `${name}=; Max-Age=0; Path=/${domain}; SameSite=Lax`; + } catch { + /* A blocked cookie jar must not block reading the site. */ + } + } +} + +// Preserve existing public ecosystem attribution without forwarding arbitrary +// query values, referring paths or private URL fragments to the provider. +export function publicAttribution(location, referrer) { + const params = new URL(location.href).searchParams, + campaign = {}; + const fields = { + utm_source: [ + "campaign_source", + [ + "superdoc.dev", + "www.superdoc.dev", + "ooxml.dev", + "docxcorp.us", + "docx.tools", + "docs.superdoc.dev", + ], + ], + utm_medium: ["campaign_medium", ["referral", "social", "email"]], + utm_campaign: ["campaign_name", ["ecosystem", "footer", "customer_welcome"]], + }; + for (const [key, [field, values]] of Object.entries(fields)) + if (values.includes(params.get(key))) campaign[field] = params.get(key); + let page_referrer = ""; + try { + const url = new URL(referrer); + if ( + url.protocol === "https:" && + !url.username && + !url.password && + !url.port && + /^(www\.)?(superdoc\.dev|ooxml\.dev|docxcorp\.us|docx\.tools|google\.com|bing\.com|linkedin\.com|github\.com|chatgpt\.com|claude\.ai)$/.test( + url.hostname, + ) + ) + page_referrer = url.origin + "/"; + } catch { + /* Unknown referrers stay absent. */ + } + return { page_referrer, ...campaign }; +} + +export function initializeAnalyticsConsent({ + measurementId, + siteHost, + win = globalThis.window, + doc = globalThis.document, + clock = Date.now, +}) { + if (!win || !doc) return null; + if (!/^G-[A-Z0-9]+$/.test(measurementId) || !["ooxml.dev", "docxcorp.us"].includes(siteHost)) + throw Error("Unknown analytics configuration"); + if (INSTALLED.has(win)) return INSTALLED.get(win); + let choice = readConsent(win, clock()), + loaded = false, + persisted = true, + reloading = false; + const allowed = () => + validChoice(choice, clock())?.analytics === true && + !privacySignal(win) && + publicSurface(win.location, siteHost); + const reload = () => { + if (!reloading) { + reloading = true; + win.location.reload(); + } + }; + const apply = () => { + const enabled = allowed(); + win.superdocAnalyticsConsent = enabled; + win["ga-disable-" + measurementId] = !enabled; + if (!enabled) { + clearAnalyticsCookies(doc, siteHost); + if (loaded) reload(); // Removing a script alone does not stop its running SDK. + return false; + } + if (!loaded) { + loaded = true; + // Nothing collected before the affirmative choice is replayed on consent. + win.dataLayer = []; + win.gtag = function () { + if (allowed()) win.dataLayer.push(arguments); + }; + win.gtag("consent", "default", { + analytics_storage: "granted", + ad_storage: "denied", + ad_user_data: "denied", + ad_personalization: "denied", + }); + win.gtag("js", new Date(clock())); + win.gtag("config", measurementId, { + page_location: win.location.origin + win.location.pathname, + ...publicAttribution(win.location, doc.referrer), + allow_google_signals: false, + allow_ad_personalization_signals: false, + }); + const script = doc.createElement("script"); + script.id = "site-google-analytics"; + script.async = true; + script.src = "https://www.googletagmanager.com/gtag/js?id=" + measurementId; + try { + doc.head.appendChild(script); + } catch { + loaded = false; + win.superdocAnalyticsConsent = false; + win["ga-disable-" + measurementId] = true; + return false; + } + } + return true; + }; + const reconcile = (fromStorage = false) => { + if (persisted || fromStorage) choice = readConsent(win, clock()); + apply(); + }; + const controller = { + get choice() { + return validChoice(choice, clock()); + }, + get blocked() { + return privacySignal(win); + }, + get reloadRequired() { + return loaded; + }, + save(analytics) { + choice = { + version: 1, + savedAt: clock(), + analytics: analytics === true && !privacySignal(win), + }; + try { + win.localStorage.setItem(CONSENT_KEY, JSON.stringify(choice)); + persisted = true; + } catch { + persisted = false; + } + apply(); + return choice; + }, + reconcile, + }; + INSTALLED.set(win, controller); + // Recheck expiry and privacy signals before a CTA listener can emit an event. + doc.addEventListener("click", () => reconcile(), true); + doc.addEventListener("visibilitychange", () => { + if (doc.visibilityState === "visible") reconcile(); + }); + win.addEventListener("pageshow", () => reconcile()); + win.addEventListener("storage", (event) => { + if (event.key === CONSENT_KEY || event.key === null) reconcile(true); + }); + for (const method of ["pushState", "replaceState"]) { + if (!win.history?.[method]) continue; + const original = win.history[method].bind(win.history); + win.history[method] = function (state, title, target) { + const next = target ? new URL(target, win.location.href) : null; + if (next && publicSurface(next, siteHost) !== publicSurface(win.location, siteHost)) { + win.superdocAnalyticsConsent = false; + win["ga-disable-" + measurementId] = true; + win.location.assign(next.href); + return; + } + return original(state, title, target); + }; + } + apply(); + return controller; +} + +export function installConsentControls(options) { + const win = options.win ?? globalThis.window, + doc = options.doc ?? globalThis.document; + const controller = initializeAnalyticsConsent({ ...options, win, doc }); + if (!controller) return null; + const banner = doc.querySelector("[data-consent-banner]"), + dialog = doc.querySelector("[data-consent-dialog]"); + if (!banner || !dialog || dialog.dataset.installed) return controller; + dialog.dataset.installed = "true"; + const checkbox = dialog.querySelector("[data-consent-analytics]"); + const update = () => { + checkbox.checked = controller.choice?.analytics === true && !controller.blocked; + checkbox.disabled = controller.blocked; + for (const button of doc.querySelectorAll("[data-consent-accept]")) + button.disabled = controller.blocked; + for (const message of doc.querySelectorAll("[data-consent-signal]")) + message.hidden = !controller.blocked; + dialog.querySelector("[data-consent-reload]").hidden = !controller.reloadRequired; + dialog.querySelector("[data-consent-save]").textContent = controller.reloadRequired + ? "Save choices (reloads if turned off)" + : "Save choices"; + dialog.querySelector("[data-consent-reject]").textContent = controller.reloadRequired + ? "Reject and reload" + : "Reject analytics"; + }; + const close = () => { + dialog.close(); + banner.hidden = Boolean(controller.choice); + }; + const show = () => { + update(); + dialog.showModal(); + }; + const save = (value) => { + controller.save(value); + banner.hidden = true; + dialog.close(); + }; + banner.hidden = Boolean(controller.choice); + update(); + doc.addEventListener("click", (event) => { + const target = event.target.closest?.( + "[data-consent-accept],[data-consent-reject],[data-consent-open],[data-consent-save],[data-consent-close]", + ); + if (!target) return; + if (target.hasAttribute("data-consent-open")) { + event.preventDefault(); + show(); + } else if (target.hasAttribute("data-consent-close")) close(); + else if (target.hasAttribute("data-consent-accept")) save(true); + else if (target.hasAttribute("data-consent-reject")) save(false); + else if (target.hasAttribute("data-consent-save")) save(checkbox.checked); + }); + dialog.addEventListener("cancel", (event) => { + event.preventDefault(); + close(); + }); + win.addEventListener("storage", (event) => { + if (event.key === CONSENT_KEY || event.key === null) { + update(); + banner.hidden = Boolean(controller.choice); + } + }); + return controller; +} diff --git a/apps/web/src/lib/growth-attribution.mjs b/apps/web/src/lib/growth-attribution.mjs index eb04ca1..3d515bc 100644 --- a/apps/web/src/lib/growth-attribution.mjs +++ b/apps/web/src/lib/growth-attribution.mjs @@ -13,6 +13,7 @@ export function analyticsAllowed(win, sourceProject) { return Boolean( Object.hasOwn(PROJECTS, sourceProject) && PROJECTS[sourceProject]?.includes(win?.location?.hostname) && + win?.superdocAnalyticsConsent === true && typeof win?.gtag === "function" && win?.navigator?.globalPrivacyControl !== true && ![win?.navigator?.doNotTrack, win?.doNotTrack].some((value) => diff --git a/apps/web/src/lib/privacy-content.d.mts b/apps/web/src/lib/privacy-content.d.mts new file mode 100644 index 0000000..0624223 --- /dev/null +++ b/apps/web/src/lib/privacy-content.d.mts @@ -0,0 +1,4 @@ +export const privacyTitle: string; +export const privacySections: { title: string; text: string }[]; +export const privacyLinks: { label: string; href: string }[]; +export function privacyMarkdown(siteHost: string): string; diff --git a/apps/web/src/lib/privacy-content.mjs b/apps/web/src/lib/privacy-content.mjs new file mode 100644 index 0000000..1e59ffd --- /dev/null +++ b/apps/web/src/lib/privacy-content.mjs @@ -0,0 +1,37 @@ +export const privacyTitle = "Privacy and cookie choices"; +export const privacySections = [ + { + title: "Optional analytics", + text: "You can use this site without optional analytics cookies. Google Analytics and our referral click measurement stay off until you choose to enable analytics on this site. Google Analytics measures page views and referral activity and may process cookie identifiers and browser or device information. Advertising personalization and Google signals are disabled in our site configuration.", + }, + { + title: "Your choice on this site", + text: "Accept analytics, reject analytics, or open Preferences to choose. Your choice is saved in this browser on this site and is valid for up to 180 days. It is not copied from superdoc.dev or shared across our other sites. Global Privacy Control and Do Not Track signals keep optional analytics off. With JavaScript disabled, optional analytics does not load.", + }, + { + title: "Change or withdraw consent", + text: "Open Cookie settings on any page to change your choice. Turning off analytics clears this site's analytics cookies and reloads the page to stop the loaded tag. Save any edits before withdrawing consent. Withdrawal does not erase data previously received by a provider.", + }, + { + title: "Referral click measurement", + text: "Our custom referral click event records which site and link placement led toward SuperDoc, documentation, pricing or a trial guide. This event excludes document contents, filenames, query strings, contact names and email addresses. A click does not establish a signup, evaluation or purchase.", + }, + { + title: "Service requests and privacy rights", + text: "Necessary service delivery, security processing and any account authentication you request are separate from optional analytics. This site is operated by Harbour Enterprises, Inc., doing business as SuperDoc. Read the SuperDoc privacy policy for details about personal information, recipients, retention and applicable privacy rights. Send privacy questions or requests to privacy@harbourshare.com.", + }, +]; +export const privacyLinks = [ + { label: "SuperDoc privacy policy", href: "https://www.superdoc.dev/privacy-policy" }, + { label: "Google privacy policy", href: "https://policies.google.com/privacy" }, + { label: "Privacy questions and requests", href: "mailto:privacy@harbourshare.com" }, +]; +export function privacyMarkdown(siteHost) { + return ( + `# ${privacyTitle}\n\nCookie choices for ${siteHost}.\n\n` + + privacySections.map((section) => `## ${section.title}\n\n${section.text}\n\n`).join("") + + "## Cookie settings\n\nOpen [Cookie settings](/privacy#cookie-settings) in your browser to change your choice.\n\n" + + privacyLinks.map((link) => `[${link.label}](${link.href})`).join("\n\n") + + "\n" + ); +} diff --git a/apps/web/src/main.tsx b/apps/web/src/main.tsx index 60879b3..0ca221c 100644 --- a/apps/web/src/main.tsx +++ b/apps/web/src/main.tsx @@ -1,3 +1,6 @@ +import { installConsentControls } from "./lib/analytics-consent.mjs"; +import { Privacy } from "./pages/Privacy"; +import "./consent.css"; import { installGrowthAttribution } from "./lib/growth-attribution.mjs"; import { StrictMode } from "react"; import { createRoot } from "react-dom/client"; @@ -11,6 +14,7 @@ import { NotFound } from "./pages/NotFound"; import { SpecExplorer } from "./pages/SpecExplorer"; import "./index.css"; +installConsentControls({ measurementId: "G-JFTMJ85VCW", siteHost: "ooxml.dev" }); installGrowthAttribution({ sourceProject: "ooxml_dev", measurementId: "G-JFTMJ85VCW" }); const router = createBrowserRouter([ @@ -19,6 +23,7 @@ const router = createBrowserRouter([ children: [ { path: "/", element: }, { path: "/cli", element: }, + { path: "/privacy", element: }, { path: "/mcp", element: }, { path: "/spec", element: }, { diff --git a/apps/web/src/pages/Privacy.tsx b/apps/web/src/pages/Privacy.tsx new file mode 100644 index 0000000..6a4e5d4 --- /dev/null +++ b/apps/web/src/pages/Privacy.tsx @@ -0,0 +1,35 @@ +import { privacyTitle, privacySections, privacyLinks } from "../lib/privacy-content.mjs"; +import { useDocumentTitle } from "../hooks/useDocumentTitle"; + +export function Privacy() { + useDocumentTitle(`${privacyTitle} | ooxml.dev`); + return ( +
+ Back to ooxml.dev +

{privacyTitle}

+

Cookie choices for ooxml.dev.

+ {privacySections.map((section) => ( +
+

{section.title}

+

{section.text}

+
+ ))} + +
    + {privacyLinks.map((link) => ( +
  • + {link.label} +
  • + ))} +
+

+ Read this notice as Markdown +

+
+ ); +} diff --git a/docs/analytics-consent.md b/docs/analytics-consent.md new file mode 100644 index 0000000..2b339b0 --- /dev/null +++ b/docs/analytics-consent.md @@ -0,0 +1,19 @@ +# Site analytics consent + +Google Analytics and the existing SuperDoc referral click event require an affirmative analytics choice on this origin. A homepage visit or cookie choice on another domain does not grant access. The necessary local choice is versioned and expires after 180 days. Malformed, future and expired records fail closed. DNT, GPC and the existing explicit opt-out override a grant. + +Cookie settings remain available on every page. Withdrawing a loaded provider disables its measurement flag, blocks the custom event, clears this site's GA cookies and reloads the document. The dialog warns users to save edits first. Other tabs and restored pages recheck the saved choice. Auth and private capability URLs never start the provider; SPA transitions across that boundary use a fresh document. Local development and previews do not send analytics to the production property. + +The UI, server HTML and Markdown notice use the same substantive notice content. `/privacy`, `/privacy.md`, the footer, sitemap and agent index connect the notice and controls. Google signals and advertising personalization are disabled. Known ecosystem campaign tags and public referring origins are retained after consent; raw queries, referring paths and fragments are excluded from the initial configuration. The existing bounded CTA payload remains unchanged. + +Run `bun run test:growth` for both the event and consent boundary tests. Test direct arrivals without a stored choice, rejection and reload, preferences with an unchecked analytics box, acceptance and revisit, withdrawal, privacy signals and narrow screens. Provider loading after consent is covered by isolated production-host controller tests. Local browser previews validate UI and rejected-visit network behavior without sending test events to a production analytics property. + +This change does not add visitor identification, change SuperDoc's homepage consent controls or change sales qualification, outreach, review approvals or schedules. + +## Required privacy follow-up and release checks + +Keep this controller byte-identical to its mirror in the other site. Inspect decoded names in the URL query, the complete fragment and any hash-router query independently; a literal question mark inside a fragment value must not hide the preceding credential key. OAuth 1.0 `oauth_token` and `oauth_verifier` are private as well as OAuth 2 token/code fields. Keep benign public anchors eligible and preserve the exact navigation target while disabling measurement on a private transition. + +Consent-negative CTA tests must use the actual site's matching production host and project, first prove that the granted control can emit, then prove absent/rejected consent emits nothing. Removing consent enforcement must make that negative test fail. Preserve refusal, withdrawal, DNT/GPC and bounded payload coverage. Use synthetic controller inputs only; never send verification events to the production property. + +Carry accepted privacy findings into this same runbook, selected controller and existing `test:growth` CI check. Before normal maintainer release, retain the exact source head, failing-before/passing-after evidence, actual build/check receipts and any remaining review holds. Human review and deployed behavior remain separate from a green fixture. diff --git a/package.json b/package.json index 4175353..e85fb85 100644 --- a/package.json +++ b/package.json @@ -43,7 +43,7 @@ "xsd:fetch": "bun scripts/ingest-xsd/fetch.ts", "xsd:ingest": "bun scripts/ingest-xsd/ingest.ts", "test": "export TEST_DATABASE_URL=${TEST_DATABASE_URL:-postgresql://postgres:postgres@localhost:5432/ecma_spec} && bun test tests/web/ && bun test tests/db/ && bun test tests/ingest-xsd/ && bun test tests/mcp-server/", - "test:growth": "node --test tests/growth-attribution.test.mjs" + "test:growth": "node --test tests/growth-attribution.test.mjs tests/analytics-consent.test.mjs" }, "devDependencies": { "@changesets/cli": "3.0.0", diff --git a/tests/analytics-consent.test.mjs b/tests/analytics-consent.test.mjs new file mode 100644 index 0000000..4a560cb --- /dev/null +++ b/tests/analytics-consent.test.mjs @@ -0,0 +1,129 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFile} from 'node:fs/promises'; +import {CONSENT_KEY, CONSENT_MAX_AGE, initializeAnalyticsConsent, readConsent} from '../apps/web/src/lib/analytics-consent.mjs'; +import {analyticsAllowed} from '../apps/web/src/lib/growth-attribution.mjs'; + +function surface() { + const storage = new Map(), scripts = [], events = new Map(), cookies = new Map([['_ga', 'old'], ['_ga_OLD', 'old'], ['session', 'necessary']]); + let now = Date.parse('2026-11-11T20:00:00Z'), reloads = 0; + const win = {location: {...new URL('https://ooxml.dev/'), href: 'https://ooxml.dev/?utm_source=superdoc.dev#public', hostname: 'ooxml.dev', origin: 'https://ooxml.dev', pathname: '/', reload(){reloads++;}, assign(url){this.assigned=url;}}, navigator: {}, + history: {pushState(){}, replaceState(){}}, + localStorage: {getItem:key=>storage.get(key)??null,setItem:(key,value)=>storage.set(key,value)}, + addEventListener(name,fn){events.set('window:'+name,fn);}, + }; + const doc = {head:{appendChild:script=>scripts.push(script)}, createElement:()=>({}), visibilityState:'visible', + addEventListener(name,fn){events.set('document:'+name,fn);}, + get cookie(){return [...cookies].map(([k,v])=>k+'='+v).join('; ');}, + set cookie(value){const name=value.split('=')[0];if(value.includes('Max-Age=0'))cookies.delete(name);}, + }; + const start=()=>initializeAnalyticsConsent({win,doc,measurementId:'G-SYNTHETIC',siteHost:'ooxml.dev',clock:()=>now}); + const saved=analytics=>storage.set(CONSENT_KEY,JSON.stringify({version:1,savedAt:now,analytics})); + return {win,doc,start,saved,storage,scripts,cookies,events,get reloads(){return reloads;},clock:()=>now,advance:milliseconds=>{now+=milliseconds;}}; +} + +test('a direct first visit loads no Google tag and does not grant CTA measurement',()=>{ + const s=surface();s.start();assert.equal(s.scripts.length,0);assert.equal(s.win.superdocAnalyticsConsent,false); + assert.equal(s.win['ga-disable-G-SYNTHETIC'],true);assert.equal(analyticsAllowed(s.win,'ooxml_dev'),false); +}); +test('only affirmative consent loads one tag with advertising disabled, without replaying prior activity',()=>{ + const s=surface();s.win.dataLayer=[['event','prior_private_activity']];const consent=s.start();consent.save(true);s.start();consent.reconcile(); + assert.equal(s.scripts.length,1);assert.match(s.scripts[0].src,/gtag\/js\?id=G-SYNTHETIC$/); + assert.equal(analyticsAllowed(s.win,'ooxml_dev'),true);assert.equal(s.win['ga-disable-G-SYNTHETIC'],false); + const calls=s.win.dataLayer.map(args=>[...args]);assert.equal(calls.length,3); + assert.equal(calls[0][2].ad_storage,'denied');assert.equal(calls[0][2].ad_user_data,'denied');assert.equal(calls[0][2].ad_personalization,'denied'); + assert.equal(calls[2][2].allow_google_signals,false);assert.equal(calls[2][2].page_location,'https://ooxml.dev/');assert.equal(calls[2][2].page_referrer,''); + assert.doesNotMatch(JSON.stringify(calls),/prior_private_activity|utm_source|#public/); +}); +test('rejection is persistent and clears only analytics cookies without reloading a fresh visit',()=>{ + const s=surface(),consent=s.start();consent.save(false); + assert.equal(readConsent(s.win,s.clock()).analytics,false);assert.equal(s.scripts.length,0);assert.equal(s.reloads,0); + assert.deepEqual([...s.cookies.keys()],['session']); +}); +test('withdrawal blocks later events, clears analytics cookies and reloads once to stop the loaded SDK',()=>{ + const s=surface(),consent=s.start();consent.save(true);const oldGtag=s.win.gtag,before=s.win.dataLayer.length; + consent.save(false);oldGtag('event','must_not_send');consent.reconcile(); + assert.equal(s.win.dataLayer.length,before);assert.equal(s.win['ga-disable-G-SYNTHETIC'],true);assert.equal(s.win.superdocAnalyticsConsent,false); + assert.equal(s.reloads,1);assert.deepEqual([...s.cookies.keys()],['session']); +}); +test('DNT, GPC and explicit opt-out override a stored grant and an attempted new grant',()=>{ + for(const block of [s=>s.win.navigator.globalPrivacyControl=true,s=>s.win.navigator.doNotTrack='1',s=>s.win.doNotTrack='yes',s=>s.win.superdocAnalyticsOptOut=true]){ + const s=surface();s.saved(true);block(s);const consent=s.start();assert.equal(consent.blocked,true);consent.save(true); + assert.equal(s.scripts.length,0);assert.equal(s.win.superdocAnalyticsConsent,false);assert.equal(readConsent(s.win,s.clock()).analytics,false); + } +}); +test('malformed, future and expired choices fail closed',()=>{ + for(const value of ['broken','{}',JSON.stringify({version:2,savedAt:0,analytics:true}),JSON.stringify({version:1,savedAt:surface().clock()+1,analytics:true}),JSON.stringify({version:1,savedAt:0,analytics:true})]){ + const s=surface();s.storage.set(CONSENT_KEY,value);s.start();assert.equal(s.scripts.length,0);assert.equal(s.win.superdocAnalyticsConsent,false); + } +}); +test('valid returning consent loads the tag, and expiry on an open page stops it',()=>{ + const s=surface();s.saved(true);s.start();assert.equal(s.scripts.length,1);s.advance(CONSENT_MAX_AGE+1);s.events.get('document:click')(); + assert.equal(s.win.superdocAnalyticsConsent,false);assert.equal(s.reloads,1); +}); +test('cross-tab withdrawal, clearing storage and a restored page cannot revive an old grant',()=>{ + for(const event of ['window:storage','window:pageshow']){ + const s=surface();s.saved(true);s.start();s.storage.clear();s.events.get(event)({key:null,persisted:true}); + assert.equal(s.win.superdocAnalyticsConsent,false);assert.equal(s.reloads,1); + } +}); +test('storage denial retains a session choice, while a fresh document still defaults off',()=>{ + const s=surface();s.win.localStorage.setItem=()=>{throw Error('Storage unavailable');};const consent=s.start();consent.save(true);consent.reconcile(); + assert.equal(s.win.superdocAnalyticsConsent,true);assert.equal(s.scripts.length,1); + const fresh=surface();fresh.win.localStorage.getItem=()=>{throw Error('Storage unavailable');};fresh.start();assert.equal(fresh.scripts.length,0); +}); +test('private and non-production surfaces never load the tag; SPA auth navigation enters a fresh document',()=>{ + for(const href of ['https://ooxml.dev/sign-in','https://ooxml.dev/auth/callback','https://ooxml.dev/?token=secret','http://localhost/']){ + const s=surface();const u=new URL(href);Object.assign(s.win.location,{href,hostname:u.hostname,origin:u.origin,pathname:u.pathname});s.saved(true);s.start();assert.equal(s.scripts.length,0); + } + const s=surface();s.saved(true);s.start();s.win.history.pushState({},'','/sign-in?code=secret'); + assert.equal(s.win.location.assigned,'https://ooxml.dev/sign-in?code=secret');assert.equal(s.win.superdocAnalyticsConsent,false);assert.equal(s.win['ga-disable-G-SYNTHETIC'],true); +}); +test('the originating site owns its choice and unknown consent cannot enable a CTA event',()=>{ + const s=surface();s.storage.set('superdoc_cookie_preferences',JSON.stringify({version:1,savedAt:Date.now(),analytics:true,identification:true}));s.start(); + assert.equal(s.scripts.length,0);s.win.gtag=()=>{};assert.equal(analyticsAllowed(s.win,'ooxml_dev'),false); +}); +test('the HTML entry point has usable privacy controls and no unconditional Google loader',async()=>{ + const html=await readFile(new URL('../apps/web/index.html',import.meta.url),'utf8'); + assert.doesNotMatch(html,/googletagmanager\.com|gtag\('config'/); + for(const attribute of ['data-consent-banner','data-consent-dialog','data-consent-accept','data-consent-reject','data-consent-open'])assert.ok(html.includes(attribute)); + assert.match(html,/href="\/privacy"/); +}); + +test('accepted visits retain known ecosystem campaigns and only the public referrer origin',()=>{ + const s=surface();s.win.location.href='https://ooxml.dev/?utm_source=superdoc.dev&utm_medium=referral&utm_campaign=ecosystem&private=secret';s.doc.referrer='https://www.superdoc.dev/private?email=private@example.test';s.start().save(true); + const config=[...s.win.dataLayer[2]][2];assert.equal(config.campaign_source,'superdoc.dev');assert.equal(config.campaign_medium,'referral');assert.equal(config.campaign_name,'ecosystem');assert.equal(config.page_referrer,'https://www.superdoc.dev/');assert.doesNotMatch(JSON.stringify(config),/private|secret|email/); +}); + +test('blocked cookie storage or script insertion cannot prevent reading the site',()=>{ + const s=surface();Object.defineProperty(s.doc,'cookie',{get(){throw Error('Cookie access blocked');}});assert.doesNotThrow(()=>s.start());assert.equal(s.win.superdocAnalyticsConsent,false); + const blocked=surface();blocked.doc.head.appendChild=()=>{throw Error('Script insertion blocked');};assert.doesNotThrow(()=>blocked.start().save(true));assert.equal(blocked.win.superdocAnalyticsConsent,false); +}); + +test('credential-bearing queries and OAuth fragments cannot load GA, even with a saved grant',()=>{ + for (const suffix of ['?access_token=secret','?id_token=secret','?ACCESS_TOKEN=secret','?%61ccess_token=secret','#access_token=secret','#id_token=secret','#code=secret&state=secret','#/callback?access_token=secret','?refresh_token=secret','#client_secret=secret']) { + const s=surface(); s.win.location.href='https://ooxml.dev/'+suffix; s.saved(true); s.start(); + assert.equal(s.scripts.length,0,suffix); assert.equal(s.win.superdocAnalyticsConsent,false,suffix); + } + const s=surface(); s.saved(true); s.start(); s.win.history.replaceState({},'','/#access_token=secret'); + assert.equal(s.win.location.assigned,'https://ooxml.dev/#access_token=secret'); assert.equal(s.win.superdocAnalyticsConsent,false); +}); + +for(const suffix of ['#access_token=abc?def','#id_token=abc?def','#%61ccess_token=abc?def','?oauth_token=secret','?oauth_verifier=secret','#oauth_token=secret','#/callback?oauth_verifier=secret','#OAUTH_TOKEN=abc?def']){ + test(`credential parameter stays private: ${suffix}`,()=>{ + const s=surface();s.win.location.href='https://ooxml.dev/'+suffix;s.saved(true);s.start(); + assert.equal(s.scripts.length,0);assert.equal(s.win.superdocAnalyticsConsent,false); + }); +} +test('credential-bearing fragments preserve the exact navigation target and disable measurement',()=>{ + for(const method of ['pushState','replaceState']){ + const s=surface();s.saved(true);s.start();s.win.history[method]({},'','/#access_token=abc?def'); + assert.equal(s.win.location.assigned,'https://ooxml.dev/#access_token=abc?def'); + assert.equal(s.win.superdocAnalyticsConsent,false);assert.equal(s.win['ga-disable-G-SYNTHETIC'],true); + } +}); +test('ordinary public fragments and hash-router queries remain eligible after consent',()=>{ + for(const suffix of ['#section?example','#/schema?search=public','#access_token_notes=public']){ + const s=surface();s.win.location.href='https://ooxml.dev/'+suffix;s.saved(true);s.start();assert.equal(s.scripts.length,1); + } +}); diff --git a/tests/growth-attribution.test.mjs b/tests/growth-attribution.test.mjs index ff24f8a..284ef22 100644 --- a/tests/growth-attribution.test.mjs +++ b/tests/growth-attribution.test.mjs @@ -4,7 +4,7 @@ import { analyticsAllowed, classifyDestination, ctaPayload, installGrowthAttribu function surface() { const calls = [], listeners = new Map(); const navigation = { prevented: 0, stopped: 0, assigned: 0, replaced: 0 }; - const win = { location: { hostname: 'ooxml.dev', origin: 'https://ooxml.dev', pathname: '/', href: 'https://ooxml.dev/', assign() { navigation.assigned++; }, replace() { navigation.replaced++; } }, navigator: {}, gtag: (...args) => calls.push(args) }; + const win = { location: { hostname: 'ooxml.dev', origin: 'https://ooxml.dev', pathname: '/', href: 'https://ooxml.dev/', assign() { navigation.assigned++; }, replace() { navigation.replaced++; } }, navigator: {}, superdocAnalyticsConsent: true, gtag: (...args) => calls.push(args) }; const doc = { addEventListener(name, fn) { if (!listeners.has(name)) listeners.set(name, new Set()); listeners.get(name).add(fn); }, removeEventListener(name, fn) { const callbacks = listeners.get(name); callbacks?.delete(fn); if (!callbacks?.size) listeners.delete(name); }, @@ -98,3 +98,13 @@ test('a docs install does not turn ordinary in-docs navigation into referral tra s.dispatch(); assert.equal(s.calls.length, 0); } }); + +test('absent or rejected consent blocks CTA events without changing navigation',()=>{ + for (const choice of [false,undefined]) { + const s=surface(); if(choice===undefined) delete s.win.superdocAnalyticsConsent; else s.win.superdocAnalyticsConsent=choice; + assert.equal(analyticsAllowed(s.win,'ooxml_dev'),false); + installGrowthAttribution({...s,sourceProject:'ooxml_dev',measurementId:'G-SYNTHETIC'}); s.dispatch(); + assert.equal(s.calls.length,0); assert.equal(s.click.defaultPrevented,false); + assert.deepEqual(s.navigation,{prevented:0,stopped:0,assigned:0,replaced:0}); + } +});