From ee5eaea19e1bda6be26a28f783ba807e7a090b67 Mon Sep 17 00:00:00 2001 From: Nick Beckley Date: Fri, 27 Nov 2026 21:33:11 +0000 Subject: [PATCH] feat: publish source-dated sitemaps and qualify legacy proxy compatibility --- Docs/Content.md | 4 ++ .../Content/page-modified.json | 9 +++ .../Controllers/SitemapController.cs | 7 ++- Tests/nginx_compatibility.py | 55 +++++++++++++++++++ 4 files changed, 74 insertions(+), 1 deletion(-) create mode 100644 PlotDirector.Website/Content/page-modified.json create mode 100644 Tests/nginx_compatibility.py diff --git a/Docs/Content.md b/Docs/Content.md index 77b1e76..7511229 100644 --- a/Docs/Content.md +++ b/Docs/Content.md @@ -15,6 +15,10 @@ its index, categories, search results, canonical article URLs and sitemap from t same approved records. Original identifiers and collision-resolved slugs are exported by the existing application HelpService, rather than independently recomputed. Modification dates come from each article's last Git commit, not packaging time. +`Content/page-modified.json` pins genuine source modification dates for the existing +public pages; update the relevant entry when their published content changes. The +help index/category/article dates derive from the approved publication. No build-time +or request-time timestamps are invented for the sitemap. ## Application developer: publish diff --git a/PlotDirector.Website/Content/page-modified.json b/PlotDirector.Website/Content/page-modified.json new file mode 100644 index 0000000..e66b14d --- /dev/null +++ b/PlotDirector.Website/Content/page-modified.json @@ -0,0 +1,9 @@ +{ + "/": "2026-11-05T23:32:20Z", + "/features": "2026-11-02T15:08:32Z", + "/pricing": "2026-11-27T21:12:04Z", + "/about": "2026-07-02T20:48:29+01:00", + "/contact": "2026-07-02T20:48:29+01:00", + "/privacy": "2026-06-24T19:03:08+01:00", + "/terms": "2026-06-24T19:03:08+01:00" +} diff --git a/PlotDirector.Website/Controllers/SitemapController.cs b/PlotDirector.Website/Controllers/SitemapController.cs index 20f53ff..afb52c0 100644 --- a/PlotDirector.Website/Controllers/SitemapController.cs +++ b/PlotDirector.Website/Controllers/SitemapController.cs @@ -8,7 +8,7 @@ using PlotDirector.Website.Services; namespace PlotDirector.Website.Controllers; [AllowAnonymous] -public sealed class SitemapController(IHelpService help, IConfiguration configuration, PlotDirector.Website.Data.IWritingSolverRepository solver, WritingProblemEditorial? editorial = null) : Controller +public sealed class SitemapController(IHelpService help, IConfiguration configuration, IWebHostEnvironment environment, PlotDirector.Website.Data.IWritingSolverRepository solver, WritingProblemEditorial? editorial = null) : Controller { [HttpGet("/sitemap.xml")] public async Task Index() @@ -59,6 +59,11 @@ public sealed class SitemapController(IHelpService help, IConfiguration configur "0.5", article.LastModifiedUtc))); + var modified = System.Text.Json.JsonSerializer.Deserialize>( + System.IO.File.ReadAllText(Path.Combine(environment.ContentRootPath, "Content/page-modified.json")))!; + if (articles.Count > 0) modified["/help"] = new DateTimeOffset(articles.Max(a => a.LastModifiedUtc)); + urls = urls.Select(url => url.LastModifiedUtc is null && modified.TryGetValue(url.Path, out var date) + ? url with { LastModifiedUtc = date.UtcDateTime } : url).ToList(); return Content(BuildXml(urls), "application/xml", Encoding.UTF8); } diff --git a/Tests/nginx_compatibility.py b/Tests/nginx_compatibility.py new file mode 100644 index 0000000..f833cf0 --- /dev/null +++ b/Tests/nginx_compatibility.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +"""Qualify prepared vhosts in an unprivileged local Nginx/TLS sandbox, not Production.""" +import http.server,json,pathlib,socket,ssl,subprocess,tempfile,threading,time,urllib.request,urllib.error,hashlib +ROOT=pathlib.Path(__file__).resolve().parents[1] +class Backend(http.server.BaseHTTPRequestHandler): + def log_message(self,*a):pass + def do_GET(self): + if self.headers.get('Upgrade','').lower()=='websocket': + self.send_response(101);self.send_header('Upgrade','websocket');self.send_header('Connection','upgrade');self.end_headers();return + self.send_response(200);self.end_headers();self.wfile.write(self.server.name.encode()) + def do_POST(self): + body=self.rfile.read(int(self.headers.get('Content-Length','0')));self.send_response(200);self.end_headers();self.wfile.write(json.dumps({'backend':self.server.name,'path':self.path,'bodySha256':hashlib.sha256(body).hexdigest(),'authorization':self.headers.get('Authorization')}).encode()) +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self,*args):return None +def port(): + with socket.socket() as s:s.bind(('127.0.0.1',0));return s.getsockname()[1] +checks=[] +with tempfile.TemporaryDirectory(prefix='pd-nginx-qualification-') as directory: + temp=pathlib.Path(directory);http_port,https_port=port(),port();backends=[] + for name in ['app','website']: + server=http.server.ThreadingHTTPServer(('127.0.0.1',0),Backend);server.name=name;threading.Thread(target=server.serve_forever,daemon=True).start();backends.append(server) + subprocess.run(['openssl','req','-x509','-newkey','rsa:2048','-nodes','-days','1','-subj','/CN=localhost','-addext','subjectAltName=IP:127.0.0.1,DNS:plotdirector.com,DNS:app.plotdirector.com,DNS:www.plotdirector.com','-keyout',str(temp/'key.pem'),'-out',str(temp/'cert.pem')],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + snippets=[] + for name in ['nginx-website.conf','nginx-application.conf']: + text=(ROOT/'Tools/Deployment/production'/name).read_text() + import re + text=re.sub(r'listen 80;',f'listen 127.0.0.1:{http_port};',text);text=re.sub(r'listen \[::\]:80;','',text) + text=re.sub(r'listen 443 ssl;',f'listen 127.0.0.1:{https_port} ssl;',text);text=re.sub(r'listen \[::\]:443 ssl;','',text) + text=re.sub(r'/etc/letsencrypt/live/[^/]+/fullchain.pem',str(temp/'cert.pem'),text);text=re.sub(r'/etc/letsencrypt/live/[^/]+/privkey.pem',str(temp/'key.pem'),text) + text=text.replace('127.0.0.1:5001',f'127.0.0.1:{backends[0].server_port}').replace('127.0.0.1:5004',f'127.0.0.1:{backends[1].server_port}') + text=re.sub(r'/var/log/nginx/([^;]+)',lambda m:str(temp/m[1]),text);snippets.append(text) + (temp/'nginx.conf').write_text(f'pid {temp}/nginx.pid;\nerror_log {temp}/error.log;\nevents {{}}\nhttp {{\naccess_log off;\n'+''.join(snippets)+'\n}\n') + result=subprocess.run(['nginx','-t','-p',str(temp)+'/', '-c',str(temp/'nginx.conf')],capture_output=True);assert result.returncode==0,result.stderr.decode();checks.append('both prepared vhosts pass nginx -t') + nginx=subprocess.Popen(['nginx','-p',str(temp)+'/', '-c',str(temp/'nginx.conf'),'-g','daemon off;'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL) + try: + ctx=ssl.create_default_context(cafile=str(temp/'cert.pem'));opener=urllib.request.build_opener(NoRedirect(),urllib.request.HTTPSHandler(context=ctx)) + def request(path,host='plotdirector.com',data=None,headers=None): + req=urllib.request.Request(f'https://127.0.0.1:{https_port}'+path,headers={'Host':host,**(headers or {})},data=data) + try:return opener.open(req,timeout=5) + except urllib.error.HTTPError as e:return e + for _ in range(50): + try:r=request('/');break + except OSError:time.sleep(.1) + assert r.read()==b'website';checks.append('public root goes to independent website') + for path in ['/Projects/Details/123?focus=4','/Account/ResetPassword?token=test','/problem-solver/workspace/characters','/admin/writing-solver','/onboarding']: + r=request(path);assert r.code==308 and r.headers['Location']=='https://app.plotdirector.com'+path;checks.append('legacy browser path/query '+path.split('?')[0]) + body=b'{"synthetic":"request body preserved"}';r=request('/api/probe?x=y',data=body,headers={'Authorization':'Bearer SYNTHETIC-TEST-ONLY'});payload=json.load(r) + assert payload=={'backend':'app','path':'/api/probe?x=y','bodySha256':hashlib.sha256(body).hexdigest(),'authorization':'Bearer SYNTHETIC-TEST-ONLY'};checks.append('legacy API preserves POST body query and bearer header') + r=request('/hubs/echo',headers={'Connection':'Upgrade','Upgrade':'websocket'});assert r.code==101;checks.append('legacy websocket upgrade reaches application') + r=request('/Projects',host='app.plotdirector.com');assert r.read()==b'app' and 'noindex' in r.headers['X-Robots-Tag'];checks.append('application host and noindex isolated') + assert request('/_deployment/health').code==404 and request('/_deployment/health',host='app.plotdirector.com').code==404;checks.append('health endpoint denied on both public hosts') + print(json.dumps({'passed':True,'sandboxOnly':True,'checks':checks},indent=2)) + finally: + nginx.terminate();nginx.wait(timeout=10) + for server in backends:server.shutdown();server.server_close()