Audit Solver SEO publication and enforce Development noindex
This commit is contained in:
parent
7d05de90a4
commit
ad489bde07
16
PlotLine.Tests/Browser/writing-solver-seo.cjs
Normal file
16
PlotLine.Tests/Browser/writing-solver-seo.cjs
Normal file
@ -0,0 +1,16 @@
|
||||
// Real Razor metadata/sitemap audit. Production mode is loopback-only: no Production deployment or database.
|
||||
const{chromium}=require('playwright'),fs=require('fs'),assert=require('node:assert/strict');
|
||||
const base=process.env.SOLVER_BASE_URL||'http://127.0.0.1:5238',production=process.env.SEO_MODE==='production';assert(!production||new URL(base).hostname==='127.0.0.1');
|
||||
const graph=JSON.parse(fs.readFileSync('PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1-repair/writing-solver-curated-v2-stage1-repair.json')),expected=graph.solutions.filter(s=>s.active&&s.index).map(s=>'/writing-problems/'+s.slug).sort();
|
||||
(async()=>{const b=await chromium.launch(),c=await b.newContext({javaScriptEnabled:false});try{await c.addCookies([{name:'solver-anonymous',value:'true',url:base}]);const p=await c.newPage(),rows=[];
|
||||
async function meta(path){const response=await p.goto(base+path);assert.equal(response.status(),200);const data=await p.evaluate(()=>({title:document.title,description:document.querySelector('meta[name=description]')?.content,canonical:document.querySelector('link[rel=canonical]')?.href,robots:document.querySelector('meta[name=robots]')?.content,og:Object.fromEntries([...document.querySelectorAll('meta[property^="og:"]')].map(e=>[e.getAttribute('property'),e.content])),json:[...document.querySelectorAll('script[type="application/ld+json"]')].map(e=>JSON.parse(e.textContent)),h1:document.querySelector('h1')?.textContent.trim(),links:[...document.querySelectorAll('main a[href]')].map(e=>e.getAttribute('href'))}));assert.equal(data.canonical,'https://plotdirector.com'+path);assert.equal(data.og['og:url'],data.canonical);assert(data.title&&data.description&&data.og['og:title']&&data.og['og:description']);assert(data.og['og:image']);const imagePath=new URL(data.og['og:image']).pathname;assert.equal((await c.request.get(base+imagePath)).status(),200);assert.equal(data.robots,production?'index, follow':'noindex, follow');assert(!production||!response.headers()['x-robots-tag']?.includes('noindex'));assert(data.json.length>0);for(const item of data.json){assert.equal(item['@type'],'WebPage');assert.equal(item.url,data.canonical);assert(item.name&&item.description);assert(!JSON.stringify(item).includes('state='));}return data;}
|
||||
const entry=await meta('/writing-problems');assert(entry.links.includes('/writing-problems/browse'));for(const path of expected){const data=await meta(path);assert(data.links.includes('/writing-problems'));assert(data.links.some(u=>u.startsWith('/features/')));assert(data.links.some(u=>u.startsWith('/writing-problems/browse/')));rows.push({path,...data});}assert.equal(new Set(rows.map(r=>r.title)).size,expected.length);assert.equal(new Set(rows.map(r=>r.description)).size,expected.length);
|
||||
// All permanent pages are discoverable through normal SSR browse anchors.
|
||||
await p.goto(base+'/writing-problems/browse');const areas=await p.locator('main a[href^="/writing-problems/browse/"]').evaluateAll(es=>es.map(e=>e.getAttribute('href'))),linked=new Set();for(const area of areas){await p.goto(base+area);for(const href of await p.locator('.solver-problem-links a').evaluateAll(es=>es.map(e=>e.getAttribute('href'))))linked.add(href);}assert.deepEqual([...linked].sort(),expected);
|
||||
const xml=await (await c.request.get(base+'/sitemap.xml')).text();const locs=await p.evaluate(xml=>{const d=new DOMParser().parseFromString(xml,'application/xml');if(d.querySelector('parsererror'))throw Error('Invalid sitemap XML');return [...d.getElementsByTagName('loc')].map(e=>e.textContent);},xml);assert.equal(locs.length,new Set(locs).size);assert(locs.every(u=>!new URL(u).search&&!new URL(u).hash));const sitemapPaths=locs.map(u=>new URL(u).pathname),permanent=sitemapPaths.filter(u=>u.startsWith('/writing-problems/')&&!u.startsWith('/writing-problems/browse')).sort();assert.deepEqual(permanent,production?expected:[]);assert.equal(sitemapPaths.includes('/writing-problems'),production);
|
||||
// Personal evidence changes the visible explanation, never the document's public identity.
|
||||
await p.goto(base+'/writing-problems');let statePath;for(const choice of ['story-not-working','too-many','lost','unwanted']){await p.locator(`input[name=choices][value="${choice}"]`).check();await p.locator('.solver-form button[type=submit]').click();if(new URL(p.url()).searchParams.has('state')){statePath=new URL(p.url()).pathname+new URL(p.url()).search;assert.equal(await p.locator('meta[name=robots]').getAttribute('content'),'noindex, follow');assert.equal(await p.locator('link[rel=canonical]').getAttribute('href'),'https://plotdirector.com/writing-problems');}}
|
||||
assert(await p.locator('.solver-result-evidence li').count()>0);const path=new URL(p.url()).pathname,personal=await meta(path),direct=rows.find(r=>r.path===path);for(const key of ['title','description','canonical','og','json'])assert.deepEqual(personal[key],direct[key]);await p.goBack();await p.goForward();assert.equal(new URL(p.url()).pathname,path);const invalid=await p.goto(base+'/writing-problems?state=invalid');assert(invalid.headers()['x-robots-tag']?.includes('noindex'));assert.equal(await p.locator('meta[name=robots]').getAttribute('content'),'noindex, follow');assert.equal(await p.locator('link[rel=canonical]').getAttribute('href'),'https://plotdirector.com/writing-problems');
|
||||
await p.goto(base+'/writing-problems?choose=true');assert.equal(await p.locator('meta[name=robots]').getAttribute('content'),'noindex, follow');assert.equal(await p.locator('link[rel=canonical]').getAttribute('href'),'https://plotdirector.com/writing-problems');
|
||||
if(!production&&new URL(base).hostname==='dev.plotdirector.com')for(const route of ['/','/features','/help','/sitemap.xml','/robots.txt']){const response=await c.request.get(base+route);assert(response.headers()['x-robots-tag']?.includes('noindex'),`Missing environmental noindex: ${route}`);}
|
||||
const report={mode:production?'Production configuration (isolated)':'Development',permanentFound:expected.length,permanentInSitemap:permanent.length,entryInSitemap:sitemapPaths.includes('/writing-problems'),statefulInSitemap:locs.filter(u=>new URL(u).search||new URL(u).hash).length,uniqueTitles:new Set(rows.map(r=>r.title)).size,uniqueDescriptions:new Set(rows.map(r=>r.description)).size,schemaTypes:[...new Set(rows.flatMap(r=>r.json.map(j=>j['@type'])))],personalIdentityStable:true,rows};fs.writeFileSync(process.env.SEO_REPORT||'/tmp/writing-solver-seo.json',JSON.stringify(report,null,2));console.log('PASS SEO audit',JSON.stringify({...report,rows:undefined}));}finally{await c.close();await b.close();}})().catch(e=>{console.error(e);process.exit(1)});
|
||||
@ -18,6 +18,7 @@ public static class WritingSolverCleanUrlTests
|
||||
}
|
||||
public static void TransitionAndIsolation()
|
||||
{
|
||||
WritingSolverSeoTests.AuditPublication();
|
||||
void Check(bool ok,string text) { if(!ok)throw new Exception(text); }
|
||||
var graph=WritingSolverRepository.Parse(File.ReadAllText("PlotLine/Content/WritingSolver/demo.json"));
|
||||
foreach(var page in graph.Solutions)page.Index=true;
|
||||
|
||||
99
PlotLine.Tests/WritingSolverSeoTests.cs
Normal file
99
PlotLine.Tests/WritingSolverSeoTests.cs
Normal file
@ -0,0 +1,99 @@
|
||||
using System.Text.Json;
|
||||
using System.Xml.Linq;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.DataProtection;
|
||||
using Microsoft.Extensions.Caching.Memory;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Microsoft.Extensions.FileProviders;
|
||||
using PlotLine.Controllers;
|
||||
using PlotLine.Data;
|
||||
using PlotLine.Models.WritingSolver;
|
||||
using PlotLine.Services;
|
||||
|
||||
internal static class WritingSolverSeoTests
|
||||
{
|
||||
private sealed class Repository(SolverGraph graph) : IWritingSolverRepository
|
||||
{
|
||||
public Task<SolverGraph> GetAsync() => Task.FromResult(graph);
|
||||
public Task PublishAsync(string json, string editor) => throw new NotSupportedException();
|
||||
}
|
||||
private sealed class Host(string environment) : IWebHostEnvironment
|
||||
{
|
||||
public string EnvironmentName { get; set; } = environment;
|
||||
public string ApplicationName { get; set; } = "PlotLine";
|
||||
public string ContentRootPath { get; set; } = Path.GetFullPath("PlotLine");
|
||||
public string WebRootPath { get; set; } = Path.GetFullPath("PlotLine/wwwroot");
|
||||
public IFileProvider ContentRootFileProvider { get; set; } = new NullFileProvider();
|
||||
public IFileProvider WebRootFileProvider { get; set; } = new NullFileProvider();
|
||||
}
|
||||
public static void AuditPublication()
|
||||
{
|
||||
void Check(bool ok, string reason) { if (!ok) throw new Exception(reason); }
|
||||
var graph = WritingSolverRepository.Parse(File.ReadAllText("PlotLine/Content/WritingSolver/Candidates/curated-v2-stage1-repair/writing-solver-curated-v2-stage1-repair.json"));
|
||||
var editorial = new WritingProblemEditorial("PlotLine/Content/WritingSolver/Editorial/pages-v1.json");
|
||||
var repo = new Repository(graph);
|
||||
var config = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?> { ["WritingSolver:EnableIndexing"] = "true" }).Build();
|
||||
var host = new Host("Production");
|
||||
var help = new HelpService(host);
|
||||
HashSet<string> Sitemap(IConfiguration settings)
|
||||
{
|
||||
var result = (ContentResult)new SitemapController(help, settings, repo, editorial).Index().GetAwaiter().GetResult();
|
||||
var xml = XDocument.Parse(result.Content!);
|
||||
XNamespace ns = "http://www.sitemaps.org/schemas/sitemap/0.9";
|
||||
var urls = xml.Descendants(ns + "loc").Select(e => e.Value).ToList();
|
||||
Check(urls.Count == urls.Distinct().Count(), "Duplicate sitemap URL.");
|
||||
Check(urls.All(u => new Uri(u).Query == "" && new Uri(u).Fragment == ""), "Sitemap contains journey/query/fragment state.");
|
||||
return urls.ToHashSet();
|
||||
}
|
||||
var expected = graph.Solutions.Where(p => p.Active && p.Index).Select(p => PublicSeo.AbsoluteUrl(config, "/writing-problems/" + p.Slug)).ToHashSet();
|
||||
Check(expected.Count == editorial.Catalog.Pages.Count, "Permanent editorial catalogue/publication eligibility diverged.");
|
||||
var urls = Sitemap(config);
|
||||
var actual = urls.Where(u => new Uri(u).AbsolutePath.StartsWith("/writing-problems/") && !new Uri(u).AbsolutePath.StartsWith("/writing-problems/browse")).ToHashSet();
|
||||
Check(expected.SetEquals(actual), "Generated sitemap must contain exactly the eligible permanent diagnoses.");
|
||||
Check(urls.Contains(PublicSeo.AbsoluteUrl(config, "/writing-problems")), "Solver discovery missing from Production sitemap.");
|
||||
var titles = new HashSet<string>(); var descriptions = new HashSet<string>();
|
||||
using var cache = new MemoryCache(new MemoryCacheOptions());
|
||||
foreach (var solution in graph.Solutions.Where(p => p.Active && p.Index))
|
||||
{
|
||||
var controller = new WritingProblemsController(repo, new EphemeralDataProtectionProvider(), config, new WritingSolverResultContext(cache), editorial) { ControllerContext = new() { HttpContext = new DefaultHttpContext() } };
|
||||
controller.Solution(solution.Slug).GetAwaiter().GetResult();
|
||||
var title = controller.ViewData["SeoTitle"] as string;
|
||||
var description = controller.ViewData["SeoDescription"] as string;
|
||||
Check(!string.IsNullOrWhiteSpace(title) && titles.Add(title), "Missing/duplicate permanent title.");
|
||||
Check(!string.IsNullOrWhiteSpace(description) && descriptions.Add(description), "Missing/duplicate permanent description.");
|
||||
var canonical = PublicSeo.AbsoluteUrl(config, "/writing-problems/" + solution.Slug);
|
||||
Check((string?)controller.ViewData["CanonicalUrl"] == canonical, "Permanent canonical is not clean/stable.");
|
||||
Check((string?)controller.ViewData["Robots"] == "index, follow" && !controller.Response.Headers.ContainsKey("X-Robots-Tag"), "Production eligible page unexpectedly noindex.");
|
||||
Check(!string.IsNullOrWhiteSpace(controller.ViewData["OgTitle"] as string) && !string.IsNullOrWhiteSpace(controller.ViewData["OgDescription"] as string), "Missing Open Graph text.");
|
||||
var image = new Uri((string)controller.ViewData["OgImage"]!);
|
||||
Check(File.Exists(Path.Combine(host.WebRootPath, image.AbsolutePath.TrimStart('/'))), "Social image missing.");
|
||||
foreach (var json in (IEnumerable<string>)controller.ViewData["StructuredData"]!)
|
||||
{
|
||||
using var doc = JsonDocument.Parse(json); var root = doc.RootElement;
|
||||
Check(root.GetProperty("@type").GetString() == "WebPage" && root.GetProperty("url").GetString() == canonical, "Unexpected structured identity/type.");
|
||||
Check(!string.IsNullOrWhiteSpace(root.GetProperty("description").GetString()), "Structured description missing.");
|
||||
}
|
||||
}
|
||||
var transient = new WritingProblemsController(repo, new EphemeralDataProtectionProvider(), config, new WritingSolverResultContext(cache), editorial) { ControllerContext = new() { HttpContext = new DefaultHttpContext() } };
|
||||
transient.Index(choose: true).GetAwaiter().GetResult();
|
||||
Check((string?)transient.ViewData["Robots"] == "noindex, follow", "Validation-only journey URL must remain noindex.");
|
||||
var first = graph.Solutions.First(p => p.Active && p.Index); first.Index = false;
|
||||
Check(!Sitemap(config).Contains(PublicSeo.AbsoluteUrl(config, "/writing-problems/" + first.Slug)), "Unpublished index flag ignored by sitemap."); first.Index = true;
|
||||
first.Active = false; Check(!Sitemap(config).Contains(PublicSeo.AbsoluteUrl(config, "/writing-problems/" + first.Slug)), "Inactive diagnosis entered sitemap."); first.Active = true;
|
||||
var disabled = new ConfigurationBuilder().AddInMemoryCollection(new Dictionary<string,string?> { ["WritingSolver:EnableIndexing"] = "false" }).Build();
|
||||
Check(!Sitemap(disabled).Any(u => new Uri(u).AbsolutePath.StartsWith("/writing-problems")), "Disabled Solver entered sitemap.");
|
||||
foreach (var environment in new[] { "Production", "Development" })
|
||||
{
|
||||
using var services = new ServiceCollection().AddSingleton<IWebHostEnvironment>(new Host(environment)).BuildServiceProvider();
|
||||
var app = new ApplicationBuilder(services); app.UseDevelopmentNoIndex(); app.Run(_ => Task.CompletedTask);
|
||||
var http = new DefaultHttpContext(); app.Build()(http).GetAwaiter().GetResult();
|
||||
Check(http.Response.Headers.ContainsKey("X-Robots-Tag") == (environment == "Development"), "Global environment indexing boundary failed.");
|
||||
Check(PublicIndexing.Robots(environment, "index, follow") == (environment == "Development" ? "noindex, follow" : "index, follow"), "HTML environment policy failed.");
|
||||
Check(PublicIndexing.Robots(environment, "noindex, follow") == "noindex, follow", "Stateful noindex was weakened.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -34,9 +34,9 @@ public sealed class WritingProblemsController(IWritingSolverRepository repositor
|
||||
catch (Exception ex) when (ex is CryptographicException or JsonException or InvalidDataException)
|
||||
{ error = "Your previous conversation has expired or changed. Let’s start afresh."; }
|
||||
var outcome = WritingSolverEngine.Evaluate(graph,history);
|
||||
if (state is not null) Response.Headers["X-Robots-Tag"] = "noindex, follow";
|
||||
if (state is not null || choose) Response.Headers["X-Robots-Tag"] = "noindex, follow";
|
||||
if (Complete(graph, outcome) is {} completed) return completed;
|
||||
SetSeo("The Writing Problem Solver", "Tell us what’s making your novel complicated and find a practical way to untangle it.", "/writing-problems", state is null);
|
||||
SetSeo("The Writing Problem Solver", "Tell us what’s making your novel complicated and find a practical way to untangle it.", "/writing-problems", state is null && !choose);
|
||||
ViewData["BackState"] = outcome.Answers.Count > 0 ? Encode(graph,outcome.Answers.Take(outcome.Answers.Count-1)) : null;
|
||||
return View(new SolverJourney(graph,outcome,Encode(graph,outcome.Answers),error));
|
||||
}
|
||||
|
||||
@ -306,6 +306,7 @@ public class Program
|
||||
app.UseHsts();
|
||||
}
|
||||
|
||||
app.UseDevelopmentNoIndex();
|
||||
app.UseHttpsRedirection();
|
||||
// Keep PWA metadata/worker revalidating even when served by static-asset endpoints.
|
||||
app.Use(async (context, next) =>
|
||||
|
||||
20
PlotLine/Services/PublicIndexing.cs
Normal file
20
PlotLine/Services/PublicIndexing.cs
Normal file
@ -0,0 +1,20 @@
|
||||
namespace PlotLine.Services;
|
||||
|
||||
// Environment protection is independent of catalogue publication/index eligibility.
|
||||
public static class PublicIndexing
|
||||
{
|
||||
public static string Robots(string environment, string requested) =>
|
||||
string.Equals(environment, Environments.Development, StringComparison.OrdinalIgnoreCase)
|
||||
? "noindex, follow" : requested;
|
||||
|
||||
public static IApplicationBuilder UseDevelopmentNoIndex(this IApplicationBuilder app)
|
||||
{
|
||||
if (app.ApplicationServices.GetRequiredService<IWebHostEnvironment>().IsDevelopment())
|
||||
app.Use(async (context, next) =>
|
||||
{
|
||||
context.Response.Headers["X-Robots-Tag"] = "noindex, follow";
|
||||
await next();
|
||||
});
|
||||
return app;
|
||||
}
|
||||
}
|
||||
@ -1,5 +1,6 @@
|
||||
@using System.Security.Claims
|
||||
@inject IConfiguration Configuration
|
||||
@inject Microsoft.AspNetCore.Hosting.IWebHostEnvironment HostingEnvironment
|
||||
@inject PlotLine.Data.IAppearanceRepository AppearancePreferences
|
||||
@{
|
||||
var isSolverPage = ViewContext.RouteData.Values["controller"]?.ToString() is "WritingProblems" or "WritingSolverReview";
|
||||
@ -39,7 +40,7 @@
|
||||
{
|
||||
<meta name="keywords" content="@seoKeywords" />
|
||||
}
|
||||
<meta name="robots" content="@(ViewData["Robots"] as string ?? "index, follow")" />
|
||||
<meta name="robots" content="@PublicIndexing.Robots(HostingEnvironment.EnvironmentName, ViewData["Robots"] as string ?? "index, follow")" />
|
||||
<meta property="og:site_name" content="PlotDirector" />
|
||||
<meta property="og:title" content="@ogTitle" />
|
||||
@if (!string.IsNullOrWhiteSpace(ogDescription))
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user