"""Static route audit; --origin also checks real HTTP routes/redirects on an authorized local deployment.""" import argparse,csv,json,concurrent.futures,urllib.request,urllib.error,hashlib,zipfile from pathlib import Path from urllib.parse import urlsplit,urljoin,unquote from bs4 import BeautifulSoup as BS ROOT=Path(__file__).resolve().parents[1];BASE='https://appinitdev.com/investigaciones/';HOSTS={'appinitdev.com','www.appinitdev.com'} parser=argparse.ArgumentParser();parser.add_argument('--origin',help='Authorized test server origin, e.g. http://127.0.0.1:18765');parser.add_argument('--previous-zip');a=parser.parse_args() def route(p): s=p.relative_to(ROOT).as_posix();return BASE+(s[:-10] if s.endswith('index.html') else s[:-5]) def same(v):return urlsplit(v).netloc in HOSTS def check(v):return same(v) and urlsplit(v).path.lower().endswith('.html') def walk(x): if isinstance(x,dict): for v in x.values():yield from walk(v) elif isinstance(x,list): for v in x:yield from walk(v) elif isinstance(x,str):yield x pages=sorted(ROOT.rglob('*.html'));errors=[];nav=0;urls=set();ext=set();external_same=set();cans=set();records=[] for p in pages: s=BS(p.read_text(encoding='utf-8'),'html.parser');can=s.select_one('link[rel=canonical]')['href'];assert can==route(p) and not check(can),p;cans.add(can) assert s.select_one('meta[property="og:url"]')['content']==can,p inner=set();n=0;outside=0;page_ext=set() for tag in s.find_all(True): for at in ('href','src','action','data-href','data-url'): v=tag.get(at) if not isinstance(v,str) or not v:continue u=urljoin(can,v);parts=urlsplit(u) if check(u):errors.append((str(p),at,v)) if parts.netloc in HOSTS and parts.path.startswith('/investigaciones/'): rel=unquote(parts.path.removeprefix('/investigaciones/'));target=ROOT/rel if target.is_dir():target=target/'index.html' if not target.exists() and not target.suffix:target=target.with_suffix('.html') if not target.is_file():errors.append((str(p),'missing route',v));continue urls.add(parts.path) if tag.name=='a' and at=='href':nav+=1;n+=1 if target.suffix=='.html' and target!=p and tag.name=='a':inner.add(target) elif parts.netloc in HOSTS:external_same.add(u);outside+=1 elif parts.scheme in ('https','http') and parts.netloc and tag.name=='a':ext.add(u);page_ext.add(u) for sc in s.select('script[type="application/ld+json"]'): for val in walk(json.loads(sc.string or sc.get_text())): if check(val):errors.append((str(p),'JSON-LD',val)) for t in s.select('meta[property="og:url"],meta[name="twitter:url"]'): if check(t.get('content','')):errors.append((str(p),'meta',t['content'])) kinds={t.get_text(' ',strip=True) for t in s.select('.expert-kind')};assert {'libro','revista','repositorio'}<=kinds and kinds.intersection({'guía','documentación','artículo','estándar','datos'}),p assert inner and page_ext and s.select_one('.expert-example'),p records.append({'page':p.relative_to(ROOT).as_posix(),'canonical':can,'internal_pages':len(inner),'internal_nav':n,'external_links':len(page_ext),'outside_section_links':outside,'clean_url':True,'book':True,'journal':True,'trusted_reference_type':True,'repository':True,'example':True,'thesis_design':bool(s.select_one('#marco-tesis'))}) for name in ('research-catalog.json','metadata-research.json'): for v in walk(json.loads((ROOT/name).read_text())): if check(v):errors.append((name,'data',v)) import xml.etree.ElementTree as ET loc=[x.text for x in ET.parse(ROOT/'sitemap.xml').getroot().iter('{http://www.sitemaps.org/schemas/sitemap/0.9}loc')];assert len(loc)==len(cans) and set(loc)==cans and not any(check(x) for x in loc) assert not errors,errors report={'pages':len(pages),'sitemap':len(loc),'internal_navigation_occurrences':nav,'unique_local_targets':len(urls),'external_links_distinct':len(ext),'same_site_outside_scope_distinct':len(external_same),'same_site_outside_scope':sorted(external_same),'extension_html_in_public_internal_urls':0,'all_have_internal_link_book_journal_reference_repository_example':True,'studies_with_thesis_design':sum(r['thesis_design'] for r in records),'http_test':'not run','limitations':'Static structure and optionally local HTTP only; external availability and scientific review not established.'} if a.previous_zip: with zipfile.ZipFile(a.previous_zip) as z: old=[n for n in z.namelist() if '/resultados/INV-' in n and not n.endswith('/')];changed=[n for n in old if not (ROOT.parent/n).is_file() or (ROOT.parent/n).read_bytes()!=z.read(n)];assert not changed,changed;report['pilot_files_byte_identical']=len(old) if a.origin: class NoRedirect(urllib.request.HTTPRedirectHandler): def redirect_request(self,*args,**kwargs):return None opener=urllib.request.build_opener(NoRedirect()) def request(path,expected,location=None): try: with opener.open(a.origin.rstrip('/')+path,timeout=12) as r:status=r.status;loc=r.headers.get('Location');r.read() except urllib.error.HTTPError as e:status=e.code;loc=e.headers.get('Location') assert status==expected,(path,status,expected,loc) if location is not None:assert urlsplit(loc or '').path==location,(path,loc,location) return 1 tests=[(p,200,None) for p in sorted(urls|{urlsplit(c).path for c in cans})] for p in pages: old='/investigaciones/'+p.relative_to(ROOT).as_posix();new=urlsplit(route(p)).path;tests.append((old,301,new)) if p.name!='index.html':tests.append((new+'/',301,new)) tests.append(('/investigaciones/__ruta_inexistente__',404,None)) with concurrent.futures.ThreadPoolExecutor(max_workers=8) as pool:list(pool.map(lambda t:request(*t),tests)) report['http_test']={'origin':a.origin,'passed':len(tests),'http_200':sum(t[1]==200 for t in tests),'redirect_301':sum(t[1]==301 for t in tests),'not_found_404':1} with (ROOT/'AUDITORIA-RUTAS.csv').open('w',encoding='utf-8-sig',newline='') as f: w=csv.DictWriter(f,fieldnames=list(records[0]));w.writeheader();w.writerows(records) (ROOT/'AUDITORIA-TESIS.json').write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n',encoding='utf-8');print(json.dumps({k:v for k,v in report.items() if k!='same_site_outside_scope'},ensure_ascii=False,indent=2))