Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9109c23794 | ||
|
|
8b3fc21fb1 |
No files matched your search
@@ -0,0 +1,9 @@
|
||||
# CFN 正式教程阅读入口
|
||||
|
||||
教程发布通知由 DevServer 使用 TeleHub 的 `info` 机器人发送到 `base`。发送程序从发布回执取文章路径,例如 `/a/firefox-clash-proxy.html`,拼到 `https://to-cfn.tomtojapan.online`。收件人须使用自有日本节点。
|
||||
|
||||
每条新通知先调用 DevServer 上 root 专用的 `/usr/local/libexec/cfn-article-reader`。探测只接受 CFN 单篇教程路径,经已登记的日本节点 VPS-017 执行一次固定的 HTTPS HEAD。节点认证由 DevServer 私有资源读取器交给本机 OpenSSH,不写入项目配置。只有证书验证通过且最终入口直接返回 200 才调用 TeleHub。节点不可用、文章缺失或返回重定向时保留待发状态;已发送通知按原 UUID 回读。
|
||||
|
||||
安装时将同一 Git 提交中的 `tools/editorial/reader_probe.py` 安装为上述 root:root、0700 的文件,将 `publish_notice.py` 部署到 XFN 的 `tools/editorial/`。在 DevServer 的 root 专用通知配置中将 `article_proxy_origin` 设为上述 HTTPS origin。只运行链接校验即可验证网络,不需要发送测试消息。
|
||||
|
||||
入口登记及访问条件见 [FNA_V3 档案](/Deck/Dev/Gem/AIDocs/10-项目/fna_v3.md)。
|
||||
@@ -24,3 +24,5 @@ ## 内容与发布边界
|
||||
生产固定经本机SSH→白色机VPS-001→正式业务服务器VPS-003。使用[固定发布命令](EDITORIAL_RELEASE.md),公网编辑API保持关闭,不在白色机部署写作服务。普通文章和图片通过内容API,源码/记录另做Git留档;程序/公共资源变更才单独Git部署,保留并行改动,不扩大成全站改版,不重建test。
|
||||
|
||||
用户授权周期内正常选题、写作、相关链接和正式发布,不逐篇再次确认。资料、权限或工具不足时保留草稿并报告真实缺口。只有有意义的完成、失败或需用户操作时通知,成功给标题和真实URL,不发每日检查流水。调度变更必须通过automation_update,不能手改调度文件或加系统cron替代。
|
||||
|
||||
正式教程通知的读者域名、访问条件与发送前的核对流程见[正式教程阅读入口](CFN_READER_PROXY.md)。
|
||||
@@ -0,0 +1,152 @@
|
||||
"""Deliver recorded CFN publication notices through TeleHub."""
|
||||
from datetime import datetime
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import stat
|
||||
import subprocess
|
||||
from uuid import UUID
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from release import atomic_json
|
||||
|
||||
CONFIG = Path('/etc/cfn-editorial-telehub.json')
|
||||
HOST = 'telehub.gemcook.net'
|
||||
ENDPOINT = '/api/v1/messages'
|
||||
STOPPED = {'sent', 'failed', 'uncertain', 'cancelled', 'blocked'}
|
||||
SOURCE_ORIGIN = 'https://clashfreenode.com'
|
||||
ARTICLE_PATH = re.compile(r'/a/[^\s/?#]+\.html')
|
||||
HOST_LABEL = r'[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?'
|
||||
|
||||
|
||||
def stage(directory, response):
|
||||
data = response['data']
|
||||
if data['phase'] != 'complete':
|
||||
return
|
||||
published = datetime.fromisoformat(data['published_at']).astimezone(ZoneInfo('Asia/Shanghai'))
|
||||
if published.date().isoformat() < '2026-11-22':
|
||||
return
|
||||
receipt = data['receipt']
|
||||
publication_id = str(UUID(receipt['publication_id']))
|
||||
new_articles = {item['content_key']: item['title'] for item in data['draft']['articles']
|
||||
if item.get('like_settings') is not None}
|
||||
for item in receipt['articles']:
|
||||
if item['content_key'] not in new_articles or not item['content_changed']:
|
||||
continue
|
||||
article_id = int(item['article_id'])
|
||||
url = item['url']
|
||||
article_path = url.removeprefix(SOURCE_ORIGIN)
|
||||
if not url.startswith(SOURCE_ORIGIN) or not ARTICLE_PATH.fullmatch(article_path):
|
||||
raise ValueError('Invalid canonical CFN article URL')
|
||||
key = f'cfn.editorial.{publication_id}.{article_id}'
|
||||
path = directory / f'{key}.json'
|
||||
if not path.exists():
|
||||
directory.mkdir(mode=0o700, exist_ok=True)
|
||||
atomic_json(path, {'key': key, 'publication_id': publication_id,
|
||||
'title': new_articles[item['content_key']], 'article_path': article_path,
|
||||
'status': 'pending', 'message_id': None})
|
||||
|
||||
|
||||
def proxy_hostname(config):
|
||||
origin = config.get('article_proxy_origin', '')
|
||||
if not isinstance(origin, str):
|
||||
return None
|
||||
host = origin.removeprefix('https://')
|
||||
if (origin != f'https://{host}' or len(host) > 253
|
||||
or not re.fullmatch(rf'(?:{HOST_LABEL}\.)+[a-z]{{2,63}}', host)
|
||||
or host in {'clashfreenode.com', 'www.clashfreenode.com'}):
|
||||
return None
|
||||
return host
|
||||
|
||||
|
||||
def article_reachable(host, article_path):
|
||||
if host == 'to-cfn.tomtojapan.online':
|
||||
try:
|
||||
result = subprocess.run(['/usr/local/libexec/cfn-article-reader', article_path],
|
||||
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL, timeout=18)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return False
|
||||
return result.returncode == 0
|
||||
connection = http.client.HTTPSConnection(host, timeout=8)
|
||||
try:
|
||||
connection.request('HEAD', article_path)
|
||||
return connection.getresponse().status == 200
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def api(key, notice):
|
||||
message_id = notice['message_id']
|
||||
headers = {'Authorization': f'Bearer {key}', 'Accept': 'application/json'}
|
||||
connection = http.client.HTTPSConnection(HOST, timeout=8)
|
||||
try:
|
||||
if message_id:
|
||||
connection.request('GET', f'{ENDPOINT}/{UUID(message_id)}', headers=headers)
|
||||
else:
|
||||
headers.update({'Content-Type': 'application/json', 'Idempotency-Key': notice['key']})
|
||||
connection.request('POST', ENDPOINT, json.dumps(notice['payload'], ensure_ascii=False).encode(), headers)
|
||||
response = connection.getresponse()
|
||||
if response.status in (400, 401, 403, 404, 409, 422):
|
||||
return {'status': 'blocked', 'http_status': response.status}
|
||||
if response.status not in (200, 202):
|
||||
return {'http_status': response.status}
|
||||
result = json.loads(response.read(65537))['data']
|
||||
if result['bot_code'] != 'info' or result['target_code'] != 'base':
|
||||
raise ValueError('Unexpected TeleHub destination')
|
||||
if result['status'] not in STOPPED | {'queued', 'sending'}:
|
||||
raise ValueError('Unexpected TeleHub status')
|
||||
return {'status': result['status'], 'message_id': str(UUID(result['id'])),
|
||||
'http_status': response.status}
|
||||
finally:
|
||||
connection.close()
|
||||
|
||||
|
||||
def deliver(directory, published_ids):
|
||||
outcomes = []
|
||||
for path in sorted(directory.glob('cfn.editorial.*.json')):
|
||||
notice = json.loads(path.read_text())
|
||||
if notice['publication_id'] not in published_ids or notice['status'] in STOPPED:
|
||||
continue
|
||||
try:
|
||||
metadata = CONFIG.stat()
|
||||
if not stat.S_ISREG(metadata.st_mode) or metadata.st_uid != os.geteuid() or metadata.st_mode & 0o077:
|
||||
raise PermissionError()
|
||||
config = json.loads(CONFIG.read_text())
|
||||
key = config['api_key']
|
||||
if not re.fullmatch(r'telehub_[a-f0-9]{64}', key):
|
||||
raise ValueError()
|
||||
except (OSError, ValueError, KeyError, TypeError):
|
||||
outcomes.append({'status': 'pending', 'reason': 'TeleHub credential unavailable'})
|
||||
break
|
||||
try:
|
||||
if not notice['message_id']:
|
||||
article_path = notice.get('article_path', '')
|
||||
if not ARTICLE_PATH.fullmatch(article_path):
|
||||
outcomes.append({'status': 'pending', 'reason': 'Legacy notice requires delivery reconciliation'})
|
||||
continue
|
||||
host = proxy_hostname(config)
|
||||
if not host:
|
||||
outcomes.append({'status': 'pending', 'reason': 'CFN article proxy origin unavailable'})
|
||||
continue
|
||||
text = f"【CFN - 教程发布】\n{notice['title']}\nhttps://{host}{article_path}"
|
||||
payload = {'bot': 'info', 'target': 'base', 'text': text}
|
||||
if 'payload' in notice and notice['payload'] != payload:
|
||||
outcomes.append({'status': 'pending', 'reason': 'Previous delivery attempt needs reconciliation'})
|
||||
continue
|
||||
if not article_reachable(host, article_path):
|
||||
outcomes.append({'status': 'pending', 'reason': 'CFN proxy article check failed'})
|
||||
continue
|
||||
if 'payload' not in notice:
|
||||
# Persist the exact body before POST so a lost response can retry the original request.
|
||||
notice['payload'] = payload
|
||||
atomic_json(path, notice)
|
||||
notice.update(api(key, notice))
|
||||
atomic_json(path, notice)
|
||||
outcomes.append({field: notice[field] for field in ('status', 'message_id', 'http_status')})
|
||||
except (OSError, ValueError, KeyError, TypeError, http.client.HTTPException):
|
||||
outcomes.append({'status': 'pending', 'reason': 'TeleHub response unavailable'})
|
||||
break
|
||||
return outcomes
|
||||
Executable
+59
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/python3 -I
|
||||
"""Check one CFN article from the registered Japan egress. Installed root-only."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from urllib.parse import quote, unquote
|
||||
|
||||
NODE = '185.200.65.70'
|
||||
HOST = 'to-cfn.tomtojapan.online'
|
||||
READER = '/Deck/Dev/Gem/AIDocs/tools/credentials.py'
|
||||
CURL = "/usr/bin/curl -q --noproxy '*' --proto '=https' --head --silent --output /dev/null --connect-timeout 4 --max-time 8 --write-out '%{http_code}' --config -"
|
||||
|
||||
def article_url(path):
|
||||
if len(path) > 1500 or re.search(r'%(?![0-9A-Fa-f]{2})', path):
|
||||
return None
|
||||
try:
|
||||
clean = unquote(path, errors='strict')
|
||||
except UnicodeError:
|
||||
return None
|
||||
if not re.fullmatch(r'/a/[\w.~\-]+\.html', clean):
|
||||
return None
|
||||
return 'https://' + HOST + quote(clean, safe='/~.-_')
|
||||
|
||||
def authenticate(prompt):
|
||||
# OpenSSH's private askpass pipe is the only permitted destination.
|
||||
if (prompt.strip() != "root@" + NODE + "'s password:" or
|
||||
os.readlink('/proc/' + str(os.getppid()) + '/exe') != '/usr/bin/ssh' or
|
||||
os.isatty(1)):
|
||||
return 1
|
||||
os.dup2(1, 3, inheritable=True)
|
||||
os.execv('/usr/bin/python3', ['/usr/bin/python3', '-E', '-s', '-B', READER, 'get',
|
||||
'VPS-017', '--field', 'password', '--output-fd', '3'])
|
||||
|
||||
def check(path):
|
||||
url = article_url(path)
|
||||
if url is None:
|
||||
return 1
|
||||
env = {'PATH':'/usr/bin:/bin', 'HOME':'/root', 'LC_ALL':'C', 'DISPLAY':':0',
|
||||
'SSH_ASKPASS_REQUIRE':'force', 'SSH_ASKPASS':str(Path(__file__).resolve())}
|
||||
cmd = ['/usr/bin/ssh','-F','/dev/null','-T','-o','StrictHostKeyChecking=yes',
|
||||
'-o','UserKnownHostsFile=/root/.ssh/known_hosts','-o','ClearAllForwardings=yes',
|
||||
'-o','IdentityAgent=none','-o','PreferredAuthentications=password',
|
||||
'-o','NumberOfPasswordPrompts=1','-o','ConnectTimeout=5',
|
||||
'-o','LogLevel=ERROR','root@'+NODE,CURL]
|
||||
try:
|
||||
result = subprocess.run(cmd,input='url = '+json.dumps(url)+'\n',text=True,
|
||||
stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,env=env,timeout=16)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return 1
|
||||
return 0 if result.returncode == 0 and result.stdout == '200' else 1
|
||||
|
||||
if __name__ == '__main__':
|
||||
if os.geteuid()!=0 or len(sys.argv)!=2:
|
||||
sys.exit(1)
|
||||
arg=sys.argv[1]
|
||||
sys.exit(check(arg) if arg.startswith('/') else authenticate(arg))
|
||||
@@ -0,0 +1,29 @@
|
||||
import subprocess
|
||||
import unittest
|
||||
from unittest.mock import patch
|
||||
|
||||
import publish_notice
|
||||
import reader_probe
|
||||
|
||||
|
||||
class ReaderTests(unittest.TestCase):
|
||||
def test_article_path_stays_on_one_origin(self):
|
||||
self.assertEqual(reader_probe.article_url('/a/教程.html'),
|
||||
'https://to-cfn.tomtojapan.online/a/%E6%95%99%E7%A8%8B.html')
|
||||
for path in ['/admin', '/a/../../admin.html', '/a/%2Fetc.html',
|
||||
'/a/a%0Ab.html', '/a/a.html?next=b', '/a/x%zz.html']:
|
||||
with self.subTest(path=path):
|
||||
self.assertIsNone(reader_probe.article_url(path))
|
||||
|
||||
def test_japan_check_fails_closed(self):
|
||||
host = 'to-cfn.tomtojapan.online'
|
||||
path = '/a/reader.html'
|
||||
with patch('publish_notice.subprocess.run') as run:
|
||||
run.return_value.returncode = 1
|
||||
self.assertFalse(publish_notice.article_reachable(host, path))
|
||||
self.assertEqual(run.call_args.args[0], ['/usr/local/libexec/cfn-article-reader', path])
|
||||
run.side_effect = subprocess.TimeoutExpired('check', 18)
|
||||
self.assertFalse(publish_notice.article_reachable(host, path))
|
||||
run.side_effect = None
|
||||
run.return_value.returncode = 0
|
||||
self.assertTrue(publish_notice.article_reachable(host, path))
|
||||
Reference in new issue
Block a user