feat: publish source-dated sitemaps and qualify legacy proxy compatibility

This commit is contained in:
Nick Beckley 2026-11-27 21:33:11 +00:00
parent 376b0bfab9
commit ee5eaea19e
4 changed files with 74 additions and 1 deletions

View File

@ -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 same approved records. Original identifiers and collision-resolved slugs are exported
by the existing application HelpService, rather than independently recomputed. by the existing application HelpService, rather than independently recomputed.
Modification dates come from each article's last Git commit, not packaging time. 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 ## Application developer: publish

View File

@ -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"
}

View File

@ -8,7 +8,7 @@ using PlotDirector.Website.Services;
namespace PlotDirector.Website.Controllers; namespace PlotDirector.Website.Controllers;
[AllowAnonymous] [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")] [HttpGet("/sitemap.xml")]
public async Task<IActionResult> Index() public async Task<IActionResult> Index()
@ -59,6 +59,11 @@ public sealed class SitemapController(IHelpService help, IConfiguration configur
"0.5", "0.5",
article.LastModifiedUtc))); article.LastModifiedUtc)));
var modified = System.Text.Json.JsonSerializer.Deserialize<Dictionary<string, DateTimeOffset>>(
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); return Content(BuildXml(urls), "application/xml", Encoding.UTF8);
} }

View File

@ -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()