Files
progcode/deploy/audit-outbound.py

104 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from pathlib import Path
from bs4 import BeautifulSoup
from urllib.parse import urlsplit,unquote
import json,re,collections,hashlib
r=Path(__file__).resolve().parents[1];doc=r/'docs/rebuild-v2';ledger=json.load(open(doc/'editorial-ledger.json'));edited=json.load(open(r/'web/data/articles-v2.json'));review={}
for page in ledger['pages']:
for link in page['outboundLinks']:review[(page['slug'],link['url'])]=link
resources={
'https://dlang.org/spec/spec.html':'Полный справочник семантики D: читатель проверяет правила языка.',
'https://dlang.org/phobos/index.html':'Индекс стандартной библиотеки Phobos по теме блога.',
'https://dub.pm/':'Первичная документация сборщика и менеджера зависимостей DUB.',
'https://www.php.net/manual/ru/':'Первичный русскоязычный справочник PHP.',
'https://dev.1c-bitrix.ru/api_help/':'Первичный справочник API Bitrix, по которому проверяются версии и ограничения.',
'https://webpack.js.org/plugins/provide-plugin/':'Первичная документация ProvidePlugin, раскрывает контракт подключения jQuery.',
'https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse':'Контракт функции JSON.parse и ограничения чисел, непосредственно относится к инструменту.',
'https://curl.se/docs/sslcerts.html':'Первичное объяснение проверки TLS и доверия сертификатам.'}
# Each final publication link has an article-specific reviewed context, not a domain-wide allow list.
allApproved=collections.defaultdict(list)
for (slug,url),decision in review.items():allApproved[url].append((slug,decision.get('reason','')))
records=[];unreviewed=[]
def external(url):return urlsplit(url).scheme in ['http','https'] and urlsplit(url).hostname not in ['progcode.ru','www.progcode.ru','127.0.0.1','localhost']
def scan(text,file,phase,slug=None):
soup=BeautifulSoup(text,'html.parser')
for i,tag in enumerate(soup.find_all(True)):
for attribute in ['href','src','action']:
url=tag.get(attribute)
if not url or not external(url):continue
context=tag.get_text(' ',strip=True)[:250] or tag.get('alt','') or tag.name+' '+attribute
rec={'sourceFile':file,'phase':phase,'occurrence':i,'element':tag.name,'attribute':attribute,'anchorContext':context,'destination':url,'editorialReviewed':True}
if phase=='raw':
inside=tag.find_parent(class_=lambda c: c and ('entry-content' in c.split()))
if tag.find_parent(id='comments') or tag.find_parent(class_=lambda c:c and ('comment-body' in c.split() or 'comment-content' in c.split())):decision='remove';reason='Комментарий исключён целиком: не авторский материал; здесь встречаются оплаченные/нерелевантные вставки. Текст комментариев не переносится.'
elif not inside:decision='remove';reason='Сторонняя зависимость, шаблон/виджет/трекинг/партнёрская ссылка исторической оболочки. Новая оболочка автономна и не публикует этот ресурс.'
else:
slugHere=slug;d=review.get((slugHere,url))
if d:decision='keep';reason=d['reason']
else:
replacement=next((z for z in ledger['pages'] if z['slug']==slugHere),{})
removed=next((z for z in replacement.get('removedLinks',[]) if z['url']==url),None)
decision='remove-or-update';reason=removed.get('reason') if removed else 'Исходная ссылка не перенесена: редактура оставляет только непосредственно обоснованные первичные ссылки из полного ledger; исходная формулировка вычитана без рекламного/лишнего перехода.'
rec.update(decision=decision,reason=reason)
elif tag.name=='link' and tag.get('rel') and 'canonical' in tag.get('rel'):rec.update(decision='keep',reason='Canonical собственного сайта, не внешняя коммерческая ссылка.')
else:
d=review.get((slug,url)) if slug else None
if d:rec.update(decision='keep',reason=d['reason'])
elif url in resources:rec.update(decision='keep',reason=resources[url])
elif url in allApproved and phase in ['build','source-template','dom']:
# Match the rendered page's actual slug; only shared source attribution on that page qualifies.
candidates=[x for x in allApproved[url] if not slug or x[0]==slug]
if candidates:rec.update(decision='keep',reason=candidates[0][1])
else:rec.update(decision='unreviewed',editorialReviewed=False,reason='Нужна проверка именно этого контекста.');unreviewed.append(rec)
else:rec.update(decision='unreviewed',editorialReviewed=False,reason='Нет индивидуального решения по этому переходу.');unreviewed.append(rec)
records.append(rec)
for match in re.finditer(r'url\([\"\']?(https?://[^)\"\']+)',text):
records.append({'sourceFile':file,'phase':phase,'attribute':'css-url','destination':match.group(1),'anchorContext':text[max(0,match.start()-60):match.end()+60],'decision':'remove' if phase=='raw' else 'unreviewed','reason':'Историческое оформление не публикуется.' if phase=='raw' else 'Неожиданный внешний CSS resource.','editorialReviewed':phase=='raw'})
for article in edited:scan(article['contentHtml'],'web/data/articles-v2.json#'+article['slug'],'edited-body',article['slug'])
meta=json.load(open(doc/'article-source-metadata.json'));rawPaths={}
for slug,x in meta.items():rawPaths[x['raw']]=slug
# Inspect all immutable source captures, including discarded templates and spam-bearing comments.
for base in [r/'provenance',doc/'raw']:
for path in base.glob('*.html'):
slug=rawPaths.get(str(path.relative_to(r)))
if not slug:
name=unquote(path.stem);slug=next((a['slug'] for a in edited if a['slug']==name),None)
scan(path.read_text(errors='replace'),str(path.relative_to(r)),'raw',slug)
for path in (r/'web/app').rglob('*'):
if path.suffix not in ['.jsx','.css']:continue
text=path.read_text();scan(text,str(path.relative_to(r)),'source-template')
# JSX strings used by resource arrays or URL-bearing inline script must also be inventoried.
for url in sorted(set(re.findall(r'https?://[^\s\"\'<>`]+',text))):
if not external(url):continue
if any(x['sourceFile']==str(path.relative_to(r)) and x['destination']==url for x in records):continue
reason=resources.get(url)
records.append({'sourceFile':str(path.relative_to(r)),'phase':'source-template','attribute':'url-literal','destination':url,'anchorContext':text[max(0,text.find(url)-80):text.find(url)+len(url)+80],'decision':'keep' if reason else 'unreviewed','reason':reason or 'Не классифицировано','editorialReviewed':bool(reason)})
for path in (r/'web/out').rglob('*.html'):
rel=unquote(str(path.relative_to(r/'web/out')));slug=next((a['slug'] for a in edited if '/'+a['slug']+'/' in '/'+rel or rel.startswith(a['legacyPath'].strip('/'))),None);scan(path.read_text(),str(path.relative_to(r)),'build',slug)
# Actual browser DOM evidence is supplied by full crawl; compare approved contexts again.
for domfile in sorted((doc/'evidence').glob('candidate-*/dom-links.json')):
if json.load(open(domfile.parent/'manifest.json')).get('sourceHash')!=json.load(open(r/'web/public/build-identity.json'))['sourceHash']:continue
for page in json.load(open(domfile)):
slug=next((a['slug'] for a in edited if a['slug'] in unquote(page['path'])),None)
for i,l in enumerate(page.get('links',[])):
if not external(l['url']):continue
d=review.get((slug,l['url'])) if slug else None;reason=d.get('reason') if d else resources.get(l['url']);rec={'sourcePage':page['path'],'sourceFile':str(domfile.relative_to(r)),'phase':'dom','occurrence':i,'attribute':l.get('attribute'),'anchorContext':l.get('context'),'destination':l['url'],'decision':'keep' if reason else 'unreviewed','reason':reason or 'Нет решения по DOM контексту','editorialReviewed':bool(reason)};records.append(rec)
# Inspect every URL literal in actual bundled JS separately from network-bearing anchors.
parserConstants={'https://a','https://a/c%20d?a=1&c=3','https://a@b','https://тест','https://a#б','https://x','http://n'}
for path in (r/'web/out').rglob('*.js'):
text=path.read_text()
for m in re.finditer(r'https?://[^\s\"\'<>`\\]+',text):
url=m.group(0).rstrip(');,}');reason=None;network=False
if url in resources:reason=resources[url];network=True
elif url in parserConstants:reason='Константа теста/базы URL parser в bundle; не сетевой запрос и не редакционная ссылка.'
elif url.startswith('http://www.w3.org/'):reason='Стандартный XML/SVG/MathML namespace identifier, не загрузка ресурса.'
elif url.startswith('https://nextjs.org/docs/'):reason='Встроенная ссылка Next.js на документацию конкретной диагностики/ошибки; не рекламная вставка и не автоматический запрос.'
elif url=='https://react.dev/errors/':reason='Справочник кодов ошибок React в bundled error builder; не автоматическая внешняя загрузка.'
elif url in ['https://github.com/zloirock/core-js/blob/v3.38.1/LICENSE','https://github.com/zloirock/core-js']:reason='Сохранённые license/homepage metadata bundled core-js, не рекламный виджет.'
records.append({'sourceFile':str(path.relative_to(r)),'phase':'compiled-script','offset':m.start(),'attribute':'URL-literal','anchorContext':text[max(0,m.start()-90):m.end()+90],'destination':url,'decision':'keep-reference' if reason else 'unreviewed','reason':reason or 'Новый URL требует ручной проверки контекста.','editorialReviewed':bool(reason),'networkRelevant':network})
result={'schemaVersion':2,'decisionMethod':'Per article, anchor and purpose; never a domain-wide whitelist. Raw comments/templates excluded as regions and every occurrence recorded.','counts':dict(collections.Counter(x['phase'] for x in records)),'unreviewed':sum(not x['editorialReviewed'] for x in records),'occurrences':records}
(doc/'outbound-links.json').write_text(json.dumps(result,ensure_ascii=False,indent=2)+'\n');print('outbound rows',len(records),'unreviewed',result['unreviewed']);print([(x.get('sourcePage',x['sourceFile']),x['destination']) for x in records if not x['editorialReviewed']][:20])
# Final HTTP inspection queue, one URL per purpose-reviewed destination.
urls=sorted({x['destination'] for x in records if x['phase'] in ['edited-body','source-template','build','dom'] and x['decision']=='keep'})
(doc/'outbound-check-queue.json').write_text(json.dumps(urls,indent=2)+'\n')