#!/usr/bin/env python3 """Rendered HTTP compatibility and crawl validation against a running website.""" import argparse,concurrent.futures,json,sys,urllib.request,urllib.parse,xml.etree.ElementTree as ET from html.parser import HTMLParser from pathlib import Path class Page(HTMLParser): def __init__(self):super().__init__();self.links=[];self.assets=[];self.canonical=[];self.description=[];self.title='';self.in_title=False;self.ld=[];self.in_ld=False def handle_starttag(self,tag,attrs): a=dict(attrs) if tag=='a' and a.get('href'):self.links.append(a['href']) if tag=='img' and a.get('src'):self.assets.append(a['src']) if tag=='script' and a.get('src'):self.assets.append(a['src']) if tag=='link' and a.get('rel')=='stylesheet':self.assets.append(a['href']) if tag=='link' and a.get('rel')=='canonical':self.canonical.append(a.get('href')) if tag=='meta' and a.get('name')=='description':self.description.append(a.get('content')) if tag=='title':self.in_title=True if tag=='script' and a.get('type')=='application/ld+json':self.in_ld=True;self.ld.append('') def handle_endtag(self,tag): if tag=='title':self.in_title=False if tag=='script':self.in_ld=False def handle_data(self,data): if self.in_title:self.title+=data if self.in_ld:self.ld[-1]+=data def run(origin,production=False,legacy_bridge=False): root=Path(__file__).resolve().parents[1];public=json.loads((root/'Tests/public-urls.json').read_text())['urls'] graph=json.loads((root/'PlotDirector.Website/Content/solver.json').read_text());editorial=json.loads((root/'PlotDirector.Website/Content/WritingSolver/Editorial/pages-v1.json').read_text()) urls={urllib.parse.urlsplit(u).path for u in public} urls|={'/problem-solver','/problem-solver/browse'}|{'/problem-solver/browse/'+a['id'] for a in editorial['areas']} urls|={'/problem-solver/'+s['slug'] for s in graph['solutions'] if s['active']} urls|={'/features/'+s['slug'] for s in graph['features'] if s['active']} errors=[];pages={};assets=set();links=set() def fetch(path): with urllib.request.urlopen(origin+path,timeout=30) as r:return r.status,r.read(),dict(r.headers) def check(path): try: status,data,headers=fetch(path);p=Page();p.feed(data.decode());return path,p,headers,None except Exception as e:return path,None,{},str(e) with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool: for path,p,headers,error in pool.map(check,sorted(urls)): if error:errors.append(path+': '+error);continue pages[path]=p if len(p.canonical)!=1 or p.canonical[0]!='https://plotdirector.com'+path:errors.append(path+': wrong canonical') if not p.title.strip() or not p.description or not p.description[0]:errors.append(path+': missing metadata') if not p.ld:errors.append(path+': missing JSON-LD') for ld in p.ld: try:json.loads(ld) except ValueError:errors.append(path+': invalid JSON-LD') robots=headers.get('X-Robots-Tag','') if not production and 'noindex' not in robots:errors.append(path+': Development indexing exposure') if production and path in {urllib.parse.urlsplit(u).path for u in public} and 'noindex' in robots:errors.append(path+': Production public page noindex') for link in p.links: if link.startswith('/') and not link.startswith('//') and not link.startswith('/Pricing/Checkout'): parsed=urllib.parse.urlsplit(link);links.add(parsed.path) assets.update(urllib.parse.urlsplit(a).path for a in p.assets if a.startswith('/')) if 'service-worker' in ' '.join(p.assets) or any('site.webmanifest' in a for a in p.assets):errors.append(path+': application PWA asset') titles={} for path,p in pages.items(): if p.title in titles:errors.append(path+': duplicate title with '+titles[p.title]) titles[p.title]=path for path in sorted((assets|links)-set(pages)): try:fetch(path) except Exception as e:errors.append(path+': broken internal link/asset '+str(e)) _,sitemap,_=fetch('/sitemap.xml');sitemap_urls={u.text for u in ET.fromstring(sitemap).findall('.//{*}loc')} from datetime import datetime,timezone expected_dates={path:datetime.fromisoformat(date.replace('Z','+00:00')).date().isoformat() for path,date in json.loads((root/'PlotDirector.Website/Content/page-modified.json').read_text()).items()} for entry in ET.fromstring(sitemap).findall('{*}url'): path=urllib.parse.urlsplit(entry.find('{*}loc').text).path;modified=entry.find('{*}lastmod') if path in expected_dates and (modified is None or modified.text!=expected_dates[path]):errors.append(path+': content modification date differs') if modified is not None and datetime.fromisoformat(modified.text).date()>datetime.now(timezone.utc).date():errors.append(path+': future modification date') if sitemap_urls!=set(public):errors.append('Sitemap differs from approved Production URL inventory') for path in ['/missing-page-acceptance','/help/missing/missing','/site.webmanifest','/service-worker.js','/hubs/word-companion-follow']: expected=401 if legacy_bridge and path=='/hubs/word-companion-follow' else 404 try:fetch(path);errors.append(path+': expected '+str(expected)) except urllib.error.HTTPError as e: if e.code!=expected:errors.append(path+': expected '+str(expected)+' got '+str(e.code)) articles=json.loads((root/'PlotDirector.Website/Help/published/articles.json').read_text()) sample=articles[0];status,fragment,headers=fetch('/HelpDrawer/Article?key='+urllib.parse.quote(sample['ContextKey'])) if status!=200 or sample['Title'] not in fragment.decode() or 'noindex' not in headers.get('X-Robots-Tag',''):errors.append('published legacy help fragment differs') restricted=json.loads((root/'Tests/restricted-help-routes.json').read_text()) restricted_paths=set(restricted['categories'])|{a['Url'] for a in restricted['articles']} for path in restricted_paths: try:fetch(path);errors.append(path+': restricted anonymous access was not denied') except urllib.error.HTTPError as e: if e.code!=404:errors.append(path+': restricted route must return 404') for article in restricted['articles']: for path in ['/Help/Article/'+urllib.parse.quote(article['ContextKey']),'/HelpDrawer/Article?key='+urllib.parse.quote(article['ContextKey'])]: try:fetch(path);errors.append(path+': restricted alias was not denied') except urllib.error.HTTPError as e: if e.code!=404:errors.append(path+': restricted alias must return 404') _,body,_=fetch('/help?q='+urllib.parse.quote(article['Title']));search=Page();search.feed(body.decode()) if any(urllib.parse.urlsplit(u).path in restricted_paths for u in search.links):errors.append('Restricted article in help search') for path in ['/help','/sitemap.xml','/llms.txt','/llms-full.txt']: _,body,_=fetch(path);body=body.decode() if 'story-intelligence-admin' in body.lower() or 'storyIntelligence.admin.' in body:errors.append(path+': restricted navigation/index entry') for path,page in pages.items(): if any(urllib.parse.urlsplit(u).path in restricted_paths for u in page.links):errors.append(path+': restricted related/navigation link') report={'origin':origin,'productionPolicy':production,'legacyApplicationBridge':legacy_bridge,'baselineUrls':len(public),'renderedPages':len(pages),'internalPaths':len(links),'assets':len(assets),'restrictedArticlesChecked':len(restricted['articles']),'errors':errors,'passed':not errors} print(json.dumps(report,indent=2));return bool(errors) if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('--origin',required=True);p.add_argument('--production',action='store_true');p.add_argument('--legacy-application-bridge',action='store_true');a=p.parse_args();sys.exit(run(a.origin.rstrip('/'),a.production,a.legacy_application_bridge))