Skip to content

Open source alternative to Semrush and Ahrefs

Show the local rank grid on a live Google Map in local-seo reports (#699)

Ben Senescud3990e35b3af
diff --git a/.agents/skills/local-seo/SKILL.md b/.agents/skills/local-seo/SKILL.md
index 5794061c..534762f1 100644
--- a/.agents/skills/local-seo/SKILL.md
+++ b/.agents/skills/local-seo/SKILL.md
@@ -49,7 +49,7 @@ Deliver through the `seo-report` skill, saving with `skill: "local-seo"`. If tha
3. Compare the user's listing against the top two competitors: primary category, additional categories, review count, hours completeness, photo count, claimed status. `search_local_businesses` rows usually carry all of this; use `get_business_profile` for what they lack.
4. Sanity-check each listing's website link (`url`/`contact_url` in the rows): it should deep-link to that location's page on the project domain, not a homepage or a stale domain. For broader on-page work, hand off to `run_site_audit`.
5. Call `get_business_reviews` for the user and the strongest competitor. Look at review volume, recency, average rating, and how many reviews got an owner reply.
-6. Run `get_local_rank_grid` for the main keyword. Use the grid to separate "ranks at the storefront only" from "ranks across the service area", and each point's `topResult` to name who wins where the target doesn't.
+6. Run `get_local_rank_grid` for the main keyword, and for each further keyword the user gave (same grid, same center; state the cost first). Use the grid to separate "ranks at the storefront only" from "ranks across the service area", and each point's `topResult` to name who wins where the target doesn't.
7. Add `get_google_business_questions` and `get_business_updates` when the profile basics are already competitive and the gap is engagement rather than setup.
8. Turn the evidence into a prioritized list. Category and claim problems outrank posting cadence every time.
@@ -71,11 +71,66 @@ Sections in this order:
1. **Snapshot** — one or two opening sentences, then a table of category, rating, review count, and claimed status. One row per location for a chain.
2. **The one fix** — one finding. Category and claim problems outrank posting cadence every time.
3. **Head to head** — a table of signal, this business, the best competitor, and the gap. Cover categories, reviews (count, recency, owner replies), hours and profile completeness, and the listing's website link.
-4. **Maps coverage** — what the grid shows, where visibility drops off, and who wins there. A bar chart of ranks by direction reads faster than a paragraph; label every value.
+4. **Maps coverage** — the grid drawn as described in "Drawing the grid" below, its four stat blocks, then what it shows: where visibility drops off, in which direction, and who wins there.
5. **Q&A and posting** — only when the basics are already competitive.
6. **What to do next** — an ordered list.
7. **How this report was made** — opens with the skill link line from `seo-report`, pointing at `https://openseo.so/docs/skills/local-seo` ("OpenSEO Local SEO skill"), then which tools returned what, plus a note reading each missing grid rank against that point's `resultsCount` rather than calling it invisibility.
+## Drawing the grid
+
+Local rank trackers (SE Ranking, Local Falcon, BrightLocal) all draw the same picture: numbered circles laid out as the grid, colored by position, with the storefront marked. Reproduce that picture so readers who know those tools recognize it. The figure carries two things: the grid's data, which the viewer draws as a live Google Map, and an inline SVG drawing of the same grid, which readers see in print, in an exported PDF, and wherever the map cannot load.
+
+**Value per point.** With one keyword, the rank. With several keywords, the average position across them as a decimal with one place (3.5), the way SE Ranking collapses many keywords into one map. A keyword that searched a point and did not find the business (`rank` null, no `error`) counts as 21 in that point's average, so ranks 1 and not found average 11.0. A value over 20 prints as "20+", which only happens when no keyword found the business there. A keyword whose search failed at a point (`error: true`) has no position there: leave it out of that point's value and out of every stat below.
+
+**Color scale.** Fixed, never restyled per report:
+
+| Value | Fill | Number |
+| --------- | --------- | ------- |
+| 1–3 | `#3F9D4E` | white |
+| over 3–5 | `#8BC34A` | white |
+| over 5–7 | `#F2C94C` | `#2A1E05` |
+| over 7–10 | `#F28C28` | white |
+| over 10–15 | `#E23B3B` | white |
+| over 15–20 | `#A31515` | white |
+| not found | `#A3ADB8` | white |
+
+**The SVG.** North up, west left, one circle per grid point on a 120-unit pitch with radius 22, so a 3x3 uses `viewBox="0 0 360 400"` and a 5x5 `viewBox="0 0 600 640"`. Set `width` to 360 for a 3x3 and 480 for a 5x5 so the drawing does not stretch to the column; the template already caps it at 100% on a phone. Print the value inside each circle (bold, 15px, centered with `text-anchor="middle"` and `dominant-baseline="central"`). Give the storefront circle a second ring: the same circle again with `fill="none"`, a 2px dark stroke, radius 27. Add an "N" label above the top row and the spacing under the bottom row ("2 km between points"). Then a `figcaption` that lists every value as text in reading order, because a chart never carries a number that is not also written out. First row of a 3x3, for the agent to repeat:
+
+```html
+<svg viewBox="0 0 360 400" width="360" role="img" aria-label="Rank grid, 3 by 3, 2 km spacing">
+<text x="180" y="18" text-anchor="middle" font-size="12" fill="#8f8f8f">N</text>
+<circle cx="60" cy="80" r="22" fill="#3F9D4E"/><text x="60" y="80" text-anchor="middle" dominant-baseline="central" font-size="15" font-weight="700" fill="#fff">3.0</text>
+<circle cx="180" cy="80" r="22" fill="#8BC34A"/><text x="180" y="80" text-anchor="middle" dominant-baseline="central" font-size="15" font-weight="700" fill="#fff">3.5</text>
+<circle cx="300" cy="80" r="22" fill="#8BC34A"/><text x="300" y="80" text-anchor="middle" dominant-baseline="central" font-size="15" font-weight="700" fill="#fff">3.5</text>
+<!-- rows 2 and 3 at cy 200 and 320; the storefront (cx 180, cy 200) also gets: -->
+<circle cx="180" cy="200" r="27" fill="none" stroke="#0a0a0a" stroke-width="2"/>
+<text x="180" y="372" text-anchor="middle" font-size="12" fill="#8f8f8f">2 km between points</text>
+</svg>
+```
+
+The `figcaption` lists every value in reading order: "Average position across 2 keywords. NW 3.0, N 3.5, NE 3.5, W 3.0, storefront 1.5, E 3.5, SW 4.5, S 4.5, SE 3.5."
+
+**Four stat blocks** beside or under the drawing, each a heading and a number or short list:
+
+1. Avg. position: the mean of the point values, two decimals.
+2. Rankings distribution: how many point values are 3 or better, over 3 to 10, over 10 to 20, and 20+, as a `.bars` chart.
+3. Avg. position per keyword: one row per keyword with its mean and how many of its points were top 3.
+4. Who ranks #1 most often: count each point's `topResult` across all keywords and list businesses by share.
+
+**Reading it.** Say where visibility drops off by compass direction and by distance ("2 km south, around 75th St" when the user has given you a landmark; otherwise the direction alone), and name who wins there from `topResult`. Proximity to a rival's storefront explains most drop-offs; say so when the rival's coordinate confirms it.
+
+**The figure.** Always wrap the drawing in a widget figure. The viewer renders it as a live Google Map fitted to the grid, with a keyword filter and a popup per point, and hides the SVG while the map is showing:
+
+```html
+<figure data-widget="rank-grid">
+<script type="application/json">{"spacingKm":1,"keywords":[{"keyword":"italian restaurant","points":[{"row":0,"col":0,"lat":41.7918,"lng":-88.1714,"rank":3,"top":"La Sorella di Francesca"}]}]}</script>
+<svg …the drawing above…</svg>
+<figcaption>…</figcaption>
+</figure>
+```
+
+Every point the tool returned goes in `points`: its `row` and `col`, `latitude` as `lat`, `longitude` as `lng`, `rank` (`null` when the business was not found there) and `topResult.title` as `top`. Leave out a point whose search failed (`error: true`); the viewer shows that keyword as "search failed" there. One entry in `keywords` per grid you ran, all with the same center and spacing. The block is data: no comments, no trailing commas, nothing computed.
+
## Guardrails
- Do not run a 5x5 grid, or grids for several keywords, without telling the user the cost first — every point is a paid SERP call.
diff --git a/.agents/skills/seo-report/SKILL.md b/.agents/skills/seo-report/SKILL.md
index e539bf84..104bcc09 100644
--- a/.agents/skills/seo-report/SKILL.md
+++ b/.agents/skills/seo-report/SKILL.md
@@ -57,7 +57,7 @@ These are enforced by the viewer, not by taste. A report that breaks them render
- **No external resources of any kind.** No web fonts, no CDN scripts or stylesheets, no images by URL, no `fetch`. Every request from a saved report is blocked. Inline all CSS in one `<style>` block.
- **Links open in a new tab.** Write every link as `<a href="..." target="_blank" rel="noopener">`. A plain link would navigate the report frame itself, replacing the report with a broken copy of the target. The exception is an in-page anchor (`href="#id"`, as in the contents rail), which stays in the document.
-- **No `<script>`.** Scripts are blocked outright. Anything interactive has to be static.
+- **No executable `<script>`.** A report's own scripts never run, however they are written. The one interactive element is a widget the viewer renders itself from a `<script type="application/json">` data block inside a `<figure data-widget="…">` (the rank grid in `local-seo` is the first). That block is data, not code, and it is the only `<script>` tag a report may contain.
- **Charts are inline SVG or CSS bars**, with real `<text>` labels and a `viewBox`. Always print the numbers next to the chart too.
- **Aim under 80 KB.** The hard cap is 500,000 bytes, and the error says "the limit is 500 KB". Inlined images are the usual way people blow it. A filled report is normally 10-30 KB.
- **No backticks and no `${` anywhere in the HTML.** Codex passes the argument through a JavaScript template literal, where both are syntax. Use `<code>` for inline code and plain text everywhere else.
@@ -251,6 +251,7 @@ footer{max-width:660px;margin:64px 0 0;padding:26px 0 0;border-top:1px solid var
- **`.note`** — one left-ruled callout for a caveat, a confidence limit, or something you could not verify. Two or three in a report, never a row of them.
- **`.tw` table** — every numeric column gets `class="n"` on both the `th` and the `td` so the digits line up. Keep tables to five columns or fewer, put the long-text column last, and keep cell text short; a wide table scrolls on a phone and clips in print.
- **`figure` + `.bars`** — one small bar chart where a comparison reads faster than a sentence. One row per item: `.label`, a `.track` holding a `.bar` whose inline width is the value as a percentage of the largest, and `.value`. Inline SVG is fine for anything that is not a bar chart; give it a `viewBox` and real `<text>` labels.
+- **Widget figure** — a `figure` with a `data-widget` name, a JSON data block the viewer reads, the static drawing as the fallback, and a `figcaption`. Only the widgets a skill documents exist; the viewer ignores any other name and shows the fallback.
- **`hr` then a closing `h2`** — the "What to do next" list, ordered, shortest useful.
- **How this report was made** — the last `h2`: the skill link line, then Tools and Verified bullets. See the section above.
- **`footer`** — one line: the sign-off and the data date. Method detail belongs in the closing section, not here.
diff --git a/.gitignore b/.gitignore
index 53cf3c6f..b2633720 100644
--- a/.gitignore
+++ b/.gitignore
@@ -44,3 +44,6 @@ dist-sourcemaps/
# Alchemy local state + bundle artifacts (SaaS deploys)
.alchemy/
+
+# built by `pnpm build:report-widgets` (predev/build)
+/src/public/report-widgets/
diff --git a/docs/GOOGLE_MAPS_SETUP.md b/docs/GOOGLE_MAPS_SETUP.md
index 1910593d..b969eec7 100644
--- a/docs/GOOGLE_MAPS_SETUP.md
+++ b/docs/GOOGLE_MAPS_SETUP.md
@@ -66,6 +66,15 @@ see Google Maps branding, copyright information, and grid markers. The map
stays fitted to the grid. Click a completed point's marker to see the
businesses ranking there.
+## Maps in Local SEO reports
+
+The same key draws the rank grid in Local SEO agent reports as a live map,
+including for anyone you share a report link with. Those readers are not
+signed in, so each report carries a link that loads tiles only for the area
+around its own grid and expires after a day. Each time someone opens a report
+with a map, it requests Google tiles. Without a key, reports show the grid as
+a drawing instead.
+
## Missing maps
- **Google Maps is not configured:** set the server key and restart or
diff --git a/package.json b/package.json
index 94ad02c5..d389fca8 100644
--- a/package.json
+++ b/package.json
@@ -6,18 +6,21 @@
"type": "module",
"packageManager": "[email protected]",
"scripts": {
+ "predev": "pnpm build:report-widgets",
"dev": "vite dev",
+ "predev:agents": "pnpm build:report-widgets",
"dev:agents": "mkdir -p .logs && portless run vite dev 2>&1 | tee .logs/dev-server.log",
"dev:agents:force": "mkdir -p .logs && portless --force run vite dev 2>&1 | tee .logs/dev-server.log",
- "build": "vite build && tsc --noEmit",
+ "build": "pnpm build:report-widgets && vite build && tsc --noEmit",
+ "build:report-widgets": "tsc --noEmit -p tsconfig.report-widgets.json && vite build -c vite.report-widgets.config.ts",
"lint": "oxlint . --type-aware",
"lint:fix": "oxlint . --type-aware --fix",
"preview": "npm run build && vite preview --port 3001",
"deploy": "npm run db:migrate:prod && npm run build && wrangler deploy -c dist/open_seo_audit/wrangler.json && wrangler deploy",
- "deploy:selfhost": "node scripts/selfhost-deploy-preflight.mjs && vite build --mode selfhost && tsc --noEmit && pnpm alchemy deploy deploy/alchemy/alchemy.run.ts --env-file .env.selfhost --stage selfhost",
+ "deploy:selfhost": "node scripts/selfhost-deploy-preflight.mjs && pnpm build:report-widgets && vite build --mode selfhost && tsc --noEmit && pnpm alchemy deploy deploy/alchemy/alchemy.run.ts --env-file .env.selfhost --stage selfhost",
"deploy:prod": "gh workflow run deploy-production.yml --repo bensenescu/open-seo --ref main",
"deploy:web": "gh workflow run deploy-website.yml --repo bensenescu/open-seo --ref main",
- "deploy:preview": "vite build --mode preview && pnpm alchemy deploy deploy/alchemy/alchemy.run.ts --env-file .env.preview",
+ "deploy:preview": "pnpm build:report-widgets && vite build --mode preview && pnpm alchemy deploy deploy/alchemy/alchemy.run.ts --env-file .env.preview",
"preview:access": "pnpm alchemy deploy deploy/alchemy/alchemy.preview-access.run.ts --env-file .env.preview --stage preview-access --adopt",
"alchemy": "NODE_OPTIONS=\"$NODE_OPTIONS --experimental-strip-types\" alchemy",
"destroy:preview": "pnpm alchemy destroy deploy/alchemy/alchemy.run.ts --env-file .env.preview",
@@ -55,7 +58,7 @@
"repair:rank-locations": "tsx scripts/repair-rank-tracking-locations.ts",
"seed:rank-tracking": "tsx scripts/seed-rank-tracking.ts",
"seed:projects": "tsx scripts/seed-projects.ts",
- "ci:check": "prettier --check . && knip && tsc --noEmit && tsc --noEmit -p tests/badseo/tsconfig.json && oxlint . --type-aware && pnpm sync-plugin-skills && test -z \"$(git status --porcelain -- plugins/openseo/skills)\""
+ "ci:check": "prettier --check . && knip && tsc --noEmit && tsc --noEmit -p tests/badseo/tsconfig.json && tsc --noEmit -p tsconfig.report-widgets.json && oxlint . --type-aware && pnpm sync-plugin-skills && test -z \"$(git status --porcelain -- plugins/openseo/skills)\""
},
"cloudflare": {
"bindings": {
diff --git a/plugins/openseo/.claude-plugin/plugin.json b/plugins/openseo/.claude-plugin/plugin.json
index 23833d9d..1ec91e16 100644
--- a/plugins/openseo/.claude-plugin/plugin.json
+++ b/plugins/openseo/.claude-plugin/plugin.json
@@ -1,7 +1,7 @@
{
"name": "openseo",
"displayName": "OpenSEO",
- "version": "1.0.24",
+ "version": "1.0.25",
"description": "Research keywords and competitors, audit sites, track rankings and AI visibility, and use connected Search Console data from your AI assistant.",
"author": {
"name": "OpenSEO",
diff --git a/plugins/openseo/.codex-plugin/plugin.json b/plugins/openseo/.codex-plugin/plugin.json
index a508efff..e566ec51 100644
--- a/plugins/openseo/.codex-plugin/plugin.json
+++ b/plugins/openseo/.codex-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openseo",
- "version": "1.0.24",
+ "version": "1.0.25",
"description": "Research keywords and competitors, audit sites, track rankings and AI visibility, and use connected Search Console data from your AI assistant.",
"author": {
"name": "OpenSEO",
diff --git a/plugins/openseo/.cursor-plugin/plugin.json b/plugins/openseo/.cursor-plugin/plugin.json
index bf36fe65..28175452 100644
--- a/plugins/openseo/.cursor-plugin/plugin.json
+++ b/plugins/openseo/.cursor-plugin/plugin.json
@@ -1,6 +1,6 @@
{
"name": "openseo",
- "version": "1.0.24",
+ "version": "1.0.25",
"description": "Research keywords and competitors, audit sites, track rankings and AI visibility, and use connected Search Console data from your AI assistant.",
"author": {
"name": "Every App, Inc",
diff --git a/plugins/openseo/skills/local-seo/SKILL.md b/plugins/openseo/skills/local-seo/SKILL.md
index 5794061c..534762f1 100644
--- a/plugins/openseo/skills/local-seo/SKILL.md
+++ b/plugins/openseo/skills/local-seo/SKILL.md
@@ -49,7 +49,7 @@ Deliver through the `seo-report` skill, saving with `skill: "local-seo"`. If tha
3. Compare the user's listing against the top two competitors: primary category, additional categories, review count, hours completeness, photo count, claimed status. `search_local_businesses` rows usually carry all of this; use `get_business_profile` for what they lack.
4. Sanity-check each listing's website link (`url`/`contact_url` in the rows): it should deep-link to that location's page on the project domain, not a homepage or a stale domain. For broader on-page work, hand off to `run_site_audit`.
5. Call `get_business_reviews` for the user and the strongest competitor. Look at review volume, recency, average rating, and how many reviews got an owner reply.
-6. Run `get_local_rank_grid` for the main keyword. Use the grid to separate "ranks at the storefront only" from "ranks across the service area", and each point's `topResult` to name who wins where the target doesn't.
+6. Run `get_local_rank_grid` for the main keyword, and for each further keyword the user gave (same grid, same center; state the cost first). Use the grid to separate "ranks at the storefront only" from "ranks across the service area", and each point's `topResult` to name who wins where the target doesn't.
7. Add `get_google_business_questions` and `get_business_updates` when the profile basics are already competitive and the gap is engagement rather than setup.
8. Turn the evidence into a prioritized list. Category and claim problems outrank posting cadence every time.
@@ -71,11 +71,66 @@ Sections in this order:
1. **Snapshot** — one or two opening sentences, then a table of category, rating, review count, and claimed status. One row per location for a chain.
2. **The one fix** — one finding. Category and claim problems outrank posting cadence every time.
3. **Head to head** — a table of signal, this business, the best competitor, and the gap. Cover categories, reviews (count, recency, owner replies), hours and profile completeness, and the listing's website link.
-4. **Maps coverage** — what the grid shows, where visibility drops off, and who wins there. A bar chart of ranks by direction reads faster than a paragraph; label every value.
+4. **Maps coverage** — the grid drawn as described in "Drawing the grid" below, its four stat blocks, then what it shows: where visibility drops off, in which direction, and who wins there.
5. **Q&A and posting** — only when the basics are already competitive.
6. **What to do next** — an ordered list.
7. **How this report was made** — opens with the skill link line from `seo-report`, pointing at `https://openseo.so/docs/skills/local-seo` ("OpenSEO Local SEO skill"), then which tools returned what, plus a note reading each missing grid rank against that point's `resultsCount` rather than calling it invisibility.
+## Drawing the grid
+
+Local rank trackers (SE Ranking, Local Falcon, BrightLocal) all draw the same picture: numbered circles laid out as the grid, colored by position, with the storefront marked. Reproduce that picture so readers who know those tools recognize it. The figure carries two things: the grid's data, which the viewer draws as a live Google Map, and an inline SVG drawing of the same grid, which readers see in print, in an exported PDF, and wherever the map cannot load.
+
+**Value per point.** With one keyword, the rank. With several keywords, the average position across them as a decimal with one place (3.5), the way SE Ranking collapses many keywords into one map. A keyword that searched a point and did not find the business (`rank` null, no `error`) counts as 21 in that point's average, so ranks 1 and not found average 11.0. A value over 20 prints as "20+", which only happens when no keyword found the business there. A keyword whose search failed at a point (`error: true`) has no position there: leave it out of that point's value and out of every stat below.
+
+**Color scale.** Fixed, never restyled per report:
+
+| Value | Fill | Number |
+| --------- | --------- | ------- |
+| 1–3 | `#3F9D4E` | white |
+| over 3–5 | `#8BC34A` | white |
+| over 5–7 | `#F2C94C` | `#2A1E05` |
+| over 7–10 | `#F28C28` | white |
+| over 10–15 | `#E23B3B` | white |
+| over 15–20 | `#A31515` | white |
+| not found | `#A3ADB8` | white |
+
+**The SVG.** North up, west left, one circle per grid point on a 120-unit pitch with radius 22, so a 3x3 uses `viewBox="0 0 360 400"` and a 5x5 `viewBox="0 0 600 640"`. Set `width` to 360 for a 3x3 and 480 for a 5x5 so the drawing does not stretch to the column; the template already caps it at 100% on a phone. Print the value inside each circle (bold, 15px, centered with `text-anchor="middle"` and `dominant-baseline="central"`). Give the storefront circle a second ring: the same circle again with `fill="none"`, a 2px dark stroke, radius 27. Add an "N" label above the top row and the spacing under the bottom row ("2 km between points"). Then a `figcaption` that lists every value as text in reading order, because a chart never carries a number that is not also written out. First row of a 3x3, for the agent to repeat:
+
+```html
+<svg viewBox="0 0 360 400" width="360" role="img" aria-label="Rank grid, 3 by 3, 2 km spacing">
+<text x="180" y="18" text-anchor="middle" font-size="12" fill="#8f8f8f">N</text>
+<circle cx="60" cy="80" r="22" fill="#3F9D4E"/><text x="60" y="80" text-anchor="middle" dominant-baseline="central" font-size="15" font-weight="700" fill="#fff">3.0</text>
+<circle cx="180" cy="80" r="22" fill="#8BC34A"/><text x="180" y="80" text-anchor="middle" dominant-baseline="central" font-size="15" font-weight="700" fill="#fff">3.5</text>
+<circle cx="300" cy="80" r="22" fill="#8BC34A"/><text x="300" y="80" text-anchor="middle" dominant-baseline="central" font-size="15" font-weight="700" fill="#fff">3.5</text>
+<!-- rows 2 and 3 at cy 200 and 320; the storefront (cx 180, cy 200) also gets: -->
+<circle cx="180" cy="200" r="27" fill="none" stroke="#0a0a0a" stroke-width="2"/>
+<text x="180" y="372" text-anchor="middle" font-size="12" fill="#8f8f8f">2 km between points</text>
+</svg>
+```
+
+The `figcaption` lists every value in reading order: "Average position across 2 keywords. NW 3.0, N 3.5, NE 3.5, W 3.0, storefront 1.5, E 3.5, SW 4.5, S 4.5, SE 3.5."
+
+**Four stat blocks** beside or under the drawing, each a heading and a number or short list:
+
+1. Avg. position: the mean of the point values, two decimals.
+2. Rankings distribution: how many point values are 3 or better, over 3 to 10, over 10 to 20, and 20+, as a `.bars` chart.
+3. Avg. position per keyword: one row per keyword with its mean and how many of its points were top 3.
+4. Who ranks #1 most often: count each point's `topResult` across all keywords and list businesses by share.
+
+**Reading it.** Say where visibility drops off by compass direction and by distance ("2 km south, around 75th St" when the user has given you a landmark; otherwise the direction alone), and name who wins there from `topResult`. Proximity to a rival's storefront explains most drop-offs; say so when the rival's coordinate confirms it.
+
+**The figure.** Always wrap the drawing in a widget figure. The viewer renders it as a live Google Map fitted to the grid, with a keyword filter and a popup per point, and hides the SVG while the map is showing:
+
+```html
+<figure data-widget="rank-grid">
+<script type="application/json">{"spacingKm":1,"keywords":[{"keyword":"italian restaurant","points":[{"row":0,"col":0,"lat":41.7918,"lng":-88.1714,"rank":3,"top":"La Sorella di Francesca"}]}]}</script>
+<svg …the drawing above…</svg>
+<figcaption>…</figcaption>
+</figure>
+```
+
+Every point the tool returned goes in `points`: its `row` and `col`, `latitude` as `lat`, `longitude` as `lng`, `rank` (`null` when the business was not found there) and `topResult.title` as `top`. Leave out a point whose search failed (`error: true`); the viewer shows that keyword as "search failed" there. One entry in `keywords` per grid you ran, all with the same center and spacing. The block is data: no comments, no trailing commas, nothing computed.
+
## Guardrails
- Do not run a 5x5 grid, or grids for several keywords, without telling the user the cost first — every point is a paid SERP call.
diff --git a/plugins/openseo/skills/seo-report/SKILL.md b/plugins/openseo/skills/seo-report/SKILL.md
index e539bf84..104bcc09 100644
--- a/plugins/openseo/skills/seo-report/SKILL.md
+++ b/plugins/openseo/skills/seo-report/SKILL.md
@@ -57,7 +57,7 @@ These are enforced by the viewer, not by taste. A report that breaks them render
- **No external resources of any kind.** No web fonts, no CDN scripts or stylesheets, no images by URL, no `fetch`. Every request from a saved report is blocked. Inline all CSS in one `<style>` block.
- **Links open in a new tab.** Write every link as `<a href="..." target="_blank" rel="noopener">`. A plain link would navigate the report frame itself, replacing the report with a broken copy of the target. The exception is an in-page anchor (`href="#id"`, as in the contents rail), which stays in the document.
-- **No `<script>`.** Scripts are blocked outright. Anything interactive has to be static.
+- **No executable `<script>`.** A report's own scripts never run, however they are written. The one interactive element is a widget the viewer renders itself from a `<script type="application/json">` data block inside a `<figure data-widget="…">` (the rank grid in `local-seo` is the first). That block is data, not code, and it is the only `<script>` tag a report may contain.
- **Charts are inline SVG or CSS bars**, with real `<text>` labels and a `viewBox`. Always print the numbers next to the chart too.
- **Aim under 80 KB.** The hard cap is 500,000 bytes, and the error says "the limit is 500 KB". Inlined images are the usual way people blow it. A filled report is normally 10-30 KB.
- **No backticks and no `${` anywhere in the HTML.** Codex passes the argument through a JavaScript template literal, where both are syntax. Use `<code>` for inline code and plain text everywhere else.
@@ -251,6 +251,7 @@ footer{max-width:660px;margin:64px 0 0;padding:26px 0 0;border-top:1px solid var
- **`.note`** — one left-ruled callout for a caveat, a confidence limit, or something you could not verify. Two or three in a report, never a row of them.
- **`.tw` table** — every numeric column gets `class="n"` on both the `th` and the `td` so the digits line up. Keep tables to five columns or fewer, put the long-text column last, and keep cell text short; a wide table scrolls on a phone and clips in print.
- **`figure` + `.bars`** — one small bar chart where a comparison reads faster than a sentence. One row per item: `.label`, a `.track` holding a `.bar` whose inline width is the value as a percentage of the largest, and `.value`. Inline SVG is fine for anything that is not a bar chart; give it a `viewBox` and real `<text>` labels.
+- **Widget figure** — a `figure` with a `data-widget` name, a JSON data block the viewer reads, the static drawing as the fallback, and a `figcaption`. Only the widgets a skill documents exist; the viewer ignores any other name and shows the fallback.
- **`hr` then a closing `h2`** — the "What to do next" list, ordered, shortest useful.
- **How this report was made** — the last `h2`: the skill link line, then Tools and Verified bullets. See the section above.
- **`footer`** — one line: the sign-off and the data date. Method detail belongs in the closing section, not here.
diff --git a/src/report-widgets/rank-grid.ts b/src/report-widgets/rank-grid.ts
new file mode 100644
index 00000000..75ee0856
--- /dev/null
+++ b/src/report-widgets/rank-grid.ts
@@ -0,0 +1,394 @@
+import L from "leaflet";
+import leafletCss from "leaflet/dist/leaflet.css?inline";
+import googleMapsLogo from "../client/features/local-seo/google-maps-logo.svg";
+import {
+ readMapGrant,
+ REPORT_MAP_HEIGHT,
+ REPORT_MAP_PADDING,
+} from "../shared/report-map";
+
+// The rank-grid report widget: turns a declarative block a skill wrote into
+// the Maps grid, the way local rank trackers draw it. The view is fixed on the
+// grid, like a rank tracker's report: no zoom, no panning. This bundle
+// is the only script a report may run (see src/shared/report-sandbox.ts), so
+// it reads data from the page and never evaluates anything found there.
+//
+// The block it looks for:
+//
+// <figure data-widget="rank-grid">
+// <script type="application/json">{ ...RankGridConfig }</script>
+// <svg>…static fallback…</svg>
+// <figcaption>…</figcaption>
+// </figure>
+//
+// The fallback stays in the document (hidden once the map is up) so an export
+// or a viewer without scripts still shows the grid. So does a document served
+// without a map grant (no Google Maps key on this deployment, or a grid too
+// big to be one): there is no map to draw it on.
+
+type GridPoint = {
+ row: number;
+ col: number;
+ lat: number;
+ lng: number;
+ rank: number | null;
+ top?: string | null;
+};
+
+type GridKeyword = { keyword: string; points: GridPoint[] };
+
+type RankGridConfig = {
+ spacingKm?: number;
+ keywords: GridKeyword[];
+};
+
+const ALL = "__all__";
+const NOT_FOUND_VALUE = 21;
+
+const STYLE = `
+.osw{margin:0 0 30px}
+.osw-bar{display:flex;flex-wrap:wrap;gap:8px;align-items:center;margin:0 0 10px;font-size:14px}
+.osw-bar:empty{display:none}
+.osw-bar label{display:inline-flex;align-items:center;gap:6px;color:#454545}
+.osw-bar select{font:inherit;font-size:14px;padding:5px 9px;border:1px solid #dcdcdc;border-radius:6px;background:#fff;color:#0a0a0a}
+.osw-map{height:${REPORT_MAP_HEIGHT}px;max-height:70vh;border:1px solid #ebebeb;border-radius:8px;background:#f2f4f3}
+.osw-legend{display:flex;flex-wrap:wrap;gap:6px 14px;font-size:13px;color:#454545;margin-top:8px}
+.osw-sw{display:inline-block;width:11px;height:11px;border-radius:50%;margin-right:5px;vertical-align:-1px}
+.osw-pin{width:34px;height:34px;border-radius:50%;display:grid;place-items:center;font:700 13px ui-monospace,Menlo,monospace;color:#fff;border:2px solid #fff;box-shadow:0 1px 4px rgba(0,0,0,.35);cursor:pointer}
+.osw-pin.dec{font-size:12px}
+.osw-pin.home{box-shadow:0 0 0 3px #fff,0 0 0 5px #0a0a0a,0 1px 4px rgba(0,0,0,.35)}
+.osw-pop b{font-weight:600}
+.osw-pop table{border-collapse:collapse;width:auto;min-width:0;font-size:13px;margin-top:6px}
+.osw-pop td{padding:3px 10px 3px 0;border:0;vertical-align:top;color:#0a0a0a}
+.osw-pop td:first-child{color:#454545}
+.osw-pop td:nth-child(2){font-family:ui-monospace,Menlo,monospace;font-weight:600;white-space:nowrap}
+.osw-pop tr+tr td{border-top:1px solid #ebebeb}
+.osw .leaflet-overlay-pane svg{max-width:none}
+.osw .leaflet-div-icon{background:transparent;border:0}
+.osw .leaflet-popup-content{margin:12px 14px;font-size:13.5px;line-height:1.45}
+.osw .leaflet-container{font-family:inherit}
+.osw-logo img{display:block;width:59px;height:18px}
+.osw .leaflet-control-attribution{font-size:11px}
+.osw-fallback{display:none}
+@media print{.osw{display:none}.osw-fallback{display:block}}
+`;
+
+const BANDS: Array<[max: number, fill: string, ink: string, label: string]> = [
+ [3, "#3F9D4E", "#fff", "1–3"],
+ [5, "#8BC34A", "#fff", "3–5"],
+ [7, "#F2C94C", "#2A1E05", "5–7"],
+ [10, "#F28C28", "#fff", "7–10"],
+ [15, "#E23B3B", "#fff", "10–15"],
+ [20, "#A31515", "#fff", "15–20"],
+ [Infinity, "#A3ADB8", "#fff", "20+"],
+];
+
+function band(value: number) {
+ return BANDS.find(([max]) => value <= max) ?? BANDS[BANDS.length - 1];
+}
+
+function formatValue(value: number): string {
+ if (value > 20) return "20+";
+ return Number.isInteger(value) ? String(value) : value.toFixed(1);
+}
+
+function isFiniteNumber(v: unknown): v is number {
+ return typeof v === "number" && Number.isFinite(v);
+}
+
+function isRecord(v: unknown): v is Record<string, unknown> {
+ return typeof v === "object" && v !== null;
+}
+
+function parseConfig(raw: string): RankGridConfig | null {
+ let data: unknown;
+ try {
+ data = JSON.parse(raw);
+ } catch {
+ return null;
+ }
+ if (!isRecord(data)) return null;
+ const cfg = data;
+ if (!Array.isArray(cfg.keywords) || cfg.keywords.length === 0) return null;
+ const keywords: GridKeyword[] = [];
+ for (const kw of cfg.keywords) {
+ if (
+ !isRecord(kw) ||
+ typeof kw.keyword !== "string" ||
+ !Array.isArray(kw.points)
+ )
+ return null;
+ const points: GridPoint[] = [];
+ for (const pt of kw.points) {
+ if (
+ !isRecord(pt) ||
+ !isFiniteNumber(pt.row) ||
+ !isFiniteNumber(pt.col) ||
+ !isFiniteNumber(pt.lat) ||
+ !isFiniteNumber(pt.lng)
+ )
+ return null;
+ points.push({
+ row: pt.row,
+ col: pt.col,
+ lat: pt.lat,
+ lng: pt.lng,
+ rank: isFiniteNumber(pt.rank) ? pt.rank : null,
+ top: typeof pt.top === "string" ? pt.top : null,
+ });
+ }
+ keywords.push({ keyword: kw.keyword, points });
+ }
+ return {
+ spacingKm: isFiniteNumber(cfg.spacingKm) ? cfg.spacingKm : undefined,
+ keywords,
+ };
+}
+
+function el<K extends keyof HTMLElementTagNameMap>(
+ tag: K,
+ className?: string,
+ text?: string,
+): HTMLElementTagNameMap[K] {
+ const node = document.createElement(tag);
+ if (className) node.className = className;
+ if (text !== undefined) node.textContent = text;
+ return node;
+}
+
+function pointKey(p: GridPoint) {
+ return `${p.row},${p.col}`;
+}
+
+// Google requires its logo on the map and the copyright line for whatever is
+// on screen, refreshed as the map moves.
+function addGoogleAttribution(map: L.Map, grant: string) {
+ const Logo = L.Control.extend({
+ onAdd: () => {
+ const box = el("div", "osw-logo");
+ const img = el("img");
+ // oxlint-disable-next-line typescript-eslint/no-unsafe-assignment -- the lint program excludes this browser bundle; tsconfig.report-widgets.json types the import
+ img.src = googleMapsLogo;
+ img.alt = "Google Maps";
+ box.appendChild(img);
+ return box;
+ },
+ });
+ new Logo({ position: "bottomleft" }).addTo(map);
+
+ let shown = "";
+ const refresh = () => {
+ const bounds = map.getBounds();
+ const query = new URLSearchParams({
+ zoom: String(Math.round(map.getZoom())),
+ north: String(Math.min(85.05, bounds.getNorth())),
+ south: String(Math.max(-85.05, bounds.getSouth())),
+ east: String(map.wrapLatLng(bounds.getNorthEast()).lng),
+ west: String(map.wrapLatLng(bounds.getSouthWest()).lng),
+ });
+ void fetch(`/report-map/${grant}/copyright?${query}`)
+ .then((response) => response.json())
+ .catch(() => null)
+ .then((data: unknown) => {
+ const text =
+ isRecord(data) && typeof data.copyright === "string"
+ ? data.copyright
+ : "Map data ©Google";
+ if (text === shown) return;
+ if (shown) map.attributionControl.removeAttribution(shown);
+ map.attributionControl.addAttribution(text);
+ shown = text;
+ });
+ };
+ map.on("moveend", refresh);
+ refresh();
+}
+
+function render(figure: HTMLElement, cfg: RankGridConfig, grant: string) {
+ // The proxy only serves tiles at the grant's zooms, inside its area. Both
+ // are sized for this widget's fitted view at any width.
+ const granted = readMapGrant(grant);
+ if (!granted) return;
+ const wrap = el("div", "osw");
+ const bar = el("div", "osw-bar");
+ const mapEl = el("div", "osw-map");
+ const legend = el("div", "osw-legend");
+ wrap.append(bar, mapEl, legend);
+
+ const fallback = figure.querySelector("svg");
+ const caption = figure.querySelector("figcaption");
+ if (caption) figure.insertBefore(wrap, caption);
+ else figure.appendChild(wrap);
+ // Print gets the drawing back: tiles may not have loaded when the print
+ // dialog snapshots the page, and the drawing is what a PDF should carry.
+ if (fallback) fallback.classList.add("osw-fallback");
+
+ // Every distinct point across keywords, keyed by grid cell.
+ const cells = new Map<string, GridPoint>();
+ for (const k of cfg.keywords)
+ for (const p of k.points)
+ if (!cells.has(pointKey(p))) cells.set(pointKey(p), p);
+ const points = [...cells.values()];
+ if (points.length === 0) return;
+
+ const rows = points.map((p) => p.row);
+ const cols = points.map((p) => p.col);
+ const midRow = (Math.min(...rows) + Math.max(...rows)) / 2;
+ const midCol = (Math.min(...cols) + Math.max(...cols)) / 2;
+ const bounds = L.latLngBounds(points.map((p) => [p.lat, p.lng]));
+
+ // A keyword with no entry at a point had its search fail there (the skill
+ // leaves it out), so it counts toward nothing rather than as a miss.
+ const valueAt = (p: GridPoint, selected: string): number | null => {
+ const ranks = cfg.keywords
+ .filter((k) => selected === ALL || k.keyword === selected)
+ .flatMap((k) => k.points.filter((q) => pointKey(q) === pointKey(p)))
+ .map((q) => q.rank ?? NOT_FOUND_VALUE);
+ if (ranks.length === 0) return null;
+ return ranks.reduce((s, r) => s + r, 0) / ranks.length;
+ };
+
+ const map = L.map(mapEl, {
+ minZoom: granted.minZoom,
+ maxZoom: granted.maxZoom,
+ zoomSnap: 0.5,
+ zoomControl: false,
+ dragging: false,
+ touchZoom: false,
+ doubleClickZoom: false,
+ scrollWheelZoom: false,
+ boxZoom: false,
+ keyboard: false,
+ attributionControl: true,
+ });
+ map.attributionControl.setPrefix(false);
+ // The whole grid in the middle of the map with room around it. Refit when
+ // the map's size changes, so a narrow column never clips the outer points,
+ // and when a popup closes, since opening one may have panned the map.
+ const fit = () =>
+ map.fitBounds(bounds, {
+ padding: [REPORT_MAP_PADDING, REPORT_MAP_PADDING],
+ animate: false,
+ });
+ fit();
+ new ResizeObserver(() => {
+ map.invalidateSize({ animate: false });
+ fit();
+ }).observe(mapEl);
+ map.on("popupclose", fit);
+ L.tileLayer(`/report-map/${grant}/{z}/{x}/{y}`).addTo(map);
+ addGoogleAttribution(map, grant);
+
+ L.rectangle(bounds, {
+ color: "#17202a",
+ weight: 1,
+ dashArray: "4 4",
+ fill: false,
+ opacity: 0.55,
+ interactive: false,
+ }).addTo(map);
+
+ const markers: L.Marker[] = [];
+ const draw = (selected: string) => {
+ for (const m of markers) m.remove();
+ markers.length = 0;
+ for (const p of points) {
+ const v = valueAt(p, selected);
+ if (v === null) continue;
+ const [, fill, ink] = band(v);
+ const isHome = p.row === midRow && p.col === midCol;
+ const decimal = selected === ALL && cfg.keywords.length > 1;
+ const icon = L.divIcon({
+ className: "leaflet-div-icon",
+ html: `<div class="osw-pin${decimal ? " dec" : ""}${isHome ? " home" : ""}" style="background:${fill};color:${ink}">${formatValue(v)}</div>`,
+ iconSize: [34, 34],
+ iconAnchor: [17, 17],
+ });
+ const marker = L.marker([p.lat, p.lng], { icon, keyboard: true }).addTo(
+ map,
+ );
+ const pop = el("div", "osw-pop");
+ const head = el(
+ "b",
+ undefined,
+ isHome ? "Storefront" : `Point ${p.row + 1},${p.col + 1}`,
+ );
+ const coords = el(
+ "span",
+ undefined,
+ ` · ${p.lat.toFixed(4)}, ${p.lng.toFixed(4)}`,
+ );
+ const table = el("table");
+ for (const k of cfg.keywords) {
+ const q = k.points.find((c) => pointKey(c) === pointKey(p));
+ const tr = el("tr");
+ tr.append(
+ el("td", undefined, k.keyword),
+ el(
+ "td",
+ undefined,
+ !q ? "search failed" : q.rank == null ? "not found" : `#${q.rank}`,
+ ),
+ el("td", undefined, q?.top ? `#1 ${q.top}` : ""),
+ );
+ table.appendChild(tr);
+ }
+ pop.append(head, coords, table);
+ marker.bindPopup(pop, { maxWidth: 320 });
+ markers.push(marker);
+ }
+ };
+
+ if (cfg.keywords.length > 1) {
+ const label = el("label", undefined, "Keywords ");
+ const select = el("select");
+ select.append(new Option("All keywords (avg. position)", ALL));
+ for (const k of cfg.keywords)
+ select.append(new Option(k.keyword, k.keyword));
+ select.addEventListener("change", () => draw(select.value));
+ label.appendChild(select);
+ bar.appendChild(label);
+ }
+
+ for (const [, fill, , label] of BANDS) {
+ const item = el("span");
+ const sw = el("i", "osw-sw");
+ sw.style.background = fill;
+ item.append(sw, document.createTextNode(label));
+ legend.appendChild(item);
+ }
+ const hint = el(
+ "span",
+ undefined,
+ cfg.spacingKm
+ ? `${cfg.spacingKm} km between points · ring marks the storefront`
+ : "ring marks the storefront",
+ );
+ legend.appendChild(hint);
+
+ draw(cfg.keywords.length > 1 ? ALL : cfg.keywords[0].keyword);
+}
+
+// The tag is `defer`, so the document is parsed by now, and currentScript is
+// still this tag.
+function boot() {
+ const script = document.currentScript;
+ const grant =
+ script instanceof HTMLScriptElement ? script.dataset.mapGrant : undefined;
+ if (!grant) return;
+ const figures = document.querySelectorAll<HTMLElement>(
+ 'figure[data-widget="rank-grid"]',
+ );
+ if (figures.length === 0) return;
+ const style = document.createElement("style");
+ style.textContent = leafletCss + STYLE;
+ document.head.appendChild(style);
+ for (const figure of figures) {
+ const data = figure.querySelector('script[type="application/json"]');
+ const cfg = data?.textContent ? parseConfig(data.textContent) : null;
+ if (!cfg) continue;
+ render(figure, cfg, grant);
+ }
+}
+
+boot();
diff --git a/src/routeTree.gen.ts b/src/routeTree.gen.ts
index c10efea7..88ff9aad 100644
--- a/src/routeTree.gen.ts
+++ b/src/routeTree.gen.ts
@@ -42,6 +42,7 @@ import { Route as AppSettingsOrganizationRouteImport } from './routes/_app/setti
import { Route as AuthenticatedOnboardingIndexRouteImport } from './routes/_authenticated.onboarding.index'
import { Route as ApiAuthSplatRouteImport } from './routes/api/auth/$'
import { Route as ApiAutumnSplatRouteImport } from './routes/api/autumn/$'
+import { Route as ReportMapGrantCopyrightRouteImport } from './routes/report-map/$grant/copyright'
import { Route as STokenIndexRouteImport } from './routes/s/$token/index'
import { Route as STokenOgDotpngRouteImport } from './routes/s/$token/og[.]png'
import { Route as STokenRawRouteImport } from './routes/s/$token/raw'
@@ -74,6 +75,7 @@ import { Route as AppPProjectIdReportsTemplatesRouteImport } from './routes/_app
import { Route as AppPProjectIdSettingsIndexRouteImport } from './routes/_app/p/$projectId/settings/index'
import { Route as AppPProjectIdSettingsContextRouteImport } from './routes/_app/p/$projectId/settings/context'
import { Route as AppPProjectIdSettingsIntegrationsRouteImport } from './routes/_app/p/$projectId/settings/integrations'
+import { Route as ReportMapGrantZXYRouteImport } from './routes/report-map/$grant/$z/$x/$y'
import { Route as AppPProjectIdAiVisibilityPromptsPromptIdRouteImport } from './routes/_app/p/$projectId/ai-visibility/prompts/$promptId'
import { Route as AppPProjectIdAuditIssuesResultIdRouteImport } from './routes/_app/p/$projectId/audit/issues/$resultId'
import { Route as ApiLocalSeoMapsProjectIdZXYRouteImport } from './routes/api/local-seo/maps/$projectId/$z/$x/$y'
@@ -244,6 +246,11 @@ const ApiAutumnSplatRoute = ApiAutumnSplatRouteImport.update({
path: '/api/autumn/$',
getParentRoute: () => rootRouteImport,
} as any)
+const ReportMapGrantCopyrightRoute = ReportMapGrantCopyrightRouteImport.update({
+ id: '/report-map/$grant/copyright',
+ path: '/report-map/$grant/copyright',
+ getParentRoute: () => rootRouteImport,
+} as any)
const STokenIndexRoute = STokenIndexRouteImport.update({
id: '/s/$token/',
path: '/s/$token/',
@@ -421,6 +428,11 @@ const AppPProjectIdSettingsIntegrationsRoute =
path: '/integrations',
getParentRoute: () => AppPProjectIdSettingsRoute,
} as any)
+const ReportMapGrantZXYRoute = ReportMapGrantZXYRouteImport.update({
+ id: '/report-map/$grant/$z/$x/$y',
+ path: '/report-map/$grant/$z/$x/$y',
+ getParentRoute: () => rootRouteImport,
+} as any)
const AppPProjectIdAiVisibilityPromptsPromptIdRoute =
AppPProjectIdAiVisibilityPromptsPromptIdRouteImport.update({
id: '/prompts/$promptId',
@@ -469,6 +481,7 @@ export interface FileRoutesByFullPath {
'/settings/organization': typeof AppSettingsOrganizationRoute
'/api/auth/$': typeof ApiAuthSplatRoute
'/api/autumn/$': typeof ApiAutumnSplatRoute
+ '/report-map/$grant/copyright': typeof ReportMapGrantCopyrightRoute
'/s/$token/og.png': typeof STokenOgDotpngRoute
'/s/$token/raw': typeof STokenRawRoute
'/settings/': typeof AppSettingsIndexRoute
@@ -497,6 +510,7 @@ export interface FileRoutesByFullPath {
'/p/$projectId/reports/templates': typeof AppPProjectIdReportsTemplatesRoute
'/p/$projectId/settings/context': typeof AppPProjectIdSettingsContextRoute
'/p/$projectId/settings/integrations': typeof AppPProjectIdSettingsIntegrationsRoute
+ '/report-map/$grant/$z/$x/$y': typeof ReportMapGrantZXYRoute
'/p/$projectId/ai-visibility/': typeof AppPProjectIdAiVisibilityIndexRoute
'/p/$projectId/audit/': typeof AppPProjectIdAuditIndexRoute
'/p/$projectId/local-seo/': typeof AppPProjectIdLocalSeoIndexRoute
@@ -534,6 +548,7 @@ export interface FileRoutesByTo {
'/settings/organization': typeof AppSettingsOrganizationRoute
'/api/auth/$': typeof ApiAuthSplatRoute
'/api/autumn/$': typeof ApiAutumnSplatRoute
+ '/report-map/$grant/copyright': typeof ReportMapGrantCopyrightRoute
'/s/$token/og.png': typeof STokenOgDotpngRoute
'/s/$token/raw': typeof STokenRawRoute
'/settings': typeof AppSettingsIndexRoute
@@ -558,6 +573,7 @@ export interface FileRoutesByTo {
'/p/$projectId/reports/templates': typeof AppPProjectIdReportsTemplatesRoute
'/p/$projectId/settings/context': typeof AppPProjectIdSettingsContextRoute
'/p/$projectId/settings/integrations': typeof AppPProjectIdSettingsIntegrationsRoute
+ '/report-map/$grant/$z/$x/$y': typeof ReportMapGrantZXYRoute
'/p/$projectId/ai-visibility': typeof AppPProjectIdAiVisibilityIndexRoute
'/p/$projectId/audit': typeof AppPProjectIdAuditIndexRoute
'/p/$projectId/local-seo': typeof AppPProjectIdLocalSeoIndexRoute
@@ -601,6 +617,7 @@ export interface FileRoutesById {
'/_app/settings/organization': typeof AppSettingsOrganizationRoute
'/api/auth/$': typeof ApiAuthSplatRoute
'/api/autumn/$': typeof ApiAutumnSplatRoute
+ '/report-map/$grant/copyright': typeof ReportMapGrantCopyrightRoute
'/s/$token/og.png': typeof STokenOgDotpngRoute
'/s/$token/raw': typeof STokenRawRoute
'/_app/settings/': typeof AppSettingsIndexRoute
@@ -629,6 +646,7 @@ export interface FileRoutesById {
'/_app/p/$projectId/reports/templates': typeof AppPProjectIdReportsTemplatesRoute
'/_app/p/$projectId/settings/context': typeof AppPProjectIdSettingsContextRoute
'/_app/p/$projectId/settings/integrations': typeof AppPProjectIdSettingsIntegrationsRoute
+ '/report-map/$grant/$z/$x/$y': typeof ReportMapGrantZXYRoute
'/_app/p/$projectId/ai-visibility/': typeof AppPProjectIdAiVisibilityIndexRoute
'/_app/p/$projectId/audit/': typeof AppPProjectIdAuditIndexRoute
'/_app/p/$projectId/local-seo/': typeof AppPProjectIdLocalSeoIndexRoute
@@ -670,6 +688,7 @@ export interface FileRouteTypes {
| '/settings/organization'
| '/api/auth/$'
| '/api/autumn/$'
+ | '/report-map/$grant/copyright'
| '/s/$token/og.png'
| '/s/$token/raw'
| '/settings/'
@@ -698,6 +717,7 @@ export interface FileRouteTypes {
| '/p/$projectId/reports/templates'
| '/p/$projectId/settings/context'
| '/p/$projectId/settings/integrations'
+ | '/report-map/$grant/$z/$x/$y'
| '/p/$projectId/ai-visibility/'
| '/p/$projectId/audit/'
| '/p/$projectId/local-seo/'
@@ -735,6 +755,7 @@ export interface FileRouteTypes {
| '/settings/organization'
| '/api/auth/$'
| '/api/autumn/$'
+ | '/report-map/$grant/copyright'
| '/s/$token/og.png'
| '/s/$token/raw'
| '/settings'
@@ -759,6 +780,7 @@ export interface FileRouteTypes {
| '/p/$projectId/reports/templates'
| '/p/$projectId/settings/context'
| '/p/$projectId/settings/integrations'
+ | '/report-map/$grant/$z/$x/$y'
| '/p/$projectId/ai-visibility'
| '/p/$projectId/audit'
| '/p/$projectId/local-seo'
@@ -801,6 +823,7 @@ export interface FileRouteTypes {
| '/_app/settings/organization'
| '/api/auth/$'
| '/api/autumn/$'
+ | '/report-map/$grant/copyright'
| '/s/$token/og.png'
| '/s/$token/raw'
| '/_app/settings/'
@@ -829,6 +852,7 @@ export interface FileRouteTypes {
| '/_app/p/$projectId/reports/templates'
| '/_app/p/$projectId/settings/context'
| '/_app/p/$projectId/settings/integrations'
+ | '/report-map/$grant/$z/$x/$y'
| '/_app/p/$projectId/ai-visibility/'
| '/_app/p/$projectId/audit/'
| '/_app/p/$projectId/local-seo/'
@@ -856,11 +880,13 @@ export interface RootRouteChildren {
RReportIdRoute: typeof RReportIdRoute
ApiAuthSplatRoute: typeof ApiAuthSplatRoute
ApiAutumnSplatRoute: typeof ApiAutumnSplatRoute
+ ReportMapGrantCopyrightRoute: typeof ReportMapGrantCopyrightRoute
STokenOgDotpngRoute: typeof STokenOgDotpngRoute
STokenRawRoute: typeof STokenRawRoute
STokenIndexRoute: typeof STokenIndexRoute
ApiGa4OauthCallbackRoute: typeof ApiGa4OauthCallbackRoute
ApiGscOauthCallbackRoute: typeof ApiGscOauthCallbackRoute
+ ReportMapGrantZXYRoute: typeof ReportMapGrantZXYRoute
ApiLocalSeoMapsProjectIdZXYRoute: typeof ApiLocalSeoMapsProjectIdZXYRoute
}
@@ -1097,6 +1123,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof ApiAutumnSplatRouteImport
parentRoute: typeof rootRouteImport
}
+ '/report-map/$grant/copyright': {
+ id: '/report-map/$grant/copyright'
+ path: '/report-map/$grant/copyright'
+ fullPath: '/report-map/$grant/copyright'
+ preLoaderRoute: typeof ReportMapGrantCopyrightRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/s/$token/': {
id: '/s/$token/'
path: '/s/$token'
@@ -1321,6 +1354,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AppPProjectIdSettingsIntegrationsRouteImport
parentRoute: typeof AppPProjectIdSettingsRoute
}
+ '/report-map/$grant/$z/$x/$y': {
+ id: '/report-map/$grant/$z/$x/$y'
+ path: '/report-map/$grant/$z/$x/$y'
+ fullPath: '/report-map/$grant/$z/$x/$y'
+ preLoaderRoute: typeof ReportMapGrantZXYRouteImport
+ parentRoute: typeof rootRouteImport
+ }
'/_app/p/$projectId/ai-visibility/prompts/$promptId': {
id: '/_app/p/$projectId/ai-visibility/prompts/$promptId'
path: '/prompts/$promptId'
@@ -1554,11 +1594,13 @@ const rootRouteChildren: RootRouteChildren = {
RReportIdRoute: RReportIdRoute,
ApiAuthSplatRoute: ApiAuthSplatRoute,
ApiAutumnSplatRoute: ApiAutumnSplatRoute,
+ ReportMapGrantCopyrightRoute: ReportMapGrantCopyrightRoute,
STokenOgDotpngRoute: STokenOgDotpngRoute,
STokenRawRoute: STokenRawRoute,
STokenIndexRoute: STokenIndexRoute,
ApiGa4OauthCallbackRoute: ApiGa4OauthCallbackRoute,
ApiGscOauthCallbackRoute: ApiGscOauthCallbackRoute,
+ ReportMapGrantZXYRoute: ReportMapGrantZXYRoute,
ApiLocalSeoMapsProjectIdZXYRoute: ApiLocalSeoMapsProjectIdZXYRoute,
}
export const routeTree = rootRouteImport
diff --git a/src/routes/r/$reportId.ts b/src/routes/r/$reportId.ts
index a1600381..dae10dc1 100644
--- a/src/routes/r/$reportId.ts
+++ b/src/routes/r/$reportId.ts
@@ -5,6 +5,7 @@ import { resolveUserContextFromHeaders } from "@/middleware/ensure-user/resolve"
import { ProjectRepository } from "@/server/features/projects/repositories/ProjectRepository";
import { ReportRepository } from "@/server/features/reports/repositories/ReportRepository";
import { asAppError } from "@/server/lib/errors";
+import { createReportMapGrant } from "@/server/features/reports/reportMapGrant";
import { reportDocumentResponse, textResponse } from "@/shared/report-sandbox";
// The report viewer: the stored document, served byte for byte from the app's
@@ -85,6 +86,7 @@ async function handleReportRequest(
return reportDocumentResponse(html, {
print,
cacheControl: "private, no-store",
+ mapGrant: await createReportMapGrant(html),
});
}
diff --git a/src/routes/report-map/$grant/$z/$x/$y.ts b/src/routes/report-map/$grant/$z/$x/$y.ts
new file mode 100644
index 00000000..9ef047f1
--- /dev/null
+++ b/src/routes/report-map/$grant/$z/$x/$y.ts
@@ -0,0 +1,45 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { z } from "zod";
+import { GoogleMapsService } from "@/server/features/local-seo/services/GoogleMapsService";
+import {
+ grantCoversTile,
+ verifyReportMapGrant,
+} from "@/server/features/reports/reportMapGrant";
+import { REPORT_MAP_MAX_ZOOM } from "@/shared/report-map";
+
+// Map tiles for the rank-grid report widget. No session: a shared report's
+// reader has none, and the sandboxed frame sends no cookies anyway. The
+// signed grant in the path is the authorization, and it only covers the area
+// around the report's grid at the zooms its fitted view uses (see
+// reportMapGrant.ts).
+//
+// A raw-Response route with no `component`, so it stays out of the client
+// bundle; nothing navigates here, the widget's <img> tags do.
+
+const tileSchema = z
+ .object({
+ z: z.coerce.number().int().min(0).max(REPORT_MAP_MAX_ZOOM),
+ x: z.coerce.number().int().min(0),
+ y: z.coerce.number().int().min(0),
+ })
+ .refine(({ z: zoom, x, y }) => x < 2 ** zoom && y < 2 ** zoom);
+
+const refused = () =>
+ new Response("No such tile.", {
+ status: 404,
+ headers: { "Cache-Control": "no-store" },
+ });
+
+export const Route = createFileRoute("/report-map/$grant/$z/$x/$y")({
+ server: {
+ handlers: {
+ GET: async ({ params }) => {
+ const tile = tileSchema.safeParse(params);
+ if (!tile.success) return refused();
+ const scope = await verifyReportMapGrant(params.grant);
+ if (!scope || !grantCoversTile(tile.data, scope)) return refused();
+ return GoogleMapsService.getTile(tile.data.z, tile.data.x, tile.data.y);
+ },
+ },
+ },
+});
diff --git a/src/routes/report-map/$grant/copyright.ts b/src/routes/report-map/$grant/copyright.ts
new file mode 100644
index 00000000..9eabc6fa
--- /dev/null
+++ b/src/routes/report-map/$grant/copyright.ts
@@ -0,0 +1,44 @@
+import { createFileRoute } from "@tanstack/react-router";
+import { z } from "zod";
+import { GoogleMapsService } from "@/server/features/local-seo/services/GoogleMapsService";
+import { verifyReportMapGrant } from "@/server/features/reports/reportMapGrant";
+import { googleMapsViewportSchema } from "@/types/schemas/google-maps";
+
+// Google requires the map's copyright line for what is on screen, so the
+// widget asks for it each time the map moves. Same grant as the tiles. The
+// report frame has an opaque origin, so the answer is CORS-readable by any
+// origin; it is a copyright string, nothing more. On any failure the widget
+// shows a generic "Map data ©Google" line.
+
+const viewportQuerySchema = z.object({
+ zoom: z.coerce.number(),
+ north: z.coerce.number(),
+ south: z.coerce.number(),
+ east: z.coerce.number(),
+ west: z.coerce.number(),
+});
+
+const headers = {
+ "Access-Control-Allow-Origin": "*",
+ "Cache-Control": "no-store",
+};
+
+export const Route = createFileRoute("/report-map/$grant/copyright")({
+ server: {
+ handlers: {
+ GET: async ({ params, request }) => {
+ const query = Object.fromEntries(new URL(request.url).searchParams);
+ const viewport = viewportQuerySchema
+ .pipe(googleMapsViewportSchema)
+ .safeParse(query);
+ if (!viewport.success || !(await verifyReportMapGrant(params.grant)))
+ return Response.json(
+ { error: "Not found." },
+ { status: 404, headers },
+ );
+ const copyright = await GoogleMapsService.getCopyright(viewport.data);
+ return Response.json({ copyright }, { headers });
+ },
+ },
+ },
+});
diff --git a/src/routes/s/$token/raw.ts b/src/routes/s/$token/raw.ts
index b8a8581d..b3d02c1c 100644
--- a/src/routes/s/$token/raw.ts
+++ b/src/routes/s/$token/raw.ts
@@ -6,6 +6,7 @@ import {
sharesEnabled,
} from "@/server/features/reports/shareAccess";
import { captureServerEvent } from "@/server/lib/posthog";
+import { createReportMapGrant } from "@/server/features/reports/reportMapGrant";
import { reportDocumentResponse, textResponse } from "@/shared/report-sandbox";
import { sharePath } from "@/shared/report-share";
@@ -117,6 +118,7 @@ async function handleSharedReportRequest(
return reportDocumentResponse(html, {
cacheControl: EDGE_CACHE_CONTROL,
noindex: true,
+ mapGrant: await createReportMapGrant(html),
});
}
diff --git a/src/server/features/reports/reportMapGrant.test.ts b/src/server/features/reports/reportMapGrant.test.ts
new file mode 100644
index 00000000..67b6208d
--- /dev/null
+++ b/src/server/features/reports/reportMapGrant.test.ts
@@ -0,0 +1,63 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ createReportMapGrant,
+ grantCoversTile,
+ verifyReportMapGrant,
+} from "./reportMapGrant";
+
+const reportWithGrid = `<!doctype html><html><body>
+<figure data-widget="rank-grid"><script type="application/json">{"version":1,"center":{"lat":40.44,"lng":-79.99},"keywords":[{"keyword":"self storage","points":[{"row":0,"col":0,"lat":40.458,"lng":-80.013,"rank":3},{"row":2,"col":2,"lat":40.422,"lng":-79.967,"rank":null}]}]}</script><svg></svg></figure>
+</body></html>`;
+
+// Web-mercator tile at zoom 14 containing a coordinate.
+function tileAt(lat: number, lng: number, z = 14) {
+ const n = 2 ** z;
+ const rad = (lat * Math.PI) / 180;
+ return {
+ z,
+ x: Math.floor(((lng + 180) / 360) * n),
+ y: Math.floor(
+ ((1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2) * n,
+ ),
+ };
+}
+
+describe("report map grants", () => {
+ beforeEach(() => {
+ vi.stubEnv("GOOGLE_MAPS_API_KEY", "test-maps-key");
+ });
+
+ it("covers the report's grid and nothing far from it", async () => {
+ const grant = await createReportMapGrant(reportWithGrid);
+ const scope = await verifyReportMapGrant(grant ?? "");
+
+ expect(scope).not.toBeNull();
+ if (!scope) return;
+ expect(grantCoversTile(tileAt(40.44, -79.99), scope)).toBe(true);
+ // Philadelphia, ~400 km east.
+ expect(grantCoversTile(tileAt(39.95, -75.16), scope)).toBe(false);
+ });
+
+ it("covers only the zooms a fitted view of the grid uses", async () => {
+ const grant = await createReportMapGrant(reportWithGrid);
+ const scope = await verifyReportMapGrant(grant ?? "");
+
+ expect(scope).not.toBeNull();
+ if (!scope) return;
+ // The grid is ~4 km across, so street level is far past any fitted view.
+ expect(grantCoversTile(tileAt(40.44, -79.99, 18), scope)).toBe(false);
+ });
+
+ it("rejects a grant whose area was widened", async () => {
+ const grant = (await createReportMapGrant(reportWithGrid)) ?? "";
+ const widened = grant.replace(/^[^~]+/, "-80");
+
+ expect(await verifyReportMapGrant(widened)).toBeNull();
+ });
+
+ it("issues no grant without a Maps key", async () => {
+ vi.stubEnv("GOOGLE_MAPS_API_KEY", "");
+
+ expect(await createReportMapGrant(reportWithGrid)).toBeNull();
+ });
+});
diff --git a/src/server/features/reports/reportMapGrant.ts b/src/server/features/reports/reportMapGrant.ts
new file mode 100644
index 00000000..00709c65
--- /dev/null
+++ b/src/server/features/reports/reportMapGrant.ts
@@ -0,0 +1,243 @@
+import { Parser } from "htmlparser2";
+import { z } from "zod";
+import { getOptionalEnvValue } from "@/server/lib/runtime-env";
+import {
+ readMapGrant,
+ REPORT_MAP_HEIGHT,
+ REPORT_MAP_MAX_ZOOM,
+ REPORT_MAP_PADDING,
+ type MapArea,
+ type MapGrantScope,
+} from "@/shared/report-map";
+
+// Signed grants for the rank-grid widget's map (see src/shared/report-map.ts).
+// The grant is signed with the Maps key itself, so there is no extra secret to
+// configure, and a deployment without Google Maps issues no grants: its
+// reports keep the static grid drawing.
+
+// Long enough for a tab left open over a day, short enough that a grant
+// copied out of a report stops working.
+const GRANT_TTL_SECONDS = 24 * 60 * 60;
+
+// Around the grid, enough to fill the widget's fixed view on a wide screen:
+// one and a half times the grid's size on every side, and never less than
+// ~3 km.
+const PAD_GRID_SPANS = 1.5;
+const MIN_PAD_DEGREES = 0.03;
+
+// The space the widget fits the grid into, from a phone to a wide report
+// column. The height is fixed by the widget's CSS.
+const MIN_FIT_PX = 160;
+const MAX_FIT_WIDTH_PX = 1080;
+const MAX_FIT_HEIGHT_PX = REPORT_MAP_HEIGHT - 2 * REPORT_MAP_PADDING;
+
+const widgetPointsSchema = z.object({
+ keywords: z.array(
+ z.object({
+ points: z.array(
+ z.object({
+ lat: z.number().min(-85).max(85),
+ lng: z.number().min(-180).max(180),
+ }),
+ ),
+ }),
+ ),
+});
+
+// The JSON data block inside each rank-grid figure. A streaming parse, not a
+// regex: this runs on every view of a stored, user-written document, and a
+// backtracking pattern can be made to burn seconds of CPU per request.
+function widgetBlocks(html: string) {
+ const blocks: string[] = [];
+ let figureDepth = 0;
+ let inBlock = false;
+ let text = "";
+ const parser = new Parser({
+ onopentag(name, attributes) {
+ if (
+ name === "figure" &&
+ (figureDepth > 0 || attributes["data-widget"] === "rank-grid")
+ )
+ figureDepth++;
+ if (
+ figureDepth > 0 &&
+ name === "script" &&
+ attributes.type === "application/json"
+ ) {
+ inBlock = true;
+ text = "";
+ }
+ },
+ ontext(chunk) {
+ if (inBlock) text += chunk;
+ },
+ onclosetag(name) {
+ if (name === "script" && inBlock) {
+ inBlock = false;
+ blocks.push(text);
+ }
+ if (name === "figure" && figureDepth > 0) figureDepth--;
+ },
+ });
+ parser.end(html);
+ return blocks;
+}
+
+function gridPoints(html: string) {
+ const points: Array<{ lat: number; lng: number }> = [];
+ for (const block of widgetBlocks(html)) {
+ let data: unknown;
+ try {
+ data = JSON.parse(block);
+ } catch {
+ continue;
+ }
+ const parsed = widgetPointsSchema.safeParse(data);
+ if (!parsed.success) continue;
+ for (const keyword of parsed.data.keywords) points.push(...keyword.points);
+ }
+ return points;
+}
+
+function mapGrantScope(
+ points: Array<{ lat: number; lng: number }>,
+): MapGrantScope {
+ const lats = points.map((p) => p.lat);
+ const lngs = points.map((p) => p.lng);
+ const south = Math.min(...lats);
+ const north = Math.max(...lats);
+ const west = Math.min(...lngs);
+ const east = Math.max(...lngs);
+ const padLat = Math.max((north - south) * PAD_GRID_SPANS, MIN_PAD_DEGREES);
+ const padLng = Math.max((east - west) * PAD_GRID_SPANS, MIN_PAD_DEGREES);
+ return {
+ area: {
+ south: south - padLat,
+ west: west - padLng,
+ north: north + padLat,
+ east: east + padLng,
+ },
+ ...fittedZoomRange({ south, west, north, east }),
+ };
+}
+
+// Web-mercator y of a latitude, 0 at the top of the world and 1 at the bottom.
+function mercatorY(lat: number) {
+ const rad = (lat * Math.PI) / 180;
+ return (1 - Math.log(Math.tan(rad) + 1 / Math.cos(rad)) / Math.PI) / 2;
+}
+
+/**
+ * The tile zooms the widget can land on when it fits the grid into its view
+ * (Leaflet's fitBounds), across every view size it can have. The widget's view
+ * is fixed, so these few levels are all it ever loads.
+ */
+function fittedZoomRange(grid: MapArea) {
+ // The grid's size in pixels at zoom 0, where the world is 256 across.
+ const width = ((grid.east - grid.west) / 360) * 256;
+ const height = (mercatorY(grid.south) - mercatorY(grid.north)) * 256;
+ const fit = (w: number, h: number) =>
+ Math.log2(Math.min(w / width, h / height));
+ const clamp = (zoom: number) =>
+ Math.min(REPORT_MAP_MAX_ZOOM, Math.max(0, zoom));
+ return {
+ minZoom: clamp(Math.floor(fit(MIN_FIT_PX, MIN_FIT_PX))),
+ maxZoom: clamp(Math.ceil(fit(MAX_FIT_WIDTH_PX, MAX_FIT_HEIGHT_PX))),
+ };
+}
+
+function hmacKey(apiKey: string) {
+ return crypto.subtle.importKey(
+ "raw",
+ new TextEncoder().encode(`openseo:report-map:${apiKey}`),
+ { name: "HMAC", hash: "SHA-256" },
+ false,
+ ["sign", "verify"],
+ );
+}
+
+async function sign(payload: string, apiKey: string) {
+ const signature = await crypto.subtle.sign(
+ "HMAC",
+ await hmacKey(apiKey),
+ new TextEncoder().encode(payload),
+ );
+ return [...new Uint8Array(signature)]
+ .map((byte) => byte.toString(16).padStart(2, "0"))
+ .join("");
+}
+
+async function mapsKey() {
+ return (await getOptionalEnvValue("GOOGLE_MAPS_API_KEY"))?.trim() || null;
+}
+
+/** A grant for the area the report's rank grids cover, or null for none. */
+export async function createReportMapGrant(html: string) {
+ const apiKey = await mapsKey();
+ if (!apiKey) return null;
+ const points = gridPoints(html);
+ if (points.length === 0) return null;
+ const scope = mapGrantScope(points);
+ const expiresAt = Math.floor(Date.now() / 1000) + GRANT_TTL_SECONDS;
+ const payload = [
+ scope.area.south.toFixed(5),
+ scope.area.west.toFixed(5),
+ scope.area.north.toFixed(5),
+ scope.area.east.toFixed(5),
+ scope.minZoom,
+ scope.maxZoom,
+ expiresAt,
+ ].join("~");
+ return `${payload}~${await sign(payload, apiKey)}`;
+}
+
+/** What a grant covers, or null when it is forged or expired. */
+export async function verifyReportMapGrant(
+ grant: string,
+): Promise<MapGrantScope | null> {
+ const parsed = readMapGrant(grant);
+ if (!parsed || parsed.expiresAt * 1000 < Date.now()) return null;
+ const apiKey = await mapsKey();
+ if (!apiKey) return null;
+ if (!/^[0-9a-f]{64}$/.test(parsed.signature)) return null;
+ const signature = Uint8Array.from(
+ parsed.signature.match(/../g) ?? [],
+ (hex) => parseInt(hex, 16),
+ );
+ // verify() compares in constant time.
+ const valid = await crypto.subtle.verify(
+ "HMAC",
+ await hmacKey(apiKey),
+ signature,
+ new TextEncoder().encode(parsed.signed),
+ );
+ if (!valid) return null;
+ return {
+ area: parsed.area,
+ minZoom: parsed.minZoom,
+ maxZoom: parsed.maxZoom,
+ };
+}
+
+function tileLatitude(y: number, zoom: number) {
+ const n = Math.PI - (2 * Math.PI * y) / 2 ** zoom;
+ return (180 / Math.PI) * Math.atan(Math.sinh(n));
+}
+
+/** Whether a grant covers a web-mercator tile: one of its zooms, in its area. */
+export function grantCoversTile(
+ tile: { z: number; x: number; y: number },
+ { area, minZoom, maxZoom }: MapGrantScope,
+) {
+ if (tile.z < minZoom || tile.z > maxZoom) return false;
+ const west = (tile.x / 2 ** tile.z) * 360 - 180;
+ const east = ((tile.x + 1) / 2 ** tile.z) * 360 - 180;
+ const north = tileLatitude(tile.y, tile.z);
+ const south = tileLatitude(tile.y + 1, tile.z);
+ return (
+ west < area.east &&
+ east > area.west &&
+ south < area.north &&
+ north > area.south
+ );
+}
diff --git a/src/server/features/reports/reportRoute.test.ts b/src/server/features/reports/reportRoute.test.ts
index 64171943..bd8b6a73 100644
--- a/src/server/features/reports/reportRoute.test.ts
+++ b/src/server/features/reports/reportRoute.test.ts
@@ -80,7 +80,7 @@ describe("handleReportRequest", () => {
`<!doctype html><html><body>report<script>${PRINT_SCRIPT}</script></body></html>`,
);
expect(response.headers.get("content-security-policy")).toBe(
- reportCsp(true),
+ reportCsp({ print: true }),
);
});
diff --git a/src/shared/report-map.ts b/src/shared/report-map.ts
new file mode 100644
index 00000000..eed893e0
--- /dev/null
+++ b/src/shared/report-map.ts
@@ -0,0 +1,51 @@
+// The map behind the rank-grid report widget: Google Maps tiles, proxied
+// through /report-map so no key reaches a reader. A report is sandboxed and
+// may be read by anyone holding a share link, so the proxy cannot ask who is
+// reading. Instead the document response carries a signed grant naming the
+// one area the report's grid covers and the few zoom levels a fitted view of
+// it can land on, and the proxy serves those tiles only. Shared by the server,
+// which signs and checks grants, and by the widget, which fits its fixed view
+// inside the grant.
+
+/** The closest zoom the map offers: street level, not building level. */
+export const REPORT_MAP_MAX_ZOOM = 18;
+
+/** The widget map's CSS height; its width follows the report column. */
+export const REPORT_MAP_HEIGHT = 480;
+
+/** Pixels the widget keeps between the grid and each edge of its view. */
+export const REPORT_MAP_PADDING = 60;
+
+export type MapArea = {
+ south: number;
+ west: number;
+ north: number;
+ east: number;
+};
+
+export type MapGrantScope = {
+ area: MapArea;
+ minZoom: number;
+ maxZoom: number;
+};
+
+/**
+ * A grant is `south~west~north~east~minZoom~maxZoom~expiresAt~signature`:
+ * path-safe, so it goes straight into tile URLs. The signature covers
+ * everything before it.
+ */
+export function readMapGrant(grant: string) {
+ const parts = grant.split("~");
+ if (parts.length !== 8) return null;
+ const numbers = parts.slice(0, 7).map(Number);
+ if (!numbers.every(Number.isFinite)) return null;
+ const [south, west, north, east, minZoom, maxZoom, expiresAt] = numbers;
+ return {
+ area: { south, west, north, east },
+ minZoom,
+ maxZoom,
+ expiresAt,
+ signed: parts.slice(0, 7).join("~"),
+ signature: parts[7],
+ };
+}
diff --git a/src/shared/report-sandbox.test.ts b/src/shared/report-sandbox.test.ts
index 61d849ba..107c2389 100644
--- a/src/shared/report-sandbox.test.ts
+++ b/src/shared/report-sandbox.test.ts
@@ -1,5 +1,11 @@
import { describe, expect, it } from "vitest";
-import { PRINT_SCRIPT, PRINT_SCRIPT_SHA256, reportCsp } from "./report-sandbox";
+import {
+ PRINT_SCRIPT,
+ PRINT_SCRIPT_SHA256,
+ REPORT_WIDGETS_SRC,
+ reportCsp,
+ reportDocumentResponse,
+} from "./report-sandbox";
describe("report-sandbox", () => {
// The hash is hardcoded because the CSP needs it synchronously, so editing
@@ -13,6 +19,31 @@ describe("report-sandbox", () => {
const base64 = btoa(String.fromCharCode(...new Uint8Array(digest)));
expect(base64).toBe(PRINT_SCRIPT_SHA256);
- expect(reportCsp(true)).toContain(`script-src 'sha256-${base64}'`);
+ expect(reportCsp({ print: true })).toContain(
+ `script-src 'sha256-${base64}'`,
+ );
+ });
+
+ // The widget script is the only script a report with a map runs: the tag
+ // the server injects carries the response's nonce, the CSP names that nonce
+ // and nothing else, and the tag lands after the doctype where no stored
+ // markup can absorb it.
+ it("injects the widget script under the response nonce", async () => {
+ const response = reportDocumentResponse(
+ '<!doctype html><html><body><script>alert(1)</script><script src="x" </body></html>',
+ { cacheControl: "no-store", mapGrant: "grant" },
+ );
+ const html = await response.text();
+ const csp = response.headers.get("Content-Security-Policy") ?? "";
+ const nonce = /'nonce-([^']+)'/.exec(csp)?.[1];
+
+ expect(nonce).toBeTruthy();
+ expect(csp).toContain("sandbox allow-scripts");
+ expect(
+ html.startsWith(
+ `<!doctype html><script nonce="${nonce}" src="${REPORT_WIDGETS_SRC}" data-map-grant="grant" defer></script>`,
+ ),
+ ).toBe(true);
+ expect(html.split(`nonce="${nonce}"`).length).toBe(2);
});
});
diff --git a/src/shared/report-sandbox.ts b/src/shared/report-sandbox.ts
index 9cbcb120..f76fe743 100644
--- a/src/shared/report-sandbox.ts
+++ b/src/shared/report-sandbox.ts
@@ -9,28 +9,39 @@
// opaque origin anyway — no cookies, no localStorage, no same-origin access to
// the app.
+// `allow-popups` plus `allow-popups-to-escape-sandbox` let a report's
+// `target="_blank"` links open normally (the audited site, a reference);
+// everything else stays restricted. `allow-same-origin` is never added: it
+// would hand the frame the app's cookies and, with scripts, let the frame
+// remove its own sandbox.
+const SANDBOX = "allow-popups allow-popups-to-escape-sandbox";
+
/**
- * The iframe's `sandbox` attribute value, matching the CSP's sandbox
- * directive. `allow-popups` plus `allow-popups-to-escape-sandbox` let a
- * report's `target="_blank"` links open normally (the audited site, a
- * reference); everything else stays restricted. The attribute must always be
- * present — an absent `sandbox` attribute is no sandbox at all — and
- * `allow-same-origin` is never added: it would hand the frame the app's cookies
- * and, with scripts, let the frame remove its own sandbox.
+ * The iframe's `sandbox` attribute value. It allows scripts so the document's
+ * own CSP decides, and that only ever lets the app's scripts run (see
+ * reportCsp). The attribute must always be present — an absent `sandbox`
+ * attribute is no sandbox at all.
*/
-export const REPORT_IFRAME_SANDBOX =
- "allow-popups allow-popups-to-escape-sandbox";
+export const REPORT_IFRAME_SANDBOX = `allow-scripts ${SANDBOX}`;
+// `'self'` in img-src and connect-src is for the rank-grid widget's map: its
+// tiles, and the copyright line Google requires under them, both come through
+// /report-map (see report-map.ts). Nothing in a report can run a fetch; only
+// the widget script can.
const CSP_TAIL =
- "default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; connect-src 'none'; form-action 'none'; base-uri 'none'; object-src 'none'; frame-ancestors 'self'";
+ "default-src 'none'; style-src 'unsafe-inline'; img-src data: 'self'; font-src data:; connect-src 'self'; form-action 'none'; base-uri 'none'; object-src 'none'; frame-ancestors 'self'";
+
+// A report's own JavaScript never runs: with no `script-src`,
+// `default-src 'none'` blocks every script.
+export const REPORT_CSP = `sandbox ${SANDBOX}; ${CSP_TAIL}`;
-// The report's own JavaScript is blocked, and there is no `script-src`:
-// `default-src 'none'` already blocks every script. One flip turns it on, in
-// three places: add `allow-scripts` to the sandbox directive below, add it to
-// REPORT_IFRAME_SANDBOX, and add `script-src 'unsafe-inline'` here. Reports
-// saved while JS is blocked keep working after the flip; the reverse is not
-// true, which is why blocking is the V1 default.
-export const REPORT_CSP = `sandbox ${REPORT_IFRAME_SANDBOX}; ${CSP_TAIL}`;
+/**
+ * The widget bundle built from src/report-widgets by
+ * vite.report-widgets.config.ts, injected into a report that has a map to
+ * draw. It reads declarative blocks (a figure with a JSON data block) and draws
+ * them; it never evaluates anything found in the document.
+ */
+export const REPORT_WIDGETS_SRC = "/report-widgets/v1.js";
/**
* The script print mode appends, and the only script authorized to run in a
@@ -53,19 +64,25 @@ export const PRINT_SCRIPT_SHA256 =
"uE0MLbgBgIu3I3pghlY0762kVHKlP7Udz5qzZNT7piw=";
/**
- * The policy for one response. Outside print mode it is REPORT_CSP, byte for
- * byte.
+ * The policy for one response: REPORT_CSP, byte for byte, unless the app adds
+ * a script of its own. The widget tag carries a per-response nonce that nothing
+ * stored in a report can, and the print script is named by hash, so a report's
+ * own scripts stay blocked however they are hidden.
*
- * Print mode (`/r/<id>?print=1`) is the one case the app appends a script of
- * its own — a `print()` call, so "Export" lands in the browser's print dialog
- * instead of asking the reader to find it. That needs `allow-scripts` (and
- * `allow-modals`, since `print()` is a modal in a sandbox) plus a `script-src`
- * naming the hash of that one script, which is also what keeps the report's own
- * scripts blocked — see withPrintScript.
+ * Print mode (`/r/<id>?print=1`) appends a `print()` call, so "Export" lands in
+ * the browser's print dialog instead of asking the reader to find it. It also
+ * needs `allow-modals`, since `print()` is a modal in a sandbox — see
+ * withPrintScript.
*/
-export function reportCsp(print?: boolean): string {
- if (!print) return REPORT_CSP;
- return `sandbox ${REPORT_IFRAME_SANDBOX} allow-scripts allow-modals; script-src 'sha256-${PRINT_SCRIPT_SHA256}'; ${CSP_TAIL}`;
+export function reportCsp(
+ options: { nonce?: string; print?: boolean } = {},
+): string {
+ const sources: string[] = [];
+ if (options.nonce) sources.push(`'nonce-${options.nonce}'`);
+ if (options.print) sources.push(`'sha256-${PRINT_SCRIPT_SHA256}'`);
+ if (sources.length === 0) return REPORT_CSP;
+ const modals = options.print ? " allow-modals" : "";
+ return `sandbox allow-scripts ${SANDBOX}${modals}; script-src ${sources.join(" ")}; ${CSP_TAIL}`;
}
/**
@@ -100,6 +117,23 @@ function withPrintScript(html: string): string {
return html + tag;
}
+/**
+ * Injects the widget script tag right after the doctype, where nothing a
+ * stored document wrote can precede it: an unclosed `<script src="…" ` at the
+ * end of a document would otherwise absorb a tag appended there, and with it
+ * the nonce. `defer` runs it once the document is parsed. A document without a
+ * closed doctype gets the tag first of all, which is just as safe; a doctype
+ * left unclosed swallows the tag entirely, and the widget simply never boots.
+ */
+function withWidgetScript(html: string, nonce: string, mapGrant: string) {
+ // The grant is path-safe (see readMapGrant), so it needs no escaping here.
+ const tag = `<script nonce="${nonce}" src="${REPORT_WIDGETS_SRC}" data-map-grant="${mapGrant}" defer></script>`;
+ const doctype = /^\s*<!doctype[^>]*>/i.exec(html);
+ if (!doctype) return tag + html;
+ const end = doctype.index + doctype[0].length;
+ return html.slice(0, end) + tag + html.slice(end);
+}
+
/**
* The one response both report documents are served with — `/r/<id>` for a
* member and `/s/<token>/raw` for a link holder — so the sandbox, the print
@@ -109,13 +143,25 @@ function withPrintScript(html: string): string {
*/
export function reportDocumentResponse(
html: string,
- options: { print?: boolean; cacheControl: string; noindex?: boolean },
+ options: {
+ print?: boolean;
+ cacheControl: string;
+ noindex?: boolean;
+ /** From createReportMapGrant: lets the rank-grid widget draw its map. */
+ mapGrant?: string | null;
+ },
): Response {
- return new Response(options.print ? withPrintScript(html) : html, {
+ // The widget only loads where it has a map to draw.
+ const nonce = options.mapGrant ? crypto.randomUUID() : undefined;
+ const document =
+ nonce && options.mapGrant
+ ? withWidgetScript(html, nonce, options.mapGrant)
+ : html;
+ return new Response(options.print ? withPrintScript(document) : document, {
status: 200,
headers: {
"Content-Type": "text/html; charset=utf-8",
- "Content-Security-Policy": reportCsp(options.print),
+ "Content-Security-Policy": reportCsp({ nonce, print: options.print }),
// The sandbox allows popups to escape, so a link in a report opens a
// real page that would otherwise keep a handle on this tab and be able
// to navigate it. COOP severs that handle. Ignored when framed, which is
diff --git a/tsconfig.json b/tsconfig.json
index d3fb791c..0d15e2bc 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,6 +1,6 @@
{
"include": ["**/*.ts", "**/*.tsx"],
- "exclude": ["web/**/*", "tests/badseo/**/*"],
+ "exclude": ["web/**/*", "tests/badseo/**/*", "src/report-widgets/**/*"],
"compilerOptions": {
"strict": true,
"esModuleInterop": true,
diff --git a/tsconfig.report-widgets.json b/tsconfig.report-widgets.json
new file mode 100644
index 00000000..452445bf
--- /dev/null
+++ b/tsconfig.report-widgets.json
@@ -0,0 +1,16 @@
+{
+ // The report widget runs in a browser, not the worker: DOM lib only, and
+ // none of the worker's ambient types. Checked by `pnpm build:report-widgets`.
+ "compilerOptions": {
+ "target": "ES2022",
+ "module": "ESNext",
+ "moduleResolution": "Bundler",
+ "lib": ["DOM", "DOM.Iterable", "ES2022"],
+ "types": ["vite/client"],
+ "strict": true,
+ "noEmit": true,
+ "skipLibCheck": true,
+ "esModuleInterop": true
+ },
+ "include": ["src/report-widgets/**/*.ts", "src/shared/report-map.ts"]
+}
diff --git a/vite.report-widgets.config.ts b/vite.report-widgets.config.ts
new file mode 100644
index 00000000..fd282eb5
--- /dev/null
+++ b/vite.report-widgets.config.ts
@@ -0,0 +1,25 @@
+import { defineConfig } from "vite";
+
+// The report widget bundle: the one script the report sandbox lets run. Built
+// separately from the app so it ships as a plain, versioned file under
+// src/public/report-widgets/ that the viewer injects into every report with a
+// per-response nonce (see src/shared/report-sandbox.ts). Leaflet and its
+// stylesheet are bundled in, so a report never loads anything else.
+export default defineConfig({
+ // The bundle lands inside src/public/; copying that into itself is not wanted.
+ publicDir: false,
+ build: {
+ lib: {
+ entry: "src/report-widgets/rank-grid.ts",
+ name: "OpenSeoReportWidgets",
+ formats: ["iife"],
+ fileName: () => "v1.js",
+ },
+ outDir: "src/public/report-widgets",
+ emptyOutDir: true,
+ sourcemap: false,
+ // Leaflet's control icons are a few hundred bytes each; inline them so the
+ // stylesheet has no external references left.
+ assetsInlineLimit: 16384,
+ },
+});
diff --git a/web/content/docs/skills/local-seo.mdx b/web/content/docs/skills/local-seo.mdx
index 7698c4cd..b277d2c6 100644
--- a/web/content/docs/skills/local-seo.mdx
+++ b/web/content/docs/skills/local-seo.mdx
@@ -30,6 +30,8 @@ It helps when a business ranks at its storefront but not across its service area
Your agent should return a profile snapshot, where visibility drops off on the grid, a signal-by-signal comparison against the best competitor, and a prioritized action list starting with the one fix for this week.
+The report shows the grid on a live Google Map, the way local rank trackers draw it: one numbered circle per point, colored by position, with the storefront marked and, when you track several keywords, the average position across them at each point. Click a point to see each keyword's rank and who is #1 there. Printed and exported reports show the same grid as a drawing. Under it sit the average position, how many points land in the top 3, the average per keyword, and which business takes #1 most often.
+
## How to get the best result
- Give the agent the business name, or better, its `cid` or `placeId`.